Commit ·
eb8af13
1
Parent(s): 513a552
Upload folder using huggingface_hub (part 18)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +6 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/debug_utils.py +284 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/halide.py +1714 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/memory_planning.py +816 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mps.py +1070 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py +24 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mtia/__init__.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py +20 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/multi_kernel.py +513 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py +34 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/__init__.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-311.pyc +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-311.pyc +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py +625 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_template.py +110 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py +58 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py +979 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py +1016 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/compile_command.py +148 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_benchmark_request.py +143 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py +99 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_kernel.py +297 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_template.py +192 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_template_buffer.py +27 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_utils.py +17 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/segmented_tree.py +241 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/simd.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/simd_kernel_features.py +618 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/subgraph.py +209 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton_combo_kernel.py +978 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton_split_scan.py +224 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton_utils.py +259 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/wrapper.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/wrapper_fxir.py +861 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/xpu/__init__.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py +67 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comm_analysis.py +320 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comm_lowering.py +366 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comms.py +1859 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comms_debug.py +112 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx_async.py +398 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx_ext.py +681 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx_subproc.py +93 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__init__.py +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__main__.py +80 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__pycache__/__init__.cpython-311.pyc +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__pycache__/utils.cpython-311.pyc +0 -0
- pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/subproc_pool.py +436 -0
.gitattributes
CHANGED
|
@@ -1269,3 +1269,9 @@ pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_functorch/__pycac
|
|
| 1269 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/__pycache__/codecache.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1270 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/__pycache__/utils.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1271 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1269 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/__pycache__/codecache.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1270 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/__pycache__/utils.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1271 |
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/__pycache__/common.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1272 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_refs/__pycache__/__init__.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1273 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1274 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/autograd/__pycache__/gradcheck.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1275 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
| 1276 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/bin/protoc-3.13.0.0 filter=lfs diff=lfs merge=lfs -text
|
| 1277 |
+
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/debug_utils.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import functools
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
from enum import Enum
|
| 8 |
+
from typing import Callable, Optional
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch import dtype as torch_dtype
|
| 12 |
+
|
| 13 |
+
from .. import config
|
| 14 |
+
from ..virtualized import V
|
| 15 |
+
from .multi_kernel import MultiKernel
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
log = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _print_debugging_tensor_value_info(msg, arg):
|
| 22 |
+
# helper for printing debugging stats for intermediate tensor values
|
| 23 |
+
# at jit inductor level codegen
|
| 24 |
+
max_numel_to_print = 64
|
| 25 |
+
print(msg)
|
| 26 |
+
if not isinstance(arg, torch.Tensor):
|
| 27 |
+
print("Value: ", arg)
|
| 28 |
+
return
|
| 29 |
+
numel = arg.float().numel()
|
| 30 |
+
# print the debug printing stats
|
| 31 |
+
if numel <= max_numel_to_print:
|
| 32 |
+
print(arg)
|
| 33 |
+
print("Number of elements: ", numel)
|
| 34 |
+
print("Size: ", arg.float().size())
|
| 35 |
+
print("Dtype: ", arg.float().mean().item())
|
| 36 |
+
print("Mean: ", arg.float().mean().item())
|
| 37 |
+
print("Min: ", arg.float().min().item())
|
| 38 |
+
print("Max: ", arg.float().max().item())
|
| 39 |
+
print("Std: ", arg.float().std().item())
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# AOTI debug printing related configs
|
| 43 |
+
class IntermediateValueDebuggingLevel(Enum):
|
| 44 |
+
# OFF: No intermediate tensor value debug info will be printed or saved.
|
| 45 |
+
OFF = "0"
|
| 46 |
+
# LEVEL 1: Save all intermediate tensor values to individual `.pt` files. No debug printing will be displayed.
|
| 47 |
+
SAVE_ONLY = "1"
|
| 48 |
+
# LEVEL 2: Print all intermediate tensor values by default to the console. No debug saving will be performed.
|
| 49 |
+
PRINT_ONLY = "2"
|
| 50 |
+
# LEVEL 3: Print all kernel names to the console only. No debug saving/printing for input tensor value info will be performed.
|
| 51 |
+
# This mode can be helpful in cases when you just want to pinpointing what kernel is running into a CUDA IMA issue, etc.
|
| 52 |
+
PRINT_KERNEL_NAMES_ONLY = "3"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class DebugPrinterManager:
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
debug_printer_level,
|
| 59 |
+
use_array_ref: bool,
|
| 60 |
+
writeline: Optional[Callable[..., None]] = None,
|
| 61 |
+
args_to_print_or_save: Optional[list[str]] = None,
|
| 62 |
+
kernel_name: str = "",
|
| 63 |
+
kernel=None,
|
| 64 |
+
arg_signatures: Optional[list[type]] = None,
|
| 65 |
+
kernel_type=None,
|
| 66 |
+
):
|
| 67 |
+
self.debug_printer_level = IntermediateValueDebuggingLevel(debug_printer_level)
|
| 68 |
+
self.use_array_ref = use_array_ref
|
| 69 |
+
if args_to_print_or_save is None:
|
| 70 |
+
args_to_print_or_save = []
|
| 71 |
+
self.args_to_print_or_save = args_to_print_or_save
|
| 72 |
+
self.kernel_name = kernel_name
|
| 73 |
+
self.arg_signatures: Optional[list[type]] = None
|
| 74 |
+
self.kernel = kernel
|
| 75 |
+
self.filtered_kernel_names_to_print = self._get_debug_filtered_kernel_names()
|
| 76 |
+
self.kernel_type = None
|
| 77 |
+
|
| 78 |
+
def __enter__(self):
|
| 79 |
+
self._perform_debug_print_or_save_helper(
|
| 80 |
+
self.args_to_print_or_save,
|
| 81 |
+
self.kernel_name,
|
| 82 |
+
before_launch=True,
|
| 83 |
+
arg_signatures=self.arg_signatures,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def __exit__(self, args_to_print_or_save, kernel_name, arg_signatures):
|
| 87 |
+
self._perform_debug_print_or_save_helper(
|
| 88 |
+
args_to_print_or_save,
|
| 89 |
+
kernel_name,
|
| 90 |
+
before_launch=False,
|
| 91 |
+
arg_signatures=arg_signatures,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def _perform_debug_print_or_save_helper(
|
| 95 |
+
self,
|
| 96 |
+
args_to_print_or_save,
|
| 97 |
+
kernel_name,
|
| 98 |
+
before_launch,
|
| 99 |
+
arg_signatures: Optional[list[type]] = None,
|
| 100 |
+
):
|
| 101 |
+
if self.debug_printer_level == IntermediateValueDebuggingLevel.OFF:
|
| 102 |
+
return
|
| 103 |
+
if self.debug_printer_level == IntermediateValueDebuggingLevel.SAVE_ONLY:
|
| 104 |
+
# by default save all the tensor values before launch
|
| 105 |
+
self.codegen_intermediate_tensor_value_save(
|
| 106 |
+
self.args_to_print_or_save,
|
| 107 |
+
self.kernel_name,
|
| 108 |
+
before_launch,
|
| 109 |
+
arg_signatures=self.arg_signatures,
|
| 110 |
+
)
|
| 111 |
+
if self.debug_printer_level == IntermediateValueDebuggingLevel.PRINT_ONLY:
|
| 112 |
+
# by default print all the tensor values before launch
|
| 113 |
+
self.codegen_intermediate_tensor_value_print(
|
| 114 |
+
self.args_to_print_or_save,
|
| 115 |
+
self.kernel_name,
|
| 116 |
+
before_launch,
|
| 117 |
+
arg_signatures=self.arg_signatures,
|
| 118 |
+
)
|
| 119 |
+
if (
|
| 120 |
+
self.debug_printer_level
|
| 121 |
+
== IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY
|
| 122 |
+
):
|
| 123 |
+
# Print all kernel names to the console only
|
| 124 |
+
self.codegen_intermediate_tensor_value_print(
|
| 125 |
+
[],
|
| 126 |
+
self.kernel_name,
|
| 127 |
+
before_launch,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
@functools.lru_cache # noqa: B019
|
| 131 |
+
def _get_debug_filtered_kernel_names(self) -> list[str]:
|
| 132 |
+
if config.aot_inductor.filtered_kernel_names is None:
|
| 133 |
+
return []
|
| 134 |
+
return [
|
| 135 |
+
x.strip()
|
| 136 |
+
for x in config.aot_inductor.filtered_kernel_names.lower().split(",")
|
| 137 |
+
]
|
| 138 |
+
|
| 139 |
+
def set_printer_args(
|
| 140 |
+
self,
|
| 141 |
+
args_to_print_or_save: list[str],
|
| 142 |
+
kernel_name: str,
|
| 143 |
+
arg_signatures: Optional[list[type]],
|
| 144 |
+
kernel,
|
| 145 |
+
kernel_type=None,
|
| 146 |
+
):
|
| 147 |
+
# Note: MultiKernel debug printing is not supported for now
|
| 148 |
+
if isinstance(kernel, MultiKernel):
|
| 149 |
+
log.info(
|
| 150 |
+
"MultiKernel type is not supported in AOTI debug printer tool yet."
|
| 151 |
+
)
|
| 152 |
+
self.debug_printer_level = IntermediateValueDebuggingLevel.OFF
|
| 153 |
+
|
| 154 |
+
self.kernel_type = kernel_type
|
| 155 |
+
# Note: if the kernel type is an extern kernel (or cpp kernel), we do a special handling to
|
| 156 |
+
# get the list of args_to_print_or_save
|
| 157 |
+
# TODO: Find a more reliable way to detect kernel args types to print for extern kernel calls
|
| 158 |
+
if kernel_type == "extern":
|
| 159 |
+
args_to_print_or_save_extern = [
|
| 160 |
+
arg for arg in args_to_print_or_save if arg.startswith(("buf", "arg"))
|
| 161 |
+
]
|
| 162 |
+
self.args_to_print_or_save = args_to_print_or_save_extern
|
| 163 |
+
elif kernel_type == "cpp":
|
| 164 |
+
self.args_to_print_or_save = [
|
| 165 |
+
(
|
| 166 |
+
f"copy_arrayref_tensor_to_tensor({arg})"
|
| 167 |
+
if self.use_array_ref
|
| 168 |
+
else arg
|
| 169 |
+
)
|
| 170 |
+
for arg in args_to_print_or_save
|
| 171 |
+
if arg.startswith(("buf", "arg"))
|
| 172 |
+
]
|
| 173 |
+
else:
|
| 174 |
+
self.args_to_print_or_save = args_to_print_or_save
|
| 175 |
+
self.kernel_name = kernel_name
|
| 176 |
+
self.arg_signatures = arg_signatures
|
| 177 |
+
self.kernel = kernel
|
| 178 |
+
|
| 179 |
+
def codegen_model_inputs_value_print(self, input_args_to_print: list[str]) -> None:
|
| 180 |
+
if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY:
|
| 181 |
+
return
|
| 182 |
+
for arg in input_args_to_print:
|
| 183 |
+
if V.graph.cpp_wrapper:
|
| 184 |
+
V.graph.wrapper_code.prefix.writeline(
|
| 185 |
+
f'aoti_torch_print_tensor_handle({arg}, "aoti_model_inputs - {arg}");'
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def codegen_intermediate_tensor_value_save(
|
| 189 |
+
self,
|
| 190 |
+
args_to_save,
|
| 191 |
+
kernel_name,
|
| 192 |
+
before_launch=True,
|
| 193 |
+
arg_signatures: Optional[list[type]] = None,
|
| 194 |
+
) -> None:
|
| 195 |
+
for i, arg in enumerate(args_to_save):
|
| 196 |
+
if arg_signatures is not None and not isinstance(
|
| 197 |
+
arg_signatures[i], torch_dtype
|
| 198 |
+
):
|
| 199 |
+
# infer from the arg data type (has torch.dtype) to see if it is a tensor type
|
| 200 |
+
continue
|
| 201 |
+
launch_prefix = "before_launch" if before_launch else "after_launch"
|
| 202 |
+
if V.graph.cpp_wrapper:
|
| 203 |
+
V.graph.wrapper_code.writeline(
|
| 204 |
+
f'aoti_torch_save_tensor_handle({arg}, "{arg}", "{launch_prefix}", "{kernel_name}");'
|
| 205 |
+
)
|
| 206 |
+
else:
|
| 207 |
+
cwd = os.getcwd()
|
| 208 |
+
saved_dir = cwd + "/tmp/jit_inductor/"
|
| 209 |
+
if not os.path.exists(saved_dir):
|
| 210 |
+
log.info(
|
| 211 |
+
"Creating directory to save inductor intermediate tensor values."
|
| 212 |
+
)
|
| 213 |
+
os.makedirs(saved_dir)
|
| 214 |
+
# Save the model to the directory
|
| 215 |
+
saved_path = saved_dir + f"{launch_prefix}_{kernel_name}_{arg}.pt"
|
| 216 |
+
log.info(
|
| 217 |
+
"Saved intermediate tensor %s for %s to %s",
|
| 218 |
+
arg,
|
| 219 |
+
kernel_name,
|
| 220 |
+
saved_path,
|
| 221 |
+
)
|
| 222 |
+
line = f"torch.save({arg}, '{saved_path}')"
|
| 223 |
+
V.graph.wrapper_code.writeline(line)
|
| 224 |
+
|
| 225 |
+
def codegen_intermediate_tensor_value_print(
|
| 226 |
+
self,
|
| 227 |
+
args_to_print,
|
| 228 |
+
kernel_name,
|
| 229 |
+
before_launch=True,
|
| 230 |
+
arg_signatures: Optional[list[type]] = None,
|
| 231 |
+
) -> None:
|
| 232 |
+
launch_prefix = "before_launch" if before_launch else "after_launch"
|
| 233 |
+
|
| 234 |
+
# if the debug printing level is PRINT_KERNEL_NAMES_ONLY
|
| 235 |
+
# we only print the kernel name to the console
|
| 236 |
+
if (
|
| 237 |
+
self.debug_printer_level
|
| 238 |
+
== IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY
|
| 239 |
+
):
|
| 240 |
+
if V.graph.cpp_wrapper:
|
| 241 |
+
V.graph.wrapper_code.writeline(
|
| 242 |
+
f'printf("[ {launch_prefix}: {kernel_name} ]\\n");'
|
| 243 |
+
)
|
| 244 |
+
return
|
| 245 |
+
|
| 246 |
+
if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY:
|
| 247 |
+
return
|
| 248 |
+
for i, arg in enumerate(args_to_print):
|
| 249 |
+
# when debug printing is enabled i.e. IntermediateValueDebuggingLevel.PRINT_ONLY,
|
| 250 |
+
# check if filtered kernel name list is provided
|
| 251 |
+
if (
|
| 252 |
+
len(self.filtered_kernel_names_to_print) > 0
|
| 253 |
+
and kernel_name.lower() not in self.filtered_kernel_names_to_print
|
| 254 |
+
):
|
| 255 |
+
continue
|
| 256 |
+
if V.graph.cpp_wrapper:
|
| 257 |
+
if arg_signatures is not None and isinstance(
|
| 258 |
+
arg_signatures[i], torch_dtype
|
| 259 |
+
):
|
| 260 |
+
# infer from the arg data type (has torch.dtype) to see if it is a tensor type
|
| 261 |
+
V.graph.wrapper_code.writeline(
|
| 262 |
+
f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");'
|
| 263 |
+
)
|
| 264 |
+
elif arg_signatures is not None and isinstance(
|
| 265 |
+
arg_signatures[i],
|
| 266 |
+
(
|
| 267 |
+
type(torch._inductor.codegen.wrapper.SymbolicCallArg),
|
| 268 |
+
type(int),
|
| 269 |
+
type(float),
|
| 270 |
+
type(bool),
|
| 271 |
+
),
|
| 272 |
+
):
|
| 273 |
+
V.graph.wrapper_code.writeline(
|
| 274 |
+
f'printf("[ {launch_prefix} - {kernel_name} - {arg}: %ld ]", {arg}); printf("\\\\n");'
|
| 275 |
+
)
|
| 276 |
+
else:
|
| 277 |
+
if arg_signatures is None and self.kernel_type == "cpp" or "extern":
|
| 278 |
+
V.graph.wrapper_code.writeline(
|
| 279 |
+
f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");'
|
| 280 |
+
)
|
| 281 |
+
else:
|
| 282 |
+
V.graph.wrapper_code.writeline(
|
| 283 |
+
f'_print_debugging_tensor_value_info("inductor: {launch_prefix} - {kernel_name} - {arg}", {arg})'
|
| 284 |
+
)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/halide.py
ADDED
|
@@ -0,0 +1,1714 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import dataclasses
|
| 5 |
+
import functools
|
| 6 |
+
import itertools
|
| 7 |
+
import logging
|
| 8 |
+
import re
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from math import inf
|
| 11 |
+
from typing import Any, Callable, cast, Optional, TYPE_CHECKING, Union
|
| 12 |
+
|
| 13 |
+
import sympy
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch._logging
|
| 17 |
+
|
| 18 |
+
from ..._prims_common import is_integer_dtype
|
| 19 |
+
from ...utils._ordered_set import OrderedSet
|
| 20 |
+
from ...utils._sympy.functions import FloorDiv, ModularIndexing
|
| 21 |
+
from ...utils._sympy.symbol import symbol_is_type, SymT
|
| 22 |
+
from ...utils._sympy.value_ranges import ValueRanges
|
| 23 |
+
from .. import config, ir
|
| 24 |
+
from ..codecache import HalideCodeCache
|
| 25 |
+
from ..ir import get_reduction_combine_fn
|
| 26 |
+
from ..metrics import is_metric_table_enabled, log_kernel_metadata
|
| 27 |
+
from ..ops_handler import AddParenHandler
|
| 28 |
+
from ..runtime.hints import HalideInputSpec, HalideMeta
|
| 29 |
+
from ..utils import (
|
| 30 |
+
get_bounds_index_expr,
|
| 31 |
+
get_kernel_metadata,
|
| 32 |
+
parallel_num_threads,
|
| 33 |
+
sympy_index_symbol,
|
| 34 |
+
sympy_subs,
|
| 35 |
+
)
|
| 36 |
+
from ..virtualized import _ops as ops, V
|
| 37 |
+
from .common import (
|
| 38 |
+
BackendFeature,
|
| 39 |
+
CSEVariable,
|
| 40 |
+
DeferredLine,
|
| 41 |
+
IndentedBuffer,
|
| 42 |
+
KernelArgType,
|
| 43 |
+
OpOverrides,
|
| 44 |
+
PythonPrinter,
|
| 45 |
+
SizeArg,
|
| 46 |
+
TensorArg,
|
| 47 |
+
)
|
| 48 |
+
from .cpp import DTYPE_TO_CPP
|
| 49 |
+
from .cpp_utils import cexpr
|
| 50 |
+
from .simd import constant_repr, SIMDKernel, SIMDScheduling
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if TYPE_CHECKING:
|
| 54 |
+
from collections.abc import Sequence
|
| 55 |
+
|
| 56 |
+
from ..ops_handler import ReductionType, StoreMode
|
| 57 |
+
from ..shape_propagation import BlockShapeType
|
| 58 |
+
|
| 59 |
+
log = logging.getLogger(__name__)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def halide_constant(val):
|
| 63 |
+
if isinstance(val, int) and not (-2147483648 <= val <= 2147483647):
|
| 64 |
+
info = torch.iinfo(torch.int64)
|
| 65 |
+
if val == info.min:
|
| 66 |
+
return "hl.Int(64).min()"
|
| 67 |
+
if val == info.max:
|
| 68 |
+
return "hl.Int(64).max()"
|
| 69 |
+
return f"hl.i64({val!r})"
|
| 70 |
+
if isinstance(val, float):
|
| 71 |
+
return f"hl.f64({constant_repr(val)})"
|
| 72 |
+
return repr(val)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Unsupported(RuntimeError):
|
| 76 |
+
def __init__(self, thing) -> None:
|
| 77 |
+
super().__init__(f"halide backend does not support: {thing}")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class HalidePrinter(PythonPrinter):
|
| 81 |
+
@staticmethod
|
| 82 |
+
def cast_index(expr):
|
| 83 |
+
return f"hl.cast({V.kernel.index_dtype}, {expr})"
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def cast_float(expr):
|
| 87 |
+
return f"hl.cast(hl.Float(32), {expr})"
|
| 88 |
+
|
| 89 |
+
def _print_Float(self, expr):
|
| 90 |
+
return f"hl.f32({expr})"
|
| 91 |
+
|
| 92 |
+
def _print_ToFloat(self, expr):
|
| 93 |
+
assert len(expr.args) == 1
|
| 94 |
+
return f"hl.f32({self._print(expr.args[0])})"
|
| 95 |
+
|
| 96 |
+
def _print_floor(self, expr):
|
| 97 |
+
assert len(expr.args) == 1
|
| 98 |
+
return self.cast_index(f"hl.floor({self._print(expr.args[0])})")
|
| 99 |
+
|
| 100 |
+
_print_FloorToInt = _print_floor
|
| 101 |
+
|
| 102 |
+
def _print_Trunc(self, expr):
|
| 103 |
+
assert len(expr.args) == 1
|
| 104 |
+
return self.cast_index(f"hl.trunc({self._print(expr.args[0])})")
|
| 105 |
+
|
| 106 |
+
_print_TruncToInt = _print_Trunc
|
| 107 |
+
|
| 108 |
+
def _print_ceiling(self, expr):
|
| 109 |
+
assert len(expr.args) == 1
|
| 110 |
+
return self.cast_index(f"hl.ceil({self._print(expr.args[0])})")
|
| 111 |
+
|
| 112 |
+
def _helper_sqrt(self, expr):
|
| 113 |
+
return f"hl.sqrt({self.cast_float(self._print(expr))})"
|
| 114 |
+
|
| 115 |
+
def _print_Where(self, expr):
|
| 116 |
+
c = self.doprint(expr.args[0])
|
| 117 |
+
p = self.doprint(expr.args[1])
|
| 118 |
+
q = self.doprint(expr.args[2])
|
| 119 |
+
return f"hl.select({c}, {p}, {q})"
|
| 120 |
+
|
| 121 |
+
def _print_Min(self, expr):
|
| 122 |
+
if len(expr.args) == 1:
|
| 123 |
+
return self._print(expr.args[0])
|
| 124 |
+
|
| 125 |
+
mid = len(expr.args) // 2
|
| 126 |
+
a = self._print(sympy.Min(*expr.args[:mid]))
|
| 127 |
+
b = self._print(sympy.Min(*expr.args[mid:]))
|
| 128 |
+
return f"hl.min({a}, {b})"
|
| 129 |
+
|
| 130 |
+
def _print_Max(self, expr):
|
| 131 |
+
if len(expr.args) == 1:
|
| 132 |
+
return self._print(expr.args[0])
|
| 133 |
+
|
| 134 |
+
mid = len(expr.args) // 2
|
| 135 |
+
a = self._print(sympy.Max(*expr.args[:mid]))
|
| 136 |
+
b = self._print(sympy.Max(*expr.args[mid:]))
|
| 137 |
+
|
| 138 |
+
return f"hl.max({a}, {b})"
|
| 139 |
+
|
| 140 |
+
def _print_Abs(self, expr):
|
| 141 |
+
assert len(expr.args) == 1
|
| 142 |
+
return self.cast_index(f"hl.abs({self._print(expr.args[0])})")
|
| 143 |
+
|
| 144 |
+
def _print_OpaqueUnaryFn_cos(self, expr):
|
| 145 |
+
assert len(expr.args) == 1
|
| 146 |
+
return f"hl.cos({self._print(expr.args[0])})"
|
| 147 |
+
|
| 148 |
+
def _print_OpaqueUnaryFn_cosh(self, expr):
|
| 149 |
+
assert len(expr.args) == 1
|
| 150 |
+
return f"hl.cosh({self._print(expr.args[0])})"
|
| 151 |
+
|
| 152 |
+
def _print_OpaqueUnaryFn_acos(self, expr):
|
| 153 |
+
assert len(expr.args) == 1
|
| 154 |
+
return f"hl.acos({self._print(expr.args[0])})"
|
| 155 |
+
|
| 156 |
+
def _print_OpaqueUnaryFn_sin(self, expr):
|
| 157 |
+
assert len(expr.args) == 1
|
| 158 |
+
return f"hl.sin({self._print(expr.args[0])})"
|
| 159 |
+
|
| 160 |
+
def _print_OpaqueUnaryFn_sinh(self, expr):
|
| 161 |
+
assert len(expr.args) == 1
|
| 162 |
+
return f"hl.sinh({self._print(expr.args[0])})"
|
| 163 |
+
|
| 164 |
+
def _print_OpaqueUnaryFn_asin(self, expr):
|
| 165 |
+
assert len(expr.args) == 1
|
| 166 |
+
return f"hl.asin({self._print(expr.args[0])})"
|
| 167 |
+
|
| 168 |
+
def _print_OpaqueUnaryFn_tan(self, expr):
|
| 169 |
+
assert len(expr.args) == 1
|
| 170 |
+
return f"hl.tan({self._print(expr.args[0])})"
|
| 171 |
+
|
| 172 |
+
def _print_OpaqueUnaryFn_tanh(self, expr):
|
| 173 |
+
assert len(expr.args) == 1
|
| 174 |
+
return f"hl.tanh({self._print(expr.args[0])})"
|
| 175 |
+
|
| 176 |
+
def _print_OpaqueUnaryFn_atan(self, expr):
|
| 177 |
+
assert len(expr.args) == 1
|
| 178 |
+
return f"hl.atan({self._print(expr.args[0])})"
|
| 179 |
+
|
| 180 |
+
def _print_OpaqueUnaryFn_log2(self, expr):
|
| 181 |
+
raise NotImplementedError("log2")
|
| 182 |
+
|
| 183 |
+
def _print_FloorDiv(self, expr):
|
| 184 |
+
if expr.is_integer:
|
| 185 |
+
return super()._print_FloorDiv(expr)
|
| 186 |
+
|
| 187 |
+
x, div = expr.args
|
| 188 |
+
x = self.cast_float(self.doprint(x))
|
| 189 |
+
div = self.cast_float(self.doprint(div))
|
| 190 |
+
return self.cast_index(f"hl.floor({x} / {div})")
|
| 191 |
+
|
| 192 |
+
def _print_Round(self, expr):
|
| 193 |
+
assert len(expr.args) == 1
|
| 194 |
+
return self.cast_index(f"hl.round({self._print(expr.args[0])})")
|
| 195 |
+
|
| 196 |
+
_print_RoundToInt = _print_Round
|
| 197 |
+
|
| 198 |
+
def _print_IntTrueDiv(self, expr):
|
| 199 |
+
a, b = expr.args
|
| 200 |
+
# force a cast to float
|
| 201 |
+
return f"({a}) / ({b}+hl.f32(0))"
|
| 202 |
+
|
| 203 |
+
def _print_RoundDecimal(self, expr):
|
| 204 |
+
val, n = expr.args
|
| 205 |
+
val = self._print(val)
|
| 206 |
+
n = int(n)
|
| 207 |
+
return f"hl.f32({10.0 ** (-n)!r})*hl.round(({val})*hl.f32({10.0**n!r}))"
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
texpr = HalidePrinter().doprint
|
| 211 |
+
pexpr = PythonPrinter().doprint
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
_halide_type = {
|
| 215 |
+
torch.bool: "hl.Bool()",
|
| 216 |
+
torch.bfloat16: "hl.BFloat(16)",
|
| 217 |
+
torch.float16: "hl.Float(16)",
|
| 218 |
+
torch.float32: "hl.Float(32)",
|
| 219 |
+
torch.float64: "hl.Float(64)",
|
| 220 |
+
torch.int8: "hl.Int(8)",
|
| 221 |
+
torch.int16: "hl.Int(16)",
|
| 222 |
+
torch.int32: "hl.Int(32)",
|
| 223 |
+
torch.int64: "hl.Int(64)",
|
| 224 |
+
torch.uint8: "hl.UInt(8)",
|
| 225 |
+
torch.uint16: "hl.UInt(16)",
|
| 226 |
+
torch.uint32: "hl.UInt(32)",
|
| 227 |
+
torch.uint64: "hl.UInt(64)",
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def halide_type(dtype):
|
| 232 |
+
return _halide_type[dtype]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def halide_acc_type(dtype):
|
| 236 |
+
if is_integer_dtype(dtype) and dtype.is_signed and dtype != torch.int64:
|
| 237 |
+
dtype = torch.int32
|
| 238 |
+
if dtype in (torch.float16, torch.bfloat16):
|
| 239 |
+
dtype = torch.float32
|
| 240 |
+
return halide_type(dtype)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class HalideOverrides(OpOverrides):
|
| 244 |
+
@staticmethod
|
| 245 |
+
def to_dtype(
|
| 246 |
+
x,
|
| 247 |
+
dtype: torch.dtype,
|
| 248 |
+
src_dtype: Optional[torch.dtype] = None,
|
| 249 |
+
use_compute_types=True,
|
| 250 |
+
):
|
| 251 |
+
if dtype == torch.bool:
|
| 252 |
+
return f"({x} != 0)"
|
| 253 |
+
return f"hl.cast({halide_type(dtype)}, {x})"
|
| 254 |
+
|
| 255 |
+
@staticmethod
|
| 256 |
+
def to_dtype_bitcast(x, dtype: torch.dtype, src_dtype: torch.dtype):
|
| 257 |
+
if src_dtype in (torch.float16, torch.bfloat16):
|
| 258 |
+
x = f"hl.cast({halide_type(src_dtype)}, {x})" # body compute is upcast to fp32
|
| 259 |
+
line = f"hl.reinterpret({halide_type(dtype)}, {x})"
|
| 260 |
+
if dtype in (torch.float16, torch.bfloat16):
|
| 261 |
+
line = f"hl.cast(hl.Float(32), {line})"
|
| 262 |
+
return line
|
| 263 |
+
|
| 264 |
+
@classmethod
|
| 265 |
+
def constant(cls, value, dtype):
|
| 266 |
+
return cls.to_dtype(halide_constant(value), dtype)
|
| 267 |
+
|
| 268 |
+
@staticmethod
|
| 269 |
+
def abs(x):
|
| 270 |
+
return f"hl.abs({x})"
|
| 271 |
+
|
| 272 |
+
@staticmethod
|
| 273 |
+
def exp(x):
|
| 274 |
+
if not hasattr(x, "name"):
|
| 275 |
+
return f"hl.exp({x})"
|
| 276 |
+
return f"hl.fast_exp(hl.cast(hl.Float(32), {x})) if {x.name}.type().bits() <= 32 else hl.exp({x})"
|
| 277 |
+
|
| 278 |
+
@staticmethod
|
| 279 |
+
def sqrt(x):
|
| 280 |
+
return f"hl.sqrt({x})"
|
| 281 |
+
|
| 282 |
+
@staticmethod
|
| 283 |
+
def minimum(a, b):
|
| 284 |
+
# return f"hl.min({a}, {b})" <== handles nan wrong
|
| 285 |
+
if not hasattr(a, "name"):
|
| 286 |
+
return f"hl.min({a}, {b})"
|
| 287 |
+
b = f"hl.cast({a.name}.type(), {b})"
|
| 288 |
+
return f"hl.select(({a}<{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.min({a}, {b})"
|
| 289 |
+
|
| 290 |
+
@staticmethod
|
| 291 |
+
def maximum(a, b):
|
| 292 |
+
# return f"hl.max({a}, {b})" <== handles nan wrong
|
| 293 |
+
if not hasattr(a, "name"):
|
| 294 |
+
return f"hl.max({a}, {b})"
|
| 295 |
+
b = f"hl.cast({a.name}.type(), {b})"
|
| 296 |
+
return f"hl.select(({a}>{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.max({a}, {b})"
|
| 297 |
+
|
| 298 |
+
@staticmethod
|
| 299 |
+
def where(a, b, c):
|
| 300 |
+
if hasattr(b, "name"):
|
| 301 |
+
c = f"hl.cast({b.name}.type(), {c})"
|
| 302 |
+
return f"hl.select({a}, {b}, {c})"
|
| 303 |
+
|
| 304 |
+
@staticmethod
|
| 305 |
+
def cos(x):
|
| 306 |
+
return f"hl.cos({x})"
|
| 307 |
+
|
| 308 |
+
@staticmethod
|
| 309 |
+
def sin(x):
|
| 310 |
+
return f"hl.sin({x})"
|
| 311 |
+
|
| 312 |
+
@staticmethod
|
| 313 |
+
def lgamma(x):
|
| 314 |
+
raise Unsupported("lgamma")
|
| 315 |
+
|
| 316 |
+
@staticmethod
|
| 317 |
+
def erf(x):
|
| 318 |
+
return f"hl.erf({x})"
|
| 319 |
+
|
| 320 |
+
@staticmethod
|
| 321 |
+
def cosh(x):
|
| 322 |
+
return f"hl.cosh({x})"
|
| 323 |
+
|
| 324 |
+
@staticmethod
|
| 325 |
+
def sinh(x):
|
| 326 |
+
return f"hl.sinh({x})"
|
| 327 |
+
|
| 328 |
+
@staticmethod
|
| 329 |
+
def acos(x):
|
| 330 |
+
return f"hl.acos({x})"
|
| 331 |
+
|
| 332 |
+
@staticmethod
|
| 333 |
+
def acosh(x):
|
| 334 |
+
return f"hl.acosh({x})"
|
| 335 |
+
|
| 336 |
+
@staticmethod
|
| 337 |
+
def asin(x):
|
| 338 |
+
return f"hl.asin({x})"
|
| 339 |
+
|
| 340 |
+
@staticmethod
|
| 341 |
+
def asinh(x):
|
| 342 |
+
return f"hl.asinh({x})"
|
| 343 |
+
|
| 344 |
+
@staticmethod
|
| 345 |
+
def atan2(x, y):
|
| 346 |
+
return f"hl.atan2({x}, {y})"
|
| 347 |
+
|
| 348 |
+
@staticmethod
|
| 349 |
+
def atan(x):
|
| 350 |
+
return f"hl.atan({x})"
|
| 351 |
+
|
| 352 |
+
@staticmethod
|
| 353 |
+
def atanh(x):
|
| 354 |
+
return f"hl.atanh({x})"
|
| 355 |
+
|
| 356 |
+
@staticmethod
|
| 357 |
+
def copysign(x, y):
|
| 358 |
+
raise Unsupported("copysign")
|
| 359 |
+
|
| 360 |
+
@staticmethod
|
| 361 |
+
def erfinv(x):
|
| 362 |
+
raise Unsupported("erfinv")
|
| 363 |
+
|
| 364 |
+
@staticmethod
|
| 365 |
+
def hypot(x, y):
|
| 366 |
+
return f"hl.hypot({x}, {y})"
|
| 367 |
+
|
| 368 |
+
@staticmethod
|
| 369 |
+
def nextafter(x, y):
|
| 370 |
+
raise Unsupported("nextafter")
|
| 371 |
+
|
| 372 |
+
@staticmethod
|
| 373 |
+
def logical_and(a, b):
|
| 374 |
+
return f"{a} & {b}"
|
| 375 |
+
|
| 376 |
+
@staticmethod
|
| 377 |
+
def logical_not(a):
|
| 378 |
+
return f"{a} == 0"
|
| 379 |
+
|
| 380 |
+
@staticmethod
|
| 381 |
+
def logical_or(a, b):
|
| 382 |
+
return f"{a} | {b}"
|
| 383 |
+
|
| 384 |
+
@staticmethod
|
| 385 |
+
def logical_xor(a, b):
|
| 386 |
+
return f"({a} ^ {b})"
|
| 387 |
+
|
| 388 |
+
@staticmethod
|
| 389 |
+
def bitwise_and(a, b):
|
| 390 |
+
return f"{a} & {b}"
|
| 391 |
+
|
| 392 |
+
@staticmethod
|
| 393 |
+
def bitwise_not(a):
|
| 394 |
+
return f"~{a}"
|
| 395 |
+
|
| 396 |
+
@staticmethod
|
| 397 |
+
def bitwise_or(a, b):
|
| 398 |
+
return f"{a} | {b}"
|
| 399 |
+
|
| 400 |
+
@staticmethod
|
| 401 |
+
def bitwise_xor(a, b):
|
| 402 |
+
return f"{a} ^ {b}"
|
| 403 |
+
|
| 404 |
+
@staticmethod
|
| 405 |
+
def bitwise_left_shift(a, b):
|
| 406 |
+
return f"{a} << {b}"
|
| 407 |
+
|
| 408 |
+
@staticmethod
|
| 409 |
+
def bitwise_right_shift(a, b):
|
| 410 |
+
return f"{a} >> {b}"
|
| 411 |
+
|
| 412 |
+
@staticmethod
|
| 413 |
+
def rand(seed, offset):
|
| 414 |
+
return f"halide_helpers.rand({seed}, {offset})"
|
| 415 |
+
|
| 416 |
+
@staticmethod
|
| 417 |
+
def randn(seed, offset):
|
| 418 |
+
return f"halide_helpers.randn({seed}, {offset})"
|
| 419 |
+
|
| 420 |
+
@staticmethod
|
| 421 |
+
def randint64(seed, offset, low, high):
|
| 422 |
+
return f"halide_helpers.randint64({seed}, {offset}, {low}, {high})"
|
| 423 |
+
|
| 424 |
+
@staticmethod
|
| 425 |
+
def load_seed(name, offset):
|
| 426 |
+
return f"{ops.load(name, 0)} + {V.kernel.args.seed_offset('load_seed_offset', offset)}"
|
| 427 |
+
|
| 428 |
+
@staticmethod
|
| 429 |
+
def rsqrt(x):
|
| 430 |
+
# return f"hl.fast_inverse_sqrt({x})" <== accuracy issues
|
| 431 |
+
return f"1./hl.sqrt({x})"
|
| 432 |
+
|
| 433 |
+
@staticmethod
|
| 434 |
+
def tan(x):
|
| 435 |
+
return f"hl.tan({x})"
|
| 436 |
+
|
| 437 |
+
@staticmethod
|
| 438 |
+
def tanh(x):
|
| 439 |
+
return f"hl.tanh({x})"
|
| 440 |
+
|
| 441 |
+
@staticmethod
|
| 442 |
+
def signbit(x):
|
| 443 |
+
return f"(hl.reinterpret(hl.UInt(32), hl.cast(hl.Float(32), {x})) >> 31) != 0"
|
| 444 |
+
|
| 445 |
+
@staticmethod
|
| 446 |
+
def fmod(a, b):
|
| 447 |
+
# TODO(jansel): find a better way to do this, builtin % has wrong sign
|
| 448 |
+
return f"{a} - hl.trunc({a}/{b})*{b}"
|
| 449 |
+
|
| 450 |
+
@staticmethod
|
| 451 |
+
def pow(a, b):
|
| 452 |
+
return f"hl.pow({a}, {b})" # hl.fast_pow fails accuracy
|
| 453 |
+
|
| 454 |
+
@staticmethod
|
| 455 |
+
def log(x):
|
| 456 |
+
return f"hl.log({x})" # hl.fast_log fails accuracy
|
| 457 |
+
|
| 458 |
+
@staticmethod
|
| 459 |
+
def log2(x):
|
| 460 |
+
raise NotImplementedError("log2")
|
| 461 |
+
|
| 462 |
+
@staticmethod
|
| 463 |
+
def isinf(x):
|
| 464 |
+
# workaround https://github.com/halide/Halide/issues/8309
|
| 465 |
+
return f"hl.is_inf(hl.cast(hl.Float(32), {x}))"
|
| 466 |
+
|
| 467 |
+
@staticmethod
|
| 468 |
+
def isnan(x):
|
| 469 |
+
# workaround https://github.com/halide/Halide/issues/8309
|
| 470 |
+
return f"hl.is_nan(hl.cast(hl.Float(32), {x}))"
|
| 471 |
+
|
| 472 |
+
@staticmethod
|
| 473 |
+
def round(x):
|
| 474 |
+
return f"hl.round({x})"
|
| 475 |
+
|
| 476 |
+
@staticmethod
|
| 477 |
+
def floor(x):
|
| 478 |
+
return f"hl.floor({x})"
|
| 479 |
+
|
| 480 |
+
@staticmethod
|
| 481 |
+
def int_truediv(a, b):
|
| 482 |
+
return f"({a}) / ({b} + hl.f32(0))"
|
| 483 |
+
|
| 484 |
+
@staticmethod
|
| 485 |
+
def floordiv(a, b):
|
| 486 |
+
# TODO(jansel): find a better ways to do this, the select-based trick from triton.py didn't work
|
| 487 |
+
return (
|
| 488 |
+
f"hl.floor(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})"
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
@classmethod
|
| 492 |
+
def sign(cls, x):
|
| 493 |
+
left = ops.to_dtype(ops.lt("0", x), torch.int8)
|
| 494 |
+
right = ops.to_dtype(ops.lt(x, "0"), torch.int8)
|
| 495 |
+
sub = ops.sub(left, right)
|
| 496 |
+
return f"hl.cast({x.name}.type(), {sub})"
|
| 497 |
+
|
| 498 |
+
@staticmethod
|
| 499 |
+
def trunc(x):
|
| 500 |
+
return f"hl.trunc({x})"
|
| 501 |
+
|
| 502 |
+
@staticmethod
|
| 503 |
+
def truncdiv(a, b):
|
| 504 |
+
# this causes crashes with floating point exception, see test_div_zero_dim_cpu
|
| 505 |
+
# return f"hl.div_round_to_zero({a}, {b})"
|
| 506 |
+
return (
|
| 507 |
+
f"hl.trunc(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})"
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
@staticmethod
|
| 511 |
+
def ceil(x):
|
| 512 |
+
return f"hl.ceil({x})"
|
| 513 |
+
|
| 514 |
+
@staticmethod
|
| 515 |
+
def relu(x):
|
| 516 |
+
return f"hl.max({x}, 0)"
|
| 517 |
+
|
| 518 |
+
@classmethod
|
| 519 |
+
def index_expr(cls, expr, dtype):
|
| 520 |
+
index = V.kernel.prepare_indexing(expr)
|
| 521 |
+
var = V.kernel.genfunc(
|
| 522 |
+
V.kernel.index_to_str(index),
|
| 523 |
+
V.kernel.used_dims_from_index(index),
|
| 524 |
+
bounds=get_bounds_index_expr(expr),
|
| 525 |
+
)
|
| 526 |
+
if dtype not in (torch.int32, torch.int64):
|
| 527 |
+
return ops.to_dtype(var, dtype)
|
| 528 |
+
return var
|
| 529 |
+
|
| 530 |
+
@classmethod
|
| 531 |
+
def indirect_indexing(cls, index_var, size, check=True, wrap_neg=True):
|
| 532 |
+
# TODO(jansel): Halide only supports 32-bit indexing, we should error on overflow
|
| 533 |
+
index_var = ops.to_dtype(index_var, torch.int32)
|
| 534 |
+
index_var = ops.halide_clamp(index_var, size, check)
|
| 535 |
+
index_var.indirect_indexing_size = size
|
| 536 |
+
return sympy_index_symbol(str(index_var))
|
| 537 |
+
|
| 538 |
+
@classmethod
|
| 539 |
+
def halide_clamp(cls, value, size, check):
|
| 540 |
+
end = V.kernel.kexpr(V.kernel.rename_indexing(size) - 1)
|
| 541 |
+
if not isinstance(size, (int, sympy.Integer)):
|
| 542 |
+
end = f"hl.cast({value.name}.type(), {end})"
|
| 543 |
+
# Skip unsafe_promise_clamped to workaround: https://github.com/halide/Halide/issues/8261#issuecomment-2148835692
|
| 544 |
+
# return f"hl.unsafe_promise_clamped({value}, 0, {end})"
|
| 545 |
+
return f"hl.clamp({value}, 0, {end})"
|
| 546 |
+
|
| 547 |
+
@staticmethod
|
| 548 |
+
def masked(mask, body, other):
|
| 549 |
+
with V.kernel.mask_loads(mask, other) as new_mask:
|
| 550 |
+
result = body()
|
| 551 |
+
|
| 552 |
+
if result.bounds.is_bool:
|
| 553 |
+
other = bool(other)
|
| 554 |
+
|
| 555 |
+
# Take dtype from result to prevent accidental promotion
|
| 556 |
+
other = V.kernel.genfunc(
|
| 557 |
+
f"hl.cast({result.name}.type(), {halide_constant(other)})",
|
| 558 |
+
[],
|
| 559 |
+
bounds=ValueRanges.wrap(other),
|
| 560 |
+
shape=result.shape,
|
| 561 |
+
)
|
| 562 |
+
# TODO(jansel): look into removing the where in the same places triton does
|
| 563 |
+
return ops.where(new_mask, result, other)
|
| 564 |
+
|
| 565 |
+
@staticmethod
|
| 566 |
+
def frexp(x):
|
| 567 |
+
raise NotImplementedError("frexp")
|
| 568 |
+
|
| 569 |
+
@staticmethod
|
| 570 |
+
def device_assert_async(cond, msg):
|
| 571 |
+
raise NotImplementedError("device_assert_async")
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
HalideOverrides._initialize_pointwise_overrides("halide")
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class HalideCSEVariable(CSEVariable):
|
| 578 |
+
undefined_re = re.compile(r"\b(tmp\d+)\[\?\]")
|
| 579 |
+
|
| 580 |
+
def __init__(
|
| 581 |
+
self,
|
| 582 |
+
name,
|
| 583 |
+
bounds: ValueRanges[Any],
|
| 584 |
+
dtype: Optional[torch.dtype] = None,
|
| 585 |
+
shape: BlockShapeType = None,
|
| 586 |
+
) -> None:
|
| 587 |
+
super().__init__(name, bounds, dtype, shape=shape)
|
| 588 |
+
self.used_dims: Optional[list[sympy.Symbol]] = None
|
| 589 |
+
|
| 590 |
+
def update_on_args(self, name, args, kwargs):
|
| 591 |
+
used = OrderedSet(self.used_dims or ())
|
| 592 |
+
for arg in itertools.chain(args, kwargs.values()):
|
| 593 |
+
if isinstance(arg, HalideCSEVariable):
|
| 594 |
+
assert arg.used_dims is not None, (name, arg, args)
|
| 595 |
+
used.update(arg.used_dims)
|
| 596 |
+
self.used_dims = V.kernel.sort_used_dims(used)
|
| 597 |
+
|
| 598 |
+
def index_str(self, dims):
|
| 599 |
+
if len(dims) == 0:
|
| 600 |
+
return f"{self.name}[()]"
|
| 601 |
+
# Reversed since Halide is column major
|
| 602 |
+
return f"{self.name}[{', '.join(map(str, dims))}]"
|
| 603 |
+
|
| 604 |
+
def __str__(self) -> str:
|
| 605 |
+
if self.used_dims is None:
|
| 606 |
+
# This will get recomputed and replaced in codegen_kernel()
|
| 607 |
+
return f"{self.name}[?]"
|
| 608 |
+
return self.index_str(self.used_dims)
|
| 609 |
+
|
| 610 |
+
def subs_str(self, replacements):
|
| 611 |
+
assert self.used_dims is not None and all(
|
| 612 |
+
isinstance(x, sympy.Expr) for x in self.used_dims
|
| 613 |
+
)
|
| 614 |
+
return self.index_str([replacements.get(n, n) for n in self.used_dims])
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
@dataclasses.dataclass
|
| 618 |
+
class DimensionInfo:
|
| 619 |
+
expr: Optional[sympy.Expr]
|
| 620 |
+
size: sympy.Expr
|
| 621 |
+
stride: sympy.Expr
|
| 622 |
+
|
| 623 |
+
def __init__(self, expr, size, stride) -> None:
|
| 624 |
+
super().__init__()
|
| 625 |
+
if V.graph.sizevars.statically_known_lt(stride, 0):
|
| 626 |
+
stride = -stride
|
| 627 |
+
expr = -expr
|
| 628 |
+
self.expr = expr
|
| 629 |
+
self.size = size
|
| 630 |
+
self.stride = stride
|
| 631 |
+
|
| 632 |
+
def index_str(self, replacements=None, zero_vars=False):
|
| 633 |
+
assert self.expr is not None
|
| 634 |
+
expr = self.expr
|
| 635 |
+
if zero_vars and expr == 0:
|
| 636 |
+
return "hl.Var()"
|
| 637 |
+
if replacements:
|
| 638 |
+
replacements = {**replacements}
|
| 639 |
+
for sym in expr.free_symbols:
|
| 640 |
+
if symbol_is_type(sym, SymT.TMP):
|
| 641 |
+
assert isinstance(sym, sympy.Symbol)
|
| 642 |
+
var = V.kernel.lookup_cse_var(sym.name)
|
| 643 |
+
assert isinstance(var, HalideCSEVariable)
|
| 644 |
+
replacements[sym] = sympy_index_symbol(var.subs_str(replacements))
|
| 645 |
+
expr = sympy_subs(expr, replacements)
|
| 646 |
+
return V.kernel.index_to_str(expr)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def eq(left, right):
|
| 650 |
+
if V.graph.sizevars.statically_known_equals(left, right):
|
| 651 |
+
return True
|
| 652 |
+
try:
|
| 653 |
+
a = V.graph.sizevars.size_hint_or_throw(left)
|
| 654 |
+
b = V.graph.sizevars.size_hint_or_throw(right)
|
| 655 |
+
except TypeError: # unbacked symints
|
| 656 |
+
return False
|
| 657 |
+
if a == b:
|
| 658 |
+
V.graph.sizevars.check_equals(left, right)
|
| 659 |
+
return a == b
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def lt(left, right):
|
| 663 |
+
if V.graph.sizevars.statically_known_lt(left, right):
|
| 664 |
+
return True
|
| 665 |
+
try:
|
| 666 |
+
a = V.graph.sizevars.size_hint_or_throw(left)
|
| 667 |
+
b = V.graph.sizevars.size_hint_or_throw(right)
|
| 668 |
+
except TypeError: # unbacked symints
|
| 669 |
+
gcd = sympy.gcd(left, right)
|
| 670 |
+
if gcd == left:
|
| 671 |
+
return left != right
|
| 672 |
+
return False
|
| 673 |
+
if a < b:
|
| 674 |
+
V.graph.sizevars.check_lt(left, right)
|
| 675 |
+
return a < b
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
class HalideKernel(SIMDKernel):
|
| 679 |
+
overrides = HalideOverrides # type: ignore[assignment]
|
| 680 |
+
kexpr: Callable[[sympy.Expr], str] = texpr
|
| 681 |
+
|
| 682 |
+
def __init__(
|
| 683 |
+
self,
|
| 684 |
+
tiling: dict[str, sympy.Expr],
|
| 685 |
+
**kwargs,
|
| 686 |
+
) -> None:
|
| 687 |
+
super().__init__(tiling, **kwargs)
|
| 688 |
+
# For halide, we just write directly to the body
|
| 689 |
+
self.compute = self.body
|
| 690 |
+
self.loads = self.body
|
| 691 |
+
self.stores = self.body
|
| 692 |
+
self.indexing_code_dom = IndentedBuffer()
|
| 693 |
+
self.needs_dom_indexing = self.inside_reduction
|
| 694 |
+
self.has_reduction = self.inside_reduction
|
| 695 |
+
self.buffer_dimensions: dict[str, list[DimensionInfo]] = {}
|
| 696 |
+
self.buffer_offsets: dict[str, sympy.Expr] = {}
|
| 697 |
+
# {h0: size1, h1: size2, ...}
|
| 698 |
+
self.halide_vars: dict[sympy.Symbol, sympy.Expr] = {}
|
| 699 |
+
# {x0: h0, x1: h1+10*h2, ...}
|
| 700 |
+
self.index_replacements: dict[sympy.Expr, sympy.Expr] = {}
|
| 701 |
+
# {h1: hr1, ...}
|
| 702 |
+
self.reduction_renames: dict[sympy.Symbol, sympy.Symbol] = {}
|
| 703 |
+
# {"i": {h0: hi0}, "o": ...}
|
| 704 |
+
self.dom_renames: dict[str, dict[sympy.Symbol, sympy.Symbol]] = {}
|
| 705 |
+
# {"in_ptr0": ["in_ptr0_view0"], ...}
|
| 706 |
+
self.buffer_aliases: dict[str, list[str]] = defaultdict(list)
|
| 707 |
+
self.has_indirect_indexing = False
|
| 708 |
+
|
| 709 |
+
def dtype_to_str(self, dtype: torch.dtype) -> str:
|
| 710 |
+
return halide_type(dtype)
|
| 711 |
+
|
| 712 |
+
def create_cse_var(self, name, bounds=None, dtype=None, shape=None):
|
| 713 |
+
self.body.writeline(f"{name} = hl.Func({name!r})")
|
| 714 |
+
return HalideCSEVariable(name, bounds, dtype, shape)
|
| 715 |
+
|
| 716 |
+
def finalize_indexing(self, indices: Sequence[sympy.Expr]):
|
| 717 |
+
"""
|
| 718 |
+
Hook called right before codegen with every index that will be
|
| 719 |
+
used in the fused kernel.
|
| 720 |
+
|
| 721 |
+
This populates self.halide_vars/index_replacements/reduction_renames which is an alternate indexing
|
| 722 |
+
scheme that avoids using divide and modulus. Instead of xindex/yindex/rindex
|
| 723 |
+
we base indexing on a larger number of vars whose product combines to those.
|
| 724 |
+
|
| 725 |
+
This function populates self.halide_vars, self.index_replacements, and self.reduction_renames
|
| 726 |
+
"""
|
| 727 |
+
assert not (
|
| 728 |
+
self.index_replacements or self.halide_vars or self.reduction_renames
|
| 729 |
+
)
|
| 730 |
+
size_hint = functools.partial(V.graph.sizevars.size_hint, fallback=inf) # type: ignore[arg-type]
|
| 731 |
+
indices = dict.fromkeys(map(super().prepare_indexing, indices))
|
| 732 |
+
all_used_symbols = OrderedSet[Any]()
|
| 733 |
+
sym_to_node = {
|
| 734 |
+
n.symbol(): n
|
| 735 |
+
for n in itertools.chain.from_iterable(
|
| 736 |
+
[tree.nodes.values() for tree in self.range_trees]
|
| 737 |
+
)
|
| 738 |
+
}
|
| 739 |
+
|
| 740 |
+
def simplify(expr):
|
| 741 |
+
return sympy.simplify(
|
| 742 |
+
V.graph.sizevars.remove_precomputed_replacements(expr)
|
| 743 |
+
)
|
| 744 |
+
|
| 745 |
+
def visit_modular_indexing(base, divisor, modulus):
|
| 746 |
+
if base in sym_to_node:
|
| 747 |
+
node = sym_to_node[base]
|
| 748 |
+
all_used_symbols.add(
|
| 749 |
+
node.root.lookup(
|
| 750 |
+
node.divisor * divisor,
|
| 751 |
+
V.graph.sizevars.evaluate_min(
|
| 752 |
+
modulus, FloorDiv(node.length, divisor)
|
| 753 |
+
),
|
| 754 |
+
).symbol()
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
def visit_floor_div(base, divisor):
|
| 758 |
+
if base in sym_to_node:
|
| 759 |
+
node = sym_to_node[base]
|
| 760 |
+
all_used_symbols.add(
|
| 761 |
+
node.root.lookup(
|
| 762 |
+
node.divisor * divisor,
|
| 763 |
+
FloorDiv(node.length, divisor),
|
| 764 |
+
).symbol()
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# first figure out all_used_symbols to do dead symbol elimination
|
| 768 |
+
for index in indices:
|
| 769 |
+
if index.has(ModularIndexing):
|
| 770 |
+
index.replace(
|
| 771 |
+
ModularIndexing(
|
| 772 |
+
sympy.Wild("base"),
|
| 773 |
+
sympy.Wild("divisor"),
|
| 774 |
+
sympy.Wild("modulus"),
|
| 775 |
+
),
|
| 776 |
+
visit_modular_indexing,
|
| 777 |
+
)
|
| 778 |
+
if index.has(FloorDiv):
|
| 779 |
+
index.replace(
|
| 780 |
+
FloorDiv(
|
| 781 |
+
sympy.Wild("base"),
|
| 782 |
+
sympy.Wild("divisor"),
|
| 783 |
+
),
|
| 784 |
+
visit_floor_div,
|
| 785 |
+
)
|
| 786 |
+
all_used_symbols.update(super().prepare_indexing(index).free_symbols)
|
| 787 |
+
|
| 788 |
+
self.has_indirect_indexing = any(
|
| 789 |
+
symbol_is_type(sym, SymT.INDIRECT) for sym in all_used_symbols
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
had_fallback = False
|
| 793 |
+
for tree in reversed(self.range_trees):
|
| 794 |
+
nodes = [n for n in tree.nodes.values() if n.symbol() in all_used_symbols]
|
| 795 |
+
nodes.sort(key=lambda n: size_hint(n.divisor))
|
| 796 |
+
if not nodes:
|
| 797 |
+
nodes.append(tree.lookup(1, tree.numel))
|
| 798 |
+
handled_count = 0
|
| 799 |
+
divisor = sympy.S.One
|
| 800 |
+
added_sym_size = []
|
| 801 |
+
# decide on a minimal set of symbols and put them in self.halide_vars
|
| 802 |
+
while handled_count < len(nodes) and not eq(tree.numel, divisor):
|
| 803 |
+
sizes_to_add = [
|
| 804 |
+
simplify(n.length) for n in nodes if eq(n.divisor, divisor)
|
| 805 |
+
]
|
| 806 |
+
handled_count += len(sizes_to_add)
|
| 807 |
+
assert sizes_to_add, nodes
|
| 808 |
+
end = divisor * functools.reduce(
|
| 809 |
+
V.graph.sizevars.evaluate_max, sizes_to_add
|
| 810 |
+
)
|
| 811 |
+
sizes_to_add.extend(
|
| 812 |
+
[
|
| 813 |
+
simplify(n.divisor / divisor)
|
| 814 |
+
for n in nodes
|
| 815 |
+
if lt(divisor, n.divisor) and lt(n.divisor, end)
|
| 816 |
+
]
|
| 817 |
+
)
|
| 818 |
+
while sizes_to_add:
|
| 819 |
+
next_size = functools.reduce(sympy.gcd, sizes_to_add)
|
| 820 |
+
if eq(next_size, 1):
|
| 821 |
+
# sizes share no common factors, e.g [2, 21, 42, 441, 889056]
|
| 822 |
+
# TODO(jansel): we should just prevent fusion in cases that hit this
|
| 823 |
+
next_size = simplify(tree.numel / divisor)
|
| 824 |
+
assert not eq(next_size, 1)
|
| 825 |
+
sizes_to_add = []
|
| 826 |
+
handled_count = len(nodes)
|
| 827 |
+
had_fallback = True
|
| 828 |
+
sym = sympy_index_symbol(f"h{len(self.halide_vars)}")
|
| 829 |
+
if tree.is_reduction:
|
| 830 |
+
self.reduction_renames[sym] = sympy_index_symbol(
|
| 831 |
+
f"hr{len(self.halide_vars)}"
|
| 832 |
+
)
|
| 833 |
+
self.halide_vars[sym] = next_size
|
| 834 |
+
added_sym_size.append((sym, next_size))
|
| 835 |
+
divisor *= next_size
|
| 836 |
+
new_sizes = [n.length for n in nodes if eq(n.divisor, divisor)]
|
| 837 |
+
handled_count += len(new_sizes)
|
| 838 |
+
prior_len = len(sizes_to_add)
|
| 839 |
+
sizes_to_add = [
|
| 840 |
+
sympy.simplify(s / next_size)
|
| 841 |
+
for s in sizes_to_add
|
| 842 |
+
if not eq(s, next_size)
|
| 843 |
+
]
|
| 844 |
+
assert len(sizes_to_add) < prior_len or prior_len == 0
|
| 845 |
+
sizes_to_add.extend(new_sizes)
|
| 846 |
+
|
| 847 |
+
# create a mapping to the new set of symbols in self.index_replacements
|
| 848 |
+
for node in nodes:
|
| 849 |
+
try:
|
| 850 |
+
idx = 0
|
| 851 |
+
divisor = 1
|
| 852 |
+
while not eq(node.divisor, divisor):
|
| 853 |
+
sym, size = added_sym_size[idx]
|
| 854 |
+
idx += 1
|
| 855 |
+
divisor *= size
|
| 856 |
+
length = 1
|
| 857 |
+
expr = sympy.S.Zero
|
| 858 |
+
while not eq(node.length, length):
|
| 859 |
+
sym, size = added_sym_size[idx]
|
| 860 |
+
idx += 1
|
| 861 |
+
expr += length * sym
|
| 862 |
+
length *= size
|
| 863 |
+
self.index_replacements[node.symbol()] = expr
|
| 864 |
+
except IndexError:
|
| 865 |
+
assert had_fallback
|
| 866 |
+
full_index = sympy.S.Zero
|
| 867 |
+
stride = sympy.S.One
|
| 868 |
+
for sym, size in added_sym_size:
|
| 869 |
+
full_index += stride * sym
|
| 870 |
+
stride *= size
|
| 871 |
+
self.index_replacements[node.symbol()] = (
|
| 872 |
+
V.graph.sizevars.simplify_with_ranges(
|
| 873 |
+
ModularIndexing(full_index, node.divisor, node.length),
|
| 874 |
+
self.halide_vars, # type: ignore[arg-type]
|
| 875 |
+
)
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
# codegen the variable definitions
|
| 879 |
+
for sym in self.halide_vars:
|
| 880 |
+
self.indexing_code.writeline(f"{sym} = hl.Var({sym.name!r})")
|
| 881 |
+
if self.reduction_renames:
|
| 882 |
+
self.codegen_rdom(
|
| 883 |
+
"rdom",
|
| 884 |
+
{rv: self.halide_vars[v] for v, rv in self.reduction_renames.items()},
|
| 885 |
+
)
|
| 886 |
+
|
| 887 |
+
def setup_dom_indexing(self):
|
| 888 |
+
"""RDom based indexing uses explicit iteration ranges for Func updates"""
|
| 889 |
+
prefix = "i" if self.inside_reduction else "o"
|
| 890 |
+
if prefix in self.dom_renames:
|
| 891 |
+
return self.dom_renames[prefix]
|
| 892 |
+
|
| 893 |
+
renames = {}
|
| 894 |
+
for var in self.halide_vars.keys():
|
| 895 |
+
if not self.inside_reduction and var in self.reduction_renames:
|
| 896 |
+
continue
|
| 897 |
+
m = re.match(r"^h(\d+)$", var.name)
|
| 898 |
+
assert m
|
| 899 |
+
renames[var] = sympy_index_symbol(f"h{prefix}{m.group(1)}")
|
| 900 |
+
|
| 901 |
+
self.codegen_rdom(
|
| 902 |
+
f"{prefix}dom", {rv: self.halide_vars[v] for v, rv in renames.items()}
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
self.dom_renames[prefix] = renames
|
| 906 |
+
return renames
|
| 907 |
+
|
| 908 |
+
def codegen_rdom(self, name, vars):
|
| 909 |
+
rsizes = [
|
| 910 |
+
f"hl.Range(0, {self.kexpr(self.rename_indexing(size))})"
|
| 911 |
+
for size in vars.values()
|
| 912 |
+
]
|
| 913 |
+
self.indexing_code.writeline(f"{name} = hl.RDom([{', '.join(rsizes)}])")
|
| 914 |
+
for i, rsym in enumerate(vars.keys()):
|
| 915 |
+
self.indexing_code.writeline(f"{rsym} = {name}[{i}]")
|
| 916 |
+
|
| 917 |
+
def prepare_indexing(
|
| 918 |
+
self,
|
| 919 |
+
index: sympy.Expr,
|
| 920 |
+
):
|
| 921 |
+
index = super().prepare_indexing(index)
|
| 922 |
+
index = sympy_subs(index, self.index_replacements)
|
| 923 |
+
return V.graph.sizevars.simplify_with_ranges(index, self.halide_vars) # type: ignore[arg-type]
|
| 924 |
+
|
| 925 |
+
def sym_size(self, sym):
|
| 926 |
+
"""The size of an index symbol"""
|
| 927 |
+
if symbol_is_type(sym, SymT.TMP):
|
| 928 |
+
return self.lookup_cse_var(sym.name).indirect_indexing_size
|
| 929 |
+
return self.halide_vars[sym]
|
| 930 |
+
|
| 931 |
+
def indexing_to_dimensions(self, var: str, index: sympy.Expr, is_store: bool):
|
| 932 |
+
"""Convert address-based indexing into dimensions using self.halide_vars"""
|
| 933 |
+
symbols = []
|
| 934 |
+
for sym in sorted(index.free_symbols, key=lambda x: x.name): # type: ignore[attr-defined]
|
| 935 |
+
if symbol_is_type(sym, (SymT.HALIDE, SymT.TMP)):
|
| 936 |
+
symbols.append(sym)
|
| 937 |
+
else:
|
| 938 |
+
assert symbol_is_type(
|
| 939 |
+
sym,
|
| 940 |
+
(
|
| 941 |
+
SymT.UNBACKED_INT,
|
| 942 |
+
SymT.SIZE,
|
| 943 |
+
SymT.PRECOMPUTED_SIZE,
|
| 944 |
+
),
|
| 945 |
+
), sym
|
| 946 |
+
|
| 947 |
+
# group the expression by variables used
|
| 948 |
+
offset = sympy.S.Zero
|
| 949 |
+
split_expr = dict.fromkeys(symbols, sympy.S.Zero)
|
| 950 |
+
split_failed: list[tuple[list[sympy.Symbol], sympy.Expr]] = []
|
| 951 |
+
index = sympy.expand(self.rename_indexing(index))
|
| 952 |
+
for part in index.args if isinstance(index, sympy.Add) else [index]:
|
| 953 |
+
part_vars = [v for v in part.free_symbols if v in split_expr]
|
| 954 |
+
if len(part_vars) == 0:
|
| 955 |
+
offset += part
|
| 956 |
+
elif len(part_vars) == 1:
|
| 957 |
+
split_expr[part_vars[0]] += part
|
| 958 |
+
else:
|
| 959 |
+
new_split_failed = []
|
| 960 |
+
for i in range(len(split_failed)):
|
| 961 |
+
assert split_failed[i] is not None
|
| 962 |
+
other_vars, other_part = split_failed[i]
|
| 963 |
+
if OrderedSet(other_vars) & OrderedSet(part_vars):
|
| 964 |
+
part_vars.extend([v for v in other_vars if v not in part_vars])
|
| 965 |
+
part += other_part
|
| 966 |
+
else:
|
| 967 |
+
new_split_failed.append((other_vars, other_part))
|
| 968 |
+
split_failed = [*new_split_failed, (part_vars, part)]
|
| 969 |
+
|
| 970 |
+
def expr_to_dimension(expr, syms):
|
| 971 |
+
expr = sympy.factor(expr)
|
| 972 |
+
if len(syms) == 1:
|
| 973 |
+
stride_wild = sympy.Wild("wild", exclude=symbols)
|
| 974 |
+
m = expr.match(stride_wild * syms[0])
|
| 975 |
+
if m:
|
| 976 |
+
return DimensionInfo(
|
| 977 |
+
syms[0], self.sym_size(syms[0]), m[stride_wild]
|
| 978 |
+
)
|
| 979 |
+
assert not is_store, expr
|
| 980 |
+
length = sympy.simplify(
|
| 981 |
+
sympy_subs(expr, {sym: self.sym_size(sym) - 1 for sym in syms}) + 1
|
| 982 |
+
)
|
| 983 |
+
stride = sympy.S.One
|
| 984 |
+
if isinstance(expr, sympy.Mul):
|
| 985 |
+
for term in expr.args:
|
| 986 |
+
if isinstance(term, sympy.Integer):
|
| 987 |
+
stride *= term
|
| 988 |
+
expr = sympy.simplify(expr / term)
|
| 989 |
+
length = sympy.simplify(sympy.ceiling(length / term))
|
| 990 |
+
return DimensionInfo(expr, length, stride)
|
| 991 |
+
|
| 992 |
+
# try to turn each group into a strided access
|
| 993 |
+
dims = []
|
| 994 |
+
for syms, expr in split_failed:
|
| 995 |
+
for v in syms:
|
| 996 |
+
expr += split_expr.pop(v)
|
| 997 |
+
dims.append(expr_to_dimension(expr, syms))
|
| 998 |
+
for sym, expr in split_expr.items():
|
| 999 |
+
dims.append(expr_to_dimension(expr, [sym]))
|
| 1000 |
+
dims.sort(key=lambda d: V.graph.sizevars.size_hint(d.stride, fallback=inf)) # type: ignore[arg-type]
|
| 1001 |
+
|
| 1002 |
+
if not dims: # scalar load/store
|
| 1003 |
+
if self.has_indirect_indexing:
|
| 1004 |
+
# workaround https://github.com/halide/Halide/issues/8338
|
| 1005 |
+
dims.append(DimensionInfo(sympy.S.Zero, 1, 1))
|
| 1006 |
+
elif not V.graph.sizevars.statically_known_equals(dims[0].stride, 1):
|
| 1007 |
+
# Halide assumes dimension 0 is stride == 1, so add a dummy dimension
|
| 1008 |
+
dims.insert(
|
| 1009 |
+
0, DimensionInfo(sympy.S.Zero, 1 if is_store else dims[0].stride, 1)
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
if dims and not is_store:
|
| 1013 |
+
if var in self.buffer_offsets and V.graph.sizevars.statically_known_geq(
|
| 1014 |
+
offset, self.buffer_offsets[var]
|
| 1015 |
+
):
|
| 1016 |
+
# reuse the existing offset to avoid needing an input alias
|
| 1017 |
+
self.apply_offset_to_dimension(dims, offset - self.buffer_offsets[var])
|
| 1018 |
+
offset = self.buffer_offsets[var]
|
| 1019 |
+
elif V.graph.sizevars.statically_known_gt(
|
| 1020 |
+
offset, 0
|
| 1021 |
+
): # TODO(jansel): negative offsets
|
| 1022 |
+
# roll the offset into the dimensions for cleaner indexing
|
| 1023 |
+
self.apply_offset_to_dimension(dims, offset)
|
| 1024 |
+
offset = 0
|
| 1025 |
+
|
| 1026 |
+
orig_var = var
|
| 1027 |
+
for i in itertools.count():
|
| 1028 |
+
if self.install_dims(var, dims, offset, is_store):
|
| 1029 |
+
return var, dims
|
| 1030 |
+
assert not is_store
|
| 1031 |
+
var = f"{orig_var}_view{i}"
|
| 1032 |
+
if var not in self.buffer_aliases[orig_var]:
|
| 1033 |
+
self.buffer_aliases[orig_var].append(var)
|
| 1034 |
+
|
| 1035 |
+
def install_dims(self, var, dims, offset, is_store):
|
| 1036 |
+
"""Try to set self.buffer_dimensions[var], return True on success"""
|
| 1037 |
+
if var not in self.buffer_dimensions:
|
| 1038 |
+
self.buffer_dimensions[var] = dims
|
| 1039 |
+
self.buffer_offsets[var] = offset
|
| 1040 |
+
return True
|
| 1041 |
+
if self.buffer_offsets[var] != offset or len(
|
| 1042 |
+
self.buffer_dimensions[var]
|
| 1043 |
+
) != len(dims):
|
| 1044 |
+
return False
|
| 1045 |
+
if is_store:
|
| 1046 |
+
return self.buffer_dimensions[var] == dims
|
| 1047 |
+
for old, new in zip(self.buffer_dimensions[var], dims):
|
| 1048 |
+
if old.stride != new.stride:
|
| 1049 |
+
return False
|
| 1050 |
+
if old.size != new.size or old.expr != new.expr:
|
| 1051 |
+
old.size = V.graph.sizevars.evaluate_max(old.size, new.size)
|
| 1052 |
+
old.expr = None
|
| 1053 |
+
return True
|
| 1054 |
+
|
| 1055 |
+
def apply_offset_to_dimension(self, dims, offset):
|
| 1056 |
+
if offset == 0:
|
| 1057 |
+
return
|
| 1058 |
+
for i in reversed(range(len(dims))):
|
| 1059 |
+
if dims[i].stride == 1 or V.graph.sizevars.statically_known_geq(
|
| 1060 |
+
offset, dims[i].stride
|
| 1061 |
+
):
|
| 1062 |
+
part = FloorDiv(offset, dims[i].stride)
|
| 1063 |
+
offset -= part * dims[i].stride
|
| 1064 |
+
dims[i].expr += part
|
| 1065 |
+
assert offset == 0
|
| 1066 |
+
|
| 1067 |
+
def used_dims_from_index(self, index: sympy.Expr):
|
| 1068 |
+
"""Detect which range trees are used to populate HalideCSEVariable.used_dims"""
|
| 1069 |
+
used_dims = OrderedSet[sympy.Symbol]()
|
| 1070 |
+
for sym in index.free_symbols:
|
| 1071 |
+
assert isinstance(sym, sympy.Symbol)
|
| 1072 |
+
if symbol_is_type(sym, SymT.TMP):
|
| 1073 |
+
# indirect indexing
|
| 1074 |
+
cse_var = self.lookup_cse_var(sym.name)
|
| 1075 |
+
assert (
|
| 1076 |
+
isinstance(cse_var, HalideCSEVariable)
|
| 1077 |
+
and cse_var.used_dims is not None
|
| 1078 |
+
)
|
| 1079 |
+
used_dims.update(cse_var.used_dims)
|
| 1080 |
+
elif symbol_is_type(sym, SymT.HALIDE):
|
| 1081 |
+
used_dims.add(sym)
|
| 1082 |
+
elif symbol_is_type(
|
| 1083 |
+
sym, (SymT.UNBACKED_INT, SymT.SIZE, SymT.PRECOMPUTED_SIZE, SymT.INDEX)
|
| 1084 |
+
):
|
| 1085 |
+
pass
|
| 1086 |
+
else:
|
| 1087 |
+
raise NotImplementedError(f"unhandled symbol {sym}")
|
| 1088 |
+
return self.sort_used_dims(used_dims)
|
| 1089 |
+
|
| 1090 |
+
def sort_used_dims(self, used_dims):
|
| 1091 |
+
assert all(isinstance(x, sympy.Expr) for x in used_dims)
|
| 1092 |
+
ordered = [
|
| 1093 |
+
sym
|
| 1094 |
+
for sym in itertools.chain(
|
| 1095 |
+
self.halide_vars, self.reduction_renames.values()
|
| 1096 |
+
)
|
| 1097 |
+
if sym in used_dims
|
| 1098 |
+
]
|
| 1099 |
+
assert len(ordered) == len(used_dims)
|
| 1100 |
+
return ordered
|
| 1101 |
+
|
| 1102 |
+
def make_index_str(self, dims, replacements=None, zero_vars=False):
|
| 1103 |
+
index_str = ", ".join(d.index_str(replacements, zero_vars) for d in dims)
|
| 1104 |
+
if len(dims) == 0:
|
| 1105 |
+
index_str = "()"
|
| 1106 |
+
elif len(dims) == 1:
|
| 1107 |
+
# workaround for https://github.com/halide/Halide/issues/8299
|
| 1108 |
+
index_str = f"{index_str},"
|
| 1109 |
+
return index_str
|
| 1110 |
+
|
| 1111 |
+
def load(self, name: str, index: sympy.Expr):
|
| 1112 |
+
"""Codegen a load from an InputBuffer"""
|
| 1113 |
+
var = self.args.input(name)
|
| 1114 |
+
index = self.prepare_indexing(index)
|
| 1115 |
+
var, dims = self.indexing_to_dimensions(var, index, False)
|
| 1116 |
+
line = f"{var}[{self.make_index_str(dims)}]"
|
| 1117 |
+
dtype = V.graph.get_dtype(name)
|
| 1118 |
+
if dtype in (torch.float16, torch.bfloat16):
|
| 1119 |
+
dtype = torch.float32
|
| 1120 |
+
line = f"hl.cast(hl.Float(32), {line})"
|
| 1121 |
+
|
| 1122 |
+
if self._load_mask:
|
| 1123 |
+
assert (
|
| 1124 |
+
isinstance(self._load_mask, HalideCSEVariable)
|
| 1125 |
+
and self._load_mask.used_dims is not None
|
| 1126 |
+
)
|
| 1127 |
+
used_dims = OrderedSet(
|
| 1128 |
+
(*self.used_dims_from_index(index), *self._load_mask.used_dims)
|
| 1129 |
+
)
|
| 1130 |
+
result = self.newfunc(self.sort_used_dims(used_dims))
|
| 1131 |
+
if result.used_dims:
|
| 1132 |
+
self.body.writeline(f"{result.name}_mask = hl.RDom([hl.Range(0, 1)])")
|
| 1133 |
+
self.body.writeline(f"{result.name}_mask.where({self._load_mask})")
|
| 1134 |
+
other = self.kexpr(self._load_other or 0) # type: ignore[arg-type]
|
| 1135 |
+
self.body.writeline(
|
| 1136 |
+
f"{result} = hl.cast({halide_type(dtype)}, {other})"
|
| 1137 |
+
)
|
| 1138 |
+
self.body.writeline(
|
| 1139 |
+
f"{result} = {line} + hl.cast({halide_type(dtype)}, {result.name}_mask)"
|
| 1140 |
+
)
|
| 1141 |
+
else:
|
| 1142 |
+
# scalar case
|
| 1143 |
+
self.body.writeline(
|
| 1144 |
+
f"{result} = hl.select({self._load_mask}, {line}, hl.cast({halide_type(dtype)}, 0))"
|
| 1145 |
+
)
|
| 1146 |
+
return result
|
| 1147 |
+
else:
|
| 1148 |
+
return self.genfunc(line, self.used_dims_from_index(index))
|
| 1149 |
+
|
| 1150 |
+
def lookup_cse_var(self, name: str):
|
| 1151 |
+
return self.cse.varname_map[re.sub(r"\[.*", "", name)]
|
| 1152 |
+
|
| 1153 |
+
def store(
|
| 1154 |
+
self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None
|
| 1155 |
+
) -> None:
|
| 1156 |
+
"""Codegen a store to an OutputBuffer"""
|
| 1157 |
+
assert isinstance(value, HalideCSEVariable)
|
| 1158 |
+
var = self.args.output(name)
|
| 1159 |
+
index = self.prepare_indexing(index)
|
| 1160 |
+
var, dims = self.indexing_to_dimensions(var, index, True)
|
| 1161 |
+
if self.is_indirect_indexing(index) or mode is not None:
|
| 1162 |
+
replacements = self.setup_dom_indexing()
|
| 1163 |
+
index_str = self.make_index_str(dims, replacements)
|
| 1164 |
+
value_str = value.subs_str(replacements)
|
| 1165 |
+
undef_dims = (", ".join(["hl.Var()"] * len(dims))) or "()"
|
| 1166 |
+
self.body.writeline(
|
| 1167 |
+
DeferredLine(name, f"{var}[{undef_dims}] = hl.undef({var}.type())")
|
| 1168 |
+
)
|
| 1169 |
+
else:
|
| 1170 |
+
index_str = self.make_index_str(dims, zero_vars=True)
|
| 1171 |
+
value_str = str(value)
|
| 1172 |
+
|
| 1173 |
+
dtype = V.graph.get_dtype(name)
|
| 1174 |
+
if mode is None:
|
| 1175 |
+
line = f"{var}[{index_str}] = hl.cast({halide_type(dtype)}, {value_str})"
|
| 1176 |
+
elif mode == "atomic_add":
|
| 1177 |
+
line = f"{var}[{index_str}] += hl.cast({halide_type(dtype)}, {value_str})"
|
| 1178 |
+
else:
|
| 1179 |
+
raise NotImplementedError(f"store mode={mode}")
|
| 1180 |
+
self.body.writeline(DeferredLine(name, line))
|
| 1181 |
+
|
| 1182 |
+
def reduction(
|
| 1183 |
+
self,
|
| 1184 |
+
dtype: torch.dtype,
|
| 1185 |
+
src_dtype: torch.dtype,
|
| 1186 |
+
reduction_type: ReductionType,
|
| 1187 |
+
value: Union[CSEVariable, tuple[CSEVariable, ...]],
|
| 1188 |
+
) -> Union[CSEVariable, tuple[CSEVariable, ...]]:
|
| 1189 |
+
"""Codegen a reduction operation"""
|
| 1190 |
+
assert self.inside_reduction
|
| 1191 |
+
assert not self._load_mask
|
| 1192 |
+
cache_key = (src_dtype, reduction_type, value)
|
| 1193 |
+
if cache_key in self.cse.reduction_cache:
|
| 1194 |
+
return self.cse.reduction_cache[cache_key]
|
| 1195 |
+
|
| 1196 |
+
if isinstance(value, tuple):
|
| 1197 |
+
assert reduction_type == "welford_combine"
|
| 1198 |
+
self.cse.reduction_cache[cache_key] = result_tuple = (
|
| 1199 |
+
self.welford_combine_impl(*value)
|
| 1200 |
+
)
|
| 1201 |
+
return result_tuple
|
| 1202 |
+
|
| 1203 |
+
assert isinstance(value, HalideCSEVariable) and value.used_dims is not None
|
| 1204 |
+
reduction_vars = OrderedSet(self.reduction_renames)
|
| 1205 |
+
result_var = self.newfunc(
|
| 1206 |
+
[v for v in value.used_dims if v not in reduction_vars],
|
| 1207 |
+
)
|
| 1208 |
+
if reduction_vars - OrderedSet(value.used_dims):
|
| 1209 |
+
value = self.genfunc(
|
| 1210 |
+
f"{value}",
|
| 1211 |
+
self.sort_used_dims(OrderedSet((*value.used_dims, *reduction_vars))),
|
| 1212 |
+
shape=value.shape,
|
| 1213 |
+
)
|
| 1214 |
+
value_str = value.subs_str(self.reduction_renames)
|
| 1215 |
+
default = ir.Reduction.default_accumulator(reduction_type, src_dtype)
|
| 1216 |
+
acc_type = halide_acc_type(dtype)
|
| 1217 |
+
|
| 1218 |
+
if reduction_type in ("argmax", "argmin"):
|
| 1219 |
+
index = f"{result_var.name}_{reduction_type}"
|
| 1220 |
+
self.body.writeline(f"{index} = hl.{reduction_type}(rdom, {value_str})")
|
| 1221 |
+
# turn the N-D argmax index into a 1-D one
|
| 1222 |
+
parts = []
|
| 1223 |
+
stride = 1
|
| 1224 |
+
for i, sym in enumerate(self.reduction_renames):
|
| 1225 |
+
parts.append(f"{index}[{i}]")
|
| 1226 |
+
if stride != 1:
|
| 1227 |
+
parts[-1] += f"*{stride}"
|
| 1228 |
+
stride *= self.halide_vars[sym]
|
| 1229 |
+
self.body.writeline(f"{result_var} = {' + '.join(parts)}")
|
| 1230 |
+
elif reduction_type == "welford_reduce":
|
| 1231 |
+
# TODO(jansel): implement welford_reduce without fallback
|
| 1232 |
+
result_var = self.welford_reduce_fallback(dtype, value)
|
| 1233 |
+
else:
|
| 1234 |
+
combine_fn = get_reduction_combine_fn(reduction_type, acc_type)
|
| 1235 |
+
with V.set_ops_handler(AddParenHandler(HalideOverrides())):
|
| 1236 |
+
combine_str = combine_fn(result_var, value_str) # type: ignore[arg-type]
|
| 1237 |
+
default_str = f"hl.cast({acc_type}, {halide_constant(default)})"
|
| 1238 |
+
self.body.writeline(f"{result_var} = {default_str}")
|
| 1239 |
+
self.body.writeline(f"{result_var} = {combine_str}")
|
| 1240 |
+
|
| 1241 |
+
self.cse.reduction_cache[cache_key] = result_var
|
| 1242 |
+
return result_var
|
| 1243 |
+
|
| 1244 |
+
def welford_combine_impl(self, mean, m2, weight):
|
| 1245 |
+
assert isinstance(mean, HalideCSEVariable) and mean.used_dims is not None
|
| 1246 |
+
assert isinstance(m2, HalideCSEVariable) and m2.used_dims is not None
|
| 1247 |
+
assert isinstance(weight, HalideCSEVariable) and weight.used_dims is not None
|
| 1248 |
+
used_dims = OrderedSet(
|
| 1249 |
+
(*mean.used_dims, *m2.used_dims, *weight.used_dims) or self.halide_vars
|
| 1250 |
+
)
|
| 1251 |
+
used_dims -= OrderedSet(self.reduction_renames)
|
| 1252 |
+
result_var = self.newfunc(self.sort_used_dims(used_dims))
|
| 1253 |
+
default = [f"hl.cast({x.name}.type(), 0)" for x in (mean, m2, weight)]
|
| 1254 |
+
pfx = result_var.name
|
| 1255 |
+
self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(default)}])")
|
| 1256 |
+
self.body.writeline(f"{pfx}_mean_1 = {result_var}[0]")
|
| 1257 |
+
self.body.writeline(f"{pfx}_m2_1 = {result_var}[1]")
|
| 1258 |
+
self.body.writeline(f"{pfx}_weight_1 = {result_var}[2]")
|
| 1259 |
+
self.body.writeline(f"{pfx}_mean_2 = {mean.subs_str(self.reduction_renames)}")
|
| 1260 |
+
self.body.writeline(f"{pfx}_m2_2 = {m2.subs_str(self.reduction_renames)}")
|
| 1261 |
+
self.body.writeline(
|
| 1262 |
+
f"{pfx}_weight_2 = {weight.subs_str(self.reduction_renames)}"
|
| 1263 |
+
)
|
| 1264 |
+
self.body.writeline(f"{pfx}_delta = {pfx}_mean_2 - {pfx}_mean_1")
|
| 1265 |
+
self.body.writeline(f"{pfx}_new_weight = {pfx}_weight_1 + {pfx}_weight_2")
|
| 1266 |
+
self.body.writeline(
|
| 1267 |
+
f"{pfx}_w2_over_w = hl.select({pfx}_new_weight == 0.0, 0.0, {pfx}_weight_2 / {pfx}_new_weight)"
|
| 1268 |
+
)
|
| 1269 |
+
update = [
|
| 1270 |
+
f"{pfx}_mean_1 + {pfx}_delta * {pfx}_w2_over_w",
|
| 1271 |
+
f"{pfx}_m2_1 + {pfx}_m2_2 + {pfx}_delta * {pfx}_delta * {pfx}_weight_1 * {pfx}_w2_over_w",
|
| 1272 |
+
f"{pfx}_new_weight",
|
| 1273 |
+
]
|
| 1274 |
+
self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(update)}])")
|
| 1275 |
+
|
| 1276 |
+
unpacked = []
|
| 1277 |
+
for i in range(3):
|
| 1278 |
+
unpacked.append(self.newfunc(result_var.used_dims))
|
| 1279 |
+
self.body.writeline(f"{unpacked[-1]} = {result_var}[{i}]")
|
| 1280 |
+
return tuple(unpacked)
|
| 1281 |
+
|
| 1282 |
+
def scan(
|
| 1283 |
+
self,
|
| 1284 |
+
dtypes: tuple[torch.dtype, ...],
|
| 1285 |
+
combine_fn: Callable[
|
| 1286 |
+
[tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...]
|
| 1287 |
+
],
|
| 1288 |
+
values_orig: tuple[CSEVariable, ...],
|
| 1289 |
+
) -> tuple[CSEVariable, ...]:
|
| 1290 |
+
assert self.inside_reduction
|
| 1291 |
+
assert len(dtypes) == len(values_orig)
|
| 1292 |
+
values: list[HalideCSEVariable] = []
|
| 1293 |
+
all_used_dims = OrderedSet[sympy.Symbol]()
|
| 1294 |
+
|
| 1295 |
+
for value in values_orig:
|
| 1296 |
+
assert isinstance(value, HalideCSEVariable) and value.used_dims is not None
|
| 1297 |
+
if OrderedSet(value.used_dims) & OrderedSet(self.reduction_renames):
|
| 1298 |
+
values.append(value)
|
| 1299 |
+
else:
|
| 1300 |
+
values.append(
|
| 1301 |
+
self.genfunc(
|
| 1302 |
+
f"{value}",
|
| 1303 |
+
[*value.used_dims, [*self.reduction_renames][:1]],
|
| 1304 |
+
shape=value.shape,
|
| 1305 |
+
)
|
| 1306 |
+
)
|
| 1307 |
+
all_used_dims.update(value.used_dims)
|
| 1308 |
+
result_var = self.newfunc(self.sort_used_dims(all_used_dims))
|
| 1309 |
+
assert result_var.used_dims and OrderedSet(result_var.used_dims) & OrderedSet(
|
| 1310 |
+
self.reduction_renames
|
| 1311 |
+
)
|
| 1312 |
+
initial = [
|
| 1313 |
+
f"hl.cast({halide_acc_type(dtype)}, {value})"
|
| 1314 |
+
for dtype, value in zip(dtypes, values)
|
| 1315 |
+
]
|
| 1316 |
+
|
| 1317 |
+
length = self.kexpr(self.rename_indexing(self.range_trees[-1].numel))
|
| 1318 |
+
scan_dom = f"{result_var.name}_rdom"
|
| 1319 |
+
scan = f"{scan_dom}.x"
|
| 1320 |
+
self.body.writeline(f"{scan_dom} = hl.RDom([hl.Range(1, {length})])")
|
| 1321 |
+
|
| 1322 |
+
assert len(self.reduction_renames) == 1, (
|
| 1323 |
+
"multi-dimensional scan not implemented"
|
| 1324 |
+
)
|
| 1325 |
+
(scan_var,) = [*self.reduction_renames] # type: ignore[misc]
|
| 1326 |
+
scan_renames_cur = {scan_var: sympy_index_symbol(scan)}
|
| 1327 |
+
scan_renames_pri = {scan_var: sympy_index_symbol(scan) - 1}
|
| 1328 |
+
|
| 1329 |
+
if len(values) == 1:
|
| 1330 |
+
|
| 1331 |
+
def maybe_tuple(x):
|
| 1332 |
+
return x[0]
|
| 1333 |
+
|
| 1334 |
+
read_left = [result_var.subs_str(scan_renames_pri)]
|
| 1335 |
+
read_right = [result_var.subs_str(scan_renames_cur)]
|
| 1336 |
+
else:
|
| 1337 |
+
|
| 1338 |
+
def maybe_tuple(x):
|
| 1339 |
+
return f"hl.Tuple([{', '.join(x)}])"
|
| 1340 |
+
|
| 1341 |
+
read_left = [
|
| 1342 |
+
result_var.subs_str(scan_renames_pri) + f"[{i}]"
|
| 1343 |
+
for i in range(len(values))
|
| 1344 |
+
]
|
| 1345 |
+
read_right = [
|
| 1346 |
+
result_var.subs_str(scan_renames_cur) + f"[{i}]"
|
| 1347 |
+
for i in range(len(values))
|
| 1348 |
+
]
|
| 1349 |
+
|
| 1350 |
+
self.body.writeline(f"{result_var} = {maybe_tuple(initial)}")
|
| 1351 |
+
|
| 1352 |
+
# Disable CSE for update fn
|
| 1353 |
+
with V.set_ops_handler(AddParenHandler(HalideOverrides())):
|
| 1354 |
+
combine_str = combine_fn(read_left, read_right) # type: ignore[arg-type]
|
| 1355 |
+
self.body.writeline(
|
| 1356 |
+
f"{result_var.subs_str(scan_renames_cur)} = {maybe_tuple(combine_str)}"
|
| 1357 |
+
)
|
| 1358 |
+
|
| 1359 |
+
if len(values) == 1:
|
| 1360 |
+
return (result_var,)
|
| 1361 |
+
|
| 1362 |
+
unpack_vars = [self.newfunc(self.sort_used_dims(all_used_dims)) for _ in values]
|
| 1363 |
+
for i, v in enumerate(unpack_vars):
|
| 1364 |
+
self.body.writeline(f"{v} = {result_var}[{i}]")
|
| 1365 |
+
return tuple(unpack_vars)
|
| 1366 |
+
|
| 1367 |
+
def genfunc(
|
| 1368 |
+
self,
|
| 1369 |
+
line,
|
| 1370 |
+
used_dims,
|
| 1371 |
+
*,
|
| 1372 |
+
bounds=ValueRanges.unknown(),
|
| 1373 |
+
shape: BlockShapeType = None,
|
| 1374 |
+
) -> HalideCSEVariable:
|
| 1375 |
+
var = self.cse.generate(self.body, line, bounds=bounds, shape=shape)
|
| 1376 |
+
assert isinstance(var, HalideCSEVariable)
|
| 1377 |
+
var.used_dims = used_dims
|
| 1378 |
+
return var
|
| 1379 |
+
|
| 1380 |
+
def newfunc(self, used_dims, *, shape: BlockShapeType = None) -> HalideCSEVariable:
|
| 1381 |
+
var = self.cse.newvar(shape=shape)
|
| 1382 |
+
assert isinstance(var, HalideCSEVariable)
|
| 1383 |
+
var.used_dims = used_dims
|
| 1384 |
+
return var
|
| 1385 |
+
|
| 1386 |
+
def halide_buffer_numel(self, name: str):
|
| 1387 |
+
"""
|
| 1388 |
+
We map all tensors to 1D buffers in Halide since Halide has trouble representing some strides that PyTorch
|
| 1389 |
+
supports. If there are gaps in the underlying layout the numel we pass to Halide includes the gaps while
|
| 1390 |
+
PyTorch's numel excludes them.
|
| 1391 |
+
"""
|
| 1392 |
+
return V.graph.get_buffer(name).get_layout().storage_size()
|
| 1393 |
+
|
| 1394 |
+
def halide_argdefs(self):
|
| 1395 |
+
"""
|
| 1396 |
+
Halide requires scalar inputs before outputs, so need to reorder args.
|
| 1397 |
+
"""
|
| 1398 |
+
|
| 1399 |
+
def arg_order(arg_tuple):
|
| 1400 |
+
_call_str, arg = arg_tuple
|
| 1401 |
+
if isinstance(arg, SizeArg):
|
| 1402 |
+
return 1 # this would normally be at the end, move it to middle
|
| 1403 |
+
elif "out_ptr" in arg.name:
|
| 1404 |
+
return 2
|
| 1405 |
+
else:
|
| 1406 |
+
assert "in_ptr" in arg.name
|
| 1407 |
+
return 0
|
| 1408 |
+
|
| 1409 |
+
result: list[tuple[Optional[str], KernelArgType]] = []
|
| 1410 |
+
_, a, b, _ = self.args.python_argdefs()
|
| 1411 |
+
for call_str, arg in sorted(zip(a, b), key=arg_order):
|
| 1412 |
+
result.append((call_str, arg))
|
| 1413 |
+
if isinstance(arg, TensorArg):
|
| 1414 |
+
assert arg.offset == 0 and arg.alias_of is None
|
| 1415 |
+
result.extend(
|
| 1416 |
+
(
|
| 1417 |
+
None,
|
| 1418 |
+
TensorArg(
|
| 1419 |
+
alias,
|
| 1420 |
+
arg.buffer,
|
| 1421 |
+
arg.dtype,
|
| 1422 |
+
arg.offset,
|
| 1423 |
+
alias_of=arg.name,
|
| 1424 |
+
),
|
| 1425 |
+
)
|
| 1426 |
+
for alias in self.buffer_aliases.get(arg.name, ())
|
| 1427 |
+
)
|
| 1428 |
+
return result
|
| 1429 |
+
|
| 1430 |
+
def halide_kernel_meta(self) -> HalideMeta:
|
| 1431 |
+
"""Compute metadata required by codecache.py"""
|
| 1432 |
+
argtypes = []
|
| 1433 |
+
for _, arg in self.halide_argdefs():
|
| 1434 |
+
if isinstance(arg, SizeArg):
|
| 1435 |
+
shape = None
|
| 1436 |
+
stride = None
|
| 1437 |
+
offset = None
|
| 1438 |
+
dtype = "long"
|
| 1439 |
+
else:
|
| 1440 |
+
shape = [
|
| 1441 |
+
cexpr(self.rename_indexing(x.size))
|
| 1442 |
+
for x in self.buffer_dimensions[arg.name]
|
| 1443 |
+
]
|
| 1444 |
+
stride = [
|
| 1445 |
+
cexpr(self.rename_indexing(x.stride))
|
| 1446 |
+
for x in self.buffer_dimensions[arg.name]
|
| 1447 |
+
]
|
| 1448 |
+
assert len(shape) == len(stride)
|
| 1449 |
+
offset = cexpr(self.buffer_offsets[arg.name])
|
| 1450 |
+
dtype = f"{DTYPE_TO_CPP[arg.dtype]}*"
|
| 1451 |
+
argtypes.append(
|
| 1452 |
+
HalideInputSpec(
|
| 1453 |
+
dtype,
|
| 1454 |
+
arg.name,
|
| 1455 |
+
shape=shape,
|
| 1456 |
+
stride=stride,
|
| 1457 |
+
offset=offset,
|
| 1458 |
+
alias_of=arg.alias_of,
|
| 1459 |
+
)
|
| 1460 |
+
)
|
| 1461 |
+
|
| 1462 |
+
current_device = V.graph.get_current_device_or_throw()
|
| 1463 |
+
if current_device.type == "cpu":
|
| 1464 |
+
target = [config.halide.cpu_target]
|
| 1465 |
+
scheduler = config.halide.scheduler_cpu
|
| 1466 |
+
scheduler_flags = {
|
| 1467 |
+
"parallelism": parallel_num_threads(),
|
| 1468 |
+
}
|
| 1469 |
+
cuda_device = None
|
| 1470 |
+
else:
|
| 1471 |
+
assert current_device.type == "cuda", "only cpu/cuda supported"
|
| 1472 |
+
assert current_device.index <= 0, "only default device supported"
|
| 1473 |
+
target = [config.halide.gpu_target]
|
| 1474 |
+
scheduler = config.halide.scheduler_cuda
|
| 1475 |
+
capability = torch.cuda.get_device_properties(current_device)
|
| 1476 |
+
if "cuda_capability" not in target[0]:
|
| 1477 |
+
for major, minor in [(8, 6), (8, 0), (7, 5), (7, 0), (6, 1)]:
|
| 1478 |
+
if capability.major >= major and capability.minor >= minor:
|
| 1479 |
+
target.append(f"cuda_capability_{major}{minor}")
|
| 1480 |
+
break
|
| 1481 |
+
target.append("user_context")
|
| 1482 |
+
scheduler_flags = {
|
| 1483 |
+
"parallelism": capability.multi_processor_count,
|
| 1484 |
+
# TODO(jansel): explore other flags, see:
|
| 1485 |
+
# grep parser.parse ~/Halide/src/autoschedulers/anderson2021/AutoSchedule.cpp
|
| 1486 |
+
}
|
| 1487 |
+
cuda_device = max(0, current_device.index)
|
| 1488 |
+
|
| 1489 |
+
# strict_float is requires for correctness
|
| 1490 |
+
target.append("strict_float")
|
| 1491 |
+
|
| 1492 |
+
# without this we will initialize cuda once per kernel and hit errors
|
| 1493 |
+
target.append("no_runtime")
|
| 1494 |
+
|
| 1495 |
+
if not config.halide.asserts:
|
| 1496 |
+
target.append("no_asserts")
|
| 1497 |
+
|
| 1498 |
+
if config.halide.debug:
|
| 1499 |
+
target.append("debug")
|
| 1500 |
+
|
| 1501 |
+
if "64" in self.index_dtype:
|
| 1502 |
+
# TODO(jansel): it is unclear if this does anything, since input sizes are still int32
|
| 1503 |
+
target.append("large_buffers")
|
| 1504 |
+
|
| 1505 |
+
return HalideMeta(
|
| 1506 |
+
argtypes,
|
| 1507 |
+
target="-".join(target),
|
| 1508 |
+
scheduler=scheduler,
|
| 1509 |
+
scheduler_flags=scheduler_flags, # type: ignore[arg-type]
|
| 1510 |
+
cuda_device=cuda_device,
|
| 1511 |
+
)
|
| 1512 |
+
|
| 1513 |
+
def codegen_kernel(self, name=None):
|
| 1514 |
+
"""Called at the end to generate a final kernel string"""
|
| 1515 |
+
if self.args.inplace_buffers:
|
| 1516 |
+
raise Unsupported("inplace_buffers")
|
| 1517 |
+
meta = self.halide_kernel_meta() # ensure needed args are added early
|
| 1518 |
+
code = IndentedBuffer()
|
| 1519 |
+
code.splice(
|
| 1520 |
+
"""
|
| 1521 |
+
import halide as hl
|
| 1522 |
+
from torch._inductor.runtime import halide_helpers
|
| 1523 |
+
from math import inf, nan
|
| 1524 |
+
|
| 1525 |
+
@hl.generator(name="kernel")
|
| 1526 |
+
class Kernel:
|
| 1527 |
+
""",
|
| 1528 |
+
strip=True,
|
| 1529 |
+
)
|
| 1530 |
+
code.do_indent()
|
| 1531 |
+
for _, arg in self.halide_argdefs():
|
| 1532 |
+
if isinstance(arg, SizeArg):
|
| 1533 |
+
code.writeline(f"{arg.name} = hl.InputScalar({self.index_dtype})")
|
| 1534 |
+
else:
|
| 1535 |
+
assert arg.buffer, arg
|
| 1536 |
+
argcls = "hl.OutputBuffer" if "out" in arg.name else "hl.InputBuffer"
|
| 1537 |
+
argtype = halide_type(arg.dtype)
|
| 1538 |
+
ndim = len(self.buffer_dimensions[arg.name])
|
| 1539 |
+
code.writeline(f"{arg.name} = {argcls}({argtype}, {ndim})")
|
| 1540 |
+
code.splice(
|
| 1541 |
+
"""
|
| 1542 |
+
def generate(g):
|
| 1543 |
+
"""
|
| 1544 |
+
)
|
| 1545 |
+
code.do_indent()
|
| 1546 |
+
for _, arg in self.halide_argdefs():
|
| 1547 |
+
code.writeline(f"{arg.name} = g.{arg.name}")
|
| 1548 |
+
for old, new in self.args.aliases():
|
| 1549 |
+
code.writeline(f"{old} = {new}")
|
| 1550 |
+
code.splice(self.indexing_code)
|
| 1551 |
+
|
| 1552 |
+
def update_index(m):
|
| 1553 |
+
var = cast(HalideCSEVariable, self.cse.varname_map[m.group(1)])
|
| 1554 |
+
assert var.used_dims is not None, var
|
| 1555 |
+
return str(var)
|
| 1556 |
+
|
| 1557 |
+
for line in self.body._lines:
|
| 1558 |
+
if isinstance(line, str):
|
| 1559 |
+
# fill in missing indices
|
| 1560 |
+
line = HalideCSEVariable.undefined_re.sub(update_index, line)
|
| 1561 |
+
code.writeline(line)
|
| 1562 |
+
code.writeline("")
|
| 1563 |
+
code.writeline("assert g.using_autoscheduler()")
|
| 1564 |
+
|
| 1565 |
+
for _, arg in self.halide_argdefs():
|
| 1566 |
+
# fallback=1 below because halide requires buffers to be at least as large as the estimates
|
| 1567 |
+
# This causes crashes if our estimate is greater than the vector length
|
| 1568 |
+
# https://github.com/halide/Halide/issues/3103
|
| 1569 |
+
if isinstance(arg, SizeArg):
|
| 1570 |
+
hint = V.graph.sizevars.size_hint(arg.expr, fallback=1)
|
| 1571 |
+
code.writeline(f"{arg.name}.set_estimate({hint})")
|
| 1572 |
+
else:
|
| 1573 |
+
dims = self.buffer_dimensions[arg.name]
|
| 1574 |
+
range_hints = []
|
| 1575 |
+
for i, dim in enumerate(dims):
|
| 1576 |
+
hint = self._autoscheduler_workarounds(
|
| 1577 |
+
V.graph.sizevars.size_hint(dim.size, fallback=1), dims
|
| 1578 |
+
)
|
| 1579 |
+
range_hints.append(f"hl.Range(0, {hint})")
|
| 1580 |
+
if "out" not in arg.name:
|
| 1581 |
+
code.writeline(f"{arg.name}.dim({i}).set_min(0)")
|
| 1582 |
+
try:
|
| 1583 |
+
code.writeline(
|
| 1584 |
+
f"{arg.name}.dim({i}).set_stride({int(dim.stride)})"
|
| 1585 |
+
)
|
| 1586 |
+
except TypeError:
|
| 1587 |
+
pass # not integer
|
| 1588 |
+
try:
|
| 1589 |
+
code.writeline(
|
| 1590 |
+
f"{arg.name}.dim({i}).set_extent({int(dim.size)})"
|
| 1591 |
+
)
|
| 1592 |
+
except TypeError:
|
| 1593 |
+
pass # not integer
|
| 1594 |
+
code.writeline(f"{arg.name}.set_estimates([{', '.join(range_hints)}])")
|
| 1595 |
+
|
| 1596 |
+
code.do_unindent(2)
|
| 1597 |
+
code.splice(
|
| 1598 |
+
"""
|
| 1599 |
+
if __name__ == "__main__":
|
| 1600 |
+
hl.main()
|
| 1601 |
+
""".rstrip(),
|
| 1602 |
+
)
|
| 1603 |
+
if meta.scheduler:
|
| 1604 |
+
code.splice(
|
| 1605 |
+
f"""
|
| 1606 |
+
else:
|
| 1607 |
+
hl.load_plugin({HalideCodeCache.find_libautoschedule(meta.scheduler)!r})
|
| 1608 |
+
target = hl.Target({meta.target!r})
|
| 1609 |
+
autoscheduler = hl.AutoschedulerParams({meta.scheduler!r}, {meta.scheduler_flags!r})
|
| 1610 |
+
with hl.GeneratorContext(target, autoscheduler):
|
| 1611 |
+
gen = Kernel()
|
| 1612 |
+
pipeline = gen._build_pipeline()
|
| 1613 |
+
# gen.compile_to_callable() does not run the autoscheduler
|
| 1614 |
+
pipeline.apply_autoscheduler(target, autoscheduler)
|
| 1615 |
+
kernel = pipeline.compile_to_callable([
|
| 1616 |
+
gen._get_input_parameter(a.name)._to_argument()
|
| 1617 |
+
for a in gen._get_arginfos()
|
| 1618 |
+
if a.dir == hl.ArgInfoDirection.Input
|
| 1619 |
+
], target)
|
| 1620 |
+
""",
|
| 1621 |
+
strip=True,
|
| 1622 |
+
)
|
| 1623 |
+
else:
|
| 1624 |
+
code.splice(
|
| 1625 |
+
f"""
|
| 1626 |
+
else:
|
| 1627 |
+
with hl.GeneratorContext(hl.Target({meta.target!r})):
|
| 1628 |
+
kernel = Kernel().compile_to_callable()
|
| 1629 |
+
""",
|
| 1630 |
+
strip=True,
|
| 1631 |
+
)
|
| 1632 |
+
return code.getvalue()
|
| 1633 |
+
|
| 1634 |
+
@staticmethod
|
| 1635 |
+
def _autoscheduler_workarounds(n, dims):
|
| 1636 |
+
if (
|
| 1637 |
+
len(dims) == 1
|
| 1638 |
+
and config.halide.scheduler_cuda == "Anderson2021"
|
| 1639 |
+
and V.graph.get_current_device_or_throw().type == "cuda"
|
| 1640 |
+
):
|
| 1641 |
+
# workaround https://github.com/halide/Halide/issues/8246
|
| 1642 |
+
n = max(2, n)
|
| 1643 |
+
return n
|
| 1644 |
+
|
| 1645 |
+
def call_kernel(self, name: str, node=None):
|
| 1646 |
+
"""Codegen a call to this kernel"""
|
| 1647 |
+
wrapper = V.graph.wrapper_code
|
| 1648 |
+
call_args = [f"{n}" for n, arg in self.halide_argdefs() if arg.alias_of is None]
|
| 1649 |
+
current_device = V.graph.get_current_device_or_throw()
|
| 1650 |
+
if current_device.type == "cuda":
|
| 1651 |
+
stream_name = wrapper.write_get_raw_stream(
|
| 1652 |
+
current_device.index, V.graph.name
|
| 1653 |
+
)
|
| 1654 |
+
call_args.append(stream_name)
|
| 1655 |
+
wrapper.generate_kernel_call(
|
| 1656 |
+
name,
|
| 1657 |
+
call_args,
|
| 1658 |
+
device=current_device,
|
| 1659 |
+
triton=False,
|
| 1660 |
+
)
|
| 1661 |
+
|
| 1662 |
+
def generate_assert(self, check):
|
| 1663 |
+
return False # TODO(jansel): support asserts
|
| 1664 |
+
|
| 1665 |
+
def check_bounds(
|
| 1666 |
+
self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool
|
| 1667 |
+
):
|
| 1668 |
+
pass # TODO(jansel): support asserts
|
| 1669 |
+
|
| 1670 |
+
|
| 1671 |
+
class HalideScheduling(SIMDScheduling):
|
| 1672 |
+
kernel_type = HalideKernel # type: ignore[arg-type,assignment]
|
| 1673 |
+
|
| 1674 |
+
@classmethod
|
| 1675 |
+
def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]:
|
| 1676 |
+
result = OrderedSet(
|
| 1677 |
+
[
|
| 1678 |
+
BackendFeature.TUPLE_REDUCTION,
|
| 1679 |
+
BackendFeature.PREFER_STORE_LOOP_ORDER,
|
| 1680 |
+
BackendFeature.REDUCE_TO_SINGLE_ELEMENT,
|
| 1681 |
+
]
|
| 1682 |
+
)
|
| 1683 |
+
if config.halide.scan_kernels:
|
| 1684 |
+
result.add(BackendFeature.SCAN)
|
| 1685 |
+
return result
|
| 1686 |
+
|
| 1687 |
+
def define_kernel(self, src_code, node_schedule, kernel):
|
| 1688 |
+
"""Codegen kernel definition to go in output wrapper code"""
|
| 1689 |
+
wrapper = V.graph.wrapper_code
|
| 1690 |
+
if src_code in wrapper.src_to_kernel:
|
| 1691 |
+
kernel_name = wrapper.src_to_kernel[src_code]
|
| 1692 |
+
else:
|
| 1693 |
+
kernel_name = f"halide_kernel_{wrapper.next_kernel_suffix()}"
|
| 1694 |
+
wrapper.src_to_kernel[src_code] = kernel_name
|
| 1695 |
+
wrapper.add_import_once(
|
| 1696 |
+
"from torch._inductor.runtime.hints import HalideMeta, HalideInputSpec"
|
| 1697 |
+
)
|
| 1698 |
+
|
| 1699 |
+
compile_wrapper = IndentedBuffer()
|
| 1700 |
+
compile_wrapper.writeline(
|
| 1701 |
+
f"async_compile.halide({kernel.halide_kernel_meta()!r}, '''"
|
| 1702 |
+
)
|
| 1703 |
+
compile_wrapper.splice(src_code, strip=True)
|
| 1704 |
+
compile_wrapper.writeline("''')")
|
| 1705 |
+
|
| 1706 |
+
origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
|
| 1707 |
+
metadata_comment = f"{origins}\n{detailed_origins}"
|
| 1708 |
+
wrapper.define_kernel(
|
| 1709 |
+
kernel_name, compile_wrapper.getvalue(), metadata_comment
|
| 1710 |
+
)
|
| 1711 |
+
if is_metric_table_enabled("kernel_metadata"):
|
| 1712 |
+
log_kernel_metadata(kernel_name, "", src_code)
|
| 1713 |
+
|
| 1714 |
+
return kernel_name
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/memory_planning.py
ADDED
|
@@ -0,0 +1,816 @@
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import collections
|
| 5 |
+
import dataclasses
|
| 6 |
+
import itertools
|
| 7 |
+
import pprint
|
| 8 |
+
from typing import Any, Optional, Protocol, TYPE_CHECKING
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
|
| 14 |
+
from torch.utils._ordered_set import OrderedSet
|
| 15 |
+
|
| 16 |
+
from .. import config
|
| 17 |
+
from ..utils import _align, align, cache_on_self, CachedMethod, IndentedBuffer
|
| 18 |
+
from ..virtualized import V
|
| 19 |
+
from .wrapper import (
|
| 20 |
+
AllocateLine,
|
| 21 |
+
BufferLike,
|
| 22 |
+
FreeIfNotReusedLine,
|
| 23 |
+
MemoryPlanningLine,
|
| 24 |
+
NullLine,
|
| 25 |
+
ReuseLine,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if TYPE_CHECKING:
|
| 30 |
+
from collections.abc import Iterable
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclasses.dataclass
|
| 34 |
+
class LiveRange:
|
| 35 |
+
"""
|
| 36 |
+
A range where a given tensor is live. Begin and end are both counters
|
| 37 |
+
representing points in the program of grouped memory operations.
|
| 38 |
+
Begin is inclusive, end is exclusive.
|
| 39 |
+
|
| 40 |
+
Invariant: begin <= end
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
begin: float # int | +/-inf
|
| 44 |
+
end: float # int | +/-inf
|
| 45 |
+
|
| 46 |
+
def contains(self, other: LiveRange):
|
| 47 |
+
"""Is other entirely within self"""
|
| 48 |
+
return self.begin <= other.begin and other.end <= self.end
|
| 49 |
+
|
| 50 |
+
def join(self, other: LiveRange):
|
| 51 |
+
"""Combine two ranges using a union operation"""
|
| 52 |
+
return LiveRange(min(self.begin, other.begin), max(self.end, other.end))
|
| 53 |
+
|
| 54 |
+
def __len__(self):
|
| 55 |
+
return self.end - self.begin
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class LiveRanges:
|
| 59 |
+
"""
|
| 60 |
+
A collection of LiveRange regions, allowing for non-contiguous
|
| 61 |
+
live regions.
|
| 62 |
+
|
| 63 |
+
Invariant: LiveRanges.ranges is in sorted order and non-overlapping
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(self, ranges: Iterable[LiveRange]):
|
| 67 |
+
ranges = [*sorted(ranges, key=lambda x: x.begin)]
|
| 68 |
+
self.ranges = ranges[:1]
|
| 69 |
+
for r in ranges[1:]:
|
| 70 |
+
assert self.ranges[-1].begin <= r.begin
|
| 71 |
+
if self.ranges[-1].end >= r.begin:
|
| 72 |
+
self.ranges[-1] = LiveRange.join(self.ranges[-1], r)
|
| 73 |
+
else:
|
| 74 |
+
self.ranges.append(r)
|
| 75 |
+
|
| 76 |
+
def overlaps(self, other: LiveRanges):
|
| 77 |
+
"""Check if any pair of ranges in self and other overlap"""
|
| 78 |
+
left = collections.deque(self.ranges)
|
| 79 |
+
right = collections.deque(other.ranges)
|
| 80 |
+
while left and right:
|
| 81 |
+
if left[0].begin > right[0].begin:
|
| 82 |
+
left, right = right, left
|
| 83 |
+
assert left[0].begin <= right[0].begin
|
| 84 |
+
if left[0].end > right[0].begin:
|
| 85 |
+
return True
|
| 86 |
+
left.popleft()
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def begin(self):
|
| 91 |
+
return self.ranges[0].begin
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def end(self):
|
| 95 |
+
return self.ranges[-1].end
|
| 96 |
+
|
| 97 |
+
def __repr__(self):
|
| 98 |
+
return f"{self.__class__.__name__}([{', '.join(map(repr, self.ranges))}])"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class AllocationTreeNode:
|
| 102 |
+
"""
|
| 103 |
+
Abstract base class for nodes in allocation pool.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
def allocate(self, block: Allocation, is_last: bool) -> bool:
|
| 107 |
+
"""
|
| 108 |
+
Try to assign block to a memory location in this bool. Return True if
|
| 109 |
+
an assignment was made.
|
| 110 |
+
"""
|
| 111 |
+
return False
|
| 112 |
+
|
| 113 |
+
def get_live_ranges(self) -> LiveRanges:
|
| 114 |
+
"""Aggregate LiveRanges for all objects below this in tree"""
|
| 115 |
+
raise NotImplementedError
|
| 116 |
+
|
| 117 |
+
def get_size_hint(self) -> int:
|
| 118 |
+
"""Number of bytes used for example inputs"""
|
| 119 |
+
raise NotImplementedError
|
| 120 |
+
|
| 121 |
+
def get_symbolic_size(self) -> sympy.Expr:
|
| 122 |
+
"""Number of bytes needed at runtime"""
|
| 123 |
+
raise NotImplementedError
|
| 124 |
+
|
| 125 |
+
def finalize(self, pool, offset) -> AllocationTreeNode:
|
| 126 |
+
"""Called after all allocations have been made"""
|
| 127 |
+
return self
|
| 128 |
+
|
| 129 |
+
def is_empty(self):
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@dataclasses.dataclass
|
| 134 |
+
class Allocation(AllocationTreeNode):
|
| 135 |
+
"""
|
| 136 |
+
Represents memory allocated to a given node in the allocation pool.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
node: BufferLike
|
| 140 |
+
live_range: LiveRange
|
| 141 |
+
size_hint: int
|
| 142 |
+
symbolic_size: sympy.Expr
|
| 143 |
+
allocated: bool = False
|
| 144 |
+
pool: Optional[AllocationPool] = None
|
| 145 |
+
offset: Optional[sympy.Expr] = None
|
| 146 |
+
earliest_available: Optional[float] = None
|
| 147 |
+
|
| 148 |
+
def __post_init__(self) -> None:
|
| 149 |
+
has_unbacked_sym = False
|
| 150 |
+
for s in self.node.get_layout().size:
|
| 151 |
+
if free_unbacked_symbols(s):
|
| 152 |
+
has_unbacked_sym = True
|
| 153 |
+
break
|
| 154 |
+
|
| 155 |
+
if has_unbacked_sym:
|
| 156 |
+
self.earliest_available = self.get_live_ranges().begin
|
| 157 |
+
|
| 158 |
+
@property
|
| 159 |
+
def device(self):
|
| 160 |
+
return self.node.get_device()
|
| 161 |
+
|
| 162 |
+
def get_live_ranges(self):
|
| 163 |
+
return LiveRanges([self.live_range])
|
| 164 |
+
|
| 165 |
+
def get_size_hint(self):
|
| 166 |
+
return self.size_hint
|
| 167 |
+
|
| 168 |
+
def get_symbolic_size(self):
|
| 169 |
+
return self.symbolic_size
|
| 170 |
+
|
| 171 |
+
def mark_allocated(self):
|
| 172 |
+
assert not self.allocated
|
| 173 |
+
self.allocated = True
|
| 174 |
+
|
| 175 |
+
def finalize(self, pool, offset):
|
| 176 |
+
assert self.pool is None and self.offset is None
|
| 177 |
+
self.pool = pool
|
| 178 |
+
self.offset = offset
|
| 179 |
+
return self
|
| 180 |
+
|
| 181 |
+
def codegen_alloc_from_pool(self, wrapper):
|
| 182 |
+
assert self.pool
|
| 183 |
+
node = self.node
|
| 184 |
+
shape = tuple(node.get_size())
|
| 185 |
+
stride = tuple(node.get_stride())
|
| 186 |
+
return wrapper.codegen_alloc_from_pool(
|
| 187 |
+
self.pool.name, self.offset, node.get_dtype(), shape, stride
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def __repr__(self):
|
| 191 |
+
return (
|
| 192 |
+
f"{self.__class__.__name__}("
|
| 193 |
+
f"node={self.node.get_name()}, "
|
| 194 |
+
f"live_range={self.live_range}, "
|
| 195 |
+
f"size_hint={self.size_hint}, "
|
| 196 |
+
f"symbolic_size={self.symbolic_size}, "
|
| 197 |
+
f"pool={self.pool.name if self.pool else None}, "
|
| 198 |
+
f"offset={self.offset})"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def get_earliest_available(self):
|
| 202 |
+
return self.earliest_available
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
@dataclasses.dataclass
|
| 206 |
+
class Empty(AllocationTreeNode):
|
| 207 |
+
"""
|
| 208 |
+
Placeholder to represent empty space in the allocation pool.
|
| 209 |
+
Only exists to get the size_hint correct in parent nodes.
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
size_hint: int
|
| 213 |
+
|
| 214 |
+
def get_live_ranges(self):
|
| 215 |
+
return LiveRanges([])
|
| 216 |
+
|
| 217 |
+
def get_size_hint(self):
|
| 218 |
+
return self.size_hint
|
| 219 |
+
|
| 220 |
+
def get_symbolic_size(self):
|
| 221 |
+
return 0
|
| 222 |
+
|
| 223 |
+
def is_empty(self):
|
| 224 |
+
return True
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class MemorySplitProtocol(Protocol):
|
| 228 |
+
get_live_ranges: CachedMethod[[], LiveRanges]
|
| 229 |
+
get_size_hint: CachedMethod[[], int]
|
| 230 |
+
get_symbolic_size: CachedMethod[[], sympy.Expr]
|
| 231 |
+
|
| 232 |
+
def _allocate(self, block: Allocation, is_last: bool) -> bool: ...
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
class ClearCacheOnAllocateMixin(MemorySplitProtocol):
|
| 236 |
+
"""
|
| 237 |
+
Helper to assist in caching get_live_ranges, get_size_hint, and
|
| 238 |
+
get_symbolic_size.
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
def allocate(self, block: Allocation, is_last: bool):
|
| 242 |
+
is_allocated = self._allocate(block, is_last)
|
| 243 |
+
if is_allocated:
|
| 244 |
+
self.clear_cache()
|
| 245 |
+
return is_allocated
|
| 246 |
+
|
| 247 |
+
def clear_cache(self):
|
| 248 |
+
self.get_live_ranges.clear_cache(self)
|
| 249 |
+
self.get_size_hint.clear_cache(self)
|
| 250 |
+
self.get_symbolic_size.clear_cache(self)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@dataclasses.dataclass
|
| 254 |
+
class TemporalSplit(ClearCacheOnAllocateMixin, AllocationTreeNode):
|
| 255 |
+
"""
|
| 256 |
+
Contains a list of allocations not overlapping in LiveRanges.
|
| 257 |
+
|
| 258 |
+
Invariant: no pair (a,b) in self.allocations will have:
|
| 259 |
+
a.get_live_ranges().overlaps(b.get_live_ranges())
|
| 260 |
+
"""
|
| 261 |
+
|
| 262 |
+
allocations: list[AllocationTreeNode]
|
| 263 |
+
|
| 264 |
+
def _allocate(self, block: Allocation, is_last: bool):
|
| 265 |
+
slot_size = self.get_size_hint()
|
| 266 |
+
block_size = block.get_size_hint()
|
| 267 |
+
if not is_last and block_size > slot_size:
|
| 268 |
+
return False # doesn't fit
|
| 269 |
+
|
| 270 |
+
block_live = block.get_live_ranges()
|
| 271 |
+
overlapping = [
|
| 272 |
+
s for s in self.allocations if s.get_live_ranges().overlaps(block_live)
|
| 273 |
+
]
|
| 274 |
+
if len(overlapping) > 1:
|
| 275 |
+
# TODO(jansel): we could try harder here by merging overlapping in space
|
| 276 |
+
return False
|
| 277 |
+
elif len(overlapping) == 1:
|
| 278 |
+
return overlapping[0].allocate(block, is_last)
|
| 279 |
+
else:
|
| 280 |
+
block.mark_allocated()
|
| 281 |
+
|
| 282 |
+
if len(self.allocations) == 1 and isinstance(self.allocations[-1], Empty):
|
| 283 |
+
self.allocations.pop()
|
| 284 |
+
|
| 285 |
+
if slot_size == block_size:
|
| 286 |
+
# perfect fit
|
| 287 |
+
self.allocations.append(block)
|
| 288 |
+
elif slot_size > block_size:
|
| 289 |
+
self.allocations.append(
|
| 290 |
+
SpatialSplit.create(block, slot_size - block_size)
|
| 291 |
+
)
|
| 292 |
+
else: # grow this allocation
|
| 293 |
+
assert is_last
|
| 294 |
+
self.allocations = [
|
| 295 |
+
*(
|
| 296 |
+
SpatialSplit.create(a, block_size - slot_size)
|
| 297 |
+
for a in self.allocations
|
| 298 |
+
),
|
| 299 |
+
block,
|
| 300 |
+
]
|
| 301 |
+
return True
|
| 302 |
+
|
| 303 |
+
@cache_on_self
|
| 304 |
+
def get_live_ranges(self) -> LiveRanges:
|
| 305 |
+
return LiveRanges(
|
| 306 |
+
itertools.chain.from_iterable(
|
| 307 |
+
x.get_live_ranges().ranges for x in self.allocations
|
| 308 |
+
)
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
@cache_on_self
|
| 312 |
+
def get_size_hint(self) -> int:
|
| 313 |
+
if not self.allocations:
|
| 314 |
+
return 0
|
| 315 |
+
return max(x.get_size_hint() for x in self.allocations)
|
| 316 |
+
|
| 317 |
+
@cache_on_self
|
| 318 |
+
def get_symbolic_size(self) -> sympy.Expr:
|
| 319 |
+
if not self.allocations:
|
| 320 |
+
return 0 # type: ignore[return-value]
|
| 321 |
+
return sympy.Max(*[x.get_symbolic_size() for x in self.allocations])
|
| 322 |
+
|
| 323 |
+
def is_empty(self):
|
| 324 |
+
return len(self.allocations) == 1 and self.allocations[0].is_empty()
|
| 325 |
+
|
| 326 |
+
def finalize(self, pool, offset):
|
| 327 |
+
self.allocations = [block.finalize(pool, offset) for block in self.allocations]
|
| 328 |
+
self.clear_cache()
|
| 329 |
+
if len(self.allocations) == 1:
|
| 330 |
+
return self.allocations[0]
|
| 331 |
+
return self
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@dataclasses.dataclass
|
| 335 |
+
class SpatialSplit(ClearCacheOnAllocateMixin, AllocationTreeNode):
|
| 336 |
+
"""
|
| 337 |
+
Contains two allocations, left and right, that do not overlap in space.
|
| 338 |
+
Right will be allocated immediately after left in memory.
|
| 339 |
+
"""
|
| 340 |
+
|
| 341 |
+
left: TemporalSplit
|
| 342 |
+
right: TemporalSplit
|
| 343 |
+
|
| 344 |
+
@staticmethod
|
| 345 |
+
def create(left, extra_space):
|
| 346 |
+
assert isinstance(left, AllocationTreeNode)
|
| 347 |
+
assert isinstance(extra_space, int) and extra_space >= 1
|
| 348 |
+
return SpatialSplit(TemporalSplit([left]), TemporalSplit([Empty(extra_space)]))
|
| 349 |
+
|
| 350 |
+
def _allocate(self, block: Allocation, is_last: bool):
|
| 351 |
+
return self.left.allocate(block, False) or self.right.allocate(block, is_last)
|
| 352 |
+
|
| 353 |
+
@cache_on_self
|
| 354 |
+
def get_live_ranges(self):
|
| 355 |
+
return LiveRanges(
|
| 356 |
+
itertools.chain(
|
| 357 |
+
self.left.get_live_ranges().ranges, self.right.get_live_ranges().ranges
|
| 358 |
+
)
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
@cache_on_self
|
| 362 |
+
def get_size_hint(self) -> int:
|
| 363 |
+
return _align(self.left.get_size_hint()) + self.right.get_size_hint()
|
| 364 |
+
|
| 365 |
+
@cache_on_self
|
| 366 |
+
def get_symbolic_size(self) -> sympy.Expr:
|
| 367 |
+
return align(self.left.get_symbolic_size()) + self.right.get_symbolic_size()
|
| 368 |
+
|
| 369 |
+
def finalize(self, pool, offset):
|
| 370 |
+
self.left = self.left.finalize(pool, offset)
|
| 371 |
+
self.right = self.right.finalize(
|
| 372 |
+
pool, offset + align(self.left.get_symbolic_size())
|
| 373 |
+
)
|
| 374 |
+
self.clear_cache()
|
| 375 |
+
if self.right.is_empty():
|
| 376 |
+
return self.left
|
| 377 |
+
return self
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
@dataclasses.dataclass
|
| 381 |
+
class AllocationPool:
|
| 382 |
+
"""
|
| 383 |
+
Represents a pool of allocations that will be generated by a single
|
| 384 |
+
call to torch.empty.
|
| 385 |
+
"""
|
| 386 |
+
|
| 387 |
+
device: torch.device
|
| 388 |
+
root: TemporalSplit
|
| 389 |
+
can_expand: bool = True
|
| 390 |
+
restrict_live_range: Optional[LiveRange] = None
|
| 391 |
+
name: Optional[str] = None
|
| 392 |
+
names_to_del: list[str] = dataclasses.field(default_factory=list)
|
| 393 |
+
creation_cache: dict[str, str] = dataclasses.field(default_factory=dict)
|
| 394 |
+
|
| 395 |
+
def __post_init__(self) -> None:
|
| 396 |
+
for block in self.root.allocations:
|
| 397 |
+
if isinstance(block, Allocation):
|
| 398 |
+
self.update_restrict_live_range(block)
|
| 399 |
+
|
| 400 |
+
def allocate(self, block: Allocation, is_last: bool):
|
| 401 |
+
if (
|
| 402 |
+
self.restrict_live_range is not None
|
| 403 |
+
and not self.restrict_live_range.contains(block.live_range)
|
| 404 |
+
):
|
| 405 |
+
return False
|
| 406 |
+
|
| 407 |
+
block_earliest_available = block.get_earliest_available()
|
| 408 |
+
pool_begin = self.root.get_live_ranges().begin
|
| 409 |
+
if block_earliest_available and block_earliest_available > pool_begin:
|
| 410 |
+
return False
|
| 411 |
+
|
| 412 |
+
is_last = self.can_expand and is_last
|
| 413 |
+
if self.root.allocate(block, is_last):
|
| 414 |
+
self.update_restrict_live_range(block)
|
| 415 |
+
return True
|
| 416 |
+
|
| 417 |
+
if is_last:
|
| 418 |
+
return self.allocate_at_end(block)
|
| 419 |
+
|
| 420 |
+
return False
|
| 421 |
+
|
| 422 |
+
def update_restrict_live_range(self, block: Allocation):
|
| 423 |
+
if block_earliest_available := block.get_earliest_available():
|
| 424 |
+
if self.restrict_live_range is None:
|
| 425 |
+
self.restrict_live_range = LiveRange(
|
| 426 |
+
block_earliest_available, float("inf")
|
| 427 |
+
)
|
| 428 |
+
else:
|
| 429 |
+
self.restrict_live_range = LiveRange(
|
| 430 |
+
min(self.restrict_live_range.begin, block_earliest_available),
|
| 431 |
+
self.restrict_live_range.end,
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
def allocate_at_end(self, block):
|
| 435 |
+
block.mark_allocated()
|
| 436 |
+
self.root = TemporalSplit([SpatialSplit(self.root, TemporalSplit([block]))])
|
| 437 |
+
self.update_restrict_live_range(block)
|
| 438 |
+
return True
|
| 439 |
+
|
| 440 |
+
def finalize(self, name):
|
| 441 |
+
assert not self.name
|
| 442 |
+
self.name = name
|
| 443 |
+
self.names_to_del.append(name)
|
| 444 |
+
self.root.finalize(self, 0)
|
| 445 |
+
|
| 446 |
+
def codegen_create(self, wrapper, code: IndentedBuffer):
|
| 447 |
+
assert self.name
|
| 448 |
+
nbytes = self.root.get_symbolic_size()
|
| 449 |
+
for block in self.root.allocations:
|
| 450 |
+
if isinstance(block, Allocation) and nbytes == block.get_symbolic_size():
|
| 451 |
+
node = block.node
|
| 452 |
+
code.writeline(
|
| 453 |
+
wrapper.make_allocation(
|
| 454 |
+
self.name,
|
| 455 |
+
device=self.device,
|
| 456 |
+
dtype=node.get_dtype(),
|
| 457 |
+
shape=tuple(node.get_size()),
|
| 458 |
+
stride=tuple(node.get_stride()),
|
| 459 |
+
)
|
| 460 |
+
)
|
| 461 |
+
return
|
| 462 |
+
else:
|
| 463 |
+
code.writeline(
|
| 464 |
+
wrapper.make_allocation(
|
| 465 |
+
self.name,
|
| 466 |
+
device=self.device,
|
| 467 |
+
dtype=torch.uint8,
|
| 468 |
+
shape=(nbytes,),
|
| 469 |
+
stride=(1,),
|
| 470 |
+
)
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
def codegen_destroy(self, wrapper, code: IndentedBuffer):
|
| 474 |
+
code.writeline(wrapper.make_free_by_names(self.names_to_del))
|
| 475 |
+
|
| 476 |
+
def __eq__(self, other):
|
| 477 |
+
return self is other
|
| 478 |
+
|
| 479 |
+
def __hash__(self):
|
| 480 |
+
return id(self)
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
@dataclasses.dataclass
|
| 484 |
+
class AllocationPools:
|
| 485 |
+
"""
|
| 486 |
+
Collection of many AllocationPool objects grouped by device.
|
| 487 |
+
"""
|
| 488 |
+
|
| 489 |
+
device_to_pools: dict[torch.device, list[AllocationPool]] = dataclasses.field(
|
| 490 |
+
default_factory=dict
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
def get_pools(self, block):
|
| 494 |
+
if block.device not in self.device_to_pools:
|
| 495 |
+
self.device_to_pools[block.device] = []
|
| 496 |
+
return self.device_to_pools[block.device]
|
| 497 |
+
|
| 498 |
+
def allocate(self, block: Allocation):
|
| 499 |
+
pools = self.get_pools(block)
|
| 500 |
+
|
| 501 |
+
for pool in pools:
|
| 502 |
+
if pool.allocate(block, is_last=pool is pools[-1]):
|
| 503 |
+
return
|
| 504 |
+
|
| 505 |
+
# everything is full, make a new pool
|
| 506 |
+
pools.append(
|
| 507 |
+
AllocationPool(
|
| 508 |
+
block.device,
|
| 509 |
+
TemporalSplit([block]),
|
| 510 |
+
can_expand=config.memory_pool != "none",
|
| 511 |
+
)
|
| 512 |
+
)
|
| 513 |
+
block.mark_allocated()
|
| 514 |
+
|
| 515 |
+
def allocate_output(self, block: Allocation):
|
| 516 |
+
"""Outputs get different pools so memory gets freed properly"""
|
| 517 |
+
pools = self.get_pools(block)
|
| 518 |
+
if pools and config.memory_pool in ("outputs", "combined"):
|
| 519 |
+
pools[-1].allocate_at_end(block)
|
| 520 |
+
else:
|
| 521 |
+
# create a new pool
|
| 522 |
+
block.mark_allocated()
|
| 523 |
+
pools.append(
|
| 524 |
+
AllocationPool(
|
| 525 |
+
block.device,
|
| 526 |
+
TemporalSplit([block]),
|
| 527 |
+
can_expand=config.memory_pool == "combined",
|
| 528 |
+
)
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
def finalize(self):
|
| 532 |
+
"""Called at the end of allocation process"""
|
| 533 |
+
for i, pool in enumerate(
|
| 534 |
+
itertools.chain.from_iterable(self.device_to_pools.values())
|
| 535 |
+
):
|
| 536 |
+
pool.finalize(f"pool{i}")
|
| 537 |
+
|
| 538 |
+
def pprint(self):
|
| 539 |
+
for pool in itertools.chain.from_iterable(self.device_to_pools.values()):
|
| 540 |
+
print()
|
| 541 |
+
print(pool.name)
|
| 542 |
+
print(pool.root.get_live_ranges())
|
| 543 |
+
pprint.pprint(pool.root)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
class BufferGroup:
|
| 547 |
+
"""
|
| 548 |
+
Due to inplace reuse an allocated buffer can have many names.
|
| 549 |
+
This tracks these collections of buffers sharing underlying memory.
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
def __init__(self, node: BufferLike):
|
| 553 |
+
self.node = node
|
| 554 |
+
self.names = [node.get_name()]
|
| 555 |
+
self.is_output = False
|
| 556 |
+
self.allocation: Optional[Allocation] = None
|
| 557 |
+
self.live_range = LiveRange(float("inf"), -float("inf"))
|
| 558 |
+
|
| 559 |
+
def update_usage(self, timestep: int):
|
| 560 |
+
"""Expand self.live_range to include timestep"""
|
| 561 |
+
self.live_range = LiveRange(
|
| 562 |
+
min(timestep, self.live_range.begin),
|
| 563 |
+
max(timestep, self.live_range.end),
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
def sym_nbytes(self):
|
| 567 |
+
return self.node.get_layout().storage_size() * self.node.get_dtype().itemsize
|
| 568 |
+
|
| 569 |
+
def make_allocation(self):
|
| 570 |
+
assert not self.allocation, "multiple allocations"
|
| 571 |
+
assert isinstance(self.live_range.begin, int), "live ranges not computed"
|
| 572 |
+
nbytes = self.sym_nbytes()
|
| 573 |
+
# For now, fallback value will be used if we encounter an unbacked SymInt. The longer-term plan is to have
|
| 574 |
+
# size_hint() use better heuristics for unbackeds, at which point the fallback value will be ignored.
|
| 575 |
+
size_hint = V.graph.sizevars.size_hint(nbytes, fallback=64)
|
| 576 |
+
self.allocation = Allocation(
|
| 577 |
+
self.node,
|
| 578 |
+
self.live_range,
|
| 579 |
+
size_hint=size_hint,
|
| 580 |
+
symbolic_size=nbytes,
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
def __repr__(self):
|
| 584 |
+
return (
|
| 585 |
+
f"{self.__class__.__name__}({self.names!r}, is_output={self.is_output}, "
|
| 586 |
+
f"live_range={self.live_range}"
|
| 587 |
+
)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
@dataclasses.dataclass
|
| 591 |
+
class PoolMemoryPlanningLine(MemoryPlanningLine):
|
| 592 |
+
"""Abstract base class for {Alloc,Dealloc}FromPoolLine"""
|
| 593 |
+
|
| 594 |
+
group: BufferGroup
|
| 595 |
+
timestep: Optional[int] = None
|
| 596 |
+
|
| 597 |
+
@property
|
| 598 |
+
def node(self):
|
| 599 |
+
return self.group.node
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
@dataclasses.dataclass
|
| 603 |
+
class AllocFromPoolLine(PoolMemoryPlanningLine):
|
| 604 |
+
"""Similar to AllocationLine, but takes memory from a pool"""
|
| 605 |
+
|
| 606 |
+
is_first_pool_usage: bool = False
|
| 607 |
+
|
| 608 |
+
def codegen(self, code: IndentedBuffer):
|
| 609 |
+
allocation = self.group.allocation
|
| 610 |
+
assert allocation and allocation.pool
|
| 611 |
+
pool = allocation.pool
|
| 612 |
+
name = self.node.get_name()
|
| 613 |
+
|
| 614 |
+
if self.is_first_pool_usage:
|
| 615 |
+
pool.codegen_create(self.wrapper, code)
|
| 616 |
+
|
| 617 |
+
pool.names_to_del.extend(self.group.names)
|
| 618 |
+
alloc_from_pool, allocation_lines_to_write = allocation.codegen_alloc_from_pool(
|
| 619 |
+
self.wrapper
|
| 620 |
+
)
|
| 621 |
+
code.writelines(allocation_lines_to_write)
|
| 622 |
+
if alloc_from_pool in pool.creation_cache:
|
| 623 |
+
code.writeline(
|
| 624 |
+
self.wrapper.make_tensor_alias(
|
| 625 |
+
name, pool.creation_cache[alloc_from_pool], "alloc"
|
| 626 |
+
)
|
| 627 |
+
)
|
| 628 |
+
else:
|
| 629 |
+
pool.creation_cache[alloc_from_pool] = name
|
| 630 |
+
code.writeline(
|
| 631 |
+
f"{self.wrapper.declare}{name} = {alloc_from_pool}{self.wrapper.ending}"
|
| 632 |
+
)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
@dataclasses.dataclass
|
| 636 |
+
class DeallocFromPoolLine(PoolMemoryPlanningLine):
|
| 637 |
+
"""Similar to FreeIfNotReusedLine, but takes memory from a pool"""
|
| 638 |
+
|
| 639 |
+
is_last_pool_usage: bool = False
|
| 640 |
+
|
| 641 |
+
def codegen(self, code: IndentedBuffer):
|
| 642 |
+
if self.is_last_pool_usage:
|
| 643 |
+
assert self.group.allocation and self.group.allocation.pool
|
| 644 |
+
self.group.allocation.pool.codegen_destroy(self.wrapper, code)
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
@dataclasses.dataclass
|
| 648 |
+
class MemoryPlanner:
|
| 649 |
+
"""
|
| 650 |
+
Coordination object to run memory planning passes during wrapper
|
| 651 |
+
codegen.
|
| 652 |
+
"""
|
| 653 |
+
|
| 654 |
+
wrapper: Any
|
| 655 |
+
pools: AllocationPools = dataclasses.field(default_factory=AllocationPools)
|
| 656 |
+
buffer_groups: Optional[list[BufferGroup]] = None
|
| 657 |
+
|
| 658 |
+
def plan(self, lines: list[Any]) -> list[Any]:
|
| 659 |
+
"""Call all the memory planning passes in sequence"""
|
| 660 |
+
lines = [*lines]
|
| 661 |
+
self.drop_removed_buffers(lines)
|
| 662 |
+
self.convert_to_pool_lines(lines)
|
| 663 |
+
self.compute_live_ranges(lines)
|
| 664 |
+
self.allocate_groups()
|
| 665 |
+
self.mark_first_last_usage(lines)
|
| 666 |
+
return lines
|
| 667 |
+
|
| 668 |
+
def drop_removed_buffers(self, lines):
|
| 669 |
+
"""
|
| 670 |
+
Replace any memory planning lines in V.graph.removed_buffers with NullLine
|
| 671 |
+
"""
|
| 672 |
+
# drop any removed buffers
|
| 673 |
+
for i, line in enumerate(lines):
|
| 674 |
+
if isinstance(line, (AllocateLine, FreeIfNotReusedLine, ReuseLine)):
|
| 675 |
+
if line.node.get_name() in V.graph.removed_buffers:
|
| 676 |
+
lines[i] = NullLine(self.wrapper)
|
| 677 |
+
|
| 678 |
+
def compute_buffer_groups(self, lines):
|
| 679 |
+
"""
|
| 680 |
+
Populates self.buffer_groups with BufferGroup objects that join
|
| 681 |
+
allocations with common storage (due to inplace reuse) into a
|
| 682 |
+
single object.
|
| 683 |
+
"""
|
| 684 |
+
name_to_group = {}
|
| 685 |
+
for line in lines:
|
| 686 |
+
if isinstance(line, AllocateLine):
|
| 687 |
+
name = line.node.get_name()
|
| 688 |
+
assert name not in name_to_group
|
| 689 |
+
name_to_group[name] = BufferGroup(line.node)
|
| 690 |
+
elif isinstance(line, ReuseLine):
|
| 691 |
+
old_name = line.node.get_name()
|
| 692 |
+
new_name = line.reused_as.get_name()
|
| 693 |
+
assert new_name not in name_to_group
|
| 694 |
+
# TODO(jansel): we should support reusing buffers created via ExternKernelAlloc
|
| 695 |
+
if old_name in name_to_group:
|
| 696 |
+
name_to_group[old_name].names.append(new_name)
|
| 697 |
+
name_to_group[new_name] = name_to_group[old_name]
|
| 698 |
+
|
| 699 |
+
outputs = OrderedSet(V.graph.get_output_names())
|
| 700 |
+
unique_groups = [*{id(g): g for g in name_to_group.values()}.values()]
|
| 701 |
+
for group in unique_groups:
|
| 702 |
+
group.is_output = any(x in outputs for x in group.names)
|
| 703 |
+
|
| 704 |
+
assert self.buffer_groups is None
|
| 705 |
+
self.buffer_groups = unique_groups
|
| 706 |
+
return name_to_group
|
| 707 |
+
|
| 708 |
+
def convert_to_pool_lines(self, lines):
|
| 709 |
+
"""
|
| 710 |
+
Convert AllocateLine/FreeIfNotReusedLine/ReuseLine into their
|
| 711 |
+
pool-based counterparts.
|
| 712 |
+
"""
|
| 713 |
+
name_to_group = self.compute_buffer_groups(lines)
|
| 714 |
+
for i, line in enumerate(lines):
|
| 715 |
+
if isinstance(line, AllocateLine):
|
| 716 |
+
if line.node.get_name() in name_to_group:
|
| 717 |
+
lines[i] = AllocFromPoolLine(
|
| 718 |
+
self.wrapper, name_to_group[line.node.get_name()]
|
| 719 |
+
)
|
| 720 |
+
elif isinstance(line, FreeIfNotReusedLine):
|
| 721 |
+
assert not line.is_reused
|
| 722 |
+
if line.node.get_name() in name_to_group:
|
| 723 |
+
lines[i] = DeallocFromPoolLine(
|
| 724 |
+
self.wrapper, name_to_group[line.node.get_name()]
|
| 725 |
+
)
|
| 726 |
+
elif isinstance(line, ReuseLine):
|
| 727 |
+
if line.node.get_name() in name_to_group:
|
| 728 |
+
line.delete_old = False
|
| 729 |
+
|
| 730 |
+
def compute_live_ranges(self, lines):
|
| 731 |
+
"""Populate every BufferGroup.live_ranges field based on first/last usage"""
|
| 732 |
+
timestep = 0
|
| 733 |
+
worklist = collections.deque(lines)
|
| 734 |
+
while worklist:
|
| 735 |
+
if isinstance(worklist[0], MemoryPlanningLine):
|
| 736 |
+
timestep += 1
|
| 737 |
+
while worklist and isinstance(worklist[0], MemoryPlanningLine):
|
| 738 |
+
line = worklist.popleft()
|
| 739 |
+
if isinstance(line, PoolMemoryPlanningLine):
|
| 740 |
+
line.group.update_usage(timestep)
|
| 741 |
+
line.timestep = timestep
|
| 742 |
+
else:
|
| 743 |
+
worklist.popleft()
|
| 744 |
+
|
| 745 |
+
timestep += 1
|
| 746 |
+
assert self.buffer_groups is not None
|
| 747 |
+
for group in self.buffer_groups:
|
| 748 |
+
if group.is_output:
|
| 749 |
+
group.update_usage(timestep)
|
| 750 |
+
|
| 751 |
+
def allocate_groups(self):
|
| 752 |
+
"""
|
| 753 |
+
Assign every allocation to a specific location in a specific AllocationPool.
|
| 754 |
+
"""
|
| 755 |
+
assert config.memory_pool in ("none", "intermediates", "outputs", "combined")
|
| 756 |
+
assert self.buffer_groups is not None
|
| 757 |
+
|
| 758 |
+
for group in self.buffer_groups:
|
| 759 |
+
group.make_allocation()
|
| 760 |
+
|
| 761 |
+
outputs: list[Allocation] = []
|
| 762 |
+
intermediates: list[Allocation] = []
|
| 763 |
+
for group in self.buffer_groups:
|
| 764 |
+
assert group.allocation
|
| 765 |
+
if group.is_output and config.memory_pool != "combined":
|
| 766 |
+
outputs.append(group.allocation)
|
| 767 |
+
else:
|
| 768 |
+
intermediates.append(group.allocation)
|
| 769 |
+
|
| 770 |
+
for block in sorted(
|
| 771 |
+
outputs,
|
| 772 |
+
key=lambda x: (
|
| 773 |
+
x.size_hint,
|
| 774 |
+
-len(x.live_range),
|
| 775 |
+
),
|
| 776 |
+
):
|
| 777 |
+
self.pools.allocate_output(block)
|
| 778 |
+
|
| 779 |
+
for block in sorted(
|
| 780 |
+
intermediates,
|
| 781 |
+
key=lambda x: (
|
| 782 |
+
-x.size_hint,
|
| 783 |
+
-len(x.live_range),
|
| 784 |
+
),
|
| 785 |
+
):
|
| 786 |
+
self.pools.allocate(block)
|
| 787 |
+
|
| 788 |
+
self.pools.finalize()
|
| 789 |
+
|
| 790 |
+
def mark_first_last_usage(self, lines):
|
| 791 |
+
"""
|
| 792 |
+
Populate the AllocFromPoolLine.is_first_pool_usage and
|
| 793 |
+
DeallocFromPoolLine.is_last_pool_usage fields so that pools
|
| 794 |
+
are created/destroyed.
|
| 795 |
+
"""
|
| 796 |
+
seen = OrderedSet[AllocationPool]()
|
| 797 |
+
for line in lines:
|
| 798 |
+
if isinstance(line, AllocFromPoolLine):
|
| 799 |
+
assert line.group.allocation
|
| 800 |
+
pool = line.group.allocation.pool
|
| 801 |
+
assert pool is not None
|
| 802 |
+
if pool not in seen:
|
| 803 |
+
line.is_first_pool_usage = True
|
| 804 |
+
seen.add(pool)
|
| 805 |
+
|
| 806 |
+
seen = OrderedSet[AllocationPool]()
|
| 807 |
+
for line in reversed(lines):
|
| 808 |
+
if isinstance(line, DeallocFromPoolLine):
|
| 809 |
+
assert line.group.allocation
|
| 810 |
+
pool = line.group.allocation.pool
|
| 811 |
+
assert pool is not None
|
| 812 |
+
if pool not in seen:
|
| 813 |
+
line.is_last_pool_usage = (
|
| 814 |
+
pool.root.get_live_ranges().end <= line.timestep
|
| 815 |
+
)
|
| 816 |
+
seen.add(pool)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mps.py
ADDED
|
@@ -0,0 +1,1070 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This is not a feature-complete compiler backend
|
| 2 |
+
# Just an early prototype that shows that one can compile elementwise ops into a Metal shader
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import functools
|
| 6 |
+
import itertools
|
| 7 |
+
import logging
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any, Optional, TYPE_CHECKING
|
| 11 |
+
|
| 12 |
+
import sympy
|
| 13 |
+
from sympy.printing.precedence import PRECEDENCE
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
from torch.utils._cpp_embed_headers import _embed_headers
|
| 17 |
+
from torch.utils._ordered_set import OrderedSet
|
| 18 |
+
from torch.utils._sympy.printers import CppPrinter, ExprPrinter as ExprPrinter_
|
| 19 |
+
from torch.utils._sympy.value_ranges import ValueRanges
|
| 20 |
+
|
| 21 |
+
from ..utils import ceildiv, get_bounds_index_expr, get_kernel_metadata
|
| 22 |
+
from ..virtualized import ops, OpsWrapper, V
|
| 23 |
+
from .common import (
|
| 24 |
+
CSEVariable,
|
| 25 |
+
DeferredLine,
|
| 26 |
+
DTYPE_TO_COMPUTATION_DTYPE,
|
| 27 |
+
IndentedBuffer,
|
| 28 |
+
OpOverrides,
|
| 29 |
+
PythonPrinter,
|
| 30 |
+
)
|
| 31 |
+
from .simd import IterationRangesEntry, SIMDKernel, SIMDScheduling
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from typing import Union
|
| 36 |
+
|
| 37 |
+
from ..ops_handler import ReductionType, StoreMode
|
| 38 |
+
from ..scheduler import Scheduler, SchedulerNode
|
| 39 |
+
from .common import OpVarT
|
| 40 |
+
|
| 41 |
+
log = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
DTYPE_TO_METAL = {
|
| 44 |
+
torch.bool: "bool",
|
| 45 |
+
torch.int8: "char",
|
| 46 |
+
torch.int16: "short",
|
| 47 |
+
torch.int32: "int",
|
| 48 |
+
torch.int64: "long",
|
| 49 |
+
torch.uint8: "uchar",
|
| 50 |
+
torch.float: "float",
|
| 51 |
+
torch.half: "half",
|
| 52 |
+
torch.bfloat16: "bfloat",
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def value_to_metal(val: Union[float, int, bool, str, CSEVariable]) -> str:
|
| 57 |
+
if isinstance(val, float):
|
| 58 |
+
if val == torch.inf:
|
| 59 |
+
return "HUGE_VALF"
|
| 60 |
+
elif val == -torch.inf:
|
| 61 |
+
return "-HUGE_VALF"
|
| 62 |
+
elif val != val: # Only float that not equal to self is nan
|
| 63 |
+
return "NAN"
|
| 64 |
+
return str(val)
|
| 65 |
+
elif isinstance(val, bool):
|
| 66 |
+
return "true" if val else "false"
|
| 67 |
+
return str(val)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class MetalExprPrinter(ExprPrinter_):
|
| 71 |
+
"""Converts sympy expression to Metal code snippet"""
|
| 72 |
+
|
| 73 |
+
def _print_FloorDiv(self, expr: sympy.Expr) -> str:
|
| 74 |
+
x, div = expr.args
|
| 75 |
+
x = self.doprint(x)
|
| 76 |
+
div = self.doprint(div)
|
| 77 |
+
if expr.is_integer:
|
| 78 |
+
return f"c10::metal::floor_divide({x}, {div})"
|
| 79 |
+
return f"metal::floor({x}) / ({div})"
|
| 80 |
+
|
| 81 |
+
def _print_ModularIndexing(self, expr: sympy.Expr) -> str:
|
| 82 |
+
x, div, mod = expr.args
|
| 83 |
+
x = self.doprint(x)
|
| 84 |
+
if div != 1:
|
| 85 |
+
div = self.doprint(div)
|
| 86 |
+
if expr.is_integer:
|
| 87 |
+
x = f"({x}) / ({div})"
|
| 88 |
+
else:
|
| 89 |
+
x = f"metal::floor({x}) / ({div})"
|
| 90 |
+
mod = self.doprint(mod)
|
| 91 |
+
return f"({x}) % ({mod})"
|
| 92 |
+
|
| 93 |
+
def _print_Min(self, expr: sympy.Expr) -> str:
|
| 94 |
+
if len(expr.args) != 2:
|
| 95 |
+
raise RuntimeError("metal::min only supported for 2 args")
|
| 96 |
+
a, b = map(self._print, expr.args)
|
| 97 |
+
typecast_a = f"static_cast<decltype({a}+{b})>({a})"
|
| 98 |
+
typecast_b = f"static_cast<decltype({a}+{b})>({b})"
|
| 99 |
+
return f"metal::min({typecast_a}, {typecast_b})"
|
| 100 |
+
|
| 101 |
+
def _print_Max(self, expr: sympy.Expr) -> str:
|
| 102 |
+
if len(expr.args) != 2:
|
| 103 |
+
raise RuntimeError("metal::max only supported for 2 args")
|
| 104 |
+
a, b = map(self._print, expr.args)
|
| 105 |
+
typecast_a = f"static_cast<decltype({a}+{b})>({a})"
|
| 106 |
+
typecast_b = f"static_cast<decltype({a}+{b})>({b})"
|
| 107 |
+
return f"metal::max({typecast_a}, {typecast_b})"
|
| 108 |
+
|
| 109 |
+
def _print_Abs(self, expr: sympy.Expr) -> str:
|
| 110 |
+
assert len(expr.args) == 1
|
| 111 |
+
return f"metal::abs({self._print(expr.args[0])})"
|
| 112 |
+
|
| 113 |
+
def _print_RoundToInt(self, expr: sympy.Expr) -> str:
|
| 114 |
+
assert len(expr.args) == 1
|
| 115 |
+
return f"static_cast<long>(metal::rint({self._print(expr.args[0])}))"
|
| 116 |
+
|
| 117 |
+
def _print_RoundDecimal(self, expr: sympy.Expr) -> str:
|
| 118 |
+
assert len(expr.args) == 2
|
| 119 |
+
number, ndigits = expr.args
|
| 120 |
+
if number.is_integer:
|
| 121 |
+
# ndigits < 0 should have been filtered by the sympy function
|
| 122 |
+
assert ndigits < 0
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"For integer inputs, only non-negative ndigits are currently supported, but got {ndigits}."
|
| 125 |
+
)
|
| 126 |
+
number_str = self.parenthesize(number, PRECEDENCE["Mul"])
|
| 127 |
+
return f"static_cast<float>(metal::rint(1e{ndigits} * {number_str}) * 1e{-ndigits})"
|
| 128 |
+
|
| 129 |
+
def _print_IntTrueDiv(self, expr: sympy.Expr) -> str:
|
| 130 |
+
lhs, rhs = expr.args
|
| 131 |
+
# TODO: This is only accurate up to 2**23
|
| 132 |
+
return f"static_cast<float>({self._print(lhs)}) / static_cast<float>({self._print(rhs)})"
|
| 133 |
+
|
| 134 |
+
def _print_PowByNatural(self, expr: sympy.Expr) -> str:
|
| 135 |
+
assert len(expr.args) == 2
|
| 136 |
+
x, y = map(self.doprint, expr.args)
|
| 137 |
+
return f"metal::pow(static_cast<float>({x}), static_cast<float>({y}))"
|
| 138 |
+
|
| 139 |
+
def _print_ToFloat(self, expr: sympy.Expr) -> str:
|
| 140 |
+
assert len(expr.args) == 1
|
| 141 |
+
x = self.doprint(expr.args[0])
|
| 142 |
+
return f"static_cast<float>({x})"
|
| 143 |
+
|
| 144 |
+
def _print_FloorToInt(self, expr: sympy.Expr) -> str:
|
| 145 |
+
assert len(expr.args) == 1
|
| 146 |
+
x = self.doprint(expr.args[0])
|
| 147 |
+
return f"static_cast<int>(metal::floor(static_cast<float>({x})))"
|
| 148 |
+
|
| 149 |
+
_print_floor = _print_FloorToInt
|
| 150 |
+
|
| 151 |
+
def _print_TruncToInt(self, expr: sympy.Expr) -> str:
|
| 152 |
+
assert len(expr.args) == 1
|
| 153 |
+
x = self.doprint(expr.args[0])
|
| 154 |
+
return f"static_cast<int>(metal::trunc({x}))"
|
| 155 |
+
|
| 156 |
+
def _print_OpaqueUnaryFn_log2(self, expr: sympy.Expr) -> str:
|
| 157 |
+
assert len(expr.args) == 1
|
| 158 |
+
x = self.doprint(expr.args[0])
|
| 159 |
+
return f"metal::log2({x})"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class MetalOverrides(OpOverrides):
|
| 163 |
+
"""Implements Metal-specific overrides for ops. Base class emits Python-friendly overrides."""
|
| 164 |
+
|
| 165 |
+
@staticmethod
|
| 166 |
+
def to_dtype(
|
| 167 |
+
x: CSEVariable,
|
| 168 |
+
dtype: torch.dtype,
|
| 169 |
+
src_dtype: Optional[torch.dtype] = None,
|
| 170 |
+
use_compute_types: bool = True,
|
| 171 |
+
) -> str:
|
| 172 |
+
if dtype == torch.double:
|
| 173 |
+
log.warning(
|
| 174 |
+
"float64 cast requested, probably from tensorify_python_scalars"
|
| 175 |
+
)
|
| 176 |
+
return f"static_cast<float>({x})"
|
| 177 |
+
return f"static_cast<{DTYPE_TO_METAL[dtype]}>({x})"
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def to_dtype_bitcast(
|
| 181 |
+
x: CSEVariable, dtype: torch.dtype, src_dtype: torch.dtype
|
| 182 |
+
) -> str:
|
| 183 |
+
return f"as_type<{DTYPE_TO_METAL[dtype]}>(static_cast<{DTYPE_TO_METAL[src_dtype]}>({x}))"
|
| 184 |
+
|
| 185 |
+
@staticmethod
|
| 186 |
+
def constant(val: Union[bool, float, int], dtype: torch.dtype) -> str:
|
| 187 |
+
return value_to_metal(val)
|
| 188 |
+
|
| 189 |
+
@staticmethod
|
| 190 |
+
def index_expr(expr: sympy.Expr, dtype: torch.dtype) -> str:
|
| 191 |
+
idx_str = V.kernel.index_to_str(V.kernel.prepare_indexing(expr))
|
| 192 |
+
var = V.kernel.cse.generate(
|
| 193 |
+
V.kernel.compute, idx_str, bounds=get_bounds_index_expr(expr)
|
| 194 |
+
)
|
| 195 |
+
return ops.to_dtype(var, dtype)
|
| 196 |
+
|
| 197 |
+
@staticmethod
|
| 198 |
+
def masked(mask: CSEVariable, body: sympy.Expr, other: CSEVariable) -> str:
|
| 199 |
+
# TODO: Type annotation for other is wrong, it's often float or int
|
| 200 |
+
with V.kernel.mask_loads(mask, other) as new_mask:
|
| 201 |
+
result = body()
|
| 202 |
+
|
| 203 |
+
if result.bounds.is_bool:
|
| 204 |
+
other = bool(other) # type: ignore[assignment]
|
| 205 |
+
|
| 206 |
+
return ops.where(new_mask, result, other)
|
| 207 |
+
|
| 208 |
+
@staticmethod
|
| 209 |
+
def where(a: OpVarT, b: OpVarT, c: OpVarT) -> str:
|
| 210 |
+
return f"{a} ? {b} : {value_to_metal(c)}"
|
| 211 |
+
|
| 212 |
+
@staticmethod
|
| 213 |
+
def remainder(a: OpVarT, b: OpVarT) -> str:
|
| 214 |
+
return f"c10::metal::remainder({a}, {b})"
|
| 215 |
+
|
| 216 |
+
@staticmethod
|
| 217 |
+
def maximum(a: CSEVariable, b: CSEVariable) -> str:
|
| 218 |
+
typecast_a = f"static_cast<decltype({a}+{b})>({a})"
|
| 219 |
+
typecast_b = f"static_cast<decltype({a}+{b})>({b})"
|
| 220 |
+
return f"c10::metal::max({typecast_a}, {typecast_b})"
|
| 221 |
+
|
| 222 |
+
@staticmethod
|
| 223 |
+
def minimum(a: CSEVariable, b: CSEVariable) -> str:
|
| 224 |
+
typecast_a = f"static_cast<decltype({a}+{b})>({a})"
|
| 225 |
+
typecast_b = f"static_cast<decltype({a}+{b})>({b})"
|
| 226 |
+
return f"c10::metal::min({typecast_a}, {typecast_b})"
|
| 227 |
+
|
| 228 |
+
@staticmethod
|
| 229 |
+
def logical_or(a: CSEVariable, b: CSEVariable) -> str:
|
| 230 |
+
return f"{a} || {b}"
|
| 231 |
+
|
| 232 |
+
@staticmethod
|
| 233 |
+
def logical_and(a: CSEVariable, b: CSEVariable) -> str:
|
| 234 |
+
return f"{a} && {b}"
|
| 235 |
+
|
| 236 |
+
@staticmethod
|
| 237 |
+
def isnan(x: CSEVariable) -> str:
|
| 238 |
+
return f"metal::isnan({x})"
|
| 239 |
+
|
| 240 |
+
@staticmethod
|
| 241 |
+
def isinf(x: CSEVariable) -> str:
|
| 242 |
+
return f"metal::isinf({x})"
|
| 243 |
+
|
| 244 |
+
@staticmethod
|
| 245 |
+
def log(x: CSEVariable) -> str:
|
| 246 |
+
return f"metal::log({x})"
|
| 247 |
+
|
| 248 |
+
@staticmethod
|
| 249 |
+
def exp(x: CSEVariable) -> str:
|
| 250 |
+
return f"metal::exp({x})"
|
| 251 |
+
|
| 252 |
+
@staticmethod
|
| 253 |
+
def abs(x: CSEVariable) -> str:
|
| 254 |
+
return f"metal::abs({x})"
|
| 255 |
+
|
| 256 |
+
@staticmethod
|
| 257 |
+
def signbit(x: CSEVariable) -> str:
|
| 258 |
+
return f"metal::signbit({x})"
|
| 259 |
+
|
| 260 |
+
@staticmethod
|
| 261 |
+
def sin(x: CSEVariable) -> str:
|
| 262 |
+
return f"metal::precise::sin({x})"
|
| 263 |
+
|
| 264 |
+
@staticmethod
|
| 265 |
+
def sinc(x: CSEVariable) -> str:
|
| 266 |
+
return f"c10::metal::sinc({x})"
|
| 267 |
+
|
| 268 |
+
@staticmethod
|
| 269 |
+
def cos(x: CSEVariable) -> str:
|
| 270 |
+
return f"metal::precise::cos({x})"
|
| 271 |
+
|
| 272 |
+
@staticmethod
|
| 273 |
+
def tan(x: CSEVariable) -> str:
|
| 274 |
+
return f"metal::tan({x})"
|
| 275 |
+
|
| 276 |
+
@staticmethod
|
| 277 |
+
def asin(x: CSEVariable) -> str:
|
| 278 |
+
return f"metal::asin({x})"
|
| 279 |
+
|
| 280 |
+
@staticmethod
|
| 281 |
+
def acos(x: CSEVariable) -> str:
|
| 282 |
+
return f"metal::acos({x})"
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def atan(x: CSEVariable) -> str:
|
| 286 |
+
return f"metal::atan({x})"
|
| 287 |
+
|
| 288 |
+
@staticmethod
|
| 289 |
+
def atan2(x: CSEVariable, y: CSEVariable) -> str:
|
| 290 |
+
return f"::metal::atan2({x}, {y})"
|
| 291 |
+
|
| 292 |
+
@staticmethod
|
| 293 |
+
def sqrt(x: CSEVariable) -> str:
|
| 294 |
+
return f"metal::sqrt({x})"
|
| 295 |
+
|
| 296 |
+
@staticmethod
|
| 297 |
+
def neg(x: CSEVariable) -> str:
|
| 298 |
+
# TODO: Does it rely on undefined behavior?
|
| 299 |
+
# If so, add special logic for unsigned types
|
| 300 |
+
return f"static_cast<decltype({x})>(-{x})"
|
| 301 |
+
|
| 302 |
+
@staticmethod
|
| 303 |
+
def rsqrt(x: CSEVariable) -> str:
|
| 304 |
+
return f"metal::rsqrt({x})"
|
| 305 |
+
|
| 306 |
+
@staticmethod
|
| 307 |
+
def tanh(x: CSEVariable) -> str:
|
| 308 |
+
return f"metal::tanh({x})"
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def atanh(x: CSEVariable) -> str:
|
| 312 |
+
return f"metal::atanh({x})"
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def floordiv(a: CSEVariable, b: CSEVariable) -> str:
|
| 316 |
+
# a and b must be of integer type
|
| 317 |
+
return f"c10::metal::floor_divide({a}, {b})"
|
| 318 |
+
|
| 319 |
+
@staticmethod
|
| 320 |
+
def floor(x: CSEVariable) -> str:
|
| 321 |
+
return f"metal::floor({x})"
|
| 322 |
+
|
| 323 |
+
@staticmethod
|
| 324 |
+
def sign(x: CSEVariable) -> str:
|
| 325 |
+
return f"metal::sign({x})"
|
| 326 |
+
|
| 327 |
+
@staticmethod
|
| 328 |
+
def fmod(a: CSEVariable, b: CSEVariable) -> str:
|
| 329 |
+
typecast_a = f"static_cast<decltype({a}+{b})>({a})"
|
| 330 |
+
typecast_b = f"static_cast<decltype({a}+{b})>({b})"
|
| 331 |
+
return f"metal::fmod({typecast_a}, {typecast_b})"
|
| 332 |
+
|
| 333 |
+
@staticmethod
|
| 334 |
+
def trunc(x: CSEVariable) -> str:
|
| 335 |
+
return f"metal::trunc({x})"
|
| 336 |
+
|
| 337 |
+
@staticmethod
|
| 338 |
+
def truncdiv(a: CSEVariable, b: CSEVariable) -> str:
|
| 339 |
+
quot = f"{a} / {b}"
|
| 340 |
+
if (a.dtype is not None and a.dtype.is_floating_point) or (
|
| 341 |
+
b.dtype is not None and b.dtype.is_floating_point
|
| 342 |
+
):
|
| 343 |
+
return f"metal::trunc({quot})"
|
| 344 |
+
return quot
|
| 345 |
+
|
| 346 |
+
@staticmethod
|
| 347 |
+
def ceil(x: CSEVariable) -> str:
|
| 348 |
+
return f"metal::ceil({x})"
|
| 349 |
+
|
| 350 |
+
@staticmethod
|
| 351 |
+
def rand(seed: CSEVariable, offset: CSEVariable) -> str:
|
| 352 |
+
V.kernel.headers.add("random")
|
| 353 |
+
return f"c10::metal::rand({seed}, {offset})"
|
| 354 |
+
|
| 355 |
+
@staticmethod
|
| 356 |
+
def randn(seed: CSEVariable, offset: CSEVariable) -> str:
|
| 357 |
+
V.kernel.headers.add("random")
|
| 358 |
+
return f"c10::metal::randn({seed}, {offset})"
|
| 359 |
+
|
| 360 |
+
@staticmethod
|
| 361 |
+
def randint64(
|
| 362 |
+
seed: CSEVariable, offset: CSEVariable, low: CSEVariable, high: CSEVariable
|
| 363 |
+
) -> str:
|
| 364 |
+
V.kernel.headers.add("random")
|
| 365 |
+
return f"c10::metal::randint64({seed}, {offset}, {low}, {high})"
|
| 366 |
+
|
| 367 |
+
@staticmethod
|
| 368 |
+
def round(x: CSEVariable) -> str:
|
| 369 |
+
return f"metal::rint({x})"
|
| 370 |
+
|
| 371 |
+
@staticmethod
|
| 372 |
+
def pow(a: CSEVariable, b: CSEVariable) -> str:
|
| 373 |
+
cast_a = f"static_cast<decltype({a}+{b})>({a})"
|
| 374 |
+
cast_b = f"static_cast<decltype({a}+{b})>({b})"
|
| 375 |
+
return f"metal::pow({cast_a}, {cast_b})"
|
| 376 |
+
|
| 377 |
+
def _special_unary(self, a: CSEVariable, name: str) -> str:
|
| 378 |
+
V.kernel.headers.add("special_math")
|
| 379 |
+
return f"c10::metal::{name}({a})"
|
| 380 |
+
|
| 381 |
+
def _special_binary(self, a: CSEVariable, b: CSEVariable, name: str) -> str:
|
| 382 |
+
V.kernel.headers.add("special_math")
|
| 383 |
+
return f"c10::metal::{name}({a}, {b})"
|
| 384 |
+
|
| 385 |
+
@classmethod
|
| 386 |
+
def _initialize_special_ops(cls) -> None:
|
| 387 |
+
# Unary special ops
|
| 388 |
+
for name in [
|
| 389 |
+
"erf",
|
| 390 |
+
"erfinv",
|
| 391 |
+
"i0",
|
| 392 |
+
"i0e",
|
| 393 |
+
"i1",
|
| 394 |
+
"i1e",
|
| 395 |
+
"digamma",
|
| 396 |
+
"spherical_bessel_j0",
|
| 397 |
+
]:
|
| 398 |
+
setattr(cls, name, functools.partialmethod(cls._special_unary, name=name))
|
| 399 |
+
|
| 400 |
+
cls.lgamma = functools.partialmethod(cls._special_unary, name="log_gamma") # type: ignore[assignment]
|
| 401 |
+
|
| 402 |
+
# Unary special ops with forward in method name
|
| 403 |
+
for name in [
|
| 404 |
+
"bessel_j0",
|
| 405 |
+
"bessel_j1",
|
| 406 |
+
"bessel_y0",
|
| 407 |
+
"bessel_y1",
|
| 408 |
+
"modified_bessel_i0",
|
| 409 |
+
"modified_bessel_i1",
|
| 410 |
+
"modified_bessel_k0",
|
| 411 |
+
"modified_bessel_k1",
|
| 412 |
+
"scaled_modified_bessel_k0",
|
| 413 |
+
"scaled_modified_bessel_k1",
|
| 414 |
+
]:
|
| 415 |
+
setattr(
|
| 416 |
+
cls,
|
| 417 |
+
name,
|
| 418 |
+
functools.partialmethod(cls._special_unary, name=name + "_forward"),
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
# Binary special ops
|
| 422 |
+
for name in [
|
| 423 |
+
"polygamma",
|
| 424 |
+
"igamma",
|
| 425 |
+
"igammac",
|
| 426 |
+
"zeta",
|
| 427 |
+
]:
|
| 428 |
+
setattr(cls, name, functools.partialmethod(cls._special_binary, name=name))
|
| 429 |
+
|
| 430 |
+
# Binary special ops with forward in method name
|
| 431 |
+
for name in [
|
| 432 |
+
"chebyshev_polynomial_t",
|
| 433 |
+
"chebyshev_polynomial_u",
|
| 434 |
+
"chebyshev_polynomial_v",
|
| 435 |
+
"chebyshev_polynomial_w",
|
| 436 |
+
"hermite_polynomial_h",
|
| 437 |
+
"hermite_polynomial_he",
|
| 438 |
+
"shifted_chebyshev_polynomial_t",
|
| 439 |
+
"shifted_chebyshev_polynomial_u",
|
| 440 |
+
"shifted_chebyshev_polynomial_v",
|
| 441 |
+
"shifted_chebyshev_polynomial_w",
|
| 442 |
+
]:
|
| 443 |
+
setattr(
|
| 444 |
+
cls,
|
| 445 |
+
name,
|
| 446 |
+
functools.partialmethod(cls._special_binary, name=name + "_forward"),
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
MetalOverrides._initialize_pointwise_overrides("mps")
|
| 451 |
+
MetalOverrides._initialize_special_ops()
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class MetalKernel(SIMDKernel):
|
| 455 |
+
"""Implement Metal codegen based on the SIMDKernel abstraction"""
|
| 456 |
+
|
| 457 |
+
overrides = MetalOverrides # type: ignore[assignment]
|
| 458 |
+
suffix = ";"
|
| 459 |
+
newvar_prefix = "auto "
|
| 460 |
+
max_threadgroup_size = 1024
|
| 461 |
+
simd_group_size = 32
|
| 462 |
+
pexpr = PythonPrinter().doprint
|
| 463 |
+
cexpr = CppPrinter().doprint
|
| 464 |
+
sexpr = MetalExprPrinter().doprint
|
| 465 |
+
kexpr = sexpr
|
| 466 |
+
headers: OrderedSet[str] = OrderedSet(["utils"])
|
| 467 |
+
multistage_reduction_entry: list[IterationRangesEntry] = []
|
| 468 |
+
|
| 469 |
+
def __init__(
|
| 470 |
+
self,
|
| 471 |
+
tiling: dict[str, sympy.Expr],
|
| 472 |
+
**kwargs: Any,
|
| 473 |
+
) -> None:
|
| 474 |
+
super().__init__(tiling, **kwargs)
|
| 475 |
+
self.acc_var_ids = itertools.count()
|
| 476 |
+
|
| 477 |
+
def dtype_to_str(self, dtype: torch.dtype) -> str:
|
| 478 |
+
return DTYPE_TO_METAL[dtype]
|
| 479 |
+
|
| 480 |
+
def load(self, name: str, index: sympy.Expr) -> CSEVariable:
|
| 481 |
+
"""Codegen a load from an InputBuffer"""
|
| 482 |
+
var = self.args.input(name)
|
| 483 |
+
index = self.prepare_indexing(index)
|
| 484 |
+
dtype = V.graph.get_dtype(name)
|
| 485 |
+
line = f"{var}[{self.index_to_str(index)}]"
|
| 486 |
+
if dtype in [torch.float16, torch.bfloat16]:
|
| 487 |
+
# TODO(NS): Figure out the right balance between optype casts
|
| 488 |
+
# op_math_t for half-precision floats should be float32
|
| 489 |
+
# Otherwise it can lead to a correctness issues with eager
|
| 490 |
+
line = f"static_cast<float>({line})"
|
| 491 |
+
dtype = torch.float32
|
| 492 |
+
return self.cse.generate(self.loads, line, dtype=dtype)
|
| 493 |
+
|
| 494 |
+
def store(
|
| 495 |
+
self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None
|
| 496 |
+
) -> None:
|
| 497 |
+
var = self.args.output(name)
|
| 498 |
+
index = self.prepare_indexing(index)
|
| 499 |
+
dtype_str = self.dtype_to_str(V.graph.get_dtype(name))
|
| 500 |
+
cast_val = f"static_cast<{dtype_str}>({value})"
|
| 501 |
+
if mode is None:
|
| 502 |
+
line = f"{var}[{self.index_to_str(index)}] = {cast_val};"
|
| 503 |
+
elif mode == "atomic_add":
|
| 504 |
+
self.headers.add("atomic")
|
| 505 |
+
atomic_type = f"c10::metal::AtomicType<{dtype_str}>"
|
| 506 |
+
cast_var = f"reinterpret_cast<device {atomic_type}::type *>({var})"
|
| 507 |
+
line = f"{atomic_type}::atomic_add({cast_var}, {self.index_to_str(index)}, {cast_val});"
|
| 508 |
+
else:
|
| 509 |
+
raise RuntimeError(f"Unimplemented store mode {mode}")
|
| 510 |
+
if self.inside_reduction:
|
| 511 |
+
self.compute.writeline(DeferredLine(name, line))
|
| 512 |
+
else:
|
| 513 |
+
self.stores.writeline(DeferredLine(name, line))
|
| 514 |
+
|
| 515 |
+
def store_reduction(self, name: str, index: sympy.Expr, value: CSEVariable) -> None:
|
| 516 |
+
var = self.args.output(name)
|
| 517 |
+
index = self.prepare_indexing(index)
|
| 518 |
+
dtype_str = self.dtype_to_str(V.graph.get_dtype(name))
|
| 519 |
+
reduction_dim = next(t for t in self.range_trees if t.is_reduction)
|
| 520 |
+
# Only one thread in the reduction group needs to store the results
|
| 521 |
+
line = f"{var}[{self.index_to_str(index)}] = static_cast<{dtype_str}>({value});"
|
| 522 |
+
line = f"if ({reduction_dim.name} == 0) {line}"
|
| 523 |
+
self.stores.writeline(DeferredLine(name, line))
|
| 524 |
+
|
| 525 |
+
def _new_idxvar(
|
| 526 |
+
self,
|
| 527 |
+
dtype: Union[str | torch.dtype],
|
| 528 |
+
elem_count: Optional[int] = None,
|
| 529 |
+
default_value: Optional[Any] = None,
|
| 530 |
+
is_threadgroup: bool = True,
|
| 531 |
+
bounds: ValueRanges[Any] = ValueRanges.unknown(),
|
| 532 |
+
) -> CSEVariable:
|
| 533 |
+
if isinstance(dtype, torch.dtype):
|
| 534 |
+
dtype = self.dtype_to_str(dtype)
|
| 535 |
+
var_name = f"tmp_acc_{next(self.acc_var_ids)}"
|
| 536 |
+
var = V.kernel.create_cse_var(var_name, bounds, dtype)
|
| 537 |
+
var_def = "threadgroup " if is_threadgroup else ""
|
| 538 |
+
var_def += f"{dtype} {var_name}"
|
| 539 |
+
if elem_count:
|
| 540 |
+
var_def += f"[{self.sexpr(elem_count)}]"
|
| 541 |
+
if default_value is not None:
|
| 542 |
+
assert not is_threadgroup, "Thread group var can not have default value"
|
| 543 |
+
var_def += f" = {default_value}"
|
| 544 |
+
self.indexing_code.writeline(var_def + self.suffix)
|
| 545 |
+
return var
|
| 546 |
+
|
| 547 |
+
def reduction(
|
| 548 |
+
self,
|
| 549 |
+
dtype: torch.dtype,
|
| 550 |
+
src_dtype: torch.dtype,
|
| 551 |
+
reduction_type: ReductionType,
|
| 552 |
+
value: Union[CSEVariable, tuple[CSEVariable, ...]],
|
| 553 |
+
) -> Union[CSEVariable, tuple[CSEVariable, ...]]:
|
| 554 |
+
"Caching wrapper around _reduction_nocache"
|
| 555 |
+
cache_key = (src_dtype, reduction_type, value)
|
| 556 |
+
# Return cached reduction
|
| 557 |
+
if cache_key in self.cse.reduction_cache:
|
| 558 |
+
return self.cse.reduction_cache[cache_key]
|
| 559 |
+
result = self._reduction_nocache(dtype, src_dtype, reduction_type, value)
|
| 560 |
+
self.cse.reduction_cache[cache_key] = result # type: ignore[assignment]
|
| 561 |
+
return result
|
| 562 |
+
|
| 563 |
+
def _reduction_nocache(
|
| 564 |
+
self,
|
| 565 |
+
dtype: torch.dtype,
|
| 566 |
+
src_dtype: torch.dtype,
|
| 567 |
+
reduction_type: ReductionType,
|
| 568 |
+
value: Union[CSEVariable, tuple[CSEVariable, ...]],
|
| 569 |
+
) -> Union[CSEVariable, tuple[CSEVariable, ...]]:
|
| 570 |
+
"""Codegen a reduction operation.
|
| 571 |
+
Only sum and prod operations are somewhat reasonable optimized"""
|
| 572 |
+
assert self.inside_reduction
|
| 573 |
+
assert not self._load_mask
|
| 574 |
+
|
| 575 |
+
def _unwrap_helper(res3: CSEVariable) -> tuple[CSEVariable, ...]:
|
| 576 |
+
# Uwraps vec3 dtype into individual components
|
| 577 |
+
return OpsWrapper._unwrap(
|
| 578 |
+
[CSEVariable(f"{res3}.{t}", res3.bounds, res3.dtype) for t in "xyz"]
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
# Establish reduction buffer size and index expression
|
| 582 |
+
reduction_idx = ""
|
| 583 |
+
acc_buf_size = 1
|
| 584 |
+
for rd in self.range_trees:
|
| 585 |
+
if not rd.is_reduction:
|
| 586 |
+
continue
|
| 587 |
+
if reduction_idx:
|
| 588 |
+
reduction_idx += " + "
|
| 589 |
+
reduction_idx += f"{rd.name} * {acc_buf_size}"
|
| 590 |
+
|
| 591 |
+
if isinstance(rd.numel, sympy.Integer):
|
| 592 |
+
acc_buf_size *= rd.numel
|
| 593 |
+
else:
|
| 594 |
+
acc_buf_size *= sympy.Symbol(
|
| 595 |
+
f"{rd.prefix}numel", integer=True, positive=True
|
| 596 |
+
)
|
| 597 |
+
|
| 598 |
+
acc_buf_size = sympy.Min(acc_buf_size, self.max_threadgroup_size)
|
| 599 |
+
acc_buf_size_str = self.sexpr(acc_buf_size)
|
| 600 |
+
shmem_buf_size = (
|
| 601 |
+
ceildiv(acc_buf_size, self.simd_group_size)
|
| 602 |
+
if isinstance(acc_buf_size, sympy.Integer)
|
| 603 |
+
else self.simd_group_size
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
if reduction_type == "any":
|
| 607 |
+
acc = self._new_idxvar(dtype)
|
| 608 |
+
self.indexing_code.writeline(f"{acc} = false;")
|
| 609 |
+
self.indexing_code.writeline(
|
| 610 |
+
"threadgroup_barrier(metal::mem_flags::mem_threadgroup);"
|
| 611 |
+
)
|
| 612 |
+
self.compute.splice(
|
| 613 |
+
f"""
|
| 614 |
+
if ({value}) {{
|
| 615 |
+
{acc} = true;
|
| 616 |
+
}}
|
| 617 |
+
"""
|
| 618 |
+
)
|
| 619 |
+
self.stores.writeline(
|
| 620 |
+
"threadgroup_barrier(metal::mem_flags::mem_threadgroup);"
|
| 621 |
+
)
|
| 622 |
+
return acc
|
| 623 |
+
|
| 624 |
+
self.headers.add("reduction_utils")
|
| 625 |
+
|
| 626 |
+
if reduction_type in ["prod", "sum"]:
|
| 627 |
+
acc_dtype = DTYPE_TO_COMPUTATION_DTYPE[src_dtype]
|
| 628 |
+
acc_buf = self._new_idxvar(acc_dtype, shmem_buf_size)
|
| 629 |
+
if not self.multistage_reduction_entry:
|
| 630 |
+
val = value
|
| 631 |
+
else:
|
| 632 |
+
default_val, reduction_op = (
|
| 633 |
+
(0, "+") if reduction_type == "sum" else (1, "*")
|
| 634 |
+
)
|
| 635 |
+
val = self._new_idxvar(
|
| 636 |
+
acc_dtype, default_value=default_val, is_threadgroup=False
|
| 637 |
+
)
|
| 638 |
+
self.compute.splice(f"{val} {reduction_op}= {value};")
|
| 639 |
+
|
| 640 |
+
return self.cse.generate(
|
| 641 |
+
self.stores,
|
| 642 |
+
f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {val}, {reduction_idx}, {acc_buf_size_str})",
|
| 643 |
+
dtype=DTYPE_TO_COMPUTATION_DTYPE[dtype],
|
| 644 |
+
)
|
| 645 |
+
if reduction_type in ["max", "min"]:
|
| 646 |
+
acc_buf = self._new_idxvar(src_dtype, shmem_buf_size)
|
| 647 |
+
src_metal_type = DTYPE_TO_METAL[src_dtype]
|
| 648 |
+
cast_value = f"static_cast<{src_metal_type}>({value})"
|
| 649 |
+
if not self.multistage_reduction_entry:
|
| 650 |
+
val = cast_value # type: ignore[assignment]
|
| 651 |
+
else:
|
| 652 |
+
lim_fn = "lowest" if reduction_type.endswith("max") else "max"
|
| 653 |
+
limit_val = f"::metal::numeric_limits<{src_metal_type}>::{lim_fn}()"
|
| 654 |
+
val = self._new_idxvar(
|
| 655 |
+
src_dtype, default_value=limit_val, is_threadgroup=False
|
| 656 |
+
)
|
| 657 |
+
self.compute.splice(
|
| 658 |
+
f"{val} = ::c10::metal::{reduction_type}({val}, {cast_value});"
|
| 659 |
+
)
|
| 660 |
+
return self.cse.generate(
|
| 661 |
+
self.stores,
|
| 662 |
+
f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {val}, {reduction_idx}, {acc_buf_size_str})",
|
| 663 |
+
dtype=DTYPE_TO_COMPUTATION_DTYPE[dtype],
|
| 664 |
+
)
|
| 665 |
+
if reduction_type in ["argmin", "argmax"]:
|
| 666 |
+
data_acc_buf = self._new_idxvar(src_dtype, shmem_buf_size)
|
| 667 |
+
idx_acc_buf = self._new_idxvar(dtype, shmem_buf_size)
|
| 668 |
+
src_metal_type = DTYPE_TO_METAL[src_dtype]
|
| 669 |
+
cast_value = f"static_cast<{src_metal_type}>({value})"
|
| 670 |
+
if not self.multistage_reduction_entry:
|
| 671 |
+
val = cast_value # type: ignore[assignment]
|
| 672 |
+
idx_val = f"static_cast<{DTYPE_TO_METAL[dtype]}>({reduction_idx})"
|
| 673 |
+
else:
|
| 674 |
+
lim_fn = "lowest" if reduction_type.endswith("max") else "max"
|
| 675 |
+
limit_val = f"::metal::numeric_limits<{src_metal_type}>::{lim_fn}()"
|
| 676 |
+
val = self._new_idxvar(
|
| 677 |
+
src_dtype, default_value=limit_val, is_threadgroup=False
|
| 678 |
+
)
|
| 679 |
+
idx_val = self._new_idxvar(dtype, default_value=0, is_threadgroup=False) # type: ignore[assignment]
|
| 680 |
+
idx_var = next(
|
| 681 |
+
t for t in self.range_tree_nodes.values() if t.is_reduction
|
| 682 |
+
)
|
| 683 |
+
cmp_op = ">" if reduction_type == "argmax" else "<"
|
| 684 |
+
nan_suffix = (
|
| 685 |
+
f" || ::metal::isnan({value}) "
|
| 686 |
+
if src_dtype.is_floating_point
|
| 687 |
+
else ""
|
| 688 |
+
)
|
| 689 |
+
self.compute.splice(f"""
|
| 690 |
+
if ({value} {cmp_op} {val}{nan_suffix}) {{
|
| 691 |
+
{val} = {value};
|
| 692 |
+
{idx_val} = {idx_var.name};
|
| 693 |
+
}}
|
| 694 |
+
""")
|
| 695 |
+
return self.cse.generate(
|
| 696 |
+
self.stores,
|
| 697 |
+
f"c10::metal::threadgroup_{reduction_type}({data_acc_buf}, {idx_acc_buf}, "
|
| 698 |
+
f"{val}, {idx_val}, {reduction_idx}, {acc_buf_size_str})",
|
| 699 |
+
dtype=dtype,
|
| 700 |
+
)
|
| 701 |
+
if reduction_type == "welford_reduce":
|
| 702 |
+
if not self.multistage_reduction_entry:
|
| 703 |
+
acc_buf = self._new_idxvar(src_dtype, acc_buf_size)
|
| 704 |
+
self.compute.splice(f"{acc_buf}[{reduction_idx}] = {value};")
|
| 705 |
+
wf_res = self.cse.generate(
|
| 706 |
+
self.compute,
|
| 707 |
+
f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {acc_buf_size_str})",
|
| 708 |
+
dtype=torch.float32,
|
| 709 |
+
)
|
| 710 |
+
return _unwrap_helper(wf_res)
|
| 711 |
+
acc_buf = self._new_idxvar("float3", acc_buf_size)
|
| 712 |
+
acc_thread_var = f"{acc_buf}[{reduction_idx}]"
|
| 713 |
+
self.indexing_code.splice(f"{acc_thread_var} = 0.0;")
|
| 714 |
+
self.compute.writeline(
|
| 715 |
+
f"{acc_thread_var} = ::c10::metal::welford_combine({acc_thread_var}, float3({value}, 0.0, 1.0));"
|
| 716 |
+
)
|
| 717 |
+
wf_res = self.cse.generate(
|
| 718 |
+
self.stores,
|
| 719 |
+
f"c10::metal::threadgroup_welford_combine({acc_buf}, {acc_buf_size})",
|
| 720 |
+
dtype=torch.float32,
|
| 721 |
+
)
|
| 722 |
+
return _unwrap_helper(wf_res)
|
| 723 |
+
if reduction_type == "welford_combine":
|
| 724 |
+
assert isinstance(value, tuple), "Input to welford combine must be tuple"
|
| 725 |
+
acc_buf = self._new_idxvar("float3", acc_buf_size)
|
| 726 |
+
acc_thread_var = f"{acc_buf}[{reduction_idx}]"
|
| 727 |
+
inp_value = f"float3({value[0]}, {value[1]}, {value[2]})"
|
| 728 |
+
self.indexing_code.splice(f"{acc_thread_var} = 0.0;")
|
| 729 |
+
if self.multistage_reduction_entry:
|
| 730 |
+
self.indexing_code.splice(f"{acc_thread_var} = 0.0;")
|
| 731 |
+
self.compute.writeline(
|
| 732 |
+
f"{acc_thread_var} = ::c10::metal::welford_combine({acc_thread_var}, {inp_value});"
|
| 733 |
+
)
|
| 734 |
+
else:
|
| 735 |
+
self.compute.writeline(f"{acc_thread_var} = {inp_value};")
|
| 736 |
+
wf_res = self.cse.generate(
|
| 737 |
+
self.stores if self.multistage_reduction_entry else self.compute,
|
| 738 |
+
f"c10::metal::threadgroup_{reduction_type}({acc_buf}, {acc_buf_size_str})",
|
| 739 |
+
dtype=torch.float32,
|
| 740 |
+
)
|
| 741 |
+
return _unwrap_helper(wf_res)
|
| 742 |
+
raise NotImplementedError(reduction_type)
|
| 743 |
+
|
| 744 |
+
def codegen_iteration_ranges_entry(self, entry: IterationRangesEntry) -> None:
|
| 745 |
+
index_expr = self.rename_indexing(entry.expr)
|
| 746 |
+
index_str = self.sexpr(index_expr) # type: ignore[misc]
|
| 747 |
+
|
| 748 |
+
if not entry.is_reduction or (
|
| 749 |
+
isinstance(entry.root.numel, sympy.Integer)
|
| 750 |
+
and entry.root.numel <= self.max_threadgroup_size
|
| 751 |
+
):
|
| 752 |
+
self.indexing_code.writeline(
|
| 753 |
+
f"{self.index_dtype} {entry.name} = {index_str};"
|
| 754 |
+
)
|
| 755 |
+
return
|
| 756 |
+
|
| 757 |
+
acc_size = (
|
| 758 |
+
entry.root.numel
|
| 759 |
+
if isinstance(entry.root.numel, sympy.Integer)
|
| 760 |
+
else sympy.Symbol(f"{entry.root.prefix}numel", integer=True, positive=True)
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
self.multistage_reduction_entry.append(entry)
|
| 764 |
+
# When reducing the tensor whose size exceeds max threadgroup size
|
| 765 |
+
# loop over extra indices per reduction thread and perform part of the operation
|
| 766 |
+
# using values in the shared memory
|
| 767 |
+
|
| 768 |
+
# Use floats so that it doesn't do integer division
|
| 769 |
+
loop_size = (acc_size + float(self.max_threadgroup_size - 1)) // float(
|
| 770 |
+
self.max_threadgroup_size
|
| 771 |
+
)
|
| 772 |
+
loop_size_str = self.sexpr(loop_size)
|
| 773 |
+
|
| 774 |
+
self.body.writeline(
|
| 775 |
+
f"for(auto {entry.name}_cnt = 0; {entry.name}_cnt < {loop_size_str}; ++{entry.name}_cnt) {{"
|
| 776 |
+
)
|
| 777 |
+
with self.body.indent():
|
| 778 |
+
if isinstance(acc_size, sympy.Symbol):
|
| 779 |
+
self.body.writeline(
|
| 780 |
+
f"{self.index_dtype} {entry.name} = {self.max_threadgroup_size} * {entry.name}_cnt + {index_str};"
|
| 781 |
+
)
|
| 782 |
+
else:
|
| 783 |
+
self.body.writeline(
|
| 784 |
+
f"{self.index_dtype} {entry.name} = {loop_size_str} * {index_str} + {entry.name}_cnt;"
|
| 785 |
+
)
|
| 786 |
+
|
| 787 |
+
# Check that reduction is performed only within tensor boundary
|
| 788 |
+
if (
|
| 789 |
+
isinstance(acc_size, sympy.Symbol)
|
| 790 |
+
or loop_size * self.max_threadgroup_size != acc_size
|
| 791 |
+
):
|
| 792 |
+
self.body.writeline(f"if ({entry.name} >= {acc_size}) break;")
|
| 793 |
+
|
| 794 |
+
def codegen_body(self) -> None:
|
| 795 |
+
"""
|
| 796 |
+
Concat output code from index_code, loads, compute, stores,
|
| 797 |
+
suffix into self.body.
|
| 798 |
+
|
| 799 |
+
For pointwise kernels, this is called just once at the end.
|
| 800 |
+
|
| 801 |
+
For reduction kernels, this generates a loop over the reduction
|
| 802 |
+
axis.
|
| 803 |
+
"""
|
| 804 |
+
if self.multistage_reduction_entry:
|
| 805 |
+
with self.body.indent():
|
| 806 |
+
self.body.splice(self.loads)
|
| 807 |
+
self.body.splice(self.compute)
|
| 808 |
+
self.body.writeline("}" * len(self.multistage_reduction_entry))
|
| 809 |
+
# Invalidate variables instantiated inside loop
|
| 810 |
+
# But results of reduction alive. Reduction cache values can be
|
| 811 |
+
# either CSEVariable or tuple of CSEVariables, in which case all
|
| 812 |
+
# variables in the tuple must be preserved
|
| 813 |
+
self.cse.invalidate(
|
| 814 |
+
OrderedSet(
|
| 815 |
+
v
|
| 816 |
+
for item in self.cse.reduction_cache.values()
|
| 817 |
+
for v in (item if isinstance(item, tuple) else (item,))
|
| 818 |
+
)
|
| 819 |
+
)
|
| 820 |
+
# And loop codegen
|
| 821 |
+
while self.multistage_reduction_entry:
|
| 822 |
+
self.multistage_reduction_entry.pop().cache_clear()
|
| 823 |
+
else:
|
| 824 |
+
self.body.splice(self.loads)
|
| 825 |
+
self.body.splice(self.compute)
|
| 826 |
+
self.body.splice(self.stores)
|
| 827 |
+
self.loads.clear()
|
| 828 |
+
self.compute.clear()
|
| 829 |
+
self.stores.clear()
|
| 830 |
+
|
| 831 |
+
def codegen_kernel(self, name: Optional[str] = None) -> str:
|
| 832 |
+
"""Called at the end to generate a final kernel string"""
|
| 833 |
+
self.codegen_body()
|
| 834 |
+
code = IndentedBuffer()
|
| 835 |
+
|
| 836 |
+
if V.graph.cpp_wrapper:
|
| 837 |
+
code.writeline('(R"MTL(')
|
| 838 |
+
else:
|
| 839 |
+
code.writeline("compile_mps_shader('''")
|
| 840 |
+
|
| 841 |
+
idx_vars = self.active_range_trees()
|
| 842 |
+
with code.indent():
|
| 843 |
+
if not V.graph.cpp_wrapper:
|
| 844 |
+
for header in self.headers:
|
| 845 |
+
code.writeline(f"#include <c10/metal/{header}.h>")
|
| 846 |
+
else:
|
| 847 |
+
headers = [
|
| 848 |
+
f"#include <c10/metal/{header}.h>" for header in self.headers
|
| 849 |
+
]
|
| 850 |
+
header_contents = _embed_headers(
|
| 851 |
+
headers,
|
| 852 |
+
[Path(__file__).parent.parent.parent / "include"],
|
| 853 |
+
OrderedSet(), # type: ignore[arg-type]
|
| 854 |
+
)
|
| 855 |
+
code.writeline(header_contents)
|
| 856 |
+
|
| 857 |
+
if self.inside_reduction:
|
| 858 |
+
total_reduction_size = math.prod(
|
| 859 |
+
t.numel for t in self.range_trees if t.is_reduction
|
| 860 |
+
)
|
| 861 |
+
# If using dynamic shapes, set the threadgroup size to be the
|
| 862 |
+
# max possible size
|
| 863 |
+
threadgroup_size = (
|
| 864 |
+
min(total_reduction_size, self.max_threadgroup_size)
|
| 865 |
+
if isinstance(total_reduction_size, sympy.Integer)
|
| 866 |
+
else self.max_threadgroup_size
|
| 867 |
+
)
|
| 868 |
+
code.writeline(
|
| 869 |
+
f"[[max_total_threads_per_threadgroup({threadgroup_size})]]"
|
| 870 |
+
)
|
| 871 |
+
code.writeline("kernel void generated_kernel(")
|
| 872 |
+
with code.indent():
|
| 873 |
+
for outer, inner in self.args.output_buffers.items():
|
| 874 |
+
if outer in self.removed_buffers:
|
| 875 |
+
continue
|
| 876 |
+
dtype_str = self.dtype_to_str(V.graph.get_dtype(outer))
|
| 877 |
+
code.writeline(f"device {dtype_str}* {inner},")
|
| 878 |
+
for outer, inner in self.args.input_buffers.items():
|
| 879 |
+
dtype = V.graph.get_dtype(outer)
|
| 880 |
+
# MPS does not support float64, but scalar inputs are fine
|
| 881 |
+
if dtype == torch.float64:
|
| 882 |
+
outer_buf = V.graph.try_get_buffer(outer)
|
| 883 |
+
if outer_buf is None or outer_buf.get_size() != []:
|
| 884 |
+
raise RuntimeError("float64 is not supported by MPS")
|
| 885 |
+
dtype_str = "float"
|
| 886 |
+
else:
|
| 887 |
+
dtype_str = self.dtype_to_str(dtype)
|
| 888 |
+
code.writeline(f"constant {dtype_str}* {inner},")
|
| 889 |
+
for outer, inner in self.args.sizevars.items():
|
| 890 |
+
code.writeline(f"constant long& {inner},")
|
| 891 |
+
|
| 892 |
+
# Write dynamic values as inputs
|
| 893 |
+
for idx_var in idx_vars:
|
| 894 |
+
if isinstance(idx_var.numel, sympy.Integer):
|
| 895 |
+
pass
|
| 896 |
+
else:
|
| 897 |
+
code.writeline(f"constant long& {idx_var.prefix}numel,")
|
| 898 |
+
|
| 899 |
+
assert len(idx_vars) < 4, "Up to 3 index variables are supported"
|
| 900 |
+
thread_pos_dtype = (
|
| 901 |
+
f"uint{len(idx_vars)}" if len(idx_vars) > 1 else "uint"
|
| 902 |
+
)
|
| 903 |
+
thread_pos_var_name = (
|
| 904 |
+
idx_vars[0].name if len(idx_vars) == 1 else "thread_pos"
|
| 905 |
+
)
|
| 906 |
+
thread_pos_suffix = "," if self.inside_reduction else ""
|
| 907 |
+
code.writeline(
|
| 908 |
+
f"{thread_pos_dtype} {thread_pos_var_name} [[thread_position_in_grid]]{thread_pos_suffix}"
|
| 909 |
+
)
|
| 910 |
+
if self.inside_reduction:
|
| 911 |
+
code.writeline(
|
| 912 |
+
f"{thread_pos_dtype} group_pos [[thread_position_in_threadgroup]]"
|
| 913 |
+
)
|
| 914 |
+
code.writeline(") {")
|
| 915 |
+
with code.indent():
|
| 916 |
+
if len(idx_vars) > 1:
|
| 917 |
+
for idx, var in enumerate(idx_vars):
|
| 918 |
+
code.writeline(
|
| 919 |
+
f"auto {var.name} = thread_pos.{chr(120 + idx)};"
|
| 920 |
+
)
|
| 921 |
+
code.splice(self.indexing_code)
|
| 922 |
+
code.splice(self.body)
|
| 923 |
+
code.writeline("}")
|
| 924 |
+
|
| 925 |
+
if V.graph.cpp_wrapper:
|
| 926 |
+
code.writeline(')MTL");')
|
| 927 |
+
else:
|
| 928 |
+
code.writeline("''')")
|
| 929 |
+
|
| 930 |
+
return code.getvalue()
|
| 931 |
+
|
| 932 |
+
def call_kernel(self, name: str, node: Any = None) -> None:
|
| 933 |
+
"""
|
| 934 |
+
Codegens a call to this kernel
|
| 935 |
+
"""
|
| 936 |
+
wrapper = V.graph.wrapper_code
|
| 937 |
+
# Make sure sizevars has been computed
|
| 938 |
+
for v in self.args.sizevars.keys():
|
| 939 |
+
wrapper.ensure_size_computed(v)
|
| 940 |
+
|
| 941 |
+
_, call_args, _, arg_types = self.args.python_argdefs()
|
| 942 |
+
arg_name_to_type = {
|
| 943 |
+
str(call_arg): arg_type for call_arg, arg_type in zip(call_args, arg_types)
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
args = [*self.args.output_buffers.keys(), *self.args.input_buffers.keys()]
|
| 947 |
+
args = [arg for arg in args if arg not in self.removed_buffers]
|
| 948 |
+
args += [str(v) for v in self.args.sizevars.keys()]
|
| 949 |
+
arg_types = [arg_name_to_type[arg] for arg in args]
|
| 950 |
+
|
| 951 |
+
# Add any dynamic ints as inputs
|
| 952 |
+
for tree in self.range_trees:
|
| 953 |
+
if isinstance(tree.numel, (sympy.Integer, int)):
|
| 954 |
+
# Don't need to pass in integers as inputs
|
| 955 |
+
continue
|
| 956 |
+
elif isinstance(tree.numel, sympy.Symbol):
|
| 957 |
+
expr = tree.numel
|
| 958 |
+
else:
|
| 959 |
+
expr = V.graph.wrapper_code.generate_numel_expr(name, tree).inner
|
| 960 |
+
|
| 961 |
+
if not tree.is_reduction or self.inside_reduction:
|
| 962 |
+
args.append(str(expr))
|
| 963 |
+
arg_types.append(int)
|
| 964 |
+
|
| 965 |
+
expr_printer = self.cexpr if V.graph.cpp_wrapper else self.pexpr
|
| 966 |
+
|
| 967 |
+
def format_threads(threads: list[str], kwarg: str) -> str:
|
| 968 |
+
if V.graph.cpp_wrapper:
|
| 969 |
+
threads = [f"static_cast<uint64_t>({t})" for t in threads]
|
| 970 |
+
return f"{{{', '.join(threads)}}}"
|
| 971 |
+
else:
|
| 972 |
+
return f"{kwarg}=[{', '.join(threads)}]"
|
| 973 |
+
|
| 974 |
+
# For reduction kernels, limit the maximum size over reduction dimensions to
|
| 975 |
+
# a maximum threadgroup size
|
| 976 |
+
if len(self.active_range_trees()) > 0:
|
| 977 |
+
threads = [
|
| 978 |
+
expr_printer(
|
| 979 |
+
sympy.Min(v.numel, self.max_threadgroup_size) # type: ignore[misc]
|
| 980 |
+
if v.is_reduction
|
| 981 |
+
else v.numel
|
| 982 |
+
)
|
| 983 |
+
for v in self.active_range_trees()
|
| 984 |
+
]
|
| 985 |
+
|
| 986 |
+
args.append(format_threads(threads, "threads"))
|
| 987 |
+
arg_types.append(list)
|
| 988 |
+
else:
|
| 989 |
+
if V.graph.cpp_wrapper:
|
| 990 |
+
raise RuntimeError("We should always have threads?")
|
| 991 |
+
|
| 992 |
+
if self.inside_reduction:
|
| 993 |
+
threads = [
|
| 994 |
+
expr_printer(sympy.Min(v.numel, self.max_threadgroup_size)) # type: ignore[misc]
|
| 995 |
+
if v.is_reduction
|
| 996 |
+
else "1"
|
| 997 |
+
for v in self.active_range_trees()
|
| 998 |
+
]
|
| 999 |
+
args.append(format_threads(threads, "group_size"))
|
| 1000 |
+
arg_types.append(list)
|
| 1001 |
+
else:
|
| 1002 |
+
if V.graph.cpp_wrapper:
|
| 1003 |
+
# Add a None so that we always have a group_size in the
|
| 1004 |
+
# arguments. We won't use it if the value is None.
|
| 1005 |
+
args += [None] # type: ignore[list-item]
|
| 1006 |
+
arg_types.append(None)
|
| 1007 |
+
|
| 1008 |
+
wrapper.generate_kernel_call(
|
| 1009 |
+
name,
|
| 1010 |
+
args,
|
| 1011 |
+
device=torch.device("mps"),
|
| 1012 |
+
triton=False,
|
| 1013 |
+
arg_types=arg_types,
|
| 1014 |
+
)
|
| 1015 |
+
|
| 1016 |
+
def check_bounds(
|
| 1017 |
+
self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool
|
| 1018 |
+
) -> None:
|
| 1019 |
+
if not (lower or upper):
|
| 1020 |
+
return
|
| 1021 |
+
# TODO(malfet): support asserts
|
| 1022 |
+
# See https://github.com/pytorch/pytorch/issues/144634
|
| 1023 |
+
expr_str = self.index_to_str(expr)
|
| 1024 |
+
lower_expr = f"{expr_str} < 0" if lower else ""
|
| 1025 |
+
# TODO(malfet): Is upper bound inclusive or exclusive?
|
| 1026 |
+
upper_expr = f"{expr_str} > {self.index_to_str(size)}" if upper else ""
|
| 1027 |
+
if lower and upper:
|
| 1028 |
+
line = f"if (({lower_expr}) && ({upper_expr})) return"
|
| 1029 |
+
else:
|
| 1030 |
+
line = f"if ({lower_expr}{upper_expr}) return"
|
| 1031 |
+
self.cse.generate(self.compute, line, assignment=False)
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
class MetalScheduling(SIMDScheduling):
|
| 1035 |
+
kernel_type = MetalKernel # type: ignore[assignment]
|
| 1036 |
+
|
| 1037 |
+
def __init__(self, scheduler: Optional[Scheduler]) -> None:
|
| 1038 |
+
super().__init__(scheduler)
|
| 1039 |
+
wrapper = V.graph.wrapper_code
|
| 1040 |
+
if wrapper is not None:
|
| 1041 |
+
if not V.graph.cpp_wrapper:
|
| 1042 |
+
wrapper.header.splice(
|
| 1043 |
+
"from torch._inductor.runtime.runtime_utils import compile_mps_shader"
|
| 1044 |
+
)
|
| 1045 |
+
|
| 1046 |
+
def define_kernel(
|
| 1047 |
+
self, src_code: str, node_schedule: list[SchedulerNode], kernel: MetalKernel
|
| 1048 |
+
) -> str:
|
| 1049 |
+
wrapper = V.graph.wrapper_code
|
| 1050 |
+
if src_code in wrapper.src_to_kernel:
|
| 1051 |
+
kernel_name = wrapper.src_to_kernel[src_code]
|
| 1052 |
+
else:
|
| 1053 |
+
# TODO: Merge multiple kernels into a single library
|
| 1054 |
+
# Either using MultiKernel concept or overriding SIMDScheduling.codegen_node_scheduling
|
| 1055 |
+
mps_lib_name = f"mps_lib_{wrapper.next_kernel_suffix()}"
|
| 1056 |
+
|
| 1057 |
+
kernel_name = f"{mps_lib_name}"
|
| 1058 |
+
wrapper.src_to_kernel[src_code] = kernel_name
|
| 1059 |
+
|
| 1060 |
+
if V.graph.cpp_wrapper:
|
| 1061 |
+
src_code = (
|
| 1062 |
+
f"at::native::mps::DynamicMetalShaderLibrary {mps_lib_name}"
|
| 1063 |
+
+ src_code
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
|
| 1067 |
+
metadata_comment = f"{origins}\n{detailed_origins}"
|
| 1068 |
+
wrapper.define_kernel(mps_lib_name, src_code, metadata_comment, gpu=False)
|
| 1069 |
+
|
| 1070 |
+
return kernel_name
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mps_device_op_overrides.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from .common import DeviceOpOverrides, register_device_op_overrides
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MPSDeviceOpOverrides(DeviceOpOverrides):
|
| 7 |
+
def device_guard(self, device_idx: int) -> str:
|
| 8 |
+
assert device_idx == 0
|
| 9 |
+
return "torch._ops.contextlib.nullcontext()"
|
| 10 |
+
|
| 11 |
+
def set_device(self, device_idx: int) -> str:
|
| 12 |
+
assert device_idx == 0
|
| 13 |
+
return "pass # MPS set device"
|
| 14 |
+
|
| 15 |
+
def kernel_driver(self) -> str:
|
| 16 |
+
return """
|
| 17 |
+
#include <ATen/native/mps/MetalShaderLibrary.h>
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def cpp_kernel_type(self) -> str:
|
| 21 |
+
return "MTLFunction_t"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
register_device_op_overrides("mps", MPSDeviceOpOverrides())
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mtia/__init__.py
ADDED
|
File without changes
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from ..common import DeviceOpOverrides, register_device_op_overrides
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class MTIADeviceOpOverrides(DeviceOpOverrides):
|
| 7 |
+
def import_get_raw_stream_as(self, name: str) -> str:
|
| 8 |
+
return f"from torch._C import _mtia_getCurrentRawStream as {name}"
|
| 9 |
+
|
| 10 |
+
def set_device(self, device_idx: int) -> str:
|
| 11 |
+
return f"torch.mtia.set_device({device_idx})"
|
| 12 |
+
|
| 13 |
+
def synchronize(self) -> str:
|
| 14 |
+
return "torch.mtia.synchronize()"
|
| 15 |
+
|
| 16 |
+
def device_guard(self, device_idx: int) -> str:
|
| 17 |
+
return f"torch.mtia.device({device_idx})"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
register_device_op_overrides("mtia", MTIADeviceOpOverrides())
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/multi_kernel.py
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import pathlib
|
| 6 |
+
|
| 7 |
+
from torch._inductor.ir import MultiTemplateBuffer
|
| 8 |
+
from torch._inductor.metrics import get_metric_table, is_metric_table_enabled
|
| 9 |
+
from torch.utils._ordered_set import OrderedSet
|
| 10 |
+
|
| 11 |
+
from .. import config
|
| 12 |
+
from ..codecache import code_hash, CodeCacheFuture, get_path, write_atomic
|
| 13 |
+
from ..runtime.benchmarking import benchmarker
|
| 14 |
+
from ..utils import cache_on_self, IndentedBuffer
|
| 15 |
+
from ..virtualized import V
|
| 16 |
+
from .common import TensorArg, WorkspaceArg
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
log = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class MultiKernelState:
|
| 23 |
+
"""
|
| 24 |
+
Maintain state of multi-kernel compilation so we don't define duplicated
|
| 25 |
+
multi-kernel for the same set of sub-kernels.
|
| 26 |
+
|
| 27 |
+
V.graph.wrapper_code has a reference to MultiKernelState instance.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(self):
|
| 31 |
+
self.subkernel_to_kernel_name = {}
|
| 32 |
+
self.kernel_defs = IndentedBuffer()
|
| 33 |
+
|
| 34 |
+
def define_kernel(self, kernels):
|
| 35 |
+
"""
|
| 36 |
+
Previously we name the multi kernel as "multi_kernel_{kernel_names[0]}".
|
| 37 |
+
This has some minor issue.
|
| 38 |
+
|
| 39 |
+
E.g. for persistent reduction https://gist.github.com/shunting314/39e7c00ff8bb2055942ed5a3255d61ca ,
|
| 40 |
+
there are 2 flavors of non-persistent reduction:
|
| 41 |
+
https://gist.github.com/shunting314/056d43d35907e87efb883970b35c17d4
|
| 42 |
+
and
|
| 43 |
+
https://gist.github.com/shunting314/02ee753b65c513c54e695626afe682bd
|
| 44 |
+
|
| 45 |
+
The only different is cache eviction policy.
|
| 46 |
+
|
| 47 |
+
We should name the multi-kernel differently in these 2 cases.
|
| 48 |
+
"""
|
| 49 |
+
# Prevent circular import
|
| 50 |
+
from ..select_algorithm import TritonTemplateKernel
|
| 51 |
+
|
| 52 |
+
kernel_names = tuple(k.kernel_name for k in kernels)
|
| 53 |
+
if kernel_names in self.subkernel_to_kernel_name:
|
| 54 |
+
return self.subkernel_to_kernel_name[kernel_names]
|
| 55 |
+
|
| 56 |
+
# name the multi kernel based on the first kernel
|
| 57 |
+
multi_kernel_name = f"multi_kernel_{len(self.subkernel_to_kernel_name)}"
|
| 58 |
+
self.subkernel_to_kernel_name[kernel_names] = multi_kernel_name
|
| 59 |
+
|
| 60 |
+
if V.graph.cpp_wrapper and not config.triton.autotune_at_compile_time:
|
| 61 |
+
# we should not generate any python code for multi-kernel during
|
| 62 |
+
# the second pass of cpp-wrapper.
|
| 63 |
+
return multi_kernel_name
|
| 64 |
+
|
| 65 |
+
arg_index: dict[int, list[slice]] = {}
|
| 66 |
+
_, call_args, _, arg_types = kernels[0].args.python_argdefs()
|
| 67 |
+
if isinstance(kernels[0], TritonTemplateKernel) and isinstance(
|
| 68 |
+
kernels[0].output_node, MultiTemplateBuffer
|
| 69 |
+
):
|
| 70 |
+
for i, kernel in enumerate(kernels):
|
| 71 |
+
additional_call_args, additional_arg_types = (
|
| 72 |
+
kernel.additional_call_args_and_types()
|
| 73 |
+
)
|
| 74 |
+
if i not in arg_index:
|
| 75 |
+
arg_index[i] = []
|
| 76 |
+
arg_index[i].append(slice(0, len(call_args)))
|
| 77 |
+
arg_index[i].append(
|
| 78 |
+
slice(
|
| 79 |
+
len(call_args) + i * len(additional_call_args),
|
| 80 |
+
len(call_args) + (i + 1) * len(additional_call_args),
|
| 81 |
+
)
|
| 82 |
+
)
|
| 83 |
+
else:
|
| 84 |
+
kernels[0].add_numel_to_call_args(multi_kernel_name, call_args, arg_types)
|
| 85 |
+
for i in range(len(kernels)):
|
| 86 |
+
arg_index[i] = [slice(0, len(call_args))]
|
| 87 |
+
|
| 88 |
+
shape_specialize = isinstance(kernels[0], TritonTemplateKernel)
|
| 89 |
+
buf = self.kernel_defs
|
| 90 |
+
buf.writeline("")
|
| 91 |
+
buf.writeline("arg_index = {")
|
| 92 |
+
for key, slice_list in arg_index.items():
|
| 93 |
+
slice_reprs = ", ".join(repr(s) for s in slice_list)
|
| 94 |
+
buf.writeline(f" {key}: [{slice_reprs}],")
|
| 95 |
+
buf.writeline("}")
|
| 96 |
+
buf.writeline(
|
| 97 |
+
f"{multi_kernel_name} = async_compile.multi_kernel({multi_kernel_name!r}, ["
|
| 98 |
+
)
|
| 99 |
+
with buf.indent():
|
| 100 |
+
for name in kernel_names:
|
| 101 |
+
buf.writeline(f"{name},")
|
| 102 |
+
buf.writeline(f"], arg_index=arg_index, shape_specialize={shape_specialize})")
|
| 103 |
+
|
| 104 |
+
if config.triton.autotune_at_compile_time:
|
| 105 |
+
V.graph.wrapper_code.src_to_kernel["\n".join(kernel_names)] = (
|
| 106 |
+
multi_kernel_name
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
return multi_kernel_name
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class MultiKernel:
|
| 113 |
+
"""
|
| 114 |
+
This class maintains the compile time state for multi kernels.
|
| 115 |
+
|
| 116 |
+
Assume we do codegen for a MultiKernel encapsulating kernel1 and kernel2.
|
| 117 |
+
The generated definition for the multi-kernel will looks like:
|
| 118 |
+
```
|
| 119 |
+
multi_kernel_kernel1 = MultiKernelCall(
|
| 120 |
+
[kernel1, kernel2], multi_kernel_definition_code
|
| 121 |
+
)
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
Here is a concrete example: https://gist.github.com/shunting314/d9f3fb6bc6cee3dbae005825ca196d39
|
| 125 |
+
"""
|
| 126 |
+
|
| 127 |
+
def __init__(self, kernels):
|
| 128 |
+
assert len(kernels) >= 2
|
| 129 |
+
|
| 130 |
+
self.kernels = kernels
|
| 131 |
+
self.kernel_name = V.graph.wrapper_code.multi_kernel_state.define_kernel(
|
| 132 |
+
kernels
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# need this since some code in inductor check if the kernel object has an args
|
| 136 |
+
# attribute to decide if it's a non-null kernel.
|
| 137 |
+
self.args = object()
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def _merge_workspace_args(left: list[WorkspaceArg], right: list[WorkspaceArg]):
|
| 141 |
+
if left == right:
|
| 142 |
+
return left
|
| 143 |
+
result = {x.inner_name: x for x in left}
|
| 144 |
+
for arg in right:
|
| 145 |
+
if arg.inner_name in result:
|
| 146 |
+
result[arg.inner_name] = WorkspaceArg.maximum(
|
| 147 |
+
result[arg.inner_name], arg
|
| 148 |
+
)
|
| 149 |
+
else:
|
| 150 |
+
result[arg.inner_name] = arg
|
| 151 |
+
return [*result.values()]
|
| 152 |
+
|
| 153 |
+
@staticmethod
|
| 154 |
+
def merge_workspaces_inplace(kernels):
|
| 155 |
+
if len(kernels) < 2:
|
| 156 |
+
return
|
| 157 |
+
# All kernels must share the same workspace
|
| 158 |
+
workspace_args = functools.reduce(
|
| 159 |
+
MultiKernel._merge_workspace_args,
|
| 160 |
+
[kernel.args.workspace_args for kernel in kernels],
|
| 161 |
+
)
|
| 162 |
+
for kernel in kernels:
|
| 163 |
+
kernel.args.workspace_args = workspace_args
|
| 164 |
+
return workspace_args
|
| 165 |
+
|
| 166 |
+
def call_kernel(self, kernel_name):
|
| 167 |
+
"""
|
| 168 |
+
Collect the union of arguments from all subkernels as the arguments
|
| 169 |
+
for the multi-kernel.
|
| 170 |
+
"""
|
| 171 |
+
# Prevent circular import
|
| 172 |
+
from ..select_algorithm import TritonTemplateKernel
|
| 173 |
+
|
| 174 |
+
assert kernel_name == self.kernel_name
|
| 175 |
+
V.graph.wrapper_code.write_triton_header_once()
|
| 176 |
+
_, call_args, _, arg_types = self.kernels[0].args.python_argdefs()
|
| 177 |
+
for kernel in self.kernels[1:]:
|
| 178 |
+
_, other_call_args, _, other_arg_types = kernel.args.python_argdefs()
|
| 179 |
+
assert call_args == other_call_args, (call_args, other_call_args)
|
| 180 |
+
assert arg_types == other_arg_types
|
| 181 |
+
|
| 182 |
+
if V.graph.cpp_wrapper and not config.triton.autotune_at_compile_time:
|
| 183 |
+
# for the second pass of cpp-wrapper codegen, we should call
|
| 184 |
+
# the fast kernel directly
|
| 185 |
+
kernel_name = MultiKernelCall.lookup_choice(self.kernel_name)
|
| 186 |
+
|
| 187 |
+
if isinstance(self.kernels[0], TritonTemplateKernel) and isinstance(
|
| 188 |
+
self.kernels[0].output_node, MultiTemplateBuffer
|
| 189 |
+
):
|
| 190 |
+
# For matmuls the grid arguments are passed in as additional arguments
|
| 191 |
+
# to the kernel run method. These grids change based on the various
|
| 192 |
+
# parameters of the matmul. So we need to pass each kernel's grid into
|
| 193 |
+
# the multi call kernel.
|
| 194 |
+
multi_call_args = call_args
|
| 195 |
+
multi_call_arg_types = arg_types
|
| 196 |
+
for i, kernel in enumerate(self.kernels):
|
| 197 |
+
additional_call_args, additional_arg_types = (
|
| 198 |
+
kernel.additional_call_args_and_types()
|
| 199 |
+
)
|
| 200 |
+
multi_call_args.extend(list(additional_call_args))
|
| 201 |
+
multi_call_arg_types.extend(list(additional_arg_types))
|
| 202 |
+
else:
|
| 203 |
+
# numels for all subkernels should be the same. Use kernels[0] here
|
| 204 |
+
self.kernels[0].add_numel_to_call_args(kernel_name, call_args, arg_types)
|
| 205 |
+
multi_call_args = call_args
|
| 206 |
+
multi_call_arg_types = arg_types
|
| 207 |
+
|
| 208 |
+
for ws in self.kernels[0].args.workspace_args:
|
| 209 |
+
V.graph.wrapper_code.generate_workspace_allocation(ws)
|
| 210 |
+
|
| 211 |
+
if V.graph.cpp_wrapper:
|
| 212 |
+
# We have already selected the best kernel at compile time
|
| 213 |
+
# so we only have one set of call args. NB: this currently
|
| 214 |
+
# doesn't work with MultiTemplateBuffer kernels. @bobrenjc93
|
| 215 |
+
# will add it in a subsequent PR.
|
| 216 |
+
V.graph.wrapper_code.generate_kernel_call(
|
| 217 |
+
kernel_name, call_args, arg_types=arg_types
|
| 218 |
+
)
|
| 219 |
+
else:
|
| 220 |
+
V.graph.wrapper_code.generate_kernel_call(
|
| 221 |
+
kernel_name, multi_call_args, arg_types=multi_call_arg_types
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
for ws in reversed(self.kernels[0].args.workspace_args):
|
| 225 |
+
V.graph.wrapper_code.generate_workspace_deallocation(ws)
|
| 226 |
+
|
| 227 |
+
def codegen_nan_check(self):
|
| 228 |
+
wrapper = V.graph.wrapper_code
|
| 229 |
+
seen: OrderedSet[str] = OrderedSet()
|
| 230 |
+
for k in self.kernels:
|
| 231 |
+
_, call_args, precompile_args, _ = k.args.python_argdefs()
|
| 232 |
+
for arg, precompile_arg in zip(call_args, precompile_args):
|
| 233 |
+
if arg in seen:
|
| 234 |
+
continue
|
| 235 |
+
seen.add(arg)
|
| 236 |
+
if isinstance(precompile_arg, TensorArg):
|
| 237 |
+
line = f"assert not {arg}.isnan().any().item()"
|
| 238 |
+
wrapper.writeline(line)
|
| 239 |
+
line = f"assert not {arg}.isinf().any().item()"
|
| 240 |
+
wrapper.writeline(line)
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def removed_buffers(self):
|
| 244 |
+
return OrderedSet.intersection(*[k.removed_buffers for k in self.kernels])
|
| 245 |
+
|
| 246 |
+
@property
|
| 247 |
+
def inplaced_to_remove(self):
|
| 248 |
+
return OrderedSet.intersection(*[k.inplaced_to_remove for k in self.kernels])
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
@cache_on_self
|
| 252 |
+
def inplace_update_buffers(self):
|
| 253 |
+
"""
|
| 254 |
+
Make sure all kernels have the same inplace update mappings.
|
| 255 |
+
"""
|
| 256 |
+
for k in self.kernels[1:]:
|
| 257 |
+
assert k.inplace_update_buffers == self.kernels[0].inplace_update_buffers
|
| 258 |
+
return self.kernels[0].inplace_update_buffers
|
| 259 |
+
|
| 260 |
+
def warn_mix_layout(self, kernel_name: str):
|
| 261 |
+
pass
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class MultiKernelCall:
|
| 265 |
+
"""
|
| 266 |
+
This class is called at run time to actually run the kernel
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
def __init__(self, multi_kernel_name, kernels, arg_index, shape_specialize=False):
|
| 270 |
+
assert len(kernels) >= 2
|
| 271 |
+
self._kernels = kernels
|
| 272 |
+
self.multi_kernel_name = multi_kernel_name
|
| 273 |
+
|
| 274 |
+
self.disable_cache = os.environ.get(
|
| 275 |
+
"TORCHINDUCTOR_DISABLE_MULTI_KERNEL_CACHE"
|
| 276 |
+
) == "1" or is_metric_table_enabled("persistent_red_perf")
|
| 277 |
+
|
| 278 |
+
self.picked_kernel = None
|
| 279 |
+
self.arg_index = arg_index
|
| 280 |
+
if config.triton.multi_kernel > 1:
|
| 281 |
+
# manually force a subkernel to ease perf testing
|
| 282 |
+
picked_by_config = config.triton.multi_kernel - 2
|
| 283 |
+
assert picked_by_config < len(self._kernels)
|
| 284 |
+
self.picked_kernel = picked_by_config
|
| 285 |
+
elif not self.disable_cache:
|
| 286 |
+
self.load_cache()
|
| 287 |
+
|
| 288 |
+
self._recorded = False
|
| 289 |
+
|
| 290 |
+
# This means for each unique shape we will do a separate assessment
|
| 291 |
+
# for which kernel is the best. This is particularly useful for matmul
|
| 292 |
+
# kernels where the best kernel can vary based on very small differences
|
| 293 |
+
# in shape.
|
| 294 |
+
self._shape_specialize = shape_specialize
|
| 295 |
+
self._shape_cache = {}
|
| 296 |
+
|
| 297 |
+
def cache_file_path(self):
|
| 298 |
+
key = code_hash(
|
| 299 |
+
",".join(
|
| 300 |
+
[
|
| 301 |
+
f"{k.fn.cache_key}{k.size_hints!r}{k.triton_meta!r}"
|
| 302 |
+
for k in self.kernels
|
| 303 |
+
]
|
| 304 |
+
)
|
| 305 |
+
)
|
| 306 |
+
_, _, path = get_path(key, "picked_kernel")
|
| 307 |
+
return pathlib.Path(path)
|
| 308 |
+
|
| 309 |
+
def load_cache(self):
|
| 310 |
+
assert self.picked_kernel is None
|
| 311 |
+
path = self.cache_file_path()
|
| 312 |
+
if path.exists():
|
| 313 |
+
with path.open() as fd:
|
| 314 |
+
self.picked_kernel = int(fd.read())
|
| 315 |
+
assert self.picked_kernel >= 0 and self.picked_kernel < len(
|
| 316 |
+
self._kernels
|
| 317 |
+
)
|
| 318 |
+
log.debug(
|
| 319 |
+
"Load picked kernel %d from cache file %s", self.picked_kernel, path
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
def store_cache(self):
|
| 323 |
+
assert self.picked_kernel is not None
|
| 324 |
+
path = self.cache_file_path()
|
| 325 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 326 |
+
|
| 327 |
+
write_atomic(path, str(self.picked_kernel))
|
| 328 |
+
log.debug("Store picked kernel %d to cache file %s", self.picked_kernel, path)
|
| 329 |
+
|
| 330 |
+
@property
|
| 331 |
+
def kernels(self):
|
| 332 |
+
"""
|
| 333 |
+
Read results from future.
|
| 334 |
+
|
| 335 |
+
This should be called after parallel compilation is done.
|
| 336 |
+
In case you call this before compilation is done,
|
| 337 |
+
it may slow down the parallel compilation.
|
| 338 |
+
"""
|
| 339 |
+
for i, kernel in enumerate(self._kernels):
|
| 340 |
+
if isinstance(kernel, CodeCacheFuture):
|
| 341 |
+
self._kernels[i] = kernel.result()
|
| 342 |
+
|
| 343 |
+
return self._kernels
|
| 344 |
+
|
| 345 |
+
def benchmark_sub_kernels(self, *args, **kwargs):
|
| 346 |
+
"""
|
| 347 |
+
Benchmark all the sub kernels and return the execution time
|
| 348 |
+
(in milliseconds) for each of time.
|
| 349 |
+
|
| 350 |
+
Unit test may mock this method to force a specific kernel to
|
| 351 |
+
be picked.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
def wrap_fn(kernel, index):
|
| 355 |
+
def inner():
|
| 356 |
+
filtered_args = self._get_filtered_args(args, index)
|
| 357 |
+
args_clone, kwargs_clone = kernel.clone_args(*filtered_args, **kwargs)
|
| 358 |
+
return kernel.run(*args_clone, **kwargs_clone)
|
| 359 |
+
|
| 360 |
+
return inner
|
| 361 |
+
|
| 362 |
+
return [
|
| 363 |
+
benchmarker.benchmark_gpu(wrap_fn(kernel, index), rep=40)
|
| 364 |
+
for index, kernel in enumerate(self.kernels)
|
| 365 |
+
]
|
| 366 |
+
|
| 367 |
+
def _get_filtered_args(self, args, index):
|
| 368 |
+
"""
|
| 369 |
+
We pass in all arguments to all kernels into the MultiKernelCall
|
| 370 |
+
so when invoking a particular kernel we need to filter to only the
|
| 371 |
+
arguments for that specific kernel.
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
# This is sometimes invoked at runtime where V.graph is
|
| 375 |
+
# a NullHandler
|
| 376 |
+
if hasattr(V.graph, "cpp_wrapper") and V.graph.cpp_wrapper:
|
| 377 |
+
# for cpp-wrapper, we should not filter the args since
|
| 378 |
+
# we already have chosen a single kernel and arg set.
|
| 379 |
+
return args
|
| 380 |
+
return [item for s in self.arg_index[index] for item in args[s]]
|
| 381 |
+
|
| 382 |
+
# record_choice and lookup_choice are helper functions for cpp-wrapper
|
| 383 |
+
# codegen. The first pass use record_choice to keep the choice and
|
| 384 |
+
# the second pass do lookup by calling lookup_choice.
|
| 385 |
+
#
|
| 386 |
+
# An alternative that reused the multi-kernel cache does not work well
|
| 387 |
+
# since during codegen of the second pass, it's very hard to know the
|
| 388 |
+
# path for the cache file. Also reading the cache file need do some IO
|
| 389 |
+
# which can be slower.
|
| 390 |
+
@staticmethod
|
| 391 |
+
def record_choice(multi_kernel_name: str, picked_kernel_name: str):
|
| 392 |
+
"""
|
| 393 |
+
Record the multi-kernel choice for cpp-wrapper after autotuning
|
| 394 |
+
|
| 395 |
+
We should do nothing if this function is not called during codegen.
|
| 396 |
+
"""
|
| 397 |
+
from torch._inductor.graph import GraphLowering
|
| 398 |
+
|
| 399 |
+
if not isinstance(V.graph, GraphLowering):
|
| 400 |
+
return
|
| 401 |
+
|
| 402 |
+
if not V.graph.record_multi_kernel_choice:
|
| 403 |
+
return
|
| 404 |
+
|
| 405 |
+
V.graph.multi_kernel_to_choice[multi_kernel_name] = picked_kernel_name
|
| 406 |
+
|
| 407 |
+
@staticmethod
|
| 408 |
+
def lookup_choice(multi_kernel_name: str) -> str:
|
| 409 |
+
# this should always been done during cpp-wrapper codegen
|
| 410 |
+
assert (
|
| 411 |
+
V.graph.record_multi_kernel_choice
|
| 412 |
+
and multi_kernel_name in V.graph.multi_kernel_to_choice
|
| 413 |
+
)
|
| 414 |
+
# there should be no miss
|
| 415 |
+
return V.graph.multi_kernel_to_choice[multi_kernel_name]
|
| 416 |
+
|
| 417 |
+
def run(self, *args, **kwargs):
|
| 418 |
+
if self._shape_specialize:
|
| 419 |
+
cache_key = self._get_shape_cache_key(*args, **kwargs)
|
| 420 |
+
cached_choice = self._get_cached_shape_choice(cache_key)
|
| 421 |
+
if cached_choice is not None:
|
| 422 |
+
self.picked_kernel = cached_choice
|
| 423 |
+
log.debug(
|
| 424 |
+
"using cached shape-specialized choice %dth sub-kernel in %s. Cache key: %s",
|
| 425 |
+
self.picked_kernel,
|
| 426 |
+
[k.inductor_meta.get("kernel_name") for k in self.kernels],
|
| 427 |
+
cache_key,
|
| 428 |
+
)
|
| 429 |
+
else:
|
| 430 |
+
self._select_kernel_by_shape(*args, **kwargs)
|
| 431 |
+
|
| 432 |
+
if self.picked_kernel is None:
|
| 433 |
+
timings = self.benchmark_sub_kernels(*args, **kwargs)
|
| 434 |
+
self.picked_kernel = timings.index(min(timings))
|
| 435 |
+
k0 = self.kernels[0]
|
| 436 |
+
log.debug(
|
| 437 |
+
"pick %dth sub-kernel in %s. Size hints %s. Reduction hint %s. Timings %s",
|
| 438 |
+
self.picked_kernel,
|
| 439 |
+
[k.inductor_meta.get("kernel_name") for k in self.kernels],
|
| 440 |
+
k0.size_hints,
|
| 441 |
+
k0.inductor_meta.get("reduction_hint"),
|
| 442 |
+
timings,
|
| 443 |
+
)
|
| 444 |
+
get_metric_table("persistent_red_perf").add_row(
|
| 445 |
+
functools.partial(self._metrics_table_row, timings)
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if not self.disable_cache:
|
| 449 |
+
self.store_cache()
|
| 450 |
+
|
| 451 |
+
if not self._recorded:
|
| 452 |
+
self._recorded = True
|
| 453 |
+
picked_kernel_name = self.kernels[self.picked_kernel].inductor_meta.get(
|
| 454 |
+
"kernel_name"
|
| 455 |
+
)
|
| 456 |
+
assert picked_kernel_name is not None
|
| 457 |
+
self.record_choice(self.multi_kernel_name, picked_kernel_name)
|
| 458 |
+
|
| 459 |
+
run = self.kernels[self.picked_kernel].run # type: ignore[method-assign]
|
| 460 |
+
filtered_args = self._get_filtered_args(args, self.picked_kernel)
|
| 461 |
+
run(*filtered_args, **kwargs)
|
| 462 |
+
|
| 463 |
+
def _get_shape_cache_key(self, *args, **kwargs):
|
| 464 |
+
"""
|
| 465 |
+
Generate a cache key based on tensor shapes for shape-specialized dispatch.
|
| 466 |
+
"""
|
| 467 |
+
shapes = []
|
| 468 |
+
for arg in args:
|
| 469 |
+
if hasattr(arg, "shape"):
|
| 470 |
+
shapes.append(tuple(arg.shape))
|
| 471 |
+
return tuple(shapes)
|
| 472 |
+
|
| 473 |
+
def _get_cached_shape_choice(self, cache_key):
|
| 474 |
+
"""
|
| 475 |
+
Get cached kernel choice for a specific shape.
|
| 476 |
+
"""
|
| 477 |
+
return self._shape_cache.get(cache_key)
|
| 478 |
+
|
| 479 |
+
def _cache_shape_choice(self, cache_key, kernel_idx):
|
| 480 |
+
"""
|
| 481 |
+
Cache kernel choice for a specific shape
|
| 482 |
+
"""
|
| 483 |
+
self._shape_cache[cache_key] = kernel_idx
|
| 484 |
+
|
| 485 |
+
def _select_kernel_by_shape(self, *args, **kwargs):
|
| 486 |
+
"""
|
| 487 |
+
Benchmark kernels for a particular shape and return the
|
| 488 |
+
best kernel for this shape.
|
| 489 |
+
"""
|
| 490 |
+
shape_key = self._get_shape_cache_key(*args, **kwargs)
|
| 491 |
+
timings = self.benchmark_sub_kernels(*args, **kwargs)
|
| 492 |
+
self.picked_kernel = timings.index(min(timings))
|
| 493 |
+
self._cache_shape_choice(shape_key, self.picked_kernel)
|
| 494 |
+
|
| 495 |
+
def _metrics_table_row(self, timings):
|
| 496 |
+
def get_kernel_path(k):
|
| 497 |
+
return k.fn.fn.__code__.co_filename
|
| 498 |
+
|
| 499 |
+
k0 = self.kernels[0]
|
| 500 |
+
row = {
|
| 501 |
+
"size_hints": k0.size_hints,
|
| 502 |
+
"reduction_hint": k0.inductor_meta.get("reduction_hint"),
|
| 503 |
+
}
|
| 504 |
+
max_kernels = 4
|
| 505 |
+
assert len(timings) <= max_kernels
|
| 506 |
+
for i in range(max_kernels):
|
| 507 |
+
if i < len(self.kernels):
|
| 508 |
+
row[f"kernel{i}_path"] = get_kernel_path(self.kernels[i])
|
| 509 |
+
row[f"kernel{i}_latency"] = timings[i]
|
| 510 |
+
else:
|
| 511 |
+
row[f"kernel{i}_path"] = ""
|
| 512 |
+
row[f"kernel{i}_latency"] = ""
|
| 513 |
+
return row
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/python_wrapper_mtia.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
from typing_extensions import override
|
| 3 |
+
|
| 4 |
+
from torch._inductor import ir
|
| 5 |
+
|
| 6 |
+
from .wrapper import PythonWrapperCodegen
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PythonWrapperMtia(PythonWrapperCodegen):
|
| 10 |
+
"""
|
| 11 |
+
A thin wrapper of PythonWrapperCodegen with MTIA specific logic
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
@override
|
| 15 |
+
def write_header(self) -> None:
|
| 16 |
+
super().write_header()
|
| 17 |
+
|
| 18 |
+
# MITA specific imports
|
| 19 |
+
self.imports.splice("import mtia.host_runtime.torch_mtia.dynamic_library")
|
| 20 |
+
|
| 21 |
+
@override
|
| 22 |
+
@staticmethod
|
| 23 |
+
def create(
|
| 24 |
+
is_subgraph: bool,
|
| 25 |
+
subgraph_name: Optional[str],
|
| 26 |
+
parent_wrapper: Optional[PythonWrapperCodegen],
|
| 27 |
+
partition_signatures: Optional[ir.GraphPartitionSignature] = None,
|
| 28 |
+
) -> PythonWrapperCodegen:
|
| 29 |
+
if is_subgraph:
|
| 30 |
+
# Delegate to the parent class to handle the case of subgraph
|
| 31 |
+
return PythonWrapperCodegen.create(
|
| 32 |
+
is_subgraph, subgraph_name, parent_wrapper, partition_signatures
|
| 33 |
+
)
|
| 34 |
+
return PythonWrapperMtia()
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/__init__.py
ADDED
|
File without changes
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (211 Bytes). View file
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/__pycache__/compile_command.cpython-311.pyc
ADDED
|
Binary file (7.48 kB). View file
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_conv_template.py
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import copy
|
| 3 |
+
import logging
|
| 4 |
+
import random
|
| 5 |
+
from typing import Any
|
| 6 |
+
from typing_extensions import override
|
| 7 |
+
|
| 8 |
+
from torch._inductor.virtualized import V
|
| 9 |
+
|
| 10 |
+
from .rocm_template import ArgInfo
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
import ck4inductor # type: ignore[import]
|
| 15 |
+
except ImportError:
|
| 16 |
+
ck4inductor = None
|
| 17 |
+
|
| 18 |
+
if ck4inductor is not None:
|
| 19 |
+
from ck4inductor.grouped_conv_fwd.gen_instances import ( # type: ignore[import]
|
| 20 |
+
gen_conv_ops_library,
|
| 21 |
+
)
|
| 22 |
+
from ck4inductor.grouped_conv_fwd.op import ( # type: ignore[import] # noqa: TCH002
|
| 23 |
+
CKGroupedConvFwdOp,
|
| 24 |
+
)
|
| 25 |
+
else:
|
| 26 |
+
|
| 27 |
+
def gen_conv_ops_library():
|
| 28 |
+
return []
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
from torch._inductor import config
|
| 32 |
+
from torch._inductor.codegen.rocm.ck_template import CKTemplate
|
| 33 |
+
from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel
|
| 34 |
+
from torch._inductor.utils import IndentedBuffer
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
log = logging.getLogger(__name__)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def torch_layout_to_ck_layouts(torch_layout):
|
| 41 |
+
# logically, torch tensors are always NCHW,
|
| 42 |
+
# and channels-last memory layout is visible in the strides
|
| 43 |
+
if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1):
|
| 44 |
+
# when input or output is NCHW
|
| 45 |
+
# NB: torch.conv2d result is always NCHW
|
| 46 |
+
return ["NGCHW", "GKCYX", "NGKHW"]
|
| 47 |
+
elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1):
|
| 48 |
+
# when input or output or weight is channels-last
|
| 49 |
+
return ["NHWGC", "GKYXC", "NHWGK"]
|
| 50 |
+
else:
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def torch_layout_to_ck_input_layout(torch_layout):
|
| 55 |
+
if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1):
|
| 56 |
+
return "NGCHW"
|
| 57 |
+
elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1):
|
| 58 |
+
return "NHWGC"
|
| 59 |
+
else:
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def torch_layout_to_ck_weight_layout(torch_layout):
|
| 64 |
+
if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1):
|
| 65 |
+
return "GKCYX"
|
| 66 |
+
elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1):
|
| 67 |
+
return "GKYXC"
|
| 68 |
+
else:
|
| 69 |
+
return None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def torch_layout_to_ck_output_layout(torch_layout):
|
| 73 |
+
if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1):
|
| 74 |
+
return "NGKHW"
|
| 75 |
+
elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-3], 1):
|
| 76 |
+
return "NHWGK"
|
| 77 |
+
else:
|
| 78 |
+
return None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class CKGroupedConvFwdTemplate(CKTemplate):
|
| 82 |
+
conv_template = r"""
|
| 83 |
+
{{headers}}
|
| 84 |
+
{{globals}}
|
| 85 |
+
{{instance_definition}}
|
| 86 |
+
extern "C" {
|
| 87 |
+
PT_EXPORT {{kernel_definition}} {
|
| 88 |
+
auto conv = {{instance_type}} {};
|
| 89 |
+
auto invoker = conv.MakeInvoker();
|
| 90 |
+
|
| 91 |
+
using ck::index_t;
|
| 92 |
+
|
| 93 |
+
constexpr index_t NumDTensor = {{n_d_tensors}};
|
| 94 |
+
constexpr index_t NDimSpatial = {{n_dim_spatial}};
|
| 95 |
+
const std::vector<index_t> FilterSize = { FilterSize_0, FilterSize_1 };
|
| 96 |
+
const std::vector<index_t> InputSize = { InputSize_0, InputSize_1 };
|
| 97 |
+
const std::vector<index_t> ConvolutionStrides = { ConvolutionStrides_0, ConvolutionStrides_1 };
|
| 98 |
+
const std::vector<index_t> Dilations = { Dilations_0, Dilations_1 };
|
| 99 |
+
const std::vector<index_t> LeftPads = { LeftPads_0, LeftPads_1 };
|
| 100 |
+
const std::vector<index_t> RightPads = { RightPads_0, RightPads_1 };
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
auto conv_param = ck::utils::conv::ConvParam {
|
| 104 |
+
NDimSpatial,
|
| 105 |
+
GroupCount,
|
| 106 |
+
NBatch,
|
| 107 |
+
NOutChannels,
|
| 108 |
+
NInChannels,
|
| 109 |
+
FilterSize,
|
| 110 |
+
InputSize,
|
| 111 |
+
ConvolutionStrides,
|
| 112 |
+
Dilations,
|
| 113 |
+
LeftPads,
|
| 114 |
+
RightPads,
|
| 115 |
+
};
|
| 116 |
+
|
| 117 |
+
using InLayout = ck::tensor_layout::convolution::{{input_layout}};
|
| 118 |
+
using WeiLayout = ck::tensor_layout::convolution::{{weight_layout}};
|
| 119 |
+
using OutLayout = ck::tensor_layout::convolution::{{output_layout}};
|
| 120 |
+
|
| 121 |
+
const auto in_g_n_c_wis_desc =
|
| 122 |
+
ck::utils::conv::make_input_host_tensor_descriptor_g_n_c_wis_packed<InLayout>(conv_param);
|
| 123 |
+
const auto wei_g_k_c_xs_desc =
|
| 124 |
+
ck::utils::conv::make_weight_host_tensor_descriptor_g_k_c_xs_packed<WeiLayout>(conv_param);
|
| 125 |
+
const auto out_g_n_k_wos_desc =
|
| 126 |
+
ck::utils::conv::make_output_host_tensor_descriptor_g_n_k_wos_packed<OutLayout>(conv_param);
|
| 127 |
+
|
| 128 |
+
const void* p_a = input;
|
| 129 |
+
const void* p_b = weight;
|
| 130 |
+
const std::array<const void*, NumDTensor> p_ds;
|
| 131 |
+
void* p_e = output;
|
| 132 |
+
std::array<index_t, NDimSpatial + 3> a_g_n_c_wis_lengths;
|
| 133 |
+
std::array<index_t, NDimSpatial + 3> a_g_n_c_wis_strides;
|
| 134 |
+
std::array<index_t, NDimSpatial + 3> b_g_k_c_xs_lengths;
|
| 135 |
+
std::array<index_t, NDimSpatial + 3> b_g_k_c_xs_strides;
|
| 136 |
+
std::array<std::array<index_t, NDimSpatial + 3>, NumDTensor> ds_g_n_k_wos_lengths;
|
| 137 |
+
std::array<std::array<index_t, NDimSpatial + 3>, NumDTensor> ds_g_n_k_wos_strides;
|
| 138 |
+
std::array<index_t, NDimSpatial + 3> e_g_n_k_wos_lengths;
|
| 139 |
+
std::array<index_t, NDimSpatial + 3> e_g_n_k_wos_strides;
|
| 140 |
+
std::array<index_t, NDimSpatial> conv_filter_strides;
|
| 141 |
+
std::array<index_t, NDimSpatial> conv_filter_dilations;
|
| 142 |
+
std::array<index_t, NDimSpatial> input_left_pads;
|
| 143 |
+
std::array<index_t, NDimSpatial> input_right_pads;
|
| 144 |
+
const auto a_element_op = PassThrough {};
|
| 145 |
+
const auto b_element_op = PassThrough {};
|
| 146 |
+
const auto cde_element_op = PassThrough {};
|
| 147 |
+
|
| 148 |
+
auto copy = [](auto& x, auto& y) { ck::ranges::copy(x, y.begin()); };
|
| 149 |
+
|
| 150 |
+
copy(in_g_n_c_wis_desc.GetLengths(), a_g_n_c_wis_lengths);
|
| 151 |
+
copy(in_g_n_c_wis_desc.GetStrides(), a_g_n_c_wis_strides);
|
| 152 |
+
copy(wei_g_k_c_xs_desc.GetLengths(), b_g_k_c_xs_lengths);
|
| 153 |
+
copy(wei_g_k_c_xs_desc.GetStrides(), b_g_k_c_xs_strides);
|
| 154 |
+
copy(out_g_n_k_wos_desc.GetLengths(), e_g_n_k_wos_lengths);
|
| 155 |
+
copy(out_g_n_k_wos_desc.GetStrides(), e_g_n_k_wos_strides);
|
| 156 |
+
copy(conv_param.conv_filter_strides_, conv_filter_strides);
|
| 157 |
+
copy(conv_param.conv_filter_dilations_, conv_filter_dilations);
|
| 158 |
+
copy(conv_param.input_left_pads_, input_left_pads);
|
| 159 |
+
copy(conv_param.input_right_pads_, input_right_pads);
|
| 160 |
+
|
| 161 |
+
auto argument = conv.MakeArgument(
|
| 162 |
+
p_a,
|
| 163 |
+
p_b,
|
| 164 |
+
p_ds,
|
| 165 |
+
p_e,
|
| 166 |
+
a_g_n_c_wis_lengths,
|
| 167 |
+
a_g_n_c_wis_strides,
|
| 168 |
+
b_g_k_c_xs_lengths,
|
| 169 |
+
b_g_k_c_xs_strides,
|
| 170 |
+
ds_g_n_k_wos_lengths,
|
| 171 |
+
ds_g_n_k_wos_strides,
|
| 172 |
+
e_g_n_k_wos_lengths,
|
| 173 |
+
e_g_n_k_wos_strides,
|
| 174 |
+
conv_filter_strides,
|
| 175 |
+
conv_filter_dilations,
|
| 176 |
+
input_left_pads,
|
| 177 |
+
input_right_pads,
|
| 178 |
+
a_element_op,
|
| 179 |
+
b_element_op,
|
| 180 |
+
cde_element_op
|
| 181 |
+
);
|
| 182 |
+
if (!conv.IsSupportedArgument(argument)) {
|
| 183 |
+
// we do our best to statically avoid this case in `filter_op`
|
| 184 |
+
std::cerr << "invalid argument for conv instance " << conv.GetTypeString() << std::endl;
|
| 185 |
+
argument.Print();
|
| 186 |
+
return -23;
|
| 187 |
+
}
|
| 188 |
+
if (workspace_size) {
|
| 189 |
+
*workspace_size = conv.GetWorkSpaceSize(&argument);
|
| 190 |
+
return 0;
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
if (p_a == nullptr) {
|
| 194 |
+
std::cerr << "p_a is nullptr" << std::endl;
|
| 195 |
+
return -1;
|
| 196 |
+
}
|
| 197 |
+
if (p_b == nullptr) {
|
| 198 |
+
std::cerr << "p_b is nullptr" << std::endl;
|
| 199 |
+
return -1;
|
| 200 |
+
}
|
| 201 |
+
if (p_e == nullptr) {
|
| 202 |
+
std::cerr << "p_e is nullptr" << std::endl;
|
| 203 |
+
return -1;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
// when debugging, do time kernel to serialize launches
|
| 207 |
+
auto stream_config = StreamConfig{stream, /* time kernel */ false, /* log level */ 0};
|
| 208 |
+
|
| 209 |
+
if (workspace != nullptr) {
|
| 210 |
+
conv.SetWorkSpacePointer(&argument, workspace, stream_config);
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
// run the kernel
|
| 214 |
+
float elapsed_time = invoker.Run(argument, stream_config);
|
| 215 |
+
return 0;
|
| 216 |
+
} // kernel definition
|
| 217 |
+
} // extern C
|
| 218 |
+
|
| 219 |
+
#ifdef GENERATE_CK_STANDALONE_RUNNER
|
| 220 |
+
int main(int argc, char** argv) {
|
| 221 |
+
(void) argc;
|
| 222 |
+
(void) argv;
|
| 223 |
+
return 0;
|
| 224 |
+
}
|
| 225 |
+
#endif // GENERATE_CK_STANDALONE_RUNNER
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
def globals(self) -> IndentedBuffer:
|
| 229 |
+
res = super().globals()
|
| 230 |
+
res.splice(
|
| 231 |
+
"""
|
| 232 |
+
// CK conv globals
|
| 233 |
+
|
| 234 |
+
using NWC = ck::tensor_layout::convolution::NWC;
|
| 235 |
+
using NHWC = ck::tensor_layout::convolution::NHWC;
|
| 236 |
+
using NDHWC = ck::tensor_layout::convolution::NDHWC;
|
| 237 |
+
|
| 238 |
+
using KXC = ck::tensor_layout::convolution::KXC;
|
| 239 |
+
using KYXC = ck::tensor_layout::convolution::KYXC;
|
| 240 |
+
using KZYXC = ck::tensor_layout::convolution::KZYXC;
|
| 241 |
+
|
| 242 |
+
using NWK = ck::tensor_layout::convolution::NWK;
|
| 243 |
+
using NHWK = ck::tensor_layout::convolution::NHWK;
|
| 244 |
+
using NDHWK = ck::tensor_layout::convolution::NDHWK;
|
| 245 |
+
|
| 246 |
+
using GNWC = ck::tensor_layout::convolution::GNWC;
|
| 247 |
+
using GNHWC = ck::tensor_layout::convolution::GNHWC;
|
| 248 |
+
using GNDHWC = ck::tensor_layout::convolution::GNDHWC;
|
| 249 |
+
|
| 250 |
+
using GKXC = ck::tensor_layout::convolution::GKXC;
|
| 251 |
+
using GKYXC = ck::tensor_layout::convolution::GKYXC;
|
| 252 |
+
using GKZYXC = ck::tensor_layout::convolution::GKZYXC;
|
| 253 |
+
|
| 254 |
+
using GKCX = ck::tensor_layout::convolution::GKCX;
|
| 255 |
+
using GKCYX = ck::tensor_layout::convolution::GKCYX;
|
| 256 |
+
using GKCZYX = ck::tensor_layout::convolution::GKCZYX;
|
| 257 |
+
|
| 258 |
+
using GNWK = ck::tensor_layout::convolution::GNWK;
|
| 259 |
+
using GNHWK = ck::tensor_layout::convolution::GNHWK;
|
| 260 |
+
using GNDHWK = ck::tensor_layout::convolution::GNDHWK;
|
| 261 |
+
|
| 262 |
+
using NGKW = ck::tensor_layout::convolution::NGKW;
|
| 263 |
+
using NGKHW = ck::tensor_layout::convolution::NGKHW;
|
| 264 |
+
using NGKDHW = ck::tensor_layout::convolution::NGKDHW;
|
| 265 |
+
|
| 266 |
+
using NWGC = ck::tensor_layout::convolution::NWGC;
|
| 267 |
+
using NHWGC = ck::tensor_layout::convolution::NHWGC;
|
| 268 |
+
using NDHWGC = ck::tensor_layout::convolution::NDHWGC;
|
| 269 |
+
|
| 270 |
+
using KXGC = ck::tensor_layout::convolution::KXGC;
|
| 271 |
+
using KYXGC = ck::tensor_layout::convolution::KYXGC;
|
| 272 |
+
using KZYXGC = ck::tensor_layout::convolution::KZYXGC;
|
| 273 |
+
|
| 274 |
+
using NWGK = ck::tensor_layout::convolution::NWGK;
|
| 275 |
+
using NHWGK = ck::tensor_layout::convolution::NHWGK;
|
| 276 |
+
using NDHWGK = ck::tensor_layout::convolution::NDHWGK;
|
| 277 |
+
|
| 278 |
+
using NGCW = ck::tensor_layout::convolution::NGCW;
|
| 279 |
+
using NGCHW = ck::tensor_layout::convolution::NGCHW;
|
| 280 |
+
using NGCDHW = ck::tensor_layout::convolution::NGCDHW;
|
| 281 |
+
|
| 282 |
+
using G_K = ck::tensor_layout::convolution::G_K;
|
| 283 |
+
|
| 284 |
+
using BlockGemmPipelineScheduler = ck::BlockGemmPipelineScheduler;
|
| 285 |
+
using GemmSpecialization = ck::tensor_operation::device::GemmSpecialization;
|
| 286 |
+
using BlockGemmPipelineVersion = ck::BlockGemmPipelineVersion;
|
| 287 |
+
|
| 288 |
+
using ConvolutionForwardSpecialization = ck::tensor_operation::device::ConvolutionForwardSpecialization;
|
| 289 |
+
|
| 290 |
+
using OutElementOp = PassThrough;
|
| 291 |
+
|
| 292 |
+
namespace ck {
|
| 293 |
+
namespace utils {
|
| 294 |
+
namespace conv {
|
| 295 |
+
|
| 296 |
+
ConvParam::ConvParam(ck::index_t n_dim,
|
| 297 |
+
ck::index_t group_count,
|
| 298 |
+
ck::index_t n_batch,
|
| 299 |
+
ck::index_t n_out_channels,
|
| 300 |
+
ck::index_t n_in_channels,
|
| 301 |
+
const std::vector<ck::index_t>& filters_len,
|
| 302 |
+
const std::vector<ck::index_t>& input_len,
|
| 303 |
+
const std::vector<ck::index_t>& strides,
|
| 304 |
+
const std::vector<ck::index_t>& dilations,
|
| 305 |
+
const std::vector<ck::index_t>& left_pads,
|
| 306 |
+
const std::vector<ck::index_t>& right_pads)
|
| 307 |
+
: num_dim_spatial_(static_cast<ck::long_index_t>(n_dim)),
|
| 308 |
+
G_(static_cast<ck::long_index_t>(group_count)),
|
| 309 |
+
N_(static_cast<ck::long_index_t>(n_batch)),
|
| 310 |
+
K_(static_cast<ck::long_index_t>(n_out_channels)),
|
| 311 |
+
C_(static_cast<ck::long_index_t>(n_in_channels)),
|
| 312 |
+
filter_spatial_lengths_(num_dim_spatial_),
|
| 313 |
+
input_spatial_lengths_(num_dim_spatial_),
|
| 314 |
+
output_spatial_lengths_(num_dim_spatial_),
|
| 315 |
+
conv_filter_strides_(num_dim_spatial_),
|
| 316 |
+
conv_filter_dilations_(num_dim_spatial_),
|
| 317 |
+
input_left_pads_(num_dim_spatial_),
|
| 318 |
+
input_right_pads_(num_dim_spatial_)
|
| 319 |
+
{
|
| 320 |
+
if(static_cast<ck::index_t>(filter_spatial_lengths_.size()) != num_dim_spatial_ ||
|
| 321 |
+
static_cast<ck::index_t>(input_spatial_lengths_.size()) != num_dim_spatial_ ||
|
| 322 |
+
static_cast<ck::index_t>(conv_filter_strides_.size()) != num_dim_spatial_ ||
|
| 323 |
+
static_cast<ck::index_t>(conv_filter_dilations_.size()) != num_dim_spatial_ ||
|
| 324 |
+
static_cast<ck::index_t>(input_left_pads_.size()) != num_dim_spatial_ ||
|
| 325 |
+
static_cast<ck::index_t>(input_right_pads_.size()) != num_dim_spatial_)
|
| 326 |
+
{
|
| 327 |
+
throw(
|
| 328 |
+
std::runtime_error("ConvParam::ConvParam: "
|
| 329 |
+
"parameter size is different from number of declared dimensions!"));
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
for(ck::index_t i = 0; i < num_dim_spatial_; ++i)
|
| 333 |
+
{
|
| 334 |
+
filter_spatial_lengths_[i] = static_cast<ck::long_index_t>(filters_len[i]);
|
| 335 |
+
input_spatial_lengths_[i] = static_cast<ck::long_index_t>(input_len[i]);
|
| 336 |
+
conv_filter_strides_[i] = static_cast<ck::long_index_t>(strides[i]);
|
| 337 |
+
conv_filter_dilations_[i] = static_cast<ck::long_index_t>(dilations[i]);
|
| 338 |
+
input_left_pads_[i] = static_cast<ck::long_index_t>(left_pads[i]);
|
| 339 |
+
input_right_pads_[i] = static_cast<ck::long_index_t>(right_pads[i]);
|
| 340 |
+
|
| 341 |
+
// XEff = (X - 1) * conv_dilation_w + 1;
|
| 342 |
+
// Wo = (Wi + in_left_pad_w + in_right_pad_w - XEff) / conv_stride_w + 1;
|
| 343 |
+
const ck::long_index_t x_eff =
|
| 344 |
+
(filter_spatial_lengths_[i] - 1) * conv_filter_dilations_[i] + 1;
|
| 345 |
+
|
| 346 |
+
output_spatial_lengths_[i] =
|
| 347 |
+
(input_spatial_lengths_[i] + input_left_pads_[i] + input_right_pads_[i] - x_eff) /
|
| 348 |
+
conv_filter_strides_[i] +
|
| 349 |
+
1;
|
| 350 |
+
}
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
} // namespace conv
|
| 354 |
+
} // namespace utils
|
| 355 |
+
} // namespace ck
|
| 356 |
+
|
| 357 |
+
const std::vector<std::size_t>& HostTensorDescriptor::GetLengths() const { return mLens; }
|
| 358 |
+
const std::vector<std::size_t>& HostTensorDescriptor::GetStrides() const { return mStrides; }
|
| 359 |
+
std::size_t HostTensorDescriptor::GetNumOfDimension() const { return mLens.size(); }
|
| 360 |
+
void HostTensorDescriptor::CalculateStrides() {
|
| 361 |
+
mStrides.clear();
|
| 362 |
+
mStrides.resize(mLens.size(), 0);
|
| 363 |
+
if(mStrides.empty())
|
| 364 |
+
return;
|
| 365 |
+
|
| 366 |
+
mStrides.back() = 1;
|
| 367 |
+
std::partial_sum(
|
| 368 |
+
mLens.rbegin(), mLens.rend() - 1, mStrides.rbegin() + 1, std::multiplies<std::size_t>());
|
| 369 |
+
}
|
| 370 |
+
"""
|
| 371 |
+
)
|
| 372 |
+
return res
|
| 373 |
+
|
| 374 |
+
def header(self) -> IndentedBuffer:
|
| 375 |
+
res = super().header()
|
| 376 |
+
res.splice(
|
| 377 |
+
"""
|
| 378 |
+
// CK conv headers
|
| 379 |
+
|
| 380 |
+
#include "ck/tensor_operation/gpu/device/impl/device_grouped_conv_fwd_multiple_abd_xdl_cshuffle_v3.hpp"
|
| 381 |
+
#include "ck/tensor_operation/gpu/device/convolution_forward_specialization.hpp"
|
| 382 |
+
#include "ck/tensor_operation/gpu/device/gemm_specialization.hpp"
|
| 383 |
+
|
| 384 |
+
#include "ck/library/utility/convolution_parameter.hpp"
|
| 385 |
+
#include "ck/library/utility/convolution_host_tensor_descriptor_helper.hpp"
|
| 386 |
+
"""
|
| 387 |
+
)
|
| 388 |
+
return res
|
| 389 |
+
|
| 390 |
+
@staticmethod
|
| 391 |
+
def add_ck_conv_choices(
|
| 392 |
+
choices,
|
| 393 |
+
layout,
|
| 394 |
+
input_nodes,
|
| 395 |
+
*,
|
| 396 |
+
stride,
|
| 397 |
+
padding,
|
| 398 |
+
dilation,
|
| 399 |
+
groups,
|
| 400 |
+
n_spatial_dimensions,
|
| 401 |
+
):
|
| 402 |
+
template = CKGroupedConvFwdTemplate(
|
| 403 |
+
input_nodes,
|
| 404 |
+
layout,
|
| 405 |
+
stride=stride,
|
| 406 |
+
padding=padding,
|
| 407 |
+
dilation=dilation,
|
| 408 |
+
groups=groups,
|
| 409 |
+
n_spatial_dimensions=n_spatial_dimensions,
|
| 410 |
+
)
|
| 411 |
+
ops = template.gen_ops()
|
| 412 |
+
for op in ops:
|
| 413 |
+
template.maybe_append_choice(
|
| 414 |
+
choices,
|
| 415 |
+
op=op,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
def __init__(
|
| 419 |
+
self,
|
| 420 |
+
input_nodes,
|
| 421 |
+
layout,
|
| 422 |
+
*,
|
| 423 |
+
stride,
|
| 424 |
+
padding,
|
| 425 |
+
dilation,
|
| 426 |
+
groups,
|
| 427 |
+
n_spatial_dimensions,
|
| 428 |
+
):
|
| 429 |
+
super().__init__(
|
| 430 |
+
"ck_conv_template",
|
| 431 |
+
input_nodes,
|
| 432 |
+
layout,
|
| 433 |
+
)
|
| 434 |
+
self.stride = stride
|
| 435 |
+
self.padding = padding
|
| 436 |
+
self.dilation = dilation
|
| 437 |
+
self.groups = groups
|
| 438 |
+
self.n_spatial_dimensions = n_spatial_dimensions
|
| 439 |
+
|
| 440 |
+
def filter_op(self, op: "CKGroupedConvFwdOp"): # type: ignore[name-defined]
|
| 441 |
+
metas = [
|
| 442 |
+
T.get_layout()
|
| 443 |
+
for T in [*self.input_nodes, self.output_node]
|
| 444 |
+
if T is not None
|
| 445 |
+
]
|
| 446 |
+
X_meta = metas[0]
|
| 447 |
+
W_meta = metas[1]
|
| 448 |
+
Y_meta = metas[-1]
|
| 449 |
+
# disable the instance if dtypes don't match
|
| 450 |
+
if op.a_element_dtype != self._TORCH_DTYPE_TO_CK[X_meta.dtype]:
|
| 451 |
+
return None
|
| 452 |
+
if op.b_element_dtype != self._TORCH_DTYPE_TO_CK[W_meta.dtype]:
|
| 453 |
+
return None
|
| 454 |
+
if op.e_element_dtype != self._TORCH_DTYPE_TO_CK[Y_meta.dtype]:
|
| 455 |
+
return None
|
| 456 |
+
# disable the instance if layouts don't match
|
| 457 |
+
if op.a_layout != torch_layout_to_ck_input_layout(X_meta):
|
| 458 |
+
return None
|
| 459 |
+
if op.b_layout != torch_layout_to_ck_weight_layout(W_meta):
|
| 460 |
+
return None
|
| 461 |
+
if op.e_layout != torch_layout_to_ck_output_layout(Y_meta):
|
| 462 |
+
return None
|
| 463 |
+
# disable the instance if number of spatial dimensions doesn't match
|
| 464 |
+
if op.n_dim_spatial != self.n_spatial_dimensions:
|
| 465 |
+
return None
|
| 466 |
+
# disable 1x1 and odd-channels conv specializations for now
|
| 467 |
+
if "Default" not in op.conv_forward_specialization:
|
| 468 |
+
return None
|
| 469 |
+
return op
|
| 470 |
+
|
| 471 |
+
def gen_ops(self):
|
| 472 |
+
unfiltered_instances = gen_conv_ops_library()
|
| 473 |
+
|
| 474 |
+
filtered_instances = list(
|
| 475 |
+
filter(lambda op: self.filter_op(op), unfiltered_instances)
|
| 476 |
+
)
|
| 477 |
+
# NB: when using a fixed list order, most likely we will pick the subset of instances
|
| 478 |
+
# which are very similar to each other. Randomizing the choice seems to solve this.
|
| 479 |
+
random.seed(-11)
|
| 480 |
+
chosen_instances = (
|
| 481 |
+
random.sample(
|
| 482 |
+
filtered_instances,
|
| 483 |
+
min(len(filtered_instances), config.rocm.ck_max_profiling_configs),
|
| 484 |
+
)
|
| 485 |
+
if config.rocm.ck_max_profiling_configs
|
| 486 |
+
else filtered_instances
|
| 487 |
+
)
|
| 488 |
+
log.debug(
|
| 489 |
+
"generated %d ck instances after filter: %s",
|
| 490 |
+
len(chosen_instances),
|
| 491 |
+
chosen_instances,
|
| 492 |
+
)
|
| 493 |
+
return chosen_instances
|
| 494 |
+
|
| 495 |
+
def emit_ck_instance(self, op: "CKGroupedConvFwdOp") -> tuple[str, str]: # type: ignore[name-defined]
|
| 496 |
+
# The Jinja template for generating a C++ type alias *definition* for a Universal GEMM instance
|
| 497 |
+
template_definition = r"""
|
| 498 |
+
// Gemm operator {{operation_name}}
|
| 499 |
+
using Operation_{{operation_name}} =
|
| 500 |
+
ck::tensor_operation::device::DeviceGroupedConvFwdMultipleABD_Xdl_CShuffle_V3<
|
| 501 |
+
{{template_params}}>;
|
| 502 |
+
|
| 503 |
+
"""
|
| 504 |
+
# The Jinja template for generating a C++ type alias *usage* for a Universal GEMM instance
|
| 505 |
+
template_type = r"""
|
| 506 |
+
Operation_{{operation_name}}
|
| 507 |
+
"""
|
| 508 |
+
template_params = []
|
| 509 |
+
for field_name, field_value in op.dict_items():
|
| 510 |
+
if isinstance(field_value, tuple):
|
| 511 |
+
tuple_elements = ", ".join(map(str, iter(field_value)))
|
| 512 |
+
if "ds" in field_name: # element type and layout for bias
|
| 513 |
+
arg = f"/* {field_name} */ Tuple<{tuple_elements}>"
|
| 514 |
+
else: # tile shape
|
| 515 |
+
arg = f"/* {field_name} */ S<{tuple_elements}>"
|
| 516 |
+
template_params.append(arg)
|
| 517 |
+
else:
|
| 518 |
+
if field_value is not None:
|
| 519 |
+
template_params.append(f"/* {field_name} */ {field_value}")
|
| 520 |
+
return self._template_from_string(template_definition).render(
|
| 521 |
+
operation_name=op.name(),
|
| 522 |
+
template_params=(",\n" + 12 * " ").join(template_params),
|
| 523 |
+
), self._template_from_string(template_type).render(operation_name=op.name())
|
| 524 |
+
|
| 525 |
+
def render( # type: ignore[override]
|
| 526 |
+
self,
|
| 527 |
+
kernel: ROCmTemplateKernel,
|
| 528 |
+
op: "CKGroupedConvFwdOp", # type: ignore[name-defined]
|
| 529 |
+
**kwargs,
|
| 530 |
+
) -> str:
|
| 531 |
+
template_buffer_node = kwargs.get("template_buffer_node", None)
|
| 532 |
+
if template_buffer_node is not None:
|
| 533 |
+
self.output_node = template_buffer_node
|
| 534 |
+
X, W = self.input_nodes[0], self.input_nodes[1]
|
| 535 |
+
Y = self.output_node
|
| 536 |
+
Bias = self.input_nodes[2] if 3 == len(self.input_nodes) else None
|
| 537 |
+
|
| 538 |
+
op = copy.deepcopy(op)
|
| 539 |
+
|
| 540 |
+
instance_definition, instance_type = self.emit_ck_instance(op)
|
| 541 |
+
|
| 542 |
+
size_arg_strs = [
|
| 543 |
+
"GroupCount",
|
| 544 |
+
"NBatch",
|
| 545 |
+
"NOutChannels",
|
| 546 |
+
"NInChannels",
|
| 547 |
+
"FilterSize_0",
|
| 548 |
+
"FilterSize_1",
|
| 549 |
+
"InputSize_0",
|
| 550 |
+
"InputSize_1",
|
| 551 |
+
"ConvolutionStrides_0",
|
| 552 |
+
"ConvolutionStrides_1",
|
| 553 |
+
"Dilations_0",
|
| 554 |
+
"Dilations_1",
|
| 555 |
+
"LeftPads_0",
|
| 556 |
+
"LeftPads_1",
|
| 557 |
+
"RightPads_0",
|
| 558 |
+
"RightPads_1",
|
| 559 |
+
]
|
| 560 |
+
|
| 561 |
+
return self._template_from_string(self.conv_template).render(
|
| 562 |
+
headers=self.header().getvalue(),
|
| 563 |
+
globals=self.globals().getvalue(),
|
| 564 |
+
instance_definition=instance_definition,
|
| 565 |
+
instance_type=instance_type,
|
| 566 |
+
kernel_definition=kernel.def_kernel(
|
| 567 |
+
inputs=[X, W, Bias] if Bias is not None else [X, W],
|
| 568 |
+
outputs=[Y],
|
| 569 |
+
names_str="input, weight, bias, output"
|
| 570 |
+
if Bias is not None
|
| 571 |
+
else "input, weight, output",
|
| 572 |
+
size_args=[f"int32_t {arg}" for arg in size_arg_strs],
|
| 573 |
+
),
|
| 574 |
+
n_d_tensors=1 if Bias is not None else 0,
|
| 575 |
+
n_dim_spatial=self.n_spatial_dimensions,
|
| 576 |
+
input_layout=op.a_layout,
|
| 577 |
+
weight_layout=op.b_layout,
|
| 578 |
+
output_layout=op.e_layout,
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
def size_args(self):
|
| 582 |
+
x, w = self.input_nodes[0], self.input_nodes[1]
|
| 583 |
+
y = self.output_node
|
| 584 |
+
|
| 585 |
+
group_count = self.groups
|
| 586 |
+
n_batch = x.shape[0] # type: ignore[index]
|
| 587 |
+
n_out_channels = y.shape[1] # type: ignore[index]
|
| 588 |
+
n_in_channels = x.shape[1] # type: ignore[index]
|
| 589 |
+
|
| 590 |
+
filter_size_0, filter_size_1 = w.shape[2:4] # type: ignore[index]
|
| 591 |
+
input_size_0, input_size_1 = x.shape[2:4] # type: ignore[index]
|
| 592 |
+
convolution_strides_0, convolution_strides_1 = self.stride
|
| 593 |
+
dilations_0, dilations_1 = self.dilation
|
| 594 |
+
left_pads_0, left_pads_1 = self.padding
|
| 595 |
+
right_pads_0, right_pads_1 = self.padding
|
| 596 |
+
|
| 597 |
+
return (
|
| 598 |
+
group_count,
|
| 599 |
+
n_batch,
|
| 600 |
+
n_out_channels,
|
| 601 |
+
n_in_channels,
|
| 602 |
+
filter_size_0,
|
| 603 |
+
filter_size_1,
|
| 604 |
+
input_size_0,
|
| 605 |
+
input_size_1,
|
| 606 |
+
convolution_strides_0,
|
| 607 |
+
convolution_strides_1,
|
| 608 |
+
dilations_0,
|
| 609 |
+
dilations_1,
|
| 610 |
+
left_pads_0,
|
| 611 |
+
left_pads_1,
|
| 612 |
+
right_pads_0,
|
| 613 |
+
right_pads_1,
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
@override
|
| 617 |
+
def get_runtime_arg_info(self) -> list[ArgInfo]:
|
| 618 |
+
return []
|
| 619 |
+
|
| 620 |
+
@override
|
| 621 |
+
def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]:
|
| 622 |
+
"""
|
| 623 |
+
Helper method to retrieve runtime args from generate kwargs
|
| 624 |
+
"""
|
| 625 |
+
return []
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_template.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
from typing_extensions import override
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch._inductor.codegen.rocm.rocm_template import ROCmTemplate
|
| 6 |
+
from torch._inductor.ir import IRNode
|
| 7 |
+
from torch._inductor.utils import IndentedBuffer
|
| 8 |
+
|
| 9 |
+
from .rocm_template import ArgInfo
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CKTemplate(ROCmTemplate):
|
| 13 |
+
"""
|
| 14 |
+
Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
_TORCH_DTYPE_TO_CK = {
|
| 18 |
+
torch.float32: "F32",
|
| 19 |
+
torch.float64: "F64",
|
| 20 |
+
torch.float16: "F16",
|
| 21 |
+
torch.bfloat16: "BF16",
|
| 22 |
+
torch.int32: "I32",
|
| 23 |
+
torch.int8: "I8",
|
| 24 |
+
torch.float8_e4m3fnuz: "F8", # gfx94
|
| 25 |
+
torch.float8_e4m3fn: "F8", # gfx95
|
| 26 |
+
torch.float8_e5m2fnuz: "BF8", # gfx94
|
| 27 |
+
torch.float8_e5m2: "BF8", # gfx95
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
def header(self) -> IndentedBuffer:
|
| 31 |
+
res = super().header()
|
| 32 |
+
res.splice(
|
| 33 |
+
"""
|
| 34 |
+
// CK headers
|
| 35 |
+
|
| 36 |
+
#ifdef DEBUG_LOG
|
| 37 |
+
#define DEBUG_LOG_TMP DEBUG_LOG
|
| 38 |
+
#undef DEBUG_LOG
|
| 39 |
+
#else
|
| 40 |
+
#define DEBUG_LOG_TMP 0
|
| 41 |
+
#endif
|
| 42 |
+
#include "ck/ck.hpp"
|
| 43 |
+
#undef DEBUG_LOG
|
| 44 |
+
#define DEBUG_LOG DEBUG_LOG_TMP
|
| 45 |
+
|
| 46 |
+
#include "ck/utility/data_type.hpp"
|
| 47 |
+
#include "ck/library/utility/check_err.hpp"
|
| 48 |
+
#include "ck/library/utility/device_memory.hpp"
|
| 49 |
+
#include "ck/library/utility/fill.hpp"
|
| 50 |
+
#include "ck/library/utility/host_tensor.hpp"
|
| 51 |
+
#include "ck/library/utility/host_tensor_generator.hpp"
|
| 52 |
+
#include "ck/library/utility/literals.hpp"
|
| 53 |
+
"""
|
| 54 |
+
)
|
| 55 |
+
return res
|
| 56 |
+
|
| 57 |
+
def globals(self) -> IndentedBuffer:
|
| 58 |
+
res = super().globals()
|
| 59 |
+
res.splice(
|
| 60 |
+
"""
|
| 61 |
+
// CK globals
|
| 62 |
+
|
| 63 |
+
template <ck::index_t... Is>
|
| 64 |
+
using S = ck::Sequence<Is...>;
|
| 65 |
+
|
| 66 |
+
template<typename... Ts>
|
| 67 |
+
using Tuple = ck::Tuple<Ts...>;
|
| 68 |
+
|
| 69 |
+
using PassThrough = ck::tensor_operation::element_wise::PassThrough;
|
| 70 |
+
using Bilinear = ck::tensor_operation::element_wise::Bilinear;
|
| 71 |
+
using Scale = ck::tensor_operation::element_wise::Scale;
|
| 72 |
+
using ScaleAdd = ck::tensor_operation::element_wise::ScaleAdd;
|
| 73 |
+
using MultiplyMultiply = ck::tensor_operation::element_wise::MultiplyMultiply;
|
| 74 |
+
|
| 75 |
+
// see "composable_kernel/include/ck/utility/data_type.hpp"
|
| 76 |
+
using F8 = ck::f8_t;
|
| 77 |
+
using BF8 = ck::bf8_t;
|
| 78 |
+
using F16 = ck::half_t;
|
| 79 |
+
using F32 = float;
|
| 80 |
+
// using F64 = double;
|
| 81 |
+
using BF16 = ck::bhalf_t;
|
| 82 |
+
// using I32 = int32_t;
|
| 83 |
+
// using I8 = int8_t;
|
| 84 |
+
// using I4 = ck::int4_t;
|
| 85 |
+
|
| 86 |
+
#if DEBUG_LOG
|
| 87 |
+
static constexpr auto kDEBUG_LOG = 1;
|
| 88 |
+
#else
|
| 89 |
+
static constexpr auto kDEBUG_LOG = 0;
|
| 90 |
+
#endif
|
| 91 |
+
"""
|
| 92 |
+
)
|
| 93 |
+
return res
|
| 94 |
+
|
| 95 |
+
def torch_type_to_ck(self, node: IRNode, ptr: str) -> str:
|
| 96 |
+
if node is None:
|
| 97 |
+
return ptr
|
| 98 |
+
else:
|
| 99 |
+
return f"({self._TORCH_DTYPE_TO_CK.get(node.get_dtype())}*)({ptr})"
|
| 100 |
+
|
| 101 |
+
@override
|
| 102 |
+
def get_runtime_arg_info(self) -> list[ArgInfo]:
|
| 103 |
+
return [ArgInfo("kBatch", "int32_t")]
|
| 104 |
+
|
| 105 |
+
@override
|
| 106 |
+
def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]:
|
| 107 |
+
"""
|
| 108 |
+
Helper method to retrieve runtime args from generate kwargs
|
| 109 |
+
"""
|
| 110 |
+
return [kwargs[arg.name] for arg in self.get_runtime_arg_info()]
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_tile_template.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch._inductor.codegen.rocm.rocm_template import ROCmTemplate
|
| 3 |
+
from torch._inductor.ir import IRNode
|
| 4 |
+
from torch._inductor.utils import IndentedBuffer
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CKTileTemplate(ROCmTemplate):
|
| 8 |
+
"""
|
| 9 |
+
Base class for generating CK templates, has common, i.e. non-gemm-specific, code generation logic
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
_TORCH_DTYPE_TO_CK = {
|
| 13 |
+
torch.float32: "F32",
|
| 14 |
+
torch.float64: "F64",
|
| 15 |
+
torch.float16: "F16",
|
| 16 |
+
torch.bfloat16: "BF16",
|
| 17 |
+
torch.int32: "I32",
|
| 18 |
+
torch.int8: "I8",
|
| 19 |
+
torch.float8_e4m3fnuz: "F8", # gfx94
|
| 20 |
+
torch.float8_e4m3fn: "F8", # gfx95
|
| 21 |
+
torch.float8_e5m2fnuz: "BF8", # gfx94
|
| 22 |
+
torch.float8_e5m2: "BF8", # gfx95
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
ck_dtype_to_size = {
|
| 26 |
+
"FP16": 2,
|
| 27 |
+
"BF16": 2,
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
def header(self) -> IndentedBuffer:
|
| 31 |
+
res = super().header()
|
| 32 |
+
res.splice(
|
| 33 |
+
"""
|
| 34 |
+
// CK headers
|
| 35 |
+
#include "ck_tile/core.hpp"
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
)
|
| 39 |
+
return res
|
| 40 |
+
|
| 41 |
+
def globals(self) -> IndentedBuffer:
|
| 42 |
+
res = super().globals()
|
| 43 |
+
res.splice(
|
| 44 |
+
"""
|
| 45 |
+
using F8 = ck_tile::fp8_t;
|
| 46 |
+
using BF8 = ck_tile::bf8_t;
|
| 47 |
+
using F16 = ck_tile::half_t;
|
| 48 |
+
using F32 = float;
|
| 49 |
+
using BF16 = ck_tile::bfloat16_t;
|
| 50 |
+
"""
|
| 51 |
+
)
|
| 52 |
+
return res
|
| 53 |
+
|
| 54 |
+
def torch_type_to_ck(self, node: IRNode, ptr: str) -> str:
|
| 55 |
+
if node is None:
|
| 56 |
+
return ptr
|
| 57 |
+
else:
|
| 58 |
+
return f"({self._TORCH_DTYPE_TO_CK.get(node.get_dtype())}*)({ptr})"
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py
ADDED
|
@@ -0,0 +1,979 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs, disable-error-code="attr-defined, valid-type"
|
| 2 |
+
import functools
|
| 3 |
+
import logging
|
| 4 |
+
import random
|
| 5 |
+
from dataclasses import asdict, dataclass
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch._inductor import config
|
| 10 |
+
from torch._inductor.codegen.rocm.ck_tile_template import CKTileTemplate
|
| 11 |
+
from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel
|
| 12 |
+
from torch._inductor.codegen.rocm.rocm_template import ArgInfo
|
| 13 |
+
from torch._inductor.ir import Buffer, Layout
|
| 14 |
+
from torch.utils._ordered_set import OrderedSet
|
| 15 |
+
|
| 16 |
+
from ...utils import IndentedBuffer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
log = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def is_static_int(number):
|
| 23 |
+
import sympy
|
| 24 |
+
|
| 25 |
+
return isinstance(number, (int, sympy.Integer))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def torch_layout_to_ck_layout(torch_layout):
|
| 29 |
+
if torch_layout.stride[-1] == 1:
|
| 30 |
+
return "Row"
|
| 31 |
+
elif torch_layout.stride[-2] == 1:
|
| 32 |
+
return "Col"
|
| 33 |
+
else:
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass
|
| 38 |
+
class CKTileGemmOperation:
|
| 39 |
+
layout_a: str
|
| 40 |
+
layout_b: str
|
| 41 |
+
layout_c: str
|
| 42 |
+
|
| 43 |
+
datatype_a: str
|
| 44 |
+
datatype_b: str
|
| 45 |
+
datatype_c: str
|
| 46 |
+
|
| 47 |
+
tile_m: int
|
| 48 |
+
tile_n: int
|
| 49 |
+
tile_k: int
|
| 50 |
+
|
| 51 |
+
warp_m: int
|
| 52 |
+
warp_n: int
|
| 53 |
+
warp_k: int
|
| 54 |
+
|
| 55 |
+
warp_tile_m: int
|
| 56 |
+
warp_tile_n: int
|
| 57 |
+
warp_tile_k: int
|
| 58 |
+
|
| 59 |
+
m_is_padded: str
|
| 60 |
+
n_is_padded: str
|
| 61 |
+
k_is_padded: str
|
| 62 |
+
|
| 63 |
+
pipeline: str
|
| 64 |
+
scheduler: str
|
| 65 |
+
epilogue: str
|
| 66 |
+
|
| 67 |
+
def layout_repr(self):
|
| 68 |
+
return f"{self.layout_a[0]}{self.layout_b[0]}{self.layout_c[0]}"
|
| 69 |
+
|
| 70 |
+
def dtype_repr(self):
|
| 71 |
+
return f"{self.datatype_a}{self.datatype_b}{self.datatype_c}"
|
| 72 |
+
|
| 73 |
+
def tile_sizes(self):
|
| 74 |
+
return "_".join(
|
| 75 |
+
[
|
| 76 |
+
f"{self.tile_m}{self.tile_n}{self.tile_k}",
|
| 77 |
+
f"{self.warp_m}{self.warp_n}{self.warp_k}",
|
| 78 |
+
f"{self.warp_tile_m}{self.warp_tile_n}{self.warp_tile_k}",
|
| 79 |
+
]
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
def name(self):
|
| 83 |
+
return "ck_tile_gemm_universal_" + "_".join(
|
| 84 |
+
[
|
| 85 |
+
f"{self.layout_repr()}",
|
| 86 |
+
f"{self.dtype_repr()}",
|
| 87 |
+
f"{self.tile_sizes()}",
|
| 88 |
+
f"{self.pipeline}",
|
| 89 |
+
f"{self.scheduler}",
|
| 90 |
+
f"{self.epilogue}",
|
| 91 |
+
]
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def dict_items(self):
|
| 95 |
+
return asdict(self).items()
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@functools.cache
|
| 99 |
+
def ops():
|
| 100 |
+
"""
|
| 101 |
+
Generate the supported instance dataclasses
|
| 102 |
+
"""
|
| 103 |
+
import itertools
|
| 104 |
+
|
| 105 |
+
compute_v3_instances = [
|
| 106 |
+
CKTileGemmOperation(
|
| 107 |
+
layout_a=layout_a,
|
| 108 |
+
layout_b=layout_b,
|
| 109 |
+
layout_c=layout_c,
|
| 110 |
+
datatype_a=datatype_a,
|
| 111 |
+
datatype_b=datatype_b,
|
| 112 |
+
datatype_c=datatype_c,
|
| 113 |
+
tile_m=tile_m,
|
| 114 |
+
tile_n=tile_n,
|
| 115 |
+
tile_k=tile_k,
|
| 116 |
+
warp_m=warp_m,
|
| 117 |
+
warp_n=warp_n,
|
| 118 |
+
warp_k=warp_k,
|
| 119 |
+
warp_tile_m=warp_tile_m,
|
| 120 |
+
warp_tile_n=warp_tile_n,
|
| 121 |
+
warp_tile_k=warp_tile_k,
|
| 122 |
+
m_is_padded=m_is_padded,
|
| 123 |
+
n_is_padded=n_is_padded,
|
| 124 |
+
k_is_padded=k_is_padded,
|
| 125 |
+
pipeline="CompV3",
|
| 126 |
+
scheduler="Intrawave",
|
| 127 |
+
epilogue=epilogue,
|
| 128 |
+
)
|
| 129 |
+
for (layout_a, layout_b, layout_c) in [
|
| 130 |
+
("Row", "Row", "Row"),
|
| 131 |
+
("Row", "Col", "Row"),
|
| 132 |
+
]
|
| 133 |
+
for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3]
|
| 134 |
+
for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)]
|
| 135 |
+
for (warp_m, warp_n, warp_k) in [(2, 2, 1)]
|
| 136 |
+
for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)]
|
| 137 |
+
for m_is_padded in ["true", "false"]
|
| 138 |
+
for n_is_padded in ["true", "false"]
|
| 139 |
+
for k_is_padded in ["true", "false"]
|
| 140 |
+
for epilogue in ["Default", "CShuffle"]
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
compute_v4_instances = [
|
| 144 |
+
CKTileGemmOperation(
|
| 145 |
+
layout_a=layout_a,
|
| 146 |
+
layout_b=layout_b,
|
| 147 |
+
layout_c=layout_c,
|
| 148 |
+
datatype_a=datatype_a,
|
| 149 |
+
datatype_b=datatype_b,
|
| 150 |
+
datatype_c=datatype_c,
|
| 151 |
+
tile_m=tile_m,
|
| 152 |
+
tile_n=tile_n,
|
| 153 |
+
tile_k=tile_k,
|
| 154 |
+
warp_m=warp_m,
|
| 155 |
+
warp_n=warp_n,
|
| 156 |
+
warp_k=warp_k,
|
| 157 |
+
warp_tile_m=warp_tile_m,
|
| 158 |
+
warp_tile_n=warp_tile_n,
|
| 159 |
+
warp_tile_k=warp_tile_k,
|
| 160 |
+
m_is_padded=m_is_padded,
|
| 161 |
+
n_is_padded=n_is_padded,
|
| 162 |
+
k_is_padded=k_is_padded,
|
| 163 |
+
pipeline="CompV4",
|
| 164 |
+
scheduler="Intrawave",
|
| 165 |
+
epilogue=epilogue,
|
| 166 |
+
)
|
| 167 |
+
for (layout_a, layout_b, layout_c) in [
|
| 168 |
+
("Row", "Row", "Row"),
|
| 169 |
+
("Row", "Col", "Row"),
|
| 170 |
+
]
|
| 171 |
+
for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3]
|
| 172 |
+
for (tile_m, tile_n, tile_k) in [
|
| 173 |
+
(256, 256, 32)
|
| 174 |
+
] # half the tile size since it has double buffering
|
| 175 |
+
for (warp_m, warp_n, warp_k) in [(2, 2, 1)]
|
| 176 |
+
for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)]
|
| 177 |
+
for m_is_padded in ["true", "false"]
|
| 178 |
+
for n_is_padded in ["true", "false"]
|
| 179 |
+
for k_is_padded in ["true", "false"]
|
| 180 |
+
for epilogue in ["Default", "CShuffle"]
|
| 181 |
+
]
|
| 182 |
+
|
| 183 |
+
mem_instances = [
|
| 184 |
+
CKTileGemmOperation(
|
| 185 |
+
layout_a=layout_a,
|
| 186 |
+
layout_b=layout_b,
|
| 187 |
+
layout_c=layout_c,
|
| 188 |
+
datatype_a=datatype_a,
|
| 189 |
+
datatype_b=datatype_b,
|
| 190 |
+
datatype_c=datatype_c,
|
| 191 |
+
tile_m=tile_m,
|
| 192 |
+
tile_n=tile_n,
|
| 193 |
+
tile_k=tile_k,
|
| 194 |
+
warp_m=warp_m,
|
| 195 |
+
warp_n=warp_n,
|
| 196 |
+
warp_k=warp_k,
|
| 197 |
+
warp_tile_m=warp_tile_m,
|
| 198 |
+
warp_tile_n=warp_tile_n,
|
| 199 |
+
warp_tile_k=warp_tile_k,
|
| 200 |
+
m_is_padded=m_is_padded,
|
| 201 |
+
n_is_padded=n_is_padded,
|
| 202 |
+
k_is_padded=k_is_padded,
|
| 203 |
+
pipeline="Mem",
|
| 204 |
+
scheduler=scheduler,
|
| 205 |
+
epilogue=epilogue,
|
| 206 |
+
)
|
| 207 |
+
for (layout_a, layout_b, layout_c) in [
|
| 208 |
+
("Row", "Row", "Row"),
|
| 209 |
+
("Row", "Col", "Row"),
|
| 210 |
+
]
|
| 211 |
+
for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3]
|
| 212 |
+
for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)]
|
| 213 |
+
for (warp_m, warp_n, warp_k) in [(2, 2, 1)]
|
| 214 |
+
for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)]
|
| 215 |
+
for m_is_padded in ["true", "false"]
|
| 216 |
+
for n_is_padded in ["true", "false"]
|
| 217 |
+
for k_is_padded in ["true", "false"]
|
| 218 |
+
for scheduler in ["Intrawave", "Interwave"]
|
| 219 |
+
for epilogue in ["Default", "CShuffle"]
|
| 220 |
+
]
|
| 221 |
+
|
| 222 |
+
return list(
|
| 223 |
+
itertools.chain(compute_v3_instances, compute_v4_instances, mem_instances)
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
class CKTileGemmTemplate(CKTileTemplate):
|
| 228 |
+
"""
|
| 229 |
+
This class is used for rendering CK-Tile Universal GEMM kernels
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
gemm_template = r"""{{version_comment}}
|
| 233 |
+
{{headers}}
|
| 234 |
+
{{globals}}
|
| 235 |
+
{{instance_definition}}
|
| 236 |
+
extern "C" {
|
| 237 |
+
PT_EXPORT {{kernel_definition}} {
|
| 238 |
+
|
| 239 |
+
using {{instance_namespace}}::BaseGemmPipeline;
|
| 240 |
+
using {{instance_namespace}}::TilePartitioner;
|
| 241 |
+
|
| 242 |
+
constexpr auto TileK = {{instance_namespace}}::TileK;
|
| 243 |
+
constexpr auto kPrefetchStages = BaseGemmPipeline::PrefetchStages;
|
| 244 |
+
|
| 245 |
+
const auto BiasTerms = std::array<const void*, 0> ();
|
| 246 |
+
const auto BiasStrides = std::array<int32_t, 0> ();
|
| 247 |
+
|
| 248 |
+
auto kargs = ck_tile::UniversalGemmKernelArgs<> {
|
| 249 |
+
{X},
|
| 250 |
+
{W},
|
| 251 |
+
BiasTerms,
|
| 252 |
+
Y,
|
| 253 |
+
M,
|
| 254 |
+
N,
|
| 255 |
+
K,
|
| 256 |
+
{LDA},
|
| 257 |
+
{LDB},
|
| 258 |
+
BiasStrides,
|
| 259 |
+
LDC,
|
| 260 |
+
kBatch
|
| 261 |
+
};
|
| 262 |
+
|
| 263 |
+
if (workspace_size) {
|
| 264 |
+
*workspace_size = 0;
|
| 265 |
+
return 0;
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
// run the kernel
|
| 269 |
+
const auto dispatch = [&](const auto has_hot_loop_, const auto tail_number_) constexpr {
|
| 270 |
+
using Kernel = {{instance_namespace}}::Kernel<has_hot_loop_.value, tail_number_.value>;
|
| 271 |
+
|
| 272 |
+
if (!Kernel::IsSupportedArgument(kargs)) {
|
| 273 |
+
// we do our best to statically avoid this case in `filter_op`
|
| 274 |
+
throw std::runtime_error("invalid argument");
|
| 275 |
+
}
|
| 276 |
+
auto stream_config = ck_tile::stream_config{stream};
|
| 277 |
+
auto grid_size = Kernel::GridSize(M, N, kBatch);
|
| 278 |
+
constexpr auto block_size = Kernel::BlockSize();
|
| 279 |
+
constexpr auto lds_bytes = 0;
|
| 280 |
+
constexpr auto kBlockPerCU = 1;
|
| 281 |
+
auto gemm = ck_tile::make_kernel<block_size.x, kBlockPerCU>(Kernel{}, grid_size, block_size, lds_bytes, kargs);
|
| 282 |
+
float elapsed_time = ck_tile::launch_kernel(stream_config, gemm);
|
| 283 |
+
};
|
| 284 |
+
|
| 285 |
+
const ck_tile::index_t k_grain = kBatch * TileK;
|
| 286 |
+
const ck_tile::index_t K_split = (K + k_grain - 1) / k_grain * TileK;
|
| 287 |
+
const ck_tile::index_t num_loop = TilePartitioner::GetLoopNum(K_split);
|
| 288 |
+
const bool has_hot_loop = BaseGemmPipeline::BlockHasHotloop(num_loop);
|
| 289 |
+
const ck_tile::TailNumber tail_num = BaseGemmPipeline::GetBlockLoopTailNum(num_loop);
|
| 290 |
+
|
| 291 |
+
{{rendered_dispatch}}
|
| 292 |
+
|
| 293 |
+
return 0;
|
| 294 |
+
} // kernel definition
|
| 295 |
+
} // extern C
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
def __init__(
|
| 299 |
+
self,
|
| 300 |
+
input_nodes: list[Buffer],
|
| 301 |
+
layout: Layout,
|
| 302 |
+
) -> None:
|
| 303 |
+
super().__init__(
|
| 304 |
+
"ck_tile_gemm_template",
|
| 305 |
+
input_nodes=input_nodes,
|
| 306 |
+
layout=layout,
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
def header(self) -> IndentedBuffer:
|
| 310 |
+
res = super().header()
|
| 311 |
+
res.splice(
|
| 312 |
+
"""
|
| 313 |
+
// CK GEMM header(s)
|
| 314 |
+
|
| 315 |
+
#include "ck_tile/ops/gemm.hpp"
|
| 316 |
+
#include "ck_tile/ops/epilogue.hpp"
|
| 317 |
+
"""
|
| 318 |
+
)
|
| 319 |
+
return res
|
| 320 |
+
|
| 321 |
+
def globals(self) -> IndentedBuffer:
|
| 322 |
+
res = super().globals()
|
| 323 |
+
res.splice(
|
| 324 |
+
"""
|
| 325 |
+
// CK GEMM globals
|
| 326 |
+
|
| 327 |
+
using Row = ck_tile::tensor_layout::gemm::RowMajor;
|
| 328 |
+
using Col = ck_tile::tensor_layout::gemm::ColumnMajor;
|
| 329 |
+
|
| 330 |
+
template <ck_tile::index_t PrefetchStages, typename Dispatcher>
|
| 331 |
+
void dispatch_memory_pipeline_hot_loop(const ck_tile::TailNumber tail_num, Dispatcher dispatch)
|
| 332 |
+
{
|
| 333 |
+
if(tail_num == ck_tile::TailNumber::One)
|
| 334 |
+
{
|
| 335 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 336 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::One>{});
|
| 337 |
+
}
|
| 338 |
+
else if(tail_num == ck_tile::TailNumber::Full)
|
| 339 |
+
{
|
| 340 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 341 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Full>{});
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
if constexpr(PrefetchStages > 2)
|
| 345 |
+
{
|
| 346 |
+
if(tail_num == ck_tile::TailNumber::Two)
|
| 347 |
+
{
|
| 348 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 349 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Two>{});
|
| 350 |
+
}
|
| 351 |
+
}
|
| 352 |
+
if constexpr(PrefetchStages > 3)
|
| 353 |
+
{
|
| 354 |
+
if(tail_num == ck_tile::TailNumber::Three)
|
| 355 |
+
{
|
| 356 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 357 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Three>{});
|
| 358 |
+
}
|
| 359 |
+
}
|
| 360 |
+
if constexpr(PrefetchStages > 4)
|
| 361 |
+
{
|
| 362 |
+
if(tail_num == ck_tile::TailNumber::Four)
|
| 363 |
+
{
|
| 364 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 365 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Four>{});
|
| 366 |
+
}
|
| 367 |
+
}
|
| 368 |
+
if constexpr(PrefetchStages > 5)
|
| 369 |
+
{
|
| 370 |
+
if(tail_num == ck_tile::TailNumber::Five)
|
| 371 |
+
{
|
| 372 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 373 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Five>{});
|
| 374 |
+
}
|
| 375 |
+
}
|
| 376 |
+
if constexpr(PrefetchStages > 6)
|
| 377 |
+
{
|
| 378 |
+
if(tail_num == ck_tile::TailNumber::Six)
|
| 379 |
+
{
|
| 380 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 381 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Six>{});
|
| 382 |
+
}
|
| 383 |
+
}
|
| 384 |
+
if constexpr(PrefetchStages > 7)
|
| 385 |
+
{
|
| 386 |
+
if(tail_num == ck_tile::TailNumber::Seven)
|
| 387 |
+
{
|
| 388 |
+
dispatch(ck_tile::bool_constant<true>{},
|
| 389 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Seven>{});
|
| 390 |
+
}
|
| 391 |
+
}
|
| 392 |
+
}
|
| 393 |
+
"""
|
| 394 |
+
)
|
| 395 |
+
return res
|
| 396 |
+
|
| 397 |
+
def check_dtypes(self, op: "CKTileGemmOperation"):
|
| 398 |
+
X_dtype, W_dtype, out_dtype = [
|
| 399 |
+
T.get_layout().dtype for T in [*self.input_nodes, self.output_node]
|
| 400 |
+
]
|
| 401 |
+
if op.datatype_a != self._TORCH_DTYPE_TO_CK[X_dtype]:
|
| 402 |
+
return False
|
| 403 |
+
if op.datatype_b != self._TORCH_DTYPE_TO_CK[W_dtype]:
|
| 404 |
+
return False
|
| 405 |
+
if op.datatype_c != self._TORCH_DTYPE_TO_CK[out_dtype]:
|
| 406 |
+
return False
|
| 407 |
+
return True
|
| 408 |
+
|
| 409 |
+
def check_layouts(self, op: "CKTileGemmOperation"):
|
| 410 |
+
X_layout, W_layout, out_layout = [
|
| 411 |
+
torch_layout_to_ck_layout(T.get_layout())
|
| 412 |
+
for T in [*self.input_nodes, self.output_node]
|
| 413 |
+
]
|
| 414 |
+
if op.layout_a != X_layout:
|
| 415 |
+
return False
|
| 416 |
+
if op.layout_b != W_layout:
|
| 417 |
+
return False
|
| 418 |
+
if op.layout_c != out_layout:
|
| 419 |
+
return False
|
| 420 |
+
return True
|
| 421 |
+
|
| 422 |
+
def get_gemm_problem_size(self):
|
| 423 |
+
X_size, W_size = [T.get_layout().size for T in [*self.input_nodes]]
|
| 424 |
+
|
| 425 |
+
M, K = X_size
|
| 426 |
+
_, N = W_size
|
| 427 |
+
|
| 428 |
+
return M, N, K
|
| 429 |
+
|
| 430 |
+
def check_block_tiles(self, op: "CKTileGemmOperation"):
|
| 431 |
+
"""
|
| 432 |
+
The contiguous dimension of a tensor must be divisible by the block tile size
|
| 433 |
+
This helper function enforces it for the inputs and the output.
|
| 434 |
+
"""
|
| 435 |
+
M, N, K = self.get_gemm_problem_size()
|
| 436 |
+
|
| 437 |
+
def check(dim_size, tile_size, is_padded):
|
| 438 |
+
if (
|
| 439 |
+
is_static_int(dim_size)
|
| 440 |
+
and dim_size % tile_size != 0
|
| 441 |
+
and is_padded == "false"
|
| 442 |
+
):
|
| 443 |
+
return False
|
| 444 |
+
return True
|
| 445 |
+
|
| 446 |
+
if op.layout_a == "Row":
|
| 447 |
+
# handle in kBatch check
|
| 448 |
+
return True
|
| 449 |
+
elif op.layout_a == "Col":
|
| 450 |
+
if not check(M, op.tile_m, op.m_is_padded):
|
| 451 |
+
return False
|
| 452 |
+
else:
|
| 453 |
+
raise AssertionError(f"Invalid layout {op.layout_a=}")
|
| 454 |
+
|
| 455 |
+
if op.layout_b == "Row":
|
| 456 |
+
if not check(N, op.tile_n, op.n_is_padded):
|
| 457 |
+
return False
|
| 458 |
+
elif op.layout_b == "Col":
|
| 459 |
+
# handle in kBatch check
|
| 460 |
+
return True
|
| 461 |
+
else:
|
| 462 |
+
raise AssertionError(f"Invalid {op.layout_b=}")
|
| 463 |
+
|
| 464 |
+
if op.layout_c == "Row":
|
| 465 |
+
if not check(N, op.tile_n, op.n_is_padded):
|
| 466 |
+
return False
|
| 467 |
+
elif op.layout_c == "Col":
|
| 468 |
+
if not check(M, op.tile_m, op.m_is_padded):
|
| 469 |
+
return False
|
| 470 |
+
else:
|
| 471 |
+
raise AssertionError(f"Invalid layout {op.layout_c=}")
|
| 472 |
+
|
| 473 |
+
return True
|
| 474 |
+
|
| 475 |
+
def check_alignments(self, op: "CKTileGemmOperation"):
|
| 476 |
+
"""
|
| 477 |
+
The contiguous dimension of a tensor must be divisible by the vector load size.
|
| 478 |
+
"""
|
| 479 |
+
M, N, K = self.get_gemm_problem_size()
|
| 480 |
+
|
| 481 |
+
def max_alignment(contiguous_elements_per_tile, elements_per_thread, ck_dtype):
|
| 482 |
+
for vector_load_bytes in (16, 8, 4, 2, 1):
|
| 483 |
+
alignment = vector_load_bytes // self.ck_dtype_to_size[ck_dtype]
|
| 484 |
+
if (
|
| 485 |
+
alignment > 0
|
| 486 |
+
and contiguous_elements_per_tile % alignment == 0
|
| 487 |
+
and elements_per_thread % alignment == 0
|
| 488 |
+
):
|
| 489 |
+
return alignment
|
| 490 |
+
|
| 491 |
+
threads_per_block = (
|
| 492 |
+
op.warp_m * op.warp_n * op.warp_k * self.gfx9_threads_per_warp
|
| 493 |
+
)
|
| 494 |
+
a_elements_per_thread = op.tile_m * op.tile_k / threads_per_block
|
| 495 |
+
b_elements_per_thread = op.tile_n * op.tile_k / threads_per_block
|
| 496 |
+
|
| 497 |
+
if op.layout_a == "Row":
|
| 498 |
+
# K is contiguous tensor dimension
|
| 499 |
+
a_max_vector_size = max_alignment(
|
| 500 |
+
op.tile_k, a_elements_per_thread, op.datatype_a
|
| 501 |
+
)
|
| 502 |
+
if is_static_int(K) and K % a_max_vector_size != 0:
|
| 503 |
+
return False
|
| 504 |
+
elif op.layout_a == "Col":
|
| 505 |
+
# M is contiguous tensor dimension
|
| 506 |
+
a_max_vector_size = max_alignment(
|
| 507 |
+
op.tile_m, a_elements_per_thread, op.datatype_a
|
| 508 |
+
)
|
| 509 |
+
if is_static_int(M) and M % a_max_vector_size != 0:
|
| 510 |
+
return False
|
| 511 |
+
else:
|
| 512 |
+
raise AssertionError(f"Invalid layout {op.layout_a=}")
|
| 513 |
+
|
| 514 |
+
if op.layout_b == "Row":
|
| 515 |
+
# N is contiguous tensor dimension
|
| 516 |
+
b_max_vector_size = max_alignment(
|
| 517 |
+
op.tile_n, b_elements_per_thread, op.datatype_b
|
| 518 |
+
)
|
| 519 |
+
if is_static_int(N) and N % b_max_vector_size != 0:
|
| 520 |
+
return False
|
| 521 |
+
elif op.layout_b == "Col":
|
| 522 |
+
# K is contiguous tensor dimension
|
| 523 |
+
b_max_vector_size = max_alignment(
|
| 524 |
+
op.tile_k, b_elements_per_thread, op.datatype_b
|
| 525 |
+
)
|
| 526 |
+
if is_static_int(K) and K % b_max_vector_size != 0:
|
| 527 |
+
return False
|
| 528 |
+
else:
|
| 529 |
+
raise AssertionError(f"Invalid layout {op.layout_b=}")
|
| 530 |
+
|
| 531 |
+
# the `default` epilogue writes C to memory by 1 tensor element
|
| 532 |
+
# (divisibility check not necessary)
|
| 533 |
+
# the `cshuffle` epilogue writes C to memory by 16 bytes
|
| 534 |
+
# (so the contiguous C dimension size must be divisible by the number of tensor elements in 16 bytes)
|
| 535 |
+
if op.epilogue == "CShuffle":
|
| 536 |
+
if (
|
| 537 |
+
op.layout_c == "Row"
|
| 538 |
+
and is_static_int(N)
|
| 539 |
+
and N % (16 / self.ck_dtype_to_size[op.datatype_c]) != 0
|
| 540 |
+
):
|
| 541 |
+
return False
|
| 542 |
+
|
| 543 |
+
return True
|
| 544 |
+
|
| 545 |
+
def check_warp_tiles(self, op: "CKTileGemmOperation"):
|
| 546 |
+
if op.tile_m % (op.warp_m * op.warp_tile_m) != 0:
|
| 547 |
+
return False
|
| 548 |
+
if op.tile_n % (op.warp_n * op.warp_tile_n) != 0:
|
| 549 |
+
return False
|
| 550 |
+
if op.tile_k % (op.warp_k * op.warp_tile_k) != 0:
|
| 551 |
+
return False
|
| 552 |
+
return True
|
| 553 |
+
|
| 554 |
+
def check_block_tile_size(self, op: "CKTileGemmOperation"):
|
| 555 |
+
# assuming LDS size is 64KB
|
| 556 |
+
if op.pipeline == "CompV4":
|
| 557 |
+
max_block_tile_size = 2**15
|
| 558 |
+
else:
|
| 559 |
+
max_block_tile_size = 2**16
|
| 560 |
+
|
| 561 |
+
block_tile_size = (
|
| 562 |
+
self.ck_dtype_to_size[op.datatype_a] * op.tile_m * op.tile_k
|
| 563 |
+
+ self.ck_dtype_to_size[op.datatype_b] * op.tile_n * op.tile_k
|
| 564 |
+
)
|
| 565 |
+
if block_tile_size > max_block_tile_size:
|
| 566 |
+
return False
|
| 567 |
+
return True
|
| 568 |
+
|
| 569 |
+
def filter_op(self, op: "CKTileGemmOperation"):
|
| 570 |
+
"""
|
| 571 |
+
Determines whether a given op definition is suitable for the current
|
| 572 |
+
input / output of the operation that this template implements.
|
| 573 |
+
|
| 574 |
+
Filter is based on inputs' dtype, layout and statically inferred size.
|
| 575 |
+
|
| 576 |
+
Returns None if the op is not suitable, otherwise returns the op to be used.
|
| 577 |
+
"""
|
| 578 |
+
if not self.check_dtypes(op):
|
| 579 |
+
return None
|
| 580 |
+
if not self.check_layouts(op):
|
| 581 |
+
return None
|
| 582 |
+
if not self.check_block_tiles(op):
|
| 583 |
+
return None
|
| 584 |
+
if not self.check_alignments(op):
|
| 585 |
+
return None
|
| 586 |
+
|
| 587 |
+
return op
|
| 588 |
+
|
| 589 |
+
def emit_ck_instance(self, op: "CKTileGemmOperation"):
|
| 590 |
+
"""
|
| 591 |
+
This method is used to generate code which defines the type alias for the generated kernel class
|
| 592 |
+
"""
|
| 593 |
+
template_definition = r"""
|
| 594 |
+
// Gemm operator {{operation_name}}
|
| 595 |
+
|
| 596 |
+
namespace {{operation_name}} {
|
| 597 |
+
// block tile
|
| 598 |
+
constexpr int32_t TileM = {{tile_m}};
|
| 599 |
+
constexpr int32_t TileN = {{tile_n}};
|
| 600 |
+
constexpr int32_t TileK = {{tile_k}};
|
| 601 |
+
// warps per block
|
| 602 |
+
constexpr int32_t WarpM = {{warp_m}};
|
| 603 |
+
constexpr int32_t WarpN = {{warp_n}};
|
| 604 |
+
constexpr int32_t WarpK = {{warp_k}};
|
| 605 |
+
// xdl tile
|
| 606 |
+
constexpr int32_t WarpTileM = {{warp_tile_m}};
|
| 607 |
+
constexpr int32_t WarpTileN = {{warp_tile_n}};
|
| 608 |
+
constexpr int32_t WarpTileK = {{warp_tile_k}};
|
| 609 |
+
|
| 610 |
+
constexpr bool kPadM = {{m_is_padded}};
|
| 611 |
+
constexpr bool kPadN = {{n_is_padded}};
|
| 612 |
+
constexpr bool kPadK = {{k_is_padded}};
|
| 613 |
+
|
| 614 |
+
using ALayout = {{layout_a}};
|
| 615 |
+
using BLayout = {{layout_b}};
|
| 616 |
+
using CLayout = {{layout_c}};
|
| 617 |
+
|
| 618 |
+
using ADataType = {{datatype_a}};
|
| 619 |
+
using BDataType = {{datatype_b}};
|
| 620 |
+
using CDataType = {{datatype_c}};
|
| 621 |
+
using AccDataType = F32;
|
| 622 |
+
|
| 623 |
+
constexpr bool permuteA = false;
|
| 624 |
+
constexpr bool permuteB = false;
|
| 625 |
+
constexpr bool DoubleSmemBuffer = {{has_double_smem_buffer}};
|
| 626 |
+
constexpr bool TransposeC = false;
|
| 627 |
+
|
| 628 |
+
constexpr int kBlockPerCu = 1;
|
| 629 |
+
constexpr ck_tile::index_t TilePartitionerGroupNum = 8;
|
| 630 |
+
constexpr ck_tile::index_t TilePartitionerM01 = 4;
|
| 631 |
+
|
| 632 |
+
using GemmShape =
|
| 633 |
+
ck_tile::TileGemmShape<ck_tile::sequence<TileM, TileN, TileK>,
|
| 634 |
+
ck_tile::sequence<WarpM, WarpN, WarpK>,
|
| 635 |
+
ck_tile::sequence<WarpTileM, WarpTileN, WarpTileK>,
|
| 636 |
+
permuteA,
|
| 637 |
+
permuteB>;
|
| 638 |
+
|
| 639 |
+
using TilePartitioner =
|
| 640 |
+
ck_tile::GemmSpatiallyLocalTilePartitioner<GemmShape,
|
| 641 |
+
TilePartitionerGroupNum,
|
| 642 |
+
TilePartitionerM01>;
|
| 643 |
+
|
| 644 |
+
using Traits =
|
| 645 |
+
ck_tile::TileGemmTraits<kPadM, kPadN, kPadK, ALayout, BLayout, CLayout>;
|
| 646 |
+
|
| 647 |
+
using GemmUniversalTraits =
|
| 648 |
+
ck_tile::TileGemmUniversalTraits<kPadM, kPadN, kPadK, DoubleSmemBuffer,
|
| 649 |
+
ALayout, BLayout, CLayout, TransposeC>;
|
| 650 |
+
|
| 651 |
+
using GemmPipelineProblem =
|
| 652 |
+
ck_tile::GemmPipelineProblem<ADataType, BDataType, AccDataType, GemmShape, Traits>;
|
| 653 |
+
|
| 654 |
+
{{rendered_scheduler}}
|
| 655 |
+
|
| 656 |
+
template<bool has_hot_loop_v, ck_tile::TailNumber tail_number_v>
|
| 657 |
+
using UniversalGemmProblem =
|
| 658 |
+
ck_tile::UniversalGemmPipelineProblem<ADataType,
|
| 659 |
+
BDataType,
|
| 660 |
+
AccDataType,
|
| 661 |
+
GemmShape,
|
| 662 |
+
GemmUniversalTraits,
|
| 663 |
+
scheduler,
|
| 664 |
+
has_hot_loop_v,
|
| 665 |
+
tail_number_v>;
|
| 666 |
+
|
| 667 |
+
{{rendered_pipeline}}
|
| 668 |
+
|
| 669 |
+
{{rendered_epilogue}}
|
| 670 |
+
|
| 671 |
+
template<bool has_hot_loop_v, ck_tile::TailNumber tail_number_v>
|
| 672 |
+
using Kernel = ck_tile::GemmKernel<TilePartitioner, GemmPipeline<has_hot_loop_v, tail_number_v>, GemmEpilogue>;
|
| 673 |
+
}
|
| 674 |
+
|
| 675 |
+
"""
|
| 676 |
+
|
| 677 |
+
def render_epilogue(epilogue_type):
|
| 678 |
+
if epilogue_type == "Default":
|
| 679 |
+
return r"""
|
| 680 |
+
using EpilogueProblem = ck_tile::DefaultGemm2DEpilogueProblem<ADataType,
|
| 681 |
+
BDataType,
|
| 682 |
+
AccDataType,
|
| 683 |
+
CDataType,
|
| 684 |
+
CLayout,
|
| 685 |
+
kPadM,
|
| 686 |
+
kPadN,
|
| 687 |
+
WarpTileM,
|
| 688 |
+
WarpTileN,
|
| 689 |
+
WarpTileK,
|
| 690 |
+
TransposeC>;
|
| 691 |
+
using GemmEpilogue = ck_tile::DefaultGemm2DEpilogue<EpilogueProblem>;
|
| 692 |
+
"""
|
| 693 |
+
elif epilogue_type == "CShuffle":
|
| 694 |
+
return r"""
|
| 695 |
+
constexpr auto kMemoryOperation = ck_tile::memory_operation_enum::set;
|
| 696 |
+
using DsDataType = ck_tile::tuple<>; // no bias terms for vanilla GEMM
|
| 697 |
+
using DsLayout = ck_tile::tuple<>;
|
| 698 |
+
constexpr auto ELayout = CLayout;
|
| 699 |
+
using CDEElementWise = ck_tile::element_wise::PassThrough; // no-op
|
| 700 |
+
using EpilogueProblem = ck_tile::CShuffleEpilogueProblem<ADataType,
|
| 701 |
+
BDataType,
|
| 702 |
+
DsDataType,
|
| 703 |
+
AccDataType,
|
| 704 |
+
CDataType,
|
| 705 |
+
DsLayout,
|
| 706 |
+
ELayout,
|
| 707 |
+
CDEElementWise,
|
| 708 |
+
GemmPipelineProblem::kBlockSize,
|
| 709 |
+
TileM,
|
| 710 |
+
TileN,
|
| 711 |
+
WarpM,
|
| 712 |
+
WarpN,
|
| 713 |
+
WarpTileM,
|
| 714 |
+
WarpTileN,
|
| 715 |
+
WarpTileK,
|
| 716 |
+
TransposeC,
|
| 717 |
+
kMemoryOperation>;
|
| 718 |
+
|
| 719 |
+
using GemmEpilogue = ck_tile::CShuffleEpilogue<EpilogueProblem>;
|
| 720 |
+
"""
|
| 721 |
+
else:
|
| 722 |
+
raise AssertionError("Epilogue must be set")
|
| 723 |
+
|
| 724 |
+
def render_pipeline(pipeline_type):
|
| 725 |
+
return rf"""
|
| 726 |
+
using BaseGemmPipeline = ck_tile::BaseGemmPipelineAgBgCr{pipeline_type}<GemmPipelineProblem>;
|
| 727 |
+
|
| 728 |
+
template<bool has_hot_loop_v, ck_tile::TailNumber tail_number_v>
|
| 729 |
+
using GemmPipeline = ck_tile::GemmPipelineAgBgCr{pipeline_type}<UniversalGemmProblem<has_hot_loop_v, tail_number_v>>;
|
| 730 |
+
"""
|
| 731 |
+
|
| 732 |
+
def render_scheduler(scheduler_type):
|
| 733 |
+
return rf"""
|
| 734 |
+
constexpr auto scheduler = ck_tile::GemmPipelineScheduler::{scheduler_type};
|
| 735 |
+
"""
|
| 736 |
+
|
| 737 |
+
rendered_definition = self._template_from_string(template_definition).render(
|
| 738 |
+
operation_name=op.name(),
|
| 739 |
+
**asdict(op),
|
| 740 |
+
rendered_scheduler=render_scheduler(op.scheduler),
|
| 741 |
+
rendered_pipeline=render_pipeline(op.pipeline),
|
| 742 |
+
rendered_epilogue=render_epilogue(op.epilogue),
|
| 743 |
+
has_double_smem_buffer=("true" if op.pipeline == "CompV4" else "false"),
|
| 744 |
+
)
|
| 745 |
+
return rendered_definition
|
| 746 |
+
|
| 747 |
+
def render( # type: ignore[override]
|
| 748 |
+
self, kernel: ROCmTemplateKernel, op: "CKTileGemmOperation", **kwargs
|
| 749 |
+
) -> str:
|
| 750 |
+
"""
|
| 751 |
+
The primary entry point for the code rendering process used in this template.
|
| 752 |
+
"""
|
| 753 |
+
epilogue_nodes = kwargs.get("epilogue_nodes", None)
|
| 754 |
+
assert epilogue_nodes is None or 0 == len(epilogue_nodes)
|
| 755 |
+
template_buffer_node = kwargs.get("template_buffer_node", None)
|
| 756 |
+
if template_buffer_node is not None:
|
| 757 |
+
self.output_node = template_buffer_node
|
| 758 |
+
assert 2 == len(self.input_nodes)
|
| 759 |
+
X, W = self.input_nodes
|
| 760 |
+
Y = self.output_node
|
| 761 |
+
|
| 762 |
+
instance_definition = self.emit_ck_instance(op)
|
| 763 |
+
|
| 764 |
+
version_comment = rf"""/**
|
| 765 |
+
* Generated code for CK inductor backend
|
| 766 |
+
* See {type(self).__module__}.{type(self).__qualname__}
|
| 767 |
+
*
|
| 768 |
+
* Template instance {op}
|
| 769 |
+
*
|
| 770 |
+
* {torch.__version__=}
|
| 771 |
+
* torch.version.git_version={getattr(torch.version, "git_version", "None")}
|
| 772 |
+
*/
|
| 773 |
+
"""
|
| 774 |
+
|
| 775 |
+
def render_dispatch(pipeline_type, op_name):
|
| 776 |
+
switch_tailnum_template = r"""
|
| 777 |
+
switch (tail_num) {
|
| 778 |
+
{% for tail_num in valid_tailnums %}
|
| 779 |
+
case ck_tile::TailNumber::{{tail_num}}:
|
| 780 |
+
dispatch({{has_hot_loop}},
|
| 781 |
+
ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::{{tail_num}}>{});
|
| 782 |
+
break;
|
| 783 |
+
{% endfor %}
|
| 784 |
+
default:
|
| 785 |
+
std::ostringstream err;
|
| 786 |
+
err << "Unsupported dispatch: "
|
| 787 |
+
<< "Pipeline: " << "{{pipeline}}"
|
| 788 |
+
<< "Prefetch stages: " << kPrefetchStages
|
| 789 |
+
<< "Tail num: " << tail_num;
|
| 790 |
+
throw std::runtime_error(err.str());
|
| 791 |
+
} // switch tail_num
|
| 792 |
+
"""
|
| 793 |
+
dispatch_template = r"""
|
| 794 |
+
if (has_hot_loop) {
|
| 795 |
+
{{rendered_with_hot_loop}}
|
| 796 |
+
}
|
| 797 |
+
else { // has_hot_loop == false
|
| 798 |
+
{{rendered_without_hot_loop}}
|
| 799 |
+
} // if has_hot_loop
|
| 800 |
+
"""
|
| 801 |
+
if pipeline_type == "CompV3":
|
| 802 |
+
return self._template_from_string(dispatch_template).render(
|
| 803 |
+
rendered_with_hot_loop=self._template_from_string(
|
| 804 |
+
switch_tailnum_template
|
| 805 |
+
).render(
|
| 806 |
+
has_hot_loop="ck_tile::integral_constant<bool, true>{}",
|
| 807 |
+
valid_tailnums=("Full", "Odd", "Even"),
|
| 808 |
+
pipeline=pipeline_type,
|
| 809 |
+
),
|
| 810 |
+
rendered_without_hot_loop=self._template_from_string(
|
| 811 |
+
switch_tailnum_template
|
| 812 |
+
).render(
|
| 813 |
+
has_hot_loop="ck_tile::integral_constant<bool, false>{}",
|
| 814 |
+
valid_tailnums=("Full", "Odd", "Even"),
|
| 815 |
+
pipeline=pipeline_type,
|
| 816 |
+
),
|
| 817 |
+
)
|
| 818 |
+
elif pipeline_type == "Mem":
|
| 819 |
+
return self._template_from_string(dispatch_template).render(
|
| 820 |
+
rendered_with_hot_loop="dispatch_memory_pipeline_hot_loop<kPrefetchStages>(tail_num, dispatch);",
|
| 821 |
+
rendered_without_hot_loop=self._template_from_string(
|
| 822 |
+
switch_tailnum_template
|
| 823 |
+
).render(
|
| 824 |
+
has_hot_loop="ck_tile::integral_constant<bool, false>{}",
|
| 825 |
+
valid_tailnums=("Full", "Odd", "Even"),
|
| 826 |
+
pipeline=pipeline_type,
|
| 827 |
+
),
|
| 828 |
+
)
|
| 829 |
+
elif pipeline_type == "CompV4":
|
| 830 |
+
return self._template_from_string(dispatch_template).render(
|
| 831 |
+
rendered_with_hot_loop=self._template_from_string(
|
| 832 |
+
switch_tailnum_template
|
| 833 |
+
).render(
|
| 834 |
+
has_hot_loop="ck_tile::integral_constant<bool, true>{}",
|
| 835 |
+
valid_tailnums=("Two", "Three"),
|
| 836 |
+
pipeline=pipeline_type,
|
| 837 |
+
),
|
| 838 |
+
rendered_without_hot_loop=self._template_from_string(
|
| 839 |
+
switch_tailnum_template
|
| 840 |
+
).render(
|
| 841 |
+
has_hot_loop="ck_tile::integral_constant<bool, false>{}",
|
| 842 |
+
valid_tailnums=("Full", "Odd", "Even"),
|
| 843 |
+
pipeline=pipeline_type,
|
| 844 |
+
),
|
| 845 |
+
)
|
| 846 |
+
else:
|
| 847 |
+
raise AssertionError(f"Pipeline {pipeline_type} is not supported")
|
| 848 |
+
|
| 849 |
+
return self._template_from_string(self.gemm_template).render(
|
| 850 |
+
headers=self.header().getvalue(),
|
| 851 |
+
globals=self.globals().getvalue(),
|
| 852 |
+
instance_definition=instance_definition,
|
| 853 |
+
kernel_definition=kernel.def_kernel(
|
| 854 |
+
inputs=[X, W], # type: ignore[list-item]
|
| 855 |
+
outputs=[Y],
|
| 856 |
+
names_str="X, W, Y",
|
| 857 |
+
size_args=[
|
| 858 |
+
f"int32_t {arg}" for arg in ["M", "N", "K", "LDA", "LDB", "LDC"]
|
| 859 |
+
],
|
| 860 |
+
),
|
| 861 |
+
instance_namespace=op.name(),
|
| 862 |
+
version_comment=version_comment,
|
| 863 |
+
rendered_dispatch=render_dispatch(op.pipeline, op.name()),
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
def gen_ops(self):
|
| 867 |
+
"""
|
| 868 |
+
Creates a list of `CKTileGemmOperation` instances that match the GEMM operation this template represents.
|
| 869 |
+
The instances are guaranteed to have the correct layout, dtype and dimension padding for the GEMM input arguments.
|
| 870 |
+
|
| 871 |
+
An instance may invalidate the GEMM configuration at runtime.
|
| 872 |
+
Such instances will be assigned +inf runtime by the autotune process.
|
| 873 |
+
"""
|
| 874 |
+
instances = ops()
|
| 875 |
+
if not instances:
|
| 876 |
+
raise AssertionError(
|
| 877 |
+
"No Composable Kernel Universal GEMM instances found. "
|
| 878 |
+
"Please check if the library is installed."
|
| 879 |
+
)
|
| 880 |
+
filtered_instances = list(filter(self.filter_op, instances))
|
| 881 |
+
# NB: when using a fixed list order, most likely we will pick the subset of instances
|
| 882 |
+
# which are very similar to each other. Randomizing the choice seems to solve this.
|
| 883 |
+
random.seed(-11)
|
| 884 |
+
chosen_instances = (
|
| 885 |
+
random.sample(
|
| 886 |
+
filtered_instances,
|
| 887 |
+
min(len(filtered_instances), config.rocm.ck_tile_max_profiling_configs),
|
| 888 |
+
)
|
| 889 |
+
if config.rocm.ck_tile_max_profiling_configs
|
| 890 |
+
else filtered_instances
|
| 891 |
+
)
|
| 892 |
+
log.debug(
|
| 893 |
+
"generated %d ck instances after sample: %s",
|
| 894 |
+
len(chosen_instances),
|
| 895 |
+
chosen_instances,
|
| 896 |
+
)
|
| 897 |
+
return chosen_instances
|
| 898 |
+
|
| 899 |
+
@staticmethod
|
| 900 |
+
def add_choices(
|
| 901 |
+
choices,
|
| 902 |
+
layout,
|
| 903 |
+
input_nodes,
|
| 904 |
+
):
|
| 905 |
+
"""
|
| 906 |
+
Add Composable Kernel Universal GEMM instance choices to the auto-tuning list.
|
| 907 |
+
"""
|
| 908 |
+
template = CKTileGemmTemplate(
|
| 909 |
+
input_nodes,
|
| 910 |
+
layout,
|
| 911 |
+
)
|
| 912 |
+
ops = template.gen_ops()
|
| 913 |
+
for op in ops:
|
| 914 |
+
for k_batch in template.k_batch_choices(op):
|
| 915 |
+
template.maybe_append_choice(
|
| 916 |
+
choices,
|
| 917 |
+
op=op,
|
| 918 |
+
kBatch=k_batch,
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
def k_batch_choices(self, op: "CKTileGemmOperation") -> tuple[int, ...]:
|
| 922 |
+
"""
|
| 923 |
+
Returns a list of k_batch choices for the template.
|
| 924 |
+
"""
|
| 925 |
+
default_choices = (1, 2, 4, 8, 16, 32)
|
| 926 |
+
|
| 927 |
+
def check(dim_size, tile_size, is_padded):
|
| 928 |
+
if (
|
| 929 |
+
is_static_int(dim_size)
|
| 930 |
+
and dim_size % tile_size != 0
|
| 931 |
+
and is_padded == "false"
|
| 932 |
+
):
|
| 933 |
+
return False
|
| 934 |
+
return True
|
| 935 |
+
|
| 936 |
+
_, _, K, _, _, _ = self.size_args()
|
| 937 |
+
if op.layout_a == "Row" or op.layout_b == "Col":
|
| 938 |
+
choices = tuple(
|
| 939 |
+
filter(
|
| 940 |
+
lambda k_batch: check(K, op.tile_k * k_batch, op.k_is_padded),
|
| 941 |
+
default_choices,
|
| 942 |
+
)
|
| 943 |
+
)
|
| 944 |
+
else:
|
| 945 |
+
choices = default_choices
|
| 946 |
+
|
| 947 |
+
if op.epilogue == "Default":
|
| 948 |
+
choices = (1,)
|
| 949 |
+
|
| 950 |
+
return choices
|
| 951 |
+
|
| 952 |
+
def size_args(self):
|
| 953 |
+
"""
|
| 954 |
+
Sizes and strides to be used for the kernel call
|
| 955 |
+
"""
|
| 956 |
+
X = self.input_nodes[0]
|
| 957 |
+
W = self.input_nodes[1]
|
| 958 |
+
Y = self.output_node
|
| 959 |
+
|
| 960 |
+
M = X.get_size()[0]
|
| 961 |
+
K = X.get_size()[1]
|
| 962 |
+
N = W.get_size()[1]
|
| 963 |
+
LDA = X.get_stride()[0 if X.get_stride()[1] == 1 else 1]
|
| 964 |
+
LDB = W.get_stride()[0 if W.get_stride()[1] == 1 else 1]
|
| 965 |
+
LDC = Y.get_stride()[0 if Y.get_stride()[1] == 1 else 1]
|
| 966 |
+
|
| 967 |
+
return M, N, K, LDA, LDB, LDC
|
| 968 |
+
|
| 969 |
+
def get_runtime_arg_info(self) -> list[ArgInfo]:
|
| 970 |
+
return [ArgInfo("kBatch", "int32_t")]
|
| 971 |
+
|
| 972 |
+
def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]:
|
| 973 |
+
# maybe_append_choice kwarg for k_batch must match the name of the argument
|
| 974 |
+
arg_names = OrderedSet([arg.name for arg in self.get_runtime_arg_info()])
|
| 975 |
+
if not arg_names.issubset(kwargs):
|
| 976 |
+
raise ValueError(
|
| 977 |
+
"Missing runtime arguments: " + ", ".join(arg_names - kwargs.keys())
|
| 978 |
+
)
|
| 979 |
+
return [kwargs[k] for k in arg_names]
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/ck_universal_gemm_template.py
ADDED
|
@@ -0,0 +1,1016 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs, disable-error-code="attr-defined, valid-type"
|
| 2 |
+
import copy
|
| 3 |
+
import logging
|
| 4 |
+
import math
|
| 5 |
+
import random
|
| 6 |
+
from collections import namedtuple
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
import sympy
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch._inductor import config
|
| 13 |
+
from torch._inductor.codegen.cpp_utils import DTYPE_TO_CPP
|
| 14 |
+
from torch._inductor.codegen.rocm.ck_template import CKTemplate
|
| 15 |
+
from torch._inductor.codegen.rocm.compile_command import rocm_compile_command
|
| 16 |
+
from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel
|
| 17 |
+
from torch._inductor.ir import Buffer, Layout
|
| 18 |
+
from torch._inductor.runtime.runtime_utils import next_power_of_2
|
| 19 |
+
|
| 20 |
+
from ...utils import IndentedBuffer, is_dynamic, try_import_ck_lib
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_, gen_ops_library, gen_ops_preselected, CKGemmOperation = try_import_ck_lib()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
log = logging.getLogger(__name__)
|
| 27 |
+
|
| 28 |
+
# lightweight collection of information about a single op
|
| 29 |
+
InductorROCmOp = namedtuple("InductorROCmOp", ["op", "kBatch"])
|
| 30 |
+
|
| 31 |
+
padding_lookup = {
|
| 32 |
+
"M": {
|
| 33 |
+
"GemmSpecialization::MPadding": True,
|
| 34 |
+
"GemmSpecialization::MNPadding": True,
|
| 35 |
+
"GemmSpecialization::MKPadding": True,
|
| 36 |
+
"GemmSpecialization::MNKPadding": True,
|
| 37 |
+
},
|
| 38 |
+
"N": {
|
| 39 |
+
"GemmSpecialization::NPadding": True,
|
| 40 |
+
"GemmSpecialization::MNPadding": True,
|
| 41 |
+
"GemmSpecialization::NKPadding": True,
|
| 42 |
+
"GemmSpecialization::MNKPadding": True,
|
| 43 |
+
},
|
| 44 |
+
"K": {
|
| 45 |
+
"GemmSpecialization::KPadding": True,
|
| 46 |
+
"GemmSpecialization::MKPadding": True,
|
| 47 |
+
"GemmSpecialization::NKPadding": True,
|
| 48 |
+
"GemmSpecialization::MNKPadding": True,
|
| 49 |
+
},
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def is_static_int(number):
|
| 54 |
+
return isinstance(number, (int, sympy.Integer))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def torch_layout_to_ck_layout(torch_layout):
|
| 58 |
+
if torch_layout.stride[-1] == 1:
|
| 59 |
+
return "Row"
|
| 60 |
+
elif torch_layout.stride[-2] == 1:
|
| 61 |
+
return "Col"
|
| 62 |
+
else:
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class CKGemmTemplate(CKTemplate):
|
| 67 |
+
# the JINJA template for rendering CK Universal GEMMs
|
| 68 |
+
gemm_template = r"""{{version_comment}}
|
| 69 |
+
{{headers}}
|
| 70 |
+
{{globals}}
|
| 71 |
+
{{instance_definition}}
|
| 72 |
+
extern "C" {
|
| 73 |
+
PT_EXPORT {{kernel_definition}} {
|
| 74 |
+
auto gemm = {{instance_type}} {};
|
| 75 |
+
auto invoker = gemm.MakeInvoker();
|
| 76 |
+
{% if is_batched %}
|
| 77 |
+
auto argument = gemm.MakeArgument(
|
| 78 |
+
reinterpret_cast<const {{a_element_dtype}}*>(X),
|
| 79 |
+
reinterpret_cast<const {{b_element_dtype}}*>(W),
|
| 80 |
+
std::array<const void*, {{ds_size}}>{ {{ds_names}} },
|
| 81 |
+
reinterpret_cast<{{c_element_dtype}}*>(Y),
|
| 82 |
+
M,
|
| 83 |
+
N,
|
| 84 |
+
K,
|
| 85 |
+
B,
|
| 86 |
+
LDA,
|
| 87 |
+
LDB,
|
| 88 |
+
std::array<ck::index_t, {{ds_size}}>{ {{ds_strides}} },
|
| 89 |
+
LDC,
|
| 90 |
+
M * K, // batch_stride_A
|
| 91 |
+
N * K, // batch_stride_B
|
| 92 |
+
std::array<ck::index_t, {{ds_size}}>{ {{ds_batch_strides}} },
|
| 93 |
+
M * N, // batch_stride_C
|
| 94 |
+
{{a_elementwise_op}},
|
| 95 |
+
{{b_elementwise_op}},
|
| 96 |
+
{{epilogue}} // c_elementwise_op
|
| 97 |
+
);
|
| 98 |
+
{% else %}
|
| 99 |
+
auto argument = gemm.MakeArgument(
|
| 100 |
+
reinterpret_cast<const {{a_element_dtype}}*>(X),
|
| 101 |
+
reinterpret_cast<const {{b_element_dtype}}*>(W),
|
| 102 |
+
std::array<const void*, {{ds_size}}>{ {{ds_names}} },
|
| 103 |
+
reinterpret_cast<{{c_element_dtype}}*>(Y),
|
| 104 |
+
M,
|
| 105 |
+
N,
|
| 106 |
+
K,
|
| 107 |
+
LDA,
|
| 108 |
+
LDB,
|
| 109 |
+
std::array<ck::index_t, {{ds_size}}>{ {{ds_strides}} },
|
| 110 |
+
LDC,
|
| 111 |
+
kBatch, // kBatch
|
| 112 |
+
{{a_elementwise_op}},
|
| 113 |
+
{{b_elementwise_op}},
|
| 114 |
+
{{epilogue}} // c_elementwise_op
|
| 115 |
+
);
|
| 116 |
+
{% endif %}
|
| 117 |
+
if (!gemm.IsSupportedArgument(argument)) {
|
| 118 |
+
// we do our best to statically avoid this case in `filter_op`
|
| 119 |
+
std::cerr << "invalid argument for gemm instance " << gemm.GetTypeString() << std::endl;
|
| 120 |
+
argument.Print();
|
| 121 |
+
return -23;
|
| 122 |
+
}
|
| 123 |
+
if (workspace_size) {
|
| 124 |
+
*workspace_size = gemm.GetWorkSpaceSize(&argument);
|
| 125 |
+
return 0;
|
| 126 |
+
}
|
| 127 |
+
// run the kernel
|
| 128 |
+
#ifdef GENERATE_CK_STANDALONE_RUNNER
|
| 129 |
+
const auto stream_config = StreamConfig{
|
| 130 |
+
stream,
|
| 131 |
+
/* time kernel */ 1,
|
| 132 |
+
/* log level */ 1,
|
| 133 |
+
/* n_cold_iter */ 100,
|
| 134 |
+
/* n_hot_iter */ 100,
|
| 135 |
+
/* flush_l2_cache */ 1,
|
| 136 |
+
/* rotate_count */ 5};
|
| 137 |
+
#else
|
| 138 |
+
const auto stream_config = StreamConfig{stream, /* time kernel */ false, /* log level */ 0};
|
| 139 |
+
#endif
|
| 140 |
+
|
| 141 |
+
const float elapsed_time = invoker.Run(argument, stream_config);
|
| 142 |
+
|
| 143 |
+
#ifdef GENERATE_CK_STANDALONE_RUNNER
|
| 144 |
+
std::cout << "elapsed time: " << elapsed_time << " ms" << std::endl;
|
| 145 |
+
#else
|
| 146 |
+
(void)elapsed_time;
|
| 147 |
+
#endif
|
| 148 |
+
return 0;
|
| 149 |
+
} // kernel definition
|
| 150 |
+
} // extern C
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
standalone_runner_template = r"""
|
| 154 |
+
#ifdef GENERATE_CK_STANDALONE_RUNNER
|
| 155 |
+
// standalone runner for the generated CK GEMM kernel
|
| 156 |
+
|
| 157 |
+
{{inline_utils}}
|
| 158 |
+
|
| 159 |
+
extern "C" {
|
| 160 |
+
int run_main(int argc, char** argv) {
|
| 161 |
+
{% if is_batched %}
|
| 162 |
+
const int32_t B = {{B}};
|
| 163 |
+
{% endif %}
|
| 164 |
+
const int32_t M = {{M}};
|
| 165 |
+
const int32_t N = {{N}};
|
| 166 |
+
const int32_t K = {{K}};
|
| 167 |
+
const int32_t LDA = {{LDA}};
|
| 168 |
+
const int32_t LDB = {{LDB}};
|
| 169 |
+
const int32_t LDC = {{LDC}};
|
| 170 |
+
const int32_t LDD = {{LDD}};
|
| 171 |
+
const int32_t kBatch = {{kBatch}};
|
| 172 |
+
|
| 173 |
+
using AElementType = {{a_ck_dtype}};
|
| 174 |
+
using BElementType = {{b_ck_dtype}};
|
| 175 |
+
using CElementType = {{c_ck_dtype}};
|
| 176 |
+
{% if has_bias %}
|
| 177 |
+
using BiasElementType = {{bias_ck_dtype}};
|
| 178 |
+
{% endif %}
|
| 179 |
+
{% if has_scale %}
|
| 180 |
+
using ScaleAElementType = {{scale_a_ck_dtype}};
|
| 181 |
+
using ScaleBElementType = {{scale_b_ck_dtype}};
|
| 182 |
+
{% endif %}
|
| 183 |
+
|
| 184 |
+
using AArgType = {{a_torch_dtype}};
|
| 185 |
+
using BArgType = {{b_torch_dtype}};
|
| 186 |
+
using CArgType = {{c_torch_dtype}};
|
| 187 |
+
{% if has_bias %}
|
| 188 |
+
using BiasArgType = {{bias_torch_dtype}};
|
| 189 |
+
{% endif %}
|
| 190 |
+
{% if has_scale %}
|
| 191 |
+
using ScaleAArgType = {{scale_a_torch_dtype}};
|
| 192 |
+
using ScaleBArgType = {{scale_b_torch_dtype}};
|
| 193 |
+
{% endif %}
|
| 194 |
+
|
| 195 |
+
using ALayout = {{a_layout}};
|
| 196 |
+
using BLayout = {{b_layout}};
|
| 197 |
+
using CLayout = {{c_layout}};
|
| 198 |
+
{% if has_bias %}
|
| 199 |
+
using BiasLayout = {{bias_layout}};
|
| 200 |
+
{% endif %}
|
| 201 |
+
|
| 202 |
+
{% if is_batched %}
|
| 203 |
+
using strides_t = std::array<int32_t, 3>;
|
| 204 |
+
auto get_strides = [](int32_t batch_stride, int32_t leading_dimension, auto layout) constexpr -> strides_t {
|
| 205 |
+
if constexpr (std::is_same_v<decltype(layout), Row>) {
|
| 206 |
+
return {batch_stride, leading_dimension, 1};
|
| 207 |
+
}
|
| 208 |
+
return {batch_stride, 1, leading_dimension};
|
| 209 |
+
};
|
| 210 |
+
auto a_size = strides_t{B, M, K};
|
| 211 |
+
auto a_stride = get_strides(M * K, LDA, ALayout{});
|
| 212 |
+
auto b_size = strides_t{B, N, K};
|
| 213 |
+
auto b_stride = get_strides(N * K, LDB, BLayout{});
|
| 214 |
+
auto c_size = strides_t{B, M, N};
|
| 215 |
+
auto c_stride = get_strides(M * N, LDC, CLayout{});
|
| 216 |
+
{% else %}
|
| 217 |
+
using strides_t = std::array<int32_t, 2>;
|
| 218 |
+
auto get_strides = [](int32_t leading_dimension, auto layout) constexpr -> strides_t {
|
| 219 |
+
if constexpr (std::is_same_v<decltype(layout), Row>) {
|
| 220 |
+
return {leading_dimension, 1};
|
| 221 |
+
}
|
| 222 |
+
return {1, leading_dimension};
|
| 223 |
+
};
|
| 224 |
+
auto a_size = strides_t{M, K};
|
| 225 |
+
auto a_stride = get_strides(LDA, ALayout{});
|
| 226 |
+
auto b_size = strides_t{N, K};
|
| 227 |
+
auto b_stride = get_strides(LDB, BLayout{});
|
| 228 |
+
auto c_size = strides_t{M, N};
|
| 229 |
+
auto c_stride = get_strides(LDC, CLayout{});
|
| 230 |
+
{% endif %}
|
| 231 |
+
|
| 232 |
+
Tensor<AElementType> a_m_k ( HostTensorDescriptor ( a_size, a_stride ) );
|
| 233 |
+
Tensor<BElementType> b_k_n ( HostTensorDescriptor ( b_size, b_stride ) );
|
| 234 |
+
{% if has_bias %}
|
| 235 |
+
Tensor<BiasElementType> d_m_n ( HostTensorDescriptor ( c_size, get_strides(LDD, BiasLayout{}) ) );
|
| 236 |
+
{% endif %}
|
| 237 |
+
{% if has_scale %}
|
| 238 |
+
// NB: these are hardcoded
|
| 239 |
+
Tensor<ScaleAElementType> s_a_m_n ( HostTensorDescriptor ( strides_t{M, N}, get_strides(0, Row{}) ));
|
| 240 |
+
Tensor<ScaleAElementType> s_b_m_n ( HostTensorDescriptor ( strides_t{M, N}, get_strides(0, Col{}) ));
|
| 241 |
+
{% endif %}
|
| 242 |
+
|
| 243 |
+
Tensor<CElementType> c_m_n_host ( HostTensorDescriptor ( c_size, c_stride ) );
|
| 244 |
+
Tensor<CElementType> c_m_n_device ( HostTensorDescriptor ( c_size, c_stride ) );
|
| 245 |
+
|
| 246 |
+
a_m_k.GenerateTensorValue(GeneratorTensor_2<AElementType>());
|
| 247 |
+
b_k_n.GenerateTensorValue(GeneratorTensor_2<BElementType>());
|
| 248 |
+
{% if has_bias %}
|
| 249 |
+
d_m_n.GenerateTensorValue(GeneratorTensor_2<BiasElementType>());
|
| 250 |
+
{% endif %}
|
| 251 |
+
{% if has_scale %}
|
| 252 |
+
s_a_m_n.GenerateTensorValue(GeneratorTensor_2<ScaleAElementType>());
|
| 253 |
+
s_b_m_n.GenerateTensorValue(GeneratorTensor_2<ScaleBElementType>());
|
| 254 |
+
{% endif %}
|
| 255 |
+
DeviceMem a_m_k_device_buf(sizeof(AElementType) * a_m_k.mDesc.GetElementSpaceSize());
|
| 256 |
+
DeviceMem b_k_n_device_buf(sizeof(BElementType) * b_k_n.mDesc.GetElementSpaceSize());
|
| 257 |
+
{% if has_bias %}
|
| 258 |
+
DeviceMem d_m_n_device_buf(sizeof(BiasElementType) * d_m_n.mDesc.GetElementSpaceSize());
|
| 259 |
+
{% endif %}
|
| 260 |
+
{% if has_scale %}
|
| 261 |
+
DeviceMem s_a_m_n_device_buf(sizeof(ScaleAElementType) * s_a_m_n.mDesc.GetElementSpaceSize());
|
| 262 |
+
DeviceMem s_b_m_n_device_buf(sizeof(ScaleBElementType) * s_b_m_n.mDesc.GetElementSpaceSize());
|
| 263 |
+
{% endif %}
|
| 264 |
+
DeviceMem c_m_n_device_buf(sizeof(CElementType) * c_m_n_device.mDesc.GetElementSpaceSize());
|
| 265 |
+
|
| 266 |
+
a_m_k_device_buf.ToDevice(a_m_k.mData.data());
|
| 267 |
+
b_k_n_device_buf.ToDevice(b_k_n.mData.data());
|
| 268 |
+
{% if has_bias %}
|
| 269 |
+
d_m_n_device_buf.ToDevice(d_m_n.mData.data());
|
| 270 |
+
{% endif %}
|
| 271 |
+
{% if has_scale %}
|
| 272 |
+
s_a_m_n_device_buf.ToDevice(s_a_m_n.mData.data());
|
| 273 |
+
s_b_m_n_device_buf.ToDevice(s_b_m_n.mData.data());
|
| 274 |
+
{% endif %}
|
| 275 |
+
|
| 276 |
+
{{kernel_name}}(
|
| 277 |
+
static_cast<const AArgType*>(a_m_k_device_buf.GetDeviceBuffer()),
|
| 278 |
+
static_cast<const BArgType*>(b_k_n_device_buf.GetDeviceBuffer()),
|
| 279 |
+
{% if has_scale %}
|
| 280 |
+
static_cast<const ScaleAArgType*>(s_a_m_n_device_buf.GetDeviceBuffer()),
|
| 281 |
+
static_cast<const ScaleBArgType*>(s_b_m_n_device_buf.GetDeviceBuffer()),
|
| 282 |
+
{% endif %}
|
| 283 |
+
{% if has_bias %}
|
| 284 |
+
static_cast<const BiasArgType*>(d_m_n_device_buf.GetDeviceBuffer()),
|
| 285 |
+
{% endif %}
|
| 286 |
+
static_cast<CArgType*>(c_m_n_device_buf.GetDeviceBuffer()),
|
| 287 |
+
{% if is_batched %}
|
| 288 |
+
B,
|
| 289 |
+
{% endif %}
|
| 290 |
+
M,
|
| 291 |
+
N,
|
| 292 |
+
K,
|
| 293 |
+
LDA,
|
| 294 |
+
LDB,
|
| 295 |
+
LDC,
|
| 296 |
+
LDD,
|
| 297 |
+
nullptr, // workspace_size
|
| 298 |
+
nullptr, // workspace
|
| 299 |
+
nullptr); // stream
|
| 300 |
+
|
| 301 |
+
hip_check_error(hipDeviceSynchronize());
|
| 302 |
+
|
| 303 |
+
return 0;
|
| 304 |
+
} // run_main
|
| 305 |
+
} // extern C
|
| 306 |
+
|
| 307 |
+
int main(int argc, char** argv) {
|
| 308 |
+
return run_main(argc, argv);
|
| 309 |
+
}
|
| 310 |
+
// compile with: {{compile_cmd}}
|
| 311 |
+
#endif // GENERATE_CK_STANDALONE_RUNNER
|
| 312 |
+
"""
|
| 313 |
+
|
| 314 |
+
def __init__(
|
| 315 |
+
self,
|
| 316 |
+
input_nodes: list[Buffer],
|
| 317 |
+
layout: Layout,
|
| 318 |
+
alpha: float,
|
| 319 |
+
beta: float,
|
| 320 |
+
input_reorder: Optional[list[int]] = None,
|
| 321 |
+
) -> None:
|
| 322 |
+
is_batched = len(layout.size) == 3
|
| 323 |
+
name = "ck_batched_gemm_template" if is_batched else "ck_gemm_template"
|
| 324 |
+
super().__init__(
|
| 325 |
+
name=name,
|
| 326 |
+
input_nodes=input_nodes,
|
| 327 |
+
layout=layout,
|
| 328 |
+
input_reorder=input_reorder,
|
| 329 |
+
)
|
| 330 |
+
self.alpha = alpha
|
| 331 |
+
self.beta = beta
|
| 332 |
+
self.is_batched = is_batched
|
| 333 |
+
|
| 334 |
+
def header(self) -> IndentedBuffer:
|
| 335 |
+
res = super().header()
|
| 336 |
+
if self.is_batched:
|
| 337 |
+
res.splice(
|
| 338 |
+
"""
|
| 339 |
+
// CK GEMM header(s)
|
| 340 |
+
|
| 341 |
+
#include "ck/tensor_operation/gpu/device/impl/device_batched_gemm_multiple_d_xdl_cshuffle_v3.hpp"
|
| 342 |
+
"""
|
| 343 |
+
)
|
| 344 |
+
else:
|
| 345 |
+
res.splice(
|
| 346 |
+
"""
|
| 347 |
+
// CK GEMM header(s)
|
| 348 |
+
|
| 349 |
+
#include "ck/tensor_operation/gpu/device/impl/device_gemm_multiple_d_xdl_cshuffle_v3.hpp"
|
| 350 |
+
"""
|
| 351 |
+
)
|
| 352 |
+
return res
|
| 353 |
+
|
| 354 |
+
def globals(self) -> IndentedBuffer:
|
| 355 |
+
res = super().globals()
|
| 356 |
+
res.splice(
|
| 357 |
+
"""
|
| 358 |
+
// CK GEMM globals
|
| 359 |
+
|
| 360 |
+
using Row = ck::tensor_layout::gemm::RowMajor;
|
| 361 |
+
using Col = ck::tensor_layout::gemm::ColumnMajor;
|
| 362 |
+
|
| 363 |
+
using BlockGemmPipelineScheduler = ck::BlockGemmPipelineScheduler;
|
| 364 |
+
using GemmSpecialization = ck::tensor_operation::device::GemmSpecialization;
|
| 365 |
+
using BlockGemmPipelineVersion = ck::BlockGemmPipelineVersion;
|
| 366 |
+
|
| 367 |
+
struct MultiplyMultiplyAdd {
|
| 368 |
+
template <typename E, typename C, typename D0, typename D1, typename D2>
|
| 369 |
+
__host__ __device__ constexpr void
|
| 370 |
+
operator()(E& e, const C& c, const D0& d0, const D1& d1, const D2& d2) const {
|
| 371 |
+
e = ck::type_convert<E>(
|
| 372 |
+
ck::type_convert<float>(c)
|
| 373 |
+
* ck::type_convert<float>(d0)
|
| 374 |
+
* ck::type_convert<float>(d1)
|
| 375 |
+
+ ck::type_convert<float>(d2)
|
| 376 |
+
);
|
| 377 |
+
}
|
| 378 |
+
};
|
| 379 |
+
"""
|
| 380 |
+
)
|
| 381 |
+
return res
|
| 382 |
+
|
| 383 |
+
def inline_utils(self):
|
| 384 |
+
res = IndentedBuffer()
|
| 385 |
+
res.splice(
|
| 386 |
+
"""
|
| 387 |
+
#include "host_tensor.cpp"
|
| 388 |
+
#include "device_memory.cpp"
|
| 389 |
+
"""
|
| 390 |
+
)
|
| 391 |
+
return res
|
| 392 |
+
|
| 393 |
+
def _has_padding(self, dimension, gemm_specialization):
|
| 394 |
+
# Get the relevant padding map for the given dimension
|
| 395 |
+
dimension_padding = padding_lookup.get(dimension, {})
|
| 396 |
+
|
| 397 |
+
# Check if the specialization is in the dimension's padding map
|
| 398 |
+
return dimension_padding.get(gemm_specialization, False)
|
| 399 |
+
|
| 400 |
+
def filter_op(self, op_info: InductorROCmOp):
|
| 401 |
+
"""
|
| 402 |
+
Determines whether a given op definition is suitable for the current
|
| 403 |
+
input / output of the operation that this template implements.
|
| 404 |
+
|
| 405 |
+
Filter is based on inputs' dtype, layout and statically inferred size.
|
| 406 |
+
|
| 407 |
+
Returns None if the op is not suitable, otherwise returns the op to be used.
|
| 408 |
+
"""
|
| 409 |
+
op, kBatch = op_info.op, op_info.kBatch
|
| 410 |
+
metas = [T.get_layout() for T in [*self.input_nodes, self.output_node]]
|
| 411 |
+
X_meta = metas[0]
|
| 412 |
+
W_meta = metas[1]
|
| 413 |
+
Y_meta = metas[-1]
|
| 414 |
+
# disable the instance if dtypes don't match
|
| 415 |
+
if op.a_element_dtype != self._TORCH_DTYPE_TO_CK[X_meta.dtype]:
|
| 416 |
+
return None
|
| 417 |
+
if op.b_element_dtype != self._TORCH_DTYPE_TO_CK[W_meta.dtype]:
|
| 418 |
+
return None
|
| 419 |
+
if op.c_element_dtype != self._TORCH_DTYPE_TO_CK[Y_meta.dtype]:
|
| 420 |
+
return None
|
| 421 |
+
# disable the instance if layouts don't match
|
| 422 |
+
if op.a_layout != torch_layout_to_ck_layout(X_meta):
|
| 423 |
+
return None
|
| 424 |
+
if op.b_layout != torch_layout_to_ck_layout(W_meta):
|
| 425 |
+
return None
|
| 426 |
+
if op.c_layout != torch_layout_to_ck_layout(Y_meta):
|
| 427 |
+
return None
|
| 428 |
+
# try to avoid launching the instance with invalid problem size
|
| 429 |
+
# see GridwiseGemm_xdl_cshuffle_v3::CheckValidity
|
| 430 |
+
|
| 431 |
+
M = X_meta.size[-2]
|
| 432 |
+
K = X_meta.size[-1]
|
| 433 |
+
N = W_meta.size[-1]
|
| 434 |
+
|
| 435 |
+
if is_static_int(M):
|
| 436 |
+
if not self._has_padding("M", op.gemm_specialization):
|
| 437 |
+
if M % op.m_per_block != 0:
|
| 438 |
+
return None
|
| 439 |
+
if is_static_int(N):
|
| 440 |
+
if not self._has_padding("N", op.gemm_specialization):
|
| 441 |
+
if N % op.n_per_block != 0:
|
| 442 |
+
return None
|
| 443 |
+
if is_static_int(K):
|
| 444 |
+
if not self._has_padding("K", op.gemm_specialization):
|
| 445 |
+
if K % op.k_per_block != 0:
|
| 446 |
+
return None
|
| 447 |
+
K_t = kBatch * op.k_per_block
|
| 448 |
+
if K % K_t != 0:
|
| 449 |
+
return None
|
| 450 |
+
else:
|
| 451 |
+
# need another kBatch check here
|
| 452 |
+
lcm = abs(op.a_k1 * op.b_k1) // math.gcd(op.a_k1, op.b_k1)
|
| 453 |
+
K_t = kBatch * lcm
|
| 454 |
+
k_read_pad_splited = math.ceil(K / K_t) * lcm
|
| 455 |
+
if (k_read_pad_splited * (kBatch - 1)) >= K:
|
| 456 |
+
return None
|
| 457 |
+
|
| 458 |
+
a_contig_size = (
|
| 459 |
+
K if op.a_layout == "Row" else M if op.a_layout == "Col" else None
|
| 460 |
+
)
|
| 461 |
+
if (
|
| 462 |
+
is_static_int(a_contig_size)
|
| 463 |
+
and a_contig_size % op.a_block_transfer_src_scalar_per_vector != 0
|
| 464 |
+
):
|
| 465 |
+
return None
|
| 466 |
+
b_contig_size = (
|
| 467 |
+
N if op.b_layout == "Row" else K if op.b_layout == "Col" else None
|
| 468 |
+
)
|
| 469 |
+
if (
|
| 470 |
+
is_static_int(b_contig_size)
|
| 471 |
+
and b_contig_size % op.b_block_transfer_src_scalar_per_vector != 0
|
| 472 |
+
):
|
| 473 |
+
return None
|
| 474 |
+
c_contig_size = (
|
| 475 |
+
N if op.c_layout == "Row" else M if op.c_layout == "Col" else None
|
| 476 |
+
)
|
| 477 |
+
c_shuffle_block_transfer_scalar_per_vector_n_per_block = (
|
| 478 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block[0]
|
| 479 |
+
if isinstance(
|
| 480 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, tuple
|
| 481 |
+
)
|
| 482 |
+
else op.c_shuffle_block_transfer_scalar_per_vector_n_per_block
|
| 483 |
+
)
|
| 484 |
+
if (
|
| 485 |
+
is_static_int(c_contig_size)
|
| 486 |
+
and c_contig_size % c_shuffle_block_transfer_scalar_per_vector_n_per_block
|
| 487 |
+
!= 0
|
| 488 |
+
):
|
| 489 |
+
return None
|
| 490 |
+
if not self._check_num_k_loops(op, kBatch):
|
| 491 |
+
return None
|
| 492 |
+
# TBD disable instances with invalid number of pipeline prefetch stages
|
| 493 |
+
# It will avoid compiling a small percentage of unrunnable instances which fail the gemm argument check
|
| 494 |
+
|
| 495 |
+
return op
|
| 496 |
+
|
| 497 |
+
def _check_num_k_loops(self, op, kBatch):
|
| 498 |
+
# Additional splitK scenario check
|
| 499 |
+
metas = [T.get_layout() for T in [*self.input_nodes]]
|
| 500 |
+
X_meta = metas[0]
|
| 501 |
+
W_meta = metas[1]
|
| 502 |
+
K = X_meta.size[-1]
|
| 503 |
+
if kBatch > 1:
|
| 504 |
+
if op.block_gemm_pipeline_version != "BlockGemmPipelineVersion::v1":
|
| 505 |
+
try:
|
| 506 |
+
prefetch_stages = self._prefetch_stages(
|
| 507 |
+
op,
|
| 508 |
+
torch.empty((), dtype=X_meta.dtype).element_size(),
|
| 509 |
+
torch.empty((), dtype=W_meta.dtype).element_size(),
|
| 510 |
+
torch.cuda.get_device_properties(X_meta.device).warp_size,
|
| 511 |
+
)
|
| 512 |
+
except Exception as e:
|
| 513 |
+
log.debug(
|
| 514 |
+
"Failed to prefetch_stages for %s with exception %s", op.name, e
|
| 515 |
+
)
|
| 516 |
+
# be conservative here and disable the op
|
| 517 |
+
return False
|
| 518 |
+
|
| 519 |
+
K_t = op.k_per_block * kBatch
|
| 520 |
+
ak0 = (K + K_t - 1) // K_t * (op.k_per_block // op.a_k1)
|
| 521 |
+
num_k_loop = ak0 // (op.k_per_block // op.a_k1)
|
| 522 |
+
if num_k_loop <= prefetch_stages:
|
| 523 |
+
log.debug(
|
| 524 |
+
"Op %s is not compatible due to invalid number of pipeline prefetch stages. "
|
| 525 |
+
"Parameters: kBatch=%s, block_gemm_pipeline_version=%s, prefetch_stages=%s, num_k_loop=%s",
|
| 526 |
+
op.name(),
|
| 527 |
+
kBatch,
|
| 528 |
+
op.block_gemm_pipeline_version,
|
| 529 |
+
prefetch_stages,
|
| 530 |
+
num_k_loop,
|
| 531 |
+
)
|
| 532 |
+
return False
|
| 533 |
+
|
| 534 |
+
return True
|
| 535 |
+
|
| 536 |
+
# small helper to figure out the prefetch stages on AMD
|
| 537 |
+
def _prefetch_stages(self, op, a_dtype_size, b_dtype_size, warp_size: int = 64):
|
| 538 |
+
version_str = op.block_gemm_pipeline_version.split("::")[-1]
|
| 539 |
+
try:
|
| 540 |
+
version = int(version_str[1:]) # Assuming the format is always 'vX'
|
| 541 |
+
except ValueError as e:
|
| 542 |
+
raise ValueError(f"Invalid version string: {version_str}") from e
|
| 543 |
+
if version not in [1, 2, 3, 4, 5]:
|
| 544 |
+
raise ValueError(
|
| 545 |
+
f"unknown prefetch stages for {op.block_gemm_pipeline_version}"
|
| 546 |
+
)
|
| 547 |
+
# Define the mapping of versions to stages
|
| 548 |
+
version_to_stages = {1: 1, 3: 2, 4: 4, 5: 3}
|
| 549 |
+
# Get the stages for the given version
|
| 550 |
+
stages = version_to_stages.get(version, None)
|
| 551 |
+
if stages is None:
|
| 552 |
+
# This means we're at stage 2, and this requires computation
|
| 553 |
+
# See github.com/ROCm/composable_kernel/blob/d6a4605/include/ck/tensor_operation/gpu/block/blockwise_gemm_pipeline_xdlops_v2.hpp#L143 # noqa: B950
|
| 554 |
+
wgp_per_cu = max(4 * warp_size // op.block_size, 1)
|
| 555 |
+
full_mem_band_prefetch_stages = math.ceil(
|
| 556 |
+
32768
|
| 557 |
+
/ wgp_per_cu
|
| 558 |
+
/ (
|
| 559 |
+
(op.m_per_block * a_dtype_size + op.n_per_block * b_dtype_size)
|
| 560 |
+
* op.k_per_block
|
| 561 |
+
)
|
| 562 |
+
)
|
| 563 |
+
stages = min(max(full_mem_band_prefetch_stages, 2), 8)
|
| 564 |
+
|
| 565 |
+
return stages
|
| 566 |
+
|
| 567 |
+
def emit_ck_instance(self, op: "CKGemmOperation"):
|
| 568 |
+
# The Jinja template for generating a C++ type alias *definition* for a Universal GEMM instance
|
| 569 |
+
struct_name = (
|
| 570 |
+
"DeviceBatchedGemmMultiD_Xdl_CShuffle_V3"
|
| 571 |
+
if self.is_batched
|
| 572 |
+
else "DeviceGemmMultiD_Xdl_CShuffle_V3"
|
| 573 |
+
)
|
| 574 |
+
template_definition = r"""
|
| 575 |
+
// Gemm operator {{operation_name}}
|
| 576 |
+
using Operation_{{operation_name}} =
|
| 577 |
+
ck::tensor_operation::device::{{struct_name}}<
|
| 578 |
+
{{template_params}}>;
|
| 579 |
+
|
| 580 |
+
"""
|
| 581 |
+
# The Jinja template for generating a C++ type alias *usage* for a Universal GEMM instance
|
| 582 |
+
template_type = r"""
|
| 583 |
+
Operation_{{operation_name}}
|
| 584 |
+
"""
|
| 585 |
+
template_params = []
|
| 586 |
+
for field_name, field_value in op.dict_items():
|
| 587 |
+
if isinstance(field_value, tuple):
|
| 588 |
+
tuple_elements = ", ".join(map(str, iter(field_value)))
|
| 589 |
+
if "ds" in field_name: # element type and layout for bias
|
| 590 |
+
arg = f"/* {field_name} */ Tuple<{tuple_elements}>"
|
| 591 |
+
else: # tile shape
|
| 592 |
+
arg = f"/* {field_name} */ S<{tuple_elements}>"
|
| 593 |
+
template_params.append(arg)
|
| 594 |
+
else:
|
| 595 |
+
if field_value is not None:
|
| 596 |
+
template_params.append(f"/* {field_name} */ {field_value}")
|
| 597 |
+
operation_name = op.name().replace("(", "").replace(",", "").replace(")", "")
|
| 598 |
+
return self._template_from_string(template_definition).render(
|
| 599 |
+
operation_name=operation_name,
|
| 600 |
+
template_params=(",\n" + 12 * " ").join(template_params),
|
| 601 |
+
struct_name=struct_name,
|
| 602 |
+
), self._template_from_string(template_type).render(
|
| 603 |
+
operation_name=operation_name
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
def render( # type: ignore[override]
|
| 607 |
+
self,
|
| 608 |
+
kernel: ROCmTemplateKernel,
|
| 609 |
+
op: "CKGemmOperation",
|
| 610 |
+
**kwargs,
|
| 611 |
+
) -> str:
|
| 612 |
+
"""
|
| 613 |
+
The primary entry point for the code rendering process used in this template.
|
| 614 |
+
"""
|
| 615 |
+
epilogue_nodes = kwargs.get("epilogue_nodes", None)
|
| 616 |
+
assert epilogue_nodes is None or 0 == len(epilogue_nodes)
|
| 617 |
+
template_buffer_node = kwargs.get("template_buffer_node", None)
|
| 618 |
+
if template_buffer_node is not None:
|
| 619 |
+
self.output_node = template_buffer_node
|
| 620 |
+
# input nodes:
|
| 621 |
+
# * X, W for matmul
|
| 622 |
+
# * X, W, Bias for addmm
|
| 623 |
+
# * X, W, inv_scale_x, inv_scale_w for scaled_mm
|
| 624 |
+
# * X, W, inv_scale_x, inv_scale_w, Bias for scaled_mm with bias
|
| 625 |
+
X, W = self.input_nodes[0], self.input_nodes[1]
|
| 626 |
+
Y = self.output_node
|
| 627 |
+
Bias = (
|
| 628 |
+
self.input_nodes[2]
|
| 629 |
+
if 3 == len(self.input_nodes)
|
| 630 |
+
else self.input_nodes[4]
|
| 631 |
+
if 5 == len(self.input_nodes)
|
| 632 |
+
else None
|
| 633 |
+
)
|
| 634 |
+
has_bias = Bias is not None
|
| 635 |
+
has_scale = len(self.input_nodes) in (4, 5)
|
| 636 |
+
op = copy.deepcopy(op)
|
| 637 |
+
|
| 638 |
+
# This parameter is converted into tuple because of change
|
| 639 |
+
# from DeviceGemm_Xdl_CShuffleV3 to DeviceGemmMultiD_Xdl_CShuffle_V3.
|
| 640 |
+
# The first tuple element corresponds to matmul result...
|
| 641 |
+
if not isinstance(
|
| 642 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block, tuple
|
| 643 |
+
):
|
| 644 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block = (
|
| 645 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block,
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
if has_scale:
|
| 649 |
+
scale_x = self.input_nodes[2]
|
| 650 |
+
scale_w = self.input_nodes[3]
|
| 651 |
+
if 1 == scale_x.get_numel() and 1 == scale_w.get_numel():
|
| 652 |
+
# tensorwise scale for both X, W
|
| 653 |
+
if has_bias:
|
| 654 |
+
op.c_elementwise_op = "ScaleAdd"
|
| 655 |
+
else:
|
| 656 |
+
op.c_elementwise_op = "Scale"
|
| 657 |
+
else:
|
| 658 |
+
# rowwise scale for both X, W
|
| 659 |
+
if has_bias:
|
| 660 |
+
op.c_elementwise_op = "MultiplyMultiplyAdd"
|
| 661 |
+
else:
|
| 662 |
+
op.c_elementwise_op = "MultiplyMultiply"
|
| 663 |
+
op.c_shuffle_dtype = "F32"
|
| 664 |
+
op.ds_layouts = (
|
| 665 |
+
torch_layout_to_ck_layout(scale_x.get_layout()),
|
| 666 |
+
torch_layout_to_ck_layout(scale_w.get_layout()),
|
| 667 |
+
)
|
| 668 |
+
op.ds_element_dtypes = (
|
| 669 |
+
self._TORCH_DTYPE_TO_CK[scale_x.get_layout().dtype],
|
| 670 |
+
self._TORCH_DTYPE_TO_CK[scale_w.get_layout().dtype],
|
| 671 |
+
)
|
| 672 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block += (1, 1)
|
| 673 |
+
else:
|
| 674 |
+
scale_x = None
|
| 675 |
+
scale_w = None
|
| 676 |
+
|
| 677 |
+
bias_dtype = ""
|
| 678 |
+
if Bias is not None:
|
| 679 |
+
bias_layout = torch_layout_to_ck_layout(Bias.get_layout())
|
| 680 |
+
bias_dtype = self._TORCH_DTYPE_TO_CK[Bias.get_layout().dtype]
|
| 681 |
+
op.ds_layouts += (bias_layout,)
|
| 682 |
+
op.ds_element_dtypes += (bias_dtype,)
|
| 683 |
+
if not has_scale:
|
| 684 |
+
op.c_elementwise_op = "Bilinear"
|
| 685 |
+
# c_shuffle_dtype is also used for adding bias to matmul result
|
| 686 |
+
# before converting down to the result dtype
|
| 687 |
+
op.c_shuffle_dtype = op.acc_dtype
|
| 688 |
+
# this parameter needs to be set accordingly to bias stride for correct accumulation
|
| 689 |
+
if bias_layout == "Row":
|
| 690 |
+
# bias has (N, ) shape
|
| 691 |
+
bias_shuffle_block_transfer_scalar_per_vector_n_per_block = (
|
| 692 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block
|
| 693 |
+
)
|
| 694 |
+
elif bias_layout == "Col":
|
| 695 |
+
# bias has (M, 1) shape
|
| 696 |
+
bias_shuffle_block_transfer_scalar_per_vector_n_per_block = (1,)
|
| 697 |
+
else:
|
| 698 |
+
raise AssertionError(
|
| 699 |
+
"Bias layout is neither row-major nor column-major"
|
| 700 |
+
)
|
| 701 |
+
# ...and the second tuple element corresponds to the bias
|
| 702 |
+
op.c_shuffle_block_transfer_scalar_per_vector_n_per_block += (
|
| 703 |
+
bias_shuffle_block_transfer_scalar_per_vector_n_per_block
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
instance_definition, instance_type = self.emit_ck_instance(op)
|
| 707 |
+
|
| 708 |
+
version_comment = rf"""/**
|
| 709 |
+
* Generated code for CK inductor backend
|
| 710 |
+
* See {type(self).__module__}.{type(self).__qualname__}
|
| 711 |
+
*
|
| 712 |
+
* Template instance {op}
|
| 713 |
+
*
|
| 714 |
+
* {torch.__version__=}
|
| 715 |
+
* torch.version.git_version={getattr(torch.version, "git_version", "None")}
|
| 716 |
+
*/
|
| 717 |
+
"""
|
| 718 |
+
epilogue = None
|
| 719 |
+
|
| 720 |
+
if op.c_elementwise_op == "Bilinear" and scale_w is None:
|
| 721 |
+
epilogue = f"Bilinear {{ {self.alpha}, {self.beta} }}"
|
| 722 |
+
|
| 723 |
+
elif op.c_elementwise_op == "Scale":
|
| 724 |
+
epilogue = "Scale { (inv_scale_w && inv_scale_x) ? (*inv_scale_w * *inv_scale_x) : 1.0f }"
|
| 725 |
+
|
| 726 |
+
elif op.c_elementwise_op == "ScaleAdd":
|
| 727 |
+
epilogue = "ScaleAdd { (inv_scale_w && inv_scale_x) ? (*inv_scale_w * *inv_scale_x) : 1.0f }"
|
| 728 |
+
|
| 729 |
+
elif op.c_elementwise_op == "MultiplyMultiply":
|
| 730 |
+
epilogue = "MultiplyMultiply {}"
|
| 731 |
+
|
| 732 |
+
elif op.c_elementwise_op == "MultiplyMultiplyAdd":
|
| 733 |
+
epilogue = "MultiplyMultiplyAdd {}"
|
| 734 |
+
|
| 735 |
+
elif op.c_elementwise_op == "PassThrough":
|
| 736 |
+
epilogue = "PassThrough {}"
|
| 737 |
+
|
| 738 |
+
assert epilogue is not None, "CK GEMM epilogue is not set"
|
| 739 |
+
|
| 740 |
+
size_arg_strs = ["M", "N", "K", "LDA", "LDB", "LDC", "LDD"]
|
| 741 |
+
if self.is_batched:
|
| 742 |
+
size_arg_strs.insert(0, "B")
|
| 743 |
+
|
| 744 |
+
res = self._template_from_string(self.gemm_template).render(
|
| 745 |
+
inline_utils=self.inline_utils(),
|
| 746 |
+
headers=self.header().getvalue(),
|
| 747 |
+
globals=self.globals().getvalue(),
|
| 748 |
+
instance_definition=instance_definition,
|
| 749 |
+
kernel_definition=kernel.def_kernel(
|
| 750 |
+
inputs=[X, W, scale_x, scale_w, Bias], # type: ignore[list-item]
|
| 751 |
+
outputs=[Y],
|
| 752 |
+
names_str="X, W, inv_scale_x, inv_scale_w, Bias, Y",
|
| 753 |
+
input_reorder=self.input_reorder,
|
| 754 |
+
size_args=[f"int32_t {arg}" for arg in size_arg_strs],
|
| 755 |
+
),
|
| 756 |
+
instance_type=instance_type,
|
| 757 |
+
a_element_dtype=op.a_element_dtype,
|
| 758 |
+
b_element_dtype=op.b_element_dtype,
|
| 759 |
+
c_element_dtype=op.c_element_dtype,
|
| 760 |
+
bias_element_dtype=bias_dtype,
|
| 761 |
+
alpha=self.alpha,
|
| 762 |
+
beta=self.beta,
|
| 763 |
+
a_elementwise_op="PassThrough {}",
|
| 764 |
+
b_elementwise_op="PassThrough {}",
|
| 765 |
+
epilogue=epilogue,
|
| 766 |
+
has_bias=has_bias,
|
| 767 |
+
ds_size=1
|
| 768 |
+
if op.c_elementwise_op in ("Bilinear", "ScaleAdd")
|
| 769 |
+
else 2
|
| 770 |
+
if op.c_elementwise_op == "MultiplyMultiply"
|
| 771 |
+
else 3
|
| 772 |
+
if op.c_elementwise_op == "MultiplyMultiplyAdd"
|
| 773 |
+
else 0,
|
| 774 |
+
ds_names=", ".join(
|
| 775 |
+
["Bias"]
|
| 776 |
+
if op.c_elementwise_op in ("Bilinear", "ScaleAdd")
|
| 777 |
+
else ["inv_scale_x", "inv_scale_w"]
|
| 778 |
+
if op.c_elementwise_op == "MultiplyMultiply"
|
| 779 |
+
else ["inv_scale_x", "inv_scale_w", "Bias"]
|
| 780 |
+
if op.c_elementwise_op == "MultiplyMultiplyAdd"
|
| 781 |
+
else []
|
| 782 |
+
),
|
| 783 |
+
ds_strides=", ".join(
|
| 784 |
+
["LDD"]
|
| 785 |
+
if op.c_elementwise_op in ("Bilinear", "ScaleAdd")
|
| 786 |
+
else ["0", "0"]
|
| 787 |
+
if op.c_elementwise_op == "MultiplyMultiply"
|
| 788 |
+
else ["0", "0", "LDD"]
|
| 789 |
+
if op.c_elementwise_op == "MultiplyMultiplyAdd"
|
| 790 |
+
else []
|
| 791 |
+
),
|
| 792 |
+
version_comment=version_comment,
|
| 793 |
+
is_batched=self.is_batched,
|
| 794 |
+
ds_batch_strides=", ".join([]), # FIXME when supporting baddbmm
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
if config.rocm.generate_test_runner:
|
| 798 |
+
is_static_problem = all(is_static_int(arg) for arg in self.size_args())
|
| 799 |
+
# NOTE: size_arg_strs is defined above
|
| 800 |
+
size_arg_vals = (
|
| 801 |
+
self.size_args()
|
| 802 |
+
if is_static_problem
|
| 803 |
+
else (
|
| 804 |
+
f"std::stoi(argv[{k}])" for k, _ in enumerate(self.size_args(), 1)
|
| 805 |
+
)
|
| 806 |
+
)
|
| 807 |
+
size_args = dict(zip(size_arg_strs, size_arg_vals, strict=True))
|
| 808 |
+
runtime_args = dict(
|
| 809 |
+
zip(
|
| 810 |
+
[a.name for a in self.get_runtime_arg_info()],
|
| 811 |
+
self.get_runtime_arg_values(),
|
| 812 |
+
)
|
| 813 |
+
)
|
| 814 |
+
runner_code = self._template_from_string(
|
| 815 |
+
self.standalone_runner_template
|
| 816 |
+
).render(
|
| 817 |
+
inline_utils=self.inline_utils().getvalue(),
|
| 818 |
+
kernel_name=kernel.kernel_name,
|
| 819 |
+
has_bias=has_bias,
|
| 820 |
+
has_scale=has_scale,
|
| 821 |
+
is_batched=self.is_batched,
|
| 822 |
+
a_ck_dtype=op.a_element_dtype,
|
| 823 |
+
b_ck_dtype=op.b_element_dtype,
|
| 824 |
+
c_ck_dtype=op.c_element_dtype,
|
| 825 |
+
bias_ck_dtype=op.ds_element_dtypes[0] if has_bias else "",
|
| 826 |
+
scale_a_ck_dtype=op.ds_element_dtypes[0]
|
| 827 |
+
if has_scale and 2 == len(op.ds_element_dtypes)
|
| 828 |
+
else "BF16",
|
| 829 |
+
scale_b_ck_dtype=op.ds_element_dtypes[1]
|
| 830 |
+
if has_scale and 2 == len(op.ds_element_dtypes)
|
| 831 |
+
else "BF16",
|
| 832 |
+
a_torch_dtype=DTYPE_TO_CPP[X.get_layout().dtype],
|
| 833 |
+
b_torch_dtype=DTYPE_TO_CPP[W.get_layout().dtype],
|
| 834 |
+
c_torch_dtype=DTYPE_TO_CPP[Y.get_layout().dtype],
|
| 835 |
+
bias_torch_dtype=DTYPE_TO_CPP[Bias.get_layout().dtype]
|
| 836 |
+
if Bias is not None
|
| 837 |
+
else "",
|
| 838 |
+
scale_a_torch_dtype=DTYPE_TO_CPP[scale_x.get_layout().dtype]
|
| 839 |
+
if scale_x is not None
|
| 840 |
+
else "",
|
| 841 |
+
scale_b_torch_dtype=DTYPE_TO_CPP[scale_w.get_layout().dtype]
|
| 842 |
+
if scale_w is not None
|
| 843 |
+
else "",
|
| 844 |
+
a_layout=torch_layout_to_ck_layout(X.get_layout()),
|
| 845 |
+
b_layout=torch_layout_to_ck_layout(W.get_layout()),
|
| 846 |
+
c_layout=torch_layout_to_ck_layout(Y.get_layout()),
|
| 847 |
+
bias_layout=torch_layout_to_ck_layout(Bias.get_layout())
|
| 848 |
+
if Bias is not None
|
| 849 |
+
else "",
|
| 850 |
+
compile_cmd=rocm_compile_command(
|
| 851 |
+
["<source_file_name>"], "<executable_name>", "exe"
|
| 852 |
+
),
|
| 853 |
+
**size_args,
|
| 854 |
+
**runtime_args,
|
| 855 |
+
)
|
| 856 |
+
res += runner_code
|
| 857 |
+
|
| 858 |
+
return res
|
| 859 |
+
|
| 860 |
+
def _is_rcr_f16(self):
|
| 861 |
+
X_meta, W_meta, Y_meta = (
|
| 862 |
+
T.get_layout() for T in [*self.input_nodes, self.output_node]
|
| 863 |
+
)
|
| 864 |
+
X_dtype, W_dtype, Y_dtype = (
|
| 865 |
+
self._TORCH_DTYPE_TO_CK[m.dtype] for m in (X_meta, W_meta, Y_meta)
|
| 866 |
+
)
|
| 867 |
+
X_layout, W_layout, Y_layout = (
|
| 868 |
+
torch_layout_to_ck_layout(m) for m in (X_meta, W_meta, Y_meta)
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
return (
|
| 872 |
+
X_dtype == "F16"
|
| 873 |
+
and W_dtype == "F16"
|
| 874 |
+
and Y_dtype == "F16"
|
| 875 |
+
and X_layout == "Row"
|
| 876 |
+
and W_layout == "Col"
|
| 877 |
+
and Y_layout == "Row"
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
# helper to calculate a potentially optimal kBatch(es) for a problem
|
| 881 |
+
def _get_kBatch(self, op):
|
| 882 |
+
# we only set a higher kBatch if K > 16 * the larger of M and N
|
| 883 |
+
# this is a hand-tuned heuristic to start
|
| 884 |
+
metas = [T.get_layout() for T in [*self.input_nodes]]
|
| 885 |
+
X_meta = metas[0]
|
| 886 |
+
W_meta = metas[1]
|
| 887 |
+
M = X_meta.size[-2]
|
| 888 |
+
K = X_meta.size[-1]
|
| 889 |
+
N = W_meta.size[-1]
|
| 890 |
+
if is_dynamic(*self.input_nodes):
|
| 891 |
+
return [1]
|
| 892 |
+
if K // max(M, N) < config.rocm.split_k_threshold:
|
| 893 |
+
return [1]
|
| 894 |
+
# if the user is telling us which kBatches to sweep, just use those
|
| 895 |
+
if config.rocm.kBatch_sweep is not None:
|
| 896 |
+
return config.rocm.kBatch_sweep
|
| 897 |
+
# Calculate the number of blocks needed for each dimension
|
| 898 |
+
total_k_blocks = math.ceil(K / op.k_per_block)
|
| 899 |
+
# we want to calculate how many blocks we need to fit per CU
|
| 900 |
+
cus = torch.cuda.get_device_properties(X_meta.device).multi_processor_count
|
| 901 |
+
# again, manual heuristics as much larger kBatch are significantly worse in
|
| 902 |
+
# initial testing
|
| 903 |
+
kBatch = min(max(next_power_of_2(total_k_blocks // cus), 1), 128)
|
| 904 |
+
return [kBatch]
|
| 905 |
+
|
| 906 |
+
def gen_ops(self) -> list[InductorROCmOp]:
|
| 907 |
+
"""
|
| 908 |
+
Creates a list of `CKGemmOperation` instances that match the GEMM operation this template represents.
|
| 909 |
+
The instances are guaranteed to have the correct layout, dtype and dimension padding for the GEMM input arguments.
|
| 910 |
+
|
| 911 |
+
An instance may invalidate the GEMM configuration at runtime.
|
| 912 |
+
Such instances will be assigned +inf runtime by the autotune process.
|
| 913 |
+
"""
|
| 914 |
+
try:
|
| 915 |
+
from ck4inductor.batched_universal_gemm.gen_instances import ( # type: ignore[import]
|
| 916 |
+
gen_ops_library as gen_batched_gemm_ops_library,
|
| 917 |
+
)
|
| 918 |
+
from ck4inductor.universal_gemm.gen_instances import ( # type: ignore[import]
|
| 919 |
+
gen_ops_library as gen_gemm_ops_library,
|
| 920 |
+
gen_ops_preselected as gen_gemm_ops_preselected,
|
| 921 |
+
)
|
| 922 |
+
except ImportError:
|
| 923 |
+
return []
|
| 924 |
+
|
| 925 |
+
generator = None
|
| 926 |
+
if self.is_batched:
|
| 927 |
+
generator = gen_batched_gemm_ops_library
|
| 928 |
+
else:
|
| 929 |
+
generator = gen_gemm_ops_library
|
| 930 |
+
if config.rocm.use_preselected_instances and self._is_rcr_f16():
|
| 931 |
+
generator = gen_gemm_ops_preselected
|
| 932 |
+
|
| 933 |
+
assert generator is not None
|
| 934 |
+
|
| 935 |
+
rops = generator()
|
| 936 |
+
ops = []
|
| 937 |
+
for o in rops:
|
| 938 |
+
kBatches = self._get_kBatch(o)
|
| 939 |
+
for kBatch in kBatches:
|
| 940 |
+
ops.append(InductorROCmOp(op=o, kBatch=kBatch))
|
| 941 |
+
|
| 942 |
+
filtered_instances = list(filter(lambda op: self.filter_op(op), ops))
|
| 943 |
+
|
| 944 |
+
# NB: when using a fixed list order, most likely we will pick the subset of instances
|
| 945 |
+
# which are very similar to each other. Randomizing the choice seems to solve this.
|
| 946 |
+
random.seed(-11)
|
| 947 |
+
chosen_instances = (
|
| 948 |
+
random.sample(
|
| 949 |
+
filtered_instances,
|
| 950 |
+
min(len(filtered_instances), config.rocm.ck_max_profiling_configs),
|
| 951 |
+
)
|
| 952 |
+
if config.rocm.ck_max_profiling_configs
|
| 953 |
+
else filtered_instances
|
| 954 |
+
)
|
| 955 |
+
log.debug(
|
| 956 |
+
"generated %d ck instances after filter: %s",
|
| 957 |
+
len(chosen_instances),
|
| 958 |
+
chosen_instances,
|
| 959 |
+
)
|
| 960 |
+
return chosen_instances
|
| 961 |
+
|
| 962 |
+
@staticmethod
|
| 963 |
+
def add_ck_gemm_choices(
|
| 964 |
+
choices,
|
| 965 |
+
layout,
|
| 966 |
+
input_nodes,
|
| 967 |
+
alpha=1,
|
| 968 |
+
beta=0,
|
| 969 |
+
input_reorder=None,
|
| 970 |
+
):
|
| 971 |
+
"""
|
| 972 |
+
Add Composable Kernel Universal GEMM instance choices to the auto-tuning list.
|
| 973 |
+
"""
|
| 974 |
+
template = CKGemmTemplate(
|
| 975 |
+
input_nodes,
|
| 976 |
+
layout,
|
| 977 |
+
alpha=alpha,
|
| 978 |
+
beta=beta,
|
| 979 |
+
input_reorder=input_reorder,
|
| 980 |
+
)
|
| 981 |
+
ops = template.gen_ops()
|
| 982 |
+
for op in ops:
|
| 983 |
+
template.maybe_append_choice(
|
| 984 |
+
choices,
|
| 985 |
+
op=op.op,
|
| 986 |
+
kBatch=op.kBatch,
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
def size_args(self):
|
| 990 |
+
X = self.input_nodes[0]
|
| 991 |
+
W = self.input_nodes[1]
|
| 992 |
+
Bias = (
|
| 993 |
+
self.input_nodes[2]
|
| 994 |
+
if len(self.input_nodes) == 3
|
| 995 |
+
else self.input_nodes[4]
|
| 996 |
+
if len(self.input_nodes) == 5
|
| 997 |
+
else None
|
| 998 |
+
)
|
| 999 |
+
Y = self.output_node
|
| 1000 |
+
|
| 1001 |
+
M = X.get_size()[-2]
|
| 1002 |
+
K = X.get_size()[-1]
|
| 1003 |
+
N = W.get_size()[-1]
|
| 1004 |
+
LDA = X.get_stride()[-2 if X.get_stride()[-1] == 1 else -1]
|
| 1005 |
+
LDB = W.get_stride()[-2 if W.get_stride()[-1] == 1 else -1]
|
| 1006 |
+
LDC = Y.get_stride()[-2 if Y.get_stride()[-1] == 1 else -1]
|
| 1007 |
+
LDD = (
|
| 1008 |
+
0
|
| 1009 |
+
if (Bias is None or len(Bias.get_size()) == 1)
|
| 1010 |
+
else Bias.get_stride()[-2 if Bias.get_stride()[-1] == 1 else -1]
|
| 1011 |
+
)
|
| 1012 |
+
if self.is_batched:
|
| 1013 |
+
B = X.get_size()[0]
|
| 1014 |
+
return B, M, N, K, LDA, LDB, LDC, LDD
|
| 1015 |
+
else:
|
| 1016 |
+
return M, N, K, LDA, LDB, LDC, LDD
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/compile_command.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
from torch._inductor import config
|
| 7 |
+
from torch._inductor.utils import is_linux
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
log = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _rocm_include_paths(dst_file_ext: str) -> list[str]:
|
| 14 |
+
from torch.utils import cpp_extension
|
| 15 |
+
|
| 16 |
+
rocm_include = (
|
| 17 |
+
os.path.join(config.rocm.rocm_home, "include")
|
| 18 |
+
if config.rocm.rocm_home
|
| 19 |
+
else cpp_extension._join_rocm_home("include")
|
| 20 |
+
)
|
| 21 |
+
if not config.rocm.ck_dir:
|
| 22 |
+
log.warning("Unspecified Composable Kernel include dir")
|
| 23 |
+
|
| 24 |
+
if config.is_fbcode():
|
| 25 |
+
from libfb.py import parutil
|
| 26 |
+
|
| 27 |
+
ck_path = parutil.get_dir_path("composable-kernel-headers")
|
| 28 |
+
else:
|
| 29 |
+
ck_path = config.rocm.ck_dir or cpp_extension._join_rocm_home(
|
| 30 |
+
"composable_kernel"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
ck_include = os.path.join(ck_path, "include")
|
| 34 |
+
ck_library_include = os.path.join(ck_path, "library", "include")
|
| 35 |
+
|
| 36 |
+
# CK has to take priority over ROCm include paths
|
| 37 |
+
# Since CK is potentially more up-to-date
|
| 38 |
+
paths = [
|
| 39 |
+
os.path.realpath(p) for p in (ck_include, ck_library_include, rocm_include)
|
| 40 |
+
]
|
| 41 |
+
if dst_file_ext == "exe":
|
| 42 |
+
ck_utility_include = os.path.join(ck_path, "library", "src", "utility")
|
| 43 |
+
paths.append(os.path.realpath(ck_utility_include))
|
| 44 |
+
return paths
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _rocm_lib_options(dst_file_ext: str) -> list[str]:
|
| 48 |
+
from torch.utils import cpp_extension
|
| 49 |
+
|
| 50 |
+
rocm_lib_dir = (
|
| 51 |
+
os.path.join(config.rocm.rocm_home, "lib")
|
| 52 |
+
if config.rocm.rocm_home
|
| 53 |
+
else cpp_extension._join_rocm_home("lib")
|
| 54 |
+
)
|
| 55 |
+
hip_lib_dir = (
|
| 56 |
+
os.path.join(config.rocm.rocm_home, "hip", "lib")
|
| 57 |
+
if config.rocm.rocm_home
|
| 58 |
+
else cpp_extension._join_rocm_home("hip", "lib")
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
opts = [
|
| 62 |
+
"-include __clang_hip_runtime_wrapper.h",
|
| 63 |
+
f"-L{os.path.realpath(rocm_lib_dir)}",
|
| 64 |
+
f"-L{os.path.realpath(hip_lib_dir)}",
|
| 65 |
+
"-lamdhip64",
|
| 66 |
+
]
|
| 67 |
+
if dst_file_ext == "exe":
|
| 68 |
+
opts += ["-lpthread", "-lstdc++"]
|
| 69 |
+
return opts
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _rocm_compiler_options() -> list[str]:
|
| 73 |
+
arch_list = config.rocm.arch or ["native"]
|
| 74 |
+
gpu_arch_flags = [f"--offload-arch={arch}" for arch in arch_list]
|
| 75 |
+
opts = [
|
| 76 |
+
config.rocm.compile_opt_level,
|
| 77 |
+
"-x",
|
| 78 |
+
"hip",
|
| 79 |
+
"-std=c++17",
|
| 80 |
+
*gpu_arch_flags,
|
| 81 |
+
"-fno-gpu-rdc",
|
| 82 |
+
"-fPIC",
|
| 83 |
+
"-fvisibility=hidden",
|
| 84 |
+
"-mllvm",
|
| 85 |
+
"-amdgpu-early-inline-all=true",
|
| 86 |
+
"-mllvm",
|
| 87 |
+
"-amdgpu-function-calls=false",
|
| 88 |
+
"-mllvm",
|
| 89 |
+
"-enable-post-misched=0",
|
| 90 |
+
]
|
| 91 |
+
if config.rocm.is_debug:
|
| 92 |
+
opts += ["-DDEBUG_LOG=1", "-g"]
|
| 93 |
+
if config.rocm.save_temps:
|
| 94 |
+
opts += ["--save-temps=obj"]
|
| 95 |
+
if config.rocm.print_kernel_resource_usage:
|
| 96 |
+
opts += ["-Rpass-analysis=kernel-resource-usage"]
|
| 97 |
+
if config.rocm.flush_denormals:
|
| 98 |
+
opts += ["-fgpu-flush-denormals-to-zero"]
|
| 99 |
+
if config.rocm.use_fast_math:
|
| 100 |
+
opts += ["-ffast-math"]
|
| 101 |
+
return opts
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def rocm_compiler() -> Optional[str]:
|
| 105 |
+
if is_linux():
|
| 106 |
+
if config.rocm.rocm_home:
|
| 107 |
+
return os.path.realpath(
|
| 108 |
+
os.path.join(config.rocm.rocm_home, "llvm", "bin", "clang")
|
| 109 |
+
)
|
| 110 |
+
try:
|
| 111 |
+
from torch.utils import cpp_extension
|
| 112 |
+
|
| 113 |
+
return os.path.realpath(
|
| 114 |
+
cpp_extension._join_rocm_home("llvm", "bin", "clang")
|
| 115 |
+
)
|
| 116 |
+
except OSError:
|
| 117 |
+
# neither config.rocm.rocm_home nor env variable ROCM_HOME are set
|
| 118 |
+
return "clang"
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def rocm_compile_command(
|
| 123 |
+
src_files: list[str],
|
| 124 |
+
dst_file: str,
|
| 125 |
+
dst_file_ext: str,
|
| 126 |
+
extra_args: Optional[list[str]] = None,
|
| 127 |
+
) -> str:
|
| 128 |
+
include_paths = _rocm_include_paths(dst_file_ext)
|
| 129 |
+
lib_options = _rocm_lib_options(dst_file_ext)
|
| 130 |
+
compiler_options = _rocm_compiler_options()
|
| 131 |
+
compiler = rocm_compiler()
|
| 132 |
+
options = (
|
| 133 |
+
compiler_options
|
| 134 |
+
+ (extra_args or [])
|
| 135 |
+
+ [f"-I{path}" for path in include_paths]
|
| 136 |
+
+ lib_options
|
| 137 |
+
)
|
| 138 |
+
src_file = " ".join(src_files)
|
| 139 |
+
# supported extensions: .o, .so, .exe
|
| 140 |
+
if dst_file_ext == "o":
|
| 141 |
+
options.append("-c")
|
| 142 |
+
elif dst_file_ext == "so":
|
| 143 |
+
options.append("-shared")
|
| 144 |
+
elif dst_file_ext == "exe":
|
| 145 |
+
options.append("-DGENERATE_CK_STANDALONE_RUNNER")
|
| 146 |
+
else:
|
| 147 |
+
raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!")
|
| 148 |
+
return f"{compiler} {' '.join(options)} -o {dst_file} {src_file}"
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_benchmark_request.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import functools
|
| 5 |
+
import logging
|
| 6 |
+
from ctypes import byref, c_int, c_size_t, c_void_p
|
| 7 |
+
from typing import Any, Callable, Optional, TYPE_CHECKING, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch._inductor import config
|
| 11 |
+
from torch._inductor.autotune_process import (
|
| 12 |
+
BenchmarkRequest,
|
| 13 |
+
GPUDeviceBenchmarkMixin,
|
| 14 |
+
TensorMeta,
|
| 15 |
+
)
|
| 16 |
+
from torch._inductor.codecache import DLLWrapper, ROCmCodeCache
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from collections.abc import Iterable
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ROCmBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest):
|
| 27 |
+
# Important: Instances of this class have to be serializable
|
| 28 |
+
# across process boundaries. Do not put CUDA Tensors in here!
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
kernel_name: str,
|
| 33 |
+
input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
|
| 34 |
+
output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
|
| 35 |
+
extra_args: Iterable[Any],
|
| 36 |
+
source_code: str,
|
| 37 |
+
) -> None:
|
| 38 |
+
super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
|
| 39 |
+
self.source_code = source_code
|
| 40 |
+
self.workspace_size: int = 0
|
| 41 |
+
self.workspace: Optional[torch.Tensor] = None
|
| 42 |
+
self.DLL: Optional[DLLWrapper] = None
|
| 43 |
+
self._workspace_size_updated = False
|
| 44 |
+
self.hash_key: str = ""
|
| 45 |
+
self.source_file: str = ""
|
| 46 |
+
self.hash_key, self.source_file = ROCmCodeCache.write(self.source_code, "so")
|
| 47 |
+
|
| 48 |
+
def precompile(self):
|
| 49 |
+
# Prepopulate code cache
|
| 50 |
+
# may happen in separate Threadpool
|
| 51 |
+
log.debug("Precompiling %s", self)
|
| 52 |
+
ROCmCodeCache.compile(self.source_code, "so")
|
| 53 |
+
if config.rocm.generate_test_runner:
|
| 54 |
+
ROCmCodeCache.compile(self.source_code, "exe")
|
| 55 |
+
log.debug("Done precompiling %s", self)
|
| 56 |
+
|
| 57 |
+
def make_run_fn(
|
| 58 |
+
self, *input_tensors: torch.Tensor, out: torch.Tensor
|
| 59 |
+
) -> Callable[[], None]:
|
| 60 |
+
self.ensure_dll_loaded()
|
| 61 |
+
self.update_workspace_size()
|
| 62 |
+
args = [c_void_p(tensor.data_ptr()) for tensor in list(input_tensors) + [out]]
|
| 63 |
+
size_args = [c_int(arg) for arg in self.extra_args]
|
| 64 |
+
log.debug(
|
| 65 |
+
"make_run_fn: self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s",
|
| 66 |
+
self.kernel_name,
|
| 67 |
+
self.source_file,
|
| 68 |
+
self.hash_key,
|
| 69 |
+
self.DLL,
|
| 70 |
+
args,
|
| 71 |
+
self.extra_args,
|
| 72 |
+
)
|
| 73 |
+
stream_ptr = c_void_p(torch.cuda.current_stream().cuda_stream)
|
| 74 |
+
run_method = getattr(self.DLL, self.kernel_name)
|
| 75 |
+
workspace_ptr = c_void_p(0)
|
| 76 |
+
if self.workspace_size > 0:
|
| 77 |
+
self.workspace = torch.zeros(
|
| 78 |
+
(self.workspace_size + 7) // 8,
|
| 79 |
+
dtype=torch.float64,
|
| 80 |
+
device=out.device,
|
| 81 |
+
)
|
| 82 |
+
workspace_ptr = c_void_p(self.workspace.data_ptr())
|
| 83 |
+
|
| 84 |
+
# Generate partial function.
|
| 85 |
+
return functools.partial(
|
| 86 |
+
run_method,
|
| 87 |
+
*args,
|
| 88 |
+
*size_args,
|
| 89 |
+
None, # null workspace size ptr
|
| 90 |
+
workspace_ptr, # set workspace ptr,
|
| 91 |
+
stream_ptr,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def update_workspace_size(self) -> None:
|
| 95 |
+
if self._workspace_size_updated:
|
| 96 |
+
return
|
| 97 |
+
self.ensure_dll_loaded()
|
| 98 |
+
unique_input_count = len(
|
| 99 |
+
dict.fromkeys(meta.name for meta in self.input_tensor_meta)
|
| 100 |
+
)
|
| 101 |
+
args = [c_void_p(None) for _ in range(unique_input_count + 1)]
|
| 102 |
+
stream_ptr = c_void_p(torch.cuda.current_stream().cuda_stream)
|
| 103 |
+
|
| 104 |
+
run_method = getattr(self.DLL, self.kernel_name)
|
| 105 |
+
# Retrieve workspace_size and initialize workspace.
|
| 106 |
+
c_workspace_size = c_size_t()
|
| 107 |
+
size_args = [c_int(arg) for arg in self.extra_args]
|
| 108 |
+
run_method(
|
| 109 |
+
*args, # input ptrs and output ptrs
|
| 110 |
+
*size_args,
|
| 111 |
+
byref(
|
| 112 |
+
c_workspace_size
|
| 113 |
+
), # set workspace size ptr to retrieve workspace size
|
| 114 |
+
None, # null workspace ptr
|
| 115 |
+
stream_ptr,
|
| 116 |
+
)
|
| 117 |
+
torch.cuda.synchronize() # shake out any CUDA errors
|
| 118 |
+
self.workspace_size = c_workspace_size.value
|
| 119 |
+
log.debug(
|
| 120 |
+
"update_workspace_size called: new workspace size=%d, self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s", # noqa: B950
|
| 121 |
+
self.workspace_size,
|
| 122 |
+
self.kernel_name,
|
| 123 |
+
self.source_file,
|
| 124 |
+
self.hash_key,
|
| 125 |
+
self.DLL,
|
| 126 |
+
args,
|
| 127 |
+
self.extra_args,
|
| 128 |
+
)
|
| 129 |
+
self._workspace_size_updated = True
|
| 130 |
+
|
| 131 |
+
def ensure_dll_loaded(self):
|
| 132 |
+
if self.DLL is None:
|
| 133 |
+
self.DLL, self.hash_key, self.source_file = ROCmCodeCache.load(
|
| 134 |
+
self.source_code, "so"
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def cleanup_run_fn(self) -> None:
|
| 138 |
+
if self.DLL is not None:
|
| 139 |
+
self.DLL.close()
|
| 140 |
+
self.workspace = None
|
| 141 |
+
|
| 142 |
+
def __str__(self) -> str:
|
| 143 |
+
return f"{self.kernel_name=}, {self.source_file=}, {self.hash_key=}"
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import logging
|
| 3 |
+
from collections.abc import Sequence
|
| 4 |
+
from typing import cast
|
| 5 |
+
|
| 6 |
+
from ... import config
|
| 7 |
+
from ...codecache import code_hash, get_path
|
| 8 |
+
from ...scheduler import BaseSchedulerNode, BaseScheduling, SchedulerNode
|
| 9 |
+
from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product
|
| 10 |
+
from ...virtualized import V
|
| 11 |
+
from ..common import IndentedBuffer
|
| 12 |
+
from .rocm_template_buffer import ROCmTemplateBuffer
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
log = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class ROCmCPPScheduling(BaseScheduling):
|
| 19 |
+
"""
|
| 20 |
+
Partial Scheduling implementation for ROCm C++ Kernels.
|
| 21 |
+
This class is intended to be used in combination with TritonScheduling,
|
| 22 |
+
and delegated to by CUDACombinedScheduling.
|
| 23 |
+
|
| 24 |
+
It handles fusion decisions and ROCm C++ specific template code generation.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def group_fn(self, sizes):
|
| 28 |
+
return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes)
|
| 29 |
+
|
| 30 |
+
@staticmethod
|
| 31 |
+
def is_rocm_cpp_template(node: BaseSchedulerNode) -> bool:
|
| 32 |
+
return isinstance(node, SchedulerNode) and isinstance(
|
| 33 |
+
node.node, ROCmTemplateBuffer
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def can_fuse_vertical(
|
| 37 |
+
self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
|
| 38 |
+
) -> bool:
|
| 39 |
+
return False
|
| 40 |
+
|
| 41 |
+
def define_kernel(self, src_code: str, node_schedule) -> str:
|
| 42 |
+
wrapper = V.graph.wrapper_code
|
| 43 |
+
if src_code in wrapper.src_to_kernel:
|
| 44 |
+
kernel_name = wrapper.src_to_kernel[src_code]
|
| 45 |
+
else:
|
| 46 |
+
fused_name = (
|
| 47 |
+
get_fused_kernel_name(node_schedule, config.triton.descriptive_names)
|
| 48 |
+
if config.triton.descriptive_names
|
| 49 |
+
else ""
|
| 50 |
+
)
|
| 51 |
+
kernel_name = "_".join(["rocm", fused_name, wrapper.next_kernel_suffix()])
|
| 52 |
+
# use the original src_code as the key
|
| 53 |
+
wrapper.src_to_kernel[src_code] = kernel_name
|
| 54 |
+
src_code = src_code.replace("KERNEL_NAME", kernel_name)
|
| 55 |
+
|
| 56 |
+
_, _, kernel_path = get_path(code_hash(src_code), "py")
|
| 57 |
+
|
| 58 |
+
compile_wrapper = IndentedBuffer()
|
| 59 |
+
compile_wrapper.writeline("async_compile.rocm(r'''")
|
| 60 |
+
compile_wrapper.splice(src_code, strip=True)
|
| 61 |
+
compile_wrapper.writeline(
|
| 62 |
+
f"''', 'so', aot_compile={str(V.graph.aot_mode)})"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
metadata_comment = f"# kernel path: {kernel_path}"
|
| 66 |
+
origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
|
| 67 |
+
metadata_comment += "\n" + origins + "\n" + detailed_origins
|
| 68 |
+
wrapper.define_kernel(
|
| 69 |
+
kernel_name, compile_wrapper.getvalue(), metadata_comment
|
| 70 |
+
)
|
| 71 |
+
return kernel_name
|
| 72 |
+
|
| 73 |
+
def codegen_template(
|
| 74 |
+
self,
|
| 75 |
+
template_node: BaseSchedulerNode,
|
| 76 |
+
epilogue_nodes: Sequence[BaseSchedulerNode],
|
| 77 |
+
prologue_nodes: Sequence[BaseSchedulerNode],
|
| 78 |
+
):
|
| 79 |
+
"""
|
| 80 |
+
Codegen a ROCm template, possibly with fused epilogues
|
| 81 |
+
"""
|
| 82 |
+
assert self.is_rocm_cpp_template(template_node), (
|
| 83 |
+
"Template node passed to ROCmScheduler.codegen_template must be a SchedulerNode that wraps a ROCmTemplateBuffer"
|
| 84 |
+
)
|
| 85 |
+
template_node = cast(SchedulerNode, template_node)
|
| 86 |
+
_, (_numel, rnumel) = template_node.group
|
| 87 |
+
assert rnumel == 1
|
| 88 |
+
ctb: ROCmTemplateBuffer = cast(ROCmTemplateBuffer, template_node.node)
|
| 89 |
+
kernel, render = ctb.make_kernel_render(ctb) # type: ignore[misc]
|
| 90 |
+
with kernel:
|
| 91 |
+
template_node.mark_run()
|
| 92 |
+
src_code = render()
|
| 93 |
+
|
| 94 |
+
with V.set_kernel_handler(kernel):
|
| 95 |
+
node_schedule = [template_node]
|
| 96 |
+
kernel_name = self.define_kernel(src_code, node_schedule)
|
| 97 |
+
kernel.call_kernel(kernel_name, ctb)
|
| 98 |
+
V.graph.removed_buffers |= kernel.removed_buffers
|
| 99 |
+
self.free_buffers_in_scheduler()
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_kernel.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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, Optional, TYPE_CHECKING, Union
|
| 5 |
+
|
| 6 |
+
import torch._inductor.config as config
|
| 7 |
+
from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu
|
| 8 |
+
from torch._inductor.utils import do_bench_using_profiling
|
| 9 |
+
|
| 10 |
+
from ...ir import (
|
| 11 |
+
Buffer,
|
| 12 |
+
ChoiceCaller,
|
| 13 |
+
IRNode,
|
| 14 |
+
Layout,
|
| 15 |
+
PrimitiveInfoType,
|
| 16 |
+
ShapeAsConstantBuffer,
|
| 17 |
+
TensorBox,
|
| 18 |
+
)
|
| 19 |
+
from ...virtualized import V
|
| 20 |
+
from ..common import Kernel, OpOverrides, WorkspaceArg, WorkspaceZeroMode
|
| 21 |
+
from ..cpp_utils import CppPrinter
|
| 22 |
+
from .rocm_benchmark_request import ROCmBenchmarkRequest
|
| 23 |
+
from .rocm_template_buffer import ROCmTemplateBuffer
|
| 24 |
+
from .rocm_utils import DTYPE_TO_ROCM_TYPE
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if TYPE_CHECKING:
|
| 28 |
+
from torch._inductor.codegen.rocm.rocm_template import ArgInfo, ROCmTemplate
|
| 29 |
+
|
| 30 |
+
log = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
cexpr = CppPrinter().doprint
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _normalize_idx(index: int, total_length: int) -> int:
|
| 36 |
+
return index if index >= 0 else index + total_length
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ROCmKernel(Kernel):
|
| 40 |
+
"""
|
| 41 |
+
Baseclass for ROCm based Kernels
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
overrides = OpOverrides # type: ignore[assignment]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ROCmTemplateKernel(ROCmKernel):
|
| 48 |
+
"""
|
| 49 |
+
Template kernels defined by ROCm in C++.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
_EXTRA_CPP_ARGS = "size_t* workspace_size, uint8_t* workspace, hipStream_t stream"
|
| 53 |
+
|
| 54 |
+
def __init__(
|
| 55 |
+
self,
|
| 56 |
+
kernel_name: str,
|
| 57 |
+
runtime_arg_info: list["ArgInfo"],
|
| 58 |
+
runtime_arg_values: list[Any],
|
| 59 |
+
) -> None:
|
| 60 |
+
"""
|
| 61 |
+
Initializes a new instance of the ROCmTemplateKernel class.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
kernel_name (str): The name of the kernel.
|
| 65 |
+
"""
|
| 66 |
+
super().__init__()
|
| 67 |
+
self.kernel_name = kernel_name
|
| 68 |
+
# Mapping from arg name to IRNode.
|
| 69 |
+
self.named_nodes: dict[str, IRNode] = {}
|
| 70 |
+
self.runtime_arg_info = runtime_arg_info
|
| 71 |
+
self.runtime_arg_values = runtime_arg_values
|
| 72 |
+
|
| 73 |
+
def get_signature(self):
|
| 74 |
+
return self.signature
|
| 75 |
+
|
| 76 |
+
def def_kernel(
|
| 77 |
+
self,
|
| 78 |
+
inputs: list[IRNode],
|
| 79 |
+
outputs: list[IRNode],
|
| 80 |
+
size_args: list[str],
|
| 81 |
+
names_str: str = "",
|
| 82 |
+
input_reorder: Optional[list[int]] = None,
|
| 83 |
+
) -> str:
|
| 84 |
+
"""
|
| 85 |
+
Hook called from template code to generate function definition and
|
| 86 |
+
needed args.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
inputs: List of input IRNodes
|
| 90 |
+
outputs: List of output IRNodes
|
| 91 |
+
names_str: Comma separated list of input + output argument names.
|
| 92 |
+
input_reorder: The actual order of input nodes.
|
| 93 |
+
e.g. The template might have input argument defined as [X, W, Bias],
|
| 94 |
+
and the actual input passed into this template could be [Bias, X, W].
|
| 95 |
+
In this case, the `input_reorder` would be [2, 0, 1].
|
| 96 |
+
"""
|
| 97 |
+
names = [x.strip() for x in names_str.strip().split(",")]
|
| 98 |
+
if len(inputs) + len(outputs) != len(names):
|
| 99 |
+
raise RuntimeError(
|
| 100 |
+
f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
if input_reorder == [2, 0, 1]:
|
| 104 |
+
input_reorder = [4, 0, 1, 2, 3]
|
| 105 |
+
|
| 106 |
+
if input_reorder is not None:
|
| 107 |
+
assert len(inputs) == len(input_reorder)
|
| 108 |
+
else:
|
| 109 |
+
input_reorder = list(range(len(inputs)))
|
| 110 |
+
|
| 111 |
+
for idx in input_reorder:
|
| 112 |
+
name = names[idx]
|
| 113 |
+
node = inputs[idx]
|
| 114 |
+
if node is not None:
|
| 115 |
+
self.named_nodes[name] = node
|
| 116 |
+
self.args.input_buffers[node.get_name()] = name
|
| 117 |
+
|
| 118 |
+
for name, node in zip(names[len(inputs) : len(inputs) + len(outputs)], outputs):
|
| 119 |
+
if node is not None:
|
| 120 |
+
self.named_nodes[name] = node
|
| 121 |
+
self.args.output_buffers[node.get_name()] = name
|
| 122 |
+
|
| 123 |
+
arg_defs, *_ = self.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE)
|
| 124 |
+
|
| 125 |
+
runtime_arg_defs = [f"{arg.ty} {arg.name}" for arg in self.runtime_arg_info]
|
| 126 |
+
|
| 127 |
+
signature = f"int {self.kernel_name}({', '.join(arg_defs + size_args + runtime_arg_defs)},{self._EXTRA_CPP_ARGS})"
|
| 128 |
+
self.signature = signature
|
| 129 |
+
return signature
|
| 130 |
+
|
| 131 |
+
def call_kernel(
|
| 132 |
+
self,
|
| 133 |
+
name: str,
|
| 134 |
+
node: "ROCmTemplateBuffer", # type: ignore[name-defined]
|
| 135 |
+
) -> None:
|
| 136 |
+
"""
|
| 137 |
+
Generates code to call the kernel through V.graph.wrapper_code.
|
| 138 |
+
used from within torch._inductor.wrapper.PythonWrapperCodegen
|
| 139 |
+
|
| 140 |
+
name: Name of kernel function.
|
| 141 |
+
node: The ROCmTemplateBuffer node which contains information about the kernel, it's fused epilogue nodes
|
| 142 |
+
as well as all required inputs and outputs.
|
| 143 |
+
"""
|
| 144 |
+
wrapper = V.graph.wrapper_code
|
| 145 |
+
|
| 146 |
+
arg_types: list[Any]
|
| 147 |
+
if V.graph.cpp_wrapper:
|
| 148 |
+
# Make sure we initialize these kernels since they're exported as
|
| 149 |
+
# C-style symbol names.
|
| 150 |
+
assert isinstance(wrapper, CppWrapperCpu)
|
| 151 |
+
wrapper.initialized_kernels[name] = self
|
| 152 |
+
# Kinda hacky because we always originally initialize name with "KERNEL_NAME"
|
| 153 |
+
# So, we replace with the real kernel name passed as an arg to this function.
|
| 154 |
+
self.signature = self.signature.replace("KERNEL_NAME", name)
|
| 155 |
+
_, call_args, arg_types = self.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE)
|
| 156 |
+
else:
|
| 157 |
+
_, call_args, _, arg_types = self.args.python_argdefs()
|
| 158 |
+
|
| 159 |
+
kernel_args = []
|
| 160 |
+
for arg in call_args:
|
| 161 |
+
# dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar
|
| 162 |
+
if V.graph.is_unspec_arg(arg):
|
| 163 |
+
arg = arg + ".item()"
|
| 164 |
+
else:
|
| 165 |
+
if not V.graph.cpp_wrapper:
|
| 166 |
+
arg = f"c_void_p({arg}.data_ptr())"
|
| 167 |
+
kernel_args.append(arg)
|
| 168 |
+
|
| 169 |
+
# add size args
|
| 170 |
+
size_args = [
|
| 171 |
+
f"{V.graph.sizevars.simplify(sarg)}" for sarg in node.template.size_args()
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
if V.graph.cpp_wrapper:
|
| 175 |
+
kernel_args.extend(size_args)
|
| 176 |
+
else:
|
| 177 |
+
kernel_args.extend(f"c_int({sarg})" for sarg in size_args)
|
| 178 |
+
|
| 179 |
+
if V.graph.cpp_wrapper:
|
| 180 |
+
arg_types.extend(["int"] * len(node.template.size_args()))
|
| 181 |
+
|
| 182 |
+
# the runtime args come right after the size args
|
| 183 |
+
kernel_args.extend(self.runtime_arg_values)
|
| 184 |
+
for arg in self.runtime_arg_info:
|
| 185 |
+
arg_types.append(arg.ty)
|
| 186 |
+
|
| 187 |
+
# workspace_size ptr is NULL to mark this call is not intended for retrieving workspace_size.
|
| 188 |
+
# workspace_size should have already been retrieved prior to this call.
|
| 189 |
+
kernel_args.append("nullptr" if V.graph.cpp_wrapper else "None")
|
| 190 |
+
if V.graph.cpp_wrapper:
|
| 191 |
+
arg_types.append("size_t*")
|
| 192 |
+
|
| 193 |
+
if node.get_workspace_size() > 0:
|
| 194 |
+
ws = WorkspaceArg(
|
| 195 |
+
count=node.get_workspace_size(),
|
| 196 |
+
device=V.graph.get_current_device_or_throw(),
|
| 197 |
+
zero_mode=WorkspaceZeroMode.UNINITIALIZED,
|
| 198 |
+
outer_name=WorkspaceArg.unique_name(),
|
| 199 |
+
)
|
| 200 |
+
wrapper.generate_workspace_allocation(ws)
|
| 201 |
+
data_ptr = f"{ws.outer_name}.data_ptr()"
|
| 202 |
+
kernel_args.append(
|
| 203 |
+
data_ptr if V.graph.cpp_wrapper else f"c_void_p({data_ptr})"
|
| 204 |
+
)
|
| 205 |
+
else:
|
| 206 |
+
ws = None
|
| 207 |
+
kernel_args.append("nullptr" if V.graph.cpp_wrapper else "None")
|
| 208 |
+
if V.graph.cpp_wrapper:
|
| 209 |
+
arg_types.append("uint8_t*")
|
| 210 |
+
wrapper.generate_kernel_call(
|
| 211 |
+
name,
|
| 212 |
+
kernel_args,
|
| 213 |
+
triton=False,
|
| 214 |
+
arg_types=arg_types,
|
| 215 |
+
)
|
| 216 |
+
if ws:
|
| 217 |
+
wrapper.generate_workspace_deallocation(ws)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class ROCmTemplateCaller(ChoiceCaller):
|
| 221 |
+
"""
|
| 222 |
+
ROCmTemplateCaller
|
| 223 |
+
|
| 224 |
+
This class represents a caller for ROCm template kernels. It is a subclass of ChoiceCaller.
|
| 225 |
+
Attributes:
|
| 226 |
+
name (str): The name of the caller.
|
| 227 |
+
category (str): The category of the caller.
|
| 228 |
+
bmreq (ROCmBenchmarkRequest): The benchmark request for the caller.
|
| 229 |
+
template_buffer (ROCmTemplateBuffer): The template buffer for the caller.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
def __init__(
|
| 233 |
+
self,
|
| 234 |
+
name: str,
|
| 235 |
+
category: str,
|
| 236 |
+
input_nodes: list[Buffer],
|
| 237 |
+
layout: Layout,
|
| 238 |
+
make_kernel_render: Callable[
|
| 239 |
+
[ROCmTemplateBuffer, Optional[Sequence[IRNode]]], str
|
| 240 |
+
],
|
| 241 |
+
bmreq: ROCmBenchmarkRequest,
|
| 242 |
+
template: "ROCmTemplate", # type: ignore[name-defined]
|
| 243 |
+
info_kwargs: Optional[
|
| 244 |
+
dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]
|
| 245 |
+
], # type: ignore[type-arg]
|
| 246 |
+
) -> None:
|
| 247 |
+
super().__init__(name, input_nodes, layout, description="")
|
| 248 |
+
self.category = category
|
| 249 |
+
self.make_kernel_render = make_kernel_render
|
| 250 |
+
self.bmreq = bmreq
|
| 251 |
+
self.template = template
|
| 252 |
+
self.info_kwargs = info_kwargs
|
| 253 |
+
|
| 254 |
+
def precompile(self) -> None:
|
| 255 |
+
assert self.bmreq is not None
|
| 256 |
+
self.bmreq.precompile()
|
| 257 |
+
|
| 258 |
+
def benchmark(self, *args, out) -> float:
|
| 259 |
+
assert self.bmreq is not None
|
| 260 |
+
if config.profile_bandwidth_with_do_bench_using_profiling:
|
| 261 |
+
algo = self.bmreq.make_run_fn(*args, out=out)
|
| 262 |
+
return do_bench_using_profiling(algo)
|
| 263 |
+
return self.bmreq.benchmark(*args, out=out)
|
| 264 |
+
|
| 265 |
+
def __str__(self) -> str:
|
| 266 |
+
return f"ROCmTemplateCaller(source_file={self.bmreq.source_file}, {self.info_dict()})"
|
| 267 |
+
|
| 268 |
+
def call_name(self) -> str:
|
| 269 |
+
return f"rocm_template_kernels.{self.name}"
|
| 270 |
+
|
| 271 |
+
def hash_key(self) -> str:
|
| 272 |
+
return "-".join(
|
| 273 |
+
[
|
| 274 |
+
self.category,
|
| 275 |
+
self.bmreq.hash_key,
|
| 276 |
+
]
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
def info_dict(self) -> dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]:
|
| 280 |
+
"""Information returned here is logged to the autotune log file when that is enabled."""
|
| 281 |
+
return {
|
| 282 |
+
"backend": "ROCm",
|
| 283 |
+
"name": self.name,
|
| 284 |
+
**dict(self.info_kwargs["op"].dict_items()), # type: ignore[union-attr, index]
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
def output_node(self) -> Union[TensorBox, ShapeAsConstantBuffer]:
|
| 288 |
+
self.bmreq.update_workspace_size()
|
| 289 |
+
return TensorBox.create(
|
| 290 |
+
ROCmTemplateBuffer(
|
| 291 |
+
layout=self.layout,
|
| 292 |
+
inputs=self.input_nodes,
|
| 293 |
+
make_kernel_render=self.make_kernel_render,
|
| 294 |
+
workspace_size=self.bmreq.workspace_size,
|
| 295 |
+
template=self.template,
|
| 296 |
+
)
|
| 297 |
+
)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_template.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import itertools
|
| 4 |
+
import logging
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Any, Optional
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
|
| 10 |
+
from ...autotune_process import TensorMeta
|
| 11 |
+
from ...ir import Buffer, IRNode, Layout
|
| 12 |
+
from ...utils import IndentedBuffer, unique
|
| 13 |
+
from ...virtualized import V
|
| 14 |
+
from ..common import KernelTemplate
|
| 15 |
+
from .rocm_benchmark_request import ROCmBenchmarkRequest
|
| 16 |
+
from .rocm_kernel import ROCmTemplateCaller, ROCmTemplateKernel
|
| 17 |
+
from .rocm_template_buffer import ROCmTemplateBuffer
|
| 18 |
+
from .rocm_utils import DTYPE_TO_ROCM_TYPE
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
log = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# FIXME: unify with the CUDA version
|
| 25 |
+
@dataclass(frozen=True)
|
| 26 |
+
class ArgInfo:
|
| 27 |
+
name: str
|
| 28 |
+
ty: str
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ROCmTemplate(KernelTemplate):
|
| 32 |
+
index_counter = itertools.count()
|
| 33 |
+
gfx9_threads_per_warp = 64
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
name: str,
|
| 38 |
+
input_nodes: list[Buffer],
|
| 39 |
+
layout: Layout,
|
| 40 |
+
input_reorder: Optional[list[int]] = None,
|
| 41 |
+
) -> None:
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
Baseclass for ROCm C++ Templates, derived from KernelTemplate. Not to be instantiated directly.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
name (str): The name of the ROCmTemplate object.
|
| 48 |
+
input_nodes (List[IRNode]): A list of input IRNodes.
|
| 49 |
+
layout (Layout): The layout of the output buffer / tensor.
|
| 50 |
+
input_reorder (Optional[List[int]]): An optional list that specifies the order of the input nodes.
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
super().__init__(name)
|
| 54 |
+
self.input_nodes = input_nodes
|
| 55 |
+
self.output_node: Buffer = Buffer(name="buf_out", layout=layout)
|
| 56 |
+
self.input_reorder = input_reorder
|
| 57 |
+
self.layout = layout
|
| 58 |
+
|
| 59 |
+
def generate( # type: ignore[override]
|
| 60 |
+
self,
|
| 61 |
+
**kwargs,
|
| 62 |
+
) -> ROCmTemplateCaller:
|
| 63 |
+
"""
|
| 64 |
+
Generates the ROCm template caller object for the given GEMM template and operation. This ROCmTemplateCaller
|
| 65 |
+
may be used to call and benchmark the generated ROCm kernel in a standalone manner to enable Autotuning.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
kwargs: Additional keyword arguments.
|
| 69 |
+
|
| 70 |
+
Returns:
|
| 71 |
+
A ROCmTemplateCaller object representing the generated ROCm template caller.
|
| 72 |
+
"""
|
| 73 |
+
kernel_name = f"rocm_{self.name}"
|
| 74 |
+
kernel_hash_name = f"rocm_{self.name}_{next(self.index_counter)}"
|
| 75 |
+
with (
|
| 76 |
+
patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)),
|
| 77 |
+
ROCmTemplateKernel(
|
| 78 |
+
kernel_name=kernel_name,
|
| 79 |
+
runtime_arg_info=self.get_runtime_arg_info(),
|
| 80 |
+
runtime_arg_values=self.get_runtime_arg_values(**kwargs),
|
| 81 |
+
) as kernel,
|
| 82 |
+
):
|
| 83 |
+
code = self.render(kernel=kernel, **kwargs)
|
| 84 |
+
_, call_args, _, _ = kernel.args.python_argdefs()
|
| 85 |
+
log.debug("Autotune key: %s, Generated Code:\n%s", kernel_hash_name, code)
|
| 86 |
+
log.debug(
|
| 87 |
+
"Args: cpp_argdefs: %s, python_argdefs: %s",
|
| 88 |
+
kernel.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE),
|
| 89 |
+
kernel.args.python_argdefs(),
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
input_reorder = (
|
| 93 |
+
self.input_reorder
|
| 94 |
+
if self.input_reorder is not None
|
| 95 |
+
else list(range(len(self.input_nodes)))
|
| 96 |
+
)
|
| 97 |
+
expected_args = list(
|
| 98 |
+
unique(self.input_nodes[idx].get_name() for idx in input_reorder)
|
| 99 |
+
)
|
| 100 |
+
expected_args.extend([self.output_node.get_name()])
|
| 101 |
+
assert list(call_args)[: len(expected_args)] == expected_args, (
|
| 102 |
+
call_args,
|
| 103 |
+
expected_args,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
size_args = (
|
| 107 |
+
self.size_args() if hasattr(self, "size_args") else ()
|
| 108 |
+
) # subclass should define def size_args()
|
| 109 |
+
size_args_ints = [
|
| 110 |
+
V.graph.sizevars.size_hint(arg) for arg in size_args
|
| 111 |
+
] # resolve to ints for benchmarking
|
| 112 |
+
# The runtime args come right after the size args
|
| 113 |
+
runtime_args = self.get_runtime_arg_values(**kwargs)
|
| 114 |
+
extra_args = size_args_ints + runtime_args
|
| 115 |
+
bmreq = ROCmBenchmarkRequest(
|
| 116 |
+
kernel_name=kernel_name,
|
| 117 |
+
input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes),
|
| 118 |
+
output_tensor_meta=TensorMeta.from_irnodes(self.output_node),
|
| 119 |
+
extra_args=extra_args,
|
| 120 |
+
source_code=code,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
def make_kernel_render(
|
| 124 |
+
template_node: ROCmTemplateBuffer,
|
| 125 |
+
epilogue_nodes: Optional[Sequence[IRNode]] = None,
|
| 126 |
+
):
|
| 127 |
+
kernel = ROCmTemplateKernel(
|
| 128 |
+
kernel_name="KERNEL_NAME",
|
| 129 |
+
runtime_arg_info=self.get_runtime_arg_info(),
|
| 130 |
+
runtime_arg_values=self.get_runtime_arg_values(**kwargs),
|
| 131 |
+
)
|
| 132 |
+
render = functools.partial(
|
| 133 |
+
self.render,
|
| 134 |
+
kernel=kernel,
|
| 135 |
+
template_buffer_node=template_node,
|
| 136 |
+
epilogue_nodes=epilogue_nodes,
|
| 137 |
+
**kwargs, # includes "op" argument in case of CUTLASSGemmTemplate
|
| 138 |
+
)
|
| 139 |
+
return kernel, render
|
| 140 |
+
|
| 141 |
+
return ROCmTemplateCaller(
|
| 142 |
+
kernel_hash_name,
|
| 143 |
+
self.name,
|
| 144 |
+
self.input_nodes,
|
| 145 |
+
self.output_node.get_layout(),
|
| 146 |
+
make_kernel_render,
|
| 147 |
+
bmreq,
|
| 148 |
+
self,
|
| 149 |
+
kwargs,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
def header(self) -> IndentedBuffer:
|
| 153 |
+
res = IndentedBuffer()
|
| 154 |
+
res.splice(
|
| 155 |
+
"""
|
| 156 |
+
#include <exception>
|
| 157 |
+
#include <iostream>
|
| 158 |
+
#include <memory>
|
| 159 |
+
#include <random>
|
| 160 |
+
#include <vector>
|
| 161 |
+
"""
|
| 162 |
+
)
|
| 163 |
+
return res
|
| 164 |
+
|
| 165 |
+
def globals(self) -> IndentedBuffer:
|
| 166 |
+
res = IndentedBuffer()
|
| 167 |
+
res.splice(
|
| 168 |
+
"""
|
| 169 |
+
// We compile all models with -fvisibility=hidden. Any symbols that need to be
|
| 170 |
+
// exposed in the final shared library must be declared with PT_EXPORT to make
|
| 171 |
+
// them visible.
|
| 172 |
+
#ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++)
|
| 173 |
+
#define PT_EXPORT __attribute__((__visibility__("default")))
|
| 174 |
+
#else
|
| 175 |
+
#ifdef _WIN32
|
| 176 |
+
#define PT_EXPORT __declspec(dllexport)
|
| 177 |
+
#else
|
| 178 |
+
#define PT_EXPORT
|
| 179 |
+
#endif
|
| 180 |
+
#endif
|
| 181 |
+
"""
|
| 182 |
+
)
|
| 183 |
+
return res
|
| 184 |
+
|
| 185 |
+
def render(self, **kwargs) -> str:
|
| 186 |
+
raise NotImplementedError
|
| 187 |
+
|
| 188 |
+
def get_runtime_arg_info(self) -> list[ArgInfo]:
|
| 189 |
+
return []
|
| 190 |
+
|
| 191 |
+
def get_runtime_arg_values(self, **kwargs) -> list[Any]:
|
| 192 |
+
return []
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_template_buffer.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from typing import Callable, TypeVar
|
| 3 |
+
from typing_extensions import ParamSpec
|
| 4 |
+
|
| 5 |
+
from ...ir import Buffer, Layout, TemplateBuffer
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
_P = ParamSpec("_P")
|
| 9 |
+
_T = TypeVar("_T")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ROCmTemplateBuffer(TemplateBuffer):
|
| 13 |
+
def __init__(
|
| 14 |
+
self,
|
| 15 |
+
layout: Layout,
|
| 16 |
+
inputs: Sequence[Buffer],
|
| 17 |
+
make_kernel_render: Callable[_P, _T],
|
| 18 |
+
workspace_size: int,
|
| 19 |
+
template: "ROCmTemplate", # type: ignore[name-defined] # noqa: F821
|
| 20 |
+
) -> None:
|
| 21 |
+
super().__init__(layout, inputs, make_kernel_render)
|
| 22 |
+
# Global memory (in bytes) needed for this template.
|
| 23 |
+
self.workspace_size = workspace_size
|
| 24 |
+
self.template = template
|
| 25 |
+
|
| 26 |
+
def get_workspace_size(self) -> int:
|
| 27 |
+
return self.workspace_size if self.workspace_size is not None else 0
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/rocm/rocm_utils.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from ..cpp_utils import DTYPE_TO_CPP
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
DTYPE_TO_ROCM_TYPE = {
|
| 10 |
+
**DTYPE_TO_CPP,
|
| 11 |
+
torch.float16: "uint16_t",
|
| 12 |
+
torch.float8_e4m3fnuz: "uint8_t",
|
| 13 |
+
torch.float8_e5m2fnuz: "uint8_t",
|
| 14 |
+
torch.float8_e4m3fn: "uint8_t",
|
| 15 |
+
torch.float8_e5m2: "uint8_t",
|
| 16 |
+
torch.bfloat16: "uint16_t",
|
| 17 |
+
}
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/segmented_tree.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Callable, Generic, Optional, TypeVar
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
T = TypeVar("T")
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _value_or(opt: Optional[T], default: T) -> T:
|
| 8 |
+
return opt if opt is not None else default
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SegmentedTree(Generic[T]):
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
values: list[T],
|
| 15 |
+
update_op: Callable[[T, T], T],
|
| 16 |
+
summary_op: Callable[[T, T], T],
|
| 17 |
+
identity_element: T,
|
| 18 |
+
):
|
| 19 |
+
"""
|
| 20 |
+
Initialize a segment tree with the given values and operations.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
values: list of initial values
|
| 24 |
+
update_op: Function to apply when updating a value (e.g., addition)
|
| 25 |
+
summary_op: Function to summarize two values (e.g., min, max, sum)
|
| 26 |
+
identity_element: Identity element for the summary_op (e.g., 0 for sum, float('inf') for min)
|
| 27 |
+
|
| 28 |
+
Raises:
|
| 29 |
+
ValueError: If the input values list is empty
|
| 30 |
+
"""
|
| 31 |
+
if not values:
|
| 32 |
+
raise ValueError("Cannot create a segment tree with empty values list")
|
| 33 |
+
|
| 34 |
+
self.n = len(values)
|
| 35 |
+
self.update_op = update_op
|
| 36 |
+
self.summary_op = summary_op
|
| 37 |
+
self.identity = identity_element
|
| 38 |
+
|
| 39 |
+
# Size of segment tree array (next power of 2 * 2)
|
| 40 |
+
# The tree follows a standard heap layout where
|
| 41 |
+
# node `n`'s children are at `2*n` and `2*n+1`.
|
| 42 |
+
# Index 0 is unused.
|
| 43 |
+
self.size = 1
|
| 44 |
+
while self.size < self.n:
|
| 45 |
+
self.size *= 2
|
| 46 |
+
self.size *= 2
|
| 47 |
+
|
| 48 |
+
# Initialize tree and lazy arrays
|
| 49 |
+
self.tree = [identity_element] * self.size
|
| 50 |
+
# The lazy array contains updates to the given node
|
| 51 |
+
# Upon update, we only push updates to the top-most
|
| 52 |
+
# nodes that fully receive the update. We then
|
| 53 |
+
# propagate the update down as required (i.e., when
|
| 54 |
+
# we receive an interval query that neither fully
|
| 55 |
+
# contains the node nor fully doesn't contain the
|
| 56 |
+
# node
|
| 57 |
+
self.lazy: list[Optional[T]] = [None] * self.size
|
| 58 |
+
|
| 59 |
+
# Build the tree
|
| 60 |
+
self._build(values, 1, 0, self.n - 1)
|
| 61 |
+
|
| 62 |
+
def _build(self, values: list[T], node: int, start: int, end: int) -> None:
|
| 63 |
+
"""
|
| 64 |
+
Build the segment tree recursively.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
values: Original array of values
|
| 68 |
+
node: Current node index in the segment tree
|
| 69 |
+
start: Start index of the segment
|
| 70 |
+
end: End index of the segment
|
| 71 |
+
"""
|
| 72 |
+
if start == end:
|
| 73 |
+
# Leaf node
|
| 74 |
+
if start < len(values):
|
| 75 |
+
self.tree[node] = values[start]
|
| 76 |
+
return
|
| 77 |
+
|
| 78 |
+
mid = (start + end) // 2
|
| 79 |
+
left_child = 2 * node
|
| 80 |
+
right_child = 2 * node + 1
|
| 81 |
+
|
| 82 |
+
# Recursively build left and right subtrees
|
| 83 |
+
self._build(values, left_child, start, mid)
|
| 84 |
+
self._build(values, right_child, mid + 1, end)
|
| 85 |
+
|
| 86 |
+
# Update current node with summary of children
|
| 87 |
+
self.tree[node] = self.summary_op(self.tree[left_child], self.tree[right_child])
|
| 88 |
+
|
| 89 |
+
def _children(self, node: int) -> list[int]:
|
| 90 |
+
return [2 * node, 2 * node + 1]
|
| 91 |
+
|
| 92 |
+
def _push_lazy(self, node: int, start: int, end: int) -> None:
|
| 93 |
+
"""
|
| 94 |
+
Push lazy updates down to children.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
node: Current node index
|
| 98 |
+
start: Start index of the segment
|
| 99 |
+
end: End index of the segment
|
| 100 |
+
"""
|
| 101 |
+
lazy_node = self.lazy[node]
|
| 102 |
+
if lazy_node is None:
|
| 103 |
+
return
|
| 104 |
+
|
| 105 |
+
# Apply lazy update to current node
|
| 106 |
+
self.tree[node] = self.update_op(self.tree[node], lazy_node)
|
| 107 |
+
|
| 108 |
+
if start != end: # Not a leaf node
|
| 109 |
+
# Propagate to children
|
| 110 |
+
for child in self._children(node):
|
| 111 |
+
self.lazy[child] = self.update_op(
|
| 112 |
+
_value_or(self.lazy[child], self.identity), lazy_node
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
# Clear the lazy value
|
| 116 |
+
self.lazy[node] = None
|
| 117 |
+
|
| 118 |
+
def _update_range_helper(
|
| 119 |
+
self, node: int, start: int, end: int, left: int, right: int, value: T
|
| 120 |
+
) -> None:
|
| 121 |
+
"""
|
| 122 |
+
Helper method to update a range of values in the segment tree.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
node: Current node index
|
| 126 |
+
start: Start index of the current segment
|
| 127 |
+
end: End index of the current segment
|
| 128 |
+
left: Start index of the range to update
|
| 129 |
+
right: End index of the range to update
|
| 130 |
+
value: Value to apply to the range
|
| 131 |
+
"""
|
| 132 |
+
# Push lazy updates before processing this node
|
| 133 |
+
self._push_lazy(node, start, end)
|
| 134 |
+
|
| 135 |
+
# No overlap
|
| 136 |
+
if start > right or end < left:
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
# Complete overlap
|
| 140 |
+
if start >= left and end <= right:
|
| 141 |
+
# Apply update to current node
|
| 142 |
+
self.lazy[node] = value
|
| 143 |
+
self._push_lazy(node, start, end)
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
# Partial overlap, recurse to children
|
| 147 |
+
mid = (start + end) // 2
|
| 148 |
+
left_child = 2 * node
|
| 149 |
+
right_child = 2 * node + 1
|
| 150 |
+
|
| 151 |
+
self._update_range_helper(left_child, start, mid, left, right, value)
|
| 152 |
+
self._update_range_helper(right_child, mid + 1, end, left, right, value)
|
| 153 |
+
|
| 154 |
+
# Update current node based on children
|
| 155 |
+
self.tree[node] = self.summary_op(self.tree[left_child], self.tree[right_child])
|
| 156 |
+
|
| 157 |
+
def _query_range_helper(
|
| 158 |
+
self, node: int, start: int, end: int, left: int, right: int
|
| 159 |
+
) -> T:
|
| 160 |
+
"""
|
| 161 |
+
Helper method to query a range of values in the segment tree.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
node: Current node index
|
| 165 |
+
start: Start index of the current segment
|
| 166 |
+
end: End index of the current segment
|
| 167 |
+
left: Start index of the range to query
|
| 168 |
+
right: End index of the range to query
|
| 169 |
+
|
| 170 |
+
Returns:
|
| 171 |
+
Summary value for the range
|
| 172 |
+
"""
|
| 173 |
+
# No overlap
|
| 174 |
+
if start > right or end < left:
|
| 175 |
+
return self.identity
|
| 176 |
+
|
| 177 |
+
# Push lazy updates before processing this node
|
| 178 |
+
self._push_lazy(node, start, end)
|
| 179 |
+
|
| 180 |
+
# Complete overlap
|
| 181 |
+
if start >= left and end <= right:
|
| 182 |
+
return self.tree[node]
|
| 183 |
+
|
| 184 |
+
# Partial overlap, recurse to children
|
| 185 |
+
mid = (start + end) // 2
|
| 186 |
+
left_child = 2 * node
|
| 187 |
+
right_child = 2 * node + 1
|
| 188 |
+
|
| 189 |
+
left_result = self._query_range_helper(left_child, start, mid, left, right)
|
| 190 |
+
right_result = self._query_range_helper(right_child, mid + 1, end, left, right)
|
| 191 |
+
|
| 192 |
+
# Combine results from children
|
| 193 |
+
return self.summary_op(left_result, right_result)
|
| 194 |
+
|
| 195 |
+
def update_range(self, start: int, end: int, value: T) -> None:
|
| 196 |
+
"""
|
| 197 |
+
Update a range of values in the segment tree.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
start: Start index of the range to update (inclusive)
|
| 201 |
+
end: End index of the range to update (inclusive)
|
| 202 |
+
value: Value to apply to the range
|
| 203 |
+
|
| 204 |
+
Raises:
|
| 205 |
+
ValueError: If start > end or indices are out of bounds
|
| 206 |
+
"""
|
| 207 |
+
if start > end:
|
| 208 |
+
raise ValueError("Start index must be less than or equal to end index")
|
| 209 |
+
|
| 210 |
+
if start < 0 or start >= self.n:
|
| 211 |
+
raise ValueError(f"Start index {start} out of bounds [0, {self.n - 1}]")
|
| 212 |
+
|
| 213 |
+
if end < 0 or end >= self.n:
|
| 214 |
+
raise ValueError(f"End index {end} out of bounds [0, {self.n - 1}]")
|
| 215 |
+
|
| 216 |
+
self._update_range_helper(1, 0, self.n - 1, start, end, value)
|
| 217 |
+
|
| 218 |
+
def summarize_range(self, start: int, end: int) -> T:
|
| 219 |
+
"""
|
| 220 |
+
Query a range of values in the segment tree.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
start: Start index of the range to query (inclusive)
|
| 224 |
+
end: End index of the range to query (inclusive)
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
Summary value for the range according to the summary operation
|
| 228 |
+
|
| 229 |
+
Raises:
|
| 230 |
+
ValueError: If start > end or indices are out of bounds
|
| 231 |
+
"""
|
| 232 |
+
if start > end:
|
| 233 |
+
raise ValueError("Start index must be less than or equal to end index")
|
| 234 |
+
|
| 235 |
+
if start < 0 or start >= self.n:
|
| 236 |
+
raise ValueError(f"Start index {start} out of bounds [0, {self.n - 1}]")
|
| 237 |
+
|
| 238 |
+
if end < 0 or end >= self.n:
|
| 239 |
+
raise ValueError(f"End index {end} out of bounds [0, {self.n - 1}]")
|
| 240 |
+
|
| 241 |
+
return self._query_range_helper(1, 0, self.n - 1, start, end)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/simd.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/simd_kernel_features.py
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import collections
|
| 4 |
+
import dataclasses
|
| 5 |
+
import functools
|
| 6 |
+
import itertools
|
| 7 |
+
import typing
|
| 8 |
+
from typing import Any, Optional, Union
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
|
| 14 |
+
from ...utils._ordered_set import OrderedSet
|
| 15 |
+
from ...utils._sympy.functions import FloorDiv, ModularIndexing
|
| 16 |
+
from ...utils._sympy.symbol import make_symbol, SymT
|
| 17 |
+
from ..dependencies import Dep, extract_loop_body_with_args, MemoryDep
|
| 18 |
+
from ..runtime.hints import ReductionHint
|
| 19 |
+
from ..scheduler import SchedulerNode
|
| 20 |
+
from ..utils import cache_on_self
|
| 21 |
+
from ..virtualized import V
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if typing.TYPE_CHECKING:
|
| 25 |
+
from collections.abc import Iterable, Sequence
|
| 26 |
+
|
| 27 |
+
from torch._inductor.tiling_utils import CoalesceVarAnalysis
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class NodeScheduleMarker:
|
| 31 |
+
@staticmethod
|
| 32 |
+
def only_nodes(it: Iterable[NodeScheduleEntry]) -> Iterable[SchedulerNode]:
|
| 33 |
+
for item in it:
|
| 34 |
+
if not (item is DisableReduction or item is EnableReduction):
|
| 35 |
+
yield item # type: ignore[misc]
|
| 36 |
+
|
| 37 |
+
@staticmethod
|
| 38 |
+
def is_reduction() -> bool:
|
| 39 |
+
return False
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
NodeScheduleEntry = Union[SchedulerNode, type[NodeScheduleMarker]]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class DisableReduction(NodeScheduleMarker):
|
| 46 |
+
"""
|
| 47 |
+
Marker to invoke `kernel.disable_reduction()`. This closes a
|
| 48 |
+
reduction loop and allows for pointwise ops to occur on the output
|
| 49 |
+
of a reduction.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class EnableReduction(NodeScheduleMarker):
|
| 54 |
+
"""
|
| 55 |
+
Marker to end a DisableReduction block.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def filter(node_schedule: list[NodeScheduleEntry]) -> Iterable[SchedulerNode]:
|
| 60 |
+
"""
|
| 61 |
+
Get the nodes from node_schedule skipping those in a
|
| 62 |
+
DisableReduction block.
|
| 63 |
+
"""
|
| 64 |
+
disabled = False
|
| 65 |
+
for node in node_schedule:
|
| 66 |
+
if node in (EnableReduction, DisableReduction):
|
| 67 |
+
# Don't tile stuff outside the main reduction loop
|
| 68 |
+
disabled = node is DisableReduction
|
| 69 |
+
elif disabled:
|
| 70 |
+
pass
|
| 71 |
+
else:
|
| 72 |
+
yield node # type: ignore[misc]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class SIMDKernelFeatures:
|
| 76 |
+
"""
|
| 77 |
+
An ordered schedule of nodes that will become a single kernel.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __init__(
|
| 81 |
+
self,
|
| 82 |
+
node_schedule: list[NodeScheduleEntry],
|
| 83 |
+
numel: sympy.Expr,
|
| 84 |
+
reduction_numel: sympy.Expr = sympy.S.One,
|
| 85 |
+
coalesce_analysis: Optional[CoalesceVarAnalysis] = None,
|
| 86 |
+
):
|
| 87 |
+
self.node_schedule = node_schedule
|
| 88 |
+
# numel excludes reduction_numel
|
| 89 |
+
self.numel: sympy.Expr = V.graph.sizevars.simplify(numel)
|
| 90 |
+
self.reduction_numel: sympy.Expr = V.graph.sizevars.simplify(reduction_numel)
|
| 91 |
+
self._stats_cache: dict[tuple[sympy.Expr, ...], MemoryStats] = {}
|
| 92 |
+
self.coalesce_analysis = coalesce_analysis
|
| 93 |
+
|
| 94 |
+
@cache_on_self
|
| 95 |
+
def is_reduction(self) -> bool:
|
| 96 |
+
return self.reduction_numel != 1
|
| 97 |
+
|
| 98 |
+
@cache_on_self
|
| 99 |
+
def scheduler_nodes(self) -> Iterable[SchedulerNode]:
|
| 100 |
+
return tuple(NodeScheduleMarker.only_nodes(self.node_schedule))
|
| 101 |
+
|
| 102 |
+
def reduction_nodes(self) -> list[SchedulerNode]:
|
| 103 |
+
return [n for n in self.scheduler_nodes() if n.is_reduction()]
|
| 104 |
+
|
| 105 |
+
@cache_on_self
|
| 106 |
+
def buf_accesses(self) -> dict[str, list[Dep]]:
|
| 107 |
+
"""only needed for config.benchmark_kernel"""
|
| 108 |
+
buf_accesses = collections.defaultdict(list)
|
| 109 |
+
for node in self.scheduler_nodes():
|
| 110 |
+
for access in node.read_writes.reads | node.read_writes.writes:
|
| 111 |
+
buf_accesses[access.name].append(access)
|
| 112 |
+
return buf_accesses
|
| 113 |
+
|
| 114 |
+
@cache_on_self
|
| 115 |
+
def op_counts(self) -> collections.Counter[str]:
|
| 116 |
+
counts: collections.Counter[str] = collections.Counter()
|
| 117 |
+
for node in self.scheduler_nodes():
|
| 118 |
+
counts.update(node._body.op_counts)
|
| 119 |
+
return counts
|
| 120 |
+
|
| 121 |
+
def contains_op(self, op_name: str) -> bool:
|
| 122 |
+
"""True if V.ops.{op_name} is used in node_schedule"""
|
| 123 |
+
return bool(self.op_counts().get(op_name))
|
| 124 |
+
|
| 125 |
+
def get_mutations(self) -> OrderedSet[str]:
|
| 126 |
+
mutations: OrderedSet[str] = OrderedSet()
|
| 127 |
+
for node in self.scheduler_nodes():
|
| 128 |
+
for buf in node.get_outputs():
|
| 129 |
+
mutations.update(buf.get_mutations())
|
| 130 |
+
return mutations
|
| 131 |
+
|
| 132 |
+
@cache_on_self
|
| 133 |
+
def select_index_dtype(self) -> torch.dtype:
|
| 134 |
+
# Gather all used buffer names
|
| 135 |
+
buffer_names: OrderedSet[str] = OrderedSet()
|
| 136 |
+
for node in self.scheduler_nodes():
|
| 137 |
+
buffer_names.update(node.get_buffer_names())
|
| 138 |
+
buffer_names.update(node.used_buffer_names())
|
| 139 |
+
buffers = [V.graph.get_buffer(name) for name in buffer_names]
|
| 140 |
+
|
| 141 |
+
# In theory we can separately check xnumel and rnumel are <= int_max
|
| 142 |
+
# but some indexers do use the full linear index so we need to be
|
| 143 |
+
# conservative here.
|
| 144 |
+
total_numel = self.numel * self.reduction_numel
|
| 145 |
+
|
| 146 |
+
from .simd import SIMDScheduling
|
| 147 |
+
|
| 148 |
+
if SIMDScheduling.can_use_32bit_indexing(total_numel, buffers):
|
| 149 |
+
return torch.int32
|
| 150 |
+
return torch.int64
|
| 151 |
+
|
| 152 |
+
@cache_on_self
|
| 153 |
+
def get_reduction_hint(self) -> ReductionHint:
|
| 154 |
+
reductions = self.reduction_nodes()
|
| 155 |
+
if len(reductions) > 0:
|
| 156 |
+
hints = [self.reduction_hint(n) for n in reductions]
|
| 157 |
+
if hints.count(hints[0]) == len(hints):
|
| 158 |
+
reduction_hint_val = hints[0]
|
| 159 |
+
else:
|
| 160 |
+
reduction_hint_val = ReductionHint.DEFAULT
|
| 161 |
+
|
| 162 |
+
if (
|
| 163 |
+
reduction_hint_val == ReductionHint.INNER
|
| 164 |
+
and self.has_non_contiguous_pw_in_reduction_kernel()
|
| 165 |
+
):
|
| 166 |
+
reduction_hint_val = ReductionHint.DEFAULT
|
| 167 |
+
else:
|
| 168 |
+
reduction_hint_val = ReductionHint.DEFAULT
|
| 169 |
+
return reduction_hint_val
|
| 170 |
+
|
| 171 |
+
@cache_on_self
|
| 172 |
+
def buffer_read_counts(self) -> dict[str, int]:
|
| 173 |
+
"""Counts how many times each buffer is read within the kernel"""
|
| 174 |
+
read_counts: dict[str, int] = collections.defaultdict(int)
|
| 175 |
+
|
| 176 |
+
for node in self.scheduler_nodes():
|
| 177 |
+
# node.read_writes.reads contains MemoryDep objects for each read
|
| 178 |
+
for read_dep in node.read_writes.reads:
|
| 179 |
+
read_counts[read_dep.name] += 1
|
| 180 |
+
|
| 181 |
+
return dict(read_counts) # Convert defaultdict to regular dict
|
| 182 |
+
|
| 183 |
+
def has_non_contiguous_pw_in_reduction_kernel(self) -> bool:
|
| 184 |
+
pointwise_nodes = [
|
| 185 |
+
n
|
| 186 |
+
for n in self.scheduler_nodes()
|
| 187 |
+
if not n.is_reduction()
|
| 188 |
+
and n.group[1][0] == self.numel * self.reduction_numel
|
| 189 |
+
]
|
| 190 |
+
for node in pointwise_nodes:
|
| 191 |
+
# An index can be an integer when loading a random seed.
|
| 192 |
+
if not all(
|
| 193 |
+
not isinstance(dep, MemoryDep)
|
| 194 |
+
or dep.is_contiguous()
|
| 195 |
+
or isinstance(dep.index, (sympy.Integer, int))
|
| 196 |
+
or dep.stride1_for_last_dim()
|
| 197 |
+
for dep in itertools.chain(
|
| 198 |
+
node.read_writes.reads, node.read_writes.writes
|
| 199 |
+
)
|
| 200 |
+
):
|
| 201 |
+
return True
|
| 202 |
+
return False
|
| 203 |
+
|
| 204 |
+
@staticmethod
|
| 205 |
+
def reduction_hint(node: Any) -> ReductionHint:
|
| 206 |
+
assert node.is_reduction()
|
| 207 |
+
if node.node.data.reduction_hint != ReductionHint.INNER and all(
|
| 208 |
+
dep.is_contiguous()
|
| 209 |
+
for dep in itertools.chain(node.read_writes.reads, node.read_writes.writes)
|
| 210 |
+
):
|
| 211 |
+
return ReductionHint.INNER
|
| 212 |
+
else:
|
| 213 |
+
return node.node.data.reduction_hint
|
| 214 |
+
|
| 215 |
+
def memory_stats(
|
| 216 |
+
self, groups_dict: Optional[dict[str, sympy.Expr]] = None
|
| 217 |
+
) -> MemoryStats:
|
| 218 |
+
"""Analysis to generate features that can be used in heuristics"""
|
| 219 |
+
if groups_dict is None:
|
| 220 |
+
groups = (self.numel, self.reduction_numel)
|
| 221 |
+
elif groups_dict.keys() == OrderedSet(["x", "r0_"]):
|
| 222 |
+
groups = (groups_dict["x"], groups_dict["r0_"])
|
| 223 |
+
else:
|
| 224 |
+
raise NotImplementedError(f"groups_dict={groups_dict!r}")
|
| 225 |
+
result = self._stats_cache.get(groups)
|
| 226 |
+
if result is None:
|
| 227 |
+
self._stats_cache[groups] = result = MemoryStats.compute(
|
| 228 |
+
MemoryEstimator(self, groups)
|
| 229 |
+
)
|
| 230 |
+
return result
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class MemoryEstimator:
|
| 234 |
+
"""
|
| 235 |
+
Estimate various properties of the kernel for use in heuristics.
|
| 236 |
+
We simulate the memory effects of CSE/buffer elimination in codegen.
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
kernel_sizes: tuple[sympy.Expr, ...]
|
| 240 |
+
outside_loop: MemoryEstimate
|
| 241 |
+
loops: list[MemoryEstimate]
|
| 242 |
+
persistent: MemoryEstimate
|
| 243 |
+
symbols: list[sympy.Symbol]
|
| 244 |
+
|
| 245 |
+
def __init__(self, features: SIMDKernelFeatures, groups: Sequence[sympy.Expr]):
|
| 246 |
+
self.features = features
|
| 247 |
+
self.inside_reduction = features.is_reduction()
|
| 248 |
+
self.store_buffer_names: OrderedSet[str] = OrderedSet()
|
| 249 |
+
self.must_keep_buffers: OrderedSet[str] = OrderedSet()
|
| 250 |
+
self.num_reductions_dims = 1
|
| 251 |
+
self.groups = groups
|
| 252 |
+
self.symbols = [make_symbol(SymT.INDEX, i) for i in range(len(groups))]
|
| 253 |
+
# We are doing two estimates simultaneously:
|
| 254 |
+
# 1) the first is a for a non-persistent (aka looped) reduction, using self.outside_loop/self.loops
|
| 255 |
+
# we add an item to loops each corresponding to each reduction loop in the kernel
|
| 256 |
+
# outside_loop is only used for broadcasting or point-wise ops that don't use the reduction dimension
|
| 257 |
+
# 2) the second is for a persistent kernel, using self.persistent
|
| 258 |
+
# persistent kernels don't have loops, so we only have one MemoryEstimate()
|
| 259 |
+
# for point-wise ops the two estimates will be the same, they matter for reductions only
|
| 260 |
+
self.outside_loop = MemoryEstimate()
|
| 261 |
+
self.loops = [MemoryEstimate()]
|
| 262 |
+
self.persistent = MemoryEstimate()
|
| 263 |
+
self.simulate_codegen()
|
| 264 |
+
self.remove_kernel_local()
|
| 265 |
+
|
| 266 |
+
def simulate_codegen(self) -> None:
|
| 267 |
+
from .simd import SIMDKernel
|
| 268 |
+
|
| 269 |
+
kernel_size_outside_loop = (*self.groups[:-1], sympy.S.One)
|
| 270 |
+
kernel_size_inside_loop = tuple(self.groups)
|
| 271 |
+
self.kernel_sizes = kernel_size_inside_loop
|
| 272 |
+
|
| 273 |
+
for node in self.features.node_schedule:
|
| 274 |
+
if node is DisableReduction:
|
| 275 |
+
self.inside_reduction = False
|
| 276 |
+
self.kernel_sizes = kernel_size_outside_loop
|
| 277 |
+
continue
|
| 278 |
+
elif node is EnableReduction:
|
| 279 |
+
self.inside_reduction = True
|
| 280 |
+
self.kernel_sizes = kernel_size_inside_loop
|
| 281 |
+
self.loops.append(MemoryEstimate())
|
| 282 |
+
continue
|
| 283 |
+
assert isinstance(node, SchedulerNode)
|
| 284 |
+
rw = extract_loop_body_with_args(
|
| 285 |
+
node._body,
|
| 286 |
+
SIMDKernel.map_kernel_groups_to_node_sizes(
|
| 287 |
+
self.kernel_sizes, node.get_ranges(), self.set_ranges
|
| 288 |
+
),
|
| 289 |
+
dict(zip(self.symbols, self.kernel_sizes)),
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
for dep in rw._reads:
|
| 293 |
+
assert isinstance(dep, MemoryDep)
|
| 294 |
+
dep = dep.simplify_with_ranges()
|
| 295 |
+
if not self.persistent.writes.get(dep.name): # cache miss?
|
| 296 |
+
self.persistent.reads[dep.name].add(dep)
|
| 297 |
+
# the cache behavior of looped kernels is more complex than the persistent case above
|
| 298 |
+
# some operations are lifted outside the loop (if they don't use the reduction dimension)
|
| 299 |
+
# other operations are inside the loop, and can only be reused within the same loop
|
| 300 |
+
if not (
|
| 301 |
+
self.outside_loop.writes.get(dep.name)
|
| 302 |
+
or self.loops[-1].writes.get(dep.name)
|
| 303 |
+
):
|
| 304 |
+
self.scope(dep).reads[dep.name].add(dep)
|
| 305 |
+
if dep.name in self.store_buffer_names and self.loops[-1].reads.get(
|
| 306 |
+
dep.name
|
| 307 |
+
):
|
| 308 |
+
self.must_keep_buffers.add(dep.name)
|
| 309 |
+
|
| 310 |
+
for dep in rw._writes:
|
| 311 |
+
assert isinstance(dep, MemoryDep)
|
| 312 |
+
dep = dep.simplify_with_ranges()
|
| 313 |
+
self.store_buffer_names.add(dep.name)
|
| 314 |
+
self.persistent.writes[dep.name].add(dep)
|
| 315 |
+
self.scope(dep).writes[dep.name].add(dep)
|
| 316 |
+
|
| 317 |
+
def remove_kernel_local(self) -> None:
|
| 318 |
+
# Remove any kernel-local buffers
|
| 319 |
+
fused_node_names = OrderedSet(
|
| 320 |
+
[n.get_name() for n in self.features.scheduler_nodes()]
|
| 321 |
+
)
|
| 322 |
+
for name in self.store_buffer_names:
|
| 323 |
+
if not self.persistent.reads.get(
|
| 324 |
+
name
|
| 325 |
+
) and V.graph.scheduler.can_buffer_be_removed_through_fusion(
|
| 326 |
+
name, fused_node_names
|
| 327 |
+
):
|
| 328 |
+
self.persistent.remove(name)
|
| 329 |
+
if name not in self.must_keep_buffers:
|
| 330 |
+
# we can also remove this from the looped kernel
|
| 331 |
+
self.outside_loop.remove(name)
|
| 332 |
+
for loop in self.loops:
|
| 333 |
+
loop.remove(name)
|
| 334 |
+
|
| 335 |
+
if not self.loops[-1]:
|
| 336 |
+
self.loops.pop() # for pointwise ops
|
| 337 |
+
|
| 338 |
+
def scope(self, dep: MemoryDep) -> MemoryEstimate:
|
| 339 |
+
"""Determine how a read/write should be categorized"""
|
| 340 |
+
if self.inside_reduction and (
|
| 341 |
+
self.has_reduction_var(dep.index) or dep.is_indirect()
|
| 342 |
+
):
|
| 343 |
+
return self.loops[-1]
|
| 344 |
+
return self.outside_loop
|
| 345 |
+
|
| 346 |
+
def has_reduction_var(self, index: sympy.Expr) -> bool:
|
| 347 |
+
for sym in self.symbols[-self.num_reductions_dims :]:
|
| 348 |
+
if isinstance(sym, sympy.Symbol) and sym in index.free_symbols:
|
| 349 |
+
return True
|
| 350 |
+
return False
|
| 351 |
+
|
| 352 |
+
def set_ranges(self, *lengths: list[list[sympy.Expr]]) -> list[list[sympy.Expr]]:
|
| 353 |
+
assert len(self.kernel_sizes) == len(lengths)
|
| 354 |
+
return [
|
| 355 |
+
self.make_flat_range(sym, numel, length)
|
| 356 |
+
for sym, numel, length in zip(self.symbols, self.kernel_sizes, lengths)
|
| 357 |
+
]
|
| 358 |
+
|
| 359 |
+
@staticmethod
|
| 360 |
+
def make_flat_range(
|
| 361 |
+
sym: sympy.Symbol, numel: sympy.Expr, lengths: list[sympy.Expr]
|
| 362 |
+
) -> list[sympy.Expr]:
|
| 363 |
+
if len(lengths) == 1 and numel == lengths[0]:
|
| 364 |
+
return [sym]
|
| 365 |
+
divisor = sympy.S.One
|
| 366 |
+
itervars = []
|
| 367 |
+
for length in reversed(lengths):
|
| 368 |
+
if V.graph.sizevars.statically_known_equals(divisor * length, numel):
|
| 369 |
+
expr = FloorDiv(sym, divisor)
|
| 370 |
+
else:
|
| 371 |
+
expr = ModularIndexing(sym, divisor, length)
|
| 372 |
+
itervars.append(expr)
|
| 373 |
+
divisor = divisor * length
|
| 374 |
+
return [*reversed(itervars)]
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
@dataclasses.dataclass
|
| 378 |
+
class MemoryEstimate:
|
| 379 |
+
"""Tracks the memory usage of a single loop in the generated kernel"""
|
| 380 |
+
|
| 381 |
+
reads: dict[str, OrderedSet[MemoryDep]] = dataclasses.field(
|
| 382 |
+
default_factory=functools.partial(collections.defaultdict, OrderedSet)
|
| 383 |
+
)
|
| 384 |
+
writes: dict[str, OrderedSet[MemoryDep]] = dataclasses.field(
|
| 385 |
+
default_factory=functools.partial(collections.defaultdict, OrderedSet)
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
def remove(self, name: str) -> None:
|
| 389 |
+
self.reads.pop(name, None)
|
| 390 |
+
self.writes.pop(name, None)
|
| 391 |
+
|
| 392 |
+
def __bool__(self) -> bool:
|
| 393 |
+
return bool(self.reads or self.writes)
|
| 394 |
+
|
| 395 |
+
def __repr__(self) -> str:
|
| 396 |
+
return f"""MemoryEstimate(
|
| 397 |
+
reads={[*itertools.chain.from_iterable(self.reads.values())]!r},
|
| 398 |
+
writes={[*itertools.chain.from_iterable(self.writes.values())]!r}
|
| 399 |
+
)"""
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
@dataclasses.dataclass
|
| 403 |
+
class StatsForDim:
|
| 404 |
+
"""Memory usage stats for a block dimension in the generated kernel (different from user dimensions)"""
|
| 405 |
+
|
| 406 |
+
# the number of load/store ops
|
| 407 |
+
count_per_thread_contiguous: int = 0
|
| 408 |
+
count_per_thread_broadcast: int = 0
|
| 409 |
+
count_per_thread_non_contiguous: int = 0 # excludes broadcast
|
| 410 |
+
|
| 411 |
+
# total bytes in each load/store op for a single element
|
| 412 |
+
bytes_per_thread_contiguous: int = 0
|
| 413 |
+
bytes_per_thread_broadcast: int = 0
|
| 414 |
+
bytes_per_thread_non_contiguous: int = 0 # excludes broadcast
|
| 415 |
+
|
| 416 |
+
# total bytes read by entire kernel
|
| 417 |
+
bytes_contiguous_or_broadcast: sympy.Expr = sympy.S.Zero
|
| 418 |
+
bytes_non_contiguous: sympy.Expr = sympy.S.Zero
|
| 419 |
+
|
| 420 |
+
def __add__(self, other: typing.Self) -> StatsForDim:
|
| 421 |
+
return StatsForDim(
|
| 422 |
+
count_per_thread_contiguous=self.count_per_thread_contiguous
|
| 423 |
+
+ other.count_per_thread_contiguous,
|
| 424 |
+
count_per_thread_broadcast=self.count_per_thread_broadcast
|
| 425 |
+
+ other.count_per_thread_broadcast,
|
| 426 |
+
count_per_thread_non_contiguous=self.count_per_thread_non_contiguous
|
| 427 |
+
+ other.count_per_thread_non_contiguous,
|
| 428 |
+
bytes_per_thread_contiguous=self.bytes_per_thread_contiguous
|
| 429 |
+
+ other.bytes_per_thread_contiguous,
|
| 430 |
+
bytes_per_thread_broadcast=self.bytes_per_thread_broadcast
|
| 431 |
+
+ other.bytes_per_thread_broadcast,
|
| 432 |
+
bytes_per_thread_non_contiguous=self.bytes_per_thread_non_contiguous
|
| 433 |
+
+ other.bytes_per_thread_non_contiguous,
|
| 434 |
+
bytes_contiguous_or_broadcast=self.bytes_contiguous_or_broadcast
|
| 435 |
+
+ other.bytes_contiguous_or_broadcast,
|
| 436 |
+
bytes_non_contiguous=self.bytes_non_contiguous + other.bytes_non_contiguous,
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
@property
|
| 440 |
+
def count_per_thread(self) -> int:
|
| 441 |
+
return (
|
| 442 |
+
self.count_per_thread_contiguous
|
| 443 |
+
+ self.count_per_thread_broadcast
|
| 444 |
+
+ self.count_per_thread_non_contiguous
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
@property
|
| 448 |
+
def bytes_per_thread(self) -> int:
|
| 449 |
+
return (
|
| 450 |
+
self.bytes_per_thread_contiguous
|
| 451 |
+
+ self.bytes_per_thread_broadcast
|
| 452 |
+
+ self.bytes_per_thread_non_contiguous
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
@property
|
| 456 |
+
def bytes(self) -> sympy.Expr:
|
| 457 |
+
return self.bytes_contiguous_or_broadcast + self.bytes_non_contiguous
|
| 458 |
+
|
| 459 |
+
@property
|
| 460 |
+
def contiguous_score(self) -> float:
|
| 461 |
+
return 1.0 - self.count_per_thread_non_contiguous / max(
|
| 462 |
+
self.count_per_thread, 1
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
@dataclasses.dataclass
|
| 467 |
+
class StatsForLoop:
|
| 468 |
+
"""Memory usage stats for single loop in the generated kernel"""
|
| 469 |
+
|
| 470 |
+
# load/store ops
|
| 471 |
+
count_per_thread: int = 0
|
| 472 |
+
bytes_per_thread: int = 0
|
| 473 |
+
|
| 474 |
+
def __add__(self, other: typing.Self) -> StatsForLoop:
|
| 475 |
+
return StatsForLoop(
|
| 476 |
+
count_per_thread=self.count_per_thread + other.count_per_thread,
|
| 477 |
+
bytes_per_thread=self.bytes_per_thread + other.bytes_per_thread,
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
@dataclasses.dataclass
|
| 482 |
+
class StatsForReadsOrWrites:
|
| 483 |
+
"""Memory usage stats that are collected for reads/writes/both"""
|
| 484 |
+
|
| 485 |
+
dim: list[StatsForDim]
|
| 486 |
+
loop: list[StatsForLoop]
|
| 487 |
+
# total bytes contiguous in any dimension
|
| 488 |
+
bytes_contiguous_or_broadcast: sympy.Expr = sympy.S.Zero
|
| 489 |
+
bytes_non_contiguous: sympy.Expr = sympy.S.Zero
|
| 490 |
+
|
| 491 |
+
def __add__(self, other: typing.Self) -> StatsForReadsOrWrites:
|
| 492 |
+
assert len(self.dim) == len(other.dim)
|
| 493 |
+
assert len(self.loop) == len(other.loop)
|
| 494 |
+
return StatsForReadsOrWrites(
|
| 495 |
+
dim=[a + b for a, b in zip(self.dim, other.dim)],
|
| 496 |
+
loop=[a + b for a, b in zip(self.loop, other.loop)],
|
| 497 |
+
bytes_contiguous_or_broadcast=self.bytes_contiguous_or_broadcast
|
| 498 |
+
+ self.bytes_contiguous_or_broadcast,
|
| 499 |
+
bytes_non_contiguous=self.bytes_non_contiguous + other.bytes_non_contiguous,
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
@property
|
| 503 |
+
def count_per_thread(self) -> int:
|
| 504 |
+
return self.dim[0].count_per_thread
|
| 505 |
+
|
| 506 |
+
@property
|
| 507 |
+
def bytes_per_thread(self) -> int:
|
| 508 |
+
return self.dim[0].bytes_per_thread
|
| 509 |
+
|
| 510 |
+
@property
|
| 511 |
+
def bytes(self) -> sympy.Expr:
|
| 512 |
+
return self.bytes_contiguous_or_broadcast + self.bytes_non_contiguous
|
| 513 |
+
|
| 514 |
+
@classmethod
|
| 515 |
+
def compute(
|
| 516 |
+
cls,
|
| 517 |
+
loop_deps: list[dict[str, OrderedSet[MemoryDep]]],
|
| 518 |
+
index_symbols: list[sympy.Symbol],
|
| 519 |
+
) -> typing.Self:
|
| 520 |
+
ndim = len(index_symbols)
|
| 521 |
+
result = cls(dim := [StatsForDim() for _ in range(ndim)], [])
|
| 522 |
+
for dep_group in loop_deps:
|
| 523 |
+
result.loop.append(loop_stats := StatsForLoop())
|
| 524 |
+
for name, deps in dep_group.items():
|
| 525 |
+
assert deps
|
| 526 |
+
contiguous_or_broadcast = [True] * ndim
|
| 527 |
+
numel = sympy.S.Zero
|
| 528 |
+
itemsize = V.graph.get_dtype(name).itemsize
|
| 529 |
+
loop_stats.count_per_thread += len(deps)
|
| 530 |
+
loop_stats.bytes_per_thread += itemsize * len(deps)
|
| 531 |
+
for dep in deps:
|
| 532 |
+
strides: list[sympy.Expr] = V.graph.sizevars.stride_vars(
|
| 533 |
+
dep.index, index_symbols
|
| 534 |
+
)
|
| 535 |
+
for i in range(ndim):
|
| 536 |
+
if V.graph.sizevars.statically_known_equals(strides[i], 1):
|
| 537 |
+
dim[i].count_per_thread_contiguous += 1
|
| 538 |
+
dim[i].bytes_per_thread_contiguous += itemsize
|
| 539 |
+
elif (
|
| 540 |
+
V.graph.sizevars.statically_known_equals(strides[i], 0)
|
| 541 |
+
and not dep.is_indirect()
|
| 542 |
+
):
|
| 543 |
+
dim[i].count_per_thread_broadcast += 1
|
| 544 |
+
dim[i].bytes_per_thread_broadcast += itemsize
|
| 545 |
+
else:
|
| 546 |
+
dim[i].count_per_thread_non_contiguous += 1
|
| 547 |
+
dim[i].bytes_per_thread_non_contiguous += itemsize
|
| 548 |
+
contiguous_or_broadcast[i] = False
|
| 549 |
+
numel += dep.get_numel()
|
| 550 |
+
if len(deps) > 1:
|
| 551 |
+
# can't read more elements than exist in the buffer
|
| 552 |
+
numel = sympy.Min(numel, V.graph.get_numel(name))
|
| 553 |
+
nbytes = numel * itemsize
|
| 554 |
+
for i in range(ndim):
|
| 555 |
+
if contiguous_or_broadcast[i]:
|
| 556 |
+
dim[i].bytes_contiguous_or_broadcast += nbytes
|
| 557 |
+
else:
|
| 558 |
+
dim[i].bytes_non_contiguous += nbytes
|
| 559 |
+
if any(contiguous_or_broadcast):
|
| 560 |
+
result.bytes_contiguous_or_broadcast += nbytes
|
| 561 |
+
else:
|
| 562 |
+
result.bytes_non_contiguous += nbytes
|
| 563 |
+
if len(result.loop) > 1:
|
| 564 |
+
# the first loop represent the "outside of the loop" compute which could be long lived
|
| 565 |
+
result.loop = [result.loop[0] + x for x in result.loop[1:]]
|
| 566 |
+
return result
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
@dataclasses.dataclass
|
| 570 |
+
class StatsForKernelType:
|
| 571 |
+
"""Memory usage stats that are collected for both persistent and looped kernels"""
|
| 572 |
+
|
| 573 |
+
reads: StatsForReadsOrWrites
|
| 574 |
+
writes: StatsForReadsOrWrites
|
| 575 |
+
memory: StatsForReadsOrWrites
|
| 576 |
+
|
| 577 |
+
@classmethod
|
| 578 |
+
def compute(
|
| 579 |
+
cls, loops: list[MemoryEstimate], estimator: MemoryEstimator
|
| 580 |
+
) -> typing.Self:
|
| 581 |
+
reads = StatsForReadsOrWrites.compute(
|
| 582 |
+
[loop.reads for loop in loops], estimator.symbols
|
| 583 |
+
)
|
| 584 |
+
writes = StatsForReadsOrWrites.compute(
|
| 585 |
+
[loop.writes for loop in loops], estimator.symbols
|
| 586 |
+
)
|
| 587 |
+
return cls(
|
| 588 |
+
reads=reads,
|
| 589 |
+
writes=writes,
|
| 590 |
+
memory=reads + writes,
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
@dataclasses.dataclass
|
| 595 |
+
class MemoryStats:
|
| 596 |
+
"""Memory usage stats collected for each generated kernel"""
|
| 597 |
+
|
| 598 |
+
persistent: StatsForKernelType
|
| 599 |
+
looped: StatsForKernelType
|
| 600 |
+
|
| 601 |
+
def get(self, persistent: bool) -> StatsForKernelType:
|
| 602 |
+
return self.persistent if persistent else self.looped
|
| 603 |
+
|
| 604 |
+
@classmethod
|
| 605 |
+
def compute(cls, estimator: MemoryEstimator) -> typing.Self:
|
| 606 |
+
persistent = StatsForKernelType.compute([estimator.persistent], estimator)
|
| 607 |
+
if len(estimator.loops) == 1 and not (
|
| 608 |
+
estimator.outside_loop and estimator.loops[0]
|
| 609 |
+
):
|
| 610 |
+
looped = persistent # loops/persistent is the same in this common case
|
| 611 |
+
else:
|
| 612 |
+
looped = StatsForKernelType.compute(
|
| 613 |
+
[estimator.outside_loop, *estimator.loops], estimator
|
| 614 |
+
)
|
| 615 |
+
return cls(
|
| 616 |
+
persistent=persistent,
|
| 617 |
+
looped=looped,
|
| 618 |
+
)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/subgraph.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import logging
|
| 3 |
+
from typing import Any, Callable, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch._inductor.config as config
|
| 7 |
+
from torch._inductor import ir
|
| 8 |
+
from torch._inductor.codegen.common import KernelTemplate
|
| 9 |
+
from torch._inductor.ir import (
|
| 10 |
+
Buffer,
|
| 11 |
+
get_free_symbols,
|
| 12 |
+
get_symbolic_inputs,
|
| 13 |
+
gm_original_output_strides,
|
| 14 |
+
ir_node_to_tensor,
|
| 15 |
+
Layout,
|
| 16 |
+
)
|
| 17 |
+
from torch._inductor.runtime.benchmarking import benchmarker
|
| 18 |
+
from torch._inductor.utils import do_bench_using_profiling
|
| 19 |
+
from torch._inductor.virtualized import V
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
log = logging.getLogger(__name__)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class SubgraphChoiceCaller(ir.ChoiceCaller):
|
| 26 |
+
"""
|
| 27 |
+
Represents a Subgraph Autotuning choice, and the subgraph can be any arbitrary
|
| 28 |
+
GraphModule. Compiles the Subgraph down to a module for benchmarking.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(
|
| 32 |
+
self,
|
| 33 |
+
name: str,
|
| 34 |
+
input_nodes: list[Buffer],
|
| 35 |
+
layout: Layout,
|
| 36 |
+
description: str,
|
| 37 |
+
make_fx_graph: Callable[..., Any],
|
| 38 |
+
) -> None:
|
| 39 |
+
super().__init__(name, input_nodes, layout, description)
|
| 40 |
+
|
| 41 |
+
self.example_inputs = []
|
| 42 |
+
with V.fake_mode:
|
| 43 |
+
for inp in self.input_nodes:
|
| 44 |
+
# Here there will be no unbacked symbols, as SubgraphBuffer does not support them
|
| 45 |
+
assert len(get_free_symbols(inp.get_size(), unbacked_only=True)) == 0
|
| 46 |
+
assert len(get_free_symbols(inp.get_stride(), unbacked_only=True)) == 0
|
| 47 |
+
|
| 48 |
+
inp.data.freeze_layout() # type: ignore[attr-defined]
|
| 49 |
+
self.example_inputs.append(ir_node_to_tensor(inp))
|
| 50 |
+
|
| 51 |
+
self.gm = make_fx_graph(*self.example_inputs)
|
| 52 |
+
gm_original_output_strides(self.gm)
|
| 53 |
+
|
| 54 |
+
self.sym_inputs = get_symbolic_inputs(self.input_nodes)
|
| 55 |
+
|
| 56 |
+
def __str__(self) -> str:
|
| 57 |
+
return f"SubgraphCaller({self.name})"
|
| 58 |
+
|
| 59 |
+
def benchmark(self, *args: list[Any], out: torch.Tensor) -> float:
|
| 60 |
+
# Codegen Subgraph for benchmarking
|
| 61 |
+
# Need GraphLowering instead of SubgraphLowering to generate
|
| 62 |
+
# fully callable module
|
| 63 |
+
import torch._inductor.config as inductor_config
|
| 64 |
+
from torch._inductor.graph import GraphLowering
|
| 65 |
+
|
| 66 |
+
bm_graph_lowering = GraphLowering(
|
| 67 |
+
gm=self.gm,
|
| 68 |
+
example_inputs=self.example_inputs,
|
| 69 |
+
shape_env=V.graph._shape_env,
|
| 70 |
+
cpp_wrapper=V.graph.cpp_wrapper,
|
| 71 |
+
aot_mode=V.graph.aot_mode,
|
| 72 |
+
extern_node_serializer=V.graph.extern_node_serializer,
|
| 73 |
+
is_inference=V.graph.is_inference,
|
| 74 |
+
is_backward=V.graph.is_backward,
|
| 75 |
+
name=f"benchmark_{self.name}",
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
for sym_inp in self.sym_inputs:
|
| 79 |
+
bm_graph_lowering.graph_inputs[sym_inp.name] = sym_inp
|
| 80 |
+
bm_graph_lowering.graph_input_names.append(sym_inp.name)
|
| 81 |
+
|
| 82 |
+
sym_inputs = [
|
| 83 |
+
int(V.graph.sizevars.shape_env.size_hint(sym_var))
|
| 84 |
+
for sym_var in self.sym_inputs
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
if len(sym_inputs) == 0:
|
| 88 |
+
# Sanity check that args are same layout as example inputs
|
| 89 |
+
# Only do it if there are no symbolic inputs, otherwise
|
| 90 |
+
# the dynamic dim will be realized to the same size as args
|
| 91 |
+
for ar, example_inp in zip(args, self.example_inputs):
|
| 92 |
+
# Sanity check that args are same layout as example inputs
|
| 93 |
+
if isinstance(ar, torch.Tensor):
|
| 94 |
+
assert isinstance(example_inp, torch.Tensor)
|
| 95 |
+
assert ar.shape == example_inp.shape
|
| 96 |
+
assert ar.stride() == example_inp.stride()
|
| 97 |
+
|
| 98 |
+
if len(sym_inputs) == 0:
|
| 99 |
+
# Sanity check that args are same layout as example inputs
|
| 100 |
+
# Only do it if there are no symbolic inputs, otherwise
|
| 101 |
+
# the dynamic dim will be realized to the same size as args
|
| 102 |
+
for ar, example_inp in zip(args, self.example_inputs):
|
| 103 |
+
# Sanity check that args are same layout as example inputs
|
| 104 |
+
if isinstance(ar, torch.Tensor):
|
| 105 |
+
assert isinstance(example_inp, torch.Tensor)
|
| 106 |
+
assert ar.shape == example_inp.shape
|
| 107 |
+
assert ar.stride() == example_inp.stride()
|
| 108 |
+
|
| 109 |
+
with V.set_graph_handler(bm_graph_lowering):
|
| 110 |
+
# Don't bother autotuning on Triton here
|
| 111 |
+
with inductor_config.patch(
|
| 112 |
+
max_autotune=False,
|
| 113 |
+
max_autotune_gemm=False,
|
| 114 |
+
max_autotune_gemm_backends="ATEN",
|
| 115 |
+
):
|
| 116 |
+
bm_graph_lowering.run(*self.example_inputs)
|
| 117 |
+
mod = bm_graph_lowering.compile_to_module()
|
| 118 |
+
bm_func = mod.call
|
| 119 |
+
|
| 120 |
+
bm_func([*sym_inputs, *args])
|
| 121 |
+
if config.profile_bandwidth_with_do_bench_using_profiling:
|
| 122 |
+
return do_bench_using_profiling(lambda: bm_func([*sym_inputs, *args]))
|
| 123 |
+
return benchmarker.benchmark_gpu(lambda: bm_func([*sym_inputs, *args]))
|
| 124 |
+
|
| 125 |
+
def hash_key(self) -> str:
|
| 126 |
+
return "-".join(
|
| 127 |
+
[
|
| 128 |
+
self.name.rsplit("_", 1)[0],
|
| 129 |
+
*[str(inp.get_size()) for inp in self.input_nodes],
|
| 130 |
+
*[str(inp.get_stride()) for inp in self.input_nodes],
|
| 131 |
+
str(self.gm.graph),
|
| 132 |
+
]
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def output_node(self) -> Union[ir.TensorBox, ir.ShapeAsConstantBuffer]:
|
| 136 |
+
return ir.TensorBox.create(
|
| 137 |
+
ir.SubgraphBuffer(
|
| 138 |
+
layout=self.layout,
|
| 139 |
+
input_nodes=self.input_nodes,
|
| 140 |
+
gm=self.gm,
|
| 141 |
+
example_inputs=self.example_inputs,
|
| 142 |
+
subgraph_name=self.name,
|
| 143 |
+
)
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def info_dict(self) -> dict[str, Any]:
|
| 147 |
+
"""Information returned here is logged to the autotune log file when that is enabled."""
|
| 148 |
+
return {
|
| 149 |
+
"backend": "subgraph",
|
| 150 |
+
"kernel_name": self.name,
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
def autoheuristic_id(self) -> str:
|
| 154 |
+
return f"subgraph_{self.name}"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class SubgraphTemplate(KernelTemplate):
|
| 158 |
+
"""
|
| 159 |
+
A template for subgraph evaluation to be used in autotuning.
|
| 160 |
+
|
| 161 |
+
This class allows creating customized subgraphs that can be appended
|
| 162 |
+
as choices during the autotuning process, enabling the selection of
|
| 163 |
+
optimal implementations for complex operations.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
index_counter = itertools.count()
|
| 167 |
+
|
| 168 |
+
def __init__(
|
| 169 |
+
self,
|
| 170 |
+
name: str,
|
| 171 |
+
):
|
| 172 |
+
"""
|
| 173 |
+
Initialize a subgraph template.
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
name: The name of this template
|
| 177 |
+
graph: The FX graph
|
| 178 |
+
"""
|
| 179 |
+
super().__init__(name=name)
|
| 180 |
+
|
| 181 |
+
def generate( # type: ignore[override]
|
| 182 |
+
self,
|
| 183 |
+
name: str,
|
| 184 |
+
input_nodes: list[Buffer],
|
| 185 |
+
layout: Layout,
|
| 186 |
+
make_fx_graph: Callable[..., Any],
|
| 187 |
+
description: str = "",
|
| 188 |
+
**kwargs: Any,
|
| 189 |
+
) -> SubgraphChoiceCaller:
|
| 190 |
+
"""
|
| 191 |
+
Generate a SubgraphChoiceCaller instance for autotuning.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
input_nodes: List of input nodes to the subgraph
|
| 195 |
+
layout: Memory layout information for the output
|
| 196 |
+
example_inputs: Example tensor inputs used to trace and benchmark the subgraph
|
| 197 |
+
**kwargs: Additional keyword arguments
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
SubgraphChoiceCaller: A callable object that can be used for autotuning
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
return SubgraphChoiceCaller(
|
| 204 |
+
name=f"{name}_{next(SubgraphTemplate.index_counter)}",
|
| 205 |
+
input_nodes=input_nodes,
|
| 206 |
+
layout=layout,
|
| 207 |
+
description=description,
|
| 208 |
+
make_fx_graph=make_fx_graph,
|
| 209 |
+
)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton_combo_kernel.py
ADDED
|
@@ -0,0 +1,978 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import logging
|
| 3 |
+
import textwrap
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any, Callable, cast, Optional, Union
|
| 7 |
+
|
| 8 |
+
import sympy
|
| 9 |
+
from sympy import Integer, Symbol
|
| 10 |
+
|
| 11 |
+
from torch.utils._ordered_set import OrderedSet
|
| 12 |
+
|
| 13 |
+
from .. import config, metrics
|
| 14 |
+
from ..runtime.hints import DeviceProperties
|
| 15 |
+
from ..runtime.runtime_utils import next_power_of_2
|
| 16 |
+
from ..runtime.triton_heuristics import (
|
| 17 |
+
RoundRobinComboKernelGrid,
|
| 18 |
+
SequentialComboKernelGrid,
|
| 19 |
+
)
|
| 20 |
+
from ..scheduler import BaseSchedulerNode
|
| 21 |
+
from ..utils import Placeholder, triton_version_uses_attrs_dict
|
| 22 |
+
from ..virtualized import V
|
| 23 |
+
from .common import (
|
| 24 |
+
ArgName,
|
| 25 |
+
ConstexprArg,
|
| 26 |
+
DeferredLine,
|
| 27 |
+
IndentedBuffer,
|
| 28 |
+
InplacedBuffer,
|
| 29 |
+
Kernel,
|
| 30 |
+
PythonPrinter,
|
| 31 |
+
RemovedArg,
|
| 32 |
+
SizeArg,
|
| 33 |
+
WorkspaceArg,
|
| 34 |
+
)
|
| 35 |
+
from .simd import prefix_is_reduction, SIMDScheduling
|
| 36 |
+
from .simd_kernel_features import SIMDKernelFeatures
|
| 37 |
+
from .triton import gen_common_triton_imports, TritonKernel
|
| 38 |
+
from .triton_utils import config_of, signature_to_meta
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
log = logging.getLogger(__name__)
|
| 42 |
+
pexpr = PythonPrinter().doprint
|
| 43 |
+
LARGE_NUMELS = 512e5
|
| 44 |
+
BLOCK_UTILIZATION = 0.8
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _default_custom_combo_kernel_horizontal_partition(
|
| 48 |
+
nodes: list[BaseSchedulerNode],
|
| 49 |
+
triton_scheduling: SIMDScheduling,
|
| 50 |
+
kernel_map: dict[BaseSchedulerNode, TritonKernel],
|
| 51 |
+
node_info_map: dict[BaseSchedulerNode, tuple[Any, Any, Any, Any]],
|
| 52 |
+
) -> list[list[BaseSchedulerNode]]:
|
| 53 |
+
"""Horizontally partition the given list of nodes into a list of list of nodes where each sublist
|
| 54 |
+
represents a partition. Nodes in different partitions are implemented in different combo kernels.
|
| 55 |
+
Nodes in the same partition are likely to be implemented
|
| 56 |
+
in the same combo kernel, but subject to subsequent restrictions like CUDA limits for number of args.
|
| 57 |
+
|
| 58 |
+
Input arguments:
|
| 59 |
+
nodes: a list of fused scheduler nodes to partition.
|
| 60 |
+
triton_scheduling: TritonScheduling instance.
|
| 61 |
+
kernel_map: a map from node to its kernel.
|
| 62 |
+
node_info_map: a map from node to (node_schedule, tiled_groups, numel, rnumel).
|
| 63 |
+
Output:
|
| 64 |
+
a list of list of nodes with each sublist representing a partition.
|
| 65 |
+
|
| 66 |
+
The default algorithm is to partition nodes based on the following rules:
|
| 67 |
+
1) nodes with the same number of block dimensions are grouped together.
|
| 68 |
+
2) large pointwise nodes (numels greater than LARGE_NUMELS) are separated from other nodes.
|
| 69 |
+
3) large reduce nodes are separated from other nodes.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
assert len(nodes) >= 1
|
| 73 |
+
|
| 74 |
+
# first partition nodes based on number of block dimensions
|
| 75 |
+
tilings = [node_info_map[n][1] for n in nodes]
|
| 76 |
+
|
| 77 |
+
max_dims = max(len(t) for t in tilings)
|
| 78 |
+
nodes_per_ndim: list[list[BaseSchedulerNode]] = []
|
| 79 |
+
for i in range(2, max_dims + 1):
|
| 80 |
+
group_per_dim = [n for n, t in zip(nodes, tilings) if len(t) == i]
|
| 81 |
+
reduction = [
|
| 82 |
+
n
|
| 83 |
+
for n in group_per_dim
|
| 84 |
+
if kernel_map[n].inside_reduction
|
| 85 |
+
and not (kernel_map[n].persistent_reduction and kernel_map[n].no_x_dim)
|
| 86 |
+
]
|
| 87 |
+
not_reduction = [n for n in group_per_dim if n not in reduction]
|
| 88 |
+
# rnumel > 2048 usually has long execution time
|
| 89 |
+
# BaseSchedulerNode.group[-1][-1] is rnumel for reduction nodes
|
| 90 |
+
long_reduction = [
|
| 91 |
+
n
|
| 92 |
+
for n in reduction
|
| 93 |
+
if V.graph.sizevars.size_hint(n.group[-1][-1]) > 2048 # type: ignore[arg-type]
|
| 94 |
+
]
|
| 95 |
+
short_reduction = [n for n in reduction if n not in long_reduction]
|
| 96 |
+
if long_reduction:
|
| 97 |
+
log.debug(
|
| 98 |
+
"ComboKernels: %d long reduction nodes are separated",
|
| 99 |
+
len(long_reduction),
|
| 100 |
+
)
|
| 101 |
+
large_pointwise = [
|
| 102 |
+
n
|
| 103 |
+
for n in not_reduction
|
| 104 |
+
if not kernel_map[n].inside_reduction
|
| 105 |
+
and len(kernel_map[n].numels) == 2
|
| 106 |
+
and V.graph.sizevars.size_hint(kernel_map[n].numels["x"]) > LARGE_NUMELS
|
| 107 |
+
]
|
| 108 |
+
if large_pointwise:
|
| 109 |
+
# TODO benchmark the performance when large pointwise nodes combining with others
|
| 110 |
+
log.debug(
|
| 111 |
+
"ComboKernels: %d large pointwise nodes are separated",
|
| 112 |
+
len(large_pointwise),
|
| 113 |
+
)
|
| 114 |
+
not_reduction = [n for n in not_reduction if n not in large_pointwise]
|
| 115 |
+
nodes_per_ndim.extend([node] for node in large_pointwise)
|
| 116 |
+
|
| 117 |
+
nodes_per_ndim.extend(
|
| 118 |
+
g for g in (not_reduction, short_reduction, long_reduction) if g
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
assert sum(len(p) for p in nodes_per_ndim) == len(nodes)
|
| 122 |
+
return nodes_per_ndim
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
_custom_combo_kernel_horizontal_partition_algorithm: Callable[
|
| 126 |
+
[
|
| 127 |
+
list[BaseSchedulerNode],
|
| 128 |
+
SIMDScheduling,
|
| 129 |
+
dict[BaseSchedulerNode, TritonKernel],
|
| 130 |
+
dict[BaseSchedulerNode, tuple[Any, Any, Any, Any]],
|
| 131 |
+
],
|
| 132 |
+
list[list[BaseSchedulerNode]],
|
| 133 |
+
] = _default_custom_combo_kernel_horizontal_partition
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def set_custom_combo_kernel_horizontal_partition(
|
| 137 |
+
algorithm: Callable[
|
| 138 |
+
[
|
| 139 |
+
list[BaseSchedulerNode],
|
| 140 |
+
SIMDScheduling,
|
| 141 |
+
dict[BaseSchedulerNode, TritonKernel],
|
| 142 |
+
dict[BaseSchedulerNode, tuple[Any, Any, Any, Any]],
|
| 143 |
+
],
|
| 144 |
+
list[list[BaseSchedulerNode]],
|
| 145 |
+
],
|
| 146 |
+
) -> None:
|
| 147 |
+
"""Sets the algorithm used to partition nodes into horizontal partitions. Nodes in different partitions
|
| 148 |
+
are implemented in different combo kernels. Nodes in the same partition are likely to be implemented
|
| 149 |
+
in the same combo kernel, but subject to subsequent restricts like CUDA limits for number of args.
|
| 150 |
+
|
| 151 |
+
The algorithm should take a list of nodes and return a list of list of nodes.
|
| 152 |
+
|
| 153 |
+
The default algorithm is to partition nodes based on number of block dimensions.
|
| 154 |
+
"""
|
| 155 |
+
global _custom_combo_kernel_horizontal_partition_algorithm
|
| 156 |
+
_custom_combo_kernel_horizontal_partition_algorithm = algorithm
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@dataclass
|
| 160 |
+
class PartitionState:
|
| 161 |
+
partitions: list[list[BaseSchedulerNode]]
|
| 162 |
+
cur_partition: list[BaseSchedulerNode]
|
| 163 |
+
cur_count: int
|
| 164 |
+
|
| 165 |
+
def finalize(self) -> None:
|
| 166 |
+
if self.cur_partition:
|
| 167 |
+
self.partitions.append(self.cur_partition)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class ComboKernel(Kernel):
|
| 171 |
+
MAX_NUM_ARGS = 250 # number where I would no longer get triton errors
|
| 172 |
+
|
| 173 |
+
@staticmethod
|
| 174 |
+
def _update_partition(
|
| 175 |
+
partition_state: PartitionState,
|
| 176 |
+
node_rw_count: int,
|
| 177 |
+
node_info: BaseSchedulerNode,
|
| 178 |
+
) -> None:
|
| 179 |
+
if partition_state.cur_count + node_rw_count > ComboKernel.MAX_NUM_ARGS:
|
| 180 |
+
partition_state.partitions.append(partition_state.cur_partition)
|
| 181 |
+
partition_state.cur_partition = [node_info]
|
| 182 |
+
partition_state.cur_count = node_rw_count
|
| 183 |
+
else:
|
| 184 |
+
partition_state.cur_count += node_rw_count
|
| 185 |
+
partition_state.cur_partition.append(node_info)
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def _base_horizontal_partition(
|
| 189 |
+
subkernel_nodes: list[BaseSchedulerNode],
|
| 190 |
+
triton_scheduling: SIMDScheduling,
|
| 191 |
+
node_info_map: dict[BaseSchedulerNode, tuple[Any, Any, Any, Any]],
|
| 192 |
+
custom_algorithm: bool,
|
| 193 |
+
) -> list[list[BaseSchedulerNode]]:
|
| 194 |
+
"""Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnumel)
|
| 195 |
+
for each subkernel node where each sublist is guaranteed to not exceed CUDA limits for number of args
|
| 196 |
+
(read/writes) and to have the same 2D or 1D blocking strategy."""
|
| 197 |
+
# TODO support combination of kernels with different block dimensions
|
| 198 |
+
assert len(subkernel_nodes) >= 1
|
| 199 |
+
mixed_sizes = config.combo_kernel_allow_mixed_sizes > 1 or (
|
| 200 |
+
config.combo_kernel_allow_mixed_sizes == 1 and custom_algorithm
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
ndim_to_partition_state: dict[int, PartitionState] = defaultdict(
|
| 204 |
+
lambda: PartitionState([], [], 0)
|
| 205 |
+
)
|
| 206 |
+
yelem_to_partition_state: dict[int, PartitionState] = defaultdict(
|
| 207 |
+
lambda: PartitionState([], [], 0)
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
for node in subkernel_nodes:
|
| 211 |
+
_node_schedule, tiled_groups, _numel, _rnumel = node_info_map[node]
|
| 212 |
+
node_info = node
|
| 213 |
+
|
| 214 |
+
read_writes = node.read_writes
|
| 215 |
+
read_write_count = len(read_writes.reads) + len(read_writes.writes)
|
| 216 |
+
|
| 217 |
+
ndim = len(tiled_groups)
|
| 218 |
+
assert ndim >= 2, f"Combokernel not support tile {tiled_groups}"
|
| 219 |
+
if not mixed_sizes and ndim == 3:
|
| 220 |
+
y_elem = tiled_groups["y"]
|
| 221 |
+
partition_state = yelem_to_partition_state[y_elem]
|
| 222 |
+
ComboKernel._update_partition(
|
| 223 |
+
partition_state, read_write_count, node_info
|
| 224 |
+
)
|
| 225 |
+
else:
|
| 226 |
+
assert mixed_sizes or ndim <= 3, f"No mixed sizes: tile {tiled_groups}"
|
| 227 |
+
partition_state = ndim_to_partition_state[ndim]
|
| 228 |
+
ComboKernel._update_partition(
|
| 229 |
+
partition_state, read_write_count, node_info
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
all_partitions = []
|
| 233 |
+
for partition_state in ndim_to_partition_state.values():
|
| 234 |
+
partition_state.finalize()
|
| 235 |
+
all_partitions.extend(partition_state.partitions)
|
| 236 |
+
for partition_state in yelem_to_partition_state.values():
|
| 237 |
+
partition_state.finalize()
|
| 238 |
+
all_partitions.extend(partition_state.partitions)
|
| 239 |
+
|
| 240 |
+
return all_partitions
|
| 241 |
+
|
| 242 |
+
@staticmethod
|
| 243 |
+
def horizontal_partition(
|
| 244 |
+
nodes: list[BaseSchedulerNode],
|
| 245 |
+
triton_scheduling: SIMDScheduling,
|
| 246 |
+
kernel_map: dict[BaseSchedulerNode, TritonKernel],
|
| 247 |
+
node_info_map: dict[BaseSchedulerNode, tuple[Any, Any, Any, Any]],
|
| 248 |
+
custom_algorithm: bool = False,
|
| 249 |
+
) -> list[list[BaseSchedulerNode]]:
|
| 250 |
+
"""Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnum)
|
| 251 |
+
for each subkernel node where each sublist forms a ComboKernel. It horizontally partitions nodes into
|
| 252 |
+
sublists in the following way:
|
| 253 |
+
1) call _custom_combo_kernel_horizontal_partition_algorithm() if custom_algorithm is True
|
| 254 |
+
2) then, call _base_horizontal_partition() to partition nodes into sublists, each sublist is
|
| 255 |
+
guaranteed to not exceed CUDA limits for number of args (read/writes) and to have the same
|
| 256 |
+
2D or 1D blocking strategy.
|
| 257 |
+
"""
|
| 258 |
+
if custom_algorithm:
|
| 259 |
+
raw_partitions = _custom_combo_kernel_horizontal_partition_algorithm(
|
| 260 |
+
nodes, triton_scheduling, kernel_map, node_info_map
|
| 261 |
+
)
|
| 262 |
+
else:
|
| 263 |
+
raw_partitions = [nodes]
|
| 264 |
+
|
| 265 |
+
"""Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnumel)
|
| 266 |
+
for each subkernel node where each sublist is guaranteed to not exceed CUDA limits for number of args
|
| 267 |
+
(read/writes) and to have the same 2D or 1D blocking strategy."""
|
| 268 |
+
all_partitions = []
|
| 269 |
+
for raw_partition in raw_partitions:
|
| 270 |
+
all_partitions.extend(
|
| 271 |
+
ComboKernel._base_horizontal_partition(
|
| 272 |
+
raw_partition, triton_scheduling, node_info_map, custom_algorithm
|
| 273 |
+
)
|
| 274 |
+
)
|
| 275 |
+
return all_partitions
|
| 276 |
+
|
| 277 |
+
class SequentialDispatch:
|
| 278 |
+
"""
|
| 279 |
+
The dispatcher which dispatches the subkernels in a sequential manner:
|
| 280 |
+
the blocks are first dispatched to the 1st subkernel (until it is filled),
|
| 281 |
+
then to the 2nd subkernel, and so on.
|
| 282 |
+
The class defines the methods specific to the dispatch algorithm.
|
| 283 |
+
Methods:
|
| 284 |
+
codegen_pid_range(...): codegen the pid range for each subkernel.
|
| 285 |
+
grid(...): codegen the grid size for launching the combo kernel.
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
grid_expr = SequentialComboKernelGrid
|
| 289 |
+
|
| 290 |
+
@classmethod
|
| 291 |
+
def codegen_pid_range(
|
| 292 |
+
cls, kernel: "ComboKernel", num: int, code: IndentedBuffer
|
| 293 |
+
) -> None:
|
| 294 |
+
if num == 0:
|
| 295 |
+
cls._calculate_xblocks(kernel, code)
|
| 296 |
+
code.splice(f"if pid < num_xblocks_{num}:")
|
| 297 |
+
with code.indent():
|
| 298 |
+
code.splice("pid_offset = pid")
|
| 299 |
+
else:
|
| 300 |
+
code.splice(f"elif pid < num_xblocks_{num}:")
|
| 301 |
+
with code.indent():
|
| 302 |
+
code.splice(f"pid_offset = pid - num_xblocks_{num - 1}")
|
| 303 |
+
|
| 304 |
+
@classmethod
|
| 305 |
+
def _calculate_xblocks(
|
| 306 |
+
cls, kernel: "ComboKernel", code: IndentedBuffer
|
| 307 |
+
) -> None:
|
| 308 |
+
x_numels_list = kernel.x_numels_list
|
| 309 |
+
for i in range(len(x_numels_list)):
|
| 310 |
+
xnumels, no_x_dim = (
|
| 311 |
+
(x_numels_list[i], False)
|
| 312 |
+
if isinstance(x_numels_list[i], str)
|
| 313 |
+
and cast(str, x_numels_list[i])[0] != "-"
|
| 314 |
+
or (
|
| 315 |
+
isinstance(x_numels_list[i], int)
|
| 316 |
+
and cast(int, x_numels_list[i]) > 0
|
| 317 |
+
)
|
| 318 |
+
else (kernel.min_x_blocks_list[i], True)
|
| 319 |
+
)
|
| 320 |
+
xblock_str = (
|
| 321 |
+
f"tl.cdiv({xnumels}, XBLOCK)" if not no_x_dim else f"{xnumels}"
|
| 322 |
+
)
|
| 323 |
+
if i == 0:
|
| 324 |
+
code.splice(f"num_xblocks_{i} = {xblock_str}")
|
| 325 |
+
else:
|
| 326 |
+
code.splice(f"num_xblocks_{i} = num_xblocks_{i - 1} + {xblock_str}")
|
| 327 |
+
|
| 328 |
+
class RoundRobinDispatch:
|
| 329 |
+
"""
|
| 330 |
+
The dispatcher which dispatches the subkernels in a round robin manner:
|
| 331 |
+
the blocks are interleavedly dispatched to each subkernel to execute them
|
| 332 |
+
in parallel.
|
| 333 |
+
The class defines the methods specific to the dispatch algorithm.
|
| 334 |
+
Methods:
|
| 335 |
+
codegen_pid_range(...): codegen the pid range for each subkernel.
|
| 336 |
+
grid(...): codegen the grid size for launching the combo kernel.
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
grid_expr = RoundRobinComboKernelGrid
|
| 340 |
+
|
| 341 |
+
@classmethod
|
| 342 |
+
def codegen_pid_range(
|
| 343 |
+
cls, kernel: "ComboKernel", num: int, code: IndentedBuffer
|
| 344 |
+
) -> None:
|
| 345 |
+
num_kernels = len(kernel.sub_kernels)
|
| 346 |
+
if num == 0:
|
| 347 |
+
cond = "if"
|
| 348 |
+
else:
|
| 349 |
+
cond = "elif"
|
| 350 |
+
code.splice(f"{cond} pid % {num_kernels} == {num}:")
|
| 351 |
+
with code.indent():
|
| 352 |
+
code.splice(f"pid_offset = pid // {num_kernels}")
|
| 353 |
+
|
| 354 |
+
def __init__(
|
| 355 |
+
self, enable_autotune: bool = False, mixed_sizes: bool = False
|
| 356 |
+
) -> None:
|
| 357 |
+
super().__init__()
|
| 358 |
+
self.sub_kernels: list[TritonKernel] = []
|
| 359 |
+
self.iter_vars_count = itertools.count()
|
| 360 |
+
self.grids: list[list[int]] = []
|
| 361 |
+
self.min_x_blocks_list: list[Union[int, str]] = []
|
| 362 |
+
self.x_numels_list: list[Union[int, str]] = []
|
| 363 |
+
self.enable_autotune = enable_autotune
|
| 364 |
+
self.mixed_sizes = mixed_sizes
|
| 365 |
+
self.dispatch_class: Optional[
|
| 366 |
+
type[Union[ComboKernel.SequentialDispatch, ComboKernel.RoundRobinDispatch]]
|
| 367 |
+
] = None
|
| 368 |
+
self.block_args: list[str] = []
|
| 369 |
+
# there following are used when autotuning is disabled
|
| 370 |
+
self.block_size_1d = 1024 # Try tuning this value
|
| 371 |
+
self.block_size_2d = 32
|
| 372 |
+
self.num_warps = 8
|
| 373 |
+
self.block_size_reduce = 256
|
| 374 |
+
self.dynamic_shape_args: list[str] = []
|
| 375 |
+
|
| 376 |
+
def create_sub_kernel(self, triton_kernel: TritonKernel) -> TritonKernel:
|
| 377 |
+
sub_kernel = triton_kernel
|
| 378 |
+
metrics.generated_kernel_count -= 1
|
| 379 |
+
sub_kernel.args = self.args
|
| 380 |
+
sub_kernel.iter_vars_count = self.iter_vars_count
|
| 381 |
+
sub_kernel.cse.iter_buffer_ids = self.cse.iter_buffer_ids
|
| 382 |
+
self.sub_kernels.append(sub_kernel)
|
| 383 |
+
return sub_kernel
|
| 384 |
+
|
| 385 |
+
@staticmethod
|
| 386 |
+
def create_triton_kernel(
|
| 387 |
+
tiling: dict[str, sympy.Expr],
|
| 388 |
+
features: SIMDKernelFeatures,
|
| 389 |
+
optimize_mask: bool,
|
| 390 |
+
) -> TritonKernel:
|
| 391 |
+
"""
|
| 392 |
+
Only allow optimize_mask=True when 1) sequential dispatch is used,
|
| 393 |
+
2) numels except x dimension are the same for each sub kernel.
|
| 394 |
+
"""
|
| 395 |
+
return TritonKernel(
|
| 396 |
+
tiling,
|
| 397 |
+
features=features,
|
| 398 |
+
pid_cache={"tl.program_id(0)": "pid_offset"},
|
| 399 |
+
optimize_mask=optimize_mask,
|
| 400 |
+
# foreach kernels don't work with cooperative reductions
|
| 401 |
+
override_cooperative_reduction=False,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
def codegen_static_numels_sub_kernel(
|
| 405 |
+
self, code: IndentedBuffer, sub_kernel: TritonKernel, num: int
|
| 406 |
+
) -> list[str]:
|
| 407 |
+
"""
|
| 408 |
+
We get a small speedup from hard coding numels if they are static.
|
| 409 |
+
|
| 410 |
+
This code stomps on the passed-in values by writing an constant to the top of the kernel.
|
| 411 |
+
|
| 412 |
+
In a kernel like:
|
| 413 |
+
def KERNEL_NAME(in_ptr0, in_ptr1, out_ptr2, xnumel, rnumel, XBLOCK : tl.constexpr, R0_BLOCK : tl.constexpr):
|
| 414 |
+
|
| 415 |
+
We would add
|
| 416 |
+
xnumel = 4096
|
| 417 |
+
rnumel = 768
|
| 418 |
+
|
| 419 |
+
After the signature, before the kernel code, if we decided to make these static. As its hardcoded, it becomes
|
| 420 |
+
a better signal to triton on how to unroll and do some static indexing. So, it's not so much that downstream
|
| 421 |
+
knows that its a static numel, as that you just plop a constant into the kernel.
|
| 422 |
+
"""
|
| 423 |
+
grid = []
|
| 424 |
+
uniquify_block_sizes = []
|
| 425 |
+
for tree in sub_kernel.range_trees:
|
| 426 |
+
simplified_tree_numel = V.graph.sizevars.simplify(tree.numel)
|
| 427 |
+
if isinstance(simplified_tree_numel, (Integer, int)):
|
| 428 |
+
code.writeline(f"{tree.prefix}numel = {int(simplified_tree_numel)}")
|
| 429 |
+
else:
|
| 430 |
+
assert f"{tree.prefix}numel_{num}" in self.dynamic_shape_args
|
| 431 |
+
uniquify_block_sizes.append(f"{tree.prefix}numel")
|
| 432 |
+
|
| 433 |
+
if not tree.is_reduction:
|
| 434 |
+
if isinstance(simplified_tree_numel, (Integer, int)):
|
| 435 |
+
grid.append(int(simplified_tree_numel))
|
| 436 |
+
else:
|
| 437 |
+
grid.append(f"{tree.prefix}numel_{num}")
|
| 438 |
+
|
| 439 |
+
if tree.is_reduction and sub_kernel.persistent_reduction:
|
| 440 |
+
if isinstance(simplified_tree_numel, (Integer, int)):
|
| 441 |
+
val = int(simplified_tree_numel)
|
| 442 |
+
else:
|
| 443 |
+
raise RuntimeError(
|
| 444 |
+
"Dynamic shape on reduction dimension is not supported"
|
| 445 |
+
)
|
| 446 |
+
val = next_power_of_2(val)
|
| 447 |
+
code.writeline(f"RBLOCK_{num}: tl.constexpr = {val}")
|
| 448 |
+
code.writeline(f"R0_BLOCK_{num}: tl.constexpr = {val}")
|
| 449 |
+
uniquify_block_sizes.append("R0_BLOCK")
|
| 450 |
+
|
| 451 |
+
if tree.prefix == "x" and sub_kernel.no_x_dim:
|
| 452 |
+
code.writeline(f"XBLOCK_{num}: tl.constexpr = 1")
|
| 453 |
+
uniquify_block_sizes.append("XBLOCK")
|
| 454 |
+
self.grids.append(grid)
|
| 455 |
+
return uniquify_block_sizes
|
| 456 |
+
|
| 457 |
+
def min_x_blocks_sub_kernel(self, sub_kernel: TritonKernel, num: int) -> None:
|
| 458 |
+
"""
|
| 459 |
+
Kernels with no_x_dim being true has no tunable XBLOCK. They have a fixed number of X blocks.
|
| 460 |
+
Grid calculation needs to make sure that they are assigned with enough number of blocks.
|
| 461 |
+
"""
|
| 462 |
+
min_x_blocks: Union[int, str] = 0
|
| 463 |
+
x_numels: Union[int, str] = 0
|
| 464 |
+
for tree in sub_kernel.range_trees:
|
| 465 |
+
simplified_tree_numel = V.graph.sizevars.simplify(tree.numel)
|
| 466 |
+
if tree.prefix == "x":
|
| 467 |
+
if isinstance(simplified_tree_numel, (Integer, int)):
|
| 468 |
+
x_numels = int(simplified_tree_numel)
|
| 469 |
+
else:
|
| 470 |
+
x_numels = f"{tree.prefix}numel_{num}"
|
| 471 |
+
if sub_kernel.no_x_dim:
|
| 472 |
+
min_x_blocks = x_numels
|
| 473 |
+
x_numels = (
|
| 474 |
+
-min_x_blocks
|
| 475 |
+
if isinstance(x_numels, int)
|
| 476 |
+
else "-" + cast(str, x_numels)
|
| 477 |
+
)
|
| 478 |
+
else:
|
| 479 |
+
if isinstance(simplified_tree_numel, (Integer, int)):
|
| 480 |
+
x_numels = int(simplified_tree_numel)
|
| 481 |
+
else:
|
| 482 |
+
x_numels = f"{tree.prefix}numel_{num}"
|
| 483 |
+
self.min_x_blocks_list.append(min_x_blocks)
|
| 484 |
+
self.x_numels_list.append(x_numels)
|
| 485 |
+
|
| 486 |
+
def select_heuristics(self, sub_kernel: TritonKernel) -> tuple[str, dict[str, int]]:
|
| 487 |
+
size_hints = {
|
| 488 |
+
prefix: next_power_of_2(V.graph.sizevars.size_hint(numel))
|
| 489 |
+
for prefix, numel in sub_kernel.numels.items()
|
| 490 |
+
if not prefix_is_reduction(prefix) or sub_kernel.inside_reduction
|
| 491 |
+
}
|
| 492 |
+
if sub_kernel.persistent_reduction:
|
| 493 |
+
assert sub_kernel.inside_reduction
|
| 494 |
+
heuristics = "persistent_reduction"
|
| 495 |
+
elif sub_kernel.inside_reduction:
|
| 496 |
+
heuristics = "reduction"
|
| 497 |
+
else:
|
| 498 |
+
heuristics = "pointwise"
|
| 499 |
+
return heuristics, size_hints
|
| 500 |
+
|
| 501 |
+
def select_combo_heuristics(
|
| 502 |
+
self, heuristics_list: list[str], size_hints_list: list[dict[str, int]]
|
| 503 |
+
) -> tuple[str, dict[str, int], TritonKernel]:
|
| 504 |
+
if not self.enable_autotune:
|
| 505 |
+
return "foreach", size_hints_list[0], self.sub_kernels[0]
|
| 506 |
+
if "reduction" in heuristics_list:
|
| 507 |
+
i, _ = max(
|
| 508 |
+
enumerate(size_hints_list),
|
| 509 |
+
key=lambda x: x[1]["x"] if heuristics_list[x[0]] == "reduction" else 0,
|
| 510 |
+
)
|
| 511 |
+
return heuristics_list[i], size_hints_list[i], self.sub_kernels[i]
|
| 512 |
+
elif "pointwise" in heuristics_list:
|
| 513 |
+
i, _ = max(
|
| 514 |
+
enumerate(size_hints_list),
|
| 515 |
+
key=lambda x: x[1]["x"] if heuristics_list[x[0]] == "pointwise" else 0,
|
| 516 |
+
)
|
| 517 |
+
# modify size_hint to avoid oom check fail (may be a false alarm)
|
| 518 |
+
num_pointwise = len([e for e in heuristics_list if e == "pointwise"])
|
| 519 |
+
num_reduction = len([e for e in heuristics_list if e == "reduction"])
|
| 520 |
+
num_persistent_reduction = len(
|
| 521 |
+
[e for e in heuristics_list if e == "persistent_reduction"]
|
| 522 |
+
)
|
| 523 |
+
assert num_reduction == 0, (
|
| 524 |
+
"combining pointwise and reduction are not supported yet."
|
| 525 |
+
)
|
| 526 |
+
heuristics = (
|
| 527 |
+
"pointwise_with_reduction"
|
| 528 |
+
if num_persistent_reduction > 0
|
| 529 |
+
else "pointwise"
|
| 530 |
+
)
|
| 531 |
+
if len(heuristics_list) - num_pointwise >= 4:
|
| 532 |
+
size_hints = size_hints_list[i]
|
| 533 |
+
size_hints["x"] = min(128, size_hints["x"])
|
| 534 |
+
return heuristics, size_hints_list[i], self.sub_kernels[i]
|
| 535 |
+
else:
|
| 536 |
+
return heuristics_list[0], size_hints_list[0], self.sub_kernels[0]
|
| 537 |
+
|
| 538 |
+
def get_mutated_args_sub_kernels(self) -> list[str]:
|
| 539 |
+
mutated_args: OrderedSet[str] = OrderedSet()
|
| 540 |
+
for sub_kernel in self.sub_kernels:
|
| 541 |
+
for mutation in sub_kernel.mutations:
|
| 542 |
+
if mutation in sub_kernel.args.input_buffers:
|
| 543 |
+
mutated_args.add(sub_kernel.args.input_buffers[mutation])
|
| 544 |
+
if (
|
| 545 |
+
mutation in sub_kernel.args.inplace_buffers
|
| 546 |
+
and mutation not in V.graph.removed_buffers
|
| 547 |
+
and mutation not in sub_kernel.removed_buffers
|
| 548 |
+
):
|
| 549 |
+
mutated_args.add(
|
| 550 |
+
cast(
|
| 551 |
+
InplacedBuffer, sub_kernel.args.inplace_buffers[mutation]
|
| 552 |
+
).inner_name
|
| 553 |
+
)
|
| 554 |
+
if mutation in sub_kernel.args.output_buffers:
|
| 555 |
+
arg = sub_kernel.args.output_buffers[mutation]
|
| 556 |
+
assert not isinstance(arg, RemovedArg)
|
| 557 |
+
mutated_args.add(arg)
|
| 558 |
+
return sorted(mutated_args)
|
| 559 |
+
|
| 560 |
+
def select_dispatch_strategy(self) -> None:
|
| 561 |
+
if self.dispatch_class is not None:
|
| 562 |
+
return
|
| 563 |
+
# mixed_sizes is used for optimize_mask, so it only allows sequential dispatch
|
| 564 |
+
# Not mixed sizes on y dim technically is ok to use round robin as wells.
|
| 565 |
+
if not self.mixed_sizes or any(isinstance(e, str) for e in self.x_numels_list):
|
| 566 |
+
# str in x_numels_list means a dynamic shape
|
| 567 |
+
self.dispatch_class = ComboKernel.SequentialDispatch
|
| 568 |
+
return
|
| 569 |
+
# A negative x_blocks_list element means the kernel is not tunable,
|
| 570 |
+
# i.e., no_x_dim = True
|
| 571 |
+
x_numels_list = [abs(cast(int, e)) for e in self.x_numels_list]
|
| 572 |
+
total = max(x_numels_list) * len(x_numels_list)
|
| 573 |
+
needed = sum(x_numels_list)
|
| 574 |
+
if needed / total > BLOCK_UTILIZATION:
|
| 575 |
+
# Introduced overhead (masked blocks) is less than 20%
|
| 576 |
+
self.dispatch_class = ComboKernel.RoundRobinDispatch
|
| 577 |
+
else:
|
| 578 |
+
self.dispatch_class = ComboKernel.SequentialDispatch
|
| 579 |
+
|
| 580 |
+
def jit_line(
|
| 581 |
+
self,
|
| 582 |
+
heuristics: str,
|
| 583 |
+
size_hints: dict[str, int],
|
| 584 |
+
selected_kernel: TritonKernel,
|
| 585 |
+
signature: list[Any],
|
| 586 |
+
argdefs: list[ArgName],
|
| 587 |
+
pointwise_with_reduce: bool = False,
|
| 588 |
+
) -> str:
|
| 589 |
+
can_use_32bit = all(k.index_dtype == "tl.int32" for k in self.sub_kernels)
|
| 590 |
+
size_dtype = "tl.int32" if can_use_32bit else "tl.int64"
|
| 591 |
+
for i, sub in enumerate(self.sub_kernels):
|
| 592 |
+
self.min_x_blocks_sub_kernel(sub, i)
|
| 593 |
+
self.select_dispatch_strategy()
|
| 594 |
+
triton_meta = {
|
| 595 |
+
"signature": signature_to_meta(
|
| 596 |
+
signature, size_dtype=size_dtype, argdefs=argdefs
|
| 597 |
+
),
|
| 598 |
+
"device": DeviceProperties.create(V.graph.get_current_device_or_throw()),
|
| 599 |
+
"constants": {},
|
| 600 |
+
}
|
| 601 |
+
triton_meta["configs"] = [config_of(signature)]
|
| 602 |
+
mutated_args = self.get_mutated_args_sub_kernels()
|
| 603 |
+
dispatch = self.dispatch_class
|
| 604 |
+
assert dispatch is not None
|
| 605 |
+
inductor_meta = {
|
| 606 |
+
"grid_type": dispatch.grid_expr.__name__,
|
| 607 |
+
"combo_grid_meta": self.combo_grid_meta(),
|
| 608 |
+
"kernel_name": str(Placeholder.DESCRIPTIVE_NAME),
|
| 609 |
+
"mutated_arg_names": mutated_args,
|
| 610 |
+
**TritonKernel.inductor_meta_common(),
|
| 611 |
+
}
|
| 612 |
+
|
| 613 |
+
sub_kernel = selected_kernel
|
| 614 |
+
if heuristics == "foreach":
|
| 615 |
+
heuristics_line = f"""
|
| 616 |
+
@triton_heuristics.foreach(
|
| 617 |
+
num_warps={self.num_warps},
|
| 618 |
+
triton_meta={triton_meta!r},
|
| 619 |
+
inductor_meta={inductor_meta!r},
|
| 620 |
+
)
|
| 621 |
+
@triton.jit
|
| 622 |
+
"""
|
| 623 |
+
elif sub_kernel.inside_reduction:
|
| 624 |
+
reduction_hint = sub_kernel.features.get_reduction_hint()
|
| 625 |
+
heuristics_line = f"""
|
| 626 |
+
@triton_heuristics.{heuristics}(
|
| 627 |
+
size_hints={size_hints!r},
|
| 628 |
+
reduction_hint={reduction_hint},
|
| 629 |
+
filename=__file__,
|
| 630 |
+
triton_meta={triton_meta!r},
|
| 631 |
+
inductor_meta={inductor_meta!r}
|
| 632 |
+
)
|
| 633 |
+
@triton.jit
|
| 634 |
+
"""
|
| 635 |
+
else:
|
| 636 |
+
tile_hint = ""
|
| 637 |
+
if len(size_hints) == 2:
|
| 638 |
+
tile_hint = "tile_hint=TileHint.SQUARE,"
|
| 639 |
+
else:
|
| 640 |
+
tile_hint = "tile_hint=TileHint.DEFAULT,"
|
| 641 |
+
heuristics_line = f"""
|
| 642 |
+
@triton_heuristics.{heuristics}(
|
| 643 |
+
size_hints={size_hints!r}, {tile_hint}
|
| 644 |
+
filename=__file__,
|
| 645 |
+
triton_meta={triton_meta!r},
|
| 646 |
+
inductor_meta={inductor_meta!r}
|
| 647 |
+
)
|
| 648 |
+
@triton.jit
|
| 649 |
+
"""
|
| 650 |
+
|
| 651 |
+
return heuristics_line
|
| 652 |
+
|
| 653 |
+
def codegen_blocks(self, code: IndentedBuffer) -> None:
|
| 654 |
+
for block in self.block_args:
|
| 655 |
+
assert block in (
|
| 656 |
+
"XBLOCK",
|
| 657 |
+
"YBLOCK",
|
| 658 |
+
"R0_BLOCK",
|
| 659 |
+
), f"{block} is not supported without autotuning"
|
| 660 |
+
if "YBLOCK" in self.block_args:
|
| 661 |
+
code.splice(f"XBLOCK: tl.constexpr = {self.block_size_2d}")
|
| 662 |
+
code.splice(f"YBLOCK: tl.constexpr = {self.block_size_2d}")
|
| 663 |
+
else:
|
| 664 |
+
code.splice(f"XBLOCK: tl.constexpr = {self.block_size_1d}")
|
| 665 |
+
if "R0_BLOCK" in self.block_args:
|
| 666 |
+
code.splice(f"R0_BLOCK: tl.constexpr = {self.block_size_reduce}")
|
| 667 |
+
code.splice(f"RBLOCK: tl.constexpr = {self.block_size_reduce}")
|
| 668 |
+
|
| 669 |
+
def get_block_args(self) -> list[ConstexprArg]:
|
| 670 |
+
"""
|
| 671 |
+
Calculate blocks from sub_kernels and range_trees.
|
| 672 |
+
**Update self.block_args**
|
| 673 |
+
Return the block args
|
| 674 |
+
"""
|
| 675 |
+
block_names = {}
|
| 676 |
+
for sub_kernel in self.sub_kernels:
|
| 677 |
+
# TODO: we assume all sub_kernels have the same block size
|
| 678 |
+
for tree in sub_kernel.range_trees:
|
| 679 |
+
if tree.is_reduction and (
|
| 680 |
+
not sub_kernel.inside_reduction or sub_kernel.persistent_reduction
|
| 681 |
+
):
|
| 682 |
+
continue
|
| 683 |
+
if tree.prefix == "x" and sub_kernel.no_x_dim:
|
| 684 |
+
continue
|
| 685 |
+
block_names[f"{tree.prefix.upper()}BLOCK"] = tree.prefix
|
| 686 |
+
self.block_args = list(block_names.keys())
|
| 687 |
+
|
| 688 |
+
return [ConstexprArg(x) for x in block_names.keys()]
|
| 689 |
+
|
| 690 |
+
def add_numel_to_args(
|
| 691 |
+
self, argdefs: list[ArgName], signature: list[Any]
|
| 692 |
+
) -> list[ArgName]:
|
| 693 |
+
for num, sub_kernel in enumerate(self.sub_kernels):
|
| 694 |
+
for tree in sub_kernel.active_range_trees():
|
| 695 |
+
if not isinstance(tree.numel, (Integer, int)):
|
| 696 |
+
# only if it is a dynamic shape
|
| 697 |
+
sizearg = SizeArg(f"{tree.prefix}numel_{num}", tree.numel)
|
| 698 |
+
signature.append(sizearg)
|
| 699 |
+
argdefs.append(ArgName(f"{tree.prefix}numel_{num}"))
|
| 700 |
+
self.dynamic_shape_args.append(f"{tree.prefix}numel_{num}")
|
| 701 |
+
return argdefs
|
| 702 |
+
|
| 703 |
+
def add_numel_to_call_args(
|
| 704 |
+
self, name: str, call_args: list[Any], arg_types: list[Any]
|
| 705 |
+
) -> None:
|
| 706 |
+
for num, sub_kernel in enumerate(self.sub_kernels):
|
| 707 |
+
for i, tree in enumerate(sub_kernel.range_trees):
|
| 708 |
+
numel_name = f"{tree.prefix}numel_{num}"
|
| 709 |
+
if numel_name not in self.dynamic_shape_args:
|
| 710 |
+
continue
|
| 711 |
+
if isinstance(tree.numel, (Integer, Symbol)):
|
| 712 |
+
expr = tree.numel
|
| 713 |
+
else:
|
| 714 |
+
expr = V.graph.wrapper_code.generate_numel_expr(
|
| 715 |
+
name, tree, suffix=str(num)
|
| 716 |
+
)
|
| 717 |
+
if not tree.is_reduction or sub_kernel.inside_reduction:
|
| 718 |
+
call_args.append(expr)
|
| 719 |
+
arg_types.append(type(expr))
|
| 720 |
+
|
| 721 |
+
def kernel_benchmark_extra_args(self) -> list[str]:
|
| 722 |
+
extra_args = []
|
| 723 |
+
for num, sub_kernel in enumerate(self.sub_kernels):
|
| 724 |
+
for i, tree in enumerate(sub_kernel.range_trees):
|
| 725 |
+
numel_name = f"{tree.prefix}numel_{num}"
|
| 726 |
+
if numel_name not in self.dynamic_shape_args:
|
| 727 |
+
continue
|
| 728 |
+
if not tree.is_reduction or sub_kernel.inside_reduction:
|
| 729 |
+
extra_args.append(str(V.graph.sizevars.size_hint(tree.numel)))
|
| 730 |
+
return extra_args
|
| 731 |
+
|
| 732 |
+
def codegen_kernel(self, name: Optional[str] = None) -> str:
|
| 733 |
+
# TODO: is it correct to use the first sub kernel's heuristics?
|
| 734 |
+
heuristics_list, size_hints_list = [], []
|
| 735 |
+
for subkernel in self.sub_kernels:
|
| 736 |
+
h, s = self.select_heuristics(subkernel)
|
| 737 |
+
heuristics_list.append(h)
|
| 738 |
+
size_hints_list.append(s)
|
| 739 |
+
heuristics, size_hints, selected_kernel = self.select_combo_heuristics(
|
| 740 |
+
heuristics_list, size_hints_list
|
| 741 |
+
)
|
| 742 |
+
pointwise_with_reduction, heuristics = (
|
| 743 |
+
(True, "pointwise")
|
| 744 |
+
if heuristics == "pointwise_with_reduction"
|
| 745 |
+
else (False, heuristics)
|
| 746 |
+
)
|
| 747 |
+
code = IndentedBuffer()
|
| 748 |
+
|
| 749 |
+
code.splice(gen_common_triton_imports())
|
| 750 |
+
if config.benchmark_combo_kernel:
|
| 751 |
+
code.splice(self.imports_for_benchmark_kernel())
|
| 752 |
+
|
| 753 |
+
argdefs, _, signature, _ = self.args.python_argdefs()
|
| 754 |
+
argdefs = self.add_numel_to_args(argdefs, signature)
|
| 755 |
+
block_args = self.get_block_args()
|
| 756 |
+
if self.enable_autotune:
|
| 757 |
+
argdefs.extend([ArgName(x.name, is_constexpr=True) for x in block_args])
|
| 758 |
+
if triton_version_uses_attrs_dict():
|
| 759 |
+
signature.extend(block_args)
|
| 760 |
+
|
| 761 |
+
code.splice(
|
| 762 |
+
self.jit_line(
|
| 763 |
+
heuristics,
|
| 764 |
+
size_hints,
|
| 765 |
+
selected_kernel,
|
| 766 |
+
pointwise_with_reduce=pointwise_with_reduction,
|
| 767 |
+
signature=signature,
|
| 768 |
+
argdefs=argdefs,
|
| 769 |
+
)
|
| 770 |
+
)
|
| 771 |
+
code.writeline(
|
| 772 |
+
f"def {name or str(Placeholder.KERNEL_NAME)}({', '.join(x.full_name() for x in argdefs)}):"
|
| 773 |
+
)
|
| 774 |
+
|
| 775 |
+
with code.indent():
|
| 776 |
+
code.splice("pid = tl.program_id(0)")
|
| 777 |
+
if not self.enable_autotune:
|
| 778 |
+
self.codegen_blocks(code)
|
| 779 |
+
|
| 780 |
+
for num, sub_kernel in enumerate(self.sub_kernels):
|
| 781 |
+
assert self.dispatch_class is not None
|
| 782 |
+
self.dispatch_class.codegen_pid_range(self, num, code)
|
| 783 |
+
with code.indent():
|
| 784 |
+
uniquify = self.codegen_static_numels_sub_kernel(
|
| 785 |
+
code, sub_kernel, num
|
| 786 |
+
)
|
| 787 |
+
sub_kernel.codegen_body()
|
| 788 |
+
uniquified_body = self.uniquify_block_sizes(
|
| 789 |
+
sub_kernel.body, num, uniquify
|
| 790 |
+
)
|
| 791 |
+
code.splice(uniquified_body)
|
| 792 |
+
|
| 793 |
+
code.splice("else:")
|
| 794 |
+
with code.indent():
|
| 795 |
+
code.splice("pass")
|
| 796 |
+
|
| 797 |
+
if config.benchmark_combo_kernel:
|
| 798 |
+
code.splice(self.codegen_kernel_benchmark(num_gb=0))
|
| 799 |
+
|
| 800 |
+
return code.getvalue()
|
| 801 |
+
|
| 802 |
+
def codegen_kernel_benchmark(self, num_gb: float) -> IndentedBuffer:
|
| 803 |
+
result = IndentedBuffer()
|
| 804 |
+
_argdefs, call_args, signature, _ = self.args.python_argdefs()
|
| 805 |
+
result.writelines(["", "", "def get_args():"])
|
| 806 |
+
with result.indent():
|
| 807 |
+
name_cnt = itertools.count()
|
| 808 |
+
var_names = []
|
| 809 |
+
for arg_name, arg_sig in zip(call_args, signature):
|
| 810 |
+
var_name = f"arg_{next(name_cnt)}"
|
| 811 |
+
buf = V.graph.try_get_buffer(arg_name)
|
| 812 |
+
if buf:
|
| 813 |
+
result.writeline(
|
| 814 |
+
f"{var_name} = rand_strided({V.graph.sizevars.size_hints(buf.get_size())}, {V.graph.sizevars.size_hints(buf.get_stride())}, device='{buf.get_device()}', dtype={buf.get_dtype()})" # noqa: B950 line too long
|
| 815 |
+
)
|
| 816 |
+
elif arg_name in V.graph.constants:
|
| 817 |
+
# note that random seed is put in V.graph.constants
|
| 818 |
+
const_tensor = V.graph.constants[arg_name]
|
| 819 |
+
result.writeline(
|
| 820 |
+
f"{var_name} = rand_strided({V.graph.sizevars.size_hints(const_tensor.size())}, {V.graph.sizevars.size_hints(const_tensor.stride())}, device='{const_tensor.device}', dtype={const_tensor.dtype})" # type: ignore[arg-type] # noqa: B950 line too long
|
| 821 |
+
)
|
| 822 |
+
elif isinstance(arg_sig, SizeArg):
|
| 823 |
+
symval_hint = V.graph.sizevars.size_hint(arg_sig.expr)
|
| 824 |
+
|
| 825 |
+
# Force the seed_offset to be 0 so calls to the same kernel
|
| 826 |
+
# using different seed offset will have the same benchmark harness.
|
| 827 |
+
# We can dedup kernel definitions in this case.
|
| 828 |
+
if "seed_offset" in arg_sig.name:
|
| 829 |
+
symval_hint = 0
|
| 830 |
+
result.writeline(f"{var_name} = {symval_hint}")
|
| 831 |
+
elif isinstance(arg_sig, WorkspaceArg):
|
| 832 |
+
device = V.graph.get_current_device_or_throw()
|
| 833 |
+
count = V.graph.sizevars.size_hint(arg_sig.count)
|
| 834 |
+
# for benchmark harness, we ignore arg_sig.zero_mode and always zero it
|
| 835 |
+
result.writeline(
|
| 836 |
+
f"{var_name} = torch.zeros({count}, device='{device}', dtype={arg_sig.dtype})"
|
| 837 |
+
)
|
| 838 |
+
else:
|
| 839 |
+
raise KeyError(
|
| 840 |
+
f"Don't find the buffer or const tensor for {arg_name}"
|
| 841 |
+
)
|
| 842 |
+
var_names.append(var_name)
|
| 843 |
+
if self.dynamic_shape_args:
|
| 844 |
+
var_names.extend(self.kernel_benchmark_extra_args())
|
| 845 |
+
result.writeline(f"return {', '.join(var_names)},")
|
| 846 |
+
|
| 847 |
+
result.writelines(["\n", "\n", "def call(args):"])
|
| 848 |
+
index = V.graph.get_current_device_or_throw().index
|
| 849 |
+
with result.indent():
|
| 850 |
+
result.writeline(f"with {V.graph.device_ops.device_guard(index)}:")
|
| 851 |
+
with result.indent():
|
| 852 |
+
result.writeline(
|
| 853 |
+
V.graph.device_ops.set_device(index)
|
| 854 |
+
) # no-op to ensure context
|
| 855 |
+
stream_name = f"stream{index}"
|
| 856 |
+
result.writeline(f"{stream_name} = get_raw_stream({index})")
|
| 857 |
+
result.writeline(
|
| 858 |
+
f"{str(Placeholder.KERNEL_NAME)}.run(*args, stream={stream_name})"
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
# benchmark all configs
|
| 862 |
+
result.writelines(["\n", "\n", "def benchmark_all_configs(args):"])
|
| 863 |
+
with result.indent():
|
| 864 |
+
result.writeline(f"with {V.graph.device_ops.device_guard(index)}:")
|
| 865 |
+
with result.indent():
|
| 866 |
+
result.writeline(
|
| 867 |
+
V.graph.device_ops.set_device(index)
|
| 868 |
+
) # no-op to ensure context
|
| 869 |
+
result.writeline(
|
| 870 |
+
f"return {str(Placeholder.KERNEL_NAME)}.benchmark_all_configs(*args)"
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
result.writelines(["\n", "\n", "if __name__ == '__main__':"])
|
| 874 |
+
with result.indent():
|
| 875 |
+
result.writeline(
|
| 876 |
+
"from torch._inductor.runtime.benchmarking import benchmarker"
|
| 877 |
+
)
|
| 878 |
+
result.writeline("")
|
| 879 |
+
|
| 880 |
+
result.writeline("args = get_args()")
|
| 881 |
+
result.writeline(
|
| 882 |
+
"ms = benchmarker.benchmark_gpu(lambda: call(args), rep=40)"
|
| 883 |
+
)
|
| 884 |
+
result.writeline(f"num_gb = {num_gb}")
|
| 885 |
+
result.writeline("gb_per_s = num_gb / (ms / 1e3)")
|
| 886 |
+
result.writeline(
|
| 887 |
+
'print(f"{ms:.3f}ms {num_gb:.3f}GB {gb_per_s:.2f}GB/s")'
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
return result
|
| 891 |
+
|
| 892 |
+
def imports_for_benchmark_kernel(self) -> str:
|
| 893 |
+
return textwrap.dedent(
|
| 894 |
+
"""
|
| 895 |
+
from torch._dynamo.testing import rand_strided
|
| 896 |
+
{}
|
| 897 |
+
import torch
|
| 898 |
+
""".format(V.graph.device_ops.import_get_raw_stream_as("get_raw_stream"))
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
def uniquify_block_sizes(
|
| 902 |
+
self, code: IndentedBuffer, num_kernel: int, uniquify: list[str]
|
| 903 |
+
) -> IndentedBuffer:
|
| 904 |
+
if not uniquify:
|
| 905 |
+
return code
|
| 906 |
+
modified = IndentedBuffer(initial_indent=code._indent)
|
| 907 |
+
for line in code._lines:
|
| 908 |
+
if isinstance(line, str) and (blocks := [e for e in uniquify if e in line]):
|
| 909 |
+
modified_line = line
|
| 910 |
+
for block in blocks:
|
| 911 |
+
modified_line = modified_line.replace(
|
| 912 |
+
block, f"{block}_{num_kernel}"
|
| 913 |
+
)
|
| 914 |
+
modified.writeline(modified_line)
|
| 915 |
+
elif isinstance(line, DeferredLine) and (
|
| 916 |
+
blocks := [e for e in uniquify if e in line.line]
|
| 917 |
+
):
|
| 918 |
+
modified_line = line.line
|
| 919 |
+
for block in blocks:
|
| 920 |
+
modified_line = modified_line.replace(
|
| 921 |
+
block, f"{block}_{num_kernel}"
|
| 922 |
+
)
|
| 923 |
+
new_line = DeferredLine(line.name, modified_line)
|
| 924 |
+
modified.writeline(new_line)
|
| 925 |
+
else:
|
| 926 |
+
modified.writeline(line)
|
| 927 |
+
return modified
|
| 928 |
+
|
| 929 |
+
def call_kernel(self, code: IndentedBuffer, name: str) -> None:
|
| 930 |
+
_, call_args, _, arg_types = self.args.python_argdefs()
|
| 931 |
+
|
| 932 |
+
wrapper = V.graph.wrapper_code
|
| 933 |
+
assert self.dispatch_class is not None
|
| 934 |
+
if self.dynamic_shape_args:
|
| 935 |
+
self.add_numel_to_call_args(name, call_args, arg_types)
|
| 936 |
+
|
| 937 |
+
wrapper.generate_kernel_call(
|
| 938 |
+
name,
|
| 939 |
+
call_args,
|
| 940 |
+
triton=True,
|
| 941 |
+
arg_types=arg_types,
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
def combo_grid_meta(self) -> dict[str, Any]:
|
| 945 |
+
dynamic_shape = bool(self.dynamic_shape_args)
|
| 946 |
+
num_kernels = len(self.sub_kernels)
|
| 947 |
+
min_blocks = (
|
| 948 |
+
max(self.min_x_blocks_list) * num_kernels if not dynamic_shape else None
|
| 949 |
+
)
|
| 950 |
+
|
| 951 |
+
if not self.enable_autotune:
|
| 952 |
+
if "YBLOCK" in self.block_args:
|
| 953 |
+
default_config = {
|
| 954 |
+
"XBLOCK": self.block_size_2d,
|
| 955 |
+
"YBLOCK": self.block_size_2d,
|
| 956 |
+
}
|
| 957 |
+
else:
|
| 958 |
+
default_config = {"XBLOCK": self.block_size_1d}
|
| 959 |
+
else:
|
| 960 |
+
default_config = None
|
| 961 |
+
|
| 962 |
+
meta = {
|
| 963 |
+
"num_kernels": num_kernels,
|
| 964 |
+
"min_blocks": min_blocks,
|
| 965 |
+
"default_config": default_config,
|
| 966 |
+
}
|
| 967 |
+
|
| 968 |
+
for num, sub_kernel in enumerate(self.sub_kernels):
|
| 969 |
+
meta[f"no_x_dim_{num}"] = sub_kernel.no_x_dim
|
| 970 |
+
for i, tree in enumerate(sub_kernel.range_trees):
|
| 971 |
+
if not tree.is_reduction:
|
| 972 |
+
numel_name = f"{tree.prefix}numel_{num}"
|
| 973 |
+
if numel_name in self.dynamic_shape_args:
|
| 974 |
+
meta[numel_name] = None
|
| 975 |
+
else:
|
| 976 |
+
meta[numel_name] = int(V.graph.sizevars.simplify(tree.numel))
|
| 977 |
+
|
| 978 |
+
return meta
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton_split_scan.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
from typing import Union
|
| 4 |
+
|
| 5 |
+
import sympy
|
| 6 |
+
|
| 7 |
+
from torch._inductor import config
|
| 8 |
+
from torch._inductor.codegen.simd import IterationRangesRoot, prefix_is_reduction
|
| 9 |
+
from torch._inductor.codegen.triton import (
|
| 10 |
+
triton_compute_type,
|
| 11 |
+
TritonCSEVariable,
|
| 12 |
+
TritonKernel,
|
| 13 |
+
)
|
| 14 |
+
from torch._inductor.runtime.triton_heuristics import SplitScanGrid
|
| 15 |
+
from torch.utils._ordered_set import OrderedSet
|
| 16 |
+
from torch.utils._sympy.functions import CeilDiv
|
| 17 |
+
|
| 18 |
+
from ..utils import sympy_product
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TritonSplitScanKernel(TritonKernel):
|
| 22 |
+
"""Generates a triton kernel that supports ops.scan calls while also splitting
|
| 23 |
+
the reduction dimension over multiple triton programs.
|
| 24 |
+
|
| 25 |
+
For this kernel, loop numels will always take the form ``(xdim, rdim)``
|
| 26 |
+
and the grid has the shape ``(CeilDiv(rdim, RBLOCK), xdim)``. Communication
|
| 27 |
+
between blocks occurs within a global memory workspace buffer, which
|
| 28 |
+
must be zero-filled before launching the kernel.
|
| 29 |
+
|
| 30 |
+
Note that generation for ``ops.reduction`` is not supported.
|
| 31 |
+
|
| 32 |
+
For details of the communication strategy, see
|
| 33 |
+
https://research.nvidia.com/publication/2016-03_single-pass-parallel-prefix-scan-decoupled-look-back
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
tiling: dict[str, sympy.Expr],
|
| 40 |
+
pid_cache=None,
|
| 41 |
+
fixed_config=None,
|
| 42 |
+
**kwargs,
|
| 43 |
+
) -> None:
|
| 44 |
+
assert pid_cache is None, "not supported"
|
| 45 |
+
assert fixed_config is None, "not supported"
|
| 46 |
+
super().__init__(
|
| 47 |
+
tiling,
|
| 48 |
+
**kwargs,
|
| 49 |
+
)
|
| 50 |
+
self.no_x_dim = True
|
| 51 |
+
|
| 52 |
+
def should_use_persistent_reduction(self) -> bool:
|
| 53 |
+
return False
|
| 54 |
+
|
| 55 |
+
def should_use_cooperative_reduction(self) -> bool:
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
def initialize_range_tree(self, pid_cache):
|
| 59 |
+
prefixes = ["y", "x", "r0_"]
|
| 60 |
+
assert len(self.numels) <= len(prefixes), (
|
| 61 |
+
"z dimension not supported for split scan"
|
| 62 |
+
)
|
| 63 |
+
active_prefixes = prefixes[len(prefixes) - len(self.numels) :]
|
| 64 |
+
|
| 65 |
+
grid_dims = {"r0_": 0, "x": 1, "y": 2}
|
| 66 |
+
for prefix in active_prefixes:
|
| 67 |
+
numel = self.numels[prefix]
|
| 68 |
+
tensor_dim = 0 if prefix_is_reduction(prefix) else None
|
| 69 |
+
grid_dim = grid_dims[prefix]
|
| 70 |
+
self.range_trees.append(
|
| 71 |
+
IterationRangesRoot(
|
| 72 |
+
f"{prefix}index",
|
| 73 |
+
numel,
|
| 74 |
+
prefix,
|
| 75 |
+
grid_dim,
|
| 76 |
+
self, # type: ignore[arg-type]
|
| 77 |
+
pid_cache=pid_cache,
|
| 78 |
+
is_loop=False,
|
| 79 |
+
tensor_dim=tensor_dim,
|
| 80 |
+
grid_dim=grid_dim,
|
| 81 |
+
has_zdim=False,
|
| 82 |
+
)
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def reduction(self, dtype, src_dtype, reduction_type, value):
|
| 86 |
+
raise NotImplementedError("NYI TritonSplitDimKernel reductions")
|
| 87 |
+
|
| 88 |
+
def scan(self, dtypes, combine_fn, values):
|
| 89 |
+
"""
|
| 90 |
+
Perform an associative scan on 'values'.
|
| 91 |
+
"""
|
| 92 |
+
import triton.language as tl
|
| 93 |
+
|
| 94 |
+
(dtype,) = dtypes
|
| 95 |
+
(value,) = values
|
| 96 |
+
|
| 97 |
+
compute_type = triton_compute_type(dtype)
|
| 98 |
+
compute_type_triton = getattr(tl, compute_type[3:])
|
| 99 |
+
|
| 100 |
+
element_nbits = compute_type_triton.primitive_bitwidth
|
| 101 |
+
|
| 102 |
+
scratch_type = "tl.uint32" if element_nbits <= 16 else "tl.uint64"
|
| 103 |
+
scratch_type_triton = getattr(tl, scratch_type[3:])
|
| 104 |
+
scratch_elems_per_block = 3 if element_nbits == 64 else 1
|
| 105 |
+
scratch_nbytes_per_block = scratch_elems_per_block * (
|
| 106 |
+
scratch_type_triton.primitive_bitwidth // 8
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
cse_load = functools.partial(self.cse.generate, self.loads, dtype=dtype)
|
| 110 |
+
cse_compute = functools.partial(self.cse.generate, self.compute)
|
| 111 |
+
|
| 112 |
+
assert len(self.numels) == 2, "Unexpected tiling"
|
| 113 |
+
min_rblock = config.triton.min_split_scan_rblock
|
| 114 |
+
reduction_numel = sympy_product(
|
| 115 |
+
numel
|
| 116 |
+
for prefix, numel in self.numels.items()
|
| 117 |
+
if prefix_is_reduction(prefix)
|
| 118 |
+
)
|
| 119 |
+
pointwise_numel = sympy_product(
|
| 120 |
+
numel
|
| 121 |
+
for prefix, numel in self.numels.items()
|
| 122 |
+
if not prefix_is_reduction(prefix)
|
| 123 |
+
)
|
| 124 |
+
max_blocks = pointwise_numel * CeilDiv(reduction_numel, min_rblock)
|
| 125 |
+
nbytes = scratch_nbytes_per_block * max_blocks
|
| 126 |
+
scratch_base: Union[str, TritonCSEVariable]
|
| 127 |
+
scratch_base, offset = self.args.workspace(nbytes=nbytes, zero_fill=True)
|
| 128 |
+
if offset != 0:
|
| 129 |
+
scratch_base = cse_load(
|
| 130 |
+
f"{scratch_base} + {self.index_to_str(offset)}", shape=()
|
| 131 |
+
)
|
| 132 |
+
runtime_rblocks = cse_load(
|
| 133 |
+
f"tl.num_programs({self.range_trees[-1].index})", shape=()
|
| 134 |
+
)
|
| 135 |
+
scratch_base = cse_load(
|
| 136 |
+
f"{scratch_base}.to(tl.pointer_type({scratch_type})) + xoffset * "
|
| 137 |
+
f"{scratch_elems_per_block} * {runtime_rblocks}",
|
| 138 |
+
shape=(),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
masks = OrderedSet(f"{tree.prefix}mask" for tree in self.range_trees)
|
| 142 |
+
self.filter_masks(masks)
|
| 143 |
+
assert not self._load_mask, "ops.scan not supported inside ops.masked"
|
| 144 |
+
|
| 145 |
+
value = cse_compute(
|
| 146 |
+
f"{value}.to({compute_type})",
|
| 147 |
+
dtype=dtype,
|
| 148 |
+
shape=value.shape,
|
| 149 |
+
)
|
| 150 |
+
value = cse_compute(
|
| 151 |
+
f"tl.broadcast_to({value}, {self.dense_size_str()})",
|
| 152 |
+
dtype=dtype,
|
| 153 |
+
shape=self.dense_size_list(),
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
combine_helper_fn = self._lift_helper(combine_fn, (value,), (dtype,))
|
| 157 |
+
dim = self.triton_tensor_ndim() - 1
|
| 158 |
+
assert dim == 0, ""
|
| 159 |
+
shape = list(self.dense_size_list())
|
| 160 |
+
del shape[dim]
|
| 161 |
+
|
| 162 |
+
block_sum = cse_compute(
|
| 163 |
+
f"tl.reduce({value}, {dim}, {combine_helper_fn})",
|
| 164 |
+
dtype=dtype,
|
| 165 |
+
shape=shape,
|
| 166 |
+
)
|
| 167 |
+
exclusive_prefix = self.cse.newvar(
|
| 168 |
+
dtype=dtype,
|
| 169 |
+
shape=shape,
|
| 170 |
+
)
|
| 171 |
+
if element_nbits == 64:
|
| 172 |
+
self.compute.splice(
|
| 173 |
+
f"""
|
| 174 |
+
{exclusive_prefix} = triton_helpers.exclusive_scan_decoupled_lookback_64(
|
| 175 |
+
{scratch_base},
|
| 176 |
+
{block_sum},
|
| 177 |
+
{self.iteration_ranges_get_pid(self.range_trees[-1])},
|
| 178 |
+
{combine_helper_fn},
|
| 179 |
+
)
|
| 180 |
+
""",
|
| 181 |
+
strip=True,
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
else:
|
| 185 |
+
assert element_nbits <= 32
|
| 186 |
+
value_as_uint_dtype = f"tl.uint{element_nbits}"
|
| 187 |
+
|
| 188 |
+
self.compute.splice(
|
| 189 |
+
f"""
|
| 190 |
+
{exclusive_prefix} = triton_helpers.exclusive_scan_decoupled_lookback(
|
| 191 |
+
{scratch_base},
|
| 192 |
+
{block_sum},
|
| 193 |
+
{self.iteration_ranges_get_pid(self.range_trees[-1])},
|
| 194 |
+
{combine_helper_fn},
|
| 195 |
+
DTYPE_VALUE_AS_UINT={value_as_uint_dtype},
|
| 196 |
+
DTYPE_PACK={scratch_type},
|
| 197 |
+
)
|
| 198 |
+
""",
|
| 199 |
+
strip=True,
|
| 200 |
+
)
|
| 201 |
+
# Compute final cumsum
|
| 202 |
+
block_scan = cse_compute(
|
| 203 |
+
f"tl.associative_scan({value}, {dim}, {combine_helper_fn})",
|
| 204 |
+
dtype=dtype,
|
| 205 |
+
shape=shape,
|
| 206 |
+
)
|
| 207 |
+
combined_result = cse_compute(
|
| 208 |
+
f"{combine_helper_fn}({exclusive_prefix}, {block_scan})",
|
| 209 |
+
dtype=dtype,
|
| 210 |
+
shape=shape,
|
| 211 |
+
)
|
| 212 |
+
return (
|
| 213 |
+
cse_compute(
|
| 214 |
+
f"tl.where(roffset == 0, {block_scan}, {combined_result})",
|
| 215 |
+
dtype=dtype,
|
| 216 |
+
shape=block_scan.shape,
|
| 217 |
+
),
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
def _get_heuristic(self):
|
| 221 |
+
return "split_scan"
|
| 222 |
+
|
| 223 |
+
def _get_grid_type(self) -> type[SplitScanGrid]:
|
| 224 |
+
return SplitScanGrid
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/triton_utils.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from typing import Any, Optional
|
| 3 |
+
|
| 4 |
+
import sympy
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
from .. import config
|
| 9 |
+
from ..runtime.hints import AttrsDescriptorWrapper
|
| 10 |
+
from ..utils import _type_of, expr_fits_within_32bit, triton_version_uses_attrs_dict
|
| 11 |
+
from ..virtualized import V
|
| 12 |
+
from .common import (
|
| 13 |
+
ArgName,
|
| 14 |
+
ConstexprArg,
|
| 15 |
+
KernelArgType,
|
| 16 |
+
SizeArg,
|
| 17 |
+
TensorArg,
|
| 18 |
+
TMADescriptorArg,
|
| 19 |
+
WorkspaceArg,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def should_unwrap_unspec_arg(name: str):
|
| 24 |
+
if V.graph.is_unspec_arg(name):
|
| 25 |
+
# Unwrap on all devices except CPU
|
| 26 |
+
if V.graph.get_current_device_or_throw().type != "cpu":
|
| 27 |
+
return True
|
| 28 |
+
# Only unwrap on CPU if the input is not used as an output
|
| 29 |
+
if name not in V.graph.mutated_buffers:
|
| 30 |
+
return True
|
| 31 |
+
return False
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def signature_of(arg: KernelArgType, *, size_dtype: Optional[str]) -> str:
|
| 35 |
+
if isinstance(arg, TensorArg):
|
| 36 |
+
# TODO: Remove fp8 special handling when Triton supports PyTorch fp8 dtypes.
|
| 37 |
+
# Related PR: https://github.com/triton-lang/triton/pull/2279/
|
| 38 |
+
if arg.dtype == torch.float8_e4m3fn:
|
| 39 |
+
typ = "*fp8e4nv"
|
| 40 |
+
elif arg.dtype == torch.float8_e5m2:
|
| 41 |
+
typ = "*fp8e5"
|
| 42 |
+
elif arg.dtype == torch.float8_e4m3fnuz:
|
| 43 |
+
typ = "*fp8e4b8"
|
| 44 |
+
elif arg.dtype == torch.float8_e5m2fnuz:
|
| 45 |
+
typ = "*fp8e5b16"
|
| 46 |
+
else:
|
| 47 |
+
typ = _type_of(arg.dtype)
|
| 48 |
+
if should_unwrap_unspec_arg(arg.buffer):
|
| 49 |
+
# had unwrapped 0d tensor as scalar
|
| 50 |
+
new_typ = typ.lstrip("*")
|
| 51 |
+
if new_typ in ["fp16", "bf16"]:
|
| 52 |
+
return "fp32"
|
| 53 |
+
else:
|
| 54 |
+
return new_typ
|
| 55 |
+
else:
|
| 56 |
+
return typ
|
| 57 |
+
if isinstance(arg, SizeArg):
|
| 58 |
+
if arg.expr is None:
|
| 59 |
+
if triton_version_uses_attrs_dict():
|
| 60 |
+
# In newer versions of Triton, the signature includes "None" args
|
| 61 |
+
# and their type is marked as "constexpr"
|
| 62 |
+
return "constexpr"
|
| 63 |
+
else:
|
| 64 |
+
# In older versions of Triton...
|
| 65 |
+
# From triton/runtime/jit.py
|
| 66 |
+
# `None` is nullptr. Implicitly convert to *i8.
|
| 67 |
+
return "*i8"
|
| 68 |
+
elif _arg_equals_1(arg) and triton_version_uses_attrs_dict():
|
| 69 |
+
# In new versions of Triton, if we have an equal-to-1 arg that's marked as a constant,
|
| 70 |
+
# it should be marked as "constexpr" in the signature.
|
| 71 |
+
return "constexpr"
|
| 72 |
+
elif isinstance(arg.expr, (float, sympy.Float)):
|
| 73 |
+
return "fp32"
|
| 74 |
+
elif isinstance(arg.expr, bool):
|
| 75 |
+
return "i1"
|
| 76 |
+
|
| 77 |
+
# if this is a integer
|
| 78 |
+
if size_dtype == "tl.int32":
|
| 79 |
+
return "i32"
|
| 80 |
+
elif size_dtype == "tl.int64":
|
| 81 |
+
return "i64"
|
| 82 |
+
elif size_dtype is None:
|
| 83 |
+
# no hint: we'll see if we know that this is a 32-bit int, and guard if possible.
|
| 84 |
+
int_max = torch.iinfo(torch.int32).max
|
| 85 |
+
if expr_fits_within_32bit(arg.expr):
|
| 86 |
+
V.graph.sizevars.check_leq(arg.expr, int_max)
|
| 87 |
+
return "i32"
|
| 88 |
+
else:
|
| 89 |
+
return "i64"
|
| 90 |
+
else:
|
| 91 |
+
raise NotImplementedError(f"unhandled size_dtype {size_dtype}")
|
| 92 |
+
if isinstance(arg, WorkspaceArg):
|
| 93 |
+
return _type_of(arg.dtype)
|
| 94 |
+
if isinstance(arg, TMADescriptorArg):
|
| 95 |
+
if arg.api_type == "experimental":
|
| 96 |
+
return "nvTmaDesc"
|
| 97 |
+
else:
|
| 98 |
+
# https://github.com/triton-lang/triton/blob/9695baed9b46cf957e08b157bb4133f4a4b331c5/python/triton/runtime/jit.py#L360-L363
|
| 99 |
+
assert arg.api_type == "stable"
|
| 100 |
+
assert arg.block_shape is not None
|
| 101 |
+
assert arg.dtype is not None
|
| 102 |
+
inner = _type_of(arg.dtype)[1:] # strip the `*`: *fp32 -> fp32
|
| 103 |
+
return f"tensordesc<{inner}{list(arg.block_shape)}>"
|
| 104 |
+
if isinstance(arg, ConstexprArg):
|
| 105 |
+
return "constexpr"
|
| 106 |
+
raise NotImplementedError(f"unhandled {type(arg)}: {arg}")
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def non_constexpr_signature(signature):
|
| 110 |
+
new_signature = []
|
| 111 |
+
for arg in signature:
|
| 112 |
+
if not isinstance(arg, ConstexprArg):
|
| 113 |
+
new_signature.append(arg)
|
| 114 |
+
|
| 115 |
+
return new_signature
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def signature_to_meta(
|
| 119 |
+
signature: list[KernelArgType],
|
| 120 |
+
*,
|
| 121 |
+
size_dtype: Optional[str],
|
| 122 |
+
argdefs: list[ArgName],
|
| 123 |
+
indices: Optional[list[int]] = None,
|
| 124 |
+
is_template: bool = False,
|
| 125 |
+
) -> dict[str, str]:
|
| 126 |
+
if indices is None:
|
| 127 |
+
indices = list(range(len(signature)))
|
| 128 |
+
|
| 129 |
+
def _decide_tl_dtype(arg):
|
| 130 |
+
# Even if the ks0 symbol itself is within tl.int32 range, it's
|
| 131 |
+
# risky to use tl.int32 dtype since we may have ks0*ks1 later
|
| 132 |
+
# for kernels like torch.mean when dynamic shape is enabled.
|
| 133 |
+
#
|
| 134 |
+
# Check config.triton.use_block_ptr, since Triton block pointer
|
| 135 |
+
# does not support 64bit indexing:
|
| 136 |
+
# https://gist.github.com/shunting314/6a41c776171720ce4561f202dcde0ad6
|
| 137 |
+
#
|
| 138 |
+
# If the triton metadata is for a template, don't use tl.int64 index.
|
| 139 |
+
# Templates like flex attention/decoding uses block pointers which
|
| 140 |
+
# does not support 64 bit indexing.
|
| 141 |
+
if (
|
| 142 |
+
not config.triton.use_block_ptr
|
| 143 |
+
and not is_template
|
| 144 |
+
and isinstance(arg, SizeArg)
|
| 145 |
+
and arg.name.startswith("ks")
|
| 146 |
+
):
|
| 147 |
+
return "tl.int64"
|
| 148 |
+
return size_dtype
|
| 149 |
+
|
| 150 |
+
return {
|
| 151 |
+
argdefs[i].name: signature_of(arg, size_dtype=_decide_tl_dtype(arg))
|
| 152 |
+
for i, arg in zip(indices, signature)
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def is_unaligned_buffer(arg: TensorArg):
|
| 157 |
+
buf_name = arg.buffer
|
| 158 |
+
if buf_name in V.graph.unaligned_buffers:
|
| 159 |
+
return True
|
| 160 |
+
|
| 161 |
+
if buf_name in V.graph.graph_inputs:
|
| 162 |
+
# See Note: [Input Alignment handling in Inductor]
|
| 163 |
+
# For graph inputs that is not recorded in V.graph.unaligned_buffers,
|
| 164 |
+
# we know for sure the tensor is aligned.
|
| 165 |
+
return False
|
| 166 |
+
|
| 167 |
+
if buf_name in V.graph.constants:
|
| 168 |
+
# all constants are assumed to be aligned
|
| 169 |
+
return False
|
| 170 |
+
|
| 171 |
+
if V.graph.scheduler:
|
| 172 |
+
layout = V.graph.scheduler.get_buffer_layout(buf_name)
|
| 173 |
+
else:
|
| 174 |
+
buffer = V.graph.try_get_buffer(buf_name)
|
| 175 |
+
# output arg
|
| 176 |
+
if not buffer:
|
| 177 |
+
assert buf_name == V.kernel.output_node.name
|
| 178 |
+
layout = V.kernel.output_node.layout
|
| 179 |
+
else:
|
| 180 |
+
layout = buffer.get_layout()
|
| 181 |
+
|
| 182 |
+
if isinstance(layout, torch._inductor.ir.NonOwningLayout):
|
| 183 |
+
return not layout.maybe_guard_aligned()
|
| 184 |
+
else:
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _arg_equals_1(arg: KernelArgType) -> bool:
|
| 189 |
+
return (
|
| 190 |
+
isinstance(arg, SizeArg)
|
| 191 |
+
and isinstance(arg.expr, (int, sympy.Integer))
|
| 192 |
+
and V.graph.sizevars.statically_known_equals(arg.expr, 1) # type: ignore[arg-type]
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def equal_1_arg_indices(
|
| 197 |
+
args: list[KernelArgType],
|
| 198 |
+
*,
|
| 199 |
+
indices: Optional[list[int]] = None,
|
| 200 |
+
) -> tuple[int, ...]:
|
| 201 |
+
if indices is None:
|
| 202 |
+
indices = list(range(len(args)))
|
| 203 |
+
|
| 204 |
+
equal_to_1 = tuple(i for i, arg in zip(indices, args) if _arg_equals_1(arg))
|
| 205 |
+
|
| 206 |
+
return equal_to_1
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def config_of(
|
| 210 |
+
args: list[KernelArgType],
|
| 211 |
+
*,
|
| 212 |
+
indices: Optional[list[int]] = None,
|
| 213 |
+
) -> Any:
|
| 214 |
+
if indices is None:
|
| 215 |
+
indices = list(range(len(args)))
|
| 216 |
+
|
| 217 |
+
def is_aligned(x: KernelArgType, alignment: int, include_tensor: bool) -> bool:
|
| 218 |
+
"""
|
| 219 |
+
Roughly follow triton code here:
|
| 220 |
+
https://github.com/triton-lang/triton/blob/5282ed890d453e10b9ee30076ef89115dd197761/python/triton/runtime/jit.py#L208-L222
|
| 221 |
+
"""
|
| 222 |
+
if isinstance(x, TensorArg):
|
| 223 |
+
if include_tensor:
|
| 224 |
+
offset_aligned = V.graph.sizevars.statically_known_multiple_of(
|
| 225 |
+
x.offset * x.dtype.itemsize,
|
| 226 |
+
alignment, # type: ignore[arg-type]
|
| 227 |
+
)
|
| 228 |
+
return offset_aligned and not is_unaligned_buffer(x)
|
| 229 |
+
else:
|
| 230 |
+
return False
|
| 231 |
+
if isinstance(x, SizeArg):
|
| 232 |
+
# TODO(voz): These are kinda redundant, if we can solve out statically_known_multiple_of with
|
| 233 |
+
# _maybe_evaluate_static...
|
| 234 |
+
if x.name.startswith("load_seed_offset"):
|
| 235 |
+
return False
|
| 236 |
+
if x.expr is None:
|
| 237 |
+
return False
|
| 238 |
+
if isinstance(x.expr, float):
|
| 239 |
+
return False
|
| 240 |
+
return V.graph.sizevars.statically_known_multiple_of(x.expr, alignment) # type: ignore[arg-type]
|
| 241 |
+
if isinstance(x, WorkspaceArg):
|
| 242 |
+
# We allocate the workspace ourselves, so it is always aligned
|
| 243 |
+
return True
|
| 244 |
+
if isinstance(x, (TMADescriptorArg, ConstexprArg)):
|
| 245 |
+
return False
|
| 246 |
+
raise NotImplementedError(f"unhandled {type(x)}: {x}")
|
| 247 |
+
|
| 248 |
+
if config.triton.divisible_by_16:
|
| 249 |
+
divisible_by_16 = tuple(
|
| 250 |
+
i
|
| 251 |
+
for i, arg in zip(indices, args)
|
| 252 |
+
if is_aligned(arg, alignment=16, include_tensor=True)
|
| 253 |
+
)
|
| 254 |
+
else:
|
| 255 |
+
divisible_by_16 = ()
|
| 256 |
+
|
| 257 |
+
equal_to_1 = equal_1_arg_indices(args, indices=indices)
|
| 258 |
+
|
| 259 |
+
return AttrsDescriptorWrapper(divisible_by_16, equal_to_1)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/wrapper.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/wrapper_fxir.py
ADDED
|
@@ -0,0 +1,861 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dataclasses
|
| 2 |
+
import functools
|
| 3 |
+
import logging
|
| 4 |
+
import operator
|
| 5 |
+
import textwrap
|
| 6 |
+
from collections import Counter
|
| 7 |
+
from collections.abc import Sequence
|
| 8 |
+
from typing import Any, Callable, Optional, Union
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch._export.passes._node_metadata_hook import (
|
| 14 |
+
_node_metadata_hook,
|
| 15 |
+
_set_node_metadata_hook,
|
| 16 |
+
)
|
| 17 |
+
from torch._export.utils import _detect_fake_mode_from_gm
|
| 18 |
+
from torch._higher_order_ops.triton_kernel_wrap import (
|
| 19 |
+
TraceableTritonKernelWrapper,
|
| 20 |
+
tracing_triton_hopifier_singleton,
|
| 21 |
+
triton_kernel_wrapper_mutation,
|
| 22 |
+
)
|
| 23 |
+
from torch._inductor.codecache import LambdaFuture, PyCodeCache
|
| 24 |
+
from torch._inductor.runtime.triton_heuristics import CachingAutotuner
|
| 25 |
+
from torch._inductor.select_algorithm import extern_kernels # noqa: F401
|
| 26 |
+
from torch._inductor.utils import convert_shape_to_symint, sympy_product
|
| 27 |
+
from torch._inductor.virtualized import V
|
| 28 |
+
from torch._library.triton import wrap_triton
|
| 29 |
+
from torch.fx import GraphModule
|
| 30 |
+
from torch.utils import _pytree as pytree
|
| 31 |
+
from torch.utils._sympy.functions import FloorDiv
|
| 32 |
+
from torch.utils._sympy.interp import _run_sympy_handler, sympy_interp
|
| 33 |
+
from torch.utils._sympy.reference import OptimizedPythonReferenceAnalysis
|
| 34 |
+
|
| 35 |
+
from .. import config, ir
|
| 36 |
+
from ..runtime.triton_compat import Config
|
| 37 |
+
from ..utils import LineContext
|
| 38 |
+
from .common import (
|
| 39 |
+
CodegenSymbol,
|
| 40 |
+
FileBackedGraphModule,
|
| 41 |
+
WorkspaceArg,
|
| 42 |
+
WorkspaceZeroMode,
|
| 43 |
+
)
|
| 44 |
+
from .wrapper import (
|
| 45 |
+
AllocateLine,
|
| 46 |
+
BufferLike,
|
| 47 |
+
CommBufferAllocateLine,
|
| 48 |
+
CommBufferFreeLine,
|
| 49 |
+
CommentLine,
|
| 50 |
+
EnterDeviceContextManagerLine,
|
| 51 |
+
EnterSubgraphLine,
|
| 52 |
+
ExitDeviceContextManagerLine,
|
| 53 |
+
ExitSubgraphLine,
|
| 54 |
+
ExternKernelAllocLine,
|
| 55 |
+
ExternKernelOutLine,
|
| 56 |
+
FreeIfNotReusedLine,
|
| 57 |
+
FreeLine,
|
| 58 |
+
KernelCallLine,
|
| 59 |
+
KernelDefinitionLine,
|
| 60 |
+
Line,
|
| 61 |
+
MultiOutputLine,
|
| 62 |
+
NullLine,
|
| 63 |
+
PythonWrapperCodegen,
|
| 64 |
+
ReinterpretLine,
|
| 65 |
+
ReuseLine,
|
| 66 |
+
SymbolicCallArg,
|
| 67 |
+
SymbolicCallArgLine,
|
| 68 |
+
WrapperLine,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
aten = torch.ops.aten
|
| 73 |
+
log = logging.getLogger(__name__)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@dataclasses.dataclass
|
| 77 |
+
class SymbolBuffer(CodegenSymbol):
|
| 78 |
+
"""
|
| 79 |
+
Represents a sympy.Symbol graph input.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
symbol: sympy.Symbol
|
| 83 |
+
|
| 84 |
+
def get_name(self) -> str:
|
| 85 |
+
return str(self.symbol)
|
| 86 |
+
|
| 87 |
+
def get_example(self) -> Union[torch.Tensor, sympy.Symbol]:
|
| 88 |
+
return self.symbol
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
CodegenBuffer = Union[BufferLike, SymbolBuffer]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@dataclasses.dataclass
|
| 95 |
+
class TritonKernel:
|
| 96 |
+
"""
|
| 97 |
+
Stores metadata about Triton kernels for use in FX.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
tuner: CachingAutotuner
|
| 101 |
+
wrapped: TraceableTritonKernelWrapper
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def replace_floor_div(expr: sympy.Expr) -> sympy.Expr:
|
| 105 |
+
"""
|
| 106 |
+
Replace sympy.floor with FloorDiv.
|
| 107 |
+
"""
|
| 108 |
+
expr = sympy.together(expr)
|
| 109 |
+
|
| 110 |
+
# Find division operations in the sympy.floor expression
|
| 111 |
+
# Div is either represented as Mul with:
|
| 112 |
+
# Rational denominator or Pow with negative exponent
|
| 113 |
+
if not isinstance(expr, sympy.core.mul.Mul):
|
| 114 |
+
return sympy.floor(expr)
|
| 115 |
+
|
| 116 |
+
if isinstance(expr.args[0], sympy.Rational):
|
| 117 |
+
frac = expr.args[0]
|
| 118 |
+
numerator = sympy_product(expr.args[1:]) * frac.numerator
|
| 119 |
+
denominator = frac.denominator
|
| 120 |
+
|
| 121 |
+
return FloorDiv(numerator, denominator)
|
| 122 |
+
elif isinstance(expr.args[0], sympy.Pow):
|
| 123 |
+
base = expr.args[0].base
|
| 124 |
+
exp = expr.args[0].exp
|
| 125 |
+
numerator = sympy_product(expr.args[1:])
|
| 126 |
+
if exp < 0:
|
| 127 |
+
denominator = base ** (-exp)
|
| 128 |
+
else:
|
| 129 |
+
numerator = numerator * (base**exp)
|
| 130 |
+
denominator = 1
|
| 131 |
+
return FloorDiv(numerator, denominator)
|
| 132 |
+
else:
|
| 133 |
+
return sympy.floor(expr)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class WrapperFxCodegen(PythonWrapperCodegen):
|
| 137 |
+
"""
|
| 138 |
+
Backend to generate wrapper code as an FX IR graph.
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
supports_caching = False
|
| 142 |
+
|
| 143 |
+
def _generate(self, is_inference: bool) -> tuple[FileBackedGraphModule, None]:
|
| 144 |
+
self.run_wrapper_ir_passes(is_inference)
|
| 145 |
+
|
| 146 |
+
prologue = "\n".join(
|
| 147 |
+
[
|
| 148 |
+
self.imports.getvalue(),
|
| 149 |
+
self.header.getvalue(),
|
| 150 |
+
]
|
| 151 |
+
)
|
| 152 |
+
gm = FxConverter(lines=self.lines, prologue=prologue).generate()
|
| 153 |
+
compiled_fn = self.compile_graph(gm)
|
| 154 |
+
|
| 155 |
+
return FileBackedGraphModule(gm, compiled_fn), None
|
| 156 |
+
|
| 157 |
+
def compile_graph(self, gm: GraphModule) -> Callable[..., Any]:
|
| 158 |
+
"""
|
| 159 |
+
Converts the graph module into a runnable function. The default implementation
|
| 160 |
+
is simply an interpreter calling kernels in eager mode. Derived backends can
|
| 161 |
+
override this to do further compilation.
|
| 162 |
+
"""
|
| 163 |
+
return gm.forward
|
| 164 |
+
|
| 165 |
+
@classmethod
|
| 166 |
+
def create(
|
| 167 |
+
cls,
|
| 168 |
+
is_subgraph: bool,
|
| 169 |
+
subgraph_name: Optional[str],
|
| 170 |
+
parent_wrapper: Optional[PythonWrapperCodegen],
|
| 171 |
+
partition_signatures: Optional[ir.GraphPartitionSignature] = None,
|
| 172 |
+
) -> "WrapperFxCodegen":
|
| 173 |
+
if is_subgraph:
|
| 174 |
+
raise NotImplementedError(
|
| 175 |
+
"Subgraphs are not yet supported by FX conversion"
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
# For derived backends, this could be a subclass.
|
| 179 |
+
return cls()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@dataclasses.dataclass
|
| 183 |
+
class FxConverter:
|
| 184 |
+
"""
|
| 185 |
+
Generates FX IR from Wrapper IR. As each instance is only meant to be used once, the
|
| 186 |
+
input and output code are stored as attributes.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
lines: list[Line]
|
| 190 |
+
prologue: str = ""
|
| 191 |
+
|
| 192 |
+
def __post_init__(self) -> None:
|
| 193 |
+
graph = torch.fx.Graph()
|
| 194 |
+
self.gm = GraphModule({}, graph) # Wrapper FX IR.
|
| 195 |
+
self.buffer_to_node: dict[
|
| 196 |
+
Optional[str], torch.fx.Node
|
| 197 |
+
] = {} # Symbol table for codegen.
|
| 198 |
+
self.kernels: dict[str, TritonKernel] = {} # Table to store Triton kernels.
|
| 199 |
+
self._unique_symbol_ids: Counter[str] = Counter()
|
| 200 |
+
self.tracer = torch.fx.proxy.GraphAppendingTracer(graph)
|
| 201 |
+
self.expr_to_proxy: dict[sympy.Expr, torch.fx.Proxy] = {}
|
| 202 |
+
|
| 203 |
+
def _import_kernel(self, code: str, kernel_name: str) -> CachingAutotuner:
|
| 204 |
+
"""
|
| 205 |
+
Imports a kernel from source, possibly autotuning block parameters.
|
| 206 |
+
"""
|
| 207 |
+
module_code = "\n".join([self.prologue, code])
|
| 208 |
+
mod = PyCodeCache.load(module_code)
|
| 209 |
+
kernel = getattr(mod, kernel_name)
|
| 210 |
+
|
| 211 |
+
if isinstance(kernel, LambdaFuture):
|
| 212 |
+
kernel = kernel.result()
|
| 213 |
+
|
| 214 |
+
if not isinstance(kernel, CachingAutotuner):
|
| 215 |
+
raise NotImplementedError(
|
| 216 |
+
textwrap.dedent(f"""
|
| 217 |
+
Unsupported type for kernel {kernel_name}: {type(kernel)}.
|
| 218 |
+
FX conversion only supports Triton kernels.
|
| 219 |
+
""")
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
return kernel
|
| 223 |
+
|
| 224 |
+
def _fake_tensor(
|
| 225 |
+
self,
|
| 226 |
+
size: tuple[Any, ...],
|
| 227 |
+
stride: tuple[Any, ...],
|
| 228 |
+
dtype: Optional[torch.dtype] = None,
|
| 229 |
+
device: Optional[torch.device] = None,
|
| 230 |
+
) -> torch.Tensor:
|
| 231 |
+
with V.fake_mode:
|
| 232 |
+
return torch.empty_strided(
|
| 233 |
+
convert_shape_to_symint(size),
|
| 234 |
+
convert_shape_to_symint(stride),
|
| 235 |
+
dtype=dtype,
|
| 236 |
+
device=device,
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
def _create_as_strided(
|
| 240 |
+
self,
|
| 241 |
+
input_node: torch.fx.Node,
|
| 242 |
+
size: tuple[Any, ...],
|
| 243 |
+
stride: tuple[Any, ...],
|
| 244 |
+
offset: Union[int, sympy.Expr],
|
| 245 |
+
) -> torch.fx.Node:
|
| 246 |
+
return self.gm.graph.call_function(
|
| 247 |
+
torch.as_strided,
|
| 248 |
+
args=(
|
| 249 |
+
input_node,
|
| 250 |
+
self._generate_sym_nodes(size),
|
| 251 |
+
self._generate_sym_nodes(stride),
|
| 252 |
+
self._generate_sym_node(offset),
|
| 253 |
+
),
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
def _record_allocation(self, buffer: CodegenBuffer, node: torch.fx.Node) -> None:
|
| 257 |
+
"""
|
| 258 |
+
Updates the symbol table to record that an Inductor buffer maps to the result of
|
| 259 |
+
an FX node.
|
| 260 |
+
"""
|
| 261 |
+
assert node not in self.buffer_to_node
|
| 262 |
+
self.buffer_to_node[buffer.get_name()] = node
|
| 263 |
+
|
| 264 |
+
def _free(self, buffer: Union[CodegenBuffer, ir.TorchBindObject]) -> None:
|
| 265 |
+
"""
|
| 266 |
+
Removes the buffer from the symbol table.
|
| 267 |
+
"""
|
| 268 |
+
name = buffer.get_name()
|
| 269 |
+
del self.buffer_to_node[name]
|
| 270 |
+
|
| 271 |
+
def _lookup_args(self, args: tuple[Any, ...]) -> tuple[Any, ...]:
|
| 272 |
+
"""
|
| 273 |
+
Maps call args back to FX nodes.
|
| 274 |
+
"""
|
| 275 |
+
return tuple(
|
| 276 |
+
self.buffer_to_node[arg]
|
| 277 |
+
if isinstance(arg, str)
|
| 278 |
+
else arg.inner_expr
|
| 279 |
+
if isinstance(arg, SymbolicCallArg)
|
| 280 |
+
else arg
|
| 281 |
+
for arg in args
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
def _get_buffer(self, node: ir.IRNode) -> CodegenBuffer:
|
| 285 |
+
"""
|
| 286 |
+
Extract buffer data from an IR node.
|
| 287 |
+
"""
|
| 288 |
+
if isinstance(node, (ir.Buffer, WorkspaceArg)):
|
| 289 |
+
return node
|
| 290 |
+
elif isinstance(node, (ir.BaseView, ir.MutableBox)):
|
| 291 |
+
return self._get_buffer(node.data)
|
| 292 |
+
elif isinstance(node, sympy.Symbol):
|
| 293 |
+
return SymbolBuffer(node)
|
| 294 |
+
else:
|
| 295 |
+
raise NotImplementedError(f"Unable to extract buffer from node: {node}")
|
| 296 |
+
|
| 297 |
+
def _generate_graph_inputs(self) -> None:
|
| 298 |
+
"""
|
| 299 |
+
Converts graph inputs to FX placeholders.
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
for node in V.graph.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr]
|
| 303 |
+
name = node.name
|
| 304 |
+
if name in V.graph.graph_inputs:
|
| 305 |
+
ir_node = V.graph.graph_inputs[name]
|
| 306 |
+
|
| 307 |
+
# Introduce a new symbol for constant inputs.
|
| 308 |
+
buffer = (
|
| 309 |
+
SymbolBuffer(sympy.Symbol(name, is_integer=True))
|
| 310 |
+
if isinstance(ir_node, (int, float, sympy.Integer, sympy.Float))
|
| 311 |
+
else self._get_buffer(ir_node)
|
| 312 |
+
)
|
| 313 |
+
placeholder_node = self.gm.graph.placeholder(buffer.get_name())
|
| 314 |
+
placeholder_node.meta["val"] = buffer.get_example()
|
| 315 |
+
self._record_allocation(buffer, placeholder_node)
|
| 316 |
+
|
| 317 |
+
elif V.aot_compilation:
|
| 318 |
+
# Create dummy input nodes to match the input signature
|
| 319 |
+
self.gm.graph.placeholder(name)
|
| 320 |
+
|
| 321 |
+
def _generate_graph_input_shapes(self) -> None:
|
| 322 |
+
"""
|
| 323 |
+
Generate nodes creating symints that are part of graph input
|
| 324 |
+
shape/strides.
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
def _codegen_symbol(
|
| 328 |
+
sym_or_exp: Union[sympy.Symbol, sympy.Expr],
|
| 329 |
+
base_node: torch.fx.Node,
|
| 330 |
+
target: torch._ops.OpOverload,
|
| 331 |
+
dim: int,
|
| 332 |
+
) -> None:
|
| 333 |
+
if isinstance(sym_or_exp, sympy.Symbol):
|
| 334 |
+
if sym_or_exp in self.expr_to_proxy:
|
| 335 |
+
return
|
| 336 |
+
|
| 337 |
+
size_node = self.gm.graph.call_function(target, (base_node, dim))
|
| 338 |
+
size_proxy = torch.fx.Proxy(size_node, tracer=self.tracer)
|
| 339 |
+
|
| 340 |
+
self.expr_to_proxy[sym_or_exp] = size_proxy
|
| 341 |
+
|
| 342 |
+
elif isinstance(sym_or_exp, sympy.Integer):
|
| 343 |
+
return
|
| 344 |
+
|
| 345 |
+
elif isinstance(sym_or_exp, sympy.Expr):
|
| 346 |
+
self._sympy_interp(sym_or_exp)
|
| 347 |
+
|
| 348 |
+
for node in V.graph.module.graph.find_nodes(op="placeholder"): # type: ignore[operator, union-attr]
|
| 349 |
+
name = node.name
|
| 350 |
+
if name in V.graph.graph_inputs:
|
| 351 |
+
ir_node = V.graph.graph_inputs[name]
|
| 352 |
+
if isinstance(ir_node, ir.TensorBox):
|
| 353 |
+
buffer = self._get_buffer(ir_node)
|
| 354 |
+
placeholder_node = self.buffer_to_node[buffer.get_name()]
|
| 355 |
+
|
| 356 |
+
for dim, size in enumerate(ir_node.get_size()):
|
| 357 |
+
_codegen_symbol(
|
| 358 |
+
size, placeholder_node, torch.ops.aten.sym_size.int, dim
|
| 359 |
+
)
|
| 360 |
+
for dim, stride in enumerate(ir_node.get_stride()):
|
| 361 |
+
_codegen_symbol(
|
| 362 |
+
stride, placeholder_node, torch.ops.aten.sym_stride.int, dim
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
def _generate_graph_constants(self) -> None:
|
| 366 |
+
for name, value in V.graph.constants.items():
|
| 367 |
+
node = self.gm.graph.get_attr(name)
|
| 368 |
+
node.meta["val"] = value
|
| 369 |
+
setattr(self.gm, name, value)
|
| 370 |
+
self.buffer_to_node[name] = node
|
| 371 |
+
|
| 372 |
+
def _generate_buffer(self, node: ir.IRNode) -> Optional[torch.fx.Node]:
|
| 373 |
+
"""
|
| 374 |
+
Generates FX IR for transformations on a buffer, such as ReinterpretView.
|
| 375 |
+
Does nothing if no such transformations are present.
|
| 376 |
+
"""
|
| 377 |
+
|
| 378 |
+
def generate_to_buffer(node: ir.IRNode) -> Optional[BufferLike]:
|
| 379 |
+
if isinstance(node, (ir.Buffer, WorkspaceArg)):
|
| 380 |
+
return node
|
| 381 |
+
elif isinstance(node, ir.NoneAsConstantBuffer):
|
| 382 |
+
return None
|
| 383 |
+
elif isinstance(node, ir.MutableBox):
|
| 384 |
+
return generate_to_buffer(node.data)
|
| 385 |
+
elif isinstance(node, ir.ReinterpretView):
|
| 386 |
+
# We need to introduce a new symbol if the output is a ReinterpretView.
|
| 387 |
+
# Use a WorkspaceArg for this.
|
| 388 |
+
buffer = self._get_buffer(node.data)
|
| 389 |
+
assert isinstance(buffer, (ir.Buffer, WorkspaceArg))
|
| 390 |
+
unique_name = self.gm.graph._graph_namespace.create_name(
|
| 391 |
+
f"{buffer.get_name()}_view", None
|
| 392 |
+
)
|
| 393 |
+
device = buffer.get_device()
|
| 394 |
+
assert device
|
| 395 |
+
reused_as = WorkspaceArg(
|
| 396 |
+
count=buffer.get_size(),
|
| 397 |
+
zero_mode=WorkspaceZeroMode.UNINITIALIZED,
|
| 398 |
+
device=device,
|
| 399 |
+
outer_name=unique_name,
|
| 400 |
+
dtype=buffer.get_dtype(),
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# Generate FX IR for the view.
|
| 404 |
+
self._generate_reinterpret_helper(buffer, reused_as, node.layout)
|
| 405 |
+
|
| 406 |
+
return reused_as
|
| 407 |
+
else:
|
| 408 |
+
raise NotImplementedError(f"Unrecognized buffer/view node: {node}")
|
| 409 |
+
|
| 410 |
+
buffer = generate_to_buffer(node)
|
| 411 |
+
return self.buffer_to_node[buffer.get_name()] if buffer is not None else None
|
| 412 |
+
|
| 413 |
+
def _generate_output(self) -> None:
|
| 414 |
+
"""
|
| 415 |
+
Generate FX IR for graph outputs.
|
| 416 |
+
"""
|
| 417 |
+
output_nodes = [
|
| 418 |
+
self._generate_buffer(node)
|
| 419 |
+
for idx, node in enumerate(V.graph.graph_outputs)
|
| 420 |
+
]
|
| 421 |
+
|
| 422 |
+
# Single return elements don't use a tuple.
|
| 423 |
+
output_value = output_nodes[0] if len(output_nodes) == 1 else output_nodes
|
| 424 |
+
|
| 425 |
+
self.gm.graph.output(output_value)
|
| 426 |
+
|
| 427 |
+
def generate(self) -> torch.fx.GraphModule:
|
| 428 |
+
"""
|
| 429 |
+
Main entrypoint for FX codegen.
|
| 430 |
+
"""
|
| 431 |
+
self._generate_graph_inputs()
|
| 432 |
+
self._generate_graph_constants()
|
| 433 |
+
|
| 434 |
+
fake_mode = _detect_fake_mode_from_gm(self.gm)
|
| 435 |
+
|
| 436 |
+
with _set_node_metadata_hook(
|
| 437 |
+
self.gm,
|
| 438 |
+
functools.partial(_node_metadata_hook, fake_mode=fake_mode),
|
| 439 |
+
):
|
| 440 |
+
self._generate_graph_input_shapes()
|
| 441 |
+
|
| 442 |
+
# Generate FX IR from Wrapper IR lines.
|
| 443 |
+
for line in self.lines:
|
| 444 |
+
if isinstance(line, WrapperLine):
|
| 445 |
+
line.codegen_fx(self)(line)
|
| 446 |
+
elif isinstance(line, LineContext):
|
| 447 |
+
# Ignore line context in FX IR.
|
| 448 |
+
pass
|
| 449 |
+
else:
|
| 450 |
+
raise NotImplementedError(
|
| 451 |
+
textwrap.dedent(
|
| 452 |
+
f"""
|
| 453 |
+
Found line of unrecognized type '{type(line)}':
|
| 454 |
+
'{line}'
|
| 455 |
+
|
| 456 |
+
FX conversion only supports Wrapper IR lines.
|
| 457 |
+
"""
|
| 458 |
+
)
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
self._generate_output()
|
| 462 |
+
self.gm.recompile()
|
| 463 |
+
return self.gm
|
| 464 |
+
|
| 465 |
+
def _sympy_interp(self, expr: sympy.Expr) -> torch.fx.Proxy:
|
| 466 |
+
# hash cons
|
| 467 |
+
if expr in self.expr_to_proxy:
|
| 468 |
+
return self.expr_to_proxy[expr]
|
| 469 |
+
# base cases, don't cache
|
| 470 |
+
if isinstance(
|
| 471 |
+
expr,
|
| 472 |
+
(
|
| 473 |
+
sympy.Integer,
|
| 474 |
+
sympy.Number,
|
| 475 |
+
sympy.Symbol,
|
| 476 |
+
sympy.logic.boolalg.BooleanAtom,
|
| 477 |
+
),
|
| 478 |
+
):
|
| 479 |
+
return sympy_interp(
|
| 480 |
+
OptimizedPythonReferenceAnalysis, self.expr_to_proxy, expr
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
# hash cons on arguments, run expr handler
|
| 484 |
+
self.expr_to_proxy[expr] = _run_sympy_handler(
|
| 485 |
+
OptimizedPythonReferenceAnalysis,
|
| 486 |
+
[self._sympy_interp(arg) for arg in expr.args],
|
| 487 |
+
expr,
|
| 488 |
+
)
|
| 489 |
+
return self.expr_to_proxy[expr]
|
| 490 |
+
|
| 491 |
+
def _generate_sym_node(
|
| 492 |
+
self, s: Union[int, sympy.Expr]
|
| 493 |
+
) -> Union[int, torch.fx.Node]:
|
| 494 |
+
if isinstance(s, (int, sympy.Integer)):
|
| 495 |
+
return int(s)
|
| 496 |
+
elif isinstance(s, sympy.Symbol):
|
| 497 |
+
assert s in self.expr_to_proxy, (
|
| 498 |
+
f"Could not find a node corresponding to the symbol {s}"
|
| 499 |
+
)
|
| 500 |
+
return self.expr_to_proxy[s].node
|
| 501 |
+
elif isinstance(s, sympy.Expr):
|
| 502 |
+
return self._sympy_interp(s).node
|
| 503 |
+
|
| 504 |
+
elif isinstance(s, torch.fx.Node):
|
| 505 |
+
return s
|
| 506 |
+
|
| 507 |
+
else:
|
| 508 |
+
raise ValueError(f"{s} of type {type(s)} is not a valid input")
|
| 509 |
+
|
| 510 |
+
def _generate_sym_nodes(
|
| 511 |
+
self, shape: Sequence[sympy.Expr]
|
| 512 |
+
) -> list[Union[int, torch.fx.Node]]:
|
| 513 |
+
return [self._generate_sym_node(s) for s in shape]
|
| 514 |
+
|
| 515 |
+
def _generate_allocate(self, line: WrapperLine) -> None:
|
| 516 |
+
assert isinstance(line, AllocateLine)
|
| 517 |
+
buffer = line.node
|
| 518 |
+
name = buffer.get_name()
|
| 519 |
+
assert name not in V.graph.removed_buffers
|
| 520 |
+
|
| 521 |
+
device = buffer.get_device()
|
| 522 |
+
dtype = buffer.get_dtype()
|
| 523 |
+
shape = self._generate_sym_nodes(buffer.get_size())
|
| 524 |
+
stride = self._generate_sym_nodes(buffer.get_stride())
|
| 525 |
+
|
| 526 |
+
node = self.gm.graph.call_function(
|
| 527 |
+
torch.empty_strided,
|
| 528 |
+
args=(shape, stride),
|
| 529 |
+
kwargs={"dtype": dtype, "device": device},
|
| 530 |
+
)
|
| 531 |
+
assert name
|
| 532 |
+
node.name = name
|
| 533 |
+
self._record_allocation(buffer, node)
|
| 534 |
+
|
| 535 |
+
def _generate_comment(self, line: WrapperLine) -> None:
|
| 536 |
+
assert isinstance(line, CommentLine)
|
| 537 |
+
# We ignore comments in FX IR.
|
| 538 |
+
|
| 539 |
+
def _generate_enter_device_context_manager(self, line: WrapperLine) -> None:
|
| 540 |
+
assert isinstance(line, EnterDeviceContextManagerLine)
|
| 541 |
+
# We ignore the device context in FX IR.
|
| 542 |
+
|
| 543 |
+
def _generate_exit_device_context_manager(self, line: WrapperLine) -> None:
|
| 544 |
+
assert isinstance(line, ExitDeviceContextManagerLine)
|
| 545 |
+
# We ignore the device context in FX IR.
|
| 546 |
+
|
| 547 |
+
def _generate_enter_subgraph(self, line: WrapperLine) -> None:
|
| 548 |
+
assert isinstance(line, EnterSubgraphLine)
|
| 549 |
+
raise NotImplementedError("Subgraphs are not yet supported by FX conversion")
|
| 550 |
+
|
| 551 |
+
def _generate_exit_subgraph(self, line: WrapperLine) -> None:
|
| 552 |
+
assert isinstance(line, ExitSubgraphLine)
|
| 553 |
+
raise NotImplementedError("Subgraphs are not yet supported by FX conversion")
|
| 554 |
+
|
| 555 |
+
def _generate_free(self, line: WrapperLine) -> None:
|
| 556 |
+
assert isinstance(line, FreeLine)
|
| 557 |
+
|
| 558 |
+
buf = line.node
|
| 559 |
+
|
| 560 |
+
# No need to free placeholders.
|
| 561 |
+
if self.buffer_to_node[buf.get_name()].op == "placeholder":
|
| 562 |
+
return
|
| 563 |
+
|
| 564 |
+
self._free(buf)
|
| 565 |
+
|
| 566 |
+
def _generate_free_if_not_reused(self, line: WrapperLine) -> None:
|
| 567 |
+
assert isinstance(line, FreeIfNotReusedLine)
|
| 568 |
+
buf = line.node
|
| 569 |
+
assert buf.get_name() not in V.graph.removed_buffers
|
| 570 |
+
if not line.is_reused:
|
| 571 |
+
self._free(buf)
|
| 572 |
+
|
| 573 |
+
def _generate_line_context(self, line: WrapperLine) -> None:
|
| 574 |
+
assert isinstance(line, LineContext)
|
| 575 |
+
# We ignore line context in FX IR.
|
| 576 |
+
|
| 577 |
+
def _generate_reinterpret(self, line: WrapperLine) -> None:
|
| 578 |
+
assert isinstance(line, ReinterpretLine)
|
| 579 |
+
self._generate_reinterpret_helper(line.node, line.reused_as, line.layout)
|
| 580 |
+
|
| 581 |
+
def _generate_reinterpret_helper(
|
| 582 |
+
self, input_buffer: BufferLike, result_buffer: BufferLike, layout: ir.Layout
|
| 583 |
+
) -> None:
|
| 584 |
+
input_node = self.buffer_to_node[input_buffer.get_name()]
|
| 585 |
+
|
| 586 |
+
# Look up output metadata.
|
| 587 |
+
name = result_buffer.get_name()
|
| 588 |
+
assert name
|
| 589 |
+
size = tuple(layout.size)
|
| 590 |
+
stride = tuple(layout.stride)
|
| 591 |
+
if isinstance(layout, ir.NonOwningLayout):
|
| 592 |
+
# Look up the view's layout.
|
| 593 |
+
view = layout.view
|
| 594 |
+
assert isinstance(view, ir.ReinterpretView), (
|
| 595 |
+
f"unexpected type: {type(view)}"
|
| 596 |
+
)
|
| 597 |
+
layout = view.layout
|
| 598 |
+
offset = input_buffer.get_offset() + layout.offset
|
| 599 |
+
|
| 600 |
+
# Map ReinterpretView to as_strided.
|
| 601 |
+
result_node = self._create_as_strided(input_node, size, stride, offset)
|
| 602 |
+
result_node.name = name
|
| 603 |
+
self._record_allocation(result_buffer, result_node)
|
| 604 |
+
|
| 605 |
+
def _generate_reuse(self, line: WrapperLine) -> None:
|
| 606 |
+
assert isinstance(line, ReuseLine)
|
| 607 |
+
old = line.node
|
| 608 |
+
new = line.reused_as
|
| 609 |
+
assert not any(buf.get_name() in V.graph.removed_buffers for buf in (old, new))
|
| 610 |
+
assert old.get_dtype() == new.get_dtype()
|
| 611 |
+
|
| 612 |
+
old_node = self.buffer_to_node[old.get_name()]
|
| 613 |
+
result_node = old_node
|
| 614 |
+
|
| 615 |
+
# Change shape and stride.
|
| 616 |
+
size = tuple(new.get_size())
|
| 617 |
+
stride = tuple(new.get_stride())
|
| 618 |
+
offset = new.get_offset()
|
| 619 |
+
if (
|
| 620 |
+
tuple(old.get_size()) != size
|
| 621 |
+
or tuple(old.get_stride()) != stride
|
| 622 |
+
or old.get_offset() != offset
|
| 623 |
+
):
|
| 624 |
+
result_node = self._create_as_strided(old_node, size, stride, offset)
|
| 625 |
+
|
| 626 |
+
self._record_allocation(new, result_node)
|
| 627 |
+
|
| 628 |
+
# Free the old buffer, if we allocated a new tensor.
|
| 629 |
+
if (
|
| 630 |
+
old.get_name() not in V.graph.get_output_names()
|
| 631 |
+
and line.delete_old
|
| 632 |
+
and result_node is not old_node
|
| 633 |
+
):
|
| 634 |
+
self._free(old)
|
| 635 |
+
|
| 636 |
+
def _generate_multi_output(self, line: WrapperLine) -> None:
|
| 637 |
+
assert isinstance(line, MultiOutputLine)
|
| 638 |
+
|
| 639 |
+
arg_node = self.buffer_to_node[line.arg_name]
|
| 640 |
+
|
| 641 |
+
# For non-tuple / non-list outputs, map the
|
| 642 |
+
# output to the same node as the input.
|
| 643 |
+
if len(line.indices) == 0:
|
| 644 |
+
self.buffer_to_node[line.result_name] = arg_node
|
| 645 |
+
return
|
| 646 |
+
|
| 647 |
+
# Extract the index for tuple access.
|
| 648 |
+
inds = line.indices[0][1:]
|
| 649 |
+
assert len(inds) == 1, f"Cannot convert {inds} to an index."
|
| 650 |
+
idx = inds[0]
|
| 651 |
+
|
| 652 |
+
node = self.gm.graph.call_function(operator.getitem, args=(arg_node, idx))
|
| 653 |
+
node.name = line.result_name
|
| 654 |
+
self.buffer_to_node[line.result_name] = node
|
| 655 |
+
|
| 656 |
+
def _generate_null(self, line: WrapperLine) -> None:
|
| 657 |
+
assert isinstance(line, NullLine)
|
| 658 |
+
# Does nothing.
|
| 659 |
+
|
| 660 |
+
def _generate_comm_buffer_allocate(self, line: WrapperLine) -> None:
|
| 661 |
+
assert isinstance(line, CommBufferAllocateLine)
|
| 662 |
+
raise NotImplementedError("Comm buffer allocation is not yet supported")
|
| 663 |
+
|
| 664 |
+
def _generate_comm_buffer_free(self, line: WrapperLine) -> None:
|
| 665 |
+
assert isinstance(line, CommBufferFreeLine)
|
| 666 |
+
self._free(line.node)
|
| 667 |
+
|
| 668 |
+
def _generate_triton_call(self, line: WrapperLine) -> None:
|
| 669 |
+
assert isinstance(line, KernelCallLine)
|
| 670 |
+
|
| 671 |
+
# Collect all kwargs, including autotuned block sizes.
|
| 672 |
+
call_args = self._lookup_args(line.call_args)
|
| 673 |
+
kernel = self.kernels[line.kernel_name]
|
| 674 |
+
tuner = kernel.tuner
|
| 675 |
+
# Use python_slow mode instead of python mode to avoid
|
| 676 |
+
# the round to neginf behaviour, which is not the convention
|
| 677 |
+
# in other languages.
|
| 678 |
+
tuner.grid_mode = "python_slow"
|
| 679 |
+
|
| 680 |
+
# Optionally autotune the kernels.
|
| 681 |
+
# The FX backend currently only supports compile-time tuning.
|
| 682 |
+
kernel_name = tuner.fn.__name__
|
| 683 |
+
if config.triton.autotune_at_compile_time:
|
| 684 |
+
from triton.runtime import driver
|
| 685 |
+
|
| 686 |
+
log.info("Autotuning Triton kernel %s at compile time.", kernel_name)
|
| 687 |
+
device = driver.active.get_current_device()
|
| 688 |
+
stream = driver.active.get_current_stream(device)
|
| 689 |
+
|
| 690 |
+
def node_to_tuning_arg(arg: Any) -> Any:
|
| 691 |
+
"""
|
| 692 |
+
Create real tensors for autotuning arguments, substituting size hints
|
| 693 |
+
for dynamic shapes.
|
| 694 |
+
"""
|
| 695 |
+
to_size_hint = functools.partial(
|
| 696 |
+
pytree.tree_map, V.graph.sizevars.size_hint
|
| 697 |
+
)
|
| 698 |
+
if not isinstance(arg, torch.fx.Node):
|
| 699 |
+
return to_size_hint(arg)
|
| 700 |
+
|
| 701 |
+
fake = arg.meta["val"]
|
| 702 |
+
return torch.empty_strided(
|
| 703 |
+
to_size_hint(fake.shape),
|
| 704 |
+
to_size_hint(fake.stride()),
|
| 705 |
+
device=device,
|
| 706 |
+
).zero_()
|
| 707 |
+
|
| 708 |
+
arg_values = [node_to_tuning_arg(arg) for arg in call_args]
|
| 709 |
+
tuner.run(*arg_values, stream=stream)
|
| 710 |
+
else:
|
| 711 |
+
log.info(
|
| 712 |
+
"Skipping autotuning for kernel %s. Set config.triton.autotune_at_compile_time = True to enable.",
|
| 713 |
+
kernel_name,
|
| 714 |
+
)
|
| 715 |
+
|
| 716 |
+
triton_meta = tuner.triton_meta
|
| 717 |
+
signature = triton_meta["signature"]
|
| 718 |
+
|
| 719 |
+
def add_constants_to_call_args(
|
| 720 |
+
call_args: Sequence[Any], cfg: Config
|
| 721 |
+
) -> tuple[Any, ...]:
|
| 722 |
+
"""
|
| 723 |
+
Add constant kwargs to the arg list.
|
| 724 |
+
"""
|
| 725 |
+
# Add args from the proper Triton signature.
|
| 726 |
+
new_call_args = []
|
| 727 |
+
call_arg_idx = 0
|
| 728 |
+
constants = triton_meta["constants"]
|
| 729 |
+
for arg_name in signature:
|
| 730 |
+
# Config kwargs are tracked separately.
|
| 731 |
+
if arg_name in cfg.kwargs:
|
| 732 |
+
continue
|
| 733 |
+
|
| 734 |
+
try:
|
| 735 |
+
new_arg = constants[arg_name]
|
| 736 |
+
except KeyError:
|
| 737 |
+
new_arg = call_args[call_arg_idx]
|
| 738 |
+
call_arg_idx += 1
|
| 739 |
+
new_call_args.append(new_arg)
|
| 740 |
+
|
| 741 |
+
# Add Inductor's extra call args to the end.
|
| 742 |
+
new_call_args.extend(call_args[call_arg_idx:])
|
| 743 |
+
|
| 744 |
+
return tuple(new_call_args)
|
| 745 |
+
|
| 746 |
+
kernel_config = tuner.compile_results[0].config
|
| 747 |
+
call_args = add_constants_to_call_args(call_args, kernel_config)
|
| 748 |
+
call_args, grid = tuner._interpret_args_grid(call_args, kernel_config)
|
| 749 |
+
call_kwargs = dict(zip(signature, call_args))
|
| 750 |
+
call_kwargs.update(kernel_config.kwargs)
|
| 751 |
+
|
| 752 |
+
# Replace all sympy.floor with FloorDiv
|
| 753 |
+
# _generate_sym_node does not support sympy.floor
|
| 754 |
+
grid = [
|
| 755 |
+
x.replace(sympy.floor, replace_floor_div)
|
| 756 |
+
if isinstance(x, sympy.Expr)
|
| 757 |
+
else x
|
| 758 |
+
for x in grid
|
| 759 |
+
]
|
| 760 |
+
wrapper_grid = [tuple(self._generate_sym_nodes(grid))]
|
| 761 |
+
call_kwargs = {
|
| 762 |
+
name: self._generate_sym_node(val) for name, val in call_kwargs.items()
|
| 763 |
+
}
|
| 764 |
+
|
| 765 |
+
# Store non-graphable kwargs in the side table.
|
| 766 |
+
(
|
| 767 |
+
call_kwargs,
|
| 768 |
+
constant_args_idx,
|
| 769 |
+
) = tracing_triton_hopifier_singleton.store_non_graphable_args(call_kwargs)
|
| 770 |
+
|
| 771 |
+
self.gm.graph.call_function(
|
| 772 |
+
triton_kernel_wrapper_mutation,
|
| 773 |
+
kwargs={
|
| 774 |
+
"kernel_idx": kernel.wrapped.kernel_idx,
|
| 775 |
+
"constant_args_idx": constant_args_idx,
|
| 776 |
+
"grid": wrapper_grid,
|
| 777 |
+
"tma_descriptor_metadata": {},
|
| 778 |
+
"kwargs": call_kwargs,
|
| 779 |
+
},
|
| 780 |
+
)
|
| 781 |
+
|
| 782 |
+
def _generate_extern_kernel_alloc(self, line: WrapperLine) -> None:
|
| 783 |
+
assert isinstance(line, ExternKernelAllocLine)
|
| 784 |
+
node = line.node
|
| 785 |
+
self._generate_extern_kernel_common(node, node)
|
| 786 |
+
|
| 787 |
+
def _generate_extern_kernel_out(
|
| 788 |
+
self,
|
| 789 |
+
line: WrapperLine,
|
| 790 |
+
) -> None:
|
| 791 |
+
assert isinstance(line, ExternKernelOutLine)
|
| 792 |
+
node = line.node
|
| 793 |
+
out_node = node.output_view if node.output_view else node
|
| 794 |
+
self._generate_extern_kernel_common(node, out_node)
|
| 795 |
+
|
| 796 |
+
def _generate_extern_kernel_common(
|
| 797 |
+
self, kernel: ir.ExternKernel, out_ir_node: ir.IRNode
|
| 798 |
+
) -> None:
|
| 799 |
+
"""
|
| 800 |
+
Generates FX IR from either ExternKernelAlloc or ExternKernelOut.
|
| 801 |
+
"""
|
| 802 |
+
|
| 803 |
+
# Get FX nodes corresponding to the call args.
|
| 804 |
+
assert ir.is_node_sequence(kernel.inputs)
|
| 805 |
+
tensor_nodes = tuple(self._generate_buffer(arg) for arg in kernel.inputs)
|
| 806 |
+
args = tensor_nodes + tuple(kernel.constant_args)
|
| 807 |
+
|
| 808 |
+
# Get the result buffer.
|
| 809 |
+
# Some kernels write to a pre-existing output tensor via the "out" kwarg.
|
| 810 |
+
kwargs = kernel.kwargs.copy()
|
| 811 |
+
result_buffer: Optional[str] = None
|
| 812 |
+
if isinstance(kernel, ir.ExternKernelOut):
|
| 813 |
+
kwargs["out"] = self.buffer_to_node[out_ir_node.codegen_reference()]
|
| 814 |
+
elif isinstance(kernel.layout, (ir.Layout, ir.MultiOutputLayout)):
|
| 815 |
+
result_buffer = kernel.get_name()
|
| 816 |
+
elif isinstance(kernel.layout, ir.NoneLayout):
|
| 817 |
+
pass
|
| 818 |
+
else:
|
| 819 |
+
raise NotImplementedError(f"Unrecognized output layout: {kernel.layout}")
|
| 820 |
+
|
| 821 |
+
fx_node = self.gm.graph.call_function(
|
| 822 |
+
kernel.op_overload, # type: ignore[arg-type]
|
| 823 |
+
args=args,
|
| 824 |
+
kwargs=kwargs,
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
# Assign the result to the given name.
|
| 828 |
+
if result_buffer:
|
| 829 |
+
assert "out" not in kwargs, (
|
| 830 |
+
f"Extern kernel '{kernel}' has both result and out kwarg. Expected only one."
|
| 831 |
+
)
|
| 832 |
+
fx_node.name = result_buffer
|
| 833 |
+
self.buffer_to_node[result_buffer] = fx_node
|
| 834 |
+
|
| 835 |
+
def _generate_kernel_call(self, line: WrapperLine) -> None:
|
| 836 |
+
assert isinstance(line, KernelCallLine)
|
| 837 |
+
if not line.triton:
|
| 838 |
+
raise NotImplementedError("FX conversion only supports Triton kernels.")
|
| 839 |
+
|
| 840 |
+
self._generate_triton_call(line)
|
| 841 |
+
|
| 842 |
+
def _generate_kernel_definition(self, line: WrapperLine) -> None:
|
| 843 |
+
assert isinstance(line, KernelDefinitionLine)
|
| 844 |
+
|
| 845 |
+
# Generate code for the kernel.
|
| 846 |
+
kernel_code = PythonWrapperCodegen._format_kernel_definition(
|
| 847 |
+
line.kernel_name, line.kernel_body, metadata=line.metadata
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
# Import the module and store the JIT kernel.
|
| 851 |
+
tuner = self._import_kernel(kernel_code, line.kernel_name)
|
| 852 |
+
wrapped = wrap_triton(tuner.fn)
|
| 853 |
+
self.kernels[line.kernel_name] = TritonKernel(tuner, wrapped)
|
| 854 |
+
|
| 855 |
+
def _generate_symbolic_call_arg(self, line: WrapperLine) -> None:
|
| 856 |
+
assert isinstance(line, SymbolicCallArgLine)
|
| 857 |
+
# Store the arg: expr mapping for later use.
|
| 858 |
+
arg = line.arg
|
| 859 |
+
|
| 860 |
+
inner_expr_proxy = self._sympy_interp(arg.inner_expr)
|
| 861 |
+
self.expr_to_proxy[arg.inner] = inner_expr_proxy
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/xpu/__init__.py
ADDED
|
File without changes
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from ..common import (
|
| 6 |
+
DeviceOpOverrides,
|
| 7 |
+
register_device_op_overrides,
|
| 8 |
+
TritonScratchWorkspace,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class XPUDeviceOpOverrides(DeviceOpOverrides):
|
| 13 |
+
def import_get_raw_stream_as(self, name: str) -> str:
|
| 14 |
+
return f"from torch._C import _xpu_getCurrentRawStream as {name}"
|
| 15 |
+
|
| 16 |
+
def set_device(self, device_idx: int) -> str:
|
| 17 |
+
return f"torch.xpu.set_device({device_idx})"
|
| 18 |
+
|
| 19 |
+
def synchronize(self) -> str:
|
| 20 |
+
return "torch.xpu.synchronize()"
|
| 21 |
+
|
| 22 |
+
def device_guard(self, device_idx: int) -> str:
|
| 23 |
+
return f"torch.xpu._DeviceGuard({device_idx})"
|
| 24 |
+
|
| 25 |
+
def cpp_device_guard(self) -> str:
|
| 26 |
+
return "at::DeviceGuard"
|
| 27 |
+
|
| 28 |
+
def cpp_aoti_device_guard(self) -> str:
|
| 29 |
+
return "AOTIXpuGuard"
|
| 30 |
+
|
| 31 |
+
def cpp_stream_guard(self) -> str:
|
| 32 |
+
return "at::xpu::XPUStreamGuard"
|
| 33 |
+
|
| 34 |
+
def cpp_aoti_stream_guard(self) -> str:
|
| 35 |
+
return "AOTIXpuStreamGuard"
|
| 36 |
+
|
| 37 |
+
def cpp_getStreamFromExternal(self) -> str:
|
| 38 |
+
return "at::xpu::getStreamFromExternal"
|
| 39 |
+
|
| 40 |
+
def kernel_header(self) -> str:
|
| 41 |
+
source_codes = """
|
| 42 |
+
#include <torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h>
|
| 43 |
+
"""
|
| 44 |
+
return source_codes
|
| 45 |
+
|
| 46 |
+
def kernel_driver(self) -> str:
|
| 47 |
+
return ""
|
| 48 |
+
|
| 49 |
+
def cpp_stream_type(self) -> str:
|
| 50 |
+
return "sycl::queue*"
|
| 51 |
+
|
| 52 |
+
def aoti_get_stream(self) -> str:
|
| 53 |
+
return "aoti_torch_get_current_xpu_stream"
|
| 54 |
+
|
| 55 |
+
def cpp_kernel_type(self) -> str:
|
| 56 |
+
return "std::unique_ptr<sycl::kernel>"
|
| 57 |
+
|
| 58 |
+
def cpp_device_ptr(self) -> str:
|
| 59 |
+
return "void *"
|
| 60 |
+
|
| 61 |
+
def cpp_scratch(
|
| 62 |
+
self, idx: int, workspace: TritonScratchWorkspace, prefix: Optional[str] = None
|
| 63 |
+
) -> Optional[tuple[list[str], str]]:
|
| 64 |
+
return [f"void *global_scratch_{idx} = 0;"], f"global_scratch_{idx}"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
register_device_op_overrides("xpu", XPUDeviceOpOverrides())
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comm_analysis.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import logging
|
| 3 |
+
import math
|
| 4 |
+
from enum import IntEnum
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
import sympy
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from . import ir
|
| 12 |
+
from .utils import get_dtype_size, snode_args_kwargs, sympy_product
|
| 13 |
+
from .virtualized import V
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
log = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class NCCL_COLL(IntEnum):
|
| 20 |
+
ALL_REDUCE = 0
|
| 21 |
+
ALL_GATHER = 1
|
| 22 |
+
REDUCE_SCATTER = 2
|
| 23 |
+
ALL_TO_ALL = 3
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class NVIDIA_GPU_TYPE(IntEnum):
|
| 27 |
+
VOLTA = 0
|
| 28 |
+
AMPERE = 1
|
| 29 |
+
HOPPER = 2
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@functools.lru_cache
|
| 33 |
+
def get_gpu_type() -> NVIDIA_GPU_TYPE:
|
| 34 |
+
gpu_info = torch.utils.collect_env.get_gpu_info(torch.utils.collect_env.run) or ""
|
| 35 |
+
if "V100" in gpu_info:
|
| 36 |
+
return NVIDIA_GPU_TYPE.VOLTA
|
| 37 |
+
elif "A100" in gpu_info:
|
| 38 |
+
return NVIDIA_GPU_TYPE.AMPERE
|
| 39 |
+
elif "H100" in gpu_info:
|
| 40 |
+
return NVIDIA_GPU_TYPE.HOPPER
|
| 41 |
+
else:
|
| 42 |
+
# for other gpu types, assume Ampere
|
| 43 |
+
return NVIDIA_GPU_TYPE.AMPERE
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_collective_type(node: ir.IRNode) -> NCCL_COLL:
|
| 47 |
+
if not isinstance(node, ir._CollectiveKernel):
|
| 48 |
+
raise ValueError(f"node is not a collective kernel: {node}")
|
| 49 |
+
|
| 50 |
+
kernel_name = node.python_kernel_name
|
| 51 |
+
assert kernel_name is not None
|
| 52 |
+
if "all_reduce" in kernel_name:
|
| 53 |
+
return NCCL_COLL.ALL_REDUCE
|
| 54 |
+
elif "all_gather" in kernel_name:
|
| 55 |
+
return NCCL_COLL.ALL_GATHER
|
| 56 |
+
elif "reduce_scatter" in kernel_name:
|
| 57 |
+
return NCCL_COLL.REDUCE_SCATTER
|
| 58 |
+
elif "torch.ops._dtensor.shard_dim_alltoall.default" in kernel_name:
|
| 59 |
+
return NCCL_COLL.ALL_TO_ALL
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(f"Unsupported collective kernel: {kernel_name}")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_collective_input_size_bytes(node: ir.IRNode) -> int:
|
| 65 |
+
sz_bytes = 0
|
| 66 |
+
for inp in node.inputs: # type: ignore[attr-defined]
|
| 67 |
+
numel = sympy_product(inp.layout.size)
|
| 68 |
+
if isinstance(numel, sympy.Integer):
|
| 69 |
+
# For ease of testing
|
| 70 |
+
numel = int(numel)
|
| 71 |
+
else:
|
| 72 |
+
numel = V.graph.sizevars.size_hint(numel, fallback=0)
|
| 73 |
+
sz_bytes += numel * get_dtype_size(inp.layout.dtype)
|
| 74 |
+
return sz_bytes
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def get_collective_group_size(node: ir.IRNode) -> int:
|
| 78 |
+
if isinstance(node, ir._CollectiveKernel) and not isinstance(node, ir._WaitKernel):
|
| 79 |
+
from torch.distributed.distributed_c10d import _get_group_size_by_name
|
| 80 |
+
|
| 81 |
+
return _get_group_size_by_name(node.constant_args[-1])
|
| 82 |
+
else:
|
| 83 |
+
raise TypeError(f"Unsupported collective type: {node}")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
####################################################################################################################
|
| 87 |
+
# The following code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc #
|
| 88 |
+
####################################################################################################################
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class NCCL_HW(IntEnum):
|
| 92 |
+
NVLINK = 0
|
| 93 |
+
PCI = 1
|
| 94 |
+
NET = 2
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class NCCL_ALGO(IntEnum):
|
| 98 |
+
TREE = 0
|
| 99 |
+
RING = 1
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class NCCL_PROTO(IntEnum):
|
| 103 |
+
# The ordering and enum values here matches original in
|
| 104 |
+
# https://github.com/NVIDIA/nccl/blob/0b083e52096c387bad7a5c5c65b26a9dca54de8c/src/include/devcomm.h#L28
|
| 105 |
+
# For difference between these protocols, see https://github.com/NVIDIA/nccl/issues/281#issuecomment-571816990
|
| 106 |
+
LL = 0 # Low-latency
|
| 107 |
+
# LL128 = 1 # Low-latency 128-byte
|
| 108 |
+
# SIMPLE = 2
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# Latencies in us
|
| 112 |
+
# len(NCCL_ALGO) x len(NCCL_PROTO)
|
| 113 |
+
# NOTE: use array instead of tensor to prevent incompatibility with fake mode
|
| 114 |
+
baseLat = [
|
| 115 |
+
# Tree
|
| 116 |
+
[
|
| 117 |
+
6.8, # LL
|
| 118 |
+
],
|
| 119 |
+
# Ring
|
| 120 |
+
[
|
| 121 |
+
6.6, # LL
|
| 122 |
+
],
|
| 123 |
+
]
|
| 124 |
+
|
| 125 |
+
# Latencies in us
|
| 126 |
+
# len(NCCL_HW) x len(NCCL_ALGO) x len(NCCL_PROTO)
|
| 127 |
+
hwLat = [
|
| 128 |
+
# NVLINK
|
| 129 |
+
[
|
| 130 |
+
[0.6], # Tree (LL)
|
| 131 |
+
[0.6], # Ring (LL)
|
| 132 |
+
],
|
| 133 |
+
# PCI
|
| 134 |
+
[
|
| 135 |
+
[1.0], # Tree (LL)
|
| 136 |
+
[1.0], # Ring (LL)
|
| 137 |
+
],
|
| 138 |
+
# NET
|
| 139 |
+
[
|
| 140 |
+
[5.0], # Tree (LL)
|
| 141 |
+
[2.7], # Ring (LL)
|
| 142 |
+
],
|
| 143 |
+
]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# LL128 max BW per channel
|
| 147 |
+
llMaxBws = [
|
| 148 |
+
# Volta-N1/Intel-N2/Intel-N4
|
| 149 |
+
[
|
| 150 |
+
39.0,
|
| 151 |
+
39.0,
|
| 152 |
+
20.4,
|
| 153 |
+
],
|
| 154 |
+
# Ampere-N1/AMD-N2/AMD-N4
|
| 155 |
+
[
|
| 156 |
+
87.7,
|
| 157 |
+
22.5, # avg of ring & tree
|
| 158 |
+
19.0,
|
| 159 |
+
],
|
| 160 |
+
# Hopper-N1/AMD-N2/AMD-N4
|
| 161 |
+
[
|
| 162 |
+
87.7,
|
| 163 |
+
22.5, # avg of ring & tree
|
| 164 |
+
19.0,
|
| 165 |
+
],
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def estimate_nccl_collective_runtime_nccl_estimator(snode) -> Optional[float]: # type: ignore[no-untyped-def]
|
| 170 |
+
kernel = snode.node
|
| 171 |
+
assert kernel is not None
|
| 172 |
+
py_kernel_name = getattr(kernel, "python_kernel_name", "")
|
| 173 |
+
if not ("all_gather" in py_kernel_name or "reduce_scatter" in py_kernel_name):
|
| 174 |
+
# NCCL of version 2.27 sometimes unrecoverably fail for all_to_all, all_reduce
|
| 175 |
+
return None
|
| 176 |
+
|
| 177 |
+
from torch.distributed.distributed_c10d import _resolve_process_group
|
| 178 |
+
|
| 179 |
+
pg_name = kernel.constant_args[-1] # type: ignore[attr-defined]
|
| 180 |
+
pg = _resolve_process_group(pg_name)
|
| 181 |
+
rank: int = torch.distributed.get_rank(pg)
|
| 182 |
+
# TODO(ivankobzarev): Figure out how we can use time estimations,
|
| 183 |
+
# without cuda allocations.
|
| 184 |
+
device = torch.device(f"cuda:{rank}")
|
| 185 |
+
|
| 186 |
+
fn = eval(py_kernel_name)
|
| 187 |
+
args, kwargs = snode_args_kwargs(snode)
|
| 188 |
+
|
| 189 |
+
# TODO(ivankobzarev): fix out variants snode_args_kwargs
|
| 190 |
+
if "all_gather_into_tensor_out" in py_kernel_name:
|
| 191 |
+
args = args[1:] + args[0]
|
| 192 |
+
|
| 193 |
+
try:
|
| 194 |
+
with torch.distributed._time_estimator(
|
| 195 |
+
group=pg, device=device
|
| 196 |
+
) as time_estimator:
|
| 197 |
+
w = fn(*args, **kwargs)
|
| 198 |
+
torch.ops._c10d_functional.wait_tensor.default(w)
|
| 199 |
+
except Exception as e:
|
| 200 |
+
# NCCL estimator can fail
|
| 201 |
+
log.info(e)
|
| 202 |
+
return None
|
| 203 |
+
|
| 204 |
+
est_time_us = time_estimator.estimated_time
|
| 205 |
+
# -1000 constant is NCCL return in case of error during estimations.
|
| 206 |
+
# Observed it for all_to_all estimations.
|
| 207 |
+
if est_time_us < 0:
|
| 208 |
+
return None
|
| 209 |
+
est_time_ms = est_time_us / 1e3
|
| 210 |
+
return est_time_ms
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def estimate_nccl_collective_runtime(node: ir.IRNode) -> float:
|
| 214 |
+
"""
|
| 215 |
+
Returns estimated NCCL collective runtime in milliseconds (ms).
|
| 216 |
+
|
| 217 |
+
The following heuristics are copied from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc.
|
| 218 |
+
We aim to estimate the runtime as accurately as possible.
|
| 219 |
+
|
| 220 |
+
Assumptions:
|
| 221 |
+
- only ring algorithm (NCCL_ALGO_RING) is used
|
| 222 |
+
- only Low-Latency protocol (NCCL_PROTO_LL) is used, i.e. Simple or LL128 is not used
|
| 223 |
+
- 8 gpus per node # TODO: Need to find a way to get accurate "gpus per node" and "# nodes" info.
|
| 224 |
+
- collective is one of: allreduce, reducescatter, allgather
|
| 225 |
+
"""
|
| 226 |
+
tensor_storage_size_bytes = get_collective_input_size_bytes(node)
|
| 227 |
+
# Convert bytes to GB
|
| 228 |
+
tensor_storage_size_GB = tensor_storage_size_bytes / 1024 / 1024 / 1024
|
| 229 |
+
|
| 230 |
+
# Currently assumes each node has 8 gpus. And when >1 node is used, assumes each node uses all 8 gpus.
|
| 231 |
+
# TODO: Need to find a way to get accurate "gpus per node" and "# nodes" info.
|
| 232 |
+
num_gpus_per_node = 8
|
| 233 |
+
group_size = get_collective_group_size(node)
|
| 234 |
+
nNodes = math.ceil(group_size / num_gpus_per_node)
|
| 235 |
+
nRanks = group_size # this is total # of gpus globally that participate in this collective op
|
| 236 |
+
|
| 237 |
+
if nRanks <= 1:
|
| 238 |
+
return 0
|
| 239 |
+
|
| 240 |
+
# Assumes ring algorithm
|
| 241 |
+
nccl_algo = NCCL_ALGO.RING
|
| 242 |
+
nccl_proto = NCCL_PROTO.LL
|
| 243 |
+
coll = get_collective_type(node)
|
| 244 |
+
|
| 245 |
+
# =============== bandwidth computation ===============
|
| 246 |
+
# First compute bandwidth in GB/s; then at the end, convert it to GB/ns
|
| 247 |
+
|
| 248 |
+
bwIntra = torch._inductor.config.intra_node_bw
|
| 249 |
+
bwInter = torch._inductor.config.inter_node_bw
|
| 250 |
+
|
| 251 |
+
compCapIndex = get_gpu_type()
|
| 252 |
+
index2 = nNodes - 1 if nNodes <= 2 else 2
|
| 253 |
+
# LL: for single node, we look at GPU type; for multi-node, we look at CPU type
|
| 254 |
+
index1 = compCapIndex if nNodes == 1 else 0
|
| 255 |
+
llMaxBw = llMaxBws[index1][index2]
|
| 256 |
+
|
| 257 |
+
# NOTE: each step of ring algorithm is synchronized,
|
| 258 |
+
# and is bottlenecked by the slowest link which is the inter-node interconnect.
|
| 259 |
+
# hence when nNodes >= 2, bw is inter-node bandwidth.
|
| 260 |
+
# NOTE: the original code in https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc
|
| 261 |
+
# have this as `if nNodes <= 2` which seems wrong. Corrected it here.
|
| 262 |
+
bw = bwIntra if nNodes == 1 else bwInter
|
| 263 |
+
nChannels = 2 # Assume # channels is 2
|
| 264 |
+
busBw = nChannels * bw
|
| 265 |
+
|
| 266 |
+
# Various model refinements
|
| 267 |
+
busBw = min(
|
| 268 |
+
llMaxBw,
|
| 269 |
+
busBw
|
| 270 |
+
* (1.0 / 4.0 if (nNodes > 1 or coll == NCCL_COLL.ALL_REDUCE) else 1.0 / 3.0),
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
if coll == NCCL_COLL.ALL_REDUCE:
|
| 274 |
+
nsteps = 2 * (nRanks - 1)
|
| 275 |
+
elif coll == NCCL_COLL.ALL_TO_ALL:
|
| 276 |
+
nsteps = 2 * (nRanks - 1)
|
| 277 |
+
elif coll in (NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_GATHER):
|
| 278 |
+
nsteps = nRanks - 1
|
| 279 |
+
|
| 280 |
+
# Convert bus BW to algorithm BW (tensor bytes / algoBW = actual execution time)
|
| 281 |
+
ratio = (1.0 * nRanks) / nsteps # type: ignore[possibly-undefined]
|
| 282 |
+
bandwidth = busBw * ratio
|
| 283 |
+
# Convert GB/s to GB/ns
|
| 284 |
+
bandwidth_GB_per_ns = bandwidth / 1e9
|
| 285 |
+
|
| 286 |
+
# =============== latency computation ===============
|
| 287 |
+
intraHw = NCCL_HW.NVLINK
|
| 288 |
+
|
| 289 |
+
if coll == NCCL_COLL.ALL_REDUCE:
|
| 290 |
+
if nNodes > 1:
|
| 291 |
+
nInterSteps = 2 * nNodes
|
| 292 |
+
else:
|
| 293 |
+
nInterSteps = 0
|
| 294 |
+
elif coll in (NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_GATHER, NCCL_COLL.ALL_TO_ALL):
|
| 295 |
+
nInterSteps = nNodes - 1
|
| 296 |
+
|
| 297 |
+
# First compute latency in us; then at the end, convert it to ns
|
| 298 |
+
latency = baseLat[nccl_algo][nccl_proto]
|
| 299 |
+
intraLat = hwLat[intraHw][nccl_algo][nccl_proto]
|
| 300 |
+
interLat = hwLat[NCCL_HW.NET][nccl_algo][nccl_proto]
|
| 301 |
+
|
| 302 |
+
# Inter-node rings still have to launch nsteps * net overhead.
|
| 303 |
+
netOverhead = 0.0
|
| 304 |
+
if nNodes > 1:
|
| 305 |
+
netOverhead = 1.0 # getNetOverhead(comm);
|
| 306 |
+
intraLat = max(intraLat, netOverhead)
|
| 307 |
+
latency += (nsteps - nInterSteps) * intraLat + nInterSteps * interLat # type: ignore[possibly-undefined]
|
| 308 |
+
# Convert us to ns
|
| 309 |
+
latency_ns = latency * 1e3
|
| 310 |
+
|
| 311 |
+
# =============== final result ===============
|
| 312 |
+
transport_ns = tensor_storage_size_GB / bandwidth_GB_per_ns
|
| 313 |
+
ns = transport_ns + latency_ns
|
| 314 |
+
ms = ns / 1e6
|
| 315 |
+
return ms
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
################################################################################################################
|
| 319 |
+
# The above code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc #
|
| 320 |
+
################################################################################################################
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comm_lowering.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import logging
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.utils._pytree as pytree
|
| 6 |
+
from torch._inductor.utils import is_symbolic
|
| 7 |
+
from torch.utils._ordered_set import OrderedSet
|
| 8 |
+
|
| 9 |
+
from . import config, ir
|
| 10 |
+
from .virtualized import V
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
log = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# NOTE [lowering-time collective optimization]
|
| 17 |
+
#
|
| 18 |
+
# In collective communication libraries such as NCCL, every rank maintains
|
| 19 |
+
# communication buffers that are remotely accessible by some peers. Depending
|
| 20 |
+
# on the underlying transport, remote accessibility may be established via
|
| 21 |
+
# mechanisms such as ib_reg_mr, CUDA P2P, or CUDA multicast. Typically, these
|
| 22 |
+
# buffers are private to the communication library by default, and
|
| 23 |
+
# communication ops copy user data in and out of these buffers.
|
| 24 |
+
#
|
| 25 |
+
# To prevent these copies, an optimization commonly known as "user buffer
|
| 26 |
+
# registration" can be employed. This allows direct establishment of remote
|
| 27 |
+
# accessibility on user buffers, eliminating the need for copying. However,
|
| 28 |
+
# this optimization introduces stringent usage requirements, which are
|
| 29 |
+
# typically hard to satisfy without being intrusive to the user code:
|
| 30 |
+
#
|
| 31 |
+
# - Establishing remote accessibility is expensive and often done ahead of
|
| 32 |
+
# time. In such implementations, all ranks must agree on the set of allocations
|
| 33 |
+
# used for every collective op. Failing to meet this requirement can
|
| 34 |
+
# lead to runtime errors or even silent correctness issues.
|
| 35 |
+
# - Even if the collective communication library supports gracefully falling
|
| 36 |
+
# back to "unregistered" implementations, the fallback mechanism would nullify
|
| 37 |
+
# the optimization.
|
| 38 |
+
# - Some communication mechanisms impose stricter requirements than others. For
|
| 39 |
+
# example, CUDA's multicast + multi-mem instructions require all ranks to agree
|
| 40 |
+
# not only on the allocations used for every collective but also on the offsets
|
| 41 |
+
# within these allocations.
|
| 42 |
+
#
|
| 43 |
+
# To support all different mechanisms with optimal results, we aim to satisfy
|
| 44 |
+
# the strictest requirement for this family of optimizations - we ensures that
|
| 45 |
+
# every collective op invocation is guaranteed to operate on the same
|
| 46 |
+
# allocation, at the same offset, in every iteration.
|
| 47 |
+
#
|
| 48 |
+
# For eligible collective ops, we identify communication buffers at lowering
|
| 49 |
+
# time and optionally choose to lower the op to a different kernel
|
| 50 |
+
# (ommunication libraries like NCCL handle both registered and non-registered
|
| 51 |
+
# buffers transparently within the same op, though some may require different
|
| 52 |
+
# ops for different cases). Later, the codegen will perform "persistent
|
| 53 |
+
# allocation" to satisfy the aforementioned constraints, and optionally,
|
| 54 |
+
# perform buffer planning to optimize overall memory usage.
|
| 55 |
+
def can_realize_as_comm_buffer(
|
| 56 |
+
x: ir.TensorBox, comm_buffer_type: ir.CommBufferType
|
| 57 |
+
) -> bool:
|
| 58 |
+
"""
|
| 59 |
+
Check if an input can be realized as a comm buffer of the specified
|
| 60 |
+
`comm_buffer_type`.
|
| 61 |
+
"""
|
| 62 |
+
data = _get_data(x)
|
| 63 |
+
|
| 64 |
+
if isinstance(data, ir.Loops):
|
| 65 |
+
return True
|
| 66 |
+
|
| 67 |
+
layout = data.get_output_spec()
|
| 68 |
+
if isinstance(layout, ir.CommBufferLayout):
|
| 69 |
+
return True
|
| 70 |
+
|
| 71 |
+
if isinstance(layout, ir.FlexibleLayout) and not is_symbolic(data.get_numel()):
|
| 72 |
+
return True
|
| 73 |
+
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def realize_as_comm_buffer(
|
| 78 |
+
x: ir.TensorBox, comm_buffer_type: ir.CommBufferType, group_name: str
|
| 79 |
+
) -> None:
|
| 80 |
+
"""
|
| 81 |
+
Realize an input as a comm buffer of the specified `comm_buffer_type`.
|
| 82 |
+
|
| 83 |
+
Specifically, this realizes the underlying buffer if it's still unrealized
|
| 84 |
+
and changes the layout of the buffer to `ir.CommBufferLayout`.
|
| 85 |
+
"""
|
| 86 |
+
x.realize()
|
| 87 |
+
buffer = _get_data(x)
|
| 88 |
+
assert isinstance(buffer, ir.Buffer)
|
| 89 |
+
|
| 90 |
+
layout = buffer.get_output_spec()
|
| 91 |
+
if isinstance(layout, ir.CommBufferLayout):
|
| 92 |
+
return
|
| 93 |
+
|
| 94 |
+
if not isinstance(layout, ir.FlexibleLayout):
|
| 95 |
+
raise AssertionError(
|
| 96 |
+
"A buffer can only be realized as a comm buffer if it "
|
| 97 |
+
f"has `FlexibleLayout` (got {layout})."
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
if is_symbolic(buffer.get_numel()):
|
| 101 |
+
raise AssertionError(
|
| 102 |
+
"A buffer with symbolic shape cannot be converted to "
|
| 103 |
+
f"a comm buffer (got {layout})."
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
buffer.layout = ir.CommBufferLayout(
|
| 107 |
+
layout=layout,
|
| 108 |
+
comm_buffer_type=comm_buffer_type,
|
| 109 |
+
group_name=group_name,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _get_data(x: ir.TensorBox) -> ir.IRNode:
|
| 114 |
+
if isinstance(x.data, ir.BaseView):
|
| 115 |
+
# TensorBox -> *View -> StorageBox -> IRNode
|
| 116 |
+
node = x.data.unwrap_view()
|
| 117 |
+
assert isinstance(node, (ir.BaseView, ir.MutableBox))
|
| 118 |
+
return node.data
|
| 119 |
+
elif isinstance(x.data, ir.StorageBox):
|
| 120 |
+
# TensorBox -> StorageBox -> IRNode
|
| 121 |
+
return x.data.data
|
| 122 |
+
else:
|
| 123 |
+
raise AssertionError(
|
| 124 |
+
"Expect the data attr of a `TensorBox` to be either "
|
| 125 |
+
f"an `ir.BaseView` or `ir.StorageBox` (got {x.data})."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
_bufs_to_skip_wait = OrderedSet[tuple[int, str]]()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def mark_as_skip_wait(x: ir.IRNode) -> None:
|
| 133 |
+
"""
|
| 134 |
+
If a non-blocking collective is lowered as a blocking collective, the wait
|
| 135 |
+
node in the original graph becomes useless and we can skip the lowering it.
|
| 136 |
+
"""
|
| 137 |
+
_bufs_to_skip_wait.add((id(V.graph), x.get_name()))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def should_skip_wait(x: ir.IRNode) -> bool:
|
| 141 |
+
return (id(V.graph), x.get_name()) in _bufs_to_skip_wait
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _should_lower_as_one_shot_all_reduce(
|
| 145 |
+
inp: ir.TensorBox, reduce_op: str, group_name: str
|
| 146 |
+
):
|
| 147 |
+
from torch.distributed._symmetric_memory import is_symm_mem_enabled_for_group
|
| 148 |
+
|
| 149 |
+
inp_size = inp.get_numel() * inp.get_dtype().itemsize
|
| 150 |
+
return (
|
| 151 |
+
config._collective.auto_select
|
| 152 |
+
and is_symm_mem_enabled_for_group(group_name)
|
| 153 |
+
and can_realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM)
|
| 154 |
+
and reduce_op in ("sum",)
|
| 155 |
+
and inp_size <= config._collective.one_shot_all_reduce_threshold_bytes
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _one_shot_all_reduce(inp: ir.TensorBox, reduce_op, group_name):
|
| 160 |
+
realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM, group_name)
|
| 161 |
+
return pytree.tree_map(
|
| 162 |
+
ir.TensorBox.create,
|
| 163 |
+
ir.FallbackKernel.create(
|
| 164 |
+
torch.ops.symm_mem.one_shot_all_reduce.default,
|
| 165 |
+
inp,
|
| 166 |
+
reduce_op,
|
| 167 |
+
group_name,
|
| 168 |
+
),
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def register_comm_lowerings():
|
| 173 |
+
try:
|
| 174 |
+
torch.ops._c10d_functional.all_reduce
|
| 175 |
+
except AttributeError:
|
| 176 |
+
log.info(
|
| 177 |
+
"Inductor support for distributed collectives depends on building "
|
| 178 |
+
"torch.distributed"
|
| 179 |
+
)
|
| 180 |
+
return
|
| 181 |
+
|
| 182 |
+
from .lowering import (
|
| 183 |
+
add_layout_constraint,
|
| 184 |
+
clone,
|
| 185 |
+
constrain_to_fx_strides,
|
| 186 |
+
copy_,
|
| 187 |
+
register_lowering,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
def register_comm_lowering(fn):
|
| 191 |
+
add_layout_constraint(fn, constrain_to_fx_strides)
|
| 192 |
+
return register_lowering(fn)
|
| 193 |
+
|
| 194 |
+
c10d = torch.ops._c10d_functional
|
| 195 |
+
|
| 196 |
+
@register_comm_lowering(c10d.all_reduce) # type: ignore[misc]
|
| 197 |
+
def _all_reduce(inp: ir.TensorBox, reduce_op: str, group_name: str) -> ir.TensorBox:
|
| 198 |
+
if _should_lower_as_one_shot_all_reduce(inp, reduce_op, group_name):
|
| 199 |
+
return _one_shot_all_reduce(inp, reduce_op, group_name)
|
| 200 |
+
|
| 201 |
+
# Lower as c10d.all_reduce_
|
| 202 |
+
inp = clone(inp)
|
| 203 |
+
if config.reorder_for_compute_comm_overlap:
|
| 204 |
+
# The horizontal fusion of this clone often severely delays the
|
| 205 |
+
# scheduling of the all_reduce_ node. Horizontally fusing this
|
| 206 |
+
# clone can almost never out-perform scheduling the all_reduce_
|
| 207 |
+
# earlier. Also in most cases, this clone is eliminated via
|
| 208 |
+
# in-place reuse. Therefore, we tell the scheduler to not fuse it.
|
| 209 |
+
inp.realize()
|
| 210 |
+
V.graph.no_fuse_buffer_names.add(inp.get_name())
|
| 211 |
+
inp = ir.ExternKernel.require_contiguous(inp)
|
| 212 |
+
# Because we are lowering as inplace c10d.all_reduce_, we should generate
|
| 213 |
+
# _AllReduce_Kernel instead of _AllReduceKernel.
|
| 214 |
+
ir._AllReduce_Kernel.create_inplace(
|
| 215 |
+
c10d.all_reduce_.default,
|
| 216 |
+
inp, # type: ignore[arg-type]
|
| 217 |
+
reduce_op,
|
| 218 |
+
group_name, # type: ignore[arg-type]
|
| 219 |
+
)
|
| 220 |
+
return inp # type: ignore[return-value]
|
| 221 |
+
|
| 222 |
+
@register_comm_lowering(c10d.all_reduce_) # type: ignore[misc]
|
| 223 |
+
def _all_reduce_(
|
| 224 |
+
inp: ir.TensorBox, reduce_op: str, group_name: str
|
| 225 |
+
) -> ir.TensorBox:
|
| 226 |
+
if _should_lower_as_one_shot_all_reduce(inp, reduce_op, group_name):
|
| 227 |
+
ret = copy_(
|
| 228 |
+
inp,
|
| 229 |
+
_one_shot_all_reduce(inp, reduce_op, group_name),
|
| 230 |
+
)
|
| 231 |
+
mark_as_skip_wait(ret)
|
| 232 |
+
return inp
|
| 233 |
+
|
| 234 |
+
# Lower as c10d.all_reduce_
|
| 235 |
+
inp = ir.ExternKernel.require_contiguous(inp)
|
| 236 |
+
ir._AllReduce_Kernel.create_inplace(
|
| 237 |
+
c10d.all_reduce_.default,
|
| 238 |
+
inp, # type: ignore[arg-type]
|
| 239 |
+
reduce_op,
|
| 240 |
+
group_name, # type: ignore[arg-type]
|
| 241 |
+
)
|
| 242 |
+
return inp # type: ignore[return-value]
|
| 243 |
+
|
| 244 |
+
@register_comm_lowering(c10d.all_reduce_coalesced)
|
| 245 |
+
def _all_reduce_coalesced(inputs, reduce_op, group_name):
|
| 246 |
+
inputs = [clone(inp) for inp in inputs]
|
| 247 |
+
ir._CollectiveKernel.create_inplace(
|
| 248 |
+
c10d.all_reduce_coalesced_.default,
|
| 249 |
+
inputs,
|
| 250 |
+
reduce_op,
|
| 251 |
+
group_name,
|
| 252 |
+
)
|
| 253 |
+
return inputs
|
| 254 |
+
|
| 255 |
+
@register_comm_lowering(c10d.all_reduce_coalesced_)
|
| 256 |
+
def _all_reduce_coalesced_(inputs, reduce_op, group_name):
|
| 257 |
+
ir._CollectiveKernel.create_inplace(
|
| 258 |
+
c10d.all_reduce_coalesced_.default,
|
| 259 |
+
inputs,
|
| 260 |
+
reduce_op,
|
| 261 |
+
group_name,
|
| 262 |
+
)
|
| 263 |
+
return inputs
|
| 264 |
+
|
| 265 |
+
def _create_out_of_place(kernel, inputs, *args) -> ir.IRNode:
|
| 266 |
+
node = ir._CollectiveKernel.create_out_of_place(kernel, inputs, *args)
|
| 267 |
+
assert isinstance(node, ir.IRNode)
|
| 268 |
+
return ir.TensorBox.create(node)
|
| 269 |
+
|
| 270 |
+
@register_comm_lowering(c10d.all_gather_into_tensor)
|
| 271 |
+
def _all_gather_into_tensor(inp, group_size, group_name):
|
| 272 |
+
return _create_out_of_place(
|
| 273 |
+
c10d.all_gather_into_tensor.default,
|
| 274 |
+
inp,
|
| 275 |
+
group_size,
|
| 276 |
+
group_name,
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
@register_comm_lowering(c10d.all_gather_into_tensor_coalesced)
|
| 280 |
+
def _all_gather_into_tensor_coalesced(inputs, group_size, group_name):
|
| 281 |
+
return pytree.tree_map(
|
| 282 |
+
ir.TensorBox.create,
|
| 283 |
+
ir._CollectiveKernel.create_out_of_place(
|
| 284 |
+
c10d.all_gather_into_tensor_coalesced.default,
|
| 285 |
+
inputs,
|
| 286 |
+
group_size,
|
| 287 |
+
group_name,
|
| 288 |
+
),
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
@register_comm_lowering(c10d.all_gather_into_tensor_out)
|
| 292 |
+
def _all_gather_into_tensor_out(inp, group_size, group_name, *, out):
|
| 293 |
+
ir._CollectiveKernel.create_inplace(
|
| 294 |
+
c10d.all_gather_into_tensor_out.default,
|
| 295 |
+
inp,
|
| 296 |
+
group_size,
|
| 297 |
+
group_name,
|
| 298 |
+
out=out,
|
| 299 |
+
)
|
| 300 |
+
return out
|
| 301 |
+
|
| 302 |
+
@register_comm_lowering(c10d.reduce_scatter_tensor)
|
| 303 |
+
def _reduce_scatter_tensor(inp, reduce_op, group_size, group_name):
|
| 304 |
+
return _create_out_of_place(
|
| 305 |
+
c10d.reduce_scatter_tensor.default,
|
| 306 |
+
inp,
|
| 307 |
+
reduce_op,
|
| 308 |
+
group_size,
|
| 309 |
+
group_name,
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
@register_comm_lowering(c10d.reduce_scatter_tensor_coalesced)
|
| 313 |
+
def _reduce_scatter_tensor_coalesced(inputs, reduce_op, group_size, group_name):
|
| 314 |
+
return pytree.tree_map(
|
| 315 |
+
ir.TensorBox.create,
|
| 316 |
+
ir._CollectiveKernel.create_out_of_place(
|
| 317 |
+
c10d.reduce_scatter_tensor_coalesced.default,
|
| 318 |
+
inputs,
|
| 319 |
+
reduce_op,
|
| 320 |
+
group_size,
|
| 321 |
+
group_name,
|
| 322 |
+
),
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
@register_comm_lowering(c10d.all_to_all_single)
|
| 326 |
+
def _all_to_all_single(inp, output_split_sizes, input_split_sizes, group_name):
|
| 327 |
+
return _create_out_of_place(
|
| 328 |
+
c10d.all_to_all_single.default,
|
| 329 |
+
inp,
|
| 330 |
+
output_split_sizes,
|
| 331 |
+
input_split_sizes,
|
| 332 |
+
group_name,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@register_comm_lowering(c10d.broadcast)
|
| 336 |
+
def _broadcast(inp, src, group_name):
|
| 337 |
+
inp = clone(inp)
|
| 338 |
+
ir._CollectiveKernel.create_inplace(
|
| 339 |
+
c10d.broadcast_.default, inp, src, group_name
|
| 340 |
+
)
|
| 341 |
+
return inp
|
| 342 |
+
|
| 343 |
+
@register_comm_lowering(c10d.broadcast_)
|
| 344 |
+
def _broadcast_(inp, src, group_name):
|
| 345 |
+
ir._CollectiveKernel.create_inplace(
|
| 346 |
+
c10d.broadcast_.default, inp, src, group_name
|
| 347 |
+
)
|
| 348 |
+
return inp
|
| 349 |
+
|
| 350 |
+
@register_comm_lowering(torch.ops._dtensor.shard_dim_alltoall)
|
| 351 |
+
def _shard_dim_alltoall(inp, gather_dim, shard_dim, group_name):
|
| 352 |
+
return _create_out_of_place(
|
| 353 |
+
torch.ops._dtensor.shard_dim_alltoall.default,
|
| 354 |
+
inp,
|
| 355 |
+
gather_dim,
|
| 356 |
+
shard_dim,
|
| 357 |
+
group_name,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
@register_comm_lowering(c10d.wait_tensor)
|
| 361 |
+
def _wait_tensor(inp):
|
| 362 |
+
if should_skip_wait(inp):
|
| 363 |
+
return inp
|
| 364 |
+
|
| 365 |
+
ir._WaitKernel.create_wait(c10d.wait_tensor.default, inp)
|
| 366 |
+
return inp
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comms.py
ADDED
|
@@ -0,0 +1,1859 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# pyre-strict
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import heapq
|
| 6 |
+
import importlib
|
| 7 |
+
import itertools
|
| 8 |
+
import logging
|
| 9 |
+
import operator
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
from torch._logging import trace_structured
|
| 18 |
+
from torch.multiprocessing.reductions import StorageWeakRef
|
| 19 |
+
from torch.utils._ordered_set import OrderedSet
|
| 20 |
+
|
| 21 |
+
from . import config, ir
|
| 22 |
+
from .dependencies import WeakDep
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if TYPE_CHECKING:
|
| 26 |
+
from .ir import IRNode, Operation
|
| 27 |
+
from .scheduler import SchedulerBuffer
|
| 28 |
+
|
| 29 |
+
from .memory import (
|
| 30 |
+
estimate_peak_memory,
|
| 31 |
+
estimate_peak_memory_allocfree,
|
| 32 |
+
FreeableInputBuffer,
|
| 33 |
+
get_freeable_input_buf,
|
| 34 |
+
SNodeMemory,
|
| 35 |
+
)
|
| 36 |
+
from .utils import (
|
| 37 |
+
contains_collective,
|
| 38 |
+
contains_wait,
|
| 39 |
+
find_recursive_deps_of_node,
|
| 40 |
+
find_recursive_users_of_node,
|
| 41 |
+
is_collective,
|
| 42 |
+
is_fallback_op,
|
| 43 |
+
is_wait,
|
| 44 |
+
)
|
| 45 |
+
from .virtualized import V
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
log = logging.getLogger(__name__)
|
| 49 |
+
overlap_log = torch._logging.getArtifactLogger(__name__, "overlap")
|
| 50 |
+
|
| 51 |
+
if TYPE_CHECKING:
|
| 52 |
+
from torch._inductor.scheduler import BaseSchedulerNode
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def align_runtime_estimations_across_all_distributed_ranks(
|
| 56 |
+
snodes: list[BaseSchedulerNode],
|
| 57 |
+
):
|
| 58 |
+
runtime_estimations = {}
|
| 59 |
+
for snode in snodes:
|
| 60 |
+
runtime_estimations[snode] = snode.get_estimated_runtime()
|
| 61 |
+
import torch.distributed as dist
|
| 62 |
+
from torch.distributed.distributed_c10d import _get_default_group
|
| 63 |
+
|
| 64 |
+
world_size = dist.get_world_size()
|
| 65 |
+
pg = _get_default_group()
|
| 66 |
+
gathered_runtime_estimations: list[list[float]] = [[] for _ in range(world_size)]
|
| 67 |
+
dist.all_gather_object(
|
| 68 |
+
gathered_runtime_estimations, list(runtime_estimations.values()), pg
|
| 69 |
+
)
|
| 70 |
+
median_runtime_estimations = torch.median(
|
| 71 |
+
torch.tensor(gathered_runtime_estimations), dim=0
|
| 72 |
+
).values.tolist()
|
| 73 |
+
for i in range(len(snodes)):
|
| 74 |
+
snodes[i].override_estimated_runtime = median_runtime_estimations[i]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def sink_waits(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]:
|
| 78 |
+
"""
|
| 79 |
+
Greedily schedules waits as late as possible.
|
| 80 |
+
"""
|
| 81 |
+
return _schedule_for_comm(
|
| 82 |
+
snodes, raise_comms=False, sink_waits=True, reorder_for_overlap=False
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def raise_comms(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]:
|
| 87 |
+
"""
|
| 88 |
+
Greedily schedules comms as early as possible.
|
| 89 |
+
"""
|
| 90 |
+
return _schedule_for_comm(
|
| 91 |
+
snodes, raise_comms=True, sink_waits=False, reorder_for_overlap=False
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def reorder_compute_for_overlap(
|
| 96 |
+
snodes: list[BaseSchedulerNode],
|
| 97 |
+
) -> list[BaseSchedulerNode]:
|
| 98 |
+
"""
|
| 99 |
+
This achieves the following overall scheduling procedure:
|
| 100 |
+
Step 1: Given that we've currently scheduled comm N, we now schedule all compute nodes
|
| 101 |
+
that are required for comm N + 1 but do not depend on comm N, to run at the same time with comm N.
|
| 102 |
+
Step 2: If all those compute nodes are sufficient to overlap comm N, we're done.
|
| 103 |
+
Otherwise, we now need to look elsewhere to find compute that overlaps with comm N.
|
| 104 |
+
We prioritize compute nodes that are needed sooner.
|
| 105 |
+
Step 3: We schedule the compute nodes dependent on comm N and required for comm N + 1.
|
| 106 |
+
Step 4: We schedule comm N + 1.
|
| 107 |
+
Repeat this for subsequent comm nodes.
|
| 108 |
+
"""
|
| 109 |
+
return _schedule_for_comm(
|
| 110 |
+
snodes, raise_comms=True, sink_waits=True, reorder_for_overlap=True
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def reorder_communication_preserving_peak_memory(
|
| 115 |
+
snodes: list[BaseSchedulerNode],
|
| 116 |
+
) -> list[BaseSchedulerNode]:
|
| 117 |
+
"""
|
| 118 |
+
Reorders communication ops relative to computation ops to improve communication-compute overlapping and hide comm
|
| 119 |
+
latency. Stops moving a particular op if it reaches a point that would have increased the peak memory footprint.
|
| 120 |
+
|
| 121 |
+
Currently, follows these heuristics (subject to change or tune):
|
| 122 |
+
- never reorders collectives relative to one another, for SPMD safety
|
| 123 |
+
- has an option for per-collective prefetch limit, but does not enable it by default
|
| 124 |
+
- limits the total number of reorder steps to some factor of the graph size to prevent worst-case quadratic
|
| 125 |
+
performance
|
| 126 |
+
|
| 127 |
+
Prerequisite: sink_comms_and_waits - ensure comm and wait nodes are scheduled as late as possible, respecting data
|
| 128 |
+
dependencies. That allows reorder_communication_preserving_peak_memory to take a best case peak-memory snapshot,
|
| 129 |
+
and then monotonically improve latency by moving collectives backward in time.
|
| 130 |
+
|
| 131 |
+
Peak memory impact is computed in an iterative fashion. First, memory use at each timestep is computed, and global
|
| 132 |
+
peak memory is computed as a max over timesteps. Then, when swapping any two adjacent nodes, only the curr-memory
|
| 133 |
+
for the earlier of the nodes after the swap is affected. This enables checking step by step whether a swap is
|
| 134 |
+
peak-memory-safe, and bailing out if not. Example:
|
| 135 |
+
|
| 136 |
+
0 n0 C0
|
| 137 |
+
1 n1 C0 + Allocs(n1) - Frees(n1)
|
| 138 |
+
2 n2 C0 + Allocs(n1) - Frees(n1) + Allocs(n2) - Frees(n2)
|
| 139 |
+
|
| 140 |
+
0 n0 C0
|
| 141 |
+
1 n2 C0 + Allocs(n2) - Frees(n2) <-- After moving n2 to Time 1, only time1 memory changes
|
| 142 |
+
2 n1 C0 + Allocs(n2) - Frees(n2) + Allocs(n1) - Frees(n1)
|
| 143 |
+
|
| 144 |
+
"""
|
| 145 |
+
reordered_snodes, node_stats = (
|
| 146 |
+
_reorder_communication_preserving_peak_memory_internal(snodes)
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
return reordered_snodes
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@dataclass
|
| 153 |
+
class ReorderInfo:
|
| 154 |
+
"""
|
| 155 |
+
Debug info describing how an individual snode was reordered
|
| 156 |
+
"""
|
| 157 |
+
|
| 158 |
+
initial_exposed: float = -1
|
| 159 |
+
final_exposed: float = -1
|
| 160 |
+
limiting_factor: str = "None"
|
| 161 |
+
moves: int = 0
|
| 162 |
+
grouped: int = 0
|
| 163 |
+
grouped_info: str = ""
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
def improvement(self):
|
| 167 |
+
return self.initial_exposed - self.final_exposed
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def is_gemm_like(node: Optional[Union[IRNode, Operation]]) -> bool:
|
| 171 |
+
if node is None:
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
if is_fallback_op(
|
| 175 |
+
node, # type: ignore[arg-type]
|
| 176 |
+
torch.ops.aten._scaled_dot_product_flash_attention.default,
|
| 177 |
+
):
|
| 178 |
+
return True
|
| 179 |
+
|
| 180 |
+
if (
|
| 181 |
+
python_kernel_name := getattr(node, "python_kernel_name", None)
|
| 182 |
+
) and "extern_kernels" in python_kernel_name:
|
| 183 |
+
return True
|
| 184 |
+
return False
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def contains_gemm_like(snode: BaseSchedulerNode) -> bool:
|
| 188 |
+
from torch._inductor.scheduler import GroupedSchedulerNode
|
| 189 |
+
|
| 190 |
+
if isinstance(snode, GroupedSchedulerNode):
|
| 191 |
+
return any(contains_gemm_like(x) for x in snode.snodes)
|
| 192 |
+
else:
|
| 193 |
+
return is_gemm_like(snode.node)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _temp_group_visit_leaves(snode, fn):
|
| 197 |
+
from torch._inductor.scheduler import GroupedSchedulerNode
|
| 198 |
+
|
| 199 |
+
if isinstance(snode, GroupedSchedulerNode) and snode.temp_grouping:
|
| 200 |
+
for _snode in snode.snodes:
|
| 201 |
+
fn(_snode)
|
| 202 |
+
else:
|
| 203 |
+
fn(snode)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _group_name(snode, with_bufs=False) -> str:
|
| 207 |
+
ret = ""
|
| 208 |
+
for n in snode.snodes:
|
| 209 |
+
if ret:
|
| 210 |
+
ret += "_"
|
| 211 |
+
ret += n.get_name()
|
| 212 |
+
if with_bufs:
|
| 213 |
+
ret += f"{list(snode.get_buffer_names())}"
|
| 214 |
+
return ret
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _is_fake_dep(d):
|
| 218 |
+
return isinstance(d, WeakDep) and d.is_fake
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _group_names(gns: list[BaseSchedulerNode]) -> str:
|
| 222 |
+
return "~".join([gn.get_name() for gn in gns])
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _initialize_memory_tracking(snodes, graph_inputs, graph_outputs):
|
| 226 |
+
"""Initialize memory tracking data structures"""
|
| 227 |
+
name_to_freeable_input_buf = get_freeable_input_buf(snodes, graph_inputs)
|
| 228 |
+
peak_memory, snodes_curr_memory, snodes_allocfree, buf_to_snode_last_use = (
|
| 229 |
+
estimate_peak_memory_allocfree(
|
| 230 |
+
snodes, name_to_freeable_input_buf, graph_outputs
|
| 231 |
+
)
|
| 232 |
+
)
|
| 233 |
+
_curr_memory = dict(zip(snodes, snodes_curr_memory))
|
| 234 |
+
_curr_memory[None] = (0, 0)
|
| 235 |
+
return (
|
| 236 |
+
peak_memory,
|
| 237 |
+
_curr_memory,
|
| 238 |
+
snodes_allocfree,
|
| 239 |
+
buf_to_snode_last_use,
|
| 240 |
+
name_to_freeable_input_buf,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _initialize_double_linked_list(
|
| 245 |
+
snodes: list[BaseSchedulerNode],
|
| 246 |
+
) -> tuple[
|
| 247 |
+
dict[BaseSchedulerNode, Optional[BaseSchedulerNode]],
|
| 248 |
+
dict[BaseSchedulerNode, Optional[BaseSchedulerNode]],
|
| 249 |
+
BaseSchedulerNode,
|
| 250 |
+
]:
|
| 251 |
+
"""Create double-linked list structure from snodes"""
|
| 252 |
+
_prev = {}
|
| 253 |
+
_next = {}
|
| 254 |
+
for i, snode in enumerate(snodes):
|
| 255 |
+
_prev[snode] = snodes[i - 1] if i > 0 else None
|
| 256 |
+
_next[snode] = snodes[i + 1] if i < len(snodes) - 1 else None
|
| 257 |
+
_head = snodes[0]
|
| 258 |
+
return _prev, _next, _head
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _reorder_communication_preserving_peak_memory_internal(
|
| 262 |
+
snodes: list[BaseSchedulerNode],
|
| 263 |
+
) -> tuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, ReorderInfo]]:
|
| 264 |
+
"""
|
| 265 |
+
Internal testing helper that also returns debug info.
|
| 266 |
+
Returns:
|
| 267 |
+
- reordered snodes list
|
| 268 |
+
- dict {snode: ReorderInfo}
|
| 269 |
+
"""
|
| 270 |
+
has_collectives = False
|
| 271 |
+
for snode in snodes:
|
| 272 |
+
if contains_collective(snode):
|
| 273 |
+
has_collectives = True
|
| 274 |
+
break
|
| 275 |
+
if not has_collectives:
|
| 276 |
+
return snodes, {}
|
| 277 |
+
|
| 278 |
+
from torch._inductor.scheduler import GroupedSchedulerNode
|
| 279 |
+
|
| 280 |
+
original_snodes_num = len(snodes)
|
| 281 |
+
# heuristic to avoid degenerating to quadratic time
|
| 282 |
+
graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys())
|
| 283 |
+
graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names())
|
| 284 |
+
(
|
| 285 |
+
peak_memory,
|
| 286 |
+
_curr_memory,
|
| 287 |
+
snodes_allocfree,
|
| 288 |
+
buf_to_snode_last_use,
|
| 289 |
+
name_to_freeable_input_buf,
|
| 290 |
+
) = _initialize_memory_tracking(snodes, graph_inputs, graph_outputs)
|
| 291 |
+
runtimes: dict[BaseSchedulerNode, float] = {
|
| 292 |
+
snode: estimate_op_runtime(snode) for snode in snodes
|
| 293 |
+
}
|
| 294 |
+
# debug stats
|
| 295 |
+
stats: dict[BaseSchedulerNode, ReorderInfo] = {}
|
| 296 |
+
|
| 297 |
+
def exposed_communication_time(
|
| 298 |
+
collective_snode: BaseSchedulerNode, remaining_snodes: list[BaseSchedulerNode]
|
| 299 |
+
) -> float:
|
| 300 |
+
# assumes a linear schedule and computes the overlap of the collective with the remaining nodes
|
| 301 |
+
comm_time = estimate_op_runtime(collective_snode)
|
| 302 |
+
compute_time = 0.0
|
| 303 |
+
for snode in remaining_snodes:
|
| 304 |
+
if contains_collective(snode):
|
| 305 |
+
continue
|
| 306 |
+
if contains_wait(snode):
|
| 307 |
+
# TODO - if the wait is for a collective that started before this collective or on another stream,
|
| 308 |
+
# we can ignore it. Otherwise, it's the end of the road for overlap opportunities
|
| 309 |
+
break
|
| 310 |
+
|
| 311 |
+
def accumulate_time(_snode: BaseSchedulerNode) -> None:
|
| 312 |
+
nonlocal compute_time
|
| 313 |
+
compute_time += runtimes[_snode]
|
| 314 |
+
|
| 315 |
+
_temp_group_visit_leaves(snode, accumulate_time)
|
| 316 |
+
return max(0, comm_time - compute_time)
|
| 317 |
+
|
| 318 |
+
total_moves = 0
|
| 319 |
+
|
| 320 |
+
_prev, _next, _head = _initialize_double_linked_list(snodes)
|
| 321 |
+
|
| 322 |
+
def _group_nodes(
|
| 323 |
+
head: Optional[BaseSchedulerNode], tail: Optional[BaseSchedulerNode]
|
| 324 |
+
) -> list[BaseSchedulerNode]:
|
| 325 |
+
ret = []
|
| 326 |
+
n = head
|
| 327 |
+
while True:
|
| 328 |
+
if n is not None:
|
| 329 |
+
ret.append(n)
|
| 330 |
+
if n == tail:
|
| 331 |
+
break
|
| 332 |
+
n = _next[n] # type: ignore[index]
|
| 333 |
+
return ret
|
| 334 |
+
|
| 335 |
+
def _perform_double_linked_list_swap(candidate, group_head, group_tail):
|
| 336 |
+
# swap (candidate, group_head...group_tail)
|
| 337 |
+
# Before:
|
| 338 |
+
# candidate_prev -0-> candidate -1-> group_head...group_tail -2-> group_tail_next
|
| 339 |
+
# After:
|
| 340 |
+
# candidate_prev -0-> group_head...group_tail -1-> candidate -2-> group_tail_next
|
| 341 |
+
# 0
|
| 342 |
+
candidate_prev = _prev[candidate]
|
| 343 |
+
if candidate_prev:
|
| 344 |
+
_next[candidate_prev] = group_head
|
| 345 |
+
_prev[group_head] = candidate_prev
|
| 346 |
+
|
| 347 |
+
# 2
|
| 348 |
+
group_tail_next = _next[group_tail]
|
| 349 |
+
if group_tail_next:
|
| 350 |
+
_prev[group_tail_next] = candidate
|
| 351 |
+
_next[candidate] = group_tail_next
|
| 352 |
+
|
| 353 |
+
# 1
|
| 354 |
+
_prev[candidate] = group_tail
|
| 355 |
+
_next[group_tail] = candidate
|
| 356 |
+
|
| 357 |
+
nonlocal _head
|
| 358 |
+
if _head == candidate:
|
| 359 |
+
_head = group_head
|
| 360 |
+
|
| 361 |
+
def _calculate_potential_peak_memory(
|
| 362 |
+
candidate, group_ns, group_n_to_bufs_after_swap_dealloc_by_candidate
|
| 363 |
+
):
|
| 364 |
+
# Caching calculations of memory for group nodes and candidate,
|
| 365 |
+
# to apply without recalculation after swap.
|
| 366 |
+
_post_alloc_update: dict[BaseSchedulerNode, int] = {}
|
| 367 |
+
potential_peak: int = 0
|
| 368 |
+
if not group_n_to_bufs_after_swap_dealloc_by_candidate:
|
| 369 |
+
# Not accounting for buffers last use change
|
| 370 |
+
potential_peak = max(
|
| 371 |
+
group_peak_memory - candidate_delta_mem,
|
| 372 |
+
_curr_memory[group_tail][1]
|
| 373 |
+
- candidate_delta_mem
|
| 374 |
+
+ candidate_allocfree.size_alloc,
|
| 375 |
+
)
|
| 376 |
+
return potential_peak, _post_alloc_update
|
| 377 |
+
|
| 378 |
+
# If candidate will be after group, the starting memory level of group nodes
|
| 379 |
+
# changes to the -(candidate.size_alloc - candidate.size_free)
|
| 380 |
+
mem_after_reorder_delta: int = -candidate_delta_mem
|
| 381 |
+
for gn in gns:
|
| 382 |
+
gn_post_alloc_mem = _curr_memory[gn][0] + mem_after_reorder_delta
|
| 383 |
+
_post_alloc_update[gn] = gn_post_alloc_mem
|
| 384 |
+
potential_peak = max(potential_peak, gn_post_alloc_mem)
|
| 385 |
+
|
| 386 |
+
bufs = group_n_to_bufs_after_swap_dealloc_by_candidate.get(gn, None)
|
| 387 |
+
if bufs is not None:
|
| 388 |
+
for buf in bufs:
|
| 389 |
+
# Candidate will deallocate those buffers
|
| 390 |
+
mem_after_reorder_delta += buf.mpi_buffer.size_free
|
| 391 |
+
|
| 392 |
+
candidate_mem_post_alloc = (
|
| 393 |
+
_curr_memory[group_tail][1]
|
| 394 |
+
+ mem_after_reorder_delta
|
| 395 |
+
+ candidate_allocfree.size_alloc
|
| 396 |
+
)
|
| 397 |
+
_post_alloc_update[candidate] = candidate_mem_post_alloc
|
| 398 |
+
potential_peak = max(potential_peak, candidate_mem_post_alloc)
|
| 399 |
+
return potential_peak, _post_alloc_update
|
| 400 |
+
|
| 401 |
+
def _update_memory_tracking_after_swap(
|
| 402 |
+
candidate,
|
| 403 |
+
gns,
|
| 404 |
+
group_n_to_bufs_after_swap_dealloc_by_candidate,
|
| 405 |
+
_post_alloc_update,
|
| 406 |
+
):
|
| 407 |
+
if not group_n_to_bufs_after_swap_dealloc_by_candidate:
|
| 408 |
+
for gn in gns:
|
| 409 |
+
cm = _curr_memory[gn]
|
| 410 |
+
_curr_memory[gn] = (
|
| 411 |
+
cm[0] - candidate_delta_mem,
|
| 412 |
+
cm[1] - candidate_delta_mem,
|
| 413 |
+
)
|
| 414 |
+
_candidate_post_alloc_mem = (
|
| 415 |
+
_curr_memory[group_tail][1] + candidate_allocfree.size_alloc
|
| 416 |
+
)
|
| 417 |
+
_candidate_post_free_mem = (
|
| 418 |
+
_candidate_post_alloc_mem - candidate_allocfree.size_free
|
| 419 |
+
)
|
| 420 |
+
_curr_memory[candidate] = (
|
| 421 |
+
_candidate_post_alloc_mem,
|
| 422 |
+
_candidate_post_free_mem,
|
| 423 |
+
)
|
| 424 |
+
return
|
| 425 |
+
|
| 426 |
+
# Candidate becomes last use of some bufs
|
| 427 |
+
for (
|
| 428 |
+
gn,
|
| 429 |
+
bufs,
|
| 430 |
+
) in group_n_to_bufs_after_swap_dealloc_by_candidate.items():
|
| 431 |
+
for buf in bufs:
|
| 432 |
+
buf_to_snode_last_use[buf] = candidate
|
| 433 |
+
|
| 434 |
+
size_free_to_move_to_candidate_sum: int = 0
|
| 435 |
+
for n in gns:
|
| 436 |
+
_gn_post_alloc_mem: int = _post_alloc_update[n]
|
| 437 |
+
size_free_to_move_to_candidate: int = sum(
|
| 438 |
+
buf.mpi_buffer.size_free
|
| 439 |
+
for buf in group_n_to_bufs_after_swap_dealloc_by_candidate[n]
|
| 440 |
+
)
|
| 441 |
+
size_free_to_move_to_candidate_sum += size_free_to_move_to_candidate
|
| 442 |
+
# group node does not deallocate this after swap
|
| 443 |
+
snodes_allocfree[n].size_free -= size_free_to_move_to_candidate
|
| 444 |
+
gn_post_free_mem: int = _gn_post_alloc_mem - snodes_allocfree[n].size_free
|
| 445 |
+
_curr_memory[n] = (_gn_post_alloc_mem, gn_post_free_mem)
|
| 446 |
+
_candidate_post_alloc_mem = _post_alloc_update[candidate]
|
| 447 |
+
snodes_allocfree[candidate].size_free += size_free_to_move_to_candidate_sum
|
| 448 |
+
candidate_post_free_mem = (
|
| 449 |
+
_candidate_post_alloc_mem - snodes_allocfree[candidate].size_free
|
| 450 |
+
)
|
| 451 |
+
_curr_memory[candidate] = (
|
| 452 |
+
_candidate_post_alloc_mem,
|
| 453 |
+
candidate_post_free_mem,
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
debug_num_collectives_to_reorder: Optional[int] = (
|
| 457 |
+
config.reorder_iterative_debug_limit_to_reorder
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
num_processed_collectives: int = 0
|
| 461 |
+
curr = _head
|
| 462 |
+
debug_iterative_memory_recompute = config.reorder_iterative_debug_memory_recompute
|
| 463 |
+
iterative_recompute_error = False
|
| 464 |
+
|
| 465 |
+
while _next[curr] is not None:
|
| 466 |
+
if iterative_recompute_error:
|
| 467 |
+
break
|
| 468 |
+
if contains_collective(curr):
|
| 469 |
+
if debug_num_collectives_to_reorder is not None and (
|
| 470 |
+
num_processed_collectives >= debug_num_collectives_to_reorder
|
| 471 |
+
):
|
| 472 |
+
break
|
| 473 |
+
num_processed_collectives += 1
|
| 474 |
+
|
| 475 |
+
info = stats[curr] = ReorderInfo()
|
| 476 |
+
info.initial_exposed = info.final_exposed = exposed_communication_time(
|
| 477 |
+
curr, _group_nodes(_next[curr], None)
|
| 478 |
+
)
|
| 479 |
+
|
| 480 |
+
candidate = _prev[curr]
|
| 481 |
+
group_head = curr
|
| 482 |
+
group_tail = curr
|
| 483 |
+
group_peak_memory = _curr_memory[curr][0] # post_alloc memory
|
| 484 |
+
while candidate is not None:
|
| 485 |
+
if contains_collective(candidate):
|
| 486 |
+
info.limiting_factor = "collective ordering"
|
| 487 |
+
break
|
| 488 |
+
|
| 489 |
+
gns: list[BaseSchedulerNode] = _group_nodes(group_head, group_tail)
|
| 490 |
+
group = GroupedSchedulerNode(
|
| 491 |
+
curr.scheduler,
|
| 492 |
+
gns,
|
| 493 |
+
temp_grouping=True,
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
# We can have multiple deps with the same name.
|
| 497 |
+
# As we ignore WeakDep(is_fake=True) =>
|
| 498 |
+
# filter them out first to avoid overwriting of real dep.
|
| 499 |
+
data_deps = {
|
| 500 |
+
d.name: d for d in group.unmet_dependencies if not _is_fake_dep(d)
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
candidate_outs = candidate.get_outputs()
|
| 504 |
+
data_dep = None
|
| 505 |
+
for o in candidate_outs:
|
| 506 |
+
if d := data_deps.get(o.get_name(), None):
|
| 507 |
+
data_dep = d
|
| 508 |
+
break
|
| 509 |
+
|
| 510 |
+
if data_dep is not None:
|
| 511 |
+
|
| 512 |
+
def is_groupable(
|
| 513 |
+
candidate: BaseSchedulerNode,
|
| 514 |
+
) -> tuple[bool, Optional[str]]:
|
| 515 |
+
# preserve ordering
|
| 516 |
+
if contains_collective(candidate):
|
| 517 |
+
return False, "contains_collective"
|
| 518 |
+
|
| 519 |
+
if contains_gemm_like(candidate):
|
| 520 |
+
return False, "contains_gemm_like"
|
| 521 |
+
return True, None
|
| 522 |
+
|
| 523 |
+
is_groupable_result, grouping_reason = is_groupable(candidate)
|
| 524 |
+
if is_groupable_result:
|
| 525 |
+
group_head = candidate
|
| 526 |
+
group_peak_memory = max(
|
| 527 |
+
group_peak_memory, _curr_memory[candidate][0]
|
| 528 |
+
)
|
| 529 |
+
info.grouped += 1
|
| 530 |
+
info.grouped_info = _group_names(gns)
|
| 531 |
+
candidate = _prev[candidate]
|
| 532 |
+
continue
|
| 533 |
+
else:
|
| 534 |
+
msg = (
|
| 535 |
+
f"data dependency {data_dep}(dep_names:{list(data_deps.keys())})"
|
| 536 |
+
f"\n candidate:{candidate.get_name()}(outs:{[candidate.get_buffer_names()]})"
|
| 537 |
+
f"dep on {_group_names(gns)}"
|
| 538 |
+
f"\n non_group_reason:{grouping_reason}"
|
| 539 |
+
)
|
| 540 |
+
info.limiting_factor = msg
|
| 541 |
+
break
|
| 542 |
+
|
| 543 |
+
candidate_allocfree: SNodeMemory = snodes_allocfree[candidate]
|
| 544 |
+
candidate_delta_mem: int = (
|
| 545 |
+
candidate_allocfree.size_alloc - candidate_allocfree.size_free
|
| 546 |
+
)
|
| 547 |
+
# candidate and one of group nodes are successors of the same buffer
|
| 548 |
+
# and last use of the buffer happen in group nodes.
|
| 549 |
+
# This last use deallocates it.
|
| 550 |
+
# If we swap [candidate [group]] to [[group] candidate],
|
| 551 |
+
# candidate becomes the last use
|
| 552 |
+
# and deallocated this buffer instead of group node.
|
| 553 |
+
# we need to update size_free accordingly to group_node and candidate,
|
| 554 |
+
# and recalculate post_alloc, post_free for them.
|
| 555 |
+
#
|
| 556 |
+
# Buf that changes its last use snode,
|
| 557 |
+
# after swap will be deallocated only by candidate,
|
| 558 |
+
# while before it was deallocated by group node.
|
| 559 |
+
group_n_to_bufs_after_swap_dealloc_by_candidate: dict[
|
| 560 |
+
BaseSchedulerNode, list[Union[FreeableInputBuffer, Any]]
|
| 561 |
+
] = defaultdict(list)
|
| 562 |
+
for (
|
| 563 |
+
buf,
|
| 564 |
+
snode_last_use,
|
| 565 |
+
) in buf_to_snode_last_use.items():
|
| 566 |
+
succ_nodes = buf.mpi_buffer.succ_nodes
|
| 567 |
+
if candidate not in succ_nodes:
|
| 568 |
+
continue
|
| 569 |
+
|
| 570 |
+
if not any(gn == snode_last_use for gn in gns):
|
| 571 |
+
continue
|
| 572 |
+
|
| 573 |
+
group_n_to_bufs_after_swap_dealloc_by_candidate[
|
| 574 |
+
snode_last_use
|
| 575 |
+
].append(buf)
|
| 576 |
+
|
| 577 |
+
potential_peak, _post_alloc_update = _calculate_potential_peak_memory(
|
| 578 |
+
candidate, gns, group_n_to_bufs_after_swap_dealloc_by_candidate
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
if potential_peak > peak_memory:
|
| 582 |
+
info.limiting_factor = (
|
| 583 |
+
f"peak memory new:{potential_peak} vs base:{peak_memory}"
|
| 584 |
+
)
|
| 585 |
+
break
|
| 586 |
+
info.moves += 1
|
| 587 |
+
total_moves += 1
|
| 588 |
+
|
| 589 |
+
_perform_double_linked_list_swap(candidate, group_head, group_tail)
|
| 590 |
+
|
| 591 |
+
info.final_exposed = exposed_communication_time(
|
| 592 |
+
curr, _group_nodes(_next[curr], None)
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
_update_memory_tracking_after_swap(
|
| 596 |
+
candidate,
|
| 597 |
+
gns,
|
| 598 |
+
group_n_to_bufs_after_swap_dealloc_by_candidate,
|
| 599 |
+
_post_alloc_update,
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
if debug_iterative_memory_recompute:
|
| 603 |
+
# Compare iteratively recomputed memory data
|
| 604 |
+
# with full run of estimate_peak_memory
|
| 605 |
+
|
| 606 |
+
from .comms_debug import _debug_iterative_memory_recompute
|
| 607 |
+
|
| 608 |
+
iterative_recompute_error = _debug_iterative_memory_recompute(
|
| 609 |
+
candidate,
|
| 610 |
+
gns,
|
| 611 |
+
_group_names(gns),
|
| 612 |
+
_group_nodes(_head, None),
|
| 613 |
+
name_to_freeable_input_buf,
|
| 614 |
+
graph_outputs,
|
| 615 |
+
peak_memory,
|
| 616 |
+
_curr_memory,
|
| 617 |
+
snodes_allocfree,
|
| 618 |
+
"reorder_communication_preserving_peak_memory",
|
| 619 |
+
group_n_to_bufs_after_swap_dealloc_by_candidate,
|
| 620 |
+
)
|
| 621 |
+
if iterative_recompute_error:
|
| 622 |
+
break
|
| 623 |
+
candidate = _prev[group_head]
|
| 624 |
+
curr = _next[curr] # type: ignore[assignment]
|
| 625 |
+
|
| 626 |
+
node_stats = stats
|
| 627 |
+
improvement = {snode: node_stats[snode].improvement for snode in node_stats}
|
| 628 |
+
total_improvement = sum([improvement[snode] for snode in improvement])
|
| 629 |
+
total_moves = sum([node_stats[snode].moves for snode in node_stats])
|
| 630 |
+
|
| 631 |
+
reorder_log_str = (
|
| 632 |
+
f"reorder_communication_preserving_peak_memory improved overlap by {total_improvement} ns"
|
| 633 |
+
f" after {total_moves} reorders.\n"
|
| 634 |
+
)
|
| 635 |
+
headers = [
|
| 636 |
+
"Collective node",
|
| 637 |
+
"initial exposed",
|
| 638 |
+
"final exposed",
|
| 639 |
+
"improvement",
|
| 640 |
+
"limiting factor",
|
| 641 |
+
"moves",
|
| 642 |
+
"grouped",
|
| 643 |
+
"grouped_info",
|
| 644 |
+
]
|
| 645 |
+
rows = [
|
| 646 |
+
[
|
| 647 |
+
node_summary(snode),
|
| 648 |
+
node_info.initial_exposed,
|
| 649 |
+
node_info.final_exposed,
|
| 650 |
+
node_info.improvement,
|
| 651 |
+
node_info.limiting_factor,
|
| 652 |
+
node_info.moves,
|
| 653 |
+
node_info.grouped,
|
| 654 |
+
node_info.grouped_info,
|
| 655 |
+
]
|
| 656 |
+
for snode, node_info in node_stats.items()
|
| 657 |
+
]
|
| 658 |
+
if importlib.util.find_spec("tabulate"):
|
| 659 |
+
from tabulate import tabulate
|
| 660 |
+
|
| 661 |
+
reorder_log_str += tabulate(
|
| 662 |
+
rows,
|
| 663 |
+
headers=headers,
|
| 664 |
+
)
|
| 665 |
+
else:
|
| 666 |
+
reorder_log_str += (
|
| 667 |
+
"Please `pip install tabulate` to nicely render overlap stats.\n"
|
| 668 |
+
)
|
| 669 |
+
reorder_log_str += str(headers) + "\n"
|
| 670 |
+
reorder_log_str += "\n".join(map(str, rows))
|
| 671 |
+
|
| 672 |
+
new_snodes = _group_nodes(_head, None)
|
| 673 |
+
assert len(new_snodes) == original_snodes_num
|
| 674 |
+
new_peak_memory, _, _, _ = estimate_peak_memory_allocfree(
|
| 675 |
+
new_snodes, name_to_freeable_input_buf, graph_outputs
|
| 676 |
+
)
|
| 677 |
+
reorder_log_str += f"\n peak_memory_before:{peak_memory}"
|
| 678 |
+
reorder_log_str += f"\n peak_memory_after:{new_peak_memory}"
|
| 679 |
+
|
| 680 |
+
overlap_log.info(reorder_log_str)
|
| 681 |
+
trace_structured(
|
| 682 |
+
"artifact",
|
| 683 |
+
metadata_fn=lambda: {
|
| 684 |
+
"name": "reorder_communication_preserving_peak_memory",
|
| 685 |
+
"encoding": "string",
|
| 686 |
+
},
|
| 687 |
+
payload_fn=lambda: reorder_log_str,
|
| 688 |
+
)
|
| 689 |
+
|
| 690 |
+
return new_snodes, stats
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def _schedule_for_comm(
|
| 694 |
+
snodes: list[BaseSchedulerNode],
|
| 695 |
+
raise_comms: bool,
|
| 696 |
+
sink_waits: bool,
|
| 697 |
+
reorder_for_overlap: bool,
|
| 698 |
+
) -> list[BaseSchedulerNode]:
|
| 699 |
+
"""
|
| 700 |
+
Schedule `snodes` for various comm optimization objectives.
|
| 701 |
+
|
| 702 |
+
Args:
|
| 703 |
+
snodes: the nodes to be scheduled.
|
| 704 |
+
raise_comms: whether to greedily schedule collectives as early as possible
|
| 705 |
+
sink_wait: whether to greedily schedule waits as late as possible
|
| 706 |
+
reorder_compute_for_overlap: whether to reorder compute nodes to
|
| 707 |
+
optimize for compute/communication overlapping.
|
| 708 |
+
|
| 709 |
+
Returns:
|
| 710 |
+
The new schedule order.
|
| 711 |
+
|
| 712 |
+
Some notes on the synergy between different options:
|
| 713 |
+
- `raise_comms` provides more overlapping oppurtunies for `reorder_compute_for_overlap`.
|
| 714 |
+
- When both `raise_comms` and `sink_waits` is `True`, `raise_comms` is prioritized.
|
| 715 |
+
"""
|
| 716 |
+
# We assign each node a tuple of scores (score_0, score_1, score_2),
|
| 717 |
+
# decreasing in importance, with a lower value indicating a higher ranking:
|
| 718 |
+
#
|
| 719 |
+
# - score_0: the lowest comm_idx among the comm nodes that the node blocks.
|
| 720 |
+
# If a node doesn't block any comm nodes, its score_0 is set to
|
| 721 |
+
# sys.maxsize. This score ensures that comm nodes get scheduled as early as
|
| 722 |
+
# possible.
|
| 723 |
+
# - score_1: 1 if the node is a wait node, 0 otherwise. This score ensures
|
| 724 |
+
# that wait nodes are deferred as late as possible.
|
| 725 |
+
# - score_2: the index of the node in the original topological order. This
|
| 726 |
+
# score provides stability in case of ties.
|
| 727 |
+
#
|
| 728 |
+
# When only raise_comms is True, only score_0 and score_2 are considered.
|
| 729 |
+
# When only sink_waits is True, only score_1 and score_2 are considered.
|
| 730 |
+
# When neither is True, the original order is yielded.
|
| 731 |
+
buf_name_to_snode = {}
|
| 732 |
+
name_to_fused_node = {}
|
| 733 |
+
scores_0, scores_1, scores_2 = {}, {}, {}
|
| 734 |
+
for idx, snode in enumerate(snodes):
|
| 735 |
+
for buf_name in snode.get_buffer_names():
|
| 736 |
+
buf_name_to_snode[buf_name] = snode
|
| 737 |
+
|
| 738 |
+
for op_name in snode.get_operation_names():
|
| 739 |
+
name_to_fused_node[op_name] = snode
|
| 740 |
+
name_to_fused_node[snode.get_name()] = snode
|
| 741 |
+
|
| 742 |
+
node_name = snode.get_name()
|
| 743 |
+
scores_0[node_name] = sys.maxsize
|
| 744 |
+
scores_1[node_name] = 0
|
| 745 |
+
scores_2[node_name] = idx
|
| 746 |
+
|
| 747 |
+
comm_idx = 0
|
| 748 |
+
for snode in snodes:
|
| 749 |
+
if raise_comms and contains_collective(snode):
|
| 750 |
+
scores_0[snode.get_name()] = comm_idx
|
| 751 |
+
for ancestor in snode.ancestors:
|
| 752 |
+
anc_fused_name = name_to_fused_node[ancestor].get_name()
|
| 753 |
+
scores_0[anc_fused_name] = min(scores_0[anc_fused_name], comm_idx)
|
| 754 |
+
comm_idx += 1
|
| 755 |
+
elif sink_waits and contains_wait(snode):
|
| 756 |
+
scores_1[snode.get_name()] = 1
|
| 757 |
+
|
| 758 |
+
class Runnable:
|
| 759 |
+
def __init__(self, snode) -> None:
|
| 760 |
+
self.snode = snode
|
| 761 |
+
name = next(iter(snode.get_operation_names()))
|
| 762 |
+
fused_name = name_to_fused_node[name].get_name()
|
| 763 |
+
self.score = (
|
| 764 |
+
scores_0[fused_name],
|
| 765 |
+
scores_1[fused_name],
|
| 766 |
+
scores_2[fused_name],
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
def __lt__(self, other):
|
| 770 |
+
return self.score < other.score
|
| 771 |
+
|
| 772 |
+
unmet_deps: dict[BaseSchedulerNode, OrderedSet[str]] = {
|
| 773 |
+
snode: OrderedSet(dep.name for dep in snode.unmet_dependencies)
|
| 774 |
+
for snode in snodes
|
| 775 |
+
}
|
| 776 |
+
|
| 777 |
+
ready: list[Runnable] = []
|
| 778 |
+
buffer_users: dict[str, OrderedSet[BaseSchedulerNode]] = defaultdict(OrderedSet)
|
| 779 |
+
snode_to_cost = {snode: estimate_op_runtime(snode) for snode in snodes}
|
| 780 |
+
|
| 781 |
+
for snode, deps in unmet_deps.items():
|
| 782 |
+
if len(deps) == 0:
|
| 783 |
+
heapq.heappush(ready, Runnable(snode))
|
| 784 |
+
for dep in deps:
|
| 785 |
+
buffer_users[dep].add(snode)
|
| 786 |
+
|
| 787 |
+
scheduled = []
|
| 788 |
+
|
| 789 |
+
def schedule(snode):
|
| 790 |
+
"""
|
| 791 |
+
Schedules `snode` and put all unblocked nodes onto the ready queue.
|
| 792 |
+
"""
|
| 793 |
+
scheduled.append(snode)
|
| 794 |
+
for buf_name in snode.get_buffer_names():
|
| 795 |
+
for snode in buffer_users[buf_name]:
|
| 796 |
+
unmet_deps[snode].remove(buf_name)
|
| 797 |
+
if len(unmet_deps[snode]) == 0:
|
| 798 |
+
heapq.heappush(ready, Runnable(snode))
|
| 799 |
+
|
| 800 |
+
def get_overlapping_candidate():
|
| 801 |
+
"""
|
| 802 |
+
Return the next node in the ready queue that's neither a collective or
|
| 803 |
+
a wait.
|
| 804 |
+
"""
|
| 805 |
+
candidates = [
|
| 806 |
+
x
|
| 807 |
+
for x in ready
|
| 808 |
+
if not contains_collective(x.snode) and not contains_wait(x.snode)
|
| 809 |
+
]
|
| 810 |
+
if len(candidates) == 0:
|
| 811 |
+
return None
|
| 812 |
+
return min(candidates, key=lambda x: x.score)
|
| 813 |
+
|
| 814 |
+
def schedule_collective_for_overlap(snode):
|
| 815 |
+
"""
|
| 816 |
+
Schedules collective node `snode`, along with one or more compute nodes
|
| 817 |
+
to overlap with it. The strategy is described in the comment of
|
| 818 |
+
`reorder_compute_for_overlap`.
|
| 819 |
+
"""
|
| 820 |
+
assert contains_collective(snode)
|
| 821 |
+
schedule(snode)
|
| 822 |
+
|
| 823 |
+
collective_cost = snode_to_cost[snode]
|
| 824 |
+
while (
|
| 825 |
+
collective_cost > 0
|
| 826 |
+
and (candidate := get_overlapping_candidate()) is not None
|
| 827 |
+
):
|
| 828 |
+
ready.remove(candidate)
|
| 829 |
+
schedule(candidate.snode)
|
| 830 |
+
collective_cost -= snode_to_cost[candidate.snode]
|
| 831 |
+
heapq.heapify(ready)
|
| 832 |
+
|
| 833 |
+
while len(ready):
|
| 834 |
+
snode = heapq.heappop(ready).snode
|
| 835 |
+
if reorder_for_overlap and contains_collective(snode):
|
| 836 |
+
schedule_collective_for_overlap(snode)
|
| 837 |
+
else:
|
| 838 |
+
schedule(snode)
|
| 839 |
+
|
| 840 |
+
for snode, deps in unmet_deps.items():
|
| 841 |
+
assert len(deps) == 0, (
|
| 842 |
+
f"Detected unscheduled nodes. Nodes with unmet dependencies: {unmet_deps}"
|
| 843 |
+
)
|
| 844 |
+
return scheduled
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def decide_global_ordering_of_comms(
|
| 848 |
+
nodes: list[BaseSchedulerNode], name_to_buf, name_to_fused_node
|
| 849 |
+
) -> list[BaseSchedulerNode]:
|
| 850 |
+
"""
|
| 851 |
+
Decide global ordering of comms, by just enforcing the ordering that's in the input graph
|
| 852 |
+
(might not be the same ordering as the eager mode program).
|
| 853 |
+
TODO: Come up with a better approach
|
| 854 |
+
"""
|
| 855 |
+
if not torch.distributed.is_available():
|
| 856 |
+
return nodes
|
| 857 |
+
|
| 858 |
+
comm_nodes = [n for n in nodes if contains_collective(n)]
|
| 859 |
+
|
| 860 |
+
for i in range(1, len(comm_nodes)):
|
| 861 |
+
# Enforce ordering by making previous comm a `WeakDep` dependency of the next comm
|
| 862 |
+
mutating_buf = next(iter(comm_nodes[i].get_buffer_names()))
|
| 863 |
+
for buf in comm_nodes[i - 1].get_buffer_names():
|
| 864 |
+
comm_nodes[i].add_fake_dep(
|
| 865 |
+
WeakDep(buf, mutating_buf=mutating_buf, is_fake=True)
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
return nodes
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
@dataclass
|
| 872 |
+
class SinkWaitInfo:
|
| 873 |
+
grouped: int = 0
|
| 874 |
+
grouped_info: str = ""
|
| 875 |
+
moves: int = 0
|
| 876 |
+
moves_info: str = ""
|
| 877 |
+
limiting_factor: str = "None"
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def _sink_waits_iterative_internal(
|
| 881 |
+
snodes: list[BaseSchedulerNode],
|
| 882 |
+
) -> tuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, SinkWaitInfo]]:
|
| 883 |
+
from torch._inductor.scheduler import GroupedSchedulerNode
|
| 884 |
+
|
| 885 |
+
original_snodes_num = len(snodes)
|
| 886 |
+
if original_snodes_num == 0:
|
| 887 |
+
return snodes, {}
|
| 888 |
+
graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys())
|
| 889 |
+
graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names())
|
| 890 |
+
(
|
| 891 |
+
peak_memory,
|
| 892 |
+
_curr_memory,
|
| 893 |
+
snodes_allocfree,
|
| 894 |
+
buf_to_snode_last_use,
|
| 895 |
+
name_to_freeable_input_buf,
|
| 896 |
+
) = _initialize_memory_tracking(snodes, graph_inputs, graph_outputs)
|
| 897 |
+
|
| 898 |
+
_prev, _next, _head = _initialize_double_linked_list(snodes)
|
| 899 |
+
|
| 900 |
+
stats: dict[BaseSchedulerNode, SinkWaitInfo] = {}
|
| 901 |
+
|
| 902 |
+
def _group_nodes(
|
| 903 |
+
head: Optional[BaseSchedulerNode], tail: Optional[BaseSchedulerNode]
|
| 904 |
+
) -> list[BaseSchedulerNode]:
|
| 905 |
+
ret = []
|
| 906 |
+
n = head
|
| 907 |
+
while True:
|
| 908 |
+
if n is not None:
|
| 909 |
+
ret.append(n)
|
| 910 |
+
if n == tail:
|
| 911 |
+
break
|
| 912 |
+
n = _next[n] # type: ignore[index]
|
| 913 |
+
return ret
|
| 914 |
+
|
| 915 |
+
def _calculate_potential_peak_memory(
|
| 916 |
+
candidate, group_ns, group_n_to_bufs_after_swap_dealloc_instead_of_candidate
|
| 917 |
+
):
|
| 918 |
+
pre_group_mem = (
|
| 919 |
+
_curr_memory[group_head][0] - snodes_allocfree[group_head].size_alloc
|
| 920 |
+
)
|
| 921 |
+
# Stash memory tracing updates to not recompute them after swap
|
| 922 |
+
_post_alloc_update: dict[BaseSchedulerNode, int] = {}
|
| 923 |
+
_size_free_delta_update: dict[BaseSchedulerNode, int] = {}
|
| 924 |
+
|
| 925 |
+
potential_peak = 0
|
| 926 |
+
if not group_n_to_bufs_after_swap_dealloc_instead_of_candidate:
|
| 927 |
+
# Not accounting for buffers liveliness change
|
| 928 |
+
potential_peak = max(
|
| 929 |
+
group_peak_memory + candidate_delta_mem,
|
| 930 |
+
pre_group_mem + candidate_allocfree.size_alloc,
|
| 931 |
+
)
|
| 932 |
+
return potential_peak, _post_alloc_update, _size_free_delta_update
|
| 933 |
+
|
| 934 |
+
candidate_post_alloc = pre_group_mem + candidate_allocfree.size_alloc
|
| 935 |
+
_post_alloc_update[candidate] = candidate_post_alloc
|
| 936 |
+
potential_peak = candidate_post_alloc
|
| 937 |
+
candidate_size_free_to_move = sum(
|
| 938 |
+
buf.mpi_buffer.size_free # type: ignore[attr-defined]
|
| 939 |
+
for buf in itertools.chain.from_iterable(
|
| 940 |
+
group_n_to_bufs_after_swap_dealloc_instead_of_candidate.values()
|
| 941 |
+
)
|
| 942 |
+
)
|
| 943 |
+
_size_free_delta_update[candidate] = -candidate_size_free_to_move
|
| 944 |
+
delta_mem = candidate_delta_mem + candidate_size_free_to_move
|
| 945 |
+
for gn in gns:
|
| 946 |
+
gn_post_alloc = _curr_memory[gn][0] + delta_mem
|
| 947 |
+
_post_alloc_update[gn] = gn_post_alloc
|
| 948 |
+
potential_peak = max(potential_peak, gn_post_alloc)
|
| 949 |
+
gn_size_free_to_add = 0
|
| 950 |
+
if gn in group_n_to_bufs_after_swap_dealloc_instead_of_candidate:
|
| 951 |
+
bufs = group_n_to_bufs_after_swap_dealloc_instead_of_candidate[gn]
|
| 952 |
+
for buf in bufs:
|
| 953 |
+
gn_size_free_to_add += buf.mpi_buffer.size_free
|
| 954 |
+
_size_free_delta_update[gn] = gn_size_free_to_add
|
| 955 |
+
delta_mem -= gn_size_free_to_add
|
| 956 |
+
return potential_peak, _post_alloc_update, _size_free_delta_update
|
| 957 |
+
|
| 958 |
+
def _perform_double_linked_list_swap(candidate, group_head, group_tail):
|
| 959 |
+
# group_head_prev -0-> candidate -1-> group_head...group_tail -2-> candidate_next
|
| 960 |
+
# 0:
|
| 961 |
+
group_head_prev = _prev[group_head]
|
| 962 |
+
if group_head_prev:
|
| 963 |
+
_next[group_head_prev] = candidate
|
| 964 |
+
_prev[candidate] = group_head_prev
|
| 965 |
+
|
| 966 |
+
# 2:
|
| 967 |
+
candidate_next = _next[candidate]
|
| 968 |
+
if candidate_next:
|
| 969 |
+
_prev[candidate_next] = group_tail
|
| 970 |
+
_next[group_tail] = candidate_next
|
| 971 |
+
|
| 972 |
+
# 1:
|
| 973 |
+
_prev[group_head] = candidate
|
| 974 |
+
_next[candidate] = group_head
|
| 975 |
+
nonlocal _head
|
| 976 |
+
if group_head == _head:
|
| 977 |
+
_head = candidate
|
| 978 |
+
|
| 979 |
+
def _update_memory_tracking_after_swap(
|
| 980 |
+
candidate,
|
| 981 |
+
gns,
|
| 982 |
+
group_n_to_bufs_after_swap_dealloc_instead_of_candidate,
|
| 983 |
+
_post_alloc_update,
|
| 984 |
+
_size_free_delta_update,
|
| 985 |
+
):
|
| 986 |
+
group_head = gns[0]
|
| 987 |
+
pre_group_mem = (
|
| 988 |
+
_curr_memory[group_head][0] - snodes_allocfree[group_head].size_alloc
|
| 989 |
+
)
|
| 990 |
+
if not group_n_to_bufs_after_swap_dealloc_instead_of_candidate:
|
| 991 |
+
candidate_post_alloc = pre_group_mem + candidate_allocfree.size_alloc
|
| 992 |
+
_curr_memory[candidate] = (
|
| 993 |
+
candidate_post_alloc,
|
| 994 |
+
candidate_post_alloc - candidate_allocfree.size_free,
|
| 995 |
+
)
|
| 996 |
+
for gn in gns:
|
| 997 |
+
cm = _curr_memory[gn]
|
| 998 |
+
_curr_memory[gn] = (
|
| 999 |
+
cm[0] + candidate_delta_mem,
|
| 1000 |
+
cm[1] + candidate_delta_mem,
|
| 1001 |
+
)
|
| 1002 |
+
return
|
| 1003 |
+
|
| 1004 |
+
for n in [candidate, *gns]:
|
| 1005 |
+
post_alloc = _post_alloc_update[n]
|
| 1006 |
+
snodes_allocfree[n].size_free += _size_free_delta_update[n]
|
| 1007 |
+
_curr_memory[n] = (
|
| 1008 |
+
post_alloc,
|
| 1009 |
+
post_alloc - snodes_allocfree[n].size_free,
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
curr = snodes[-1]
|
| 1013 |
+
|
| 1014 |
+
processed_waits = OrderedSet() # type: ignore[var-annotated]
|
| 1015 |
+
debug_iterative_memory_recompute = config.reorder_iterative_debug_memory_recompute
|
| 1016 |
+
debug_num_sink_waits_to_reorder: Optional[int] = (
|
| 1017 |
+
config.sink_waits_iterative_debug_limit_to_sink
|
| 1018 |
+
)
|
| 1019 |
+
|
| 1020 |
+
iterative_recompute_error = False
|
| 1021 |
+
|
| 1022 |
+
while _prev[curr] is not None:
|
| 1023 |
+
if iterative_recompute_error:
|
| 1024 |
+
break
|
| 1025 |
+
if (
|
| 1026 |
+
debug_num_sink_waits_to_reorder is not None
|
| 1027 |
+
and len(processed_waits) >= debug_num_sink_waits_to_reorder
|
| 1028 |
+
):
|
| 1029 |
+
break
|
| 1030 |
+
|
| 1031 |
+
if contains_wait(curr) and curr not in processed_waits:
|
| 1032 |
+
processed_waits.add(curr)
|
| 1033 |
+
info = stats[curr] = SinkWaitInfo()
|
| 1034 |
+
candidate = _next[curr]
|
| 1035 |
+
wait_snode = curr
|
| 1036 |
+
group_head = curr
|
| 1037 |
+
group_tail = curr
|
| 1038 |
+
group_peak_memory = _curr_memory[curr][0]
|
| 1039 |
+
while candidate is not None:
|
| 1040 |
+
if iterative_recompute_error:
|
| 1041 |
+
break
|
| 1042 |
+
gns: list[BaseSchedulerNode] = _group_nodes(group_head, group_tail)
|
| 1043 |
+
group = GroupedSchedulerNode(
|
| 1044 |
+
wait_snode.scheduler,
|
| 1045 |
+
gns,
|
| 1046 |
+
temp_grouping=True,
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
# We can have multiple deps with the same name.
|
| 1050 |
+
# As we ignore WeakDep(is_fake=True) =>
|
| 1051 |
+
# filter them out first to avoid overwriting of real dep.
|
| 1052 |
+
data_deps = {
|
| 1053 |
+
d.name: d
|
| 1054 |
+
for d in candidate.unmet_dependencies
|
| 1055 |
+
if not _is_fake_dep(d)
|
| 1056 |
+
}
|
| 1057 |
+
|
| 1058 |
+
group_outs = group.get_outputs()
|
| 1059 |
+
data_dep = None
|
| 1060 |
+
for o in group_outs:
|
| 1061 |
+
if d := data_deps.get(o.get_name(), None):
|
| 1062 |
+
data_dep = d
|
| 1063 |
+
break
|
| 1064 |
+
# 1. If we have data_dep - we can not swap => trying to group
|
| 1065 |
+
# 2. If swap candidate and current node both contain collectives => trying to group
|
| 1066 |
+
if data_dep is not None or (
|
| 1067 |
+
both_contain_comms := (
|
| 1068 |
+
contains_collective(group) and contains_collective(candidate)
|
| 1069 |
+
)
|
| 1070 |
+
):
|
| 1071 |
+
|
| 1072 |
+
def is_groupable(snode):
|
| 1073 |
+
# We do not want to group with collectives to not reorder them forward.
|
| 1074 |
+
if contains_collective(snode):
|
| 1075 |
+
return (
|
| 1076 |
+
False,
|
| 1077 |
+
f"candidate contains collective {snode.get_name()}",
|
| 1078 |
+
)
|
| 1079 |
+
if contains_gemm_like(snode):
|
| 1080 |
+
return (
|
| 1081 |
+
False,
|
| 1082 |
+
f"candidate contains gemm_like {snode.get_name()}",
|
| 1083 |
+
)
|
| 1084 |
+
return True, None
|
| 1085 |
+
|
| 1086 |
+
is_grp, grp_reason = is_groupable(candidate)
|
| 1087 |
+
if is_grp:
|
| 1088 |
+
group_tail = candidate
|
| 1089 |
+
group_peak_memory = max(
|
| 1090 |
+
group_peak_memory, _curr_memory[candidate][0]
|
| 1091 |
+
)
|
| 1092 |
+
info.grouped += 1
|
| 1093 |
+
info.grouped_info = _group_names(gns)
|
| 1094 |
+
candidate = _next[candidate]
|
| 1095 |
+
continue
|
| 1096 |
+
elif (data_dep is None) and both_contain_comms:
|
| 1097 |
+
info.limiting_factor = (
|
| 1098 |
+
f"collective ordering {_group_names(gns)}"
|
| 1099 |
+
f" with candidate:{candidate.get_name()}"
|
| 1100 |
+
)
|
| 1101 |
+
break
|
| 1102 |
+
else:
|
| 1103 |
+
info.limiting_factor = (
|
| 1104 |
+
f"data dependency {data_dep}(dep_names:{list(data_deps.keys())})"
|
| 1105 |
+
f"\n candidate:{candidate.get_name()}(os:{[candidate.get_buffer_names()]})"
|
| 1106 |
+
f"dep on {gns}"
|
| 1107 |
+
f"\n outs:{[o.get_name() for o in group_outs]}"
|
| 1108 |
+
f"\n non_group_reason:{grp_reason}"
|
| 1109 |
+
)
|
| 1110 |
+
break
|
| 1111 |
+
candidate_allocfree: SNodeMemory = snodes_allocfree[candidate]
|
| 1112 |
+
candidate_delta_mem = (
|
| 1113 |
+
candidate_allocfree.size_alloc - candidate_allocfree.size_free
|
| 1114 |
+
)
|
| 1115 |
+
# [group] candidate -> candidate [group]
|
| 1116 |
+
# Check for buffers with successors in group and candidate last successor
|
| 1117 |
+
#
|
| 1118 |
+
# Buf that changes its last use snode,
|
| 1119 |
+
# It was deallocated by candidate,
|
| 1120 |
+
# but after swap it will be deallocated by group node.
|
| 1121 |
+
group_n_to_bufs_after_swap_dealloc_instead_of_candidate: dict[
|
| 1122 |
+
BaseSchedulerNode, list[Union[FreeableInputBuffer, SchedulerBuffer]]
|
| 1123 |
+
] = defaultdict(list)
|
| 1124 |
+
for (
|
| 1125 |
+
buf,
|
| 1126 |
+
snode_last_use,
|
| 1127 |
+
) in buf_to_snode_last_use.items():
|
| 1128 |
+
succ_nodes = buf.mpi_buffer.succ_nodes
|
| 1129 |
+
if snode_last_use != candidate: # noqa: E711
|
| 1130 |
+
continue
|
| 1131 |
+
# candidate is last use of buf
|
| 1132 |
+
last_succ_gn = None
|
| 1133 |
+
for gn in gns:
|
| 1134 |
+
if gn in succ_nodes:
|
| 1135 |
+
last_succ_gn = gn
|
| 1136 |
+
if last_succ_gn is None:
|
| 1137 |
+
continue
|
| 1138 |
+
|
| 1139 |
+
# gn has successors of buf that after potential swap will become
|
| 1140 |
+
# last use of buf and start deallocating buf instead of candidate
|
| 1141 |
+
group_n_to_bufs_after_swap_dealloc_instead_of_candidate[
|
| 1142 |
+
last_succ_gn
|
| 1143 |
+
].append(buf)
|
| 1144 |
+
|
| 1145 |
+
potential_peak, _post_alloc_update, _size_free_delta_update = (
|
| 1146 |
+
_calculate_potential_peak_memory(
|
| 1147 |
+
candidate,
|
| 1148 |
+
gns,
|
| 1149 |
+
group_n_to_bufs_after_swap_dealloc_instead_of_candidate,
|
| 1150 |
+
)
|
| 1151 |
+
)
|
| 1152 |
+
if potential_peak > peak_memory:
|
| 1153 |
+
info.limiting_factor = (
|
| 1154 |
+
f"peak memory new:{potential_peak} vs base:{peak_memory}"
|
| 1155 |
+
)
|
| 1156 |
+
break
|
| 1157 |
+
|
| 1158 |
+
info.moves += 1
|
| 1159 |
+
info.moves_info += f"+{candidate.get_name()}"
|
| 1160 |
+
|
| 1161 |
+
_perform_double_linked_list_swap(candidate, group_head, group_tail)
|
| 1162 |
+
|
| 1163 |
+
_update_memory_tracking_after_swap(
|
| 1164 |
+
candidate,
|
| 1165 |
+
gns,
|
| 1166 |
+
group_n_to_bufs_after_swap_dealloc_instead_of_candidate,
|
| 1167 |
+
_post_alloc_update,
|
| 1168 |
+
_size_free_delta_update,
|
| 1169 |
+
)
|
| 1170 |
+
|
| 1171 |
+
if debug_iterative_memory_recompute:
|
| 1172 |
+
from .comms_debug import _debug_iterative_memory_recompute
|
| 1173 |
+
|
| 1174 |
+
iterative_recompute_error = _debug_iterative_memory_recompute(
|
| 1175 |
+
candidate,
|
| 1176 |
+
gns,
|
| 1177 |
+
_group_names(gns),
|
| 1178 |
+
_group_nodes(_head, None),
|
| 1179 |
+
name_to_freeable_input_buf,
|
| 1180 |
+
graph_outputs,
|
| 1181 |
+
peak_memory,
|
| 1182 |
+
_curr_memory,
|
| 1183 |
+
snodes_allocfree,
|
| 1184 |
+
"sink_waits_iterative",
|
| 1185 |
+
group_n_to_bufs_after_swap_dealloc_instead_of_candidate,
|
| 1186 |
+
)
|
| 1187 |
+
if iterative_recompute_error:
|
| 1188 |
+
break
|
| 1189 |
+
|
| 1190 |
+
candidate = _next[group_tail]
|
| 1191 |
+
curr = _prev[curr] # type: ignore[assignment]
|
| 1192 |
+
|
| 1193 |
+
headers = [
|
| 1194 |
+
"Wait node",
|
| 1195 |
+
"grouped",
|
| 1196 |
+
"grouped_info",
|
| 1197 |
+
"moves",
|
| 1198 |
+
"moves_info",
|
| 1199 |
+
"limiting factor",
|
| 1200 |
+
]
|
| 1201 |
+
rows = [
|
| 1202 |
+
[
|
| 1203 |
+
node_summary(snode),
|
| 1204 |
+
info.grouped,
|
| 1205 |
+
info.grouped_info,
|
| 1206 |
+
info.moves,
|
| 1207 |
+
info.moves_info,
|
| 1208 |
+
info.limiting_factor,
|
| 1209 |
+
]
|
| 1210 |
+
for snode, info in stats.items()
|
| 1211 |
+
]
|
| 1212 |
+
log_str = ""
|
| 1213 |
+
if importlib.util.find_spec("tabulate"):
|
| 1214 |
+
from tabulate import tabulate
|
| 1215 |
+
|
| 1216 |
+
log_str += tabulate(
|
| 1217 |
+
rows,
|
| 1218 |
+
headers=headers,
|
| 1219 |
+
)
|
| 1220 |
+
else:
|
| 1221 |
+
log_str += "Please `pip install tabulate` to nicely render overlap stats.\n"
|
| 1222 |
+
log_str += str(headers) + "\n"
|
| 1223 |
+
log_str += "\n".join(map(str, rows))
|
| 1224 |
+
overlap_log.info(log_str)
|
| 1225 |
+
new_snodes = _group_nodes(_head, None)
|
| 1226 |
+
assert len(new_snodes) == original_snodes_num
|
| 1227 |
+
new_peak_memory, _, _, _ = estimate_peak_memory_allocfree(
|
| 1228 |
+
new_snodes, name_to_freeable_input_buf, graph_outputs
|
| 1229 |
+
)
|
| 1230 |
+
log_str += f"\n sink_waits_iterative peak_memory_before:{peak_memory}"
|
| 1231 |
+
log_str += f"\n sink_waits_iterative peak_memory_after:{new_peak_memory}"
|
| 1232 |
+
trace_structured(
|
| 1233 |
+
"artifact",
|
| 1234 |
+
metadata_fn=lambda: {
|
| 1235 |
+
"name": "sink_waits_iterative_info",
|
| 1236 |
+
"encoding": "string",
|
| 1237 |
+
},
|
| 1238 |
+
payload_fn=lambda: log_str,
|
| 1239 |
+
)
|
| 1240 |
+
return new_snodes, stats
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
def sink_waits_iterative(
|
| 1244 |
+
snodes: list[BaseSchedulerNode],
|
| 1245 |
+
) -> list[BaseSchedulerNode]:
|
| 1246 |
+
return _sink_waits_iterative_internal(snodes)[0]
|
| 1247 |
+
|
| 1248 |
+
|
| 1249 |
+
def estimate_op_runtime(snode: BaseSchedulerNode) -> float:
|
| 1250 |
+
"""
|
| 1251 |
+
Returns estimated op runtime in nanoseconds (ns)
|
| 1252 |
+
"""
|
| 1253 |
+
if config.estimate_op_runtime == "default":
|
| 1254 |
+
runtime = snode.get_estimated_runtime()
|
| 1255 |
+
else:
|
| 1256 |
+
assert callable(config.estimate_op_runtime)
|
| 1257 |
+
runtime = config.estimate_op_runtime(snode)
|
| 1258 |
+
return runtime
|
| 1259 |
+
|
| 1260 |
+
|
| 1261 |
+
def node_summary(snode):
|
| 1262 |
+
snodes = snode.get_nodes()
|
| 1263 |
+
if len(snodes) == 1:
|
| 1264 |
+
detail = ""
|
| 1265 |
+
if isinstance(snode.node, (ir.ExternKernelOut, ir._CollectiveKernel)):
|
| 1266 |
+
outs_str = f"outs:{[o.get_name() for o in snode.get_outputs()]}"
|
| 1267 |
+
ins_str = f"ins:{[d.name for d in snode.unmet_dependencies]}"
|
| 1268 |
+
detail = f" {snode.get_name()} ({snode.node.python_kernel_name})\n {outs_str}\n ({ins_str})"
|
| 1269 |
+
layouts = [child.node.get_output_spec() for child in snode.get_nodes()]
|
| 1270 |
+
out_tensor_info = ",".join(
|
| 1271 |
+
[
|
| 1272 |
+
f" (size={layout.size}, stride={layout.stride})"
|
| 1273 |
+
if isinstance(layout, ir.Layout)
|
| 1274 |
+
else ""
|
| 1275 |
+
for layout in layouts
|
| 1276 |
+
]
|
| 1277 |
+
)
|
| 1278 |
+
try:
|
| 1279 |
+
node_name = snode.node.maybe_get_name()
|
| 1280 |
+
except AttributeError:
|
| 1281 |
+
# TODO: node_summary was written without FusedSchedulerNode in mind, generally needs to be hardened
|
| 1282 |
+
node_name = ""
|
| 1283 |
+
return f"{snode.node.__class__.__name__}{detail}{out_tensor_info} ({node_name} ({snode.get_estimated_runtime():.0f} ns)"
|
| 1284 |
+
|
| 1285 |
+
# Flatten the summaries for Fused/Foreach/Grouped nodes
|
| 1286 |
+
summaries = []
|
| 1287 |
+
for child_snode in snodes:
|
| 1288 |
+
summaries.append(node_summary(child_snode))
|
| 1289 |
+
return f"{snode.__class__.__name__}: {', '.join(summaries)}"
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
def visualize_overlap(order):
|
| 1293 |
+
# TODO - this function probably doesn't do a very good job estimating the runtime because it doesn't carefully model
|
| 1294 |
+
# streams and overlap. For now its mostly useful as a debug visualization.
|
| 1295 |
+
|
| 1296 |
+
total_est_runtime: float = 0.0
|
| 1297 |
+
cur_comm_node = None
|
| 1298 |
+
|
| 1299 |
+
def step_log(step, msg):
|
| 1300 |
+
overlap_log.debug(f"{step:>6}: {msg}") # noqa: G004
|
| 1301 |
+
|
| 1302 |
+
for step, snode in enumerate(order):
|
| 1303 |
+
if cur_comm_node is None:
|
| 1304 |
+
if contains_collective(snode):
|
| 1305 |
+
total_est_runtime += estimate_op_runtime(snode)
|
| 1306 |
+
cur_comm_node = snode.node
|
| 1307 |
+
elif is_wait(snode.node):
|
| 1308 |
+
# raise AssertionError(
|
| 1309 |
+
# "Wait is not expected when there is no collective running"
|
| 1310 |
+
# )
|
| 1311 |
+
pass
|
| 1312 |
+
else: # exposed compute op
|
| 1313 |
+
total_est_runtime += estimate_op_runtime(snode)
|
| 1314 |
+
step_log(step, f"{node_summary(snode)}")
|
| 1315 |
+
else: # cur_comm_node is not None
|
| 1316 |
+
if contains_collective(snode):
|
| 1317 |
+
total_est_runtime += estimate_op_runtime(snode)
|
| 1318 |
+
cur_comm_node = snode.node
|
| 1319 |
+
step_log(step, f"{node_summary(snode)}") # noqa: G004
|
| 1320 |
+
elif is_wait(snode.node): # end of this comm op
|
| 1321 |
+
step_log(step, f"{node_summary(snode)}")
|
| 1322 |
+
cur_comm_node = None
|
| 1323 |
+
else: # overlapped compute op
|
| 1324 |
+
step_log(step, f"| {node_summary(snode)}")
|
| 1325 |
+
overlap_log.debug(
|
| 1326 |
+
f"Est. runtime (ms): {total_est_runtime / 1000 / 1000}" # noqa: G004
|
| 1327 |
+
)
|
| 1328 |
+
|
| 1329 |
+
|
| 1330 |
+
def reorder_compute_and_comm_for_overlap(
|
| 1331 |
+
snodes: list[BaseSchedulerNode],
|
| 1332 |
+
) -> list[BaseSchedulerNode]:
|
| 1333 |
+
order = snodes
|
| 1334 |
+
graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys())
|
| 1335 |
+
graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names())
|
| 1336 |
+
for p in config.reorder_for_compute_comm_overlap_passes:
|
| 1337 |
+
if isinstance(p, str) and p in globals():
|
| 1338 |
+
p = globals()[p] # it is a builtin pass
|
| 1339 |
+
assert callable(p), (
|
| 1340 |
+
f"Invalid reorder_compute_and_comm_for_overlap pass: {p} is not callable"
|
| 1341 |
+
)
|
| 1342 |
+
peak_memory, _ = estimate_peak_memory(
|
| 1343 |
+
snodes, get_freeable_input_buf(snodes, graph_inputs), graph_outputs
|
| 1344 |
+
)
|
| 1345 |
+
if torch.distributed.get_rank() == 0:
|
| 1346 |
+
overlap_log.debug(
|
| 1347 |
+
f"==== Visualize overlap before reordering pass {p}, {peak_memory=} ====" # noqa: G004
|
| 1348 |
+
)
|
| 1349 |
+
try:
|
| 1350 |
+
visualize_overlap(order)
|
| 1351 |
+
except Exception as e:
|
| 1352 |
+
overlap_log.debug("", exc_info=e)
|
| 1353 |
+
t0 = time.time()
|
| 1354 |
+
order = p(order) # type: ignore[operator]
|
| 1355 |
+
t = time.time() - t0
|
| 1356 |
+
if torch.distributed.get_rank() == 0:
|
| 1357 |
+
overlap_log.debug(
|
| 1358 |
+
f"==== Visualize overlap after reordering pass {p} (ran in {t} sec)====" # noqa: G004
|
| 1359 |
+
)
|
| 1360 |
+
try:
|
| 1361 |
+
visualize_overlap(order)
|
| 1362 |
+
except Exception as e:
|
| 1363 |
+
overlap_log.debug("", exc_info=e)
|
| 1364 |
+
peak_memory, _ = estimate_peak_memory(
|
| 1365 |
+
snodes, get_freeable_input_buf(snodes, graph_inputs), graph_outputs
|
| 1366 |
+
)
|
| 1367 |
+
print(f"final {peak_memory=}")
|
| 1368 |
+
return order
|
| 1369 |
+
|
| 1370 |
+
|
| 1371 |
+
def remove_fsdp2_unsharded_param_graph_input_usage(graph: torch.fx.Graph):
|
| 1372 |
+
"""
|
| 1373 |
+
This FX graph pass replaces uses of FSDP2 unsharded params with their corresponding
|
| 1374 |
+
graph intermediates that were fsdp.copy_ into the unsharded params in the original graph.
|
| 1375 |
+
|
| 1376 |
+
NOTE: Can only apply this pass to any of the FSDP2 unsharded params that have this pattern
|
| 1377 |
+
(or repetition of): `resize_(full) -> copy_ -> resize_(0)`. Because of this, for partial-graph case
|
| 1378 |
+
where `resize_(full) -> copy_` is in one graph and `resize_(0)` is in another graph, we can't
|
| 1379 |
+
remove these resize and copy ops and thus we will have worse performance there.
|
| 1380 |
+
|
| 1381 |
+
In other words, "do we try to remove all the resize_(full) -> copy_ -> resize_(0) nodes for this unsharded param"
|
| 1382 |
+
is actually a per-unsharded-param decision, since for each unsharded param, we look at its resize sequence pattern
|
| 1383 |
+
(in `check_resize_pattern()`) to determine if its set of resize and copy nodes can be removed.
|
| 1384 |
+
"""
|
| 1385 |
+
node_list = list(graph.nodes)
|
| 1386 |
+
|
| 1387 |
+
# Find all graph inputs and their resize counts
|
| 1388 |
+
graph_input_to_resized_to_full_node_idxes = defaultdict(list)
|
| 1389 |
+
graph_input_to_resized_to_0_node_idxes = defaultdict(list)
|
| 1390 |
+
for idx, node in enumerate(node_list):
|
| 1391 |
+
if (
|
| 1392 |
+
node.op == "call_function"
|
| 1393 |
+
and node.target == torch.ops.inductor.resize_storage_bytes_.default
|
| 1394 |
+
):
|
| 1395 |
+
assert node.args[0].op == "placeholder", f"""\
|
| 1396 |
+
Resize can only operate on graph inputs, but got {node} which is resizing non-graph-input {node.args[0]}
|
| 1397 |
+
"""
|
| 1398 |
+
graph_input = node.args[0]
|
| 1399 |
+
new_size = node.args[1]
|
| 1400 |
+
if new_size > 0:
|
| 1401 |
+
graph_input_to_resized_to_full_node_idxes[graph_input].append(idx)
|
| 1402 |
+
else:
|
| 1403 |
+
graph_input_to_resized_to_0_node_idxes[graph_input].append(idx)
|
| 1404 |
+
|
| 1405 |
+
def check_resize_pattern(graph_input):
|
| 1406 |
+
# Check the number of resize-to-full and resize-to-0 nodes are equal,
|
| 1407 |
+
# and that for each (resize-to-full, resize-to-0) pair, the resize-to-full node
|
| 1408 |
+
# always happens before the resize-to-0 node.
|
| 1409 |
+
# This is the precondition for being able to remove all the resize and copy nodes
|
| 1410 |
+
# for this specific unsharded param.
|
| 1411 |
+
resized_to_full_idxes = graph_input_to_resized_to_full_node_idxes.get(
|
| 1412 |
+
graph_input, []
|
| 1413 |
+
)
|
| 1414 |
+
resized_to_0_idxes = graph_input_to_resized_to_0_node_idxes.get(graph_input, [])
|
| 1415 |
+
|
| 1416 |
+
if not len(resized_to_full_idxes) == len(resized_to_0_idxes):
|
| 1417 |
+
log.warning(
|
| 1418 |
+
f"""
|
| 1419 |
+
Unequal number of resize-to-full and resize-to-0 nodes for graph input {graph_input}:
|
| 1420 |
+
{len(resized_to_full_idxes)} vs. {len(resized_to_0_idxes)}.
|
| 1421 |
+
Skipping `remove_fsdp2_unsharded_param_graph_input_usage` FX graph pass.
|
| 1422 |
+
""" # noqa: G004
|
| 1423 |
+
)
|
| 1424 |
+
return False
|
| 1425 |
+
|
| 1426 |
+
# Check the sequence: (resize_to_full -> resize_to_0)+
|
| 1427 |
+
for resize_to_full_idx, resize_to_0_idx in zip(
|
| 1428 |
+
resized_to_full_idxes, resized_to_0_idxes
|
| 1429 |
+
):
|
| 1430 |
+
if resize_to_full_idx >= resize_to_0_idx:
|
| 1431 |
+
log.warning(
|
| 1432 |
+
f"""
|
| 1433 |
+
For graph input {graph_input}: resize-to-full node {node_list[resize_to_full_idx]} at index {resize_to_full_idx}
|
| 1434 |
+
happens after resize-to-0 node {node_list[resize_to_0_idx]} at index {resize_to_0_idx}.
|
| 1435 |
+
Skipping `remove_fsdp2_unsharded_param_graph_input_usage` FX graph pass for that unsharded param.
|
| 1436 |
+
""" # noqa: G004
|
| 1437 |
+
)
|
| 1438 |
+
return False
|
| 1439 |
+
return True
|
| 1440 |
+
|
| 1441 |
+
# Find all eligible unsharded params and their corresponding graph intermediates.
|
| 1442 |
+
unsharded_param_to_fsdp_copy_node_idxes = defaultdict(list)
|
| 1443 |
+
for idx, node in enumerate(node_list):
|
| 1444 |
+
if node.op == "call_function" and node.target == torch.ops.fsdp.copy_.default:
|
| 1445 |
+
fsdp_copy_node = node
|
| 1446 |
+
unsharded_param = node.args[0]
|
| 1447 |
+
assert unsharded_param.op == "placeholder", f"""
|
| 1448 |
+
Assumed all FSDP2 `unsharded_param`s to be graph input, but it's not true!
|
| 1449 |
+
Offending node: {unsharded_param}. Graph: {graph}
|
| 1450 |
+
"""
|
| 1451 |
+
if check_resize_pattern(unsharded_param):
|
| 1452 |
+
unsharded_param_to_fsdp_copy_node_idxes[unsharded_param].append(idx)
|
| 1453 |
+
|
| 1454 |
+
def is_allowed_mutation(node):
|
| 1455 |
+
return (
|
| 1456 |
+
node.target == torch.ops.fsdp.copy_.default
|
| 1457 |
+
or node.target == torch.ops.inductor.resize_storage_bytes_.default
|
| 1458 |
+
)
|
| 1459 |
+
|
| 1460 |
+
def is_node_mutating_unsharded_param_or_its_alias(node, unsharded_params):
|
| 1461 |
+
# Check whether the node is mutating any of the unsharded params or their aliases.
|
| 1462 |
+
mutated_arg_idxes = (
|
| 1463 |
+
[
|
| 1464 |
+
i
|
| 1465 |
+
for i, x in enumerate(node.target._schema.arguments)
|
| 1466 |
+
if x.alias_info is not None and x.alias_info.is_write
|
| 1467 |
+
]
|
| 1468 |
+
if isinstance(node.target, torch._ops.OpOverload)
|
| 1469 |
+
else []
|
| 1470 |
+
)
|
| 1471 |
+
mutated_node_arg_storages = OrderedSet(
|
| 1472 |
+
[
|
| 1473 |
+
StorageWeakRef(node.args[i].meta["val"].untyped_storage())
|
| 1474 |
+
for i in mutated_arg_idxes
|
| 1475 |
+
]
|
| 1476 |
+
)
|
| 1477 |
+
storages_of_unsharded_params = OrderedSet(
|
| 1478 |
+
[
|
| 1479 |
+
StorageWeakRef(unsharded_param.meta["val"].untyped_storage())
|
| 1480 |
+
for unsharded_param in unsharded_params
|
| 1481 |
+
]
|
| 1482 |
+
)
|
| 1483 |
+
return len(mutated_node_arg_storages & storages_of_unsharded_params) > 0
|
| 1484 |
+
|
| 1485 |
+
# Check no user mutation on any unsharded_param
|
| 1486 |
+
for node in node_list:
|
| 1487 |
+
if (
|
| 1488 |
+
node.op == "call_function"
|
| 1489 |
+
and isinstance(node.target, torch._ops.OpOverload)
|
| 1490 |
+
and node.target._schema.is_mutable
|
| 1491 |
+
and not is_allowed_mutation(node)
|
| 1492 |
+
):
|
| 1493 |
+
assert not is_node_mutating_unsharded_param_or_its_alias(
|
| 1494 |
+
node, unsharded_param_to_fsdp_copy_node_idxes.keys()
|
| 1495 |
+
), f"""\
|
| 1496 |
+
User mutation on FSDP2 unsharded param is not allowed when Traceable FSDP2 is used. Violating node: {node}
|
| 1497 |
+
"""
|
| 1498 |
+
|
| 1499 |
+
# For each `fsdp.copy_(unsharded_param, Y)`, replace downstream usage of `unsharded_param` with `Y`.
|
| 1500 |
+
#
|
| 1501 |
+
# NOTE: Because of "layer reuse" use case, there could be multiple `fsdp.copy_` to the same `unsharded_param` graph input.
|
| 1502 |
+
# e.g.
|
| 1503 |
+
# ```
|
| 1504 |
+
# fsdp_copy_1 = fsdp.copy_(unsharded_param_1, Y1)
|
| 1505 |
+
# ... (use of unsharded_param_1) -> Subgraph 1
|
| 1506 |
+
# fsdp_copy_2 = fsdp.copy_(unsharded_param_1, Y2)
|
| 1507 |
+
# ... (use of unsharded_param_1) -> Subgraph 2
|
| 1508 |
+
# fsdp_copy_3 = fsdp.copy_(unsharded_param_1, Y3)
|
| 1509 |
+
# ... (use of unsharded_param_1) -> Subgraph 3
|
| 1510 |
+
# ```
|
| 1511 |
+
# We must do the replacement only within each subgraph.
|
| 1512 |
+
for (
|
| 1513 |
+
unsharded_param,
|
| 1514 |
+
fsdp_copy_node_idxes,
|
| 1515 |
+
) in unsharded_param_to_fsdp_copy_node_idxes.items():
|
| 1516 |
+
for i, fsdp_copy_node_idx in enumerate(fsdp_copy_node_idxes):
|
| 1517 |
+
fsdp_copy_node = node_list[fsdp_copy_node_idx]
|
| 1518 |
+
assert fsdp_copy_node.args[0] is unsharded_param
|
| 1519 |
+
_, replacement = fsdp_copy_node.args
|
| 1520 |
+
# subgraph_start_idx is exclusive
|
| 1521 |
+
subgraph_start_idx = fsdp_copy_node_idx + 1
|
| 1522 |
+
# subgraph_end_idx is exclusive (also intentionally don't replace args in return op)
|
| 1523 |
+
subgraph_end_idx = (
|
| 1524 |
+
fsdp_copy_node_idxes[i + 1]
|
| 1525 |
+
if i < len(fsdp_copy_node_idxes) - 1
|
| 1526 |
+
else len(node_list) - 1
|
| 1527 |
+
)
|
| 1528 |
+
subgraph_nodes = node_list[subgraph_start_idx:subgraph_end_idx]
|
| 1529 |
+
assert not any(
|
| 1530 |
+
is_node_mutating_unsharded_param_or_its_alias(node, [unsharded_param])
|
| 1531 |
+
for node in subgraph_nodes
|
| 1532 |
+
), f"""\
|
| 1533 |
+
Assumed no ops mutating unsharded param {unsharded_param} in subgraph {subgraph_nodes}, but it's not true!
|
| 1534 |
+
Graph: {graph}
|
| 1535 |
+
"""
|
| 1536 |
+
for node in subgraph_nodes:
|
| 1537 |
+
if (
|
| 1538 |
+
node.op == "call_function"
|
| 1539 |
+
and unsharded_param in node.args
|
| 1540 |
+
and node.target != torch.ops.inductor.resize_storage_bytes_.default
|
| 1541 |
+
): # TODO(yf225): implement replacement in kwargs
|
| 1542 |
+
new_args = tuple(
|
| 1543 |
+
replacement if arg is unsharded_param else arg
|
| 1544 |
+
for arg in node.args
|
| 1545 |
+
)
|
| 1546 |
+
node.args = new_args
|
| 1547 |
+
|
| 1548 |
+
# Delete `fsdp.copy_(unsharded_param, Y)` nodes
|
| 1549 |
+
for (
|
| 1550 |
+
unsharded_param,
|
| 1551 |
+
fsdp_copy_node_idxes,
|
| 1552 |
+
) in unsharded_param_to_fsdp_copy_node_idxes.items():
|
| 1553 |
+
for i, fsdp_copy_node_idx in enumerate(fsdp_copy_node_idxes):
|
| 1554 |
+
fsdp_copy_node = node_list[fsdp_copy_node_idx]
|
| 1555 |
+
graph.erase_node(fsdp_copy_node)
|
| 1556 |
+
|
| 1557 |
+
# Delete `resize_(unsharded_param, ...)` nodes
|
| 1558 |
+
for node in node_list:
|
| 1559 |
+
if (
|
| 1560 |
+
node.op == "call_function"
|
| 1561 |
+
and node.target == torch.ops.inductor.resize_storage_bytes_.default
|
| 1562 |
+
and node.args[0] in unsharded_param_to_fsdp_copy_node_idxes
|
| 1563 |
+
):
|
| 1564 |
+
graph.erase_node(node)
|
| 1565 |
+
|
| 1566 |
+
|
| 1567 |
+
def reinplace_fsdp_all_gather(graph: torch.fx.Graph) -> None:
|
| 1568 |
+
try:
|
| 1569 |
+
import torch.distributed.fsdp._fully_shard._fsdp_collectives
|
| 1570 |
+
|
| 1571 |
+
assert torch.distributed.is_available()
|
| 1572 |
+
# Assert existence of these ops
|
| 1573 |
+
assert (
|
| 1574 |
+
torch.ops._c10d_functional.all_gather_into_tensor
|
| 1575 |
+
and torch.ops._c10d_functional.all_gather_into_tensor_out
|
| 1576 |
+
)
|
| 1577 |
+
except (ImportError, AttributeError, AssertionError):
|
| 1578 |
+
return
|
| 1579 |
+
|
| 1580 |
+
from .pattern_matcher import (
|
| 1581 |
+
CallFunction,
|
| 1582 |
+
KeywordArg,
|
| 1583 |
+
Match,
|
| 1584 |
+
PatternMatcherPass,
|
| 1585 |
+
register_graph_pattern,
|
| 1586 |
+
)
|
| 1587 |
+
|
| 1588 |
+
"""
|
| 1589 |
+
all_gather_copy_in = torch.ops.fsdp.all_gather_copy_in.default(...);
|
| 1590 |
+
getitem = all_gather_copy_in[0];
|
| 1591 |
+
(getitem_1 = all_gather_copy_in[1];) # optional
|
| 1592 |
+
|
| 1593 |
+
all_gather_into_tensor = torch.ops._c10d_functional.all_gather_into_tensor.default(getitem, ...);
|
| 1594 |
+
|
| 1595 |
+
->
|
| 1596 |
+
|
| 1597 |
+
all_gather_copy_in = torch.ops.fsdp.all_gather_copy_in.default(...);
|
| 1598 |
+
getitem = all_gather_copy_in[0];
|
| 1599 |
+
getitem_1 = all_gather_copy_in[1];
|
| 1600 |
+
|
| 1601 |
+
all_gather_into_tensor = torch.ops._c10d_functional.all_gather_into_tensor_out.default(getitem, ..., out=getitem_1);
|
| 1602 |
+
"""
|
| 1603 |
+
|
| 1604 |
+
def remove_unused_getitem(g):
|
| 1605 |
+
# Remove `getitem_X = all_gather_copy_in[1]` which is never used.
|
| 1606 |
+
node_list = list(g.nodes)
|
| 1607 |
+
for n in node_list:
|
| 1608 |
+
if (
|
| 1609 |
+
n.target == operator.getitem
|
| 1610 |
+
and n.args[0].target is torch.ops.fsdp.all_gather_copy_in.default
|
| 1611 |
+
and n.args[1] == 1
|
| 1612 |
+
):
|
| 1613 |
+
g.erase_node(n)
|
| 1614 |
+
|
| 1615 |
+
graph_pass = PatternMatcherPass()
|
| 1616 |
+
|
| 1617 |
+
@register_graph_pattern(
|
| 1618 |
+
CallFunction(
|
| 1619 |
+
torch.ops._c10d_functional.all_gather_into_tensor.default,
|
| 1620 |
+
CallFunction(
|
| 1621 |
+
operator.getitem,
|
| 1622 |
+
CallFunction(
|
| 1623 |
+
torch.ops.fsdp.all_gather_copy_in.default,
|
| 1624 |
+
KeywordArg("all_gather_inputs"),
|
| 1625 |
+
KeywordArg("all_gather_output"),
|
| 1626 |
+
KeywordArg("inp_split_sizes"),
|
| 1627 |
+
KeywordArg("all_gather_input_numel"),
|
| 1628 |
+
KeywordArg("rank"),
|
| 1629 |
+
),
|
| 1630 |
+
KeywordArg("item_idx"),
|
| 1631 |
+
),
|
| 1632 |
+
KeywordArg("group_size"),
|
| 1633 |
+
KeywordArg("group_name"),
|
| 1634 |
+
),
|
| 1635 |
+
pass_dict=graph_pass,
|
| 1636 |
+
extra_check=lambda match: match.kwargs["item_idx"] == 0,
|
| 1637 |
+
)
|
| 1638 |
+
def reinplace_all_gather(match: Match, *args, **kwargs):
|
| 1639 |
+
def repl(
|
| 1640 |
+
*args,
|
| 1641 |
+
):
|
| 1642 |
+
copy_in_args = args[:-2]
|
| 1643 |
+
group_size = args[-2]
|
| 1644 |
+
group_name = args[-1]
|
| 1645 |
+
all_gather_copy_in = torch.ops.fsdp.all_gather_copy_in.default(
|
| 1646 |
+
*copy_in_args
|
| 1647 |
+
)
|
| 1648 |
+
getitem = all_gather_copy_in[0]
|
| 1649 |
+
getitem_1 = all_gather_copy_in[1]
|
| 1650 |
+
all_gather_into_tensor = (
|
| 1651 |
+
torch.ops._c10d_functional.all_gather_into_tensor_out.default(
|
| 1652 |
+
getitem, group_size, group_name, out=getitem_1
|
| 1653 |
+
)
|
| 1654 |
+
)
|
| 1655 |
+
return all_gather_into_tensor
|
| 1656 |
+
|
| 1657 |
+
match.replace_by_example(
|
| 1658 |
+
repl,
|
| 1659 |
+
[
|
| 1660 |
+
kwargs["all_gather_inputs"],
|
| 1661 |
+
kwargs["all_gather_output"],
|
| 1662 |
+
kwargs["inp_split_sizes"],
|
| 1663 |
+
kwargs["all_gather_input_numel"],
|
| 1664 |
+
kwargs["rank"],
|
| 1665 |
+
kwargs["group_size"],
|
| 1666 |
+
kwargs["group_name"],
|
| 1667 |
+
],
|
| 1668 |
+
)
|
| 1669 |
+
|
| 1670 |
+
remove_unused_getitem(graph)
|
| 1671 |
+
graph_pass.apply(graph) # type: ignore[arg-type]
|
| 1672 |
+
|
| 1673 |
+
|
| 1674 |
+
def get_op_idx(snode):
|
| 1675 |
+
assert not isinstance(
|
| 1676 |
+
snode,
|
| 1677 |
+
(
|
| 1678 |
+
torch._inductor.scheduler.FusedSchedulerNode,
|
| 1679 |
+
torch._inductor.scheduler.GroupedSchedulerNode,
|
| 1680 |
+
),
|
| 1681 |
+
)
|
| 1682 |
+
return int(snode.get_name()[2:])
|
| 1683 |
+
|
| 1684 |
+
|
| 1685 |
+
def enforce_comm_ordering_for_fsdp(
|
| 1686 |
+
snodes: list[torch._inductor.scheduler.BaseSchedulerNode],
|
| 1687 |
+
name_to_buf: dict[str, torch._inductor.scheduler.SchedulerBuffer],
|
| 1688 |
+
name_to_fused_node: dict[str, BaseSchedulerNode],
|
| 1689 |
+
) -> list[torch._inductor.scheduler.BaseSchedulerNode]:
|
| 1690 |
+
from . import scheduler
|
| 1691 |
+
|
| 1692 |
+
new_order: list[BaseSchedulerNode] = []
|
| 1693 |
+
scheduled = OrderedSet[Any]()
|
| 1694 |
+
ag_exists = False
|
| 1695 |
+
rs_exists = False
|
| 1696 |
+
ag_grouped_node_to_wait_grouped_node = {}
|
| 1697 |
+
rs_grouped_node_to_wait_grouped_node = {}
|
| 1698 |
+
snode_name_to_final_snode = {}
|
| 1699 |
+
|
| 1700 |
+
def _create_group_node(snodes_to_group):
|
| 1701 |
+
group_node = scheduler.GroupedSchedulerNode.create(snodes_to_group)
|
| 1702 |
+
for snode in snodes_to_group:
|
| 1703 |
+
snode_name_to_final_snode[snode.get_name()] = group_node
|
| 1704 |
+
snode_name_to_final_snode[group_node.get_name()] = group_node
|
| 1705 |
+
return group_node
|
| 1706 |
+
|
| 1707 |
+
# Create grouped nodes for specific sets of ops
|
| 1708 |
+
for snode in snodes:
|
| 1709 |
+
# Case 1: Handle AllGather
|
| 1710 |
+
if is_collective(
|
| 1711 |
+
snode.node, op=torch.ops._c10d_functional.all_gather_into_tensor_out.default
|
| 1712 |
+
) and any(
|
| 1713 |
+
is_fallback_op(
|
| 1714 |
+
name_to_fused_node[x].node, torch.ops.fsdp.all_gather_copy_in.default
|
| 1715 |
+
)
|
| 1716 |
+
for x in snode.ancestors
|
| 1717 |
+
):
|
| 1718 |
+
ag_exists = True
|
| 1719 |
+
ag_snode = snode
|
| 1720 |
+
ag_related_snode_set: OrderedSet[scheduler.BaseSchedulerNode] = OrderedSet()
|
| 1721 |
+
|
| 1722 |
+
# Find the "cast + copy_in + getitem + all_gather" code block
|
| 1723 |
+
find_recursive_deps_of_node(
|
| 1724 |
+
ag_snode,
|
| 1725 |
+
ag_related_snode_set,
|
| 1726 |
+
name_to_buf,
|
| 1727 |
+
name_to_fused_node,
|
| 1728 |
+
)
|
| 1729 |
+
|
| 1730 |
+
# Find the "all_gather + all_gather_wait_tensor + copy_out" code block
|
| 1731 |
+
allowed_ops = OrderedSet(
|
| 1732 |
+
[
|
| 1733 |
+
torch.ops._c10d_functional.all_gather_into_tensor_out.default,
|
| 1734 |
+
torch.ops._c10d_functional.wait_tensor.default,
|
| 1735 |
+
torch.ops.fsdp.split_with_sizes_copy.default,
|
| 1736 |
+
]
|
| 1737 |
+
)
|
| 1738 |
+
find_recursive_users_of_node(
|
| 1739 |
+
ag_snode,
|
| 1740 |
+
ag_related_snode_set,
|
| 1741 |
+
name_to_buf,
|
| 1742 |
+
name_to_fused_node,
|
| 1743 |
+
criteria_cb=lambda x: not (
|
| 1744 |
+
isinstance(x, scheduler.NopKernelSchedulerNode)
|
| 1745 |
+
or (
|
| 1746 |
+
isinstance(x, scheduler.ExternKernelSchedulerNode)
|
| 1747 |
+
and x.node.op_overload in allowed_ops # type: ignore[union-attr]
|
| 1748 |
+
)
|
| 1749 |
+
),
|
| 1750 |
+
)
|
| 1751 |
+
|
| 1752 |
+
# sort nodes by original operation order
|
| 1753 |
+
ag_related_snodes = sorted(
|
| 1754 |
+
ag_related_snode_set, key=lambda x: get_op_idx(x)
|
| 1755 |
+
)
|
| 1756 |
+
|
| 1757 |
+
# In the "reuse layer" case, some ops in the 2nd all-gather code block could also
|
| 1758 |
+
# depend on ops in the 1st all-gather code block, and we don't want to group them together.
|
| 1759 |
+
end_idx_of_current_ag_block = len(ag_related_snodes)
|
| 1760 |
+
copy_out_count = 0
|
| 1761 |
+
for i in range(len(ag_related_snodes)):
|
| 1762 |
+
cur_snode = ag_related_snodes[i]
|
| 1763 |
+
if is_fallback_op(
|
| 1764 |
+
cur_snode.node, torch.ops.fsdp.split_with_sizes_copy.default
|
| 1765 |
+
):
|
| 1766 |
+
copy_out_count += 1
|
| 1767 |
+
if copy_out_count > 1:
|
| 1768 |
+
end_idx_of_current_ag_block = i
|
| 1769 |
+
break
|
| 1770 |
+
|
| 1771 |
+
ag_related_snodes = ag_related_snodes[:end_idx_of_current_ag_block]
|
| 1772 |
+
|
| 1773 |
+
# Group "cast + copy_in + getitem + all_gather" into one GroupedSchedulerNode
|
| 1774 |
+
wait_node_idx = None
|
| 1775 |
+
for i in range(len(ag_related_snodes) - 1):
|
| 1776 |
+
if isinstance(ag_related_snodes[i + 1].node, ir._WaitKernel):
|
| 1777 |
+
wait_node_idx = i + 1
|
| 1778 |
+
break
|
| 1779 |
+
assert wait_node_idx is not None
|
| 1780 |
+
ag_group_node = _create_group_node(ag_related_snodes[:wait_node_idx])
|
| 1781 |
+
|
| 1782 |
+
# Group "all_gather_wait_tensor + copy_out" into one GroupedSchedulerNode
|
| 1783 |
+
ag_wait_group_node = _create_group_node(ag_related_snodes[wait_node_idx:])
|
| 1784 |
+
|
| 1785 |
+
ag_grouped_node_to_wait_grouped_node[ag_group_node] = ag_wait_group_node
|
| 1786 |
+
|
| 1787 |
+
# Case 2: Handle ReduceScatter
|
| 1788 |
+
elif is_fallback_op(snode.node, torch.ops.fsdp.chunk_cat.default):
|
| 1789 |
+
rs_exists = True
|
| 1790 |
+
rs_snode = snode
|
| 1791 |
+
|
| 1792 |
+
# Find the "reduce_scatter copy-in + reduce_scatter comm + reduce_scatter wait" code block
|
| 1793 |
+
rs_related_snode_set: OrderedSet[scheduler.BaseSchedulerNode] = OrderedSet()
|
| 1794 |
+
find_recursive_users_of_node(
|
| 1795 |
+
rs_snode,
|
| 1796 |
+
rs_related_snode_set,
|
| 1797 |
+
name_to_buf,
|
| 1798 |
+
name_to_fused_node,
|
| 1799 |
+
)
|
| 1800 |
+
|
| 1801 |
+
# sort nodes by original operation order
|
| 1802 |
+
rs_related_snodes = sorted(
|
| 1803 |
+
rs_related_snode_set, key=lambda x: get_op_idx(x)
|
| 1804 |
+
)
|
| 1805 |
+
|
| 1806 |
+
# Group "reduce_scatter copy-in + reduce_scatter comm" into one GroupedSchedulerNode
|
| 1807 |
+
wait_node_idx = None
|
| 1808 |
+
for i in range(len(rs_related_snodes) - 1):
|
| 1809 |
+
if isinstance(rs_related_snodes[i + 1].node, ir._WaitKernel):
|
| 1810 |
+
wait_node_idx = i + 1
|
| 1811 |
+
break
|
| 1812 |
+
assert wait_node_idx is not None
|
| 1813 |
+
rs_group_node = _create_group_node(rs_related_snodes[:wait_node_idx])
|
| 1814 |
+
|
| 1815 |
+
# Group "reduce_scatter wait + related output nodes" into one GroupedSchedulerNode
|
| 1816 |
+
rs_wait_group_node = _create_group_node(rs_related_snodes[wait_node_idx:])
|
| 1817 |
+
|
| 1818 |
+
rs_grouped_node_to_wait_grouped_node[rs_group_node] = rs_wait_group_node
|
| 1819 |
+
|
| 1820 |
+
assert len(snode_name_to_final_snode) > 0
|
| 1821 |
+
if ag_exists:
|
| 1822 |
+
assert len(ag_grouped_node_to_wait_grouped_node) > 0
|
| 1823 |
+
if rs_exists:
|
| 1824 |
+
assert len(rs_grouped_node_to_wait_grouped_node) > 0
|
| 1825 |
+
|
| 1826 |
+
# Build the new node schedule, taking GroupedSchedulerNode into account
|
| 1827 |
+
for snode in snodes:
|
| 1828 |
+
if snode.get_name() in snode_name_to_final_snode:
|
| 1829 |
+
snode = snode_name_to_final_snode[snode.get_name()]
|
| 1830 |
+
if snode in scheduled:
|
| 1831 |
+
continue
|
| 1832 |
+
new_order.append(snode)
|
| 1833 |
+
scheduled.add(snode)
|
| 1834 |
+
|
| 1835 |
+
# Enforce AllGather ordering: previous AllGather's "wait then copy_out" group node must run
|
| 1836 |
+
# before next AllGather's "copy_in then AG" group node
|
| 1837 |
+
prev_ag_wait = None
|
| 1838 |
+
for ag_group_node, wait_group_node in ag_grouped_node_to_wait_grouped_node.items():
|
| 1839 |
+
if prev_ag_wait is not None:
|
| 1840 |
+
mutating_buf = next(iter(ag_group_node.get_buffer_names()))
|
| 1841 |
+
for o in prev_ag_wait.get_outputs():
|
| 1842 |
+
ag_group_node.add_fake_dep(
|
| 1843 |
+
WeakDep(o.get_name(), mutating_buf=mutating_buf, is_fake=True)
|
| 1844 |
+
)
|
| 1845 |
+
prev_ag_wait = wait_group_node
|
| 1846 |
+
|
| 1847 |
+
# Enforce ReduceScatter ordering: previous ReduceScatter's "wait" group node must run
|
| 1848 |
+
# before next ReduceScatter's "copy_in then RS" group node
|
| 1849 |
+
prev_rs_wait = None
|
| 1850 |
+
for rs_group_node, wait_group_node in rs_grouped_node_to_wait_grouped_node.items():
|
| 1851 |
+
if prev_rs_wait is not None:
|
| 1852 |
+
mutating_buf = next(iter(rs_group_node.get_buffer_names()))
|
| 1853 |
+
for o in prev_rs_wait.get_outputs():
|
| 1854 |
+
rs_group_node.add_fake_dep(
|
| 1855 |
+
WeakDep(o.get_name(), mutating_buf=mutating_buf, is_fake=True)
|
| 1856 |
+
)
|
| 1857 |
+
prev_rs_wait = wait_group_node
|
| 1858 |
+
|
| 1859 |
+
return new_order # type: ignore[return-value]
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/comms_debug.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Union
|
| 4 |
+
|
| 5 |
+
from torch._logging import trace_structured
|
| 6 |
+
|
| 7 |
+
from .memory import estimate_peak_memory_allocfree
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
if TYPE_CHECKING:
|
| 11 |
+
from torch.utils._ordered_set import OrderedSet
|
| 12 |
+
|
| 13 |
+
from .memory import FreeableInputBuffer, SNodeMemory
|
| 14 |
+
from .scheduler import BaseSchedulerNode, SchedulerBuffer
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _debug_iterative_memory_recompute(
|
| 18 |
+
candidate: BaseSchedulerNode,
|
| 19 |
+
gns: list[BaseSchedulerNode],
|
| 20 |
+
group_names: str,
|
| 21 |
+
snodes: list[BaseSchedulerNode],
|
| 22 |
+
name_to_freeable_input_buf: dict[str, FreeableInputBuffer],
|
| 23 |
+
graph_outputs: OrderedSet[str],
|
| 24 |
+
peak_memory: int,
|
| 25 |
+
iter_curr_memory: dict[BaseSchedulerNode, tuple[int, int]],
|
| 26 |
+
snodes_allocfree: dict[BaseSchedulerNode, SNodeMemory],
|
| 27 |
+
tlparse_name: str,
|
| 28 |
+
gn_to_bufs_last_use: dict[
|
| 29 |
+
BaseSchedulerNode, list[Union[FreeableInputBuffer, SchedulerBuffer]]
|
| 30 |
+
],
|
| 31 |
+
) -> bool:
|
| 32 |
+
iterative_recompute_error = False
|
| 33 |
+
candidate_allocfree = snodes_allocfree[candidate]
|
| 34 |
+
est_peak_memory, snodes_curr_memory, snodes_allocfree, _ = (
|
| 35 |
+
estimate_peak_memory_allocfree(
|
| 36 |
+
snodes, name_to_freeable_input_buf, graph_outputs
|
| 37 |
+
)
|
| 38 |
+
)
|
| 39 |
+
est_curr_memory = dict(zip(snodes, snodes_curr_memory))
|
| 40 |
+
iter_cm = iter_curr_memory[candidate]
|
| 41 |
+
new_cm = est_curr_memory[candidate]
|
| 42 |
+
log = ""
|
| 43 |
+
if est_peak_memory > peak_memory:
|
| 44 |
+
log = "ITERATIVE PEAK DOES NOT MATCH"
|
| 45 |
+
iterative_recompute_error = True
|
| 46 |
+
if iter_cm != new_cm:
|
| 47 |
+
log = "ITERATIVE CURR MEMORY CANDIDATE DOES NOT MATCH"
|
| 48 |
+
iterative_recompute_error = True
|
| 49 |
+
for i, gn in enumerate(gns):
|
| 50 |
+
iter_gnm = iter_curr_memory[gn]
|
| 51 |
+
new_gnm = est_curr_memory[gn]
|
| 52 |
+
if iter_gnm != new_gnm:
|
| 53 |
+
log = f"ITERATIVE GN CURR MEMORY DOES NOT MATCH:{gn.get_name()}"
|
| 54 |
+
iterative_recompute_error = True
|
| 55 |
+
if iterative_recompute_error:
|
| 56 |
+
log += (
|
| 57 |
+
f"\nCANDIDATE:{candidate.get_name()}"
|
| 58 |
+
f"\nGROUP:{group_names}"
|
| 59 |
+
f"\nPEAK_MEMORY_BEFORE:{peak_memory}"
|
| 60 |
+
f"\nPEAK_MEMORY_AFTER_SWAP:{est_peak_memory}"
|
| 61 |
+
f"\nCANDIDATE:{candidate.debug_str()}"
|
| 62 |
+
f"\nCANDIDATE_ITER_CURR_MEMORY:{iter_cm}"
|
| 63 |
+
f"\nCANDIDATE_NEW__CURR_MEMORY:{new_cm}"
|
| 64 |
+
f"\nCANDIDATE_ITER_ALLOCFREE:{candidate_allocfree}"
|
| 65 |
+
f"\nCANDIDATE_NEW_ALLOCFREE:{snodes_allocfree[candidate]}"
|
| 66 |
+
)
|
| 67 |
+
peak_log = ""
|
| 68 |
+
for i, (pre, post) in enumerate(snodes_curr_memory):
|
| 69 |
+
if est_peak_memory == pre:
|
| 70 |
+
n = snodes[i]
|
| 71 |
+
peak_log = (
|
| 72 |
+
f"\nNEW_PEAK:{est_peak_memory}(BASE:{peak_memory})"
|
| 73 |
+
f" @ SNODE[{i}/{len(snodes)}]:{n.get_name()} {n.debug_str()}"
|
| 74 |
+
)
|
| 75 |
+
break
|
| 76 |
+
group_log = ""
|
| 77 |
+
for i, gn in enumerate(gns):
|
| 78 |
+
iter_gnm = iter_curr_memory[gn]
|
| 79 |
+
new_gnm = est_curr_memory[gn]
|
| 80 |
+
group_log += (
|
| 81 |
+
f"\nGROUP_NODE[{i}]:{gn.debug_str()}"
|
| 82 |
+
f"\nGROUP_NODE[{i}] ITER_GNM[{gn.get_name()}]:{iter_gnm}"
|
| 83 |
+
f"\nGROUP_NODE[{i}] ESTM_GNM[{gn.get_name()}]:{new_gnm}"
|
| 84 |
+
f"\nGROUP_NODE[{i}] ITER_allocfree:{snodes_allocfree[gn]}"
|
| 85 |
+
f"\nGROUP_NODE[{i}] ESTM_allocfree:{snodes_allocfree[gn]}"
|
| 86 |
+
)
|
| 87 |
+
log += peak_log
|
| 88 |
+
log += group_log
|
| 89 |
+
log += f"\nGN_TO_BUFS_LAST_USE:{gn_to_bufs_last_use}"
|
| 90 |
+
log += "\n\n".join(
|
| 91 |
+
[
|
| 92 |
+
(
|
| 93 |
+
f"\nSNODE[{i}]\n{n.debug_str()}"
|
| 94 |
+
f"\nITER_cur_mem:{iter_curr_memory[n]}"
|
| 95 |
+
f"\nESTM_cur_mem:{est_curr_memory[n]}"
|
| 96 |
+
f"\nITER_allocfree:{snodes_allocfree[n]}"
|
| 97 |
+
f"\nESTM_allocfree:{snodes_allocfree[n]}"
|
| 98 |
+
)
|
| 99 |
+
for i, n in enumerate(snodes)
|
| 100 |
+
]
|
| 101 |
+
)
|
| 102 |
+
tname = f"{tlparse_name}_ITERATIVE_RECOMPUTE_ERROR"
|
| 103 |
+
print(f"{tname}:\n{log}")
|
| 104 |
+
trace_structured(
|
| 105 |
+
"artifact",
|
| 106 |
+
metadata_fn=lambda: {
|
| 107 |
+
"name": tname,
|
| 108 |
+
"encoding": "string",
|
| 109 |
+
},
|
| 110 |
+
payload_fn=lambda: log,
|
| 111 |
+
)
|
| 112 |
+
return iterative_recompute_error
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx_async.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections import deque
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any, Callable, Optional, TYPE_CHECKING
|
| 6 |
+
from typing_extensions import final, override
|
| 7 |
+
|
| 8 |
+
import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
|
| 9 |
+
from torch._inductor.output_code import CompiledFxGraphConstants, OutputCode
|
| 10 |
+
|
| 11 |
+
from .compile_fx import _CompileFxKwargs, _InProcessFxCompile, FxCompile
|
| 12 |
+
from .output_code import complex_memory_overlap as complex_memory_overlap # noqa: F401
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# When async compile works with cache, remove the disabling below
|
| 16 |
+
BUG_CACHES_DONT_WORK_WITH_ASYNC = True
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from collections.abc import Sequence
|
| 21 |
+
from concurrent.futures import Future
|
| 22 |
+
|
| 23 |
+
from torch._inductor.utils import InputType
|
| 24 |
+
from torch.fx import GraphModule
|
| 25 |
+
|
| 26 |
+
from .compile_fx_ext import _OutOfProcessFxCompile, _WireProtocolPickledOutput
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class _PostCompileData:
|
| 31 |
+
example_inputs: Sequence[InputType]
|
| 32 |
+
constants: CompiledFxGraphConstants
|
| 33 |
+
graph_kwargs: _CompileFxKwargs
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class ProgressiveCompilationState:
|
| 38 |
+
progression_futures: deque[Future[_WireProtocolPickledOutput]]
|
| 39 |
+
callback: Callable[[_WireProtocolPickledOutput], OutputCode]
|
| 40 |
+
post_compile_data: Optional[_PostCompileData]
|
| 41 |
+
|
| 42 |
+
def check_and_get_ready_stage(self) -> int:
|
| 43 |
+
"""Check if any progression stage is ready and return its index, or -1 if none are ready."""
|
| 44 |
+
if not self.progression_futures:
|
| 45 |
+
return -1
|
| 46 |
+
|
| 47 |
+
stage_index = -1
|
| 48 |
+
if self.post_compile_data:
|
| 49 |
+
for i, future in enumerate(self.progression_futures):
|
| 50 |
+
if future.done():
|
| 51 |
+
stage_index = i
|
| 52 |
+
|
| 53 |
+
return stage_index
|
| 54 |
+
|
| 55 |
+
def switch_to_progression_stage(self, stage_index: int) -> tuple[OutputCode, bool]:
|
| 56 |
+
"""
|
| 57 |
+
Switch to the specified progression stage and return the optimized output code.
|
| 58 |
+
Returns a tuple of (optimized_output_code, should_clear_compilation_state).
|
| 59 |
+
"""
|
| 60 |
+
future = self.progression_futures[stage_index]
|
| 61 |
+
assert future is not None
|
| 62 |
+
optimized_output_code = self.callback(future.result())
|
| 63 |
+
|
| 64 |
+
if pcd := self.post_compile_data:
|
| 65 |
+
optimized_output_code.post_compile(
|
| 66 |
+
pcd.example_inputs, pcd.constants, pcd.graph_kwargs
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# Clear earlier progression futures to free memory
|
| 70 |
+
for _ in range(stage_index + 1):
|
| 71 |
+
self.progression_futures.popleft()
|
| 72 |
+
|
| 73 |
+
# Return whether all compilation state should be cleared
|
| 74 |
+
should_clear_state = not self.progression_futures
|
| 75 |
+
return optimized_output_code, should_clear_state
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# _AsyncOutputCode handles the actual management of waiting for an
|
| 79 |
+
# out-of-process compile to finish and then switching over to it.
|
| 80 |
+
@final
|
| 81 |
+
class _AsyncOutputCode(OutputCode):
|
| 82 |
+
_eager_fn: Optional[Callable[..., Any]]
|
| 83 |
+
_output_code: Optional[OutputCode]
|
| 84 |
+
_future: Optional[Future[_WireProtocolPickledOutput]]
|
| 85 |
+
_callback: Callable[[_WireProtocolPickledOutput], OutputCode]
|
| 86 |
+
_post_compile_data: Optional[_PostCompileData] = None
|
| 87 |
+
_boxed_call: bool # Copied from the forward/output_code
|
| 88 |
+
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
# eager_fn is run until the future is finished.
|
| 92 |
+
eager_fn: Callable[..., Any],
|
| 93 |
+
# this responds with the result of the out-of-process compile when it's
|
| 94 |
+
# ready.
|
| 95 |
+
future: Future[_WireProtocolPickledOutput],
|
| 96 |
+
# this callback gets called to turn the _WireProtocolPickledOutput into an OutputCode
|
| 97 |
+
callback: Callable[[_WireProtocolPickledOutput], OutputCode],
|
| 98 |
+
) -> None:
|
| 99 |
+
self._eager_fn = eager_fn
|
| 100 |
+
self._boxed_call = getattr(eager_fn, "_boxed_call", False)
|
| 101 |
+
self._output_code = None
|
| 102 |
+
|
| 103 |
+
self._future = future
|
| 104 |
+
self._callback = callback
|
| 105 |
+
|
| 106 |
+
@override
|
| 107 |
+
def __call__(self, *args: Any) -> Any:
|
| 108 |
+
if self._future is not None and self._future.done():
|
| 109 |
+
args = self._switch_to_compiled_fn(args)
|
| 110 |
+
|
| 111 |
+
if eager_fn := self._eager_fn:
|
| 112 |
+
_AsyncFxCompile._stat_eager_runs += 1
|
| 113 |
+
return eager_fn(*args)
|
| 114 |
+
|
| 115 |
+
else:
|
| 116 |
+
_AsyncFxCompile._stat_compiled_runs += 1
|
| 117 |
+
assert self._output_code is not None
|
| 118 |
+
return self._output_code.__call__(*args)
|
| 119 |
+
|
| 120 |
+
# Takes and returns the args (converted to the "right" boxed mode)
|
| 121 |
+
def _switch_to_compiled_fn(self, args: tuple[Any, ...]) -> tuple[Any, ...]:
|
| 122 |
+
assert self._future is not None
|
| 123 |
+
|
| 124 |
+
# TODO: If the future ended in an exception do we want to continue
|
| 125 |
+
# running eager or hit the exception now?
|
| 126 |
+
f, self._future = self._future, None
|
| 127 |
+
output_code = self._callback(f.result())
|
| 128 |
+
|
| 129 |
+
if pcd := self._post_compile_data:
|
| 130 |
+
self._post_compile_data = None
|
| 131 |
+
|
| 132 |
+
output_code.post_compile(
|
| 133 |
+
pcd.example_inputs, pcd.constants, pcd.graph_kwargs
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self._output_code = output_code
|
| 137 |
+
self._eager_fn = None
|
| 138 |
+
boxed_call = getattr(output_code, "_boxed_call", False)
|
| 139 |
+
|
| 140 |
+
if self._boxed_call != boxed_call:
|
| 141 |
+
if self._boxed_call:
|
| 142 |
+
# Was boxed, now unboxed
|
| 143 |
+
args = args[0] if len(args) > 0 else ()
|
| 144 |
+
else:
|
| 145 |
+
# Was unboxed, now boxed
|
| 146 |
+
args = (args,)
|
| 147 |
+
|
| 148 |
+
self._boxed_call = boxed_call
|
| 149 |
+
return args
|
| 150 |
+
|
| 151 |
+
@override
|
| 152 |
+
def post_compile(
|
| 153 |
+
self,
|
| 154 |
+
example_inputs: Sequence[InputType],
|
| 155 |
+
constants: CompiledFxGraphConstants,
|
| 156 |
+
graph_kwargs: _CompileFxKwargs,
|
| 157 |
+
) -> None:
|
| 158 |
+
if self._eager_fn is not None:
|
| 159 |
+
self._post_compile_data = _PostCompileData(
|
| 160 |
+
example_inputs, constants, graph_kwargs
|
| 161 |
+
)
|
| 162 |
+
else:
|
| 163 |
+
assert self._output_code is not None
|
| 164 |
+
self._output_code.post_compile(example_inputs, constants, graph_kwargs)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
# Given an FxCompile for an out-of-process compile _AsyncFxCompile will run
|
| 168 |
+
# eager until the compiled artifact is ready then it will automatically switch
|
| 169 |
+
# over to using the compiled version.
|
| 170 |
+
@final
|
| 171 |
+
class _AsyncFxCompile(FxCompile):
|
| 172 |
+
_compile: _OutOfProcessFxCompile
|
| 173 |
+
|
| 174 |
+
# Some debugging stats:
|
| 175 |
+
# Number of times we started a background compile.
|
| 176 |
+
_stat_bg_started: int = 0
|
| 177 |
+
# Number of times we finished a background compile.
|
| 178 |
+
_stat_bg_finished: int = 0
|
| 179 |
+
# Number of times we ran "eager"
|
| 180 |
+
_stat_eager_runs: int = 0
|
| 181 |
+
# Number of times we ran our compiled (out-of-process) artifact
|
| 182 |
+
_stat_compiled_runs: int = 0
|
| 183 |
+
|
| 184 |
+
def __init__(self, compile: _OutOfProcessFxCompile) -> None:
|
| 185 |
+
self._compile = compile
|
| 186 |
+
|
| 187 |
+
@classmethod
|
| 188 |
+
def _reset_stats(cls) -> None:
|
| 189 |
+
cls._stat_bg_started = 0
|
| 190 |
+
cls._stat_bg_finished = 0
|
| 191 |
+
cls._stat_eager_runs = 0
|
| 192 |
+
cls._stat_compiled_runs = 0
|
| 193 |
+
|
| 194 |
+
@override
|
| 195 |
+
def codegen_and_compile(
|
| 196 |
+
self,
|
| 197 |
+
gm: GraphModule,
|
| 198 |
+
example_inputs: Sequence[InputType],
|
| 199 |
+
inputs_to_check: Sequence[int],
|
| 200 |
+
graph_kwargs: _CompileFxKwargs,
|
| 201 |
+
) -> OutputCode:
|
| 202 |
+
eager_output_code = _InProcessFxCompile().codegen_and_compile(
|
| 203 |
+
gm, example_inputs, inputs_to_check, graph_kwargs
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
# This is similar to _SerializedFxCompile.codegen_and_compile() but
|
| 207 |
+
# handles the async routing.
|
| 208 |
+
|
| 209 |
+
serialized = self._compile.serialize_compile(
|
| 210 |
+
gm, example_inputs, inputs_to_check, graph_kwargs
|
| 211 |
+
)
|
| 212 |
+
if not serialized:
|
| 213 |
+
# We can't serialize - just return the eager OutputCode
|
| 214 |
+
return eager_output_code
|
| 215 |
+
|
| 216 |
+
inputs, constants = serialized
|
| 217 |
+
|
| 218 |
+
_AsyncFxCompile._stat_bg_started += 1
|
| 219 |
+
f = self._compile._send_to_child_async(inputs)
|
| 220 |
+
|
| 221 |
+
# This is called by _switch_to_compiled_fn() when f has a result...
|
| 222 |
+
def callback(pickled_output: _WireProtocolPickledOutput) -> OutputCode:
|
| 223 |
+
_AsyncFxCompile._stat_bg_finished += 1
|
| 224 |
+
output = pickled_output.deserialize(constants)
|
| 225 |
+
self._compile._postprocess(output)
|
| 226 |
+
return output.graph
|
| 227 |
+
|
| 228 |
+
return _AsyncOutputCode(eager_output_code, f, callback)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# _ProgressiveOutputCode handles running a fast compile first, then hot-swapping
|
| 232 |
+
# to a more optimized version when the expensive compile finishes.
|
| 233 |
+
@final
|
| 234 |
+
class _ProgressiveOutputCode(OutputCode):
|
| 235 |
+
_fast_output_code: Optional[OutputCode]
|
| 236 |
+
_optimized_output_code: Optional[OutputCode]
|
| 237 |
+
_compilation_state: Optional[ProgressiveCompilationState]
|
| 238 |
+
# _boxed_call state is effectively cached (we sometimes wrap unboxed w/
|
| 239 |
+
# lambdas to box them) so we can't change it mid-way. Since _boxed_call=True
|
| 240 |
+
# is more common let's default to that and we'll convert if necessary.
|
| 241 |
+
_boxed_call: bool = True
|
| 242 |
+
|
| 243 |
+
def __init__(
|
| 244 |
+
self,
|
| 245 |
+
# Fast compile that runs faster than the progressive compiles
|
| 246 |
+
fast_output_code: OutputCode,
|
| 247 |
+
# Futures for the progressive optimized compiles
|
| 248 |
+
progression_futures: Sequence[Future[_WireProtocolPickledOutput]],
|
| 249 |
+
# Callback to convert the optimized result to OutputCode
|
| 250 |
+
callback: Callable[[_WireProtocolPickledOutput], OutputCode],
|
| 251 |
+
) -> None:
|
| 252 |
+
self._fast_output_code = fast_output_code
|
| 253 |
+
self._optimized_output_code = None
|
| 254 |
+
self._compilation_state = ProgressiveCompilationState(
|
| 255 |
+
progression_futures=deque(progression_futures),
|
| 256 |
+
callback=callback,
|
| 257 |
+
post_compile_data=None,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
@override
|
| 261 |
+
def __call__(self, args: Sequence[Any]) -> Any:
|
| 262 |
+
# Check if any newer progression stage is ready and switch to it
|
| 263 |
+
self._check_and_switch_progression()
|
| 264 |
+
|
| 265 |
+
if self._optimized_output_code is not None:
|
| 266 |
+
_ProgressiveFxCompile._stat_optimized_runs += 1
|
| 267 |
+
output_code = self._optimized_output_code
|
| 268 |
+
else:
|
| 269 |
+
_ProgressiveFxCompile._stat_fast_runs += 1
|
| 270 |
+
assert self._fast_output_code is not None
|
| 271 |
+
output_code = self._fast_output_code
|
| 272 |
+
|
| 273 |
+
boxed_call = getattr(output_code, "_boxed_call", False)
|
| 274 |
+
if boxed_call:
|
| 275 |
+
res = output_code.__call__(args)
|
| 276 |
+
else:
|
| 277 |
+
res = output_code.__call__(*args)
|
| 278 |
+
return res
|
| 279 |
+
|
| 280 |
+
def _check_and_switch_progression(self) -> None:
|
| 281 |
+
if not self._compilation_state:
|
| 282 |
+
return
|
| 283 |
+
|
| 284 |
+
stage_index = self._compilation_state.check_and_get_ready_stage()
|
| 285 |
+
if stage_index == -1:
|
| 286 |
+
# no futures are ready
|
| 287 |
+
return
|
| 288 |
+
|
| 289 |
+
self._switch_to_progression_stage(stage_index)
|
| 290 |
+
|
| 291 |
+
def _switch_to_progression_stage(self, stage_index: int) -> None:
|
| 292 |
+
assert self._compilation_state is not None
|
| 293 |
+
optimized_output_code, should_clear_state = (
|
| 294 |
+
self._compilation_state.switch_to_progression_stage(stage_index)
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
self._optimized_output_code = optimized_output_code
|
| 298 |
+
self._fast_output_code = None
|
| 299 |
+
|
| 300 |
+
# Clear all compilation state if no more progression futures are left
|
| 301 |
+
if should_clear_state:
|
| 302 |
+
self._compilation_state = None
|
| 303 |
+
|
| 304 |
+
@override
|
| 305 |
+
def post_compile(
|
| 306 |
+
self,
|
| 307 |
+
example_inputs: Sequence[InputType],
|
| 308 |
+
constants: CompiledFxGraphConstants,
|
| 309 |
+
graph_kwargs: _CompileFxKwargs,
|
| 310 |
+
) -> None:
|
| 311 |
+
assert self._fast_output_code is not None
|
| 312 |
+
self._fast_output_code.post_compile(example_inputs, constants, graph_kwargs)
|
| 313 |
+
|
| 314 |
+
assert self._compilation_state is not None
|
| 315 |
+
# Store for later when optimized version is ready
|
| 316 |
+
self._compilation_state.post_compile_data = _PostCompileData(
|
| 317 |
+
example_inputs, constants, graph_kwargs
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
# _ProgressiveFxCompile runs a fast compile immediately, then kicks off
|
| 322 |
+
# progressive compiles in the background and hot-swaps when they're ready.
|
| 323 |
+
@final
|
| 324 |
+
class _ProgressiveFxCompile(FxCompile):
|
| 325 |
+
_fast_compile: FxCompile
|
| 326 |
+
_optimized_compile: _OutOfProcessFxCompile
|
| 327 |
+
_progression_configs: list[dict[str, Any]]
|
| 328 |
+
|
| 329 |
+
# Debugging stats
|
| 330 |
+
_stat_bg_started: int = 0
|
| 331 |
+
_stat_bg_finished: int = 0
|
| 332 |
+
_stat_fast_runs: int = 0
|
| 333 |
+
_stat_optimized_runs: int = 0
|
| 334 |
+
|
| 335 |
+
def __init__(
|
| 336 |
+
self,
|
| 337 |
+
fast_compile: FxCompile,
|
| 338 |
+
optimized_compile: _OutOfProcessFxCompile,
|
| 339 |
+
progression_configs: list[dict[str, Any]],
|
| 340 |
+
) -> None:
|
| 341 |
+
self._fast_compile = fast_compile
|
| 342 |
+
self._optimized_compile = optimized_compile
|
| 343 |
+
self._progression_configs = progression_configs
|
| 344 |
+
|
| 345 |
+
@classmethod
|
| 346 |
+
def _reset_stats(cls) -> None:
|
| 347 |
+
cls._stat_bg_started = 0
|
| 348 |
+
cls._stat_bg_finished = 0
|
| 349 |
+
cls._stat_fast_runs = 0
|
| 350 |
+
cls._stat_optimized_runs = 0
|
| 351 |
+
|
| 352 |
+
@override
|
| 353 |
+
def codegen_and_compile(
|
| 354 |
+
self,
|
| 355 |
+
gm: GraphModule,
|
| 356 |
+
example_inputs: Sequence[InputType],
|
| 357 |
+
inputs_to_check: Sequence[int],
|
| 358 |
+
graph_kwargs: _CompileFxKwargs,
|
| 359 |
+
) -> OutputCode:
|
| 360 |
+
import torch._inductor.config as inductor_config
|
| 361 |
+
|
| 362 |
+
progression_futures: list[Future[_WireProtocolPickledOutput]] = []
|
| 363 |
+
|
| 364 |
+
for config in self._progression_configs:
|
| 365 |
+
with inductor_config.patch(config):
|
| 366 |
+
_ProgressiveFxCompile._stat_bg_started += 1
|
| 367 |
+
|
| 368 |
+
# Start the progressive compiles in the background
|
| 369 |
+
serialized = self._optimized_compile.serialize_compile(
|
| 370 |
+
gm, example_inputs, inputs_to_check, graph_kwargs
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
if not serialized:
|
| 374 |
+
continue
|
| 375 |
+
|
| 376 |
+
inputs, constants = serialized
|
| 377 |
+
future = self._optimized_compile._send_to_child_async(inputs)
|
| 378 |
+
progression_futures.append(future)
|
| 379 |
+
|
| 380 |
+
fast_output_code = self._fast_compile.codegen_and_compile(
|
| 381 |
+
gm, example_inputs, inputs_to_check, graph_kwargs
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
if not progression_futures:
|
| 385 |
+
# All async compile attempts failed - just return the fast version
|
| 386 |
+
return fast_output_code
|
| 387 |
+
|
| 388 |
+
# Callback to handle the optimized result.
|
| 389 |
+
# This callback may be called multiple times, once for each progressive level completed,
|
| 390 |
+
# but may be skipped if a level either never completes or if a more optimal level
|
| 391 |
+
# completes before a less optimal one is switched to.
|
| 392 |
+
def callback(pickled_output: _WireProtocolPickledOutput) -> OutputCode:
|
| 393 |
+
_ProgressiveFxCompile._stat_bg_finished += 1
|
| 394 |
+
output = pickled_output.deserialize(constants)
|
| 395 |
+
self._optimized_compile._postprocess(output)
|
| 396 |
+
return output.graph
|
| 397 |
+
|
| 398 |
+
return _ProgressiveOutputCode(fast_output_code, progression_futures, callback)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx_ext.py
ADDED
|
@@ -0,0 +1,681 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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7 |
+
import os
|
| 8 |
+
import queue
|
| 9 |
+
import sys
|
| 10 |
+
import warnings
|
| 11 |
+
from abc import abstractmethod
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 14 |
+
from typing_extensions import final, override, Self, TypeGuard
|
| 15 |
+
|
| 16 |
+
import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
|
| 17 |
+
import torch.fx
|
| 18 |
+
from torch._inductor.codecache import BypassFxGraphCache, FxGraphCache
|
| 19 |
+
from torch._inductor.metrics import CachedMetricsDeltas, CachedMetricsHelper
|
| 20 |
+
from torch._inductor.output_code import (
|
| 21 |
+
CompiledFxGraph,
|
| 22 |
+
CompiledFxGraphConstants,
|
| 23 |
+
CompiledFxGraphConstantsWithGm,
|
| 24 |
+
OutputCode,
|
| 25 |
+
)
|
| 26 |
+
from torch._subclasses import FakeTensorMode
|
| 27 |
+
from torch.utils._ordered_set import OrderedSet
|
| 28 |
+
|
| 29 |
+
from . import config
|
| 30 |
+
from .compile_fx import _CompileFxKwargs, _InProcessFxCompile, FxCompile, log
|
| 31 |
+
from .debug import DebugContext
|
| 32 |
+
from .graph import GraphLowering
|
| 33 |
+
from .output_code import complex_memory_overlap as complex_memory_overlap # noqa: F401
|
| 34 |
+
from .virtualized import V
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if TYPE_CHECKING:
|
| 38 |
+
import types
|
| 39 |
+
from collections.abc import Generator, Mapping, Sequence
|
| 40 |
+
from concurrent.futures import Future
|
| 41 |
+
|
| 42 |
+
from torch._inductor.utils import InputType
|
| 43 |
+
from torch.fx import GraphModule
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class _VirtualizedSerializer:
|
| 48 |
+
"""
|
| 49 |
+
This handles the data for serializing Virtualized.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
# The values here get serialized. We don't grab everything because some of
|
| 53 |
+
# the fields can't be serialized.
|
| 54 |
+
aot_compilation: Any = None
|
| 55 |
+
choices: Any = None
|
| 56 |
+
local_buffer_context: Any = None
|
| 57 |
+
ops: Any = None
|
| 58 |
+
kernel: Any = None
|
| 59 |
+
current_node: Any = None
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def serialize(cls) -> _VirtualizedSerializer:
|
| 63 |
+
"""
|
| 64 |
+
Turn the current state of torch._inductor.virtualized.V into a
|
| 65 |
+
serializable structure.
|
| 66 |
+
"""
|
| 67 |
+
kwargs = {}
|
| 68 |
+
for f in dataclasses.fields(cls):
|
| 69 |
+
kwargs[f.name] = getattr(V, f.name)
|
| 70 |
+
return _VirtualizedSerializer(**kwargs)
|
| 71 |
+
|
| 72 |
+
def patch(self) -> _VirtualizedSerializerContextManager:
|
| 73 |
+
"""
|
| 74 |
+
Returns a context manager which patches the saved values into the
|
| 75 |
+
current environment. While patched, any value not listed above will be
|
| 76 |
+
poisoned so that reads will raise an error.
|
| 77 |
+
"""
|
| 78 |
+
return _VirtualizedSerializerContextManager(self)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class _VirtualizedSerializerContextManager(contextlib.ExitStack):
|
| 82 |
+
"""
|
| 83 |
+
Helper for _VirtualizedSerializer.patch()
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, virtualized: _VirtualizedSerializer) -> None:
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.virtualized = virtualized
|
| 89 |
+
|
| 90 |
+
@override
|
| 91 |
+
def __enter__(self) -> Self:
|
| 92 |
+
super().__enter__()
|
| 93 |
+
|
| 94 |
+
for set_name in dir(V):
|
| 95 |
+
if not set_name.startswith("set_"):
|
| 96 |
+
continue
|
| 97 |
+
name = set_name[4:]
|
| 98 |
+
name = name.removesuffix("_handler")
|
| 99 |
+
set_handler = getattr(V, set_name)
|
| 100 |
+
if hasattr(self.virtualized, name):
|
| 101 |
+
value = getattr(self.virtualized, name)
|
| 102 |
+
else:
|
| 103 |
+
# poison any values that we don't serialize so that any
|
| 104 |
+
# unset accesses are caught.
|
| 105 |
+
value = torch._inductor.virtualized._PoisonedVirtual
|
| 106 |
+
self.enter_context(set_handler(value))
|
| 107 |
+
|
| 108 |
+
return self
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _is_fallback_handler(op: object) -> bool:
|
| 112 |
+
try:
|
| 113 |
+
return op._is_fallback_handler # type: ignore[attr-defined]
|
| 114 |
+
except AttributeError:
|
| 115 |
+
return False
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class _LoweringSerializer:
|
| 119 |
+
"""
|
| 120 |
+
This handles the data for serializing lowering.lowering
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
# A full implementation would make sure that all lowerings are copied over
|
| 124 |
+
# (or at least detected and raise a bypass when a non-standard lowering is
|
| 125 |
+
# used). For now we just handle tests by looking for lowerings that were
|
| 126 |
+
# overridden with a forced fallback.
|
| 127 |
+
fallbacks: OrderedSet[str]
|
| 128 |
+
|
| 129 |
+
def __init__(self) -> None:
|
| 130 |
+
from . import lowering
|
| 131 |
+
|
| 132 |
+
self.fallbacks = OrderedSet(
|
| 133 |
+
str(k) for k, v in lowering.lowerings.items() if _is_fallback_handler(v)
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def patch(self) -> _LoweringSerializerContextManager:
|
| 137 |
+
return _LoweringSerializerContextManager(self)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class _LoweringSerializerContextManager(contextlib.ExitStack):
|
| 141 |
+
"""
|
| 142 |
+
Helper for _LoweringSerializer.patch()
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def __init__(self, lowering: _LoweringSerializer) -> None:
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.lowering = lowering
|
| 148 |
+
|
| 149 |
+
@override
|
| 150 |
+
def __enter__(self) -> Self:
|
| 151 |
+
super().__enter__()
|
| 152 |
+
|
| 153 |
+
from . import lowering
|
| 154 |
+
|
| 155 |
+
for k, v in lowering.lowerings.items():
|
| 156 |
+
name = str(k)
|
| 157 |
+
if name in self.lowering.fallbacks:
|
| 158 |
+
if not _is_fallback_handler(v):
|
| 159 |
+
self.enter_context(lowering.force_fallback(k)) # type: ignore[arg-type]
|
| 160 |
+
|
| 161 |
+
return self
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@dataclass
|
| 165 |
+
class _FakeTensorModeSerializer:
|
| 166 |
+
allow_non_fake_inputs: bool
|
| 167 |
+
|
| 168 |
+
def __init__(self, fake_mode: FakeTensorMode) -> None:
|
| 169 |
+
self.allow_non_fake_inputs = fake_mode.allow_non_fake_inputs
|
| 170 |
+
self.shape_env = fake_mode.shape_env
|
| 171 |
+
|
| 172 |
+
@contextlib.contextmanager
|
| 173 |
+
def patch(self, fake_mode: FakeTensorMode) -> Generator[None, None, None]:
|
| 174 |
+
saved_allow_non_fake_inputs = fake_mode.allow_non_fake_inputs
|
| 175 |
+
fake_mode.allow_non_fake_inputs = self.allow_non_fake_inputs
|
| 176 |
+
|
| 177 |
+
yield
|
| 178 |
+
|
| 179 |
+
fake_mode.allow_non_fake_inputs = saved_allow_non_fake_inputs
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@dataclass
|
| 183 |
+
class _WireProtocolInput:
|
| 184 |
+
"""
|
| 185 |
+
For _SerializedFxCompile - encapsulates all the data being transferred
|
| 186 |
+
(sent) from the parent to the child.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
gm: torch.fx.GraphModule
|
| 190 |
+
example_inputs: Sequence[InputType]
|
| 191 |
+
inputs_to_check: Sequence[int]
|
| 192 |
+
graph_kwargs: _CompileFxKwargs
|
| 193 |
+
tracing_context: Optional[torch._guards.TracingContext]
|
| 194 |
+
config: dict[str, object]
|
| 195 |
+
virtualized: _VirtualizedSerializer
|
| 196 |
+
deterministic_guard_for_testing: Optional[ # type: ignore[name-defined] # mypy bug
|
| 197 |
+
torch.testing._internal.common_utils.DeterministicGuard
|
| 198 |
+
]
|
| 199 |
+
logger_state: _LoggerState
|
| 200 |
+
lowering: _LoweringSerializer
|
| 201 |
+
fake_tensor_mode: _FakeTensorModeSerializer
|
| 202 |
+
|
| 203 |
+
def serialize(self) -> _WireProtocolPickledInput:
|
| 204 |
+
"""
|
| 205 |
+
Turns this object into a _WireProtocolPickledInput which can be
|
| 206 |
+
directly transferred across a stream.
|
| 207 |
+
"""
|
| 208 |
+
from torch.fx._graph_pickler import GraphPickler
|
| 209 |
+
|
| 210 |
+
return _WireProtocolPickledInput(GraphPickler.dumps(self))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _current_fake_mode() -> FakeTensorMode:
|
| 214 |
+
fake_mode = None
|
| 215 |
+
if context := torch._guards.TracingContext.try_get():
|
| 216 |
+
fake_mode = context.fake_mode
|
| 217 |
+
if fake_mode is not None:
|
| 218 |
+
return fake_mode
|
| 219 |
+
|
| 220 |
+
shape_env = torch.fx.experimental.symbolic_shapes.ShapeEnv()
|
| 221 |
+
return FakeTensorMode(shape_env=shape_env)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@dataclass
|
| 225 |
+
class _WireProtocolPickledInput:
|
| 226 |
+
value: bytes
|
| 227 |
+
|
| 228 |
+
def deserialize(self) -> _WireProtocolInput:
|
| 229 |
+
"""
|
| 230 |
+
Turn this streamable object back into a _WireProtocolInput.
|
| 231 |
+
"""
|
| 232 |
+
from torch.fx._graph_pickler import GraphPickler
|
| 233 |
+
|
| 234 |
+
fake_mode = _current_fake_mode()
|
| 235 |
+
result = GraphPickler.loads(self.value, fake_mode)
|
| 236 |
+
assert isinstance(result, _WireProtocolInput)
|
| 237 |
+
return result
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@dataclass
|
| 241 |
+
class _WireProtocolOutput:
|
| 242 |
+
"""
|
| 243 |
+
For _SerializedFxCompile - encapsulates all the data being transferred
|
| 244 |
+
(returned) back from the child to the parent.
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
graph: OutputCode
|
| 248 |
+
metrics: CachedMetricsDeltas
|
| 249 |
+
logs: list[logging.LogRecord]
|
| 250 |
+
warning_replay: Optional[list[warnings.WarningMessage]]
|
| 251 |
+
shape_env: Optional[torch.fx.experimental.symbolic_shapes.ShapeEnv]
|
| 252 |
+
|
| 253 |
+
def serialize(self) -> _WireProtocolPickledOutput:
|
| 254 |
+
"""
|
| 255 |
+
Turns this object into a _WireProtocolPickledOutput which can be
|
| 256 |
+
directly transferred across a stream.
|
| 257 |
+
"""
|
| 258 |
+
from torch.fx._graph_pickler import GraphPickler
|
| 259 |
+
|
| 260 |
+
if isinstance(self.graph, CompiledFxGraph):
|
| 261 |
+
self.graph.prepare_for_serialization()
|
| 262 |
+
return _WireProtocolPickledOutput(GraphPickler.dumps(self))
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@dataclass
|
| 266 |
+
class _WireProtocolPickledOutput:
|
| 267 |
+
value: bytes
|
| 268 |
+
|
| 269 |
+
def deserialize(self, constants: CompiledFxGraphConstants) -> _WireProtocolOutput:
|
| 270 |
+
"""
|
| 271 |
+
Turn this streamable object back into a _WireProtocolOutput.
|
| 272 |
+
"""
|
| 273 |
+
from torch.fx._graph_pickler import GraphPickler
|
| 274 |
+
|
| 275 |
+
fake_mode = _current_fake_mode()
|
| 276 |
+
result = GraphPickler.loads(self.value, fake_mode)
|
| 277 |
+
assert isinstance(result, _WireProtocolOutput)
|
| 278 |
+
if isinstance(result.graph, CompiledFxGraph):
|
| 279 |
+
result.graph.after_deserialization(constants)
|
| 280 |
+
return result
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class _LoggerState:
|
| 284 |
+
"""
|
| 285 |
+
This class is for tracking logging that happens during an out-of-process
|
| 286 |
+
compile so we can "replay" those messages when the compile is done. Used as
|
| 287 |
+
a context manager which returns the captured logs (object).
|
| 288 |
+
"""
|
| 289 |
+
|
| 290 |
+
loggers: dict[str, int]
|
| 291 |
+
# The actual log capturing mechanism - this should be None when we're not
|
| 292 |
+
# actively capturing logs.
|
| 293 |
+
captured_logs: Optional[_CapturedLogs] = None
|
| 294 |
+
|
| 295 |
+
def __init__(self) -> None:
|
| 296 |
+
# Mapping from logger name to level.
|
| 297 |
+
self.loggers = {}
|
| 298 |
+
|
| 299 |
+
def filter(
|
| 300 |
+
logger: Union[logging.Logger, logging.PlaceHolder],
|
| 301 |
+
) -> TypeGuard[logging.Logger]:
|
| 302 |
+
if not isinstance(logger, logging.Logger):
|
| 303 |
+
# Assume that Placeholders propagate
|
| 304 |
+
return False
|
| 305 |
+
# We only want to track torch._inductor logging
|
| 306 |
+
if not logger.name.startswith("torch._inductor"):
|
| 307 |
+
return False
|
| 308 |
+
# If this logger propagates then assume we'll track its parent
|
| 309 |
+
if logger.propagate:
|
| 310 |
+
return False
|
| 311 |
+
return True
|
| 312 |
+
|
| 313 |
+
root = logging.getLogger("torch._inductor")
|
| 314 |
+
if sys.version_info < (3, 12):
|
| 315 |
+
# logging.getChildren() doesn't exist until 3.12
|
| 316 |
+
logging._acquireLock() # type: ignore[attr-defined]
|
| 317 |
+
try:
|
| 318 |
+
for logger in root.manager.loggerDict.values():
|
| 319 |
+
if filter(logger):
|
| 320 |
+
self.loggers[logger.name] = logger.level
|
| 321 |
+
finally:
|
| 322 |
+
logging._releaseLock() # type: ignore[attr-defined]
|
| 323 |
+
else:
|
| 324 |
+
q = [root]
|
| 325 |
+
while q:
|
| 326 |
+
logger = q.pop()
|
| 327 |
+
if filter(logger):
|
| 328 |
+
self.loggers[logger.name] = logger.level
|
| 329 |
+
q.extend(logger.getChildren())
|
| 330 |
+
|
| 331 |
+
def __enter__(self) -> _CapturedLogs:
|
| 332 |
+
assert self.captured_logs is None
|
| 333 |
+
self.captured_logs = _CapturedLogs(self)
|
| 334 |
+
self.captured_logs.apply()
|
| 335 |
+
return self.captured_logs
|
| 336 |
+
|
| 337 |
+
def __exit__(
|
| 338 |
+
self,
|
| 339 |
+
exc_type: Optional[type[BaseException]],
|
| 340 |
+
exc_value: Optional[BaseException],
|
| 341 |
+
traceback: Optional[types.TracebackType],
|
| 342 |
+
) -> None:
|
| 343 |
+
assert self.captured_logs is not None
|
| 344 |
+
self.captured_logs.remove()
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class _CapturedLogs:
|
| 348 |
+
"""
|
| 349 |
+
Helper for _LoggerState - this class actually attaches to the logger in
|
| 350 |
+
the child process and grabs the log messages themselves.
|
| 351 |
+
"""
|
| 352 |
+
|
| 353 |
+
state: _LoggerState
|
| 354 |
+
queue: queue.Queue[logging.LogRecord]
|
| 355 |
+
handlers: Optional[dict[str, logging.Handler]]
|
| 356 |
+
|
| 357 |
+
def __init__(self, state: _LoggerState) -> None:
|
| 358 |
+
self.state = state
|
| 359 |
+
# A queue of the log entries
|
| 360 |
+
# TODO: For memory purposes should we log to a file and then respond with that?
|
| 361 |
+
self.queue = queue.Queue(-1)
|
| 362 |
+
# Mapping from name to handler (only valid when applied)
|
| 363 |
+
self.handlers = None
|
| 364 |
+
|
| 365 |
+
def finish(self) -> list[logging.LogRecord]:
|
| 366 |
+
assert self.handlers is None
|
| 367 |
+
logs = []
|
| 368 |
+
try:
|
| 369 |
+
while True:
|
| 370 |
+
logs.append(self.queue.get_nowait())
|
| 371 |
+
except queue.Empty:
|
| 372 |
+
pass
|
| 373 |
+
return logs
|
| 374 |
+
|
| 375 |
+
def remove(self) -> None:
|
| 376 |
+
assert self.handlers is not None
|
| 377 |
+
handlers, self.handlers = self.handlers, None
|
| 378 |
+
for name, handler in handlers.items():
|
| 379 |
+
logger = logging.getLogger(name)
|
| 380 |
+
logger.removeHandler(handler)
|
| 381 |
+
|
| 382 |
+
def apply(self) -> None:
|
| 383 |
+
from logging.handlers import QueueHandler
|
| 384 |
+
|
| 385 |
+
assert self.handlers is None
|
| 386 |
+
self.handlers = {}
|
| 387 |
+
for name, level in self.state.loggers.items():
|
| 388 |
+
logger = logging.getLogger(name)
|
| 389 |
+
handler = QueueHandler(self.queue)
|
| 390 |
+
self.handlers[name] = handler
|
| 391 |
+
logger.addHandler(handler)
|
| 392 |
+
if level != logging.NOTSET:
|
| 393 |
+
logger.setLevel(level)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class _SerializedFxCompile(FxCompile):
|
| 397 |
+
"""
|
| 398 |
+
This is used to represent an FxCompile which occurs across a serialized
|
| 399 |
+
boundary.
|
| 400 |
+
"""
|
| 401 |
+
|
| 402 |
+
@override
|
| 403 |
+
def codegen_and_compile(
|
| 404 |
+
self,
|
| 405 |
+
gm: GraphModule,
|
| 406 |
+
example_inputs: Sequence[InputType],
|
| 407 |
+
inputs_to_check: Sequence[int],
|
| 408 |
+
graph_kwargs: _CompileFxKwargs,
|
| 409 |
+
) -> OutputCode:
|
| 410 |
+
# If this code changes it's likely _AsyncFxCompile.codegen_and_compile()
|
| 411 |
+
# will also need to match.
|
| 412 |
+
|
| 413 |
+
serialized = self.serialize_compile(
|
| 414 |
+
gm, example_inputs, inputs_to_check, graph_kwargs
|
| 415 |
+
)
|
| 416 |
+
if not serialized:
|
| 417 |
+
return _InProcessFxCompile().codegen_and_compile(
|
| 418 |
+
gm, example_inputs, inputs_to_check, graph_kwargs
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
inputs, constants = serialized
|
| 422 |
+
output = self._send_to_child(inputs).deserialize(constants)
|
| 423 |
+
|
| 424 |
+
self._postprocess(output)
|
| 425 |
+
self._compile_stats[type(self)].codegen_and_compile += 1
|
| 426 |
+
|
| 427 |
+
# TODO: Do we need to figure out what changed in TracingContext in the
|
| 428 |
+
# child and plumb that back up to the parent?
|
| 429 |
+
|
| 430 |
+
return output.graph
|
| 431 |
+
|
| 432 |
+
def serialize_compile(
|
| 433 |
+
self,
|
| 434 |
+
gm: GraphModule,
|
| 435 |
+
example_inputs: Sequence[InputType],
|
| 436 |
+
inputs_to_check: Sequence[int],
|
| 437 |
+
graph_kwargs: _CompileFxKwargs,
|
| 438 |
+
) -> Optional[tuple[_WireProtocolPickledInput, CompiledFxGraphConstantsWithGm]]:
|
| 439 |
+
"""
|
| 440 |
+
Prepare a _WireProtocolInput to compile. If None is returned then it
|
| 441 |
+
wasn't possible to serialize and we should fallback to in-process.
|
| 442 |
+
"""
|
| 443 |
+
try:
|
| 444 |
+
# _check_for_hop raises BypassFxGraphCache when it detects something
|
| 445 |
+
# we can't cache (or serialize)
|
| 446 |
+
FxGraphCache._check_for_hop(gm)
|
| 447 |
+
except BypassFxGraphCache as e:
|
| 448 |
+
log.debug("Skipping %s compile: %s", type(self), e)
|
| 449 |
+
return None
|
| 450 |
+
|
| 451 |
+
context = torch._guards.TracingContext.try_get()
|
| 452 |
+
constants = CompiledFxGraphConstantsWithGm(gm)
|
| 453 |
+
logger_state = _LoggerState()
|
| 454 |
+
lowering = _LoweringSerializer()
|
| 455 |
+
|
| 456 |
+
# If we're running tests then grab the DeterministicGuard (don't want to
|
| 457 |
+
# import this if it isn't already imported because it has side-effects)
|
| 458 |
+
deterministic_guard_for_testing: Optional[ # type: ignore[name-defined] # mypy bug
|
| 459 |
+
torch.testing._internal.common_utils.DeterministicGuard
|
| 460 |
+
] = None
|
| 461 |
+
try:
|
| 462 |
+
deterministic_guard_for_testing = (
|
| 463 |
+
torch.testing._internal.common_utils.DeterministicGuard._current_state() # type: ignore[attr-defined] # mypy bug
|
| 464 |
+
)
|
| 465 |
+
except AttributeError:
|
| 466 |
+
pass
|
| 467 |
+
|
| 468 |
+
fake_mode = _current_fake_mode()
|
| 469 |
+
fake_tensor_mode = _FakeTensorModeSerializer(fake_mode)
|
| 470 |
+
|
| 471 |
+
try:
|
| 472 |
+
input = _WireProtocolInput(
|
| 473 |
+
gm,
|
| 474 |
+
example_inputs,
|
| 475 |
+
inputs_to_check,
|
| 476 |
+
graph_kwargs,
|
| 477 |
+
context,
|
| 478 |
+
config.save_config_portable(),
|
| 479 |
+
_VirtualizedSerializer.serialize(),
|
| 480 |
+
deterministic_guard_for_testing,
|
| 481 |
+
logger_state,
|
| 482 |
+
lowering,
|
| 483 |
+
fake_tensor_mode,
|
| 484 |
+
).serialize()
|
| 485 |
+
return (input, constants)
|
| 486 |
+
except (AttributeError, BypassFxGraphCache):
|
| 487 |
+
# For example: AttributeError: Can't pickle local object
|
| 488 |
+
# 'make_opaque_unary_fn.<locals>.OpaqueUnaryFn'
|
| 489 |
+
|
| 490 |
+
# TODO: scuba record about not being able to do this?
|
| 491 |
+
log.warning("Unable to pickle input graph or example inputs", exc_info=True)
|
| 492 |
+
|
| 493 |
+
return None
|
| 494 |
+
|
| 495 |
+
@abstractmethod
|
| 496 |
+
def _send_to_child(
|
| 497 |
+
self, pickled_input: _WireProtocolPickledInput
|
| 498 |
+
) -> _WireProtocolPickledOutput:
|
| 499 |
+
# The implementation of this should transfer `input` to the child, call
|
| 500 |
+
# `_run_in_child(input)` and transfer the result back.
|
| 501 |
+
...
|
| 502 |
+
|
| 503 |
+
def _postprocess(self, output: _WireProtocolOutput) -> None:
|
| 504 |
+
pass
|
| 505 |
+
|
| 506 |
+
@classmethod
|
| 507 |
+
def _run_in_child(
|
| 508 |
+
cls,
|
| 509 |
+
pickled_input: _WireProtocolPickledInput,
|
| 510 |
+
extra_env: Optional[Mapping[str, str]] = None,
|
| 511 |
+
) -> _WireProtocolPickledOutput:
|
| 512 |
+
metrics = CachedMetricsHelper()
|
| 513 |
+
|
| 514 |
+
with contextlib.ExitStack() as stack:
|
| 515 |
+
if extra_env is not None:
|
| 516 |
+
import unittest
|
| 517 |
+
|
| 518 |
+
stack.enter_context(unittest.mock.patch.dict("os.environ", extra_env))
|
| 519 |
+
|
| 520 |
+
# Save warnings to "replay" in the parent
|
| 521 |
+
warning_replay = stack.enter_context(warnings.catch_warnings(record=True))
|
| 522 |
+
|
| 523 |
+
# TODO: Should we split the input into multiple sections where each
|
| 524 |
+
# section sets up state for the previous section? (i.e. a Config section
|
| 525 |
+
# which we decode and apply, followed by a FakeTensorMode section which
|
| 526 |
+
# we decode and apply, etc)
|
| 527 |
+
input = pickled_input.deserialize()
|
| 528 |
+
|
| 529 |
+
stack.enter_context(input.virtualized.patch())
|
| 530 |
+
stack.enter_context(input.lowering.patch())
|
| 531 |
+
stack.enter_context(config.patch(input.config))
|
| 532 |
+
captured_logs = stack.enter_context(input.logger_state)
|
| 533 |
+
if input.deterministic_guard_for_testing:
|
| 534 |
+
stack.enter_context(input.deterministic_guard_for_testing)
|
| 535 |
+
stack.enter_context(torch._guards.tracing(input.tracing_context))
|
| 536 |
+
stack.enter_context(DebugContext())
|
| 537 |
+
|
| 538 |
+
fake_mode = _current_fake_mode()
|
| 539 |
+
stack.enter_context(input.fake_tensor_mode.patch(fake_mode))
|
| 540 |
+
|
| 541 |
+
output_graph = _InProcessFxCompile().codegen_and_compile(
|
| 542 |
+
input.gm,
|
| 543 |
+
input.example_inputs,
|
| 544 |
+
input.inputs_to_check,
|
| 545 |
+
input.graph_kwargs,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
logs = captured_logs.finish()
|
| 549 |
+
|
| 550 |
+
return _WireProtocolOutput(
|
| 551 |
+
output_graph,
|
| 552 |
+
metrics.get_deltas(),
|
| 553 |
+
logs,
|
| 554 |
+
warning_replay,
|
| 555 |
+
fake_mode.shape_env,
|
| 556 |
+
).serialize()
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
# This is a debugging/testing implementation of FxCompile which serializes the
|
| 560 |
+
# input and output but still runs the FxCompile in-process.
|
| 561 |
+
@final
|
| 562 |
+
class _DebugSerdeFxCompile(_SerializedFxCompile):
|
| 563 |
+
@override
|
| 564 |
+
def _send_to_child(
|
| 565 |
+
self, pickled_input: _WireProtocolPickledInput
|
| 566 |
+
) -> _WireProtocolPickledOutput:
|
| 567 |
+
# For debugging just serde the input and output but don't run in a
|
| 568 |
+
# subprocess.
|
| 569 |
+
return self._run_in_child(pickled_input)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
class _OutOfProcessFxCompile(_SerializedFxCompile):
|
| 573 |
+
"""
|
| 574 |
+
Represents an FxCompile which is run outside the current process (in
|
| 575 |
+
either a subprocess or possibly even a separate machine).
|
| 576 |
+
"""
|
| 577 |
+
|
| 578 |
+
@override
|
| 579 |
+
@final
|
| 580 |
+
def _send_to_child(
|
| 581 |
+
self, pickled_input: _WireProtocolPickledInput
|
| 582 |
+
) -> _WireProtocolPickledOutput:
|
| 583 |
+
f = self._send_to_child_async(pickled_input)
|
| 584 |
+
|
| 585 |
+
# For debugging: If we want to print status updates...
|
| 586 |
+
# last = time.time()
|
| 587 |
+
# while not f.done():
|
| 588 |
+
# print("tick...")
|
| 589 |
+
# time.sleep(0.125)
|
| 590 |
+
# now = time.time()
|
| 591 |
+
# if now - last > 1:
|
| 592 |
+
# last = now
|
| 593 |
+
|
| 594 |
+
return f.result()
|
| 595 |
+
|
| 596 |
+
@abstractmethod
|
| 597 |
+
def _send_to_child_async(
|
| 598 |
+
self, pickled_input: _WireProtocolPickledInput
|
| 599 |
+
) -> Future[_WireProtocolPickledOutput]: ...
|
| 600 |
+
|
| 601 |
+
def _postprocess(self, output: _WireProtocolOutput) -> None:
|
| 602 |
+
# Since our metrics were gathered in a subprocess make sure to add them
|
| 603 |
+
# here.
|
| 604 |
+
CachedMetricsHelper.apply_deltas(output.metrics)
|
| 605 |
+
|
| 606 |
+
# This is used by tests to check the output for specific details. For
|
| 607 |
+
# remote things (subproc and RE) we need to do the `save_output_code`
|
| 608 |
+
# here since it didn't happen earlier in-process. In the future if this
|
| 609 |
+
# doesn't have "source_code" (it's a CompiledAOTI, for example) and we
|
| 610 |
+
# need it we'll have to grab it and serialize it separately from the
|
| 611 |
+
# child.
|
| 612 |
+
if GraphLowering.save_output_code is not None:
|
| 613 |
+
GraphLowering.save_output_code(output.graph.source_code) # type: ignore[attr-defined]
|
| 614 |
+
|
| 615 |
+
# And forward our collected logs. The cache is cleared when the outer
|
| 616 |
+
# function exits.
|
| 617 |
+
@functools.cache
|
| 618 |
+
def getLogger(name: str) -> logging.Logger:
|
| 619 |
+
return logging.getLogger(name)
|
| 620 |
+
|
| 621 |
+
if output.warning_replay:
|
| 622 |
+
for w in output.warning_replay:
|
| 623 |
+
warnings.warn_explicit(
|
| 624 |
+
message=w.message,
|
| 625 |
+
category=w.category,
|
| 626 |
+
filename=w.filename,
|
| 627 |
+
lineno=w.lineno,
|
| 628 |
+
source=w.source,
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
for record in output.logs:
|
| 632 |
+
logger = getLogger(record.name)
|
| 633 |
+
logger.handle(record)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
# For debugging - create a _FxCompile which writes the serialized data to a file
|
| 637 |
+
# and then exits.
|
| 638 |
+
#
|
| 639 |
+
# TODO: make this a FxCompileMode value?
|
| 640 |
+
#
|
| 641 |
+
# The "child runner" should look something like this:
|
| 642 |
+
#
|
| 643 |
+
# import torch
|
| 644 |
+
# from torch._inductor import compile_fx
|
| 645 |
+
# idx = 0
|
| 646 |
+
# with open(f"/tmp/pytorch_compile_fx_tmp_input_{idx}.bin", "rb") as f:
|
| 647 |
+
# input = compile_fx._WireProtocolPickledInput(f.read())
|
| 648 |
+
# result = compile_fx._SubprocessFxCompile._run_in_child(input)
|
| 649 |
+
# with open(f"/tmp/pytorch_compile_fx_tmp_output_{idx}.bin", "wb") as f:
|
| 650 |
+
# f.write(result.value)
|
| 651 |
+
#
|
| 652 |
+
@final
|
| 653 |
+
class _DebugFileFxCompile(_SerializedFxCompile):
|
| 654 |
+
file_index = 0
|
| 655 |
+
|
| 656 |
+
@override
|
| 657 |
+
def _send_to_child(
|
| 658 |
+
self, pickled_input: _WireProtocolPickledInput
|
| 659 |
+
) -> _WireProtocolPickledOutput:
|
| 660 |
+
idx = _DebugFileFxCompile.file_index
|
| 661 |
+
_DebugFileFxCompile.file_index += 1
|
| 662 |
+
|
| 663 |
+
name = f"/tmp/aorenste/pytorch_compile_fx_tmp_input_{idx}.bin"
|
| 664 |
+
with open(name, "wb") as f:
|
| 665 |
+
f.write(pickled_input.value)
|
| 666 |
+
print(f"Wrote to {name}")
|
| 667 |
+
|
| 668 |
+
if False:
|
| 669 |
+
name = f"/tmp/aorenste/pytorch_compile_fx_tmp_actual_{idx}.bin"
|
| 670 |
+
actual = self._run_in_child(pickled_input)
|
| 671 |
+
with open(name, "wb") as f:
|
| 672 |
+
f.write(actual.value)
|
| 673 |
+
return actual
|
| 674 |
+
elif False:
|
| 675 |
+
name = f"/tmp/aorenste/pytorch_compile_fx_tmp_output_{idx}.bin"
|
| 676 |
+
with open(name, "rb") as f:
|
| 677 |
+
result = _WireProtocolPickledOutput(f.read())
|
| 678 |
+
print(f"Read from {name}")
|
| 679 |
+
return result
|
| 680 |
+
else:
|
| 681 |
+
os._exit(-1)
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_fx_subproc.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import atexit
|
| 4 |
+
import functools
|
| 5 |
+
import os
|
| 6 |
+
from typing import Optional, TYPE_CHECKING
|
| 7 |
+
from typing_extensions import final, override
|
| 8 |
+
|
| 9 |
+
import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
|
| 10 |
+
import torch.fx
|
| 11 |
+
from torch._inductor.compile_worker.subproc_pool import (
|
| 12 |
+
AnyPool,
|
| 13 |
+
SubprocKind,
|
| 14 |
+
SubprocPool,
|
| 15 |
+
)
|
| 16 |
+
from torch._inductor.utils import clear_caches
|
| 17 |
+
|
| 18 |
+
from .compile_fx_ext import (
|
| 19 |
+
_OutOfProcessFxCompile,
|
| 20 |
+
_WireProtocolPickledInput,
|
| 21 |
+
_WireProtocolPickledOutput,
|
| 22 |
+
)
|
| 23 |
+
from .output_code import complex_memory_overlap as complex_memory_overlap # noqa: F401
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from collections.abc import Mapping
|
| 28 |
+
from concurrent.futures import Future
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@final
|
| 32 |
+
class _SubprocessFxCompile(_OutOfProcessFxCompile):
|
| 33 |
+
@override
|
| 34 |
+
def _send_to_child_async(
|
| 35 |
+
self, input: _WireProtocolPickledInput
|
| 36 |
+
) -> Future[_WireProtocolPickledOutput]:
|
| 37 |
+
# TODO: Do we need to copy across some kind of logging IDs? (ChromiumEventLogger)
|
| 38 |
+
|
| 39 |
+
pool = self.process_pool()
|
| 40 |
+
|
| 41 |
+
# TODO: This is probably the wrong thing to do long-term - but for now
|
| 42 |
+
# let's share the cache so we can identify tests broken by this later.
|
| 43 |
+
env_vars = ["TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"]
|
| 44 |
+
extra_env = {v: os.environ[v] for v in env_vars if v in os.environ}
|
| 45 |
+
|
| 46 |
+
return pool.submit(
|
| 47 |
+
_SubprocessFxCompile._run_in_child_subprocess, input, extra_env
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
@functools.cache
|
| 52 |
+
def process_pool() -> AnyPool:
|
| 53 |
+
pool = SubprocPool(
|
| 54 |
+
# TODO: Consider raising this limit if we start using async w/
|
| 55 |
+
# subprocess and want to compile multiple graphs in parallel.
|
| 56 |
+
1,
|
| 57 |
+
kind=SubprocKind.SPAWN,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
atexit.register(pool.shutdown)
|
| 61 |
+
|
| 62 |
+
return pool
|
| 63 |
+
|
| 64 |
+
@classmethod
|
| 65 |
+
def _run_in_child_subprocess(
|
| 66 |
+
cls,
|
| 67 |
+
pickled_input: _WireProtocolPickledInput,
|
| 68 |
+
extra_env: Optional[Mapping[str, str]],
|
| 69 |
+
) -> _WireProtocolPickledOutput:
|
| 70 |
+
# TODO: In subprocess mode we need to clear the inductor caches.
|
| 71 |
+
# The problem:
|
| 72 |
+
# 1. We compile in worker A which fills stuff in tmpdir
|
| 73 |
+
# 2. parent clears inductor caches which deletes tmpdirs and tells
|
| 74 |
+
# cpp_prefix_path() to clear its LRU cache
|
| 75 |
+
# 3. We compile a second time in subproc A - but since we never told
|
| 76 |
+
# cpp_prefix_path() in worker A to clear its LRU it thinks the
|
| 77 |
+
# tmpdir still exists and fails to compile.
|
| 78 |
+
#
|
| 79 |
+
# TODO: We probably should be using a separate tmpdir in the worker
|
| 80 |
+
# anyway... but we should probably still respect clear_caches()
|
| 81 |
+
# in the parent... maybe?
|
| 82 |
+
#
|
| 83 |
+
# TODO: We could be less aggressive by keeping a clock which gets
|
| 84 |
+
# incremented when we clear the cache, send the clock to the worker and
|
| 85 |
+
# only clear caches if the clock changed since last time.
|
| 86 |
+
#
|
| 87 |
+
clear_caches()
|
| 88 |
+
torch._inductor.metrics.reset()
|
| 89 |
+
|
| 90 |
+
# TODO: turn off config.fx_graph_async_compile
|
| 91 |
+
|
| 92 |
+
result = cls._run_in_child(pickled_input, extra_env)
|
| 93 |
+
return result
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__init__.py
ADDED
|
File without changes
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__main__.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import argparse
|
| 3 |
+
import base64
|
| 4 |
+
import functools
|
| 5 |
+
import importlib
|
| 6 |
+
import logging
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
from typing import TypeVar
|
| 10 |
+
|
| 11 |
+
from torch._inductor.async_compile import pre_fork_setup
|
| 12 |
+
from torch._inductor.codecache import torch_key
|
| 13 |
+
from torch._inductor.compile_worker.subproc_pool import (
|
| 14 |
+
SubprocKind,
|
| 15 |
+
SubprocMain,
|
| 16 |
+
SubprocPickler,
|
| 17 |
+
)
|
| 18 |
+
from torch._inductor.compile_worker.utils import _async_compile_initializer
|
| 19 |
+
from torch._inductor.runtime.compile_tasks import _set_triton_ptxas_path
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_T = TypeVar("_T")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
log = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
_set_triton_ptxas_path()
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
import triton
|
| 31 |
+
|
| 32 |
+
assert triton is not None # preload in parent
|
| 33 |
+
except ImportError:
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _lookup_and_create_type(base: type[_T], qname: str) -> _T:
|
| 38 |
+
"""
|
| 39 |
+
Given a base type and qualified name: import & lookup that name, check
|
| 40 |
+
that it's of the given type and then instantiate it.
|
| 41 |
+
"""
|
| 42 |
+
pkg, name = qname.rsplit(".", 1)
|
| 43 |
+
mod = importlib.import_module(pkg)
|
| 44 |
+
ty = getattr(mod, name)
|
| 45 |
+
if not issubclass(ty, base):
|
| 46 |
+
raise TypeError(f"Type {ty} is not a subtype of {base}")
|
| 47 |
+
return ty()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def main():
|
| 51 |
+
try:
|
| 52 |
+
parser = argparse.ArgumentParser()
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
"--pickler", type=functools.partial(_lookup_and_create_type, SubprocPickler)
|
| 55 |
+
)
|
| 56 |
+
parser.add_argument("--kind", type=SubprocKind)
|
| 57 |
+
parser.add_argument("--workers", type=int)
|
| 58 |
+
parser.add_argument("--parent", type=int)
|
| 59 |
+
parser.add_argument("--read-fd", type=int)
|
| 60 |
+
parser.add_argument("--write-fd", type=int)
|
| 61 |
+
parser.add_argument("--torch-key", type=str)
|
| 62 |
+
args = parser.parse_args()
|
| 63 |
+
if os.getppid() != args.parent:
|
| 64 |
+
sys.exit(0)
|
| 65 |
+
read_fd = os.fdopen(args.read_fd, "rb")
|
| 66 |
+
write_fd = os.fdopen(args.write_fd, "wb")
|
| 67 |
+
|
| 68 |
+
pre_fork_setup()
|
| 69 |
+
|
| 70 |
+
torch_key.set(base64.b64decode(args.torch_key.encode("utf-8"))) # type: ignore[attr-defined]
|
| 71 |
+
|
| 72 |
+
_async_compile_initializer(args.parent)
|
| 73 |
+
|
| 74 |
+
SubprocMain(args.pickler, args.kind, args.workers, read_fd, write_fd).main()
|
| 75 |
+
except Exception:
|
| 76 |
+
log.exception("Uncaught exception in compile_worker subprocess")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
if __name__ == "__main__":
|
| 80 |
+
main()
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (213 Bytes). View file
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/__pycache__/utils.cpython-311.pyc
ADDED
|
Binary file (2.12 kB). View file
|
|
|
pace_revision_2/.venv-pace/lib/python3.11/site-packages/torch/_inductor/compile_worker/subproc_pool.py
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
| 1 |
+
import base64
|
| 2 |
+
import functools
|
| 3 |
+
import itertools
|
| 4 |
+
import logging
|
| 5 |
+
import multiprocessing
|
| 6 |
+
import os
|
| 7 |
+
import pickle
|
| 8 |
+
import struct
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import threading
|
| 12 |
+
import traceback
|
| 13 |
+
import typing
|
| 14 |
+
from concurrent.futures import Future, ProcessPoolExecutor
|
| 15 |
+
from concurrent.futures.process import BrokenProcessPool
|
| 16 |
+
from enum import Enum, IntEnum
|
| 17 |
+
from typing import Any, Callable, IO, Optional, TypeVar
|
| 18 |
+
from typing_extensions import Never, ParamSpec
|
| 19 |
+
|
| 20 |
+
# _thread_safe_fork is needed because the subprocesses in the pool can read
|
| 21 |
+
# justknobs, e.g., in the Triton compiler. For internal, the import installs
|
| 22 |
+
# functionality to destroy singletons before forking and re-enable them after.
|
| 23 |
+
import torch._thread_safe_fork # noqa: F401
|
| 24 |
+
from torch._inductor import config
|
| 25 |
+
from torch._inductor.codecache import torch_key
|
| 26 |
+
from torch._inductor.compile_worker.tracked_process_pool import (
|
| 27 |
+
TrackedProcessPoolExecutor,
|
| 28 |
+
)
|
| 29 |
+
from torch._inductor.compile_worker.utils import _async_compile_initializer
|
| 30 |
+
from torch._inductor.utils import get_ld_library_path, python_subprocess_env
|
| 31 |
+
from torch._utils_internal import find_compile_subproc_binary
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
log = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
_P = ParamSpec("_P")
|
| 37 |
+
_T = TypeVar("_T")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class MsgHeader(IntEnum):
|
| 41 |
+
ERROR = 0
|
| 42 |
+
SHUTDOWN = 1
|
| 43 |
+
QUIESCE = 2
|
| 44 |
+
WAKEUP = 3
|
| 45 |
+
JOB = 4
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _pack_msg(msg_header: MsgHeader, job_id: int, length: int) -> bytes:
|
| 49 |
+
return struct.pack("nnn", int(msg_header), job_id, length)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _unpack_msg(data: bytes) -> tuple[MsgHeader, int, int]:
|
| 53 |
+
if not data:
|
| 54 |
+
return MsgHeader.ERROR, -1, -1
|
| 55 |
+
msg_header, job_id, length = struct.unpack("nnn", data)
|
| 56 |
+
return MsgHeader(msg_header), job_id, length
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
msg_bytes = len(_pack_msg(MsgHeader.JOB, 0, 0))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _send_msg(
|
| 63 |
+
write_pipe: IO[bytes], msg_header: MsgHeader, job_id: int = -1, data: bytes = b""
|
| 64 |
+
) -> None:
|
| 65 |
+
length = len(data)
|
| 66 |
+
write_pipe.write(_pack_msg(msg_header, job_id, length))
|
| 67 |
+
if length > 0:
|
| 68 |
+
write_pipe.write(data)
|
| 69 |
+
write_pipe.flush()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _recv_msg(read_pipe: IO[bytes]) -> tuple[MsgHeader, int, bytes]:
|
| 73 |
+
msg_header, job_id, length = _unpack_msg(read_pipe.read(msg_bytes))
|
| 74 |
+
data = read_pipe.read(length) if length > 0 else b""
|
| 75 |
+
return msg_header, job_id, data
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class _SubprocExceptionInfo:
|
| 79 |
+
"""
|
| 80 |
+
Carries exception info from subprocesses across the wire. traceback
|
| 81 |
+
objects are not pickleable, so we store the trace as a string and
|
| 82 |
+
use it for the message in the exception thrown in the main process.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def __init__(self, details: str) -> None:
|
| 86 |
+
self.details = details
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class SubprocException(Exception):
|
| 90 |
+
"""
|
| 91 |
+
Thrown when a job in a subprocess raises an Exception.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
def __init__(self, details: str, name: str = "<unknown>") -> None:
|
| 95 |
+
self.details = details
|
| 96 |
+
super().__init__(
|
| 97 |
+
f"An exception occurred in a subprocess:\n\nName={name}\n{details}"
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
def with_name(self, name: str) -> "SubprocException":
|
| 101 |
+
return SubprocException(self.details, name)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class SubprocPickler:
|
| 105 |
+
"""
|
| 106 |
+
Allows a caller to provide a custom pickler for passing data with the
|
| 107 |
+
subprocess.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def dumps(self, obj: object) -> bytes:
|
| 111 |
+
return pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
|
| 112 |
+
|
| 113 |
+
def loads(self, data: bytes) -> object:
|
| 114 |
+
return pickle.loads(data)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class SubprocKind(Enum):
|
| 118 |
+
FORK = "fork"
|
| 119 |
+
SPAWN = "spawn"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class SubprocPool:
|
| 123 |
+
"""
|
| 124 |
+
Mimic a concurrent.futures.ProcessPoolExecutor, but wrap it in
|
| 125 |
+
a subprocess.Popen() to try to avoid issues with forking/spawning
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
def __init__(
|
| 129 |
+
self,
|
| 130 |
+
nprocs: int,
|
| 131 |
+
pickler: Optional[SubprocPickler] = None,
|
| 132 |
+
kind: SubprocKind = SubprocKind.FORK,
|
| 133 |
+
) -> None:
|
| 134 |
+
entry = os.path.join(os.path.dirname(__file__), "__main__.py")
|
| 135 |
+
self.pickler = pickler or SubprocPickler()
|
| 136 |
+
self.kind = kind
|
| 137 |
+
|
| 138 |
+
subproc_read_fd, write_fd = os.pipe()
|
| 139 |
+
read_fd, subproc_write_fd = os.pipe()
|
| 140 |
+
self.write_pipe = os.fdopen(write_fd, "wb")
|
| 141 |
+
self.read_pipe = os.fdopen(read_fd, "rb")
|
| 142 |
+
torch_key_str = base64.b64encode(torch_key()).decode("utf-8")
|
| 143 |
+
|
| 144 |
+
cmd = [
|
| 145 |
+
sys.executable,
|
| 146 |
+
entry,
|
| 147 |
+
]
|
| 148 |
+
if (binary := find_compile_subproc_binary()) is not None:
|
| 149 |
+
cmd = [binary]
|
| 150 |
+
|
| 151 |
+
args = [
|
| 152 |
+
f"--pickler={self.pickler.__class__.__module__}.{self.pickler.__class__.__name__}",
|
| 153 |
+
f"--kind={self.kind.value}",
|
| 154 |
+
f"--workers={nprocs}",
|
| 155 |
+
f"--parent={os.getpid()}",
|
| 156 |
+
f"--read-fd={str(subproc_read_fd)}",
|
| 157 |
+
f"--write-fd={str(subproc_write_fd)}",
|
| 158 |
+
f"--torch-key={torch_key_str}",
|
| 159 |
+
]
|
| 160 |
+
cmd.extend(args)
|
| 161 |
+
log_path = None
|
| 162 |
+
self.log_file = None
|
| 163 |
+
|
| 164 |
+
if config.worker_suppress_logging:
|
| 165 |
+
log_path = os.devnull
|
| 166 |
+
log.info("Suppressing compile worker output due to config")
|
| 167 |
+
else:
|
| 168 |
+
log_path = config.torchinductor_worker_logpath
|
| 169 |
+
if not log_path:
|
| 170 |
+
log_path = config.get_worker_log_path()
|
| 171 |
+
|
| 172 |
+
if log_path:
|
| 173 |
+
self.log_file = open(log_path, "w")
|
| 174 |
+
|
| 175 |
+
self.process = subprocess.Popen(
|
| 176 |
+
cmd,
|
| 177 |
+
env={
|
| 178 |
+
**python_subprocess_env(),
|
| 179 |
+
# Safeguard against creating a SubprocPool in the subprocess.
|
| 180 |
+
"TORCH_WARM_POOL": "0",
|
| 181 |
+
# Some internal usages need a modified LD_LIBRARY_PATH.
|
| 182 |
+
"LD_LIBRARY_PATH": get_ld_library_path(),
|
| 183 |
+
},
|
| 184 |
+
pass_fds=(subproc_read_fd, subproc_write_fd),
|
| 185 |
+
stdout=self.log_file,
|
| 186 |
+
stderr=self.log_file,
|
| 187 |
+
)
|
| 188 |
+
self.write_lock = threading.Lock()
|
| 189 |
+
self.read_thread = threading.Thread(
|
| 190 |
+
target=self._read_thread, name="InductorSubproc", daemon=True
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
self.futures_lock = threading.Lock()
|
| 194 |
+
self.pending_futures: dict[int, Future[Any]] = {}
|
| 195 |
+
self.job_id_count = itertools.count()
|
| 196 |
+
|
| 197 |
+
self.running = True
|
| 198 |
+
|
| 199 |
+
# Start thread last to ensure all member variables are initialized
|
| 200 |
+
# before any access.
|
| 201 |
+
self.read_thread.start()
|
| 202 |
+
|
| 203 |
+
def submit(
|
| 204 |
+
self, job_fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
|
| 205 |
+
) -> Future[_T]:
|
| 206 |
+
if args or kwargs:
|
| 207 |
+
job_fn = functools.partial(job_fn, *args, **kwargs)
|
| 208 |
+
job_data = self.pickler.dumps(job_fn)
|
| 209 |
+
future: Future[_T]
|
| 210 |
+
with self.futures_lock:
|
| 211 |
+
job_id = next(self.job_id_count)
|
| 212 |
+
self.pending_futures[job_id] = future = Future()
|
| 213 |
+
future.set_running_or_notify_cancel()
|
| 214 |
+
self._send(MsgHeader.JOB, job_id, job_data)
|
| 215 |
+
return future
|
| 216 |
+
|
| 217 |
+
def _send(self, msg_header: MsgHeader, job_id: int = -1, data: bytes = b"") -> None:
|
| 218 |
+
with self.write_lock:
|
| 219 |
+
if not self.running:
|
| 220 |
+
raise RuntimeError("Attempting to use a closed pool")
|
| 221 |
+
_send_msg(self.write_pipe, msg_header, job_id, data)
|
| 222 |
+
|
| 223 |
+
def _read_thread(self) -> None:
|
| 224 |
+
while True:
|
| 225 |
+
data = b""
|
| 226 |
+
job_id = -1
|
| 227 |
+
try:
|
| 228 |
+
msg_header, job_id, data = _recv_msg(self.read_pipe)
|
| 229 |
+
except Exception:
|
| 230 |
+
# Something went wrong during the read. There's no way we have a
|
| 231 |
+
# valid msg.
|
| 232 |
+
log.exception("failure in subproc_pool._recv_msg")
|
| 233 |
+
msg_header = MsgHeader.ERROR
|
| 234 |
+
|
| 235 |
+
if msg_header != MsgHeader.JOB:
|
| 236 |
+
# read_pipe returned None or got exception
|
| 237 |
+
if self.running:
|
| 238 |
+
log.warning("SubprocPool unclean exit")
|
| 239 |
+
self.running = False
|
| 240 |
+
self.read_pipe.close()
|
| 241 |
+
# Cancel all the pending futures.
|
| 242 |
+
self.shutdown()
|
| 243 |
+
return
|
| 244 |
+
|
| 245 |
+
try:
|
| 246 |
+
result = self.pickler.loads(data)
|
| 247 |
+
except Exception as e:
|
| 248 |
+
# Something went wrong unpickling. We have a job_id so just
|
| 249 |
+
# notify that particular future and continue on.
|
| 250 |
+
log.exception("unpickle failure in SubprocPool._read_thread")
|
| 251 |
+
result = e
|
| 252 |
+
|
| 253 |
+
with self.futures_lock:
|
| 254 |
+
if not self.running:
|
| 255 |
+
return
|
| 256 |
+
if isinstance(result, _SubprocExceptionInfo):
|
| 257 |
+
# An exception occurred in the submitted job
|
| 258 |
+
self.pending_futures[job_id].set_exception(
|
| 259 |
+
SubprocException(result.details)
|
| 260 |
+
)
|
| 261 |
+
elif isinstance(result, Exception):
|
| 262 |
+
# An exception occurred in some of our subprocess machinery.
|
| 263 |
+
self.pending_futures[job_id].set_exception(result)
|
| 264 |
+
else:
|
| 265 |
+
self.pending_futures[job_id].set_result(result)
|
| 266 |
+
del self.pending_futures[job_id]
|
| 267 |
+
|
| 268 |
+
def quiesce(self) -> None:
|
| 269 |
+
self._send(MsgHeader.QUIESCE)
|
| 270 |
+
|
| 271 |
+
def wakeup(self) -> None:
|
| 272 |
+
self._send(MsgHeader.WAKEUP)
|
| 273 |
+
|
| 274 |
+
def shutdown(self) -> None:
|
| 275 |
+
try:
|
| 276 |
+
with self.write_lock:
|
| 277 |
+
if not self.running:
|
| 278 |
+
return
|
| 279 |
+
self.running = False
|
| 280 |
+
_send_msg(self.write_pipe, MsgHeader.SHUTDOWN)
|
| 281 |
+
self.write_pipe.close()
|
| 282 |
+
self.process.wait(300)
|
| 283 |
+
if self.log_file:
|
| 284 |
+
self.log_file.close()
|
| 285 |
+
except OSError as e:
|
| 286 |
+
log.warning("Ignored OSError in pool shutdown: %s", e)
|
| 287 |
+
finally:
|
| 288 |
+
with self.futures_lock:
|
| 289 |
+
for future in self.pending_futures.values():
|
| 290 |
+
if not future.cancel():
|
| 291 |
+
future.set_exception(RuntimeError("SubprocPool closed"))
|
| 292 |
+
self.pending_futures.clear()
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
class SubprocMain:
|
| 296 |
+
"""Communicates with a SubprocPool in the parent process, called by __main__.py"""
|
| 297 |
+
|
| 298 |
+
def __init__(
|
| 299 |
+
self,
|
| 300 |
+
pickler: SubprocPickler,
|
| 301 |
+
kind: SubprocKind,
|
| 302 |
+
nprocs: int,
|
| 303 |
+
read_pipe: IO[bytes],
|
| 304 |
+
write_pipe: IO[bytes],
|
| 305 |
+
) -> None:
|
| 306 |
+
self.pickler = pickler
|
| 307 |
+
self.kind = kind
|
| 308 |
+
self.read_pipe = read_pipe
|
| 309 |
+
self.write_pipe = write_pipe
|
| 310 |
+
self.write_lock = threading.Lock()
|
| 311 |
+
self.nprocs = nprocs
|
| 312 |
+
self.pool: Optional[ProcessPoolExecutor] = None
|
| 313 |
+
self.running = True
|
| 314 |
+
|
| 315 |
+
def main(self) -> None:
|
| 316 |
+
while True:
|
| 317 |
+
msg_header, job_id, data = _recv_msg(self.read_pipe)
|
| 318 |
+
if msg_header == MsgHeader.JOB:
|
| 319 |
+
self.submit(job_id, data)
|
| 320 |
+
elif msg_header == MsgHeader.WAKEUP:
|
| 321 |
+
self._start_pool()
|
| 322 |
+
elif msg_header == MsgHeader.QUIESCE:
|
| 323 |
+
self._quiesce()
|
| 324 |
+
else:
|
| 325 |
+
return self._shutdown()
|
| 326 |
+
|
| 327 |
+
def _quiesce(self) -> None:
|
| 328 |
+
if self.pool is not None:
|
| 329 |
+
self.pool.shutdown(wait=False)
|
| 330 |
+
self.pool = None
|
| 331 |
+
|
| 332 |
+
def _shutdown(self) -> None:
|
| 333 |
+
with self.write_lock:
|
| 334 |
+
self.running = False
|
| 335 |
+
try:
|
| 336 |
+
_send_msg(self.write_pipe, MsgHeader.SHUTDOWN)
|
| 337 |
+
self.write_pipe.close()
|
| 338 |
+
except BrokenPipeError:
|
| 339 |
+
pass # parent process already shutdown
|
| 340 |
+
self.read_pipe.close()
|
| 341 |
+
self._quiesce()
|
| 342 |
+
|
| 343 |
+
def submit(self, job_id: int, data: bytes) -> None:
|
| 344 |
+
while self.running:
|
| 345 |
+
try:
|
| 346 |
+
self._submit_inner(job_id, data)
|
| 347 |
+
return
|
| 348 |
+
except BrokenProcessPool:
|
| 349 |
+
# If any subprocess in the pool crashes, we get a BrokenProcessPool
|
| 350 |
+
# exception and the whole pool becomes unusable. Handle crashes by
|
| 351 |
+
# recreating the pool and resubmitting.
|
| 352 |
+
self.pool = None
|
| 353 |
+
|
| 354 |
+
def _submit_inner(self, job_id: int, data: bytes) -> None:
|
| 355 |
+
def callback(fut: Future[Any]) -> None:
|
| 356 |
+
if not self.running:
|
| 357 |
+
return
|
| 358 |
+
try:
|
| 359 |
+
result = fut.result()
|
| 360 |
+
except Exception as e:
|
| 361 |
+
log.exception("Error in subprocess")
|
| 362 |
+
result = self.pickler.dumps(e)
|
| 363 |
+
assert isinstance(result, bytes)
|
| 364 |
+
with self.write_lock:
|
| 365 |
+
if self.running:
|
| 366 |
+
_send_msg(self.write_pipe, MsgHeader.JOB, job_id, result)
|
| 367 |
+
return
|
| 368 |
+
|
| 369 |
+
self._start_pool()
|
| 370 |
+
assert self.pool is not None
|
| 371 |
+
|
| 372 |
+
future = self.pool.submit(
|
| 373 |
+
functools.partial(SubprocMain.do_job, self.pickler, data)
|
| 374 |
+
)
|
| 375 |
+
future.add_done_callback(callback)
|
| 376 |
+
|
| 377 |
+
def _start_pool(self) -> None:
|
| 378 |
+
if self.pool is not None:
|
| 379 |
+
return
|
| 380 |
+
|
| 381 |
+
self.pool = TrackedProcessPoolExecutor(
|
| 382 |
+
self.nprocs,
|
| 383 |
+
mp_context=multiprocessing.get_context(self.kind.value),
|
| 384 |
+
initializer=functools.partial(_async_compile_initializer, os.getpid()),
|
| 385 |
+
)
|
| 386 |
+
multiprocessing.util.Finalize(
|
| 387 |
+
None, self.pool.shutdown, exitpriority=sys.maxsize
|
| 388 |
+
)
|
| 389 |
+
_warm_process_pool(self.pool, self.nprocs)
|
| 390 |
+
|
| 391 |
+
@staticmethod
|
| 392 |
+
def do_job(pickler: SubprocPickler, data: bytes) -> bytes:
|
| 393 |
+
# do the pickle/unpickle in the sub-subproc
|
| 394 |
+
job = typing.cast(Callable[[], object], pickler.loads(data))
|
| 395 |
+
|
| 396 |
+
try:
|
| 397 |
+
result = job()
|
| 398 |
+
except Exception:
|
| 399 |
+
result = _SubprocExceptionInfo(traceback.format_exc())
|
| 400 |
+
return pickler.dumps(result)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
AnyPool = typing.Union[ProcessPoolExecutor, SubprocPool]
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def _warm_process_pool(pool: ProcessPoolExecutor, n: int) -> None:
|
| 407 |
+
# We have to fork processes for compiler workers, but the more memory and other resources that are loaded, the
|
| 408 |
+
# slower the os.fork time is, quite drastically. It also holds the GIL so we can't put it on another thread.
|
| 409 |
+
|
| 410 |
+
# Examples:
|
| 411 |
+
# A simple x + x + x script: 10ms seconds in the middle of the program, 2ms at startup
|
| 412 |
+
# tf_efficientnet_b0 benchmark: 50ms! in the middle of the program , 3ms at startup
|
| 413 |
+
|
| 414 |
+
# So we want to start the workers early when it is still cheap, and also to allow the workers to get
|
| 415 |
+
# ready before we have work for them.
|
| 416 |
+
|
| 417 |
+
# ProcessPoolExecutor also does not launch the workers until it finds a point when all the workers are idle.
|
| 418 |
+
# But if we waited until then fork time will be long and we will be waiting for the processes to initialize.
|
| 419 |
+
|
| 420 |
+
# We force them to start here with some YOLOing of the internal methods.
|
| 421 |
+
|
| 422 |
+
if hasattr(pool, "_start_queue_management_thread"):
|
| 423 |
+
pool._start_queue_management_thread()
|
| 424 |
+
else:
|
| 425 |
+
for _ in range(n):
|
| 426 |
+
pool._adjust_process_count()
|
| 427 |
+
if hasattr(pool, "_start_executor_manager_thread"):
|
| 428 |
+
pool._start_executor_manager_thread()
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class TestException(RuntimeError):
|
| 432 |
+
pass
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def raise_testexc() -> Never:
|
| 436 |
+
raise TestException
|