inductor_pass.py 2.47 KB
Newer Older
1
2
3
import hashlib
import inspect
import types
4
from abc import ABC, abstractmethod
5
from typing import Any, Callable, Optional, Union
6
7

import torch
8
from torch import fx
9
10
11


class InductorPass(ABC):
12
13
14
15
    """
    General custom inductor pass interface.
    TODO(torch==2.6) use torch._inductor.custom_graph_pass.CustomGraphPass
    """
16
17
18

    @abstractmethod
    def __call__(self, graph: torch.fx.Graph):
19
20
21
        """
        Execute the pass on the given graph.
        """
22
23
        raise NotImplementedError

24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    def uuid(self) -> Any:
        """
        Provide a unique identifier for the pass, used in Inductor code cache.
        This should depend on the pass implementation, so that changes to the
        pass result in recompilation.
        By default, the object source is hashed.
        """
        return InductorPass.hash_source(self)

    @staticmethod
    def hash_source(*srcs: Union[str, Any]):
        """
        Utility method to hash the sources of functions or objects.
        :param srcs: strings or objects to add to the hash.
        Objects and functions have their source inspected.
        :return:
        """
        hasher = hashlib.sha256()
        for src in srcs:
            if isinstance(src, str):
                src_str = src
            elif isinstance(src, types.FunctionType):
                src_str = inspect.getsource(src)
            else:
                src_str = inspect.getsource(src.__class__)
            hasher.update(src_str.encode("utf-8"))
        return hasher.digest()


class CallableInductorPass(InductorPass):
    """
    This class is a wrapper for a callable that automatically provides an
    implementation of the UUID.
    """

    def __init__(self,
                 callable: Callable[[fx.Graph], None],
                 uuid: Optional[Any] = None):
        self.callable = callable
        if uuid is None:
            uuid = InductorPass.hash_source(callable)
        self._uuid = uuid

    def __call__(self, graph: torch.fx.Graph):
        self.callable(graph)

    def uuid(self) -> Any:
        return self._uuid

    def __getstate__(self):
        """
        Pickling occurs in the Inductor code cache if a pass is not given to
        the pass manager but is instead directly added to config as a pass.
        See PostGradPassManager for more.

        TODO(torch==2.6), use the `uuid` method in CustomGraphPass instead.
        """
        return self._uuid

    def __setstate__(self, state):
        raise ValueError("Cannot unpickle CallableInductorPass")