Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/__init__.py +3 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/common.py +356 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/flex_attention.py +977 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/flex_cpu.py +339 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/flex_decoding.py +436 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/flex_flash_attention.py +491 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/common.py.jinja +204 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flash_attention.py.jinja +76 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flash_attention_backward.py.jinja +28 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flex_attention.py.jinja +215 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flex_backwards.py.jinja +620 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flex_decode.py.jinja +242 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/utilities.py.jinja +59 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/cutedsl_mm_grouped.py.jinja +333 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_blackwell_ws_persistent_device_tma_mm.py.jinja +107 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_epilogue_scaled_mm.py.jinja +194 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_main_loop_scaled_mm.py.jinja +212 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_mm.py.jinja +72 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_mm_rocm.py.jinja +71 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_persistent_tma_mm.py.jinja +129 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/vendored_templates/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl_grouped_gemm.py +2372 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/lookup_table/__init__.py +32 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/lookup_table/choices.py +418 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/package/__init__.py +1 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/package/build_package.py +15 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/package/package.py +138 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/autotune_cache.py +649 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/benchmarking.py +441 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/cache_dir_utils.py +54 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/__init__.py +68 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/config.py +127 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/context.py +292 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/exceptions.py +189 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/implementations.py +415 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/interfaces.py +818 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/locks.py +202 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/utils.py +109 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/compile_tasks.py +78 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/coordinate_descent_tuner.py +412 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/debug_utils.py +138 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/halide_helpers.py +118 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/hints.py +224 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/runtime_utils.py +249 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/static_cuda_launcher.py +270 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/triton_compat.py +176 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/triton_helpers.py +761 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/triton_heuristics.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/template_heuristics/__init__.py +6 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
# Import so here and then reimport above so that register_lowering gets triggered
|
| 3 |
+
from . import flex_attention, flex_decoding
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Common utilities and functions for flex attention kernels"""
|
| 3 |
+
|
| 4 |
+
import math
|
| 5 |
+
from collections.abc import Sequence
|
| 6 |
+
from functools import partial
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch._inductor.virtualized import V
|
| 14 |
+
from torch.utils._ordered_set import OrderedSet
|
| 15 |
+
from torch.utils._pytree import tree_map, tree_map_only
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from torch._inductor.codegen.cuda_combined_scheduling import _IntLike
|
| 20 |
+
else:
|
| 21 |
+
_IntLike = Union[int, sympy.Expr]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
from ...ir import (
|
| 25 |
+
ComputedBuffer,
|
| 26 |
+
ExternKernel,
|
| 27 |
+
FixedLayout,
|
| 28 |
+
FlexibleLayout,
|
| 29 |
+
get_fill_order,
|
| 30 |
+
InputBuffer,
|
| 31 |
+
IRNode,
|
| 32 |
+
MutationLayoutSHOULDREMOVE,
|
| 33 |
+
Scatter,
|
| 34 |
+
ShapeAsConstantBuffer,
|
| 35 |
+
StorageBox,
|
| 36 |
+
Subgraph,
|
| 37 |
+
TensorBox,
|
| 38 |
+
)
|
| 39 |
+
from ...lowering import (
|
| 40 |
+
_full,
|
| 41 |
+
check_and_broadcast_indices,
|
| 42 |
+
expand,
|
| 43 |
+
index_output_size_and_inner_fn,
|
| 44 |
+
to_dtype,
|
| 45 |
+
)
|
| 46 |
+
from ...select_algorithm import realize_inputs
|
| 47 |
+
from ...utils import load_template
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
SubgraphResults = Union[list[Optional[ComputedBuffer]], Optional[ComputedBuffer]]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def zeros_and_scatter_lowering(shape: list[int], indices, values):
|
| 54 |
+
"""To support backwards on captured buffers we register a specific lowering for our specific custom up"""
|
| 55 |
+
# Always accumulate into fp32 then cast
|
| 56 |
+
grad = _full(0, values.get_device(), torch.float32, shape)
|
| 57 |
+
assert isinstance(grad, TensorBox)
|
| 58 |
+
grad.realize()
|
| 59 |
+
x_size = grad.get_size()
|
| 60 |
+
values = to_dtype(values, grad.get_dtype())
|
| 61 |
+
indices_loaders = [i.make_loader() if i is not None else None for i in indices]
|
| 62 |
+
indices, tensor_indices = check_and_broadcast_indices(indices, grad.get_device())
|
| 63 |
+
# We can use the first one since they are all required to be the same size
|
| 64 |
+
tensor_size = list(indices[tensor_indices[0]].get_size())
|
| 65 |
+
indexed_size = [x_size[i] for i in range(len(indices))]
|
| 66 |
+
|
| 67 |
+
expected_vals_size, inner_fn = index_output_size_and_inner_fn(
|
| 68 |
+
x_size,
|
| 69 |
+
indices,
|
| 70 |
+
tensor_indices,
|
| 71 |
+
tensor_size,
|
| 72 |
+
indices_loaders,
|
| 73 |
+
indexed_size,
|
| 74 |
+
None,
|
| 75 |
+
check=True,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
values = expand(values, expected_vals_size)
|
| 79 |
+
device = grad.get_device()
|
| 80 |
+
assert device is not None
|
| 81 |
+
scatter = Scatter(
|
| 82 |
+
device=device,
|
| 83 |
+
dtype=grad.get_dtype(),
|
| 84 |
+
inner_fn=values.make_loader(),
|
| 85 |
+
ranges=expected_vals_size, # iter_ranges,
|
| 86 |
+
output_indexer=inner_fn,
|
| 87 |
+
scatter_mode="atomic_add",
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
buffer = ComputedBuffer(
|
| 91 |
+
name=grad.data.data.name, # type: ignore[attr-defined]
|
| 92 |
+
layout=MutationLayoutSHOULDREMOVE(grad),
|
| 93 |
+
data=scatter,
|
| 94 |
+
)
|
| 95 |
+
return buffer
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def get_fwd_subgraph_outputs(
|
| 99 |
+
subgraph_buffer: SubgraphResults, mask_graph_buffer: SubgraphResults
|
| 100 |
+
) -> list[Optional[ComputedBuffer]]:
|
| 101 |
+
subgraph_buffer = (
|
| 102 |
+
# pyrefly: ignore [bad-assignment]
|
| 103 |
+
subgraph_buffer if isinstance(subgraph_buffer, Sequence) else [subgraph_buffer]
|
| 104 |
+
)
|
| 105 |
+
mask_graph_buffer = (
|
| 106 |
+
# pyrefly: ignore [bad-assignment]
|
| 107 |
+
mask_graph_buffer
|
| 108 |
+
if isinstance(mask_graph_buffer, Sequence)
|
| 109 |
+
else [mask_graph_buffer]
|
| 110 |
+
)
|
| 111 |
+
# pyrefly: ignore [not-iterable]
|
| 112 |
+
return [*subgraph_buffer, *mask_graph_buffer]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def build_subgraph_module_buffer(
|
| 116 |
+
args: list[Union[TensorBox, ShapeAsConstantBuffer]],
|
| 117 |
+
graph_module: torch.fx.GraphModule,
|
| 118 |
+
) -> SubgraphResults:
|
| 119 |
+
"""This function's goal is to take in the required args and produce the subgraph buffer
|
| 120 |
+
The subgraph buffer is a ComputedBuffer that will be inlined into the triton template
|
| 121 |
+
|
| 122 |
+
Args:
|
| 123 |
+
args: The args that are passed into the subgraph. Contains both fixed and lifted inputs.
|
| 124 |
+
subgraph: The Subgraph ir for which to produce the output node
|
| 125 |
+
"""
|
| 126 |
+
# This one we gotta keep lazy
|
| 127 |
+
from ...subgraph_lowering import PointwiseSubgraphLowering
|
| 128 |
+
|
| 129 |
+
pw_subgraph = PointwiseSubgraphLowering(
|
| 130 |
+
graph_module,
|
| 131 |
+
root_graph_lowering=V.graph,
|
| 132 |
+
allowed_mutations=OrderedSet([torch.ops.flex_lib.zeros_and_scatter.default]),
|
| 133 |
+
additional_lowerings={
|
| 134 |
+
torch.ops.flex_lib.zeros_and_scatter.default: zeros_and_scatter_lowering
|
| 135 |
+
},
|
| 136 |
+
)
|
| 137 |
+
with V.set_graph_handler(pw_subgraph): # type: ignore[arg-type]
|
| 138 |
+
pw_subgraph.run(*args)
|
| 139 |
+
|
| 140 |
+
def convert_output_node_to_buffer(output_buffer) -> Optional[ComputedBuffer]:
|
| 141 |
+
if output_buffer is None:
|
| 142 |
+
return None
|
| 143 |
+
if isinstance(output_buffer, ComputedBuffer):
|
| 144 |
+
# These nodes are coming from the output of zeros_and_scatter
|
| 145 |
+
return output_buffer
|
| 146 |
+
assert isinstance(output_buffer, TensorBox), (
|
| 147 |
+
"The output node for flex attention's subgraph must be a TensorBox, but got: ",
|
| 148 |
+
type(output_buffer),
|
| 149 |
+
)
|
| 150 |
+
assert isinstance(output_buffer.data, StorageBox), (
|
| 151 |
+
"The output node for the flex attention subgraph must be a StorageBox, but got: ",
|
| 152 |
+
type(output_buffer),
|
| 153 |
+
)
|
| 154 |
+
device = output_buffer.data.get_device()
|
| 155 |
+
assert device is not None
|
| 156 |
+
subgraph_buffer = ComputedBuffer(
|
| 157 |
+
name=None,
|
| 158 |
+
layout=FlexibleLayout(
|
| 159 |
+
device=device,
|
| 160 |
+
dtype=output_buffer.data.get_dtype(),
|
| 161 |
+
size=output_buffer.data.get_size(),
|
| 162 |
+
),
|
| 163 |
+
data=output_buffer.data.data, # type: ignore[arg-type]
|
| 164 |
+
)
|
| 165 |
+
return subgraph_buffer
|
| 166 |
+
|
| 167 |
+
return tree_map(convert_output_node_to_buffer, pw_subgraph.graph_outputs)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def build_subgraph_buffer(
|
| 171 |
+
args: list[Union[TensorBox, ShapeAsConstantBuffer]], subgraph: Subgraph
|
| 172 |
+
) -> SubgraphResults:
|
| 173 |
+
return build_subgraph_module_buffer(args, subgraph.graph_module)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def maybe_realize(args: list[Optional[IRNode]]):
|
| 177 |
+
"""Accepts a list of optional IRNodes and returns a list of realized IRNodes"""
|
| 178 |
+
return tree_map(
|
| 179 |
+
lambda x: (
|
| 180 |
+
realize_inputs(x)
|
| 181 |
+
if x is not None and not isinstance(x, sympy.Symbol)
|
| 182 |
+
else x
|
| 183 |
+
),
|
| 184 |
+
args,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def freeze_irnodes(tree: Any) -> Any:
|
| 189 |
+
"""Freeze layouts for every IRNode contained in a pytree."""
|
| 190 |
+
|
| 191 |
+
if tree is None:
|
| 192 |
+
return None
|
| 193 |
+
|
| 194 |
+
def _freeze(node: IRNode) -> IRNode:
|
| 195 |
+
try:
|
| 196 |
+
node.freeze_layout()
|
| 197 |
+
except NotImplementedError:
|
| 198 |
+
pass
|
| 199 |
+
return node
|
| 200 |
+
|
| 201 |
+
return tree_map_only(IRNode, _freeze, tree)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def create_placeholder(
|
| 205 |
+
name: str,
|
| 206 |
+
dtype: torch.dtype,
|
| 207 |
+
device: torch.device,
|
| 208 |
+
size: Optional[list[int]] = None,
|
| 209 |
+
) -> Union[TensorBox, ShapeAsConstantBuffer]:
|
| 210 |
+
"""Creates a placeholder input buffers for producing subgraph_output."""
|
| 211 |
+
input_buffer = InputBuffer(
|
| 212 |
+
name=name,
|
| 213 |
+
layout=FixedLayout(
|
| 214 |
+
device,
|
| 215 |
+
dtype,
|
| 216 |
+
size if size else [],
|
| 217 |
+
FlexibleLayout.contiguous_strides(size) if size else [],
|
| 218 |
+
),
|
| 219 |
+
)
|
| 220 |
+
return TensorBox.create(input_buffer)
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def construct_strides(
|
| 224 |
+
sizes: Sequence[_IntLike],
|
| 225 |
+
fill_order: Sequence[int],
|
| 226 |
+
) -> Sequence[_IntLike]:
|
| 227 |
+
"""From a list of sizes and a fill order, construct the strides of the permuted tensor."""
|
| 228 |
+
# Initialize strides
|
| 229 |
+
assert len(sizes) == len(fill_order), (
|
| 230 |
+
"Length of sizes must match the length of the fill order"
|
| 231 |
+
)
|
| 232 |
+
strides: list[_IntLike] = [0] * len(sizes)
|
| 233 |
+
|
| 234 |
+
# Start with stride 1 for the innermost dimension
|
| 235 |
+
current_stride: _IntLike = 1
|
| 236 |
+
|
| 237 |
+
# Iterate through the fill order populating strides
|
| 238 |
+
for dim in fill_order:
|
| 239 |
+
strides[dim] = current_stride
|
| 240 |
+
current_stride *= sizes[dim]
|
| 241 |
+
|
| 242 |
+
return strides
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def infer_dense_strides(
|
| 246 |
+
size: Sequence[_IntLike],
|
| 247 |
+
orig_strides: Sequence[_IntLike],
|
| 248 |
+
):
|
| 249 |
+
"""This is a mirror of the same function in aten/src/ATen/ExpandUtils.cpp
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
size: The size of the output tensor
|
| 253 |
+
orig_strides: The strides of the input tensor
|
| 254 |
+
Returns:
|
| 255 |
+
List[int]: Dense non-overlapping strides that preserve the input tensor's layout permutation.
|
| 256 |
+
The returned strides follow the same stride propagation rules as TensorIterator. This matches
|
| 257 |
+
The behavior of empty_like()
|
| 258 |
+
"""
|
| 259 |
+
fill_order = get_fill_order(orig_strides, V.graph.sizevars.shape_env)
|
| 260 |
+
return construct_strides(size, fill_order)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def create_indices_fake(x) -> torch.Tensor:
|
| 264 |
+
"""Create a fake indices that is used for autotuning."""
|
| 265 |
+
size = [V.graph.sizevars.size_hint(i) for i in x.get_size()]
|
| 266 |
+
indices = torch.arange(0, size[-1], dtype=x.get_dtype(), device=x.get_device())
|
| 267 |
+
indices = indices.expand(size).contiguous()
|
| 268 |
+
return indices
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def create_num_blocks_fake_generator(sparse_indices):
|
| 272 |
+
"""Create a fake num_blocks that is used for autotuning.
|
| 273 |
+
|
| 274 |
+
The idea here is that we need to create a real tensor with real data
|
| 275 |
+
that's representative for benchmarking.
|
| 276 |
+
For example, returning all zeros for the `kv_num_blocks` input would mean
|
| 277 |
+
that we are computing 0 blocks for each row, which would provide bogus
|
| 278 |
+
autotuning results.
|
| 279 |
+
|
| 280 |
+
In this case, we choose to use min(16, max_block) blocks, because I
|
| 281 |
+
(Horace) think it'll probably result in pretty representative performance.
|
| 282 |
+
If it's too short then prefetching won't help. If it's too long then
|
| 283 |
+
autotuning will take longer for no good reason.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def create_num_blocks_fake(x) -> torch.Tensor:
|
| 287 |
+
num_blocks_for_autotuning = V.graph.sizevars.size_hint(sparse_indices.shape[-1])
|
| 288 |
+
size = [V.graph.sizevars.size_hint(i) for i in x.get_size()]
|
| 289 |
+
return torch.full(
|
| 290 |
+
size,
|
| 291 |
+
num_blocks_for_autotuning,
|
| 292 |
+
dtype=x.get_dtype(),
|
| 293 |
+
device=x.get_device(),
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
return create_num_blocks_fake
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def contiguous_last_dim(x):
|
| 300 |
+
"""Ensure that realized IR node has a contiguous stride in the last dimension."""
|
| 301 |
+
strides = x.maybe_get_stride()
|
| 302 |
+
if strides and strides[-1] != 1:
|
| 303 |
+
contiguous_stride_order = list(reversed(range(len(x.get_size()))))
|
| 304 |
+
return ExternKernel.require_stride_order(x, contiguous_stride_order)
|
| 305 |
+
return x
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def set_head_dim_values(
|
| 309 |
+
kernel_options: dict[str, Any], qk_head_dim, v_head_dim, graph_sizevars
|
| 310 |
+
):
|
| 311 |
+
"""
|
| 312 |
+
Mutates kernel options, adding head dimension calculations.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
kernel_options: Dictionary to populate with options
|
| 316 |
+
qk_head_dim: Query/Key head dimension
|
| 317 |
+
v_head_dim: Value head dimension
|
| 318 |
+
graph_sizevars: Graph size variables object with guard_int method
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
# QK dimensions
|
| 322 |
+
qk_head_dim_static = graph_sizevars.guard_int(qk_head_dim)
|
| 323 |
+
kernel_options.setdefault("QK_HEAD_DIM", qk_head_dim_static)
|
| 324 |
+
kernel_options.setdefault(
|
| 325 |
+
"QK_HEAD_DIM_ROUNDED", next_power_of_two(qk_head_dim_static)
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
# V dimensions
|
| 329 |
+
v_head_dim_static = graph_sizevars.guard_int(v_head_dim)
|
| 330 |
+
kernel_options.setdefault("V_HEAD_DIM", v_head_dim_static)
|
| 331 |
+
kernel_options.setdefault(
|
| 332 |
+
"V_HEAD_DIM_ROUNDED", next_power_of_two(v_head_dim_static)
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
# Safety flag
|
| 336 |
+
kernel_options.setdefault(
|
| 337 |
+
"SAFE_HEAD_DIM",
|
| 338 |
+
is_power_of_2(qk_head_dim_static) and is_power_of_2(v_head_dim_static),
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def is_power_of_2(n):
|
| 343 |
+
return n != 0 and ((n & (n - 1)) == 0)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def next_power_of_two(n):
|
| 347 |
+
if n <= 0:
|
| 348 |
+
return 1
|
| 349 |
+
return 2 ** math.ceil(math.log2(n))
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
_FLEX_TEMPLATE_DIR = Path(__file__).parent / "templates"
|
| 353 |
+
load_flex_template = partial(load_template, template_dir=_FLEX_TEMPLATE_DIR)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# Template strings have been moved to templates/common.py.jinja
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/flex_attention.py
ADDED
|
@@ -0,0 +1,977 @@
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Triton Implementation of the flex_attention Kernel"""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import logging
|
| 7 |
+
import math
|
| 8 |
+
from collections.abc import Sequence
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
from typing import Any, cast, Optional, TYPE_CHECKING, Union
|
| 11 |
+
|
| 12 |
+
import sympy
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from torch._inductor.virtualized import V
|
| 16 |
+
from torch.nn.attention.flex_attention import _Backend
|
| 17 |
+
|
| 18 |
+
from ...ir import ComputedBuffer, ExternKernel, FixedLayout, TensorBox
|
| 19 |
+
from ...lowering import empty, empty_strided, lowerings, register_lowering
|
| 20 |
+
from ...select_algorithm import (
|
| 21 |
+
autotune_select_algorithm,
|
| 22 |
+
SymbolicGridFn,
|
| 23 |
+
TritonTemplate,
|
| 24 |
+
)
|
| 25 |
+
from .common import (
|
| 26 |
+
build_subgraph_buffer,
|
| 27 |
+
create_indices_fake,
|
| 28 |
+
create_num_blocks_fake_generator,
|
| 29 |
+
create_placeholder,
|
| 30 |
+
freeze_irnodes,
|
| 31 |
+
get_fwd_subgraph_outputs,
|
| 32 |
+
infer_dense_strides,
|
| 33 |
+
load_flex_template,
|
| 34 |
+
maybe_realize,
|
| 35 |
+
set_head_dim_values,
|
| 36 |
+
SubgraphResults,
|
| 37 |
+
)
|
| 38 |
+
from .flex_cpu import lower_cpu
|
| 39 |
+
from .flex_decoding import _use_flex_decoding, create_flex_decoding_kernel
|
| 40 |
+
from .flex_flash_attention import (
|
| 41 |
+
_use_flex_flash_attention,
|
| 42 |
+
_use_flex_flash_attention_backward,
|
| 43 |
+
create_flex_flash_attention_backward_kernel,
|
| 44 |
+
create_flex_flash_attention_kernel,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if TYPE_CHECKING:
|
| 49 |
+
from ...template_heuristics.triton import FlexBwDConfig, FlexConfig
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
log = logging.getLogger(__name__)
|
| 53 |
+
aten = torch.ops.aten
|
| 54 |
+
Expr = sympy.Expr
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _sanitize_kernel_options_for_triton(
|
| 58 |
+
kernel_options: dict[str, Any],
|
| 59 |
+
) -> tuple[dict[str, Any], _Backend]:
|
| 60 |
+
"""We always strip quotes around str values, we only need this in lowering, so we pop it here
|
| 61 |
+
to avoid passing to triton constexpr dict
|
| 62 |
+
"""
|
| 63 |
+
sanitized = dict(kernel_options)
|
| 64 |
+
backend = cast(_Backend, sanitized.pop("BACKEND", "AUTO"))
|
| 65 |
+
return sanitized, backend
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@SymbolicGridFn
|
| 69 |
+
def flex_attention_grid(batch_size, q_heads, num_queries, d_model, meta, *, cdiv):
|
| 70 |
+
"""How is this kernel parallelized?
|
| 71 |
+
We create a grid of (ceil_div(n_queries, query_block_size), batch_size, num_heads)
|
| 72 |
+
Each block is responsible for iterating over blocks of keys and values calculating
|
| 73 |
+
the final attention output.
|
| 74 |
+
"""
|
| 75 |
+
return (cdiv(num_queries, meta["BLOCK_M"]), batch_size, q_heads)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def get_float32_precision():
|
| 79 |
+
if (
|
| 80 |
+
(
|
| 81 |
+
torch.backends.cuda.matmul.fp32_precision == "ieee"
|
| 82 |
+
if torch.backends.cuda.matmul.fp32_precision != "none"
|
| 83 |
+
else torch.get_float32_matmul_precision() == "highest"
|
| 84 |
+
)
|
| 85 |
+
or torch.version.hip
|
| 86 |
+
or torch.mtia.is_available()
|
| 87 |
+
):
|
| 88 |
+
return "'ieee'"
|
| 89 |
+
else:
|
| 90 |
+
return "'tf32'"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
flex_attention_template = TritonTemplate(
|
| 94 |
+
name="flex_attention",
|
| 95 |
+
grid=flex_attention_grid,
|
| 96 |
+
source=load_flex_template("flex_attention")
|
| 97 |
+
+ load_flex_template("utilities")
|
| 98 |
+
+ load_flex_template("common"),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@register_lowering(torch.ops.higher_order.flex_attention, type_promotion_kind=None)
|
| 103 |
+
def flex_attention(
|
| 104 |
+
query,
|
| 105 |
+
key,
|
| 106 |
+
value,
|
| 107 |
+
subgraph,
|
| 108 |
+
block_mask,
|
| 109 |
+
scale,
|
| 110 |
+
kernel_options: dict[str, Any],
|
| 111 |
+
score_mod_other_buffers,
|
| 112 |
+
mask_mod_other_buffers,
|
| 113 |
+
):
|
| 114 |
+
"""The main lowering for the flex_attention hop
|
| 115 |
+
This can currently lower to one of 3 templates:
|
| 116 |
+
1. Base Triton Template
|
| 117 |
+
2. Flex Decode Triton Template
|
| 118 |
+
3. Cpu specific CPP template
|
| 119 |
+
"""
|
| 120 |
+
if query.get_device().type == "cpu":
|
| 121 |
+
return lower_cpu(
|
| 122 |
+
query,
|
| 123 |
+
key,
|
| 124 |
+
value,
|
| 125 |
+
subgraph,
|
| 126 |
+
block_mask,
|
| 127 |
+
scale,
|
| 128 |
+
kernel_options,
|
| 129 |
+
score_mod_other_buffers,
|
| 130 |
+
mask_mod_other_buffers,
|
| 131 |
+
)
|
| 132 |
+
# below is cuda path if device is not cpu
|
| 133 |
+
# tl.dot does not support embedding size less than 16
|
| 134 |
+
small_dqk = V.graph.sizevars.evaluate_expr(sympy.Lt(query.get_size()[-1], 16))
|
| 135 |
+
small_dv = V.graph.sizevars.evaluate_expr(sympy.Lt(value.get_size()[-1], 16))
|
| 136 |
+
if small_dqk or small_dv:
|
| 137 |
+
raise NotImplementedError(
|
| 138 |
+
f"NYI: embedding dimension of the query, key, and value must be "
|
| 139 |
+
f"at least 16 but got E={query.get_size()[-1]} and Ev={value.get_size()[-1]}"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
(
|
| 143 |
+
_, # q_length
|
| 144 |
+
_, # kv_length
|
| 145 |
+
kv_num_blocks,
|
| 146 |
+
kv_indices,
|
| 147 |
+
full_kv_num_blocks,
|
| 148 |
+
full_kv_indices,
|
| 149 |
+
q_num_blocks,
|
| 150 |
+
q_indices,
|
| 151 |
+
full_q_num_blocks,
|
| 152 |
+
full_q_indices,
|
| 153 |
+
SPARSE_Q_BLOCK_SIZE,
|
| 154 |
+
SPARSE_KV_BLOCK_SIZE,
|
| 155 |
+
mask_graph,
|
| 156 |
+
) = block_mask
|
| 157 |
+
|
| 158 |
+
placeholder_inps = [
|
| 159 |
+
create_placeholder(name, dtype, query.get_device())
|
| 160 |
+
for name, dtype in [
|
| 161 |
+
("score", query.get_dtype()),
|
| 162 |
+
("b", torch.int32),
|
| 163 |
+
("h", torch.int32),
|
| 164 |
+
("m", torch.int32),
|
| 165 |
+
("n", torch.int32),
|
| 166 |
+
]
|
| 167 |
+
]
|
| 168 |
+
subgraph_buffer = build_subgraph_buffer(
|
| 169 |
+
placeholder_inps + list(score_mod_other_buffers), subgraph
|
| 170 |
+
)
|
| 171 |
+
freeze_irnodes(subgraph_buffer)
|
| 172 |
+
|
| 173 |
+
mask_graph_placeholder_inps = [
|
| 174 |
+
create_placeholder(name, dtype, query.get_device())
|
| 175 |
+
for name, dtype in [
|
| 176 |
+
("b", torch.int32),
|
| 177 |
+
("h", torch.int32),
|
| 178 |
+
("m", torch.int32),
|
| 179 |
+
("n", torch.int32),
|
| 180 |
+
]
|
| 181 |
+
]
|
| 182 |
+
mask_graph_buffer = build_subgraph_buffer(
|
| 183 |
+
mask_graph_placeholder_inps + list(mask_mod_other_buffers), mask_graph
|
| 184 |
+
)
|
| 185 |
+
freeze_irnodes(mask_graph_buffer)
|
| 186 |
+
|
| 187 |
+
kernel_options, backend = _sanitize_kernel_options_for_triton(kernel_options)
|
| 188 |
+
# Mark symbols in custom kernel options as static shapes and add guards.
|
| 189 |
+
kernel_options = {
|
| 190 |
+
k: V.graph.sizevars.guard_int(v) if isinstance(v, sympy.Symbol) else v
|
| 191 |
+
for k, v in kernel_options.items()
|
| 192 |
+
}
|
| 193 |
+
kernel_options.setdefault("FLOAT32_PRECISION", get_float32_precision())
|
| 194 |
+
enable_gqa = V.graph.sizevars.evaluate_expr(
|
| 195 |
+
sympy.Ne(query.get_size()[1], key.get_size()[1]),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
can_use_decode = _use_flex_decoding(
|
| 199 |
+
query, kv_indices, value, kernel_options, enable_gqa
|
| 200 |
+
)
|
| 201 |
+
use_decode = (backend == "TRITON_DECODE") or (backend == "AUTO" and can_use_decode)
|
| 202 |
+
|
| 203 |
+
if backend == "TRITON_DECODE" and not can_use_decode:
|
| 204 |
+
raise RuntimeError(
|
| 205 |
+
"BACKEND='TRITON_DECODE' was specified but flex_decoding cannot be used for this input. "
|
| 206 |
+
"flex_decoding is only available for short sequence lengths with specific configurations."
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
if use_decode:
|
| 210 |
+
return create_flex_decoding_kernel(
|
| 211 |
+
query,
|
| 212 |
+
key,
|
| 213 |
+
value,
|
| 214 |
+
block_mask,
|
| 215 |
+
scale,
|
| 216 |
+
kernel_options,
|
| 217 |
+
subgraph_buffer,
|
| 218 |
+
mask_graph_buffer,
|
| 219 |
+
score_mod_other_buffers,
|
| 220 |
+
mask_mod_other_buffers,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
(
|
| 224 |
+
query,
|
| 225 |
+
key,
|
| 226 |
+
value,
|
| 227 |
+
kv_num_blocks,
|
| 228 |
+
kv_indices,
|
| 229 |
+
full_kv_num_blocks,
|
| 230 |
+
full_kv_indices,
|
| 231 |
+
q_num_blocks,
|
| 232 |
+
q_indices,
|
| 233 |
+
full_q_num_blocks,
|
| 234 |
+
full_q_indices,
|
| 235 |
+
) = maybe_realize(
|
| 236 |
+
[
|
| 237 |
+
query,
|
| 238 |
+
key,
|
| 239 |
+
value,
|
| 240 |
+
kv_num_blocks,
|
| 241 |
+
kv_indices,
|
| 242 |
+
full_kv_num_blocks,
|
| 243 |
+
full_kv_indices,
|
| 244 |
+
q_num_blocks,
|
| 245 |
+
q_indices,
|
| 246 |
+
full_q_num_blocks,
|
| 247 |
+
full_q_indices,
|
| 248 |
+
]
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
if _use_flex_flash_attention(
|
| 252 |
+
subgraph,
|
| 253 |
+
mask_graph,
|
| 254 |
+
kernel_options,
|
| 255 |
+
num_score_mod_placeholders=len(placeholder_inps),
|
| 256 |
+
backend=backend,
|
| 257 |
+
):
|
| 258 |
+
return create_flex_flash_attention_kernel(
|
| 259 |
+
query,
|
| 260 |
+
key,
|
| 261 |
+
value,
|
| 262 |
+
block_mask,
|
| 263 |
+
scale,
|
| 264 |
+
kernel_options,
|
| 265 |
+
subgraph_buffer,
|
| 266 |
+
mask_graph_buffer,
|
| 267 |
+
score_mod_other_buffers,
|
| 268 |
+
mask_mod_other_buffers,
|
| 269 |
+
kv_num_blocks,
|
| 270 |
+
kv_indices,
|
| 271 |
+
full_kv_num_blocks,
|
| 272 |
+
full_kv_indices,
|
| 273 |
+
mask_graph=mask_graph,
|
| 274 |
+
subgraph=subgraph,
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
score_mod_other_buffers = maybe_realize(score_mod_other_buffers)
|
| 278 |
+
mask_mod_other_buffers = maybe_realize(mask_mod_other_buffers)
|
| 279 |
+
|
| 280 |
+
freeze_irnodes(score_mod_other_buffers)
|
| 281 |
+
freeze_irnodes(mask_mod_other_buffers)
|
| 282 |
+
|
| 283 |
+
Bq, Hq, seq_len_q, qk_head_dim = query.get_size()
|
| 284 |
+
Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size()
|
| 285 |
+
assert V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv) | sympy.Eq(Bkv, 1)), (
|
| 286 |
+
f"Bq and Bkv must broadcastable. Got Bq={Bq} and Bkv={Bkv}"
|
| 287 |
+
)
|
| 288 |
+
assert V.graph.sizevars.evaluate_expr(sympy.Gt(seq_len_q, 0)), (
|
| 289 |
+
"Query length must be greater than 0"
|
| 290 |
+
)
|
| 291 |
+
assert V.graph.sizevars.evaluate_expr(sympy.Gt(seq_len_kv, 0)), (
|
| 292 |
+
"Key length must be greater than 0"
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
B = Bq
|
| 296 |
+
|
| 297 |
+
if seq_len_q % 128 != 0 or seq_len_kv % 128 != 0:
|
| 298 |
+
kernel_options.setdefault("IS_DIVISIBLE", False)
|
| 299 |
+
else:
|
| 300 |
+
kernel_options.setdefault("IS_DIVISIBLE", True)
|
| 301 |
+
|
| 302 |
+
# NB it is okay that the v_head_dim is different
|
| 303 |
+
# We are using these to match fill order of the output.
|
| 304 |
+
q_strides = query.get_stride()
|
| 305 |
+
# Construct output layout with strides matching the query.
|
| 306 |
+
out_size = [B, Hq, seq_len_q, v_head_dim]
|
| 307 |
+
out_strides = infer_dense_strides(out_size, q_strides)
|
| 308 |
+
|
| 309 |
+
layout = FixedLayout(
|
| 310 |
+
query.get_device(),
|
| 311 |
+
query.get_dtype(),
|
| 312 |
+
[B, Hq, seq_len_q, v_head_dim],
|
| 313 |
+
stride=[sympy.sympify(s) for s in out_strides],
|
| 314 |
+
)
|
| 315 |
+
# see NOTE:[TritonTemplates with multiple outputs]
|
| 316 |
+
logsumexp_shape = [B, Hq, seq_len_q]
|
| 317 |
+
logsumexp = empty_strided(
|
| 318 |
+
logsumexp_shape,
|
| 319 |
+
None,
|
| 320 |
+
dtype=torch.float32, # The logsumexp is always stored in fp32 regardless of the input dtype
|
| 321 |
+
device=query.get_device(),
|
| 322 |
+
)
|
| 323 |
+
max_scores = empty_strided(
|
| 324 |
+
logsumexp_shape, # Same shape as logsumexp
|
| 325 |
+
None,
|
| 326 |
+
dtype=torch.float32, # The max scores are always stored in fp32 regardless of the input dtype
|
| 327 |
+
device=query.get_device(),
|
| 328 |
+
)
|
| 329 |
+
kernel_options.setdefault("SM_SCALE", scale)
|
| 330 |
+
|
| 331 |
+
# Determine GQA broadcast factor.
|
| 332 |
+
gqa_shared_heads = Hq // Hkv
|
| 333 |
+
kernel_options.setdefault("GQA_SHARED_HEADS", gqa_shared_heads)
|
| 334 |
+
|
| 335 |
+
# Inside of Triton kernel, only apply partial masking if partial blocks are computed.
|
| 336 |
+
# full_kv_num_blocks is None if partial blocks are not computed
|
| 337 |
+
has_full_blocks = full_kv_num_blocks is not None
|
| 338 |
+
kernel_options.setdefault("HAS_FULL_BLOCKS", has_full_blocks)
|
| 339 |
+
if not has_full_blocks:
|
| 340 |
+
full_kv_num_blocks, full_kv_indices = (
|
| 341 |
+
empty(0, device=query.get_device()) for _ in range(2)
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
set_head_dim_values(kernel_options, qk_head_dim, v_head_dim, V.graph.sizevars)
|
| 345 |
+
|
| 346 |
+
choices: list[Any] = []
|
| 347 |
+
|
| 348 |
+
dtype = query.get_dtype()
|
| 349 |
+
head_dim = V.graph.sizevars.guard_int(query.get_size()[-1])
|
| 350 |
+
configs: list[FlexConfig] = V.choices.get_flex_attention_fwd_configs(
|
| 351 |
+
head_dim, dtype, query.get_device().type
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
# Mark SPARSE_KV_BLOCK_SIZE & SPARSE_Q_BLOCK_SIZE as static shapes and add guards.
|
| 355 |
+
SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE)
|
| 356 |
+
SPARSE_Q_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_Q_BLOCK_SIZE)
|
| 357 |
+
|
| 358 |
+
# Note, we don't need to pass in the captured buffers explicitly
|
| 359 |
+
# because they're implicitly added by the score_mod function
|
| 360 |
+
# We do need to explicitly pass it in for autotuning though.
|
| 361 |
+
original_kernel_options = kernel_options.copy()
|
| 362 |
+
# Default config for warp specialization
|
| 363 |
+
num_consumer_groups, num_buffers_warp_spec = 0, 0
|
| 364 |
+
|
| 365 |
+
for conf in configs:
|
| 366 |
+
cur_kernel_options = original_kernel_options.copy()
|
| 367 |
+
# Performance tuning
|
| 368 |
+
# Triton parameters
|
| 369 |
+
# Remove prefix for forward kernels options and delete backward kernel options.
|
| 370 |
+
for k in list(cur_kernel_options.keys()):
|
| 371 |
+
if k.startswith("fwd_"):
|
| 372 |
+
v = cur_kernel_options.pop(k)
|
| 373 |
+
cur_kernel_options[k[4:]] = v
|
| 374 |
+
if k.startswith("bwd_"):
|
| 375 |
+
cur_kernel_options.pop(k)
|
| 376 |
+
cur_kernel_options.setdefault("num_stages", conf.num_stages)
|
| 377 |
+
cur_kernel_options.setdefault("num_warps", conf.num_warps)
|
| 378 |
+
if cur_kernel_options.get("num_consumer_groups", False):
|
| 379 |
+
cur_kernel_options.setdefault("num_consumer_groups", num_consumer_groups)
|
| 380 |
+
cur_kernel_options.setdefault(
|
| 381 |
+
"num_buffers_warp_spec", num_buffers_warp_spec
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
# USE TMA = false by default
|
| 385 |
+
cur_kernel_options.setdefault("USE_TMA", False)
|
| 386 |
+
|
| 387 |
+
cur_kernel_options.setdefault("BLOCK_M", conf.block_m)
|
| 388 |
+
cur_kernel_options.setdefault("BLOCK_N", conf.block_n)
|
| 389 |
+
# Blocksparse options
|
| 390 |
+
cur_kernel_options.setdefault("SPARSE_Q_BLOCK_SIZE", SPARSE_Q_BLOCK_SIZE)
|
| 391 |
+
cur_kernel_options.setdefault("SPARSE_KV_BLOCK_SIZE", SPARSE_KV_BLOCK_SIZE)
|
| 392 |
+
|
| 393 |
+
if (
|
| 394 |
+
cur_kernel_options["SPARSE_KV_BLOCK_SIZE"] % cur_kernel_options["BLOCK_N"]
|
| 395 |
+
!= 0
|
| 396 |
+
or cur_kernel_options["SPARSE_Q_BLOCK_SIZE"] % cur_kernel_options["BLOCK_M"]
|
| 397 |
+
!= 0
|
| 398 |
+
):
|
| 399 |
+
if len(configs) == 1:
|
| 400 |
+
raise ValueError(
|
| 401 |
+
f"Q and KV block size must be divisible by BLOCK_M and BLOCK_N. We "
|
| 402 |
+
f"got Q_BLOCK_SIZE={cur_kernel_options['SPARSE_Q_BLOCK_SIZE']} and "
|
| 403 |
+
f"KV_BLOCK_SIZE={cur_kernel_options['SPARSE_KV_BLOCK_SIZE']}."
|
| 404 |
+
)
|
| 405 |
+
continue
|
| 406 |
+
|
| 407 |
+
# ROCm specific kernargs
|
| 408 |
+
for attrib in ["kpack", "matrix_instr_nonkdim", "waves_per_eu"]:
|
| 409 |
+
if hasattr(conf, attrib):
|
| 410 |
+
cur_kernel_options[attrib] = getattr(conf, attrib)
|
| 411 |
+
|
| 412 |
+
error = flex_attention_template.maybe_append_choice(
|
| 413 |
+
choices=choices,
|
| 414 |
+
input_nodes=[
|
| 415 |
+
query,
|
| 416 |
+
key,
|
| 417 |
+
value,
|
| 418 |
+
logsumexp,
|
| 419 |
+
max_scores,
|
| 420 |
+
kv_num_blocks,
|
| 421 |
+
kv_indices,
|
| 422 |
+
full_kv_num_blocks,
|
| 423 |
+
full_kv_indices,
|
| 424 |
+
],
|
| 425 |
+
layout=layout,
|
| 426 |
+
subgraphs=[
|
| 427 |
+
subgraph_buffer,
|
| 428 |
+
mask_graph_buffer,
|
| 429 |
+
],
|
| 430 |
+
mutated_inputs=[
|
| 431 |
+
logsumexp,
|
| 432 |
+
max_scores,
|
| 433 |
+
],
|
| 434 |
+
call_sizes=query.get_size(),
|
| 435 |
+
**cur_kernel_options,
|
| 436 |
+
)
|
| 437 |
+
if error is not None and len(configs) == 1:
|
| 438 |
+
raise error
|
| 439 |
+
inputs_for_autotuning = (
|
| 440 |
+
[
|
| 441 |
+
query,
|
| 442 |
+
key,
|
| 443 |
+
value,
|
| 444 |
+
logsumexp,
|
| 445 |
+
max_scores,
|
| 446 |
+
kv_num_blocks,
|
| 447 |
+
kv_indices,
|
| 448 |
+
full_kv_num_blocks,
|
| 449 |
+
full_kv_indices,
|
| 450 |
+
]
|
| 451 |
+
+ list(score_mod_other_buffers)
|
| 452 |
+
+ list(mask_mod_other_buffers)
|
| 453 |
+
)
|
| 454 |
+
input_gen_fns = {
|
| 455 |
+
5: create_num_blocks_fake_generator(kv_indices),
|
| 456 |
+
6: create_indices_fake,
|
| 457 |
+
7: create_num_blocks_fake_generator(full_kv_indices),
|
| 458 |
+
8: create_indices_fake,
|
| 459 |
+
}
|
| 460 |
+
|
| 461 |
+
out = autotune_select_algorithm(
|
| 462 |
+
"flex_attention",
|
| 463 |
+
choices,
|
| 464 |
+
# Need to filter out symbols since there is an invariant
|
| 465 |
+
# that all input_nodes are of type IRNode
|
| 466 |
+
[x for x in inputs_for_autotuning if isinstance(x, torch._inductor.ir.IRNode)],
|
| 467 |
+
layout,
|
| 468 |
+
input_gen_fns=input_gen_fns,
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
# need subgraph inputs and outputs to analyze all symints used in flex attention
|
| 472 |
+
out.data.data.subgraph_inps = list(score_mod_other_buffers) + list(
|
| 473 |
+
mask_mod_other_buffers
|
| 474 |
+
)
|
| 475 |
+
out.data.data.subgraph_outs = get_fwd_subgraph_outputs(
|
| 476 |
+
subgraph_buffer, mask_graph_buffer
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
return (out, logsumexp, max_scores)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
# ---------------------------- Backward HOP Implementation ----------------------------
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
@SymbolicGridFn
|
| 486 |
+
def flex_attention_backward_grid(
|
| 487 |
+
batch_size, q_heads, num_queries, d_model, kv_heads, num_key_value, meta, *, cdiv
|
| 488 |
+
):
|
| 489 |
+
"""How is this kernel parallelized?
|
| 490 |
+
We create a grid of (ceil_div(n_queries, query_block_size) * heads_ratio + ceil_div(n_kv, kv_block_size), batch_size, kv_heads)
|
| 491 |
+
Currently this is only parallelizing over batch* kv_heads, but we can, and want to
|
| 492 |
+
parallelize over ceil_div(q_heads//kv_heads * num_key_value, key_value_block_size).
|
| 493 |
+
To do this will either require atomic updates to some grad values or to have a two pass kernel design.
|
| 494 |
+
"""
|
| 495 |
+
return (
|
| 496 |
+
cdiv(num_queries, meta["BLOCK_M2"]) * (q_heads // kv_heads)
|
| 497 |
+
+ cdiv(num_key_value, meta["BLOCK_N1"]),
|
| 498 |
+
batch_size,
|
| 499 |
+
kv_heads,
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
flex_attention_backward_template = TritonTemplate(
|
| 504 |
+
name="flex_attention_backward",
|
| 505 |
+
grid=flex_attention_backward_grid,
|
| 506 |
+
source=load_flex_template("flex_backwards") + load_flex_template("utilities"),
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def validate_joint_graph(joint_graph: torch.fx.Graph):
|
| 511 |
+
"""We do some pre lowering graph checks in order to raise nicer error messages"""
|
| 512 |
+
for node in joint_graph.nodes:
|
| 513 |
+
if (
|
| 514 |
+
node.op == "call_function"
|
| 515 |
+
and node.target is torch.ops.flex_lib.zeros_and_scatter.default
|
| 516 |
+
):
|
| 517 |
+
for user in node.users:
|
| 518 |
+
if user.op != "output":
|
| 519 |
+
raise NotImplementedError(
|
| 520 |
+
"Using multiple indexing operations on the same tensor that requires gradients "
|
| 521 |
+
"in a score_mod function is not currently supported. "
|
| 522 |
+
"This typically happens when indexing the same tensor multiple times, like:\n\n"
|
| 523 |
+
" def score_mod(score, b, h, q_idx, kv_idx):\n"
|
| 524 |
+
" return score + bias[q_idx] + bias[kv_idx] # bias used twice!\n\n"
|
| 525 |
+
"A valid workaround is to clone() the tensors that will be indexed multiple times. For example:\n\n"
|
| 526 |
+
" bias1 = bias.clone()\n"
|
| 527 |
+
" def score_mod(score, b, h, q_idx, kv_idx):\n"
|
| 528 |
+
" return score + bias[q_idx] + bias1[kv_idx]\n\n"
|
| 529 |
+
"Note that this solution will use additional memory."
|
| 530 |
+
)
|
| 531 |
+
return
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
@dataclass(frozen=True)
|
| 535 |
+
class JointOutputResult:
|
| 536 |
+
"""Results from processing joint outputs."""
|
| 537 |
+
|
| 538 |
+
grad_input: ComputedBuffer
|
| 539 |
+
captured_grads_compute: list[ComputedBuffer]
|
| 540 |
+
captured_grads: list[Optional[TensorBox]]
|
| 541 |
+
mutated_grads: list[TensorBox]
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def process_joint_outputs(
|
| 545 |
+
all_joint_outputs: SubgraphResults, num_placeholders: int
|
| 546 |
+
) -> JointOutputResult:
|
| 547 |
+
"""Process joint outputs and extract various buffers needed for lowering
|
| 548 |
+
|
| 549 |
+
Args:
|
| 550 |
+
all_joint_outputs: List of all the outputs from build_subgraphs
|
| 551 |
+
num_placeholders: The number of placeholder inputs, used to skip over unused backward compute buffers
|
| 552 |
+
|
| 553 |
+
Returns:
|
| 554 |
+
JointOutputResult containing processed buffers and gradients
|
| 555 |
+
"""
|
| 556 |
+
assert isinstance(all_joint_outputs, list)
|
| 557 |
+
assert all_joint_outputs[0] is not None, (
|
| 558 |
+
"joint_subgraph_buffer is None - this is a bug!"
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
joint_buffer = all_joint_outputs[0]
|
| 562 |
+
other_grads = all_joint_outputs[num_placeholders - 1 :]
|
| 563 |
+
|
| 564 |
+
# outer_grads has the structure: Len(other_buffer_grads) if buffer doesn't require grad than it will be None
|
| 565 |
+
# We only grab the buffers that require grad for inlining into kernel
|
| 566 |
+
grads_compute = [buf for buf in other_grads if buf is not None]
|
| 567 |
+
|
| 568 |
+
def get_out(buf):
|
| 569 |
+
if buf is None:
|
| 570 |
+
return None
|
| 571 |
+
assert isinstance(buf, ComputedBuffer)
|
| 572 |
+
assert buf.name is not None
|
| 573 |
+
return TensorBox.create(V.graph.get_buffer(buf.name))
|
| 574 |
+
|
| 575 |
+
grads_out = [get_out(x) for x in other_grads]
|
| 576 |
+
mutated_grads = [buf for buf in grads_out if buf is not None]
|
| 577 |
+
|
| 578 |
+
return JointOutputResult(
|
| 579 |
+
grad_input=joint_buffer,
|
| 580 |
+
captured_grads_compute=grads_compute,
|
| 581 |
+
captured_grads=grads_out,
|
| 582 |
+
mutated_grads=mutated_grads,
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
# TODO: We probably also need a layout constraint?
|
| 587 |
+
@register_lowering(
|
| 588 |
+
torch.ops.higher_order.flex_attention_backward, type_promotion_kind=None
|
| 589 |
+
)
|
| 590 |
+
def flex_attention_backward(*args, **kwargs):
|
| 591 |
+
"""Lowering for the flex_attention_backward op in triton"""
|
| 592 |
+
(
|
| 593 |
+
query,
|
| 594 |
+
key,
|
| 595 |
+
value,
|
| 596 |
+
out,
|
| 597 |
+
logsumexp,
|
| 598 |
+
grad_out,
|
| 599 |
+
grad_logsumexp,
|
| 600 |
+
fw_graph,
|
| 601 |
+
joint_graph,
|
| 602 |
+
block_mask,
|
| 603 |
+
scale,
|
| 604 |
+
kernel_options,
|
| 605 |
+
score_mod_other_buffers,
|
| 606 |
+
mask_mod_other_buffers,
|
| 607 |
+
) = args
|
| 608 |
+
(
|
| 609 |
+
_, # q_length
|
| 610 |
+
_, # kv_length
|
| 611 |
+
kv_num_blocks,
|
| 612 |
+
kv_indices,
|
| 613 |
+
full_kv_num_blocks,
|
| 614 |
+
full_kv_indices,
|
| 615 |
+
q_num_blocks,
|
| 616 |
+
q_indices,
|
| 617 |
+
full_q_num_blocks,
|
| 618 |
+
full_q_indices,
|
| 619 |
+
SPARSE_Q_BLOCK_SIZE,
|
| 620 |
+
SPARSE_KV_BLOCK_SIZE,
|
| 621 |
+
mask_graph,
|
| 622 |
+
) = block_mask
|
| 623 |
+
|
| 624 |
+
(
|
| 625 |
+
query,
|
| 626 |
+
key,
|
| 627 |
+
value,
|
| 628 |
+
logsumexp,
|
| 629 |
+
grad_out,
|
| 630 |
+
kv_num_blocks,
|
| 631 |
+
kv_indices,
|
| 632 |
+
full_kv_num_blocks,
|
| 633 |
+
full_kv_indices,
|
| 634 |
+
q_num_blocks,
|
| 635 |
+
q_indices,
|
| 636 |
+
full_q_num_blocks,
|
| 637 |
+
full_q_indices,
|
| 638 |
+
) = maybe_realize(
|
| 639 |
+
[
|
| 640 |
+
query,
|
| 641 |
+
key,
|
| 642 |
+
value,
|
| 643 |
+
logsumexp,
|
| 644 |
+
grad_out,
|
| 645 |
+
kv_num_blocks,
|
| 646 |
+
kv_indices,
|
| 647 |
+
full_kv_num_blocks,
|
| 648 |
+
full_kv_indices,
|
| 649 |
+
q_num_blocks,
|
| 650 |
+
q_indices,
|
| 651 |
+
full_q_num_blocks,
|
| 652 |
+
full_q_indices,
|
| 653 |
+
]
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
device = query.get_device()
|
| 657 |
+
dtype = query.get_dtype()
|
| 658 |
+
Bq, Hq, seq_len_q, qk_head_dim = query.get_size()
|
| 659 |
+
Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size()
|
| 660 |
+
|
| 661 |
+
assert V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv) | sympy.Eq(Bkv, 1)), (
|
| 662 |
+
f"Bq and Bkv must broadcastable. Got Bq={Bq} and Bkv={Bkv}"
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
kernel_options, backend = _sanitize_kernel_options_for_triton(kernel_options)
|
| 666 |
+
# Mark symbols in custom kernel options as static shapes and add guards.
|
| 667 |
+
kernel_options = {
|
| 668 |
+
k: V.graph.sizevars.guard_int(v) if isinstance(v, sympy.Symbol) else v
|
| 669 |
+
for k, v in kernel_options.items()
|
| 670 |
+
}
|
| 671 |
+
kernel_options.setdefault("FLOAT32_PRECISION", get_float32_precision())
|
| 672 |
+
seq_q_divisible = V.graph.sizevars.statically_known_true(seq_len_q % 128 == 0)
|
| 673 |
+
seq_kv_divisible = V.graph.sizevars.statically_known_true(seq_len_kv % 128 == 0)
|
| 674 |
+
if seq_q_divisible and seq_kv_divisible:
|
| 675 |
+
kernel_options.setdefault("IS_DIVISIBLE", True)
|
| 676 |
+
else:
|
| 677 |
+
kernel_options.setdefault("IS_DIVISIBLE", False)
|
| 678 |
+
|
| 679 |
+
fwd_placeholder_inps = [
|
| 680 |
+
create_placeholder(name, dtype, device)
|
| 681 |
+
for name, dtype in [
|
| 682 |
+
("score", dtype),
|
| 683 |
+
("b", torch.int32),
|
| 684 |
+
("h", torch.int32),
|
| 685 |
+
("m", torch.int32),
|
| 686 |
+
("n", torch.int32),
|
| 687 |
+
]
|
| 688 |
+
]
|
| 689 |
+
fw_subgraph_buffer = build_subgraph_buffer(
|
| 690 |
+
fwd_placeholder_inps + list(score_mod_other_buffers), fw_graph
|
| 691 |
+
)
|
| 692 |
+
freeze_irnodes(fw_subgraph_buffer)
|
| 693 |
+
|
| 694 |
+
joint_placeholder_inps = fwd_placeholder_inps + [
|
| 695 |
+
create_placeholder("grad_score_mod", dtype, device)
|
| 696 |
+
]
|
| 697 |
+
# Sometimes we have weird unused nodes here
|
| 698 |
+
joint_graph.graph_module.graph.eliminate_dead_code()
|
| 699 |
+
|
| 700 |
+
# It is hard to raise nice errors for some joint graphs during subgraph lowering
|
| 701 |
+
# This lets us do some checks before attempting to lower
|
| 702 |
+
validate_joint_graph(joint_graph.graph_module.graph)
|
| 703 |
+
|
| 704 |
+
all_joint_outputs = build_subgraph_buffer(
|
| 705 |
+
joint_placeholder_inps + list(score_mod_other_buffers),
|
| 706 |
+
joint_graph,
|
| 707 |
+
)
|
| 708 |
+
freeze_irnodes(all_joint_outputs)
|
| 709 |
+
|
| 710 |
+
joint_outputs = process_joint_outputs(
|
| 711 |
+
all_joint_outputs, len(joint_placeholder_inps)
|
| 712 |
+
)
|
| 713 |
+
|
| 714 |
+
mask_graph_placeholder_inps = [
|
| 715 |
+
create_placeholder(name, dtype, query.get_device())
|
| 716 |
+
for name, dtype in [
|
| 717 |
+
("b", torch.int32),
|
| 718 |
+
("h", torch.int32),
|
| 719 |
+
("m", torch.int32),
|
| 720 |
+
("n", torch.int32),
|
| 721 |
+
]
|
| 722 |
+
]
|
| 723 |
+
mask_graph_buffer = build_subgraph_buffer(
|
| 724 |
+
mask_graph_placeholder_inps + list(mask_mod_other_buffers), mask_graph
|
| 725 |
+
)
|
| 726 |
+
freeze_irnodes(mask_graph_buffer)
|
| 727 |
+
|
| 728 |
+
if _use_flex_flash_attention_backward(
|
| 729 |
+
fw_graph,
|
| 730 |
+
mask_graph,
|
| 731 |
+
backend=backend,
|
| 732 |
+
):
|
| 733 |
+
return create_flex_flash_attention_backward_kernel(
|
| 734 |
+
query, key, value, out, logsumexp, grad_out, scale, kernel_options
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
# Construct layout with stride order matching K
|
| 738 |
+
key_size = [Bq, Hkv, seq_len_kv, qk_head_dim]
|
| 739 |
+
key_strides = infer_dense_strides(key_size, key.get_stride())
|
| 740 |
+
|
| 741 |
+
layout_broadcasted_k = FixedLayout(
|
| 742 |
+
key.get_device(),
|
| 743 |
+
key.get_dtype(),
|
| 744 |
+
key_size,
|
| 745 |
+
stride=[sympy.sympify(s) for s in key_strides],
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
# Create delta which will is needed for the bwd's kernel
|
| 749 |
+
grad_lse_exp2 = lowerings[aten.mul](grad_logsumexp, 1 / math.log(2))
|
| 750 |
+
mul_delta = lowerings[aten.mul](out, grad_out)
|
| 751 |
+
delta = lowerings[aten.sum](mul_delta, axis=-1)
|
| 752 |
+
delta = lowerings[aten.sub](delta, grad_lse_exp2)
|
| 753 |
+
delta = ExternKernel.require_contiguous(delta)
|
| 754 |
+
|
| 755 |
+
grad_lse_exp2, delta = maybe_realize([grad_lse_exp2, delta])
|
| 756 |
+
|
| 757 |
+
# # see NOTE:[TritonTemplates with multiple outputs]
|
| 758 |
+
query_size = [Bq, Hq, seq_len_q, qk_head_dim]
|
| 759 |
+
grad_query_strides = infer_dense_strides(query_size, query.get_stride())
|
| 760 |
+
grad_query = empty_strided(
|
| 761 |
+
query_size,
|
| 762 |
+
stride=[sympy.sympify(s) for s in grad_query_strides],
|
| 763 |
+
dtype=query.get_dtype(),
|
| 764 |
+
device=query.get_device(),
|
| 765 |
+
)
|
| 766 |
+
|
| 767 |
+
# Construct output layout with stride order matching value
|
| 768 |
+
value_size = [Bq, Hkv, seq_len_kv, v_head_dim]
|
| 769 |
+
value_strides = infer_dense_strides(value_size, value.get_stride())
|
| 770 |
+
|
| 771 |
+
broadcasted_grad_value = empty_strided(
|
| 772 |
+
value_size,
|
| 773 |
+
stride=[sympy.sympify(s) for s in value_strides],
|
| 774 |
+
dtype=value.get_dtype(),
|
| 775 |
+
device=value.get_device(),
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
kernel_options.setdefault("SM_SCALE", scale)
|
| 779 |
+
|
| 780 |
+
# Determine GQA factor
|
| 781 |
+
gqa_shared_heads = Hq // Hkv
|
| 782 |
+
kernel_options.setdefault("GQA_SHARED_HEADS", gqa_shared_heads)
|
| 783 |
+
|
| 784 |
+
# Inside of Triton kernel, only apply partial masking if partial blocks are computed.
|
| 785 |
+
# full_kv_num_blocks is torch.zeros([1, 1, 1]) if partial blocks are not computed.
|
| 786 |
+
has_full_blocks = full_kv_num_blocks is not None
|
| 787 |
+
kernel_options.setdefault("HAS_FULL_BLOCKS", has_full_blocks)
|
| 788 |
+
if not has_full_blocks:
|
| 789 |
+
full_kv_num_blocks, full_kv_indices, full_q_num_blocks, full_q_indices = (
|
| 790 |
+
empty(0, device=query.get_device()) for _ in range(4)
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
set_head_dim_values(kernel_options, qk_head_dim, v_head_dim, V.graph.sizevars)
|
| 794 |
+
|
| 795 |
+
SPARSE_Q_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_Q_BLOCK_SIZE)
|
| 796 |
+
SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE)
|
| 797 |
+
|
| 798 |
+
choices: list[Any] = []
|
| 799 |
+
|
| 800 |
+
dtype = query.get_dtype()
|
| 801 |
+
head_dim = V.graph.sizevars.guard_int(query.get_size()[-1])
|
| 802 |
+
configs: list[FlexBwDConfig] = V.choices.get_flex_attention_bwd_configs(
|
| 803 |
+
head_dim, dtype, query.get_device().type
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
# Default config for warp specialization
|
| 807 |
+
num_consumer_groups, num_buffers_warp_spec = 0, 0
|
| 808 |
+
|
| 809 |
+
original_kernel_options = kernel_options.copy()
|
| 810 |
+
|
| 811 |
+
for conf in configs:
|
| 812 |
+
if (
|
| 813 |
+
SPARSE_KV_BLOCK_SIZE % conf.block_n1 != 0
|
| 814 |
+
or SPARSE_Q_BLOCK_SIZE % conf.block_m1 != 0
|
| 815 |
+
or SPARSE_KV_BLOCK_SIZE % conf.block_n2 != 0
|
| 816 |
+
or SPARSE_Q_BLOCK_SIZE % conf.block_m2 != 0
|
| 817 |
+
):
|
| 818 |
+
continue
|
| 819 |
+
|
| 820 |
+
# Performance tuning
|
| 821 |
+
# Triton heuristics
|
| 822 |
+
cur_kernel_options = original_kernel_options.copy()
|
| 823 |
+
# Remove prefix for backward kernels options and delete forward kernel options.
|
| 824 |
+
for k in list(cur_kernel_options.keys()):
|
| 825 |
+
if k.startswith("bwd_"):
|
| 826 |
+
v = cur_kernel_options.pop(k)
|
| 827 |
+
cur_kernel_options[k[4:]] = v
|
| 828 |
+
if k.startswith("fwd_"):
|
| 829 |
+
cur_kernel_options.pop(k)
|
| 830 |
+
cur_kernel_options.setdefault("num_warps", conf.num_warps)
|
| 831 |
+
cur_kernel_options.setdefault("num_stages", conf.num_stages)
|
| 832 |
+
|
| 833 |
+
if cur_kernel_options.get("num_consumer_groups", False):
|
| 834 |
+
cur_kernel_options.setdefault("num_consumer_groups", num_consumer_groups)
|
| 835 |
+
cur_kernel_options.setdefault(
|
| 836 |
+
"num_buffers_warp_spec", num_buffers_warp_spec
|
| 837 |
+
)
|
| 838 |
+
|
| 839 |
+
cur_kernel_options.setdefault("BLOCK_M1", conf.block_m1)
|
| 840 |
+
cur_kernel_options.setdefault("BLOCK_N1", conf.block_n1)
|
| 841 |
+
cur_kernel_options.setdefault("BLOCK_M2", conf.block_m2)
|
| 842 |
+
cur_kernel_options.setdefault("BLOCK_N2", conf.block_n2)
|
| 843 |
+
|
| 844 |
+
# Blocksparse options
|
| 845 |
+
cur_kernel_options.setdefault("SPARSE_Q_BLOCK_SIZE", SPARSE_Q_BLOCK_SIZE)
|
| 846 |
+
cur_kernel_options.setdefault("SPARSE_KV_BLOCK_SIZE", SPARSE_KV_BLOCK_SIZE)
|
| 847 |
+
|
| 848 |
+
# ROCm specific kernargs
|
| 849 |
+
for attrib in ["kpack", "matrix_instr_nonkdim", "waves_per_eu"]:
|
| 850 |
+
if hasattr(conf, attrib):
|
| 851 |
+
cur_kernel_options[attrib] = getattr(conf, attrib)
|
| 852 |
+
|
| 853 |
+
flex_attention_backward_template.maybe_append_choice(
|
| 854 |
+
choices=choices,
|
| 855 |
+
input_nodes=[
|
| 856 |
+
query,
|
| 857 |
+
key,
|
| 858 |
+
value,
|
| 859 |
+
logsumexp,
|
| 860 |
+
delta,
|
| 861 |
+
grad_out,
|
| 862 |
+
grad_query,
|
| 863 |
+
broadcasted_grad_value,
|
| 864 |
+
kv_num_blocks,
|
| 865 |
+
kv_indices,
|
| 866 |
+
q_num_blocks,
|
| 867 |
+
q_indices,
|
| 868 |
+
full_kv_num_blocks,
|
| 869 |
+
full_kv_indices,
|
| 870 |
+
full_q_num_blocks,
|
| 871 |
+
full_q_indices,
|
| 872 |
+
],
|
| 873 |
+
layout=layout_broadcasted_k, # We use store_output only for grad_key
|
| 874 |
+
subgraphs=[
|
| 875 |
+
fw_subgraph_buffer,
|
| 876 |
+
joint_outputs.grad_input,
|
| 877 |
+
mask_graph_buffer,
|
| 878 |
+
joint_outputs.captured_grads_compute,
|
| 879 |
+
],
|
| 880 |
+
mutated_inputs=[
|
| 881 |
+
grad_query,
|
| 882 |
+
broadcasted_grad_value,
|
| 883 |
+
*joint_outputs.mutated_grads,
|
| 884 |
+
],
|
| 885 |
+
call_sizes=query.get_size() + key.get_size()[1:3],
|
| 886 |
+
**cur_kernel_options,
|
| 887 |
+
)
|
| 888 |
+
inputs_for_autotuning = (
|
| 889 |
+
# pyrefly: ignore [unsupported-operation]
|
| 890 |
+
[
|
| 891 |
+
query,
|
| 892 |
+
key,
|
| 893 |
+
value,
|
| 894 |
+
logsumexp,
|
| 895 |
+
delta,
|
| 896 |
+
grad_out,
|
| 897 |
+
grad_query,
|
| 898 |
+
broadcasted_grad_value,
|
| 899 |
+
kv_num_blocks,
|
| 900 |
+
kv_indices,
|
| 901 |
+
q_num_blocks,
|
| 902 |
+
q_indices,
|
| 903 |
+
full_kv_num_blocks,
|
| 904 |
+
full_kv_indices,
|
| 905 |
+
full_q_num_blocks,
|
| 906 |
+
full_q_indices,
|
| 907 |
+
]
|
| 908 |
+
+ list(score_mod_other_buffers)
|
| 909 |
+
+ list(mask_mod_other_buffers)
|
| 910 |
+
+ joint_outputs.mutated_grads
|
| 911 |
+
)
|
| 912 |
+
input_gen_fns = {
|
| 913 |
+
8: create_num_blocks_fake_generator(kv_indices), # kv_num_blocks
|
| 914 |
+
9: create_indices_fake,
|
| 915 |
+
10: create_num_blocks_fake_generator(q_indices), # q_num_blocks
|
| 916 |
+
11: create_indices_fake,
|
| 917 |
+
12: create_num_blocks_fake_generator(full_kv_indices), # full_kv_num_blocks
|
| 918 |
+
13: create_indices_fake,
|
| 919 |
+
14: create_num_blocks_fake_generator(full_q_indices), # full_q_num_blocks
|
| 920 |
+
15: create_indices_fake,
|
| 921 |
+
}
|
| 922 |
+
|
| 923 |
+
broadcasted_grad_key = autotune_select_algorithm(
|
| 924 |
+
"flex_attention_backward",
|
| 925 |
+
choices,
|
| 926 |
+
[x for x in inputs_for_autotuning if isinstance(x, torch._inductor.ir.IRNode)],
|
| 927 |
+
layout_broadcasted_k,
|
| 928 |
+
input_gen_fns=input_gen_fns,
|
| 929 |
+
) # [Bq, Hkv, seq_len_kv, k_head_dim]
|
| 930 |
+
|
| 931 |
+
# need subgraph inputs and outputs to analyze all symints used in flex attention
|
| 932 |
+
broadcasted_grad_key.data.data.subgraph_inps = list(score_mod_other_buffers) + list(
|
| 933 |
+
mask_mod_other_buffers
|
| 934 |
+
)
|
| 935 |
+
broadcasted_grad_key.data.data.subgraph_outs = get_bwd_subgraph_outputs(
|
| 936 |
+
fw_subgraph_buffer, mask_graph_buffer, joint_outputs
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
if V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv)):
|
| 940 |
+
grad_key = broadcasted_grad_key
|
| 941 |
+
grad_value = broadcasted_grad_value
|
| 942 |
+
else:
|
| 943 |
+
assert V.graph.sizevars.evaluate_expr(sympy.Gt(Bq, 1) & sympy.Eq(Bkv, 1)), (
|
| 944 |
+
f"Bq and Bkv must broadcastable. "
|
| 945 |
+
f"Got Bq={V.graph.sizevars.evaluate_expr(Bq)} "
|
| 946 |
+
f"and Bkv={V.graph.sizevars.evaluate_expr(Bkv)}"
|
| 947 |
+
)
|
| 948 |
+
grad_key = lowerings[aten.sum](broadcasted_grad_key, axis=0, keepdims=True)
|
| 949 |
+
grad_value = lowerings[aten.sum](broadcasted_grad_value, axis=0, keepdims=True)
|
| 950 |
+
|
| 951 |
+
return (grad_query, grad_key, grad_value, tuple(joint_outputs.captured_grads))
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
def get_bwd_subgraph_outputs(
|
| 955 |
+
subgraph_buffer: SubgraphResults,
|
| 956 |
+
mask_graph_buffer: SubgraphResults,
|
| 957 |
+
joint_outputs: JointOutputResult,
|
| 958 |
+
) -> list[Optional[Union[ComputedBuffer, TensorBox]]]:
|
| 959 |
+
subgraph_buffer = (
|
| 960 |
+
# pyrefly: ignore [bad-assignment]
|
| 961 |
+
subgraph_buffer if isinstance(subgraph_buffer, Sequence) else [subgraph_buffer]
|
| 962 |
+
)
|
| 963 |
+
mask_graph_buffer = (
|
| 964 |
+
# pyrefly: ignore [bad-assignment]
|
| 965 |
+
mask_graph_buffer
|
| 966 |
+
if isinstance(mask_graph_buffer, Sequence)
|
| 967 |
+
else [mask_graph_buffer]
|
| 968 |
+
)
|
| 969 |
+
joint_output_buffers = [
|
| 970 |
+
joint_outputs.grad_input,
|
| 971 |
+
*joint_outputs.captured_grads_compute,
|
| 972 |
+
*joint_outputs.captured_grads,
|
| 973 |
+
*joint_outputs.mutated_grads,
|
| 974 |
+
]
|
| 975 |
+
|
| 976 |
+
# pyrefly: ignore [not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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""CPU-specific implementations for flex attention"""
|
| 3 |
+
|
| 4 |
+
import copy
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
import sympy
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from torch._inductor.virtualized import V
|
| 13 |
+
from torch.utils._ordered_set import OrderedSet
|
| 14 |
+
from torch.utils._sympy.numbers import int_oo
|
| 15 |
+
from torch.utils._sympy.value_ranges import ValueRanges
|
| 16 |
+
|
| 17 |
+
from ...codegen.cpp_flex_attention_template import CppFlexAttentionTemplate
|
| 18 |
+
from ...ir import Buffer, FixedLayout, TensorBox
|
| 19 |
+
from ...select_algorithm import autotune_select_algorithm
|
| 20 |
+
from .common import (
|
| 21 |
+
build_subgraph_buffer,
|
| 22 |
+
build_subgraph_module_buffer,
|
| 23 |
+
contiguous_last_dim,
|
| 24 |
+
create_placeholder,
|
| 25 |
+
get_fwd_subgraph_outputs,
|
| 26 |
+
infer_dense_strides,
|
| 27 |
+
maybe_realize,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def check_cpu_supported():
|
| 32 |
+
requires_avx2_on_cpu = (
|
| 33 |
+
torch.cpu._is_avx2_supported() and os.getenv("ATEN_CPU_CAPABILITY") != "default"
|
| 34 |
+
)
|
| 35 |
+
supported = (
|
| 36 |
+
requires_avx2_on_cpu
|
| 37 |
+
and not torch.xpu.is_available()
|
| 38 |
+
and sys.platform != "darwin"
|
| 39 |
+
)
|
| 40 |
+
return supported
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def lower_cpu(
|
| 44 |
+
query,
|
| 45 |
+
key,
|
| 46 |
+
value,
|
| 47 |
+
subgraph,
|
| 48 |
+
block_mask,
|
| 49 |
+
scale,
|
| 50 |
+
kernel_options,
|
| 51 |
+
score_mod_other_buffers,
|
| 52 |
+
mask_mod_other_buffers,
|
| 53 |
+
):
|
| 54 |
+
"""CPP based template for flex attention for x86 CPUs"""
|
| 55 |
+
(
|
| 56 |
+
_, # q_length
|
| 57 |
+
_, # kv_length
|
| 58 |
+
kv_num_blocks,
|
| 59 |
+
kv_indices,
|
| 60 |
+
full_kv_num_blocks,
|
| 61 |
+
full_kv_indices,
|
| 62 |
+
q_num_blocks,
|
| 63 |
+
q_indices,
|
| 64 |
+
full_q_num_blocks,
|
| 65 |
+
full_q_indices,
|
| 66 |
+
SPARSE_Q_BLOCK_SIZE,
|
| 67 |
+
SPARSE_KV_BLOCK_SIZE,
|
| 68 |
+
mask_graph,
|
| 69 |
+
) = block_mask
|
| 70 |
+
|
| 71 |
+
if kernel_options["OUTPUT_LOGSUMEXP"]:
|
| 72 |
+
raise NotImplementedError(
|
| 73 |
+
"torch.compile on CPU only supports inference and `return_lse` is not supported yet."
|
| 74 |
+
)
|
| 75 |
+
if not check_cpu_supported():
|
| 76 |
+
raise NotImplementedError(
|
| 77 |
+
"torch.compile on current platform is not supported for CPU."
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
fake_buffers: list[Buffer] = [] # noqa: F821
|
| 81 |
+
|
| 82 |
+
# [Note] Handle the case where the split sizes are not statically known.
|
| 83 |
+
# The value of cur_qSplitSize and cur_kvSplitSize are decided during runtime.
|
| 84 |
+
# We use symbols to represent them during the compilation here.
|
| 85 |
+
# They'll be replaced by the string "cur_qSplitSize" and "cur_kvSplitSize" in
|
| 86 |
+
# the modification function of the CppFlexAttentionTemplate class.
|
| 87 |
+
cur_qSplitSize = V.graph.sizevars.shape_env.create_unbacked_symint().node.expr
|
| 88 |
+
cur_kvSplitSize = V.graph.sizevars.shape_env.create_unbacked_symint().node.expr
|
| 89 |
+
shape_env = V.graph.sizevars.shape_env
|
| 90 |
+
|
| 91 |
+
# We don't know the concrete value of cur_qSplitSize and cur_kvSplitSize during the compilation.
|
| 92 |
+
# Mark symbols > 1 to ensure broadcasting is always applied.
|
| 93 |
+
# This avoids treating them as equal when `eq(var, 1)` is evaluated in `broadcast_symbolic_shapes`.
|
| 94 |
+
shape_env.var_to_range[cur_qSplitSize] = ValueRanges(2, int_oo)
|
| 95 |
+
shape_env.var_to_range[cur_kvSplitSize] = ValueRanges(2, int_oo)
|
| 96 |
+
|
| 97 |
+
score_dtype = torch.float
|
| 98 |
+
placeholder_inps = [
|
| 99 |
+
create_placeholder(name, dtype, query.get_device(), size)
|
| 100 |
+
for name, dtype, size in [
|
| 101 |
+
("score", score_dtype, [cur_qSplitSize, cur_kvSplitSize]),
|
| 102 |
+
("b", torch.int64, []),
|
| 103 |
+
("h", torch.int64, []),
|
| 104 |
+
("q_idx", torch.int64, [cur_qSplitSize, 1]),
|
| 105 |
+
("kv_idx", torch.int64, [1, cur_kvSplitSize]),
|
| 106 |
+
]
|
| 107 |
+
]
|
| 108 |
+
subgraph_buffer = build_subgraph_buffer(
|
| 109 |
+
placeholder_inps + list(score_mod_other_buffers), subgraph
|
| 110 |
+
)
|
| 111 |
+
if subgraph_buffer is not None:
|
| 112 |
+
if isinstance(subgraph_buffer, list):
|
| 113 |
+
for _buf in subgraph_buffer:
|
| 114 |
+
if _buf is not None:
|
| 115 |
+
_buf.freeze_layout()
|
| 116 |
+
else:
|
| 117 |
+
subgraph_buffer.freeze_layout()
|
| 118 |
+
mask_graph_placeholder_inps = [
|
| 119 |
+
create_placeholder(name, dtype, query.get_device(), size)
|
| 120 |
+
for name, dtype, size in [
|
| 121 |
+
("score", score_dtype, [cur_qSplitSize, cur_kvSplitSize]),
|
| 122 |
+
("b", torch.int64, []),
|
| 123 |
+
("h", torch.int64, []),
|
| 124 |
+
("q_idx", torch.int64, [cur_qSplitSize, 1]),
|
| 125 |
+
("kv_idx", torch.int64, [1, cur_kvSplitSize]),
|
| 126 |
+
]
|
| 127 |
+
]
|
| 128 |
+
|
| 129 |
+
# The original mask_graph works on a scalar and only includes
|
| 130 |
+
# the logic of calculating the mask value.
|
| 131 |
+
# We need to add the logic of applying the mark to the qk_data tensor
|
| 132 |
+
# into the graph for the later codegen of this part.
|
| 133 |
+
# Example:
|
| 134 |
+
# mask_graph:
|
| 135 |
+
# def mask_fn(b, h, q_idx, kv_idx):
|
| 136 |
+
# mask = q_idx >= kv_idx
|
| 137 |
+
# return mask
|
| 138 |
+
# The converted_mask_graph should be:
|
| 139 |
+
# def converted_mask_fn(qk_data, b, h, q_idx, kv_idx):
|
| 140 |
+
# mask = q_idx >= kv_idx
|
| 141 |
+
# qk_data = torch.where(mask, qk_data, torch.full_like(qk_data, -float("inf")))
|
| 142 |
+
# return qk_data
|
| 143 |
+
def convert_mask_graph_module(mask_graph):
|
| 144 |
+
gm = copy.deepcopy(mask_graph.graph_module)
|
| 145 |
+
graph = gm.graph
|
| 146 |
+
# Add qk_data as the first input
|
| 147 |
+
with graph.inserting_before(next(iter(graph.nodes))):
|
| 148 |
+
qk_data_node = graph.placeholder("qk_data")
|
| 149 |
+
|
| 150 |
+
# Find the node that returns the mask
|
| 151 |
+
output_node = None
|
| 152 |
+
for node in graph.nodes:
|
| 153 |
+
if node.op == "output":
|
| 154 |
+
output_node = node
|
| 155 |
+
break
|
| 156 |
+
|
| 157 |
+
# Get the mask node
|
| 158 |
+
assert output_node is not None
|
| 159 |
+
mask_node = output_node.args[0]
|
| 160 |
+
|
| 161 |
+
size_node = [cur_qSplitSize, cur_kvSplitSize]
|
| 162 |
+
# Create a new node for torch.full
|
| 163 |
+
with graph.inserting_after(mask_node):
|
| 164 |
+
full_node = graph.call_function(
|
| 165 |
+
torch.full,
|
| 166 |
+
args=(size_node, -float("inf")),
|
| 167 |
+
kwargs={"dtype": score_dtype},
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# Create a new node for torch.where
|
| 171 |
+
with graph.inserting_after(full_node):
|
| 172 |
+
where_node = graph.call_function(
|
| 173 |
+
torch.ops.aten.where, args=(mask_node, qk_data_node, full_node)
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# Update the output node to return the result of torch.where
|
| 177 |
+
output_node.args = (where_node,)
|
| 178 |
+
|
| 179 |
+
graph.lint()
|
| 180 |
+
converted = torch.fx.GraphModule(gm, graph)
|
| 181 |
+
return converted
|
| 182 |
+
|
| 183 |
+
converted_mask_graph_module = convert_mask_graph_module(mask_graph)
|
| 184 |
+
|
| 185 |
+
mask_graph_buffer = build_subgraph_module_buffer(
|
| 186 |
+
mask_graph_placeholder_inps + list(mask_mod_other_buffers),
|
| 187 |
+
converted_mask_graph_module,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
# Clear the pending fresh unbacked symbols that are created for cur_qSplitSize and cur_kvSplitSize in the current kernel.
|
| 191 |
+
pending = V.graph.sizevars.shape_env.pending_fresh_unbacked_symbols
|
| 192 |
+
V.graph.sizevars.shape_env.pending_fresh_unbacked_symbols = [
|
| 193 |
+
x for x in pending if x not in (cur_qSplitSize, cur_kvSplitSize)
|
| 194 |
+
]
|
| 195 |
+
|
| 196 |
+
buffer_list = (
|
| 197 |
+
placeholder_inps
|
| 198 |
+
+ list(score_mod_other_buffers)
|
| 199 |
+
+ mask_graph_placeholder_inps
|
| 200 |
+
+ list(mask_mod_other_buffers)
|
| 201 |
+
)
|
| 202 |
+
for item in buffer_list:
|
| 203 |
+
if isinstance(item, TensorBox):
|
| 204 |
+
fake_buffers.append(item.data.data) # type: ignore[attr-defined]
|
| 205 |
+
|
| 206 |
+
# CPU kernel requires last dim to be contiguous
|
| 207 |
+
query, key, value = map(contiguous_last_dim, [query, key, value])
|
| 208 |
+
|
| 209 |
+
(
|
| 210 |
+
query,
|
| 211 |
+
key,
|
| 212 |
+
value,
|
| 213 |
+
kv_num_blocks,
|
| 214 |
+
kv_indices,
|
| 215 |
+
full_kv_num_blocks,
|
| 216 |
+
full_kv_indices,
|
| 217 |
+
q_num_blocks,
|
| 218 |
+
q_indices,
|
| 219 |
+
full_q_num_blocks,
|
| 220 |
+
full_q_indices,
|
| 221 |
+
) = maybe_realize(
|
| 222 |
+
[
|
| 223 |
+
query,
|
| 224 |
+
key,
|
| 225 |
+
value,
|
| 226 |
+
kv_num_blocks,
|
| 227 |
+
kv_indices,
|
| 228 |
+
full_kv_num_blocks,
|
| 229 |
+
full_kv_indices,
|
| 230 |
+
q_num_blocks,
|
| 231 |
+
q_indices,
|
| 232 |
+
full_q_num_blocks,
|
| 233 |
+
full_q_indices,
|
| 234 |
+
]
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
if len(OrderedSet([query.get_name(), key.get_name(), value.get_name()])) != 3:
|
| 238 |
+
raise NotImplementedError(
|
| 239 |
+
"Unsupported for now if query, key, value are the same buffer."
|
| 240 |
+
)
|
| 241 |
+
if query.get_dtype() not in [torch.float, torch.bfloat16, torch.float16]:
|
| 242 |
+
raise NotImplementedError(
|
| 243 |
+
"`torch.float` , `torch.float16` and `torch.bfloat16` are supported in FlexAttention for CPU device. "
|
| 244 |
+
f"Found input tensors are `{query.get_dtype()}`."
|
| 245 |
+
)
|
| 246 |
+
score_mod_other_buffers = maybe_realize(score_mod_other_buffers)
|
| 247 |
+
mask_mod_other_buffers = maybe_realize(mask_mod_other_buffers)
|
| 248 |
+
Bq, Hq, seq_len_q, qk_head_dim = query.get_size()
|
| 249 |
+
Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size()
|
| 250 |
+
B = Bq
|
| 251 |
+
|
| 252 |
+
# Construct output layout with strides matching the query.
|
| 253 |
+
out_size = [B, Hq, seq_len_q, v_head_dim]
|
| 254 |
+
out_strides = infer_dense_strides(out_size, query.get_stride())
|
| 255 |
+
|
| 256 |
+
layout = FixedLayout(
|
| 257 |
+
query.get_device(),
|
| 258 |
+
query.get_dtype(),
|
| 259 |
+
[B, Hq, seq_len_q, v_head_dim],
|
| 260 |
+
stride=[sympy.sympify(s) for s in out_strides],
|
| 261 |
+
)
|
| 262 |
+
_choices: list[Any] = []
|
| 263 |
+
input_nodes = [query, key, value, kv_num_blocks, kv_indices]
|
| 264 |
+
if not full_kv_num_blocks:
|
| 265 |
+
no_full_kv_block = True
|
| 266 |
+
else:
|
| 267 |
+
no_full_kv_block = False
|
| 268 |
+
input_nodes += [full_kv_num_blocks]
|
| 269 |
+
input_nodes += [full_kv_indices]
|
| 270 |
+
has_other_buffer = False
|
| 271 |
+
kernel_input_name_to_buffer = {}
|
| 272 |
+
if score_mod_other_buffers or mask_mod_other_buffers:
|
| 273 |
+
has_other_buffer = True
|
| 274 |
+
|
| 275 |
+
for prefix, buffers in [
|
| 276 |
+
("score_others", score_mod_other_buffers),
|
| 277 |
+
("mask_others", mask_mod_other_buffers),
|
| 278 |
+
]:
|
| 279 |
+
kernel_input_name_to_buffer.update(
|
| 280 |
+
{f"{prefix}_{i}": buf for i, buf in enumerate(buffers)}
|
| 281 |
+
)
|
| 282 |
+
input_nodes += [
|
| 283 |
+
value
|
| 284 |
+
for value in kernel_input_name_to_buffer.values()
|
| 285 |
+
if not isinstance(value, sympy.Symbol)
|
| 286 |
+
]
|
| 287 |
+
|
| 288 |
+
skip_mask_score = kernel_options.get("SKIP_MASK_SCORE", False)
|
| 289 |
+
# Mark SPARSE_KV_BLOCK_SIZE & SPARSE_Q_BLOCK_SIZE as static shapes and add guards.
|
| 290 |
+
SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE)
|
| 291 |
+
SPARSE_Q_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_Q_BLOCK_SIZE)
|
| 292 |
+
assert V.graph.sizevars.evaluate_expr(
|
| 293 |
+
sympy.Le(seq_len_q, sympy.Mul(kv_indices.get_size()[-2], SPARSE_Q_BLOCK_SIZE))
|
| 294 |
+
), (
|
| 295 |
+
"Q seqlen must be smaller than the block_mask size in the Q dimension, considering pass a larger block_mask."
|
| 296 |
+
)
|
| 297 |
+
assert V.graph.sizevars.evaluate_expr(
|
| 298 |
+
sympy.Le(seq_len_kv, sympy.Mul(kv_indices.get_size()[-1], SPARSE_KV_BLOCK_SIZE))
|
| 299 |
+
), (
|
| 300 |
+
"KV seqlen must be smaller than the block_mask size in the KV dimension, considering pass a larger block_mask."
|
| 301 |
+
)
|
| 302 |
+
CppFlexAttentionTemplate.add_choices(
|
| 303 |
+
choices=_choices,
|
| 304 |
+
input_nodes=input_nodes,
|
| 305 |
+
layout=layout,
|
| 306 |
+
scale=scale,
|
| 307 |
+
score_mod=None if skip_mask_score else subgraph_buffer,
|
| 308 |
+
mask_mod=None if skip_mask_score else mask_graph_buffer,
|
| 309 |
+
kv_block_size=SPARSE_KV_BLOCK_SIZE,
|
| 310 |
+
q_block_size=SPARSE_Q_BLOCK_SIZE,
|
| 311 |
+
has_other_buffer=has_other_buffer,
|
| 312 |
+
no_full_kv_block=no_full_kv_block,
|
| 313 |
+
fake_buffers=fake_buffers,
|
| 314 |
+
len_score_other=len(score_mod_other_buffers),
|
| 315 |
+
len_mask_other=len(mask_mod_other_buffers),
|
| 316 |
+
kernel_input_name_to_buffer=kernel_input_name_to_buffer,
|
| 317 |
+
block_vars=(cur_qSplitSize, cur_kvSplitSize),
|
| 318 |
+
)
|
| 319 |
+
inputs_for_autotuning = [
|
| 320 |
+
query,
|
| 321 |
+
key,
|
| 322 |
+
value,
|
| 323 |
+
]
|
| 324 |
+
res = autotune_select_algorithm(
|
| 325 |
+
"flex_attention",
|
| 326 |
+
_choices,
|
| 327 |
+
inputs_for_autotuning,
|
| 328 |
+
layout,
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
# need subgraph inputs and outputs to analyze all symints used in flex attention
|
| 332 |
+
res.data.data.subgraph_inps = list(score_mod_other_buffers) + list(
|
| 333 |
+
mask_mod_other_buffers
|
| 334 |
+
)
|
| 335 |
+
res.data.data.subgraph_outs = get_fwd_subgraph_outputs(
|
| 336 |
+
subgraph_buffer, mask_graph_buffer
|
| 337 |
+
)
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""Triton Implementation of the flex_attention Kernel for short query length (FlexDecoding)"""
|
| 3 |
+
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import sympy
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch._inductor.virtualized import V
|
| 10 |
+
|
| 11 |
+
from ... import ir
|
| 12 |
+
from ...ir import FixedLayout, FlexibleLayout
|
| 13 |
+
from ...lowering import empty, empty_strided, lowerings
|
| 14 |
+
from ...runtime.runtime_utils import is_power_of_2, next_power_of_2
|
| 15 |
+
from ...select_algorithm import (
|
| 16 |
+
autotune_select_algorithm,
|
| 17 |
+
SymbolicGridFn,
|
| 18 |
+
TritonTemplate,
|
| 19 |
+
)
|
| 20 |
+
from .common import (
|
| 21 |
+
create_indices_fake,
|
| 22 |
+
create_num_blocks_fake_generator,
|
| 23 |
+
freeze_irnodes,
|
| 24 |
+
get_fwd_subgraph_outputs,
|
| 25 |
+
load_flex_template,
|
| 26 |
+
maybe_realize,
|
| 27 |
+
set_head_dim_values,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
aten = torch.ops.aten
|
| 32 |
+
prims = torch.ops.prims
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _use_flex_decoding(query, kv_indices, value, kernel_options, enable_gqa) -> bool:
|
| 36 |
+
"""Decide which kernel to use, return true if use flex decoding kernel.
|
| 37 |
+
Note:
|
| 38 |
+
Since the number of splits is calculated based of the number of batch and head dims
|
| 39 |
+
we need to ensure that the batch and head dims are statically known. Otherwise we just
|
| 40 |
+
use the main flex_attention kernel.
|
| 41 |
+
"""
|
| 42 |
+
force_flex = kernel_options.get("FORCE_USE_FLEX_ATTENTION", False)
|
| 43 |
+
short_query_length = V.graph.sizevars.evaluate_expr(
|
| 44 |
+
sympy.Lt(query.get_size()[-2], 128)
|
| 45 |
+
)
|
| 46 |
+
non_zero_length = V.graph.sizevars.evaluate_expr(sympy.Gt(query.get_size()[-2], 0))
|
| 47 |
+
static_batch = isinstance(query.get_size()[0], (int, sympy.Integer))
|
| 48 |
+
static_num_heads = isinstance(query.get_size()[1], (int, sympy.Integer))
|
| 49 |
+
if enable_gqa:
|
| 50 |
+
# in the current flex decoding triton kernel, grouped query heads for the
|
| 51 |
+
# same kv head are handled by the same block. So it's hard to support different
|
| 52 |
+
# kv num blocks for grouped query heads. We just fall back to main flex_attention
|
| 53 |
+
# kernel where each query head is handled by a separate block.
|
| 54 |
+
valid_block_mask_num_heads = V.graph.sizevars.evaluate_expr(
|
| 55 |
+
sympy.Eq(kv_indices.get_size()[1], 1)
|
| 56 |
+
)
|
| 57 |
+
else:
|
| 58 |
+
valid_block_mask_num_heads = V.graph.sizevars.evaluate_expr(
|
| 59 |
+
sympy.Or(
|
| 60 |
+
sympy.Eq(kv_indices.get_size()[1], 1),
|
| 61 |
+
sympy.Eq(kv_indices.get_size()[1], query.get_size()[1]),
|
| 62 |
+
)
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
Hq = query.get_size()[1]
|
| 66 |
+
Hkv = value.get_size()[1]
|
| 67 |
+
ratio = Hq // Hkv
|
| 68 |
+
|
| 69 |
+
pw_of_two = V.graph.sizevars.guard_or_false(
|
| 70 |
+
sympy.And(sympy.Gt(ratio, 0), sympy.Eq(ratio & (ratio - 1), 0))
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
return (
|
| 74 |
+
not force_flex
|
| 75 |
+
and not kernel_options.get("OUTPUT_MAX", False)
|
| 76 |
+
and short_query_length
|
| 77 |
+
and static_batch
|
| 78 |
+
and static_num_heads
|
| 79 |
+
and non_zero_length
|
| 80 |
+
and valid_block_mask_num_heads
|
| 81 |
+
and pw_of_two
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@SymbolicGridFn
|
| 86 |
+
def flex_decoding_grid(batch_size, kv_heads, gqa_group_size, n_keys, d_model, meta):
|
| 87 |
+
"""How is this kernel parallelized?
|
| 88 |
+
We create a grid of (batch_size * kv_heads, SPLIT_KV, 1)
|
| 89 |
+
Each block is responsible for iterating over blocks of keys and values calculating
|
| 90 |
+
the local output for their tile of keys and values over all full length of query.
|
| 91 |
+
groups of SPLIT_KV blocks then combine their output to produce the final result.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
return (batch_size * kv_heads, meta["SPLIT_KV"], 1)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
flex_decoding_template = TritonTemplate(
|
| 98 |
+
name="flex_decoding",
|
| 99 |
+
grid=flex_decoding_grid,
|
| 100 |
+
source=load_flex_template("flex_decode")
|
| 101 |
+
+ load_flex_template("utilities")
|
| 102 |
+
+ load_flex_template("common"),
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def get_split_k(B: int, H: int, Mk: int) -> int:
|
| 107 |
+
if torch.xpu.is_available():
|
| 108 |
+
num_SM = torch.xpu.get_device_properties("xpu").gpu_subslice_count
|
| 109 |
+
else:
|
| 110 |
+
num_SM = torch.cuda.get_device_properties("cuda").multi_processor_count
|
| 111 |
+
bh = max(B * H, 1) # NOTE: Handle B*h=0 case
|
| 112 |
+
assert isinstance(bh, (int, sympy.Integer)), "B and H must be concrete integers"
|
| 113 |
+
split_k = num_SM // bh * 2 # Each SM should at least get one block.
|
| 114 |
+
# TODO: workload evening at runtime for splits fully masked out.
|
| 115 |
+
# Before we have runtime workload evening, assign 2 splits per SM.
|
| 116 |
+
split_k = max(split_k, 1)
|
| 117 |
+
|
| 118 |
+
return split_k
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def create_flex_decoding_kernel(*args, **kwargs):
|
| 122 |
+
"""Flex decode lowering that is optimized for small Q_LEN and GQA packing"""
|
| 123 |
+
(
|
| 124 |
+
query,
|
| 125 |
+
key,
|
| 126 |
+
value,
|
| 127 |
+
block_mask,
|
| 128 |
+
scale,
|
| 129 |
+
kernel_options,
|
| 130 |
+
score_mod_subgraph,
|
| 131 |
+
mask_mod_subgraph,
|
| 132 |
+
score_mod_other_buffers,
|
| 133 |
+
mask_mod_other_buffers,
|
| 134 |
+
) = args
|
| 135 |
+
(
|
| 136 |
+
_, # q_length
|
| 137 |
+
_, # kv_length
|
| 138 |
+
kv_num_blocks,
|
| 139 |
+
kv_indices,
|
| 140 |
+
full_kv_num_blocks, # full_kv_num_blocks,
|
| 141 |
+
full_kv_indices, # full_kv_indices,
|
| 142 |
+
_, # q_num_blocks
|
| 143 |
+
_, # q_indices
|
| 144 |
+
_, # full_q_num_blocks,
|
| 145 |
+
_, # full_q_indices,
|
| 146 |
+
_, # SPARSE_Q_BLOCK_SIZE,
|
| 147 |
+
SPARSE_KV_BLOCK_SIZE,
|
| 148 |
+
_,
|
| 149 |
+
) = block_mask
|
| 150 |
+
|
| 151 |
+
Bq, Hq, seq_len_q, qk_head_dim = query.get_size()
|
| 152 |
+
Bkv, Hkv, seq_len_kv, v_head_dim = value.get_size()
|
| 153 |
+
|
| 154 |
+
assert V.graph.sizevars.evaluate_expr(sympy.Eq(Bq, Bkv) | sympy.Eq(Bkv, 1)), (
|
| 155 |
+
f"Bq and Bkv must broadcastable. Got Bq={Bq} and Bkv={Bkv}"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
B = Bq
|
| 159 |
+
kernel_options = dict(kernel_options)
|
| 160 |
+
# Mark symbols in custom kernel options as static shapes and add guards.
|
| 161 |
+
kernel_options = {
|
| 162 |
+
k: V.graph.sizevars.guard_int(v) if isinstance(v, sympy.Symbol) else v
|
| 163 |
+
for k, v in kernel_options.items()
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
seq_q_divisible = V.graph.sizevars.statically_known_true(seq_len_q % 128 == 0)
|
| 167 |
+
seq_kv_divisible = V.graph.sizevars.statically_known_true(seq_len_kv % 128 == 0)
|
| 168 |
+
if seq_q_divisible and seq_kv_divisible:
|
| 169 |
+
kernel_options.setdefault("IS_DIVISIBLE", True)
|
| 170 |
+
else:
|
| 171 |
+
kernel_options.setdefault("IS_DIVISIBLE", False)
|
| 172 |
+
|
| 173 |
+
# Calculate GQA head sharing
|
| 174 |
+
gqa_shared_heads = Hq // Hkv
|
| 175 |
+
if not is_power_of_2(gqa_shared_heads):
|
| 176 |
+
raise ValueError(
|
| 177 |
+
"Number of shared query heads sharing the same KV head must be power of 2. "
|
| 178 |
+
)
|
| 179 |
+
kernel_options.setdefault("GQA_SHARED_HEADS", gqa_shared_heads)
|
| 180 |
+
|
| 181 |
+
# Determine if there are "full" blocks where we only need to apply score_mod, and can skip mask_mod
|
| 182 |
+
has_full_blocks = full_kv_num_blocks is not None
|
| 183 |
+
kernel_options.setdefault("HAS_FULL_BLOCKS", has_full_blocks)
|
| 184 |
+
if not has_full_blocks:
|
| 185 |
+
# Create a plackeholder full block list in case it is empty
|
| 186 |
+
full_kv_num_blocks, full_kv_indices = (
|
| 187 |
+
empty(0, device=query.get_device()) for _ in range(2)
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
(
|
| 191 |
+
query,
|
| 192 |
+
key,
|
| 193 |
+
value,
|
| 194 |
+
kv_num_blocks,
|
| 195 |
+
kv_indices,
|
| 196 |
+
full_kv_num_blocks,
|
| 197 |
+
full_kv_indices,
|
| 198 |
+
) = maybe_realize(
|
| 199 |
+
[
|
| 200 |
+
query,
|
| 201 |
+
key,
|
| 202 |
+
value,
|
| 203 |
+
kv_num_blocks,
|
| 204 |
+
kv_indices,
|
| 205 |
+
full_kv_num_blocks,
|
| 206 |
+
full_kv_indices,
|
| 207 |
+
]
|
| 208 |
+
)
|
| 209 |
+
score_mod_other_buffers = maybe_realize(score_mod_other_buffers)
|
| 210 |
+
mask_mod_other_buffers = maybe_realize(mask_mod_other_buffers)
|
| 211 |
+
|
| 212 |
+
freeze_irnodes(score_mod_other_buffers)
|
| 213 |
+
freeze_irnodes(mask_mod_other_buffers)
|
| 214 |
+
|
| 215 |
+
choices: list[Any] = []
|
| 216 |
+
dtype = key.get_dtype()
|
| 217 |
+
head_dim = V.graph.sizevars.guard_int(key.get_size()[-1])
|
| 218 |
+
configs = V.choices.get_flex_decode_configs(
|
| 219 |
+
head_dim, dtype, query.get_device().type
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
# TODO: fix autotuning.
|
| 223 |
+
|
| 224 |
+
kernel_options.setdefault("SM_SCALE", scale)
|
| 225 |
+
kernel_options.setdefault("SPLIT_KV", get_split_k(B, Hkv, seq_len_kv))
|
| 226 |
+
MAX_SPLIT_KV = kernel_options["SPLIT_KV"]
|
| 227 |
+
|
| 228 |
+
# create config dependent intermediate buffers
|
| 229 |
+
buf_ACC_shape = [B, MAX_SPLIT_KV, Hq, seq_len_q, v_head_dim]
|
| 230 |
+
buf_ML_shape = buf_ACC_shape[:-1]
|
| 231 |
+
buf_M = empty_strided(
|
| 232 |
+
buf_ML_shape,
|
| 233 |
+
None,
|
| 234 |
+
dtype=torch.float32, # The rowmax is always stored in fp32 regardless of the input dtype
|
| 235 |
+
device=query.get_device(),
|
| 236 |
+
)
|
| 237 |
+
buf_L = empty_strided(
|
| 238 |
+
buf_ML_shape,
|
| 239 |
+
None,
|
| 240 |
+
dtype=torch.float32, # The intermediate sumexp is always stored in fp32 regardless of the input dtype
|
| 241 |
+
device=query.get_device(),
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
layout_acc = FixedLayout(
|
| 245 |
+
query.get_device(),
|
| 246 |
+
torch.float32,
|
| 247 |
+
buf_ACC_shape,
|
| 248 |
+
FlexibleLayout.contiguous_strides(buf_ACC_shape),
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
set_head_dim_values(kernel_options, qk_head_dim, v_head_dim, V.graph.sizevars)
|
| 252 |
+
|
| 253 |
+
kernel_options.setdefault(
|
| 254 |
+
"BLOCK_M",
|
| 255 |
+
(
|
| 256 |
+
# m
|
| 257 |
+
# if V.graph.sizevars.evaluate_expr(sympy.Lt(query.get_size()[-2], 0))
|
| 258 |
+
# else # Always use a BLOCK_M > 16 before Triton fix https://github.com/triton-lang/triton/pull/4061 is in pin
|
| 259 |
+
max(
|
| 260 |
+
next_power_of_2(
|
| 261 |
+
V.graph.sizevars.size_hint(
|
| 262 |
+
seq_len_q,
|
| 263 |
+
fallback=torch._inductor.config.unbacked_symint_fallback, # type: ignore[arg-type]
|
| 264 |
+
)
|
| 265 |
+
* gqa_shared_heads
|
| 266 |
+
),
|
| 267 |
+
1 if torch.xpu.is_available() else 16,
|
| 268 |
+
)
|
| 269 |
+
),
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
query = ir.ExternKernel.realize_input(query)
|
| 273 |
+
stride_b, stride_hq, stride_seq_len_q, stride_qk_head_dim = query.get_stride()
|
| 274 |
+
|
| 275 |
+
# Reshape query for GQA: [B, Hq, Mq, D] -> [B, Hkv, G, Mq, D]
|
| 276 |
+
gqa_query_shape = (B, Hkv, gqa_shared_heads, seq_len_q, qk_head_dim)
|
| 277 |
+
gqa_query_stride = (
|
| 278 |
+
stride_b,
|
| 279 |
+
stride_hq * gqa_shared_heads,
|
| 280 |
+
stride_hq,
|
| 281 |
+
stride_seq_len_q,
|
| 282 |
+
stride_qk_head_dim,
|
| 283 |
+
)
|
| 284 |
+
query = lowerings[aten.as_strided](query, gqa_query_shape, gqa_query_stride)
|
| 285 |
+
|
| 286 |
+
V.graph.sizevars.check_leq(
|
| 287 |
+
seq_len_q * gqa_shared_heads, sympy.Integer(kernel_options["BLOCK_M"])
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
kernel_options.setdefault(
|
| 291 |
+
"SAFE_M_BOUNDARY",
|
| 292 |
+
((seq_len_q * gqa_shared_heads) % kernel_options["BLOCK_M"]) == 0,
|
| 293 |
+
)
|
| 294 |
+
# TODO: This feels sketchy
|
| 295 |
+
kernel_options.setdefault("SAFE_N_BOUNDARY", True)
|
| 296 |
+
# Mark SPARSE_KV_BLOCK_SIZE as static shapes and add guards.
|
| 297 |
+
SPARSE_KV_BLOCK_SIZE = V.graph.sizevars.guard_int(SPARSE_KV_BLOCK_SIZE)
|
| 298 |
+
|
| 299 |
+
original_kernel_options = kernel_options.copy()
|
| 300 |
+
# Note, we don't need to pass in the captured buffers explicitly
|
| 301 |
+
# because they're implicitly added by the score_mod function
|
| 302 |
+
# We do need to explicitly pass it in for autotuning though.
|
| 303 |
+
|
| 304 |
+
# Default config for warp specialization
|
| 305 |
+
num_consumer_groups, num_buffers_warp_spec = 0, 0
|
| 306 |
+
|
| 307 |
+
for conf in configs:
|
| 308 |
+
if SPARSE_KV_BLOCK_SIZE % conf.block_n != 0:
|
| 309 |
+
continue
|
| 310 |
+
|
| 311 |
+
cur_kernel_options = original_kernel_options.copy()
|
| 312 |
+
# Remove prefix for forward kernels options and delete backward kernel options.
|
| 313 |
+
for k in list(cur_kernel_options.keys()):
|
| 314 |
+
if k.startswith("fwd_"):
|
| 315 |
+
v = cur_kernel_options.pop(k)
|
| 316 |
+
cur_kernel_options[k[4:]] = v
|
| 317 |
+
if k.startswith("bwd_"):
|
| 318 |
+
cur_kernel_options.pop(k)
|
| 319 |
+
# Performance tuning
|
| 320 |
+
cur_kernel_options.setdefault("BLOCK_N", conf.block_n)
|
| 321 |
+
cur_kernel_options.setdefault("SPARSE_KV_BLOCK_SIZE", SPARSE_KV_BLOCK_SIZE)
|
| 322 |
+
cur_kernel_options.setdefault("num_warps", conf.num_warps)
|
| 323 |
+
cur_kernel_options.setdefault("num_stages", conf.num_stages)
|
| 324 |
+
|
| 325 |
+
if cur_kernel_options.get("num_consumer_groups", False):
|
| 326 |
+
cur_kernel_options.setdefault("num_consumer_groups", num_consumer_groups)
|
| 327 |
+
cur_kernel_options.setdefault(
|
| 328 |
+
"num_buffers_warp_spec", num_buffers_warp_spec
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
# Set default to False
|
| 332 |
+
cur_kernel_options.setdefault("USE_TMA", False)
|
| 333 |
+
|
| 334 |
+
# Add ROCm-specific parameters if they exist in the config
|
| 335 |
+
for attrib in ["kpack", "matrix_instr_nonkdim", "waves_per_eu"]:
|
| 336 |
+
if hasattr(conf, attrib):
|
| 337 |
+
cur_kernel_options[attrib] = getattr(conf, attrib)
|
| 338 |
+
|
| 339 |
+
flex_decoding_template.maybe_append_choice(
|
| 340 |
+
choices=choices,
|
| 341 |
+
input_nodes=[
|
| 342 |
+
query,
|
| 343 |
+
key,
|
| 344 |
+
value,
|
| 345 |
+
buf_M,
|
| 346 |
+
buf_L,
|
| 347 |
+
kv_num_blocks,
|
| 348 |
+
kv_indices,
|
| 349 |
+
full_kv_num_blocks,
|
| 350 |
+
full_kv_indices,
|
| 351 |
+
],
|
| 352 |
+
layout=layout_acc,
|
| 353 |
+
subgraphs=[
|
| 354 |
+
score_mod_subgraph,
|
| 355 |
+
mask_mod_subgraph,
|
| 356 |
+
],
|
| 357 |
+
mutated_inputs=[buf_M, buf_L],
|
| 358 |
+
call_sizes=query.get_size(),
|
| 359 |
+
**cur_kernel_options,
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
filtered_score_mod_buffers = [
|
| 363 |
+
buf for buf in score_mod_other_buffers if not isinstance(buf, sympy.Symbol)
|
| 364 |
+
]
|
| 365 |
+
filtered_mask_mod_buffers = [
|
| 366 |
+
buf for buf in mask_mod_other_buffers if not isinstance(buf, sympy.Symbol)
|
| 367 |
+
]
|
| 368 |
+
|
| 369 |
+
inputs_for_flex_decoding = (
|
| 370 |
+
# pyrefly: ignore [unsupported-operation]
|
| 371 |
+
[
|
| 372 |
+
query,
|
| 373 |
+
key,
|
| 374 |
+
value,
|
| 375 |
+
buf_M,
|
| 376 |
+
buf_L,
|
| 377 |
+
kv_num_blocks,
|
| 378 |
+
kv_indices,
|
| 379 |
+
full_kv_num_blocks,
|
| 380 |
+
full_kv_indices,
|
| 381 |
+
]
|
| 382 |
+
+ filtered_score_mod_buffers
|
| 383 |
+
+ filtered_mask_mod_buffers
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
input_gen_fns = {
|
| 387 |
+
5: create_num_blocks_fake_generator(kv_indices),
|
| 388 |
+
6: create_indices_fake,
|
| 389 |
+
7: create_num_blocks_fake_generator(full_kv_indices),
|
| 390 |
+
8: create_indices_fake,
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
buf_ACC = autotune_select_algorithm(
|
| 394 |
+
"flex_decoding",
|
| 395 |
+
choices,
|
| 396 |
+
inputs_for_flex_decoding,
|
| 397 |
+
layout_acc,
|
| 398 |
+
input_gen_fns=input_gen_fns,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# need subgraph inputs and outputs to analyze all symints used in flex attention
|
| 402 |
+
buf_ACC.data.data.subgraph_inps = list(score_mod_other_buffers) + list(
|
| 403 |
+
mask_mod_other_buffers
|
| 404 |
+
)
|
| 405 |
+
buf_ACC.data.data.subgraph_outs = get_fwd_subgraph_outputs(
|
| 406 |
+
score_mod_subgraph, mask_mod_subgraph
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
# Reduction
|
| 410 |
+
|
| 411 |
+
g_M = lowerings[aten.max](buf_M, dim=1, keepdim=True)[0]
|
| 412 |
+
# See [Note] Handle fully masked out rows:
|
| 413 |
+
# g_M Is the global max among split kv blocks.
|
| 414 |
+
masked_rows = lowerings[aten.eq](g_M, -float("inf"))
|
| 415 |
+
adj_M = lowerings[aten.sub](buf_M, g_M)
|
| 416 |
+
adj_M = lowerings[aten.where](masked_rows, 0, adj_M)
|
| 417 |
+
alpha = lowerings[aten.exp2](adj_M)
|
| 418 |
+
|
| 419 |
+
buf_L = lowerings[aten.mul](buf_L, alpha)
|
| 420 |
+
g_L = lowerings[aten.sum](buf_L, axis=1)
|
| 421 |
+
masked_rows_squeezed = lowerings[aten.squeeze](masked_rows, dim=1)
|
| 422 |
+
g_L = lowerings[aten.where](masked_rows_squeezed, 1.0, g_L)
|
| 423 |
+
logsumexp = lowerings[aten.log2](g_L)
|
| 424 |
+
logsumexp = lowerings[aten.add](logsumexp, lowerings[aten.squeeze](g_M, dim=1))
|
| 425 |
+
|
| 426 |
+
alpha_unseq = lowerings[aten.unsqueeze](alpha, 4)
|
| 427 |
+
buf_ACC = lowerings[aten.mul](buf_ACC, alpha_unseq)
|
| 428 |
+
output = lowerings[aten.sum](buf_ACC, axis=1)
|
| 429 |
+
L_unseq = lowerings[aten.unsqueeze](g_L, 3)
|
| 430 |
+
output = lowerings[aten.div](output, L_unseq)
|
| 431 |
+
output = lowerings[prims.convert_element_type](output, query.get_dtype())
|
| 432 |
+
|
| 433 |
+
return (
|
| 434 |
+
output,
|
| 435 |
+
logsumexp,
|
| 436 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/flex_flash_attention.py
ADDED
|
@@ -0,0 +1,491 @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equence
|
| 7 |
+
from contextlib import contextmanager
|
| 8 |
+
from typing import Any, Literal, Optional
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
from sympy import Expr, Integer
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch.fx import GraphModule
|
| 15 |
+
from torch.utils._sympy.functions import Identity
|
| 16 |
+
|
| 17 |
+
from ...ir import FixedLayout, ShapeAsConstantBuffer, Subgraph, TensorBox
|
| 18 |
+
from ...lowering import empty_strided
|
| 19 |
+
from .common import infer_dense_strides, load_flex_template, SubgraphResults
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
aten = torch.ops.aten
|
| 23 |
+
prims = torch.ops.prims
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@functools.lru_cache(maxsize=1)
|
| 27 |
+
def ensure_flash_available() -> bool:
|
| 28 |
+
"""Check if flash-attn is importable; cache the result for reuse.
|
| 29 |
+
|
| 30 |
+
Call ensure_flash_available.cache_clear() after installing flash-attn
|
| 31 |
+
in the same interpreter to retry the import.
|
| 32 |
+
"""
|
| 33 |
+
try:
|
| 34 |
+
return importlib.util.find_spec("flash_attn.cute") is not None # type: ignore[attr-defined]
|
| 35 |
+
except ImportError:
|
| 36 |
+
return False
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
from ...codegen.cutedsl.cutedsl_template import CuteDSLTemplate
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
flash_attention_cutedsl_template = CuteDSLTemplate(
|
| 43 |
+
name="flash_attention_cutedsl", source=load_flex_template("flash_attention")
|
| 44 |
+
)
|
| 45 |
+
flash_attention_backward_cutedsl_template = CuteDSLTemplate(
|
| 46 |
+
name="flash_attention_backward_cutedsl",
|
| 47 |
+
source=load_flex_template("flash_attention_backward"),
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _fixed_indexer_cute(
|
| 52 |
+
size: Sequence[int],
|
| 53 |
+
stride: Optional[Sequence[int]] = None,
|
| 54 |
+
offset: Expr = Integer(0),
|
| 55 |
+
) -> Callable[[Sequence[Expr]], Expr]:
|
| 56 |
+
"""
|
| 57 |
+
Colexicographic indexer for CuteDSL - matches CuTe's coordinate interpretation.
|
| 58 |
+
|
| 59 |
+
CuTe interprets linear indices in colexicographic (column-major) order,
|
| 60 |
+
whereas Inductor's default _fixed_indexer uses lexicographic (row-major) order.
|
| 61 |
+
|
| 62 |
+
For size=[4, 128] with index=[b, q_idx]:
|
| 63 |
+
- Lexicographic: b*128 + q_idx*1
|
| 64 |
+
- Colexicographic: b*1 + q_idx*2
|
| 65 |
+
|
| 66 |
+
CuTe then applies the tensor's actual memory strides to get the correct offset.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def indexer(index: Sequence[Expr]) -> Expr:
|
| 70 |
+
assert offset == Integer(0), "Offset not supported for colexicographic indexing"
|
| 71 |
+
if not index:
|
| 72 |
+
return Integer(0)
|
| 73 |
+
|
| 74 |
+
result = index[0]
|
| 75 |
+
runner = size[0]
|
| 76 |
+
|
| 77 |
+
for idx, sz in zip(index[1:], size[1:], strict=True):
|
| 78 |
+
result = result + runner * Identity(idx)
|
| 79 |
+
runner = runner * sz
|
| 80 |
+
|
| 81 |
+
return result
|
| 82 |
+
|
| 83 |
+
return indexer
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@contextmanager
|
| 87 |
+
def patch_fixed_layout_indexer_for_cutedsl():
|
| 88 |
+
"""
|
| 89 |
+
Temporarily swap FixedLayout.make_indexer so CuteDSL sees colexicographic indexing.
|
| 90 |
+
|
| 91 |
+
Note [CuteDSL indexer patch]:
|
| 92 |
+
Flex flash attention only supports a limited set of IR ops (pointwise, reads, no stores),
|
| 93 |
+
so temporarily changing the indexing order is safe for the kernels we emit today.
|
| 94 |
+
TODO(dynamic shapes): Reconfirm once flex flash attention supports dynamic shapes.
|
| 95 |
+
"""
|
| 96 |
+
original_make_indexer = FixedLayout.make_indexer
|
| 97 |
+
|
| 98 |
+
def cutedsl_make_indexer(self):
|
| 99 |
+
return _fixed_indexer_cute(self.size, self.stride, self.offset)
|
| 100 |
+
|
| 101 |
+
FixedLayout.make_indexer = cutedsl_make_indexer # type: ignore[assignment]
|
| 102 |
+
try:
|
| 103 |
+
yield
|
| 104 |
+
finally:
|
| 105 |
+
FixedLayout.make_indexer = original_make_indexer # type: ignore[assignment]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def wrap_choice_render_with_cutedsl_indexer(choice: Any) -> None:
|
| 109 |
+
"""
|
| 110 |
+
Wrap a template choice's kernel render to apply CuteDSL indexer patching.
|
| 111 |
+
|
| 112 |
+
See Note [CuteDSL indexer patch]:
|
| 113 |
+
This wrapper allows the template to construct its closures normally, then
|
| 114 |
+
scopes the indexer patch to the actual render call that emits the kernel.
|
| 115 |
+
This ensures CuteDSL templates see colexicographic indexing while preserving
|
| 116 |
+
the template's setup logic.
|
| 117 |
+
"""
|
| 118 |
+
original_make_kernel_render = choice.make_kernel_render
|
| 119 |
+
|
| 120 |
+
def make_kernel_render_with_patch(*args, **kwargs):
|
| 121 |
+
render_kernel, render = original_make_kernel_render(*args, **kwargs)
|
| 122 |
+
# Let the template construct its closures, then scope the indexer patch
|
| 123 |
+
# to the actual render call that emits the kernel
|
| 124 |
+
render_with_patch = patch_fixed_layout_indexer_for_cutedsl()(render)
|
| 125 |
+
return render_kernel, render_with_patch
|
| 126 |
+
|
| 127 |
+
choice.make_kernel_render = make_kernel_render_with_patch
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def input_buffers_require_grads(graph_module, num_score_mod_placeholders: int):
|
| 131 |
+
"""Check if any of the input buffers (beyond the score mod placeholders) require gradients."""
|
| 132 |
+
inputs = []
|
| 133 |
+
for node in graph_module.graph.nodes:
|
| 134 |
+
if node.op == "placeholder":
|
| 135 |
+
inputs.append(node)
|
| 136 |
+
if len(inputs) <= num_score_mod_placeholders:
|
| 137 |
+
return False
|
| 138 |
+
|
| 139 |
+
def requires_grad(n):
|
| 140 |
+
tensor_meta = n.meta.get("tensor_meta")
|
| 141 |
+
return tensor_meta.requires_grad if tensor_meta is not None else False
|
| 142 |
+
|
| 143 |
+
return any(requires_grad(n) for n in inputs[num_score_mod_placeholders:])
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def is_trivial_score_graph(graph_module: GraphModule) -> bool:
|
| 147 |
+
"""Backwards currently doesn't support score_mods, match against identity"""
|
| 148 |
+
graph = graph_module.graph
|
| 149 |
+
nodes = list(graph.nodes)
|
| 150 |
+
placeholders = [n for n in nodes if n.op == "placeholder"]
|
| 151 |
+
output = [n for n in nodes if n.op == "output"]
|
| 152 |
+
assert len(output) == 1, "Got graph w/ multiple outputs"
|
| 153 |
+
output_val = output[0].args[0]
|
| 154 |
+
# The identity graph just sends the score straight through
|
| 155 |
+
return output_val == placeholders[0]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def is_trivial_mask_graph(graph_module: GraphModule) -> bool:
|
| 159 |
+
"""Mask graph is trivial when it only gates via the default full op."""
|
| 160 |
+
graph = graph_module.graph
|
| 161 |
+
nodes = list(graph.nodes)
|
| 162 |
+
placeholders = [n for n in nodes if n.op == "placeholder"]
|
| 163 |
+
output = [n for n in nodes if n.op == "output"]
|
| 164 |
+
assert len(output) == 1, "Got graph w/ multiple outputs"
|
| 165 |
+
output_val = output[0].args[0]
|
| 166 |
+
|
| 167 |
+
# mask mod graph is empty if we have 4 inputs and full_default output
|
| 168 |
+
return len(placeholders) == 4 and output_val.target is torch.ops.aten.full.default
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@functools.lru_cache(maxsize=1)
|
| 172 |
+
def _supports_nontrivial_mask_graphs() -> bool:
|
| 173 |
+
"""Currently only supported on Hopper (SM90) GPUs."""
|
| 174 |
+
return torch.cuda.get_device_capability()[0] in [9, 10]
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _can_use_flex_flash_attention(
|
| 178 |
+
subgraph: Subgraph, mask_graph: Subgraph, num_score_mod_placeholders: int
|
| 179 |
+
) -> tuple[bool, str]:
|
| 180 |
+
"""Check if flex flash attention can be used for the given inputs.
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
tuple: (can_use, reason) where reason explains why it can't be used if can_use is False
|
| 184 |
+
"""
|
| 185 |
+
if not ensure_flash_available():
|
| 186 |
+
return False, "CUTE flash attention library is not available"
|
| 187 |
+
|
| 188 |
+
if input_buffers_require_grads(subgraph.graph_module, num_score_mod_placeholders):
|
| 189 |
+
return (
|
| 190 |
+
False,
|
| 191 |
+
"Input buffers require gradients (not supported by flash attention)",
|
| 192 |
+
)
|
| 193 |
+
mask_trivial = is_trivial_mask_graph(mask_graph.graph_module)
|
| 194 |
+
|
| 195 |
+
if mask_trivial:
|
| 196 |
+
return True, ""
|
| 197 |
+
|
| 198 |
+
if not _supports_nontrivial_mask_graphs():
|
| 199 |
+
return (
|
| 200 |
+
False,
|
| 201 |
+
"NYI: Non-trivial mask graphs only supported on Hopper (SM90) for flash attention",
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
return True, ""
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _use_flex_flash_attention(
|
| 208 |
+
subgraph: Subgraph,
|
| 209 |
+
mask_graph: Subgraph,
|
| 210 |
+
kernel_options: dict[str, Any],
|
| 211 |
+
num_score_mod_placeholders: int,
|
| 212 |
+
backend: Literal["AUTO", "TRITON", "FLASH", "TRITON_DECODE"],
|
| 213 |
+
) -> bool:
|
| 214 |
+
"""Determine if we should use flex flash attention for the given inputs.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
subgraph: The score modification subgraph
|
| 218 |
+
mask_graph: The mask modification subgraph
|
| 219 |
+
kernel_options: Kernel configuration options
|
| 220 |
+
num_score_mod_placeholders: Number of placeholders in score_mod
|
| 221 |
+
backend: Implementation selector (AUTO, TRITON, FLASH, TRITON_DECODE)
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
True if flash attention should be used, False otherwise
|
| 225 |
+
"""
|
| 226 |
+
# Flash is experimental and must be explicitly requested
|
| 227 |
+
if backend != "FLASH":
|
| 228 |
+
return False
|
| 229 |
+
|
| 230 |
+
can_use, reason = _can_use_flex_flash_attention(
|
| 231 |
+
subgraph, mask_graph, num_score_mod_placeholders
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
if not can_use:
|
| 235 |
+
raise RuntimeError(
|
| 236 |
+
f"BACKEND='FLASH' but flash attention cannot be used: {reason}"
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
return True
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def create_flex_flash_attention_kernel(
|
| 243 |
+
query: TensorBox,
|
| 244 |
+
key: TensorBox,
|
| 245 |
+
value: TensorBox,
|
| 246 |
+
block_mask: tuple[Any, ...],
|
| 247 |
+
scale: float,
|
| 248 |
+
kernel_options: dict[str, Any],
|
| 249 |
+
subgraph_buffer: SubgraphResults,
|
| 250 |
+
mask_graph_buffer: SubgraphResults,
|
| 251 |
+
score_mod_other_buffers: list[TensorBox],
|
| 252 |
+
mask_mod_other_buffers: list[TensorBox],
|
| 253 |
+
kv_num_blocks: TensorBox | None,
|
| 254 |
+
kv_indices: TensorBox | None,
|
| 255 |
+
full_kv_num_blocks: TensorBox | None,
|
| 256 |
+
full_kv_indices: TensorBox | None,
|
| 257 |
+
mask_graph: Subgraph,
|
| 258 |
+
subgraph: Subgraph | None = None,
|
| 259 |
+
) -> tuple[TensorBox | ShapeAsConstantBuffer, TensorBox | ShapeAsConstantBuffer]:
|
| 260 |
+
"""Create a flex flash attention kernel using CuteDSL template."""
|
| 261 |
+
if not ensure_flash_available():
|
| 262 |
+
raise RuntimeError("CUTE flash attention not available")
|
| 263 |
+
|
| 264 |
+
# Get dimensions
|
| 265 |
+
batch_size, num_heads, seq_len_q, head_dim = query.get_size()
|
| 266 |
+
v_head_dim = value.get_size()[-1]
|
| 267 |
+
device = query.get_device()
|
| 268 |
+
dtype = query.get_dtype()
|
| 269 |
+
assert device is not None, "Device must be specified"
|
| 270 |
+
|
| 271 |
+
# Match stride pattern from query tensor
|
| 272 |
+
q_strides = query.get_stride()
|
| 273 |
+
out_size = [batch_size, num_heads, seq_len_q, v_head_dim]
|
| 274 |
+
out_strides = infer_dense_strides(out_size, q_strides)
|
| 275 |
+
|
| 276 |
+
output = empty_strided(
|
| 277 |
+
size=out_size,
|
| 278 |
+
stride=out_strides,
|
| 279 |
+
dtype=dtype,
|
| 280 |
+
device=device,
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
lse = empty_strided(
|
| 284 |
+
size=[batch_size, num_heads, seq_len_q],
|
| 285 |
+
stride=None, # LSE can be contiguous
|
| 286 |
+
dtype=torch.float32, # LSE is always fp32
|
| 287 |
+
device=device,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
# Create layout for primary output
|
| 291 |
+
output_layout = FixedLayout(
|
| 292 |
+
device=device,
|
| 293 |
+
dtype=dtype,
|
| 294 |
+
size=[batch_size, num_heads, seq_len_q, v_head_dim],
|
| 295 |
+
stride=[sympy.sympify(s) for s in output.get_stride()],
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
# Used to check if we can skip block sparse impl
|
| 299 |
+
mask_graph_is_trivial = is_trivial_mask_graph(mask_graph.graph_module)
|
| 300 |
+
|
| 301 |
+
needs_block_mask = not mask_graph_is_trivial
|
| 302 |
+
has_full_blocks = full_kv_num_blocks is not None
|
| 303 |
+
|
| 304 |
+
choices: list[Any] = []
|
| 305 |
+
assert flash_attention_cutedsl_template is not None
|
| 306 |
+
|
| 307 |
+
input_nodes = [query, key, value, lse]
|
| 308 |
+
if has_full_blocks:
|
| 309 |
+
input_nodes.extend(
|
| 310 |
+
[kv_num_blocks, kv_indices, full_kv_num_blocks, full_kv_indices]
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
if needs_block_mask and not has_full_blocks:
|
| 314 |
+
raise NotImplementedError(
|
| 315 |
+
"Flash attention with block mask but without full blocks is not supported yet"
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
error = flash_attention_cutedsl_template.maybe_append_choice(
|
| 319 |
+
choices,
|
| 320 |
+
input_nodes=input_nodes,
|
| 321 |
+
layout=output_layout,
|
| 322 |
+
mutated_inputs=[lse],
|
| 323 |
+
subgraphs=[subgraph_buffer, mask_graph_buffer],
|
| 324 |
+
SM_SCALE=scale,
|
| 325 |
+
NEEDS_BLOCK_MASK=needs_block_mask,
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
for choice in choices:
|
| 329 |
+
wrap_choice_render_with_cutedsl_indexer(choice)
|
| 330 |
+
|
| 331 |
+
if error or not choices:
|
| 332 |
+
# Fallback to original implementation
|
| 333 |
+
raise RuntimeError(f"CuteDSL template failed: {error}")
|
| 334 |
+
|
| 335 |
+
# No autotune for now
|
| 336 |
+
template_output = choices[0].output_node()
|
| 337 |
+
|
| 338 |
+
return (template_output, lse)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _can_use_flex_flash_attention_backward(
|
| 342 |
+
fw_subgraph: Subgraph,
|
| 343 |
+
mask_graph: Subgraph,
|
| 344 |
+
) -> tuple[bool, str]:
|
| 345 |
+
if not ensure_flash_available():
|
| 346 |
+
return False, "CUTE flash attention is not available"
|
| 347 |
+
|
| 348 |
+
if not is_trivial_score_graph(fw_subgraph.graph_module):
|
| 349 |
+
return (
|
| 350 |
+
False,
|
| 351 |
+
"NYI: Flex Flash Attention doesn't support score_mods in bwds yet.",
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
if not is_trivial_mask_graph(mask_graph.graph_module):
|
| 355 |
+
return False, "NYI: Flex Flash Attention doesn't support block_sparsity yet."
|
| 356 |
+
|
| 357 |
+
return True, ""
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def _use_flex_flash_attention_backward(
|
| 361 |
+
fw_subgraph: Subgraph,
|
| 362 |
+
mask_graph: Subgraph,
|
| 363 |
+
backend: Literal["AUTO", "TRITON", "FLASH", "TRITON_DECODE"],
|
| 364 |
+
) -> bool:
|
| 365 |
+
"""Determine if we should use flex flash attention for the given inputs.
|
| 366 |
+
|
| 367 |
+
Args:
|
| 368 |
+
subgraph: The score modification subgraph
|
| 369 |
+
mask_graph: The mask modification subgraph
|
| 370 |
+
kernel_options: Kernel configuration options
|
| 371 |
+
num_score_mod_placeholders: Number of placeholders in score_mod
|
| 372 |
+
backend: Implementation selector (AUTO, TRITON, FLASH, TRITON_DECODE)
|
| 373 |
+
|
| 374 |
+
Returns:
|
| 375 |
+
True if flash attention should be used, False otherwise
|
| 376 |
+
"""
|
| 377 |
+
# Flash is experimental and must be explicitly requested
|
| 378 |
+
if backend != "FLASH":
|
| 379 |
+
return False
|
| 380 |
+
|
| 381 |
+
can_use, reason = _can_use_flex_flash_attention_backward(
|
| 382 |
+
fw_subgraph,
|
| 383 |
+
mask_graph,
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
if not can_use:
|
| 387 |
+
raise RuntimeError(
|
| 388 |
+
f"BACKEND='FLASH' but flash attention cannot be used: {reason}"
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
return True
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def create_flex_flash_attention_backward_kernel(
|
| 395 |
+
query: TensorBox,
|
| 396 |
+
key: TensorBox,
|
| 397 |
+
value: TensorBox,
|
| 398 |
+
out: TensorBox,
|
| 399 |
+
logsumexp: TensorBox,
|
| 400 |
+
grad_out: TensorBox,
|
| 401 |
+
scale: float,
|
| 402 |
+
kernel_options: dict[str, Any],
|
| 403 |
+
# TODO: will be needed
|
| 404 |
+
# grad_logsumexp,
|
| 405 |
+
# fw_graph: SubgraphResults,
|
| 406 |
+
# joint_graph: SubgraphResults,
|
| 407 |
+
# mask_graph: SubgraphResults,
|
| 408 |
+
# score_mod_other_buffers: list[TensorBox],
|
| 409 |
+
# mask_mod_other_buffers: list[TensorBox],
|
| 410 |
+
# kv_num_blocks: TensorBox | None,
|
| 411 |
+
# kv_indices: TensorBox | None,
|
| 412 |
+
# full_kv_num_blocks: TensorBox | None,
|
| 413 |
+
# full_kv_indices: TensorBox | None,
|
| 414 |
+
) -> tuple[TensorBox | ShapeAsConstantBuffer, TensorBox, TensorBox, tuple]:
|
| 415 |
+
"""Create a CuteDSL flash attention backward kernel for the default mod path."""
|
| 416 |
+
if not ensure_flash_available():
|
| 417 |
+
raise RuntimeError("CUTE flash attention not available")
|
| 418 |
+
|
| 419 |
+
batch_size, num_heads, seq_len_q, head_dim = query.get_size()
|
| 420 |
+
v_head_dim = value.get_size()[-1]
|
| 421 |
+
device = query.get_device()
|
| 422 |
+
dtype = query.get_dtype()
|
| 423 |
+
assert device is not None
|
| 424 |
+
|
| 425 |
+
grad_query_strides = infer_dense_strides(
|
| 426 |
+
[batch_size, num_heads, seq_len_q, head_dim], query.get_stride()
|
| 427 |
+
)
|
| 428 |
+
grad_query = empty_strided(
|
| 429 |
+
size=[batch_size, num_heads, seq_len_q, head_dim],
|
| 430 |
+
stride=grad_query_strides,
|
| 431 |
+
dtype=dtype,
|
| 432 |
+
device=device,
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
grad_key_strides = infer_dense_strides(
|
| 436 |
+
[batch_size, num_heads, value.get_size()[2], head_dim], key.get_stride()
|
| 437 |
+
)
|
| 438 |
+
grad_key = empty_strided(
|
| 439 |
+
size=[batch_size, num_heads, value.get_size()[2], head_dim],
|
| 440 |
+
stride=grad_key_strides,
|
| 441 |
+
dtype=dtype,
|
| 442 |
+
device=device,
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
grad_value_strides = infer_dense_strides(
|
| 446 |
+
[batch_size, num_heads, value.get_size()[2], v_head_dim], value.get_stride()
|
| 447 |
+
)
|
| 448 |
+
grad_value = empty_strided(
|
| 449 |
+
size=[batch_size, num_heads, value.get_size()[2], v_head_dim],
|
| 450 |
+
stride=grad_value_strides,
|
| 451 |
+
dtype=dtype,
|
| 452 |
+
device=device,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
output_layout = FixedLayout(
|
| 456 |
+
device=device,
|
| 457 |
+
dtype=dtype,
|
| 458 |
+
size=[batch_size, num_heads, seq_len_q, head_dim],
|
| 459 |
+
stride=[sympy.sympify(s) for s in grad_query.get_stride()],
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
choices: list[Any] = []
|
| 463 |
+
|
| 464 |
+
input_nodes = [
|
| 465 |
+
query,
|
| 466 |
+
key,
|
| 467 |
+
value,
|
| 468 |
+
out,
|
| 469 |
+
grad_out,
|
| 470 |
+
logsumexp,
|
| 471 |
+
grad_key,
|
| 472 |
+
grad_value,
|
| 473 |
+
]
|
| 474 |
+
|
| 475 |
+
error = flash_attention_backward_cutedsl_template.maybe_append_choice(
|
| 476 |
+
choices,
|
| 477 |
+
input_nodes=input_nodes,
|
| 478 |
+
layout=output_layout,
|
| 479 |
+
mutated_inputs=[grad_key, grad_value],
|
| 480 |
+
SM_SCALE=scale,
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
for choice in choices:
|
| 484 |
+
wrap_choice_render_with_cutedsl_indexer(choice)
|
| 485 |
+
|
| 486 |
+
if error or not choices:
|
| 487 |
+
raise RuntimeError(f"CuteDSL template failed: {error}")
|
| 488 |
+
|
| 489 |
+
template_output = choices[0].output_node()
|
| 490 |
+
|
| 491 |
+
return (template_output, grad_key, grad_value, tuple())
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/common.py.jinja
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
{{gen_argdefs()}},
|
| 7 |
+
q, K, V, desc_k, desc_v, Q_LEN, KV_LEN,
|
| 8 |
+
# accumulated values
|
| 9 |
+
acc, l_i, m_i,
|
| 10 |
+
# Offsets
|
| 11 |
+
off_z, off_h, offs_m, offs_n,
|
| 12 |
+
# Offsets needed for TMA loads
|
| 13 |
+
kv_start,
|
| 14 |
+
kv_offset,
|
| 15 |
+
MATMUL_PRECISION, RCP_LN2,
|
| 16 |
+
# Strides for K and V
|
| 17 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 18 |
+
IS_FULL_BLOCKS, CHECK_BLOCK_BOUNDARY=False,
|
| 19 |
+
|
| 20 |
+
):
|
| 21 |
+
# Redefines all kernel parameters (BLOCK_M, etc.) so we don't need to plumb them all through
|
| 22 |
+
{{gen_defines() | indent_except_first(1)}}
|
| 23 |
+
|
| 24 |
+
# -- load k --
|
| 25 |
+
# NB reversed order to since K is transposed
|
| 26 |
+
kv_base_offset = kv_start + kv_offset
|
| 27 |
+
{%- if USE_TMA %}
|
| 28 |
+
k = tl.load_tensor_descriptor(
|
| 29 |
+
desc_k,
|
| 30 |
+
[kv_base_offset, 0],
|
| 31 |
+
)
|
| 32 |
+
{%- else %}
|
| 33 |
+
|
| 34 |
+
# Load K as [BLOCK_N, QK_HEAD_DIM_ROUNDED] then transpose to [QK_HEAD_DIM_ROUNDED, BLOCK_N]
|
| 35 |
+
offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED)
|
| 36 |
+
offs_n_load = kv_base_offset + tl.arange(0, BLOCK_N)
|
| 37 |
+
k = load_checked_2d(K, offs_n_load, offs_k, stride_kn, stride_kk, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, QK_HEAD_DIM)
|
| 38 |
+
{%- endif %}
|
| 39 |
+
|
| 40 |
+
k = tl.trans(k)
|
| 41 |
+
# -- compute qk ---
|
| 42 |
+
qk = tl.dot(q, k, input_precision=FLOAT32_PRECISION) # TODO: use cuda matmul when q_len <= 2.
|
| 43 |
+
if not PRESCALE_QK:
|
| 44 |
+
qk *= SM_SCALE
|
| 45 |
+
# ~~~~~~~~~~~~~~~~~~~ Apply score modification ~~~~~~~~~~~~~~~~~~~
|
| 46 |
+
# If this is the last block of a non divisible seqlen, we still need to load [BLOCK_M, BLOCK_N] elements,
|
| 47 |
+
# which is larger than the actual number of elements. To avoid access memory out of bound,
|
| 48 |
+
# we need to mask out the elements that are out of Q_LEN & KV_LEN.
|
| 49 |
+
m = get_bounded_indices(offs_m, Q_LEN if CHECK_BLOCK_BOUNDARY else None)
|
| 50 |
+
n = get_bounded_indices(offs_n, KV_LEN if CHECK_BLOCK_BOUNDARY else None)
|
| 51 |
+
|
| 52 |
+
{{ modification(
|
| 53 |
+
subgraph_number=0,
|
| 54 |
+
output_name="post_mod_scores",
|
| 55 |
+
score="qk",
|
| 56 |
+
b="off_z",
|
| 57 |
+
h="off_h",
|
| 58 |
+
m="m",
|
| 59 |
+
n="n",
|
| 60 |
+
out="qk"
|
| 61 |
+
) | indent_except_first(1) }}
|
| 62 |
+
|
| 63 |
+
if CHECK_BLOCK_BOUNDARY:
|
| 64 |
+
# Mask out the elements that are out of the KV_LEN for non divisible seqlen.
|
| 65 |
+
post_mod_scores = tl.where(offs_n < KV_LEN, post_mod_scores, float("-inf"))
|
| 66 |
+
|
| 67 |
+
if not IS_FULL_BLOCKS:
|
| 68 |
+
{{ modification(
|
| 69 |
+
subgraph_number=1,
|
| 70 |
+
output_name="mask_mod_output",
|
| 71 |
+
score="qk",
|
| 72 |
+
b="off_z",
|
| 73 |
+
h="off_h",
|
| 74 |
+
m="m",
|
| 75 |
+
n="n",
|
| 76 |
+
) | indent_except_first(2) }}
|
| 77 |
+
|
| 78 |
+
if CHECK_BLOCK_BOUNDARY:
|
| 79 |
+
mask_mod_output = tl.where(offs_n < KV_LEN, mask_mod_output, False)
|
| 80 |
+
# apply mask for partially unmasked blocks
|
| 81 |
+
post_mod_scores = tl.where(mask_mod_output, post_mod_scores, float("-inf"))
|
| 82 |
+
|
| 83 |
+
if not PRESCALE_QK:
|
| 84 |
+
post_mod_scores *= RCP_LN2
|
| 85 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 86 |
+
|
| 87 |
+
# -- compute scaling constant ---
|
| 88 |
+
m_ij = tl.maximum(m_i, tl.max(post_mod_scores, 1))
|
| 89 |
+
if not ROWS_GUARANTEED_SAFE:
|
| 90 |
+
masked_out_rows = (m_ij == float("-inf"))
|
| 91 |
+
m_ij_masked = tl.where(masked_out_rows, 0, m_ij)
|
| 92 |
+
else:
|
| 93 |
+
m_ij_masked = m_ij
|
| 94 |
+
|
| 95 |
+
alpha = tl.math.exp2(m_i - m_ij_masked)
|
| 96 |
+
p = tl.math.exp2(post_mod_scores - m_ij_masked[:, None])
|
| 97 |
+
|
| 98 |
+
# NB: l_i update is pulled up here since it's a bit faster
|
| 99 |
+
# NB: For headdim=256, it's faster to move it back down to after m_i =
|
| 100 |
+
# m_ij
|
| 101 |
+
l_i = l_i * alpha + tl.sum(p, 1)
|
| 102 |
+
# # -- scale and update acc --
|
| 103 |
+
acc = acc * alpha[:, None]
|
| 104 |
+
{%- if USE_TMA %}
|
| 105 |
+
v = tl.load_tensor_descriptor(
|
| 106 |
+
desc_v,
|
| 107 |
+
[kv_base_offset, 0],
|
| 108 |
+
)
|
| 109 |
+
{%- else %}
|
| 110 |
+
# Calculate offsets for V loading - reuse kv_base_offset from K loading
|
| 111 |
+
offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED)
|
| 112 |
+
v = load_checked_2d(V, offs_n_load, offs_v, stride_vn, stride_vk, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, V_HEAD_DIM)
|
| 113 |
+
{%- endif %}
|
| 114 |
+
acc = tl.dot(p.to(MATMUL_PRECISION), v, acc, input_precision=FLOAT32_PRECISION)
|
| 115 |
+
|
| 116 |
+
# -- update m_i
|
| 117 |
+
m_i = m_ij
|
| 118 |
+
|
| 119 |
+
return acc, l_i, m_i
|
| 120 |
+
|
| 121 |
+
@triton.jit
|
| 122 |
+
def forward_inner(
|
| 123 |
+
{{gen_argdefs()}},
|
| 124 |
+
q, K, V,
|
| 125 |
+
desc_k, desc_v, Q_LEN, KV_LEN,
|
| 126 |
+
# accumulated values
|
| 127 |
+
acc, l_i, m_i,
|
| 128 |
+
# Offsets used as inputs to score_mod & mask_mod
|
| 129 |
+
# of size [BLOCK_M, BLOCK_N] or scalar.
|
| 130 |
+
off_z, off_h, offs_m, offs_n,
|
| 131 |
+
# Offsets needed for TMA loads
|
| 132 |
+
kv_start,
|
| 133 |
+
# blocksparse data
|
| 134 |
+
kv_indices, kv_num_blocks,
|
| 135 |
+
# start kv and end kv block
|
| 136 |
+
block_n_start, block_n_end,
|
| 137 |
+
MATMUL_PRECISION,
|
| 138 |
+
# Strides for K and V
|
| 139 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 140 |
+
IS_FULL_BLOCKS,
|
| 141 |
+
):
|
| 142 |
+
# Redefines all kernel parameters (BLOCK_M, etc.) so we don't need to plumb them all through
|
| 143 |
+
{{gen_defines() | indent_except_first(1)}}
|
| 144 |
+
|
| 145 |
+
SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N)
|
| 146 |
+
RCP_LN2: tl.constexpr = 1.44269504
|
| 147 |
+
|
| 148 |
+
if PRESCALE_QK:
|
| 149 |
+
q = (q * SM_SCALE * RCP_LN2).to(MATMUL_PRECISION)
|
| 150 |
+
|
| 151 |
+
kv_offset = 0
|
| 152 |
+
|
| 153 |
+
# loop over k, v and update accumulator until block_n_end
|
| 154 |
+
for start_n in range(block_n_start, block_n_end):
|
| 155 |
+
# Here IS_DIVISIBLE acts are the start_n = tl.multiple_of(start_n, BLOCK_N) from triton_fused_attention.
|
| 156 |
+
if IS_DIVISIBLE:
|
| 157 |
+
acc, l_i, m_i = forward_block_mn(
|
| 158 |
+
{{gen_argdefs()}},
|
| 159 |
+
q, K, V, desc_k, desc_v, Q_LEN, KV_LEN,
|
| 160 |
+
# accumulated values
|
| 161 |
+
acc, l_i, m_i,
|
| 162 |
+
# Offsets
|
| 163 |
+
off_z, off_h, offs_m, offs_n,
|
| 164 |
+
# Offsets needed for TMA loads
|
| 165 |
+
kv_start,
|
| 166 |
+
kv_offset,
|
| 167 |
+
MATMUL_PRECISION, RCP_LN2,
|
| 168 |
+
# Strides for K and V
|
| 169 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 170 |
+
IS_FULL_BLOCKS,
|
| 171 |
+
)
|
| 172 |
+
else:
|
| 173 |
+
# Benchmark shows even we applied mod & mask to each block for non divisible seqlen,
|
| 174 |
+
# it's on par or slightly faster than only applying to the last block in fwd.
|
| 175 |
+
# However, we choose different strategy for bwd, where we only apply mod & mask
|
| 176 |
+
# to the last block because it's faster a lot.
|
| 177 |
+
acc, l_i, m_i = forward_block_mn(
|
| 178 |
+
{{gen_argdefs()}},
|
| 179 |
+
q, K, V, desc_k, desc_v, Q_LEN, KV_LEN,
|
| 180 |
+
# accumulated values
|
| 181 |
+
acc, l_i, m_i,
|
| 182 |
+
# Offsets
|
| 183 |
+
off_z, off_h, offs_m, offs_n,
|
| 184 |
+
# Offsets needed for TMA loads
|
| 185 |
+
kv_start,
|
| 186 |
+
kv_offset,
|
| 187 |
+
MATMUL_PRECISION, RCP_LN2,
|
| 188 |
+
# Strides for K and V
|
| 189 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 190 |
+
IS_FULL_BLOCKS, CHECK_BLOCK_BOUNDARY=True,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
offset = get_offset_for_next_block(
|
| 196 |
+
start_n, kv_indices, kv_num_blocks,
|
| 197 |
+
SPARSE_KV_BLOCK_SIZE, SPARSE_KV_MULTIPLE, BLOCK_N, BLOCKS_ARE_CONTIGUOUS
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
offs_n = offs_n + offset
|
| 201 |
+
kv_offset += offset
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
return acc, l_i, m_i
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flash_attention.py.jinja
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% if NEEDS_BLOCK_MASK %}
|
| 2 |
+
{{def_kernel("Q", "K", "V", "LOGSUMEXP", "KV_NUM_BLKS", "KV_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX")}}
|
| 3 |
+
{% else %}
|
| 4 |
+
{{def_kernel("Q", "K", "V", "LOGSUMEXP")}}
|
| 5 |
+
{% endif %}
|
| 6 |
+
from flash_attn.cute.interface import _flash_attn_fwd
|
| 7 |
+
from flash_attn.cute.block_sparsity import BlockSparseTensorsTorch
|
| 8 |
+
|
| 9 |
+
# Transpose tensors for _flash_attn_fwd compatibility (B,H,M,D) -> (B,M,H,D)
|
| 10 |
+
q_transposed = Q.transpose(1, 2)
|
| 11 |
+
k_transposed = K.transpose(1, 2)
|
| 12 |
+
v_transposed = V.transpose(1, 2)
|
| 13 |
+
|
| 14 |
+
@cute.jit
|
| 15 |
+
def score_mod(tSrS_ssa, b_idx, h_idx, q_idx, kv_idx, aux_tensors):
|
| 16 |
+
{{unpack_buffers("aux_tensors", indent_width=8)}}
|
| 17 |
+
{{ modification(
|
| 18 |
+
subgraph_number=0,
|
| 19 |
+
output_name="tSrS_ssa",
|
| 20 |
+
score="tSrS_ssa",
|
| 21 |
+
b="b_idx",
|
| 22 |
+
h="h_idx",
|
| 23 |
+
m="q_idx",
|
| 24 |
+
n="kv_idx",
|
| 25 |
+
out="tSrS_ssa"
|
| 26 |
+
) | indent_except_first(2) }}
|
| 27 |
+
return tSrS_ssa
|
| 28 |
+
{{ set_cute_hash("score_mod", "score") }}
|
| 29 |
+
|
| 30 |
+
# (B,M,H,D) -> (B,H,M,D)
|
| 31 |
+
output = {{get_output()}}
|
| 32 |
+
output_transposed = output.transpose(1, 2)
|
| 33 |
+
|
| 34 |
+
{% if NEEDS_BLOCK_MASK %}
|
| 35 |
+
@cute.jit
|
| 36 |
+
def mask_mod(b_idx, h_idx, q_idx, kv_idx, aux_tensors):
|
| 37 |
+
{{unpack_buffers("aux_tensors", indent_width=8)}}
|
| 38 |
+
{{ modification(
|
| 39 |
+
subgraph_number=1,
|
| 40 |
+
output_name="mask_mod_output",
|
| 41 |
+
b="b_idx",
|
| 42 |
+
h="h_idx",
|
| 43 |
+
m="q_idx",
|
| 44 |
+
n="kv_idx",
|
| 45 |
+
) | indent_except_first(2) }}
|
| 46 |
+
return mask_mod_output
|
| 47 |
+
{{ set_cute_hash("mask_mod", "mask") }}
|
| 48 |
+
block_sparse_tensors = BlockSparseTensorsTorch(KV_NUM_BLKS, KV_IDX, FULL_KV_NUM_BLKS, FULL_KV_IDX)
|
| 49 |
+
{% else %}
|
| 50 |
+
block_sparse_tensors = None
|
| 51 |
+
mask_mod = None
|
| 52 |
+
{% endif %}
|
| 53 |
+
|
| 54 |
+
# Collect any additional tensor buffers that were added during modifications
|
| 55 |
+
{% set tensor_buffers = get_tensor_buffers() -%}
|
| 56 |
+
{% if tensor_buffers -%}
|
| 57 |
+
buffers = [{% for buffer in tensor_buffers %}{{buffer}}{% if not loop.last %}, {% endif %}{% endfor %}]
|
| 58 |
+
buffers = list(buffers)
|
| 59 |
+
{% else -%}
|
| 60 |
+
buffers = None
|
| 61 |
+
{% endif -%}
|
| 62 |
+
|
| 63 |
+
# Out and LSE filled inplace
|
| 64 |
+
_flash_attn_fwd(
|
| 65 |
+
q_transposed,
|
| 66 |
+
k_transposed,
|
| 67 |
+
v_transposed,
|
| 68 |
+
softmax_scale={{SM_SCALE}},
|
| 69 |
+
return_lse=True,
|
| 70 |
+
score_mod=score_mod,
|
| 71 |
+
mask_mod=mask_mod,
|
| 72 |
+
out=output_transposed,
|
| 73 |
+
lse=LOGSUMEXP,
|
| 74 |
+
block_sparse_tensors=block_sparse_tensors,
|
| 75 |
+
aux_tensors=buffers
|
| 76 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flash_attention_backward.py.jinja
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("Q", "K", "V", "OUT", "D_OUT", "LSE", "DK", "DV")}}
|
| 2 |
+
from flash_attn.cute.interface import _flash_attn_bwd
|
| 3 |
+
|
| 4 |
+
q_transposed = Q.transpose(1, 2)
|
| 5 |
+
k_transposed = K.transpose(1, 2)
|
| 6 |
+
v_transposed = V.transpose(1, 2)
|
| 7 |
+
out_transposed = OUT.transpose(1, 2)
|
| 8 |
+
d_out_transposed = D_OUT.transpose(1, 2)
|
| 9 |
+
|
| 10 |
+
dq_transposed, dk_transposed, dv_transposed = _flash_attn_bwd(
|
| 11 |
+
q_transposed,
|
| 12 |
+
k_transposed,
|
| 13 |
+
v_transposed,
|
| 14 |
+
out_transposed,
|
| 15 |
+
d_out_transposed,
|
| 16 |
+
LSE,
|
| 17 |
+
softmax_scale={{SM_SCALE}},
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
dq = dq_transposed.transpose(1, 2)
|
| 21 |
+
dk = dk_transposed.transpose(1, 2)
|
| 22 |
+
dv = dv_transposed.transpose(1, 2)
|
| 23 |
+
|
| 24 |
+
dq_out = {{get_output()}}
|
| 25 |
+
{# TODO: add out support to flash #}
|
| 26 |
+
dq_out.copy_(dq)
|
| 27 |
+
DK.copy_(dk)
|
| 28 |
+
DV.copy_(dv)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flex_attention.py.jinja
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("Q", "K", "V", "LSE", "MAX", "KV_NUM_BLKS", "KV_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX")}}
|
| 2 |
+
# Sub notation for this kernel:
|
| 3 |
+
#
|
| 4 |
+
# Q: Query, K: Key, V: Value
|
| 5 |
+
# M: Number of queries, N: Number of keys/values, D: Model dimension
|
| 6 |
+
# QK_HEAD_DIM: The dimension of the query and key embeddings
|
| 7 |
+
# V_HEAD_DIM: The dimension of the value embeddings
|
| 8 |
+
# z: Batch size, h: Number of heads, m: Number of queries per head, k: Number of keys per head
|
| 9 |
+
# GQA_SHARED_HEADS: number of query heads sharing one kv head in GQA setups.
|
| 10 |
+
#
|
| 11 |
+
# The following FULL_* and PARTIAL_* is defined in the block sparse mask grid, rather than the thread block grid.
|
| 12 |
+
# KV_NUM_BLKS: The number of KV blocks (that may or may not require masking) for each query.
|
| 13 |
+
# KV_IDX: The indices of KV blocks (that may or may not require masking) for each query.
|
| 14 |
+
# FULL_KV_NUM_BLKS: The number of fully unmasked KV blocks (so we don't need masking) for each query.
|
| 15 |
+
# FULL_KV_IDX: The indices of fully unmasked KV blocks (so we don't need masking) for each query.
|
| 16 |
+
#
|
| 17 |
+
# OUTPUT_LOGSUMEXP: We only need to store the logsumexp if we require grad
|
| 18 |
+
#
|
| 19 |
+
# (Modifiable) Performance tuning options
|
| 20 |
+
# BLOCK_M: The thread block size across the seqlen dim of Q.
|
| 21 |
+
# BLOCK_N: Iterate over BLOCK_N across the seqlen dim of K/V in each thread block.
|
| 22 |
+
|
| 23 |
+
# The below are kernel options that can be applied for certain score_mods,
|
| 24 |
+
# or involve a numerics vs. perf tradeoff
|
| 25 |
+
# PRESCALE_QK: Whether to pre-scale QK by 1/sqrt(d) and change of base. Has
|
| 26 |
+
# about 20% more numerical error, but slightly faster.
|
| 27 |
+
# ROWS_GUARANTEED_SAFE: Is it guaranteed that at least one value in each row
|
| 28 |
+
# is not masked out? If so, we can skip an extra safety check
|
| 29 |
+
# BLOCKS_ARE_CONTIGUOUS: Is it guaranteed that all blocks in the mask are
|
| 30 |
+
# contiguous? If so, we don't need to do an indirect jump for every block
|
| 31 |
+
|
| 32 |
+
tl.static_assert(SPARSE_Q_BLOCK_SIZE >= BLOCK_M and SPARSE_Q_BLOCK_SIZE % BLOCK_M == 0)
|
| 33 |
+
tl.static_assert(SPARSE_KV_BLOCK_SIZE >= BLOCK_N and SPARSE_KV_BLOCK_SIZE % BLOCK_N == 0)
|
| 34 |
+
|
| 35 |
+
# Define strides of inputs
|
| 36 |
+
stride_qz, stride_qh, stride_qm, stride_qk = {{stride("Q")}}
|
| 37 |
+
stride_kz, stride_kh, stride_kn, stride_kk = {{stride("K")}}
|
| 38 |
+
stride_vz, stride_vh, stride_vn, stride_vk = {{stride("V")}}
|
| 39 |
+
|
| 40 |
+
ZQ = {{size("Q", 0)}}
|
| 41 |
+
HQ = {{size("Q", 1)}}
|
| 42 |
+
Q_LEN = {{size("Q", 2)}}
|
| 43 |
+
ZKV = {{size("K", 0)}}
|
| 44 |
+
KV_LEN = {{size("K", 2)}}
|
| 45 |
+
|
| 46 |
+
MATMUL_PRECISION = Q.dtype.element_ty
|
| 47 |
+
|
| 48 |
+
q_start = tl.program_id(0).to(INDEX_DTYPE)
|
| 49 |
+
off_zq = tl.program_id(1).to(INDEX_DTYPE)
|
| 50 |
+
off_hq = tl.program_id(2).to(INDEX_DTYPE)
|
| 51 |
+
|
| 52 |
+
# We support two cases for batch dimension. a) (ZKV == ZQ) where off_zkv = off_zq.
|
| 53 |
+
# b) (ZKV == 1 and ZQ > 1) where KV is broadcasted along the batch dimension and off_zkv=0.
|
| 54 |
+
off_zkv = off_zq % ZKV
|
| 55 |
+
off_hkv = off_hq // GQA_SHARED_HEADS
|
| 56 |
+
off_g = off_hq % GQA_SHARED_HEADS
|
| 57 |
+
|
| 58 |
+
q_offset = off_zq * stride_qz + off_hq * stride_qh
|
| 59 |
+
k_offset = off_zkv * stride_kz + off_hkv * stride_kh
|
| 60 |
+
v_offset = off_zkv * stride_vz + off_hkv * stride_vh
|
| 61 |
+
|
| 62 |
+
Q = Q + q_offset
|
| 63 |
+
K = K + k_offset
|
| 64 |
+
V = V + v_offset
|
| 65 |
+
|
| 66 |
+
# Setting up the TMA descriptors for Q, K, V
|
| 67 |
+
desc_q = None
|
| 68 |
+
desc_k = None
|
| 69 |
+
desc_v = None
|
| 70 |
+
{%- if USE_TMA %}
|
| 71 |
+
desc_q = tl.make_tensor_descriptor(
|
| 72 |
+
base=Q,
|
| 73 |
+
shape=[Q_LEN, QK_HEAD_DIM],
|
| 74 |
+
strides=[stride_qm, 1],
|
| 75 |
+
block_shape=[BLOCK_M, QK_HEAD_DIM_ROUNDED],
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
desc_k = tl.make_tensor_descriptor(
|
| 79 |
+
base=K,
|
| 80 |
+
shape=[KV_LEN, QK_HEAD_DIM],
|
| 81 |
+
strides=[stride_kn, 1],
|
| 82 |
+
block_shape=[BLOCK_N, QK_HEAD_DIM_ROUNDED],
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
desc_v = tl.make_tensor_descriptor(
|
| 86 |
+
base=V,
|
| 87 |
+
shape=[KV_LEN, V_HEAD_DIM],
|
| 88 |
+
strides=[stride_vn, 1],
|
| 89 |
+
block_shape=[BLOCK_N, V_HEAD_DIM_ROUNDED],
|
| 90 |
+
)
|
| 91 |
+
{%- endif %}
|
| 92 |
+
|
| 93 |
+
SPARSE_Z = {{size("KV_NUM_BLKS", 0)}}
|
| 94 |
+
SPARSE_HQ = {{size("KV_NUM_BLKS", 1)}}
|
| 95 |
+
|
| 96 |
+
sparse_idx_z = off_zq % SPARSE_Z
|
| 97 |
+
sparse_idx_hq = off_hq % SPARSE_HQ
|
| 98 |
+
|
| 99 |
+
SPARSE_Q_MULTIPLE: tl.constexpr = (SPARSE_Q_BLOCK_SIZE // BLOCK_M)
|
| 100 |
+
SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N)
|
| 101 |
+
|
| 102 |
+
stride_kv_num_blks_h = {{stride("KV_NUM_BLKS", 1)}}
|
| 103 |
+
stride_kv_idx_h = {{stride("KV_IDX", 1)}}
|
| 104 |
+
stride_kv_idx_m = {{stride("KV_IDX", 2)}}
|
| 105 |
+
|
| 106 |
+
# initialize pointer to m and l
|
| 107 |
+
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
|
| 108 |
+
l_i = tl.zeros([BLOCK_M], dtype=tl.float32)
|
| 109 |
+
acc = tl.zeros([BLOCK_M, V_HEAD_DIM_ROUNDED], dtype=tl.float32)
|
| 110 |
+
|
| 111 |
+
offs_m = q_start * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 112 |
+
|
| 113 |
+
# KV_IDX and KV_NUM_BLKS are always contiguous.
|
| 114 |
+
sparse_hz_offset = sparse_idx_z * SPARSE_HQ + sparse_idx_hq
|
| 115 |
+
sparse_kv_num_blks_offset = sparse_hz_offset * stride_kv_num_blks_h + q_start // SPARSE_Q_MULTIPLE
|
| 116 |
+
sparse_kv_idx_offset = sparse_hz_offset * stride_kv_idx_h + (q_start // SPARSE_Q_MULTIPLE) * stride_kv_idx_m # noqa: B950
|
| 117 |
+
|
| 118 |
+
{%- if USE_TMA %}
|
| 119 |
+
q = tl.load_tensor_descriptor(
|
| 120 |
+
desc_q,
|
| 121 |
+
[(q_start * BLOCK_M).to(tl.int32), 0],
|
| 122 |
+
)
|
| 123 |
+
{%- else %}
|
| 124 |
+
offs_m = q_start * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 125 |
+
offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED)
|
| 126 |
+
q = load_checked_2d(Q, offs_m, offs_k, stride_qm, stride_qk, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, QK_HEAD_DIM)
|
| 127 |
+
{%- endif %}
|
| 128 |
+
|
| 129 |
+
# ~~~~~~~~~~~~~~ normal blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 130 |
+
# We don't know anything "special" about these blocks, so we need to apply
|
| 131 |
+
# both score_mod and mask_mod to it
|
| 132 |
+
kv_indices = KV_IDX + sparse_kv_idx_offset
|
| 133 |
+
kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading
|
| 134 |
+
kv_num_blocks = tl.load(KV_NUM_BLKS + sparse_kv_num_blks_offset)
|
| 135 |
+
block_n_end = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# K and V pointers will be passed directly to forward_inner
|
| 139 |
+
|
| 140 |
+
offs_n = kv_start + tl.arange(0, BLOCK_N)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
acc, l_i, m_i = forward_inner(
|
| 144 |
+
{{gen_argdefs()}},
|
| 145 |
+
q, K, V,
|
| 146 |
+
desc_k, desc_v, Q_LEN, KV_LEN,
|
| 147 |
+
acc, l_i, m_i,
|
| 148 |
+
off_zq, off_hq, offs_m[:, None], offs_n[None, :],
|
| 149 |
+
kv_start,
|
| 150 |
+
kv_indices, kv_num_blocks,
|
| 151 |
+
0, block_n_end,
|
| 152 |
+
MATMUL_PRECISION,
|
| 153 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 154 |
+
IS_FULL_BLOCKS=False,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# ~~~~~~~~~~~~~~ "full" blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 158 |
+
# We know these blocks are guaranteed to be "full", so we don't need to
|
| 159 |
+
# apply mask_mod to them - only score_mod
|
| 160 |
+
if HAS_FULL_BLOCKS:
|
| 161 |
+
# FULL_KV_IDX and FULL_KV_NUM_BLKS are always contiguous.
|
| 162 |
+
kv_indices = FULL_KV_IDX + sparse_kv_idx_offset
|
| 163 |
+
kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading
|
| 164 |
+
kv_num_blocks = tl.load(FULL_KV_NUM_BLKS + sparse_kv_num_blks_offset)
|
| 165 |
+
block_n_end = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1))
|
| 166 |
+
# K and V pointers will be passed directly to forward_inner
|
| 167 |
+
offs_n = kv_start + tl.arange(0, BLOCK_N)
|
| 168 |
+
|
| 169 |
+
acc, l_i, m_i = forward_inner(
|
| 170 |
+
{{gen_argdefs()}},
|
| 171 |
+
q, K, V,
|
| 172 |
+
desc_k, desc_v, Q_LEN, KV_LEN,
|
| 173 |
+
acc, l_i, m_i,
|
| 174 |
+
off_zq, off_hq, offs_m[:, None], offs_n[None, :],
|
| 175 |
+
kv_start,
|
| 176 |
+
kv_indices, kv_num_blocks,
|
| 177 |
+
0, block_n_end,
|
| 178 |
+
MATMUL_PRECISION,
|
| 179 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 180 |
+
IS_FULL_BLOCKS=True,
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# [Note] Handle fully masked out rows:
|
| 185 |
+
# Li will be the sum(e^(-inf)) == 0.0 for masked out rows, mi will be -inf.
|
| 186 |
+
# We set Li to 1.0 which will result in lse/out = 0.0 | after the log(li) + mi(0.0) step
|
| 187 |
+
l_i = tl.where(l_i == 0.0, 1, l_i)
|
| 188 |
+
|
| 189 |
+
acc = acc / l_i[:, None]
|
| 190 |
+
idx_zq = tl.program_id(1).to(INDEX_DTYPE)
|
| 191 |
+
idx_hq = tl.program_id(2).to(INDEX_DTYPE)
|
| 192 |
+
idx_m = offs_m[:, None].to(INDEX_DTYPE)
|
| 193 |
+
idx_d = tl.arange(0, V_HEAD_DIM_ROUNDED)[None, :].to(INDEX_DTYPE)
|
| 194 |
+
|
| 195 |
+
mask = (idx_m < Q_LEN) & (idx_d < V_HEAD_DIM)
|
| 196 |
+
|
| 197 |
+
tl.static_assert(acc.shape == [BLOCK_M, V_HEAD_DIM_ROUNDED])
|
| 198 |
+
{{store_output(("idx_zq", "idx_hq", "idx_m", "idx_d"), "acc", "mask", val_shape=("BLOCK_M", "V_HEAD_DIM_ROUNDED"))}}
|
| 199 |
+
|
| 200 |
+
if OUTPUT_LOGSUMEXP:
|
| 201 |
+
off_hz = off_zq * HQ + off_hq
|
| 202 |
+
l_ptrs = LSE + off_hz * Q_LEN + offs_m
|
| 203 |
+
lse = m_i + tl.math.log2(l_i)
|
| 204 |
+
if IS_DIVISIBLE:
|
| 205 |
+
tl.store(l_ptrs, lse)
|
| 206 |
+
else:
|
| 207 |
+
tl.store(l_ptrs, lse, mask=offs_m < Q_LEN)
|
| 208 |
+
|
| 209 |
+
if OUTPUT_MAX:
|
| 210 |
+
off_hz = off_zq * HQ + off_hq
|
| 211 |
+
max_ptrs = MAX + off_hz * Q_LEN + offs_m
|
| 212 |
+
if IS_DIVISIBLE:
|
| 213 |
+
tl.store(max_ptrs, m_i)
|
| 214 |
+
else:
|
| 215 |
+
tl.store(max_ptrs, m_i, mask=offs_m < Q_LEN)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flex_backwards.py.jinja
ADDED
|
@@ -0,0 +1,620 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("Q", "K", "V", "LSE", "DELTA", "DO", "DQ", "DV", "KV_NUM_BLKS", "KV_IDX", "Q_NUM_BLKS", "Q_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX", "FULL_Q_NUM_BLKS", "FULL_Q_IDX")}}
|
| 2 |
+
# Sub notation for this kernel:
|
| 3 |
+
#
|
| 4 |
+
# Q: Query, K: Key, V: Value
|
| 5 |
+
# LSE: logsumexp (logsumexp is always stored in fp32 regardless of the input dtype)
|
| 6 |
+
# DELTA: Precomputed sum(OUT*DO, axis=-1)
|
| 7 |
+
# DO: Derivative of Output, DQ: Derivative of Query, DV: Derivative of Value
|
| 8 |
+
# DK: Derivative of Key, is the written to via the store_output call due to some limitations with
|
| 9 |
+
# inductor codegen
|
| 10 |
+
# M: Number of queries, N: Number of keys/values
|
| 11 |
+
# QK_HEAD_DIM: The dimension of the query and key embeddings
|
| 12 |
+
# V_HEAD_DIM: The dimension of the value embeddings
|
| 13 |
+
# z: Batch size, h: Number of heads, m: Number of queries or keys/values, d: Head dim
|
| 14 |
+
# GQA_SHARED_HEADS: number of query heads sharing one kv head in GQA setups.
|
| 15 |
+
# (Modifiable) Performance tuning options
|
| 16 |
+
# BLOCK_M1: when calculating DK & DV, iterate over BLOCK_M1 across the seqlen dim of Q in each thread block.
|
| 17 |
+
# BLOCK_N1: when calculating DK & DV, the thread block size across the seqlen dim of K/V.
|
| 18 |
+
# BLOCK_M2: when calculating DQ, the thread block size across the seqlen dim of Q.
|
| 19 |
+
# BLOCK_N2: when calculating DQ, iterate over BLOCK_N2 across the seqlen dim of K/V in each thread block.
|
| 20 |
+
#
|
| 21 |
+
# The following FULL_* and PARTIAL_* is defined in the block sparse mask grid, rather than the thread block grid.
|
| 22 |
+
# KV_NUM_BLKS: The number of KV blocks (that may or may not require masking) for each query.
|
| 23 |
+
# KV_IDX: The indices of KV blocks (that may or may not require masking) for each query.
|
| 24 |
+
# Q_NUM_BLKS: The number of Q blocks (that may or may not require masking) for each query.
|
| 25 |
+
# Q_IDX: The indices of Q blocks (that may or may not require masking) for each query.
|
| 26 |
+
# FULL_KV_NUM_BLKS: The number of fully unmasked KV blocks (so we don't need masking) for each query.
|
| 27 |
+
# FULL_KV_IDX: The indices of fully unmasked KV blocks (so we don't need masking) for each query.
|
| 28 |
+
# FULL_Q_NUM_BLKS: The number of fully unmasked Q blocks (so we don't need masking) for each query.
|
| 29 |
+
# FULL_Q_IDX: The indices of fully unmasked Q blocks (so we don't need masking) for each query.
|
| 30 |
+
|
| 31 |
+
# The below are kernel options that can be applied for certain score_mods,
|
| 32 |
+
# or involve a numerics vs. perf tradeoff
|
| 33 |
+
# PRESCALE_QK: Whether to pre-scale QK by 1/sqrt(d) and change of base. Has
|
| 34 |
+
# about 20% more numerical error, but slightly faster.
|
| 35 |
+
|
| 36 |
+
# Define strides of inputs
|
| 37 |
+
stride_qz, stride_qh, stride_qm, stride_qd = {{stride("Q")}}
|
| 38 |
+
stride_kz, stride_kh, stride_kn, stride_kd = {{stride("K")}}
|
| 39 |
+
stride_vz, stride_vh, stride_vn, stride_vd = {{stride("V")}}
|
| 40 |
+
stride_doz, stride_doh, stride_dom, stride_dod = {{stride("DO")}}
|
| 41 |
+
|
| 42 |
+
stride_dqz, stride_dqh, stride_dqm, stride_dqd = {{stride("DQ")}}
|
| 43 |
+
stride_dvz, stride_dvh, stride_dvm, stride_dvd = {{stride("DV")}}
|
| 44 |
+
|
| 45 |
+
ZQ = {{size("Q", 0)}}
|
| 46 |
+
HQ = {{size("Q", 1)}}
|
| 47 |
+
HKV = {{size("K", 1)}}
|
| 48 |
+
Q_LEN = {{size("Q", 2)}}
|
| 49 |
+
ZKV = {{size("K", 0)}}
|
| 50 |
+
KV_LEN = {{size("K", 2)}}
|
| 51 |
+
|
| 52 |
+
MATMUL_PRECISION = Q.dtype.element_ty
|
| 53 |
+
|
| 54 |
+
pid = tl.program_id(0).to(INDEX_DTYPE)
|
| 55 |
+
NUM_KV_BLOCKS = tl.cdiv(KV_LEN, BLOCK_N1)
|
| 56 |
+
NUM_Q_BLOCKS = tl.cdiv(Q_LEN, BLOCK_M2)
|
| 57 |
+
|
| 58 |
+
off_zq = tl.program_id(1).to(INDEX_DTYPE) # q batch idx
|
| 59 |
+
off_hkv = tl.program_id(2).to(INDEX_DTYPE) # kv head idx
|
| 60 |
+
off_zkv = off_zq % ZKV # kv batch idx
|
| 61 |
+
|
| 62 |
+
SPARSE_Z = {{size("KV_NUM_BLKS", 0)}}
|
| 63 |
+
SPARSE_HQ = {{size("KV_NUM_BLKS", 1)}}
|
| 64 |
+
|
| 65 |
+
sparse_idx_z = off_zq % SPARSE_Z
|
| 66 |
+
|
| 67 |
+
k_adj = (stride_kh * off_hkv + stride_kz * off_zkv).to(tl.int64)
|
| 68 |
+
v_adj = (stride_vh * off_hkv + stride_vz * off_zkv).to(tl.int64)
|
| 69 |
+
# first compute broadcasted dv of shape [Bq, Hkv, KV_LEN, V_HEAD_DIM]
|
| 70 |
+
# then reduce to dv of shape [Bkv, Hkv, KV_LEN, V_HEAD_DIM]
|
| 71 |
+
dv_adj = (stride_dvh * off_hkv + stride_dvz * off_zq).to(tl.int64)
|
| 72 |
+
|
| 73 |
+
# offset K, V, DV pointers for batch/kv-head
|
| 74 |
+
K += k_adj
|
| 75 |
+
V += v_adj
|
| 76 |
+
DV += dv_adj
|
| 77 |
+
|
| 78 |
+
RCP_LN2 = 1.44269504
|
| 79 |
+
offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED)
|
| 80 |
+
offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED)
|
| 81 |
+
|
| 82 |
+
if pid >= NUM_KV_BLOCKS:
|
| 83 |
+
off_pid = pid - NUM_KV_BLOCKS
|
| 84 |
+
# THIS BLOCK DOES DQ
|
| 85 |
+
SPARSE_Q_MULTIPLE = (SPARSE_Q_BLOCK_SIZE // BLOCK_M2)
|
| 86 |
+
SPARSE_KV_MULTIPLE = (SPARSE_KV_BLOCK_SIZE // BLOCK_N2)
|
| 87 |
+
off_hq2 = off_pid // NUM_Q_BLOCKS + off_hkv * GQA_SHARED_HEADS
|
| 88 |
+
start_m2_block = off_pid % NUM_Q_BLOCKS
|
| 89 |
+
off_pid_mask = start_m2_block // SPARSE_Q_MULTIPLE
|
| 90 |
+
stride_kv_num_blks_h = {{stride("KV_NUM_BLKS", 1)}}
|
| 91 |
+
stride_kv_idx_h = {{stride("KV_IDX", 1)}}
|
| 92 |
+
stride_kv_idx_m = {{stride("KV_IDX", 2)}}
|
| 93 |
+
|
| 94 |
+
sparse_idx_hq2 = off_hq2 % SPARSE_HQ
|
| 95 |
+
sparse_hz_offset = sparse_idx_z * SPARSE_HQ + sparse_idx_hq2
|
| 96 |
+
|
| 97 |
+
sparse_kv_num_blks_offset = sparse_hz_offset * stride_kv_num_blks_h + off_pid_mask
|
| 98 |
+
sparse_kv_idx_offset = sparse_hz_offset * stride_kv_idx_h + off_pid_mask * stride_kv_idx_m # noqa: B950
|
| 99 |
+
|
| 100 |
+
# Offset Q, DQ, DO, DELTA & LSE. These inputs are offsetted by query heads.
|
| 101 |
+
q_adj2 = (stride_qh * off_hq2 + stride_qz * off_zq).to(tl.int64)
|
| 102 |
+
do_adj2 = (stride_doh * off_hq2 + stride_doz * off_zq).to(tl.int64)
|
| 103 |
+
dq_adj2 = (stride_dqh * off_hq2 + stride_dqz * off_zq).to(tl.int64)
|
| 104 |
+
off_chz2 = ((off_zq * HQ + off_hq2) * Q_LEN).to(tl.int64)
|
| 105 |
+
|
| 106 |
+
Q2 = Q + q_adj2
|
| 107 |
+
DO2 = DO + do_adj2
|
| 108 |
+
# TODO: This does not work if DQ is not the same layout as Q (for example,
|
| 109 |
+
# if Q is broadcasted)
|
| 110 |
+
DQ2 = DQ + dq_adj2
|
| 111 |
+
LSE2 = LSE + off_chz2
|
| 112 |
+
DELTA2 = DELTA + off_chz2
|
| 113 |
+
|
| 114 |
+
# dq = tl.zeros([BLOCK_M2, QK_HEAD_DIM], dtype=tl.float32)
|
| 115 |
+
dq = tl.zeros([BLOCK_M2, QK_HEAD_DIM_ROUNDED], dtype=tl.float32)
|
| 116 |
+
|
| 117 |
+
start_m2 = start_m2_block * BLOCK_M2
|
| 118 |
+
offs_m2 = start_m2 + tl.arange(0, BLOCK_M2)
|
| 119 |
+
|
| 120 |
+
# load Q and do: they stay in SRAM throughout the inner loop.
|
| 121 |
+
q = load_checked_2d(Q2, offs_m2, offs_k, stride_qm, stride_qd, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, QK_HEAD_DIM)
|
| 122 |
+
do = load_checked_2d(DO2, offs_m2, offs_v, stride_dom, stride_dod, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, V_HEAD_DIM)
|
| 123 |
+
|
| 124 |
+
if PRESCALE_QK:
|
| 125 |
+
q = (q * SM_SCALE * RCP_LN2).to(MATMUL_PRECISION)
|
| 126 |
+
|
| 127 |
+
if IS_DIVISIBLE:
|
| 128 |
+
Di = tl.load(DELTA2 + offs_m2)
|
| 129 |
+
lse = tl.load(LSE2 + offs_m2)
|
| 130 |
+
else:
|
| 131 |
+
Di = tl.load(DELTA2 + offs_m2, mask=offs_m2 < Q_LEN)
|
| 132 |
+
lse = tl.load(LSE2 + offs_m2, mask=offs_m2 < Q_LEN)
|
| 133 |
+
lse = tl.where(lse == -float("inf"), 0.0, lse)
|
| 134 |
+
lse = lse[:, None]
|
| 135 |
+
|
| 136 |
+
# ~~~~~~~~~~~ fully unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 137 |
+
# KV_IDX and KV_NUM_BLKS are always contiguous.
|
| 138 |
+
kv_indices = KV_IDX + sparse_kv_idx_offset
|
| 139 |
+
kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading
|
| 140 |
+
sparse_kv_num_blocks = tl.load(KV_NUM_BLKS + sparse_kv_num_blks_offset)
|
| 141 |
+
|
| 142 |
+
offs_n2 = kv_start + tl.arange(0, BLOCK_N2)
|
| 143 |
+
dq = bwd_dq_inner(
|
| 144 |
+
{{gen_argdefs()}},
|
| 145 |
+
K, V,
|
| 146 |
+
dq, q, do, Di, lse,
|
| 147 |
+
off_zq, off_hq2, offs_m2, offs_n2,
|
| 148 |
+
stride_kn, stride_kd, stride_vn, stride_vd,
|
| 149 |
+
kv_indices, sparse_kv_num_blocks,
|
| 150 |
+
MATMUL_PRECISION,
|
| 151 |
+
IS_FULL_BLOCKS=False,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
if HAS_FULL_BLOCKS:
|
| 155 |
+
# ~~~~~~~~~~~ partial unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 156 |
+
# FULL_KV_IDX and FULL_KV_NUM_BLKS are always contiguous.
|
| 157 |
+
kv_indices = FULL_KV_IDX + sparse_kv_idx_offset
|
| 158 |
+
kv_start = tl.load(kv_indices) * SPARSE_KV_BLOCK_SIZE # first kv block we're loading
|
| 159 |
+
sparse_kv_num_blocks = tl.load(FULL_KV_NUM_BLKS + sparse_kv_num_blks_offset)
|
| 160 |
+
|
| 161 |
+
offs_n2 = kv_start + tl.arange(0, BLOCK_N2)
|
| 162 |
+
dq = bwd_dq_inner(
|
| 163 |
+
{{gen_argdefs()}},
|
| 164 |
+
K, V,
|
| 165 |
+
dq, q, do, Di, lse,
|
| 166 |
+
off_zq, off_hq2, offs_m2, offs_n2,
|
| 167 |
+
stride_kn, stride_kd, stride_vn, stride_vd,
|
| 168 |
+
kv_indices, sparse_kv_num_blocks,
|
| 169 |
+
MATMUL_PRECISION,
|
| 170 |
+
IS_FULL_BLOCKS=True,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# Write back dQ.
|
| 174 |
+
dq_ptrs = DQ2 + offs_m2[:, None] * stride_dqm + offs_k[None, :] * stride_dqd
|
| 175 |
+
dq *= SM_SCALE
|
| 176 |
+
if IS_DIVISIBLE and SAFE_HEAD_DIM:
|
| 177 |
+
tl.store(dq_ptrs, dq)
|
| 178 |
+
else:
|
| 179 |
+
tl.store(dq_ptrs, dq, mask=(offs_m2[:, None] < Q_LEN) & (offs_k[None, :] < QK_HEAD_DIM))
|
| 180 |
+
else:
|
| 181 |
+
# THIS BLOCK DOES DK & DV
|
| 182 |
+
SPARSE_Q_MULTIPLE = (SPARSE_Q_BLOCK_SIZE // BLOCK_M1)
|
| 183 |
+
SPARSE_KV_MULTIPLE = (SPARSE_KV_BLOCK_SIZE // BLOCK_N1)
|
| 184 |
+
|
| 185 |
+
pid_mask = pid // SPARSE_KV_MULTIPLE
|
| 186 |
+
|
| 187 |
+
stride_q_num_blks_h = {{stride("Q_NUM_BLKS", 1)}}
|
| 188 |
+
stride_q_idx_h = {{stride("Q_IDX", 1)}}
|
| 189 |
+
stride_q_idx_n = {{stride("Q_IDX", 2)}}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
dv = tl.zeros([BLOCK_N1, V_HEAD_DIM_ROUNDED], dtype=tl.float32)
|
| 193 |
+
dk = tl.zeros([BLOCK_N1, QK_HEAD_DIM_ROUNDED], dtype=tl.float32)
|
| 194 |
+
|
| 195 |
+
start_n1 = pid * BLOCK_N1
|
| 196 |
+
offs_n1 = start_n1 + tl.arange(0, BLOCK_N1)
|
| 197 |
+
|
| 198 |
+
# load K and V: they stay in SRAM throughout the inner loop.
|
| 199 |
+
k = load_checked_2d(K, offs_n1, offs_k, stride_kn, stride_kd, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, QK_HEAD_DIM)
|
| 200 |
+
v = load_checked_2d(V, offs_n1, offs_v, stride_vn, stride_vd, IS_DIVISIBLE, SAFE_HEAD_DIM, KV_LEN, V_HEAD_DIM)
|
| 201 |
+
|
| 202 |
+
if PRESCALE_QK:
|
| 203 |
+
k = (k * SM_SCALE * RCP_LN2).to(MATMUL_PRECISION)
|
| 204 |
+
|
| 205 |
+
for off_g in range(0, GQA_SHARED_HEADS):
|
| 206 |
+
off_hq1 = off_hkv * GQA_SHARED_HEADS + off_g
|
| 207 |
+
|
| 208 |
+
# Offset Q, DQ, DO, DELTA & LSE. These inputs are offsetted by query heads.
|
| 209 |
+
q_adj1 = (stride_qh * off_hq1 + stride_qz * off_zq).to(tl.int64)
|
| 210 |
+
do_adj1 = (stride_doh * off_hq1 + stride_doz * off_zq).to(tl.int64)
|
| 211 |
+
dq_adj1 = (stride_dqh * off_hq1 + stride_dqz * off_zq).to(tl.int64)
|
| 212 |
+
off_chz1 = ((off_zq * HQ + off_hq1) * Q_LEN).to(tl.int64)
|
| 213 |
+
|
| 214 |
+
Q1 = Q + q_adj1
|
| 215 |
+
DO1 = DO + do_adj1
|
| 216 |
+
# TODO: This does not work if DQ is not the same layout as Q (for example,
|
| 217 |
+
# if Q is broadcasted)
|
| 218 |
+
LSE1 = LSE + off_chz1
|
| 219 |
+
DELTA1 = DELTA + off_chz1
|
| 220 |
+
|
| 221 |
+
sparse_idx_hq1 = off_hq1 % SPARSE_HQ
|
| 222 |
+
sparse_hz_offset = sparse_idx_z * SPARSE_HQ + sparse_idx_hq1
|
| 223 |
+
|
| 224 |
+
sparse_q_num_blks_offset = sparse_hz_offset * stride_q_num_blks_h + pid_mask
|
| 225 |
+
sparse_q_idx_offset = sparse_hz_offset * stride_q_idx_h + pid_mask * stride_q_idx_n # noqa: B950
|
| 226 |
+
|
| 227 |
+
# ~~~~~~~~~~~~~~~ fully unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 228 |
+
# Q_IDX and Q_NUM_BLKS are always contiguous.
|
| 229 |
+
q_indices = Q_IDX + sparse_q_idx_offset
|
| 230 |
+
q_start = tl.load(q_indices) * SPARSE_Q_BLOCK_SIZE # first q block we're loading
|
| 231 |
+
sparse_q_num_blocks = tl.load(Q_NUM_BLKS + sparse_q_num_blks_offset)
|
| 232 |
+
|
| 233 |
+
offs_m1 = q_start + tl.arange(0, BLOCK_M1)
|
| 234 |
+
dk, dv = bwd_dkdv_inner(
|
| 235 |
+
{{gen_argdefs()}},
|
| 236 |
+
Q1, DO1, DELTA1, LSE1,
|
| 237 |
+
dk, dv, k, v,
|
| 238 |
+
off_zq, off_hq1, offs_n1, offs_m1,
|
| 239 |
+
stride_qm, stride_qd, stride_dom, stride_dod,
|
| 240 |
+
q_indices, sparse_q_num_blocks,
|
| 241 |
+
MATMUL_PRECISION,
|
| 242 |
+
IS_FULL_BLOCKS=False,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
if HAS_FULL_BLOCKS:
|
| 247 |
+
# ~~~~~~~~~~~~~~~ fully unmasked blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 248 |
+
# FULL_Q_IDX and FULL_Q_NUM_BLKS are always contiguous.
|
| 249 |
+
q_indices = FULL_Q_IDX + sparse_q_idx_offset
|
| 250 |
+
q_start = tl.load(q_indices) * SPARSE_Q_BLOCK_SIZE # first q block we're loading
|
| 251 |
+
sparse_q_num_blocks = tl.load(FULL_Q_NUM_BLKS + sparse_q_num_blks_offset)
|
| 252 |
+
|
| 253 |
+
offs_m1 = q_start + tl.arange(0, BLOCK_M1)
|
| 254 |
+
dk, dv = bwd_dkdv_inner(
|
| 255 |
+
{{gen_argdefs()}},
|
| 256 |
+
Q1, DO1, DELTA1, LSE1,
|
| 257 |
+
dk, dv, k, v,
|
| 258 |
+
off_zq, off_hq1, offs_n1, offs_m1,
|
| 259 |
+
stride_qm, stride_qd, stride_dom, stride_dod,
|
| 260 |
+
q_indices, sparse_q_num_blocks,
|
| 261 |
+
MATMUL_PRECISION,
|
| 262 |
+
IS_FULL_BLOCKS=True,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
# Write back dV and dK.
|
| 266 |
+
dv_ptrs = DV + offs_n1[:, None] * stride_dvm + offs_v[None, :] * stride_dvd
|
| 267 |
+
|
| 268 |
+
index_n = offs_n1[:, None]
|
| 269 |
+
index_k = offs_k[None, :]
|
| 270 |
+
index_v = offs_v[None, :]
|
| 271 |
+
|
| 272 |
+
if IS_DIVISIBLE and SAFE_HEAD_DIM:
|
| 273 |
+
tl.store(dv_ptrs, dv)
|
| 274 |
+
else:
|
| 275 |
+
tl.store(dv_ptrs, dv, mask=(index_n < KV_LEN) & (index_v < V_HEAD_DIM))
|
| 276 |
+
|
| 277 |
+
dk *= SM_SCALE
|
| 278 |
+
|
| 279 |
+
if SAFE_HEAD_DIM:
|
| 280 |
+
mask = index_n < KV_LEN
|
| 281 |
+
else:
|
| 282 |
+
mask = (index_n < KV_LEN) & (index_k < QK_HEAD_DIM)
|
| 283 |
+
|
| 284 |
+
# first compute broadcasted dk of shape [Bq, Hkv, KV_LEN, V_HEAD_DIM]
|
| 285 |
+
# then reduce to dk of shape [Bkv, Hkv, KV_LEN, V_HEAD_DIM]
|
| 286 |
+
tl.static_assert(dk.shape == [BLOCK_N1, QK_HEAD_DIM_ROUNDED])
|
| 287 |
+
{{store_output(("off_zq", "off_hkv", "index_n", "index_k"), "dk", "mask", indent_width=8, val_shape=("BLOCK_N1", "QK_HEAD_DIM_ROUNDED"))}}
|
| 288 |
+
|
| 289 |
+
@triton.jit
|
| 290 |
+
def bwd_dq_inner(
|
| 291 |
+
{{gen_argdefs()}},
|
| 292 |
+
K, V, # pointers
|
| 293 |
+
dq, q, do, Di, lse,
|
| 294 |
+
off_z, off_hq, offs_m2, offs_n2,
|
| 295 |
+
stride_kn, stride_kd, stride_vn, stride_vd,
|
| 296 |
+
kv_indices, sparse_kv_num_blocks,
|
| 297 |
+
MATMUL_PRECISION,
|
| 298 |
+
IS_FULL_BLOCKS,
|
| 299 |
+
):
|
| 300 |
+
{{gen_defines() | indent_except_first(1) }}
|
| 301 |
+
SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N2)
|
| 302 |
+
RCP_LN2: tl.constexpr = 1.44269504
|
| 303 |
+
Q_LEN = {{size("Q", 2)}}
|
| 304 |
+
KV_LEN = {{size("K", 2)}}
|
| 305 |
+
|
| 306 |
+
offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED)
|
| 307 |
+
offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED)
|
| 308 |
+
|
| 309 |
+
kT_ptrs = K + offs_n2[None, :] * stride_kn + offs_k[:, None] * stride_kd
|
| 310 |
+
vT_ptrs = V + offs_n2[None, :] * stride_vn + offs_v[:, None] * stride_vd
|
| 311 |
+
# BLOCK_M2 must be a multiple of BLOCK_N2, otherwise the code wouldn't work.
|
| 312 |
+
tl.static_assert(BLOCK_M2 % BLOCK_N2 == 0)
|
| 313 |
+
|
| 314 |
+
hi = tl.minimum(sparse_kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N2), 1))
|
| 315 |
+
|
| 316 |
+
for start_n in range(0, hi):
|
| 317 |
+
dq = bwd_dq_block_mn(
|
| 318 |
+
{{gen_argdefs()}},
|
| 319 |
+
dq, q, kT_ptrs, vT_ptrs, do, Di, lse, Q_LEN, KV_LEN,
|
| 320 |
+
off_z, off_hq, offs_m2, offs_n2, offs_k, offs_v,
|
| 321 |
+
stride_kn, stride_kd, stride_vn, stride_vd,
|
| 322 |
+
kv_indices, sparse_kv_num_blocks,
|
| 323 |
+
MATMUL_PRECISION, RCP_LN2,
|
| 324 |
+
IS_FULL_BLOCKS,
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Increment pointers.
|
| 328 |
+
offset = get_offset_for_next_block(
|
| 329 |
+
start_n, kv_indices, sparse_kv_num_blocks,
|
| 330 |
+
SPARSE_KV_BLOCK_SIZE, SPARSE_KV_MULTIPLE, BLOCK_N2, BLOCKS_ARE_CONTIGUOUS
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
kT_ptrs += offset * stride_kn
|
| 334 |
+
vT_ptrs += offset * stride_vn
|
| 335 |
+
|
| 336 |
+
offs_n2 += offset
|
| 337 |
+
|
| 338 |
+
return dq
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
@triton.jit
|
| 342 |
+
def bwd_dq_block_mn(
|
| 343 |
+
{{gen_argdefs()}},
|
| 344 |
+
dq, q, kT_ptrs, vT_ptrs, do, Di, lse, Q_LEN, KV_LEN,
|
| 345 |
+
off_z, off_hq, offs_m2, offs_n2, offs_k, offs_v,
|
| 346 |
+
stride_kn, stride_kd, stride_vn, stride_vd,
|
| 347 |
+
kv_indices, sparse_kv_num_blocks,
|
| 348 |
+
MATMUL_PRECISION, RCP_LN2,
|
| 349 |
+
IS_FULL_BLOCKS,
|
| 350 |
+
):
|
| 351 |
+
{{gen_defines() | indent_except_first(1)}}
|
| 352 |
+
|
| 353 |
+
# NB reversed order to since K is transposed
|
| 354 |
+
kT = load_checked_2d(kT_ptrs, offs_k, offs_n2, None, None, SAFE_HEAD_DIM, IS_DIVISIBLE, QK_HEAD_DIM, KV_LEN)
|
| 355 |
+
qk = tl.dot(q, kT, input_precision=FLOAT32_PRECISION)
|
| 356 |
+
if not PRESCALE_QK:
|
| 357 |
+
qk *= SM_SCALE
|
| 358 |
+
# ~~~~~~~~~~~~~~~~~~~ Apply score modification ~~~~~~~~~~~~~~~~~~~
|
| 359 |
+
pre_mod_scores = qk
|
| 360 |
+
n = get_bounded_indices(offs_n2[None, :], KV_LEN if not IS_DIVISIBLE else None)
|
| 361 |
+
# The boundary check is done for the outer loop, but here it's possible since we're iterating across N dim
|
| 362 |
+
# that the M reads out of bounds for the PIDS spanning the Q_LEN boundary
|
| 363 |
+
m = get_bounded_indices(offs_m2[:, None], Q_LEN if not IS_DIVISIBLE else None)
|
| 364 |
+
|
| 365 |
+
{{ modification(
|
| 366 |
+
subgraph_number=0,
|
| 367 |
+
output_name="post_mod_scores",
|
| 368 |
+
score="qk",
|
| 369 |
+
b="off_z",
|
| 370 |
+
h="off_hq",
|
| 371 |
+
m="m",
|
| 372 |
+
n="n",
|
| 373 |
+
out="qk"
|
| 374 |
+
) | indent_except_first(1) }}
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
{# Note: Selective masking DQ
|
| 378 |
+
We load elements beyond KV_LEN w/ zero, some score mods may convert this elements to NaN
|
| 379 |
+
Example: lambda x, *_: 1 / score, this NaN would propagate regardless of other masking
|
| 380 |
+
We only need to do this on the m1 dim since these elements take part in the final reduction
|
| 381 |
+
for DQ #}
|
| 382 |
+
if not IS_DIVISIBLE:
|
| 383 |
+
post_mod_scores = tl.where(offs_n2[None, :] < KV_LEN, post_mod_scores, float("-inf"))
|
| 384 |
+
|
| 385 |
+
if not IS_FULL_BLOCKS:
|
| 386 |
+
{{ modification(
|
| 387 |
+
subgraph_number=2,
|
| 388 |
+
output_name="mask_mod_output",
|
| 389 |
+
score="qk",
|
| 390 |
+
b="off_z",
|
| 391 |
+
h="off_hq",
|
| 392 |
+
m="m",
|
| 393 |
+
n="n",
|
| 394 |
+
) | indent_except_first(2) }}
|
| 395 |
+
|
| 396 |
+
# apply mask for partial masked block
|
| 397 |
+
post_mod_scores = tl.where(mask_mod_output, post_mod_scores, float("-inf"))
|
| 398 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 399 |
+
if not PRESCALE_QK:
|
| 400 |
+
post_mod_scores *= RCP_LN2
|
| 401 |
+
p = tl.math.exp2(post_mod_scores - lse)
|
| 402 |
+
# Compute dP and dS.
|
| 403 |
+
# NB reversed order to since V is transposed
|
| 404 |
+
vT = load_checked_2d(vT_ptrs, offs_v, offs_n2, None, None, SAFE_HEAD_DIM, IS_DIVISIBLE, V_HEAD_DIM, KV_LEN)
|
| 405 |
+
|
| 406 |
+
dp = tl.dot(do, vT, input_precision=FLOAT32_PRECISION)
|
| 407 |
+
ds = p * (dp - Di[:, None])
|
| 408 |
+
# ~~~~~~~~~~~~~~~~~~~ Apply joint modification ~~~~~~~~~~~~~~~~~~~
|
| 409 |
+
{{ modification(
|
| 410 |
+
subgraph_number=1,
|
| 411 |
+
output_name = "grad_scores",
|
| 412 |
+
score="pre_mod_scores",
|
| 413 |
+
b="off_z",
|
| 414 |
+
h="off_hq",
|
| 415 |
+
m="m",
|
| 416 |
+
n="n",
|
| 417 |
+
grad_score_mod="ds"
|
| 418 |
+
) | indent_except_first(1) }}
|
| 419 |
+
{# See Note Selective masking DQ #}
|
| 420 |
+
if not IS_DIVISIBLE:
|
| 421 |
+
grad_scores = tl.where(offs_n2[None, :] < KV_LEN, grad_scores, 0.0)
|
| 422 |
+
|
| 423 |
+
# ~~~~~~~~~~~~~~~~~~~ Apply other buffer grad writes ~~~~~~~~~~~~~
|
| 424 |
+
if WRITE_DQ:
|
| 425 |
+
scatter_mask = (offs_m2[:, None] < Q_LEN ) & (offs_n2[None, :] < KV_LEN)
|
| 426 |
+
{{ modification(
|
| 427 |
+
subgraph_number=3,
|
| 428 |
+
output_name=None,
|
| 429 |
+
mask="scatter_mask",
|
| 430 |
+
score="pre_mod_scores",
|
| 431 |
+
b="off_z",
|
| 432 |
+
h="off_hq",
|
| 433 |
+
m="m",
|
| 434 |
+
n="n",
|
| 435 |
+
grad_score_mod="ds"
|
| 436 |
+
) | indent_except_first(2) }}
|
| 437 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 438 |
+
ds = grad_scores
|
| 439 |
+
|
| 440 |
+
if not IS_FULL_BLOCKS:
|
| 441 |
+
# (grads) apply mask for partially unmasked block
|
| 442 |
+
ds = tl.where(mask_mod_output, ds, 0.0)
|
| 443 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 444 |
+
ds = ds.to(MATMUL_PRECISION)
|
| 445 |
+
# Compute dQ.
|
| 446 |
+
dq += tl.dot(ds, tl.trans(kT), input_precision=FLOAT32_PRECISION)
|
| 447 |
+
|
| 448 |
+
return dq
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
@triton.jit
|
| 452 |
+
def bwd_dkdv_inner(
|
| 453 |
+
{{gen_argdefs()}},
|
| 454 |
+
Q, DO, DELTA, LSE, # pointers
|
| 455 |
+
dk, dv, k, v,
|
| 456 |
+
off_z, off_hq, offs_n1, offs_m1,
|
| 457 |
+
stride_qm, stride_qd, stride_dom, stride_dod,
|
| 458 |
+
q_indices, sparse_q_num_blocks,
|
| 459 |
+
MATMUL_PRECISION,
|
| 460 |
+
IS_FULL_BLOCKS,
|
| 461 |
+
):
|
| 462 |
+
{{gen_defines() | indent_except_first(1) }}
|
| 463 |
+
SPARSE_Q_MULTIPLE: tl.constexpr = (SPARSE_Q_BLOCK_SIZE // BLOCK_M1)
|
| 464 |
+
RCP_LN2: tl.constexpr = 1.44269504
|
| 465 |
+
Q_LEN = {{size("Q", 2)}}
|
| 466 |
+
KV_LEN = {{size("K", 2)}}
|
| 467 |
+
|
| 468 |
+
offs_k = tl.arange(0, QK_HEAD_DIM_ROUNDED)
|
| 469 |
+
offs_v = tl.arange(0, V_HEAD_DIM_ROUNDED)
|
| 470 |
+
|
| 471 |
+
qT_ptrs = Q + offs_m1[None, :] * stride_qm + offs_k[:, None] * stride_qd
|
| 472 |
+
do_ptrs = DO + offs_m1[:, None] * stride_dom + offs_v[None, :] * stride_dod
|
| 473 |
+
# BLOCK_N1 must be a multiple of BLOCK_M1, otherwise the code wouldn't work.
|
| 474 |
+
tl.static_assert(BLOCK_N1 % BLOCK_M1 == 0)
|
| 475 |
+
|
| 476 |
+
# The minimum is needed to handle the case where we run with a super large
|
| 477 |
+
# SPARSE_BLOCK_SIZE (i.e. no block-mask!)
|
| 478 |
+
hi = tl.minimum(sparse_q_num_blocks * SPARSE_Q_MULTIPLE, tl.maximum(tl.cdiv(Q_LEN, BLOCK_M1), 1))
|
| 479 |
+
|
| 480 |
+
for start_m in range(0, hi):
|
| 481 |
+
dk, dv = bwd_dkdv_block_mn(
|
| 482 |
+
{{gen_argdefs()}},
|
| 483 |
+
dk, dv, qT_ptrs, k, v, do_ptrs, DELTA, LSE, Q_LEN, KV_LEN,
|
| 484 |
+
off_z, off_hq, offs_n1, offs_m1, offs_k, offs_v,
|
| 485 |
+
stride_qm, stride_qd, stride_dom, stride_dod,
|
| 486 |
+
q_indices, sparse_q_num_blocks,
|
| 487 |
+
MATMUL_PRECISION, RCP_LN2,
|
| 488 |
+
IS_FULL_BLOCKS,
|
| 489 |
+
)
|
| 490 |
+
# Increment pointers.
|
| 491 |
+
offset = get_offset_for_next_block(
|
| 492 |
+
start_m, q_indices, sparse_q_num_blocks,
|
| 493 |
+
SPARSE_Q_BLOCK_SIZE, SPARSE_Q_MULTIPLE, BLOCK_M1, BLOCKS_ARE_CONTIGUOUS
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
qT_ptrs += offset * stride_qm
|
| 497 |
+
do_ptrs += offset * stride_dom
|
| 498 |
+
offs_m1 += offset
|
| 499 |
+
|
| 500 |
+
return dk, dv
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
@triton.jit
|
| 504 |
+
def bwd_dkdv_block_mn(
|
| 505 |
+
{{gen_argdefs()}},
|
| 506 |
+
dk, dv, qT_ptrs, k, v, do_ptrs, DELTA, LSE, Q_LEN, KV_LEN,
|
| 507 |
+
off_z, off_hq, offs_n1, offs_m1, offs_k, offs_v,
|
| 508 |
+
stride_qm, stride_qd, stride_dom, stride_dod,
|
| 509 |
+
q_indices, sparse_q_num_blocks,
|
| 510 |
+
MATMUL_PRECISION, RCP_LN2,
|
| 511 |
+
IS_FULL_BLOCKS,
|
| 512 |
+
):
|
| 513 |
+
{{gen_defines() | indent_except_first(1) }}
|
| 514 |
+
|
| 515 |
+
# NB reversed order since Q is transposed
|
| 516 |
+
qT = load_checked_2d(qT_ptrs, offs_k, offs_m1, None, None, SAFE_HEAD_DIM, IS_DIVISIBLE, QK_HEAD_DIM, Q_LEN)
|
| 517 |
+
# Load LSE before computing qk to reduce pipeline stall.
|
| 518 |
+
if IS_DIVISIBLE:
|
| 519 |
+
lse = tl.load(LSE + offs_m1)
|
| 520 |
+
else:
|
| 521 |
+
lse = tl.load(LSE + offs_m1, mask=offs_m1 < Q_LEN)
|
| 522 |
+
lse = tl.where(lse == -float("inf"), 0.0, lse)
|
| 523 |
+
qkT = tl.dot(k, qT, input_precision=FLOAT32_PRECISION)
|
| 524 |
+
if not PRESCALE_QK:
|
| 525 |
+
qkT *= SM_SCALE
|
| 526 |
+
# ~~~~~~~~~~~~~~~~~~~ Apply score modification ~~~~~~~~~~~~~~~~~~~
|
| 527 |
+
m = get_bounded_indices(offs_m1[None, :], Q_LEN if not IS_DIVISIBLE else None)
|
| 528 |
+
# The boundary check is done for the outer loop, but here it's possible since we're iterating across M dim
|
| 529 |
+
# that the n reads out of bounds for the PIDS spanning the KV_LEN boundary
|
| 530 |
+
n = get_bounded_indices(offs_n1[:, None], KV_LEN if not IS_DIVISIBLE else None)
|
| 531 |
+
|
| 532 |
+
pre_mod_scores = qkT
|
| 533 |
+
{{ modification(
|
| 534 |
+
subgraph_number=0,
|
| 535 |
+
output_name="post_mod_scores",
|
| 536 |
+
score="qkT",
|
| 537 |
+
b="off_z",
|
| 538 |
+
h="off_hq",
|
| 539 |
+
m="m",
|
| 540 |
+
n="n",
|
| 541 |
+
out="qkT"
|
| 542 |
+
) | indent_except_first(1) }}
|
| 543 |
+
|
| 544 |
+
{# Note: Selective masking DK/DV
|
| 545 |
+
We load elements beyond Q_LEN w/ zero, some score mods may convert this elements to NaN
|
| 546 |
+
Example: lambda x, *_: 1 / score, this NaN would propagate regardless of other masking
|
| 547 |
+
We only need to do this on the m1 dim since these elements take part in the final reduction
|
| 548 |
+
for DK/DV #}
|
| 549 |
+
if not IS_DIVISIBLE:
|
| 550 |
+
post_mod_scores = tl.where(offs_m1[None, :] < Q_LEN, post_mod_scores, float("-inf"))
|
| 551 |
+
|
| 552 |
+
if not IS_FULL_BLOCKS:
|
| 553 |
+
{{ modification(
|
| 554 |
+
subgraph_number=2,
|
| 555 |
+
output_name="mask_mod_output",
|
| 556 |
+
b="off_z",
|
| 557 |
+
h="off_hq",
|
| 558 |
+
m="m",
|
| 559 |
+
n="n",
|
| 560 |
+
) | indent_except_first(2) }}
|
| 561 |
+
# (grads) apply mask for fully masked block
|
| 562 |
+
post_mod_scores = tl.where(mask_mod_output, post_mod_scores, float("-inf"))
|
| 563 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 564 |
+
if not PRESCALE_QK:
|
| 565 |
+
post_mod_scores *= RCP_LN2
|
| 566 |
+
pT = tl.math.exp2(post_mod_scores - lse[None, :])
|
| 567 |
+
do = load_checked_2d(do_ptrs, offs_m1, offs_v, None, None, IS_DIVISIBLE, SAFE_HEAD_DIM, Q_LEN, V_HEAD_DIM)
|
| 568 |
+
# Compute dV.
|
| 569 |
+
ppT = pT
|
| 570 |
+
dv += tl.dot(ppT.to(MATMUL_PRECISION), do, input_precision=FLOAT32_PRECISION)
|
| 571 |
+
if IS_DIVISIBLE:
|
| 572 |
+
Di = tl.load(DELTA + offs_m1)
|
| 573 |
+
else:
|
| 574 |
+
Di = tl.load(DELTA + offs_m1, mask=offs_m1 < Q_LEN)
|
| 575 |
+
# Compute dP and dS.
|
| 576 |
+
dpT = tl.dot(v, tl.trans(do), input_precision=FLOAT32_PRECISION)
|
| 577 |
+
dsT = pT * (dpT - Di[None, :])
|
| 578 |
+
# ~~~~~~~~~~~~~~~~~~~ Apply joint modification ~~~~~~~~~~~~~~~~~~~
|
| 579 |
+
{{ modification(
|
| 580 |
+
subgraph_number=1,
|
| 581 |
+
output_name = "grad_scores",
|
| 582 |
+
score="pre_mod_scores",
|
| 583 |
+
b="off_z",
|
| 584 |
+
h="off_hq",
|
| 585 |
+
m="m",
|
| 586 |
+
n="n",
|
| 587 |
+
grad_score_mod="dsT"
|
| 588 |
+
) | indent_except_first(1) }}
|
| 589 |
+
|
| 590 |
+
{# See Note: Selective masking DK/DV#}
|
| 591 |
+
if not IS_DIVISIBLE:
|
| 592 |
+
grad_scores = tl.where(offs_m1[None, :] < Q_LEN, grad_scores, 0.0)
|
| 593 |
+
|
| 594 |
+
# ~~~~~~~~~~~~~~~~~~~ Apply other buffer grad writes ~~~~~~~~~~~~~
|
| 595 |
+
if not WRITE_DQ:
|
| 596 |
+
idx_b = off_z
|
| 597 |
+
idx_h = off_hq
|
| 598 |
+
idx_m = m
|
| 599 |
+
idx_n = n
|
| 600 |
+
scatter_mask = (offs_m1[None, :] < Q_LEN) & (offs_n1[:, None] < KV_LEN)
|
| 601 |
+
{{ modification(
|
| 602 |
+
subgraph_number=3,
|
| 603 |
+
output_name=None,
|
| 604 |
+
mask="scatter_mask",
|
| 605 |
+
score="pre_mod_scores",
|
| 606 |
+
b="idx_b",
|
| 607 |
+
h="idx_h",
|
| 608 |
+
m="idx_m",
|
| 609 |
+
n="idx_n",
|
| 610 |
+
grad_score_mod="dsT"
|
| 611 |
+
) | indent_except_first(2) }}
|
| 612 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 613 |
+
dsT = grad_scores
|
| 614 |
+
if not IS_FULL_BLOCKS:
|
| 615 |
+
# (grads) apply mask for partially unmasked block
|
| 616 |
+
dsT = tl.where(mask_mod_output, dsT, 0.0)
|
| 617 |
+
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 618 |
+
dk += tl.dot(dsT.to(MATMUL_PRECISION), tl.trans(qT), input_precision=FLOAT32_PRECISION)
|
| 619 |
+
|
| 620 |
+
return dk, dv
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/flex_decode.py.jinja
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("Q", "K", "V", "M", "L", "KV_NUM_BLKS", "KV_IDX", "FULL_KV_NUM_BLKS", "FULL_KV_IDX")}}
|
| 2 |
+
# Sub notation for this kernel:
|
| 3 |
+
# Q: Query, K: Key, V: Value
|
| 4 |
+
# reduction buffers: M rowmax across local KV split, L local sumexp across local KV split
|
| 5 |
+
# M: Number of queries, N: Number of keys/values
|
| 6 |
+
# QK_HEAD_DIM: The dimension of the query and key embeddings
|
| 7 |
+
# V_HEAD_DIM: The dimension of the value embeddings
|
| 8 |
+
# BLOCK_M, QK_HEAD_DIM: M, and D dimemsion are always assigned to the same block
|
| 9 |
+
# z: Batch size, h: Number of heads, m: Number of queries per head, k: Number of keys per head t: Number of kv splits
|
| 10 |
+
# (Modifiable) Config options:
|
| 11 |
+
# SPLIT_KV: number of blocks K & V are split into
|
| 12 |
+
# TILE_KV: length of each local KV split
|
| 13 |
+
# BLOCK_M: block size that Q is padded along seqlen dim.
|
| 14 |
+
# BLOCK_N: block size of K & V along N dimension.
|
| 15 |
+
# GQA_SHARED_HEADS: number of query heads sharing one kv head in GQA setups.
|
| 16 |
+
#
|
| 17 |
+
# change of base out of the loop
|
| 18 |
+
# ROWS_GUARANTEED_SAFE: Is it guaranteed that at least one value in each row
|
| 19 |
+
# is not masked out? If so, we can skip an extra safety check
|
| 20 |
+
# SAFE_M_BOUNDARY: Is Q seqlen a multiple of BLOCK_M? If so, we can skip an extra boundary check for loading query.
|
| 21 |
+
# SAFE_N_BOUNDARY: Is KV seqlen a multiple of BLOCK_N? If so, we can skip an extra boundary check for loading key/value.
|
| 22 |
+
|
| 23 |
+
# PRESCALE_QK: Whether to pre-scale QK by 1/sqrt(d) and change of base.
|
| 24 |
+
#
|
| 25 |
+
# SPARSE_KV_BLOCK_SIZE: sparse mask block size along KV seqlen dim.
|
| 26 |
+
# KV_NUM_BLKS: The number of KV blocks (that may or may not require masking) for each query.
|
| 27 |
+
# KV_IDX: The indices of KV blocks (that may or may not require masking) for each query.
|
| 28 |
+
#
|
| 29 |
+
#
|
| 30 |
+
# Output: ACC output accumulated across local KV split.
|
| 31 |
+
|
| 32 |
+
tl.static_assert(SPARSE_KV_BLOCK_SIZE >= BLOCK_N and SPARSE_KV_BLOCK_SIZE % BLOCK_N == 0)
|
| 33 |
+
|
| 34 |
+
# Define Q Strides
|
| 35 |
+
stride_qz, stride_qh, stride_qg, stride_qm, stride_qk = {{stride("Q")}}
|
| 36 |
+
stride_kz, stride_kh, stride_kn, stride_kk = {{stride("K")}}
|
| 37 |
+
stride_vz, stride_vh, stride_vn, stride_vk = {{stride("V")}}
|
| 38 |
+
stride_mz, stride_mt, stride_mh, stride_mm = {{stride("M")}}
|
| 39 |
+
stride_lz, stride_lt, stride_lh, stride_lm = {{stride("L")}}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
Z = {{size("Q", 0)}}
|
| 43 |
+
ZKV = {{size("K", 0)}}
|
| 44 |
+
HKV = {{size("Q", 1)}}
|
| 45 |
+
G: tl.constexpr = GQA_SHARED_HEADS
|
| 46 |
+
HQ = HKV * G
|
| 47 |
+
Q_LEN = {{size("Q", 3)}}
|
| 48 |
+
KV_LEN = {{size("K", 2)}}
|
| 49 |
+
|
| 50 |
+
MATMUL_PRECISION = Q.dtype.element_ty
|
| 51 |
+
|
| 52 |
+
# Make sure each split is a multiple of BLOCK_N
|
| 53 |
+
TILE_KV_OG = tl.cdiv(KV_LEN, SPLIT_KV)
|
| 54 |
+
TILE_KV = tl.cdiv(TILE_KV_OG, BLOCK_N) * BLOCK_N
|
| 55 |
+
TILE_KV_MULTIPLE: tl.constexpr = (TILE_KV // BLOCK_N)
|
| 56 |
+
|
| 57 |
+
off_z = tl.program_id(0).to(INDEX_DTYPE) // HKV
|
| 58 |
+
off_zkv = off_z % ZKV
|
| 59 |
+
off_hkv = tl.program_id(0).to(INDEX_DTYPE) % HKV
|
| 60 |
+
off_t = tl.program_id(1).to(INDEX_DTYPE)
|
| 61 |
+
|
| 62 |
+
q_offset = off_z * stride_qz + off_hkv * stride_qh
|
| 63 |
+
k_offset = off_zkv * stride_kz + off_hkv * stride_kh
|
| 64 |
+
v_offset = off_zkv * stride_vz + off_hkv * stride_vh
|
| 65 |
+
|
| 66 |
+
K = K + k_offset
|
| 67 |
+
V = V + v_offset
|
| 68 |
+
|
| 69 |
+
SPARSE_Z = {{size("KV_NUM_BLKS", 0)}}
|
| 70 |
+
SPARSE_HQ = {{size("KV_NUM_BLKS", 1)}}
|
| 71 |
+
|
| 72 |
+
sparse_idx_z = off_z % SPARSE_Z
|
| 73 |
+
sparse_idx_h = off_hkv % SPARSE_HQ
|
| 74 |
+
|
| 75 |
+
SPARSE_KV_MULTIPLE: tl.constexpr = (SPARSE_KV_BLOCK_SIZE // BLOCK_N)
|
| 76 |
+
SPARSE_KV_BLOCK_CNT = tl.cdiv(KV_LEN, SPARSE_KV_BLOCK_SIZE)
|
| 77 |
+
|
| 78 |
+
# initialize pointer to m and l
|
| 79 |
+
m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf")
|
| 80 |
+
l_i = tl.zeros([BLOCK_M], dtype=tl.float32)
|
| 81 |
+
acc = tl.zeros([BLOCK_M, V_HEAD_DIM_ROUNDED], dtype=tl.float32)
|
| 82 |
+
|
| 83 |
+
# initialize offsets
|
| 84 |
+
tl.device_assert(BLOCK_M % G == 0)
|
| 85 |
+
BLOCK_M_PER_HQ: tl.constexpr = BLOCK_M // G
|
| 86 |
+
off_g = tl.arange(0, G) # [G]
|
| 87 |
+
offs_g = tl.ravel(tl.broadcast_to(off_g[:, None], [G, BLOCK_M_PER_HQ])) # [BLOCK_M]
|
| 88 |
+
offs_hq = offs_g + off_hkv * G
|
| 89 |
+
off_m = tl.arange(0, BLOCK_M_PER_HQ) # [BLOCK_M_PER_HQ]
|
| 90 |
+
offs_m = tl.ravel(tl.broadcast_to(off_m[None, :], [G, BLOCK_M_PER_HQ])) # [BLOCK_M]
|
| 91 |
+
offs_d = tl.arange(0, QK_HEAD_DIM_ROUNDED)
|
| 92 |
+
offs_vd = tl.arange(0, V_HEAD_DIM_ROUNDED)
|
| 93 |
+
|
| 94 |
+
# Get HZ offsets for KV_NUM_BLKS and KV_IDX
|
| 95 |
+
stride_block_z, stride_block_h, stride_block_row = {{stride("KV_NUM_BLKS")}}
|
| 96 |
+
sparse_block_hz_offset = sparse_idx_z * stride_block_z + sparse_idx_h * stride_block_h
|
| 97 |
+
stride_kv_z, stride_kv_h, stride_kv_row, stride_kv_col = {{stride("KV_IDX")}}
|
| 98 |
+
sparse_idx_hz_offset = sparse_idx_z * stride_kv_z + sparse_idx_h * stride_kv_h
|
| 99 |
+
|
| 100 |
+
# Calculate KV blocks that belong this CTA.
|
| 101 |
+
block_n_start = off_t * TILE_KV_MULTIPLE # n_offset inside sparse block
|
| 102 |
+
block_n_end = block_n_start + TILE_KV_MULTIPLE # end BLOCK_N
|
| 103 |
+
|
| 104 |
+
q_range = stride_qg * off_g[:, None, None] + stride_qm * off_m[None, :, None] + stride_qk * offs_d[None, None, :]
|
| 105 |
+
|
| 106 |
+
if not SAFE_M_BOUNDARY and not SAFE_HEAD_DIM:
|
| 107 |
+
q = tl.load(Q + q_offset + q_range, mask=(offs_d[None, None, :] < QK_HEAD_DIM) & (off_m[None, :, None] < Q_LEN))
|
| 108 |
+
elif SAFE_M_BOUNDARY and not SAFE_HEAD_DIM:
|
| 109 |
+
q = tl.load(Q + q_offset + q_range, mask=offs_d[None, None, :] < QK_HEAD_DIM)
|
| 110 |
+
elif not SAFE_M_BOUNDARY and SAFE_HEAD_DIM:
|
| 111 |
+
q = tl.load(Q + q_offset + q_range, mask=off_m[None, :, None] < Q_LEN)
|
| 112 |
+
else:
|
| 113 |
+
q = tl.load(Q + q_offset + q_range)
|
| 114 |
+
|
| 115 |
+
q = tl.reshape(q, [BLOCK_M, QK_HEAD_DIM_ROUNDED])
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
# ~~~~~~~~~~~~~~ normal blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 119 |
+
# find first kv block we are loading and the number of blocks we are loading
|
| 120 |
+
# Offset the kv_indices tensor by the correct batch and head
|
| 121 |
+
kv_indices = KV_IDX + sparse_idx_hz_offset
|
| 122 |
+
kv_num_blocks = tl.load(KV_NUM_BLKS + sparse_block_hz_offset)
|
| 123 |
+
MAX_KV_IDX = {{size("KV_IDX", -1)}}
|
| 124 |
+
indices_idx = (block_n_start // SPARSE_KV_MULTIPLE) % (MAX_KV_IDX)
|
| 125 |
+
off_n_block_in_sparse = block_n_start % SPARSE_KV_MULTIPLE
|
| 126 |
+
off_n = tl.load(kv_indices + indices_idx) * SPARSE_KV_BLOCK_SIZE + off_n_block_in_sparse * BLOCK_N
|
| 127 |
+
# first kv block we're loading
|
| 128 |
+
|
| 129 |
+
# last valid block according to sparse mask
|
| 130 |
+
block_n_last_valid = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1))
|
| 131 |
+
|
| 132 |
+
offs_n = tl.arange(0, BLOCK_N) + off_n
|
| 133 |
+
|
| 134 |
+
desc_k = None
|
| 135 |
+
desc_v = None
|
| 136 |
+
{%- if USE_TMA %}
|
| 137 |
+
desc_k = tl.make_tensor_descriptor(
|
| 138 |
+
base=K,
|
| 139 |
+
shape=[KV_LEN, QK_HEAD_DIM],
|
| 140 |
+
strides=[stride_kn, 1],
|
| 141 |
+
block_shape=[BLOCK_N, QK_HEAD_DIM_ROUNDED],
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
desc_v = tl.make_tensor_descriptor(
|
| 145 |
+
base=V,
|
| 146 |
+
shape=[KV_LEN, V_HEAD_DIM],
|
| 147 |
+
strides=[stride_vn, 1],
|
| 148 |
+
block_shape=[BLOCK_N, V_HEAD_DIM_ROUNDED],
|
| 149 |
+
)
|
| 150 |
+
{%- endif %}
|
| 151 |
+
|
| 152 |
+
acc, l_i, m_i = forward_inner(
|
| 153 |
+
{{gen_argdefs()}},
|
| 154 |
+
q, K, V, desc_k, desc_v, Q_LEN, KV_LEN,
|
| 155 |
+
# accumulatd values
|
| 156 |
+
acc, l_i, m_i,
|
| 157 |
+
#offsets
|
| 158 |
+
off_z, offs_hq[:, None], offs_m[:, None], offs_n[None, :],
|
| 159 |
+
off_n,
|
| 160 |
+
#block sparse data
|
| 161 |
+
kv_indices, kv_num_blocks,
|
| 162 |
+
block_n_start, block_n_end if block_n_end <= block_n_last_valid else block_n_last_valid,
|
| 163 |
+
MATMUL_PRECISION,
|
| 164 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 165 |
+
IS_FULL_BLOCKS=False,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# ~~~~~~~~~~~~~~ "full" blocks ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 170 |
+
# We know these blocks are guaranteed to be "full", so we don't need to
|
| 171 |
+
# apply mask_mod to them - only score_mod
|
| 172 |
+
if HAS_FULL_BLOCKS:
|
| 173 |
+
kv_indices = FULL_KV_IDX + sparse_idx_hz_offset
|
| 174 |
+
kv_num_blocks = tl.load(FULL_KV_NUM_BLKS + sparse_block_hz_offset)
|
| 175 |
+
# Assign full block in a reverse order for off_t. Prioritize the last CTA.
|
| 176 |
+
block_n_start = (SPLIT_KV - off_t - 1) * TILE_KV_MULTIPLE
|
| 177 |
+
block_n_end = block_n_start + TILE_KV_MULTIPLE
|
| 178 |
+
indices_idx = (block_n_start // SPARSE_KV_MULTIPLE) % (MAX_KV_IDX)
|
| 179 |
+
off_n_block_in_sparse = block_n_start % SPARSE_KV_MULTIPLE
|
| 180 |
+
off_n = tl.load(kv_indices + indices_idx) * SPARSE_KV_BLOCK_SIZE + off_n_block_in_sparse * BLOCK_N
|
| 181 |
+
|
| 182 |
+
# last valid block according to sparse mask
|
| 183 |
+
block_n_last_valid = tl.minimum(kv_num_blocks * SPARSE_KV_MULTIPLE, tl.maximum(tl.cdiv(KV_LEN, BLOCK_N), 1))
|
| 184 |
+
|
| 185 |
+
offs_n = tl.arange(0, BLOCK_N) + off_n
|
| 186 |
+
|
| 187 |
+
acc, l_i, m_i = forward_inner(
|
| 188 |
+
{{gen_argdefs()}},
|
| 189 |
+
q, K, V, desc_k, desc_v, Q_LEN, KV_LEN,
|
| 190 |
+
# accumulatd values
|
| 191 |
+
acc, l_i, m_i,
|
| 192 |
+
#offsets
|
| 193 |
+
off_z, offs_hq[:, None], offs_m[:, None], offs_n[None, :],
|
| 194 |
+
off_n,
|
| 195 |
+
#block sparse data
|
| 196 |
+
kv_indices, kv_num_blocks,
|
| 197 |
+
block_n_start, block_n_end if block_n_end <= block_n_last_valid else block_n_last_valid,
|
| 198 |
+
MATMUL_PRECISION,
|
| 199 |
+
stride_kk, stride_kn, stride_vn, stride_vk,
|
| 200 |
+
IS_FULL_BLOCKS=True,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
m_offset = off_t * stride_mt + off_z * stride_mz
|
| 204 |
+
l_offset = off_t * stride_lt + off_z * stride_lz
|
| 205 |
+
|
| 206 |
+
M_block_ptr = tl.make_block_ptr(
|
| 207 |
+
base=M + m_offset,
|
| 208 |
+
shape=(G, Q_LEN), # (G, M)
|
| 209 |
+
strides=(stride_mh, stride_mm),
|
| 210 |
+
offsets=(off_hkv*G, 0),
|
| 211 |
+
block_shape=(G, BLOCK_M_PER_HQ),
|
| 212 |
+
order=(1, 0)
|
| 213 |
+
)
|
| 214 |
+
L_block_ptr = tl.make_block_ptr(
|
| 215 |
+
base=L + l_offset,
|
| 216 |
+
shape=(G, Q_LEN), # (G, M)
|
| 217 |
+
strides=(stride_lh, stride_lm),
|
| 218 |
+
offsets=(off_hkv*G, 0),
|
| 219 |
+
block_shape=(G, BLOCK_M_PER_HQ),
|
| 220 |
+
order=(1, 0)
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# Store output, logsumexp and rowmax for cross CTA reduction. (all in float32, even when input data are in fp16)
|
| 224 |
+
m_i = m_i.reshape(G, BLOCK_M_PER_HQ)
|
| 225 |
+
l_i = l_i.reshape(G, BLOCK_M_PER_HQ)
|
| 226 |
+
if SAFE_M_BOUNDARY:
|
| 227 |
+
tl.store(M_block_ptr, m_i)
|
| 228 |
+
tl.store(L_block_ptr, l_i)
|
| 229 |
+
else:
|
| 230 |
+
tl.store(M_block_ptr, m_i, boundary_check=(1,))
|
| 231 |
+
tl.store(L_block_ptr, l_i, boundary_check=(1,))
|
| 232 |
+
|
| 233 |
+
# -- store output
|
| 234 |
+
idx_z = off_z
|
| 235 |
+
idx_t = off_t
|
| 236 |
+
idx_hq = off_hkv*G + off_g[:, None, None]
|
| 237 |
+
idx_m = off_m[None, :, None]
|
| 238 |
+
idx_d = offs_vd[None, None, :]
|
| 239 |
+
|
| 240 |
+
mask = (idx_m < Q_LEN) & (idx_d < V_HEAD_DIM)
|
| 241 |
+
acc = acc.reshape(G, BLOCK_M_PER_HQ, V_HEAD_DIM)
|
| 242 |
+
{{store_output(("idx_z", "idx_t", "idx_hq", "idx_m", "idx_d"), "acc", "mask", val_shape=("GQA_SHARED_HEADS", "BLOCK_M_PER_HQ", "V_HEAD_DIM"))}}
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/flex/templates/utilities.py.jinja
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
# Utility triton funcs
|
| 4 |
+
@triton.jit
|
| 5 |
+
def get_offset_for_next_block(
|
| 6 |
+
loop_iter, col_indices, total_blocks,
|
| 7 |
+
SPARSE_BLOCK, SPARSE_BLOCK_MULTIPLE, BLOCK,
|
| 8 |
+
BLOCKS_ARE_CONTIGUOUS: tl.constexpr
|
| 9 |
+
):
|
| 10 |
+
if BLOCKS_ARE_CONTIGUOUS:
|
| 11 |
+
return BLOCK
|
| 12 |
+
cur_block_idx = loop_iter // SPARSE_BLOCK_MULTIPLE
|
| 13 |
+
cur_block = tl.load(col_indices + cur_block_idx, eviction_policy="evict_last")
|
| 14 |
+
next_block = tl.load(col_indices + cur_block_idx + 1, eviction_policy="evict_last", mask=cur_block_idx + 1 < total_blocks)
|
| 15 |
+
needs_jump = (loop_iter + 1) % SPARSE_BLOCK_MULTIPLE == 0
|
| 16 |
+
jump_to_block = (next_block - cur_block ) * SPARSE_BLOCK - (SPARSE_BLOCK_MULTIPLE - 1) * BLOCK
|
| 17 |
+
offset = jump_to_block * needs_jump + (1 - needs_jump) * BLOCK
|
| 18 |
+
return offset
|
| 19 |
+
|
| 20 |
+
@triton.jit
|
| 21 |
+
def get_bounded_indices(indices, max_len=None):
|
| 22 |
+
return indices % max_len if max_len is not None else indices
|
| 23 |
+
|
| 24 |
+
@triton.jit
|
| 25 |
+
def load_checked_block(block_ptr, IS_DIVISIBLE: tl.constexpr, SAFE_HEAD_DIM: tl.constexpr):
|
| 26 |
+
if IS_DIVISIBLE and SAFE_HEAD_DIM:
|
| 27 |
+
return tl.load(block_ptr)
|
| 28 |
+
elif IS_DIVISIBLE and not SAFE_HEAD_DIM:
|
| 29 |
+
return tl.load(block_ptr, boundary_check=(1,), padding_option="zero")
|
| 30 |
+
elif not IS_DIVISIBLE and SAFE_HEAD_DIM:
|
| 31 |
+
return tl.load(block_ptr, boundary_check=(0,), padding_option="zero")
|
| 32 |
+
else:
|
| 33 |
+
return tl.load(block_ptr, boundary_check=(0, 1), padding_option="zero")
|
| 34 |
+
|
| 35 |
+
@triton.jit
|
| 36 |
+
def load_checked_2d(
|
| 37 |
+
ptr,
|
| 38 |
+
offs_m,
|
| 39 |
+
offs_n,
|
| 40 |
+
stride_m,
|
| 41 |
+
stride_n,
|
| 42 |
+
IS_DIVISIBLE_M: tl.constexpr,
|
| 43 |
+
IS_DIVISIBLE_N: tl.constexpr,
|
| 44 |
+
M_LEN: tl.constexpr,
|
| 45 |
+
N_LEN: tl.constexpr,
|
| 46 |
+
):
|
| 47 |
+
# Calculate final pointer if strides are provided
|
| 48 |
+
if stride_m is not None and stride_n is not None:
|
| 49 |
+
ptr = ptr + offs_m[:, None] * stride_m + offs_n[None, :] * stride_n
|
| 50 |
+
|
| 51 |
+
# Handle all masking cases
|
| 52 |
+
if not IS_DIVISIBLE_M and not IS_DIVISIBLE_N:
|
| 53 |
+
return tl.load(ptr, mask=(offs_m[:, None] < M_LEN) & (offs_n[None, :] < N_LEN), other=0.0)
|
| 54 |
+
elif IS_DIVISIBLE_M and not IS_DIVISIBLE_N:
|
| 55 |
+
return tl.load(ptr, mask=(offs_n[None, :] < N_LEN), other=0.0)
|
| 56 |
+
elif not IS_DIVISIBLE_M and IS_DIVISIBLE_N:
|
| 57 |
+
return tl.load(ptr, mask=(offs_m[:, None] < M_LEN), other=0.0)
|
| 58 |
+
else: # Both divisible
|
| 59 |
+
return tl.load(ptr)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/cutedsl_mm_grouped.py.jinja
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
from torch._inductor.runtime.runtime_utils import ceildiv
|
| 3 |
+
from cutlass.utils import TensorMapUpdateMode
|
| 4 |
+
{{gen_defines()}}
|
| 5 |
+
# ---- Import GroupedGemm implementation, copied on PyTorch build from Cutlass repository: cutlass/examples/python/CuTeDSL/blackwell/grouped_gemm.py ----
|
| 6 |
+
from torch._inductor.kernel.vendored_templates.cutedsl_grouped_gemm import (
|
| 7 |
+
GroupedGemmKernel,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Note about caching:
|
| 12 |
+
# Each instantiated CuTeDSL grouped GEMM kernel file generated by Inductor
|
| 13 |
+
# maintains its own local caching system. At this stage, all compile-time
|
| 14 |
+
# constexprs (e.g., TILE_M, TILE_N, CLUSTER_M/N, USE_2_CTA) and the kernel
|
| 15 |
+
# name itself ({{kernel_name}}) are permanently baked into the file, so they
|
| 16 |
+
# do not need to be included in any cache key.
|
| 17 |
+
#
|
| 18 |
+
# The caching mechanism is split into two levels:
|
| 19 |
+
#
|
| 20 |
+
# 1. prep_cache
|
| 21 |
+
# Caches the compiled executor for build_group_ptrs_from_bases(). This
|
| 22 |
+
# kernel depends only on the tensor shapes, strides, and dtypes of A/B/C,
|
| 23 |
+
# and can therefore be safely reused across runs with different group
|
| 24 |
+
# partitioning (`offs`).
|
| 25 |
+
#
|
| 26 |
+
# 2. gemm_cache
|
| 27 |
+
# Caches the compiled Grouped GEMM executor. Its key extends the prep
|
| 28 |
+
# cache key with hardware- and grid-specific parameters:
|
| 29 |
+
# (prep_cache_key, max_active_clusters, total_num_clusters).
|
| 30 |
+
# This is necessary because different `offs` tensors can change the
|
| 31 |
+
# per-group problem sizes and thus alter `total_num_clusters`, which in
|
| 32 |
+
# turn changes the grid shape and persistent scheduler configuration.
|
| 33 |
+
# Kernels compiled for one grid cannot be safely reused for another.
|
| 34 |
+
#
|
| 35 |
+
#
|
| 36 |
+
# Additionally, note the @lru_cache decorator on get_hardware_info(). Empirically,
|
| 37 |
+
# hw.get_max_active_clusters() triggers significant MLIR recompilation overhead,
|
| 38 |
+
# despite depending only on the GPU type. We cache this function to mitigate
|
| 39 |
+
# redundant recompiles even when shape/stride/dtype cache misses force kernel
|
| 40 |
+
# regeneration. A follow-up study will investigate the root cause.
|
| 41 |
+
|
| 42 |
+
prep_cache = {}
|
| 43 |
+
gemm_cache = {}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@functools.lru_cache
|
| 47 |
+
def get_hardware_info():
|
| 48 |
+
hw = cutlass.utils.HardwareInfo()
|
| 49 |
+
sm_count = hw.get_max_active_clusters(1)
|
| 50 |
+
max_active_clusters = hw.get_max_active_clusters(CLUSTER_M * CLUSTER_N)
|
| 51 |
+
|
| 52 |
+
return (sm_count, max_active_clusters)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_prep_cache_key(input_a, input_b, output):
|
| 56 |
+
"""
|
| 57 |
+
Returns a tuple key for caching the preprocessing kernel executor based on kernel name,
|
| 58 |
+
shapes, strides, and dtypes of input/output tensors.
|
| 59 |
+
"""
|
| 60 |
+
return (
|
| 61 |
+
tuple(input_a.shape),
|
| 62 |
+
tuple(input_a.stride()),
|
| 63 |
+
input_a.dtype,
|
| 64 |
+
tuple(input_b.shape),
|
| 65 |
+
tuple(input_b.stride()),
|
| 66 |
+
input_b.dtype,
|
| 67 |
+
tuple(output.shape),
|
| 68 |
+
tuple(output.stride()),
|
| 69 |
+
output.dtype,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def get_gemm_cache_key(prep_cache_key, max_active_clusters, total_num_clusters):
|
| 74 |
+
"""
|
| 75 |
+
Returns a tuple key for caching the gemm kernel executor by extending the
|
| 76 |
+
prep cache key with hardware- and grid-specific parameters.
|
| 77 |
+
"""
|
| 78 |
+
return (
|
| 79 |
+
prep_cache_key,
|
| 80 |
+
max_active_clusters,
|
| 81 |
+
total_num_clusters,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
@cute.kernel
|
| 86 |
+
def build_group_ptrs_from_bases_kernel(
|
| 87 |
+
base_A_u64: cutlass.Int64, # device addr of input_a (bytes)
|
| 88 |
+
base_B_u64: cutlass.Int64, # device addr of input_b (bytes)
|
| 89 |
+
base_C_u64: cutlass.Int64, # device addr of Output (bytes)
|
| 90 |
+
offs: cute.Tensor, # [G], cutlass.Int32/64 cumulative
|
| 91 |
+
K: cutlass.Constexpr,
|
| 92 |
+
N: cutlass.Constexpr,
|
| 93 |
+
sizeof_element: cutlass.Int32, # bytes
|
| 94 |
+
# -------- STRIDES (in ELEMENTS) --------
|
| 95 |
+
stride_A_m_elems: cutlass.Constexpr, # A.stride(0)
|
| 96 |
+
stride_A_k_elems: cutlass.Constexpr, # A.stride(1)
|
| 97 |
+
stride_B0_elems: cutlass.Constexpr, # B.stride(0)
|
| 98 |
+
stride_Bk_elems: cutlass.Constexpr, # B.stride(1)
|
| 99 |
+
stride_Bn_elems: cutlass.Constexpr, # B.stride(2)
|
| 100 |
+
stride_C_m_elems: cutlass.Constexpr, # C.stride(0)
|
| 101 |
+
stride_C_n_elems: cutlass.Constexpr, # C.stride(1)
|
| 102 |
+
# -------- OUTPUTS --------
|
| 103 |
+
out_ptrs: cute.Tensor, # [G,3] cutlass.Int64: (A_ptr, B_ptr, C_ptr)
|
| 104 |
+
out_problem: cute.Tensor, # [G,4] cutlass.Int32: (m_g, n, k, 1)
|
| 105 |
+
out_strides_abc: cute.Tensor, # [G,3,2] cutlass.Int32 [[A_m,A_k],[B_n,B_k],[C_m,C_n]]
|
| 106 |
+
):
|
| 107 |
+
tidx, _, _ = cute.arch.thread_idx()
|
| 108 |
+
g = tidx
|
| 109 |
+
|
| 110 |
+
m_beg_i32 = 0
|
| 111 |
+
if g > 0:
|
| 112 |
+
m_beg_i32 = offs[g - 1]
|
| 113 |
+
m_end_i32 = offs[g]
|
| 114 |
+
m_g_i32 = m_end_i32 - m_beg_i32
|
| 115 |
+
|
| 116 |
+
a_byte_off = (
|
| 117 |
+
cutlass.Int64(m_beg_i32) * stride_A_m_elems * cutlass.Int64(sizeof_element)
|
| 118 |
+
)
|
| 119 |
+
c_byte_off = (
|
| 120 |
+
cutlass.Int64(m_beg_i32) * stride_C_m_elems * cutlass.Int64(sizeof_element)
|
| 121 |
+
)
|
| 122 |
+
b_byte_off = cutlass.Int64(g) * stride_B0_elems * cutlass.Int64(sizeof_element)
|
| 123 |
+
|
| 124 |
+
# ---- pointers ----
|
| 125 |
+
out_ptrs[g, 0] = base_A_u64 + a_byte_off
|
| 126 |
+
out_ptrs[g, 1] = base_B_u64 + b_byte_off
|
| 127 |
+
out_ptrs[g, 2] = base_C_u64 + c_byte_off
|
| 128 |
+
|
| 129 |
+
# ---- (m, n, k, 1) ----
|
| 130 |
+
out_problem[g, 0] = m_g_i32
|
| 131 |
+
out_problem[g, 1] = N
|
| 132 |
+
out_problem[g, 2] = K
|
| 133 |
+
out_problem[g, 3] = cutlass.Int32(1)
|
| 134 |
+
|
| 135 |
+
# ---- strides ----
|
| 136 |
+
out_strides_abc[g, 0, 0] = cutlass.Int32(stride_A_m_elems)
|
| 137 |
+
out_strides_abc[g, 0, 1] = cutlass.Int32(stride_A_k_elems)
|
| 138 |
+
out_strides_abc[g, 1, 0] = cutlass.Int32(stride_Bn_elems)
|
| 139 |
+
out_strides_abc[g, 1, 1] = cutlass.Int32(stride_Bk_elems)
|
| 140 |
+
out_strides_abc[g, 2, 0] = cutlass.Int32(stride_C_m_elems)
|
| 141 |
+
out_strides_abc[g, 2, 1] = cutlass.Int32(stride_C_n_elems)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@cute.jit
|
| 145 |
+
def launch_build_group_ptrs_from_bases(
|
| 146 |
+
base_A_u64: cutlass.Int64,
|
| 147 |
+
base_B_u64: cutlass.Int64,
|
| 148 |
+
base_C_u64: cutlass.Int64,
|
| 149 |
+
offs: cute.Tensor,
|
| 150 |
+
G: cutlass.Constexpr,
|
| 151 |
+
K: cutlass.Constexpr,
|
| 152 |
+
N: cutlass.Constexpr,
|
| 153 |
+
sizeof_element: cutlass.Constexpr,
|
| 154 |
+
stride_A_m_elems: cutlass.Constexpr,
|
| 155 |
+
stride_A_k_elems: cutlass.Constexpr,
|
| 156 |
+
stride_B0_elems: cutlass.Constexpr,
|
| 157 |
+
stride_Bk_elems: cutlass.Constexpr,
|
| 158 |
+
stride_Bn_elems: cutlass.Constexpr,
|
| 159 |
+
stride_C_m_elems: cutlass.Constexpr,
|
| 160 |
+
stride_C_n_elems: cutlass.Constexpr,
|
| 161 |
+
out_ptrs: cute.Tensor, # [G,3] cutlass.Int64
|
| 162 |
+
out_problem: cute.Tensor, # [G,4] cutlass.Int32
|
| 163 |
+
out_strides_abc: cute.Tensor, # [3,2] cutlass.Int32
|
| 164 |
+
stream: cuda.CUstream,
|
| 165 |
+
):
|
| 166 |
+
build_group_ptrs_from_bases_kernel(
|
| 167 |
+
base_A_u64,
|
| 168 |
+
base_B_u64,
|
| 169 |
+
base_C_u64,
|
| 170 |
+
offs,
|
| 171 |
+
K,
|
| 172 |
+
N,
|
| 173 |
+
sizeof_element,
|
| 174 |
+
stride_A_m_elems,
|
| 175 |
+
stride_A_k_elems,
|
| 176 |
+
stride_B0_elems,
|
| 177 |
+
stride_Bk_elems,
|
| 178 |
+
stride_Bn_elems,
|
| 179 |
+
stride_C_m_elems,
|
| 180 |
+
stride_C_n_elems,
|
| 181 |
+
out_ptrs,
|
| 182 |
+
out_problem,
|
| 183 |
+
out_strides_abc,
|
| 184 |
+
).launch(grid=(1, 1, 1), block=(G, 1, 1), stream=stream)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
{{def_kernel("input_a", "input_b", "input_a_offs")}}
|
| 188 |
+
stream = cuda.CUstream(stream)
|
| 189 |
+
|
| 190 |
+
input_b = input_b.transpose(1, 2)
|
| 191 |
+
|
| 192 |
+
sumM, K = input_a.shape
|
| 193 |
+
G, N, Kb = input_b.shape
|
| 194 |
+
|
| 195 |
+
dev = input_a.device
|
| 196 |
+
|
| 197 |
+
base_A_u64 = int(input_a.data_ptr())
|
| 198 |
+
base_B_u64 = int(input_b.data_ptr())
|
| 199 |
+
base_C_u64 = int({{get_output()}}.data_ptr())
|
| 200 |
+
|
| 201 |
+
ptrs_t = torch.empty((G, 3), device=dev, dtype=torch.int64)
|
| 202 |
+
probs_t = torch.empty((G, 4), device=dev, dtype=torch.int32)
|
| 203 |
+
strides_t = torch.empty((G, 3, 2), device=dev, dtype=torch.int32)
|
| 204 |
+
ptrs = from_dlpack(ptrs_t)
|
| 205 |
+
probs = from_dlpack(probs_t)
|
| 206 |
+
strides = from_dlpack(strides_t)
|
| 207 |
+
|
| 208 |
+
prep_cache_key = get_prep_cache_key(input_a, input_b, {{get_output()}})
|
| 209 |
+
prep_executor = prep_cache.get(prep_cache_key)
|
| 210 |
+
|
| 211 |
+
if prep_executor is None:
|
| 212 |
+
sizeof_element = int(input_a.element_size())
|
| 213 |
+
sA_m, sA_k = map(int, input_a.stride())
|
| 214 |
+
sB_0, sB_n, sB_k = map(int, input_b.stride())
|
| 215 |
+
sC_m, sC_n = map(int, {{get_output()}}.stride())
|
| 216 |
+
|
| 217 |
+
prep_executor = cute.compile(
|
| 218 |
+
launch_build_group_ptrs_from_bases,
|
| 219 |
+
base_A_u64=base_A_u64,
|
| 220 |
+
base_B_u64=base_B_u64,
|
| 221 |
+
base_C_u64=base_C_u64,
|
| 222 |
+
offs=from_dlpack(input_a_offs),
|
| 223 |
+
G=int(G),
|
| 224 |
+
K=int(K),
|
| 225 |
+
N=int(N),
|
| 226 |
+
sizeof_element=sizeof_element,
|
| 227 |
+
stride_A_m_elems=sA_m,
|
| 228 |
+
stride_A_k_elems=sA_k,
|
| 229 |
+
stride_B0_elems=sB_0,
|
| 230 |
+
stride_Bk_elems=sB_k,
|
| 231 |
+
stride_Bn_elems=sB_n,
|
| 232 |
+
stride_C_m_elems=sC_m,
|
| 233 |
+
stride_C_n_elems=sC_n,
|
| 234 |
+
out_ptrs=ptrs,
|
| 235 |
+
out_problem=probs,
|
| 236 |
+
out_strides_abc=strides,
|
| 237 |
+
stream=stream,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
prep_cache[prep_cache_key] = prep_executor
|
| 241 |
+
|
| 242 |
+
prep_executor(
|
| 243 |
+
base_A_u64=base_A_u64,
|
| 244 |
+
base_B_u64=base_B_u64,
|
| 245 |
+
base_C_u64=base_C_u64,
|
| 246 |
+
offs=from_dlpack(input_a_offs),
|
| 247 |
+
out_ptrs=ptrs,
|
| 248 |
+
out_problem=probs,
|
| 249 |
+
out_strides_abc=strides,
|
| 250 |
+
stream=stream,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# --- Tensormap workspace per SM ---
|
| 254 |
+
num_tensormap_buffers, max_active_clusters = get_hardware_info()
|
| 255 |
+
tensormap_shape = (
|
| 256 |
+
num_tensormap_buffers,
|
| 257 |
+
GroupedGemmKernel.num_tensormaps,
|
| 258 |
+
GroupedGemmKernel.bytes_per_tensormap // 8,
|
| 259 |
+
)
|
| 260 |
+
tensormap_workspace_t = torch.empty(tensormap_shape, device=dev, dtype=torch.int64)
|
| 261 |
+
tensormap_workspace = from_dlpack(tensormap_workspace_t)
|
| 262 |
+
|
| 263 |
+
# --- Total clusters ---
|
| 264 |
+
def compute_total_num_clusters(
|
| 265 |
+
problem_sizes_mnkl,
|
| 266 |
+
cluster_tile_shape_mn,
|
| 267 |
+
):
|
| 268 |
+
total_num_clusters = 0
|
| 269 |
+
for m, n, _, _ in problem_sizes_mnkl:
|
| 270 |
+
num_clusters_mn = tuple(
|
| 271 |
+
ceildiv(x, y) for x, y in zip((m, n), cluster_tile_shape_mn)
|
| 272 |
+
)
|
| 273 |
+
total_num_clusters += functools.reduce(lambda x, y: x * y, num_clusters_mn)
|
| 274 |
+
return total_num_clusters
|
| 275 |
+
|
| 276 |
+
# Compute cluster tile shape
|
| 277 |
+
def compute_cluster_tile_shape(
|
| 278 |
+
mma_tiler_mn,
|
| 279 |
+
cluster_shape_mn,
|
| 280 |
+
use_2cta_instrs,
|
| 281 |
+
):
|
| 282 |
+
cta_tile_shape_mn = list(mma_tiler_mn)
|
| 283 |
+
if use_2cta_instrs:
|
| 284 |
+
cta_tile_shape_mn[0] = cta_tile_shape_mn[0] // 2
|
| 285 |
+
return tuple(x * y for x, y in zip(cta_tile_shape_mn, cluster_shape_mn))
|
| 286 |
+
|
| 287 |
+
cluster_tile_shape_mn = compute_cluster_tile_shape(
|
| 288 |
+
(TILE_M, TILE_N), (CLUSTER_M, CLUSTER_N), bool(USE_2_CTA)
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
total_num_clusters = int(compute_total_num_clusters(probs_t, cluster_tile_shape_mn))
|
| 292 |
+
|
| 293 |
+
gemm_cache_key = get_gemm_cache_key(
|
| 294 |
+
prep_cache_key, max_active_clusters, total_num_clusters
|
| 295 |
+
)
|
| 296 |
+
gemm_executor = gemm_cache.get(gemm_cache_key)
|
| 297 |
+
|
| 298 |
+
if gemm_executor is None:
|
| 299 |
+
grouped_gemm = GroupedGemmKernel(
|
| 300 |
+
acc_dtype=ACC_DTYPE,
|
| 301 |
+
use_2cta_instrs=USE_2_CTA,
|
| 302 |
+
mma_tiler_mn=(TILE_M, TILE_N),
|
| 303 |
+
cluster_shape_mn=(CLUSTER_M, CLUSTER_N),
|
| 304 |
+
tensormap_update_mode=TENSORMAP_UPDATE_MODE,
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
gemm_executor = cute.compile(
|
| 308 |
+
grouped_gemm,
|
| 309 |
+
from_dlpack(input_a.unsqueeze(-1), assumed_align=16),
|
| 310 |
+
from_dlpack(input_b[0].unsqueeze(-1), assumed_align=16),
|
| 311 |
+
from_dlpack({{get_output()}}.unsqueeze(-1), assumed_align=16),
|
| 312 |
+
G,
|
| 313 |
+
probs,
|
| 314 |
+
strides,
|
| 315 |
+
ptrs,
|
| 316 |
+
total_num_clusters,
|
| 317 |
+
tensormap_workspace,
|
| 318 |
+
max_active_clusters,
|
| 319 |
+
stream,
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
gemm_cache[gemm_cache_key] = gemm_executor
|
| 323 |
+
|
| 324 |
+
gemm_executor(
|
| 325 |
+
from_dlpack(input_a.unsqueeze(-1), assumed_align=16),
|
| 326 |
+
from_dlpack(input_b[0].unsqueeze(-1), assumed_align=16),
|
| 327 |
+
from_dlpack({{get_output()}}.unsqueeze(-1), assumed_align=16),
|
| 328 |
+
probs,
|
| 329 |
+
strides,
|
| 330 |
+
ptrs,
|
| 331 |
+
tensormap_workspace,
|
| 332 |
+
stream,
|
| 333 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_blackwell_ws_persistent_device_tma_mm.py.jinja
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("A", "B")}}
|
| 2 |
+
M = {{size("A", 0)}}
|
| 3 |
+
N = {{size("B", 1)}}
|
| 4 |
+
K = {{size("A", 1)}}
|
| 5 |
+
if M * N == 0:
|
| 6 |
+
# early exit due to zero-size input(s)
|
| 7 |
+
return
|
| 8 |
+
start_pid = tl.program_id(0)
|
| 9 |
+
grid_m = tl.cdiv(M, BLOCK_M)
|
| 10 |
+
grid_n = tl.cdiv(N, BLOCK_N)
|
| 11 |
+
k_tiles = tl.cdiv(K, BLOCK_K)
|
| 12 |
+
num_tiles = grid_m * grid_n
|
| 13 |
+
|
| 14 |
+
# Note: We require TMA_EXPERIMENTAL_API == False, which
|
| 15 |
+
# we will check before invoking this template.
|
| 16 |
+
stride_am = {{stride("A", 0)}}
|
| 17 |
+
stride_ak = {{stride("A", 1)}}
|
| 18 |
+
stride_bk = {{stride("B", 0)}}
|
| 19 |
+
stride_bn = {{stride("B", 1)}}
|
| 20 |
+
a_desc = triton.language.make_tensor_descriptor(
|
| 21 |
+
base=A,
|
| 22 |
+
shape=[M, K] if A_ROW_MAJOR else [K, M],
|
| 23 |
+
strides=[stride_am, 1] if A_ROW_MAJOR else [stride_ak, 1],
|
| 24 |
+
block_shape=[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M],
|
| 25 |
+
)
|
| 26 |
+
b_desc = triton.language.make_tensor_descriptor(
|
| 27 |
+
base=B,
|
| 28 |
+
shape=[K, N] if B_ROW_MAJOR else [N, K],
|
| 29 |
+
strides=[stride_bk, 1] if B_ROW_MAJOR else [stride_bn, 1],
|
| 30 |
+
block_shape=[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K],
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# tile_id_c is used in the epilogue to break the dependency between
|
| 34 |
+
# the prologue and the epilogue
|
| 35 |
+
tile_id_c = start_pid - NUM_SMS
|
| 36 |
+
num_pid_in_group = GROUP_M * grid_n
|
| 37 |
+
|
| 38 |
+
for tile_id in tl.range(
|
| 39 |
+
start_pid, num_tiles, NUM_SMS, flatten=FLATTEN, warp_specialize=WARP_SPECIALIZE
|
| 40 |
+
):
|
| 41 |
+
pid_m, pid_n = _compute_pid(
|
| 42 |
+
tile_id, num_pid_in_group, grid_m, GROUP_M, NUM_SMS
|
| 43 |
+
)
|
| 44 |
+
offs_am = pid_m * BLOCK_M
|
| 45 |
+
offs_bn = pid_n * BLOCK_N
|
| 46 |
+
|
| 47 |
+
accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
|
| 48 |
+
for ki in range(k_tiles):
|
| 49 |
+
offs_k = ki * BLOCK_K
|
| 50 |
+
a = tl.load_tensor_descriptor(
|
| 51 |
+
a_desc,
|
| 52 |
+
[offs_am, offs_k] if A_ROW_MAJOR else [offs_k, offs_am],
|
| 53 |
+
)
|
| 54 |
+
b = tl.load_tensor_descriptor(
|
| 55 |
+
b_desc,
|
| 56 |
+
[offs_k, offs_bn] if B_ROW_MAJOR else [offs_bn, offs_k],
|
| 57 |
+
)
|
| 58 |
+
accumulator += tl.dot(
|
| 59 |
+
a if A_ROW_MAJOR else a.T,
|
| 60 |
+
b if B_ROW_MAJOR else b.T,
|
| 61 |
+
allow_tf32=ALLOW_TF32,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
tile_id_c += NUM_SMS
|
| 65 |
+
pid_m, pid_n = _compute_pid(
|
| 66 |
+
tile_id_c, num_pid_in_group, grid_m, GROUP_M, NUM_SMS
|
| 67 |
+
)
|
| 68 |
+
offs_cm = pid_m * BLOCK_M
|
| 69 |
+
offs_cn = pid_n * BLOCK_N
|
| 70 |
+
{%- if EPILOGUE_SUBTILE %}
|
| 71 |
+
tl.static_assert(BLOCK_N % 2 == 0)
|
| 72 |
+
acc = tl.reshape(accumulator, (BLOCK_M, 2, BLOCK_N // 2))
|
| 73 |
+
acc = tl.permute(acc, (0, 2, 1))
|
| 74 |
+
acc0, acc1 = tl.split(acc)
|
| 75 |
+
{{store_output(
|
| 76 |
+
("offs_cm", "offs_cn"),
|
| 77 |
+
"acc0",
|
| 78 |
+
indent_width=8,
|
| 79 |
+
val_shape=("BLOCK_M", "BLOCK_N // 2"),
|
| 80 |
+
block_indexing=True
|
| 81 |
+
)}}
|
| 82 |
+
offs_cn2 = offs_cn + BLOCK_N // 2
|
| 83 |
+
{{store_output(
|
| 84 |
+
("offs_cm", "offs_cn2"),
|
| 85 |
+
"acc1",
|
| 86 |
+
indent_width=8,
|
| 87 |
+
val_shape=("BLOCK_M", "BLOCK_N // 2"),
|
| 88 |
+
block_indexing=True
|
| 89 |
+
)}}
|
| 90 |
+
{%- else %}
|
| 91 |
+
{{store_output(
|
| 92 |
+
("offs_cm", "offs_cn"),
|
| 93 |
+
"accumulator",
|
| 94 |
+
indent_width=8,
|
| 95 |
+
val_shape=("BLOCK_M", "BLOCK_N"),
|
| 96 |
+
block_indexing=True
|
| 97 |
+
)}}
|
| 98 |
+
{%- endif %}
|
| 99 |
+
|
| 100 |
+
@triton.jit
|
| 101 |
+
def _compute_pid(tile_id, num_pid_in_group, grid_m, GROUP_M: tl.constexpr, NUM_SMS: tl.constexpr):
|
| 102 |
+
group_id = tile_id // num_pid_in_group
|
| 103 |
+
first_pid_m = group_id * GROUP_M
|
| 104 |
+
GROUP_M = min(grid_m - first_pid_m, GROUP_M)
|
| 105 |
+
pid_m = first_pid_m + (tile_id % GROUP_M)
|
| 106 |
+
pid_n = (tile_id % num_pid_in_group) // GROUP_M
|
| 107 |
+
return pid_m, pid_n
|
mini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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("A", "B", "A_inverse_scale", "B_inverse_scale")}}
|
| 2 |
+
M = {{size("A", 0)}}
|
| 3 |
+
N = {{size("B", 1)}}
|
| 4 |
+
K = {{size("A", 1)}}
|
| 5 |
+
if M * N == 0:
|
| 6 |
+
# early exit due to zero-size input(s)
|
| 7 |
+
return
|
| 8 |
+
|
| 9 |
+
stride_am = {{stride("A", 0)}}
|
| 10 |
+
stride_ak = {{stride("A", 1)}}
|
| 11 |
+
stride_bk = {{stride("B", 0)}}
|
| 12 |
+
stride_bn = {{stride("B", 1)}}
|
| 13 |
+
|
| 14 |
+
if SCALE_RECIPE_A == 1: # ScalingType.RowWise
|
| 15 |
+
stride_a_scale_m = 1
|
| 16 |
+
else:
|
| 17 |
+
stride_a_scale_m = 0
|
| 18 |
+
|
| 19 |
+
if SCALE_RECIPE_B == 1: # ScalingType.RowWise
|
| 20 |
+
stride_b_scale_n = 1
|
| 21 |
+
else:
|
| 22 |
+
stride_b_scale_n = 0
|
| 23 |
+
|
| 24 |
+
start_pid = tl.program_id(axis=0).to(INDEX_DTYPE)
|
| 25 |
+
num_pid_m = tl.cdiv(M, BLOCK_M)
|
| 26 |
+
num_pid_n = tl.cdiv(N, BLOCK_N)
|
| 27 |
+
k_tiles = tl.cdiv(K, BLOCK_K)
|
| 28 |
+
num_tiles = num_pid_m * num_pid_n
|
| 29 |
+
|
| 30 |
+
{%- if TMA_EXPERIMENTAL_API %}
|
| 31 |
+
workspace_base = ws_ptr + start_pid * 2 * TMA_SIZE
|
| 32 |
+
a_desc_ptr = workspace_base
|
| 33 |
+
b_desc_ptr = workspace_base + TMA_SIZE
|
| 34 |
+
|
| 35 |
+
triton.language.extra.cuda.experimental_device_tensormap_create2d(
|
| 36 |
+
desc_ptr=a_desc_ptr,
|
| 37 |
+
global_address=A,
|
| 38 |
+
load_size=[BLOCK_M, BLOCK_K],
|
| 39 |
+
global_size=[M, K],
|
| 40 |
+
element_ty=A.dtype.element_ty,
|
| 41 |
+
)
|
| 42 |
+
triton.language.extra.cuda.experimental_device_tensormap_create2d(
|
| 43 |
+
desc_ptr=b_desc_ptr,
|
| 44 |
+
global_address=B,
|
| 45 |
+
load_size=[BLOCK_N, BLOCK_K],
|
| 46 |
+
global_size=[N, K],
|
| 47 |
+
element_ty=B.dtype.element_ty,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(a_desc_ptr)
|
| 51 |
+
tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(b_desc_ptr)
|
| 52 |
+
|
| 53 |
+
{%- else %}
|
| 54 |
+
stride_am = {{stride("A", 0)}}
|
| 55 |
+
stride_bn = {{stride("B", 1)}}
|
| 56 |
+
a_desc = triton.language.make_tensor_descriptor(
|
| 57 |
+
base=A,
|
| 58 |
+
shape=[M, K],
|
| 59 |
+
strides=[stride_am, 1],
|
| 60 |
+
block_shape=[BLOCK_M, BLOCK_K],
|
| 61 |
+
)
|
| 62 |
+
b_desc = triton.language.make_tensor_descriptor(
|
| 63 |
+
base=B,
|
| 64 |
+
shape=[N, K],
|
| 65 |
+
strides=[stride_bn, 1],
|
| 66 |
+
block_shape=[BLOCK_N, BLOCK_K],
|
| 67 |
+
)
|
| 68 |
+
{%- endif %}
|
| 69 |
+
|
| 70 |
+
tiles_per_SM = num_tiles // NUM_SMS
|
| 71 |
+
if start_pid < num_tiles % NUM_SMS:
|
| 72 |
+
tiles_per_SM += 1
|
| 73 |
+
|
| 74 |
+
tile_id = start_pid - NUM_SMS
|
| 75 |
+
ki = -1
|
| 76 |
+
|
| 77 |
+
pid_m = 0
|
| 78 |
+
pid_n = 0
|
| 79 |
+
offs_am = 0
|
| 80 |
+
offs_bn = 0
|
| 81 |
+
|
| 82 |
+
num_pid_in_group = GROUP_M * num_pid_n
|
| 83 |
+
accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE)
|
| 84 |
+
a_scale = load_scales(A_inverse_scale, SCALE_RECIPE_A)
|
| 85 |
+
b_scale = load_scales(B_inverse_scale, SCALE_RECIPE_B)
|
| 86 |
+
|
| 87 |
+
for _ in range(0, k_tiles * tiles_per_SM):
|
| 88 |
+
ki = tl.where(ki == k_tiles - 1, 0, ki + 1)
|
| 89 |
+
if ki == 0:
|
| 90 |
+
tile_id += NUM_SMS
|
| 91 |
+
group_id = tile_id // num_pid_in_group
|
| 92 |
+
first_pid_m = group_id * GROUP_M
|
| 93 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
|
| 94 |
+
pid_m = first_pid_m + (tile_id % group_size_m)
|
| 95 |
+
pid_n = (tile_id % num_pid_in_group) // group_size_m
|
| 96 |
+
|
| 97 |
+
offs_am = pid_m * BLOCK_M
|
| 98 |
+
offs_bn = pid_n * BLOCK_N
|
| 99 |
+
|
| 100 |
+
offs_k = ki * BLOCK_K
|
| 101 |
+
|
| 102 |
+
{%- if TMA_EXPERIMENTAL_API %}
|
| 103 |
+
a = tl._experimental_descriptor_load(
|
| 104 |
+
a_desc_ptr, [offs_am, offs_k], [BLOCK_M, BLOCK_K], A.dtype.element_ty
|
| 105 |
+
)
|
| 106 |
+
b = tl._experimental_descriptor_load(
|
| 107 |
+
b_desc_ptr, [offs_bn, offs_k], [BLOCK_N, BLOCK_K], B.dtype.element_ty
|
| 108 |
+
)
|
| 109 |
+
{%- else %}
|
| 110 |
+
a = tl.load_tensor_descriptor(a_desc, [offs_am, offs_k])
|
| 111 |
+
b = tl.load_tensor_descriptor(b_desc, [offs_bn, offs_k])
|
| 112 |
+
{%- endif %}
|
| 113 |
+
if USE_FAST_ACCUM:
|
| 114 |
+
accumulator = tl.dot(a, b.T, accumulator)
|
| 115 |
+
else:
|
| 116 |
+
accumulator += tl.dot(a, b.T)
|
| 117 |
+
|
| 118 |
+
if ki == k_tiles - 1:
|
| 119 |
+
# Apply inverse scaling
|
| 120 |
+
offs_cm = offs_am + tl.arange(0, BLOCK_M)
|
| 121 |
+
offs_cn = offs_bn + tl.arange(0, BLOCK_N)
|
| 122 |
+
# Apply scaling
|
| 123 |
+
accumulator = apply_scaling(
|
| 124 |
+
accumulator,
|
| 125 |
+
a_scale,
|
| 126 |
+
b_scale,
|
| 127 |
+
SCALE_RECIPE_A,
|
| 128 |
+
SCALE_RECIPE_B,
|
| 129 |
+
offs_cm,
|
| 130 |
+
offs_cn,
|
| 131 |
+
M,
|
| 132 |
+
N,
|
| 133 |
+
stride_a_scale_m,
|
| 134 |
+
stride_b_scale_n,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
# inductor generates a suffix
|
| 138 |
+
{%- if TMA_EXPERIMENTAL_API %}
|
| 139 |
+
idx_m = offs_cm[:, None]
|
| 140 |
+
idx_n = offs_cn[None, :]
|
| 141 |
+
mask = (idx_m < M) & (idx_n < N)
|
| 142 |
+
{{store_output(("idx_m", "idx_n"), "accumulator", "mask", indent_width=12, val_shape=("BLOCK_M", "BLOCK_N"))}}
|
| 143 |
+
{%- else %}
|
| 144 |
+
{{store_output(
|
| 145 |
+
("offs_am", "offs_bn"),
|
| 146 |
+
"accumulator",
|
| 147 |
+
indent_width=12,
|
| 148 |
+
val_shape=("BLOCK_M", "BLOCK_N"),
|
| 149 |
+
block_indexing=True,
|
| 150 |
+
)}}
|
| 151 |
+
{%- endif %}
|
| 152 |
+
accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@triton.jit
|
| 156 |
+
def load_scales(scale_ptr, SCALE_RECIPE: tl.constexpr):
|
| 157 |
+
if SCALE_RECIPE == 0:
|
| 158 |
+
return tl.load(scale_ptr) # For tensor-wise scaling, we'll load the scalar values
|
| 159 |
+
else:
|
| 160 |
+
return scale_ptr # For all other scaling recipes, we'll return the pointers
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
@triton.jit
|
| 164 |
+
def apply_scaling(
|
| 165 |
+
accumulator,
|
| 166 |
+
a_scale,
|
| 167 |
+
b_scale,
|
| 168 |
+
SCALE_RECIPE_A: tl.constexpr,
|
| 169 |
+
SCALE_RECIPE_B: tl.constexpr,
|
| 170 |
+
offs_cm,
|
| 171 |
+
offs_cn,
|
| 172 |
+
M,
|
| 173 |
+
N,
|
| 174 |
+
stride_a_scale_m,
|
| 175 |
+
stride_b_scale_n,
|
| 176 |
+
):
|
| 177 |
+
if SCALE_RECIPE_A == 1 and SCALE_RECIPE_B == 1: # (ScalingType.RowWise, ScalingType.RowWise)
|
| 178 |
+
# For row-wise scaling, we need to load the scales for each row/column
|
| 179 |
+
a_scales = tl.load(
|
| 180 |
+
a_scale + (offs_cm * stride_a_scale_m),
|
| 181 |
+
mask=offs_cm < M,
|
| 182 |
+
other=0.0,
|
| 183 |
+
)
|
| 184 |
+
b_scales = tl.load(
|
| 185 |
+
b_scale + (offs_cn * stride_b_scale_n),
|
| 186 |
+
mask=offs_cn < N,
|
| 187 |
+
other=0.0,
|
| 188 |
+
)
|
| 189 |
+
acc_scale = a_scales[:, None] * b_scales[None, :]
|
| 190 |
+
else: # (ScalingType.TensorWise, ScalingType.TensorWise)
|
| 191 |
+
# For per-tensor scaling, we can directly use the loaded scalar values
|
| 192 |
+
acc_scale = a_scale * b_scale
|
| 193 |
+
|
| 194 |
+
return accumulator * acc_scale
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_main_loop_scaled_mm.py.jinja
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("A", "B", "A_inverse_scale", "B_inverse_scale")}}
|
| 2 |
+
M = {{size("A", 0)}}
|
| 3 |
+
N = {{size("B", 1)}}
|
| 4 |
+
K = {{size("A", 1)}}
|
| 5 |
+
if M * N == 0:
|
| 6 |
+
# early exit due to zero-size input(s)
|
| 7 |
+
return
|
| 8 |
+
|
| 9 |
+
stride_am = {{stride("A", 0)}}
|
| 10 |
+
stride_bn = {{stride("B", 1)}}
|
| 11 |
+
|
| 12 |
+
start_pid = tl.program_id(axis=0).to(INDEX_DTYPE)
|
| 13 |
+
num_pid_m = tl.cdiv(M, BLOCK_M)
|
| 14 |
+
num_pid_n = tl.cdiv(N, BLOCK_N)
|
| 15 |
+
k_tiles = tl.cdiv(K, BLOCK_K)
|
| 16 |
+
num_tiles = num_pid_m * num_pid_n
|
| 17 |
+
|
| 18 |
+
a_desc = triton.language.make_tensor_descriptor(
|
| 19 |
+
base=A,
|
| 20 |
+
shape=[M, K],
|
| 21 |
+
strides=[stride_am, 1],
|
| 22 |
+
block_shape=[BLOCK_M, BLOCK_K],
|
| 23 |
+
)
|
| 24 |
+
b_desc = triton.language.make_tensor_descriptor(
|
| 25 |
+
base=B,
|
| 26 |
+
shape=[N, K],
|
| 27 |
+
strides=[stride_bn, 1],
|
| 28 |
+
block_shape=[BLOCK_N, BLOCK_K],
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
tiles_per_SM = num_tiles // NUM_SMS
|
| 32 |
+
if start_pid < num_tiles % NUM_SMS:
|
| 33 |
+
tiles_per_SM += 1
|
| 34 |
+
|
| 35 |
+
tile_id = start_pid - NUM_SMS
|
| 36 |
+
ki = -1
|
| 37 |
+
|
| 38 |
+
pid_m = 0
|
| 39 |
+
pid_n = 0
|
| 40 |
+
offs_am = 0
|
| 41 |
+
offs_bn = 0
|
| 42 |
+
|
| 43 |
+
num_pid_in_group = GROUP_M * num_pid_n
|
| 44 |
+
accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE)
|
| 45 |
+
a_scale = load_scales(A_inverse_scale, SCALE_RECIPE_A)
|
| 46 |
+
b_scale = load_scales(B_inverse_scale, SCALE_RECIPE_B)
|
| 47 |
+
|
| 48 |
+
for _ in range(0, k_tiles * tiles_per_SM):
|
| 49 |
+
ki = tl.where(ki == k_tiles - 1, 0, ki + 1)
|
| 50 |
+
if ki == 0:
|
| 51 |
+
tile_id += NUM_SMS
|
| 52 |
+
group_id = tile_id // num_pid_in_group
|
| 53 |
+
first_pid_m = group_id * GROUP_M
|
| 54 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_M)
|
| 55 |
+
pid_m = first_pid_m + (tile_id % group_size_m)
|
| 56 |
+
pid_n = (tile_id % num_pid_in_group) // group_size_m
|
| 57 |
+
|
| 58 |
+
offs_am = pid_m * BLOCK_M
|
| 59 |
+
offs_bn = pid_n * BLOCK_N
|
| 60 |
+
|
| 61 |
+
offs_k = ki * BLOCK_K
|
| 62 |
+
|
| 63 |
+
a = tl.load_tensor_descriptor(a_desc, [offs_am, offs_k])
|
| 64 |
+
b = tl.load_tensor_descriptor(b_desc, [offs_bn, offs_k])
|
| 65 |
+
|
| 66 |
+
am_blocks = tl.cdiv(M, TILE_SIZE_A)
|
| 67 |
+
ak_blocks = tl.cdiv(K, TILE_SIZE_A)
|
| 68 |
+
bn_blocks = tl.cdiv(N, TILE_SIZE_B)
|
| 69 |
+
bk_blocks = tl.cdiv(K, TILE_SIZE_B)
|
| 70 |
+
|
| 71 |
+
{%- if SCALE_RECIPE_A == 5 %} # ScalingType.Blockwise128x128
|
| 72 |
+
scale_a_block = blockwise128x128_scaling(
|
| 73 |
+
pid_m,
|
| 74 |
+
a_scale,
|
| 75 |
+
ki,
|
| 76 |
+
am_blocks,
|
| 77 |
+
ak_blocks,
|
| 78 |
+
BLOCK_M,
|
| 79 |
+
BLOCK_K,
|
| 80 |
+
MIN_BLOCK_TILE_AM,
|
| 81 |
+
MIN_BLOCK_TILE_AK,
|
| 82 |
+
)
|
| 83 |
+
{%- else %} # ScalingType.Blockwise1xTILESIZE
|
| 84 |
+
scale_a_block = blockwise1xTILESIZE_scaling(
|
| 85 |
+
pid_m,
|
| 86 |
+
a_scale,
|
| 87 |
+
ki,
|
| 88 |
+
M,
|
| 89 |
+
am_blocks,
|
| 90 |
+
ak_blocks,
|
| 91 |
+
BLOCK_M,
|
| 92 |
+
BLOCK_K,
|
| 93 |
+
MIN_BLOCK_TILE_AK,
|
| 94 |
+
TILE_SIZE_A,
|
| 95 |
+
)
|
| 96 |
+
{%- endif %}
|
| 97 |
+
|
| 98 |
+
{%- if SCALE_RECIPE_A == 5 %} # ScalingType.Blockwise128x128
|
| 99 |
+
scale_b_block = blockwise128x128_scaling(
|
| 100 |
+
pid_n,
|
| 101 |
+
b_scale,
|
| 102 |
+
ki,
|
| 103 |
+
bn_blocks,
|
| 104 |
+
bk_blocks,
|
| 105 |
+
BLOCK_N,
|
| 106 |
+
BLOCK_K,
|
| 107 |
+
MIN_BLOCK_TILE_BN,
|
| 108 |
+
MIN_BLOCK_TILE_BK,
|
| 109 |
+
)
|
| 110 |
+
{%- else %} # ScalingType.Blockwise1xTILESIZE
|
| 111 |
+
scale_b_block = blockwise1xTILESIZE_scaling(
|
| 112 |
+
pid_n,
|
| 113 |
+
b_scale,
|
| 114 |
+
ki,
|
| 115 |
+
N,
|
| 116 |
+
bn_blocks,
|
| 117 |
+
bk_blocks,
|
| 118 |
+
BLOCK_N,
|
| 119 |
+
BLOCK_K,
|
| 120 |
+
MIN_BLOCK_TILE_BK,
|
| 121 |
+
TILE_SIZE_B,
|
| 122 |
+
)
|
| 123 |
+
{%- endif %}
|
| 124 |
+
|
| 125 |
+
a_scaled = a * scale_a_block
|
| 126 |
+
b_scaled = b * scale_b_block
|
| 127 |
+
accumulator = tl.dot(a_scaled, b_scaled.T, accumulator)
|
| 128 |
+
|
| 129 |
+
if ki == k_tiles - 1:
|
| 130 |
+
offs_cm = offs_am + tl.arange(0, BLOCK_M)
|
| 131 |
+
offs_cn = offs_bn + tl.arange(0, BLOCK_N)
|
| 132 |
+
|
| 133 |
+
# inductor generates a suffix
|
| 134 |
+
{{store_output(
|
| 135 |
+
("offs_am", "offs_bn"),
|
| 136 |
+
"accumulator",
|
| 137 |
+
indent_width=12,
|
| 138 |
+
val_shape=("BLOCK_M", "BLOCK_N"),
|
| 139 |
+
block_indexing=True,
|
| 140 |
+
)}}
|
| 141 |
+
accumulator = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@triton.jit
|
| 145 |
+
def load_scales(scale_ptr, SCALE_RECIPE: tl.constexpr):
|
| 146 |
+
if SCALE_RECIPE == 0:
|
| 147 |
+
return tl.load(scale_ptr) # For tensor-wise scaling, we'll load the scalar values
|
| 148 |
+
else:
|
| 149 |
+
return scale_ptr # For all other scaling recipes, we'll return the pointers
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
@triton.jit
|
| 153 |
+
def blockwise1xTILESIZE_scaling(
|
| 154 |
+
pid,
|
| 155 |
+
scale,
|
| 156 |
+
ki,
|
| 157 |
+
lhs_size,
|
| 158 |
+
lhs_blocks,
|
| 159 |
+
k_blocks,
|
| 160 |
+
BLOCK_lhs: tl.constexpr,
|
| 161 |
+
BLOCK_K: tl.constexpr,
|
| 162 |
+
MIN_BLOCK_TILE_K: tl.constexpr,
|
| 163 |
+
TILE_SIZE: tl.constexpr,
|
| 164 |
+
):
|
| 165 |
+
row_offs_scale = pid * BLOCK_lhs + tl.arange(0, BLOCK_lhs)
|
| 166 |
+
col_offs_scale = ki * tl.cdiv(BLOCK_K, TILE_SIZE) + tl.arange(0, (BLOCK_K + TILE_SIZE - 1) // TILE_SIZE)
|
| 167 |
+
ptrs = scale + row_offs_scale[:, None] * k_blocks + col_offs_scale[None, :]
|
| 168 |
+
mask = (row_offs_scale[:, None] < lhs_size) & (col_offs_scale[None, :] < k_blocks)
|
| 169 |
+
scale_block = tl.load(ptrs, mask=mask, other=1.0)
|
| 170 |
+
|
| 171 |
+
scale_expanded = scale_block[:, :, None]
|
| 172 |
+
scale_expanded = tl.broadcast_to(
|
| 173 |
+
scale_expanded,
|
| 174 |
+
(BLOCK_lhs, (BLOCK_K + TILE_SIZE - 1) // TILE_SIZE, MIN_BLOCK_TILE_K)
|
| 175 |
+
)
|
| 176 |
+
scale_expanded = scale_expanded.reshape(
|
| 177 |
+
BLOCK_lhs,
|
| 178 |
+
((BLOCK_K + TILE_SIZE - 1) // TILE_SIZE) * MIN_BLOCK_TILE_K
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
return scale_expanded
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@triton.jit
|
| 185 |
+
def blockwise128x128_scaling(
|
| 186 |
+
pid,
|
| 187 |
+
scale,
|
| 188 |
+
ki,
|
| 189 |
+
lhs_blocks,
|
| 190 |
+
k_blocks,
|
| 191 |
+
BLOCK_lhs: tl.constexpr,
|
| 192 |
+
BLOCK_K: tl.constexpr,
|
| 193 |
+
MIN_BLOCK_TILE_lhs: tl.constexpr,
|
| 194 |
+
MIN_BLOCK_TILE_K: tl.constexpr,
|
| 195 |
+
):
|
| 196 |
+
row_offs_scale = pid * tl.cdiv(BLOCK_lhs, 128) + tl.arange(0, (BLOCK_lhs + 128 - 1) // 128)
|
| 197 |
+
col_offs_scale = ki * tl.cdiv(BLOCK_K, 128) + tl.arange(0, (BLOCK_K + 128 - 1) // 128)
|
| 198 |
+
ptrs = scale + row_offs_scale[:, None] * k_blocks + col_offs_scale[None, :]
|
| 199 |
+
mask = (row_offs_scale[:, None] < lhs_blocks) & (col_offs_scale[None, :] < k_blocks)
|
| 200 |
+
scale_block = tl.load(ptrs, mask=mask, other=1.0)
|
| 201 |
+
|
| 202 |
+
scale_expanded = scale_block[:, :, None, None]
|
| 203 |
+
scale_expanded = tl.broadcast_to(
|
| 204 |
+
scale_expanded,
|
| 205 |
+
((BLOCK_lhs + 128 - 1) // 128, (BLOCK_K + 128 - 1) // 128, MIN_BLOCK_TILE_lhs, MIN_BLOCK_TILE_K)
|
| 206 |
+
)
|
| 207 |
+
scale_expanded = scale_expanded.reshape(
|
| 208 |
+
((BLOCK_lhs + 128 - 1) // 128) * MIN_BLOCK_TILE_lhs,
|
| 209 |
+
((BLOCK_K + 128 - 1) // 128) * MIN_BLOCK_TILE_K
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
return scale_expanded
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_mm.py.jinja
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("A", "B")}}
|
| 2 |
+
M = {{size("A", 0)}}
|
| 3 |
+
N = {{size("B", 1)}}
|
| 4 |
+
K = {{size("A", 1)}}
|
| 5 |
+
if M * N == 0:
|
| 6 |
+
# early exit due to zero-size input(s)
|
| 7 |
+
return
|
| 8 |
+
stride_am = {{stride("A", 0)}}
|
| 9 |
+
stride_ak = {{stride("A", 1)}}
|
| 10 |
+
stride_bk = {{stride("B", 0)}}
|
| 11 |
+
stride_bn = {{stride("B", 1)}}
|
| 12 |
+
|
| 13 |
+
# based on triton.ops.matmul
|
| 14 |
+
pid = tl.program_id(0).to(INDEX_DTYPE)
|
| 15 |
+
grid_m = (M + BLOCK_M - 1) // BLOCK_M
|
| 16 |
+
grid_n = (N + BLOCK_N - 1) // BLOCK_N
|
| 17 |
+
|
| 18 |
+
# re-order program ID for better L2 performance
|
| 19 |
+
width = GROUP_M * grid_n
|
| 20 |
+
group_id = pid // width
|
| 21 |
+
group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
|
| 22 |
+
pid_m = group_id * GROUP_M + (pid % group_size)
|
| 23 |
+
pid_n = (pid % width) // (group_size)
|
| 24 |
+
tl.assume(pid_m >= 0)
|
| 25 |
+
tl.assume(pid_n >= 0)
|
| 26 |
+
|
| 27 |
+
rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 28 |
+
rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
| 29 |
+
if ((stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1)) and (M >= BLOCK_M and K > 1):
|
| 30 |
+
offs_a_m = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M)
|
| 31 |
+
else:
|
| 32 |
+
offs_a_m = rm % M
|
| 33 |
+
if ((stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1)) and (N >= BLOCK_N and K > 1):
|
| 34 |
+
offs_b_n = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N)
|
| 35 |
+
else:
|
| 36 |
+
offs_b_n = rn % N
|
| 37 |
+
offs_k = tl.arange(0, BLOCK_K)
|
| 38 |
+
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE)
|
| 39 |
+
|
| 40 |
+
for k_idx in range(0, tl.cdiv(K, BLOCK_K)):
|
| 41 |
+
{% if not EVEN_K %}
|
| 42 |
+
a_mask = offs_k[None, :] < (K - k_idx * BLOCK_K)
|
| 43 |
+
b_mask = offs_k[:, None] < (K - k_idx * BLOCK_K)
|
| 44 |
+
{% endif %}
|
| 45 |
+
a_k_idx_vals = offs_k[None, :] + (k_idx * BLOCK_K)
|
| 46 |
+
b_k_idx_vals = offs_k[:, None] + (k_idx * BLOCK_K)
|
| 47 |
+
|
| 48 |
+
idx_m = offs_a_m[:, None]
|
| 49 |
+
idx_n = a_k_idx_vals
|
| 50 |
+
{{load_input("A", "a", ("idx_m", "idx_n"), mask=None if EVEN_K else "a_mask",
|
| 51 |
+
indent_width=8, index_shape=("BLOCK_M", "BLOCK_K"))}}
|
| 52 |
+
|
| 53 |
+
idx_m = b_k_idx_vals
|
| 54 |
+
idx_n = offs_b_n[None, :]
|
| 55 |
+
{{load_input("B", "b", ("idx_m", "idx_n"), mask=None if EVEN_K else "b_mask",
|
| 56 |
+
indent_width=8, index_shape=("BLOCK_K", "BLOCK_N"))}}
|
| 57 |
+
|
| 58 |
+
{% if USE_FAST_ACCUM %}
|
| 59 |
+
acc = tl.dot(a, b, acc, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE)
|
| 60 |
+
{% else %}
|
| 61 |
+
acc += tl.dot(a, b, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE)
|
| 62 |
+
{% endif %}
|
| 63 |
+
|
| 64 |
+
# rematerialize rm and rn to save registers
|
| 65 |
+
rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 66 |
+
rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
| 67 |
+
idx_m = rm[:, None]
|
| 68 |
+
idx_n = rn[None, :]
|
| 69 |
+
mask = (idx_m < M) & (idx_n < N)
|
| 70 |
+
|
| 71 |
+
# inductor generates a suffix
|
| 72 |
+
{{store_output(("idx_m", "idx_n"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}}
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_mm_rocm.py.jinja
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("A", "B")}}
|
| 2 |
+
M = {{size("A", 0)}}
|
| 3 |
+
N = {{size("B", 1)}}
|
| 4 |
+
K = {{size("A", 1)}}
|
| 5 |
+
if M * N == 0:
|
| 6 |
+
# early exit due to zero-size input(s)
|
| 7 |
+
return
|
| 8 |
+
stride_am = {{stride("A", 0)}}
|
| 9 |
+
stride_ak = {{stride("A", 1)}}
|
| 10 |
+
stride_bk = {{stride("B", 0)}}
|
| 11 |
+
stride_bn = {{stride("B", 1)}}
|
| 12 |
+
|
| 13 |
+
# based on triton.ops.matmul
|
| 14 |
+
pid = tl.program_id(0).to(INDEX_DTYPE)
|
| 15 |
+
grid_m = (M + BLOCK_M - 1) // BLOCK_M
|
| 16 |
+
grid_n = (N + BLOCK_N - 1) // BLOCK_N
|
| 17 |
+
|
| 18 |
+
# re-order program ID for better L2 performance
|
| 19 |
+
width = GROUP_M * grid_n
|
| 20 |
+
group_id = pid // width
|
| 21 |
+
group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
|
| 22 |
+
pid_m = group_id * GROUP_M + (pid % group_size)
|
| 23 |
+
pid_n = (pid % width) // (group_size)
|
| 24 |
+
tl.assume(pid_m >= 0)
|
| 25 |
+
tl.assume(pid_n >= 0)
|
| 26 |
+
|
| 27 |
+
rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 28 |
+
rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
| 29 |
+
if (stride_am == 1 and stride_ak == M) or (stride_am == K and stride_ak == 1):
|
| 30 |
+
offs_a_m = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M)
|
| 31 |
+
else:
|
| 32 |
+
offs_a_m = rm % M
|
| 33 |
+
if (stride_bk == 1 and stride_bn == K) or (stride_bk == N and stride_bn == 1):
|
| 34 |
+
offs_b_n = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N)
|
| 35 |
+
else:
|
| 36 |
+
offs_b_n = rn % N
|
| 37 |
+
offs_k = tl.arange(0, BLOCK_K)
|
| 38 |
+
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE)
|
| 39 |
+
|
| 40 |
+
for k_idx in range(0, tl.cdiv(K, BLOCK_K)):
|
| 41 |
+
{% if not EVEN_K %}
|
| 42 |
+
a_mask = offs_k[None, :] < (K - k_idx * BLOCK_K)
|
| 43 |
+
b_mask = offs_k[:, None] < (K - k_idx * BLOCK_K)
|
| 44 |
+
{% endif %}
|
| 45 |
+
a_k_idx_vals = offs_k[None, :] + (k_idx * BLOCK_K)
|
| 46 |
+
b_k_idx_vals = offs_k[:, None] + (k_idx * BLOCK_K)
|
| 47 |
+
|
| 48 |
+
idx_m = offs_a_m[:, None]
|
| 49 |
+
idx_n = a_k_idx_vals
|
| 50 |
+
{{load_input("A", "a", ("idx_m", "idx_n"), mask=None if EVEN_K else "a_mask",
|
| 51 |
+
indent_width=8, index_shape=("BLOCK_M", "BLOCK_K"))}}
|
| 52 |
+
|
| 53 |
+
idx_m = b_k_idx_vals
|
| 54 |
+
idx_n = offs_b_n[None, :]
|
| 55 |
+
{{load_input("B", "b", ("idx_m", "idx_n"), mask=None if EVEN_K else "b_mask",
|
| 56 |
+
indent_width=8, index_shape=("BLOCK_K", "BLOCK_N"))}}
|
| 57 |
+
{% if USE_FAST_ACCUM %}
|
| 58 |
+
acc = tl.dot(a, b, acc, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE)
|
| 59 |
+
{% else %}
|
| 60 |
+
acc += tl.dot(a, b, allow_tf32=ALLOW_TF32, out_dtype=ACC_TYPE)
|
| 61 |
+
{% endif %}
|
| 62 |
+
|
| 63 |
+
# rematerialize rm and rn to save registers
|
| 64 |
+
rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
| 65 |
+
rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
| 66 |
+
idx_m = rm[:, None]
|
| 67 |
+
idx_n = rn[None, :]
|
| 68 |
+
mask = (idx_m < M) & (idx_n < N)
|
| 69 |
+
|
| 70 |
+
# inductor generates a suffix
|
| 71 |
+
{{store_output(("idx_m", "idx_n"), "acc", "mask", val_shape=("BLOCK_M", "BLOCK_N"))}}
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/templates/triton_persistent_tma_mm.py.jinja
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{{def_kernel("A", "B")}}
|
| 2 |
+
M = {{size("A", 0)}}
|
| 3 |
+
N = {{size("B", 1)}}
|
| 4 |
+
K = {{size("A", 1)}}
|
| 5 |
+
if M * N == 0:
|
| 6 |
+
# early exit due to zero-size input(s)
|
| 7 |
+
return
|
| 8 |
+
|
| 9 |
+
start_pid = tl.program_id(0).to(INDEX_DTYPE)
|
| 10 |
+
grid_m = tl.cdiv(M, BLOCK_M)
|
| 11 |
+
grid_n = tl.cdiv(N, BLOCK_N)
|
| 12 |
+
k_tiles = tl.cdiv(K, BLOCK_K)
|
| 13 |
+
num_tiles = grid_m * grid_n
|
| 14 |
+
tiles_per_SM = num_tiles // NUM_SMS
|
| 15 |
+
if start_pid < num_tiles % NUM_SMS:
|
| 16 |
+
tiles_per_SM += 1
|
| 17 |
+
|
| 18 |
+
tile_id = start_pid - NUM_SMS
|
| 19 |
+
ki = -1
|
| 20 |
+
|
| 21 |
+
width = GROUP_M * grid_n
|
| 22 |
+
rk_for_mask = tl.arange(0, BLOCK_K)
|
| 23 |
+
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE)
|
| 24 |
+
|
| 25 |
+
{%- if TMA_EXPERIMENTAL_API %}
|
| 26 |
+
workspace_base = ws_ptr + start_pid * 2 * TMA_SIZE
|
| 27 |
+
a_desc_ptr = workspace_base
|
| 28 |
+
b_desc_ptr = workspace_base + TMA_SIZE
|
| 29 |
+
|
| 30 |
+
triton.language.extra.cuda.experimental_device_tensormap_create2d(
|
| 31 |
+
desc_ptr=a_desc_ptr,
|
| 32 |
+
global_address=A,
|
| 33 |
+
load_size=[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M],
|
| 34 |
+
global_size=[M, K] if A_ROW_MAJOR else [K, M],
|
| 35 |
+
element_ty=A.dtype.element_ty,
|
| 36 |
+
)
|
| 37 |
+
triton.language.extra.cuda.experimental_device_tensormap_create2d(
|
| 38 |
+
desc_ptr=b_desc_ptr,
|
| 39 |
+
global_address=B,
|
| 40 |
+
load_size=[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K],
|
| 41 |
+
global_size=[K, N] if B_ROW_MAJOR else [N, K],
|
| 42 |
+
element_ty=B.dtype.element_ty,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(a_desc_ptr)
|
| 46 |
+
tl.extra.cuda.experimental_tensormap_fenceproxy_acquire(b_desc_ptr)
|
| 47 |
+
|
| 48 |
+
{%- else %}
|
| 49 |
+
stride_am = {{stride("A", 0)}}
|
| 50 |
+
stride_ak = {{stride("A", 1)}}
|
| 51 |
+
stride_bk = {{stride("B", 0)}}
|
| 52 |
+
stride_bn = {{stride("B", 1)}}
|
| 53 |
+
a_desc = triton.language.make_tensor_descriptor(
|
| 54 |
+
base=A,
|
| 55 |
+
shape=[M, K] if A_ROW_MAJOR else [K, M],
|
| 56 |
+
strides=[stride_am, 1] if A_ROW_MAJOR else [stride_ak, 1],
|
| 57 |
+
block_shape=[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M],
|
| 58 |
+
)
|
| 59 |
+
b_desc = triton.language.make_tensor_descriptor(
|
| 60 |
+
base=B,
|
| 61 |
+
shape=[K, N] if B_ROW_MAJOR else [N, K],
|
| 62 |
+
strides=[stride_bk, 1] if B_ROW_MAJOR else [stride_bn, 1],
|
| 63 |
+
block_shape=[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K],
|
| 64 |
+
)
|
| 65 |
+
{%- endif %}
|
| 66 |
+
|
| 67 |
+
pid_m = 0
|
| 68 |
+
pid_n = 0
|
| 69 |
+
rm = 0
|
| 70 |
+
rn = 0
|
| 71 |
+
|
| 72 |
+
for _ in range(0, k_tiles * tiles_per_SM):
|
| 73 |
+
ki = tl.where(ki == k_tiles - 1, 0, ki + 1)
|
| 74 |
+
if ki == 0:
|
| 75 |
+
tile_id += NUM_SMS
|
| 76 |
+
# re-order program ID for better L2 performance
|
| 77 |
+
group_id = tile_id // width
|
| 78 |
+
group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
|
| 79 |
+
pid_m = group_id * GROUP_M + (tile_id % group_size)
|
| 80 |
+
pid_n = (tile_id % width) // (group_size)
|
| 81 |
+
|
| 82 |
+
rm = pid_m * BLOCK_M
|
| 83 |
+
rn = pid_n * BLOCK_N
|
| 84 |
+
|
| 85 |
+
rk = ki * BLOCK_K
|
| 86 |
+
|
| 87 |
+
{%- if TMA_EXPERIMENTAL_API %}
|
| 88 |
+
a = tl._experimental_descriptor_load(
|
| 89 |
+
a_desc_ptr,
|
| 90 |
+
[rm, rk] if A_ROW_MAJOR else [rk, rm],
|
| 91 |
+
[BLOCK_M, BLOCK_K] if A_ROW_MAJOR else [BLOCK_K, BLOCK_M],
|
| 92 |
+
A.dtype.element_ty,
|
| 93 |
+
)
|
| 94 |
+
b = tl._experimental_descriptor_load(
|
| 95 |
+
b_desc_ptr,
|
| 96 |
+
[rk, rn] if B_ROW_MAJOR else [rn, rk],
|
| 97 |
+
[BLOCK_K, BLOCK_N] if B_ROW_MAJOR else [BLOCK_N, BLOCK_K],
|
| 98 |
+
B.dtype.element_ty,
|
| 99 |
+
)
|
| 100 |
+
{%- else %}
|
| 101 |
+
a = tl.load_tensor_descriptor(
|
| 102 |
+
a_desc,
|
| 103 |
+
[rm, rk] if A_ROW_MAJOR else [rk, rm],
|
| 104 |
+
)
|
| 105 |
+
b = tl.load_tensor_descriptor(
|
| 106 |
+
b_desc,
|
| 107 |
+
[rk, rn] if B_ROW_MAJOR else [rn, rk],
|
| 108 |
+
)
|
| 109 |
+
{%- endif %}
|
| 110 |
+
acc += tl.dot(
|
| 111 |
+
a if A_ROW_MAJOR else a.T,
|
| 112 |
+
b if B_ROW_MAJOR else b.T,
|
| 113 |
+
allow_tf32=ALLOW_TF32,
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
if ki == k_tiles - 1:
|
| 117 |
+
# inductor generates a suffix
|
| 118 |
+
{%- if TMA_EXPERIMENTAL_API %}
|
| 119 |
+
# rematerialize rm and rn to save registers
|
| 120 |
+
rcm = rm + tl.arange(0, BLOCK_M)
|
| 121 |
+
rcn = rn + tl.arange(0, BLOCK_N)
|
| 122 |
+
idx_m = rcm[:, None]
|
| 123 |
+
idx_n = rcn[None, :]
|
| 124 |
+
mask = (idx_m < M) & (idx_n < N)
|
| 125 |
+
{{store_output(("idx_m", "idx_n"), "acc", "mask", indent_width=12, val_shape=("BLOCK_M", "BLOCK_N"))}}
|
| 126 |
+
{%- else %}
|
| 127 |
+
{{store_output(("rm", "rn"), "acc", indent_width=12, val_shape=("BLOCK_M", "BLOCK_N"), block_indexing=True)}}
|
| 128 |
+
{%- endif %}
|
| 129 |
+
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/vendored_templates/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/kernel/vendored_templates/cutedsl_grouped_gemm.py
ADDED
|
@@ -0,0 +1,2372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
| 2 |
+
# SPDX-License-Identifier: BSD-3-Clause
|
| 3 |
+
|
| 4 |
+
# Redistribution and use in source and binary forms, with or without
|
| 5 |
+
# modification, are permitted provided that the following conditions are met:
|
| 6 |
+
|
| 7 |
+
# 1. Redistributions of source code must retain the above copyright notice, this
|
| 8 |
+
# list of conditions and the following disclaimer.
|
| 9 |
+
|
| 10 |
+
# 2. Redistributions in binary form must reproduce the above copyright notice,
|
| 11 |
+
# this list of conditions and the following disclaimer in the documentation
|
| 12 |
+
# and/or other materials provided with the distribution.
|
| 13 |
+
|
| 14 |
+
# 3. Neither the name of the copyright holder nor the names of its
|
| 15 |
+
# contributors may be used to endorse or promote products derived from
|
| 16 |
+
# this software without specific prior written permission.
|
| 17 |
+
|
| 18 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
| 19 |
+
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
| 20 |
+
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
| 21 |
+
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
| 22 |
+
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
| 23 |
+
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
| 24 |
+
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
| 25 |
+
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
| 26 |
+
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 27 |
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 28 |
+
|
| 29 |
+
import argparse
|
| 30 |
+
import functools
|
| 31 |
+
from typing import List, Type, Union
|
| 32 |
+
from inspect import isclass
|
| 33 |
+
|
| 34 |
+
import torch
|
| 35 |
+
import cuda.bindings.driver as cuda
|
| 36 |
+
|
| 37 |
+
import cutlass
|
| 38 |
+
import cutlass.cute as cute
|
| 39 |
+
import cutlass.cute.testing as testing
|
| 40 |
+
import cutlass.utils as utils
|
| 41 |
+
import cutlass.pipeline as pipeline
|
| 42 |
+
from cutlass.pipeline import pipeline_init_arrive, pipeline_init_wait
|
| 43 |
+
from cutlass.cute.nvgpu import cpasync, tcgen05
|
| 44 |
+
import cutlass.utils.blackwell_helpers as sm100_utils
|
| 45 |
+
import cutlass.torch as cutlass_torch
|
| 46 |
+
|
| 47 |
+
"""
|
| 48 |
+
A grouped GEMM example for the NVIDIA Blackwell SM100 architecture using CUTE DSL
|
| 49 |
+
|
| 50 |
+
This example demonstrates an implementation of grouped GEMM using a TMA plus Blackwell SM100 TensorCore
|
| 51 |
+
warp-specialized persistent kernel.
|
| 52 |
+
The grouped GEMM workload computes a batch of GEMM operations with distinct problem sizes. Pointers to matrices
|
| 53 |
+
in global memory are passed to the kernel in an array (also held in global memory). Similarly, problem shapes and
|
| 54 |
+
strides are also stored in arrays in GMEM.
|
| 55 |
+
|
| 56 |
+
This differs from "Batched Array" GEMM since the size of each GEMM problem in the grouped GEMM concept may be distinct.
|
| 57 |
+
|
| 58 |
+
To run this example:
|
| 59 |
+
|
| 60 |
+
.. code-block:: bash
|
| 61 |
+
|
| 62 |
+
python examples/blackwell/grouped_gemm.py \
|
| 63 |
+
--ab_dtype Float16 --c_dtype Float16 --acc_dtype Float32 \
|
| 64 |
+
--mma_tiler_mn 128,64 --cluster_shape_mn 1,1 \
|
| 65 |
+
--problem_sizes_mnkl "(8192,1280,32,1),(16,384,1536,1),(640,1280,16,1),(640,160,16,1)" \
|
| 66 |
+
--num_groups 4 --tensormap_update_mode SMEM
|
| 67 |
+
|
| 68 |
+
The above example command makes 4 groups of different m, n, k sizes. The Blackwell tcgen05 MMA tile shape
|
| 69 |
+
is specified as (128, 64) and the cluster shape is (1,1). The input, mma accumulator and output data type
|
| 70 |
+
are set as fp16, fp32 and fp16, respectively.
|
| 71 |
+
|
| 72 |
+
To collect performance with NCU profiler:
|
| 73 |
+
|
| 74 |
+
.. code-block:: bash
|
| 75 |
+
|
| 76 |
+
ncu python examples/blackwell/grouped_gemm.py \
|
| 77 |
+
--ab_dtype Float16 --c_dtype Float16 --acc_dtype Float32 \
|
| 78 |
+
--mma_tiler_mn 128,64 --cluster_shape_mn 1,1 \
|
| 79 |
+
--problem_sizes_mnkl "(8192,1280,32,1),(16,384,1536,1),(640,1280,16,1),(640,160,16,1)" \
|
| 80 |
+
--num_groups 4 --tensormap_update_mode SMEM \
|
| 81 |
+
--warmup_iterations 1 --iterations 10 --skip_ref_check
|
| 82 |
+
|
| 83 |
+
There are some constrains for this example. Besides the constrains from the Balckwell dense GEMM persistent example,
|
| 84 |
+
there are also the following constrains:
|
| 85 |
+
* Only fp16 and bf16 data types are supported as inputs.
|
| 86 |
+
* Output data types could be fp16, bf16 or fp32.
|
| 87 |
+
* The contiguous dimension of each tensor must be at least 16 bytes aligned.
|
| 88 |
+
* The l mode(aka, batch size) for each group must be 1.
|
| 89 |
+
* The majorness for A, B and C must be the same across all groups.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class GroupedGemmKernel:
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
acc_dtype: type[cutlass.Numeric],
|
| 97 |
+
use_2cta_instrs: bool,
|
| 98 |
+
mma_tiler_mn: tuple[int, int],
|
| 99 |
+
cluster_shape_mn: tuple[int, int],
|
| 100 |
+
tensormap_update_mode: utils.TensorMapUpdateMode = utils.TensorMapUpdateMode.SMEM,
|
| 101 |
+
):
|
| 102 |
+
"""Initializes the configuration for a Blackwell grouped GEMM kernel.
|
| 103 |
+
|
| 104 |
+
Besides configurations for dense persistent GEMM, there is an extra config specific to grouped GEMM:
|
| 105 |
+
|
| 106 |
+
Tensormap Update Mode:
|
| 107 |
+
- tensormap_update_mode: Specifies whether the tensormap is
|
| 108 |
+
updated in global memory(GMEM) or shared memory(SMEM).
|
| 109 |
+
The 2 modes are functionally equivalent and the difference are:
|
| 110 |
+
- We buffer 3 tensormaps in SMEM for A, B, and C tensors (each TMA descriptor takes 128B) when TMA updates performed on SMEM.
|
| 111 |
+
- Performance varies between modes depending on problem size; optimal choice differs across workloads.
|
| 112 |
+
|
| 113 |
+
:param acc_dtype: Data type of the accumulator.
|
| 114 |
+
:type acc_dtype: type[cutlass.Numeric]
|
| 115 |
+
:param use_2cta_instrs: Boolean, True to use cta_group=2 MMA variant.
|
| 116 |
+
:type use_2cta_instrs: bool
|
| 117 |
+
:param mma_tiler_mn: tuple (M, N) shape of the MMA instruction.
|
| 118 |
+
:type mma_tiler_mn: tuple[int, int]
|
| 119 |
+
:param cluster_shape_mn: tuple (ClusterM, ClusterN) shape of the cluster.
|
| 120 |
+
:type cluster_shape_mn: tuple[int, int]
|
| 121 |
+
:param tensormap_update_mode: Mode for updating the tensormap (GMEM or SMEM), defaults to SMEM.
|
| 122 |
+
:type tensormap_update_mode: utils.TensorMapUpdateMode, optional
|
| 123 |
+
"""
|
| 124 |
+
self.acc_dtype: Type[cutlass.Numeric] = acc_dtype
|
| 125 |
+
self.use_2cta_instrs = use_2cta_instrs
|
| 126 |
+
self.cluster_shape_mn = cluster_shape_mn
|
| 127 |
+
# K dimension is deferred in _setup_attributes
|
| 128 |
+
self.mma_tiler = (*mma_tiler_mn, 1)
|
| 129 |
+
self.cta_group = (
|
| 130 |
+
tcgen05.CtaGroup.TWO if use_2cta_instrs else tcgen05.CtaGroup.ONE
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
self.tensormap_update_mode = tensormap_update_mode
|
| 134 |
+
# Delegate tensormap ab initialization to MMA warp when SMEM mode is used for better latency hiding
|
| 135 |
+
self.delegate_tensormap_ab_init = (
|
| 136 |
+
tensormap_update_mode == utils.TensorMapUpdateMode.SMEM
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
self.num_mcast_ctas_a = 1
|
| 140 |
+
self.num_mcast_ctas_b = 1
|
| 141 |
+
self.is_a_mcast = False
|
| 142 |
+
self.is_b_mcast = False
|
| 143 |
+
|
| 144 |
+
self.occupancy = 1
|
| 145 |
+
# Set specialized warp ids
|
| 146 |
+
self.epilog_warp_id = (
|
| 147 |
+
0,
|
| 148 |
+
1,
|
| 149 |
+
2,
|
| 150 |
+
3,
|
| 151 |
+
)
|
| 152 |
+
self.mma_warp_id = 4
|
| 153 |
+
self.tma_warp_id = 5
|
| 154 |
+
self.threads_per_cta = 32 * len(
|
| 155 |
+
(self.mma_warp_id, self.tma_warp_id, *self.epilog_warp_id)
|
| 156 |
+
)
|
| 157 |
+
# Set barrier for epilog sync, tmem ptr sync and tensormap update sync
|
| 158 |
+
self.epilog_sync_barrier = pipeline.NamedBarrier(
|
| 159 |
+
barrier_id=1,
|
| 160 |
+
num_threads=32 * len(self.epilog_warp_id),
|
| 161 |
+
)
|
| 162 |
+
self.tmem_alloc_barrier = pipeline.NamedBarrier(
|
| 163 |
+
barrier_id=2,
|
| 164 |
+
num_threads=32 * len((self.mma_warp_id, *self.epilog_warp_id)),
|
| 165 |
+
)
|
| 166 |
+
# Barrier used by MMA/TMA warps to signal A/B tensormap initialization completion
|
| 167 |
+
self.tensormap_ab_init_barrier = pipeline.NamedBarrier(
|
| 168 |
+
barrier_id=3,
|
| 169 |
+
num_threads=32 * (len(self.epilog_warp_id) + 1),
|
| 170 |
+
)
|
| 171 |
+
self.smem_capacity = utils.get_smem_capacity_in_bytes("sm_100")
|
| 172 |
+
self.num_tma_load_bytes = 0
|
| 173 |
+
|
| 174 |
+
def _setup_attributes(self):
|
| 175 |
+
"""Set up configurations that are dependent on GEMM inputs
|
| 176 |
+
|
| 177 |
+
Most of the implementation follows standard dense GEMM patterns,
|
| 178 |
+
with the key difference being additional consideration for SMEM
|
| 179 |
+
buffer needed for tensormap updates.
|
| 180 |
+
"""
|
| 181 |
+
# Configure tiled mma
|
| 182 |
+
tiled_mma = sm100_utils.make_trivial_tiled_mma(
|
| 183 |
+
self.a_dtype,
|
| 184 |
+
self.a_major_mode,
|
| 185 |
+
self.b_major_mode,
|
| 186 |
+
self.acc_dtype,
|
| 187 |
+
self.cta_group,
|
| 188 |
+
self.mma_tiler[:2],
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
# Compute mma/cluster/tile shapes
|
| 192 |
+
mma_inst_shape_k = cute.size(tiled_mma.shape_mnk, mode=[2])
|
| 193 |
+
mma_inst_tile_k = 4
|
| 194 |
+
self.mma_tiler = (
|
| 195 |
+
self.mma_tiler[0],
|
| 196 |
+
self.mma_tiler[1],
|
| 197 |
+
mma_inst_shape_k * mma_inst_tile_k,
|
| 198 |
+
)
|
| 199 |
+
self.cta_tile_shape_mnk = (
|
| 200 |
+
self.mma_tiler[0] // cute.size(tiled_mma.thr_id.shape),
|
| 201 |
+
self.mma_tiler[1],
|
| 202 |
+
self.mma_tiler[2],
|
| 203 |
+
)
|
| 204 |
+
self.cluster_tile_shape_mnk = tuple(
|
| 205 |
+
x * y for x, y in zip(self.cta_tile_shape_mnk, (*self.cluster_shape_mn, 1))
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
# Compute cluster layout
|
| 209 |
+
self.cluster_layout_vmnk = cute.tiled_divide(
|
| 210 |
+
cute.make_layout((*self.cluster_shape_mn, 1)),
|
| 211 |
+
(tiled_mma.thr_id.shape,),
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
# Compute number of multicast CTAs for A/B
|
| 215 |
+
self.num_mcast_ctas_a = cute.size(self.cluster_layout_vmnk.shape[2])
|
| 216 |
+
self.num_mcast_ctas_b = cute.size(self.cluster_layout_vmnk.shape[1])
|
| 217 |
+
self.is_a_mcast = self.num_mcast_ctas_a > 1
|
| 218 |
+
self.is_b_mcast = self.num_mcast_ctas_b > 1
|
| 219 |
+
|
| 220 |
+
# Compute epilogue subtile
|
| 221 |
+
self.epi_tile = utils.compute_epilogue_tile_shape(
|
| 222 |
+
self.cta_tile_shape_mnk,
|
| 223 |
+
self.use_2cta_instrs,
|
| 224 |
+
self.c_layout,
|
| 225 |
+
self.c_dtype,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
# Setup A/B/C stage count in shared memory and ACC stage count in tensor memory
|
| 229 |
+
(
|
| 230 |
+
self.num_acc_stage,
|
| 231 |
+
self.num_ab_stage,
|
| 232 |
+
self.num_epi_stage,
|
| 233 |
+
) = self._compute_stages(
|
| 234 |
+
tiled_mma,
|
| 235 |
+
self.mma_tiler,
|
| 236 |
+
self.a_dtype,
|
| 237 |
+
self.b_dtype,
|
| 238 |
+
self.epi_tile,
|
| 239 |
+
self.c_dtype,
|
| 240 |
+
self.c_layout,
|
| 241 |
+
self.smem_capacity,
|
| 242 |
+
self.occupancy,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
self.a_smem_layout_staged = sm100_utils.make_smem_layout_a(
|
| 246 |
+
tiled_mma,
|
| 247 |
+
self.mma_tiler,
|
| 248 |
+
self.a_dtype,
|
| 249 |
+
self.num_ab_stage,
|
| 250 |
+
)
|
| 251 |
+
self.b_smem_layout_staged = sm100_utils.make_smem_layout_b(
|
| 252 |
+
tiled_mma,
|
| 253 |
+
self.mma_tiler,
|
| 254 |
+
self.b_dtype,
|
| 255 |
+
self.num_ab_stage,
|
| 256 |
+
)
|
| 257 |
+
self.epi_smem_layout_staged = sm100_utils.make_smem_layout_epi(
|
| 258 |
+
self.c_dtype,
|
| 259 |
+
self.c_layout,
|
| 260 |
+
self.epi_tile,
|
| 261 |
+
self.num_epi_stage,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
mbar_smem_bytes = self._get_mbar_smem_bytes(
|
| 265 |
+
num_acc_stage=self.num_acc_stage,
|
| 266 |
+
num_ab_stage=self.num_ab_stage,
|
| 267 |
+
num_epi_stage=self.num_epi_stage,
|
| 268 |
+
)
|
| 269 |
+
tensormap_smem_bytes = self._get_tensormap_smem_bytes(
|
| 270 |
+
self.tensormap_update_mode
|
| 271 |
+
)
|
| 272 |
+
if (
|
| 273 |
+
mbar_smem_bytes
|
| 274 |
+
+ tensormap_smem_bytes
|
| 275 |
+
+ GroupedGemmKernel.tensor_memory_management_bytes
|
| 276 |
+
> self.reserved_smem_bytes
|
| 277 |
+
):
|
| 278 |
+
raise ValueError(
|
| 279 |
+
f"smem consumption for mbar and tensormap {mbar_smem_bytes + tensormap_smem_bytes} exceeds the "
|
| 280 |
+
f"reserved smem bytes {self.reserved_smem_bytes}"
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# Compute the number of tensor memory allocation columns
|
| 284 |
+
self.num_tmem_alloc_cols = self._compute_num_tmem_alloc_cols(
|
| 285 |
+
tiled_mma, self.mma_tiler, self.num_acc_stage
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
@cute.jit
|
| 289 |
+
def __call__(
|
| 290 |
+
self,
|
| 291 |
+
initial_a: cute.Tensor,
|
| 292 |
+
initial_b: cute.Tensor,
|
| 293 |
+
initial_c: cute.Tensor,
|
| 294 |
+
group_count: cutlass.Constexpr[int],
|
| 295 |
+
problem_shape_mnkl: cute.Tensor,
|
| 296 |
+
strides_abc: cute.Tensor,
|
| 297 |
+
tensor_address_abc: cute.Tensor,
|
| 298 |
+
total_num_clusters: cutlass.Constexpr[int],
|
| 299 |
+
tensormap_cute_tensor: cute.Tensor,
|
| 300 |
+
max_active_clusters: cutlass.Constexpr[int],
|
| 301 |
+
stream: cuda.CUstream,
|
| 302 |
+
):
|
| 303 |
+
"""Execute the GEMM operation in steps:
|
| 304 |
+
- Setup static attributes before smem/grid/tma computation
|
| 305 |
+
- Setup TMA load/store atoms and tensors
|
| 306 |
+
- Compute grid size with regard to hardware constraints
|
| 307 |
+
- Define shared storage for kernel
|
| 308 |
+
- Launch the kernel synchronously
|
| 309 |
+
|
| 310 |
+
For grouped GEMM, tensor shapes, tensor strides, and tensor address are all provided
|
| 311 |
+
by different tensors in global memory. The "initial" tensors only carry data type and
|
| 312 |
+
majorness information.
|
| 313 |
+
|
| 314 |
+
:param initial_a: Initial tensor A, used for data type and majorness information.
|
| 315 |
+
:type initial_a: cute.Tensor
|
| 316 |
+
:param initial_b: Initial tensor B, used for data type and majorness information.
|
| 317 |
+
:type initial_b: cute.Tensor
|
| 318 |
+
:param initial_c: Initial tensor C, used for data type and majorness information.
|
| 319 |
+
:type initial_c: cute.Tensor
|
| 320 |
+
:param group_count: The number of GEMM groups.
|
| 321 |
+
:type group_count: cutlass.Constexpr[int]
|
| 322 |
+
:param problem_shape_mnkl: Tensor containing the (M, N, K, L) shape for each group.
|
| 323 |
+
:type problem_shape_mnkl: cute.Tensor
|
| 324 |
+
:param strides_abc: Tensor containing the strides for A, B, and C for each group.
|
| 325 |
+
:type strides_abc: cute.Tensor
|
| 326 |
+
:param tensor_address_abc: Tensor containing the base addresses for A, B, and C for each group.
|
| 327 |
+
:type tensor_address_abc: cute.Tensor
|
| 328 |
+
:param total_num_clusters: Total number of clusters needed for all groups.
|
| 329 |
+
:type total_num_clusters: cutlass.Constexpr[int]
|
| 330 |
+
:param tensormap_cute_tensor: Tensor for storing tensormaps.
|
| 331 |
+
:type tensormap_cute_tensor: cute.Tensor
|
| 332 |
+
:param max_active_clusters: Maximum number of active clusters.
|
| 333 |
+
:type max_active_clusters: cutlass.Constexpr[int]
|
| 334 |
+
:param stream: CUDA stream for asynchronous execution.
|
| 335 |
+
:type stream: cuda.CUstream
|
| 336 |
+
:raises TypeError: If A and B data types do not match.
|
| 337 |
+
"""
|
| 338 |
+
self.a_dtype = initial_a.element_type
|
| 339 |
+
self.b_dtype = initial_b.element_type
|
| 340 |
+
self.c_dtype = initial_c.element_type
|
| 341 |
+
self.a_major_mode = utils.LayoutEnum.from_tensor(initial_a).mma_major_mode()
|
| 342 |
+
self.b_major_mode = utils.LayoutEnum.from_tensor(initial_b).mma_major_mode()
|
| 343 |
+
self.c_layout = utils.LayoutEnum.from_tensor(initial_c)
|
| 344 |
+
if cutlass.const_expr(self.a_dtype != self.b_dtype):
|
| 345 |
+
raise TypeError(f"Type mismatch: {self.a_dtype} != {self.b_dtype}")
|
| 346 |
+
|
| 347 |
+
# Setup attributes that dependent on gemm inputs
|
| 348 |
+
self._setup_attributes()
|
| 349 |
+
|
| 350 |
+
tiled_mma = sm100_utils.make_trivial_tiled_mma(
|
| 351 |
+
self.a_dtype,
|
| 352 |
+
self.a_major_mode,
|
| 353 |
+
self.b_major_mode,
|
| 354 |
+
self.acc_dtype,
|
| 355 |
+
self.cta_group,
|
| 356 |
+
self.mma_tiler[:2],
|
| 357 |
+
)
|
| 358 |
+
atom_thr_size = cute.size(tiled_mma.thr_id.shape)
|
| 359 |
+
|
| 360 |
+
# Setup TMA load for A
|
| 361 |
+
a_op = sm100_utils.cluster_shape_to_tma_atom_A(
|
| 362 |
+
self.cluster_shape_mn, tiled_mma.thr_id
|
| 363 |
+
)
|
| 364 |
+
a_smem_layout = cute.slice_(self.a_smem_layout_staged, (None, None, None, 0))
|
| 365 |
+
tma_atom_a, tma_tensor_a = cute.nvgpu.make_tiled_tma_atom_A(
|
| 366 |
+
a_op,
|
| 367 |
+
initial_a,
|
| 368 |
+
a_smem_layout,
|
| 369 |
+
self.mma_tiler,
|
| 370 |
+
tiled_mma,
|
| 371 |
+
self.cluster_layout_vmnk.shape,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
# Setup TMA load for B
|
| 375 |
+
b_op = sm100_utils.cluster_shape_to_tma_atom_B(
|
| 376 |
+
self.cluster_shape_mn, tiled_mma.thr_id
|
| 377 |
+
)
|
| 378 |
+
b_smem_layout = cute.slice_(self.b_smem_layout_staged, (None, None, None, 0))
|
| 379 |
+
tma_atom_b, tma_tensor_b = cute.nvgpu.make_tiled_tma_atom_B(
|
| 380 |
+
b_op,
|
| 381 |
+
initial_b,
|
| 382 |
+
b_smem_layout,
|
| 383 |
+
self.mma_tiler,
|
| 384 |
+
tiled_mma,
|
| 385 |
+
self.cluster_layout_vmnk.shape,
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
a_copy_size = cute.size_in_bytes(self.a_dtype, a_smem_layout)
|
| 389 |
+
b_copy_size = cute.size_in_bytes(self.b_dtype, b_smem_layout)
|
| 390 |
+
self.num_tma_load_bytes = (a_copy_size + b_copy_size) * atom_thr_size
|
| 391 |
+
|
| 392 |
+
# Setup TMA store for C
|
| 393 |
+
tma_atom_c = None
|
| 394 |
+
tma_tensor_c = None
|
| 395 |
+
epi_smem_layout = cute.slice_(self.epi_smem_layout_staged, (None, None, 0))
|
| 396 |
+
tma_atom_c, tma_tensor_c = cpasync.make_tiled_tma_atom(
|
| 397 |
+
cpasync.CopyBulkTensorTileS2GOp(),
|
| 398 |
+
initial_c,
|
| 399 |
+
epi_smem_layout,
|
| 400 |
+
self.epi_tile,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
self.tile_sched_params, grid = self._compute_grid(
|
| 404 |
+
total_num_clusters, self.cluster_shape_mn, max_active_clusters
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
self.buffer_align_bytes = 1024
|
| 408 |
+
self.size_tensormap_in_i64 = (
|
| 409 |
+
0
|
| 410 |
+
if self.tensormap_update_mode == utils.TensorMapUpdateMode.GMEM
|
| 411 |
+
else GroupedGemmKernel.num_tensormaps
|
| 412 |
+
* GroupedGemmKernel.bytes_per_tensormap
|
| 413 |
+
// 8
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
# Define shared storage for kernel
|
| 417 |
+
@cute.struct
|
| 418 |
+
class SharedStorage:
|
| 419 |
+
tensormap_buffer: cute.struct.MemRange[
|
| 420 |
+
cutlass.Int64, self.size_tensormap_in_i64
|
| 421 |
+
]
|
| 422 |
+
ab_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage]
|
| 423 |
+
ab_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_ab_stage]
|
| 424 |
+
acc_full_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage]
|
| 425 |
+
acc_empty_mbar_ptr: cute.struct.MemRange[cutlass.Int64, self.num_acc_stage]
|
| 426 |
+
tmem_dealloc_mbar_ptr: cutlass.Int64
|
| 427 |
+
tmem_holding_buf: cutlass.Int32
|
| 428 |
+
# (EPI_TILE_M, EPI_TILE_N, STAGE)
|
| 429 |
+
sC: cute.struct.Align[
|
| 430 |
+
cute.struct.MemRange[
|
| 431 |
+
self.c_dtype,
|
| 432 |
+
cute.cosize(self.epi_smem_layout_staged.outer),
|
| 433 |
+
],
|
| 434 |
+
self.buffer_align_bytes,
|
| 435 |
+
]
|
| 436 |
+
# (MMA, MMA_M, MMA_K, STAGE)
|
| 437 |
+
sA: cute.struct.Align[
|
| 438 |
+
cute.struct.MemRange[
|
| 439 |
+
self.a_dtype, cute.cosize(self.a_smem_layout_staged.outer)
|
| 440 |
+
],
|
| 441 |
+
self.buffer_align_bytes,
|
| 442 |
+
]
|
| 443 |
+
# (MMA, MMA_N, MMA_K, STAGE)
|
| 444 |
+
sB: cute.struct.Align[
|
| 445 |
+
cute.struct.MemRange[
|
| 446 |
+
self.b_dtype, cute.cosize(self.b_smem_layout_staged.outer)
|
| 447 |
+
],
|
| 448 |
+
self.buffer_align_bytes,
|
| 449 |
+
]
|
| 450 |
+
|
| 451 |
+
self.shared_storage = SharedStorage
|
| 452 |
+
|
| 453 |
+
# Launch the kernel synchronously
|
| 454 |
+
self.kernel(
|
| 455 |
+
tiled_mma,
|
| 456 |
+
tma_atom_a,
|
| 457 |
+
tma_tensor_a,
|
| 458 |
+
tma_atom_b,
|
| 459 |
+
tma_tensor_b,
|
| 460 |
+
tma_atom_c,
|
| 461 |
+
tma_tensor_c,
|
| 462 |
+
self.cluster_layout_vmnk,
|
| 463 |
+
self.a_smem_layout_staged,
|
| 464 |
+
self.b_smem_layout_staged,
|
| 465 |
+
self.epi_smem_layout_staged,
|
| 466 |
+
self.epi_tile,
|
| 467 |
+
self.tile_sched_params,
|
| 468 |
+
group_count,
|
| 469 |
+
problem_shape_mnkl,
|
| 470 |
+
strides_abc,
|
| 471 |
+
tensor_address_abc,
|
| 472 |
+
tensormap_cute_tensor,
|
| 473 |
+
).launch(
|
| 474 |
+
grid=grid,
|
| 475 |
+
block=[self.threads_per_cta, 1, 1],
|
| 476 |
+
cluster=(*self.cluster_shape_mn, 1),
|
| 477 |
+
stream=stream,
|
| 478 |
+
)
|
| 479 |
+
return
|
| 480 |
+
|
| 481 |
+
# GPU device kernel
|
| 482 |
+
@cute.kernel
|
| 483 |
+
def kernel(
|
| 484 |
+
self,
|
| 485 |
+
tiled_mma: cute.TiledMma,
|
| 486 |
+
tma_atom_a: cute.CopyAtom,
|
| 487 |
+
mA_mkl: cute.Tensor,
|
| 488 |
+
tma_atom_b: cute.CopyAtom,
|
| 489 |
+
mB_nkl: cute.Tensor,
|
| 490 |
+
tma_atom_c: cute.CopyAtom,
|
| 491 |
+
mC_mnl: cute.Tensor,
|
| 492 |
+
cluster_layout_vmnk: cute.Layout,
|
| 493 |
+
a_smem_layout_staged: cute.ComposedLayout,
|
| 494 |
+
b_smem_layout_staged: cute.ComposedLayout,
|
| 495 |
+
epi_smem_layout_staged: Union[cute.Layout, cute.ComposedLayout],
|
| 496 |
+
epi_tile: cute.Tile,
|
| 497 |
+
tile_sched_params: utils.PersistentTileSchedulerParams,
|
| 498 |
+
group_count: cutlass.Constexpr[int],
|
| 499 |
+
problem_sizes_mnkl: cute.Tensor,
|
| 500 |
+
strides_abc: cute.Tensor,
|
| 501 |
+
ptrs_abc: cute.Tensor,
|
| 502 |
+
tensormaps: cute.Tensor,
|
| 503 |
+
):
|
| 504 |
+
"""
|
| 505 |
+
GPU device kernel performing the grouped GEMM computation.
|
| 506 |
+
"""
|
| 507 |
+
warp_idx = cute.arch.warp_idx()
|
| 508 |
+
warp_idx = cute.arch.make_warp_uniform(warp_idx)
|
| 509 |
+
|
| 510 |
+
#
|
| 511 |
+
# Prefetch tma desc
|
| 512 |
+
#
|
| 513 |
+
if warp_idx == self.tma_warp_id:
|
| 514 |
+
cpasync.prefetch_descriptor(tma_atom_a)
|
| 515 |
+
cpasync.prefetch_descriptor(tma_atom_b)
|
| 516 |
+
cpasync.prefetch_descriptor(tma_atom_c)
|
| 517 |
+
|
| 518 |
+
use_2cta_instrs = cute.size(tiled_mma.thr_id.shape) == 2
|
| 519 |
+
|
| 520 |
+
#
|
| 521 |
+
# Setup cta/thread coordinates
|
| 522 |
+
#
|
| 523 |
+
# Coord inside cluster
|
| 524 |
+
bid = cute.arch.block_idx()
|
| 525 |
+
mma_tile_coord_v = bid[0] % cute.size(tiled_mma.thr_id.shape)
|
| 526 |
+
is_leader_cta = mma_tile_coord_v == 0
|
| 527 |
+
cta_rank_in_cluster = cute.arch.make_warp_uniform(
|
| 528 |
+
cute.arch.block_idx_in_cluster()
|
| 529 |
+
)
|
| 530 |
+
block_in_cluster_coord_vmnk = cluster_layout_vmnk.get_flat_coord(
|
| 531 |
+
cta_rank_in_cluster
|
| 532 |
+
)
|
| 533 |
+
# Coord inside cta
|
| 534 |
+
tidx, _, _ = cute.arch.thread_idx()
|
| 535 |
+
|
| 536 |
+
#
|
| 537 |
+
# Alloc and init: tensormap buffer, a+b full/empty, accumulator full/empty, tensor memory dealloc barrier
|
| 538 |
+
#
|
| 539 |
+
smem = utils.SmemAllocator()
|
| 540 |
+
storage = smem.allocate(self.shared_storage)
|
| 541 |
+
|
| 542 |
+
tensormap_a_smem_ptr = None
|
| 543 |
+
tensormap_b_smem_ptr = None
|
| 544 |
+
tensormap_c_smem_ptr = None
|
| 545 |
+
if cutlass.const_expr(
|
| 546 |
+
self.tensormap_update_mode == utils.TensorMapUpdateMode.SMEM
|
| 547 |
+
):
|
| 548 |
+
tensormap_smem_ptr = storage.tensormap_buffer.data_ptr()
|
| 549 |
+
tensormap_a_smem_ptr = tensormap_smem_ptr
|
| 550 |
+
tensormap_b_smem_ptr = (
|
| 551 |
+
tensormap_a_smem_ptr + GroupedGemmKernel.bytes_per_tensormap // 8
|
| 552 |
+
)
|
| 553 |
+
tensormap_c_smem_ptr = (
|
| 554 |
+
tensormap_b_smem_ptr + GroupedGemmKernel.bytes_per_tensormap // 8
|
| 555 |
+
)
|
| 556 |
+
ab_full_mbar_ptr = storage.ab_full_mbar_ptr.data_ptr()
|
| 557 |
+
ab_empty_mbar_ptr = storage.ab_empty_mbar_ptr.data_ptr()
|
| 558 |
+
acc_full_mbar_ptr = storage.acc_full_mbar_ptr.data_ptr()
|
| 559 |
+
acc_empty_mbar_ptr = storage.acc_empty_mbar_ptr.data_ptr()
|
| 560 |
+
|
| 561 |
+
# init barrier for loading A, B with TMA
|
| 562 |
+
if warp_idx == self.epilog_warp_id[0]:
|
| 563 |
+
for k_stage in range(self.num_ab_stage):
|
| 564 |
+
num_tma_producer = self.num_mcast_ctas_a + self.num_mcast_ctas_b - 1
|
| 565 |
+
with cute.arch.elect_one():
|
| 566 |
+
cute.arch.mbarrier_init(ab_full_mbar_ptr + k_stage, 1)
|
| 567 |
+
cute.arch.mbarrier_init(
|
| 568 |
+
ab_empty_mbar_ptr + k_stage, num_tma_producer
|
| 569 |
+
)
|
| 570 |
+
# Accumulator barrier init
|
| 571 |
+
if warp_idx == self.mma_warp_id:
|
| 572 |
+
for acc_stage in range(self.num_acc_stage):
|
| 573 |
+
with cute.arch.elect_one():
|
| 574 |
+
cute.arch.mbarrier_init(acc_full_mbar_ptr + acc_stage, 1)
|
| 575 |
+
cute.arch.mbarrier_init(
|
| 576 |
+
acc_empty_mbar_ptr + acc_stage, 8 if use_2cta_instrs else 4
|
| 577 |
+
)
|
| 578 |
+
# Tensor memory dealloc barrier init
|
| 579 |
+
tmem = utils.TmemAllocator(
|
| 580 |
+
storage.tmem_holding_buf,
|
| 581 |
+
barrier_for_retrieve=self.tmem_alloc_barrier,
|
| 582 |
+
allocator_warp_id=self.epilog_warp_id[0],
|
| 583 |
+
is_two_cta=use_2cta_instrs,
|
| 584 |
+
two_cta_tmem_dealloc_mbar_ptr=storage.tmem_dealloc_mbar_ptr,
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
# Cluster arrive after barrier init
|
| 588 |
+
pipeline_init_arrive(cluster_shape_mn=self.cluster_shape_mn, is_relaxed=True)
|
| 589 |
+
|
| 590 |
+
#
|
| 591 |
+
# Setup smem tensor A/B/C
|
| 592 |
+
#
|
| 593 |
+
# (EPI_TILE_M, EPI_TILE_N, STAGE)
|
| 594 |
+
sC = storage.sC.get_tensor(
|
| 595 |
+
epi_smem_layout_staged.outer, swizzle=epi_smem_layout_staged.inner
|
| 596 |
+
)
|
| 597 |
+
# (MMA, MMA_M, MMA_K, STAGE)
|
| 598 |
+
sA = storage.sA.get_tensor(
|
| 599 |
+
a_smem_layout_staged.outer, swizzle=a_smem_layout_staged.inner
|
| 600 |
+
)
|
| 601 |
+
# (MMA, MMA_N, MMA_K, STAGE)
|
| 602 |
+
sB = storage.sB.get_tensor(
|
| 603 |
+
b_smem_layout_staged.outer, swizzle=b_smem_layout_staged.inner
|
| 604 |
+
)
|
| 605 |
+
|
| 606 |
+
#
|
| 607 |
+
# Compute multicast mask for A/B buffer full and empty
|
| 608 |
+
#
|
| 609 |
+
a_full_mcast_mask = None
|
| 610 |
+
b_full_mcast_mask = None
|
| 611 |
+
ab_empty_mcast_mask = None
|
| 612 |
+
if cutlass.const_expr(self.is_a_mcast or self.is_b_mcast or use_2cta_instrs):
|
| 613 |
+
a_full_mcast_mask = cpasync.create_tma_multicast_mask(
|
| 614 |
+
cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=2
|
| 615 |
+
)
|
| 616 |
+
b_full_mcast_mask = cpasync.create_tma_multicast_mask(
|
| 617 |
+
cluster_layout_vmnk, block_in_cluster_coord_vmnk, mcast_mode=1
|
| 618 |
+
)
|
| 619 |
+
ab_empty_mcast_mask = a_full_mcast_mask | b_full_mcast_mask
|
| 620 |
+
acc_full_mcast_mask = None
|
| 621 |
+
if cutlass.const_expr(use_2cta_instrs):
|
| 622 |
+
acc_full_mcast_mask = cute.make_layout_image_mask(
|
| 623 |
+
cluster_layout_vmnk, block_in_cluster_coord_vmnk, mode=0
|
| 624 |
+
)
|
| 625 |
+
block_in_cluster_coord_vmnk_peer = (
|
| 626 |
+
block_in_cluster_coord_vmnk[0] ^ 1,
|
| 627 |
+
*block_in_cluster_coord_vmnk[1:],
|
| 628 |
+
)
|
| 629 |
+
a_full_mcast_mask_peer = cpasync.create_tma_multicast_mask(
|
| 630 |
+
cluster_layout_vmnk, block_in_cluster_coord_vmnk_peer, mcast_mode=2
|
| 631 |
+
)
|
| 632 |
+
b_full_mcast_mask_peer = cpasync.create_tma_multicast_mask(
|
| 633 |
+
cluster_layout_vmnk, block_in_cluster_coord_vmnk_peer, mcast_mode=1
|
| 634 |
+
)
|
| 635 |
+
ab_empty_mcast_mask = (
|
| 636 |
+
a_full_mcast_mask_peer
|
| 637 |
+
| b_full_mcast_mask_peer
|
| 638 |
+
| cutlass.Int16(
|
| 639 |
+
0 if ab_empty_mcast_mask is None else ab_empty_mcast_mask
|
| 640 |
+
)
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
#
|
| 644 |
+
# Local_tile partition global tensors
|
| 645 |
+
#
|
| 646 |
+
# (bM, bK, RestM, RestK, RestL)
|
| 647 |
+
gA_mkl = cute.local_tile(
|
| 648 |
+
mA_mkl, cute.slice_(self.mma_tiler, (None, 0, None)), (None, None, None)
|
| 649 |
+
)
|
| 650 |
+
# (bN, bK, RestN, RestK, RestL)
|
| 651 |
+
gB_nkl = cute.local_tile(
|
| 652 |
+
mB_nkl, cute.slice_(self.mma_tiler, (0, None, None)), (None, None, None)
|
| 653 |
+
)
|
| 654 |
+
# (bM, bN, RestM, RestN, RestL)
|
| 655 |
+
gC_mnl = cute.local_tile(
|
| 656 |
+
mC_mnl, cute.slice_(self.mma_tiler, (None, None, 0)), (None, None, None)
|
| 657 |
+
)
|
| 658 |
+
|
| 659 |
+
#
|
| 660 |
+
# Partition global tensor for TiledMMA_A/B/C
|
| 661 |
+
#
|
| 662 |
+
thr_mma = tiled_mma.get_slice(mma_tile_coord_v)
|
| 663 |
+
# (MMA, MMA_M, MMA_K, RestM, RestK, RestL)
|
| 664 |
+
tCgA = thr_mma.partition_A(gA_mkl)
|
| 665 |
+
# (MMA, MMA_N, MMA_K, RestN, RestK, RestL)
|
| 666 |
+
tCgB = thr_mma.partition_B(gB_nkl)
|
| 667 |
+
# (MMA, MMA_M, MMA_N, RestM, RestN, RestL)
|
| 668 |
+
tCgC = thr_mma.partition_C(gC_mnl)
|
| 669 |
+
|
| 670 |
+
#
|
| 671 |
+
# Partition global/shared tensor for load A, B with TMA
|
| 672 |
+
#
|
| 673 |
+
a_cta_layout = cute.make_layout(
|
| 674 |
+
cute.slice_(cluster_layout_vmnk, (0, 0, None, 0)).shape
|
| 675 |
+
)
|
| 676 |
+
# ((atom_v, rest_v), STAGE)
|
| 677 |
+
# ((atom_v, rest_v), RestM, RestK, RestL)
|
| 678 |
+
tAsA, tAgA = cpasync.tma_partition(
|
| 679 |
+
tma_atom_a,
|
| 680 |
+
block_in_cluster_coord_vmnk[2],
|
| 681 |
+
a_cta_layout,
|
| 682 |
+
cute.group_modes(sA, 0, 3),
|
| 683 |
+
cute.group_modes(tCgA, 0, 3),
|
| 684 |
+
)
|
| 685 |
+
# TMA load B partition_S/D
|
| 686 |
+
b_cta_layout = cute.make_layout(
|
| 687 |
+
cute.slice_(cluster_layout_vmnk, (0, None, 0, 0)).shape
|
| 688 |
+
)
|
| 689 |
+
# ((atom_v, rest_v), STAGE)
|
| 690 |
+
# ((atom_v, rest_v), RestM, RestK, RestL)
|
| 691 |
+
tBsB, tBgB = cpasync.tma_partition(
|
| 692 |
+
tma_atom_b,
|
| 693 |
+
block_in_cluster_coord_vmnk[1],
|
| 694 |
+
b_cta_layout,
|
| 695 |
+
cute.group_modes(sB, 0, 3),
|
| 696 |
+
cute.group_modes(tCgB, 0, 3),
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
#
|
| 700 |
+
# Partition shared/tensor memory tensor for TiledMMA_A/B/C
|
| 701 |
+
#
|
| 702 |
+
# (MMA, MMA_M, MMA_K, STAGE)
|
| 703 |
+
tCrA = tiled_mma.make_fragment_A(sA)
|
| 704 |
+
# (MMA, MMA_N, MMA_K, STAGE)
|
| 705 |
+
tCrB = tiled_mma.make_fragment_B(sB)
|
| 706 |
+
# (MMA, MMA_M, MMA_N)
|
| 707 |
+
acc_shape = tiled_mma.partition_shape_C(self.mma_tiler[:2])
|
| 708 |
+
# (MMA, MMA_M, MMA_N, STAGE)
|
| 709 |
+
tCtAcc_fake = tiled_mma.make_fragment_C(
|
| 710 |
+
cute.append(acc_shape, self.num_acc_stage)
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
#
|
| 714 |
+
# Cluster wait before tensor memory alloc
|
| 715 |
+
#
|
| 716 |
+
pipeline_init_wait(cluster_shape_mn=self.cluster_shape_mn)
|
| 717 |
+
|
| 718 |
+
#
|
| 719 |
+
# Get tensormap buffer address
|
| 720 |
+
#
|
| 721 |
+
grid_dim = cute.arch.grid_dim()
|
| 722 |
+
tensormap_workspace_idx = (
|
| 723 |
+
bid[2] * grid_dim[1] * grid_dim[0] + bid[1] * grid_dim[0] + bid[0]
|
| 724 |
+
)
|
| 725 |
+
|
| 726 |
+
tensormap_manager = utils.TensorMapManager(
|
| 727 |
+
self.tensormap_update_mode, GroupedGemmKernel.bytes_per_tensormap
|
| 728 |
+
)
|
| 729 |
+
tensormap_a_ptr = tensormap_manager.get_tensormap_ptr(
|
| 730 |
+
tensormaps[(tensormap_workspace_idx, 0, None)].iterator
|
| 731 |
+
)
|
| 732 |
+
tensormap_b_ptr = tensormap_manager.get_tensormap_ptr(
|
| 733 |
+
tensormaps[(tensormap_workspace_idx, 1, None)].iterator
|
| 734 |
+
)
|
| 735 |
+
tensormap_c_ptr = tensormap_manager.get_tensormap_ptr(
|
| 736 |
+
tensormaps[(tensormap_workspace_idx, 2, None)].iterator
|
| 737 |
+
)
|
| 738 |
+
# Setup tensormap initialization pointer based on the mode
|
| 739 |
+
if cutlass.const_expr(
|
| 740 |
+
self.tensormap_update_mode == utils.TensorMapUpdateMode.SMEM
|
| 741 |
+
):
|
| 742 |
+
tensormap_a_init_ptr = tensormap_a_smem_ptr
|
| 743 |
+
tensormap_b_init_ptr = tensormap_b_smem_ptr
|
| 744 |
+
tensormap_c_init_ptr = tensormap_c_smem_ptr
|
| 745 |
+
else:
|
| 746 |
+
tensormap_a_init_ptr = tensormap_a_ptr
|
| 747 |
+
tensormap_b_init_ptr = tensormap_b_ptr
|
| 748 |
+
tensormap_c_init_ptr = tensormap_c_ptr
|
| 749 |
+
|
| 750 |
+
#
|
| 751 |
+
# Specialized TMA load warp
|
| 752 |
+
#
|
| 753 |
+
if warp_idx == self.tma_warp_id:
|
| 754 |
+
# Initialize tensormaps for A, B
|
| 755 |
+
if cutlass.const_expr(self.delegate_tensormap_ab_init == False):
|
| 756 |
+
tensormap_manager.init_tensormap_from_atom(
|
| 757 |
+
tma_atom_a, tensormap_a_init_ptr, self.tma_warp_id
|
| 758 |
+
)
|
| 759 |
+
tensormap_manager.init_tensormap_from_atom(
|
| 760 |
+
tma_atom_b, tensormap_b_init_ptr, self.tma_warp_id
|
| 761 |
+
)
|
| 762 |
+
#
|
| 763 |
+
# Persistent tile scheduling loop
|
| 764 |
+
#
|
| 765 |
+
tile_sched = utils.StaticPersistentTileScheduler.create(
|
| 766 |
+
tile_sched_params, bid, grid_dim
|
| 767 |
+
)
|
| 768 |
+
# grouped gemm tile scheduler helper will compute the group index for the tile we're working on
|
| 769 |
+
group_gemm_ts_helper = utils.GroupedGemmTileSchedulerHelper(
|
| 770 |
+
group_count,
|
| 771 |
+
tile_sched_params,
|
| 772 |
+
self.cluster_tile_shape_mnk,
|
| 773 |
+
utils.create_initial_search_state(),
|
| 774 |
+
)
|
| 775 |
+
tensormap_init_done = cutlass.Boolean(False)
|
| 776 |
+
# tile count we have searched
|
| 777 |
+
total_k_tile_cnt = cutlass.Int32(0)
|
| 778 |
+
# group index of last tile
|
| 779 |
+
last_group_idx = cutlass.Int32(-1)
|
| 780 |
+
work_tile = tile_sched.initial_work_tile_info()
|
| 781 |
+
while work_tile.is_valid_tile:
|
| 782 |
+
cur_tile_coord = work_tile.tile_idx
|
| 783 |
+
grouped_gemm_cta_tile_info = group_gemm_ts_helper.delinearize_z(
|
| 784 |
+
cur_tile_coord,
|
| 785 |
+
problem_sizes_mnkl,
|
| 786 |
+
)
|
| 787 |
+
cur_k_tile_cnt = grouped_gemm_cta_tile_info.cta_tile_count_k
|
| 788 |
+
cur_group_idx = grouped_gemm_cta_tile_info.group_idx
|
| 789 |
+
is_group_changed = cur_group_idx != last_group_idx
|
| 790 |
+
# skip tensormap update if we're working on the same group
|
| 791 |
+
if is_group_changed:
|
| 792 |
+
real_tensor_a = self.make_tensor_for_tensormap_update(
|
| 793 |
+
cur_group_idx,
|
| 794 |
+
self.a_dtype,
|
| 795 |
+
(
|
| 796 |
+
grouped_gemm_cta_tile_info.problem_shape_m,
|
| 797 |
+
grouped_gemm_cta_tile_info.problem_shape_n,
|
| 798 |
+
grouped_gemm_cta_tile_info.problem_shape_k,
|
| 799 |
+
),
|
| 800 |
+
strides_abc,
|
| 801 |
+
ptrs_abc,
|
| 802 |
+
0, # 0 for tensor A
|
| 803 |
+
)
|
| 804 |
+
real_tensor_b = self.make_tensor_for_tensormap_update(
|
| 805 |
+
cur_group_idx,
|
| 806 |
+
self.b_dtype,
|
| 807 |
+
(
|
| 808 |
+
grouped_gemm_cta_tile_info.problem_shape_m,
|
| 809 |
+
grouped_gemm_cta_tile_info.problem_shape_n,
|
| 810 |
+
grouped_gemm_cta_tile_info.problem_shape_k,
|
| 811 |
+
),
|
| 812 |
+
strides_abc,
|
| 813 |
+
ptrs_abc,
|
| 814 |
+
1, # 1 for tensor B
|
| 815 |
+
)
|
| 816 |
+
# wait tensormap initialization complete before update
|
| 817 |
+
if tensormap_init_done == False:
|
| 818 |
+
if cutlass.const_expr(self.delegate_tensormap_ab_init):
|
| 819 |
+
self.tensormap_ab_init_barrier.arrive_and_wait()
|
| 820 |
+
tensormap_manager.fence_tensormap_initialization()
|
| 821 |
+
tensormap_init_done = True
|
| 822 |
+
|
| 823 |
+
tensormap_manager.update_tensormap(
|
| 824 |
+
(real_tensor_a, real_tensor_b),
|
| 825 |
+
(tma_atom_a, tma_atom_b),
|
| 826 |
+
(tensormap_a_ptr, tensormap_b_ptr),
|
| 827 |
+
self.tma_warp_id,
|
| 828 |
+
(tensormap_a_smem_ptr, tensormap_b_smem_ptr),
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
mma_tile_coord_mnl = (
|
| 832 |
+
grouped_gemm_cta_tile_info.cta_tile_idx_m
|
| 833 |
+
// cute.size(tiled_mma.thr_id.shape),
|
| 834 |
+
grouped_gemm_cta_tile_info.cta_tile_idx_n,
|
| 835 |
+
0,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
#
|
| 839 |
+
# Slice to per mma tile index
|
| 840 |
+
#
|
| 841 |
+
# ((atom_v, rest_v), RestK)
|
| 842 |
+
tAgA_slice = tAgA[
|
| 843 |
+
(None, mma_tile_coord_mnl[0], None, mma_tile_coord_mnl[2])
|
| 844 |
+
]
|
| 845 |
+
# ((atom_v, rest_v), RestK)
|
| 846 |
+
tBgB_slice = tBgB[
|
| 847 |
+
(None, mma_tile_coord_mnl[1], None, mma_tile_coord_mnl[2])
|
| 848 |
+
]
|
| 849 |
+
|
| 850 |
+
num_prev_k_blk = total_k_tile_cnt
|
| 851 |
+
total_k_tile_cnt += cur_k_tile_cnt
|
| 852 |
+
|
| 853 |
+
# Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt
|
| 854 |
+
tma_wr_k_tile = cutlass.Int32(0)
|
| 855 |
+
smem_wr_buffer = (num_prev_k_blk + tma_wr_k_tile) % self.num_ab_stage
|
| 856 |
+
tma_wr_ab_empty_phase = (
|
| 857 |
+
num_prev_k_blk + tma_wr_k_tile
|
| 858 |
+
) // self.num_ab_stage % 2 ^ 1
|
| 859 |
+
peek_ab_empty_status = cute.arch.mbarrier_conditional_try_wait(
|
| 860 |
+
tma_wr_k_tile < cur_k_tile_cnt,
|
| 861 |
+
ab_empty_mbar_ptr + smem_wr_buffer,
|
| 862 |
+
tma_wr_ab_empty_phase,
|
| 863 |
+
)
|
| 864 |
+
# ensure the update to tensormap has completed before using it
|
| 865 |
+
if is_group_changed:
|
| 866 |
+
tensormap_manager.fence_tensormap_update(tensormap_a_ptr)
|
| 867 |
+
tensormap_manager.fence_tensormap_update(tensormap_b_ptr)
|
| 868 |
+
#
|
| 869 |
+
# Tma load loop
|
| 870 |
+
#
|
| 871 |
+
for k_tile in cutlass.range(0, cur_k_tile_cnt, 1, unroll=1):
|
| 872 |
+
tma_wr_k_tile_next = tma_wr_k_tile + 1
|
| 873 |
+
smem_wr_buffer_next = (
|
| 874 |
+
num_prev_k_blk + tma_wr_k_tile_next
|
| 875 |
+
) % self.num_ab_stage
|
| 876 |
+
tma_wr_ab_empty_phase_next = (
|
| 877 |
+
tma_wr_ab_empty_phase ^ 1
|
| 878 |
+
if smem_wr_buffer_next == 0
|
| 879 |
+
else tma_wr_ab_empty_phase
|
| 880 |
+
)
|
| 881 |
+
|
| 882 |
+
smem_full_mbar_ptr = ab_full_mbar_ptr + smem_wr_buffer
|
| 883 |
+
|
| 884 |
+
# Wait for AB buffer empty
|
| 885 |
+
if peek_ab_empty_status == 0:
|
| 886 |
+
cute.arch.mbarrier_wait(
|
| 887 |
+
ab_empty_mbar_ptr + smem_wr_buffer, tma_wr_ab_empty_phase
|
| 888 |
+
)
|
| 889 |
+
|
| 890 |
+
# Arrive AB buffer and expect full transaction bytes
|
| 891 |
+
if is_leader_cta:
|
| 892 |
+
with cute.arch.elect_one():
|
| 893 |
+
cute.arch.mbarrier_arrive_and_expect_tx(
|
| 894 |
+
smem_full_mbar_ptr, self.num_tma_load_bytes
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
# Load A/B with TMA
|
| 898 |
+
cute.copy(
|
| 899 |
+
tma_atom_a,
|
| 900 |
+
tAgA_slice[(None, tma_wr_k_tile)],
|
| 901 |
+
tAsA[(None, smem_wr_buffer)],
|
| 902 |
+
tma_bar_ptr=smem_full_mbar_ptr,
|
| 903 |
+
mcast_mask=a_full_mcast_mask,
|
| 904 |
+
tma_desc_ptr=tensormap_manager.get_tensormap_ptr(
|
| 905 |
+
tensormap_a_ptr,
|
| 906 |
+
cute.AddressSpace.generic,
|
| 907 |
+
),
|
| 908 |
+
)
|
| 909 |
+
cute.copy(
|
| 910 |
+
tma_atom_b,
|
| 911 |
+
tBgB_slice[(None, tma_wr_k_tile)],
|
| 912 |
+
tBsB[(None, smem_wr_buffer)],
|
| 913 |
+
tma_bar_ptr=smem_full_mbar_ptr,
|
| 914 |
+
mcast_mask=b_full_mcast_mask,
|
| 915 |
+
tma_desc_ptr=tensormap_manager.get_tensormap_ptr(
|
| 916 |
+
tensormap_b_ptr,
|
| 917 |
+
cute.AddressSpace.generic,
|
| 918 |
+
),
|
| 919 |
+
)
|
| 920 |
+
|
| 921 |
+
# Peek (try_wait) AB buffer empty for k_tile = prefetch_k_tile_cnt + k_tile + 1
|
| 922 |
+
peek_ab_empty_status = cute.arch.mbarrier_conditional_try_wait(
|
| 923 |
+
tma_wr_k_tile_next < cur_k_tile_cnt,
|
| 924 |
+
ab_empty_mbar_ptr + smem_wr_buffer_next,
|
| 925 |
+
tma_wr_ab_empty_phase_next,
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
tma_wr_k_tile = tma_wr_k_tile_next
|
| 929 |
+
smem_wr_buffer = smem_wr_buffer_next
|
| 930 |
+
tma_wr_ab_empty_phase = tma_wr_ab_empty_phase_next
|
| 931 |
+
|
| 932 |
+
# Advance to next tile
|
| 933 |
+
tile_sched.advance_to_next_work()
|
| 934 |
+
work_tile = tile_sched.get_current_work()
|
| 935 |
+
last_group_idx = cur_group_idx
|
| 936 |
+
|
| 937 |
+
#
|
| 938 |
+
# Specialized MMA warp
|
| 939 |
+
#
|
| 940 |
+
if warp_idx == self.mma_warp_id:
|
| 941 |
+
# Bar sync for retrieve tmem ptr from shared mem
|
| 942 |
+
tmem.wait_for_alloc()
|
| 943 |
+
|
| 944 |
+
#
|
| 945 |
+
# Retrieving tensor memory ptr and make accumulator tensor
|
| 946 |
+
#
|
| 947 |
+
tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
|
| 948 |
+
# (MMA, MMA_M, MMA_N, STAGE)
|
| 949 |
+
tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
|
| 950 |
+
|
| 951 |
+
#
|
| 952 |
+
# Persistent tile scheduling loop
|
| 953 |
+
#
|
| 954 |
+
tile_sched = utils.StaticPersistentTileScheduler.create(
|
| 955 |
+
tile_sched_params, bid, grid_dim
|
| 956 |
+
)
|
| 957 |
+
# grouped gemm tile scheduler helper will compute the group index for the tile we're working on
|
| 958 |
+
group_gemm_ts_helper = utils.GroupedGemmTileSchedulerHelper(
|
| 959 |
+
group_count,
|
| 960 |
+
tile_sched_params,
|
| 961 |
+
self.cluster_tile_shape_mnk,
|
| 962 |
+
utils.create_initial_search_state(),
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
work_tile = tile_sched.initial_work_tile_info()
|
| 966 |
+
# tile count we have searched
|
| 967 |
+
total_k_tile_cnt = cutlass.Int32(0)
|
| 968 |
+
while work_tile.is_valid_tile:
|
| 969 |
+
cur_tile_coord = work_tile.tile_idx
|
| 970 |
+
# MMA warp is only interested in number of tiles along K dimension
|
| 971 |
+
(
|
| 972 |
+
cur_k_tile_cnt,
|
| 973 |
+
cur_group_idx,
|
| 974 |
+
) = group_gemm_ts_helper.search_cluster_tile_count_k(
|
| 975 |
+
cur_tile_coord,
|
| 976 |
+
problem_sizes_mnkl,
|
| 977 |
+
)
|
| 978 |
+
# Set tensor memory buffer for current tile
|
| 979 |
+
acc_buf_idx = tile_sched.num_tiles_executed % self.num_acc_stage
|
| 980 |
+
# (MMA, MMA_M, MMA_N)
|
| 981 |
+
tCtAcc = tCtAcc_base[(None, None, None, acc_buf_idx)]
|
| 982 |
+
|
| 983 |
+
num_prev_k_blk = total_k_tile_cnt
|
| 984 |
+
total_k_tile_cnt += cur_k_tile_cnt
|
| 985 |
+
|
| 986 |
+
# Peek (try_wait) AB buffer full for k_tile = 0
|
| 987 |
+
mma_rd_k_tile = cutlass.Int32(0)
|
| 988 |
+
smem_rd_buffer = (num_prev_k_blk + mma_rd_k_tile) % self.num_ab_stage
|
| 989 |
+
if is_leader_cta:
|
| 990 |
+
need_check_rd_buffer_full = (
|
| 991 |
+
mma_rd_k_tile < cur_k_tile_cnt and is_leader_cta
|
| 992 |
+
)
|
| 993 |
+
mma_rd_ab_full_phase = (
|
| 994 |
+
(num_prev_k_blk + mma_rd_k_tile) // self.num_ab_stage % 2
|
| 995 |
+
)
|
| 996 |
+
peek_ab_full_status = cute.arch.mbarrier_conditional_try_wait(
|
| 997 |
+
need_check_rd_buffer_full,
|
| 998 |
+
ab_full_mbar_ptr + smem_rd_buffer,
|
| 999 |
+
mma_rd_ab_full_phase,
|
| 1000 |
+
)
|
| 1001 |
+
|
| 1002 |
+
#
|
| 1003 |
+
# Wait for accumulator buffer empty
|
| 1004 |
+
#
|
| 1005 |
+
acc_empty_phase = (
|
| 1006 |
+
tile_sched.num_tiles_executed // self.num_acc_stage % 2 ^ 1
|
| 1007 |
+
)
|
| 1008 |
+
cute.arch.mbarrier_wait(
|
| 1009 |
+
acc_empty_mbar_ptr + acc_buf_idx, acc_empty_phase
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
#
|
| 1013 |
+
# Reset the ACCUMULATE field for each tile
|
| 1014 |
+
#
|
| 1015 |
+
tiled_mma.set(tcgen05.Field.ACCUMULATE, False)
|
| 1016 |
+
|
| 1017 |
+
#
|
| 1018 |
+
# Mma mainloop
|
| 1019 |
+
#
|
| 1020 |
+
for k_tile in range(cur_k_tile_cnt):
|
| 1021 |
+
mma_rd_k_tile_next = cutlass.Int32(k_tile + 1)
|
| 1022 |
+
smem_rd_buffer_next = (
|
| 1023 |
+
num_prev_k_blk + mma_rd_k_tile_next
|
| 1024 |
+
) % self.num_ab_stage
|
| 1025 |
+
mma_rd_ab_full_phase_next = (
|
| 1026 |
+
mma_rd_ab_full_phase ^ 1
|
| 1027 |
+
if smem_rd_buffer_next == 0
|
| 1028 |
+
else mma_rd_ab_full_phase
|
| 1029 |
+
)
|
| 1030 |
+
# Wait for AB buffer full
|
| 1031 |
+
if peek_ab_full_status == 0:
|
| 1032 |
+
cute.arch.mbarrier_wait(
|
| 1033 |
+
ab_full_mbar_ptr + smem_rd_buffer, mma_rd_ab_full_phase
|
| 1034 |
+
)
|
| 1035 |
+
|
| 1036 |
+
# tCtAcc += tCrA * tCrB
|
| 1037 |
+
num_kblocks = cute.size(tCrA, mode=[2])
|
| 1038 |
+
for kblock_idx in cutlass.range(num_kblocks, unroll_full=True):
|
| 1039 |
+
kblock_coord = (None, None, kblock_idx, smem_rd_buffer)
|
| 1040 |
+
|
| 1041 |
+
cute.gemm(
|
| 1042 |
+
tiled_mma,
|
| 1043 |
+
tCtAcc,
|
| 1044 |
+
tCrA[kblock_coord],
|
| 1045 |
+
tCrB[kblock_coord],
|
| 1046 |
+
tCtAcc,
|
| 1047 |
+
)
|
| 1048 |
+
# Enable accumulate on tCtAcc after first kblock
|
| 1049 |
+
tiled_mma.set(tcgen05.Field.ACCUMULATE, True)
|
| 1050 |
+
|
| 1051 |
+
# Async arrive AB buffer empty
|
| 1052 |
+
with cute.arch.elect_one():
|
| 1053 |
+
tcgen05.commit(
|
| 1054 |
+
ab_empty_mbar_ptr + smem_rd_buffer,
|
| 1055 |
+
ab_empty_mcast_mask,
|
| 1056 |
+
self.cta_group,
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
# Peek (try_wait) AB buffer full for k_tile = k_tile + 1
|
| 1060 |
+
need_check_rd_buffer_full = (
|
| 1061 |
+
mma_rd_k_tile_next < cur_k_tile_cnt and is_leader_cta
|
| 1062 |
+
)
|
| 1063 |
+
|
| 1064 |
+
peek_ab_full_status = cute.arch.mbarrier_conditional_try_wait(
|
| 1065 |
+
need_check_rd_buffer_full,
|
| 1066 |
+
ab_full_mbar_ptr + smem_rd_buffer_next,
|
| 1067 |
+
mma_rd_ab_full_phase_next,
|
| 1068 |
+
)
|
| 1069 |
+
|
| 1070 |
+
mma_rd_k_tile = mma_rd_k_tile_next
|
| 1071 |
+
smem_rd_buffer = smem_rd_buffer_next
|
| 1072 |
+
mma_rd_ab_full_phase = mma_rd_ab_full_phase_next
|
| 1073 |
+
|
| 1074 |
+
#
|
| 1075 |
+
# Async arrive accumulator buffer full
|
| 1076 |
+
#
|
| 1077 |
+
with cute.arch.elect_one():
|
| 1078 |
+
tcgen05.commit(
|
| 1079 |
+
acc_full_mbar_ptr + acc_buf_idx,
|
| 1080 |
+
acc_full_mcast_mask,
|
| 1081 |
+
self.cta_group,
|
| 1082 |
+
)
|
| 1083 |
+
|
| 1084 |
+
#
|
| 1085 |
+
# Advance to next tile
|
| 1086 |
+
#
|
| 1087 |
+
tile_sched.advance_to_next_work()
|
| 1088 |
+
work_tile = tile_sched.get_current_work()
|
| 1089 |
+
|
| 1090 |
+
#
|
| 1091 |
+
# Specialized epilogue warps
|
| 1092 |
+
#
|
| 1093 |
+
if warp_idx < self.mma_warp_id:
|
| 1094 |
+
# initialize tensormap A, B for TMA warp
|
| 1095 |
+
if cutlass.const_expr(self.delegate_tensormap_ab_init):
|
| 1096 |
+
tensormap_manager.init_tensormap_from_atom(
|
| 1097 |
+
tma_atom_a, tensormap_a_init_ptr, self.epilog_warp_id[0]
|
| 1098 |
+
)
|
| 1099 |
+
tensormap_manager.init_tensormap_from_atom(
|
| 1100 |
+
tma_atom_b, tensormap_b_init_ptr, self.epilog_warp_id[0]
|
| 1101 |
+
)
|
| 1102 |
+
# signal tensormap initialization has finished
|
| 1103 |
+
self.tensormap_ab_init_barrier.arrive_and_wait()
|
| 1104 |
+
# initialize tensorap for C
|
| 1105 |
+
tensormap_manager.init_tensormap_from_atom(
|
| 1106 |
+
tma_atom_c,
|
| 1107 |
+
tensormap_c_init_ptr,
|
| 1108 |
+
self.epilog_warp_id[0],
|
| 1109 |
+
)
|
| 1110 |
+
# Alloc tensor memory buffer
|
| 1111 |
+
tmem.allocate(self.num_tmem_alloc_cols)
|
| 1112 |
+
|
| 1113 |
+
#
|
| 1114 |
+
# Bar sync for retrieve tensor memory ptr from shared memory
|
| 1115 |
+
#
|
| 1116 |
+
tmem.wait_for_alloc()
|
| 1117 |
+
|
| 1118 |
+
#
|
| 1119 |
+
# Retrieving tensor memory ptr and make accumulator tensor
|
| 1120 |
+
#
|
| 1121 |
+
tmem_ptr = tmem.retrieve_ptr(self.acc_dtype)
|
| 1122 |
+
# (MMA, MMA_M, MMA_N, STAGE)
|
| 1123 |
+
tCtAcc_base = cute.make_tensor(tmem_ptr, tCtAcc_fake.layout)
|
| 1124 |
+
|
| 1125 |
+
epi_tidx = tidx
|
| 1126 |
+
#
|
| 1127 |
+
# Partition for epilogue
|
| 1128 |
+
#
|
| 1129 |
+
(
|
| 1130 |
+
tiled_copy_t2r,
|
| 1131 |
+
tTR_tAcc_base,
|
| 1132 |
+
tTR_rAcc,
|
| 1133 |
+
) = self.epilog_tmem_copy_and_partition(
|
| 1134 |
+
epi_tidx, tCtAcc_base, tCgC, epi_tile, use_2cta_instrs
|
| 1135 |
+
)
|
| 1136 |
+
|
| 1137 |
+
tTR_rC = cute.make_rmem_tensor(tTR_rAcc.shape, self.c_dtype)
|
| 1138 |
+
tiled_copy_r2s, tRS_rC, tRS_sC = self.epilog_smem_copy_and_partition(
|
| 1139 |
+
tiled_copy_t2r, tTR_rC, epi_tidx, sC
|
| 1140 |
+
)
|
| 1141 |
+
(
|
| 1142 |
+
tma_atom_c,
|
| 1143 |
+
bSG_sC,
|
| 1144 |
+
bSG_gC_partitioned,
|
| 1145 |
+
) = self.epilog_gmem_copy_and_partition(tma_atom_c, tCgC, epi_tile, sC)
|
| 1146 |
+
|
| 1147 |
+
#
|
| 1148 |
+
# Persistent tile scheduling loop
|
| 1149 |
+
#
|
| 1150 |
+
tile_sched = utils.StaticPersistentTileScheduler.create(
|
| 1151 |
+
tile_sched_params, bid, grid_dim
|
| 1152 |
+
)
|
| 1153 |
+
# grouped gemm tile scheduler helper will compute the group index for the tile we're working on
|
| 1154 |
+
group_gemm_ts_helper = utils.GroupedGemmTileSchedulerHelper(
|
| 1155 |
+
group_count,
|
| 1156 |
+
tile_sched_params,
|
| 1157 |
+
self.cluster_tile_shape_mnk,
|
| 1158 |
+
utils.create_initial_search_state(),
|
| 1159 |
+
)
|
| 1160 |
+
|
| 1161 |
+
work_tile = tile_sched.initial_work_tile_info()
|
| 1162 |
+
# wait tensormap initialization complete before update
|
| 1163 |
+
tensormap_manager.fence_tensormap_initialization()
|
| 1164 |
+
# tile count we have searched
|
| 1165 |
+
total_k_tile_cnt = cutlass.Int32(0)
|
| 1166 |
+
# group index of last tile
|
| 1167 |
+
last_group_idx = cutlass.Int32(-1)
|
| 1168 |
+
while work_tile.is_valid_tile:
|
| 1169 |
+
cur_tile_coord = work_tile.tile_idx
|
| 1170 |
+
grouped_gemm_cta_tile_info = group_gemm_ts_helper.delinearize_z(
|
| 1171 |
+
cur_tile_coord,
|
| 1172 |
+
problem_sizes_mnkl,
|
| 1173 |
+
)
|
| 1174 |
+
cur_group_idx = grouped_gemm_cta_tile_info.group_idx
|
| 1175 |
+
is_group_changed = cur_group_idx != last_group_idx
|
| 1176 |
+
if is_group_changed:
|
| 1177 |
+
# construct tensor C based on real address, shape and stride information
|
| 1178 |
+
real_tensor_c = self.make_tensor_for_tensormap_update(
|
| 1179 |
+
cur_group_idx,
|
| 1180 |
+
self.c_dtype,
|
| 1181 |
+
(
|
| 1182 |
+
grouped_gemm_cta_tile_info.problem_shape_m,
|
| 1183 |
+
grouped_gemm_cta_tile_info.problem_shape_n,
|
| 1184 |
+
grouped_gemm_cta_tile_info.problem_shape_k,
|
| 1185 |
+
),
|
| 1186 |
+
strides_abc,
|
| 1187 |
+
ptrs_abc,
|
| 1188 |
+
2, # 2 for tensor C
|
| 1189 |
+
)
|
| 1190 |
+
tensormap_manager.update_tensormap(
|
| 1191 |
+
((real_tensor_c),),
|
| 1192 |
+
((tma_atom_c),),
|
| 1193 |
+
((tensormap_c_ptr),),
|
| 1194 |
+
self.epilog_warp_id[0],
|
| 1195 |
+
(tensormap_c_smem_ptr,),
|
| 1196 |
+
)
|
| 1197 |
+
|
| 1198 |
+
mma_tile_coord_mnl = (
|
| 1199 |
+
grouped_gemm_cta_tile_info.cta_tile_idx_m
|
| 1200 |
+
// cute.size(tiled_mma.thr_id.shape),
|
| 1201 |
+
grouped_gemm_cta_tile_info.cta_tile_idx_n,
|
| 1202 |
+
0,
|
| 1203 |
+
)
|
| 1204 |
+
cur_k_tile_cnt = grouped_gemm_cta_tile_info.cta_tile_count_k
|
| 1205 |
+
total_k_tile_cnt += cur_k_tile_cnt
|
| 1206 |
+
|
| 1207 |
+
#
|
| 1208 |
+
# Slice to per mma tile index
|
| 1209 |
+
#
|
| 1210 |
+
# ((ATOM_V, REST_V), EPI_M, EPI_N)
|
| 1211 |
+
bSG_gC = bSG_gC_partitioned[
|
| 1212 |
+
(
|
| 1213 |
+
None,
|
| 1214 |
+
None,
|
| 1215 |
+
None,
|
| 1216 |
+
*mma_tile_coord_mnl,
|
| 1217 |
+
)
|
| 1218 |
+
]
|
| 1219 |
+
|
| 1220 |
+
# Set tensor memory buffer for current tile
|
| 1221 |
+
acc_buf_idx = tile_sched.num_tiles_executed % self.num_acc_stage
|
| 1222 |
+
# (T2R, T2R_M, T2R_N, EPI_M, EPI_M)
|
| 1223 |
+
tTR_tAcc = tTR_tAcc_base[(None, None, None, None, None, acc_buf_idx)]
|
| 1224 |
+
|
| 1225 |
+
#
|
| 1226 |
+
# Wait for accumulator buffer full
|
| 1227 |
+
#
|
| 1228 |
+
acc_full_phase = tile_sched.num_tiles_executed // self.num_acc_stage % 2
|
| 1229 |
+
cute.arch.mbarrier_wait(acc_full_mbar_ptr + acc_buf_idx, acc_full_phase)
|
| 1230 |
+
|
| 1231 |
+
tTR_tAcc = cute.group_modes(tTR_tAcc, 3, cute.rank(tTR_tAcc))
|
| 1232 |
+
bSG_gC = cute.group_modes(bSG_gC, 1, cute.rank(bSG_gC))
|
| 1233 |
+
# ensure the update to tensormap has completed before using it
|
| 1234 |
+
if is_group_changed:
|
| 1235 |
+
if warp_idx == self.epilog_warp_id[0]:
|
| 1236 |
+
tensormap_manager.fence_tensormap_update(tensormap_c_ptr)
|
| 1237 |
+
#
|
| 1238 |
+
# Store accumulator to global memory in subtiles
|
| 1239 |
+
#
|
| 1240 |
+
subtile_cnt = cute.size(tTR_tAcc.shape, mode=[3])
|
| 1241 |
+
num_prev_subtiles = tile_sched.num_tiles_executed * subtile_cnt
|
| 1242 |
+
for subtile_idx in range(subtile_cnt):
|
| 1243 |
+
#
|
| 1244 |
+
# Load accumulator from tensor memory buffer to register
|
| 1245 |
+
#
|
| 1246 |
+
tTR_tAcc_mn = tTR_tAcc[(None, None, None, subtile_idx)]
|
| 1247 |
+
cute.copy(tiled_copy_t2r, tTR_tAcc_mn, tTR_rAcc)
|
| 1248 |
+
|
| 1249 |
+
#
|
| 1250 |
+
# Convert to output type
|
| 1251 |
+
#
|
| 1252 |
+
acc_vec = tiled_copy_r2s.retile(tTR_rAcc).load()
|
| 1253 |
+
tRS_rC.store(acc_vec.to(self.c_dtype))
|
| 1254 |
+
#
|
| 1255 |
+
# Store C to shared memory
|
| 1256 |
+
#
|
| 1257 |
+
epi_buffer = (num_prev_subtiles + subtile_idx) % self.num_epi_stage
|
| 1258 |
+
cute.copy(
|
| 1259 |
+
tiled_copy_r2s,
|
| 1260 |
+
tRS_rC,
|
| 1261 |
+
tRS_sC[(None, None, None, epi_buffer)],
|
| 1262 |
+
)
|
| 1263 |
+
# Fence and barrier to make sure shared memory store is visible to TMA store
|
| 1264 |
+
cute.arch.fence_proxy(
|
| 1265 |
+
cute.arch.ProxyKind.async_shared,
|
| 1266 |
+
space=cute.arch.SharedSpace.shared_cta,
|
| 1267 |
+
)
|
| 1268 |
+
self.epilog_sync_barrier.arrive_and_wait()
|
| 1269 |
+
#
|
| 1270 |
+
# store C to global memory with TMA
|
| 1271 |
+
#
|
| 1272 |
+
if warp_idx == self.epilog_warp_id[0]:
|
| 1273 |
+
cute.copy(
|
| 1274 |
+
tma_atom_c,
|
| 1275 |
+
bSG_sC[(None, epi_buffer)],
|
| 1276 |
+
bSG_gC[(None, subtile_idx)],
|
| 1277 |
+
tma_desc_ptr=tensormap_manager.get_tensormap_ptr(
|
| 1278 |
+
tensormap_c_ptr,
|
| 1279 |
+
cute.AddressSpace.generic,
|
| 1280 |
+
),
|
| 1281 |
+
)
|
| 1282 |
+
cute.arch.cp_async_bulk_commit_group()
|
| 1283 |
+
cute.arch.cp_async_bulk_wait_group(
|
| 1284 |
+
self.num_epi_stage - 1, read=True
|
| 1285 |
+
)
|
| 1286 |
+
self.epilog_sync_barrier.arrive_and_wait()
|
| 1287 |
+
#
|
| 1288 |
+
# Async arrive accumulator buffer empty
|
| 1289 |
+
#
|
| 1290 |
+
with cute.arch.elect_one():
|
| 1291 |
+
cute.arch.mbarrier_arrive(
|
| 1292 |
+
acc_empty_mbar_ptr + acc_buf_idx,
|
| 1293 |
+
cta_rank_in_cluster // 2 * 2 if use_2cta_instrs else None,
|
| 1294 |
+
)
|
| 1295 |
+
|
| 1296 |
+
#
|
| 1297 |
+
# Advance to next tile
|
| 1298 |
+
#
|
| 1299 |
+
tile_sched.advance_to_next_work()
|
| 1300 |
+
work_tile = tile_sched.get_current_work()
|
| 1301 |
+
last_group_idx = cur_group_idx
|
| 1302 |
+
|
| 1303 |
+
#
|
| 1304 |
+
# Dealloc the tensor memory buffer
|
| 1305 |
+
#
|
| 1306 |
+
tmem.relinquish_alloc_permit()
|
| 1307 |
+
self.epilog_sync_barrier.arrive_and_wait()
|
| 1308 |
+
tmem.free(tmem_ptr)
|
| 1309 |
+
|
| 1310 |
+
#
|
| 1311 |
+
# Wait a/b buffer empty
|
| 1312 |
+
#
|
| 1313 |
+
if warp_idx == self.epilog_warp_id[0]:
|
| 1314 |
+
cute.arch.mbarrier_wait(
|
| 1315 |
+
(ab_empty_mbar_ptr + ((total_k_tile_cnt - 1) % self.num_ab_stage)),
|
| 1316 |
+
(((total_k_tile_cnt - 1) // self.num_ab_stage) % 2),
|
| 1317 |
+
)
|
| 1318 |
+
|
| 1319 |
+
@cute.jit
|
| 1320 |
+
def make_tensor_for_tensormap_update(
|
| 1321 |
+
self,
|
| 1322 |
+
group_idx: cutlass.Int32,
|
| 1323 |
+
dtype: Type[cutlass.Numeric],
|
| 1324 |
+
problem_shape_mnk: tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32],
|
| 1325 |
+
strides_abc: cute.Tensor,
|
| 1326 |
+
tensor_address_abc: cute.Tensor,
|
| 1327 |
+
tensor_index: int,
|
| 1328 |
+
):
|
| 1329 |
+
"""Extract stride and tensor address for a given group and construct a global tensor.
|
| 1330 |
+
|
| 1331 |
+
This function is used within the kernel to dynamically create a CUTE tensor
|
| 1332 |
+
representing A, B, or C for the current group being processed, using the
|
| 1333 |
+
group-specific address, shape, and stride information.
|
| 1334 |
+
|
| 1335 |
+
:param group_idx: The index of the current group within the grouped GEMM.
|
| 1336 |
+
:type group_idx: cutlass.Int32
|
| 1337 |
+
:param dtype: The data type of the tensor elements (e.g., cutlass.Float16).
|
| 1338 |
+
:type dtype: Type[cutlass.Numeric]
|
| 1339 |
+
:param problem_shape_mnk: The (M, N, K) problem shape for the current group.
|
| 1340 |
+
:type problem_shape_mnk: tuple[cutlass.Int32, cutlass.Int32, cutlass.Int32]
|
| 1341 |
+
:param strides_abc: Tensor containing strides for A, B, C for all groups. Layout: (group_count, 3, 2).
|
| 1342 |
+
:type strides_abc: cute.Tensor
|
| 1343 |
+
:param tensor_address_abc: Tensor containing global memory addresses for A, B, C for all groups. Layout: (group_count, 3).
|
| 1344 |
+
:type tensor_address_abc: cute.Tensor
|
| 1345 |
+
:param tensor_index: Specifies which tensor to create: 0 for A, 1 for B, 2 for C.
|
| 1346 |
+
:type tensor_index: int
|
| 1347 |
+
:return: A CUTE tensor representing the requested global memory tensor (A, B, or C) for the specified group.
|
| 1348 |
+
:rtype: cute.Tensor
|
| 1349 |
+
:raises TypeError: If the provided dtype is not a subclass of cutlass.Numeric.
|
| 1350 |
+
"""
|
| 1351 |
+
ptr_i64 = tensor_address_abc[(group_idx, tensor_index)]
|
| 1352 |
+
if cutlass.const_expr(
|
| 1353 |
+
not isclass(dtype) or not issubclass(dtype, cutlass.Numeric)
|
| 1354 |
+
):
|
| 1355 |
+
raise TypeError(
|
| 1356 |
+
f"dtype must be a type of cutlass.Numeric, got {type(dtype)}"
|
| 1357 |
+
)
|
| 1358 |
+
tensor_gmem_ptr = cute.make_ptr(
|
| 1359 |
+
dtype, ptr_i64, cute.AddressSpace.gmem, assumed_align=16
|
| 1360 |
+
)
|
| 1361 |
+
|
| 1362 |
+
strides_tensor_gmem = strides_abc[(group_idx, tensor_index, None)]
|
| 1363 |
+
strides_tensor_reg = cute.make_rmem_tensor(
|
| 1364 |
+
cute.make_layout(2),
|
| 1365 |
+
strides_abc.element_type,
|
| 1366 |
+
)
|
| 1367 |
+
cute.autovec_copy(strides_tensor_gmem, strides_tensor_reg)
|
| 1368 |
+
stride_mn = strides_tensor_reg[0]
|
| 1369 |
+
stride_k = strides_tensor_reg[1]
|
| 1370 |
+
c1 = cutlass.Int32(1)
|
| 1371 |
+
c0 = cutlass.Int32(0)
|
| 1372 |
+
|
| 1373 |
+
if cutlass.const_expr(tensor_index == 0): # tensor A
|
| 1374 |
+
m = problem_shape_mnk[0]
|
| 1375 |
+
k = problem_shape_mnk[2]
|
| 1376 |
+
return cute.make_tensor(
|
| 1377 |
+
tensor_gmem_ptr,
|
| 1378 |
+
cute.make_layout((m, k, c1), stride=(stride_mn, stride_k, c0)),
|
| 1379 |
+
)
|
| 1380 |
+
elif cutlass.const_expr(tensor_index == 1): # tensor B
|
| 1381 |
+
n = problem_shape_mnk[1]
|
| 1382 |
+
k = problem_shape_mnk[2]
|
| 1383 |
+
return cute.make_tensor(
|
| 1384 |
+
tensor_gmem_ptr,
|
| 1385 |
+
cute.make_layout((n, k, c1), stride=(stride_mn, stride_k, c0)),
|
| 1386 |
+
)
|
| 1387 |
+
else: # tensor C
|
| 1388 |
+
m = problem_shape_mnk[0]
|
| 1389 |
+
n = problem_shape_mnk[1]
|
| 1390 |
+
return cute.make_tensor(
|
| 1391 |
+
tensor_gmem_ptr,
|
| 1392 |
+
cute.make_layout((m, n, c1), stride=(stride_mn, stride_k, c0)),
|
| 1393 |
+
)
|
| 1394 |
+
|
| 1395 |
+
def epilog_tmem_copy_and_partition(
|
| 1396 |
+
self,
|
| 1397 |
+
tidx: cutlass.Int32,
|
| 1398 |
+
tAcc: cute.Tensor,
|
| 1399 |
+
gC_mnl: cute.Tensor,
|
| 1400 |
+
epi_tile: cute.Tile,
|
| 1401 |
+
use_2cta_instrs: Union[cutlass.Boolean, bool],
|
| 1402 |
+
) -> tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]:
|
| 1403 |
+
"""
|
| 1404 |
+
Make tiledCopy for tensor memory load, then use it to partition tensor memory (source) and register array (destination).
|
| 1405 |
+
|
| 1406 |
+
:param tidx: The thread index in epilogue warp groups
|
| 1407 |
+
:type tidx: cutlass.Int32
|
| 1408 |
+
:param tAcc: The accumulator tensor to be copied and partitioned
|
| 1409 |
+
:type tAcc: cute.Tensor
|
| 1410 |
+
:param gC_mnl: The global tensor C
|
| 1411 |
+
:type gC_mnl: cute.Tensor
|
| 1412 |
+
:param epi_tile: The epilogue tiler
|
| 1413 |
+
:type epi_tile: cute.Tile
|
| 1414 |
+
:param use_2cta_instrs: Whether use_2cta_instrs is enabled
|
| 1415 |
+
:type use_2cta_instrs: bool
|
| 1416 |
+
|
| 1417 |
+
:return: A tuple containing (tiled_copy_t2r, tTR_tAcc, tTR_rAcc) where:
|
| 1418 |
+
- tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r)
|
| 1419 |
+
- tTR_tAcc: The partitioned accumulator tensor
|
| 1420 |
+
- tTR_rAcc: The accumulated tensor in register used to hold t2r results
|
| 1421 |
+
:rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]
|
| 1422 |
+
"""
|
| 1423 |
+
# Make tiledCopy for tensor memory load(t2r)
|
| 1424 |
+
copy_atom_t2r = sm100_utils.get_tmem_load_op(
|
| 1425 |
+
self.cta_tile_shape_mnk,
|
| 1426 |
+
self.c_layout,
|
| 1427 |
+
self.c_dtype,
|
| 1428 |
+
self.acc_dtype,
|
| 1429 |
+
epi_tile,
|
| 1430 |
+
use_2cta_instrs,
|
| 1431 |
+
)
|
| 1432 |
+
# (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, STAGE)
|
| 1433 |
+
tAcc_epi = cute.flat_divide(
|
| 1434 |
+
tAcc[((None, None), 0, 0, None)],
|
| 1435 |
+
epi_tile,
|
| 1436 |
+
)
|
| 1437 |
+
# (EPI_TILE_M, EPI_TILE_N)
|
| 1438 |
+
tiled_copy_t2r = tcgen05.make_tmem_copy(
|
| 1439 |
+
copy_atom_t2r, tAcc_epi[(None, None, 0, 0, 0)]
|
| 1440 |
+
)
|
| 1441 |
+
|
| 1442 |
+
thr_copy_t2r = tiled_copy_t2r.get_slice(tidx)
|
| 1443 |
+
# (T2R, T2R_M, T2R_N, EPI_M, EPI_M, STAGE)
|
| 1444 |
+
tTR_tAcc = thr_copy_t2r.partition_S(tAcc_epi)
|
| 1445 |
+
|
| 1446 |
+
# (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, RestM, RestN, RestL)
|
| 1447 |
+
gC_mnl_epi = cute.flat_divide(
|
| 1448 |
+
gC_mnl[((None, None), 0, 0, None, None, None)], epi_tile
|
| 1449 |
+
)
|
| 1450 |
+
# (T2R, T2R_M, T2R_N, EPI_M, EPI_N, RestM, RestN, RestL)
|
| 1451 |
+
tTR_gC = thr_copy_t2r.partition_D(gC_mnl_epi)
|
| 1452 |
+
# (T2R, T2R_M, T2R_N)
|
| 1453 |
+
tTR_rAcc = cute.make_rmem_tensor(
|
| 1454 |
+
tTR_gC[(None, None, None, 0, 0, 0, 0, 0)].shape, self.acc_dtype
|
| 1455 |
+
)
|
| 1456 |
+
return tiled_copy_t2r, tTR_tAcc, tTR_rAcc
|
| 1457 |
+
|
| 1458 |
+
def epilog_smem_copy_and_partition(
|
| 1459 |
+
self,
|
| 1460 |
+
tiled_copy_t2r: cute.TiledCopy,
|
| 1461 |
+
tTR_rC: cute.Tensor,
|
| 1462 |
+
tidx: cutlass.Int32,
|
| 1463 |
+
sC: cute.Tensor,
|
| 1464 |
+
) -> tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]:
|
| 1465 |
+
"""
|
| 1466 |
+
Make tiledCopy for shared memory store, then use it to partition register array (source) and shared memory (destination).
|
| 1467 |
+
|
| 1468 |
+
:param tiled_copy_t2r: The tiled copy operation for tmem to register copy(t2r)
|
| 1469 |
+
:type tiled_copy_t2r: cute.TiledCopy
|
| 1470 |
+
:param tTR_rC: The partitioned accumulator tensor
|
| 1471 |
+
:type tTR_rC: cute.Tensor
|
| 1472 |
+
:param tidx: The thread index in epilogue warp groups
|
| 1473 |
+
:type tidx: cutlass.Int32
|
| 1474 |
+
:param sC: The shared memory tensor to be copied and partitioned
|
| 1475 |
+
:type sC: cute.Tensor
|
| 1476 |
+
|
| 1477 |
+
:return: A tuple containing (tiled_copy_r2s, tRS_rC, tRS_sC) where:
|
| 1478 |
+
- tiled_copy_r2s: The tiled copy operation for register to smem copy(r2s)
|
| 1479 |
+
- tRS_rC: The partitioned tensor C (register source)
|
| 1480 |
+
- tRS_sC: The partitioned tensor C (smem destination)
|
| 1481 |
+
:rtype: Tuple[cute.TiledCopy, cute.Tensor, cute.Tensor]
|
| 1482 |
+
"""
|
| 1483 |
+
copy_atom_r2s = sm100_utils.get_smem_store_op(
|
| 1484 |
+
self.c_layout, self.c_dtype, self.acc_dtype, tiled_copy_t2r
|
| 1485 |
+
)
|
| 1486 |
+
tiled_copy_r2s = cute.make_tiled_copy_D(copy_atom_r2s, tiled_copy_t2r)
|
| 1487 |
+
# (R2S, R2S_M, R2S_N, PIPE_D)
|
| 1488 |
+
thr_copy_r2s = tiled_copy_r2s.get_slice(tidx)
|
| 1489 |
+
tRS_sC = thr_copy_r2s.partition_D(sC)
|
| 1490 |
+
# (R2S, R2S_M, R2S_N)
|
| 1491 |
+
tRS_rC = tiled_copy_r2s.retile(tTR_rC)
|
| 1492 |
+
return tiled_copy_r2s, tRS_rC, tRS_sC
|
| 1493 |
+
|
| 1494 |
+
def epilog_gmem_copy_and_partition(
|
| 1495 |
+
self,
|
| 1496 |
+
tma_atom_c: cute.CopyAtom,
|
| 1497 |
+
gC_mnl: cute.Tensor,
|
| 1498 |
+
epi_tile: cute.Tile,
|
| 1499 |
+
sC: cute.Tensor,
|
| 1500 |
+
) -> tuple[cute.CopyAtom, cute.Tensor, cute.Tensor]:
|
| 1501 |
+
"""Make tiledCopy for global memory store, then use it to partition
|
| 1502 |
+
shared memory (source) and global memory (destination) for TMA store version.
|
| 1503 |
+
|
| 1504 |
+
:param tma_atom_c: The TMA copy atom configured for storing tensor C.
|
| 1505 |
+
:type tma_atom_c: cute.CopyAtom
|
| 1506 |
+
:param gC_mnl: The global memory tensor C.
|
| 1507 |
+
:type gC_mnl: cute.Tensor
|
| 1508 |
+
:param epi_tile: The epilogue tiler defining the granularity of the operation.
|
| 1509 |
+
:type epi_tile: cute.Tile
|
| 1510 |
+
:param sC: The shared memory epilogue buffer tensor.
|
| 1511 |
+
:type sC: cute.Tensor
|
| 1512 |
+
:return: A tuple containing:
|
| 1513 |
+
- tma_atom_c: The input TMA copy atom (passed through).
|
| 1514 |
+
- bSG_sC: The source shared memory tensor partitioned for the TMA operation.
|
| 1515 |
+
- tCgC: The destination global memory tensor partitioned for the TMA operation.
|
| 1516 |
+
:rtype: tuple[cute.CopyAtom, cute.Tensor, cute.Tensor]
|
| 1517 |
+
"""
|
| 1518 |
+
# (EPI_TILE_M, EPI_TILE_N, EPI_M, EPI_N, RestM, RestN, RestL)
|
| 1519 |
+
gC_epi = cute.flat_divide(
|
| 1520 |
+
gC_mnl[((None, None), 0, 0, None, None, None)], epi_tile
|
| 1521 |
+
)
|
| 1522 |
+
sC_for_tma_partition = cute.group_modes(sC, 0, 2)
|
| 1523 |
+
gC_for_tma_partition = cute.group_modes(gC_epi, 0, 2)
|
| 1524 |
+
# ((ATOM_V, REST_V), EPI_M, EPI_N)
|
| 1525 |
+
# ((ATOM_V, REST_V), EPI_M, EPI_N, RestM, RestN, RestL)
|
| 1526 |
+
bSG_sC, bSG_gC = cpasync.tma_partition(
|
| 1527 |
+
tma_atom_c,
|
| 1528 |
+
0,
|
| 1529 |
+
cute.make_layout(1),
|
| 1530 |
+
sC_for_tma_partition,
|
| 1531 |
+
gC_for_tma_partition,
|
| 1532 |
+
)
|
| 1533 |
+
return tma_atom_c, bSG_sC, bSG_gC
|
| 1534 |
+
|
| 1535 |
+
@staticmethod
|
| 1536 |
+
def _compute_stages(
|
| 1537 |
+
tiled_mma: cute.TiledMma,
|
| 1538 |
+
mma_tiler_mnk: tuple[int, int, int],
|
| 1539 |
+
a_dtype: type[cutlass.Numeric],
|
| 1540 |
+
b_dtype: type[cutlass.Numeric],
|
| 1541 |
+
epi_tile: cute.Tile,
|
| 1542 |
+
c_dtype: type[cutlass.Numeric],
|
| 1543 |
+
c_layout: utils.LayoutEnum,
|
| 1544 |
+
smem_capacity: int,
|
| 1545 |
+
occupancy: int,
|
| 1546 |
+
) -> tuple[int, int, int]:
|
| 1547 |
+
"""Computes the number of stages for accumulator, A/B operands, and epilogue based on heuristics.
|
| 1548 |
+
|
| 1549 |
+
:param tiled_mma: The tiled MMA object defining the core computation.
|
| 1550 |
+
:type tiled_mma: cute.TiledMma
|
| 1551 |
+
:param mma_tiler_mnk: The shape (M, N, K) of the MMA tiler.
|
| 1552 |
+
:type mma_tiler_mnk: tuple[int, int, int]
|
| 1553 |
+
:param a_dtype: Data type of operand A.
|
| 1554 |
+
:type a_dtype: type[cutlass.Numeric]
|
| 1555 |
+
:param b_dtype: Data type of operand B.
|
| 1556 |
+
:type b_dtype: type[cutlass.Numeric]
|
| 1557 |
+
:param epi_tile: The epilogue tile shape.
|
| 1558 |
+
:type epi_tile: cute.Tile
|
| 1559 |
+
:param c_dtype: Data type of operand C (output).
|
| 1560 |
+
:type c_dtype: type[cutlass.Numeric]
|
| 1561 |
+
:param c_layout: Layout enum of operand C in global memory.
|
| 1562 |
+
:type c_layout: utils.LayoutEnum
|
| 1563 |
+
:param smem_capacity: Total available shared memory capacity in bytes.
|
| 1564 |
+
:type smem_capacity: int
|
| 1565 |
+
:param occupancy: Target number of CTAs per SM (occupancy).
|
| 1566 |
+
:type occupancy: int
|
| 1567 |
+
|
| 1568 |
+
:return: A tuple containing the computed number of stages for:
|
| 1569 |
+
(accumulator stages, A/B operand stages, epilogue stages)
|
| 1570 |
+
:rtype: tuple[int, int, int]
|
| 1571 |
+
"""
|
| 1572 |
+
# Default accumulator and epilogue stages
|
| 1573 |
+
num_acc_stage = 2
|
| 1574 |
+
num_epi_stage = 2
|
| 1575 |
+
|
| 1576 |
+
# Calculate smem layout and size for one stage of A, B, and Epilogue
|
| 1577 |
+
a_smem_layout_stage_one = sm100_utils.make_smem_layout_a(
|
| 1578 |
+
tiled_mma,
|
| 1579 |
+
mma_tiler_mnk,
|
| 1580 |
+
a_dtype,
|
| 1581 |
+
1, # stage=1
|
| 1582 |
+
)
|
| 1583 |
+
b_smem_layout_staged_one = sm100_utils.make_smem_layout_b(
|
| 1584 |
+
tiled_mma,
|
| 1585 |
+
mma_tiler_mnk,
|
| 1586 |
+
b_dtype,
|
| 1587 |
+
1, # stage=1
|
| 1588 |
+
)
|
| 1589 |
+
epi_smem_layout_staged_one = sm100_utils.make_smem_layout_epi(
|
| 1590 |
+
c_dtype,
|
| 1591 |
+
c_layout,
|
| 1592 |
+
epi_tile,
|
| 1593 |
+
1, # stage=1
|
| 1594 |
+
)
|
| 1595 |
+
ab_bytes_per_stage = cute.size_in_bytes(
|
| 1596 |
+
a_dtype, a_smem_layout_stage_one
|
| 1597 |
+
) + cute.size_in_bytes(b_dtype, b_smem_layout_staged_one)
|
| 1598 |
+
|
| 1599 |
+
epi_bytes_per_stage = cute.size_in_bytes(c_dtype, epi_smem_layout_staged_one)
|
| 1600 |
+
epi_bytes = epi_bytes_per_stage * num_epi_stage
|
| 1601 |
+
|
| 1602 |
+
# Calculate A/B stages:
|
| 1603 |
+
# Start with total smem per CTA (capacity / occupancy)
|
| 1604 |
+
# Subtract reserved bytes and initial epilogue bytes
|
| 1605 |
+
# Divide remaining by bytes needed per A/B stage
|
| 1606 |
+
num_ab_stage = (
|
| 1607 |
+
smem_capacity // occupancy
|
| 1608 |
+
- GroupedGemmKernel.reserved_smem_bytes
|
| 1609 |
+
- epi_bytes
|
| 1610 |
+
) // ab_bytes_per_stage
|
| 1611 |
+
|
| 1612 |
+
# Refine epilogue stages:
|
| 1613 |
+
# Calculate remaining smem after allocating for A/B stages and reserved bytes
|
| 1614 |
+
# Add remaining unused smem to epilogue
|
| 1615 |
+
remaining_smem = (
|
| 1616 |
+
smem_capacity
|
| 1617 |
+
- occupancy * ab_bytes_per_stage * num_ab_stage
|
| 1618 |
+
- occupancy * (GroupedGemmKernel.reserved_smem_bytes + epi_bytes)
|
| 1619 |
+
)
|
| 1620 |
+
num_epi_stage += remaining_smem // (occupancy * epi_bytes_per_stage)
|
| 1621 |
+
return num_acc_stage, num_ab_stage, num_epi_stage
|
| 1622 |
+
|
| 1623 |
+
@staticmethod
|
| 1624 |
+
def _compute_grid(
|
| 1625 |
+
total_num_clusters: int,
|
| 1626 |
+
cluster_shape_mn: tuple[int, int],
|
| 1627 |
+
max_active_clusters: cutlass.Constexpr[int],
|
| 1628 |
+
) -> tuple[utils.PersistentTileSchedulerParams, tuple[int, int, int]]:
|
| 1629 |
+
"""Compute tile scheduler parameters and grid shape for grouped GEMM operations.
|
| 1630 |
+
|
| 1631 |
+
:param total_num_clusters: Total number of clusters to process across all groups.
|
| 1632 |
+
:type total_num_clusters: int
|
| 1633 |
+
:param cluster_shape_mn: Shape of each cluster in M, N dimensions.
|
| 1634 |
+
:type cluster_shape_mn: tuple[int, int]
|
| 1635 |
+
:param max_active_clusters: Maximum number of active clusters.
|
| 1636 |
+
:type max_active_clusters: cutlass.Constexpr[int]
|
| 1637 |
+
|
| 1638 |
+
:return: A tuple containing:
|
| 1639 |
+
- tile_sched_params: Parameters for the persistent tile scheduler.
|
| 1640 |
+
- grid: Grid shape for kernel launch.
|
| 1641 |
+
:rtype: tuple[utils.PersistentTileSchedulerParams, tuple[int, ...]]
|
| 1642 |
+
"""
|
| 1643 |
+
# Create problem shape with M, N dimensions from cluster shape
|
| 1644 |
+
# and L dimension representing the total number of clusters.
|
| 1645 |
+
problem_shape_ntile_mnl = (
|
| 1646 |
+
cluster_shape_mn[0],
|
| 1647 |
+
cluster_shape_mn[1],
|
| 1648 |
+
cutlass.Int32(total_num_clusters),
|
| 1649 |
+
)
|
| 1650 |
+
|
| 1651 |
+
tile_sched_params = utils.PersistentTileSchedulerParams(
|
| 1652 |
+
problem_shape_ntile_mnl, (*cluster_shape_mn, 1)
|
| 1653 |
+
)
|
| 1654 |
+
|
| 1655 |
+
grid = utils.StaticPersistentTileScheduler.get_grid_shape(
|
| 1656 |
+
tile_sched_params, max_active_clusters
|
| 1657 |
+
)
|
| 1658 |
+
|
| 1659 |
+
return tile_sched_params, grid
|
| 1660 |
+
|
| 1661 |
+
@staticmethod
|
| 1662 |
+
def _get_mbar_smem_bytes(**kwargs_stages: int) -> int:
|
| 1663 |
+
"""Calculate shared memory consumption for memory barriers based on provided stages.
|
| 1664 |
+
|
| 1665 |
+
Each stage requires 2 barriers, and each barrier consumes 8 bytes of shared memory.
|
| 1666 |
+
The total consumption is the sum across all provided stages. This function calculates the total
|
| 1667 |
+
shared memory needed for these barriers.
|
| 1668 |
+
|
| 1669 |
+
:param kwargs_stages: Variable keyword arguments where each key is a stage name
|
| 1670 |
+
(e.g., num_acc_stage, num_ab_stage) and each value is the
|
| 1671 |
+
number of stages of that type.
|
| 1672 |
+
:type kwargs_stages: int
|
| 1673 |
+
:return: Total shared memory bytes required for all memory barriers.
|
| 1674 |
+
:rtype: int
|
| 1675 |
+
"""
|
| 1676 |
+
num_barriers_per_stage = 2
|
| 1677 |
+
num_bytes_per_barrier = 8
|
| 1678 |
+
mbar_smem_consumption = sum(
|
| 1679 |
+
[
|
| 1680 |
+
num_barriers_per_stage * num_bytes_per_barrier * stage
|
| 1681 |
+
for stage in kwargs_stages.values()
|
| 1682 |
+
]
|
| 1683 |
+
)
|
| 1684 |
+
return mbar_smem_consumption
|
| 1685 |
+
|
| 1686 |
+
@staticmethod
|
| 1687 |
+
def _get_tensormap_smem_bytes(
|
| 1688 |
+
tensormap_update_mode: utils.TensorMapUpdateMode,
|
| 1689 |
+
) -> int:
|
| 1690 |
+
"""Get the SMEM consumption for the tensormap buffer based on the update mode.
|
| 1691 |
+
|
| 1692 |
+
:param tensormap_update_mode: Specifies whether tensormaps are updated in GMEM or SMEM.
|
| 1693 |
+
:type tensormap_update_mode: utils.TensorMapUpdateMode
|
| 1694 |
+
:return: The shared memory bytes required for the tensormap buffer. Returns 0 if mode is GMEM.
|
| 1695 |
+
:rtype: int
|
| 1696 |
+
:raises ValueError: If an invalid tensormap update mode is provided.
|
| 1697 |
+
"""
|
| 1698 |
+
if tensormap_update_mode == utils.TensorMapUpdateMode.GMEM:
|
| 1699 |
+
return 0
|
| 1700 |
+
elif tensormap_update_mode == utils.TensorMapUpdateMode.SMEM:
|
| 1701 |
+
return (
|
| 1702 |
+
GroupedGemmKernel.bytes_per_tensormap * GroupedGemmKernel.num_tensormaps
|
| 1703 |
+
)
|
| 1704 |
+
else:
|
| 1705 |
+
raise ValueError(f"Invalid tensormap update mode: {tensormap_update_mode}")
|
| 1706 |
+
|
| 1707 |
+
@staticmethod
|
| 1708 |
+
def _compute_num_tmem_alloc_cols(
|
| 1709 |
+
tiled_mma: cute.TiledMma,
|
| 1710 |
+
mma_tiler: tuple[int, int, int],
|
| 1711 |
+
num_acc_stage: int,
|
| 1712 |
+
) -> int:
|
| 1713 |
+
"""
|
| 1714 |
+
Compute the number of tensor memory allocation columns.
|
| 1715 |
+
|
| 1716 |
+
:param tiled_mma: The tiled MMA object defining the core computation.
|
| 1717 |
+
:type tiled_mma: cute.TiledMma
|
| 1718 |
+
:param mma_tiler: The shape (M, N, K) of the MMA tile.
|
| 1719 |
+
:type mma_tiler: tuple[int, int, int]
|
| 1720 |
+
:param acc_stage: The stage of the accumulator tensor.
|
| 1721 |
+
:type acc_stage: int
|
| 1722 |
+
|
| 1723 |
+
:return: The number of tensor memory allocation columns.
|
| 1724 |
+
:rtype: int
|
| 1725 |
+
"""
|
| 1726 |
+
acc_shape = tiled_mma.partition_shape_C(mma_tiler[:2])
|
| 1727 |
+
tCtAcc_fake = tiled_mma.make_fragment_C(cute.append(acc_shape, num_acc_stage))
|
| 1728 |
+
num_tmem_alloc_cols = utils.get_num_tmem_alloc_cols(tCtAcc_fake)
|
| 1729 |
+
|
| 1730 |
+
return num_tmem_alloc_cols
|
| 1731 |
+
|
| 1732 |
+
# Size of smem we reserved for mbarrier, tensor memory management and tensormap update
|
| 1733 |
+
reserved_smem_bytes = 1024
|
| 1734 |
+
bytes_per_tensormap = 128
|
| 1735 |
+
num_tensormaps = 3
|
| 1736 |
+
# size of smem used for tensor memory management
|
| 1737 |
+
tensor_memory_management_bytes = 12
|
| 1738 |
+
|
| 1739 |
+
|
| 1740 |
+
# Create tensor and return the pointer, tensor, and stride
|
| 1741 |
+
def create_tensor_and_stride(
|
| 1742 |
+
l: int,
|
| 1743 |
+
mode0: int,
|
| 1744 |
+
mode1: int,
|
| 1745 |
+
is_mode0_major: bool,
|
| 1746 |
+
dtype: type[cutlass.Numeric],
|
| 1747 |
+
is_dynamic_layout: bool = True,
|
| 1748 |
+
torch_tensor_cpu: torch.Tensor = None,
|
| 1749 |
+
) -> tuple[int, torch.Tensor, cute.Tensor, torch.Tensor, tuple[int, int]]:
|
| 1750 |
+
"""Create GPU tensor from either a new or existing CPU tensor.
|
| 1751 |
+
|
| 1752 |
+
:param torch_tensor_cpu: Optional existing CPU tensor to reuse. If None, creates a new one.
|
| 1753 |
+
:type torch_tensor_cpu: torch.Tensor, optional
|
| 1754 |
+
"""
|
| 1755 |
+
if torch_tensor_cpu is None:
|
| 1756 |
+
# Create new CPU tensor
|
| 1757 |
+
torch_tensor_cpu = cutlass_torch.matrix(l, mode0, mode1, is_mode0_major, dtype)
|
| 1758 |
+
|
| 1759 |
+
# Create GPU tensor from CPU tensor (new or existing)
|
| 1760 |
+
cute_tensor, torch_tensor = cutlass_torch.cute_tensor_like(
|
| 1761 |
+
torch_tensor_cpu, dtype, is_dynamic_layout, assumed_align=16
|
| 1762 |
+
)
|
| 1763 |
+
return (
|
| 1764 |
+
torch_tensor.data_ptr(),
|
| 1765 |
+
torch_tensor,
|
| 1766 |
+
cute_tensor,
|
| 1767 |
+
torch_tensor_cpu,
|
| 1768 |
+
torch_tensor.stride()[:-1],
|
| 1769 |
+
)
|
| 1770 |
+
|
| 1771 |
+
|
| 1772 |
+
def create_tensors_for_all_groups(
|
| 1773 |
+
problem_sizes_mnkl: List[tuple[int, int, int, int]],
|
| 1774 |
+
ab_dtype: Type[cutlass.Numeric],
|
| 1775 |
+
c_dtype: Type[cutlass.Numeric],
|
| 1776 |
+
a_major: str,
|
| 1777 |
+
b_major: str,
|
| 1778 |
+
c_major: str,
|
| 1779 |
+
torch_fp32_tensors_abc: List[List[torch.Tensor]] = None,
|
| 1780 |
+
) -> tuple[
|
| 1781 |
+
List[List[int]],
|
| 1782 |
+
List[List[torch.Tensor]],
|
| 1783 |
+
List[tuple],
|
| 1784 |
+
List[List[tuple]],
|
| 1785 |
+
List[List[torch.Tensor]],
|
| 1786 |
+
]:
|
| 1787 |
+
if torch_fp32_tensors_abc is not None and len(torch_fp32_tensors_abc) != len(
|
| 1788 |
+
problem_sizes_mnkl
|
| 1789 |
+
):
|
| 1790 |
+
raise ValueError("torch_fp32_tensors_abc must have one entry per group")
|
| 1791 |
+
|
| 1792 |
+
# Initialize lists to store tensors for all groups
|
| 1793 |
+
new_torch_fp32_tensors_abc = (
|
| 1794 |
+
[] if torch_fp32_tensors_abc is None else torch_fp32_tensors_abc
|
| 1795 |
+
)
|
| 1796 |
+
torch_tensors_abc = []
|
| 1797 |
+
cute_tensors_abc = []
|
| 1798 |
+
strides_abc = []
|
| 1799 |
+
ptrs_abc = []
|
| 1800 |
+
|
| 1801 |
+
# Iterate through all groups and create tensors for each group
|
| 1802 |
+
for group_idx, (m, n, k, l) in enumerate(problem_sizes_mnkl):
|
| 1803 |
+
# Get existing CPU tensors if available, otherwise None
|
| 1804 |
+
existing_cpu_a = (
|
| 1805 |
+
torch_fp32_tensors_abc[group_idx][0] if torch_fp32_tensors_abc else None
|
| 1806 |
+
)
|
| 1807 |
+
existing_cpu_b = (
|
| 1808 |
+
torch_fp32_tensors_abc[group_idx][1] if torch_fp32_tensors_abc else None
|
| 1809 |
+
)
|
| 1810 |
+
existing_cpu_c = (
|
| 1811 |
+
torch_fp32_tensors_abc[group_idx][2] if torch_fp32_tensors_abc else None
|
| 1812 |
+
)
|
| 1813 |
+
|
| 1814 |
+
# Create tensors (reusing CPU tensors if provided)
|
| 1815 |
+
(
|
| 1816 |
+
ptr_a,
|
| 1817 |
+
torch_tensor_a,
|
| 1818 |
+
cute_tensor_a,
|
| 1819 |
+
tensor_fp32_a,
|
| 1820 |
+
stride_mk_a,
|
| 1821 |
+
) = create_tensor_and_stride(
|
| 1822 |
+
l, m, k, a_major == "m", ab_dtype, torch_tensor_cpu=existing_cpu_a
|
| 1823 |
+
)
|
| 1824 |
+
(
|
| 1825 |
+
ptr_b,
|
| 1826 |
+
torch_tensor_b,
|
| 1827 |
+
cute_tensor_b,
|
| 1828 |
+
tensor_fp32_b,
|
| 1829 |
+
stride_nk_b,
|
| 1830 |
+
) = create_tensor_and_stride(
|
| 1831 |
+
l, n, k, b_major == "n", ab_dtype, torch_tensor_cpu=existing_cpu_b
|
| 1832 |
+
)
|
| 1833 |
+
(
|
| 1834 |
+
ptr_c,
|
| 1835 |
+
torch_tensor_c,
|
| 1836 |
+
cute_tensor_c,
|
| 1837 |
+
tensor_fp32_c,
|
| 1838 |
+
stride_mn_c,
|
| 1839 |
+
) = create_tensor_and_stride(
|
| 1840 |
+
l, m, n, c_major == "m", c_dtype, torch_tensor_cpu=existing_cpu_c
|
| 1841 |
+
)
|
| 1842 |
+
|
| 1843 |
+
# Only append to new_torch_fp32_tensors_abc if we created new CPU tensors
|
| 1844 |
+
if torch_fp32_tensors_abc is None:
|
| 1845 |
+
new_torch_fp32_tensors_abc.append(
|
| 1846 |
+
[tensor_fp32_a, tensor_fp32_b, tensor_fp32_c]
|
| 1847 |
+
)
|
| 1848 |
+
|
| 1849 |
+
ptrs_abc.append([ptr_a, ptr_b, ptr_c])
|
| 1850 |
+
torch_tensors_abc.append([torch_tensor_a, torch_tensor_b, torch_tensor_c])
|
| 1851 |
+
strides_abc.append([stride_mk_a, stride_nk_b, stride_mn_c])
|
| 1852 |
+
cute_tensors_abc.append(
|
| 1853 |
+
(
|
| 1854 |
+
cute_tensor_a,
|
| 1855 |
+
cute_tensor_b,
|
| 1856 |
+
cute_tensor_c,
|
| 1857 |
+
)
|
| 1858 |
+
)
|
| 1859 |
+
|
| 1860 |
+
return (
|
| 1861 |
+
ptrs_abc,
|
| 1862 |
+
torch_tensors_abc,
|
| 1863 |
+
cute_tensors_abc,
|
| 1864 |
+
strides_abc,
|
| 1865 |
+
new_torch_fp32_tensors_abc,
|
| 1866 |
+
)
|
| 1867 |
+
|
| 1868 |
+
|
| 1869 |
+
def run(
|
| 1870 |
+
num_groups: int,
|
| 1871 |
+
problem_sizes_mnkl: tuple[int, int, int, int],
|
| 1872 |
+
ab_dtype: Type[cutlass.Numeric],
|
| 1873 |
+
c_dtype: Type[cutlass.Numeric],
|
| 1874 |
+
acc_dtype: Type[cutlass.Numeric],
|
| 1875 |
+
a_major: str,
|
| 1876 |
+
b_major: str,
|
| 1877 |
+
c_major: str,
|
| 1878 |
+
mma_tiler_mn: tuple[int, int],
|
| 1879 |
+
cluster_shape_mn: tuple[int, int],
|
| 1880 |
+
use_2cta_instrs: bool,
|
| 1881 |
+
tensormap_update_mode: utils.TensorMapUpdateMode,
|
| 1882 |
+
tolerance: float,
|
| 1883 |
+
warmup_iterations: int,
|
| 1884 |
+
iterations: int,
|
| 1885 |
+
skip_ref_check: bool,
|
| 1886 |
+
use_cold_l2: bool = False,
|
| 1887 |
+
**kwargs,
|
| 1888 |
+
):
|
| 1889 |
+
"""Run grouped GEMM example with specified configurations.
|
| 1890 |
+
|
| 1891 |
+
:param use_cold_l2: Whether to use circular buffer strategy to ensure cold L2 cache, defaults to False
|
| 1892 |
+
:type use_cold_l2: bool, optional
|
| 1893 |
+
:return: Execution time of the GEMM kernel in microseconds
|
| 1894 |
+
:rtype: float
|
| 1895 |
+
"""
|
| 1896 |
+
print("Running Blackwell Grouped GEMM test with:")
|
| 1897 |
+
print(f"{num_groups} groups")
|
| 1898 |
+
for i, (m, n, k, l) in enumerate(problem_sizes_mnkl):
|
| 1899 |
+
print(f"Group {i}: {m}x{n}x{k}x{l}")
|
| 1900 |
+
print(f"AB dtype: {ab_dtype}, C dtype: {c_dtype}, Acc dtype: {acc_dtype}")
|
| 1901 |
+
print(f"Matrix majors - A: {a_major}, B: {b_major}, C: {c_major}")
|
| 1902 |
+
print(f"Mma Tiler (M, N): {mma_tiler_mn}, Cluster Shape (M, N): {cluster_shape_mn}")
|
| 1903 |
+
print(f"2CTA MMA instructions: {'True' if use_2cta_instrs else 'False'}")
|
| 1904 |
+
print(f"Tensor map update mode: {tensormap_update_mode}")
|
| 1905 |
+
print(f"Tolerance: {tolerance}")
|
| 1906 |
+
print(f"Warmup iterations: {warmup_iterations}")
|
| 1907 |
+
print(f"Iterations: {iterations}")
|
| 1908 |
+
print(f"Skip reference checking: {skip_ref_check}")
|
| 1909 |
+
print(f"Use cold L2: {'True' if use_cold_l2 else 'False'}")
|
| 1910 |
+
|
| 1911 |
+
# Skip unsupported types
|
| 1912 |
+
if ab_dtype not in {
|
| 1913 |
+
cutlass.Float16,
|
| 1914 |
+
cutlass.BFloat16,
|
| 1915 |
+
}:
|
| 1916 |
+
raise ValueError(f"Skip unsupported ab_dtype {ab_dtype}")
|
| 1917 |
+
if c_dtype not in {cutlass.Float16, cutlass.BFloat16, cutlass.Float32}:
|
| 1918 |
+
raise ValueError(f"Skip unsupported c_dtype {c_dtype}")
|
| 1919 |
+
# Skip unsupported acc dtype
|
| 1920 |
+
if acc_dtype not in {cutlass.Float32, cutlass.Float16}:
|
| 1921 |
+
raise ValueError(f"Skip unsupported acc_dtype {acc_dtype}")
|
| 1922 |
+
# Skip invalid ab_dtype and acc_dtype combination
|
| 1923 |
+
if ab_dtype == cutlass.BFloat16 and acc_dtype == cutlass.Float16:
|
| 1924 |
+
raise ValueError("Skip invalid ab_dtype and acc_dtype combination")
|
| 1925 |
+
# Skip invalid mma tile shape
|
| 1926 |
+
if not (
|
| 1927 |
+
(not use_2cta_instrs and mma_tiler_mn[0] in [64, 128])
|
| 1928 |
+
or (use_2cta_instrs and mma_tiler_mn[0] in [128, 256])
|
| 1929 |
+
):
|
| 1930 |
+
raise ValueError(f"Skip invalid mma tiler M {mma_tiler_mn[0]}")
|
| 1931 |
+
if mma_tiler_mn[1] not in range(32, 257, 32):
|
| 1932 |
+
raise ValueError(f"Skip invalid mma tiler N {mma_tiler_mn[1]}")
|
| 1933 |
+
# Skip illegal cluster shape
|
| 1934 |
+
if cluster_shape_mn[0] % (2 if use_2cta_instrs else 1) != 0:
|
| 1935 |
+
raise ValueError(
|
| 1936 |
+
f"cluster_shape_m need align with use_2cta_instrs config {cluster_shape_mn}"
|
| 1937 |
+
)
|
| 1938 |
+
# Skip invalid cluster shape
|
| 1939 |
+
is_power_of_2 = lambda x: x > 0 and (x & (x - 1)) == 0
|
| 1940 |
+
if (
|
| 1941 |
+
cluster_shape_mn[0] * cluster_shape_mn[1] > 16
|
| 1942 |
+
or cluster_shape_mn[0] <= 0
|
| 1943 |
+
or cluster_shape_mn[1] <= 0
|
| 1944 |
+
or not is_power_of_2(cluster_shape_mn[0])
|
| 1945 |
+
or not is_power_of_2(cluster_shape_mn[1])
|
| 1946 |
+
):
|
| 1947 |
+
raise ValueError(f"Skip invalid cluster shape {cluster_shape_mn}")
|
| 1948 |
+
|
| 1949 |
+
# Skip illegal problem shape for load/store alignment
|
| 1950 |
+
def check_contigous_16B_alignment(dtype, is_mode0_major, tensor_shape):
|
| 1951 |
+
major_mode_idx = 0 if is_mode0_major else 1
|
| 1952 |
+
num_major_elements = tensor_shape[major_mode_idx]
|
| 1953 |
+
num_contiguous_elements = 16 * 8 // dtype.width
|
| 1954 |
+
return num_major_elements % num_contiguous_elements == 0
|
| 1955 |
+
|
| 1956 |
+
if (
|
| 1957 |
+
not check_contigous_16B_alignment(ab_dtype, a_major == "m", (m, k, l))
|
| 1958 |
+
or not check_contigous_16B_alignment(ab_dtype, b_major == "n", (n, k, l))
|
| 1959 |
+
or not check_contigous_16B_alignment(c_dtype, c_major == "m", (m, n, l))
|
| 1960 |
+
):
|
| 1961 |
+
raise ValueError("Skip invalid problem alignment")
|
| 1962 |
+
if not torch.cuda.is_available():
|
| 1963 |
+
raise RuntimeError("GPU is required to run this example!")
|
| 1964 |
+
|
| 1965 |
+
# Create tensors for all groups using the new function
|
| 1966 |
+
(
|
| 1967 |
+
ptrs_abc,
|
| 1968 |
+
torch_tensors_abc,
|
| 1969 |
+
cute_tensors_abc,
|
| 1970 |
+
strides_abc,
|
| 1971 |
+
torch_fp32_tensors_abc,
|
| 1972 |
+
) = create_tensors_for_all_groups(
|
| 1973 |
+
problem_sizes_mnkl,
|
| 1974 |
+
ab_dtype,
|
| 1975 |
+
c_dtype,
|
| 1976 |
+
a_major,
|
| 1977 |
+
b_major,
|
| 1978 |
+
c_major,
|
| 1979 |
+
)
|
| 1980 |
+
|
| 1981 |
+
# Choose A, B, C with the smallest size to create initial tensormaps
|
| 1982 |
+
key_size_a = lambda item: item[1][0] * item[1][2]
|
| 1983 |
+
key_size_b = lambda item: item[1][1] * item[1][2]
|
| 1984 |
+
key_size_c = lambda item: item[1][0] * item[1][1]
|
| 1985 |
+
# Find the indices of the groups with the smallest tensor sizes
|
| 1986 |
+
min_a_idx, _ = min(enumerate(problem_sizes_mnkl), key=key_size_a)
|
| 1987 |
+
min_b_idx, _ = min(enumerate(problem_sizes_mnkl), key=key_size_b)
|
| 1988 |
+
min_c_idx, _ = min(enumerate(problem_sizes_mnkl), key=key_size_c)
|
| 1989 |
+
initial_cute_tensors_abc = [
|
| 1990 |
+
cute_tensors_abc[min_a_idx][0], # A with smallest (m, k)
|
| 1991 |
+
cute_tensors_abc[min_b_idx][1], # B with smallest (n, k)
|
| 1992 |
+
cute_tensors_abc[min_c_idx][2], # C with smallest (m, n)
|
| 1993 |
+
]
|
| 1994 |
+
|
| 1995 |
+
hardware_info = utils.HardwareInfo()
|
| 1996 |
+
sm_count = hardware_info.get_max_active_clusters(1)
|
| 1997 |
+
max_active_clusters = hardware_info.get_max_active_clusters(
|
| 1998 |
+
cluster_shape_mn[0] * cluster_shape_mn[1]
|
| 1999 |
+
)
|
| 2000 |
+
# Prepare tensormap buffer for each SM
|
| 2001 |
+
num_tensormap_buffers = sm_count
|
| 2002 |
+
tensormap_shape = (
|
| 2003 |
+
num_tensormap_buffers,
|
| 2004 |
+
GroupedGemmKernel.num_tensormaps,
|
| 2005 |
+
GroupedGemmKernel.bytes_per_tensormap // 8,
|
| 2006 |
+
)
|
| 2007 |
+
tensor_of_tensormap, tensor_of_tensormap_torch = cutlass_torch.cute_tensor_like(
|
| 2008 |
+
torch.empty(tensormap_shape, dtype=torch.int64),
|
| 2009 |
+
cutlass.Int64,
|
| 2010 |
+
is_dynamic_layout=False,
|
| 2011 |
+
)
|
| 2012 |
+
|
| 2013 |
+
grouped_gemm = GroupedGemmKernel(
|
| 2014 |
+
acc_dtype,
|
| 2015 |
+
use_2cta_instrs,
|
| 2016 |
+
mma_tiler_mn,
|
| 2017 |
+
cluster_shape_mn,
|
| 2018 |
+
tensormap_update_mode,
|
| 2019 |
+
)
|
| 2020 |
+
|
| 2021 |
+
# layout (num_groups, 4):(4, 1)
|
| 2022 |
+
(
|
| 2023 |
+
tensor_of_dim_size_mnkl,
|
| 2024 |
+
tensor_of_dim_size_mnkl_torch,
|
| 2025 |
+
) = cutlass_torch.cute_tensor_like(
|
| 2026 |
+
torch.tensor(problem_sizes_mnkl, dtype=torch.int32),
|
| 2027 |
+
cutlass.Int32,
|
| 2028 |
+
is_dynamic_layout=False,
|
| 2029 |
+
assumed_align=16,
|
| 2030 |
+
)
|
| 2031 |
+
|
| 2032 |
+
# layout (num_groups, 3, 2):(6, 2, 1)
|
| 2033 |
+
tensor_of_strides_abc, tensor_of_strides_abc_torch = cutlass_torch.cute_tensor_like(
|
| 2034 |
+
torch.tensor(strides_abc, dtype=torch.int32),
|
| 2035 |
+
cutlass.Int32,
|
| 2036 |
+
is_dynamic_layout=False,
|
| 2037 |
+
assumed_align=16,
|
| 2038 |
+
)
|
| 2039 |
+
|
| 2040 |
+
# layout (num_groups,3):(3, 1)
|
| 2041 |
+
tensor_of_ptrs_abc, tensor_of_ptrs_abc_torch = cutlass_torch.cute_tensor_like(
|
| 2042 |
+
torch.tensor(ptrs_abc, dtype=torch.int64),
|
| 2043 |
+
cutlass.Int64,
|
| 2044 |
+
is_dynamic_layout=False,
|
| 2045 |
+
assumed_align=16,
|
| 2046 |
+
)
|
| 2047 |
+
|
| 2048 |
+
# Compute total number of cluster tiles we need to compute for given grouped GEMM problem
|
| 2049 |
+
def compute_total_num_clusters(
|
| 2050 |
+
problem_sizes_mnkl: List[tuple[int, int, int, int]],
|
| 2051 |
+
cluster_tile_shape_mn: tuple[int, int],
|
| 2052 |
+
) -> int:
|
| 2053 |
+
total_num_clusters = 0
|
| 2054 |
+
for m, n, _, _ in problem_sizes_mnkl:
|
| 2055 |
+
num_clusters_mn = tuple(
|
| 2056 |
+
(x + y - 1) // y for x, y in zip((m, n), cluster_tile_shape_mn)
|
| 2057 |
+
)
|
| 2058 |
+
total_num_clusters += functools.reduce(lambda x, y: x * y, num_clusters_mn)
|
| 2059 |
+
return total_num_clusters
|
| 2060 |
+
|
| 2061 |
+
# Compute cluster tile shape
|
| 2062 |
+
def compute_cluster_tile_shape(
|
| 2063 |
+
mma_tiler_mn: tuple[int, int],
|
| 2064 |
+
cluster_shape_mn: tuple[int, int],
|
| 2065 |
+
use_2cta_instrs: bool,
|
| 2066 |
+
) -> tuple[int, int]:
|
| 2067 |
+
cta_tile_shape_mn = list(mma_tiler_mn)
|
| 2068 |
+
if use_2cta_instrs:
|
| 2069 |
+
cta_tile_shape_mn[0] = cta_tile_shape_mn[0] // 2
|
| 2070 |
+
return tuple(x * y for x, y in zip(cta_tile_shape_mn, cluster_shape_mn))
|
| 2071 |
+
|
| 2072 |
+
cluster_tile_shape_mn = compute_cluster_tile_shape(
|
| 2073 |
+
mma_tiler_mn, cluster_shape_mn, use_2cta_instrs
|
| 2074 |
+
)
|
| 2075 |
+
total_num_clusters = compute_total_num_clusters(
|
| 2076 |
+
problem_sizes_mnkl, cluster_tile_shape_mn
|
| 2077 |
+
)
|
| 2078 |
+
|
| 2079 |
+
# Initialize Stream
|
| 2080 |
+
current_stream = cutlass_torch.default_stream()
|
| 2081 |
+
|
| 2082 |
+
# Compile grouped GEMM kernel
|
| 2083 |
+
compiled_grouped_gemm = cute.compile(
|
| 2084 |
+
grouped_gemm,
|
| 2085 |
+
initial_cute_tensors_abc[0],
|
| 2086 |
+
initial_cute_tensors_abc[1],
|
| 2087 |
+
initial_cute_tensors_abc[2],
|
| 2088 |
+
num_groups,
|
| 2089 |
+
tensor_of_dim_size_mnkl,
|
| 2090 |
+
tensor_of_strides_abc,
|
| 2091 |
+
tensor_of_ptrs_abc,
|
| 2092 |
+
total_num_clusters,
|
| 2093 |
+
tensor_of_tensormap,
|
| 2094 |
+
max_active_clusters,
|
| 2095 |
+
current_stream,
|
| 2096 |
+
)
|
| 2097 |
+
|
| 2098 |
+
if not skip_ref_check:
|
| 2099 |
+
compiled_grouped_gemm(
|
| 2100 |
+
initial_cute_tensors_abc[0],
|
| 2101 |
+
initial_cute_tensors_abc[1],
|
| 2102 |
+
initial_cute_tensors_abc[2],
|
| 2103 |
+
tensor_of_dim_size_mnkl,
|
| 2104 |
+
tensor_of_strides_abc,
|
| 2105 |
+
tensor_of_ptrs_abc,
|
| 2106 |
+
tensor_of_tensormap,
|
| 2107 |
+
current_stream,
|
| 2108 |
+
)
|
| 2109 |
+
|
| 2110 |
+
# Compute reference result
|
| 2111 |
+
for i, (a, b, c) in enumerate(torch_tensors_abc):
|
| 2112 |
+
ref = torch.einsum(
|
| 2113 |
+
"mkl,nkl->mnl",
|
| 2114 |
+
a.cpu().to(dtype=torch.float32),
|
| 2115 |
+
b.cpu().to(dtype=torch.float32),
|
| 2116 |
+
)
|
| 2117 |
+
print(f"checking group {i}")
|
| 2118 |
+
torch.testing.assert_close(
|
| 2119 |
+
c.cpu(),
|
| 2120 |
+
ref.to(cutlass_torch.dtype(c_dtype)),
|
| 2121 |
+
atol=tolerance,
|
| 2122 |
+
rtol=1e-05,
|
| 2123 |
+
)
|
| 2124 |
+
|
| 2125 |
+
def generate_tensors():
|
| 2126 |
+
# Reuse existing CPU tensors and create new GPU tensors from them
|
| 2127 |
+
(
|
| 2128 |
+
ptrs_abc_workspace,
|
| 2129 |
+
torch_tensors_abc_workspace,
|
| 2130 |
+
cute_tensors_abc_workspace,
|
| 2131 |
+
strides_abc_workspace,
|
| 2132 |
+
_,
|
| 2133 |
+
) = create_tensors_for_all_groups(
|
| 2134 |
+
problem_sizes_mnkl,
|
| 2135 |
+
ab_dtype,
|
| 2136 |
+
c_dtype,
|
| 2137 |
+
a_major,
|
| 2138 |
+
b_major,
|
| 2139 |
+
c_major,
|
| 2140 |
+
torch_fp32_tensors_abc,
|
| 2141 |
+
)
|
| 2142 |
+
|
| 2143 |
+
initial_cute_tensors_abc_workspace = [
|
| 2144 |
+
cute_tensors_abc_workspace[min_a_idx][0], # A with smallest (m, k)
|
| 2145 |
+
cute_tensors_abc_workspace[min_b_idx][1], # B with smallest (n, k)
|
| 2146 |
+
cute_tensors_abc_workspace[min_c_idx][2], # C with smallest (m, n)
|
| 2147 |
+
]
|
| 2148 |
+
|
| 2149 |
+
# Create new tensors for this workspace
|
| 2150 |
+
tensor_of_strides_abc_workspace, _ = cutlass_torch.cute_tensor_like(
|
| 2151 |
+
torch.tensor(strides_abc_workspace, dtype=torch.int32),
|
| 2152 |
+
cutlass.Int32,
|
| 2153 |
+
is_dynamic_layout=False,
|
| 2154 |
+
assumed_align=16,
|
| 2155 |
+
)
|
| 2156 |
+
|
| 2157 |
+
tensor_of_ptrs_abc_workspace, _ = cutlass_torch.cute_tensor_like(
|
| 2158 |
+
torch.tensor(ptrs_abc_workspace, dtype=torch.int64),
|
| 2159 |
+
cutlass.Int64,
|
| 2160 |
+
is_dynamic_layout=False,
|
| 2161 |
+
assumed_align=16,
|
| 2162 |
+
)
|
| 2163 |
+
|
| 2164 |
+
tensormap_workspace, _ = cutlass_torch.cute_tensor_like(
|
| 2165 |
+
torch.empty(tensormap_shape, dtype=torch.int64),
|
| 2166 |
+
cutlass.Int64,
|
| 2167 |
+
is_dynamic_layout=False,
|
| 2168 |
+
)
|
| 2169 |
+
|
| 2170 |
+
return testing.JitArguments(
|
| 2171 |
+
initial_cute_tensors_abc_workspace[0],
|
| 2172 |
+
initial_cute_tensors_abc_workspace[1],
|
| 2173 |
+
initial_cute_tensors_abc_workspace[2],
|
| 2174 |
+
tensor_of_dim_size_mnkl,
|
| 2175 |
+
tensor_of_strides_abc_workspace,
|
| 2176 |
+
tensor_of_ptrs_abc_workspace,
|
| 2177 |
+
tensormap_workspace,
|
| 2178 |
+
current_stream,
|
| 2179 |
+
)
|
| 2180 |
+
|
| 2181 |
+
workspace_count = 1
|
| 2182 |
+
if use_cold_l2:
|
| 2183 |
+
one_workspace_bytes = (
|
| 2184 |
+
sum(
|
| 2185 |
+
[
|
| 2186 |
+
sum(
|
| 2187 |
+
[
|
| 2188 |
+
torch_tensor.numel() * torch_tensor.element_size()
|
| 2189 |
+
for torch_tensor in group_tensors
|
| 2190 |
+
]
|
| 2191 |
+
)
|
| 2192 |
+
for group_tensors in torch_tensors_abc
|
| 2193 |
+
]
|
| 2194 |
+
)
|
| 2195 |
+
+
|
| 2196 |
+
# Add size of strides tensor
|
| 2197 |
+
tensor_of_strides_abc_torch.numel()
|
| 2198 |
+
* tensor_of_strides_abc_torch.element_size()
|
| 2199 |
+
+
|
| 2200 |
+
# Add size of ptrs tensor
|
| 2201 |
+
tensor_of_ptrs_abc_torch.numel() * tensor_of_ptrs_abc_torch.element_size()
|
| 2202 |
+
+
|
| 2203 |
+
# Add size of tensormap tensor
|
| 2204 |
+
tensor_of_tensormap_torch.numel() * tensor_of_tensormap_torch.element_size()
|
| 2205 |
+
)
|
| 2206 |
+
workspace_count = testing.get_workspace_count(
|
| 2207 |
+
one_workspace_bytes, warmup_iterations, iterations
|
| 2208 |
+
)
|
| 2209 |
+
|
| 2210 |
+
exec_time = testing.benchmark(
|
| 2211 |
+
compiled_grouped_gemm,
|
| 2212 |
+
workspace_generator=generate_tensors,
|
| 2213 |
+
workspace_count=workspace_count,
|
| 2214 |
+
stream=current_stream,
|
| 2215 |
+
warmup_iterations=warmup_iterations,
|
| 2216 |
+
iterations=iterations,
|
| 2217 |
+
)
|
| 2218 |
+
|
| 2219 |
+
return exec_time # Return execution time in microseconds
|
| 2220 |
+
|
| 2221 |
+
|
| 2222 |
+
if __name__ == "__main__":
|
| 2223 |
+
|
| 2224 |
+
def parse_comma_separated_ints(s: str) -> tuple[int, ...]:
|
| 2225 |
+
try:
|
| 2226 |
+
return tuple(int(x.strip()) for x in s.split(","))
|
| 2227 |
+
except ValueError:
|
| 2228 |
+
raise argparse.ArgumentTypeError(
|
| 2229 |
+
"Invalid format. Expected comma-separated integers."
|
| 2230 |
+
)
|
| 2231 |
+
|
| 2232 |
+
def parse_comma_separated_tuples(s: str) -> List[tuple[int, ...]]:
|
| 2233 |
+
if s.strip().startswith("("):
|
| 2234 |
+
# Split on ),( to separate tuples
|
| 2235 |
+
tuples = s.strip("()").split("),(")
|
| 2236 |
+
result = []
|
| 2237 |
+
tuple_len = None
|
| 2238 |
+
|
| 2239 |
+
for t in tuples:
|
| 2240 |
+
# Parse individual tuple
|
| 2241 |
+
nums = [int(x.strip()) for x in t.split(",")]
|
| 2242 |
+
|
| 2243 |
+
# Validate tuple length consistency
|
| 2244 |
+
if tuple_len is None:
|
| 2245 |
+
tuple_len = len(nums)
|
| 2246 |
+
elif len(nums) != tuple_len:
|
| 2247 |
+
raise argparse.ArgumentTypeError(
|
| 2248 |
+
"All tuples must have the same length"
|
| 2249 |
+
)
|
| 2250 |
+
|
| 2251 |
+
result.append(tuple(nums))
|
| 2252 |
+
return result
|
| 2253 |
+
|
| 2254 |
+
raise argparse.ArgumentTypeError(
|
| 2255 |
+
"Invalid format. Expected comma-separated integers or list of tuples"
|
| 2256 |
+
)
|
| 2257 |
+
|
| 2258 |
+
parser = argparse.ArgumentParser(
|
| 2259 |
+
description="Example of Grouped GEMM on Blackwell."
|
| 2260 |
+
)
|
| 2261 |
+
parser.add_argument(
|
| 2262 |
+
"--num_groups",
|
| 2263 |
+
type=int,
|
| 2264 |
+
default=2,
|
| 2265 |
+
help="Number of groups",
|
| 2266 |
+
)
|
| 2267 |
+
parser.add_argument(
|
| 2268 |
+
"--problem_sizes_mnkl",
|
| 2269 |
+
type=parse_comma_separated_tuples,
|
| 2270 |
+
default=((128, 128, 128, 1), (128, 128, 128, 1)),
|
| 2271 |
+
help="a tuple of problem sizes for each group (comma-separated tuples)",
|
| 2272 |
+
)
|
| 2273 |
+
parser.add_argument(
|
| 2274 |
+
"--mma_tiler_mn",
|
| 2275 |
+
type=parse_comma_separated_ints,
|
| 2276 |
+
default=(128, 128),
|
| 2277 |
+
help="Mma tile shape (comma-separated)",
|
| 2278 |
+
)
|
| 2279 |
+
parser.add_argument(
|
| 2280 |
+
"--cluster_shape_mn",
|
| 2281 |
+
type=parse_comma_separated_ints,
|
| 2282 |
+
default=(1, 1),
|
| 2283 |
+
help="Cluster shape (comma-separated)",
|
| 2284 |
+
)
|
| 2285 |
+
parser.add_argument(
|
| 2286 |
+
"--tensormap_update_mode",
|
| 2287 |
+
type=str,
|
| 2288 |
+
default="SMEM",
|
| 2289 |
+
help="Tensor map update mode",
|
| 2290 |
+
)
|
| 2291 |
+
parser.add_argument("--ab_dtype", type=cutlass.dtype, default=cutlass.Float16)
|
| 2292 |
+
parser.add_argument("--c_dtype", type=cutlass.dtype, default=cutlass.Float16)
|
| 2293 |
+
parser.add_argument("--acc_dtype", type=cutlass.dtype, default=cutlass.Float32)
|
| 2294 |
+
parser.add_argument(
|
| 2295 |
+
"--use_2cta_instrs",
|
| 2296 |
+
action="store_true",
|
| 2297 |
+
help="Enable 2CTA MMA instructions feature",
|
| 2298 |
+
)
|
| 2299 |
+
parser.add_argument("--a_major", choices=["k", "m"], type=str, default="k")
|
| 2300 |
+
parser.add_argument("--b_major", choices=["k", "n"], type=str, default="k")
|
| 2301 |
+
parser.add_argument("--c_major", choices=["n", "m"], type=str, default="n")
|
| 2302 |
+
parser.add_argument(
|
| 2303 |
+
"--tolerance", type=float, default=1e-01, help="Tolerance for validation"
|
| 2304 |
+
)
|
| 2305 |
+
parser.add_argument(
|
| 2306 |
+
"--warmup_iterations", type=int, default=0, help="Warmup iterations"
|
| 2307 |
+
)
|
| 2308 |
+
parser.add_argument(
|
| 2309 |
+
"--iterations",
|
| 2310 |
+
type=int,
|
| 2311 |
+
default=1,
|
| 2312 |
+
help="Number of iterations to run the kernel",
|
| 2313 |
+
)
|
| 2314 |
+
parser.add_argument(
|
| 2315 |
+
"--skip_ref_check", action="store_true", help="Skip reference checking"
|
| 2316 |
+
)
|
| 2317 |
+
parser.add_argument(
|
| 2318 |
+
"--use_cold_l2",
|
| 2319 |
+
action="store_true",
|
| 2320 |
+
default=False,
|
| 2321 |
+
help="Use circular buffer tensor sets to ensure L2 cold cache",
|
| 2322 |
+
)
|
| 2323 |
+
|
| 2324 |
+
args = parser.parse_args()
|
| 2325 |
+
|
| 2326 |
+
if (
|
| 2327 |
+
len(args.problem_sizes_mnkl) != 0
|
| 2328 |
+
and len(args.problem_sizes_mnkl) != args.num_groups
|
| 2329 |
+
):
|
| 2330 |
+
parser.error("--problem_sizes_mnkl must contain exactly num_groups tuples")
|
| 2331 |
+
|
| 2332 |
+
# l mode must be 1 for all groups
|
| 2333 |
+
for _, _, _, l in args.problem_sizes_mnkl:
|
| 2334 |
+
if l != 1:
|
| 2335 |
+
parser.error("l must be 1 for all groups")
|
| 2336 |
+
|
| 2337 |
+
if len(args.mma_tiler_mn) != 2:
|
| 2338 |
+
parser.error("--mma_tiler_mn must contain exactly 2 values")
|
| 2339 |
+
|
| 2340 |
+
if len(args.cluster_shape_mn) != 2:
|
| 2341 |
+
parser.error("--cluster_shape_mn must contain exactly 2 values")
|
| 2342 |
+
|
| 2343 |
+
if args.tensormap_update_mode not in ["GMEM", "SMEM"]:
|
| 2344 |
+
parser.error("--tensormap_update_mode must be GMEM or SMEM")
|
| 2345 |
+
|
| 2346 |
+
if args.tensormap_update_mode == "GMEM":
|
| 2347 |
+
tensormap_update_mode = utils.TensorMapUpdateMode.GMEM
|
| 2348 |
+
else:
|
| 2349 |
+
tensormap_update_mode = utils.TensorMapUpdateMode.SMEM
|
| 2350 |
+
|
| 2351 |
+
torch.manual_seed(2025)
|
| 2352 |
+
|
| 2353 |
+
run(
|
| 2354 |
+
args.num_groups,
|
| 2355 |
+
args.problem_sizes_mnkl,
|
| 2356 |
+
args.ab_dtype,
|
| 2357 |
+
args.c_dtype,
|
| 2358 |
+
args.acc_dtype,
|
| 2359 |
+
args.a_major,
|
| 2360 |
+
args.b_major,
|
| 2361 |
+
args.c_major,
|
| 2362 |
+
args.mma_tiler_mn,
|
| 2363 |
+
args.cluster_shape_mn,
|
| 2364 |
+
args.use_2cta_instrs,
|
| 2365 |
+
tensormap_update_mode,
|
| 2366 |
+
args.tolerance,
|
| 2367 |
+
args.warmup_iterations,
|
| 2368 |
+
args.iterations,
|
| 2369 |
+
args.skip_ref_check,
|
| 2370 |
+
args.use_cold_l2,
|
| 2371 |
+
)
|
| 2372 |
+
print("PASS")
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/lookup_table/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Template lookup table system for PyTorch Inductor.
|
| 3 |
+
|
| 4 |
+
This package provides functionality for:
|
| 5 |
+
- Loading pre-configured template choices from lookup tables
|
| 6 |
+
- Managing template configurations and choices
|
| 7 |
+
|
| 8 |
+
All functionality is contained within the LookupTableChoices class.
|
| 9 |
+
You can customize any aspect by subclassing LookupTableChoices and overriding methods.
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
# Basic usage
|
| 13 |
+
choices = LookupTableChoices()
|
| 14 |
+
V.set_choices_handler(choices)
|
| 15 |
+
|
| 16 |
+
# Custom usage
|
| 17 |
+
class MyCustomChoices(LookupTableChoices):
|
| 18 |
+
def _get_lookup_table(self):
|
| 19 |
+
return my_custom_table
|
| 20 |
+
|
| 21 |
+
def make_lookup_key(self, kernel_inputs, op_name, include_device=False):
|
| 22 |
+
return f"custom_{op_name}_{hash(str(kernel_inputs))}"
|
| 23 |
+
|
| 24 |
+
V.set_choices_handler(MyCustomChoices())
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
from .choices import LookupTableChoices
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
"LookupTableChoices",
|
| 32 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/lookup_table/choices.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ging
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch._inductor import config
|
| 10 |
+
from torch._inductor.choices import InductorChoices
|
| 11 |
+
from torch._inductor.kernel_template_choice import KernelTemplateChoice
|
| 12 |
+
from torch._inductor.template_heuristics.params import DictKernelTemplateParams
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
log = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from collections.abc import Generator
|
| 20 |
+
|
| 21 |
+
from torch._inductor.codegen.common import KernelTemplate
|
| 22 |
+
from torch._inductor.kernel_inputs import KernelInputs
|
| 23 |
+
from torch._inductor.select_algorithm import ExternKernelChoice
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class LookupTableChoices(InductorChoices):
|
| 27 |
+
"""
|
| 28 |
+
InductorChoices subclass that uses lookup table when available, otherwise falls back to parent.
|
| 29 |
+
All lookup functionality is contained within this class and can be customized by overriding methods.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def _get_lookup_table(self) -> dict[str, list[dict[str, Any]]]:
|
| 33 |
+
"""
|
| 34 |
+
Get the template lookup table from config.
|
| 35 |
+
Override this method to use custom lookup table sources (database, API, etc.).
|
| 36 |
+
"""
|
| 37 |
+
if not torch.cuda.is_available() or config.lookup_table.table is None:
|
| 38 |
+
return {}
|
| 39 |
+
return config.lookup_table.table
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
@lru_cache
|
| 43 |
+
def _get_device_key(device: torch.device) -> Optional[str]:
|
| 44 |
+
"""
|
| 45 |
+
Generate a device key for lookup table indexing.
|
| 46 |
+
For CPU devices, returns None.
|
| 47 |
+
For CUDA devices, returns the props.gcnArchName string.
|
| 48 |
+
"""
|
| 49 |
+
if device.type != "cuda":
|
| 50 |
+
# only cuda devices are supported, this indicates that the system is not in use
|
| 51 |
+
# for this device
|
| 52 |
+
return None
|
| 53 |
+
|
| 54 |
+
# Get CUDA device properties
|
| 55 |
+
props = torch.cuda.get_device_properties(device.index)
|
| 56 |
+
return props.gcnArchName
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def _generate_kernel_inputs_key(kernel_inputs: KernelInputs) -> str:
|
| 60 |
+
"""
|
| 61 |
+
Generate a key based on input node properties and scalars.
|
| 62 |
+
The key includes dtype, size, and stride information for each input node,
|
| 63 |
+
plus scalar values as key=value pairs separated by & signs.
|
| 64 |
+
"""
|
| 65 |
+
# Get node information using existing methods
|
| 66 |
+
dtypes = kernel_inputs.dtypes()
|
| 67 |
+
shapes = kernel_inputs.shapes_hinted()
|
| 68 |
+
strides = kernel_inputs.strides_hinted()
|
| 69 |
+
|
| 70 |
+
# Create tuple of (dtype, shape_list, stride_list) for each node
|
| 71 |
+
node_info = tuple(
|
| 72 |
+
(dtype, list(shape), list(stride))
|
| 73 |
+
for dtype, shape, stride in zip(dtypes, shapes, strides)
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Create base key from node information
|
| 77 |
+
fmt_key = str(node_info)
|
| 78 |
+
# Add scalar information if present
|
| 79 |
+
if kernel_inputs._scalars:
|
| 80 |
+
# Sort scalars for consistent key generation and join with &
|
| 81 |
+
scalar_parts = [
|
| 82 |
+
f"{key}={value}"
|
| 83 |
+
for key, value in sorted(kernel_inputs._scalars.items())
|
| 84 |
+
]
|
| 85 |
+
scalars_key = "&".join(scalar_parts)
|
| 86 |
+
fmt_key = f"{fmt_key}+{scalars_key}"
|
| 87 |
+
|
| 88 |
+
return f"{fmt_key}"
|
| 89 |
+
|
| 90 |
+
def make_lookup_key(
|
| 91 |
+
self, kernel_inputs: KernelInputs, op_name: str, include_device: bool = False
|
| 92 |
+
) -> Optional[str]:
|
| 93 |
+
"""
|
| 94 |
+
Create a flattened lookup key from kernel inputs and operation name.
|
| 95 |
+
Override this method to customize key generation.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
kernel_inputs: KernelInputs object containing input nodes and scalars
|
| 99 |
+
op_name: Operation name (e.g., "mm", "addmm")
|
| 100 |
+
include_device: Whether to include device key in the generated key
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
A string key combining device (optional), operation, and input information
|
| 104 |
+
"""
|
| 105 |
+
device = kernel_inputs.device()
|
| 106 |
+
dev_key = self._get_device_key(device)
|
| 107 |
+
if dev_key is None:
|
| 108 |
+
# The system does not run when dev_key is None, regardless of
|
| 109 |
+
# whether include_device is True or False
|
| 110 |
+
return None
|
| 111 |
+
if not include_device:
|
| 112 |
+
dev_key = None
|
| 113 |
+
|
| 114 |
+
# Generate input key using our staticmethod
|
| 115 |
+
input_key = self._generate_kernel_inputs_key(kernel_inputs)
|
| 116 |
+
|
| 117 |
+
# Create the flattened lookup key
|
| 118 |
+
if dev_key is not None:
|
| 119 |
+
key_parts = [dev_key, input_key, op_name]
|
| 120 |
+
else:
|
| 121 |
+
key_parts = [input_key, op_name]
|
| 122 |
+
|
| 123 |
+
return "+".join(key_parts)
|
| 124 |
+
|
| 125 |
+
def make_lookup_key_variants(
|
| 126 |
+
self, kernel_inputs: KernelInputs, op_name: str
|
| 127 |
+
) -> tuple[Optional[str], Optional[str]]:
|
| 128 |
+
"""
|
| 129 |
+
Generate both device-specific and device-agnostic lookup keys.
|
| 130 |
+
Override this method to customize key variant generation.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
kernel_inputs: KernelInputs object containing input nodes and scalars
|
| 134 |
+
op_name: Operation name (e.g., "mm", "addmm")
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
Tuple of (device_key, device_agnostic_key). Either may be None if generation fails.
|
| 138 |
+
"""
|
| 139 |
+
device_key = self.make_lookup_key(kernel_inputs, op_name, include_device=True)
|
| 140 |
+
device_agnostic_key = self.make_lookup_key(
|
| 141 |
+
kernel_inputs, op_name, include_device=False
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
return device_key, device_agnostic_key
|
| 145 |
+
|
| 146 |
+
@staticmethod
|
| 147 |
+
def _entry_is_valid(
|
| 148 |
+
cfg: dict[str, Any],
|
| 149 |
+
template_id: str,
|
| 150 |
+
template_hash_map: Optional[dict[str, Optional[str]]],
|
| 151 |
+
) -> bool:
|
| 152 |
+
"""
|
| 153 |
+
Check if a config entry is valid based on template hash validation.
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
cfg: Configuration dictionary that may contain a template_hash field
|
| 157 |
+
template_id: The template identifier
|
| 158 |
+
template_hash_map: Optional mapping from template_uid to src_hash for validation
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
True if the config is valid and should be kept, False if it should be filtered out
|
| 162 |
+
"""
|
| 163 |
+
# If hash checking is disabled or no hash map provided, keep the config
|
| 164 |
+
if not config.lookup_table.check_src_hash or not template_hash_map:
|
| 165 |
+
return True
|
| 166 |
+
|
| 167 |
+
template_hash = template_hash_map.get(template_id)
|
| 168 |
+
config_hash = cfg.get("template_hash")
|
| 169 |
+
|
| 170 |
+
# Both hashes present - validate they match
|
| 171 |
+
if template_hash is not None and config_hash is not None:
|
| 172 |
+
if config_hash != template_hash:
|
| 173 |
+
log.warning(
|
| 174 |
+
"Hash validation failed for template '%s': config_hash='%s' != template_hash='%s'. "
|
| 175 |
+
"Template code may have changed. Filtering out config: %s",
|
| 176 |
+
template_id,
|
| 177 |
+
config_hash,
|
| 178 |
+
template_hash,
|
| 179 |
+
{k: v for k, v in cfg.items() if k != "template_hash"},
|
| 180 |
+
)
|
| 181 |
+
return False
|
| 182 |
+
else:
|
| 183 |
+
log.debug(
|
| 184 |
+
"Hash validation passed for template '%s': hash='%s'",
|
| 185 |
+
template_id,
|
| 186 |
+
template_hash,
|
| 187 |
+
)
|
| 188 |
+
return True
|
| 189 |
+
# Config has no hash - keep it
|
| 190 |
+
elif config_hash is None:
|
| 191 |
+
log.debug(
|
| 192 |
+
"Config for template '%s' has no hash - keeping it (template_hash='%s')",
|
| 193 |
+
template_id,
|
| 194 |
+
template_hash,
|
| 195 |
+
)
|
| 196 |
+
return True
|
| 197 |
+
# Template has no hash - keep config
|
| 198 |
+
else:
|
| 199 |
+
log.debug(
|
| 200 |
+
"Template '%s' has no src_hash - keeping config with hash '%s'",
|
| 201 |
+
template_id,
|
| 202 |
+
config_hash,
|
| 203 |
+
)
|
| 204 |
+
return True
|
| 205 |
+
|
| 206 |
+
def lookup_template_configs(
|
| 207 |
+
self,
|
| 208 |
+
kernel_inputs: KernelInputs,
|
| 209 |
+
op_name: str,
|
| 210 |
+
template_uids: list[str],
|
| 211 |
+
template_hash_map: Optional[dict[str, Optional[str]]] = None,
|
| 212 |
+
) -> dict[str, list[dict[str, Any]]]:
|
| 213 |
+
"""
|
| 214 |
+
Unified function to look up template configurations for multiple templates.
|
| 215 |
+
Override this method to customize lookup logic.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
kernel_inputs: KernelInputs object containing input nodes and scalars
|
| 219 |
+
op_name: Operation name (e.g., "mm", "addmm")
|
| 220 |
+
template_uids: List of template identifiers (e.g., ["mm", "tma", "decompose_k"])
|
| 221 |
+
template_hash_map: Optional mapping from template_uid to src_hash for validation
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
{}: No lookup table in use, or no matches found for any template
|
| 225 |
+
{"template_uid1": [config1, config2], ...}: Matches found, filtered configurations
|
| 226 |
+
"""
|
| 227 |
+
lookup_table = self._get_lookup_table()
|
| 228 |
+
if not lookup_table:
|
| 229 |
+
log.debug("Lookup table: no table configured or CUDA unavailable")
|
| 230 |
+
return {}
|
| 231 |
+
|
| 232 |
+
# Try both key variants: device-specific first, then device-agnostic
|
| 233 |
+
# If both exist, device-specific takes priority
|
| 234 |
+
device_key, device_agnostic_key = self.make_lookup_key_variants(
|
| 235 |
+
kernel_inputs, op_name
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
config_list = []
|
| 239 |
+
|
| 240 |
+
for key_type, key in [
|
| 241 |
+
("device-specific", device_key),
|
| 242 |
+
("device-agnostic", device_agnostic_key),
|
| 243 |
+
]:
|
| 244 |
+
if key is not None:
|
| 245 |
+
config_list = lookup_table.get(key, [])
|
| 246 |
+
if config_list:
|
| 247 |
+
log.debug(
|
| 248 |
+
"Lookup table: found %d configs using %s key '%s' for %s",
|
| 249 |
+
len(config_list),
|
| 250 |
+
key_type,
|
| 251 |
+
key,
|
| 252 |
+
op_name,
|
| 253 |
+
)
|
| 254 |
+
break
|
| 255 |
+
else:
|
| 256 |
+
log.debug(
|
| 257 |
+
"Lookup table: no match for %s (tried keys: %s, %s) (table has %d keys)",
|
| 258 |
+
op_name,
|
| 259 |
+
device_key,
|
| 260 |
+
device_agnostic_key,
|
| 261 |
+
len(lookup_table),
|
| 262 |
+
)
|
| 263 |
+
return {}
|
| 264 |
+
|
| 265 |
+
log.debug(
|
| 266 |
+
"Lookup table: found %d configs for %s templates %s",
|
| 267 |
+
len(config_list),
|
| 268 |
+
op_name,
|
| 269 |
+
template_uids,
|
| 270 |
+
)
|
| 271 |
+
# Group configs by template_id
|
| 272 |
+
configs_by_template: dict[str, list[dict[str, Any]]] = {}
|
| 273 |
+
for cfg in config_list:
|
| 274 |
+
if not isinstance(cfg, dict):
|
| 275 |
+
raise ValueError(
|
| 276 |
+
f"Config for {op_name} operation is not a dictionary: {cfg}"
|
| 277 |
+
)
|
| 278 |
+
if "template_id" not in cfg:
|
| 279 |
+
raise ValueError(
|
| 280 |
+
f"Config for {op_name} operation missing required 'template_id' field: {cfg}"
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
template_id = cfg["template_id"]
|
| 284 |
+
if template_id in template_uids:
|
| 285 |
+
if template_id not in configs_by_template:
|
| 286 |
+
configs_by_template[template_id] = []
|
| 287 |
+
configs_by_template[template_id].append(cfg)
|
| 288 |
+
|
| 289 |
+
# Check template hashes and clean up template_id field
|
| 290 |
+
result = {}
|
| 291 |
+
for template_id, matching_configs in configs_by_template.items():
|
| 292 |
+
filtered_configs = []
|
| 293 |
+
for cfg in matching_configs:
|
| 294 |
+
# Check template hash using helper function
|
| 295 |
+
if not self._entry_is_valid(cfg, template_id, template_hash_map):
|
| 296 |
+
continue
|
| 297 |
+
|
| 298 |
+
# Return a copy of the config, as we don't want to modify the original
|
| 299 |
+
cconfig = copy.deepcopy(cfg)
|
| 300 |
+
# Lastly, we have to throw out the template_id, as it's not a valid kwarg
|
| 301 |
+
# and just used to identify which template the entry belongs to
|
| 302 |
+
del cconfig["template_id"]
|
| 303 |
+
# Similarly, the template_hash is not a valid kwarg
|
| 304 |
+
cconfig.pop("template_hash", None)
|
| 305 |
+
filtered_configs.append(cconfig)
|
| 306 |
+
|
| 307 |
+
if filtered_configs:
|
| 308 |
+
result[template_id] = filtered_configs
|
| 309 |
+
|
| 310 |
+
return result
|
| 311 |
+
|
| 312 |
+
def _finalize_template_configs(
|
| 313 |
+
self,
|
| 314 |
+
template_choices: dict[str, Generator[KernelTemplateChoice, None, None]],
|
| 315 |
+
kernel_inputs: KernelInputs,
|
| 316 |
+
templates: list[Union[KernelTemplate, ExternKernelChoice]],
|
| 317 |
+
op_name: str,
|
| 318 |
+
kwarg_overrides: Optional[dict[str, dict[str, Any]]] = None,
|
| 319 |
+
) -> list[KernelTemplateChoice]:
|
| 320 |
+
"""Check lookup table for hits, use those if found, otherwise fall back to parent."""
|
| 321 |
+
# 1. Collect template src_hashes for validation
|
| 322 |
+
template_uids = [template.uid for template in templates]
|
| 323 |
+
template_hash_map = {}
|
| 324 |
+
for template in templates:
|
| 325 |
+
src_hash = getattr(template, "src_hash", None)
|
| 326 |
+
template_hash_map[template.uid] = src_hash
|
| 327 |
+
|
| 328 |
+
log.debug(
|
| 329 |
+
"Choices: attempting lookup for %s with %d templates",
|
| 330 |
+
op_name,
|
| 331 |
+
len(template_uids),
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
# 2. Single batch lookup for all templates
|
| 335 |
+
lookup_results = self.lookup_template_configs(
|
| 336 |
+
kernel_inputs, op_name, template_uids, template_hash_map
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
# 3. Early exit if no lookup table or no matches
|
| 340 |
+
if not lookup_results: # Empty dict
|
| 341 |
+
log.info("LookupChoices: lookup miss for %s, using fallback", op_name)
|
| 342 |
+
return self._fallback(
|
| 343 |
+
template_choices,
|
| 344 |
+
kernel_inputs,
|
| 345 |
+
templates,
|
| 346 |
+
op_name,
|
| 347 |
+
kwarg_overrides,
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
log.info(
|
| 351 |
+
"LookupChoices: lookup hit for %s - found %d/%d templates: %s",
|
| 352 |
+
op_name,
|
| 353 |
+
len(lookup_results),
|
| 354 |
+
len(template_uids),
|
| 355 |
+
list(lookup_results.keys()),
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
# 4. Create KTCs only for templates with lookup entries
|
| 359 |
+
return self._create_lookup_choices(
|
| 360 |
+
lookup_results, templates, kernel_inputs, op_name
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
def _fallback(
|
| 364 |
+
self,
|
| 365 |
+
template_choices: dict[str, Generator[KernelTemplateChoice, None, None]],
|
| 366 |
+
kernel_inputs: KernelInputs,
|
| 367 |
+
templates: list[Union[KernelTemplate, ExternKernelChoice]],
|
| 368 |
+
op_name: str,
|
| 369 |
+
kwarg_overrides: Optional[dict[str, dict[str, Any]]] = None,
|
| 370 |
+
) -> list[KernelTemplateChoice]:
|
| 371 |
+
"""Fallback to parent if no lookup table or no matches."""
|
| 372 |
+
# NOTE: this is broken out, so that subclasses are able to override this
|
| 373 |
+
# to handle explicitly the situations where the lookup take had a miss vs
|
| 374 |
+
# overriding the entire logic
|
| 375 |
+
return super()._finalize_template_configs(
|
| 376 |
+
template_choices,
|
| 377 |
+
kernel_inputs,
|
| 378 |
+
templates,
|
| 379 |
+
op_name,
|
| 380 |
+
kwarg_overrides,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
def _create_lookup_choices(
|
| 384 |
+
self,
|
| 385 |
+
lookup_results: dict[str, list[dict[str, Any]]],
|
| 386 |
+
templates: list[Union[KernelTemplate, ExternKernelChoice]],
|
| 387 |
+
kernel_inputs: KernelInputs,
|
| 388 |
+
op_name: str,
|
| 389 |
+
) -> list[KernelTemplateChoice]:
|
| 390 |
+
"""Create KernelTemplateChoice objects from lookup results using parent's get_ktc method."""
|
| 391 |
+
templates_by_uid = {template.uid: template for template in templates}
|
| 392 |
+
lookup_choices: list[KernelTemplateChoice] = []
|
| 393 |
+
|
| 394 |
+
for template_uid, configs in lookup_results.items():
|
| 395 |
+
template = templates_by_uid[template_uid]
|
| 396 |
+
|
| 397 |
+
# Use parent's get_ktc method to get a generator, then get the first base KTC
|
| 398 |
+
ktc_generator = self.get_ktc(kernel_inputs, template, op_name)
|
| 399 |
+
|
| 400 |
+
try:
|
| 401 |
+
base_ktc = next(ktc_generator)
|
| 402 |
+
except StopIteration:
|
| 403 |
+
# No configs from heuristic, skip this template
|
| 404 |
+
continue
|
| 405 |
+
|
| 406 |
+
# For each lookup config, create a KTC with the override kwargs
|
| 407 |
+
for c in configs:
|
| 408 |
+
lookup_ktc = KernelTemplateChoice(
|
| 409 |
+
template=base_ktc.template,
|
| 410 |
+
# use the ones from the lookup table
|
| 411 |
+
params=DictKernelTemplateParams(c),
|
| 412 |
+
extra_kwargs=base_ktc.extra_kwargs,
|
| 413 |
+
layout=base_ktc.layout,
|
| 414 |
+
inputs=base_ktc.inputs,
|
| 415 |
+
)
|
| 416 |
+
lookup_choices.append(lookup_ktc)
|
| 417 |
+
|
| 418 |
+
return lookup_choices
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/package/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .package import AOTICompiledModel, load_package, package_aoti
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/package/build_package.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
build_package_contents = """
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from torch._inductor.package.package import compile_so
|
| 6 |
+
|
| 7 |
+
curr_dir = Path(__file__).parent
|
| 8 |
+
aoti_files = [
|
| 9 |
+
os.path.join(root, file)
|
| 10 |
+
for root, dirs, files in os.walk(curr_dir)
|
| 11 |
+
for file in files
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
output_so = compile_so(curr_dir, aoti_files, curr_dir)
|
| 15 |
+
"""
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/package/package.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import tempfile
|
| 6 |
+
from typing import IO
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from torch._inductor import config
|
| 10 |
+
from torch._inductor.cpp_builder import BuildOptionsBase, CppBuilder
|
| 11 |
+
from torch.export.pt2_archive._package import (
|
| 12 |
+
AOTI_FILES,
|
| 13 |
+
AOTICompiledModel,
|
| 14 |
+
load_pt2,
|
| 15 |
+
package_pt2,
|
| 16 |
+
)
|
| 17 |
+
from torch.types import FileLike
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
log = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def compile_so(aoti_dir: str, aoti_files: list[str], so_path: str) -> str:
|
| 24 |
+
def get_aoti_file_with_suffix(suffix: str) -> str:
|
| 25 |
+
for file in aoti_files:
|
| 26 |
+
if file.endswith(suffix):
|
| 27 |
+
return file
|
| 28 |
+
raise RuntimeError(f"Unable to find file with suffix {suffix}")
|
| 29 |
+
|
| 30 |
+
# Compile all the files into a .so
|
| 31 |
+
cpp_file = os.path.join(aoti_dir, get_aoti_file_with_suffix(".cpp"))
|
| 32 |
+
consts_o = os.path.join(aoti_dir, get_aoti_file_with_suffix(".o"))
|
| 33 |
+
|
| 34 |
+
file_name = os.path.splitext(cpp_file)[0]
|
| 35 |
+
|
| 36 |
+
# Parse compile flags and build the .o file
|
| 37 |
+
with open(file_name + "_compile_flags.json") as f:
|
| 38 |
+
compile_flags = json.load(f)
|
| 39 |
+
|
| 40 |
+
compile_options = BuildOptionsBase(
|
| 41 |
+
**compile_flags, use_relative_path=config.is_fbcode()
|
| 42 |
+
)
|
| 43 |
+
object_builder = CppBuilder(
|
| 44 |
+
name=file_name,
|
| 45 |
+
sources=cpp_file,
|
| 46 |
+
BuildOption=compile_options,
|
| 47 |
+
)
|
| 48 |
+
output_o = object_builder.get_target_file_path()
|
| 49 |
+
object_builder.build()
|
| 50 |
+
|
| 51 |
+
# Parse linker flags and build the .so file
|
| 52 |
+
with open(file_name + "_linker_flags.json") as f:
|
| 53 |
+
linker_flags = json.load(f)
|
| 54 |
+
|
| 55 |
+
linker_options = BuildOptionsBase(
|
| 56 |
+
**linker_flags, use_relative_path=config.is_fbcode()
|
| 57 |
+
)
|
| 58 |
+
so_builder = CppBuilder(
|
| 59 |
+
name=os.path.split(so_path)[-1],
|
| 60 |
+
sources=[output_o, consts_o],
|
| 61 |
+
BuildOption=linker_options,
|
| 62 |
+
output_dir=so_path,
|
| 63 |
+
)
|
| 64 |
+
output_so = so_builder.get_target_file_path()
|
| 65 |
+
so_builder.build()
|
| 66 |
+
|
| 67 |
+
# mmapped weights
|
| 68 |
+
serialized_weights_filename = file_name + "_serialized_weights.bin"
|
| 69 |
+
if serialized_weights_filename in aoti_files:
|
| 70 |
+
with open(serialized_weights_filename, "rb") as f_weights:
|
| 71 |
+
serialized_weights = f_weights.read()
|
| 72 |
+
|
| 73 |
+
with open(output_so, "a+b") as f_so:
|
| 74 |
+
so_size = f_so.tell()
|
| 75 |
+
# Page align the weights
|
| 76 |
+
f_so.write(b" " * (16384 - so_size % 16384))
|
| 77 |
+
f_so.write(serialized_weights)
|
| 78 |
+
|
| 79 |
+
return output_so
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def package_aoti(
|
| 83 |
+
archive_file: FileLike,
|
| 84 |
+
aoti_files: AOTI_FILES,
|
| 85 |
+
) -> FileLike:
|
| 86 |
+
"""
|
| 87 |
+
Saves the AOTInductor generated files to the PT2Archive format.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
archive_file: The file name to save the package to.
|
| 91 |
+
aoti_files: This can either be a singular path to a directory containing
|
| 92 |
+
the AOTInductor files, or a dictionary mapping the model name to the
|
| 93 |
+
path to its AOTInductor generated files.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
return package_pt2(
|
| 97 |
+
archive_file,
|
| 98 |
+
aoti_files=aoti_files,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def load_package(
|
| 103 |
+
path: FileLike,
|
| 104 |
+
model_name: str = "model",
|
| 105 |
+
run_single_threaded: bool = False,
|
| 106 |
+
num_runners: int = 1,
|
| 107 |
+
device_index: int = -1,
|
| 108 |
+
) -> AOTICompiledModel:
|
| 109 |
+
try:
|
| 110 |
+
pt2_contents = load_pt2(
|
| 111 |
+
path,
|
| 112 |
+
run_single_threaded=run_single_threaded,
|
| 113 |
+
num_runners=num_runners,
|
| 114 |
+
device_index=device_index,
|
| 115 |
+
)
|
| 116 |
+
if model_name not in pt2_contents.aoti_runners:
|
| 117 |
+
raise RuntimeError(f"Model {model_name} not found in package")
|
| 118 |
+
return pt2_contents.aoti_runners[model_name]
|
| 119 |
+
except RuntimeError:
|
| 120 |
+
log.warning("Loading outdated pt2 file. Please regenerate your package.")
|
| 121 |
+
|
| 122 |
+
if isinstance(path, (io.IOBase, IO)):
|
| 123 |
+
with tempfile.NamedTemporaryFile(suffix=".pt2") as f:
|
| 124 |
+
# TODO(angelayi): We shouldn't need to do this -- miniz should
|
| 125 |
+
# handle reading the buffer. This is just a temporary workaround
|
| 126 |
+
path.seek(0)
|
| 127 |
+
f.write(path.read())
|
| 128 |
+
log.debug("Writing buffer to tmp file located at %s.", f.name)
|
| 129 |
+
loader = torch._C._aoti.AOTIModelPackageLoader(
|
| 130 |
+
f.name, model_name, run_single_threaded, num_runners, device_index
|
| 131 |
+
)
|
| 132 |
+
return AOTICompiledModel(loader)
|
| 133 |
+
|
| 134 |
+
path = os.fspath(path) # AOTIModelPackageLoader expects (str, str)
|
| 135 |
+
loader = torch._C._aoti.AOTIModelPackageLoader(
|
| 136 |
+
path, model_name, run_single_threaded, num_runners, device_index
|
| 137 |
+
)
|
| 138 |
+
return AOTICompiledModel(loader)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/autotune_cache.py
ADDED
|
@@ -0,0 +1,649 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PyTorch Inductor Autotuning Cache System
|
| 3 |
+
|
| 4 |
+
This module implements a caching system for autotuning configurations in PyTorch's Inductor compiler.
|
| 5 |
+
It provides mechanisms to store and retrieve optimal kernel configurations both locally and remotely,
|
| 6 |
+
which significantly speeds up compilation by reusing previously discovered optimal parameters.
|
| 7 |
+
|
| 8 |
+
The caching system includes:
|
| 9 |
+
- Local filesystem caching for individual machine reuse
|
| 10 |
+
- Remote caching for sharing optimizations across machines
|
| 11 |
+
- Bundled caching to efficiently store multiple related configurations
|
| 12 |
+
- Cache invalidation based on PyTorch versions and backend changes
|
| 13 |
+
- Serialization/deserialization support for worker processes
|
| 14 |
+
|
| 15 |
+
Key components:
|
| 16 |
+
- AutotuneCache: Main class for managing cache access and storage
|
| 17 |
+
- AutotuneCacheBundler: Bundles multiple cache entries for efficient storage
|
| 18 |
+
- LocalAutotuneCache: Handles filesystem-based caching
|
| 19 |
+
- _LocalAutotuneCacheBackend: Low-level file operations for cache storage
|
| 20 |
+
- AutotuneCacheArtifact: Integration with PyTorch's artifact system
|
| 21 |
+
|
| 22 |
+
This caching system is critical for performance as it eliminates the need to re-run
|
| 23 |
+
expensive autotuning operations when the same kernels are compiled multiple times.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import dataclasses
|
| 29 |
+
import hashlib
|
| 30 |
+
import logging
|
| 31 |
+
import os
|
| 32 |
+
import os.path
|
| 33 |
+
import re
|
| 34 |
+
from typing import Any, TYPE_CHECKING
|
| 35 |
+
from typing_extensions import override
|
| 36 |
+
|
| 37 |
+
import torch
|
| 38 |
+
from torch._inductor.runtime.runtime_utils import cache_dir
|
| 39 |
+
from torch.compiler._cache import (
|
| 40 |
+
CacheArtifact,
|
| 41 |
+
CacheArtifactFactory,
|
| 42 |
+
CacheArtifactManager,
|
| 43 |
+
)
|
| 44 |
+
from torch.utils._triton import has_triton
|
| 45 |
+
|
| 46 |
+
from ..remote_cache import (
|
| 47 |
+
create_cache,
|
| 48 |
+
JsonDataTy,
|
| 49 |
+
RemoteCache,
|
| 50 |
+
RemoteCacheBackend,
|
| 51 |
+
RemoteCacheJsonSerde,
|
| 52 |
+
)
|
| 53 |
+
from .triton_compat import Config, HAS_WARP_SPEC
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if TYPE_CHECKING:
|
| 57 |
+
from ..remote_cache import Sample
|
| 58 |
+
|
| 59 |
+
log = logging.getLogger(__name__)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
_InductorMetaTy = dict[str, object]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def inductor_meta_from_config() -> _InductorMetaTy:
|
| 66 |
+
from torch._inductor import config
|
| 67 |
+
|
| 68 |
+
backend_hash = None
|
| 69 |
+
if has_triton():
|
| 70 |
+
try:
|
| 71 |
+
backend_hash = torch.utils._triton.triton_hash_with_backend()
|
| 72 |
+
except RuntimeError:
|
| 73 |
+
# This can get the error:
|
| 74 |
+
# RuntimeError: 0 active drivers ([]). There should only be one.
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
is_hip = None
|
| 78 |
+
if torch.version.hip is not None:
|
| 79 |
+
is_hip = True
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
"autotune_local_cache": config.autotune_local_cache,
|
| 83 |
+
"autotune_remote_cache": config.autotune_remote_cache,
|
| 84 |
+
"backend_hash": backend_hash,
|
| 85 |
+
"bundled_autotune_remote_cache": config.bundled_autotune_remote_cache,
|
| 86 |
+
"coordinate_descent_tuning": config.coordinate_descent_tuning,
|
| 87 |
+
"is_fbcode": config.is_fbcode(),
|
| 88 |
+
"is_hip": is_hip,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@CacheArtifactFactory.register
|
| 93 |
+
class AutotuneCacheArtifact(CacheArtifact):
|
| 94 |
+
@override
|
| 95 |
+
def populate_cache(self) -> None:
|
| 96 |
+
autotune_cache = _LocalAutotuneCacheBackend()
|
| 97 |
+
key = os.path.join(cache_dir(), self.key)
|
| 98 |
+
autotune_cache._put(key, self.content)
|
| 99 |
+
|
| 100 |
+
@override
|
| 101 |
+
@staticmethod
|
| 102 |
+
def type() -> str:
|
| 103 |
+
return "autotune"
|
| 104 |
+
|
| 105 |
+
@override
|
| 106 |
+
@staticmethod
|
| 107 |
+
def encode(content: JsonDataTy) -> bytes:
|
| 108 |
+
assert not isinstance(content, bytes)
|
| 109 |
+
serde = RemoteCacheJsonSerde()
|
| 110 |
+
content_bytes = serde.encode(content)
|
| 111 |
+
assert isinstance(content_bytes, bytes)
|
| 112 |
+
return content_bytes
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@dataclasses.dataclass
|
| 116 |
+
class AutotuneCache:
|
| 117 |
+
configs_hash: str
|
| 118 |
+
local_cache: tuple[RemoteCache[JsonDataTy], str] | None = None
|
| 119 |
+
remote_cache: tuple[RemoteCache[JsonDataTy], str] | None = None
|
| 120 |
+
|
| 121 |
+
# Create a AutotuneCache. Returns None if none of the caches can be used.
|
| 122 |
+
@staticmethod
|
| 123 |
+
def create(
|
| 124 |
+
inductor_meta: _InductorMetaTy, filename: str, configs_hash: str
|
| 125 |
+
) -> AutotuneCache | None:
|
| 126 |
+
cache = AutotuneCache(configs_hash)
|
| 127 |
+
key = AutotuneCache._prepare_key(filename)
|
| 128 |
+
|
| 129 |
+
cache._setup_local_cache(inductor_meta, os.path.dirname(filename), key)
|
| 130 |
+
cache._setup_remote_autotune_cache(inductor_meta, key)
|
| 131 |
+
if cache.local_cache or cache.remote_cache:
|
| 132 |
+
return cache
|
| 133 |
+
else:
|
| 134 |
+
return None
|
| 135 |
+
|
| 136 |
+
@staticmethod
|
| 137 |
+
def _prepare_key(filename: str) -> str:
|
| 138 |
+
from torch.compiler import config as cconfig
|
| 139 |
+
|
| 140 |
+
# base of filename is already sha256 hash the source contents
|
| 141 |
+
key = f"{os.path.basename(filename)}:{cconfig.cache_key_tag}"
|
| 142 |
+
return hashlib.sha256(key.encode("utf-8")).hexdigest()
|
| 143 |
+
|
| 144 |
+
# Read the best config options from the most local cache and return it.
|
| 145 |
+
def _read(self) -> dict[str, JsonDataTy] | None:
|
| 146 |
+
if local_cache := self.local_cache:
|
| 147 |
+
cache, key = local_cache
|
| 148 |
+
if best_config := cache.get(key):
|
| 149 |
+
if isinstance(best_config, dict):
|
| 150 |
+
return best_config
|
| 151 |
+
|
| 152 |
+
if remote_cache := self.remote_cache:
|
| 153 |
+
cache, key = remote_cache
|
| 154 |
+
if best_config := cache.get(key):
|
| 155 |
+
if isinstance(best_config, dict):
|
| 156 |
+
return best_config
|
| 157 |
+
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
# Read the best config options from the most local cache and figure out
|
| 161 |
+
# which `configs` represents that option.
|
| 162 |
+
def read_best(
|
| 163 |
+
self, inductor_meta: _InductorMetaTy, configs: list[Config]
|
| 164 |
+
) -> Config | None:
|
| 165 |
+
if best := self._read():
|
| 166 |
+
return _load_cached_autotuning(
|
| 167 |
+
best, self.configs_hash, configs, inductor_meta
|
| 168 |
+
)
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
# Set up local filesystem caching information
|
| 172 |
+
def _setup_local_cache(
|
| 173 |
+
self, inductor_meta: _InductorMetaTy, dirname: str, cache_key: str
|
| 174 |
+
) -> None:
|
| 175 |
+
if not inductor_meta.get("autotune_local_cache", True):
|
| 176 |
+
return
|
| 177 |
+
|
| 178 |
+
from ..codecache import torch_key
|
| 179 |
+
|
| 180 |
+
"""
|
| 181 |
+
[Note: torch_key in autotune cache key]
|
| 182 |
+
Include torch_key() in the cache key so that different versions
|
| 183 |
+
of torch result in cache invalidation. This is important in case
|
| 184 |
+
of changes to the best_config format or other code changes that
|
| 185 |
+
are not backward compatible w.r.t. the cache.
|
| 186 |
+
"""
|
| 187 |
+
hasher = hashlib.sha256()
|
| 188 |
+
hasher.update(cache_key.encode("utf-8"))
|
| 189 |
+
hasher.update(torch_key())
|
| 190 |
+
updated_cache_key = hasher.hexdigest()
|
| 191 |
+
|
| 192 |
+
cache_filename = f"{dirname}/{updated_cache_key}.best_config"
|
| 193 |
+
local_cache = LocalAutotuneCache()
|
| 194 |
+
self.local_cache = (local_cache, cache_filename)
|
| 195 |
+
|
| 196 |
+
# Set up remote caching information
|
| 197 |
+
def _setup_remote_autotune_cache(
|
| 198 |
+
self, inductor_meta: _InductorMetaTy, cache_key: str
|
| 199 |
+
) -> None:
|
| 200 |
+
if not _should_use_remote_autotune_cache(inductor_meta):
|
| 201 |
+
return
|
| 202 |
+
|
| 203 |
+
if (backend_hash := inductor_meta.get("backend_hash", None)) is None:
|
| 204 |
+
log.debug(
|
| 205 |
+
"backend_hash is not passed on the inductor_meta, unable to use autotune remote cache"
|
| 206 |
+
)
|
| 207 |
+
return
|
| 208 |
+
assert isinstance(backend_hash, str)
|
| 209 |
+
|
| 210 |
+
from ..codecache import torch_key
|
| 211 |
+
|
| 212 |
+
is_fbcode = bool(inductor_meta.get("is_fbcode", False))
|
| 213 |
+
|
| 214 |
+
salt = "autotune-best-config-v2"
|
| 215 |
+
# re: torch_key - see [Note: torch_key in autotune cache key]
|
| 216 |
+
key = torch_key().hex() + backend_hash + self.configs_hash + salt
|
| 217 |
+
key = hashlib.sha256(key.encode("utf-8")).hexdigest()
|
| 218 |
+
|
| 219 |
+
remote_cache = create_cache(
|
| 220 |
+
key,
|
| 221 |
+
is_fbcode,
|
| 222 |
+
"FbRemoteAutotuneCache",
|
| 223 |
+
"RemoteAutotuneCache",
|
| 224 |
+
)
|
| 225 |
+
if not remote_cache:
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
# Save the args passed to create_cache
|
| 229 |
+
# in case AutotuneCache needs to be pickled
|
| 230 |
+
self.remote_cache_full_key = key
|
| 231 |
+
self.is_fbcode = is_fbcode
|
| 232 |
+
self.remote_cache = (remote_cache, cache_key)
|
| 233 |
+
|
| 234 |
+
# The AutotuneCache may be serialized/deserialized if we're using
|
| 235 |
+
# AsyncCompile worker processes to run triton compilation.
|
| 236 |
+
# This is because AutotuneCache instances are created on the worker
|
| 237 |
+
# process, but we need to run AutotuneCache.save on the parent process
|
| 238 |
+
# when actually doing autotuning.
|
| 239 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 240 |
+
# The remote cache handles themselves may not be serializable
|
| 241 |
+
# So clear it and reconstruct it on setstate
|
| 242 |
+
remote_cache = getattr(self, "remote_cache", None)
|
| 243 |
+
return {
|
| 244 |
+
**self.__dict__,
|
| 245 |
+
# Save the cache_key portion
|
| 246 |
+
"remote_cache": remote_cache and remote_cache[1],
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
def __setstate__(self, state: dict[str, Any]) -> None:
|
| 250 |
+
# Reconstruct the remote cache on the parent class
|
| 251 |
+
self.__dict__.update(state)
|
| 252 |
+
if self.remote_cache is not None:
|
| 253 |
+
assert isinstance(self.remote_cache, str)
|
| 254 |
+
assert hasattr(self, "remote_cache_full_key")
|
| 255 |
+
assert hasattr(self, "is_fbcode")
|
| 256 |
+
cache_key = self.remote_cache
|
| 257 |
+
remote_cache = create_cache(
|
| 258 |
+
self.remote_cache_full_key,
|
| 259 |
+
self.is_fbcode,
|
| 260 |
+
"FbRemoteAutotuneCache",
|
| 261 |
+
"RemoteAutotuneCache",
|
| 262 |
+
)
|
| 263 |
+
if remote_cache is not None:
|
| 264 |
+
self.remote_cache = (remote_cache, cache_key)
|
| 265 |
+
else:
|
| 266 |
+
log.warning("Warning, failed to recreate remote cache after pickling")
|
| 267 |
+
self.remote_cache = None
|
| 268 |
+
|
| 269 |
+
# Save the config in the caches
|
| 270 |
+
def save(
|
| 271 |
+
self,
|
| 272 |
+
config: Config,
|
| 273 |
+
time_taken_ns: int,
|
| 274 |
+
found_by_coordesc: bool = False,
|
| 275 |
+
triton_cache_hash: str | None = None,
|
| 276 |
+
) -> None:
|
| 277 |
+
data = {
|
| 278 |
+
# pyrefly: ignore [missing-attribute]
|
| 279 |
+
**config.kwargs,
|
| 280 |
+
# pyrefly: ignore [missing-attribute]
|
| 281 |
+
"num_warps": config.num_warps,
|
| 282 |
+
# pyrefly: ignore [missing-attribute]
|
| 283 |
+
"num_stages": config.num_stages,
|
| 284 |
+
"configs_hash": self.configs_hash,
|
| 285 |
+
"found_by_coordesc": found_by_coordesc,
|
| 286 |
+
"time_taken_ms": time_taken_ns // 1000000, # Convert from NS to MS
|
| 287 |
+
"triton_cache_hash": triton_cache_hash,
|
| 288 |
+
}
|
| 289 |
+
if HAS_WARP_SPEC:
|
| 290 |
+
data.update(
|
| 291 |
+
{
|
| 292 |
+
"num_consumer_groups": getattr(config, "num_consumer_groups", 0),
|
| 293 |
+
"num_buffers_warp_spec": getattr(
|
| 294 |
+
config, "num_buffers_warp_spec", 0
|
| 295 |
+
),
|
| 296 |
+
}
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
if local_cache := self.local_cache:
|
| 300 |
+
cache, key = local_cache
|
| 301 |
+
cache.put(key, data)
|
| 302 |
+
AutotuneCacheBundler.put(key, data)
|
| 303 |
+
autotune_artifact_key = os.path.join(*key.split(os.sep)[-2:])
|
| 304 |
+
CacheArtifactManager.record_artifact(
|
| 305 |
+
AutotuneCacheArtifact.type(), autotune_artifact_key, data
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
if log.isEnabledFor(logging.DEBUG):
|
| 309 |
+
type_str = "coordesc" if found_by_coordesc else "heuristic"
|
| 310 |
+
log.debug("Save %s tuning result to %s", type_str, key)
|
| 311 |
+
|
| 312 |
+
if remote_cache := self.remote_cache:
|
| 313 |
+
cache, key = remote_cache
|
| 314 |
+
cache.put(key, data)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
class _AutotuneCacheBundlerImpl:
|
| 318 |
+
"""
|
| 319 |
+
Caches a set of LocalAutotuneCacheBackend entries together in a single
|
| 320 |
+
cache.
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
_key: str
|
| 324 |
+
_cache: RemoteCache[JsonDataTy]
|
| 325 |
+
|
| 326 |
+
# All known entries from LocalAutotuneCache.put()
|
| 327 |
+
_entries: dict[str, JsonDataTy]
|
| 328 |
+
|
| 329 |
+
def end_compile(self) -> None:
|
| 330 |
+
# TODO: Do we need to compute time_taken_ms and encode that somehow?
|
| 331 |
+
if self._entries:
|
| 332 |
+
self._cache.put(self._key, self._entries)
|
| 333 |
+
|
| 334 |
+
def put(self, basename: str, data: JsonDataTy) -> None:
|
| 335 |
+
# Do we need to worry about duplicates? We only have a single local fs
|
| 336 |
+
# entry - so probably not.
|
| 337 |
+
self._entries[basename] = data
|
| 338 |
+
|
| 339 |
+
def __init__(self, key: str, cache: RemoteCache[JsonDataTy]) -> None:
|
| 340 |
+
self._key = key
|
| 341 |
+
self._cache = cache
|
| 342 |
+
self._entries = {}
|
| 343 |
+
|
| 344 |
+
def sync(self) -> None:
|
| 345 |
+
# We don't currently use this - but we could async load starting at
|
| 346 |
+
# `begin_compile` and wait for the load to be finished here.
|
| 347 |
+
pass
|
| 348 |
+
|
| 349 |
+
@classmethod
|
| 350 |
+
def _should_use_bundled_autotune_remote_cache(
|
| 351 |
+
cls, inductor_meta: _InductorMetaTy
|
| 352 |
+
) -> bool:
|
| 353 |
+
# The bundled autotune cache is only available if you've also got local
|
| 354 |
+
# caching enabled (because we feed the bundled data to the local cache).
|
| 355 |
+
if not inductor_meta.get("autotune_local_cache", True):
|
| 356 |
+
return False
|
| 357 |
+
|
| 358 |
+
# Check if the we're enabled via config
|
| 359 |
+
if (
|
| 360 |
+
bundled_autotune_remote_cache := inductor_meta.get(
|
| 361 |
+
"bundled_autotune_remote_cache"
|
| 362 |
+
)
|
| 363 |
+
) is not None:
|
| 364 |
+
return bool(bundled_autotune_remote_cache)
|
| 365 |
+
|
| 366 |
+
if not cls._get_is_fbcode(inductor_meta):
|
| 367 |
+
return False
|
| 368 |
+
if torch._utils_internal.is_fb_unit_test():
|
| 369 |
+
return False
|
| 370 |
+
if inductor_meta.get("is_hip"):
|
| 371 |
+
return False
|
| 372 |
+
|
| 373 |
+
try:
|
| 374 |
+
from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION
|
| 375 |
+
except ModuleNotFoundError:
|
| 376 |
+
return False
|
| 377 |
+
|
| 378 |
+
jk = torch._utils_internal.justknobs_getval_int(
|
| 379 |
+
"pytorch/remote_cache:bundled_autotune_remote_cache_version"
|
| 380 |
+
)
|
| 381 |
+
return REMOTE_CACHE_VERSION >= jk
|
| 382 |
+
|
| 383 |
+
def _load_cache(self) -> bool:
|
| 384 |
+
from torch._inductor import codecache
|
| 385 |
+
|
| 386 |
+
# The single key is defined on construction of the cache.
|
| 387 |
+
entries = self._cache.get(self._key)
|
| 388 |
+
if entries is None or not isinstance(entries, dict):
|
| 389 |
+
# We couldn't load the cache - so mark _entries as non-None so we
|
| 390 |
+
# store local cache values.
|
| 391 |
+
return False
|
| 392 |
+
|
| 393 |
+
# Go through the entries we got from the cache and save them locally.
|
| 394 |
+
time_saved_ns = 0
|
| 395 |
+
for basename, data in entries.items():
|
| 396 |
+
# Reconstruct the final filename (see put())
|
| 397 |
+
root, ext = _splitext_nodot(basename)
|
| 398 |
+
_, _, filename = codecache.get_path(root, ext)
|
| 399 |
+
if isinstance(data, dict) and (tsns := data.get("time_saved_ns")):
|
| 400 |
+
time_saved_ns += int(tsns) # type: ignore[arg-type]
|
| 401 |
+
local_cache = LocalAutotuneCache()
|
| 402 |
+
local_cache.put(filename, data)
|
| 403 |
+
|
| 404 |
+
codecache.add_ephemeral_timeout_increase_for_distributed(time_saved_ns)
|
| 405 |
+
|
| 406 |
+
return True
|
| 407 |
+
|
| 408 |
+
@staticmethod
|
| 409 |
+
def _get_is_fbcode(inductor_meta: _InductorMetaTy) -> bool:
|
| 410 |
+
return bool(inductor_meta.get("is_fbcode", False))
|
| 411 |
+
|
| 412 |
+
@staticmethod
|
| 413 |
+
def _get_backend_hash(inductor_meta: _InductorMetaTy) -> str:
|
| 414 |
+
backend_hash = inductor_meta["backend_hash"]
|
| 415 |
+
assert isinstance(backend_hash, str)
|
| 416 |
+
return backend_hash
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class AutotuneCacheBundler:
|
| 420 |
+
_bundler: _AutotuneCacheBundlerImpl | None = None
|
| 421 |
+
|
| 422 |
+
def __init__(self) -> None:
|
| 423 |
+
pass
|
| 424 |
+
|
| 425 |
+
# Call this before we start any autotune computation for an inductor python
|
| 426 |
+
# file. On a cache hit it copies the individual results into the local
|
| 427 |
+
# autotune caches.
|
| 428 |
+
@classmethod
|
| 429 |
+
def begin_compile(
|
| 430 |
+
cls,
|
| 431 |
+
inductor_meta: _InductorMetaTy,
|
| 432 |
+
*,
|
| 433 |
+
code: str | None = None,
|
| 434 |
+
code_hash: str | None = None,
|
| 435 |
+
) -> None:
|
| 436 |
+
assert cls._bundler is None
|
| 437 |
+
|
| 438 |
+
if code is not None:
|
| 439 |
+
assert code_hash is None, "Cannot specify both code and code_hash"
|
| 440 |
+
code_hash = _comment_stripped_hash(code)
|
| 441 |
+
assert code_hash is not None
|
| 442 |
+
|
| 443 |
+
if not _AutotuneCacheBundlerImpl._should_use_bundled_autotune_remote_cache(
|
| 444 |
+
inductor_meta
|
| 445 |
+
):
|
| 446 |
+
return
|
| 447 |
+
|
| 448 |
+
cache = create_cache(
|
| 449 |
+
"bundled-autotune-v1",
|
| 450 |
+
_AutotuneCacheBundlerImpl._get_is_fbcode(inductor_meta),
|
| 451 |
+
"FbRemoteBundledAutotuneCache",
|
| 452 |
+
"RemoteBundledAutotuneCache",
|
| 453 |
+
)
|
| 454 |
+
if not cache:
|
| 455 |
+
return
|
| 456 |
+
|
| 457 |
+
# We're starting a compilation phase. We have a cache key for the code
|
| 458 |
+
# we're compiling. We'll get the individual autotune bundles later (via
|
| 459 |
+
# self.put()). For now create the AutotuneCacheBundler and try to load
|
| 460 |
+
# from the cache.
|
| 461 |
+
|
| 462 |
+
salt = "bundled-autotune-best-configs-v1"
|
| 463 |
+
backend_hash = _AutotuneCacheBundlerImpl._get_backend_hash(inductor_meta)
|
| 464 |
+
# TODO: The autotune cache includes configs_hash in the key. The problem
|
| 465 |
+
# is that the configs_hash includes info from the individual pointwise()
|
| 466 |
+
# calls (size_hints, for example) which we can't know yet. I *think*
|
| 467 |
+
# that info is basically present in the `code_hash` (since it's a
|
| 468 |
+
# parameter to the pointwise decorator) - but is there other info we
|
| 469 |
+
# need to include from inductor_meta?
|
| 470 |
+
key = code_hash + backend_hash + salt
|
| 471 |
+
key = hashlib.sha256(key.encode("utf-8")).hexdigest()
|
| 472 |
+
|
| 473 |
+
bundler = _AutotuneCacheBundlerImpl(key, cache)
|
| 474 |
+
if not bundler._load_cache():
|
| 475 |
+
# We couldn't load from the cache - so save the data so we can store
|
| 476 |
+
# the saved autotunes.
|
| 477 |
+
cls._bundler = bundler
|
| 478 |
+
|
| 479 |
+
# If we get a cache hit don't bother saving any of the individual
|
| 480 |
+
# autotune results.
|
| 481 |
+
|
| 482 |
+
# Call this after all individual autotune results are finished for a
|
| 483 |
+
# inductor python file. If we gathered any individual results then we bundle
|
| 484 |
+
# those and put it into the cache.
|
| 485 |
+
@classmethod
|
| 486 |
+
def end_compile(cls) -> None:
|
| 487 |
+
if bundler := cls._bundler:
|
| 488 |
+
cls._bundler = None
|
| 489 |
+
bundler.end_compile()
|
| 490 |
+
|
| 491 |
+
@classmethod
|
| 492 |
+
def sync(cls) -> None:
|
| 493 |
+
if bundler := cls._bundler:
|
| 494 |
+
bundler.sync()
|
| 495 |
+
|
| 496 |
+
@classmethod
|
| 497 |
+
def put(cls, filename: str, data: JsonDataTy) -> None:
|
| 498 |
+
if bundler := cls._bundler:
|
| 499 |
+
# The filename comes in as something like
|
| 500 |
+
# "/tmp/tmp{random}/{aa}/{basename}.py" (where aa is
|
| 501 |
+
# basename[1:3]). Strip it down and make sure that it looks like a path
|
| 502 |
+
# we could reconstruct (because it's possible for the caller to
|
| 503 |
+
# customize the path).
|
| 504 |
+
basename = os.path.basename(filename)
|
| 505 |
+
|
| 506 |
+
# TODO: check cache_dir() vs filename, then strip dirname
|
| 507 |
+
bundler.put(basename, data)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
# Remove the comments from the code (which include things like run ids and file
|
| 511 |
+
# paths) and then hash the result.
|
| 512 |
+
def _comment_stripped_hash(code: str) -> str:
|
| 513 |
+
code = re.sub(r"#.*$", "", code, count=0, flags=re.MULTILINE)
|
| 514 |
+
return torch._inductor.codecache.code_hash(code)
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def _should_use_remote_autotune_cache(inductor_meta: _InductorMetaTy) -> bool:
|
| 518 |
+
if (config := inductor_meta.get("autotune_remote_cache")) is not None:
|
| 519 |
+
return bool(config)
|
| 520 |
+
if not inductor_meta.get("is_fbcode"):
|
| 521 |
+
return False
|
| 522 |
+
if torch._utils_internal.is_fb_unit_test():
|
| 523 |
+
return False
|
| 524 |
+
if inductor_meta.get("is_hip"):
|
| 525 |
+
return False
|
| 526 |
+
|
| 527 |
+
try:
|
| 528 |
+
from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION
|
| 529 |
+
except ModuleNotFoundError:
|
| 530 |
+
return False
|
| 531 |
+
|
| 532 |
+
return REMOTE_CACHE_VERSION >= torch._utils_internal.justknobs_getval_int(
|
| 533 |
+
"pytorch/remote_cache:autotune_memcache_version"
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _load_cached_autotuning(
|
| 538 |
+
best_config: dict[str, JsonDataTy],
|
| 539 |
+
configs_hash: str,
|
| 540 |
+
configs: list[Config],
|
| 541 |
+
inductor_meta: _InductorMetaTy,
|
| 542 |
+
) -> Config | None:
|
| 543 |
+
if best_config is None:
|
| 544 |
+
return None
|
| 545 |
+
if best_config.pop("configs_hash", None) != configs_hash:
|
| 546 |
+
return None
|
| 547 |
+
|
| 548 |
+
# Remove time taken for comparison
|
| 549 |
+
best_config.pop("time_taken_ms", None)
|
| 550 |
+
|
| 551 |
+
best_config.pop("triton_cache_hash", None)
|
| 552 |
+
|
| 553 |
+
if inductor_meta.get("coordinate_descent_tuning") and best_config.pop(
|
| 554 |
+
"found_by_coordesc", False
|
| 555 |
+
):
|
| 556 |
+
num_warps = best_config.pop("num_warps")
|
| 557 |
+
num_stages = best_config.pop("num_stages")
|
| 558 |
+
|
| 559 |
+
# Extract common arguments
|
| 560 |
+
config_args = {
|
| 561 |
+
"num_warps": num_warps,
|
| 562 |
+
"num_stages": num_stages,
|
| 563 |
+
}
|
| 564 |
+
|
| 565 |
+
if HAS_WARP_SPEC:
|
| 566 |
+
config_args.update(
|
| 567 |
+
{
|
| 568 |
+
"num_consumer_groups": best_config.pop("num_consumer_groups", 0),
|
| 569 |
+
"num_buffers_warp_spec": best_config.pop(
|
| 570 |
+
"num_buffers_warp_spec", 0
|
| 571 |
+
),
|
| 572 |
+
}
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
# Create the triton_config with the appropriate arguments
|
| 576 |
+
# pyrefly: ignore [bad-argument-count]
|
| 577 |
+
triton_config = Config(best_config, **config_args)
|
| 578 |
+
# pyrefly: ignore [missing-attribute]
|
| 579 |
+
triton_config.found_by_coordesc = True
|
| 580 |
+
return triton_config
|
| 581 |
+
|
| 582 |
+
matching_configs = [
|
| 583 |
+
cfg
|
| 584 |
+
for cfg in configs
|
| 585 |
+
# pyrefly: ignore [missing-attribute]
|
| 586 |
+
if all(val == best_config.get(key) for key, val in cfg.kwargs.items())
|
| 587 |
+
# pyrefly: ignore [missing-attribute]
|
| 588 |
+
and cfg.num_warps == best_config.get("num_warps")
|
| 589 |
+
# pyrefly: ignore [missing-attribute]
|
| 590 |
+
and cfg.num_stages == best_config.get("num_stages")
|
| 591 |
+
]
|
| 592 |
+
if len(matching_configs) != 1:
|
| 593 |
+
return None
|
| 594 |
+
|
| 595 |
+
return matching_configs[0]
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class _LocalAutotuneCacheBackend(RemoteCacheBackend[bytes]):
|
| 599 |
+
@override
|
| 600 |
+
def _get(self, key: str) -> bytes | None:
|
| 601 |
+
try:
|
| 602 |
+
with open(key, "rb") as fd:
|
| 603 |
+
return fd.read()
|
| 604 |
+
except FileNotFoundError:
|
| 605 |
+
return None
|
| 606 |
+
|
| 607 |
+
@override
|
| 608 |
+
def _put(self, key: str, data: bytes) -> None:
|
| 609 |
+
os.makedirs(os.path.dirname(key), exist_ok=True)
|
| 610 |
+
from torch._inductor import codecache
|
| 611 |
+
|
| 612 |
+
codecache.write_atomic(key, data)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
class LocalAutotuneCache(RemoteCache[JsonDataTy]):
|
| 616 |
+
def __init__(self) -> None:
|
| 617 |
+
backend = _LocalAutotuneCacheBackend()
|
| 618 |
+
serde = RemoteCacheJsonSerde()
|
| 619 |
+
super().__init__(backend, serde)
|
| 620 |
+
|
| 621 |
+
@override
|
| 622 |
+
def _get(self, key: str, sample: Sample | None) -> JsonDataTy | None:
|
| 623 |
+
AutotuneCacheBundler.sync()
|
| 624 |
+
result = super()._get(key, sample)
|
| 625 |
+
if result is not None:
|
| 626 |
+
assert isinstance(result, dict)
|
| 627 |
+
# What? Why are we doing a put() here? Imagine we have a new model
|
| 628 |
+
# that reuses some existing kernels that have already been
|
| 629 |
+
# compiled. If we didn't do a `put` here (on cache hit) then the new
|
| 630 |
+
# model would only bundle *newly* compiled kernels, not existing
|
| 631 |
+
# kernels that were already compiled and cached.
|
| 632 |
+
AutotuneCacheBundler.put(key, result)
|
| 633 |
+
autotune_artifact_key = os.path.join(*key.split(os.sep)[-2:])
|
| 634 |
+
CacheArtifactManager.record_artifact(
|
| 635 |
+
AutotuneCacheArtifact.type(), autotune_artifact_key, result
|
| 636 |
+
)
|
| 637 |
+
return result
|
| 638 |
+
|
| 639 |
+
@override
|
| 640 |
+
def _put(self, key: str, value: JsonDataTy, sample: Sample | None) -> None:
|
| 641 |
+
AutotuneCacheBundler.put(key, value)
|
| 642 |
+
super()._put(key, value, sample)
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def _splitext_nodot(basename: str) -> tuple[str, str]:
|
| 646 |
+
root, ext = os.path.splitext(basename)
|
| 647 |
+
if ext:
|
| 648 |
+
ext = ext[1:]
|
| 649 |
+
return root, ext
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/benchmarking.py
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import inspect
|
| 3 |
+
import time
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from functools import cached_property, wraps
|
| 6 |
+
from itertools import chain
|
| 7 |
+
from statistics import median
|
| 8 |
+
from typing import Any, Concatenate, Optional, Union
|
| 9 |
+
from typing_extensions import ParamSpec, Self, TypeVar
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.utils._pytree as pytree
|
| 13 |
+
from torch._dynamo.utils import counters, dynamo_timed
|
| 14 |
+
from torch._inductor.config import use_experimental_benchmarker
|
| 15 |
+
from torch.utils._debug_mode import DebugMode
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
logger = torch._logging.getArtifactLogger(__name__, "benchmarking")
|
| 19 |
+
use_experimental_benchmarker = (
|
| 20 |
+
use_experimental_benchmarker and torch.cuda.is_available()
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
MILLISECONDS_PER_SECOND = 1000
|
| 25 |
+
|
| 26 |
+
P = ParamSpec("P")
|
| 27 |
+
T = TypeVar("T")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def may_distort_benchmarking_result(fn: Callable[..., Any]) -> Callable[..., Any]:
|
| 31 |
+
from torch._inductor import config
|
| 32 |
+
|
| 33 |
+
if config.test_configs.distort_benchmarking_result == "":
|
| 34 |
+
return fn
|
| 35 |
+
|
| 36 |
+
def distort(
|
| 37 |
+
ms: list[float] | tuple[float, ...] | float,
|
| 38 |
+
) -> list[float] | tuple[float, ...] | float:
|
| 39 |
+
if isinstance(ms, (list, tuple)):
|
| 40 |
+
return type(ms)(distort(val) for val in ms) # type: ignore[misc]
|
| 41 |
+
|
| 42 |
+
distort_method = config.test_configs.distort_benchmarking_result
|
| 43 |
+
assert isinstance(ms, float)
|
| 44 |
+
if distort_method == "inverse":
|
| 45 |
+
return 1.0 / ms if ms else 0.0
|
| 46 |
+
elif distort_method == "random":
|
| 47 |
+
import random
|
| 48 |
+
|
| 49 |
+
return random.random()
|
| 50 |
+
else:
|
| 51 |
+
raise RuntimeError(f"Unrecognized distort method {distort_method}")
|
| 52 |
+
|
| 53 |
+
@functools.wraps(fn)
|
| 54 |
+
def wrapper(
|
| 55 |
+
*args: list[Any], **kwargs: dict[str, Any]
|
| 56 |
+
) -> list[float] | tuple[float, ...] | float:
|
| 57 |
+
ms = fn(*args, **kwargs)
|
| 58 |
+
|
| 59 |
+
return distort(ms)
|
| 60 |
+
|
| 61 |
+
return wrapper
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def may_ban_benchmarking() -> None:
|
| 65 |
+
if torch._inductor.config.deterministic:
|
| 66 |
+
raise RuntimeError("""In the deterministic mode of Inductor, we will avoid those
|
| 67 |
+
benchmarkings that would cause non deterministic results. Only benchmarkings in the vetted
|
| 68 |
+
scenarios are allowed. Example include autotuning for triton configs of pointwise kernels.
|
| 69 |
+
|
| 70 |
+
When you see this exception, you can do one of the following two things:
|
| 71 |
+
1. if the benchmarking you are doing does not introduce any non-determinism, you can just
|
| 72 |
+
add is_vetted_benchmarking=True to you benchmark_gpu call. That would solve the issue.
|
| 73 |
+
|
| 74 |
+
2. if the benchmarking you are doing indeed introduces non-determinism, you'll need to disable
|
| 75 |
+
such feature in deterministic mode or find an alternative implementation that is deterministic.
|
| 76 |
+
""")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def time_and_count(
|
| 80 |
+
fn: Callable[Concatenate[Any, P], T],
|
| 81 |
+
) -> Callable[Concatenate[Any, P], T]:
|
| 82 |
+
"""Wraps `fn` with `dynamo_timed` context, and increments the appropriate dynamo
|
| 83 |
+
counters. It is expected that `fn` is a method of `Benchmarker` or one of its
|
| 84 |
+
subclasses; typing limitations prevent us from declaring this directly.
|
| 85 |
+
"""
|
| 86 |
+
|
| 87 |
+
@wraps(fn)
|
| 88 |
+
def wrapper(self: Any, *args: P.args, **kwargs: P.kwargs) -> T:
|
| 89 |
+
fn_qual_name = f"{self.__class__.__name__}.{fn.__name__}"
|
| 90 |
+
counters["inductor"][f"benchmarking.{fn_qual_name}"] += 1
|
| 91 |
+
with dynamo_timed(fn_qual_name, log_pt2_compile_event=False):
|
| 92 |
+
return fn(self, *args, **kwargs)
|
| 93 |
+
|
| 94 |
+
return wrapper
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class Benchmarker:
|
| 98 |
+
"""
|
| 99 |
+
A device-agnostic benchmarking utility for measuring the runtime of
|
| 100 |
+
inductor generated callables.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
def __init__(self: Self) -> None:
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
def infer_device(self, *fn_args: Any, **fn_kwargs: Any) -> torch.device:
|
| 107 |
+
inferred_device: Optional[torch.device] = None
|
| 108 |
+
for arg_or_kwarg in chain(fn_args, fn_kwargs.values()):
|
| 109 |
+
# Some callables take nested structures as arguments so use the
|
| 110 |
+
# flattened form to find any tensors
|
| 111 |
+
for arg_or_kwarg_leaf in pytree.tree_leaves(arg_or_kwarg):
|
| 112 |
+
if not isinstance(arg_or_kwarg_leaf, torch.Tensor):
|
| 113 |
+
continue
|
| 114 |
+
if inferred_device is None:
|
| 115 |
+
inferred_device = arg_or_kwarg_leaf.device
|
| 116 |
+
elif arg_or_kwarg_leaf.device != inferred_device:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
"Can't safely infer the device type of `fn` with multiple device types in `fn_args` and `fn_kwargs`!"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
if inferred_device is None:
|
| 122 |
+
raise ValueError(
|
| 123 |
+
"Can't safely infer the device type of `fn` with no device types"
|
| 124 |
+
" in `fn_args` or `fn_kwargs`. Use a direct benchmarking method instead e.g. "
|
| 125 |
+
"`Benchmarker.benchmark_cpu` or `Benchmarker.benchmark_gpu`."
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
return inferred_device
|
| 129 |
+
|
| 130 |
+
@time_and_count
|
| 131 |
+
def benchmark(
|
| 132 |
+
self: Self,
|
| 133 |
+
fn: Callable[..., Any],
|
| 134 |
+
fn_args: Optional[tuple[Any, ...]] = None,
|
| 135 |
+
fn_kwargs: Optional[dict[str, Any]] = None,
|
| 136 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 137 |
+
**kwargs: Any,
|
| 138 |
+
) -> float:
|
| 139 |
+
"""Benchmark `fn(*fn_args, *fn_kwargs)` and return the runtime, in milliseconds (the
|
| 140 |
+
actual runtime calculation is dictated by the benchmarking implementation, but may be
|
| 141 |
+
one of [mean, median, minimum, etc.]). Functions as a convenience wrapper around
|
| 142 |
+
device-specific implementations, like `benchmark_cpu` and `benchmark_gpu`. Raises
|
| 143 |
+
`ValueError(...)` if we can't safely infer the device type of `fn`; for example,
|
| 144 |
+
if multiple device types are found in `fn_args` and `fn_kwargs`, or if no device
|
| 145 |
+
types are found. To bypass device inference, provide the device to the `device`
|
| 146 |
+
parameter.
|
| 147 |
+
|
| 148 |
+
WARNING: if `fn` mutates `fn_args` or `fn_kwargs`, benchmarking may fail unexpectedly.
|
| 149 |
+
For example, if `fn` clears a mutable object, subsequent invocations of `fn` during
|
| 150 |
+
benchmarking will fail. In such cases, `fn` should handle cloning its arguments internally.
|
| 151 |
+
If device inference is required, `Benchmarker.infer_device` can be used prior to calling
|
| 152 |
+
this method without any arguments for `fn_args` and `fn_kwargs`.
|
| 153 |
+
|
| 154 |
+
Arguments:
|
| 155 |
+
- fn: The function to benchmark.
|
| 156 |
+
- fn_args: The function's arguments.
|
| 157 |
+
- fn_kwargs: The function's kwargs.
|
| 158 |
+
|
| 159 |
+
Keyword Arguments:
|
| 160 |
+
- device: Which device to use for benchmarking. If not provided the device will be attempted
|
| 161 |
+
to be inferred from `fn_args` and `fn_kwargs`.
|
| 162 |
+
- **kwargs: The benchmarking implementation's kwargs.
|
| 163 |
+
|
| 164 |
+
Returns:
|
| 165 |
+
- The runtime of `fn(*fn_args, **fn_kwargs)`, in milliseconds.
|
| 166 |
+
"""
|
| 167 |
+
inferred_device: Optional[torch.device] = None
|
| 168 |
+
if device is not None:
|
| 169 |
+
inferred_device = (
|
| 170 |
+
torch.device(device) if isinstance(device, str) else device
|
| 171 |
+
)
|
| 172 |
+
else:
|
| 173 |
+
if fn_args is None and fn_kwargs is None:
|
| 174 |
+
raise ValueError(
|
| 175 |
+
"`fn_args` and `fn_kwargs` cannot both be None if `device` is not provided."
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
fn_args = fn_args or tuple()
|
| 179 |
+
fn_kwargs = fn_kwargs or {}
|
| 180 |
+
inferred_device = self.infer_device(*fn_args, **fn_kwargs)
|
| 181 |
+
|
| 182 |
+
assert isinstance(inferred_device, torch.device)
|
| 183 |
+
|
| 184 |
+
fn_args = fn_args or tuple()
|
| 185 |
+
fn_kwargs = fn_kwargs or {}
|
| 186 |
+
|
| 187 |
+
# No need to wrap if the callable takes no arguments
|
| 188 |
+
if len(fn_args) == 0 and len(fn_kwargs) == 0:
|
| 189 |
+
_callable = fn
|
| 190 |
+
else:
|
| 191 |
+
_callable = lambda: fn(*fn_args, **fn_kwargs) # noqa: E731
|
| 192 |
+
|
| 193 |
+
# Surfacing all kernels during autotuning is super noisy; filtering these out.
|
| 194 |
+
with DebugMode._benchmarking_inductor():
|
| 195 |
+
if inferred_device == torch.device("cpu"):
|
| 196 |
+
return self.benchmark_cpu(_callable, **kwargs)
|
| 197 |
+
# TODO(nmacchioni): For non-CPU functions we default to using the GPU-specific benchmarking
|
| 198 |
+
# implementation which was written specifically with CUDA devices in mind, we may want to
|
| 199 |
+
# explore alternate implementations for other device types.
|
| 200 |
+
return self.benchmark_gpu(_callable, **kwargs)
|
| 201 |
+
|
| 202 |
+
@time_and_count
|
| 203 |
+
def benchmark_cpu(
|
| 204 |
+
self: Self, _callable: Callable[[], Any], warmup: int = 20, rep: int = 100
|
| 205 |
+
) -> float:
|
| 206 |
+
"""Benchmark the CPU callable, `_callable`, and return the median runtime,
|
| 207 |
+
in milliseconds.
|
| 208 |
+
|
| 209 |
+
Arguments:
|
| 210 |
+
- _callable: The CPU callable to benchmark.
|
| 211 |
+
|
| 212 |
+
Keyword Arguments:
|
| 213 |
+
- warmup: Optionally, the duration, in milliseconds, to run `_callable`
|
| 214 |
+
before benchmarking starts.
|
| 215 |
+
- rep: Optionally, the duration, in milliseconds, to run `_callable`
|
| 216 |
+
during benchmarking.
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
- The median runtime of `_callable`, in milliseconds.
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
def run_for(ms: int) -> list[float]:
|
| 223 |
+
timings = []
|
| 224 |
+
run_start_t = time.perf_counter()
|
| 225 |
+
while True:
|
| 226 |
+
start_t = time.perf_counter()
|
| 227 |
+
_callable()
|
| 228 |
+
end_t = time.perf_counter()
|
| 229 |
+
timings.append((end_t - start_t) * MILLISECONDS_PER_SECOND)
|
| 230 |
+
if ((end_t - run_start_t) * MILLISECONDS_PER_SECOND) > ms:
|
| 231 |
+
break
|
| 232 |
+
return timings
|
| 233 |
+
|
| 234 |
+
run_for(warmup)
|
| 235 |
+
return median(run_for(rep))
|
| 236 |
+
|
| 237 |
+
@time_and_count
|
| 238 |
+
def benchmark_gpu(self: Self, *args: Any, **kwargs: Any) -> float:
|
| 239 |
+
raise NotImplementedError
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class TritonBenchmarker(Benchmarker):
|
| 243 |
+
@cached_property
|
| 244 |
+
def triton_do_bench(self: Self) -> Callable[..., Any]:
|
| 245 |
+
"""Lazily import Triton's `do_bench`."""
|
| 246 |
+
try:
|
| 247 |
+
from triton.testing import do_bench
|
| 248 |
+
except ImportError as e:
|
| 249 |
+
raise NotImplementedError("requires Triton") from e
|
| 250 |
+
return do_bench
|
| 251 |
+
|
| 252 |
+
@may_distort_benchmarking_result
|
| 253 |
+
@time_and_count
|
| 254 |
+
# pyrefly: ignore [bad-override]
|
| 255 |
+
def benchmark_gpu(
|
| 256 |
+
self: Self,
|
| 257 |
+
_callable: Callable[[], Any],
|
| 258 |
+
is_vetted_benchmarking: bool = False,
|
| 259 |
+
**kwargs: Any,
|
| 260 |
+
) -> float:
|
| 261 |
+
"""Benchmark the GPU callable, `_callable`, and return the runtime, in milliseconds.
|
| 262 |
+
|
| 263 |
+
Arguments:
|
| 264 |
+
- _callable: The GPU callable to benchmark.
|
| 265 |
+
|
| 266 |
+
Keyword Arguments:
|
| 267 |
+
- quantiles: Optionally, a tuple of floats denoting the requested quantiles.
|
| 268 |
+
- return_mode: Optionally, the requested return mode. Currently, Triton's
|
| 269 |
+
`do_bench` supports min, max, mean, and median return modes.
|
| 270 |
+
- **kwargs: Additional kwargs passed to Triton's `do_bench`.
|
| 271 |
+
|
| 272 |
+
Returns:
|
| 273 |
+
- The runtime of `callable`, in milliseconds. If `kwargs["quantiles"]` is specified,
|
| 274 |
+
this is the first requested quantile. Else, if `kwargs["return_mode"]` is specified,
|
| 275 |
+
this is the requested return mode. Otherwise, this is the median.
|
| 276 |
+
"""
|
| 277 |
+
if not is_vetted_benchmarking:
|
| 278 |
+
may_ban_benchmarking()
|
| 279 |
+
|
| 280 |
+
do_bench_params = inspect.signature(self.triton_do_bench).parameters
|
| 281 |
+
for kwarg in list(kwargs.keys()):
|
| 282 |
+
if kwarg not in do_bench_params:
|
| 283 |
+
del kwargs[kwarg]
|
| 284 |
+
if "quantiles" in kwargs:
|
| 285 |
+
return self.triton_do_bench(_callable, **kwargs)[0]
|
| 286 |
+
elif "return_mode" in kwargs:
|
| 287 |
+
return self.triton_do_bench(_callable, **kwargs)
|
| 288 |
+
return self.triton_do_bench(_callable, **kwargs, return_mode="median")
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class InductorBenchmarker(TritonBenchmarker): # noqa: docstring_linter
|
| 292 |
+
@cached_property
|
| 293 |
+
def L2_cache_size(self: Self) -> int:
|
| 294 |
+
"""Get the L2 cache size, in bytes, of the current device."""
|
| 295 |
+
device = torch.cuda.current_device()
|
| 296 |
+
props = torch.cuda.get_device_properties(device)
|
| 297 |
+
return props.L2_cache_size
|
| 298 |
+
|
| 299 |
+
def get_event_pairs(
|
| 300 |
+
self: Self, iters: int
|
| 301 |
+
) -> list[tuple[torch.cuda.Event, torch.cuda.Event]]:
|
| 302 |
+
"""Get `iters` pairs of CUDA events."""
|
| 303 |
+
return [
|
| 304 |
+
(
|
| 305 |
+
torch.cuda.Event(enable_timing=True),
|
| 306 |
+
torch.cuda.Event(enable_timing=True),
|
| 307 |
+
)
|
| 308 |
+
for _ in range(iters)
|
| 309 |
+
]
|
| 310 |
+
|
| 311 |
+
def get_event_pairs_min_timing(
|
| 312 |
+
self: Self, event_pairs: list[tuple[torch.cuda.Event, torch.cuda.Event]]
|
| 313 |
+
) -> float:
|
| 314 |
+
"""Get the minimum timing, in milliseconds, for a group of CUDA event pairs."""
|
| 315 |
+
return min(
|
| 316 |
+
[
|
| 317 |
+
start_event.elapsed_time(end_event)
|
| 318 |
+
for start_event, end_event in event_pairs
|
| 319 |
+
]
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
@may_distort_benchmarking_result
|
| 323 |
+
@time_and_count
|
| 324 |
+
def benchmark_gpu( # type: ignore[override]
|
| 325 |
+
self: Self,
|
| 326 |
+
_callable: Callable[[], Any],
|
| 327 |
+
estimation_iters: int = 5,
|
| 328 |
+
memory_warmup_iters: int = 100,
|
| 329 |
+
benchmark_iters: int = 100,
|
| 330 |
+
max_benchmark_duration: int = 25,
|
| 331 |
+
return_mode: str = "min",
|
| 332 |
+
grad_to_none: list[torch.Tensor] | None = None,
|
| 333 |
+
is_vetted_benchmarking: bool = False,
|
| 334 |
+
**kwargs: Any,
|
| 335 |
+
) -> float | list[float]:
|
| 336 |
+
"""Benchmark a GPU callable using a custom benchmarking implementation.
|
| 337 |
+
|
| 338 |
+
Arguments:
|
| 339 |
+
- _callable: The callable to benchmark.
|
| 340 |
+
|
| 341 |
+
Keyword Arguments:
|
| 342 |
+
- estimation_iters: Optionally, the number of iterations to run `_callable`
|
| 343 |
+
during runtime estimation.
|
| 344 |
+
- memory_warmup_iters: Optionally, the number of iterations to flush the L2
|
| 345 |
+
cache before starting benchmarking.
|
| 346 |
+
- benchmark_iters: Optionally, the number of iterations to run `_callable`
|
| 347 |
+
during the benchmarking.
|
| 348 |
+
- max_benchmark_duration: Optionally, the maximum duration of the benchmarking,
|
| 349 |
+
in milliseconds. An estimated duration is calculated based on the values
|
| 350 |
+
of `memory_warmup_iters` and `benchmark_iters`, along with the estimated
|
| 351 |
+
runtime of `_callable` and various other factors, and we then shrink
|
| 352 |
+
`benchmark_iters` to fit in the allotted maximum duration.
|
| 353 |
+
- return_mode: Return mode for benchmark results. Options are "min" (default),
|
| 354 |
+
"all" (returns all measurements).
|
| 355 |
+
- grad_to_none: Optionally, a list of tensors whose gradients should be cleared
|
| 356 |
+
before each benchmark iteration.
|
| 357 |
+
- is_vetted_benchmarking: in deterministic mode, we only allow
|
| 358 |
+
benchmarking in vetted cases.
|
| 359 |
+
- **kwargs: Additional kwargs that may be passed to the fallback.
|
| 360 |
+
|
| 361 |
+
Returns:
|
| 362 |
+
- If return_mode="min": The minimum runtime of `_callable`, in milliseconds.
|
| 363 |
+
- If return_mode="all": List of all runtime measurements, in milliseconds.
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
if not is_vetted_benchmarking:
|
| 367 |
+
may_ban_benchmarking()
|
| 368 |
+
|
| 369 |
+
# we don't want any outside errors propagating into benchmarking
|
| 370 |
+
torch.cuda.synchronize()
|
| 371 |
+
|
| 372 |
+
# warmup `_callable` (and catches any failures in the process)
|
| 373 |
+
_callable()
|
| 374 |
+
torch.cuda.synchronize()
|
| 375 |
+
|
| 376 |
+
# see https://github.com/triton-lang/triton/pull/840 for why `dtype=torch.int`
|
| 377 |
+
buffer = torch.empty(self.L2_cache_size // 4, dtype=torch.int, device="cuda")
|
| 378 |
+
buffer.zero_()
|
| 379 |
+
|
| 380 |
+
# estimate the runtime of `_callable`
|
| 381 |
+
event_pairs = self.get_event_pairs(estimation_iters)
|
| 382 |
+
for start_event, end_event in event_pairs:
|
| 383 |
+
# Clear gradients before timing (matches triton.testing.do_bench)
|
| 384 |
+
if grad_to_none is not None:
|
| 385 |
+
for x in grad_to_none:
|
| 386 |
+
x.grad = None
|
| 387 |
+
buffer.zero_()
|
| 388 |
+
start_event.record()
|
| 389 |
+
_callable()
|
| 390 |
+
end_event.record()
|
| 391 |
+
torch.cuda.synchronize()
|
| 392 |
+
estimated_timing = self.get_event_pairs_min_timing(event_pairs)
|
| 393 |
+
|
| 394 |
+
# adjust `benchmark_iters` to fit in the maximum benchmarking duration
|
| 395 |
+
benchmark_iters = max(
|
| 396 |
+
min(benchmark_iters, int(max_benchmark_duration // estimated_timing)), 1
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
# do the memory warmup
|
| 400 |
+
for _ in range(memory_warmup_iters):
|
| 401 |
+
buffer.zero_()
|
| 402 |
+
|
| 403 |
+
# benchmark `_callable`
|
| 404 |
+
event_pairs = self.get_event_pairs(benchmark_iters)
|
| 405 |
+
for start_event, end_event in event_pairs:
|
| 406 |
+
# Clear gradients before timing (matches triton.testing.do_bench)
|
| 407 |
+
if grad_to_none is not None:
|
| 408 |
+
for x in grad_to_none:
|
| 409 |
+
x.grad = None
|
| 410 |
+
buffer.zero_()
|
| 411 |
+
start_event.record()
|
| 412 |
+
_callable()
|
| 413 |
+
end_event.record()
|
| 414 |
+
torch.cuda.synchronize()
|
| 415 |
+
|
| 416 |
+
# explicitly delete the buffer, sometimes helps memory
|
| 417 |
+
# footprint metrics in OSS Inductor performance benchmarks
|
| 418 |
+
del buffer
|
| 419 |
+
|
| 420 |
+
# Return based on the requested mode
|
| 421 |
+
if return_mode == "all":
|
| 422 |
+
# Get all timings from event pairs
|
| 423 |
+
all_timings = [
|
| 424 |
+
start_event.elapsed_time(end_event)
|
| 425 |
+
for start_event, end_event in event_pairs
|
| 426 |
+
]
|
| 427 |
+
return all_timings
|
| 428 |
+
elif return_mode == "min":
|
| 429 |
+
benchmarked_timing = self.get_event_pairs_min_timing(event_pairs)
|
| 430 |
+
# return the minimum of `estimated_timing` and `benchmarked_timing`,
|
| 431 |
+
# we just want the minimum timing overall so we might as well check both
|
| 432 |
+
return min(estimated_timing, benchmarked_timing)
|
| 433 |
+
else:
|
| 434 |
+
raise ValueError(
|
| 435 |
+
f"Unsupported return_mode: {return_mode}. Use 'min' or 'all'."
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
benchmarker = (
|
| 440 |
+
InductorBenchmarker() if use_experimental_benchmarker else TritonBenchmarker()
|
| 441 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/cache_dir_utils.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import getpass
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import tempfile
|
| 5 |
+
from collections.abc import Generator
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
|
| 8 |
+
from torch._environment import is_fbcode
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Factoring out to file without torch dependencies
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def cache_dir() -> str:
|
| 15 |
+
cache_dir = os.environ.get("TORCHINDUCTOR_CACHE_DIR")
|
| 16 |
+
if cache_dir is None:
|
| 17 |
+
os.environ["TORCHINDUCTOR_CACHE_DIR"] = cache_dir = default_cache_dir()
|
| 18 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 19 |
+
return cache_dir
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def default_cache_dir() -> str:
|
| 23 |
+
sanitized_username = re.sub(r'[\\/:*?"<>|]', "_", getpass.getuser())
|
| 24 |
+
return os.path.join(
|
| 25 |
+
tempfile.gettempdir() if not is_fbcode() else "/var/tmp",
|
| 26 |
+
"torchinductor_" + sanitized_username,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def triton_cache_dir(device: int) -> str:
|
| 31 |
+
if (directory := os.getenv("TRITON_CACHE_DIR")) is not None:
|
| 32 |
+
return directory
|
| 33 |
+
return os.path.join(
|
| 34 |
+
cache_dir(),
|
| 35 |
+
"triton",
|
| 36 |
+
str(device),
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@contextmanager
|
| 41 |
+
def temporary_cache_dir(directory: str) -> Generator[None, None, None]:
|
| 42 |
+
from torch._inductor.utils import clear_caches
|
| 43 |
+
|
| 44 |
+
original = os.environ.get("TORCHINDUCTOR_CACHE_DIR")
|
| 45 |
+
os.environ["TORCHINDUCTOR_CACHE_DIR"] = directory
|
| 46 |
+
try:
|
| 47 |
+
clear_caches()
|
| 48 |
+
yield
|
| 49 |
+
finally:
|
| 50 |
+
clear_caches()
|
| 51 |
+
if original is None:
|
| 52 |
+
del os.environ["TORCHINDUCTOR_CACHE_DIR"]
|
| 53 |
+
else:
|
| 54 |
+
os.environ["TORCHINDUCTOR_CACHE_DIR"] = original
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/__init__.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from threading import Lock
|
| 2 |
+
|
| 3 |
+
from . import config, interfaces as intfs, locks
|
| 4 |
+
from .context import IsolationSchema, SelectedCompileContext, SelectedRuntimeContext
|
| 5 |
+
from .exceptions import (
|
| 6 |
+
CacheError,
|
| 7 |
+
CustomParamsEncoderRequiredError,
|
| 8 |
+
CustomResultDecoderRequiredError,
|
| 9 |
+
CustomResultEncoderRequiredError,
|
| 10 |
+
DeterministicCachingDisabledError,
|
| 11 |
+
DeterministicCachingIMCDumpConflictError,
|
| 12 |
+
DeterministicCachingInvalidConfigurationError,
|
| 13 |
+
DeterministicCachingRequiresStrongConsistencyError,
|
| 14 |
+
FileLockTimeoutError,
|
| 15 |
+
KeyEncodingError,
|
| 16 |
+
KeyPicklingError,
|
| 17 |
+
LockTimeoutError,
|
| 18 |
+
StrictDeterministicCachingKeyNotFoundError,
|
| 19 |
+
SystemError,
|
| 20 |
+
UserError,
|
| 21 |
+
ValueDecodingError,
|
| 22 |
+
ValueEncodingError,
|
| 23 |
+
ValuePicklingError,
|
| 24 |
+
ValueUnPicklingError,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# fast cache; does not bother supporting deterministic caching, and is essentially
|
| 29 |
+
# a memoized on-disk cache. use when deterministic caching is not required
|
| 30 |
+
fcache: intfs._CacheIntf = intfs._FastCacheIntf()
|
| 31 |
+
# deterministic cache; slower than fcache but provides deterministic guarantees.
|
| 32 |
+
# use when deterministic caching is absolutely required, as this will raise
|
| 33 |
+
# an exception if use is attempted when deterministic caching is disabled
|
| 34 |
+
dcache: intfs._CacheIntf = intfs._DeterministicCacheIntf()
|
| 35 |
+
# inductor cache; defaults to the deterministic cache if deterministic caching
|
| 36 |
+
# is enabled, otherwise uses the fast cache. use when you would like deterministic
|
| 37 |
+
# caching but are okay with non-deterministic caching if deterministic caching is disabled
|
| 38 |
+
icache: intfs._CacheIntf = (
|
| 39 |
+
dcache if config.IS_DETERMINISTIC_CACHING_ENABLED() else fcache
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
__all__ = [
|
| 43 |
+
"SelectedCompileContext",
|
| 44 |
+
"SelectedRuntimeContext",
|
| 45 |
+
"IsolationSchema",
|
| 46 |
+
"CacheError",
|
| 47 |
+
"SystemError",
|
| 48 |
+
"UserError",
|
| 49 |
+
"LockTimeoutError",
|
| 50 |
+
"FileLockTimeoutError",
|
| 51 |
+
"KeyEncodingError",
|
| 52 |
+
"KeyPicklingError",
|
| 53 |
+
"ValueEncodingError",
|
| 54 |
+
"ValuePicklingError",
|
| 55 |
+
"ValueDecodingError",
|
| 56 |
+
"ValueUnPicklingError",
|
| 57 |
+
"CustomParamsEncoderRequiredError",
|
| 58 |
+
"CustomResultEncoderRequiredError",
|
| 59 |
+
"CustomResultDecoderRequiredError",
|
| 60 |
+
"DeterministicCachingDisabledError",
|
| 61 |
+
"DeterministicCachingRequiresStrongConsistencyError",
|
| 62 |
+
"StrictDeterministicCachingKeyNotFoundError",
|
| 63 |
+
"DeterministicCachingInvalidConfigurationError",
|
| 64 |
+
"DeterministicCachingIMCDumpConflictError",
|
| 65 |
+
"fcache",
|
| 66 |
+
"dcache",
|
| 67 |
+
"icache",
|
| 68 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/config.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from functools import cache, partial
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch._environment import is_fbcode
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@cache
|
| 10 |
+
def _env_var_config(env_var: str, default: bool) -> bool:
|
| 11 |
+
if (env_val := os.environ.get(env_var)) is not None:
|
| 12 |
+
return env_val == "1"
|
| 13 |
+
return default
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@cache
|
| 17 |
+
def _versioned_config(
|
| 18 |
+
jk_name: str,
|
| 19 |
+
this_version: int,
|
| 20 |
+
oss_default: bool,
|
| 21 |
+
env_var_override: str | None = None,
|
| 22 |
+
) -> bool:
|
| 23 |
+
"""
|
| 24 |
+
A versioned configuration utility that determines boolean settings based on:
|
| 25 |
+
1. Environment variable override (highest priority)
|
| 26 |
+
2. JustKnobs version comparison in fbcode environments
|
| 27 |
+
3. OSS default fallback
|
| 28 |
+
|
| 29 |
+
This function enables gradual rollouts of features in fbcode by comparing
|
| 30 |
+
a local version against a JustKnobs-controlled remote version, while
|
| 31 |
+
allowing environment variable overrides for testing and OSS defaults
|
| 32 |
+
for non-fbcode environments.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
jk_name: JustKnobs key name (e.g., "pytorch/inductor:feature_version")
|
| 36 |
+
this_version: Local version number to compare against JustKnobs version
|
| 37 |
+
oss_default: Default value to use in non-fbcode environments
|
| 38 |
+
env_var_override: Optional environment variable name that, when set,
|
| 39 |
+
overrides all other logic
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
bool: Configuration value determined by the priority order above
|
| 43 |
+
"""
|
| 44 |
+
if (
|
| 45 |
+
env_var_override
|
| 46 |
+
and (env_var_value := os.environ.get(env_var_override)) is not None
|
| 47 |
+
):
|
| 48 |
+
return env_var_value == "1"
|
| 49 |
+
elif is_fbcode():
|
| 50 |
+
# this method returns 0 on failure, which we should check for specifically.
|
| 51 |
+
# in the case of JK failure, the safe bet is to simply disable the config
|
| 52 |
+
jk_version: int = torch._utils_internal.justknobs_getval_int(jk_name)
|
| 53 |
+
return (this_version >= jk_version) and (jk_version != 0)
|
| 54 |
+
return oss_default
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# toggles the entire caching module, but only when calling through the
|
| 58 |
+
# public facing interfaces. get/insert operations become no-ops in the sense
|
| 59 |
+
# that get will always miss and insert will never insert; record becomes a
|
| 60 |
+
# no-op in the sense that the function will always be called and the cache
|
| 61 |
+
# will never be accessed
|
| 62 |
+
_CACHING_MODULE_VERSION: int = 0
|
| 63 |
+
_CACHING_MODULE_VERSION_JK: str = "pytorch/inductor:caching_module_version"
|
| 64 |
+
_CACHING_MODULE_OSS_DEFAULT: bool = False
|
| 65 |
+
_CACHING_MODULE_ENV_VAR_OVERRIDE: str = "TORCHINDUCTOR_ENABLE_CACHING_MODULE"
|
| 66 |
+
IS_CACHING_MODULE_ENABLED: Callable[[], bool] = partial(
|
| 67 |
+
_versioned_config,
|
| 68 |
+
_CACHING_MODULE_VERSION_JK,
|
| 69 |
+
_CACHING_MODULE_VERSION,
|
| 70 |
+
_CACHING_MODULE_OSS_DEFAULT,
|
| 71 |
+
_CACHING_MODULE_ENV_VAR_OVERRIDE,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# toggles the deterministic caching interface. silently disabling deterministic
|
| 76 |
+
# caching (i.e. by mimicking the functionality of IS_CACHING_MODULE_ENABLED) can
|
| 77 |
+
# be problematic if the user is directly calling the deterministic caching interface
|
| 78 |
+
# (for example, if they were to interface with dcache instead of icache). instead, if
|
| 79 |
+
# the user tries to use the deterministic caching interface while it is disabled we
|
| 80 |
+
# will simply throw DeterministicCachingDisabledError
|
| 81 |
+
_DETERMINISTIC_CACHING_VERSION: int = 0
|
| 82 |
+
_DETERMINISTIC_CACHING_VERSION_JK: str = (
|
| 83 |
+
"pytorch/inductor:deterministic_caching_version"
|
| 84 |
+
)
|
| 85 |
+
_DETERMINISTIC_CACHING_OSS_DEFAULT: bool = False
|
| 86 |
+
_DETERMINISTIC_CACHING_ENV_VAR_OVERRIDE: str = (
|
| 87 |
+
"TORCHINDUCTOR_ENABLE_DETERMINISTIC_CACHING"
|
| 88 |
+
)
|
| 89 |
+
IS_DETERMINISTIC_CACHING_ENABLED: Callable[[], bool] = partial(
|
| 90 |
+
_versioned_config,
|
| 91 |
+
_DETERMINISTIC_CACHING_VERSION_JK,
|
| 92 |
+
_DETERMINISTIC_CACHING_VERSION,
|
| 93 |
+
_DETERMINISTIC_CACHING_OSS_DEFAULT,
|
| 94 |
+
_DETERMINISTIC_CACHING_ENV_VAR_OVERRIDE,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
# enabling strictly pre-populated determinism forces the deterministic caching
|
| 98 |
+
# interface to pull from and only from a pre-populated in-memory cache. this
|
| 99 |
+
# in-memory cache gets pre-populated from a file path that is specified by
|
| 100 |
+
# environment variable "TORCHINDUCTOR_PRE_POPULATE_DETERMINISTIC_CACHE".
|
| 101 |
+
# coincidentally, the deterministic caching interface will dump its in-memory
|
| 102 |
+
# cache to disk on program exit (check the logs for the exact file path) which
|
| 103 |
+
# can be used as a drop-in solution for pre-population on subsequent runs. if
|
| 104 |
+
# strictly pre-populated determinism is enabled and a key is encountered which
|
| 105 |
+
# is not covered by the pre-populated in-memory cache an exception,
|
| 106 |
+
# StrictDeterministicCachingKeyNotFoundError, will be raised
|
| 107 |
+
STRICTLY_PRE_POPULATED_DETERMINISM: bool = _env_var_config(
|
| 108 |
+
"TORCHINDUCTOR_STRICTLY_PRE_POPULATED_DETERMINISM",
|
| 109 |
+
default=False,
|
| 110 |
+
)
|
| 111 |
+
# similar to strictly pre-populated determinism, except that any key can either
|
| 112 |
+
# be in the pre-populated in-memory cache or the on-disk/remote cache (depending
|
| 113 |
+
# on whether or not local/global determinism is enabled).
|
| 114 |
+
STRICTLY_CACHED_DETERMINISM: bool = _env_var_config(
|
| 115 |
+
"TORCHINDUCTOR_STRICTLY_CACHED_DETERMINISM",
|
| 116 |
+
default=False,
|
| 117 |
+
)
|
| 118 |
+
# local determinism ensures that caching is deterministic on a single machine,
|
| 119 |
+
# hence an on-disk cache is used for synchronization of results
|
| 120 |
+
LOCAL_DETERMINISM: bool = _env_var_config(
|
| 121 |
+
"TORCHINDUCTOR_LOCAL_DETERMINISM", default=(not is_fbcode())
|
| 122 |
+
)
|
| 123 |
+
# global determinism ensures that caching is deterministic across any/all machines,
|
| 124 |
+
# hence a remote cache (with strong consistency!) is used for synchronization of results
|
| 125 |
+
GLOBAL_DETERMINISM: bool = _env_var_config(
|
| 126 |
+
"TORCHINDUCTOR_GLOBAL_DETERMINISM", default=is_fbcode()
|
| 127 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/context.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Context management for PyTorch Inductor runtime caching.
|
| 2 |
+
|
| 3 |
+
This module provides context classes for collecting configuration and environment
|
| 4 |
+
information used in caching decisions for PyTorch's Inductor runtime.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
from abc import ABC, abstractmethod
|
| 9 |
+
from base64 import b64encode
|
| 10 |
+
from collections.abc import Sequence
|
| 11 |
+
from functools import cache
|
| 12 |
+
from hashlib import sha256
|
| 13 |
+
from typing import Any
|
| 14 |
+
from typing_extensions import override, TypedDict
|
| 15 |
+
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class _Context(ABC):
|
| 20 |
+
"""Abstract base class for context providers.
|
| 21 |
+
|
| 22 |
+
Context providers collect specific configuration and environment information
|
| 23 |
+
that affects compilation and runtime behavior.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
@abstractmethod
|
| 28 |
+
def forms_of_context() -> Sequence[str]:
|
| 29 |
+
"""Return a sequence of context form names provided by this context class.
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
A sequence of strings representing the available context forms.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class _RuntimeContext(_Context):
|
| 37 |
+
"""Context provider for runtime configuration and environment settings.
|
| 38 |
+
|
| 39 |
+
Collects configuration settings that affect runtime behavior but not
|
| 40 |
+
compilation, such as Inductor configs, determinism settings, and CUDA
|
| 41 |
+
matmul precision configurations.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
@override
|
| 45 |
+
@staticmethod
|
| 46 |
+
def forms_of_context() -> Sequence[str]:
|
| 47 |
+
"""Return the runtime context forms provided by this class.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
A sequence containing the available runtime context forms:
|
| 51 |
+
- "inductor_configs": PyTorch Inductor configuration settings
|
| 52 |
+
- "torch_determinism_configs": Deterministic algorithm settings
|
| 53 |
+
- "cuda_matmul_precision_configs": CUDA matrix multiplication precision settings
|
| 54 |
+
"""
|
| 55 |
+
return (
|
| 56 |
+
"inductor_configs",
|
| 57 |
+
"torch_determinism_configs",
|
| 58 |
+
"cuda_matmul_precision_configs",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def inductor_configs() -> dict[str, Any]:
|
| 63 |
+
"""Get portable Inductor configuration settings.
|
| 64 |
+
|
| 65 |
+
Returns:
|
| 66 |
+
A dictionary containing Inductor configuration settings,
|
| 67 |
+
including private configs.
|
| 68 |
+
"""
|
| 69 |
+
from torch._inductor import config
|
| 70 |
+
|
| 71 |
+
return config.save_config_portable(ignore_private_configs=False)
|
| 72 |
+
|
| 73 |
+
@staticmethod
|
| 74 |
+
def torch_determinism_configs() -> dict[str, Any]:
|
| 75 |
+
"""Get PyTorch deterministic algorithm configuration settings.
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
A dictionary containing deterministic algorithm settings:
|
| 79 |
+
- Whether deterministic algorithms are enabled
|
| 80 |
+
- Whether deterministic algorithm warnings are enabled
|
| 81 |
+
- Fill uninitialized memory setting
|
| 82 |
+
"""
|
| 83 |
+
return {
|
| 84 |
+
"torch.are_deterministic_algorithms_enabled": torch.are_deterministic_algorithms_enabled(),
|
| 85 |
+
"torch.is_deterministic_algorithms_warn_only_enabled": (
|
| 86 |
+
torch.is_deterministic_algorithms_warn_only_enabled()
|
| 87 |
+
),
|
| 88 |
+
"torch.utils.deterministic.fill_uninitialized_memory": (
|
| 89 |
+
torch.utils.deterministic.fill_uninitialized_memory # type: ignore[attr-defined]
|
| 90 |
+
),
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def cuda_matmul_precision_configs() -> dict[str, Any]:
|
| 95 |
+
"""Get CUDA matrix multiplication precision configuration settings.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
A dictionary containing CUDA matmul precision settings:
|
| 99 |
+
- FP32 precision setting
|
| 100 |
+
- FP16 reduced precision reduction allowance
|
| 101 |
+
- BF16 reduced precision reduction allowance
|
| 102 |
+
"""
|
| 103 |
+
return {
|
| 104 |
+
"torch.backends.cuda.matmul.fp32_precision": torch.backends.cuda.matmul.fp32_precision,
|
| 105 |
+
"torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction": (
|
| 106 |
+
torch.backends.cuda.matmul.allow_fp16_reduced_precision_reduction
|
| 107 |
+
),
|
| 108 |
+
"torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction": (
|
| 109 |
+
torch.backends.cuda.matmul.allow_bf16_reduced_precision_reduction
|
| 110 |
+
),
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class _CompileContext(_Context):
|
| 115 |
+
"""Context provider for compilation-related configuration and environment settings.
|
| 116 |
+
|
| 117 |
+
Collects information that affects compilation behavior, such as PyTorch and Triton
|
| 118 |
+
versions, runtime environment, and accelerator properties.
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
@override
|
| 122 |
+
@staticmethod
|
| 123 |
+
def forms_of_context() -> Sequence[str]:
|
| 124 |
+
"""Return the compile context forms provided by this class.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
A sequence containing the available compile context forms:
|
| 128 |
+
- "torch_version_hash": PyTorch version hash
|
| 129 |
+
- "triton_version_hash": Triton version hash (if available)
|
| 130 |
+
- "runtime": Runtime type (CUDA/HIP/None)
|
| 131 |
+
- "runtime_version": Runtime version string
|
| 132 |
+
- "accelerator_properties": GPU/accelerator properties
|
| 133 |
+
"""
|
| 134 |
+
return (
|
| 135 |
+
"torch_version_hash",
|
| 136 |
+
"triton_version_hash",
|
| 137 |
+
"runtime",
|
| 138 |
+
"runtime_version",
|
| 139 |
+
"accelerator_properties",
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
@cache
|
| 143 |
+
@staticmethod
|
| 144 |
+
def torch_version_hash() -> str:
|
| 145 |
+
"""Get base64-encoded PyTorch version hash.
|
| 146 |
+
|
| 147 |
+
Returns:
|
| 148 |
+
A base64-encoded string representing the PyTorch version hash.
|
| 149 |
+
"""
|
| 150 |
+
from torch._inductor.codecache import torch_key
|
| 151 |
+
|
| 152 |
+
return b64encode(torch_key()).decode()
|
| 153 |
+
|
| 154 |
+
@cache
|
| 155 |
+
@staticmethod
|
| 156 |
+
def triton_version_hash() -> str | None:
|
| 157 |
+
"""Get Triton version key if Triton is available.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
Triton version key if Triton is available, None otherwise.
|
| 161 |
+
"""
|
| 162 |
+
from torch._inductor.runtime.triton_compat import HAS_TRITON, triton_key
|
| 163 |
+
|
| 164 |
+
return triton_key() if HAS_TRITON else None
|
| 165 |
+
|
| 166 |
+
@cache
|
| 167 |
+
@staticmethod
|
| 168 |
+
def runtime() -> str | None:
|
| 169 |
+
"""Determine the runtime type based on available backends.
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
"CUDA" if CUDA is available, "HIP" if HIP is available, None otherwise.
|
| 173 |
+
"""
|
| 174 |
+
return "CUDA" if torch.version.cuda else "HIP" if torch.version.hip else None
|
| 175 |
+
|
| 176 |
+
@cache
|
| 177 |
+
@staticmethod
|
| 178 |
+
def runtime_version() -> str | None:
|
| 179 |
+
"""Get the version string for the detected runtime.
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
Version string for the current runtime (CUDA or HIP), or None if
|
| 183 |
+
no supported runtime is detected.
|
| 184 |
+
"""
|
| 185 |
+
return {
|
| 186 |
+
"CUDA": torch.version.cuda,
|
| 187 |
+
"HIP": torch.version.hip,
|
| 188 |
+
}.get(_CompileContext.runtime()) # type: ignore[arg-type]
|
| 189 |
+
|
| 190 |
+
@cache
|
| 191 |
+
@staticmethod
|
| 192 |
+
def accelerator_properties() -> str | None:
|
| 193 |
+
"""Get string representation of CUDA device properties.
|
| 194 |
+
|
| 195 |
+
Returns:
|
| 196 |
+
String representation of CUDA device properties if a runtime is
|
| 197 |
+
available, None otherwise.
|
| 198 |
+
"""
|
| 199 |
+
return (
|
| 200 |
+
repr(torch.cuda.get_device_properties())
|
| 201 |
+
if _CompileContext.runtime() and torch.cuda.is_available()
|
| 202 |
+
else None
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class SelectedRuntimeContext(TypedDict):
|
| 207 |
+
inductor_configs: bool
|
| 208 |
+
torch_determinism_configs: bool
|
| 209 |
+
cuda_matmul_precision_configs: bool
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class SelectedCompileContext(TypedDict):
|
| 213 |
+
torch_version_hash: bool
|
| 214 |
+
triton_version_hash: bool
|
| 215 |
+
runtime: bool
|
| 216 |
+
runtime_version: bool
|
| 217 |
+
accelerator_properties: bool
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class IsolationSchema(TypedDict):
|
| 221 |
+
"""Schema for specifying which context forms to include in cache isolation.
|
| 222 |
+
|
| 223 |
+
Attributes:
|
| 224 |
+
runtime_context: Either True (include all runtime context), False (exclude all),
|
| 225 |
+
or a SelectedRuntimeContext dict specifying which forms to include.
|
| 226 |
+
compile_context: Either True (include all compile context), False (exclude all),
|
| 227 |
+
or a SelectedCompileContext dict specifying which forms to include.
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
runtime_context: SelectedRuntimeContext | bool
|
| 231 |
+
compile_context: SelectedCompileContext | bool
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
_DEFAULT_ISOLATION_SCHEMA: IsolationSchema = IsolationSchema(
|
| 235 |
+
runtime_context=True, compile_context=True
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _isolation_context(
|
| 240 |
+
ischema: IsolationSchema = _DEFAULT_ISOLATION_SCHEMA,
|
| 241 |
+
) -> dict[str, Any]:
|
| 242 |
+
"""Generate context data based on the isolation schema.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
ischema: Schema specifying which context forms to include.
|
| 246 |
+
Defaults to including all runtime and compile context.
|
| 247 |
+
|
| 248 |
+
Returns:
|
| 249 |
+
A dictionary containing the selected context data with keys
|
| 250 |
+
"runtime_context" and "compile_context", where each value is
|
| 251 |
+
either None (if excluded) or a dict of context form data.
|
| 252 |
+
"""
|
| 253 |
+
isolation_context: dict[str, Any] = {}
|
| 254 |
+
for context_name, context_cls in (
|
| 255 |
+
("runtime_context", _RuntimeContext),
|
| 256 |
+
("compile_context", _CompileContext),
|
| 257 |
+
):
|
| 258 |
+
selected_context: dict[str, Any] | None = None
|
| 259 |
+
if ischema[context_name] is True: # type: ignore[literal-required]
|
| 260 |
+
selected_context = {
|
| 261 |
+
form_of_context: getattr(context_cls, form_of_context)()
|
| 262 |
+
for form_of_context in context_cls.forms_of_context()
|
| 263 |
+
}
|
| 264 |
+
elif ischema[context_name] is False: # type: ignore[literal-required]
|
| 265 |
+
selected_context = None
|
| 266 |
+
else:
|
| 267 |
+
selected_context = {}
|
| 268 |
+
for form_of_context in ischema[context_name]: # type: ignore[literal-required]
|
| 269 |
+
selected = ischema[context_name][form_of_context] # type: ignore[literal-required]
|
| 270 |
+
if selected:
|
| 271 |
+
selected_context[form_of_context] = getattr(
|
| 272 |
+
context_cls, form_of_context
|
| 273 |
+
)()
|
| 274 |
+
selected_context = selected_context or None
|
| 275 |
+
isolation_context[context_name] = selected_context
|
| 276 |
+
return isolation_context
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _isolation_key(ischema: IsolationSchema = _DEFAULT_ISOLATION_SCHEMA) -> str:
|
| 280 |
+
"""Generate a unique key for the given isolation schema.
|
| 281 |
+
|
| 282 |
+
Args:
|
| 283 |
+
ischema: Schema specifying which context forms to include.
|
| 284 |
+
Defaults to including all runtime and compile context.
|
| 285 |
+
|
| 286 |
+
Returns:
|
| 287 |
+
A 32-character hexadecimal string that uniquely identifies
|
| 288 |
+
the context specified by the isolation schema.
|
| 289 |
+
"""
|
| 290 |
+
return sha256(
|
| 291 |
+
json.dumps(_isolation_context(ischema), sort_keys=True).encode()
|
| 292 |
+
).hexdigest()[:32]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/exceptions.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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or runtime caching.
|
| 4 |
+
|
| 5 |
+
This module defines a hierarchy of exceptions used throughout the caching system.
|
| 6 |
+
All custom exceptions inherit from CacheError, with UserError serving as a base
|
| 7 |
+
for user-facing errors that also inherit from TypeError for compatibility.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from threading import Lock
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
from filelock import FileLock
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CacheError(Exception):
|
| 17 |
+
"""Base class for all caching-related errors.
|
| 18 |
+
|
| 19 |
+
This is the root exception class for all custom exceptions raised by the caching
|
| 20 |
+
module, providing a common interface for error handling and logging.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class SystemError(CacheError, RuntimeError):
|
| 25 |
+
"""Base class for system-level caching errors.
|
| 26 |
+
|
| 27 |
+
This class represents errors that occur during cache operations, such as
|
| 28 |
+
storage or retrieval failures. It inherits from RuntimeError to indicate
|
| 29 |
+
that the error is not caused by user input.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class LockTimeoutError(SystemError):
|
| 34 |
+
"""Error raised when a lock operation times out.
|
| 35 |
+
|
| 36 |
+
This exception is raised when a lock operation exceeds the specified timeout
|
| 37 |
+
limit, indicating that the lock could not be acquired within the allotted time.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, lock: Lock, timeout: float) -> None:
|
| 41 |
+
"""Initialize the lock timeout error with detailed lock information.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
lock: The lock object that timed out.
|
| 45 |
+
timeout: The timeout limit that was exceeded.
|
| 46 |
+
"""
|
| 47 |
+
super().__init__(f"Failed to acquire lock {lock} within {timeout} seconds.")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class FileLockTimeoutError(SystemError):
|
| 51 |
+
"""Error raised when a file lock operation times out.
|
| 52 |
+
|
| 53 |
+
This exception is raised when a file lock operation exceeds the specified timeout
|
| 54 |
+
limit, indicating that the lock could not be acquired within the allotted time.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(self, flock: FileLock, timeout: float) -> None:
|
| 58 |
+
"""Initialize the file lock timeout error with detailed lock information.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
flock: The file lock object that timed out.
|
| 62 |
+
timeout: The timeout limit that was exceeded.
|
| 63 |
+
"""
|
| 64 |
+
super().__init__(
|
| 65 |
+
f"Failed to acquire file lock {flock} within {timeout} seconds."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class UserError(CacheError, TypeError):
|
| 70 |
+
"""Base class for user-facing cache errors that also inherit from TypeError.
|
| 71 |
+
|
| 72 |
+
This class combines CacheError with TypeError to provide compatibility
|
| 73 |
+
with existing exception handling patterns while maintaining the cache
|
| 74 |
+
error hierarchy. All user-facing cache errors should inherit from this class.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class KeyEncodingError(UserError):
|
| 79 |
+
"""Base class for errors that occur during cache key encoding operations.
|
| 80 |
+
|
| 81 |
+
Raised when cache keys cannot be properly encoded for storage or transmission.
|
| 82 |
+
This includes serialization, hashing, or other encoding-related failures.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class KeyPicklingError(KeyEncodingError):
|
| 87 |
+
"""Error raised when a cache key cannot be pickled for serialization.
|
| 88 |
+
|
| 89 |
+
This typically occurs when trying to cache objects with keys that contain
|
| 90 |
+
non-serializable components, lambda functions, or other unpickleable types.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
def __init__(self, key: Any) -> None:
|
| 94 |
+
"""Initialize the key pickling error with detailed key information.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
key: The cache key that failed to be pickled.
|
| 98 |
+
"""
|
| 99 |
+
super().__init__(
|
| 100 |
+
f"Failed to pickle cache key with type {type(key)} and value {key!r}."
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class ValueEncodingError(UserError):
|
| 105 |
+
"""Base class for errors that occur during cache value encoding operations.
|
| 106 |
+
|
| 107 |
+
Raised when cache values cannot be properly encoded for storage or transmission.
|
| 108 |
+
This includes serialization, compression, or other encoding-related failures.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class ValuePicklingError(ValueEncodingError):
|
| 113 |
+
"""Error raised when a cache value cannot be pickled for serialization.
|
| 114 |
+
|
| 115 |
+
This occurs when trying to cache objects that contain non-serializable
|
| 116 |
+
components, file handles, network connections, or other unpickleable types.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(self, value: Any) -> None:
|
| 120 |
+
"""Initialize the value pickling error with detailed value information.
|
| 121 |
+
|
| 122 |
+
Args:
|
| 123 |
+
value: The cache value that failed to be pickled.
|
| 124 |
+
"""
|
| 125 |
+
super().__init__(
|
| 126 |
+
f"Failed to pickle cache value with type {type(value)} and value {value!r}."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class ValueDecodingError(UserError):
|
| 131 |
+
"""Base class for errors that occur during cache value decoding operations.
|
| 132 |
+
|
| 133 |
+
Raised when cached values cannot be properly decoded during retrieval.
|
| 134 |
+
This includes deserialization, decompression, or other decoding-related failures.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class ValueUnPicklingError(ValueDecodingError):
|
| 139 |
+
"""Error raised when cached value data cannot be unpickled during retrieval.
|
| 140 |
+
|
| 141 |
+
This typically indicates corruption, version incompatibility, or missing
|
| 142 |
+
dependencies required to reconstruct the cached object.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def __init__(self, pickled_value: bytes) -> None:
|
| 146 |
+
"""Initialize the value unpickling error with the problematic data.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
pickled_value: The bytes that failed to be unpickled.
|
| 150 |
+
"""
|
| 151 |
+
super().__init__(
|
| 152 |
+
f"Failed to unpickle cache value from pickled value {pickled_value!r}."
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class CustomParamsEncoderRequiredError(UserError):
|
| 157 |
+
pass
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class CustomResultEncoderRequiredError(UserError):
|
| 161 |
+
pass
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class CustomResultDecoderRequiredError(UserError):
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class DeterministicCachingDisabledError(UserError):
|
| 169 |
+
pass
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class DeterministicCachingRequiresStrongConsistencyError(UserError):
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class StrictDeterministicCachingKeyNotFoundError(UserError):
|
| 177 |
+
pass
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class DeterministicCachingInvalidConfigurationError(UserError):
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class StrictDeterministicCachingInsertionError(UserError):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class DeterministicCachingIMCDumpConflictError(SystemError):
|
| 189 |
+
pass
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/implementations.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Cache implementation classes for PyTorch Inductor runtime caching.
|
| 2 |
+
|
| 3 |
+
This module provides concrete implementations of caching backends including
|
| 4 |
+
in-memory, on-disk, and remote caching strategies. Each implementation follows
|
| 5 |
+
the abstract _CacheImpl interface and provides thread-safe operations with
|
| 6 |
+
appropriate locking mechanisms.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from abc import ABC, abstractmethod
|
| 10 |
+
from collections.abc import Generator
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from hashlib import sha256
|
| 14 |
+
from io import BufferedReader, BufferedWriter
|
| 15 |
+
from os import PathLike
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from threading import Lock
|
| 18 |
+
from typing import Any
|
| 19 |
+
from typing_extensions import override
|
| 20 |
+
|
| 21 |
+
from filelock import FileLock
|
| 22 |
+
|
| 23 |
+
from . import locks, utils
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class Hit:
|
| 28 |
+
"""Result wrapper for hits on cache get operations.
|
| 29 |
+
|
| 30 |
+
Allows distinguishing between a cache miss and a cached None value.
|
| 31 |
+
|
| 32 |
+
Attributes:
|
| 33 |
+
value: The cached value.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
value: Any
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Miss:
|
| 40 |
+
"""Sentinel class representing a cache miss.
|
| 41 |
+
|
| 42 |
+
Used to distinguish between a cached None value and a cache miss
|
| 43 |
+
when None is a valid cached value.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# Singleton instance for cache miss sentinel
|
| 48 |
+
miss = Miss()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _CacheImpl(ABC):
|
| 52 |
+
"""Abstract base class for cache implementations.
|
| 53 |
+
|
| 54 |
+
This class defines the interface that all cache implementations must follow.
|
| 55 |
+
It provides thread-safe operations through a locking mechanism and supports
|
| 56 |
+
both get and insert operations.
|
| 57 |
+
|
| 58 |
+
Note: We don't use generics here as doing so would require that the interfaces
|
| 59 |
+
know which k/v types the implementation can work with. Instead, we leave that
|
| 60 |
+
determination up to the implementation itself and require that the interfaces
|
| 61 |
+
handle any potential errors from invalid k/v types being passed to the
|
| 62 |
+
implementation.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self) -> None:
|
| 66 |
+
"""Initialize the cache implementation with a threading lock."""
|
| 67 |
+
self._lock: Lock = Lock()
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def lock(self) -> locks._LockProtocol:
|
| 71 |
+
"""Get a context manager for acquiring the cache lock.
|
| 72 |
+
|
| 73 |
+
Locking of the cache is not done by the implementation itself, but by the
|
| 74 |
+
interface that uses it. The interface may want to hold the lock for longer
|
| 75 |
+
than a single cache operation, for example when dealing with multiple
|
| 76 |
+
cache implementations at once, so we leave that decision up to the interface.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
timeout: Optional timeout in seconds (float) for acquiring the lock.
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
A callable that returns a context manager for the lock.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def _lock_with_timeout(
|
| 86 |
+
timeout: float | None = None,
|
| 87 |
+
) -> locks._LockContextManager:
|
| 88 |
+
return locks._acquire_lock_with_timeout(self._lock, timeout)
|
| 89 |
+
|
| 90 |
+
return _lock_with_timeout
|
| 91 |
+
|
| 92 |
+
@abstractmethod
|
| 93 |
+
def get(self, key: Any) -> Hit | None:
|
| 94 |
+
"""Retrieve a value from the cache.
|
| 95 |
+
|
| 96 |
+
Args:
|
| 97 |
+
key: The key to look up in the cache.
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
A Hit object on cache hit where Hit.value is the cached value,
|
| 101 |
+
or None on cache miss.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
@abstractmethod
|
| 105 |
+
def insert(self, key: Any, value: Any) -> bool:
|
| 106 |
+
"""Insert a key-value pair into the cache.
|
| 107 |
+
|
| 108 |
+
Args:
|
| 109 |
+
key: The key to insert.
|
| 110 |
+
value: The value to associate with the key.
|
| 111 |
+
|
| 112 |
+
Returns:
|
| 113 |
+
True if the insertion was successful, False if not inserted.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class _InMemoryCacheImpl(_CacheImpl):
|
| 118 |
+
"""In-memory cache implementation using a dictionary.
|
| 119 |
+
|
| 120 |
+
This implementation stores key-value pairs in a Python dictionary,
|
| 121 |
+
with keys being pickled for consistent hashing. It provides fast
|
| 122 |
+
access but is limited by available memory and process lifetime.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
def __init__(self) -> None:
|
| 126 |
+
"""Initialize the in-memory cache with an empty dictionary."""
|
| 127 |
+
super().__init__()
|
| 128 |
+
self._memory: dict[bytes, Any] = {}
|
| 129 |
+
|
| 130 |
+
@override
|
| 131 |
+
def get(self, key: Any) -> Hit | None:
|
| 132 |
+
"""Retrieve a value from the in-memory cache.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
key: The key to look up. Will be pickled for storage.
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
A Hit object on cache hit where Hit.value is the cached value,
|
| 139 |
+
or None on cache miss.
|
| 140 |
+
"""
|
| 141 |
+
pickled_key: bytes = utils._try_pickle_key(key)
|
| 142 |
+
if (value := self._memory.get(pickled_key, miss)) is not miss:
|
| 143 |
+
return Hit(value=value)
|
| 144 |
+
return None
|
| 145 |
+
|
| 146 |
+
@override
|
| 147 |
+
def insert(self, key: Any, value: Any) -> bool:
|
| 148 |
+
"""Insert a key-value pair into the in-memory cache.
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
key: The key to insert. Will be pickled for storage.
|
| 152 |
+
value: The value to associate with the key.
|
| 153 |
+
|
| 154 |
+
Returns:
|
| 155 |
+
True if the insertion was successful (key was new),
|
| 156 |
+
False if not inserted (key already existed).
|
| 157 |
+
"""
|
| 158 |
+
pickled_key: bytes = utils._try_pickle_key(key)
|
| 159 |
+
if pickled_key not in self._memory:
|
| 160 |
+
self._memory[pickled_key] = value
|
| 161 |
+
return True
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class _OnDiskCacheImpl(_CacheImpl):
|
| 166 |
+
"""On-disk cache implementation using file system storage.
|
| 167 |
+
|
| 168 |
+
This implementation stores cached data as files on disk, with version
|
| 169 |
+
headers to handle cache invalidation. It uses file locking to ensure
|
| 170 |
+
thread safety across processes and provides persistent storage that
|
| 171 |
+
survives process restarts.
|
| 172 |
+
|
| 173 |
+
Attributes:
|
| 174 |
+
_version: Version number for cache format compatibility.
|
| 175 |
+
_version_header_length: Length of the version header in bytes.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
_version: int = 0
|
| 179 |
+
_version_header_length: int = 4
|
| 180 |
+
|
| 181 |
+
def __init__(self, sub_dir: PathLike[str] | None = None) -> None:
|
| 182 |
+
"""Initialize the on-disk cache with a specified subdirectory.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
sub_dir: Subdirectory name within the cache directory.
|
| 186 |
+
Defaults to empty string if not specified.
|
| 187 |
+
"""
|
| 188 |
+
self._cache_dir: Path = self._base_dir / (sub_dir or "")
|
| 189 |
+
# pyrefly: ignore [bad-assignment]
|
| 190 |
+
self._flock: FileLock = FileLock(str(self._cache_dir / "dir.lock"))
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def _base_dir(self) -> Path:
|
| 194 |
+
"""Get the base directory for cache storage.
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
Path to the cache directory based on the default cache dir
|
| 198 |
+
and the specified subdirectory.
|
| 199 |
+
"""
|
| 200 |
+
from torch._inductor.runtime.runtime_utils import default_cache_dir
|
| 201 |
+
|
| 202 |
+
return Path(default_cache_dir(), "cache")
|
| 203 |
+
|
| 204 |
+
def _fpath_from_key(self, key: Any) -> Path:
|
| 205 |
+
"""Generate a file path from a cache key.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
key: The cache key to convert to a file path.
|
| 209 |
+
|
| 210 |
+
Returns:
|
| 211 |
+
A Path object representing the file location for this key.
|
| 212 |
+
"""
|
| 213 |
+
pickled_key: bytes = utils._try_pickle_key(key)
|
| 214 |
+
return self._cache_dir / sha256(pickled_key).hexdigest()[:32]
|
| 215 |
+
|
| 216 |
+
@classmethod
|
| 217 |
+
def _version_header(cls) -> bytes:
|
| 218 |
+
"""Generate the version header bytes.
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
A byte string representing the current cache version header.
|
| 222 |
+
"""
|
| 223 |
+
return sha256(str(cls._version).encode()).digest()[: cls._version_header_length]
|
| 224 |
+
|
| 225 |
+
def _version_header_matches(self, fp: BufferedReader) -> bool:
|
| 226 |
+
"""Check if the file's version header matches the current version.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
fp: File pointer positioned at the start of the file.
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
True if the version header matches, False otherwise.
|
| 233 |
+
"""
|
| 234 |
+
return fp.read(self._version_header_length) == self._version_header()
|
| 235 |
+
|
| 236 |
+
def _write_version_header(self, fp: BufferedWriter) -> None:
|
| 237 |
+
"""Write the version header to a file.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
fp: File pointer where the version header should be written.
|
| 241 |
+
"""
|
| 242 |
+
fp.write(self._version_header())
|
| 243 |
+
|
| 244 |
+
@override
|
| 245 |
+
@property
|
| 246 |
+
def lock(self) -> locks._LockProtocol:
|
| 247 |
+
"""Get a context manager for acquiring the file lock.
|
| 248 |
+
|
| 249 |
+
Uses file locking to ensure thread safety across processes.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
timeout: Optional timeout in seconds (float) for acquiring the file lock.
|
| 253 |
+
|
| 254 |
+
Returns:
|
| 255 |
+
A callable that returns a context manager for the file lock.
|
| 256 |
+
"""
|
| 257 |
+
|
| 258 |
+
def _lock_with_timeout(
|
| 259 |
+
timeout: float | None = None,
|
| 260 |
+
) -> locks._LockContextManager:
|
| 261 |
+
return locks._acquire_flock_with_timeout(self._flock, timeout)
|
| 262 |
+
|
| 263 |
+
return _lock_with_timeout
|
| 264 |
+
|
| 265 |
+
@override
|
| 266 |
+
def get(self, key: Any) -> Hit | None:
|
| 267 |
+
"""Retrieve a value from the on-disk cache.
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
key: The key to look up in the cache.
|
| 271 |
+
|
| 272 |
+
Returns:
|
| 273 |
+
A Hit object on cache hit where Hit.value is the cached value,
|
| 274 |
+
or None on cache miss or version mismatch.
|
| 275 |
+
"""
|
| 276 |
+
fpath: Path = self._fpath_from_key(key)
|
| 277 |
+
|
| 278 |
+
if not fpath.is_file():
|
| 279 |
+
return None
|
| 280 |
+
|
| 281 |
+
pickled_value: bytes | None = None
|
| 282 |
+
with open(fpath, "rb") as fp:
|
| 283 |
+
if self._version_header_matches(fp):
|
| 284 |
+
pickled_value = fp.read()
|
| 285 |
+
|
| 286 |
+
if not pickled_value:
|
| 287 |
+
# if pickled_value is still None, even though the file exists, then
|
| 288 |
+
# we know that the version header did not match. in this case implementation
|
| 289 |
+
# is up to preference, we choose to remove entries that do not match
|
| 290 |
+
# the version header so that the key can be re-cached later with the correct
|
| 291 |
+
# version header
|
| 292 |
+
fpath.unlink()
|
| 293 |
+
return None
|
| 294 |
+
|
| 295 |
+
return Hit(value=utils._try_unpickle_value(pickled_value))
|
| 296 |
+
|
| 297 |
+
@override
|
| 298 |
+
def insert(self, key: Any, value: Any) -> bool:
|
| 299 |
+
"""Insert a key-value pair into the on-disk cache.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
key: The key to insert.
|
| 303 |
+
value: The value to associate with the key.
|
| 304 |
+
|
| 305 |
+
Returns:
|
| 306 |
+
True if successfully inserted, False if the key already exists
|
| 307 |
+
with a valid version.
|
| 308 |
+
"""
|
| 309 |
+
fpath: Path = self._fpath_from_key(key)
|
| 310 |
+
fpath.parent.mkdir(parents=True, exist_ok=True)
|
| 311 |
+
|
| 312 |
+
r_fp, w_fp, inserted = None, None, False
|
| 313 |
+
try:
|
| 314 |
+
w_fp = open(fpath, "xb") # noqa: SIM115
|
| 315 |
+
except FileExistsError:
|
| 316 |
+
is_stale: bool = False
|
| 317 |
+
with open(fpath, "rb") as r_fp:
|
| 318 |
+
is_stale = not self._version_header_matches(r_fp)
|
| 319 |
+
|
| 320 |
+
if is_stale:
|
| 321 |
+
# same story as above, in this case the version header doesn't
|
| 322 |
+
# match so we choose to remove the old entry so that the new
|
| 323 |
+
# k/v pair can be cached
|
| 324 |
+
fpath.unlink()
|
| 325 |
+
w_fp = open(fpath, "xb") # noqa: SIM115
|
| 326 |
+
else:
|
| 327 |
+
w_fp = None
|
| 328 |
+
finally:
|
| 329 |
+
if w_fp:
|
| 330 |
+
try:
|
| 331 |
+
pickled_value: bytes = utils._try_pickle_value(value)
|
| 332 |
+
self._write_version_header(w_fp)
|
| 333 |
+
w_fp.write(pickled_value)
|
| 334 |
+
inserted = True
|
| 335 |
+
finally:
|
| 336 |
+
w_fp.close()
|
| 337 |
+
|
| 338 |
+
return inserted
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
try:
|
| 342 |
+
from .fb.implementations import _RemoteCacheImpl
|
| 343 |
+
except ModuleNotFoundError:
|
| 344 |
+
|
| 345 |
+
class _RemoteCacheImpl(_CacheImpl): # type: ignore[no-redef]
|
| 346 |
+
"""Fallback remote cache implementation for non-Facebook environments.
|
| 347 |
+
|
| 348 |
+
This is a no-op implementation that always raises NotImplementedError.
|
| 349 |
+
The actual remote cache implementation is provided in the `.fb` module
|
| 350 |
+
for Facebook-specific environments.
|
| 351 |
+
|
| 352 |
+
Attributes:
|
| 353 |
+
_version: Version number for cache format compatibility.
|
| 354 |
+
has_strong_consistency: Whether the remote cache provides strong
|
| 355 |
+
consistency guarantees.
|
| 356 |
+
"""
|
| 357 |
+
|
| 358 |
+
_version: int = 0
|
| 359 |
+
has_strong_consistency: bool = False
|
| 360 |
+
|
| 361 |
+
def __init__(self) -> None:
|
| 362 |
+
"""Initialize the fallback remote cache implementation.
|
| 363 |
+
|
| 364 |
+
Note: We don't need to initialize any form of lock since this
|
| 365 |
+
implementation provides a pseudo-lock context manager.
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
@override
|
| 369 |
+
@property
|
| 370 |
+
def lock(self) -> locks._LockProtocol:
|
| 371 |
+
"""Get a pseudo lock that does nothing.
|
| 372 |
+
|
| 373 |
+
Most remote cache implementations don't have an ability to implement
|
| 374 |
+
any form of locking, so we provide a no-op pseudo-lock for consistency
|
| 375 |
+
with the interface.
|
| 376 |
+
|
| 377 |
+
Args:
|
| 378 |
+
timeout: Optional timeout in seconds (float). Ignored in this
|
| 379 |
+
|
| 380 |
+
Returns:
|
| 381 |
+
A callable that returns a no-op context manager.
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
@contextmanager
|
| 385 |
+
def pseudo_lock(
|
| 386 |
+
timeout: float | None = None,
|
| 387 |
+
) -> Generator[None, None, None]:
|
| 388 |
+
yield
|
| 389 |
+
|
| 390 |
+
return pseudo_lock
|
| 391 |
+
|
| 392 |
+
@override
|
| 393 |
+
def get(self, key: Any) -> Hit | None:
|
| 394 |
+
"""Raise NotImplementedError for remote cache get operations.
|
| 395 |
+
|
| 396 |
+
Args:
|
| 397 |
+
key: The key to look up (ignored).
|
| 398 |
+
|
| 399 |
+
Raises:
|
| 400 |
+
NotImplementedError: Always raised as this is a fallback implementation.
|
| 401 |
+
"""
|
| 402 |
+
raise NotImplementedError
|
| 403 |
+
|
| 404 |
+
@override
|
| 405 |
+
def insert(self, key: Any, value: Any) -> bool:
|
| 406 |
+
"""Raise NotImplementedError for remote cache insert operations.
|
| 407 |
+
|
| 408 |
+
Args:
|
| 409 |
+
key: The key to insert (ignored).
|
| 410 |
+
value: The value to insert (ignored).
|
| 411 |
+
|
| 412 |
+
Raises:
|
| 413 |
+
NotImplementedError: Always raised as this is a fallback implementation.
|
| 414 |
+
"""
|
| 415 |
+
raise NotImplementedError
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/interfaces.py
ADDED
|
@@ -0,0 +1,818 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import atexit
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
from abc import ABC, abstractmethod
|
| 7 |
+
from ast import literal_eval
|
| 8 |
+
from enum import Enum
|
| 9 |
+
from functools import partial, wraps
|
| 10 |
+
from logging import DEBUG, getLogger, INFO, Logger
|
| 11 |
+
from os import PathLike
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from threading import Lock
|
| 14 |
+
from time import time
|
| 15 |
+
from typing import Any, TYPE_CHECKING, TypeAlias
|
| 16 |
+
from typing_extensions import override
|
| 17 |
+
|
| 18 |
+
from . import config, context, exceptions, implementations as impls, locks
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
from collections.abc import Callable
|
| 23 |
+
|
| 24 |
+
from .utils import P, R
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# ideally we could annotate this as tuple[P.args, P.kwargs] but
|
| 28 |
+
# functionally that doesn't work as P is defined in a specific
|
| 29 |
+
# scope and P.args/P.kwargs are only valid in that scope
|
| 30 |
+
Params: TypeAlias = tuple[Any, Any]
|
| 31 |
+
|
| 32 |
+
logger: Logger = getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _IntfCallbackOrigin(Enum):
|
| 36 |
+
RECORD = "record"
|
| 37 |
+
GET = "get"
|
| 38 |
+
INSERT = "insert"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class _IntfCallbackAction(Enum):
|
| 42 |
+
REPLAY = "replay"
|
| 43 |
+
RECORD_INSERTED = "record_inserted"
|
| 44 |
+
RECORD_NOT_INSERTED = "record_not_inserted"
|
| 45 |
+
RECORD_NOT_INSERTED_REPLAY = "record_not_inserted_replay"
|
| 46 |
+
HIT = "hit"
|
| 47 |
+
MISS = "miss"
|
| 48 |
+
INSERTED = "inserted"
|
| 49 |
+
NOT_INSERTED = "not_inserted"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _intf_callback(
|
| 53 |
+
origin: _IntfCallbackOrigin,
|
| 54 |
+
action: _IntfCallbackAction,
|
| 55 |
+
dur: float,
|
| 56 |
+
fn: Callable[P, R],
|
| 57 |
+
params: Params,
|
| 58 |
+
*args: Any,
|
| 59 |
+
) -> None:
|
| 60 |
+
if origin == _IntfCallbackOrigin.RECORD:
|
| 61 |
+
result: R = args[0]
|
| 62 |
+
if action == _IntfCallbackAction.REPLAY:
|
| 63 |
+
logger.log(
|
| 64 |
+
DEBUG,
|
| 65 |
+
"[RECORD] for fn %s with params %r cached, "
|
| 66 |
+
"returned result %r in %f seconds.",
|
| 67 |
+
fn.__name__,
|
| 68 |
+
params,
|
| 69 |
+
result,
|
| 70 |
+
dur,
|
| 71 |
+
)
|
| 72 |
+
elif action == _IntfCallbackAction.RECORD_INSERTED:
|
| 73 |
+
fn_dur: float = args[1]
|
| 74 |
+
logger.log(
|
| 75 |
+
DEBUG,
|
| 76 |
+
"[RECORD] for fn %s with params %r not cached, "
|
| 77 |
+
"calculated and cached result %r in %f seconds "
|
| 78 |
+
"of which %f seconds was spent on the function call.",
|
| 79 |
+
fn.__name__,
|
| 80 |
+
params,
|
| 81 |
+
result,
|
| 82 |
+
dur,
|
| 83 |
+
fn_dur,
|
| 84 |
+
)
|
| 85 |
+
elif action == _IntfCallbackAction.RECORD_NOT_INSERTED:
|
| 86 |
+
fn_dur = args[1]
|
| 87 |
+
logger.log(
|
| 88 |
+
DEBUG,
|
| 89 |
+
"[RECORD] for fn %s with params %r not cached, "
|
| 90 |
+
"calculated result %r but was not able to "
|
| 91 |
+
"insert it into the cache as a matching "
|
| 92 |
+
"entry already exists; returned calculated result in %f seconds "
|
| 93 |
+
"of which %f seconds was spent on the function call.",
|
| 94 |
+
fn.__name__,
|
| 95 |
+
params,
|
| 96 |
+
result,
|
| 97 |
+
dur,
|
| 98 |
+
fn_dur,
|
| 99 |
+
)
|
| 100 |
+
elif action == _IntfCallbackAction.RECORD_NOT_INSERTED_REPLAY:
|
| 101 |
+
fn_dur = args[1]
|
| 102 |
+
cached_result: R = args[2]
|
| 103 |
+
logger.log(
|
| 104 |
+
DEBUG,
|
| 105 |
+
"[RECORD] for fn %s with params %r not cached, "
|
| 106 |
+
"calculated result %r but was not able to "
|
| 107 |
+
"insert it into the synchronization cache as a matching "
|
| 108 |
+
"entry already exists; returned cached result %r in %f seconds "
|
| 109 |
+
"of which %f seconds was spent on the function call.",
|
| 110 |
+
fn.__name__,
|
| 111 |
+
params,
|
| 112 |
+
result,
|
| 113 |
+
cached_result,
|
| 114 |
+
dur,
|
| 115 |
+
fn_dur,
|
| 116 |
+
)
|
| 117 |
+
else:
|
| 118 |
+
raise NotImplementedError
|
| 119 |
+
elif origin == _IntfCallbackOrigin.GET:
|
| 120 |
+
if action == _IntfCallbackAction.HIT:
|
| 121 |
+
result = args[0]
|
| 122 |
+
logger.log(
|
| 123 |
+
DEBUG,
|
| 124 |
+
"[GET] for fn %s with params %r cached, "
|
| 125 |
+
"returned result %r in %f seconds.",
|
| 126 |
+
fn.__name__,
|
| 127 |
+
params,
|
| 128 |
+
result,
|
| 129 |
+
dur,
|
| 130 |
+
)
|
| 131 |
+
elif action == _IntfCallbackAction.MISS:
|
| 132 |
+
logger.log(
|
| 133 |
+
DEBUG,
|
| 134 |
+
"[GET] for fn %s with params %r not cached, "
|
| 135 |
+
"returned nothing in %f seconds.",
|
| 136 |
+
fn.__name__,
|
| 137 |
+
params,
|
| 138 |
+
dur,
|
| 139 |
+
)
|
| 140 |
+
else:
|
| 141 |
+
raise NotImplementedError
|
| 142 |
+
elif origin == _IntfCallbackOrigin.INSERT:
|
| 143 |
+
result = args[0]
|
| 144 |
+
if action == _IntfCallbackAction.INSERTED:
|
| 145 |
+
logger.log(
|
| 146 |
+
DEBUG,
|
| 147 |
+
"[INSERT] for fn %s with params %r and "
|
| 148 |
+
"result %r inserted in %f seconds.",
|
| 149 |
+
fn.__name__,
|
| 150 |
+
params,
|
| 151 |
+
result,
|
| 152 |
+
dur,
|
| 153 |
+
)
|
| 154 |
+
elif action == _IntfCallbackAction.NOT_INSERTED:
|
| 155 |
+
logger.log(
|
| 156 |
+
DEBUG,
|
| 157 |
+
"[INSERT] for fn %s with params %r and "
|
| 158 |
+
"result %r not inserted in %f seconds as there is "
|
| 159 |
+
"already has a matching entry.",
|
| 160 |
+
fn.__name__,
|
| 161 |
+
params,
|
| 162 |
+
result,
|
| 163 |
+
dur,
|
| 164 |
+
)
|
| 165 |
+
else:
|
| 166 |
+
raise NotImplementedError
|
| 167 |
+
else:
|
| 168 |
+
raise NotImplementedError
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class _CacheIntf(ABC):
|
| 172 |
+
def __init__(self) -> None:
|
| 173 |
+
self._lock: Lock = Lock()
|
| 174 |
+
|
| 175 |
+
def _make_key(
|
| 176 |
+
self,
|
| 177 |
+
fn: Callable[P, R],
|
| 178 |
+
params: Params,
|
| 179 |
+
ischema: context.IsolationSchema | None = None,
|
| 180 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 181 |
+
) -> Any:
|
| 182 |
+
callee: str = fn.__name__
|
| 183 |
+
fkey: Any = (
|
| 184 |
+
(callee, params)
|
| 185 |
+
if not custom_params_encoder
|
| 186 |
+
# pyrefly: ignore [invalid-param-spec]
|
| 187 |
+
else (callee, custom_params_encoder(*params[0], **params[1]))
|
| 188 |
+
)
|
| 189 |
+
ikey: Any = context._isolation_key(
|
| 190 |
+
ischema if ischema is not None else context._DEFAULT_ISOLATION_SCHEMA
|
| 191 |
+
)
|
| 192 |
+
return (fkey, ikey)
|
| 193 |
+
|
| 194 |
+
def _make_dummy_record_wrapper(self, fn: Callable[P, R]) -> Callable[P, R]:
|
| 195 |
+
@wraps(fn)
|
| 196 |
+
def dummy_wrapper(*args: Any, **kwargs: Any) -> R:
|
| 197 |
+
# pyrefly: ignore [invalid-param-spec]
|
| 198 |
+
return fn(*args, **kwargs)
|
| 199 |
+
|
| 200 |
+
# pyrefly: ignore [bad-return]
|
| 201 |
+
return dummy_wrapper
|
| 202 |
+
|
| 203 |
+
@abstractmethod
|
| 204 |
+
def _make_record_wrapper(
|
| 205 |
+
self,
|
| 206 |
+
fn: Callable[P, R],
|
| 207 |
+
ischema: context.IsolationSchema | None = None,
|
| 208 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 209 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 210 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 211 |
+
) -> Callable[P, R]:
|
| 212 |
+
pass
|
| 213 |
+
|
| 214 |
+
@abstractmethod
|
| 215 |
+
def _get(
|
| 216 |
+
self,
|
| 217 |
+
fn: Callable[P, R],
|
| 218 |
+
params: Params,
|
| 219 |
+
ischema: context.IsolationSchema | None = None,
|
| 220 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 221 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 222 |
+
) -> impls.Hit | None:
|
| 223 |
+
pass
|
| 224 |
+
|
| 225 |
+
@abstractmethod
|
| 226 |
+
def _insert(
|
| 227 |
+
self,
|
| 228 |
+
fn: Callable[P, R],
|
| 229 |
+
params: Params,
|
| 230 |
+
result: R,
|
| 231 |
+
ischema: context.IsolationSchema | None = None,
|
| 232 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 233 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 234 |
+
) -> bool:
|
| 235 |
+
pass
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def lock(self) -> locks._LockProtocol:
|
| 239 |
+
"""Get a context manager for acquiring the file lock.
|
| 240 |
+
|
| 241 |
+
Uses file locking to ensure thread safety across processes.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
timeout: Optional timeout in seconds (float) for acquiring the file lock.
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
A callable that returns a context manager for the file lock.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
def _lock_with_timeout(
|
| 251 |
+
timeout: float | None = None,
|
| 252 |
+
) -> locks._LockContextManager:
|
| 253 |
+
return locks._acquire_lock_with_timeout(self._lock, timeout)
|
| 254 |
+
|
| 255 |
+
return _lock_with_timeout
|
| 256 |
+
|
| 257 |
+
def get(
|
| 258 |
+
self,
|
| 259 |
+
fn: Callable[P, R],
|
| 260 |
+
params: Params,
|
| 261 |
+
ischema: context.IsolationSchema | None = None,
|
| 262 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 263 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 264 |
+
) -> impls.Hit | None:
|
| 265 |
+
if not config.IS_CACHING_MODULE_ENABLED():
|
| 266 |
+
return None
|
| 267 |
+
|
| 268 |
+
start_t: float = time()
|
| 269 |
+
with self.lock(): # type: ignore[call-arg]
|
| 270 |
+
result: impls.Hit | None = self._get(
|
| 271 |
+
fn,
|
| 272 |
+
params,
|
| 273 |
+
ischema=ischema,
|
| 274 |
+
custom_params_encoder=custom_params_encoder,
|
| 275 |
+
custom_result_decoder=custom_result_decoder,
|
| 276 |
+
)
|
| 277 |
+
dur: float = time() - start_t
|
| 278 |
+
|
| 279 |
+
_intf_callback(
|
| 280 |
+
_IntfCallbackOrigin.GET,
|
| 281 |
+
_IntfCallbackAction.HIT if result else _IntfCallbackAction.MISS,
|
| 282 |
+
dur,
|
| 283 |
+
fn,
|
| 284 |
+
params,
|
| 285 |
+
*((result.value,) if result else ()),
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
return result
|
| 289 |
+
|
| 290 |
+
def insert(
|
| 291 |
+
self,
|
| 292 |
+
fn: Callable[P, R],
|
| 293 |
+
params: Params,
|
| 294 |
+
result: R,
|
| 295 |
+
ischema: context.IsolationSchema | None = None,
|
| 296 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 297 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 298 |
+
) -> bool:
|
| 299 |
+
if not config.IS_CACHING_MODULE_ENABLED():
|
| 300 |
+
return False
|
| 301 |
+
|
| 302 |
+
start_t: float = time()
|
| 303 |
+
with self.lock(): # type: ignore[call-arg]
|
| 304 |
+
inserted: bool = self._insert(
|
| 305 |
+
fn,
|
| 306 |
+
params,
|
| 307 |
+
result,
|
| 308 |
+
ischema=ischema,
|
| 309 |
+
custom_params_encoder=custom_params_encoder,
|
| 310 |
+
custom_result_encoder=custom_result_encoder,
|
| 311 |
+
)
|
| 312 |
+
dur: float = time() - start_t
|
| 313 |
+
|
| 314 |
+
_intf_callback(
|
| 315 |
+
_IntfCallbackOrigin.INSERT,
|
| 316 |
+
_IntfCallbackAction.INSERTED
|
| 317 |
+
if inserted
|
| 318 |
+
else _IntfCallbackAction.NOT_INSERTED,
|
| 319 |
+
dur,
|
| 320 |
+
fn,
|
| 321 |
+
params,
|
| 322 |
+
result,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
return inserted
|
| 326 |
+
|
| 327 |
+
def record(
|
| 328 |
+
self,
|
| 329 |
+
ischema: context.IsolationSchema | None = None,
|
| 330 |
+
custom_params_encoder: Callable[..., Any] | None = None,
|
| 331 |
+
custom_result_encoder: Callable[..., Any] | None = None,
|
| 332 |
+
custom_result_decoder: Callable[..., ...] | None = None,
|
| 333 |
+
) -> Callable[[Callable[..., ...]], Callable[..., ...]]:
|
| 334 |
+
if custom_result_encoder and not custom_result_decoder:
|
| 335 |
+
raise exceptions.CustomResultDecoderRequiredError(
|
| 336 |
+
"Custom result encoder provided without custom result decoder."
|
| 337 |
+
)
|
| 338 |
+
elif not custom_result_encoder and custom_result_decoder:
|
| 339 |
+
raise exceptions.CustomResultEncoderRequiredError(
|
| 340 |
+
"Custom result decoder provided without custom result encoder."
|
| 341 |
+
)
|
| 342 |
+
elif not config.IS_CACHING_MODULE_ENABLED():
|
| 343 |
+
return self._make_dummy_record_wrapper
|
| 344 |
+
else:
|
| 345 |
+
return partial(
|
| 346 |
+
self._make_record_wrapper,
|
| 347 |
+
ischema=ischema,
|
| 348 |
+
custom_params_encoder=custom_params_encoder,
|
| 349 |
+
custom_result_encoder=custom_result_encoder,
|
| 350 |
+
custom_result_decoder=custom_result_decoder,
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
class _FastCacheIntf(_CacheIntf):
|
| 355 |
+
def __init__(self) -> None:
|
| 356 |
+
super().__init__()
|
| 357 |
+
self._imc: impls._InMemoryCacheImpl = impls._InMemoryCacheImpl()
|
| 358 |
+
self._callee_to_odc: dict[str, impls._OnDiskCacheImpl] = {}
|
| 359 |
+
|
| 360 |
+
def _get_odc_from_callee(self, callee: str) -> impls._OnDiskCacheImpl:
|
| 361 |
+
if not (odc := self._callee_to_odc.get(callee)):
|
| 362 |
+
callee_sub_dir: PathLike[str] = Path(callee)
|
| 363 |
+
odc = impls._OnDiskCacheImpl(sub_dir=callee_sub_dir)
|
| 364 |
+
self._callee_to_odc[callee] = odc
|
| 365 |
+
# pyrefly: ignore [unbound-name]
|
| 366 |
+
return odc
|
| 367 |
+
|
| 368 |
+
@override
|
| 369 |
+
def _make_record_wrapper(
|
| 370 |
+
self,
|
| 371 |
+
fn: Callable[P, R],
|
| 372 |
+
ischema: context.IsolationSchema | None = None,
|
| 373 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 374 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 375 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 376 |
+
) -> Callable[P, R]:
|
| 377 |
+
@wraps(fn)
|
| 378 |
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 379 |
+
start_t: float = time()
|
| 380 |
+
params = (
|
| 381 |
+
args,
|
| 382 |
+
kwargs,
|
| 383 |
+
)
|
| 384 |
+
with self.lock():
|
| 385 |
+
get: impls.Hit | None = self._get(
|
| 386 |
+
fn,
|
| 387 |
+
params,
|
| 388 |
+
ischema=ischema,
|
| 389 |
+
custom_params_encoder=custom_params_encoder,
|
| 390 |
+
custom_result_decoder=custom_result_decoder,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
if get:
|
| 394 |
+
dur: float = time() - start_t
|
| 395 |
+
_intf_callback(
|
| 396 |
+
_IntfCallbackOrigin.RECORD,
|
| 397 |
+
_IntfCallbackAction.REPLAY,
|
| 398 |
+
dur,
|
| 399 |
+
fn,
|
| 400 |
+
params,
|
| 401 |
+
get.value,
|
| 402 |
+
)
|
| 403 |
+
return get.value
|
| 404 |
+
else:
|
| 405 |
+
fn_start_t: float = time()
|
| 406 |
+
result: R = fn(*args, **kwargs)
|
| 407 |
+
fn_dur: float = time() - fn_start_t
|
| 408 |
+
inserted: bool = self._insert(
|
| 409 |
+
fn,
|
| 410 |
+
params,
|
| 411 |
+
result,
|
| 412 |
+
ischema=ischema,
|
| 413 |
+
custom_params_encoder=custom_params_encoder,
|
| 414 |
+
custom_result_encoder=custom_result_encoder,
|
| 415 |
+
)
|
| 416 |
+
dur = time() - start_t
|
| 417 |
+
_intf_callback(
|
| 418 |
+
_IntfCallbackOrigin.RECORD,
|
| 419 |
+
_IntfCallbackAction.RECORD_INSERTED
|
| 420 |
+
if inserted
|
| 421 |
+
else _IntfCallbackAction.RECORD_NOT_INSERTED,
|
| 422 |
+
dur,
|
| 423 |
+
fn,
|
| 424 |
+
params,
|
| 425 |
+
result,
|
| 426 |
+
fn_dur,
|
| 427 |
+
)
|
| 428 |
+
return result
|
| 429 |
+
|
| 430 |
+
return wrapper
|
| 431 |
+
|
| 432 |
+
@override
|
| 433 |
+
def _get(
|
| 434 |
+
self,
|
| 435 |
+
fn: Callable[P, R],
|
| 436 |
+
params: Params,
|
| 437 |
+
ischema: context.IsolationSchema | None = None,
|
| 438 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 439 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 440 |
+
) -> impls.Hit | None:
|
| 441 |
+
key: Any = self._make_key(
|
| 442 |
+
fn, params, ischema=ischema, custom_params_encoder=custom_params_encoder
|
| 443 |
+
)
|
| 444 |
+
odc: impls._OnDiskCacheImpl = self._get_odc_from_callee(fn.__name__)
|
| 445 |
+
with locks._acquire_many_impl_locks_with_timeout(self._imc, odc):
|
| 446 |
+
try:
|
| 447 |
+
# we'll check the memoization first, since that is much faster
|
| 448 |
+
# than checking the on-disk cache (and the two should be consistent
|
| 449 |
+
# regardless)
|
| 450 |
+
imc_get: impls.Hit | None = self._imc.get(key)
|
| 451 |
+
if imc_get:
|
| 452 |
+
if custom_result_decoder:
|
| 453 |
+
return impls.Hit(value=custom_result_decoder(imc_get.value))
|
| 454 |
+
else:
|
| 455 |
+
return imc_get
|
| 456 |
+
else:
|
| 457 |
+
odc_get: impls.Hit | None = odc.get(key)
|
| 458 |
+
if odc_get:
|
| 459 |
+
if custom_result_decoder:
|
| 460 |
+
return impls.Hit(value=custom_result_decoder(odc_get.value))
|
| 461 |
+
return odc_get
|
| 462 |
+
return None
|
| 463 |
+
except exceptions.KeyEncodingError as err:
|
| 464 |
+
raise exceptions.CustomParamsEncoderRequiredError(fn, params) from err
|
| 465 |
+
|
| 466 |
+
@override
|
| 467 |
+
def _insert(
|
| 468 |
+
self,
|
| 469 |
+
fn: Callable[P, R],
|
| 470 |
+
params: Params,
|
| 471 |
+
result: R,
|
| 472 |
+
ischema: context.IsolationSchema | None = None,
|
| 473 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 474 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 475 |
+
) -> bool:
|
| 476 |
+
key: Any = self._make_key(
|
| 477 |
+
fn, params, ischema=ischema, custom_params_encoder=custom_params_encoder
|
| 478 |
+
)
|
| 479 |
+
odc: impls._OnDiskCacheImpl = self._get_odc_from_callee(fn.__name__)
|
| 480 |
+
with locks._acquire_many_impl_locks_with_timeout(self._imc, odc):
|
| 481 |
+
try:
|
| 482 |
+
encoded_result: Any = (
|
| 483 |
+
result
|
| 484 |
+
if not custom_result_encoder
|
| 485 |
+
else custom_result_encoder(result)
|
| 486 |
+
)
|
| 487 |
+
# reverse order of get, as we don't want to memoize values
|
| 488 |
+
# if we haven't actually inserted them into the on-disk cache
|
| 489 |
+
# so that the memoization and the on-disk cache remain consistent
|
| 490 |
+
if odc.insert(key, encoded_result):
|
| 491 |
+
assert self._imc.insert(key, encoded_result)
|
| 492 |
+
return True
|
| 493 |
+
return False
|
| 494 |
+
except exceptions.KeyEncodingError as err:
|
| 495 |
+
raise exceptions.CustomParamsEncoderRequiredError(fn, params) from err
|
| 496 |
+
except exceptions.ValueEncodingError as err:
|
| 497 |
+
raise exceptions.CustomResultEncoderRequiredError(
|
| 498 |
+
f"Custom result encoder required for function {fn} with parameters {params} and result {result}."
|
| 499 |
+
) from err
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
class _DeterministicCacheIntf(_CacheIntf):
|
| 503 |
+
def __init__(self) -> None:
|
| 504 |
+
super().__init__()
|
| 505 |
+
self._imc: impls._InMemoryCacheImpl = impls._InMemoryCacheImpl()
|
| 506 |
+
|
| 507 |
+
if fpath_str := os.environ.get(
|
| 508 |
+
"TORCHINDUCTOR_PRE_POPULATE_DETERMINISTIC_CACHE"
|
| 509 |
+
):
|
| 510 |
+
fpath: Path = Path(fpath_str)
|
| 511 |
+
fpath_parent: PathLike[str] = fpath.parent
|
| 512 |
+
if fpath.is_file():
|
| 513 |
+
odc: impls._OnDiskCacheImpl = impls._OnDiskCacheImpl(
|
| 514 |
+
sub_dir=fpath_parent
|
| 515 |
+
)
|
| 516 |
+
with odc.lock():
|
| 517 |
+
with open(fpath) as fp:
|
| 518 |
+
dump_for_pre_population: dict[str, str] = json.load(fp)
|
| 519 |
+
for key_r, value_r in dump_for_pre_population.items():
|
| 520 |
+
key: bytes = literal_eval(key_r)
|
| 521 |
+
value: bytes = literal_eval(value_r)
|
| 522 |
+
self._imc._memory[key] = value
|
| 523 |
+
|
| 524 |
+
if config.STRICTLY_PRE_POPULATED_DETERMINISM:
|
| 525 |
+
# we'll never need a synchronization cache if we're in strictly pre-populated mode,
|
| 526 |
+
# as we'll only ever be checking the memoized pre-population
|
| 527 |
+
self._get_sc_from_callee: Callable[
|
| 528 |
+
[str], None | impls._OnDiskCacheImpl | impls._RemoteCacheImpl
|
| 529 |
+
] = lambda callee: None
|
| 530 |
+
elif config.GLOBAL_DETERMINISM:
|
| 531 |
+
# if we want global determinism we need to use a remote cache with strong
|
| 532 |
+
# consistency as the synchronization cache
|
| 533 |
+
self._rc: impls._RemoteCacheImpl = impls._RemoteCacheImpl()
|
| 534 |
+
if not self._rc.has_strong_consistency:
|
| 535 |
+
raise exceptions.DeterministicCachingRequiresStrongConsistencyError
|
| 536 |
+
self._get_sc_from_callee = lambda callee: self._rc
|
| 537 |
+
elif config.LOCAL_DETERMINISM:
|
| 538 |
+
# local determinism can use the on-disk cache as the synchronization cache,
|
| 539 |
+
# for cleanliness of the on-disk cache we subdir based on the callee
|
| 540 |
+
self._callee_to_odc: dict[str, impls._OnDiskCacheImpl] = {}
|
| 541 |
+
self._get_sc_from_callee = self._get_odc_from_callee
|
| 542 |
+
else:
|
| 543 |
+
raise exceptions.DeterministicCachingInvalidConfigurationError(
|
| 544 |
+
"Deterministic caching must specify at least one of STRICTLY_PRE_POPULATED_DETERMINISM, "
|
| 545 |
+
"GLOBAL_DETERMINISM, or LOCAL_DETERMINISM."
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
atexit.register(self._dump_imc_to_disk)
|
| 549 |
+
|
| 550 |
+
def __del__(self) -> None:
|
| 551 |
+
atexit.unregister(self._dump_imc_to_disk)
|
| 552 |
+
del self
|
| 553 |
+
|
| 554 |
+
def _get_odc_from_callee(self, callee: str) -> impls._OnDiskCacheImpl:
|
| 555 |
+
if not (odc := self._callee_to_odc.get(callee)):
|
| 556 |
+
callee_sub_dir: PathLike[str] = Path(callee)
|
| 557 |
+
odc = impls._OnDiskCacheImpl(sub_dir=callee_sub_dir)
|
| 558 |
+
self._callee_to_odc[callee] = odc
|
| 559 |
+
# pyrefly: ignore [unbound-name]
|
| 560 |
+
return odc
|
| 561 |
+
|
| 562 |
+
def _dump_imc_to_disk(self) -> Path | None:
|
| 563 |
+
with self.lock(): # type: ignore[call-arg]
|
| 564 |
+
to_dump: dict[str, str] = {
|
| 565 |
+
repr(key): repr(value) for key, value in self._imc._memory.items()
|
| 566 |
+
}
|
| 567 |
+
if not to_dump:
|
| 568 |
+
return None
|
| 569 |
+
|
| 570 |
+
odc: impls._OnDiskCacheImpl = impls._OnDiskCacheImpl(
|
| 571 |
+
sub_dir=Path("dcache_dump")
|
| 572 |
+
)
|
| 573 |
+
fpath: Path = odc._cache_dir / "imc.save"
|
| 574 |
+
with odc.lock():
|
| 575 |
+
w_fp = None
|
| 576 |
+
try:
|
| 577 |
+
w_fp = open(fpath, "x") # noqa:SIM115
|
| 578 |
+
except FileExistsError:
|
| 579 |
+
with open(fpath) as r_fp:
|
| 580 |
+
existing_dump = json.load(r_fp)
|
| 581 |
+
|
| 582 |
+
for key, value in existing_dump.items():
|
| 583 |
+
if key not in to_dump:
|
| 584 |
+
to_dump[key] = value
|
| 585 |
+
elif to_dump[key] != value:
|
| 586 |
+
raise exceptions.DeterministicCachingIMCDumpConflictError from None
|
| 587 |
+
|
| 588 |
+
w_fp = open(fpath, "w") # noqa:SIM115
|
| 589 |
+
finally:
|
| 590 |
+
assert w_fp is not None
|
| 591 |
+
try:
|
| 592 |
+
json.dump(to_dump, w_fp, indent=4)
|
| 593 |
+
logger.log(
|
| 594 |
+
INFO, "Dumped deterministic cache memoization to %s", fpath
|
| 595 |
+
)
|
| 596 |
+
finally:
|
| 597 |
+
w_fp.close()
|
| 598 |
+
|
| 599 |
+
return fpath
|
| 600 |
+
|
| 601 |
+
@override
|
| 602 |
+
def _make_record_wrapper(
|
| 603 |
+
self,
|
| 604 |
+
fn: Callable[P, R],
|
| 605 |
+
ischema: context.IsolationSchema | None = None,
|
| 606 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 607 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 608 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 609 |
+
) -> Callable[P, R]:
|
| 610 |
+
@wraps(fn)
|
| 611 |
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
|
| 612 |
+
if not config.IS_DETERMINISTIC_CACHING_ENABLED():
|
| 613 |
+
raise exceptions.DeterministicCachingDisabledError
|
| 614 |
+
start_t: float = time()
|
| 615 |
+
params = (
|
| 616 |
+
args,
|
| 617 |
+
kwargs,
|
| 618 |
+
)
|
| 619 |
+
with self.lock():
|
| 620 |
+
get: impls.Hit | None = self._get(
|
| 621 |
+
fn,
|
| 622 |
+
params,
|
| 623 |
+
ischema=ischema,
|
| 624 |
+
custom_params_encoder=custom_params_encoder,
|
| 625 |
+
custom_result_decoder=custom_result_decoder,
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
if get:
|
| 629 |
+
dur: float = time() - start_t
|
| 630 |
+
_intf_callback(
|
| 631 |
+
_IntfCallbackOrigin.RECORD,
|
| 632 |
+
_IntfCallbackAction.REPLAY,
|
| 633 |
+
dur,
|
| 634 |
+
fn,
|
| 635 |
+
params,
|
| 636 |
+
get.value,
|
| 637 |
+
)
|
| 638 |
+
return get.value
|
| 639 |
+
else:
|
| 640 |
+
fn_start_t: float = time()
|
| 641 |
+
result: R = fn(*args, **kwargs)
|
| 642 |
+
fn_dur: float = time() - fn_start_t
|
| 643 |
+
if not self._insert(
|
| 644 |
+
fn,
|
| 645 |
+
params,
|
| 646 |
+
result,
|
| 647 |
+
ischema,
|
| 648 |
+
custom_params_encoder,
|
| 649 |
+
custom_result_encoder,
|
| 650 |
+
):
|
| 651 |
+
# if we couldn't insert that means that some other callee has populated
|
| 652 |
+
# the key entry in the remote cache within the time between our first get
|
| 653 |
+
# and the insert attempt; in that case, to be deterministic, we should
|
| 654 |
+
# call get again and return that value as the assumption is that other
|
| 655 |
+
# compile workers will also use that value
|
| 656 |
+
get = self._get(
|
| 657 |
+
fn,
|
| 658 |
+
params,
|
| 659 |
+
ischema,
|
| 660 |
+
custom_params_encoder=custom_params_encoder,
|
| 661 |
+
custom_result_decoder=custom_result_decoder,
|
| 662 |
+
)
|
| 663 |
+
assert get is not None, (
|
| 664 |
+
"remote cache should get(key) if insert(key, _) failed"
|
| 665 |
+
)
|
| 666 |
+
dur = time() - start_t
|
| 667 |
+
_intf_callback(
|
| 668 |
+
_IntfCallbackOrigin.RECORD,
|
| 669 |
+
_IntfCallbackAction.RECORD_NOT_INSERTED_REPLAY,
|
| 670 |
+
dur,
|
| 671 |
+
fn,
|
| 672 |
+
params,
|
| 673 |
+
fn_dur,
|
| 674 |
+
get.value,
|
| 675 |
+
)
|
| 676 |
+
return get.value
|
| 677 |
+
dur = time() - start_t
|
| 678 |
+
_intf_callback(
|
| 679 |
+
_IntfCallbackOrigin.RECORD,
|
| 680 |
+
_IntfCallbackAction.RECORD_INSERTED,
|
| 681 |
+
dur,
|
| 682 |
+
fn,
|
| 683 |
+
params,
|
| 684 |
+
result,
|
| 685 |
+
fn_dur,
|
| 686 |
+
)
|
| 687 |
+
return result
|
| 688 |
+
|
| 689 |
+
return wrapper
|
| 690 |
+
|
| 691 |
+
@override
|
| 692 |
+
def _get(
|
| 693 |
+
self,
|
| 694 |
+
fn: Callable[P, R],
|
| 695 |
+
params: Params,
|
| 696 |
+
ischema: context.IsolationSchema | None = None,
|
| 697 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 698 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 699 |
+
) -> impls.Hit | None:
|
| 700 |
+
key: Any = self._make_key(
|
| 701 |
+
fn, params, ischema=ischema, custom_params_encoder=custom_params_encoder
|
| 702 |
+
)
|
| 703 |
+
sc: impls._OnDiskCacheImpl | impls._RemoteCacheImpl | None = (
|
| 704 |
+
self._get_sc_from_callee(fn.__name__)
|
| 705 |
+
)
|
| 706 |
+
with locks._acquire_many_impl_locks_with_timeout(
|
| 707 |
+
*([self._imc, sc] if sc else [self._imc])
|
| 708 |
+
):
|
| 709 |
+
try:
|
| 710 |
+
# we'll check the memoization first, since that is much faster
|
| 711 |
+
# than checking the remote cache and the two should be consistent
|
| 712 |
+
imc_get: impls.Hit | None = self._imc.get(key)
|
| 713 |
+
if imc_get:
|
| 714 |
+
if custom_result_decoder:
|
| 715 |
+
return impls.Hit(value=custom_result_decoder(imc_get.value))
|
| 716 |
+
else:
|
| 717 |
+
return imc_get
|
| 718 |
+
elif not sc:
|
| 719 |
+
raise exceptions.StrictDeterministicCachingKeyNotFoundError
|
| 720 |
+
else:
|
| 721 |
+
sc_get: impls.Hit | None = sc.get(key)
|
| 722 |
+
if sc_get:
|
| 723 |
+
if custom_result_decoder:
|
| 724 |
+
return impls.Hit(value=custom_result_decoder(sc_get.value))
|
| 725 |
+
return sc_get
|
| 726 |
+
elif config.STRICTLY_CACHED_DETERMINISM:
|
| 727 |
+
raise exceptions.StrictDeterministicCachingKeyNotFoundError
|
| 728 |
+
return None
|
| 729 |
+
except exceptions.KeyEncodingError as err:
|
| 730 |
+
raise exceptions.CustomParamsEncoderRequiredError(fn, params) from err
|
| 731 |
+
|
| 732 |
+
@override
|
| 733 |
+
def _insert(
|
| 734 |
+
self,
|
| 735 |
+
fn: Callable[P, R],
|
| 736 |
+
params: Params,
|
| 737 |
+
result: R,
|
| 738 |
+
ischema: context.IsolationSchema | None = None,
|
| 739 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 740 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 741 |
+
) -> bool:
|
| 742 |
+
if (
|
| 743 |
+
config.STRICTLY_PRE_POPULATED_DETERMINISM
|
| 744 |
+
or config.STRICTLY_CACHED_DETERMINISM
|
| 745 |
+
):
|
| 746 |
+
raise exceptions.StrictDeterministicCachingInsertionError
|
| 747 |
+
|
| 748 |
+
key: Any = self._make_key(
|
| 749 |
+
fn, params, ischema=ischema, custom_params_encoder=custom_params_encoder
|
| 750 |
+
)
|
| 751 |
+
sc: impls._OnDiskCacheImpl | impls._RemoteCacheImpl | None = (
|
| 752 |
+
self._get_sc_from_callee(fn.__name__)
|
| 753 |
+
)
|
| 754 |
+
assert sc, (
|
| 755 |
+
"sc should be either an on-disk cache or a remote cache if we're inserting"
|
| 756 |
+
)
|
| 757 |
+
with locks._acquire_many_impl_locks_with_timeout(self._imc, sc):
|
| 758 |
+
try:
|
| 759 |
+
encoded_result: Any = (
|
| 760 |
+
result
|
| 761 |
+
if not custom_result_encoder
|
| 762 |
+
else custom_result_encoder(result)
|
| 763 |
+
)
|
| 764 |
+
# reverse order of get, as we don't want to memoize values
|
| 765 |
+
# if we haven't actually inserted them into the remote cache
|
| 766 |
+
# so that the memoization and the remote cache remain consistent
|
| 767 |
+
if sc.insert(key, encoded_result):
|
| 768 |
+
if not self._imc.insert(key, encoded_result):
|
| 769 |
+
# imc might have the mapping already, if pre-populated
|
| 770 |
+
assert self._imc.get(key) == encoded_result
|
| 771 |
+
return True
|
| 772 |
+
return False
|
| 773 |
+
except exceptions.KeyEncodingError as err:
|
| 774 |
+
raise exceptions.CustomParamsEncoderRequiredError(fn, params) from err
|
| 775 |
+
except exceptions.ValueEncodingError as err:
|
| 776 |
+
raise exceptions.CustomResultEncoderRequiredError(
|
| 777 |
+
f"Custom result encoder required for function {fn} with parameters {params} and result {result}."
|
| 778 |
+
) from err
|
| 779 |
+
|
| 780 |
+
@override
|
| 781 |
+
def get(
|
| 782 |
+
self,
|
| 783 |
+
fn: Callable[P, R],
|
| 784 |
+
params: Params,
|
| 785 |
+
ischema: context.IsolationSchema | None = None,
|
| 786 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 787 |
+
custom_result_decoder: Callable[[Any], R] | None = None,
|
| 788 |
+
) -> impls.Hit | None:
|
| 789 |
+
if not config.IS_DETERMINISTIC_CACHING_ENABLED():
|
| 790 |
+
raise exceptions.DeterministicCachingDisabledError
|
| 791 |
+
return super().get(
|
| 792 |
+
fn,
|
| 793 |
+
params,
|
| 794 |
+
ischema=ischema,
|
| 795 |
+
custom_params_encoder=custom_params_encoder,
|
| 796 |
+
custom_result_decoder=custom_result_decoder,
|
| 797 |
+
)
|
| 798 |
+
|
| 799 |
+
@override
|
| 800 |
+
def insert(
|
| 801 |
+
self,
|
| 802 |
+
fn: Callable[P, R],
|
| 803 |
+
params: Params,
|
| 804 |
+
result: R,
|
| 805 |
+
ischema: context.IsolationSchema | None = None,
|
| 806 |
+
custom_params_encoder: Callable[P, Any] | None = None,
|
| 807 |
+
custom_result_encoder: Callable[[R], Any] | None = None,
|
| 808 |
+
) -> bool:
|
| 809 |
+
if not config.IS_DETERMINISTIC_CACHING_ENABLED():
|
| 810 |
+
raise exceptions.DeterministicCachingDisabledError
|
| 811 |
+
return super().insert(
|
| 812 |
+
fn,
|
| 813 |
+
params,
|
| 814 |
+
result,
|
| 815 |
+
ischema=ischema,
|
| 816 |
+
custom_params_encoder=custom_params_encoder,
|
| 817 |
+
custom_result_encoder=custom_result_encoder,
|
| 818 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/locks.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lock acquisition utilities for caching system with timeout support.
|
| 2 |
+
|
| 3 |
+
This module provides safe and unsafe lock acquisition functions for both threading.Lock
|
| 4 |
+
and FileLock objects, with configurable timeout behaviors. It supports three timeout modes:
|
| 5 |
+
blocking (infinite wait), non-blocking (immediate), and blocking with timeout (finite wait).
|
| 6 |
+
|
| 7 |
+
The module offers both context manager and manual acquisition patterns:
|
| 8 |
+
- Safe acquisition: Uses context managers that automatically handle lock release
|
| 9 |
+
- Unsafe acquisition: Manual acquisition that requires explicit release by the caller
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from contextlib import _GeneratorContextManager, contextmanager, ExitStack
|
| 15 |
+
from typing import TYPE_CHECKING, TypeAlias
|
| 16 |
+
from typing_extensions import Protocol
|
| 17 |
+
|
| 18 |
+
from filelock import FileLock, Timeout
|
| 19 |
+
|
| 20 |
+
from . import exceptions, implementations as impls
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from collections.abc import Generator
|
| 25 |
+
from threading import Lock
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
_LockContextManager: TypeAlias = _GeneratorContextManager[None, None, None]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class _LockProtocol(Protocol): # noqa: PYI046
|
| 32 |
+
def __call__(self, timeout: float | None = None) -> _LockContextManager: ...
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Infinite timeout - blocks indefinitely until lock is acquired.
|
| 36 |
+
_BLOCKING: float = -1
|
| 37 |
+
# No timeout - returns immediately if lock cannot be acquired.
|
| 38 |
+
_NON_BLOCKING: float = 0
|
| 39 |
+
# Finite timeout - blocks for a specified duration before raising a timeout error.
|
| 40 |
+
_BLOCKING_WITH_TIMEOUT: float = 60.0
|
| 41 |
+
# Default timeout for lock acquisition.
|
| 42 |
+
_DEFAULT_TIMEOUT: float = _BLOCKING_WITH_TIMEOUT
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@contextmanager
|
| 46 |
+
def _acquire_lock_with_timeout(
|
| 47 |
+
lock: Lock,
|
| 48 |
+
timeout: float | None = None,
|
| 49 |
+
) -> Generator[None, None, None]:
|
| 50 |
+
"""Context manager that safely acquires a threading.Lock with timeout and automatically releases it.
|
| 51 |
+
|
| 52 |
+
This function provides a safe way to acquire a lock with timeout support, ensuring
|
| 53 |
+
the lock is always released even if an exception occurs during execution.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
lock: The threading.Lock object to acquire
|
| 57 |
+
timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT.
|
| 58 |
+
- Use _BLOCKING (-1.0) for infinite wait
|
| 59 |
+
- Use _NON_BLOCKING (0.0) for immediate return
|
| 60 |
+
- Use positive value for finite timeout
|
| 61 |
+
|
| 62 |
+
Yields:
|
| 63 |
+
None: Yields control to the caller while holding the lock
|
| 64 |
+
|
| 65 |
+
Raises:
|
| 66 |
+
LockTimeoutError: If the lock cannot be acquired within the timeout period
|
| 67 |
+
|
| 68 |
+
Example:
|
| 69 |
+
with _acquire_lock_with_timeout(my_lock, timeout=30.0):
|
| 70 |
+
# Critical section - lock is held
|
| 71 |
+
perform_critical_operation()
|
| 72 |
+
# Lock is automatically released here
|
| 73 |
+
"""
|
| 74 |
+
_unsafe_acquire_lock_with_timeout(lock, timeout=timeout)
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
yield
|
| 78 |
+
finally:
|
| 79 |
+
lock.release()
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _unsafe_acquire_lock_with_timeout(lock: Lock, timeout: float | None = None) -> None:
|
| 83 |
+
"""Acquire a threading.Lock with timeout without automatic release (unsafe).
|
| 84 |
+
|
| 85 |
+
This function acquires a lock with timeout support but does NOT automatically
|
| 86 |
+
release it. The caller is responsible for releasing the lock explicitly.
|
| 87 |
+
Use this only when you need manual control over lock lifetime.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
lock: The threading.Lock object to acquire
|
| 91 |
+
timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT.
|
| 92 |
+
- Use _BLOCKING (-1.0) for infinite wait
|
| 93 |
+
- Use _NON_BLOCKING (0.0) for immediate return
|
| 94 |
+
- Use positive value for finite timeout
|
| 95 |
+
|
| 96 |
+
Raises:
|
| 97 |
+
LockTimeoutError: If the lock cannot be acquired within the timeout period
|
| 98 |
+
|
| 99 |
+
Warning:
|
| 100 |
+
This is an "unsafe" function because it does not automatically release
|
| 101 |
+
the lock. Always call lock.release() when done, preferably in a try/finally
|
| 102 |
+
block or use the safe _acquire_lock_with_timeout context manager instead.
|
| 103 |
+
|
| 104 |
+
Example:
|
| 105 |
+
lock = Lock()
|
| 106 |
+
try:
|
| 107 |
+
_unsafe_acquire_lock_with_timeout(lock, timeout=30.0)
|
| 108 |
+
# Critical section - lock is held
|
| 109 |
+
perform_critical_operation()
|
| 110 |
+
finally:
|
| 111 |
+
lock.release() # Must manually release!
|
| 112 |
+
"""
|
| 113 |
+
_timeout: float = timeout if timeout is not None else _DEFAULT_TIMEOUT
|
| 114 |
+
if not lock.acquire(timeout=_timeout):
|
| 115 |
+
raise exceptions.LockTimeoutError(lock, _timeout)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@contextmanager
|
| 119 |
+
def _acquire_flock_with_timeout(
|
| 120 |
+
flock: FileLock,
|
| 121 |
+
timeout: float | None = None,
|
| 122 |
+
) -> Generator[None, None, None]:
|
| 123 |
+
"""Context manager that safely acquires a FileLock with timeout and automatically releases it.
|
| 124 |
+
|
| 125 |
+
This function provides a safe way to acquire a file lock with timeout support, ensuring
|
| 126 |
+
the lock is always released even if an exception occurs during execution.
|
| 127 |
+
|
| 128 |
+
Args:
|
| 129 |
+
flock: The FileLock object to acquire
|
| 130 |
+
timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT.
|
| 131 |
+
- Use _BLOCKING (-1.0) for infinite wait
|
| 132 |
+
- Use _NON_BLOCKING (0.0) for immediate return
|
| 133 |
+
- Use positive value for finite timeout
|
| 134 |
+
|
| 135 |
+
Yields:
|
| 136 |
+
None: Yields control to the caller while holding the file lock
|
| 137 |
+
|
| 138 |
+
Raises:
|
| 139 |
+
FileLockTimeoutError: If the file lock cannot be acquired within the timeout period
|
| 140 |
+
|
| 141 |
+
Example:
|
| 142 |
+
flock = FileLock("/tmp/my_process.lock")
|
| 143 |
+
with _acquire_flock_with_timeout(flock, timeout=30.0):
|
| 144 |
+
# Critical section - file lock is held
|
| 145 |
+
perform_exclusive_file_operation()
|
| 146 |
+
# File lock is automatically released here
|
| 147 |
+
"""
|
| 148 |
+
_unsafe_acquire_flock_with_timeout(flock, timeout=timeout)
|
| 149 |
+
|
| 150 |
+
try:
|
| 151 |
+
yield
|
| 152 |
+
finally:
|
| 153 |
+
flock.release()
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _unsafe_acquire_flock_with_timeout(flock: FileLock, timeout: float | None) -> None:
|
| 157 |
+
"""Acquire a FileLock with timeout without automatic release (unsafe).
|
| 158 |
+
|
| 159 |
+
This function acquires a file lock with timeout support but does NOT automatically
|
| 160 |
+
release it. The caller is responsible for releasing the lock explicitly.
|
| 161 |
+
Use this only when you need manual control over lock lifetime.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
flock: The FileLock object to acquire
|
| 165 |
+
timeout: Timeout in seconds. If None, uses _DEFAULT_TIMEOUT.
|
| 166 |
+
- Use _BLOCKING (-1.0) for infinite wait
|
| 167 |
+
- Use _NON_BLOCKING (0.0) for immediate return
|
| 168 |
+
- Use positive value for finite timeout
|
| 169 |
+
|
| 170 |
+
Raises:
|
| 171 |
+
FileLockTimeoutError: If the file lock cannot be acquired within the timeout period
|
| 172 |
+
|
| 173 |
+
Warning:
|
| 174 |
+
This is an "unsafe" function because it does not automatically release
|
| 175 |
+
the lock. Always call flock.release() when done, preferably in a try/finally
|
| 176 |
+
block or use the safe _acquire_flock_with_timeout context manager instead.
|
| 177 |
+
|
| 178 |
+
Example:
|
| 179 |
+
flock = FileLock("/tmp/my_process.lock")
|
| 180 |
+
try:
|
| 181 |
+
_unsafe_acquire_flock_with_timeout(flock, timeout=30.0)
|
| 182 |
+
# Critical section - file lock is held
|
| 183 |
+
perform_exclusive_file_operation()
|
| 184 |
+
finally:
|
| 185 |
+
flock.release() # Must manually release!
|
| 186 |
+
"""
|
| 187 |
+
_timeout: float = timeout if timeout is not None else _DEFAULT_TIMEOUT
|
| 188 |
+
try:
|
| 189 |
+
_ = flock.acquire(timeout=_timeout)
|
| 190 |
+
except Timeout as err:
|
| 191 |
+
raise exceptions.FileLockTimeoutError(flock, _timeout) from err
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@contextmanager
|
| 195 |
+
def _acquire_many_impl_locks_with_timeout(
|
| 196 |
+
*impls: impls._CacheImpl,
|
| 197 |
+
timeout: float | None = None,
|
| 198 |
+
) -> Generator[None, None, None]:
|
| 199 |
+
with ExitStack() as stack:
|
| 200 |
+
for impl in impls:
|
| 201 |
+
stack.enter_context(impl.lock(timeout))
|
| 202 |
+
yield
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/caching/utils.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utility functions for caching operations in PyTorch Inductor runtime.
|
| 2 |
+
|
| 3 |
+
This module provides helper functions for pickling/unpickling operations
|
| 4 |
+
with error handling, LRU caching decorators, and type-safe serialization
|
| 5 |
+
utilities used throughout the caching system.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import pickle
|
| 9 |
+
from collections.abc import Callable
|
| 10 |
+
from functools import lru_cache, partial, wraps
|
| 11 |
+
from typing import Any
|
| 12 |
+
from typing_extensions import ParamSpec, TypeVar
|
| 13 |
+
|
| 14 |
+
from . import exceptions
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# Type specification for function parameters
|
| 18 |
+
P = ParamSpec("P")
|
| 19 |
+
# Type variable for function return values
|
| 20 |
+
R = TypeVar("R")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _lru_cache(fn: Callable[P, R]) -> Callable[P, R]:
|
| 24 |
+
"""LRU cache decorator with TypeError fallback.
|
| 25 |
+
|
| 26 |
+
Provides LRU caching with a fallback mechanism that calls the original
|
| 27 |
+
function if caching fails due to unhashable arguments. Uses a cache
|
| 28 |
+
size of 64 with typed comparison.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
fn: The function to be cached.
|
| 32 |
+
|
| 33 |
+
Returns:
|
| 34 |
+
A wrapper function that attempts caching with fallback to original function.
|
| 35 |
+
"""
|
| 36 |
+
cached_fn = lru_cache(maxsize=64, typed=True)(fn)
|
| 37 |
+
|
| 38 |
+
@wraps(fn)
|
| 39 |
+
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: # type: ignore[type-var]
|
| 40 |
+
try:
|
| 41 |
+
return cached_fn(*args, **kwargs) # type: ignore[arg-type]
|
| 42 |
+
except TypeError:
|
| 43 |
+
return fn(*args, **kwargs)
|
| 44 |
+
|
| 45 |
+
return wrapper
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@_lru_cache
|
| 49 |
+
def _try_pickle(to_pickle: Any, raise_if_failed: type = exceptions.CacheError) -> bytes:
|
| 50 |
+
"""Attempt to pickle an object with error handling.
|
| 51 |
+
|
| 52 |
+
Tries to serialize an object using pickle.dumps with appropriate error
|
| 53 |
+
handling and custom exception raising.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
to_pickle: The object to be pickled.
|
| 57 |
+
raise_if_failed: Exception class to raise if pickling fails.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
The pickled bytes representation of the object.
|
| 61 |
+
|
| 62 |
+
Raises:
|
| 63 |
+
The exception class specified in raise_if_failed if pickling fails.
|
| 64 |
+
"""
|
| 65 |
+
try:
|
| 66 |
+
pickled: bytes = pickle.dumps(to_pickle)
|
| 67 |
+
except (pickle.PicklingError, AttributeError) as err:
|
| 68 |
+
raise raise_if_failed(to_pickle) from err
|
| 69 |
+
return pickled
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# Specialized pickle function for cache keys with KeyPicklingError handling.
|
| 73 |
+
_try_pickle_key: Callable[[Any], bytes] = partial(
|
| 74 |
+
_try_pickle, raise_if_failed=exceptions.KeyPicklingError
|
| 75 |
+
)
|
| 76 |
+
# Specialized pickle function for cache values with ValuePicklingError handling.
|
| 77 |
+
_try_pickle_value: Callable[[Any], bytes] = partial(
|
| 78 |
+
_try_pickle, raise_if_failed=exceptions.ValuePicklingError
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@_lru_cache
|
| 83 |
+
def _try_unpickle(pickled: bytes, raise_if_failed: type = exceptions.CacheError) -> Any:
|
| 84 |
+
"""Attempt to unpickle bytes with error handling.
|
| 85 |
+
|
| 86 |
+
Tries to deserialize bytes using pickle.loads with appropriate error
|
| 87 |
+
handling and custom exception raising.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
pickled: The bytes to be unpickled.
|
| 91 |
+
raise_if_failed: Exception class to raise if unpickling fails.
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
The unpickled object.
|
| 95 |
+
|
| 96 |
+
Raises:
|
| 97 |
+
The exception class specified in raise_if_failed if unpickling fails.
|
| 98 |
+
"""
|
| 99 |
+
try:
|
| 100 |
+
unpickled: Any = pickle.loads(pickled)
|
| 101 |
+
except pickle.UnpicklingError as err:
|
| 102 |
+
raise raise_if_failed(pickled) from err
|
| 103 |
+
return unpickled
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
# Specialized unpickle function for cache keys with KeyUnPicklingError handling.
|
| 107 |
+
_try_unpickle_value: Callable[[Any], bytes] = partial(
|
| 108 |
+
_try_unpickle, raise_if_failed=exceptions.ValueUnPicklingError
|
| 109 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/compile_tasks.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import linecache
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import time
|
| 8 |
+
import warnings
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from types import ModuleType
|
| 11 |
+
from typing import Any, TYPE_CHECKING
|
| 12 |
+
|
| 13 |
+
from torch._utils_internal import log_triton_builds
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from collections.abc import Callable
|
| 18 |
+
|
| 19 |
+
from torch._inductor.runtime.triton_heuristics import CachingAutotuner
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _reload_python_module(
|
| 23 |
+
key: str, path: str, set_sys_modules: bool = True
|
| 24 |
+
) -> ModuleType:
|
| 25 |
+
with open(path) as f:
|
| 26 |
+
try:
|
| 27 |
+
code = compile(f.read(), path, "exec", dont_inherit=True)
|
| 28 |
+
except Exception as e:
|
| 29 |
+
raise RuntimeError(
|
| 30 |
+
f"Failed to import {path}\n{type(e).__name__}: {e}"
|
| 31 |
+
) from None
|
| 32 |
+
mod = ModuleType(f"{__name__}.{key}")
|
| 33 |
+
mod.__file__ = path
|
| 34 |
+
mod.key = key # type: ignore[attr-defined]
|
| 35 |
+
exec(code, mod.__dict__, mod.__dict__)
|
| 36 |
+
if set_sys_modules:
|
| 37 |
+
sys.modules[mod.__name__] = mod
|
| 38 |
+
return mod
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@functools.cache
|
| 42 |
+
def _set_triton_ptxas_path() -> None:
|
| 43 |
+
if os.environ.get("TRITON_PTXAS_PATH") is not None:
|
| 44 |
+
return
|
| 45 |
+
ptxas = Path(__file__).absolute().parents[2] / "bin" / "ptxas"
|
| 46 |
+
if not ptxas.exists():
|
| 47 |
+
return
|
| 48 |
+
if ptxas.is_file() and os.access(ptxas, os.X_OK):
|
| 49 |
+
os.environ["TRITON_PTXAS_PATH"] = str(ptxas)
|
| 50 |
+
else:
|
| 51 |
+
warnings.warn(f"{ptxas} exists but is not an executable")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _worker_compile_triton(
|
| 55 |
+
load_kernel: Callable[[], CachingAutotuner],
|
| 56 |
+
extra_env: dict[str, str],
|
| 57 |
+
extra_config: dict[str, Any],
|
| 58 |
+
) -> tuple[CachingAutotuner, int]:
|
| 59 |
+
_set_triton_ptxas_path()
|
| 60 |
+
os.environ.update(extra_env)
|
| 61 |
+
from torch._inductor import config
|
| 62 |
+
|
| 63 |
+
with config.patch(extra_config):
|
| 64 |
+
fail = None
|
| 65 |
+
try:
|
| 66 |
+
start_ns = time.time_ns()
|
| 67 |
+
kernel = load_kernel()
|
| 68 |
+
kernel.precompile(warm_cache_only=True)
|
| 69 |
+
elapsed_ns = time.time_ns() - start_ns
|
| 70 |
+
kernel.prepare_for_pickle()
|
| 71 |
+
# We can release this memory in the compile subprocesses:
|
| 72 |
+
linecache.clearcache()
|
| 73 |
+
return kernel, elapsed_ns // 1000
|
| 74 |
+
except Exception as e:
|
| 75 |
+
fail = str(e)
|
| 76 |
+
raise
|
| 77 |
+
finally:
|
| 78 |
+
log_triton_builds(fail=fail)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/coordinate_descent_tuner.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import copy
|
| 3 |
+
import itertools
|
| 4 |
+
import logging
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
from typing import TYPE_CHECKING
|
| 7 |
+
|
| 8 |
+
from torch.utils._ordered_set import OrderedSet
|
| 9 |
+
|
| 10 |
+
from ..utils import get_max_numwarps
|
| 11 |
+
from .hints import TRITON_MAX_BLOCK
|
| 12 |
+
from .runtime_utils import red_text, triton_config_to_hashable
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
if TYPE_CHECKING:
|
| 16 |
+
from .triton_compat import triton
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
log = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_field(config, name):
|
| 23 |
+
if name == "num_warps":
|
| 24 |
+
return config.num_warps
|
| 25 |
+
elif name == "num_stages":
|
| 26 |
+
return config.num_stages
|
| 27 |
+
elif name == "waves_per_eu":
|
| 28 |
+
return config.kwargs.get(name, int(8 // config.num_warps))
|
| 29 |
+
else:
|
| 30 |
+
return config.kwargs.get(name, None)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def set_field(config, name, value):
|
| 34 |
+
if name == "num_warps":
|
| 35 |
+
config.num_warps = value
|
| 36 |
+
elif name == "num_stages":
|
| 37 |
+
config.num_stages = value
|
| 38 |
+
else:
|
| 39 |
+
config.kwargs[name] = value
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class CoordescTuner:
|
| 43 |
+
"""
|
| 44 |
+
The coordinate descent tuner. Tune one field/coordinate at a time.
|
| 45 |
+
|
| 46 |
+
TODO will it be necessary to tune multiple fields simultaneously.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
TODO: what if both increasing and decreasing a field can improve perf.
|
| 50 |
+
i.e., there are multiple local optima..
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
is_mm=False,
|
| 56 |
+
is_native_matmul=False,
|
| 57 |
+
is_mix_order_reduction=False,
|
| 58 |
+
name="unknown",
|
| 59 |
+
size_hints=None,
|
| 60 |
+
inductor_meta=None,
|
| 61 |
+
frozen_fields=None,
|
| 62 |
+
):
|
| 63 |
+
self.is_mm = is_mm # we will tune num_stages for mm
|
| 64 |
+
|
| 65 |
+
# Native matmul codegen assumes ZBLOCK=1 always.
|
| 66 |
+
# This is because 3d tl.dot is slow and so we want to tile y and x only.
|
| 67 |
+
# tl.dot also does not support size smaller than 16; we put this restriction.
|
| 68 |
+
self.is_native_matmul = is_native_matmul
|
| 69 |
+
assert not (self.is_mm and self.is_native_matmul)
|
| 70 |
+
self.is_mix_order_reduction = is_mix_order_reduction
|
| 71 |
+
self.cached_benchmark_results = {}
|
| 72 |
+
self.name = name
|
| 73 |
+
self.size_hints = size_hints
|
| 74 |
+
self.inductor_meta = inductor_meta or {}
|
| 75 |
+
self.frozen_fields: OrderedSet[str] = (
|
| 76 |
+
OrderedSet(frozen_fields) if frozen_fields is not None else OrderedSet()
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def get_config_max(self, prefix: str) -> int:
|
| 80 |
+
max_block = TRITON_MAX_BLOCK[prefix.upper()]
|
| 81 |
+
size_hint = self.size_hints.get(prefix) if self.size_hints is not None else None
|
| 82 |
+
return min(max_block, size_hint) if size_hint is not None else max_block
|
| 83 |
+
|
| 84 |
+
def get_warpsmax(self):
|
| 85 |
+
# Avoid querying device directly if device properties are populated in inductor_meta
|
| 86 |
+
warp_size = self.inductor_meta.get("warp_size")
|
| 87 |
+
max_threads_per_block = self.inductor_meta.get("max_threads_per_block")
|
| 88 |
+
if warp_size and max_threads_per_block:
|
| 89 |
+
return max_threads_per_block // warp_size
|
| 90 |
+
else:
|
| 91 |
+
return get_max_numwarps()
|
| 92 |
+
|
| 93 |
+
def cache_benchmark_result(self, config, timing):
|
| 94 |
+
self.cached_benchmark_results[triton_config_to_hashable(config)] = timing
|
| 95 |
+
|
| 96 |
+
def lookup_in_cache(self, config):
|
| 97 |
+
return self.cached_benchmark_results.get(triton_config_to_hashable(config))
|
| 98 |
+
|
| 99 |
+
def call_func(self, func, config):
|
| 100 |
+
found = self.lookup_in_cache(config)
|
| 101 |
+
if found is not None:
|
| 102 |
+
log.debug(" CACHED")
|
| 103 |
+
return found
|
| 104 |
+
timing = func(config)
|
| 105 |
+
self.cache_benchmark_result(config, timing)
|
| 106 |
+
return timing
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def tunable_fields(self):
|
| 110 |
+
out = [
|
| 111 |
+
"XBLOCK",
|
| 112 |
+
"YBLOCK",
|
| 113 |
+
"ZBLOCK",
|
| 114 |
+
# NOTE: we should not tune R0_BLOCK for persistent reduction.
|
| 115 |
+
# We rely on the fact that persistent reduction's triton.Config
|
| 116 |
+
# does not have the R0_BLOCK field to guarantee that.
|
| 117 |
+
"R0_BLOCK",
|
| 118 |
+
"R1_BLOCK",
|
| 119 |
+
# the following 3 are for mm
|
| 120 |
+
"BLOCK_M",
|
| 121 |
+
"BLOCK_N",
|
| 122 |
+
"BLOCK_K",
|
| 123 |
+
"num_warps",
|
| 124 |
+
]
|
| 125 |
+
if self.is_mm:
|
| 126 |
+
out.append("num_stages")
|
| 127 |
+
if self.inductor_meta.get("is_hip") is True:
|
| 128 |
+
out.append("waves_per_eu")
|
| 129 |
+
if self.is_native_matmul:
|
| 130 |
+
out.append("num_stages")
|
| 131 |
+
out.remove("ZBLOCK") # ZBLOCK=1 always in native matmul
|
| 132 |
+
|
| 133 |
+
if self.is_mix_order_reduction:
|
| 134 |
+
# unlike TritonConfig.num_stages, this one is
|
| 135 |
+
# put in TritonConfig.kwargs["NUM_STAGES"] and is used to
|
| 136 |
+
# control the stage of pipelining of tl.range.
|
| 137 |
+
out.append("NUM_STAGES")
|
| 138 |
+
|
| 139 |
+
return [f for f in out if f not in self.frozen_fields]
|
| 140 |
+
|
| 141 |
+
def value_too_large(self, name: str, val: int) -> bool:
|
| 142 |
+
block_suffix = "BLOCK"
|
| 143 |
+
if name.endswith(block_suffix):
|
| 144 |
+
prefix = name.strip(block_suffix).lower()
|
| 145 |
+
return val > self.get_config_max(prefix)
|
| 146 |
+
if name == "num_warps":
|
| 147 |
+
return val > self.get_warpsmax()
|
| 148 |
+
if name == "waves_per_eu":
|
| 149 |
+
return val > 8
|
| 150 |
+
|
| 151 |
+
return False
|
| 152 |
+
|
| 153 |
+
def value_too_small(self, name: str, val: int) -> bool:
|
| 154 |
+
# In native matmul, block size should be >= 16 for tl.dot
|
| 155 |
+
if self.is_native_matmul:
|
| 156 |
+
if name in ["YBLOCK", "XBLOCK", "R0_BLOCK"]:
|
| 157 |
+
return val < 16
|
| 158 |
+
|
| 159 |
+
# Break if value becomes 0/neg
|
| 160 |
+
return val <= 0
|
| 161 |
+
|
| 162 |
+
def get_neighbour_values(self, name, orig_val, radius=None, include_self=False):
|
| 163 |
+
"""
|
| 164 |
+
Get neighbour values in 'radius' steps. The original value is not
|
| 165 |
+
returned as it's own neighbour.
|
| 166 |
+
"""
|
| 167 |
+
if radius is None:
|
| 168 |
+
radius = 1
|
| 169 |
+
if name == "NUM_STAGES":
|
| 170 |
+
# we see cases that
|
| 171 |
+
# NUM_STAGES=1 is better than NUM_STAGES=2
|
| 172 |
+
# while NUM_STAGES=1 is worse than NUM_STAGES=3
|
| 173 |
+
radius = max(radius, 2)
|
| 174 |
+
|
| 175 |
+
assert radius >= 1
|
| 176 |
+
|
| 177 |
+
def update(cur_val, inc=True):
|
| 178 |
+
if name in ["num_stages", "NUM_STAGES"]:
|
| 179 |
+
if inc:
|
| 180 |
+
return cur_val + 1
|
| 181 |
+
else:
|
| 182 |
+
return cur_val - 1
|
| 183 |
+
else:
|
| 184 |
+
if inc:
|
| 185 |
+
return cur_val * 2
|
| 186 |
+
else:
|
| 187 |
+
return cur_val // 2
|
| 188 |
+
|
| 189 |
+
out = []
|
| 190 |
+
# increment loop
|
| 191 |
+
cur_val = orig_val
|
| 192 |
+
for _ in range(radius):
|
| 193 |
+
cur_val = update(cur_val, True)
|
| 194 |
+
if self.value_too_large(name, cur_val):
|
| 195 |
+
break
|
| 196 |
+
out.append(cur_val)
|
| 197 |
+
|
| 198 |
+
# decrement loop
|
| 199 |
+
cur_val = orig_val
|
| 200 |
+
for _ in range(radius):
|
| 201 |
+
cur_val = update(cur_val, False)
|
| 202 |
+
if self.value_too_small(name, cur_val):
|
| 203 |
+
break
|
| 204 |
+
out.append(cur_val)
|
| 205 |
+
|
| 206 |
+
if include_self:
|
| 207 |
+
out.append(orig_val)
|
| 208 |
+
return out
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def has_improvement(baseline, test):
|
| 212 |
+
threshold = 0.001 # 0.1%
|
| 213 |
+
return test is not None and test < baseline * (1 - threshold)
|
| 214 |
+
|
| 215 |
+
def is_valid_config(self, config) -> bool:
|
| 216 |
+
if self.is_mix_order_reduction:
|
| 217 |
+
# Mix order reduction has an extra constraint that
|
| 218 |
+
# we should not tune XBLOCK beyond RSPLIT_SIZE
|
| 219 |
+
xblock = config.kwargs["XBLOCK"]
|
| 220 |
+
split_size = config.kwargs["RSPLIT_SIZE"]
|
| 221 |
+
return xblock <= split_size
|
| 222 |
+
return True
|
| 223 |
+
|
| 224 |
+
def check_all_tuning_directions(
|
| 225 |
+
self,
|
| 226 |
+
# pyrefly: ignore [missing-attribute]
|
| 227 |
+
func: Callable[["triton.Config"], float],
|
| 228 |
+
best_config,
|
| 229 |
+
best_timing,
|
| 230 |
+
):
|
| 231 |
+
"""
|
| 232 |
+
Check all directions. We only do this once the regular coordinate
|
| 233 |
+
descent tuning find no better choices any more.
|
| 234 |
+
We only have a few tunable fields, so this should be fine.
|
| 235 |
+
"""
|
| 236 |
+
candidate_values_list = []
|
| 237 |
+
effective_fields = []
|
| 238 |
+
for field in self.tunable_fields:
|
| 239 |
+
old_value = get_field(best_config, field)
|
| 240 |
+
if old_value is None:
|
| 241 |
+
continue
|
| 242 |
+
radius = self.inductor_meta.get("coordinate_descent_search_radius", 1)
|
| 243 |
+
candidate_values = self.get_neighbour_values(
|
| 244 |
+
field,
|
| 245 |
+
old_value,
|
| 246 |
+
radius=radius,
|
| 247 |
+
include_self=True,
|
| 248 |
+
)
|
| 249 |
+
candidate_values_list.append(candidate_values)
|
| 250 |
+
effective_fields.append(field)
|
| 251 |
+
|
| 252 |
+
choices = itertools.product(*candidate_values_list)
|
| 253 |
+
improved = False
|
| 254 |
+
for choice in choices:
|
| 255 |
+
assert len(choice) == len(effective_fields)
|
| 256 |
+
candidate_config = copy.deepcopy(best_config)
|
| 257 |
+
for new_val, field in zip(choice, effective_fields):
|
| 258 |
+
set_field(candidate_config, field, new_val)
|
| 259 |
+
if not self.is_valid_config(candidate_config):
|
| 260 |
+
continue
|
| 261 |
+
cmp_res, candidate_timing = self.compare_config(
|
| 262 |
+
func, candidate_config, best_config, best_timing
|
| 263 |
+
)
|
| 264 |
+
if cmp_res:
|
| 265 |
+
improved = True
|
| 266 |
+
best_config = candidate_config
|
| 267 |
+
best_timing = candidate_timing
|
| 268 |
+
|
| 269 |
+
return improved, best_config, best_timing
|
| 270 |
+
|
| 271 |
+
def compare_config(self, func, candidate_config, best_config, best_timing):
|
| 272 |
+
"""
|
| 273 |
+
Check if candidate_config is better than best_config.
|
| 274 |
+
|
| 275 |
+
Return a tuple of (compare_result, candidate_timing).
|
| 276 |
+
compare_result is true iff candidate_config is better.
|
| 277 |
+
"""
|
| 278 |
+
log.debug("Try config %s", candidate_config)
|
| 279 |
+
try:
|
| 280 |
+
candidate_timing = self.call_func(func, candidate_config)
|
| 281 |
+
except Exception as e:
|
| 282 |
+
log.debug("Got exception %s", e) # noqa: G200
|
| 283 |
+
return False, float("inf")
|
| 284 |
+
|
| 285 |
+
if self.has_improvement(best_timing, candidate_timing):
|
| 286 |
+
log.debug(
|
| 287 |
+
"Tune from %s %f -> %s %f",
|
| 288 |
+
best_config,
|
| 289 |
+
best_timing,
|
| 290 |
+
candidate_config,
|
| 291 |
+
candidate_timing,
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
return True, candidate_timing
|
| 295 |
+
return False, candidate_timing
|
| 296 |
+
|
| 297 |
+
def autotune(
|
| 298 |
+
self,
|
| 299 |
+
# pyrefly: ignore [missing-attribute]
|
| 300 |
+
func: Callable[["triton.Config"], float],
|
| 301 |
+
# pyrefly: ignore [missing-attribute]
|
| 302 |
+
baseline_config: "triton.Config",
|
| 303 |
+
baseline_timing: float | None = None,
|
| 304 |
+
) -> "triton.Config": # pyrefly: ignore # missing-attribute
|
| 305 |
+
if baseline_timing is None:
|
| 306 |
+
baseline_timing = self.call_func(func, baseline_config)
|
| 307 |
+
|
| 308 |
+
log.debug("= Do coordinate descent tuning for %s =", self.name)
|
| 309 |
+
log.debug(
|
| 310 |
+
"%s: Baseline Config %s, baseline timing %f",
|
| 311 |
+
self.name,
|
| 312 |
+
baseline_config,
|
| 313 |
+
baseline_timing,
|
| 314 |
+
)
|
| 315 |
+
improved = True
|
| 316 |
+
best_config = baseline_config
|
| 317 |
+
best_timing = baseline_timing
|
| 318 |
+
tunable_fields = self.tunable_fields
|
| 319 |
+
|
| 320 |
+
while improved:
|
| 321 |
+
improved = False
|
| 322 |
+
|
| 323 |
+
for name in tunable_fields:
|
| 324 |
+
cur_val = get_field(best_config, name)
|
| 325 |
+
# some kernel don't have R0_BLOCK/YBLOCK/ZBLOCK. So cur_val may be None
|
| 326 |
+
if cur_val is None:
|
| 327 |
+
continue
|
| 328 |
+
|
| 329 |
+
# It's possible that candidate_values is empty.
|
| 330 |
+
# E.g., if XBLOCK is 1 initially and size_hint for x is also 1.
|
| 331 |
+
# We would not try either larger or smaller XBLOCK in this case.
|
| 332 |
+
candidate_values = self.get_neighbour_values(name, cur_val)
|
| 333 |
+
|
| 334 |
+
for next_val in candidate_values:
|
| 335 |
+
candidate_config = copy.deepcopy(best_config)
|
| 336 |
+
set_field(candidate_config, name, next_val)
|
| 337 |
+
|
| 338 |
+
if not self.is_valid_config(candidate_config):
|
| 339 |
+
continue
|
| 340 |
+
cmp_res, candidate_timing = self.compare_config(
|
| 341 |
+
func, candidate_config, best_config, best_timing
|
| 342 |
+
)
|
| 343 |
+
if cmp_res:
|
| 344 |
+
improved = True
|
| 345 |
+
best_config, best_timing = candidate_config, candidate_timing
|
| 346 |
+
|
| 347 |
+
if not improved and self.inductor_meta.get(
|
| 348 |
+
"coordinate_descent_check_all_directions"
|
| 349 |
+
):
|
| 350 |
+
old_best_timing = best_timing
|
| 351 |
+
improved, best_config, best_timing = self.check_all_tuning_directions(
|
| 352 |
+
func, best_config, best_timing
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
if improved:
|
| 356 |
+
msg = red_text(
|
| 357 |
+
"%s: Coordinate descend tuning found improvement of %.3fx by looking in all directions."
|
| 358 |
+
)
|
| 359 |
+
log.debug(
|
| 360 |
+
msg,
|
| 361 |
+
self.name,
|
| 362 |
+
old_best_timing / best_timing,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
log.debug(
|
| 366 |
+
"%s: Improve from %s %f -> %s %f, %.3fx",
|
| 367 |
+
self.name,
|
| 368 |
+
baseline_config,
|
| 369 |
+
baseline_timing,
|
| 370 |
+
best_config,
|
| 371 |
+
best_timing,
|
| 372 |
+
baseline_timing / best_timing,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
return best_config
|
| 376 |
+
|
| 377 |
+
@staticmethod
|
| 378 |
+
def autotune_single_field(fn, init_val, min_val=None, max_val=None):
|
| 379 |
+
"""
|
| 380 |
+
fn is a function that takes the field value and returns the benchmarking result
|
| 381 |
+
init_val is the starting point of autotuning.
|
| 382 |
+
|
| 383 |
+
Should work well for parabola like curve. Here is a real example
|
| 384 |
+
for split-size of mix-order-reduction: https://github.com/pytorch/pytorch/pull/166461
|
| 385 |
+
"""
|
| 386 |
+
cache = {}
|
| 387 |
+
|
| 388 |
+
def _bench(val):
|
| 389 |
+
if val not in cache:
|
| 390 |
+
cache[val] = fn(val)
|
| 391 |
+
# print(f"split size {val} -> {cache[val]:.3f} ms")
|
| 392 |
+
return cache[val]
|
| 393 |
+
|
| 394 |
+
if min_val is None:
|
| 395 |
+
min_val = 1
|
| 396 |
+
if max_val is None:
|
| 397 |
+
max_val = 2**30 # some arbitrary large value
|
| 398 |
+
|
| 399 |
+
best_val = init_val
|
| 400 |
+
improved = True
|
| 401 |
+
while improved:
|
| 402 |
+
improved = False
|
| 403 |
+
candlist = [best_val // 2, best_val * 2]
|
| 404 |
+
for cand in candlist:
|
| 405 |
+
cand = max(cand, min_val)
|
| 406 |
+
cand = min(cand, max_val)
|
| 407 |
+
|
| 408 |
+
if _bench(cand) < _bench(best_val):
|
| 409 |
+
best_val = cand
|
| 410 |
+
improved = True
|
| 411 |
+
|
| 412 |
+
return best_val
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/debug_utils.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import logging
|
| 3 |
+
import threading
|
| 4 |
+
import weakref
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.utils._ordered_set import OrderedSet
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
log = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
local = threading.local()
|
| 13 |
+
local.memory_tracker = None
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BufferMemoryTracker:
|
| 17 |
+
"""
|
| 18 |
+
Tracks inductor runtime allocations and deallocations to compare against
|
| 19 |
+
expected behavior.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self) -> None:
|
| 23 |
+
self.tensor_tracker: dict[str, torch.storage.UntypedStorage] = (
|
| 24 |
+
weakref.WeakValueDictionary() # type: ignore[assignment]
|
| 25 |
+
)
|
| 26 |
+
self.died_since_last_step: OrderedSet[str] = OrderedSet()
|
| 27 |
+
self.added_since_last_step: OrderedSet[str] = OrderedSet()
|
| 28 |
+
self.error = (
|
| 29 |
+
torch._inductor.config.test_configs.track_memory_lifecycle == "assert"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
def set_tensor(self, name: str, tensor: torch.Tensor) -> None:
|
| 33 |
+
storage = tensor.untyped_storage()
|
| 34 |
+
|
| 35 |
+
self.added_since_last_step.add(name)
|
| 36 |
+
self.tensor_tracker[name] = storage
|
| 37 |
+
|
| 38 |
+
def on_tensor_death() -> None:
|
| 39 |
+
self.died_since_last_step.add(name)
|
| 40 |
+
|
| 41 |
+
weakref.finalize(storage, on_tensor_death)
|
| 42 |
+
|
| 43 |
+
def advance_step(self) -> None:
|
| 44 |
+
self.died_since_last_step.clear()
|
| 45 |
+
self.added_since_last_step.clear()
|
| 46 |
+
|
| 47 |
+
def log_or_raise(self, msg: str) -> None:
|
| 48 |
+
if self.error:
|
| 49 |
+
raise RuntimeError(msg)
|
| 50 |
+
else:
|
| 51 |
+
log.info(msg)
|
| 52 |
+
|
| 53 |
+
def check_step_delta(
|
| 54 |
+
self,
|
| 55 |
+
expected_allocated: list[str],
|
| 56 |
+
expected_freed: list[str],
|
| 57 |
+
is_final_step: bool,
|
| 58 |
+
) -> None:
|
| 59 |
+
"""Check only the delta changes since last step"""
|
| 60 |
+
|
| 61 |
+
# Check expected deaths - we dont currently distinguish between nodes which die in last step
|
| 62 |
+
# and are returned as outputs, so skip if final_step.
|
| 63 |
+
if not is_final_step:
|
| 64 |
+
missing_deaths = OrderedSet(expected_freed) - self.died_since_last_step
|
| 65 |
+
if missing_deaths:
|
| 66 |
+
self.log_or_raise(
|
| 67 |
+
f"Expected tensors to die but still alive: {missing_deaths}"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
# Check for unexpected deaths
|
| 71 |
+
unexpected_deaths = self.died_since_last_step - OrderedSet(expected_freed)
|
| 72 |
+
if unexpected_deaths:
|
| 73 |
+
self.log_or_raise(f"Unexpected tensor deaths: {unexpected_deaths}")
|
| 74 |
+
|
| 75 |
+
# Check newly alive tensors - separate messages like deaths
|
| 76 |
+
actual_allocated = self.added_since_last_step
|
| 77 |
+
expected_allocated_set = OrderedSet(expected_allocated)
|
| 78 |
+
|
| 79 |
+
extra_alive = actual_allocated - expected_allocated_set
|
| 80 |
+
if extra_alive:
|
| 81 |
+
self.log_or_raise(f"Unexpected allocated tensors: {extra_alive}")
|
| 82 |
+
|
| 83 |
+
missing_alive = expected_allocated_set - actual_allocated
|
| 84 |
+
if missing_alive:
|
| 85 |
+
self.log_or_raise(
|
| 86 |
+
f"Expected allocated tensors but missing: {missing_alive}"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Reset for next step
|
| 90 |
+
self.advance_step()
|
| 91 |
+
|
| 92 |
+
if is_final_step:
|
| 93 |
+
local.memory_tracker = None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def get_mem_tracker() -> BufferMemoryTracker:
|
| 97 |
+
if local.memory_tracker is None:
|
| 98 |
+
local.memory_tracker = BufferMemoryTracker()
|
| 99 |
+
return local.memory_tracker
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def track_tensor(tensor: torch.Tensor, name: str) -> None:
|
| 103 |
+
get_mem_tracker().set_tensor(name, tensor)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def tracked_empty_strided(
|
| 107 |
+
size: list[int],
|
| 108 |
+
stride: list[int],
|
| 109 |
+
*,
|
| 110 |
+
dtype: torch.dtype,
|
| 111 |
+
device: torch.device,
|
| 112 |
+
name: str,
|
| 113 |
+
) -> torch.Tensor:
|
| 114 |
+
o = torch.empty_strided(size, stride, dtype=dtype, device=device)
|
| 115 |
+
track_tensor(o, name)
|
| 116 |
+
return o
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def check_memory_step(
|
| 120 |
+
allocated: list[str], freed: list[str], is_final_step: bool = False
|
| 121 |
+
) -> None:
|
| 122 |
+
tracker = get_mem_tracker()
|
| 123 |
+
tracker.check_step_delta(allocated, freed, is_final_step)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@functools.lru_cache(None)
|
| 127 |
+
def register_check_mem_op() -> None:
|
| 128 |
+
lib = torch.library.Library("_inductor_debug", "FRAGMENT") # noqa: TOR901
|
| 129 |
+
lib.define(
|
| 130 |
+
"check_memory_step(str[] allocated, str[] freed, bool is_final_step) -> ()"
|
| 131 |
+
)
|
| 132 |
+
lib.impl("check_memory_step", check_memory_step, "BackendSelect")
|
| 133 |
+
from torch._higher_order_ops.effects import _EffectType, _register_effectful_op
|
| 134 |
+
|
| 135 |
+
_register_effectful_op(
|
| 136 |
+
torch.ops._inductor_debug.check_memory_step.default,
|
| 137 |
+
_EffectType.ORDERED,
|
| 138 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/halide_helpers.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
try:
|
| 3 |
+
import halide as hl # type: ignore[import-untyped, import-not-found]
|
| 4 |
+
except ImportError:
|
| 5 |
+
hl = None
|
| 6 |
+
|
| 7 |
+
PHILOX_N_ROUNDS_DEFAULT = 10 # Default number of rounds for philox
|
| 8 |
+
|
| 9 |
+
if hl is not None:
|
| 10 |
+
PHILOX_KEY_A_U32 = hl.u32(0x9E3779B9)
|
| 11 |
+
PHILOX_KEY_B_U32 = hl.u32(0xBB67AE85)
|
| 12 |
+
PHILOX_ROUND_A_U32 = hl.u32(0xD2511F53)
|
| 13 |
+
PHILOX_ROUND_B_U32 = hl.u32(0xCD9E8D57)
|
| 14 |
+
else:
|
| 15 |
+
PHILOX_KEY_A_U32 = None
|
| 16 |
+
PHILOX_KEY_B_U32 = None
|
| 17 |
+
PHILOX_ROUND_A_U32 = None
|
| 18 |
+
PHILOX_ROUND_B_U32 = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _pair_uniform_to_normal(u1, u2):
|
| 22 |
+
"""Box-Muller transform"""
|
| 23 |
+
u1 = hl.max(hl.f32(1.0e-7), u1)
|
| 24 |
+
th = hl.f32(6.283185307179586) * u2
|
| 25 |
+
r = hl.sqrt(hl.f32(-2.0) * hl.log(u1))
|
| 26 |
+
return r * hl.cos(th), r * hl.sin(th)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _uint_to_uniform_float(x):
|
| 30 |
+
"""
|
| 31 |
+
Numerically stable function to convert a random uint into a random float uniformly sampled in [0, 1).
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
# TODO:
|
| 35 |
+
# conditions can be simplified
|
| 36 |
+
# scale is ((2**23 - 1) / 2**23) * 2**(N_BITS - 1)
|
| 37 |
+
# https://github.com/triton-lang/triton/blob/e4a0d93ff1a367c7d4eeebbcd7079ed267e6b06f/python/triton/language/random.py#L116-L132.
|
| 38 |
+
assert x.type() == hl.UInt(32) or x.type() == hl.Int(32)
|
| 39 |
+
x = hl.cast(hl.Int(32), x)
|
| 40 |
+
scale = hl.f64(4.6566127342e-10)
|
| 41 |
+
x = hl.select(x < 0, -x - 1, x)
|
| 42 |
+
return x * scale
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def philox_impl(c0, c1, c2, c3, k0, k1, n_rounds):
|
| 46 |
+
def umulhi(a, b):
|
| 47 |
+
a = hl.cast(hl.UInt(64), a)
|
| 48 |
+
b = hl.cast(hl.UInt(64), b)
|
| 49 |
+
return hl.cast(hl.UInt(32), ((a * b) >> 32) & hl.u64(0xFFFFFFFF))
|
| 50 |
+
|
| 51 |
+
for _ in range(n_rounds):
|
| 52 |
+
_c0, _c2 = c0, c2
|
| 53 |
+
|
| 54 |
+
c0 = umulhi(PHILOX_ROUND_B_U32, _c2) ^ c1 ^ k0
|
| 55 |
+
c2 = umulhi(PHILOX_ROUND_A_U32, _c0) ^ c3 ^ k1
|
| 56 |
+
c1 = PHILOX_ROUND_B_U32 * _c2
|
| 57 |
+
c3 = PHILOX_ROUND_A_U32 * _c0
|
| 58 |
+
# raise key
|
| 59 |
+
k0 = k0 + PHILOX_KEY_A_U32
|
| 60 |
+
k1 = k1 + PHILOX_KEY_B_U32
|
| 61 |
+
|
| 62 |
+
return c0, c1, c2, c3
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def halide_philox(seed, c0, c1, c2, c3, n_rounds):
|
| 66 |
+
seed = hl.cast(hl.UInt(64), seed)
|
| 67 |
+
|
| 68 |
+
assert c0.type().bits() == 32
|
| 69 |
+
|
| 70 |
+
seed_hi = hl.cast(hl.UInt(32), (seed >> 32) & hl.u64(0xFFFFFFFF))
|
| 71 |
+
seed_lo = hl.cast(hl.UInt(32), seed & hl.u64(0xFFFFFFFF))
|
| 72 |
+
|
| 73 |
+
return philox_impl(c0, c1, c2, c3, seed_lo, seed_hi, n_rounds)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def randint4x(seed, offset, n_rounds):
|
| 77 |
+
offset = hl.cast(hl.UInt(32), offset)
|
| 78 |
+
_0 = hl.u32(0)
|
| 79 |
+
return halide_philox(seed, offset, _0, _0, _0, n_rounds)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def rand4x(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT):
|
| 83 |
+
i1, i2, i3, i4 = randint4x(seed, offset, n_rounds)
|
| 84 |
+
u1 = _uint_to_uniform_float(i1)
|
| 85 |
+
u2 = _uint_to_uniform_float(i2)
|
| 86 |
+
u3 = _uint_to_uniform_float(i3)
|
| 87 |
+
u4 = _uint_to_uniform_float(i4)
|
| 88 |
+
return u1, u2, u3, u4
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def randint(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT):
|
| 92 |
+
ret, _, _, _ = randint4x(seed, offset, n_rounds)
|
| 93 |
+
return ret
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def rand(seed, offset, n_rounds=PHILOX_N_ROUNDS_DEFAULT):
|
| 97 |
+
source = randint(seed, offset, n_rounds)
|
| 98 |
+
return _uint_to_uniform_float(source)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def randn(seed, offset):
|
| 102 |
+
i1, i2, _, _ = randint4x(seed, offset, PHILOX_N_ROUNDS_DEFAULT)
|
| 103 |
+
u1 = _uint_to_uniform_float(i1)
|
| 104 |
+
u2 = _uint_to_uniform_float(i2)
|
| 105 |
+
n1, _ = _pair_uniform_to_normal(u1, u2)
|
| 106 |
+
return n1
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def randint64(seed, offset, low, high):
|
| 110 |
+
r0, r1, _r2, _r3 = randint4x(seed, offset, PHILOX_N_ROUNDS_DEFAULT)
|
| 111 |
+
r0 = hl.cast(hl.UInt(64), r0)
|
| 112 |
+
r1 = hl.cast(hl.UInt(64), r1)
|
| 113 |
+
|
| 114 |
+
result = r0 | (r1 << 32)
|
| 115 |
+
size = high - low
|
| 116 |
+
result = result % hl.cast(hl.UInt(64), size)
|
| 117 |
+
result = hl.cast(hl.Int(64), result) + low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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import collections
|
| 5 |
+
import functools
|
| 6 |
+
import typing
|
| 7 |
+
from enum import auto, Enum
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch.utils._triton import has_triton_package
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# The following maximums only apply to runtime autotuning, when using FixedTritonConfig one may see larger values
|
| 14 |
+
# NOTE: if these fail asserts submit a PR to increase them
|
| 15 |
+
TRITON_MAX_BLOCK = {
|
| 16 |
+
"X": 8192 if torch.version.hip else 4096,
|
| 17 |
+
"Y": 1024,
|
| 18 |
+
"Z": 1024,
|
| 19 |
+
"R0_": 4096 * 16, # * 16 is multi-kernel only
|
| 20 |
+
"R1_": 2048 * 16, # * 16 is multi-kernel only
|
| 21 |
+
}
|
| 22 |
+
TRITON_MAX_RSPLIT = 64
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ReductionHint(Enum):
|
| 26 |
+
INNER = 0
|
| 27 |
+
OUTER = 1
|
| 28 |
+
OUTER_TINY = 2
|
| 29 |
+
DEFAULT = 3
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class TileHint(Enum):
|
| 33 |
+
SQUARE = 0
|
| 34 |
+
DEFAULT = 1
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Define `AttrsDescriptorWrapper` function with clear conditional handling
|
| 38 |
+
if has_triton_package():
|
| 39 |
+
import triton
|
| 40 |
+
import triton.backends.compiler
|
| 41 |
+
import triton.compiler.compiler
|
| 42 |
+
|
| 43 |
+
if hasattr(triton.backends.compiler, "AttrsDescriptor"):
|
| 44 |
+
# Triton 3.2.0 - the second implementation
|
| 45 |
+
from triton.backends.compiler import AttrsDescriptor
|
| 46 |
+
|
| 47 |
+
def AttrsDescriptorWrapper(
|
| 48 |
+
divisible_by_16=None,
|
| 49 |
+
equal_to_1=None,
|
| 50 |
+
):
|
| 51 |
+
# Prepare the arguments for AttrsDescriptor
|
| 52 |
+
kwargs = {
|
| 53 |
+
"tt.divisibility": divisible_by_16,
|
| 54 |
+
"tt.equal_to": equal_to_1,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
# Instantiate AttrsDescriptor with the prepared arguments
|
| 58 |
+
res = AttrsDescriptor.from_dict(
|
| 59 |
+
{"arg_properties": kwargs, "cls": AttrsDescriptor.__name__}
|
| 60 |
+
)
|
| 61 |
+
assert res.property_values["tt.divisibility"] == 16
|
| 62 |
+
assert res.property_values["tt.equal_to"] == 1
|
| 63 |
+
return res
|
| 64 |
+
|
| 65 |
+
elif hasattr(triton.compiler.compiler, "AttrsDescriptor"):
|
| 66 |
+
# Triton 3.0.0 - the original implementation
|
| 67 |
+
from triton.compiler.compiler import AttrsDescriptor
|
| 68 |
+
|
| 69 |
+
def AttrsDescriptorWrapper(
|
| 70 |
+
divisible_by_16=None,
|
| 71 |
+
equal_to_1=None,
|
| 72 |
+
):
|
| 73 |
+
# Prepare the arguments for AttrsDescriptor
|
| 74 |
+
kwargs = {
|
| 75 |
+
"divisible_by_16": divisible_by_16,
|
| 76 |
+
"equal_to_1": equal_to_1,
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
# Instantiate AttrsDescriptor with the prepared arguments
|
| 80 |
+
return AttrsDescriptor(**kwargs)
|
| 81 |
+
|
| 82 |
+
else:
|
| 83 |
+
# Triton in 2025:
|
| 84 |
+
# note: there's also a range of triton commits not currently supported
|
| 85 |
+
# from ~Dec 9, 2024 to Jan 1 2025, in which AttrsDescriptors are still
|
| 86 |
+
# used, but the contents are different.
|
| 87 |
+
|
| 88 |
+
def AttrsDescriptorWrapper(
|
| 89 |
+
divisible_by_16=None,
|
| 90 |
+
equal_to_1=None,
|
| 91 |
+
):
|
| 92 |
+
# pyrefly: ignore [not-iterable]
|
| 93 |
+
return {(x,): [["tt.divisibility", 16]] for x in divisible_by_16}
|
| 94 |
+
|
| 95 |
+
else:
|
| 96 |
+
# Define a namedtuple as a fallback when AttrsDescriptor is not available
|
| 97 |
+
AttrsDescriptorWrapper = collections.namedtuple( # type: ignore[no-redef, name-match]
|
| 98 |
+
# pyrefly: ignore [invalid-argument]
|
| 99 |
+
"AttrsDescriptor",
|
| 100 |
+
["divisible_by_16", "equal_to_1"],
|
| 101 |
+
defaults=[(), ()],
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
_NUM_THREADS_PER_WARP = 32
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class HeuristicType(Enum):
|
| 109 |
+
PERSISTENT_REDUCTION = auto()
|
| 110 |
+
POINTWISE = auto()
|
| 111 |
+
REDUCTION = auto()
|
| 112 |
+
SPLIT_SCAN = auto()
|
| 113 |
+
TEMPLATE = auto()
|
| 114 |
+
USER_AUTOTUNE = auto()
|
| 115 |
+
FIXED = auto()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class AutotuneHint(Enum):
|
| 119 |
+
ONE_ELEMENT_PER_THREAD = 0
|
| 120 |
+
|
| 121 |
+
# Triton codegen tries to codegen set of AutotuneHints.
|
| 122 |
+
# Enum.__repr__ looks like "<AutotuneHint.ELEMENTS_PER_WARP_32: 0>""
|
| 123 |
+
# which isn't valid python.
|
| 124 |
+
# Enum.__str__ will just return "AutotuneHint.ELEMENTS_PER_WARP_32".
|
| 125 |
+
__repr__ = Enum.__str__
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class DeviceProperties(typing.NamedTuple):
|
| 129 |
+
"""Copy device properties into a data structure not requiring torch to be imported"""
|
| 130 |
+
|
| 131 |
+
type: str # type: ignore[assignment]
|
| 132 |
+
index: int # type: ignore[assignment]
|
| 133 |
+
multi_processor_count: int
|
| 134 |
+
cc: int
|
| 135 |
+
major: int | None = None
|
| 136 |
+
regs_per_multiprocessor: int | None = None
|
| 137 |
+
max_threads_per_multi_processor: int | None = None
|
| 138 |
+
max_threads_per_block: int | None = None
|
| 139 |
+
warp_size: int | None = None
|
| 140 |
+
|
| 141 |
+
@classmethod
|
| 142 |
+
@functools.cache
|
| 143 |
+
def create(cls, device) -> DeviceProperties:
|
| 144 |
+
import torch
|
| 145 |
+
from torch._dynamo.device_interface import get_interface_for_device
|
| 146 |
+
|
| 147 |
+
device_type = device.type
|
| 148 |
+
|
| 149 |
+
if torch.version.hip and device_type == "cuda":
|
| 150 |
+
device_type = "hip"
|
| 151 |
+
|
| 152 |
+
device_interface = get_interface_for_device(device)
|
| 153 |
+
props = device_interface.get_device_properties(device)
|
| 154 |
+
try:
|
| 155 |
+
multi_processor_count = props.multi_processor_count
|
| 156 |
+
except AttributeError:
|
| 157 |
+
if device_type == "xpu":
|
| 158 |
+
multi_processor_count = props.gpu_subslice_count
|
| 159 |
+
elif device_type == "mtia":
|
| 160 |
+
multi_processor_count = 64
|
| 161 |
+
else:
|
| 162 |
+
raise
|
| 163 |
+
return cls(
|
| 164 |
+
type=device_type,
|
| 165 |
+
index=device.index,
|
| 166 |
+
multi_processor_count=multi_processor_count,
|
| 167 |
+
cc=device_interface.get_compute_capability(device),
|
| 168 |
+
major=getattr(props, "major", None),
|
| 169 |
+
regs_per_multiprocessor=getattr(props, "regs_per_multiprocessor", None),
|
| 170 |
+
max_threads_per_multi_processor=getattr(
|
| 171 |
+
props, "max_threads_per_multi_processor", None
|
| 172 |
+
),
|
| 173 |
+
max_threads_per_block=getattr(props, "max_threads_per_block", 1024),
|
| 174 |
+
warp_size=getattr(props, "warp_size", 32 if device_type != "cpu" else None),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class HalideInputSpec(typing.NamedTuple):
|
| 179 |
+
ctype: str
|
| 180 |
+
name: str
|
| 181 |
+
shape: list[str] | None = None
|
| 182 |
+
stride: list[str] | None = None
|
| 183 |
+
offset: str | None = None
|
| 184 |
+
alias_of: str | None = None
|
| 185 |
+
|
| 186 |
+
def bindings_type(self) -> str:
|
| 187 |
+
if self.ctype in ("at::Half*", "at::BFloat16*"):
|
| 188 |
+
return "uint16_t*" # half not defined
|
| 189 |
+
return self.ctype
|
| 190 |
+
|
| 191 |
+
def halide_type(self) -> str:
|
| 192 |
+
if self.ctype == "at::Half*":
|
| 193 |
+
return "halide_type_t(halide_type_float, 16)" # half not defined
|
| 194 |
+
if self.ctype == "at::BFloat16*":
|
| 195 |
+
return "halide_type_t(halide_type_bfloat, 16)" # half not defined
|
| 196 |
+
return f"halide_type_of<{self.ctype.replace('*', '')}>()"
|
| 197 |
+
|
| 198 |
+
def is_scalar(self) -> bool:
|
| 199 |
+
return self.shape is None
|
| 200 |
+
|
| 201 |
+
def is_buffer(self) -> bool:
|
| 202 |
+
return self.shape is not None
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class HalideMeta(typing.NamedTuple):
|
| 206 |
+
argtypes: list[HalideInputSpec]
|
| 207 |
+
target: str
|
| 208 |
+
scheduler: str | None = None
|
| 209 |
+
scheduler_flags: dict[str, int | str] | None = None
|
| 210 |
+
cuda_device: int | None = None
|
| 211 |
+
|
| 212 |
+
def args(self) -> list[str]:
|
| 213 |
+
"""Command line args to pass to halide generator"""
|
| 214 |
+
args = [f"target={self.target}"]
|
| 215 |
+
if self.scheduler:
|
| 216 |
+
args.append(f"autoscheduler={self.scheduler}")
|
| 217 |
+
if self.scheduler_flags:
|
| 218 |
+
assert self.scheduler
|
| 219 |
+
for k, v in self.scheduler_flags.items():
|
| 220 |
+
args.append(f"autoscheduler.{k}={v}")
|
| 221 |
+
return args
|
| 222 |
+
|
| 223 |
+
def is_cuda(self) -> bool:
|
| 224 |
+
return self.cuda_device is not None
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/runtime_utils.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import operator
|
| 5 |
+
from typing import Any, TYPE_CHECKING
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
# NOTE: other files rely on the imports below
|
| 10 |
+
from torch._dynamo import callback as compilation_callback # noqa: F401
|
| 11 |
+
from torch._inductor.runtime.cache_dir_utils import ( # noqa: F401
|
| 12 |
+
cache_dir,
|
| 13 |
+
default_cache_dir,
|
| 14 |
+
triton_cache_dir,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from collections.abc import Hashable
|
| 20 |
+
|
| 21 |
+
from .triton_compat import Config
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def conditional_product(*args: int) -> int:
|
| 25 |
+
return functools.reduce(operator.mul, [x for x in args if x])
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def ceildiv(number: int, denom: int) -> int:
|
| 29 |
+
return -(number // -denom)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def is_power_of_2(n: int) -> bool:
|
| 33 |
+
"""Returns whether n = 2 ** m for some integer m."""
|
| 34 |
+
return n > 0 and n & n - 1 == 0
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def next_power_of_2(n: int) -> int:
|
| 38 |
+
"""Return the smallest power of 2 greater than or equal to n"""
|
| 39 |
+
n -= 1
|
| 40 |
+
n |= n >> 1
|
| 41 |
+
n |= n >> 2
|
| 42 |
+
n |= n >> 4
|
| 43 |
+
n |= n >> 8
|
| 44 |
+
n |= n >> 16
|
| 45 |
+
n |= n >> 32
|
| 46 |
+
n += 1
|
| 47 |
+
return n
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def last_power_of_2(n: int) -> int:
|
| 51 |
+
"""Return the largest power of 2 less than or equal to n"""
|
| 52 |
+
next_pow2 = next_power_of_2(n)
|
| 53 |
+
return next_pow2 // 2 if next_pow2 > n else next_pow2
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def get_num_bytes(*args: torch.Tensor, num_in_out_args: int = 0) -> int:
|
| 57 |
+
"""
|
| 58 |
+
Return the total number of bytes the arguments of tensor type takes.
|
| 59 |
+
|
| 60 |
+
For in/out args, tensor sizes are counted twice: once for reading and
|
| 61 |
+
once for writing.
|
| 62 |
+
|
| 63 |
+
The first num_in_out_args arguments are in out tensors.
|
| 64 |
+
"""
|
| 65 |
+
return sum(
|
| 66 |
+
arg.numel() * arg.element_size() * (1 + int(i < num_in_out_args))
|
| 67 |
+
for i, arg in enumerate(args)
|
| 68 |
+
if isinstance(arg, torch.Tensor)
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def triton_config_to_hashable(cfg: Config) -> Hashable:
|
| 73 |
+
"""
|
| 74 |
+
Convert triton config to a tuple that can uniquely identify it. We can use
|
| 75 |
+
the return value as a dictionary key.
|
| 76 |
+
"""
|
| 77 |
+
# pyrefly: ignore [missing-attribute]
|
| 78 |
+
items = sorted(cfg.kwargs.items())
|
| 79 |
+
# pyrefly: ignore [missing-attribute]
|
| 80 |
+
items.append(("num_warps", cfg.num_warps))
|
| 81 |
+
# pyrefly: ignore [missing-attribute]
|
| 82 |
+
items.append(("num_stages", cfg.num_stages))
|
| 83 |
+
return tuple(items)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def validate_triton_config(cfg: Config) -> None:
|
| 87 |
+
# [Note: Triton pre_hook in inductor]
|
| 88 |
+
# pre-hook is a lambda function, which we don't attempt to serialize.
|
| 89 |
+
# right now, if a pre-hook is attached to the config, it will not be saved;
|
| 90 |
+
# and then it won't be used when the config is loaded from cache.
|
| 91 |
+
# So we assert - if we do get a pre_hook, it might get ignored after caching.
|
| 92 |
+
assert getattr(cfg, "pre_hook", None) is None, (
|
| 93 |
+
"triton configs with pre_hooks not supported"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def create_bandwidth_info_str(
|
| 98 |
+
ms: float,
|
| 99 |
+
num_gb: float,
|
| 100 |
+
gb_per_s: float,
|
| 101 |
+
prefix: str = "",
|
| 102 |
+
suffix: str = "",
|
| 103 |
+
color: bool = True,
|
| 104 |
+
) -> str:
|
| 105 |
+
info_str = f"{prefix}{ms:.3f}ms \t{num_gb:.3f} GB \t {gb_per_s:7.2f}GB/s{suffix}"
|
| 106 |
+
slow = ms > 0.012 and gb_per_s < 650
|
| 107 |
+
return red_text(info_str) if color and slow else info_str
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def get_max_y_grid() -> int:
|
| 111 |
+
return 65535
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
# pyrefly: ignore [import-error]
|
| 116 |
+
import colorama
|
| 117 |
+
|
| 118 |
+
HAS_COLORAMA = True
|
| 119 |
+
except ModuleNotFoundError:
|
| 120 |
+
HAS_COLORAMA = False
|
| 121 |
+
colorama = None # type: ignore[assignment]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if HAS_COLORAMA:
|
| 125 |
+
|
| 126 |
+
def _color_text(msg: str, color: str) -> str:
|
| 127 |
+
# pyrefly: ignore [missing-attribute]
|
| 128 |
+
return getattr(colorama.Fore, color.upper()) + msg + colorama.Fore.RESET
|
| 129 |
+
|
| 130 |
+
else:
|
| 131 |
+
|
| 132 |
+
def _color_text(msg: str, color: str) -> str:
|
| 133 |
+
return msg
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def green_text(msg: str) -> str:
|
| 137 |
+
return _color_text(msg, "green")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def yellow_text(msg: str) -> str:
|
| 141 |
+
return _color_text(msg, "yellow")
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def red_text(msg: str) -> str:
|
| 145 |
+
return _color_text(msg, "red")
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def blue_text(msg: str) -> str:
|
| 149 |
+
return _color_text(msg, "blue")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def get_first_attr(obj: Any, *attrs: str) -> Any:
|
| 153 |
+
"""
|
| 154 |
+
Return the first available attribute or throw an exception if none is present.
|
| 155 |
+
"""
|
| 156 |
+
for attr in attrs:
|
| 157 |
+
if hasattr(obj, attr):
|
| 158 |
+
return getattr(obj, attr)
|
| 159 |
+
|
| 160 |
+
raise AssertionError(f"{obj} does not has any of the attributes: {attrs}")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
dynamo_timed = torch._dynamo.utils.dynamo_timed # type: ignore[has-type]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def triton_hash_to_path_key(key: str) -> str:
|
| 167 |
+
# In early versions of Triton, the hash is directly used in the path name.
|
| 168 |
+
# Later, the hash is converted to base64 before being used in the path name.
|
| 169 |
+
# Later, the base64 conversion was replaced to the base32
|
| 170 |
+
#
|
| 171 |
+
# This code tries to import _base64 and falls back to _base32 if _base64 is unavailable.
|
| 172 |
+
#
|
| 173 |
+
# To handle this, try to import the to-base64-conversion function.
|
| 174 |
+
# If it exists, use it; otherwise, try using _base32; if both are unavailable, use the hash directly.
|
| 175 |
+
try:
|
| 176 |
+
from triton.runtime.cache import _base64
|
| 177 |
+
|
| 178 |
+
return _base64(key)
|
| 179 |
+
except Exception:
|
| 180 |
+
try:
|
| 181 |
+
from triton.runtime.cache import _base32
|
| 182 |
+
|
| 183 |
+
return _base32(key)
|
| 184 |
+
except Exception:
|
| 185 |
+
return key
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def compile_mps_shader(source: str) -> Any:
|
| 189 |
+
"""
|
| 190 |
+
Compiles shader source but raise more actionable error message when needed
|
| 191 |
+
"""
|
| 192 |
+
try:
|
| 193 |
+
return torch.mps.compile_shader(source)
|
| 194 |
+
except SyntaxError as err:
|
| 195 |
+
raise SyntaxError(f"failed to compile {source} with {err.msg}") from err
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def torch_dtype_to_jax_runtime(dtype: torch.dtype) -> Any:
|
| 199 |
+
"""
|
| 200 |
+
Map PyTorch dtype to actual JAX dtype object at runtime.
|
| 201 |
+
|
| 202 |
+
This helper is used in generated Pallas kernels at runtime to convert
|
| 203 |
+
PyTorch dtypes to JAX dtype objects (not string representations).
|
| 204 |
+
|
| 205 |
+
Args:
|
| 206 |
+
dtype: PyTorch dtype to convert
|
| 207 |
+
|
| 208 |
+
Returns:
|
| 209 |
+
JAX dtype object (e.g., jnp.float32 object itself)
|
| 210 |
+
"""
|
| 211 |
+
import jax.numpy as jnp # pyrefly: ignore [import-error]
|
| 212 |
+
|
| 213 |
+
dtype_map = {
|
| 214 |
+
torch.float32: jnp.float32,
|
| 215 |
+
torch.float64: jnp.float64,
|
| 216 |
+
torch.float16: jnp.float16,
|
| 217 |
+
torch.bfloat16: jnp.bfloat16,
|
| 218 |
+
torch.int32: jnp.int32,
|
| 219 |
+
torch.int64: jnp.int64,
|
| 220 |
+
torch.int16: jnp.int16,
|
| 221 |
+
torch.int8: jnp.int8,
|
| 222 |
+
torch.uint8: jnp.uint8,
|
| 223 |
+
torch.bool: jnp.bool_,
|
| 224 |
+
torch.complex64: jnp.complex64,
|
| 225 |
+
torch.complex128: jnp.complex128,
|
| 226 |
+
}
|
| 227 |
+
if dtype not in dtype_map:
|
| 228 |
+
raise ValueError(f"Unsupported dtype for JAX conversion: {dtype}")
|
| 229 |
+
return dtype_map[dtype]
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def torch_dtype_to_jax(dtype: torch.dtype) -> str:
|
| 233 |
+
"""
|
| 234 |
+
Map PyTorch dtype to JAX dtype expression string.
|
| 235 |
+
|
| 236 |
+
This helper is used at compile time in codegen to generate
|
| 237 |
+
JAX dtype expressions for Pallas kernels.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
dtype: PyTorch dtype to convert
|
| 241 |
+
|
| 242 |
+
Returns:
|
| 243 |
+
JAX dtype expression as string (e.g., "jnp.float32")
|
| 244 |
+
"""
|
| 245 |
+
jax_dtype = torch_dtype_to_jax_runtime(dtype)
|
| 246 |
+
dtype_name = jax_dtype.__name__
|
| 247 |
+
if dtype_name == "bool":
|
| 248 |
+
dtype_name = "bool_"
|
| 249 |
+
return f"jnp.{dtype_name}"
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/static_cuda_launcher.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import os
|
| 3 |
+
from typing import Any
|
| 4 |
+
from typing_extensions import Unpack
|
| 5 |
+
|
| 6 |
+
from .triton_compat import ASTSource, CompiledKernel, knobs as triton_knobs
|
| 7 |
+
from .triton_helpers import get_constexprs
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class StaticallyLaunchedCudaKernel:
|
| 11 |
+
"""
|
| 12 |
+
Parses the metadata of a CompiledKernel from Triton into a structure that can
|
| 13 |
+
launch the cuda kernel directly. Only works for triton kernels compiled to cubin.
|
| 14 |
+
|
| 15 |
+
Doing this avoids C++ codegen and compilation during compile, since we can use a
|
| 16 |
+
statically compiled library to launch the kernel. To avoid mallocing for the arguments,
|
| 17 |
+
we have a launcher for different numbers of arguments up to a max. StaticCudaLauncher
|
| 18 |
+
only supports # of arguments up until 10 for now.
|
| 19 |
+
|
| 20 |
+
Workflow:
|
| 21 |
+
Compile time:
|
| 22 |
+
1. Compile a kernel with triton and get a CompiledKernel
|
| 23 |
+
2. Instantiate kernel = StaticallyLaunchedCudaKernel(triton_kernel)
|
| 24 |
+
3. Write to a cubin file: kernel.write_cubin_to_file(filepath)
|
| 25 |
+
4. Call kernel.load_kernel() (CUDA should be initialized by this point) to load the cubin
|
| 26 |
+
Runtime:
|
| 27 |
+
5. Call kernel.run(grid, stream, args) to launch the kernel
|
| 28 |
+
|
| 29 |
+
Note that after step 3, StaticallyLaunchedCudaKernel is fully pickleable/serializable.
|
| 30 |
+
This allows it to be cached by FXGraphCache/TritonBundler, as well as sent from the worker
|
| 31 |
+
to the parent process in inductor.
|
| 32 |
+
|
| 33 |
+
There are two main versions of triton that we wish to support: 3.3 and 3.2. Triton makes considerable changes
|
| 34 |
+
to how it handles constants in 3.3, so there's some special logic necessary to handle both versions.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, kernel: CompiledKernel) -> None:
|
| 38 |
+
# pyrefly: ignore [missing-attribute]
|
| 39 |
+
self.name = kernel.src.fn.__name__
|
| 40 |
+
# pyrefly: ignore [missing-attribute]
|
| 41 |
+
self.cubin_raw = kernel.asm.get("cubin", None)
|
| 42 |
+
# pyrefly: ignore [missing-attribute]
|
| 43 |
+
self.cubin_path = kernel._cubin_path
|
| 44 |
+
|
| 45 |
+
# Used by torch.compile to filter constants in older triton versions
|
| 46 |
+
# pyrefly: ignore [missing-attribute]
|
| 47 |
+
self.arg_names = kernel.src.fn.arg_names
|
| 48 |
+
|
| 49 |
+
# Const exprs that are declared by the triton kernel directly
|
| 50 |
+
# Used to generate the kernel launcher's def args
|
| 51 |
+
# pyrefly: ignore [missing-attribute]
|
| 52 |
+
self.declared_constexprs = get_constexprs(kernel.src.fn)
|
| 53 |
+
|
| 54 |
+
# pyrefly: ignore [missing-attribute]
|
| 55 |
+
self.hash = kernel.hash
|
| 56 |
+
|
| 57 |
+
if triton_knobs is None:
|
| 58 |
+
# pyrefly: ignore [missing-attribute]
|
| 59 |
+
launch_enter = kernel.__class__.launch_enter_hook
|
| 60 |
+
# pyrefly: ignore [missing-attribute]
|
| 61 |
+
launch_exit = kernel.__class__.launch_exit_hook
|
| 62 |
+
else:
|
| 63 |
+
launch_enter = triton_knobs.runtime.launch_enter_hook
|
| 64 |
+
launch_exit = triton_knobs.runtime.launch_exit_hook
|
| 65 |
+
|
| 66 |
+
def hook_is_empty(hook: Any) -> bool:
|
| 67 |
+
if hook is None:
|
| 68 |
+
return True
|
| 69 |
+
if (
|
| 70 |
+
triton_knobs
|
| 71 |
+
and (HookChain := getattr(triton_knobs, "HookChain", None)) is not None
|
| 72 |
+
and isinstance(hook, HookChain)
|
| 73 |
+
):
|
| 74 |
+
# Support hooks after https://github.com/triton-lang/triton/pull/7866
|
| 75 |
+
return len(hook.calls) == 0
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
if not hook_is_empty(launch_enter) or not hook_is_empty(launch_exit):
|
| 79 |
+
raise NotImplementedError(
|
| 80 |
+
"We don't support launch enter or launch exit hooks"
|
| 81 |
+
)
|
| 82 |
+
# pyrefly: ignore [missing-attribute]
|
| 83 |
+
self.num_warps = kernel.metadata.num_warps
|
| 84 |
+
self.shared = (
|
| 85 |
+
# pyrefly: ignore [missing-attribute]
|
| 86 |
+
kernel.shared if hasattr(kernel, "shared") else kernel.metadata.shared
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
def needs_scratch_arg(scratch_name: str, param_name: str) -> bool:
|
| 90 |
+
# pyrefly: ignore [missing-attribute]
|
| 91 |
+
if hasattr(kernel.metadata, param_name):
|
| 92 |
+
if getattr(kernel.metadata, param_name) > 0:
|
| 93 |
+
raise NotImplementedError(
|
| 94 |
+
f"{scratch_name} scratch not yet supported"
|
| 95 |
+
)
|
| 96 |
+
return True
|
| 97 |
+
return False
|
| 98 |
+
|
| 99 |
+
# Newer triton versions pass an extra global scratch parameter to the compiled cuda kernel.
|
| 100 |
+
# Inductor never uses this field or enables it, but we still have to pass
|
| 101 |
+
# an extra None into the set of params if its enabled
|
| 102 |
+
self.has_global_scratch = needs_scratch_arg("Global", "global_scratch_size")
|
| 103 |
+
# same situation for profile scratch - triton-lang/triton#7258
|
| 104 |
+
self.has_profile_scratch = needs_scratch_arg("Profile", "profile_scratch_size")
|
| 105 |
+
|
| 106 |
+
# pyrefly: ignore [missing-attribute]
|
| 107 |
+
self.arg_tys = self.arg_ty_from_signature(kernel.src)
|
| 108 |
+
self.function: int | None = None # Loaded by load_kernel(on the parent process)
|
| 109 |
+
num_ctas = 1
|
| 110 |
+
if hasattr(kernel, "num_ctas"):
|
| 111 |
+
num_ctas = kernel.num_ctas
|
| 112 |
+
elif hasattr(kernel, "metadata"):
|
| 113 |
+
num_ctas = kernel.metadata.num_ctas
|
| 114 |
+
|
| 115 |
+
if num_ctas != 1:
|
| 116 |
+
raise NotImplementedError(
|
| 117 |
+
"Static cuda launcher only supports num_ctas == 1"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
def reload_cubin_from_raw(self, filepath: str) -> str:
|
| 121 |
+
"""
|
| 122 |
+
If the cubin file triton generated gets deleted under us, we can
|
| 123 |
+
reload it from the raw cubin file.
|
| 124 |
+
"""
|
| 125 |
+
if self.cubin_path is None:
|
| 126 |
+
assert self.cubin_raw is not None
|
| 127 |
+
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
| 128 |
+
with open(filepath, "wb") as f:
|
| 129 |
+
f.write(self.cubin_raw)
|
| 130 |
+
self.cubin_path = filepath
|
| 131 |
+
return self.cubin_path
|
| 132 |
+
|
| 133 |
+
def load_kernel(self, device: int) -> None:
|
| 134 |
+
from torch._C import _StaticCudaLauncher
|
| 135 |
+
|
| 136 |
+
if self.function is not None:
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
assert hasattr(self, "cubin_path")
|
| 140 |
+
assert self.cubin_path is not None
|
| 141 |
+
(self.function, self.n_regs, self.n_spills) = _StaticCudaLauncher._load_kernel(
|
| 142 |
+
self.cubin_path, self.name, self.shared, device
|
| 143 |
+
)
|
| 144 |
+
# Don't need the cubin path anymore now that we've loaded
|
| 145 |
+
self.cubin_path = None
|
| 146 |
+
self.cubin_raw = None
|
| 147 |
+
|
| 148 |
+
@staticmethod
|
| 149 |
+
@functools.lru_cache
|
| 150 |
+
def type_mappings() -> dict[str, str]:
|
| 151 |
+
return {
|
| 152 |
+
"i1": "i",
|
| 153 |
+
"i8": "b",
|
| 154 |
+
"i16": "h",
|
| 155 |
+
"i32": "i",
|
| 156 |
+
"i64": "l",
|
| 157 |
+
"u1": "I",
|
| 158 |
+
"u8": "B",
|
| 159 |
+
"u16": "H",
|
| 160 |
+
"u32": "I",
|
| 161 |
+
"u64": "K",
|
| 162 |
+
"fp16": "f",
|
| 163 |
+
"bf16": "f",
|
| 164 |
+
"fp32": "f",
|
| 165 |
+
"f32": "f",
|
| 166 |
+
"fp64": "d",
|
| 167 |
+
# TODO handle nvTmaDesc/CUtensormap
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
def extract_type(self, ty: str) -> str:
|
| 171 |
+
"""
|
| 172 |
+
Takes a triton type from CompiledKernel.signature and
|
| 173 |
+
converts it into a single char encoding. _StaticCudaLauncher
|
| 174 |
+
will switch on this char to figure out what type the underlying
|
| 175 |
+
value should be passed to the triton kernel as.
|
| 176 |
+
"""
|
| 177 |
+
if ty[0] == "*":
|
| 178 |
+
return "O"
|
| 179 |
+
elif ty == "nvTmaDesc":
|
| 180 |
+
raise NotImplementedError("nvTmaDesc kernels are not yet supported")
|
| 181 |
+
return StaticallyLaunchedCudaKernel.type_mappings()[ty]
|
| 182 |
+
|
| 183 |
+
def arg_ty_from_signature(self, src: ASTSource) -> str:
|
| 184 |
+
def index_key(i: Any) -> int:
|
| 185 |
+
if isinstance(i, str):
|
| 186 |
+
# pyrefly: ignore [missing-attribute]
|
| 187 |
+
return src.fn.arg_names.index(i)
|
| 188 |
+
elif isinstance(i, tuple):
|
| 189 |
+
# In triton 3.3, src.fn.constants has tuples as a key
|
| 190 |
+
return i[0]
|
| 191 |
+
else:
|
| 192 |
+
return i
|
| 193 |
+
|
| 194 |
+
# pyrefly: ignore [missing-attribute]
|
| 195 |
+
signature = {index_key(key): value for key, value in src.signature.items()}
|
| 196 |
+
# Triton uses these as the main way to filter out constants passed to their cubin
|
| 197 |
+
constants = [index_key(key) for key in getattr(src, "constants", dict())]
|
| 198 |
+
# This value is always a superset of kernel.fn.constexprs: kernel.fn.constexprs are
|
| 199 |
+
# constants declared by the triton kernel directly, whereas this list can have
|
| 200 |
+
# constants that are unused by the triton kernel that triton figured out during
|
| 201 |
+
# compilation.
|
| 202 |
+
self.full_constexprs = constants
|
| 203 |
+
# Despite requiring them to be passed in, the triton CUDA launcher
|
| 204 |
+
# completely ignores the constexprs passed into it when generating code.
|
| 205 |
+
# So we can ignore them here too
|
| 206 |
+
params = []
|
| 207 |
+
|
| 208 |
+
for i in sorted(signature.keys()):
|
| 209 |
+
ty = signature[i]
|
| 210 |
+
# In newer triton versions, constants are passed in to signature with type `constexpr`
|
| 211 |
+
# In older triton versions, there can be constants in src.constants that are not `constexpr` in signature
|
| 212 |
+
# so we check both here
|
| 213 |
+
if ty == "constexpr" or i in constants:
|
| 214 |
+
pass
|
| 215 |
+
else:
|
| 216 |
+
# pyrefly: ignore [bad-argument-type]
|
| 217 |
+
params.append(self.extract_type(ty))
|
| 218 |
+
return "".join(params)
|
| 219 |
+
|
| 220 |
+
def __getstate__(self) -> dict[str, Any]:
|
| 221 |
+
# Remove objects that are no longer valid for pickling
|
| 222 |
+
state = self.__dict__.copy()
|
| 223 |
+
state["function"] = None
|
| 224 |
+
# Cubin paths aren't consistent across processes, so we clear
|
| 225 |
+
# and reload them.
|
| 226 |
+
state["cubin_path"] = None
|
| 227 |
+
return state
|
| 228 |
+
|
| 229 |
+
def run(
|
| 230 |
+
self,
|
| 231 |
+
grid_x: int,
|
| 232 |
+
grid_y: int,
|
| 233 |
+
grid_z: int,
|
| 234 |
+
stream: int,
|
| 235 |
+
*args: Unpack[tuple[object, ...]],
|
| 236 |
+
) -> None:
|
| 237 |
+
"""Actually run the kernel at runtime. This function is the hot codepath."""
|
| 238 |
+
from torch._C import _StaticCudaLauncher
|
| 239 |
+
|
| 240 |
+
# Assert load_kernel() has been called and args match
|
| 241 |
+
assert self.function is not None
|
| 242 |
+
|
| 243 |
+
# TODO: actually, if the args *don't* match, we probably should
|
| 244 |
+
# throw an exception. But if inductor is the only one calling this
|
| 245 |
+
# thing, it should always match.
|
| 246 |
+
# Get rid of constants before passing to cubin launcher
|
| 247 |
+
|
| 248 |
+
# Add a None if triton wants extra parameters for scratch spaces
|
| 249 |
+
arg_tys = self.arg_tys
|
| 250 |
+
for has_scratch in [self.has_global_scratch, self.has_profile_scratch]:
|
| 251 |
+
if has_scratch:
|
| 252 |
+
arg_tys = arg_tys + "O"
|
| 253 |
+
args = (*args, None)
|
| 254 |
+
# pyrefly: ignore [bad-argument-type]
|
| 255 |
+
assert len(args) == len(arg_tys)
|
| 256 |
+
|
| 257 |
+
# TODO: can handle grid functions here or in C++, so
|
| 258 |
+
# that we don't need the grid handler above.
|
| 259 |
+
_StaticCudaLauncher._launch_kernel(
|
| 260 |
+
self.function,
|
| 261 |
+
grid_x,
|
| 262 |
+
grid_y,
|
| 263 |
+
grid_z,
|
| 264 |
+
self.num_warps,
|
| 265 |
+
self.shared,
|
| 266 |
+
arg_tys,
|
| 267 |
+
# pyrefly: ignore [bad-argument-type]
|
| 268 |
+
args,
|
| 269 |
+
stream,
|
| 270 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/triton_compat.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
| 14 |
+
|
| 15 |
+
if triton is not None:
|
| 16 |
+
import triton.language as tl
|
| 17 |
+
from triton import Config
|
| 18 |
+
from triton.compiler import CompiledKernel
|
| 19 |
+
from triton.runtime.autotuner import OutOfResources
|
| 20 |
+
from triton.runtime.jit import JITFunction, KernelInterface
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from triton.runtime.autotuner import PTXASError
|
| 24 |
+
except ImportError:
|
| 25 |
+
|
| 26 |
+
class PTXASError(Exception): # type: ignore[no-redef]
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
from triton.compiler.compiler import ASTSource
|
| 31 |
+
except ImportError:
|
| 32 |
+
ASTSource = None
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
from triton.backends.compiler import GPUTarget
|
| 36 |
+
except ImportError:
|
| 37 |
+
|
| 38 |
+
def GPUTarget(
|
| 39 |
+
backend: str,
|
| 40 |
+
arch: int | str,
|
| 41 |
+
warp_size: int,
|
| 42 |
+
) -> Any:
|
| 43 |
+
if torch.version.hip:
|
| 44 |
+
return [backend, arch, warp_size]
|
| 45 |
+
return (backend, arch)
|
| 46 |
+
|
| 47 |
+
# In the latest triton, math functions were shuffled around into different modules:
|
| 48 |
+
# https://github.com/triton-lang/triton/pull/3172
|
| 49 |
+
try:
|
| 50 |
+
from triton.language.extra import libdevice
|
| 51 |
+
|
| 52 |
+
libdevice = tl.extra.libdevice # noqa: F811
|
| 53 |
+
math = tl.math
|
| 54 |
+
except ImportError:
|
| 55 |
+
if hasattr(tl.extra, "cuda") and hasattr(tl.extra.cuda, "libdevice"):
|
| 56 |
+
libdevice = tl.extra.cuda.libdevice
|
| 57 |
+
math = tl.math
|
| 58 |
+
elif hasattr(tl.extra, "intel") and hasattr(tl.extra.intel, "libdevice"):
|
| 59 |
+
libdevice = tl.extra.intel.libdevice
|
| 60 |
+
math = tl.math
|
| 61 |
+
else:
|
| 62 |
+
libdevice = tl.math
|
| 63 |
+
math = tl
|
| 64 |
+
|
| 65 |
+
try:
|
| 66 |
+
from triton.language.standard import _log2
|
| 67 |
+
except ImportError:
|
| 68 |
+
|
| 69 |
+
def _log2(x: Any) -> Any:
|
| 70 |
+
raise NotImplementedError
|
| 71 |
+
|
| 72 |
+
def _triton_config_has(param_name: str) -> bool:
|
| 73 |
+
if not hasattr(triton, "Config"):
|
| 74 |
+
return False
|
| 75 |
+
if not hasattr(triton.Config, "__init__"):
|
| 76 |
+
return False
|
| 77 |
+
return param_name in inspect.signature(triton.Config.__init__).parameters
|
| 78 |
+
|
| 79 |
+
# Drop the legacy support of autoWS
|
| 80 |
+
HAS_WARP_SPEC = False
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
from triton import knobs
|
| 84 |
+
except ImportError:
|
| 85 |
+
knobs = None
|
| 86 |
+
|
| 87 |
+
try:
|
| 88 |
+
from triton.runtime.cache import triton_key # type: ignore[attr-defined]
|
| 89 |
+
except ImportError:
|
| 90 |
+
from triton.compiler.compiler import (
|
| 91 |
+
triton_key, # type: ignore[attr-defined,no-redef]
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
builtins_use_semantic_kwarg = (
|
| 95 |
+
"_semantic" in inspect.signature(triton.language.core.view).parameters
|
| 96 |
+
)
|
| 97 |
+
HAS_TRITON = True
|
| 98 |
+
else:
|
| 99 |
+
|
| 100 |
+
def _raise_error(*args: Any, **kwargs: Any) -> Any:
|
| 101 |
+
raise RuntimeError("triton package is not installed")
|
| 102 |
+
|
| 103 |
+
class OutOfResources(Exception): # type: ignore[no-redef]
|
| 104 |
+
pass
|
| 105 |
+
|
| 106 |
+
class PTXASError(Exception): # type: ignore[no-redef]
|
| 107 |
+
pass
|
| 108 |
+
|
| 109 |
+
Config = object
|
| 110 |
+
CompiledKernel = object
|
| 111 |
+
KernelInterface = object
|
| 112 |
+
ASTSource = None
|
| 113 |
+
GPUTarget = None
|
| 114 |
+
_log2 = _raise_error
|
| 115 |
+
libdevice = None
|
| 116 |
+
math = None
|
| 117 |
+
knobs = None
|
| 118 |
+
builtins_use_semantic_kwarg = False
|
| 119 |
+
|
| 120 |
+
class triton: # type: ignore[no-redef]
|
| 121 |
+
@staticmethod
|
| 122 |
+
def jit(*args: Any, **kwargs: Any) -> Any:
|
| 123 |
+
return _raise_error
|
| 124 |
+
|
| 125 |
+
class tl: # type: ignore[no-redef]
|
| 126 |
+
@staticmethod
|
| 127 |
+
def constexpr(val: Any) -> Any:
|
| 128 |
+
return val
|
| 129 |
+
|
| 130 |
+
tensor = Any
|
| 131 |
+
dtype = Any
|
| 132 |
+
|
| 133 |
+
class JITFunction: # type: ignore[no-redef]
|
| 134 |
+
pass
|
| 135 |
+
|
| 136 |
+
HAS_WARP_SPEC = False
|
| 137 |
+
triton_key = _raise_error
|
| 138 |
+
HAS_TRITON = False
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def cc_warp_size(cc: str | int) -> int:
|
| 142 |
+
if torch.version.hip:
|
| 143 |
+
cc_str = str(cc)
|
| 144 |
+
if "gfx10" in cc_str or "gfx11" in cc_str:
|
| 145 |
+
return 32
|
| 146 |
+
else:
|
| 147 |
+
return 64
|
| 148 |
+
else:
|
| 149 |
+
return 32
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
try:
|
| 153 |
+
autograd_profiler = torch.autograd.profiler
|
| 154 |
+
except AttributeError: # Compile workers only have a mock version of torch
|
| 155 |
+
|
| 156 |
+
class autograd_profiler: # type: ignore[no-redef]
|
| 157 |
+
_is_profiler_enabled = False
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
__all__ = [
|
| 161 |
+
"Config",
|
| 162 |
+
"CompiledKernel",
|
| 163 |
+
"OutOfResources",
|
| 164 |
+
"KernelInterface",
|
| 165 |
+
"PTXASError",
|
| 166 |
+
"ASTSource",
|
| 167 |
+
"GPUTarget",
|
| 168 |
+
"tl",
|
| 169 |
+
"_log2",
|
| 170 |
+
"libdevice",
|
| 171 |
+
"math",
|
| 172 |
+
"triton",
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
import math as pymath
|
| 4 |
+
import warnings
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
from typing import Any, TypeVar
|
| 7 |
+
|
| 8 |
+
from .triton_compat import ( # noqa: F401
|
| 9 |
+
_log2,
|
| 10 |
+
builtins_use_semantic_kwarg,
|
| 11 |
+
JITFunction,
|
| 12 |
+
libdevice,
|
| 13 |
+
math,
|
| 14 |
+
tl,
|
| 15 |
+
triton,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_T = TypeVar("_T")
|
| 20 |
+
_LOG_2_E: tl.constexpr = tl.constexpr(pymath.log2(pymath.e))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def set_driver_to_cpu():
|
| 24 |
+
driver = triton.runtime.driver
|
| 25 |
+
if backend := triton.backends.backends.get("cpu", None):
|
| 26 |
+
if isinstance(driver.active, backend.driver):
|
| 27 |
+
# Don't re-initialize backend if it is already active
|
| 28 |
+
return
|
| 29 |
+
driver.set_active(backend.driver())
|
| 30 |
+
return
|
| 31 |
+
# This can be a hard error once triton-cpu is merged into fbcode
|
| 32 |
+
warnings.warn(
|
| 33 |
+
"Could not find an active CPU backend. Generated kernels will not be executable!"
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def set_driver_to_gpu():
|
| 38 |
+
driver = triton.runtime.driver
|
| 39 |
+
for name, backend in triton.backends.backends.items():
|
| 40 |
+
if backend.driver.is_active() and name != "cpu":
|
| 41 |
+
# After https://github.com/triton-lang/triton/commit/b844d519bc5e86edf00fe6b3c6c2d1badcd509a4,
|
| 42 |
+
# `driver.active` can be of `LazyProxy` type and the sign of this - `_obj` attribute.
|
| 43 |
+
if (
|
| 44 |
+
isinstance(driver.active, backend.driver)
|
| 45 |
+
or hasattr(driver.active, "_obj")
|
| 46 |
+
and isinstance(driver.active._obj, backend.driver)
|
| 47 |
+
):
|
| 48 |
+
# Don't re-initialize backend if it is already active
|
| 49 |
+
return
|
| 50 |
+
driver.set_active(backend.driver())
|
| 51 |
+
return
|
| 52 |
+
raise RuntimeError("Could not find an active GPU backend")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_backend_options():
|
| 56 |
+
from triton.runtime import driver
|
| 57 |
+
|
| 58 |
+
target = driver.active.get_current_target()
|
| 59 |
+
backend = triton.compiler.compiler.make_backend(target)
|
| 60 |
+
options = backend.parse_options(dict())
|
| 61 |
+
return options.__dict__
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_constexprs(kernel: JITFunction) -> list[int]:
|
| 65 |
+
return [p.num for p in kernel.params if p.is_constexpr]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
@triton.jit
|
| 69 |
+
def promote_to_tensor(x):
|
| 70 |
+
# Addition promotes to tensor for us
|
| 71 |
+
return x + tl.zeros((1,), tl.int1)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@triton.jit
|
| 75 |
+
def div_floor_integer(a, b):
|
| 76 |
+
# NOTE: a // b is C division, but we want floor division
|
| 77 |
+
# Based on c10::div_floor_integer
|
| 78 |
+
quot = a // b
|
| 79 |
+
remainder = a % b
|
| 80 |
+
fixed = tl.where(remainder != 0, quot - 1, quot)
|
| 81 |
+
return tl.where((a < 0) != (b < 0), fixed, quot)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@triton.jit
|
| 85 |
+
def remainder_integer(a, b):
|
| 86 |
+
# NOTE: a % b matches C division, not floor division
|
| 87 |
+
remainder = a % b
|
| 88 |
+
return tl.where((remainder != 0) & ((a < 0) != (b < 0)), remainder + b, remainder)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@triton.jit
|
| 92 |
+
def is_floating(x):
|
| 93 |
+
return promote_to_tensor(x).dtype.is_floating()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@triton.jit
|
| 97 |
+
def _prod_accumulate(a, b):
|
| 98 |
+
return a * b
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@triton.jit
|
| 102 |
+
def prod(input, axis):
|
| 103 |
+
return tl.reduce(input, axis, _prod_accumulate)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@triton.jit
|
| 107 |
+
def minimum(a, b):
|
| 108 |
+
mask = a < b
|
| 109 |
+
if is_floating(a):
|
| 110 |
+
mask |= a != a
|
| 111 |
+
return tl.where(mask, a, b)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@triton.jit
|
| 115 |
+
def maximum(a, b):
|
| 116 |
+
mask = a > b
|
| 117 |
+
if is_floating(a):
|
| 118 |
+
mask |= a != a
|
| 119 |
+
return tl.where(mask, a, b)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@triton.jit
|
| 123 |
+
def min2(a, dim):
|
| 124 |
+
return tl.reduce(a, dim, minimum)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@triton.jit
|
| 128 |
+
def max2(a, dim):
|
| 129 |
+
return tl.reduce(a, dim, maximum)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@triton.jit
|
| 133 |
+
def minimum_with_index(a_value, a_index, b_value, b_index):
|
| 134 |
+
mask = a_value < b_value
|
| 135 |
+
equal = a_value == b_value
|
| 136 |
+
if is_floating(a_value):
|
| 137 |
+
a_isnan = a_value != a_value
|
| 138 |
+
b_isnan = b_value != b_value
|
| 139 |
+
mask |= a_isnan & (not b_isnan)
|
| 140 |
+
# Consider NaNs as equal
|
| 141 |
+
equal |= a_isnan & b_isnan
|
| 142 |
+
|
| 143 |
+
# Prefer lowest index if values are equal
|
| 144 |
+
mask |= equal & (a_index < b_index)
|
| 145 |
+
return tl.where(mask, a_value, b_value), tl.where(mask, a_index, b_index)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
@triton.jit
|
| 149 |
+
def maximum_with_index(a_value, a_index, b_value, b_index):
|
| 150 |
+
mask = a_value > b_value
|
| 151 |
+
equal = a_value == b_value
|
| 152 |
+
if is_floating(a_value):
|
| 153 |
+
a_isnan = a_value != a_value
|
| 154 |
+
b_isnan = b_value != b_value
|
| 155 |
+
mask |= a_isnan & (not b_isnan)
|
| 156 |
+
# Consider NaNs as equal
|
| 157 |
+
equal |= a_isnan & b_isnan
|
| 158 |
+
|
| 159 |
+
# Prefer lowest index if values are equal
|
| 160 |
+
mask |= equal & (a_index < b_index)
|
| 161 |
+
return tl.where(mask, a_value, b_value), tl.where(mask, a_index, b_index)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@triton.jit
|
| 165 |
+
def min_with_index(value, index, dim):
|
| 166 |
+
return tl.reduce((value, index), dim, minimum_with_index)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@triton.jit
|
| 170 |
+
def max_with_index(value, index, dim):
|
| 171 |
+
return tl.reduce((value, index), dim, maximum_with_index)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
@triton.jit
|
| 175 |
+
def exp(x, use_fast_math: tl.constexpr):
|
| 176 |
+
if use_fast_math:
|
| 177 |
+
return math.exp(x)
|
| 178 |
+
else:
|
| 179 |
+
return libdevice.exp(x)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
@triton.jit
|
| 183 |
+
def online_softmax_reduce(lhs_max, lhs_sum, dim, use_fast_math: tl.constexpr):
|
| 184 |
+
out_max = max2(lhs_max, dim)
|
| 185 |
+
out_max_keepdim = tl.expand_dims(out_max, dim)
|
| 186 |
+
delta = tl.where(out_max_keepdim == float("-inf"), 0, lhs_max - out_max_keepdim)
|
| 187 |
+
out_sum = tl.sum(lhs_sum * exp(delta, use_fast_math), dim)
|
| 188 |
+
return out_max, out_sum
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@triton.jit
|
| 192 |
+
def online_softmax_combine(lhs_max, lhs_sum, rhs_max, use_fast_math: tl.constexpr):
|
| 193 |
+
"""
|
| 194 |
+
When we do combine, we assume lhs is the accumulator and rhs is the next
|
| 195 |
+
block of data.
|
| 196 |
+
Then rhs_sum is always 1. With that assumption, we can save some registers
|
| 197 |
+
and computation.
|
| 198 |
+
"""
|
| 199 |
+
out_max = maximum(lhs_max, rhs_max)
|
| 200 |
+
|
| 201 |
+
lhs_scale = tl.where(
|
| 202 |
+
out_max == float("-inf"), 1.0, exp(lhs_max - out_max, use_fast_math)
|
| 203 |
+
)
|
| 204 |
+
rhs_scale = tl.where(
|
| 205 |
+
out_max == float("-inf"), 1.0, exp(rhs_max - out_max, use_fast_math)
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
# Should be
|
| 209 |
+
# out_sum = lhs_sum * lhs_scale + rhs_sum * rhs_scale
|
| 210 |
+
# but since rhs_sum is all 1, we can simplify it.
|
| 211 |
+
out_sum = lhs_sum * lhs_scale + rhs_scale
|
| 212 |
+
return out_max, out_sum
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@triton.jit
|
| 216 |
+
def welford_reduce(value, mean, m2, weight, first_iteration):
|
| 217 |
+
if first_iteration:
|
| 218 |
+
new_weight = tl.full(weight.shape, 1, weight.dtype)
|
| 219 |
+
new_mean = value
|
| 220 |
+
new_m2 = tl.zeros_like(m2)
|
| 221 |
+
else:
|
| 222 |
+
delta = value - mean
|
| 223 |
+
new_weight = weight + 1
|
| 224 |
+
new_mean = mean + delta / new_weight
|
| 225 |
+
new_m2 = m2 + delta * (value - new_mean)
|
| 226 |
+
return new_mean, new_m2, new_weight
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@triton.jit
|
| 230 |
+
def welford_combine(mean_1, m2_1, weight_1, mean_2, m2_2, weight_2):
|
| 231 |
+
delta = mean_2 - mean_1
|
| 232 |
+
new_weight = weight_1 + weight_2
|
| 233 |
+
w2_over_w = tl.where(new_weight == 0.0, 0.0, weight_2 / new_weight)
|
| 234 |
+
return (
|
| 235 |
+
mean_1 + delta * w2_over_w,
|
| 236 |
+
m2_1 + m2_2 + delta * delta * weight_1 * w2_over_w,
|
| 237 |
+
new_weight,
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@triton.jit
|
| 242 |
+
def welford(mean, m2, weight, dim):
|
| 243 |
+
return tl.reduce((mean, m2, weight), dim, welford_combine)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
@triton.jit
|
| 247 |
+
def device_assert_then(cond, msg, r):
|
| 248 |
+
tl.device_assert(cond, msg)
|
| 249 |
+
return r
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@triton.jit
|
| 253 |
+
def randint64(seed, offset, low, high):
|
| 254 |
+
r0, r1, _r2, _r3 = tl.randint4x(seed, offset)
|
| 255 |
+
r0 = r0.to(tl.uint64)
|
| 256 |
+
r1 = r1.to(tl.uint64)
|
| 257 |
+
result = r0 | (r1 << 32)
|
| 258 |
+
size = high - low
|
| 259 |
+
result = result % size.to(tl.uint64)
|
| 260 |
+
result = result.to(tl.int64) + low
|
| 261 |
+
return result
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
@triton.jit
|
| 265 |
+
def _any_combine(a, b):
|
| 266 |
+
return a | b
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
@triton.jit
|
| 270 |
+
def any(a, dim):
|
| 271 |
+
return tl.reduce(a, dim, _any_combine)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@triton.jit
|
| 275 |
+
def bucketize_binary_search(
|
| 276 |
+
values: tl.tensor,
|
| 277 |
+
boundaries_ptr: tl.tensor,
|
| 278 |
+
BOUNDARIES_SIZE: int,
|
| 279 |
+
BOUNDARIES_UNDERLYING_NUMEL: int,
|
| 280 |
+
BOUNDARIES_STRIDE: int,
|
| 281 |
+
boundary_indices: tl.tensor,
|
| 282 |
+
indexing_dtype: tl.dtype,
|
| 283 |
+
right: "bool", # triton can't handle the unquoted bool annotation
|
| 284 |
+
sorter_ptr: tl.tensor,
|
| 285 |
+
SORTER_STRIDE: int,
|
| 286 |
+
sorter_indices: tl.tensor,
|
| 287 |
+
):
|
| 288 |
+
"""
|
| 289 |
+
See [Note: Inductor bucketize op]
|
| 290 |
+
|
| 291 |
+
Inputs:
|
| 292 |
+
-------
|
| 293 |
+
values: the values to bucketize.
|
| 294 |
+
boundaries_ptr: a pointer to the beginning of the boundaries tensor, in 1-D.
|
| 295 |
+
BOUNDARIES_SIZE: the length of the last dimension of the boundaries tensor (i.e. one
|
| 296 |
+
individual set of boundaries).
|
| 297 |
+
BOUNDARIES_UNDERLYING_NUMEL: the length of the boundaries tensor, in 1-D, ignoring
|
| 298 |
+
any striding.
|
| 299 |
+
BOUNDARIES_STRIDE: the stride of the last dimension of the boundaries tensor
|
| 300 |
+
boundary_indices: a tensor of the same size as "values"; each element is an index
|
| 301 |
+
into a 1-D, un-strided boundaries tensor, pointing to the first element in the set
|
| 302 |
+
of boundaries used for that value.
|
| 303 |
+
indexing_dtype: the dtype used for indexing into the boundaries tensor, and the
|
| 304 |
+
return dtype.
|
| 305 |
+
right: if true, use boundary intervals closed on the left; otherwise use intervals
|
| 306 |
+
closed on the right.
|
| 307 |
+
sorter_ptr: an optional pointer to a sorter tensor of the same shape as boundaries,
|
| 308 |
+
but potentially different striding. If present, this allows us to treat boundaries
|
| 309 |
+
as sorted even if the elements of boundaries are unsorted.
|
| 310 |
+
SORTER_STRIDE: must be present if sorter_ptr is non-None; the stride of the last
|
| 311 |
+
dimension of the sorter tensor.
|
| 312 |
+
sorter_indices: must be present if sorter_ptr is non-None; see "boundary_indices".
|
| 313 |
+
BLOCK_SHAPE: the shape of the data block being processed.
|
| 314 |
+
"""
|
| 315 |
+
|
| 316 |
+
low = tl.zeros(values.shape, dtype=indexing_dtype)
|
| 317 |
+
high = tl.full(values.shape, BOUNDARIES_SIZE, dtype=indexing_dtype)
|
| 318 |
+
|
| 319 |
+
full_range = BOUNDARIES_SIZE + 1
|
| 320 |
+
while full_range > 1:
|
| 321 |
+
mid = (high + low) // 2
|
| 322 |
+
mask = (
|
| 323 |
+
(mid * BOUNDARIES_STRIDE + boundary_indices) < BOUNDARIES_UNDERLYING_NUMEL
|
| 324 |
+
).logical_and(mid < BOUNDARIES_SIZE)
|
| 325 |
+
mid_indices = (
|
| 326 |
+
mid
|
| 327 |
+
if sorter_ptr is None or SORTER_STRIDE is None
|
| 328 |
+
else tl.load(
|
| 329 |
+
sorter_ptr + sorter_indices + SORTER_STRIDE * mid,
|
| 330 |
+
mask=mask,
|
| 331 |
+
other=0,
|
| 332 |
+
)
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
bucket_upper_bound = tl.load(
|
| 336 |
+
boundaries_ptr + boundary_indices + BOUNDARIES_STRIDE * mid_indices,
|
| 337 |
+
mask=mask,
|
| 338 |
+
other=0,
|
| 339 |
+
)
|
| 340 |
+
if right:
|
| 341 |
+
is_above = values >= bucket_upper_bound
|
| 342 |
+
else:
|
| 343 |
+
is_above = values > bucket_upper_bound
|
| 344 |
+
|
| 345 |
+
low = tl.where(is_above & mask, mid + 1, low)
|
| 346 |
+
high = tl.where(is_above, high, mid)
|
| 347 |
+
|
| 348 |
+
full_range = (full_range + 1) // 2
|
| 349 |
+
|
| 350 |
+
return low
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
@triton.jit
|
| 354 |
+
def pack_value_flag(
|
| 355 |
+
value,
|
| 356 |
+
flag,
|
| 357 |
+
DTYPE_VALUE_AS_UINT: tl.constexpr,
|
| 358 |
+
DTYPE_PACK: tl.constexpr,
|
| 359 |
+
):
|
| 360 |
+
# Workaround for triton bug, tensor.to doesn't unwrap constexpr values
|
| 361 |
+
DTYPE_VALUE_AS_UINT = tl.core._unwrap_if_constexpr(DTYPE_VALUE_AS_UINT)
|
| 362 |
+
bitwidth = DTYPE_VALUE_AS_UINT.primitive_bitwidth
|
| 363 |
+
uv = value.to(DTYPE_VALUE_AS_UINT, bitcast=True).to(DTYPE_PACK)
|
| 364 |
+
return flag.to(DTYPE_PACK) | (uv << bitwidth)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@triton.jit
|
| 368 |
+
def unpack_value(
|
| 369 |
+
pack,
|
| 370 |
+
DTYPE_VALUE,
|
| 371 |
+
DTYPE_VALUE_AS_UINT,
|
| 372 |
+
):
|
| 373 |
+
# Workaround for triton bug, tensor.to doesn't unwrap constexpr values
|
| 374 |
+
DTYPE_VALUE = tl.core._unwrap_if_constexpr(DTYPE_VALUE)
|
| 375 |
+
DTYPE_VALUE_AS_UINT = tl.core._unwrap_if_constexpr(DTYPE_VALUE_AS_UINT)
|
| 376 |
+
bitwidth = DTYPE_VALUE_AS_UINT.primitive_bitwidth
|
| 377 |
+
value_uint = (pack >> bitwidth).to(DTYPE_VALUE_AS_UINT)
|
| 378 |
+
return value_uint.to(DTYPE_VALUE, bitcast=True)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@triton.jit
|
| 382 |
+
def unpack_flag(pack, DTYPE_FLAG):
|
| 383 |
+
return pack.to(DTYPE_FLAG)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
@triton.jit
|
| 387 |
+
def exclusive_scan_decoupled_lookback(
|
| 388 |
+
scratch_base,
|
| 389 |
+
block_value,
|
| 390 |
+
index,
|
| 391 |
+
combine_fn,
|
| 392 |
+
DTYPE_VALUE_AS_UINT: tl.constexpr,
|
| 393 |
+
DTYPE_PACK: tl.constexpr,
|
| 394 |
+
):
|
| 395 |
+
"""Compute exclusive scan of a scalar value between blocks
|
| 396 |
+
|
| 397 |
+
Ref: https://research.nvidia.com/publication/2016-03_single-pass-parallel-prefix-scan-decoupled-look-back
|
| 398 |
+
|
| 399 |
+
scratch_base: Pointer to scratch space in global memory
|
| 400 |
+
block_value: Scalar value for this block
|
| 401 |
+
index: Scalar index of this block relative to the current scan
|
| 402 |
+
combine_fn: Function ``(value, value) -> value`` which is scanned over
|
| 403 |
+
DTYPE_VALUE_AS_UINT: A tl.uint{n} type equal in size to ``block_value``
|
| 404 |
+
DTYPE_PACK: Unsigned type twice the width of block_value
|
| 405 |
+
|
| 406 |
+
NOTE: This function is limited to values which are 32-bits or less because
|
| 407 |
+
we need to pack (value, flag) into a single unsigned int.
|
| 408 |
+
"""
|
| 409 |
+
# Publish block sum so subsequent blocks don't get stuck waiting for us
|
| 410 |
+
DTYPE_VALUE = block_value.dtype
|
| 411 |
+
pack = pack_value_flag(
|
| 412 |
+
block_value,
|
| 413 |
+
tl.full(block_value.shape, 1, DTYPE_VALUE_AS_UINT),
|
| 414 |
+
DTYPE_VALUE_AS_UINT,
|
| 415 |
+
DTYPE_PACK,
|
| 416 |
+
)
|
| 417 |
+
if index > 0:
|
| 418 |
+
tl.atomic_xchg(scratch_base + index, pack, sem="relaxed")
|
| 419 |
+
|
| 420 |
+
# Calculate exclusive prefix scan
|
| 421 |
+
exclusive_prefix = tl.zeros([], DTYPE_VALUE)
|
| 422 |
+
prefix_valid = False
|
| 423 |
+
test_target = index - 1
|
| 424 |
+
while test_target >= 0:
|
| 425 |
+
# tl.atomic_load
|
| 426 |
+
flag = tl.full([], 0, DTYPE_VALUE_AS_UINT)
|
| 427 |
+
while flag == 0:
|
| 428 |
+
pack = tl.atomic_add(scratch_base + test_target, 0, sem="relaxed")
|
| 429 |
+
flag = unpack_flag(pack, DTYPE_VALUE_AS_UINT)
|
| 430 |
+
|
| 431 |
+
value = unpack_value(pack, DTYPE_VALUE, DTYPE_VALUE_AS_UINT)
|
| 432 |
+
if prefix_valid:
|
| 433 |
+
exclusive_prefix = combine_fn(value, exclusive_prefix)
|
| 434 |
+
else:
|
| 435 |
+
exclusive_prefix = value
|
| 436 |
+
prefix_valid = True
|
| 437 |
+
|
| 438 |
+
if flag == 2:
|
| 439 |
+
test_target = -1
|
| 440 |
+
else:
|
| 441 |
+
test_target = test_target - 1
|
| 442 |
+
|
| 443 |
+
# Make inclusive block sum visible to other blocks
|
| 444 |
+
if prefix_valid:
|
| 445 |
+
inclusive_prefix = combine_fn(exclusive_prefix, block_value)
|
| 446 |
+
else:
|
| 447 |
+
inclusive_prefix = block_value
|
| 448 |
+
pack = pack_value_flag(
|
| 449 |
+
inclusive_prefix,
|
| 450 |
+
tl.full([], 2, DTYPE_VALUE_AS_UINT),
|
| 451 |
+
DTYPE_VALUE_AS_UINT,
|
| 452 |
+
DTYPE_PACK,
|
| 453 |
+
)
|
| 454 |
+
tl.atomic_xchg(scratch_base + index, pack, sem="relaxed")
|
| 455 |
+
return exclusive_prefix
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
@triton.jit
|
| 459 |
+
def exclusive_scan_decoupled_lookback_64(scratch_base, block_value, index, combine_fn):
|
| 460 |
+
"""Compute exclusive scan of a scalar value between blocks
|
| 461 |
+
|
| 462 |
+
Ref: https://research.nvidia.com/publication/2016-03_single-pass-parallel-prefix-scan-decoupled-look-back
|
| 463 |
+
|
| 464 |
+
scratch_base: Pointer to scratch space in global memory
|
| 465 |
+
block_value: Scalar value for this block, must be 64-bits wide
|
| 466 |
+
index: Scalar index of this block relative to the current scan
|
| 467 |
+
combine_fn: Function ``(value, value) -> value`` which is scanned over
|
| 468 |
+
init: Scalar value equal to the identity of combine_fn
|
| 469 |
+
"""
|
| 470 |
+
# Publish block sum so subsequent blocks don't get stuck waiting for us
|
| 471 |
+
if index > 0:
|
| 472 |
+
block_value_u64 = block_value.to(tl.uint64, bitcast=True)
|
| 473 |
+
tl.store(scratch_base + 3 * index + 1, block_value_u64)
|
| 474 |
+
tl.debug_barrier()
|
| 475 |
+
flag_one = tl.full([], 1, tl.uint64)
|
| 476 |
+
tl.atomic_xchg(scratch_base + 3 * index + 0, flag_one, sem="release")
|
| 477 |
+
|
| 478 |
+
# Calculate exclusive prefix scan
|
| 479 |
+
exclusive_prefix = tl.zeros([], block_value.dtype)
|
| 480 |
+
prefix_valid = False
|
| 481 |
+
test_target = index - 1
|
| 482 |
+
while test_target >= 0:
|
| 483 |
+
flag = tl.full([], 0, tl.uint64)
|
| 484 |
+
while flag == 0:
|
| 485 |
+
flag = tl.atomic_add(scratch_base + 3 * test_target + 0, 0, sem="acquire")
|
| 486 |
+
|
| 487 |
+
value_u64 = tl.load(scratch_base + 3 * test_target + flag.to(tl.int32))
|
| 488 |
+
value = value_u64.to(block_value.dtype, bitcast=True)
|
| 489 |
+
if prefix_valid:
|
| 490 |
+
exclusive_prefix = combine_fn(value, exclusive_prefix)
|
| 491 |
+
else:
|
| 492 |
+
exclusive_prefix = value
|
| 493 |
+
prefix_valid = True
|
| 494 |
+
|
| 495 |
+
if flag == 2:
|
| 496 |
+
test_target = -1
|
| 497 |
+
else:
|
| 498 |
+
test_target = test_target - 1
|
| 499 |
+
|
| 500 |
+
# Make inclusive block sum visible to other blocks
|
| 501 |
+
if prefix_valid:
|
| 502 |
+
inclusive_prefix = combine_fn(exclusive_prefix, block_value)
|
| 503 |
+
else:
|
| 504 |
+
inclusive_prefix = block_value
|
| 505 |
+
inclusive_prefix_u64 = inclusive_prefix.to(tl.uint64, bitcast=True)
|
| 506 |
+
tl.store(scratch_base + 3 * index + 2, inclusive_prefix_u64)
|
| 507 |
+
tl.debug_barrier()
|
| 508 |
+
flag_two = tl.full([], 2, tl.uint64)
|
| 509 |
+
tl.atomic_xchg(scratch_base + 3 * index + 0, flag_two, sem="release")
|
| 510 |
+
|
| 511 |
+
return exclusive_prefix
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
@triton.jit
|
| 515 |
+
def frexp(x):
|
| 516 |
+
# TODO(isuruf): use inline_asm_elementwise here
|
| 517 |
+
y = libdevice.ilogb(x) + 1
|
| 518 |
+
exponent = tl.where(x == 0, 0, y)
|
| 519 |
+
mantissa = tl.where(x == 0, 0, libdevice.ldexp(x, -y))
|
| 520 |
+
return mantissa, exponent
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@triton.jit
|
| 524 |
+
def _compare_and_swap_with_index(
|
| 525 |
+
x,
|
| 526 |
+
idxs,
|
| 527 |
+
rnumel,
|
| 528 |
+
flip,
|
| 529 |
+
i: tl.constexpr,
|
| 530 |
+
n_dims: tl.constexpr,
|
| 531 |
+
stable: tl.constexpr,
|
| 532 |
+
descending: tl.constexpr,
|
| 533 |
+
):
|
| 534 |
+
n_outer: tl.constexpr = x.numel >> n_dims
|
| 535 |
+
shape: tl.constexpr = [n_outer * 2**i, 2, 2 ** (n_dims - i - 1)]
|
| 536 |
+
|
| 537 |
+
idtype = tl.core.get_int_dtype(bitwidth=x.dtype.primitive_bitwidth, signed=True)
|
| 538 |
+
|
| 539 |
+
y = tl.reshape(x, shape)
|
| 540 |
+
iy = y.to(idtype, bitcast=True)
|
| 541 |
+
# slice left/right with 'stride' 2**(n_dims - i - 1)
|
| 542 |
+
right_mask = tl.arange(0, 2)[None, :, None].to(idtype)
|
| 543 |
+
left_mask = (1 - right_mask).to(idtype)
|
| 544 |
+
ileft = tl.broadcast_to(tl.sum(iy * left_mask, 1).to(idtype)[:, None, :], shape)
|
| 545 |
+
iright = tl.broadcast_to(tl.sum(iy * right_mask, 1).to(idtype)[:, None, :], shape)
|
| 546 |
+
ileft = tl.reshape(ileft, x.shape)
|
| 547 |
+
iright = tl.reshape(iright, x.shape)
|
| 548 |
+
left = ileft.to(x.dtype, bitcast=True)
|
| 549 |
+
right = iright.to(x.dtype, bitcast=True)
|
| 550 |
+
|
| 551 |
+
# idx
|
| 552 |
+
y_idx = tl.reshape(idxs, shape)
|
| 553 |
+
left_idx = tl.broadcast_to(
|
| 554 |
+
tl.sum(y_idx * left_mask.to(y_idx.dtype), 1)[:, None, :], shape
|
| 555 |
+
)
|
| 556 |
+
right_idx = tl.broadcast_to(
|
| 557 |
+
tl.sum(y_idx * right_mask.to(y_idx.dtype), 1)[:, None, :], shape
|
| 558 |
+
)
|
| 559 |
+
left_idx = tl.reshape(left_idx, x.shape)
|
| 560 |
+
right_idx = tl.reshape(right_idx, x.shape)
|
| 561 |
+
|
| 562 |
+
# valid
|
| 563 |
+
if rnumel is None:
|
| 564 |
+
left_valid_mask = tl.full(x.shape, True, tl.int1)
|
| 565 |
+
right_valid_mask = tl.full(x.shape, True, tl.int1)
|
| 566 |
+
else:
|
| 567 |
+
left_valid_mask = left_idx < rnumel
|
| 568 |
+
right_valid_mask = right_idx < rnumel
|
| 569 |
+
|
| 570 |
+
# actual compare-and-swap
|
| 571 |
+
ix = x.to(idtype, bitcast=True)
|
| 572 |
+
|
| 573 |
+
# sort treats nan as having the higher value. comparisons with nan always return False.
|
| 574 |
+
# to align with sort semantics, we need to update descending to check if right_isnan,
|
| 575 |
+
# and ascending to check if left_isnan.
|
| 576 |
+
left_isnan = left != left
|
| 577 |
+
right_isnan = right != right
|
| 578 |
+
|
| 579 |
+
if descending:
|
| 580 |
+
cond = left < right
|
| 581 |
+
if is_floating(left):
|
| 582 |
+
if not stable:
|
| 583 |
+
cond = cond | right_isnan
|
| 584 |
+
else:
|
| 585 |
+
cond = cond | (right_isnan & (~left_isnan))
|
| 586 |
+
|
| 587 |
+
else:
|
| 588 |
+
cond = left > right
|
| 589 |
+
if is_floating(left):
|
| 590 |
+
if not stable:
|
| 591 |
+
cond = cond | left_isnan
|
| 592 |
+
else:
|
| 593 |
+
cond = cond | (left_isnan & (~right_isnan))
|
| 594 |
+
|
| 595 |
+
if stable:
|
| 596 |
+
# When stable sorting, tie break by index
|
| 597 |
+
eq = left == right
|
| 598 |
+
if is_floating(left):
|
| 599 |
+
eq = eq | (left_isnan & right_isnan)
|
| 600 |
+
cond = cond | (eq & (left_idx > right_idx))
|
| 601 |
+
|
| 602 |
+
cond = (right_valid_mask > left_valid_mask) | (
|
| 603 |
+
(right_valid_mask == left_valid_mask) & cond
|
| 604 |
+
)
|
| 605 |
+
cond = (cond ^ flip).to(tl.int1)
|
| 606 |
+
ret = ix ^ tl.where(cond, ileft ^ iright, tl.zeros_like(ix))
|
| 607 |
+
new_idxs = idxs ^ tl.where(cond, left_idx ^ right_idx, tl.zeros_like(idxs))
|
| 608 |
+
|
| 609 |
+
return ret.to(x.dtype, bitcast=True), new_idxs
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
@triton.jit
|
| 613 |
+
def _bitonic_merge_with_index(
|
| 614 |
+
x,
|
| 615 |
+
idxs,
|
| 616 |
+
rnumel,
|
| 617 |
+
stage: tl.constexpr,
|
| 618 |
+
alternating: tl.constexpr,
|
| 619 |
+
n_dims: tl.constexpr,
|
| 620 |
+
stable: tl.constexpr,
|
| 621 |
+
descending: tl.constexpr,
|
| 622 |
+
):
|
| 623 |
+
n_outer: tl.constexpr = x.numel >> n_dims
|
| 624 |
+
tl.static_assert(stage <= n_dims)
|
| 625 |
+
# flip denotes whether to re-arrange sub-sequences of elements in ascending or
|
| 626 |
+
# descending order.
|
| 627 |
+
# if flip = 00000000... then all elements will be re-arranged ascendingly at this stage
|
| 628 |
+
# if flip = 00110011... then all the elements will be re-arranged alternatingly (with
|
| 629 |
+
# a stride of 2) at this stage
|
| 630 |
+
if alternating:
|
| 631 |
+
shape: tl.constexpr = [n_outer * 2 ** (n_dims - 1 - stage), 2, 2**stage]
|
| 632 |
+
flip = tl.reshape(
|
| 633 |
+
tl.broadcast_to(tl.arange(0, 2)[None, :, None], shape), x.shape
|
| 634 |
+
)
|
| 635 |
+
else:
|
| 636 |
+
flip = False
|
| 637 |
+
# perform `stage` rounds of `compare-and-swap`
|
| 638 |
+
for i in tl.static_range(stage):
|
| 639 |
+
x, idxs = _compare_and_swap_with_index(
|
| 640 |
+
x, idxs, rnumel, flip, i + (n_dims - stage), n_dims, stable, descending
|
| 641 |
+
)
|
| 642 |
+
return x, idxs
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
@triton.jit
|
| 646 |
+
def sort_with_index(
|
| 647 |
+
x, # value
|
| 648 |
+
idxs, # index
|
| 649 |
+
rnumel, # number of elements
|
| 650 |
+
dim: tl.constexpr = None,
|
| 651 |
+
stable: tl.constexpr = tl.constexpr(False),
|
| 652 |
+
descending: tl.constexpr = tl.constexpr(False),
|
| 653 |
+
):
|
| 654 |
+
x, idxs = tl.broadcast(x, idxs)
|
| 655 |
+
# handle default dimension or check that it is the most minor dim
|
| 656 |
+
_dim: tl.constexpr = len(x.shape) - 1 if dim is None else dim
|
| 657 |
+
tl.static_assert(
|
| 658 |
+
_dim == len(x.shape) - 1, "only minor dimension is currently supported"
|
| 659 |
+
)
|
| 660 |
+
# iteratively run bitonic merge-sort steps
|
| 661 |
+
n_dims: tl.constexpr = _log2(x.shape[_dim])
|
| 662 |
+
|
| 663 |
+
for i in tl.static_range(1, n_dims + 1):
|
| 664 |
+
x, idxs = _bitonic_merge_with_index(
|
| 665 |
+
x,
|
| 666 |
+
idxs,
|
| 667 |
+
rnumel,
|
| 668 |
+
i,
|
| 669 |
+
alternating=i < n_dims,
|
| 670 |
+
n_dims=n_dims,
|
| 671 |
+
stable=stable,
|
| 672 |
+
descending=descending,
|
| 673 |
+
)
|
| 674 |
+
return x, idxs
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
@triton.jit
|
| 678 |
+
def select_one(x, mask, dim, keep_dims=False):
|
| 679 |
+
idtype = tl.core.get_int_dtype(x.dtype.primitive_bitwidth, signed=False)
|
| 680 |
+
ix = x.to(idtype, bitcast=True)
|
| 681 |
+
iy = tl.sum(ix * mask, dim, keep_dims=keep_dims)
|
| 682 |
+
return iy.to(x.dtype, bitcast=True)
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
@triton.jit
|
| 686 |
+
def x_grid_barrier(sem):
|
| 687 |
+
"""
|
| 688 |
+
Wait for all other thread blocks in grid sharing same y/z program_id
|
| 689 |
+
to reach this barrier before returning.
|
| 690 |
+
|
| 691 |
+
Args:
|
| 692 |
+
sem: an uint32 semaphores, zero or 0x80000000 initialized. Must be unique to each y/z program ID.
|
| 693 |
+
"""
|
| 694 |
+
# ensure stores before this are visible
|
| 695 |
+
tl.debug_barrier()
|
| 696 |
+
|
| 697 |
+
one_i32 = 1
|
| 698 |
+
one_u32 = one_i32.to(tl.uint32) # type: ignore[attr-defined]
|
| 699 |
+
expected = tl.num_programs(0).to(tl.uint32)
|
| 700 |
+
if tl.program_id(0) == 0:
|
| 701 |
+
nb = 0x80000000 - (expected - one_u32)
|
| 702 |
+
else:
|
| 703 |
+
nb = one_u32
|
| 704 |
+
|
| 705 |
+
old_arrive = tl.atomic_add(sem, nb, sem="release")
|
| 706 |
+
|
| 707 |
+
bar_flipped = False
|
| 708 |
+
while not bar_flipped:
|
| 709 |
+
# want a `ld.acquire.gpu.u32 $0,[$1];` but Triton doesn't have it
|
| 710 |
+
current_arrive = tl.atomic_add(sem, 0, sem="acquire")
|
| 711 |
+
# current_arrive = tl.load(sem, volatile=True)
|
| 712 |
+
bar_flipped = ((old_arrive ^ current_arrive) & 0x80000000) != 0
|
| 713 |
+
|
| 714 |
+
# TODO(jansel): is this needed?
|
| 715 |
+
tl.debug_barrier()
|
| 716 |
+
|
| 717 |
+
|
| 718 |
+
def triton_builtin(f: Callable[..., _T]) -> Callable[..., _T]:
|
| 719 |
+
"""
|
| 720 |
+
Decorator to mark a function as a Triton built-in function. These functions
|
| 721 |
+
are evaluated at compile time.
|
| 722 |
+
|
| 723 |
+
Args:
|
| 724 |
+
f (function): The function to be marked as a Triton built-in.
|
| 725 |
+
|
| 726 |
+
Returns:
|
| 727 |
+
function: The same function, marked as a Triton built-in.
|
| 728 |
+
"""
|
| 729 |
+
if builtins_use_semantic_kwarg:
|
| 730 |
+
# support Triton before and after https://github.com/triton-lang/triton/pull/7054
|
| 731 |
+
# and after https://github.com/triton-lang/triton/pull/7239
|
| 732 |
+
def wrapper(*args, _semantic, **kwargs):
|
| 733 |
+
kwargs["_builder"] = _semantic
|
| 734 |
+
return f(*args, **kwargs)
|
| 735 |
+
else:
|
| 736 |
+
wrapper = f # type: ignore[assignment]
|
| 737 |
+
|
| 738 |
+
wrapper.__triton_builtin__ = True # type: ignore[attr-defined]
|
| 739 |
+
return wrapper
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
@triton_builtin
|
| 743 |
+
def constexpr_next_power_of_2(
|
| 744 |
+
n: tl.constexpr, *, _builder: object = None
|
| 745 |
+
) -> tl.constexpr:
|
| 746 |
+
"""
|
| 747 |
+
A version triton.next_power_of_two that can be used within a kernel on constants.
|
| 748 |
+
"""
|
| 749 |
+
assert isinstance(n, tl.constexpr)
|
| 750 |
+
return tl.constexpr(triton.next_power_of_2(n.value))
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
@triton_builtin
|
| 754 |
+
def if_mask(mask: Any, val, *, _builder: object = None) -> tl.constexpr:
|
| 755 |
+
"""
|
| 756 |
+
Work around triton compile error: `ValueError: `other` cannot be provided without `mask``
|
| 757 |
+
A compile-time to check to return either `val` or `None` depending on the value of mask.
|
| 758 |
+
"""
|
| 759 |
+
if isinstance(mask, tl.constexpr) and mask.value is None:
|
| 760 |
+
return tl.constexpr(None)
|
| 761 |
+
return val
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/runtime/triton_heuristics.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/template_heuristics/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTE: add new template heuristics here, so they get imported and registered
|
| 2 |
+
# TODO: write a simple glob if there are many heuristics to auto import them in the right order
|
| 3 |
+
from . import aten, base, contiguous_mm, decompose_k, registry, triton
|
| 4 |
+
|
| 5 |
+
# expose the entry function
|
| 6 |
+
from .registry import get_template_heuristic
|