|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import dataclasses |
| 4 | +import functools |
| 5 | +import hashlib |
| 6 | +import inspect |
| 7 | +import logging |
| 8 | +import os |
| 9 | +from pathlib import Path |
| 10 | +import textwrap |
| 11 | +from typing import TYPE_CHECKING |
| 12 | +from typing import Sequence |
| 13 | + |
| 14 | +import torch |
| 15 | + |
| 16 | +from .._utils import counters |
| 17 | +from ..runtime.config import Config |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from ..runtime.kernel import Kernel |
| 21 | + |
| 22 | +log: logging.Logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | +""" |
| 25 | +TODO(oulgen) |
| 26 | +- Allow user defined cache keys that can be passed on @helion.kernel |
| 27 | +- Add import/export for set of configs |
| 28 | +""" |
| 29 | + |
| 30 | + |
| 31 | +@dataclasses.dataclass(frozen=True) |
| 32 | +class AutotuneCacheKey: |
| 33 | + """ |
| 34 | + helion_key: Hash of source code of Helion |
| 35 | + torch_key: Hash of source code of PyTorch |
| 36 | + system_hash: Hash of system information, |
| 37 | + including Triton, current device, cuda/rocm arch version |
| 38 | + function_source_hash: Hash of source code of input Helion kernel |
| 39 | + input_dtypes: dtypes of input tensors |
| 40 | + input_shapes: shapes of input tensors |
| 41 | + """ |
| 42 | + |
| 43 | + helion_key: str |
| 44 | + torch_key: str |
| 45 | + system_hash: str |
| 46 | + kernel_source_hash: str |
| 47 | + input_dtypes: list[tuple[int, torch.dtype]] |
| 48 | + input_shapes: list[tuple[int, torch.Size]] |
| 49 | + |
| 50 | + def stable_hash(self) -> str: |
| 51 | + return hashlib.sha256(repr(self).encode("utf-8")).hexdigest() |
| 52 | + |
| 53 | + |
| 54 | +class AutotuneCache: |
| 55 | + def __init__(self, kernel: Kernel, args: Sequence[object]) -> None: |
| 56 | + self.key: AutotuneCacheKey = AutotuneCache._generate_key(kernel, args) |
| 57 | + |
| 58 | + @staticmethod |
| 59 | + def _generate_key(kernel: Kernel, args: Sequence[object]) -> AutotuneCacheKey: |
| 60 | + from torch._inductor.codecache import CacheBase |
| 61 | + from torch._inductor.codecache import torch_key |
| 62 | + |
| 63 | + kernel_source = textwrap.dedent(inspect.getsource(kernel.fn)) |
| 64 | + kernel_source_hash = hashlib.sha256(kernel_source.encode("utf-8")).hexdigest() |
| 65 | + |
| 66 | + input_dtypes = [] |
| 67 | + input_shapes = [] |
| 68 | + |
| 69 | + for idx, a in enumerate(args): |
| 70 | + if isinstance(a, torch.Tensor): |
| 71 | + input_dtypes.append((idx, a.dtype)) |
| 72 | + input_shapes.append((idx, a.shape)) |
| 73 | + |
| 74 | + return AutotuneCacheKey( |
| 75 | + helion_key=helion_key(), |
| 76 | + torch_key=torch_key().hex(), |
| 77 | + system_hash=CacheBase.get_system()["hash"], |
| 78 | + kernel_source_hash=kernel_source_hash, |
| 79 | + input_dtypes=input_dtypes, |
| 80 | + input_shapes=input_shapes, |
| 81 | + ) |
| 82 | + |
| 83 | + def _get_cache_key(self) -> str: |
| 84 | + return self.key.stable_hash() |
| 85 | + |
| 86 | + def _get_local_cache_path(self) -> Path: |
| 87 | + from torch._inductor.runtime.cache_dir_utils import ( |
| 88 | + cache_dir, # pyright: ignore[reportPrivateImportUsage] |
| 89 | + ) |
| 90 | + |
| 91 | + return Path(cache_dir()) / "helion" / f"{self._get_cache_key()}.best_config" |
| 92 | + |
| 93 | + def get(self) -> Config | None: |
| 94 | + path = self._get_local_cache_path() |
| 95 | + try: |
| 96 | + config = Config.load(path) |
| 97 | + log.debug("Cache hit on config at %s", path) |
| 98 | + counters["autotune"]["cache_hit"] += 1 |
| 99 | + return config |
| 100 | + except Exception: |
| 101 | + log.debug("Cache miss on config at %s", path) |
| 102 | + counters["autotune"]["cache_miss"] += 1 |
| 103 | + return None |
| 104 | + |
| 105 | + def put(self, config: Config) -> None: |
| 106 | + path = self._get_local_cache_path() |
| 107 | + config.save(path) |
| 108 | + log.debug("Cache write of config at %s", path) |
| 109 | + counters["autotune"]["cache_put"] += 1 |
| 110 | + |
| 111 | + |
| 112 | +@functools.cache |
| 113 | +def helion_key() -> str: |
| 114 | + from torch._inductor.codecache import build_code_hash |
| 115 | + |
| 116 | + here = os.path.abspath(__file__) |
| 117 | + helion_path = os.path.dirname(os.path.dirname(here)) |
| 118 | + |
| 119 | + combined_hash = hashlib.sha256() |
| 120 | + build_code_hash([helion_path], "", combined_hash) |
| 121 | + return combined_hash.hexdigest() |
0 commit comments