diff --git a/.gitattributes b/.gitattributes index 0ce655e229043f553f0d1ab5b0e79fc07c7932ad..21d0bbfde01ec350adf8126fb8076c83cb9358d4 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1188,3 +1188,4 @@ llava_next/lib/python3.10/site-packages/torch/distributed/__pycache__/distribute vlmpy310/lib/python3.10/site-packages/pyglet/gl/__pycache__/gl_compat.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text vlmpy310/lib/python3.10/site-packages/pyglet/libs/win32/__pycache__/constants.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text llava_next/lib/python3.10/site-packages/torch/lib/libgomp-a34b3233.so.1 filter=lfs diff=lfs merge=lfs -text +vlmpy310/lib/python3.10/site-packages/pyglet/gl/__pycache__/gl.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/llava_next/lib/python3.10/site-packages/torch/__pycache__/_namedtensor_internals.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/__pycache__/_namedtensor_internals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a6ddc339975b9ad4a7374174ebe92cb885781a8 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/__pycache__/_namedtensor_internals.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/__pycache__/functional.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/__pycache__/functional.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e780385f0675bcdb67836d9929cda65e53fccd15 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/__pycache__/functional.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/__pycache__/quasirandom.cpython-310.pyc b/llava_next/lib/python3.10/site-packages/torch/__pycache__/quasirandom.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14e5ba845758f41ec3846080c0ca112333a95fb5 Binary files /dev/null and b/llava_next/lib/python3.10/site-packages/torch/__pycache__/quasirandom.cpython-310.pyc differ diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/__init__.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f4bac6fa13222dc5aace45e3bb6599948139044 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/__init__.py @@ -0,0 +1,112 @@ +from typing import Any, Dict, List, Optional + +import torch.fx + +__all__ = ["compile", "list_mode_options", "list_options", "cudagraph_mark_step_begin"] + + +def compile( + gm: torch.fx.GraphModule, + example_inputs: List[torch.Tensor], + options: Optional[Dict[str, Any]] = None, +): + """ + Compile a given FX graph with TorchInductor. This allows compiling + FX graphs captured without using TorchDynamo. + + Args: + gm: The FX graph to compile. + example_inputs: List of tensor inputs. + options: Optional dict of config options. See `torch._inductor.config`. + + Returns: + Callable with same behavior as gm but faster. + """ + from .compile_fx import compile_fx + + return compile_fx(gm, example_inputs, config_patches=options) + + +def aot_compile( + gm: torch.fx.GraphModule, + example_inputs: List[torch.Tensor], + options: Optional[Dict[str, Any]] = None, +) -> str: + """ + Ahead-of-time compile a given FX graph with TorchInductor into a shared library. + + Args: + gm: The FX graph to compile. + example_inputs: List of tensor inputs. + options: Optional dict of config options. See `torch._inductor.config`. + + Returns: + Path to the generated shared library + """ + from .compile_fx import compile_fx_aot + + result = compile_fx_aot( + gm, + example_inputs, + config_patches=options, + )() + lib_path = result[0] if isinstance(result, (list, tuple)) else result + return lib_path + + +def list_mode_options(mode: str = None, dynamic: bool = None) -> Dict[str, Any]: + r"""Returns a dictionary describing the optimizations that each of the available + modes passed to `torch.compile()` performs. + + Args: + mode (str, optional): The mode to return the optimizations for. + If None, returns optimizations for all modes + dynamic (bool, optional): Whether dynamic shape is enabled. + + Example:: + >>> torch._inductor.list_mode_options() + """ + + mode_options = { + "default": {}, + # enable cudagraphs + "reduce-overhead": { + "triton.cudagraphs": True, + }, + # enable max-autotune + "max-autotune-no-cudagraphs": { + "max_autotune": True, + }, + # enable max-autotune + # enable cudagraphs + "max-autotune": { + "max_autotune": True, + "triton.cudagraphs": True, + }, + } + return mode_options[mode] if mode else mode_options + + +def list_options() -> Dict[str, Any]: + r"""Returns a dictionary describing the optimizations and debug configurations + that are available to `torch.compile()`. + + The options are documented in `torch._inductor.config`. + + Example:: + + >>> torch._inductor.list_options() + """ + + from torch._inductor import config + + current_config: Dict[str, Any] = config.to_dict() # type: ignore[attr-defined] + + return list(current_config.keys()) + + +def cudagraph_mark_step_begin(): + "Indicates that a new iteration of inference or training is about to begin." + from .cudagraph_trees import mark_step_begin + + mark_step_begin() diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/bounds.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/bounds.py new file mode 100644 index 0000000000000000000000000000000000000000..f97e27d097ecee90522f58a4d6cdb02b76c2fae6 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/bounds.py @@ -0,0 +1,101 @@ +import operator +from functools import partial +from typing import Dict, Optional + +import torch +from torch.fx.experimental.symbolic_shapes import free_symbols +from torch.utils._sympy.value_ranges import bound_sympy, ValueRangeAnalysis, ValueRanges +from .ir import InterpreterShim, LoopBody +from .utils import cache_on_self, dominated_nodes +from .virtualized import V + + +class BoundVars: + """ + Performs Value Range Analysis on LoopBody's fx graph by calling BoundVars.run() + It exposes the ranges of the nodes in the `bounds` variable + + Note. A current limitation of this analysis is that it just works on a per-loop basis. + We should be able to propagate the bounds between across the whole graph. This may benefit + the case a bounded variable is returned by a kernel and fed into another. + """ + + def __init__(self, loop_body: LoopBody): + self.loop_body = loop_body + self.replacement_vals = { + k: ValueRanges(0, v - 1) if not free_symbols(v) else bound_sympy(v) + for k, v in loop_body.var_ranges.items() + } + # avoid computing these values, pessimistically assume that they are unbounded + self.unbounded_vars = dominated_nodes( + node + for node in self.loop_body.get_nodes() + if node.target in ["load", "reduction", operator.getitem] + or "masked_subblock" in node.target + ) + # To access this variable call `get_bounds()` + self._bounds: Optional[Dict[torch.fx.Node, ValueRanges]] = {} + + @cache_on_self + def get_bounds(self): + submodules = self.swap_submodules(self.loop_body.submodules) + + # Initialize the environment with the unbounded variables + for node in self.unbounded_vars: + # we need to evaluate masked_subblock to recurse, and we need to set indirect values + if not isinstance(node.target, str) or ( + "masked_subblock" not in node.target + and "set_indirect" not in node.target + ): + self._bounds[node] = ValueRanges.unknown() + + with V.set_ops_handler(ValueRangeAnalysis()): + interpreter = InterpreterShim(self.loop_body.root_block.graph, submodules) + interpreter.run(V.get_ops_handler(), initial_env=self._bounds) + return self._bounds + + def swap_submodules(self, submodules): + result = {} + for key in submodules.keys(): + if key == "get_index": + result[key] = self.get_index + elif "masked_subblock" in key: + subblock = self.loop_body.subblocks[key] + # The result within the lambda will reference to the final + # set of modules at the end of the for-loop as it stores a reference to it + result[key] = lambda mask, value: self.masked_subblock( + subblock, self._bounds, mask, value, result + ) + else: + assert "set_indirect" in key + idx = int(key[len("set_indirect") :]) + var = self.loop_body.indirect_vars[idx] + indirect = partial(self.set_indirect, var) + result[key] = indirect + + return result + + def masked_subblock(self, subblock, env, mask, value, submodules): + interp = InterpreterShim(subblock.graph, submodules) + interp.run(V.get_ops_handler(), initial_env=env) + output = [node for node in subblock.graph.nodes if node.target == "output"] + assert len(output) == 1 + # dont bother unioning with value since the load from buffer will be + # pessimistically assumed to be inf anyway + return interp.env[output[0]] + + def set_indirect(self, old, new): + assert isinstance(new, ValueRanges) + self.replacement_vals[old] = new + return new + + def get_index(self, name): + expr = self.loop_body.indexing_exprs[name] + bound = self.replacement_vals.get(expr) + if bound is None: + bound = bound_sympy(expr, self.replacement_vals) + # The following assertion is true at the time of this writing + # We don't assert is as to not execute bound_sympy when bound is not None + # assert bound is None or bound == bound_sympy(expr, self.replacement_vals) + self.replacement_vals[name] = bound + return bound diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/codecache.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/codecache.py new file mode 100644 index 0000000000000000000000000000000000000000..2fd3e710fdbfc13d0f6bedfde12b1e20983a02bd --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/codecache.py @@ -0,0 +1,1424 @@ +import base64 +import dataclasses +import functools +import getpass +import hashlib +import importlib +import json +import logging +import multiprocessing +import os +import pathlib +import platform +import re +import shlex +import shutil +import signal +import subprocess +import sys +import sysconfig +import tempfile +import threading +import types +import warnings +import weakref +from bisect import bisect_right +from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor +from ctypes import cdll +from dataclasses import field +from functools import partial +from importlib import abc +from pathlib import Path +from threading import Thread +from time import sleep, time +from typing import Any, Callable, Dict, List, Set, Union + +import torch + +from torch._inductor import config, cuda_properties, exc +from torch._inductor.utils import developer_warning +from torch.hub import _Faketqdm, tqdm + +_HERE = os.path.abspath(__file__) +_TORCH_PATH = os.path.dirname(os.path.dirname(_HERE)) + +if config.is_fbcode(): + from triton.fb import build_paths + from triton.fb.build import _run_build_command + + from torch._inductor.fb.utils import ( + log_global_cache_stats, + log_global_cache_vals, + use_global_cache, + ) +else: + + def log_global_cache_stats(*args, **kwargs): + pass + + def log_global_cache_vals(*args, **kwargs): + pass + + def use_global_cache(): + return False + + +LOCK_TIMEOUT = 600 + +# timing metrics for time spent in the compilation +_cumulative_compile_time = 0 +_t0 = None + + +def _compile_start(): + global _t0 + if _t0 is None: + _t0 = time() + + +def _compile_end(): + global _cumulative_compile_time, _t0 + if _t0 is not None: + t1 = time() + _cumulative_compile_time += t1 - _t0 + _t0 = None + # print("CUMULATIVE COMPILE TIME", _cumulative_compile_time) + + +log = logging.getLogger(__name__) + + +@functools.lru_cache(None) +def cache_dir(): + cache_dir = os.environ.get("TORCHINDUCTOR_CACHE_DIR") + if cache_dir is None: + cache_dir = f"{tempfile.gettempdir()}/torchinductor_{getpass.getuser()}" + os.makedirs(cache_dir, exist_ok=True) + return cache_dir + + +def cpp_wrapper_cache_dir(name): + cu_str = ( + "cpu" + if torch.version.cuda is None + else f'cu{torch.version.cuda.replace(".", "")}' + ) + python_version = f"py{sys.version_info.major}{sys.version_info.minor}" + build_folder = f"{python_version}_{cu_str}" + + cpp_wrapper_dir = os.path.join(cache_dir(), build_folder) + cpp_wrapper_build_directory = os.path.join(cpp_wrapper_dir, name) + os.makedirs(cpp_wrapper_build_directory, exist_ok=True) + return cpp_wrapper_build_directory + + +class CacheBase: + @staticmethod + @functools.lru_cache(None) + def get_system(): + try: + import triton + + triton_version = triton.__version__ + except ModuleNotFoundError: + triton_version = None + + system = { + "device": { + "name": torch.cuda.get_device_properties( + torch.cuda.current_device() + ).name, + }, + "version": { + "cuda": torch.version.cuda, + "triton": triton_version, + }, + "other": { + "allow_tf32": torch.backends.cuda.matmul.allow_tf32, + }, + } + + system["hash"] = hashlib.sha256( + json.dumps(system, sort_keys=True).encode("utf-8") + ).hexdigest() + + return system + + @staticmethod + @functools.lru_cache(None) + def get_local_cache_path(): + return Path(os.path.join(cache_dir(), "cache", CacheBase.get_system()["hash"])) + + @staticmethod + @functools.lru_cache(None) + def get_global_cache_path(): + return ( + Path(os.path.join(config.global_cache_dir, CacheBase.get_system()["hash"])) + if config.global_cache_dir is not None + else None + ) + + def __init__(self): + if not torch.cuda.is_available(): + return + + self.system = CacheBase.get_system() + + self.local_cache_path = CacheBase.get_local_cache_path() + self.global_cache_path = CacheBase.get_global_cache_path() + + def get_local_cache(self): + if not self.local_cache_path.is_file(): + return {} + with open(self.local_cache_path) as local_cache_fp: + local_cache = json.load(local_cache_fp) + return local_cache["cache"] + + def update_local_cache(self, local_cache): + if not os.path.exists(self.local_cache_path.parent): + os.makedirs(self.local_cache_path.parent, exist_ok=True) + write_atomic( + self.local_cache_path, + json.dumps({"system": self.system, "cache": local_cache}, indent=4), + ) + + +class LocalCache(CacheBase): + def lookup(self, *keys: List[str]): + cache = self.get_local_cache() + + sub_cache = cache + for key in keys: + if key in cache: + sub_cache = cache[key] + else: + return None + + return sub_cache + + def set_value(self, *keys: List[str], value: Any): + cache = self.get_local_cache() + + sub_cache = cache + for key in keys[0:-1]: + sub_cache.setdefault(key, {}) + sub_cache = sub_cache[key] + sub_cache[keys[-1]] = value + + self.update_local_cache(cache) + + +class PersistentCache(CacheBase): + @functools.lru_cache(None) + def get_global_cache(self): + if self.global_cache_path is None or not self.global_cache_path.is_file(): + return {} + with open(self.global_cache_path) as global_cache_fp: + global_cache = json.load(global_cache_fp) + return global_cache["cache"] + + def lookup( + self, + choices, + name: str, + inputs: str, + benchmark: Callable[[Any], float], + ): + """ + Check to see if we have benchmarked the given choice callers. For each + choice caller: + + 1. Check global_cache[name][inputs][choice], return benchmark if cached. + 2. Check local_cache[name][inputs][choice], return benchmark if cached. + 3. + a. `max_autotune_gemm=True`: benchmark the choice, update + local_cache[name][inputs][choice], and return the benchmark. + b. `max_autotune_gemm=False`: don't benchmark the choice, return nothing. + """ + + log_stats = partial(log_global_cache_stats, self.system, name, inputs) + log_vals = partial(log_global_cache_vals, self.system, name, inputs) + timings = {} + + def check_cache(cache, callback=None): + """Check if `cache` contains data for all the choices""" + hit = True + for choice in choices: + choice_hash = choice.hash_key() + if choice_hash in cache.get(name, {}).get(inputs, {}): + # cache hit + timings[choice] = cache[name][inputs][choice_hash] + else: + # cache miss + hit = False + break + if callback: + callback(cached=hit) + return hit + + if config.max_autotune or config.max_autotune_gemm: + local_cache = self.get_local_cache() + # check local cache first since it is data specific to the current machine + if not check_cache(local_cache) and not ( + use_global_cache() + and check_cache(self.get_global_cache(), callback=log_stats) + ): + # re-benchmark everything to try to get consistent numbers from the same machine + for choice in choices: + timings[choice] = benchmark(choice) + local_cache.setdefault(name, {}) + local_cache[name].setdefault(inputs, {}) + local_cache[name][inputs][choice.hash_key()] = timings[choice] + + self.update_local_cache(local_cache) + + if use_global_cache(): + timings_to_log = { + choice.hash_key(): timings[choice] for choice in choices + } + log_vals(timings_to_log) + elif use_global_cache(): + # only check global cache, not local one + check_cache(self.get_global_cache(), callback=log_stats) + # may have a partial cache hit, where not everything is benchmarked + + return timings + + +def get_lock_dir(): + lock_dir = os.path.join(cache_dir(), "locks") + if not os.path.exists(lock_dir): + os.makedirs(lock_dir, exist_ok=True) + return lock_dir + + +def code_hash(code, extra: str = ""): + hashing_str = code + if extra != "": + hashing_str = hashing_str + "||" + extra + return ( + "c" + + base64.b32encode(hashlib.sha256(hashing_str.encode("utf-8")).digest())[:51] + .decode("utf-8") + .lower() + ) + + +def get_path(basename: str, extension: str, specified_dir: str = ""): + if specified_dir: + if os.path.isabs(specified_dir): + subdir = specified_dir + else: + subdir = os.path.join(cache_dir(), specified_dir) + else: + subdir = os.path.join(cache_dir(), basename[1:3]) + path = os.path.join(subdir, f"{basename}.{extension}") + return basename, subdir, path + + +def get_hash(content: Union[str, bytes], extra: str = "", hash_type: str = "code"): + assert hash_type in ["code", "cubin"], "Hash type not supported" + if hash_type == "code": + return code_hash(content, extra) + if hash_type == "cubin": + return code_hash(repr(content)) + + +def write( + content: Union[str, bytes], + extension: str, + extra: str = "", + hash_type: str = "code", + specified_dir: str = "", +): + key: str = get_hash(content, extra, hash_type) + basename, subdir, path = get_path(key, extension, specified_dir) + if not os.path.exists(subdir): + os.makedirs(subdir, exist_ok=True) + if not os.path.exists(path): + write_atomic(path, content) + return basename, path + + +def write_atomic(path: str, content: Union[str, bytes]): + # Write into temporary file first to avoid conflicts between threads + # Avoid using a named temporary file, as those have restricted permissions + assert isinstance( + content, (str, bytes) + ), "Only strings and byte arrays can be saved in the cache" + path = pathlib.Path(path) + tmp_path = path.parent / f".{os.getpid()}.{threading.get_ident()}.tmp" + write_mode = "w" if isinstance(content, str) else "wb" + with tmp_path.open(write_mode) as f: + f.write(content) + tmp_path.rename(path) + + +@dataclasses.dataclass +class CompiledFxGraph: + """Class holding a compiled FX graph""" + + compiled_artifact: Callable = None + current_callable: Callable = None + cache_key: str = None + artifact_path: str = None + cache_linemap: List = None + device_types: Set[str] = field(default_factory=set) + device_idxs: Set[int] = field(default_factory=set) + mutated_inputs: Set[str] = field(default_factory=set) + mutated_input_idxs: Set[int] = field(default_factory=list) + + _boxed_call: bool = None + + def __call__(self, inputs) -> Any: + return self.get_current_callable()(inputs) + + def get_current_callable(self): + if self.current_callable is None: + # This prevents a circular reference that makes CompiledFxGraph + # get stuck without getting garbage collected + return functools.partial(_run_from_cache, weakref.proxy(self)) + else: + return self.current_callable + + +def _run_from_cache(compiled_graph: CompiledFxGraph, inputs): + # We can't really serialize callables that may be C++/Triton/etc., + # so we serialize their disk cache location instead + # TODO: When making an API that can save compiled models e2e to disk + # this will need to be better + if compiled_graph.compiled_artifact is None: + from .codecache import PyCodeCache + + compiled_graph.compiled_artifact = PyCodeCache.load_by_key_path( + compiled_graph.cache_key, + compiled_graph.artifact_path, + compiled_graph.cache_linemap + if compiled_graph.cache_linemap is not None + else (), + ).call + + return compiled_graph.compiled_artifact(inputs) + + +def cpp_compiler(): + if config.is_fbcode(): + return build_paths.gcc() + if isinstance(config.cpp.cxx, (list, tuple)): + search = tuple(config.cpp.cxx) + else: + search = (config.cpp.cxx,) + return cpp_compiler_search(search) + + +@functools.lru_cache(1) +def cpp_compiler_search(search): + for cxx in search: + try: + if cxx is None: + # gxx package is only available for Linux + # according to https://anaconda.org/conda-forge/gxx/ + if sys.platform != "linux": + continue + # Do not install GXX by default + if not os.getenv("TORCH_INDUCTOR_INSTALL_GXX"): + continue + from filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock( + os.path.join(lock_dir, "g++.lock"), timeout=LOCK_TIMEOUT + ) + with lock: + cxx = install_gcc_via_conda() + subprocess.check_output([cxx, "--version"]) + return cxx + except (subprocess.SubprocessError, FileNotFoundError, ImportError): + continue + raise exc.InvalidCxxCompiler() + + +def install_gcc_via_conda(): + """On older systems, this is a quick way to get a modern compiler""" + prefix = os.path.join(cache_dir(), "gcc") + cxx_path = os.path.join(prefix, "bin", "g++") + if not os.path.exists(cxx_path): + log.info("Downloading GCC via conda") + conda = os.environ.get("CONDA_EXE", "conda") + if conda is None: + conda = shutil.which("conda") + if conda is not None: + subprocess.check_call( + [ + conda, + "create", + f"--prefix={prefix}", + "--channel=conda-forge", + "--quiet", + "-y", + "python=3.8", + "gxx", + ], + stdout=subprocess.PIPE, + ) + return cxx_path + + +def is_gcc(): + return re.search(r"(gcc|g\+\+)", cpp_compiler()) + + +@functools.lru_cache(None) +def is_apple_clang(): + cxx = cpp_compiler() + version_string = subprocess.check_output([cxx, "--version"]).decode("utf8") + return "Apple" in version_string.splitlines()[0] + + +class VecISA: + _bit_width: int + _macro: str + _arch_flags: str + _dtype_nelements: Dict[torch.dtype, int] + + # Note [Checking for Vectorized Support in Inductor] + # TorchInductor CPU vectorization reuses PyTorch vectorization utility functions + # Hence, TorchInductor would depend on Sleef* to accelerate mathematical functions + # like exp, pow, sin, cos and etc. + # But PyTorch and TorchInductor might use different compilers to build code. If + # PyTorch uses gcc-7/g++-7 to build the release package, the libtorch_cpu.so + # will not expose the Sleef* AVX512 symbols since gcc-7/g++-7 cannot pass + # avx512 check in CMake - FindAVX.cmake. But TorchInductor install the latest + # gcc/g++ compiler by default while it could support the AVX512 compilation. + # Therefore, there would be a conflict sleef version between PyTorch and + # TorchInductor. Hence, we dry-compile the following code to check whether current + # HW platform and PyTorch both could support AVX512 or AVX2. And suppose ARM + # also needs the logic + # In fbcode however, we are using the same compiler for pytorch and for inductor codegen, + # making the runtime check unnecessary. + _avx_code = """ +#if defined(CPU_CAPABILITY_AVX512) || defined(CPU_CAPABILITY_AVX2) +#include +#include +#endif + +__attribute__((aligned(64))) float in_out_ptr0[16] = {0.0}; + +extern "C" void __avx_chk_kernel() { + auto tmp0 = at::vec::Vectorized(1); + auto tmp1 = tmp0.exp(); + tmp1.store(in_out_ptr0); +} +""" + + _avx_py_load = """ +import torch +from ctypes import cdll +cdll.LoadLibrary("__lib_path__") +""" + + def bit_width(self): + return self._bit_width + + def nelements(self, dtype: torch.dtype = torch.float): + return self._dtype_nelements[dtype] + + def build_macro(self): + return self._macro + + def build_arch_flags(self): + return self._arch_flags + + def __hash__(self) -> int: + return hash(str(self)) + + @functools.lru_cache(None) + def __bool__(self): + if config.cpp.vec_isa_ok is not None: + return config.cpp.vec_isa_ok + + key, input_path = write(VecISA._avx_code, "cpp") + from filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) + with lock: + output_path = input_path[:-3] + "so" + build_cmd = shlex.split( + cpp_compile_command( + input_path, output_path, warning_all=False, vec_isa=self + ) + ) + try: + # Check build result + compile_file(input_path, output_path, build_cmd) + subprocess.check_call( + [ + sys.executable, + "-c", + VecISA._avx_py_load.replace("__lib_path__", output_path), + ], + stderr=subprocess.DEVNULL, + env={**os.environ, "PYTHONPATH": ":".join(sys.path)}, + ) + except Exception as e: + return False + + return True + + +@dataclasses.dataclass +class VecAVX512(VecISA): + _bit_width = 512 + _macro = "CPU_CAPABILITY_AVX512" + _arch_flags = "-mavx512f -mavx512dq -mavx512vl -mavx512bw -mfma" + _dtype_nelements = {torch.float: 16, torch.bfloat16: 32, torch.float16: 32} + + def __str__(self) -> str: + return "avx512" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ + + +@dataclasses.dataclass +class VecAVX2(VecISA): + _bit_width = 256 + _macro = "CPU_CAPABILITY_AVX2" + _arch_flags = "-mavx2 -mfma" + _dtype_nelements = {torch.float: 8, torch.bfloat16: 16, torch.float16: 16} + + def __str__(self) -> str: + return "avx2" + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ + + +class InvalidVecISA(VecISA): + _bit_width = 0 + _macro = "" + _arch_flags = "" + _dtype_nelements = {} + + def __str__(self) -> str: + return "INVALID_VEC_ISA" + + def __bool__(self): + return False + + __hash__: Callable[[VecISA], Any] = VecISA.__hash__ + + +invalid_vec_isa = InvalidVecISA() +supported_vec_isa_list = [VecAVX512(), VecAVX2()] + + +# Cache the cpuinfo to avoid I/O overhead. Meanwhile, the cpuinfo content +# might have too much redundant content that is useless for ISA check. Hence, +# we only cache some key isa information. +@functools.lru_cache(None) +def valid_vec_isa_list(): + if sys.platform != "linux": + return [] + + isa_list = [] + with open("/proc/cpuinfo") as _cpu_info: + _cpu_info_content = _cpu_info.read() + for isa in supported_vec_isa_list: + if str(isa) in _cpu_info_content and isa: + isa_list.append(isa) + return isa_list + + +def pick_vec_isa(): + _valid_vec_isa_list: List[VecISA] = valid_vec_isa_list() + if not _valid_vec_isa_list: + return invalid_vec_isa + + # If the simdlen is None, it indicates determin the vectorization length automatically + if config.cpp.simdlen is None: + assert _valid_vec_isa_list + return _valid_vec_isa_list[0] + + for isa in _valid_vec_isa_list: + if config.cpp.simdlen == isa.bit_width(): + return isa + + return invalid_vec_isa + + +def get_shared(shared=True): + return "-shared -fPIC" if shared else "" + + +def get_warning_all_flag(warning_all=True): + return "-Wall" if warning_all else "" + + +def cpp_flags(): + return "-std=c++17 -Wno-unused-variable" + + +def cpp_wrapper_flags(): + return "-DTORCH_INDUCTOR_CPP_WRAPPER" + + +def optimization_flags(): + base_flags = "-O3 -ffast-math -fno-finite-math-only" + if config.is_fbcode(): + # FIXME: passing `-fopenmp` adds libgomp.so to the generated shared library's dependencies. + # This causes `ldopen` to fail in fbcode, because libgomp does not exist in the default paths. + # We will fix it later by exposing the lib path. + return base_flags + + if sys.platform == "darwin": + # Per https://mac.r-project.org/openmp/ right way to pass `openmp` flags to MacOS is via `-Xclang` + # Also, `-march=native` is unrecognized option on M1 + base_flags += " -Xclang" + else: + if platform.machine() == "ppc64le": + base_flags += " -mcpu=native" + else: + base_flags += " -march=native" + + # Internal cannot find libgomp.so + if not config.is_fbcode(): + base_flags += " -fopenmp" + return base_flags + + +def use_custom_generated_macros(): + return "-D C10_USING_CUSTOM_GENERATED_MACROS" + + +def use_fb_internal_macros(): + if config.is_fbcode(): + openmp_lib = build_paths.openmp_lib() + return f"-Wp,-fopenmp {openmp_lib} -D C10_USE_GLOG -D C10_USE_MINIMAL_GLOG" + else: + return "" + + +def use_standard_sys_dir_headers(): + if config.is_fbcode(): + return "-nostdinc" + else: + return "" + + +@functools.lru_cache(None) +def is_conda_llvm_openmp_installed(): + try: + command = "conda list llvm-openmp --json" + output = subprocess.check_output(command.split()).decode("utf8") + return len(json.loads(output)) > 0 + except subprocess.SubprocessError: + return False + + +@functools.lru_cache(None) +def homebrew_libomp(): + try: + # check if `brew` is installed + subprocess.check_output(["which", "brew"]) + # get the location of `libomp` if it is installed + # this is the location that `libomp` **would** be installed + # see https://github.com/Homebrew/brew/issues/10261#issuecomment-756563567 for details + libomp_path = ( + subprocess.check_output(["brew", "--prefix", "libomp"]) + .decode("utf8") + .strip() + ) + # check if `libomp` is installed + omp_available = os.path.exists(libomp_path) + return omp_available, libomp_path + except subprocess.SubprocessError: + return False, "" + + +def get_include_and_linking_paths( + include_pytorch=False, vec_isa: VecISA = invalid_vec_isa, cuda=False, aot_mode=False +): + if ( + config.is_fbcode() + and "CUDA_HOME" not in os.environ + and "CUDA_PATH" not in os.environ + ): + os.environ["CUDA_HOME"] = os.path.dirname(build_paths.cuda()) + from torch.utils import cpp_extension + + if aot_mode and config.is_fbcode(): + # Hack. The AOT inductor libs reference CUDA, so let's just include it for now. + cuda = True + + macros = "" + if sys.platform == "linux" and ( + include_pytorch + or vec_isa != invalid_vec_isa + or cuda + or config.cpp.enable_kernel_profile + ): + # Note - We include pytorch only on linux right now. There is more work + # to do to enable OMP build on darwin where PyTorch is built with IOMP + # and we need a way to link to what PyTorch links. + ipaths = cpp_extension.include_paths(cuda) + [sysconfig.get_path("include")] + lpaths = cpp_extension.library_paths(cuda) + [ + sysconfig.get_config_var("LIBDIR") + ] + libs = [] + # No need to manually specify libraries in fbcode. + if not config.is_fbcode(): + libs += ["c10", "torch", "torch_cpu"] + libs += ["gomp"] + if not aot_mode: + libs += ["torch_python"] + else: + # internal remote execution is able to find omp, but not gomp + libs += ["omp"] + if aot_mode: + ipaths += [os.path.dirname(cpp_prefix_path())] + macros = vec_isa.build_macro() + if macros: + if config.is_fbcode() and vec_isa != invalid_vec_isa: + cap = str(vec_isa).upper() + macros = " ".join( + [ + vec_isa.build_arch_flags(), + f"-D CPU_CAPABILITY={cap}", + f"-D CPU_CAPABILITY_{cap}", + f"-D HAVE_{cap}_CPU_DEFINITION", + ] + ) + else: + macros = f"-D{macros}" + if cuda: + if config.is_fbcode(): + libs += ["cuda"] + else: + libs += ["c10_cuda", "cuda", "torch_cuda"] + else: + # Note - this is effectively a header only inclusion. Usage of some header files may result in + # symbol not found, if those header files require a library. + # For those cases, include the lpath and libs command as we do for pytorch above. + # This approach allows us to only pay for what we use. + ipaths = cpp_extension.include_paths(cuda) + [sysconfig.get_path("include")] + lpaths = [] + if sys.platform == "darwin": + # only Apple builtin compilers (Apple Clang++) require openmp + omp_available = not is_apple_clang() + + # check the `OMP_PREFIX` environment first + if os.getenv("OMP_PREFIX") is not None: + header_path = os.path.join(os.getenv("OMP_PREFIX"), "include", "omp.h") + valid_env = os.path.exists(header_path) + if valid_env: + ipaths.append(os.path.join(os.getenv("OMP_PREFIX"), "include")) + lpaths.append(os.path.join(os.getenv("OMP_PREFIX"), "lib")) + else: + warnings.warn("environment variable `OMP_PREFIX` is invalid.") + omp_available = omp_available or valid_env + + libs = [] if omp_available else ["omp"] + + # prefer to use openmp from `conda install llvm-openmp` + if not omp_available and os.getenv("CONDA_PREFIX") is not None: + omp_available = is_conda_llvm_openmp_installed() + if omp_available: + conda_lib_path = os.path.join(os.getenv("CONDA_PREFIX"), "lib") + ipaths.append(os.path.join(os.getenv("CONDA_PREFIX"), "include")) + lpaths.append(conda_lib_path) + # Prefer Intel OpenMP on x86 machine + if os.uname().machine == "x86_64" and os.path.exists( + os.path.join(conda_lib_path, "libiomp5.dylib") + ): + libs = ["iomp5"] + + # next, try to use openmp from `brew install libomp` + if not omp_available: + omp_available, libomp_path = homebrew_libomp() + if omp_available: + ipaths.append(os.path.join(libomp_path, "include")) + lpaths.append(os.path.join(libomp_path, "lib")) + + # if openmp is still not available, we let the compiler to have a try, + # and raise error together with instructions at compilation error later + else: + libs = ["omp"] if config.is_fbcode() else ["gomp"] + + # third party libs + if config.is_fbcode(): + ipaths.append(build_paths.sleef()) + ipaths.append(build_paths.openmp()) + ipaths.append(build_paths.gcc_include()) + ipaths.append(build_paths.libgcc()) + ipaths.append(build_paths.libgcc_arch()) + ipaths.append(build_paths.libgcc_backward()) + ipaths.append(build_paths.glibc()) + ipaths.append(build_paths.linux_kernel()) + ipaths.append(build_paths.gcc_install_tools_include()) + # We also need to bundle includes with absolute paths into a remote directory + # (later on, we copy the include paths from cpp_extensions into our remote dir) + ipaths.append("include") + + ipaths = " ".join(["-I" + p for p in ipaths]) + lpaths = " ".join(["-L" + p for p in lpaths]) + libs = " ".join(["-l" + p for p in libs]) + return ipaths, lpaths, libs, macros + + +def cpp_compile_command( + input, + output, + warning_all=True, + shared=True, + include_pytorch=False, + vec_isa: VecISA = invalid_vec_isa, + cuda=False, + aot_mode=False, +): + ipaths, lpaths, libs, macros = get_include_and_linking_paths( + include_pytorch, vec_isa, cuda, aot_mode + ) + if config.is_fbcode(): + if aot_mode: + inp_name = input + out_name = output + else: + # We need to copy any absolute-path torch includes + inp_name = os.path.basename(input) + out_name = os.path.basename(output) + linker_paths = [os.path.dirname(build_paths.ld()), build_paths.glibc_lib()] + linker_paths = " ".join(["-B" + p for p in linker_paths]) + else: + inp_name = input + out_name = output + linker_paths = "" # let the compiler pick + return re.sub( + r"[ \n]+", + " ", + f""" + {cpp_compiler()} {inp_name} {get_shared(shared)} + {get_warning_all_flag(warning_all)} {cpp_flags()} + {ipaths} {lpaths} {libs} {macros} {linker_paths} + {optimization_flags()} + {use_custom_generated_macros()} + {use_fb_internal_macros()} + {use_standard_sys_dir_headers()} + -o {out_name} + """, + ).strip() + + +class CudaKernelParamCache: + cache = dict() + clear = staticmethod(cache.clear) + + @classmethod + def set(cls, key, params, cubin): + _, path = write( + cubin, + "cubin", + hash_type="cubin", + specified_dir=config.aot_inductor_output_path, + ) + params["cubin_path"] = path + cls.cache[key] = params + + @classmethod + def get(cls, key): + return cls.cache.get(key, None) + + +class AotCodeCache: + cache = dict() + clear = staticmethod(cache.clear) + + @classmethod + def compile(cls, graph, source_code, cuda): + # TODO: update cpp_compile_command for different platforms + picked_vec_isa = invalid_vec_isa if cuda else pick_vec_isa() + cpp_command = repr( + cpp_compile_command( + "i", "o", vec_isa=picked_vec_isa, cuda=cuda, aot_mode=graph.aot_mode + ) + ) + key, input_path = write( + source_code, + "cpp", + extra=cpp_command, + specified_dir=config.aot_inductor_output_path, + ) + if key not in cls.cache: + from filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) + with lock: + output_so = os.path.splitext(input_path)[0] + ".so" + + if not os.path.exists(output_so): + cmd = shlex.split( + cpp_compile_command( + input=input_path, + output=output_so, + vec_isa=picked_vec_isa, + cuda=cuda, + aot_mode=graph.aot_mode, + ) + ) + log.debug("aot compilation command: %s", " ".join(cmd)) + try: + subprocess.check_call(cmd) + except subprocess.CalledProcessError as e: + raise exc.CppCompileError(cmd, e.output) from e + else: + log.debug( + "aot_inductor dynamic library already exist: %s", output_so + ) + + cls.cache[key] = output_so + + def wrapper_call(*args): + assert len(graph.graph_outputs) > 0 + return cls.cache[key], *(None for i in range(len(graph.graph_outputs) - 1)) + + return wrapper_call + + +# Putting this fn in cpp.py (unfortunately) causes a deadlock, which is why it's in codecache.py. +# Why? importing from cpp.py invokes codecache.pick_vec_isa(), which takes out a lock. +# Cycle goes: +# - CppCodeCache.load() +# - pick_vec_isa() +# - valid_vec_isa_list() +# - VecISA.__bool__() <-- takes out a lock +# - compile_file() <-- imports cpp_prefix_path from cpp, which causes us to try to take out the same lock. +@functools.lru_cache +def cpp_prefix_path(): + path = Path(__file__).parent / "codegen/cpp_prefix.h" + with path.open() as f: + content = f.read() + _, filename = write( + content, + "h", + ) + return filename + + +def cpp_prefix(): + filename = cpp_prefix_path() + if config.is_fbcode(): + # We need relative paths, since we bundle up + # everything that we compile into a folder for remote compilation. + return f'#include "{os.path.basename(filename)}"' + else: + return f'#include "{filename}"' + + +# Given a path to an input cpp file and an output path, +# Attempts to compile the file, storing the output in "output_path" +def compile_file(input_path, output_path, cmd) -> None: + input_file = os.path.basename(input_path) if config.is_fbcode() else input_path + try: + if config.is_fbcode(): + # Need to copy our header into the same folder as the sourcecode. + header_path = cpp_prefix_path() + header_name = os.path.basename(header_path) + output_name = os.path.basename(output_path) + # When we build remotely, we need to make sure to carefully copy any files + # that are required during the compilation process into our build directly. + # This is where all of the ATen/c10/Torch includes come from. + torch_includes_path = os.path.join( + torch.utils.cpp_extension._TORCH_PATH, "include" + ) + with tempfile.TemporaryDirectory() as tmp_dir: + # Copy everything to tmp compilation folder + shutil.copy(header_path, os.path.join(tmp_dir, header_name)) + shutil.copy(input_path, os.path.join(tmp_dir, input_file)) + dest_include_path = os.path.join(tmp_dir, "include") + shutil.copytree(torch_includes_path, dest_include_path) + # Run the build + output_file_path = _run_build_command(cmd, tmp_dir, output_name) + # Copy output from the build + if os.path.exists(output_path): + os.remove(output_path) + shutil.copy(output_file_path, output_path) + else: + subprocess.check_output(cmd, stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as e: + output = e.output.decode("utf-8") + openmp_problem = "'omp.h' file not found" in output or "libomp" in output + if openmp_problem and sys.platform == "darwin": + instruction = ( + "\n\nOpenMP support not found. Please try one of the following solutions:\n" + "(1) Set the `CXX` environment variable to a compiler other than Apple clang++/g++ " + "that has builtin OpenMP support;\n" + "(2) install OpenMP via conda: `conda install llvm-openmp`;\n" + "(3) install libomp via brew: `brew install libomp`;\n" + "(4) manually setup OpenMP and set the `OMP_PREFIX` environment variable to point to a path" + " with `include/omp.h` under it." + ) + output += instruction + raise exc.CppCompileError(cmd, output) from e + + +class CppCodeCache: + cache = dict() + clear = staticmethod(cache.clear) + + @staticmethod + def _load_library(path): + try: + return cdll.LoadLibrary(path) + except OSError as e: + if "gomp" in str(e) and os.path.exists("/usr/lib64/libgomp.so.1"): + # hacky workaround for fbcode/buck + global _libgomp + _libgomp = cdll.LoadLibrary("/usr/lib64/libgomp.so.1") + return cdll.LoadLibrary(path) + if "failed to map segment from shared object" in str(e): + raise OSError( + f"{e}. The most common reason this may occur is if the {tempfile.gettempdir()} folder " + "is mounted with noexec (e.g., by default Docker mounts tmp file systems " + f"as noexec). Please remount {tempfile.gettempdir()} with exec enabled, or set another " + "temporary directory with TORCHINDUCTOR_CACHE_DIR environment variable." + ) from e + raise + + @classmethod + def load(cls, source_code): + picked_vec_isa = pick_vec_isa() + cpp_command = repr(cpp_compile_command("i", "o", vec_isa=picked_vec_isa)) + key, input_path = write(source_code, "cpp", extra=cpp_command) + if key not in cls.cache: + from filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) + with lock: + output_path = input_path[:-3] + "so" + if not os.path.exists(output_path): + cmd = shlex.split( + cpp_compile_command( + input=input_path, output=output_path, vec_isa=picked_vec_isa + ) + ) + compile_file(input_path, output_path, cmd) + cls.cache[key] = cls._load_library(output_path) + cls.cache[key].key = key + + return cls.cache[key] + + +class PyCodeCache: + cache: Dict[Any, types.ModuleType] = dict() + linemaps = dict() + clear = staticmethod(cache.clear) + + @classmethod + def write(cls, source_code, extra=""): + return write(source_code, "py", extra=extra) + + @classmethod + def load(cls, source_code, extra="", linemap=()): + key, path = write(source_code, "py", extra=extra) + return cls.load_by_key_path(key, path, linemap) + + @classmethod + def load_by_key_path(cls, key, path, linemap=()): + if key not in cls.cache: + with open(path) as f: + try: + code = compile(f.read(), path, "exec") + except Exception as e: + raise RuntimeError( + f"Failed to import {path}\n{type(e).__name__}: {e}" + ) + mod = types.ModuleType(f"{__name__}.{key}") + mod.__file__ = path + mod.key = key + exec(code, mod.__dict__, mod.__dict__) + sys.modules[mod.__name__] = mod + # another thread might set this first + cls.cache.setdefault(key, mod) + # unzip into separate lines/nodes lists + cls.linemaps[path] = list(zip(*linemap)) + + return cls.cache[key] + + @classmethod + @functools.lru_cache(None) + def stack_frames_for_code(cls, path, lineno): + if path not in cls.linemaps: + return None + # [(starting_line, ), ...] + lines, nodes = cls.linemaps[path] + p = bisect_right(lines, lineno) + if p == 0: + return None + entry = nodes[p - 1] + if not entry: + return None + + def parse_stack_trace(stack_trace): + # ideally fx stores stack traces as data rather than a string + # but this is not along a performance critical path + regex = r'File "(.+)", line (\d+), in (.+)\n' + matches = re.findall(regex, stack_trace) + return [ + {"filename": f, "line": int(l), "name": n} + for f, l, n in reversed(matches) + ] + + return parse_stack_trace(entry) + + +class CppWrapperCodeCache: + cache = dict() + clear = staticmethod(cache.clear) + + @classmethod + def load(cls, source_code, func_name, key, cuda): + name = f"inline_extension_{key}" + cpp_wrapper_dir = cpp_wrapper_cache_dir(name) + if not os.path.exists(cpp_wrapper_dir): + os.makedirs(cpp_wrapper_dir) + + ext = "so" + filepath = os.path.join(cpp_wrapper_dir, f"{name}.{ext}") + log.debug("Cpp wrapper code path %s", filepath) + + if key not in cls.cache: + log.debug("Cpp wrapper cache miss for %s", filepath) + from filelock import FileLock + + lock_dir = get_lock_dir() + lock = FileLock(os.path.join(lock_dir, key + ".lock"), timeout=LOCK_TIMEOUT) + with lock: + if not os.path.exists(filepath): + log.debug("Cpp wrapper building %s", filepath) + + _cpp_flags = cpp_flags() + _opt_flags = optimization_flags() + _shared = get_shared() + _warning_all_flag = get_warning_all_flag() + _ipaths, _lpaths, _libs, _macros = get_include_and_linking_paths( + vec_isa=pick_vec_isa(), + cuda=cuda, + ) + _use_custom_generated_macros = use_custom_generated_macros() + _cpp_wrapper_flags = cpp_wrapper_flags() + + extra_cflags = f"{_cpp_flags} {_opt_flags} {_warning_all_flag} {_macros} {_cpp_wrapper_flags} \ + {_use_custom_generated_macros}" + # For CPP wrapper, add -ffast-math during linking to make CPU flush denormals. + # CPP wrapper leverages cpp_extension which will do the compilation and linking in two stages. + # We need to explicitly add -ffast-math as a linking flag. + # For the default python wrapper, the compilation and linking are done in one command thus -ffast-math + # will take effect in both compilation and linking. + extra_ldflags = f"{_shared} {_lpaths} {_libs} -ffast-math" + extra_include_paths = f"{_ipaths}" + + mod = torch.utils.cpp_extension.load_inline( + name=name, + build_directory=cpp_wrapper_dir, + cpp_sources=[source_code], + functions=[func_name], + extra_cflags=[extra_cflags], + extra_ldflags=[extra_ldflags], + extra_include_paths=[extra_include_paths], + use_pch=True, + ) + log.debug("Cpp wrapper done building %s", filepath) + else: + log.debug("Found target .so, cpp wrapper loading %s", filepath) + spec = importlib.util.spec_from_file_location(name, filepath) + assert spec is not None + mod = importlib.util.module_from_spec(spec) + assert isinstance(spec.loader, abc.Loader) + spec.loader.exec_module(mod) + log.debug("Cpp wrapper done loading %s", filepath) + + cls.cache[key] = mod + + return cls.cache[key] + + +class TritonCodeCache: + @classmethod + def load(cls, kernel_name, source_code): + mod = PyCodeCache.load(source_code) + return getattr(mod, kernel_name) + + +def _worker_compile(kernel_name, source_code, cc, device): + cuda_properties.set_compiler_worker_current_device(device) + kernel = TritonCodeCache.load(kernel_name, source_code) + kernel.precompile(warm_cache_only_with_cc=cc) + + +def _load_kernel(kernel_name, source_code): + kernel = TritonCodeCache.load(kernel_name, source_code) + kernel.precompile() + return kernel + + +class TritonFuture: + def __init__(self, kernel_name, source_code, future): + self.kernel_name = kernel_name + self.source_code = source_code + self.future = future + + # @dynamo_utils.dynamo_timed + def result(self): + t0 = time() + if hasattr(self, "kernel"): + return self.kernel + # If the worker failed this will throw an exception. + self.future.result() + kernel = self.kernel = _load_kernel(self.kernel_name, self.source_code) + latency = time() - t0 + if latency > 50: + developer_warning( + f"Detected long compilation time of {latency} seconds for kernel name {self.kernel_name}" + ) + developer_warning(self.source_code) + del self.kernel_name, self.source_code, self.future + return kernel + + +class AsyncCompile: + def __init__(self): + pass + + @staticmethod + @functools.lru_cache(1) + def pool(): + assert config.compile_threads > 1 + return ThreadPoolExecutor(config.compile_threads) + + @staticmethod + @functools.lru_cache(1) + def process_pool(): + # ensure properties have been calculated before processes + # are forked + cuda_properties._properties() + assert config.compile_threads > 1 + orig_ppid = os.getpid() + + # if this process dies abnormally (e.g. segfault) + # it will not shut down the workers. Instead + # the workers will have their parent reassigned to the + # init process. This launches a separate thread to + # watch for the worker getting reassigned, + # and cleans it up in this case. + def init(): + def run(): + while True: + sleep(1) + if orig_ppid != os.getppid(): + os.kill(os.getpid(), signal.SIGKILL) + + global _watchdog_thread + _watchdog_thread = Thread(target=run, daemon=True) + _watchdog_thread.start() + + # we rely on 'fork' because we cannot control whether users + # have an `if __name__ == '__main__'` in their main process. + fork_context = multiprocessing.get_context("fork") + pool = ProcessPoolExecutor( + config.compile_threads, mp_context=fork_context, initializer=init + ) + # when this pool is created in a subprocess object, the normal exit handler + # doesn't run, and we need to register our own handler. + # exitpriority has to be high, because another one of the finalizers will + # kill the worker thread that sends the shutdown message to the workers... + multiprocessing.util.Finalize(None, pool.shutdown, exitpriority=sys.maxsize) + return pool + + @classmethod + def warm_pool(cls): + if config.compile_threads <= 1: + return + _compile_start() + pool = cls.process_pool() + + # We have to fork processes for compiler workers, but the more memory and other resources that are loaded, the + # slower the os.fork time is, quite drastically. It also holds the GIL so we can't put it on another thread. + + # Examples: + # A simple x + x + x script: 10ms seconds in the middle of the program, 2ms at startup + # tf_efficientnet_b0 benchmark: 50ms! in the middle of the program , 3ms at startup + + # So we want to start the workers early when it is still cheap, and also to allow the workers to get + # ready before we have work for them. + + # ProcessPoolExecutor also does not launch the workers until it finds a point when all the workers are idle. + # But if we waited until then fork time will be long and we will be waiting for the processes to initialize. + + # We force them to start here with some YOLOing of the internal methods. + if hasattr(pool, "_start_queue_management_thread"): + pool._start_queue_management_thread() + else: + for _ in range(config.compile_threads): + pool._adjust_process_count() + pool._start_executor_manager_thread() + _compile_end() + + @classmethod + def submit(cls, task): + if config.compile_threads <= 1: + return task() + return cls.pool().submit(task) + + @classmethod + def map(cls, fn, seq): + if config.compile_threads <= 1 or len(seq) <= 1: + return list(map(fn, seq)) + return [t.result() for t in [cls.pool().submit(fn, x) for x in seq]] + + def triton(self, kernel_name, source_code): + _compile_start() + + if config.compile_threads > 1: + major, minor = torch.cuda.get_device_capability() + device = torch.cuda.current_device() + cc = major * 10 + minor + future = self.process_pool().submit( + _worker_compile, kernel_name, source_code, cc, device + ) + return TritonFuture(kernel_name, source_code, future) + else: + return _load_kernel(kernel_name, source_code) + + def cpp(self, source_code): + def task(): + return CppCodeCache.load(source_code).kernel + + return self.submit(task) + + def wait(self, scope: Dict[str, Any]): + num_kernels = len( + [ + value + for key, value in scope.items() + if isinstance(value, (Future, TritonFuture)) + ] + ) + pbar = tqdm( + total=num_kernels, + desc="Inductor Compilation", + disable=config.disable_progress, + delay=0, + ) + if config.compile_threads > 1: + for key, result in scope.items(): + if config.verbose_progress and not isinstance(pbar, _Faketqdm): + pbar.set_postfix_str(key) + if isinstance(result, (Future, TritonFuture)): + scope[key] = result.result() + pbar.update(1) + + _compile_end() + + +AsyncCompile.warm_pool() diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/compile_fx.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/compile_fx.py new file mode 100644 index 0000000000000000000000000000000000000000..01188b490555cbee6f23970e7dba8707319c5567 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/compile_fx.py @@ -0,0 +1,1284 @@ +import contextlib +import dataclasses +import functools +import itertools +import logging +import sys +import warnings + +from functools import wraps +from typing import Any, Callable, Dict, FrozenSet, List, Optional, Sequence, Union +from unittest import mock + +from functorch.compile import min_cut_rematerialization_partition + +import torch._functorch.config as functorch_config + +import torch.fx +import torch.utils._pytree as pytree +from torch._dynamo import ( + compiled_autograd, + logging as dynamo_logging, + utils as dynamo_utils, +) +from torch._dynamo.utils import detect_fake_mode +from torch._functorch.aot_autograd import make_boxed_func +from torch._inductor.codecache import code_hash, CompiledFxGraph + +from torch._inductor.debug import save_args_for_compile_fx_inner +from torch._ops import OpOverload +from torch._subclasses.fake_tensor import FakeTensor +from torch.fx.passes.fake_tensor_prop import FakeTensorProp + +from .._dynamo.backends.common import aot_autograd +from ..fx.graph import _PyTreeCodeGen +from . import config, metrics +from .debug import DebugContext +from .decomposition import select_decomp_table +from .fx_passes.joint_graph import joint_graph_passes +from .fx_passes.post_grad import post_grad_passes, view_to_reshape +from .fx_passes.pre_grad import pre_grad_passes +from .graph import GraphLowering +from .pattern_matcher import clone_graph +from .utils import get_dtype_size, has_incompatible_cudagraph_ops +from .virtualized import V + +if config.is_fbcode(): + from torch._inductor.fb.utils import time_and_log # type: ignore[import] +else: + # no-op decorator + def time_and_log(attr: str): + def wrap(old_func): + @wraps(old_func) + def newFunction(*args, **kwargs): + return old_func(*args, **kwargs) + + return newFunction + + return wrap + + +log = logging.getLogger(__name__) +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") +ALIGNMENT = 16 + + +@dataclasses.dataclass +class BoxedBool: + value: bool + + def __bool__(self): + return self.value + + @staticmethod + def disable(obj): + if isinstance(obj, BoxedBool): + obj.value = False + return obj + return False + + +@dataclasses.dataclass +class BoxedDeviceIndex: + value: Optional[int] + + def set(self, device_idx): + assert device_idx is None or isinstance(device_idx, int) + self.value = device_idx + + +# copy_ fails when trying to write to tensors with memory overlap, +# for expanded dimensions (a dimension which used to have size 1 -> ?) +# we can select one element from that dimension and write to it +# to achieve writing to all values of that dimension of the input tensor +def get_expanded_dims(t): + if not isinstance(t, torch.Tensor): + return None + return [i for i in range(t.ndim) if t.stride(i) == 0 and t.size(i) != 1] + + +def index_expanded_dims(t: torch.Tensor, expanded_dims: List[int]) -> torch.Tensor: + for expanded_dim in expanded_dims: + t = torch.ops.aten.slice(t, expanded_dim, 0, 1) + return t + + +def complex_memory_overlap(t: torch.Tensor) -> bool: + # if torch._debug_has_internal_overlap thinks this tensor potentially has + # memory overlap internally, let's dig deeper to find out whether it's true. + t = index_expanded_dims(t, get_expanded_dims(t)) + if torch._debug_has_internal_overlap(t) != 0: + strides = t.stride() + sizes = t.shape + indices = list(range(len(strides))) + indices = [x for _, x in sorted(zip(strides, indices))] + for i in range(len(strides)): + prev_stride = 1 if i == 0 else strides[indices[i - 1]] + prev_size = 1 if i == 0 else sizes[indices[i - 1]] + if strides[indices[i]] < prev_stride * prev_size: + return True + return False + + +@functools.lru_cache(None) +def _step_logger(): + return dynamo_logging.get_step_logger(log) + + +@functools.lru_cache(None) +def _warn_tf32_disabled(): + if ( + torch.cuda.is_available() + and not torch.backends.cuda.matmul.allow_tf32 + and torch.cuda.get_device_capability() >= (8, 0) + ): + warnings.warn( + "TensorFloat32 tensor cores for float32 matrix multiplication available but not enabled. " + "Consider setting `torch.set_float32_matmul_precision('high')` for better performance." + ) + + +def is_tf32_warning_applicable(gm: torch.fx.GraphModule): + aten = torch.ops.aten + tf32_ops = { + aten.mm.default, + aten.addmm.default, + aten.bmm.default, + aten.baddbmm.default, + } + for node in gm.graph.nodes: + if ( + node.op == "call_function" + and node.target in tf32_ops + and isinstance(node.meta.get("val", None), torch.Tensor) + and node.meta["val"].dtype == torch.float32 + and node.meta["val"].device.type == "cuda" + ): + return True + return False + + +@DebugContext.wrap +def count_bytes_inner( + gm: torch.fx.GraphModule, + example_inputs: List[torch.Tensor], + num_fixed: int = 0, + **kwargs, +): + shape_env = _shape_env_from_inputs(example_inputs) + + graph = GraphLowering(gm, shape_env=shape_env, num_static_inputs=num_fixed) + with V.set_graph_handler(graph), V.set_real_inputs(example_inputs): # type: ignore[call-arg] + graph.run(*example_inputs) + num_bytes, nodes_num_elem, node_runtimes = graph.count_bytes() + metrics.num_bytes_accessed += num_bytes + metrics.nodes_num_elem += nodes_num_elem + metrics.node_runtimes += node_runtimes + return make_boxed_func(gm.forward) + + +def inner_compile_with_cpp_wrapper(inner_compile: Callable[..., Any]): + @functools.wraps(inner_compile) + def wrapper(gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor], **kwargs): + """ + Compile into cpp wrapper: + For CPU, this is currently done in one pass. + For GPU, this is done in two passes: JIT-compile the model with python wrapper code + and run it to generate autotuned kernel binaries in the first pass; and then generate + cpp wrapper code and compile it to a dynamic library in the second pass. + """ + devices = ( + {t.device.type for t in gm.parameters()} + | {t.device.type for t in gm.buffers()} + | {t.device.type for t in example_inputs if isinstance(t, torch.Tensor)} + ) + + if "cuda" not in devices: + kwargs_patched = {**kwargs, "cpp_wrapper": True} + return inner_compile(gm, example_inputs, **kwargs_patched) + else: + with config.patch( # type: ignore[attr-defined] + { + "triton.store_cubin": True, + } + ): + # first pass with regular python wrapper code + kwargs_patched = { + **kwargs, + "cpp_wrapper": False, + } + # clone_graph(gm) makes sure no graph modification from the first pass will + # leak to the second pass. It does increase memory pressure, but the problem + # can be alleviated once we have parameters as FakeTensor. + + compiled = inner_compile( + clone_graph(gm), example_inputs, **kwargs_patched + ) + + def materialize(x): + if isinstance(x, (torch.SymInt, torch.SymFloat)): + # Need concrete value to run dynamic shapes and tune the result + return x.node.hint + else: + assert not isinstance(x, FakeTensor) + return x + + tracing_context = torch._guards.TracingContext.get() + if tracing_context: + if tracing_context.output_strides: + tracing_context.output_strides.clear() + + params_flat = [ + param + for param in tracing_context.params_flat # type: ignore[union-attr] + if param is not None + ] + real_inputs = [ + materialize(x) for x in (params_flat + V.real_inputs) + ] + else: + real_inputs = [materialize(x) for x in V.real_inputs] + + with torch.utils._python_dispatch._disable_current_modes(): + compiled(real_inputs) + + del real_inputs + + # second pass + kwargs_patched = {**kwargs, "cpp_wrapper": True} + return inner_compile(gm, example_inputs, **kwargs_patched) + + return wrapper + + +def fake_tensor_prop( + gm: torch.fx.GraphModule, + example_inputs: List[torch.Tensor], + force_allow_non_fake_inputs: bool = False, +): + """ + If we can not detect fake mode from the context of inputs, create one. + + The created fake mode will be returned. + """ + fake_mode = detect_fake_mode(example_inputs) + if not fake_mode: + fake_mode = torch._subclasses.FakeTensorMode(allow_non_fake_inputs=True) + FakeTensorProp(gm, mode=fake_mode).propagate(*example_inputs) + else: + ctx = ( + contextlib.nullcontext() + if not force_allow_non_fake_inputs + else mock.patch.object(fake_mode, "allow_non_fake_inputs", True) + ) + with ctx: # type: ignore[attr-defined] + FakeTensorProp(gm, mode=fake_mode).propagate_dont_convert_inputs( + *example_inputs + ) + + return fake_mode + + +@DebugContext.wrap +@torch.utils._python_dispatch._disable_current_modes() +@time_and_log(attr="compilation time (in seconds)") +def compile_fx_inner( + gm: torch.fx.GraphModule, + example_inputs: List[torch.Tensor], + cudagraphs: Optional[BoxedBool] = None, + num_fixed: int = 0, + is_backward: bool = False, + graph_id: Optional[int] = None, + cpp_wrapper: bool = False, + aot_mode: bool = False, + is_inference: bool = False, + boxed_forward_device_index: Optional[BoxedDeviceIndex] = None, + user_visible_outputs: FrozenSet[str] = frozenset(), + layout_opt: Optional[bool] = None, +): + """ + Inductor API that compiles a single graph. + + If you change the argument list for this funtion, make sure you + also update the call to save_args_for_compile_fx_inner below accordingly. + """ + if dynamo_utils.count_calls(gm.graph) == 0: + return make_boxed_func(gm.forward) + + if config.save_args: + save_args_for_compile_fx_inner( + gm, + example_inputs, + cudagraphs=cudagraphs, + num_fixed=num_fixed, + is_backward=is_backward, + graph_id=graph_id, + cpp_wrapper=cpp_wrapper, + aot_mode=aot_mode, + is_inference=is_inference, + boxed_forward_device_index=boxed_forward_device_index, + user_visible_outputs=user_visible_outputs, + layout_opt=layout_opt, + ) + + if cudagraphs is None: + cudagraphs = BoxedBool(config.triton.cudagraphs) + + # Inputs to fx_codegen_and_compile + graph_args = [gm, example_inputs] + graph_kwargs = { + "cudagraphs": cudagraphs, + "num_fixed": num_fixed, + "is_backward": is_backward, + "graph_id": graph_id, + "cpp_wrapper": cpp_wrapper, + "aot_mode": aot_mode, + "is_inference": is_inference, + "user_visible_outputs": user_visible_outputs, + "layout_opt": layout_opt, + } + + compiled_graph: CompiledFxGraph = fx_codegen_and_compile( + *graph_args, **graph_kwargs # type: ignore[arg-type] + ) + + if aot_mode: + return compiled_graph + + if cudagraphs: + # output args are tuple of first argument + output = list(gm.graph.nodes)[-1] + assert len(output.args) == 1 + stack_traces = [ + (arg.stack_trace if isinstance(arg, torch.fx.node.Node) else None) + for arg in output.args[0] + ] + + complex_memory_overlap_inputs = any( + complex_memory_overlap(t) + for t in example_inputs + if isinstance(t, torch.Tensor) + ) + + # doesnt work for non-trees because the warmup run would apply mutation twice + if config.triton.cudagraph_trees: + # checking if mutation is only on paramameters/static inputs + has_mutation = not all( + idx < num_fixed for idx in compiled_graph.mutated_input_idxs + ) + else: + has_mutation = len(compiled_graph.mutated_inputs) != 0 + + cudagraph_tests = [ + (set(compiled_graph.device_types) == {"cuda"}, "non-cuda device in graph"), + (not has_mutation, "mutated inputs"), + (not has_incompatible_cudagraph_ops(gm), "incompatible ops"), + (not complex_memory_overlap_inputs, "complex memory overlap"), + ( + all( + isinstance(t, (torch.Tensor, torch.SymInt)) for t in example_inputs + ), + "non-Tensor inputs", + ), + ( + ( + len(compiled_graph.device_idxs) == 1 + or not config.triton.cudagraph_trees + ), + "multiple device indices without cudagraph_trees", + ), + ] + cudagraph_fail_reasons = [s for b, s in cudagraph_tests if not b] + + if not cudagraph_fail_reasons: + if not config.triton.cudagraph_trees: + # Force specialize all inputs so that CUDA graphs will work + for t in example_inputs: + if isinstance(t, torch.SymInt): + int(t) # guard + + if ( + boxed_forward_device_index is not None + and not is_inference + and not is_backward + ): + boxed_forward_device_index.set(next(iter(compiled_graph.device_idxs))) + + compiled_graph.current_callable = cudagraphify( + compiled_graph.get_current_callable(), + example_inputs, + static_input_idxs=range(num_fixed), + device_index=next(iter(compiled_graph.device_idxs)), + stack_traces=stack_traces, + is_backward=is_backward, + is_inference=is_inference, + ) + else: + BoxedBool.disable(cudagraphs) + + # See [Backward Generation Handling] + # if cudagraph'd the forward and set the device, we need to let the cudagraph manager + # know we are we running the backward even if we will not run it in cudagraphs + if is_backward and config.triton.cudagraph_trees: + assert boxed_forward_device_index is not None + assert boxed_forward_device_index.value is not None + compiled_graph_callable = compiled_graph.get_current_callable() + + manager = torch._inductor.cudagraph_trees.get_manager( + boxed_forward_device_index.value, create_if_none_exists=False + ) + # should already exist from forward + assert manager is not None + + def compiled_artifact(new_inputs): + manager.set_to_running_backward() + return compiled_graph_callable(new_inputs) + + compiled_graph.current_callable = compiled_artifact + + if len(set(compiled_graph.device_types)) > 1: + perf_hint_log.warning("skipping cudagraphs due to multiple devices") + elif set(compiled_graph.device_types) == {"cuda"}: + if has_mutation: + perf_hint_log.warning("skipping cudagraphs due to input mutation") + elif complex_memory_overlap_inputs: + perf_hint_log.warning( + "skipping cudagraphs due to complex input striding" + ) + elif ( + len(compiled_graph.device_idxs) > 1 + and config.triton.cudagraph_trees + ): + perf_hint_log.warning( + "skipping cudagraphs due to multiple device indexes" + ) + else: + perf_hint_log.warning("skipping cudagraphs for unknown reason") + else: + perf_hint_log.warning("skipping cudagraphs for unknown reason") + + # cudagraphs does its own aligning of inputs + if not cudagraphs: + new_callable = align_inputs( + compiled_graph.get_current_callable(), example_inputs, range(num_fixed) + ) + if new_callable is not compiled_graph.get_current_callable(): + compiled_graph.current_callable = new_callable + + _step_logger()( + logging.INFO, + "torchinductor done compiling " + f"{'BACKWARDS' if is_backward else 'FORWARDS'} " + f"graph {graph_id}", + ) + + # aot autograd needs to know to pass in inputs as a list + compiled_graph._boxed_call = True + return compiled_graph + + +def fx_codegen_and_compile( + gm: torch.fx.GraphModule, + example_inputs: List[torch.Tensor], + cudagraphs: Optional[BoxedBool] = None, + num_fixed: int = 0, + is_backward: bool = False, + graph_id: Optional[int] = None, + cpp_wrapper: bool = False, + aot_mode: bool = False, + is_inference: bool = False, + user_visible_outputs: FrozenSet[str] = frozenset(), + layout_opt: Optional[bool] = None, +) -> CompiledFxGraph: + if is_tf32_warning_applicable(gm): + _warn_tf32_disabled() + + # lift the maximum depth of the Python interpreter stack + # to adapt large/deep models + sys.setrecursionlimit(max(sys.getrecursionlimit(), 2000)) + + _step_logger()( + logging.INFO, + "torchinductor compiling " + f"{'BACKWARDS' if is_backward else 'FORWARDS'} " + f"graph {graph_id}", + ) + V.debug.fx_graph(gm, example_inputs) + + shape_env = _shape_env_from_inputs(example_inputs) + + # Convert view to reshape in the graph. This is necessary primarily for + # layout optimization. Do it unconditionally for uniformity. + # + # It's needed because when we do layout optimization, an contiguous tensor + # in eager mode may becomes a channels last tensor. A view op previously + # can be applied to the contiguous tensor may not be able to be applied + # on the channels tensor any more. An error like + # RuntimeError: view size is not compatible with input tensor's size and stride + # (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead. + # will be printed. + # + # Replace view op to reshape op in this case. + # As an example, timm_resnest/botnet26t_256/convnext_base etc. will fail if we don't do this. + # + # Also this has to be done before FakeTensorProp below to avoid the failed + # .view() call. + view_to_reshape(gm) + + fake_mode = fake_tensor_prop(gm, example_inputs) + + # pattern matcher passes might not preserve striding information + # on node.meta["val"]. if in the future we rely on these being + # correct we will need to fix. + + with V.set_fake_mode(fake_mode): # type: ignore[call-arg] + # has some issues with memory in training + post_grad_passes(gm, is_inference=is_inference) + V.debug.fx_graph_transformed(gm, example_inputs) + + with V.set_fake_mode(fake_mode): # type: ignore[call-arg] + graph = GraphLowering( + gm, + shape_env=shape_env, + num_static_inputs=num_fixed, + graph_id=graph_id, + cpp_wrapper=cpp_wrapper, + aot_mode=aot_mode, + user_visible_outputs=user_visible_outputs, + ) + with V.set_graph_handler(graph): # type: ignore[call-arg] + graph.run(*example_inputs) + context = torch._guards.TracingContext.get() + if context is not None and context.output_strides is not None: + # Return the output strides to the caller via TracingContext + assert len(context.output_strides) == 0 + assert graph.graph_outputs is not None + for out in graph.graph_outputs: + if hasattr(out, "layout"): + context.output_strides.append( + tuple( # type: ignore[arg-type] + V.graph.sizevars.size_hint(s) for s in out.layout.stride + ) + ) + else: + context.output_strides.append(None) + compiled_fn = graph.compile_to_fn() + + if graph.disable_cudagraphs: + BoxedBool.disable(cudagraphs) + + compiled_graph = CompiledFxGraph( + compiled_artifact=compiled_fn, + cache_key=graph.cache_key, + artifact_path=graph.cache_path, + cache_linemap=graph.cache_linemap, + device_types=graph.device_types, + device_idxs=graph.device_idxs, + mutated_inputs=graph.mutated_inputs, + mutated_input_idxs=set(graph.mutated_input_idxs), + ) + return compiled_graph + + +def clone_preserve_strides(x: torch.Tensor): + needed_size = ( + sum((shape - 1) * stride for shape, stride in zip(x.size(), x.stride())) + 1 + ) + buffer = torch.as_strided(x, (needed_size,), (1,)).clone() + return torch.as_strided(buffer, x.size(), x.stride()) + + +def copy_misaligned_inputs( + new_inputs: List[torch.Tensor], check_inputs_idxs: Sequence[int] +) -> None: + for i in check_inputs_idxs: + if new_inputs[i].data_ptr() % ALIGNMENT: + new_inputs[i] = clone_preserve_strides(new_inputs[i]) + + +def get_input_idxs_to_check( + inputs: Union[List[torch.Tensor], Sequence[int]], + static_input_idxs: Sequence[int], +) -> Sequence[int]: + def is_aligned(storage_offset, dtype): + return (storage_offset * get_dtype_size(dtype)) % ALIGNMENT == 0 + + ids_to_check = [] + for i, input in enumerate(inputs): + if ( + isinstance(input, torch.Tensor) + and ( + i not in static_input_idxs + or not is_aligned(input.storage_offset(), input.dtype) + ) + and input.device.type == "cuda" + ): + ids_to_check.append(i) + return ids_to_check + + +def align_inputs_from_check_idxs( + model: Callable[[List[torch.Tensor]], Any], inputs_to_check: Sequence[int] +): + if len(inputs_to_check) == 0: + return model + + def run(new_inputs): + copy_misaligned_inputs(new_inputs, inputs_to_check) + return model(new_inputs) + + return run + + +def align_inputs( + model: Callable[[List[torch.Tensor]], Any], + inputs: List[torch.Tensor], + static_input_idxs: Sequence[int] = (), +): + inputs_to_check = get_input_idxs_to_check(inputs, static_input_idxs) + return align_inputs_from_check_idxs(model, inputs_to_check) + + +@dynamo_utils.dynamo_timed +def cudagraphify( + model: torch.fx.GraphModule, + inputs: List[torch.Tensor], + static_input_idxs: Sequence[int] = (), + *, + device_index: int, + stack_traces: List[Optional[str]], + is_backward: bool, + is_inference: bool, +): + from torch._inductor.cudagraph_trees import ( + cudagraphify_impl as new_cudagraphify_impl, + ) + + cudagraphify_fn: Callable[..., Any] + if config.triton.cudagraph_trees: + cudagraphify_fn = functools.partial( + new_cudagraphify_impl, + device_index=device_index, + stack_traces=stack_traces, + is_backward=is_backward, + is_inference=is_inference, + ) + else: + cudagraphify_fn = cudagraphify_impl + + # if using fake tensors, defer cudagraphs until we get real inputs at runtime + if not any(isinstance(inp, FakeTensor) for inp in inputs): + return cudagraphify_fn(model, inputs, static_input_idxs) + + compiled_fn = None + + def run(new_inputs): + nonlocal compiled_fn + if compiled_fn is None: + with dynamo_utils.preserve_rng_state(): + compiled_fn = cudagraphify_fn(model, new_inputs, static_input_idxs) + return compiled_fn(new_inputs) + + return run + + +def remove_unaligned_input_idxs( + inputs: Union[List[torch.Tensor], Sequence[int]], + static_input_idxs: Sequence[int], +): + """ + We require all inputs to be aligned, so introduce a copy for any + that aren't. + """ + aligned_static_input_idxs = [] + for idx, input in zip(static_input_idxs, inputs): + if isinstance(input, torch.Tensor) and (input.data_ptr() % ALIGNMENT) == 0: + aligned_static_input_idxs.append(idx) + if len(aligned_static_input_idxs) != len(static_input_idxs): + return aligned_static_input_idxs + return static_input_idxs + + +def static_input(x: torch.Tensor): + """ + Copy and input while preserving strides + """ + # TODO(jansel): figure out why this version doesn't work: + # return torch.empty_strided(x.size(), x.stride(), dtype=x.dtype, device=x.device) + needed_size = ( + sum((shape - 1) * stride for shape, stride in zip(x.size(), x.stride())) + 1 + ) + buffer = torch.empty(needed_size, dtype=x.dtype, device=x.device) + return torch.as_strided(buffer, x.size(), x.stride()) + + +def index_expanded_dims_and_copy_( + dst: torch.Tensor, + src: torch.Tensor, + expanded_dims: List[int], +): + "Index into expanded dimensions of both dst and src then copy_" + dst = index_expanded_dims(dst, expanded_dims) + src = index_expanded_dims(src, expanded_dims) + dst.copy_(src) + + +def cudagraphify_impl( + model: torch.fx.GraphModule, + inputs: List[torch.Tensor], + static_input_idxs: Sequence[int] = (), +): + """ + Assumes inputs[static_input_idxs[i]] are always the same memory address + """ + check_input_idxs = get_input_idxs_to_check(inputs, static_input_idxs) + static_input_idxs = remove_unaligned_input_idxs(inputs, static_input_idxs) + copy_misaligned_inputs(inputs, check_input_idxs) + + assert isinstance(inputs, list) + + inps_expanded_dims = [ + get_expanded_dims(x) if idx not in static_input_idxs else [] + for idx, x in enumerate(inputs) + ] + + # allocate static tensor inputs + static_inputs = [ + x + if not isinstance(x, torch.Tensor) + else static_input(x) + if idx not in static_input_idxs + else x.detach() + for idx, x in enumerate(inputs) + ] + + # copy over input values for fresh allocations + for idx, (x, expanded_dims) in enumerate(zip(inputs, inps_expanded_dims)): + if isinstance(x, torch.Tensor) and idx not in static_input_idxs: + index_expanded_dims_and_copy_(static_inputs[idx], x, expanded_dims) + + # warmup + torch.cuda.synchronize() + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + # copy static_inputs because it will be cleared in model + with torch.cuda.stream(stream): + model(list(static_inputs)) + stream.synchronize() + torch.cuda.current_stream().wait_stream(stream) + torch.cuda.synchronize() + + # record + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream, capture_error_mode="thread_local"): + static_outputs = model(list(static_inputs)) + if not isinstance(static_outputs, (list, tuple)): + static_outputs = (static_outputs,) + + if config.size_asserts: + + def run(new_inputs): + assert len(static_inputs) == len(new_inputs) + for idx, (dst, src, expanded_dims) in enumerate( + zip(static_inputs, new_inputs, inps_expanded_dims) + ): + if not isinstance(dst, torch.Tensor): + pass + elif idx in static_input_idxs: + assert dst.data_ptr() == src.data_ptr() + else: + # TODO - could make one single op of multiple slices + # and avoid dispatch. + # Could also pre-index the `dst` tensors + index_expanded_dims_and_copy_(dst, src, expanded_dims) + new_inputs.clear() + graph.replay() + return static_outputs + + else: + copy_indices = [ + idx for idx in range(len(static_inputs)) if idx not in static_input_idxs + ] + + def run(new_inputs): + for idx in copy_indices: + expanded_dims = inps_expanded_dims[idx] + index_expanded_dims_and_copy_( + static_inputs[idx], new_inputs[idx], expanded_dims + ) + new_inputs.clear() + graph.replay() + return static_outputs + + return align_inputs_from_check_idxs(run, check_input_idxs) + + +def count_tangents(fx_g: torch.fx.GraphModule): + """ + Infers which inputs are static for a backwards graph + """ + + def is_saved_tensor(x): + return ( + "tangents" not in x.name + and "bwd_seed" not in x.name + and "bwd_base_offset" not in x.name + ) + + arg_count = 0 + static_arg_idxs = [] + for n in fx_g.graph.nodes: + if n.op == "placeholder": + if is_saved_tensor(n): + static_arg_idxs.append(arg_count) + arg_count += 1 + + assert static_arg_idxs == list(range(len(static_arg_idxs))) + return len(static_arg_idxs) + + +_in_aot_compilation = BoxedBool(False) + + +def compile_fx_aot( + model_: torch.fx.GraphModule, + example_inputs_: List[torch.Tensor], + inner_compile: Callable[..., Any] = compile_fx_inner, + config_patches: Optional[Dict[str, Any]] = None, +): + config_patches = ( + {"cpp_wrapper": True} + if config_patches is None + else {**config_patches, "cpp_wrapper": True} + ) + if ( + "aot_inductor_output_path" not in config_patches + and not config.aot_inductor_output_path + ): + config_patches = { + **config_patches, + "aot_inductor_output_path": code_hash(model_.code), + } + + with mock.patch.object(_in_aot_compilation, "value", True): + return compile_fx( + model_, + example_inputs_, + inner_compile=functools.partial(inner_compile, aot_mode=True), + config_patches=config_patches, + ) + + +_graph_counter = itertools.count(0) + + +def fw_compiler_freezing( + aot_autograd_model: torch.fx.GraphModule, + aot_example_inputs: List[torch.Tensor], + dynamo_model: torch.fx.GraphModule, + num_example_inputs: int, + inner_compile: Callable[..., Any], + cudagraphs: BoxedBool, + graph_id: int, + forward_device: BoxedDeviceIndex, +): + from torch._inductor.freezing import convert_conv_weights_to_channels_last, freeze + + # partition_fn won't be called + joint_graph_passes(aot_autograd_model) + + layout_opt = GraphLowering.decide_layout_opt(aot_autograd_model) + if layout_opt: + # make sure meta['val'] is properly setup + fake_tensor_prop(aot_autograd_model, aot_example_inputs, True) + convert_conv_weights_to_channels_last(aot_autograd_model) + + opt_model, preserved_arg_indices = freeze( + dynamo_model, + aot_autograd_model, + aot_example_inputs, # type: ignore[arg-type] + ) + + aot_example_inputs = [aot_example_inputs[ind] for ind in preserved_arg_indices] + num_fixed = len(preserved_arg_indices) - num_example_inputs + + fake_mode = detect_fake_mode(aot_example_inputs) + + # for freezing, all graph outputs should be user visible + *_, model_outputs_node = opt_model.graph.nodes + model_outputs = model_outputs_node.args[0] + user_visible_outputs = [ + n.name for n in model_outputs if isinstance(n, torch.fx.Node) + ] + + # constant params will be real tensors, not fake + tracing_context = torch._guards.TracingContext.get() + assert tracing_context is not None + params_flat = tracing_context.params_flat + assert params_flat is not None + for i in range(len(params_flat)): + if i not in preserved_arg_indices: + params_flat[i] = None + + with mock.patch.object(fake_mode, "allow_non_fake_inputs", True): + optimized_function = inner_compile( + opt_model, + aot_example_inputs, + num_fixed=num_fixed, + cudagraphs=cudagraphs, + graph_id=graph_id, + is_inference=True, + boxed_forward_device_index=forward_device, + layout_opt=layout_opt, + user_visible_outputs=user_visible_outputs, + ) + + # aot_inductor codegens a call that takes in just the inputs, so we don't return a wrapper + # that drops constant-ified params + if _in_aot_compilation: + return optimized_function + + def wrapper(args): + args_new = [args[i] for i in preserved_arg_indices] + args.clear() + return optimized_function(args_new) + + wrapper._boxed_call = True # type: ignore[attr-defined] + + return wrapper + + +def compile_fx( + model_: torch.fx.GraphModule, + example_inputs_: List[torch.Tensor], + inner_compile: Callable[..., Any] = compile_fx_inner, + config_patches: Optional[Dict[str, Any]] = None, + decompositions: Optional[Dict[OpOverload, Callable[..., Any]]] = None, +): + """Main entrypoint to a compile given FX graph""" + if config_patches: + with config.patch(config_patches): # type: ignore[attr-defined] + return compile_fx( + model_, + example_inputs_, + # need extra layer of patching as backwards is compiled out of scope + inner_compile=config.patch(config_patches)(inner_compile), # type: ignore[attr-defined] + decompositions=decompositions, + ) + + if config.cpp_wrapper: + with config.patch( # type: ignore[attr-defined] + { + "cpp_wrapper": False, + "triton.autotune_cublasLt": False, + "triton.cudagraphs": False, + # CudaWrapperCodeGen relies on kernel name to find the autotuned cubin file + "triton.unique_kernel_names": True, + } + ), V.set_real_inputs( + example_inputs_ + ): # type: ignore[call-arg] + return compile_fx( + model_, + example_inputs_, + inner_compile=inner_compile_with_cpp_wrapper(inner_compile), + decompositions=decompositions, + ) + + recursive_compile_fx = functools.partial( + compile_fx, + inner_compile=inner_compile, + decompositions=decompositions, + ) + + if not graph_returns_tuple(model_): + return make_graph_return_tuple( + model_, + example_inputs_, + recursive_compile_fx, + ) + + if isinstance(model_, torch.fx.GraphModule): + if isinstance(model_.graph._codegen, _PyTreeCodeGen): + # this graph is the result of dynamo.export() + return handle_dynamo_export_graph( + model_, + example_inputs_, + recursive_compile_fx, + ) + + # Since handle_dynamo_export_graph will trigger compile_fx again, + # Move these passes after handle_dynamo_export_graph to avoid repeated calls. + model_ = pre_grad_passes(model_, example_inputs_) + + if any(isinstance(x, (list, tuple, dict)) for x in example_inputs_): + return flatten_graph_inputs( + model_, + example_inputs_, + recursive_compile_fx, + ) + + assert not config._raise_error_for_testing + num_example_inputs = len(example_inputs_) + cudagraphs = BoxedBool(config.triton.cudagraphs) + forward_device = BoxedDeviceIndex(None) + + graph_id = next(_graph_counter) + + decompositions = ( + decompositions if decompositions is not None else select_decomp_table() + ) + + @dynamo_utils.dynamo_timed + def fw_compiler_base( + model: torch.fx.GraphModule, + example_inputs: List[torch.Tensor], + is_inference: bool, + ): + if is_inference: + # partition_fn won't be called + joint_graph_passes(model) + + num_rng_seed_offset_inputs = 2 if functorch_config.functionalize_rng_ops else 0 + fixed = len(example_inputs) - num_example_inputs - num_rng_seed_offset_inputs + user_visible_outputs = set() + + if config.keep_output_stride: + *_, model_outputs_node = model.graph.nodes + assert model_outputs_node.op == "output" + model_outputs, _ = pytree.tree_flatten(model_outputs_node.args) + num_model_outputs = len(model_outputs) + + context = torch._guards.TracingContext.get() + if context is not None and context.fw_metadata: + original_output_start_index = context.fw_metadata.num_mutated_inputs + else: + original_output_start_index = 0 + + if isinstance(model_, torch.fx.GraphModule): + *_, orig_model_outputs_node = model_.graph.nodes + assert orig_model_outputs_node.op == "output" + orig_model_outputs, _ = pytree.tree_flatten( + orig_model_outputs_node.args + ) + num_orig_model_outputs = len(orig_model_outputs) + else: + num_orig_model_outputs = num_model_outputs + + assert num_orig_model_outputs <= num_model_outputs + + # We makes the following assumption + # For inference + # len(orig_model_outputs) == len(model_outputs) + # For training + # len(orig_model_outputs) <= len(model_outputs) + # During training, most of the time the model_outputs starts with + # orignal module's outputs followed by saved activations. + # But this can be not true if the model have inplace updated tensors. + # AOTAutograd will make those tensors being returned before the orignal + # module's output. + # To make things safe, we'll use original_output_start_index field + # set by AOTAutograd to decide where the original module outputs start. + + user_visible_outputs = { + n.name + for n in model_outputs[ + original_output_start_index : original_output_start_index + + num_orig_model_outputs + ] + if isinstance(n, torch.fx.Node) + } + + return inner_compile( + model, + example_inputs, + num_fixed=fixed, + cudagraphs=cudagraphs, + graph_id=graph_id, + is_inference=is_inference, + boxed_forward_device_index=forward_device, + user_visible_outputs=user_visible_outputs, + ) + + fw_compiler = functools.partial(fw_compiler_base, is_inference=False) + + if config.freezing and not torch.is_grad_enabled(): + inference_compiler = functools.partial( + fw_compiler_freezing, + dynamo_model=model_, + num_example_inputs=num_example_inputs, + inner_compile=inner_compile, + cudagraphs=cudagraphs, + graph_id=graph_id, + forward_device=forward_device, + ) + else: + inference_compiler = functools.partial(fw_compiler_base, is_inference=True) + + def partition_fn(graph, joint_inputs, **kwargs): + joint_graph_passes(graph) + return min_cut_rematerialization_partition( + graph, joint_inputs, **kwargs, compiler="inductor" + ) + + @dynamo_utils.dynamo_timed + def bw_compiler(model: torch.fx.GraphModule, example_inputs: List[torch.Tensor]): + fixed = count_tangents(model) + return inner_compile( + model, + example_inputs, + num_fixed=fixed, + cudagraphs=cudagraphs, + is_backward=True, + graph_id=graph_id, + boxed_forward_device_index=forward_device, + ) + + # TODO: can add logging before/after the call to create_aot_dispatcher_function + # in torch._functorch/aot_autograd.py::aot_module_simplified::aot_function_simplified::new_func + # once torchdynamo is merged into pytorch + fake_mode = detect_fake_mode(example_inputs_) or torch._subclasses.FakeTensorMode( + allow_non_fake_inputs=True + ) + tracing_context = ( + torch._guards.TracingContext.get() or torch._guards.TracingContext(fake_mode) + ) + + with V.set_fake_mode(fake_mode), torch._guards.tracing( # type: ignore[call-arg] + tracing_context + ), compiled_autograd.disable(): + return aot_autograd( + fw_compiler=fw_compiler, + bw_compiler=bw_compiler, + inference_compiler=inference_compiler, + decompositions=decompositions, + partition_fn=partition_fn, + keep_inference_input_mutations=True, + )(model_, example_inputs_) + + +# pass config dict back to user +def get_patched_config_dict(config_patches=None): + with config.patch(config_patches): # type: ignore[attr-defined] + return config.get_config_copy() # type: ignore[attr-defined] + + +def _shape_env_from_inputs(inputs: List[torch.Tensor]): + shape_env = None + fake_mode = detect_fake_mode(inputs) + + # TODO(voz): It would be nice to enable this assert, but there are lots of tests that + # pass in real inputs for now. + # if len(inputs) > 0: + # assert fake_mode is not None, breakpoint() + + if fake_mode is not None: + return fake_mode.shape_env + + # When there are no tensor inputs, get shape_env from the first SymInt. + for input in inputs: + if isinstance(input, torch.SymInt): + return input.node.shape_env + + # TODO(voz): Should we always have one anyway? + return None + + +def output_node(gm: torch.fx.GraphModule): + """Get the output node from an FX graph""" + last_node = next(iter(reversed(gm.graph.nodes))) + assert last_node.op == "output" + return last_node + + +def graph_returns_tuple(gm: torch.fx.GraphModule): + """True if a FX graph returns a tuple""" + if not isinstance(gm, torch.fx.GraphModule): + return True # can't check this, assume true + (rv,) = output_node(gm).args + if isinstance(rv, (list, tuple)): + return True + if ( + isinstance(rv, torch.fx.node.Node) + and hasattr(rv.target, "_schema") + and len(rv.target._schema.returns) > 1 + and all(str(ret.type) == "Tensor" for ret in rv.target._schema.returns) + ): + # for graphs whose result is one node with multiple outputs + return True + return False + + +def make_graph_return_tuple( + gm: torch.fx.GraphModule, + inputs: List[torch.Tensor], + compile_gm: Callable[..., Any], +): + """ + Mutate gm so it returns a tuple. This is only needed for graphs + not created by torchdynamo that return non-tuples. + """ + node = output_node(gm) + (rv,) = node.args + rv, spec = pytree.tree_flatten(rv) + with gm.graph.inserting_before(node): + gm.graph.output(rv) + gm.graph.erase_node(node) + assert graph_returns_tuple(gm) + + compiled_fn = compile_gm(gm, inputs) + + @functools.wraps(compiled_fn) + def wrapper(*args, **kwargs): + return pytree.tree_unflatten(compiled_fn(*args, **kwargs), spec) + + return wrapper + + +def flatten_graph_inputs(gm: torch.fx.GraphModule, inputs, compile_gm): + """ + Mutate inputs so that they are flat and wrap gm such that it + accepts those inputs. This is only needed for graphs not created + by torchdynamo that take bumpy inputs. + """ + inputs, spec = pytree.tree_flatten(inputs) + + class GmWrapper(torch.nn.Module): + def __init__(self): + super().__init__() + self.gm = gm + + def forward(self, *args): + args: List[Any] = list(args) + return self.gm(*pytree.tree_unflatten(args, spec)) + + compiled_fn = compile_gm(GmWrapper(), inputs) + + @functools.wraps(compiled_fn) + def wrapper(*args): + # note this doesn't check the spec, assuming it is the same + return compiled_fn(*pytree.tree_flatten(args)[0]) + + return wrapper + + +def handle_dynamo_export_graph( + gm: torch.fx.GraphModule, + inputs: List[torch.Tensor], + compile_gm: Callable[..., Any], +): + """ + `torch._dynamo.export` embeds pytrees in the FX graph codegen object, + convert that to a normal FX graph so inductor can compile it. + """ + codegen = gm.graph._codegen + gm.graph._codegen = torch.fx.graph.CodeGen() + gm.recompile() + + compiled_fn = compile_gm(gm, codegen.process_inputs(*inputs)) + + @functools.wraps(compiled_fn) + def wrapper(*args): + return codegen.process_outputs(compiled_fn(*codegen.process_inputs(*args))) + + return wrapper diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/config.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/config.py new file mode 100644 index 0000000000000000000000000000000000000000..579546851e50a07ec2ed09483ad0ba895203fc6d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/config.py @@ -0,0 +1,449 @@ +import os +import sys + +import torch + +# add some debug printouts +debug = False + +# Whether to disable a progress bar for autotuning +disable_progress = True + +# Whether to enable printing the source code for each future +verbose_progress = False + +# use cpp wrapper instead of python wrapper +cpp_wrapper = False + +# dead code elimination +dce = False + +# assume weight tensors are fixed size +static_weight_shapes = True + +# put correctness assertions in generated code +size_asserts = os.environ.get("TORCHINDUCTOR_SIZE_ASSERTS", "1") == "1" + +# enable loop reordering based on input orders +pick_loop_orders = True + +# reuse a kernel input as the output +inplace_buffers = True + +# reuse a buffer for an unrelated purpose +allow_buffer_reuse = True + +# codegen benchmark harness +benchmark_harness = True + +# fuse pointwise into templates +epilogue_fusion = True + +# do epilogue fusions before other fusions +epilogue_fusion_first = False + +# enable pattern match+replace optimizations +pattern_matcher = True + +# Optimize away split cat patterns (Experimental) +split_cat_fx_passes = True + +# enable pattern match with group fusion (using fbgemm) +group_fusion = False + +# enable pattern match with batch fusion (using torch op) +batch_fusion = True + +# enable reordering pass +reordering = True + +# for pattern torch.mm(a, b.to(dtype)) with cuda tensors, +# enable torch._inductor.kernel.mm.tuned_mixed_mm fused kernel. +# Autotune will compare perf with normal cast->then->mm option +use_mixed_mm = False + +# for pattern torch.mm(a, b.to(dtype)) with cuda tensors, always use +# torch._inductor.kernel.mm.tuned_mixed_mm's fused kernel. +# Autotune will not compare with normal cast->then->mm option. +# (if force_mixed_mm is true, the use_mixed_mm flag will be ignored) +force_mixed_mm = False + +# AOTInductor output path +# If an absolute path is specified, the generated lib files will be stored under the directory; +# If a relative path is specified, it will be used as a subdirectory under the default caching path; +# If not specified, a temp directory will be created under the default caching path +aot_inductor_output_path = "" + +# enable slow autotuning passes to select algorithms +max_autotune = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE") == "1" + +# enable slow autotuning passes to select pointwise/reductions algorithms +max_autotune_pointwise = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_POINTWISE") == "1" + +# enable slow autotuning passes to select gemm algorithms +max_autotune_gemm = os.environ.get("TORCHINDUCTOR_MAX_AUTOTUNE_GEMM") == "1" + +# Specify candidate backends for gemm autotune. +# Possible choices are combinations of: ATen, Triton. +# ATen: default Pytorch ATen kernels. +# Triton: Triton templates defined in torch inductor. +max_autotune_gemm_backends = os.environ.get( + "TORCHINDUCTOR_MAX_AUTOTUNE_GEMM_BACKENDS", "ATEN,TRITON" +).upper() + +# enable searching global and local cache regardless of `max_autotune` +search_autotune_cache = os.environ.get("TORCHINDUCTOR_SEARCH_AUTOTUNE_CACHE") == "1" + +save_args = os.environ.get("TORCHINDUCTOR_SAVE_ARGS") == "1" + +# We will disable creating subprocess for autotuning if this is False +autotune_in_subproc = os.environ.get("TORCHINDUCTOR_AUTOTUNE_IN_SUBPROC") == "1" + +coordinate_descent_tuning = ( + os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_TUNING") == "1" +) +coordinate_descent_check_all_directions = ( + os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_CHECK_ALL_DIRECTIONS") == "1" +) +coordinate_descent_search_radius = int( + os.environ.get("TORCHINDUCTOR_COORDINATE_DESCENT_RADIUS", "1") +) + +layout_optimization = os.environ.get("TORCHINDUCTOR_LAYOUT_OPTIMIZATION", "1") == "1" + +# Whether to keep the output strides the same as eager after layout optimization. +keep_output_stride = os.environ.get("TORCHINDUCTOR_KEEP_OUTPUT_STRIDE", "1") == "1" + +# Enabling this will let compiler print warning messages if a generated triton +# kernel has inputs with mixed layouts. This is helpful for perf debugging +# since kernel with mixed layout inputs may run much slower then one whose inputs +# have uniform layouts. +warn_mix_layout = os.environ.get("TORCHINDUCTOR_WARN_MIX_LAYOUT") == "1" + +# control store vs recompute heuristic +# For fanouts, rematerialization can lead to exponential blowup. So, have +# smaller threshold +realize_reads_threshold = 4 +realize_bytes_threshold = 2000 + +# Threshold to prevent excessive accumulation of ops in one buffer during lowering +realize_acc_reads_threshold = 8 + +# fallback to eager for random/dropout, this is slow but useful for debugging +fallback_random = False + +# automatically create fallbacks when encountering an unhandled op +implicit_fallbacks = True + +# fuse even in cases without common reads +aggressive_fusion = False + +# how many nodes to allow into a single fusion +max_fusion_size = 64 + +# replace small reductions with pointwise, disable with `= 1` +unroll_reductions_threshold = 8 + +# Add extra comments to output code (causes compile cache misses) +comment_origin = False + +# Convert 1x1 convs into matmuls +conv_1x1_as_mm = False + +# Enable split reductions for better utilization when the dimension +# being reduced over is large (by splitting it) +split_reductions = True + +benchmark_kernel = os.environ.get("TORCHINDUCTOR_BENCHMARK_KERNEL", "0") == "1" + +# Enable constant and index_expr folding +constant_and_index_propagation = True + +# constant folding on the joint graph +joint_graph_constant_folding = True + +# Enable indirect_indexing asserts for decompositions and lowerings +debug_index_asserts = False + + +def is_fbcode(): + return not hasattr(torch.version, "git_version") + + +# warnings intended for PyTorch developers, disable for point releases +is_nightly_or_source = "dev" in torch.__version__ or "git" in torch.__version__ +developer_warnings = is_fbcode() or is_nightly_or_source + + +def decide_compile_threads(): + """ + Here are the precedence to decide compile_threads + 1. User can override it by TORCHINDUCTOR_COMPILE_THREADS. One may want to disable async compiling by + setting this to 1 to make pdb happy. + 2. Set to 1 if it's win32 platform or it's a fbcode build + 3. decide by the number of CPU cores + """ + if "TORCHINDUCTOR_COMPILE_THREADS" in os.environ: + return int(os.environ["TORCHINDUCTOR_COMPILE_THREADS"]) + elif sys.platform == "win32" or is_fbcode(): + return 1 + else: + cpu_count = ( + len(os.sched_getaffinity(0)) + if hasattr(os, "sched_getaffinity") + else os.cpu_count() + ) + assert cpu_count + return min(32, cpu_count) + + +compile_threads = decide_compile_threads() + +# gemm autotuning global cache dir +if is_fbcode(): + from libfb.py import parutil # type: ignore[import] + + try: + if __package__: + global_cache_dir = parutil.get_dir_path( + os.path.join(__package__.replace(".", os.sep), "fb/cache") + ) + else: + global_cache_dir = parutil.get_dir_path("fb/cache") + except ValueError: + global_cache_dir = None +else: + global_cache_dir = None + +# If kernel is fused, the name is generated from the origin node op names +# for larger kernels limit this +kernel_name_max_ops = 10 + +# Pad input tensors of matmul/bmm/addmm to leverage Tensor Cores in NVIDIA GPUs +shape_padding = os.environ.get("TORCHINDUCTOR_SHAPE_PADDING", "1") == "1" + +# Fx-based linear/matmul/bmm + permute/transpose vertical fusion +permute_fusion = os.environ.get("TORCHINDUCTOR_PERMUTE_FUSION", "0") == "1" + +# Mark the wrapper call in PyTorch profiler +profiler_mark_wrapper_call = False + +# Generate hook calls to torch._inductor.hooks.run_intermediate_hooks for +# every intermediate for which we can correlate it with an intermediate +# from the original FX graph +generate_intermediate_hooks = False + +# Populate traceback field on IRNode; good for debugging why origin_node is +# not populated, or finding out where an IRNode was constructed +debug_ir_traceback = False + +# used for debugging to make sure config is properly set +_raise_error_for_testing = False + +_profile_var = os.environ.get("TORCHINDUCTOR_PROFILE", "") +profile_bandwidth = _profile_var != "" +profile_bandwidth_regex = "" if _profile_var == "1" else _profile_var + +# TODO: remove later +disable_cpp_codegen = False + + +# Freezing will attempt to inline weights as constants in optimization +# and run constant folding and other optimizations on them. After freezing, weights +# can no longer be updated. +freezing: bool = os.environ.get("TORCHINDUCTOR_FREEZING", "0") == "1" + +# Make freezing invalidate the eager Parameters of nn modules, to avoid memory overhead +# of potentially keeping multiple copies of weights. +freezing_discard_parameters: bool = False + + +# config specific to codegen/cpp.py +class cpp: + # set to torch.get_num_threads() + threads = -1 + + # Do not generate loops when the condition doesn't hold, like: + # for(long i0=4096; i0<4096; i0+=1) + no_redundant_loops = True + + # Assume number of threads is dynamic, don't specialize thread number. + # Kernels don't recompile on thread number changes with this flag on. + # For single-threaded workload, turning it on would incur a slight + # performance degradation. + dynamic_threads = False + + simdlen = None + min_chunk_size = 4096 + cxx = ( + None, # download gcc12 from conda-forge if conda is installed + # "g++-12", + # "g++-11", + # "g++-10", + # "clang++", + os.environ.get("CXX", "g++"), + # "g++.par", + ) + # Allow kernel performance profiling via PyTorch profiler + enable_kernel_profile = False + + # enable weight prepacking to get a better performance; may lead to large memory footprint + weight_prepack = True + + # Inject a bug into our relu implementation; useful for testing our repro + # extraction and minification functionality. + # Valid values: "compile_error", "runtime_error", "accuracy" + inject_relu_bug_TESTING_ONLY = None + inject_log1p_bug_TESTING_ONLY = None + + # If None, autodetect whether or not AVX512/AVX2 can be used. Otherwise, + # force usage as specified, without testing. + vec_isa_ok = None + + # similar to config.triton.descriptive_names + descriptive_names = "original_aten" + + # how many nodes to allow into a single horizontal fusion + max_horizontal_fusion_size = 16 + + +# config specific to codegen/triton.py +class triton: + # Use cudagraphs on output code + cudagraphs = False + + # Use cudagraph trees for memory pooling if `cudagraphs` is True + cudagraph_trees = not is_fbcode() + + # assertions not on the fast path, steady state + slow_path_cudagraph_asserts = True + + # TODO - need to debug why this prevents cleanup + cudagraph_trees_history_recording = False + + # assertions on the fast path + fast_path_cudagraph_asserts = False + + # skip warmup for cudagraph trees + skip_cudagraph_warmup = False + + # Synchronize before and after every compiled graph. + debug_sync_graph = False + + # Synchronize after every kernel launch, to help pinpoint bugs + debug_sync_kernel = False + + # Always load full blocks (rather than broadcasting inside the block) + dense_indexing = False + + # limit tiling dimensions + max_tiles = 2 + + # use triton.autotune for pointwise ops with complex layouts + # this should only be disabled for debugging/testing + autotune_pointwise = True + + # max autotune gemm with cublasLt + autotune_cublasLt = True + + # should we stop a fusion to allow better tiling? + tiling_prevents_pointwise_fusion = True + tiling_prevents_reduction_fusion = True + + # assert that indirect indexing does not read / write out of bounds + assert_indirect_indexing = True + + # should we give different names to kernels + # Note: This is orthogonal to descriptive_names - this is deciding whether + # our triton kernel names should all be `triton_` (to maximize caching) or + # whether they should be unique. + unique_kernel_names = os.environ.get("TORCHINDUCTOR_UNIQUE_KERNEL_NAMES") == "1" + + # should we put op names in kernel names + # False: No special names (just triton__1, triton__2, etc.) + # "torch": Maps to the fx op in the Dynamo graph (module name, method name, etc.) + # "original_aten": Maps to the highest-level aten op (i.e. pre-decompositions) + # "inductor_node": Maps to the node name in the FX graph passed to Inductor + descriptive_names = "original_aten" + + # use alternate codegen for smaller reductions + persistent_reductions = ( + os.environ.get("TORCHINDUCTOR_PERSISTENT_REDUCTIONS", "1") == "1" + ) + + # hint to Triton when arguments are divisible by 16 + divisible_by_16 = True + + # theses are not enforced, but they are used by asserts in triton_heuristics.py + # NOTE: mobilevit_s in timm_models required X to be set to the higher value 2048 + max_block = {"X": 2048, "Y": 1024, "Z": 1024} + + # Store the generated cubin files for cpp wrapper code to load + store_cubin = False + + # the max number of spills we allow for the configs we benchmark. + # Setting this to 0 means we skip a config if it spills even a single + # register. + # Settting it to a larger value allows a config spilling a small amount + # of registers being benchmarked. + # + # NOTE: triton will always report >0 register spills for kernels using sin/cos. + # (check this issue https://github.com/openai/triton/issues/1756 ) + # So far we see a fixed 8 spilled registers for kernels using sin/cos. + # Raise the threshold to 16 to be safe. + # We should revisit this once we understand more of the source of register spills. + spill_threshold: int = 16 + + # Inject a bug into our relu implementation; useful for testing our repro + # extraction and minification functionality. + # Valid values: "compile_error", "runtime_error", "accuracy" + inject_relu_bug_TESTING_ONLY = None + + +# create a directory containing lots of debug information +class trace: + # master switch for all debugging flags below + enabled = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1" + + # Save python logger call >=logging.DEBUG + debug_log = False + + # Save python logger call >=logging.INFO + info_log = False + + # Save input FX graph (post decomps, pre optimization) + fx_graph = True + + # Save FX graph after transformations + fx_graph_transformed = True + + # Save TorchInductor IR before fusion pass + ir_pre_fusion = True + + # Save TorchInductor IR after fusion pass + ir_post_fusion = True + + # Copy generated code to trace dir + output_code = True + + # SVG figure showing post-fusion graph + graph_diagram = os.environ.get("INDUCTOR_POST_FUSION_SVG", "0") == "1" + + # Store cProfile (see snakeviz to view) + compile_profile = False + + # Upload the .tar.gz file + # Needs to be overriden based on specific environment needs + upload_tar = None + + +_save_config_ignore = { + # workaround: "Can't pickle " + "trace.upload_tar", +} + + +from .._dynamo.config_utils import install_config_module + +# adds patch, save_config, etc +install_config_module(sys.modules[__name__]) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/cudagraph_trees.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/cudagraph_trees.py new file mode 100644 index 0000000000000000000000000000000000000000..bdbae6d00badb2c14a071a036d63368266816346 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/cudagraph_trees.py @@ -0,0 +1,2137 @@ +""" +CUDA graph trees are a safety abstraction over CUDAGraphs, similar to make_graph_callables, +which share the same memory pool. Sharing a memory pool is an extremely +important optimization when chaining multiple CUDA graphs together, as it +prevents you from needing to copy intermediate tensors from one graph to the +next, and reduces overall memory usage by allowing dead memory from the first +pool to be reused in the second. + +The standard graph/make_graph_callables support sharing memory pool, but +with a lot of caveats. CUDA graph trees remove these restrictions: + +* Previously, if you recorded graphs A, B, you had to replay A, B in that + order. With CUDA graph trees, after replaying A, you can change your + mind and record/replay a different graph B'; we will support efficient + execution of both A, B and A, B', using only max(mem(A, B), mem(A, B')). In + other words: we support arbitrary trees of CUDA graph operations, not just + sequences (this is why this feature is called CUDA graph trees.) + +* Previously, if you executed graph A, some non-CUDA graph code, and then + graph B, after executing graph B, it was not safe to retain any references + to intermediates produced by A. With CUDA graph trees, we track if any +outputs of graph A are still live by the time graph B is run, and make + sure graph B doesn't clobber there memory when reusing the CUDA graphs + pool. You'll get a separate recording of B depending on what tensors + stay live or dead. + +CUDA graph trees are flexible enough to be used in Dynamo across graph breaks, +which is their primary use case. + +The ability to switch from replay to record is fairly nontrivial: remember that +when you replay a CUDA graph, you only replay CUDA operations; no CPU side state +is updated. In particular, the CPU-side book-keeping for the allocator is not +reconstructed. However, to record a new child CUDA graph, we must restore this +book-keeping. This is what checkpoint pool state is used for. +""" + +from __future__ import annotations + +import contextlib +import dataclasses +import functools +import gc +import itertools +import logging +import operator +import sys +import threading +import traceback +import warnings +import weakref +from collections import defaultdict + +from enum import auto, Enum +from typing import ( + Any, + Callable, + Dict, + Iterator, + List, + Optional, + Sequence, + Set, + Tuple, + Union, +) + +import torch.fx +from torch import Tensor +from torch._dynamo.mutation_guard import GenerationTracker +from torch._dynamo.utils import preserve_rng_state +from torch._inductor.compile_fx import ( + align_inputs_from_check_idxs, + copy_misaligned_inputs, + get_expanded_dims, + get_input_idxs_to_check, + index_expanded_dims, + remove_unaligned_input_idxs, + static_input, +) +from torch.multiprocessing.reductions import StorageWeakRef +from torch.storage import UntypedStorage +from torch.types import _bool +from torch.utils import _pytree as pytree +from torch.utils.weak import TensorWeakRef + +StorageWeakRefPointer = int +StorageDataPtr = int +NBytes = int + +if torch.backends.cuda.is_built(): + from torch._C import ( + _cuda_CUDAAllocator_AllocatorState as AllocatorState, + _set_cached_tensors_enabled as _set_cached_tensors_enabled, + ) +else: + + class AllocatorState: # type: ignore[no-redef] + pass + + def _set_cached_tensors_enabled(enabled: _bool) -> None: + pass + + +log = logging.getLogger(__name__) + +from . import config + + +@dataclasses.dataclass(frozen=True) +class GraphID: + "Unique counter of a cuda graph recording" + id: int + + +@dataclasses.dataclass(frozen=True) +class FunctionID: + "Unique counter of a function wrapped in cudagraphify_impl" + id: int + + +@dataclasses.dataclass(frozen=True) +class WrappedFunction: + """ + Represents a function that you want to record for CUDA graph replay, + with a little more metadata so we can identify if we have an applicable + CUDA graph in our CUDA graph tree for it. + """ + + model: Callable[..., Any] + static_input_idxs: Sequence[int] + id: FunctionID + + +def clear_cublass_cache(): + """ + Cublas keeps a persistent workspace allocation for running matmuls. This poses a problem for + doing warmup within a CUDAGraph private pool because we do not want persistent allocations from + one one run to the next. When we begin a new run of a cudagraphs path (generation), all tensors + from the previous generation are freed. This frees them the the memory pool, but not elsewhere. + A tensor in the cublas workspace would continue to be in use the workspace but would also get allocated + in the next run. The memory would be in use in two places. + + To solve this, we clear cublas caches before and after warming up or recording. If a workspace is required + it will be allocated to the cudagraph private pool and accounted for in the allocator for the duration of the + program. There is no overhead to this on replay since cudagraphs removes allocation overhead. + """ + torch._C._cuda_clearCublasWorkspaces() + + +@contextlib.contextmanager +def clear_cublas_manager(): + "Context manager around clearing cublas caches that will clear on enter and exit" + clear_cublass_cache() + try: + yield + finally: + clear_cublass_cache() + + +@contextlib.contextmanager +def disable_conv_cache_emptying(): + prev = torch._C._cuda_get_conv_benchmark_empty_cache() + torch._C._cudnn_set_conv_benchmark_empty_cache(False) + try: + yield + finally: + torch._C._cudnn_set_conv_benchmark_empty_cache(prev) + + +@contextlib.contextmanager +def enable_history_recording(): + "Turns on history recording in the CUDA Caching Allocator" + enabled = torch._C._cuda_isHistoryEnabled() + try: + if not enabled: + torch.cuda.memory._record_memory_history() + yield + finally: + if not enabled: + torch.cuda.memory._record_memory_history(None) + + +def get_history_recording(): + # TODO - remove, prevents cleanup + if not config.triton.cudagraph_trees_history_recording: + return contextlib.nullcontext() + return enable_history_recording() + + +class TreeManagerContainer: + """ + Manages the lifetime of the tree manager. Like `PrivatePool` in cuda caching allocator, + the tree and its corresponding memory pool should be kept alive as long as any outstanding + graph or tensor which is an output of a graph remains alive. + + There is a single tree manager container per device. + + The lifecycle of a tree_manager is: + - Is constructed, no graph, no fns, no tensors + - Tree manager is fetched, resulting in tree manager being allocated + - We generate a bunch of functions, calling add_strong_reference + - These functions die, calling finalize_reference + - When all the functions die, we finalize_tree_manager. + + TODO: in the future, we would like to do the following once storage weak refs land + - We look for all the live storages and add references to THOSE + - We count as storages die + - All the storages are dead, we deallocate the tree manager + """ + + def __init__(self, device_index): + # This class keeps a strong reference to tree_manager, + # but upon all other strong references to the tree_manager will reset it to None. + # We need a strong reference so that we can still access its attributes upon cleanup. + self.tree_manager: Optional[CUDAGraphTreeManager] = None + + # Number of outstanding references to the current tree manager + self.live_cudagraphify_fns = 0 + + self.device_index = device_index + + # Following two objects are only set in the case that Tensor outputs outlive + # the cudagraphify_fns. Reference to the Graph is needed to keep the private pool from + # deallocation. + self.live_storages_count = 0 + self.graph: Optional[torch.cuda.CUDAGraph] = None + + self.lock = threading.Lock() + + def _finalize_tensor(self): + with self.lock: + self.live_storages_count -= 1 + if self.live_storages_count == 0: + self.graph = None + + # manager was used again after existing cleanup, + # we shouldnt set it to None + if self.live_cudagraphify_fns == 0: + self.tree_manager = None + + def finalize_cudagraphify_fn(self): + with self.lock: + self.live_cudagraphify_fns -= 1 + if self.live_cudagraphify_fns == 0: + self._finalize_tree_manager() + + def _finalize_tree_manager(self): + assert self.lock.locked() + self.tree_manager = None + + # TODO - when issue #91395 is landed, we can set a weakref on + # storages and trigger a deallocation when all outputs of the + # cudagraph are dead. + + # live_storages = list( + # tree_manager.live_cudagraph_pool_storages_in_curr_execution() + # ) + + # # Maintain reference to graph to keep tensors alive + # assert len(tree_manager.roots) > 0, "expected at least one use" + # root = next(tree_manager.get_roots()) + # self.graph = root.graph + # seen_storages = set() + # for stor in live_storages: + # if stor in seen_storages: + # continue + # seen_storages.add(stor) + # self.live_storages_count += 1 + # . weakref.finalize(stor, self._finalize_tensor) + + def add_strong_reference(self, fn: Callable[..., Any]): + with self.lock: + self.live_cudagraphify_fns += 1 + + weakref.finalize(fn, self.finalize_cudagraphify_fn) + + def get_tree_manager(self) -> CUDAGraphTreeManager: + with self.lock: + if self.tree_manager is None: + self.tree_manager = CUDAGraphTreeManager(self.device_index) + return self.tree_manager + + +local = threading.local() + +# one tree manager per device +local.tree_manager_containers = {} +local.tree_manager_locks = defaultdict(threading.Lock) + + +# only incremented by user call of mark_step_begin +class MarkStepBox: + mark_step_counter = 0 + + +# We need to register this as an object that will be copied over as TLS when new +# threads are created in autograd +torch._C._stash_obj_in_tls("tree_manager_containers", local.tree_manager_containers) +torch._C._stash_obj_in_tls("tree_manager_locks", local.tree_manager_locks) + + +def mark_step_begin(): + "Indicates that a new iteration of inference or training is about to begin." + + # iterate down to distinguish from GenerationTracking counter + MarkStepBox.mark_step_counter -= 1 + + +def reset_cudagraph_trees(): + "Clear all cudagraph trees" + # see shutdown below for why this is necessary + container_dict = get_obj(local, "tree_manager_containers") + locks_dict = get_obj(local, "tree_manager_locks") + for device, lock in locks_dict.items(): + with lock: + container = container_dict.get(device) + if not container or not container.tree_manager: + continue + + container.tree_manager.shutdown() + + _set_cached_tensors_enabled(False) + container_dict.clear() + + MarkStepBox.mark_step_counter = 0 + + +def get_obj(local, attr_name): + if hasattr(local, attr_name): + return getattr(local, attr_name) + else: + assert torch._C._is_key_in_tls(attr_name) + return torch._C._get_obj_in_tls(attr_name) + + +def get_container(device_index: int): + container_dict = get_obj(local, "tree_manager_containers") + lock = get_obj(local, "tree_manager_locks")[device_index] + + with lock: + if device_index not in container_dict: + container_dict[device_index] = TreeManagerContainer(device_index) + + return container_dict[device_index] + + +def get_manager( + device_index: int, create_if_none_exists=True +) -> Optional[CUDAGraphTreeManager]: + if create_if_none_exists: + return get_container(device_index).get_tree_manager() + return get_container(device_index).tree_manager + + +def cudagraphify_impl(model, inputs, static_input_idxs, *args, **kwargs): + fn_cache: Dict[Tuple[int, ...], Callable[..., Any]] = {} + + # Detect int inputs: we need to index on these + int_key = [i for i, v in enumerate(inputs) if isinstance(v, int)] + get_ints: Any = operator.itemgetter(*int_key) if int_key else lambda _: None + + del inputs + + def deferred_cudagraphify(inputs): + int_key = get_ints(inputs) + fn = fn_cache.get(int_key) + if fn is not None: + return fn(inputs) + + log.info("recording cudagraph tree for %s", int_key) + + # first get indices we need to check to align, then update our static inputs, + # and finally copy + check_input_idxs = get_input_idxs_to_check(inputs, static_input_idxs) + new_static_input_idxs = remove_unaligned_input_idxs(inputs, static_input_idxs) + copy_misaligned_inputs(inputs, check_input_idxs) + + fn, out = cudagraphify(model, inputs, new_static_input_idxs, *args, **kwargs) + fn = align_inputs_from_check_idxs(fn, inputs_to_check=check_input_idxs) + fn_cache[int_key] = fn + + return out + + return deferred_cudagraphify + + +def cudagraphify( + model, + inputs, + static_input_idxs=(), + *, + device_index: int, + is_backward: bool, + is_inference: bool, + stack_traces: Optional[StackTraces] = None, +): + manager = get_container(device_index).get_tree_manager() + assert not (is_backward and is_inference) + mode = ( + CompilationMode.BACKWARD + if is_backward + else (CompilationMode.INFERENCE if is_inference else CompilationMode.FORWARD) + ) + + return manager.add_function( + model, + inputs, + static_input_idxs, + stack_traces, + mode, + ) + + +class StorageWeakRefWrapper: + """ + Wrapper around a storage weak ref. Will deallocate it upon expiration if invoked. + """ + + __slots__ = ["ref", "_data_ptr", "extra_ref_check"] + + storage_ref: Optional[StorageWeakRef] + + def __init__( + self, + inp: Union[Tensor, UntypedStorage], + extra_ref_check: Optional[Callable[[], None]] = None, + ): + """ + extra_ref_check is an additional check we need to run to check if the + weak ref has expired. in checking storage use count we assume extra_ref_check + will hold an additional reference to the storage. + """ + if isinstance(inp, Tensor): + stor = inp.untyped_storage() + else: + assert isinstance(inp, UntypedStorage) + stor = inp + self.ref = StorageWeakRef(stor) + self._data_ptr = stor.data_ptr() + self.extra_ref_check = extra_ref_check + + @classmethod + def from_weakref_and_data_ptr(cls, cdata, data_ptr, extra_ref_check=None): + instance = cls.__new__(cls) + instance._data_ptr = data_ptr + instance.ref = StorageWeakRef.from_weakref(cdata) + instance.extra_ref_check = extra_ref_check + return instance + + def __call__(self) -> Optional[StorageWeakRefPointer]: + if self.expired(): + return None + + return self.ref.cdata + + def swap_weakref(self, cdata): + self.ref.__del__() + self.ref.cdata = cdata + + def data_ptr(self) -> int: + "NB: returns the data ptr even if the storage has expired" + return self._data_ptr + + def remove_extra_reference(self): + self.extra_ref_check = None + + def expired(self): + if self.extra_ref_check is not None and not self.extra_ref_check(): + return False + + # if extra_ref_check is not None we expect an additional reference + stor_count = torch._C._storage_Use_Count(self.ref.cdata) + return (stor_count - (self.extra_ref_check is not None)) == 0 + + def __repr__(self): + if self.ref is None or self.ref.expired(): + return f"StorageWeakRefWrapper to {self.data_ptr()}; dead" + else: + return f"StorageWeakRefWrapper to {self.data_ptr()}; alive" + + +def is_live(weak_ref: Optional[StorageWeakRefWrapper]) -> bool: + return maybe_deref(weak_ref) is not None + + +def maybe_deref( + weak_ref: Optional[StorageWeakRefWrapper], +) -> Optional[Tuple[UntypedStorage, int]]: + if weak_ref is None: + return None + r = weak_ref() + if r is None: + return None + # NB: r.data_ptr() does not necessarily equal weak_ref.data_ptr() + return r, weak_ref.data_ptr() + + +@contextlib.contextmanager +def _use_cuda_memory_pool_manager(device, mem_pool, stream): + """ + Context manager to use cuda graph pool for new allocations. If you use this manager + all cudagraph tensors in use should be reflected in the allocator or they will be overwritten. + existing_graph should already have been used in a capture, and the mem_pool must already exist, + because this manager will not preserve a reference to the pool which keeps it alive. + """ + torch.cuda.synchronize() + stream.wait_stream(torch.cuda.current_stream()) + + with torch.cuda.stream(stream), torch.device(device): + torch._C._cuda_beginAllocateCurrentStreamToPool(device, mem_pool) + try: + yield + finally: + torch._C._cuda_endAllocateCurrentStreamToPool(device) + torch._C._cuda_releasePool(device, mem_pool) + + +def map_to_ref(t: Optional[Tensor]) -> Optional[StorageWeakRefWrapper]: + if not isinstance(t, torch.Tensor): + assert t is None + return None + return StorageWeakRefWrapper(t) + + +# A path index of (depth, offset) indices into a graph that is `depth`` number of nodes from the root +# at graph output offset +PathOutputIndex = Tuple[int, int] + +# For each node in the path, for each output, is the output alive +PathLiveness = List[List[bool]] + +StackTraces = List[Optional[str]] + + +class CUDAWarmupNode: + """ + Simplified Wrapper around A CUDA Model that wraps outputs in storage refs and exposes + apis to get the live storages in the current chain of warmup. + + A CUDAWarmupNode may have either CUDAGraphNode or CUDAWarmupNode as a parent, but may only have + CUDAWarmupNode as children, because we cannot record or execute with tensors which do not have stable + memory addresses. + + CUDAWarmupNode and CUDAGraphNode have a number of differences that make it easier to use separate classes. + - Much of the CUDAGraphNode logic & initialization is based on the tensor properties of first recording. In the + first instance of warmup, these are not finalized yet. + - All Inputs to the RecordedFunction must be copied over to the cuda graph memory pool, this is unnecessary in warmup. + - CUDAWarmup is only used once and so does not need to optimize as much bookkeeping. It is much simpler. + + NB: this class and CUDAGraphNode need to expose `path_live_weakrefs`, `all_outputs_are_dead`, and + `self.outputs_weakrefs`, `stack_traces`, and `tensor_weakrefs` for compatibility. + """ + + def __init__( + self, + wrapped_function: WrappedFunction, + parent, + cuda_graphs_pool: Tuple[int, int], + existing_cuda_graph: torch.cuda.Graph, + device_index: int, + stack_traces: Optional[StackTraces], + stream: torch.cuda.Stream, + already_warm: bool, + ): + self.wrapped_function = wrapped_function + self.parent = parent + self.cuda_graphs_pool = cuda_graphs_pool + self.outputs_weakrefs: List[Optional[StorageWeakRefWrapper]] = [] + self.tensor_weakrefs: List[Optional[TensorWeakRef]] = [] + self.existing_cuda_graph = existing_cuda_graph + self.has_run = False + self.device_index = device_index + self.stack_traces = stack_traces + self.stream = stream + self.already_warm = already_warm + + def run(self, new_inputs): + assert not self.has_run, "Wrapped function should never be run twice" + + # See: output_is_alias_of_persistent_static_inputs below. We should only be returning freshly created + # storages in path_live_weakrefs. + existing_path_data_ptrs = { + t.data_ptr() for t in self.path_live_weakrefs() if t() + } + non_cudagraph_inps = set() + for i in range(len(new_inputs)): + if ( + isinstance(new_inputs[i], torch.Tensor) + and new_inputs[i].untyped_storage().data_ptr() + not in existing_path_data_ptrs + ): + non_cudagraph_inps.add(new_inputs[i].untyped_storage().data_ptr()) + + if config.triton.slow_path_cudagraph_asserts and not self.already_warm: + refs = list(self.path_live_weakrefs()) + check_memory_pool(self.device_index, self.cuda_graphs_pool, refs) + + with torch.cuda.device( + self.device_index + ), disable_conv_cache_emptying(), clear_cublas_manager(), _use_cuda_memory_pool_manager( + self.device_index, self.cuda_graphs_pool, self.stream + ), get_history_recording(): + out = self.wrapped_function.model(new_inputs) + + # sync up stream used in `_use_cuda_memory_pool_manager` - TODO - wait stream instead ? + torch.cuda.synchronize() + + assert len(new_inputs) == 0 + + # sdpa returns cpu tensors when not recording cuda graph + def add_ref(o): + return ( + o is not None + and isinstance(o, torch.Tensor) + and o.is_cuda + and o.untyped_storage().data_ptr() not in non_cudagraph_inps + and o.untyped_storage().data_ptr() != 0 + ) + + self.outputs_weakrefs.extend( + [map_to_ref(o) if add_ref(o) else None for o in out] + ) + self.tensor_weakrefs.extend( + [TensorWeakRef(o) if add_ref(o) else None for o in out] + ) + + if config.triton.slow_path_cudagraph_asserts and not self.already_warm: + out_refs = self.path_live_weakrefs() + new_storages = [ + t for t in out_refs if t.data_ptr() not in non_cudagraph_inps + ] + check_memory_pool(self.device_index, self.cuda_graphs_pool, new_storages) + + return out + + @property + def _path_from_root(self): + nodes = [] + node = self + while node: + nodes.append(node) + node = node.parent + + yield from reversed(nodes) + + def path_live_weakrefs(self) -> Iterator[StorageWeakRefWrapper]: + "Returns all live storages weakrefs that created by nodes in this path" + for node in self._path_from_root: + for output in node.outputs_weakrefs: + if is_live(output): + yield output + + def all_outputs_are_dead(self): + return not list(self.path_live_weakrefs()) + + +# Aliases for List that say what the indices denote +InputList = List # input indexes +OutputList = List # output indexes +LevelList = List # levels (distance from root of tree) + + +class OutputAliasInfo: + pass + + +class _UnaliasedStorage(OutputAliasInfo): + "Singleton to mark that the graph output constructs a new alias or is None" + pass + + +UnaliasedStorage = _UnaliasedStorage() + + +class AliasesPriorGraphOutput(OutputAliasInfo): + "Marks that the graph output aliases an output of a prior graph" + __slots__ = ["index"] + + index: PathOutputIndex + + def __init__(self, index: PathOutputIndex): + assert isinstance(index, tuple) + self.index = index + + +class AliasesNewOutput(OutputAliasInfo): + "Marks that the graph output aliases an index in the new, returned outputs" + + __slots__ = ["index"] + + index: int + + def __init__(self, index): + assert isinstance(index, int) + self.index = index + + +class CUDAGraphNode: + """ + A single recording of a function into a CUDA Graph. Recordings of CUDA Graphs share a single memory pool + and are structured into a tree, where there is a single recording that can precede it (parent) and multiple + subsequent recordings that may follow (children). A node will have no parent if it is the first recording + in a tree; i.e., when it is first recorded, there are no live tensors from a previous recording which + would force a dependency. + + On first recording, all of the live tensors in the current CUDA Graph Node path will be + reflected in the corresponding private pool. On subsequent executions, the caching allocator + is unaffected when the graph is replayed. + + In order to support recording a subsequent cuda graph recording after execution of this graph, + we checkpoint the state of the memory pool so that it may later be resumed. + + WrappedFunction should have already been warmed up prior to invocation. + + See [setCheckpointPoolState] for further explanation, as well as + https://user-images.githubusercontent.com/13564/222815509-374f3400-f83d-4f7d-8fa6-4a092b3250bb.png + """ + + def __init__( + self, + wrapped_function: WrappedFunction, + id: GraphID, + parent: Optional[CUDAGraphNode], + inputs: List[Tensor], + cuda_graphs_pool: Tuple[int, int], + device_index: int, + stack_traces: Optional[StackTraces], + stream: torch.cuda.Stream, + ): + assert isinstance(inputs, (list, tuple)) + + self.wrapped_function = wrapped_function + self.id = id + self.device = device_index + self.stack_traces = stack_traces + self.stream = stream + + # if this is a root parent will be None. use weakref to prevent reference cycle + self._parent = weakref.ref(parent) if parent is not None else None + # reference to the shared memory pool for the entire cuda graphs tree + self.cuda_graphs_pool = cuda_graphs_pool + + # A single wrapped function may be recorded multiple times if memory patterns or + # invariants change from one execution to the next + self.children: Dict[FunctionID, List[CUDAGraphNode]] = defaultdict(list) + + # StorageWeakRef maintains whether the Storage C++ object remains allocated, + # not whether the corresponding memory has been deallocated. In order + # to use them to track memory deallocations we must maintain a single StorageWeakRef + # for all Storages that reference that memory (even if we are constructing Storages + # that do not have a deallocator function). We maintain one single storage_cache + # as we execute any tree path. When we retrieve a storage from the cache we + # check that it is still alive, and we hash based on observed recording data ptr + # and storage cdata. + + # we preserve a single reference to executed outputs that is then referenced + # in children to avoid children having to chase parent pointers in the hot path + # DO NOT reassign output_weakrefs, only call `clear()` + # Path is a series of nodes from root to the current node + self.outputs_weakrefs: OutputList[Optional[StorageWeakRefWrapper]] = [] + self.path_weakrefs: LevelList[OutputList[Optional[StorageWeakRefWrapper]]] = [ + node.outputs_weakrefs for node in self._path_from_root + ] + self.path_stacktraces: LevelList[StackTraces] = [ + node.stack_traces for node in self._path_from_root + ] + self.tensor_weakrefs: OutputList[Optional[TensorWeakRef]] = [] + + # tensors which are outputs of previous graphs in the tree + self.cudagraph_managed_idxs: List[int] = [ + idx + for idx, t in enumerate(inputs) + if isinstance(t, torch.Tensor) and self._is_cuda_graph_recorded_tensor(t) + ] + + self.static_input_idxs: List[int] = list( + set(wrapped_function.static_input_idxs) | set(self.cudagraph_managed_idxs) + ) + + self.static_input_data_ptrs: InputList[int] = [ + ( + inputs[i].data_ptr() + if isinstance(inputs[i], torch.Tensor) and i in self.static_input_idxs + else None + ) + for i in range(len(inputs)) + ] + + # When we checkpoint, and free generations, we will be manually freeing the outputs + # of CUDAGraphNodes. We should not be freeing parameters, not do we need to account for + # their liveness (they are static), so we need to compute which outputs are aliases of + # parameters. Some static inputs are saved tensors from the forward that die in the backward. + # Their locations are static but lifetimes are not. We only include the persistent static + # data ptrs below because the non persistent data ptrs may be outputs of this record and + # fresh allocations. + + # precompute expanded dims to avoid computing in the hot path + self.expanded_dims: List[List[int]] = [ + get_expanded_dims(x) + if isinstance(x, torch.Tensor) and idx not in self.static_input_idxs + else [] + for idx, x in enumerate(inputs) + ] + + # For each node in path, which outputs were observed to be live + # before invoking graph recording, and after graph recording + self.recorded_liveness_before_graph: LevelList[OutputList[bool]] = [] + self.recorded_liveness_after_graph: LevelList[OutputList[bool]] = [] + + # List of Tuples of (depth, output_index) that index into node at depth + # number of nodes from root and output_index of outputs. Will index into + # path_weakrefs. + self.expected_dead_indices_before_graph: List[PathOutputIndex] = [] + self.expected_dead_indices_after_graph: List[PathOutputIndex] = [] + + # all live indices after graph recording + self.live_indices_after_graph: List[PathOutputIndex] = [] + + if self.parent is not None: + previous_liveness = self.parent.recorded_liveness_after_graph + curr_liveness = self._get_liveness(self.path_weakrefs) + + different_indices = self._get_different_indices( + previous_liveness, curr_liveness + ) + + self.recorded_liveness_before_graph = curr_liveness + self.expected_dead_indices_before_graph = different_indices + + recording_inputs = self._allocate_and_copy_recording_inputs(inputs) + # recording inputs will copy over memory, so we can free non recording inputs + inputs.clear() + del inputs + + # graph used for recording model invocation + self.graph = torch.cuda.CUDAGraph() + + # we allocate non-static inputs within the same memory pool as the CUDAGraph + # which we will record the model with. For memory efficiency, it is important + # to reclaim the input memory when the inputs are no longer live. To accomplish this, + # we reconstruct tensors at the correct data pointers of our inputs which are + # non owning and do not prevent deallocation. On subsequent executions, input values + # will be copied over to these tensors. + self.reconstructed_inputs: InputList[Tensor] = [ + self._reconstruct_from_tensor_metadata(self._tensor_metadata(x)) + if isinstance(x, torch.Tensor) + else x + for x in recording_inputs + ] + + # DO THE RECORDING!!! + # We record the CUDA graph in the constructor of CUDAGraphNode, which + # gives you what the CPU side compute of the function would do. We + # don't throw the recording outputs away: their memory is + # correctly accounted for in the CUDAGraphs caching allocator. This + # means on the very FIRST run of the CUDA graph node, we can directly + # do more recording, because we have a valid caching allocator state. + # NB: This relies on run() being called immediately after the + # constructor, otherwise this optimization would not be valid. + + # initialized below in _record + + self.checkpointed_caching_state: Optional[AllocatorState] = None + + # Output Storage Alias information, can be: + # - A new, unaliased storage, or the output is None + # - An alias of an output of a prior graph + # - An alias of an output already created in the reconstructed outputs + # This is None if the output in question is an int + self.output_storage_alias: OutputList[Optional[OutputAliasInfo]] = [] + + # is the output Storage unaliased in subsequent outputs, of all subsequent paths + # if it is, we cached the output tensor and adjust storage liveness tracking to also + # check if the output tensor does not have an additional python reference. + # If a descendent node discovers it has an alias of a prior output, then the output + # will no longer be cached in the ancestor. + # The large majority of tensors are unaliased, and preserving aliased output tensors would add + # significant additional complexity with marginal gains + # The cached tensor outputs are added on the first execution, and cleared whenever we need + # to do subsequent recording + self.unaliased_in_all_paths: OutputList[bool] = [] + self.cached_tensor_outputs: OutputList[Optional[Tensor]] = [] + + # if an output aliases a static, persistent input then the corresponding Tensor will + # be set here. These are different than cached tensors, because they are tensors that + # are aliases of parameters that are always live. + self.static_output_tensors: OutputList[Optional[Tensor]] = [] + + # Cleared after recording + self.recording_outputs: Optional[ + OutputList[Union[torch.Tensor, int]] + ] = self._record(wrapped_function.model, recording_inputs) + self.outputs_metadata: OutputList[Union[Dict[str, Any], int, None]] = [] + + # As with inputs, we do not want to keep the outputs permanently alive because that would prevent + # their memory being reclaimed in subsequent cuda graph recordings. We record the tensor metadata + # needed to reconstruct instead. + assert self.recording_outputs is not None + for out in self.recording_outputs: + if isinstance(out, torch.Tensor): + self.outputs_metadata.append( + self._tensor_metadata(out, ignore_storage_offset=False) + ) + else: + assert isinstance(out, (int, type(None))), type(out) + self.outputs_metadata.append(out) + + self.graph.replay() + + def _copy_input(self, idx, dst, src): + expanded_dims = self.expanded_dims[idx] + dst = index_expanded_dims(dst, expanded_dims) + src = index_expanded_dims(src, expanded_dims) + # TODO - one jit kernel across multiple inputs + dst.copy_(src) + + def run_first_inputs(self, new_inputs): + if config.triton.fast_path_cudagraph_asserts: + self.debug_check_invariants_before_invocation() + + # graph is already invoked in the __init__ + # inputs are copied over in _allocate_recording_inputs and subsequently cleared + assert len(new_inputs) == 0 + outputs = self.recording_outputs + self.recording_outputs = None + return outputs + + def run(self, new_inputs): + if config.triton.fast_path_cudagraph_asserts: + self.debug_check_invariants_before_invocation() + + assert len(self.static_input_data_ptrs) == len(new_inputs) + # NB: this ranges over non-static inputs too + for idx, data_ptr in enumerate(self.static_input_data_ptrs): + if idx in self.cudagraph_managed_idxs: + continue + if not isinstance(new_inputs[idx], torch.Tensor): + pass + elif data_ptr is not None: + # static input, e.g., parameter + assert data_ptr == new_inputs[idx].data_ptr() + else: + # non-static input, need to copy it into CUDA graph + dst = self.reconstructed_inputs[idx] + src = new_inputs[idx] + self._copy_input(idx, dst, src) + + new_inputs.clear() + self.run_graph() + + outputs = self.reconstruct_outputs() + self.debug_check_invariants_after_invocation() + + return outputs + + def reconstruct_outputs(self): + "Reconstruct output tensors according to their saved metadata and alias information" + + # Cached tensors will not yet be set on the first execution + # They are also cleared in checkpointing, so if we checkpoint this node + # and then execute it again we will need to repopulate cached tensors + if not self.cached_tensor_outputs: + self._initialize_cached_tensors() + + outputs: List[torch.Tensor] = [] + + for i, (storage_info, metadata) in enumerate( + zip(self.output_storage_alias, self.outputs_metadata) + ): + if not isinstance(metadata, dict): # tensor metadata + assert isinstance(metadata, (int, type(None))) + outputs.append(metadata) + continue + + cached_t = self.cached_tensor_outputs[i] + if cached_t is not None: + # No need to update weakrefs, already correctly initialized + outputs.append(cached_t) + continue + + static_t = self.static_output_tensors[i] + if static_t is not None: + assert self.outputs_weakrefs[i] is None + outputs.append(static_t) + continue + + storage = self.prepare_alias_info_for_tensor_construction( + storage_info, metadata + ) + + if isinstance(storage, UntypedStorage) or storage is None: + out = self._reconstruct_from_tensor_metadata(metadata, storage) + else: + assert isinstance(storage, int) + out = self._reconstruct_from_tensor_metadata( + metadata, outputs[storage].untyped_storage() + ) + + outputs.append(out) + w = self.outputs_weakrefs[i] + assert w is not None + w.swap_weakref(out.untyped_storage()._weak_ref()) + + return outputs + + def prepare_alias_info_for_tensor_construction( + self, + out_alias_info: Optional[OutputAliasInfo], + metadata: Union[Dict[str, Any], int, None], + ) -> Union[UntypedStorage, None, int]: + if ( + isinstance(metadata, (int, type(None))) + or out_alias_info is UnaliasedStorage + ): + return None + + if isinstance(out_alias_info, AliasesPriorGraphOutput): + depth, existing_output_index = out_alias_info.index + ref = self.path_weakrefs[depth][existing_output_index] + assert ref is not None + return torch.UntypedStorage._new_with_weak_ptr(ref()) + + assert isinstance(out_alias_info, AliasesNewOutput) + return out_alias_info.index + + def prepare_storages_for_construction( + self, + ) -> List[Union[UntypedStorage, None, int]]: + output_storages = [] + for output_storage_alias, metadata in zip( + self.output_storage_alias, self.outputs_metadata + ): + output_storages.append( + self.prepare_alias_info_for_tensor_construction( + output_storage_alias, metadata + ) + ) + + return output_storages + + def run_graph(self): + self.graph.replay() + + def all_outputs_are_dead(self): + "All outputs of the path from this node to its root are dead" + for depth, output_index in self.live_indices_after_graph: + if is_live(self.path_weakrefs[depth][output_index]): + return False + return True + + def _record(self, model, inputs): + "Record the model" + + # see: output_is_alias_of_persistent_static_inputs above + static_input_persistent_storage_ptrs: Dict[int, StorageWeakRefWrapper] = { + inputs[i].untyped_storage().data_ptr(): StorageWeakRefWrapper(inputs[i]) + for i in self.wrapped_function.static_input_idxs + if isinstance(inputs[i], torch.Tensor) + and not self._is_cuda_graph_recorded_tensor(inputs[i]) + } + + if config.triton.slow_path_cudagraph_asserts: + # need to use parent live weakrefs because live_indices isnt set yet + memory = ( + [] if self.parent is None else list(self.parent.path_live_weakrefs()) + ) + memory += [ + StorageWeakRefWrapper(elem) + for i, elem in enumerate(inputs) + if isinstance(elem, torch.Tensor) + and i not in self.wrapped_function.static_input_idxs + and elem.data_ptr() != 0 + ] + check_memory_pool(self.device, self.cuda_graphs_pool, memory) + + with preserve_rng_state(), torch.cuda.device( + self.device + ), clear_cublas_manager(), torch.cuda.graph( + self.graph, + stream=self.stream, + pool=self.cuda_graphs_pool, + capture_error_mode="thread_local", + ), get_history_recording(): + static_outputs = model(inputs) + + # running model should reclaim memory + assert len(inputs) == 0 + + if not isinstance(static_outputs, (list, tuple)): + static_outputs = (static_outputs,) + + self._add_first_outputs(static_outputs, static_input_persistent_storage_ptrs) + + return static_outputs + + def _add_first_outputs( + self, + outputs, + static_input_persistent_storage_ptrs: Dict[int, StorageWeakRefWrapper], + ): + "Add the outputs from the first invocation of the node and set up metadata" + + # getting liveness before we have added the outputs to path, so the length + # of the two lists is equal + prev_liveness = self.recorded_liveness_before_graph + curr_liveness = self._get_liveness(self.path_weakrefs) + + delta = self._get_different_indices(prev_liveness, curr_liveness) + self.expected_dead_indices_after_graph = delta + + assert len(self.outputs_weakrefs) == 0 + # index from data pointer to index in outputs + output_new_storages_index: Dict[StorageDataPtr, int] = {} + + self.unaliased_in_all_paths = [False for _ in range(len(outputs))] + self.static_output_tensors = [None for _ in range(len(outputs))] + + for i, o in enumerate(outputs): + if o is None or not isinstance(o, torch.Tensor): + self.output_storage_alias.append(UnaliasedStorage) + continue + + torch._check( + o.is_cuda, + lambda: ( + "Expected all cuda outputs in cuda graph recording. Non cuda output " + f"from {self.stack_traces[i] if self.stack_traces else '(unknown)'}" + ), + ), + + ref = static_input_persistent_storage_ptrs.get( + o.untyped_storage().data_ptr(), None + ) + # also treat empty storages as static outputs because we do not need to manage their lifetime + # and they should not participate in checkpointing + is_empty_storage = o.data_ptr() == 0 + if ref and ref() is not None or is_empty_storage: + self.output_storage_alias.append(None) + self.static_output_tensors[i] = o + continue + + path_ref = self._is_alias_of_live_recorded_tensor(o) + if path_ref is not None: + self._mark_prior_graph_output_as_aliased(path_ref) + self.output_storage_alias.append(AliasesPriorGraphOutput(path_ref)) + continue + + if o.untyped_storage().data_ptr() in output_new_storages_index: + index = output_new_storages_index[o.untyped_storage().data_ptr()] + self.unaliased_in_all_paths[index] = False + self.output_storage_alias.append(AliasesNewOutput(index)) + continue + + output_new_storages_index[o.untyped_storage().data_ptr()] = i + self.output_storage_alias.append(UnaliasedStorage) + self.unaliased_in_all_paths[i] = True + + if self.stack_traces is None: + self.stack_traces = [None for _ in range(len(outputs))] + else: + assert len(self.stack_traces) == len( + outputs + ), "Wrong number of stack traces passed in" + + assert not self.outputs_weakrefs + for out, static_output_tensor in zip(outputs, self.static_output_tensors): + if not isinstance(out, torch.Tensor) or static_output_tensor is not None: + self.outputs_weakrefs.append(None) + self.tensor_weakrefs.append(None) + else: + self.outputs_weakrefs.append(StorageWeakRefWrapper(out)) + self.tensor_weakrefs.append(TensorWeakRef(out)) + + self.recorded_liveness_after_graph = self._get_liveness(self.path_weakrefs) + self.checkpointed_caching_state = torch._C._cuda_getCheckpointState( + self.device, self.cuda_graphs_pool + ) + + # now, get liveness with outputs added + for depth in range(len(self.path_weakrefs)): + for output_index in range(len(self.path_weakrefs[depth])): + if is_live(self.path_weakrefs[depth][output_index]): + self.live_indices_after_graph.append((depth, output_index)) + + self.debug_check_invariants_after_invocation() + if config.triton.slow_path_cudagraph_asserts: + check_memory_pool( + self.device, self.cuda_graphs_pool, list(self.path_live_weakrefs()) + ) + + def _mark_prior_graph_output_as_aliased(self, index: PathOutputIndex): + "Remove a graph output from the unaliased, cached tensors in an ancestor node" + depth, output_index = index + node = list(self._path_from_root)[depth] + node.unaliased_in_all_paths[output_index] = False + x = self.path_weakrefs[depth][output_index] + assert x is not None + x.remove_extra_reference() + + def _initialize_cached_tensors(self): + # we should not be clearing output_weakrefs, and they should be set in the first + # record run + assert len(self.outputs_weakrefs) == len(self.outputs_metadata) + + for i, (storage_info, metadata, make_cached) in enumerate( + zip( + self.output_storage_alias, + self.outputs_metadata, + self.unaliased_in_all_paths, + ) + ): + if not make_cached: + self.cached_tensor_outputs.append(None) + continue + + assert storage_info is UnaliasedStorage + assert isinstance(metadata, dict) + s = self.create_storage(metadata) + out = self._reconstruct_from_tensor_metadata(metadata, storage=s) + + # XXX: let autograd know that there will be an additional reference to the tensor + # that can be ignored when deciding whether to do gradient buffer inplacing. + # Otherwise, inplacing could differ between tracing and subsequent execution. + # For some models we tested this led to inputs no longer being in cudagraph pools, + # leading to spurious re-recordings. + # It also tells AMP cache that even though the tensor impls cannot be cached + # in dtype conversions. + + torch._C._add_cached_tensor(out) + + self_ref = weakref.ref(self) + + # one reference in our array, and calling sys.getrefcount bumps the refcount by one + def check_refcount(i): + self_loc = self_ref() + if self_loc is None: + return False + return self_loc.get_output_refcount(i) == 2 + + check = functools.partial(check_refcount, i=i) + + self.outputs_weakrefs[i] = StorageWeakRefWrapper(out, extra_ref_check=check) + self.cached_tensor_outputs.append(out) + + def get_output_refcount(self, index): + return sys.getrefcount(self.cached_tensor_outputs[index]) + + @property + def parent(self): + "unwraps the weakref to _parent" + return self._parent() if self._parent is not None else None + + @property + def _path_to_root(self): + "Returns all nodes in the path starting at self and ending at root" + node = self + while node: + yield node + node = node.parent + + @property + def _path_from_root(self): + "Returns all nodes in the path starting at the root and ending at self" + nodes = reversed(list(self._path_to_root)) + yield from nodes + + def _is_cuda_graph_recorded_tensor(self, t: torch.Tensor): + "Is this tensor an output of a node in this path" + for output_refs in self.path_weakrefs: + for storage_weak_ref in output_refs: + if storage_weak_ref is None: + continue + # don't need to check liveness of storage since the cuda graph managed + # memory is never released. + data_ptr = storage_weak_ref.data_ptr() + if t.untyped_storage().data_ptr() == data_ptr: + return True + + return False + + def _is_alias_of_live_recorded_tensor( + self, t: torch.Tensor + ) -> Optional[PathOutputIndex]: + for depth, output_refs in enumerate(self.path_weakrefs): + for output_index, storage_ref in enumerate(output_refs): + if (storage_and_ptr := maybe_deref(storage_ref)) is not None: + storage, ptr = storage_and_ptr + if ptr == t.untyped_storage().data_ptr(): + return (depth, output_index) + + return None + + @staticmethod + def _check_liveness( + indices: List[PathOutputIndex], + output_refs: List[List[Optional[StorageWeakRefWrapper]]], + ): + "Check that all of the indices specified are dead references" + for depth, output_index in indices: + w = output_refs[depth][output_index] + assert w is not None + if w() is not None: + return False + return True + + def add_child(self, function_id: FunctionID, node: CUDAGraphNode): + "Adds node as a a child of self" + self.children[function_id].append(node) + + @staticmethod + def _get_different_indices( + prev: List[List[bool]], curr: List[List[bool]] + ) -> List[PathOutputIndex]: + "Find indices where the two lists differ." + dead_indices = [] + assert len(prev) <= len(curr) + for i, (outputs1, outputs2) in enumerate(zip(prev, curr)): + assert len(outputs1) == len(outputs2) + for j, (output1, output2) in enumerate(zip(outputs1, outputs2)): + if output1 != output2: + dead_indices.append((i, j)) + + return dead_indices + + @staticmethod + def _get_liveness( + weakrefs: List[List[Optional[StorageWeakRefWrapper]]], + ) -> List[List[bool]]: + "Maps weakrefs to true if the reference is alive and false otherwise" + if len(weakrefs) == 0: + return [] + + return [pytree.tree_map(is_live, outputs) for outputs in weakrefs] + + def debug_assert_invariants( + self, expected_liveness: List[List[bool]], newly_dead: List[PathOutputIndex] + ): + if not config.triton.fast_path_cudagraph_asserts: + return + + for i, node in enumerate(self._path_from_root): + assert self.path_weakrefs[i] is node.outputs_weakrefs + + nodes = list(self._path_from_root) + + live_blocks = get_block_addrs(self.cuda_graphs_pool) + + live_storage_data_ptrs = set() + live_storage_weak_ptrs = set() + + for depth, outputs_liveness in enumerate(expected_liveness): + for output_idx, output_liveness in enumerate(outputs_liveness): + # tensor can die early, but it can't be alive when it should be dead + w = self.path_weakrefs[depth][output_idx] + if (stor_weak_ptr_and_data_ptr := maybe_deref(w)) is not None: + assert output_liveness + stor_weak_ptr, stor_data_ptr = stor_weak_ptr_and_data_ptr + assert (stor_data_ptr in live_storage_data_ptrs) == ( + stor_weak_ptr in live_storage_weak_ptrs + ) + live_storage_data_ptrs.add(stor_data_ptr) + live_storage_weak_ptrs.add(stor_weak_ptr) + + is_persistent_alias = ( + nodes[depth].static_output_tensors[output_idx] is not None + ) + + if is_persistent_alias: + assert stor_data_ptr not in live_blocks + + for depth, output_index in newly_dead: + assert not is_live(self.path_weakrefs[depth][output_index]) + + def debug_check_invariants_before_invocation(self): + self.debug_assert_invariants( + self.recorded_liveness_before_graph, self.expected_dead_indices_before_graph + ) + + def debug_check_invariants_after_invocation(self): + self.debug_assert_invariants( + self.recorded_liveness_before_graph, self.expected_dead_indices_after_graph + ) + + def data_ptrs_dead_since_invocation(self) -> List[int]: + """ + Since this node was invoked, return data ptrs of all tensor outputs that have died + in the current executing tree path. + """ + curr_liveness = self._get_liveness(self.path_weakrefs) + _get_different_indices = self._get_different_indices( + self.recorded_liveness_after_graph, curr_liveness + ) + + path = list(self._path_from_root) + ptrs_to_deallocate = [] + for depth, output_index in _get_different_indices: + ptrs_to_deallocate.append( + path[depth].outputs_metadata[output_index]["data_ptr"] + ) + + return ptrs_to_deallocate + + def path_live_weakrefs(self) -> Iterator[StorageWeakRefWrapper]: + for i, j in self.live_indices_after_graph: + out = self.path_weakrefs[i][j] + if out is not None and is_live(out): + yield out + + def remove_node_cached_tensors(self): + for t in self.cached_tensor_outputs: + if t is not None: + torch._C._remove_cached_tensor(t) + self.cached_tensor_outputs.clear() + + for i, unaliased in enumerate(self.unaliased_in_all_paths): + if unaliased: + n = self.outputs_weakrefs[i] + assert n is not None + n.remove_extra_reference() + + def remove_path_cached_tensors(self): + for node in self._path_from_root: + node.remove_node_cached_tensors() + + def clear_path_state(self): + "Clear the path state in this current executing node" + # this doesnt actually do anything right now, leaving it as placeholder + pass + + @staticmethod + def _tensor_metadata(x, ignore_storage_offset=True): + assert isinstance(x, torch.Tensor) + # We ignore the storage offset for inputs, but not for outputs + # TODO: - should we make the storage resizable ? + return { + "nbytes": x.untyped_storage().nbytes(), + "data_ptr": x.untyped_storage().data_ptr(), + "size": x.shape, + "stride": x.stride(), + "dtype": x.dtype, + "device": x.device, + "storage_offset": x.storage_offset() if not ignore_storage_offset else 0, + } + + def _reconstruct_from_tensor_metadata( + self, metadata: Dict[str, Any], storage=None + ) -> Tensor: + s = self.create_storage(metadata) if storage is None else storage + return torch._C._construct_CUDA_Tensor_From_Storage_And_Metadata(metadata, s) + + def create_storage(self, metadata): + return torch._C._construct_storage_from_data_pointer( + metadata["data_ptr"], metadata["device"], metadata["nbytes"] + ) + + def _allocate_and_copy_recording_inputs( + self, inputs + ) -> List[Union[torch.Tensor, int]]: + """ + Allocate inputs for non static, non cudagraph managraphed managed tensors in the memory pool + and copy over the tensor values. + """ + + torch.cuda.synchronize() + self.stream.wait_stream(torch.cuda.current_stream()) + recording_inputs = [] + + with warnings.catch_warnings(record=True), torch.cuda.device( + self.device + ), _use_cuda_memory_pool_manager( + self.device, + mem_pool=self.cuda_graphs_pool, + stream=self.stream, + ): + for i, inp in enumerate(inputs): + if not isinstance(inp, torch.Tensor): + assert isinstance(inp, int) + recording_inputs.append(inp) + elif i not in self.static_input_idxs: + # static_input does an allocation! + recording_inputs.append(static_input(inp)) + # copy over and clear non recording input + self._copy_input(i, recording_inputs[-1], inp) + inputs[i] = None + del inp + else: + recording_inputs.append(inp) + + return recording_inputs + + def check_invariants(self, inputs: List[Tensor]) -> bool: + """ + Checks if this node can be run. The same pattern of tensor liveness and tensors + managed in the cudagraph private pool must remain stable. + """ + + # previously managed data pointers remain stable + for idx in self.cudagraph_managed_idxs: + if inputs[idx].data_ptr() != self.static_input_data_ptrs[idx]: + return False + + if not self._check_liveness( + self.expected_dead_indices_before_graph, self.path_weakrefs + ): + return False + + # the cudagraph managed tensors which died upon recording must also die upon + # this invocation. it is too late to check after we've replayed the graph, + # because we would have already written over their memory. + for idx in self.cudagraph_managed_idxs: + inputs[idx] = None + + torch._check( + self._check_liveness( + self.expected_dead_indices_after_graph, self.path_weakrefs + ), + lambda: "TODO: graph recording observed an input tensor deallocate during graph " + " recording that did not occur during replay. Please file an issue.", + ) + return True + + def num_descendants(self) -> int: + "Total number of descendents of this node" + num_desc = 0 + for children in self.children.values(): + for child in children: + num_desc += 1 + num_desc += child.num_descendants() + return num_desc + + +def get_cudagraph_segments(pool_id): + segments = torch.cuda.memory_snapshot() + return [segment for segment in segments if segment["segment_pool_id"] == pool_id] + + +def get_block_addrs(pool_id, live_only=True): + blocks = [] + + for segment in get_cudagraph_segments(pool_id): + addr = segment["address"] + for block in segment["blocks"]: + if block["state"] == "active_allocated" or not live_only: + blocks.append(addr) + + addr += block["size"] + + return blocks + + +def format_tb(frames): + formatted_traceback = [] + + for entry in frames: + formatted_traceback.append( + traceback.FrameSummary(entry["filename"], entry["line"], entry["name"]) + ) + + return "".join(traceback.format_list(formatted_traceback)) + + +def check_memory_pool(device, pool_id, live_storages_ptrs: List[StorageWeakRefWrapper]): + assert all( + isinstance(elem, StorageWeakRefWrapper) for elem in live_storages_ptrs + ) # noqa: C419 + unique_storages = {stor.data_ptr() for stor in live_storages_ptrs if stor()} + + # check if there is a divergence first, then do the expensive snapshot call after + # we know it will error + if torch._C._cuda_checkPoolLiveAllocations(device, pool_id, unique_storages): + return + + # at this point we are past the fast-path. we have seen rare cases where a dead tensor is dead, + # but hasn't been gc'd yet, and gives false positive for allocated_not_in_live_storages + gc.collect() + + segments = get_cudagraph_segments(pool_id) + + allocated_not_in_live_storages = {} + + for segment in segments: + addr = segment["address"] + for block in segment["blocks"]: + if block["state"] == "active_allocated": + if addr not in unique_storages: + allocated_not_in_live_storages[addr] = block + else: + unique_storages.remove(addr) + + addr += block["size"] + + torch._check( + len(unique_storages) == 0, + lambda: f"These storage data ptrs are not allocated in pool {pool_id} but should be {unique_storages}", + ) + + if allocated_not_in_live_storages != 0: + formatted = [] + for dp, block in allocated_not_in_live_storages.items(): + trace = format_tb(block.get("frames", [])) + formatted.append(f"Data Pointer: {dp}, history: \n{trace}") + formatted_s = "\n".join(formatted) + msg = ( + f"These live storage data ptrs are in the cudagraph pool but not " + f"accounted for as an output of cudagraph trees: \n\n{formatted_s}" + ) + raise RuntimeError(msg) + + +class ExecutionState(Enum): + """ + Represents the state of the CUDAGraph Tree. Will be None if there is no live current memory allocated + in the cuda graph pool. Otherwise will reflect the state of the most recently executed node. + """ + + NONE = auto() + WARMUP = auto() + RECORDING = auto() + EXECUTION = auto() + + +class CompilationMode(Enum): + FORWARD = auto() + BACKWARD = auto() + INFERENCE = auto() + + +class CUDAGraphTreeManager: + """ + Groups individual recordings or executions of cuda graphs into a tree of recordings, + and checks required invariants, and manages warmups of graphs. + + When graphs are recorded in the same tree, it enforces subsequent execution + to follow the same order and have the same output tensor livespans. To remove + unnecessary coupling of cuda graphs (and additional imposed invariants), + the tree manager will end a currently recording tree whenever it is valid - when + the memory pool no longer has any live allocations. + + We ignore outputs from a previous generation that correspond to prior model outputs. + Currently this is hardcoded `GenerationTracker.generation` tracked in torch dynamo. + # TODO: make generation increment configurable, warn on overwrite. + + We run graph warmups in the cudagraph memory pool and return the result on the first invocation + of a function. For many models it is important to reclaim activations as you run the backward. + If we were to warm up the model and keep an extra copy of the inputs around to subsequently + use for recording, we would incur a memory penalty. Additionally, if we are part way through training + your model and need to recompile, memory will be allocated to the cuda graph pool, so we run this + warmup run in the cuda graph memory pool. As for recording, warm up needs the state of live tensors + to be accurately reflected so we checkpoint the allocator state if we need to warm up following graph + replay. + """ + + def __init__(self, device_index: int): + # roots are functions which have no dependencies on an other node. I.e., + # when they are first invoked, none of their inputs are outputs are outputs + # of another node, nor are there any live outputs of another node whose + # liveness would create a dependency. + self.roots: Dict[FunctionID, List[CUDAGraphNode]] = defaultdict(list) + + # mapping from function id to wrapped function + self.ids_to_funcs: Dict[FunctionID, WrappedFunction] = {} + + self.ids_to_stack_traces: Dict[FunctionID, StackTraces] = {} + + self.warmed_up_functions: Set[FunctionID] = set() + # if we fail to increment generation, and are stuck warming up, + # only warn on each function once + self.warned_functions: Set[FunctionID] = set() + torch._C._set_cached_tensors_enabled(True) + + # NB: cuda caching allocator will remember the stream a segment is allocated to + # and only allocate that segment to the same stream. we need to use a single stream + # for all allocations to the memory pool, otherwise the allocations to separate streams + # will not be reused; separate recordings would have use the same memory pool, but not + # the same memory. + + with torch.cuda.device(device_index): + torch.cuda.synchronize() + self.stream = torch.cuda.Stream() + self.stream.wait_stream(torch.cuda.current_stream()) + + self.cuda_graphs_thread_pool = torch.cuda.graph_pool_handle() + # Keeps Memory Pool Alive + self.graph = torch.cuda.CUDAGraph() + + self.cuda_graphs_thread_pool = torch.cuda.graph_pool_handle() + + with warnings.catch_warnings(record=True), torch.cuda.graph( + self.graph, + pool=self.cuda_graphs_thread_pool, + stream=self.stream, + capture_error_mode="thread_local", + ): + pass + + self.graph_counter = itertools.count(0) + self.func_counter = itertools.count(0) + + # whether we the current node is in a state of warmup, recording, execution. If + # there is no current node the state will be ExecutionState.None. + self.path_state = ExecutionState.NONE + self.device_index = device_index + + # the most recently invoked cudagraph wrapping of a function. Will be None + # when there is no output from a previous recording or execution whose memory + # we need to respect in the cuda caching allocation. If you incremented generation, + # this will also be none, as ignore those allocations. + self.current_node: Optional[CUDAGraphNode] = None + + # current generation of cudagraph invocations. when torch.compile is run + # we increment the current generation. are willing to ignore live outputs + # of a previous generation in checking liveness. + self.current_gen: int = -1 + + # number of instances we are in execution and failed to match to an + # existing child + self.debug_fail_counter = 0 + # number of instances we had to checkpoint the function + self.debug_checkpointing_counter = 0 + + self.id_to_mode: Dict[FunctionID, CompilationMode] = {} + + # Note: [Backward Generation Handling] + # We generally perform a sequence of forward executions followed by backward executions. + # If multiple torch.compile wrapped forwards are executed with their backwards pending, + # we should not disregard the outputs from a prior torch.compile since the entire training + # loop hasn't completed. Occasionally, a backward pass corresponding to a forward pass may + # not be executed, so we cannot wait for all pending forward pass backward completions, so + # we cannot wait for all backwards to have been invoked. Instead we wait for a single backward + # invocation. Triggering a backward pass typically doesn't lead to another torch.compile + # invocation, making it less likely for the generation to increase between multiple + # backward calls. The following use case is covered by this approach: + # mod1 = torch.compile(...) + # mod2 = torch.compile(...) + # mod2(mod1(x)).sum().backward() + + self.running_forwards_with_pending_backwards = False + + def run(self, new_inputs: List[Tensor], function_id: FunctionID): + assert self.graph is not None, "Running CUDAGraph after shutdown" + out = self._run(new_inputs, function_id) + + # The forwards are only pending following invocation, not before + mode = self.id_to_mode[function_id] + if mode == CompilationMode.FORWARD: + self.running_forwards_with_pending_backwards = True + elif mode == CompilationMode.BACKWARD: + self.running_forwards_with_pending_backwards = False + + return out + + def set_to_running_backward(self): + self.running_forwards_with_pending_backwards = False + + def _run(self, new_inputs: List[Tensor], function_id: FunctionID): + # we will try to end the current execution lazily, since + # we dont want to do unnecessary checking of the existing outputs + # on the hot path, but both recording and warmup only happen once + # so we check up front + if self.in_recording: + self.try_end_curr_recording(function_id) + + if self.in_warmup: + self.try_end_curr_warmup(function_id) + + # warming up a function and subsequentally recording may use different memory addresses + # because both depend on the state of the caching allocator. if we warm up graph A, + # then warm up graph B and make more allocations, the subsequent recording of A will not + # necessarily use the same addresses as in the warm up. Thus any warm up of a node can only + # be followed by warm up runs. + if ( + not ( + function_id in self.warmed_up_functions + or config.triton.skip_cudagraph_warmup + ) + ) or self.in_warmup: + # If we are in the middle of executing cuda graphs, then we need to checkpoint memory state. + # Both Recording and Warmup will be reflected in the allocator and dont need changes + if self.path_state == ExecutionState.EXECUTION: + self.apply_checkpoint_execution_state_in_allocator() + + return self.run_eager(new_inputs, function_id) + + child_nodes = ( + self.roots if self.current_node is None else self.current_node.children + ) + + if not self.in_recording: + for child in child_nodes[function_id]: + # here we are checking memory consistency between recording and execution, + # as well as things like stability of tensor locations, etc + # and other + if child.check_invariants(new_inputs): + return self.execute_node(child, new_inputs) + + # now that we know the new function can't be run as a child of the + # current node, if it is a root, try to end the current execution. + # as noted above, we want to do this lazily to avoid having to + # check all existing outputs + if self.current_node is not None and function_id in self.roots: + self.try_end_curr_execution() + + # run again to hit the root matching case which must succeed + if self.current_node is None: + return self.run(new_inputs, function_id) + + # at this point, we necessarily will do a new recording + self.debug_fail_counter += 1 + + self.try_end_curr_execution() + if self.current_node is not None: + self.apply_checkpoint_execution_state_in_allocator() + + # now, we are in a recording state ! + return self.record_function(new_inputs, function_id) + + def shutdown(self): + """ + Remove all cached tensors in all nodes. Because cached tensors can hold gradients which in turn + might reference a backward which invokes a CUDA Graph Node, we have to manually clear them on shutdown + to avoid a reference cycle. + """ + nodes = [] + for roots in self.roots.values(): + nodes.extend(roots) + + while nodes: + node = nodes.pop() + for children in node.children.values(): + nodes.extend(children) + node.remove_node_cached_tensors() + node.graph = None + + self.graph = None + self.roots = None # type: ignore[assignment] + self.current_node = None + + def record_function(self, new_inputs, function_id) -> List[Optional[Tensor]]: + graph_id = self.new_graph_id() + log.debug( + "Recording function %d of graph recording id %d", + function_id.id, + graph_id.id, + ) + torch.cuda.synchronize() + node = CUDAGraphNode( + self.ids_to_funcs[function_id], + graph_id, + self.current_node, + new_inputs, + self.cuda_graphs_thread_pool, + self.device_index, + self.ids_to_stack_traces[function_id], + self.stream, + ) + if self.current_node is None: + self.roots[function_id].append(node) + else: + self.current_node.add_child(function_id, node) + self.current_node = node + self.path_state = ExecutionState.RECORDING + self.update_generation() + torch.cuda.synchronize() + return node.run_first_inputs(new_inputs) + + def execute_node(self, node: CUDAGraphNode, new_inputs) -> List[Optional[Tensor]]: + self.current_node = node + self.path_state = ExecutionState.EXECUTION + self.update_generation() + return node.run(new_inputs) + + def run_eager(self, new_inputs, function_id: FunctionID): + # this is only stored on current node, because when we start a new path, + # we will deallocate it + already_warm = function_id in self.warmed_up_functions + if not already_warm: + log.debug("Running warmup of function %d", function_id.id) + else: + log.debug( + "Running eager of function %d because ancestor needed to warm up", + function_id.id, + ) + self.warmed_up_functions.add(function_id) + node = CUDAWarmupNode( + self.ids_to_funcs[function_id], + self.current_node, + self.cuda_graphs_thread_pool, + self.graph, + self.device_index, + self.ids_to_stack_traces[function_id], + self.stream, + already_warm, + ) + self.current_node = node + self.path_state = ExecutionState.WARMUP + self.update_generation() + return node.run(new_inputs) + + def new_graph_id(self) -> GraphID: + return GraphID(next(self.graph_counter)) + + def new_func_id(self) -> FunctionID: + return FunctionID(next(self.func_counter)) + + def add_function( + self, + model, + inputs, + static_input_idxs, + stack_traces, + mode, + ) -> Tuple[Callable[..., Any], List[Optional[Tensor]]]: + id = self.new_func_id() + self.ids_to_stack_traces[id] = stack_traces + self.ids_to_funcs[id] = WrappedFunction(model, static_input_idxs, id) + self.id_to_mode[id] = mode + fn = functools.partial(self.run, function_id=id) + + # container needs to set clean up when fn dies + get_container(self.device_index).add_strong_reference(fn) + return fn, fn(inputs) + + @property + def in_recording(self): + return self.path_state == ExecutionState.RECORDING + + @property + def in_warmup(self): + return self.path_state == ExecutionState.WARMUP + + def get_roots(self) -> Iterator[CUDAGraphNode]: + for nodes in self.roots.values(): + yield from nodes + + @property + def current_node(self): + return self._current_node + + @current_node.setter + def current_node(self, value): + self._current_node = value + if value is None: + self.path_state = ExecutionState.NONE + + def update_generation(self): + self.current_gen = self.get_curr_generation() + + @staticmethod + def get_curr_generation() -> int: + if MarkStepBox.mark_step_counter != 0: + return MarkStepBox.mark_step_counter + + return GenerationTracker.generation + + @staticmethod + def user_invoked_mark_step(): + return MarkStepBox.mark_step_counter != 0 + + def can_start_new_generation(self) -> bool: + if not self.in_new_torch_compile_invocation(): + return False + + if self.user_invoked_mark_step(): + return True + + return not self.running_forwards_with_pending_backwards + + def in_new_torch_compile_invocation(self): + return self.current_gen != self.get_curr_generation() + + def try_end_curr_recording(self, function_id: FunctionID) -> None: + """ + Check if the current recording can be terminated, either because all outputs of the + previously recorded node are dead or because it was executed in a different + generation. Will set current_node to None and in_recording to False if successful. + """ + assert self.in_recording + assert self.current_node is not None + + # multiple invocations, allow overwriting the previous generation + if self.can_start_new_generation(): + self.dealloc_current_path_weakrefs() + self.clear_current_path_state_and_set_to_none() + return + + if self.current_node.all_outputs_are_dead(): + self.clear_current_path_state_and_set_to_none() + return + + self.check_warn_on_unable_to_start_executing(function_id) + + def try_end_curr_execution(self) -> None: + """ + Check if the current executing node can be terminated, either because all outputs of the + previously executed node are dead or because it was executed in a different generation. + Will set current_node to None if successful. + """ + + assert not self.in_recording + if self.current_node is None: + return + + if self.can_start_new_generation(): + self.clear_current_path_state_and_set_to_none() + return + + if self.current_node.all_outputs_are_dead(): + self.clear_current_path_state_and_set_to_none() + + def try_end_curr_warmup(self, function_id: FunctionID): + if self.can_start_new_generation(): + self.dealloc_current_path_weakrefs() + self.current_node = None + return + + if self.current_node.all_outputs_are_dead(): + self.current_node = None + return + + self.check_warn_on_unable_to_start_executing(function_id) + + def check_warn_on_unable_to_start_executing(self, function_id: FunctionID): + "Warn if we in a potential loop where we are unable to hit fast path" + if ( + function_id in self.warned_functions + or not self.in_new_torch_compile_invocation() + ): + return + + existing_nodes = [ + node + for node in self.current_node._path_from_root + if node.wrapped_function.id == function_id + ] + + if len(existing_nodes) <= 1: + return + + # repeated same pattern + parents = { + n.parent.wrapped_function.id + for n in itertools.chain(existing_nodes, (self.current_node,)) + if n.parent is not None + } + if len(parents) == len(existing_nodes): + return + + self.warned_functions.add(function_id) + warnings.warn( + "Unable to hit fast path of CUDAGraphs because of pending, uninvoked backwards. " + "Consider running with torch.no_grad() or using torch._inductor.cudagraph_mark_step_begin() " + "before each model invocation" + ) + + def dealloc_current_path_weakrefs(self): + # TODO: we could also allow the these weak refs to continue to be allocated, + # but that adds some complications. + for node in self.current_node._path_from_root: + assert len(node.tensor_weakrefs) == len(node.stack_traces) + for t, stack_trace in zip(node.tensor_weakrefs, node.stack_traces): + ten = None if t is None else t() + if ten is None: + continue + + stack_trace = ( + stack_trace.strip() + if stack_trace + else "[Could not find stack trace]" + ) + msg = ( + "Error: accessing tensor output of CUDAGraphs that has been overwritten by a subsequent run. " + f"Stack trace: {stack_trace}. " + "To prevent overwriting, clone the tensor outside of torch.compile() " + "before running the model again." + ) + torch._C._set_storage_access_error_msg(ten, msg) + + deleted = set() + for storage_ref in self.current_node.path_live_weakrefs(): + if storage_ref() and storage_ref.data_ptr() not in deleted: + deleted.add(storage_ref.data_ptr()) + torch._C._free_And_Remove_DeleterFn(storage_ref()) + + def clear_current_path_state_and_set_to_none(self): + self.current_node.clear_path_state() + self.current_node = None + + def apply_checkpoint_execution_state_in_allocator(self): + """ + Checkpoint the current execution state in the caching allocator so that + additional cudagraph recordings can be made respecting existent live storages. + """ + self.debug_checkpointing_counter += 1 + log.debug( + "Checkpointing cuda caching allocator state. Number of checkpoints %d", + self.debug_checkpointing_counter, + ) + + state = self.current_node.checkpointed_caching_state + device = self.current_node.device + assert state is not None and device is not None + + # currently we deallocate on instead of allowing stale recordings + stale_storages: List[int] = [] + + # remove cached tensors, otherwise they would prevent memory from being + # reclaimed in subsequent recordings + self.current_node.remove_path_cached_tensors() + live_storages_wrappers = list(self.current_node.path_live_weakrefs()) + + live_storages_weak_refs = [t() for t in live_storages_wrappers] + ptrs_to_deallocate = self.current_node.data_ptrs_dead_since_invocation() + torch._C._cuda_setCheckpointPoolState( + device, state, stale_storages, live_storages_weak_refs + ) + + # NB: deduplicate aliased outputs + for ptr in set(ptrs_to_deallocate): + torch._C._cuda_cudaCachingAllocator_raw_delete(ptr) + + # Now the live blocks should be exactly equal to the live storages in private pool + if config.triton.slow_path_cudagraph_asserts: + check_memory_pool( + self.device_index, self.cuda_graphs_thread_pool, live_storages_wrappers + ) + for wrapper in live_storages_wrappers: + assert wrapper() + assert torch._C._has_Standard_Deleter(wrapper()) + assert wrapper.data_ptr() not in ptrs_to_deallocate + + def live_cudagraph_pool_storages_in_curr_execution( + self, + ) -> List[StorageWeakRefPointer]: + if self.current_node is None: + return [] + # explicitly ignoring previous recorded outputs from past path + return [t() for t in self.current_node.path_live_weakrefs()] diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/debug.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..3e42009b56c47d3d489da5210f46b37ad317dbf5 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/debug.py @@ -0,0 +1,471 @@ +import collections +import contextlib +import cProfile +import dataclasses +import functools +import itertools +import logging +import os +import os.path +import pickle +import pstats +import shutil +import subprocess +from typing import Any, List +from unittest.mock import patch + +from functorch.compile import draw_graph, get_aot_graph_name, get_graph_being_compiled + +import torch +from torch import fx as fx + +from torch._dynamo.repro.after_aot import save_graph_repro, wrap_compiler_debug +from torch._dynamo.utils import get_debug_dir +from torch.fx.graph_module import GraphModule +from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata +from torch.fx.passes.tools_common import legalize_graph +from torch.utils._pytree import tree_map + +from . import config, ir # noqa: F811, this is needed +from .scheduler import ( + BaseSchedulerNode, + FusedSchedulerNode, + NopKernelSchedulerNode, + OutputNode, + SchedulerNode, +) +from .virtualized import V + +log = logging.getLogger(__name__) + + +@functools.lru_cache(None) +def has_dot(): + try: + subprocess.check_output(["which", "dot"], stderr=subprocess.PIPE) + return True + except subprocess.SubprocessError: + return False + + +def draw_buffers(nodes, print_graph=False, fname=None): + """ + Draw a graph in fname.svg. + nodes is a list of SchedulerNode objects. + """ + if not has_dot(): + log.warning("draw_buffers() requires `graphviz` package") + return + + if fname is None: + fname = get_graph_being_compiled() + + graph = create_fx_from_snodes(nodes) + + for node in graph.nodes: + if "fusion_meta" not in node.meta: + continue + group = node.meta["fusion_meta"].group + if isinstance(group, tuple): + group = group[1] + + # gather meta data + dtype = None + if isinstance(node, ir.ComputedBuffer): + dtype = node.data.dtype + + metadata = TensorMetadata(group, dtype, None, None, None, None, None) + node.meta["tensor_meta"] = metadata + + if print_graph: + print(graph) + + gm = GraphModule({}, graph) + legalize_graph(gm) + gm.graph.lint() + draw_graph(gm, fname, clear_meta=False) + + +def create_fx_from_snodes(snodes: List[BaseSchedulerNode]) -> fx.Graph: + """ + Creates a FX Graph from a list of SchedulerNode objects. + """ + + def get_fake_func(name): + def func1(*args): + return 0 + + func1.__name__ = name + return func1 + + FusionMeta = collections.namedtuple("FusionMeta", ["group", "snode", "type"]) + + buf_to_fx_node = {} + graph = torch.fx.Graph() + first_node = None + + outputs = [] + group: Any = None + # create call_function node for each Buffer and Kernel + for snode in snodes: + if snode.is_extern(): + node_type = "extern" + group = node_type + elif snode.is_template(): + node_type = "template" + group = node_type + elif isinstance(snode, NopKernelSchedulerNode): + node_type = "nop" + group = node_type + elif isinstance(snode, SchedulerNode): + node_type = "compute" + group = snode.group + elif isinstance(snode, FusedSchedulerNode): + node_type = "fused" + group = snode.group + else: + raise RuntimeError("Unknown node type") + + fused_name = torch._inductor.utils.get_fused_kernel_name( + snode.get_nodes(), "original_aten" + ) + func_name = f"{node_type}: {fused_name}" + node_func = get_fake_func(func_name) + fx_node = graph.call_function(node_func, args=(), kwargs=None) + + def in_output(snode): + if isinstance(snode, FusedSchedulerNode): + return any(in_output(x) for x in snode.snodes) + return any(isinstance(user.node, OutputNode) for user in snode.users) + + if in_output(snode): + outputs.append(fx_node) + name = snode.get_name() + fx_node.name = name + + fx_node.meta["fusion_meta"] = FusionMeta(group, snode, node_type) + + if isinstance(snode, FusedSchedulerNode): + for x in snode.snodes: + buf_to_fx_node[x.get_name()] = fx_node + buf_to_fx_node[name] = fx_node + + if first_node is None: + first_node = fx_node + + # create edges between nodes + for snode in snodes: + name = snode.get_name() + deps = snode.read_writes.reads + + fx_node = buf_to_fx_node[name] + new_args = [] + for dep in deps: + if dep.name in buf_to_fx_node: + dep_node = buf_to_fx_node[dep.name] + else: + with graph.inserting_before(first_node): + dep_node = graph.placeholder(dep.name) + buf_to_fx_node[dep.name] = dep_node + new_args.append(dep_node) + + fx_node.args = tuple(new_args) + + graph.output(outputs[0] if len(outputs) == 1 else tuple(outputs)) + return graph + + +@contextlib.contextmanager +def enable_aot_logging(): + compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1" + + import torch._functorch.aot_autograd + + log = logging.getLogger(torch._functorch.aot_autograd.__name__) + + stack = contextlib.ExitStack() + if not compile_debug: + try: + yield + finally: + stack.close() + return + + # Enable all graphs to be logged to a file by setting the flags to True + # and the log level of the file logger to DEBUG + stack.enter_context(patch("functorch.compile.config.debug_partitioner", True)) + + path = os.path.join(get_debug_dir(), "torchinductor") + if not os.path.exists(path): + os.makedirs(path) + + fh = logging.FileHandler( + os.path.join( + path, + f"aot_{get_aot_graph_name()}_debug.log", + ) + ) + fh.setLevel(logging.DEBUG) + fh.setFormatter( + logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s") + ) + log.addHandler(fh) + try: + yield + finally: + log.removeHandler(fh) + stack.close() + + +class DebugContext: + _counter = itertools.count() + + @staticmethod + def wrap(fn): + @functools.wraps(fn) + def inner(*args, **kwargs): + with DebugContext(): + return fn(*args, **kwargs) + + return wrap_compiler_debug(inner, compiler_name="inductor") + + @staticmethod + def create_debug_dir(folder_name): + for n in DebugContext._counter: + dirname = os.path.join( + get_debug_dir(), + "torchinductor", + f"{folder_name}.{n}", + ) + if not os.path.exists(dirname): + os.makedirs(dirname) + return dirname + + def __init__(self): + self._prof = None + self._path = None + self._stack = contextlib.ExitStack() + + def copy(self, new_path: str): + if not self._path: + return + assert new_path.endswith(".debug"), new_path + if os.path.exists(new_path): + shutil.rmtree(new_path) + try: + shutil.copytree(self._path, new_path) + self._path = new_path + except OSError: + log.warning( + "Failed to copy debug files from %s to %s", self._path, new_path + ) + pass + + def fopen(self, filename): + assert self._path + return open(os.path.join(self._path, filename), "w") + + def filename(self, suffix): + return os.path.join(self._path, suffix) + + def upload_tar(self): + if config.trace.upload_tar is not None: + import tarfile + + assert self._path + tar_file = os.path.join( + self._path, f"{os.path.basename(self._path)}.tar.gz" + ) + with tarfile.open(tar_file, "w:gz") as tar: + tar.add(self._path, arcname=os.path.basename(self._path)) + config.trace.upload_tar(tar_file) + + def __enter__(self): + if config.debug: + log = logging.getLogger("torch._dynamo") + prev_level = log.level + log.setLevel(logging.DEBUG) + + def reset_log_level(level): + log.setLevel(level) + + self._stack.callback(reset_log_level, prev_level) + + self._stack.enter_context(V.set_debug_handler(self)) + + if not config.trace.enabled: + return + + self._path = self.create_debug_dir(get_aot_graph_name()) + + if config.trace.debug_log: + self._setup_log_capture("debug.log", logging.DEBUG) + if config.trace.info_log: + self._setup_log_capture("info.log", logging.INFO) + if config.trace.compile_profile: + self._prof = cProfile.Profile() + self._prof.enable() + + def _setup_log_capture(self, filename, level): + log = logging.getLogger("torch._inductor") + fd = self._stack.enter_context(self.fopen(filename)) + ch = logging.StreamHandler(fd) + ch.setLevel(level) + ch.setFormatter( + logging.Formatter("[%(filename)s:%(lineno)d %(levelname)s] %(message)s") + ) + log.addHandler(ch) + log.setLevel(min(log.level, level)) + self._stack.callback(log.removeHandler, ch) + + def __exit__(self, exc_type, exc_val, exc_tb): + if self._prof: + self._prof.disable() + self._save_profile_data() + + if self._path: + self.upload_tar() + log.warning("%s debug trace: %s", get_graph_being_compiled(), self._path) + self._stack.close() + + def _save_profile_data(self): + self._prof.dump_stats(self.filename("compile.prof")) + with self.fopen("compile.stats") as fd: + stats = pstats.Stats(self._prof, stream=fd) + stats.strip_dirs() + stats.sort_stats("cumtime") + stats.print_stats(100) + stats.sort_stats("tottime") + stats.print_stats(100) + + def __getattr__(self, name): + if config.trace.enabled and getattr(config.trace, name): + try: + return getattr(DebugFormatter(self), name) + except Exception: + log.warning("Ignoring exception in debug code", exc_info=True) + else: + + def ignored(*args, **kwargs): + pass + + return ignored + + +SchedulerNodeList = List[Any] + + +class DebugFormatter: + def __init__(self, handler): + self.fopen = handler.fopen + self.filename = handler.filename + self.handler = handler + + def fx_graph(self, gm: torch.fx.GraphModule, inputs: List[torch.Tensor]): + with self.fopen("fx_graph_runnable.py") as fd: + save_graph_repro(fd, gm, inputs, "inductor") + + with self.fopen("fx_graph_readable.py") as fd: + fd.write(gm.print_readable(print_output=False)) + + def fx_graph_transformed( + self, gm: torch.fx.GraphModule, inputs: List[torch.Tensor] + ): + with self.fopen("fx_graph_transformed.py") as fd: + fd.write(gm.print_readable(print_output=False)) + + def ir_pre_fusion(self, nodes: SchedulerNodeList): + self._write_ir("ir_pre_fusion.txt", nodes) + + def ir_post_fusion(self, nodes: SchedulerNodeList): + self._write_ir("ir_post_fusion.txt", nodes) + + def _write_ir(self, filename: str, nodes: SchedulerNodeList): + with self.fopen(filename) as fd: + for node in nodes: + fd.write(node.debug_str()) + fd.write("\n\n\n") + + def graph_diagram(self, nodes: SchedulerNodeList): + draw_buffers(nodes, fname=self.filename("graph_diagram.svg")) + + def output_code(self, filename): + shutil.copy(filename, self.filename("output_code.py")) + + +@dataclasses.dataclass +class TensorMetadataHolder: + tensor_metadata: TensorMetadata + device: torch.device + + +save_args_cnt = itertools.count() + + +def save_args_for_compile_fx_inner(*args, **kwargs): + """ + This function is used to save arguments for a compile_fx_inner function call + to the file system. Later on one can replay the compile_fx_inner call + with the saved arguments using load_args_and_run_compile_fx_inner. + """ + + folder = "/tmp/inductor_saved_args" + if not os.path.exists(folder): + os.mkdir(folder) + + def handle_tensor(x): + """ + Pickle FakeTensor will result in error: + AttributeError: Can't pickle local object 'WeakValueDictionary.__init__..remove' + + Convert all Tensor to metadata. This may also makes pickle faster. + """ + if isinstance(x, torch.Tensor): + return TensorMetadataHolder(_extract_tensor_metadata(x), x.device) + else: + return x + + args_to_save, kwargs_to_save = tree_map(handle_tensor, (args, kwargs)) + + fn_name = "compile_fx_inner" + path = f"{folder}/{fn_name}_{next(save_args_cnt)}.pkl" + with open(path, "wb") as f: + pickle.dump((args_to_save, kwargs_to_save), f) + + if log.isEnabledFor(logging.DEBUG): + message = f""" +Arguments for a compile_fx_inner call is saved to {path}. To replay the call, +run the following: + +from torch._inductor.debug import load_args_and_run_compile_fx_inner +load_args_and_run_compile_fx_inner({path!r}) + """ + # call print rather than log.debug. log.debug will print message + # prefix for each line which makes the code snippet harder to be + # copied. + # Not a big deal since the code is already been guarded by checking + # the log level. + print(message) + + +def load_args_and_run_compile_fx_inner(path): + from torch._inductor.compile_fx import compile_fx_inner + + with open(path, "rb") as f: + args, kwargs = pickle.load(f) + + def handle_tensor(x): + if isinstance(x, TensorMetadataHolder): + return torch._dynamo.testing.rand_strided( + x.tensor_metadata.shape, + x.tensor_metadata.stride, + x.tensor_metadata.dtype, + x.device, + ) + else: + return x + + fake_mode = torch._subclasses.FakeTensorMode(allow_non_fake_inputs=True) + with fake_mode, config.patch("save_args", False): + args, kwargs = tree_map(handle_tensor, (args, kwargs)) + return compile_fx_inner(*args, **kwargs) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/decomposition.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/decomposition.py new file mode 100644 index 0000000000000000000000000000000000000000..4735e9fb4f0f41b306b38137c34732c62483cc5d --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/decomposition.py @@ -0,0 +1,500 @@ +import functools +import logging +import math +import numbers +import typing + +import torch +import torch._decomp as decomp +import torch.ao.quantization.fx._decomposed +from torch._decomp import ( + core_aten_decompositions, + get_decompositions, + remove_decompositions, +) +from torch._decomp.decompositions import pw_cast_for_opmath +from torch._decomp.decompositions_for_rng import extra_random_decomps + +from . import config + +log = logging.getLogger(__name__) +aten = torch.ops.aten +prims = torch.ops.prims +quantized_decomposed = torch.ops.quantized_decomposed + +inductor_decompositions = get_decompositions( + [ + aten._adaptive_avg_pool2d_backward, + aten.arange, + aten.bitwise_and_, + aten.bitwise_or_, + aten.clamp_min_, + aten.dist, + aten.empty_like, + aten.flip, + aten.gelu, + aten.hardtanh, + aten.index_select, + aten.lcm, + aten.leaky_relu, + aten.linalg_vector_norm, + aten._log_softmax, + aten.max_pool2d_with_indices_backward, + aten._native_batch_norm_legit, + aten._native_batch_norm_legit_functional, + aten._native_batch_norm_legit_no_training, + aten.native_batch_norm, + aten.native_group_norm, + aten.native_layer_norm, + aten._softmax, + aten.sin_, + aten.sqrt_, + aten.std, + aten.std_mean, + aten._to_copy, + aten.tril_indices, + aten.triu_indices, + aten.unsafe_split, + aten.upsample_bilinear2d.vec, + ] +) +decompositions = {**core_aten_decompositions(), **inductor_decompositions} + +# Remove unwanted decompositions included via the core ATen decompositions from +# the Inductor decomp table. +decomps_to_exclude = [ + aten._unsafe_index, +] + +remove_decompositions(decompositions, decomps_to_exclude) + + +def register_decomposition(ops): + for op in [ops] if callable(ops) else ops: + if op in decompositions: + log.warning("duplicate decomp: %s", ops) + return decomp.register_decomposition(ops, decompositions) + + +@register_decomposition(aten._unsafe_view.default) +def _unsafe_view(self, size): + # this makes pattern matching easier + return self.view(size) + + +# TODO: for now, inductor doesn't handle asserts +# because the condition is symbool -> tensor in the graph. +@register_decomposition([aten._assert_async.msg]) +def assert_async_msg_decomp(tensor, msg): + return + + +# Following `assert_async_msg_decomp` and implement as non-op. +@register_decomposition([aten._functional_assert_async.msg]) +def functional_assert_async_msg_decomp(tensor, msg): + return + + +@register_decomposition([aten.sym_constrain_range_for_size.default]) +def sym_constrain_range_for_size(symbol, *, min=None, max=None): + return + + +@register_decomposition([aten.clamp]) +@pw_cast_for_opmath +def clamp(x, min=None, max=None): + if min is not None: + x = x.clamp_min(min) + if max is not None: + x = x.clamp_max(max) + return x + + +# TorchInductor-only decomposition. It should not be taken to core. +# See https://github.com/pytorch/torchdynamo/pull/1120 +@register_decomposition([aten.floor_divide.default]) +def floordiv(a, b): + return aten.div.Tensor_mode(a, b, rounding_mode="floor") + + +# Not really sure how to put this into the main library. PrimTorch wants +# empty_permuted to go to the prim, and typically users don't really want +# to decompose to empty_strided (but inductor is OK with it, because we are +# cool with strides and everything goes to empty_strided) +@register_decomposition([aten.empty_permuted.default]) +def empty_permuted(size, physical_layout, **kwargs): + perm = [0] * len(size) + for p, l in enumerate(physical_layout): + perm[l] = p + return torch.empty([size[l] for l in physical_layout], **kwargs).permute(perm) + + +@register_decomposition([aten.convolution_backward]) +def convolution_backward( + grad_output, + input, + weight, + bias_sizes, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + output_mask, +): + if not output_mask[2] or grad_output.device.type != "cuda": + return NotImplemented + grad_bias = aten.sum(grad_output, [0] + list(range(2, grad_output.dim()))) + grad_inp, grad_weight, _ = aten.convolution_backward( + grad_output, + input, + weight, + bias_sizes, + stride, + padding, + dilation, + transposed, + output_padding, + groups, + [output_mask[0], output_mask[1], False], + ) + return (grad_inp, grad_weight, grad_bias) + + +@register_decomposition([aten.log2]) +def log2(x): + return torch.log(x) * (1.0 / math.log(2.0)) + + +@register_decomposition([aten.round.decimals]) +def round_dec(x, decimals=0): + ten_pow_decimals = 10.0**decimals + return aten.round(x * ten_pow_decimals) * (1.0 / ten_pow_decimals) + + +@register_decomposition([aten.all.default]) +def all(input): + return torch.logical_not(torch.any(torch.logical_not(input))) + + +@register_decomposition([aten.all.dim]) +def all_dim(input, dim, keepdim=False): + return torch.logical_not(torch.any(torch.logical_not(input), dim, keepdim)) + + +@register_decomposition([aten.baddbmm]) +def baddbmm(self, batch1, batch2, beta=1, alpha=1): + result = torch.bmm(batch1, batch2) + if not isinstance(alpha, numbers.Number) or alpha != 1: + result = result * alpha + if beta == 0: + return result + if not isinstance(beta, numbers.Number) or beta != 1: + self = self * beta + return self + result + + +@register_decomposition([aten.bmm]) +def bmm(self, batch2): + if self.device == "cpu": + if self.size(1) == 1 and batch2.size(-1) == 1: + return torch.sum( + self.squeeze(1) * batch2.squeeze(-1), dim=1, keepdim=True + ).unsqueeze(1) + return NotImplemented + + +@register_decomposition([aten.mm]) +def mm(self, input2): + if self.device == "cpu": + if ( + self.size(-1) == 1 + and input2.size(0) == 1 + and (self.dtype == input2.dtype) + and ((torch.numel(self) + torch.numel(input2)) <= 32) + ): + return torch.cat([self[i, :] * input2 for i in range(self.size(0))]) + if self.size(0) == 1 and input2.size(-1) == 1: + return torch.sum( + self.squeeze(0) * input2.squeeze(-1), dim=0, keepdim=True + ).unsqueeze(0) + return NotImplemented + + +@register_decomposition([aten.cat.default]) +def cat(tensors, dim=0): + def non_empty_tensor(x): + # special case for cat'ing with an empty tensor - + # just drop the 'empty' inputs so they don't confuse the logic below. + return len(x.shape) > 1 or x.shape[0] > 0 + + filtered_tensors = list(filter(non_empty_tensor, tensors)) + + if len(filtered_tensors) == 1: + return tensors[0].clone() + elif 1 < len(filtered_tensors) < len(tensors): + # on the first call, when we remove empty tensors, we redispatch recursively + return aten.cat.default(filtered_tensors, dim) + # when no 'filtering' has occured, we raise to prevent infinite recursion (no more decomposition needed) + return NotImplemented + + +@register_decomposition([aten.angle]) +def angle(x): + if x.is_complex(): + return torch.where( + torch.isnan(x.real), float("nan"), torch.atan2(x.imag, x.real) + ) + else: + # when x is real number + # if x >= 0, return 0 + # if x < 0, return pi + # if x is nan, return nan + ret = torch.where(x < 0, math.pi, 0.0) + nan = torch.where(torch.isnan(x), float("nan"), 0.0) + return ret + nan + + +@register_decomposition([aten.conj_physical]) +def conj_physical(self): + assert not self.is_complex(), "TODO: implement this" + return self + + +@register_decomposition([aten.lift, aten.detach_]) +def lift(self): + return self + + +@register_decomposition([aten.bernoulli.default]) +def bernoulli(self, *, generator=None): + assert generator is None + return torch.rand_like(self, dtype=torch.float32) < self + + +@register_decomposition([aten.fmin, prims.fmin]) +def fmin(self, other): + return torch.where(torch.isnan(other) | (other > self), self, other) + + +@register_decomposition([aten.fmax, prims.fmax]) +def fmax(self, other): + return torch.where(torch.isnan(other) | (other < self), self, other) + + +@register_decomposition([aten.narrow_copy]) +def narrow_copy(self, dim, start, length): + return torch.narrow(self, dim, start, length).clone() + + +@register_decomposition([aten.expand_copy]) +def expand_copy(self, size, *, implicit=False): + return aten.expand(self, size, implicit=implicit).clone() + + +@register_decomposition([aten.view_copy.default]) +def view_copy_default(self, size): + return aten.view(self, size).clone() + + +@register_decomposition([aten.view_copy.dtype]) +def view_copy_dtype(self, dtype): + return self.to(dtype).clone() + + +@register_decomposition(aten.rand_like) +def rand_like(self, *, dtype=None, device=None, **kwargs): + return torch.rand( + [*self.size()], + dtype=dtype or self.dtype, + device=device or self.device, + **kwargs, + ) + + +@register_decomposition(aten.randn_like) +def randn_like(self, *, dtype=None, device=None, **kwargs): + return torch.randn( + [*self.size()], + dtype=dtype or self.dtype, + device=device or self.device, + **kwargs, + ) + + +@register_decomposition(aten.full_like) +def full_like( + self, + fill_value, + *, + dtype=None, + layout=None, + device=None, + pin_memory=False, + requires_grad=False, + memory_format=torch.preserve_format, +): + return torch.full( + [*self.size()], + fill_value, + dtype=dtype or self.dtype, + layout=layout or self.layout, + device=device or self.device, + requires_grad=requires_grad, + ) + + +@register_decomposition(aten.randint_like.default) +def randint_like(self, high, *, dtype=None, device=None, **kwargs): + return aten.randint.low( + 0, + high, + [*self.size()], + dtype=dtype or self.dtype, + device=device or self.device, + **kwargs, + ) + + +@register_decomposition(aten.randint_like.low_dtype) +def randint_like_low(self, low, high, *, dtype=None, device=None, **kwargs): + return aten.randint.low( + low, + high, + [*self.size()], + dtype=dtype or self.dtype, + device=device or self.device, + **kwargs, + ) + + +@register_decomposition(aten.randint.default) +def randint(high, size, **kwargs): + return aten.randint.low(0, high, size, **kwargs) + + +# The difference between quantize_per_tensor.default and quantize_per_tensor.tensor is +# scale and zero_point is scalar or scalar tensor +@register_decomposition(quantized_decomposed.quantize_per_tensor.default) +def quantize_per_tensor_default_decomp_impl( + input: torch.Tensor, + scale: float, + zero_point: int, + quant_min: int, + quant_max: int, + dtype: torch.dtype, +) -> torch.Tensor: + inv_scale = 1.0 / scale + return torch.clamp( + torch.round(input * inv_scale) + zero_point, quant_min, quant_max + ).to(dtype) + + +# The difference between dequantize_per_tensor.default and dequantize_per_tensor.tensor is +# scale and zero_point is scalar or scalar tensor +@register_decomposition(quantized_decomposed.dequantize_per_tensor.default) +def dequantize_per_tensor_default_decomp_impl( + input: torch.Tensor, + scale: float, + zero_point: int, + quant_min: int, + quant_max: int, + dtype: torch.dtype, +) -> torch.Tensor: + return (input.to(torch.float32) - zero_point) * scale + + +@register_decomposition(quantized_decomposed.quantize_per_tensor.tensor) +def quantize_per_tensor_tensor_decomp_impl( + input: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + quant_min: int, + quant_max: int, + dtype: torch.dtype, +) -> torch.Tensor: + inv_scale = 1.0 / scale + return torch.clamp( + torch.round(input * inv_scale) + zero_point, quant_min, quant_max + ).to(dtype) + + +@register_decomposition(quantized_decomposed.dequantize_per_tensor.tensor) +def dequantize_per_tensor_tensor_decomp_impl( + input: torch.Tensor, + scale: torch.Tensor, + zero_point: torch.Tensor, + quant_min: int, + quant_max: int, + dtype: torch.dtype, +) -> torch.Tensor: + return (input.to(torch.float32) - zero_point) * scale + + +@register_decomposition(aten._foreach_addcmul.Scalar) +def _foreach_addcmul_scalar(self, left_tensors, right_tensors, scalar=1): + return aten._foreach_add.List( + self, aten._foreach_mul.List(left_tensors, right_tensors), alpha=scalar + ) + + +@register_decomposition(aten._foreach_addcdiv.Scalar) +def _foreach_addcdiv_scalar(self, left_tensors, right_tensors, scalar=1): + return aten._foreach_add.List( + self, aten._foreach_div.List(left_tensors, right_tensors), alpha=scalar + ) + + +@register_decomposition(aten._foreach_lerp.Scalar) +def _foreach_lerp_scalar(start_tensors, end_tensors, weight): + return aten._foreach_add.List( + start_tensors, + aten._foreach_mul.Scalar( + aten._foreach_sub.List(end_tensors, start_tensors), weight + ), + ) + + +@aten.miopen_batch_norm.default.py_impl(torch._C.DispatchKey.Autograd) +@register_decomposition(aten.miopen_batch_norm) +def miopen_batch_norm( + input: torch.Tensor, + weight: torch.Tensor, + bias: typing.Optional[torch.Tensor], + running_mean: typing.Optional[torch.Tensor], + running_var: typing.Optional[torch.Tensor], + training: bool, + exponential_average_factor: float, + epsilon: float, +): + a, b, c = aten.native_batch_norm( + input, + weight, + bias, + running_mean, + running_var, + training, + exponential_average_factor, + epsilon, + ) + + if training: + return (a, b, c) + return ( + a, + weight.new_zeros((0,)), + weight.new_zeros((0,)), + ) + + +@functools.lru_cache(None) +def fast_random_decomps(): + return {**decompositions, **extra_random_decomps} + + +def select_decomp_table(): + """decomps can change based on config""" + if config.fallback_random: + return decompositions + return fast_random_decomps() diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/dependencies.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/dependencies.py new file mode 100644 index 0000000000000000000000000000000000000000..dc240e56acff3f78eef5bb72353d941b9cfa8236 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/dependencies.py @@ -0,0 +1,360 @@ +import collections +import dataclasses +import itertools +import logging +import re +import typing +from typing import Callable, Dict, List, Optional, Set, Tuple, Union + +import sympy + +import torch + +from .codegen.common import index_prevent_reordering +from .utils import get_dtype_size, sympy_str, sympy_subs, sympy_symbol, VarRanges +from .virtualized import V + +log = logging.getLogger(__name__) +is_indirect = re.compile(r"indirect|tmp").search +Dep = Union["MemoryDep", "StarDep", "WeakDep"] + + +class MemoryDep(typing.NamedTuple): + name: str + index: sympy.Expr # type: ignore[assignment] + var_names: Tuple[sympy.Symbol, ...] + size: Tuple[sympy.Expr, ...] + + def __repr__(self): + return f"MemoryDep({self.name!r}, {self.index}, {self.ranges})" + + @property + def ranges(self) -> Dict[sympy.Symbol, sympy.Expr]: + """{c0: 128, c1: 512, ...}""" + return dict(zip(self.var_names, self.size)) + + def rename(self, renames: Dict[str, str]) -> "MemoryDep": + if self.name in renames: + return MemoryDep( + renames[self.name], self.index, var_names=self.var_names, size=self.size + ) + return self + + def numbytes_hint(self): + if self.is_indirect(): + numel = V.graph.get_numel(self.name) + else: + vars = set(self.index.free_symbols) + numel = sympy.Integer(1) + for var, size in zip(self.var_names, self.size): + if var in vars: + numel = numel * size + return V.graph.sizevars.size_hint(numel) * get_dtype_size( + V.graph.get_dtype(self.name) + ) + + def is_contiguous(self) -> bool: + return isinstance(self.index, sympy.Symbol) and self.index in self.var_names + + def is_scalar(self) -> bool: + if isinstance(self.index, sympy.Symbol): + return self.index not in self.var_names and not self.is_indirect() + return isinstance(self.index, (int, sympy.Integer)) + + def is_indirect(self) -> bool: + return any(is_indirect(v.name) for v in self.index.free_symbols) + + +class StarDep(typing.NamedTuple): + # depends on the entire buffer + name: str + + @property + def index(self): + raise NotImplementedError("StarDep does not have an index") + + def rename(self, renames: Dict[str, str]) -> "StarDep": + if self.name in renames: + return StarDep(renames[self.name]) + return self + + def numbytes_hint(self): + return V.graph.sizevars.size_hint( + V.graph.get_numel(self.name) + ) * get_dtype_size(V.graph.get_dtype(self.name)) + + def is_contiguous(self) -> bool: + return False + + def is_scalar(self) -> bool: + return False + + def is_indirect(self) -> bool: + return False + + +# Used for tracking mutation ordering +# if A reads a buffer and B mutates it +# B must be ordered after A +class WeakDep(typing.NamedTuple): + name: str + + @property + def index(self): + raise NotImplementedError("WeakDep does not have an index") + + def rename(self, renames: Dict[str, str]) -> "WeakDep": + if self.name in renames: + return WeakDep(renames[self.name]) + return self + + def numbytes_hint(self): + return 1 # Purely inserted for ordering, not an actual dep + + def is_contiguous(self) -> bool: + return False + + +class IndexExprDep(typing.NamedTuple): + index: sympy.Expr # type: ignore[assignment] + var_names: Tuple[sympy.Symbol, ...] + size: Tuple[sympy.Expr, ...] + + +@dataclasses.dataclass +class ReadWrites: + reads: Set[Dep] + writes: Set[Dep] + index_exprs: Set[IndexExprDep] + range_vars: Optional[List[sympy.Expr]] = None + var_ranges: Optional[VarRanges] = None + op_counts: collections.Counter = None + + def rename(self, renames: typing.Dict[str, str]) -> "ReadWrites": + return ReadWrites( + {dep.rename(renames) for dep in self.reads}, + {dep.rename(renames) for dep in self.writes}, + self.index_exprs, + self.range_vars, + self.var_ranges, + op_counts=self.op_counts, + ) + + def with_read(self, dep: Dep) -> "ReadWrites": + assert isinstance(dep, (WeakDep, StarDep)) + return ReadWrites( + set.union(self.reads, {dep}), + self.writes, + self.index_exprs, + self.range_vars, + self.var_ranges, + op_counts=self.op_counts, + ) + + def merge(self, other: "ReadWrites"): + reads = set.union(self.reads, other.reads) + writes = set.union(self.writes, other.writes) + index_exprs = set.union(self.index_exprs, other.index_exprs) + if self.op_counts is not None: + op_counts = collections.Counter(self.op_counts) + op_counts.update(other.op_counts or {}) + else: + op_counts = other.op_counts + return ReadWrites(reads - writes, writes, index_exprs, op_counts=op_counts) + + @staticmethod + def merge_list(read_writes: List["ReadWrites"]): + all_writes = set.union(*[rw.writes for rw in read_writes]) + all_reads = set.union(*[rw.reads for rw in read_writes]) - all_writes + all_index_exprs = set.union(*[rw.index_exprs for rw in read_writes]) + + op_counts = collections.Counter() + for rw in read_writes: + if rw.op_counts is not None: + op_counts.update(rw.op_counts) + + return ReadWrites(all_reads, all_writes, all_index_exprs, op_counts=op_counts) + + def remove_reads(self, rem_reads): + return ReadWrites( + self.reads - rem_reads, + self.writes, + self.index_exprs, + self.range_vars, + self.var_ranges, + op_counts=self.op_counts, + ) + + def reads_and_writes(self): + return itertools.chain(self.reads, self.writes) + + +class _RecordLoadStoreInner(V.MockHandler): + def __init__(self, var_ranges: VarRanges, normalize: bool): + super().__init__() + self._reads: Set[MemoryDep] = set() + self._writes: Set[MemoryDep] = set() + self._index_exprs: Set[IndexExprDep] = set() + self._var_ranges: VarRanges = var_ranges + self._normalize: bool = normalize + + def canonicalize( + self, index: sympy.Expr + ) -> Tuple[sympy.Expr, Tuple[sympy.Expr, ...]]: + if not self._normalize: + sizes = [V.graph.sizevars.simplify(x) for x in self._var_ranges.values()] + var_names = tuple( + k for k, v in zip(self._var_ranges.keys(), sizes) if v != 1 + ) + sizes = tuple(v for v in sizes if v != 1) + return index, var_names, sizes + + # Try to further simplify the indexes even if simplify_loops didn't + # convert it to the simplest form because of the interference from + # different indexing formulas. + free_symbols = index.free_symbols + var_ranges = { + k: V.graph.sizevars.simplify(v) + for k, v in self._var_ranges.items() + # TODO(jansel): explore this further normalization + # if k in free_symbols + } + index_vars = [*var_ranges.keys()] + sizes = [*var_ranges.values()] + new_sizes, reindex, prune = V.graph.sizevars._simplify_loops( + index_vars, + sizes, + index_prevent_reordering([index], index_vars, sizes), + ) + + # assign new variables each dimension to deal with numbering mismatches + # d0, d1, d2 could become d0, d2 -- which won't match d0, d1 + new_vars, add_var = var_builder(canonicalization_prefix()) + replacement = dict(zip(index_vars, reindex([add_var(x) for x in new_sizes]))) + index = sympy_subs(sympy.expand(index), replacement) + + new_vars = [*new_vars.keys()] + new_sizes = [*new_sizes] + free_symbols = index.free_symbols + while new_vars and new_vars[-1] not in free_symbols: + # Reduction has last (reduced) dim in its sizes, but + # downstream users won't. Normalize this away. + new_vars.pop() + new_sizes.pop() + return index, tuple(new_vars), tuple(new_sizes) + + def load(self, name: str, index: sympy.Expr) -> str: + self._reads.add(MemoryDep(name, *self.canonicalize(index))) + return f"load({name}, {sympy_str(index)})" + + def load_seed(self, name: str, index: int): + assert isinstance(index, int) + return self.load(name, sympy.Integer(index)) + + def store(self, name: str, index: sympy.Expr, value: str, mode=None) -> str: + self._writes.add(MemoryDep(name, *self.canonicalize(index))) + return f"store({name}, {sympy_str(index)}, {value}, {mode})" + + def store_reduction(self, name: str, index, value) -> str: + return self.store(name, index, f"store_reduction({value})") + + def index_expr(self, index: sympy.Expr, dtype) -> str: + self._index_exprs.add(IndexExprDep(*self.canonicalize(index))) + return f"index_expr({sympy_str(index)}, {dtype})" + + def bucketize( + self, + values, + offsets_name: str, + offsets_size: sympy.Expr, + indexing_dtype: torch.dtype, + right: bool, + ): + self._reads.add(StarDep(offsets_name)) + return f"bucketize({values}, {offsets_name}, {sympy_str(offsets_size)}, {indexing_dtype}, {right})" + + +class _OpCounter: + """Shim to count how many times each op is used""" + + def __init__(self, inner): + super().__init__() + self.parent_handler = inner + self._op_counts = collections.Counter() + + def __getattr__(self, name): + self._op_counts[name] += 1 + return getattr(self.parent_handler, name) + + +class RecordLoadStore(V.KernelFormatterHandler): + def __init__(self, var_ranges: VarRanges, normalize: bool): + parent_handler = _RecordLoadStoreInner( + var_ranges=var_ranges, normalize=normalize + ) + parent_handler = _OpCounter(parent_handler) + super().__init__(parent_handler=parent_handler) + + +def var_builder(prefix: str) -> Tuple[VarRanges, Callable[[sympy.Expr], sympy.Symbol]]: + cnt = itertools.count() + var_ranges: VarRanges = dict() + + def add_var(length: sympy.Expr) -> sympy.Symbol: + v = sympy_symbol(f"{prefix}{next(cnt)}") + var_ranges[v] = length + return v + + return var_ranges, add_var + + +def index_vars_no_squeeze(*argsizes: Tuple[sympy.Expr, ...], prefix: str): + var_ranges, add_var = var_builder(prefix) + args: List[List[sympy.Symbol]] = [] + for size in argsizes: + args.append(list(map(add_var, size))) + return args, var_ranges + + +def index_vars_squeeze(*argsizes: Tuple[sympy.Expr, ...], prefix: str = "d"): + from .ir import SqueezeView + + var_ranges, add_var = var_builder(prefix) + args: List[List[sympy.Expr]] = [] + new_sizes: List[List[sympy.Expr]] = [] + for size in argsizes: + new_size, reindex = SqueezeView.squeezer(size) + new_sizes.append(new_size) + args.append(reindex(list(map(add_var, new_size)))) + return args, var_ranges + + +def extract_read_writes( + fn: Callable, + *argsizes: Tuple[sympy.Expr, ...], + normalize: bool = False, + prefix: str = "d", +): + args, var_ranges = index_vars_squeeze(*argsizes, prefix=prefix) + rw = RecordLoadStore(var_ranges, normalize=normalize) + with V.set_ops_handler(rw): # type: ignore[call-arg] + fn(*args) + + if normalize: + range_vars = [] # Number of vars could differ due to normalization + else: + range_vars = [*itertools.chain(*args)] + + inner = rw.parent_handler.parent_handler + return ReadWrites( + set(inner._reads), + set(inner._writes), + inner._index_exprs, + range_vars, + var_ranges, + rw.parent_handler._op_counts, + ) + + +def canonicalization_prefix(): + return "c" diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/exc.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/exc.py new file mode 100644 index 0000000000000000000000000000000000000000..7da7fe67d8e87cd54e88275406b7ad8b40684bf2 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/exc.py @@ -0,0 +1,87 @@ +import os +import tempfile +import textwrap +from functools import lru_cache + +if os.environ.get("TORCHINDUCTOR_WRITE_MISSING_OPS") == "1": + + @lru_cache(None) + def _record_missing_op(target): + with open(f"{tempfile.gettempdir()}/missing_ops.txt", "a") as fd: + fd.write(str(target) + "\n") + +else: + + def _record_missing_op(target): + pass + + +class OperatorIssue(RuntimeError): + @staticmethod + def operator_str(target, args, kwargs): + lines = [f"target: {target}"] + [ + f"args[{i}]: {arg}" for i, arg in enumerate(args) + ] + if kwargs: + lines.append(f"kwargs: {kwargs}") + return textwrap.indent("\n".join(lines), " ") + + +class MissingOperatorWithoutDecomp(OperatorIssue): + def __init__(self, target, args, kwargs): + _record_missing_op(target) + super().__init__(f"missing lowering\n{self.operator_str(target, args, kwargs)}") + + +class MissingOperatorWithDecomp(OperatorIssue): + def __init__(self, target, args, kwargs): + _record_missing_op(target) + super().__init__( + f"missing decomposition\n{self.operator_str(target, args, kwargs)}" + + textwrap.dedent( + f""" + + There is a decomposition available for {target} in + torch._decomp.get_decompositions(). Please add this operator to the + `decompositions` list in torch._inductor.decompositions + """ + ) + ) + + +class LoweringException(OperatorIssue): + def __init__(self, exc, target, args, kwargs): + super().__init__( + f"{type(exc).__name__}: {exc}\n{self.operator_str(target, args, kwargs)}" + ) + + +class InvalidCxxCompiler(RuntimeError): + def __init__(self): + from . import config + + super().__init__( + f"No working C++ compiler found in {config.__name__}.cpp.cxx: {config.cpp.cxx}" + ) + + +class CppCompileError(RuntimeError): + def __init__(self, cmd, output): + if isinstance(output, bytes): + output = output.decode("utf-8") + + super().__init__( + textwrap.dedent( + """ + C++ compile error + + Command: + {cmd} + + Output: + {output} + """ + ) + .strip() + .format(cmd=" ".join(cmd), output=output) + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/fx_utils.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/fx_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..15934caeaf271bf17d59d18cf579d5ca42afac50 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/fx_utils.py @@ -0,0 +1,30 @@ +import torch + + +# Check the pattern: (nn.module, F.function/torch.Tensor.method) matched. +# Works for length 2 patterns with 1 module and 1 function/method. +def matches_module_function_pattern(pattern, node, modules): + if len(node.args) == 0: + return False + if not isinstance(node.args[0], torch.fx.Node) or not isinstance( + node, torch.fx.Node + ): + return False + # the first node is call_module + if node.args[0].op != "call_module": + return False + if not isinstance(node.args[0].target, str): + return False + if node.args[0].target not in modules: + return False + if type(modules[node.args[0].target]) is not pattern[0]: + return False + # the second node is call_function or call_method + if node.op != "call_function" and node.op != "call_method": + return False + if node.target != pattern[1]: + return False + # make sure node.args[0] output is only used by current node. + if len(node.args[0].users) > 1: + return False + return True diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/graph.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/graph.py new file mode 100644 index 0000000000000000000000000000000000000000..4eabf793a9b04438d8cc49ebe3bbaa2edef47e66 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/graph.py @@ -0,0 +1,988 @@ +import hashlib +import logging +import operator +import os +import re +import sys +import time +from collections import defaultdict +from contextlib import contextmanager +from typing import DefaultDict, Dict, List, Optional, Set, Tuple + +import sympy + +import torch +import torch._logging +import torch.fx +from torch._decomp import get_decompositions +from torch._dynamo.utils import dynamo_timed +from torch.fx.experimental.symbolic_shapes import ( + free_symbols, + magic_methods, + method_to_operator, + ShapeEnv, + SymTypes, +) +from torch.utils._mode_utils import no_dispatch + +from . import config, ir, metrics +from .codegen.common import ( + get_scheduling_for_device, + get_wrapper_codegen_for_device, + register_backend_for_device, +) +from .codegen.wrapper import CppWrapperCodeGen, CudaWrapperCodeGen, WrapperCodeGen +from .exc import ( + LoweringException, + MissingOperatorWithDecomp, + MissingOperatorWithoutDecomp, +) +from .ir import Constant, FixedLayout, InputBuffer, Pointwise, Reduction, TensorBox +from .lowering import ( + FALLBACK_ALLOW_LIST, + fallback_handler, + fallback_node_due_to_unsupported_type, + layout_constraints, + lowerings, + make_fallback, + needs_realized_inputs, + unsupported_output_tensor, +) +from .sizevars import SizeVarAllocator +from .utils import convert_shape_to_inductor, gather_origins, get_sympy_Expr_dtype +from .virtualized import V + +log = logging.getLogger(__name__) +perf_hint_log = torch._logging.getArtifactLogger(__name__, "perf_hints") +output_code_log = torch._logging.getArtifactLogger(__name__, "output_code") + + +def supported_dtype_of_cpp_wrapper(dtype, cuda): + supported_dtype = { + torch.float32, + torch.float64, + torch.int64, + torch.int32, + torch.int16, + torch.int8, + torch.uint8, + torch.bool, + torch.bfloat16, + torch.complex64, + # torch.float16, # TODO: implement this + } + if cuda: + supported_dtype.add(torch.float16) + + return dtype in supported_dtype + + +def may_get_constant_buffer_dtype(constant_buffer): + assert isinstance( + constant_buffer, (sympy.Symbol, sympy.Expr, sympy.core.numbers.Integer) + ), "get_constant_buffer_dtype only supports input of sympy.Symbol, sympy.Expr or sympy.core.numbers.Integer" + if isinstance(constant_buffer, sympy.core.numbers.Integer): + return torch.int64 + + if isinstance(constant_buffer, sympy.Expr): + return get_sympy_Expr_dtype(constant_buffer) + + if constant_buffer.is_integer: + return torch.int64 + elif constant_buffer.is_float: + return torch.float32 + else: + return None + + +def is_magic_method(op): + magic_ops = {method_to_operator(m) for m in magic_methods} + return op in magic_ops + + +class GraphLowering(torch.fx.Interpreter): + def symbolic_sizes_strides(self, ex: torch.Tensor): + """ + Support dynamic shapes and dynamic strides by assigning variables + to each dimension. We duck-shape tensors, so if two tensors + have the same size they get assigned the same symbolic variable. + """ + if self.reuse_shape_env: + return convert_shape_to_inductor(ex.size()), convert_shape_to_inductor( + ex.stride() + ) + else: + from torch._dynamo.source import ConstantSource + + # TODO: this should not be needed once #93059 lands + # https://github.com/pytorch/pytorch/pull/94031#discussion_r1096044816 + # TODO: make a dedicated UnknownSource for this? + # NB: This is using the legacy default behavior from + # create_symbolic_sizes_strides_storage_offset but we hope we can + # just delete this entirely + source = ConstantSource( + f"__inductor_unknown_tensor_{len(self._shape_env.var_to_val)}" + ) + ( + size, + stride, + _, + ) = self._shape_env.create_symbolic_sizes_strides_storage_offset( + ex, + source, + ) + + size = [i.node.expr if isinstance(i, torch.SymInt) else i for i in size] + stride = [i.node.expr if isinstance(i, torch.SymInt) else i for i in stride] + return size, stride + + def static_sizes_strides(self, ex: torch.Tensor): + """ + Primarily used to weights + """ + size = [sympy.Integer(i) for i in ex.size()] + stride = [sympy.Integer(i) for i in ex.stride()] + return size, stride + + def init_backend_registration(self): + if get_scheduling_for_device("cpu") is None: + from .codegen.cpp import CppScheduling + + register_backend_for_device("cpu", CppScheduling, WrapperCodeGen) + + if get_scheduling_for_device("cuda") is None: + from .codegen.triton import TritonScheduling + + register_backend_for_device("cuda", TritonScheduling, WrapperCodeGen) + + def __init__( + self, + gm: torch.fx.GraphModule, + shape_env=None, + num_static_inputs=None, + graph_id=None, + cpp_wrapper=False, + aot_mode=False, + user_visible_outputs=frozenset(), + layout_opt=None, + ): + super().__init__(gm) + + self.layout_opt = ( + layout_opt if layout_opt is not None else self.decide_layout_opt(gm) + ) + self.num_channels_last_conv = 0 + + self.extra_traceback = False # we do our own error wrapping + if shape_env is None: + shape_env = ShapeEnv() + self.reuse_shape_env = False + else: + self._shape_env = shape_env + self.reuse_shape_env = True + self._shape_env = shape_env + self.sizevars = SizeVarAllocator(shape_env) + self.graph_inputs: Dict[str, TensorBox] = {} + self.graph_inputs_original: Dict[str, InputBuffer] = {} + self.graph_outputs: Optional[List[ir.IRNode]] = None + self.device_types: Set[str] = set() + self.device_idxs: Set[int] = set() + self.cuda = False + self.buffers: List[ir.ComputedBuffer] = [] + self.constants: Dict[str, torch.Tensor] = {} + self.constant_reprs: Dict[str, str] = {} + self.removed_buffers: Set[str] = set() + self.removed_inplace_buffers: Set[str] = set() + self.mutated_buffers: Set[str] = set() + self.inplaced_to_remove: Set[str] = set() + self.wrapper_code: Optional[WrapperCodeGen] = None + self.current_node: Optional[torch.fx.Node] = None + self.num_static_inputs = num_static_inputs + self.lists: Dict[str, List[str]] = {} + self.mutated_inputs: Set[str] = set() + self.mutated_input_idxs: List[int] = [] + self.unaligned_buffers: Set[str] = set() + self.name_to_buffer: Dict[str, ir.ComputedBuffer] = {} + self.name_to_users: DefaultDict[str, List[ir.IRNode]] = defaultdict(list) + self.creation_time = time.time() + self.name = "GraphLowering" + self.cpp_wrapper = cpp_wrapper + self.aot_mode = aot_mode + self.graph_id = graph_id + self.scheduler = None + self.nodes_prefer_channels_last = ( + self.find_nodes_prefer_channels_last() if self.layout_opt else set() + ) + self._warned_fallback = {"aten.convolution_backward"} + self.user_visible_outputs = user_visible_outputs + self.cache_key: str = "" # This is the cache key for the compiled artifact + self.cache_path: str = "" # This is the path in the filesystem where the compiled artifact is stored + self.cache_linemap: List[ + Tuple[int, str] + ] = ( + [] + ) # This is the linemap used by the profiler to mark custom compiled kernels getting run + # Used if lowering encounters cases where cudagraphs are not supported + self.disable_cudagraphs = False + self.init_backend_registration() + + @staticmethod + def decide_layout_opt(gm) -> bool: + """ + Decide if we should enable layout optimization for this graph based on + heuristics. + """ + if not config.layout_optimization: + return False + + conv_nodes = [ + n for n in gm.graph.nodes if n.target == torch.ops.aten.convolution.default + ] + nconv = len(conv_nodes) + + if nconv == 0: + return False + + # Currently on ROCm we are seeing some slow downs in gcnArch that do not + # have optimal NHWC implementations. On ROCm MI200 series we will + # default to the enforced last channels behavior, but on non-MI200 series + # we will disable the forced layout. + if torch.version.hip and torch.cuda.is_available(): + gpu_name = torch.cuda.get_device_name(0) + if not re.search(r"MI2\d\d", gpu_name): + return False + + # For cpu backend and mkldnn enabled, we always using channels_last for a better performance. + if ( + all( + n.args[idx].meta["val"].device == torch.device("cpu") + for n in conv_nodes + for idx in [0, 1] + ) + and torch.backends.mkldnn.enabled + and torch.backends.mkldnn.is_available() + ): + return True + + # Followering models are skipped due to this: + # jx_nest_base + # volo_d1_224 + if len(list(gm.graph.nodes)) >= 300 * nconv: + log.debug("Only a few conv, skip layout optimization") + return False + + if any( + free_symbols(n.args[idx].meta["val"]) for n in conv_nodes for idx in [0, 1] + ): + log.debug( + "See perf regression with dynamic shape. Follow up in https://github.com/pytorch/pytorch/issues/102670" + ) + return False + + # Channels last layout can dramatically hurt grouped conv perf. E.g. + # Conv with arguments like + # {"input_shape": [32, 224, 112, 112], "weight_shape": [224, 112, 3, 3], + # "stride": [2, 2], "padding": [1, 1], "groups": 2} + # slows down 31x using channels last.. + + # But a lot of timm models use depthwise separable convolution which will + # result in grouped convolution with in-channel size == 1. + # For those grouped convolution, channels last still helps a lot. + # E.g. + # Conv with arguments + # {"input_shape": [128, 58, 56, 56], "weight_shape": [58, 1, 3, 3], + # "stride": [2, 2], "padding": [1, 1], "groups": 58} + # get 1.86x speedup with channels last layout. + # + # The following heuristics skip using channels-last if the model contains + # grouped convolution with in-channels > 1. + if any( + n.args[-1] > 1 and n.args[1].meta["val"].size(1) > 1 for n in conv_nodes + ): + log.debug("Found grouped convolution with >1 in_channels!") + return False + + # For some models that contain convolution with larger in-channel than out-channel, applying + # channels last hurts performance. + # Following models are skipped due to this: + # - pytorch_unet + # - phlippe_densenet (slightly worse) + # - Background_Matting (1.22x -> 0.821x) + # - pytorch_CycleGAN_and_pix2pix (1.597x -> 1.294x) + if any( + n.args[1].meta["val"].size(0) * 2 <= n.args[1].meta["val"].size(1) + and n.args[1].meta["val"].size(2) > 1 + for n in conv_nodes + ): + log.debug( + "Skip layout optimization because some convolutions have smaller out_channel" + ) + return False + + # Following models are skipped due to this: + # - functorch_maml_omniglot + if all( + n.args[1].meta["val"].size(0) <= 64 and n.args[1].meta["val"].size(1) <= 64 + for n in conv_nodes + ): + log.debug("Skip layout opt because all convolution channels are too small") + return False + + # aten._scaled_dot_product_flash_attention requires the last stride of query/key/value + # to be 1. Check https://gist.github.com/shunting314/fa6eeab2aad8d1265c4d5e50b560d94f + # for more details. + # + # When a model contains aten._scaled_dot_product_flash_attention and we enable layout optimization, + # the op may get channels last input and fail. Example include: twins_pcpvt_base, xcit_large_24_p8_224 + # for _scaled_dot_product_flash_attention and xcit_large_24_p8_224 for _scaled_dot_product_efficient_attention. + # + # We disable layout optimization if a model contains aten._scaled_dot_product_flash_attention. + # + # An alternative is to do necessary layout convertion to make sure aten._scaled_dot_product_flash_attention's + # inputs have the layout needed. But that seems to have worse perf than disabing the layout opt. + # TODO(shunting) revisit if we can still apply layout optimization to models containing sdpa while + # bringing perf gains. + for n in gm.graph.nodes: + if n.target in ( + torch.ops.aten._scaled_dot_product_flash_attention.default, + torch.ops.aten._scaled_dot_product_efficient_attention.default, + ): + log.debug( + "Skip layout optimization because sdpa (scaled dot product attention) is found" + ) + return False + + return True + + def find_nodes_prefer_channels_last(self): + """ + The rule to decide if an node prefer channels last is simple. + 1. if it's input/output of a convolution + 2. if one of its user prefers channels last + + We have rule 1 because cudnn runs a faster convolution kernel for channels last inputs; + Rule 2 is also important. It makes sure that indirect inputs to convolution also prefers + channels last. + + Consider the scenario: conv -> batch-norm -> relu -> conv + Without rule 2, batch-norm output may use a contiguous layout. That will cause 2 extra copies: + 1. the output of batch-norm should be channels last initially since its input is a conv's output. + Forcing the batch-norm's output to be contiguous results in the first copy + 2. The second conv's input is initially contiguous. This layout is propagated from the batch-norm's output. + We need convert it to channels last layout which results in the second copy. + With rule 2, we makes sure all the tensors in the chain uses channels last layout. So both copies + can be saved. + """ + output_set = set() + for n in reversed(self.module.graph.nodes): + if n.target == torch.ops.aten.convolution.default: + output_set.add(n) + continue + + for user in n.users: + if user in output_set: + output_set.add(n) + break + + # need a second pass to add downstream nodes of those channel last nodes to the sets. + # This pass is especially needed to avoid mix-layout kernel inputs in backward pass. + # + # Let's say a conv-batchnorm 's output is passed to relu whose output is in turn returned + # from the fwd graph. Without this second pass, we will force relu's output to be contiguous. + # Then in the kernel in backward pass, the contiguous output of relu may be mix with other channels last + # tensors and passed to a kernel. + # + # This pass improve yolov3 training speedup from 1.116x (worse than disabling layout optimization speedup 1.196x) to 1.457x. + # It also improves dla102 training speedup from 1.240x (worse than disabling layout optimization speedup 1.523x) to 1.835x . + # This also helps the following models: + # - res2net101_26w_4s + # - res2net50_14w_8s + # - sebotnet33ts_256 + for n in self.module.graph.nodes: + if n in output_set: + for child in n.users: + output_set.add(child) + + return output_set + + def warn_fallback(self, name): + if name not in self._warned_fallback: + self._warned_fallback.add(name) + perf_hint_log.info("Using FallbackKernel: %s", name) + + def add_device_idx(self, idx: Optional[int]): + if idx is not None: + self.device_idxs.add(idx) + + @property + def fake_mode(self): + return V.fake_mode + + def get_buffer(self, buffer_name: str): + if buffer_name in self.name_to_buffer: + return self.name_to_buffer[buffer_name] + if buffer_name in self.graph_inputs: + return self.graph_inputs[buffer_name] + return None + + def get_dtype(self, buffer_name: str): + if buffer_name in self.constants: + return self.constants[buffer_name].dtype + if buffer_name in self.name_to_buffer: + return self.name_to_buffer[buffer_name].get_dtype() + if buffer_name in self.graph_inputs: + return self.graph_inputs[buffer_name].get_dtype() + m = re.match(r"(as_strided|reinterpret_tensor)\(([a-zA-Z0-9_]+),", buffer_name) + if m: + return self.get_dtype(m.group(1)) + raise KeyError(f"could not find {buffer_name}") + + def get_numel(self, buffer_name: str): + from .ir import MultiOutputLayout + + if buffer_name in self.constants: + return self.constants[buffer_name].numel() + if buffer_name in self.name_to_buffer: + buf = self.name_to_buffer[buffer_name] + if isinstance(getattr(buf, "layout", None), MultiOutputLayout): + return 1 + return buf.get_numel() + if buffer_name in self.graph_inputs: + return self.graph_inputs[buffer_name].get_numel() + raise KeyError(f"could not find {buffer_name}") + + @dynamo_timed + def run(self, *args): + return super().run(*args) + + def disable_cpp_wrapper(self, cond): + metrics.disable_cpp_wrapper += 1 + self.cpp_wrapper = False + log.debug("Set cpp_wrapper to False due to %s", cond) + + def register_buffer(self, buffer: ir.ComputedBuffer): + name = f"buf{len(self.buffers)}" + self.buffers.append(buffer) + self.name_to_buffer[name] = buffer + return name + + def register_list(self, buffer_names: List[str]): + name = "list_" + "_".join(buffer_names) + self.lists[name] = buffer_names + return name + + def register_users_of(self, node_output): + def register(value): + if isinstance(value, (list, tuple)): + for x in value: + register(x) + if isinstance(value, ir.IRNode): + if ( + not hasattr(value, "data") + or not isinstance(value.data, ir.IRNode) + or not isinstance(value.data.data, ir.IRNode) + ): + return + + for read_name in value.get_read_names(): + self.name_to_users[read_name].append(value) + + register(node_output) + + def mark_buffer_mutated(self, name: str): + """ + When a buffer is mutated we need to make sure all the reads to + the old version are realized before the mutation happens. + """ + assert isinstance(name, str) + self.mutated_buffers.add(name) + + if name not in self.name_to_users: + return + + for user in self.name_to_users[name]: + user.realize() + + def add_tensor_constant(self, data): + def allocate(): + for name, value in self.constants.items(): + if ( + not data.is_mkldnn + and data.size() == value.size() + and data.stride() == value.stride() + and data.dtype == value.dtype + and data.device == value.device + and torch.eq(data, value).all() + ): + return name + name = f"constant{len(self.constants)}" + self.constants[name] = data + self.constant_reprs[name] = hashlib.sha256( + repr(data).encode("utf-8") + ).hexdigest() + return name + + return TensorBox.create( + ir.ConstantBuffer( + allocate(), + FixedLayout(data.device, data.dtype, *self.static_sizes_strides(data)), + ) + ) + + def constant_name(self, name: str, device_override: torch.device): + """ + We AOT copy constants to the devices they are needed on. + If device_override doesn't match the constant's device, then + copy it and return a different name. + """ + if self.constants[name].device == device_override or device_override is None: + return name + alt_name = f"{name}_{device_override.type}{device_override.index or 0}" + if alt_name not in self.constants: + self.constants[alt_name] = self.constants[name].to(device_override) + return alt_name + + def placeholder(self, target: str, args, kwargs): + example = super().placeholder(target, args, kwargs) + if isinstance(example, SymTypes): + expr = example.node.expr + self.graph_inputs[target] = expr + return expr + elif isinstance(example, (int, bool, float)): + expr = sympy.sympify(example) + self.graph_inputs[target] = expr + return expr + assert isinstance(example, torch.Tensor), example + # todo(chilli): We can remove the last check once we turn buffers into + # static shape tensors. That's a hack to workaround Inductor believing + # the buffer should be static but us passing in a fake tensor with + # symbolic shapes. + if not example._has_symbolic_sizes_strides: + # the first N inputs are weights + sizes, strides = self.static_sizes_strides(example) + else: + sizes, strides = self.symbolic_sizes_strides(example) + # TODO(jansel): handle input aliasing + tensor = TensorBox.create( + InputBuffer( + target, + FixedLayout(example.device, example.dtype, sizes, strides), + ) + ) + self.graph_inputs[target] = tensor + self.graph_inputs_original[target] = tensor.data.data + self.device_types.add(example.device.type) + self.add_device_idx(example.device.index) + return tensor + + def call_function(self, target, args, kwargs): + if target is operator.getitem and isinstance(args[0], (list, tuple)): + return super().call_function(target, args, kwargs) + + if hasattr(target, "_inductor_lowering_function"): + # passthrough lowerings from .pattern_matcher + return target(*args, **kwargs) + + if target not in lowerings: + base_name = target.name().split(".")[0] + if base_name in FALLBACK_ALLOW_LIST: + make_fallback(target) + elif config.implicit_fallbacks: + error = ( + MissingOperatorWithDecomp + if get_decompositions([target]) + else MissingOperatorWithoutDecomp + ) + log.info( + "Creating implicit fallback for:\n%s", + error.operator_str(target, args, kwargs), + ) + make_fallback(target) + elif get_decompositions([target]): + # There isn't a good way to dynamically patch this in + # since AOT Autograd already ran. The error message tells + # the user how to fix it. + raise MissingOperatorWithDecomp(target, args, kwargs) + else: + raise MissingOperatorWithoutDecomp(target, args, kwargs) + + try: + out = lowerings[target](*args, **kwargs) + return out + except Exception as e: + raise LoweringException(e, target, args, kwargs).with_traceback( + e.__traceback__ + ) from None + + def get_attr(self, target, args, kwargs): + # this is a constant + value = getattr(self.module, target) + + if unsupported_output_tensor(value): + return self.add_tensor_constant(value) + + with no_dispatch(): + if value.shape == (): + return Constant(value.item(), value.dtype, value.device) + if len(value.shape) == 1 and value.shape[0] <= 8: + # tensor lowering has constant inlining logic + from .lowering import tensor + + return tensor(value.tolist(), dtype=value.dtype, device=value.device) + + return self.add_tensor_constant(value) + + def call_module(self, target, args, kwargs): + raise AssertionError() + + def call_method(self, target, args, kwargs): + raise AssertionError() + + def output(self, target, args, kwargs): + result = super().output(target, args, kwargs) + assert isinstance(result, (tuple, list)), type(result) + assert all( + isinstance( + x, + ( + TensorBox, + ir.Constant, + type(None), + ir.ConstantBuffer, + sympy.Expr, + sympy.logic.boolalg.Boolean, + int, + ), + ) + for x in result + ), result + self.graph_outputs = [ir.ExternKernel.realize_input(x) for x in result] + value: ir.IRNode + for name, value in self.graph_inputs.items(): + assert isinstance(value, (TensorBox, sympy.Expr)) + if not isinstance(value, TensorBox): + continue + value.realize() + assert isinstance(value, TensorBox) + value = value.data + assert isinstance(value, ir.StorageBox) + value_storage_box = value + value = value.data + if not isinstance(value, InputBuffer) or value.get_name() != name: + # one of our inputs was mutated, need to turn that into a copy + ir.MutationLayout.realize_into(value, self.graph_inputs_original[name]) + # replace output with mutated input + try: + ind = self.graph_outputs.index(value_storage_box) + self.graph_outputs[ind] = self.graph_inputs_original[name] + except ValueError: + pass + + self.finalize() + log.debug( + "Force channels last inputs for %d conv for the current graph with id %d", + self.num_channels_last_conv, + self.graph_id, + ) + + def finalize(self): + for buf in self.buffers: + buf.decide_layout() + + def run_node(self, n: torch.fx.Node): + origins = {n} + if n.op == "call_function": + args, kwargs = self.fetch_args_kwargs_from_env(n) + origins |= gather_origins(args, kwargs) + with ir.IRNode.current_origins(origins), self.set_current_node(n): + if ( + n.op == "call_function" + and n.target is not operator.getitem + and fallback_node_due_to_unsupported_type(n) + ): + result = fallback_handler(n.target, add_to_fallback_set=False)( + *args, **kwargs + ) + elif n.op == "call_function" and n.target in layout_constraints: + args, kwargs = layout_constraints[n.target](n, *args, **kwargs) + result = self.call_function(n.target, args, kwargs) + elif n.target == torch.ops.aten.sym_stride: + # inductor graphs can occasionally return sizes/strides, + # e.g. if we need to save symints for the backward graph. + if isinstance(n.meta["val"], torch.SymInt): + result = n.meta["val"].node.expr + else: + result = super().run_node(n) + elif is_magic_method(n.target): + if isinstance(n.meta["val"], torch.SymInt): + result = n.meta["val"].node.expr + else: + result = super().run_node(n) + else: + result = super().run_node(n) + + # require the same stride order for dense outputs, + # 1. user-land view() will not throw because inductor + # output different strides than eager + # long term the solution is to make view() always succeed + # with infallible strides. + # 2: as_strided ops, we need make sure its input has same size/stride with + # eager model to align with eager behavior. + as_strided_ops = [ + torch.ops.aten.as_strided.default, + torch.ops.aten.as_strided_.default, + torch.ops.aten.as_strided_scatter.default, + ] + is_output = any(user.op == "output" for user in n.users) + is_input_for_as_strided = any( + user.target in as_strided_ops for user in n.users + ) + if (is_output or is_input_for_as_strided) and isinstance( + n.meta["val"], torch.Tensor + ): + strides = n.meta["val"].stride() + dense = torch._prims_common.is_non_overlapping_and_dense(n.meta["val"]) + # requiring a stride order for a non-dense output wouldn't + # recreate the same strides, and would fail with view, defer for now. + if dense and len(strides): + stride_order = ir.get_stride_order(strides) + if ( + len(result.get_size()) == 4 + and n in self.nodes_prefer_channels_last + and n.name not in self.user_visible_outputs + and not is_input_for_as_strided + ): + stride_order = ir.NHWC_STRIDE_ORDER + result = ir.ExternKernel.require_stride_order(result, stride_order) + + # Realize if (1) any user need inputs realized, or (2) there is + # already too many reads and rematerializing can be bad. + num_users = len(set(n.users)) + if num_users > 1 and isinstance(result, TensorBox): + for user in n.users: + if user.target in needs_realized_inputs: + result.realize_hint() + # This inclusion is somewhat controversial (from + # discussion between Horace, Natalia, and Elias). + # Currently, it's not very clear why this is helpful. + # The general idea here is that even though a node may + # have FlexibleLayout, we still often *treat* it as if + # it was contiguous. This appears to sometimes result in + # suboptimal behavior. + # + # When we do a better job selecting layout, we should + # revisit this. + need_fixed_layout = [ + torch.ops.aten.convolution_backward.default, + torch.ops.aten.mm.default, + torch.ops.aten._int_mm.default, + ] + if not self.layout_opt: + need_fixed_layout.append(torch.ops.aten.convolution.default) + if torch._C._has_mkldnn: + need_fixed_layout += [ + torch.ops.mkldnn._convolution_pointwise.default, + torch.ops.mkldnn._convolution_pointwise.binary, + torch.ops.mkldnn._convolution_pointwise_.binary, + torch.ops.mkldnn._convolution_transpose_pointwise.default, + torch.ops.mkldnn._linear_pointwise.default, + torch.ops.mkldnn._linear_pointwise.binary, + torch.ops.aten.mkldnn_rnn_layer.default, + torch.ops.onednn.qconv2d_pointwise.default, + torch.ops.onednn.qconv2d_pointwise.binary, + torch.ops.onednn.qlinear_pointwise.default, + ] + if torch._C.has_mkl: + need_fixed_layout += [torch.ops.mkl._mkl_linear.default] + if user.target in need_fixed_layout: + result = ir.ExternKernel.require_stride_order( + result, ir.get_stride_order(n.meta["val"].stride()) + ) + if user.op == "output": + if isinstance(result.data.data, (Pointwise, Reduction)): + result.realize() + + # TODO(jansel): introduce a store vs inline choice + result.mark_reuse(len(n.users)) + + # Realize if the IRNode already has accumulated lots of reads + if isinstance(result, TensorBox) and result.has_exceeded_max_reads(): + # Prevent excessive accumulation in a computed buffer, when + # there are multiple branches each with small number of memory + # reads, but they converge to a user. + result.realize_hint() + + # This is not complete, but it doesn't have to be: origin_node + # tracking is best effort. The logic here critically relies on direct + # TensorBox -> StorageBox denoting a non-view; we don't bother trying + # to get views to work. Feel free to add any extra cases as needed. + # + # Note: we can't YOLO tree_map over this result, because if there are + # buffers or a view involved, we might not be able to validly assign + # the origin_node here. + if isinstance(result, TensorBox) and isinstance(result.data, ir.StorageBox): + if isinstance(result.data.data, ir.Loops): + result.data.data.origin_node = n + elif isinstance(result.data.data, ir.Buffer): + result.data.data.origin_node = n + if isinstance(result.data.data, ir.ComputedBuffer) and isinstance( + result.data.data.data, ir.Loops + ): + result.data.data.data.origin_node = n + # Not really multi-output, can straightforwardly recurse in + elif ( + isinstance(result.data.data, ir.MultiOutput) + and not result.data.data.indices + ): + if isinstance(result.data.data.inputs[0], ir.Buffer): + result.data.data.inputs[0].origin_node = n + + self.register_users_of(result) + + return result + + def check_cpp_codegen_disabled(self): + if config.disable_cpp_codegen: + self.disable_cpp_wrapper("cpp codegen disabled") + + def check_platform(self): + if sys.platform != "linux": + self.disable_cpp_wrapper("platform not linux") + + def check_input_for_cpp_buffer(self): + for value in self.graph_inputs.values(): + dtype = None + if isinstance(value, TensorBox): + dtype = value.get_dtype() + elif isinstance( + value, (sympy.Symbol, sympy.Expr, sympy.core.numbers.Integer) + ): + dtype = may_get_constant_buffer_dtype(value) + + if not supported_dtype_of_cpp_wrapper(dtype, self.cuda): + self.disable_cpp_wrapper("unsupported inputs dtype") + + @contextmanager + def set_current_node(self, node: torch.fx.Node): + old = self.current_node + try: + self.current_node = node + yield + finally: + self.current_node = old + + def check_cpp_wrapper(self): + self.check_cpp_codegen_disabled() + self.check_platform() + self.check_input_for_cpp_buffer() + + def init_wrapper_code(self): + self.cuda = "cuda" in self.device_types + if self.cpp_wrapper: + self.check_cpp_wrapper() + # Re-check self.cpp_wrapper because it might be disabled due to failed checking + if self.cuda: + assert self.cpp_wrapper, "CudaWrapperCodeGen hit unsupported case" + + if self.cpp_wrapper: + self.wrapper_code = ( + CudaWrapperCodeGen() if self.cuda else CppWrapperCodeGen() + ) + return + + device_types = self.device_types.copy() + # In terms of some operations that don't have input tensors, we need to + # check the deivce of the buffers. + for buffer in self.buffers: + device_types.add(buffer.get_device().type) + device_types.discard("cpu") + # TODO(Eikan): Only support mixing cpu and other device now. + assert len(device_types) <= 1, "Does not support mixing {}".format( + "+".join(device_types) + ) + only_cpu = len(device_types) == 0 + device_type = "cpu" if only_cpu else device_types.pop() + wrapper_code_gen_cls = get_wrapper_codegen_for_device(device_type) + self.wrapper_code = wrapper_code_gen_cls() + + def codegen(self): + from .scheduler import Scheduler + + self.init_wrapper_code() + + self.scheduler = Scheduler(self.buffers) + assert self.scheduler is not None # mypy can't figure this out + self.scheduler.codegen() + assert self.wrapper_code is not None + return self.wrapper_code.generate() + + def count_bytes(self): + from .scheduler import Scheduler + + scheduler = Scheduler(self.buffers) + + total_bytes = 0 + node_counts = [] + node_runtimes = [] + for node in scheduler.nodes: + num_bytes = node.get_read_write_buffers_sizes() + total_bytes += num_bytes + node_counts.append((node, num_bytes // 4)) + node_runtimes.append((node, node.get_estimated_runtime())) + return total_bytes, node_counts, node_runtimes + + @dynamo_timed + def compile_to_module(self): + from .codecache import PyCodeCache + + code, linemap = self.codegen() + linemap = [(line_no, node.stack_trace) for line_no, node in linemap] + key, path = PyCodeCache.write(code) + mod = PyCodeCache.load_by_key_path(key, path, linemap=linemap) + self.cache_key = key + self.cache_path = path + self.cache_linemap = linemap + + for name, value in self.constants.items(): + setattr(mod, name, value) + + # Logged twice as per https://github.com/pytorch/pytorch/pull/99038#discussion_r1167826029 + # TODO. Revisit this once the logging API is more mature + output_code_log.info("Output code written to: %s", mod.__file__) + log.debug("Output code written to: %s", mod.__file__) + output_code_log.debug("Output code: \n%s", code) + if config.benchmark_kernel: + print(f"Compiled module path: {mod.__file__}", file=sys.stderr) + V.debug.output_code(mod.__file__) + V.debug.copy(os.path.splitext(mod.__file__)[0] + ".debug") + return mod + + def compile_to_fn(self): + if self.aot_mode and self.cpp_wrapper: + from .codecache import AotCodeCache + + code, linemap = self.codegen() + output_code_log.debug("Output code: \n%s", code) + + # Directly return the file path with the compiled code + return AotCodeCache.compile(self, code, cuda=self.cuda) + else: + return self.compile_to_module().call + + def get_output_names(self): + assert self.graph_outputs is not None + return [ + node.get_name() + for node in self.graph_outputs + if not isinstance(node, ir.NoneAsConstantBuffer) + and not isinstance(node, ir.ShapeAsConstantBuffer) + ] + + def is_unspec_arg(self, name: str): + # dynamo wraps unspec variable as 0d CPU tensor, + # need to convert to scalar during codegen (triton only) + return ( + name in self.graph_inputs.keys() + and self.graph_inputs[name].get_numel() == 1 + and self.graph_inputs[name].get_device().type == "cpu" + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/hooks.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..2b7eba55ba8b9ad1e5f08812e7052fb54d4739ed --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/hooks.py @@ -0,0 +1,24 @@ +import contextlib + +# Executed in the order they're registered +INTERMEDIATE_HOOKS = [] + + +@contextlib.contextmanager +def intermediate_hook(fn): + INTERMEDIATE_HOOKS.append(fn) + try: + yield + finally: + INTERMEDIATE_HOOKS.pop() + + +def run_intermediate_hooks(name, val): + global INTERMEDIATE_HOOKS + hooks = INTERMEDIATE_HOOKS + INTERMEDIATE_HOOKS = [] + try: + for hook in hooks: + hook(name, val) + finally: + INTERMEDIATE_HOOKS = hooks diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/inductor_prims.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/inductor_prims.py new file mode 100644 index 0000000000000000000000000000000000000000..9b45b5ff95b8016ab51bbd3320236d9a9cf0cae9 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/inductor_prims.py @@ -0,0 +1,73 @@ +import logging + +import torch +from torch import _prims + +log = logging.getLogger(__name__) + + +def make_prim( + schema, + impl_aten, + return_type=_prims.RETURN_TYPE.NEW, + doc="", + tags=None, +): + def meta(*args, **kwargs): + return _prims.TensorMeta(impl_aten(*args, **kwargs)) + + return _prims._make_prim( + schema=schema, + return_type=return_type, + meta=meta, + impl_aten=impl_aten, + doc=doc, + tags=tags, + ) + + +def eager_force_stride(input_tensor, stride): + if input_tensor.stride() == stride: + return input_tensor + new_tensor = input_tensor.clone().as_strided( + input_tensor.shape, + stride, + ) + new_tensor.copy_(input_tensor) + return new_tensor + + +# Custom prims used for handling randomness +seed = make_prim( + "inductor_seed(Device device) -> Tensor", + lambda device: torch.randint(2**63 - 1, [], device=device), + doc="create a fresh seed (one per call) for use with inductor_rand", + tags=(torch.Tag.nondeterministic_seeded,), +) +seeds = make_prim( + "inductor_seeds(int count, Device device) -> Tensor", + lambda count, device: torch.randint(2**63 - 1, [count], device=device), + doc="Horizontally fusion of many inductor_seed() calls", + tags=(torch.Tag.nondeterministic_seeded,), +) +lookup_seed = make_prim( + # if inductor_lookup_seed changes, update partitioners.py + "inductor_lookup_seed(Tensor seeds, int index) -> Tensor", + lambda seeds, index: seeds[index], + doc="Extract a single seed from the result of inductor_seeds()", +) +random = make_prim( + "inductor_random(SymInt[] size, Tensor seed, str mode) -> Tensor", + lambda size, seed, mode: getattr(torch, mode)(size, device=seed.device), + doc="torch.rand()/torch.randn() using backend-specific RNG that can be fused", +) +randint = make_prim( + "inductor_randint(SymInt low, SymInt high, SymInt[] size, Tensor seed) -> Tensor", + lambda low, high, size, seed: torch.randint(low, high, size, device=seed.device), + doc="torch.randint() using backend-specific RNG that can be fused", +) +force_stride_order = make_prim( + "inductor_force_stride_order(Tensor input, SymInt[] stride) -> Tensor", + lambda input_tensor, stride: eager_force_stride(input_tensor, stride), + doc="Force the stride order for input tensor. No-op if the input tensor already has the stride. Do a copy otherwise", +) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/lowering.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/lowering.py new file mode 100644 index 0000000000000000000000000000000000000000..13f8a0dfc1a8045e240e9064d65fe9d7ba15de05 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/lowering.py @@ -0,0 +1,4772 @@ +import functools +import itertools +import logging +import os +import warnings +from collections import defaultdict +from collections.abc import Iterable +from typing import Any, List, Optional, Tuple, Union + +import sympy + +import torch +import torch.fx +import torch.utils._pytree as pytree +from torch._prims_common import ( + canonicalize_dim, + canonicalize_dims, + check, + dtype_to_type, + elementwise_dtypes, + ELEMENTWISE_TYPE_PROMOTION_KIND, + is_boolean_dtype, + is_float_dtype, + is_integer_dtype, + Number, + type_to_dtype, +) +from torch.fx.experimental.symbolic_shapes import magic_methods, method_to_operator +from torch.utils._pytree import tree_flatten +from torch.utils._sympy.functions import CeilDiv, FloorDiv, ModularIndexing +from .._dynamo.utils import import_submodule + +from . import config, inductor_prims, ir, test_operators # NOQA: F401 +from .decomposition import decompositions, get_decompositions +from .ir import ( + ExpandView, + IndexingConstant, + is_triton, + ops_wrapper, + PermuteView, + Pointwise, + Reduction, + SqueezeView, + TensorBox, + validate_ir, + View, +) +from .utils import ceildiv, decode_device, pad_listlike, sympy_product +from .virtualized import ops, V + +log = logging.getLogger(__name__) +lowerings = {} +layout_constraints = {} +fallbacks = set() +aten = torch.ops.aten +tr_c10d = torch.ops.tr_c10d +prims = torch.ops.prims +needs_realized_inputs = set() +foreach_ops = set() + + +def assert_nyi(cond, msg): + if not cond: + raise NotImplementedError(f"inductor does not support {msg}") + + +def add_needs_realized_inputs(fn): + if isinstance(fn, (list, tuple, set)): + return [add_needs_realized_inputs(x) for x in fn] + needs_realized_inputs.add(fn) + if isinstance(fn, torch._ops.OpOverloadPacket): + for overload in fn.overloads(): + needs_realized_inputs.add(getattr(fn, overload)) + + +def add_layout_constraint(fn, constraint): + if isinstance(fn, torch._ops.OpOverloadPacket): + for overload in fn.overloads(): + layout_constraints[getattr(fn, overload)] = constraint + else: + layout_constraints[fn] = constraint + + +add_needs_realized_inputs( + [ + aten.as_strided, + aten.avg_pool2d, + aten.avg_pool2d_backward, + aten.bmm, + aten.convolution, + aten.convolution_backward, + aten.max_pool2d_with_indices, + aten.max_pool2d_with_indices_backward, + aten.mm, + aten.upsample_nearest2d, + aten.upsample_bicubic2d, + aten._int_mm, + ] +) + +# TODO(jansel): ezyang says we won't need this in the future, try removing it +# based on https://github.com/pytorch/pytorch/blob/9e3eb329df8f701/c10/core/ScalarType.h#L28 +DTYPE_ID_LOOKUP = { + 0: torch.uint8, + 1: torch.int8, + 2: torch.int16, + 3: torch.int32, + 4: torch.int64, + 5: torch.float16, + 6: torch.float32, + 7: torch.float64, + 8: torch.complex32, + 9: torch.complex64, + 10: torch.complex32, + 11: torch.bool, + 15: torch.bfloat16, + # TODO(jansel): add quantized types? + # _(c10::qint8, QInt8) /* 12 */ + # _(c10::quint8, QUInt8) /* 13 */ + # _(c10::qint32, QInt32) /* 14 */ + # _(c10::quint4x2, QUInt4x2) /* 16 */ + # _(c10::quint2x4, QUInt2x4) /* 17 */ +} + + +def decode_dtype(dtype: int): + if not isinstance(dtype, int): + return dtype + assert dtype in DTYPE_ID_LOOKUP, f"id {dtype} missing from DTYPE_ID_LOOKUP" + dtype = DTYPE_ID_LOOKUP[dtype] + return dtype + + +def is_integer_type(x): + if isinstance(x, TensorBox): + return is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + elif isinstance(x, sympy.Symbol): + return x.is_integer is True # type: ignore[attr-defined] + else: + return isinstance(x, int) + + +def is_boolean_type(x): + if isinstance(x, TensorBox): + return is_boolean_dtype(x.get_dtype()) + else: + return isinstance(x, bool) + + +def get_promoted_dtype(*args, type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND): + def construct_input(inp): + if isinstance(inp, (Number, sympy.Symbol)): + return inp + else: + assert hasattr(inp, "get_dtype") + dim = len(inp.get_size()) + # construct a tmp tensor to feed into torch.result_type + return torch.zeros([1] * dim, dtype=inp.get_dtype()) + + inps = [construct_input(arg) for arg in args] + _, dtype = elementwise_dtypes(*inps, type_promotion_kind=type_promotion_kind) + return dtype + + +def get_overloads(aten_fn): + if not isinstance(aten_fn, (list, tuple)): + aten_fn = [aten_fn] + else: + aten_fn = list(aten_fn) + + for fn in list(aten_fn): + if isinstance(fn, torch._ops.OpOverloadPacket): + for overload in fn.overloads(): + other_fn = getattr(fn, overload) + if other_fn not in lowerings: + aten_fn.append(other_fn) + + return aten_fn + + +def transform_args(args, broadcast, type_promotion_kind, convert_input_to_bool): + indices = [i for i, x in enumerate(args) if isinstance(x, TensorBox)] + if (type_promotion_kind or convert_input_to_bool) and indices: + if convert_input_to_bool: + dtype = torch.bool + else: + # FIXME that's a crude approximation for promoting args + promoting_args = [ + a for a in args if isinstance(a, Number) or hasattr(a, "get_dtype") + ] + dtype = get_promoted_dtype( + *promoting_args, type_promotion_kind=type_promotion_kind + ) + + # sometimes args are an immutable list so we can't mutate them + def promote(arg): + if isinstance(arg, TensorBox): + return to_dtype(arg, dtype) + elif isinstance(arg, ir.Constant): + return ir.Constant(arg.value, dtype, args[indices[0]].get_device()) + else: + return arg + + args = [promote(a) for a in args] + if broadcast and indices: + for i, x in zip(indices, broadcast_tensors(*[args[i] for i in indices])): + args[i] = x + for i in range(len(args)): + if isinstance(args[i], ir.Constant): + args[i] = ExpandView.create(args[i], list(args[indices[0]].get_size())) + + return args + + +def _register_foreach_lowering(aten_fn, decomp_fn): + """ + Add a foreach lowering to lowerings dict. + + Arguments: + aten_fn: torch.ops.aten.* fn we are lowering + decomp_fn: alternate implementation on our IR + broadcast: True to apply broadcasting to tensor inputs + type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion + convert_input_to_bool: some logical ops require inputs are converted to bool + """ + + @functools.wraps(decomp_fn) + def wrapped(*args, **kwargs): + assert len(args) <= 2 + out = decomp_fn(*args, **kwargs) + validate_ir(out) + return out + + aten_fns = get_overloads(aten_fn) + foreach_ops.update(aten_fns) + lowerings.update({fn: wrapped for fn in aten_fns}) + return wrapped + + +def _register_lowering( + aten_fn, decomp_fn, broadcast, type_promotion_kind, convert_input_to_bool +): + """ + Add a lowering to lowerings dict + + Arguments: + aten_fn: torch.ops.aten.* fn we are lowering + decomp_fn: alternate implementation on our IR + broadcast: True to apply broadcasting to tensor inputs + type_promotion_kind: kind of type promotion applied to tensor inputs, `None` means no type promotion + convert_input_to_bool: some logical ops require inputs are converted to bool + """ + + @functools.wraps(decomp_fn) + def wrapped(*args, **kwargs): + args: Union[List[Any], Tuple[Any, ...]] = list(args) + unpacked = False + # TODO maybe we need to use pytrees here + if len(args) == 1 and isinstance(args[0], (list, tuple)): + unpacked = True + args = args[0] + + # explicitly assert for "out=" ops for better error messages + assert not any( + x == "out" for x in kwargs.keys() + ), "out= ops aren't yet supported" + # kwargs tensors not supported yet unless it's a fallback op + assert not any(isinstance(x, TensorBox) for x in kwargs.values()) or all( + fn in fallbacks for fn in aten_fn + ) + + args = transform_args( + args, broadcast, type_promotion_kind, convert_input_to_bool + ) + + if unpacked: + args = [args] + + out = decomp_fn(*args, **kwargs) + validate_ir(out) + + return out + + aten_fn = get_overloads(aten_fn) + + lowerings.update({fn: wrapped for fn in aten_fn}) + return wrapped + + +def register_lowering( + aten_fn, + broadcast=False, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + convert_input_to_bool=False, +): + """ + Shim to support decorator syntax. + """ + return functools.partial( + _register_lowering, + aten_fn, + broadcast=broadcast, + type_promotion_kind=type_promotion_kind, + convert_input_to_bool=convert_input_to_bool, + ) + + +def broadcast_symbolic_shapes(a, b): + """ + Broadcasting logic based on symbolic shapes. + + We give the shapes 0 and 1 concrete values, while all other shapes + are symbolic sympy formulas. + """ + output = [] + for a, b in itertools.zip_longest( + reversed(a), reversed(b), fillvalue=sympy.Integer(1) + ): + if b == 1: + output.append(a) + elif a == 1: + output.append(b) + else: + V.graph.sizevars.guard_equals(a, b) + if len(sympy.expand(b).free_symbols) < len(sympy.expand(a).free_symbols): + output.append(b) # prefer shorter formula + else: + output.append(a) + return tuple(reversed(output)) + + +def promote_constants(inputs, override_return_dtype=None): + if not any(isinstance(x, (sympy.Expr, int, float)) for x in inputs): + return inputs + if all(isinstance(x, (int, float, sympy.Symbol)) for x in inputs): + dtype = override_return_dtype or get_promoted_dtype( + *inputs, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + + def const_func(x): + if isinstance(x, sympy.Symbol): + return ir.IndexingConstant(x, dtype, decode_device(None)) + else: + return ir.Constant(x, dtype, decode_device(None)) + + return [const_func(x) for x in inputs] + ex = next(x for x in inputs if isinstance(x, (TensorBox, ExpandView))) + out = [] + for x in inputs: + if isinstance(x, (int, float)): + out.append( + ExpandView.create( + ir.Constant(x, ex.get_dtype(), ex.get_device()), list(ex.get_size()) + ) + ) + elif isinstance(x, sympy.Expr): + out.append(IndexingConstant(x, ex.get_dtype(), ex.get_device())) + else: + out.append(x) + + return out + + +def make_pointwise( + fn, + override_return_dtype=None, + override_device=None, + override_fn_when_input_bool=None, + override_fn_when_cuda_float64=None, + allow_alpha=False, +): + def inner(*inputs: List[TensorBox], alpha=None): + inputs = promote_constants(inputs, override_return_dtype) + if allow_alpha: + if alpha is not None and alpha != 1: + inputs = list(inputs) + inputs[-1] = mul(inputs[-1], alpha) + else: + assert alpha is None + loaders = [x.make_loader() for x in inputs] + ranges = inputs[0].get_size() + dtype = override_return_dtype or inputs[0].get_dtype() + is_cuda = decode_device(inputs[0].get_device()).type == "cuda" + + for other in inputs[1:]: + assert isinstance(other, ir.BaseConstant) or len(ranges) == len( + other.get_size() + ), f"ndim mismatch {fn} {ranges} {other.get_size()}" + + def inner_fn(index): + assert len(index) == len(ranges), f"wrong ndim {index} {ranges}" + if dtype == torch.bool and override_fn_when_input_bool is not None: + return override_fn_when_input_bool(*[load(index) for load in loaders]) + elif override_fn_when_cuda_float64 and is_cuda and dtype == torch.float64: + return override_fn_when_cuda_float64(*[load(index) for load in loaders]) + else: + return fn(*[load(index) for load in loaders]) + + if not override_device: + device = None + for i in inputs: + if i.get_device().type == "cuda": + device = i.get_device() + break + if not device: + device = inputs[0].get_device() + + device = override_device or device + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=ranges, + ) + + return inner + + +def make_foreach_pointwise(pw_fn, allow_alpha=False): + def inner(*inputs: List[List[TensorBox]], alpha=1): + def is_dynamic(*args): + return any( + isinstance(t, TensorBox) + and any(x.free_symbols for x in t.data.get_size()) # type: ignore[attr-defined] + for t in args + ) + + # group by device, whether any of the inputs are dynamic, and whether their types match + # (proxy for type promotion) + def group_args(arg_pairs): + out = defaultdict(list) + for i, args in enumerate(arg_pairs): + use_foreach = not is_dynamic(*args) + device = None + for t in args: + if isinstance(t, TensorBox): + device = t.data.get_device() # type: ignore[attr-defined] + break + assert ( + device is not None + ), "foreach op should have at least one tensor arg" + out[(device, use_foreach)].append((i, args)) + return out + + realize_outputs = False + for node in V.graph.current_node.users: + for user in node.users: + if not (user.op == "call_function" and user.target in foreach_ops): + realize_outputs = True + + a_list_input = None + for input in inputs: + if isinstance(input, (list, tuple)): + a_list_input = input + break + assert ( + a_list_input is not None + ), "at least one input must be a list to a foreach op" + + # broadcast scalar inputs to match length of list inputs + broadcast_inputs = [] + for input in inputs: + if not isinstance(input, (list, tuple)): + broadcast_inputs.append([input] * len(a_list_input)) + else: + broadcast_inputs.append(input) + + groups = group_args(zip(*broadcast_inputs)) + + outputs = [None] * len(a_list_input) + for (device, use_foreach), group in groups.items(): + buffer_list = [] + for ( + output_ind, + args, + ) in group: + if allow_alpha: + output = pw_fn(*args, alpha=alpha) + else: + output = pw_fn(*args) + + outputs[output_ind] = output + + if device.type == "cuda" and use_foreach and realize_outputs: + buffer_list.append(output.realize()) + + if buffer_list: + V.graph.register_list(buffer_list) + + assert all(x is not None for x in outputs) + return outputs + + return inner + + +def to_dtype(x: TensorBox, dtype: torch.dtype, copy=False): + if x.get_dtype() == dtype: + return clone(x) if copy else x + + def _to_dtype(x): + return ops.to_dtype(x, dtype) + + return make_pointwise(_to_dtype, override_return_dtype=dtype)(x) + + +@register_lowering(prims.convert_element_type, type_promotion_kind=None) +def _convert_element_type(x: TensorBox, dtype: torch.dtype): + return to_dtype(x, dtype, copy=True) + + +def to_dtype_bitcast(x: TensorBox, dtype: torch.dtype, *, copy=False): + if x.get_dtype() == dtype: + return clone(x) if copy else x + + def _get_primitive_bitwidth(dtype): + if dtype.is_floating_point: + return torch.finfo(dtype).bits + else: + return torch.iinfo(dtype).bits + + src_bits = _get_primitive_bitwidth(x.get_dtype()) + dst_bits = _get_primitive_bitwidth(dtype) + if src_bits != dst_bits: + raise NotImplementedError( + f"bitcast {x.get_dtype()} to different bitwidth type {dtype} is not supported yet." + ) + + def _to_dtype_bitcast(x): + return ops.to_dtype_bitcast(x, dtype) + + return make_pointwise(_to_dtype_bitcast, override_return_dtype=dtype)(x) + + +@register_lowering(aten.view.dtype, type_promotion_kind=None) +def _view_dtype(x: TensorBox, dtype: torch.dtype): + return to_dtype_bitcast(x, dtype, copy=True) + + +def to_device(x: TensorBox, device: torch.device, *, copy=False): + device = decode_device(device) + if x.get_device() == device: + return clone(x) if copy else x + return TensorBox.create(ir.DeviceCopy.create(x, device)) + + +@register_lowering(prims.device_put, type_promotion_kind=None) +def _device_put(x: TensorBox, device: torch.device): + return to_device(x, device, copy=True) + + +def register_pointwise( + aten_fn, + name=None, + broadcast=True, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, + convert_input_to_bool=False, + override_return_dtype=None, + override_fn_when_input_bool=None, + allow_alpha=False, + use_libdevice_for_f64=False, +): + """A pointwise function that maps ops.{name} to inputs""" + name = name or aten_fn.__name__ + fn = ops_wrapper(name) + if use_libdevice_for_f64: + fn_libdevice = ops_wrapper("libdevice_" + name) + if override_fn_when_input_bool is not None: + override_fn_when_input_bool = ops_wrapper(override_fn_when_input_bool) + + fn = make_pointwise( + fn, + override_return_dtype=override_return_dtype, + override_fn_when_input_bool=override_fn_when_input_bool, + override_fn_when_cuda_float64=fn_libdevice if use_libdevice_for_f64 else None, + allow_alpha=allow_alpha, + ) + fn = register_lowering( + aten_fn, + broadcast=broadcast, + type_promotion_kind=type_promotion_kind, + convert_input_to_bool=convert_input_to_bool, + )(fn) + + if hasattr(prims, name): + register_lowering( + getattr(prims, name), + type_promotion_kind=None, + convert_input_to_bool=convert_input_to_bool, + )(fn) + return fn + + +def register_foreach_pointwise( + aten_fn, + pointwise_lowering_fn, + allow_alpha=False, +): + fn = make_foreach_pointwise(pointwise_lowering_fn, allow_alpha=allow_alpha) + fn = _register_foreach_lowering(aten_fn, fn) + return fn + + +@register_lowering(aten.where, broadcast=False, type_promotion_kind=None) +def where(cond, a, b): + def fn(*args): + return ops.where(*args) + + if isinstance(a, (float, int)): + a = constant_like(a)(b) + if isinstance(b, (float, int)): + b = constant_like(b)(a) + + args = [cond, a, b] + dtype = get_promoted_dtype( + args[1], args[2], type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + indices = [i for i, x in enumerate(args) if isinstance(x, TensorBox)] + for i, x in zip(indices, broadcast_tensors(*[args[i] for i in indices])): + args[i] = x + for i in range(len(args)): + if isinstance(args[i], ir.Constant): + args[i] = ExpandView.create(args[i], list(args[indices[0]].get_size())) + return make_pointwise(fn, override_return_dtype=dtype)( + args[0], to_dtype(args[1], dtype), to_dtype(args[2], dtype) + ) + + +@register_lowering(aten.broadcast_tensors, broadcast=False, type_promotion_kind=None) +def broadcast_tensors(*inputs): + if len(inputs) == 1 and isinstance(inputs[0], (list, tuple)): + return broadcast_tensors(*inputs[0]) + target: List[sympy.Expr] = functools.reduce( + broadcast_symbolic_shapes, [x.get_size() for x in inputs], [] + ) + outputs = [] + for x in inputs: + sizes = x.get_size() + if len(sizes) != len(target) or any( + ((a == 1 and b != 1) or (a != 1 and b == 1)) for a, b in zip(sizes, target) + ): + x = expand(x, target) + outputs.append(x) + return outputs + + +@register_lowering([aten.alias, aten.detach, aten.detach_, aten.lift, prims.view_of]) +def nop(x): + return x # AOT autograd handles this for us + + +if hasattr(aten, "lift_fresh"): + register_lowering(aten.lift_fresh)(nop) + + +@register_lowering(aten.squeeze, type_promotion_kind=None) +def squeeze(x, dim=None): + assert isinstance(x, TensorBox) + if dim is None: + return TensorBox(SqueezeView.create(x.data)) + + dim = canonicalize_dims(len(x.get_size()), dim) + dims = set((dim,) if not isinstance(dim, tuple) else dim) + + new_shape = [] + for d, s in enumerate(x.get_size()): + if not (d in dims and V.graph.sizevars.evaluate_expr(sympy.Eq(s, 1))): + new_shape.append(s) + + # squeeze does nothing if the size isn't 1 + return view(x, new_shape) if new_shape != x.get_size() else x + + +@register_lowering(aten.squeeze_copy, type_promotion_kind=None) +def squeeze_copy(x, dim=None): + return clone(squeeze(x, dim)) + + +@register_lowering([aten.squeeze_]) +def squeeze_(x, dim=None): + val = squeeze(x, dim) + assert isinstance(x, TensorBox) + assert isinstance(val, TensorBox) + x.data = val.data + return x + + +@register_lowering(aten.isinf) +def isinf(x): + if is_integer_type(x): + return full_like(x, False, dtype=torch.bool) + fn = ops_wrapper("isinf") + return make_pointwise(fn, override_return_dtype=torch.bool)(x) + + +@register_lowering(aten.isnan) +def isnan(x): + if is_integer_type(x): + return full_like(x, False, dtype=torch.bool) + fn = ops_wrapper("isnan") + return make_pointwise(fn, override_return_dtype=torch.bool)(x) + + +@register_lowering(aten.ceil) +def ceil(x): + if is_integer_type(x): + return clone(x) + fn = ops_wrapper("ceil") + return make_pointwise(fn)(x) + + +@register_lowering(aten.floor) +def floor(x): + if is_integer_type(x): + return clone(x) + fn = ops_wrapper("floor") + return make_pointwise(fn)(x) + + +@register_lowering(aten.round) +def round(x): + if is_integer_type(x): + return clone(x) + fn = ops_wrapper("round") + return make_pointwise(fn)(x) + + +@register_lowering(aten.trunc) +def trunc(x): + if is_integer_type(x): + return clone(x) + fn = ops_wrapper("trunc") + return make_pointwise(fn)(x) + + +@register_lowering(aten.expand, type_promotion_kind=None) +def expand(x, sizes): + (x,) = promote_constants([x]) + if isinstance(x, ir.BaseConstant): + return ExpandView.create(x, tuple(sizes)) + assert isinstance(x, TensorBox) + assert isinstance(sizes, (list, tuple)) + if tuple(x.get_size()) == tuple(sizes): + return x + + x_size_product = V.graph.sizevars.size_hint(sympy_product(x.get_size())) + if x_size_product > 0: + # maybe realize input before broadcasting it + x.mark_reuse(V.graph.sizevars.size_hint(sympy_product(sizes)) // x_size_product) + return TensorBox(ExpandView.create(x.data, tuple(sizes))) + + +@register_lowering(prims.broadcast_in_dim, type_promotion_kind=None) +def broadcast_in_dim(a, shape, broadcast_dimensions): + s = list(shape) + for broadcast_dimension in broadcast_dimensions: + s[broadcast_dimension] = -1 + + v = a + for idx, x in enumerate(s): + if x != -1: + v = unsqueeze(v, idx) + + return expand(v, shape) + + +@register_lowering(aten.expand_as, type_promotion_kind=None) +def expand_as(x, y): + return expand(x, y.get_size()) + + +@register_lowering(aten.repeat) +def repeat(x, repeats): + old_size = list(x.get_size()) + if len(repeats) > len(old_size): + old_size = [sympy.Integer(1)] * (len(repeats) - len(old_size)) + old_size + x = view(x, list(old_size)) + assert len(repeats) == len(x.get_size()) + + new_size = list(x.get_size()) + + zero_tensor = False + for i in range(len(repeats)): + if repeats[i] == 0: + zero_tensor = True + new_size[i] = new_size[i] * repeats[i] + + if zero_tensor: + return empty(new_size, dtype=x.get_dtype(), device=x.get_device()) + if all((a == 1 or b == 1) for a, b in zip(repeats, old_size)): + return expand(x, new_size) + + def inner_fn(index): + assert len(index) == len(repeats) + index = list(index) + for i in range(len(repeats)): + if repeats[i] != 1: + if old_size[i] == 1: + index[i] = sympy.Integer(0) + else: + index[i] = ModularIndexing(index[i], 1, old_size[i]) + return x_loader(index) + + old_size_product = V.graph.sizevars.size_hint(sympy_product(old_size)) + if old_size_product > 0: + # maybe realize the input + x.mark_reuse( + V.graph.sizevars.size_hint(sympy_product(new_size)) // old_size_product + ) + + x_loader = x.make_loader() + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=inner_fn, + ranges=list(new_size), + ) + + +@register_lowering(aten._unsafe_view, type_promotion_kind=None) +@register_lowering(aten.view, type_promotion_kind=None) +@register_lowering(aten.reshape, type_promotion_kind=None) +def view(x, sizes): + assert isinstance(x, TensorBox) + assert isinstance(sizes, (list, tuple)) + return TensorBox(View.create(x.data, sizes)) + + +@register_lowering(aten.permute, type_promotion_kind=None) +def permute(x, dims): + assert isinstance(x, TensorBox) + assert isinstance(dims, (list, tuple)) + return TensorBox(PermuteView.create(x.data, tuple(dims))) + + +@register_lowering(aten.slice, type_promotion_kind=None) +def slice_(x, dim=0, start=0, end=2**63, step=1): + assert isinstance(x, TensorBox) + dim = _validate_dim(x, dim, 0) + dim_size = x.get_size()[dim] + if V.graph.sizevars.evaluate_expr(sympy.Lt(start + dim_size, 0)): + start = 0 + if V.graph.sizevars.evaluate_expr(sympy.Lt(end + dim_size, 0)): + end = 0 + return TensorBox(ir.SliceView.create(x.data, dim, start, end, step)) + + +@register_lowering(aten.roll, type_promotion_kind=None) +def roll(a, shifts, dims=tuple()): + """ + This is based on torch._refs.roll(), but uses ModularIndexing(). + + We can't use the ref here because it is based on multiple calls to + torch.cat() that this will result in terrible code. + """ + # ATen specifies int[1] type for shifts and dims which expands integers to tuples of length 1 + if not isinstance(shifts, Iterable): + shifts = (shifts,) + if not isinstance(dims, Iterable): + dims = (dims,) + dims = [_validate_dim(a, d) for d in dims] + + if sympy_product(a.get_size()) == 0: + return clone(a) + + len_shifts = len(shifts) + len_dims = len(dims) + if len_shifts != 1 or len_dims != 1: + if len_shifts == 0: + raise RuntimeError("`shifts` required") + # Takes care of the case when dims is not specified (default) + # By default, the tensor is flattened before shifting, after which the original shape is restored + if len_dims == 0 and len_shifts == 1: + flat = view(a, [sympy_product(a.get_size())]) + rolled = roll(flat, shifts, 0) + return view(rolled, list(a.get_size())) + if len_shifts != len_dims: + raise RuntimeError( + f"shifts and dimensions must align. shifts: {len_shifts}, dims: {len_dims}" + ) + tail_shifts = shifts[1:] + tail_dims = dims[1:] + first_dim_rolled = roll(a, shifts[0], dims[0]) + return roll(first_dim_rolled, tail_shifts, tail_dims) + + (dim,) = dims + # TODO: Avoid guarding on shape here + size = V.graph.sizevars.evaluate_static_shape(a.get_size()[dim]) + start = (size - shifts[0]) % size + a_loader = a.make_loader() + + def fn(index): + index = list(index) + index[dim] = ModularIndexing( + index[dim] + start, sympy.Integer(1), sympy.expand(size) + ) + return a_loader(index) + + return Pointwise.create( + device=a.get_device(), + dtype=a.get_dtype(), + inner_fn=fn, + ranges=a.get_size(), + ) + + +@register_lowering(aten.as_strided, type_promotion_kind=None) +def as_strided(x, size, stride, storage_offset=None): + if isinstance(x, TensorBox) and isinstance(x.data, ir.BaseView): + # as_strided ignores views + x = x.data.unwrap_view() + x.realize() + if not ir.is_storage_and_layout(x): + raise NotImplementedError(f"unrealized as_strided({x}, ...)") + storage, old_layout = ir.as_storage_and_layout(x) + new_layout = ir.FixedLayout( + old_layout.device, + old_layout.dtype, + [sympy.expand(s) for s in size], + [sympy.expand(s) for s in stride], + sympy.expand(storage_offset or 0), + ) + return TensorBox(ir.ReinterpretView(storage, new_layout)) + + +@register_lowering(aten.as_strided_, type_promotion_kind=None) +def as_strided_(x, size, stride, storage_offset=None): + assert isinstance(x, TensorBox) + x.data = as_strided(x, size, stride, storage_offset).data + return x + + +@register_lowering(aten.as_strided_copy, type_promotion_kind=None) +def as_strided_copy(x, size, stride, storage_offset=None): + result = as_strided(x, size, stride, storage_offset) + return clone(result) + + +@register_lowering(aten.cat) +def cat(inputs, dim=0): + if all(input.get_dtype() is torch.uint8 for input in inputs): + # TODO Remove this fallback when we support vectorization + # code gen with uint8 data type directly. + for input in inputs: + input.realize() + if all(len(input.layout.size) == 4 for input in inputs): + inputs, _ = require_channels_last(aten.cat, *inputs) + return fallback_handler(aten.cat)(inputs, dim) + + if len(inputs) == 1: + return clone(inputs[0]) + + dim = _validate_dim(inputs[0], dim, 0) + dtype = get_promoted_dtype( + *inputs, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT + ) + inputs = [to_dtype(inp, dtype) for inp in inputs] + return TensorBox(ir.ConcatKernel.create(inputs, dim)) + + +@register_lowering(aten.diagonal, type_promotion_kind=None) +def diagonal(input, offset: int = 0, dim1: int = 0, dim2: int = 1): + original_shape = input.get_size() + num_dims = len(original_shape) + dim1 = canonicalize_dim(idx=dim1, rank=num_dims) + dim2 = canonicalize_dim(idx=dim2, rank=num_dims) + + check( + dim1 != dim2, lambda: f"diagonal dimensions cannot be identical {dim1}, {dim2}" + ) + + offset_negative = V.graph.sizevars.evaluate_expr(sympy.Lt(offset, 0)) + if offset_negative: + diag_size = max(min(original_shape[dim1] + offset, original_shape[dim2]), 0) + else: + diag_size = max(min(original_shape[dim1], original_shape[dim2] - offset), 0) + + base_idx = (0, 0) + if offset_negative: + base_idx = (-offset, 0) + else: + base_idx = (0, offset) + + sizes = [s for i, s in enumerate(original_shape) if i not in (dim1, dim2)] + sizes.append(diag_size) + + def reindexer(idx): + diag_idx = idx[-1] + original_idx = [0] * len(original_shape) + cur_dim = 0 + for d in range(num_dims): + if d == dim1: + original_idx[d] = diag_idx + base_idx[0] + elif d == dim2: + original_idx[d] = diag_idx + base_idx[1] + else: + original_idx[d] = idx[cur_dim] + cur_dim += 1 + + assert cur_dim == len(original_shape) - 2 + return original_idx + + return TensorBox(ir.GenericView.create(input, sizes, reindexer)) + + +@register_lowering(aten.diagonal_copy, type_promotion_kind=None) +def diagonal_copy(input, offset: int = 0, dim1: int = 0, dim2: int = 1): + return clone(diagonal(input, offset, dim1, dim2)) + + +@register_lowering(aten.diagonal_scatter, type_promotion_kind=None) +def diagonal_scatter(input, src, offset: int = 0, dim1: int = 0, dim2: int = 1): + output = clone(input) + target = diagonal(output, offset, dim1, dim2) + mutate_to(target, src) + return output + + +@register_lowering(aten.select, type_promotion_kind=None) +def select(x, dim, idx): + idx = View.handle_negative_index(idx, x.get_size()[dim]) + return squeeze(slice_(x, dim, idx, idx + 1), dim) + + +@register_lowering(aten.split, type_promotion_kind=None) +def split(x, sizes, dim=0): + dim = _validate_dim(x, dim, 0) + x_size = V.graph.sizevars.evaluate_static_shape(x.get_size()[dim]) + if isinstance(sizes, sympy.Expr): + # TODO: We don't have to guard on sizes per se, but the number + # of splits must stay constant + sizes = V.graph.sizevars.evaluate_static_shape(sizes) + if isinstance(sizes, (int, sympy.Integer)): + sizes = [sizes] * ((x_size + sizes - 1) // sizes) + result = [] + start = 0 + for size in sizes: + end = start + size + result.append(slice_(x, dim, start, end)) + start = end + return result + + +@register_lowering(aten.split_with_sizes, type_promotion_kind=None) +def split_with_sizes(x, sizes, dim=0): + return split(x, sizes, dim) + + +@register_lowering(aten.unbind, type_promotion_kind=None) +def unbind(x, dim=0): + dim = _validate_dim(x, dim, 0) + x_size = V.graph.sizevars.evaluate_static_shape(x.get_size()[dim]) + result = [] + for i in range(x_size): + result.append(select(x, dim, i)) + return result + + +@register_lowering(aten.unfold, type_promotion_kind=None) +def unfold(x, dimension, size, step): + sizes = x.get_size() + ndim = len(sizes) + dim = canonicalize_dim(ndim, dimension) + + if ndim == 0: + return slice_(unsqueeze(x, 0), end=size) + + sizevars = V.graph.sizevars + sizevars.guard_leq(size, sizes[dim]) + sizevars.guard_lt(0, step) + + new_dim_size = FloorDiv(sizes[dim] - size, step) + 1 + x.mark_reuse(sizevars.size_hint(CeilDiv(new_dim_size * size, sizes[dim]))) + + out_size = [*sizes[:dim], new_dim_size, *sizes[dim + 1 :], size] + + def reindexer(idx): + dim_idx = idx[-1] + idx[dim] * step + return (*idx[:dim], dim_idx, *idx[dim + 1 : -1]) + + return TensorBox(ir.GenericView.create(x, out_size, reindexer)) + + +@register_lowering(aten.unsqueeze, type_promotion_kind=None) +def unsqueeze(x, dim): + dim = _validate_dim(x, dim, 1) + new_shape = list(x.get_size()) + new_shape.insert(dim, sympy.Integer(1)) + return view(x, new_shape) + + +@register_lowering(aten.unsqueeze_, type_promotion_kind=None) +def unsqueeze_(x, dim): + val = unsqueeze(x, dim) + assert isinstance(x, TensorBox) + assert isinstance(val, TensorBox) + x.data = val.data + return x + + +def _validate_dim(x, dim, offset=0): + assert isinstance(dim, int) + ndim = len(x.get_size()) + if dim < 0: + dim += ndim + offset + assert 0 <= dim < ndim + offset + return dim + + +@register_lowering(aten.glu) +def glu(x, dim=-1): + dim = _validate_dim(x, dim, 0) + # TODO: don't guard on static shape here + new_len = V.graph.sizevars.evaluate_static_shape(x.get_size()[dim]) // 2 + a = slice_(x, dim, 0, new_len) + b = slice_(x, dim, new_len, new_len * 2) + return mul(a, sigmoid(b)) + + +def register_onednn_fusion_ops(): + if torch._C._has_mkldnn: + cpu_needs_realized_inputs = [ + torch.ops.mkldnn._convolution_pointwise, + torch.ops.mkldnn._convolution_pointwise_, + torch.ops.mkldnn._convolution_transpose_pointwise, + torch.ops.mkldnn._linear_pointwise, + aten.mkldnn_rnn_layer.default, + torch.ops.onednn.qconv2d_pointwise, + ] + + @register_lowering(torch.ops.mkldnn._convolution_pointwise) + def convolution_unary( + x: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ): + return TensorBox.create( + ir.ConvolutionUnary.create( + x, + weight, + bias, + padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ) + ) + + @register_lowering(torch.ops.mkldnn._convolution_pointwise.binary) + def convolution_binary( + x: TensorBox, + other: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ): + return TensorBox.create( + ir.ConvolutionBinary.create( + x, + other, + weight, + bias, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ) + ) + + @register_lowering(torch.ops.mkldnn._convolution_pointwise_.binary) + def convolution_binary_inplace( + x: TensorBox, + other: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ): + return TensorBox.create( + ir.ConvolutionBinaryInplace.create( + x, + other, + weight, + bias, + padding, + stride, + dilation, + groups, + binary_attr, + binary_alpha, + unary_attr, + unary_scalars, + unary_algorithm, + ) + ) + + @register_lowering(torch.ops.mkldnn._linear_pointwise) + def linear_unary( + x: TensorBox, w: TensorBox, b: TensorBox, attr, scalars, algorithm + ): + return TensorBox.create( + ir.LinearUnary.create(x, w, b, attr, scalars, algorithm) + ) + + @register_lowering(torch.ops.mkldnn._linear_pointwise.binary) + def linear_binary(x: TensorBox, y: TensorBox, w: TensorBox, b: TensorBox, attr): + return TensorBox.create(ir.LinearBinary.create(x, y, w, b, attr)) + + @register_lowering(torch.ops.mkldnn._convolution_transpose_pointwise) + def convolution_transpose_unary( + x: TensorBox, + weight: TensorBox, + bias: TensorBox, + padding, + output_padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ): + return TensorBox.create( + ir.ConvolutionTransposeUnary.create( + x, + weight, + bias, + padding, + output_padding, + stride, + dilation, + groups, + attr, + scalars, + algorithm, + ) + ) + + @register_lowering(aten.mkldnn_rnn_layer.default) + def mkldnn_rnn_layer( + x: TensorBox, + w0: TensorBox, + w1: TensorBox, + w2: TensorBox, + w3: TensorBox, + hx: TensorBox, + cx: TensorBox, + reverse: bool, + batch_sizes: List[int], + mode: int, + hidden_size: int, + num_layers: int, + has_biases: bool, + bidirectional: bool, + batch_first: bool, + train: bool, + ): + return pytree.tree_map( + TensorBox.create, + ir.MkldnnRnnLayer.create( + x, + w0, + w1, + w2, + w3, + hx, + cx, + reverse, + batch_sizes, + mode, + hidden_size, + num_layers, + has_biases, + bidirectional, + batch_first, + train, + ), + ) + + @register_lowering(torch.ops.onednn.qconv2d_pointwise, type_promotion_kind=None) + def qconvolution_unary( + x: TensorBox, + x_scale, + x_zp, + packed_weight: TensorBox, + w_scale: TensorBox, + w_zp: TensorBox, + bias: TensorBox, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + fp32_output, + attr, + scalars, + algorithm, + ): + return TensorBox.create( + ir.QConvPointWisePT2E.create( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + bias, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + fp32_output, + attr, + scalars, + algorithm, + ) + ) + + @register_lowering( + torch.ops.onednn.qconv2d_pointwise.binary, type_promotion_kind=None + ) + def qconvolution_binary( + x: TensorBox, + x_scale, + x_zp, + accum: TensorBox, + accum_scale, + accum_zp, + packed_weight: TensorBox, + w_scale: TensorBox, + w_zp: TensorBox, + bias: TensorBox, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + fp32_output, + binary_attr, + alpha, + unary_attr, + unary_scalars, + unary_algorithmm, + ): + return TensorBox.create( + ir.QConvPointWiseBinaryPT2E.create( + x, + x_scale, + x_zp, + accum, + accum_scale, + accum_zp, + packed_weight, + w_scale, + w_zp, + bias, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + fp32_output, + binary_attr, + alpha, + unary_attr, + unary_scalars, + unary_algorithmm, + ) + ) + + @register_lowering(torch.ops.onednn.qlinear_pointwise, type_promotion_kind=None) + def qlinear_unary( + x: TensorBox, + x_scale, + x_zp, + packed_weight: TensorBox, + w_scale: TensorBox, + w_zp: TensorBox, + bias: TensorBox, + o_inv_scale, + o_zero_point, + fp32_output, + attr, + scalars, + algorithm, + ): + return TensorBox.create( + ir.QLinearPointwisePT2E.create( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + bias, + o_inv_scale, + o_zero_point, + fp32_output, + attr, + scalars, + algorithm, + ) + ) + + if torch._C.has_mkl: + cpu_needs_realized_inputs.append(torch.ops.mkl._mkl_linear) + + @register_lowering(torch.ops.mkl._mkl_linear) + def mkl_packed_linear( + x: TensorBox, + packed_w: TensorBox, + orig_w: TensorBox, + b: TensorBox, + batch_size, + ): + result = TensorBox.create( + ir.MKLPackedLinear.create(x, packed_w, orig_w, batch_size) + ) + if b is not None: + result = add(result, b) + return result + + add_needs_realized_inputs(cpu_needs_realized_inputs) + else: + pass + + +register_onednn_fusion_ops() + + +def fallback_handler(kernel, add_to_fallback_set=True): + if add_to_fallback_set: + fallbacks.add(kernel) + + def handler(*args, **kwargs): + return pytree.tree_map( + TensorBox.create, ir.FallbackKernel.create(kernel, *args, **kwargs) + ) + + return handler + + +@functools.lru_cache(None) +def _warn_complex_not_supported(): + warnings.warn( + "Torchinductor does not support code generation for complex operators. Performance may be worse than eager." + ) + + +# There are some types (CPU) which we accept as input but not as +# output. +def unsupported_input_tensor(t: torch._subclasses.FakeTensor): + "Do not support reading or writing to this tensor" + if t.is_complex(): + _warn_complex_not_supported() + return True + return False + + +def unsupported_output_tensor(t: torch._subclasses.FakeTensor): + "Do not support writing tensor but can read from it" + if unsupported_input_tensor(t): + return True + return t.is_cpu and config.disable_cpp_codegen + + +def fallback_node_due_to_unsupported_type(node: torch.fx.Node, allow_cpu_inputs=True): + # Custom fallback lowering + if node.target is aten.view_as_complex.default: + return False + + # We should be able to remove this special case once `disable_cpp_codegen` is killed. + if node.target is aten.lift_fresh_copy.default: + return False + + def check_skip_condition(node, is_output): + if not isinstance(node, torch.fx.Node): + return False + + if "val" not in node.meta: + return False + + for meta in tree_flatten(node.meta["val"])[0]: + if not isinstance(meta, torch._subclasses.FakeTensor): + continue + + if is_output: + if unsupported_output_tensor(meta): + return True + else: + if unsupported_input_tensor(meta): + return True + + return False + + # only skip codegen if there is a cpu output, not input + for arg in tree_flatten((node.args, node.kwargs))[0]: + if check_skip_condition(arg, is_output=False): + return True + + return check_skip_condition(node, is_output=True) + + +def make_fallback(kernel, layout_constraint=None, warn=True): + assert ( + kernel not in decompositions + ), f"both a fallback and a decomp for same kernel: {kernel}" + if get_decompositions([kernel]) and warn and bool(os.getenv("CI")): + # Note: 'warn' is holdover from when this was a warning, but for ops that previously + # set warn=False we do not want a CI error. + # Ignore the 'suppress errors' configs in CI, as this particular warning happens on startup anyway and is not + # likely to be triggered preferentially on one CI config over another. + if torch._dynamo.config.suppress_errors: + torch._dynamo.config.suppress_errors = False + log.warning( + "A make_fallback error occured in suppress_errors config," + " and suppress_errors is being disabled to surface it." + ) + raise AssertionError( + f"make_fallback({kernel}): a decomposition exists, we should switch to it." + " To fix this error, either add a decomposition to core_aten_decompositions (preferred)" + " or inductor_decompositions, and delete the corresponding `make_fallback` line." + " Get help from the inductor team if unsure, don't pick arbitrarily to unblock yourself.", + ) + + add_needs_realized_inputs(kernel) + if layout_constraint is not None: + add_layout_constraint(kernel, layout_constraint) + return register_lowering(kernel, type_promotion_kind=None)(fallback_handler(kernel)) + + +def philox_rand_offset(shape): + """ + TorchInductor offset calculation differs from PyTorch eager offset + calculation for random ops (tl.rand vs torch.rand). In future, we should + strive for same impl for tl.rand and torch.rand. + """ + numel = 1 + for s in shape: + numel = numel * s + return tensor(numel, dtype=torch.int64) + + +@register_lowering(torch.ops.rngprims.philox_rand, type_promotion_kind=None) +def philox_rand(size, seed, offset, stride, device, dtype): + # stride arg is optional and will be used in future for distributed random + # ops. Currently, its ununsed. + random_pos = ir.FixedLayout( + device, + dtype, + size, + ir.FlexibleLayout.contiguous_strides(size), + ).make_indexer() + seed_loader = seed.make_loader() + offset_loader = offset.make_loader() + + def inner_fn(index): + # Both seed and offset in the philox_rand op are tensors. + # torch seed and offsets are of type int64, but tl.rand accepts int32 + seed_index_expr = ops.to_dtype(seed_loader([]), torch.int32) + offset_index_expr = ops.to_dtype(offset_loader([]), torch.int32) + # Get the offset'd position + rand_index_expr = ops.add( + ops.index_expr(random_pos(index), torch.int32), offset_index_expr + ) + result = ops.rand( + seed_index_expr, + rand_index_expr, + ) + return ops.to_dtype(result, dtype) + + random_values_node = Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=list(size), + ) + + offset_node = philox_rand_offset(size) + return random_values_node, offset_node + + +@register_lowering(aten.native_dropout, type_promotion_kind=None) +def native_dropout(x, p, train): + if config.fallback_random: + return pytree.tree_map( + TensorBox.create, ir.FallbackKernel.create(aten.native_dropout, x, p, train) + ) + else: + raise AssertionError("should be handled in replace_random.py") + + +@register_lowering(aten.bernoulli_, type_promotion_kind=None) +def bernoulli_(x, *args): + assert config.fallback_random or x.get_device() == torch.device( + "cpu" + ), "this should be handled in decomps unless config.fallback_random or the device is CPU" + x.realize() + ir.InplaceBernoulliFallback(x, *args) + return x + + +@register_lowering(aten.bernoulli.p, type_promotion_kind=None) +def bernoulli_p(x, *args): + assert config.fallback_random or x.get_device() == torch.device( + "cpu" + ), "this should be handled in decomps unless config.fallback_random or the device is CPU" + return bernoulli_(clone(x), *args) + + +# This shouldn't be called in general +@register_lowering(aten._foobar) +def _foobar(_): + raise AssertionError() + + +@functools.lru_cache(1) +def _warn_triton_random(salt): + log.info("using triton random, expect difference from eager") + + +def warn_triton_random(): + # only warn once per graph + _warn_triton_random(V.graph.creation_time) + + +fallback_rand = fallback_handler(aten.rand) +fallback_randn = fallback_handler(aten.randn) +make_fallback(aten.randint) + + +@register_lowering(aten.rand) +def rand(*args, **kwargs): + if config.fallback_random or kwargs.get("generator", None) is not None: + return fallback_rand(*args, **kwargs) + raise AssertionError("should have been handled in replace_random.py") + + +@register_lowering(aten.randn) +def randn(*args, **kwargs): + if config.fallback_random or kwargs.get("generator", None) is not None: + return fallback_randn(*args, **kwargs) + raise AssertionError("should have been handled in replace_random.py") + + +@register_lowering(inductor_prims.force_stride_order, type_promotion_kind=None) +def inductor_force_stride_order(input_tensor, stride): + stride_order = ir.get_stride_order(stride) + return ir.ExternKernel.require_stride_order(input_tensor, stride_order) + + +@register_lowering(inductor_prims.seed, type_promotion_kind=None) +def inductor_seed(device: torch.device): + raise AssertionError("should be handled in fuse_seed_creation_pass()") + + +@register_lowering(inductor_prims.seeds, type_promotion_kind=None) +def inductor_seeds(count, device): + warn_triton_random() + return TensorBox.create(ir.RandomSeeds(count, decode_device(device))) + + +@register_lowering(inductor_prims.lookup_seed, type_promotion_kind=None) +def inductor_lookup_seed(seeds, index): + def inner_fn(_): + return ops.load_seed(seeds.get_name(), index) + + return Pointwise.create( + device=seeds.get_device(), + dtype=seeds.get_dtype(), + inner_fn=inner_fn, + ranges=[], + ) + + +@register_lowering(inductor_prims.random, type_promotion_kind=None) +def inductor_random(size: List[int], seed: TensorBox, mode: str, *, offset: int = 0): + assert not config.fallback_random + assert mode in ("rand", "randn") + size = [*size] + dtype = torch.float32 + device = seed.get_device() + random_pos = ir.FixedLayout( + device, dtype, size, ir.FlexibleLayout.contiguous_strides(size), offset=offset + ).make_indexer() + seed_loader = seed.make_loader() + + def inner_fn(index): + return getattr(ops, mode)( + seed_loader([]), + ops.index_expr(random_pos(index), torch.int32), + ) + + result = Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=[*size], + ) + result.realize() + return result + + +@register_lowering(inductor_prims.randint, type_promotion_kind=None) +def inductor_randint( + low: int, high: int, size: List[int], seed: TensorBox, *, offset: int = 0 +): + assert not config.fallback_random + size = [*size] + dtype = torch.int64 + device = seed.get_device() + random_pos = ir.FixedLayout( + device, dtype, size, ir.FlexibleLayout.contiguous_strides(size), offset=offset + ).make_indexer() + seed_loader = seed.make_loader() + + def inner_fn(index): + return ops.randint64( + seed_loader([]), + ops.index_expr(random_pos(index), torch.int32), + low, + high, + ) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=[*size], + ) + + +@register_lowering(aten.bucketize, type_promotion_kind=None) +def bucketize( + input: TensorBox, + boundaries: TensorBox, + *, + out_int32: bool = False, + right: bool = False, +): + assert len(boundaries.get_size()) == 1 + + if not (is_triton(input) and is_triton(boundaries)): + return fallback_handler(aten.bucketize, add_to_fallback_set=False)( + input, boundaries, out_int32=out_int32, right=right + ) + + # The entire boundaries tensor needs to be used by ops.bucketize, so we + # need to realize it into global memory; or in other words, we can't + # guarantee that boundaries.get_name() (used below) will exist unless + # we call boundaries.realize(). + boundaries.realize() + boundaries_size = boundaries.get_size()[0] + boundaries_loader = boundaries.make_loader() + device = input.get_device() + input_loader = input.make_loader() + + index_dtype = torch.int32 if out_int32 else torch.int64 + + def inner_fn(index): + val = input_loader(index) + indices = ops.bucketize( + val, + boundaries.get_name(), + boundaries_size, + index_dtype, + right, + ) + + return indices + + return Pointwise.create( + device=device, + dtype=index_dtype, + inner_fn=inner_fn, + ranges=input.get_size(), + ) + + +def require_dense(_, *args, **kwargs): + args, kwargs = pytree.tree_map_only( + ir.IRNode, lambda t: ir.ExternKernel.require_stride1(t), (args, kwargs) + ) + return args, kwargs + + +def require_contiguous(_, *args, **kwargs): + args, kwargs = pytree.tree_map_only( + ir.IRNode, lambda t: ir.ExternKernel.require_contiguous(t), (args, kwargs) + ) + return args, kwargs + + +def require_channels_last(_, *args, **kwargs): + args, kwargs = pytree.tree_map_only( + ir.IRNode, lambda t: ir.ExternKernel.require_channels_last(t), (args, kwargs) + ) + return args, kwargs + + +def constrain_to_fx_strides(fx_node, *args, **kwargs): + def apply_constraint(arg, fx_arg): + if isinstance(arg, ir.IRNode): + stride_order = ir.get_stride_order(fx_arg.meta["val"].stride()) + return ir.ExternKernel.require_stride_order(arg, stride_order) + return arg + + args = tuple( + apply_constraint(arg, fx_arg) for arg, fx_arg in zip(args, fx_node.args) + ) + kwargs = {k: apply_constraint(v, fx_node.kwargs[k]) for k, v in kwargs.items()} + return args, kwargs + + +# TODO(jansel): we should implement decomps or lowerings for these +# https://github.com/pytorch/torchdynamo/issues/327 +FALLBACK_ALLOW_LIST = { + "torchvision::roi_align", +} +make_fallback(aten._adaptive_avg_pool2d_backward, require_dense) +make_fallback(aten.convolution_backward, constrain_to_fx_strides) +make_fallback(aten._cudnn_rnn, require_dense) +make_fallback(aten._cudnn_rnn_backward, require_contiguous) +make_fallback(aten.cumsum, require_dense, warn=False) +make_fallback(aten.cumprod, require_dense, warn=False) +make_fallback(aten._embedding_bag, require_contiguous) +make_fallback(aten._embedding_bag_forward_only, require_contiguous) +make_fallback(aten._flash_attention_forward) +make_fallback(aten._flash_attention_backward) +make_fallback(aten._fused_moving_avg_obs_fq_helper) +make_fallback(aten._fused_moving_avg_obs_fq_helper_functional) +make_fallback(aten.grid_sampler_2d_backward, require_dense) +make_fallback(aten.randperm) +make_fallback(aten._scaled_dot_product_efficient_attention) +make_fallback(aten._scaled_dot_product_efficient_attention_backward) +make_fallback(aten._scaled_dot_product_flash_attention) +make_fallback(aten._scaled_dot_product_flash_attention_backward) +make_fallback(aten.sort) +make_fallback(aten.sort.stable) +make_fallback(aten._sparse_coo_tensor_with_dims_and_tensors) +make_fallback(aten._thnn_fused_lstm_cell, require_dense) +make_fallback(aten.topk) +make_fallback(aten.upsample_bicubic2d_backward, require_contiguous) + +make_fallback(aten.view_as_complex, require_contiguous) + +# The following were added as a result of https://github.com/pytorch/pytorch/pull/94039 to pass tests +# It's not necessarily a priority to implement these +make_fallback(aten.upsample_linear1d) +make_fallback(aten.upsample_trilinear3d) +make_fallback(aten.upsample_linear1d_backward) +make_fallback(aten.upsample_trilinear3d_backward) +make_fallback(aten._adaptive_avg_pool3d) +make_fallback(aten.adaptive_max_pool2d) +make_fallback(aten.adaptive_max_pool3d) +make_fallback(aten.addbmm) +make_fallback(aten.addmv, warn=False) +make_fallback(aten._addmm_activation, warn=False) +make_fallback(aten.avg_pool3d) +make_fallback(aten.block_diag) +make_fallback(aten._cdist_forward) +make_fallback(aten.cummax) +make_fallback(aten.cummin) +make_fallback(aten.cumprod, warn=False) +make_fallback(aten.digamma, warn=False) +make_fallback(aten._efficientzerotensor) +make_fallback(aten._embedding_bag_per_sample_weights_backward) +make_fallback(aten._efficientzerotensor) +make_fallback(aten._embedding_bag_per_sample_weights_backward) +make_fallback(aten.fractional_max_pool2d) +make_fallback(aten.fractional_max_pool3d) +make_fallback(aten.frexp) +make_fallback(aten.geqrf) +make_fallback(aten.histc) +make_fallback(aten.i0) +make_fallback(aten.igamma, warn=False) +make_fallback(aten.igammac, warn=False) +make_fallback(aten.isin) +make_fallback(aten.kthvalue) +make_fallback(aten.linalg_cholesky_ex) +make_fallback(aten.linalg_cross) +make_fallback(aten._linalg_det) +make_fallback(aten.linalg_householder_product) +make_fallback(aten.linalg_inv_ex) +make_fallback(aten.linalg_ldl_factor_ex) +make_fallback(aten.linalg_ldl_solve) +make_fallback(aten.linalg_lu) +make_fallback(aten.linalg_lu_factor_ex) +make_fallback(aten.linalg_lu_solve) +make_fallback(aten.linalg_matrix_exp) +make_fallback(aten.linalg_qr) +make_fallback(aten._linalg_slogdet) +make_fallback(aten._linalg_solve_ex) +make_fallback(aten.linalg_solve_triangular) +make_fallback(aten._linalg_svd) +make_fallback(aten.logcumsumexp) +make_fallback(aten.lu_unpack) +make_fallback(aten.max_pool3d_with_indices) +make_fallback(aten.max_unpool2d) +make_fallback(aten.max_unpool3d) +make_fallback(aten.median) +make_fallback(aten.mode) +make_fallback(aten.nanmedian) +make_fallback(aten.ormqr) +make_fallback(aten._pdist_forward) +make_fallback(aten.pixel_shuffle) +make_fallback(aten.pixel_unshuffle) +make_fallback(aten.polygamma) +make_fallback(aten.put) +make_fallback(aten.reflection_pad1d) +make_fallback(aten.replication_pad1d) +make_fallback(aten.resize) +make_fallback(aten.resize_) +make_fallback(aten.resize_as) +make_fallback(aten.resize_as_) +make_fallback(aten.searchsorted) +make_fallback(aten.special_airy_ai) +make_fallback(aten.special_bessel_j0, warn=False) +make_fallback(aten.special_bessel_j1, warn=False) +make_fallback(aten.special_bessel_y0, warn=False) +make_fallback(aten.special_bessel_y1) +make_fallback(aten.special_chebyshev_polynomial_t) +make_fallback(aten.special_chebyshev_polynomial_u) +make_fallback(aten.special_erfcx, warn=False) +make_fallback(aten.special_hermite_polynomial_h) +make_fallback(aten.special_hermite_polynomial_he) +make_fallback(aten.special_i0e, warn=False) +make_fallback(aten.special_i1, warn=False) +make_fallback(aten.special_i1e, warn=False) +make_fallback(aten.special_laguerre_polynomial_l) +make_fallback(aten.special_modified_bessel_i0) +make_fallback(aten.special_modified_bessel_i1) +make_fallback(aten.special_modified_bessel_k0) +make_fallback(aten.special_modified_bessel_k1) +make_fallback(aten.special_ndtri, warn=False) +make_fallback(aten.special_scaled_modified_bessel_k0) +make_fallback(aten.special_scaled_modified_bessel_k1) +make_fallback(aten.special_spherical_bessel_j0, warn=False) +make_fallback(aten.special_zeta, warn=False) +make_fallback(aten.take) +make_fallback(aten._trilinear) +make_fallback(aten.uniform, warn=False) +make_fallback(aten.unsafe_split, warn=False) +make_fallback(aten.vdot) +make_fallback(aten._adaptive_avg_pool3d_backward) +make_fallback(aten.adaptive_max_pool2d_backward) +make_fallback(aten.adaptive_max_pool3d_backward) +make_fallback(aten.avg_pool3d_backward) +make_fallback(aten._cdist_backward) +make_fallback(aten._embedding_bag_dense_backward) +make_fallback(aten.fractional_max_pool2d_backward) +make_fallback(aten.fractional_max_pool3d_backward) +make_fallback(aten._linalg_check_errors) +make_fallback(aten.max_pool3d_with_indices_backward) +make_fallback(aten._pdist_backward) +make_fallback(aten.reflection_pad1d_backward) +make_fallback(aten.replication_pad1d_backward) +make_fallback(aten.soft_margin_loss_backward, warn=False) +make_fallback(aten.linalg_pinv.atol_rtol_tensor) +make_fallback(aten.segment_reduce.default) +make_fallback(aten._segment_reduce_backward.default) +make_fallback(aten.angle) +make_fallback(aten.cholesky_inverse) +make_fallback(aten.cholesky_solve) +make_fallback(aten._fft_r2c) +make_fallback(aten.histogram.bin_ct) +make_fallback(aten._histogramdd_bin_edges.default) +make_fallback(aten._histogramdd_from_bin_cts.default) +make_fallback(aten.index_reduce) +make_fallback(aten.masked_scatter) +make_fallback(aten.to_sparse) +make_fallback(aten._to_sparse) +make_fallback(aten.triangular_solve) +make_fallback(aten.gcd.default, warn=False) +make_fallback(aten._linalg_eigh) +make_fallback(aten.zeros.names) + + +make_fallback(torch._prims.rng_prims.run_and_save_rng_state) +make_fallback(torch._prims.rng_prims.run_with_rng_state) + +# fails accuracy on test_torch.py, and explicit fallback required to avoid warn=True on implicit +make_fallback(aten.exponential.default, warn=False) + + +# Register with type_promotion_kind None. +# For example, fp16.copy_(fp32) should **not** promote the first input's dtype. +@register_lowering(aten.copy, type_promotion_kind=None) +def copy(self, src, non_blocking=False): + x = src + if self.get_device() != src.get_device(): + x = to_device(x, self.get_device()) + if self.get_dtype() != src.get_dtype(): + x = to_dtype(x, self.get_dtype()) + + if self.get_size() != src.get_size(): + out = expand(x, self.get_size()) + return clone(out) + return clone(x) + + +@register_lowering(aten.clone) +def clone(x, *, memory_format=None): + # TODO(jansel): memory format + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=x.make_loader(), + ranges=list(x.get_size()), + ) + + +if hasattr(aten, "lift_fresh_copy"): + register_lowering(aten.lift_fresh_copy)(clone) + + +@register_lowering(prims.iota) +def iota( + length, + *, + start, + step, + dtype, + device, + requires_grad, +): + def fn(index): + return ops.index_expr(step * index[0] + start, dtype=dtype) + + return Pointwise.create( + device=decode_device(device), + dtype=dtype, + inner_fn=fn, + ranges=[length], + ) + + +@register_lowering(aten.select_scatter, type_promotion_kind=None) +def select_scatter(x, src, dim: int, index: int): + assert x.get_dtype() == src.get_dtype() + x_loader = x.make_loader() + dim = _validate_dim(x, dim, 0) + if V.graph.sizevars.evaluate_expr(sympy.Lt(index, 0)): + index = index + x.get_size()[dim] + V.graph.sizevars.guard_leq(0, index) + V.graph.sizevars.guard_lt(index, x.get_size()[dim]) + src = expand(unsqueeze(src, dim), x.get_size()) + src_loader = src.make_loader() + + def inner_fn(idx): + return ops.where( + ops.eq( + ops.index_expr(idx[dim], torch.int32), + ops.index_expr(index, torch.int32), + ), + src_loader(idx), + x_loader(idx), + ) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=inner_fn, + ranges=list(x.get_size()), + ) + + +@register_lowering(aten.slice_scatter, type_promotion_kind=None) +def slice_scatter(x, src, dim=0, start=None, end=None, step=1): + assert x.get_dtype() == src.get_dtype() + x_loader = x.make_loader() + dim = _validate_dim(x, dim, 0) + dim_size = x.get_size()[dim] + if start is not None and V.graph.sizevars.evaluate_expr(sympy.Lt(start, 0)): + start = start + dim_size + if end is not None and V.graph.sizevars.evaluate_expr(sympy.Lt(end, 0)): + end = end + dim_size + if start is None: + start = 0 + if end is None or V.graph.sizevars.statically_known_leq(x.get_size()[dim], end): + end = dim_size + + src_size = list(x.get_size()) + src_size[dim] = FloorDiv(sympy.expand(end - start), sympy.expand(step)) + src = expand(src, src_size) + src_loader = src.make_loader() + + def inner_fn(idx): + if start == 0 and end == dim_size and step == 1: + # selecting every element is the same as just src.clone() + return src_loader(idx) + + idx_dim = ops.index_expr(idx[dim], torch.int64) + src_idx = list(idx) + src_idx[dim] = FloorDiv(idx[dim] - start, step) + + mask = [] + if start != 0: + mask.append( + ops.ge( + idx_dim, + ops.index_expr(sympy.expand(start), torch.int64), + ) + ) + if end != dim_size: + mask.append( + ops.lt( + idx_dim, + ops.index_expr(sympy.expand(end), torch.int64), + ) + ) + if step != 1: + mask.append( + ops.eq( + ops.index_expr( + ModularIndexing(idx[dim] - start, 1, step), torch.int64 + ), + ops.constant(0, torch.torch.int64), + ) + ) + assert mask + mask = functools.reduce(ops.and_, mask) + src_val = ops.masked( + mask, + lambda: src_loader(src_idx), + 0 if is_integer_type(x) else 0.0, + ) + return ops.where( + mask, + src_val, + x_loader(idx), + ) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=inner_fn, + ranges=list(x.get_size()), + ) + + +def _unwrap(x): + if isinstance(x, (list, tuple)) and len(x) > 0: + return _unwrap(x[0]) + return x + + +@register_lowering([torch.tensor, aten.scalar_tensor]) +def tensor(data, *, dtype=None, device=None, layout=None, pin_memory=False): + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + assert_nyi(not pin_memory, "pin_memory") + if isinstance(_unwrap(data), int): + dtype = dtype or torch.int64 + else: + dtype = dtype or torch.get_default_dtype() + + ranges: List[sympy.Expr] = [] + + if isinstance(data, sympy.Expr): + + def inner_fn(index): + return ops.index_expr(data, dtype) + + elif isinstance(data, (float, int)): + + def inner_fn(index): + return ops.constant(data, dtype) + + elif len(data) == 0 or isinstance(data[0], (float, int)) and len(data) <= 8: + # inline small tensors + ranges.append(sympy.Integer(len(data))) + + def inner_fn(index): + def binary_search(start, end): + assert start < end + if end - start == 1: + return ops.constant(data[start], dtype) + mid = (end - start) // 2 + start + return ops.where( + ops.lt( + ops.index_expr(index[0], torch.int64), + ops.constant(mid, torch.int64), + ), + binary_search(start, mid), + binary_search(mid, end), + ) + + if len(data) == 0: + return ops.constant(0, dtype) + return binary_search(0, len(data)) + + else: + return V.graph.add_tensor_constant( + torch.tensor(data, dtype=dtype, device=device) + ) + + return Pointwise.create( + device=decode_device(device), + dtype=dtype, + inner_fn=inner_fn, + ranges=ranges, + ) + + +@register_lowering(torch.as_tensor) +def as_tensor(data, dtype=None, device=None): + if isinstance(data, TensorBox): + if dtype is not None: + data = to_dtype(data, dtype) + if device is not None: + data = to_device(data, device) + return data + return tensor(data, dtype=dtype, device=device) + + +@register_lowering(torch.LongTensor) +def long_tensor(data): + return tensor(data, dtype=torch.int64) + + +@register_lowering(aten._local_scalar_dense) +def _local_scalar_dense(data): + return ir.DynamicScalar() + + +def _full(fill_value, device, dtype, size): + value = fill_value + if not isinstance(fill_value, (int, float)) and hasattr(value, "value"): + value = value.value + + if isinstance(value, (int, float)): + + def inner_fn(index): + return ops.constant(value, dtype) + + elif isinstance(value, sympy.Expr): + + def inner_fn(index): + return ops.index_expr(value, dtype) + + else: + assert len(value.get_size()) == 0 + value_loader = value.make_loader() + + def inner_fn(index): + return value_loader([]) + + return Pointwise.create( + device=device, + dtype=dtype, + inner_fn=inner_fn, + ranges=list(size), + ) + + +@register_lowering(aten.full_like, type_promotion_kind=None) +def full_like(x, fill_value, **kwargs): + return create_tensor_like(tensor_constructor(fill_value))(x, **kwargs) + + +def tensor_constructor(fill_value): + # torch.zeros, torch.ones, etc + def inner( + *size, + names=None, + dtype=None, + device=None, + layout=None, + pin_memory=False, + memory_format=None, + ): + assert_nyi(names is None, "named tensors") + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + assert_nyi(not pin_memory, "pin_memory") + device = decode_device(device) + dtype = dtype or torch.get_default_dtype() + if len(size) == 1 and isinstance(size[0], (list, tuple, torch.Size)): + size = tuple(size[0]) + size = [sympy.expand(s) for s in size] + return _full(fill_value, device, dtype, size) + + return inner + + +@register_lowering([torch.empty, aten.empty]) +def empty( + *size, + names=None, + dtype=None, + layout=None, + device=None, + pin_memory=None, + memory_format=None, +): + assert_nyi(names is None, "named tensors") + device = decode_device(device) + if len(size) == 1 and isinstance(size[0], (list, tuple, torch.Size)): + size = tuple(size[0]) + return empty_strided( + size, None, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +def create_tensor_like(creation_fn): + """ + Shim to convert X_like(...) into X(...). For example zeros_like() into zeros(). + """ + + def _constant_like( + x, *, dtype=None, device=None, layout=None, pin_memory=False, memory_format=None + ): + assert_nyi(not pin_memory, "pin_memory") + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + if dtype is None: + dtype = x.get_dtype() + else: + dtype = decode_dtype(dtype) + device = device or x.get_device() + size = list(x.get_size()) + return creation_fn( + size, dtype=dtype, device=device, layout=layout, pin_memory=pin_memory + ) + + return _constant_like + + +def constant_like(fill_value): + return create_tensor_like(tensor_constructor(fill_value)) + + +empty_like = register_lowering(aten.empty_like)(create_tensor_like(empty)) +ones_like = create_tensor_like(tensor_constructor(1)) +zeros_like = create_tensor_like(tensor_constructor(0)) + + +def new_constant(fill_value): + def _new_constant( + x, size, *, dtype=None, layout=None, device=None, pin_memory=None + ): + assert isinstance(size, (list, tuple)) + assert_nyi(not pin_memory, "pin_memory") + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + dtype = decode_dtype(dtype) or x.get_dtype() + device = device or x.get_device() + size = [sympy.Integer(s) for s in size] + return _full(fill_value, device, dtype, size) + + return _new_constant + + +@register_lowering(aten.new_empty) +def new_empty(x, size, *, dtype=None, layout=None, device=None, pin_memory=None): + if dtype is None: + dtype = x.get_dtype() + if device is None: + device = x.get_device() + return empty_strided( + size, None, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_lowering(aten.empty_strided) +def empty_strided( + size, stride, *, dtype=None, layout=None, device=None, pin_memory=None +): + assert isinstance(size, (list, tuple)) + assert isinstance(stride, (list, tuple, type(None))) + assert_nyi(not pin_memory, "pin_memory") + assert_nyi(layout in (None, torch.strided), f"layout={layout}") + dtype = decode_dtype(dtype) or torch.get_default_dtype() + device = device or torch.tensor(0.0).device + pointwise = _full(fill_value=0, device=device, dtype=dtype, size=size) + pointwise.realize() + buffer = pointwise.data.data + # explicitly set ranges to zeros in order to make a NopKernelSchedulerNode + buffer.data.ranges = [0] * len(size) + assert isinstance(buffer, ir.ComputedBuffer) + size = [sympy.expand(s) for s in size] + stride = ( + [sympy.expand(s) for s in stride] + if stride + else ir.FlexibleLayout.contiguous_strides(size) + ) + buffer.layout = ir.FixedLayout( + device=device, + dtype=dtype, + size=size, + stride=stride, + ) + return pointwise + + +@register_lowering(aten.new_empty_strided) +def new_empty_strided( + x, size, stride, *, dtype=None, layout=None, device=None, pin_memory=None +): + if dtype is None: + dtype = x.get_dtype() + if device is None: + device = x.get_device() + return empty_strided( + size, stride, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory + ) + + +@register_lowering(prims.copy_strided.default) +def copy_strided(x, stride): + stride = [V.graph.sizevars.size_hint(s) for s in stride] + stride_order = sorted(range(len(stride)), key=stride.__getitem__) + return ir.ExternKernel.require_stride_order(x, stride_order) + + +@register_lowering([torch.full, aten.full]) +def full(size, fill_value, **kwargs): + dtype = kwargs.get("dtype") + kwargs["dtype"] = dtype if dtype is not None else type_to_dtype(type(fill_value)) + return tensor_constructor(fill_value)(size, **kwargs) + + +@register_lowering(aten.gather, type_promotion_kind=None) +def gather(x, dim, index, sparse_grad=False): + # sparse_grad doesn't affect forward computation, + # and backward tracing is taken care of by AOT Autograd + assert isinstance(x, TensorBox) + assert index.get_dtype() == torch.int64 + size = x.get_size() + offset = len(size) == 0 + dim = _validate_dim(x, dim, offset) + + x_loader = x.make_loader() + index_loader = index.make_loader() + + def fn(idx): + idx = list(idx) + if len(idx) != 0: + idx[dim] = ops.indirect_indexing(index_loader(idx), size[dim]) + return x_loader(idx) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=index.get_size(), + ) + + +@register_lowering(aten.embedding, type_promotion_kind=None) +def embedding(weight, indices, padding_idx=-1, scale_grad_by_freq=False, sparse=False): + assert not sparse + assert isinstance(weight, TensorBox) + assert isinstance(indices, TensorBox) + assert "int" in str(indices.get_dtype()) + + weight_loader = weight.make_loader() + indices_loader = indices.make_loader() + indices_ndim = len(indices.get_size()) + weight_size = weight.get_size() + new_size = [*indices.get_size(), *weight_size[1:]] + + def fn(idx): + assert len(idx) == len(new_size), f"{idx} != {new_size}" + var_index = indices_loader(idx[:indices_ndim]) + weight_idx = [ops.indirect_indexing(var_index, weight_size[0])] + [ + *idx[indices_ndim:] + ] + return weight_loader(weight_idx) + + return Pointwise.create( + device=weight.get_device(), + dtype=weight.get_dtype(), + inner_fn=fn, + ranges=new_size, + ) + + +def check_and_broadcast_indices(indices, device): + assert all( + i.get_dtype() in (torch.int64, torch.int32, torch.bool, torch.uint8) + for i in indices + if i is not None + ), f"indices must be int64, byte or bool. Got {[i.get_dtype() for i in indices if i is not None]}" + if any( + i.get_dtype() in (torch.bool, torch.uint8) for i in indices if i is not None + ): + raise NotImplementedError("Fallback for bool indices") + + valid_idxs = [i for i, x in enumerate(indices) if isinstance(x, TensorBox)] + assert len(valid_idxs) > 0, "requires at least 1 non-None index" + new_indices = [None] * len(indices) + for i, x in zip(valid_idxs, broadcast_tensors(*[indices[i] for i in valid_idxs])): + # Eager allows indices to be CPU tensor when running on CUDA + # FIXME: Calling to_device(x, device) should work but + # test_advancedindex_mixed_cpu_devices still fails + if x.get_device() != device: + raise NotImplementedError("Fallback when indices is on a different device") + new_indices[i] = x + output_dim = len(x.get_size()) + start_offset = 0 + # only support None at start or end for now + tmp = list(new_indices) + while tmp and tmp[-1] is None: + tmp.pop() + while tmp and tmp[0] is None: + tmp.pop(0) + start_offset += 1 + if any((i is None) for i in tmp): + raise NotImplementedError("Fallback when None is in the middle of indices") + + end_offset = output_dim + start_offset + return new_indices, start_offset, end_offset + + +def index_impl(x, indices, check): + assert isinstance(indices, (list, tuple)) + x_loader = x.make_loader() + indices, start_offset, end_offset = check_and_broadcast_indices( + indices, x.get_device() + ) + + indices_sizes = [i.get_size() for i in indices if i is not None] + indices_loaders = [i.make_loader() for i in indices if i is not None] + # no guards on output size, all the guards are set in broadcast_tensors + + output_size = list(indices_sizes[0]) + + x_size = x.get_size() + + indexed_size = [x_size[i] for i in range(len(indices)) if indices[i] is not None] + if 0 in indexed_size and 0 not in output_size: + raise IndexError("index is out of bounds for dimension with size 0") + + output_size = [ + *x_size[:start_offset], + *output_size, + *x_size[start_offset + len(indices_loaders) :], + ] + + def fn(idx): + assert len(idx) == len(output_size) + assert len(indices_loaders) == len(indexed_size) + new_index = [ + ops.indirect_indexing( + loader(idx[start_offset:end_offset]), size, check=check + ) + for loader, size in zip(indices_loaders, indexed_size) + ] + new_index = [*idx[:start_offset], *new_index, *idx[end_offset:]] + return x_loader(new_index) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=output_size, + ) + + +@register_lowering(aten.index, type_promotion_kind=None) +def index(x, indices): + try: + return index_impl(x, indices, check=True) + except NotImplementedError: + # Fallback to ATen for boolean indexing + x.realize() + return fallback_handler(aten.index)(x, indices) + + +@register_lowering(aten._unsafe_index, type_promotion_kind=None) +def _unsafe_index(x, indices): + return index_impl(x, indices, check=False) + + +# All the indexing decompositions are written in terms of index, index_put, and index_put_ +# We cannot have this lowering as a decomposition as it introduces +# mutation in the graph, which is bad for Aot Autograd. Aot Autograd runs dead +# code elimination and common subexpression elimination optimizations, which +# assume graphs to be side-effect free. More details at +# https://github.com/pytorch/torchdynamo/issues/1235 +# and +# https://github.com/pytorch/torchdynamo/issues/1863 +@register_lowering(aten.index_put) +def index_put(x, indices, values, accumulate=False): + return index_put_(clone(x), indices, values, accumulate) + + +@register_lowering(aten._unsafe_index_put) +def _unsafe_index_put(x, indices, values, accumulate=False): + return index_put_impl_(clone(x), indices, values, accumulate, check=False) + + +def index_put_as_masked_fill(self, indices, value, accumulate): + if value.get_device() != self.get_device(): + value = to_device(value, self.get_device()) + if accumulate: + value = add(self, value) + return mutate_to(self, where(indices[0], value, self)) + + +def index_put_fallback(self, indices, values, accumulate): + if is_triton(values) and ( + accumulate is True or torch.are_deterministic_algorithms_enabled() + ): + V.graph.disable_cudagraphs = True + ir.IndexPutFallback(self, indices, values, accumulate) + return self + + +@register_lowering(aten.index_put_, type_promotion_kind=None) +def index_put_(self, indices, values, accumulate=False): + return index_put_impl_(self, indices, values, accumulate, check=True) + + +def index_put_impl_(self, indices, values, accumulate, check): + # Dispatch to masked fill for single boolean index with single value + if ( + values.get_numel() == 1 + and len(indices) == 1 + and indices[0].get_dtype() in {torch.bool, torch.uint8} + ): + mask = indices[0] + for _ in range(len(mask.get_size()), len(self.get_size())): + mask = unsqueeze(mask, -1) + return index_put_as_masked_fill(self, [mask], values, accumulate) + + # Fallback in torch deterministic mode + if torch.are_deterministic_algorithms_enabled(): + return index_put_fallback(self, indices, values, accumulate) + + # Fallback if there is a boolean index + for index in indices: + if index is not None and index.get_dtype() in {torch.bool, torch.uint8}: + return index_put_fallback(self, indices, values, accumulate) + + x_size = self.get_size() + x_ndim = len(x_size) + + # fallback to aten.index_put_, as tl.atomic_add does NOT support int64 or bool + if self.get_dtype() in {torch.int64, torch.bool}: + # self is an scalar Tensor + if x_ndim == 0: + self = view(self, [1]) + self = index_put_fallback(self, indices, values, accumulate) + if x_ndim == 0: + self = view(self, []) + return self + + values = to_dtype(values, self.get_dtype()) + try: + indices, start_offset, end_offset = check_and_broadcast_indices( + indices, self.get_device() + ) + except NotImplementedError: + return index_put_fallback(self, indices, values, accumulate) + indices_sizes = [i.get_size() for i in indices if i is not None] + indices_loaders = [i.make_loader() for i in indices if i is not None] + + assert isinstance(self, TensorBox) + self.realize() + + # self is an scalar Tensor + if x_ndim == 0: + self = view(self, [1]) + + output_size = list(indices_sizes[0]) + expected_vals_size = [ + *x_size[:start_offset], + *output_size, + *x_size[start_offset + len(indices_sizes) :], + ] + indexed_size = [x_size[i] for i in range(len(indices)) if indices[i] is not None] + + values = expand(values, expected_vals_size) + # all guards are set above during broadcast_tensors and expand + + def output_indexer(index): + assert len(index) == len(expected_vals_size) + new_index = [ + ops.indirect_indexing( + loader(index[start_offset:end_offset]), size, check=check + ) + for loader, size in zip(indices_loaders, indexed_size) + ] + new_index = [*index[:start_offset], *new_index, *index[end_offset:]] + return new_index + + scatter = ir.Scatter( + device=self.get_device(), + dtype=self.get_dtype(), + inner_fn=values.make_loader(), + ranges=expected_vals_size, # iter_ranges, + output_indexer=output_indexer, + scatter_mode="atomic_add" if accumulate else None, + ) + buffer = ir.ComputedBuffer( + None, + ir.MutationLayout(self), + scatter, + ) + buffer.name = V.graph.register_buffer(buffer) + + if x_ndim == 0: + self = view(self, []) + return self + + +@register_lowering(aten.as_strided_scatter, type_promotion_kind=None) +def as_strided_scatter(self, src, size, stride, storage_offset=None): + output = clone(self) + output_view = as_strided(output, size, stride, storage_offset) + copy_(output_view, src) + return output + + +@register_lowering(aten.scatter, type_promotion_kind=None) +def scatter(x, dim: int, index, src, **kwargs): + return scatter_(clone(x), dim, index, src, **kwargs) + + +def scatter_fallback( + fn, + self, + dim: int, + index, + src, + *, + reduce: Optional[str] = None, + include_self: bool = True, +): + reduce_ty = "add" if fn == "aten.scatter_" else "sum" + if ( + reduce not in {None, reduce_ty} + or (reduce == reduce_ty and self.get_dtype() in {torch.bool, torch.int64}) + or torch.are_deterministic_algorithms_enabled() + ): + ir.ScatterFallback( + fn, self, dim, index, src, reduce=reduce, include_self=include_self + ) + return self + + return None + + +@register_lowering(aten.scatter_, type_promotion_kind=None) +def scatter_(self, dim: int, index, src, *, reduce: Optional[str] = None): + assert reduce in {None, "add", "multiply"} + + fallback_result = scatter_fallback( + "aten.scatter_", self, dim, index, src, reduce=reduce + ) + + if fallback_result: + return fallback_result + + if reduce == "add": + reduce = "sum" + elif reduce == "multiply": + reduce = "prod" + + return scatter_reduce_(self, dim, index, src, reduce) + + +@register_lowering(aten.scatter_add, type_promotion_kind=None) +def scatter_add(x, dim: int, index, src): + return scatter_add_(clone(x), dim, index, src) + + +@register_lowering(aten.scatter_add_, type_promotion_kind=None) +def scatter_add_(x, dim: int, index, src): + return scatter_reduce_(clone(x), dim, index, src, "sum") + + +@register_lowering(aten.scatter_reduce, type_promotion_kind=None) +def scatter_reduce(x, dim: int, index, src, reduction_type, **kwargs): + return scatter_reduce_(clone(x), dim, index, src, reduction_type, **kwargs) + + +@register_lowering(aten.scatter_reduce_, type_promotion_kind=None) +def scatter_reduce_(self, dim: int, index, src, reduce, *, include_self: bool = True): + assert reduce in {None, "sum", "prod", "mean", "amax", "amin"} + + fallback_result = scatter_fallback( + "aten.scatter_reduce_", + self, + dim, + index, + src, + reduce=reduce, + include_self=include_self, + ) + + if fallback_result: + return fallback_result + + assert isinstance(self, TensorBox) + assert "int" in str(index.get_dtype()) + + ndim = len(self.get_size()) + if ndim == 0: + self = view(self, [1]) + + if isinstance(src, TensorBox) and len(src.get_size()) == 0: + src = view(src, [1]) + + if isinstance(index, TensorBox) and len(index.get_size()) == 0: + index = view(index, [1]) + + dim = _validate_dim(self, dim) + + self.realize() + index_loader = index.make_loader() + src_loader = src.make_loader() if isinstance(src, TensorBox) else None + + def output_indexer(idx): + # self is captured from the end of the function, so it may have 0 dim + shape = self.get_size() + ndim = len(shape) + indirect_idx = list(idx) + indirect_idx[dim] = ops.indirect_indexing( + index_loader(idx), 1 if ndim == 0 else shape[dim] + ) + return indirect_idx + + def fn(idx): + if src_loader: + return src_loader(idx) + else: + # src is a scalar + return ops.constant(src, self.get_dtype()) + + def backend_reduce_str(reduce): + if reduce == "sum": + return "atomic_add" + else: + # TODO: Need to support more reduction type + assert reduce is None + return None + + if not include_self: + # zero out the corresponding elements first + zero_out = ir.Scatter( + device=self.get_device(), + dtype=self.get_dtype(), + inner_fn=lambda index: ops.constant(0, self.get_dtype()), + ranges=index.get_size(), + output_indexer=output_indexer, + scatter_mode=None, + ) + buffer = ir.ComputedBuffer( + None, + ir.MutationLayout(self), + zero_out, + ) + buffer.name = V.graph.register_buffer(buffer) + + # self[index[i][j][k]][j][k] += src[i][j][k] # if dim == 0 + # self[i][index[i][j][k]][k] += src[i][j][k] # if dim == 1 + # self[i][j][index[i][j][k]] += src[i][j][k] # if dim == 2 + scatter = ir.Scatter( + device=self.get_device(), + dtype=self.get_dtype(), + inner_fn=fn, + ranges=index.get_size(), + output_indexer=output_indexer, + scatter_mode=backend_reduce_str(reduce), + ) + buffer = ir.ComputedBuffer( + None, + ir.MutationLayout(self), + scatter, + ) + buffer.name = V.graph.register_buffer(buffer) + + if ndim == 0: + self = view(self, []) + return self + + +def upsample_nearestnd( + x, output_size, scales_x: Tuple[Optional[float], ...], n: int = 2 +): + x.realize_hint() # elements are reused + x_loader = x.make_loader() + i_sizes = x.get_size()[-n:] + batch = x.get_size()[:-n] + i_sizes = [V.graph.sizevars.evaluate_static_shape(i) for i in i_sizes] + + assert len(scales_x) == n + o_sizes = output_size + + scales = [i / o for i, o in zip(i_sizes, o_sizes)] + for i, scale in enumerate(scales): + if scale: + scales[i] = scale + + def scale_fn(x, scale, size): + x = ops.index_expr(x, torch.float32) + x = ops.mul(x, ops.constant(scale, torch.float32)) + x = ops.to_dtype(x, torch.int32) + return ops.indirect_indexing(x, size, check=False) + + def fn(idx): + x = idx[-n:] + b = idx[:-n] + return x_loader( + [*b, *[scale_fn(i, s, size) for i, s, size in zip(x, scales, i_sizes)]] + ) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=[*batch, *o_sizes], + ) + + +@register_lowering(aten.upsample_nearest1d.default) +def upsample_nearest1d(x, output_size, scales: Optional[float] = None): + return upsample_nearestnd(x, output_size, (scales,), n=1) + + +@register_lowering(aten.upsample_nearest2d.default) +def upsample_nearest2d( + x, output_size, scales_h: Optional[float] = None, scales_w: Optional[float] = None +): + return upsample_nearestnd(x, output_size, (scales_h, scales_w), n=2) + + +@register_lowering(aten.upsample_nearest3d.default) +def upsample_nearest3d( + x, + output_size, + scales_d: Optional[float] = None, + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +): + return upsample_nearestnd(x, output_size, (scales_d, scales_h, scales_w), n=3) + + +def _create_constants(*args, dtype): + return tuple(ops.constant(a, dtype) for a in args) + + +@register_lowering(aten.upsample_bicubic2d.default) +def upsample_bicubic2d_default( + x, + output_size, + align_corners: bool, + scales_h: Optional[float] = None, + scales_w: Optional[float] = None, +): + x.realize_hint() + x_loader = x.make_loader() + + N, C, iH, iW = x.get_size() + oH, oW = output_size + + iH = V.graph.sizevars.evaluate_static_shape(iH) + iW = V.graph.sizevars.evaluate_static_shape(iW) + + def get_int_dtype(maxval): + if maxval > torch.iinfo(torch.int32).max: + return torch.int64 + return torch.int32 + + def compute_scale(in_size, out_size, align_corners, scale=None): + if align_corners: + return (in_size - 1) / (out_size - 1) if out_size > 1 else 0 + else: + return 1 / scale if scale is not None and scale > 0 else in_size / out_size + + def compute_source_index(scale, dst_index, align_corners): + dst_index_ie = ops.index_expr(dst_index, torch.float32) + scale = ops.constant(scale, torch.float32) + if align_corners: + return ops.mul(scale, dst_index_ie) + else: + half = ops.constant(0.5, torch.float32) + return scale * (dst_index_ie + half) - half + + def cubic_convolution1(x, A): + _Ap2, _Ap3, _1 = _create_constants(A + 2, A + 3, 1, dtype=torch.float32) + return (_Ap2 * x - _Ap3) * x * x + _1 + + def cubic_convolution2(x, A): + _A, _4A, _5A, _8A = _create_constants( + A, 4 * A, 5 * A, 8 * A, dtype=torch.float32 + ) + return ((_A * x - _5A) * x + _8A) * x - _4A + + def get_cubic_upsample_coefficients(t): + A = -0.75 + _1 = ops.constant(1.0, torch.float32) + c0 = cubic_convolution2(ops.add(t, _1), A) + c1 = cubic_convolution1(t, A) + + x2 = ops.sub(_1, t) + c2 = cubic_convolution1(x2, A) + c3 = cubic_convolution2(ops.add(x2, _1), A) + return (c0, c1, c2, c3) + + def cubic_interp1d(xs, t): + cs = get_cubic_upsample_coefficients(t) + # dot product between xs and cs + return xs[0] * cs[0] + xs[1] * cs[1] + xs[2] * cs[2] + xs[3] * cs[3] + + height_scale = compute_scale(iH, oH, align_corners, scales_h) + width_scale = compute_scale(iW, oW, align_corners, scales_h) + + def clamp(v, min, max): + return ops.maximum(min, ops.minimum(max, v)) + + def fn(idx): + n, c, oy, ox = idx + + real_x = compute_source_index(width_scale, ox, align_corners) + in_x = ops.floor(real_x) + t_x = ops.sub(real_x, in_x) + + real_y = compute_source_index(height_scale, oy, align_corners) + in_y = ops.floor(real_y) + t_y = ops.sub(real_y, in_y) + + def load_bounded(fy, fx): + # TODO(Lezcano) Here we may not need to set-up a device_size + _0 = ops.constant(0, torch.int32) + iHm1 = ops.constant(iH - 1, torch.int32) + iWm1 = ops.constant(iW - 1, torch.int32) + iy = ops.indirect_indexing(clamp(fy, _0, iHm1), iH, check=False) + ix = ops.indirect_indexing(clamp(fx, _0, iWm1), iW, check=False) + return x_loader([n, c, iy, ix]) + + iy = ops.to_dtype(in_y, get_int_dtype(iH + 1)) + ix = ops.to_dtype(in_x, get_int_dtype(iW + 1)) + iys_ofs = tuple(ops.add(iy, ofs) for ofs in (-1, 0, 1, 2)) + ixs_ofs = tuple(ops.add(ix, ofs) for ofs in (-1, 0, 1, 2)) + + def get_x_interp(y): + coeffs_x = tuple(load_bounded(y, x) for x in ixs_ofs) + return cubic_interp1d(coeffs_x, t_x) + + coeffs_y = tuple(get_x_interp(y) for y in iys_ofs) + return cubic_interp1d(coeffs_y, t_y) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=[N, C, sympy.Integer(oH), sympy.Integer(oW)], + ) + + +@register_lowering(aten.reflection_pad2d) +def reflection_pad2d(x, padding): + assert len(padding) == 4 + left, right, top, bot = padding + + x_loader = x.make_loader() + *batch, h, w = x.get_size() + h = V.graph.sizevars.evaluate_static_shape(h) + w = V.graph.sizevars.evaluate_static_shape(w) + + def reflect(x, size, offset): + size_num = size + size = ops.constant(size - 1, torch.int32) + x = ops.index_expr(x, torch.int32) + x = ops.sub(x, ops.constant(offset, torch.int32)) + x = ops.sub(size, ops.abs(ops.sub(size, ops.abs(x)))) + return ops.indirect_indexing(x, size_num, check=False) + + def fn(idx): + *b, x, y = idx + x = reflect(x, h, top) + y = reflect(y, w, left) + return x_loader([*b, x, y]) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=[*batch, sympy.Integer(h + top + bot), sympy.Integer(w + left + right)], + ) + + +@register_lowering(aten.reflection_pad2d_backward) +def reflection_pad2d_backward(grad_output, x, padding): + assert len(padding) == 4 + left, right, top, bot = padding + + *_, h, w = x.get_size() + h = V.graph.sizevars.evaluate_static_shape(h) - 1 + w = V.graph.sizevars.evaluate_static_shape(w) - 1 + grad_loader = grad_output.make_loader() + *_, h_grad, w_grad = grad_output.get_size() + + def fn(idx): + *b, x, y = idx + + def load_from_output(x, y): + return grad_loader([*b, x, y]) + + def index_range_condition(index_range): + i, lb, ub = index_range + i = ops.index_expr(i, torch.int32) + lb = ops.index_expr(lb, torch.int64) + ub = ops.index_expr(ub, torch.int64) + return ops.and_(ops.ge(i, lb), ops.le(i, ub)) + + # Areas after reflection: + # + # top-left | top | top-right + # ----------------------------------------- + # left | center | right + # ----------------------------------------- + # bottom-left | bottom | bottom-right + # + # The center area is the original matrix. Other areas are reflections. + + center_x, center_y = x + top, y + left + top_reflect_x, left_reflect_y = top - x, left - y + bot_reflect_x, right_reflect_y = 2 * h + top - x, 2 * w + left - y + + # Accumulate gradients from different areas + # If some of the padding is negative, center load is not always valid + range_cx = (center_x, 0, h + top + bot) + range_cy = (center_y, 0, w + left + right) + cond = ops.and_( + index_range_condition(range_cx), index_range_condition(range_cy) + ) + grad = ops.masked(cond, lambda: load_from_output(center_x, center_y), 0.0) + + def accumulate(out_x, out_y, index_range1, index_range2=None): + nonlocal grad + + # If the upper bound is less than the lower bound, we can get rid of one accumulation. + # This happens when the padding size is zero. + upper_less_than_lower1 = index_range1[2] < index_range1[1] + if isinstance(upper_less_than_lower1, bool) and upper_less_than_lower1: + return + cond = index_range_condition(index_range1) + if index_range2 is not None: + upper_less_than_lower2 = index_range2[2] < index_range2[1] + if isinstance(upper_less_than_lower2, bool) and upper_less_than_lower2: + return + cond = ops.and_(cond, index_range_condition(index_range2)) + g = ops.masked(cond, lambda: load_from_output(out_x, out_y), 0.0) + grad = ops.add(grad, g) + + accumulate(center_x, left_reflect_y, range_cx, (y, 1, left)) + accumulate(center_x, right_reflect_y, range_cx, (y, w - right, w - 1)) + accumulate(top_reflect_x, center_y, (x, 1, top), range_cy) + accumulate(bot_reflect_x, center_y, (x, h - bot, h - 1), range_cy) + accumulate(top_reflect_x, left_reflect_y, (x, 1, top), (y, 1, left)) + accumulate(top_reflect_x, right_reflect_y, (x, 1, top), (y, w - right, w - 1)) + accumulate(bot_reflect_x, left_reflect_y, (x, h - bot, h - 1), (y, 1, left)) + accumulate( + bot_reflect_x, right_reflect_y, (x, h - bot, h - 1), (y, w - right, w - 1) + ) + + return grad + + return Pointwise.create( + device=grad_output.get_device(), + dtype=grad_output.get_dtype(), + inner_fn=fn, + ranges=list(x.get_size()), + ) + + +@register_lowering(prims.rev.default) +def rev(x, dims): + # note - dims pre-canonicalized + x_loader = x.make_loader() + sizes = x.get_size() + + def loader(idx): + idx = list(idx) + assert len(idx) == len(sizes) + for dim in dims: + idx[dim] = (sizes[dim] - 1) - idx[dim] + + return x_loader(idx) + + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=loader, + ranges=sizes, + ) + + +@register_lowering(aten.constant_pad_nd, type_promotion_kind=None) +def constant_pad_nd(x, padding, fill_value=0): + assert (len(padding) % 2) == 0 + if all(p == 0 for p in padding): + return clone(x) + + sizes = x.get_size() + + bounds = list(reversed(list(zip(padding[::2], padding[1::2])))) + n = len(sizes) - len(bounds) + + # if padding is a complicated expression, hoist it + bounds_precomp = [] + for l, h in bounds: + l_precomp = ( + V.graph.sizevars.lookup_precomputed_size(l) + if isinstance(l, sympy.Expr) and l.free_symbols + else l + ) + bounds_precomp.append((l_precomp, h)) + + output_size = list(sizes[:n]) + mask_sizes = [] + for (low, high), size in zip(bounds, sizes[n:]): + mask_sizes.append(size) + output_size.append(sympy.expand(size + low + high)) + assert len(output_size) == len(sizes) + fill_value = dtype_to_type(x.get_dtype())(fill_value) + + def mask(index): + mask = [] + for idx, (low, high), length in zip(index[n:], bounds, mask_sizes): + if low != 0: + mask.append(range_mask_low(idx, 0)) + if high != 0: + mask.append(range_mask_high(idx, length)) + mask = functools.reduce(ops.and_, mask) + return ops.masked(mask, lambda: x_loader(index), fill_value) + + def offset_fn(index): + new_index = list(index[:n]) + for idx, (low, high) in zip(index[n:], bounds_precomp): + new_index.append(idx - low) + assert len(new_index) == len(index) + return mask(new_index) + + x_loader = x.make_loader() + return Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=offset_fn, + ranges=output_size, + ) + + +def range_mask_low(i: sympy.Expr, low: Union[sympy.Expr, int]): + return ops.ge( + ops.index_expr(i, torch.int64), + ops.index_expr(sympy.Integer(low), torch.int64), + ) + + +def range_mask_high(i: sympy.Expr, high: sympy.Expr): + return ops.lt( + ops.index_expr(i, torch.int64), + ops.index_expr(high, torch.int64), + ) + + +def range_mask(i: sympy.Expr, high: sympy.Expr, low: sympy.Expr): + return ops.and_( + range_mask_low(i, low), + range_mask_high(i, high), + ) + + +def constant_boundary_condition_2d(x, fill_value, padding=None, pad_fill_value=1.0): + *_, h, w = x.get_size() + x_loader = x.make_loader() + padding_h = padding[0] if padding else 0 + padding_w = padding[1] if padding else 0 + + def load(index): + *prefix, ih, iw = index + + mask = ops.and_( + range_mask(ih, h + padding_h, -padding_h), + range_mask(iw, w + padding_w, -padding_w), + ) + return ( + ops.masked( + mask, + lambda: constant_boundary_condition_2d(x, pad_fill_value)( + [*prefix, ih, iw] + ), + fill_value, + ) + if padding + else ops.masked(mask, lambda: x_loader([*prefix, ih, iw]), fill_value) + ) + + return load + + +def pooling_size(x, i, kernel_size, stride, padding, ceil_mode): + x_out = FloorDiv( + x + 2 * padding[i] - (kernel_size[i] - 1) + (stride[i] - 1), stride[i] + ) + + if ceil_mode: + x_alt = FloorDiv( + x + 2 * padding[i] - (kernel_size[i] - 1) + 2 * (stride[i] - 1), stride[i] + ) + if V.graph.sizevars.size_hint((x_alt - 1) * stride[i] - x - padding[i]) >= 0: + # Sliding windows must start within the input or left padding + x_alt -= 1 + V.graph.sizevars.guard_leq(0, x_alt * stride[i] - x - padding[i]) + if V.graph.sizevars.size_hint(x_out - x_alt) == 0: + # ceil mode is actually a no-op, lets guard on that + V.graph.sizevars.guard_equals(x_out, x_alt) + ceil_mode = False + else: + x_out = x_alt + return x_out, ceil_mode + + +fallback_max_pool2d_with_indices = fallback_handler(aten.max_pool2d_with_indices) + + +@register_lowering(aten.max_pool2d_with_indices, type_promotion_kind=None) +def max_pool2d_with_indices( + x, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False +): + if padding == 0: + padding = [0, 0] + if dilation == 1: + dilation = [1, 1] + if not stride: + stride = kernel_size + kernel_size = pad_listlike(kernel_size, 2) + stride = pad_listlike(stride, 2) + padding = pad_listlike(padding, 2) + dilation = pad_listlike(dilation, 2) + + assert isinstance(x, TensorBox) + assert len(kernel_size) == 2 + assert len(stride) == 2 + assert len(padding) == 2 + assert len(dilation) == 2 + assert len(x.get_size()) in (3, 4) + + x.realize_hint() + *batch, h, w = x.get_size() + + h_out, ceil_mode1 = pooling_size(h, 0, kernel_size, stride, padding, ceil_mode) + w_out, ceil_mode2 = pooling_size(w, 1, kernel_size, stride, padding, ceil_mode) + + if padding[0] or padding[1] or ceil_mode1 or ceil_mode2: + x_loader = constant_boundary_condition_2d(x, float("-inf")) + else: + x_loader = x.make_loader() + + new_size = list(batch) + [h_out, w_out] + window_size = kernel_size[0] * kernel_size[1] + + if window_size > 25 or any(d != 1 for d in dilation): + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_max_pool2d_with_indices( + x, kernel_size, stride, padding, dilation, ceil_mode + ) + + def fn(idx, return_index): + *prefix, bh, bw = idx + maxval = None + maxindex = None + for ih, iw in itertools.product(range(kernel_size[0]), range(kernel_size[1])): + ih = bh * stride[0] + ih - padding[0] + iw = bw * stride[1] + iw - padding[1] + val = x_loader([*prefix, ih, iw]) + if return_index: + index = ops.index_expr(ih * w + iw, torch.int64) + if maxindex is None: + maxindex = index + else: + maxindex = ops.where(ops.gt(val, maxval), index, maxindex) + if maxval is None: + maxval = val + else: + maxval = ops.maximum(val, maxval) + if return_index: + return maxindex + else: + return maxval + + r1 = Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=functools.partial(fn, return_index=False), + ranges=new_size, + ) + r2 = Pointwise.create( + device=x.get_device(), + dtype=torch.int64, + inner_fn=functools.partial(fn, return_index=True), + ranges=new_size, + ) + # TODO(jansel): should we force these to be realized? + return r1, r2 + + +fallback_max_pool2d_with_indices_backward = fallback_handler( + aten.max_pool2d_with_indices_backward +) + + +@register_lowering(aten.max_pool2d_with_indices_backward, type_promotion_kind=None) +def max_pool2d_with_indices_backward( + grad_output, x, kernel_size, stride, padding, dilation, ceil_mode, indices +): + if padding == 0: + padding = [0, 0] + if dilation == 1: + dilation = [1, 1] + if not stride: + stride = kernel_size + + assert isinstance(x, TensorBox) + assert len(kernel_size) == 2 + assert len(stride) == 2 + assert len(padding) == 2 + assert len(dilation) == 2 + assert len(x.get_size()) in (3, 4) + + # we will read this many times, so make sure it is computed + grad_output.realize_hint() + try: + gO_stride = grad_output.get_stride() + except AttributeError: + # some classes don't have `get_stride` + # TODO will need a better way of determining if inputs are channels-last + gO_stride = None + if isinstance(x, TensorBox) and isinstance(x.data.data, Pointwise): # type: ignore[attr-defined] + data = x.data.data # type: ignore[attr-defined] + x_buffer = ir.ComputedBuffer( + name=None, + layout=ir.FlexibleLayout( + device=data.get_device(), + dtype=data.get_dtype(), + size=data.get_size(), + ), + data=data, + ) + x_buffer.decide_layout() + x_stride = x_buffer.get_stride() + else: + try: + x_stride = x.get_stride() + except AttributeError: + x_stride = None + + is_channels_last = (x_stride is not None and x_stride[1] == 1) or ( + gO_stride is not None and gO_stride[1] == 1 + ) + autotune = ( + config.coordinate_descent_tuning + or config.max_autotune + or config.max_autotune_pointwise + ) + if any(d != 1 for d in dilation) or (is_channels_last and not autotune): + # don't codegen channels-last when autotune is not enabled, it's very slow + return fallback_max_pool2d_with_indices_backward( + grad_output, x, kernel_size, stride, padding, dilation, ceil_mode, indices + ) + + indices.realize_hint() + + *batch, height, width = x.get_size() + *_, pooled_height, pooled_width = grad_output.get_size() + + indices_loader = indices.make_loader() + grad_loader = grad_output.make_loader() + new_size = list(x.get_size()) + + h_window_size = max( + [ + max(h // stride[0] - max(0, (h - kernel_size[0]) // stride[0]), 1) + for h in range(kernel_size[0] * 2) + ] + ) + w_window_size = max( + [ + max(w // stride[1] - max(0, (w - kernel_size[1]) // stride[1]), 1) + for w in range(kernel_size[1] * 2) + ] + ) + + window_size = h_window_size * w_window_size + + if window_size > 25: + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_max_pool2d_with_indices_backward( + grad_output, x, kernel_size, stride, padding, dilation, ceil_mode, indices + ) + + indices_size = indices.get_size() + + def fn(idx): + *prefix, h, w = idx + index_test = ops.index_expr(h * width + w, torch.int32) + h = h + padding[0] + w = w + padding[1] + phstart = ops.index_expr( + FloorDiv(h - kernel_size[0] + stride[0], stride[0]), torch.int32 + ) + pwstart = ops.index_expr( + FloorDiv(w - kernel_size[1] + stride[1], stride[1]), torch.int32 + ) + phend = ops.index_expr(FloorDiv(h, stride[0]) + 1, torch.int32) + pwend = ops.index_expr(FloorDiv(w, stride[1]) + 1, torch.int32) + + phstart = ops.maximum(phstart, ops.constant(0, torch.int32)) + pwstart = ops.maximum(pwstart, ops.constant(0, torch.int32)) + phend = ops.minimum(phend, ops.index_expr(pooled_height, torch.int32)) + pwend = ops.minimum(pwend, ops.index_expr(pooled_width, torch.int32)) + + gradient = None + for ph_ in range(h_window_size): + for pw_ in range(w_window_size): + ph = ops.add(phstart, ops.constant(ph_, torch.int32)) + pw = ops.add(pwstart, ops.constant(pw_, torch.int32)) + grad_index = [ + *prefix, + ops.indirect_indexing( + ops.minimum(ph, ops.sub(phend, ops.constant(1, torch.int32))), + indices_size[-2], + check=False, + ), + ops.indirect_indexing( + ops.minimum(pw, ops.sub(pwend, ops.constant(1, torch.int32))), + indices_size[-1], + check=False, + ), + ] + + index_actual = indices_loader(grad_index) + grad_part = grad_loader(grad_index) + check = ops.eq(index_actual, index_test) + + if gradient is None: + # don't need mask for 0, 0 + gradient = ops.where( + check, grad_part, ops.constant(0.0, torch.float32) + ) + else: + mask = ops.and_( + ops.and_( + ops.lt(ph, phend), + ops.lt(pw, pwend), + ), + check, + ) + gradient = ops.where(mask, ops.add(gradient, grad_part), gradient) + assert gradient is not None + return gradient + + return Pointwise.create( + device=grad_output.get_device(), + dtype=grad_output.get_dtype(), + inner_fn=fn, + ranges=new_size, + ) + + +def pad_adaptive_loader(x): + *_, h, w = x.get_size() + x_loader = x.make_loader() + + def load(prefix, increments, start_indices, end_indices): + ih, iw = increments + h_start_index, w_start_index = start_indices + h_end_index, w_end_index = end_indices + + mask = ops.and_( + ops.lt( + ops.index_expr(h_start_index + ih, torch.int64), + ops.index_expr(h_end_index, torch.int64), + ), + ops.lt( + ops.index_expr(w_start_index + iw, torch.int64), + ops.index_expr(w_end_index, torch.int64), + ), + ) + + return ops.masked( + mask, + lambda: x_loader([*prefix, h_start_index + ih, w_start_index + iw]), + 0.0, + ) + + return load + + +def _adaptive_pooling_idx_sum(kernel_maxes, start_index_fns, end_index_fns): + h_start_index_fn, w_start_index_fn = start_index_fns + h_end_index_fn, w_end_index_fn = end_index_fns + + def fn_sum(idx, loader): + *prefix, bh, bw = idx + + h_start_index = h_start_index_fn(bh) + h_end_index = h_end_index_fn(bh) + + w_start_index = w_start_index_fn(bw) + w_end_index = w_end_index_fn(bw) + + total = None + for ih, iw in itertools.product(range(kernel_maxes[0]), range(kernel_maxes[1])): + val = loader( + prefix, + [ih, iw], + [h_start_index, w_start_index], + [h_end_index, w_end_index], + ) + if total is None: + total = val + else: + total = ops.add(val, total) + return total + + return fn_sum + + +fallback_adaptive_avg_pool2d = fallback_handler(aten._adaptive_avg_pool2d) + + +@register_lowering(aten._adaptive_avg_pool2d) +def _adaptive_avg_pool2d(x, output_size): + assert isinstance(x, TensorBox) + assert len(output_size) == 2 + x.realize_hint() + + *batch, h_in, w_in = x.get_size() + + h_in = V.graph.sizevars.evaluate_static_shape(h_in) + w_in = V.graph.sizevars.evaluate_static_shape(w_in) + + h_out, w_out = output_size + + # no-op if the same input and output + if h_in == h_out and w_in == w_out: + return clone(x) + + if h_out == 0 or w_out == 0: + o_size = [*batch, h_out, w_out] + return empty(o_size, dtype=x.get_dtype(), device=x.get_device()) + if h_in % h_out == 0 and w_in % w_out == 0: + kernel_size = [h_in // h_out, w_in // w_out] + return avg_pool2d(x, kernel_size) + + h_kernel_max = ceildiv((h_in + h_out - 1), h_out) + w_kernel_max = ceildiv((w_in + w_out - 1), w_out) + + new_size = list(batch) + [h_out, w_out] + dtype = x.get_dtype() + + def start_index(index, out_dim, inp_dim): + return FloorDiv((index * inp_dim), out_dim) + + def end_index(index, out_dim, inp_dim): + return FloorDiv((index + 1) * inp_dim + out_dim - 1, out_dim) + + h_start_index = functools.partial(start_index, out_dim=h_out, inp_dim=h_in) + h_end_index = functools.partial(end_index, out_dim=h_out, inp_dim=h_in) + + w_start_index = functools.partial(start_index, out_dim=w_out, inp_dim=w_in) + w_end_index = functools.partial(end_index, out_dim=w_out, inp_dim=w_in) + + window_size = h_kernel_max * w_kernel_max + if window_size > 25: + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_adaptive_avg_pool2d(x, output_size) + + fn_sum = _adaptive_pooling_idx_sum( + [h_kernel_max, w_kernel_max], + [h_start_index, w_start_index], + [h_end_index, w_end_index], + ) + + ones_loader = pad_adaptive_loader(ones_like(x)) + + def fn(idx): + return ops.div(fn_sum(idx, pad_adaptive_loader(x)), fn_sum(idx, ones_loader)) + + rv = Pointwise.create( + device=x.get_device(), + dtype=dtype, + inner_fn=fn, + ranges=new_size, + ) + # TODO: should we force these to be realized? + return rv + + +@register_lowering(aten.upsample_nearest2d_backward.default) +def upsample_nearest2d_backward( + x, output_size=None, input_size=None, scales_h=None, scales_w=None +): + x.realize_hint() + + *batch, inp_h, inp_w = x.get_size() + inp_h = V.graph.sizevars.evaluate_static_shape(inp_h) + inp_w = V.graph.sizevars.evaluate_static_shape(inp_w) + + *batch, out_h, out_w = input_size + + if inp_h % out_h == 0 and inp_w % out_w == 0: + return avg_pool2d(x, [inp_h // out_h, inp_w // out_w], divisor_override=1) + + h_kernel_max = ceildiv(inp_h, out_h) + w_kernel_max = ceildiv(inp_w, out_w) + + def start_index(index, out_dim, inp_dim): + return CeilDiv(index * inp_dim, out_dim) + + def end_index(index, out_dim, inp_dim): + return start_index((index + 1), out_dim, inp_dim) + + h_start_index = functools.partial(start_index, out_dim=out_h, inp_dim=inp_h) + h_end_index = functools.partial(end_index, out_dim=out_h, inp_dim=inp_h) + + w_start_index = functools.partial(start_index, out_dim=out_w, inp_dim=inp_w) + w_end_index = functools.partial(end_index, out_dim=out_w, inp_dim=inp_w) + + fn_sum = _adaptive_pooling_idx_sum( + [h_kernel_max, w_kernel_max], + [h_start_index, w_start_index], + [h_end_index, w_end_index], + ) + + def fn(idx): + return fn_sum(idx, pad_adaptive_loader(x)) + + rv = Pointwise.create( + device=x.get_device(), + dtype=x.get_dtype(), + inner_fn=fn, + ranges=list(input_size), + ) + + return rv + + +fallback_avg_pool2d = fallback_handler(aten.avg_pool2d) + + +@register_lowering(aten.avg_pool2d, type_promotion_kind=None) +def avg_pool2d( + x, + kernel_size, + stride=(), + padding=0, + ceil_mode=False, + count_include_pad=True, + divisor_override=None, +): + if not stride: + stride = kernel_size + if not padding: + padding = [0, 0] + kernel_size = pad_listlike(kernel_size, 2) + stride = pad_listlike(stride, 2) + padding = pad_listlike(padding, 2) + + assert isinstance(x, TensorBox) + assert len(kernel_size) == 2 + assert len(stride) == 2 + assert len(padding) == 2 + assert len(x.get_size()) in (3, 4) + + x.realize_hint() + *batch, h, w = x.get_size() + + h_out, ceil_mode1 = pooling_size(h, 0, kernel_size, stride, padding, ceil_mode) + w_out, ceil_mode2 = pooling_size(w, 1, kernel_size, stride, padding, ceil_mode) + + if padding[0] or padding[1] or ceil_mode1 or ceil_mode2: + x_loader = constant_boundary_condition_2d(x, 0.0) + had_padding = True + else: + x_loader = x.make_loader() + had_padding = False + + new_size = list(batch) + [h_out, w_out] + dtype = x.get_dtype() + + window_size = kernel_size[0] * kernel_size[1] + if window_size > 25: + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_avg_pool2d( + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + ) + + def fn_sum(idx, loader): + *prefix, bh, bw = idx + total = None + for ih, iw in itertools.product(range(kernel_size[0]), range(kernel_size[1])): + ih = bh * stride[0] + ih - padding[0] + iw = bw * stride[1] + iw - padding[1] + val = loader([*prefix, ih, iw]) + if total is None: + total = val + else: + total = ops.add(val, total) + return total + + if not had_padding or divisor_override: + if divisor_override: + scale = 1 / divisor_override + else: + scale = 1.0 / (kernel_size[0] * kernel_size[1]) + + def fn(idx): + return ops.mul(fn_sum(idx, x_loader), ops.constant(scale, dtype)) + + else: + ones_loader = constant_boundary_condition_2d( + ones_like(x), 0.0, padding if count_include_pad else None + ) + + def fn(idx): + # TODO(jansel): optimize to do `int(x 25: + # Kernel size too big. Results in hard-to-optimize Triton code. Use fallback. + return fallback_avg_pool2d_backward( + grad_output, + x, + kernel_size, + stride, + padding, + ceil_mode, + count_include_pad, + divisor_override, + ) + + def compute_pool_size_without_padding(ph, pw): + """ + This computes the scaling factor that we will divide an element + by when `count_include_pad=False` + """ + stride_h = ops.constant(stride[0], torch.int32) + stride_w = ops.constant(stride[1], torch.int32) + pad_h = ops.constant(padding[0], torch.int32) + pad_w = ops.constant(padding[1], torch.int32) + kernel_h = ops.constant(kernel_size[0], torch.int32) + kernel_w = ops.constant(kernel_size[1], torch.int32) + hstart = ops.sub(ops.mul(ph, stride_h), pad_h) + wstart = ops.sub(ops.mul(pw, stride_w), pad_w) + hend = ops.minimum( + ops.add(hstart, kernel_h), + ops.add(ops.index_expr(height, torch.int32), pad_h), + ) + wend = ops.minimum( + ops.add(wstart, kernel_w), + ops.add(ops.index_expr(width, torch.int32), pad_w), + ) + hstart = ops.maximum(hstart, ops.constant(0, torch.int32)) + wstart = ops.maximum(wstart, ops.constant(0, torch.int32)) + hend = ops.minimum(hend, ops.index_expr(height, torch.int32)) + wend = ops.minimum(wend, ops.index_expr(width, torch.int32)) + divide_factor = ops.mul(ops.sub(hend, hstart), ops.sub(wend, wstart)) + return divide_factor + + def fn(idx): + *prefix, h, w = idx + h = h + padding[0] + w = w + padding[1] + phstart = ops.index_expr( + FloorDiv(h - kernel_size[0] + stride[0], stride[0]), torch.int32 + ) + pwstart = ops.index_expr( + FloorDiv(w - kernel_size[1] + stride[1], stride[1]), torch.int32 + ) + phend = ops.index_expr(FloorDiv(h, stride[0]) + 1, torch.int32) + pwend = ops.index_expr(FloorDiv(w, stride[1]) + 1, torch.int32) + + phstart = ops.maximum(phstart, ops.constant(0, torch.int32)) + pwstart = ops.maximum(pwstart, ops.constant(0, torch.int32)) + phend = ops.minimum(phend, ops.index_expr(pooled_height, torch.int32)) + pwend = ops.minimum(pwend, ops.index_expr(pooled_width, torch.int32)) + + gradient = None + for ph_ in range(h_window_size): + for pw_ in range(w_window_size): + ph = ops.add(phstart, ops.constant(ph_, torch.int32)) + pw = ops.add(pwstart, ops.constant(pw_, torch.int32)) + + if divisor_override is not None: + scale = divisor_override + elif count_include_pad or not had_padding: + scale = kernel_size[0] * kernel_size[1] + else: + scale = compute_pool_size_without_padding(ph, pw) + + part = ops.truediv( + grad_loader( + [ + *prefix, + ops.indirect_indexing( + ops.minimum( + ph, ops.sub(phend, ops.constant(1, torch.int32)) + ), + pooled_height, + check=False, + ), + ops.indirect_indexing( + ops.minimum( + pw, ops.sub(pwend, ops.constant(1, torch.int32)) + ), + pooled_width, + check=False, + ), + ] + ), + scale, + ) + + mask = ops.and_( + ops.lt(ph, phend), + ops.lt(pw, pwend), + ) + if gradient is None: + gradient = ops.where(mask, part, ops.constant(0.0, torch.float32)) + else: + gradient = ops.where(mask, ops.add(gradient, part), gradient) + assert gradient is not None + return gradient + + rv = Pointwise.create( + device=grad_output.get_device(), + dtype=dtype, + inner_fn=fn, + ranges=new_size, + ) + return rv + + +def _validate_reduction_axis(x, axis): + size = x.get_size() + if isinstance(axis, int): + axis = [axis] + elif not axis: + axis = range(len(size)) + if len(size) == 0: + assert tuple(axis) in [(), (0,), (-1,)], f"invalid axis: {axis}" + return [] + axis = list(axis) + for i in range(len(axis)): + if axis[i] < 0: + axis[i] += len(size) if len(size) else 1 + assert 0 <= axis[i] < len(size) or (len(size) == 0 and axis[i] == 0) + assert len(set(axis)) == len(axis), "reduction axis not unique" + return axis + + +def _make_reduction_inner(x, *, axis, keepdims, dtype, override_return_dtype): + if dtype is not None: + x = to_dtype(x, dtype) + size = x.get_size() + axis = set(_validate_reduction_axis(x, axis)) + + kept_sizes = [] + kept_idx = [] + reduced_sizes = [] + reduced_idx = [] + for i in range(len(size)): + if i in axis: + reduced_idx.append(i) + reduced_sizes.append(size[i]) + else: + kept_idx.append(i) + kept_sizes.append(size[i]) + + def loader(index, reduction_index): + assert len(reduction_index) == len(reduced_idx) + if keepdims: + assert len(index) == len(size) + assert all(index[i] == 0 for i in reduced_idx) + index = [index[i] for i in kept_idx] + assert len(index) == len(kept_idx) + new_index = [None] * (len(index) + len(reduction_index)) + for idx, var in itertools.chain( + zip(kept_idx, index), zip(reduced_idx, reduction_index) + ): + new_index[idx] = var + return inner_loader(new_index) + + if keepdims: + new_size = list(size) + for i in reduced_idx: + new_size[i] = sympy.Integer(1) + else: + new_size = kept_sizes + + inner_loader = x.make_loader() + return dict( + device=x.get_device(), + dst_dtype=override_return_dtype or x.get_dtype(), + src_dtype=x.get_dtype(), + inner_fn=loader, + ranges=new_size, + reduction_ranges=reduced_sizes, + ) + + +def make_reduction(reduction_type: str, override_return_dtype=None): + def inner(x, axis=None, keepdims=False, *, dtype=None): + kwargs = _make_reduction_inner( + x, + axis=axis, + keepdims=keepdims, + dtype=dtype, + override_return_dtype=override_return_dtype, + ) + result = Reduction.create(reduction_type=reduction_type, **kwargs) + if isinstance( + result.data.data, Reduction + ): # Only realize if reduction isn't unrolled + result.realize() + return result + + return inner + + +@register_lowering(aten.mean) +def mean(x, axis=None, keepdim=False, *, dtype=None): + if dtype is not None: + x = to_dtype(x, dtype) + size = x.get_size() + axis = _validate_reduction_axis(x, axis) + # compute in higher-precision until end of mean lowering + output_dtype = x.get_dtype() + if output_dtype in (torch.float16, torch.bfloat16): + x = to_dtype(x, torch.float) + sum_result = sum_(x, axis, keepdim) + denom = sympy_product(size[i] for i in axis) + denom = ir.IndexingConstant(denom, x.get_dtype(), x.get_device()) + denom = ExpandView.create(denom, list(sum_result.get_size())) + return to_dtype(div(sum_result, denom), output_dtype) + + +def var_mean_sum_(x, axis, correction, keepdim, return_mean): + if correction is None: + correction = 1 + + size = x.get_size() + axis = _validate_reduction_axis(x, axis) + x_mean = mean(x, axis, keepdim=True) + if return_mean: + x_mean.realize() + + diffs = square(sub(x, x_mean)) + sum_result = sum_(diffs, axis, keepdim) + + denom = sympy_product(size[i] for i in axis) + if correction: + denom = denom - correction + denom = ir.IndexingConstant(denom, x.get_dtype(), x.get_device()) + denom = ExpandView.create(denom, list(sum_result.get_size())) + x_var = div(sum_result, denom) + if not return_mean: + return x_var + + x_mean = x_mean if keepdim else squeeze(x_mean, axis) + return x_var, x_mean + + +def use_two_step_variance(x, axis, keepdim): + # Instead of unrolling welford, just unroll the simpler two-step var + axis = _validate_reduction_axis(x, axis) + kwargs = _make_reduction_inner( + x, axis=axis, keepdims=keepdim, dtype=None, override_return_dtype=None + ) + + ranges = kwargs["ranges"] + reduction_numel = sympy_product(kwargs["reduction_ranges"]) + return ( + isinstance(reduction_numel, sympy.Integer) + and int(reduction_numel) < config.unroll_reductions_threshold + and sympy_product(ranges) != 1 + ) + + +def var_mean_welford_(x, axis, *, correction, keepdim, return_mean): + if correction is None: + correction = 1 + + kwargs = _make_reduction_inner( + x, axis=axis, keepdims=keepdim, dtype=None, override_return_dtype=None + ) + loader = kwargs.pop("inner_fn") + kwargs.pop("dst_dtype") + kwargs.pop("src_dtype") + + mean, m2, _ = ir.WelfordReduction.create( + inner_fns=(loader,), + reduction_type="welford_reduce", + dtype=x.get_dtype(), + **kwargs, + ) + m2.realize() + + dtype = x.get_dtype() + size = x.get_size() + axis = _validate_reduction_axis(x, axis) + rnumel = sympy_product(size[i] for i in axis) + + def get_constant_or_index_expr(x, dtype): + if isinstance(x, sympy.Expr) and not x.is_constant(): + return ops.to_dtype(ops.index_expr(x, torch.int64), dtype) + return ops.constant(x, dtype) + + def scale_fn(data): + c = get_constant_or_index_expr(correction, dtype) + N = get_constant_or_index_expr(rnumel, dtype) + return data / (N - c) + + var = make_pointwise(scale_fn)(m2) + + if return_mean: + mean.realize() + return var, mean + return var + + +@register_lowering([aten.var, prims.var]) +def var_(x, axis=None, *, correction=None, keepdim=False): + if use_two_step_variance(x, axis=axis, keepdim=keepdim): + return var_mean_sum_( + x, axis=axis, correction=correction, keepdim=keepdim, return_mean=False + ) + + return var_mean_welford_( + x, axis=axis, correction=correction, keepdim=keepdim, return_mean=False + ) + + +@register_lowering(aten.var_mean) +def var_mean(x, axis=None, *, correction=None, keepdim=False): + if use_two_step_variance(x, axis=axis, keepdim=keepdim): + return var_mean_sum_( + x, axis=axis, correction=correction, keepdim=keepdim, return_mean=True + ) + + return var_mean_welford_( + x, axis=axis, correction=correction, keepdim=keepdim, return_mean=True + ) + + +def pow_recursive(x, y, dtype): + if y < 0: + return pow_recursive(ops.reciprocal(x), -y, dtype) + if y == 0: + return ops.constant(1, dtype) + if y == 1: + return x + + result = pow_recursive(x, y // 2, dtype) + result = ops.mul(result, result) + if (y % 2) == 1: + result = ops.mul(result, x) + return result + + +@make_pointwise +def pow_native(a, b): + return ops.pow(a, b) + + +fallback_pow = fallback_handler(aten.pow) + + +@register_lowering(aten.pow, broadcast=True) +def pow(a, b): + if isinstance(b, float) and b == int(b): + return pow(a, int(b)) + elif isinstance(b, float) and b == 0.5: + return sqrt(a) + elif isinstance(b, int) and b == 1: + return clone(a) + + # Type promotion ensures all tensor arguments have the same type + dtype = next(x.get_dtype() for x in (a, b) if isinstance(x, ir.TensorBox)) + is_integer_pow = is_integer_dtype(dtype) + + # Optimize away small fixed powers, or for integers avoid falling back to ATen + embed_exponent = isinstance(b, int) and ( + -32 < b < 32 or (is_integer_pow and b >= 0) + ) + if embed_exponent: + loader = a.make_loader() + + def fn(idx): + return pow_recursive(loader(idx), b, a.get_dtype()) + + return Pointwise.create( + device=a.get_device(), + dtype=a.get_dtype(), + inner_fn=fn, + ranges=a.get_size(), + ) + + if isinstance(a, Number): + if a == 1: + return full_like(b, 1) + if a == 2 and is_float_dtype(b.get_dtype()): + return exp2(b) + + if is_integer_pow: + # ops.pow doesn't work for integers + return fallback_pow(a, b) + + return pow_native(a, b) + + +def mutate_to(changed, val): + if isinstance(changed, TensorBox): + changed_data = changed.data + else: + changed_data = changed + if isinstance(val, TensorBox): + val = val.data + + if not isinstance(val, ir.StorageBox): + # introduce a copy to handle views + val = Pointwise.create( + device=changed.get_device(), + dtype=changed.get_dtype(), + inner_fn=val.make_loader(), + ranges=changed.get_size(), + ).data + assert isinstance(val, ir.StorageBox) + + if isinstance(changed_data, ir.StorageBox) and not ( + changed_data.is_input_buffer() or isinstance(changed_data.data, ir.NopKernel) + ): + # Fast path, just swing the data pointer + val.realize() + changed_data.data = val.data + return changed + + ir.MutationLayout.realize_into(val, changed_data) + return changed + + +@register_lowering(aten.fill_) +def fill_(x, fill_value): + return mutate_to(x, full_like(x, fill_value)) + + +@register_lowering(aten.copy_, type_promotion_kind=None) +def copy_(dst, src, non_blocking=False): + src = to_device(src, dst.get_device()) + src = to_dtype(src, dst.get_dtype()) + src = expand(src, dst.get_size()) + return mutate_to(dst, src) + + +@make_pointwise +def floordiv(a, b): + return ops.floordiv(a, b) + + +@make_pointwise +def truncdiv(a, b): + return ops.truncdiv(a, b) + + +@register_lowering(aten.div, broadcast=True) +def div_mode(a, b, rounding_mode=None): + both_integer = is_integer_type(a) and is_integer_type(b) + both_boolean = is_boolean_type(a) and is_boolean_type(b) + + # floordiv and truncdiv need special handling for integer tensors on Triton, + # see the discussion at https://github.com/openai/triton/issues/605 + if rounding_mode == "floor": + assert not both_boolean, "floordiv operands can not be boolean at the same time" + return floordiv(a, b) if both_integer else floor(div(a, b)) + if rounding_mode == "trunc": + assert not both_boolean, "truncdiv operands can not be boolean at the same time" + return truncdiv(a, b) if both_integer else trunc(div(a, b)) + return div(a, b) + + +@register_lowering([aten.mul], broadcast=True) +def mul(a, b): + both_bool = is_boolean_type(a) and is_boolean_type(b) + if both_bool: + return logical_and(a, b) + else: + fn = ops_wrapper(aten.mul.__name__) + return make_pointwise(fn)(a, b) + + +# NOTE: prims.div maps to a / b in C, so performs truncation division on +# integer inputs and true division for floating and complex inputs. +@register_lowering([prims.div], broadcast=True) +def div_prim(a, b): + is_integral = is_boolean_type(a) or is_integer_type(a) + + if is_integral: + return truncdiv(a, b) + + def fn(*args): + return ops.div(*args) + + return make_pointwise(fn)(a, b) + + +div = register_lowering( + [aten.true_divide, aten.div.Tensor], + broadcast=True, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, +)(div_prim) + + +@register_lowering([aten.fmod, prims.fmod], broadcast=True) +def fmod(a, b): + is_integral = is_boolean_type(a) or is_integer_type(a) + + if is_integral: + + def fn(a, b): + return ops.mod(a, b) + + else: + + def fn(a, b): + return ops.fmod(a, b) + + return make_pointwise(fn)(a, b) + + +@register_lowering(aten.rsqrt) +def rsqrt(x): + dtype = x.get_dtype() + if is_integer_dtype(dtype) or is_boolean_dtype(dtype): + x = to_dtype(x, torch.get_default_dtype()) + + def _rsqrt(x): + return ops.rsqrt(x) + + return make_pointwise(_rsqrt)(x) + + +@register_lowering([aten.sum, prims.sum]) +def sum_(x, axis=None, keepdims=False, *, dtype=None): + if ( + is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + ) and dtype is None: + dtype = torch.int64 + + fn = make_reduction("sum", override_return_dtype=dtype) + return fn(x, axis, keepdims, dtype=dtype) + + +@register_lowering(aten.prod) +def prod(x, axis=None, keepdims=False, *, dtype=None): + if ( + is_integer_dtype(x.get_dtype()) or is_boolean_dtype(x.get_dtype()) + ) and dtype is None: + dtype = torch.int64 + + fn = make_reduction("prod", override_return_dtype=dtype) + return fn(x, axis, keepdims, dtype=dtype) + + +@register_lowering(aten.any) +def reduce_any(x, dim=None, keepdim=False): + x = to_dtype(x, torch.bool) + return make_reduction("any")(x, axis=dim, keepdims=keepdim) + + +@register_lowering(aten.max) +def reduce_max(x, dim=None, keepdim=False): + if dim is not None: + return ( + reduce_amax(x, axis=dim, keepdims=keepdim), + reduce_argmax(x, axis=dim, keepdims=keepdim), + ) + + return reduce_amax(x, axis=None, keepdims=keepdim) + + +@register_lowering(aten.min) +def reduce_min(x, dim=None, keepdim=False): + if dim is not None: + return ( + reduce_amin(x, axis=dim, keepdims=keepdim), + reduce_argmin(x, axis=dim, keepdims=keepdim), + ) + + return reduce_amin(x, axis=None, keepdims=keepdim) + + +register_lowering(prims.xor_sum)(make_reduction("xor_sum")) +reduce_amax = register_lowering(aten.amax)(make_reduction("max")) +reduce_amin = register_lowering(aten.amin)(make_reduction("min")) +reduce_argmax = register_lowering(aten.argmax)( + make_reduction("argmax", override_return_dtype=torch.int64) +) +reduce_argmin = register_lowering(aten.argmin)( + make_reduction("argmin", override_return_dtype=torch.int64) +) + +add = register_pointwise( + aten.add, allow_alpha=True, override_fn_when_input_bool="logical_or" +) + + +def register_pointwise_numeric(op): + return register_pointwise( + op, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT + ) + + +def register_pointwise_numeric_ldf64(op): + return register_pointwise( + op, + type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, + use_libdevice_for_f64=True, + ) + + +exp = register_pointwise_numeric_ldf64(aten.exp) +exp2 = register_pointwise_numeric(aten.exp2) +expm1 = register_pointwise_numeric(aten.expm1) +relu = register_pointwise(aten.relu) +sigmoid = register_pointwise_numeric_ldf64(aten.sigmoid) +sqrt = register_pointwise_numeric_ldf64(aten.sqrt) +square = register_pointwise(aten.square) +sub = register_pointwise(aten.sub, allow_alpha=True) +register_pointwise_numeric_ldf64(aten.cos) +register_pointwise_numeric_ldf64(aten.sin) +register_pointwise(aten.abs) +bitwise_and = register_pointwise(aten.bitwise_and) +bitwise_left_shift = register_pointwise(aten.bitwise_left_shift) +bitwise_not = register_pointwise( + aten.bitwise_not, override_fn_when_input_bool="logical_not" +) +bitwise_or = register_pointwise(aten.bitwise_or) +bitwise_right_shift = register_pointwise(aten.bitwise_right_shift) +bitwise_xor = register_pointwise(aten.bitwise_xor) +register_pointwise_numeric(aten.lgamma) +erf = register_pointwise_numeric(aten.erf) +register_lowering( + aten.special_erf, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT +)(erf) + +register_pointwise_numeric(aten.log1p) +register_pointwise_numeric(aten.tan) +register_pointwise_numeric(aten.tanh) +register_pointwise_numeric_ldf64(aten.log) +logical_and = register_pointwise( + aten.logical_and, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +logical_not = register_pointwise( + aten.logical_not, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +logical_or = register_pointwise( + aten.logical_or, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +logical_xor = register_pointwise( + aten.logical_xor, + type_promotion_kind=None, + convert_input_to_bool=True, + override_return_dtype=torch.bool, +) +maximum = register_pointwise(aten.maximum) +minimum = register_pointwise(aten.minimum) +register_lowering(aten.clamp_min)(maximum) +register_lowering(aten.clamp_max)(minimum) +neg = register_pointwise(aten.neg) +reciprocal = register_pointwise_numeric(aten.reciprocal) +register_pointwise(aten.remainder) +sign = register_pointwise(aten.sign, override_fn_when_input_bool="identity") +register_pointwise(aten.ceil) +register_pointwise(aten.signbit, override_return_dtype=torch.bool) + +register_pointwise(aten.le, override_return_dtype=torch.bool) +register_pointwise(aten.lt, override_return_dtype=torch.bool) +register_pointwise(aten.ge, override_return_dtype=torch.bool) +gt = register_pointwise(aten.gt, override_return_dtype=torch.bool) +register_pointwise(aten.eq, override_return_dtype=torch.bool) +register_pointwise(aten.ne, override_return_dtype=torch.bool) + +register_pointwise_numeric(aten.cosh) +register_pointwise_numeric(aten.sinh) +register_pointwise_numeric(aten.acos) +register_pointwise_numeric(aten.acosh) +register_pointwise_numeric(aten.asin) +register_pointwise_numeric(aten.asinh) +register_pointwise_numeric(aten.atan2) +register_pointwise_numeric(aten.atan) +register_pointwise_numeric(aten.atanh) +register_pointwise_numeric(aten.copysign) +register_pointwise_numeric(aten.erfc) +register_pointwise_numeric(aten.erfinv) +register_pointwise_numeric(aten.hypot) +register_pointwise_numeric(aten.log10) +register_pointwise_numeric(aten.nextafter) + +register_foreach_pointwise(aten._foreach_add.List, add, allow_alpha=True) +register_foreach_pointwise(aten._foreach_add.Scalar, add, allow_alpha=True) +register_foreach_pointwise(aten._foreach_mul.List, mul) +register_foreach_pointwise(aten._foreach_mul.Scalar, mul) +register_foreach_pointwise(aten._foreach_sub.List, sub) +register_foreach_pointwise(aten._foreach_sub.Scalar, sub) +register_foreach_pointwise(aten._foreach_neg.default, neg) +register_foreach_pointwise(aten._foreach_pow.Scalar, pow) +register_foreach_pointwise(aten._foreach_pow.ScalarAndTensor, pow) +register_foreach_pointwise(aten._foreach_div.List, div) +register_foreach_pointwise(aten._foreach_div.Scalar, div) +register_foreach_pointwise(aten._foreach_sqrt, sqrt) +register_foreach_pointwise(aten._foreach_maximum.List, maximum) +register_foreach_pointwise(aten._foreach_maximum.Scalar, maximum) +register_foreach_pointwise(aten._foreach_reciprocal, reciprocal) +register_foreach_pointwise(aten._foreach_sign, sign) +register_foreach_pointwise(aten._foreach_copy, copy) + + +def register_inplace(aten_op, outplace_op): + @register_lowering(aten_op, type_promotion_kind=None) + def fn(*args, **kwargs): + result = outplace_op(*args, **kwargs) + result = to_dtype(result, args[0].get_dtype()) + return mutate_to(args[0], result) + + return fn + + +register_inplace(aten.add_, add) +register_inplace(aten.bitwise_and_, bitwise_and) +register_inplace(aten.bitwise_left_shift_, bitwise_left_shift) +register_inplace(aten.bitwise_not_, bitwise_not) +register_inplace(aten.bitwise_or_, bitwise_or) +register_inplace(aten.bitwise_right_shift_, bitwise_right_shift) +register_inplace(aten.bitwise_xor_, bitwise_xor) +register_inplace(aten.mul_, mul) +register_inplace(aten.div_.Tensor, div) +register_inplace(aten.div_.Tensor_mode, div_mode) +register_inplace(aten.logical_and_, logical_and) +register_inplace(aten.logical_not_, logical_not) +register_inplace(aten.logical_or_, logical_or) +register_inplace(aten.logical_xor_, logical_xor) +register_inplace(aten.sub_, sub) +register_inplace(aten.relu_, relu) +register_inplace(aten.sigmoid_, sigmoid) + + +register_lowering(aten.__and__)(bitwise_and) +register_lowering(aten.__lshift__)(bitwise_left_shift) +register_lowering(aten.__or__)(bitwise_or) +register_lowering(aten.__rshift__)(bitwise_right_shift) +register_lowering(aten.__xor__)(bitwise_xor) + +register_inplace(aten.__iand__, aten.__and__) +register_inplace(aten.__ilshift__, aten.__lshift__) +register_inplace(aten.__ior__, aten.__or__) +register_inplace(aten.__irshift__, aten.__rshift__) +register_inplace(aten.__ixor__, aten.__xor__) + + +@register_lowering(aten.sym_constrain_range) +def sym_constrain_range(a, min, max): + tracing_context = torch._guards.TracingContext.get() + assert tracing_context is not None + assert a in tracing_context.fake_mode.shape_env.var_to_range + return a + + +@register_lowering(aten.sym_size) +def sym_size(a, dim): + return a.get_size()[dim] + + +@register_lowering(aten.sym_stride) +def sym_stride(a, dim): + return a.get_stride()[dim] + + +@register_lowering(aten.sym_numel) +def sym_numel(a): + return a.get_numel() + + +for method, func in magic_methods.items(): + register_lowering(method_to_operator(method))(func) + + +@register_lowering(aten._foobar) +def foobar(self, *args, **kwargs): + raise NotImplementedError("Helpful for debugging") + + +@register_lowering(torch.ops._inductor_test.realize) +def _realize(x): + x.realize() + return clone(x) + + +try: + import torch.distributed._functional_collectives + + c10d_functional = torch.ops.c10d_functional + + @register_lowering(c10d_functional.wait_tensor) + def wait(input): + return TensorBox.create(ir.Wait.create(input)) + + @register_lowering(c10d_functional.all_reduce) + def allreduce(input, reduce_op, tag, ranks, group_size): + return ir.AllReduce.create(input, reduce_op, tag, ranks, group_size) + + @register_lowering(c10d_functional.all_gather_into_tensor) + def all_gather_into_tensor(shard, tag, ranks, group_size): + return TensorBox.create( + ir.AllGatherIntoTensor.create(shard, tag, ranks, group_size) + ) + + @register_lowering(c10d_functional.reduce_scatter_tensor) + def reduce_scatter_tensor(input, reduce_op, tag, ranks, group_size): + return TensorBox.create( + ir.ReduceScatterTensor.create(input, reduce_op, tag, ranks, group_size) + ) + + @register_lowering(c10d_functional.all_reduce_coalesced) + def all_reduce_coalesced(input, reduce_op, tag, ranks, group_size): + return ir.AllReduceCoalesced.create(input, reduce_op, tag, ranks, group_size) + + @register_lowering(c10d_functional.all_gather_into_tensor_coalesced) + def all_gather_into_tensor_coalesced(self, tag, ranks, group_size): + result = ir.AllGatherIntoTensorCoalesced.create(self, tag, ranks, group_size) + return list(map(TensorBox.create, result)) + + @register_lowering(c10d_functional.reduce_scatter_tensor_coalesced) + def reduce_scatter_tensor_coalesced(self, reduceOp, tag, ranks, group_size): + result = ir.ReduceScatterTensorCoalesced.create( + self, reduceOp, tag, ranks, group_size + ) + return list(map(TensorBox.create, result)) + +except ImportError: + log.info( + "Inductor support for distributed collectives depends on building torch.distributed" + ) + +# populate lowerings defined in kernel/* +from . import kernel + +import_submodule(kernel) + +from . import quantized_lowerings + +quantized_lowerings.register_quantized_ops() diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/metrics.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..f558ecf861437cf2797a0982e9c9cee0b128378a --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/metrics.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import List, Tuple, TYPE_CHECKING, Union + +# Prevent circular import +if TYPE_CHECKING: + from torch._inductor.scheduler import ( + BaseSchedulerNode, + ExternKernelSchedulerNode, + NopKernelSchedulerNode, + SchedulerNode, + ) + +# counter for tracking how many kernels have been generated +generated_kernel_count = 0 +generated_cpp_vec_kernel_count = 0 +num_bytes_accessed = 0 +nodes_num_elem: List[ + Tuple[ + Union[NopKernelSchedulerNode, SchedulerNode, ExternKernelSchedulerNode], + int, + ] +] = [] +node_runtimes: List[Tuple[BaseSchedulerNode, float]] = [] + +# counters for tracking fusions +ir_nodes_pre_fusion = 0 + +# counters for tracking to_dtype inserted +cpp_to_dtype_count = 0 + +# counters for tracking cpp_wrapper disabled +disable_cpp_wrapper = 0 + + +# reset all counters +def reset(): + global generated_kernel_count + global generated_cpp_vec_kernel_count + global num_bytes_accessed, nodes_num_elem + global ir_nodes_pre_fusion + global cpp_to_dtype_count + global disable_cpp_wrapper + + generated_kernel_count = 0 + generated_cpp_vec_kernel_count = 0 + num_bytes_accessed = 0 + nodes_num_elem.clear() + node_runtimes.clear() + ir_nodes_pre_fusion = 0 + cpp_to_dtype_count = 0 + disable_cpp_wrapper = 0 diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/optimize_indexing.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/optimize_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ce2610e9a04db57b7122558c3b569222b7e883 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/optimize_indexing.py @@ -0,0 +1,118 @@ +import math + +import sympy + +import torch +from torch.utils._sympy.value_ranges import ValueRanges +from .ir import LoopBody +from .utils import dominated_nodes + + +def val_expressable_in_32_bits(val): + if getattr(val, "is_Boolean", False): + return True + + if isinstance(val, sympy.Expr): + assert val.is_constant() + if val.is_Integer or val.is_Boolean: + val = int(val) + else: + val = float(val) + + # bound within mantissa + if isinstance(val, float): + return val <= (2**24) and val >= -(2**24) + + if isinstance(val, int): + iinfo = torch.iinfo(torch.int32) + return val <= iinfo.max and val >= iinfo.min + + raise Exception(f"Unexpected value {val}") + + +def range_expressable_in_32_bits(range): + return val_expressable_in_32_bits(range.lower) and val_expressable_in_32_bits( + range.upper + ) + + +def try_to_reduce_precision(node, bounds, indirect_vars, indices, replacement_vals): + # if a downstream use of a node explicitly converts to int32, or float16/float32/float64, + # then it's precision is set for that chain of uses, and we don't need to consider those + # dominated values + def skip_filter(node): + return node.target == "to_dtype" and node.args[2] in ( + torch.int32, + torch.float32, + torch.float64, + ) + + # TODO - there are dominated uses whose dtype does not depend on whether + # we reduce the precision here, e.g. add(int64, int64) one of the args can be reduced to + # int32 without changing the output precision of the node. this case hasn't shown up + for dominated in dominated_nodes([node], skip_filter): + if dominated.target in ["store", "output"]: + continue + + if "set_indirect" in dominated.target: + idx = int(dominated.target[len("set_indirect") :]) + indirect_var = indirect_vars[idx] + + # We check that we can compute all the indices it's involved in with int32 + for index, expr in indices.items(): + if indirect_var in expr.free_symbols: + index_val = replacement_vals[index] + + if math.isinf(index_val.lower) or math.isinf(index_val.upper): + return + + # all indices are integers, so make sure that we + # use the bounds of integers instead of floats. + # TODO - not sure if we should be doing int/float casts while tracing, + # might interfere with sympy. + + index_val_int = ValueRanges( + int(index_val.lower), int(index_val.upper) + ) + if not range_expressable_in_32_bits(index_val_int): + return + + if not range_expressable_in_32_bits(bounds[dominated]): + return + + args = list(node.args) + args[2] = torch.int32 + node.args = tuple(args) + + +def indexing_dtype_strength_reduction(loop_body: LoopBody): + """ + Performs Value Range Analysis on LoopBody's fx graph to reduce precision of + intermediaries from int64 to int32 + """ + bv = loop_body.bounds() + + int64_dtype_nodes = [ + node + for node in loop_body.get_nodes() + if ( + node.target == "to_dtype" + and node.args[2] == torch.int64 + and node not in bv.unbounded_vars + ) + ] + if not int64_dtype_nodes: + return + + bounds = bv.get_bounds() + + # TODO - if dominated node of one to_dtype is not expressible in int32, + # we should short circuit another to_dtype node if that node also dominates + for node in int64_dtype_nodes: + try_to_reduce_precision( + node, + bounds, + loop_body.indirect_vars, + loop_body.indexing_exprs, + bv.replacement_vals, + ) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/pattern_matcher.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/pattern_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..70822dd4aadd766af520f6b17407f5ccaef212a6 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/pattern_matcher.py @@ -0,0 +1,1169 @@ +import dataclasses +import functools +import inspect +import itertools +import logging +import os +import re +from collections import defaultdict +from typing import Any, Callable, Dict, List, Optional, Union + +import torch +import torch._guards +import torch.fx +import torch.utils._pytree as pytree +from torch._dynamo.utils import counters +from torch._prims_common import is_integer_dtype +from torch.fx import Node +from torch.fx.experimental.proxy_tensor import make_fx, maybe_disable_fake_tensor_mode +from torch.fx.immutable_collections import immutable_dict, immutable_list + +from .._functorch import config as functorch_config +from .._functorch.aot_autograd import aot_function, make_boxed_func +from .._functorch.partitioners import default_partition +from .._subclasses import FakeTensorMode +from ..fx import Transformer +from . import config +from .decomposition import select_decomp_table +from .lowering import fallback_node_due_to_unsupported_type + +log = logging.getLogger(__name__) +aten = torch.ops.aten +prims = torch.ops.prims + +Constant = Any +NodeOrConstant = Union[Constant, torch.fx.Node] + +# Sentinel indicating multiple quantities can be matched +MULTIPLE = object() + + +class Match: + """ + Represents a successfully matched pattern. + """ + + def __init__(self, pattern, args=None, kwargs=None): + super().__init__() + self.pattern = pattern + # The input nodes that must be passed in to the result + self.args = args or [] + self.kwargs = kwargs or {} + # The nodes matched in this expression + self.nodes = [] + # Mapping CallFunction to the node.target + self.targets = {} + self.ctx: MatchContext = None + + @property + def graph(self): + return self.ctx.graph + + def extend(self, other): + if self.kwargs: + for key in set(self.kwargs.keys()) & set(other.kwargs.keys()): + if self.kwargs[key] != other.kwargs[key]: + raise FailedMatch(f"kwarg mismatch: {key}") + self.args.extend(other.args) + self.nodes.extend(other.nodes) + self.kwargs.update(other.kwargs) + self.targets.update(other.targets) + + def bundle(self): + # Wrap args in an extra list + self.args = [tuple(self.args)] if self.args else [] + return self + + def __repr__(self): + return f"Match(..., {self.args}, {self.kwargs})" + + def erase_nodes(self, graph: torch.fx.Graph): + for n in reversed(self.nodes): + if not n._erased: + graph.erase_node(n) + + def output_nodes(self): + return [ + (self.ctx.pattern_to_node[p] if p is not None else None) + for p in self.ctx.outputs + ] + + def output_node(self): + return [p for p in self.output_nodes() if p][0] + + def replace_with_graph(self, replacement_graph, args): + ReplacementPatternEntry.replace_with_graph( + self, self.ctx.graph, replacement_graph, args + ) + + def replace_by_example(self, replacement_fn, args, trace_fn=None): + if trace_fn is None: + trace_fn = inference_graph + replacement = trace_fn( + replacement_fn, torch.fx.map_arg(args, lambda arg: arg.meta["val"]) + ) + ReplacementPatternEntry.replace_with_graph( + self, + self.ctx.graph, + replacement, + args, + ) + + +class FailedMatch(RuntimeError): + def __bool__(self): + return False + + +class MatchContext: + """ + State needed while running PatternExpr._match(). + """ + + def __init__( + self, + outputs: List["PatternExpr"], + pattern_to_node: Optional[Dict["PatternExpr", Node]] = None, + *, + graph: torch.fx.Graph, + ): + self.outputs = outputs + self.pattern_to_node = pattern_to_node + self.graph = graph + self.exclusive_node_set = [] + if self.pattern_to_node is None: + self.pattern_to_node = {} + + def match(self, pattern, node): + """wrapper to check reused nodes in patterns""" + if pattern in self.pattern_to_node: + if self.pattern_to_node[pattern] == node: + return Match(pattern) # already checked this node + else: + return FailedMatch("repeated pattern differs") + m = pattern._match(node, self) + assert pattern not in self.pattern_to_node + self.pattern_to_node[pattern] = node if m else None + m.ctx = self + return m + + def filter_multi_user_patterns(self): + return { + pattern: node + for pattern, node in self.pattern_to_node.items() + if pattern.has_multiple_users() and node is not None + } + + +class PatternExpr: + """ + Base class for types of patterns + """ + + def _match( + self, node: torch.fx.Node, ctx: MatchContext + ) -> Union[Match, FailedMatch]: + raise NotImplementedError() + + def match(self, node: torch.fx.Node) -> Union[Match, FailedMatch]: + try: + return MatchContext([self], graph=node.graph).match(self, node) + except FailedMatch as e: + return e + + def has_multiple_users(self) -> bool: + return False + + def __repr__(self): + return self.__class__.__name__ + "()" + + def find_anchor_nodes(self, ctx: MatchContext, searched): + if self in ctx.pattern_to_node: + yield ctx.pattern_to_node[self] + + +class Arg(PatternExpr): + """ + Capture an arg which will become an input to the handler. Args are + passed in depth first order. + """ + + def _match(self, node: NodeOrConstant, ctx: MatchContext): + return Match(self, args=[node]) # matches anything + + +class Ignored(PatternExpr): + """ + Match an arg, but don't pass it to handler + """ + + def _match(self, node: NodeOrConstant, ctx: MatchContext): + return Match(self) # matches anything + + def __repr__(self): + return "*" + + +class KeywordArg(PatternExpr): + """ + Capture a kwarg which will become an input to the handler. + """ + + def __init__(self, name): + super().__init__() + self.name = name + + def __repr__(self): + return f"KeywordArg({self.name!r})" + + def _match(self, node: NodeOrConstant, ctx: MatchContext): + return Match(self, kwargs={self.name: node}) # matches anything + + +class ExclusiveKeywordArg(PatternExpr): + """ + Capture a kwarg which will become an input to the handler. + """ + + def __init__(self, name): + super().__init__() + self.name = name + + def __repr__(self): + return f"ExclusiveKeywordArg({self.name!r})" + + def _match(self, node: NodeOrConstant, ctx: MatchContext): + if node in ctx.exclusive_node_set: + return FailedMatch("exclusive arg appears twice") + + ctx.exclusive_node_set.append(node) + return Match(self, kwargs={self.name: node}) # matches anything + + +class _TargetExpr(PatternExpr): + """ + Base class for filtering match by node.target + """ + + op = None + + def __init__(self, fns, users=1): + if not self.op: + raise NotImplementedError("Shouldn't directly use _BaseNodeMatch") + super().__init__() + fns = [fns] if callable(fns) or isinstance(fns, str) else list(fns) + for fn in list(fns): + if isinstance(fn, torch._ops.OpOverloadPacket): + fns.extend([getattr(fn, overload) for overload in fn.overloads()]) + + self.fns = fns + self.fns_set = set(fns) + self.users = users + + def fns_repr(self): + return ( + f"[{self.fns[0].__name__}, ...]" + if len(self.fns) > 1 + else self.fns[0].__name__ + ) + + def __repr__(self): + return f"{self.__class__.__name__}({self.fns_repr()})" + + def has_multiple_users(self) -> bool: + return self.users is MULTIPLE or self.users > 1 + + def find_anchor_nodes(self, ctx: MatchContext, searched): + raise NotImplementedError() + + def _match_fns(self, node: torch.fx.Node): + return ( + isinstance(node, torch.fx.Node) + and node.op == self.op + and node.target in self.fns_set + ) + + def _match_users(self, node: torch.fx.Node, ctx: MatchContext): + return ( + self in ctx.outputs + or self.users is MULTIPLE + or len(node.users) == self.users + ) + + +class _TargetArgsExpr(_TargetExpr): + """ + Base class for filtering match by node.{target,args,kwargs} + """ + + def __init__(self, fns, *args, _users=1, **kwargs): + super().__init__(fns, _users) + self.args = tuple(args) + self.kwargs = dict(kwargs) + if any( + isinstance(x, (dict, list, tuple)) + for x in itertools.chain(args, kwargs.values()) + ): + self.flatten = self.pytree_flatten + else: + self.flatten = self.simple_flatten + self.flat_args_kwargs = self.flatten(self.args, self.kwargs) + + @staticmethod + def simple_flatten(args, kwargs): + return (*args, *kwargs.values()), (len(args), *kwargs.keys()) + + @staticmethod + def pytree_flatten(args, kwargs): + def norm_spec(s: pytree.TreeSpec): + if s.type is None: + return s + mapping = {immutable_list: list, tuple: list, immutable_dict: dict} + return pytree.TreeSpec( + mapping.get(s.type, s.type), + s.context, + list(map(norm_spec, s.children_specs)), + ) + + flat, spec = pytree.tree_flatten([args, kwargs]) + spec = norm_spec(spec) + return flat, spec + + def __repr__(self): + args = [ + self.fns_repr(), + *map(repr, self.args), + *[f"{k}={v}" for k, v in self.kwargs.items()], + ] + return f"{self.__class__.__name__}({', '.join(args)})" + + def _match(self, node: torch.fx.Node, ctx: MatchContext): + if ( + not self._match_fns(node) + or len(node.args) != len(self.args) + or len(node.kwargs) != len(self.kwargs) + ): + return FailedMatch(f"function_mismatch: node={node}, pattern={self}") + + if not self._match_users(node, ctx): + return FailedMatch(f"multiple_users {node}") + + node_items, node_spec = self.flatten(node.args, node.kwargs) + self_items, self_spec = self.flat_args_kwargs + if node_spec != self_spec: + return FailedMatch(f"args_structure {node_spec} {self_spec}") + assert len(node_items) == len(self_items) + + m = Match(self) + for i, pattern, child_node in zip(itertools.count(), self_items, node_items): + if isinstance(pattern, PatternExpr): + child_match = ctx.match(pattern, child_node) + if not child_match: + return child_match + m.extend(child_match) + elif isinstance(child_node, torch.fx.Node) or child_node != pattern: + return FailedMatch(f"constant_args: {node} {child_node!r}!={pattern!r}") + m.nodes.append(node) + m.targets[self] = node.target + return m + + def find_anchor_nodes(self, ctx: MatchContext, searched): + """ + This is used when we are matching a pattern with multiple outputs. + There is a partial match (stored in ctx) and we want to walk + this pattern to find a connection to an already-matched node. + + Yields candidate nodes that `self._match` might like. + """ + if self in ctx.pattern_to_node: + yield ctx.pattern_to_node[self] + return + + for pattern in self.flat_args_kwargs[0]: + if isinstance(pattern, PatternExpr): + for other_node in pattern.find_anchor_nodes(ctx, searched): + if not isinstance(other_node, torch.fx.Node): + continue + for node in other_node.users: + if node not in searched: + if self._match_fns(node): + yield node + searched.add(node) + + +class CallFunction(_TargetArgsExpr): + """ + Matches a call_function node in the FX graphs: `fns[i](*args, **kwargs)` + """ + + op = "call_function" + + +class CallMethod(_TargetArgsExpr): + """ + Matches a call_method node in the FX graphs: `fns[i].method(*args, **kwargs)` + """ + + op = "call_method" + + +class _TargetExprVarArgs(_TargetExpr): + """ + Matches a call_function node with any arguments which are passed into the pattern + """ + + def _match(self, node: torch.fx.Node, ctx: MatchContext): + if not self._match_fns(node): + return FailedMatch("function_mismatch") + + if not self._match_users(node, ctx): + return FailedMatch("multiple_users") + + m = Match(self) + m.nodes.append(node) + m.targets[self] = node.target + m.args.extend(node.args) + m.kwargs.update(node.kwargs) + return m + + +class CallFunctionVarArgs(_TargetExprVarArgs): + op = "call_function" + + +class CallMethodVarArgs(_TargetExprVarArgs): + op = "call_method" + + +class ListOf(PatternExpr): + """ + Matches a repeated pattern + """ + + def __init__(self, pattern, partial=False): + super().__init__() + assert isinstance(pattern, PatternExpr) + self.pattern = pattern + self.partial = partial + + def __repr__(self): + return f"{self.__class__.__name__}({self.pattern})" + + def _match(self, node: List[torch.fx.Node], ctx: MatchContext): + if not isinstance(node, (list, tuple)) or len(node) == 0: + return FailedMatch("non_list") + m = Match(self) + # Propogating patterns with multiple users will ensure we don't revisit + # the same nodes + pattern_to_node = ctx.filter_multi_user_patterns() + matched = False + for i, child_node in enumerate(node): + child_ctx = MatchContext( + ctx.outputs, pattern_to_node, graph=child_node.graph + ) + child_match = child_ctx.match(self.pattern, child_node) + pattern_to_node = child_ctx.filter_multi_user_patterns() + if not child_match: + if not self.partial: + return FailedMatch(f"list[{i}]: {child_match}") + continue + matched = True + m.extend(child_match.bundle()) + if not matched: + return FailedMatch("list: no_match") + return m.bundle() + + +class MultiOutputPattern(PatternExpr): + def __init__(self, outputs): + super().__init__() + assert all(isinstance(x, (PatternExpr, type(None))) for x in outputs), outputs + self.outputs = outputs + + @property + def fns(self): + return self.outputs[0].fns + + def __repr__(self): + return f"{self.__class__.__name__}({self.outputs})" + + def _match(self, node: torch.fx.Node, ctx: MatchContext): + m = ctx.match(self.outputs[0], node) + if not m: + return m + + for pattern in self.outputs[1:]: + if pattern is None: + continue + child_match = self._match_from_anchors(pattern, ctx) + if not child_match: + return child_match + m.extend(child_match) + + return m + + def _match_from_anchors(self, pattern, ctx): + prior = dict(ctx.pattern_to_node) + m = FailedMatch("no anchor found") + for node in pattern.find_anchor_nodes(ctx, set()): + m = ctx.match(pattern, node) + if m: + return m + # revert any partial matches + ctx.pattern_to_node = dict(prior) + return m + + def match(self, node: torch.fx.Node) -> Union[Match, FailedMatch]: + try: + return MatchContext(self.outputs, graph=node.graph).match(self, node) + except FailedMatch as e: + return e + + +class RepeatedExpr(PatternExpr): + """ + Checks for a repeated pattern. Useful for repeated operations after a node such as `split` or `unbind` + """ + + def __init__(self, inner_pattern): + super().__init__() + assert isinstance(inner_pattern, PatternExpr) + self.inner_pattern = inner_pattern + + @property + def fns(self): + return self.inner_pattern.fns + + def _match(self, node: torch.fx.Node, ctx: MatchContext): + m = ctx.match(self.inner_pattern, node) + if not m: + return m + ctx.pattern_to_node.pop( + self.inner_pattern, + ) + # Check all anchor nodes match the pattern + for anchor_node in self.inner_pattern.find_anchor_nodes(ctx, set()): + anchor_m = MatchContext([self], graph=node.graph).match( + self.inner_pattern, anchor_node + ) + if not anchor_m: + return anchor_m + m.extend(anchor_m) + return m + + +@dataclasses.dataclass +class PatternEntry: + pattern: PatternExpr + extra_check: Callable[[Match], bool] + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node): + raise NotImplementedError() + + def register(self, pass_dicts, target=None, prepend=False): + if target is None: + for fn in self.pattern.fns: + self.register(pass_dicts, fn, prepend=prepend) + elif isinstance(pass_dicts, (dict, PatternMatcherPass)): + if prepend: + pass_dicts[target].insert(0, self) + else: + pass_dicts[target].append(self) + else: + for x in pass_dicts: + self.register(x, target, prepend=prepend) + + +@dataclasses.dataclass +class LoweringPatternEntry(PatternEntry): + handler: Any + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node): + handler = functools.wraps(self.handler)(functools.partial(self.handler, match)) + with graph.inserting_before(node): + replacement = graph.call_function(handler, tuple(match.args), match.kwargs) + replacement.meta.update(node.meta) + node.replace_all_uses_with(replacement) + assert match.nodes[-1] is node + match.erase_nodes(graph) + + +@dataclasses.dataclass +class GraphPatternEntry(PatternEntry): + """ + A pattern that runs a function on the FX graph + """ + + handler: Any + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node): + with graph.inserting_before(node): + self.handler(match, *match.args, **match.kwargs) + + +@dataclasses.dataclass +class ReplacementPatternEntry(PatternEntry): + normalize_args: Callable + + @staticmethod + def replace_with_graph( + match: Match, + graph: torch.fx.Graph, + replacement_graph: torch.fx.Graph, + args: List[Any], + ): + output_nodes = match.output_nodes() + first_node = output_nodes[0] + + class Replacer(torch.fx.Interpreter): + call_method = None + call_module = None + get_attr = None + + def run_node(self, node) -> Any: + if node.op in ("placeholder", "output"): + return super().run_node(node) + if node.op == "call_function": + target = node.target + args, kwargs = self.fetch_args_kwargs_from_env(node) + result = graph.call_function(target, args, kwargs) + if "val" in node.meta and "val" not in result.meta: + result.meta["val"] = node.meta["val"] + if isinstance(node.meta["val"], torch.Tensor): + assert "tensor_meta" in node.meta + result.meta["tensor_meta"] = node.meta["tensor_meta"] + return result + raise NotImplementedError(f"unhandled {node}") + + output_nodes = match.output_nodes() + + if len(output_nodes) == 1: + last_node = output_nodes[0] + else: + nodes = list(output_nodes[0].graph.nodes) + indices = [ + (nodes.index(n), n) + for n in output_nodes + if isinstance(n, torch.fx.Node) + ] + last_node = min(indices, key=lambda tup: tup[0])[1] + + def percolate_tags(node, recompute_tag): + for arg in node.all_input_nodes: + if hasattr(arg, "meta"): + arg.meta["recompute"] = recompute_tag + percolate_tags(arg, recompute_tag) + + with graph.inserting_before(last_node): + replacement = Replacer(replacement_graph).run(*args) + if isinstance(replacement, torch.fx.Node): + replacement = [replacement] + assert len(replacement) == len(output_nodes) + for old, new in zip(output_nodes, replacement): + if old is None: + assert new is None + elif new is None: + old.replace_all_uses_with(None) + else: + if "val" not in new.meta: + new.meta.update(old.meta) + + # Preserve the recompute tags in the replacement graph. We + # look at the recompute tags of the original output node to + # propagate the tag from the output all the way to the input + # args in the replacement graph. + # Note that this is best effort. Since patterns are from + # many to many, there is no easy way to correctly map the + # recomputable tags. It is possible in some scenarios that we + # incorrectly tag some nodes as recomputables. + if "recompute" in old.meta: + percolate_tags(new, old.meta["recompute"]) + + old.replace_all_uses_with(new) + + match.erase_nodes(graph) + + def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node): + self.replace_with_graph( + match, + graph, + match.replacement_graph, + self.normalize_args(*match.args, **match.kwargs), + ) + + +def _return_true(match): + return True + + +def register_replacement( + search_fn, + replace_fn, + example_inputs, + trace_fn, + pass_dict, + extra_check=_return_true, + scalar_workaround=(), + exclusive_arg_names=(), +): + """ + Create a replacement rule based on example functions that get traced + to create patterns. This supports both training and inference when + run on a joint foward+backward graph. + + Args: + search_fn: traced to give original pattern + replace_fn: traced to give replacement graph + example_inputs: example inputs for initial trace + trace_fn: inference_graph or training_graph + pass_dict: dict of passes to register to + extra_check: additional check to run on match(using real shapes) + """ + + def check_fn(match: Match): + """ + Often shapes get burned into the pattern, so our initial match ran with + `ignore_types=(int, ...)`. + + Recheck the match with the correct shapes. + """ + args = list( + torch.fx.map_arg( + [match.kwargs[name] for name in argnames], lambda n: n.meta["val"] + ) + ) + for i, grad in enumerate(requires_grad): + if isinstance(args[i], torch.Tensor): + if grad and is_integer_dtype(args[i].dtype): + return False + + with torch._dynamo.utils.detect_fake_mode(args): + args[i] = torch.empty_strided( + args[i].size(), + args[i].stride(), + dtype=args[i].dtype, + device=args[i].device, + requires_grad=grad, + ) + specific_graph = trace_fn(search_fn, args) + specific_pattern = fx_to_pattern( + specific_graph, argnames=argnames, exclusive_arg_names=exclusive_arg_names + ) + specific_pattern_match = specific_pattern.match(match.output_nodes()[0]) + if specific_pattern_match and extra_check(specific_pattern_match): + # trace the pattern using the shapes form the user program + match.replacement_graph = trace_fn(replace_fn, args) + return True + return False + + def normalize_args(**kwargs): + args = [] + for name in argnames: + args.append(kwargs.pop(name)) + for i in range(1, len(kwargs) + 1): + args.append(kwargs.pop(f"tangents_{i}")) + assert not kwargs, f"leftover kwargs: {kwargs!r}" + return args + + # TODO: Revisit the functionalize_rng_ops for lowmem dropout + with functorch_config.patch(functionalize_rng_ops=False): + argnames = [*inspect.signature(search_fn).parameters.keys()] + requires_grad = [ + isinstance(x, torch.Tensor) and x.requires_grad for x in example_inputs + ] + search_gm = trace_fn(search_fn, example_inputs) + pattern = fx_to_pattern( + search_gm, + ignore_types=(int, float, list, torch.device, torch.dtype), + argnames=argnames, + scalar_workaround=scalar_workaround, + exclusive_arg_names=exclusive_arg_names, + ) + assert repr(pattern) not in _seen_patterns + _seen_patterns.add(repr(pattern)) + pattern = ReplacementPatternEntry( + pattern=pattern, + extra_check=check_fn, + normalize_args=normalize_args, + ) + pattern.register(pass_dict) + + +def register_lowering_pattern( + pattern, extra_check=_return_true, *, pass_dict, prepend=False +): + """ + Register an aten to inductor IR replacement pattern. The decorated + function is saved and then called a lowering time allowing direct + pattern to inductor IR conversion. + """ + + def decorator(handler): + assert callable(handler) + LoweringPatternEntry( + pattern=pattern, extra_check=extra_check, handler=handler + ).register(pass_dict, prepend=prepend) + handler._inductor_lowering_function = True + return handler + + return decorator + + +def register_graph_pattern( + pattern, extra_check=_return_true, *, pass_dict, prepend=False +): + """ + Register a pattern that runs a function on the FX graph, allowing + custom transformation code. + """ + + def decorator(handler): + assert callable(handler) + GraphPatternEntry( + pattern=pattern, extra_check=extra_check, handler=handler + ).register(pass_dict, prepend=prepend) + return handler + + return decorator + + +def is_start_of_fx_graph(graph, node): + # first node in the graph + return node is next(iter(graph.nodes)) + + +# match: copy_, relu_, _set_grad_enabled, manual_seed, enter_functional_autocast, etc +_mutation_op_re = re.compile(r"_$|(\b|_)(set|enter|exit|seed)(\b|_)") + + +def is_mutation_op(node): + if node.op == "call_function": + if _mutation_op_re.search(node.target.__name__): + return True + elif node.op == "call_method": + if _mutation_op_re.search(node.target): + return True + return node.kwargs.get("out") is not None + + +def get_mutation_region_id(graph, node): + n = node + while "mutation_region_id" not in n.meta and not is_start_of_fx_graph(graph, n): + n = n.prev + mutation_region_id = n.meta.get("mutation_region_id", 0) + while n is not node: + n = n.next + if is_mutation_op(n): + mutation_region_id += 1 + n.meta["mutation_region_id"] = mutation_region_id + return mutation_region_id + + +def should_compute_mutation_region_ids(graph): + return "mutation_region_id" not in next(iter(graph.nodes)).meta + + +def compute_mutation_region_ids(graph): + mutation_region_id = 0 + for nd in graph.nodes: + if is_mutation_op(nd): + mutation_region_id += 1 + nd.meta["mutation_region_id"] = mutation_region_id + + +class PatternMatcherPass: + def __init__(self, prevent_match_across_mutations=False): + super().__init__() + self.patterns = defaultdict(list) + self.prevent_match_across_mutations = prevent_match_across_mutations + + def __getitem__(self, item): + return self.patterns[item] + + def apply(self, graph): + if not self.patterns: + return 0 + if isinstance(graph, torch.fx.GraphModule): + graph = graph.graph + if self.prevent_match_across_mutations: + if should_compute_mutation_region_ids(graph): + compute_mutation_region_ids(graph) + get_mutation_region_id_partial = functools.partial( + get_mutation_region_id, graph + ) + count = 0 + for node in reversed(graph.nodes): + if ( + node.op in ["call_function", "call_method"] + and node.target in self.patterns + ): + # conservatively not applying pattern for cpu input, + # since some of the patterns induce codegen and split nodes. + # Note: we will only skip cpu compute if disable_cpp_codegen=True + if fallback_node_due_to_unsupported_type(node, allow_cpu_inputs=False): + continue + + for entry in self.patterns[node.target]: + if node._erased: + break + m = entry.pattern.match(node) + # pattern match crosses mutation barrier - discard + if ( + self.prevent_match_across_mutations + and m + and len(set(map(get_mutation_region_id_partial, m.nodes))) != 1 + ): + continue + if os.environ.get("TORCHINDUCTOR_PATTERN_MATCH_DEBUG") == node.name: + log.warning("%s%s %s %s", node, node.args, m, entry.pattern) + if m and entry.extra_check(m): + count += 1 + entry.apply(m, graph, node) + counters["inductor"]["pattern_matcher_count"] += 1 + counters["inductor"]["pattern_matcher_nodes"] += len(m.nodes) + return count + + def clear(self): + self.patterns.clear() + + +def _not_implemented(*args, **kwargs): + raise NotImplementedError() + + +def fx_to_pattern( + gm, ignore_types=(), argnames=(), scalar_workaround=(), exclusive_arg_names=() +): + """ + Convert an FX graph into a PatternExpr. This is useful for simple + patterns that can only match single functions and fixed length lists. + """ + # scalar_workaround is a hack to capture dropout_p + # see https://github.com/pytorch/pytorch/issues/97894 + scalar_workaround = scalar_workaround or {} + inv_scalar_workaround = {v: k for k, v in scalar_workaround.items()} + assert len(inv_scalar_workaround) == len(scalar_workaround) + + def process_arg(x): + if isinstance(x, (float, int)) and x in inv_scalar_workaround: + return KeywordArg(inv_scalar_workaround[x]) + if type(x) in ignore_types: + return Ignored() + if isinstance(x, list) and all(isinstance(y, Ignored) for y in x) and x: + return Ignored() + return x + + argnum = itertools.count() + + class Converter(torch.fx.Interpreter): + call_method = _not_implemented + call_module = _not_implemented + get_attr = _not_implemented + + def placeholder(self, target, args, kwargs): + n = next(argnum) + if n < len(argnames): + name = argnames[n] + elif argnames: + assert target.startswith("tangent") + name = target + else: + target = re.sub(r"_\d+$", "", target) # de-mangle arg name + name = target + if name in exclusive_arg_names: + return ExclusiveKeywordArg(name) + else: + return KeywordArg(name) + + def call_function(self, target, args, kwargs): + args, kwargs = pytree.tree_map(process_arg, (args, kwargs)) + if list in ignore_types: + # Handle a burned in tensor size which are now [Ignored(), Ignored(), ...] + args = [process_arg(a) for a in args] + kwargs = {k: process_arg(a) for k, a in kwargs.items()} + return CallFunction(target, *args, **kwargs) + + def run_node(self, n): + rv = super().run_node(n) + if n.op == "output" and isinstance(rv, tuple): + assert len(rv) == len(n.args[0]) + for r, arg in zip(rv, n.args[0]): + r.users = len(arg.users) + else: + rv.users = len(n.users) + return rv + + pattern = Converter(gm).run() + if not isinstance(pattern, PatternExpr): + return MultiOutputPattern(pytree.tree_flatten(pattern)[0]) + return pattern + + +@torch.no_grad() +def inference_graph(fn, args): + """Build a normalized inference graph, for use with fx_to_pattern""" + gm = make_fx(fn, select_decomp_table())(*args) + gm.graph.eliminate_dead_code() + gm.recompile() + return gm + + +@torch.enable_grad() +def training_graph(fn, args): + """Build a normalized training graph, for use with fx_to_pattern""" + gm = None + + def record_joint_graph(joint_graph, inputs, **kwargs): + nonlocal gm + assert not gm + gm = clone_graph(joint_graph) + return default_partition(joint_graph, inputs, **kwargs) + + with torch._guards.tracing(None): + aot_function( + fn, + lambda g, i: make_boxed_func(g), + partition_fn=record_joint_graph, + decompositions=select_decomp_table(), + enable_log=False, + )(*args) + + from .fx_passes.joint_graph import pointless_view + + matcher_pass = PatternMatcherPass() + + pattern = CallFunction( + torch.ops.aten.view.default, KeywordArg("arg"), KeywordArg("size") + ) + GraphPatternEntry( + pattern=pattern, handler=pointless_view, extra_check=_return_true + ).register(matcher_pass.patterns) + matcher_pass.apply(gm.graph) + + # remove in/out specs + gm.graph._codegen = torch.fx.graph.CodeGen() + gm.graph.eliminate_dead_code() + gm.recompile() + return gm + + +def _args(n: torch.fx.Node): + args = list() + torch.fx.map_arg((n.args, n.kwargs), args.append) + return args + + +def stable_topological_sort(graph: torch.fx.Graph): + waiting = defaultdict(list) + ready = set() + cursor = None + + def check(node): + waiting_for = [x for x in _args(node) if x not in ready] + if waiting_for: + # revisit this node when next input is ready + waiting[waiting_for[0]].append(node) + else: + nonlocal cursor + cursor = node + ready.add(node) + for other in waiting.pop(node, ()): + cursor.append(other) + check(other) + + for n in list(graph.nodes): + check(n) + assert not waiting and len(ready) == len(graph.nodes) + + +def init_once_fakemode(fn): + """Wrapper around lazy init functions in fx_passes/""" + + @functools.lru_cache(None) + @functools.wraps(fn) + def lazy_init(): + counters_ref = counters["inductor"].copy() + + with torch._guards.tracing( + None + ), maybe_disable_fake_tensor_mode(), FakeTensorMode(): + result = fn() + + # clear view matches encountered during tracing + counters["inductor"] = counters_ref + + return result + + return lazy_init + + +def config_flag(name): + """Function for extra_check to put pass behind a flag""" + + def flag_check(match): + return getattr(config, name) + + return flag_check + + +def clone_graph(input_graph): + class CopyGraph(Transformer): + def run_node(self, old_node): + new_node = super().run_node(old_node) + if isinstance(new_node, torch.fx.Proxy): + new_node.node.meta.update(old_node.meta) + new_node.node.name = self.new_graph._graph_namespace.create_name( + old_node.name, None + ) + return new_node + + return CopyGraph(input_graph).transform() + + +_seen_patterns = set() + + +def get_arg_value(node, arg_number, kwarg_name=None): + return ( + node.args[arg_number] + if len(node.args) > arg_number + else node.kwargs.get(kwarg_name) + ) + + +def filter_nodes(nodes, fn): + fns = [fn] + if isinstance(fn, torch._ops.OpOverloadPacket): + fns.extend([getattr(fn, overload) for overload in fn.overloads()]) + + return [node for node in nodes if node.target in fns] + + +def same_layout(node1: torch.fx.Node, node2: torch.fx.Node): + """True if two nodes have the same size/strides""" + val1 = node1.meta.get("val") + val2 = node2.meta.get("val") + return ( + val1 is not None + and val2 is not None + and val1.size() == val2.size() + and val1.stride() == val2.stride() + ) + + +def remove_extra_clones(graph: torch.fx.Graph): + seen = set() + for node in reversed(graph.nodes): + if node.target is aten.clone.default: + src = node.args[0] + if ( + isinstance(src, torch.fx.Node) + and src.op == "call_function" + and isinstance(src.target, torch._ops.OpOverload) + and not src.target.is_view + and not any(u in seen for u in src.users) + and same_layout(src, node) + ): + node.replace_all_uses_with(src) + graph.erase_node(node) + seen.add(node) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/quantized_lowerings.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/quantized_lowerings.py new file mode 100644 index 0000000000000000000000000000000000000000..97818a6cb7e923e3aee5a0dcf929e6fd5ea17b85 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/quantized_lowerings.py @@ -0,0 +1,15 @@ +import torch + + +def register_quantized_ops(): + from . import lowering + + quantized = torch.ops.quantized + + lowering.add_needs_realized_inputs( + [ + quantized.max_pool2d, + ] + ) + + lowering.make_fallback(quantized.max_pool2d) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/scheduler.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..7c6679a4547539524c01753887f71913e1734708 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/scheduler.py @@ -0,0 +1,1749 @@ +import collections +import dataclasses +import functools +import itertools +import logging +import os +import pprint +import textwrap +from typing import Dict, List, Optional, Set + +import sympy + +import torch +from torch._dynamo.utils import dynamo_timed + +from . import config, dependencies, ir, metrics +from .codegen.common import get_scheduling_for_device +from .dependencies import StarDep, WeakDep +from .ir import ComputedBuffer +from .sizevars import SimplifyIndexing +from .utils import ( + cache_on_self, + cmp, + free_symbol_has, + get_device_tflops, + get_dtype_size, + get_gpu_dram_gbps, + has_triton, + sympy_product, +) +from .virtualized import V + + +log = logging.getLogger(__name__) + + +def pformat(obj): + if isinstance(obj, set): + # pformat has trouble with sets of sympy exprs + obj = sorted(obj, key=str) + result = pprint.pformat(obj, indent=4) + if "\n" in result: + return f"\n{textwrap.indent(result, ' '*4)}" + return result + + +class OutputNode: + def __init__(self, dep): + self.unmet_dependencies = {dep} + self.inverse_users = [] + + def is_reduction(self): + return False + + def get_alias_names(self): + return () + + def get_name(self): + return "OUTPUT" + + __repr__ = get_name + + +def fuse(node1: "BaseSchedulerNode", node2: "BaseSchedulerNode"): + if node1.is_foreach() or node2.is_foreach(): + return ForeachKernelSchedulerNode.fuse(node1, node2) + else: + return FusedSchedulerNode.fuse(node1, node2) + + +# TODO(xmfan): reuse an existing mapping for this if it exists, or formalize this into ir.py:ExternKernel +kernel_name_to_op = { + "extern_kernels.convolution": torch.ops.aten.convolution, + "extern_kernels.mm": torch.ops.aten.mm, + "extern_kernels.bmm": torch.ops.aten.bmm, + "extern_kernels.addmm": torch.ops.aten.addmm, +} + + +class BaseSchedulerNode: + def __init__(self, scheduler: "Scheduler", node: ir.Buffer): + self.scheduler: Scheduler = scheduler + self.node: ir.Buffer = node + self.users: Optional[List[NodeUser]] = None + self.inverse_users: List[BaseSchedulerNode] = [] + self.set_read_writes(node.get_read_writes()) + self.recursive_predecessors: Optional[Set[str]] = None + self.min_order: Optional[int] = None + self.max_order: Optional[int] = None + self.last_usage: Set[str] = None # buffers that won't be used after this kernel + self.written = False + + def __repr__(self): + return f"{type(self).__name__}(name={self.get_name()!r})" + + def debug_str(self) -> str: + """Longer form printout for trace logs""" + name = self.get_name() + lines = [ + f"{name}: {type(self).__name__}({type(self.node).__name__})", + f"{name}.writes = {pformat(self.read_writes.writes)}", + f"{name}.unmet_dependencies = {pformat(self.unmet_dependencies)}", + f"{name}.met_dependencies = {pformat(self.read_writes.reads - self.unmet_dependencies)}", + f"{name}.users = {self.users}", + ] + try: + lines += [ + self.debug_str_extra(), + ] + except Exception: + log.warning("Ignoring error in debug_str()", exc_info=True) + + return "\n".join(lines).rstrip() + + def debug_str_extra(self) -> str: + return "" + + def log_details(self): + log.info( + "%s: unmet_dependencies = %s, writes = %s", + self, + self.unmet_dependencies, + self.read_writes.writes, + ) + + def update_mutated_names(self, renames: Dict[str, str]): + self.set_read_writes(self.read_writes.rename(renames)) + + def add_mutation_dep(self, dep): + self.set_read_writes(self.read_writes.with_read(dep)) + + def set_users(self, users: List["NodeUser"]): + # deduplicate + result: Dict[int, NodeUser] = {} + for use in users: + if id(use.node) in result: + result[id(use.node)] = use.merge(result[id(use.node)]) + else: + result[id(use.node)] = use + self.users = list(result.values()) + + def set_last_usage( + self, future_used_buffers: Set[str], mutation_real_name: Dict[str, str] + ): + used_buffers = self.used_or_aliased_buffer_names() + used_buffers = {mutation_real_name.get(k, k) for k in used_buffers} + self.last_usage = used_buffers - future_used_buffers + + def get_aliases(self): + return self.node.get_alias_names() + + def get_mutations(self): + return self.node.get_mutation_names() + + def has_aliasing_or_mutation(self): + return bool(self.get_aliases() or self.get_mutations()) + + def set_read_writes(self, rw: dependencies.ReadWrites): + self.read_writes: dependencies.ReadWrites = rw + self.unmet_dependencies = self.read_writes.reads + self.prune_deps() + + def op_counts(self): + return self.read_writes.op_counts + + def used_buffer_names(self) -> Set[str]: + return { + dep.name + for dep in itertools.chain(self.read_writes.reads, self.read_writes.writes) + } + + def used_or_aliased_buffer_names(self) -> Set[str]: + used_names = set() + for dep in itertools.chain(self.read_writes.reads, self.read_writes.writes): + used_names.add(dep.name) + if V.graph.name_to_buffer.get(dep.name): + layout = V.graph.name_to_buffer[dep.name].get_layout() + # needed to avoid deallocating aliased buffer + # if there are still uses of aliases ahead + if isinstance(layout, ir.AliasedLayout): + used_names.add(layout.view.data.get_name()) + return used_names + + def prune_deps(self): + self.unmet_dependencies = { + dep + for dep in self.unmet_dependencies + if dep.name not in self.scheduler.available_buffer_names + } + + def prune_weak_deps(self): + # Prune weak dependencies on buffers that have been removed + def should_prune(dep): + return isinstance(dep, WeakDep) and dep.name in V.graph.removed_buffers + + to_remove = {dep for dep in self.read_writes.reads if should_prune(dep)} + self.set_read_writes(self.read_writes.remove_reads(to_remove)) + + def prune_redundant_deps(self, name_to_fused_node): + """ + Prunes stardeps intended for mutation ordering + on an upstream fused node if after fusion there is another dependency + on the fused upstream node, making the stardep redundant + + In essence this enforces an ordering on fusions. As fusions occur, prunable stardeps will + be incrementally removed, enabling other fusions, ensuring they are fused in order. + """ + name_to_dep_count = collections.Counter() + + for dep in self.unmet_dependencies: + if not isinstance(dep, WeakDep): + name_to_dep_count[name_to_fused_node[dep.name].get_name()] += 1 + + def should_prune(dep): + if isinstance(dep, WeakDep): + is_redundant = ( + name_to_dep_count[name_to_fused_node[dep.name].get_name()] > 0 + ) + # These can occur because fused nodes always gather deps from their snodes + # If B has a weakdep on A + # B gets fused with C, then any time BC is fused, the weakdep will reappear + is_self_dep = name_to_fused_node[dep.name] == self + return is_redundant or is_self_dep + else: + return False + + deps_to_prune = {dep for dep in self.unmet_dependencies if should_prune(dep)} + self.unmet_dependencies = self.unmet_dependencies - deps_to_prune + self.set_read_writes(self.read_writes.remove_reads(deps_to_prune)) + + def get_name(self) -> str: + return self.node.get_name() + + def get_first_name(self) -> str: + return self.get_name() + + def get_names(self) -> Set[str]: + return {self.get_name()} + + def get_nodes(self) -> List["BaseSchedulerNode"]: + return [self] + + def get_device(self): + return self.node.get_device() + + def is_reduction(self): + return False + + def is_template(self): + return False + + def is_extern(self): + return False + + def is_foreach(self): + return False + + def can_inplace(self, read_dep: dependencies.MemoryDep): + return False + + def has_side_effects(self): + return False + + def allocate(self): + if not self.node.should_allocate(): + return + + if isinstance(self, (SchedulerNode,)) and ( + self.node.get_alias_names() or self.node.get_mutation_names() + ): + V.graph.wrapper_code.codegen_allocation(self.node) + return + + if ( + ( + isinstance(self, (SchedulerNode,)) + # o what have i done. lets make this an api + or ( + isinstance(self, ExternKernelSchedulerNode) + and isinstance(self.node, (ir.AllReduce, ir.InPlaceHint)) + ) + ) + and config.inplace_buffers + and ( + not isinstance(V.kernel, torch._inductor.codegen.triton.TritonKernel) + or getattr(V.kernel, "mutations", None) is not None + ) + ): + from .codegen.wrapper import buffer_reuse_key + + ordered_reads = sorted(self.read_writes.reads, key=lambda x: x.name) + + for read in ordered_reads: + input_node: BaseSchedulerNode = self.scheduler.name_to_node.get( + read.name + ) + if input_node and V.graph.wrapper_code.can_reuse(input_node, self): + remaining_uses = [ + x + for x in input_node.users + if x.node.get_name() + not in self.scheduler.available_buffer_names + ] + if ( + len(remaining_uses) == 1 + and remaining_uses[0].can_inplace + and remaining_uses[0].node is self + and not isinstance( + input_node.node.get_layout(), + ( + ir.MultiOutputLayout, + ir.MutationLayout, + ir.AliasedLayout, + ), + ) + and buffer_reuse_key(input_node.node) + == buffer_reuse_key(self.node) + ): + V.graph.wrapper_code.codegen_inplace_reuse( + input_node.node, self.node + ) + # hacky check for if V.kernel is a real kernel or NullHandler + if hasattr(V.kernel, "args"): + # if there isn't a triton kernel, then we don't need to call triton-specific things. + # but TODO this might be a convenient place to signal to the Collective kernels to inplace + # (and, can we make "kernel" less generic of a name?) + V.kernel.args.make_inplace( + input_node.get_name(), self.get_name() + ) + # mutations not tracked in cpp kernels + if isinstance( + V.kernel, torch._inductor.codegen.triton.TritonKernel + ): + V.kernel.mutations.add(input_node.get_name()) + V.kernel.mutations.add(self.get_name()) + + # update last usage of reused node + self.last_usage.discard(input_node.get_name()) + + return + V.graph.wrapper_code.codegen_allocation(self.node) + + def can_free(self): + for use in self.users: + if isinstance(use.node, OutputNode): + return False + return True + + def codegen_originating_info(self, buffer, only_once=True): + if not config.comment_origin: + return + + if only_once and self.written: + return + origins = self.node.origins + out_lines = [] + + for o in origins: + if o.op == "output": + # These are boring and samey + continue + + out_lines.append("") + # TODO(voz): Should the pragma be constant somewhere? + out_lines.append("#pragma CMT ORIGIN:") + op_info_str = f"#pragma CMT {o.op} {o.target}" + if "seq_nr" in o.meta: + op_info_str = op_info_str + f" seq_nr:{o.meta['seq_nr']}" + out_lines.append(op_info_str) + if "stack_trace" in o.meta: + stack_trace = f"{o.meta['stack_trace']}" + stack_trace_last_line = stack_trace.split("|")[-1] + out_lines.append( + "#pragma CMT " + + stack_trace_last_line.replace("{", "{{") + .replace("}", "}}") + .replace("\n", "\\") + ) + out_lines.append("#pragma CMT END ORIGIN") + out_lines.append("") + + if len(out_lines) == 0: + return + + # TODO(voz): Ostensibly, we should not need this. But there are cases where C++ codegen does + # not use BracesBuffer, so we have no good indicator of a C++ buffer atm. + buffer.writelines(out_lines) + self.written = True + + def get_read_write_buffers_sizes(self) -> int: + if isinstance(self, NopKernelSchedulerNode): + return 0 + reads = {dep.name for dep in self.read_writes.reads} + writes = {dep.name for dep in self.read_writes.writes} + + def is_materialized(buf): + buf_uses = {user.node for user in self.scheduler.name_to_node[buf].users} + return len(buf_uses - set(self.snodes)) > 0 + + if isinstance(self, FusedSchedulerNode): + removed_buffers = {dep for dep in writes if not is_materialized(dep)} + writes = writes - removed_buffers + reads = reads - removed_buffers + node_bytes = 0 + for buf in reads | writes: + if buf in V.graph.name_to_buffer: + buf = V.graph.name_to_buffer[buf] + elif buf in V.graph.graph_inputs: + buf = V.graph.graph_inputs[buf] + else: + continue + + node_bytes += V.graph.sizevars.size_hint( + sympy_product(buf.get_size()) + ) * get_dtype_size(buf.get_dtype()) + return node_bytes + + def get_estimated_runtime(self) -> float: + layout = None + dtype = None + if not self.node: + assert self.snodes + layout = self.snodes[0].node.get_layout() + dtype = self.snodes[0].node.get_dtype() + else: + layout = self.node.get_layout() + dtype = self.node.get_dtype() + + if "cuda" != layout.device.type: + # default to no reordering based on runtime + return 0 + + try: + gpu_memory_bandwidth = get_gpu_dram_gbps() + gpu_flops = get_device_tflops(dtype) * 10**12 + except Exception: + return 0 + + if isinstance(self, ExternKernelSchedulerNode): + op = kernel_name_to_op.get(getattr(self.node, "kernel", ""), None) + + # if there is a resolved op, dry-run using fake mode and record flop count + if op is not None: + from torch._subclasses.fake_tensor import FakeTensorMode + from torch.utils.flop_counter import FlopCounterMode + + with FakeTensorMode(), FlopCounterMode( + display=False + ) as flop_counter_mode: + from .ir import ir_node_to_tensor + + fake_inputs = [ + ir_node_to_tensor(input) for input in self.node.inputs + ] + cls = self.node.__class__ + cls.process_kernel(op, *fake_inputs, **self.node.kwargs) + + # TODO(xmfan): find a better heuristic to model FLOPS/latency relationship + factor = 0.5 + counted_flops = flop_counter_mode.get_total_flops() + return factor * counted_flops / gpu_flops + + elif isinstance(self, FusedSchedulerNode) or isinstance( + self.node, ComputedBuffer + ): + return self.get_read_write_buffers_sizes() / gpu_memory_bandwidth + + # TODO(xmfan): add support for CollectiveKernel + + return 0 + + +class ExternKernelSchedulerNode(BaseSchedulerNode): + def debug_str_extra(self) -> str: + return f"{self.get_name()}.node.kernel = {getattr(self.node, 'kernel', None)}" + + def is_extern(self): + return True + + def has_side_effects(self): + return hasattr(self.node, "has_side_effects") and self.node.has_side_effects() + + def can_inplace(self, read_dep: dependencies.MemoryDep): + if self.get_aliases() or self.is_template(): + return False + + if read_dep.name not in self.scheduler.name_to_node: + # don't allow reuse of an 'input' buffer, we don't own it + # (would this have been fixed if I tracked mutations properly above?) + return False + + if not isinstance( + self.node, (torch._inductor.ir.AllReduce, torch._inductor.ir.InPlaceHint) + ): + # TODO make this a property of the IR + return False + + if len(self.read_writes.writes) == 1: + write_dep = next(iter(self.read_writes.writes)) + return read_dep.numbytes_hint() == write_dep.numbytes_hint() + + return False + + +class NopKernelSchedulerNode(BaseSchedulerNode): + pass + + +class SchedulerNode(BaseSchedulerNode): + def __init__(self, scheduler: "Scheduler", node: ir.ComputedBuffer, group_fn): + super().__init__(scheduler, node) + ( + self._sizes, + self._body, + ) = node.simplify_and_reorder() + + self.group = (node.get_device(), group_fn(self._sizes)) + + if self.is_template(): + self.set_read_writes(node.normalized_read_writes()) + else: + self.set_read_writes( + dependencies.extract_read_writes( + self._body, *self._sizes, normalize=True + ) + ) + + def debug_str_extra(self) -> str: + name = self.get_name() + lines = [ + f"{name}.group.device = {self.group[0]}", + f"{name}.group.iteration = {self.group[1]}", + f"{name}.sizes = {self._sizes}", + ] + if self.get_aliases(): + lines.append(f"{name}.aliases = {pformat(self.get_aliases())}") + if self.get_mutations(): + lines.append(f"{name}.mutations = {pformat(self.get_mutations())}") + if isinstance(self._body, ir.LoopBody): + lines.append(f"class {name}_loop_body:") + lines.append(textwrap.indent(self._body.debug_str(), " ")) + return "\n".join(lines) + + def get_ranges(self): + return self._sizes + + def is_reduction(self): + return bool(self.node.get_reduction_type()) + + def is_template(self): + return isinstance(self.node, ir.TemplateBuffer) + + def run(self, *index_vars): + self.mark_run() + self.codegen(index_vars) + + def mark_run(self): + self.allocate() + + def ranges_from_index_vars(self, index_vars): + sizes = self._sizes + assert sum(map(len, sizes)) == sum(map(len, index_vars)) + var_ranges = dict( + zip( + itertools.chain.from_iterable(index_vars), + itertools.chain.from_iterable(sizes), + ) + ) + return var_ranges + + def codegen(self, index_vars): + var_ranges = self.ranges_from_index_vars(index_vars) + try: + with V.set_ops_handler( + SimplifyIndexing(V.get_ops_handler(), var_ranges) + ), V.kernel.set_current_node(self): + self._body(*index_vars) + except Exception: + log.fatal("Error in codegen for %s", self.node) + raise + + def pointwise_read_writes(self): + """ + Get the memory dependencies in the non-reduction axis. + """ + sizes, reduction_sizes = self._sizes + + def fn(index): + return self._body(index, [sympy.Integer(0) for _ in reduction_sizes]) + + return dependencies.extract_read_writes(fn, sizes) + + def can_inplace(self, read_dep: dependencies.MemoryDep): + if self.get_aliases() or self.is_template(): + return False + if len(self.read_writes.writes) == 1 and isinstance( + read_dep, dependencies.MemoryDep + ): + write_dep = next(iter(self.read_writes.writes)) + return read_dep.index == write_dep.index and read_dep.size == write_dep.size + return False + + +class FusedSchedulerNode(BaseSchedulerNode): + """ + This is a "fake" scheduler node that represents a group of scheduler nodes + that are meant to be fused together. The way it does this is by maintaining + its unmet dependencies as the union of its constituent nodes. + """ + + @classmethod + def fuse(cls, node1: BaseSchedulerNode, node2: BaseSchedulerNode): + assert node1.scheduler is node2.scheduler + return cls(node1.scheduler, node1.get_nodes() + node2.get_nodes()) + + def __init__(self, scheduler: "Scheduler", snodes: List[SchedulerNode]): + # NB: No need to call super().__init__() because we don't need to re-use any of its logic. + self.snodes = snodes + self.scheduler = scheduler + self.node = None # type: ignore[assignment] + self.users = None + self.inverse_users = [] + self.group = max(snodes, key=lambda x: int(x.is_reduction())).group + self.recursive_predecessors = set.union( + *[x.recursive_predecessors for x in snodes] + ) + + self.set_read_writes( + dependencies.ReadWrites.merge_list([x.read_writes for x in snodes]) + ) + + self.unmet_dependencies = { + dep + for dep in set.union(*[x.unmet_dependencies for x in snodes]) + if dep.name not in self.get_names() + } - self.read_writes.writes + self.min_order = min([x.min_order for x in self.snodes]) + self.max_order = max([x.max_order for x in self.snodes]) + + @cache_on_self + def get_name(self) -> str: + return "_".join([x.get_name() for x in self.snodes]) + + def get_first_name(self) -> str: + return self.snodes[0].get_name() + + @cache_on_self + def get_names(self) -> Set[str]: + return set.union(*[x.get_names() for x in self.snodes]) + + def debug_str_extra(self) -> str: + lines = [ + f"{self.get_name()}.snodes[{i}] =\n{node.debug_str()}" + for i, node in enumerate(self.snodes) + ] + return textwrap.indent("\n".join(lines).rstrip(), " ") + + def set_last_usage( + self, future_used_buffers: Set[str], mutation_real_name: Dict[str, str] + ): + # Set self.last_usage using the global information + # This will be used for inter-kernel optimisations + super().set_last_usage(future_used_buffers, mutation_real_name) + # Set self.last_usage on the snodes + # This will be used for optimisations within the kernel + future_used_buffers = set() + for node in reversed(self.snodes): + node.set_last_usage(future_used_buffers, mutation_real_name) + future_used_buffers.update(node.last_usage) + + @cache_on_self + def used_buffer_names(self) -> Set[str]: + return set.union(*[x.used_buffer_names() for x in self.snodes]) + + @cache_on_self + def used_or_aliased_buffer_names(self) -> Set[str]: + return set.union(*[x.used_or_aliased_buffer_names() for x in self.snodes]) + + def get_nodes(self) -> List[BaseSchedulerNode]: + return self.snodes + + def __repr__(self): + return f"{type(self).__name__}(nodes={self.get_name()})" + + @cache_on_self + def is_reduction(self): + return any(x.is_reduction() for x in self.snodes) + + @cache_on_self + def is_template(self): + return any(x.is_template() for x in self.snodes) + + def is_foreach(self): + return False + + def get_device(self): + return self.group[0] + + @cache_on_self + def has_aliasing_or_mutation(self): + return any(x.has_aliasing_or_mutation() for x in self.snodes) + + @cache_on_self + def op_counts(self): + op_counts = collections.Counter() + for node in self.snodes: + op_counts.update(node.op_counts()) + return op_counts + + # None of these need to be implemented, as a FusedSchedulerNode is just an + # abstraction for scheduling purposes + def update_mutated_names(self, renames: Dict[str, str]): + raise NotImplementedError + + def add_mutation_dep(self, name): + raise NotImplementedError + + def set_users(self, users: List["NodeUser"]): + raise NotImplementedError + + def get_aliases(self): + raise NotImplementedError + + def get_mutations(self): + raise NotImplementedError + + def can_inplace(self, read_dep: dependencies.MemoryDep): + raise NotImplementedError + + def allocate(self): + raise NotImplementedError + + def can_free(self): + raise NotImplementedError + + +class ForeachKernelSchedulerNode(FusedSchedulerNode): + """Scheduler node which consists of a list of scheduler nodes that each operate on a + distinct tensor in a list of tensors.""" + + def get_consumer_subnode_for(self, producer): + if producer.get_name() in self.read_to_node: + return self.read_to_node[producer.get_name()] + + return None + + def get_producer_subnode_for(self, consumer): + for rd in consumer.read_writes.reads: + if rd.name in self.name_to_node: + return self.name_to_node[rd.name] + + return None + + @classmethod + def can_fuse(cls, producer, consumer): + if producer.is_foreach() and consumer.is_foreach(): + return len(producer.snodes) == len(consumer.snodes) and all( + producer.scheduler.can_fuse(l, r) + for l, r in zip(producer.snodes, consumer.snodes) + ) + elif consumer.is_foreach(): + consumer_subnode = consumer.get_consumer_subnode_for(producer) + if consumer_subnode is not None: + return consumer.scheduler.can_fuse(producer, consumer_subnode) + + return False + + elif producer.is_foreach(): + producer_subnode = producer.get_producer_subnode_for(consumer) + if producer_subnode is not None: + return producer.scheduler.can_fuse(producer_subnode, consumer) + + return False + + raise AssertionError( + "At least one node passed to ForeachKernelSchedulerNode.can_fuse should be a foreach node" + ) + + @classmethod + def fuse(cls, producer, consumer): + assert producer.is_foreach() or consumer.is_foreach() + prev_node_1 = None + prev_node_2 = None + if producer.is_foreach() and consumer.is_foreach(): + fused_nodes = [ + FusedSchedulerNode.fuse(l, r) + for l, r in zip(producer.snodes, consumer.snodes) + ] + elif producer.is_foreach(): + producer_subnode = producer.get_producer_subnode_for(consumer) + fused_nodes = [] + prev_node_1 = producer + prev_node_2 = None + for node in producer.snodes: + if node is producer_subnode: + new_node = FusedSchedulerNode.fuse(node, consumer) + prev_node_2 = new_node + fused_nodes.append(new_node) + else: + fused_nodes.append(node) + + elif consumer.is_foreach(): + consumer_subnode = consumer.get_consumer_subnode_for(producer) + fused_nodes = [] + prev_node_1 = consumer + prev_node_2 = None + + for node in consumer.snodes: + if node is consumer_subnode: + new_node = FusedSchedulerNode.fuse(producer, node) + prev_node_2 = new_node + fused_nodes.append(new_node) + else: + fused_nodes.append(node) + + return cls(producer.scheduler, fused_nodes, prev_node_1, prev_node_2) + + def __init__( + self, + scheduler: "Scheduler", + nodes: List[SchedulerNode], + prev_node_1=None, + prev_node_2=None, + ): + self.read_to_node = {} + self.name_to_node = {} + + if prev_node_1 is None or prev_node_2 is None: + super().__init__(scheduler, nodes) + + for node in nodes: + for read in node.read_writes.reads: + self.read_to_node[read.name] = node + + for name in node.get_names(): + self.name_to_node[name] = node + else: + self.scheduler = scheduler + self.snodes = nodes + + self.set_read_writes( + dependencies.ReadWrites.merge_list( + [prev_node_1.read_writes, prev_node_2.read_writes] + ) + ) + + self.unmet_dependencies = { + dep + for dep in set.union( + prev_node_1.unmet_dependencies, prev_node_2.unmet_dependencies + ) + if dep.name not in self.get_names() + } - self.read_writes.writes + + self.min_order = min([prev_node_1.min_order, prev_node_2.min_order]) + self.max_order = max([prev_node_1.max_order, prev_node_2.max_order]) + + foreach_node = prev_node_1 if prev_node_1.is_foreach() else prev_node_2 + other_node = prev_node_2 if prev_node_1.is_foreach() else prev_node_1 + + self.recursive_predecessors = foreach_node.recursive_predecessors + self.recursive_predecessors.update(other_node.recursive_predecessors) + + self.name_to_node = foreach_node.name_to_node + for name in other_node.get_names(): + self.name_to_node[name] = other_node + + self.group = (nodes[0].get_device(), 0) + + self.origins = set() + + def mark_run(self): + raise NotImplementedError + + def codegen(self): + self.node.get_store_function()(self.node.make_loader()()) + + def can_free(self): + return NotImplementedError + + def is_foreach(self): + return True + + def get_subkernel_nodes(self): + """Returns a list of nodes which comprise the foreach kernel, operating on corresponding elements of our input lists. + These nodes may be vertically fused.""" + return list(self.snodes) + + def get_nodes(self): + """Returns all nodes contained in this kernel, unpacking fused nodes into their constituent scheduler nodes.""" + return list(itertools.chain(*[x.get_nodes() for x in self.snodes])) + + def get_first_name(self): + return self.snodes[0].get_first_name() + + +def pick_loop_order(stride_lengths, sizes, priority_idx=()): + """ + A heuristic to decide loop iteration orders. This has not been well + tuned and may be something we should autotune. + """ + + @functools.cmp_to_key + def index_cmp(a, b): + if sizes[a] == 1 or sizes[b] == 1: + # 1-sizes don't matter, just move them to the end + return cmp(sizes[a] == 1, sizes[b] == 1) + + stride_len_a = [sl[a] for sl in stride_lengths] + stride_len_b = [sl[b] for sl in stride_lengths] + + # equivalent to + # np.logical_or(stride_lengths[:, b] == 0, stride_lengths[:, a] < stride_lengths[:, b]).all() + a_first = sum( + sl_b == 0 or sl_a < sl_b for sl_a, sl_b in zip(stride_len_a, stride_len_b) + ) + b_first = sum( + sl_a == 0 or sl_b < sl_a for sl_a, sl_b in zip(stride_len_a, stride_len_b) + ) + if a_first > b_first: + return -1 + if b_first > a_first: + return 1 + + # otherwise contiguous + return cmp(b, a) + + order = list(reversed(range(len(stride_lengths[0])))) + if len(priority_idx) > 0: + # if we have priority node, only use that node's order + stride_lengths = [stride_lengths[pi] for pi in priority_idx] + if config.pick_loop_orders: + order.sort(key=index_cmp) + return order + + +@dataclasses.dataclass +class NodeUser: + node: BaseSchedulerNode + can_inplace: bool = False + + # A weak user must be scheduled after a given node, but doesn't actually + # use the result + is_weak: bool = False + + def get_name(self): + return self.node.get_name() + + def merge(self, other: "NodeUser") -> "NodeUser": + assert self.node is other.node + return NodeUser( + self.node, + self.can_inplace and other.can_inplace, + self.is_weak and other.is_weak, + ) + + +class Scheduler: + @dynamo_timed + def __init__(self, nodes): + super().__init__() + self.backends = {} + self.fuse_cache = {} + + self.nodes = [] + self.available_buffer_names = { + *V.graph.graph_inputs.keys(), + *V.graph.constants.keys(), + } + + self.nodes = [self.create_scheduler_node(n) for n in nodes] + + # some new constants could have been created above + self.available_buffer_names.update(V.graph.constants.keys()) + for node in self.nodes: + node.prune_deps() + + self.name_to_node = {n.get_name(): n for n in self.nodes} + self.name_to_fused_node = None # set in fuse_nods() + + # we handle mutation by renaming modified versions of the same + # buffer in the dependency graph to prevent cycles. + # mutation_renames: tracks the current name for a given buffer + # (changed once per mutation) + self.mutation_real_name = {} + # mutation_real_name: maps back to the original name for codegen + self.mutation_renames = {} + + self.compute_dependencies() + self.topological_sort_schedule() + self.dead_node_elimination() + self.compute_predecessors() + + metrics.ir_nodes_pre_fusion += len(self.nodes) + V.debug.ir_pre_fusion(self.nodes) + self.num_orig_nodes = len(self.nodes) + self.name_to_fused_node = {n.get_name(): n for n in self.nodes} + self.create_foreach_nodes() + self.topological_sort_schedule() + self.fuse_nodes() + self.compute_last_usage() + V.debug.ir_post_fusion(self.nodes) + V.debug.graph_diagram(self.nodes) + self.debug_draw_graph() + + # used during codegen: + self.current_device = None + self.buffer_names_to_free = set() + self.buffer_names_no_longer_needed = set() + + # fx graph node to the position it appears in the graph + # for debug attribution + self.origin_to_index = {} + + log.info("Number of scheduler nodes after fusion %d", len(self.nodes)) + + def debug_draw_graph(self): + """Generate an image of the graph for debugging""" + if os.environ.get("INDUCTOR_WRITE_SCHEDULER_GRAPH", None) == "1": + from .debug import draw_buffers + + draw_buffers(self.nodes, print_graph=True) + + def debug_print_nodes(self, label): + if log.isEnabledFor(logging.INFO): + log.info("%s:", label) + for node in self.nodes: + node.log_details() + + def create_scheduler_node(self, node): + assert ( + node.origins is not None + ), "All nodes passed to scheduling must have an origin" + if node.is_no_op(): + return NopKernelSchedulerNode(self, node) + elif isinstance(node, (ir.ComputedBuffer, ir.TemplateBuffer)): + group_fn = self.get_backend(node.get_device()).group_fn + return SchedulerNode(self, node, group_fn) + elif isinstance(node, ir.ExternKernel): + return ExternKernelSchedulerNode(self, node) + else: + raise NotImplementedError(node) + + def create_foreach_nodes(self): + removed_node_names = set() + fe_nodes = [] + kept_node_names = self.name_to_fused_node.keys() + + for names in V.graph.lists.values(): + removed_node_names.update(names) + + names = [name for name in names if name in kept_node_names] + if not names: + # All nodes eliminated + continue + + snodes = [self.name_to_node[name] for name in names] + fe_node = ForeachKernelSchedulerNode(self, snodes) + + fe_nodes.append(fe_node) + + for name in names: + self.name_to_fused_node[name] = fe_node + + self.nodes = [ + node for node in self.nodes if node.get_name() not in removed_node_names + ] + fe_nodes + + def compute_dependencies(self): + """ + Create dependency edges between nodes, handling aliasing and + mutation properly. + """ + name_to_users = collections.defaultdict(list) + + # handle aliasing by using python aliasing in name_to_users + # if foo aliases bar then we will make name_to_users["foo"] point + # to the same python list as name_to_users["bar"] + for node1 in self.nodes: + node1_name = node1.get_name() + for node2_name in node1.get_aliases(): + if node1_name in name_to_users and node2_name in name_to_users: + # merge the two + list1 = name_to_users[node1_name] + list2 = name_to_users[node2_name] + combined = list1 + list2 + for key in name_to_users.keys(): + if name_to_users[key] is list1 or name_to_users[key] is list2: + name_to_users[key] = combined + elif node1_name in name_to_users: + name_to_users[node2_name] = name_to_users[node1_name] + else: + name_to_users[node1_name] = name_to_users[node2_name] + + def rename(n): + if n in self.mutation_renames: + return rename(self.mutation_renames[n]) + return n + + def dep_closure(node_name): + reachable_names = {node_name} + node = self.name_to_node[node_name] + write_dep = list(node.read_writes.writes)[0] + for read_dep in node.read_writes.reads: + if ( + read_dep.name in self.name_to_node + and isinstance(read_dep, dependencies.MemoryDep) + and isinstance(write_dep, dependencies.MemoryDep) + and read_dep.index == write_dep.index + and read_dep.size == write_dep.size + ): + reachable_names.update(dep_closure(read_dep.name)) + return reachable_names + + def add_user(used_by_name, user_node, can_inplace=False, is_weak=False): + name_to_users[rename(used_by_name)].append( + NodeUser(user_node, can_inplace, is_weak) + ) + + for node in self.nodes: + # a node will mutate either 0 or 1 buffers + for alt_name in node.get_mutations(): + alt_name = rename(alt_name) + # this node must run after the prior writer + add_user(alt_name, node) + node.add_mutation_dep(StarDep(alt_name)) + for other_node in name_to_users[alt_name]: + # this node must run after all prior readers + other_name = rename(other_node.get_name()) + known_dep_node_names = dep_closure(node.get_name()) + if other_name not in known_dep_node_names: + # If this node already directly or indirectly depends on other_node, + # we don't need to insert an extra dep. + node.add_mutation_dep(WeakDep(other_name)) + add_user(other_name, node, is_weak=True) + + # add normal non-mutation dependencies + for read in node.read_writes.reads: + is_weak = isinstance(read, WeakDep) + add_user(read.name, node, node.can_inplace(read), is_weak) + + node.update_mutated_names(self.mutation_renames) + + # update our renaming scheme for the next iteration + for alt_name in node.get_mutations(): + self.mutation_renames[rename(alt_name)] = node.get_name() + self.mutation_renames[alt_name] = node.get_name() + self.mutation_real_name[node.get_name()] = self.mutation_real_name.get( + alt_name, alt_name + ) + + # make sure outputs aren't dead-code-eliminated + for node_name in V.graph.get_output_names(): + add_user(node_name, OutputNode(StarDep(node_name))) + + # make sure input mutation isn't dead-code-eliminated + for name in self.mutation_renames: + if name in V.graph.graph_inputs: + add_user(name, OutputNode(StarDep(name))) + V.graph.mutated_inputs.add(name) + + inp_names = { + name: index for index, name in enumerate(V.graph.graph_inputs.keys()) + } + V.graph.mutated_input_idxs = [ + inp_names[name] for name in V.graph.mutated_inputs + ] + + # copy users information onto the nodes + for node in self.nodes: + node.set_users(name_to_users[node.get_name()]) + + # populate inverse_users + for node in self.nodes: + for user in node.users: + user.node.inverse_users.append(node) + + def dead_node_elimination(self): + """ + Remove any nodes without users + """ + again = True # repeat until a fixed point + while again: + updated_nodes = [] + for node in self.nodes: + + def can_eliminate_user(user: NodeUser): + return user.is_weak or user.get_name() in V.graph.removed_buffers + + can_eliminate = not node.has_side_effects() and all( + can_eliminate_user(u) for u in node.users + ) + + if not can_eliminate: + updated_nodes.append(node) + else: + # dead code + log.debug("removed dead node: %s", node.get_name()) + V.graph.removed_buffers.add(node.get_name()) + + again = len(self.nodes) > len(updated_nodes) + self.nodes = updated_nodes + + # Prune any WeakDeps no longer needed + for node in self.nodes: + node.prune_weak_deps() + + def topological_sort_schedule(self): + """ + Ensure self.nodes is in topologically sorted order + """ + seen = set() + name_to_node = dict() + result = [] + + def visit(n): + if n not in seen: + seen.add(n) + for dep in sorted(n.unmet_dependencies, key=lambda d: d.name): + visit(name_to_node[dep.name]) + result.append(n) + + for node in self.nodes: + for name in node.get_names(): + name_to_node[name] = node + for node in self.nodes: + visit(node) + self.nodes = result + + def compute_predecessors(self): + """ + Populate each node.recursive_predecessors + """ + # note self.nodes is topologically sorted + name_to_predecessors = {} + for node in self.nodes: + recursive_predecessors = set() + for dep in node.unmet_dependencies: + recursive_predecessors.add(dep.name) + recursive_predecessors |= name_to_predecessors[dep.name] + name_to_predecessors[node.get_name()] = recursive_predecessors + node.recursive_predecessors = recursive_predecessors + + for order, node in enumerate(self.nodes): + node.min_order = order + node.max_order = order + + def fuse_nodes(self): + """ + Mutates self.nodes to combine nodes into FusedSchedulerNodes. + """ + for _ in range(10): + old_len = len(self.nodes) + self.fuse_nodes_once() + if len(self.nodes) == old_len: + break + + def fuse_nodes_once(self): + """ + Mutates self.nodes to combine nodes into FusedSchedulerNodes. + + This relies on two key functions to control the logic: + - self.can_fuses(): checks if a fusion is legal + - self.score_fusion(): assigns priority to a given fusion + """ + fused_nodes = set(self.nodes) + for node1, node2 in self.get_possible_fusions(): + node1 = self.name_to_fused_node[node1.get_first_name()] + node2 = self.name_to_fused_node[node2.get_first_name()] + if self.can_fuse(node1, node2) and not self.will_fusion_create_cycle( + node1, node2 + ): + node3 = fuse(node1, node2) + fused_nodes.remove(node1) + fused_nodes.remove(node2) + fused_nodes.add(node3) + self.name_to_fused_node.update( + {n.get_name(): node3 for n in node3.get_nodes()} + ) + self.nodes = sorted(fused_nodes, key=lambda x: x.min_order) + self.topological_sort_schedule() + self.prune_redundant_deps() + + def prune_redundant_deps(self): + for node in self.nodes: + node.prune_redundant_deps(self.name_to_fused_node) + + def get_possible_fusions(self): + """ + Helper to find all legal fusion opportunities, sorted by self.score_fusion() + """ + possible_fusions = [] + seen = set() + + def check_all_pairs(nodes): + for node1_index, node1 in enumerate(nodes): + for node2 in nodes[node1_index + 1 :]: + key = (node1, node2) + if key in seen: + continue + seen.add(key) + + if self.can_fuse(node1, node2): + possible_fusions.append(key) + elif (node2.is_template() or node2.is_foreach()) and self.can_fuse( + node2, node1 + ): + # foreach fusions and epilogue fusions are order dependent + possible_fusions.append((node2, node1)) + + buffer_names_grouping = collections.defaultdict(list) + for node in self.nodes: + for buf in node.used_buffer_names(): + buffer_names_grouping[buf].append(node) + for node_grouping in buffer_names_grouping.values(): + check_all_pairs(node_grouping) + + if config.aggressive_fusion: + group_grouping = collections.defaultdict(list) + for node in self.nodes: + group = getattr(node, "group", None) + if group: + group_grouping[group].append(node) + for node_grouping in group_grouping.values(): + check_all_pairs(node_grouping) + + return sorted(possible_fusions, key=self.score_fusion_key, reverse=True) + + def will_fusion_create_cycle(self, node1, node2): + """Finds whether there's a path from src to dst caused indirectly by fusion""" + + def check(node): + if isinstance(node, FusedSchedulerNode) and node not in visited: + visited.add(node) + cond0 = bool(combined_names & node.recursive_predecessors) + + if cond0: + return cond0 + + names = node.get_names() + shortcut = names.issubset(combined_predecessors) + + if shortcut: + return cond0 + else: + return any( + check(self.name_to_fused_node[n]) + for n in node.recursive_predecessors - combined_predecessors + ) + return False + + visited = set() + combined_names = node1.get_names() | node2.get_names() + combined_predecessors = ( + node1.recursive_predecessors | node2.recursive_predecessors + ) - combined_names + return any(check(self.name_to_fused_node[n]) for n in combined_predecessors) + + def can_fusion_increase_peak_memory( + self, node1: BaseSchedulerNode, node2: BaseSchedulerNode + ): + """ + This function prevents fusion for nodes that can increase memory + footprint. This problem is more common in horizontal fusion, where nodes + that are far apart in the original order get fused, lengthening the live + intervals of tensors. This is very evident in models with activation + checkpointing, where the recomputed nodes from different checkpointed + regions get fused and significantly increase the memory footprint. + + The current attempt is a quick, possibly hacky, heuristic to prevent the + fusion of nodes that are far away in the original order. + + A better but difficult to implement heursitic would be to use live + intervals of the buffers, find region of peak pressure in the original + program and prevent fusion that crosses that peak region. We might need + special care or good approximation in this implementation, as fusion of + node changes live intervals, and re-computing live intervals and peak + memory after each fusion can introduce large compilation overhead. + """ + proximity_score = max( + abs(node1.min_order - node2.max_order), + abs(node2.min_order - node1.max_order), + ) + return proximity_score > 64 + + def can_fuse(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode): + """ + Determine if it is possible to combine node1 and node2 into a + single fused node. + """ + + if node1 is node2: + return False + if ( + isinstance(node1, (ExternKernelSchedulerNode, NopKernelSchedulerNode)) + and not node1.is_template() + ): + return False + if ( + isinstance(node2, (ExternKernelSchedulerNode, NopKernelSchedulerNode)) + and not node2.is_template() + ): + return False + + if node1.is_foreach() or node2.is_foreach(): + return ForeachKernelSchedulerNode.can_fuse(node1, node2) + + if node2.get_names() & node1.recursive_predecessors: + return False # node2 must go before node1 + + if node2.is_template(): + return False # only epilogues + if node1.is_template() and ( + node2.has_aliasing_or_mutation() + or node2.is_reduction() + or not config.epilogue_fusion + ): + return False + + device = node1.get_device() + if device != node2.get_device(): + return False # wrong device + + no_shared_data = self.score_fusion_memory(node1, node2) == 0 + if no_shared_data and ( + not config.aggressive_fusion or node1.is_reduction() or node2.is_reduction() + ): + return False # heuristic not needed for correctness + + if ( + not node1.is_foreach() + and not node2.is_foreach() + and len(node1.get_nodes()) + len(node2.get_nodes()) > config.max_fusion_size + ): + return False # heuristic not needed for correctness + + if node1.get_names() & node2.recursive_predecessors: + # node2 depends on node1 outputs + if not self.can_fuse_vertical(node1, node2): + return False + return self.get_backend(device).can_fuse_vertical(node1, node2) + else: # nodes don't depend on each other, but may have common reads + if self.can_fusion_increase_peak_memory(node1, node2): + return False + return self.get_backend(device).can_fuse_horizontal(node1, node2) + + def can_fuse_vertical(self, node1, node2): + """ + Check if it is legal to fuse a consumer (node2) into a producer (node1). + + We can fuse them if all the reads of node2 either match + corresponding writes in node1, or are written by nodes that can + be scheduled before the fusion of node1 and node2. + """ + node1_names = node1.get_names() + computed_deps = set() + + for rd in node2.unmet_dependencies: + for cd in node1.read_writes.writes: + # StarDep doesn't match MemoryDep, different indices don't match + # However, broadcasting sometimes strips dimensions, and if that's the case + # we still can match unmet dep + # if there's indirect indexing, don't match it + if ( + rd.name == cd.name + and type(rd) == type(cd) + and not free_symbol_has(rd.index, "tmp") + and not free_symbol_has(cd.index, "tmp") + and rd.index == cd.index + and len(rd.size) >= len(cd.size) + and rd.size[: len(cd.size)] == cd.size + ): + computed_deps.add(rd) + + remaining_deps = {dep.name for dep in node2.unmet_dependencies - computed_deps} + if remaining_deps & node1_names: + # MemoryDeps didn't match and read different locations of the same buffer. + # Examples here include: + # - MemoryDep("foo", x) != MemoryDep("foo", x + 1) + # - MemoryDep("foo", x) != StarDep("foo") + return False + for name in remaining_deps: + if node1_names & self.name_to_fused_node[name].recursive_predecessors: + return False + return True + + def score_fusion(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode): + """ + Assign a score (higher comes first) to the fusion of node1 + and node2. When different fusions conflict with each other, + this is the way we decide what order to run them in. + + Our current score is based on: + - Estimate of the saved memory operations + - Fusions closer together in original order + """ + memory_score = self.score_fusion_memory(node1, node2) + proximity_score = -max( + abs(node1.min_order - node2.max_order), + abs(node2.min_order - node1.max_order), + ) + return ( + node1.is_template() == config.epilogue_fusion_first and memory_score > 0, + node1.is_reduction() == node2.is_reduction() and memory_score > 0, + memory_score, + proximity_score, + ) + + def score_fusion_memory(self, node1, node2): + """ + The first term in our fusion score that estimates number of saved memory operations. + """ + common_memory_deps = (node1.read_writes.reads | node1.read_writes.writes) & ( + node2.read_writes.reads | node2.read_writes.writes + ) + return sum(dep.numbytes_hint() for dep in common_memory_deps) + + def score_fusion_key(self, nodes): + """ + Shim for list.sort(key=...) + """ + node1, node2 = nodes + return self.score_fusion(node1, node2) + + def compute_last_usage(self): + """ + Populate node.last_usage recursively (also for the nodes within a FusedSchedulerNode) + """ + + future_used_buffers = set() + for node_name in V.graph.get_output_names(): + future_used_buffers.add(node_name) + + for node in reversed(self.nodes): + node.set_last_usage(future_used_buffers, self.mutation_real_name) + future_used_buffers.update(node.last_usage) + + def free_buffers(self): + """Free any buffers that are no longer needed""" + for name in sorted( + self.buffer_names_to_free + - V.graph.removed_buffers + - V.graph.wrapper_code.freed + ): + if name in self.name_to_node: + node = self.name_to_node[name] + if node.can_free(): + V.graph.wrapper_code.codegen_free(node.node) + elif name in V.graph.graph_inputs: + storage = V.graph.graph_inputs[name].data + assert storage.is_input_buffer() + V.graph.wrapper_code.codegen_free(storage.data) + + self.buffer_names_to_free.clear() + + def remove_kernel_local_buffers(self): + """ + Any buffers that are both created and have a last use in the + same kernel can be removed. + """ + + names_to_remove = ( + V.kernel.store_buffer_names & self.buffer_names_no_longer_needed + ) + + def remove_filter(n): + return ( + n not in V.kernel.must_keep_buffers + and n not in V.kernel.args.input_buffers + and n not in self.mutation_renames + and n not in self.mutation_real_name + ) + + names_to_remove = list(filter(remove_filter, names_to_remove)) + + for name in names_to_remove: + if name in V.kernel.args.inplace_buffers: + buf = V.kernel.args.inplace_buffers[name] + if isinstance(buf, str) and buf.startswith("REMOVED"): + continue + remove = all(n in names_to_remove for n in buf.other_names) + if remove: + self.remove_inplace_buffer(name) + V.graph.inplaced_to_remove.add(name) + else: + self.remove_buffer(name) + + def remove_buffer(self, name): + # Assign a special value instead of deleting the entry + # because we still rely on output_buffers's length to + # generate unique arg name. + log.debug("remove_buffer(%r)", name) + V.kernel.args.output_buffers[name] = "REMOVED" + V.graph.removed_buffers.add(name) + + def remove_inplace_buffer(self, name): + log.debug("removing_inplace_buffer(%r)", name) + inner_name = V.kernel.args.inplace_buffers[name].inner_name + V.kernel.args.inplace_buffers[name] = inner_name.replace( + "in_out_ptr", "REMOVED" + ) + V.graph.removed_buffers.add(name) + + def flush(self): + for backend in self.backends.values(): + backend.flush() + self.free_buffers() + + def codegen_extern_call(self, scheduler_node: ExternKernelSchedulerNode): + assert isinstance(scheduler_node, ExternKernelSchedulerNode) + scheduler_node.allocate() + node = scheduler_node.node + node.codegen(V.graph.wrapper_code) + self.free_buffers() + + def create_backend(self, device: torch.device): + assert ( + device.type != "cuda" or device.index is not None + ), f"{device} should have been normalized in lowering" + V.graph.device_types.add(device.type) + V.graph.add_device_idx(device.index) + + device_scheduling = get_scheduling_for_device(device.type) + if device_scheduling is None: + raise RuntimeError(f"Unsupported device type: {device.type}") + + if device.type == "cuda" and not has_triton(): + device_props = torch.cuda.get_device_properties(device) + if device_props.major < 7: + raise RuntimeError( + f"Found {device_props.name} which is too old to be supported by the triton GPU compiler, which is used as the backend. Triton only supports devices of CUDA Capability >= 7.0, but your device is of CUDA capability {device_props.major}.{device_props.minor}" # noqa: B950 + ) + else: + raise RuntimeError( + "Cannot find a working triton installation. More information on installing Triton can be found at https://github.com/openai/triton" # noqa: B950 + ) + + return device_scheduling(self) + + def get_backend(self, device: torch.device): + if device not in self.backends: + self.backends[device] = self.create_backend(device) + return self.backends[device] + + def enter_context(self, node): + def get_order(n): + if n not in self.origin_to_index: + self.origin_to_index.update({n: i for i, n in enumerate(n.graph.nodes)}) + return self.origin_to_index[n] + + origins = [(get_order(e), e) for n in node.get_nodes() for e in n.node.origins] + if origins: + _, last = max(origins) + V.graph.wrapper_code.enter_context(last) + + @dynamo_timed + def codegen(self): + for node in self.nodes: + self.enter_context(node) + self.buffer_names_no_longer_needed.update(node.last_usage) + + if not isinstance(node, NopKernelSchedulerNode): + device = node.get_device() + if ( + device != self.current_device + or node.is_extern() + or node.is_template() + ): + self.flush() + if device != self.current_device: + if device.type == "cuda": + if self.current_device and self.current_device.type == "cuda": + V.graph.wrapper_code.codegen_device_guard_exit() + assert device.index is not None, "device should have an index" + V.graph.wrapper_code.codegen_device_guard_enter(device.index) + elif self.current_device and self.current_device.type == "cuda": + V.graph.wrapper_code.codegen_device_guard_exit() + self.current_device = device + + self.buffer_names_to_free.update(node.last_usage) + + if node.is_template(): + node, *epilogue = node.get_nodes() + self.get_backend(device).codegen_template(node, epilogue) + elif node.is_extern(): + self.codegen_extern_call(node) + elif node.is_foreach(): + self.get_backend(device).codegen_foreach(node) + elif isinstance(node, (FusedSchedulerNode, SchedulerNode)): + self.get_backend(device).codegen_nodes(node.get_nodes()) + else: + assert isinstance(node, NopKernelSchedulerNode) + node.allocate() + + if config.triton.debug_sync_kernel: + self.get_backend(device).codegen_sync() + + self.available_buffer_names.update(node.get_names()) + + self.flush() + + +class BaseScheduling: + def can_fuse_vertical(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode): + """ + Check whether node1 and node2 can be vertically fused or not. + """ + raise NotImplementedError() + + def can_fuse_horizontal(self, node1: BaseSchedulerNode, node2: BaseSchedulerNode): + """ + Check whether node1 and node2 can be horizontally fused or not. + """ + raise NotImplementedError() + + def group_fn(self, sizes): + """ + Process the iteration sizes in case a transformation needs to be applied. + """ + raise NotImplementedError() + + def codegen_template( + self, template_node: BaseSchedulerNode, epilogue_nodes: List[BaseSchedulerNode] + ): + """ + Given a template node, generate a kernel. + + This function is only available for triton now. If the third-party backend behaves as a sub-class + of TritonScheduling, it can override it or reuse it. + """ + raise NotImplementedError() + + def codegen_nodes(self, nodes: List[BaseSchedulerNode]): + """ + Generate a kernel given a list of pre-fused nodes. + """ + raise NotImplementedError() + + def codegen_sync(self): + """ + Generate synchronization code for the kernel. This method depends on the hardware characteristics. + """ + raise NotImplementedError() + + def flush(self): + """ + Flush the generated kernel and python wrapper code to the source code file. + """ + raise NotImplementedError() diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/select_algorithm.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/select_algorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..7ff74929391642a0e34694a159147d8adc1f8850 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/select_algorithm.py @@ -0,0 +1,974 @@ +import builtins +import functools +import inspect +import itertools +import logging +import sys +import textwrap +import time +from io import StringIO + +from typing import Any, Dict, List, Type, Union +from unittest.mock import patch + +import sympy + +import torch +from torch._dynamo.testing import rand_strided +from torch._dynamo.utils import counters, identity + +from . import config, ir +from .autotune_process import BenchmarkRequest, TensorMeta +from .codecache import code_hash, PersistentCache, PyCodeCache + +from .codegen.common import IndentedBuffer +from .codegen.triton import texpr, TritonKernel, TritonPrinter, TritonScheduling + +from .codegen.triton_utils import config_of, signature_to_meta + +from .utils import do_bench, sympy_dot, sympy_product, unique +from .virtualized import V + +log = logging.getLogger(__name__) + +# correctness checks struggle with fp16/tf32 +VERIFY: Dict[str, Any] = dict() +PRINT_AUTOTUNE = True +DEBUG = False + + +class KernelNamespace: + pass + + +# these objects are imported from the generated wrapper code +extern_kernels = KernelNamespace() + + +class PartialRender: + """ + Some parts of a template need to be generated at the end, but + inserted into the template at the start. This allows doing a bunch + of replacements after the initial render. + """ + + def __init__(self, code, replacement_hooks): + super().__init__() + self.code = code + self.replacement_hooks = replacement_hooks + + def finalize(self): + code = self.code + assert code is not None, "can only be called once" + self.code = None + for key, fn in self.replacement_hooks.items(): + code = code.replace(key, fn()) + return code + + +class TritonTemplateKernel(TritonKernel): + def __init__( + self, + kernel_name, + input_nodes, + output_node, + defines, + num_stages, + num_warps, + grid_fn, + meta, + call_sizes, + use_jit=True, + prefix_args=0, + suffix_args=0, + epilogue_fn=identity, + *, + index_dtype, + ): + super().__init__( + sympy_product(output_node.get_size()), + sympy.Integer(1), + index_dtype=index_dtype, + ) + self.input_nodes = input_nodes + self.output_node = output_node + self.named_input_nodes = {} + self.defines = defines + self.kernel_name = kernel_name + self.template_mask = None + self.use_jit = use_jit + self.num_stages = num_stages + self.num_warps = num_warps + self.grid_fn = grid_fn + self.meta = meta + self.call_sizes = call_sizes + # for templates with fixed epilogues + self.prefix_args = prefix_args + self.suffix_args = suffix_args + self.epilogue_fn = epilogue_fn + self.render_hooks = dict() + + def jit_line(self): + if self.use_jit: + return "@triton.jit" + + argdefs, _, signature = self.args.python_argdefs() + triton_meta = { + "signature": signature_to_meta(signature, size_dtype=self.index_dtype), + "device": V.graph.scheduler.current_device.index, + "device_type": V.graph.scheduler.current_device.type, + "constants": {}, + } + triton_meta["configs"] = [config_of(signature)] + return ( + f"@template(num_stages={self.num_stages}, num_warps={self.num_warps}, meta={triton_meta!r})\n" + + "@triton.jit" + ) + + def def_kernel(self, *argnames): + """ + Hook called from template code to generate function def and + needed args. + """ + assert all(isinstance(x, str) for x in argnames) + renames = IndentedBuffer(initial_indent=1) + + named_args = self.input_nodes[ + self.prefix_args : len(self.input_nodes) - self.suffix_args + ] + + assert len(argnames) == len(named_args), ( + len(argnames), + len(named_args), + self.prefix_args, + len(self.input_nodes), + ) + + for input_node in self.input_nodes[: self.prefix_args]: + # get args in correct order + self.args.input(input_node.get_name()) + + for name, input_node in zip(argnames, named_args): + arg_name = f"arg_{name}" + self.named_input_nodes[name] = input_node + self.args.input_buffers[input_node.get_name()] = arg_name + + # The args may be duplicated, so renaming must be after args are de-duplicated. + for name in argnames: + input_node = self.named_input_nodes[name] + arg_name = self.args.input_buffers[input_node.get_name()] + if input_node.get_layout().offset == 0: + renames.writeline(f"{name} = {arg_name}") + else: + offset = texpr(self.rename_indexing(input_node.get_layout().offset)) + renames.writeline(f"{name} = {arg_name} + {offset}") + + for input_node in self.input_nodes[len(self.input_nodes) - self.suffix_args :]: + # get args in correct order + self.args.input(input_node.get_name()) + + def hook(): + # python_argdefs() cannot be run until after the rest of the template lazily adds more args + arg_defs, *_ = self.args.python_argdefs() + return "\n".join( + [ + "import triton.language as tl", + "import triton", + "from torch._inductor.triton_heuristics import template", + "from torch._inductor.utils import instance_descriptor", + "from torch._inductor import triton_helpers", + "", + self.jit_line(), + f"def {self.kernel_name}({', '.join(arg_defs)}):", + self.defines, + renames.getvalue(), + ] + ) + + assert "" not in self.render_hooks + self.render_hooks[""] = hook + return "" + + def size(self, name: str, index: int): + """ + Hook called from template code to get the size of an arg. + Will add needed args to pass it in if it is dynamic. + """ + assert isinstance(index, int) + if name is None: + val = self.output_node.get_size()[index] + else: + assert isinstance(name, str) + val = self.named_input_nodes[name].get_size()[index] + return texpr(self.rename_indexing(val)) + + def stride(self, name, index): + """ + Hook called from template code to get the stride of an arg. + Will add needed args to pass it in if it is dynamic. + """ + assert isinstance(index, int) + if name is None: + val = self.output_node.get_stride()[index] + else: + assert isinstance(name, str) + val = self.named_input_nodes[name].get_stride()[index] + return texpr(self.rename_indexing(val)) + + def store_output(self, indices, val, mask): + """ + Hook called from template code to store the final output + (if the buffer hasn't been optimized away), then append any + epilogue fusions. + """ + assert isinstance(indices, (list, tuple)) + assert isinstance(val, str) + assert isinstance(mask, str) + assert self.template_mask is None + indices = list(map(TritonPrinter.paren, indices)) + index_symbols = [sympy.Symbol(x) for x in indices] + lengths = [V.graph.sizevars.simplify(s) for s in self.output_node.get_size()] + assert len(indices) == len(lengths) + + # glue to make generated code use same indexing from template + for name, range_tree_entry in zip( + indices, self.range_trees[0].construct_entries(lengths) + ): + range_tree_entry.set_name(name) + contiguous_index = sympy_dot( + ir.FlexibleLayout.contiguous_strides(lengths), index_symbols + ) + contiguous_index = self.rename_indexing(contiguous_index) + self.body.writeline("xindex = " + texpr(contiguous_index)) + self.range_trees[0].lookup(sympy.Integer(1), sympy_product(lengths)).set_name( + "xindex" + ) + self.template_mask = mask + self.template_indices = indices + output_index = self.output_node.get_layout().make_indexer()(index_symbols) + output_index = self.rename_indexing(output_index) + if output_index == contiguous_index: + output_index = sympy.Symbol("xindex") + + epilogue_args = [val] + for input_node in itertools.chain( + self.input_nodes[: self.prefix_args], + self.input_nodes[len(self.input_nodes) - self.suffix_args :], + ): + input_node.freeze_layout() + epilogue_args.append(input_node.make_loader()(index_symbols)) + + V.ops.store( # type: ignore[attr-defined] + self.output_node.get_name(), + output_index, + self.epilogue_fn(*epilogue_args), + ) + self.codegen_body() + + def hook(): + # more stuff might have been added since the codegen_body above + self.codegen_body() + return textwrap.indent(self.body.getvalue(), " ").strip() + + assert "" not in self.render_hooks + self.render_hooks[""] = hook + return "" + + def render(self, template, kwargs): + return PartialRender( + template.render(**self.template_env(), **kwargs), + self.render_hooks, + ) + + def make_load(self, name, indices, mask): + """ + Optional helper called from template code to generate the code + needed to load from an tensor. + """ + assert isinstance(indices, (list, tuple)) + assert isinstance(name, str) + assert isinstance(mask, str) + stride = self.named_input_nodes[name].get_stride() + indices = list(map(TritonPrinter.paren, indices)) + assert len(indices) == len(stride) + index = " + ".join( + f"{texpr(self.rename_indexing(s))} * {i}" for s, i in zip(stride, indices) + ) + return f"tl.load({name} + ({index}), {mask})" + + def template_env(self): + """ + Generate the namespace visible in the template. + """ + return { + fn.__name__: fn + for fn in [ + self.def_kernel, + self.size, + self.stride, + self.store_output, + self.make_load, + ] + } + + def indexing( + self, + index: sympy.Expr, + *, + copy_shape=None, + dense_indexing=False, + override_mask=None, + ): + """ + Override the default indexing to use our custom mask and force + dense indexing. + """ + result, *mask = super().indexing( + index, + dense_indexing=False, + copy_shape=self.template_mask, + override_mask=self.template_mask, + ) + return (result, *mask) + + def initialize_range_tree(self, pid_cache): + super().initialize_range_tree(pid_cache) + # ignore default codegen + self.body.clear() + self.indexing_code.clear() + + def call_kernel(self, name: str): + wrapper = V.graph.wrapper_code + _, call_args, _ = self.args.python_argdefs() + call_args = [str(a) for a in call_args] + + for i in range(len(call_args)): + if V.graph.is_unspec_arg(call_args[i]): + call_args[i] = call_args[i] + ".item()" + if isinstance(call_args[i], sympy.Symbol): + call_args[i] = texpr(call_args[i]) + + if V.graph.cpp_wrapper: + wrapper.generate_kernel_call( + name, + call_args, + device_index=V.graph.scheduler.current_device.index, + ) + else: + call_args = ", ".join(call_args) # type: ignore[assignment] + stream_name = wrapper.write_get_cuda_stream( + V.graph.scheduler.current_device.index + ) + + wrapper.add_import_once(f"import {self.grid_fn.__module__}") + meta = wrapper.add_meta_once(self.meta) + + grid_call = [ + texpr(V.graph.sizevars.simplify(s)) for s in self.call_sizes + ] + [meta] + grid_call = f"{self.grid_fn.__module__}.{self.grid_fn.__name__}({', '.join(grid_call)})" + wrapper.writeline( + f"{name}.run({call_args}, grid={grid_call}, stream={stream_name})" + ) + + +@functools.lru_cache(None) +def _jinja2_env(): + try: + import jinja2 + + return jinja2.Environment( + undefined=jinja2.StrictUndefined, + ) + except ImportError: + return None + + +class TritonTemplate: + index_counter = itertools.count() + all_templates: Dict[str, "TritonTemplate"] = dict() + + @staticmethod + def _template_from_string(source): + env = _jinja2_env() + if env is not None: + return env.from_string(source) + return None + + def __init__(self, name: str, grid: Any, source: str, debug=False): + super().__init__() + self.name = name + self.grid = grid + self.template = self._template_from_string(source) + assert name not in self.all_templates, "duplicate template name" + self.all_templates[name] = self + self.debug = debug + + def maybe_append_choice( + self, + choices, + input_nodes, + layout, + num_stages, + num_warps, + prefix_args=0, + suffix_args=0, + epilogue_fn=identity, + **kwargs, + ): + try: + choices.append( + self.generate( + input_nodes=input_nodes, + layout=layout, + num_stages=num_stages, + num_warps=num_warps, + prefix_args=prefix_args, + suffix_args=suffix_args, + epilogue_fn=epilogue_fn, + **kwargs, + ) + ) + except NotImplementedError: + pass + + def generate( + self, + input_nodes, + layout, + num_stages, + num_warps, + prefix_args=0, + suffix_args=0, + epilogue_fn=identity, + **kwargs, + ): + assert self.template, "requires jinja2" + defines = StringIO() + for name, val in kwargs.items(): + defines.write(f" {name} : tl.constexpr = {val}\n") + defines = defines.getvalue() + + fake_out = ir.Buffer("buf_out", layout) + kernel_name = f"triton_{self.name}" + + numel = sympy_product(layout.size) + buffers = itertools.chain(input_nodes, (fake_out,)) + if not TritonScheduling.can_use_32bit_indexing(numel, buffers): + raise NotImplementedError( + "64-bit indexing is not yet implemented for triton templates" + ) + + kernel_options = dict( + input_nodes=input_nodes, + defines=defines, + num_stages=num_stages, + num_warps=num_warps, + grid_fn=self.grid, + meta=kwargs, + call_sizes=layout.size, + prefix_args=prefix_args, + suffix_args=suffix_args, + epilogue_fn=epilogue_fn, + index_dtype="tl.int32", + ) + with patch.object( + V.graph, "get_dtype", self.fake_get_dtype(fake_out) + ), TritonTemplateKernel( + kernel_name=kernel_name, + output_node=fake_out, + use_jit=True, + **kernel_options, + ) as kernel: + try: + code = kernel.render(self.template, kwargs).finalize() + except ZeroDivisionError: + # TODO(nmacchioni): fix sympy division by zero + return None + if self.debug: + print("Generated Code:\n", code) + extra = ( + "-".join( + [ + *[ + f"{kwarg}={repr(kwargs[kwarg])}" + for kwarg in sorted(kwargs.keys()) + ], + f"num_stages={num_stages}", + f"num_warps={num_warps}", + ] + ) + + "-" + ) + mod = PyCodeCache.load(code, extra) + _, call_args, _ = kernel.args.python_argdefs() + + expected_args = list(unique(x.get_name() for x in input_nodes)) + expected_args.extend([fake_out.get_name()]) + assert list(call_args)[: len(expected_args)] == expected_args, ( + call_args, + expected_args, + ) + extra_args = V.graph.sizevars.size_hints( + map(sympy.expand, call_args[len(expected_args) :]) + ) + + kernel_hash_name = f"triton_{self.name}_{next(self.index_counter)}" + + def make_kernel_render(out_node): + kernel = TritonTemplateKernel( + kernel_name="KERNEL_NAME", + output_node=out_node, + use_jit=False, + **kernel_options, + ) + render = functools.partial( + kernel.render, + self.template, + kwargs, + ) + return kernel, render + + # create the BenchmarkRequest + grid = self.grid(*V.graph.sizevars.size_hints(layout.size), kwargs) + bmreq = BenchmarkRequest( + module_path=mod.__file__, + module_cache_key=mod.key, + kernel_name=kernel_name, + grid=grid, + extra_args=extra_args, + num_stages=num_stages, + num_warps=num_warps, + input_tensors=TensorMeta.from_irnodes(input_nodes), + output_tensor=TensorMeta.from_irnodes(layout), + ) + + return TritonTemplateCaller( + kernel_hash_name, + input_nodes, + layout, + make_kernel_render, + extra.strip("-").replace("-", ", "), + bmreq, + ) + + @staticmethod + def fake_get_dtype(fake_out): + _get_dtype_real = V.graph.get_dtype + + def get_dtype(name): + if name == fake_out.get_name(): + return fake_out.get_dtype() + return _get_dtype_real(name) + + return get_dtype + + +class ExternKernelChoice: + def __init__( + self, + kernel, + cpp_kernel=None, + *, + name=None, + has_out_variant=True, + ): + super().__init__() + name = name or kernel.__name__ + assert callable(kernel) + assert not hasattr(extern_kernels, name), "duplicate extern kernel" + self.name = name + self.cpp_kernel = cpp_kernel + self.has_out_variant = has_out_variant + setattr(extern_kernels, name, kernel) + + def to_callable(self): + return getattr(extern_kernels, self.name) + + def call_name(self): + return f"extern_kernels.{self.name}" + + @functools.lru_cache(None) + def hash_key(self): + fn = self.to_callable() + parts = [ + self.name, + getattr(fn, "__name__", ""), + getattr(fn, "__module__", ""), + ] + try: + parts.append(inspect.getsource(fn)) + except Exception: + pass + return code_hash("-".join(parts)) + + def bind(self, input_nodes, layout, ordered_kwargs_for_cpp_kernel=(), **kwargs): + self.ordered_kwargs_for_cpp_kernel = ordered_kwargs_for_cpp_kernel + return ExternKernelCaller( + self, input_nodes, layout, kwargs, has_out_variant=self.has_out_variant + ) + + +class ChoiceCaller: + def __init__(self, name, input_nodes, layout): + super().__init__() + self.name = name + self.layout = layout + self.input_nodes = input_nodes + + def benchmark(self, *args, out): + algo = self.to_callable() + return do_bench(lambda: algo(*args, out=out)) + + def call_name(self): + raise NotImplementedError() + + def to_callable(self): + raise NotImplementedError() + + def hash_key(self): + raise NotImplementedError() + + def output_node(self): + raise NotImplementedError() + + +class TritonTemplateCaller(ChoiceCaller): + def __init__( + self, name, input_nodes, layout, make_kernel_render, debug_extra, bmreq + ): + super().__init__(name, input_nodes, layout) + self.make_kernel_render = make_kernel_render + self.debug_extra = debug_extra + self.bmreq = bmreq + + def benchmark(self, *args, out): + assert self.bmreq is not None + return self.bmreq.benchmark(*args, output_tensor=out) + + def __str__(self): + return f"TritonTemplateCaller({self.bmreq.module_path}, {self.debug_extra})" + + def call_name(self): + return f"template_kernels.{self.name}" + + def hash_key(self): + return "-".join( + [ + self.name.rsplit("_", 1)[0], + self.bmreq.module_cache_key, + ] + ) + + def output_node(self): + return ir.TensorBox.create( + ir.TemplateBuffer( + layout=self.layout, + inputs=self.input_nodes, + make_kernel_render=self.make_kernel_render, + ) + ) + + +class ExternKernelCaller(ChoiceCaller): + def __init__( + self, + choice: ExternKernelChoice, + input_nodes, + layout, + kwargs=None, + *, + has_out_variant=True, + ): + super().__init__(choice.name, input_nodes, layout) + self.choice = choice + self.kwargs = kwargs or {} + self.has_out_variant = has_out_variant + + def __str__(self): + return f"ExternKernelCaller({self.choice.call_name()})" + + def benchmark(self, *args, out): + if self.has_out_variant: + return super().benchmark(*args, out=out) + else: + algo = self.to_callable() + out_new = algo(*args) + torch._C._dynamo.guards.assert_size_stride( # type: ignore[attr-defined] + out_new, tuple(out.size()), tuple(out.stride()) + ) + out.copy_(out_new) # for correctness checking + return do_bench(lambda: algo(*args)) + + def to_callable(self): + fn = self.choice.to_callable() + if self.kwargs: + return functools.partial(fn, **self.kwargs) + else: + return fn + + def hash_key(self): + return "-".join( + [ + self.choice.name, + *[ + f"{kwarg}={repr(self.kwargs[kwarg])}" + for kwarg in sorted(self.kwargs.keys()) + ], + self.choice.hash_key(), + ] + ) + + def output_node(self): + cls: Union[Type[ir.ExternKernelOut], Type[ir.ExternKernelAlloc]] + if self.has_out_variant: + cls = ir.ExternKernelOut + else: + cls = ir.ExternKernelAlloc + return ir.TensorBox.create( + cls( + layout=self.layout, + inputs=self.input_nodes, + kernel=self.choice.call_name(), + cpp_kernel=self.choice.cpp_kernel, + ordered_kwargs_for_cpp_kernel=self.choice.ordered_kwargs_for_cpp_kernel, + kwargs=self.kwargs, + ) + ) + + +class ErrorFromChoice(RuntimeError): + def __init__(self, msg, choice: ChoiceCaller, inputs_str): + msg += f"\nFrom choice {choice}\n{inputs_str}" + super().__init__(msg) + self.choice = choice + + +class AlgorithmSelectorCache(PersistentCache): + def __call__(self, name, choices: List[ChoiceCaller], input_nodes, layout): + # TODO(nmacchioni): remove once CI tests are fixed + choices = [choice for choice in choices if choice is not None] + if len(choices) == 0: + raise RuntimeError( + "No choices to select, please consider adding ATEN into max_autotune_gemm_backends " + "config (defined in torch/_inductor/config.py) to allow at least one choice. " + ) + + if len(choices) == 1: + return choices[0].output_node() + + @functools.lru_cache(None) + def make_benchmark_fn(): + return self.make_benchmark_fn(choices, input_nodes, layout) + + def autotune(choice): + benchmark_fn = make_benchmark_fn() + try: + timing = benchmark_fn( + choice, + ) + except RuntimeError as e: + msg = str(e) + if "invalid argument" in msg: + msg += "\n\nThis may mean this GPU is too small for max_autotune mode.\n\n" + log.warning(msg) + return float("inf") + elif "illegal memory access" in msg: + msg += "\n\nEither error in template or triton bug.\n" + raise ErrorFromChoice(msg, choice, benchmark_fn.debug_str()) + except AssertionError as e: + raise AssertionError(f"Incorrect result from choice {choice}\n\n{e}") + return timing + + if config.autotune_in_subproc: + from .autotune_process import tuning_process + + # do the optional warmup + tuning_process.initialize() + assert tuning_process.valid() + + autotune_start_ts = time.time() + timings = self.lookup( + choices, + name, + repr([self.key_of(x) for x in input_nodes]), + autotune, + ) + autotune_elapse = time.time() - autotune_start_ts + if timings == {} or choices[0] not in timings: + return choices[0].output_node() + + if make_benchmark_fn.cache_info().currsize: + counters["inductor"]["select_algorithm_autotune"] += 1 + self.log_results(name, input_nodes, timings, autotune_elapse) + return builtins.min(timings, key=timings.__getitem__).output_node() + + @classmethod + def make_benchmark_fn( + cls, + choices, + input_nodes, + layout, + ): + # de-duplicate args + unique_example_inputs = { + x.get_name(): cls.benchmark_example_value(x) for x in input_nodes + } + example_inputs = list(unique_example_inputs.values()) + example_inputs_extern = [ + torch.as_strided( + unique_example_inputs[input_node.get_name()], + V.graph.sizevars.size_hints(input_node.get_size()), + V.graph.sizevars.size_hints(input_node.get_stride()), + V.graph.sizevars.size_hint(input_node.get_layout().offset), + ) + for input_node in input_nodes + ] + + out = cls.benchmark_example_value(layout) + out_extern = torch.as_strided( + out, out.size(), out.stride(), V.graph.sizevars.size_hint(layout.offset) + ) + if VERIFY: + choices[0].benchmark(*example_inputs_extern, out=out_extern) + expected = out_extern.clone() + + if DEBUG: + print(f"{len(choices)} tuning requests:") + + def benchmark_in_current_process(choice): + if DEBUG: + start_ts = time.time() + out.zero_() + if isinstance(choice, ExternKernelCaller): + # aten kernels want the offset baked in for sliced tensors + result = choice.benchmark(*example_inputs_extern, out=out_extern) + else: + # triton templates want the base pointer for sliced tensors + result = choice.benchmark(*example_inputs, out=out) + if VERIFY: + torch.testing.assert_close(out_extern, expected, **VERIFY) + torch.cuda.synchronize() # shake out any CUDA errors + return result + + def benchmark_in_sub_process(choice): + # only benchmark triton kernel in sub process for now. + # ATen/Extern kernel are still benchmarked in the current process. + if isinstance(choice, ExternKernelCaller): + return benchmark_in_current_process(choice) + + from . import autotune_process + + if DEBUG: + start_ts = time.time() + + out = autotune_process.benchmark_in_sub_process( + choice, + ) + if DEBUG: + elapse = time.time() - start_ts + print(f"MultiProcessTuning {choice}: {elapse}") + return out + + benchmark = ( + benchmark_in_sub_process + if config.autotune_in_subproc + else benchmark_in_current_process + ) + + def debug_str(): + def tensor_repr(x): + return ( + f"torch.empty_strided({tuple(x.size())!r}, {tuple(x.stride())!r}, " + f"dtype={x.dtype!r}, device={x.device.type!r})" + ) + + lines = [ + "inputs = [", + ] + for x in example_inputs: + lines.append(f" {tensor_repr(x)},") + lines += ["]", f"out = {tensor_repr(out)}", ""] + return "\n".join(lines) + + benchmark.debug_str = debug_str # type: ignore[attr-defined] + return benchmark + + @staticmethod + def log_results(name, input_nodes, timings, elapse): + if not (config.max_autotune or config.max_autotune_gemm) or not PRINT_AUTOTUNE: + return + sizes = ", ".join( + [ + "x".join(map(str, V.graph.sizevars.size_hints(n.get_size()))) + for n in input_nodes + ] + ) + top_k = sorted(timings, key=timings.__getitem__)[:10] + best = top_k[0] + best_time = timings[best] + sys.stderr.write(f"AUTOTUNE {name}({sizes})\n") + for choice in top_k: + result = timings[choice] + sys.stderr.write( + f" {choice.name} {result:.4f} ms {best_time/result:.1%}\n" + ) + + autotune_type_str = ( + "SubProcess" if config.autotune_in_subproc else "SingleProcess" + ) + sys.stderr.write(f"{autotune_type_str} AUTOTUNE takes {elapse:.4f} seconds\n") + + @staticmethod + def benchmark_example_value(node): + """ + Convert an ir.Buffer into a concrete torch.Tensor we can use for + benchmarking. + """ + if isinstance(node, ir.Layout): + node = ir.Buffer("fake", node) + # triton templates want the base tensor. + if isinstance(node, ir.BaseView): + node = node.unwrap_view() + return rand_strided( + V.graph.sizevars.size_hints(node.get_size()), + V.graph.sizevars.size_hints(node.get_stride()), + device=node.get_device(), + dtype=node.get_dtype(), + extra_size=node.layout.offset, + ) + + @staticmethod + def key_of(node): + """ + Extract the pieces of an ir.Buffer that we should invalidate cached + autotuning results on. + """ + sizevars = V.graph.sizevars + return ( + node.get_device().type, + str(node.get_dtype()), + *sizevars.size_hints(node.get_size()), + *sizevars.size_hints(node.get_stride()), + sizevars.size_hint(node.get_layout().offset), + ) + + +_ALGORITHM_SELECTOR_CACHE = None + + +def autotune_select_algorithm(*args, **kwargs): + global _ALGORITHM_SELECTOR_CACHE + if _ALGORITHM_SELECTOR_CACHE is None: + _ALGORITHM_SELECTOR_CACHE = AlgorithmSelectorCache() + return _ALGORITHM_SELECTOR_CACHE(*args, **kwargs) + + +def realize_inputs(*args): + if len(args) == 1: + return ir.ExternKernel.require_stride1(ir.ExternKernel.realize_input(args[0])) + return [realize_inputs(x) for x in args] + + +# ensure lowering is imported so that `extern_kernels.*` is populated +from . import lowering # noqa: F401 diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/sizevars.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/sizevars.py new file mode 100644 index 0000000000000000000000000000000000000000..4398fc7fc6620e6dfb131966979b67f578f6b077 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/sizevars.py @@ -0,0 +1,576 @@ +import functools +import itertools +import logging +from typing import Callable, Dict, List, Tuple, Union + +import sympy +from sympy import Expr + +from torch.fx.experimental.symbolic_shapes import ShapeEnv +from torch.utils._sympy.functions import FloorDiv, ModularIndexing + +from .utils import sympy_subs, sympy_symbol, VarRanges +from .virtualized import V + +log = logging.getLogger(__name__) + + +# This class is a little awkward, because ShapeEnv is doing most of the heavy +# lifting and in some cases we should be directly passing through to ShapeEnv, +# but there is some extra inductor logic that needs to be handled here +class SizeVarAllocator: + def __init__(self, shape_env=None): + super().__init__() + if shape_env is None: + shape_env = ShapeEnv() + self.shape_env = shape_env + self.var_to_val = self.shape_env.var_to_val + self.replacements: Dict[sympy.Symbol, Expr] = self.shape_env.replacements + # Maps of dynamic sizes that have to be precomputed on the host to the kernel args. + # The basic idea is if we have some complicated sympy expression + # f(s0), we may choose to precompute it on the host and then replace + # all occurrences of that sympy expression with ps0, so that when we + # codegen we simply reference ps0 directly without repeating + # f(s0). Unlike regular size variables, ps variables cannot be + # guarded upon; so if we are asked to guard on a Sympy expression + # which potentially could have already had a precomputed replacement + # on it, we are obligated to invert the precomputed replacements + # (inv_precomputed_replacements). + self.precomputed_replacements: Dict[Expr, sympy.Symbol] = dict() + self.inv_precomputed_replacements: Dict[sympy.Symbol, Expr] = dict() + self.stride_vars = self.make_stride_vars_cache() + self.simplify_with_ranges = self.make_simplify_with_ranges_cache() + self._simplify_loops = self.make_simplify_loops_cache() + + def simplify(self, expr: Expr): + return sympy.expand(expr).xreplace(self.replacements) + + def make_simplify_with_ranges_cache(self): + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache = dict() + replacement_count = len(self.replacements) + + def simplify_with_ranges(expr: Expr, var_ranges: VarRanges): + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (expr, *var_ranges.items()) + result = cache.get(key, None) + if result is None: + result = self._simplify_with_ranges(expr, var_ranges) + cache[key] = result + return result + + return simplify_with_ranges + + def make_simplify_loops_cache(self): + """ + self._simplify_with_ranges() can be expensive, cache its results + """ + cache = dict() + replacement_count = len(self.replacements) + + def simplify_loops(index_vars, sizes, index_formulas): + nonlocal replacement_count + if replacement_count != len(self.replacements): + # new replacements invalidates cached results + cache.clear() + replacement_count = len(self.replacements) + key = (*index_vars, *sizes, *index_formulas) + result = cache.get(key, None) + if result is None: + result = self._simplify_loops_impl(index_vars, sizes, index_formulas) + cache[key] = result + return result + + return simplify_loops + + def _simplify_with_ranges(self, expr: Expr, var_ranges: VarRanges): + """ + Simplify indexing expression with knowledge of the ranges of + iteration variables. + """ + + expr = join_dimensions(self.simplify(expr)) + original_expr = expr + + def remove_zero_terms(base, divisor): + """Symbols smaller than the divisor are zero""" + for v in base.free_symbols: + if v in var_ranges: + # var smaller than divisor can be removed + # if the rest is guaranteed to be multiple of divisor + rest = sympy.Wild("_rest", exclude=[v]) + m = base.match(v + rest) + if m and v not in m[rest].free_symbols: + gcd = sympy.gcd(m[rest], divisor) + if gcd == divisor: + if self.statically_known_leq(var_ranges[v], divisor): + base = m[rest] + return base + + def visit_indexing_div(base, divisor): + return FloorDiv(remove_zero_terms(base, divisor), divisor) + + def visit_modular_indexing(base, divisor, modulus): + base = remove_zero_terms(base, divisor) + base_pos = True + if isinstance(base, ModularIndexing): + # for modular indexing, biggest values from the ranges don't necessarily result in + # the biggest result, the biggest result is modulus - 1 + base_s = base.args[2] - 1 + elif not base.has(ModularIndexing): + # actual iteration range is to size-1 + iter_ranges_zero = {k: 0 for k, v in var_ranges.items()} + base_lowest = sympy_subs(base, iter_ranges_zero) + if self.statically_known_leq(0, base_lowest): + # can't replace with indexing div if base can be negative + base_pos = True + else: + base_pos = False + iter_ranges = {k: v - 1 for k, v in var_ranges.items()} + base_s = sympy_subs(base, iter_ranges) + else: + base_s = base + if self.statically_known_lt(base_s, modulus * divisor) and base_pos: + return FloorDiv(base, divisor) + return ModularIndexing(base, divisor, modulus) + + if expr.has(ModularIndexing): + expr = expr.replace( + ModularIndexing( + sympy.Wild("base"), + sympy.Wild("divisor"), + sympy.Wild("modulus"), + ), + visit_modular_indexing, + ) + + if expr.has(FloorDiv): + expr = expr.replace( + FloorDiv( + sympy.Wild("base"), + sympy.Wild("divisor"), + ), + visit_indexing_div, + ) + + if expr != original_expr: + return self._simplify_with_ranges(expr, var_ranges) + return expr + + def _simplify_loops_impl(self, index_vars, sizes, index_formulas): + """ + Try to remove as many axis from loop iterations as possible, by: + 1) removing size==1 dimensions + 2) fuse contiguous dimensions into a single loop + If channel_last = True, we will prevent the last dim fused with other dims + """ + sizes = list(map(self.simplify, sizes)) + + strides = [self.stride_vars(x, index_vars) for x in index_formulas] + assert len(sizes) == len(strides[0]), (len(sizes), len(strides[0])) + + for i in range(len(sizes)): + if sizes[i] == 1: + # remove dim + sizes[i] = None + + def can_merge_dims(a, b): + for k in range(len(strides)): + if self.simplify(strides[k][a] * sizes[a]) == self.simplify( + strides[k][b] + ): + # approximate test passed, try sound version + va = index_vars[a] + vb = index_vars[b] + v = sympy_symbol("_merge_tester") + expr1 = sympy_subs(index_formulas[k], {va: v * sizes[a], vb: 0}) + expr2 = sympy_subs(index_formulas[k], {va: 0, vb: v}) + if self.simplify(expr1) == self.simplify(expr2): + continue + return False + return True + + changed = True + while changed: + changed = False + for i, j in itertools.product( + reversed(range(len(sizes))), reversed(range(len(sizes))) + ): + if i == j or sizes[i] is None or sizes[j] is None: + continue + if can_merge_dims(i, j): + changed = True + sizes[i] = sizes[i] * sizes[j] + sizes[j] = None + + def reindex(index): + it = list(reversed(index)) + new_index = [] + for size in sizes: + if size is None: + new_index.append(sympy.Integer(0)) + else: + new_index.append(it.pop()) + assert not it + return new_index + + def prune(index): + assert len(index) == len(sizes) + return [i for i, s in zip(index, sizes) if s is not None] + + return [x for x in sizes if x is not None], reindex, prune + + # Note - [On Statically Known] + # + # The statically_known_* family of functions below replaces a prior system, called maybe_guard_*. The prior system + # operated by providing esentially a question, where the size hinted values were evaluted. If the condition was + # true, we add a guard and return True, otherwise, False. + # + # def maybe_guard_foo(args): + # if size_hinted_check(args): + # return False # No guard, no optim + # guard(args) # Make a guard + # return True # Safe to apply optimization + # + # The prior system incurred a guard, and green lit an optimization. + # + # The new system works in reverse - in the new system, if we know that the inputs are static, and evaluate the + # condition as true, we green light the optimization, and we do not incur a guard. If we cannot prove that, we + # return False. + # + # def maybe_guard_foo(args): + # if all_static(args): + # return True # Safe to apply optimization + # else: + # return False # No guard, no optim + + # See Note - [On Statically Known] + + def is_expr_static_and_true(self, expr: Union[Expr, int]) -> bool: + if expr in (True, False): + return expr + + try: + simplified = self.shape_env._maybe_evaluate_static(expr) + if simplified is not None: + return bool(simplified) + except Exception: + log.debug("Could not simplify %s", expr) + + return False + + def statically_known_equals(self, left: Expr, right: Expr) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right are equal. + """ + return self.is_expr_static_and_true(sympy.Eq(left, right)) + + # See Note - [On Statically Known] + def statically_known_list_equals(self, left: List[Expr], right: List[Expr]) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left and right lists are equal. + """ + if len(left) != len(right): + return False + if all(self.statically_known_equals(l, r) for l, r in zip(left, right)): + return True + return False + + # See Note - [On Statically Known] + def statically_known_leq(self, left: Expr, right: Expr) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than or equal to right. + """ + expr = left <= right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_lt(self, left: Expr, right: Expr) -> bool: + """ + Returns a bool indicating if it is sound to optimize as if left is less than right. + """ + expr = left < right + return self.is_expr_static_and_true(expr) + + # See Note - [On Statically Known] + def statically_known_multiple_of(self, numerator: Expr, denominator: Expr) -> bool: + """ + Return a bool indicating if it is sound to optimize for the numerator being a multiple of the denominator. + """ + expr = sympy.Eq(numerator % denominator, 0) + return self.is_expr_static_and_true(expr) + + # The guard functions require you to ALREADY KNOW that a particular + # condition holds. If you don't know (you want to guard on an expression + # being a particular value, and then get access to that value), use + # the evaluate functions. + + def guard_equals(self, left: Expr, right: Expr) -> Expr: + if isinstance(left, Expr): + left = sympy_subs(left, self.inv_precomputed_replacements) + if isinstance(right, Expr): + right = sympy_subs(right, self.inv_precomputed_replacements) + assert self.shape_env.evaluate_expr(sympy.Eq(left, right)) + return left + + def guard_leq(self, left: Expr, right: Expr) -> None: + return self.guard_lt(left, right + 1) + + def guard_lt(self, left: Expr, right: Expr) -> None: + assert self.shape_env.evaluate_expr(sympy.Lt(left, right)) + + # The evaluate functions evaluate some symbolic sympy expression + # (NB: not necessarily an Expr) and return what the concrete result + # is, guarding on the expression being that result + + # NB: write evaluate_expr(sympy.Lt(a, b)) rather than evaluate_expr(a < b) + # as this will ensure that you actually have a sympy'ified expression, + # and will prevent you from incorrectly writing evaluate_expr(a == b) + # which does the wrong thing if a or b is a sympy expression + def evaluate_expr(self, left: Union[Expr, sympy.logic.boolalg.Boolean]) -> bool: + assert isinstance(left, (Expr, sympy.logic.boolalg.Boolean)), type(left) + return self.shape_env.evaluate_expr(sympy.sympify(left)) + + def evaluate_min(self, left: Expr, right: Expr) -> Expr: + """return the smaller of left and right, and guard on that choice""" + lv = self.size_hint(left) + rv = self.size_hint(right) + if lv == rv: + return self.guard_equals(left, right) + elif lv < rv: + self.guard_lt(left, right) + return left + else: + self.guard_lt(right, left) + return right + + def evaluate_static_shape(self, left: Expr) -> int: + right = self.size_hint(left) + self.guard_equals(left, sympy.Integer(right)) + return int(right) + + def evaluate_static_shapes(self, left: List[Expr]) -> List[int]: + return [self.evaluate_static_shape(x) for x in left] + + def symbolic_hint(self, expr: Expr) -> Expr: + # Substitute all hints into expr, but leave unbacked symints alone + if not isinstance(expr, Expr): + assert isinstance(expr, int) + return expr + free_symbols = expr.free_symbols + if not free_symbols: + return int(expr) + while any(s.name.startswith("ps") for s in free_symbols): + expr = sympy_subs(expr, self.inv_precomputed_replacements) + free_symbols = expr.free_symbols + return sympy_subs(expr, self.var_to_val) + + def size_hint(self, expr: Expr) -> int: + out = self.symbolic_hint(expr) + try: + return int(out) + except Exception: + log.debug("failed on: %s", out) + raise + + def size_hints(self, exprs: List[Expr]) -> Tuple[int, ...]: + return tuple(self.size_hint(x) for x in exprs) + + def _lru_cache(self, fn, maxsize=None): + """ + Wrapper around functools.lru_cache that clears when replacements + has been invalidated. + """ + fn_cache = functools.lru_cache(maxsize)(fn) + prior_len = len(self.replacements) + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + nonlocal prior_len + if prior_len != len(self.replacements): + prior_len = len(self.replacements) + fn_cache.cache_clear() + return fn_cache(*args, **kwargs) + + return wrapper + + def make_stride_vars_cache(self): + cache = self._lru_cache(self._stride_vars) + + def stride_vars( + index: Expr, + vars: List[sympy.Symbol], + support_vars: List[sympy.Symbol] = None, + ) -> List[Expr]: + if not support_vars: + support_vars = vars + return cache(index, tuple(vars), tuple(support_vars)) + + return stride_vars + + def _stride_vars( + self, index: Expr, vars: List[sympy.Symbol], support_vars: List[sympy.Symbol] + ) -> List[Expr]: + """Convert an indexing expression back into strides + + NOTE: This is only valid if the index is a standard strided offset + calculation. e.g. 10 * ModularIndexing(i0 + 1, 1, 2) would give a + stride of -10 because the index wraps around after the first element + + """ + strides = [] + index = self.simplify(index) + # remove any offset + index = index - sympy_subs( + index, {v: sympy.Integer(0) for v in support_vars if v != 0} + ) + for i in range(len(vars)): + # drop all the other dims + index_dim = sympy_subs( + index, + { + support_vars[j]: sympy.Integer(0) + for j in range(len(support_vars)) + if vars[i] != support_vars[j] and support_vars[j] != 0 + }, + ) + v = vars[i] + if v == 0: + strides.append(sympy.Integer(0)) + else: + # TODO(jansel): should we use sympy.diff here? + strides.append( + sympy_subs(index_dim, {v: sympy.Integer(1)}) + - sympy_subs(index_dim, {v: sympy.Integer(0)}) + ) + return strides + + def offset_var(self, index: Expr, vars: List[sympy.Symbol]) -> Expr: + """Extract offset part of an indexing expression""" + index = self.simplify(index) + return sympy_subs(index, {v: sympy.Integer(0) for v in vars if v != 0}) + + def stride_hints( + self, + index: Expr, + vars: List[sympy.Symbol], + support_vars: List[sympy.Symbol] = None, + ) -> List[int]: + for v in index.free_symbols: + if v.name.startswith("indirect"): + index = sympy_subs(index, {v: 0}) + result = [] + for s in self.stride_vars(index, vars, support_vars): + try: + result.append(self.size_hint(s)) + except TypeError: + result.append(0) + return result + + def stride_order(self, index: Expr, vars: List[sympy.Symbol]) -> List[int]: + strides = tuple( + map(abs, self.stride_hints(index, vars)) + ) # lambda to placate mypy + order = list(range(len(strides))) + order.sort(key=lambda x: (strides[x] == 0, strides[x])) + return order + + def lookup_precomputed_size(self, expr: Expr): + if expr not in self.precomputed_replacements: + sym = sympy_symbol(f"ps{len(self.precomputed_replacements)}") + self.precomputed_replacements[expr] = sym + self.inv_precomputed_replacements[sym] = expr + return self.precomputed_replacements[expr] + + +def join_dimensions(expr: Expr) -> Expr: + if not isinstance(expr, sympy.Add) or not expr.has(ModularIndexing): + return expr # fast exit path + return _join_dimensions_cached(expr) + + +@functools.lru_cache(256) +def _join_dimensions_cached(expr: Expr) -> Expr: + """ + ModularIndexing(i0, 1, 32) + 32 * ModularIndexing(i0, 32, 4) + becomes + ModularIndexing(i0, 1, 128) + ModularIndexing(i0, 1, 32) + 32 * FloorDiv(i0, 32) + becomes i0 + + + This type of pattern can come from view operations + """ + assert isinstance(expr, sympy.Add) + + scale = sympy.Wild("scale", exclude=[0]) + base = sympy.Wild("base") + divisor = sympy.Wild("divisor") + mod1 = sympy.Wild("modulus") + mod2 = sympy.Wild("modulus2") + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] + * m1[mod1] + * ModularIndexing(m1[base], m1[divisor] * m1[mod1], mod2) + ) + if m2 and term1 != term2: + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] + * ModularIndexing(m1[base], m1[divisor], m1[mod1] * m2[mod2]) + ) + return expr + for term1 in expr.args: + m1 = term1.match(scale * ModularIndexing(base, divisor, mod1)) + if m1: + for term2 in expr.args: + m2 = term2.match( + m1[scale] * m1[mod1] * FloorDiv(m1[base], m1[divisor] * m1[mod1]) + ) + if m2 is not None: # in case of success we get an empty dict here + expr = join_dimensions( + expr + - term1 + - term2 + + m1[scale] * FloorDiv(m1[base], m1[divisor]) + ) + return expr + return expr + + +class SimplifyIndexing(V.WrapperHandler): # type: ignore[name-defined] + """ + A wrapper around .virtualize.ops that uses var range information to + simplify ModularIndexing/FloorDiv. + """ + + def __init__(self, inner, var_ranges: VarRanges): + super().__init__(inner) + self.name = "SimplifyIndexing" + self._simplify: Callable[ + [Expr], Expr + ] = lambda index: V.graph.sizevars.simplify_with_ranges(index, var_ranges) + + def load(self, name: str, index: sympy.Expr): + return self._inner.load(name, self._simplify(index)) + + def store(self, name, index, value, mode=None): + return self._inner.store(name, self._simplify(index), value, mode=mode) + + def store_reduction(self, name, index, value): + return self._inner.store_reduction(name, self._simplify(index), value) + + def index_expr(self, index, dtype): + return self._inner.index_expr(self._simplify(index), dtype) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/test_operators.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/test_operators.py new file mode 100644 index 0000000000000000000000000000000000000000..100b013566bdbebe4e8b83d8a7d5d8eeff757c80 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/test_operators.py @@ -0,0 +1,24 @@ +import torch.library +from torch import Tensor +from torch.autograd import Function + +_test_lib_def = torch.library.Library("_inductor_test", "DEF") +_test_lib_def.define("realize(Tensor self) -> Tensor") + +_test_lib_impl = torch.library.Library("_inductor_test", "IMPL") +for dispatch_key in ("CPU", "CUDA", "Meta"): + _test_lib_impl.impl("realize", lambda x: x.clone(), dispatch_key) + + +class Realize(Function): + @staticmethod + def forward(ctx, x): + return torch.ops._inductor_test.realize(x) + + @staticmethod + def backward(ctx, grad_output): + return grad_output + + +def realize(x: Tensor) -> Tensor: + return Realize.apply(x) diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/triton_helpers.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/triton_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..e6be9c8756c68d701ff42e59285a15416ca71928 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/triton_helpers.py @@ -0,0 +1,182 @@ +import triton +import triton.language as tl + + +@triton.jit +def promote_to_tensor(x): + # Addition promotes to tensor for us + return x + tl.zeros((1,), tl.int1) + + +@triton.jit +def is_floating(x): + return promote_to_tensor(x).dtype.is_floating() + + +@triton.jit +def _prod_accumulate(a, b): + return a * b + + +@triton.jit +def prod(input, axis): + return tl.reduce(input, axis, _prod_accumulate) + + +@triton.jit +def minimum(a, b): + mask = a < b + if is_floating(a): + mask |= a != a + return tl.where(mask, a, b) + + +@triton.jit +def maximum(a, b): + mask = a > b + if is_floating(a): + mask |= a != a + return tl.where(mask, a, b) + + +@triton.jit +def min2(a, dim): + return tl.reduce(a, dim, minimum) + + +@triton.jit +def max2(a, dim): + return tl.reduce(a, dim, maximum) + + +@triton.jit +def minimum_with_index(a_value, a_index, b_value, b_index): + mask = a_value < b_value + equal = a_value == b_value + if is_floating(a_value): + a_isnan = a_value != a_value + b_isnan = b_value != b_value + mask |= a_isnan and not b_isnan + # Consider NaNs as equal + equal |= a_isnan and b_isnan + + # Prefer lowest index if values are equal + mask |= equal & (a_index < b_index) + return tl.where(mask, a_value, b_value), tl.where(mask, a_index, b_index) + + +@triton.jit +def maximum_with_index(a_value, a_index, b_value, b_index): + mask = a_value > b_value + equal = a_value == b_value + if is_floating(a_value): + a_isnan = a_value != a_value + b_isnan = b_value != b_value + mask |= a_isnan and not b_isnan + # Consider NaNs as equal + equal |= a_isnan and b_isnan + + # Prefer lowest index if values are equal + mask |= equal & (a_index < b_index) + return tl.where(mask, a_value, b_value), tl.where(mask, a_index, b_index) + + +@triton.jit +def min_with_index(value, index, dim): + return tl.reduce((value, index), dim, minimum_with_index) + + +@triton.jit +def max_with_index(value, index, dim): + return tl.reduce((value, index), dim, maximum_with_index) + + +@triton.jit +def welford_reduce(value, mean, m2, weight): + delta = value - mean + new_weight = weight + 1 + new_mean = mean + delta / new_weight + return ( + new_mean, + m2 + delta * (value - new_mean), + new_weight, + ) + + +@triton.jit +def welford_combine(mean_1, m2_1, weight_1, mean_2, m2_2, weight_2): + delta = mean_2 - mean_1 + new_weight = weight_1 + weight_2 + w2_over_w = tl.where(new_weight == 0.0, 0.0, weight_2 / new_weight) + return ( + mean_1 + delta * w2_over_w, + m2_1 + m2_2 + delta * delta * weight_1 * w2_over_w, + new_weight, + ) + + +@triton.jit +def welford(mean, m2, weight, dim): + return tl.reduce((mean, m2, weight), dim, welford_combine) + + +@triton.jit +def device_assert_then(cond, msg, r): + tl.device_assert(cond, msg) + return r + + +@triton.jit +def randint64(seed, offset, low, high): + r0, r1, r2, r3 = tl.randint4x(seed, offset) + r0 = r0.to(tl.uint64) + r1 = r1.to(tl.uint64) + result = r0 | (r1 << 32) + size = high - low + result = result % size.to(tl.uint64) + result = result.to(tl.int64) + low + return result + + +@triton.jit +def _any_combine(a, b): + return a | b + + +@triton.jit +def any(a, dim): + return tl.reduce(a, dim, _any_combine) + + +@triton.jit +def bucketize_binary_search( + values, # 1D tensor + offsets_ptr, + indexing_dtype, + right, # bool: if true, use intervals closed on the left; see [Note: Inductor bucketize op] + OFFSETS_SIZE: int, + BLOCK_SHAPE, # tuple/list of block shape +): + """ + See [Note: Inductor bucketize op] + """ + + low = tl.zeros(BLOCK_SHAPE, dtype=indexing_dtype) + high = tl.full(BLOCK_SHAPE, OFFSETS_SIZE, dtype=indexing_dtype) + + full_range = OFFSETS_SIZE + 1 + while full_range > 1: + mid = (high + low) // 2 + mask = mid < OFFSETS_SIZE + bucket_upper_bound = tl.load(offsets_ptr + mid, mask=mask) + if right: + is_above = values >= bucket_upper_bound + else: + is_above = values > bucket_upper_bound + + low = tl.where(is_above & mask, mid + 1, low) + high = tl.where(is_above, high, mid) + + full_range = (full_range + 1) // 2 + + return low diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/triton_heuristics.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/triton_heuristics.py new file mode 100644 index 0000000000000000000000000000000000000000..3e14c7522634da603f3f8e6795c6f381caeede80 --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/triton_heuristics.py @@ -0,0 +1,1046 @@ +import builtins +import copy +import functools +import hashlib +import inspect +import json +import logging +import operator +import os +import os.path +import re +import threading +from enum import auto, Enum +from typing import Any, Callable, List, Optional, Set, Tuple + +import torch + +import torch.autograd.profiler as autograd_profiler +from torch._dynamo.utils import dynamo_timed + +from . import config +from .codecache import cache_dir, CudaKernelParamCache +from .coordinate_descent_tuner import CoordescTuner + +from .ir import ReductionHint, TileHint +from .utils import ( + ceildiv, + conditional_product, + create_bandwidth_info_str, + do_bench, + get_num_bytes, + has_triton, + next_power_of_2, + triton_config_to_hashable, +) + + +log = logging.getLogger(__name__) + +if has_triton(): + import triton + from triton import Config + from triton.runtime.jit import get_cuda_stream, KernelInterface +else: + Config = object + get_cuda_stream = None + KernelInterface = object + triton = None + + +class HeuristicType(Enum): + POINTWISE = auto() + REDUCTION = auto() + PERSISTENT_REDUCTION = auto() + TEMPLATE = auto() + + +class AutotuneHint(Enum): + ELEMENTS_PER_WARP_32 = 0 + + # Triton codegen tries to codegen set of AutotuneHints. + # Enum.__repr__ looks like """ + # which isn't valid python. + # Enum.__str__ will just return "AutotuneHint.ELEMENTS_PER_WARP_32". + __repr__ = Enum.__str__ + + +def autotune_hints_to_configs( + hints: Set[AutotuneHint], size_hints, block_size +) -> List[Config]: + """ + AutotuneHints can be attached to the metadata of triton kernels for providing + suggestions about what to try for autotuning. One reason to do this is if there are + some configs that are only useful in specific scenarios, in which case we can avoid + wasting compile time on autotuning unless we know we are in one of those scenarios. + + Based on those hints, this function will generate a list of additional autotuning + configs to try. + """ + xyz_options: Tuple[Tuple[Any, ...], ...] + configs = [] + + for hint in hints: + if hint == AutotuneHint.ELEMENTS_PER_WARP_32: + if len(size_hints) == 1: + xyz_options = ((block_size // 4,),) + elif len(size_hints) == 2: + xyz_options = ((block_size // 4, 1), (1, block_size // 4)) + elif len(size_hints) == 3: + xyz_options = ( + (block_size // 4, 1, 1), + (1, block_size // 4, 1), + (1, 1, block_size // 4), + ) + for xyz in xyz_options: + configs.append( + triton_config( # type: ignore[misc] + size_hints, + *xyz, + num_elements_per_warp=32, + ) + ) + + return configs + + +def disable_pointwise_autotuning(): + # Autotuning can give different benchmarking results from run to run, and + # therefore we disable autotuning when use_deterministic flag is on. + if torch.are_deterministic_algorithms_enabled(): + return True + return not config.triton.autotune_pointwise + + +class CachingAutotuner(KernelInterface): + """ + Simplified version of Triton autotuner that has no invalidation + key and caches the best config to disk to improve cold start times. + Unlike the main triton Autotuner, this version can precompile all + configs, and does not rely on the Triton JIT. + """ + + def __init__( + self, + fn, + meta, + configs, + save_cache_hook, + mutated_arg_names, + heuristic_type, + size_hints=None, + ): + super().__init__() + self.fn = fn + self.meta = meta + self.save_cache_hook = save_cache_hook + self.mutated_arg_names = mutated_arg_names + self.configs = configs + self.heuristic_type = heuristic_type + + if log.isEnabledFor(logging.DEBUG): + log.debug("CachingAutotuner gets %d configs", len(self.configs)) + for c in self.configs: + log.debug(c) + + self.launchers = [] + self.lock = threading.Lock() + if os.getenv("TRITON_CACHE_DIR") is None: + os.environ["TRITON_CACHE_DIR"] = os.path.join( + cache_dir(), + "triton", + str(self.meta.get("device", 0)), + ) + + self.coordesc_tuner = CoordescTuner( + is_mm=False, name=self.fn.__name__, size_hints=size_hints + ) + + # pre-create the profiler context manager to reduce latency + self.record_function_ctx = torch._C._profiler._RecordFunctionFast( + self.meta.get("kernel_name", "triton kernel") + ) + + def precompile(self, warm_cache_only_with_cc=None): + with self.lock: + if self.launchers: + return + self.launchers = [ + self._precompile_config(c, warm_cache_only_with_cc) + for c in self.configs + ] + self.configs = None + + def _precompile_config(self, cfg: Config, warm_cache_only_with_cc: Optional[int]): + """Ahead of time compile a given autotuner config.""" + compile_meta = copy.deepcopy(self.meta) + for k, v in cfg.kwargs.items(): + compile_meta["constants"][self.fn.arg_names.index(k)] = v + compile_meta["num_warps"] = cfg.num_warps + compile_meta["num_stages"] = cfg.num_stages + compile_meta["debug"] = ( + config.triton.assert_indirect_indexing and torch.version.hip is None + ) + + # Setting device_type="hip" required on ROCm to pass down to triton + compile_meta["device_type"] = "cuda" if torch.version.hip is None else "hip" + + if warm_cache_only_with_cc: + triton.compile( + self.fn, + warm_cache_only=True, + cc=warm_cache_only_with_cc, + **compile_meta, + ) + return + + # load binary to the correct device + with torch.cuda.device(compile_meta["device"]): + # need to initialize context + torch.cuda.synchronize(torch.cuda.current_device()) + binary = triton.compile( + self.fn, + **compile_meta, + ) + binary._init_handles() + + call_args = [ + arg + for i, arg in enumerate(self.fn.arg_names) + if i not in self.fn.constexprs + ] + def_args = list(self.fn.arg_names) + while def_args and def_args[-1] in cfg.kwargs: + def_args.pop() + + scope = { + "grid_meta": cfg.kwargs, + "bin": binary, + "torch": torch, + "set_device": torch.cuda.set_device, + "current_device": torch.cuda.current_device, + } + exec( + f""" + def launcher({', '.join(def_args)}, grid, stream): + if callable(grid): + grid_0, grid_1, grid_2 = grid(grid_meta) + else: + grid_0, grid_1, grid_2 = grid + + if hasattr(bin, "num_ctas"): + bin.c_wrapper(grid_0, grid_1, grid_2, bin.num_warps, + bin.num_ctas, *bin.clusterDims, bin.shared, + stream, bin.cu_function, None, None, None, + {', '.join(call_args)}) + else: + bin.c_wrapper(grid_0, grid_1, grid_2, bin.num_warps, bin.shared, + stream, bin.cu_function, None, None, None, + {', '.join(call_args)}) + """.lstrip(), + scope, + ) + + launcher = scope["launcher"] + launcher.config = cfg + launcher.n_regs = getattr(binary, "n_regs", None) + launcher.n_spills = getattr(binary, "n_spills", None) + launcher.shared = getattr(binary, "shared", None) + launcher.store_cubin = config.triton.store_cubin + # store this global varible to avoid the high overhead of reading it when calling run + if launcher.store_cubin: + launcher.fn = self.fn + launcher.bin = binary + + return launcher + + def bench(self, launcher, *args, grid): + """Measure the performance of a given launcher""" + if launcher.n_spills > config.triton.spill_threshold: + log.debug( + "Skip config %s because of register spilling: %d", + launcher.config, + launcher.n_spills, + ) + return float("inf") + + stream = get_cuda_stream(torch.cuda.current_device()) + + def kernel_call(): + if launcher.config.pre_hook is not None: + launcher.config.pre_hook( + {**dict(zip(self.arg_names, args)), **launcher.config.kwargs} + ) + + cloned_args = self.clone_args(*args) + launcher( + *cloned_args, + grid=grid, + stream=stream, + ) + + return do_bench(kernel_call, rep=40, fast_flush=True) + + def clone_args(self, *args): + from .compile_fx import clone_preserve_strides + + # clone inplace buffers to avoid autotune contaminating them if + # the kernel does in-place stores. avoid cloning other buffers because + # it leads to increase memory use + cloned_args = [] + for i, arg in enumerate(args): + if self.fn.arg_names[i] in self.mutated_arg_names: + assert isinstance(arg, torch.Tensor) + cloned_args.append(clone_preserve_strides(arg)) + else: + cloned_args.append(arg) + + return cloned_args + + @dynamo_timed + def benchmark_all_configs(self, *args, **kwargs): + timings = { + launcher: self.bench(launcher, *args, **kwargs) + for launcher in self.launchers + } + + for k, v in timings.items(): + self.coordesc_tuner.cache_benchmark_result(k.config, v) + + if log.isEnabledFor(logging.DEBUG): + log.debug("Benchmark all input configs get:") + for k, v in timings.items(): + log.debug( + "%s: %f, nreg %d, nspill %d, #shared-mem %d", + k.config, + v, + k.n_regs, + k.n_spills, + k.shared, + ) + + return timings + + def autotune_to_one_config(self, *args, **kwargs): + """Do the actual autotuning""" + timings = self.benchmark_all_configs(*args, **kwargs) + self.launchers = [builtins.min(timings, key=timings.get)] + if self.save_cache_hook: + self.save_cache_hook(self.launchers[0].config) + + def save_cuda_kernel(self, grid, stream, launcher): + if callable(grid): + grid_x, grid_y, grid_z = grid(launcher.config.kwargs) + else: + grid_x, grid_y, grid_z = grid + + key = launcher.fn.fn.__qualname__ # unique kernel name + params = { + "mangled_name": launcher.bin.metadata["name"], + "grid_x": grid_x, + "grid_y": grid_y, + "grid_z": grid_z, + "num_warps": launcher.bin.num_warps, + "shared_mem": launcher.bin.shared, + "stream": stream, + } + CudaKernelParamCache.set(key, params, launcher.bin.asm["cubin"]) + + def coordinate_descent_tuning(self, launcher, *args, **kwargs): + """ + Coordinate descent tuning can be run with or without max-autotune. + + The only difference between these two is the starting config for coordinate_descent tuning. + E.g., assuming regular autotune only get one config C1; while max-autotune get 4 configs C1, C2, C3, C4 + and max-autotune figure out C3 is the best. + + Then if coordinate descnt tuning is run with max-autotune disabled, it will start from C1; + while if coordinate descent tuning is run with max-autotune enabled, it will start from C3. + """ + if self.heuristic_type == HeuristicType.TEMPLATE: + # skip triton template + return launcher + + cloned_args = self.clone_args(*args) + config2launcher = {launcher.config: launcher} + + def benchmark_one_config(config): + with self.lock: + launcher = self._precompile_config(config, None) + config2launcher[config] = launcher + + out = self.bench(launcher, *cloned_args, **kwargs) + log.debug( + "COORDESC: %s: %f, nreg %d, nspill %d, #shared-mem %d", + launcher.config, + out, + launcher.n_regs, + launcher.n_spills, + launcher.shared, + ) + return out + + assert not ( + self.heuristic_type == HeuristicType.PERSISTENT_REDUCTION + and "RBLOCK" in launcher.config.kwargs + ), "Coordinate descent tuner relies on the assumption that persistent reduction's triton config does not have RBLOCK" + best_config = self.coordesc_tuner.autotune( + benchmark_one_config, launcher.config, None + ) + best_config.found_by_coordesc = True + + if self.save_cache_hook: + self.save_cache_hook(best_config, found_by_coordesc=True) + return config2launcher.get(best_config) + + def run(self, *args, grid, stream): + if len(self.launchers) != 1: + if len(self.launchers) == 0: + self.precompile() + if len(self.launchers) > 1: + self.autotune_to_one_config(*args, grid=grid) + + if ( + not getattr(self.launchers[0].config, "found_by_coordesc", False) + and config.coordinate_descent_tuning + ): + self.launchers = [ + self.coordinate_descent_tuning(self.launchers[0], *args, grid=grid) + ] + + (launcher,) = self.launchers + if launcher.store_cubin: + self.save_cuda_kernel(grid, stream, launcher) + + if launcher.config.pre_hook is not None: + launcher.config.pre_hook( + {**dict(zip(self.arg_names, args)), **launcher.config.kwargs} + ) + + # guard the record_function_ctx and only call it if profiling is currently + # in progress, to reduce latency when profiler is not turned on. Note that + # the "if" statement (instead of, say, a contextlib.nullcontext) is intentional; + # it is faster than entering and exiting a context manager, even if the context + # manager is a nullcontext. + if autograd_profiler._is_profiler_enabled: + with self.record_function_ctx: + return launcher( + *args, + grid=grid, + stream=stream, + ) + else: + return launcher( + *args, + grid=grid, + stream=stream, + ) + + +def _find_names(obj): + import gc + import inspect + + frame = inspect.currentframe() + for frame in iter(lambda: frame.f_back, None): # type: ignore[union-attr] + frame.f_locals + obj_names = [] + for referrer in gc.get_referrers(obj): + if isinstance(referrer, dict): + for k, v in referrer.items(): + if v is obj: + obj_names.append(k) + return obj_names + + +collected_calls: List[Any] = [] + + +def start_graph(): + collected_calls.clear() + + +def end_graph(): + if len(collected_calls) == 0: + return + overall_time = sum(call[0] for call in collected_calls) + overall_gb = sum(call[1] for call in collected_calls) + cur_file = inspect.stack()[1].filename + print(f"SUMMARY ({cur_file})") + print( + f"{overall_time:.2f}ms \t {overall_gb:.2f} GB\t {overall_gb/(overall_time/1e3):.2f}GB/s" + ) + print() + + +class DebugAutotuner(CachingAutotuner): + def __init__(self, *args, regex_filter="", **kwargs): + self.regex_filter = regex_filter + super().__init__(*args, **kwargs) + self.cached = None + + def run(self, *args, grid, stream): + possible_names = _find_names(self) + kernel_name = f"{max(possible_names, key=lambda x: len(x))}" + if not re.match(self.regex_filter, kernel_name): + return + super().run(*args, grid=grid, stream=stream) + (launcher,) = self.launchers + + if self.cached is None: + ms = self.bench(launcher, *args, grid=grid) + num_in_out_ptrs = len( + [ + arg_name + for arg_name in self.fn.arg_names + if arg_name.startswith("in_out_ptr") + ] + ) + num_gb = get_num_bytes(*args, num_in_out_args=num_in_out_ptrs) / 1e9 + gb_per_s = num_gb / (ms / 1e3) + self.cached = (ms, num_gb, gb_per_s, kernel_name) + else: + ms, num_gb, gb_per_s, kernel_name = self.cached + collected_calls.append((ms, num_gb, gb_per_s, kernel_name)) + print( + create_bandwidth_info_str(ms, num_gb, gb_per_s, suffix=f" \t {kernel_name}") + ) + + +def hash_configs(configs: List[Config]): + """ + Hash used to check for changes in configurations + """ + hasher = hashlib.sha256() + for cfg in configs: + hasher.update( + f"{sorted(cfg.kwargs.items())} {cfg.num_warps} {cfg.num_stages}\n".encode() + ) + return hasher.hexdigest() + + +def load_cached_autotuning( + cache_filename: str, configs_hash: str, configs: List[Config] +): + """ + Read a cached autotuning result from disk + """ + if not os.path.exists(cache_filename): + return None + + with open(cache_filename) as fd: + best_config = json.loads(fd.read()) + if best_config.pop("configs_hash", None) != configs_hash: + return None + + if config.coordinate_descent_tuning and best_config.pop("found_by_coordesc", False): + num_warps = best_config.pop("num_warps") + num_stages = best_config.pop("num_stages") + triton_config = Config(best_config, num_warps=num_warps, num_stages=num_stages) + triton_config.found_by_coordesc = True + return triton_config + + matching_configs = [ + cfg + for cfg in configs + if all(val == best_config.get(key) for key, val in cfg.kwargs.items()) + and cfg.num_warps == best_config.get("num_warps") + and cfg.num_stages == best_config.get("num_stages") + ] + if len(matching_configs) != 1: + return None + + return matching_configs[0] + + +def cached_autotune( + size_hints: Optional[List[int]], + configs: List[Config], + meta, + heuristic_type, + filename=None, +): + """ + A copy of triton.autotune that calls our subclass. Our subclass + has additional debugging, error handling, and on-disk caching. + """ + configs = unique_configs(configs) + assert len(configs) == 1 or filename + save_cache_hook: Optional[Callable[[Any, Any], Any]] + + # on disk caching logic + if filename is not None and (len(configs) > 1 or config.coordinate_descent_tuning): + cache_filename = os.path.splitext(filename)[0] + ".best_config" + configs_hash = hash_configs(configs) + best_config = load_cached_autotuning(cache_filename, configs_hash, configs) + if best_config: + configs = [best_config] + + def save_cache_hook(cfg, found_by_coordesc=False): + with open(cache_filename, "w") as fd: + fd.write( + json.dumps( + { + **cfg.kwargs, + "num_warps": cfg.num_warps, + "num_stages": cfg.num_stages, + "configs_hash": configs_hash, + "found_by_coordesc": found_by_coordesc, + } + ) + ) + if log.isEnabledFor(logging.DEBUG): + type_str = "coordesc" if found_by_coordesc else "heuristic" + log.debug("Save %s tuning result to %s", type_str, cache_filename) + + else: + save_cache_hook = None + + mutated_arg_names = meta.pop("mutated_arg_names", ()) + + def decorator(fn): + # Remove XBLOCK from config if it's not a function argument. + # This way, coordinate descent tuning will not try to tune it. + # + # Context: When TritonKernel.no_x_dim is True, we hardcode XBLOCK to 1. + import inspect + + if "XBLOCK" not in inspect.signature(fn.fn).parameters: + for tconfig in configs: + if "XBLOCK" in tconfig.kwargs: + assert tconfig.kwargs["XBLOCK"] == 1 + tconfig.kwargs.pop("XBLOCK") + + if config.profile_bandwidth: + return DebugAutotuner( + fn, + meta=meta, + regex_filter=config.profile_bandwidth_regex, + configs=configs, + save_cache_hook=save_cache_hook, + mutated_arg_names=mutated_arg_names, + heuristic_type=heuristic_type, + size_hints=size_hints, + ) + return CachingAutotuner( + fn, + meta=meta, + configs=configs, + save_cache_hook=save_cache_hook, + mutated_arg_names=mutated_arg_names, + heuristic_type=heuristic_type, + size_hints=size_hints, + ) + + return decorator + + +def unique_configs(configs: List[Config]): + """Remove duplicate configurations""" + seen = set() + pruned_configs = [] + + for cfg in configs: + key = triton_config_to_hashable(cfg) + if key not in seen: + seen.add(key) + pruned_configs.append(cfg) + return pruned_configs + + +def check_config(cfg, *, xnumel=None, ynumel=None, znumel=None): + for numel, label in zip((xnumel, ynumel, znumel), "XYZ"): + if numel is None: + continue + block = cfg[f"{label}BLOCK"] + if numel == 1: + assert block == 1, ( + f"TritonKernel.indexing assumes numel == 1 => BLOCK == 1" + f" but {label.lower()}numel=={numel} and {label}BLOCK={block} (cfg={cfg})." + ) + max_block = config.triton.max_block[label] + max_block_str = f'config.triton.max_block["{label}"]' + assert max_block % block == 0, ( + f"TritonKernel.indexing assumes {label}BLOCK divides {max_block_str}" + f" but {label}BLOCK={block} and {max_block_str}={max_block} (cfg={cfg})." + ) + + +def triton_config( + size_hints, x, y=None, z=None, num_stages=1, num_elements_per_warp=256 +) -> Config: + """ + Construct a pointwise triton config with some adjustment heuristics + based on size_hints. Size_hints is a tuple of numels in each tile + dimension and will be rounded up to the nearest power of 2. + + num_elements_per_warp is a suggestion for controlling how many warps + the triton config should contain. e.g.: if x=16, y=8, z=4 then + num_elements = 16*8*4 = 512. Then if we set num_elements_per_warp=128, + we'll launch 512 (elem) / 128 (elem/warp) = 4 warps. Note that it's + just a suggestion, and sometimes other adjustment heuristics will + override the num_elements_per_warp. + """ + # Ideally we want to read this from some device config + + # for a 2d size_hints [a, b], a should be mapped to YBLOCK rather than XBLOCK + size_hints = list(reversed(size_hints)) + + maxGridSize = [2147483647, 65535, 65535] + + target = conditional_product(x, y, z) + if conditional_product(*size_hints) < target: + target //= 8 + + # shrink sizes to size hints + x = min(x, size_hints[0]) + if y: + y = min(y, size_hints[1]) + if z: + z = min(z, size_hints[2]) + + # if we are below original block size, scale up where we can; + # or if the calculated grid size is larger than the limit, we bump up the corresponding dimension + while x < min(size_hints[0], config.triton.max_block["X"]) and ( + x * maxGridSize[0] < size_hints[0] or conditional_product(x, y, z) < target + ): + x *= 2 + while ( + y + and y < min(size_hints[1], config.triton.max_block["Y"]) + and ( + y * maxGridSize[1] < size_hints[1] or conditional_product(x, y, z) < target + ) + ): + y *= 2 + while ( + z + and z < min(size_hints[2], config.triton.max_block["Z"]) + and ( + z * maxGridSize[2] < size_hints[2] or conditional_product(x, y, z) < target + ) + ): + z *= 2 + + cfg = {"XBLOCK": x} + if y: + cfg["YBLOCK"] = y + if z: + cfg["ZBLOCK"] = z + num_warps = next_power_of_2( + min(max(conditional_product(x, y, z) // num_elements_per_warp, 1), 8) + ) + # we are going to arrive at 2 warps only if bs was too small due to + # numel being too small. However to workaround some ptx bugs we still + # want at least 4 warps if there's enough elements per thread + # given that this is a rare situation, don't expect this to affect perf + # in general + # see https://github.com/pytorch/pytorch/pull/97950 + num_warps = max(num_warps, 4) if conditional_product(x, y, z) >= 128 else num_warps + xnumel = size_hints[0] + ynumel = size_hints[1] if y else None + znumel = size_hints[2] if z else None + check_config(cfg, xnumel=xnumel, ynumel=ynumel, znumel=znumel) + return Config(cfg, num_warps=num_warps, num_stages=num_stages) + + +def triton_config_reduction(size_hints, x, r, num_stages=1, num_warps=None) -> Config: + """ + Construct a reduction triton config with some adjustment heuristics + based on size_hints. Size_hints is a tuple of numels in each tile + dimension and will be rounded up to the nearest power of 2. + """ + + target = conditional_product(x, r) + if conditional_product(*size_hints) < target: + target //= 8 + + # shrink sizes to size hints + x = min(x, size_hints[0]) + r = min(r, size_hints[1]) + + # if we are below original block size, scale up where we can + while x < size_hints[0] and conditional_product(x, r) < target: + x *= 2 + while r < size_hints[1] and conditional_product(x, r) < target: + r *= 2 + + cfg = {"XBLOCK": x, "RBLOCK": r} + if num_warps is None: + num_warps = conditional_product(x, r) // 128 + num_warps = next_power_of_2(min(max(num_warps, 2), 8)) + check_config(cfg, xnumel=size_hints[0]) + return Config(cfg, num_warps=num_warps, num_stages=num_stages) + + +def triton_config_tiled_reduction(size_hints, x, y, r, num_stages=1): + """ + Construct a tile reduction triton config with some adjustment + heuristics based on size_hints. Size_hints is a tuple of numels in + each tile dimension and will be rounded up to the nearest power of 2. + """ + + target = conditional_product(x, y, r) + if conditional_product(*size_hints) < target: + target //= 8 + + # shrink sizes to size hints + x = min(x, size_hints[0]) + y = min(y, size_hints[1]) + r = min(r, size_hints[2]) + + # if we are below original block size, scale up where we can + while x < size_hints[0] and conditional_product(x, y, r) < target: + x *= 2 + while r < size_hints[2] and conditional_product(x, y, r) < target: + r *= 2 + while y < size_hints[1] and conditional_product(x, y, r) < target: + y *= 2 + + cfg = {"XBLOCK": x, "YBLOCK": y, "RBLOCK": r} + num_warps = next_power_of_2(min(max(conditional_product(x, y, r) // 256, 1), 8)) + check_config(cfg, xnumel=size_hints[0], ynumel=size_hints[1]) + return Config(cfg, num_warps=num_warps, num_stages=num_stages) + + +def pointwise(size_hints, meta, tile_hint=None, filename=None): + """ + Construct @triton.heuristics() based on size_hints. + """ + numel = functools.reduce(operator.mul, size_hints) + bs = max(256, min(numel // 128, 1024)) + + hinted_configs = autotune_hints_to_configs( + meta.get("autotune_hints", set()), size_hints, bs + ) + + if len(size_hints) == 1: + if disable_pointwise_autotuning() and not ( + config.max_autotune or config.max_autotune_pointwise + ): + return cached_autotune( + size_hints, + [triton_config(size_hints, bs)], + meta=meta, + heuristic_type=HeuristicType.POINTWISE, + filename=filename, + ) + else: + return cached_autotune( + size_hints, + [ + triton_config(size_hints, bs, num_elements_per_warp=256), + triton_config(size_hints, bs // 2, num_elements_per_warp=64), + *hinted_configs, + ], + meta=meta, + heuristic_type=HeuristicType.POINTWISE, + filename=filename, + ) + if len(size_hints) == 2: + if (disable_pointwise_autotuning() or tile_hint == TileHint.SQUARE) and not ( + config.max_autotune or config.max_autotune_pointwise + ): + return cached_autotune( + size_hints, + [triton_config(size_hints, 32, 32)], + meta=meta, + heuristic_type=HeuristicType.POINTWISE, + filename=filename, + ) + return cached_autotune( + size_hints, + [ + triton_config(size_hints, 32, 32), + triton_config(size_hints, 64, 64), # ~8% better for fp16 + triton_config(size_hints, 256, 16), + triton_config(size_hints, 16, 256), + triton_config(size_hints, bs, 1), + triton_config(size_hints, 1, bs), + *hinted_configs, + ], + meta=meta, + filename=filename, + heuristic_type=HeuristicType.POINTWISE, + ) + if len(size_hints) == 3: + if disable_pointwise_autotuning(): + return cached_autotune( + size_hints, + [triton_config(size_hints, 16, 16, 16)], + meta=meta, + heuristic_type=HeuristicType.POINTWISE, + filename=filename, + ) + return cached_autotune( + size_hints, + [ + triton_config(size_hints, 16, 16, 16), + triton_config(size_hints, 64, 8, 8), + triton_config(size_hints, 8, 64, 8), + triton_config(size_hints, 8, 8, 64), + triton_config(size_hints, bs, 1, 1), + triton_config(size_hints, 1, bs, 1), + triton_config(size_hints, 1, 1, bs), + *hinted_configs, + ], + meta=meta, + filename=filename, + heuristic_type=HeuristicType.POINTWISE, + ) + raise NotImplementedError(f"size_hints: {size_hints}") + + +def reduction(size_hints, reduction_hint=False, meta=None, filename=None): + """args to @triton.heuristics()""" + assert meta is not None + rnumel = size_hints[-1] + if len(size_hints) == 2: + contiguous_config = triton_config_reduction( + size_hints, 1, (rnumel if 256 <= rnumel < 2048 else 2048) + ) + outer_config = triton_config_reduction(size_hints, 128, 8) + tiny_config = triton_config_reduction( + size_hints, 2 * (256 // rnumel) if rnumel <= 256 else 1, min(rnumel, 2048) + ) + if config.max_autotune or config.max_autotune_pointwise: + pass # skip all these cases + elif reduction_hint == ReductionHint.INNER: + return cached_autotune( + size_hints, + [contiguous_config], + meta=meta, + heuristic_type=HeuristicType.REDUCTION, + filename=filename, + ) + elif reduction_hint == ReductionHint.OUTER: + return cached_autotune( + size_hints, + [outer_config], + meta=meta, + heuristic_type=HeuristicType.REDUCTION, + filename=filename, + ) + elif reduction_hint == ReductionHint.OUTER_TINY: + return cached_autotune( + size_hints, + [tiny_config], + meta=meta, + heuristic_type=HeuristicType.REDUCTION, + filename=filename, + ) + if disable_pointwise_autotuning(): + return cached_autotune( + size_hints, + [triton_config_reduction(size_hints, 32, 128)], + meta=meta, + heuristic_type=HeuristicType.REDUCTION, + filename=filename, + ) + return cached_autotune( + size_hints, + [ + contiguous_config, + outer_config, + tiny_config, + triton_config_reduction(size_hints, 64, 64), + triton_config_reduction(size_hints, 8, 512), + # halve the XBLOCK/RBLOCK compared to outer_config + # TODO: this may only be beneficial when each iteration of the reduciton + # is quite heavy. E.g. https://gist.github.com/shunting314/189a8ef69f90db9d614a823385147a72 + triton_config_reduction(size_hints, 64, 4, num_warps=8), + ], + meta=meta, + filename=filename, + heuristic_type=HeuristicType.REDUCTION, + ) + raise NotImplementedError(f"size_hints: {size_hints}") + + +def persistent_reduction(size_hints, reduction_hint=False, meta=None, filename=None): + xnumel, rnumel = size_hints + + configs = [ + triton_config_reduction(size_hints, xblock, rnumel) + for xblock in (1, 8, 32, 128) + if rnumel * xblock <= 4096 and xblock <= xnumel + ] + + # TODO(jansel): we should be able to improve these heuristics + if reduction_hint == ReductionHint.INNER and rnumel >= 256: + configs = configs[:1] + elif reduction_hint == ReductionHint.OUTER: + configs = configs[-1:] + elif reduction_hint == ReductionHint.OUTER_TINY: + configs = [ + triton_config_reduction( + size_hints, 2 * (256 // rnumel) if rnumel <= 256 else 1, rnumel + ) + ] + for c in configs: + # we don't need RBLOCK for persistent reduction + c.kwargs.pop("RBLOCK") + + if disable_pointwise_autotuning(): + configs = configs[:1] + + return cached_autotune( + size_hints, + configs, + meta=meta, + filename=filename, + heuristic_type=HeuristicType.PERSISTENT_REDUCTION, + ) + + +def template(num_stages, num_warps, meta, filename=None): + """ + Compile a triton template + """ + return cached_autotune( + None, + [triton.Config({}, num_stages=num_stages, num_warps=num_warps)], + meta=meta, + heuristic_type=HeuristicType.TEMPLATE, + filename=filename, + ) + + +def foreach(meta, num_warps, filename=None): + """ + Compile a triton foreach kernel + """ + return cached_autotune( + None, + [triton.Config({}, num_stages=1, num_warps=num_warps)], + meta=meta, + heuristic_type=HeuristicType.TEMPLATE, + filename=filename, + ) + + +def grid(*numels): + """Helper function to compute triton grids""" + + if len(numels) == 1: + xnumel, ynumel, znumel = numels[0], None, None + elif len(numels) == 2: + xnumel, ynumel, znumel = numels[1], numels[0], None + elif len(numels) == 3: + xnumel, ynumel, znumel = numels[2], numels[1], numels[0] + else: + raise AssertionError(f"invalid size for numels {len(numels)}") + + def get_grid_dim(numel, block): + if numel is None: + return 1 + return ceildiv(numel, block) + + def grid_fn(meta): + return ( + get_grid_dim(xnumel, meta.get("XBLOCK", 1)), + get_grid_dim(ynumel, meta.get("YBLOCK", None)), + get_grid_dim(znumel, meta.get("ZBLOCK", None)), + ) + + return grid_fn diff --git a/llava_next/lib/python3.10/site-packages/torch/_inductor/virtualized.py b/llava_next/lib/python3.10/site-packages/torch/_inductor/virtualized.py new file mode 100644 index 0000000000000000000000000000000000000000..502c8903ac58d7335b47e4514caba956040a915e --- /dev/null +++ b/llava_next/lib/python3.10/site-packages/torch/_inductor/virtualized.py @@ -0,0 +1,310 @@ +import itertools +from contextlib import contextmanager +from itertools import chain +from threading import local +from typing import Any +from unittest.mock import patch + +import sympy + +from torch._inductor.utils import IndentedBuffer + +from torch.fx.graph import inplace_methods, magic_methods + +from .utils import reduction_num_outputs, sympy_str, sympy_symbol + +threadlocal = local() + + +class Virtualized: + """ + A global variable that redirects via thread local variable + + This allows us to swap in different op implementations in codegen. + """ + + def __init__(self, vname, default): + self._key = f"__torchinductor_{vname}" + self._default = default + + def _set_handler(self, value): + prior = self._get_handler() + setattr(threadlocal, self._key, value) + + @contextmanager + def ctx(): + try: + yield + finally: + self._set_handler(prior) + + return ctx() + + def _get_handler(self): + try: + return getattr(threadlocal, self._key) + except AttributeError: + return self._default() + + def __getattr__(self, name): + return getattr(self._get_handler(), name) + + +class NullHandler: + pass + + +def _arg_str(a): + if isinstance(a, sympy.Expr): + return sympy_str(a) + return str(a) + + +class MockHandler: + def __getattr__(self, name): + if name == "name": + return "MockHandler" + + def inner(*args, **kwargs): + fargs = [_arg_str(a) for a in args] + fargs.extend(f"{k}={v}" for k, v in kwargs.items()) + return f"ops.{name}({', '.join(fargs)})" + + return inner + + @staticmethod + def masked(mask, body, other): + return f"ops.masked({mask}, {body()}, {other})" + + @staticmethod + def indirect_indexing(index_var, size, check=True): + return sympy_symbol(f"({str(index_var)})") + + @classmethod + def _init_cls(cls): + def make_handler(format_string): + @staticmethod # type: ignore[misc] + def inner(*args): + return format_string.format(*args) + + return inner + + for name, format_string in chain( + magic_methods.items(), inplace_methods.items() + ): + setattr(cls, name, make_handler(format_string)) + + +class KernelFormatterHandler: + def __init__(self, parent_handler): + self.parent_handler = parent_handler + self.output = IndentedBuffer(1) + self.var_counter = itertools.count() + + @staticmethod + def ir_to_string(ir_fn, index, rindex=None): + from .ir import FlexibleLayout + + args = [index, rindex] if rindex is not None else [index] + names = ["index", "rindex"] if rindex is not None else ["index"] + formatter = KernelFormatterHandler(MockHandler()) + + with formatter.output.indent(-1): + formatter.output.writeline(f"def inner_fn({', '.join(names)}):") + for name, arg in zip(names, args): + if arg: + lhs = ", ".join( + [ + str("_" if isinstance(v, (int, sympy.Integer)) else v) + for v in arg + ] + ) + formatter.output.writeline(f"{lhs} = {name}") + + with V.set_ops_handler(formatter), patch.object( # type: ignore[call-arg] + FlexibleLayout, "allow_indexing", True + ): + result = ir_fn(*args) + return formatter.getvalue(result) + + def __getattr__(self, name): + def inner(*args, **kwargs): + line = getattr(self.parent_handler, name)(*args, **kwargs) + if name == "indirect_indexing": + return line + # replace line with a new variable name + varname = f"tmp{next(self.var_counter)}" + self.output.writeline(f"{varname} = {line}") + return varname + + return inner + + def reduction(self, dtype, src_dtype, reduction_type, value): + line = self.parent_handler.reduction(dtype, src_dtype, reduction_type, value) + num_values = reduction_num_outputs(reduction_type) + varnames = [f"tmp{next(self.var_counter)}" for _ in range(num_values)] + self.output.writeline(f"{','.join(varnames)} = {line}") + return tuple(varnames) if num_values > 1 else varnames[0] + + def getvalue(self, result): + self.output.writeline(f"return {result}") + return self.output.getvalue() + + +class WrapperHandler: + def __init__(self, inner): + self._inner = inner + + def __getattr__(self, item): + return getattr(self._inner, item) + + +MockHandler._init_cls() + +_ops = Virtualized("ops", MockHandler) +_graph = Virtualized("graph", NullHandler) +_real_inputs = Virtualized("real_inputs", NullHandler) +_fake_mode = Virtualized("fake_mode", NullHandler) +_kernel = Virtualized("kernel", NullHandler) +_debug = Virtualized("debug", NullHandler) +_interpreter = Virtualized("interpreter", NullHandler) + + +class OpsValue: + """The return type of most ops calls. + + This exists so we can overload magic methods, and write mathematical + expressions much more fluently. So instead of + + ops.add(ops.mul(ops.mul(ops.sub(ops.mul(_Ap2, x), _Ap3), x), x), _1) + + we can write + + (_Ap2 * x - _Ap3) * x * x + _1 + + """ + + value: Any + + def __init__(self, value): + self.value = value + + def __str__(self): + return str(self.value) + + def __repr__(self): + return f"OpsValue({self.value!r})" + + def __add__(self, other): + return ops.add(self, other) + + def __mul__(self, other): + return ops.mul(self, other) + + def __sub__(self, other): + return ops.sub(self, other) + + def __neg__(self): + return ops.neg(self) + + def __truediv__(self, other): + return ops.truediv(self, other) + + def __floordiv__(self, other): + return ops.floordiv(self, other) + + def __mod__(self, other): + return ops.mod(self, other) + + def __pow__(self, other): + return ops.pow(self, other) + + +class OpsWrapper: + """This wraps any returned IR values into an `OpsValue` instance, so that we + can overload the magic methods for writing mathematical expressions fluently. + """ + + def __getattr__(self, name): + def inner(*args, **kwargs): + new_args = [OpsWrapper._unwrap(a) for a in args] + new_kwargs = {k: OpsWrapper._unwrap(v) for k, v in kwargs.items()} + return OpsWrapper._wrap(getattr(_ops, name)(*new_args, **new_kwargs)) + + return inner + + @staticmethod + def _unwrap(x): + if isinstance(x, (list, tuple)): + return tuple(OpsWrapper._unwrap(v) for v in x) + if isinstance(x, OpsValue): + return x.value + return x + + @staticmethod + def _wrap(x): + if isinstance(x, (list, tuple)): + return tuple(OpsValue(v) for v in x) + return OpsValue(x) + + @staticmethod + def indirect_indexing(index, size, check=True): + # Returns a sympy value, not IR value + index = OpsWrapper._unwrap(index) + return _ops.indirect_indexing(index, size, check) + + +ops = OpsWrapper() + + +class _V: + MockHandler = MockHandler + KernelFormatterHandler = KernelFormatterHandler + WrapperHandler = WrapperHandler + + set_ops_handler = _ops._set_handler + get_ops_handler = _ops._get_handler + set_graph_handler = _graph._set_handler + set_real_inputs = _real_inputs._set_handler + get_real_inputs = _real_inputs._get_handler + set_fake_mode = _fake_mode._set_handler + get_fake_mode = _fake_mode._get_handler + set_kernel_handler = _kernel._set_handler + set_debug_handler = _debug._set_handler + set_interpreter_handler = _interpreter._set_handler + + @property + def ops(self) -> MockHandler: # type: ignore[valid-type] + """The operator handler specific to the current codegen task""" + return _ops._get_handler() + + @property + def graph(self): + """The graph currently being generated""" + return _graph._get_handler() + + @property + def real_inputs(self): + """non-fake example inputs""" + return _real_inputs._get_handler() + + @property + def fake_mode(self): + """The graph currently being generated""" + return _fake_mode._get_handler() + + @property + def kernel(self): + """The kernel currently being generated""" + return _kernel._get_handler() + + @property + def debug(self): + return _debug._get_handler() + + @property + def interpreter(self): + return _interpreter._get_handler() + + +V = _V() diff --git a/vlmpy310/lib/python3.10/site-packages/pyglet/gl/__pycache__/gl.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/pyglet/gl/__pycache__/gl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9f491af5beae2a4234b5000aaedc6413fbd821a --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/pyglet/gl/__pycache__/gl.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a88fc0af7a9eb460244b9ab24220a69f994edaa733ca8d75f6a023b41f3201c +size 118683 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/future/__init__.py b/vlmpy310/lib/python3.10/site-packages/skimage/future/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..de3ab448b046e1d1c656687633c095c18e5dd9a8 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/future/__init__.py @@ -0,0 +1,13 @@ +"""Functionality with an experimental API. + +.. warning:: + Although you can count on the functions in this package being + around in the future, the API may change with any version update + **and will not follow the skimage two-version deprecation path**. + Therefore, use the functions herein with care, and do not use them + in production code that will depend on updated skimage versions. +""" + +import lazy_loader as _lazy + +__getattr__, __dir__, __all__ = _lazy.attach_stub(__name__, __file__) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/future/manual_segmentation.py b/vlmpy310/lib/python3.10/site-packages/skimage/future/manual_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..8223393cef6322e40f815d6dde54ef7a0686ddc5 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/future/manual_segmentation.py @@ -0,0 +1,235 @@ +from functools import reduce +import numpy as np +from ..draw import polygon +from .._shared.version_requirements import require + + +LEFT_CLICK = 1 +RIGHT_CLICK = 3 + + +def _mask_from_vertices(vertices, shape, label): + mask = np.zeros(shape, dtype=int) + pr = [y for x, y in vertices] + pc = [x for x, y in vertices] + rr, cc = polygon(pr, pc, shape) + mask[rr, cc] = label + return mask + + +@require("matplotlib", ">=3.3") +def _draw_polygon(ax, vertices, alpha=0.4): + from matplotlib.patches import Polygon + from matplotlib.collections import PatchCollection + import matplotlib.pyplot as plt + + polygon = Polygon(vertices, closed=True) + p = PatchCollection([polygon], match_original=True, alpha=alpha) + polygon_object = ax.add_collection(p) + plt.draw() + return polygon_object + + +@require("matplotlib", ">=3.3") +def manual_polygon_segmentation(image, alpha=0.4, return_all=False): + """Return a label image based on polygon selections made with the mouse. + + Parameters + ---------- + image : (M, N[, 3]) array + Grayscale or RGB image. + + alpha : float, optional + Transparency value for polygons drawn over the image. + + return_all : bool, optional + If True, an array containing each separate polygon drawn is returned. + (The polygons may overlap.) If False (default), latter polygons + "overwrite" earlier ones where they overlap. + + Returns + ------- + labels : array of int, shape ([Q, ]M, N) + The segmented regions. If mode is `'separate'`, the leading dimension + of the array corresponds to the number of regions that the user drew. + + Notes + ----- + Use left click to select the vertices of the polygon + and right click to confirm the selection once all vertices are selected. + + Examples + -------- + >>> from skimage import data, future + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> camera = data.camera() + >>> mask = future.manual_polygon_segmentation(camera) # doctest: +SKIP + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(mask) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + import matplotlib + import matplotlib.pyplot as plt + + list_of_vertex_lists = [] + polygons_drawn = [] + + temp_list = [] + preview_polygon_drawn = [] + + if image.ndim not in (2, 3): + raise ValueError('Only 2D grayscale or RGB images are supported.') + + fig, ax = plt.subplots() + fig.subplots_adjust(bottom=0.2) + ax.imshow(image, cmap="gray") + ax.set_axis_off() + + def _undo(*args, **kwargs): + if list_of_vertex_lists: + list_of_vertex_lists.pop() + # Remove last polygon from list of polygons... + last_poly = polygons_drawn.pop() + # ... then from the plot + last_poly.remove() + fig.canvas.draw_idle() + + undo_pos = fig.add_axes([0.85, 0.05, 0.075, 0.075]) + undo_button = matplotlib.widgets.Button(undo_pos, '\u27f2') + undo_button.on_clicked(_undo) + + def _extend_polygon(event): + # Do not record click events outside axis or in undo button + if event.inaxes is None or event.inaxes is undo_pos: + return + # Do not record click events when toolbar is active + if ax.get_navigate_mode(): + return + + if event.button == LEFT_CLICK: # Select vertex + temp_list.append([event.xdata, event.ydata]) + # Remove previously drawn preview polygon if any. + if preview_polygon_drawn: + poly = preview_polygon_drawn.pop() + poly.remove() + + # Preview polygon with selected vertices. + polygon = _draw_polygon(ax, temp_list, alpha=(alpha / 1.4)) + preview_polygon_drawn.append(polygon) + + elif event.button == RIGHT_CLICK: # Confirm the selection + if not temp_list: + return + + # Store the vertices of the polygon as shown in preview. + # Redraw polygon and store it in polygons_drawn so that + # `_undo` works correctly. + list_of_vertex_lists.append(temp_list[:]) + polygon_object = _draw_polygon(ax, temp_list, alpha=alpha) + polygons_drawn.append(polygon_object) + + # Empty the temporary variables. + preview_poly = preview_polygon_drawn.pop() + preview_poly.remove() + del temp_list[:] + + plt.draw() + + fig.canvas.mpl_connect('button_press_event', _extend_polygon) + + plt.show(block=True) + + labels = ( + _mask_from_vertices(vertices, image.shape[:2], i) + for i, vertices in enumerate(list_of_vertex_lists, start=1) + ) + if return_all: + return np.stack(labels) + else: + return reduce(np.maximum, labels, np.broadcast_to(0, image.shape[:2])) + + +@require("matplotlib", ">=3.3") +def manual_lasso_segmentation(image, alpha=0.4, return_all=False): + """Return a label image based on freeform selections made with the mouse. + + Parameters + ---------- + image : (M, N[, 3]) array + Grayscale or RGB image. + + alpha : float, optional + Transparency value for polygons drawn over the image. + + return_all : bool, optional + If True, an array containing each separate polygon drawn is returned. + (The polygons may overlap.) If False (default), latter polygons + "overwrite" earlier ones where they overlap. + + Returns + ------- + labels : array of int, shape ([Q, ]M, N) + The segmented regions. If mode is `'separate'`, the leading dimension + of the array corresponds to the number of regions that the user drew. + + Notes + ----- + Press and hold the left mouse button to draw around each object. + + Examples + -------- + >>> from skimage import data, future + >>> import matplotlib.pyplot as plt # doctest: +SKIP + >>> camera = data.camera() + >>> mask = future.manual_lasso_segmentation(camera) # doctest: +SKIP + >>> fig, ax = plt.subplots() # doctest: +SKIP + >>> ax.imshow(mask) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP + """ + import matplotlib + import matplotlib.pyplot as plt + + list_of_vertex_lists = [] + polygons_drawn = [] + + if image.ndim not in (2, 3): + raise ValueError('Only 2D grayscale or RGB images are supported.') + + fig, ax = plt.subplots() + fig.subplots_adjust(bottom=0.2) + ax.imshow(image, cmap="gray") + ax.set_axis_off() + + def _undo(*args, **kwargs): + if list_of_vertex_lists: + list_of_vertex_lists.pop() + # Remove last polygon from list of polygons... + last_poly = polygons_drawn.pop() + # ... then from the plot + last_poly.remove() + fig.canvas.draw_idle() + + undo_pos = fig.add_axes([0.85, 0.05, 0.075, 0.075]) + undo_button = matplotlib.widgets.Button(undo_pos, '\u27f2') + undo_button.on_clicked(_undo) + + def _on_lasso_selection(vertices): + if len(vertices) < 3: + return + list_of_vertex_lists.append(vertices) + polygon_object = _draw_polygon(ax, vertices, alpha=alpha) + polygons_drawn.append(polygon_object) + plt.draw() + + matplotlib.widgets.LassoSelector(ax, _on_lasso_selection) + + plt.show(block=True) + + labels = ( + _mask_from_vertices(vertices, image.shape[:2], i) + for i, vertices in enumerate(list_of_vertex_lists, start=1) + ) + if return_all: + return np.stack(labels) + else: + return reduce(np.maximum, labels, np.broadcast_to(0, image.shape[:2])) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/future/trainable_segmentation.py b/vlmpy310/lib/python3.10/site-packages/skimage/future/trainable_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5d7df6e16409a4b65f69e1090c71f2165cf0e9 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/future/trainable_segmentation.py @@ -0,0 +1,164 @@ +from skimage.feature import multiscale_basic_features + +try: + from sklearn.exceptions import NotFittedError + from sklearn.ensemble import RandomForestClassifier + + has_sklearn = True +except ImportError: + has_sklearn = False + + class NotFittedError(Exception): + pass + + +class TrainableSegmenter: + """Estimator for classifying pixels. + + Parameters + ---------- + clf : classifier object, optional + classifier object, exposing a ``fit`` and a ``predict`` method as in + scikit-learn's API, for example an instance of + ``RandomForestClassifier`` or ``LogisticRegression`` classifier. + features_func : function, optional + function computing features on all pixels of the image, to be passed + to the classifier. The output should be of shape + ``(m_features, *labels.shape)``. If None, + :func:`skimage.feature.multiscale_basic_features` is used. + + Methods + ------- + compute_features + fit + predict + """ + + def __init__(self, clf=None, features_func=None): + if clf is None: + if has_sklearn: + self.clf = RandomForestClassifier(n_estimators=100, n_jobs=-1) + else: + raise ImportError( + "Please install scikit-learn or pass a classifier instance" + "to TrainableSegmenter." + ) + else: + self.clf = clf + self.features_func = features_func + + def compute_features(self, image): + if self.features_func is None: + self.features_func = multiscale_basic_features + self.features = self.features_func(image) + + def fit(self, image, labels): + """Train classifier using partially labeled (annotated) image. + + Parameters + ---------- + image : ndarray + Input image, which can be grayscale or multichannel, and must have a + number of dimensions compatible with ``self.features_func``. + labels : ndarray of ints + Labeled array of shape compatible with ``image`` (same shape for a + single-channel image). Labels >= 1 correspond to the training set and + label 0 to unlabeled pixels to be segmented. + """ + self.compute_features(image) + fit_segmenter(labels, self.features, self.clf) + + def predict(self, image): + """Segment new image using trained internal classifier. + + Parameters + ---------- + image : ndarray + Input image, which can be grayscale or multichannel, and must have a + number of dimensions compatible with ``self.features_func``. + + Raises + ------ + NotFittedError if ``self.clf`` has not been fitted yet (use ``self.fit``). + """ + if self.features_func is None: + self.features_func = multiscale_basic_features + features = self.features_func(image) + return predict_segmenter(features, self.clf) + + +def fit_segmenter(labels, features, clf): + """Segmentation using labeled parts of the image and a classifier. + + Parameters + ---------- + labels : ndarray of ints + Image of labels. Labels >= 1 correspond to the training set and + label 0 to unlabeled pixels to be segmented. + features : ndarray + Array of features, with the first dimension corresponding to the number + of features, and the other dimensions correspond to ``labels.shape``. + clf : classifier object + classifier object, exposing a ``fit`` and a ``predict`` method as in + scikit-learn's API, for example an instance of + ``RandomForestClassifier`` or ``LogisticRegression`` classifier. + + Returns + ------- + clf : classifier object + classifier trained on ``labels`` + + Raises + ------ + NotFittedError if ``self.clf`` has not been fitted yet (use ``self.fit``). + """ + mask = labels > 0 + training_data = features[mask] + training_labels = labels[mask].ravel() + clf.fit(training_data, training_labels) + return clf + + +def predict_segmenter(features, clf): + """Segmentation of images using a pretrained classifier. + + Parameters + ---------- + features : ndarray + Array of features, with the last dimension corresponding to the number + of features, and the other dimensions are compatible with the shape of + the image to segment, or a flattened image. + clf : classifier object + trained classifier object, exposing a ``predict`` method as in + scikit-learn's API, for example an instance of + ``RandomForestClassifier`` or ``LogisticRegression`` classifier. The + classifier must be already trained, for example with + :func:`skimage.future.fit_segmenter`. + + Returns + ------- + output : ndarray + Labeled array, built from the prediction of the classifier. + """ + sh = features.shape + if features.ndim > 2: + features = features.reshape((-1, sh[-1])) + + try: + predicted_labels = clf.predict(features) + except NotFittedError: + raise NotFittedError( + "You must train the classifier `clf` first" + "for example with the `fit_segmenter` function." + ) + except ValueError as err: + if err.args and 'x must consist of vectors of length' in err.args[0]: + raise ValueError( + err.args[0] + + '\n' + + "Maybe you did not use the same type of features for training the classifier." + ) + else: + raise err + output = predicted_labels.reshape(sh[:-1]) + return output diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/__init__.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cffdd0d37dd5df6ee420fc5b764d93e681c39fe1 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/__init__.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_chan_vese.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_chan_vese.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e417d75068e9b9d05bea5d129f22e8981c383046 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_chan_vese.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_clear_border.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_clear_border.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59bb6e668ec615083f970ea00270312582c39a34 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_clear_border.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_expand_labels.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_expand_labels.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b9f75b606c757d299745acb70c6db7bde5afc0 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_expand_labels.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_felzenszwalb.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_felzenszwalb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5b252da39cd8c64c75ae3dad82e753564310786 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_felzenszwalb.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_join.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_join.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d27e861bcacceafbed24f5ced7d4441115fbbe9 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_join.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_quickshift.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_quickshift.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18b40ce3c3615be8b83af973cc84c2a150d621af Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_quickshift.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_watershed.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_watershed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bcfd5fe4356993fa83eb4267aa0d075ea49d1c8 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/_watershed.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/active_contour_model.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/active_contour_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec7df36605a2e0c34f117a64d306d72f6f92949e Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/active_contour_model.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/boundaries.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/boundaries.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b21af90971ca87d35720048b7df972b865e6f068 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/boundaries.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/morphsnakes.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/morphsnakes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c7177ebc644e8c827ecf46cd2b12b6d55c4f23d Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/morphsnakes.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/random_walker_segmentation.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/random_walker_segmentation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3c6f10b4163e1850f7649c520f48bd5b14b4ee2 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/random_walker_segmentation.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/slic_superpixels.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/slic_superpixels.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d2ede00886cea1fdbf899b479386c2b6b88e3c1 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/__pycache__/slic_superpixels.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/_clear_border.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/_clear_border.py new file mode 100644 index 0000000000000000000000000000000000000000..3ac598cde2e8b59f0b5576059d0232a536ac3358 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/_clear_border.py @@ -0,0 +1,109 @@ +import numpy as np + +from ..measure import label + + +def clear_border(labels, buffer_size=0, bgval=0, mask=None, *, out=None): + """Clear objects connected to the label image border. + + Parameters + ---------- + labels : (M[, N[, ..., P]]) array of int or bool + Imaging data labels. + buffer_size : int, optional + The width of the border examined. By default, only objects + that touch the outside of the image are removed. + bgval : float or int, optional + Cleared objects are set to this value. + mask : ndarray of bool, same shape as `image`, optional. + Image data mask. Objects in labels image overlapping with + False pixels of mask will be removed. If defined, the + argument buffer_size will be ignored. + out : ndarray + Array of the same shape as `labels`, into which the + output is placed. By default, a new array is created. + + Returns + ------- + out : (M[, N[, ..., P]]) array + Imaging data labels with cleared borders + + Examples + -------- + >>> import numpy as np + >>> from skimage.segmentation import clear_border + >>> labels = np.array([[0, 0, 0, 0, 0, 0, 0, 1, 0], + ... [1, 1, 0, 0, 1, 0, 0, 1, 0], + ... [1, 1, 0, 1, 0, 1, 0, 0, 0], + ... [0, 0, 0, 1, 1, 1, 1, 0, 0], + ... [0, 1, 1, 1, 1, 1, 1, 1, 0], + ... [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + >>> clear_border(labels) + array([[0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + >>> mask = np.array([[0, 0, 1, 1, 1, 1, 1, 1, 1], + ... [0, 0, 1, 1, 1, 1, 1, 1, 1], + ... [1, 1, 1, 1, 1, 1, 1, 1, 1], + ... [1, 1, 1, 1, 1, 1, 1, 1, 1], + ... [1, 1, 1, 1, 1, 1, 1, 1, 1], + ... [1, 1, 1, 1, 1, 1, 1, 1, 1]]).astype(bool) + >>> clear_border(labels, mask=mask) + array([[0, 0, 0, 0, 0, 0, 0, 1, 0], + [0, 0, 0, 0, 1, 0, 0, 1, 0], + [0, 0, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0]]) + + """ + if any(buffer_size >= s for s in labels.shape) and mask is None: + # ignore buffer_size if mask + raise ValueError("buffer size may not be greater than labels size") + + if out is None: + out = labels.copy() + + if mask is not None: + err_msg = ( + f'labels and mask should have the same shape but ' + f'are {out.shape} and {mask.shape}' + ) + if out.shape != mask.shape: + raise (ValueError, err_msg) + if mask.dtype != bool: + raise TypeError("mask should be of type bool.") + borders = ~mask + else: + # create borders with buffer_size + borders = np.zeros_like(out, dtype=bool) + ext = buffer_size + 1 + slstart = slice(ext) + slend = slice(-ext, None) + slices = [slice(None) for _ in out.shape] + for d in range(out.ndim): + slices[d] = slstart + borders[tuple(slices)] = True + slices[d] = slend + borders[tuple(slices)] = True + slices[d] = slice(None) + + # Re-label, in case we are dealing with a binary out + # and to get consistent labeling + labels, number = label(out, background=0, return_num=True) + + # determine all objects that are connected to borders + borders_indices = np.unique(labels[borders]) + indices = np.arange(number + 1) + # mask all label indices that are connected to borders + label_mask = np.isin(indices, borders_indices) + # create mask for pixels to clear + mask = label_mask[labels.reshape(-1)].reshape(labels.shape) + + # clear border pixels + out[mask] = bgval + + return out diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/_felzenszwalb.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/_felzenszwalb.py new file mode 100644 index 0000000000000000000000000000000000000000..74b482941ed00114871869d48e9ae90ee894c4e6 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/_felzenszwalb.py @@ -0,0 +1,69 @@ +import numpy as np + +from ._felzenszwalb_cy import _felzenszwalb_cython +from .._shared import utils + + +@utils.channel_as_last_axis(multichannel_output=False) +def felzenszwalb(image, scale=1, sigma=0.8, min_size=20, *, channel_axis=-1): + """Computes Felsenszwalb's efficient graph based image segmentation. + + Produces an oversegmentation of a multichannel (i.e. RGB) image + using a fast, minimum spanning tree based clustering on the image grid. + The parameter ``scale`` sets an observation level. Higher scale means + less and larger segments. ``sigma`` is the diameter of a Gaussian kernel, + used for smoothing the image prior to segmentation. + + The number of produced segments as well as their size can only be + controlled indirectly through ``scale``. Segment size within an image can + vary greatly depending on local contrast. + + For RGB images, the algorithm uses the euclidean distance between pixels in + color space. + + Parameters + ---------- + image : (M, N[, 3]) ndarray + Input image. + scale : float + Free parameter. Higher means larger clusters. + sigma : float + Width (standard deviation) of Gaussian kernel used in preprocessing. + min_size : int + Minimum component size. Enforced using postprocessing. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + segment_mask : (M, N) ndarray + Integer mask indicating segment labels. + + References + ---------- + .. [1] Efficient graph-based image segmentation, Felzenszwalb, P.F. and + Huttenlocher, D.P. International Journal of Computer Vision, 2004 + + Notes + ----- + The `k` parameter used in the original paper renamed to `scale` here. + + Examples + -------- + >>> from skimage.segmentation import felzenszwalb + >>> from skimage.data import coffee + >>> img = coffee() + >>> segments = felzenszwalb(img, scale=3.0, sigma=0.95, min_size=5) + """ + if channel_axis is None and image.ndim > 2: + raise ValueError( + "This algorithm works only on single or " "multi-channel 2d images. " + ) + + image = np.atleast_3d(image) + return _felzenszwalb_cython(image, scale=scale, sigma=sigma, min_size=min_size) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/morphsnakes.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/morphsnakes.py new file mode 100644 index 0000000000000000000000000000000000000000..c65349020b664be1a5e920eeef4623ff20db9894 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/morphsnakes.py @@ -0,0 +1,449 @@ +from itertools import cycle + +import numpy as np +from scipy import ndimage as ndi + +from .._shared.utils import check_nD + +__all__ = [ + 'morphological_chan_vese', + 'morphological_geodesic_active_contour', + 'inverse_gaussian_gradient', + 'disk_level_set', + 'checkerboard_level_set', +] + + +class _fcycle: + def __init__(self, iterable): + """Call functions from the iterable each time it is called.""" + self.funcs = cycle(iterable) + + def __call__(self, *args, **kwargs): + f = next(self.funcs) + return f(*args, **kwargs) + + +# SI and IS operators for 2D and 3D. +_P2 = [ + np.eye(3), + np.array([[0, 1, 0]] * 3), + np.flipud(np.eye(3)), + np.rot90([[0, 1, 0]] * 3), +] +_P3 = [np.zeros((3, 3, 3)) for i in range(9)] + +_P3[0][:, :, 1] = 1 +_P3[1][:, 1, :] = 1 +_P3[2][1, :, :] = 1 +_P3[3][:, [0, 1, 2], [0, 1, 2]] = 1 +_P3[4][:, [0, 1, 2], [2, 1, 0]] = 1 +_P3[5][[0, 1, 2], :, [0, 1, 2]] = 1 +_P3[6][[0, 1, 2], :, [2, 1, 0]] = 1 +_P3[7][[0, 1, 2], [0, 1, 2], :] = 1 +_P3[8][[0, 1, 2], [2, 1, 0], :] = 1 + + +def sup_inf(u): + """SI operator.""" + + if np.ndim(u) == 2: + P = _P2 + elif np.ndim(u) == 3: + P = _P3 + else: + raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") + + erosions = [] + for P_i in P: + erosions.append(ndi.binary_erosion(u, P_i).astype(np.int8)) + + return np.stack(erosions, axis=0).max(0) + + +def inf_sup(u): + """IS operator.""" + + if np.ndim(u) == 2: + P = _P2 + elif np.ndim(u) == 3: + P = _P3 + else: + raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") + + dilations = [] + for P_i in P: + dilations.append(ndi.binary_dilation(u, P_i).astype(np.int8)) + + return np.stack(dilations, axis=0).min(0) + + +_curvop = _fcycle( + [lambda u: sup_inf(inf_sup(u)), lambda u: inf_sup(sup_inf(u))] # SIoIS +) # ISoSI + + +def _check_input(image, init_level_set): + """Check that shapes of `image` and `init_level_set` match.""" + check_nD(image, [2, 3]) + + if len(image.shape) != len(init_level_set.shape): + raise ValueError( + "The dimensions of the initial level set do not " + "match the dimensions of the image." + ) + + +def _init_level_set(init_level_set, image_shape): + """Auxiliary function for initializing level sets with a string. + + If `init_level_set` is not a string, it is returned as is. + """ + if isinstance(init_level_set, str): + if init_level_set == 'checkerboard': + res = checkerboard_level_set(image_shape) + elif init_level_set == 'disk': + res = disk_level_set(image_shape) + else: + raise ValueError("`init_level_set` not in " "['checkerboard', 'disk']") + else: + res = init_level_set + return res + + +def disk_level_set(image_shape, *, center=None, radius=None): + """Create a disk level set with binary values. + + Parameters + ---------- + image_shape : tuple of positive integers + Shape of the image + center : tuple of positive integers, optional + Coordinates of the center of the disk given in (row, column). If not + given, it defaults to the center of the image. + radius : float, optional + Radius of the disk. If not given, it is set to the 75% of the + smallest image dimension. + + Returns + ------- + out : array with shape `image_shape` + Binary level set of the disk with the given `radius` and `center`. + + See Also + -------- + checkerboard_level_set + """ + + if center is None: + center = tuple(i // 2 for i in image_shape) + + if radius is None: + radius = min(image_shape) * 3.0 / 8.0 + + grid = np.mgrid[[slice(i) for i in image_shape]] + grid = (grid.T - center).T + phi = radius - np.sqrt(np.sum((grid) ** 2, 0)) + res = np.int8(phi > 0) + return res + + +def checkerboard_level_set(image_shape, square_size=5): + """Create a checkerboard level set with binary values. + + Parameters + ---------- + image_shape : tuple of positive integers + Shape of the image. + square_size : int, optional + Size of the squares of the checkerboard. It defaults to 5. + + Returns + ------- + out : array with shape `image_shape` + Binary level set of the checkerboard. + + See Also + -------- + disk_level_set + """ + + grid = np.mgrid[[slice(i) for i in image_shape]] + grid = grid // square_size + + # Alternate 0/1 for even/odd numbers. + grid = grid & 1 + + checkerboard = np.bitwise_xor.reduce(grid, axis=0) + res = np.int8(checkerboard) + return res + + +def inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0): + """Inverse of gradient magnitude. + + Compute the magnitude of the gradients in the image and then inverts the + result in the range [0, 1]. Flat areas are assigned values close to 1, + while areas close to borders are assigned values close to 0. + + This function or a similar one defined by the user should be applied over + the image as a preprocessing step before calling + `morphological_geodesic_active_contour`. + + Parameters + ---------- + image : (M, N) or (L, M, N) array + Grayscale image or volume. + alpha : float, optional + Controls the steepness of the inversion. A larger value will make the + transition between the flat areas and border areas steeper in the + resulting array. + sigma : float, optional + Standard deviation of the Gaussian filter applied over the image. + + Returns + ------- + gimage : (M, N) or (L, M, N) array + Preprocessed image (or volume) suitable for + `morphological_geodesic_active_contour`. + """ + gradnorm = ndi.gaussian_gradient_magnitude(image, sigma, mode='nearest') + return 1.0 / np.sqrt(1.0 + alpha * gradnorm) + + +def morphological_chan_vese( + image, + num_iter, + init_level_set='checkerboard', + smoothing=1, + lambda1=1, + lambda2=1, + iter_callback=lambda x: None, +): + """Morphological Active Contours without Edges (MorphACWE) + + Active contours without edges implemented with morphological operators. It + can be used to segment objects in images and volumes without well defined + borders. It is required that the inside of the object looks different on + average than the outside (i.e., the inner area of the object should be + darker or lighter than the outer area on average). + + Parameters + ---------- + image : (M, N) or (L, M, N) array + Grayscale image or volume to be segmented. + num_iter : uint + Number of num_iter to run + init_level_set : str, (M, N) array, or (L, M, N) array + Initial level set. If an array is given, it will be binarized and used + as the initial level set. If a string is given, it defines the method + to generate a reasonable initial level set with the shape of the + `image`. Accepted values are 'checkerboard' and 'disk'. See the + documentation of `checkerboard_level_set` and `disk_level_set` + respectively for details about how these level sets are created. + smoothing : uint, optional + Number of times the smoothing operator is applied per iteration. + Reasonable values are around 1-4. Larger values lead to smoother + segmentations. + lambda1 : float, optional + Weight parameter for the outer region. If `lambda1` is larger than + `lambda2`, the outer region will contain a larger range of values than + the inner region. + lambda2 : float, optional + Weight parameter for the inner region. If `lambda2` is larger than + `lambda1`, the inner region will contain a larger range of values than + the outer region. + iter_callback : function, optional + If given, this function is called once per iteration with the current + level set as the only argument. This is useful for debugging or for + plotting intermediate results during the evolution. + + Returns + ------- + out : (M, N) or (L, M, N) array + Final segmentation (i.e., the final level set) + + See Also + -------- + disk_level_set, checkerboard_level_set + + Notes + ----- + This is a version of the Chan-Vese algorithm that uses morphological + operators instead of solving a partial differential equation (PDE) for the + evolution of the contour. The set of morphological operators used in this + algorithm are proved to be infinitesimally equivalent to the Chan-Vese PDE + (see [1]_). However, morphological operators are do not suffer from the + numerical stability issues typically found in PDEs (it is not necessary to + find the right time step for the evolution), and are computationally + faster. + + The algorithm and its theoretical derivation are described in [1]_. + + References + ---------- + .. [1] A Morphological Approach to Curvature-based Evolution of Curves and + Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE + Transactions on Pattern Analysis and Machine Intelligence (PAMI), + 2014, :DOI:`10.1109/TPAMI.2013.106` + """ + + init_level_set = _init_level_set(init_level_set, image.shape) + + _check_input(image, init_level_set) + + u = np.int8(init_level_set > 0) + + iter_callback(u) + + for _ in range(num_iter): + # inside = u > 0 + # outside = u <= 0 + c0 = (image * (1 - u)).sum() / float((1 - u).sum() + 1e-8) + c1 = (image * u).sum() / float(u.sum() + 1e-8) + + # Image attachment + du = np.gradient(u) + abs_du = np.abs(du).sum(0) + aux = abs_du * (lambda1 * (image - c1) ** 2 - lambda2 * (image - c0) ** 2) + + u[aux < 0] = 1 + u[aux > 0] = 0 + + # Smoothing + for _ in range(smoothing): + u = _curvop(u) + + iter_callback(u) + + return u + + +def morphological_geodesic_active_contour( + gimage, + num_iter, + init_level_set='disk', + smoothing=1, + threshold='auto', + balloon=0, + iter_callback=lambda x: None, +): + """Morphological Geodesic Active Contours (MorphGAC). + + Geodesic active contours implemented with morphological operators. It can + be used to segment objects with visible but noisy, cluttered, broken + borders. + + Parameters + ---------- + gimage : (M, N) or (L, M, N) array + Preprocessed image or volume to be segmented. This is very rarely the + original image. Instead, this is usually a preprocessed version of the + original image that enhances and highlights the borders (or other + structures) of the object to segment. + :func:`morphological_geodesic_active_contour` will try to stop the contour + evolution in areas where `gimage` is small. See + :func:`inverse_gaussian_gradient` as an example function to + perform this preprocessing. Note that the quality of + :func:`morphological_geodesic_active_contour` might greatly depend on this + preprocessing. + num_iter : uint + Number of num_iter to run. + init_level_set : str, (M, N) array, or (L, M, N) array + Initial level set. If an array is given, it will be binarized and used + as the initial level set. If a string is given, it defines the method + to generate a reasonable initial level set with the shape of the + `image`. Accepted values are 'checkerboard' and 'disk'. See the + documentation of `checkerboard_level_set` and `disk_level_set` + respectively for details about how these level sets are created. + smoothing : uint, optional + Number of times the smoothing operator is applied per iteration. + Reasonable values are around 1-4. Larger values lead to smoother + segmentations. + threshold : float, optional + Areas of the image with a value smaller than this threshold will be + considered borders. The evolution of the contour will stop in these + areas. + balloon : float, optional + Balloon force to guide the contour in non-informative areas of the + image, i.e., areas where the gradient of the image is too small to push + the contour towards a border. A negative value will shrink the contour, + while a positive value will expand the contour in these areas. Setting + this to zero will disable the balloon force. + iter_callback : function, optional + If given, this function is called once per iteration with the current + level set as the only argument. This is useful for debugging or for + plotting intermediate results during the evolution. + + Returns + ------- + out : (M, N) or (L, M, N) array + Final segmentation (i.e., the final level set) + + See Also + -------- + inverse_gaussian_gradient, disk_level_set, checkerboard_level_set + + Notes + ----- + This is a version of the Geodesic Active Contours (GAC) algorithm that uses + morphological operators instead of solving partial differential equations + (PDEs) for the evolution of the contour. The set of morphological operators + used in this algorithm are proved to be infinitesimally equivalent to the + GAC PDEs (see [1]_). However, morphological operators are do not suffer + from the numerical stability issues typically found in PDEs (e.g., it is + not necessary to find the right time step for the evolution), and are + computationally faster. + + The algorithm and its theoretical derivation are described in [1]_. + + References + ---------- + .. [1] A Morphological Approach to Curvature-based Evolution of Curves and + Surfaces, Pablo Márquez-Neila, Luis Baumela, Luis Álvarez. In IEEE + Transactions on Pattern Analysis and Machine Intelligence (PAMI), + 2014, :DOI:`10.1109/TPAMI.2013.106` + """ + + image = gimage + init_level_set = _init_level_set(init_level_set, image.shape) + + _check_input(image, init_level_set) + + if threshold == 'auto': + threshold = np.percentile(image, 40) + + structure = np.ones((3,) * len(image.shape), dtype=np.int8) + dimage = np.gradient(image) + # threshold_mask = image > threshold + if balloon != 0: + threshold_mask_balloon = image > threshold / np.abs(balloon) + + u = np.int8(init_level_set > 0) + + iter_callback(u) + + for _ in range(num_iter): + # Balloon + if balloon > 0: + aux = ndi.binary_dilation(u, structure) + elif balloon < 0: + aux = ndi.binary_erosion(u, structure) + if balloon != 0: + u[threshold_mask_balloon] = aux[threshold_mask_balloon] + + # Image attachment + aux = np.zeros_like(image) + du = np.gradient(u) + for el1, el2 in zip(dimage, du): + aux += el1 * el2 + u[aux > 0] = 1 + u[aux < 0] = 0 + + # Smoothing + for _ in range(smoothing): + u = _curvop(u) + + iter_callback(u) + + return u diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/random_walker_segmentation.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/random_walker_segmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..696cf46a52a7d35cc6a72652e51afe4e0a9989ef --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/random_walker_segmentation.py @@ -0,0 +1,588 @@ +""" +Random walker segmentation algorithm + +from *Random walks for image segmentation*, Leo Grady, IEEE Trans +Pattern Anal Mach Intell. 2006 Nov;28(11):1768-83. + +Installing pyamg and using the 'cg_mg' mode of random_walker improves +significantly the performance. +""" + +import numpy as np +from scipy import sparse, ndimage as ndi + +from .._shared import utils +from .._shared.utils import warn +from .._shared.compat import SCIPY_CG_TOL_PARAM_NAME + +# executive summary for next code block: try to import umfpack from +# scipy, but make sure not to raise a fuss if it fails since it's only +# needed to speed up a few cases. +# See discussions at: +# https://groups.google.com/d/msg/scikit-image/FrM5IGP6wh4/1hp-FtVZmfcJ +# https://stackoverflow.com/questions/13977970/ignore-exceptions-printed-to-stderr-in-del/13977992?noredirect=1#comment28386412_13977992 +try: + from scipy.sparse.linalg.dsolve.linsolve import umfpack + + old_del = umfpack.UmfpackContext.__del__ + + def new_del(self): + try: + old_del(self) + except AttributeError: + pass + + umfpack.UmfpackContext.__del__ = new_del + UmfpackContext = umfpack.UmfpackContext() +except ImportError: + UmfpackContext = None + +try: + from pyamg import ruge_stuben_solver + + amg_loaded = True +except ImportError: + amg_loaded = False + +from ..util import img_as_float + +from scipy.sparse.linalg import cg, spsolve + + +def _make_graph_edges_3d(n_x, n_y, n_z): + """Returns a list of edges for a 3D image. + + Parameters + ---------- + n_x : integer + The size of the grid in the x direction. + n_y : integer + The size of the grid in the y direction + n_z : integer + The size of the grid in the z direction + + Returns + ------- + edges : (2, N) ndarray + with the total number of edges:: + + N = n_x * n_y * (nz - 1) + + n_x * (n_y - 1) * nz + + (n_x - 1) * n_y * nz + + Graph edges with each column describing a node-id pair. + """ + vertices = np.arange(n_x * n_y * n_z).reshape((n_x, n_y, n_z)) + edges_deep = np.vstack((vertices[..., :-1].ravel(), vertices[..., 1:].ravel())) + edges_right = np.vstack((vertices[:, :-1].ravel(), vertices[:, 1:].ravel())) + edges_down = np.vstack((vertices[:-1].ravel(), vertices[1:].ravel())) + edges = np.hstack((edges_deep, edges_right, edges_down)) + return edges + + +def _compute_weights_3d(data, spacing, beta, eps, multichannel): + # Weight calculation is main difference in multispectral version + # Original gradient**2 replaced with sum of gradients ** 2 + gradients = ( + np.concatenate( + [ + np.diff(data[..., 0], axis=ax).ravel() / spacing[ax] + for ax in [2, 1, 0] + if data.shape[ax] > 1 + ], + axis=0, + ) + ** 2 + ) + for channel in range(1, data.shape[-1]): + gradients += ( + np.concatenate( + [ + np.diff(data[..., channel], axis=ax).ravel() / spacing[ax] + for ax in [2, 1, 0] + if data.shape[ax] > 1 + ], + axis=0, + ) + ** 2 + ) + + # All channels considered together in this standard deviation + scale_factor = -beta / (10 * data.std()) + if multichannel: + # New final term in beta to give == results in trivial case where + # multiple identical spectra are passed. + scale_factor /= np.sqrt(data.shape[-1]) + weights = np.exp(scale_factor * gradients) + weights += eps + return -weights + + +def _build_laplacian(data, spacing, mask, beta, multichannel): + l_x, l_y, l_z = data.shape[:3] + edges = _make_graph_edges_3d(l_x, l_y, l_z) + weights = _compute_weights_3d( + data, spacing, beta=beta, eps=1.0e-10, multichannel=multichannel + ) + if mask is not None: + # Remove edges of the graph connected to masked nodes, as well + # as corresponding weights of the edges. + mask0 = np.hstack( + [mask[..., :-1].ravel(), mask[:, :-1].ravel(), mask[:-1].ravel()] + ) + mask1 = np.hstack( + [mask[..., 1:].ravel(), mask[:, 1:].ravel(), mask[1:].ravel()] + ) + ind_mask = np.logical_and(mask0, mask1) + edges, weights = edges[:, ind_mask], weights[ind_mask] + + # Reassign edges labels to 0, 1, ... edges_number - 1 + _, inv_idx = np.unique(edges, return_inverse=True) + edges = inv_idx.reshape(edges.shape) + + # Build the sparse linear system + pixel_nb = l_x * l_y * l_z + i_indices = edges.ravel() + j_indices = edges[::-1].ravel() + data = np.hstack((weights, weights)) + lap = sparse.csr_array((data, (i_indices, j_indices)), shape=(pixel_nb, pixel_nb)) + lap.setdiag(-np.ravel(lap.sum(axis=0))) + return lap + + +def _build_linear_system(data, spacing, labels, nlabels, mask, beta, multichannel): + """ + Build the matrix A and rhs B of the linear system to solve. + A and B are two block of the laplacian of the image graph. + """ + if mask is None: + labels = labels.ravel() + else: + labels = labels[mask] + + indices = np.arange(labels.size) + seeds_mask = labels > 0 + unlabeled_indices = indices[~seeds_mask] + seeds_indices = indices[seeds_mask] + + lap_sparse = _build_laplacian( + data, spacing, mask=mask, beta=beta, multichannel=multichannel + ) + + rows = lap_sparse[unlabeled_indices, :] + lap_sparse = rows[:, unlabeled_indices] + B = -rows[:, seeds_indices] + + seeds = labels[seeds_mask] + seeds_mask = sparse.csc_array( + np.hstack([np.atleast_2d(seeds == lab).T for lab in range(1, nlabels + 1)]) + ) + rhs = B @ seeds_mask + + return lap_sparse, rhs + + +def _solve_linear_system(lap_sparse, B, tol, mode): + if mode is None: + mode = 'cg_j' + + if mode == 'cg_mg' and not amg_loaded: + warn( + '"cg_mg" not available, it requires pyamg to be installed. ' + 'The "cg_j" mode will be used instead.', + stacklevel=2, + ) + mode = 'cg_j' + + if mode == 'bf': + X = spsolve(lap_sparse, B.toarray()).T + else: + maxiter = None + if mode == 'cg': + if UmfpackContext is None: + warn( + '"cg" mode may be slow because UMFPACK is not available. ' + 'Consider building Scipy with UMFPACK or use a ' + 'preconditioned version of CG ("cg_j" or "cg_mg" modes).', + stacklevel=2, + ) + M = None + elif mode == 'cg_j': + n = lap_sparse.shape[-1] + M = sparse.dia_array((1.0 / lap_sparse.diagonal(), 0), shape=(n, n)) + else: + # mode == 'cg_mg' + lap_sparse.indices, lap_sparse.indptr = _safe_downcast_indices( + lap_sparse, np.int32, "index values too large for int32 mode 'cg_mg'" + ) + ml = ruge_stuben_solver(lap_sparse, coarse_solver='pinv') + M = ml.aspreconditioner(cycle='V') + maxiter = 30 + rtol = {SCIPY_CG_TOL_PARAM_NAME: tol} + cg_out = [ + cg(lap_sparse, B[:, [i]].toarray(), **rtol, atol=0, M=M, maxiter=maxiter) + for i in range(B.shape[1]) + ] + if np.any([info > 0 for _, info in cg_out]): + warn( + "Conjugate gradient convergence to tolerance not achieved. " + "Consider decreasing beta to improve system conditionning.", + stacklevel=2, + ) + X = np.asarray([x for x, _ in cg_out]) + + return X + + +def _safe_downcast_indices(A, itype, msg): + # check for safe downcasting + max_value = np.iinfo(itype).max + + if A.indptr[-1] > max_value: # indptr[-1] is max b/c indptr always sorted + raise ValueError(msg) + + if max(*A.shape) > max_value: # only check large enough arrays + if np.any(A.indices > max_value): + raise ValueError(msg) + + indices = A.indices.astype(itype, copy=False) + indptr = A.indptr.astype(itype, copy=False) + return indices, indptr + + +def _preprocess(labels): + label_values, inv_idx = np.unique(labels, return_inverse=True) + if max(label_values) <= 0: + raise ValueError( + 'No seeds provided in label image: please ensure ' + 'it contains at least one positive value' + ) + + if not (label_values == 0).any(): + warn( + 'Random walker only segments unlabeled areas, where ' + 'labels == 0. No zero valued areas in labels were ' + 'found. Returning provided labels.', + stacklevel=2, + ) + + return labels, None, None, None, None + + # If some labeled pixels are isolated inside pruned zones, prune them + # as well and keep the labels for the final output + + null_mask = labels == 0 + pos_mask = labels > 0 + mask = labels >= 0 + + fill = ndi.binary_propagation(null_mask, mask=mask) + isolated = np.logical_and(pos_mask, np.logical_not(fill)) + + pos_mask[isolated] = False + + # If the array has pruned zones, be sure that no isolated pixels + # exist between pruned zones (they could not be determined) + if label_values[0] < 0 or np.any(isolated): + isolated = np.logical_and( + np.logical_not(ndi.binary_propagation(pos_mask, mask=mask)), null_mask + ) + + labels[isolated] = -1 + if np.all(isolated[null_mask]): + warn( + 'All unlabeled pixels are isolated, they could not be ' + 'determined by the random walker algorithm.', + stacklevel=2, + ) + return labels, None, None, None, None + + mask[isolated] = False + mask = np.atleast_3d(mask) + else: + mask = None + + # Reorder label values to have consecutive integers (no gaps) + zero_idx = np.searchsorted(label_values, 0) + labels = np.atleast_3d(inv_idx.reshape(labels.shape) - zero_idx) + + nlabels = label_values[zero_idx + 1 :].shape[0] + + inds_isolated_seeds = np.nonzero(isolated) + isolated_values = labels[inds_isolated_seeds] + + return labels, nlabels, mask, inds_isolated_seeds, isolated_values + + +@utils.channel_as_last_axis(multichannel_output=False) +def random_walker( + data, + labels, + beta=130, + mode='cg_j', + tol=1.0e-3, + copy=True, + return_full_prob=False, + spacing=None, + *, + prob_tol=1e-3, + channel_axis=None, +): + """Random walker algorithm for segmentation from markers. + + Random walker algorithm is implemented for gray-level or multichannel + images. + + Parameters + ---------- + data : (M, N[, P][, C]) ndarray + Image to be segmented in phases. Gray-level `data` can be two- or + three-dimensional; multichannel data can be three- or four- + dimensional with `channel_axis` specifying the dimension containing + channels. Data spacing is assumed isotropic unless the `spacing` + keyword argument is used. + labels : (M, N[, P]) array of ints + Array of seed markers labeled with different positive integers + for different phases. Zero-labeled pixels are unlabeled pixels. + Negative labels correspond to inactive pixels that are not taken + into account (they are removed from the graph). If labels are not + consecutive integers, the labels array will be transformed so that + labels are consecutive. In the multichannel case, `labels` should have + the same shape as a single channel of `data`, i.e. without the final + dimension denoting channels. + beta : float, optional + Penalization coefficient for the random walker motion + (the greater `beta`, the more difficult the diffusion). + mode : string, available options {'cg', 'cg_j', 'cg_mg', 'bf'} + Mode for solving the linear system in the random walker algorithm. + + - 'bf' (brute force): an LU factorization of the Laplacian is + computed. This is fast for small images (<1024x1024), but very slow + and memory-intensive for large images (e.g., 3-D volumes). + - 'cg' (conjugate gradient): the linear system is solved iteratively + using the Conjugate Gradient method from scipy.sparse.linalg. This is + less memory-consuming than the brute force method for large images, + but it is quite slow. + - 'cg_j' (conjugate gradient with Jacobi preconditionner): the + Jacobi preconditionner is applied during the Conjugate + gradient method iterations. This may accelerate the + convergence of the 'cg' method. + - 'cg_mg' (conjugate gradient with multigrid preconditioner): a + preconditioner is computed using a multigrid solver, then the + solution is computed with the Conjugate Gradient method. This mode + requires that the pyamg module is installed. + tol : float, optional + Tolerance to achieve when solving the linear system using + the conjugate gradient based modes ('cg', 'cg_j' and 'cg_mg'). + copy : bool, optional + If copy is False, the `labels` array will be overwritten with + the result of the segmentation. Use copy=False if you want to + save on memory. + return_full_prob : bool, optional + If True, the probability that a pixel belongs to each of the + labels will be returned, instead of only the most likely + label. + spacing : iterable of floats, optional + Spacing between voxels in each spatial dimension. If `None`, then + the spacing between pixels/voxels in each dimension is assumed 1. + prob_tol : float, optional + Tolerance on the resulting probability to be in the interval [0, 1]. + If the tolerance is not satisfied, a warning is displayed. + channel_axis : int or None, optional + If None, the image is assumed to be a grayscale (single channel) image. + Otherwise, this parameter indicates which axis of the array corresponds + to channels. + + .. versionadded:: 0.19 + ``channel_axis`` was added in 0.19. + + Returns + ------- + output : ndarray + * If `return_full_prob` is False, array of ints of same shape + and data type as `labels`, in which each pixel has been + labeled according to the marker that reached the pixel first + by anisotropic diffusion. + * If `return_full_prob` is True, array of floats of shape + `(nlabels, labels.shape)`. `output[label_nb, i, j]` is the + probability that label `label_nb` reaches the pixel `(i, j)` + first. + + See Also + -------- + skimage.segmentation.watershed + A segmentation algorithm based on mathematical morphology + and "flooding" of regions from markers. + + Notes + ----- + Multichannel inputs are scaled with all channel data combined. Ensure all + channels are separately normalized prior to running this algorithm. + + The `spacing` argument is specifically for anisotropic datasets, where + data points are spaced differently in one or more spatial dimensions. + Anisotropic data is commonly encountered in medical imaging. + + The algorithm was first proposed in [1]_. + + The algorithm solves the diffusion equation at infinite times for + sources placed on markers of each phase in turn. A pixel is labeled with + the phase that has the greatest probability to diffuse first to the pixel. + + The diffusion equation is solved by minimizing x.T L x for each phase, + where L is the Laplacian of the weighted graph of the image, and x is + the probability that a marker of the given phase arrives first at a pixel + by diffusion (x=1 on markers of the phase, x=0 on the other markers, and + the other coefficients are looked for). Each pixel is attributed the label + for which it has a maximal value of x. The Laplacian L of the image + is defined as: + + - L_ii = d_i, the number of neighbors of pixel i (the degree of i) + - L_ij = -w_ij if i and j are adjacent pixels + + The weight w_ij is a decreasing function of the norm of the local gradient. + This ensures that diffusion is easier between pixels of similar values. + + When the Laplacian is decomposed into blocks of marked and unmarked + pixels:: + + L = M B.T + B A + + with first indices corresponding to marked pixels, and then to unmarked + pixels, minimizing x.T L x for one phase amount to solving:: + + A x = - B x_m + + where x_m = 1 on markers of the given phase, and 0 on other markers. + This linear system is solved in the algorithm using a direct method for + small images, and an iterative method for larger images. + + References + ---------- + .. [1] Leo Grady, Random walks for image segmentation, IEEE Trans Pattern + Anal Mach Intell. 2006 Nov;28(11):1768-83. + :DOI:`10.1109/TPAMI.2006.233`. + + Examples + -------- + >>> rng = np.random.default_rng() + >>> a = np.zeros((10, 10)) + 0.2 * rng.random((10, 10)) + >>> a[5:8, 5:8] += 1 + >>> b = np.zeros_like(a, dtype=np.int32) + >>> b[3, 3] = 1 # Marker for first phase + >>> b[6, 6] = 2 # Marker for second phase + >>> random_walker(a, b) # doctest: +SKIP + array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32) + + """ + # Parse input data + if mode not in ('cg_mg', 'cg', 'bf', 'cg_j', None): + raise ValueError( + f"{mode} is not a valid mode. Valid modes are 'cg_mg', " + f"'cg', 'cg_j', 'bf', and None" + ) + + # Spacing kwarg checks + if spacing is None: + spacing = np.ones(3) + elif len(spacing) == labels.ndim: + if len(spacing) == 2: + # Need a dummy spacing for singleton 3rd dim + spacing = np.r_[spacing, 1.0] + spacing = np.asarray(spacing) + else: + raise ValueError( + 'Input argument `spacing` incorrect, should be an ' + 'iterable with one number per spatial dimension.' + ) + + # This algorithm expects 4-D arrays of floats, where the first three + # dimensions are spatial and the final denotes channels. 2-D images have + # a singleton placeholder dimension added for the third spatial dimension, + # and single channel images likewise have a singleton added for channels. + # The following block ensures valid input and coerces it to the correct + # form. + multichannel = channel_axis is not None + if not multichannel: + if data.ndim not in (2, 3): + raise ValueError( + 'For non-multichannel input, data must be of ' 'dimension 2 or 3.' + ) + if data.shape != labels.shape: + raise ValueError('Incompatible data and labels shapes.') + data = np.atleast_3d(img_as_float(data))[..., np.newaxis] + else: + if data.ndim not in (3, 4): + raise ValueError( + 'For multichannel input, data must have 3 or 4 ' 'dimensions.' + ) + if data.shape[:-1] != labels.shape: + raise ValueError('Incompatible data and labels shapes.') + data = img_as_float(data) + if data.ndim == 3: # 2D multispectral, needs singleton in 3rd axis + data = data[:, :, np.newaxis, :] + + labels_shape = labels.shape + labels_dtype = labels.dtype + + if copy: + labels = np.copy(labels) + + (labels, nlabels, mask, inds_isolated_seeds, isolated_values) = _preprocess(labels) + + if isolated_values is None: + # No non isolated zero valued areas in labels were + # found. Returning provided labels. + if return_full_prob: + # Return the concatenation of the masks of each unique label + return np.concatenate( + [np.atleast_3d(labels == lab) for lab in np.unique(labels) if lab > 0], + axis=-1, + ) + return labels + + # Build the linear system (lap_sparse, B) + lap_sparse, B = _build_linear_system( + data, spacing, labels, nlabels, mask, beta, multichannel + ) + + # Solve the linear system lap_sparse X = B + # where X[i, j] is the probability that a marker of label i arrives + # first at pixel j by anisotropic diffusion. + X = _solve_linear_system(lap_sparse, B, tol, mode) + + if X.min() < -prob_tol or X.max() > 1 + prob_tol: + warn( + 'The probability range is outside [0, 1] given the tolerance ' + '`prob_tol`. Consider decreasing `beta` and/or decreasing ' + '`tol`.' + ) + + # Build the output according to return_full_prob value + # Put back labels of isolated seeds + labels[inds_isolated_seeds] = isolated_values + labels = labels.reshape(labels_shape) + + mask = labels == 0 + mask[inds_isolated_seeds] = False + + if return_full_prob: + out = np.zeros((nlabels,) + labels_shape) + for lab, (label_prob, prob) in enumerate(zip(out, X), start=1): + label_prob[mask] = prob + label_prob[labels == lab] = 1 + else: + X = np.argmax(X, axis=0) + 1 + out = labels.astype(labels_dtype) + out[mask] = X + + return out diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__init__.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/__init__.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b11edc3be976c1a64622ebd71fa5ae447e195dbc Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_active_contour_model.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_active_contour_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..722b4c070248678d8b33101f8304a1be4c64f2e3 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_active_contour_model.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_boundaries.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_boundaries.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de5ebced49ab26425edb834f125530962b6ac535 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_boundaries.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_chan_vese.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_chan_vese.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fba603bc716707fb2568b409850f3937ebf2261e Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_chan_vese.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_clear_border.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_clear_border.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..731eaef78190271ba1b3a60403fa00f019f42e99 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_clear_border.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_expand_labels.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_expand_labels.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b29cb0a8bfc5ba6bf88e1f52d98c4a779b280c73 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_expand_labels.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_felzenszwalb.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_felzenszwalb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56c97baef20503f563bf312264c1e143283082a5 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_felzenszwalb.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_join.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_join.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc6b05edefa0db79fbefe9aa51fbfd9bac35e410 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_join.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_morphsnakes.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_morphsnakes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..738b3e6ce195c092bb44a0f481e0bacf3a36f33a Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_morphsnakes.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_quickshift.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_quickshift.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e88b33c83223c70c30bd3ba62ce3273262bebbe4 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_quickshift.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_random_walker.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_random_walker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32c9d616833438bcb5183035e78777900bec1420 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_random_walker.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_slic.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_slic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c04a6aba1844d966b8de842c135a34219aed07b2 Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_slic.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_watershed.cpython-310.pyc b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_watershed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c117ca9e1ab48e17c14c325cc047e0e0750467d Binary files /dev/null and b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/__pycache__/test_watershed.cpython-310.pyc differ diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_active_contour_model.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_active_contour_model.py new file mode 100644 index 0000000000000000000000000000000000000000..79844ddd2cd7be55314d0089f120fdc7a5ccbeae --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_active_contour_model.py @@ -0,0 +1,190 @@ +import numpy as np +import pytest +from numpy.testing import assert_equal, assert_allclose + +from skimage import data +from skimage._shared.utils import _supported_float_type +from skimage.color import rgb2gray +from skimage.filters import gaussian +from skimage.segmentation import active_contour + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_periodic_reference(dtype): + img = data.astronaut() + img = rgb2gray(img) + s = np.linspace(0, 2 * np.pi, 400) + r = 100 + 100 * np.sin(s) + c = 220 + 100 * np.cos(s) + init = np.array([r, c]).T + img_smooth = gaussian(img, sigma=3, preserve_range=False).astype(dtype, copy=False) + snake = active_contour( + img_smooth, init, alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001 + ) + assert snake.dtype == _supported_float_type(dtype) + refr = [98, 99, 100, 101, 102, 103, 104, 105, 106, 108] + refc = [299, 298, 298, 298, 298, 297, 297, 296, 296, 295] + assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr) + assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc) + + +@pytest.mark.parametrize('dtype', [np.float32, np.float64]) +def test_fixed_reference(dtype): + img = data.text() + r = np.linspace(136, 50, 100) + c = np.linspace(5, 424, 100) + init = np.array([r, c]).T + image_smooth = gaussian(img, sigma=1, preserve_range=False).astype( + dtype, copy=False + ) + snake = active_contour( + image_smooth, + init, + boundary_condition='fixed', + alpha=0.1, + beta=1.0, + w_line=-5, + w_edge=0, + gamma=0.1, + ) + assert snake.dtype == _supported_float_type(dtype) + refr = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125] + refc = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42] + assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr) + assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc) + + +@pytest.mark.parametrize('dtype', [np.float32, np.float64]) +def test_free_reference(dtype): + img = data.text() + r = np.linspace(70, 40, 100) + c = np.linspace(5, 424, 100) + init = np.array([r, c]).T + img_smooth = gaussian(img, sigma=3, preserve_range=False).astype(dtype, copy=False) + snake = active_contour( + img_smooth, + init, + boundary_condition='free', + alpha=0.1, + beta=1.0, + w_line=-5, + w_edge=0, + gamma=0.1, + ) + assert snake.dtype == _supported_float_type(dtype) + refr = [76, 76, 75, 74, 73, 72, 71, 70, 69, 69] + refc = [10, 13, 16, 19, 23, 26, 29, 32, 36, 39] + assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr) + assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc) + + +@pytest.mark.parametrize('dtype', [np.float32, np.float64]) +def test_RGB(dtype): + img = gaussian(data.text(), sigma=1, preserve_range=False) + imgR = np.zeros((img.shape[0], img.shape[1], 3), dtype=dtype) + imgG = np.zeros((img.shape[0], img.shape[1], 3), dtype=dtype) + imgRGB = np.zeros((img.shape[0], img.shape[1], 3), dtype=dtype) + imgR[:, :, 0] = img + imgG[:, :, 1] = img + imgRGB[:, :, :] = img[:, :, None] + r = np.linspace(136, 50, 100) + c = np.linspace(5, 424, 100) + init = np.array([r, c]).T + snake = active_contour( + imgR, + init, + boundary_condition='fixed', + alpha=0.1, + beta=1.0, + w_line=-5, + w_edge=0, + gamma=0.1, + ) + float_dtype = _supported_float_type(dtype) + assert snake.dtype == float_dtype + refr = [136, 135, 134, 133, 132, 131, 129, 128, 127, 125] + refc = [5, 9, 13, 17, 21, 25, 30, 34, 38, 42] + assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr) + assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc) + snake = active_contour( + imgG, + init, + boundary_condition='fixed', + alpha=0.1, + beta=1.0, + w_line=-5, + w_edge=0, + gamma=0.1, + ) + assert snake.dtype == float_dtype + assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr) + assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc) + snake = active_contour( + imgRGB, + init, + boundary_condition='fixed', + alpha=0.1, + beta=1.0, + w_line=-5 / 3.0, + w_edge=0, + gamma=0.1, + ) + assert snake.dtype == float_dtype + assert_equal(np.array(snake[:10, 0], dtype=np.int32), refr) + assert_equal(np.array(snake[:10, 1], dtype=np.int32), refc) + + +def test_end_points(): + img = data.astronaut() + img = rgb2gray(img) + s = np.linspace(0, 2 * np.pi, 400) + r = 100 + 100 * np.sin(s) + c = 220 + 100 * np.cos(s) + init = np.array([r, c]).T + snake = active_contour( + gaussian(img, sigma=3), + init, + boundary_condition='periodic', + alpha=0.015, + beta=10, + w_line=0, + w_edge=1, + gamma=0.001, + max_num_iter=100, + ) + assert np.sum(np.abs(snake[0, :] - snake[-1, :])) < 2 + snake = active_contour( + gaussian(img, sigma=3), + init, + boundary_condition='free', + alpha=0.015, + beta=10, + w_line=0, + w_edge=1, + gamma=0.001, + max_num_iter=100, + ) + assert np.sum(np.abs(snake[0, :] - snake[-1, :])) > 2 + snake = active_contour( + gaussian(img, sigma=3), + init, + boundary_condition='fixed', + alpha=0.015, + beta=10, + w_line=0, + w_edge=1, + gamma=0.001, + max_num_iter=100, + ) + assert_allclose(snake[0, :], [r[0], c[0]], atol=1e-5) + + +def test_bad_input(): + img = np.zeros((10, 10)) + r = np.linspace(136, 50, 100) + c = np.linspace(5, 424, 100) + init = np.array([r, c]).T + with pytest.raises(ValueError): + active_contour(img, init, boundary_condition='wrong') + with pytest.raises(ValueError): + active_contour(img, init, max_num_iter=-15) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_boundaries.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_boundaries.py new file mode 100644 index 0000000000000000000000000000000000000000..578c20b863f6b4ec45ea246de140ce2653f042d7 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_boundaries.py @@ -0,0 +1,159 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal, assert_allclose + +from skimage._shared.utils import _supported_float_type +from skimage.segmentation import find_boundaries, mark_boundaries + + +white = (1, 1, 1) + + +def test_find_boundaries(): + image = np.zeros((10, 10), dtype=np.uint8) + image[2:7, 2:7] = 1 + + ref = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + ) + + result = find_boundaries(image) + assert_array_equal(result, ref) + + +def test_find_boundaries_bool(): + image = np.zeros((5, 5), dtype=bool) + image[2:5, 2:5] = True + + ref = np.array( + [ + [False, False, False, False, False], + [False, False, True, True, True], + [False, True, True, True, True], + [False, True, True, False, False], + [False, True, True, False, False], + ], + dtype=bool, + ) + result = find_boundaries(image) + assert_array_equal(result, ref) + + +@pytest.mark.parametrize('dtype', [np.uint8, np.float16, np.float32, np.float64]) +def test_mark_boundaries(dtype): + image = np.zeros((10, 10), dtype=dtype) + label_image = np.zeros((10, 10), dtype=np.uint8) + label_image[2:7, 2:7] = 1 + + ref = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + ) + + marked = mark_boundaries(image, label_image, color=white, mode='thick') + assert marked.dtype == _supported_float_type(dtype) + result = np.mean(marked, axis=-1) + assert_array_equal(result, ref) + + ref = np.array( + [ + [0, 2, 2, 2, 2, 2, 2, 2, 0, 0], + [2, 2, 1, 1, 1, 1, 1, 2, 2, 0], + [2, 1, 1, 1, 1, 1, 1, 1, 2, 0], + [2, 1, 1, 2, 2, 2, 1, 1, 2, 0], + [2, 1, 1, 2, 0, 2, 1, 1, 2, 0], + [2, 1, 1, 2, 2, 2, 1, 1, 2, 0], + [2, 1, 1, 1, 1, 1, 1, 1, 2, 0], + [2, 2, 1, 1, 1, 1, 1, 2, 2, 0], + [0, 2, 2, 2, 2, 2, 2, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + ) + marked = mark_boundaries( + image, label_image, color=white, outline_color=(2, 2, 2), mode='thick' + ) + result = np.mean(marked, axis=-1) + assert_array_equal(result, ref) + + +def test_mark_boundaries_bool(): + image = np.zeros((10, 10), dtype=bool) + label_image = np.zeros((10, 10), dtype=np.uint8) + label_image[2:7, 2:7] = 1 + + ref = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 0, 0, 0, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + ) + + marked = mark_boundaries(image, label_image, color=white, mode='thick') + result = np.mean(marked, axis=-1) + assert_array_equal(result, ref) + + +@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_mark_boundaries_subpixel(dtype): + labels = np.array( + [[0, 0, 0, 0], [0, 0, 5, 0], [0, 1, 5, 0], [0, 0, 5, 0], [0, 0, 0, 0]], + dtype=np.uint8, + ) + np.random.seed(0) + image = np.round(np.random.rand(*labels.shape), 2) + image = image.astype(dtype, copy=False) + marked = mark_boundaries(image, labels, color=white, mode='subpixel') + assert marked.dtype == _supported_float_type(dtype) + marked_proj = np.round(np.mean(marked, axis=-1), 2) + + ref_result = np.array( + [ + [0.55, 0.63, 0.72, 0.69, 0.6, 0.55, 0.54], + [0.45, 0.58, 0.72, 1.0, 1.0, 1.0, 0.69], + [0.42, 0.54, 0.65, 1.0, 0.44, 1.0, 0.89], + [0.69, 1.0, 1.0, 1.0, 0.69, 1.0, 0.83], + [0.96, 1.0, 0.38, 1.0, 0.79, 1.0, 0.53], + [0.89, 1.0, 1.0, 1.0, 0.38, 1.0, 0.16], + [0.57, 0.78, 0.93, 1.0, 0.07, 1.0, 0.09], + [0.2, 0.52, 0.92, 1.0, 1.0, 1.0, 0.54], + [0.02, 0.35, 0.83, 0.9, 0.78, 0.81, 0.87], + ] + ) + assert_allclose(marked_proj, ref_result, atol=0.01) + + +@pytest.mark.parametrize('mode', ['thick', 'inner', 'outer', 'subpixel']) +def test_boundaries_constant_image(mode): + """A constant-valued image has not boundaries.""" + ones = np.ones((8, 8), dtype=int) + b = find_boundaries(ones, mode=mode) + assert np.all(b == 0) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_chan_vese.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_chan_vese.py new file mode 100644 index 0000000000000000000000000000000000000000..ba92a1e2e48fe1eb2ed3ec1b4bd5f9e7781f6c46 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_chan_vese.py @@ -0,0 +1,102 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from skimage._shared.utils import _supported_float_type +from skimage.segmentation import chan_vese + + +@pytest.mark.parametrize('dtype', [np.float32, np.float64]) +def test_chan_vese_flat_level_set(dtype): + # because the algorithm evolves the level set around the + # zero-level, it the level-set has no zero level, the algorithm + # will not produce results in theory. However, since a continuous + # approximation of the delta function is used, the algorithm + # still affects the entirety of the level-set. Therefore with + # infinite time, the segmentation will still converge. + img = np.zeros((10, 10), dtype=dtype) + img[3:6, 3:6] = 1 + ls = np.full((10, 10), 1000, dtype=dtype) + result = chan_vese(img, mu=0.0, tol=1e-3, init_level_set=ls) + assert_array_equal(result.astype(float), np.ones((10, 10))) + result = chan_vese(img, mu=0.0, tol=1e-3, init_level_set=-ls) + assert_array_equal(result.astype(float), np.zeros((10, 10))) + + +def test_chan_vese_small_disk_level_set(): + img = np.zeros((10, 10)) + img[3:6, 3:6] = 1 + result = chan_vese(img, mu=0.0, tol=1e-3, init_level_set="small disk") + assert_array_equal(result.astype(float), img) + + +def test_chan_vese_simple_shape(): + img = np.zeros((10, 10)) + img[3:6, 3:6] = 1 + result = chan_vese(img, mu=0.0, tol=1e-8).astype(float) + assert_array_equal(result, img) + + +@pytest.mark.parametrize('dtype', [np.uint8, np.float16, np.float32, np.float64]) +def test_chan_vese_extended_output(dtype): + img = np.zeros((10, 10), dtype=dtype) + img[3:6, 3:6] = 1 + result = chan_vese(img, mu=0.0, tol=1e-8, extended_output=True) + float_dtype = _supported_float_type(dtype) + assert result[1].dtype == float_dtype + assert all(arr.dtype == float_dtype for arr in result[2]) + assert_array_equal(len(result), 3) + + +def test_chan_vese_remove_noise(): + ref = np.zeros((10, 10)) + ref[1:6, 1:6] = np.array( + [ + [0, 1, 1, 1, 0], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [1, 1, 1, 1, 1], + [0, 1, 1, 1, 0], + ] + ) + img = ref.copy() + img[8, 3] = 1 + result = chan_vese( + img, mu=0.3, tol=1e-3, max_num_iter=100, dt=10, init_level_set="disk" + ).astype(float) + assert_array_equal(result, ref) + + +def test_chan_vese_incorrect_image_type(): + img = np.zeros((10, 10, 3)) + ls = np.zeros((10, 9)) + with pytest.raises(ValueError): + chan_vese(img, mu=0.0, init_level_set=ls) + + +def test_chan_vese_gap_closing(): + ref = np.zeros((20, 20)) + ref[8:15, :] = np.ones((7, 20)) + img = ref.copy() + img[:, 6] = np.zeros(20) + result = chan_vese( + img, mu=0.7, tol=1e-3, max_num_iter=1000, dt=1000, init_level_set="disk" + ).astype(float) + assert_array_equal(result, ref) + + +def test_chan_vese_incorrect_level_set(): + img = np.zeros((10, 10)) + ls = np.zeros((10, 9)) + with pytest.raises(ValueError): + chan_vese(img, mu=0.0, init_level_set=ls) + with pytest.raises(ValueError): + chan_vese(img, mu=0.0, init_level_set="a") + + +def test_chan_vese_blank_image(): + img = np.zeros((10, 10)) + level_set = np.random.rand(10, 10) + ref = level_set > 0 + result = chan_vese(img, mu=0.0, tol=0.0, init_level_set=level_set) + assert_array_equal(result, ref) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_clear_border.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_clear_border.py new file mode 100644 index 0000000000000000000000000000000000000000..4131997d09ab1c1a005a7aa0f8b1a8329ee25843 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_clear_border.py @@ -0,0 +1,180 @@ +import numpy as np +from skimage.segmentation import clear_border + +from skimage._shared.testing import assert_array_equal, assert_ + + +def test_clear_border(): + image = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 1, 0], + [1, 1, 0, 0, 1, 0, 0, 1, 0], + [1, 1, 0, 1, 0, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 0, 0], + [0, 1, 1, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0], + ] + ) + + # test default case + result = clear_border(image.copy()) + ref = image.copy() + ref[1:3, 0:2] = 0 + ref[0:2, -2] = 0 + assert_array_equal(result, ref) + + # test buffer + result = clear_border(image.copy(), 1) + assert_array_equal(result, np.zeros(result.shape)) + + # test background value + result = clear_border(image.copy(), buffer_size=1, bgval=2) + assert_array_equal(result, 2 * np.ones_like(image)) + + # test mask + mask = np.array( + [ + [0, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + [1, 1, 1, 1, 1, 1, 1, 1, 1], + ] + ).astype(bool) + result = clear_border(image.copy(), mask=mask) + ref = image.copy() + ref[1:3, 0:2] = 0 + assert_array_equal(result, ref) + + +def test_clear_border_3d(): + image = np.array( + [ + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 0, 0, 0]], + [[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0]], + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + ] + ) + # test default case + result = clear_border(image.copy()) + ref = image.copy() + ref[0, 3, 0] = 0 + assert_array_equal(result, ref) + + # test buffer + result = clear_border(image.copy(), 1) + assert_array_equal(result, np.zeros(result.shape)) + + # test background value + result = clear_border(image.copy(), buffer_size=1, bgval=2) + assert_array_equal(result, 2 * np.ones_like(image)) + + +def test_clear_border_non_binary(): + image = np.array( + [[1, 2, 3, 1, 2], [3, 3, 5, 4, 2], [3, 4, 5, 4, 2], [3, 3, 2, 1, 2]] + ) + + result = clear_border(image) + expected = np.array( + [[0, 0, 0, 0, 0], [0, 0, 5, 4, 0], [0, 4, 5, 4, 0], [0, 0, 0, 0, 0]] + ) + + assert_array_equal(result, expected) + assert_(not np.all(image == result)) + + +def test_clear_border_non_binary_3d(): + image3d = np.array( + [ + [[1, 2, 3, 1, 2], [3, 3, 3, 4, 2], [3, 4, 3, 4, 2], [3, 3, 2, 1, 2]], + [[1, 2, 3, 1, 2], [3, 3, 5, 4, 2], [3, 4, 5, 4, 2], [3, 3, 2, 1, 2]], + [[1, 2, 3, 1, 2], [3, 3, 3, 4, 2], [3, 4, 3, 4, 2], [3, 3, 2, 1, 2]], + ] + ) + + result = clear_border(image3d) + expected = np.array( + [ + [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], + [[0, 0, 0, 0, 0], [0, 0, 5, 0, 0], [0, 0, 5, 0, 0], [0, 0, 0, 0, 0]], + [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], + ] + ) + + assert_array_equal(result, expected) + assert_(not np.all(image3d == result)) + + +def test_clear_border_non_binary_inplace(): + image = np.array( + [[1, 2, 3, 1, 2], [3, 3, 5, 4, 2], [3, 4, 5, 4, 2], [3, 3, 2, 1, 2]] + ) + + result = clear_border(image, out=image) + expected = np.array( + [[0, 0, 0, 0, 0], [0, 0, 5, 4, 0], [0, 4, 5, 4, 0], [0, 0, 0, 0, 0]] + ) + + assert_array_equal(result, expected) + assert_array_equal(image, result) + + +def test_clear_border_non_binary_inplace_3d(): + image3d = np.array( + [ + [[1, 2, 3, 1, 2], [3, 3, 3, 4, 2], [3, 4, 3, 4, 2], [3, 3, 2, 1, 2]], + [[1, 2, 3, 1, 2], [3, 3, 5, 4, 2], [3, 4, 5, 4, 2], [3, 3, 2, 1, 2]], + [[1, 2, 3, 1, 2], [3, 3, 3, 4, 2], [3, 4, 3, 4, 2], [3, 3, 2, 1, 2]], + ] + ) + + result = clear_border(image3d, out=image3d) + expected = np.array( + [ + [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], + [[0, 0, 0, 0, 0], [0, 0, 5, 0, 0], [0, 0, 5, 0, 0], [0, 0, 0, 0, 0]], + [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], + ] + ) + + assert_array_equal(result, expected) + assert_array_equal(image3d, result) + + +def test_clear_border_non_binary_out(): + image = np.array( + [[1, 2, 3, 1, 2], [3, 3, 5, 4, 2], [3, 4, 5, 4, 2], [3, 3, 2, 1, 2]] + ) + out = image.copy() + result = clear_border(image, out=out) + expected = np.array( + [[0, 0, 0, 0, 0], [0, 0, 5, 4, 0], [0, 4, 5, 4, 0], [0, 0, 0, 0, 0]] + ) + + assert_array_equal(result, expected) + assert_array_equal(out, result) + + +def test_clear_border_non_binary_out_3d(): + image3d = np.array( + [ + [[1, 2, 3, 1, 2], [3, 3, 3, 4, 2], [3, 4, 3, 4, 2], [3, 3, 2, 1, 2]], + [[1, 2, 3, 1, 2], [3, 3, 5, 4, 2], [3, 4, 5, 4, 2], [3, 3, 2, 1, 2]], + [[1, 2, 3, 1, 2], [3, 3, 3, 4, 2], [3, 4, 3, 4, 2], [3, 3, 2, 1, 2]], + ] + ) + out = image3d.copy() + + result = clear_border(image3d, out=out) + expected = np.array( + [ + [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], + [[0, 0, 0, 0, 0], [0, 0, 5, 0, 0], [0, 0, 5, 0, 0], [0, 0, 0, 0, 0]], + [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], + ] + ) + + assert_array_equal(result, expected) + assert_array_equal(out, result) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_expand_labels.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_expand_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..4d589a4982a0193093a38f290fca45d3b03b8790 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_expand_labels.py @@ -0,0 +1,182 @@ +from scipy import ndimage as ndi +from skimage import data + +import numpy as np + +from skimage import measure +from skimage.segmentation._expand_labels import expand_labels + +from skimage._shared import testing +from skimage._shared.testing import assert_array_equal + +SAMPLE1D = np.array([0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0]) +SAMPLE1D_EXPANDED_3 = np.array([4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]) + +# Some pixels are important edge cases with undefined behaviour: +# these are the pixels that are at the same distance from +# multiple labels. Ideally the label would be chosen at random +# to avoid bias, but as we are relying on the index map returned +# by the scipy.ndimage distance transform, what actually happens +# is determined by the upstream implementation of the distance +# tansform, thus we don't give any guarantees for the edge case pixels. +# +# Regardless, it seems prudent to have a test including an edge case +# so we can detect whether future upstream changes in scipy.ndimage +# modify the behaviour. + +EDGECASE1D = np.array([0, 0, 4, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0]) +EDGECASE1D_EXPANDED_3 = np.array([4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]) + +SAMPLE2D = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] +) + +SAMPLE2D_EXPANDED_3 = np.array( + [ + [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 1, 1, 0, 0, 2, 0], + [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2], + [1, 1, 1, 1, 1, 1, 0, 2, 2, 2, 2], + [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2], + [1, 1, 1, 1, 1, 0, 2, 2, 2, 2, 2], + [1, 1, 1, 1, 1, 0, 0, 2, 2, 2, 2], + [0, 0, 1, 0, 0, 0, 0, 2, 2, 2, 2], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0], + ] +) + +# non-integer expansion +SAMPLE2D_EXPANDED_1_5 = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], + [1, 1, 1, 1, 1, 0, 0, 0, 2, 2, 2], + [1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2], + [0, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2], + [0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] +) + + +EDGECASE2D = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 0], + [0, 0, 1, 1, 0, 2, 2, 0, 0, 0, 0], + [0, 1, 1, 1, 0, 2, 0, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], + ] +) + +EDGECASE2D_EXPANDED_4 = np.array( + [ + [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 0], + [1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2], + [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], + [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0], + [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0], + ] +) + +SAMPLE3D = np.array( + [ + [[0, 0, 0, 0], [0, 3, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + [[0, 0, 0, 0], [0, 3, 3, 0], [0, 0, 0, 0], [0, 0, 0, 0]], + [[0, 0, 0, 0], [0, 3, 0, 0], [0, 0, 0, 0], [0, 0, 5, 0]], + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 5, 0]], + ] +) + +SAMPLE3D_EXPANDED_2 = np.array( + [ + [[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [0, 3, 5, 0]], + [[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3], [0, 5, 5, 5]], + [[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 5, 5], [5, 5, 5, 5]], + [[3, 3, 3, 0], [3, 3, 3, 0], [3, 3, 5, 5], [5, 5, 5, 5]], + ] +) +SAMPLE3D_EXPAND_SPACING = np.array( + [ + [[0, 3, 0, 0], [3, 3, 3, 0], [0, 3, 0, 0], [0, 0, 0, 0]], + [[0, 3, 3, 0], [3, 3, 3, 3], [0, 3, 3, 0], [0, 0, 0, 0]], + [[0, 3, 0, 0], [3, 3, 3, 0], [0, 3, 5, 0], [0, 5, 5, 5]], + [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 5, 0], [0, 5, 5, 5]], + ] +) + +SAMPLE_EDGECASE_BEHAVIOUR = np.array([[0, 1, 0, 0], [2, 0, 0, 0], [0, 3, 0, 0]]) + + +@testing.parametrize( + "input_array, expected_output, expand_distance, spacing", + [ + (SAMPLE1D, SAMPLE1D_EXPANDED_3, 3, 1), + (SAMPLE2D, SAMPLE2D_EXPANDED_3, 3, 1), + (SAMPLE2D, SAMPLE2D_EXPANDED_1_5, 1.5, 1), + (EDGECASE1D, EDGECASE1D_EXPANDED_3, 3, 1), + (EDGECASE2D, EDGECASE2D_EXPANDED_4, 4, 1), + (SAMPLE3D, SAMPLE3D_EXPANDED_2, 2, 1), + (SAMPLE3D, SAMPLE3D_EXPAND_SPACING, 1, [2, 1, 1]), + ], +) +def test_expand_labels(input_array, expected_output, expand_distance, spacing): + expanded = expand_labels(input_array, expand_distance, spacing) + assert_array_equal(expanded, expected_output) + + +@testing.parametrize('ndim', [2, 3]) +@testing.parametrize('distance', range(6)) +def test_binary_blobs(ndim, distance): + """Check some invariants with label expansion. + + - New labels array should exactly contain the original labels array. + - Distance to old labels array within new labels should never exceed input + distance. + - Distance beyond the expanded labels should always exceed the input + distance. + """ + img = data.binary_blobs(length=64, blob_size_fraction=0.05, n_dim=ndim) + labels = measure.label(img) + expanded = expand_labels(labels, distance=distance) + original_mask = labels != 0 + assert_array_equal(labels[original_mask], expanded[original_mask]) + expanded_only_mask = (expanded - labels).astype(bool) + distance_map = ndi.distance_transform_edt(~original_mask) + expanded_distances = distance_map[expanded_only_mask] + if expanded_distances.size > 0: + assert np.all(expanded_distances <= distance) + beyond_expanded_distances = distance_map[~expanded.astype(bool)] + if beyond_expanded_distances.size > 0: + assert np.all(beyond_expanded_distances > distance) + + +def test_edge_case_behaviour(): + """Check edge case behavior to detect upstream changes + + For edge cases where a pixel has the same distance to several regions, + lexicographical order seems to determine which region gets to expand + into this pixel given the current upstream behaviour in + scipy.ndimage.distance_map_edt. + + As a result, we expect different results when transposing the array. + If this test fails, something has changed upstream. + """ + expanded = expand_labels(SAMPLE_EDGECASE_BEHAVIOUR, 1) + expanded_transpose = expand_labels(SAMPLE_EDGECASE_BEHAVIOUR.T, 1) + assert not np.all(expanded == expanded_transpose.T) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_felzenszwalb.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_felzenszwalb.py new file mode 100644 index 0000000000000000000000000000000000000000..88597f024203b41b904d8982807f5aadfa006a79 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_felzenszwalb.py @@ -0,0 +1,90 @@ +import numpy as np +from skimage import data +from skimage.segmentation import felzenszwalb + +from skimage._shared import testing +from skimage._shared.testing import ( + assert_greater, + run_in_parallel, + assert_equal, + assert_array_equal, + assert_warns, + assert_no_warnings, +) + + +@run_in_parallel() +def test_grey(): + # very weak tests. + img = np.zeros((20, 21)) + img[:10, 10:] = 0.2 + img[10:, :10] = 0.4 + img[10:, 10:] = 0.6 + seg = felzenszwalb(img, sigma=0) + # we expect 4 segments: + assert_equal(len(np.unique(seg)), 4) + # that mostly respect the 4 regions: + for i in range(4): + hist = np.histogram(img[seg == i], bins=[0, 0.1, 0.3, 0.5, 1])[0] + assert_greater(hist[i], 40) + + +def test_minsize(): + # single-channel: + img = data.coins()[20:168, 0:128] + for min_size in np.arange(10, 100, 10): + segments = felzenszwalb(img, min_size=min_size, sigma=3) + counts = np.bincount(segments.ravel()) + # actually want to test greater or equal. + assert_greater(counts.min() + 1, min_size) + # multi-channel: + coffee = data.coffee()[::4, ::4] + for min_size in np.arange(10, 100, 10): + segments = felzenszwalb(coffee, min_size=min_size, sigma=3) + counts = np.bincount(segments.ravel()) + # actually want to test greater or equal. + assert_greater(counts.min() + 1, min_size) + + +@testing.parametrize('channel_axis', [0, -1]) +def test_3D(channel_axis): + grey_img = np.zeros((10, 10)) + rgb_img = np.zeros((10, 10, 3)) + three_d_img = np.zeros((10, 10, 10)) + + rgb_img = np.moveaxis(rgb_img, -1, channel_axis) + with assert_no_warnings(): + felzenszwalb(grey_img, channel_axis=-1) + felzenszwalb(grey_img, channel_axis=None) + felzenszwalb(rgb_img, channel_axis=channel_axis) + with assert_warns(RuntimeWarning): + felzenszwalb(three_d_img, channel_axis=channel_axis) + with testing.raises(ValueError): + felzenszwalb(rgb_img, channel_axis=None) + felzenszwalb(three_d_img, channel_axis=None) + + +def test_color(): + # very weak tests. + img = np.zeros((20, 21, 3)) + img[:10, :10, 0] = 1 + img[10:, :10, 1] = 1 + img[10:, 10:, 2] = 1 + seg = felzenszwalb(img, sigma=0) + # we expect 4 segments: + assert_equal(len(np.unique(seg)), 4) + assert_array_equal(seg[:10, :10], 0) + assert_array_equal(seg[10:, :10], 2) + assert_array_equal(seg[:10, 10:], 1) + assert_array_equal(seg[10:, 10:], 3) + + +def test_merging(): + # test region merging in the post-processing step + img = np.array([[0, 0.3], [0.7, 1]]) + # With scale=0, only the post-processing is performed. + seg = felzenszwalb(img, scale=0, sigma=0, min_size=2) + # we expect 2 segments: + assert_equal(len(np.unique(seg)), 2) + assert_array_equal(seg[0, :], 0) + assert_array_equal(seg[1, :], 1) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_join.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_join.py new file mode 100644 index 0000000000000000000000000000000000000000..2db2d1204d29334809853a0ed75a89f4a2ed99f2 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_join.py @@ -0,0 +1,219 @@ +import numpy as np +from skimage.segmentation import join_segmentations, relabel_sequential + +from skimage._shared import testing +from skimage._shared.testing import assert_array_equal +import pytest + + +@pytest.mark.parametrize("dtype", [int, np.uint16, np.uint]) +def test_join_segmentations(dtype): + s1 = np.array([[0, 0, 1, 1], [0, 2, 1, 1], [2, 2, 2, 1]], dtype=dtype) + s2 = np.array([[0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 1]], dtype=dtype) + + # test correct join + # NOTE: technically, equality to j_ref is not required, only that there + # is a one-to-one mapping between j and j_ref. I don't know of an easy way + # to check this (i.e. not as error-prone as the function being tested) + j = join_segmentations(s1, s2) + j_ref = np.array([[0, 1, 3, 2], [0, 5, 3, 2], [4, 5, 5, 3]]) + assert_array_equal(j, j_ref) + + # test correct mapping + j, m1, m2 = join_segmentations(s1, s2, return_mapping=True) + assert_array_equal(m1[j], s1) + assert_array_equal(m2[j], s2) + + # test correct exception when arrays are different shapes + s3 = np.array([[0, 0, 1, 1], [0, 2, 2, 1]]) + with testing.raises(ValueError): + join_segmentations(s1, s3) + + +def _check_maps(ar, ar_relab, fw, inv): + assert_array_equal(fw[ar], ar_relab) + assert_array_equal(inv[ar_relab], ar) + + +def test_relabel_sequential_offset1(): + ar = np.array([1, 1, 5, 5, 8, 99, 42]) + ar_relab, fw, inv = relabel_sequential(ar) + _check_maps(ar, ar_relab, fw, inv) + ar_relab_ref = np.array([1, 1, 2, 2, 3, 5, 4]) + assert_array_equal(ar_relab, ar_relab_ref) + fw_ref = np.zeros(100, int) + fw_ref[1] = 1 + fw_ref[5] = 2 + fw_ref[8] = 3 + fw_ref[42] = 4 + fw_ref[99] = 5 + assert_array_equal(fw, fw_ref) + inv_ref = np.array([0, 1, 5, 8, 42, 99]) + assert_array_equal(inv, inv_ref) + + +def test_relabel_sequential_offset5(): + ar = np.array([1, 1, 5, 5, 8, 99, 42]) + ar_relab, fw, inv = relabel_sequential(ar, offset=5) + _check_maps(ar, ar_relab, fw, inv) + ar_relab_ref = np.array([5, 5, 6, 6, 7, 9, 8]) + assert_array_equal(ar_relab, ar_relab_ref) + fw_ref = np.zeros(100, int) + fw_ref[1] = 5 + fw_ref[5] = 6 + fw_ref[8] = 7 + fw_ref[42] = 8 + fw_ref[99] = 9 + assert_array_equal(fw, fw_ref) + inv_ref = np.array([0, 0, 0, 0, 0, 1, 5, 8, 42, 99]) + assert_array_equal(inv, inv_ref) + + +def test_relabel_sequential_offset5_with0(): + ar = np.array([1, 1, 5, 5, 8, 99, 42, 0]) + ar_relab, fw, inv = relabel_sequential(ar, offset=5) + _check_maps(ar, ar_relab, fw, inv) + ar_relab_ref = np.array([5, 5, 6, 6, 7, 9, 8, 0]) + assert_array_equal(ar_relab, ar_relab_ref) + fw_ref = np.zeros(100, int) + fw_ref[1] = 5 + fw_ref[5] = 6 + fw_ref[8] = 7 + fw_ref[42] = 8 + fw_ref[99] = 9 + assert_array_equal(fw, fw_ref) + inv_ref = np.array([0, 0, 0, 0, 0, 1, 5, 8, 42, 99]) + assert_array_equal(inv, inv_ref) + + +def test_relabel_sequential_dtype(): + ar = np.array([1, 1, 5, 5, 8, 99, 42, 0], dtype=np.uint8) + ar_relab, fw, inv = relabel_sequential(ar, offset=5) + _check_maps(ar.astype(int), ar_relab, fw, inv) + ar_relab_ref = np.array([5, 5, 6, 6, 7, 9, 8, 0]) + assert_array_equal(ar_relab, ar_relab_ref) + fw_ref = np.zeros(100, int) + fw_ref[1] = 5 + fw_ref[5] = 6 + fw_ref[8] = 7 + fw_ref[42] = 8 + fw_ref[99] = 9 + assert_array_equal(fw, fw_ref) + inv_ref = np.array([0, 0, 0, 0, 0, 1, 5, 8, 42, 99]) + assert_array_equal(inv, inv_ref) + + +def test_relabel_sequential_signed_overflow(): + imax = np.iinfo(np.int32).max + labels = np.array([0, 1, 99, 42, 42], dtype=np.int32) + output, fw, inv = relabel_sequential(labels, offset=imax) + reference = np.array([0, imax, imax + 2, imax + 1, imax + 1], dtype=np.uint32) + assert_array_equal(output, reference) + assert output.dtype == reference.dtype + + +def test_very_large_labels(): + imax = np.iinfo(np.int64).max + labels = np.array([0, 1, imax, 42, 42], dtype=np.int64) + output, fw, inv = relabel_sequential(labels, offset=imax) + assert np.max(output) == imax + 2 + + +@pytest.mark.parametrize( + 'dtype', + ( + np.byte, + np.short, + np.intc, + int, + np.longlong, + np.ubyte, + np.ushort, + np.uintc, + np.uint, + np.ulonglong, + ), +) +@pytest.mark.parametrize('data_already_sequential', (False, True)) +def test_relabel_sequential_int_dtype_stability(data_already_sequential, dtype): + if data_already_sequential: + ar = np.array([1, 3, 0, 2, 5, 4], dtype=dtype) + else: + ar = np.array([1, 1, 5, 5, 8, 99, 42, 0], dtype=dtype) + assert all(a.dtype == dtype for a in relabel_sequential(ar)) + + +def test_relabel_sequential_int_dtype_overflow(): + ar = np.array([1, 3, 0, 2, 5, 4], dtype=np.uint8) + offset = 254 + ar_relab, fw, inv = relabel_sequential(ar, offset=offset) + _check_maps(ar, ar_relab, fw, inv) + assert all(a.dtype == np.uint16 for a in (ar_relab, fw)) + assert inv.dtype == ar.dtype + ar_relab_ref = np.where(ar > 0, ar.astype(int) + offset - 1, 0) + assert_array_equal(ar_relab, ar_relab_ref) + + +def test_relabel_sequential_negative_values(): + ar = np.array([1, 1, 5, -5, 8, 99, 42, 0]) + with pytest.raises(ValueError): + relabel_sequential(ar) + + +@pytest.mark.parametrize('offset', (0, -3)) +@pytest.mark.parametrize('data_already_sequential', (False, True)) +def test_relabel_sequential_nonpositive_offset(data_already_sequential, offset): + if data_already_sequential: + ar = np.array([1, 3, 0, 2, 5, 4]) + else: + ar = np.array([1, 1, 5, 5, 8, 99, 42, 0]) + with pytest.raises(ValueError): + relabel_sequential(ar, offset=offset) + + +@pytest.mark.parametrize('offset', (1, 5)) +@pytest.mark.parametrize('with0', (False, True)) +@pytest.mark.parametrize('input_starts_at_offset', (False, True)) +def test_relabel_sequential_already_sequential(offset, with0, input_starts_at_offset): + if with0: + ar = np.array([1, 3, 0, 2, 5, 4]) + else: + ar = np.array([1, 3, 2, 5, 4]) + if input_starts_at_offset: + ar[ar > 0] += offset - 1 + ar_relab, fw, inv = relabel_sequential(ar, offset=offset) + _check_maps(ar, ar_relab, fw, inv) + if input_starts_at_offset: + ar_relab_ref = ar + else: + ar_relab_ref = np.where(ar > 0, ar + offset - 1, 0) + assert_array_equal(ar_relab, ar_relab_ref) + + +def test_incorrect_input_dtype(): + labels = np.array([0, 2, 2, 1, 1, 8], dtype=float) + with testing.raises(TypeError): + _ = relabel_sequential(labels) + + +def test_arraymap_call(): + ar = np.array([1, 1, 5, 5, 8, 99, 42, 0], dtype=np.intp) + relabeled, fw, inv = relabel_sequential(ar) + testing.assert_array_equal(relabeled, fw(ar)) + testing.assert_array_equal(ar, inv(relabeled)) + + +def test_arraymap_len(): + ar = np.array([1, 1, 5, 5, 8, 99, 42, 0], dtype=np.intp) + relabeled, fw, inv = relabel_sequential(ar) + assert len(fw) == 100 + assert len(fw) == len(np.array(fw)) + assert len(inv) == 6 + assert len(inv) == len(np.array(inv)) + + +def test_arraymap_set(): + ar = np.array([1, 1, 5, 5, 8, 99, 42, 0], dtype=np.intp) + relabeled, fw, inv = relabel_sequential(ar) + fw[72] = 6 + assert fw[72] == 6 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_morphsnakes.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_morphsnakes.py new file mode 100644 index 0000000000000000000000000000000000000000..7d8ad2f2a7a8343c6efe2cd68c26ba29593fbffa --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_morphsnakes.py @@ -0,0 +1,152 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from skimage.segmentation import ( + disk_level_set, + inverse_gaussian_gradient, + morphological_chan_vese, + morphological_geodesic_active_contour, +) + + +def gaussian_blob(): + coords = np.mgrid[-5:6, -5:6] + sqrdistances = (coords**2).sum(0) + return np.exp(-sqrdistances / 10) + + +def test_morphsnakes_incorrect_image_shape(): + img = np.zeros((10, 10, 3)) + ls = np.zeros((10, 9)) + + with pytest.raises(ValueError): + morphological_chan_vese(img, num_iter=1, init_level_set=ls) + with pytest.raises(ValueError): + morphological_geodesic_active_contour(img, num_iter=1, init_level_set=ls) + + +def test_morphsnakes_incorrect_ndim(): + img = np.zeros((4, 4, 4, 4)) + ls = np.zeros((4, 4, 4, 4)) + + with pytest.raises(ValueError): + morphological_chan_vese(img, num_iter=1, init_level_set=ls) + with pytest.raises(ValueError): + morphological_geodesic_active_contour(img, num_iter=1, init_level_set=ls) + + +def test_morphsnakes_black(): + img = np.zeros((11, 11)) + ls = disk_level_set(img.shape, center=(5, 5), radius=3) + + ref_zeros = np.zeros(img.shape, dtype=np.int8) + ref_ones = np.ones(img.shape, dtype=np.int8) + + acwe_ls = morphological_chan_vese(img, num_iter=6, init_level_set=ls) + assert_array_equal(acwe_ls, ref_zeros) + + gac_ls = morphological_geodesic_active_contour(img, num_iter=6, init_level_set=ls) + assert_array_equal(gac_ls, ref_zeros) + + gac_ls2 = morphological_geodesic_active_contour( + img, num_iter=6, init_level_set=ls, balloon=1, threshold=-1, smoothing=0 + ) + assert_array_equal(gac_ls2, ref_ones) + + assert acwe_ls.dtype == gac_ls.dtype == gac_ls2.dtype == np.int8 + + +def test_morphsnakes_simple_shape_chan_vese(): + img = gaussian_blob() + ls1 = disk_level_set(img.shape, center=(5, 5), radius=3) + ls2 = disk_level_set(img.shape, center=(5, 5), radius=6) + + acwe_ls1 = morphological_chan_vese(img, num_iter=10, init_level_set=ls1) + acwe_ls2 = morphological_chan_vese(img, num_iter=10, init_level_set=ls2) + + assert_array_equal(acwe_ls1, acwe_ls2) + + assert acwe_ls1.dtype == acwe_ls2.dtype == np.int8 + + +def test_morphsnakes_simple_shape_geodesic_active_contour(): + img = (disk_level_set((11, 11), center=(5, 5), radius=3.5)).astype(float) + gimg = inverse_gaussian_gradient(img, alpha=10.0, sigma=1.0) + ls = disk_level_set(img.shape, center=(5, 5), radius=6) + + ref = np.array( + [ + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ], + dtype=np.int8, + ) + + gac_ls = morphological_geodesic_active_contour( + gimg, num_iter=10, init_level_set=ls, balloon=-1 + ) + assert_array_equal(gac_ls, ref) + assert gac_ls.dtype == np.int8 + + +def test_init_level_sets(): + image = np.zeros((6, 6)) + checkerboard_ls = morphological_chan_vese(image, 0, 'checkerboard') + checkerboard_ref = np.array( + [ + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [0, 0, 0, 0, 0, 1], + [1, 1, 1, 1, 1, 0], + ], + dtype=np.int8, + ) + + disk_ls = morphological_geodesic_active_contour(image, 0, 'disk') + disk_ref = np.array( + [ + [0, 0, 0, 0, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1], + [0, 1, 1, 1, 1, 1], + [0, 0, 1, 1, 1, 0], + ], + dtype=np.int8, + ) + + assert_array_equal(checkerboard_ls, checkerboard_ref) + assert_array_equal(disk_ls, disk_ref) + + +def test_morphsnakes_3d(): + image = np.zeros((7, 7, 7)) + + evolution = [] + + def callback(x): + evolution.append(x.sum()) + + ls = morphological_chan_vese(image, 5, 'disk', iter_callback=callback) + + # Check that the initial disk level set is correct + assert evolution[0] == 81 + + # Check that the final level set is correct + assert ls.sum() == 0 + + # Check that the contour is shrinking at every iteration + for v1, v2 in zip(evolution[:-1], evolution[1:]): + assert v1 >= v2 diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_quickshift.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_quickshift.py new file mode 100644 index 0000000000000000000000000000000000000000..c72e330ba526cc5b5f7613ec55abed1150399487 --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_quickshift.py @@ -0,0 +1,79 @@ +import numpy as np +import pytest +from skimage.segmentation import quickshift + +from skimage._shared import testing +from skimage._shared.testing import ( + assert_greater, + run_in_parallel, + assert_equal, + assert_array_equal, +) + + +@run_in_parallel() +@testing.parametrize('dtype', [np.float32, np.float64]) +def test_grey(dtype): + rng = np.random.default_rng(0) + img = np.zeros((20, 21)) + img[:10, 10:] = 0.2 + img[10:, :10] = 0.4 + img[10:, 10:] = 0.6 + img += 0.05 * rng.normal(size=img.shape) + img = img.astype(dtype, copy=False) + seg = quickshift(img, kernel_size=2, max_dist=3, rng=0, convert2lab=False, sigma=0) + quickshift(img, kernel_size=2, max_dist=3, rng=0, convert2lab=False, sigma=0) + # we expect 4 segments: + assert_equal(len(np.unique(seg)), 4) + # that mostly respect the 4 regions: + for i in range(4): + hist = np.histogram(img[seg == i], bins=[0, 0.1, 0.3, 0.5, 1])[0] + assert_greater(hist[i], 20) + + +@testing.parametrize('dtype', [np.float32, np.float64]) +@testing.parametrize('channel_axis', [-3, -2, -1, 0, 1, 2]) +def test_color(dtype, channel_axis): + rng = np.random.default_rng(583428449) + img = np.zeros((20, 21, 3)) + img[:10, :10, 0] = 1 + img[10:, :10, 1] = 1 + img[10:, 10:, 2] = 1 + img += 0.01 * rng.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + img = img.astype(dtype, copy=False) + + img = np.moveaxis(img, source=-1, destination=channel_axis) + seg = quickshift( + img, rng=0, max_dist=30, kernel_size=10, sigma=0, channel_axis=channel_axis + ) + # we expect 4 segments: + assert_equal(len(np.unique(seg)), 4) + assert_array_equal(seg[:10, :10], 1) + assert_array_equal(seg[10:, :10], 3) + assert_array_equal(seg[:10, 10:], 0) + assert_array_equal(seg[10:, 10:], 2) + + seg2 = quickshift( + img, + kernel_size=1, + max_dist=2, + rng=0, + convert2lab=False, + sigma=0, + channel_axis=channel_axis, + ) + # very oversegmented: + assert len(np.unique(seg2)) > 10 + # still don't cross lines + assert (seg2[9, :] != seg2[10, :]).all() + assert (seg2[:, 9] != seg2[:, 10]).all() + + +def test_convert2lab_not_rgb(): + img = np.zeros((20, 21, 2)) + with pytest.raises( + ValueError, match="Only RGB images can be converted to Lab space" + ): + quickshift(img, convert2lab=True) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_random_walker.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_random_walker.py new file mode 100644 index 0000000000000000000000000000000000000000..0b74d9dbcfcb00262e58197eb936bc0ad7cee0ba --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_random_walker.py @@ -0,0 +1,573 @@ +import numpy as np + +from skimage._shared import testing +from skimage._shared._warnings import expected_warnings +from skimage._shared.testing import xfail, arch32, is_wasm +from skimage.segmentation import random_walker +from skimage.transform import resize + +PYAMG_MISSING_WARNING = r'pyamg|\A\Z' + + +def make_2d_syntheticdata(lx, ly=None): + if ly is None: + ly = lx + np.random.seed(1234) + data = np.zeros((lx, ly)) + 0.1 * np.random.randn(lx, ly) + small_l = int(lx // 5) + data[ + lx // 2 - small_l : lx // 2 + small_l, ly // 2 - small_l : ly // 2 + small_l + ] = 1 + data[ + lx // 2 - small_l + 1 : lx // 2 + small_l - 1, + ly // 2 - small_l + 1 : ly // 2 + small_l - 1, + ] = 0.1 * np.random.randn(2 * small_l - 2, 2 * small_l - 2) + data[lx // 2 - small_l, ly // 2 - small_l // 8 : ly // 2 + small_l // 8] = 0 + seeds = np.zeros_like(data) + seeds[lx // 5, ly // 5] = 1 + seeds[lx // 2 + small_l // 4, ly // 2 - small_l // 4] = 2 + return data, seeds + + +def make_3d_syntheticdata(lx, ly=None, lz=None): + if ly is None: + ly = lx + if lz is None: + lz = lx + np.random.seed(1234) + data = np.zeros((lx, ly, lz)) + 0.1 * np.random.randn(lx, ly, lz) + small_l = int(lx // 5) + data[ + lx // 2 - small_l : lx // 2 + small_l, + ly // 2 - small_l : ly // 2 + small_l, + lz // 2 - small_l : lz // 2 + small_l, + ] = 1 + data[ + lx // 2 - small_l + 1 : lx // 2 + small_l - 1, + ly // 2 - small_l + 1 : ly // 2 + small_l - 1, + lz // 2 - small_l + 1 : lz // 2 + small_l - 1, + ] = 0 + # make a hole + hole_size = np.max([1, small_l // 8]) + data[ + lx // 2 - small_l, + ly // 2 - hole_size : ly // 2 + hole_size, + lz // 2 - hole_size : lz // 2 + hole_size, + ] = 0 + seeds = np.zeros_like(data) + seeds[lx // 5, ly // 5, lz // 5] = 1 + seeds[lx // 2 + small_l // 4, ly // 2 - small_l // 4, lz // 2 - small_l // 4] = 2 + return data, seeds + + +@testing.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_2d_bf(dtype): + lx = 70 + ly = 100 + + # have to use a smaller beta to avoid warning with lower precision input + beta = 90 if dtype == np.float64 else 25 + + data, labels = make_2d_syntheticdata(lx, ly) + data = data.astype(dtype, copy=False) + labels_bf = random_walker(data, labels, beta=beta, mode='bf') + assert (labels_bf[25:45, 40:60] == 2).all() + assert data.shape == labels.shape + full_prob_bf = random_walker( + data, labels, beta=beta, mode='bf', return_full_prob=True + ) + assert (full_prob_bf[1, 25:45, 40:60] >= full_prob_bf[0, 25:45, 40:60]).all() + assert data.shape == labels.shape + # Now test with more than two labels + labels[55, 80] = 3 + full_prob_bf = random_walker( + data, labels, beta=beta, mode='bf', return_full_prob=True + ) + assert (full_prob_bf[1, 25:45, 40:60] >= full_prob_bf[0, 25:45, 40:60]).all() + assert len(full_prob_bf) == 3 + assert data.shape == labels.shape + + +@testing.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_2d_cg(dtype): + lx = 70 + ly = 100 + data, labels = make_2d_syntheticdata(lx, ly) + data = data.astype(dtype, copy=False) + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + labels_cg = random_walker(data, labels, beta=90, mode='cg') + assert (labels_cg[25:45, 40:60] == 2).all() + assert data.shape == labels.shape + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + full_prob = random_walker( + data, labels, beta=90, mode='cg', return_full_prob=True + ) + assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all() + assert data.shape == labels.shape + + +@testing.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_2d_cg_mg(dtype): + lx = 70 + ly = 100 + data, labels = make_2d_syntheticdata(lx, ly) + data = data.astype(dtype, copy=False) + anticipated_warnings = [ + f'Changing the sparsity structure|conversion of A to CSR|scipy.sparse.sparsetools|' + f'{PYAMG_MISSING_WARNING}|scipy.sparse.linalg.cg' + ] + with expected_warnings(anticipated_warnings): + labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') + assert (labels_cg_mg[25:45, 40:60] == 2).all() + assert data.shape == labels.shape + with expected_warnings(anticipated_warnings): + full_prob = random_walker( + data, labels, beta=90, mode='cg_mg', return_full_prob=True + ) + assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all() + assert data.shape == labels.shape + + +@testing.parametrize('dtype', [np.float16, np.float32, np.float64]) +def test_2d_cg_j(dtype): + lx = 70 + ly = 100 + data, labels = make_2d_syntheticdata(lx, ly) + data = data.astype(dtype, copy=False) + labels_cg = random_walker(data, labels, beta=90, mode='cg_j') + assert (labels_cg[25:45, 40:60] == 2).all() + assert data.shape == labels.shape + full_prob = random_walker(data, labels, beta=90, mode='cg_j', return_full_prob=True) + assert (full_prob[1, 25:45, 40:60] >= full_prob[0, 25:45, 40:60]).all() + assert data.shape == labels.shape + + +def test_types(): + lx = 70 + ly = 100 + data, labels = make_2d_syntheticdata(lx, ly) + data = 255 * (data - data.min()) // (data.max() - data.min()) + data = data.astype(np.uint8) + anticipated_warnings = [ + f"Changing the sparsity structure|conversion of A to CSR|{PYAMG_MISSING_WARNING}|scipy.sparse.linalg.cg" + ] + with expected_warnings(anticipated_warnings): + labels_cg_mg = random_walker(data, labels, beta=90, mode='cg_mg') + assert (labels_cg_mg[25:45, 40:60] == 2).all() + assert data.shape == labels.shape + + +def test_reorder_labels(): + lx = 70 + ly = 100 + data, labels = make_2d_syntheticdata(lx, ly) + labels[labels == 2] = 4 + labels_bf = random_walker(data, labels, beta=90, mode='bf') + assert (labels_bf[25:45, 40:60] == 2).all() + assert data.shape == labels.shape + + +def test_2d_inactive(): + lx = 70 + ly = 100 + data, labels = make_2d_syntheticdata(lx, ly) + labels[10:20, 10:20] = -1 + labels[46:50, 33:38] = -2 + labels = random_walker(data, labels, beta=90) + assert (labels.reshape((lx, ly))[25:45, 40:60] == 2).all() + assert data.shape == labels.shape + + +def test_2d_laplacian_size(): + # test case from: https://github.com/scikit-image/scikit-image/issues/5034 + # The markers here were modified from the ones in the original issue to + # avoid a singular matrix, but still reproduce the issue. + data = np.asarray( + [[12823, 12787, 12710], [12883, 13425, 12067], [11934, 11929, 12309]] + ) + markers = np.asarray([[0, -1, 2], [0, -1, 0], [1, 0, -1]]) + expected_labels = np.asarray([[1, -1, 2], [1, -1, 2], [1, 1, -1]]) + labels = random_walker(data, markers, beta=10) + np.testing.assert_array_equal(labels, expected_labels) + + +@testing.parametrize('dtype', [np.float32, np.float64]) +def test_3d(dtype): + n = 30 + lx, ly, lz = n, n, n + data, labels = make_3d_syntheticdata(lx, ly, lz) + data = data.astype(dtype, copy=False) + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + labels = random_walker(data, labels, mode='cg') + assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all() + assert data.shape == labels.shape + + +def test_3d_inactive(): + n = 30 + lx, ly, lz = n, n, n + data, labels = make_3d_syntheticdata(lx, ly, lz) + labels[5:25, 26:29, 26:29] = -1 + with expected_warnings( + [ + 'Changing the sparsity structure|"cg" mode|CObject type|scipy.sparse.linalg.cg' + ] + ): + labels = random_walker(data, labels, mode='cg') + assert (labels.reshape(data.shape)[13:17, 13:17, 13:17] == 2).all() + assert data.shape == labels.shape + + +@testing.parametrize('channel_axis', [0, 1, -1]) +@testing.parametrize('dtype', [np.float32, np.float64]) +def test_multispectral_2d(dtype, channel_axis): + lx, ly = 70, 100 + data, labels = make_2d_syntheticdata(lx, ly) + data = data.astype(dtype, copy=False) + data = data[..., np.newaxis].repeat(2, axis=-1) # Expect identical output + + data = np.moveaxis(data, -1, channel_axis) + with expected_warnings( + [ + 'Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg', + 'The probability range is outside', + ] + ): + multi_labels = random_walker(data, labels, mode='cg', channel_axis=channel_axis) + data = np.moveaxis(data, channel_axis, -1) + + assert data[..., 0].shape == labels.shape + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + random_walker(data[..., 0], labels, mode='cg') + assert (multi_labels.reshape(labels.shape)[25:45, 40:60] == 2).all() + assert data[..., 0].shape == labels.shape + + +@testing.parametrize('dtype', [np.float32, np.float64]) +def test_multispectral_3d(dtype): + n = 30 + lx, ly, lz = n, n, n + data, labels = make_3d_syntheticdata(lx, ly, lz) + data = data.astype(dtype, copy=False) + data = data[..., np.newaxis].repeat(2, axis=-1) # Expect identical output + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + multi_labels = random_walker(data, labels, mode='cg', channel_axis=-1) + assert data[..., 0].shape == labels.shape + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + single_labels = random_walker(data[..., 0], labels, mode='cg') + assert (multi_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all() + assert (single_labels.reshape(labels.shape)[13:17, 13:17, 13:17] == 2).all() + assert data[..., 0].shape == labels.shape + + +def test_spacing_0(): + n = 30 + lx, ly, lz = n, n, n + data, _ = make_3d_syntheticdata(lx, ly, lz) + + # Rescale `data` along Z axis + data_aniso = np.zeros((n, n, n // 2)) + for i, yz in enumerate(data): + data_aniso[i, :, :] = resize( + yz, (n, n // 2), mode='constant', anti_aliasing=False + ) + + # Generate new labels + small_l = int(lx // 5) + labels_aniso = np.zeros_like(data_aniso) + labels_aniso[lx // 5, ly // 5, lz // 5] = 1 + labels_aniso[ + lx // 2 + small_l // 4, ly // 2 - small_l // 4, lz // 4 - small_l // 8 + ] = 2 + + # Test with `spacing` kwarg + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + labels_aniso = random_walker( + data_aniso, labels_aniso, mode='cg', spacing=(1.0, 1.0, 0.5) + ) + + assert (labels_aniso[13:17, 13:17, 7:9] == 2).all() + + +# Passing on WASM +@xfail( + condition=arch32 and not is_wasm, + reason=( + 'Known test failure on 32-bit platforms. See links for ' + 'details: ' + 'https://github.com/scikit-image/scikit-image/issues/3091 ' + 'https://github.com/scikit-image/scikit-image/issues/3092' + ), +) +def test_spacing_1(): + n = 30 + lx, ly, lz = n, n, n + data, _ = make_3d_syntheticdata(lx, ly, lz) + + # Rescale `data` along Y axis + # `resize` is not yet 3D capable, so this must be done by looping in 2D. + data_aniso = np.zeros((n, n * 2, n)) + for i, yz in enumerate(data): + data_aniso[i, :, :] = resize( + yz, (n * 2, n), mode='constant', anti_aliasing=False + ) + + # Generate new labels + small_l = int(lx // 5) + labels_aniso = np.zeros_like(data_aniso) + labels_aniso[lx // 5, ly // 5, lz // 5] = 1 + labels_aniso[lx // 2 + small_l // 4, ly - small_l // 2, lz // 2 - small_l // 4] = 2 + + # Test with `spacing` kwarg + # First, anisotropic along Y + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + labels_aniso = random_walker( + data_aniso, labels_aniso, mode='cg', spacing=(1.0, 2.0, 1.0) + ) + assert (labels_aniso[13:17, 26:34, 13:17] == 2).all() + + # Rescale `data` along X axis + # `resize` is not yet 3D capable, so this must be done by looping in 2D. + data_aniso = np.zeros((n, n * 2, n)) + for i in range(data.shape[1]): + data_aniso[i, :, :] = resize( + data[:, 1, :], (n * 2, n), mode='constant', anti_aliasing=False + ) + + # Generate new labels + small_l = int(lx // 5) + labels_aniso2 = np.zeros_like(data_aniso) + labels_aniso2[lx // 5, ly // 5, lz // 5] = 1 + labels_aniso2[lx - small_l // 2, ly // 2 + small_l // 4, lz // 2 - small_l // 4] = 2 + + # Anisotropic along X + with expected_warnings( + ['Changing the sparsity structure|"cg" mode|scipy.sparse.linalg.cg'] + ): + labels_aniso2 = random_walker( + data_aniso, labels_aniso2, mode='cg', spacing=(2.0, 1.0, 1.0) + ) + assert (labels_aniso2[26:34, 13:17, 13:17] == 2).all() + + +def test_trivial_cases(): + # When all voxels are labeled + img = np.ones((10, 10)) + labels = np.ones((10, 10)) + + with expected_warnings(["Returning provided labels"]): + pass_through = random_walker(img, labels) + np.testing.assert_array_equal(pass_through, labels) + + # When all voxels are labeled AND return_full_prob is True + labels[:, :5] = 3 + expected = np.concatenate( + ((labels == 1)[..., np.newaxis], (labels == 3)[..., np.newaxis]), axis=2 + ) + with expected_warnings(["Returning provided labels"]): + test = random_walker(img, labels, return_full_prob=True) + np.testing.assert_array_equal(test, expected) + + # Unlabeled voxels not connected to seed, so nothing can be done + img = np.full((10, 10), False) + object_A = np.array([(6, 7), (6, 8), (7, 7), (7, 8)]) + object_B = np.array([(3, 1), (4, 1), (2, 2), (3, 2), (4, 2), (2, 3), (3, 3)]) + for x, y in np.vstack((object_A, object_B)): + img[y][x] = True + + markers = np.zeros((10, 10), dtype=np.int8) + for x, y in object_B: + markers[y][x] = 1 + + markers[img == 0] = -1 + with expected_warnings(["All unlabeled pixels are isolated"]): + output_labels = random_walker(img, markers) + assert np.all(output_labels[markers == 1] == 1) + # Here 0-labeled pixels could not be determined (no connection to seed) + assert np.all(output_labels[markers == 0] == -1) + with expected_warnings(["All unlabeled pixels are isolated"]): + test = random_walker(img, markers, return_full_prob=True) + + +def test_length2_spacing(): + # If this passes without raising an exception (warnings OK), the new + # spacing code is working properly. + np.random.seed(42) + img = np.ones((10, 10)) + 0.2 * np.random.normal(size=(10, 10)) + labels = np.zeros((10, 10), dtype=np.uint8) + labels[2, 4] = 1 + labels[6, 8] = 4 + random_walker(img, labels, spacing=(1.0, 2.0)) + + +def test_bad_inputs(): + # Too few dimensions + img = np.ones(10) + labels = np.arange(10) + with testing.raises(ValueError): + random_walker(img, labels) + with testing.raises(ValueError): + random_walker(img, labels, channel_axis=-1) + + # Too many dimensions + np.random.seed(42) + img = np.random.normal(size=(3, 3, 3, 3, 3)) + labels = np.arange(3**5).reshape(img.shape) + with testing.raises(ValueError): + random_walker(img, labels) + with testing.raises(ValueError): + random_walker(img, labels, channel_axis=-1) + + # Spacing incorrect length + img = np.random.normal(size=(10, 10)) + labels = np.zeros((10, 10)) + labels[2, 4] = 2 + labels[6, 8] = 5 + with testing.raises(ValueError): + random_walker(img, labels, spacing=(1,)) + + # Invalid mode + img = np.random.normal(size=(10, 10)) + labels = np.zeros((10, 10)) + with testing.raises(ValueError): + random_walker(img, labels, mode='bad') + + +def test_isolated_seeds(): + np.random.seed(0) + a = np.random.random((7, 7)) + mask = -np.ones(a.shape) + # This pixel is an isolated seed + mask[1, 1] = 1 + # Unlabeled pixels + mask[3:, 3:] = 0 + # Seeds connected to unlabeled pixels + mask[4, 4] = 2 + mask[6, 6] = 1 + + # Test that no error is raised, and that labels of isolated seeds are OK + with expected_warnings( + [ + 'Changing the sparsity structure|The probability range is outside|scipy.sparse.linalg.cg' + ] + ): + res = random_walker(a, mask) + assert res[1, 1] == 1 + with expected_warnings( + [ + 'Changing the sparsity structure|The probability range is outside|scipy.sparse.linalg.cg' + ] + ): + res = random_walker(a, mask, return_full_prob=True) + assert res[0, 1, 1] == 1 + assert res[1, 1, 1] == 0 + + +def test_isolated_area(): + np.random.seed(0) + a = np.random.random((7, 7)) + mask = -np.ones(a.shape) + # This pixel is an isolated seed + mask[1, 1] = 0 + # Unlabeled pixels + mask[3:, 3:] = 0 + # Seeds connected to unlabeled pixels + mask[4, 4] = 2 + mask[6, 6] = 1 + + # Test that no error is raised, and that labels of isolated seeds are OK + with expected_warnings( + [ + 'Changing the sparsity structure|The probability range is outside|scipy.sparse.linalg.cg' + ] + ): + res = random_walker(a, mask) + assert res[1, 1] == 0 + with expected_warnings( + [ + 'Changing the sparsity structure|The probability range is outside|scipy.sparse.linalg.cg' + ] + ): + res = random_walker(a, mask, return_full_prob=True) + assert res[0, 1, 1] == 0 + assert res[1, 1, 1] == 0 + + +def test_prob_tol(): + np.random.seed(0) + a = np.random.random((7, 7)) + mask = -np.ones(a.shape) + # This pixel is an isolated seed + mask[1, 1] = 1 + # Unlabeled pixels + mask[3:, 3:] = 0 + # Seeds connected to unlabeled pixels + mask[4, 4] = 2 + mask[6, 6] = 1 + + with expected_warnings( + [ + 'Changing the sparsity structure|The probability range is outside|scipy.sparse.linalg.cg' + ] + ): + res = random_walker(a, mask, return_full_prob=True) + + # Lower beta, no warning is expected. + res = random_walker(a, mask, return_full_prob=True, beta=10) + assert res[0, 1, 1] == 1 + assert res[1, 1, 1] == 0 + + # Being more prob_tol tolerant, no warning is expected. + res = random_walker(a, mask, return_full_prob=True, prob_tol=1e-1) + assert res[0, 1, 1] == 1 + assert res[1, 1, 1] == 0 + + # Reduced tol, no warning is expected. + res = random_walker(a, mask, return_full_prob=True, tol=1e-9) + assert res[0, 1, 1] == 1 + assert res[1, 1, 1] == 0 + + +def test_umfpack_import(): + from skimage.segmentation import random_walker_segmentation + + UmfpackContext = random_walker_segmentation.UmfpackContext + try: + # when scikit-umfpack is installed UmfpackContext should not be None + import scikits.umfpack # noqa: F401 + + assert UmfpackContext is not None + except ImportError: + assert UmfpackContext is None + + +def test_empty_labels(): + image = np.random.random((5, 5)) + labels = np.zeros((5, 5), dtype=int) + + with testing.raises(ValueError, match="No seeds provided"): + random_walker(image, labels) + + labels[1, 1] = -1 + with testing.raises(ValueError, match="No seeds provided"): + random_walker(image, labels) + + # Once seeds are provided, it should run without error + labels[3, 3] = 1 + random_walker(image, labels) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_slic.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_slic.py new file mode 100644 index 0000000000000000000000000000000000000000..658c2cccd71519732d6738390dad8d23a0ca921a --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_slic.py @@ -0,0 +1,632 @@ +from itertools import product + +import numpy as np +import pytest +from numpy.testing import assert_equal + +from skimage import data, filters, img_as_float +from skimage._shared.testing import run_in_parallel, expected_warnings +from skimage.segmentation import slic + + +@run_in_parallel() +def test_color_2d(): + rng = np.random.default_rng(0) + img = np.zeros((20, 21, 3)) + img[:10, :10, 0] = 1 + img[10:, :10, 1] = 1 + img[10:, 10:, 2] = 1 + img += 0.01 * rng.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + seg = slic(img, n_segments=4, sigma=0, enforce_connectivity=False, start_label=0) + + # we expect 4 segments + assert_equal(len(np.unique(seg)), 4) + assert_equal(seg.shape, img.shape[:-1]) + assert_equal(seg[:10, :10], 0) + assert_equal(seg[10:, :10], 2) + assert_equal(seg[:10, 10:], 1) + assert_equal(seg[10:, 10:], 3) + + +def test_multichannel_2d(): + rng = np.random.default_rng(0) + img = np.zeros((20, 20, 8)) + img[:10, :10, 0:2] = 1 + img[:10, 10:, 2:4] = 1 + img[10:, :10, 4:6] = 1 + img[10:, 10:, 6:8] = 1 + img += 0.01 * rng.normal(size=img.shape) + img = np.clip(img, 0, 1, out=img) + seg = slic(img, n_segments=4, enforce_connectivity=False, start_label=0) + + # we expect 4 segments + assert_equal(len(np.unique(seg)), 4) + assert_equal(seg.shape, img.shape[:-1]) + assert_equal(seg[:10, :10], 0) + assert_equal(seg[10:, :10], 2) + assert_equal(seg[:10, 10:], 1) + assert_equal(seg[10:, 10:], 3) + + +def test_gray_2d(): + rng = np.random.default_rng(0) + img = np.zeros((20, 21)) + img[:10, :10] = 0.33 + img[10:, :10] = 0.67 + img[10:, 10:] = 1.00 + img += 0.0033 * rng.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + seg = slic( + img, + sigma=0, + n_segments=4, + compactness=1, + channel_axis=None, + convert2lab=False, + start_label=0, + ) + + assert_equal(len(np.unique(seg)), 4) + assert_equal(seg.shape, img.shape) + assert_equal(seg[:10, :10], 0) + assert_equal(seg[10:, :10], 2) + assert_equal(seg[:10, 10:], 1) + assert_equal(seg[10:, 10:], 3) + + +def test_gray2d_default_channel_axis(): + img = np.zeros((20, 21)) + img[:10, :10] = 0.33 + with pytest.raises(ValueError, match="channel_axis=-1 indicates multichannel"): + slic(img) + slic(img, channel_axis=None) + + +def _check_segment_labels(seg1, seg2, allowed_mismatch_ratio=0.1): + size = seg1.size + ndiff = np.sum(seg1 != seg2) + assert (ndiff / size) < allowed_mismatch_ratio + + +def test_slic_consistency_across_image_magnitude(): + # verify that that images of various scales across integer and float dtypes + # give the same segmentation result + img_uint8 = data.cat()[:256, :128] + img_uint16 = 256 * img_uint8.astype(np.uint16) + img_float32 = img_as_float(img_uint8) + img_float32_norm = img_float32 / img_float32.max() + img_float32_offset = img_float32 + 1000 + + seg1 = slic(img_uint8) + seg2 = slic(img_uint16) + seg3 = slic(img_float32) + seg4 = slic(img_float32_norm) + seg5 = slic(img_float32_offset) + + np.testing.assert_array_equal(seg1, seg2) + np.testing.assert_array_equal(seg1, seg3) + # Assert that offset has no impact on result + np.testing.assert_array_equal(seg4, seg5) + # Floating point cases can have mismatch due to floating point error + # exact match was observed on x86_64, but mismatches seen no i686. + # For now just verify that a similar number of superpixels are present in + # each case. + n_seg1 = seg1.max() + n_seg4 = seg4.max() + assert abs(n_seg1 - n_seg4) / n_seg1 < 0.5 + + +def test_color_3d(): + rng = np.random.default_rng(0) + img = np.zeros((20, 21, 22, 3)) + slices = [] + for dim_size in img.shape[:-1]: + midpoint = dim_size // 2 + slices.append((slice(None, midpoint), slice(midpoint, None))) + slices = list(product(*slices)) + colors = list(product(*(([0, 1],) * 3))) + for s, c in zip(slices, colors): + img[s] = c + img += 0.01 * rng.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + seg = slic(img, sigma=0, n_segments=8, start_label=0) + + assert_equal(len(np.unique(seg)), 8) + for s, c in zip(slices, range(8)): + assert_equal(seg[s], c) + + +def test_gray_3d(): + rng = np.random.default_rng(0) + img = np.zeros((20, 21, 22)) + slices = [] + for dim_size in img.shape: + midpoint = dim_size // 2 + slices.append((slice(None, midpoint), slice(midpoint, None))) + slices = list(product(*slices)) + shades = np.arange(0, 1.000001, 1.0 / 7) + for s, sh in zip(slices, shades): + img[s] = sh + img += 0.001 * rng.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + seg = slic( + img, + sigma=0, + n_segments=8, + compactness=1, + channel_axis=None, + convert2lab=False, + start_label=0, + ) + + assert_equal(len(np.unique(seg)), 8) + for s, c in zip(slices, range(8)): + assert_equal(seg[s], c) + + +def test_list_sigma(): + rng = np.random.default_rng(0) + img = np.array([[1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1]], float) + img += 0.1 * rng.normal(size=img.shape) + result_sigma = np.array([[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]], int) + with expected_warnings( + ["Input image is 2D: sigma number of " "elements must be 2"] + ): + seg_sigma = slic( + img, n_segments=2, sigma=[1, 50, 1], channel_axis=None, start_label=0 + ) + assert_equal(seg_sigma, result_sigma) + + +def test_spacing(): + rng = np.random.default_rng(0) + img = np.array([[1, 1, 1, 0, 0], [1, 1, 0, 0, 0]], float) + result_non_spaced = np.array([[0, 0, 0, 1, 1], [0, 0, 1, 1, 1]], int) + result_spaced = np.array([[0, 0, 0, 0, 0], [1, 1, 1, 1, 1]], int) + img += 0.1 * rng.normal(size=img.shape) + seg_non_spaced = slic( + img, n_segments=2, sigma=0, channel_axis=None, compactness=1.0, start_label=0 + ) + seg_spaced = slic( + img, + n_segments=2, + sigma=0, + spacing=[500, 1], + compactness=1.0, + channel_axis=None, + start_label=0, + ) + assert_equal(seg_non_spaced, result_non_spaced) + assert_equal(seg_spaced, result_spaced) + + +def test_invalid_lab_conversion(): + img = np.array([[1, 1, 1, 0, 0], [1, 1, 0, 0, 0]], float) + 1 + with pytest.raises(ValueError): + slic(img, channel_axis=-1, convert2lab=True, start_label=0) + + +def test_enforce_connectivity(): + img = np.array([[0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0]], float) + + segments_connected = slic( + img, + 2, + compactness=0.0001, + enforce_connectivity=True, + convert2lab=False, + start_label=0, + channel_axis=None, + ) + segments_disconnected = slic( + img, + 2, + compactness=0.0001, + enforce_connectivity=False, + convert2lab=False, + start_label=0, + channel_axis=None, + ) + + # Make sure nothing fatal occurs (e.g. buffer overflow) at low values of + # max_size_factor + segments_connected_low_max = slic( + img, + 2, + compactness=0.0001, + enforce_connectivity=True, + convert2lab=False, + max_size_factor=0.8, + start_label=0, + channel_axis=None, + ) + + result_connected = np.array( + [[0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 1, 1]], float + ) + + result_disconnected = np.array( + [[0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0]], float + ) + + assert_equal(segments_connected, result_connected) + assert_equal(segments_disconnected, result_disconnected) + assert_equal(segments_connected_low_max, result_connected) + + +def test_slic_zero(): + # Same as test_color_2d but with slic_zero=True + rng = np.random.default_rng(0) + img = np.zeros((20, 21, 3)) + img[:10, :10, 0] = 1 + img[10:, :10, 1] = 1 + img[10:, 10:, 2] = 1 + img += 0.01 * rng.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + seg = slic(img, n_segments=4, sigma=0, slic_zero=True, start_label=0) + + # we expect 4 segments + assert_equal(len(np.unique(seg)), 4) + assert_equal(seg.shape, img.shape[:-1]) + assert_equal(seg[:10, :10], 0) + assert_equal(seg[10:, :10], 2) + assert_equal(seg[:10, 10:], 1) + assert_equal(seg[10:, 10:], 3) + + +def test_more_segments_than_pixels(): + rng = np.random.default_rng(0) + img = np.zeros((20, 21)) + img[:10, :10] = 0.33 + img[10:, :10] = 0.67 + img[10:, 10:] = 1.00 + img += 0.0033 * rng.normal(size=img.shape) + img[img > 1] = 1 + img[img < 0] = 0 + seg = slic( + img, + sigma=0, + n_segments=500, + compactness=1, + channel_axis=None, + convert2lab=False, + start_label=0, + ) + assert np.all(seg.ravel() == np.arange(seg.size)) + + +def test_color_2d_mask(): + rng = np.random.default_rng(0) + msk = np.zeros((20, 21)) + msk[2:-2, 2:-2] = 1 + img = np.zeros((20, 21, 3)) + img[:10, :10, 0] = 1 + img[10:, :10, 1] = 1 + img[10:, 10:, 2] = 1 + img += 0.01 * rng.normal(size=img.shape) + np.clip(img, 0, 1, out=img) + seg = slic(img, n_segments=4, sigma=0, enforce_connectivity=False, mask=msk) + + # we expect 4 segments + masked area + assert_equal(len(np.unique(seg)), 5) + assert_equal(seg.shape, img.shape[:-1]) + # segments + assert_equal(seg[2:10, 2:10], 1) + assert_equal(seg[10:-2, 2:10], 4) + assert_equal(seg[2:10, 10:-2], 2) + assert_equal(seg[10:-2, 10:-2], 3) + # non masked area + assert_equal(seg[:2, :], 0) + assert_equal(seg[-2:, :], 0) + assert_equal(seg[:, :2], 0) + assert_equal(seg[:, -2:], 0) + + +def test_multichannel_2d_mask(): + rng = np.random.default_rng(0) + msk = np.zeros((20, 20)) + msk[2:-2, 2:-2] = 1 + img = np.zeros((20, 20, 8)) + img[:10, :10, 0:2] = 1 + img[:10, 10:, 2:4] = 1 + img[10:, :10, 4:6] = 1 + img[10:, 10:, 6:8] = 1 + img += 0.01 * rng.normal(size=img.shape) + np.clip(img, 0, 1, out=img) + seg = slic(img, n_segments=4, enforce_connectivity=False, mask=msk) + + # we expect 4 segments + masked area + assert_equal(len(np.unique(seg)), 5) + assert_equal(seg.shape, img.shape[:-1]) + # segments + assert_equal(seg[2:10, 2:10], 2) + assert_equal(seg[2:10, 10:-2], 1) + assert_equal(seg[10:-2, 2:10], 4) + assert_equal(seg[10:-2, 10:-2], 3) + # non masked area + assert_equal(seg[:2, :], 0) + assert_equal(seg[-2:, :], 0) + assert_equal(seg[:, :2], 0) + assert_equal(seg[:, -2:], 0) + + +def test_gray_2d_mask(): + rng = np.random.default_rng(0) + msk = np.zeros((20, 21)) + msk[2:-2, 2:-2] = 1 + img = np.zeros((20, 21)) + img[:10, :10] = 0.33 + img[10:, :10] = 0.67 + img[10:, 10:] = 1.00 + img += 0.0033 * rng.normal(size=img.shape) + np.clip(img, 0, 1, out=img) + seg = slic( + img, + sigma=0, + n_segments=4, + compactness=1, + channel_axis=None, + convert2lab=False, + mask=msk, + ) + + assert_equal(len(np.unique(seg)), 5) + assert_equal(seg.shape, img.shape) + # segments + assert_equal(seg[2:10, 2:10], 1) + assert_equal(seg[2:10, 10:-2], 2) + assert_equal(seg[10:-2, 2:10], 3) + assert_equal(seg[10:-2, 10:-2], 4) + # non masked area + assert_equal(seg[:2, :], 0) + assert_equal(seg[-2:, :], 0) + assert_equal(seg[:, :2], 0) + assert_equal(seg[:, -2:], 0) + + +def test_list_sigma_mask(): + rng = np.random.default_rng(0) + msk = np.zeros((2, 6)) + msk[:, 1:-1] = 1 + img = np.array([[1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1]], float) + img += 0.1 * rng.normal(size=img.shape) + result_sigma = np.array([[0, 1, 1, 2, 2, 0], [0, 1, 1, 2, 2, 0]], int) + seg_sigma = slic(img, n_segments=2, sigma=[50, 1], channel_axis=None, mask=msk) + assert_equal(seg_sigma, result_sigma) + + +def test_spacing_mask(): + rng = np.random.default_rng(0) + msk = np.zeros((2, 5)) + msk[:, 1:-1] = 1 + img = np.array([[1, 1, 1, 0, 0], [1, 1, 0, 0, 0]], float) + result_non_spaced = np.array([[0, 1, 1, 2, 0], [0, 1, 2, 2, 0]], int) + result_spaced = np.array([[0, 1, 1, 1, 0], [0, 2, 2, 2, 0]], int) + img += 0.1 * rng.normal(size=img.shape) + seg_non_spaced = slic( + img, n_segments=2, sigma=0, channel_axis=None, compactness=1.0, mask=msk + ) + seg_spaced = slic( + img, + n_segments=2, + sigma=0, + spacing=[50, 1], + compactness=1.0, + channel_axis=None, + mask=msk, + ) + assert_equal(seg_non_spaced, result_non_spaced) + assert_equal(seg_spaced, result_spaced) + + +def test_enforce_connectivity_mask(): + msk = np.zeros((3, 6)) + msk[:, 1:-1] = 1 + img = np.array([[0, 0, 0, 1, 1, 1], [1, 0, 0, 1, 1, 0], [0, 0, 0, 1, 1, 0]], float) + + segments_connected = slic( + img, + 2, + compactness=0.0001, + enforce_connectivity=True, + convert2lab=False, + mask=msk, + channel_axis=None, + ) + segments_disconnected = slic( + img, + 2, + compactness=0.0001, + enforce_connectivity=False, + convert2lab=False, + mask=msk, + channel_axis=None, + ) + + # Make sure nothing fatal occurs (e.g. buffer overflow) at low values of + # max_size_factor + segments_connected_low_max = slic( + img, + 2, + compactness=0.0001, + enforce_connectivity=True, + convert2lab=False, + max_size_factor=0.8, + mask=msk, + channel_axis=None, + ) + + result_connected = np.array( + [[0, 1, 1, 2, 2, 0], [0, 1, 1, 2, 2, 0], [0, 1, 1, 2, 2, 0]], float + ) + + result_disconnected = np.array( + [[0, 1, 1, 2, 2, 0], [0, 1, 1, 2, 2, 0], [0, 1, 1, 2, 2, 0]], float + ) + + assert_equal(segments_connected, result_connected) + assert_equal(segments_disconnected, result_disconnected) + assert_equal(segments_connected_low_max, result_connected) + + +def test_slic_zero_mask(): + rng = np.random.default_rng(0) + msk = np.zeros((20, 21)) + msk[2:-2, 2:-2] = 1 + img = np.zeros((20, 21, 3)) + img[:10, :10, 0] = 1 + img[10:, :10, 1] = 1 + img[10:, 10:, 2] = 1 + img += 0.01 * rng.normal(size=img.shape) + np.clip(img, 0, 1, out=img) + seg = slic(img, n_segments=4, sigma=0, slic_zero=True, mask=msk) + + # we expect 4 segments + masked area + assert_equal(len(np.unique(seg)), 5) + assert_equal(seg.shape, img.shape[:-1]) + # segments + assert_equal(seg[2:10, 2:10], 1) + assert_equal(seg[2:10, 10:-2], 2) + assert_equal(seg[10:-2, 2:10], 3) + assert_equal(seg[10:-2, 10:-2], 4) + # non masked area + assert_equal(seg[:2, :], 0) + assert_equal(seg[-2:, :], 0) + assert_equal(seg[:, :2], 0) + assert_equal(seg[:, -2:], 0) + + +def test_more_segments_than_pixels_mask(): + rng = np.random.default_rng(0) + msk = np.zeros((20, 21)) + msk[2:-2, 2:-2] = 1 + img = np.zeros((20, 21)) + img[:10, :10] = 0.33 + img[10:, :10] = 0.67 + img[10:, 10:] = 1.00 + img += 0.0033 * rng.normal(size=img.shape) + np.clip(img, 0, 1, out=img) + seg = slic( + img, + sigma=0, + n_segments=500, + compactness=1, + channel_axis=None, + convert2lab=False, + mask=msk, + ) + + expected = np.arange(seg[2:-2, 2:-2].size) + 1 + assert np.all(seg[2:-2, 2:-2].ravel() == expected) + + +def test_color_3d_mask(): + msk = np.zeros((20, 21, 22)) + msk[2:-2, 2:-2, 2:-2] = 1 + + rng = np.random.default_rng(0) + img = np.zeros((20, 21, 22, 3)) + slices = [] + for dim_size in msk.shape: + midpoint = dim_size // 2 + slices.append((slice(None, midpoint), slice(midpoint, None))) + slices = list(product(*slices)) + colors = list(product(*(([0, 1],) * 3))) + for s, c in zip(slices, colors): + img[s] = c + img += 0.01 * rng.normal(size=img.shape) + np.clip(img, 0, 1, out=img) + + seg = slic(img, sigma=0, n_segments=8, mask=msk) + + # we expect 8 segments + masked area + assert_equal(len(np.unique(seg)), 9) + for s, c in zip(slices, range(1, 9)): + assert_equal(seg[s][2:-2, 2:-2, 2:-2], c) + + +def test_gray_3d_mask(): + msk = np.zeros((20, 21, 22)) + msk[2:-2, 2:-2, 2:-2] = 1 + + rng = np.random.default_rng(0) + img = np.zeros((20, 21, 22)) + slices = [] + for dim_size in img.shape: + midpoint = dim_size // 2 + slices.append((slice(None, midpoint), slice(midpoint, None))) + slices = list(product(*slices)) + shades = np.linspace(0, 1, 8) + for s, sh in zip(slices, shades): + img[s] = sh + img += 0.001 * rng.normal(size=img.shape) + np.clip(img, 0, 1, out=img) + seg = slic( + img, sigma=0, n_segments=8, channel_axis=None, convert2lab=False, mask=msk + ) + + # we expect 8 segments + masked area + assert_equal(len(np.unique(seg)), 9) + for s, c in zip(slices, range(1, 9)): + assert_equal(seg[s][2:-2, 2:-2, 2:-2], c) + + +@pytest.mark.parametrize("dtype", ['float16', 'float32', 'float64', 'uint8', 'int']) +def test_dtype_support(dtype): + img = np.random.rand(28, 28).astype(dtype) + + # Simply run the function to assert that it runs without error + slic(img, start_label=1, channel_axis=None) + + +def test_start_label_fix(): + """Tests the fix for a bug producing a label < start_label (gh-6240). + + For the v0.19.1 release, the `img` and `slic` call as below result in two + non-contiguous regions with value 0 despite `start_label=1`. We verify that + the minimum label is now `start_label` as expected. + """ + + # generate bumpy data that gives unexpected label prior to bug fix + rng = np.random.default_rng(9) + img = rng.standard_normal((8, 13)) > 0 + img = filters.gaussian(img, sigma=1) + + start_label = 1 + superp = slic( + img, + start_label=start_label, + channel_axis=None, + n_segments=6, + compactness=0.01, + enforce_connectivity=True, + max_num_iter=10, + ) + assert superp.min() == start_label + + +def test_raises_ValueError_if_input_has_NaN(): + img = np.zeros((4, 5), dtype=float) + img[2, 3] = np.nan + with pytest.raises(ValueError): + slic(img, channel_axis=None) + + mask = ~np.isnan(img) + slic(img, mask=mask, channel_axis=None) + + +@pytest.mark.parametrize("inf", [-np.inf, np.inf]) +def test_raises_ValueError_if_input_has_inf(inf): + img = np.zeros((4, 5), dtype=float) + img[2, 3] = inf + with pytest.raises(ValueError): + slic(img, channel_axis=None) + + mask = np.isfinite(img) + slic(img, mask=mask, channel_axis=None) diff --git a/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_watershed.py b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_watershed.py new file mode 100644 index 0000000000000000000000000000000000000000..ddbfc092fa352290d7b3eaed0eac8e9b882d26da --- /dev/null +++ b/vlmpy310/lib/python3.10/site-packages/skimage/segmentation/tests/test_watershed.py @@ -0,0 +1,967 @@ +"""test_watershed.py - tests the watershed function""" + +import math +import unittest + +import numpy as np +import pytest +from scipy import ndimage as ndi + +import skimage.measure +from skimage._shared.filters import gaussian +from skimage.feature import peak_local_max +from skimage.measure import label + +from .._watershed import watershed + +eps = 1e-12 +# fmt: off +blob = np.array([[255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 204, 204, 204, 204, 204, 204, 255, 255, 255, 255, 255], + [255, 255, 255, 204, 204, 183, 153, 153, 153, 153, 183, 204, 204, 255, 255, 255], + [255, 255, 204, 183, 153, 141, 111, 103, 103, 111, 141, 153, 183, 204, 255, 255], + [255, 255, 204, 153, 111, 94, 72, 52, 52, 72, 94, 111, 153, 204, 255, 255], + [255, 255, 204, 153, 111, 72, 39, 1, 1, 39, 72, 111, 153, 204, 255, 255], + [255, 255, 204, 183, 141, 111, 72, 39, 39, 72, 111, 141, 183, 204, 255, 255], + [255, 255, 255, 204, 183, 141, 111, 72, 72, 111, 141, 183, 204, 255, 255, 255], + [255, 255, 255, 255, 204, 183, 141, 94, 94, 141, 183, 204, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 204, 153, 103, 103, 153, 204, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 204, 183, 141, 94, 94, 141, 183, 204, 255, 255, 255, 255], + [255, 255, 255, 204, 183, 141, 111, 72, 72, 111, 141, 183, 204, 255, 255, 255], + [255, 255, 204, 183, 141, 111, 72, 39, 39, 72, 111, 141, 183, 204, 255, 255], + [255, 255, 204, 153, 111, 72, 39, 1, 1, 39, 72, 111, 153, 204, 255, 255], + [255, 255, 204, 153, 111, 94, 72, 52, 52, 72, 94, 111, 153, 204, 255, 255], + [255, 255, 204, 183, 153, 141, 111, 103, 103, 111, 141, 153, 183, 204, 255, 255], + [255, 255, 255, 204, 204, 183, 153, 153, 153, 153, 183, 204, 204, 255, 255, 255], + [255, 255, 255, 255, 255, 204, 204, 204, 204, 204, 204, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255], + [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]]) +# fmt: on + + +def diff(a, b): + if not isinstance(a, np.ndarray): + a = np.asarray(a) + if not isinstance(b, np.ndarray): + b = np.asarray(b) + if (0 in a.shape) and (0 in b.shape): + return 0.0 + b[a == 0] = 0 + if a.dtype in [np.complex64, np.complex128] or b.dtype in [ + np.complex64, + np.complex128, + ]: + a = np.asarray(a, np.complex128) + b = np.asarray(b, np.complex128) + t = ((a.real - b.real) ** 2).sum() + ((a.imag - b.imag) ** 2).sum() + else: + a = np.asarray(a) + a = a.astype(np.float64) + b = np.asarray(b) + b = b.astype(np.float64) + t = ((a - b) ** 2).sum() + return math.sqrt(t) + + +class TestWatershed(unittest.TestCase): + eight = np.ones((3, 3), bool) + + def test_watershed01(self): + "watershed 1" + data = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + markers = np.array( + [ + [-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.int8, + ) + out = watershed(data, markers, self.eight) + expected = np.array( + [ + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + ] + ) + error = diff(expected, out) + assert error < eps + + def test_watershed02(self): + "watershed 2" + data = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + markers = np.array( + [ + [-1, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.int8, + ) + out = watershed(data, markers) + error = diff( + [ + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, 1, 1, 1, -1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, 1, 1, 1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + ], + out, + ) + self.assertTrue(error < eps) + + def test_watershed03(self): + "watershed 3" + data = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + markers = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 2, 0, 3, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1], + ], + np.int8, + ) + out = watershed(data, markers) + error = diff( + [ + [-1, -1, -1, -1, -1, -1, -1], + [-1, 0, 2, 0, 3, 0, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, 0, 2, 0, 3, 0, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + ], + out, + ) + self.assertTrue(error < eps) + + def test_watershed04(self): + "watershed 4" + data = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + markers = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 2, 0, 3, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1], + ], + np.int8, + ) + out = watershed(data, markers, self.eight) + error = diff( + [ + [-1, -1, -1, -1, -1, -1, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, 2, 2, 0, 3, 3, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + ], + out, + ) + self.assertTrue(error < eps) + + def test_watershed05(self): + "watershed 5" + data = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 0, 1, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + markers = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 3, 0, 2, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, -1], + ], + np.int8, + ) + out = watershed(data, markers, self.eight) + error = diff( + [ + [-1, -1, -1, -1, -1, -1, -1], + [-1, 3, 3, 0, 2, 2, -1], + [-1, 3, 3, 0, 2, 2, -1], + [-1, 3, 3, 0, 2, 2, -1], + [-1, 3, 3, 0, 2, 2, -1], + [-1, 3, 3, 0, 2, 2, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + ], + out, + ) + self.assertTrue(error < eps) + + def test_watershed06(self): + "watershed 6" + data = np.array( + [ + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 0, 0, 0, 1, 0], + [0, 1, 1, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + ], + np.uint8, + ) + markers = np.array( + [ + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 0, 0, 0], + [-1, 0, 0, 0, 0, 0, 0], + ], + np.int8, + ) + out = watershed(data, markers, self.eight) + error = diff( + [ + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, 1, 1, 1, 1, 1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + [-1, -1, -1, -1, -1, -1, -1], + ], + out, + ) + self.assertTrue(error < eps) + + def test_watershed07(self): + "A regression test of a competitive case that failed" + data = blob + mask = data != 255 + markers = np.zeros(data.shape, int) + markers[6, 7] = 1 + markers[14, 7] = 2 + out = watershed(data, markers, self.eight, mask=mask) + # + # The two objects should be the same size, except possibly for the + # border region + # + size1 = np.sum(out == 1) + size2 = np.sum(out == 2) + self.assertTrue(abs(size1 - size2) <= 6) + + def test_watershed08(self): + "The border pixels + an edge are all the same value" + data = blob.copy() + data[10, 7:9] = 141 + mask = data != 255 + markers = np.zeros(data.shape, int) + markers[6, 7] = 1 + markers[14, 7] = 2 + out = watershed(data, markers, self.eight, mask=mask) + # + # The two objects should be the same size, except possibly for the + # border region + # + size1 = np.sum(out == 1) + size2 = np.sum(out == 2) + self.assertTrue(abs(size1 - size2) <= 6) + + def test_watershed09(self): + """Test on an image of reasonable size + + This is here both for timing (does it take forever?) and to + ensure that the memory constraints are reasonable + """ + image = np.zeros((1000, 1000)) + coords = np.random.uniform(0, 1000, (100, 2)).astype(int) + markers = np.zeros((1000, 1000), int) + idx = 1 + for x, y in coords: + image[x, y] = 1 + markers[x, y] = idx + idx += 1 + + image = gaussian(image, sigma=4, mode='reflect') + watershed(image, markers, self.eight) + ndi.watershed_ift(image.astype(np.uint16), markers, self.eight) + + def test_watershed10(self): + "watershed 10" + data = np.array( + [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], np.uint8 + ) + markers = np.array( + [[1, 0, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [3, 0, 0, 4]], np.int8 + ) + out = watershed(data, markers, self.eight) + error = diff([[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]], out) + self.assertTrue(error < eps) + + def test_watershed11(self): + '''Make sure that all points on this plateau are assigned to closest seed''' + # https://github.com/scikit-image/scikit-image/issues/803 + # + # Make sure that no point in a level image is farther away + # from its seed than any other + # + image = np.zeros((21, 21)) + markers = np.zeros((21, 21), int) + markers[5, 5] = 1 + markers[5, 10] = 2 + markers[10, 5] = 3 + markers[10, 10] = 4 + + structure = np.array( + [[False, True, False], [True, True, True], [False, True, False]] + ) + out = watershed(image, markers, structure) + i, j = np.mgrid[0:21, 0:21] + d = np.dstack( + [ + np.sqrt((i.astype(float) - i0) ** 2, (j.astype(float) - j0) ** 2) + for i0, j0 in ((5, 5), (5, 10), (10, 5), (10, 10)) + ] + ) + dmin = np.min(d, 2) + self.assertTrue(np.all(d[i, j, out[i, j] - 1] == dmin)) + + def test_watershed12(self): + "The watershed line" + data = np.array( + [ + [ + 203, + 255, + 203, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + ], + [ + 203, + 255, + 203, + 153, + 153, + 153, + 102, + 102, + 102, + 102, + 102, + 102, + 153, + 153, + 153, + 153, + ], + [ + 203, + 255, + 203, + 203, + 153, + 153, + 102, + 102, + 77, + 0, + 102, + 102, + 153, + 153, + 203, + 203, + ], + [ + 203, + 255, + 255, + 203, + 153, + 153, + 153, + 102, + 102, + 102, + 102, + 153, + 153, + 203, + 203, + 255, + ], + [ + 203, + 203, + 255, + 203, + 203, + 203, + 153, + 153, + 153, + 153, + 153, + 153, + 203, + 203, + 255, + 255, + ], + [ + 153, + 203, + 255, + 255, + 255, + 203, + 203, + 203, + 203, + 203, + 203, + 203, + 203, + 255, + 255, + 203, + ], + [ + 153, + 203, + 203, + 203, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 203, + 203, + ], + [ + 153, + 153, + 153, + 203, + 203, + 203, + 203, + 203, + 255, + 203, + 203, + 203, + 203, + 203, + 203, + 153, + ], + [ + 102, + 102, + 153, + 153, + 153, + 153, + 203, + 203, + 255, + 203, + 203, + 255, + 203, + 153, + 153, + 153, + ], + [ + 102, + 102, + 102, + 102, + 102, + 153, + 203, + 255, + 255, + 203, + 203, + 203, + 203, + 153, + 102, + 153, + ], + [ + 102, + 51, + 51, + 102, + 102, + 153, + 203, + 255, + 203, + 203, + 153, + 153, + 153, + 153, + 102, + 153, + ], + [ + 77, + 51, + 51, + 102, + 153, + 153, + 203, + 255, + 203, + 203, + 203, + 153, + 102, + 102, + 102, + 153, + ], + [ + 77, + 0, + 51, + 102, + 153, + 203, + 203, + 255, + 203, + 255, + 203, + 153, + 102, + 51, + 102, + 153, + ], + [ + 77, + 0, + 51, + 102, + 153, + 203, + 255, + 255, + 203, + 203, + 203, + 153, + 102, + 0, + 102, + 153, + ], + [ + 102, + 0, + 51, + 102, + 153, + 203, + 255, + 203, + 203, + 153, + 153, + 153, + 102, + 102, + 102, + 153, + ], + [ + 102, + 102, + 102, + 102, + 153, + 203, + 255, + 203, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + 153, + ], + ] + ) + markerbin = data == 0 + marker = label(markerbin) + ws = watershed(data, marker, connectivity=2, watershed_line=True) + for lab, area in zip(range(4), [34, 74, 74, 74]): + self.assertTrue(np.sum(ws == lab) == area) + + def test_watershed_input_not_modified(self): + """Test to ensure input markers are not modified.""" + image = np.random.default_rng().random(size=(21, 21)) + markers = np.zeros((21, 21), dtype=np.uint8) + markers[[5, 5, 15, 15], [5, 15, 5, 15]] = [1, 2, 3, 4] + original_markers = np.copy(markers) + result = watershed(image, markers) + np.testing.assert_equal(original_markers, markers) + assert not np.all(result == markers) + + +def test_compact_watershed(): + # in this test, when compactness is greater than zero the watershed line + # is labeled with the closest marker (label=2) + # when compactness is zero the watershed line is labeled with + # the marker that reaches it first (label=1) + # because it has a zero cost path to the line. + image = np.zeros((5, 6)) + image[:, 3] = 2 # watershed line + image[:, 4:] = 1 + seeds = np.zeros((5, 6), dtype=int) + seeds[2, 0] = 1 + seeds[2, 5] = 2 + compact = watershed(image, seeds, compactness=0.01) + expected = np.array( + [ + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + [1, 1, 1, 2, 2, 2], + ], + dtype=int, + ) + np.testing.assert_equal(compact, expected) + normal = watershed(image, seeds) + expected = np.array( + [ + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + ], + dtype=int, + ) + np.testing.assert_equal(normal, expected) + + # checks that compact watershed labels with watershed lines are + # a subset of the labels from compact watershed for this specific example + compact_wsl = watershed(image, seeds, compactness=0.01, watershed_line=True) + difference = compact_wsl != compact + difference[compact_wsl == 0] = False + + assert not np.any(difference) + + +def test_watershed_with_markers_offset(): + """ + Regression test from https://github.com/scikit-image/scikit-image/issues/6632 + Generate an initial image with two overlapping circles. + """ + # Generate an initial image with two overlapping circles + x, y = np.indices((80, 80)) + x1, y1, x2, y2 = 28, 28, 44, 52 + r1, r2 = 16, 20 + mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 + mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 + image = np.logical_or(mask_circle1, mask_circle2) + + # Now we want to separate the two objects in image + # Generate the markers as local maxima of the distance to the background + # and then apply an y-offset + distance = ndi.distance_transform_edt(image) + coords = peak_local_max(distance, footprint=np.ones((3, 3)), labels=image) + coords[:, 0] += 6 + mask = np.zeros(distance.shape, dtype=bool) + mask[tuple(coords.T)] = True + markers, _ = ndi.label(mask) + + labels = watershed(-distance, markers, mask=image) + + # Assert pixel count from reviewed reproducing example in bug report + # Generally, assert both objects have covered their basin + props = skimage.measure.regionprops(labels) + assert props[0].eccentricity <= 0.5 + assert props[1].eccentricity <= 0.5 + assert props[0].num_pixels == 732 + assert props[1].num_pixels == 1206 + + +def test_watershed_simple_basin_overspill(): + """ + Test behavior when markers spill over into another basin / compete. + + Regression test for + https://github.com/scikit-image/scikit-image/issues/6632. + """ + image = -np.array([1, 2, 2, 2, 2, 2, 3]) + markers = np.array([1, 0, 0, 0, 0, 0, 2]) + expected = np.array([1, 1, 1, 1, 2, 2, 2]) + result = watershed(image, markers=markers, mask=image != 0) + np.testing.assert_array_equal(result, expected) + + +def test_numeric_seed_watershed(): + """Test that passing just the number of seeds to watershed works.""" + image = np.zeros((5, 6)) + image[:, 3:] = 1 + compact = watershed(image, 2, compactness=0.01) + expected = np.array( + [ + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + [1, 1, 1, 1, 2, 2], + ], + dtype=np.int32, + ) + np.testing.assert_equal(compact, expected) + + +@pytest.mark.parametrize( + 'dtype', + [np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64, np.int64], +) +def test_watershed_output_dtype(dtype): + image = np.zeros((100, 100)) + markers = np.zeros((100, 100), dtype) + out = watershed(image, markers) + assert out.dtype == markers.dtype + + +def test_incorrect_markers_shape(): + image = np.ones((5, 6)) + markers = np.ones((5, 7)) + with pytest.raises(ValueError): + watershed(image, markers) + + +def test_incorrect_mask_shape(): + image = np.ones((5, 6)) + mask = np.ones((5, 7)) + with pytest.raises(ValueError): + watershed(image, markers=4, mask=mask) + + +def test_markers_in_mask(): + data = blob + mask = data != 255 + out = watershed(data, 25, connectivity=2, mask=mask) + # There should be no markers where the mask is false + assert np.all(out[~mask] == 0) + + +def test_no_markers(): + data = blob + mask = data != 255 + out = watershed(data, mask=mask) + assert np.max(out) == 2 + + +def test_connectivity(): + """ + Watershed segmentation should output different result for + different connectivity + when markers are calculated where None is supplied. + Issue = 5084 + """ + # Generate a dummy BrightnessTemperature image + x, y = np.indices((406, 270)) + x1, y1, x2, y2, x3, y3, x4, y4 = 200, 208, 300, 120, 100, 100, 340, 208 + r1, r2, r3, r4 = 100, 50, 40, 80 + mask_circle1 = (x - x1) ** 2 + (y - y1) ** 2 < r1**2 + mask_circle2 = (x - x2) ** 2 + (y - y2) ** 2 < r2**2 + mask_circle3 = (x - x3) ** 2 + (y - y3) ** 2 < r3**2 + mask_circle4 = (x - x4) ** 2 + (y - y4) ** 2 < r4**2 + image = np.logical_or(mask_circle1, mask_circle2) + image = np.logical_or(image, mask_circle3) + image = np.logical_or(image, mask_circle4) + + # calculate distance in discrete increase + DummyBT = ndi.distance_transform_edt(image) + DummyBT_dis = np.around(DummyBT / 12, decimals=0) * 12 + # calculate the mask + Img_mask = np.where(DummyBT_dis == 0, 0, 1) + + # segments for connectivity 1 and 2 + labels_c1 = watershed( + 200 - DummyBT_dis, mask=Img_mask, connectivity=1, compactness=0.01 + ) + labels_c2 = watershed( + 200 - DummyBT_dis, mask=Img_mask, connectivity=2, compactness=0.01 + ) + + # assertions + assert np.unique(labels_c1).shape[0] == 6 + assert np.unique(labels_c2).shape[0] == 5 + + # checking via area of each individual segment. + for lab, area in zip(range(6), [61824, 3653, 20467, 11097, 1300, 11279]): + assert np.sum(labels_c1 == lab) == area + + for lab, area in zip(range(5), [61824, 3653, 20466, 12385, 11292]): + assert np.sum(labels_c2 == lab) == area