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/analysis/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/analysis/device_info.py +216 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/analysis/profile_analysis.py +823 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py +296 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py +321 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py +150 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py +149 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py +109 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic.py +316 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py +340 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py +119 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py +89 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py +36 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp +488 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/block_analysis.py +192 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/common.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_bmm_template.py +263 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py +1090 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_gemm_template.py +1819 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py +511 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py +2232 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template.py +140 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template_kernel.py +621 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_utils.py +787 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py +897 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py +891 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py +301 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py +30 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_cpp_scheduling.py +296 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_env.py +55 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_kernel.py +687 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_template.py +394 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_cache.py +119 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/__init__.py +0 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/__init__.py +6 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/cuda.py +24 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/cudart.py +17 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/pydot/__init__.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/scipy/__init__.py +3 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/scipy/special.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/evt_extensions.py +276 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/gemm_operation_extensions.py +411 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_python_evt.py +326 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/analysis/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/analysis/device_info.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Optional, Union
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
log = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass(frozen=True)
|
| 12 |
+
class DeviceInfo:
|
| 13 |
+
"""
|
| 14 |
+
Theoretical Numbers from data sheet. If two numbers are given, Tensor/Matrix Core vs not,
|
| 15 |
+
then the higher number is reported. Sparsity is not considered.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
Bandwidth numbers are tricky, because there are platform differences that may not show up in the profiler trace.
|
| 19 |
+
For example,
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
tops: dict[Union[torch.dtype, str], float]
|
| 23 |
+
dram_bw_gbs: float
|
| 24 |
+
dram_gb: float
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Indexing is based on `torch.cuda.get_device_name()`
|
| 28 |
+
# TODO investigate profiler support for tf32 and allow device to report correct number when it's turned on.
|
| 29 |
+
_device_mapping: dict[str, DeviceInfo] = {
|
| 30 |
+
# Source:
|
| 31 |
+
# @lint-ignore https://www.nvidia.com/en-us/data-center/h100/
|
| 32 |
+
"NVIDIA H100": DeviceInfo(
|
| 33 |
+
tops={
|
| 34 |
+
torch.float64: 67.0,
|
| 35 |
+
torch.float32: 67.5,
|
| 36 |
+
"torch.tf32": 156.0,
|
| 37 |
+
torch.bfloat16: 1979.0,
|
| 38 |
+
torch.float16: 1979.0,
|
| 39 |
+
torch.float8_e8m0fnu: 3958.0,
|
| 40 |
+
torch.float8_e8m0fnu: 3958.0,
|
| 41 |
+
torch.float8_e4m3fnuz: 3958.0,
|
| 42 |
+
torch.float8_e5m2: 3958.0,
|
| 43 |
+
torch.float8_e5m2fnuz: 3958.0,
|
| 44 |
+
torch.float8_e8m0fnu: 3958.0,
|
| 45 |
+
torch.int8: 3958.0,
|
| 46 |
+
},
|
| 47 |
+
dram_bw_gbs=3350,
|
| 48 |
+
dram_gb=80,
|
| 49 |
+
),
|
| 50 |
+
# Source:
|
| 51 |
+
# @lint-ignore https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/
|
| 52 |
+
# nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf
|
| 53 |
+
"NVIDIA A100": DeviceInfo(
|
| 54 |
+
tops={
|
| 55 |
+
torch.float64: 19.5,
|
| 56 |
+
torch.float32: 19.5,
|
| 57 |
+
torch.bfloat16: 312.5,
|
| 58 |
+
torch.float16: 312.5,
|
| 59 |
+
# Not in datasheet: float8
|
| 60 |
+
torch.int8: 624.0,
|
| 61 |
+
"torch.tf32": 156.0,
|
| 62 |
+
},
|
| 63 |
+
dram_bw_gbs=2039.0,
|
| 64 |
+
dram_gb=80.0,
|
| 65 |
+
),
|
| 66 |
+
# Source:
|
| 67 |
+
# @lint-ignore https://resources.nvidia.com/en-us-gpu-resources/l4-tensor-datasheet
|
| 68 |
+
"NVIDIA L4": DeviceInfo(
|
| 69 |
+
tops={
|
| 70 |
+
# This is a guess, not in datasheet
|
| 71 |
+
torch.float64: 15.1,
|
| 72 |
+
torch.float32: 30.3,
|
| 73 |
+
"torch.tf32": 120.0,
|
| 74 |
+
torch.bfloat16: 242.0,
|
| 75 |
+
torch.float16: 242.0,
|
| 76 |
+
torch.float8_e8m0fnu: 485.0,
|
| 77 |
+
torch.float8_e8m0fnu: 485.0,
|
| 78 |
+
torch.float8_e4m3fnuz: 485.0,
|
| 79 |
+
torch.float8_e5m2: 485.0,
|
| 80 |
+
torch.float8_e5m2fnuz: 485.0,
|
| 81 |
+
torch.float8_e8m0fnu: 485.0,
|
| 82 |
+
torch.int8: 485.0,
|
| 83 |
+
},
|
| 84 |
+
dram_bw_gbs=3350,
|
| 85 |
+
dram_gb=24,
|
| 86 |
+
),
|
| 87 |
+
# Source:
|
| 88 |
+
# @lint-ignore https://www.amd.com/content/dam/amd/en/documents\
|
| 89 |
+
# /instinct-tech-docs/product-briefs/amd-instinct-mi350x-gpu-brochure.pdf
|
| 90 |
+
"AMD MI350X": DeviceInfo(
|
| 91 |
+
tops={
|
| 92 |
+
torch.float64: 72.1,
|
| 93 |
+
torch.float32: 144.2,
|
| 94 |
+
# not specified, fall back to float32 numbers
|
| 95 |
+
"torch.tf32": 144.2,
|
| 96 |
+
torch.bfloat16: 2309.6,
|
| 97 |
+
torch.float16: 2309.6,
|
| 98 |
+
torch.float8_e8m0fnu: 4614.0,
|
| 99 |
+
torch.float8_e8m0fnu: 4614.0,
|
| 100 |
+
torch.float8_e4m3fnuz: 4614.0,
|
| 101 |
+
torch.float8_e5m2: 4614.0,
|
| 102 |
+
torch.float8_e5m2fnuz: 4614.0,
|
| 103 |
+
torch.float8_e8m0fnu: 4614.0,
|
| 104 |
+
torch.int8: 4614.0,
|
| 105 |
+
},
|
| 106 |
+
dram_bw_gbs=8000.0,
|
| 107 |
+
dram_gb=288.0,
|
| 108 |
+
),
|
| 109 |
+
# Source:
|
| 110 |
+
# @lint-ignore https://www.amd.com/content/dam/amd/en/documents\
|
| 111 |
+
# /instinct-tech-docs/data-sheets/amd-instinct-mi300a-data-sheet.pdf
|
| 112 |
+
"AMD MI300A": DeviceInfo(
|
| 113 |
+
tops={
|
| 114 |
+
torch.float64: 122.6,
|
| 115 |
+
torch.float32: 122.6,
|
| 116 |
+
"torch.tf32": 490.3,
|
| 117 |
+
torch.bfloat16: 980.6,
|
| 118 |
+
torch.float16: 980.6,
|
| 119 |
+
torch.float8_e8m0fnu: 1961.2,
|
| 120 |
+
torch.float8_e8m0fnu: 1961.2,
|
| 121 |
+
torch.float8_e4m3fnuz: 1961.2,
|
| 122 |
+
torch.float8_e5m2: 1961.2,
|
| 123 |
+
torch.float8_e5m2fnuz: 1961.2,
|
| 124 |
+
torch.float8_e8m0fnu: 1961.2,
|
| 125 |
+
torch.int8: 1961.2,
|
| 126 |
+
},
|
| 127 |
+
dram_bw_gbs=5300.0,
|
| 128 |
+
dram_gb=128.0,
|
| 129 |
+
),
|
| 130 |
+
# Source:
|
| 131 |
+
# @lint-ignore https://www.amd.com/content/dam/amd/en/documents/\
|
| 132 |
+
# instinct-tech-docs/data-sheets/amd-instinct-mi300x-data-sheet.pdf
|
| 133 |
+
"AMD MI300X": DeviceInfo(
|
| 134 |
+
tops={
|
| 135 |
+
torch.float64: 163.4,
|
| 136 |
+
torch.float32: 163.4,
|
| 137 |
+
"torch.tf32": 653.7,
|
| 138 |
+
torch.bfloat16: 1307.4,
|
| 139 |
+
torch.float16: 1307.4,
|
| 140 |
+
torch.float8_e8m0fnu: 2614.9,
|
| 141 |
+
torch.float8_e8m0fnu: 2614.9,
|
| 142 |
+
torch.float8_e4m3fnuz: 2614.9,
|
| 143 |
+
torch.float8_e5m2: 2614.9,
|
| 144 |
+
torch.float8_e5m2fnuz: 2614.9,
|
| 145 |
+
torch.float8_e8m0fnu: 2614.9,
|
| 146 |
+
torch.int8: 2614.9,
|
| 147 |
+
},
|
| 148 |
+
dram_bw_gbs=5300.0,
|
| 149 |
+
dram_gb=192.0,
|
| 150 |
+
),
|
| 151 |
+
# Source:
|
| 152 |
+
# @lint-ignore https://www.amd.com/content/dam/amd/\
|
| 153 |
+
# en/documents/instinct-business-docs/product-briefs/instinct-mi210-brochure.pdf
|
| 154 |
+
"AMD MI210X": DeviceInfo(
|
| 155 |
+
tops={
|
| 156 |
+
torch.float64: 45.3,
|
| 157 |
+
torch.float32: 45.3,
|
| 158 |
+
# not specified, fall back to float32 numbers
|
| 159 |
+
"torch.tf32": 45.3,
|
| 160 |
+
torch.bfloat16: 181.0,
|
| 161 |
+
torch.float16: 181.0,
|
| 162 |
+
# not specified, fall back to float16 numbers
|
| 163 |
+
torch.float8_e8m0fnu: 181.0,
|
| 164 |
+
torch.float8_e8m0fnu: 181.0,
|
| 165 |
+
torch.float8_e4m3fnuz: 181.0,
|
| 166 |
+
torch.float8_e5m2: 181.0,
|
| 167 |
+
torch.float8_e5m2fnuz: 181.0,
|
| 168 |
+
torch.float8_e8m0fnu: 181.0,
|
| 169 |
+
torch.int8: 181.0,
|
| 170 |
+
},
|
| 171 |
+
# pcie4.0x16
|
| 172 |
+
dram_bw_gbs=1600.0,
|
| 173 |
+
dram_gb=64.0,
|
| 174 |
+
),
|
| 175 |
+
}
|
| 176 |
+
_device_mapping["AMD INSTINCT MI350X"] = _device_mapping["AMD MI350X"]
|
| 177 |
+
_device_mapping["AMD INSTINCT MI300X"] = _device_mapping["AMD MI300X"]
|
| 178 |
+
_device_mapping["AMD INSTINCT MI210X"] = _device_mapping["AMD MI210X"]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def lookup_device_info(name: str) -> Optional[DeviceInfo]:
|
| 182 |
+
"""
|
| 183 |
+
Problem: when diffing profiles between amd and nvidia, we don't have access to the device information
|
| 184 |
+
of the other one. Also, since the analysis is static, we should be able to do it on another device unrelated
|
| 185 |
+
to the recorded device. Therefore, _device_mapping statically contains the information for lots of devices.
|
| 186 |
+
If one is missing, please run DeviceInfo.get_device_info() and add it to _device_mapping.
|
| 187 |
+
name (str): name of the device to lookup. Should map onto torch.cuda.get_device_name().
|
| 188 |
+
"""
|
| 189 |
+
return _device_mapping.get(name)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def datasheet_tops(dtype: torch.dtype, is_tf32: bool = False) -> Optional[float]:
|
| 193 |
+
"""
|
| 194 |
+
Get the theoretical TFLOPS of the device for a given dtype. This can throw an exception if the device
|
| 195 |
+
is not in the datasheet list above.
|
| 196 |
+
"""
|
| 197 |
+
name: Optional[str] = torch.cuda.get_device_name()
|
| 198 |
+
if name is None:
|
| 199 |
+
log.info("No device found, returning None")
|
| 200 |
+
return None
|
| 201 |
+
device_info = lookup_device_info(name)
|
| 202 |
+
if device_info is None:
|
| 203 |
+
log_str = f"Device {name} not in datasheet, returning None"
|
| 204 |
+
log.info(log_str)
|
| 205 |
+
return None
|
| 206 |
+
if dtype not in device_info.tops:
|
| 207 |
+
log.info(
|
| 208 |
+
"Device %s does not have a datasheet entry for %s, returning None",
|
| 209 |
+
name,
|
| 210 |
+
dtype,
|
| 211 |
+
)
|
| 212 |
+
return None
|
| 213 |
+
|
| 214 |
+
return device_info.tops[
|
| 215 |
+
"torch.tf32" if dtype == torch.float32 and is_tf32 else dtype
|
| 216 |
+
]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/analysis/profile_analysis.py
ADDED
|
@@ -0,0 +1,823 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import logging
|
| 3 |
+
import math
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from typing import Any, Optional, Union
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
from torch._inductor.analysis.device_info import DeviceInfo, lookup_device_info
|
| 11 |
+
from torch._inductor.utils import tabulate_2d, zip_dicts
|
| 12 |
+
from torch.utils import _pytree as pytree
|
| 13 |
+
from torch.utils._ordered_set import OrderedSet
|
| 14 |
+
from torch.utils.flop_counter import flop_registry
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
log = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
ATEN_PREFIX = "aten::"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class ProfileEvent:
|
| 25 |
+
category: str
|
| 26 |
+
key: str
|
| 27 |
+
self_device_time_ms: float
|
| 28 |
+
# the benchmark is run multiple times and we average the count across all the
|
| 29 |
+
# runs. It should be an integer but define a float just in case.
|
| 30 |
+
count: float
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# adapters convert the json trace into a format that works with flops_counter
|
| 34 |
+
ArgsType = tuple[tuple[Any, ...], dict[Any, Any]]
|
| 35 |
+
AdapterType = Callable[[tuple[Any, ...], tuple[Any, ...]], ArgsType]
|
| 36 |
+
adapters_map: dict[str, AdapterType] = {}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def parse_list(lst: str) -> list[int]:
|
| 40 |
+
lst = lst.replace("[", "").replace("]", "")
|
| 41 |
+
substrings = lst.split(",")
|
| 42 |
+
|
| 43 |
+
return [int(substring.strip()) for substring in substrings]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def register_adapter(
|
| 47 |
+
aten: Union[str, list[str]],
|
| 48 |
+
) -> Callable[
|
| 49 |
+
[AdapterType],
|
| 50 |
+
AdapterType,
|
| 51 |
+
]:
|
| 52 |
+
def decorator(func: AdapterType) -> AdapterType:
|
| 53 |
+
# pyrefly: ignore [unknown-name]
|
| 54 |
+
global _adapters_map
|
| 55 |
+
|
| 56 |
+
if isinstance(aten, str):
|
| 57 |
+
adapters_map[aten] = func
|
| 58 |
+
else:
|
| 59 |
+
for at in aten:
|
| 60 |
+
adapters_map[at] = func
|
| 61 |
+
return func
|
| 62 |
+
|
| 63 |
+
return decorator
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@register_adapter(["_slow_conv2d_forward"])
|
| 67 |
+
def _slow_conv2d_adapter(
|
| 68 |
+
shapes: tuple[Any, ...], concrete: tuple[Any, ...]
|
| 69 |
+
) -> tuple[tuple[Any], dict[Any, Any]]:
|
| 70 |
+
tmp = list(shapes)
|
| 71 |
+
tmp.append(False)
|
| 72 |
+
tmp2 = list(concrete)
|
| 73 |
+
if len(tmp2) < 5:
|
| 74 |
+
raise ParseException("slow conv2d has less than 5 concrete inputs")
|
| 75 |
+
tmp2[3] = tmp2[4]
|
| 76 |
+
return conv_adapter(tuple(tmp), tuple(tmp2))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@register_adapter(
|
| 80 |
+
["convolution", "_convolution", "cudnn_convolution", "convolution_overrideable"]
|
| 81 |
+
)
|
| 82 |
+
def conv_adapter(
|
| 83 |
+
shapes: tuple[Any, ...], concrete: tuple[Any, ...]
|
| 84 |
+
) -> tuple[tuple[Any], dict[Any, Any]]:
|
| 85 |
+
tmp = list(shapes)
|
| 86 |
+
if len(tmp) == 4:
|
| 87 |
+
transposed = False
|
| 88 |
+
elif len(tmp) > 6:
|
| 89 |
+
transposed = bool(tmp[6])
|
| 90 |
+
tmp[6] = transposed
|
| 91 |
+
else:
|
| 92 |
+
raise ParseException(f"Convolution has the wrong number of inputs: {len(tmp)}")
|
| 93 |
+
|
| 94 |
+
kwargs: dict[Any, Any] = {}
|
| 95 |
+
if not transposed:
|
| 96 |
+
# calculate output shape if not transposed.
|
| 97 |
+
def conv_out_dims(x: int, kernel: int, stride: int) -> int:
|
| 98 |
+
return (x - kernel) // stride + 1
|
| 99 |
+
|
| 100 |
+
stride = parse_list(concrete[3])
|
| 101 |
+
inp = shapes[0]
|
| 102 |
+
w = shapes[1]
|
| 103 |
+
out_x_y = [conv_out_dims(*args) for args in zip(inp[2:], w[2:], stride)]
|
| 104 |
+
out = [inp[0], w[0]] + out_x_y # we only need the xy values
|
| 105 |
+
kwargs["out_val"] = out
|
| 106 |
+
|
| 107 |
+
return tuple(tmp), kwargs
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def default_adapter(
|
| 111 |
+
shapes: tuple[Any], concrete: tuple[Any]
|
| 112 |
+
) -> tuple[tuple[Any], dict[Any, Any]]:
|
| 113 |
+
return shapes, {}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@register_adapter("addmm")
|
| 117 |
+
def addmm_adapter(
|
| 118 |
+
shapes: tuple[Any], concrete: tuple[Any]
|
| 119 |
+
) -> tuple[tuple[Any], dict[Any, Any]]:
|
| 120 |
+
tmp = list(shapes)[:3]
|
| 121 |
+
return tuple(tmp), {}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@register_adapter("bmm")
|
| 125 |
+
def bmm_adapter(
|
| 126 |
+
shapes: tuple[Any], concrete: tuple[Any]
|
| 127 |
+
) -> tuple[tuple[Any], dict[Any, Any]]:
|
| 128 |
+
tmp = list(shapes)
|
| 129 |
+
return tuple(tmp[:2]), {}
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
@register_adapter("baddbmm")
|
| 133 |
+
def baddbmm_adapter(
|
| 134 |
+
shapes: tuple[Any], concrete: tuple[Any]
|
| 135 |
+
) -> tuple[tuple[Any], dict[Any, Any]]:
|
| 136 |
+
tmp = list(shapes)[:3]
|
| 137 |
+
return tuple(tmp), {}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
@register_adapter("mm")
|
| 141 |
+
def mm_adapter(
|
| 142 |
+
shapes: tuple[Any], concrete: tuple[Any]
|
| 143 |
+
) -> tuple[tuple[Any], dict[Any, Any]]:
|
| 144 |
+
return shapes, {}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _parse_kernel_name(name: str) -> Optional[str]:
|
| 148 |
+
"""
|
| 149 |
+
parse the name of the kernel from the event name.
|
| 150 |
+
"""
|
| 151 |
+
if name.startswith(ATEN_PREFIX):
|
| 152 |
+
return name[len(ATEN_PREFIX) :]
|
| 153 |
+
elif "conv" in name:
|
| 154 |
+
return "convolution"
|
| 155 |
+
elif "addmm" in name:
|
| 156 |
+
return "addmm"
|
| 157 |
+
elif "bmm" in name:
|
| 158 |
+
return "bmm"
|
| 159 |
+
elif "baddbmm" in name:
|
| 160 |
+
return "baddbmm"
|
| 161 |
+
elif "_mm" in name:
|
| 162 |
+
return "mm"
|
| 163 |
+
else:
|
| 164 |
+
return None
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _calculate_flops(event: dict[str, Any]) -> int:
|
| 168 |
+
"""
|
| 169 |
+
This function has to parse the kernel name, which is error prone. There doesn't seem to be another solution that
|
| 170 |
+
will support all the different backends that can generate kernels, so make sure to update this function when new
|
| 171 |
+
ops and backends are desired.
|
| 172 |
+
"""
|
| 173 |
+
name = event["name"]
|
| 174 |
+
if "kernel_flop" in event["args"] and event["args"]["kernel_flop"] != 0:
|
| 175 |
+
return event["args"]["kernel_flop"]
|
| 176 |
+
op_name = _parse_kernel_name(name)
|
| 177 |
+
if op_name is None:
|
| 178 |
+
return 0
|
| 179 |
+
|
| 180 |
+
op_obj = getattr(torch.ops.aten, op_name, None)
|
| 181 |
+
if op_obj is None or op_obj not in flop_registry:
|
| 182 |
+
return 0
|
| 183 |
+
|
| 184 |
+
flop_function = flop_registry[op_obj]
|
| 185 |
+
|
| 186 |
+
if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]:
|
| 187 |
+
return 0
|
| 188 |
+
input_shapes = event["args"]["Input Dims"]
|
| 189 |
+
concrete = event["args"]["Concrete Inputs"]
|
| 190 |
+
if op_name in adapters_map:
|
| 191 |
+
try:
|
| 192 |
+
args, kwargs = adapters_map[op_name](input_shapes, concrete)
|
| 193 |
+
except ParseException as e:
|
| 194 |
+
msg = f"Failed to parse {op_name} with {e}"
|
| 195 |
+
log.warning(msg)
|
| 196 |
+
return 0
|
| 197 |
+
else:
|
| 198 |
+
try:
|
| 199 |
+
args, kwargs = default_adapter(input_shapes, concrete)
|
| 200 |
+
except ParseException as e:
|
| 201 |
+
msg = f"Failed to parse {op_name} with {e}"
|
| 202 |
+
log.warning(msg)
|
| 203 |
+
return 0
|
| 204 |
+
return flop_function(*args, **kwargs)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _get_size_from_string(type_string: str) -> int:
|
| 208 |
+
if not hasattr(torch, type_string):
|
| 209 |
+
return 1
|
| 210 |
+
else:
|
| 211 |
+
return getattr(torch, type_string).itemsize
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _default_estimate_gb(event: dict[str, Any]) -> float:
|
| 215 |
+
sizes_and_types = zip(event["args"]["Input Dims"], event["args"]["Input type"])
|
| 216 |
+
bw = 0
|
| 217 |
+
for size, typ in sizes_and_types:
|
| 218 |
+
isize = _get_size_from_string(typ)
|
| 219 |
+
bw += isize * math.prod(pytree.tree_flatten(size)[0])
|
| 220 |
+
return bw / 1e9
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def _estimate_gb(event: dict[str, Any]) -> float:
|
| 224 |
+
"""
|
| 225 |
+
Our best effort to estimate the gb, should be refactored soon with MemoryCounter.
|
| 226 |
+
"""
|
| 227 |
+
name = event["name"]
|
| 228 |
+
if "kernel_num_gb" in event["args"] and event["args"]["kernel_num_gb"] != 0:
|
| 229 |
+
return event["args"]["kernel_num_gb"]
|
| 230 |
+
if "Input type" not in event["args"] or "Input Dims" not in event["args"]:
|
| 231 |
+
return 0
|
| 232 |
+
op_name = _parse_kernel_name(name)
|
| 233 |
+
if op_name is None:
|
| 234 |
+
return _default_estimate_gb(event)
|
| 235 |
+
|
| 236 |
+
op_obj = getattr(torch.ops.aten, op_name, None)
|
| 237 |
+
if op_obj is None:
|
| 238 |
+
return _default_estimate_gb(event)
|
| 239 |
+
|
| 240 |
+
if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]:
|
| 241 |
+
return _default_estimate_gb(event)
|
| 242 |
+
input_shapes = event["args"]["Input Dims"]
|
| 243 |
+
|
| 244 |
+
# NOTE these will be refactored into a similar object to FlopCounter soon
|
| 245 |
+
def mm_formula(M: int, N: int, K: int, size: int) -> int:
|
| 246 |
+
return 2 * (M * K + N * K + M * N) * size
|
| 247 |
+
|
| 248 |
+
if op_name == "addmm":
|
| 249 |
+
add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0])
|
| 250 |
+
add_type_size = _get_size_from_string(event["args"]["Input type"][0])
|
| 251 |
+
M = input_shapes[1][0]
|
| 252 |
+
N = input_shapes[1][1]
|
| 253 |
+
assert input_shapes[1][1] == input_shapes[2][0]
|
| 254 |
+
K = input_shapes[2][1]
|
| 255 |
+
mul_type_size = _get_size_from_string(event["args"]["Input type"][1])
|
| 256 |
+
return (mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size) / 1e9
|
| 257 |
+
elif op_name == "mm":
|
| 258 |
+
M = input_shapes[0][0]
|
| 259 |
+
N = input_shapes[0][1]
|
| 260 |
+
assert input_shapes[0][1] == input_shapes[1][0]
|
| 261 |
+
K = input_shapes[1][1]
|
| 262 |
+
type_size = _get_size_from_string(event["args"]["Input type"][0])
|
| 263 |
+
return mm_formula(M, N, K, type_size) / 1e9
|
| 264 |
+
elif op_name == "baddbmm":
|
| 265 |
+
add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0])
|
| 266 |
+
add_type_size = _get_size_from_string(event["args"]["Input type"][0])
|
| 267 |
+
B = input_shapes[0][0]
|
| 268 |
+
M = input_shapes[1][1]
|
| 269 |
+
N = input_shapes[1][2]
|
| 270 |
+
K = input_shapes[2][2]
|
| 271 |
+
mul_type_size = _get_size_from_string(event["args"]["Input type"][1])
|
| 272 |
+
return (
|
| 273 |
+
B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size
|
| 274 |
+
) / 1e9
|
| 275 |
+
elif op_name == "bmm":
|
| 276 |
+
add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0])
|
| 277 |
+
add_type_size = _get_size_from_string(event["args"]["Input type"][0])
|
| 278 |
+
B = input_shapes[0][0]
|
| 279 |
+
M = input_shapes[0][1]
|
| 280 |
+
N = input_shapes[0][2]
|
| 281 |
+
K = input_shapes[1][2]
|
| 282 |
+
mul_type_size = _get_size_from_string(event["args"]["Input type"][1])
|
| 283 |
+
return (
|
| 284 |
+
B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size
|
| 285 |
+
) / 1e9
|
| 286 |
+
elif op_name in [
|
| 287 |
+
"convolution",
|
| 288 |
+
"_convolution",
|
| 289 |
+
"cudnn_convolution",
|
| 290 |
+
"_slow_conv2d_forward",
|
| 291 |
+
]:
|
| 292 |
+
concrete = event["args"]["Concrete Inputs"]
|
| 293 |
+
|
| 294 |
+
def conv_out_dim(x: int, kernel: int, stride: int) -> int:
|
| 295 |
+
return (x - kernel) // stride + 1
|
| 296 |
+
|
| 297 |
+
stride = parse_list(
|
| 298 |
+
concrete[3] if op_name != "_slow_conv2d_forward" else concrete[4]
|
| 299 |
+
)
|
| 300 |
+
inp = input_shapes[0]
|
| 301 |
+
w = input_shapes[1]
|
| 302 |
+
out_x_y = [conv_out_dim(*args) for args in zip(inp[2:], w[2:], stride)]
|
| 303 |
+
out = [inp[0], w[0]] + out_x_y
|
| 304 |
+
# each output element reads in * w * w chunk
|
| 305 |
+
input_reads = out[0] * out[1] * out[2] * out[3] * inp[1] * w[2] * w[3]
|
| 306 |
+
# Assume weights are in cache, so only read once
|
| 307 |
+
weight_reads = w[0] * w[1] * w[2] * w[3]
|
| 308 |
+
return (input_reads + weight_reads) / 1e9
|
| 309 |
+
|
| 310 |
+
return _default_estimate_gb(event)
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _create_extern_mapping(
|
| 314 |
+
data: dict[str, Any],
|
| 315 |
+
) -> defaultdict[int, list[dict[str, Any]]]:
|
| 316 |
+
"""
|
| 317 |
+
compute a mapping from external ids to non kernels, which contain the information we need to estimate flops etc
|
| 318 |
+
"""
|
| 319 |
+
extern_mapping: defaultdict[int, list[dict[str, Any]]] = defaultdict(list)
|
| 320 |
+
for event in data["traceEvents"]:
|
| 321 |
+
if (
|
| 322 |
+
"args" not in event
|
| 323 |
+
or "External id" not in event["args"]
|
| 324 |
+
or event["cat"] != "cpu_op"
|
| 325 |
+
):
|
| 326 |
+
continue
|
| 327 |
+
if len(extern_mapping[event["args"]["External id"]]) > 0:
|
| 328 |
+
raise ParseException("duplicate external id in event")
|
| 329 |
+
extern_mapping[event["args"]["External id"]].append(event)
|
| 330 |
+
return extern_mapping
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _augment_trace_helper(data: dict[str, Any]) -> dict[str, Any]:
|
| 334 |
+
extern_mapping = _create_extern_mapping(data)
|
| 335 |
+
|
| 336 |
+
for event in data["traceEvents"]:
|
| 337 |
+
if "cat" not in event or event["cat"] != "kernel":
|
| 338 |
+
continue
|
| 339 |
+
if "args" not in event:
|
| 340 |
+
raise ParseException(f"kernel has no args: {event}")
|
| 341 |
+
if "External id" not in event["args"]:
|
| 342 |
+
event_str = f"kernel has no External id: {event}"
|
| 343 |
+
log.info(event_str)
|
| 344 |
+
continue
|
| 345 |
+
|
| 346 |
+
external_op = extern_mapping[event["args"]["External id"]][0]
|
| 347 |
+
flops = _calculate_flops(external_op)
|
| 348 |
+
if flops == 0:
|
| 349 |
+
flops = _calculate_flops(event)
|
| 350 |
+
external_op["args"]["kernel_flop"] = flops
|
| 351 |
+
external_op["args"]["kernel_num_gb"] = _estimate_gb(external_op)
|
| 352 |
+
event["args"]["kernel_flop"] = external_op["args"]["kernel_flop"]
|
| 353 |
+
event["args"]["kernel_num_gb"] = external_op["args"]["kernel_num_gb"]
|
| 354 |
+
return data
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
_dtype_map = {
|
| 358 |
+
"float": torch.float,
|
| 359 |
+
"float32": torch.float,
|
| 360 |
+
"int": torch.int,
|
| 361 |
+
"int8": torch.int8,
|
| 362 |
+
"int16": torch.int16,
|
| 363 |
+
"int32": torch.int,
|
| 364 |
+
"long": torch.long,
|
| 365 |
+
"long int": torch.long,
|
| 366 |
+
"bfloat16": torch.bfloat16,
|
| 367 |
+
"float16": torch.float16,
|
| 368 |
+
"float64": torch.double,
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@dataclass(frozen=True)
|
| 373 |
+
class KernelStats:
|
| 374 |
+
flops: int
|
| 375 |
+
bw: float
|
| 376 |
+
latency: float # us
|
| 377 |
+
achieved_flops: float
|
| 378 |
+
achieved_bandwidth: float
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
KernelNameMap = defaultdict[str, OrderedSet[KernelStats]]
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@dataclass(frozen=False)
|
| 385 |
+
class Device:
|
| 386 |
+
name: str
|
| 387 |
+
index: int
|
| 388 |
+
info: Optional[DeviceInfo]
|
| 389 |
+
stats: KernelNameMap
|
| 390 |
+
|
| 391 |
+
def __repr__(self) -> str:
|
| 392 |
+
return f"Device({self.name}, {self.index}): {self.info}"
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
DeviceMap = dict[int, Device]
|
| 396 |
+
Table = tuple[list[str], dict[str, list[str]]]
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
class JsonProfile:
|
| 400 |
+
_devices: DeviceMap
|
| 401 |
+
|
| 402 |
+
def __init__(
|
| 403 |
+
self,
|
| 404 |
+
path: str,
|
| 405 |
+
benchmark_name: Optional[str] = None,
|
| 406 |
+
dtype: Optional[Union[torch.dtype, str]] = None,
|
| 407 |
+
):
|
| 408 |
+
"""
|
| 409 |
+
Convenience class for running common operations on chrome/perfetto json traces.
|
| 410 |
+
"""
|
| 411 |
+
self.path = path
|
| 412 |
+
with open(path) as f:
|
| 413 |
+
self.data = json.load(f)
|
| 414 |
+
self.events = self.data["traceEvents"]
|
| 415 |
+
self.benchmark_name = benchmark_name
|
| 416 |
+
if dtype is None:
|
| 417 |
+
self.dtype = None
|
| 418 |
+
elif isinstance(dtype, torch.dtype):
|
| 419 |
+
# pyrefly: ignore [bad-assignment]
|
| 420 |
+
self.dtype = dtype
|
| 421 |
+
else:
|
| 422 |
+
# pyrefly: ignore [bad-assignment]
|
| 423 |
+
self.dtype = _dtype_map.get(dtype)
|
| 424 |
+
self._create_devices()
|
| 425 |
+
|
| 426 |
+
def convert_dtype(self, event: dict[str, Any]) -> Optional[torch.dtype]:
|
| 427 |
+
"""
|
| 428 |
+
Each op has a list of dtypes for each input arg. We need to convert these into a single dtype for flop estimation.
|
| 429 |
+
Issues:
|
| 430 |
+
- converting the strings to concrete torch.dtypes
|
| 431 |
+
- What if we have float32, float, float16 all in the inputs? Our choice is to use the largest buffer dtype.
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
if (
|
| 435 |
+
"Input Dims" not in event["args"]
|
| 436 |
+
or "Input type" not in event["args"]
|
| 437 |
+
or "Concrete Inputs" not in event["args"]
|
| 438 |
+
):
|
| 439 |
+
if "bfloat16" in event["name"]:
|
| 440 |
+
return torch.bfloat16
|
| 441 |
+
elif "float16" in event["name"]:
|
| 442 |
+
return torch.float16
|
| 443 |
+
else:
|
| 444 |
+
return None
|
| 445 |
+
|
| 446 |
+
input_sizes = event["args"]["Input Dims"]
|
| 447 |
+
input_types = event["args"]["Input type"]
|
| 448 |
+
concrete_inputs = event["args"]["Concrete Inputs"]
|
| 449 |
+
assert len(input_sizes) == len(input_types)
|
| 450 |
+
assert len(input_types) == len(concrete_inputs)
|
| 451 |
+
|
| 452 |
+
if len(input_sizes) == 0:
|
| 453 |
+
raise RuntimeError("Empty input_sizes and input_types")
|
| 454 |
+
|
| 455 |
+
biggest_size = 0
|
| 456 |
+
biggest_index = 0
|
| 457 |
+
for i in range(len(input_sizes)):
|
| 458 |
+
if concrete_inputs[i] != "":
|
| 459 |
+
# concrete inputs are usually small tensors, so we can just skip
|
| 460 |
+
continue
|
| 461 |
+
my_size = input_sizes[i]
|
| 462 |
+
total_size = sum(parse_list(my_size))
|
| 463 |
+
if total_size > biggest_size:
|
| 464 |
+
biggest_size = total_size
|
| 465 |
+
biggest_index = i
|
| 466 |
+
ret_type = input_types[biggest_index]
|
| 467 |
+
if ret_type in _dtype_map:
|
| 468 |
+
return _dtype_map[ret_type]
|
| 469 |
+
raise RuntimeError(f"Unknown type: {ret_type}. Please add to _dtype_map.")
|
| 470 |
+
|
| 471 |
+
def _create_devices(self) -> None:
|
| 472 |
+
self._devices = {}
|
| 473 |
+
for dev in self.data["deviceProperties"]:
|
| 474 |
+
name = dev["name"]
|
| 475 |
+
device_info = lookup_device_info(name)
|
| 476 |
+
|
| 477 |
+
if device_info is None:
|
| 478 |
+
log.info(
|
| 479 |
+
"Unsupported device in profile: %s, please consider contributing to _device_mapping.",
|
| 480 |
+
name,
|
| 481 |
+
)
|
| 482 |
+
self._devices[dev["id"]] = Device(
|
| 483 |
+
name, dev["id"], device_info, defaultdict(OrderedSet)
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
def calculate_flops(self, event: dict[str, Any]) -> int:
|
| 487 |
+
return _calculate_flops(event)
|
| 488 |
+
|
| 489 |
+
def estimate_gb(self, event: dict[str, Any]) -> float:
|
| 490 |
+
return _estimate_gb(event)
|
| 491 |
+
|
| 492 |
+
def augment_trace(self) -> None:
|
| 493 |
+
self.data = _augment_trace_helper(self.data)
|
| 494 |
+
|
| 495 |
+
def _compute_stats(self) -> None:
|
| 496 |
+
"""populates the name -> stats map"""
|
| 497 |
+
for event in self.events:
|
| 498 |
+
if "cat" not in event or "args" not in event or event["cat"] != "kernel":
|
| 499 |
+
continue
|
| 500 |
+
if "device" not in event["args"]:
|
| 501 |
+
continue
|
| 502 |
+
dev_tmp = event["args"]["device"]
|
| 503 |
+
if dev_tmp not in self._devices:
|
| 504 |
+
continue
|
| 505 |
+
dev = self._devices[event["args"]["device"]]
|
| 506 |
+
|
| 507 |
+
dur = event["dur"] # us
|
| 508 |
+
if "kernel_flop" in event["args"]:
|
| 509 |
+
assert dur != 0
|
| 510 |
+
# 1,000,000us/s * flop / us
|
| 511 |
+
op_flops = event["args"]["kernel_flop"] / (dur / 1e6)
|
| 512 |
+
else:
|
| 513 |
+
op_flops = 0
|
| 514 |
+
|
| 515 |
+
if "kernel_num_gb" in event["args"]:
|
| 516 |
+
assert dur != 0
|
| 517 |
+
# 1,000,000us/s * gb = gb/s
|
| 518 |
+
op_gbps = event["args"]["kernel_num_gb"] / (dur / 1e6)
|
| 519 |
+
else:
|
| 520 |
+
op_gbps = 0
|
| 521 |
+
|
| 522 |
+
if dev.info is not None:
|
| 523 |
+
dtype = self.convert_dtype(event) or self.dtype
|
| 524 |
+
if dtype is None:
|
| 525 |
+
raise RuntimeError(
|
| 526 |
+
"dtype is not found on tensor and default dtype is not set"
|
| 527 |
+
)
|
| 528 |
+
achieved_flops = 100 * op_flops / (1e12 * dev.info.tops[dtype])
|
| 529 |
+
achieved_bandwidth = 100 * op_gbps / dev.info.dram_bw_gbs
|
| 530 |
+
else:
|
| 531 |
+
achieved_flops = 0
|
| 532 |
+
achieved_bandwidth = 0
|
| 533 |
+
|
| 534 |
+
if "name" not in event["args"]:
|
| 535 |
+
continue
|
| 536 |
+
dev.stats[event["name"]].add(
|
| 537 |
+
KernelStats(
|
| 538 |
+
flops=op_flops,
|
| 539 |
+
bw=op_gbps,
|
| 540 |
+
latency=dur,
|
| 541 |
+
achieved_bandwidth=achieved_bandwidth,
|
| 542 |
+
achieved_flops=achieved_flops,
|
| 543 |
+
)
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
def _create_single_table(self, dev: Device) -> Table:
|
| 547 |
+
"""Create a table with the devices mapped to indices."""
|
| 548 |
+
headers = [
|
| 549 |
+
"Kernel Name",
|
| 550 |
+
"Kernel Count",
|
| 551 |
+
"FLOPS",
|
| 552 |
+
"Kernel Reads (GB)",
|
| 553 |
+
"Dur (us)",
|
| 554 |
+
"Achieved FLOPS %",
|
| 555 |
+
"Achieved Bandwidth %",
|
| 556 |
+
]
|
| 557 |
+
rows: dict[str, list[str]] = {}
|
| 558 |
+
|
| 559 |
+
def safe_div_format(x: float, y: float) -> str:
|
| 560 |
+
if y == 0:
|
| 561 |
+
return "0.0"
|
| 562 |
+
return f"{x / y:.4f}"
|
| 563 |
+
|
| 564 |
+
for kernel_name, stats_set in dev.stats.items():
|
| 565 |
+
ker_count = 0
|
| 566 |
+
flops = 0
|
| 567 |
+
flops_count = 0
|
| 568 |
+
achieved_flops = 0.0
|
| 569 |
+
bw = 0.0
|
| 570 |
+
bw_count = 0
|
| 571 |
+
achieved_bandwidth = 0.0
|
| 572 |
+
latency = 0.0
|
| 573 |
+
for stats in stats_set:
|
| 574 |
+
if stats.flops != 0:
|
| 575 |
+
flops += stats.flops
|
| 576 |
+
achieved_flops += stats.achieved_flops
|
| 577 |
+
flops_count += 1
|
| 578 |
+
if stats.bw != 0:
|
| 579 |
+
bw += stats.bw
|
| 580 |
+
achieved_bandwidth += stats.achieved_bandwidth
|
| 581 |
+
bw_count += 1
|
| 582 |
+
latency += stats.latency
|
| 583 |
+
ker_count += 1
|
| 584 |
+
assert ker_count != 0
|
| 585 |
+
rows[kernel_name] = [
|
| 586 |
+
str(ker_count),
|
| 587 |
+
safe_div_format(flops, flops_count),
|
| 588 |
+
safe_div_format(bw, bw_count),
|
| 589 |
+
safe_div_format(latency, ker_count),
|
| 590 |
+
safe_div_format(achieved_flops, flops_count),
|
| 591 |
+
safe_div_format(achieved_bandwidth, bw_count),
|
| 592 |
+
]
|
| 593 |
+
|
| 594 |
+
return headers, rows
|
| 595 |
+
|
| 596 |
+
def _create_tables(self, devs: DeviceMap) -> dict[int, Table]:
|
| 597 |
+
return {idx: self._create_single_table(dev) for idx, dev in devs.items()}
|
| 598 |
+
|
| 599 |
+
def _combine_tables(
|
| 600 |
+
self, table1: Table, table1_name: str, table2: Table, table2_name: str
|
| 601 |
+
) -> Table:
|
| 602 |
+
new_headers = (
|
| 603 |
+
["Kernel Name"]
|
| 604 |
+
+ [f"{table1_name} {head}" for head in table1[0][1:]]
|
| 605 |
+
+ [f"{table2_name} {head}" for head in table2[0][1:]]
|
| 606 |
+
)
|
| 607 |
+
t1_length = len(table1[0][1:])
|
| 608 |
+
t2_length = len(table2[0][1:])
|
| 609 |
+
new_rows = {}
|
| 610 |
+
|
| 611 |
+
for key, row1, row2 in zip_dicts(
|
| 612 |
+
table1[1],
|
| 613 |
+
table2[1],
|
| 614 |
+
d1_default=["Empty"] * t1_length,
|
| 615 |
+
d2_default=["Empty"] * t2_length,
|
| 616 |
+
):
|
| 617 |
+
assert row1 is not None
|
| 618 |
+
assert row2 is not None
|
| 619 |
+
new_rows[key] = row1 + row2
|
| 620 |
+
return new_headers, new_rows
|
| 621 |
+
|
| 622 |
+
def report(
|
| 623 |
+
self, other: Optional["JsonProfile"] = None, name_limit: int = 40
|
| 624 |
+
) -> str:
|
| 625 |
+
def create_ret(
|
| 626 |
+
table_headers: list[str], table_rows: dict[str, list[str]]
|
| 627 |
+
) -> str:
|
| 628 |
+
table_flattened = [
|
| 629 |
+
[kernel_name[:name_limit], *kernel_vals]
|
| 630 |
+
for kernel_name, kernel_vals in table_rows.items()
|
| 631 |
+
]
|
| 632 |
+
return tabulate_2d(table_flattened, headers=table_headers)
|
| 633 |
+
|
| 634 |
+
if other is not None:
|
| 635 |
+
self._compute_stats()
|
| 636 |
+
other._compute_stats()
|
| 637 |
+
|
| 638 |
+
self_tables = self._create_tables(self._devices)
|
| 639 |
+
other_tables = self._create_tables(other._devices)
|
| 640 |
+
|
| 641 |
+
self_name = (
|
| 642 |
+
self.benchmark_name if self.benchmark_name is not None else "Table 1"
|
| 643 |
+
)
|
| 644 |
+
other_name = (
|
| 645 |
+
other.benchmark_name if other.benchmark_name is not None else "Table 2"
|
| 646 |
+
)
|
| 647 |
+
|
| 648 |
+
ret = []
|
| 649 |
+
assert self._devices.keys() == other._devices.keys()
|
| 650 |
+
for device_idx, t1, t2 in zip_dicts(
|
| 651 |
+
self_tables, other_tables, d1_default=None, d2_default=None
|
| 652 |
+
):
|
| 653 |
+
assert t1 is not None
|
| 654 |
+
assert t2 is not None
|
| 655 |
+
table_headers, table_rows = self._combine_tables(
|
| 656 |
+
t1, self_name, t2, other_name
|
| 657 |
+
)
|
| 658 |
+
tab_string = create_ret(table_headers, table_rows)
|
| 659 |
+
# pyrefly: ignore [bad-argument-type]
|
| 660 |
+
ret.append(f"{self._devices[device_idx]}:\n{tab_string}")
|
| 661 |
+
return "\n".join(ret)
|
| 662 |
+
self._compute_stats()
|
| 663 |
+
|
| 664 |
+
self_tables = self._create_tables(self._devices)
|
| 665 |
+
|
| 666 |
+
ret = []
|
| 667 |
+
for idx, table in self_tables.items():
|
| 668 |
+
table_headers, table_rows = table
|
| 669 |
+
tab_string = create_ret(table_headers, table_rows)
|
| 670 |
+
# pyrefly: ignore [bad-argument-type]
|
| 671 |
+
ret.append(f"{self._devices[idx]}:\n{tab_string}")
|
| 672 |
+
return "\n".join(ret)
|
| 673 |
+
|
| 674 |
+
def dump(self, out: str) -> None:
|
| 675 |
+
with open(out, "w") as f:
|
| 676 |
+
json.dump(self.data, f)
|
| 677 |
+
|
| 678 |
+
def combine_with(self, other: "JsonProfile") -> "JsonProfile":
|
| 679 |
+
"""
|
| 680 |
+
Combine this profile with another profile by merging their trace events.
|
| 681 |
+
Returns a new JsonProfile object with combined data.
|
| 682 |
+
"""
|
| 683 |
+
# Create a new combined data structure
|
| 684 |
+
combined_data = {
|
| 685 |
+
"traceEvents": self.data["traceEvents"] + other.data["traceEvents"],
|
| 686 |
+
"deviceProperties": self.data.get("deviceProperties", []),
|
| 687 |
+
}
|
| 688 |
+
|
| 689 |
+
# Merge device properties, avoiding duplicates
|
| 690 |
+
other_device_props = other.data.get("deviceProperties", [])
|
| 691 |
+
existing_device_ids = OrderedSet(
|
| 692 |
+
[dev["id"] for dev in combined_data["deviceProperties"]]
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
for device_prop in other_device_props:
|
| 696 |
+
if device_prop["id"] not in existing_device_ids:
|
| 697 |
+
combined_data["deviceProperties"].append(device_prop)
|
| 698 |
+
|
| 699 |
+
# Copy any other top-level properties from the first profile
|
| 700 |
+
for key, value in self.data.items():
|
| 701 |
+
if key not in combined_data:
|
| 702 |
+
combined_data[key] = value
|
| 703 |
+
|
| 704 |
+
import os
|
| 705 |
+
|
| 706 |
+
# Create a temporary file to write the combined data
|
| 707 |
+
import tempfile
|
| 708 |
+
|
| 709 |
+
with tempfile.NamedTemporaryFile(
|
| 710 |
+
mode="w", suffix=".json", delete=False
|
| 711 |
+
) as tmp_file:
|
| 712 |
+
json.dump(combined_data, tmp_file)
|
| 713 |
+
tmp_path = tmp_file.name
|
| 714 |
+
|
| 715 |
+
try:
|
| 716 |
+
# Create new JsonProfile from the combined data
|
| 717 |
+
combined_profile = JsonProfile(
|
| 718 |
+
tmp_path,
|
| 719 |
+
benchmark_name=f"{self.benchmark_name or 'Profile1'}_+_{other.benchmark_name or 'Profile2'}",
|
| 720 |
+
dtype=self.dtype or other.dtype,
|
| 721 |
+
)
|
| 722 |
+
return combined_profile
|
| 723 |
+
finally:
|
| 724 |
+
# Clean up temporary file
|
| 725 |
+
os.unlink(tmp_path)
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
class ParseException(RuntimeError):
|
| 729 |
+
pass
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def main() -> None:
|
| 733 |
+
"""
|
| 734 |
+
Main function for the profile analysis script.
|
| 735 |
+
"""
|
| 736 |
+
import argparse
|
| 737 |
+
|
| 738 |
+
parser = argparse.ArgumentParser()
|
| 739 |
+
parser.add_argument(
|
| 740 |
+
"--diff",
|
| 741 |
+
nargs=5,
|
| 742 |
+
metavar=(
|
| 743 |
+
"input_file1",
|
| 744 |
+
"name1",
|
| 745 |
+
"input_file2",
|
| 746 |
+
"name2",
|
| 747 |
+
"dtype",
|
| 748 |
+
),
|
| 749 |
+
help="Two json traces to compare with, specified as <file1> <name1> <file2> <name2> <dtype>",
|
| 750 |
+
)
|
| 751 |
+
parser.add_argument(
|
| 752 |
+
"--name_limit",
|
| 753 |
+
type=int,
|
| 754 |
+
help="the maximum name size in the final report",
|
| 755 |
+
)
|
| 756 |
+
parser.add_argument(
|
| 757 |
+
"--augment_trace",
|
| 758 |
+
"-a",
|
| 759 |
+
nargs=3,
|
| 760 |
+
metavar=("input_file", "output_file", "dtype"),
|
| 761 |
+
help="Augment a trace with inductor meta information. Provide input and output file paths.",
|
| 762 |
+
)
|
| 763 |
+
parser.add_argument(
|
| 764 |
+
"--analysis",
|
| 765 |
+
nargs=2,
|
| 766 |
+
metavar=("input_file", "dtype"),
|
| 767 |
+
help="Run analysis on a single trace, specified as <file> <dtype>",
|
| 768 |
+
)
|
| 769 |
+
parser.add_argument(
|
| 770 |
+
"--combine",
|
| 771 |
+
nargs="+",
|
| 772 |
+
metavar=("input_files", "output_file"),
|
| 773 |
+
help="Combine multiple profiles into a single profile by merging trace events. Specify as <input_file1> \
|
| 774 |
+
<input_file2> [input_file3 ...] <output_file>. The last argument is the output file, all preceding arguments are \
|
| 775 |
+
input files to combine.",
|
| 776 |
+
)
|
| 777 |
+
args = parser.parse_args()
|
| 778 |
+
|
| 779 |
+
if args.diff:
|
| 780 |
+
p1 = JsonProfile(args.diff[0], args.diff[1], dtype=args.diff[4])
|
| 781 |
+
p1.augment_trace()
|
| 782 |
+
p2 = JsonProfile(args.diff[2], args.diff[3], dtype=args.diff[4])
|
| 783 |
+
p2.augment_trace()
|
| 784 |
+
if args.name_limit:
|
| 785 |
+
print(p1.report(p2, name_limit=args.name_limit))
|
| 786 |
+
else:
|
| 787 |
+
print(p1.report(p2))
|
| 788 |
+
if args.analysis:
|
| 789 |
+
p1 = JsonProfile(
|
| 790 |
+
args.analysis[0],
|
| 791 |
+
dtype=args.analysis[1],
|
| 792 |
+
)
|
| 793 |
+
p1.augment_trace()
|
| 794 |
+
if args.name_limit:
|
| 795 |
+
print(p1.report(name_limit=args.name_limit))
|
| 796 |
+
else:
|
| 797 |
+
print(p1.report())
|
| 798 |
+
if args.augment_trace:
|
| 799 |
+
p = JsonProfile(args.augment_trace[0], dtype=args.augment_trace[2])
|
| 800 |
+
p.augment_trace()
|
| 801 |
+
p.dump(args.augment_trace[1])
|
| 802 |
+
if args.combine:
|
| 803 |
+
input_files = args.combine[:-1] # All arguments except the last one
|
| 804 |
+
output_file = args.combine[-1] # Last argument is the output file
|
| 805 |
+
|
| 806 |
+
if len(input_files) < 2:
|
| 807 |
+
print("Error: At least 2 input files are required for combining")
|
| 808 |
+
return
|
| 809 |
+
|
| 810 |
+
# Load the first profile
|
| 811 |
+
combined = JsonProfile(input_files[0], dtype=None)
|
| 812 |
+
|
| 813 |
+
# Iteratively combine with all other profiles
|
| 814 |
+
for input_file in input_files[1:]:
|
| 815 |
+
profile = JsonProfile(input_file, dtype=None)
|
| 816 |
+
combined = combined.combine_with(profile)
|
| 817 |
+
|
| 818 |
+
combined.dump(output_file)
|
| 819 |
+
print(f"Successfully combined {', '.join(input_files)} into {output_file}")
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
if __name__ == "__main__":
|
| 823 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: B950
|
| 2 |
+
# fmt: off
|
| 3 |
+
# This file was generated by AutoHeuristic. Do not modify it manually!
|
| 4 |
+
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mm/
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import (
|
| 8 |
+
AHContext,
|
| 9 |
+
AHMetadata,
|
| 10 |
+
Choice,
|
| 11 |
+
)
|
| 12 |
+
from torch._inductor.autoheuristic.learnedheuristic_interface import (
|
| 13 |
+
LearnedHeuristicDecision,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MMRankingA100(LearnedHeuristicDecision):
|
| 18 |
+
|
| 19 |
+
def __init__(self) -> None:
|
| 20 |
+
self.choices: list[Choice] = []
|
| 21 |
+
self.fill_choices()
|
| 22 |
+
|
| 23 |
+
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
|
| 24 |
+
return (
|
| 25 |
+
metadata.name == self.get_name()
|
| 26 |
+
and metadata.shared_memory == 166912
|
| 27 |
+
and str(metadata.device_capa) == "(8, 0)"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def get_confidence_threshold(self) -> float:
|
| 31 |
+
return 0.0
|
| 32 |
+
|
| 33 |
+
def get_choice(self, idx: int) -> Optional[str]:
|
| 34 |
+
if idx < len(self.choices):
|
| 35 |
+
return self.choices[idx]
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
def fill_choices(self) -> None:
|
| 39 |
+
self.choices.append('extern_mm')
|
| 40 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=8')
|
| 41 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=8')
|
| 42 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8')
|
| 43 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8')
|
| 44 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4')
|
| 45 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8')
|
| 46 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4')
|
| 47 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4')
|
| 48 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8')
|
| 49 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2')
|
| 50 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=8')
|
| 51 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4')
|
| 52 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=8')
|
| 53 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4')
|
| 54 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=8')
|
| 55 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4')
|
| 56 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=8')
|
| 57 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2')
|
| 58 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=8')
|
| 59 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4')
|
| 60 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=8')
|
| 61 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4')
|
| 62 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8')
|
| 63 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4')
|
| 64 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8')
|
| 65 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2')
|
| 66 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=8')
|
| 67 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4')
|
| 68 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8')
|
| 69 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4')
|
| 70 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8')
|
| 71 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4')
|
| 72 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8')
|
| 73 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8')
|
| 74 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 75 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=8')
|
| 76 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4')
|
| 77 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=4')
|
| 78 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=8')
|
| 79 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=8')
|
| 80 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4')
|
| 81 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=8')
|
| 82 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4')
|
| 83 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=8')
|
| 84 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4')
|
| 85 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=8')
|
| 86 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=2')
|
| 87 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=8')
|
| 88 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4')
|
| 89 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8')
|
| 90 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4')
|
| 91 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8')
|
| 92 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4')
|
| 93 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8')
|
| 94 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=2')
|
| 95 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=8')
|
| 96 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4')
|
| 97 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8')
|
| 98 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4')
|
| 99 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8')
|
| 100 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4')
|
| 101 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8')
|
| 102 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 103 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8')
|
| 104 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4')
|
| 105 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 106 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4')
|
| 107 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=8')
|
| 108 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=8')
|
| 109 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4')
|
| 110 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=8')
|
| 111 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4')
|
| 112 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8')
|
| 113 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=8')
|
| 114 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4')
|
| 115 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=8')
|
| 116 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 117 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8')
|
| 118 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=8')
|
| 119 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4')
|
| 120 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=8')
|
| 121 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 122 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2')
|
| 123 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4')
|
| 124 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4')
|
| 125 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 126 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4')
|
| 127 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8')
|
| 128 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4')
|
| 129 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8')
|
| 130 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8')
|
| 131 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=1')
|
| 132 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2')
|
| 133 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2')
|
| 134 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=2')
|
| 135 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=2')
|
| 136 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=2')
|
| 137 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4')
|
| 138 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4')
|
| 139 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4')
|
| 140 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 141 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4')
|
| 142 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=1')
|
| 143 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=2')
|
| 144 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4')
|
| 145 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4')
|
| 146 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4')
|
| 147 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4')
|
| 148 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 149 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=2')
|
| 150 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 151 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4')
|
| 152 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4')
|
| 153 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 154 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=16_numstages=2_numwarps=2')
|
| 155 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4')
|
| 156 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 157 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4')
|
| 158 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8')
|
| 159 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 160 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=1_numwarps=2')
|
| 161 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2')
|
| 162 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=2')
|
| 163 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2')
|
| 164 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4')
|
| 165 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4')
|
| 166 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8')
|
| 167 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2')
|
| 168 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=2')
|
| 169 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8')
|
| 170 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 171 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4')
|
| 172 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=4')
|
| 173 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 174 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=3_numwarps=4')
|
| 175 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=4')
|
| 176 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=5_numwarps=4')
|
| 177 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=3_numwarps=4')
|
| 178 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=4')
|
| 179 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 180 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4')
|
| 181 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4')
|
| 182 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8')
|
| 183 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 184 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4')
|
| 185 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4')
|
| 186 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8')
|
| 187 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=4')
|
| 188 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4')
|
| 189 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4')
|
| 190 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4')
|
| 191 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4')
|
| 192 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4')
|
| 193 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=8')
|
| 194 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4')
|
| 195 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8')
|
| 196 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4')
|
| 197 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8')
|
| 198 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4')
|
| 199 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4')
|
| 200 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8')
|
| 201 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4')
|
| 202 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8')
|
| 203 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4')
|
| 204 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 205 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4')
|
| 206 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8')
|
| 207 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=4')
|
| 208 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4')
|
| 209 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4')
|
| 210 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4')
|
| 211 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4')
|
| 212 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4')
|
| 213 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8')
|
| 214 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4')
|
| 215 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8')
|
| 216 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4')
|
| 217 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8')
|
| 218 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4')
|
| 219 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4')
|
| 220 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8')
|
| 221 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4')
|
| 222 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8')
|
| 223 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4')
|
| 224 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 225 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=4_numwarps=4')
|
| 226 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4')
|
| 227 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=4')
|
| 228 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4')
|
| 229 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4')
|
| 230 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8')
|
| 231 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=4')
|
| 232 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4')
|
| 233 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 234 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8')
|
| 235 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4')
|
| 236 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4')
|
| 237 |
+
|
| 238 |
+
def get_name(self) -> str:
|
| 239 |
+
return 'mm'
|
| 240 |
+
|
| 241 |
+
def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:
|
| 242 |
+
if context.get_value('arith_intensity') <= 52.6245059967041:
|
| 243 |
+
if context.get_value('n') <= 34.0:
|
| 244 |
+
if context.get_value('n') <= 18.0:
|
| 245 |
+
if context.get_value('k*n') <= 312.0:
|
| 246 |
+
return [(0.093, 12), (0.081, 16), (0.081, 148), (0.070, 10), (0.070, 17), (0.070, 149), (0.070, 151), (0.070, 150), (0.070, 14), (0.058, 11), (0.058, 15), (0.058, 13), (0.058, 122), (0.047, 121), (0.035, 123), (0.012, 92)]
|
| 247 |
+
else:
|
| 248 |
+
if context.get_value('k') <= 40.0:
|
| 249 |
+
return [(0.083, 42), (0.083, 46), (0.083, 44), (0.083, 40), (0.083, 128), (0.067, 45), (0.067, 43), (0.067, 41), (0.067, 169), (0.067, 171), (0.067, 168), (0.067, 129), (0.067, 170), (0.033, 103), (0.017, 121)]
|
| 250 |
+
else:
|
| 251 |
+
return [(0.112, 137), (0.104, 136), (0.101, 0), (0.081, 1), (0.073, 135), (0.069, 67), (0.066, 187), (0.058, 41), (0.050, 71), (0.046, 68), (0.046, 70), (0.031, 44), (0.027, 43), (0.027, 170), (0.019, 189), (0.019, 188), (0.015, 169), (0.015, 171), (0.012, 115), (0.012, 168), (0.012, 69), (0.004, 103)]
|
| 252 |
+
else:
|
| 253 |
+
if context.get_value('mat1_stride_0') <= 20.0:
|
| 254 |
+
return [(0.069, 0), (0.059, 157), (0.059, 22), (0.059, 153), (0.059, 155), (0.059, 25), (0.059, 23), (0.059, 19), (0.044, 21), (0.044, 18), (0.044, 152), (0.044, 158), (0.044, 154), (0.044, 156), (0.044, 20), (0.044, 124), (0.044, 24), (0.030, 125), (0.029, 126), (0.015, 97), (0.015, 95), (0.015, 96), (0.010, 2), (0.010, 75)]
|
| 255 |
+
else:
|
| 256 |
+
if context.get_value('k') <= 68.0:
|
| 257 |
+
return [(0.087, 72), (0.087, 74), (0.087, 73), (0.086, 76), (0.077, 75), (0.067, 192), (0.058, 190), (0.048, 47), (0.048, 193), (0.048, 49), (0.048, 51), (0.048, 191), (0.038, 53), (0.019, 133), (0.019, 50), (0.019, 175), (0.019, 172), (0.019, 48), (0.019, 174), (0.010, 173), (0.010, 177), (0.010, 52), (0.010, 54), (0.010, 178), (0.010, 176)]
|
| 258 |
+
else:
|
| 259 |
+
return [(0.154, 52), (0.154, 72), (0.102, 75), (0.087, 49), (0.087, 73), (0.086, 51), (0.057, 176), (0.045, 2), (0.038, 191), (0.038, 178), (0.038, 190), (0.029, 173), (0.029, 76), (0.026, 138), (0.013, 139), (0.013, 140), (0.003, 0)]
|
| 260 |
+
else:
|
| 261 |
+
if context.get_value('k') <= 35.0:
|
| 262 |
+
if context.get_value('k') <= 18.0:
|
| 263 |
+
if context.get_value('m*n') <= 19505152.0:
|
| 264 |
+
return [(0.151, 159), (0.140, 160), (0.129, 164), (0.055, 127), (0.051, 29), (0.044, 161), (0.044, 147), (0.040, 146), (0.040, 31), (0.037, 145), (0.026, 28), (0.022, 90), (0.022, 93), (0.022, 94), (0.022, 100), (0.022, 125), (0.022, 158), (0.022, 157), (0.011, 87), (0.011, 88), (0.011, 89), (0.011, 91), (0.011, 95), (0.011, 96), (0.011, 98), (0.011, 99)]
|
| 265 |
+
else:
|
| 266 |
+
return [(0.069, 7), (0.069, 5), (0.067, 147), (0.066, 8), (0.061, 145), (0.058, 146), (0.052, 124), (0.049, 29), (0.049, 159), (0.046, 31), (0.043, 157), (0.041, 9), (0.041, 4), (0.040, 6), (0.035, 164), (0.035, 160), (0.026, 158), (0.017, 125), (0.017, 28), (0.017, 32), (0.017, 162), (0.017, 27), (0.017, 30), (0.017, 161), (0.009, 33), (0.009, 26), (0.009, 163), (0.006, 0)]
|
| 267 |
+
else:
|
| 268 |
+
if context.get_value('n') <= 68.0:
|
| 269 |
+
return [(0.101, 182), (0.101, 59), (0.088, 57), (0.076, 184), (0.076, 61), (0.076, 179), (0.076, 62), (0.076, 58), (0.063, 180), (0.063, 60), (0.051, 56), (0.050, 181), (0.025, 130), (0.025, 177), (0.025, 183), (0.013, 178), (0.013, 55)]
|
| 270 |
+
else:
|
| 271 |
+
return [(0.089, 180), (0.079, 60), (0.066, 35), (0.066, 181), (0.066, 38), (0.066, 58), (0.066, 179), (0.066, 57), (0.062, 184), (0.053, 37), (0.044, 166), (0.040, 55), (0.040, 39), (0.040, 36), (0.040, 165), (0.040, 167), (0.027, 177), (0.027, 34), (0.022, 159)]
|
| 272 |
+
else:
|
| 273 |
+
if context.get_value('m*n') <= 309760.0:
|
| 274 |
+
return [(0.298, 0), (0.097, 140), (0.080, 83), (0.072, 86), (0.044, 84), (0.036, 178), (0.036, 117), (0.036, 82), (0.032, 120), (0.032, 85), (0.028, 119), (0.024, 130), (0.024, 109), (0.020, 108), (0.020, 118), (0.012, 104), (0.012, 116), (0.012, 141), (0.012, 144), (0.008, 105), (0.008, 106), (0.008, 111), (0.008, 114), (0.008, 107), (0.008, 132), (0.004, 101), (0.004, 102), (0.004, 110), (0.004, 112), (0.004, 113), (0.004, 131)]
|
| 275 |
+
else:
|
| 276 |
+
if context.get_value('n') <= 72.0:
|
| 277 |
+
return [(0.227, 77), (0.118, 78), (0.102, 194), (0.086, 80), (0.059, 57), (0.054, 81), (0.049, 196), (0.048, 197), (0.048, 59), (0.043, 79), (0.032, 195), (0.027, 180), (0.022, 3), (0.021, 141), (0.016, 60), (0.016, 142), (0.011, 183), (0.011, 0), (0.011, 144)]
|
| 278 |
+
else:
|
| 279 |
+
return [(0.140, 186), (0.132, 185), (0.109, 63), (0.085, 65), (0.078, 37), (0.077, 35), (0.062, 197), (0.047, 194), (0.046, 165), (0.046, 57), (0.039, 78), (0.039, 79), (0.039, 66), (0.039, 64), (0.016, 195), (0.008, 159)]
|
| 280 |
+
else:
|
| 281 |
+
if str(context.get_value('using_tf32')) != 'False':
|
| 282 |
+
if context.get_value('m*n') <= 815360.0:
|
| 283 |
+
if context.get_value('k') <= 1184.0:
|
| 284 |
+
return [(0.218, 140), (0.205, 0), (0.154, 144), (0.115, 141), (0.051, 185), (0.051, 104), (0.039, 78), (0.038, 116), (0.026, 165), (0.026, 130), (0.026, 178), (0.013, 57), (0.013, 195), (0.013, 167), (0.013, 186)]
|
| 285 |
+
else:
|
| 286 |
+
return [(0.901, 0), (0.030, 144), (0.030, 134), (0.016, 3), (0.006, 78), (0.006, 77), (0.002, 57), (0.002, 194), (0.002, 59), (0.002, 60), (0.002, 143)]
|
| 287 |
+
else:
|
| 288 |
+
if context.get_value('arith_intensity') <= 187.23922729492188:
|
| 289 |
+
if context.get_value('mat1_stride_0') <= 198.0:
|
| 290 |
+
return [(0.273, 63), (0.158, 37), (0.152, 35), (0.127, 57), (0.097, 165), (0.053, 185), (0.031, 0), (0.028, 64), (0.014, 60), (0.014, 78), (0.009, 55), (0.008, 134), (0.005, 34), (0.005, 167), (0.005, 179), (0.005, 65), (0.005, 66), (0.005, 186), (0.005, 194), (0.002, 166)]
|
| 291 |
+
else:
|
| 292 |
+
return [(0.296, 63), (0.235, 0), (0.132, 64), (0.074, 37), (0.069, 78), (0.051, 185), (0.051, 35), (0.030, 57), (0.020, 77), (0.016, 194), (0.008, 66), (0.007, 65), (0.003, 3), (0.003, 165), (0.003, 141), (0.001, 134), (0.001, 166)]
|
| 293 |
+
else:
|
| 294 |
+
return [(0.405, 0), (0.246, 37), (0.177, 63), (0.145, 35), (0.005, 185), (0.005, 65), (0.005, 64), (0.004, 57), (0.003, 66), (0.002, 165), (0.001, 78), (0.001, 55)]
|
| 295 |
+
else:
|
| 296 |
+
return [(0.357, 0), (0.112, 165), (0.101, 57), (0.094, 179), (0.086, 64), (0.074, 167), (0.067, 60), (0.064, 159), (0.033, 35), (0.007, 195), (0.002, 180), (0.001, 34), (0.001, 166), (0.001, 78)]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingH100.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: B950
|
| 2 |
+
# fmt: off
|
| 3 |
+
# This file was generated by AutoHeuristic. Do not modify it manually!
|
| 4 |
+
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mm/
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import (
|
| 8 |
+
AHContext,
|
| 9 |
+
AHMetadata,
|
| 10 |
+
Choice,
|
| 11 |
+
)
|
| 12 |
+
from torch._inductor.autoheuristic.learnedheuristic_interface import (
|
| 13 |
+
LearnedHeuristicDecision,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MMRankingH100(LearnedHeuristicDecision):
|
| 18 |
+
|
| 19 |
+
def __init__(self) -> None:
|
| 20 |
+
self.choices: list[Choice] = []
|
| 21 |
+
self.fill_choices()
|
| 22 |
+
|
| 23 |
+
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
|
| 24 |
+
return (
|
| 25 |
+
metadata.name == self.get_name()
|
| 26 |
+
and metadata.shared_memory == 232448
|
| 27 |
+
and str(metadata.device_capa) == "(9, 0)"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def get_confidence_threshold(self) -> float:
|
| 31 |
+
return 0.0
|
| 32 |
+
|
| 33 |
+
def get_choice(self, idx: int) -> Optional[str]:
|
| 34 |
+
if idx < len(self.choices):
|
| 35 |
+
return self.choices[idx]
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
def fill_choices(self) -> None:
|
| 39 |
+
self.choices.append('extern_mm')
|
| 40 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=8')
|
| 41 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=8')
|
| 42 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=8')
|
| 43 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8')
|
| 44 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4')
|
| 45 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8')
|
| 46 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4')
|
| 47 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4')
|
| 48 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8')
|
| 49 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2')
|
| 50 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=8')
|
| 51 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4')
|
| 52 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=8')
|
| 53 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4')
|
| 54 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=8')
|
| 55 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4')
|
| 56 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=8')
|
| 57 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2')
|
| 58 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=8')
|
| 59 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4')
|
| 60 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4')
|
| 61 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=8')
|
| 62 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4')
|
| 63 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2')
|
| 64 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=8')
|
| 65 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4')
|
| 66 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8')
|
| 67 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4')
|
| 68 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8')
|
| 69 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4')
|
| 70 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8')
|
| 71 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8')
|
| 72 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 73 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=8')
|
| 74 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4')
|
| 75 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=4')
|
| 76 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=5_numwarps=8')
|
| 77 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2')
|
| 78 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=8')
|
| 79 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4')
|
| 80 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=8')
|
| 81 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4')
|
| 82 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=8')
|
| 83 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4')
|
| 84 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=8')
|
| 85 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=2')
|
| 86 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=8')
|
| 87 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4')
|
| 88 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8')
|
| 89 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4')
|
| 90 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8')
|
| 91 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4')
|
| 92 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8')
|
| 93 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=2')
|
| 94 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=8')
|
| 95 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4')
|
| 96 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8')
|
| 97 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4')
|
| 98 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8')
|
| 99 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4')
|
| 100 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8')
|
| 101 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 102 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8')
|
| 103 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4')
|
| 104 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 105 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4')
|
| 106 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=8')
|
| 107 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=8')
|
| 108 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4')
|
| 109 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=8')
|
| 110 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4')
|
| 111 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8')
|
| 112 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=8')
|
| 113 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4')
|
| 114 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=8')
|
| 115 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 116 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8')
|
| 117 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=8')
|
| 118 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4')
|
| 119 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=8')
|
| 120 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 121 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2')
|
| 122 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2')
|
| 123 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4')
|
| 124 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4')
|
| 125 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 126 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=2_numwarps=8')
|
| 127 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4')
|
| 128 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=8')
|
| 129 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4')
|
| 130 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8')
|
| 131 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=4')
|
| 132 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=128_numstages=5_numwarps=8')
|
| 133 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=1')
|
| 134 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=1')
|
| 135 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=1')
|
| 136 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2')
|
| 137 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=2')
|
| 138 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=2')
|
| 139 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=2')
|
| 140 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=2')
|
| 141 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=2')
|
| 142 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4')
|
| 143 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4')
|
| 144 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4')
|
| 145 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4')
|
| 146 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=2_numwarps=8')
|
| 147 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 148 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4')
|
| 149 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8')
|
| 150 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=1')
|
| 151 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=1')
|
| 152 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=2')
|
| 153 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=2')
|
| 154 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4')
|
| 155 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4')
|
| 156 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4')
|
| 157 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 158 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=8')
|
| 159 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=4')
|
| 160 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 161 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 162 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=16_numstages=2_numwarps=2')
|
| 163 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4')
|
| 164 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 165 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 166 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=1_numwarps=2')
|
| 167 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=2')
|
| 168 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=2')
|
| 169 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=1_numwarps=2')
|
| 170 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4')
|
| 171 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4')
|
| 172 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=8')
|
| 173 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=2')
|
| 174 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=2')
|
| 175 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4')
|
| 176 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4')
|
| 177 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8')
|
| 178 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=16_numstages=2_numwarps=2')
|
| 179 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=64_BLOCK-N=32_numstages=2_numwarps=4')
|
| 180 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 181 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=3_numwarps=4')
|
| 182 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=4_numwarps=4')
|
| 183 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=16_numstages=5_numwarps=4')
|
| 184 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=3_numwarps=4')
|
| 185 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=4_numwarps=4')
|
| 186 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 187 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=3_numwarps=4')
|
| 188 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=4_numwarps=4')
|
| 189 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 190 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=3_numwarps=4')
|
| 191 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=4')
|
| 192 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=128_numstages=4_numwarps=8')
|
| 193 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=2_numwarps=4')
|
| 194 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=3_numwarps=4')
|
| 195 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=4_numwarps=4')
|
| 196 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=16_numstages=5_numwarps=4')
|
| 197 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=2_numwarps=4')
|
| 198 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=3_numwarps=4')
|
| 199 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=4_numwarps=4')
|
| 200 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=4')
|
| 201 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=32_numstages=5_numwarps=8')
|
| 202 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=2_numwarps=4')
|
| 203 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=4')
|
| 204 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=3_numwarps=8')
|
| 205 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=4')
|
| 206 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=4_numwarps=8')
|
| 207 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=16_BLOCK-N=64_numstages=5_numwarps=4')
|
| 208 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 209 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=4')
|
| 210 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8')
|
| 211 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=2_numwarps=4')
|
| 212 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=3_numwarps=4')
|
| 213 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=4_numwarps=4')
|
| 214 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=16_numstages=5_numwarps=4')
|
| 215 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=2_numwarps=4')
|
| 216 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=4')
|
| 217 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=3_numwarps=8')
|
| 218 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=4')
|
| 219 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=4_numwarps=8')
|
| 220 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=4')
|
| 221 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=32_numstages=5_numwarps=8')
|
| 222 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=2_numwarps=4')
|
| 223 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4')
|
| 224 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=8')
|
| 225 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=4')
|
| 226 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=4_numwarps=8')
|
| 227 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=4')
|
| 228 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 229 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=4_numwarps=4')
|
| 230 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=3_numwarps=4')
|
| 231 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=4_numwarps=4')
|
| 232 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=16_numstages=5_numwarps=4')
|
| 233 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=4')
|
| 234 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=3_numwarps=8')
|
| 235 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=4_numwarps=4')
|
| 236 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=32_numstages=5_numwarps=4')
|
| 237 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 238 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8')
|
| 239 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=4_numwarps=4')
|
| 240 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=5_numwarps=4')
|
| 241 |
+
|
| 242 |
+
def get_name(self) -> str:
|
| 243 |
+
return 'mm'
|
| 244 |
+
|
| 245 |
+
def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:
|
| 246 |
+
if context.get_value('arith_intensity') <= 29.89772129058838:
|
| 247 |
+
if context.get_value('n') <= 34.0:
|
| 248 |
+
if context.get_value('n') <= 18.0:
|
| 249 |
+
if context.get_value('k*n') <= 432.0:
|
| 250 |
+
if context.get_value('arith_intensity') <= 7.8700292110443115:
|
| 251 |
+
return [(0.098, 128), (0.098, 129), (0.098, 127), (0.073, 14), (0.073, 16), (0.073, 12), (0.073, 154), (0.073, 156), (0.073, 157), (0.073, 155), (0.049, 10), (0.049, 94), (0.049, 95), (0.048, 96)]
|
| 252 |
+
else:
|
| 253 |
+
return [(0.091, 154), (0.073, 10), (0.073, 15), (0.073, 13), (0.073, 11), (0.073, 17), (0.073, 16), (0.073, 14), (0.073, 12), (0.055, 127), (0.054, 157), (0.054, 156), (0.054, 155), (0.036, 129), (0.036, 128), (0.018, 41), (0.018, 43)]
|
| 254 |
+
else:
|
| 255 |
+
if context.get_value('k') <= 40.0:
|
| 256 |
+
return [(0.070, 39), (0.069, 45), (0.069, 41), (0.069, 43), (0.069, 111), (0.069, 112), (0.056, 38), (0.056, 40), (0.056, 42), (0.056, 44), (0.056, 174), (0.056, 173), (0.056, 175), (0.056, 134), (0.056, 172), (0.056, 135), (0.014, 154), (0.014, 127)]
|
| 257 |
+
else:
|
| 258 |
+
return [(0.147, 144), (0.119, 143), (0.087, 142), (0.083, 0), (0.073, 191), (0.059, 69), (0.050, 67), (0.046, 70), (0.041, 1), (0.036, 174), (0.032, 43), (0.032, 123), (0.028, 40), (0.027, 42), (0.027, 173), (0.023, 175), (0.018, 66), (0.014, 192), (0.014, 193), (0.014, 139), (0.014, 68), (0.014, 127)]
|
| 259 |
+
else:
|
| 260 |
+
if context.get_value('mat1_stride_0') <= 40.0:
|
| 261 |
+
if context.get_value('mat1_stride_0') <= 20.0:
|
| 262 |
+
return [(0.109, 23), (0.109, 21), (0.109, 20), (0.088, 0), (0.087, 131), (0.066, 18), (0.065, 130), (0.065, 132), (0.065, 159), (0.065, 160), (0.065, 161), (0.065, 158), (0.022, 22), (0.022, 19)]
|
| 263 |
+
else:
|
| 264 |
+
return [(0.065, 46), (0.064, 52), (0.064, 50), (0.064, 48), (0.064, 51), (0.064, 49), (0.064, 47), (0.064, 53), (0.064, 181), (0.064, 177), (0.064, 179), (0.064, 176), (0.038, 130), (0.038, 136), (0.026, 182), (0.026, 178), (0.026, 180), (0.026, 137), (0.025, 158), (0.013, 114), (0.013, 113)]
|
| 265 |
+
else:
|
| 266 |
+
if context.get_value('mat1_stride_0') <= 68.0:
|
| 267 |
+
return [(0.138, 140), (0.125, 195), (0.100, 71), (0.100, 74), (0.100, 196), (0.100, 194), (0.100, 197), (0.075, 75), (0.062, 72), (0.062, 73), (0.012, 180), (0.012, 51), (0.012, 182)]
|
| 268 |
+
else:
|
| 269 |
+
return [(0.124, 180), (0.124, 182), (0.114, 75), (0.103, 74), (0.093, 51), (0.093, 71), (0.072, 72), (0.062, 194), (0.052, 145), (0.052, 195), (0.021, 48), (0.021, 50), (0.021, 47), (0.020, 124), (0.010, 147), (0.010, 146), (0.010, 46)]
|
| 270 |
+
else:
|
| 271 |
+
if context.get_value('k') <= 18.0:
|
| 272 |
+
if context.get_value('m*k') <= 528.0:
|
| 273 |
+
return [(0.097, 88), (0.087, 92), (0.077, 90), (0.058, 105), (0.058, 103), (0.058, 104), (0.058, 99), (0.058, 100), (0.058, 106), (0.058, 93), (0.057, 91), (0.057, 97), (0.057, 98), (0.057, 101), (0.048, 102), (0.029, 87), (0.029, 89)]
|
| 274 |
+
else:
|
| 275 |
+
if context.get_value('n') <= 80.0:
|
| 276 |
+
return [(0.057, 161), (0.057, 130), (0.057, 24), (0.056, 164), (0.056, 163), (0.056, 166), (0.056, 168), (0.056, 30), (0.056, 28), (0.056, 26), (0.056, 25), (0.056, 27), (0.056, 29), (0.056, 31), (0.042, 131), (0.028, 99), (0.028, 101), (0.028, 100), (0.028, 167), (0.028, 165), (0.028, 133)]
|
| 277 |
+
else:
|
| 278 |
+
return [(0.110, 164), (0.108, 163), (0.106, 168), (0.069, 161), (0.066, 151), (0.060, 152), (0.055, 165), (0.050, 27), (0.050, 29), (0.048, 131), (0.043, 153), (0.037, 133), (0.037, 130), (0.028, 8), (0.028, 5), (0.027, 7), (0.026, 26), (0.016, 162), (0.012, 9), (0.007, 4), (0.005, 100), (0.005, 6), (0.005, 24)]
|
| 279 |
+
else:
|
| 280 |
+
if context.get_value('k') <= 36.0:
|
| 281 |
+
if context.get_value('n') <= 68.0:
|
| 282 |
+
return [(0.097, 184), (0.097, 56), (0.086, 186), (0.086, 183), (0.086, 188), (0.086, 58), (0.086, 60), (0.065, 54), (0.043, 187), (0.043, 185), (0.043, 57), (0.043, 61), (0.032, 55), (0.032, 130), (0.032, 59), (0.011, 181), (0.011, 163), (0.011, 136), (0.011, 138)]
|
| 283 |
+
else:
|
| 284 |
+
return [(0.117, 184), (0.117, 170), (0.117, 169), (0.107, 183), (0.106, 188), (0.075, 181), (0.064, 130), (0.064, 56), (0.053, 171), (0.032, 57), (0.032, 59), (0.032, 185), (0.011, 163), (0.011, 32), (0.011, 37), (0.011, 34), (0.011, 33), (0.011, 35), (0.011, 36), (0.011, 54)]
|
| 285 |
+
else:
|
| 286 |
+
if context.get_value('mat2_stride_0') <= 384.0:
|
| 287 |
+
return [(0.244, 0), (0.061, 76), (0.061, 79), (0.030, 3), (0.030, 183), (0.030, 189), (0.030, 187), (0.030, 64), (0.030, 190), (0.030, 62), (0.030, 198), (0.030, 201), (0.030, 77), (0.030, 200), (0.030, 80), (0.030, 199), (0.030, 78), (0.030, 184), (0.020, 86), (0.020, 84), (0.020, 120), (0.020, 81), (0.020, 121), (0.020, 85), (0.020, 122), (0.010, 83), (0.010, 118), (0.010, 119), (0.010, 82)]
|
| 288 |
+
else:
|
| 289 |
+
return [(0.274, 83), (0.171, 86), (0.152, 0), (0.071, 85), (0.061, 125), (0.050, 84), (0.020, 109), (0.020, 117), (0.020, 81), (0.020, 118), (0.020, 121), (0.020, 108), (0.020, 115), (0.020, 116), (0.010, 110), (0.010, 120), (0.010, 103), (0.010, 107), (0.010, 119), (0.010, 122)]
|
| 290 |
+
else:
|
| 291 |
+
if context.get_value('arith_intensity') <= 56.995582580566406:
|
| 292 |
+
if context.get_value('n') <= 68.0:
|
| 293 |
+
if context.get_value('k*n') <= 4448.0:
|
| 294 |
+
if context.get_value('m*n') <= 29626368.0:
|
| 295 |
+
return [(0.107, 198), (0.107, 200), (0.107, 201), (0.107, 199), (0.106, 76), (0.106, 79), (0.064, 197), (0.063, 56), (0.043, 184), (0.043, 187), (0.042, 80), (0.042, 77), (0.042, 183), (0.021, 78)]
|
| 296 |
+
else:
|
| 297 |
+
return [(0.073, 201), (0.073, 198), (0.073, 200), (0.073, 199), (0.073, 197), (0.073, 56), (0.073, 58), (0.073, 79), (0.073, 76), (0.072, 59), (0.072, 78), (0.072, 77), (0.072, 80), (0.018, 184), (0.018, 55), (0.018, 54)]
|
| 298 |
+
else:
|
| 299 |
+
if context.get_value('k') <= 348.0:
|
| 300 |
+
return [(0.206, 76), (0.183, 77), (0.169, 198), (0.160, 199), (0.053, 59), (0.046, 56), (0.038, 3), (0.030, 148), (0.030, 58), (0.030, 187), (0.023, 184), (0.015, 0), (0.008, 55), (0.008, 54)]
|
| 301 |
+
else:
|
| 302 |
+
return [(0.146, 198), (0.145, 199), (0.145, 148), (0.126, 0), (0.084, 76), (0.084, 77), (0.042, 80), (0.042, 79), (0.021, 149), (0.021, 150), (0.021, 3), (0.014, 46), (0.014, 74), (0.014, 75), (0.014, 124), (0.014, 194), (0.014, 195), (0.007, 145), (0.007, 146), (0.007, 2), (0.007, 72), (0.007, 147), (0.007, 71)]
|
| 303 |
+
else:
|
| 304 |
+
if context.get_value('m') <= 3264.0:
|
| 305 |
+
return [(0.247, 147), (0.115, 197), (0.066, 199), (0.066, 201), (0.066, 198), (0.049, 0), (0.049, 169), (0.049, 171), (0.033, 140), (0.033, 125), (0.033, 114), (0.016, 126), (0.016, 183), (0.016, 184), (0.016, 185), (0.016, 182), (0.016, 188), (0.016, 78), (0.016, 148), (0.016, 138), (0.016, 77), (0.016, 56), (0.016, 59)]
|
| 306 |
+
else:
|
| 307 |
+
if context.get_value('k') <= 62.5:
|
| 308 |
+
return [(0.226, 190), (0.226, 189), (0.122, 62), (0.122, 64), (0.055, 77), (0.055, 78), (0.037, 198), (0.036, 201), (0.036, 33), (0.024, 163), (0.018, 56), (0.018, 35), (0.018, 169), (0.006, 171)]
|
| 309 |
+
else:
|
| 310 |
+
return [(0.162, 35), (0.118, 33), (0.096, 189), (0.096, 190), (0.088, 169), (0.074, 62), (0.073, 56), (0.066, 171), (0.051, 198), (0.051, 201), (0.044, 59), (0.037, 64), (0.029, 63), (0.007, 0), (0.007, 77)]
|
| 311 |
+
else:
|
| 312 |
+
if context.get_value('m*n') <= 1097728.0:
|
| 313 |
+
return [(0.403, 0), (0.179, 141), (0.134, 150), (0.086, 147), (0.051, 148), (0.048, 3), (0.024, 189), (0.020, 199), (0.017, 64), (0.010, 65), (0.010, 77), (0.007, 114), (0.003, 138), (0.003, 59), (0.003, 182)]
|
| 314 |
+
else:
|
| 315 |
+
if context.get_value('m*n') <= 3244032.0:
|
| 316 |
+
return [(0.295, 189), (0.176, 64), (0.157, 65), (0.090, 0), (0.069, 62), (0.059, 63), (0.046, 77), (0.039, 169), (0.023, 199), (0.020, 35), (0.013, 33), (0.010, 171), (0.003, 141)]
|
| 317 |
+
else:
|
| 318 |
+
if context.get_value('n') <= 136.0:
|
| 319 |
+
return [(0.197, 189), (0.197, 63), (0.161, 77), (0.157, 62), (0.061, 33), (0.044, 65), (0.039, 35), (0.039, 64), (0.030, 169), (0.026, 0), (0.017, 199), (0.017, 148), (0.009, 56), (0.004, 3)]
|
| 320 |
+
else:
|
| 321 |
+
return [(0.460, 0), (0.145, 62), (0.138, 63), (0.081, 35), (0.047, 33), (0.043, 189), (0.023, 64), (0.018, 77), (0.013, 169), (0.009, 65), (0.009, 56), (0.005, 32), (0.005, 59), (0.002, 183), (0.002, 163)]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMA100.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: B950
|
| 2 |
+
# fmt: off
|
| 3 |
+
# This file was generated by AutoHeuristic. Do not modify it manually!
|
| 4 |
+
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/
|
| 5 |
+
from typing import List, Optional, Tuple
|
| 6 |
+
|
| 7 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import (
|
| 8 |
+
AHContext,
|
| 9 |
+
AHMetadata,
|
| 10 |
+
Choice,
|
| 11 |
+
)
|
| 12 |
+
from torch._inductor.autoheuristic.learnedheuristic_interface import (
|
| 13 |
+
LearnedHeuristicDecision,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MixedMMA100(LearnedHeuristicDecision):
|
| 18 |
+
|
| 19 |
+
def __init__(self) -> None:
|
| 20 |
+
self.choices: list[Choice] = []
|
| 21 |
+
self.fill_choices()
|
| 22 |
+
|
| 23 |
+
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
|
| 24 |
+
return (
|
| 25 |
+
metadata.name == self.get_name()
|
| 26 |
+
and metadata.shared_memory == 166912
|
| 27 |
+
and str(metadata.device_capa) == "(8, 0)"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def get_confidence_threshold(self) -> float:
|
| 31 |
+
return 0.0
|
| 32 |
+
|
| 33 |
+
def get_choice(self, idx: int) -> Optional[str]:
|
| 34 |
+
if idx < len(self.choices):
|
| 35 |
+
return self.choices[idx]
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
def fill_choices(self) -> None:
|
| 39 |
+
self.choices.append('extern_fallback_mixed_mm')
|
| 40 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 41 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 42 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 43 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2')
|
| 44 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2')
|
| 45 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 46 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=3_numwarps=4')
|
| 47 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=5_numwarps=8')
|
| 48 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 49 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 50 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 51 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4')
|
| 52 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 53 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 54 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 55 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 56 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 57 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=128_numstages=4_numwarps=8')
|
| 58 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4')
|
| 59 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 60 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 61 |
+
|
| 62 |
+
def get_name(self) -> str:
|
| 63 |
+
return 'mixed_mm'
|
| 64 |
+
|
| 65 |
+
def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:
|
| 66 |
+
if str(context.get_value('1LEQmLEQ16')) != 'True':
|
| 67 |
+
if context.get_value('m') <= 32.5:
|
| 68 |
+
if context.get_value('n') <= 6976.0:
|
| 69 |
+
if context.get_value('n') <= 3520.0:
|
| 70 |
+
if context.get_value('m*n') <= 37632.0:
|
| 71 |
+
return None
|
| 72 |
+
else:
|
| 73 |
+
return [(1.000, 13)]
|
| 74 |
+
else:
|
| 75 |
+
if context.get_value('m*k') <= 452352.0:
|
| 76 |
+
return [(0.590, 13), (0.256, 8), (0.103, 7), (0.051, 11)]
|
| 77 |
+
else:
|
| 78 |
+
return [(0.778, 8), (0.222, 13)]
|
| 79 |
+
else:
|
| 80 |
+
if context.get_value('k*n') <= 102776832.0:
|
| 81 |
+
if context.get_value('n') <= 14656.0:
|
| 82 |
+
return [(1.000, 11)]
|
| 83 |
+
else:
|
| 84 |
+
return [(0.889, 11), (0.111, 13)]
|
| 85 |
+
else:
|
| 86 |
+
return [(1.000, 11)]
|
| 87 |
+
else:
|
| 88 |
+
if context.get_value('m*n') <= 446464.0:
|
| 89 |
+
if context.get_value('m*n') <= 223424.0:
|
| 90 |
+
if context.get_value('mat1_stride_0') <= 3968.0:
|
| 91 |
+
return None
|
| 92 |
+
else:
|
| 93 |
+
return None
|
| 94 |
+
else:
|
| 95 |
+
if context.get_value('m*n') <= 346112.0:
|
| 96 |
+
return [(0.960, 16), (0.040, 7)]
|
| 97 |
+
else:
|
| 98 |
+
return [(0.750, 16), (0.136, 14), (0.114, 7)]
|
| 99 |
+
else:
|
| 100 |
+
if str(context.get_value('33LEQmLEQ64')) != 'True':
|
| 101 |
+
if context.get_value('n') <= 6976.0:
|
| 102 |
+
return [(1.000, 14)]
|
| 103 |
+
else:
|
| 104 |
+
return [(0.753, 2), (0.222, 1), (0.015, 7), (0.007, 16), (0.004, 12)]
|
| 105 |
+
else:
|
| 106 |
+
if context.get_value('n') <= 13888.0:
|
| 107 |
+
return [(0.710, 14), (0.275, 21), (0.014, 12)]
|
| 108 |
+
else:
|
| 109 |
+
return [(0.374, 19), (0.339, 20), (0.106, 21), (0.101, 16), (0.066, 17), (0.009, 14), (0.004, 18)]
|
| 110 |
+
else:
|
| 111 |
+
if context.get_value('n') <= 3520.0:
|
| 112 |
+
if context.get_value('arith_intensity') <= 3.994754433631897:
|
| 113 |
+
if str(context.get_value('mat2_dtype')) != 'torch.uint8':
|
| 114 |
+
if context.get_value('m*k') <= 18944.0:
|
| 115 |
+
return [(0.577, 5), (0.423, 6)]
|
| 116 |
+
else:
|
| 117 |
+
return [(0.988, 5), (0.012, 6)]
|
| 118 |
+
else:
|
| 119 |
+
if context.get_value('arith_intensity') <= 2.9899919033050537:
|
| 120 |
+
return None
|
| 121 |
+
else:
|
| 122 |
+
return None
|
| 123 |
+
else:
|
| 124 |
+
if context.get_value('arith_intensity') <= 7.956453561782837:
|
| 125 |
+
if context.get_value('k*n') <= 9244032.0:
|
| 126 |
+
return [(0.822, 5), (0.178, 6)]
|
| 127 |
+
else:
|
| 128 |
+
return [(0.977, 5), (0.023, 0)]
|
| 129 |
+
else:
|
| 130 |
+
if context.get_value('m*k') <= 978944.0:
|
| 131 |
+
return [(1.000, 5)]
|
| 132 |
+
else:
|
| 133 |
+
return [(0.971, 5), (0.029, 0)]
|
| 134 |
+
else:
|
| 135 |
+
if context.get_value('n') <= 13632.0:
|
| 136 |
+
if context.get_value('n') <= 6976.0:
|
| 137 |
+
return [(1.000, 6)]
|
| 138 |
+
else:
|
| 139 |
+
if context.get_value('k') <= 3968.0:
|
| 140 |
+
return [(0.617, 3), (0.111, 5), (0.099, 7), (0.086, 9), (0.062, 6), (0.025, 8)]
|
| 141 |
+
else:
|
| 142 |
+
return [(0.779, 8), (0.119, 5), (0.053, 7), (0.035, 6), (0.013, 3)]
|
| 143 |
+
else:
|
| 144 |
+
if context.get_value('k*n') <= 39518208.0:
|
| 145 |
+
return [(0.385, 4), (0.327, 3), (0.192, 6), (0.038, 7), (0.038, 10), (0.019, 5)]
|
| 146 |
+
else:
|
| 147 |
+
if context.get_value('n') <= 20800.0:
|
| 148 |
+
return [(0.821, 6), (0.121, 7), (0.029, 4), (0.014, 5), (0.007, 3), (0.007, 8)]
|
| 149 |
+
else:
|
| 150 |
+
return [(0.530, 7), (0.386, 6), (0.046, 8), (0.021, 3), (0.015, 4), (0.002, 5)]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MixedMMH100.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: B950
|
| 2 |
+
# fmt: off
|
| 3 |
+
# This file was generated by AutoHeuristic. Do not modify it manually!
|
| 4 |
+
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/mixed_mm/
|
| 5 |
+
from typing import Optional
|
| 6 |
+
|
| 7 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import (
|
| 8 |
+
AHContext,
|
| 9 |
+
AHMetadata,
|
| 10 |
+
Choice,
|
| 11 |
+
)
|
| 12 |
+
from torch._inductor.autoheuristic.learnedheuristic_interface import (
|
| 13 |
+
LearnedHeuristicDecision,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MixedMMH100(LearnedHeuristicDecision):
|
| 18 |
+
|
| 19 |
+
def __init__(self) -> None:
|
| 20 |
+
self.choices: list[Choice] = []
|
| 21 |
+
self.fill_choices()
|
| 22 |
+
|
| 23 |
+
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
|
| 24 |
+
return (
|
| 25 |
+
metadata.name == self.get_name()
|
| 26 |
+
and metadata.shared_memory == 232448
|
| 27 |
+
and str(metadata.device_capa) == "(9, 0)"
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def get_confidence_threshold(self) -> float:
|
| 31 |
+
return 0.0
|
| 32 |
+
|
| 33 |
+
def get_choice(self, idx: int) -> Optional[str]:
|
| 34 |
+
if idx < len(self.choices):
|
| 35 |
+
return self.choices[idx]
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
def fill_choices(self) -> None:
|
| 39 |
+
self.choices.append('extern_fallback_mixed_mm')
|
| 40 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=128_numstages=3_numwarps=4')
|
| 41 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=32_BLOCK-N=64_numstages=3_numwarps=4')
|
| 42 |
+
self.choices.append('type=triton_BLOCK-M=128_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 43 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 44 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=2')
|
| 45 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=2')
|
| 46 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 47 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=3_numwarps=4')
|
| 48 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=256_BLOCK-N=128_numstages=5_numwarps=8')
|
| 49 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=128_numstages=5_numwarps=8')
|
| 50 |
+
self.choices.append('type=triton_BLOCK-M=16_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=4')
|
| 51 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 52 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=2_numwarps=4')
|
| 53 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 54 |
+
self.choices.append('type=triton_BLOCK-M=32_BLOCK-K=32_BLOCK-N=64_numstages=5_numwarps=8')
|
| 55 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=128_numstages=4_numwarps=4')
|
| 56 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=32_numstages=5_numwarps=4')
|
| 57 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=128_BLOCK-N=64_numstages=5_numwarps=4')
|
| 58 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=128_numstages=3_numwarps=4')
|
| 59 |
+
self.choices.append('type=triton_BLOCK-M=64_BLOCK-K=64_BLOCK-N=64_numstages=3_numwarps=8')
|
| 60 |
+
|
| 61 |
+
def get_name(self) -> str:
|
| 62 |
+
return 'mixed_mm'
|
| 63 |
+
|
| 64 |
+
def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:
|
| 65 |
+
if context.get_value('arith_intensity') <= 15.988086223602295:
|
| 66 |
+
if context.get_value('n') <= 25280.0:
|
| 67 |
+
if context.get_value('n') <= 1344.0:
|
| 68 |
+
if context.get_value('mat1_stride_0') <= 7808.0:
|
| 69 |
+
return [(0.581, 7), (0.419, 6)]
|
| 70 |
+
else:
|
| 71 |
+
if context.get_value('m*n') <= 7680.0:
|
| 72 |
+
return [(0.875, 0), (0.125, 6)]
|
| 73 |
+
else:
|
| 74 |
+
return [(0.833, 0), (0.167, 7)]
|
| 75 |
+
else:
|
| 76 |
+
if context.get_value('n') <= 8512.0:
|
| 77 |
+
if str(context.get_value('mat2_dtype')) != 'torch.int8':
|
| 78 |
+
return [(0.763, 6), (0.237, 7)]
|
| 79 |
+
else:
|
| 80 |
+
return [(0.725, 7), (0.275, 6)]
|
| 81 |
+
else:
|
| 82 |
+
if str(context.get_value('mat1_dtype')) != 'torch.bfloat16':
|
| 83 |
+
return [(0.736, 7), (0.197, 9), (0.048, 6), (0.014, 8), (0.005, 10)]
|
| 84 |
+
else:
|
| 85 |
+
return [(0.473, 7), (0.398, 6), (0.097, 9), (0.032, 10)]
|
| 86 |
+
else:
|
| 87 |
+
if context.get_value('n') <= 42254.0:
|
| 88 |
+
if context.get_value('n') <= 33856.0:
|
| 89 |
+
if context.get_value('k*n') <= 68157440.0:
|
| 90 |
+
return [(0.370, 4), (0.370, 5), (0.074, 7), (0.074, 8), (0.074, 11), (0.037, 6)]
|
| 91 |
+
else:
|
| 92 |
+
return [(0.916, 8), (0.036, 7), (0.036, 9), (0.012, 4)]
|
| 93 |
+
else:
|
| 94 |
+
return [(0.659, 5), (0.341, 6)]
|
| 95 |
+
else:
|
| 96 |
+
if context.get_value('k*n') <= 326052992.0:
|
| 97 |
+
if context.get_value('n') <= 55232.0:
|
| 98 |
+
return [(0.571, 6), (0.321, 7), (0.036, 4), (0.036, 8), (0.036, 9)]
|
| 99 |
+
else:
|
| 100 |
+
return [(0.506, 6), (0.325, 8), (0.104, 7), (0.039, 5), (0.026, 9)]
|
| 101 |
+
else:
|
| 102 |
+
if context.get_value('n') <= 57024.0:
|
| 103 |
+
return [(0.462, 9), (0.385, 7), (0.115, 6), (0.038, 8)]
|
| 104 |
+
else:
|
| 105 |
+
return [(0.598, 8), (0.223, 9), (0.107, 6), (0.071, 7)]
|
| 106 |
+
else:
|
| 107 |
+
if context.get_value('m*n') <= 543936.0:
|
| 108 |
+
if str(context.get_value('17LEQmLEQ32')) != 'True':
|
| 109 |
+
if context.get_value('m*n') <= 262272.0:
|
| 110 |
+
if context.get_value('n') <= 1592.5:
|
| 111 |
+
return [(0.860, 0), (0.140, 9)]
|
| 112 |
+
else:
|
| 113 |
+
return None
|
| 114 |
+
else:
|
| 115 |
+
if context.get_value('m*k') <= 1294336.0:
|
| 116 |
+
return [(0.833, 17), (0.150, 18), (0.017, 15)]
|
| 117 |
+
else:
|
| 118 |
+
return [(0.917, 17), (0.083, 8)]
|
| 119 |
+
else:
|
| 120 |
+
if context.get_value('n') <= 12416.0:
|
| 121 |
+
if context.get_value('m*n') <= 43008.0:
|
| 122 |
+
return None
|
| 123 |
+
else:
|
| 124 |
+
return [(0.853, 14), (0.147, 9)]
|
| 125 |
+
else:
|
| 126 |
+
return [(0.625, 12), (0.375, 14)]
|
| 127 |
+
else:
|
| 128 |
+
if context.get_value('m') <= 32.5:
|
| 129 |
+
if context.get_value('mat2_stride_1') <= 6656.0:
|
| 130 |
+
if context.get_value('n') <= 69184.0:
|
| 131 |
+
return [(0.611, 12), (0.361, 14), (0.028, 13)]
|
| 132 |
+
else:
|
| 133 |
+
return [(1.000, 12)]
|
| 134 |
+
else:
|
| 135 |
+
if context.get_value('mat2_stride_1') <= 20864.0:
|
| 136 |
+
return [(1.000, 12)]
|
| 137 |
+
else:
|
| 138 |
+
return [(0.958, 12), (0.042, 9)]
|
| 139 |
+
else:
|
| 140 |
+
if context.get_value('m*n') <= 1085440.0:
|
| 141 |
+
if context.get_value('n') <= 9152.0:
|
| 142 |
+
return [(1.000, 18)]
|
| 143 |
+
else:
|
| 144 |
+
return [(0.780, 18), (0.160, 16), (0.060, 20)]
|
| 145 |
+
else:
|
| 146 |
+
if context.get_value('m') <= 67.0:
|
| 147 |
+
return [(0.650, 16), (0.203, 19), (0.122, 18), (0.016, 20), (0.008, 1)]
|
| 148 |
+
else:
|
| 149 |
+
return [(0.561, 3), (0.185, 16), (0.096, 20), (0.083, 19), (0.076, 2)]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# flake8: noqa: B950
|
| 2 |
+
# fmt: off
|
| 3 |
+
# This file was generated by AutoHeuristic. Do not modify it manually!
|
| 4 |
+
# To regenerate this file, take a look at the steps in the README.md file inside torchgen/_autoheuristic/pad_mm/
|
| 5 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import AHContext, AHMetadata, Choice, CHOICE_COL
|
| 6 |
+
from torch._inductor.autoheuristic.learnedheuristic_interface import (
|
| 7 |
+
LearnedHeuristicRegression,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class PadMMA100(LearnedHeuristicRegression):
|
| 12 |
+
|
| 13 |
+
def __init__(self) -> None:
|
| 14 |
+
pass
|
| 15 |
+
|
| 16 |
+
def check_precondition(self, metadata: AHMetadata, context: AHContext,) -> bool:
|
| 17 |
+
return (
|
| 18 |
+
metadata.name == self.get_name()
|
| 19 |
+
and metadata.shared_memory == 166912
|
| 20 |
+
and str(metadata.device_capa) == "(8, 0)"
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def get_feedback(self, context: AHContext, choice: Choice) -> float:
|
| 24 |
+
context.context_dict[CHOICE_COL] = choice
|
| 25 |
+
return self.predict(context)
|
| 26 |
+
|
| 27 |
+
def get_confidence_threshold(self) -> float:
|
| 28 |
+
return 1.7025303314066
|
| 29 |
+
|
| 30 |
+
def get_name(self) -> str:
|
| 31 |
+
return 'pad_mm'
|
| 32 |
+
|
| 33 |
+
def predict(self, context: AHContext) -> float:
|
| 34 |
+
if str(context.get_value('choice')) != 'pad':
|
| 35 |
+
if str(context.get_value('using_tf32')) != 'False':
|
| 36 |
+
if context.get_value('m*n') <= 4171264.0:
|
| 37 |
+
if context.get_value('m*k') <= 3999308.0:
|
| 38 |
+
return 1.8751469764071178
|
| 39 |
+
else:
|
| 40 |
+
if str(context.get_value('n_multiple_32')) != 'True':
|
| 41 |
+
return 0.9117231355626345
|
| 42 |
+
else:
|
| 43 |
+
return 1.1607689608873861
|
| 44 |
+
else:
|
| 45 |
+
if str(context.get_value('n_multiple_2')) != 'True':
|
| 46 |
+
if str(context.get_value('using_tf32')) != 'True':
|
| 47 |
+
return 0.7430382200435992
|
| 48 |
+
else:
|
| 49 |
+
return 0.8531269794448678
|
| 50 |
+
else:
|
| 51 |
+
if str(context.get_value('k_multiple_2')) != 'True':
|
| 52 |
+
return 0.7577181972719917
|
| 53 |
+
else:
|
| 54 |
+
return 0.8977349440424219
|
| 55 |
+
else:
|
| 56 |
+
if context.get_value('m*n') <= 1299712.0:
|
| 57 |
+
return 1.1669723418995592
|
| 58 |
+
else:
|
| 59 |
+
if context.get_value('mat2_stride_1') <= 45217.5:
|
| 60 |
+
if context.get_value('m*n') <= 55884158.0:
|
| 61 |
+
return 1.0262769936909601
|
| 62 |
+
else:
|
| 63 |
+
return 1.0022677428470845
|
| 64 |
+
else:
|
| 65 |
+
if context.get_value('m') <= 18478.0:
|
| 66 |
+
return 1.1127066261894312
|
| 67 |
+
else:
|
| 68 |
+
return 1.0337740659894263
|
| 69 |
+
else:
|
| 70 |
+
if str(context.get_value('mat1_dtype')) != 'torch.float32':
|
| 71 |
+
if str(context.get_value('n_multiple_2')) != 'False':
|
| 72 |
+
if str(context.get_value('k_multiple_2')) != 'True':
|
| 73 |
+
if context.get_value('mat1_stride_0') <= 561.0:
|
| 74 |
+
return 1.2900382135142956
|
| 75 |
+
else:
|
| 76 |
+
return 1.5761737616057887
|
| 77 |
+
else:
|
| 78 |
+
if context.get_value('num_dims_needs_padding') <= 1.5:
|
| 79 |
+
return 1.0472263310239422
|
| 80 |
+
else:
|
| 81 |
+
return 1.1727673465762514
|
| 82 |
+
else:
|
| 83 |
+
if context.get_value('k') <= 28238.5:
|
| 84 |
+
if context.get_value('k/(m*n)') <= 0.00026227018679492176:
|
| 85 |
+
return 1.6770542505397175
|
| 86 |
+
else:
|
| 87 |
+
return 1.3974785435105923
|
| 88 |
+
else:
|
| 89 |
+
if str(context.get_value('mat1_dtype')) != 'torch.bfloat16':
|
| 90 |
+
return 1.3952699800111992
|
| 91 |
+
else:
|
| 92 |
+
return 1.5759286511628336
|
| 93 |
+
else:
|
| 94 |
+
if str(context.get_value('using_tf32')) != 'False':
|
| 95 |
+
if context.get_value('m*n') <= 14119424.0:
|
| 96 |
+
return 0.8875772670422478
|
| 97 |
+
else:
|
| 98 |
+
if str(context.get_value('mat2_innermost_needs_padding')) != 'True':
|
| 99 |
+
return 1.1467728924377265
|
| 100 |
+
else:
|
| 101 |
+
return 1.215842963532998
|
| 102 |
+
else:
|
| 103 |
+
if context.get_value('arith_intensity') <= 396.8774871826172:
|
| 104 |
+
return 0.89940161869551
|
| 105 |
+
else:
|
| 106 |
+
if context.get_value('mat2_stride_1') <= 45217.5:
|
| 107 |
+
return 0.9964328169353532
|
| 108 |
+
else:
|
| 109 |
+
return 0.9493479238294826
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from functools import partial
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import (
|
| 9 |
+
AHContext,
|
| 10 |
+
AHMetadata,
|
| 11 |
+
AHOperation,
|
| 12 |
+
Choice,
|
| 13 |
+
CHOICE_COL,
|
| 14 |
+
Feedback,
|
| 15 |
+
FEEDBACK_COL,
|
| 16 |
+
get_metadata_str_from_log,
|
| 17 |
+
)
|
| 18 |
+
from torch._inductor.autoheuristic.learned_heuristic_controller import (
|
| 19 |
+
LearnedHeuristicController,
|
| 20 |
+
)
|
| 21 |
+
from torch._inductor.ir import ChoiceCaller
|
| 22 |
+
from torch._inductor.runtime.runtime_utils import cache_dir
|
| 23 |
+
from torch._inductor.utils import get_gpu_shared_memory
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class LocalFeedback:
|
| 27 |
+
"""
|
| 28 |
+
To be able to collect data for a choice, a function providing feedback given a choice has to be provided.
|
| 29 |
+
LocalFeedback can be used when AutoHeuristic should immediately run the function to collect feedback for each choice
|
| 30 |
+
(see pad_mm.py, where the autotuning happens locally, for an example).
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, feedback_fn: Callable[[Choice], Feedback]) -> None:
|
| 34 |
+
self.feedback_fn = feedback_fn
|
| 35 |
+
|
| 36 |
+
def __call__(self, choice: Choice) -> Feedback:
|
| 37 |
+
return self.feedback_fn(choice)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class InconsistentMetadata(Exception):
|
| 41 |
+
"""
|
| 42 |
+
Exception that is thrown when AutoHeuristic tries to log data to a file where the metadata stored in the file does
|
| 43 |
+
not match the metadata it would store if the file didn't exist.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class AutoHeuristic:
|
| 48 |
+
"""
|
| 49 |
+
AutoHeuristic is a framework that allows one to collect data, learn a heuristic (i.e. a regression tree) and
|
| 50 |
+
generate the heuristic to code. This class allows one to collect data. The collected data can then be used to train
|
| 51 |
+
a heuristic (see torchgen/autoheuristic/).
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
collected_feedback: dict[Choice, Feedback]
|
| 55 |
+
|
| 56 |
+
def __init__(
|
| 57 |
+
self,
|
| 58 |
+
fallback: Callable[[], Choice],
|
| 59 |
+
choices: list[Choice],
|
| 60 |
+
feedback: Optional[LocalFeedback],
|
| 61 |
+
context: AHContext,
|
| 62 |
+
name: str,
|
| 63 |
+
augment_context: Optional[list[AHOperation]] = None,
|
| 64 |
+
precondition: Optional[Callable[[AHMetadata, AHContext], bool]] = None,
|
| 65 |
+
) -> None:
|
| 66 |
+
"""
|
| 67 |
+
Initializes an instance of the AutoHeuristic class.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
fallback: A callable that returns a Choice when the heuristic is unsure which choice to make, or
|
| 71 |
+
AutoHeuristic is in data collection mode.
|
| 72 |
+
choices: A list of possible choices the heuristic can make.
|
| 73 |
+
feedback: An instance of LocalFeedback that provides feedback for a given choice.
|
| 74 |
+
context: Context to store with each choice and feedback.
|
| 75 |
+
name: A string that identifies the heuristic.
|
| 76 |
+
augment_context: An optional list of AHOperation instances that augment the context.
|
| 77 |
+
precondition: A callable that returns a boolean indicating whether AutoHeuristic should run.
|
| 78 |
+
"""
|
| 79 |
+
self.fallback = fallback
|
| 80 |
+
self.choices = choices
|
| 81 |
+
self.feedback = feedback
|
| 82 |
+
self.context = context
|
| 83 |
+
self.name = name
|
| 84 |
+
self.collected_feedback = {}
|
| 85 |
+
self.augment_context = augment_context
|
| 86 |
+
self.metadata = AHMetadata(
|
| 87 |
+
get_gpu_shared_memory(),
|
| 88 |
+
torch.cuda.get_device_capability(),
|
| 89 |
+
self.choices,
|
| 90 |
+
self.name,
|
| 91 |
+
)
|
| 92 |
+
self.precondition = precondition
|
| 93 |
+
|
| 94 |
+
if not self.satisfies_precondition():
|
| 95 |
+
return
|
| 96 |
+
|
| 97 |
+
if torch._inductor.config.autoheuristic_log_path == "DEFAULT":
|
| 98 |
+
self.log_path = self.get_default_log_path()
|
| 99 |
+
else:
|
| 100 |
+
self.log_path = torch._inductor.config.autoheuristic_log_path
|
| 101 |
+
|
| 102 |
+
if torch._inductor.config.collect_autoheuristic(self.name):
|
| 103 |
+
if self.feedback is not None:
|
| 104 |
+
for choice in self.choices:
|
| 105 |
+
feedback_val = self.feedback(choice)
|
| 106 |
+
self.save_data(choice, feedback_val)
|
| 107 |
+
|
| 108 |
+
def satisfies_precondition(self) -> bool:
|
| 109 |
+
return self.precondition is None or self.precondition(
|
| 110 |
+
self.metadata, self.context
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
def get_choice(self) -> Choice:
|
| 114 |
+
"""
|
| 115 |
+
Returns the chosen option based on the value of autoheuristic_use.
|
| 116 |
+
If self.name is one of the comma separated strings in autoheuristic_use,
|
| 117 |
+
it queries a learned heuristic to make a decision. Otherwise, it returns the fallback option.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
if not self.satisfies_precondition():
|
| 121 |
+
return self.fallback()
|
| 122 |
+
|
| 123 |
+
if torch._inductor.config.use_autoheuristic(self.name):
|
| 124 |
+
if self.augment_context is not None:
|
| 125 |
+
self.context.apply_operations(self.augment_context)
|
| 126 |
+
controller = LearnedHeuristicController(
|
| 127 |
+
self.metadata,
|
| 128 |
+
self.context,
|
| 129 |
+
)
|
| 130 |
+
decision = controller.get_decision()
|
| 131 |
+
if decision not in self.choices:
|
| 132 |
+
# TODO(AlnisM): We might want to allow this in the future
|
| 133 |
+
return self.fallback()
|
| 134 |
+
if decision is not None:
|
| 135 |
+
return decision
|
| 136 |
+
return self.fallback()
|
| 137 |
+
|
| 138 |
+
def get_top_k_choices(
|
| 139 |
+
self, top_k: int, always_included: Optional[list[str]] = None
|
| 140 |
+
) -> Optional[list[Choice]]:
|
| 141 |
+
if not self.satisfies_precondition():
|
| 142 |
+
return None
|
| 143 |
+
if torch._inductor.config.use_autoheuristic(self.name):
|
| 144 |
+
if self.augment_context is not None:
|
| 145 |
+
self.context.apply_operations(self.augment_context)
|
| 146 |
+
controller = LearnedHeuristicController(
|
| 147 |
+
self.metadata,
|
| 148 |
+
self.context,
|
| 149 |
+
)
|
| 150 |
+
choices = controller.get_decisions_ranked(top_k)
|
| 151 |
+
if choices is None:
|
| 152 |
+
return None
|
| 153 |
+
if always_included is not None:
|
| 154 |
+
for choice in always_included:
|
| 155 |
+
if choice not in choices:
|
| 156 |
+
choices.append(choice)
|
| 157 |
+
return choices
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
def get_collected_feedback(self, choice: Choice) -> Any:
|
| 161 |
+
return self.collected_feedback.get(choice, None)
|
| 162 |
+
|
| 163 |
+
@staticmethod
|
| 164 |
+
def get_device_identifier() -> str:
|
| 165 |
+
# a heuristic might work well for one GPU, but not for another
|
| 166 |
+
# we store the collected data per GPU model and learn a heuristic per GPU model
|
| 167 |
+
|
| 168 |
+
# TODO(AlnisM): just using the device name for now, but the same GPU model can have different names
|
| 169 |
+
device_name = torch.cuda.get_device_name().replace(" ", "_")
|
| 170 |
+
return device_name
|
| 171 |
+
|
| 172 |
+
def get_default_log_path(self) -> str:
|
| 173 |
+
device_name = self.get_device_identifier()
|
| 174 |
+
path = f"{cache_dir()}/autoheuristic/{device_name}/"
|
| 175 |
+
os.makedirs(path, exist_ok=True)
|
| 176 |
+
path += f"{self.name}.txt"
|
| 177 |
+
return path
|
| 178 |
+
|
| 179 |
+
def serialize_metadata(self) -> str:
|
| 180 |
+
metadata_dict = self.metadata.to_dict()
|
| 181 |
+
(
|
| 182 |
+
num_features,
|
| 183 |
+
cat_features,
|
| 184 |
+
) = self.context.get_numerical_and_categorical_features()
|
| 185 |
+
metadata_dict["numerical_features"] = num_features
|
| 186 |
+
metadata_dict["categorical_features"] = cat_features
|
| 187 |
+
return json.dumps(metadata_dict)
|
| 188 |
+
|
| 189 |
+
def save_data(self, choice: Choice, feedback_val: Feedback) -> None:
|
| 190 |
+
self.collected_feedback[choice] = feedback_val
|
| 191 |
+
log_path = self.log_path
|
| 192 |
+
|
| 193 |
+
lines = []
|
| 194 |
+
log_exists = os.path.exists(log_path)
|
| 195 |
+
if log_exists:
|
| 196 |
+
# if log already exists, make sure it is consistent
|
| 197 |
+
metadata = self.serialize_metadata()
|
| 198 |
+
existing_metadata = get_metadata_str_from_log(self.log_path)
|
| 199 |
+
if existing_metadata != metadata:
|
| 200 |
+
raise InconsistentMetadata(
|
| 201 |
+
"Given metadata does not match existing metadata"
|
| 202 |
+
)
|
| 203 |
+
else:
|
| 204 |
+
lines.append(self.serialize_metadata())
|
| 205 |
+
feature_header = self.context.get_feature_names_csv()
|
| 206 |
+
header = feature_header + "," + CHOICE_COL + "," + FEEDBACK_COL
|
| 207 |
+
lines.append(header)
|
| 208 |
+
|
| 209 |
+
line = ""
|
| 210 |
+
feature_values = self.context.get_feature_values_csv()
|
| 211 |
+
line += feature_values + "," + choice + "," + str(feedback_val)
|
| 212 |
+
lines.append(line)
|
| 213 |
+
|
| 214 |
+
with open(log_path, "a") as f:
|
| 215 |
+
f.write("\n".join(lines) + "\n")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class AutoHeuristicSelectAlgorithm(AutoHeuristic):
|
| 219 |
+
"""
|
| 220 |
+
AutoHeuristicSelectAlgorithm is a subclass of AutoHeuristic that allows one to collect data and learn a heuristic
|
| 221 |
+
when one wants to use AutoHeuristic for kernel choice selection.
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
def __init__(
|
| 225 |
+
self,
|
| 226 |
+
fallback: Callable[[], Optional[ChoiceCaller]],
|
| 227 |
+
choices: list[ChoiceCaller],
|
| 228 |
+
input_nodes: list[Any],
|
| 229 |
+
context: AHContext,
|
| 230 |
+
name: str,
|
| 231 |
+
augment_context: Optional[list[AHOperation]] = None,
|
| 232 |
+
precondition: Optional[Callable[[AHMetadata, AHContext], bool]] = None,
|
| 233 |
+
) -> None:
|
| 234 |
+
"""
|
| 235 |
+
The arguments choices, input_nodes and name have to match the ones used in the call to
|
| 236 |
+
autotune_select_algorithm(), e.g. if the following call is made
|
| 237 |
+
autotune_select_algorithm(name, choices, input_nodes, layout), the same name, choices and input_nodes
|
| 238 |
+
have to be used here.
|
| 239 |
+
"""
|
| 240 |
+
self.input_nodes = input_nodes
|
| 241 |
+
self.choicestr2choice: dict[str, ChoiceCaller] = {}
|
| 242 |
+
for choice in choices:
|
| 243 |
+
self.choicestr2choice[choice.autoheuristic_id()] = choice
|
| 244 |
+
choices_str = list(self.choicestr2choice.keys())
|
| 245 |
+
|
| 246 |
+
def fallback_str() -> str:
|
| 247 |
+
fallback_choice = fallback()
|
| 248 |
+
if fallback_choice is None:
|
| 249 |
+
# TODO: Find a nicer way to handle this
|
| 250 |
+
return "unsure"
|
| 251 |
+
return fallback_choice.autoheuristic_id()
|
| 252 |
+
|
| 253 |
+
super().__init__(
|
| 254 |
+
fallback_str,
|
| 255 |
+
choices_str,
|
| 256 |
+
None,
|
| 257 |
+
context,
|
| 258 |
+
name,
|
| 259 |
+
augment_context,
|
| 260 |
+
precondition,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
if (
|
| 264 |
+
torch._inductor.config.collect_autoheuristic(self.name)
|
| 265 |
+
and self.satisfies_precondition()
|
| 266 |
+
):
|
| 267 |
+
self.register_global_feedback(input_nodes, choices)
|
| 268 |
+
|
| 269 |
+
def register_global_feedback(
|
| 270 |
+
self, input_nodes: list[Any], choices: list[ChoiceCaller]
|
| 271 |
+
) -> None:
|
| 272 |
+
"""
|
| 273 |
+
Registers a callback in select_algorithm, which is called with the timing of each choice.
|
| 274 |
+
"""
|
| 275 |
+
|
| 276 |
+
from torch._inductor.select_algorithm import (
|
| 277 |
+
add_feedback_saver,
|
| 278 |
+
create_inputs_key,
|
| 279 |
+
create_precompile_key,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
def store_global_feedback(
|
| 283 |
+
ah_inputs_key: str,
|
| 284 |
+
ah_precompile_key: str,
|
| 285 |
+
timings: dict[ChoiceCaller, float],
|
| 286 |
+
name: str,
|
| 287 |
+
input_nodes: list[Any],
|
| 288 |
+
choices: list[ChoiceCaller],
|
| 289 |
+
) -> None:
|
| 290 |
+
current_inputs_key = create_inputs_key(input_nodes)
|
| 291 |
+
if current_inputs_key != ah_inputs_key:
|
| 292 |
+
return
|
| 293 |
+
current_precompile_key = create_precompile_key(
|
| 294 |
+
name, current_inputs_key, choices
|
| 295 |
+
)
|
| 296 |
+
if current_precompile_key != ah_precompile_key:
|
| 297 |
+
return
|
| 298 |
+
for choice, time in timings.items():
|
| 299 |
+
self.save_data(choice.autoheuristic_id(), time)
|
| 300 |
+
|
| 301 |
+
inputs_key = create_inputs_key(input_nodes)
|
| 302 |
+
precompile_key = create_precompile_key(self.name, inputs_key, choices)
|
| 303 |
+
feedback_saver = partial(store_global_feedback, inputs_key, precompile_key)
|
| 304 |
+
add_feedback_saver(feedback_saver)
|
| 305 |
+
|
| 306 |
+
def get_choice_caller(self) -> Optional[ChoiceCaller]:
|
| 307 |
+
choice = self.get_choice()
|
| 308 |
+
return self.choicestr2choice.get(choice, None)
|
| 309 |
+
|
| 310 |
+
def get_top_k_choices_caller(
|
| 311 |
+
self, top_k: int, always_included: Optional[list[str]] = None
|
| 312 |
+
) -> Optional[list[ChoiceCaller]]:
|
| 313 |
+
choices = self.get_top_k_choices(top_k, always_included)
|
| 314 |
+
if choices is None:
|
| 315 |
+
return None
|
| 316 |
+
return [self.choicestr2choice[choice] for choice in choices]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
from collections.abc import Callable
|
| 3 |
+
from typing import Any
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
Feedback = float
|
| 9 |
+
Choice = str
|
| 10 |
+
Value = Any
|
| 11 |
+
|
| 12 |
+
CHOICE_COL = "choice"
|
| 13 |
+
FEEDBACK_COL = "feedback"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class AHFeature:
|
| 17 |
+
"""
|
| 18 |
+
The context, that AutoHeuristic stores, is a list of features. AutoHeuristic needs to know whether a feature is
|
| 19 |
+
categorical (i.e., not a continuous variable) to learn a machine learning model.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, name: str, value: Value, is_categorical: bool = False) -> None:
|
| 23 |
+
self.name = name
|
| 24 |
+
self.value = value
|
| 25 |
+
self.is_categorical = is_categorical
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class AHOperation:
|
| 29 |
+
"""
|
| 30 |
+
AHOperation can be used to augment the data collected by AutoHeuristic.
|
| 31 |
+
One might for example store features like m, k, n, but also want to use
|
| 32 |
+
features like m*n, or k*n, to learn a heuristic. Instead of storing features
|
| 33 |
+
that can be created from the collected data, one can use AHOperation to
|
| 34 |
+
create new features from the collected data.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self, name: str, func: Callable[[Any], Value], is_categorical: bool = False
|
| 39 |
+
) -> None:
|
| 40 |
+
self.name = name
|
| 41 |
+
self.func = func
|
| 42 |
+
self.is_categorical = is_categorical
|
| 43 |
+
|
| 44 |
+
def apply_operation(self, data: Any) -> None:
|
| 45 |
+
data[self.name] = self.func(data)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class AHContext:
|
| 49 |
+
"""
|
| 50 |
+
This class is used to specify which information AutoHeuristic should store. For each choice, AutoHeursitic will
|
| 51 |
+
store the context and the collected feedback. The context could be something like the shape of a tensor, i.e.,
|
| 52 |
+
information that will help to learn a heuristic.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
features: list[AHFeature]
|
| 56 |
+
context_dict: dict[str, Value]
|
| 57 |
+
|
| 58 |
+
def __init__(self) -> None:
|
| 59 |
+
self.features = []
|
| 60 |
+
self.context_dict = {}
|
| 61 |
+
|
| 62 |
+
def add_feature(
|
| 63 |
+
self, name: str, value: Value, is_categorical: bool = False
|
| 64 |
+
) -> None:
|
| 65 |
+
self.features.append(AHFeature(name, value, is_categorical=is_categorical))
|
| 66 |
+
self.context_dict[name] = value
|
| 67 |
+
|
| 68 |
+
def get_numerical_and_categorical_features(self) -> tuple[list[str], list[str]]:
|
| 69 |
+
numerical_features = []
|
| 70 |
+
categorical_features = []
|
| 71 |
+
for feature in self.features:
|
| 72 |
+
if feature.is_categorical:
|
| 73 |
+
categorical_features.append(feature.name)
|
| 74 |
+
else:
|
| 75 |
+
numerical_features.append(feature.name)
|
| 76 |
+
|
| 77 |
+
return numerical_features, categorical_features
|
| 78 |
+
|
| 79 |
+
def get_feature_names_csv(self) -> str:
|
| 80 |
+
return ",".join(feature.name for feature in self.features)
|
| 81 |
+
|
| 82 |
+
def get_feature_values_csv(self) -> str:
|
| 83 |
+
return ",".join(str(feature.value) for feature in self.features)
|
| 84 |
+
|
| 85 |
+
def get_value(self, name: str) -> Value:
|
| 86 |
+
return self.context_dict[name]
|
| 87 |
+
|
| 88 |
+
def apply_operations(self, operations: list[AHOperation]) -> None:
|
| 89 |
+
for op in operations:
|
| 90 |
+
op.apply_operation(self.context_dict)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class AHMetadata:
|
| 94 |
+
def __init__(
|
| 95 |
+
self,
|
| 96 |
+
shared_memory: Any,
|
| 97 |
+
device_capa: tuple[int, int],
|
| 98 |
+
choices: list[Choice],
|
| 99 |
+
name: str,
|
| 100 |
+
) -> None:
|
| 101 |
+
# use amount of shared_memory and device_capability to identify GPU
|
| 102 |
+
# TODO(AlnisM): there might be a better way to do this
|
| 103 |
+
self.shared_memory = shared_memory
|
| 104 |
+
self.device_capa = device_capa
|
| 105 |
+
self.choices = choices
|
| 106 |
+
self.name = name
|
| 107 |
+
|
| 108 |
+
def to_dict(self) -> dict[str, Value]:
|
| 109 |
+
return {
|
| 110 |
+
"shared_memory": self.shared_memory,
|
| 111 |
+
"device_capa": self.device_capa,
|
| 112 |
+
"name": self.name,
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def get_metadata_str_from_log(log_path: str) -> str:
|
| 117 |
+
with open(log_path, newline="") as file:
|
| 118 |
+
json_string = file.readline().strip()
|
| 119 |
+
return json_string
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def check_minsize(context: AHContext, minsize: int) -> bool:
|
| 123 |
+
return (
|
| 124 |
+
context.get_value("m") >= minsize
|
| 125 |
+
and context.get_value("k") >= minsize
|
| 126 |
+
and context.get_value("n") >= minsize
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def pad_mm_precondition(metadata: AHMetadata, context: AHContext) -> bool:
|
| 131 |
+
if metadata.shared_memory == 166912 and metadata.device_capa == (8, 0):
|
| 132 |
+
# A100 precondition
|
| 133 |
+
return check_minsize(context, 512)
|
| 134 |
+
elif metadata.shared_memory == 232448 and metadata.device_capa == (9, 0):
|
| 135 |
+
# H100 precondition
|
| 136 |
+
return check_minsize(context, 768)
|
| 137 |
+
return True
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_mixedmm_precondition(metadata: AHMetadata, context: AHContext) -> bool:
|
| 141 |
+
m = context.get_value("m")
|
| 142 |
+
k = context.get_value("k")
|
| 143 |
+
n = context.get_value("n")
|
| 144 |
+
if m > 128 or k < 1024 or n < 1024:
|
| 145 |
+
return False
|
| 146 |
+
mat1_iscontig = context.get_value("mat1_iscontig")
|
| 147 |
+
mat2_iscontig = context.get_value("mat2_iscontig")
|
| 148 |
+
return mat1_iscontig and not mat2_iscontig
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def get_mult_dims_ops() -> list[AHOperation]:
|
| 152 |
+
m_times_k_op = AHOperation("m*k", lambda data: data["m"] * data["k"])
|
| 153 |
+
m_times_n_op = AHOperation("m*n", lambda data: data["m"] * data["n"])
|
| 154 |
+
k_times_n_op = AHOperation("k*n", lambda data: data["k"] * data["n"])
|
| 155 |
+
return [m_times_k_op, m_times_n_op, k_times_n_op]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def get_arith_intensity(data: Any) -> float:
|
| 159 |
+
m = data["m"]
|
| 160 |
+
k = data["k"]
|
| 161 |
+
n = data["n"]
|
| 162 |
+
if m == 0 or k == 0 or n == 0:
|
| 163 |
+
return 0.0
|
| 164 |
+
return m * k * n / (m * k + k * n + m * n)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def pad_mm_operations() -> list[AHOperation]:
|
| 168 |
+
mult_dims_ops = get_mult_dims_ops()
|
| 169 |
+
k_div_m_times_n_op = AHOperation(
|
| 170 |
+
"k/(m*n)", lambda data: data["k"] / (data["m"] * data["n"])
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def bfloat_perf_hit(data: Any) -> bool:
|
| 174 |
+
m = data["m"]
|
| 175 |
+
k = data["k"]
|
| 176 |
+
n = data["n"]
|
| 177 |
+
is_bfloat = str(data["mat1_dtype"]) == "torch.bfloat16"
|
| 178 |
+
return k > (m * 1024) and k > (n * 1024) and is_bfloat
|
| 179 |
+
|
| 180 |
+
bfloat_perf_hit_op = AHOperation(
|
| 181 |
+
"bfloat_perf_hit", bfloat_perf_hit, is_categorical=True
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
arith_intensity_op = AHOperation("arith_intensity", get_arith_intensity)
|
| 185 |
+
dims_need_padding_ops = get_dims_need_padding_ops()
|
| 186 |
+
dims_multiple_ops = get_dims_multiple_ops()
|
| 187 |
+
is_contig_ops = get_is_contig_ops()
|
| 188 |
+
|
| 189 |
+
ah_operations = mult_dims_ops + [
|
| 190 |
+
k_div_m_times_n_op,
|
| 191 |
+
bfloat_perf_hit_op,
|
| 192 |
+
arith_intensity_op,
|
| 193 |
+
]
|
| 194 |
+
ah_operations.extend(dims_need_padding_ops)
|
| 195 |
+
ah_operations.extend(dims_multiple_ops)
|
| 196 |
+
ah_operations.extend(is_contig_ops)
|
| 197 |
+
return ah_operations
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def between_op(data: Any, dim: str, lower: int, upper: int) -> bool:
|
| 201 |
+
return data[dim] >= lower and data[dim] <= upper
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def between_ops() -> list[AHOperation]:
|
| 205 |
+
dims = ["m", "k", "n"]
|
| 206 |
+
limits = [(1, 16), (17, 32), (33, 64), (65, 128), (129, 256)]
|
| 207 |
+
ah_operations = []
|
| 208 |
+
for dim in dims:
|
| 209 |
+
for lower, upper in limits:
|
| 210 |
+
between_op_fn = functools.partial(
|
| 211 |
+
between_op, dim=dim, lower=lower, upper=upper
|
| 212 |
+
)
|
| 213 |
+
# using 'LEQ' instead of '<=' because '<=' cannot be exported to dot
|
| 214 |
+
between_op_name = f"{lower}LEQ{dim}LEQ{upper}"
|
| 215 |
+
ah_operations.append(
|
| 216 |
+
AHOperation(between_op_name, between_op_fn, is_categorical=True)
|
| 217 |
+
)
|
| 218 |
+
return ah_operations
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def pow2_op(data: Any, dim: str, exponent: int) -> bool:
|
| 222 |
+
return data[dim] == 2**exponent
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def mm_operations() -> list[AHOperation]:
|
| 226 |
+
mult_dims_ops = get_mult_dims_ops()
|
| 227 |
+
arith_intensity_op = AHOperation("arith_intensity", get_arith_intensity)
|
| 228 |
+
return mult_dims_ops + [arith_intensity_op]
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def mixed_mm_operations() -> list[AHOperation]:
|
| 232 |
+
return mm_operations() + between_ops()
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def is_multiple(data: Any, dim: str, mult: int) -> bool:
|
| 236 |
+
return data[dim] % mult == 0
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def get_dims_multiple_ops() -> list[AHOperation]:
|
| 240 |
+
multiples = [2, 4, 8, 16, 32]
|
| 241 |
+
dims = ["m", "k", "n"]
|
| 242 |
+
dims_multiple_ops = []
|
| 243 |
+
for dim in dims:
|
| 244 |
+
for mult in multiples:
|
| 245 |
+
is_multiple_fn = functools.partial(is_multiple, dim=dim, mult=mult)
|
| 246 |
+
dims_multiple_op = AHOperation(
|
| 247 |
+
f"{dim}_multiple_{mult}", is_multiple_fn, is_categorical=True
|
| 248 |
+
)
|
| 249 |
+
dims_multiple_ops.append(dims_multiple_op)
|
| 250 |
+
return dims_multiple_ops
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def get_dims_need_padding_ops() -> list[AHOperation]:
|
| 254 |
+
def mat1_innermost_needs_padding_fn(data: Any) -> bool:
|
| 255 |
+
mat1_stride_0 = data["mat1_stride_0"]
|
| 256 |
+
mat1_stride_1 = data["mat1_stride_1"]
|
| 257 |
+
m_padded_length = data["m_padded_length"]
|
| 258 |
+
k_padded_length = data["k_padded_length"]
|
| 259 |
+
mat1_innermost_needs_padding = False
|
| 260 |
+
if mat1_stride_0 == 1 and m_padded_length != 0:
|
| 261 |
+
mat1_innermost_needs_padding = True
|
| 262 |
+
if mat1_stride_1 == 1 and k_padded_length != 0:
|
| 263 |
+
mat1_innermost_needs_padding = True
|
| 264 |
+
return mat1_innermost_needs_padding
|
| 265 |
+
|
| 266 |
+
mat1_innermost_op = AHOperation(
|
| 267 |
+
"mat1_innermost_needs_padding",
|
| 268 |
+
mat1_innermost_needs_padding_fn,
|
| 269 |
+
is_categorical=True,
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
def mat2_innermost_needs_padding_fn(data: Any) -> bool:
|
| 273 |
+
mat2_stride_0 = data["mat2_stride_0"]
|
| 274 |
+
mat2_stride_1 = data["mat2_stride_1"]
|
| 275 |
+
k_padded_length = data["k_padded_length"]
|
| 276 |
+
n_padded_length = data["n_padded_length"]
|
| 277 |
+
mat2_innermost_needs_padding = False
|
| 278 |
+
if mat2_stride_0 == 1 and k_padded_length != 0:
|
| 279 |
+
mat2_innermost_needs_padding = True
|
| 280 |
+
if mat2_stride_1 == 1 and n_padded_length != 0:
|
| 281 |
+
mat2_innermost_needs_padding = True
|
| 282 |
+
return mat2_innermost_needs_padding
|
| 283 |
+
|
| 284 |
+
mat2_innermost_op = AHOperation(
|
| 285 |
+
"mat2_innermost_needs_padding",
|
| 286 |
+
mat2_innermost_needs_padding_fn,
|
| 287 |
+
is_categorical=True,
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
def num_dims_needs_padding_fn(data: Any) -> int:
|
| 291 |
+
m_padded_length = data["m_padded_length"]
|
| 292 |
+
k_padded_length = data["k_padded_length"]
|
| 293 |
+
n_padded_length = data["n_padded_length"]
|
| 294 |
+
num_dims_needs_padding = 0
|
| 295 |
+
if m_padded_length != 0:
|
| 296 |
+
num_dims_needs_padding += 1
|
| 297 |
+
if k_padded_length != 0:
|
| 298 |
+
num_dims_needs_padding += 1
|
| 299 |
+
if n_padded_length != 0:
|
| 300 |
+
num_dims_needs_padding += 1
|
| 301 |
+
return num_dims_needs_padding
|
| 302 |
+
|
| 303 |
+
num_dims_op = AHOperation("num_dims_needs_padding", num_dims_needs_padding_fn)
|
| 304 |
+
return [mat1_innermost_op, mat2_innermost_op, num_dims_op]
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def get_is_contig_ops() -> list[AHOperation]:
|
| 308 |
+
def mat1_is_contig_fn(data: Any) -> bool:
|
| 309 |
+
stride_0 = data["mat1_stride_0"]
|
| 310 |
+
stride_1 = data["mat1_stride_1"]
|
| 311 |
+
k = data["k"]
|
| 312 |
+
return stride_0 == k and stride_1 == 1
|
| 313 |
+
|
| 314 |
+
mat1_is_contig_op = AHOperation(
|
| 315 |
+
"mat1_iscontig", mat1_is_contig_fn, is_categorical=True
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
def mat2_is_contig_fn(data: Any) -> bool:
|
| 319 |
+
stride_0 = data["mat2_stride_0"]
|
| 320 |
+
stride_1 = data["mat2_stride_1"]
|
| 321 |
+
n = data["n"]
|
| 322 |
+
return stride_0 == n and stride_1 == 1
|
| 323 |
+
|
| 324 |
+
mat2_is_contig_op = AHOperation(
|
| 325 |
+
"mat2_iscontig", mat2_is_contig_fn, is_categorical=True
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
return [mat1_is_contig_op, mat2_is_contig_op]
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def context_add_strides(context: AHContext, name: str, stride: tuple[int, ...]) -> None:
|
| 332 |
+
for i, s in enumerate(stride):
|
| 333 |
+
context.add_feature(f"{name}_stride_{i}", s)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def context_add_using_tf32(context: AHContext, dtype: torch.dtype) -> None:
|
| 337 |
+
using_tf32 = "not_float_32"
|
| 338 |
+
if dtype == torch.float32:
|
| 339 |
+
using_tf32 = torch.backends.cuda.matmul.allow_tf32
|
| 340 |
+
context.add_feature("using_tf32", using_tf32, is_categorical=True)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import importlib
|
| 2 |
+
import inspect
|
| 3 |
+
import pkgutil
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
|
| 7 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import (
|
| 8 |
+
AHContext,
|
| 9 |
+
AHMetadata,
|
| 10 |
+
Choice,
|
| 11 |
+
)
|
| 12 |
+
from torch._inductor.autoheuristic.learnedheuristic_interface import LearnedHeuristic
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def find_and_instantiate_subclasses(
|
| 16 |
+
package_name: str, base_class: Any
|
| 17 |
+
) -> list[LearnedHeuristic]:
|
| 18 |
+
instances = []
|
| 19 |
+
|
| 20 |
+
package = importlib.import_module(package_name)
|
| 21 |
+
for _, module_name, _ in pkgutil.walk_packages(
|
| 22 |
+
package.__path__, package.__name__ + "."
|
| 23 |
+
):
|
| 24 |
+
try:
|
| 25 |
+
module_basename = module_name.split(".")[-1]
|
| 26 |
+
if not module_basename.startswith("_"):
|
| 27 |
+
# learned heuristics start with an underscore
|
| 28 |
+
continue
|
| 29 |
+
module = importlib.import_module(module_name)
|
| 30 |
+
|
| 31 |
+
# look for classes that are subclasses of base_class
|
| 32 |
+
for _name, obj in inspect.getmembers(module):
|
| 33 |
+
if (
|
| 34 |
+
inspect.isclass(obj)
|
| 35 |
+
and issubclass(obj, base_class)
|
| 36 |
+
and obj != base_class
|
| 37 |
+
):
|
| 38 |
+
instance = obj()
|
| 39 |
+
instances.append(instance)
|
| 40 |
+
except Exception as e:
|
| 41 |
+
print(f"Error processing module {module_name}: {e}")
|
| 42 |
+
|
| 43 |
+
return instances
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class LearnedHeuristicController:
|
| 47 |
+
"""
|
| 48 |
+
Class that finds and instantiates all learned heuristics. It also provides
|
| 49 |
+
a way to get the decision of a learned heuristic.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
existing_heuristics: dict[str, list[LearnedHeuristic]] = defaultdict(list)
|
| 53 |
+
"""
|
| 54 |
+
A dictionary that stores all the learned heuristics for each optimization.
|
| 55 |
+
The key is the optimization name, and the value is a list of LearnedHeuristic objects.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
heuristics_initialized: bool = False
|
| 59 |
+
"""
|
| 60 |
+
A flag that indicates whether the learned heuristics have been initialized.
|
| 61 |
+
Set to true when the get_decision() function is called for the first time.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
metadata: AHMetadata,
|
| 67 |
+
context: AHContext,
|
| 68 |
+
) -> None:
|
| 69 |
+
self.metadata = metadata
|
| 70 |
+
self.context = context
|
| 71 |
+
|
| 72 |
+
def get_heuristics(self, name: str) -> list[LearnedHeuristic]:
|
| 73 |
+
"""
|
| 74 |
+
Returns a list of learned heuristics for the given optimization name.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
if not LearnedHeuristicController.heuristics_initialized:
|
| 78 |
+
# learned heuristics are generated into the following package
|
| 79 |
+
learned_heuristics_package = "torch._inductor.autoheuristic.artifacts"
|
| 80 |
+
|
| 81 |
+
# learned heuristics have to be of type LearnedHeuristic
|
| 82 |
+
base_class = LearnedHeuristic
|
| 83 |
+
found_heuristics = find_and_instantiate_subclasses(
|
| 84 |
+
learned_heuristics_package, base_class
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
for learned_heuristic in found_heuristics:
|
| 88 |
+
opt_name = learned_heuristic.get_name()
|
| 89 |
+
LearnedHeuristicController.existing_heuristics[opt_name].append(
|
| 90 |
+
learned_heuristic
|
| 91 |
+
)
|
| 92 |
+
LearnedHeuristicController.heuristics_initialized = True
|
| 93 |
+
|
| 94 |
+
return LearnedHeuristicController.existing_heuristics[name]
|
| 95 |
+
|
| 96 |
+
def get_decision(self) -> Optional[Choice]:
|
| 97 |
+
"""
|
| 98 |
+
Returns the decision made by the learned heuristic or None if no heuristic was found or the heuristic is unsure
|
| 99 |
+
which choice to make.
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
heuristics = self.get_heuristics(self.metadata.name)
|
| 103 |
+
for heuristic in heuristics:
|
| 104 |
+
if heuristic.check_precondition(self.metadata, self.context):
|
| 105 |
+
return heuristic.get_decision(self.context, self.metadata.choices)
|
| 106 |
+
return None
|
| 107 |
+
|
| 108 |
+
def get_decisions_ranked(self, top_k: int) -> Optional[list[Choice]]:
|
| 109 |
+
heuristics = self.get_heuristics(self.metadata.name)
|
| 110 |
+
for heuristic in heuristics:
|
| 111 |
+
if heuristic.check_precondition(self.metadata, self.context):
|
| 112 |
+
choices = heuristic.get_decisions_ranked(self.context)
|
| 113 |
+
if choices is None:
|
| 114 |
+
return None
|
| 115 |
+
avail_choices = [
|
| 116 |
+
choice for choice in choices if choice in self.metadata.choices
|
| 117 |
+
]
|
| 118 |
+
return avail_choices[:top_k]
|
| 119 |
+
return None
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import operator
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from torch._inductor.autoheuristic.autoheuristic_utils import (
|
| 5 |
+
AHContext,
|
| 6 |
+
AHMetadata,
|
| 7 |
+
Choice,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class LearnedHeuristic:
|
| 12 |
+
"""
|
| 13 |
+
LearnedHeuristic is a base class for all learned heuristics.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self) -> None:
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
def check_precondition(
|
| 20 |
+
self,
|
| 21 |
+
metadata: AHMetadata,
|
| 22 |
+
context: AHContext,
|
| 23 |
+
) -> bool:
|
| 24 |
+
return True
|
| 25 |
+
|
| 26 |
+
def get_decision(
|
| 27 |
+
self, context: AHContext, choices: list[Choice]
|
| 28 |
+
) -> Optional[Choice]:
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
def get_confidence_threshold(self) -> float:
|
| 32 |
+
return 1.0
|
| 33 |
+
|
| 34 |
+
def get_name(self) -> str:
|
| 35 |
+
return ""
|
| 36 |
+
|
| 37 |
+
def get_decisions_ranked(self, context: AHContext) -> Optional[list[str]]:
|
| 38 |
+
return None
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class LearnedHeuristicRegression(LearnedHeuristic):
|
| 42 |
+
def get_feedback(self, context: AHContext, choice: Choice) -> float:
|
| 43 |
+
return 1.0
|
| 44 |
+
|
| 45 |
+
def get_decision(
|
| 46 |
+
self, context: AHContext, choices: list[Choice]
|
| 47 |
+
) -> Optional[Choice]:
|
| 48 |
+
choice2feedback = {}
|
| 49 |
+
for choice in choices:
|
| 50 |
+
predicted_feedback = self.get_feedback(context, choice)
|
| 51 |
+
choice2feedback[choice] = predicted_feedback
|
| 52 |
+
sorted_choices_feedback = sorted(
|
| 53 |
+
choice2feedback.items(), key=operator.itemgetter(1)
|
| 54 |
+
)
|
| 55 |
+
highest_feedback = sorted_choices_feedback[-1][1]
|
| 56 |
+
second_highest_feedback = sorted_choices_feedback[-2][1]
|
| 57 |
+
if highest_feedback / second_highest_feedback > self.get_confidence_threshold():
|
| 58 |
+
return sorted_choices_feedback[-1][0]
|
| 59 |
+
# We are not sure which choice is the best one
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class LearnedHeuristicDecision(LearnedHeuristic):
|
| 64 |
+
def get_choice(self, idx: int) -> Optional[str]:
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
def get_decision(
|
| 68 |
+
self, context: AHContext, choices: list[Choice]
|
| 69 |
+
) -> Optional[Choice]:
|
| 70 |
+
best_choices = self.get_best_choices(context)
|
| 71 |
+
if not best_choices:
|
| 72 |
+
return None
|
| 73 |
+
(best_choice_proba, best_choice_idx) = best_choices[0]
|
| 74 |
+
if best_choice_proba <= self.get_confidence_threshold():
|
| 75 |
+
return None
|
| 76 |
+
return self.get_choice(best_choice_idx)
|
| 77 |
+
|
| 78 |
+
def get_decisions_ranked(self, context: AHContext) -> Optional[list[str]]:
|
| 79 |
+
feedback_idx_list = self.get_best_choices(context)
|
| 80 |
+
if feedback_idx_list is None:
|
| 81 |
+
return None
|
| 82 |
+
choices = [
|
| 83 |
+
self.get_choice(feedback_idx[1]) for feedback_idx in feedback_idx_list
|
| 84 |
+
]
|
| 85 |
+
choices = [choice for choice in choices if choice is not None]
|
| 86 |
+
return choices
|
| 87 |
+
|
| 88 |
+
def get_best_choices(self, context: AHContext) -> Optional[list[tuple[float, int]]]:
|
| 89 |
+
return []
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# It is not a good idea to directly apply hipify_torch to codegen, which will be vulnerable to cases like:
|
| 7 |
+
# "...
|
| 8 |
+
# from ..codecache import CudaKernelParamCache
|
| 9 |
+
# ..."
|
| 10 |
+
# In such cases, we do not need to hipify_torch the original class/file name in codegen/codecache
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def maybe_hipify_code_wrapper(source_codes: str, force_hipify: bool = False) -> str:
|
| 14 |
+
if torch.version.hip is None and not force_hipify:
|
| 15 |
+
return source_codes
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from torch.utils.hipify.hipify_python import PYTORCH_MAP, PYTORCH_TRIE
|
| 19 |
+
except ImportError:
|
| 20 |
+
# hipify not available for non-AMD builds
|
| 21 |
+
return source_codes
|
| 22 |
+
|
| 23 |
+
def c2_repl(m: re.Match[str]) -> object:
|
| 24 |
+
return PYTORCH_MAP[m.group(0)]
|
| 25 |
+
|
| 26 |
+
# We need to redefine RE_PYTORCH_PREPROCESSOR here since in hipify_torch,
|
| 27 |
+
# it will apply positive lookbehind (?<=\W) to the pattern to avoid matching
|
| 28 |
+
# keyword at the beginning of code line. However, this can happen in codegen,
|
| 29 |
+
# which will cause the pattern to not match.
|
| 30 |
+
|
| 31 |
+
# Note that lookahead (?=\W) is still needed to keep hipification idomponent, for example
|
| 32 |
+
# we need to skip replacing "getStreamFromExternal" in "getStreamFromExternalMasqueradingAsCUDA"
|
| 33 |
+
RE_PYTORCH_PREPROCESSOR = re.compile(rf"({PYTORCH_TRIE.export_to_regex()})(?=\W)")
|
| 34 |
+
|
| 35 |
+
source_codes = RE_PYTORCH_PREPROCESSOR.sub(c2_repl, source_codes) # type: ignore[arg-type]
|
| 36 |
+
return source_codes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Definition of AOTI runtime interface functions
|
| 2 |
+
|
| 3 |
+
#include <torch/csrc/inductor/aoti_runtime/interface.h>
|
| 4 |
+
#include <torch/csrc/inductor/aoti_runtime/model_container.h>
|
| 5 |
+
|
| 6 |
+
#include <iostream>
|
| 7 |
+
#include <vector>
|
| 8 |
+
|
| 9 |
+
#define CONVERT_EXCEPTION_TO_ERROR_CODE(...) \
|
| 10 |
+
try { \
|
| 11 |
+
__VA_ARGS__ \
|
| 12 |
+
} catch (const std::exception& e) { \
|
| 13 |
+
std::cerr << "Error: " << e.what() << '\n'; \
|
| 14 |
+
return AOTI_RUNTIME_FAILURE; \
|
| 15 |
+
} catch (...) { \
|
| 16 |
+
std::cerr << "Unknown exception occurred.\n"; \
|
| 17 |
+
return AOTI_RUNTIME_FAILURE; \
|
| 18 |
+
} \
|
| 19 |
+
return AOTI_RUNTIME_SUCCESS;
|
| 20 |
+
|
| 21 |
+
#define AOTI_VECTOR_SIZE_CHECK(actual_size, expected_size, name) \
|
| 22 |
+
do { \
|
| 23 |
+
AOTI_RUNTIME_CHECK( \
|
| 24 |
+
actual_size == expected_size, \
|
| 25 |
+
"expected " + std::string(name) + " vector size to be " + \
|
| 26 |
+
std::to_string(expected_size) + ", but got " + \
|
| 27 |
+
std::to_string(actual_size)); \
|
| 28 |
+
} while (0)
|
| 29 |
+
|
| 30 |
+
// AOTInductor uses at::addmm_out, which doesn't supports
|
| 31 |
+
// arguments that requires gradient. For this reason, we
|
| 32 |
+
// enforce no_grad context for run APIs.
|
| 33 |
+
//
|
| 34 |
+
// A RAII, thread local (!) guard that enables or disables grad mode upon
|
| 35 |
+
// construction, and sets it back to the original value upon destruction.
|
| 36 |
+
struct AOTINoGradGuard {
|
| 37 |
+
AOTINoGradGuard() {
|
| 38 |
+
aoti_torch_grad_mode_set_enabled(false);
|
| 39 |
+
}
|
| 40 |
+
AOTINoGradGuard(const AOTINoGradGuard&) = delete;
|
| 41 |
+
AOTINoGradGuard(AOTINoGradGuard&&) noexcept = delete;
|
| 42 |
+
~AOTINoGradGuard() {
|
| 43 |
+
aoti_torch_grad_mode_set_enabled(prev_mode);
|
| 44 |
+
}
|
| 45 |
+
AOTINoGradGuard& operator=(const AOTINoGradGuard&) = delete;
|
| 46 |
+
AOTINoGradGuard& operator=(AOTINoGradGuard&&) noexcept = delete;
|
| 47 |
+
bool prev_mode{aoti_torch_grad_mode_is_enabled()};
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
extern "C" {
|
| 51 |
+
|
| 52 |
+
AOTIRuntimeError AOTInductorModelContainerCreate(
|
| 53 |
+
AOTInductorModelContainerHandle* container_handle,
|
| 54 |
+
size_t num_models,
|
| 55 |
+
bool is_cpu,
|
| 56 |
+
const char* cubin_dir) {
|
| 57 |
+
return AOTInductorModelContainerCreateWithDevice(
|
| 58 |
+
container_handle,
|
| 59 |
+
num_models,
|
| 60 |
+
is_cpu ? "cpu" : "cuda",
|
| 61 |
+
cubin_dir);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
AOTIRuntimeError AOTInductorModelContainerCreateWithDevice(
|
| 65 |
+
AOTInductorModelContainerHandle* container_handle,
|
| 66 |
+
size_t num_models,
|
| 67 |
+
const char* device_str,
|
| 68 |
+
const char* cubin_dir) {
|
| 69 |
+
|
| 70 |
+
if (num_models == 0) {
|
| 71 |
+
std::cerr << "Error: num_models must be positive, but got 0\n";
|
| 72 |
+
return AOTI_RUNTIME_FAILURE;
|
| 73 |
+
}
|
| 74 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 75 |
+
std::optional<std::string> cubin_dir_opt;
|
| 76 |
+
if (cubin_dir != nullptr) {
|
| 77 |
+
cubin_dir_opt.emplace(cubin_dir);
|
| 78 |
+
}
|
| 79 |
+
auto* container = new torch::aot_inductor::AOTInductorModelContainer(
|
| 80 |
+
num_models, std::string(device_str), cubin_dir_opt);
|
| 81 |
+
*container_handle =
|
| 82 |
+
reinterpret_cast<AOTInductorModelContainerHandle>(container);
|
| 83 |
+
})
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
AOTIRuntimeError AOTInductorModelContainerDelete(
|
| 88 |
+
AOTInductorModelContainerHandle container_handle) {
|
| 89 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 90 |
+
auto* container =
|
| 91 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 92 |
+
container_handle);
|
| 93 |
+
delete container;
|
| 94 |
+
});
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
AOTIRuntimeError AOTInductorModelContainerRun(
|
| 98 |
+
AOTInductorModelContainerHandle container_handle,
|
| 99 |
+
AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles
|
| 100 |
+
// are stolen; the array itself is borrowed
|
| 101 |
+
size_t num_inputs,
|
| 102 |
+
AtenTensorHandle*
|
| 103 |
+
output_handles, // array for writing output AtenTensorHandle; handles
|
| 104 |
+
// will be stolen by the caller; the array itself is
|
| 105 |
+
// borrowed
|
| 106 |
+
size_t num_outputs,
|
| 107 |
+
AOTInductorStreamHandle stream_handle,
|
| 108 |
+
AOTIProxyExecutorHandle proxy_executor_handle) {
|
| 109 |
+
auto* container =
|
| 110 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 111 |
+
container_handle);
|
| 112 |
+
AOTI_VECTOR_SIZE_CHECK(num_inputs, container->num_inputs(), "inputs");
|
| 113 |
+
AOTI_VECTOR_SIZE_CHECK(num_outputs, container->num_outputs(), "outputs");
|
| 114 |
+
|
| 115 |
+
auto stream =
|
| 116 |
+
reinterpret_cast<torch::aot_inductor::DeviceStreamType>(stream_handle);
|
| 117 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 118 |
+
AOTINoGradGuard guard;
|
| 119 |
+
container->run(
|
| 120 |
+
input_handles, output_handles, stream, proxy_executor_handle);
|
| 121 |
+
})
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
AOTIRuntimeError AOTInductorModelContainerRunSingleThreaded(
|
| 125 |
+
AOTInductorModelContainerHandle container_handle,
|
| 126 |
+
AtenTensorHandle* input_handles, // array of input AtenTensorHandle; handles
|
| 127 |
+
// are stolen; the array itself is borrowed
|
| 128 |
+
size_t num_inputs,
|
| 129 |
+
AtenTensorHandle*
|
| 130 |
+
output_handles, // array for writing output AtenTensorHandle; handles
|
| 131 |
+
// will be stolen by the caller; the array itself is
|
| 132 |
+
// borrowed
|
| 133 |
+
size_t num_outputs,
|
| 134 |
+
AOTInductorStreamHandle stream_handle,
|
| 135 |
+
AOTIProxyExecutorHandle proxy_executor_handle) {
|
| 136 |
+
auto* container =
|
| 137 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 138 |
+
container_handle);
|
| 139 |
+
AOTI_VECTOR_SIZE_CHECK(num_inputs, container->num_inputs(), "inputs");
|
| 140 |
+
AOTI_VECTOR_SIZE_CHECK(num_outputs, container->num_outputs(), "outputs");
|
| 141 |
+
|
| 142 |
+
auto stream =
|
| 143 |
+
reinterpret_cast<torch::aot_inductor::DeviceStreamType>(stream_handle);
|
| 144 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 145 |
+
AOTINoGradGuard guard;
|
| 146 |
+
container->run_single_threaded(
|
| 147 |
+
input_handles, output_handles, stream, proxy_executor_handle);
|
| 148 |
+
})
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
AOTIRuntimeError AOTInductorModelContainerGetNumConstants(
|
| 152 |
+
AOTInductorModelContainerHandle container_handle,
|
| 153 |
+
size_t* num_constants) {
|
| 154 |
+
auto* container =
|
| 155 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 156 |
+
container_handle);
|
| 157 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 158 |
+
{ *num_constants = container->num_constants(); })
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
AOTIRuntimeError AOTInductorModelContainerGetConstantName(
|
| 162 |
+
AOTInductorModelContainerHandle container_handle,
|
| 163 |
+
size_t idx,
|
| 164 |
+
const char** name) {
|
| 165 |
+
auto* container =
|
| 166 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 167 |
+
container_handle);
|
| 168 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 169 |
+
{ *name = container->constant_name(idx); })
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
AOTIRuntimeError AOTInductorModelContainerGetConstantOriginalFQN(
|
| 173 |
+
AOTInductorModelContainerHandle container_handle,
|
| 174 |
+
size_t idx,
|
| 175 |
+
const char** original_fqn) {
|
| 176 |
+
auto* container =
|
| 177 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 178 |
+
container_handle);
|
| 179 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 180 |
+
{ *original_fqn = container->constant_original_fqn(idx); })
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
AOTIRuntimeError AOTInductorModelContainerGetConstantFromFolded(
|
| 184 |
+
AOTInductorModelContainerHandle container_handle,
|
| 185 |
+
size_t idx,
|
| 186 |
+
bool* from_folded) {
|
| 187 |
+
auto* container =
|
| 188 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(container_handle);
|
| 189 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({ *from_folded = container->constant_from_folded(idx); })
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
AOTIRuntimeError AOTInductorModelContainerGetConstantType(
|
| 193 |
+
AOTInductorModelContainerHandle container_handle,
|
| 194 |
+
size_t idx,
|
| 195 |
+
int32_t* type) {
|
| 196 |
+
auto* container =
|
| 197 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(container_handle);
|
| 198 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({ *type = container->constant_type(idx); })
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
AOTIRuntimeError AOTInductorModelContainerGetConstantDtype(
|
| 202 |
+
AOTInductorModelContainerHandle container_handle,
|
| 203 |
+
size_t idx,
|
| 204 |
+
int32_t* dtype) {
|
| 205 |
+
auto* container =
|
| 206 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 207 |
+
container_handle);
|
| 208 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 209 |
+
{ *dtype = container->constant_dtype(idx); })
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
AOTIRuntimeError AOTInductorModelContainerGetConstantDataSize(
|
| 213 |
+
AOTInductorModelContainerHandle container_handle,
|
| 214 |
+
size_t idx,
|
| 215 |
+
size_t* data_size) {
|
| 216 |
+
auto* container =
|
| 217 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 218 |
+
container_handle);
|
| 219 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 220 |
+
{ *data_size = container->constant_data_size(idx); })
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
AOTIRuntimeError AOTInductorModelContainerExtractConstantsMap(
|
| 224 |
+
AOTInductorModelContainerHandle container_handle,
|
| 225 |
+
AOTInductorConstantMapHandle constant_map_handle,
|
| 226 |
+
bool use_inactive) {
|
| 227 |
+
auto* container =
|
| 228 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 229 |
+
container_handle);
|
| 230 |
+
auto constants_map = reinterpret_cast<std::unordered_map<std::string, AtenTensorHandle>*>(constant_map_handle);
|
| 231 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 232 |
+
{ const auto ret = container->extract_constants_map(use_inactive);
|
| 233 |
+
for (const auto& pair: ret) {
|
| 234 |
+
constants_map->emplace(pair.first, pair.second);
|
| 235 |
+
}
|
| 236 |
+
})
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
AOTIRuntimeError AOTInductorModelContainerUpdateUserManagedConstantBuffer(
|
| 240 |
+
AOTInductorModelContainerHandle container_handle,
|
| 241 |
+
AOTInductorConstantMapHandle constant_map_handle,
|
| 242 |
+
bool use_inactive,
|
| 243 |
+
bool validate_full_update) {
|
| 244 |
+
auto* container =
|
| 245 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 246 |
+
container_handle);
|
| 247 |
+
auto input_map = reinterpret_cast<std::unordered_map<std::string, AtenTensorHandle>*>(constant_map_handle);
|
| 248 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 249 |
+
container->update_constant_buffer(
|
| 250 |
+
*input_map, use_inactive, validate_full_update, /* user_managed = */ true);
|
| 251 |
+
})
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
AOTIRuntimeError AOTInductorModelContainerUpdateUserManagedConstantBufferPairs(
|
| 255 |
+
AOTInductorModelContainerHandle container_handle,
|
| 256 |
+
const AOTInductorConstantMapEntry* pairs,
|
| 257 |
+
size_t num_pairs,
|
| 258 |
+
bool use_inactive,
|
| 259 |
+
bool validate_full_update) {
|
| 260 |
+
auto* container =
|
| 261 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(container_handle);
|
| 262 |
+
// Build a local unordered_map inside
|
| 263 |
+
std::unordered_map<std::string, AtenTensorHandle> input_map;
|
| 264 |
+
input_map.reserve(num_pairs);
|
| 265 |
+
for (size_t i = 0; i < num_pairs; ++i) {
|
| 266 |
+
input_map.emplace(pairs[i].name, pairs[i].handle);
|
| 267 |
+
}
|
| 268 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 269 |
+
container->update_constant_buffer(
|
| 270 |
+
input_map, use_inactive, validate_full_update, /*user_managed=*/true);
|
| 271 |
+
})
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
AOTIRuntimeError AOTInductorModelContainerUpdateConstantBuffer(
|
| 275 |
+
AOTInductorModelContainerHandle container_handle,
|
| 276 |
+
AOTInductorConstantMapHandle constant_map_handle,
|
| 277 |
+
bool use_inactive,
|
| 278 |
+
bool validate_full_update) {
|
| 279 |
+
auto* container =
|
| 280 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 281 |
+
container_handle);
|
| 282 |
+
auto input_map = reinterpret_cast<std::unordered_map<std::string, AtenTensorHandle>*>(constant_map_handle);
|
| 283 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 284 |
+
container->update_constant_buffer(
|
| 285 |
+
*input_map, use_inactive, validate_full_update);
|
| 286 |
+
})
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
AOTIRuntimeError AOTInductorModelContainerUpdateInactiveConstantBuffer(
|
| 290 |
+
AOTInductorModelContainerHandle container_handle,
|
| 291 |
+
AOTInductorConstantMapHandle constant_map_handle) {
|
| 292 |
+
return AOTInductorModelContainerUpdateConstantBuffer(container_handle,
|
| 293 |
+
constant_map_handle,
|
| 294 |
+
/*use_inactive*/ true,
|
| 295 |
+
/*validate_full_update*/ true);
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
AOTIRuntimeError AOTInductorModelContainerFreeInactiveConstantBuffer(
|
| 299 |
+
AOTInductorModelContainerHandle container_handle) {
|
| 300 |
+
auto* container =
|
| 301 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 302 |
+
container_handle);
|
| 303 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 304 |
+
container->free_inactive_constant_buffer();
|
| 305 |
+
})
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
AOTIRuntimeError AOTInductorModelContainerRunConstantFolding(
|
| 309 |
+
AOTInductorModelContainerHandle container_handle,
|
| 310 |
+
bool use_inactive,
|
| 311 |
+
AOTInductorStreamHandle stream_handle,
|
| 312 |
+
AOTIProxyExecutorHandle proxy_executor_handle) {
|
| 313 |
+
auto* container =
|
| 314 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 315 |
+
container_handle);
|
| 316 |
+
auto stream =
|
| 317 |
+
reinterpret_cast<torch::aot_inductor::DeviceStreamType>(stream_handle);
|
| 318 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 319 |
+
AOTINoGradGuard guard;
|
| 320 |
+
container->run_const_fold(use_inactive, stream, proxy_executor_handle);
|
| 321 |
+
})
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
AOTIRuntimeError AOTInductorModelContainerSwapConstantBuffer(
|
| 325 |
+
AOTInductorModelContainerHandle container_handle) {
|
| 326 |
+
auto* container =
|
| 327 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 328 |
+
container_handle);
|
| 329 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 330 |
+
container->swap_constant_buffer();
|
| 331 |
+
})
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
AOTIRuntimeError AOTInductorModelContainerGetNumInputs(
|
| 335 |
+
AOTInductorModelContainerHandle container_handle,
|
| 336 |
+
size_t* ret_num_inputs) {
|
| 337 |
+
auto* container =
|
| 338 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 339 |
+
container_handle);
|
| 340 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 341 |
+
{ *ret_num_inputs = container->num_inputs(); })
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
AOTIRuntimeError AOTInductorModelContainerGetInputName(
|
| 345 |
+
AOTInductorModelContainerHandle container_handle,
|
| 346 |
+
size_t input_idx,
|
| 347 |
+
const char** ret_input_names) {
|
| 348 |
+
auto* container =
|
| 349 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 350 |
+
container_handle);
|
| 351 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 352 |
+
{ *ret_input_names = container->input_name(input_idx); })
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
AOTIRuntimeError AOTInductorModelContainerGetNumOutputs(
|
| 356 |
+
AOTInductorModelContainerHandle container_handle,
|
| 357 |
+
size_t* ret_num_outputs) {
|
| 358 |
+
auto* container =
|
| 359 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 360 |
+
container_handle);
|
| 361 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 362 |
+
{ *ret_num_outputs = container->num_outputs(); })
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
AOTIRuntimeError AOTInductorModelContainerGetOutputName(
|
| 366 |
+
AOTInductorModelContainerHandle container_handle,
|
| 367 |
+
size_t output_idx,
|
| 368 |
+
const char** ret_output_names) {
|
| 369 |
+
auto* container =
|
| 370 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 371 |
+
container_handle);
|
| 372 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 373 |
+
{ *ret_output_names = container->output_name(output_idx); })
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
AOTIRuntimeError AOTInductorModelContainerGetCallSpec(
|
| 377 |
+
AOTInductorModelContainerHandle container_handle,
|
| 378 |
+
const char** in_spec,
|
| 379 |
+
const char** out_spec) {
|
| 380 |
+
auto* container =
|
| 381 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 382 |
+
container_handle);
|
| 383 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 384 |
+
*in_spec = container->get_in_spec();
|
| 385 |
+
*out_spec = container->get_out_spec();
|
| 386 |
+
})
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
AOTIRuntimeError AOTInductorModelCreate(
|
| 390 |
+
AOTInductorModelHandle* model_handle,
|
| 391 |
+
AOTInductorConstantMapHandle constant_map_handle){
|
| 392 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 393 |
+
auto constant_map = std::make_shared<torch::aot_inductor::ConstantMap>();
|
| 394 |
+
auto constant_array = std::make_shared<std::vector<torch::aot_inductor::ConstantHandle>>();
|
| 395 |
+
auto input_map = reinterpret_cast<std::unordered_map<std::string, AtenTensorHandle>*>(constant_map_handle);
|
| 396 |
+
|
| 397 |
+
auto model = new torch::aot_inductor::AOTInductorModel(
|
| 398 |
+
constant_map,
|
| 399 |
+
constant_array,
|
| 400 |
+
"cpu", // device_str is hardcoded, as AOTInductorModelCreate is only use for CPU models
|
| 401 |
+
""
|
| 402 |
+
);
|
| 403 |
+
|
| 404 |
+
if (input_map) {
|
| 405 |
+
for (auto const& kv : *input_map) {
|
| 406 |
+
constant_map->emplace(kv.first, kv.second);
|
| 407 |
+
}
|
| 408 |
+
} else {
|
| 409 |
+
model->load_constants();
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
*model_handle = reinterpret_cast<AOTInductorModelHandle>(model);
|
| 413 |
+
})}
|
| 414 |
+
|
| 415 |
+
AOTIRuntimeError AOTInductorModelRun(
|
| 416 |
+
AOTInductorModelHandle model_handle,
|
| 417 |
+
AtenTensorHandle* input_handles,
|
| 418 |
+
AtenTensorHandle* output_handles) {
|
| 419 |
+
auto model =
|
| 420 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModel*>(model_handle);
|
| 421 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 422 |
+
AOTINoGradGuard guard;
|
| 423 |
+
model->run_impl(
|
| 424 |
+
input_handles,
|
| 425 |
+
output_handles,
|
| 426 |
+
(torch::aot_inductor::DeviceStreamType) nullptr,
|
| 427 |
+
nullptr);
|
| 428 |
+
})
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
AOTIRuntimeError AOTInductorModelDelete(AOTInductorModelHandle model_handle){
|
| 432 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 433 |
+
auto model = reinterpret_cast<torch::aot_inductor::AOTInductorModel*>(
|
| 434 |
+
model_handle);
|
| 435 |
+
delete model;
|
| 436 |
+
})}
|
| 437 |
+
|
| 438 |
+
AOTIRuntimeError AOTInductorModelGetNumOutputs(
|
| 439 |
+
AOTInductorModelHandle model_handle,
|
| 440 |
+
size_t* ret_num_outputs) {
|
| 441 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 442 |
+
auto model = reinterpret_cast<torch::aot_inductor::AOTInductorModel*>(model_handle);
|
| 443 |
+
*ret_num_outputs = model->num_outputs();
|
| 444 |
+
})
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
AOTIRuntimeError AOTInductorModelUpdateConstantsMap(
|
| 448 |
+
AOTInductorModelHandle model_handle,
|
| 449 |
+
AOTInductorConstantMapHandle constant_map_handle) {
|
| 450 |
+
auto model =
|
| 451 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModel*>(model_handle);
|
| 452 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 453 |
+
auto constant_map = std::make_shared<torch::aot_inductor::ConstantMap>();
|
| 454 |
+
auto input_map =
|
| 455 |
+
reinterpret_cast<std::unordered_map<std::string, AtenTensorHandle>*>(
|
| 456 |
+
constant_map_handle);
|
| 457 |
+
|
| 458 |
+
for (auto const& kv : *input_map) {
|
| 459 |
+
constant_map->emplace(kv.first, kv.second);
|
| 460 |
+
}
|
| 461 |
+
model->update_constants_map(std::move(constant_map));
|
| 462 |
+
})
|
| 463 |
+
}
|
| 464 |
+
|
| 465 |
+
AOTIRuntimeError AOTInductorModelContainerGetConstantsBlobSize(
|
| 466 |
+
AOTInductorModelContainerHandle container_handle,
|
| 467 |
+
uint64_t* ret_size) {
|
| 468 |
+
auto* container =
|
| 469 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 470 |
+
container_handle);
|
| 471 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 472 |
+
{ *ret_size = container->constant_blob_size(); })
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
// Load weights from a single blob in weight_blob_ptr
|
| 477 |
+
AOTIRuntimeError AOTInductorModelUpdateConstantsFromBlob(
|
| 478 |
+
AOTInductorModelContainerHandle container_handle,
|
| 479 |
+
const uint8_t* weight_blob_ptr){
|
| 480 |
+
auto* container =
|
| 481 |
+
reinterpret_cast<torch::aot_inductor::AOTInductorModelContainer*>(
|
| 482 |
+
container_handle);
|
| 483 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE(
|
| 484 |
+
{container->update_constants_from_blob(weight_blob_ptr); })
|
| 485 |
+
}
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
} // extern "C"
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/block_analysis.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import functools
|
| 3 |
+
import textwrap
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import sympy
|
| 7 |
+
from sympy import Expr, Symbol
|
| 8 |
+
|
| 9 |
+
from torch.utils._sympy.functions import FloorDiv, ModularIndexing
|
| 10 |
+
|
| 11 |
+
from ..utils import sympy_dot, sympy_subs
|
| 12 |
+
from ..virtualized import V
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class BlockPatternMatcher:
|
| 16 |
+
"""
|
| 17 |
+
Matches block indexing expressions.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
_indexing_wild_signed_int = functools.partial(
|
| 21 |
+
sympy.Wild, properties=[lambda x: x.is_integer]
|
| 22 |
+
)
|
| 23 |
+
_indexing_wild_unsigned_int = functools.partial(
|
| 24 |
+
sympy.Wild, properties=[lambda x: x.is_integer and x.is_nonnegative]
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
@classmethod
|
| 28 |
+
def get_subexpr_involving_symbol(cls, expr: Expr, symbol: Symbol) -> Expr:
|
| 29 |
+
"""
|
| 30 |
+
Given a sympy expression, return the subexpression comprised only of terms
|
| 31 |
+
involving the specified symbol.
|
| 32 |
+
|
| 33 |
+
For example, if `expr` is `x * 5 + x ** 2 + y * 2 + 5`, and `symbol` is `x`,
|
| 34 |
+
this returns `x * 5 + x ** 2`.
|
| 35 |
+
"""
|
| 36 |
+
expr = cls._preprocess(expr)
|
| 37 |
+
return sympy.S.Zero + sum(
|
| 38 |
+
term for term in sympy.Add.make_args(expr) if symbol in term.free_symbols
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
@staticmethod
|
| 42 |
+
def get_slice_numels(dims: list[Expr]) -> list[Expr]:
|
| 43 |
+
"""
|
| 44 |
+
Compute the cumulative size of each dimension's slice.
|
| 45 |
+
This proceeds from the last dim up to the second.
|
| 46 |
+
"""
|
| 47 |
+
numels = collections.deque([sympy.S.One])
|
| 48 |
+
for dim in dims[:0:-1]:
|
| 49 |
+
numel = dim * numels[0]
|
| 50 |
+
numels.appendleft(numel)
|
| 51 |
+
return [*numels]
|
| 52 |
+
|
| 53 |
+
@staticmethod
|
| 54 |
+
def _preprocess(expr: Expr) -> Expr:
|
| 55 |
+
# Remove any Identity nodes, e.g. expand x + (5 * y) to x + 5 * y.
|
| 56 |
+
return expr.expand(identity=True)
|
| 57 |
+
|
| 58 |
+
@classmethod
|
| 59 |
+
def match_mod_div_block_expr(
|
| 60 |
+
cls,
|
| 61 |
+
index: Expr,
|
| 62 |
+
index_var: Symbol,
|
| 63 |
+
numel: Expr,
|
| 64 |
+
num_dims: int,
|
| 65 |
+
) -> Optional[tuple[list[Expr], list[Expr], list[Expr]]]:
|
| 66 |
+
"""
|
| 67 |
+
Matches modular indexing expressions, converting them to implied block dimensions and strides.
|
| 68 |
+
See triton.py for more information.
|
| 69 |
+
"""
|
| 70 |
+
index = cls._preprocess(index)
|
| 71 |
+
|
| 72 |
+
# Pattern match to find the strides and offset.
|
| 73 |
+
wild_unsigned_int = functools.partial(
|
| 74 |
+
cls._indexing_wild_unsigned_int, exclude=[index_var]
|
| 75 |
+
)
|
| 76 |
+
wild_signed_int = functools.partial(
|
| 77 |
+
cls._indexing_wild_signed_int, exclude=[index_var]
|
| 78 |
+
)
|
| 79 |
+
dims: list[Expr] = [
|
| 80 |
+
wild_unsigned_int(f"dim_mod{idx}") for idx in range(num_dims)
|
| 81 |
+
]
|
| 82 |
+
strides: list[Expr] = [
|
| 83 |
+
wild_signed_int(f"stride_mod{idx}") for idx in range(num_dims)
|
| 84 |
+
]
|
| 85 |
+
|
| 86 |
+
# The first dimension's index is computed by division.
|
| 87 |
+
# The remaining are computed by modulo.
|
| 88 |
+
slice_numels = cls.get_slice_numels(dims[:num_dims])
|
| 89 |
+
block_index_exprs = [FloorDiv(index_var, slice_numels[0])] + [
|
| 90 |
+
ModularIndexing(index_var, numel, dim)
|
| 91 |
+
for dim, numel in zip(dims[1:], slice_numels[1:])
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
# Calculate a linear index from block indices.
|
| 95 |
+
match_expr = sympy_dot(strides, block_index_exprs)
|
| 96 |
+
|
| 97 |
+
# Heuristic: if the number of dimensions is high, check that the minimum requirements
|
| 98 |
+
# are met before attempting an expensive full match. see triton.py:match_mod_div_block
|
| 99 |
+
# for more details. In short, here we check that each subexpression in sympy.Add contains
|
| 100 |
+
# only FloorDiv or ModularIndexing expressions.
|
| 101 |
+
if num_dims >= 5:
|
| 102 |
+
stride = sympy.symbols("stride", cls=wild_signed_int)
|
| 103 |
+
denom, other = sympy.symbols("denominator other", cls=wild_unsigned_int)
|
| 104 |
+
mod_div_pattern = stride * ModularIndexing(index_var, denom, other)
|
| 105 |
+
floor_div_pattern = stride * FloorDiv(index_var, denom)
|
| 106 |
+
first_dim_floor_div_matched = False
|
| 107 |
+
match_failed = False
|
| 108 |
+
for arg in sympy.Add.make_args(index):
|
| 109 |
+
if arg.match(floor_div_pattern):
|
| 110 |
+
# There should only be a single FloorDiv(index, denom) expression
|
| 111 |
+
# corresponding to the first dimension
|
| 112 |
+
if first_dim_floor_div_matched:
|
| 113 |
+
match_failed = True
|
| 114 |
+
break
|
| 115 |
+
first_dim_floor_div_matched = True
|
| 116 |
+
elif arg.match(mod_div_pattern):
|
| 117 |
+
continue
|
| 118 |
+
else:
|
| 119 |
+
match_failed = True
|
| 120 |
+
break
|
| 121 |
+
|
| 122 |
+
if match_failed:
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
# Pattern match.
|
| 126 |
+
match = index.match(match_expr)
|
| 127 |
+
if match is None:
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
# Provide default values for unmatched dims and strides.
|
| 131 |
+
for dim in dims[1:]:
|
| 132 |
+
if dim not in match:
|
| 133 |
+
match[dim] = sympy.S.One
|
| 134 |
+
for stride in strides[1:]:
|
| 135 |
+
if stride not in match:
|
| 136 |
+
match[stride] = sympy.S.Zero
|
| 137 |
+
|
| 138 |
+
sizevars = V.graph.sizevars
|
| 139 |
+
|
| 140 |
+
def get_match(expr: Expr) -> Expr:
|
| 141 |
+
return sizevars.lookup_precomputed_size(match[expr])
|
| 142 |
+
|
| 143 |
+
# Replace wildcards with matched expressions.
|
| 144 |
+
dims = [dims[0]] + [get_match(dim) for dim in dims[1:]]
|
| 145 |
+
strides = [get_match(stride) for stride in strides]
|
| 146 |
+
slice_numels = cls.get_slice_numels(dims)
|
| 147 |
+
block_index_exprs = [sympy_subs(expr, match) for expr in block_index_exprs]
|
| 148 |
+
|
| 149 |
+
# The leading dimension is not directly matched in our expression.
|
| 150 |
+
# We solve for it by dividing the range tree numel by the product of
|
| 151 |
+
# all other dimensions. We quit if they are not known to be divisible.
|
| 152 |
+
assert dims[0] not in match, "Expected not to match the leading dimension!"
|
| 153 |
+
if not sizevars.statically_known_multiple_of(numel, slice_numels[0]):
|
| 154 |
+
return None
|
| 155 |
+
dims[0] = numel / slice_numels[0]
|
| 156 |
+
|
| 157 |
+
# Sanity check that we can recover the index from the matched subexpressions.
|
| 158 |
+
matched_index = sympy_dot(strides, block_index_exprs)
|
| 159 |
+
assert sizevars.statically_known_equals(
|
| 160 |
+
# New precomputed replacements may be generated when the `get_match` function
|
| 161 |
+
# above is called, but the `index` that is being matched has not been updated.
|
| 162 |
+
# So remove them when checking for equivalence e.g. if ps0=3*s0 and
|
| 163 |
+
# index=3*s0*expr, matched_index=ps0*expr, then index == matched_index
|
| 164 |
+
sizevars.remove_precomputed_replacements(matched_index),
|
| 165 |
+
sizevars.remove_precomputed_replacements(index),
|
| 166 |
+
), textwrap.dedent(
|
| 167 |
+
f"""
|
| 168 |
+
Invalid match!
|
| 169 |
+
Index: {index}
|
| 170 |
+
Matched expression: {matched_index}
|
| 171 |
+
"""
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
return dims, strides, block_index_exprs
|
| 175 |
+
|
| 176 |
+
@classmethod
|
| 177 |
+
def match_affine_block_expr(
|
| 178 |
+
cls,
|
| 179 |
+
index: Expr,
|
| 180 |
+
index_var: Symbol,
|
| 181 |
+
) -> Optional[Expr]:
|
| 182 |
+
"""
|
| 183 |
+
Matches simple expressions of the form stride * index, returning the
|
| 184 |
+
stride.
|
| 185 |
+
"""
|
| 186 |
+
index = cls._preprocess(index)
|
| 187 |
+
stride = cls._indexing_wild_signed_int(name="stride", exclude=[index_var])
|
| 188 |
+
m = index.match(index_var * stride)
|
| 189 |
+
if m is None:
|
| 190 |
+
return None
|
| 191 |
+
|
| 192 |
+
return m[stride]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/common.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/codegen/cpp.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/codegen/cpp_bmm_template.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
import itertools
|
| 4 |
+
from collections.abc import Callable
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
|
| 8 |
+
import sympy
|
| 9 |
+
|
| 10 |
+
from .. import ir
|
| 11 |
+
from ..select_algorithm import PartialRender
|
| 12 |
+
from ..virtualized import V
|
| 13 |
+
from .common import ArgName
|
| 14 |
+
from .cpp_gemm_template import CppGemmTemplate, GEMM_TEMPLATE
|
| 15 |
+
from .cpp_micro_gemm import LayoutType
|
| 16 |
+
from .cpp_template_kernel import CppTemplateKernel
|
| 17 |
+
from .cpp_utils import DTYPE_TO_CPP, GemmBlocking
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# We pass all sizevars present in BY to the GEMM templates so variables are not renamed in the BMM definition
|
| 21 |
+
GEMM_SINGLE_THREAD_MM_STUB = r"""
|
| 22 |
+
{{kernel.def_kernel(
|
| 23 |
+
inputs={"X": X, "W": W},
|
| 24 |
+
outputs={"Y": Y_2d},
|
| 25 |
+
aliases=aliases,
|
| 26 |
+
function_name=kernel_name+"_single_thread_mm",
|
| 27 |
+
extra_sizevars=BY_sizevars + [b_index],
|
| 28 |
+
placeholder="<SINGLE_THREAD_MM_DEF_FOR_BMM>")}}"""
|
| 29 |
+
|
| 30 |
+
GEMM_THREADED_MM_STUB = r"""
|
| 31 |
+
{{kernel.def_kernel(
|
| 32 |
+
inputs={"X": X, "W": W},
|
| 33 |
+
outputs={"Y": Y_2d},
|
| 34 |
+
aliases=aliases,
|
| 35 |
+
function_name=kernel_name+"_threaded_mm",
|
| 36 |
+
extra_sizevars=BY_sizevars + [b_index],
|
| 37 |
+
placeholder="<THREADED_MM_DEF_FOR_BMM>")}}"""
|
| 38 |
+
|
| 39 |
+
BMM_TEMPLATE = r"""
|
| 40 |
+
{{ template.codegen_microkernel_def() }}
|
| 41 |
+
{{ template.codegen_single_thread_gemm() }}
|
| 42 |
+
{{ template.codegen_multi_thread_gemm() }}
|
| 43 |
+
|
| 44 |
+
extern "C"
|
| 45 |
+
{{kernel.def_kernel(inputs={"X": BX, "W": BW}, outputs={"Y": BY}, aliases=aliases)}}
|
| 46 |
+
{
|
| 47 |
+
const int64_t B = {{kernel.size(BY_2d, 0)}};
|
| 48 |
+
{%- if num_threads > 1 %}
|
| 49 |
+
constexpr int64_t num_threads = {{num_threads}};
|
| 50 |
+
int64_t B_single_thread_block = (B / num_threads) * num_threads;
|
| 51 |
+
|
| 52 |
+
#pragma omp parallel for num_threads({{num_threads}})
|
| 53 |
+
{%- else %}
|
| 54 |
+
int64_t B_single_thread_block = B;
|
| 55 |
+
{%- endif %}
|
| 56 |
+
for (int64_t b_start = 0; b_start < B_single_thread_block; ++b_start) {
|
| 57 |
+
{{template.get_gemm_function_call(
|
| 58 |
+
kernel,
|
| 59 |
+
kernel_name+"_single_thread_mm",
|
| 60 |
+
"<SINGLE_THREAD_CALL_FOR_BMM>",
|
| 61 |
+
b_index="b_start",
|
| 62 |
+
)}}
|
| 63 |
+
}
|
| 64 |
+
for (int64_t b_start = B_single_thread_block; b_start < B; ++b_start) {
|
| 65 |
+
{{template.get_gemm_function_call(
|
| 66 |
+
kernel,
|
| 67 |
+
kernel_name+"_threaded_mm",
|
| 68 |
+
"<THREADED_MM_CALL_FOR_BMM>",
|
| 69 |
+
b_index="b_start",
|
| 70 |
+
)}}
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class CppBmmTemplate(CppGemmTemplate):
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
input_nodes,
|
| 80 |
+
layout: ir.Layout,
|
| 81 |
+
num_threads: int,
|
| 82 |
+
register_blocking: GemmBlocking,
|
| 83 |
+
beta=1,
|
| 84 |
+
alpha=1,
|
| 85 |
+
has_bias=False,
|
| 86 |
+
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
|
| 87 |
+
should_block_weights: bool = False,
|
| 88 |
+
name="bmm",
|
| 89 |
+
):
|
| 90 |
+
"""
|
| 91 |
+
In order to simplify the implementation and increase code reuse, the BMM template implements
|
| 92 |
+
two versions of the GEMM kernel: a single-threaded version and a multi-threaded version.
|
| 93 |
+
GEMM kernels are called in a loop over the batch dimension, with single-threaded GEMM calls
|
| 94 |
+
for all but the last (B % num_threads), which are handled by the multi-threaded GEMM kernel.
|
| 95 |
+
|
| 96 |
+
We use an extra sizevar `b_index` to index the batch dimension, which we pass into the GEMM
|
| 97 |
+
template as a sympy.Symbol. This allows us to slice the 3D batch tensors in the GEMM template
|
| 98 |
+
without any changes to the GEMM template itself.
|
| 99 |
+
"""
|
| 100 |
+
super().__init__(
|
| 101 |
+
input_nodes,
|
| 102 |
+
layout,
|
| 103 |
+
num_threads,
|
| 104 |
+
register_blocking,
|
| 105 |
+
beta=beta,
|
| 106 |
+
alpha=alpha,
|
| 107 |
+
has_bias=has_bias,
|
| 108 |
+
epilogue_creator=epilogue_creator,
|
| 109 |
+
should_block_weights=should_block_weights,
|
| 110 |
+
name=name,
|
| 111 |
+
)
|
| 112 |
+
self.b_index = sympy.Symbol("s_b_index", integer=True, nonnegative=True)
|
| 113 |
+
|
| 114 |
+
@staticmethod
|
| 115 |
+
def get_padded_size(n, block_n, k, should_block_weight):
|
| 116 |
+
if should_block_weight:
|
| 117 |
+
# Tensor is constant or not contiguous, so we will pad and block
|
| 118 |
+
new_size, padded_n = CppGemmTemplate.get_padded_size(
|
| 119 |
+
n, block_n, k, should_block_weight
|
| 120 |
+
)
|
| 121 |
+
# Add the new batch dimension
|
| 122 |
+
new_size.insert(0, -1)
|
| 123 |
+
return new_size, padded_n
|
| 124 |
+
else:
|
| 125 |
+
new_size = [-1, k, n]
|
| 126 |
+
return new_size, n
|
| 127 |
+
|
| 128 |
+
@staticmethod
|
| 129 |
+
def check_if_block_weight(W, micro_gemm):
|
| 130 |
+
assert isinstance(W, ir.IRNode)
|
| 131 |
+
_, n = W.get_size()[-2:]
|
| 132 |
+
result = (
|
| 133 |
+
not W.get_layout().is_contiguous()
|
| 134 |
+
or W.get_name() in V.graph.constants
|
| 135 |
+
or (
|
| 136 |
+
n % micro_gemm.register_blocking.block_n != 0
|
| 137 |
+
and micro_gemm.get_b_layout != LayoutType.NORMAL
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
return result
|
| 141 |
+
|
| 142 |
+
def get_gemm_function_call(
|
| 143 |
+
self,
|
| 144 |
+
kernel: CppTemplateKernel,
|
| 145 |
+
function_name: str,
|
| 146 |
+
placeholder: str,
|
| 147 |
+
b_index: str,
|
| 148 |
+
) -> str:
|
| 149 |
+
"""
|
| 150 |
+
Similar to 'def_kernel' in cpp_template_kernel, but instead of generating a function definition,
|
| 151 |
+
generate a function call for the GEMM kernel.
|
| 152 |
+
Args:
|
| 153 |
+
placeholder: The string to replace the function call with
|
| 154 |
+
b_index: The index for slicing the 3D batch tensors
|
| 155 |
+
"""
|
| 156 |
+
|
| 157 |
+
def hook():
|
| 158 |
+
arg_defs, call_args, _, _ = kernel.args.python_argdefs()
|
| 159 |
+
for i, buf in enumerate(call_args):
|
| 160 |
+
if buf == self.b_index:
|
| 161 |
+
arg_defs[i] = ArgName(b_index)
|
| 162 |
+
call = f"{function_name}({', '.join(x.full_name() for x in arg_defs)});"
|
| 163 |
+
return call
|
| 164 |
+
|
| 165 |
+
assert placeholder not in kernel.render_hooks
|
| 166 |
+
kernel.render_hooks[placeholder] = hook
|
| 167 |
+
return placeholder
|
| 168 |
+
|
| 169 |
+
def get_default_reindexers(self, epilogue_nodes):
|
| 170 |
+
def reindexer(args):
|
| 171 |
+
# if epilogue nodes exist, they have 3D ranges but args are 2D, so add 0 index
|
| 172 |
+
return [self.b_index] + args
|
| 173 |
+
|
| 174 |
+
return [reindexer] * len(epilogue_nodes)
|
| 175 |
+
|
| 176 |
+
def get_options(
|
| 177 |
+
self,
|
| 178 |
+
kernel: CppTemplateKernel,
|
| 179 |
+
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
|
| 180 |
+
flag_template_buffer_has_other_users: Optional[bool] = None,
|
| 181 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 182 |
+
**kwargs,
|
| 183 |
+
) -> dict[str, Any]:
|
| 184 |
+
options = super().get_options(
|
| 185 |
+
kernel=kernel,
|
| 186 |
+
template_buffer_node=template_buffer_node,
|
| 187 |
+
flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
|
| 188 |
+
epilogue_nodes=epilogue_nodes,
|
| 189 |
+
**kwargs,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
BX, BW, BY = options["X"], options["W"], options["Y"]
|
| 193 |
+
options["BX"], options["BW"], options["BY"] = BX, BW, BY
|
| 194 |
+
options["BY_2d"] = options["Y_2d"]
|
| 195 |
+
for kword in ["X", "W", "GemmOut", "Y_2d"]:
|
| 196 |
+
options[kword] = kernel.select(options[kword], 0, self.b_index)
|
| 197 |
+
for kword in ["X", "W", "Y_2d"]:
|
| 198 |
+
options[kword + "_dtype"] = DTYPE_TO_CPP[options[kword].dtype]
|
| 199 |
+
options["b_index"] = self.b_index
|
| 200 |
+
options["BY_sizevars"] = [
|
| 201 |
+
s
|
| 202 |
+
for sym in itertools.chain(BY.get_size(), BY.get_stride())
|
| 203 |
+
if isinstance(sym, sympy.Expr)
|
| 204 |
+
for s in sym.free_symbols
|
| 205 |
+
]
|
| 206 |
+
options["kernel_name"] = kernel.kernel_name
|
| 207 |
+
|
| 208 |
+
return options
|
| 209 |
+
|
| 210 |
+
def render( # type: ignore[override, return]
|
| 211 |
+
self,
|
| 212 |
+
kernel: CppTemplateKernel,
|
| 213 |
+
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
|
| 214 |
+
flag_template_buffer_has_other_users: Optional[bool] = None,
|
| 215 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 216 |
+
**kwargs,
|
| 217 |
+
) -> str:
|
| 218 |
+
options = self.get_options(
|
| 219 |
+
kernel=kernel,
|
| 220 |
+
template_buffer_node=template_buffer_node,
|
| 221 |
+
flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
|
| 222 |
+
epilogue_nodes=epilogue_nodes,
|
| 223 |
+
**kwargs,
|
| 224 |
+
)
|
| 225 |
+
self.render_options = options
|
| 226 |
+
|
| 227 |
+
with contextlib.ExitStack() as stack:
|
| 228 |
+
for buf in options["fake_buffers"]:
|
| 229 |
+
stack.enter_context(
|
| 230 |
+
patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf))
|
| 231 |
+
)
|
| 232 |
+
result = self._template_from_string(BMM_TEMPLATE).render(**options)
|
| 233 |
+
|
| 234 |
+
# Finalize the function definitions for the gemm routines
|
| 235 |
+
sub_mm_hooks = {
|
| 236 |
+
name: hook
|
| 237 |
+
for name, hook in kernel.render_hooks.items()
|
| 238 |
+
if "FOR_BMM" in name
|
| 239 |
+
}
|
| 240 |
+
result = PartialRender(result, sub_mm_hooks).finalize_all()
|
| 241 |
+
for name in sub_mm_hooks:
|
| 242 |
+
del kernel.render_hooks[name]
|
| 243 |
+
del kernel.args.sizevars[options["b_index"]]
|
| 244 |
+
return result
|
| 245 |
+
|
| 246 |
+
def codegen_single_thread_gemm(self):
|
| 247 |
+
stub = self._template_from_string(GEMM_SINGLE_THREAD_MM_STUB).render(
|
| 248 |
+
self.render_options
|
| 249 |
+
)
|
| 250 |
+
return stub + self._template_from_string(GEMM_TEMPLATE).render(
|
| 251 |
+
{**self.render_options, "num_threads": 1}
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
def codegen_multi_thread_gemm(self):
|
| 255 |
+
stub = self._template_from_string(GEMM_THREADED_MM_STUB).render(
|
| 256 |
+
self.render_options
|
| 257 |
+
)
|
| 258 |
+
return stub + self._template_from_string(GEMM_TEMPLATE).render(
|
| 259 |
+
self.render_options
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
def codegen_gemm_stub_def(self):
|
| 263 |
+
return ""
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py
ADDED
|
@@ -0,0 +1,1090 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
import logging
|
| 4 |
+
import re
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from unittest.mock import patch
|
| 7 |
+
|
| 8 |
+
import sympy
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.utils
|
| 12 |
+
|
| 13 |
+
from ...utils._ordered_set import OrderedSet
|
| 14 |
+
from .. import ir
|
| 15 |
+
from ..ir import TensorBox
|
| 16 |
+
from ..select_algorithm import DataProcessorTemplateWrapper
|
| 17 |
+
from ..utils import parallel_num_threads
|
| 18 |
+
from ..virtualized import V
|
| 19 |
+
from .cpp_template import CppTemplate
|
| 20 |
+
from .cpp_utils import GemmBlocking
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
# TODO: reuse cpp codegen to generate below pointwise/reduction kernels
|
| 26 |
+
SOFTMAX_FUSIONS = r"""
|
| 27 |
+
// 1) out = exp(a - val)
|
| 28 |
+
// 2) val = sum(out)
|
| 29 |
+
template <typename T1, typename T2>
|
| 30 |
+
inline void {{kernel_name}}_exp_reduce_sum_fusion_kernel(
|
| 31 |
+
T1* a,
|
| 32 |
+
const int& size,
|
| 33 |
+
T2* out,
|
| 34 |
+
T1& val) {
|
| 35 |
+
auto vec_size = at::vec::Vectorized<T1>::size();
|
| 36 |
+
auto vec_max = at::vec::Vectorized<T1>(val);
|
| 37 |
+
T1 tmp_sum = 0;
|
| 38 |
+
auto vec_tmp_sum = at::vec::Vectorized<T1>(tmp_sum);
|
| 39 |
+
for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) {
|
| 40 |
+
auto tmp0 = at::vec::Vectorized<T1>::loadu(a + i);
|
| 41 |
+
auto tmp1 = tmp0 - vec_max;
|
| 42 |
+
auto tmp2 = tmp1.exp_u20();
|
| 43 |
+
vec_tmp_sum += tmp2;
|
| 44 |
+
at::native::_store(out + i, tmp2);
|
| 45 |
+
}
|
| 46 |
+
tmp_sum = at::vec::vec_reduce_all<T1>(
|
| 47 |
+
[](at::vec::Vectorized<T1>& x, at::vec::Vectorized<T1>& y) {
|
| 48 |
+
return x + y;
|
| 49 |
+
},
|
| 50 |
+
vec_tmp_sum);
|
| 51 |
+
for (long i = vec_size * (size / vec_size); i < size; i++) {
|
| 52 |
+
auto tmp0 = a[i];
|
| 53 |
+
auto tmp1 = tmp0 - val;
|
| 54 |
+
auto tmp2 = exp(tmp1);
|
| 55 |
+
tmp_sum += tmp2;
|
| 56 |
+
out[i] = tmp2;
|
| 57 |
+
}
|
| 58 |
+
val = tmp_sum;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// 1) out = a * scale
|
| 62 |
+
// 2) max = max(out)
|
| 63 |
+
template <typename scalar_t>
|
| 64 |
+
inline void {{kernel_name}}_mul_reduce_max_fusion_kernel(
|
| 65 |
+
const scalar_t* a,
|
| 66 |
+
const scalar_t& scale,
|
| 67 |
+
const int& size,
|
| 68 |
+
scalar_t* out,
|
| 69 |
+
scalar_t& max) {
|
| 70 |
+
auto vec_size = at::vec::Vectorized<scalar_t>::size();
|
| 71 |
+
auto vec_scale = at::vec::Vectorized<scalar_t>(scale);
|
| 72 |
+
scalar_t tmp_max = -std::numeric_limits<scalar_t>::infinity();
|
| 73 |
+
auto vec_tmp_max = at::vec::Vectorized<scalar_t>(tmp_max);
|
| 74 |
+
for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) {
|
| 75 |
+
auto tmp0 = at::vec::Vectorized<scalar_t>::loadu(a + i);
|
| 76 |
+
auto tmp1 = tmp0 * vec_scale;
|
| 77 |
+
vec_tmp_max = at::vec::maximum(vec_tmp_max, tmp1);
|
| 78 |
+
at::native::_store(out + i, tmp1);
|
| 79 |
+
}
|
| 80 |
+
for (long i = vec_size * (size / vec_size); i < size; i++) {
|
| 81 |
+
auto tmp0 = a[i];
|
| 82 |
+
auto tmp1 = tmp0 * scale;
|
| 83 |
+
tmp_max = std::max(tmp_max, tmp1);
|
| 84 |
+
out[i] = tmp1;
|
| 85 |
+
}
|
| 86 |
+
max = std::max(
|
| 87 |
+
tmp_max,
|
| 88 |
+
at::vec::vec_reduce_all<scalar_t>(
|
| 89 |
+
[](at::vec::Vectorized<scalar_t>& x, at::vec::Vectorized<scalar_t>& y) {
|
| 90 |
+
return at::vec::maximum(x, y);
|
| 91 |
+
},
|
| 92 |
+
vec_tmp_max));
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
template <typename scalar_t>
|
| 96 |
+
static inline scalar_t* {{kernel_name}}_conditional_data_ptr(scalar_t* ptr, scalar_t* ptr2) {
|
| 97 |
+
TORCH_CHECK(ptr2 == nullptr);
|
| 98 |
+
return ptr;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
template <typename scalar_t,
|
| 102 |
+
typename std::enable_if_t<c10::is_reduced_floating_point_v<scalar_t>, int> = 0>
|
| 103 |
+
static inline scalar_t* {{kernel_name}}_conditional_data_ptr(float* ptr, scalar_t* ptr2) {
|
| 104 |
+
return ptr2;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
template <typename scalar_t>
|
| 108 |
+
inline void {{kernel_name}}_fill_stub(scalar_t* data, scalar_t val, int64_t size) {
|
| 109 |
+
using Vec = at::vec::Vectorized<scalar_t>;
|
| 110 |
+
Vec data_vec = Vec(val);
|
| 111 |
+
int64_t d = 0;
|
| 112 |
+
for (; d < size - (size % Vec::size()); d += Vec::size()) {
|
| 113 |
+
data_vec.store(data + d);
|
| 114 |
+
}
|
| 115 |
+
#if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
|
| 116 |
+
# pragma unroll
|
| 117 |
+
#endif
|
| 118 |
+
for (; d < size; d++) {
|
| 119 |
+
data[d] = val;
|
| 120 |
+
}
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
// out = a * scale
|
| 124 |
+
template <typename scalar_t>
|
| 125 |
+
inline void {{kernel_name}}_mul_scale_kernel(
|
| 126 |
+
scalar_t* a,
|
| 127 |
+
scalar_t scale,
|
| 128 |
+
int64_t size) {
|
| 129 |
+
auto vec_size = at::vec::Vectorized<scalar_t>::size();
|
| 130 |
+
auto vec_scale = at::vec::Vectorized<scalar_t>(scale);
|
| 131 |
+
for (int64_t i = 0; i < vec_size * (size / vec_size); i += vec_size) {
|
| 132 |
+
auto tmp0 = at::vec::Vectorized<scalar_t>::loadu(a + i);
|
| 133 |
+
auto tmp1 = tmp0 * vec_scale;
|
| 134 |
+
at::native::_store(a + i, tmp1);
|
| 135 |
+
}
|
| 136 |
+
for (int64_t i = vec_size * (size / vec_size); i < size; i++) {
|
| 137 |
+
auto tmp0 = a[i];
|
| 138 |
+
auto tmp1 = tmp0 * scale;
|
| 139 |
+
a[i] = tmp1;
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
BRGEMM_PACK_FUNCTIONS = r"""
|
| 146 |
+
template <typename scalar_t>
|
| 147 |
+
inline void {{kernel_name}}_copy_value_with_pad(
|
| 148 |
+
const scalar_t* value_ptr,
|
| 149 |
+
scalar_t* dst_ptr,
|
| 150 |
+
int64_t rows,
|
| 151 |
+
int64_t cols,
|
| 152 |
+
int64_t prows,
|
| 153 |
+
int64_t pcols,
|
| 154 |
+
int64_t ldi) {
|
| 155 |
+
auto vec_size = at::vec::Vectorized<scalar_t>::size();
|
| 156 |
+
int64_t i = 0;
|
| 157 |
+
for (; i < rows; i++) {
|
| 158 |
+
int64_t j = 0;
|
| 159 |
+
for (; j < cols - (cols % vec_size); j += vec_size) {
|
| 160 |
+
auto vec_v =
|
| 161 |
+
at::vec::Vectorized<scalar_t>::loadu(value_ptr + i * ldi + j);
|
| 162 |
+
vec_v.store(dst_ptr + i * pcols + j);
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
if (j < cols) {
|
| 166 |
+
auto vec_v = at::vec::Vectorized<scalar_t>::loadu(
|
| 167 |
+
value_ptr + i * ldi + j, cols - j);
|
| 168 |
+
vec_v.store(dst_ptr + i * pcols + j, cols - j);
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
// col padding
|
| 172 |
+
auto psize = pcols - cols;
|
| 173 |
+
if (psize > 0) {
|
| 174 |
+
auto zero_vec = at::vec::Vectorized<scalar_t>(0);
|
| 175 |
+
int64_t pj = 0;
|
| 176 |
+
for (; pj < psize - (psize % vec_size); pj += vec_size) {
|
| 177 |
+
zero_vec.store(dst_ptr + i * pcols + cols + pj);
|
| 178 |
+
}
|
| 179 |
+
if (pj < psize) {
|
| 180 |
+
zero_vec.store(dst_ptr + i * pcols + cols + pj, psize - pj);
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
// row padding
|
| 185 |
+
for (; i < prows; i++) {
|
| 186 |
+
auto zero_vec = at::vec::Vectorized<scalar_t>(0);
|
| 187 |
+
int64_t j = 0;
|
| 188 |
+
for (; j < pcols - (pcols % vec_size); j += vec_size) {
|
| 189 |
+
zero_vec.store(dst_ptr + i * pcols + j);
|
| 190 |
+
}
|
| 191 |
+
if (j < pcols) {
|
| 192 |
+
zero_vec.store(dst_ptr + i * pcols + j, pcols - j);
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
MICRO_GEMM_TEMPLATE = r"""
|
| 200 |
+
GEMM_DEFINE
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
ALLOCATE_BUFFER = r"""
|
| 204 |
+
int64_t {{buffer_name}}_dtype_itemsize = c10::is_reduced_floating_point_v<{{buffer_dtype}}> ? 2 : 4;
|
| 205 |
+
auto& {{buffer_name}}_allocator = *at::getCPUAllocator();
|
| 206 |
+
auto {{buffer_name}}_work_data = {{buffer_name}}_allocator.allocate({{buffer_size}}*{{buffer_name}}_dtype_itemsize);
|
| 207 |
+
void* {{buffer_name}}_data_ptr = {{buffer_name}}_work_data.get();
|
| 208 |
+
{{buffer_dtype}}* {{buffer_name}} = ({{buffer_dtype}}*){{buffer_name}}_data_ptr;
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
FLEX_ATTENTION_TEMPLATE = r"""
|
| 212 |
+
{{template.header().getvalue()}}
|
| 213 |
+
#include <ATen/native/cpu/utils.h>
|
| 214 |
+
#include <ATen/native/CPUBlas.h>
|
| 215 |
+
#include <ATen/Context.h>
|
| 216 |
+
{{template.codegen_micro_gemm(kernel.kernel_name)}}
|
| 217 |
+
{{template.codegen_softmax_fusion(kernel.kernel_name)}}
|
| 218 |
+
{{template.codegen_brgemm_pack_function(kernel.kernel_name)}}
|
| 219 |
+
{%- set kernel_args = {"query": query, "key": key, "value": value,
|
| 220 |
+
"kv_num_blocks": kv_num_blocks, "kv_indices": kv_indices,
|
| 221 |
+
"full_kv_num_blocks": full_kv_num_blocks, "full_kv_indices": full_kv_indices } %}
|
| 222 |
+
{%- set kernel_args = template.update_kernel_args(kernel_args) %}
|
| 223 |
+
|
| 224 |
+
extern "C"
|
| 225 |
+
{{kernel.def_kernel(inputs=kernel_args, outputs={"output": output}, extra_sizevars=template.extra_sizevars)}}
|
| 226 |
+
{
|
| 227 |
+
{{ kernel.maybe_codegen_profile() }}
|
| 228 |
+
int64_t qBlockSize = {{qBlockSize}};
|
| 229 |
+
int64_t kvBlockSize = {{kvBlockSize}};
|
| 230 |
+
int64_t num_thread = {{num_thread}};
|
| 231 |
+
|
| 232 |
+
// dtypes of kernel and internal buffers
|
| 233 |
+
using scalar_t = {{kernel.dtype(query)}};
|
| 234 |
+
constexpr bool is_reduced_type = c10::is_reduced_floating_point_v<scalar_t>;
|
| 235 |
+
using accum_t = at::opmath_type<{{kernel.dtype(query)}}>;
|
| 236 |
+
using Vec = at::vec::Vectorized<accum_t>;
|
| 237 |
+
accum_t scaling_factor = {{scale}};
|
| 238 |
+
int64_t batchSize = {{kernel.size(query, 0)}};
|
| 239 |
+
int64_t qSize = {{kernel.size(query, 1)}};
|
| 240 |
+
int64_t num_head = {{kernel.size(query, 2)}};
|
| 241 |
+
int64_t headSize = {{kernel.size(query, 3)}};
|
| 242 |
+
int64_t batchSize_k = {{kernel.size(key, 0)}};
|
| 243 |
+
int64_t num_head_k = {{kernel.size(key, 2)}};
|
| 244 |
+
int64_t headSize_v = {{kernel.size(value, 3)}};
|
| 245 |
+
bool is_broadcast_bs_kv = batchSize != batchSize_k;
|
| 246 |
+
bool is_broadcast_head_kv = num_head != num_head_k;
|
| 247 |
+
int64_t gqa_shards = num_head / num_head_k;
|
| 248 |
+
int64_t bs_shards = batchSize / batchSize_k;
|
| 249 |
+
|
| 250 |
+
int64_t batchSize_kvi = {{kernel.size(kv_indices, 0)}};
|
| 251 |
+
int64_t num_head_kvi = {{kernel.size(kv_indices, 1)}};
|
| 252 |
+
int64_t block_num_kvi = {{kernel.size(kv_indices, 3)}};
|
| 253 |
+
bool is_broadcast_bs_kvi = batchSize != batchSize_kvi;
|
| 254 |
+
bool is_broadcast_head_kvi = num_head != num_head_kvi;
|
| 255 |
+
int64_t gqa_shards_kvi = num_head / num_head_kvi;
|
| 256 |
+
int64_t bs_shards_kvi = batchSize / batchSize_kvi;
|
| 257 |
+
|
| 258 |
+
int64_t kviStrideB = {{kernel.stride(kv_indices, 0)}};
|
| 259 |
+
int64_t kviStrideH = {{kernel.stride(kv_indices, 1)}};
|
| 260 |
+
int64_t kviStrideQ = {{kernel.stride(kv_indices, 2)}};
|
| 261 |
+
|
| 262 |
+
int64_t num_kviStrideB = {{kernel.stride(kv_num_blocks, 0)}};
|
| 263 |
+
int64_t num_kviStrideH = {{kernel.stride(kv_num_blocks, 1)}};
|
| 264 |
+
|
| 265 |
+
{%- if has_full_kv_block %}
|
| 266 |
+
int64_t full_kviStrideB = {{kernel.stride(full_kv_indices, 0)}};
|
| 267 |
+
int64_t full_kviStrideH = {{kernel.stride(full_kv_indices, 1)}};
|
| 268 |
+
int64_t full_kviStrideQ = {{kernel.stride(full_kv_indices, 2)}};
|
| 269 |
+
|
| 270 |
+
int64_t full_num_kviStrideB = {{kernel.stride(full_kv_num_blocks, 0)}};
|
| 271 |
+
int64_t full_num_kviStrideH = {{kernel.stride(full_kv_num_blocks, 1)}};
|
| 272 |
+
auto full_kv_indices_data = full_kv_indices;
|
| 273 |
+
auto full_kv_num_blocks_data = full_kv_num_blocks;
|
| 274 |
+
{%- endif %}
|
| 275 |
+
|
| 276 |
+
auto kv_num_blocks_data = kv_num_blocks;
|
| 277 |
+
auto kv_indices_data = kv_indices;
|
| 278 |
+
|
| 279 |
+
// Strides
|
| 280 |
+
int64_t qStrideB = {{kernel.stride(query, 0)}};
|
| 281 |
+
int64_t qStrideM = {{kernel.stride(query, 1)}};
|
| 282 |
+
int64_t qStrideH = {{kernel.stride(query, 2)}};
|
| 283 |
+
int64_t kStrideB = {{kernel.stride(key, 0)}};
|
| 284 |
+
int64_t kStrideN = {{kernel.stride(key, 1)}};
|
| 285 |
+
int64_t kStrideH = {{kernel.stride(key, 2)}};
|
| 286 |
+
int64_t vStrideB = {{kernel.stride(value, 0)}};
|
| 287 |
+
int64_t vStrideN = {{kernel.stride(value, 1)}};
|
| 288 |
+
int64_t vStrideH = {{kernel.stride(value, 2)}};
|
| 289 |
+
int64_t oStrideB = {{kernel.stride(output, 0)}};
|
| 290 |
+
int64_t oStrideM = {{kernel.stride(output, 2)}};
|
| 291 |
+
int64_t oStrideH = {{kernel.stride(output, 1)}};
|
| 292 |
+
|
| 293 |
+
int64_t kvSize = {{kernel.size(key, 1)}};
|
| 294 |
+
|
| 295 |
+
int64_t qSplitSize = qBlockSize;
|
| 296 |
+
int64_t kvSplitSize = kvBlockSize;
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
qSplitSize = qSplitSize > qSize ? qSize : qSplitSize;
|
| 300 |
+
kvSplitSize = kvSplitSize > kvSize ? kvSize : kvSplitSize;
|
| 301 |
+
int64_t qSlice = (qSize + qSplitSize - 1) / qSplitSize;
|
| 302 |
+
int64_t kvSlice = (kvSize + kvSplitSize - 1) / kvSplitSize;
|
| 303 |
+
int64_t kvTail = (kvSize - 1) % kvSplitSize + 1;
|
| 304 |
+
|
| 305 |
+
bool need_pack = false;
|
| 306 |
+
// Whether pack is needed for BFloat16/Half
|
| 307 |
+
if (is_reduced_type) {
|
| 308 |
+
// check platform ability
|
| 309 |
+
need_pack = std::is_same_v<scalar_t, at::BFloat16> ? at::native::cpublas::could_pack(at::kBFloat16)
|
| 310 |
+
: at::native::cpublas::could_pack(at::kHalf);
|
| 311 |
+
}
|
| 312 |
+
if (need_pack) {
|
| 313 |
+
// When the number of gemm is greater than the number of pack,
|
| 314 |
+
// the pack overhead can be overlapped.
|
| 315 |
+
int64_t thresh_size = 64;
|
| 316 |
+
need_pack = kvSize >= thresh_size && qSize >= thresh_size;
|
| 317 |
+
if (need_pack) {
|
| 318 |
+
double pack_size = batchSize * num_head * kvSize * headSize;
|
| 319 |
+
double qs_per_thread = (batchSize * num_head * qSlice + num_thread - 1) / num_thread;
|
| 320 |
+
double gemm_size_per_thread = qs_per_thread * qSplitSize * kvSize * headSize;
|
| 321 |
+
need_pack = gemm_size_per_thread / pack_size >= 4;
|
| 322 |
+
}
|
| 323 |
+
}
|
| 324 |
+
// Pad is needed for packing when K is not even
|
| 325 |
+
bool headSize_even = headSize % 2 == 0;
|
| 326 |
+
int64_t eheadSize = need_pack && !headSize_even ? headSize + 1: headSize;
|
| 327 |
+
int64_t ekvSplitSize = need_pack && (kvSplitSize % 2 != 0) ? kvSplitSize + 1 : kvSplitSize;
|
| 328 |
+
int64_t ekvTail = need_pack && (kvTail % 2 != 0) ? kvTail + 1 : kvTail;
|
| 329 |
+
int64_t kv_padding_size = (kvSize - 1) / kvSplitSize * ekvSplitSize + ekvTail;
|
| 330 |
+
|
| 331 |
+
// Allocate per thread temp buf (accumulate type)
|
| 332 |
+
int64_t _size_per_thread =
|
| 333 |
+
/* qk */ qSplitSize * kvSplitSize +
|
| 334 |
+
/* qk_max */ qSplitSize +
|
| 335 |
+
/* qk_sum */ qSplitSize +
|
| 336 |
+
/* dst */ qSplitSize * headSize_v;
|
| 337 |
+
|
| 338 |
+
// Inputs/outputs buffers
|
| 339 |
+
const scalar_t* q_data = query;
|
| 340 |
+
const scalar_t* k_data = key;
|
| 341 |
+
const scalar_t* v_data = value;
|
| 342 |
+
scalar_t* out_data = output;
|
| 343 |
+
|
| 344 |
+
// Buffers to store accum results, padding query and transpose/packing key/value
|
| 345 |
+
{{template.codegen_allocate_buffer("buf_data", "accum_t", "num_thread*_size_per_thread")}}
|
| 346 |
+
{{template.codegen_allocate_buffer("buf_reduced_data", "scalar_t", "num_thread*qSplitSize*ekvSplitSize")}}
|
| 347 |
+
{{template.codegen_allocate_buffer("key_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*eheadSize*kvSize")}}
|
| 348 |
+
{{template.codegen_allocate_buffer("value_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*kv_padding_size*headSize_v")}}
|
| 349 |
+
{{template.codegen_allocate_buffer("transpose_buffer_ptr", "scalar_t", "num_thread*kvSplitSize*headSize")}}
|
| 350 |
+
{{template.codegen_allocate_buffer("query_padding_ptr", "scalar_t", "num_thread*qSplitSize*eheadSize")}}
|
| 351 |
+
if (need_pack) {
|
| 352 |
+
// Pack K, V
|
| 353 |
+
at::parallel_for(0, batchSize_k * num_head_k * kvSlice, 1, [&](int64_t begin, int64_t end) {
|
| 354 |
+
int ompIdx = at::get_thread_num();
|
| 355 |
+
int64_t i = 0, j = 0, l = 0, n = 0;
|
| 356 |
+
scalar_t* transpose_ptr = need_pack? transpose_buffer_ptr + ompIdx * kvSplitSize * headSize : nullptr;
|
| 357 |
+
at::native::data_index_init(begin, i, batchSize_k, j, num_head_k, l, kvSlice);
|
| 358 |
+
for ([[maybe_unused]] auto z : c10::irange(begin, end)) {
|
| 359 |
+
n = l * kvSplitSize;
|
| 360 |
+
int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n);
|
| 361 |
+
auto k_addr =
|
| 362 |
+
k_data + i * kStrideB + j * kStrideH + n * kStrideN;
|
| 363 |
+
auto v_addr =
|
| 364 |
+
v_data + i * vStrideB + j * vStrideH + n * vStrideN;
|
| 365 |
+
// transpose [cur_kvSplitSize, headSize] -> [headSize, cur_kvSplitSize]
|
| 366 |
+
at::native::utils::transpose<uint16_t>(
|
| 367 |
+
cur_kvSplitSize,
|
| 368 |
+
headSize,
|
| 369 |
+
/* src_ptr */
|
| 370 |
+
reinterpret_cast<const uint16_t*>(k_addr),
|
| 371 |
+
/* ld_src */ kStrideN,
|
| 372 |
+
/* dst */ reinterpret_cast<uint16_t*>(transpose_ptr),
|
| 373 |
+
/* ld_dst */ cur_kvSplitSize);
|
| 374 |
+
|
| 375 |
+
// Pack [headSize, cur_kvSplitSize]
|
| 376 |
+
at::vec::pack_vnni2(
|
| 377 |
+
/* src */ reinterpret_cast<const uint16_t*>(transpose_ptr),
|
| 378 |
+
/* dst */ reinterpret_cast<uint16_t*>(key_reorder_ptr + i * num_head_k * eheadSize * kvSize +
|
| 379 |
+
j * eheadSize * kvSize + n * eheadSize),
|
| 380 |
+
/* ld_src */ cur_kvSplitSize,
|
| 381 |
+
/* K */ headSize,
|
| 382 |
+
/* N */ cur_kvSplitSize);
|
| 383 |
+
|
| 384 |
+
// Pack [cur_kvSplitSize, headSize_v]
|
| 385 |
+
at::vec::pack_vnni2(
|
| 386 |
+
/* src */ reinterpret_cast<const uint16_t*>(v_addr),
|
| 387 |
+
/* dst */ reinterpret_cast<uint16_t*>(value_reorder_ptr +
|
| 388 |
+
i * num_head_k * kv_padding_size * headSize_v +
|
| 389 |
+
j * kv_padding_size * headSize_v + n * headSize_v),
|
| 390 |
+
/* ld_src */ vStrideN,
|
| 391 |
+
/* K */ cur_kvSplitSize,
|
| 392 |
+
/* N */ headSize_v);
|
| 393 |
+
// Move to the next query
|
| 394 |
+
at::native::data_index_step(i, batchSize_k, j, num_head_k, l, kvSlice);
|
| 395 |
+
}
|
| 396 |
+
});
|
| 397 |
+
}
|
| 398 |
+
// Attention loop below
|
| 399 |
+
at::parallel_for(0, batchSize * num_head * qSlice, 1, [&](int64_t begin, int64_t end) {
|
| 400 |
+
int64_t i = 0, j = 0, k = 0;
|
| 401 |
+
at::native::data_index_init(begin, i, batchSize, j, num_head, k, qSlice);
|
| 402 |
+
int ompIdx = at::get_thread_num();
|
| 403 |
+
accum_t* buf_ptr = buf_data + ompIdx * _size_per_thread;
|
| 404 |
+
accum_t* qk_data = buf_ptr;
|
| 405 |
+
accum_t* qk_max_data = qk_data + qSplitSize * kvSplitSize;
|
| 406 |
+
accum_t* qk_sum_data = qk_max_data + qSplitSize;
|
| 407 |
+
accum_t* dst_data = qk_sum_data + qSplitSize;
|
| 408 |
+
scalar_t *qk_reduced_data =
|
| 409 |
+
is_reduced_type
|
| 410 |
+
? buf_reduced_data + ompIdx * qSplitSize * ekvSplitSize
|
| 411 |
+
: nullptr;
|
| 412 |
+
scalar_t* query_t_padding_ptr = (!headSize_even && need_pack)
|
| 413 |
+
? query_padding_ptr + ompIdx * qSplitSize * eheadSize
|
| 414 |
+
: nullptr;
|
| 415 |
+
|
| 416 |
+
for ([[maybe_unused]] auto z : c10::irange(begin, end)) {
|
| 417 |
+
auto i_kvi = is_broadcast_bs_kvi ? i/bs_shards_kvi : i;
|
| 418 |
+
auto j_kvi = is_broadcast_head_kvi ? j/gqa_shards_kvi : j;
|
| 419 |
+
auto kv_logical_num_data = kv_num_blocks_data + i_kvi * num_kviStrideB +
|
| 420 |
+
j_kvi * num_kviStrideH + k;
|
| 421 |
+
int kv_indice_num = *kv_logical_num_data;
|
| 422 |
+
std::vector<int> kv_indice_list(kv_indice_num);
|
| 423 |
+
for(int kv_i = 0; kv_i < kv_indice_num; kv_i++){
|
| 424 |
+
auto kv_logical_data = kv_indices_data + i_kvi * kviStrideB +
|
| 425 |
+
j_kvi * kviStrideH + k*kviStrideQ + kv_i;
|
| 426 |
+
kv_indice_list[kv_i] = *kv_logical_data;
|
| 427 |
+
}
|
| 428 |
+
bool is_skip_kv = kv_indice_num > 0 ? false : true;
|
| 429 |
+
{%- if has_full_kv_block %}
|
| 430 |
+
auto full_kv_logical_num_data = full_kv_num_blocks_data + i_kvi * num_kviStrideB +
|
| 431 |
+
j_kvi * num_kviStrideH + k;
|
| 432 |
+
int full_kv_indice_num = *full_kv_logical_num_data;
|
| 433 |
+
std::vector<int> full_kv_indice_list(full_kv_indice_num);
|
| 434 |
+
for(int kv_i = 0; kv_i < full_kv_indice_num; kv_i++){
|
| 435 |
+
auto full_kv_logical_data = full_kv_indices_data + i_kvi * full_kviStrideB +
|
| 436 |
+
j_kvi * full_kviStrideH + k*full_kviStrideQ + kv_i;
|
| 437 |
+
full_kv_indice_list[kv_i] = *full_kv_logical_data;
|
| 438 |
+
}
|
| 439 |
+
is_skip_kv = kv_indice_num + full_kv_indice_num > 0 ? false : true;
|
| 440 |
+
{%- endif %}
|
| 441 |
+
int64_t m = k * qSplitSize;
|
| 442 |
+
int64_t cur_qSplitSize = std::min(qSplitSize, qSize - m);
|
| 443 |
+
if (!is_skip_kv){
|
| 444 |
+
// Initialize max and sum
|
| 445 |
+
{{kernel.kernel_name}}_fill_stub(qk_max_data,
|
| 446 |
+
-std::numeric_limits<accum_t>::infinity(), cur_qSplitSize);
|
| 447 |
+
{{kernel.kernel_name}}_fill_stub(qk_sum_data,
|
| 448 |
+
static_cast<accum_t>(0), cur_qSplitSize);
|
| 449 |
+
|
| 450 |
+
if (!headSize_even && need_pack) {
|
| 451 |
+
// Pad query if headSize is not even
|
| 452 |
+
{{kernel.kernel_name}}_copy_value_with_pad<scalar_t>(
|
| 453 |
+
q_data + i * qStrideB + j * qStrideH + m * qStrideM,
|
| 454 |
+
query_t_padding_ptr,
|
| 455 |
+
cur_qSplitSize,
|
| 456 |
+
headSize,
|
| 457 |
+
cur_qSplitSize,
|
| 458 |
+
eheadSize,
|
| 459 |
+
qStrideM
|
| 460 |
+
);
|
| 461 |
+
}
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
{%- if has_full_kv_block %}
|
| 465 |
+
for (int64_t n_idx = 0; n_idx < kv_indice_num + full_kv_indice_num ; n_idx += 1) {
|
| 466 |
+
auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize;
|
| 467 |
+
{%- else %}
|
| 468 |
+
for (int64_t n_idx = 0; n_idx < kv_indice_num ; n_idx += 1) {
|
| 469 |
+
auto n = kv_indice_list[n_idx]*kvSplitSize;
|
| 470 |
+
{%- endif %}
|
| 471 |
+
|
| 472 |
+
auto cur_n = n/kvSplitSize;
|
| 473 |
+
int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n);
|
| 474 |
+
int64_t cur_ekvSplitSize = (need_pack && cur_kvSplitSize % 2 != 0) ? cur_kvSplitSize + 1 : cur_kvSplitSize;
|
| 475 |
+
|
| 476 |
+
// Calculate scale * q @ k.T
|
| 477 |
+
auto i_kv = is_broadcast_bs_kv ? i/bs_shards : i;
|
| 478 |
+
auto j_kv = is_broadcast_head_kv ? j/gqa_shards : j;
|
| 479 |
+
|
| 480 |
+
if (!need_pack) {
|
| 481 |
+
auto k_addr =
|
| 482 |
+
k_data + i_kv * kStrideB + j_kv * kStrideH + n * kStrideN;
|
| 483 |
+
|
| 484 |
+
{{kernel.kernel_name}}_kernel_micro_gemm_transpose_b<static_cast<bool>(false)>(
|
| 485 |
+
q_data + i * qStrideB + j * qStrideH +
|
| 486 |
+
m * qStrideM,
|
| 487 |
+
k_addr,
|
| 488 |
+
qk_data,
|
| 489 |
+
cur_qSplitSize,
|
| 490 |
+
cur_kvSplitSize,
|
| 491 |
+
headSize,
|
| 492 |
+
qStrideM,
|
| 493 |
+
kStrideN,
|
| 494 |
+
cur_kvSplitSize);
|
| 495 |
+
|
| 496 |
+
} else {
|
| 497 |
+
at::native::cpublas::brgemm(
|
| 498 |
+
cur_qSplitSize,
|
| 499 |
+
cur_kvSplitSize,
|
| 500 |
+
eheadSize,
|
| 501 |
+
headSize_even ? qStrideM : eheadSize,
|
| 502 |
+
cur_kvSplitSize,
|
| 503 |
+
cur_kvSplitSize,
|
| 504 |
+
false,
|
| 505 |
+
!headSize_even
|
| 506 |
+
? query_t_padding_ptr
|
| 507 |
+
: q_data + i * qStrideB + j * qStrideH + m * qStrideM,
|
| 508 |
+
key_reorder_ptr + i_kv * num_head_k * eheadSize * kvSize +
|
| 509 |
+
j_kv * eheadSize * kvSize + n * eheadSize,
|
| 510 |
+
qk_data,
|
| 511 |
+
need_pack);
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
{{kernel.kernel_name}}_mul_scale_kernel<accum_t>(qk_data, scaling_factor, cur_qSplitSize*cur_kvSplitSize);
|
| 515 |
+
|
| 516 |
+
{%- if score_mod and mask_mod %}
|
| 517 |
+
// TODO: reduce the number of calls of q_idx and kv_idx initialization
|
| 518 |
+
std::vector<int64_t> q_idx(cur_qSplitSize);
|
| 519 |
+
for (int64_t i = 0; i < cur_qSplitSize; ++i) {
|
| 520 |
+
q_idx[i] = m + i;
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
std::vector<int64_t> kv_idx(cur_kvSplitSize);
|
| 524 |
+
for (int64_t i = 0; i < cur_kvSplitSize; ++i) {
|
| 525 |
+
kv_idx[i] = n + i;
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
std::vector<int64_t> b_idx = {i};
|
| 529 |
+
std::vector<int64_t> h_idx = {j};
|
| 530 |
+
|
| 531 |
+
accum_t* in_ptr0 = qk_data;
|
| 532 |
+
|
| 533 |
+
auto in_ptr1 = b_idx.data();
|
| 534 |
+
auto in_ptr2 = h_idx.data();
|
| 535 |
+
auto in_ptr3 = q_idx.data();
|
| 536 |
+
auto in_ptr4 = kv_idx.data();
|
| 537 |
+
|
| 538 |
+
// apply score mod function
|
| 539 |
+
{
|
| 540 |
+
{{ template.generate_other_buffer("score_others", 0, "len_score_other", kernel.args) }}
|
| 541 |
+
accum_t* out_ptr{{score_buf_idx}} = in_ptr0;
|
| 542 |
+
{{ template.modification(score_mod, score_buf_name, score_buf_idx)|indent(12, false) }}
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
if ((std::find(kv_indice_list.begin(), kv_indice_list.end(), cur_n) != kv_indice_list.end()) ){
|
| 546 |
+
// Apply block mask, fill unused with -inf
|
| 547 |
+
{
|
| 548 |
+
{{ template.generate_other_buffer("mask_others", -1, "len_mask_other", kernel.args) }}
|
| 549 |
+
accum_t* out_ptr{{mask_buf_idx}} = in_ptr0;
|
| 550 |
+
{{ template.modification(mask_mod, mask_buf_name, mask_buf_idx)|indent(12, false) }}
|
| 551 |
+
}
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
{%- endif %}
|
| 555 |
+
// Update coefficients with Softmax
|
| 556 |
+
accum_t tmp_max = 0, tmp_sum = 0, exp_tmp = 0;
|
| 557 |
+
for (int64_t row = 0; row < cur_qSplitSize; ++row) {
|
| 558 |
+
// apply scaling factor and max per row in fusion
|
| 559 |
+
{{kernel.kernel_name}}_mul_reduce_max_fusion_kernel(
|
| 560 |
+
qk_data + row * cur_kvSplitSize,
|
| 561 |
+
static_cast<accum_t>(1),
|
| 562 |
+
cur_kvSplitSize,
|
| 563 |
+
qk_data + row * cur_kvSplitSize,
|
| 564 |
+
tmp_max);
|
| 565 |
+
tmp_max = qk_max_data[row] > tmp_max ? qk_max_data[row] : tmp_max;
|
| 566 |
+
if (tmp_max == -std::numeric_limits<accum_t>::infinity()) {
|
| 567 |
+
// to avoid `nan = exp2f(-inf - (-inf))`
|
| 568 |
+
{{kernel.kernel_name}}_fill_stub(
|
| 569 |
+
{{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize,
|
| 570 |
+
static_cast<scalar_t>(0), cur_kvSplitSize);
|
| 571 |
+
} else {
|
| 572 |
+
tmp_sum = tmp_max;
|
| 573 |
+
// qk <- exp(qk - max) and sum per row
|
| 574 |
+
{{kernel.kernel_name}}_exp_reduce_sum_fusion_kernel(
|
| 575 |
+
qk_data + row * cur_kvSplitSize, cur_kvSplitSize,
|
| 576 |
+
{{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize,
|
| 577 |
+
tmp_sum);
|
| 578 |
+
// exp_tmp <- exp(max[row] - max)
|
| 579 |
+
exp_tmp = std::exp(qk_max_data[row] - tmp_max);
|
| 580 |
+
// sum[row] <- sum + exp_tmp * sum[row]
|
| 581 |
+
qk_sum_data[row] = tmp_sum + exp_tmp * qk_sum_data[row];
|
| 582 |
+
// max[row] <- max
|
| 583 |
+
qk_max_data[row] = tmp_max;
|
| 584 |
+
// dst <- dst * exp_tmp
|
| 585 |
+
if (n_idx > 0) {
|
| 586 |
+
at::vec::map<accum_t>(
|
| 587 |
+
[exp_tmp](Vec x) { return x * Vec(exp_tmp); },
|
| 588 |
+
dst_data + row * headSize_v,
|
| 589 |
+
dst_data + row * headSize_v,
|
| 590 |
+
headSize_v);
|
| 591 |
+
}
|
| 592 |
+
}
|
| 593 |
+
if (need_pack && cur_kvSplitSize % 2 != 0) {
|
| 594 |
+
// Pad: [qSplitSize, cur_kvSplitSize] -> [qSplitSize, cur_kvSplitSize + 1]
|
| 595 |
+
*(qk_reduced_data + row * (1 + cur_kvSplitSize) + cur_kvSplitSize) = scalar_t(0);
|
| 596 |
+
}
|
| 597 |
+
}
|
| 598 |
+
// Calculate Softmax(q @ k.T) @ v
|
| 599 |
+
if (!need_pack) {
|
| 600 |
+
auto v_addr =
|
| 601 |
+
v_data + i_kv * vStrideB + j_kv * vStrideH + n * vStrideN;
|
| 602 |
+
// Fallback Half brgemm is slower than micro gemm
|
| 603 |
+
if (!std::is_same_v<scalar_t, at::Half>) {
|
| 604 |
+
at::native::cpublas::brgemm(
|
| 605 |
+
cur_qSplitSize,
|
| 606 |
+
headSize_v,
|
| 607 |
+
cur_ekvSplitSize,
|
| 608 |
+
cur_ekvSplitSize,
|
| 609 |
+
vStrideN,
|
| 610 |
+
headSize_v,
|
| 611 |
+
n_idx > 0,
|
| 612 |
+
{{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data),
|
| 613 |
+
v_addr,
|
| 614 |
+
dst_data,
|
| 615 |
+
need_pack);
|
| 616 |
+
} else {
|
| 617 |
+
if (n_idx > 0) {
|
| 618 |
+
{{kernel.kernel_name}}_kernel_micro_gemm<static_cast<bool>(true)>(
|
| 619 |
+
{{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data),
|
| 620 |
+
v_addr,
|
| 621 |
+
dst_data,
|
| 622 |
+
cur_qSplitSize,
|
| 623 |
+
headSize_v,
|
| 624 |
+
cur_ekvSplitSize,
|
| 625 |
+
cur_ekvSplitSize,
|
| 626 |
+
vStrideN,
|
| 627 |
+
headSize_v);
|
| 628 |
+
} else {
|
| 629 |
+
{{kernel.kernel_name}}_kernel_micro_gemm<static_cast<bool>(false)>(
|
| 630 |
+
{{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data),
|
| 631 |
+
v_addr,
|
| 632 |
+
dst_data,
|
| 633 |
+
cur_qSplitSize,
|
| 634 |
+
headSize_v,
|
| 635 |
+
cur_ekvSplitSize,
|
| 636 |
+
cur_ekvSplitSize,
|
| 637 |
+
vStrideN,
|
| 638 |
+
headSize_v);
|
| 639 |
+
}
|
| 640 |
+
}
|
| 641 |
+
} else {
|
| 642 |
+
int64_t psize = n / kvSplitSize * ekvSplitSize;
|
| 643 |
+
at::native::cpublas::brgemm(
|
| 644 |
+
cur_qSplitSize,
|
| 645 |
+
headSize_v,
|
| 646 |
+
cur_ekvSplitSize,
|
| 647 |
+
cur_ekvSplitSize,
|
| 648 |
+
headSize_v,
|
| 649 |
+
headSize_v,
|
| 650 |
+
n_idx > 0,
|
| 651 |
+
qk_reduced_data,
|
| 652 |
+
value_reorder_ptr +
|
| 653 |
+
i_kv * num_head_k * kv_padding_size * headSize_v +
|
| 654 |
+
j_kv * kv_padding_size * headSize_v + psize * headSize_v,
|
| 655 |
+
dst_data,
|
| 656 |
+
need_pack);
|
| 657 |
+
}
|
| 658 |
+
}
|
| 659 |
+
|
| 660 |
+
// dst <- dst / sum[row]
|
| 661 |
+
// reorder MHA output with strides
|
| 662 |
+
for (int64_t row = 0; row < cur_qSplitSize; ++row) {
|
| 663 |
+
// Row sums for full masked out rows are 0, we set them to 1
|
| 664 |
+
// in order to avoid NaNs in the output and instead set fully
|
| 665 |
+
// masked out rows to 0
|
| 666 |
+
qk_max_data[row] = qk_max_data[row] == -std::numeric_limits<accum_t>::infinity() ? 0 : qk_max_data[row];
|
| 667 |
+
qk_sum_data[row] = qk_sum_data[row] == 0 ? 1 : qk_sum_data[row];
|
| 668 |
+
accum_t sum_reciprocal = 1 / qk_sum_data[row];
|
| 669 |
+
at::vec::map<scalar_t>(
|
| 670 |
+
[sum_reciprocal, is_skip_kv](Vec x) { return is_skip_kv ? Vec(0.0) : x * Vec(sum_reciprocal); },
|
| 671 |
+
out_data + i * oStrideB + j * oStrideH + m * oStrideM + row * oStrideM,
|
| 672 |
+
dst_data + row * headSize_v,
|
| 673 |
+
headSize_v);
|
| 674 |
+
}
|
| 675 |
+
|
| 676 |
+
// Move to the next query
|
| 677 |
+
at::native::data_index_step(i, batchSize, j, num_head, k, qSlice);
|
| 678 |
+
}
|
| 679 |
+
|
| 680 |
+
at::native::cpublas::brgemm_release(need_pack);
|
| 681 |
+
|
| 682 |
+
});
|
| 683 |
+
}
|
| 684 |
+
"""
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
class CppFlexAttentionTemplate(CppTemplate):
|
| 688 |
+
def __init__(
|
| 689 |
+
self,
|
| 690 |
+
input_nodes,
|
| 691 |
+
layout: ir.Layout,
|
| 692 |
+
scale,
|
| 693 |
+
score_mod,
|
| 694 |
+
mask_mod,
|
| 695 |
+
kv_block_size,
|
| 696 |
+
q_block_size,
|
| 697 |
+
has_other_buffer,
|
| 698 |
+
no_full_kv_block,
|
| 699 |
+
fake_buffers,
|
| 700 |
+
len_score_other,
|
| 701 |
+
len_mask_other,
|
| 702 |
+
kernel_input_name_to_buffer,
|
| 703 |
+
block_vars,
|
| 704 |
+
) -> None:
|
| 705 |
+
assert layout.dtype in [torch.float, torch.bfloat16, torch.float16]
|
| 706 |
+
super().__init__("flex_attention", input_nodes, layout, parallel_num_threads())
|
| 707 |
+
self.scale = scale
|
| 708 |
+
self.score_mod = score_mod
|
| 709 |
+
self.mask_mod = mask_mod
|
| 710 |
+
self.score_buf_name = (
|
| 711 |
+
V.graph.register_buffer(self.score_mod) if self.score_mod else None
|
| 712 |
+
)
|
| 713 |
+
self.mask_buf_name = (
|
| 714 |
+
V.graph.register_buffer(self.mask_mod) if self.mask_mod else None
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
def get_idx(buf_name):
|
| 718 |
+
match = re.search(r"\d+", buf_name)
|
| 719 |
+
assert match, f"incorrect score buf name: {buf_name}"
|
| 720 |
+
return match.group()
|
| 721 |
+
|
| 722 |
+
self.score_buf_idx = (
|
| 723 |
+
get_idx(self.score_buf_name) if self.score_buf_name else None
|
| 724 |
+
)
|
| 725 |
+
self.mask_buf_idx = get_idx(self.mask_buf_name) if self.mask_buf_name else None
|
| 726 |
+
self.kv_block_size = kv_block_size
|
| 727 |
+
self.q_block_size = q_block_size
|
| 728 |
+
self.has_other_buffer = has_other_buffer
|
| 729 |
+
self.no_full_kv_block = no_full_kv_block
|
| 730 |
+
self.other_buffer_input_offset = 2
|
| 731 |
+
if self.no_full_kv_block:
|
| 732 |
+
self.other_buffer_input_offset = 0
|
| 733 |
+
self.fake_buffers = fake_buffers
|
| 734 |
+
self.len_score_other = len_score_other
|
| 735 |
+
self.len_mask_other = len_mask_other
|
| 736 |
+
self.kernel_input_name_to_buffer = kernel_input_name_to_buffer
|
| 737 |
+
self.block_vars = block_vars
|
| 738 |
+
self.extra_sizevars = list(
|
| 739 |
+
OrderedSet(
|
| 740 |
+
val
|
| 741 |
+
for val in self.kernel_input_name_to_buffer.values()
|
| 742 |
+
if isinstance(val, sympy.Symbol)
|
| 743 |
+
)
|
| 744 |
+
)
|
| 745 |
+
self.other_buf_start_idx = 5
|
| 746 |
+
self.score_mod_other_buffers = (
|
| 747 |
+
self.input_nodes[
|
| 748 |
+
self.other_buf_start_idx
|
| 749 |
+
+ self.other_buffer_input_offset : self.other_buf_start_idx
|
| 750 |
+
+ self.other_buffer_input_offset
|
| 751 |
+
+ self.len_score_other
|
| 752 |
+
]
|
| 753 |
+
if self.has_other_buffer
|
| 754 |
+
else None
|
| 755 |
+
)
|
| 756 |
+
self.mask_mod_other_buffers = (
|
| 757 |
+
self.input_nodes[
|
| 758 |
+
self.other_buf_start_idx
|
| 759 |
+
+ self.other_buffer_input_offset
|
| 760 |
+
+ self.len_score_other :
|
| 761 |
+
]
|
| 762 |
+
if self.has_other_buffer
|
| 763 |
+
else None
|
| 764 |
+
)
|
| 765 |
+
self.other_ptr_data = {} # type: ignore[var-annotated]
|
| 766 |
+
|
| 767 |
+
def update_kernel_args(self, kernel_args):
|
| 768 |
+
kernel_args.update(
|
| 769 |
+
{
|
| 770 |
+
key: value
|
| 771 |
+
for key, value in self.kernel_input_name_to_buffer.items()
|
| 772 |
+
if not isinstance(value, sympy.Symbol)
|
| 773 |
+
}
|
| 774 |
+
)
|
| 775 |
+
return kernel_args
|
| 776 |
+
|
| 777 |
+
def generate_other_buffer(self, buf_list, start_offset, len_attr, kernel_args):
|
| 778 |
+
kernel_input_name_to_buffer_name = {
|
| 779 |
+
key: value if isinstance(value, sympy.Symbol) else value.get_name()
|
| 780 |
+
for key, value in self.kernel_input_name_to_buffer.items()
|
| 781 |
+
}
|
| 782 |
+
|
| 783 |
+
def get_arg(name):
|
| 784 |
+
return kernel_input_name_to_buffer_name.get(name)
|
| 785 |
+
|
| 786 |
+
def get_arg_name(name):
|
| 787 |
+
if isinstance(get_arg(name), sympy.Symbol):
|
| 788 |
+
return kernel_args.sizevars.get(get_arg(name))
|
| 789 |
+
return kernel_args.input_buffers.get(get_arg(name))
|
| 790 |
+
|
| 791 |
+
if not self.has_other_buffer:
|
| 792 |
+
return ""
|
| 793 |
+
|
| 794 |
+
if start_offset == -1:
|
| 795 |
+
start_offset = self.len_score_other
|
| 796 |
+
|
| 797 |
+
length = getattr(self, len_attr)
|
| 798 |
+
for i in range(length):
|
| 799 |
+
pointer = f"in_ptr{self.other_buf_start_idx + start_offset + i}"
|
| 800 |
+
buffer_key = f"{buf_list}_{i}"
|
| 801 |
+
if pointer not in self.other_ptr_data:
|
| 802 |
+
self.other_ptr_data[pointer] = (
|
| 803 |
+
get_arg_name(buffer_key),
|
| 804 |
+
get_arg(buffer_key),
|
| 805 |
+
)
|
| 806 |
+
|
| 807 |
+
return "\n".join(
|
| 808 |
+
f"auto {ptr} = {name};" for ptr, (name, _) in self.other_ptr_data.items()
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
def modification(self, subgraph_buffer, output_name, output_idx):
|
| 812 |
+
assert isinstance(subgraph_buffer, ir.ComputedBuffer)
|
| 813 |
+
subgraph_buffer_data = subgraph_buffer.data
|
| 814 |
+
from ..loop_body import LoopBody
|
| 815 |
+
from ..utils import sympy_index_symbol_with_prefix, SymT
|
| 816 |
+
from ..virtualized import V
|
| 817 |
+
from .cpp import CppKernelProxy, KernelGroup, ParallelDepth
|
| 818 |
+
|
| 819 |
+
kernel_group = KernelGroup()
|
| 820 |
+
kernel_input_args = {
|
| 821 |
+
"score": "in_ptr0",
|
| 822 |
+
"b": "in_ptr1",
|
| 823 |
+
"h": "in_ptr2",
|
| 824 |
+
"q_idx": "in_ptr3",
|
| 825 |
+
"kv_idx": "in_ptr4",
|
| 826 |
+
}
|
| 827 |
+
if self.has_other_buffer:
|
| 828 |
+
kernel_input_args.update(
|
| 829 |
+
{arg: ptr for ptr, (_, arg) in self.other_ptr_data.items()}
|
| 830 |
+
)
|
| 831 |
+
|
| 832 |
+
kernel_output_args = {output_name: f"out_ptr{output_idx}"}
|
| 833 |
+
|
| 834 |
+
args = kernel_group.args
|
| 835 |
+
for name, inp in kernel_input_args.items():
|
| 836 |
+
args.input_buffers[name] = inp
|
| 837 |
+
|
| 838 |
+
for name, inp in kernel_output_args.items():
|
| 839 |
+
args.output_buffers[name] = inp
|
| 840 |
+
|
| 841 |
+
for name in self.extra_sizevars:
|
| 842 |
+
args.sizevars[name] = f"k{name}"
|
| 843 |
+
|
| 844 |
+
kernel_group.args = args
|
| 845 |
+
|
| 846 |
+
cpp_kernel_proxy = CppKernelProxy(kernel_group)
|
| 847 |
+
bodies = []
|
| 848 |
+
var_sizes_list = []
|
| 849 |
+
var_sizes = tuple(subgraph_buffer.get_size())
|
| 850 |
+
var_ranges = {
|
| 851 |
+
sympy_index_symbol_with_prefix(SymT.INDEX, i): sz
|
| 852 |
+
for i, sz in enumerate(var_sizes)
|
| 853 |
+
}
|
| 854 |
+
|
| 855 |
+
dst_layout = subgraph_buffer.get_layout()
|
| 856 |
+
output_index = dst_layout.make_indexer()([*var_ranges.keys()])
|
| 857 |
+
|
| 858 |
+
def fn(*args):
|
| 859 |
+
V.ops.store(
|
| 860 |
+
output_name,
|
| 861 |
+
output_index,
|
| 862 |
+
subgraph_buffer_data.make_loader()(args).value,
|
| 863 |
+
)
|
| 864 |
+
|
| 865 |
+
body = LoopBody(
|
| 866 |
+
fn,
|
| 867 |
+
(list(var_ranges.keys())),
|
| 868 |
+
var_ranges,
|
| 869 |
+
list(var_ranges.keys()),
|
| 870 |
+
tuple(),
|
| 871 |
+
)
|
| 872 |
+
|
| 873 |
+
from ..loop_body import MemoryUsageType
|
| 874 |
+
|
| 875 |
+
assert all(
|
| 876 |
+
mem.buffer_name in kernel_group.args.input_buffers
|
| 877 |
+
for mem in body.memory_usage[MemoryUsageType.LOAD]
|
| 878 |
+
), (
|
| 879 |
+
"All the buffers in the score and mask subgraph should be in kernel_group.args.input_buffers"
|
| 880 |
+
)
|
| 881 |
+
|
| 882 |
+
bodies.append(body)
|
| 883 |
+
var_sizes_list.append((var_sizes, ()))
|
| 884 |
+
|
| 885 |
+
cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list)
|
| 886 |
+
|
| 887 |
+
def max_parallel_depth():
|
| 888 |
+
return ParallelDepth(parallel_depth=0, start_depth=0)
|
| 889 |
+
|
| 890 |
+
# This loop is not parallelized since it is not the outermost loop.
|
| 891 |
+
with patch.object(
|
| 892 |
+
cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth
|
| 893 |
+
):
|
| 894 |
+
kernel_group.finalize_kernel(cpp_kernel_proxy, [])
|
| 895 |
+
output_code = kernel_group.loops_code.getvalue()
|
| 896 |
+
|
| 897 |
+
var_q_symbol, var_kv_symbol = self.block_vars
|
| 898 |
+
# See [Note] Handle the case where the split sizes are not statically known.
|
| 899 |
+
# We don't know the value of qBlockSize and rkvBlockSize during compilation time
|
| 900 |
+
# thus we've represented them by symbols.
|
| 901 |
+
# We change the symbol strings back to "cur_qSplitSize" and "cur_kvSplitSize"
|
| 902 |
+
# in the generated code thus they'll be filled with the real value during runtime.
|
| 903 |
+
if var_q_symbol in kernel_group.args.sizevars:
|
| 904 |
+
output_code = output_code.replace(
|
| 905 |
+
kernel_group.args.sizevars[var_q_symbol], "cur_qSplitSize"
|
| 906 |
+
)
|
| 907 |
+
if var_kv_symbol in kernel_group.args.sizevars:
|
| 908 |
+
output_code = output_code.replace(
|
| 909 |
+
kernel_group.args.sizevars[var_kv_symbol], "cur_kvSplitSize"
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
return output_code
|
| 913 |
+
|
| 914 |
+
@staticmethod
|
| 915 |
+
def add_choices(
|
| 916 |
+
choices,
|
| 917 |
+
input_nodes,
|
| 918 |
+
layout,
|
| 919 |
+
scale,
|
| 920 |
+
score_mod,
|
| 921 |
+
mask_mod,
|
| 922 |
+
kv_block_size,
|
| 923 |
+
q_block_size,
|
| 924 |
+
has_other_buffer,
|
| 925 |
+
no_full_kv_block,
|
| 926 |
+
fake_buffers,
|
| 927 |
+
len_score_other,
|
| 928 |
+
len_mask_other,
|
| 929 |
+
kernel_input_name_to_buffer,
|
| 930 |
+
block_vars,
|
| 931 |
+
):
|
| 932 |
+
def preprocessor(input_nodes, layout):
|
| 933 |
+
return input_nodes, layout
|
| 934 |
+
|
| 935 |
+
def postprocessor(output):
|
| 936 |
+
return output
|
| 937 |
+
|
| 938 |
+
template = DataProcessorTemplateWrapper(
|
| 939 |
+
CppFlexAttentionTemplate,
|
| 940 |
+
preprocessor,
|
| 941 |
+
postprocessor,
|
| 942 |
+
input_nodes=input_nodes,
|
| 943 |
+
layout=layout,
|
| 944 |
+
scale=scale,
|
| 945 |
+
score_mod=score_mod,
|
| 946 |
+
mask_mod=mask_mod,
|
| 947 |
+
kv_block_size=kv_block_size,
|
| 948 |
+
q_block_size=q_block_size,
|
| 949 |
+
has_other_buffer=has_other_buffer,
|
| 950 |
+
no_full_kv_block=no_full_kv_block,
|
| 951 |
+
fake_buffers=fake_buffers,
|
| 952 |
+
len_score_other=len_score_other,
|
| 953 |
+
len_mask_other=len_mask_other,
|
| 954 |
+
kernel_input_name_to_buffer=kernel_input_name_to_buffer,
|
| 955 |
+
block_vars=block_vars,
|
| 956 |
+
)
|
| 957 |
+
template.maybe_append_choice(choices)
|
| 958 |
+
return template
|
| 959 |
+
|
| 960 |
+
def apply_score_mod(self, score, b, h, q_idx, kv_idx):
|
| 961 |
+
return self.score_mod.graph_module(score, b, h, q_idx, kv_idx).item()
|
| 962 |
+
|
| 963 |
+
def render( # type: ignore[override,return]
|
| 964 |
+
self,
|
| 965 |
+
kernel,
|
| 966 |
+
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
|
| 967 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 968 |
+
**kwargs,
|
| 969 |
+
) -> str:
|
| 970 |
+
if epilogue_nodes is not None and epilogue_nodes != []:
|
| 971 |
+
raise NotImplementedError(
|
| 972 |
+
"Unsupported for `epilogue_nodes` in CppFlexAttentionTemplate."
|
| 973 |
+
)
|
| 974 |
+
# Query (Batch x Num_heads x Q_seq_len x Dim_per_head)
|
| 975 |
+
# -> (Batch x Q_seq_len x Num_heads x Dim_per_head)
|
| 976 |
+
# Key (Batch x Num_heads x KV_seq_len x Dim_per_head)
|
| 977 |
+
# -> (Batch x KV_seq_len x Num_heads x Dim_per_head)
|
| 978 |
+
# Value (Batch x Num_heads x KV_seq_len x Dim_per_head)
|
| 979 |
+
# -> (Batch x KV_seq_len x Num_heads x Dim_per_head)
|
| 980 |
+
|
| 981 |
+
query = kernel.permute(self.input_nodes[0], [0, 2, 1, 3])
|
| 982 |
+
key = kernel.permute(self.input_nodes[1], [0, 2, 1, 3])
|
| 983 |
+
value = kernel.permute(self.input_nodes[2], [0, 2, 1, 3])
|
| 984 |
+
self.accumulate_dtype = torch.float
|
| 985 |
+
self.input_dtype = query.layout.dtype
|
| 986 |
+
|
| 987 |
+
num_threads = parallel_num_threads()
|
| 988 |
+
assert isinstance(self.output_node, ir.IRNode)
|
| 989 |
+
buf_out: ir.IRNode = TensorBox.create(self.output_node)
|
| 990 |
+
if template_buffer_node is not None:
|
| 991 |
+
buf_out = template_buffer_node
|
| 992 |
+
options = dict(
|
| 993 |
+
query=query,
|
| 994 |
+
key=key,
|
| 995 |
+
value=value,
|
| 996 |
+
kv_num_blocks=self.input_nodes[3],
|
| 997 |
+
kv_indices=self.input_nodes[4],
|
| 998 |
+
full_kv_num_blocks=(
|
| 999 |
+
self.input_nodes[5] if not self.no_full_kv_block else None
|
| 1000 |
+
),
|
| 1001 |
+
full_kv_indices=self.input_nodes[6] if not self.no_full_kv_block else None,
|
| 1002 |
+
score_mod_other_buffers=self.score_mod_other_buffers,
|
| 1003 |
+
mask_mod_other_buffers=self.mask_mod_other_buffers,
|
| 1004 |
+
scale=self.scale,
|
| 1005 |
+
has_full_kv_block=not self.no_full_kv_block,
|
| 1006 |
+
accumulate_dtype=self.accumulate_dtype,
|
| 1007 |
+
query_dtype=self.input_dtype,
|
| 1008 |
+
kvBlockSize=self.kv_block_size,
|
| 1009 |
+
qBlockSize=self.q_block_size,
|
| 1010 |
+
template=self,
|
| 1011 |
+
output=buf_out,
|
| 1012 |
+
kernel=kernel,
|
| 1013 |
+
num_thread=num_threads,
|
| 1014 |
+
score_mod=self.score_mod,
|
| 1015 |
+
mask_mod=self.mask_mod,
|
| 1016 |
+
score_buf_name=self.score_buf_name,
|
| 1017 |
+
mask_buf_name=self.mask_buf_name,
|
| 1018 |
+
score_buf_idx=self.score_buf_idx,
|
| 1019 |
+
mask_buf_idx=self.mask_buf_idx,
|
| 1020 |
+
)
|
| 1021 |
+
with contextlib.ExitStack() as stack:
|
| 1022 |
+
for buf in self.fake_buffers:
|
| 1023 |
+
stack.enter_context(
|
| 1024 |
+
patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf))
|
| 1025 |
+
)
|
| 1026 |
+
return self._template_from_string(FLEX_ATTENTION_TEMPLATE).render(**options)
|
| 1027 |
+
|
| 1028 |
+
def codegen_softmax_fusion(self, kernel_name: str):
|
| 1029 |
+
# TODO: use inductor IR to rewrite those fusions
|
| 1030 |
+
return self._template_from_string(SOFTMAX_FUSIONS).render(
|
| 1031 |
+
dict(kernel_name=kernel_name)
|
| 1032 |
+
)
|
| 1033 |
+
|
| 1034 |
+
def codegen_brgemm_pack_function(self, kernel_name: str):
|
| 1035 |
+
# TODO: make them general for common bmm templates
|
| 1036 |
+
return self._template_from_string(BRGEMM_PACK_FUNCTIONS).render(
|
| 1037 |
+
dict(kernel_name=kernel_name)
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
def codegen_allocate_buffer(self, buffer_name: str, buffer_dtype, buffer_size):
|
| 1041 |
+
return self._template_from_string(ALLOCATE_BUFFER).render(
|
| 1042 |
+
dict(
|
| 1043 |
+
buffer_name=buffer_name,
|
| 1044 |
+
buffer_dtype=buffer_dtype,
|
| 1045 |
+
buffer_size=buffer_size,
|
| 1046 |
+
)
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
def micro_gemm_define(self, kernel_name: str):
|
| 1050 |
+
from torch._inductor.codegen.cpp_gemm_template import (
|
| 1051 |
+
CppTemplateKernel,
|
| 1052 |
+
parallel_num_threads,
|
| 1053 |
+
)
|
| 1054 |
+
from torch._inductor.codegen.cpp_micro_gemm import CppMicroGemmFP32Vec
|
| 1055 |
+
from torch._inductor.virtualized import V
|
| 1056 |
+
|
| 1057 |
+
micro_gemm_trans = CppMicroGemmFP32Vec(
|
| 1058 |
+
kernel_name + "_kernel_micro_gemm_transpose_b",
|
| 1059 |
+
self.input_dtype,
|
| 1060 |
+
self.input_dtype,
|
| 1061 |
+
self.accumulate_dtype,
|
| 1062 |
+
self.accumulate_dtype,
|
| 1063 |
+
GemmBlocking(1, 16, 1),
|
| 1064 |
+
1,
|
| 1065 |
+
True,
|
| 1066 |
+
True,
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
micro_gemm = CppMicroGemmFP32Vec(
|
| 1070 |
+
kernel_name + "_kernel_micro_gemm",
|
| 1071 |
+
self.input_dtype,
|
| 1072 |
+
self.input_dtype,
|
| 1073 |
+
self.accumulate_dtype,
|
| 1074 |
+
self.accumulate_dtype,
|
| 1075 |
+
GemmBlocking(1, 16, 1),
|
| 1076 |
+
1,
|
| 1077 |
+
True,
|
| 1078 |
+
False,
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
with V.set_graph_handler(V.graph):
|
| 1082 |
+
kernel = CppTemplateKernel("cpp_micro_gemm", parallel_num_threads())
|
| 1083 |
+
code_trans = micro_gemm_trans.codegen_define(kernel)
|
| 1084 |
+
code = micro_gemm.codegen_define(kernel)
|
| 1085 |
+
return code + code_trans
|
| 1086 |
+
|
| 1087 |
+
def codegen_micro_gemm(self, kernel_name: str):
|
| 1088 |
+
micro_gemm = self.micro_gemm_define(kernel_name)
|
| 1089 |
+
GEMM_SOURCE_CODE = MICRO_GEMM_TEMPLATE.replace("GEMM_DEFINE", micro_gemm)
|
| 1090 |
+
return self._template_from_string(GEMM_SOURCE_CODE).render()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_gemm_template.py
ADDED
|
@@ -0,0 +1,1819 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
import logging
|
| 4 |
+
import math
|
| 5 |
+
from collections.abc import Callable
|
| 6 |
+
from functools import lru_cache
|
| 7 |
+
from typing import Any, cast, Optional, TypeVar, Union
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.utils
|
| 12 |
+
from torch.utils._ordered_set import OrderedSet
|
| 13 |
+
|
| 14 |
+
from ..._dynamo.utils import counters
|
| 15 |
+
from .. import config, ir, lowering as L
|
| 16 |
+
from ..kernel.mm_common import mm_args
|
| 17 |
+
from ..select_algorithm import DataProcessorTemplateWrapper
|
| 18 |
+
from ..utils import (
|
| 19 |
+
has_free_symbols,
|
| 20 |
+
is_same_mkldnn_tensor,
|
| 21 |
+
is_same_tensor,
|
| 22 |
+
parallel_num_threads,
|
| 23 |
+
)
|
| 24 |
+
from ..virtualized import ops, V
|
| 25 |
+
from .cpp import get_export_declaration
|
| 26 |
+
from .cpp_micro_gemm import (
|
| 27 |
+
CppMicroBrgemm,
|
| 28 |
+
CppMicroGemm,
|
| 29 |
+
CppMicroGemmAMX,
|
| 30 |
+
CppMicroGemmFP32Vec,
|
| 31 |
+
create_micro_gemm,
|
| 32 |
+
is_int8_woq_gemm_small_m_dim_corner_case,
|
| 33 |
+
LayoutType,
|
| 34 |
+
)
|
| 35 |
+
from .cpp_template import CppTemplate
|
| 36 |
+
from .cpp_template_kernel import CppTemplateKernel
|
| 37 |
+
from .cpp_utils import (
|
| 38 |
+
create_epilogue_with_attr,
|
| 39 |
+
DTYPE_TO_CPP,
|
| 40 |
+
GemmBlocking,
|
| 41 |
+
get_gemm_template_output_and_compute_dtype,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
log = logging.getLogger(__name__)
|
| 46 |
+
|
| 47 |
+
GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK = r"""
|
| 48 |
+
constexpr int64_t num_threads = {{num_threads}};
|
| 49 |
+
constexpr int64_t N = {{N}};
|
| 50 |
+
constexpr int64_t K = {{K}};
|
| 51 |
+
constexpr int64_t Mr = {{micro_gemm.register_blocking.block_m}};
|
| 52 |
+
constexpr int64_t Nr = {{micro_gemm.register_blocking.block_n}};
|
| 53 |
+
constexpr int64_t Kr = {{micro_gemm.register_blocking.block_k}};
|
| 54 |
+
constexpr int64_t Nr_blocks = (N + Nr - 1) / Nr;
|
| 55 |
+
constexpr int64_t Kr_blocks = (K + Kr - 1) / Kr;
|
| 56 |
+
{%- if is_dynamic_M %}
|
| 57 |
+
const int64_t M = {{kernel.size(GemmOut, 0)}};
|
| 58 |
+
const int64_t Mr_blocks = (M + Mr - 1) / Mr;
|
| 59 |
+
{%- else %}
|
| 60 |
+
constexpr int64_t M = {{kernel.size(GemmOut, 0)}};
|
| 61 |
+
constexpr int64_t Mr_blocks = (M + Mr - 1) / Mr;
|
| 62 |
+
{%- endif %}
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED = r"""
|
| 66 |
+
{%- if is_dynamic_M %}
|
| 67 |
+
{%- if num_threads > 1 %}
|
| 68 |
+
int64_t Mt_blocks, Nt_blocks, Kt_blocks;
|
| 69 |
+
mm_get_thread_blocking(num_threads, {{config.cpp.gemm_max_k_slices}}, M, N, K, Mr, Nr, Kr, Mt_blocks, Nt_blocks, Kt_blocks);
|
| 70 |
+
{%- else %}
|
| 71 |
+
const auto Mt_blocks = Mr_blocks;
|
| 72 |
+
const auto Nt_blocks = Nr_blocks;
|
| 73 |
+
const auto Kt_blocks = Kr_blocks;
|
| 74 |
+
{%- endif %}
|
| 75 |
+
int64_t Mc_blocks, Nc_blocks, Kc_blocks;
|
| 76 |
+
uint32_t L1_cache_size = {{L1_cache_size}};
|
| 77 |
+
uint32_t L2_cache_size = {{L2_cache_size}};
|
| 78 |
+
mm_get_cache_blocking<{{kernel.dtype(X)}}, {{kernel.dtype(W)}}>(
|
| 79 |
+
num_threads,
|
| 80 |
+
M,
|
| 81 |
+
N,
|
| 82 |
+
K,
|
| 83 |
+
Mr,
|
| 84 |
+
Nr,
|
| 85 |
+
Kr,
|
| 86 |
+
Mt_blocks,
|
| 87 |
+
Nt_blocks,
|
| 88 |
+
Kt_blocks,
|
| 89 |
+
Mc_blocks,
|
| 90 |
+
Nc_blocks,
|
| 91 |
+
Kc_blocks,
|
| 92 |
+
L1_cache_size,
|
| 93 |
+
L2_cache_size
|
| 94 |
+
);
|
| 95 |
+
const int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks;
|
| 96 |
+
const int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks;
|
| 97 |
+
const int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks;
|
| 98 |
+
const int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks;
|
| 99 |
+
const int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks;
|
| 100 |
+
{%- else %}
|
| 101 |
+
constexpr int64_t Mt_blocks = {{template.thread_blocking(num_threads).block_m}};
|
| 102 |
+
constexpr int64_t Nt_blocks = {{template.thread_blocking(num_threads).block_n}};
|
| 103 |
+
constexpr int64_t Kt_blocks = {{template.thread_blocking(num_threads).block_k}};
|
| 104 |
+
constexpr int64_t Mc_blocks = {{template.cache_blocking(num_threads).block_m}};
|
| 105 |
+
constexpr int64_t Nc_blocks = {{template.cache_blocking(num_threads).block_n}};
|
| 106 |
+
constexpr int64_t Kc_blocks = {{template.cache_blocking(num_threads).block_k}};
|
| 107 |
+
constexpr int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks;
|
| 108 |
+
constexpr int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks;
|
| 109 |
+
constexpr int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks;
|
| 110 |
+
constexpr int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks;
|
| 111 |
+
constexpr int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks;
|
| 112 |
+
{%- endif %}
|
| 113 |
+
{%- if is_woq_int4 %}
|
| 114 |
+
int64_t group_size = *q_group_size;
|
| 115 |
+
{%- endif %}
|
| 116 |
+
|
| 117 |
+
// make sure all partitions are assigned
|
| 118 |
+
{{kernel.assert_function}}(
|
| 119 |
+
Mt_blocks * Nt_blocks * Kt_blocks * {{num_threads}} >= Mr_blocks * Nr_blocks * Kr_blocks,
|
| 120 |
+
"Not all partitions are assigned."
|
| 121 |
+
);
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
GEMM_TEMPLATE_MULTI_THREADS_PARAMS = r"""
|
| 125 |
+
const int tid = omp_get_thread_num();
|
| 126 |
+
const int64_t k_group_id = tid / num_Kt_blocks;
|
| 127 |
+
const int64_t k_slice_id = tid % num_Kt_blocks;
|
| 128 |
+
const int64_t n_group_id = k_group_id / num_Nt_blocks;
|
| 129 |
+
const int64_t n_slice_id = k_group_id % num_Nt_blocks;
|
| 130 |
+
const int64_t k_block_start = k_slice_id * Kt_blocks;
|
| 131 |
+
const int64_t k_block_end = std::min(k_block_start + Kt_blocks, Kr_blocks);
|
| 132 |
+
const int64_t n_block_start = n_slice_id * Nt_blocks;
|
| 133 |
+
const int64_t n_block_end = std::min(n_block_start + Nt_blocks, Nr_blocks);
|
| 134 |
+
const int64_t m_block_start = std::min(n_group_id * Mt_blocks, Mr_blocks);
|
| 135 |
+
const int64_t m_block_end = std::min(m_block_start + Mt_blocks, Mr_blocks);
|
| 136 |
+
const int64_t num_Mc_blocks_per_thread = (m_block_end - m_block_start + Mc_blocks - 1) / Mc_blocks;
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
GEMM_TEMPLATE_SINGLE_THREAD_PARAMS = r"""
|
| 140 |
+
constexpr int tid = 0;
|
| 141 |
+
constexpr int64_t k_group_id = 0;
|
| 142 |
+
constexpr int64_t k_slice_id = 0;
|
| 143 |
+
constexpr int64_t n_group_id = 0;
|
| 144 |
+
constexpr int64_t n_slice_id = 0;
|
| 145 |
+
constexpr int64_t m_block_start = 0;
|
| 146 |
+
constexpr int64_t n_block_start = 0;
|
| 147 |
+
constexpr int64_t n_block_end = Nr_blocks;
|
| 148 |
+
constexpr int64_t k_block_start = 0;
|
| 149 |
+
constexpr int64_t k_block_end = Kr_blocks;
|
| 150 |
+
{%- if is_dynamic_M %}
|
| 151 |
+
const int64_t num_Mc_blocks_per_thread = num_Mc_blocks;
|
| 152 |
+
const int64_t m_block_end = Mr_blocks;
|
| 153 |
+
{%- else %}
|
| 154 |
+
constexpr int64_t num_Mc_blocks_per_thread = num_Mc_blocks;
|
| 155 |
+
constexpr int64_t m_block_end = Mr_blocks;
|
| 156 |
+
{%- endif %}
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
GEMM_TEMPLATE_M_LOOP_PARAMS = r"""
|
| 160 |
+
const int64_t my_mc_block_id = (mc_block_id + n_slice_id) % num_Mc_blocks_per_thread;
|
| 161 |
+
const int64_t mc = m_block_start + my_mc_block_id * Mc_blocks;
|
| 162 |
+
const int64_t m_start = mc * Mr;
|
| 163 |
+
const int64_t m_end = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M);
|
| 164 |
+
const int64_t m_size = m_end - m_start;
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
GEMM_TEMPLATE_N_LOOP_PARAMS = r"""
|
| 168 |
+
const int64_t n_start = nc * Nr;
|
| 169 |
+
const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N);
|
| 170 |
+
const int64_t n_size = n_end - n_start;
|
| 171 |
+
// NB: assume we pad N, nc_block_end won't exceed padded N here.
|
| 172 |
+
const int64_t nc_block_end = std::min(nc + Nc_blocks, n_block_end);
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
GEMM_TEMPLATE_MICROKERNEL_DEF = r"""
|
| 176 |
+
{{template.header().getvalue()}}
|
| 177 |
+
|
| 178 |
+
{{micro_gemm.codegen_define(kernel)}}
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
GEMM_TEMPLATE_STUB_DEF = r"""
|
| 182 |
+
{%- if x_scale is not none %}
|
| 183 |
+
{%- set kernel_args = {"X": X, "W": W, "inp": inp, "x_scale": x_scale, "x_zp": x_zp, "w_scale": w_scale, "w_zp": w_zp,} %}
|
| 184 |
+
{%- elif is_woq_int4 %}
|
| 185 |
+
{%- set kernel_args = {"X": X, "W": W, "q_group_size": q_group_size, "qscale_and_zeros": qscale_and_zeros} %}
|
| 186 |
+
{%- else %}
|
| 187 |
+
{%- set kernel_args = {"X": X, "W": W, "inp": inp} %}
|
| 188 |
+
{%- endif %}
|
| 189 |
+
|
| 190 |
+
extern "C" {{export_declaration}}
|
| 191 |
+
{{kernel.def_kernel(inputs=kernel_args, outputs={"Y": Y}, aliases=aliases)}}
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
GEMM_TEMPLATE = r"""
|
| 195 |
+
{{ template.codegen_gemm_stub_def() }}
|
| 196 |
+
{
|
| 197 |
+
{{ kernel.maybe_codegen_profile() }}
|
| 198 |
+
{{ template.codegen_blocks(
|
| 199 |
+
num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W
|
| 200 |
+
) }}
|
| 201 |
+
|
| 202 |
+
{%- if maybe_k_slicing %}
|
| 203 |
+
std::unique_ptr<std::unique_ptr<{{DTYPE_TO_CPP[acc_buf_dtype]}}[]>[]> local_buf_ptrs;
|
| 204 |
+
if (num_Kt_blocks > 1) {
|
| 205 |
+
local_buf_ptrs.reset(new std::unique_ptr<{{DTYPE_TO_CPP[acc_buf_dtype]}}[]>[num_Mc_blocks * num_Nc_blocks * num_Kt_blocks]);
|
| 206 |
+
}
|
| 207 |
+
{%- endif %}
|
| 208 |
+
|
| 209 |
+
{%- if num_threads > 1 %}
|
| 210 |
+
#pragma omp parallel num_threads({{num_threads}})
|
| 211 |
+
{
|
| 212 |
+
{{ template.codegen_multi_threads_params()|indent(8, false) }}
|
| 213 |
+
{%- else %}
|
| 214 |
+
{
|
| 215 |
+
{{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }}
|
| 216 |
+
{%- endif %}
|
| 217 |
+
{{ micro_gemm.codegen_init(kernel) }}
|
| 218 |
+
{%- if use_local_acc %}
|
| 219 |
+
{%- set acc_buf_name = "local_acc_buf" %}
|
| 220 |
+
{{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }}
|
| 221 |
+
{%- endif %}
|
| 222 |
+
for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) {
|
| 223 |
+
{{ template.codegen_m_loop_params()|indent(12, false) }}
|
| 224 |
+
for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) {
|
| 225 |
+
{{ template.codegen_n_loop_params()|indent(16, false) }}
|
| 226 |
+
{%- if use_local_acc %}
|
| 227 |
+
{%- set acc = kernel.local_buffers[acc_buf_name] %}
|
| 228 |
+
{{ kernel.reinit_buffer_if_null(acc_buf_name) }}
|
| 229 |
+
{%- else %}
|
| 230 |
+
{%- set acc = kernel.slice_nd(GemmOut, [("m_start", "m_end"), ("n_start", "n_end")]) %}
|
| 231 |
+
{%- endif %}
|
| 232 |
+
for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) {
|
| 233 |
+
int64_t k_start = kc * Kr;
|
| 234 |
+
int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K);
|
| 235 |
+
{%- set tile_X = kernel.slice_nd(X, [("m_start", "m_end"), ("k_start", "k_end")]) %}
|
| 236 |
+
for (int64_t nci = nc; nci < nc_block_end; nci++) {
|
| 237 |
+
{%- set acc_slice = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")]) %}
|
| 238 |
+
{%- if template.should_block_weights and not is_woq_int4 %}
|
| 239 |
+
{%- set tile_W_3d = kernel.slice_nd(W, [("nci", "nci + 1"), ("k_start", "k_end"), ()]) %}
|
| 240 |
+
{%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %}
|
| 241 |
+
{%- else %}
|
| 242 |
+
{%- if is_woq_int4 %}
|
| 243 |
+
{%- set tile_W = kernel.slice_nd(W, [("nci * Nr", "(nci + 1) * Nr"), ("k_start * Nr / 2", "k_end * Nr / 2")]) %}
|
| 244 |
+
{%- set tile_qparam = kernel.slice_nd(
|
| 245 |
+
qscale_and_zeros, [("k_start // group_size", "k_end // group_size"), ("nci * Nr", "(nci + 1) * Nr"), ()]) %}
|
| 246 |
+
{%- else %}
|
| 247 |
+
{%- set tile_W = kernel.slice_nd(W, [("k_start", "k_end"), ("n_start", "n_start + n_size")]) %}
|
| 248 |
+
{%- set tile_qparam = None %}
|
| 249 |
+
{%- endif %}
|
| 250 |
+
{%- endif %}
|
| 251 |
+
if (kc == k_block_start) {
|
| 252 |
+
{{ micro_gemm.codegen_call(kernel,
|
| 253 |
+
tile_X,
|
| 254 |
+
tile_W,
|
| 255 |
+
acc_slice,
|
| 256 |
+
accum=False,
|
| 257 |
+
qscale_and_zeros=tile_qparam)|indent(28, false)
|
| 258 |
+
}}
|
| 259 |
+
} else {
|
| 260 |
+
{{ micro_gemm.codegen_call(kernel,
|
| 261 |
+
tile_X,
|
| 262 |
+
tile_W,
|
| 263 |
+
acc_slice,
|
| 264 |
+
accum=True,
|
| 265 |
+
qscale_and_zeros=tile_qparam)|indent(28, false)
|
| 266 |
+
}}
|
| 267 |
+
}
|
| 268 |
+
}
|
| 269 |
+
}
|
| 270 |
+
{%- if maybe_k_slicing %}
|
| 271 |
+
if (num_Kt_blocks > 1) {
|
| 272 |
+
const int64_t mxn_cache_block_id = (mc / Mc_blocks) * num_Nc_blocks + nc;
|
| 273 |
+
local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + k_slice_id].reset(
|
| 274 |
+
{{ kernel.release_buffer(acc_buf_name) }});
|
| 275 |
+
} else
|
| 276 |
+
{%- endif %}
|
| 277 |
+
{
|
| 278 |
+
{%- set tile_Y = kernel.slice_nd(Y_2d, [("m_start", "m_end"), ("n_start", "n_end")]) %}
|
| 279 |
+
{%- set tile_acc = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("0", "n_end - n_start")]) %}
|
| 280 |
+
{{ kernel.store_output(
|
| 281 |
+
tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers
|
| 282 |
+
)|indent(20, false)
|
| 283 |
+
}}
|
| 284 |
+
}
|
| 285 |
+
}
|
| 286 |
+
}
|
| 287 |
+
{%- if maybe_k_slicing %}
|
| 288 |
+
if (num_Kt_blocks > 1) {
|
| 289 |
+
#pragma omp barrier
|
| 290 |
+
for (int64_t mc = m_block_start; mc < m_block_end; mc += Mc_blocks) {
|
| 291 |
+
// We slice M-dim and each thread in the k-slicing group works on a slice
|
| 292 |
+
const int64_t m_start_unsliced = mc * Mr;
|
| 293 |
+
const int64_t m_end_unsliced = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M);
|
| 294 |
+
const int64_t m_size_unsliced = m_end_unsliced - m_start_unsliced;
|
| 295 |
+
const int64_t m_slice_size = (m_size_unsliced + num_Kt_blocks - 1) / num_Kt_blocks;
|
| 296 |
+
const int64_t m_start = std::min(m_start_unsliced + m_slice_size * k_slice_id, m_end_unsliced);
|
| 297 |
+
const int64_t m_end = std::min(m_start_unsliced + m_slice_size * (k_slice_id + 1), m_end_unsliced);
|
| 298 |
+
const int64_t m_size = m_end - m_start;
|
| 299 |
+
const int64_t m_offset = m_start - m_start_unsliced;
|
| 300 |
+
for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) {
|
| 301 |
+
const int64_t n_start = nc * Nr;
|
| 302 |
+
const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N);
|
| 303 |
+
const int64_t n_size = n_end - n_start;
|
| 304 |
+
const int64_t mxn_cache_block_id = (mc / Mc_blocks) * num_Nc_blocks + nc;
|
| 305 |
+
auto {{acc_buf_name}} = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks].get();
|
| 306 |
+
for (int64_t other_slice = 1; other_slice < num_Kt_blocks; other_slice++) {
|
| 307 |
+
auto other_acc = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + other_slice].get();
|
| 308 |
+
for (int64_t m = m_offset; m < m_offset + m_size; m++) {
|
| 309 |
+
#pragma omp simd
|
| 310 |
+
for (int64_t n = 0; n < n_size; n++) {
|
| 311 |
+
{{acc_buf_name}}[m*Nr + n] += other_acc[m*Nr + n];
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
}
|
| 315 |
+
{%- set tile_acc_m_slice = kernel.slice_nd(tile_acc, [("m_offset", "m_offset + m_end - m_start"), ()]) %}
|
| 316 |
+
{{ kernel.store_output(
|
| 317 |
+
tile_Y, tile_acc_m_slice, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers
|
| 318 |
+
)|indent(20, false)
|
| 319 |
+
}}
|
| 320 |
+
}
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
{%- endif %}
|
| 324 |
+
{{ micro_gemm.codegen_finalize(kernel) }}
|
| 325 |
+
}
|
| 326 |
+
}
|
| 327 |
+
"""
|
| 328 |
+
|
| 329 |
+
SMALL_M_GEMM_TEMPLATE = r"""
|
| 330 |
+
{{ template.codegen_gemm_stub_def() }}
|
| 331 |
+
{
|
| 332 |
+
{{ kernel.maybe_codegen_profile() }}
|
| 333 |
+
{{ template.codegen_blocks(
|
| 334 |
+
num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W
|
| 335 |
+
) }}
|
| 336 |
+
# pragma omp parallel
|
| 337 |
+
{
|
| 338 |
+
#pragma omp for nowait
|
| 339 |
+
for (int64_t nr_block_id = 0; nr_block_id < Nr_blocks; nr_block_id++) {
|
| 340 |
+
// Handle one output M * Nr block in each thread
|
| 341 |
+
int64_t n_start = nr_block_id * Nr;
|
| 342 |
+
int64_t n_end = (nr_block_id + 1) * Nr;
|
| 343 |
+
{%- if use_local_acc %}
|
| 344 |
+
{%- set acc_buf_name = "local_acc_buf" %}
|
| 345 |
+
{{ kernel.define_stack_allocated_buffer(acc_buf_name, ["M", "Nr"], acc_buf_dtype) }}
|
| 346 |
+
{%- set acc = kernel.local_buffers[acc_buf_name] %}
|
| 347 |
+
{%- else %}
|
| 348 |
+
{%- set acc = kernel.slice_nd(GemmOut, [(0, "M"), ("n_start", "n_end")]) %}
|
| 349 |
+
{%- endif %}
|
| 350 |
+
for (int64_t kr_block_id = 0; kr_block_id < Kr_blocks; kr_block_id++) {
|
| 351 |
+
// this loop is not parallelized
|
| 352 |
+
int64_t k_start = kr_block_id * Kr;
|
| 353 |
+
int64_t k_end = std::min((kr_block_id + 1) * Kr, K);
|
| 354 |
+
{%- set tile_X = kernel.slice_nd(X, [(0, "M"), ("k_start", "k_end")]) %}
|
| 355 |
+
{%- set tile_W_3d = kernel.slice_nd(W, [("nr_block_id", "nr_block_id + 1"), ("k_start", "k_end"), ()]) %}
|
| 356 |
+
{%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %}
|
| 357 |
+
if C10_UNLIKELY(kr_block_id == 0) {
|
| 358 |
+
{{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=False, prefetch=True)|indent(20, false) }}
|
| 359 |
+
} else if C10_UNLIKELY(k_end == K) {
|
| 360 |
+
{{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=False)|indent(20, false) }}
|
| 361 |
+
} else {
|
| 362 |
+
{{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=True)|indent(20, false) }}
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
{%- set tile_Y = kernel.slice_nd(Y_2d, [("0", "M"), ("n_start", "n_end")]) %}
|
| 366 |
+
{%- set tile_acc = kernel.slice_nd(acc, [("0", "M"), ("0", "n_end - n_start")]) %}
|
| 367 |
+
{{ kernel.store_output(
|
| 368 |
+
tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("0", "n_start"), reindexers=reindexers
|
| 369 |
+
)|indent(20, false) }}
|
| 370 |
+
}
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _is_int8_gemm(inputs):
|
| 377 |
+
return (
|
| 378 |
+
isinstance(inputs[0], ir.IRNode)
|
| 379 |
+
and inputs[0].get_dtype() in [torch.uint8, torch.int8]
|
| 380 |
+
) or (
|
| 381 |
+
isinstance(inputs[0], torch.Tensor)
|
| 382 |
+
and inputs[0].dtype in [torch.uint8, torch.int8]
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def get_padded_n(n, block_n):
|
| 387 |
+
return (n + block_n - 1) // block_n * block_n
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
_T = TypeVar("_T", ir.IRNode, torch.Tensor)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def transpose_w(W: _T, trans_w: bool) -> _T:
|
| 394 |
+
"""
|
| 395 |
+
Transpose W based on the trans_w flag.
|
| 396 |
+
"""
|
| 397 |
+
if isinstance(W, ir.IRNode):
|
| 398 |
+
if trans_w:
|
| 399 |
+
if not isinstance(W, ir.TensorBox):
|
| 400 |
+
# pyrefly: ignore [bad-assignment]
|
| 401 |
+
W = ir.TensorBox(W)
|
| 402 |
+
W = L.permute(W, [1, 0])
|
| 403 |
+
else:
|
| 404 |
+
if trans_w:
|
| 405 |
+
assert isinstance(W, torch.Tensor)
|
| 406 |
+
# pyrefly: ignore [bad-assignment]
|
| 407 |
+
W = W.transpose(0, 1)
|
| 408 |
+
# pyrefly: ignore [bad-return]
|
| 409 |
+
return W
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def expand_bias(B: Optional[_T], X: _T) -> Optional[_T]:
|
| 413 |
+
"""
|
| 414 |
+
Expand Bias to the same size of X.
|
| 415 |
+
"""
|
| 416 |
+
if B is not None:
|
| 417 |
+
if isinstance(B, ir.IRNode):
|
| 418 |
+
if not isinstance(B, ir.TensorBox):
|
| 419 |
+
# pyrefly: ignore [bad-assignment]
|
| 420 |
+
B = ir.TensorBox(B)
|
| 421 |
+
assert hasattr(X, "get_size")
|
| 422 |
+
# pyrefly: ignore [missing-attribute]
|
| 423 |
+
B = L.expand(B, (X.get_size()[0], B.get_size()[-1]))
|
| 424 |
+
else:
|
| 425 |
+
assert isinstance(B, torch.Tensor)
|
| 426 |
+
assert isinstance(X, torch.Tensor)
|
| 427 |
+
# pyrefly: ignore [bad-assignment]
|
| 428 |
+
B = B.expand(X.shape[0], B.shape[-1])
|
| 429 |
+
return B
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def prune_tensors(input_nodes: list[ir.IRNode], new_input_nodes: list[ir.IRNode]):
|
| 433 |
+
"""
|
| 434 |
+
Prune unused tensors from `V.graph` since the GEMM Template use new packed weight.
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
def share_storage(base_tensor: torch.Tensor, comp_tensor: torch.Tensor):
|
| 438 |
+
return base_tensor.is_mkldnn == comp_tensor.is_mkldnn and (
|
| 439 |
+
is_same_tensor(base_tensor, comp_tensor)
|
| 440 |
+
or is_same_mkldnn_tensor(base_tensor, comp_tensor)
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
def get_candidates(input_nodes, new_input_nodes):
|
| 444 |
+
# Only Constant Buffer like weight and bias might be changed in GEMM Template.
|
| 445 |
+
# The Inductor IR Node may changed, but still share the storage. For example:
|
| 446 |
+
# bias in bfloat16 case which only do the expand
|
| 447 |
+
return [
|
| 448 |
+
node
|
| 449 |
+
for node in input_nodes
|
| 450 |
+
if (
|
| 451 |
+
node not in new_input_nodes
|
| 452 |
+
and isinstance(node, (ir.TensorBox, ir.StorageBox))
|
| 453 |
+
and node.get_name() in V.graph.constants
|
| 454 |
+
and not any(
|
| 455 |
+
(
|
| 456 |
+
isinstance(new_node, (ir.TensorBox, ir.StorageBox))
|
| 457 |
+
and new_node.get_name() in V.graph.constants
|
| 458 |
+
and share_storage(
|
| 459 |
+
V.graph.constants[node.get_name()],
|
| 460 |
+
V.graph.constants[new_node.get_name()],
|
| 461 |
+
)
|
| 462 |
+
)
|
| 463 |
+
for new_node in new_input_nodes
|
| 464 |
+
)
|
| 465 |
+
)
|
| 466 |
+
]
|
| 467 |
+
|
| 468 |
+
for candidate_node in get_candidates(input_nodes, new_input_nodes):
|
| 469 |
+
# By using the new packed weight for the GEMM template, we can prune the
|
| 470 |
+
# old weight if it has no other users. This saves memory but makes the FX graph
|
| 471 |
+
# non-retraceable. To support retracing, we can add a repack node to the
|
| 472 |
+
# FX graph. For example:
|
| 473 |
+
# mkldnn._linear_pointwise <- repack_linear_wgt <- packed_wgt_for_template
|
| 474 |
+
candidate_tensor_users = 0
|
| 475 |
+
candidate_tensor = V.graph.constants[candidate_node.get_name()]
|
| 476 |
+
for node in reversed(V.graph.graph.nodes):
|
| 477 |
+
# Case may happen when the candidate tensor is used by more than 1 get_attr node
|
| 478 |
+
# https://github.com/pytorch/pytorch/issues/134998
|
| 479 |
+
if node.op == "get_attr" and hasattr(
|
| 480 |
+
V.graph.module, node.target
|
| 481 |
+
): # candidate tensor might already be deleted
|
| 482 |
+
comp_tensor = getattr(V.graph.module, node.target)
|
| 483 |
+
if isinstance(comp_tensor, torch.Tensor) and share_storage(
|
| 484 |
+
candidate_tensor, comp_tensor
|
| 485 |
+
):
|
| 486 |
+
candidate_tensor_users += 1
|
| 487 |
+
|
| 488 |
+
for node in reversed(V.graph.graph.nodes):
|
| 489 |
+
# The get_attr node has only 1 user fx node
|
| 490 |
+
# The candidate tensor has been used by only 1 get_attr node
|
| 491 |
+
if (
|
| 492 |
+
node.op == "get_attr"
|
| 493 |
+
and node.target == candidate_node.get_name()
|
| 494 |
+
and len(node.users) == 1
|
| 495 |
+
and candidate_tensor_users == 1
|
| 496 |
+
):
|
| 497 |
+
del V.graph.constants[node.target]
|
| 498 |
+
delattr(V.graph.module, node.target)
|
| 499 |
+
delattr(V.graph.graph.owning_module, node.target)
|
| 500 |
+
counters["inductor"]["select_algorithm_weight_prune"] += 1
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def gen_2d_view_of_epilogue_buf(
|
| 504 |
+
Y: ir.Buffer,
|
| 505 |
+
template_buffer: ir.Buffer,
|
| 506 |
+
epilogue_nodes: list[ir.IRNode],
|
| 507 |
+
reindexers: list[Optional[Callable[[list[Any]], list[Any]]]],
|
| 508 |
+
default_reindexers: list[Optional[Callable[[list[Any]], list[Any]]]],
|
| 509 |
+
) -> tuple[
|
| 510 |
+
Union[ir.Buffer, ir.ReinterpretView],
|
| 511 |
+
list[Optional[Callable[[list[Any]], list[Any]]]],
|
| 512 |
+
]:
|
| 513 |
+
"""
|
| 514 |
+
The dimension and the indexing could be different between the GEMM output, i.e. `template_buffer`, which is
|
| 515 |
+
2D with MxN) and the output from the template after epilogues, i.e. `Y`. In the GEMM template code,
|
| 516 |
+
we are not aware of the dimension and the indexing of the epilogues and always work on 2D tiles according to
|
| 517 |
+
the indexing of the GEMM output.
|
| 518 |
+
In this function, we return a 2D buffer (`Y_2d`) according to GEMM output (reinterpreted from `Y` if needed) and
|
| 519 |
+
build a reindexer that converts the indexing of `Y` into `Y_2d`.
|
| 520 |
+
"""
|
| 521 |
+
Y_2d: Union[ir.Buffer, ir.ReinterpretView] = Y
|
| 522 |
+
if (
|
| 523 |
+
Y.get_size() == template_buffer.get_size()
|
| 524 |
+
and Y.get_stride() == template_buffer.get_stride()
|
| 525 |
+
):
|
| 526 |
+
reindexers.extend(default_reindexers)
|
| 527 |
+
Y_2d = Y
|
| 528 |
+
else:
|
| 529 |
+
|
| 530 |
+
def get_reindexer(epilogue_node, default_reindexer=None):
|
| 531 |
+
# From template_buffer to epilogue_node_ordered (ordered by stride decreasingly, in dense format), for example:
|
| 532 |
+
# template_buffer:
|
| 533 |
+
# size (324, 512), stride (512, 1)
|
| 534 |
+
# epilogue_node_ordered (ordered by stride decreasingly, in dense format):
|
| 535 |
+
# size (1, 18, 18, 512), stride (165888, 9216, 512, 1)
|
| 536 |
+
stride_order = list(
|
| 537 |
+
ir.get_stride_order(
|
| 538 |
+
V.graph.sizevars.size_hints(epilogue_node.get_stride())
|
| 539 |
+
)
|
| 540 |
+
)
|
| 541 |
+
fill_order = ir.stride_order2fill_order(stride_order)
|
| 542 |
+
reversed_fill_order = list(reversed(fill_order))
|
| 543 |
+
size_with_stride_ordered_decreasingly = [
|
| 544 |
+
epilogue_node.get_size()[i] for i in reversed_fill_order
|
| 545 |
+
]
|
| 546 |
+
reshape_reindex = ir.View.dynamic_reshape_indexer(
|
| 547 |
+
size_with_stride_ordered_decreasingly,
|
| 548 |
+
template_buffer.get_size(),
|
| 549 |
+
)
|
| 550 |
+
if default_reindexer:
|
| 551 |
+
reshape_reindex = ir.fuse_reindexing(reshape_reindex, default_reindexer)
|
| 552 |
+
|
| 553 |
+
# From epilogue_node_ordered (ordered by stride decreasingly, in dense format) to epilogue_node, for example:
|
| 554 |
+
# epilogue_node_ordered (ordered by stride decreasingly, in dense format):
|
| 555 |
+
# size (1, 18, 18, 512), stride (165888, 9216, 512, 1)
|
| 556 |
+
# epilogue_node:
|
| 557 |
+
# size (1, 18, 18, 512), stride (165888, 1, 9216, 512)
|
| 558 |
+
from_stride_ordered_decreasingly_to_epilogue_node_order = [
|
| 559 |
+
(len(stride_order) - 1) - stride_order[i]
|
| 560 |
+
for i in range(len(stride_order))
|
| 561 |
+
]
|
| 562 |
+
stride_reindex = ir.same_reorder(
|
| 563 |
+
from_stride_ordered_decreasingly_to_epilogue_node_order
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
reindexer = ir.fuse_reindexing(stride_reindex, reshape_reindex) # type: ignore[var-annotated]
|
| 567 |
+
return reindexer
|
| 568 |
+
|
| 569 |
+
if default_reindexers is None:
|
| 570 |
+
default_reindexers = [None] * len(epilogue_nodes)
|
| 571 |
+
new_reindexers = [
|
| 572 |
+
get_reindexer(epilogue_node, default_reindexer)
|
| 573 |
+
for epilogue_node, default_reindexer in zip(
|
| 574 |
+
epilogue_nodes, default_reindexers
|
| 575 |
+
)
|
| 576 |
+
]
|
| 577 |
+
reindexers.extend(new_reindexers)
|
| 578 |
+
if isinstance(Y, ir.BaseView):
|
| 579 |
+
storage = ir.StorageBox(Y.unwrap_view())
|
| 580 |
+
else:
|
| 581 |
+
assert isinstance(Y, ir.Buffer)
|
| 582 |
+
storage = ir.StorageBox(Y)
|
| 583 |
+
Y_2d = ir.ReinterpretView(data=storage, layout=template_buffer.get_layout())
|
| 584 |
+
return Y_2d, reindexers
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
class CppGemmTemplate(CppTemplate):
|
| 588 |
+
"""
|
| 589 |
+
GEMM Template for Inductor CPP Backend.
|
| 590 |
+
"""
|
| 591 |
+
|
| 592 |
+
def __init__(
|
| 593 |
+
self,
|
| 594 |
+
input_nodes,
|
| 595 |
+
layout: ir.Layout,
|
| 596 |
+
num_threads: int,
|
| 597 |
+
register_blocking: GemmBlocking,
|
| 598 |
+
beta=1,
|
| 599 |
+
alpha=1,
|
| 600 |
+
has_bias=False,
|
| 601 |
+
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
|
| 602 |
+
should_block_weights: bool = True,
|
| 603 |
+
name="packed_gemm",
|
| 604 |
+
) -> None:
|
| 605 |
+
assert layout.dtype in [torch.float, torch.bfloat16, torch.half, torch.uint8]
|
| 606 |
+
super().__init__(
|
| 607 |
+
name,
|
| 608 |
+
input_nodes,
|
| 609 |
+
layout,
|
| 610 |
+
num_threads,
|
| 611 |
+
epilogue_creator=epilogue_creator,
|
| 612 |
+
)
|
| 613 |
+
self.beta = beta
|
| 614 |
+
self.alpha = alpha
|
| 615 |
+
self.has_bias = has_bias
|
| 616 |
+
self.register_blocking = register_blocking
|
| 617 |
+
m, n = layout.size[-2:]
|
| 618 |
+
k = input_nodes[0].get_size()[-1]
|
| 619 |
+
self.m, self.n, self.k = m, n, k
|
| 620 |
+
self.padded_n = get_padded_n(n, self.register_blocking.block_n)
|
| 621 |
+
self.is_dynamic_M = has_free_symbols((m,))
|
| 622 |
+
self.should_block_weights = should_block_weights
|
| 623 |
+
self.thread_blocking = self.make_thread_blocking_cache()
|
| 624 |
+
self.cache_blocking = self.make_cache_blocking_cache()
|
| 625 |
+
|
| 626 |
+
def make_thread_blocking_cache(self):
|
| 627 |
+
cache = lru_cache()(self._thread_blocking)
|
| 628 |
+
|
| 629 |
+
def thread_blocking(num_threads: int) -> GemmBlocking:
|
| 630 |
+
return cache(num_threads)
|
| 631 |
+
|
| 632 |
+
return thread_blocking
|
| 633 |
+
|
| 634 |
+
def _thread_blocking(self, num_threads: int) -> GemmBlocking:
|
| 635 |
+
"""
|
| 636 |
+
NOTE [Thread blocking in Cpp GEMM]
|
| 637 |
+
We use simple heuristics to decide the thread blocking:
|
| 638 |
+
1. Make sure all threads are occupied as much as possible.
|
| 639 |
+
2. For (m, n) blocks, favor more square-sized thread blocks for better data reuse.
|
| 640 |
+
3. If (m, n) blocks cannot occupy all the threads, we consider k-slicing.
|
| 641 |
+
TODO(jgong5): allow tuning various blocking options
|
| 642 |
+
"""
|
| 643 |
+
|
| 644 |
+
def get_factors(number):
|
| 645 |
+
factors = []
|
| 646 |
+
for i in range(int(number**0.5), 0, -1):
|
| 647 |
+
if number % i == 0:
|
| 648 |
+
factors.append(number // i)
|
| 649 |
+
factors.append(i)
|
| 650 |
+
return factors
|
| 651 |
+
|
| 652 |
+
def get_blocking(m_factor, n_factor, k_factor, m_blocks, n_blocks, k_blocks):
|
| 653 |
+
thread_block_k = math.ceil(k_blocks / k_factor)
|
| 654 |
+
thread_block_n = math.ceil(n_blocks / n_factor)
|
| 655 |
+
thread_block_m = math.ceil(m_blocks / m_factor)
|
| 656 |
+
return GemmBlocking(thread_block_m, thread_block_n, thread_block_k)
|
| 657 |
+
|
| 658 |
+
assert not self.is_dynamic_M, (
|
| 659 |
+
"Unable to determine thread blocking for dynamic M."
|
| 660 |
+
)
|
| 661 |
+
register_blocking = self.register_blocking
|
| 662 |
+
m_blocks = math.ceil(self.m / register_blocking.block_m)
|
| 663 |
+
n_blocks = math.ceil(self.n / register_blocking.block_n)
|
| 664 |
+
k_blocks = math.ceil(self.k / register_blocking.block_k)
|
| 665 |
+
factors = get_factors(num_threads)
|
| 666 |
+
assert len(factors) > 0
|
| 667 |
+
|
| 668 |
+
if config.cpp.gemm_thread_factors is not None:
|
| 669 |
+
factors = [int(i) for i in config.cpp.gemm_thread_factors.split(",")]
|
| 670 |
+
assert len(factors) == 3
|
| 671 |
+
assert math.prod(factors) == self.num_threads
|
| 672 |
+
return get_blocking(
|
| 673 |
+
factors[0], factors[1], factors[2], m_blocks, n_blocks, k_blocks
|
| 674 |
+
)
|
| 675 |
+
|
| 676 |
+
# we favor square-sized thread blocks for good data reuse
|
| 677 |
+
def get_better_blocking(blocking, best_blocking):
|
| 678 |
+
if best_blocking is None:
|
| 679 |
+
best_blocking = blocking
|
| 680 |
+
else:
|
| 681 |
+
block_m_size = blocking.block_m * register_blocking.block_m
|
| 682 |
+
block_n_size = blocking.block_n * register_blocking.block_n
|
| 683 |
+
best_block_m_size = best_blocking.block_m * register_blocking.block_m
|
| 684 |
+
best_block_n_size = best_blocking.block_n * register_blocking.block_n
|
| 685 |
+
if blocking.block_k > best_blocking.block_k:
|
| 686 |
+
best_blocking = blocking
|
| 687 |
+
elif (
|
| 688 |
+
blocking.block_k == best_blocking.block_k
|
| 689 |
+
and block_m_size + block_n_size
|
| 690 |
+
< best_block_m_size + best_block_n_size
|
| 691 |
+
):
|
| 692 |
+
best_blocking = blocking
|
| 693 |
+
return best_blocking
|
| 694 |
+
|
| 695 |
+
best_blocking = None
|
| 696 |
+
# check if we can have a thread-blocking to occupy all threads without k-slicing
|
| 697 |
+
for n_factor in factors:
|
| 698 |
+
m_factor = num_threads // n_factor
|
| 699 |
+
if n_blocks >= n_factor and m_blocks >= m_factor:
|
| 700 |
+
blocking = get_blocking(
|
| 701 |
+
m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks
|
| 702 |
+
)
|
| 703 |
+
best_blocking = get_better_blocking(blocking, best_blocking)
|
| 704 |
+
|
| 705 |
+
if best_blocking is None:
|
| 706 |
+
for k_factor in factors:
|
| 707 |
+
if k_blocks >= k_factor and (
|
| 708 |
+
config.cpp.gemm_max_k_slices == 0
|
| 709 |
+
or k_factor <= config.cpp.gemm_max_k_slices
|
| 710 |
+
):
|
| 711 |
+
n_factors = get_factors(num_threads // k_factor)
|
| 712 |
+
for n_factor in n_factors:
|
| 713 |
+
m_factor = (num_threads // k_factor) // n_factor
|
| 714 |
+
if n_blocks >= n_factor and m_blocks >= m_factor:
|
| 715 |
+
blocking = get_blocking(
|
| 716 |
+
m_factor,
|
| 717 |
+
n_factor,
|
| 718 |
+
k_factor,
|
| 719 |
+
m_blocks,
|
| 720 |
+
n_blocks,
|
| 721 |
+
k_blocks,
|
| 722 |
+
)
|
| 723 |
+
best_blocking = get_better_blocking(blocking, best_blocking)
|
| 724 |
+
|
| 725 |
+
if best_blocking is None:
|
| 726 |
+
for n_factor in factors:
|
| 727 |
+
m_factor = num_threads // n_factor
|
| 728 |
+
if n_blocks >= n_factor or m_blocks >= m_factor:
|
| 729 |
+
blocking = get_blocking(
|
| 730 |
+
m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks
|
| 731 |
+
)
|
| 732 |
+
best_blocking = get_better_blocking(blocking, best_blocking)
|
| 733 |
+
|
| 734 |
+
assert best_blocking is not None
|
| 735 |
+
return best_blocking
|
| 736 |
+
|
| 737 |
+
def make_cache_blocking_cache(self):
|
| 738 |
+
cache = lru_cache()(self._cache_blocking)
|
| 739 |
+
|
| 740 |
+
def cache_blocking(num_threads: int) -> GemmBlocking:
|
| 741 |
+
return cache(num_threads)
|
| 742 |
+
|
| 743 |
+
return cache_blocking
|
| 744 |
+
|
| 745 |
+
def _cache_blocking(self, num_threads: int) -> GemmBlocking:
|
| 746 |
+
def get_cache_blocking(register_blocking, thread_blocking):
|
| 747 |
+
Mr = register_blocking.block_m
|
| 748 |
+
Nr = register_blocking.block_n
|
| 749 |
+
Kr = register_blocking.block_k
|
| 750 |
+
|
| 751 |
+
Mt_blocks = thread_blocking.block_m
|
| 752 |
+
Nt_blocks = thread_blocking.block_n
|
| 753 |
+
Kt_blocks = thread_blocking.block_k
|
| 754 |
+
|
| 755 |
+
if config.cpp.gemm_cache_blocking is not None:
|
| 756 |
+
blockings = [int(i) for i in config.cpp.gemm_cache_blocking.split(",")]
|
| 757 |
+
assert len(blockings) == 3
|
| 758 |
+
Mc_blocks, Nc_blocks, Kc_blocks = blockings
|
| 759 |
+
return (
|
| 760 |
+
min(Mc_blocks, Mt_blocks),
|
| 761 |
+
min(Nc_blocks, Nt_blocks),
|
| 762 |
+
min(Kc_blocks, Kt_blocks),
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
# The ratios below are empirically determined to decide
|
| 766 |
+
# the effective sizes of L1 and L2.
|
| 767 |
+
# TODO: tune the factor here
|
| 768 |
+
L1_limit_factor = 0.8
|
| 769 |
+
L2_limit_factor = 0.5
|
| 770 |
+
|
| 771 |
+
L1_cache_size = (
|
| 772 |
+
torch._C._cpu._L1d_cache_size()
|
| 773 |
+
) # per core cache size in Bytes
|
| 774 |
+
assert L1_cache_size > 0, (
|
| 775 |
+
f"Expect L1_cache_size > 0 but got {L1_cache_size}"
|
| 776 |
+
)
|
| 777 |
+
L1 = L1_cache_size * L1_limit_factor
|
| 778 |
+
|
| 779 |
+
L2_cache_size = (
|
| 780 |
+
torch._C._cpu._L2_cache_size()
|
| 781 |
+
) # per core cache size in Bytes
|
| 782 |
+
assert L2_cache_size > 0, (
|
| 783 |
+
f"Expect L2_cache_size > 0 but got {L2_cache_size}"
|
| 784 |
+
)
|
| 785 |
+
L2 = L2_cache_size * L2_limit_factor
|
| 786 |
+
|
| 787 |
+
def get_num_byte(dtype):
|
| 788 |
+
return torch.tensor([], dtype=dtype).element_size()
|
| 789 |
+
|
| 790 |
+
dtype_A = self.input_nodes[0].get_dtype()
|
| 791 |
+
dtype_B = self.input_nodes[1].get_dtype()
|
| 792 |
+
num_byte_A = get_num_byte(dtype_A)
|
| 793 |
+
num_byte_B = get_num_byte(dtype_B)
|
| 794 |
+
if dtype_A is torch.bfloat16 and dtype_B is torch.int8 and Kr != 1:
|
| 795 |
+
# We will cache dequantized weights (BF16) in L1D for AMX micro-kernel.
|
| 796 |
+
# In this case, the choice of the micro-kernel being used can't be decoupled from
|
| 797 |
+
# the cache blocking.
|
| 798 |
+
# TODO: Decouple the choice of micro-kernel from cache blocking
|
| 799 |
+
num_byte_B *= num_byte_A
|
| 800 |
+
|
| 801 |
+
# NOTE [CPP GEMM Cache Blocking Algorithm]
|
| 802 |
+
# Our overall strategy is to
|
| 803 |
+
# 1) Make cache blocks of B L1-reside and reused by multiple rows of A, i.e. Mc.
|
| 804 |
+
# Here, B is Kc x Nr where Nr is a single register block. We use L1 size to
|
| 805 |
+
# decide Kc. We want to make Mc large enough to better reuse B.
|
| 806 |
+
# 2) Make cache blocks of A L2-reside, which would limit Mc. We want to reuse A
|
| 807 |
+
# along N, where we have two sub-strategies (see notes below) to decide Mc and Nc.
|
| 808 |
+
|
| 809 |
+
# Step 1: Decide Kc assuming B block is L1-reside.
|
| 810 |
+
size_cache_B = Kr * Kt_blocks * Nr * num_byte_B
|
| 811 |
+
|
| 812 |
+
Kc_blocks = Kt_blocks
|
| 813 |
+
if size_cache_B > L1:
|
| 814 |
+
Kc_blocks = math.floor(L1 / (Kr * Nr * num_byte_B))
|
| 815 |
+
|
| 816 |
+
if (
|
| 817 |
+
config.cpp.use_small_dequant_buffer
|
| 818 |
+
and dtype_A is torch.bfloat16
|
| 819 |
+
and Mt_blocks == 1
|
| 820 |
+
):
|
| 821 |
+
if dtype_B is torch.uint8:
|
| 822 |
+
# A16W4
|
| 823 |
+
# Make a small dequant_B buffer for woq int4 [q_group_size, Nr]
|
| 824 |
+
# Since when Mt_blocks == 1, L1-reside B block can't be reused by A.
|
| 825 |
+
if Kc_blocks * Kr >= self.q_group_size():
|
| 826 |
+
Kc_blocks = self.q_group_size() // Kr
|
| 827 |
+
|
| 828 |
+
elif dtype_B is torch.int8:
|
| 829 |
+
# A16W8
|
| 830 |
+
# Make A, B, C buffer in L1
|
| 831 |
+
A_buf_size_div_K = self.m * num_byte_A
|
| 832 |
+
B_buf_size_div_K = Nr * num_byte_B
|
| 833 |
+
# assume acc in float32/int32 and Mc_blocks = Nc_blocks = 1
|
| 834 |
+
C_buf_size = Mr * Nr * 4
|
| 835 |
+
K_block_size = (L1 - C_buf_size) // (
|
| 836 |
+
A_buf_size_div_K + B_buf_size_div_K
|
| 837 |
+
)
|
| 838 |
+
if Kc_blocks * Kr >= K_block_size:
|
| 839 |
+
Kc_blocks = (K_block_size + Kr - 1) // Kr
|
| 840 |
+
|
| 841 |
+
# Step 2: Decide Mc assuming A block is L2-reside.
|
| 842 |
+
min_Mc_ratio = 2 # TODO(jgong5): something to tune?
|
| 843 |
+
min_Mc_blocks = math.ceil(min_Mc_ratio * Mr / Nr)
|
| 844 |
+
assert min_Mc_blocks >= 1
|
| 845 |
+
Kt_bytes = Kt_blocks * Kr * num_byte_A
|
| 846 |
+
if min_Mc_blocks * Mr * Kt_bytes < L2:
|
| 847 |
+
# Strategy 1: A (Mc x Kt) resides in L2 and reused by all Nt
|
| 848 |
+
# when Nc_blocks is kept 1. Mc should be large enough (>= min_Mc_blocks)
|
| 849 |
+
# to reuse B (Kc x Nr) in L1. This makes C (Mc x Nr) small enough to reside
|
| 850 |
+
# in L1.
|
| 851 |
+
Mc_blocks = min(Mt_blocks, math.floor(L2 / (Mr * Kt_bytes)))
|
| 852 |
+
Nc_blocks = 1
|
| 853 |
+
else:
|
| 854 |
+
# Strategy 2: Kt is too large to hold A (Mc x Kt) in L2, we reuse
|
| 855 |
+
# A (Mc x Kc) in L2 by B (Kc x Nc). C (Mc x Nc) resides in L2.
|
| 856 |
+
Mc_blocks = Mt_blocks
|
| 857 |
+
Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks)
|
| 858 |
+
Nc_bytes = Nc_blocks * Nr * 4 # assume C or acc is float32/int32
|
| 859 |
+
Kc_bytes = Kc_blocks * Kr * num_byte_A
|
| 860 |
+
if Mc_blocks * Mr * (Kc_bytes + Nc_bytes) > L2:
|
| 861 |
+
# The following is the solution for 4*Mc*Nc + Mc*Kc_bytes = L2,
|
| 862 |
+
# assuming Mc == Nc for good data reuse.
|
| 863 |
+
M_max = (math.sqrt(Kc_bytes * Kc_bytes + 16 * L2) - Kc_bytes) / 8
|
| 864 |
+
if M_max < Mc_blocks * Mr:
|
| 865 |
+
Mc_blocks = math.floor(M_max / Mr)
|
| 866 |
+
Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks)
|
| 867 |
+
|
| 868 |
+
return Mc_blocks, Nc_blocks, Kc_blocks
|
| 869 |
+
|
| 870 |
+
assert not self.is_dynamic_M, (
|
| 871 |
+
"Unable to determine cache blocking for dynamic M."
|
| 872 |
+
)
|
| 873 |
+
register_blocking = self.register_blocking
|
| 874 |
+
thread_blocking = self.thread_blocking(num_threads)
|
| 875 |
+
|
| 876 |
+
return GemmBlocking(*get_cache_blocking(register_blocking, thread_blocking))
|
| 877 |
+
|
| 878 |
+
def log_blockings(self):
|
| 879 |
+
log.debug(f"Register blocking: {self.register_blocking}") # noqa: G004
|
| 880 |
+
if self.is_dynamic_M:
|
| 881 |
+
# thread and cache blockings are determined at runtime for dynamic shapes
|
| 882 |
+
return
|
| 883 |
+
log.debug(
|
| 884 |
+
f"Cache blocking: {self.cache_blocking(self.num_threads)}" # noqa: G004
|
| 885 |
+
)
|
| 886 |
+
thread_blocking = self.thread_blocking(self.num_threads)
|
| 887 |
+
log.debug(f"Thread blocking: {thread_blocking}") # noqa: G004
|
| 888 |
+
|
| 889 |
+
def get_occupancy():
|
| 890 |
+
m_blocks = math.ceil(self.m / self.register_blocking.block_m)
|
| 891 |
+
n_blocks = math.ceil(self.n / self.register_blocking.block_n)
|
| 892 |
+
k_blocks = math.ceil(self.k / self.register_blocking.block_k)
|
| 893 |
+
m = math.ceil(m_blocks / thread_blocking.block_m)
|
| 894 |
+
n = math.ceil(n_blocks / thread_blocking.block_n)
|
| 895 |
+
k = math.ceil(k_blocks / thread_blocking.block_k)
|
| 896 |
+
return (m, n, k)
|
| 897 |
+
|
| 898 |
+
log.debug(
|
| 899 |
+
f"Number of threads: {self.num_threads}, occupancy: {get_occupancy()}" # noqa: G004
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
def maybe_k_slicing(self):
|
| 903 |
+
if self.num_threads == 1:
|
| 904 |
+
return False
|
| 905 |
+
if self.is_dynamic_M:
|
| 906 |
+
# TODO(jgong5): perhaps use size hint to decide?
|
| 907 |
+
return True
|
| 908 |
+
register_blocking = self.register_blocking
|
| 909 |
+
k_blocks = math.ceil(self.k / register_blocking.block_k)
|
| 910 |
+
thread_blocking = self.thread_blocking(self.num_threads)
|
| 911 |
+
return k_blocks > thread_blocking.block_k
|
| 912 |
+
|
| 913 |
+
@classmethod
|
| 914 |
+
def add_choices(
|
| 915 |
+
cls,
|
| 916 |
+
choices,
|
| 917 |
+
layout,
|
| 918 |
+
input_nodes,
|
| 919 |
+
beta=1,
|
| 920 |
+
alpha=1,
|
| 921 |
+
has_bias=False,
|
| 922 |
+
trans_w=False,
|
| 923 |
+
input_indices=None,
|
| 924 |
+
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
|
| 925 |
+
act_mapping: Optional[dict[int, ir.IRNode]] = None,
|
| 926 |
+
):
|
| 927 |
+
"""
|
| 928 |
+
Add choices for the GEMM template.
|
| 929 |
+
"""
|
| 930 |
+
# Fast path to save the epilogue calculation when x_scale/x_zp/w_scale are constant
|
| 931 |
+
use_int8_fast_compensation_path = _is_int8_gemm(input_nodes) and all(
|
| 932 |
+
(
|
| 933 |
+
isinstance(input_nodes[idx], ir.TensorBox)
|
| 934 |
+
and isinstance(input_nodes[idx].data.data, ir.ConstantBuffer)
|
| 935 |
+
)
|
| 936 |
+
for idx in [1, 2, 4]
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
if input_indices is None:
|
| 940 |
+
input_indices = list(range(len(input_nodes)))
|
| 941 |
+
|
| 942 |
+
def reorder_and_filter(inputs, layout_or_out):
|
| 943 |
+
if has_bias:
|
| 944 |
+
assert len(input_indices) >= 3
|
| 945 |
+
# Assume the input order is [inp, x, w] and we reorder it to [x, w, inp]
|
| 946 |
+
inp_idx = input_indices[0]
|
| 947 |
+
x_idx = input_indices[1]
|
| 948 |
+
w_idx = input_indices[2]
|
| 949 |
+
return [
|
| 950 |
+
inputs[x_idx],
|
| 951 |
+
inputs[w_idx],
|
| 952 |
+
inputs[inp_idx],
|
| 953 |
+
*[inputs[idx] for idx in input_indices[3:]],
|
| 954 |
+
], layout_or_out
|
| 955 |
+
elif len(inputs) >= len(input_indices):
|
| 956 |
+
assert len(input_indices) >= 2
|
| 957 |
+
return [inputs[idx] for idx in input_indices], layout_or_out
|
| 958 |
+
else:
|
| 959 |
+
# For when input is used for x and w, i.e. X@X.T or similar
|
| 960 |
+
# Assumes the first input is the only input
|
| 961 |
+
assert len(inputs) == 1
|
| 962 |
+
return [inputs[0]] * len(input_indices), layout_or_out
|
| 963 |
+
|
| 964 |
+
new_inputs, new_layout = reorder_and_filter(input_nodes, layout)
|
| 965 |
+
is_mkldnn_wgt = (
|
| 966 |
+
new_inputs[1].get_name() in V.graph.constants
|
| 967 |
+
and V.graph.constants[new_inputs[1].get_name()].is_mkldnn
|
| 968 |
+
)
|
| 969 |
+
if is_mkldnn_wgt:
|
| 970 |
+
# It shouldn't happen as viewing an mkldnn tensor, we can extend the
|
| 971 |
+
# implementation if it does.
|
| 972 |
+
assert not isinstance(new_inputs[1], ir.BaseView)
|
| 973 |
+
# Note that the layout of MKLDNN Tensor is with the wrong stride
|
| 974 |
+
view_size = new_inputs[1].layout.size
|
| 975 |
+
view_stride = new_inputs[1].layout.stride
|
| 976 |
+
view_offset = new_inputs[1].layout.offset
|
| 977 |
+
|
| 978 |
+
def maybe_to_dense(inputs, layout_or_out):
|
| 979 |
+
new_inputs = list(inputs)
|
| 980 |
+
if isinstance(inputs[1], torch.Tensor):
|
| 981 |
+
W = inputs[1]
|
| 982 |
+
new_inputs[1] = W.to_dense() if W.is_mkldnn else W
|
| 983 |
+
return new_inputs, layout_or_out
|
| 984 |
+
|
| 985 |
+
def normalize_shapes(inputs, layout_or_out):
|
| 986 |
+
new_inputs = list(inputs)
|
| 987 |
+
if not is_mkldnn_wgt and isinstance(new_inputs[1], torch.Tensor):
|
| 988 |
+
if has_free_symbols(view_size):
|
| 989 |
+
# If batch size B is dynamic, we need to set the batch size and possibly stride
|
| 990 |
+
assert not has_free_symbols(view_size[1:])
|
| 991 |
+
view_size[:] = V.graph.sizevars.size_hints(view_size)
|
| 992 |
+
view_stride[:] = V.graph.sizevars.size_hints(view_stride)
|
| 993 |
+
# With the assumptation that W is the storage of unwrap view
|
| 994 |
+
# thus view it back here
|
| 995 |
+
new_inputs[1] = new_inputs[1].as_strided(
|
| 996 |
+
view_size, view_stride, view_offset
|
| 997 |
+
)
|
| 998 |
+
|
| 999 |
+
if not trans_w:
|
| 1000 |
+
return new_inputs, layout_or_out
|
| 1001 |
+
X = new_inputs[0]
|
| 1002 |
+
W = new_inputs[1]
|
| 1003 |
+
B = new_inputs[2] if has_bias else None
|
| 1004 |
+
W = transpose_w(W, trans_w)
|
| 1005 |
+
B = expand_bias(B, X) # type:ignore[arg-type]
|
| 1006 |
+
new_inputs[1] = W
|
| 1007 |
+
if B is not None:
|
| 1008 |
+
new_inputs[2] = B
|
| 1009 |
+
return new_inputs, layout_or_out
|
| 1010 |
+
|
| 1011 |
+
# TODO(jgong5): decide proper number of threads per problem size
|
| 1012 |
+
num_threads = parallel_num_threads()
|
| 1013 |
+
new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout))
|
| 1014 |
+
m, n, k, *_ = mm_args(
|
| 1015 |
+
new_inputs[0],
|
| 1016 |
+
new_inputs[1],
|
| 1017 |
+
mat2_transposed=cls.is_woq_int4(),
|
| 1018 |
+
use_4x2_dim=cls.is_woq_int4(),
|
| 1019 |
+
)
|
| 1020 |
+
output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
|
| 1021 |
+
new_inputs[0].get_dtype()
|
| 1022 |
+
)
|
| 1023 |
+
micro_gemm = create_micro_gemm(
|
| 1024 |
+
"micro_gemm",
|
| 1025 |
+
m,
|
| 1026 |
+
n,
|
| 1027 |
+
k,
|
| 1028 |
+
input_dtype=new_inputs[0].get_dtype(),
|
| 1029 |
+
input2_dtype=new_inputs[1].get_dtype(),
|
| 1030 |
+
output_dtype=output_dtype,
|
| 1031 |
+
compute_dtype=compute_dtype,
|
| 1032 |
+
alpha=alpha,
|
| 1033 |
+
num_threads=num_threads,
|
| 1034 |
+
use_ref=not cls.is_woq_int4(),
|
| 1035 |
+
q_group_size=cls.q_group_size(),
|
| 1036 |
+
)
|
| 1037 |
+
assert micro_gemm is not None
|
| 1038 |
+
pre_block_weights = cls.check_if_block_weight(new_inputs[1], micro_gemm)
|
| 1039 |
+
micro_gemm.use_local_vnni_blocking(not pre_block_weights)
|
| 1040 |
+
only_one_input = (
|
| 1041 |
+
input_nodes[0] == input_nodes[1] if len(input_nodes) > 1 else False
|
| 1042 |
+
) and not pre_block_weights # If weights are blocked, use the second input
|
| 1043 |
+
|
| 1044 |
+
def preprocessor(inputs, layout):
|
| 1045 |
+
new_inputs, new_layout = normalize_shapes(
|
| 1046 |
+
*maybe_to_dense(*reorder_and_filter(inputs, layout))
|
| 1047 |
+
)
|
| 1048 |
+
if only_one_input and isinstance(new_inputs[0], torch.Tensor):
|
| 1049 |
+
return new_inputs[1:], new_layout
|
| 1050 |
+
return cls.prep_weight(
|
| 1051 |
+
new_inputs,
|
| 1052 |
+
new_layout,
|
| 1053 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1054 |
+
micro_gemm,
|
| 1055 |
+
pre_block_weights,
|
| 1056 |
+
use_int8_fast_compensation_path,
|
| 1057 |
+
)
|
| 1058 |
+
|
| 1059 |
+
def postprocessor(output):
|
| 1060 |
+
if isinstance(output, ir.TensorBox):
|
| 1061 |
+
# prepack the weight as input to the template buffer
|
| 1062 |
+
template_buffer = ir.InputsKernel.unwrap_storage_for_input(output)
|
| 1063 |
+
assert isinstance(template_buffer, ir.CppTemplateBuffer)
|
| 1064 |
+
new_input_nodes, _ = reorder_and_filter(input_nodes, layout)
|
| 1065 |
+
|
| 1066 |
+
W_node = new_input_nodes[1]
|
| 1067 |
+
if W_node.get_name() not in V.graph.constants:
|
| 1068 |
+
return output
|
| 1069 |
+
W = V.graph.constants[W_node.get_name()]
|
| 1070 |
+
new_input_nodes[1] = W
|
| 1071 |
+
new_input_nodes, new_layout = normalize_shapes(
|
| 1072 |
+
*maybe_to_dense(new_input_nodes, layout)
|
| 1073 |
+
)
|
| 1074 |
+
new_input_nodes, _ = cls.prep_weight(
|
| 1075 |
+
new_input_nodes,
|
| 1076 |
+
new_layout,
|
| 1077 |
+
# pyrefly: ignore [bad-argument-type]
|
| 1078 |
+
micro_gemm,
|
| 1079 |
+
pre_block_weights,
|
| 1080 |
+
use_int8_fast_compensation_path,
|
| 1081 |
+
skip_int8_compensation=True,
|
| 1082 |
+
)
|
| 1083 |
+
W_packed = new_input_nodes[1]
|
| 1084 |
+
W_packed_constant = V.graph.add_tensor_constant(W_packed)
|
| 1085 |
+
new_input_nodes[1] = W_packed_constant
|
| 1086 |
+
|
| 1087 |
+
# Prune unused tensors
|
| 1088 |
+
prune_tensors(input_nodes, new_input_nodes)
|
| 1089 |
+
|
| 1090 |
+
template_buffer.inputs[1] = ir.InputsKernel.unwrap_storage_for_input(
|
| 1091 |
+
W_packed_constant
|
| 1092 |
+
)
|
| 1093 |
+
return output
|
| 1094 |
+
|
| 1095 |
+
template = DataProcessorTemplateWrapper(
|
| 1096 |
+
cls,
|
| 1097 |
+
preprocessor,
|
| 1098 |
+
postprocessor,
|
| 1099 |
+
input_nodes=input_nodes,
|
| 1100 |
+
layout=layout,
|
| 1101 |
+
num_threads=num_threads,
|
| 1102 |
+
register_blocking=micro_gemm.register_blocking,
|
| 1103 |
+
beta=beta,
|
| 1104 |
+
alpha=alpha,
|
| 1105 |
+
has_bias=has_bias,
|
| 1106 |
+
epilogue_creator=epilogue_creator,
|
| 1107 |
+
should_block_weights=pre_block_weights,
|
| 1108 |
+
name=micro_gemm.__class__.__name__,
|
| 1109 |
+
)
|
| 1110 |
+
template.maybe_append_choice(choices)
|
| 1111 |
+
return template
|
| 1112 |
+
|
| 1113 |
+
@staticmethod
|
| 1114 |
+
def get_padded_size(n, block_n, k, should_block_weight):
|
| 1115 |
+
padded_n = get_padded_n(n, block_n)
|
| 1116 |
+
# We assume that all GEMM weight tensors should be blocked and padded
|
| 1117 |
+
new_size = [padded_n // block_n, k, block_n]
|
| 1118 |
+
return new_size, padded_n
|
| 1119 |
+
|
| 1120 |
+
@staticmethod
|
| 1121 |
+
def _maybe_remove_storage_offset(node: ir.IRNode):
|
| 1122 |
+
if node.get_layout().offset == 0:
|
| 1123 |
+
return node
|
| 1124 |
+
# node may be contiguous but still have a non-zero storage offset.
|
| 1125 |
+
# GEMM_TEMPLATE emits code like:
|
| 1126 |
+
# W.data_ptr[node.offset + ...]
|
| 1127 |
+
# but runtime W.data_ptr (after normalize_shapes()) already includes this offset.
|
| 1128 |
+
# To avoid double-offsetting, we remove the offset in the node also in the generated code.
|
| 1129 |
+
# W.data_ptr[...]
|
| 1130 |
+
return ir.ExternKernel.copy_input(node)
|
| 1131 |
+
|
| 1132 |
+
@classmethod
|
| 1133 |
+
def prep_weight(
|
| 1134 |
+
cls,
|
| 1135 |
+
inputs,
|
| 1136 |
+
layout: ir.Layout,
|
| 1137 |
+
micro_gemm: CppMicroGemm,
|
| 1138 |
+
should_block_weight: bool,
|
| 1139 |
+
use_int8_fast_compensation_path: bool = False,
|
| 1140 |
+
skip_int8_compensation: bool = False,
|
| 1141 |
+
):
|
| 1142 |
+
"""
|
| 1143 |
+
NOTE Weight prep consists of 2 separate steps:
|
| 1144 |
+
1. Blocking the weight tensor into a 3D shape: [n//block_n, k, block_n]
|
| 1145 |
+
This is always done if the weight tensor is constant, i.e. for all GEMM and some BMM.
|
| 1146 |
+
For BMM, we also block non-contiguous weight tensors, since they would be reshaped anyway.
|
| 1147 |
+
This assumes that blocked, contiguous weights will be more efficient for the GEMM kernel,
|
| 1148 |
+
and is worth the overhead of reshape and blocking.
|
| 1149 |
+
|
| 1150 |
+
This blocking includes additional padding, when n is not a multiple of block_n.
|
| 1151 |
+
This padding allows a more efficient microkernel implementation. For BMM, this is only done
|
| 1152 |
+
if reshape would happen anyway, i.e. if the weight tensor is constant, is not contiguous,
|
| 1153 |
+
or is using AMX VNNI layout.
|
| 1154 |
+
2. Packing the weight tensor into a VNNI-friendly shape. For constant input,
|
| 1155 |
+
this is done at the same time as the weight blocking.
|
| 1156 |
+
|
| 1157 |
+
At compile time, the constant weight tensors are blocked and packed. For non-constant tensors (e.g. BMM)
|
| 1158 |
+
which will be blocked (non-contiguous or VNNI-layout tensors), the weight tensor is blocked and packed at runtime.
|
| 1159 |
+
|
| 1160 |
+
CppBmmTemplate overrides the methods get_padded_size, and block_weight in order to accommodate
|
| 1161 |
+
an additional dimension for the batch size and to determine if the weight tensor should be blocked.
|
| 1162 |
+
"""
|
| 1163 |
+
W = inputs[1]
|
| 1164 |
+
new_inputs = list(inputs)
|
| 1165 |
+
if cls.is_woq_int4():
|
| 1166 |
+
assert (
|
| 1167 |
+
len(W.get_size()) == 2
|
| 1168 |
+
if isinstance(W, ir.IRNode)
|
| 1169 |
+
else len(W.shape) == 2
|
| 1170 |
+
)
|
| 1171 |
+
n, k = W.get_size() if isinstance(W, ir.IRNode) else W.shape
|
| 1172 |
+
else:
|
| 1173 |
+
k, n = W.get_size()[-2:] if isinstance(W, ir.IRNode) else W.shape[-2:]
|
| 1174 |
+
_, block_n, _ = micro_gemm.register_blocking
|
| 1175 |
+
new_size, padded_n = cls.get_padded_size(n, block_n, k, should_block_weight)
|
| 1176 |
+
padding = padded_n - n
|
| 1177 |
+
|
| 1178 |
+
if should_block_weight and not cls.is_woq_int4():
|
| 1179 |
+
blocked_w = cls.block_weight(W, new_size, padding)
|
| 1180 |
+
new_inputs[1] = cls.pack_vnni_weight(blocked_w, micro_gemm, new_size)
|
| 1181 |
+
elif should_block_weight:
|
| 1182 |
+
assert cls.is_woq_int4()
|
| 1183 |
+
new_inputs[1] = cls.block_weight(W, new_size, padding)
|
| 1184 |
+
elif isinstance(W, ir.IRNode):
|
| 1185 |
+
# Require W layout to be fixed & contiguous, happens inplace.
|
| 1186 |
+
ir.ExternKernel.require_contiguous(W)
|
| 1187 |
+
new_inputs[1] = cls._maybe_remove_storage_offset(W)
|
| 1188 |
+
|
| 1189 |
+
if not skip_int8_compensation and _is_int8_gemm(new_inputs):
|
| 1190 |
+
BCompensate = None
|
| 1191 |
+
x_w_scale = None
|
| 1192 |
+
|
| 1193 |
+
def _get_compensation_node(W, use_int8_fast_compensation_path):
|
| 1194 |
+
BCompensate = V.graph.add_tensor_constant(
|
| 1195 |
+
V.graph.constants[W.get_name() + "_BMatrixCompens"],
|
| 1196 |
+
W.get_name() + "_BMatrixCompens",
|
| 1197 |
+
)
|
| 1198 |
+
x_w_scale = None
|
| 1199 |
+
if use_int8_fast_compensation_path:
|
| 1200 |
+
x_w_scale = V.graph.add_tensor_constant(
|
| 1201 |
+
V.graph.constants[W.get_name() + "_x_w_compens"],
|
| 1202 |
+
W.get_name() + "_x_w_compens",
|
| 1203 |
+
)
|
| 1204 |
+
return BCompensate, x_w_scale
|
| 1205 |
+
|
| 1206 |
+
if use_int8_fast_compensation_path:
|
| 1207 |
+
# new_inputs has been reordered: [x, w, optional[bias], x_scale, x_zp, w_scale, w_zp]
|
| 1208 |
+
x_scale = new_inputs[-4]
|
| 1209 |
+
x_zp = new_inputs[-3]
|
| 1210 |
+
w_scale = new_inputs[-2]
|
| 1211 |
+
if isinstance(W, ir.IRNode):
|
| 1212 |
+
BCompensate, x_w_scale = _get_compensation_node(
|
| 1213 |
+
W, use_int8_fast_compensation_path
|
| 1214 |
+
)
|
| 1215 |
+
else:
|
| 1216 |
+
# Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate
|
| 1217 |
+
BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment]
|
| 1218 |
+
assert all(
|
| 1219 |
+
isinstance(item, torch.Tensor)
|
| 1220 |
+
for item in (x_scale, x_zp, w_scale)
|
| 1221 |
+
)
|
| 1222 |
+
BCompensate = BCompensate * x_scale * w_scale * x_zp
|
| 1223 |
+
x_w_scale = x_scale * w_scale
|
| 1224 |
+
new_inputs.append(BCompensate)
|
| 1225 |
+
new_inputs.append(x_w_scale)
|
| 1226 |
+
else:
|
| 1227 |
+
if isinstance(W, ir.IRNode):
|
| 1228 |
+
BCompensate, _ = _get_compensation_node(
|
| 1229 |
+
W, use_int8_fast_compensation_path
|
| 1230 |
+
)
|
| 1231 |
+
else:
|
| 1232 |
+
# Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate
|
| 1233 |
+
BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment]
|
| 1234 |
+
new_inputs.append(BCompensate)
|
| 1235 |
+
return new_inputs, layout
|
| 1236 |
+
|
| 1237 |
+
@staticmethod
|
| 1238 |
+
def check_if_block_weight(W, micro_gemm):
|
| 1239 |
+
return True
|
| 1240 |
+
|
| 1241 |
+
@classmethod
|
| 1242 |
+
def block_weight(cls, W, new_size, padding):
|
| 1243 |
+
# These are separated into two methods to allow subclasses to override them separately
|
| 1244 |
+
if isinstance(W, ir.IRNode):
|
| 1245 |
+
if W.get_name() in V.graph.constants:
|
| 1246 |
+
# Create a new buffer, representing the constant blocked tensor
|
| 1247 |
+
blocked_w = ir.Buffer(
|
| 1248 |
+
name=W.get_name(), # Borrow the registered buffer name
|
| 1249 |
+
layout=ir.FixedLayout(
|
| 1250 |
+
W.get_device_or_error(),
|
| 1251 |
+
W.get_dtype(),
|
| 1252 |
+
new_size,
|
| 1253 |
+
ir.FlexibleLayout.contiguous_strides(new_size),
|
| 1254 |
+
0,
|
| 1255 |
+
),
|
| 1256 |
+
)
|
| 1257 |
+
else:
|
| 1258 |
+
if not isinstance(W, ir.TensorBox):
|
| 1259 |
+
W = ir.TensorBox(W)
|
| 1260 |
+
permute_dims = list(range(len(new_size)))
|
| 1261 |
+
permute_dims[-2], permute_dims[-3] = permute_dims[-3], permute_dims[-2]
|
| 1262 |
+
permute_size = list(new_size)
|
| 1263 |
+
permute_size[-2], permute_size[-3] = permute_size[-3], permute_size[-2]
|
| 1264 |
+
blocked_w = L.constant_pad_nd(W, (0, padding))
|
| 1265 |
+
blocked_w = L.permute(
|
| 1266 |
+
L.view(blocked_w, permute_size), # type: ignore[arg-type]
|
| 1267 |
+
permute_dims,
|
| 1268 |
+
)
|
| 1269 |
+
else:
|
| 1270 |
+
assert isinstance(W, torch.Tensor)
|
| 1271 |
+
# Pad the weight tensor and reshape it into a 3D blocked shape
|
| 1272 |
+
blocked_size = list(new_size)
|
| 1273 |
+
blocked_size[-2], blocked_size[-3] = blocked_size[-3], blocked_size[-2]
|
| 1274 |
+
blocked_w = (
|
| 1275 |
+
torch.nn.functional.pad(W, (0, padding)) # type: ignore[assignment]
|
| 1276 |
+
.reshape(*blocked_size)
|
| 1277 |
+
.transpose(-3, -2)
|
| 1278 |
+
.contiguous()
|
| 1279 |
+
)
|
| 1280 |
+
return blocked_w
|
| 1281 |
+
|
| 1282 |
+
@classmethod
|
| 1283 |
+
def pack_vnni_weight(cls, W, micro_gemm, new_size):
|
| 1284 |
+
# WOQ INT4 weights are reordered in microkernel so do not pack them here
|
| 1285 |
+
should_pack = (
|
| 1286 |
+
micro_gemm.get_b_layout() != LayoutType.NORMAL
|
| 1287 |
+
and not micro_gemm.is_woq_int4()
|
| 1288 |
+
)
|
| 1289 |
+
|
| 1290 |
+
# These are separated into two methods to allow subclasses to override them separately
|
| 1291 |
+
if isinstance(W, ir.IRNode):
|
| 1292 |
+
if isinstance(W, ir.Buffer) and W.get_name() in V.graph.constants:
|
| 1293 |
+
return W
|
| 1294 |
+
k = new_size[-2]
|
| 1295 |
+
if not isinstance(W, ir.TensorBox):
|
| 1296 |
+
W = ir.TensorBox(W)
|
| 1297 |
+
if should_pack:
|
| 1298 |
+
permute_dims = list(range(len(new_size) + 1))
|
| 1299 |
+
permute_dims[-1], permute_dims[-2] = permute_dims[-2], permute_dims[-1]
|
| 1300 |
+
vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2
|
| 1301 |
+
vnni_view_size = list(new_size)
|
| 1302 |
+
vnni_view_size[-2] = k // vnni_size
|
| 1303 |
+
vnni_view_size.insert(-1, vnni_size)
|
| 1304 |
+
W = L.view(
|
| 1305 |
+
L.permute(L.view(W, vnni_view_size), permute_dims),
|
| 1306 |
+
new_size,
|
| 1307 |
+
)
|
| 1308 |
+
W = ir.ExternKernel.realize_input(W)
|
| 1309 |
+
W = ir.ExternKernel.require_contiguous(W)
|
| 1310 |
+
return W
|
| 1311 |
+
else:
|
| 1312 |
+
k = new_size[-2]
|
| 1313 |
+
# Apply VNNI packing to the weight tensor
|
| 1314 |
+
if should_pack:
|
| 1315 |
+
# TODO: Move VNNI weight packing for non-constant tensors into the template,
|
| 1316 |
+
# to improve cache locality and avoid full-tensor copy.
|
| 1317 |
+
layout_str = (
|
| 1318 |
+
"VNNI4"
|
| 1319 |
+
if micro_gemm.get_b_layout() == LayoutType.VNNI4
|
| 1320 |
+
else "VNNI2"
|
| 1321 |
+
)
|
| 1322 |
+
assert micro_gemm.get_b_layout() in [
|
| 1323 |
+
LayoutType.VNNI2,
|
| 1324 |
+
LayoutType.VNNI4,
|
| 1325 |
+
], f"We only support {layout_str} for now"
|
| 1326 |
+
vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2
|
| 1327 |
+
assert k % vnni_size == 0, (
|
| 1328 |
+
f"k should be divisible by vnni_size for {layout_str} layout"
|
| 1329 |
+
)
|
| 1330 |
+
vnni_view_size = list(new_size)
|
| 1331 |
+
vnni_view_size[-2] = k // vnni_size
|
| 1332 |
+
vnni_view_size.insert(-1, vnni_size)
|
| 1333 |
+
W = W.view(vnni_view_size).transpose(-1, -2).contiguous().view(new_size)
|
| 1334 |
+
# normalize stride to be "contiguous_strides" per size
|
| 1335 |
+
# this avoids the problems in L.view during template codegen
|
| 1336 |
+
new_stride = [1]
|
| 1337 |
+
for sz in reversed(W.shape[1:]):
|
| 1338 |
+
new_stride.insert(0, new_stride[0] * sz)
|
| 1339 |
+
W = W.as_strided(W.shape, new_stride)
|
| 1340 |
+
return W
|
| 1341 |
+
|
| 1342 |
+
def get_default_reindexers(self, epilogue_nodes):
|
| 1343 |
+
return [None] * len(epilogue_nodes)
|
| 1344 |
+
|
| 1345 |
+
def get_options(
|
| 1346 |
+
self,
|
| 1347 |
+
kernel: CppTemplateKernel,
|
| 1348 |
+
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
|
| 1349 |
+
flag_template_buffer_has_other_users: Optional[bool] = None,
|
| 1350 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 1351 |
+
) -> dict[str, Any]:
|
| 1352 |
+
assert len(self.input_nodes) >= 2
|
| 1353 |
+
|
| 1354 |
+
int8_gemm = self.input_nodes[0].get_dtype() in [torch.uint8, torch.int8]
|
| 1355 |
+
x_scale = None
|
| 1356 |
+
x_zp = None
|
| 1357 |
+
w_scale = None
|
| 1358 |
+
w_zp = None
|
| 1359 |
+
inp = None
|
| 1360 |
+
q_group_size_node = None
|
| 1361 |
+
qscale_and_zeros = None
|
| 1362 |
+
if int8_gemm:
|
| 1363 |
+
X, W = self.input_nodes[0], self.input_nodes[1]
|
| 1364 |
+
bias_idx = 2 if self.has_bias else 1
|
| 1365 |
+
inp = self.input_nodes[bias_idx] if self.has_bias else None
|
| 1366 |
+
x_scale = self.input_nodes[bias_idx + 1]
|
| 1367 |
+
x_zp = self.input_nodes[bias_idx + 2]
|
| 1368 |
+
w_scale = self.input_nodes[bias_idx + 3]
|
| 1369 |
+
w_zp = self.input_nodes[bias_idx + 4]
|
| 1370 |
+
Y = self.output_node
|
| 1371 |
+
elif self.is_woq_int4():
|
| 1372 |
+
X, W = self.input_nodes[0], self.input_nodes[1]
|
| 1373 |
+
Y = self.output_node
|
| 1374 |
+
q_group_size_node = self.input_nodes[2]
|
| 1375 |
+
qscale_and_zeros = self.input_nodes[3]
|
| 1376 |
+
else:
|
| 1377 |
+
X, W = self.input_nodes[0], self.input_nodes[1]
|
| 1378 |
+
Y = self.output_node
|
| 1379 |
+
inp = self.input_nodes[2] if self.has_bias else None
|
| 1380 |
+
|
| 1381 |
+
template_buffer_has_other_users = None
|
| 1382 |
+
|
| 1383 |
+
if template_buffer_node is not None:
|
| 1384 |
+
# Use the updated prepacked weight buffer
|
| 1385 |
+
W = template_buffer_node.inputs[1]
|
| 1386 |
+
Y = template_buffer_node
|
| 1387 |
+
|
| 1388 |
+
assert flag_template_buffer_has_other_users is not None
|
| 1389 |
+
template_buffer_has_other_users = flag_template_buffer_has_other_users
|
| 1390 |
+
|
| 1391 |
+
template_buffer = Y
|
| 1392 |
+
gemm_output_buffer = template_buffer
|
| 1393 |
+
|
| 1394 |
+
epilogues: list[ir.IRNode] = []
|
| 1395 |
+
reindexers: list[Optional[Callable[[list[Any]], list[Any]]]] = []
|
| 1396 |
+
epilogue_creators: list[Callable[[ir.Buffer], ir.Pointwise]] = []
|
| 1397 |
+
fake_buffers: list[ir.Buffer] = []
|
| 1398 |
+
Y_aliases: OrderedSet[str] = OrderedSet()
|
| 1399 |
+
|
| 1400 |
+
use_local_acc = (
|
| 1401 |
+
self.layout.dtype != torch.float
|
| 1402 |
+
or template_buffer_has_other_users
|
| 1403 |
+
or int8_gemm
|
| 1404 |
+
or self.padded_n != self.n
|
| 1405 |
+
or self.maybe_k_slicing()
|
| 1406 |
+
or (epilogue_nodes and epilogue_nodes[-1].get_dtype() != self.layout.dtype)
|
| 1407 |
+
)
|
| 1408 |
+
|
| 1409 |
+
# TODO(jgong5): for int8 gemm, bias-add is handled outside of gemm template,
|
| 1410 |
+
# but we'd better move it here to align with fp.
|
| 1411 |
+
if inp is not None and self.beta != 0 and not int8_gemm:
|
| 1412 |
+
# add an epilogue for bias add
|
| 1413 |
+
def _bias_add_epilogue(buf):
|
| 1414 |
+
return create_epilogue_with_attr(
|
| 1415 |
+
buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype
|
| 1416 |
+
)
|
| 1417 |
+
|
| 1418 |
+
epilogue_creators.append(_bias_add_epilogue)
|
| 1419 |
+
|
| 1420 |
+
if self.epilogue_creator is not None:
|
| 1421 |
+
epilogue_creators.append(self.epilogue_creator)
|
| 1422 |
+
|
| 1423 |
+
# When the GEMM output buffer is localized but it has users other than the epilogue nodes,
|
| 1424 |
+
# we need to copy the value in the GEMM output local buffer to a global buffer.
|
| 1425 |
+
def need_copy_from_local_to_global_buffer_epilogue(
|
| 1426 |
+
use_local_acc, template_buffer_has_other_users, epilogue_creators
|
| 1427 |
+
):
|
| 1428 |
+
# The GEMM output buffer is a global buffer, thus copy is not needed.
|
| 1429 |
+
if not use_local_acc:
|
| 1430 |
+
return False
|
| 1431 |
+
|
| 1432 |
+
# The possible value of template_buffer_has_other_users is (None, False, True)
|
| 1433 |
+
# It is None when generating the gemm template during autotune and it will have value during scheduler codegen.
|
| 1434 |
+
# extra copy_from_local_to_global_buffer_epilogue is not needed in either of the below two cases:
|
| 1435 |
+
# 1. template_buffer_has_other_users is None (i.e. when doing the codegen during autotune)
|
| 1436 |
+
# 2. template_buffer_has_other_users is False, which means it's safe to keep the value in the
|
| 1437 |
+
# GEMM output buffer in local buffer only (no users outside of the epilogues will use its value).
|
| 1438 |
+
if not template_buffer_has_other_users:
|
| 1439 |
+
return False
|
| 1440 |
+
|
| 1441 |
+
# When bias is not None or self.epilogue_creator is not None,
|
| 1442 |
+
# there will be epilogue_creators after the GEMM.
|
| 1443 |
+
# The GEMM output buffer is localized while
|
| 1444 |
+
# the output buffer of the epilogue_creators is a global buffer.
|
| 1445 |
+
if epilogue_creators:
|
| 1446 |
+
return False
|
| 1447 |
+
|
| 1448 |
+
return True
|
| 1449 |
+
|
| 1450 |
+
if need_copy_from_local_to_global_buffer_epilogue(
|
| 1451 |
+
use_local_acc, template_buffer_has_other_users, epilogue_creators
|
| 1452 |
+
):
|
| 1453 |
+
|
| 1454 |
+
def copy_from_local_to_global_buffer_epilogue(input_buffer: ir.Buffer):
|
| 1455 |
+
dtype = self.layout.dtype
|
| 1456 |
+
input_loader = input_buffer.make_loader()
|
| 1457 |
+
|
| 1458 |
+
def copy_inner(index):
|
| 1459 |
+
input = input_loader(index)
|
| 1460 |
+
result = ops.to_dtype(input, dtype)
|
| 1461 |
+
return result
|
| 1462 |
+
|
| 1463 |
+
return ir.Pointwise(
|
| 1464 |
+
device=input_buffer.get_device_or_error(),
|
| 1465 |
+
dtype=self.layout.dtype,
|
| 1466 |
+
inner_fn=copy_inner,
|
| 1467 |
+
ranges=input_buffer.get_size(),
|
| 1468 |
+
)
|
| 1469 |
+
|
| 1470 |
+
epilogue_creators.append(copy_from_local_to_global_buffer_epilogue)
|
| 1471 |
+
|
| 1472 |
+
# NOTE [How CPP GEMM template epilogues are organized]
|
| 1473 |
+
# gemm_output_buffer
|
| 1474 |
+
# --> zero or more in-template epilogues (created by `epilogue_creators`) -->
|
| 1475 |
+
# template_buffer
|
| 1476 |
+
# --> zero or more out-of-template epilogues (`epilogue_nodes`) -->
|
| 1477 |
+
# Y
|
| 1478 |
+
if epilogue_creators:
|
| 1479 |
+
assert isinstance(template_buffer, ir.IRNode)
|
| 1480 |
+
gemm_output_name = f"{template_buffer.get_name()}_GemmOut"
|
| 1481 |
+
gemm_output_buffer = ir.Buffer(
|
| 1482 |
+
name=gemm_output_name,
|
| 1483 |
+
# pyrefly: ignore [missing-attribute]
|
| 1484 |
+
layout=template_buffer.layout,
|
| 1485 |
+
)
|
| 1486 |
+
current_input_buffer = gemm_output_buffer
|
| 1487 |
+
for i, creator in enumerate(epilogue_creators):
|
| 1488 |
+
if i == len(epilogue_creators) - 1:
|
| 1489 |
+
buffer_name = template_buffer.get_name()
|
| 1490 |
+
else:
|
| 1491 |
+
buffer_name = f"{gemm_output_name}_epilogue_{i}"
|
| 1492 |
+
epilogues.append(
|
| 1493 |
+
ir.ComputedBuffer(
|
| 1494 |
+
name=buffer_name,
|
| 1495 |
+
# pyrefly: ignore [missing-attribute]
|
| 1496 |
+
layout=template_buffer.layout,
|
| 1497 |
+
data=creator(current_input_buffer),
|
| 1498 |
+
)
|
| 1499 |
+
)
|
| 1500 |
+
fake_buffers.append(current_input_buffer)
|
| 1501 |
+
Y_aliases.add(current_input_buffer.get_name())
|
| 1502 |
+
reindexers.append(None)
|
| 1503 |
+
if i < len(epilogue_creators) - 1:
|
| 1504 |
+
current_input_buffer = ir.Buffer(
|
| 1505 |
+
name=buffer_name,
|
| 1506 |
+
# pyrefly: ignore [missing-attribute]
|
| 1507 |
+
layout=template_buffer.layout,
|
| 1508 |
+
)
|
| 1509 |
+
|
| 1510 |
+
assert isinstance(Y, (ir.Buffer, ir.ReinterpretView))
|
| 1511 |
+
Y_2d: Union[ir.Buffer, ir.ReinterpretView] = Y
|
| 1512 |
+
|
| 1513 |
+
if epilogue_nodes:
|
| 1514 |
+
if not template_buffer_has_other_users:
|
| 1515 |
+
assert isinstance(template_buffer, ir.IRNode)
|
| 1516 |
+
Y_aliases.add(template_buffer.get_name())
|
| 1517 |
+
epilogues.extend(epilogue_nodes)
|
| 1518 |
+
assert Y.get_numel() == epilogues[-1].get_numel()
|
| 1519 |
+
Y = cast(ir.Buffer, epilogues[-1])
|
| 1520 |
+
assert isinstance(template_buffer, ir.Buffer)
|
| 1521 |
+
Y_2d, reindexers = gen_2d_view_of_epilogue_buf(
|
| 1522 |
+
Y,
|
| 1523 |
+
template_buffer,
|
| 1524 |
+
epilogue_nodes,
|
| 1525 |
+
reindexers,
|
| 1526 |
+
default_reindexers=self.get_default_reindexers(epilogue_nodes),
|
| 1527 |
+
)
|
| 1528 |
+
|
| 1529 |
+
output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
|
| 1530 |
+
X.get_dtype()
|
| 1531 |
+
)
|
| 1532 |
+
micro_gemm = create_micro_gemm(
|
| 1533 |
+
f"{kernel.kernel_name}_micro_gemm",
|
| 1534 |
+
self.m,
|
| 1535 |
+
self.n,
|
| 1536 |
+
self.k,
|
| 1537 |
+
input_dtype=X.get_dtype(),
|
| 1538 |
+
# pyrefly: ignore [missing-attribute]
|
| 1539 |
+
input2_dtype=W.get_dtype(),
|
| 1540 |
+
output_dtype=output_dtype,
|
| 1541 |
+
compute_dtype=compute_dtype,
|
| 1542 |
+
alpha=self.alpha,
|
| 1543 |
+
num_threads=self.num_threads,
|
| 1544 |
+
use_ref=not self.is_woq_int4(),
|
| 1545 |
+
q_group_size=self.q_group_size(),
|
| 1546 |
+
)
|
| 1547 |
+
assert micro_gemm is not None
|
| 1548 |
+
micro_gemm.use_local_vnni_blocking(not self.should_block_weights)
|
| 1549 |
+
assert self.register_blocking == micro_gemm.register_blocking
|
| 1550 |
+
self.log_blockings()
|
| 1551 |
+
if isinstance(micro_gemm, CppMicroGemmAMX):
|
| 1552 |
+
counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1
|
| 1553 |
+
if isinstance(micro_gemm, CppMicroBrgemm):
|
| 1554 |
+
counters["inductor"]["cpp_micro_brgemm_counter"] += 1
|
| 1555 |
+
|
| 1556 |
+
L1_cache_size = torch._C._cpu._L1d_cache_size() # per core cache size in Bytes
|
| 1557 |
+
assert L1_cache_size > 0, f"Expect L1_cache_size > 0 but got {L1_cache_size}"
|
| 1558 |
+
|
| 1559 |
+
L2_cache_size = torch._C._cpu._L2_cache_size() # per core cache size in Bytes
|
| 1560 |
+
assert L2_cache_size > 0, f"Expect L2_cache_size > 0 but got {L2_cache_size}"
|
| 1561 |
+
|
| 1562 |
+
options = dict(
|
| 1563 |
+
X=X,
|
| 1564 |
+
W=W,
|
| 1565 |
+
inp=inp,
|
| 1566 |
+
Y=Y,
|
| 1567 |
+
N=self.n,
|
| 1568 |
+
K=self.k,
|
| 1569 |
+
PADDED_N=self.padded_n,
|
| 1570 |
+
GemmOut=gemm_output_buffer,
|
| 1571 |
+
aliases={alias: Y.get_name() for alias in Y_aliases},
|
| 1572 |
+
beta=self.beta,
|
| 1573 |
+
alpha=self.alpha,
|
| 1574 |
+
num_threads=self.num_threads,
|
| 1575 |
+
micro_gemm=micro_gemm,
|
| 1576 |
+
is_dynamic_M=self.is_dynamic_M,
|
| 1577 |
+
template=self,
|
| 1578 |
+
kernel=kernel,
|
| 1579 |
+
export_declaration=get_export_declaration(),
|
| 1580 |
+
epilogue_nodes=epilogues,
|
| 1581 |
+
reindexers=reindexers,
|
| 1582 |
+
Y_2d=Y_2d,
|
| 1583 |
+
use_local_acc=use_local_acc,
|
| 1584 |
+
maybe_k_slicing=self.maybe_k_slicing(),
|
| 1585 |
+
x_scale=x_scale,
|
| 1586 |
+
x_zp=x_zp,
|
| 1587 |
+
w_scale=w_scale,
|
| 1588 |
+
w_zp=w_zp,
|
| 1589 |
+
acc_buf_dtype=torch.int32 if int8_gemm else torch.float,
|
| 1590 |
+
DTYPE_TO_CPP=DTYPE_TO_CPP,
|
| 1591 |
+
L1_cache_size=L1_cache_size,
|
| 1592 |
+
L2_cache_size=L2_cache_size,
|
| 1593 |
+
config=config,
|
| 1594 |
+
fake_buffers=fake_buffers,
|
| 1595 |
+
is_woq_int4=self.is_woq_int4(),
|
| 1596 |
+
q_group_size=q_group_size_node,
|
| 1597 |
+
qscale_and_zeros=qscale_and_zeros,
|
| 1598 |
+
)
|
| 1599 |
+
return options
|
| 1600 |
+
|
| 1601 |
+
def is_int8_woq_gemm_small_m_dim(
|
| 1602 |
+
self,
|
| 1603 |
+
X: ir.ReinterpretView,
|
| 1604 |
+
W: ir.ReinterpretView,
|
| 1605 |
+
N,
|
| 1606 |
+
K,
|
| 1607 |
+
micro_gemm,
|
| 1608 |
+
):
|
| 1609 |
+
"""Use SMALL_M_GEMM_TEMPLATE"""
|
| 1610 |
+
return (
|
| 1611 |
+
isinstance(micro_gemm, CppMicroGemmFP32Vec)
|
| 1612 |
+
and is_int8_woq_gemm_small_m_dim_corner_case(
|
| 1613 |
+
micro_gemm, X.get_size()[0], N, K
|
| 1614 |
+
)
|
| 1615 |
+
and X.get_dtype() is torch.bfloat16
|
| 1616 |
+
and W.get_dtype() is torch.int8
|
| 1617 |
+
)
|
| 1618 |
+
|
| 1619 |
+
def render( # type: ignore[override, return]
|
| 1620 |
+
self,
|
| 1621 |
+
kernel: CppTemplateKernel,
|
| 1622 |
+
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
|
| 1623 |
+
flag_template_buffer_has_other_users: Optional[bool] = None,
|
| 1624 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 1625 |
+
**kwargs,
|
| 1626 |
+
) -> str:
|
| 1627 |
+
options = self.get_options(
|
| 1628 |
+
kernel=kernel,
|
| 1629 |
+
template_buffer_node=template_buffer_node,
|
| 1630 |
+
flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
|
| 1631 |
+
epilogue_nodes=epilogue_nodes,
|
| 1632 |
+
)
|
| 1633 |
+
self.render_options = options
|
| 1634 |
+
|
| 1635 |
+
with contextlib.ExitStack() as stack:
|
| 1636 |
+
for buf in options["fake_buffers"]:
|
| 1637 |
+
stack.enter_context(
|
| 1638 |
+
patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf))
|
| 1639 |
+
)
|
| 1640 |
+
if not options["is_dynamic_M"] and self.is_int8_woq_gemm_small_m_dim(
|
| 1641 |
+
options["X"],
|
| 1642 |
+
options["W"],
|
| 1643 |
+
options["N"],
|
| 1644 |
+
options["K"],
|
| 1645 |
+
options["micro_gemm"],
|
| 1646 |
+
):
|
| 1647 |
+
template_str = SMALL_M_GEMM_TEMPLATE
|
| 1648 |
+
else:
|
| 1649 |
+
template_str = GEMM_TEMPLATE
|
| 1650 |
+
return self._template_from_string(template_str).render(**options)
|
| 1651 |
+
|
| 1652 |
+
def codegen_blocks(
|
| 1653 |
+
self,
|
| 1654 |
+
num_threads,
|
| 1655 |
+
N,
|
| 1656 |
+
K,
|
| 1657 |
+
micro_gemm,
|
| 1658 |
+
is_dynamic_M,
|
| 1659 |
+
kernel,
|
| 1660 |
+
GemmOut,
|
| 1661 |
+
config,
|
| 1662 |
+
L1_cache_size,
|
| 1663 |
+
L2_cache_size,
|
| 1664 |
+
X,
|
| 1665 |
+
W,
|
| 1666 |
+
):
|
| 1667 |
+
options = dict(
|
| 1668 |
+
num_threads=num_threads,
|
| 1669 |
+
N=N,
|
| 1670 |
+
K=K,
|
| 1671 |
+
micro_gemm=micro_gemm,
|
| 1672 |
+
is_dynamic_M=is_dynamic_M,
|
| 1673 |
+
kernel=kernel,
|
| 1674 |
+
GemmOut=GemmOut,
|
| 1675 |
+
config=config,
|
| 1676 |
+
L1_cache_size=L1_cache_size,
|
| 1677 |
+
L2_cache_size=L2_cache_size,
|
| 1678 |
+
template=self,
|
| 1679 |
+
X=X,
|
| 1680 |
+
W=W,
|
| 1681 |
+
is_woq_int4=self.is_woq_int4(),
|
| 1682 |
+
)
|
| 1683 |
+
template_str = GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK
|
| 1684 |
+
if not (
|
| 1685 |
+
not is_dynamic_M
|
| 1686 |
+
and self.is_int8_woq_gemm_small_m_dim(X, W, N, K, micro_gemm)
|
| 1687 |
+
):
|
| 1688 |
+
template_str += GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED
|
| 1689 |
+
return self._template_from_string(template_str).render(options)
|
| 1690 |
+
|
| 1691 |
+
def codegen_microkernel_def(self):
|
| 1692 |
+
return self._template_from_string(GEMM_TEMPLATE_MICROKERNEL_DEF).render(
|
| 1693 |
+
self.render_options
|
| 1694 |
+
)
|
| 1695 |
+
|
| 1696 |
+
def codegen_gemm_stub_def(self):
|
| 1697 |
+
microkernel = self.codegen_microkernel_def()
|
| 1698 |
+
return microkernel + self._template_from_string(GEMM_TEMPLATE_STUB_DEF).render(
|
| 1699 |
+
self.render_options
|
| 1700 |
+
)
|
| 1701 |
+
|
| 1702 |
+
def codegen_multi_threads_params(self):
|
| 1703 |
+
return self._template_from_string(GEMM_TEMPLATE_MULTI_THREADS_PARAMS).render()
|
| 1704 |
+
|
| 1705 |
+
def codegen_single_thread_params(self, is_dynamic_M):
|
| 1706 |
+
options = dict(
|
| 1707 |
+
is_dynamic_M=is_dynamic_M,
|
| 1708 |
+
)
|
| 1709 |
+
return self._template_from_string(GEMM_TEMPLATE_SINGLE_THREAD_PARAMS).render(
|
| 1710 |
+
options
|
| 1711 |
+
)
|
| 1712 |
+
|
| 1713 |
+
def codegen_m_loop_params(self):
|
| 1714 |
+
return self._template_from_string(GEMM_TEMPLATE_M_LOOP_PARAMS).render()
|
| 1715 |
+
|
| 1716 |
+
def codegen_n_loop_params(self):
|
| 1717 |
+
return self._template_from_string(GEMM_TEMPLATE_N_LOOP_PARAMS).render()
|
| 1718 |
+
|
| 1719 |
+
@classmethod
|
| 1720 |
+
def is_woq_int4(cls):
|
| 1721 |
+
return False
|
| 1722 |
+
|
| 1723 |
+
@classmethod
|
| 1724 |
+
def q_group_size(cls):
|
| 1725 |
+
return None
|
| 1726 |
+
|
| 1727 |
+
|
| 1728 |
+
class CppWoqInt4GemmTemplateMeta(type):
|
| 1729 |
+
def __getitem__(cls, q_group_size):
|
| 1730 |
+
class CppWoqInt4GemmTemplateInstance(CppGemmTemplate):
|
| 1731 |
+
def __init__(
|
| 1732 |
+
self,
|
| 1733 |
+
*args,
|
| 1734 |
+
**kwargs,
|
| 1735 |
+
) -> None:
|
| 1736 |
+
super().__init__(
|
| 1737 |
+
*args,
|
| 1738 |
+
**kwargs,
|
| 1739 |
+
)
|
| 1740 |
+
|
| 1741 |
+
@classmethod
|
| 1742 |
+
def is_woq_int4(cls):
|
| 1743 |
+
return True
|
| 1744 |
+
|
| 1745 |
+
@classmethod
|
| 1746 |
+
def q_group_size(cls):
|
| 1747 |
+
return q_group_size
|
| 1748 |
+
|
| 1749 |
+
@staticmethod
|
| 1750 |
+
def check_if_block_weight(W, micro_gemm):
|
| 1751 |
+
# For WOQ INT4, weight is already packed
|
| 1752 |
+
# However, for AMX microkernel, we want to change the blocking of weight
|
| 1753 |
+
from .cpp_micro_gemm import CppMicroGemmWoQInt4Amx
|
| 1754 |
+
|
| 1755 |
+
return isinstance(micro_gemm, CppMicroGemmWoQInt4Amx)
|
| 1756 |
+
|
| 1757 |
+
@classmethod
|
| 1758 |
+
def block_weight(cls, W, new_size, padding):
|
| 1759 |
+
# This method is called only if AMX microkernels are used.
|
| 1760 |
+
# In this case, we unpack and repack weight so that block_n=32
|
| 1761 |
+
# the format of packed weight is described here:
|
| 1762 |
+
# https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L583
|
| 1763 |
+
if isinstance(W, ir.IRNode):
|
| 1764 |
+
# in this case, we do nothing
|
| 1765 |
+
ir.ExternKernel.require_contiguous(W)
|
| 1766 |
+
blocked_w = W
|
| 1767 |
+
else:
|
| 1768 |
+
# in this case, we unpack and repack weight
|
| 1769 |
+
assert isinstance(W, torch.Tensor)
|
| 1770 |
+
assert W.dim() == 2
|
| 1771 |
+
N = W.size(0)
|
| 1772 |
+
K = W.size(-1) * 2
|
| 1773 |
+
G = cls.q_group_size()
|
| 1774 |
+
# x and qscales_and_zeros are in bfloat16 instead of float to use the optimized kernel
|
| 1775 |
+
# so that the unpacking process is faster
|
| 1776 |
+
x = torch.eye(K).bfloat16()
|
| 1777 |
+
# Here we use scale=1 and qzero=8 because we want to unpack weight
|
| 1778 |
+
# without dequantizing it. The qzero here is 8 instead of 0 because
|
| 1779 |
+
# int4 values are converted to [-7, 8] in the _weight_int4pack_mm_for_cpu kernel:
|
| 1780 |
+
# https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L95
|
| 1781 |
+
qscales_and_zeros = (
|
| 1782 |
+
torch.tensor([1.0, 8.0])
|
| 1783 |
+
.bfloat16()
|
| 1784 |
+
.expand(K // G, N, 2)
|
| 1785 |
+
.contiguous()
|
| 1786 |
+
)
|
| 1787 |
+
# shape: [K, N]
|
| 1788 |
+
unpacked_w = torch.ops.aten._weight_int4pack_mm_for_cpu(
|
| 1789 |
+
x,
|
| 1790 |
+
W,
|
| 1791 |
+
G,
|
| 1792 |
+
qscales_and_zeros,
|
| 1793 |
+
).to(torch.uint8)
|
| 1794 |
+
block_n = 32
|
| 1795 |
+
# shape: [N // block_n, K, block_n]
|
| 1796 |
+
w_blocked = (
|
| 1797 |
+
unpacked_w.view(K, N // block_n, block_n)
|
| 1798 |
+
.permute(1, 0, 2)
|
| 1799 |
+
.contiguous()
|
| 1800 |
+
)
|
| 1801 |
+
# pack 2 int4 -> 1 int8
|
| 1802 |
+
# block_n: [a0, a1, ..., a15, b0, b1, ..., b15]
|
| 1803 |
+
# -> [(a0 & 0xf) | (b0 << 4), (a1 & 0xf) | (b1 << 4), ...]
|
| 1804 |
+
# shape: [N // block_n, K, 2, block_n // 2]
|
| 1805 |
+
w_blocked = w_blocked.view(N // block_n, K, 2, block_n // 2)
|
| 1806 |
+
# shape: [N // block_n, K, block_n // 2]
|
| 1807 |
+
w_blocked_packed = (w_blocked[:, :, 0, :] & 0xF) | (
|
| 1808 |
+
w_blocked[:, :, 1, :] << 4
|
| 1809 |
+
)
|
| 1810 |
+
# shape: [N, K // 2]
|
| 1811 |
+
blocked_w = w_blocked_packed.view(N, K // 2)
|
| 1812 |
+
|
| 1813 |
+
return blocked_w
|
| 1814 |
+
|
| 1815 |
+
return CppWoqInt4GemmTemplateInstance
|
| 1816 |
+
|
| 1817 |
+
|
| 1818 |
+
class CppWoqInt4GemmTemplate(metaclass=CppWoqInt4GemmTemplateMeta):
|
| 1819 |
+
pass
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextlib
|
| 2 |
+
import logging
|
| 3 |
+
from collections.abc import Callable
|
| 4 |
+
from typing import Any, cast, Optional, TypeVar
|
| 5 |
+
from unittest.mock import patch
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch.utils
|
| 9 |
+
from torch.utils._ordered_set import OrderedSet
|
| 10 |
+
|
| 11 |
+
from ..._dynamo.utils import counters
|
| 12 |
+
from .. import config, ir
|
| 13 |
+
from ..kernel.mm_common import mm_args
|
| 14 |
+
from ..select_algorithm import ChoiceCaller, DataProcessorTemplateWrapper
|
| 15 |
+
from ..utils import parallel_num_threads
|
| 16 |
+
from ..virtualized import V
|
| 17 |
+
from .cpp import get_export_declaration
|
| 18 |
+
from .cpp_gemm_template import (
|
| 19 |
+
CppGemmTemplate,
|
| 20 |
+
expand_bias,
|
| 21 |
+
gen_2d_view_of_epilogue_buf,
|
| 22 |
+
prune_tensors,
|
| 23 |
+
transpose_w,
|
| 24 |
+
)
|
| 25 |
+
from .cpp_micro_gemm import CppMicroGemmAMX, create_micro_gemm
|
| 26 |
+
from .cpp_template_kernel import CppTemplateKernel
|
| 27 |
+
from .cpp_utils import (
|
| 28 |
+
create_epilogue_with_attr,
|
| 29 |
+
DTYPE_TO_CPP,
|
| 30 |
+
GemmBlocking,
|
| 31 |
+
get_gemm_template_output_and_compute_dtype,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
log = logging.getLogger(__name__)
|
| 36 |
+
|
| 37 |
+
GEMM_TEMPLATE = r"""
|
| 38 |
+
{{template.header().getvalue()}}
|
| 39 |
+
{{micro_gemm.codegen_define(kernel)}}
|
| 40 |
+
|
| 41 |
+
extern "C" {{export_declaration}}
|
| 42 |
+
{{kernel.def_kernel(inputs=kernel_args, outputs=Y_list, aliases=aliases)}}
|
| 43 |
+
{
|
| 44 |
+
{{kernel.maybe_codegen_profile()}}
|
| 45 |
+
{{ template.codegen_blocks(
|
| 46 |
+
num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOuts[0], config, L1_cache_size, L2_cache_size, X_list[0], W_list[0]
|
| 47 |
+
) }}
|
| 48 |
+
{%- if num_threads > 1 %}
|
| 49 |
+
#pragma omp parallel num_threads({{num_threads}})
|
| 50 |
+
{
|
| 51 |
+
{{ template.codegen_multi_threads_params()|indent(8, false) }}
|
| 52 |
+
{%- else %}
|
| 53 |
+
{
|
| 54 |
+
{{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }}
|
| 55 |
+
{%- endif %}
|
| 56 |
+
{{ micro_gemm.codegen_init(kernel) }}
|
| 57 |
+
{%- set acc_buf_name_list=[] %}
|
| 58 |
+
{%- set acc_buf_name_prefix = "local_acc_buf_" %}
|
| 59 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 60 |
+
{%- set acc_buf_name = acc_buf_name_prefix + gemm_idx|string %}
|
| 61 |
+
{{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }}
|
| 62 |
+
{%- set acc_buf_name_list=acc_buf_name_list.append(acc_buf_name) %}
|
| 63 |
+
{%- endfor %}
|
| 64 |
+
for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) {
|
| 65 |
+
{{ template.codegen_m_loop_params()|indent(12, false) }}
|
| 66 |
+
for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) {
|
| 67 |
+
{{ template.codegen_n_loop_params()|indent(16, false) }}
|
| 68 |
+
{%- set acc_list=[] %}
|
| 69 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 70 |
+
{%- set acc_list = acc_list.append( kernel.local_buffers[acc_buf_name_list[gemm_idx]] ) %}
|
| 71 |
+
{{ kernel.reinit_buffer_if_null(acc_buf_name_list[gemm_idx]) }}
|
| 72 |
+
{%- endfor %}
|
| 73 |
+
for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) {
|
| 74 |
+
int64_t k_start = kc * Kr;
|
| 75 |
+
int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K);
|
| 76 |
+
{%- set tile_X_list=[] %}
|
| 77 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 78 |
+
{%- set tile_X_list = tile_X_list.append( kernel.slice_nd(X_list[gemm_idx], [("m_start", "m_end"), ("k_start", "k_end")]) ) %}
|
| 79 |
+
{%- endfor %}
|
| 80 |
+
for (int64_t nci = nc; nci < nc_block_end; nci++) {
|
| 81 |
+
{%- set tile_W_3d_list=[] %}
|
| 82 |
+
{%- set tile_W_list=[] %}
|
| 83 |
+
{%- set acc_slice_list=[] %}
|
| 84 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 85 |
+
{%- set acc_slice_list = acc_slice_list.append(
|
| 86 |
+
kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")])
|
| 87 |
+
) %}
|
| 88 |
+
{%- set tile_W_3d_list = tile_W_3d_list.append(
|
| 89 |
+
kernel.slice_nd(W_list[gemm_idx], [("nci", "nci + 1"), ("k_start", "k_end"), ()])
|
| 90 |
+
) %}
|
| 91 |
+
{%- endfor %}
|
| 92 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 93 |
+
{%- set tile_W_list = tile_W_list.append(
|
| 94 |
+
kernel.view(tile_W_3d_list[gemm_idx], ["k_end - k_start", micro_gemm.register_blocking.block_n])
|
| 95 |
+
) %}
|
| 96 |
+
{%- endfor %}
|
| 97 |
+
if (kc == k_block_start) {
|
| 98 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 99 |
+
{{ micro_gemm.codegen_call(
|
| 100 |
+
kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=False
|
| 101 |
+
)|indent(28, false) }}
|
| 102 |
+
{%- endfor %}
|
| 103 |
+
} else {
|
| 104 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 105 |
+
{{ micro_gemm.codegen_call(
|
| 106 |
+
kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=True
|
| 107 |
+
)|indent(28, false) }}
|
| 108 |
+
{%- endfor %}
|
| 109 |
+
}
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
{
|
| 113 |
+
{%- set tile_acc_list = [] %}
|
| 114 |
+
{%- set tile_Y_list = [] %}
|
| 115 |
+
{%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
|
| 116 |
+
{%- set tile_acc_list = tile_acc_list.append(
|
| 117 |
+
kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("0", "n_end - n_start")])
|
| 118 |
+
) %}
|
| 119 |
+
{%- set tile_Y_list = tile_Y_list.append(
|
| 120 |
+
kernel.slice_nd(Y_2d_list[gemm_idx], [("m_start", "m_end"), ("n_start", "n_end")])
|
| 121 |
+
) %}
|
| 122 |
+
{%- endfor %}
|
| 123 |
+
{{ kernel.store_outputs(
|
| 124 |
+
tile_Y_list,
|
| 125 |
+
tile_acc_list,
|
| 126 |
+
GemmOuts,
|
| 127 |
+
epilogue_nodes,
|
| 128 |
+
offsets=("m_start", "n_start"),
|
| 129 |
+
reindexers=reindexers,
|
| 130 |
+
multi_output_buffers=multi_output_buffers
|
| 131 |
+
)|indent(20, false)
|
| 132 |
+
}}
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
}
|
| 136 |
+
{{ micro_gemm.codegen_finalize(kernel) }}
|
| 137 |
+
}
|
| 138 |
+
}
|
| 139 |
+
"""
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_deduplicated_act(act_mapping: dict[int, ir.IRNode]) -> list[ir.IRNode]:
|
| 143 |
+
act_deduplicated = []
|
| 144 |
+
act_deduplicated_name: OrderedSet[str] = OrderedSet()
|
| 145 |
+
for act_idx in range(len(act_mapping.values())):
|
| 146 |
+
act = act_mapping[act_idx]
|
| 147 |
+
if act.get_name() not in act_deduplicated_name:
|
| 148 |
+
act_deduplicated.append(act)
|
| 149 |
+
act_deduplicated_name.add(act.get_name())
|
| 150 |
+
return act_deduplicated
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class CppGroupedGemmTemplate(CppGemmTemplate):
|
| 154 |
+
def __init__(
|
| 155 |
+
self,
|
| 156 |
+
input_nodes: list[ir.IRNode],
|
| 157 |
+
layout: ir.Layout,
|
| 158 |
+
num_threads: int,
|
| 159 |
+
register_blocking: GemmBlocking,
|
| 160 |
+
beta: int = 1,
|
| 161 |
+
alpha: int = 1,
|
| 162 |
+
has_bias: bool = False,
|
| 163 |
+
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
|
| 164 |
+
act_mapping: Optional[dict[int, ir.IRNode]] = None,
|
| 165 |
+
gemm_grouped_num: int = 1,
|
| 166 |
+
) -> None:
|
| 167 |
+
"""
|
| 168 |
+
Template for Group of GEMMs:
|
| 169 |
+
* Each GEMM has the same dimensions (m, n, k) and the same leading dimensions (lda, ldb, ldc)
|
| 170 |
+
for their A, B, and C matrices.
|
| 171 |
+
* Each GEMM has distinct or shared activations, has distinct weight, has unique bias or no bias, has distinct epilogues.
|
| 172 |
+
* In the current implementation, the outputs of all GEMMs are accumulated using pointwise epilogues.
|
| 173 |
+
This behavior can be extended in the future if needed.
|
| 174 |
+
"""
|
| 175 |
+
super().__init__(
|
| 176 |
+
input_nodes,
|
| 177 |
+
layout,
|
| 178 |
+
num_threads,
|
| 179 |
+
register_blocking,
|
| 180 |
+
beta,
|
| 181 |
+
alpha,
|
| 182 |
+
has_bias,
|
| 183 |
+
epilogue_creator,
|
| 184 |
+
)
|
| 185 |
+
self.act_mapping = act_mapping
|
| 186 |
+
self.gemm_grouped_num = gemm_grouped_num
|
| 187 |
+
# pyrefly: ignore [bad-override]
|
| 188 |
+
self.output_node: list[ir.Buffer] = [
|
| 189 |
+
ir.Buffer(name="buf_out" + str(idx), layout=layout)
|
| 190 |
+
for idx in range(gemm_grouped_num)
|
| 191 |
+
]
|
| 192 |
+
|
| 193 |
+
@classmethod
|
| 194 |
+
# pyrefly: ignore [bad-override]
|
| 195 |
+
def add_choices(
|
| 196 |
+
cls,
|
| 197 |
+
choices: list[ChoiceCaller],
|
| 198 |
+
layout: ir.Layout,
|
| 199 |
+
input_nodes: list[ir.IRNode],
|
| 200 |
+
beta: int = 1,
|
| 201 |
+
alpha: int = 1,
|
| 202 |
+
has_bias: tuple[bool, ...] = (False, False),
|
| 203 |
+
trans_w: bool = False,
|
| 204 |
+
input_indices: Optional[list[int]] = None,
|
| 205 |
+
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
|
| 206 |
+
act_mapping: Optional[dict[int, ir.IRNode]] = None, # gemm idx to its act buf
|
| 207 |
+
) -> DataProcessorTemplateWrapper:
|
| 208 |
+
# Input nodes order: x, optional[x1], ... w0, w1, ... optional[b0], optional[b1], ...
|
| 209 |
+
gemm_grouped_num = len(has_bias)
|
| 210 |
+
assert act_mapping
|
| 211 |
+
act_deduplicated = get_deduplicated_act(act_mapping)
|
| 212 |
+
wgt_start_idx = len(act_deduplicated)
|
| 213 |
+
bias_start_idx = wgt_start_idx + gemm_grouped_num
|
| 214 |
+
input_indices = list(range(len(input_nodes)))
|
| 215 |
+
|
| 216 |
+
_T = TypeVar("_T", ir.IRNode, torch.Tensor)
|
| 217 |
+
_U = TypeVar("_U", ir.Layout, torch.Tensor)
|
| 218 |
+
|
| 219 |
+
def reorder_and_filter(
|
| 220 |
+
inputs: list[_T],
|
| 221 |
+
layout_or_out: _U,
|
| 222 |
+
) -> tuple[list[_T], _U]:
|
| 223 |
+
assert input_indices is not None, "input_indices must be set"
|
| 224 |
+
return [inputs[idx] for idx in input_indices], layout_or_out
|
| 225 |
+
|
| 226 |
+
new_inputs, new_layout = reorder_and_filter(input_nodes, layout)
|
| 227 |
+
|
| 228 |
+
def maybe_to_dense(
|
| 229 |
+
inputs: list[_T],
|
| 230 |
+
layout_or_out: _U,
|
| 231 |
+
) -> tuple[list[_T], _U]:
|
| 232 |
+
new_inputs = list(inputs)
|
| 233 |
+
for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num):
|
| 234 |
+
if isinstance(inputs[idx], torch.Tensor):
|
| 235 |
+
W = inputs[idx]
|
| 236 |
+
assert isinstance(W, torch.Tensor), "W must be a torch.Tensor"
|
| 237 |
+
# pyrefly: ignore [unsupported-operation]
|
| 238 |
+
new_inputs[idx] = W.to_dense() if W.is_mkldnn else W
|
| 239 |
+
return new_inputs, layout_or_out
|
| 240 |
+
|
| 241 |
+
def normalize_shapes(
|
| 242 |
+
inputs: list[_T],
|
| 243 |
+
layout_or_out: _U,
|
| 244 |
+
) -> tuple[list[_T], _U]:
|
| 245 |
+
new_inputs: list[_T] = list(inputs)
|
| 246 |
+
if not trans_w:
|
| 247 |
+
return new_inputs, layout_or_out
|
| 248 |
+
X = new_inputs[0]
|
| 249 |
+
for wgt_idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num):
|
| 250 |
+
new_input = new_inputs[wgt_idx]
|
| 251 |
+
new_inputs[wgt_idx] = transpose_w(new_input, trans_w)
|
| 252 |
+
for bias_idx in range(bias_start_idx, len(new_inputs)):
|
| 253 |
+
# pyrefly: ignore [bad-argument-type]
|
| 254 |
+
new_bias = expand_bias(new_inputs[bias_idx], X)
|
| 255 |
+
assert new_bias is not None
|
| 256 |
+
# pyrefly: ignore [unsupported-operation]
|
| 257 |
+
new_inputs[bias_idx] = new_bias
|
| 258 |
+
return new_inputs, layout_or_out
|
| 259 |
+
|
| 260 |
+
num_threads = parallel_num_threads()
|
| 261 |
+
new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout))
|
| 262 |
+
m, n, k, *_ = mm_args(new_inputs[0], new_inputs[wgt_start_idx])
|
| 263 |
+
output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
|
| 264 |
+
new_inputs[0].get_dtype()
|
| 265 |
+
)
|
| 266 |
+
micro_gemm = create_micro_gemm(
|
| 267 |
+
"micro_gemm",
|
| 268 |
+
m,
|
| 269 |
+
n,
|
| 270 |
+
k,
|
| 271 |
+
input_dtype=new_inputs[0].get_dtype(),
|
| 272 |
+
input2_dtype=new_inputs[wgt_start_idx].get_dtype(),
|
| 273 |
+
output_dtype=output_dtype,
|
| 274 |
+
compute_dtype=compute_dtype,
|
| 275 |
+
alpha=alpha,
|
| 276 |
+
num_threads=num_threads,
|
| 277 |
+
)
|
| 278 |
+
assert micro_gemm is not None
|
| 279 |
+
_, block_n, _ = micro_gemm.register_blocking
|
| 280 |
+
new_size, padded_n = cls.get_padded_size(
|
| 281 |
+
n, block_n, k, should_block_weight=True
|
| 282 |
+
)
|
| 283 |
+
padding = padded_n - n
|
| 284 |
+
|
| 285 |
+
def pack_weight(
|
| 286 |
+
inputs: list[_T],
|
| 287 |
+
layout_or_out: _U,
|
| 288 |
+
) -> tuple[list[_T], _U]:
|
| 289 |
+
new_W_list = []
|
| 290 |
+
new_inputs = list(inputs)
|
| 291 |
+
W_list = new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num]
|
| 292 |
+
for W in W_list:
|
| 293 |
+
blocked_w = cls.block_weight(W, new_size, padding)
|
| 294 |
+
new_W_list.append(cls.pack_vnni_weight(blocked_w, micro_gemm, new_size))
|
| 295 |
+
new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = new_W_list
|
| 296 |
+
return new_inputs, layout_or_out
|
| 297 |
+
|
| 298 |
+
def preprocessor(
|
| 299 |
+
inputs: list[_T],
|
| 300 |
+
layout: _U,
|
| 301 |
+
) -> tuple[list[_T], _U]:
|
| 302 |
+
return pack_weight(
|
| 303 |
+
*normalize_shapes(*maybe_to_dense(*reorder_and_filter(inputs, layout)))
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
def postprocessor(output: _T) -> _T:
|
| 307 |
+
if isinstance(output, ir.TensorBox):
|
| 308 |
+
template_buffer = ir.InputsKernel.unwrap_storage_for_input(output)
|
| 309 |
+
assert isinstance(template_buffer, ir.CppTemplateBuffer)
|
| 310 |
+
new_input_nodes, _ = reorder_and_filter(input_nodes, layout)
|
| 311 |
+
W_nodes = new_input_nodes[
|
| 312 |
+
wgt_start_idx : wgt_start_idx + gemm_grouped_num
|
| 313 |
+
]
|
| 314 |
+
W_tensor = []
|
| 315 |
+
for W_node in W_nodes:
|
| 316 |
+
assert W_node.get_name() in V.graph.constants
|
| 317 |
+
# pyrefly: ignore [bad-argument-type]
|
| 318 |
+
W_tensor.append(V.graph.constants[W_node.get_name()])
|
| 319 |
+
new_input_nodes[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = (
|
| 320 |
+
W_tensor # type: ignore[assignment]
|
| 321 |
+
)
|
| 322 |
+
new_input_nodes, _ = pack_weight(
|
| 323 |
+
*normalize_shapes(*maybe_to_dense(new_input_nodes, layout))
|
| 324 |
+
)
|
| 325 |
+
# Prune unused tensors
|
| 326 |
+
prune_tensors(input_nodes, new_input_nodes)
|
| 327 |
+
for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num):
|
| 328 |
+
W_packed = new_input_nodes[idx]
|
| 329 |
+
assert isinstance(W_packed, torch.Tensor)
|
| 330 |
+
W_packed_constant = V.graph.add_tensor_constant(W_packed)
|
| 331 |
+
template_buffer.inputs[idx] = (
|
| 332 |
+
ir.InputsKernel.unwrap_storage_for_input(W_packed_constant)
|
| 333 |
+
)
|
| 334 |
+
# pyrefly: ignore [bad-return]
|
| 335 |
+
return output
|
| 336 |
+
|
| 337 |
+
template = DataProcessorTemplateWrapper(
|
| 338 |
+
CppGroupedGemmTemplate,
|
| 339 |
+
preprocessor,
|
| 340 |
+
postprocessor,
|
| 341 |
+
input_nodes=input_nodes,
|
| 342 |
+
layout=layout,
|
| 343 |
+
num_threads=num_threads,
|
| 344 |
+
register_blocking=micro_gemm.register_blocking,
|
| 345 |
+
beta=beta,
|
| 346 |
+
alpha=alpha,
|
| 347 |
+
has_bias=has_bias,
|
| 348 |
+
epilogue_creator=epilogue_creator,
|
| 349 |
+
act_mapping=act_mapping,
|
| 350 |
+
gemm_grouped_num=gemm_grouped_num,
|
| 351 |
+
)
|
| 352 |
+
template.maybe_append_choice(choices)
|
| 353 |
+
return template
|
| 354 |
+
|
| 355 |
+
def render( # type: ignore[override,return,no-untyped-def]
|
| 356 |
+
self,
|
| 357 |
+
kernel: CppTemplateKernel,
|
| 358 |
+
template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
|
| 359 |
+
flag_template_buffer_has_other_users: Optional[bool] = None,
|
| 360 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 361 |
+
**kwargs,
|
| 362 |
+
) -> str:
|
| 363 |
+
assert self.act_mapping
|
| 364 |
+
act_deduplicated = get_deduplicated_act(self.act_mapping)
|
| 365 |
+
wgt_start_idx = len(act_deduplicated)
|
| 366 |
+
bias_start_idx = wgt_start_idx + self.gemm_grouped_num
|
| 367 |
+
X_list = list(self.act_mapping.values())
|
| 368 |
+
W_list = self.input_nodes[wgt_start_idx : wgt_start_idx + self.gemm_grouped_num]
|
| 369 |
+
inp_list = []
|
| 370 |
+
cur_idx = bias_start_idx
|
| 371 |
+
for inp_idx in range(self.gemm_grouped_num):
|
| 372 |
+
inp = None
|
| 373 |
+
# pyrefly: ignore [index-error]
|
| 374 |
+
if self.has_bias[inp_idx]:
|
| 375 |
+
inp = self.input_nodes[cur_idx]
|
| 376 |
+
cur_idx += 1
|
| 377 |
+
inp_list.append(inp)
|
| 378 |
+
|
| 379 |
+
Y_list = self.output_node
|
| 380 |
+
multi_output_buffers = None
|
| 381 |
+
if template_buffer_node is not None:
|
| 382 |
+
W_list = template_buffer_node.inputs[
|
| 383 |
+
wgt_start_idx : wgt_start_idx + self.gemm_grouped_num
|
| 384 |
+
]
|
| 385 |
+
assert isinstance(template_buffer_node.outputs, list)
|
| 386 |
+
Y_list = template_buffer_node.outputs
|
| 387 |
+
counters["inductor"]["cpp_grouped_gemm_template"] += 1
|
| 388 |
+
multi_output_buffers = template_buffer_node.outputs
|
| 389 |
+
|
| 390 |
+
template_buffer = Y_list[0]
|
| 391 |
+
fake_buffers: list[ir.Buffer] = []
|
| 392 |
+
Y_2d_list = Y_list
|
| 393 |
+
output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
|
| 394 |
+
X_list[0].get_dtype()
|
| 395 |
+
)
|
| 396 |
+
micro_gemm = create_micro_gemm(
|
| 397 |
+
f"{kernel.kernel_name}_micro_gemm",
|
| 398 |
+
self.m,
|
| 399 |
+
self.n,
|
| 400 |
+
self.k,
|
| 401 |
+
input_dtype=X_list[0].get_dtype(),
|
| 402 |
+
# pyrefly: ignore [missing-attribute]
|
| 403 |
+
input2_dtype=W_list[0].get_dtype(),
|
| 404 |
+
output_dtype=output_dtype,
|
| 405 |
+
compute_dtype=compute_dtype,
|
| 406 |
+
alpha=self.alpha,
|
| 407 |
+
num_threads=self.num_threads,
|
| 408 |
+
)
|
| 409 |
+
assert micro_gemm is not None
|
| 410 |
+
assert self.register_blocking == micro_gemm.register_blocking
|
| 411 |
+
self.log_blockings()
|
| 412 |
+
if isinstance(micro_gemm, CppMicroGemmAMX):
|
| 413 |
+
counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1
|
| 414 |
+
|
| 415 |
+
L1_cache_size = torch._C._cpu._L1d_cache_size() # per core cache size in Bytes
|
| 416 |
+
assert L1_cache_size > 0, f"Expect L1_cache_size > 0 but got {L1_cache_size}"
|
| 417 |
+
|
| 418 |
+
L2_cache_size = torch._C._cpu._L2_cache_size() # per core cache size in Bytes
|
| 419 |
+
assert L2_cache_size > 0, f"Expect L2_cache_size > 0 but got {L2_cache_size}"
|
| 420 |
+
|
| 421 |
+
epilogues: list[ir.IRNode] = []
|
| 422 |
+
reindexers: list[Optional[Callable[[list[Any]], list[Any]]]] = []
|
| 423 |
+
gemm_output_buffers: list[ir.Buffer] = []
|
| 424 |
+
for out_buf_idx in range(self.gemm_grouped_num):
|
| 425 |
+
gemm_output_name = f"{template_buffer.get_name()}_GemmOut" + str(
|
| 426 |
+
out_buf_idx
|
| 427 |
+
)
|
| 428 |
+
gemm_output_buffers.append(
|
| 429 |
+
ir.Buffer(name=gemm_output_name, layout=template_buffer.layout)
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
assert not self.epilogue_creator, (
|
| 433 |
+
"epilogue_creator is not supported yet in Grouped GEMM Template"
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
kernel_args: dict[str, Optional[ir.IRNode]] = {}
|
| 437 |
+
for x_idx in range(wgt_start_idx):
|
| 438 |
+
kernel_args["X" + str(x_idx)] = act_deduplicated[x_idx]
|
| 439 |
+
for w_idx in range(self.gemm_grouped_num):
|
| 440 |
+
# pyrefly: ignore [unsupported-operation]
|
| 441 |
+
kernel_args["W" + str(w_idx)] = W_list[w_idx]
|
| 442 |
+
for inp_idx in range(self.gemm_grouped_num):
|
| 443 |
+
kernel_args["inp" + str(inp_idx)] = inp_list[inp_idx]
|
| 444 |
+
|
| 445 |
+
def _bias_add_epilogue(buf: ir.IRNode, inp: ir.IRNode) -> ir.Pointwise:
|
| 446 |
+
return create_epilogue_with_attr(
|
| 447 |
+
buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
for gemm_idx, inp in enumerate(inp_list):
|
| 451 |
+
if inp:
|
| 452 |
+
buffer_name = Y_list[gemm_idx].get_name()
|
| 453 |
+
epilogues.append(
|
| 454 |
+
ir.ComputedBuffer(
|
| 455 |
+
name=buffer_name,
|
| 456 |
+
layout=template_buffer.layout,
|
| 457 |
+
data=_bias_add_epilogue(gemm_output_buffers[gemm_idx], inp),
|
| 458 |
+
)
|
| 459 |
+
)
|
| 460 |
+
reindexers.append(None)
|
| 461 |
+
|
| 462 |
+
if epilogue_nodes:
|
| 463 |
+
epilogues.extend(epilogue_nodes)
|
| 464 |
+
for epilogue_node in epilogue_nodes:
|
| 465 |
+
Y = cast(ir.Buffer, epilogue_node)
|
| 466 |
+
_, reindexers = gen_2d_view_of_epilogue_buf(
|
| 467 |
+
Y,
|
| 468 |
+
template_buffer,
|
| 469 |
+
[
|
| 470 |
+
epilogue_node,
|
| 471 |
+
],
|
| 472 |
+
reindexers,
|
| 473 |
+
default_reindexers=[
|
| 474 |
+
None,
|
| 475 |
+
],
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
options = dict(
|
| 479 |
+
N=self.n,
|
| 480 |
+
K=self.k,
|
| 481 |
+
PADDED_N=self.padded_n,
|
| 482 |
+
aliases={},
|
| 483 |
+
beta=self.beta,
|
| 484 |
+
alpha=self.alpha,
|
| 485 |
+
num_threads=self.num_threads,
|
| 486 |
+
micro_gemm=micro_gemm,
|
| 487 |
+
is_dynamic_M=self.is_dynamic_M,
|
| 488 |
+
template=self,
|
| 489 |
+
kernel=kernel,
|
| 490 |
+
export_declaration=get_export_declaration(),
|
| 491 |
+
acc_buf_dtype=torch.float,
|
| 492 |
+
DTYPE_TO_CPP=DTYPE_TO_CPP,
|
| 493 |
+
L1_cache_size=L1_cache_size,
|
| 494 |
+
L2_cache_size=L2_cache_size,
|
| 495 |
+
config=config,
|
| 496 |
+
epilogue_nodes=epilogues,
|
| 497 |
+
GemmOuts=gemm_output_buffers,
|
| 498 |
+
reindexers=reindexers,
|
| 499 |
+
kernel_args=kernel_args,
|
| 500 |
+
X_list=X_list,
|
| 501 |
+
W_list=W_list,
|
| 502 |
+
gemm_grouped_num=self.gemm_grouped_num,
|
| 503 |
+
Y_list={"Y" + str(idx): Y for idx, Y in enumerate(Y_list)},
|
| 504 |
+
Y_2d_list=Y_2d_list,
|
| 505 |
+
multi_output_buffers=multi_output_buffers,
|
| 506 |
+
)
|
| 507 |
+
with contextlib.ExitStack() as stack:
|
| 508 |
+
stack.enter_context(
|
| 509 |
+
patch.object(V.graph, "get_dtype", self._fake_get_dtype(fake_buffers))
|
| 510 |
+
)
|
| 511 |
+
return self._template_from_string(GEMM_TEMPLATE).render(**options)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py
ADDED
|
@@ -0,0 +1,2232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from enum import Enum
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
|
| 11 |
+
from .. import cpp_builder, ir
|
| 12 |
+
from ..cpu_vec_isa import (
|
| 13 |
+
pick_vec_isa,
|
| 14 |
+
VecAMX,
|
| 15 |
+
VecAVX2,
|
| 16 |
+
VecAVX512,
|
| 17 |
+
VecAVX512VNNI,
|
| 18 |
+
VecISA,
|
| 19 |
+
VecNEON,
|
| 20 |
+
VecSVE256,
|
| 21 |
+
)
|
| 22 |
+
from ..utils import IndentedBuffer, parallel_num_threads
|
| 23 |
+
from ..virtualized import V
|
| 24 |
+
from .common import KernelTemplate
|
| 25 |
+
from .cpp_template_kernel import CppTemplateKernel
|
| 26 |
+
from .cpp_utils import DTYPE_TO_CPP, GemmBlocking, value_to_cpp
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class LayoutType(Enum):
|
| 30 |
+
NORMAL = 0
|
| 31 |
+
VNNI2 = 1
|
| 32 |
+
VNNI4 = 2
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
_IS_WINDOWS = sys.platform == "win32"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def get_restrict_keyword() -> str:
|
| 39 |
+
if _IS_WINDOWS:
|
| 40 |
+
# https://learn.microsoft.com/en-us/cpp/cpp/extension-restrict?view=msvc-170
|
| 41 |
+
return "__restrict"
|
| 42 |
+
else:
|
| 43 |
+
return "__restrict__"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class CppMicroGemm:
|
| 47 |
+
"""
|
| 48 |
+
A class that codegens a kernel that computes small-sized matrix multiplication.
|
| 49 |
+
|
| 50 |
+
A micro GEMM kernel is responsible for register blocking, instruction selection,
|
| 51 |
+
and other CPU architecture-specific optimizations.
|
| 52 |
+
|
| 53 |
+
The subclasses need to override `codegen_define` to define the kernel function
|
| 54 |
+
that is called by the code generated by `codegen_call`.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
# TODO(jgong5): support constant shapes and lds as template args.
|
| 58 |
+
DECLARE_KERNEL = r"""
|
| 59 |
+
template <bool accum, bool prefetch=false>
|
| 60 |
+
inline void {{kernel_name}}(
|
| 61 |
+
{%- if kernel_extra_args_declare %}
|
| 62 |
+
{{kernel_extra_args_declare}}
|
| 63 |
+
{%- endif %}
|
| 64 |
+
const {{input_t}}* {{restrict_keyword}} A,
|
| 65 |
+
const {{input2_t}}* {{restrict_keyword}} B,
|
| 66 |
+
{{output_t}}* {{restrict_keyword}} C,
|
| 67 |
+
int64_t M,
|
| 68 |
+
int64_t N,
|
| 69 |
+
int64_t K,
|
| 70 |
+
int64_t lda,
|
| 71 |
+
int64_t ldb,
|
| 72 |
+
int64_t ldc
|
| 73 |
+
)
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
name,
|
| 79 |
+
input_dtype,
|
| 80 |
+
input2_dtype,
|
| 81 |
+
output_dtype,
|
| 82 |
+
compute_dtype,
|
| 83 |
+
register_blocking,
|
| 84 |
+
alpha=1,
|
| 85 |
+
) -> None:
|
| 86 |
+
self.name = name
|
| 87 |
+
self.input_dtype = input_dtype
|
| 88 |
+
assert input2_dtype is not None
|
| 89 |
+
self.input2_dtype = input2_dtype
|
| 90 |
+
self.output_dtype = output_dtype
|
| 91 |
+
self.compute_dtype = compute_dtype
|
| 92 |
+
self.register_blocking = register_blocking
|
| 93 |
+
self.alpha = alpha
|
| 94 |
+
self.pack_vnni_B_locally = False
|
| 95 |
+
|
| 96 |
+
def get_common_options(self):
|
| 97 |
+
if self.input_dtype in [torch.uint8, torch.int8]:
|
| 98 |
+
assert self.compute_dtype == torch.int32
|
| 99 |
+
assert self.output_dtype == torch.int32
|
| 100 |
+
assert self.input2_dtype == torch.int8
|
| 101 |
+
return {
|
| 102 |
+
"torch": torch,
|
| 103 |
+
"kernel_name": self.name,
|
| 104 |
+
"input_dtype": self.input_dtype,
|
| 105 |
+
"input2_dtype": self.input2_dtype,
|
| 106 |
+
"output_dtype": self.output_dtype,
|
| 107 |
+
"compute_dtype": self.compute_dtype,
|
| 108 |
+
"input_t": DTYPE_TO_CPP[self.input_dtype],
|
| 109 |
+
"input2_t": DTYPE_TO_CPP[self.input2_dtype],
|
| 110 |
+
"output_t": DTYPE_TO_CPP[self.output_dtype],
|
| 111 |
+
"compute_t": DTYPE_TO_CPP[self.compute_dtype],
|
| 112 |
+
"alpha": self.alpha,
|
| 113 |
+
"kernel_extra_args_declare": self.get_kernel_extra_args_declare(),
|
| 114 |
+
"int8_gemm": self.input_dtype in [torch.uint8, torch.int8],
|
| 115 |
+
"vnni_size": 4 if self.input_dtype in [torch.uint8, torch.int8] else 2,
|
| 116 |
+
"restrict_keyword": get_restrict_keyword(),
|
| 117 |
+
"pack_vnni_B_locally": self.pack_vnni_B_locally,
|
| 118 |
+
"template": self,
|
| 119 |
+
"is_woq_int4": self.is_woq_int4(),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
def get_kernel_declaration(self):
|
| 123 |
+
options = self.get_common_options()
|
| 124 |
+
return KernelTemplate._template_from_string(self.DECLARE_KERNEL).render(options)
|
| 125 |
+
|
| 126 |
+
def get_kernel_extra_args_declare(self) -> str:
|
| 127 |
+
return ""
|
| 128 |
+
|
| 129 |
+
def get_kernel_extra_args(self, **kwargs) -> list[str]:
|
| 130 |
+
return []
|
| 131 |
+
|
| 132 |
+
def codegen_define(self, kernel: CppTemplateKernel) -> str:
|
| 133 |
+
raise NotImplementedError
|
| 134 |
+
|
| 135 |
+
def codegen_call(
|
| 136 |
+
self,
|
| 137 |
+
kernel: CppTemplateKernel,
|
| 138 |
+
A: ir.Buffer,
|
| 139 |
+
B: ir.Buffer,
|
| 140 |
+
C: ir.Buffer,
|
| 141 |
+
accum: bool,
|
| 142 |
+
prefetch: bool = False,
|
| 143 |
+
**kwargs_for_extra_args,
|
| 144 |
+
) -> str:
|
| 145 |
+
"""
|
| 146 |
+
Generate the code for calling the templated kernel that computes
|
| 147 |
+
`C += alpha * A @ B` if `accum` is True, or `C = alpha * A @ B` otherwise.
|
| 148 |
+
"""
|
| 149 |
+
A_ptr = f"&({kernel.index(A, [0, 0])})"
|
| 150 |
+
B_ptr = f"&({kernel.index(B, [0, 0])})"
|
| 151 |
+
C_ptr = f"&({kernel.index(C, [0, 0])})"
|
| 152 |
+
M = kernel.size(C, 0)
|
| 153 |
+
N = kernel.size(C, 1)
|
| 154 |
+
K = kernel.size(A, 1)
|
| 155 |
+
lda = kernel.stride(A, 0)
|
| 156 |
+
ldb = kernel.stride(B, 0)
|
| 157 |
+
ldc = kernel.stride(C, 0)
|
| 158 |
+
res = IndentedBuffer()
|
| 159 |
+
res.writeline(
|
| 160 |
+
f"{self.name}<{value_to_cpp(accum, 'bool')}, {value_to_cpp(prefetch, 'bool')}>("
|
| 161 |
+
)
|
| 162 |
+
with res.indent():
|
| 163 |
+
kwargs_for_extra_args.update({"kernel": kernel})
|
| 164 |
+
extra_args = self.get_kernel_extra_args(**kwargs_for_extra_args)
|
| 165 |
+
for arg in extra_args:
|
| 166 |
+
res.writeline(arg)
|
| 167 |
+
res.writeline(f"{A_ptr},")
|
| 168 |
+
res.writeline(f"{B_ptr},")
|
| 169 |
+
res.writeline(f"{C_ptr},")
|
| 170 |
+
res.writeline(f"{M},")
|
| 171 |
+
res.writeline(f"{N},")
|
| 172 |
+
res.writeline(f"{K},")
|
| 173 |
+
res.writeline(f"{lda},")
|
| 174 |
+
res.writeline(f"{ldb},")
|
| 175 |
+
res.writeline(f"{ldc}")
|
| 176 |
+
res.writeline(");")
|
| 177 |
+
return res.getvalue()
|
| 178 |
+
|
| 179 |
+
def use_local_vnni_blocking(self, should_block_weight: bool):
|
| 180 |
+
self.pack_vnni_B_locally = should_block_weight
|
| 181 |
+
|
| 182 |
+
def codegen_init(
|
| 183 |
+
self,
|
| 184 |
+
kernel: CppTemplateKernel,
|
| 185 |
+
) -> str:
|
| 186 |
+
return ""
|
| 187 |
+
|
| 188 |
+
def codegen_finalize(
|
| 189 |
+
self,
|
| 190 |
+
kernel: CppTemplateKernel,
|
| 191 |
+
) -> str:
|
| 192 |
+
return ""
|
| 193 |
+
|
| 194 |
+
def get_b_layout(self) -> LayoutType:
|
| 195 |
+
return LayoutType.NORMAL
|
| 196 |
+
|
| 197 |
+
ALLOCATE_WEIGHT_BUFFER = r"""
|
| 198 |
+
{%- if is_msvc_compiler %}
|
| 199 |
+
// MSVC doesn't support stack-allocated dynamic-sized arrays, so using heap memory here.
|
| 200 |
+
auto heap_deq_b_buf_ptr = std::make_unique<{{buffer_dtype}}[]>({{buffer_size}});
|
| 201 |
+
{{buffer_dtype}}* {{buffer_name}} = heap_deq_b_buf_ptr.get();
|
| 202 |
+
{%- else %}
|
| 203 |
+
// It's safe to use a stack-allocated array since the blocking strategy would
|
| 204 |
+
// require us to allocate an array that's smaller than the size of L1D cache,
|
| 205 |
+
// and the default per thread max stack size on Linux is quite higher,
|
| 206 |
+
// so we need not worry about stack overflow.
|
| 207 |
+
alignas(4096) {{buffer_dtype}} {{buffer_name}}[{{buffer_size}}];
|
| 208 |
+
{%- endif %}
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def codegen_allocate_weight_buffer(
|
| 212 |
+
self, buffer_name: str, buffer_dtype: str, *size_args
|
| 213 |
+
) -> str:
|
| 214 |
+
buffer_size = " * ".join(map(str, size_args))
|
| 215 |
+
return KernelTemplate._template_from_string(self.ALLOCATE_WEIGHT_BUFFER).render(
|
| 216 |
+
{
|
| 217 |
+
"buffer_name": buffer_name,
|
| 218 |
+
"buffer_dtype": buffer_dtype,
|
| 219 |
+
"buffer_size": buffer_size,
|
| 220 |
+
"is_msvc_compiler": cpp_builder.is_msvc_cl(),
|
| 221 |
+
}
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
def is_woq_int4(self):
|
| 225 |
+
return False
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@dataclasses.dataclass
|
| 229 |
+
class CppMicroGemmConfig:
|
| 230 |
+
input_dtype: torch.dtype
|
| 231 |
+
input2_dtype: torch.dtype
|
| 232 |
+
output_dtype: torch.dtype
|
| 233 |
+
compute_dtype: torch.dtype
|
| 234 |
+
vec_isa_cls: type[VecISA]
|
| 235 |
+
register_blocking: GemmBlocking
|
| 236 |
+
extra_check: Optional[Callable[..., bool]] = None
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
micro_gemm_configs: dict[type[CppMicroGemm], list[CppMicroGemmConfig]] = {}
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def register_micro_gemm(*configs):
|
| 243 |
+
def inner(cls):
|
| 244 |
+
assert cls not in micro_gemm_configs, (
|
| 245 |
+
f"Duplicate micro_gemm registration for {cls}"
|
| 246 |
+
)
|
| 247 |
+
assert len(configs) > 0, f"No micro_gemm configs provided for {cls}"
|
| 248 |
+
micro_gemm_configs[cls] = list(configs)
|
| 249 |
+
return cls
|
| 250 |
+
|
| 251 |
+
return inner
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def generate_gemm_config(
|
| 255 |
+
vec_isa_cls,
|
| 256 |
+
register_blockings,
|
| 257 |
+
input_dtype=torch.float,
|
| 258 |
+
input2_dtype=None,
|
| 259 |
+
output_dtype=None,
|
| 260 |
+
compute_dtype=None,
|
| 261 |
+
extra_check=None,
|
| 262 |
+
):
|
| 263 |
+
if output_dtype is None:
|
| 264 |
+
output_dtype = input_dtype
|
| 265 |
+
if compute_dtype is None:
|
| 266 |
+
compute_dtype = output_dtype
|
| 267 |
+
if input2_dtype is None:
|
| 268 |
+
input2_dtype = input_dtype
|
| 269 |
+
return [
|
| 270 |
+
CppMicroGemmConfig(
|
| 271 |
+
input_dtype,
|
| 272 |
+
input2_dtype,
|
| 273 |
+
output_dtype,
|
| 274 |
+
compute_dtype,
|
| 275 |
+
vec_isa_cls,
|
| 276 |
+
GemmBlocking(*blocking),
|
| 277 |
+
extra_check,
|
| 278 |
+
)
|
| 279 |
+
for blocking in register_blockings
|
| 280 |
+
]
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class CppMicroGemmRef(CppMicroGemm):
|
| 284 |
+
"""
|
| 285 |
+
A reference implementation of the CppMicroGemm class with naive C++ code.
|
| 286 |
+
It is used for correctness debugging.
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
TEMPLATE_ENTRY = r"""
|
| 290 |
+
{{declare_kernel}} {
|
| 291 |
+
for (int64_t m = 0; m < M; ++m) {
|
| 292 |
+
for (int64_t n = 0; n < N; ++n) {
|
| 293 |
+
{{compute_t}} result = accum ? C[m * ldc + n] : 0;
|
| 294 |
+
for (int64_t k = 0; k < K; ++k) {
|
| 295 |
+
result += ({{compute_t}})A[m * lda + k] * ({{compute_t}})B[k * ldb + n] * {{alpha}};
|
| 296 |
+
}
|
| 297 |
+
C[m * ldc + n] = result;
|
| 298 |
+
}
|
| 299 |
+
}
|
| 300 |
+
}
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
def __init__(
|
| 304 |
+
self, name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha
|
| 305 |
+
) -> None:
|
| 306 |
+
super().__init__(
|
| 307 |
+
name,
|
| 308 |
+
input_dtype,
|
| 309 |
+
input2_dtype,
|
| 310 |
+
output_dtype,
|
| 311 |
+
compute_dtype,
|
| 312 |
+
GemmBlocking(1, 1, 1),
|
| 313 |
+
alpha,
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
def codegen_define(self, kernel: CppTemplateKernel) -> str:
|
| 317 |
+
options = {
|
| 318 |
+
"declare_kernel": self.get_kernel_declaration(),
|
| 319 |
+
**self.get_common_options(),
|
| 320 |
+
}
|
| 321 |
+
return KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k):
|
| 325 |
+
return (
|
| 326 |
+
k % config.register_blocking.block_k == 0
|
| 327 |
+
and n % config.register_blocking.block_n == 0
|
| 328 |
+
and m < 16
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
# extra check for small M dimension for int8 WoQ case
|
| 333 |
+
def check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs):
|
| 334 |
+
return is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k) and not kwargs.get(
|
| 335 |
+
"dynamic_M", False
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
# For int8 WoQ GEMM with small M, we use different blockings that shouldn't be used otherwise
|
| 340 |
+
def do_not_use_with_small_m_for_int8_woq(config, m, n, k, alpha, num_threads, **kwargs):
|
| 341 |
+
return not check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
@register_micro_gemm(
|
| 345 |
+
*generate_gemm_config(
|
| 346 |
+
VecAVX512,
|
| 347 |
+
[(8, 48, 1), (8, 32, 1), (16, 16, 1)],
|
| 348 |
+
input_dtype=torch.float,
|
| 349 |
+
),
|
| 350 |
+
*generate_gemm_config(
|
| 351 |
+
VecAVX512,
|
| 352 |
+
[(8, 48, 1), (8, 32, 1), (16, 16, 1)],
|
| 353 |
+
input_dtype=torch.bfloat16,
|
| 354 |
+
output_dtype=torch.float,
|
| 355 |
+
),
|
| 356 |
+
*generate_gemm_config(
|
| 357 |
+
VecAVX512,
|
| 358 |
+
[(8, 48, 1), (8, 32, 1), (16, 16, 1)],
|
| 359 |
+
input_dtype=torch.half,
|
| 360 |
+
output_dtype=torch.float,
|
| 361 |
+
),
|
| 362 |
+
*generate_gemm_config(
|
| 363 |
+
VecAVX512,
|
| 364 |
+
[(8, 48, 1), (8, 32, 1), (16, 16, 1)],
|
| 365 |
+
input_dtype=torch.bfloat16,
|
| 366 |
+
input2_dtype=torch.int8,
|
| 367 |
+
output_dtype=torch.float,
|
| 368 |
+
compute_dtype=torch.float,
|
| 369 |
+
extra_check=do_not_use_with_small_m_for_int8_woq,
|
| 370 |
+
),
|
| 371 |
+
*generate_gemm_config(
|
| 372 |
+
VecAVX512,
|
| 373 |
+
[
|
| 374 |
+
(4, 32, 64),
|
| 375 |
+
(8, 32, 64),
|
| 376 |
+
],
|
| 377 |
+
input_dtype=torch.bfloat16,
|
| 378 |
+
input2_dtype=torch.int8,
|
| 379 |
+
output_dtype=torch.float,
|
| 380 |
+
compute_dtype=torch.float,
|
| 381 |
+
extra_check=check_int8_woq_small_m_dim,
|
| 382 |
+
),
|
| 383 |
+
*generate_gemm_config(
|
| 384 |
+
VecAVX2,
|
| 385 |
+
[(4, 24, 1), (4, 16, 1), (8, 8, 1)],
|
| 386 |
+
input_dtype=torch.float,
|
| 387 |
+
),
|
| 388 |
+
*generate_gemm_config(
|
| 389 |
+
VecAVX2,
|
| 390 |
+
[(4, 24, 1), (4, 16, 1), (8, 8, 1)],
|
| 391 |
+
input_dtype=torch.bfloat16,
|
| 392 |
+
output_dtype=torch.float,
|
| 393 |
+
),
|
| 394 |
+
*generate_gemm_config(
|
| 395 |
+
VecAVX2,
|
| 396 |
+
[(4, 24, 1), (4, 16, 1), (8, 8, 1)],
|
| 397 |
+
input_dtype=torch.half,
|
| 398 |
+
output_dtype=torch.float,
|
| 399 |
+
),
|
| 400 |
+
*generate_gemm_config(
|
| 401 |
+
VecAVX2,
|
| 402 |
+
[(4, 24, 1), (4, 16, 1), (8, 8, 1)],
|
| 403 |
+
input_dtype=torch.bfloat16,
|
| 404 |
+
input2_dtype=torch.int8,
|
| 405 |
+
output_dtype=torch.float,
|
| 406 |
+
compute_dtype=torch.float,
|
| 407 |
+
extra_check=do_not_use_with_small_m_for_int8_woq,
|
| 408 |
+
),
|
| 409 |
+
*generate_gemm_config(
|
| 410 |
+
VecAVX2,
|
| 411 |
+
[
|
| 412 |
+
(2, 16, 64),
|
| 413 |
+
(4, 16, 64),
|
| 414 |
+
],
|
| 415 |
+
input_dtype=torch.bfloat16,
|
| 416 |
+
input2_dtype=torch.int8,
|
| 417 |
+
output_dtype=torch.float,
|
| 418 |
+
compute_dtype=torch.float,
|
| 419 |
+
extra_check=check_int8_woq_small_m_dim,
|
| 420 |
+
),
|
| 421 |
+
*generate_gemm_config(
|
| 422 |
+
VecNEON,
|
| 423 |
+
[(4, 24, 1), (4, 16, 1), (8, 8, 1)],
|
| 424 |
+
input_dtype=torch.float,
|
| 425 |
+
input2_dtype=torch.float,
|
| 426 |
+
output_dtype=torch.float,
|
| 427 |
+
compute_dtype=torch.float,
|
| 428 |
+
),
|
| 429 |
+
*generate_gemm_config(
|
| 430 |
+
VecSVE256,
|
| 431 |
+
[(4, 24, 1), (4, 16, 1), (8, 8, 1)],
|
| 432 |
+
input_dtype=torch.float,
|
| 433 |
+
input2_dtype=torch.float,
|
| 434 |
+
output_dtype=torch.float,
|
| 435 |
+
compute_dtype=torch.float,
|
| 436 |
+
),
|
| 437 |
+
)
|
| 438 |
+
class CppMicroGemmFP32Vec(CppMicroGemm):
|
| 439 |
+
"""
|
| 440 |
+
This class generates the code for micro gemm using fp32 vec instructions for compute.
|
| 441 |
+
It supports input types of torch.float, torch.bfloat16, and torch.half with fp32 output.
|
| 442 |
+
The output of the microkernel is in FP32, but it would be converted to BF16/FP16 in the template,
|
| 443 |
+
if the desired output is BF16/FP16.
|
| 444 |
+
"""
|
| 445 |
+
|
| 446 |
+
TEMPLATE_ENTRY = r"""
|
| 447 |
+
{{declare_kernel}} {
|
| 448 |
+
using Vectorized = at::vec::Vectorized<{{compute_t}}>;
|
| 449 |
+
constexpr auto VLEN = Vectorized::size();
|
| 450 |
+
{{kernel.assert_function}}({{block_n}} % VLEN == 0, "block_n dimension must be multiple of Vector size");
|
| 451 |
+
{{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}");
|
| 452 |
+
// TODO(jgong5): loop unroll for M and N
|
| 453 |
+
for (int64_t m = 0; m < M; m += {{block_m}}) {
|
| 454 |
+
int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
|
| 455 |
+
for (int64_t n = 0; n < N; n += {{block_n}}) {
|
| 456 |
+
int64_t block_n = std::min<int64_t>(N - n, {{block_n}});
|
| 457 |
+
if (block_m == {{block_m}} && block_n == {{block_n}}) {
|
| 458 |
+
{%- if not trans_b %}
|
| 459 |
+
{{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum, prefetch>(
|
| 460 |
+
{%- else %}
|
| 461 |
+
{{kernel_name}}_transpose_b_kernel<{{block_m}}, {{block_n}}, accum, prefetch>(
|
| 462 |
+
{%- endif %}
|
| 463 |
+
A + m * lda,
|
| 464 |
+
{%- if not trans_b %}
|
| 465 |
+
B + n,
|
| 466 |
+
{%- else %}
|
| 467 |
+
B + n * ldb,
|
| 468 |
+
{%- endif %}
|
| 469 |
+
C + m * ldc + n,
|
| 470 |
+
K,
|
| 471 |
+
lda,
|
| 472 |
+
ldb,
|
| 473 |
+
ldc
|
| 474 |
+
);
|
| 475 |
+
{%- if tail_n %}
|
| 476 |
+
} else if (block_n == {{block_n}}){
|
| 477 |
+
{%- else %}
|
| 478 |
+
} else {
|
| 479 |
+
{%- endif %}
|
| 480 |
+
switch (block_m) {
|
| 481 |
+
{%- for b in range(block_m - 1, 0, -1) %}
|
| 482 |
+
case {{b}}:
|
| 483 |
+
{%- if not trans_b %}
|
| 484 |
+
{{kernel_name}}_kernel<{{b}}, {{block_n}}, accum, prefetch>(
|
| 485 |
+
{%- else %}
|
| 486 |
+
{{kernel_name}}_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>(
|
| 487 |
+
{%- endif %}
|
| 488 |
+
A + m * lda,
|
| 489 |
+
{%- if not trans_b %}
|
| 490 |
+
B + n,
|
| 491 |
+
{%- else %}
|
| 492 |
+
B + n * ldb,
|
| 493 |
+
{%- endif %}
|
| 494 |
+
C + m * ldc + n,
|
| 495 |
+
K,
|
| 496 |
+
lda,
|
| 497 |
+
ldb,
|
| 498 |
+
ldc
|
| 499 |
+
);
|
| 500 |
+
break;
|
| 501 |
+
{%- endfor %}
|
| 502 |
+
default:
|
| 503 |
+
{{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}");
|
| 504 |
+
}
|
| 505 |
+
|
| 506 |
+
{%- if tail_n %}
|
| 507 |
+
} else {
|
| 508 |
+
switch (block_m) {
|
| 509 |
+
{%- for b in range(block_m, 0, -1) %}
|
| 510 |
+
case {{b}}:
|
| 511 |
+
{%- if not trans_b %}
|
| 512 |
+
{{kernel_name}}_ntail_kernel<{{b}}, {{block_n}}, accum, prefetch>(
|
| 513 |
+
{%- else %}
|
| 514 |
+
{{kernel_name}}_ntail_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>(
|
| 515 |
+
{%- endif %}
|
| 516 |
+
A + m * lda,
|
| 517 |
+
{%- if not trans_b %}
|
| 518 |
+
B + n,
|
| 519 |
+
{%- else %}
|
| 520 |
+
B + n * ldb,
|
| 521 |
+
{%- endif %}
|
| 522 |
+
C + m * ldc + n,
|
| 523 |
+
block_n,
|
| 524 |
+
K,
|
| 525 |
+
lda,
|
| 526 |
+
ldb,
|
| 527 |
+
ldc
|
| 528 |
+
);
|
| 529 |
+
break;
|
| 530 |
+
{%- endfor %}
|
| 531 |
+
default:
|
| 532 |
+
{{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}");
|
| 533 |
+
}
|
| 534 |
+
}
|
| 535 |
+
{%- else %}
|
| 536 |
+
}
|
| 537 |
+
{%- endif %}
|
| 538 |
+
}
|
| 539 |
+
}
|
| 540 |
+
}
|
| 541 |
+
"""
|
| 542 |
+
|
| 543 |
+
TEMPLATE_KERNEL = r"""
|
| 544 |
+
|
| 545 |
+
template <int64_t BLOCK_M, int64_t BLOCK_N, bool accum, bool prefetch=false>
|
| 546 |
+
{%- if not trans_b %}
|
| 547 |
+
{%- if tail_n %}
|
| 548 |
+
inline void {{kernel_name}}_ntail_kernel(
|
| 549 |
+
{%- else %}
|
| 550 |
+
inline void {{kernel_name}}_kernel(
|
| 551 |
+
{%- endif %}
|
| 552 |
+
{%- else %}
|
| 553 |
+
{%- if tail_n %}
|
| 554 |
+
inline void {{kernel_name}}_ntail_transpose_b_kernel(
|
| 555 |
+
{%- else %}
|
| 556 |
+
inline void {{kernel_name}}_transpose_b_kernel(
|
| 557 |
+
{%- endif %}
|
| 558 |
+
{%- endif %}
|
| 559 |
+
const {{input_t}}* {{restrict_keyword}} A,
|
| 560 |
+
const {{input2_t}}* {{restrict_keyword}} B,
|
| 561 |
+
{{output_t}}* {{restrict_keyword}} C,
|
| 562 |
+
{%- if tail_n %}
|
| 563 |
+
int64_t N,
|
| 564 |
+
{%- endif %}
|
| 565 |
+
int64_t K,
|
| 566 |
+
int64_t lda,
|
| 567 |
+
int64_t ldb,
|
| 568 |
+
int64_t ldc
|
| 569 |
+
) {
|
| 570 |
+
using Vectorized = at::vec::Vectorized<{{compute_t}}>;
|
| 571 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 572 |
+
using VectorizedIn = at::vec::Vectorized<{{input_t}}>;
|
| 573 |
+
{%- endif %}
|
| 574 |
+
|
| 575 |
+
{%- if not trans_b %}
|
| 576 |
+
constexpr auto VLEN = Vectorized::size();
|
| 577 |
+
constexpr auto ROWS = BLOCK_M;
|
| 578 |
+
constexpr auto COLS = BLOCK_N / VLEN;
|
| 579 |
+
|
| 580 |
+
Vectorized va;
|
| 581 |
+
at::vec::VectorizedN<{{compute_t}}, COLS> vb;
|
| 582 |
+
at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc;
|
| 583 |
+
|
| 584 |
+
{%- if tail_n %}
|
| 585 |
+
int64_t rCOLS = (N + VLEN - 1) / VLEN;
|
| 586 |
+
int ntail = N % VLEN;
|
| 587 |
+
{%- endif %}
|
| 588 |
+
auto loadc = [&](auto i) {
|
| 589 |
+
if constexpr (accum) {
|
| 590 |
+
constexpr int row = i / COLS;
|
| 591 |
+
constexpr int col = i % COLS;
|
| 592 |
+
{%- if tail_n %}
|
| 593 |
+
int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN;
|
| 594 |
+
if (col < rCOLS) {
|
| 595 |
+
vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN, load_size);
|
| 596 |
+
}
|
| 597 |
+
{%- else %}
|
| 598 |
+
vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN);
|
| 599 |
+
{%- endif %}
|
| 600 |
+
} else {
|
| 601 |
+
vc[i] = Vectorized(0.0f);
|
| 602 |
+
}
|
| 603 |
+
};
|
| 604 |
+
c10::ForcedUnroll<ROWS * COLS>{}(loadc);
|
| 605 |
+
|
| 606 |
+
auto compute = [&, COLS](auto i, int k) {
|
| 607 |
+
constexpr int row = i / COLS;
|
| 608 |
+
constexpr int col = i % COLS;
|
| 609 |
+
{%- if tail_n %}
|
| 610 |
+
int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN;
|
| 611 |
+
{%- endif %}
|
| 612 |
+
if constexpr (col == 0) {
|
| 613 |
+
{%- if alpha != 1 %}
|
| 614 |
+
va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k]) * {{alpha}});
|
| 615 |
+
{%- else %}
|
| 616 |
+
va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k]));
|
| 617 |
+
{%- endif %}
|
| 618 |
+
}
|
| 619 |
+
|
| 620 |
+
if constexpr (row == 0) {
|
| 621 |
+
{%- if tail_n %}
|
| 622 |
+
if (col < rCOLS) {
|
| 623 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 624 |
+
auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, load_size);
|
| 625 |
+
vb[col] = at::vec::convert<{{compute_t}}>(b);
|
| 626 |
+
{%- elif input2_dtype == torch.int8 %}
|
| 627 |
+
// Convert VLEN int8 elements to int32, and then fp32
|
| 628 |
+
auto b32 = at::vec::convert_to_int32<int8_t>(B + k * ldb + col * VLEN, load_size);
|
| 629 |
+
vb[col] = at::vec::convert<float>(b32);
|
| 630 |
+
{%- else %}
|
| 631 |
+
vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN, load_size);
|
| 632 |
+
{%- endif %}
|
| 633 |
+
} else {
|
| 634 |
+
vb[col] = Vectorized(0.0f);
|
| 635 |
+
}
|
| 636 |
+
|
| 637 |
+
{%- else %}
|
| 638 |
+
|
| 639 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 640 |
+
auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, VLEN);
|
| 641 |
+
vb[col] = at::vec::convert<{{compute_t}}>(b);
|
| 642 |
+
{%- elif input2_dtype == torch.int8 %}
|
| 643 |
+
// Convert VLEN int8 elements to int32, and then fp32
|
| 644 |
+
auto b32 = at::vec::convert_to_int32<int8_t>(B + k * ldb + col * VLEN);
|
| 645 |
+
if constexpr (prefetch) {
|
| 646 |
+
_mm_prefetch(B + (k + {{block_k}}) * ldb + col * VLEN, _MM_HINT_T0);
|
| 647 |
+
}
|
| 648 |
+
vb[col] = at::vec::convert<float>(b32);
|
| 649 |
+
{%- else %}
|
| 650 |
+
vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN);
|
| 651 |
+
{%- endif %}
|
| 652 |
+
{%- endif %}
|
| 653 |
+
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
constexpr int idx = row * COLS + col;
|
| 657 |
+
{%- if tail_n %}
|
| 658 |
+
if (col < rCOLS) {
|
| 659 |
+
vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]);
|
| 660 |
+
}
|
| 661 |
+
{%- else %}
|
| 662 |
+
vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]);
|
| 663 |
+
{%- endif %}
|
| 664 |
+
};
|
| 665 |
+
|
| 666 |
+
for (int k = 0; k < K; ++k) {
|
| 667 |
+
c10::ForcedUnroll<ROWS * COLS>{}(compute, k);
|
| 668 |
+
}
|
| 669 |
+
|
| 670 |
+
// store to C
|
| 671 |
+
auto storec = [&](auto i) {
|
| 672 |
+
constexpr int row = i / COLS;
|
| 673 |
+
constexpr int col = i % COLS;
|
| 674 |
+
{%- if tail_n %}
|
| 675 |
+
int store_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN;
|
| 676 |
+
if (col < rCOLS) {
|
| 677 |
+
vc[i].store(C + row * ldc + col * VLEN, store_size);
|
| 678 |
+
}
|
| 679 |
+
{%- else %}
|
| 680 |
+
vc[i].store(C + row * ldc + col * VLEN);
|
| 681 |
+
{%- endif %}
|
| 682 |
+
};
|
| 683 |
+
c10::ForcedUnroll<ROWS * COLS>{}(storec);
|
| 684 |
+
|
| 685 |
+
{%- else %}
|
| 686 |
+
// Use 2 implementations for the transposed B:
|
| 687 |
+
// First implementation:
|
| 688 |
+
// Transpose first and then perform outer product calculation in sub-blocks,
|
| 689 |
+
// which introduces an additional transpose overhead of [K, N] compared to the non-transpose version.
|
| 690 |
+
// Second implementation:
|
| 691 |
+
// Directly perform inner product calculation in sub-blocks,
|
| 692 |
+
// which introduces an additional vector reduction of [M, N] compared to the non-tranpose version.
|
| 693 |
+
// Therefore, when M * N / (K * N) is large, the first implementation has better performance.
|
| 694 |
+
{%- if tail_n %}
|
| 695 |
+
if (K % Vectorized::size() == 0 && N % Vectorized::size() == 0 && 24 * BLOCK_M > K) {
|
| 696 |
+
{%- else %}
|
| 697 |
+
if (K % Vectorized::size() == 0 && 24 * BLOCK_M > K) {
|
| 698 |
+
{%- endif %}
|
| 699 |
+
// First implementation:
|
| 700 |
+
constexpr auto VLEN = Vectorized::size();
|
| 701 |
+
constexpr auto ROWS = BLOCK_M;
|
| 702 |
+
constexpr auto COLS = BLOCK_N / VLEN;
|
| 703 |
+
int _K = K / VLEN;
|
| 704 |
+
Vectorized va;
|
| 705 |
+
at::vec::VectorizedN<{{compute_t}}, VLEN> vb;
|
| 706 |
+
at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc;
|
| 707 |
+
auto loadc = [&](auto i) {
|
| 708 |
+
if constexpr (accum) {
|
| 709 |
+
constexpr int row = i / COLS;
|
| 710 |
+
constexpr int col = i % COLS;
|
| 711 |
+
vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN);
|
| 712 |
+
} else {
|
| 713 |
+
vc[i] = Vectorized(0.0f);
|
| 714 |
+
}
|
| 715 |
+
};
|
| 716 |
+
c10::ForcedUnroll<ROWS * COLS>{}(loadc);
|
| 717 |
+
auto unroll_loadB = [&](auto i, const {{input2_t}}* {{restrict_keyword}} src_ptr) {
|
| 718 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 719 |
+
auto b = VectorizedIn::loadu(src_ptr + i * ldb, VLEN);
|
| 720 |
+
vb[i] = at::vec::convert<{{compute_t}}>(b);
|
| 721 |
+
{%- elif input2_dtype == torch.int8 %}
|
| 722 |
+
auto b32 = at::vec::convert_to_int32<int8_t>(src_ptr + i * ldb, VLEN);
|
| 723 |
+
vb[i] = at::vec::convert<float>(b32);
|
| 724 |
+
{%- else %}
|
| 725 |
+
vb[i] = Vectorized::loadu(src_ptr + i * ldb, VLEN);
|
| 726 |
+
{%- endif %}
|
| 727 |
+
};
|
| 728 |
+
auto compute_trans = [&, COLS](auto i, int k) {
|
| 729 |
+
constexpr int row = i % ROWS;
|
| 730 |
+
constexpr int col = i / ROWS;
|
| 731 |
+
constexpr int e_col = col * VLEN;
|
| 732 |
+
int idk = k * VLEN;
|
| 733 |
+
if constexpr (row == 0) {
|
| 734 |
+
c10::ForcedUnroll<VLEN>{}(unroll_loadB, B + e_col * ldb + idk);
|
| 735 |
+
at::vec::transpose_block(vb);
|
| 736 |
+
}
|
| 737 |
+
constexpr int idx = row * COLS + col;
|
| 738 |
+
{{kernel.unroll_pragma(16)}}
|
| 739 |
+
for (int j = 0; j < VLEN; j++) {
|
| 740 |
+
{%- if alpha != 1 %}
|
| 741 |
+
va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j]) * {{alpha}});
|
| 742 |
+
{%- else %}
|
| 743 |
+
va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j]));
|
| 744 |
+
{%- endif %}
|
| 745 |
+
vc[idx] = at::vec::fmadd(va, vb[j], vc[idx]);
|
| 746 |
+
}
|
| 747 |
+
};
|
| 748 |
+
for (int k = 0; k < _K; ++k) {
|
| 749 |
+
c10::ForcedUnroll<ROWS * COLS>{}(compute_trans, k);
|
| 750 |
+
}
|
| 751 |
+
// store to C
|
| 752 |
+
auto storec = [&](auto i) {
|
| 753 |
+
constexpr int row = i / COLS;
|
| 754 |
+
constexpr int col = i % COLS;
|
| 755 |
+
vc[i].store(C + row * ldc + col * VLEN);
|
| 756 |
+
};
|
| 757 |
+
c10::ForcedUnroll<ROWS * COLS>{}(storec);
|
| 758 |
+
} else {
|
| 759 |
+
// Second implementation
|
| 760 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 761 |
+
constexpr auto VLEN = VectorizedIn::size();
|
| 762 |
+
{%- else %}
|
| 763 |
+
constexpr auto VLEN = Vectorized::size();
|
| 764 |
+
{%- endif %}
|
| 765 |
+
int _K = (K + VLEN - 1) / VLEN;
|
| 766 |
+
// sub-block size of BLOCK_N and BLOCK_M
|
| 767 |
+
constexpr int sM = {{sub_block_m}};
|
| 768 |
+
constexpr int sN = {{sub_block_n}};
|
| 769 |
+
{%- if tail_n %}
|
| 770 |
+
int bN = (N + sN - 1) / sN;
|
| 771 |
+
{%- else %}
|
| 772 |
+
constexpr int bN = (BLOCK_N + sN - 1) / sN;
|
| 773 |
+
{%- endif %}
|
| 774 |
+
constexpr int bM = (BLOCK_M + sM - 1) / sM;
|
| 775 |
+
|
| 776 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 777 |
+
at::vec::VectorizedN<{{compute_t}}, 2> va;
|
| 778 |
+
at::vec::VectorizedN<{{compute_t}}, 2 * sN> vb;
|
| 779 |
+
{%- else %}
|
| 780 |
+
at::vec::Vectorized<{{compute_t}}> va;
|
| 781 |
+
at::vec::VectorizedN<{{compute_t}}, sN> vb;
|
| 782 |
+
{%- endif %}
|
| 783 |
+
at::vec::VectorizedN<{{compute_t}}, sN * sM> vmid;
|
| 784 |
+
|
| 785 |
+
{%- if tail_n %}
|
| 786 |
+
int ntail = N % sN;
|
| 787 |
+
{%- else %}
|
| 788 |
+
constexpr int ntail = BLOCK_N % sN;
|
| 789 |
+
{%- endif %}
|
| 790 |
+
constexpr int mtail = BLOCK_M % sM;
|
| 791 |
+
int ktail = K % VLEN;
|
| 792 |
+
|
| 793 |
+
auto compute_trans = [&](int m, int n, int k) {
|
| 794 |
+
{%- if tail_n %}
|
| 795 |
+
int e_n = (n == bN - 1 && ntail != 0) ? (N - n * sN) : sN;
|
| 796 |
+
{%- else %}
|
| 797 |
+
int e_n = (n == bN - 1 && ntail != 0) ? (BLOCK_N - n * sN) : sN;
|
| 798 |
+
{%- endif %}
|
| 799 |
+
int e_m = (m == bM - 1 && mtail != 0) ? (BLOCK_M - m * sM) : sM;
|
| 800 |
+
int e_k = (k == _K - 1 && ktail != 0) ? (K - k * VLEN) : VLEN;
|
| 801 |
+
{{kernel.unroll_pragma(sub_block_n)}}
|
| 802 |
+
for (int i = 0; i < e_n; i++) {
|
| 803 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 804 |
+
auto b = VectorizedIn::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k);
|
| 805 |
+
std::tie(vb[2 * i], vb[2 * i + 1]) = at::vec::convert_to_float<{{input_t}}>(b);
|
| 806 |
+
{%- elif input2_dtype == torch.int8 %}
|
| 807 |
+
auto b32 = at::vec::convert_to_int32<int8_t>(B + (sN * n + i) * ldb + k * VLEN, e_k);
|
| 808 |
+
vb[i] = at::vec::convert<float>(b32);
|
| 809 |
+
{%- else %}
|
| 810 |
+
vb[i] = Vectorized::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k);
|
| 811 |
+
{%- endif %}
|
| 812 |
+
}
|
| 813 |
+
|
| 814 |
+
{{kernel.unroll_pragma(sub_block_m)}}
|
| 815 |
+
for (int s = 0; s < e_m; s++) {
|
| 816 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 817 |
+
auto a = VectorizedIn::loadu(A + (sM * m + s) * lda + k * VLEN, e_k);
|
| 818 |
+
std::tie(va[0], va[1]) = at::vec::convert_to_float<{{input_t}}>(a);
|
| 819 |
+
{%- elif input2_dtype == torch.int8 %}
|
| 820 |
+
auto a32 = at::vec::convert_to_int32<int8_t>(A + (sM * m + s) * lda + k * VLEN, e_k);
|
| 821 |
+
va = at::vec::convert<float>(a32);
|
| 822 |
+
{%- else %}
|
| 823 |
+
va = Vectorized::loadu(A + (sM * m + s) * lda + k * VLEN, e_k);
|
| 824 |
+
{%- endif %}
|
| 825 |
+
|
| 826 |
+
{%- if alpha != 1 %}
|
| 827 |
+
va = va * Vectorized({{alpha}});
|
| 828 |
+
{%- endif %}
|
| 829 |
+
if (k == 0) {
|
| 830 |
+
{{kernel.unroll_pragma(sub_block_n)}}
|
| 831 |
+
for (int i = 0; i < e_n; i++) {
|
| 832 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 833 |
+
vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], Vectorized(0.0f));
|
| 834 |
+
vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]);
|
| 835 |
+
{%- else %}
|
| 836 |
+
vmid[sN * s + i] = at::vec::fmadd(va, vb[i], Vectorized(0.0f));
|
| 837 |
+
{%- endif %}
|
| 838 |
+
}
|
| 839 |
+
} else {
|
| 840 |
+
{{kernel.unroll_pragma(sub_block_n)}}
|
| 841 |
+
for (int i = 0; i < e_n; i++) {
|
| 842 |
+
{%- if input2_dtype in [torch.bfloat16, torch.float16] %}
|
| 843 |
+
vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], vmid[sN * s + i]);
|
| 844 |
+
vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]);
|
| 845 |
+
{%- else %}
|
| 846 |
+
vmid[sN * s + i] = at::vec::fmadd(va, vb[i], vmid[sN * s + i]);
|
| 847 |
+
{%- endif %}
|
| 848 |
+
}
|
| 849 |
+
}
|
| 850 |
+
}
|
| 851 |
+
|
| 852 |
+
// store to C
|
| 853 |
+
if (k == _K - 1) {
|
| 854 |
+
{{kernel.unroll_pragma(sub_block_m)}}
|
| 855 |
+
for (int s = 0; s < e_m; s++) {
|
| 856 |
+
{{kernel.unroll_pragma(sub_block_n)}}
|
| 857 |
+
for (int i = 0; i < e_n; i++) {
|
| 858 |
+
auto v = at::vec::vec_reduce_all([](Vectorized& x, Vectorized& y) { return x + y; }, vmid[sN * s + i]);
|
| 859 |
+
if constexpr (accum) {
|
| 860 |
+
auto c = *(C + (sM * m + s) * ldc + sN * n + i);
|
| 861 |
+
*(C + (sM * m + s) * ldc + sN * n + i) = c + v;
|
| 862 |
+
} else {
|
| 863 |
+
*(C + (sM * m + s) * ldc + sN * n + i) = v;
|
| 864 |
+
}
|
| 865 |
+
}
|
| 866 |
+
}
|
| 867 |
+
}
|
| 868 |
+
};
|
| 869 |
+
|
| 870 |
+
for (int n = 0; n < bN; ++n) {
|
| 871 |
+
for (int m = 0; m < bM; ++m) {
|
| 872 |
+
for (int k = 0; k < _K; ++k) {
|
| 873 |
+
compute_trans(m, n, k);
|
| 874 |
+
}
|
| 875 |
+
}
|
| 876 |
+
}
|
| 877 |
+
}
|
| 878 |
+
{%- endif %}
|
| 879 |
+
}
|
| 880 |
+
"""
|
| 881 |
+
|
| 882 |
+
# set trans_b to generate gemm that supports transposed B matrix
|
| 883 |
+
# set tail_n to support the tail of N
|
| 884 |
+
# TODO add trans_b support for other micro gemms
|
| 885 |
+
# and move setting of trans_b to the init of CppMicroGemm
|
| 886 |
+
def __init__(
|
| 887 |
+
self,
|
| 888 |
+
name,
|
| 889 |
+
input_dtype,
|
| 890 |
+
input2_dtype,
|
| 891 |
+
output_dtype,
|
| 892 |
+
compute_dtype,
|
| 893 |
+
register_blocking,
|
| 894 |
+
alpha=1,
|
| 895 |
+
tail_n=False,
|
| 896 |
+
trans_b=False,
|
| 897 |
+
) -> None:
|
| 898 |
+
super().__init__(
|
| 899 |
+
name,
|
| 900 |
+
input_dtype,
|
| 901 |
+
input2_dtype,
|
| 902 |
+
output_dtype,
|
| 903 |
+
compute_dtype,
|
| 904 |
+
register_blocking,
|
| 905 |
+
alpha,
|
| 906 |
+
)
|
| 907 |
+
self.tail_n = tail_n
|
| 908 |
+
# trans_b is only supported on platforms that
|
| 909 |
+
# support avx512 or avx2 since transpose_block is
|
| 910 |
+
# only implemented on these platforms
|
| 911 |
+
if trans_b:
|
| 912 |
+
vec_isa = pick_vec_isa()
|
| 913 |
+
assert issubclass(vec_isa.__class__, VecAVX512) or issubclass(
|
| 914 |
+
vec_isa.__class__, VecAVX2
|
| 915 |
+
)
|
| 916 |
+
self.trans_b = trans_b
|
| 917 |
+
|
| 918 |
+
def codegen_define(self, kernel: CppTemplateKernel) -> str:
|
| 919 |
+
options = {
|
| 920 |
+
"declare_kernel": self.get_kernel_declaration(),
|
| 921 |
+
"kernel": kernel,
|
| 922 |
+
"block_m": self.register_blocking.block_m,
|
| 923 |
+
"block_n": self.register_blocking.block_n,
|
| 924 |
+
"block_k": self.register_blocking.block_k,
|
| 925 |
+
"trans_b": False,
|
| 926 |
+
"tail_n": False,
|
| 927 |
+
"restrict_keyword": get_restrict_keyword(),
|
| 928 |
+
**self.get_common_options(),
|
| 929 |
+
}
|
| 930 |
+
if self.trans_b:
|
| 931 |
+
# TODO supports tuning of sub_block_m/sub_block_n
|
| 932 |
+
# to get better performance for specific shapes
|
| 933 |
+
sub_block_m = min(1, self.register_blocking.block_m)
|
| 934 |
+
sub_block_n = min(4, self.register_blocking.block_n)
|
| 935 |
+
# update options to generate kernel with trans_b and sub-block size
|
| 936 |
+
options.update(
|
| 937 |
+
{
|
| 938 |
+
"trans_b": self.trans_b,
|
| 939 |
+
"sub_block_m": sub_block_m,
|
| 940 |
+
"sub_block_n": sub_block_n,
|
| 941 |
+
}
|
| 942 |
+
)
|
| 943 |
+
result = KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
|
| 944 |
+
options
|
| 945 |
+
)
|
| 946 |
+
# update options to generate the kernel for the tail of N
|
| 947 |
+
if self.tail_n:
|
| 948 |
+
options.update(
|
| 949 |
+
{
|
| 950 |
+
"tail_n": self.tail_n,
|
| 951 |
+
}
|
| 952 |
+
)
|
| 953 |
+
result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
|
| 954 |
+
options
|
| 955 |
+
)
|
| 956 |
+
result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(
|
| 957 |
+
options
|
| 958 |
+
)
|
| 959 |
+
return result
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
def check_vnni_extra(config, m, n, k, alpha, num_threads, **kwargs):
|
| 963 |
+
assert config.input_dtype == torch.uint8 and config.input2_dtype == torch.int8
|
| 964 |
+
vnni_size = 4
|
| 965 |
+
return k % vnni_size == 0
|
| 966 |
+
|
| 967 |
+
|
| 968 |
+
@register_micro_gemm(
|
| 969 |
+
*generate_gemm_config(
|
| 970 |
+
VecAVX512VNNI,
|
| 971 |
+
# (block_m, block_n, block_k)
|
| 972 |
+
[(6, 64, 4)],
|
| 973 |
+
input_dtype=torch.uint8,
|
| 974 |
+
input2_dtype=torch.int8,
|
| 975 |
+
output_dtype=torch.int32,
|
| 976 |
+
compute_dtype=torch.int32,
|
| 977 |
+
extra_check=check_vnni_extra,
|
| 978 |
+
),
|
| 979 |
+
)
|
| 980 |
+
class CppMicroGemmAVX512VNNI(CppMicroGemm):
|
| 981 |
+
"""
|
| 982 |
+
This class generates the code for micro gemm using AVX512 VNNI instructions for compute.
|
| 983 |
+
It supports u8s8s32 GEMM only.
|
| 984 |
+
AVX512_VNNI ISA has been available since the 3rd gen of Intel Xeon.
|
| 985 |
+
"""
|
| 986 |
+
|
| 987 |
+
TEMPLATE_ENTRY = r"""
|
| 988 |
+
{{declare_kernel}} {
|
| 989 |
+
{{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
|
| 990 |
+
{{kernel.assert_function}}(K % {{vnni_size}} == 0, "K dimension must be multiple of {{vnni_size}}");
|
| 991 |
+
constexpr int64_t M_BLOCK = {{block_m}};
|
| 992 |
+
const int64_t M_TAIL = M % M_BLOCK;
|
| 993 |
+
const int64_t M_MAIN = M - M_TAIL;
|
| 994 |
+
for (int64_t m = 0; m < M_MAIN; m += M_BLOCK) {
|
| 995 |
+
for (int64_t n = 0; n < N; n += {{block_n}}) {
|
| 996 |
+
{{kernel_name}}_kernel<M_BLOCK, {{block_n}}, accum>(
|
| 997 |
+
A + m * lda,
|
| 998 |
+
B + n,
|
| 999 |
+
C + m * ldc + n,
|
| 1000 |
+
K,
|
| 1001 |
+
lda,
|
| 1002 |
+
ldb,
|
| 1003 |
+
ldc
|
| 1004 |
+
);
|
| 1005 |
+
}
|
| 1006 |
+
}
|
| 1007 |
+
if (M_TAIL > 0) {
|
| 1008 |
+
switch (M_TAIL) {
|
| 1009 |
+
{%- for m_tail in range(block_m - 1, 0, -1) %}
|
| 1010 |
+
case ({{m_tail}}):
|
| 1011 |
+
for (int64_t n = 0; n < N; n += {{block_n}}) {
|
| 1012 |
+
{{kernel_name}}_kernel<{{m_tail}}, {{block_n}}, accum>(
|
| 1013 |
+
A + M_MAIN * lda,
|
| 1014 |
+
B + n,
|
| 1015 |
+
C + M_MAIN * ldc + n,
|
| 1016 |
+
K,
|
| 1017 |
+
lda,
|
| 1018 |
+
ldb,
|
| 1019 |
+
ldc
|
| 1020 |
+
);
|
| 1021 |
+
}
|
| 1022 |
+
break;
|
| 1023 |
+
{%- endfor %}
|
| 1024 |
+
default:
|
| 1025 |
+
{{kernel.assert_function}}(false, "Unsupported M_TAIL: {}", M_TAIL);
|
| 1026 |
+
} // switch M_TAIL
|
| 1027 |
+
} // if M_TAIL
|
| 1028 |
+
}
|
| 1029 |
+
"""
|
| 1030 |
+
|
| 1031 |
+
TEMPLATE_KERNEL = r"""
|
| 1032 |
+
template <int64_t M, int64_t N, bool accum>
|
| 1033 |
+
inline void {{kernel_name}}_kernel(
|
| 1034 |
+
const {{input_t}}* {{restrict_keyword}} A,
|
| 1035 |
+
const {{input2_t}}* {{restrict_keyword}} B,
|
| 1036 |
+
{{output_t}}* {{restrict_keyword}} C,
|
| 1037 |
+
int64_t K,
|
| 1038 |
+
int64_t lda,
|
| 1039 |
+
int64_t ldb,
|
| 1040 |
+
int64_t ldc
|
| 1041 |
+
) {
|
| 1042 |
+
constexpr const int COLS = N / {{vec_len}};
|
| 1043 |
+
__m512i va;
|
| 1044 |
+
__m512i vb[COLS];
|
| 1045 |
+
__m512i vc[M * COLS];
|
| 1046 |
+
|
| 1047 |
+
c10::ForcedUnroll<M * COLS>{}([&](auto i) { vc[i] = _mm512_setzero_epi32(); });
|
| 1048 |
+
|
| 1049 |
+
auto compute = [&](auto i, int k) {
|
| 1050 |
+
constexpr const int row = i / COLS;
|
| 1051 |
+
constexpr const int col = i % COLS;
|
| 1052 |
+
|
| 1053 |
+
if constexpr (col == 0) {
|
| 1054 |
+
va = _mm512_set1_epi32(*(int32_t*)(A + row * lda + k));
|
| 1055 |
+
}
|
| 1056 |
+
|
| 1057 |
+
if constexpr (row == 0) {
|
| 1058 |
+
// B block in VNNI layout: [K / {{vnni_size}}, N, {{vnni_size}}]
|
| 1059 |
+
int64_t offset = k * ldb + col * {{vec_len}} * {{vnni_size}};
|
| 1060 |
+
vb[col] = _mm512_loadu_si512((__m512i const*)(B + offset));
|
| 1061 |
+
}
|
| 1062 |
+
vc[i] = _mm512_dpbusd_epi32(vc[i], va, vb[col]);
|
| 1063 |
+
};
|
| 1064 |
+
|
| 1065 |
+
// Accumulate along k
|
| 1066 |
+
constexpr const int k_unroll = 2;
|
| 1067 |
+
int k = 0;
|
| 1068 |
+
int k_limit = K / {{vnni_size}} / k_unroll;
|
| 1069 |
+
for (; k < k_limit; k++) {
|
| 1070 |
+
c10::ForcedUnroll<k_unroll>{}(
|
| 1071 |
+
[&](auto i) {
|
| 1072 |
+
c10::ForcedUnroll<M * COLS>{}(compute, {{vnni_size}} * (k * k_unroll + i));
|
| 1073 |
+
}
|
| 1074 |
+
);
|
| 1075 |
+
}
|
| 1076 |
+
k *= {{vnni_size}} * k_unroll;
|
| 1077 |
+
for (; k < K; k += {{vnni_size}}) {
|
| 1078 |
+
c10::ForcedUnroll<M * COLS>{}(compute, k);
|
| 1079 |
+
}
|
| 1080 |
+
|
| 1081 |
+
// Store to C
|
| 1082 |
+
auto store_c = [&](auto i) {
|
| 1083 |
+
constexpr const int row = i / COLS;
|
| 1084 |
+
constexpr const int col = i % COLS;
|
| 1085 |
+
if constexpr (accum) {
|
| 1086 |
+
__m512i vc_old = _mm512_loadu_si512((__m512i const*)(C + row * ldc + col * {{vec_len}}));
|
| 1087 |
+
vc[i] = _mm512_add_epi32(vc[i], vc_old);
|
| 1088 |
+
}
|
| 1089 |
+
_mm512_storeu_si512((__m512i*)(C + row * ldc + col * {{vec_len}}), vc[i]);
|
| 1090 |
+
};
|
| 1091 |
+
c10::ForcedUnroll<M * COLS>{}(store_c);
|
| 1092 |
+
}
|
| 1093 |
+
"""
|
| 1094 |
+
|
| 1095 |
+
def __init__(
|
| 1096 |
+
self,
|
| 1097 |
+
name,
|
| 1098 |
+
input_dtype,
|
| 1099 |
+
input2_dtype,
|
| 1100 |
+
output_dtype,
|
| 1101 |
+
compute_dtype,
|
| 1102 |
+
register_blocking,
|
| 1103 |
+
alpha=1,
|
| 1104 |
+
) -> None:
|
| 1105 |
+
super().__init__(
|
| 1106 |
+
name,
|
| 1107 |
+
input_dtype,
|
| 1108 |
+
input2_dtype,
|
| 1109 |
+
output_dtype,
|
| 1110 |
+
compute_dtype,
|
| 1111 |
+
register_blocking,
|
| 1112 |
+
alpha,
|
| 1113 |
+
)
|
| 1114 |
+
assert input_dtype == torch.uint8 and input2_dtype == torch.int8, (
|
| 1115 |
+
f"Only u8s8s32 GEMM is supported by AVX512VNNI microkernel, got A:{input_dtype}, B:{input2_dtype}, C:{output_dtype}."
|
| 1116 |
+
)
|
| 1117 |
+
|
| 1118 |
+
def codegen_define(self, kernel: CppTemplateKernel) -> str:
|
| 1119 |
+
options = {
|
| 1120 |
+
"declare_kernel": self.get_kernel_declaration(),
|
| 1121 |
+
"kernel": kernel,
|
| 1122 |
+
"block_m": self.register_blocking.block_m,
|
| 1123 |
+
"block_n": self.register_blocking.block_n,
|
| 1124 |
+
"block_k": self.register_blocking.block_k,
|
| 1125 |
+
"restrict_keyword": get_restrict_keyword(),
|
| 1126 |
+
"vec_len": 16, # = 512 / 32 for C
|
| 1127 |
+
**self.get_common_options(),
|
| 1128 |
+
}
|
| 1129 |
+
return KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
|
| 1130 |
+
options
|
| 1131 |
+
) + KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options)
|
| 1132 |
+
|
| 1133 |
+
def get_b_layout(self):
|
| 1134 |
+
return LayoutType.VNNI4
|
| 1135 |
+
|
| 1136 |
+
|
| 1137 |
+
# extra check for CppMicroGemmAMX
|
| 1138 |
+
def check_amx_extra(config, m, n, k, alpha, num_threads, **kwargs):
|
| 1139 |
+
vnni_size = 4 if config.input_dtype in [torch.uint8, torch.int8] else 2
|
| 1140 |
+
return k % vnni_size == 0 and alpha == 1
|
| 1141 |
+
|
| 1142 |
+
|
| 1143 |
+
def check_int8_bf16_amx_extra(config, m, n, k, alpha, num_threads, **kwargs):
|
| 1144 |
+
# We need avx512_bf16 to dequant int8 to bf16
|
| 1145 |
+
vec_isa = kwargs.get("vec_isa")
|
| 1146 |
+
assert vec_isa is not None
|
| 1147 |
+
return vec_isa.is_avx512_bf16_supported() and check_amx_extra(
|
| 1148 |
+
config, m, n, k, alpha, num_threads, **kwargs
|
| 1149 |
+
)
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
# amx_fp16 need to be checked separately since it is not always supported when amx is supported
|
| 1153 |
+
def check_amx_fp16_extra(config, m, n, k, alpha, num_threads, **kwargs):
|
| 1154 |
+
assert config.input_dtype == torch.float16 and config.output_dtype == torch.float
|
| 1155 |
+
vec_isa = kwargs.get("vec_isa")
|
| 1156 |
+
assert vec_isa is not None
|
| 1157 |
+
vnni_size = 2
|
| 1158 |
+
return vec_isa.is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1
|
| 1159 |
+
|
| 1160 |
+
|
| 1161 |
+
@register_micro_gemm(
|
| 1162 |
+
*generate_gemm_config(
|
| 1163 |
+
VecAMX,
|
| 1164 |
+
[(32, 32, 64), (48, 16, 64)],
|
| 1165 |
+
input_dtype=torch.int8,
|
| 1166 |
+
input2_dtype=torch.int8,
|
| 1167 |
+
output_dtype=torch.int32,
|
| 1168 |
+
compute_dtype=torch.int32,
|
| 1169 |
+
extra_check=check_amx_extra,
|
| 1170 |
+
),
|
| 1171 |
+
*generate_gemm_config(
|
| 1172 |
+
VecAMX,
|
| 1173 |
+
[(32, 32, 32), (48, 16, 32)],
|
| 1174 |
+
input_dtype=torch.bfloat16,
|
| 1175 |
+
input2_dtype=torch.int8,
|
| 1176 |
+
output_dtype=torch.float,
|
| 1177 |
+
compute_dtype=torch.float,
|
| 1178 |
+
extra_check=check_int8_bf16_amx_extra,
|
| 1179 |
+
),
|
| 1180 |
+
*generate_gemm_config(
|
| 1181 |
+
VecAMX,
|
| 1182 |
+
[(32, 16, 32), (32, 32, 32), (48, 16, 32), (16, 48, 32)],
|
| 1183 |
+
input_dtype=torch.bfloat16,
|
| 1184 |
+
output_dtype=torch.float,
|
| 1185 |
+
extra_check=check_amx_extra,
|
| 1186 |
+
),
|
| 1187 |
+
*generate_gemm_config(
|
| 1188 |
+
VecAMX,
|
| 1189 |
+
[(32, 32, 32), (48, 16, 32), (16, 48, 32)],
|
| 1190 |
+
input_dtype=torch.float16,
|
| 1191 |
+
output_dtype=torch.float,
|
| 1192 |
+
extra_check=check_amx_fp16_extra,
|
| 1193 |
+
),
|
| 1194 |
+
*generate_gemm_config(
|
| 1195 |
+
VecAMX,
|
| 1196 |
+
[(32, 32, 64), (48, 16, 64)],
|
| 1197 |
+
input_dtype=torch.uint8,
|
| 1198 |
+
input2_dtype=torch.int8,
|
| 1199 |
+
output_dtype=torch.int32,
|
| 1200 |
+
compute_dtype=torch.int32,
|
| 1201 |
+
extra_check=check_amx_extra,
|
| 1202 |
+
),
|
| 1203 |
+
)
|
| 1204 |
+
class CppMicroGemmAMX(CppMicroGemm):
|
| 1205 |
+
"""
|
| 1206 |
+
This class generates the code for micro gemm using Advanced Matrix extension (AMX)
|
| 1207 |
+
instructions available in 4th generation Intel Xeon for compute.
|
| 1208 |
+
It supports input types of torch.bfloat16 with fp32 output.
|
| 1209 |
+
"""
|
| 1210 |
+
|
| 1211 |
+
TEMPLATE_ENTRY = r"""
|
| 1212 |
+
{{declare_kernel}} {
|
| 1213 |
+
{{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
|
| 1214 |
+
{{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2");
|
| 1215 |
+
{%- if pack_vnni_B_locally %}
|
| 1216 |
+
{{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K", block_n)}}
|
| 1217 |
+
{%- endif %}
|
| 1218 |
+
{%- if use_cached_dequantized_B %}
|
| 1219 |
+
// Create a stack-allocated buffer for tiles of B.
|
| 1220 |
+
// Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements.
|
| 1221 |
+
// we cache K * {{block_n}} elements of dequantized B
|
| 1222 |
+
{{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}}
|
| 1223 |
+
const auto buf_size = K * {{block_n}};
|
| 1224 |
+
auto load_dequantized_B = [&](int base_idx) {
|
| 1225 |
+
// Load a tile of B & cache it in L1D.
|
| 1226 |
+
{{input2_t}}* base_addr = const_cast<{{input2_t}}*>(B) + base_idx;
|
| 1227 |
+
for (int idx_dq = 0, idx_q = 0; idx_dq < buf_size; idx_q += ldb, idx_dq += {{block_n}}) {
|
| 1228 |
+
{%- for vec_idx in range(0, block_n, 32) %}
|
| 1229 |
+
_mm_prefetch(base_addr + idx_q + 64 * ldb, _MM_HINT_T0);
|
| 1230 |
+
{%- if (block_n - vec_idx) >= 32 %}
|
| 1231 |
+
// 1) Load 32 x int8
|
| 1232 |
+
__m256i v8 = _mm256_loadu_si256((const __m256i*)(base_addr + idx_q + {{vec_idx}}));
|
| 1233 |
+
// 2) Extract two halves
|
| 1234 |
+
__m128i v8_lo = _mm256_extracti128_si256(v8, 0);
|
| 1235 |
+
__m128i v8_hi = _mm256_extracti128_si256(v8, 1);
|
| 1236 |
+
// 3) Widen each half to i32
|
| 1237 |
+
__m512i v32_lo = _mm512_cvtepi8_epi32(v8_lo);
|
| 1238 |
+
__m512i v32_hi = _mm512_cvtepi8_epi32(v8_hi);
|
| 1239 |
+
// 4) Convert to f32
|
| 1240 |
+
__m512 f_lo = _mm512_cvtepi32_ps(v32_lo);
|
| 1241 |
+
__m512 f_hi = _mm512_cvtepi32_ps(v32_hi);
|
| 1242 |
+
// 5) f32 -> bf16 (round-to-nearest-even) and pack 32 lanes to 512b
|
| 1243 |
+
// Packs the second operand (f_lo) into the lower 16 bf16 lanes and the first (f_hi) into the upper 16.
|
| 1244 |
+
__m512i bf = (__m512i)_mm512_cvtne2ps_pbh(f_hi, f_lo);
|
| 1245 |
+
// 6) Store 32 x bf16 (512 bits)
|
| 1246 |
+
_mm512_storeu_si512((__m512i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf);
|
| 1247 |
+
{%- elif (block_n - vec_idx) >= 16 %}
|
| 1248 |
+
// 1) Load 16 x int8 (128 bits)
|
| 1249 |
+
__m128i v8 = _mm_loadu_si128((const __m128i*)(base_addr + idx_q + {{vec_idx}}));
|
| 1250 |
+
// 2) Widen: 16 x i8 -> 16 x i32
|
| 1251 |
+
__m512i v32 = _mm512_cvtepi8_epi32(v8);
|
| 1252 |
+
// 3) Convert to f32
|
| 1253 |
+
__m512 f32 = _mm512_cvtepi32_ps(v32);
|
| 1254 |
+
// 4) Convert f32 -> bf16 (round-to-nearest-even)
|
| 1255 |
+
__m256i bf16 = (__m256i)_mm512_cvtneps_pbh(f32);
|
| 1256 |
+
// 5) Store 16 x bf16 (256 bits)
|
| 1257 |
+
_mm256_storeu_si256((__m256i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf16);
|
| 1258 |
+
{%- else %}
|
| 1259 |
+
auto b_int8_tail = at::vec::Vectorized<int8_t>::loadu(
|
| 1260 |
+
base_addr + idx_q + {{block_n - (block_n % 32)}},
|
| 1261 |
+
static_cast<int64_t>({{block_n % 32}})
|
| 1262 |
+
);
|
| 1263 |
+
auto b_bf16_tail = at::vec::convert<{{input_t}}>(b_int8_tail);
|
| 1264 |
+
b_bf16_tail.store(
|
| 1265 |
+
dequantized_B_buf + idx_dq + {{block_n - (block_n % 32)}},
|
| 1266 |
+
static_cast<int64_t>({{block_n % 32}})
|
| 1267 |
+
);
|
| 1268 |
+
{%- endif %}
|
| 1269 |
+
{%- endfor %}
|
| 1270 |
+
}
|
| 1271 |
+
};
|
| 1272 |
+
{%- endif %}
|
| 1273 |
+
// The ldb would not be block_n if N != block_n
|
| 1274 |
+
{%- if use_cached_dequantized_B or pack_vnni_B_locally %}
|
| 1275 |
+
const int64_t updated_ldb = {{block_n}};
|
| 1276 |
+
{%- else %}
|
| 1277 |
+
const int64_t updated_ldb = ldb;
|
| 1278 |
+
{%- endif %}
|
| 1279 |
+
// TODO(jgong5): loop unroll for M and N
|
| 1280 |
+
for (int64_t n = 0; n < N; n += {{block_n}}) {
|
| 1281 |
+
{%- if pack_vnni_B_locally %}
|
| 1282 |
+
// Pack non-constant weights into VNNI interleaved format in packed_B_buf
|
| 1283 |
+
at::vec::pack_vnni2(B + n, packed_B_buf, ldb, K, {{block_n}});
|
| 1284 |
+
{%- elif use_cached_dequantized_B %}
|
| 1285 |
+
// Dequantize K * block_n int8 B elements into BF16
|
| 1286 |
+
load_dequantized_B(n);
|
| 1287 |
+
{%- endif %}
|
| 1288 |
+
for (int64_t m = 0; m < M; m += {{block_m}}) {
|
| 1289 |
+
int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
|
| 1290 |
+
int64_t m_tail = m;
|
| 1291 |
+
{%- for num_rows in range(block_m, 0, -16) %}
|
| 1292 |
+
{%- if num_rows != block_m %}
|
| 1293 |
+
else
|
| 1294 |
+
{%- endif %}
|
| 1295 |
+
if (block_m >= {{num_rows}}) {
|
| 1296 |
+
{{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}<accum>(
|
| 1297 |
+
amx_state,
|
| 1298 |
+
A + m * lda,
|
| 1299 |
+
{%- if use_cached_dequantized_B %}
|
| 1300 |
+
dequantized_B_buf,
|
| 1301 |
+
{%- elif pack_vnni_B_locally %}
|
| 1302 |
+
packed_B_buf,
|
| 1303 |
+
{%- else %}
|
| 1304 |
+
B + n,
|
| 1305 |
+
{%- endif %}
|
| 1306 |
+
C + m * ldc + n,
|
| 1307 |
+
K,
|
| 1308 |
+
lda,
|
| 1309 |
+
updated_ldb,
|
| 1310 |
+
ldc,
|
| 1311 |
+
16
|
| 1312 |
+
);
|
| 1313 |
+
block_m -= {{num_rows}};
|
| 1314 |
+
m_tail += {{num_rows}};
|
| 1315 |
+
}
|
| 1316 |
+
{%- endfor %}
|
| 1317 |
+
if (block_m > 0) {
|
| 1318 |
+
{{kernel_name}}_amx_kernel_16_{{num_columns}}<accum>(
|
| 1319 |
+
amx_state,
|
| 1320 |
+
A + m_tail * lda,
|
| 1321 |
+
{%- if use_cached_dequantized_B %}
|
| 1322 |
+
dequantized_B_buf,
|
| 1323 |
+
{%- elif pack_vnni_B_locally %}
|
| 1324 |
+
packed_B_buf,
|
| 1325 |
+
{%- else %}
|
| 1326 |
+
B + n,
|
| 1327 |
+
{%- endif %}
|
| 1328 |
+
C + m_tail * ldc + n,
|
| 1329 |
+
K,
|
| 1330 |
+
lda,
|
| 1331 |
+
updated_ldb,
|
| 1332 |
+
ldc,
|
| 1333 |
+
block_m
|
| 1334 |
+
);
|
| 1335 |
+
}
|
| 1336 |
+
}
|
| 1337 |
+
}
|
| 1338 |
+
}
|
| 1339 |
+
"""
|
| 1340 |
+
|
| 1341 |
+
TEMPLATE_KERNEL = r"""
|
| 1342 |
+
|
| 1343 |
+
template <bool accum, bool prefetch=false>
|
| 1344 |
+
inline void {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}(
|
| 1345 |
+
AMXState& amx_state,
|
| 1346 |
+
const {{input_t}}* {{restrict_keyword}} A,
|
| 1347 |
+
{%- if use_cached_dequantized_B %}
|
| 1348 |
+
const {{input_t}}* {{restrict_keyword}} B,
|
| 1349 |
+
{%- else %}
|
| 1350 |
+
const {{input2_t}}* {{restrict_keyword}} B,
|
| 1351 |
+
{%- endif %}
|
| 1352 |
+
{{output_t}}* {{restrict_keyword}} C,
|
| 1353 |
+
int64_t K,
|
| 1354 |
+
int64_t lda,
|
| 1355 |
+
int64_t ldb,
|
| 1356 |
+
int64_t ldc,
|
| 1357 |
+
uint8_t tilecfg_rows
|
| 1358 |
+
) {
|
| 1359 |
+
// TODO(jgong5): add prefetch hint for A, B, C
|
| 1360 |
+
auto loadconfig = [](const amx_tilecfg& cfg) {
|
| 1361 |
+
_tile_loadconfig(&cfg);
|
| 1362 |
+
};
|
| 1363 |
+
const auto last_k_offset = K / {{block_k}} * {{block_k}};
|
| 1364 |
+
const auto tail_k_size = K - last_k_offset;
|
| 1365 |
+
if C10_LIKELY (last_k_offset > 0) {
|
| 1366 |
+
amx_state.configure(tilecfg_rows, 64, {{num_rows}} / 16, {{num_columns}}, loadconfig);
|
| 1367 |
+
} else {
|
| 1368 |
+
amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig);
|
| 1369 |
+
}
|
| 1370 |
+
auto load_c = [&]() {
|
| 1371 |
+
{%- for tile_row in range(num_rows // 16) %}
|
| 1372 |
+
{%- for tile_col in range(num_columns) %}
|
| 1373 |
+
{%- set tile_idx = tile_row * num_columns + tile_col %}
|
| 1374 |
+
_tile_loadd({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}}));
|
| 1375 |
+
{%- endfor %}
|
| 1376 |
+
{%- endfor %}
|
| 1377 |
+
};
|
| 1378 |
+
auto zero_c = [&]() {
|
| 1379 |
+
{%- for tile_row in range(num_rows // 16) %}
|
| 1380 |
+
{%- for tile_col in range(num_columns) %}
|
| 1381 |
+
{%- set tile_idx = tile_row * num_columns + tile_col %}
|
| 1382 |
+
_tile_zero({{tile_idx}});
|
| 1383 |
+
{%- endfor %}
|
| 1384 |
+
{%- endfor %}
|
| 1385 |
+
};
|
| 1386 |
+
|
| 1387 |
+
if constexpr (accum) {
|
| 1388 |
+
load_c();
|
| 1389 |
+
} else {
|
| 1390 |
+
zero_c();
|
| 1391 |
+
}
|
| 1392 |
+
|
| 1393 |
+
auto compute = [&](int k) {
|
| 1394 |
+
{%- set tile_offset_a = num_rows // 16 * num_columns %}
|
| 1395 |
+
{%- set tile_offset_b = tile_offset_a + num_rows // 16 %}
|
| 1396 |
+
{%- for tile_row in range(num_rows // 16) %}
|
| 1397 |
+
{%- for tile_col in range(num_columns) %}
|
| 1398 |
+
{%- set tile_idx_a = tile_offset_a + tile_row %}
|
| 1399 |
+
{%- set tile_idx_b = tile_offset_b + tile_col %}
|
| 1400 |
+
{%- set tile_idx_c = tile_row * num_columns + tile_col %}
|
| 1401 |
+
{%- if tile_col == 0 %}
|
| 1402 |
+
_tile_stream_loadd({{tile_idx_a}}, A + {{tile_row * 16}} * lda + k, lda * sizeof({{input_t}}));
|
| 1403 |
+
{%- endif %}
|
| 1404 |
+
{%- if tile_row == 0 %}
|
| 1405 |
+
_tile_loadd({{tile_idx_b}}, B + k * ldb + {{tile_col * 16 * vnni_size}}, ldb * {{vnni_size}} * sizeof({{input_t}}));
|
| 1406 |
+
{%- endif %}
|
| 1407 |
+
{%- if int8_gemm %}
|
| 1408 |
+
{%- if input_dtype == torch.int8 %}
|
| 1409 |
+
_tile_dpbssd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
|
| 1410 |
+
{%- else %}
|
| 1411 |
+
_tile_dpbusd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
|
| 1412 |
+
{%- endif %}
|
| 1413 |
+
{%- else %}
|
| 1414 |
+
{%- if input_dtype == torch.float16 %}
|
| 1415 |
+
_tile_dpfp16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
|
| 1416 |
+
{%- else %}
|
| 1417 |
+
_tile_dpbf16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
|
| 1418 |
+
{%- endif %}
|
| 1419 |
+
{%- endif %}
|
| 1420 |
+
{%- endfor %}
|
| 1421 |
+
{%- endfor %}
|
| 1422 |
+
};
|
| 1423 |
+
|
| 1424 |
+
{{kernel.unroll_pragma(4)}}
|
| 1425 |
+
for (int k = 0; k < last_k_offset; k += {{block_k}}) {
|
| 1426 |
+
compute(k);
|
| 1427 |
+
}
|
| 1428 |
+
|
| 1429 |
+
auto store_c = [&]() {
|
| 1430 |
+
// store to C
|
| 1431 |
+
{%- for tile_row in range(num_rows // 16) %}
|
| 1432 |
+
{%- for tile_col in range(num_columns) %}
|
| 1433 |
+
{%- set tile_idx = tile_row * num_columns + tile_col %}
|
| 1434 |
+
_tile_stored({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}}));
|
| 1435 |
+
{%- endfor %}
|
| 1436 |
+
{%- endfor %}
|
| 1437 |
+
};
|
| 1438 |
+
|
| 1439 |
+
// TODO(jgong5): move tail k computation to separate loopnest to save tile configuration overhead
|
| 1440 |
+
if C10_UNLIKELY (tail_k_size > 0) {
|
| 1441 |
+
if C10_LIKELY (last_k_offset > 0) {
|
| 1442 |
+
store_c();
|
| 1443 |
+
amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig);
|
| 1444 |
+
load_c();
|
| 1445 |
+
}
|
| 1446 |
+
compute(last_k_offset);
|
| 1447 |
+
}
|
| 1448 |
+
|
| 1449 |
+
store_c();
|
| 1450 |
+
}
|
| 1451 |
+
"""
|
| 1452 |
+
|
| 1453 |
+
def codegen_define(self, kernel: CppTemplateKernel) -> str:
|
| 1454 |
+
block_m, block_n, block_k = self.register_blocking
|
| 1455 |
+
assert block_m % 16 == 0, "Only support block_m % 16 == 0 for AMX"
|
| 1456 |
+
assert block_n % 16 == 0, "Only support block_n % 16 == 0 for AMX"
|
| 1457 |
+
if self.input_dtype in [torch.uint8, torch.int8]:
|
| 1458 |
+
assert block_k == 64, "Only support block_k = 64 for AMX INT8"
|
| 1459 |
+
else:
|
| 1460 |
+
assert block_k == 32, "Only support block_k = 32 for AMX Bfloat16/Float16"
|
| 1461 |
+
num_columns = block_n // 16
|
| 1462 |
+
options = {
|
| 1463 |
+
"declare_kernel": self.get_kernel_declaration(),
|
| 1464 |
+
"use_cached_dequantized_B": (
|
| 1465 |
+
self.input_dtype == torch.bfloat16
|
| 1466 |
+
and self.input2_dtype in [torch.int8, torch.uint8]
|
| 1467 |
+
),
|
| 1468 |
+
"kernel": kernel,
|
| 1469 |
+
"block_m": block_m,
|
| 1470 |
+
"block_n": block_n,
|
| 1471 |
+
"block_k": block_k,
|
| 1472 |
+
"num_columns": num_columns,
|
| 1473 |
+
"restrict_keyword": get_restrict_keyword(),
|
| 1474 |
+
**self.get_common_options(),
|
| 1475 |
+
}
|
| 1476 |
+
result = ""
|
| 1477 |
+
for num_rows in range(block_m, 0, -16):
|
| 1478 |
+
amx_kernel_options = {**options, "num_rows": num_rows}
|
| 1479 |
+
result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
|
| 1480 |
+
amx_kernel_options
|
| 1481 |
+
)
|
| 1482 |
+
result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(
|
| 1483 |
+
options
|
| 1484 |
+
)
|
| 1485 |
+
return result
|
| 1486 |
+
|
| 1487 |
+
def codegen_init(
|
| 1488 |
+
self,
|
| 1489 |
+
kernel: CppTemplateKernel,
|
| 1490 |
+
) -> str:
|
| 1491 |
+
return "AMXState amx_state;"
|
| 1492 |
+
|
| 1493 |
+
def codegen_finalize(
|
| 1494 |
+
self,
|
| 1495 |
+
kernel: CppTemplateKernel,
|
| 1496 |
+
) -> str:
|
| 1497 |
+
return "amx_state.release([]() { _tile_release(); });"
|
| 1498 |
+
|
| 1499 |
+
def get_kernel_extra_args_declare(self) -> str:
|
| 1500 |
+
return "AMXState& amx_state,"
|
| 1501 |
+
|
| 1502 |
+
def get_kernel_extra_args(self, **kwargs) -> list[str]:
|
| 1503 |
+
return ["amx_state,"]
|
| 1504 |
+
|
| 1505 |
+
def get_b_layout(self):
|
| 1506 |
+
if self.input_dtype in [torch.uint8, torch.int8]:
|
| 1507 |
+
return LayoutType.VNNI4
|
| 1508 |
+
else:
|
| 1509 |
+
return LayoutType.VNNI2
|
| 1510 |
+
|
| 1511 |
+
|
| 1512 |
+
# extra check for CppMicroBrgemm
|
| 1513 |
+
def check_brgemm_extra(config, m, n, k, alpha, num_threads, **kwargs):
|
| 1514 |
+
assert config.input_dtype == torch.half and config.output_dtype == torch.float
|
| 1515 |
+
vnni_size = 2
|
| 1516 |
+
# use brgemm for Half when amx_fp16 is supported
|
| 1517 |
+
return torch.cpu._is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
@register_micro_gemm(
|
| 1521 |
+
*generate_gemm_config(
|
| 1522 |
+
VecAMX,
|
| 1523 |
+
[(32, 32, 32), (48, 16, 32), (16, 48, 32)],
|
| 1524 |
+
input_dtype=torch.half,
|
| 1525 |
+
output_dtype=torch.float,
|
| 1526 |
+
extra_check=check_brgemm_extra,
|
| 1527 |
+
),
|
| 1528 |
+
)
|
| 1529 |
+
class CppMicroBrgemm(CppMicroGemm):
|
| 1530 |
+
"""
|
| 1531 |
+
This class generates the code for micro gemm using oneDNN brgemm.
|
| 1532 |
+
It supports input types of torch.half.
|
| 1533 |
+
"""
|
| 1534 |
+
|
| 1535 |
+
TEMPLATE_ENTRY = r"""
|
| 1536 |
+
#include <ATen/native/CPUBlas.h>
|
| 1537 |
+
{{declare_kernel}} {
|
| 1538 |
+
{%- if pack_vnni_B_locally %}
|
| 1539 |
+
{{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K * N")}}
|
| 1540 |
+
at::vec::pack_vnni2(B, packed_B_buf, ldb, K, N);
|
| 1541 |
+
{%- endif %}
|
| 1542 |
+
at::native::cpublas::brgemm(
|
| 1543 |
+
M, N, K,
|
| 1544 |
+
{%- if pack_vnni_B_locally %}
|
| 1545 |
+
lda, N, ldc,
|
| 1546 |
+
{%- else %}
|
| 1547 |
+
lda, ldb, ldc,
|
| 1548 |
+
{%- endif %}
|
| 1549 |
+
accum,
|
| 1550 |
+
A,
|
| 1551 |
+
{%- if pack_vnni_B_locally %}
|
| 1552 |
+
packed_B_buf,
|
| 1553 |
+
{%- else %}
|
| 1554 |
+
B,
|
| 1555 |
+
{%- endif %}
|
| 1556 |
+
C);
|
| 1557 |
+
}
|
| 1558 |
+
"""
|
| 1559 |
+
|
| 1560 |
+
def codegen_define(self, kernel: CppTemplateKernel) -> str:
|
| 1561 |
+
options = {
|
| 1562 |
+
"declare_kernel": self.get_kernel_declaration(),
|
| 1563 |
+
"kernel": kernel,
|
| 1564 |
+
"block_m": self.register_blocking.block_m,
|
| 1565 |
+
"block_n": self.register_blocking.block_n,
|
| 1566 |
+
"block_k": self.register_blocking.block_k,
|
| 1567 |
+
"restrict_keyword": get_restrict_keyword(),
|
| 1568 |
+
**self.get_common_options(),
|
| 1569 |
+
}
|
| 1570 |
+
result = ""
|
| 1571 |
+
result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(
|
| 1572 |
+
options
|
| 1573 |
+
)
|
| 1574 |
+
return result
|
| 1575 |
+
|
| 1576 |
+
def codegen_finalize(
|
| 1577 |
+
self,
|
| 1578 |
+
kernel: CppTemplateKernel,
|
| 1579 |
+
) -> str:
|
| 1580 |
+
return "at::native::cpublas::brgemm_release();"
|
| 1581 |
+
|
| 1582 |
+
def get_b_layout(self):
|
| 1583 |
+
assert self.input_dtype == torch.half and torch.cpu._is_amx_fp16_supported()
|
| 1584 |
+
return LayoutType.VNNI2
|
| 1585 |
+
|
| 1586 |
+
|
| 1587 |
+
def check_woq_int4_extra(config, m, n, k, alpha, num_threads, **kwargs):
|
| 1588 |
+
if alpha != 1:
|
| 1589 |
+
return False
|
| 1590 |
+
q_group_size = kwargs.get("q_group_size")
|
| 1591 |
+
assert q_group_size is not None
|
| 1592 |
+
if (
|
| 1593 |
+
q_group_size not in [32, 64, 128]
|
| 1594 |
+
or k % q_group_size != 0
|
| 1595 |
+
or config.register_blocking.block_k > q_group_size
|
| 1596 |
+
):
|
| 1597 |
+
return False
|
| 1598 |
+
return k % config.register_blocking.block_k == 0 and n % 64 == 0
|
| 1599 |
+
|
| 1600 |
+
|
| 1601 |
+
@register_micro_gemm(
|
| 1602 |
+
# TODO: support float/half input
|
| 1603 |
+
*generate_gemm_config(
|
| 1604 |
+
VecAVX512,
|
| 1605 |
+
[(4, 64, 32), (4, 64, 64), (4, 64, 128)],
|
| 1606 |
+
input_dtype=torch.bfloat16,
|
| 1607 |
+
input2_dtype=torch.uint8,
|
| 1608 |
+
output_dtype=torch.float,
|
| 1609 |
+
compute_dtype=torch.float,
|
| 1610 |
+
extra_check=check_woq_int4_extra,
|
| 1611 |
+
),
|
| 1612 |
+
)
|
| 1613 |
+
class CppMicroGemmWoQInt4Avx512(CppMicroGemmFP32Vec):
|
| 1614 |
+
"""
|
| 1615 |
+
This class generates the code for WoQ int4 micro gemm using AVX512 intrinsics.
|
| 1616 |
+
It is based on the corresponding ATen kernel.
|
| 1617 |
+
Shape of packed weight = [N // 64, K, 32], viewed as [N, K // 2]
|
| 1618 |
+
Shape of packed ScalesAndZeros = [K // group_size, N, 2]
|
| 1619 |
+
"""
|
| 1620 |
+
|
| 1621 |
+
TEMPLATE_ENTRY = r"""
|
| 1622 |
+
{{declare_kernel}} {
|
| 1623 |
+
{{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
|
| 1624 |
+
{{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}");
|
| 1625 |
+
auto group_size = q_group_size;
|
| 1626 |
+
for (int64_t m = 0; m < M; m += {{block_m}}) {
|
| 1627 |
+
int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
|
| 1628 |
+
for (int64_t n = 0; n < N; n += {{block_n}}) {
|
| 1629 |
+
if (block_m == {{block_m}}) {
|
| 1630 |
+
{{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum>(
|
| 1631 |
+
A + m * lda,
|
| 1632 |
+
reinterpret_cast<const uint8_t*>(B) + n * ldb,
|
| 1633 |
+
C + m * ldc + n,
|
| 1634 |
+
K,
|
| 1635 |
+
lda,
|
| 1636 |
+
/* ldb */ {{block_n}} / 2,
|
| 1637 |
+
ldc,
|
| 1638 |
+
group_size,
|
| 1639 |
+
ScaleAndZeros + n * 2,
|
| 1640 |
+
lds,
|
| 1641 |
+
k_start
|
| 1642 |
+
);
|
| 1643 |
+
} else {
|
| 1644 |
+
switch (block_m) {
|
| 1645 |
+
{%- for b in range(block_m - 1, 0, -1) %}
|
| 1646 |
+
case {{b}}:
|
| 1647 |
+
{{kernel_name}}_kernel<{{b}}, {{block_n}}, accum>(
|
| 1648 |
+
A + m * lda,
|
| 1649 |
+
reinterpret_cast<const uint8_t*>(B) + n * ldb,
|
| 1650 |
+
C + m * ldc + n,
|
| 1651 |
+
K,
|
| 1652 |
+
lda,
|
| 1653 |
+
/* ldb */ {{block_n}} / 2,
|
| 1654 |
+
ldc,
|
| 1655 |
+
group_size,
|
| 1656 |
+
ScaleAndZeros + n * 2,
|
| 1657 |
+
lds,
|
| 1658 |
+
k_start
|
| 1659 |
+
);
|
| 1660 |
+
break;
|
| 1661 |
+
{%- endfor %}
|
| 1662 |
+
default:
|
| 1663 |
+
{{kernel.assert_function}}(false, "Unsupported block_m: ", block_m);
|
| 1664 |
+
}
|
| 1665 |
+
}
|
| 1666 |
+
}
|
| 1667 |
+
}
|
| 1668 |
+
}
|
| 1669 |
+
"""
|
| 1670 |
+
|
| 1671 |
+
TEMPLATE_KERNEL = r"""
|
| 1672 |
+
inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) {
|
| 1673 |
+
return (k_start + index) % group_size == 0;
|
| 1674 |
+
}
|
| 1675 |
+
|
| 1676 |
+
inline __m128i {{kernel_name}}_convert_int4_to_int8(const uint8_t* data) {
|
| 1677 |
+
__m128i tmp = _mm_loadu_si64((const __m128i*)data);
|
| 1678 |
+
__m128i bytes = _mm_cvtepu8_epi16(tmp);
|
| 1679 |
+
const __m128i lowMask = _mm_set1_epi8(0xF);
|
| 1680 |
+
__m128i high = _mm_andnot_si128(lowMask, bytes);
|
| 1681 |
+
__m128i low = _mm_and_si128(lowMask, bytes);
|
| 1682 |
+
high = _mm_slli_epi16(high, 4);
|
| 1683 |
+
bytes = _mm_or_si128(low, high);
|
| 1684 |
+
return bytes;
|
| 1685 |
+
}
|
| 1686 |
+
|
| 1687 |
+
template <int64_t BLOCK_M, int64_t BLOCK_N, bool accum>
|
| 1688 |
+
inline void {{kernel_name}}_kernel(
|
| 1689 |
+
const {{input_t}}* {{restrict_keyword}} A,
|
| 1690 |
+
const uint8_t* {{restrict_keyword}} B,
|
| 1691 |
+
{{output_t}}* {{restrict_keyword}} C,
|
| 1692 |
+
int64_t K,
|
| 1693 |
+
int64_t lda,
|
| 1694 |
+
int64_t ldb,
|
| 1695 |
+
int64_t ldc,
|
| 1696 |
+
int64_t q_group_size,
|
| 1697 |
+
const at::BFloat16* {{restrict_keyword}} ScaleAndZeros,
|
| 1698 |
+
int64_t lds, // leading dimension of ScaleAndZeros
|
| 1699 |
+
int64_t k_start) {
|
| 1700 |
+
constexpr int BLOCK_K = {{block_k}};
|
| 1701 |
+
constexpr int ROWS = BLOCK_M;
|
| 1702 |
+
constexpr int COLS = BLOCK_N / 16;
|
| 1703 |
+
|
| 1704 |
+
const int PREFETCH_SIZE_K = 16 * 4;
|
| 1705 |
+
const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K;
|
| 1706 |
+
|
| 1707 |
+
// number of blocks on K
|
| 1708 |
+
const int KB = K / BLOCK_K;
|
| 1709 |
+
|
| 1710 |
+
__m512 va;
|
| 1711 |
+
__m512 vb[COLS];
|
| 1712 |
+
__m512 vc[ROWS * COLS];
|
| 1713 |
+
__m512 scale[COLS];
|
| 1714 |
+
__m512 zero[COLS];
|
| 1715 |
+
|
| 1716 |
+
// Lookup table to de-quantize int4 values to bf16.
|
| 1717 |
+
// Values are dequantized as truly int4 [-8, 7] range;
|
| 1718 |
+
//
|
| 1719 |
+
// dequant = (bf16(int4_value) * bf16_scale) + bf16_zero
|
| 1720 |
+
//
|
| 1721 |
+
static const __m512 lut = _mm512_set_ps(
|
| 1722 |
+
7.0f, 6.0f, 5.0f, 4.0f,
|
| 1723 |
+
3.0f, 2.0f, 1.0f, 0.0f,
|
| 1724 |
+
-1.0f, -2.0f, -3.0f, -4.0f,
|
| 1725 |
+
-5.0f, -6.0f, -7.0f, -8.0f);
|
| 1726 |
+
|
| 1727 |
+
// index for transpose
|
| 1728 |
+
static const __m512i idx1 = _mm512_set_epi32(
|
| 1729 |
+
30, 28, 26, 24, 22, 20, 18, 16,
|
| 1730 |
+
14, 12, 10, 8, 6, 4, 2, 0);
|
| 1731 |
+
static const __m512i idx2 = _mm512_set_epi32(
|
| 1732 |
+
31, 29, 27, 25, 23, 21, 19, 17,
|
| 1733 |
+
15, 13, 11, 9, 7, 5, 3, 1);
|
| 1734 |
+
|
| 1735 |
+
// load scale and zero point
|
| 1736 |
+
auto load_scale_and_zeros = [&](int i, int _kb) {
|
| 1737 |
+
// load 2x bfloat16 vector
|
| 1738 |
+
__m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i));
|
| 1739 |
+
_mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0);
|
| 1740 |
+
|
| 1741 |
+
// convert to 2x f32 vector
|
| 1742 |
+
__m512 a, b;
|
| 1743 |
+
at::vec::cvtbf16_fp32(t, a, b);
|
| 1744 |
+
|
| 1745 |
+
// transpose scale_and_zero from {16, 2} to {2, 16}
|
| 1746 |
+
// inputs:
|
| 1747 |
+
// a: {s0, z0, s1, z1, ..., s7, z7}
|
| 1748 |
+
// b: {s8, z8, s9, z9, ..., s15, z15}
|
| 1749 |
+
// output:
|
| 1750 |
+
// scale: {s0, s1, s2, ..., s15}
|
| 1751 |
+
// zero: {z0, z1, z2, ..., z15}
|
| 1752 |
+
scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b);
|
| 1753 |
+
zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b);
|
| 1754 |
+
};
|
| 1755 |
+
|
| 1756 |
+
auto loadc = [&](auto i) {
|
| 1757 |
+
if constexpr (accum) {
|
| 1758 |
+
constexpr int row = i / COLS;
|
| 1759 |
+
constexpr int col = i % COLS;
|
| 1760 |
+
vc[i] = _mm512_loadu_ps(C + row * ldc + col * 16);
|
| 1761 |
+
} else {
|
| 1762 |
+
vc[i] = _mm512_setzero_ps();
|
| 1763 |
+
}
|
| 1764 |
+
};
|
| 1765 |
+
c10::ForcedUnroll<ROWS * COLS>{}(loadc);
|
| 1766 |
+
|
| 1767 |
+
auto compute = [&, COLS](auto i, int k) {
|
| 1768 |
+
constexpr int row = i / COLS;
|
| 1769 |
+
constexpr int col = i % COLS;
|
| 1770 |
+
|
| 1771 |
+
if constexpr (col == 0) {
|
| 1772 |
+
float aa = static_cast<float>(A[row * lda + k]);
|
| 1773 |
+
_mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0);
|
| 1774 |
+
va = _mm512_set1_ps(aa);
|
| 1775 |
+
}
|
| 1776 |
+
|
| 1777 |
+
if constexpr (row == 0) {
|
| 1778 |
+
if constexpr (COLS == 4) {
|
| 1779 |
+
// when BLOCK_N = 64, handle each row at a time
|
| 1780 |
+
// to reduce de-quantize overhead.
|
| 1781 |
+
if constexpr (col == 0) {
|
| 1782 |
+
__m256i b4 = _mm256_loadu_si256((__m256i*)(B + k * ldb));
|
| 1783 |
+
_mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb, _MM_HINT_T0);
|
| 1784 |
+
|
| 1785 |
+
__m512i b32 = _mm512_cvtepu8_epi32(_mm256_castsi256_si128(b4));
|
| 1786 |
+
vb[0] = _mm512_permutexvar_ps(b32, lut);
|
| 1787 |
+
vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]);
|
| 1788 |
+
vb[2] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut);
|
| 1789 |
+
vb[2] = _mm512_fmadd_ps(vb[2], scale[2], zero[2]);
|
| 1790 |
+
|
| 1791 |
+
b32 = _mm512_cvtepu8_epi32(_mm256_extracti128_si256(b4, 1));
|
| 1792 |
+
vb[1] = _mm512_permutexvar_ps(b32, lut);
|
| 1793 |
+
vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]);
|
| 1794 |
+
vb[3] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut);
|
| 1795 |
+
vb[3] = _mm512_fmadd_ps(vb[3], scale[3], zero[3]);
|
| 1796 |
+
}
|
| 1797 |
+
} else {
|
| 1798 |
+
__m128i b8 = {{kernel_name}}_convert_int4_to_int8(B + k * ldb + col * 8);
|
| 1799 |
+
__m512i b32 = _mm512_cvtepu8_epi32(b8);
|
| 1800 |
+
vb[col] = _mm512_permutexvar_ps(b32, lut);
|
| 1801 |
+
vb[col] = _mm512_fmadd_ps(vb[col], scale[col], zero[col]);
|
| 1802 |
+
}
|
| 1803 |
+
}
|
| 1804 |
+
|
| 1805 |
+
constexpr int idx = row * COLS + col;
|
| 1806 |
+
vc[idx] = _mm512_fmadd_ps(va, vb[col], vc[idx]);
|
| 1807 |
+
};
|
| 1808 |
+
|
| 1809 |
+
for (int k = 0, kb = 0; k < K; ++k) {
|
| 1810 |
+
if ({{kernel_name}}_is_block_start(k, k_start, q_group_size)) {
|
| 1811 |
+
c10::ForcedUnroll<COLS>{}(load_scale_and_zeros, kb++);
|
| 1812 |
+
}
|
| 1813 |
+
c10::ForcedUnroll<ROWS * COLS>{}(compute, k);
|
| 1814 |
+
}
|
| 1815 |
+
|
| 1816 |
+
//store to C
|
| 1817 |
+
auto storec = [&, COLS](auto i) {
|
| 1818 |
+
constexpr int row = i / COLS;
|
| 1819 |
+
constexpr int col = i % COLS;
|
| 1820 |
+
_mm512_storeu_ps(C + row * ldc + col * 16, vc[i]);
|
| 1821 |
+
};
|
| 1822 |
+
c10::ForcedUnroll<ROWS * COLS>{}(storec);
|
| 1823 |
+
}
|
| 1824 |
+
"""
|
| 1825 |
+
|
| 1826 |
+
def get_kernel_extra_args_declare(self) -> str:
|
| 1827 |
+
return (
|
| 1828 |
+
"const int64_t q_group_size,\n"
|
| 1829 |
+
" const at::BFloat16* __restrict__ ScaleAndZeros,\n"
|
| 1830 |
+
" const int64_t lds,\n"
|
| 1831 |
+
" int64_t k_start,"
|
| 1832 |
+
)
|
| 1833 |
+
|
| 1834 |
+
def get_kernel_extra_args(self, **kwargs) -> list[str]:
|
| 1835 |
+
assert "kernel" in kwargs
|
| 1836 |
+
assert "qscale_and_zeros" in kwargs
|
| 1837 |
+
kernel = kwargs["kernel"]
|
| 1838 |
+
qscale_and_zeros = kwargs["qscale_and_zeros"]
|
| 1839 |
+
return [
|
| 1840 |
+
"group_size,",
|
| 1841 |
+
f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),",
|
| 1842 |
+
"N * 2,", # lds
|
| 1843 |
+
"k_start,",
|
| 1844 |
+
]
|
| 1845 |
+
|
| 1846 |
+
def is_woq_int4(self):
|
| 1847 |
+
return True
|
| 1848 |
+
|
| 1849 |
+
|
| 1850 |
+
@register_micro_gemm(
|
| 1851 |
+
*generate_gemm_config(
|
| 1852 |
+
VecAMX,
|
| 1853 |
+
[ # (block_m, block_n, block_k)
|
| 1854 |
+
(16, 32, 32),
|
| 1855 |
+
(32, 32, 32),
|
| 1856 |
+
],
|
| 1857 |
+
input_dtype=torch.bfloat16,
|
| 1858 |
+
input2_dtype=torch.uint8,
|
| 1859 |
+
output_dtype=torch.float,
|
| 1860 |
+
compute_dtype=torch.float,
|
| 1861 |
+
extra_check=check_amx_extra,
|
| 1862 |
+
),
|
| 1863 |
+
)
|
| 1864 |
+
class CppMicroGemmWoQInt4Amx(CppMicroGemmAMX):
|
| 1865 |
+
"""
|
| 1866 |
+
This class generates the code for WoQ int4 micro gemm using AMX intrinsics,
|
| 1867 |
+
which are available on 4th and newer generations of Intel Xeon.
|
| 1868 |
+
Shape of packed weight = [N // 32, K, 16], viewed as [N, K // 2]
|
| 1869 |
+
Shape of packed ScalesAndZeros = [K // group_size, N, 2]
|
| 1870 |
+
Reuse TEMPLATE_KERNEL of CppMicroGemmAMX.
|
| 1871 |
+
"""
|
| 1872 |
+
|
| 1873 |
+
TEMPLATE_ENTRY = r"""
|
| 1874 |
+
inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) {
|
| 1875 |
+
// check if (k_start + index) % group_size == 0, assuming group_size = 32/64/128
|
| 1876 |
+
return ((k_start + index) & (group_size - 1)) == 0;
|
| 1877 |
+
}
|
| 1878 |
+
|
| 1879 |
+
{{declare_kernel}} {
|
| 1880 |
+
{{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
|
| 1881 |
+
{{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2");
|
| 1882 |
+
{{kernel.assert_function}}({{block_n}} == 32, "block_n must be 32 for WOQ int4");
|
| 1883 |
+
|
| 1884 |
+
// Create a stack-allocated buffer for tiles of B.
|
| 1885 |
+
// Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements.
|
| 1886 |
+
// we cache K * {{block_n}} elements of dequantized B
|
| 1887 |
+
{{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}}
|
| 1888 |
+
|
| 1889 |
+
constexpr int BLOCK_K = {{block_k}};
|
| 1890 |
+
constexpr int64_t BLOCK_N = {{block_n}};
|
| 1891 |
+
constexpr int COLS = BLOCK_N / 16;
|
| 1892 |
+
const int PREFETCH_SIZE_K = 16 * 4;
|
| 1893 |
+
const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K;
|
| 1894 |
+
const int KB = K / BLOCK_K;
|
| 1895 |
+
|
| 1896 |
+
__m512i b32[COLS * 2];
|
| 1897 |
+
__m512 vb[COLS * 2];
|
| 1898 |
+
__m512 scale[COLS];
|
| 1899 |
+
__m512 zero[COLS];
|
| 1900 |
+
|
| 1901 |
+
// Lookup table to de-quantize int4 values to bf16.
|
| 1902 |
+
// Values are dequantized as truly int4 [-8, 7] range;
|
| 1903 |
+
//
|
| 1904 |
+
// dequant = (bf16(int4_value) * bf16_scale) + bf16_zero
|
| 1905 |
+
//
|
| 1906 |
+
static const __m512 lut = _mm512_set_ps(
|
| 1907 |
+
7.0f, 6.0f, 5.0f, 4.0f,
|
| 1908 |
+
3.0f, 2.0f, 1.0f, 0.0f,
|
| 1909 |
+
-1.0f, -2.0f, -3.0f, -4.0f,
|
| 1910 |
+
-5.0f, -6.0f, -7.0f, -8.0f);
|
| 1911 |
+
|
| 1912 |
+
// index for transpose
|
| 1913 |
+
static const __m512i idx1 = _mm512_set_epi32(
|
| 1914 |
+
30, 28, 26, 24, 22, 20, 18, 16,
|
| 1915 |
+
14, 12, 10, 8, 6, 4, 2, 0);
|
| 1916 |
+
static const __m512i idx2 = _mm512_set_epi32(
|
| 1917 |
+
31, 29, 27, 25, 23, 21, 19, 17,
|
| 1918 |
+
15, 13, 11, 9, 7, 5, 3, 1);
|
| 1919 |
+
|
| 1920 |
+
// Indices for VNNI layout conversion
|
| 1921 |
+
__m512i idx_low = _mm512_set_epi32(
|
| 1922 |
+
0x17,
|
| 1923 |
+
0x07,
|
| 1924 |
+
0x16,
|
| 1925 |
+
0x06,
|
| 1926 |
+
0x15,
|
| 1927 |
+
0x05,
|
| 1928 |
+
0x14,
|
| 1929 |
+
0x04,
|
| 1930 |
+
0x13,
|
| 1931 |
+
0x03,
|
| 1932 |
+
0x12,
|
| 1933 |
+
0x02,
|
| 1934 |
+
0x11,
|
| 1935 |
+
0x01,
|
| 1936 |
+
0x10,
|
| 1937 |
+
0x00);
|
| 1938 |
+
__m512i idx_high = _mm512_set_epi32(
|
| 1939 |
+
0x1f,
|
| 1940 |
+
0x0f,
|
| 1941 |
+
0x1e,
|
| 1942 |
+
0x0e,
|
| 1943 |
+
0x1d,
|
| 1944 |
+
0x0d,
|
| 1945 |
+
0x1c,
|
| 1946 |
+
0x0c,
|
| 1947 |
+
0x1b,
|
| 1948 |
+
0x0b,
|
| 1949 |
+
0x1a,
|
| 1950 |
+
0x0a,
|
| 1951 |
+
0x19,
|
| 1952 |
+
0x09,
|
| 1953 |
+
0x18,
|
| 1954 |
+
0x08);
|
| 1955 |
+
|
| 1956 |
+
// load scale and zero point
|
| 1957 |
+
auto load_scale_and_zeros = [&](int i, int _kb) {
|
| 1958 |
+
// load 2x bfloat16 vector
|
| 1959 |
+
__m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i));
|
| 1960 |
+
_mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0);
|
| 1961 |
+
|
| 1962 |
+
// convert to 2x f32 vector
|
| 1963 |
+
__m512 a, b;
|
| 1964 |
+
at::vec::cvtbf16_fp32(t, a, b);
|
| 1965 |
+
|
| 1966 |
+
// transpose scale_and_zero from {16, 2} to {2, 16}
|
| 1967 |
+
// inputs:
|
| 1968 |
+
// a: {s0, z0, s1, z1, ..., s7, z7}
|
| 1969 |
+
// b: {s8, z8, s9, z9, ..., s15, z15}
|
| 1970 |
+
// output:
|
| 1971 |
+
// scale: {s0, s1, s2, ..., s15}
|
| 1972 |
+
// zero: {z0, z1, z2, ..., z15}
|
| 1973 |
+
scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b);
|
| 1974 |
+
zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b);
|
| 1975 |
+
};
|
| 1976 |
+
|
| 1977 |
+
// Dequantize a B block of 2 * block_n into bf16
|
| 1978 |
+
// So, it handles k and k+1 at the same time
|
| 1979 |
+
auto dequantize_B = [&](int n) {
|
| 1980 |
+
constexpr int64_t ldb_int4 = BLOCK_N / 2; // 16
|
| 1981 |
+
for (int k = 0, kb = 0; k < K; k += 2) {
|
| 1982 |
+
// Since block_k must be 32 for AMX microkernels, k_start may not be
|
| 1983 |
+
// a multiple of q_group_size. In that case, we need to load scales
|
| 1984 |
+
// and zero points immediately when k == 0 here
|
| 1985 |
+
if ({{kernel_name}}_is_block_start(k, k_start, q_group_size) || k == 0) {
|
| 1986 |
+
c10::ForcedUnroll<COLS>{}(load_scale_and_zeros, kb++);
|
| 1987 |
+
}
|
| 1988 |
+
|
| 1989 |
+
_mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb_int4, _MM_HINT_T0);
|
| 1990 |
+
|
| 1991 |
+
// load 256 bits = 64 elements in int4
|
| 1992 |
+
__m128i b4 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + k * ldb_int4));
|
| 1993 |
+
b32[0] = _mm512_cvtepu8_epi32(b4);
|
| 1994 |
+
b32[1] = _mm512_srli_epi32(b32[0], 4);
|
| 1995 |
+
vb[0] = _mm512_permutexvar_ps(b32[0] , lut);
|
| 1996 |
+
vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]);
|
| 1997 |
+
vb[1] = _mm512_permutexvar_ps(b32[1], lut);
|
| 1998 |
+
vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]);
|
| 1999 |
+
|
| 2000 |
+
__m128i b4_2 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + (k + 1) * ldb_int4));
|
| 2001 |
+
b32[0 + COLS] = _mm512_cvtepu8_epi32(b4_2);
|
| 2002 |
+
b32[1 + COLS] = _mm512_srli_epi32(b32[0 + COLS], 4);
|
| 2003 |
+
vb[0 + COLS] = _mm512_permutexvar_ps(b32[0 + COLS] , lut);
|
| 2004 |
+
vb[0 + COLS] = _mm512_fmadd_ps(vb[0 + COLS], scale[0], zero[0]);
|
| 2005 |
+
vb[1 + COLS] = _mm512_permutexvar_ps(b32[1 + COLS], lut);
|
| 2006 |
+
vb[1 + COLS] = _mm512_fmadd_ps(vb[1 + COLS], scale[1], zero[1]);
|
| 2007 |
+
|
| 2008 |
+
for (int i = 0; i < COLS; i++) {
|
| 2009 |
+
// convert to VNNI
|
| 2010 |
+
auto low = _mm512_permutex2var_ps(vb[i], idx_low, vb[i + COLS]);
|
| 2011 |
+
auto high = _mm512_permutex2var_ps(vb[i], idx_high, vb[i + COLS]);
|
| 2012 |
+
// convert lower 16 float32 values to bfloat16
|
| 2013 |
+
auto v0_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(low));
|
| 2014 |
+
// convert higher 16 float32 values to bfloat16
|
| 2015 |
+
auto v1_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(high));
|
| 2016 |
+
// combine the lower 16 and higher 16 bfloat16 values
|
| 2017 |
+
auto v = _mm512_castsi256_si512(v0_bf16);
|
| 2018 |
+
v = _mm512_inserti64x4(v, v1_bf16, 1);
|
| 2019 |
+
// store the VNNI format bfloat16 values
|
| 2020 |
+
{{input_t}}* addr = dequantized_B_buf + k * 32 + (i % 2) * 32;
|
| 2021 |
+
_mm512_storeu_si512(addr, v);
|
| 2022 |
+
}
|
| 2023 |
+
}
|
| 2024 |
+
};
|
| 2025 |
+
|
| 2026 |
+
for (int64_t n = 0; n < N; n += {{block_n}}) {
|
| 2027 |
+
// Dequantize K * block_n int8 B elements into BF16
|
| 2028 |
+
dequantize_B(n);
|
| 2029 |
+
for (int64_t m = 0; m < M; m += {{block_m}}) {
|
| 2030 |
+
int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
|
| 2031 |
+
int64_t m_tail = m;
|
| 2032 |
+
{%- for num_rows in range(block_m, 0, -16) %}
|
| 2033 |
+
{%- if num_rows != block_m %}
|
| 2034 |
+
else
|
| 2035 |
+
{%- endif %}
|
| 2036 |
+
if (block_m >= {{num_rows}}) {
|
| 2037 |
+
{{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}<accum>(
|
| 2038 |
+
amx_state,
|
| 2039 |
+
A + m * lda,
|
| 2040 |
+
dequantized_B_buf + n * K,
|
| 2041 |
+
C + m * ldc + n,
|
| 2042 |
+
K,
|
| 2043 |
+
lda,
|
| 2044 |
+
{{block_n}},
|
| 2045 |
+
ldc,
|
| 2046 |
+
16
|
| 2047 |
+
);
|
| 2048 |
+
block_m -= {{num_rows}};
|
| 2049 |
+
m_tail += {{num_rows}};
|
| 2050 |
+
}
|
| 2051 |
+
{%- endfor %}
|
| 2052 |
+
if (block_m > 0) {
|
| 2053 |
+
{{kernel_name}}_amx_kernel_16_{{num_columns}}<accum>(
|
| 2054 |
+
amx_state,
|
| 2055 |
+
A + m_tail * lda,
|
| 2056 |
+
dequantized_B_buf + n * K,
|
| 2057 |
+
C + m_tail * ldc + n,
|
| 2058 |
+
K,
|
| 2059 |
+
lda,
|
| 2060 |
+
{{block_n}},
|
| 2061 |
+
ldc,
|
| 2062 |
+
block_m
|
| 2063 |
+
);
|
| 2064 |
+
}
|
| 2065 |
+
} // for m
|
| 2066 |
+
} // for n
|
| 2067 |
+
}
|
| 2068 |
+
"""
|
| 2069 |
+
|
| 2070 |
+
def get_kernel_extra_args_declare(self) -> str:
|
| 2071 |
+
return (
|
| 2072 |
+
"AMXState& amx_state,\n"
|
| 2073 |
+
" const int64_t q_group_size,\n"
|
| 2074 |
+
" const c10::BFloat16* __restrict__ ScaleAndZeros,\n"
|
| 2075 |
+
" const int64_t lds,\n"
|
| 2076 |
+
" int64_t k_start,"
|
| 2077 |
+
)
|
| 2078 |
+
|
| 2079 |
+
def get_kernel_extra_args(self, **kwargs) -> list[str]:
|
| 2080 |
+
assert "kernel" in kwargs
|
| 2081 |
+
assert "qscale_and_zeros" in kwargs
|
| 2082 |
+
kernel = kwargs["kernel"]
|
| 2083 |
+
qscale_and_zeros = kwargs["qscale_and_zeros"]
|
| 2084 |
+
return [
|
| 2085 |
+
"amx_state,",
|
| 2086 |
+
"group_size,",
|
| 2087 |
+
f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),",
|
| 2088 |
+
"N * 2,", # lds
|
| 2089 |
+
"k_start,",
|
| 2090 |
+
]
|
| 2091 |
+
|
| 2092 |
+
def is_woq_int4(self):
|
| 2093 |
+
return True
|
| 2094 |
+
|
| 2095 |
+
|
| 2096 |
+
def create_micro_gemm(
|
| 2097 |
+
name,
|
| 2098 |
+
m,
|
| 2099 |
+
n,
|
| 2100 |
+
k,
|
| 2101 |
+
input_dtype,
|
| 2102 |
+
input2_dtype,
|
| 2103 |
+
output_dtype=None,
|
| 2104 |
+
compute_dtype=None,
|
| 2105 |
+
alpha=1,
|
| 2106 |
+
num_threads=-1,
|
| 2107 |
+
use_ref=True,
|
| 2108 |
+
q_group_size=None,
|
| 2109 |
+
) -> Optional[CppMicroGemm]:
|
| 2110 |
+
"""
|
| 2111 |
+
Based on the provided info, try to find the config of the micro-kernel that would
|
| 2112 |
+
deliver the best performance in terms of lower latency for this case.
|
| 2113 |
+
"""
|
| 2114 |
+
|
| 2115 |
+
def create_from_config(cls, config: CppMicroGemmConfig):
|
| 2116 |
+
return cls(
|
| 2117 |
+
name,
|
| 2118 |
+
config.input_dtype,
|
| 2119 |
+
config.input2_dtype,
|
| 2120 |
+
config.output_dtype,
|
| 2121 |
+
config.compute_dtype,
|
| 2122 |
+
config.register_blocking,
|
| 2123 |
+
alpha,
|
| 2124 |
+
)
|
| 2125 |
+
|
| 2126 |
+
def skip_amx_kernel_for_woq(dynamic_M):
|
| 2127 |
+
# For WoQ GEMM, AMX micro-kernel may not perform well if m is small.
|
| 2128 |
+
# Exception: for dynamic shapes, we consider using the AMX micro-kernel.
|
| 2129 |
+
if (
|
| 2130 |
+
dynamic_M
|
| 2131 |
+
or input_dtype != torch.bfloat16
|
| 2132 |
+
or input2_dtype not in [torch.int8, torch.uint8]
|
| 2133 |
+
):
|
| 2134 |
+
return False
|
| 2135 |
+
m_threshold = 5
|
| 2136 |
+
return m < m_threshold
|
| 2137 |
+
|
| 2138 |
+
assert isinstance(n, int) or n.is_number, n
|
| 2139 |
+
assert isinstance(k, int) or k.is_number, k
|
| 2140 |
+
from ..utils import has_free_symbols
|
| 2141 |
+
|
| 2142 |
+
dynamic_M = has_free_symbols((m,))
|
| 2143 |
+
m = V.graph.sizevars.size_hint(m, fallback=1) if dynamic_M else m
|
| 2144 |
+
assert isinstance(m, int) or m.is_number, m
|
| 2145 |
+
if output_dtype is None:
|
| 2146 |
+
output_dtype = input_dtype
|
| 2147 |
+
if compute_dtype is None:
|
| 2148 |
+
compute_dtype = output_dtype
|
| 2149 |
+
if num_threads < 0:
|
| 2150 |
+
num_threads = parallel_num_threads()
|
| 2151 |
+
vec_isa = pick_vec_isa()
|
| 2152 |
+
matched_configs = []
|
| 2153 |
+
for cls, configs in micro_gemm_configs.items():
|
| 2154 |
+
for config in configs:
|
| 2155 |
+
if not issubclass(vec_isa.__class__, config.vec_isa_cls):
|
| 2156 |
+
continue
|
| 2157 |
+
if (
|
| 2158 |
+
config.input_dtype == input_dtype
|
| 2159 |
+
and config.compute_dtype == compute_dtype
|
| 2160 |
+
and config.input2_dtype == input2_dtype
|
| 2161 |
+
and config.output_dtype == output_dtype
|
| 2162 |
+
# The output_dtype here is the output dtype of the micro-kernel.
|
| 2163 |
+
# In some cases, the actual output dtype of the op for which the micro-kernel
|
| 2164 |
+
# is being created would be same as that of the activation, but the micro-kernels
|
| 2165 |
+
# compute output in Float/int32, which is converted in the GEMM template. This is
|
| 2166 |
+
# subject to change in the future.
|
| 2167 |
+
):
|
| 2168 |
+
if config.extra_check is not None and not config.extra_check(
|
| 2169 |
+
config,
|
| 2170 |
+
m,
|
| 2171 |
+
n,
|
| 2172 |
+
k,
|
| 2173 |
+
alpha,
|
| 2174 |
+
num_threads,
|
| 2175 |
+
dynamic_M=dynamic_M,
|
| 2176 |
+
q_group_size=q_group_size,
|
| 2177 |
+
vec_isa=vec_isa,
|
| 2178 |
+
):
|
| 2179 |
+
continue
|
| 2180 |
+
block_m, block_n, block_k = config.register_blocking
|
| 2181 |
+
if config.vec_isa_cls == VecAMX and skip_amx_kernel_for_woq(dynamic_M):
|
| 2182 |
+
continue
|
| 2183 |
+
# Criteria on the ranking of configurations
|
| 2184 |
+
# 1. ISA: AMX > VNNI > VEC
|
| 2185 |
+
# 2. Dividable by block sizes (block_m, block_n, block_k)
|
| 2186 |
+
# 3. Number of mxn blocks is large enough to occupy all the threads
|
| 2187 |
+
# 4. Register blocks are larger
|
| 2188 |
+
isa_score = 0
|
| 2189 |
+
if config.vec_isa_cls == VecAMX:
|
| 2190 |
+
isa_score += 2
|
| 2191 |
+
elif config.vec_isa_cls == VecAVX512VNNI:
|
| 2192 |
+
isa_score += 1
|
| 2193 |
+
dividable_score = 0
|
| 2194 |
+
if m % block_m == 0:
|
| 2195 |
+
dividable_score += 1
|
| 2196 |
+
if n % block_n == 0:
|
| 2197 |
+
dividable_score += 1
|
| 2198 |
+
if k % block_k == 0:
|
| 2199 |
+
dividable_score += 1
|
| 2200 |
+
occupancy_score = 0
|
| 2201 |
+
n_blocks = (n + block_n - 1) // block_n
|
| 2202 |
+
total_mxn_blocks = n_blocks * ((m + block_m - 1) // block_m)
|
| 2203 |
+
if n_blocks >= num_threads:
|
| 2204 |
+
occupancy_score += 1
|
| 2205 |
+
if total_mxn_blocks >= num_threads:
|
| 2206 |
+
occupancy_score += 1
|
| 2207 |
+
register_bytes = (
|
| 2208 |
+
block_m * block_n * config.compute_dtype.itemsize
|
| 2209 |
+
+ (block_m * block_k + block_k * block_n)
|
| 2210 |
+
* config.input_dtype.itemsize
|
| 2211 |
+
)
|
| 2212 |
+
size_score = register_bytes
|
| 2213 |
+
# if number of mxn blocks can not occupy all the threads,
|
| 2214 |
+
# we favor smaller register blocks.
|
| 2215 |
+
if occupancy_score == 0:
|
| 2216 |
+
size_score = 0 - register_bytes
|
| 2217 |
+
matched_configs.append(
|
| 2218 |
+
(
|
| 2219 |
+
(isa_score, dividable_score, occupancy_score, size_score),
|
| 2220 |
+
cls,
|
| 2221 |
+
config,
|
| 2222 |
+
)
|
| 2223 |
+
)
|
| 2224 |
+
if len(matched_configs) == 0:
|
| 2225 |
+
if use_ref:
|
| 2226 |
+
return CppMicroGemmRef(
|
| 2227 |
+
name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha
|
| 2228 |
+
)
|
| 2229 |
+
else:
|
| 2230 |
+
return None
|
| 2231 |
+
# TODO(jgong5): allow autotuning on choices of configs
|
| 2232 |
+
return create_from_config(*max(matched_configs, key=operator.itemgetter(0))[1:])
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import ctypes
|
| 3 |
+
import functools
|
| 4 |
+
import itertools
|
| 5 |
+
import logging
|
| 6 |
+
import sys
|
| 7 |
+
from collections.abc import Callable, Iterable
|
| 8 |
+
from typing import Optional, Union
|
| 9 |
+
from unittest.mock import patch
|
| 10 |
+
|
| 11 |
+
import sympy
|
| 12 |
+
|
| 13 |
+
from .. import config, ir
|
| 14 |
+
from ..autotune_process import CppBenchmarkRequest, TensorMeta
|
| 15 |
+
from ..utils import IndentedBuffer, Placeholder, unique
|
| 16 |
+
from ..virtualized import V
|
| 17 |
+
from .common import KernelTemplate
|
| 18 |
+
from .cpp_template_kernel import CppTemplateCaller, CppTemplateKernel
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
log = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class CppTemplate(KernelTemplate):
|
| 25 |
+
index_counter = itertools.count()
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self,
|
| 29 |
+
name: str,
|
| 30 |
+
input_nodes,
|
| 31 |
+
layout: ir.Layout,
|
| 32 |
+
num_threads: int,
|
| 33 |
+
epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
|
| 34 |
+
) -> None:
|
| 35 |
+
super().__init__(name)
|
| 36 |
+
self.input_nodes = input_nodes
|
| 37 |
+
self.index = next(self.index_counter)
|
| 38 |
+
self.output_node: Union[ir.Buffer, list[ir.Buffer]] = ir.Buffer(
|
| 39 |
+
name=f"buf_out{self.index}", layout=layout
|
| 40 |
+
)
|
| 41 |
+
self.layout = layout
|
| 42 |
+
self.num_threads = num_threads
|
| 43 |
+
self.epilogue_creator = epilogue_creator
|
| 44 |
+
|
| 45 |
+
def generate(self, **kwargs):
|
| 46 |
+
kernel_name = f"cpp_{self.name}"
|
| 47 |
+
with (
|
| 48 |
+
patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)),
|
| 49 |
+
patch.object(ir.FlexibleLayout, "allow_indexing", True),
|
| 50 |
+
V.graph.set_current_device(self.layout.device),
|
| 51 |
+
CppTemplateKernel(
|
| 52 |
+
kernel_name=kernel_name, num_threads=self.num_threads
|
| 53 |
+
) as kernel,
|
| 54 |
+
):
|
| 55 |
+
code = kernel.render(self, **kwargs)
|
| 56 |
+
_, call_args, _, _ = kernel.args.python_argdefs()
|
| 57 |
+
log.debug("Generated Code:\n%s", code)
|
| 58 |
+
log.debug(
|
| 59 |
+
"Args: cpp_argdefs: %s, python_argdefs: %s",
|
| 60 |
+
kernel.args.cpp_argdefs(),
|
| 61 |
+
kernel.args.python_argdefs(),
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
expected_args = list(
|
| 65 |
+
unique(input_node.get_name() for input_node in self.input_nodes)
|
| 66 |
+
)
|
| 67 |
+
if isinstance(self.output_node, Iterable):
|
| 68 |
+
expected_args.extend([node.get_name() for node in self.output_node])
|
| 69 |
+
else:
|
| 70 |
+
expected_args.extend([self.output_node.get_name()])
|
| 71 |
+
assert list(call_args)[: len(expected_args)] == expected_args, (
|
| 72 |
+
call_args,
|
| 73 |
+
expected_args,
|
| 74 |
+
)
|
| 75 |
+
extra_args = V.graph.sizevars.size_hints(
|
| 76 |
+
map(sympy.expand, call_args[len(expected_args) :])
|
| 77 |
+
)
|
| 78 |
+
# Cast the size hint from int to ctypes.c_ulonglong explicitly
|
| 79 |
+
# since in cpp kernel, we bind it to C long
|
| 80 |
+
extra_args = tuple(ctypes.c_ulonglong(x) for x in extra_args)
|
| 81 |
+
|
| 82 |
+
kernel_hash_name = f"cpp_{self.name}_{self.index}"
|
| 83 |
+
|
| 84 |
+
# Create the BenchmarkRequest for CPP
|
| 85 |
+
bmreq = CppBenchmarkRequest(
|
| 86 |
+
kernel_name=kernel_name,
|
| 87 |
+
input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes),
|
| 88 |
+
# pyrefly: ignore [bad-argument-type]
|
| 89 |
+
output_tensor_meta=TensorMeta.from_irnodes(self.output_node),
|
| 90 |
+
extra_args=extra_args,
|
| 91 |
+
source_code=code,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def make_kernel_render(
|
| 95 |
+
template_node: ir.CppTemplateBuffer,
|
| 96 |
+
flag_template_buffer_has_other_users: bool,
|
| 97 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 98 |
+
):
|
| 99 |
+
kernel = CppTemplateKernel(
|
| 100 |
+
kernel_name=str(Placeholder.KERNEL_NAME), num_threads=self.num_threads
|
| 101 |
+
)
|
| 102 |
+
render = functools.partial(
|
| 103 |
+
kernel.render,
|
| 104 |
+
self,
|
| 105 |
+
template_buffer_node=template_node,
|
| 106 |
+
flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
|
| 107 |
+
epilogue_nodes=epilogue_nodes,
|
| 108 |
+
**kwargs,
|
| 109 |
+
)
|
| 110 |
+
return kernel, render
|
| 111 |
+
|
| 112 |
+
return CppTemplateCaller(
|
| 113 |
+
kernel_hash_name,
|
| 114 |
+
self.name,
|
| 115 |
+
self.input_nodes,
|
| 116 |
+
# pyrefly: ignore [index-error]
|
| 117 |
+
self.output_node[0].get_layout()
|
| 118 |
+
if isinstance(self.output_node, Iterable)
|
| 119 |
+
else self.output_node.get_layout(),
|
| 120 |
+
make_kernel_render,
|
| 121 |
+
bmreq,
|
| 122 |
+
self,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def header(self) -> IndentedBuffer:
|
| 126 |
+
res = IndentedBuffer()
|
| 127 |
+
res.writeline("#include <torch/csrc/inductor/cpp_prefix.h>")
|
| 128 |
+
# TODO: add c10::ForcedUnroll test to test_aoti_abi_check
|
| 129 |
+
res.splice("""#include <c10/util/Unroll.h>""")
|
| 130 |
+
res.splice("""#include <torch/csrc/inductor/aoti_torch/c/shim.h>""")
|
| 131 |
+
enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [
|
| 132 |
+
"linux",
|
| 133 |
+
"win32",
|
| 134 |
+
]
|
| 135 |
+
if enable_kernel_profile:
|
| 136 |
+
res.writelines(["#include <torch/csrc/inductor/aoti_runtime/utils.h>"])
|
| 137 |
+
return res
|
| 138 |
+
|
| 139 |
+
def render(self, **kwargs) -> str:
|
| 140 |
+
raise NotImplementedError
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template_kernel.py
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import itertools
|
| 3 |
+
from collections.abc import Callable, Iterable
|
| 4 |
+
from typing import Any, Optional, Union
|
| 5 |
+
from unittest.mock import patch
|
| 6 |
+
|
| 7 |
+
import sympy
|
| 8 |
+
from sympy.parsing.sympy_parser import parse_expr
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
from torch._inductor.utils import do_bench_using_profiling
|
| 12 |
+
from torch.utils._ordered_set import OrderedSet
|
| 13 |
+
from torch.utils._sympy.symbol import SymT
|
| 14 |
+
|
| 15 |
+
from .. import config, cpp_builder, ir, lowering as L
|
| 16 |
+
from ..autotune_process import CppBenchmarkRequest
|
| 17 |
+
from ..loop_body import LoopBody
|
| 18 |
+
from ..select_algorithm import PartialRender
|
| 19 |
+
from ..utils import sympy_index_symbol, sympy_index_symbol_with_prefix
|
| 20 |
+
from ..virtualized import V
|
| 21 |
+
from .common import REMOVED
|
| 22 |
+
from .cpp import CppKernel, CppKernelProxy, KernelGroup, ParallelDepth
|
| 23 |
+
from .cpp_utils import cexpr_index, DTYPE_TO_CPP, LocalBufferContext
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def parse_expr_with_index_symbols(expr):
|
| 27 |
+
if isinstance(expr, sympy.Expr):
|
| 28 |
+
return expr
|
| 29 |
+
elif isinstance(expr, (list, tuple)):
|
| 30 |
+
return [parse_expr_with_index_symbols(e) for e in expr]
|
| 31 |
+
else:
|
| 32 |
+
expr = parse_expr(str(expr))
|
| 33 |
+
int_symbols = {sym: sympy_index_symbol(sym.name) for sym in expr.free_symbols}
|
| 34 |
+
return expr.subs(int_symbols)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def wrap_with_tensorbox(node) -> Union[ir.TensorBox, ir.ShapeAsConstantBuffer]:
|
| 38 |
+
return (
|
| 39 |
+
ir.TensorBox.create(node) if isinstance(node, ir.Buffer) else ir.TensorBox(node)
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class CppTemplateKernel(CppKernel):
|
| 44 |
+
def __init__(self, kernel_name, num_threads):
|
| 45 |
+
super().__init__(None, num_threads)
|
| 46 |
+
self.kernel_name = kernel_name
|
| 47 |
+
self.render_hooks = {}
|
| 48 |
+
self.local_buffers = {}
|
| 49 |
+
|
| 50 |
+
def render(self, template, **kwargs):
|
| 51 |
+
return PartialRender(
|
| 52 |
+
template.render(kernel=self, **kwargs), self.render_hooks
|
| 53 |
+
).finalize_all()
|
| 54 |
+
|
| 55 |
+
def def_kernel(
|
| 56 |
+
self,
|
| 57 |
+
inputs: dict[str, ir.Buffer],
|
| 58 |
+
outputs: dict[str, ir.Buffer],
|
| 59 |
+
aliases: Optional[dict[str, str]] = None,
|
| 60 |
+
function_name: str = "",
|
| 61 |
+
extra_sizevars: Optional[list[sympy.Expr]] = None,
|
| 62 |
+
placeholder: str = "<DEF_KERNEL>",
|
| 63 |
+
) -> str:
|
| 64 |
+
if len(function_name) == 0:
|
| 65 |
+
function_name = str(self.kernel_name)
|
| 66 |
+
for name, inp in inputs.items():
|
| 67 |
+
if inp is not None:
|
| 68 |
+
self.args.input_buffers[inp.get_name()] = name
|
| 69 |
+
for name, out in outputs.items():
|
| 70 |
+
self.args.output_buffers[out.get_name()] = name
|
| 71 |
+
if aliases is not None:
|
| 72 |
+
for alias, orig in aliases.items():
|
| 73 |
+
if orig in self.args.input_buffers:
|
| 74 |
+
self.args.input_buffers[alias] = self.args.input_buffers[orig]
|
| 75 |
+
if orig in self.args.output_buffers:
|
| 76 |
+
self.args.output_buffers[alias] = self.args.output_buffers[orig]
|
| 77 |
+
|
| 78 |
+
unique_sizevars = OrderedSet(
|
| 79 |
+
s
|
| 80 |
+
for input in inputs.values()
|
| 81 |
+
if input is not None
|
| 82 |
+
for sym in itertools.chain(input.get_size(), input.get_stride())
|
| 83 |
+
if isinstance(sym, sympy.Expr)
|
| 84 |
+
for s in sym.free_symbols
|
| 85 |
+
)
|
| 86 |
+
unique_sizevars.update(
|
| 87 |
+
s
|
| 88 |
+
for sym in extra_sizevars or []
|
| 89 |
+
if isinstance(sym, sympy.Expr)
|
| 90 |
+
for s in sym.free_symbols
|
| 91 |
+
)
|
| 92 |
+
unique_sizevars.update(
|
| 93 |
+
s
|
| 94 |
+
for output in outputs.values()
|
| 95 |
+
for sym in itertools.chain(output.get_size(), output.get_stride())
|
| 96 |
+
if isinstance(sym, sympy.Expr)
|
| 97 |
+
for s in sym.free_symbols
|
| 98 |
+
)
|
| 99 |
+
sizevars = sorted(unique_sizevars, key=str)
|
| 100 |
+
for sizevar in sizevars:
|
| 101 |
+
self.args.sizevars[sizevar] = f"k{sizevar}"
|
| 102 |
+
|
| 103 |
+
def hook():
|
| 104 |
+
# remove all aliases before generate function definition
|
| 105 |
+
if aliases is not None:
|
| 106 |
+
for alias in aliases:
|
| 107 |
+
if alias in self.args.input_buffers:
|
| 108 |
+
raise AssertionError(
|
| 109 |
+
f"input_buffers cannot be removed: {alias}"
|
| 110 |
+
)
|
| 111 |
+
if alias in self.args.output_buffers:
|
| 112 |
+
self.args.output_buffers[alias] = REMOVED
|
| 113 |
+
cpp_argdefs, _, _ = self.args.cpp_argdefs()
|
| 114 |
+
return f"void {function_name}({', '.join(cpp_argdefs)})"
|
| 115 |
+
|
| 116 |
+
assert placeholder not in self.render_hooks
|
| 117 |
+
self.render_hooks[placeholder] = hook
|
| 118 |
+
return placeholder
|
| 119 |
+
|
| 120 |
+
def call_kernel(self, name: str, node: ir.CppTemplateBuffer):
|
| 121 |
+
wrapper = V.graph.wrapper_code
|
| 122 |
+
_, call_args, arg_types = self.args.cpp_argdefs()
|
| 123 |
+
wrapper.generate_kernel_call(name, call_args, triton=False, arg_types=arg_types)
|
| 124 |
+
|
| 125 |
+
def dtype(self, node: ir.Buffer) -> str:
|
| 126 |
+
return DTYPE_TO_CPP[node.get_dtype()]
|
| 127 |
+
|
| 128 |
+
def acc_dtype(self, node: ir.Buffer) -> str:
|
| 129 |
+
if node.get_dtype() in [torch.float32, torch.bfloat16, torch.half]:
|
| 130 |
+
return "float"
|
| 131 |
+
else:
|
| 132 |
+
raise NotImplementedError(f"Unsupported dtype: {node.get_dtype()}")
|
| 133 |
+
|
| 134 |
+
def size(self, node: ir.Buffer, dim: int) -> str:
|
| 135 |
+
return cexpr_index(self.rename_indexing(node.get_size()[dim]))
|
| 136 |
+
|
| 137 |
+
def stride(self, node: ir.Buffer, dim: int) -> str:
|
| 138 |
+
return cexpr_index(self.rename_indexing(node.get_stride()[dim]))
|
| 139 |
+
|
| 140 |
+
def index(self, node: ir.Buffer, indices: list[Any]) -> str:
|
| 141 |
+
indexer = node.get_layout().as_fixed().make_indexer()
|
| 142 |
+
index = indexer(parse_expr_with_index_symbols(indices))
|
| 143 |
+
index = self.rename_indexing(index)
|
| 144 |
+
outer_name = node.get_name()
|
| 145 |
+
inner_name = (
|
| 146 |
+
outer_name
|
| 147 |
+
if outer_name in self.local_buffers
|
| 148 |
+
else self.args.input(node.get_name())
|
| 149 |
+
)
|
| 150 |
+
return f"{inner_name}[{cexpr_index(index)}]"
|
| 151 |
+
|
| 152 |
+
def slice_nd(self, node, ranges: list[tuple[Any, Any]]) -> ir.ReinterpretView:
|
| 153 |
+
"""
|
| 154 |
+
Slice the given node with a list of ranges (start and end) corresponding to its dims.
|
| 155 |
+
The dim is not sliced if the corresponding range is empty.
|
| 156 |
+
"""
|
| 157 |
+
assert len(ranges) == len(node.get_size()), f"{ranges=}, {node=}"
|
| 158 |
+
sliced = wrap_with_tensorbox(node)
|
| 159 |
+
for dim, _range in enumerate(ranges):
|
| 160 |
+
if len(_range) == 0:
|
| 161 |
+
continue
|
| 162 |
+
assert len(_range) == 2
|
| 163 |
+
start, end = parse_expr_with_index_symbols(_range)
|
| 164 |
+
sliced = L.slice_(sliced, dim, start, end, clamp=False)
|
| 165 |
+
assert isinstance(sliced, ir.TensorBox)
|
| 166 |
+
assert isinstance(sliced.data, ir.ReinterpretView), sliced.data
|
| 167 |
+
return sliced.data
|
| 168 |
+
|
| 169 |
+
def select(self, node, dim: int, idx: int) -> ir.ReinterpretView:
|
| 170 |
+
# We avoid using L.select here because we need clamp=False so the dim after slicing
|
| 171 |
+
# is 1 instead of a sympy expression of symbol - dim_size.
|
| 172 |
+
node = wrap_with_tensorbox(node)
|
| 173 |
+
idx = ir.View.handle_negative_index(idx, node.get_size()[dim])
|
| 174 |
+
sliced = L.squeeze(L.slice_(node, dim, idx, idx + 1, clamp=False), dim)
|
| 175 |
+
assert isinstance(sliced.data, ir.ReinterpretView), sliced.data
|
| 176 |
+
return sliced.data
|
| 177 |
+
|
| 178 |
+
def view(self, node, sizes: list[Any]) -> ir.IRNode:
|
| 179 |
+
node = wrap_with_tensorbox(node)
|
| 180 |
+
sizes = parse_expr_with_index_symbols(sizes)
|
| 181 |
+
return L.view(node, sizes).data # type: ignore[arg-type]
|
| 182 |
+
|
| 183 |
+
def permute(self, node, dims):
|
| 184 |
+
node = wrap_with_tensorbox(node)
|
| 185 |
+
permuted = L.permute(node, dims).data
|
| 186 |
+
assert isinstance(permuted, ir.ReinterpretView)
|
| 187 |
+
return permuted
|
| 188 |
+
|
| 189 |
+
def maybe_codegen_profile(self) -> str:
|
| 190 |
+
if config.cpp.enable_kernel_profile:
|
| 191 |
+
graph_id = V.graph.graph_id
|
| 192 |
+
prefix = "graph_" + str(graph_id) + "_" if graph_id is not None else ""
|
| 193 |
+
handle_str = (
|
| 194 |
+
"torch::aot_inductor::RAIIAtenRecordFunctionHandle "
|
| 195 |
+
f'record_{prefix}{self.kernel_name}_("{prefix}{self.kernel_name}", nullptr);'
|
| 196 |
+
)
|
| 197 |
+
return handle_str
|
| 198 |
+
else:
|
| 199 |
+
return ""
|
| 200 |
+
|
| 201 |
+
def unroll_pragma(self, unroll):
|
| 202 |
+
if cpp_builder.is_gcc():
|
| 203 |
+
return f"#pragma GCC unroll {unroll}"
|
| 204 |
+
else:
|
| 205 |
+
return f"#pragma unroll {unroll}"
|
| 206 |
+
|
| 207 |
+
def define_buffer(self, name, sizes: list[Any], dtype=torch.float) -> str:
|
| 208 |
+
"""Define kernel local buffer"""
|
| 209 |
+
sizes = parse_expr_with_index_symbols(sizes)
|
| 210 |
+
buf = ir.Buffer(
|
| 211 |
+
name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes)
|
| 212 |
+
)
|
| 213 |
+
self.local_buffers[name] = buf
|
| 214 |
+
ctype = f"{DTYPE_TO_CPP[dtype]}"
|
| 215 |
+
numel = f"{cexpr_index(buf.get_numel())}"
|
| 216 |
+
return f"auto _{name} = std::make_unique<{ctype}[]>({numel}); auto {name} = _{name}.get();"
|
| 217 |
+
|
| 218 |
+
def define_stack_allocated_buffer(
|
| 219 |
+
self, name, sizes: list[Any], dtype=torch.float
|
| 220 |
+
) -> str:
|
| 221 |
+
"""Define stack-allocated buffer"""
|
| 222 |
+
sizes = parse_expr_with_index_symbols(sizes)
|
| 223 |
+
buf = ir.Buffer(
|
| 224 |
+
name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes)
|
| 225 |
+
)
|
| 226 |
+
self.local_buffers[name] = buf
|
| 227 |
+
ctype = f"{DTYPE_TO_CPP[dtype]}"
|
| 228 |
+
numel = f"{cexpr_index(buf.get_numel())}"
|
| 229 |
+
return f"alignas(64) {ctype} _{name}[{numel}]; {ctype}* {name} = _{name};"
|
| 230 |
+
|
| 231 |
+
def reinit_buffer_if_null(self, name):
|
| 232 |
+
"""Reinit the previously defined local buffer if it is null"""
|
| 233 |
+
assert name in self.local_buffers
|
| 234 |
+
buf = self.local_buffers[name]
|
| 235 |
+
ctype = f"{DTYPE_TO_CPP[buf.layout.dtype]}"
|
| 236 |
+
numel = f"{cexpr_index(buf.get_numel())}"
|
| 237 |
+
return f"if (_{name} == nullptr) {{ _{name} = std::make_unique<{ctype}[]>({numel}); {name} = _{name}.get(); }}"
|
| 238 |
+
|
| 239 |
+
def release_buffer(self, name):
|
| 240 |
+
"""Codegen the code to release the ownership of a local buffer to others"""
|
| 241 |
+
assert name in self.local_buffers
|
| 242 |
+
return f"_{name}.release()"
|
| 243 |
+
|
| 244 |
+
def store_pointwise_nodes(
|
| 245 |
+
self,
|
| 246 |
+
dst: ir.Buffer,
|
| 247 |
+
nodes: list[ir.IRNode],
|
| 248 |
+
offsets: Optional[list[sympy.Expr]] = None,
|
| 249 |
+
reindexers: Optional[list[Optional[Callable[[list[Any]], list[Any]]]]] = None,
|
| 250 |
+
) -> str:
|
| 251 |
+
var_sizes = (tuple(dst.get_size()), ())
|
| 252 |
+
var_ranges = {
|
| 253 |
+
sympy_index_symbol_with_prefix(SymT.INDEX, i): sz
|
| 254 |
+
for i, sz in enumerate(var_sizes[0])
|
| 255 |
+
}
|
| 256 |
+
if not offsets:
|
| 257 |
+
offsets = [sympy.S.Zero] * len(var_sizes[0])
|
| 258 |
+
if not reindexers:
|
| 259 |
+
reindexers = [None] * len(nodes)
|
| 260 |
+
assert len(offsets) == len(var_sizes[0])
|
| 261 |
+
output_index = dst.get_layout().make_indexer()([*var_ranges.keys()])
|
| 262 |
+
kernel_group = KernelGroup()
|
| 263 |
+
kernel_group.args = self.args
|
| 264 |
+
cpp_kernel_proxy = CppKernelProxy(kernel_group)
|
| 265 |
+
bodies = []
|
| 266 |
+
var_sizes_list = []
|
| 267 |
+
for i, node in enumerate(nodes):
|
| 268 |
+
output_name = node.get_name() if i < len(nodes) - 1 else dst.get_name()
|
| 269 |
+
node = node.data if isinstance(node, ir.ComputedBuffer) else node
|
| 270 |
+
assert isinstance(node, ir.Pointwise), node
|
| 271 |
+
|
| 272 |
+
def fn(*args):
|
| 273 |
+
assert len(args) == 2
|
| 274 |
+
assert len(args[0]) == len(var_sizes[0])
|
| 275 |
+
assert len(args[1]) == 0
|
| 276 |
+
new_args = [arg + offset for arg, offset in zip(args[0], offsets)] # type: ignore[arg-type]
|
| 277 |
+
if reindexers[i] is not None:
|
| 278 |
+
new_args = reindexers[i](new_args) # type: ignore[misc]
|
| 279 |
+
V.ops.store(
|
| 280 |
+
output_name,
|
| 281 |
+
output_index,
|
| 282 |
+
node.make_loader()(new_args).value,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
body = LoopBody(
|
| 286 |
+
fn,
|
| 287 |
+
(list(var_ranges.keys()), ()),
|
| 288 |
+
var_ranges,
|
| 289 |
+
list(var_ranges.keys()),
|
| 290 |
+
tuple(),
|
| 291 |
+
)
|
| 292 |
+
bodies.append(body)
|
| 293 |
+
var_sizes_list.append(var_sizes)
|
| 294 |
+
|
| 295 |
+
cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list)
|
| 296 |
+
|
| 297 |
+
def max_parallel_depth():
|
| 298 |
+
return ParallelDepth(parallel_depth=0, start_depth=0)
|
| 299 |
+
|
| 300 |
+
# This loop is not parallelized since it is not the outermost loop.
|
| 301 |
+
with patch.object(
|
| 302 |
+
cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth
|
| 303 |
+
):
|
| 304 |
+
kernel_group.finalize_kernel(cpp_kernel_proxy, [])
|
| 305 |
+
return kernel_group.loops_code.getvalue()
|
| 306 |
+
|
| 307 |
+
def store_grouped_gemm_pointwise_nodes(
|
| 308 |
+
self,
|
| 309 |
+
dst: tuple[ir.Buffer],
|
| 310 |
+
nodes: list[ir.IRNode],
|
| 311 |
+
offsets: list[sympy.Expr],
|
| 312 |
+
reindexers: list[Optional[Callable[[list[Any]], list[Any]]]],
|
| 313 |
+
output_names: list[str],
|
| 314 |
+
) -> str:
|
| 315 |
+
ref_dst = dst[0]
|
| 316 |
+
var_sizes = (tuple(ref_dst.get_size()), ())
|
| 317 |
+
var_ranges = {
|
| 318 |
+
sympy_index_symbol_with_prefix(SymT.INDEX, i): sz
|
| 319 |
+
for i, sz in enumerate(var_sizes[0])
|
| 320 |
+
}
|
| 321 |
+
assert offsets, "offsets should be set outside"
|
| 322 |
+
assert all(len(offset) == len(var_sizes[0]) for offset in offsets)
|
| 323 |
+
output_index = ref_dst.get_layout().make_indexer()([*var_ranges.keys()])
|
| 324 |
+
kernel_group = KernelGroup()
|
| 325 |
+
kernel_group.args = self.args
|
| 326 |
+
cpp_kernel_proxy = CppKernelProxy(kernel_group)
|
| 327 |
+
bodies = []
|
| 328 |
+
var_sizes_list = []
|
| 329 |
+
for i, node in enumerate(nodes):
|
| 330 |
+
output_name = output_names[i]
|
| 331 |
+
node = node.data if isinstance(node, ir.ComputedBuffer) else node
|
| 332 |
+
assert isinstance(node, ir.Pointwise), node
|
| 333 |
+
|
| 334 |
+
def fn(*args):
|
| 335 |
+
assert len(args) == 2
|
| 336 |
+
assert len(args[0]) == len(var_sizes[0])
|
| 337 |
+
assert len(args[1]) == 0
|
| 338 |
+
new_args = [arg + offset for arg, offset in zip(args[0], offsets[i])] # type: ignore[arg-type]
|
| 339 |
+
if reindexers[i] is not None:
|
| 340 |
+
new_args = reindexers[i](new_args) # type: ignore[misc]
|
| 341 |
+
V.ops.store(
|
| 342 |
+
output_name,
|
| 343 |
+
output_index,
|
| 344 |
+
node.make_loader()(new_args).value,
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
body = LoopBody(
|
| 348 |
+
fn,
|
| 349 |
+
(list(var_ranges.keys()), ()),
|
| 350 |
+
var_ranges,
|
| 351 |
+
list(var_ranges.keys()),
|
| 352 |
+
tuple(),
|
| 353 |
+
)
|
| 354 |
+
bodies.append(body)
|
| 355 |
+
var_sizes_list.append(var_sizes)
|
| 356 |
+
|
| 357 |
+
cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list)
|
| 358 |
+
|
| 359 |
+
def max_parallel_depth():
|
| 360 |
+
return ParallelDepth(parallel_depth=0, start_depth=0)
|
| 361 |
+
|
| 362 |
+
# This loop is not parallelized since it is not the outermost loop.
|
| 363 |
+
with patch.object(
|
| 364 |
+
cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth
|
| 365 |
+
):
|
| 366 |
+
kernel_group.finalize_kernel(cpp_kernel_proxy, [])
|
| 367 |
+
return kernel_group.loops_code.getvalue()
|
| 368 |
+
|
| 369 |
+
def store_output(
|
| 370 |
+
self,
|
| 371 |
+
dst: ir.Buffer,
|
| 372 |
+
src: ir.Buffer,
|
| 373 |
+
orig_src: Optional[ir.Buffer] = None,
|
| 374 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 375 |
+
offsets: Optional[list[Any]] = None,
|
| 376 |
+
reindexers: Optional[list[Optional[Callable[[list[Any]], list[Any]]]]] = None,
|
| 377 |
+
):
|
| 378 |
+
"""
|
| 379 |
+
Store the `src` buffer to the `dst` buffer. The size of `src` and `dst` should match.
|
| 380 |
+
If `epilogue_nodes` is provided, the `src` buffer is firstly computed with the epilogues
|
| 381 |
+
before stored to `dst`. The `epilogues_nodes` are all pointwise.
|
| 382 |
+
|
| 383 |
+
Notes:
|
| 384 |
+
1. `src` and `dst` buffer could be the same buffer in which case we are doing in-place compute
|
| 385 |
+
and stores. In case `epilogue_nodes` are not provided, we do nothing.
|
| 386 |
+
2. The `epilogue_nodes`, if exist, have computations on `src` before storing to `dst` but since
|
| 387 |
+
they come form the original Inductor IR, they might need to be adjusted before working with
|
| 388 |
+
`src` and `dst` as outlined below:
|
| 389 |
+
a) `src` or `dst` buffer could be a sub-slice of the ranges the `epilogue_nodes`work on.
|
| 390 |
+
In this case, the `offsets` could be provided to adjust the indices passed to
|
| 391 |
+
`epilogue_nodes` during codegen and the data ranges are also configured according to
|
| 392 |
+
the sizes of `src` and `dst`.
|
| 393 |
+
b) `dst` might be indexed in a different way as the `epilogue_nodes`, hence a `reindexer` is
|
| 394 |
+
needed on the indices to `epilogue_nodes` to match the indexing of `dst`.
|
| 395 |
+
c) If `src` is local, we need to add a local buffer for it and localize the `orig_src` buffer
|
| 396 |
+
in `epilogue_nodes` with `src`.
|
| 397 |
+
"""
|
| 398 |
+
assert isinstance(dst, (ir.Buffer, ir.ReinterpretView))
|
| 399 |
+
assert dst.get_size() == src.get_size(), f"{dst=}, {src=}"
|
| 400 |
+
if offsets:
|
| 401 |
+
offsets = parse_expr_with_index_symbols(offsets)
|
| 402 |
+
if epilogue_nodes:
|
| 403 |
+
with LocalBufferContext(self.args) as scope:
|
| 404 |
+
assert orig_src is not None
|
| 405 |
+
if orig_src.get_name() != src.get_name():
|
| 406 |
+
scope.add_local_buffer(
|
| 407 |
+
src,
|
| 408 |
+
[
|
| 409 |
+
orig_src,
|
| 410 |
+
],
|
| 411 |
+
)
|
| 412 |
+
epilogue_nodes = scope.localize_nodes(epilogue_nodes)
|
| 413 |
+
return self.store_pointwise_nodes(
|
| 414 |
+
# pyrefly: ignore [bad-argument-type]
|
| 415 |
+
dst,
|
| 416 |
+
epilogue_nodes, # type: ignore[arg-type]
|
| 417 |
+
offsets,
|
| 418 |
+
reindexers,
|
| 419 |
+
)
|
| 420 |
+
else:
|
| 421 |
+
if dst.get_name() != src.get_name():
|
| 422 |
+
# src is local
|
| 423 |
+
copy = L.copy(dst, src).data.data
|
| 424 |
+
with LocalBufferContext(self.args) as scope:
|
| 425 |
+
scope.add_local_buffer(src)
|
| 426 |
+
# pyrefly: ignore [bad-argument-type]
|
| 427 |
+
return self.store_pointwise_nodes(dst, [copy])
|
| 428 |
+
else:
|
| 429 |
+
assert dst.layout == src.layout, f"{dst=}, {src=}"
|
| 430 |
+
return ""
|
| 431 |
+
|
| 432 |
+
def store_outputs(
|
| 433 |
+
self,
|
| 434 |
+
dst: tuple[ir.Buffer],
|
| 435 |
+
src: tuple[ir.IRNode],
|
| 436 |
+
orig_src: Optional[tuple[ir.IRNode]] = None,
|
| 437 |
+
epilogue_nodes: Optional[list[ir.IRNode]] = None,
|
| 438 |
+
offsets: Optional[list[Any]] = None,
|
| 439 |
+
reindexers: Optional[list[Optional[Callable[[list[Any]], list[Any]]]]] = None,
|
| 440 |
+
multi_output_buffers: Optional[tuple[ir.MultiOutput, ...]] = None,
|
| 441 |
+
):
|
| 442 |
+
assert isinstance(dst, Iterable)
|
| 443 |
+
assert all(_dst.get_size() == _src.get_size() for _src, _dst in zip(src, dst))
|
| 444 |
+
if offsets:
|
| 445 |
+
offsets = parse_expr_with_index_symbols(offsets)
|
| 446 |
+
gemm_num = len(src)
|
| 447 |
+
final_offsets = []
|
| 448 |
+
output_names = []
|
| 449 |
+
if epilogue_nodes:
|
| 450 |
+
if not reindexers:
|
| 451 |
+
reindexers = [None] * len(epilogue_nodes)
|
| 452 |
+
with LocalBufferContext(self.args) as scope:
|
| 453 |
+
assert orig_src is not None
|
| 454 |
+
localize_epilogue_nodes = []
|
| 455 |
+
all_read_names = []
|
| 456 |
+
for epilogue in epilogue_nodes:
|
| 457 |
+
all_read_names.extend(list(epilogue.get_read_names()))
|
| 458 |
+
localize_epilogue_nodes.extend(scope.localize_nodes(epilogue_nodes))
|
| 459 |
+
final_offsets.extend([offsets] * len(localize_epilogue_nodes))
|
| 460 |
+
output_names.extend(
|
| 461 |
+
[node.get_name() for node in localize_epilogue_nodes]
|
| 462 |
+
)
|
| 463 |
+
for gemm_idx in range(gemm_num):
|
| 464 |
+
if orig_src[gemm_idx].get_name() != src[gemm_idx].get_name():
|
| 465 |
+
if orig_src[gemm_idx].get_name() in all_read_names or (
|
| 466 |
+
multi_output_buffers
|
| 467 |
+
and multi_output_buffers[gemm_idx].get_name()
|
| 468 |
+
in all_read_names
|
| 469 |
+
):
|
| 470 |
+
# If any of the Epilogue nodes use this GEMM output, let's localize the GEMM output
|
| 471 |
+
global_buffers = [orig_src[gemm_idx]]
|
| 472 |
+
if (
|
| 473 |
+
multi_output_buffers
|
| 474 |
+
and multi_output_buffers[gemm_idx].get_name()
|
| 475 |
+
in all_read_names
|
| 476 |
+
and orig_src[gemm_idx].get_name() not in all_read_names
|
| 477 |
+
):
|
| 478 |
+
# Epilogue might directly read the MultiOutput, Locallize MultiOutput to the local Buffer
|
| 479 |
+
# if this MultiOutput has not been stored by in-template epilogue
|
| 480 |
+
# otherwise, use the cse store cache if it will be stored before used
|
| 481 |
+
global_buffers.append(multi_output_buffers[gemm_idx])
|
| 482 |
+
scope.add_local_buffer(
|
| 483 |
+
src[gemm_idx],
|
| 484 |
+
global_buffers,
|
| 485 |
+
)
|
| 486 |
+
else:
|
| 487 |
+
scope.add_local_buffer(src[gemm_idx])
|
| 488 |
+
localize_epilogue_nodes.extend(
|
| 489 |
+
[L.copy(dst[gemm_idx], src[gemm_idx]).data.data]
|
| 490 |
+
)
|
| 491 |
+
reindexers.append(None)
|
| 492 |
+
output_names.append(dst[gemm_idx].get_name())
|
| 493 |
+
final_offsets.append(
|
| 494 |
+
[sympy.S.Zero] * len(dst[gemm_idx].get_size())
|
| 495 |
+
)
|
| 496 |
+
res = self.store_grouped_gemm_pointwise_nodes(
|
| 497 |
+
dst,
|
| 498 |
+
localize_epilogue_nodes,
|
| 499 |
+
final_offsets,
|
| 500 |
+
reindexers,
|
| 501 |
+
output_names=output_names,
|
| 502 |
+
)
|
| 503 |
+
for gemm_idx in range(gemm_num):
|
| 504 |
+
if (
|
| 505 |
+
multi_output_buffers
|
| 506 |
+
and multi_output_buffers[gemm_idx].get_name() in all_read_names
|
| 507 |
+
):
|
| 508 |
+
# If the MultiOutput is used in the Epilogue, let's remove it from args
|
| 509 |
+
multi_output_name = multi_output_buffers[gemm_idx].get_name()
|
| 510 |
+
if (
|
| 511 |
+
multi_output_name in self.args.output_buffers
|
| 512 |
+
and self.args.output_buffers[multi_output_name]
|
| 513 |
+
is not REMOVED
|
| 514 |
+
):
|
| 515 |
+
self.remove_buffer(multi_output_name)
|
| 516 |
+
return res
|
| 517 |
+
else:
|
| 518 |
+
if dst[0].get_name() != src[0].get_name():
|
| 519 |
+
copy_list = []
|
| 520 |
+
with LocalBufferContext(self.args) as scope:
|
| 521 |
+
for _src, _dst in zip(src, dst):
|
| 522 |
+
copy_list.extend([L.copy(_dst, _src).data.data])
|
| 523 |
+
scope.add_local_buffer(_src)
|
| 524 |
+
output_names.append(_dst.get_name())
|
| 525 |
+
final_offsets.append([sympy.S.Zero] * len(_dst.get_size()))
|
| 526 |
+
reindexers = [None] * len(copy_list)
|
| 527 |
+
return self.store_grouped_gemm_pointwise_nodes(
|
| 528 |
+
dst,
|
| 529 |
+
nodes=copy_list,
|
| 530 |
+
offsets=final_offsets,
|
| 531 |
+
reindexers=reindexers,
|
| 532 |
+
output_names=output_names,
|
| 533 |
+
)
|
| 534 |
+
else:
|
| 535 |
+
assert all(
|
| 536 |
+
_src.get_name() == _dst.get_name() for _src, _dst in zip(src, dst)
|
| 537 |
+
)
|
| 538 |
+
assert all(
|
| 539 |
+
_src.get_layout() == _dst.get_layout()
|
| 540 |
+
for _src, _dst in zip(src, dst)
|
| 541 |
+
)
|
| 542 |
+
return ""
|
| 543 |
+
|
| 544 |
+
def check_bounds(self, expr, size, lower, upper):
|
| 545 |
+
# CppTemplateKernel does not need codegen related operations
|
| 546 |
+
return
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class CppTemplateCaller(ir.ChoiceCaller):
|
| 550 |
+
"""
|
| 551 |
+
CppTemplateCaller
|
| 552 |
+
|
| 553 |
+
This class represents a caller for CPP template kernels. It is a subclass of ir.ChoiceCaller.
|
| 554 |
+
Attributes:
|
| 555 |
+
name (str): The name of the caller.
|
| 556 |
+
category (str): The category of the caller.
|
| 557 |
+
bmreq (CppBenchmarkRequest): The benchmark request for the caller.
|
| 558 |
+
template_buffer (ir.CppTemplateBuffer): The template buffer for the caller.
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
def __init__(
|
| 562 |
+
self,
|
| 563 |
+
name: str,
|
| 564 |
+
category: str,
|
| 565 |
+
input_nodes: list[ir.Buffer],
|
| 566 |
+
layout: ir.Layout,
|
| 567 |
+
make_kernel_render: Callable[
|
| 568 |
+
[
|
| 569 |
+
ir.CppTemplateBuffer,
|
| 570 |
+
bool,
|
| 571 |
+
Optional[list[ir.IRNode]],
|
| 572 |
+
],
|
| 573 |
+
str,
|
| 574 |
+
],
|
| 575 |
+
bmreq: CppBenchmarkRequest,
|
| 576 |
+
template: "CppTemplate", # type: ignore[name-defined] # noqa: F821
|
| 577 |
+
info_kwargs: Optional[
|
| 578 |
+
dict[str, Union[ir.PrimitiveInfoType, list[ir.PrimitiveInfoType]]]
|
| 579 |
+
] = None,
|
| 580 |
+
):
|
| 581 |
+
super().__init__(name, input_nodes, layout, description="")
|
| 582 |
+
self.category = category
|
| 583 |
+
self.make_kernel_render = make_kernel_render
|
| 584 |
+
self.bmreq = bmreq
|
| 585 |
+
self.template = template
|
| 586 |
+
self.info_kwargs = info_kwargs
|
| 587 |
+
|
| 588 |
+
def precompile(self) -> None:
|
| 589 |
+
assert self.bmreq is not None
|
| 590 |
+
self.bmreq.precompile()
|
| 591 |
+
|
| 592 |
+
def benchmark(self, *args, out) -> float:
|
| 593 |
+
assert self.bmreq is not None
|
| 594 |
+
if config.profile_bandwidth_with_do_bench_using_profiling:
|
| 595 |
+
algo = self.bmreq.make_run_fn(*args, out=out)
|
| 596 |
+
return do_bench_using_profiling(algo)
|
| 597 |
+
return self.bmreq.benchmark(*args, out=out)
|
| 598 |
+
|
| 599 |
+
def hash_key(self) -> str:
|
| 600 |
+
return "-".join(
|
| 601 |
+
[
|
| 602 |
+
self.category,
|
| 603 |
+
self.bmreq.hash_key,
|
| 604 |
+
]
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
def info_dict(
|
| 608 |
+
self,
|
| 609 |
+
) -> dict[str, Union[ir.PrimitiveInfoType, list[ir.PrimitiveInfoType]]]:
|
| 610 |
+
return {"backend": "CPP", "op_type": "unknown"}
|
| 611 |
+
|
| 612 |
+
def output_node(self) -> Union[ir.TensorBox, ir.ShapeAsConstantBuffer]:
|
| 613 |
+
return ir.TensorBox.create(
|
| 614 |
+
ir.CppTemplateBuffer(
|
| 615 |
+
layout=self.layout,
|
| 616 |
+
inputs=self.input_nodes,
|
| 617 |
+
make_kernel_render=self.make_kernel_render,
|
| 618 |
+
template=self.template,
|
| 619 |
+
choice=self,
|
| 620 |
+
)
|
| 621 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_utils.py
ADDED
|
@@ -0,0 +1,787 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
import dataclasses
|
| 4 |
+
import functools
|
| 5 |
+
import math
|
| 6 |
+
import sys
|
| 7 |
+
from collections import namedtuple
|
| 8 |
+
from collections.abc import Callable, Sequence
|
| 9 |
+
from typing import Any, Optional
|
| 10 |
+
from unittest.mock import patch
|
| 11 |
+
|
| 12 |
+
import sympy
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from torch._prims_common import is_integer_dtype
|
| 16 |
+
from torch.utils._ordered_set import OrderedSet
|
| 17 |
+
from torch.utils._sympy.printers import CppPrinter as _CppPrinter
|
| 18 |
+
from torch.utils._sympy.symbol import symbol_is_type, SymT
|
| 19 |
+
from torch.utils._sympy.value_ranges import ValueRanges
|
| 20 |
+
|
| 21 |
+
from .. import ir
|
| 22 |
+
from ..dependencies import Dep
|
| 23 |
+
from ..loop_body import LoopBody
|
| 24 |
+
from ..scheduler import BaseSchedulerNode, SchedulerBuffer
|
| 25 |
+
from ..shape_propagation import BlockShapeType
|
| 26 |
+
from ..utils import IndentedBuffer, sympy_index_symbol_with_prefix, sympy_subs
|
| 27 |
+
from ..virtualized import ops, OpsValue, V
|
| 28 |
+
from .common import CSEVariable, Kernel, KernelArgs, OptimizationContext
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
DTYPE_TO_CPP = {
|
| 32 |
+
torch.float32: "float",
|
| 33 |
+
torch.float64: "double",
|
| 34 |
+
torch.float16: "at::Half",
|
| 35 |
+
torch.int64: "int64_t",
|
| 36 |
+
torch.int32: "int32_t",
|
| 37 |
+
torch.int16: "int16_t",
|
| 38 |
+
torch.int8: "int8_t",
|
| 39 |
+
torch.uint64: "uint64_t",
|
| 40 |
+
torch.uint32: "uint32_t",
|
| 41 |
+
torch.uint16: "uint16_t",
|
| 42 |
+
torch.uint8: "uint8_t",
|
| 43 |
+
torch.bool: "bool",
|
| 44 |
+
torch.bfloat16: "at::BFloat16",
|
| 45 |
+
torch.complex32: "at::complex<at::Half>",
|
| 46 |
+
torch.complex64: "at::complex<float>",
|
| 47 |
+
torch.complex128: "at::complex<double>",
|
| 48 |
+
torch.float8_e4m3fn: "at::Float8_e4m3fn",
|
| 49 |
+
torch.float8_e5m2: "at::Float8_e5m2",
|
| 50 |
+
torch.float8_e4m3fnuz: "at::Float8_e4m3fnuz",
|
| 51 |
+
torch.float8_e5m2fnuz: "at::Float8_e5m2fnuz",
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
DTYPE_TO_ATEN = {
|
| 55 |
+
torch.float32: "at::kFloat",
|
| 56 |
+
torch.float64: "at::kDouble",
|
| 57 |
+
torch.float16: "at::kHalf",
|
| 58 |
+
torch.int64: "at::kLong",
|
| 59 |
+
torch.int32: "at::kInt",
|
| 60 |
+
torch.int16: "at::kShort",
|
| 61 |
+
torch.int8: "at::kChar",
|
| 62 |
+
torch.uint64: "at::kUInt64",
|
| 63 |
+
torch.uint32: "at::kUInt32",
|
| 64 |
+
torch.uint16: "at::kUInt16",
|
| 65 |
+
torch.uint8: "at::kByte",
|
| 66 |
+
torch.uint32: "at::kUInt32",
|
| 67 |
+
torch.uint64: "at::kUInt64",
|
| 68 |
+
torch.bool: "at::kBool",
|
| 69 |
+
torch.bfloat16: "at::kBFloat16",
|
| 70 |
+
torch.complex32: "at::kComplexHalf",
|
| 71 |
+
torch.complex64: "at::kComplexFloat",
|
| 72 |
+
torch.complex128: "at::kComplexDouble",
|
| 73 |
+
torch.float8_e4m3fn: "at::kFloat8_e4m3fn",
|
| 74 |
+
torch.float8_e5m2: "at::kFloat8_e5m2",
|
| 75 |
+
torch.float8_e4m3fnuz: "at::kFloat8_e4m3fnuz",
|
| 76 |
+
torch.float8_e5m2fnuz: "at::kFloat8_e5m2fnuz",
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
DEVICE_TO_ATEN = {
|
| 80 |
+
"meta": "at::kMeta",
|
| 81 |
+
"cpu": "at::kCPU",
|
| 82 |
+
"cuda": "at::kCUDA",
|
| 83 |
+
"xpu": "at::kXPU",
|
| 84 |
+
"mps": "at::kMPS",
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
LAYOUT_TO_ATEN = {
|
| 88 |
+
torch.strided: "at::kStrided",
|
| 89 |
+
torch._mkldnn: "at::kMkldnn", # type: ignore[attr-defined]
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
# matches c10/core/DeviceType.h
|
| 93 |
+
DEVICE_TO_INT = {"cpu": 0, "cuda": 1}
|
| 94 |
+
|
| 95 |
+
_IS_WINDOWS = sys.platform == "win32"
|
| 96 |
+
|
| 97 |
+
INDEX_TYPE = "int64_t"
|
| 98 |
+
|
| 99 |
+
GemmBlocking = namedtuple("GemmBlocking", ["block_m", "block_n", "block_k"])
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_promote_dtype(args):
|
| 103 |
+
return (
|
| 104 |
+
functools.reduce(
|
| 105 |
+
torch.promote_types, # type: ignore[arg-type]
|
| 106 |
+
[n.dtype for n in args if isinstance(n, CppCSEVariable)],
|
| 107 |
+
)
|
| 108 |
+
if all(n.dtype is not None for n in args if isinstance(n, CppCSEVariable))
|
| 109 |
+
else None # not enough info to calculate the promote dtype
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def promote_args(new_args):
|
| 114 |
+
def promote_arg(arg, promote_type):
|
| 115 |
+
if (
|
| 116 |
+
isinstance(arg, CppCSEVariable)
|
| 117 |
+
and arg.dtype
|
| 118 |
+
and promote_type
|
| 119 |
+
and arg.dtype != promote_type
|
| 120 |
+
):
|
| 121 |
+
arg = ops.to_dtype(arg, promote_type)
|
| 122 |
+
arg = arg.value if isinstance(arg, OpsValue) else arg
|
| 123 |
+
arg.dtype = promote_type
|
| 124 |
+
return arg
|
| 125 |
+
|
| 126 |
+
promote_type = get_promote_dtype(new_args)
|
| 127 |
+
promote_fn = functools.partial(
|
| 128 |
+
promote_arg,
|
| 129 |
+
promote_type=promote_type,
|
| 130 |
+
)
|
| 131 |
+
if (
|
| 132 |
+
all(
|
| 133 |
+
new_arg.dtype is not None
|
| 134 |
+
for new_arg in new_args
|
| 135 |
+
if isinstance(new_arg, CppCSEVariable)
|
| 136 |
+
)
|
| 137 |
+
and promote_type
|
| 138 |
+
):
|
| 139 |
+
new_args = list(map(promote_fn, new_args))
|
| 140 |
+
return new_args
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class CppCSEVariable(CSEVariable):
|
| 144 |
+
def __init__(
|
| 145 |
+
self,
|
| 146 |
+
name,
|
| 147 |
+
bounds: ValueRanges[Any],
|
| 148 |
+
dtype: Optional[torch.dtype] = None,
|
| 149 |
+
shape: BlockShapeType = None,
|
| 150 |
+
) -> None:
|
| 151 |
+
super().__init__(name, bounds, dtype, shape=shape)
|
| 152 |
+
self.is_vec = False
|
| 153 |
+
self.dependent_itervars = OrderedSet[sympy.Symbol]()
|
| 154 |
+
|
| 155 |
+
def __repr__(self) -> str:
|
| 156 |
+
return (
|
| 157 |
+
f"CppCSEVariable(name: {self.name}, bounds: {self.bounds}, is_vec: {self.is_vec}, dtype: {self.dtype}, "
|
| 158 |
+
f"dependent_itervars: {self.dependent_itervars})"
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
def update_on_args(self, name, args, kwargs):
|
| 162 |
+
if name == "load":
|
| 163 |
+
# args[2] is index
|
| 164 |
+
self._set_dependent_itervars(args[2])
|
| 165 |
+
else:
|
| 166 |
+
# propagate relevant itervars and is_vec from args
|
| 167 |
+
self.dependent_itervars.update(
|
| 168 |
+
*[
|
| 169 |
+
arg.dependent_itervars
|
| 170 |
+
for arg in args
|
| 171 |
+
if isinstance(arg, CppCSEVariable)
|
| 172 |
+
]
|
| 173 |
+
)
|
| 174 |
+
if name == "index_expr":
|
| 175 |
+
self._set_dependent_itervars(args[0])
|
| 176 |
+
if any(arg.is_vec for arg in args if isinstance(arg, CppCSEVariable)):
|
| 177 |
+
self.is_vec = True
|
| 178 |
+
|
| 179 |
+
def _set_dependent_itervars(self, index: sympy.Expr):
|
| 180 |
+
"""
|
| 181 |
+
Set the relevant itervars for this variable based on the `index` expression.
|
| 182 |
+
This includes the itervars directly used in the `index` as well as relevant itervars
|
| 183 |
+
of other cse variables used in the `index`.
|
| 184 |
+
"""
|
| 185 |
+
for s in index.free_symbols:
|
| 186 |
+
if s in V.kernel.itervars:
|
| 187 |
+
self.dependent_itervars.add(s) # type: ignore[arg-type]
|
| 188 |
+
elif s.name in V.kernel.cse.varname_map: # type: ignore[attr-defined]
|
| 189 |
+
self.dependent_itervars.update(
|
| 190 |
+
V.kernel.cse.varname_map[s.name].dependent_itervars # type: ignore[attr-defined]
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
def depends_on(self, itervar: sympy.Symbol):
|
| 194 |
+
return itervar in self.dependent_itervars
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class CppPrinter(_CppPrinter):
|
| 198 |
+
def doprint(self, expr, *, simplify: bool = True, p=True):
|
| 199 |
+
# TODO: why are people passing strings to the printer here :think:
|
| 200 |
+
if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"):
|
| 201 |
+
expr = V.graph.sizevars.simplify(expr)
|
| 202 |
+
return super().doprint(expr)
|
| 203 |
+
|
| 204 |
+
def parenthesize(self, item: sympy.Expr, level: int, strict: bool = False) -> str:
|
| 205 |
+
if isinstance(item, sympy.Mod):
|
| 206 |
+
# use parenthesis to enforce precedence.
|
| 207 |
+
# in sympy 1.13.3, -2*Mod(x,y) becomes -2*x%y, which is wrong.
|
| 208 |
+
return f"({self._print(item)})"
|
| 209 |
+
else:
|
| 210 |
+
return super().parenthesize(item, level, strict)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# A function to print, useful for printing sympy symbols.
|
| 214 |
+
cexpr = CppPrinter().doprint
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def cexpr_index(index):
|
| 218 |
+
return f"static_cast<{INDEX_TYPE}>({cexpr(index)})"
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def value_to_cpp(value, cpp_type):
|
| 222 |
+
if value == float("-inf"):
|
| 223 |
+
return f"-std::numeric_limits<{cpp_type}>::infinity()"
|
| 224 |
+
elif value == float("inf"):
|
| 225 |
+
return f"std::numeric_limits<{cpp_type}>::infinity()"
|
| 226 |
+
elif isinstance(value, bool):
|
| 227 |
+
return f"static_cast<{cpp_type}>({str(value).lower()})"
|
| 228 |
+
elif math.isnan(value):
|
| 229 |
+
return f"std::numeric_limits<{cpp_type}>::quiet_NaN()"
|
| 230 |
+
else:
|
| 231 |
+
return f"static_cast<{cpp_type}>({repr(value)})"
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def rewrite_index_for_function(
|
| 235 |
+
localize_buffer_handler: "LocalizeBufferHandler",
|
| 236 |
+
index: sympy.Expr,
|
| 237 |
+
global_buf_name: str,
|
| 238 |
+
):
|
| 239 |
+
# Local buffer at the inner dimensions
|
| 240 |
+
snode = V.graph.scheduler.name_to_buf[global_buf_name].defining_op
|
| 241 |
+
assert snode is not None
|
| 242 |
+
local_buf = localize_buffer_handler.global_to_local[global_buf_name]
|
| 243 |
+
scheduler_nodes = snode.get_nodes()
|
| 244 |
+
_, (group, reduction_group) = max(
|
| 245 |
+
scheduler_nodes, key=lambda x: int(x.is_reduction())
|
| 246 |
+
).group
|
| 247 |
+
call_ranges = tuple(group) + tuple(reduction_group)
|
| 248 |
+
indices_to_keep = [
|
| 249 |
+
f"x{len(call_ranges) - (idx + 1)}"
|
| 250 |
+
for idx in range(len(local_buf.get_layout().size))
|
| 251 |
+
]
|
| 252 |
+
sorted_symbols = sorted(index.free_symbols, key=lambda s: s.name) # type: ignore[attr-defined]
|
| 253 |
+
replacements = {}
|
| 254 |
+
for x in sorted_symbols:
|
| 255 |
+
if x.name.startswith("x") and x.name not in indices_to_keep: # type: ignore[attr-defined]
|
| 256 |
+
# Only keep index used by local buffer
|
| 257 |
+
replacements[x] = sympy.core.numbers.Zero()
|
| 258 |
+
index = sympy_subs(index, replacements) # type: ignore[arg-type]
|
| 259 |
+
return index
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def rewrite_index_for_nodes(
|
| 263 |
+
localize_buffer_handler: "LocalizeBufferHandler",
|
| 264 |
+
index: sympy.Expr,
|
| 265 |
+
global_buf_name: str,
|
| 266 |
+
):
|
| 267 |
+
used_vars = OrderedSet(
|
| 268 |
+
s for s in index.free_symbols if symbol_is_type(s, SymT.INDEX)
|
| 269 |
+
)
|
| 270 |
+
index_vars = []
|
| 271 |
+
local_buf = localize_buffer_handler.global_to_local[global_buf_name]
|
| 272 |
+
for i in range(len(local_buf.get_size())):
|
| 273 |
+
var = sympy_index_symbol_with_prefix(SymT.INDEX, i)
|
| 274 |
+
index_vars.append(var if var in used_vars else 0)
|
| 275 |
+
index = local_buf.get_layout().make_indexer()(index_vars)
|
| 276 |
+
return index
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class LocalizeBufferHandler(V.WrapperHandler): # type: ignore[name-defined]
|
| 280 |
+
def __init__(
|
| 281 |
+
self,
|
| 282 |
+
inner,
|
| 283 |
+
global_to_local: dict[str, ir.Buffer],
|
| 284 |
+
rewrite_index: Callable[["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr],
|
| 285 |
+
) -> None:
|
| 286 |
+
super().__init__(inner)
|
| 287 |
+
self.global_to_local = global_to_local
|
| 288 |
+
self.rewrite_index = rewrite_index
|
| 289 |
+
|
| 290 |
+
def localize(self, name: str, index: sympy.Expr):
|
| 291 |
+
if self.global_to_local and name in self.global_to_local:
|
| 292 |
+
assert self.rewrite_index is not None
|
| 293 |
+
index = self.rewrite_index(self, index, name)
|
| 294 |
+
name = self.global_to_local[name].get_name()
|
| 295 |
+
return name, index
|
| 296 |
+
|
| 297 |
+
def load(self, name: str, index: sympy.Expr):
|
| 298 |
+
return self._inner.load(*self.localize(name, index))
|
| 299 |
+
|
| 300 |
+
def store(self, name, index, value, mode=None):
|
| 301 |
+
local_buffer_name, local_buffer_index = self.localize(name, index)
|
| 302 |
+
res = self._inner.store(local_buffer_name, local_buffer_index, value, mode)
|
| 303 |
+
if (
|
| 304 |
+
self.global_to_local
|
| 305 |
+
and name in self.global_to_local
|
| 306 |
+
and isinstance(V.kernel, Kernel)
|
| 307 |
+
):
|
| 308 |
+
# Remove name of local buffer from Kernel.store_buffer_names
|
| 309 |
+
# local_buffer_name is added to Kernel.store_buffer_names in Kernel.CSEProxy.store.
|
| 310 |
+
V.kernel.store_buffer_names.discard(local_buffer_name)
|
| 311 |
+
return res
|
| 312 |
+
|
| 313 |
+
def store_reduction(self, name, index, value):
|
| 314 |
+
# pyrefly: ignore [bad-argument-count]
|
| 315 |
+
return self._inner.store_reduction(*self.localize(name, index), value)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class LocalBufferContext:
|
| 319 |
+
"""
|
| 320 |
+
This class creates a context that helps to generate code involving Inductor IR with
|
| 321 |
+
function local buffers. These buffers are constructed during the codegen process and
|
| 322 |
+
are used to store intermediate results such as local accumulators. We do not want to
|
| 323 |
+
add them to `V.graph` since they are not global and we do not want to add them as
|
| 324 |
+
function arguments either. So we patch the codegen processes under this scope to support
|
| 325 |
+
these buffers without exposure to the outside world.
|
| 326 |
+
"""
|
| 327 |
+
|
| 328 |
+
def __init__(self, kernel_args: KernelArgs) -> None:
|
| 329 |
+
self.kernel_args = kernel_args
|
| 330 |
+
self.exit_stack = contextlib.ExitStack()
|
| 331 |
+
# map local buffer name to local buffer
|
| 332 |
+
self.local_buffers: dict[str, ir.Buffer] = {}
|
| 333 |
+
# map global buffer name to global buffer
|
| 334 |
+
self.global_buffers: dict[str, ir.Buffer] = {}
|
| 335 |
+
# map global buffer name to local buffer
|
| 336 |
+
self.global_to_local: dict[str, ir.Buffer] = {}
|
| 337 |
+
# record the global buffers that are removed by this LocalBufferContext
|
| 338 |
+
self.removed_buffers: OrderedSet[str] = OrderedSet()
|
| 339 |
+
|
| 340 |
+
def __enter__(self):
|
| 341 |
+
self.exit_stack.__enter__()
|
| 342 |
+
original_get_dtype = V.graph.get_dtype
|
| 343 |
+
|
| 344 |
+
def get_dtype(name):
|
| 345 |
+
if name in self.local_buffers:
|
| 346 |
+
return self.local_buffers[name].get_dtype()
|
| 347 |
+
return original_get_dtype(name)
|
| 348 |
+
|
| 349 |
+
self.exit_stack.enter_context(patch.object(V.graph, "get_dtype", get_dtype))
|
| 350 |
+
|
| 351 |
+
original_input = self.kernel_args.input
|
| 352 |
+
|
| 353 |
+
def input(name):
|
| 354 |
+
if name in self.local_buffers:
|
| 355 |
+
return name
|
| 356 |
+
return original_input(name)
|
| 357 |
+
|
| 358 |
+
self.exit_stack.enter_context(patch.object(self.kernel_args, "input", input))
|
| 359 |
+
|
| 360 |
+
original_output = self.kernel_args.output
|
| 361 |
+
|
| 362 |
+
def output(name):
|
| 363 |
+
if name in self.local_buffers:
|
| 364 |
+
return name
|
| 365 |
+
return original_output(name)
|
| 366 |
+
|
| 367 |
+
self.exit_stack.enter_context(patch.object(self.kernel_args, "output", output))
|
| 368 |
+
|
| 369 |
+
# Set current LocalBufferContext into V
|
| 370 |
+
self.exit_stack.enter_context(V.set_local_buffer_context(self))
|
| 371 |
+
|
| 372 |
+
return self
|
| 373 |
+
|
| 374 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 375 |
+
self.local_buffers.clear()
|
| 376 |
+
self.exit_stack.__exit__(exc_type, exc_val, exc_tb)
|
| 377 |
+
|
| 378 |
+
def add_local_buffer(
|
| 379 |
+
self, local_buffer: ir.Buffer, global_buffers: Optional[list[ir.Buffer]] = None
|
| 380 |
+
):
|
| 381 |
+
assert local_buffer.get_name() not in self.local_buffers
|
| 382 |
+
self.local_buffers[local_buffer.get_name()] = local_buffer
|
| 383 |
+
if global_buffers:
|
| 384 |
+
for global_buffer in global_buffers:
|
| 385 |
+
global_buffer_name = global_buffer.get_name()
|
| 386 |
+
assert (
|
| 387 |
+
global_buffer_name not in self.global_buffers
|
| 388 |
+
and global_buffer_name not in self.global_to_local
|
| 389 |
+
)
|
| 390 |
+
self.global_buffers[global_buffer_name] = global_buffer
|
| 391 |
+
self.global_to_local[global_buffer_name] = local_buffer
|
| 392 |
+
if global_buffer_name not in V.graph.removed_buffers:
|
| 393 |
+
# Record the global buffers that are removed by this LocalBufferContext
|
| 394 |
+
# since which may need to restore. Refer to issue:
|
| 395 |
+
# https://github.com/pytorch/pytorch/issues/144186
|
| 396 |
+
self.removed_buffers.add(global_buffer_name)
|
| 397 |
+
V.graph.removed_buffers.add(global_buffer_name)
|
| 398 |
+
|
| 399 |
+
def localize_function(
|
| 400 |
+
self,
|
| 401 |
+
fn: Callable[..., Any],
|
| 402 |
+
rewrite_index: Callable[
|
| 403 |
+
["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr
|
| 404 |
+
] = rewrite_index_for_function,
|
| 405 |
+
):
|
| 406 |
+
def inner(*args, **kwargs):
|
| 407 |
+
with V.set_ops_handler(
|
| 408 |
+
LocalizeBufferHandler(
|
| 409 |
+
V.get_ops_handler(),
|
| 410 |
+
global_to_local=self.global_to_local,
|
| 411 |
+
rewrite_index=rewrite_index,
|
| 412 |
+
)
|
| 413 |
+
):
|
| 414 |
+
return fn(*args, **kwargs)
|
| 415 |
+
|
| 416 |
+
return inner
|
| 417 |
+
|
| 418 |
+
def localize_nodes(
|
| 419 |
+
self,
|
| 420 |
+
nodes: list[ir.IRNode],
|
| 421 |
+
rewrite_index: Callable[
|
| 422 |
+
["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr
|
| 423 |
+
] = rewrite_index_for_nodes,
|
| 424 |
+
) -> list[ir.IRNode]:
|
| 425 |
+
"""
|
| 426 |
+
Given `local_buf` and `global_buf` registered in current `LocalBufferContext`
|
| 427 |
+
though the method of `add_local_buffer`, localizes the `global_buf` to `local_buf`
|
| 428 |
+
for the given `nodes` and returns a new list of IR nodes that work on `local_buf`
|
| 429 |
+
instead of `global_buf`, i.e., all the loads and stores are redirected to
|
| 430 |
+
`local_buf`. This helps the fused loops to work on smaller-sized local buffers
|
| 431 |
+
for better data locality.
|
| 432 |
+
|
| 433 |
+
The data access of `local_buf` is assumed to be contiguous with the
|
| 434 |
+
same order as the `global_buf`.
|
| 435 |
+
"""
|
| 436 |
+
assert len(nodes) > 0
|
| 437 |
+
|
| 438 |
+
def wrap_inner_fn_for_node(node: ir.IRNode):
|
| 439 |
+
loops = node.data if isinstance(node, ir.ComputedBuffer) else node
|
| 440 |
+
assert isinstance(loops, ir.Loops)
|
| 441 |
+
new_inner_fn = self.localize_function(
|
| 442 |
+
loops.inner_fn,
|
| 443 |
+
rewrite_index,
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
new_loops = dataclasses.replace(loops, inner_fn=new_inner_fn)
|
| 447 |
+
if isinstance(node, ir.ComputedBuffer):
|
| 448 |
+
new_node = ir.ComputedBuffer(
|
| 449 |
+
name=node.get_name(), layout=node.get_layout(), data=new_loops
|
| 450 |
+
)
|
| 451 |
+
else:
|
| 452 |
+
new_node = new_loops # type: ignore[assignment]
|
| 453 |
+
|
| 454 |
+
return new_node
|
| 455 |
+
|
| 456 |
+
return [wrap_inner_fn_for_node(node) for node in nodes]
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def unify_mask_base_type(
|
| 460 |
+
buffer: IndentedBuffer,
|
| 461 |
+
vars: tuple[CSEVariable, ...],
|
| 462 |
+
dtype=torch.float,
|
| 463 |
+
):
|
| 464 |
+
"""
|
| 465 |
+
Given list of cse variables,
|
| 466 |
+
Cast each to new mask base dtype and return casted cse variable.
|
| 467 |
+
"""
|
| 468 |
+
new_vars = (
|
| 469 |
+
V.kernel.cse.generate(
|
| 470 |
+
buffer,
|
| 471 |
+
f"{V.kernel._get_mask_cast(var, dtype)}",
|
| 472 |
+
)
|
| 473 |
+
for var in vars
|
| 474 |
+
)
|
| 475 |
+
return new_vars
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def may_unify_binary_op_mask_type(a, b):
|
| 479 |
+
"""
|
| 480 |
+
Given two cse variables, when dtype is bool, unify them to the same mask dtype and return casted cse variable.
|
| 481 |
+
"""
|
| 482 |
+
if a.dtype == torch.bool:
|
| 483 |
+
assert b.dtype == torch.bool
|
| 484 |
+
mask_dtype = torch.int32
|
| 485 |
+
return unify_mask_base_type(V.kernel.compute, (a, b), mask_dtype)
|
| 486 |
+
return a, b
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def codegen_rand(offset, code, rand_function, dst_dtype=torch.float32):
|
| 490 |
+
assert is_integer_dtype(offset.dtype)
|
| 491 |
+
code.writeline("[&]()")
|
| 492 |
+
with code.indent():
|
| 493 |
+
code.writeline(
|
| 494 |
+
f"{DTYPE_TO_CPP[offset.dtype]} offset[{V.kernel.tiling_factor}];"
|
| 495 |
+
)
|
| 496 |
+
code.writeline(f"{DTYPE_TO_CPP[dst_dtype]} result[{V.kernel.tiling_factor}];")
|
| 497 |
+
code.writeline(f"{offset}.store(offset);")
|
| 498 |
+
code.writeline(
|
| 499 |
+
f"for( {DTYPE_TO_CPP[offset.dtype]} offset_idx = 0; offset_idx < {V.kernel.tiling_factor}; offset_idx++ )"
|
| 500 |
+
)
|
| 501 |
+
with code.indent():
|
| 502 |
+
code.writeline(rand_function)
|
| 503 |
+
num_vectors = V.kernel._get_num_vectors(dtype=dst_dtype)
|
| 504 |
+
if num_vectors == 1:
|
| 505 |
+
code.writeline(
|
| 506 |
+
f"return at::vec::Vectorized<{DTYPE_TO_CPP[dst_dtype]}>::loadu(result);"
|
| 507 |
+
)
|
| 508 |
+
else:
|
| 509 |
+
code.writeline(
|
| 510 |
+
f"return at::vec::VectorizedN<{DTYPE_TO_CPP[dst_dtype]}, {num_vectors}>::loadu(result);"
|
| 511 |
+
)
|
| 512 |
+
code.writeline("()")
|
| 513 |
+
return code
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def get_gemm_template_output_and_compute_dtype(input_dtype):
|
| 517 |
+
if input_dtype in [torch.uint8, torch.int8]:
|
| 518 |
+
return (torch.int32, torch.int32)
|
| 519 |
+
else:
|
| 520 |
+
return (torch.float32, torch.float32)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def create_epilogue_with_attr(input_buffer, attr, **kwargs):
|
| 524 |
+
input_loader = input_buffer.make_loader()
|
| 525 |
+
dtype = input_buffer.get_dtype()
|
| 526 |
+
if attr == "relu":
|
| 527 |
+
|
| 528 |
+
def inner_fn(index):
|
| 529 |
+
input = input_loader(index)
|
| 530 |
+
zero = ops.constant(0, dtype)
|
| 531 |
+
return ops.maximum(input, zero)
|
| 532 |
+
|
| 533 |
+
elif attr == "gelu":
|
| 534 |
+
assert "algorithm" in kwargs
|
| 535 |
+
if kwargs["algorithm"] == "none":
|
| 536 |
+
|
| 537 |
+
def inner_fn(index):
|
| 538 |
+
input = input_loader(index)
|
| 539 |
+
if dtype != torch.float:
|
| 540 |
+
input = ops.to_dtype(input, torch.float)
|
| 541 |
+
half = ops.constant(0.5, torch.float)
|
| 542 |
+
one = ops.constant(1.0, torch.float)
|
| 543 |
+
const = ops.constant(0.7071067811865476, torch.float)
|
| 544 |
+
result = input * half * (ops.erf(input * const) + one)
|
| 545 |
+
if dtype != torch.float:
|
| 546 |
+
result = ops.to_dtype(result, dtype)
|
| 547 |
+
return result
|
| 548 |
+
|
| 549 |
+
else:
|
| 550 |
+
assert kwargs["algorithm"] == "tanh"
|
| 551 |
+
|
| 552 |
+
def inner_fn(index):
|
| 553 |
+
input = input_loader(index)
|
| 554 |
+
if dtype != torch.float:
|
| 555 |
+
input = ops.to_dtype(input, torch.float)
|
| 556 |
+
half = ops.constant(0.5, torch.float)
|
| 557 |
+
one = ops.constant(1.0, torch.float)
|
| 558 |
+
const1 = ops.constant(0.7978845608028654, torch.float)
|
| 559 |
+
const2 = ops.constant(0.044715, torch.float)
|
| 560 |
+
result = (
|
| 561 |
+
half
|
| 562 |
+
* input
|
| 563 |
+
* (
|
| 564 |
+
one
|
| 565 |
+
+ ops.tanh(const1 * (input + const2 * input * input * input))
|
| 566 |
+
)
|
| 567 |
+
)
|
| 568 |
+
if dtype != torch.float:
|
| 569 |
+
result = ops.to_dtype(result, dtype)
|
| 570 |
+
return result
|
| 571 |
+
|
| 572 |
+
elif attr == "swish":
|
| 573 |
+
|
| 574 |
+
def inner_fn(index):
|
| 575 |
+
input = input_loader(index)
|
| 576 |
+
result = input * ops.sigmoid(input)
|
| 577 |
+
return result
|
| 578 |
+
|
| 579 |
+
elif attr == "sigmoid":
|
| 580 |
+
|
| 581 |
+
def inner_fn(index):
|
| 582 |
+
return ops.sigmoid(input_loader(index))
|
| 583 |
+
|
| 584 |
+
elif attr == "tanh":
|
| 585 |
+
|
| 586 |
+
def inner_fn(index):
|
| 587 |
+
return ops.tanh(input_loader(index))
|
| 588 |
+
|
| 589 |
+
elif attr == "hardswish" or attr == "hardsigmoid":
|
| 590 |
+
|
| 591 |
+
def hardsigmoid_float(input):
|
| 592 |
+
zero = ops.constant(0, torch.float)
|
| 593 |
+
six = ops.constant(6, torch.float)
|
| 594 |
+
three = ops.constant(3, torch.float)
|
| 595 |
+
one_over_six = ops.constant(0.16666666666666666, torch.float)
|
| 596 |
+
max = ops.maximum(input + three, zero)
|
| 597 |
+
min = ops.minimum(max, six)
|
| 598 |
+
return min * one_over_six
|
| 599 |
+
|
| 600 |
+
def inner_fn(index):
|
| 601 |
+
input = input_loader(index)
|
| 602 |
+
if dtype != torch.float:
|
| 603 |
+
input = ops.to_dtype(input, torch.float)
|
| 604 |
+
result = hardsigmoid_float(input)
|
| 605 |
+
if attr == "hardswish":
|
| 606 |
+
result = input * result
|
| 607 |
+
if dtype != torch.float:
|
| 608 |
+
result = ops.to_dtype(result, dtype)
|
| 609 |
+
return result
|
| 610 |
+
|
| 611 |
+
elif attr == "leaky_relu":
|
| 612 |
+
assert "scalars" in kwargs
|
| 613 |
+
assert len(kwargs["scalars"]) == 1
|
| 614 |
+
negative_slope = kwargs["scalars"][0]
|
| 615 |
+
|
| 616 |
+
def inner_fn(index):
|
| 617 |
+
input = input_loader(index)
|
| 618 |
+
if dtype != torch.float:
|
| 619 |
+
input = ops.to_dtype(input, torch.float)
|
| 620 |
+
zero = ops.constant(0, torch.float)
|
| 621 |
+
result = ops.where(
|
| 622 |
+
input > zero, input, input * ops.constant(negative_slope, torch.float)
|
| 623 |
+
)
|
| 624 |
+
if dtype != torch.float:
|
| 625 |
+
result = ops.to_dtype(result, dtype)
|
| 626 |
+
return result
|
| 627 |
+
|
| 628 |
+
elif attr == "hardtanh":
|
| 629 |
+
assert "scalars" in kwargs
|
| 630 |
+
assert len(kwargs["scalars"]) == 2
|
| 631 |
+
min_value = kwargs["scalars"][0]
|
| 632 |
+
max_value = kwargs["scalars"][1]
|
| 633 |
+
|
| 634 |
+
def inner_fn(index):
|
| 635 |
+
input = input_loader(index)
|
| 636 |
+
if dtype != torch.float:
|
| 637 |
+
input = ops.to_dtype(input, torch.float)
|
| 638 |
+
result = ops.minimum(
|
| 639 |
+
ops.maximum(input, ops.constant(min_value, torch.float)),
|
| 640 |
+
ops.constant(max_value, torch.float),
|
| 641 |
+
)
|
| 642 |
+
if dtype != torch.float:
|
| 643 |
+
result = ops.to_dtype(result, dtype)
|
| 644 |
+
return result
|
| 645 |
+
|
| 646 |
+
elif attr in ["add", "sub", "mul"]:
|
| 647 |
+
assert "other" in kwargs
|
| 648 |
+
other = kwargs["other"]
|
| 649 |
+
num_input_dims = len(input_buffer.get_size())
|
| 650 |
+
num_other_dims = len(other.get_size())
|
| 651 |
+
dims_diff = num_input_dims - num_other_dims
|
| 652 |
+
other_loader = other.make_loader()
|
| 653 |
+
|
| 654 |
+
def inner_fn(index):
|
| 655 |
+
op = getattr(ops, attr)
|
| 656 |
+
if dims_diff != 0:
|
| 657 |
+
return op(input_loader(index), other_loader(index[dims_diff:]))
|
| 658 |
+
else:
|
| 659 |
+
return op(input_loader(index), other_loader(index))
|
| 660 |
+
|
| 661 |
+
elif attr == "bias_add":
|
| 662 |
+
assert "other" in kwargs
|
| 663 |
+
assert "beta" in kwargs
|
| 664 |
+
assert "dtype" in kwargs
|
| 665 |
+
beta = kwargs["beta"]
|
| 666 |
+
other = kwargs["other"]
|
| 667 |
+
dtype = kwargs["dtype"]
|
| 668 |
+
bias_loader = other.make_loader()
|
| 669 |
+
|
| 670 |
+
def inner_fn(index):
|
| 671 |
+
bias = bias_loader(index)
|
| 672 |
+
input = input_loader(index)
|
| 673 |
+
if beta != 1:
|
| 674 |
+
result = ops.constant(beta, torch.float) * bias + input
|
| 675 |
+
else:
|
| 676 |
+
result = bias + input
|
| 677 |
+
return result
|
| 678 |
+
|
| 679 |
+
else:
|
| 680 |
+
raise ValueError(f"Unsupported epilogue attribute: {attr}")
|
| 681 |
+
return ir.Pointwise(
|
| 682 |
+
device=input_buffer.get_device(),
|
| 683 |
+
dtype=dtype,
|
| 684 |
+
inner_fn=inner_fn,
|
| 685 |
+
ranges=input_buffer.get_size(),
|
| 686 |
+
)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def _get_loop_body(fn_list):
|
| 690 |
+
if all(isinstance(fn, LoopBody) for fn in fn_list):
|
| 691 |
+
loop_bodies = fn_list
|
| 692 |
+
else:
|
| 693 |
+
if hasattr(fn_list[0], "original_fn"):
|
| 694 |
+
# For the case of local buffer, we wrap the fn with localize_function
|
| 695 |
+
assert all(hasattr(fn, "original_fn") for fn in fn_list)
|
| 696 |
+
assert all(
|
| 697 |
+
isinstance(fn.original_fn.args[0]._body, LoopBody) for fn in fn_list
|
| 698 |
+
)
|
| 699 |
+
loop_bodies = [fn.original_fn.args[0]._body for fn in fn_list]
|
| 700 |
+
else:
|
| 701 |
+
assert all(isinstance(fn, functools.partial) for fn in fn_list)
|
| 702 |
+
assert all(isinstance(fn.args[0]._body, LoopBody) for fn in fn_list)
|
| 703 |
+
loop_bodies = [fn.args[0]._body for fn in fn_list]
|
| 704 |
+
assert loop_bodies is not None
|
| 705 |
+
return loop_bodies
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def _get_dtype_from_loopbodies(loop_bodies):
|
| 709 |
+
dtypes = OrderedSet[torch.dtype]()
|
| 710 |
+
for loop_body in loop_bodies:
|
| 711 |
+
graphs = [loop_body.root_block.graph] + [
|
| 712 |
+
body.graph for body in list(loop_body.subblocks.values())
|
| 713 |
+
]
|
| 714 |
+
for graph in graphs:
|
| 715 |
+
for node in graph.nodes:
|
| 716 |
+
if node.op != "call_method":
|
| 717 |
+
continue
|
| 718 |
+
dtypes.add(node.meta[OptimizationContext.key].dtype)
|
| 719 |
+
return dtypes
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
def template_fusion_with_epilogues_supported(
|
| 723 |
+
template: BaseSchedulerNode, epilogues: list[BaseSchedulerNode]
|
| 724 |
+
) -> tuple[bool, bool]:
|
| 725 |
+
def _get_indexes_of_template_buf_read(
|
| 726 |
+
epilogue_node: ir.Operation, template_buf_names: list[str]
|
| 727 |
+
) -> list[sympy.Expr]:
|
| 728 |
+
return [
|
| 729 |
+
read.index
|
| 730 |
+
for read in epilogue_node.get_reads()
|
| 731 |
+
if read.name in template_buf_names
|
| 732 |
+
]
|
| 733 |
+
|
| 734 |
+
def _check_supported_and_same_indexes(
|
| 735 |
+
index_of_template_buf_read: Sequence[sympy.Expr],
|
| 736 |
+
epilogue_writes: OrderedSet[Dep],
|
| 737 |
+
) -> tuple[bool, bool]:
|
| 738 |
+
num_indexes = len(OrderedSet(index_of_template_buf_read))
|
| 739 |
+
|
| 740 |
+
if num_indexes > 1:
|
| 741 |
+
same_index = False
|
| 742 |
+
supported = False # Different read indexes not supported
|
| 743 |
+
elif num_indexes == 0:
|
| 744 |
+
same_index = True
|
| 745 |
+
supported = True # No reads, automatically supported
|
| 746 |
+
elif num_indexes == 1:
|
| 747 |
+
iotbr = index_of_template_buf_read[0]
|
| 748 |
+
same_index = all(write.index == iotbr for write in epilogue_writes)
|
| 749 |
+
# TODO: Add support of fusion when the read of template buffer and the write of epilogue output
|
| 750 |
+
# in the epilogue node don't have the same index and change supported to True
|
| 751 |
+
supported = same_index
|
| 752 |
+
else:
|
| 753 |
+
raise AssertionError("Should not reach here")
|
| 754 |
+
|
| 755 |
+
return supported, same_index
|
| 756 |
+
|
| 757 |
+
def _template_fusion_supported(
|
| 758 |
+
template_outputs: Sequence[SchedulerBuffer], epilogue_nodes: list[ir.Operation]
|
| 759 |
+
) -> tuple[bool, bool]:
|
| 760 |
+
template_buf_names = [x.get_name() for x in template_outputs]
|
| 761 |
+
indexes_of_template_buf_reads = [
|
| 762 |
+
_get_indexes_of_template_buf_read(epilogue_node, template_buf_names)
|
| 763 |
+
for epilogue_node in epilogue_nodes
|
| 764 |
+
]
|
| 765 |
+
epilogue_nodes_writes = [
|
| 766 |
+
epilogue_node.get_read_writes().writes for epilogue_node in epilogue_nodes
|
| 767 |
+
]
|
| 768 |
+
|
| 769 |
+
results = [
|
| 770 |
+
_check_supported_and_same_indexes(reads, writes)
|
| 771 |
+
for reads, writes in zip(
|
| 772 |
+
indexes_of_template_buf_reads, epilogue_nodes_writes
|
| 773 |
+
)
|
| 774 |
+
]
|
| 775 |
+
supported, same_indexes = zip(*results)
|
| 776 |
+
return all(supported), all(same_indexes)
|
| 777 |
+
|
| 778 |
+
assert template.is_template()
|
| 779 |
+
template_outputs = template.get_outputs()
|
| 780 |
+
|
| 781 |
+
epilogue_nodes = [
|
| 782 |
+
n.node
|
| 783 |
+
for epilogue in epilogues
|
| 784 |
+
for n in epilogue.get_nodes()
|
| 785 |
+
if n.node is not None
|
| 786 |
+
]
|
| 787 |
+
return _template_fusion_supported(template_outputs, epilogue_nodes)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.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/codegen/cpp_wrapper_cpu_array_ref.py
ADDED
|
@@ -0,0 +1,897 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from collections.abc import Callable, Sequence
|
| 3 |
+
from typing import Any, Optional, Union
|
| 4 |
+
|
| 5 |
+
import sympy
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
|
| 9 |
+
import torch._ops
|
| 10 |
+
|
| 11 |
+
from .. import config, ir
|
| 12 |
+
from ..utils import sympy_product
|
| 13 |
+
from ..virtualized import V
|
| 14 |
+
from .cpp_utils import DTYPE_TO_CPP
|
| 15 |
+
from .cpp_wrapper_cpu import CppWrapperCpu
|
| 16 |
+
from .wrapper import (
|
| 17 |
+
BufferLike,
|
| 18 |
+
EnterSubgraphLine,
|
| 19 |
+
ExitSubgraphLine,
|
| 20 |
+
MemoryPlanningLine,
|
| 21 |
+
MemoryPlanningState,
|
| 22 |
+
PythonWrapperCodegen,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
BufferName = str
|
| 27 |
+
|
| 28 |
+
# Default thread stack sizes vary by platform:
|
| 29 |
+
# - Linux: 8 MB
|
| 30 |
+
# - macOS: 512 KB
|
| 31 |
+
# - Windows: 1 MB
|
| 32 |
+
# Just pick something comfortably smaller than the smallest for now.
|
| 33 |
+
MAX_STACK_ALLOCATION_SIZE = 1024 * 100
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CppWrapperCpuArrayRef(CppWrapperCpu):
|
| 37 |
+
"""
|
| 38 |
+
Generates cpp wrapper for running on CPU and calls cpp kernels
|
| 39 |
+
|
| 40 |
+
This class is forked from CppWrapperCpu, with a difference that tensors may be
|
| 41 |
+
represented as ArrayRef, see torch/csrc/inductor/aoti_runtime/arrayref_tensor.h
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self):
|
| 45 |
+
super().__init__()
|
| 46 |
+
assert self.device == "cpu", "ArrayRefTensor only supported on CPU!"
|
| 47 |
+
self.allow_stack_allocation = config.aot_inductor.allow_stack_allocation
|
| 48 |
+
self.stack_allocated_buffers: dict[BufferName, BufferLike] = {}
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def create(
|
| 52 |
+
is_subgraph: bool,
|
| 53 |
+
subgraph_name: Optional[str],
|
| 54 |
+
parent_wrapper: Optional[PythonWrapperCodegen],
|
| 55 |
+
partition_signatures: Optional[ir.GraphPartitionSignature] = None,
|
| 56 |
+
):
|
| 57 |
+
# TODO - support subgraph codegen by lifting functions. Check the
|
| 58 |
+
# comment at CppWrapperCpu `codegen_subgraph` function.
|
| 59 |
+
return CppWrapperCpuArrayRef()
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def get_input_cpp_type(input):
|
| 63 |
+
assert config.aot_inductor.use_minimal_arrayref_interface
|
| 64 |
+
|
| 65 |
+
if isinstance(input, sympy.Expr):
|
| 66 |
+
from ..graph import may_get_constant_buffer_dtype
|
| 67 |
+
|
| 68 |
+
dtype = may_get_constant_buffer_dtype(input)
|
| 69 |
+
assert dtype is not None, f"Failed to get the dtype of sympy.Expr: {input}"
|
| 70 |
+
return DTYPE_TO_CPP[dtype]
|
| 71 |
+
return f"ArrayRefTensor<{DTYPE_TO_CPP[input.get_dtype()]}>"
|
| 72 |
+
|
| 73 |
+
@staticmethod
|
| 74 |
+
def get_device_include_path(device: str) -> str:
|
| 75 |
+
assert device == "cpu", "ArrayRef only supported on CPU!"
|
| 76 |
+
if V.graph.aot_mode:
|
| 77 |
+
return "#include <torch/csrc/inductor/aoti_include/array_ref.h>"
|
| 78 |
+
return "#include <torch/csrc/inductor/cpp_wrapper/array_ref.h>"
|
| 79 |
+
|
| 80 |
+
def codegen_input_numel_asserts(self):
|
| 81 |
+
for name, buf in V.graph.graph_inputs.items():
|
| 82 |
+
if isinstance(buf, sympy.Expr):
|
| 83 |
+
continue
|
| 84 |
+
|
| 85 |
+
# comparing strides for 0 size tensor is tricky. Ignore them for now.
|
| 86 |
+
if sympy_product(buf.get_size()) == 0:
|
| 87 |
+
continue
|
| 88 |
+
numel = buf.get_numel()
|
| 89 |
+
self.prefix.writeline(f"assert_numel({name}, {numel});")
|
| 90 |
+
|
| 91 |
+
def generate_extern_kernel_alloc(self, *args, **kwargs):
|
| 92 |
+
# Disable stack allocation for extern kernels.
|
| 93 |
+
self.allow_stack_allocation = False
|
| 94 |
+
super().generate_extern_kernel_alloc(*args, **kwargs)
|
| 95 |
+
|
| 96 |
+
def generate_extern_kernel_out(self, *args, **kwargs):
|
| 97 |
+
# Disable stack allocation for extern kernels.
|
| 98 |
+
self.allow_stack_allocation = False
|
| 99 |
+
super().generate_extern_kernel_out(*args, **kwargs)
|
| 100 |
+
|
| 101 |
+
def generate_fallback_kernel(self, node: ir.FallbackKernel) -> None:
|
| 102 |
+
# Disable stack allocation for extern kernels.
|
| 103 |
+
self.allow_stack_allocation = False
|
| 104 |
+
super().generate_fallback_kernel(node)
|
| 105 |
+
|
| 106 |
+
def _generate_kernel_call_helper(
|
| 107 |
+
self,
|
| 108 |
+
kernel_name: str,
|
| 109 |
+
call_args,
|
| 110 |
+
*,
|
| 111 |
+
device=None,
|
| 112 |
+
triton=True,
|
| 113 |
+
arg_types=None,
|
| 114 |
+
raw_keys=None,
|
| 115 |
+
raw_args=None,
|
| 116 |
+
triton_meta=None,
|
| 117 |
+
graph_name="",
|
| 118 |
+
original_fxnode_name=None,
|
| 119 |
+
):
|
| 120 |
+
"""
|
| 121 |
+
Generates kernel call code.
|
| 122 |
+
|
| 123 |
+
triton: Defines whether the GPU backend uses Triton for codegen.
|
| 124 |
+
Otherwise it uses the CUDA language for codegen.
|
| 125 |
+
Only valid when cuda == True.
|
| 126 |
+
"""
|
| 127 |
+
assert not triton, (
|
| 128 |
+
"CppWrapperCpuArrayRef.generate_kernel_call does not support GPU"
|
| 129 |
+
)
|
| 130 |
+
assert arg_types is not None and len(call_args) == len(arg_types), (
|
| 131 |
+
"Mismatch call_args and arg_types in generate_kernel_call"
|
| 132 |
+
)
|
| 133 |
+
new_args = []
|
| 134 |
+
for idx, arg in enumerate(call_args):
|
| 135 |
+
if "*" in arg_types[idx]:
|
| 136 |
+
var_name = f"var_{next(self.arg_var_id)}"
|
| 137 |
+
self.writeline(f"auto* {var_name} = get_data_ptr_wrapper({arg});")
|
| 138 |
+
new_args.append(f"({arg_types[idx]})({var_name})")
|
| 139 |
+
else:
|
| 140 |
+
# arg is a scalar
|
| 141 |
+
new_args.append(arg)
|
| 142 |
+
# debug printer related logic for cpp kernel type.
|
| 143 |
+
debug_printer_manager = V.graph.wrapper_code.debug_printer
|
| 144 |
+
debug_printer_manager.set_printer_args(
|
| 145 |
+
call_args,
|
| 146 |
+
kernel_name,
|
| 147 |
+
None,
|
| 148 |
+
None,
|
| 149 |
+
"cpp",
|
| 150 |
+
)
|
| 151 |
+
with debug_printer_manager:
|
| 152 |
+
self.writeline(self.wrap_kernel_call(kernel_name, new_args))
|
| 153 |
+
|
| 154 |
+
def write_wrapper_decl(self):
|
| 155 |
+
inputs_len = len(V.graph.graph_inputs.keys())
|
| 156 |
+
if V.graph.aot_mode:
|
| 157 |
+
if (
|
| 158 |
+
config.aot_inductor.use_minimal_arrayref_interface
|
| 159 |
+
and not V.graph.is_const_graph
|
| 160 |
+
):
|
| 161 |
+
input_cpp_types = ", ".join(
|
| 162 |
+
f"{CppWrapperCpuArrayRef.get_input_cpp_type(x)}"
|
| 163 |
+
for x in V.graph.graph_inputs.values()
|
| 164 |
+
)
|
| 165 |
+
output_arrayref_types = ", ".join(
|
| 166 |
+
f"ArrayRefTensor<{DTYPE_TO_CPP[x.get_dtype()]}>"
|
| 167 |
+
for x in V.graph.graph_outputs
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
self.prefix.splice(
|
| 171 |
+
f"""
|
| 172 |
+
using AOTInductorModelInputs = std::tuple<{input_cpp_types}>;
|
| 173 |
+
using AOTInductorModelOutputs = std::tuple<{output_arrayref_types}>;
|
| 174 |
+
"""
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
if V.graph.const_module:
|
| 178 |
+
self.header.splice(V.graph.const_module.wrapper_code.header)
|
| 179 |
+
|
| 180 |
+
assert V.graph.const_wrapper_code is not None
|
| 181 |
+
self.prefix.splice(V.graph.const_wrapper_code)
|
| 182 |
+
|
| 183 |
+
assert V.graph.const_kernel_code is not None
|
| 184 |
+
self.kernel_declarations.splice(V.graph.const_kernel_code)
|
| 185 |
+
|
| 186 |
+
if V.graph.is_const_graph:
|
| 187 |
+
self.prefix.splice(
|
| 188 |
+
"""
|
| 189 |
+
void AOTInductorModel::_const_run_impl(
|
| 190 |
+
std::vector<AtenTensorHandle>& output_handles,
|
| 191 |
+
DeviceStreamType stream,
|
| 192 |
+
AOTIProxyExecutorHandle proxy_executor
|
| 193 |
+
) {
|
| 194 |
+
"""
|
| 195 |
+
)
|
| 196 |
+
else:
|
| 197 |
+
if not config.aot_inductor.use_runtime_constant_folding:
|
| 198 |
+
# If we do not split the constant graph, we'll just create
|
| 199 |
+
# an empty implementation when wrapping the main module.
|
| 200 |
+
self.prefix.splice(
|
| 201 |
+
"""
|
| 202 |
+
void AOTInductorModel::_const_run_impl(
|
| 203 |
+
std::vector<AtenTensorHandle>& output_handles,
|
| 204 |
+
DeviceStreamType stream,
|
| 205 |
+
AOTIProxyExecutorHandle proxy_executor
|
| 206 |
+
) {}
|
| 207 |
+
|
| 208 |
+
"""
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
run_impl_proto = """
|
| 212 |
+
void AOTInductorModel::run_impl(
|
| 213 |
+
AtenTensorHandle*
|
| 214 |
+
input_handles, // array of input AtenTensorHandle; handles
|
| 215 |
+
// are stolen; the array itself is borrowed
|
| 216 |
+
AtenTensorHandle*
|
| 217 |
+
output_handles, // array for writing output AtenTensorHandle; handles
|
| 218 |
+
// will be stolen by the caller; the array itself is
|
| 219 |
+
// borrowed
|
| 220 |
+
DeviceStreamType stream,
|
| 221 |
+
AOTIProxyExecutorHandle proxy_executor
|
| 222 |
+
) {
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
self.generate_input_output_runtime_checks()
|
| 226 |
+
run_impl_proto += """
|
| 227 |
+
__check_inputs_outputs(input_handles, output_handles);
|
| 228 |
+
"""
|
| 229 |
+
|
| 230 |
+
if config.aot_inductor.use_minimal_arrayref_interface:
|
| 231 |
+
self.prefix.splice(
|
| 232 |
+
"""
|
| 233 |
+
template <>
|
| 234 |
+
AOTInductorModelOutputs AOTInductorModel::run_impl_minimal_arrayref_interface<
|
| 235 |
+
AOTInductorModelInputs, AOTInductorModelOutputs>(
|
| 236 |
+
const AOTInductorModelInputs& inputs,
|
| 237 |
+
DeviceStreamType stream,
|
| 238 |
+
AOTIProxyExecutorHandle proxy_executor
|
| 239 |
+
) {
|
| 240 |
+
"""
|
| 241 |
+
)
|
| 242 |
+
self.suffix.splice(run_impl_proto)
|
| 243 |
+
self.suffix.splice(
|
| 244 |
+
"""
|
| 245 |
+
AOTInductorModelInputs inputs;
|
| 246 |
+
convert_handles_to_inputs(input_handles, inputs);
|
| 247 |
+
auto outputs = run_impl_minimal_arrayref_interface<AOTInductorModelInputs, AOTInductorModelOutputs>(
|
| 248 |
+
inputs, stream, proxy_executor);
|
| 249 |
+
// NOTE: outputs is full of ArrayRef to thread_local storage. If in the future we need this
|
| 250 |
+
// interface to perform well for a DSO using the minimal arrayref interface, all we need
|
| 251 |
+
// to do is provide ThreadLocalCachedTensor for each one!
|
| 252 |
+
convert_outputs_to_handles(outputs, output_handles);
|
| 253 |
+
}
|
| 254 |
+
"""
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
self.suffix.splice(
|
| 258 |
+
"""
|
| 259 |
+
extern "C" AOTIRuntimeError AOTInductorModelRunMinimalArrayrefInterface(
|
| 260 |
+
AOTInductorModelHandle model_handle,
|
| 261 |
+
const AOTInductorModelInputs& inputs,
|
| 262 |
+
AOTInductorModelOutputs& outputs) {
|
| 263 |
+
auto model = reinterpret_cast<torch::aot_inductor::AOTInductorModel*>(model_handle);
|
| 264 |
+
CONVERT_EXCEPTION_TO_ERROR_CODE({
|
| 265 |
+
outputs = model->run_impl_minimal_arrayref_interface<AOTInductorModelInputs, AOTInductorModelOutputs>(
|
| 266 |
+
inputs,
|
| 267 |
+
(torch::aot_inductor::DeviceStreamType)nullptr,
|
| 268 |
+
nullptr);
|
| 269 |
+
})
|
| 270 |
+
}
|
| 271 |
+
"""
|
| 272 |
+
)
|
| 273 |
+
else:
|
| 274 |
+
self.prefix.splice(run_impl_proto)
|
| 275 |
+
else:
|
| 276 |
+
# cpp entry function for JIT with cpp wrapper
|
| 277 |
+
self.prefix.splice(
|
| 278 |
+
"""
|
| 279 |
+
void inductor_entry_impl(
|
| 280 |
+
AtenTensorHandle*
|
| 281 |
+
input_handles, // array of input AtenTensorHandle; handles
|
| 282 |
+
// are stolen; the array itself is borrowed
|
| 283 |
+
AtenTensorHandle*
|
| 284 |
+
output_handles // array for writing output AtenTensorHandle; handles
|
| 285 |
+
// will be stolen by the caller; the array itself is
|
| 286 |
+
// borrowed)
|
| 287 |
+
) {
|
| 288 |
+
"""
|
| 289 |
+
)
|
| 290 |
+
with self.prefix.indent():
|
| 291 |
+
# assign inputs and outputs in both cases so the later codegen can be simplified
|
| 292 |
+
if not config.aot_inductor.use_minimal_arrayref_interface:
|
| 293 |
+
if not V.graph.is_const_graph:
|
| 294 |
+
if V.graph.aot_mode:
|
| 295 |
+
num_args = len(V.graph.graph_inputs)
|
| 296 |
+
else:
|
| 297 |
+
# Weights are promoted in the JIT mode
|
| 298 |
+
num_args = len(V.graph.graph_inputs) + len(V.graph.constants)
|
| 299 |
+
# release GIL to support multiple instances inference (in different threads of the same process)
|
| 300 |
+
self.prefix.splice("py::gil_scoped_release_simple release;")
|
| 301 |
+
|
| 302 |
+
self.prefix.splice(
|
| 303 |
+
f"""
|
| 304 |
+
auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {num_args});
|
| 305 |
+
"""
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
if inputs_len != 0:
|
| 309 |
+
for idx, input_key in enumerate(V.graph.graph_inputs.keys()):
|
| 310 |
+
if config.aot_inductor.use_minimal_arrayref_interface:
|
| 311 |
+
self.prefix.writeline(
|
| 312 |
+
f"auto {input_key} = std::get<{idx}>(inputs);"
|
| 313 |
+
)
|
| 314 |
+
continue
|
| 315 |
+
# unwrap input tensor back to scalar
|
| 316 |
+
if isinstance(V.graph.graph_inputs[input_key], sympy.Expr):
|
| 317 |
+
from ..graph import may_get_constant_buffer_dtype
|
| 318 |
+
|
| 319 |
+
dtype = may_get_constant_buffer_dtype(
|
| 320 |
+
V.graph.graph_inputs[input_key] # type: ignore[arg-type]
|
| 321 |
+
)
|
| 322 |
+
assert dtype is not None, (
|
| 323 |
+
"Fails to get the dtype of the sympy.Expr"
|
| 324 |
+
)
|
| 325 |
+
self.codegen_tensor_item(
|
| 326 |
+
dtype, f"inputs[{idx}]", input_key, self.prefix
|
| 327 |
+
)
|
| 328 |
+
else:
|
| 329 |
+
self.prefix.writeline(
|
| 330 |
+
f"auto {input_key} = std::move(inputs[{idx}]);"
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
assert all(
|
| 334 |
+
isinstance(v, torch.Tensor) for v in list(V.graph.constants.values())
|
| 335 |
+
), "Expect all constants to be Tensor"
|
| 336 |
+
for idx, constants_key in enumerate(V.graph.constants.keys()):
|
| 337 |
+
if V.graph.aot_mode:
|
| 338 |
+
# Weights are stored in constants_ and owned by RAIIAtenTensorHandle there.
|
| 339 |
+
# Don't call std::move here because it will cause constants_ to lose the ownership.
|
| 340 |
+
self.prefix.writeline(
|
| 341 |
+
f"""auto {constants_key} = constants_->at({idx});"""
|
| 342 |
+
)
|
| 343 |
+
else:
|
| 344 |
+
# Append constants as inputs to the graph
|
| 345 |
+
constants_idx = inputs_len + idx
|
| 346 |
+
self.prefix.writeline(
|
| 347 |
+
f"auto {constants_key} = std::move(inputs[{constants_idx}]);"
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
self.codegen_inputs()
|
| 351 |
+
|
| 352 |
+
if V.graph.aot_mode:
|
| 353 |
+
if not V.graph.is_const_graph:
|
| 354 |
+
if config.aot_inductor.use_minimal_arrayref_interface:
|
| 355 |
+
# TODO: input shape checking for regular tensor interface as well?
|
| 356 |
+
self.codegen_input_numel_asserts()
|
| 357 |
+
else:
|
| 358 |
+
self.prefix.writeline("inputs.clear();")
|
| 359 |
+
self.prefix.writeline(
|
| 360 |
+
"[[maybe_unused]] auto& kernels = static_cast<AOTInductorModelKernels&>(*this->kernels_.get());"
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
def generate_return(self, output_refs: list[str]):
|
| 364 |
+
cst_names = V.graph.constants.keys()
|
| 365 |
+
arr_iface = (
|
| 366 |
+
not V.graph.is_const_graph
|
| 367 |
+
and config.aot_inductor.use_minimal_arrayref_interface
|
| 368 |
+
) # For brevity.
|
| 369 |
+
|
| 370 |
+
def use_thread_local_cached_output_tensor(idx, output):
|
| 371 |
+
cached_output_name = f"cached_output_{next(self.cached_output_id)}"
|
| 372 |
+
cache_type = "Array" if arr_iface else "Tensor"
|
| 373 |
+
self.wrapper_call.writeline(
|
| 374 |
+
f"thread_local ThreadLocalCachedOutput{cache_type}<std::decay_t<decltype({output})>> "
|
| 375 |
+
f"{cached_output_name}({output});"
|
| 376 |
+
)
|
| 377 |
+
if arr_iface:
|
| 378 |
+
self.wrapper_call.writeline(
|
| 379 |
+
f"{cached_output_name}.copy_data_from({output});"
|
| 380 |
+
)
|
| 381 |
+
output_entry = f"std::get<{idx}>(output_arrayref_tensors)"
|
| 382 |
+
element_type = f"std::decay_t<decltype({output_entry}.data()[0])>"
|
| 383 |
+
self.wrapper_call.writeline(
|
| 384 |
+
f"{output_entry} = {cached_output_name}.arrayref_tensor<{element_type}>();"
|
| 385 |
+
)
|
| 386 |
+
else:
|
| 387 |
+
self.wrapper_call.writeline(
|
| 388 |
+
f"{cached_output_name}.copy_data_from({output});"
|
| 389 |
+
)
|
| 390 |
+
self.wrapper_call.writeline(
|
| 391 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&output_handles[{idx}]));"
|
| 392 |
+
)
|
| 393 |
+
self.wrapper_call.writeline(
|
| 394 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors({cached_output_name}.tensor(), "
|
| 395 |
+
f"output_handles[{idx}]));"
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
if arr_iface:
|
| 399 |
+
self.wrapper_call.writeline(
|
| 400 |
+
"AOTInductorModelOutputs output_arrayref_tensors;"
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
output2idx: dict[str, int] = {}
|
| 404 |
+
for idx, output in enumerate(output_refs):
|
| 405 |
+
if output == "nullptr":
|
| 406 |
+
continue
|
| 407 |
+
|
| 408 |
+
is_constant_buffer = output in cst_names
|
| 409 |
+
output_buffer = V.graph.graph_outputs[idx]
|
| 410 |
+
if isinstance(output_buffer, ir.BaseView):
|
| 411 |
+
output_storage = output_buffer.unwrap_view()
|
| 412 |
+
assert isinstance(output_storage, (ir.BaseView, ir.MutableBox))
|
| 413 |
+
if isinstance(output_storage.data, ir.ConstantBuffer):
|
| 414 |
+
is_constant_buffer = True
|
| 415 |
+
|
| 416 |
+
if isinstance(output_buffer, ir.ShapeAsConstantBuffer):
|
| 417 |
+
# Need to wrap scalar into tensor as the main function returns a vector of tensors
|
| 418 |
+
output_tensor = self.codegen_scalar_to_tensor(output)
|
| 419 |
+
self.wrapper_call.writeline(
|
| 420 |
+
f"output_handles[{idx}] = {output_tensor}.release();"
|
| 421 |
+
)
|
| 422 |
+
continue
|
| 423 |
+
|
| 424 |
+
output_is_tensor_handle_expr = (
|
| 425 |
+
f"std::is_same_v<std::decay_t<decltype({output})>,"
|
| 426 |
+
"RAIIAtenTensorHandle> || "
|
| 427 |
+
f"std::is_same_v<std::decay_t<decltype({output})>,"
|
| 428 |
+
"AtenTensorHandle> || "
|
| 429 |
+
f"std::is_same_v<std::decay_t<decltype({output})>,"
|
| 430 |
+
"ConstantHandle>"
|
| 431 |
+
)
|
| 432 |
+
self.wrapper_call.writeline(
|
| 433 |
+
f"if constexpr ({output_is_tensor_handle_expr}) {{"
|
| 434 |
+
)
|
| 435 |
+
with self.wrapper_call.indent():
|
| 436 |
+
if arr_iface:
|
| 437 |
+
cached_output_name = f"cached_output_{next(self.cached_output_id)}"
|
| 438 |
+
self.wrapper_call.writeline(
|
| 439 |
+
f"thread_local RAIIAtenTensorHandle {cached_output_name};"
|
| 440 |
+
)
|
| 441 |
+
if is_constant_buffer:
|
| 442 |
+
# NOTE(return_constant): In some rare cases where we return
|
| 443 |
+
# a constant, we have to return a copy of this constant,
|
| 444 |
+
# because (1) constants are not owned by the Model instance
|
| 445 |
+
# (2) constants remain the same cross inference runs,
|
| 446 |
+
# assuming they are not updated at runtime Basically, we
|
| 447 |
+
# cannot release or transfer the ownership of any original
|
| 448 |
+
# constant to the user.
|
| 449 |
+
self.wrapper_call.writeline(
|
| 450 |
+
f"AtenTensorHandle {cached_output_name}_tmp;"
|
| 451 |
+
)
|
| 452 |
+
self.wrapper_call.writeline(
|
| 453 |
+
f"aoti_torch_clone({output}, &{cached_output_name}_tmp);"
|
| 454 |
+
)
|
| 455 |
+
self.wrapper_call.writeline(
|
| 456 |
+
f"{cached_output_name} = {cached_output_name}_tmp;"
|
| 457 |
+
)
|
| 458 |
+
else:
|
| 459 |
+
self.wrapper_call.writeline(
|
| 460 |
+
f"{cached_output_name} = {output}.release();"
|
| 461 |
+
)
|
| 462 |
+
self.wrapper_call.writeline(
|
| 463 |
+
f"convert_handle_to_arrayref_tensor({cached_output_name}, "
|
| 464 |
+
f"std::get<{idx}>(output_arrayref_tensors));"
|
| 465 |
+
)
|
| 466 |
+
else:
|
| 467 |
+
if is_constant_buffer:
|
| 468 |
+
# See NOTE(return_constant) above.
|
| 469 |
+
self.wrapper_call.writeline(
|
| 470 |
+
f"aoti_torch_clone({output}, &output_handles[{idx}]);"
|
| 471 |
+
)
|
| 472 |
+
else:
|
| 473 |
+
if output in output2idx:
|
| 474 |
+
src_idx = output2idx[output]
|
| 475 |
+
self.wrapper_call.writeline(
|
| 476 |
+
f"output_handles[{idx}] = output_handles[{src_idx}];"
|
| 477 |
+
)
|
| 478 |
+
else:
|
| 479 |
+
self.wrapper_call.writeline(
|
| 480 |
+
f"output_handles[{idx}] = {output}.release();"
|
| 481 |
+
)
|
| 482 |
+
self.wrapper_call.writeline("} else {")
|
| 483 |
+
with self.wrapper_call.indent():
|
| 484 |
+
use_thread_local_cached_output_tensor(idx, output)
|
| 485 |
+
self.wrapper_call.writeline("}")
|
| 486 |
+
|
| 487 |
+
if output not in output2idx:
|
| 488 |
+
output2idx[output] = idx
|
| 489 |
+
if arr_iface:
|
| 490 |
+
self.wrapper_call.writeline("return output_arrayref_tensors;")
|
| 491 |
+
|
| 492 |
+
def memory_plan(self):
|
| 493 |
+
from .memory_planning import MemoryPlanner
|
| 494 |
+
|
| 495 |
+
self.lines = MemoryPlanner(self).plan(self.lines)
|
| 496 |
+
# TODO: integrate memory planning & stack allocation?
|
| 497 |
+
self.allow_stack_allocation = False
|
| 498 |
+
|
| 499 |
+
def memory_plan_reuse(self):
|
| 500 |
+
out_names = V.graph.get_output_names()
|
| 501 |
+
|
| 502 |
+
while (
|
| 503 |
+
self.lines
|
| 504 |
+
and isinstance(self.lines[-1], MemoryPlanningLine)
|
| 505 |
+
# TODO: this seems legit, NullLine has no node
|
| 506 |
+
and self.lines[-1].node.name not in out_names # type: ignore[attr-defined]
|
| 507 |
+
):
|
| 508 |
+
# these lines will be pointless
|
| 509 |
+
self.lines.pop()
|
| 510 |
+
|
| 511 |
+
# codegen allocations in two passes
|
| 512 |
+
planning_states = [MemoryPlanningState()]
|
| 513 |
+
past_planning_states = []
|
| 514 |
+
for i in range(len(self.lines)):
|
| 515 |
+
line = self.lines[i]
|
| 516 |
+
if isinstance(line, MemoryPlanningLine):
|
| 517 |
+
self.lines[i] = line.plan(planning_states[-1])
|
| 518 |
+
elif isinstance(line, EnterSubgraphLine):
|
| 519 |
+
planning_states.append(MemoryPlanningState())
|
| 520 |
+
elif isinstance(line, ExitSubgraphLine):
|
| 521 |
+
past_planning_states.append(planning_states.pop())
|
| 522 |
+
past_planning_states.append(planning_states.pop())
|
| 523 |
+
assert len(planning_states) == 0
|
| 524 |
+
|
| 525 |
+
# conservatively use the sum of all allocated buffer sizes
|
| 526 |
+
# in potentially nested scopes as the total allocated size
|
| 527 |
+
total_allocated_buffer_size = sum(
|
| 528 |
+
s.total_allocated_buffer_size for s in past_planning_states
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
self.allow_stack_allocation = (
|
| 532 |
+
self.allow_stack_allocation is not False
|
| 533 |
+
and config.aot_inductor.allow_stack_allocation
|
| 534 |
+
and total_allocated_buffer_size <= MAX_STACK_ALLOCATION_SIZE
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
def can_stack_allocate_buffer(self, buffer):
|
| 538 |
+
return (
|
| 539 |
+
self.allow_stack_allocation
|
| 540 |
+
and buffer.get_device().type == "cpu"
|
| 541 |
+
and self.can_prove_buffer_has_static_shape(buffer)
|
| 542 |
+
and ir.is_contiguous_strides_for_shape(
|
| 543 |
+
buffer.get_stride(), buffer.get_size()
|
| 544 |
+
)
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
def make_buffer_free(self, buffer):
|
| 548 |
+
return (
|
| 549 |
+
""
|
| 550 |
+
if isinstance(buffer.get_output_spec(), ir.MultiOutputLayout)
|
| 551 |
+
or (V.graph.aot_mode and buffer.get_name() in self.stack_allocated_buffers)
|
| 552 |
+
or (
|
| 553 |
+
config.aot_inductor.use_minimal_arrayref_interface
|
| 554 |
+
and V.graph.aot_mode
|
| 555 |
+
and buffer.get_name() in V.graph.graph_inputs
|
| 556 |
+
)
|
| 557 |
+
else f"{buffer.get_name()}.reset();"
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
def make_buffer_allocation(self, buffer):
|
| 561 |
+
return self.make_allocation(
|
| 562 |
+
buffer.get_name(),
|
| 563 |
+
buffer.get_device(),
|
| 564 |
+
buffer.get_dtype(),
|
| 565 |
+
buffer.get_size(),
|
| 566 |
+
buffer.get_stride(),
|
| 567 |
+
buffer if self.can_stack_allocate_buffer(buffer) else None,
|
| 568 |
+
buffer.get_is_pinned(),
|
| 569 |
+
)
|
| 570 |
+
|
| 571 |
+
def make_allocation(
|
| 572 |
+
self,
|
| 573 |
+
name,
|
| 574 |
+
device,
|
| 575 |
+
dtype,
|
| 576 |
+
shape,
|
| 577 |
+
stride,
|
| 578 |
+
buffer_if_can_stack_allocate=None,
|
| 579 |
+
is_pinned=False,
|
| 580 |
+
):
|
| 581 |
+
orig_stride = stride
|
| 582 |
+
device_str = self.codegen_device(device)
|
| 583 |
+
dtype_code = self.codegen_dtype(dtype)
|
| 584 |
+
size = self.codegen_shape_tuple(shape)
|
| 585 |
+
stride = self.codegen_shape_tuple(orig_stride)
|
| 586 |
+
size_array_var = self.codegen_int_array_var(
|
| 587 |
+
size,
|
| 588 |
+
self.wrapper_call.writeline,
|
| 589 |
+
known_statically=self.is_statically_known_list_of_ints(shape),
|
| 590 |
+
graph=self.get_codegened_graph(),
|
| 591 |
+
)
|
| 592 |
+
stride_array_var = self.codegen_int_array_var(
|
| 593 |
+
stride,
|
| 594 |
+
self.wrapper_call.writeline,
|
| 595 |
+
known_statically=self.is_statically_known_list_of_ints(orig_stride),
|
| 596 |
+
graph=self.get_codegened_graph(),
|
| 597 |
+
)
|
| 598 |
+
device_type, device_id = device_str.split(",")
|
| 599 |
+
device_idx = "this->device_idx_" if V.graph.aot_mode else device_id
|
| 600 |
+
if buffer_if_can_stack_allocate is not None:
|
| 601 |
+
self.stack_allocated_buffers[name] = buffer_if_can_stack_allocate
|
| 602 |
+
cpp_type = DTYPE_TO_CPP[dtype]
|
| 603 |
+
numel = buffer_if_can_stack_allocate.get_numel()
|
| 604 |
+
# Note: we don't zero storage because empty_strided doesn't zero either.
|
| 605 |
+
self.wrapper_call.writeline(f"{cpp_type} {name}_storage[{numel}];")
|
| 606 |
+
args = [
|
| 607 |
+
f"{name}_storage",
|
| 608 |
+
size_array_var,
|
| 609 |
+
stride_array_var,
|
| 610 |
+
device_type,
|
| 611 |
+
device_idx,
|
| 612 |
+
]
|
| 613 |
+
return f"ArrayRefTensor<{cpp_type}> {name}({', '.join(args)});"
|
| 614 |
+
|
| 615 |
+
args = [
|
| 616 |
+
str(len(shape)),
|
| 617 |
+
size_array_var,
|
| 618 |
+
stride_array_var,
|
| 619 |
+
dtype_code,
|
| 620 |
+
device_type,
|
| 621 |
+
device_idx,
|
| 622 |
+
f"&{name}_handle",
|
| 623 |
+
]
|
| 624 |
+
|
| 625 |
+
self.wrapper_call.writeline(f"AtenTensorHandle {name}_handle;")
|
| 626 |
+
pinned_str = "_pinned" if is_pinned else ""
|
| 627 |
+
self.wrapper_call.writeline(
|
| 628 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided{pinned_str}({', '.join(args)}));"
|
| 629 |
+
)
|
| 630 |
+
|
| 631 |
+
return f"RAIIAtenTensorHandle {name}({name}_handle);"
|
| 632 |
+
|
| 633 |
+
def make_buffer_reuse(self, old: BufferLike, new: BufferLike, delete_old: bool):
|
| 634 |
+
assert old.get_dtype() == new.get_dtype()
|
| 635 |
+
old_name = old.get_name()
|
| 636 |
+
new_name = new.get_name()
|
| 637 |
+
del_line = ";"
|
| 638 |
+
if old_name not in V.graph.get_output_names() and delete_old:
|
| 639 |
+
del_line = f"; {self.make_buffer_free(old)}"
|
| 640 |
+
|
| 641 |
+
if old.get_size() == new.get_size() and old.get_stride() == new.get_stride():
|
| 642 |
+
if old_name in self.stack_allocated_buffers:
|
| 643 |
+
self.stack_allocated_buffers[new_name] = new
|
| 644 |
+
return self.codegen_exact_buffer_reuse(old_name, new_name, del_line)
|
| 645 |
+
|
| 646 |
+
reinterpret_view = self.codegen_reinterpret_view(
|
| 647 |
+
old, new.get_size(), new.get_stride(), 0, self.wrapper_call.writeline
|
| 648 |
+
)
|
| 649 |
+
if reinterpret_view in self.stack_allocated_buffers:
|
| 650 |
+
self.stack_allocated_buffers[new_name] = new
|
| 651 |
+
# The only way to get into this case is via an exact buffer reuse, since all
|
| 652 |
+
# other options result in a new tensor handle.
|
| 653 |
+
return self.codegen_exact_buffer_reuse(old_name, new_name, del_line)
|
| 654 |
+
return f"{self.declare}{new_name} = {reinterpret_view}{del_line} // reuse"
|
| 655 |
+
|
| 656 |
+
def _assert_safe_to_use_borrow_arrayref_tensor_as_tensor(self):
|
| 657 |
+
# Borrowing arguments to shim functions is only safe because we know
|
| 658 |
+
# that the arguments can't be stack-allocated. Otherwise, to be sure
|
| 659 |
+
# we can't return a dangling pointer, we need to either 1) be
|
| 660 |
+
# certain that the shim function cannot return an alias of a
|
| 661 |
+
# borrowed argument, or 2) be certain that the returned Tensor from
|
| 662 |
+
# the shim function cannot escape.
|
| 663 |
+
assert self.is_safe_to_use_borrow_arrayref_tensor_as_tensor(), (
|
| 664 |
+
"borrowing arguments to shim functions is unsafe with "
|
| 665 |
+
"stack allocation on! (see comment above this assertion)"
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
def is_safe_to_use_borrow_arrayref_tensor_as_tensor(self):
|
| 669 |
+
return not self.allow_stack_allocation and not self.stack_allocated_buffers
|
| 670 |
+
|
| 671 |
+
def generate_c_shim_extern_kernel_call(
|
| 672 |
+
self, kernel: str, args: list[str], device: str, **_
|
| 673 |
+
) -> None:
|
| 674 |
+
# In the abi_compatible mode, we call fallback aten ops through a C shim layer
|
| 675 |
+
# Setting self.allow_stack_allocation to False because the exchange between
|
| 676 |
+
# ArrayRefTensor and at::Tensor is still fragile.
|
| 677 |
+
self.allow_stack_allocation = False
|
| 678 |
+
|
| 679 |
+
wrapped_args = []
|
| 680 |
+
for arg in args:
|
| 681 |
+
# We only really *need* borrow_arrayref_tensor_as_tensor for
|
| 682 |
+
# ArrayRefTensors. The code flowing into here uses `0` for nullptr, which
|
| 683 |
+
# borrow_arrayref_tensor_as_tensor would blindly coerce to int, so just
|
| 684 |
+
# avoid wrapping integers. Name matching is to find tensor is hacky, but
|
| 685 |
+
# fixing all the ArrayRefTensor issues is not a priority for now.
|
| 686 |
+
if isinstance(arg, str) and arg.startswith(
|
| 687 |
+
("buf", "arg", "wrap_with_raii_handle_if_needed")
|
| 688 |
+
):
|
| 689 |
+
self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor()
|
| 690 |
+
arg = f"borrow_arrayref_tensor_as_tensor({arg})"
|
| 691 |
+
wrapped_args.append(arg)
|
| 692 |
+
|
| 693 |
+
super().generate_c_shim_extern_kernel_call(
|
| 694 |
+
kernel, wrapped_args, device, debug_args=args
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
def generate_scatter_fallback(self, node: ir.ScatterFallback):
|
| 698 |
+
# No stack allocation when there is a fallback op
|
| 699 |
+
self.allow_stack_allocation = False
|
| 700 |
+
super().generate_scatter_fallback(node)
|
| 701 |
+
|
| 702 |
+
def _generate_scatter_fallback(
|
| 703 |
+
self,
|
| 704 |
+
output,
|
| 705 |
+
inputs,
|
| 706 |
+
cpp_kernel_name,
|
| 707 |
+
python_kernel_name,
|
| 708 |
+
src_is_tensor,
|
| 709 |
+
reduce,
|
| 710 |
+
kwargs,
|
| 711 |
+
device,
|
| 712 |
+
):
|
| 713 |
+
reduce = self._get_scatter_reduce_enum(reduce)
|
| 714 |
+
|
| 715 |
+
# call the ABI shim function instead of the ATen one
|
| 716 |
+
self.add_device_include(device)
|
| 717 |
+
cpp_kernel_name = self.get_c_shim_func_name(cpp_kernel_name, device)
|
| 718 |
+
|
| 719 |
+
# TODO: consider remove "_out" and add missing inplace variants to fallback_ops.py
|
| 720 |
+
cpp_kernel_name = cpp_kernel_name.replace("__", "_") + "_out"
|
| 721 |
+
self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor()
|
| 722 |
+
inputs_wrapped = [
|
| 723 |
+
(f"borrow_arrayref_tensor_as_tensor({x})" if isinstance(x, str) else str(x))
|
| 724 |
+
for x in inputs
|
| 725 |
+
]
|
| 726 |
+
line = f"{cpp_kernel_name}(borrow_arrayref_tensor_as_tensor({output}), {','.join(inputs_wrapped)}"
|
| 727 |
+
|
| 728 |
+
if python_kernel_name.startswith("aten.scatter_reduce"):
|
| 729 |
+
line += f", {','.join(kwargs)}"
|
| 730 |
+
else:
|
| 731 |
+
if src_is_tensor:
|
| 732 |
+
if reduce:
|
| 733 |
+
line += f", {V.graph.wrapper_code.val_to_arg_str(reduce)}"
|
| 734 |
+
else:
|
| 735 |
+
assert reduce is None, (
|
| 736 |
+
"Expect reduce to be None for aten.scatter_ with scalar src"
|
| 737 |
+
)
|
| 738 |
+
line += ");"
|
| 739 |
+
self.writeline(line)
|
| 740 |
+
|
| 741 |
+
def generate_index_put_fallback(self, node: ir.IndexPutFallback) -> None:
|
| 742 |
+
# No stack allocation when there is a fallback op
|
| 743 |
+
self.allow_stack_allocation = False
|
| 744 |
+
super().generate_index_put_fallback(node)
|
| 745 |
+
|
| 746 |
+
def _generate_index_put_fallback(self, kernel, x, indices, values, accumulate):
|
| 747 |
+
self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor()
|
| 748 |
+
# TODO: update aoti_torch_index_put_out in ir.py to use autogen out version
|
| 749 |
+
# See the comment in codegen_reinterpret_view about why having something like
|
| 750 |
+
# RAIIAtenTensorHandle(tmp_tensor_handle_2) in a tmp array can cause the corresponding
|
| 751 |
+
# tensor prematurely deallocated, thus the temporary array trick here.
|
| 752 |
+
indices_str = self._generate_temporary_array_pointer(
|
| 753 |
+
"AtenTensorHandle",
|
| 754 |
+
[f"borrow_arrayref_tensor_as_tensor({i})" for i in indices],
|
| 755 |
+
)
|
| 756 |
+
args = [
|
| 757 |
+
f"borrow_arrayref_tensor_as_tensor({x})",
|
| 758 |
+
indices_str,
|
| 759 |
+
str(len(indices)),
|
| 760 |
+
f"borrow_arrayref_tensor_as_tensor({values})",
|
| 761 |
+
accumulate,
|
| 762 |
+
]
|
| 763 |
+
args.insert(
|
| 764 |
+
0, f"borrow_arrayref_tensor_as_tensor({x})"
|
| 765 |
+
) # set x as the output tensor, this fallback mutates x.
|
| 766 |
+
self.writeline(self.wrap_kernel_call(kernel, args))
|
| 767 |
+
|
| 768 |
+
def generate_fallback_kernel_with_runtime_lookup(
|
| 769 |
+
self,
|
| 770 |
+
buf_name: str,
|
| 771 |
+
python_kernel_name: str,
|
| 772 |
+
get_args: Callable[[], Sequence[str]],
|
| 773 |
+
op_overload: Union[torch._ops.OpOverload, torch._ops.HigherOrderOperator],
|
| 774 |
+
raw_args: Sequence[Any],
|
| 775 |
+
outputs: Sequence[ir.Buffer],
|
| 776 |
+
) -> None:
|
| 777 |
+
# No stack allocation when there is a fallback op
|
| 778 |
+
self.allow_stack_allocation = False
|
| 779 |
+
super().generate_fallback_kernel_with_runtime_lookup(
|
| 780 |
+
buf_name, python_kernel_name, get_args, op_overload, raw_args, outputs
|
| 781 |
+
)
|
| 782 |
+
|
| 783 |
+
def codegen_device_copy(self, src, dst, non_blocking: Union[bool, str]):
|
| 784 |
+
# aoti_torch_tensor_copy_ takes AtenTensorHandle as input,
|
| 785 |
+
# while stack-allocation results in ArrayRefTensor
|
| 786 |
+
# so disable stack allocation here
|
| 787 |
+
self.allow_stack_allocation = False
|
| 788 |
+
self.writeline(
|
| 789 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_copy_(expensive_copy_to_tensor_if_needed({dst}), {src}, {non_blocking}));"
|
| 790 |
+
)
|
| 791 |
+
|
| 792 |
+
def codegen_reinterpret_view(
|
| 793 |
+
self,
|
| 794 |
+
data,
|
| 795 |
+
size,
|
| 796 |
+
stride,
|
| 797 |
+
offset,
|
| 798 |
+
writeline: Callable[..., None],
|
| 799 |
+
dtype=None,
|
| 800 |
+
) -> str:
|
| 801 |
+
"""Returns a newly-created, temporary RAII tensor handle containing the
|
| 802 |
+
reinterpreted tensor data. Callers of this function are responsible for saving
|
| 803 |
+
the handle if persistent access is needed."""
|
| 804 |
+
dim = str(len(size))
|
| 805 |
+
|
| 806 |
+
def create_reinterpret_call() -> str:
|
| 807 |
+
args = [
|
| 808 |
+
f"{data.get_name()}",
|
| 809 |
+
dim,
|
| 810 |
+
self.codegen_int_array_var(
|
| 811 |
+
self.codegen_shape_tuple(size),
|
| 812 |
+
writeline,
|
| 813 |
+
known_statically=self.is_statically_known_list_of_ints(size),
|
| 814 |
+
graph=self.get_codegened_graph(),
|
| 815 |
+
),
|
| 816 |
+
self.codegen_int_array_var(
|
| 817 |
+
self.codegen_shape_tuple(stride),
|
| 818 |
+
writeline,
|
| 819 |
+
known_statically=self.is_statically_known_list_of_ints(stride),
|
| 820 |
+
graph=self.get_codegened_graph(),
|
| 821 |
+
),
|
| 822 |
+
offset,
|
| 823 |
+
]
|
| 824 |
+
return f"wrap_with_raii_handle_if_needed(reinterpret_tensor_wrapper({', '.join(args)}))"
|
| 825 |
+
|
| 826 |
+
def create_new_tensor_handle() -> tuple[str, list[str]]:
|
| 827 |
+
# Calling reset() on ArrayRefTensor does nothing, since the array is
|
| 828 |
+
# const-allocated on the stack. Thus, it's safe to return a reference to
|
| 829 |
+
# the original array.
|
| 830 |
+
if (name := data.get_name()) in self.stack_allocated_buffers:
|
| 831 |
+
return name, []
|
| 832 |
+
|
| 833 |
+
tmp_AtenTensorHandle = f"tmp_{name}_{next(self.tmp_tensor_id)}"
|
| 834 |
+
tmp_call_strs = [
|
| 835 |
+
f"AtenTensorHandle {tmp_AtenTensorHandle};",
|
| 836 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_tensor_handle({data.get_name()}, &{tmp_AtenTensorHandle}));",
|
| 837 |
+
]
|
| 838 |
+
return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs
|
| 839 |
+
|
| 840 |
+
if (
|
| 841 |
+
size == data.layout.size
|
| 842 |
+
and stride == data.layout.stride
|
| 843 |
+
and offset == data.layout.offset
|
| 844 |
+
and (dtype is None or dtype == data.dtype)
|
| 845 |
+
):
|
| 846 |
+
final_tensor_str, call_strs = create_new_tensor_handle()
|
| 847 |
+
for line in call_strs:
|
| 848 |
+
writeline(line)
|
| 849 |
+
return final_tensor_str
|
| 850 |
+
|
| 851 |
+
return super().codegen_reinterpret_view(
|
| 852 |
+
data, size, stride, offset, writeline, dtype
|
| 853 |
+
)
|
| 854 |
+
|
| 855 |
+
def val_to_arg_str(self, val, type_=None) -> str:
|
| 856 |
+
if (
|
| 857 |
+
val is not None
|
| 858 |
+
and isinstance(type_, torch.OptionalType)
|
| 859 |
+
and isinstance(type_.getElementType(), torch.TensorType)
|
| 860 |
+
):
|
| 861 |
+
# Handle optional tensors as a special case, as in the parent class.
|
| 862 |
+
base_handle = self.val_to_arg_str(val, torch.TensorType)
|
| 863 |
+
if config.aot_inductor.use_minimal_arrayref_interface:
|
| 864 |
+
if self.is_safe_to_use_borrow_arrayref_tensor_as_tensor():
|
| 865 |
+
base_handle = f"borrow_arrayref_tensor_as_tensor({base_handle})"
|
| 866 |
+
else:
|
| 867 |
+
base_handle = f"copy_arrayref_tensor_to_tensor({base_handle})"
|
| 868 |
+
return f"&temporary_reference({base_handle}.get())"
|
| 869 |
+
|
| 870 |
+
return super().val_to_arg_str(val, type_)
|
| 871 |
+
|
| 872 |
+
def codegen_tensor_item(
|
| 873 |
+
self, dtype: torch.dtype, tensor: str, scalar: str, indented_buffer=None
|
| 874 |
+
):
|
| 875 |
+
dtype_str = str(dtype).split(".")[-1]
|
| 876 |
+
writer = indented_buffer or self
|
| 877 |
+
|
| 878 |
+
if dtype == torch.float16 or dtype == torch.bfloat16:
|
| 879 |
+
scalar_tmp = f"{scalar}_tmp"
|
| 880 |
+
writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar_tmp};")
|
| 881 |
+
|
| 882 |
+
# We know that item_ doesn't alias the input, so borrowing should be safe.
|
| 883 |
+
tensor = f"borrow_arrayref_tensor_as_tensor({tensor})"
|
| 884 |
+
|
| 885 |
+
writer.writeline(
|
| 886 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar_tmp}));"
|
| 887 |
+
)
|
| 888 |
+
writer.writeline(f"float {scalar} = float({scalar_tmp});")
|
| 889 |
+
else:
|
| 890 |
+
writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar};")
|
| 891 |
+
|
| 892 |
+
# We know that item_ doesn't alias the input, so borrowing should be safe.
|
| 893 |
+
tensor = f"borrow_arrayref_tensor_as_tensor({tensor})"
|
| 894 |
+
|
| 895 |
+
writer.writeline(
|
| 896 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar}));"
|
| 897 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py
ADDED
|
@@ -0,0 +1,891 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
import sys
|
| 7 |
+
from itertools import count, zip_longest
|
| 8 |
+
from typing import Any, Optional, Union
|
| 9 |
+
from typing_extensions import Self
|
| 10 |
+
|
| 11 |
+
import sympy
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch import dtype as torch_dtype
|
| 15 |
+
from torch._inductor.codecache import get_cpp_wrapper_cubin_path_name
|
| 16 |
+
from torch._inductor.runtime.runtime_utils import dynamo_timed
|
| 17 |
+
|
| 18 |
+
from .. import config
|
| 19 |
+
from ..codecache import CudaKernelParamCache
|
| 20 |
+
from ..ir import (
|
| 21 |
+
GraphPartitionSignature,
|
| 22 |
+
TensorBox,
|
| 23 |
+
TMADescriptorExperimental,
|
| 24 |
+
TMADescriptorStable,
|
| 25 |
+
)
|
| 26 |
+
from ..utils import cache_on_self, get_gpu_type, GPU_ALIGN_BYTES, IndentedBuffer
|
| 27 |
+
from ..virtualized import V
|
| 28 |
+
from .aoti_hipify_utils import maybe_hipify_code_wrapper
|
| 29 |
+
from .common import get_device_op_overrides, TritonScratchWorkspace
|
| 30 |
+
from .cpp_utils import cexpr
|
| 31 |
+
from .cpp_wrapper_cpu import CppWrapperCpu
|
| 32 |
+
from .multi_kernel import MultiKernelCall
|
| 33 |
+
from .triton_utils import should_unwrap_unspec_arg
|
| 34 |
+
from .wrapper import PythonWrapperCodegen, SymbolicCallArg
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
_cpp_string_literal_escapes = {
|
| 38 |
+
"\\": "\\\\",
|
| 39 |
+
'"': '\\"',
|
| 40 |
+
"\n": "\\n",
|
| 41 |
+
"\t": "\\t",
|
| 42 |
+
"\r": "\\r",
|
| 43 |
+
}
|
| 44 |
+
_cpp_string_literal_pattern = re.compile(r'["\\\n\t\r]')
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def cpp_string_literal(s: str) -> str:
|
| 48 |
+
escaped = _cpp_string_literal_pattern.sub(
|
| 49 |
+
lambda match: _cpp_string_literal_escapes[match.group(0)], s
|
| 50 |
+
)
|
| 51 |
+
return f'"{escaped}"'
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclasses.dataclass
|
| 55 |
+
class DeferredTritonCallWrapper:
|
| 56 |
+
"""
|
| 57 |
+
When using cpp wrapper, GPU kernel load and launch needs to wait for Triton kernels
|
| 58 |
+
to be tuned and stored as cubin files, so use a deferred generating the final wrapper around
|
| 59 |
+
the triton kernel until right before the prefix is written.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
wrapper_name: str
|
| 63 |
+
kernel_name: str
|
| 64 |
+
kernel_name_to_body: dict[str, str]
|
| 65 |
+
arg_types: list[Any]
|
| 66 |
+
|
| 67 |
+
def generate(self, wrapper: CppWrapperGpu):
|
| 68 |
+
"""
|
| 69 |
+
Generate the GPU kernel definition, as well as load and launch code.
|
| 70 |
+
"""
|
| 71 |
+
prefix = wrapper.prefix
|
| 72 |
+
if self.kernel_name.startswith("multi_kernel_"):
|
| 73 |
+
# MultiKernel will select one kernel after running the autotune block
|
| 74 |
+
self.kernel_name = MultiKernelCall.lookup_choice(self.kernel_name)
|
| 75 |
+
params = CudaKernelParamCache.get(self.kernel_name)
|
| 76 |
+
assert params, f"CudaKernelParamCache not populated for {self.kernel_name}"
|
| 77 |
+
def_args = params["def_args"]
|
| 78 |
+
arg_types = self.arg_types
|
| 79 |
+
inductor_meta = params["inductor_meta"]
|
| 80 |
+
|
| 81 |
+
if "extra_launcher_args" in inductor_meta and len(def_args) > len(arg_types):
|
| 82 |
+
# extra_launcher_args should already be in def_args
|
| 83 |
+
assert len(def_args) == len(arg_types) - len(
|
| 84 |
+
inductor_meta["extra_launcher_args"]
|
| 85 |
+
)
|
| 86 |
+
arg_types = arg_types + [SymbolicCallArg] * len(
|
| 87 |
+
inductor_meta["extra_launcher_args"]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
if not V.graph.aot_mode:
|
| 91 |
+
prefix.writeline(
|
| 92 |
+
maybe_hipify_code_wrapper(
|
| 93 |
+
f"static {wrapper.device_codegen.cpp_kernel_type()} {self.kernel_name} = nullptr;"
|
| 94 |
+
)
|
| 95 |
+
)
|
| 96 |
+
kernel_var_name = self.kernel_name
|
| 97 |
+
else:
|
| 98 |
+
kernel_var_name = f"kernels_.{self.kernel_name}"
|
| 99 |
+
|
| 100 |
+
# tensors can be RAIIAtenTensorHandle or ConstantHandle, so make them template types
|
| 101 |
+
template_types = [
|
| 102 |
+
f"typename {name}_type_"
|
| 103 |
+
for name, arg_type in zip(def_args, arg_types)
|
| 104 |
+
if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg))
|
| 105 |
+
]
|
| 106 |
+
if V.graph.aot_mode:
|
| 107 |
+
template_types.append("typename kernels_type_")
|
| 108 |
+
if template_types:
|
| 109 |
+
prefix.writeline(f"template <{', '.join(template_types)}>")
|
| 110 |
+
prefix.writeline(f"static inline void {self.wrapper_name}(")
|
| 111 |
+
with prefix.indent():
|
| 112 |
+
assert len(def_args) == len(arg_types), (def_args, arg_types)
|
| 113 |
+
for name, arg_type in zip(def_args, arg_types):
|
| 114 |
+
if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg)):
|
| 115 |
+
prefix.writeline(f"const {name}_type_& {name},")
|
| 116 |
+
elif issubclass(arg_type, (SymbolicCallArg, sympy.Expr, int)):
|
| 117 |
+
prefix.writeline(f"int64_t {name},")
|
| 118 |
+
elif arg_type is float:
|
| 119 |
+
prefix.writeline(f"float {name},")
|
| 120 |
+
elif arg_type is bool:
|
| 121 |
+
prefix.writeline(f"bool {name},")
|
| 122 |
+
else:
|
| 123 |
+
raise ValueError(f"Unexpected arg type {arg_type}")
|
| 124 |
+
prefix.writeline("int32_t device_idx_,")
|
| 125 |
+
prefix.writeline(
|
| 126 |
+
maybe_hipify_code_wrapper(
|
| 127 |
+
f"{wrapper.device_codegen.cpp_stream_type()} stream_,"
|
| 128 |
+
)
|
| 129 |
+
)
|
| 130 |
+
if V.graph.aot_mode:
|
| 131 |
+
prefix.writeline("kernels_type_& kernels_,")
|
| 132 |
+
prefix.writeline(
|
| 133 |
+
"const std::optional<std::string>& cubin_dir_ = std::nullopt"
|
| 134 |
+
)
|
| 135 |
+
prefix.writeline("){")
|
| 136 |
+
with prefix.indent():
|
| 137 |
+
if V.graph.aot_mode:
|
| 138 |
+
# Emit the original Triton kernel for debugging purposes
|
| 139 |
+
prefix.writeline("/*")
|
| 140 |
+
prefix.splice(self.kernel_name_to_body[self.kernel_name])
|
| 141 |
+
prefix.writeline("*/")
|
| 142 |
+
self.generate_grid(prefix, inductor_meta, params)
|
| 143 |
+
self.generate_load_kernel(prefix, kernel_var_name, params)
|
| 144 |
+
self.generate_launch_kernel(prefix, wrapper, kernel_var_name, params)
|
| 145 |
+
prefix.writeline("}")
|
| 146 |
+
|
| 147 |
+
if not config.aot_inductor.embed_kernel_binary:
|
| 148 |
+
# Ensure the cubin file is included in the package
|
| 149 |
+
V.graph.wrapper_code.additional_files.append(
|
| 150 |
+
params[get_cpp_wrapper_cubin_path_name()]
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def generate_grid(
|
| 154 |
+
self,
|
| 155 |
+
prefix: IndentedBuffer,
|
| 156 |
+
inductor_meta: dict[str, Any],
|
| 157 |
+
params: dict[str, Any],
|
| 158 |
+
):
|
| 159 |
+
from ..runtime.triton_heuristics import GridExpr
|
| 160 |
+
|
| 161 |
+
grid = GridExpr.from_meta(inductor_meta, params["config"], mode="cpp")
|
| 162 |
+
for line in grid.prefix:
|
| 163 |
+
prefix.writeline(line)
|
| 164 |
+
prefix.splice(
|
| 165 |
+
f"""\
|
| 166 |
+
uint32_t grid_0 = {grid.x_grid};
|
| 167 |
+
uint32_t grid_1 = {grid.y_grid};
|
| 168 |
+
uint32_t grid_2 = {grid.z_grid};
|
| 169 |
+
"""
|
| 170 |
+
)
|
| 171 |
+
prefix.writeline("if (grid_0 == 0 || grid_1 == 0 || grid_2 == 0) return;")
|
| 172 |
+
|
| 173 |
+
def generate_load_kernel(self, prefix, kernel_var_name, params):
|
| 174 |
+
prefix.writeline(f"if ({kernel_var_name} == nullptr) {{")
|
| 175 |
+
with prefix.indent():
|
| 176 |
+
embed_kernel_args = [f"__{params['inductor_meta']['kernel_name']}_start"]
|
| 177 |
+
if torch.xpu.is_available():
|
| 178 |
+
# XPU needs the end address of the kernel to calculate the size of the kernel binary.
|
| 179 |
+
embed_kernel_args.append(
|
| 180 |
+
f"__{params['inductor_meta']['kernel_name']}_end"
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
load_kernel_args = (
|
| 184 |
+
[
|
| 185 |
+
*embed_kernel_args,
|
| 186 |
+
cpp_string_literal(params["mangled_name"]),
|
| 187 |
+
str(params["shared_mem"]),
|
| 188 |
+
]
|
| 189 |
+
if V.graph.aot_mode and config.aot_inductor.embed_kernel_binary
|
| 190 |
+
else [
|
| 191 |
+
cpp_string_literal(params[get_cpp_wrapper_cubin_path_name()]),
|
| 192 |
+
cpp_string_literal(params["mangled_name"]),
|
| 193 |
+
str(params["shared_mem"]),
|
| 194 |
+
"cubin_dir_",
|
| 195 |
+
]
|
| 196 |
+
)
|
| 197 |
+
prefix.writeline(
|
| 198 |
+
f"{kernel_var_name} = loadKernel({', '.join(load_kernel_args)}); "
|
| 199 |
+
)
|
| 200 |
+
prefix.writeline("}")
|
| 201 |
+
|
| 202 |
+
def generate_launch_kernel(self, prefix, wrapper, kernel_var_name, params):
|
| 203 |
+
"""
|
| 204 |
+
Generate the GPU kernel launching code.
|
| 205 |
+
This is where all the call args being sorted out and generated.
|
| 206 |
+
If enable_kernel_profile is enabled, all args related information would be packed in this function.
|
| 207 |
+
"""
|
| 208 |
+
triton_meta = params["triton_meta"]
|
| 209 |
+
assert len(self.arg_types) == len(params["def_args"]), (
|
| 210 |
+
self.arg_types,
|
| 211 |
+
params["def_args"],
|
| 212 |
+
)
|
| 213 |
+
arg_type_loookup = dict(zip(params["def_args"], self.arg_types))
|
| 214 |
+
# difference between Python and C++ wrapper: C++ wrapper strips out equal_to_1 constants
|
| 215 |
+
call_args = [
|
| 216 |
+
name for name in params["call_args"] if name not in triton_meta["constants"]
|
| 217 |
+
]
|
| 218 |
+
arg_types = [arg_type_loookup[name] for name in call_args]
|
| 219 |
+
arg_signatures = [triton_meta["signature"][name] for name in call_args]
|
| 220 |
+
scratch_spaces = {
|
| 221 |
+
name: params[name]
|
| 222 |
+
for name in ["global_scratch", "profile_scratch"]
|
| 223 |
+
if params.get(name, None) is not None
|
| 224 |
+
}
|
| 225 |
+
call_args_str = wrapper.generate_args_decl(
|
| 226 |
+
prefix,
|
| 227 |
+
call_args,
|
| 228 |
+
arg_types,
|
| 229 |
+
arg_signatures,
|
| 230 |
+
scratch_spaces=scratch_spaces,
|
| 231 |
+
)
|
| 232 |
+
prefix.writeline(f"void* kernel_args_[] = {{{call_args_str}}};")
|
| 233 |
+
launch_kernel_args = [
|
| 234 |
+
kernel_var_name,
|
| 235 |
+
"grid_0",
|
| 236 |
+
"grid_1",
|
| 237 |
+
"grid_2",
|
| 238 |
+
str(params["num_warps"]),
|
| 239 |
+
str(params["shared_mem"]),
|
| 240 |
+
"kernel_args_",
|
| 241 |
+
"stream_",
|
| 242 |
+
]
|
| 243 |
+
if wrapper.device == "xpu":
|
| 244 |
+
launch_kernel_args.append(str(params["threads_per_warp"]))
|
| 245 |
+
|
| 246 |
+
enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [
|
| 247 |
+
"linux",
|
| 248 |
+
"win32",
|
| 249 |
+
]
|
| 250 |
+
if enable_kernel_profile:
|
| 251 |
+
normalized_kernel_name = re.sub(r"[^a-zA-Z0-9_]", "_", f"{kernel_var_name}")
|
| 252 |
+
prefix.writeline("{")
|
| 253 |
+
with prefix.indent():
|
| 254 |
+
prefix.writelines(
|
| 255 |
+
[
|
| 256 |
+
f"std::unordered_map<std::string, C10IValueHandle> kwargs_{normalized_kernel_name};",
|
| 257 |
+
"",
|
| 258 |
+
]
|
| 259 |
+
)
|
| 260 |
+
# Add launch args info
|
| 261 |
+
record_launch_kernel_args = [
|
| 262 |
+
("grid_0", "grid_0"),
|
| 263 |
+
("grid_1", "grid_1"),
|
| 264 |
+
("grid_2", "grid_2"),
|
| 265 |
+
("num_warps", str(params["num_warps"])),
|
| 266 |
+
("shared_mem", str(params["shared_mem"])),
|
| 267 |
+
]
|
| 268 |
+
for k, v in record_launch_kernel_args:
|
| 269 |
+
arg_name = f"{normalized_kernel_name}_{k}"
|
| 270 |
+
prefix.writelines(
|
| 271 |
+
[
|
| 272 |
+
f"// Create c10::IValue for {k}",
|
| 273 |
+
f"C10IValueHandle tmp_{arg_name};",
|
| 274 |
+
f"aoti_torch_int64_to_ivalue({v}, &tmp_{arg_name});",
|
| 275 |
+
f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});",
|
| 276 |
+
f'kwargs_{normalized_kernel_name}.emplace("{k}", RAII_{arg_name});',
|
| 277 |
+
]
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
# Add input info (This copies the logic from args_decl)
|
| 281 |
+
signature2dtype = {
|
| 282 |
+
"i32": "int32_t",
|
| 283 |
+
"i64": "int64_t",
|
| 284 |
+
"fp32": "float",
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
def signature_is_tma_desc(sig):
|
| 288 |
+
if not sig:
|
| 289 |
+
return False
|
| 290 |
+
if sig == "nvTmaDesc":
|
| 291 |
+
return True
|
| 292 |
+
if sig.startswith("tensordesc<"):
|
| 293 |
+
return True
|
| 294 |
+
return False
|
| 295 |
+
|
| 296 |
+
curr_arg_id = -1
|
| 297 |
+
total_args = []
|
| 298 |
+
ordered_argsname = []
|
| 299 |
+
|
| 300 |
+
def write_dummy_scalar_ivalue(arg_name):
|
| 301 |
+
# We only care about the shape, therefore we create a dummy scalar here.
|
| 302 |
+
prefix.writelines(
|
| 303 |
+
[
|
| 304 |
+
f"// Create c10::IValue for arg_{curr_arg_id}",
|
| 305 |
+
f"C10IValueHandle tmp_{arg_name};",
|
| 306 |
+
f"aoti_torch_int64_to_ivalue(0, &tmp_{arg_name});",
|
| 307 |
+
f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});",
|
| 308 |
+
]
|
| 309 |
+
)
|
| 310 |
+
# pyrefly: ignore [bad-argument-type]
|
| 311 |
+
total_args.append(f"tmp_{arg_name}")
|
| 312 |
+
|
| 313 |
+
def process_args_for_input_shape(arg, arg_type, arg_signature=None):
|
| 314 |
+
nonlocal curr_arg_id
|
| 315 |
+
curr_arg_id += 1
|
| 316 |
+
arg_name = f"{normalized_kernel_name}_arg_{curr_arg_id}"
|
| 317 |
+
# ignore tma descriptors, as host-side TMA descriptors need
|
| 318 |
+
# to be passed to the compiled Triton kernel by value
|
| 319 |
+
if isinstance(
|
| 320 |
+
arg_type, UnwrapUnspecArg
|
| 321 |
+
) and not signature_is_tma_desc(arg_signature):
|
| 322 |
+
write_dummy_scalar_ivalue(arg_name)
|
| 323 |
+
elif isinstance(
|
| 324 |
+
arg_type, torch_dtype
|
| 325 |
+
) and not signature_is_tma_desc(arg_signature):
|
| 326 |
+
# This is an at::Tensor.
|
| 327 |
+
prefix.writelines(
|
| 328 |
+
[
|
| 329 |
+
f"// Create c10::IValue for arg_{curr_arg_id}",
|
| 330 |
+
f"C10IValueHandle tmp_{arg_name};",
|
| 331 |
+
f"aoti_torch_tensor_to_ivalue({arg}, &tmp_{arg_name});",
|
| 332 |
+
f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});",
|
| 333 |
+
]
|
| 334 |
+
)
|
| 335 |
+
# pyrefly: ignore [bad-argument-type]
|
| 336 |
+
total_args.append(f"tmp_{arg_name}")
|
| 337 |
+
elif (
|
| 338 |
+
isinstance(arg_type, type(SymbolicCallArg))
|
| 339 |
+
and arg_signature is not None
|
| 340 |
+
and arg_signature in signature2dtype
|
| 341 |
+
) or arg_type in (sympy.Integer, int, sympy.Float, float):
|
| 342 |
+
write_dummy_scalar_ivalue(arg_name)
|
| 343 |
+
elif arg_signature and arg_signature.startswith("tensordesc<"):
|
| 344 |
+
# Skip tma related args
|
| 345 |
+
pass
|
| 346 |
+
else:
|
| 347 |
+
write_dummy_scalar_ivalue(arg_name)
|
| 348 |
+
|
| 349 |
+
# Add input name and shape information
|
| 350 |
+
for arg, arg_type, arg_signature in zip_longest(
|
| 351 |
+
call_args, arg_types, arg_signatures
|
| 352 |
+
):
|
| 353 |
+
# pyrefly: ignore [bad-argument-type]
|
| 354 |
+
ordered_argsname.append(f'"{arg}"')
|
| 355 |
+
process_args_for_input_shape(arg, arg_type, arg_signature)
|
| 356 |
+
|
| 357 |
+
# Add input name into kwargs
|
| 358 |
+
name_var = f"{normalized_kernel_name}_input_names"
|
| 359 |
+
prefix.writelines(
|
| 360 |
+
[
|
| 361 |
+
"// Create c10::IValue for input names",
|
| 362 |
+
f"C10IValueHandle tmp_{name_var};",
|
| 363 |
+
f"std::vector<const char*> {name_var}({{{', '.join(ordered_argsname)}}});",
|
| 364 |
+
f"aoti_torch_strlist_to_ivalue({name_var}.data(), {len(ordered_argsname)}, &tmp_{name_var});",
|
| 365 |
+
f"RAIIC10IValueHandle RAII_{name_var}(tmp_{name_var});",
|
| 366 |
+
f'kwargs_{normalized_kernel_name}.emplace("Input Args", RAII_{name_var});',
|
| 367 |
+
]
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
inputs_info_ = f"{normalized_kernel_name}_inputs_info_"
|
| 371 |
+
# We pass in the non-RAII handles, since C10 doesn't automatically free them.
|
| 372 |
+
# The RAII will make sure they get freed when they are out of scope.
|
| 373 |
+
tmp_args = ",".join(total_args)
|
| 374 |
+
prefix.writelines(
|
| 375 |
+
[
|
| 376 |
+
"// Aggregate all c10::IValue for inputs",
|
| 377 |
+
f"std::vector<C10IValueHandle> {inputs_info_}({{{tmp_args}}});",
|
| 378 |
+
]
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# Start recording Function
|
| 382 |
+
prefix.writelines(
|
| 383 |
+
[
|
| 384 |
+
"",
|
| 385 |
+
(
|
| 386 |
+
"torch::aot_inductor::RAIIAtenRecordFunctionHandle "
|
| 387 |
+
f"record_{normalized_kernel_name}_"
|
| 388 |
+
f'("{kernel_var_name}", '
|
| 389 |
+
f"reinterpret_cast<IValueMapHandle>(&kwargs_{normalized_kernel_name}), "
|
| 390 |
+
f"{inputs_info_});"
|
| 391 |
+
),
|
| 392 |
+
"",
|
| 393 |
+
f"launchKernel({', '.join(launch_kernel_args)});",
|
| 394 |
+
]
|
| 395 |
+
)
|
| 396 |
+
prefix.writeline("}")
|
| 397 |
+
else:
|
| 398 |
+
prefix.writeline(f"launchKernel({', '.join(launch_kernel_args)});")
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
class CppWrapperGpu(CppWrapperCpu):
|
| 402 |
+
"""
|
| 403 |
+
Generates cpp wrapper for running on GPU and calls CUDA kernels
|
| 404 |
+
"""
|
| 405 |
+
|
| 406 |
+
def __init__(self) -> None:
|
| 407 |
+
self.device = get_gpu_type()
|
| 408 |
+
self.device_codegen = get_device_op_overrides(self.device)
|
| 409 |
+
super().__init__()
|
| 410 |
+
self.grid_id = count()
|
| 411 |
+
self._kernel_name_to_body: dict[str, str] = {}
|
| 412 |
+
self._triton_call_wrappers: dict[str, DeferredTritonCallWrapper] = {}
|
| 413 |
+
self.autotune_input_prefix = "_REAL_AUTOTUNE_INPUT"
|
| 414 |
+
|
| 415 |
+
@staticmethod
|
| 416 |
+
def create(
|
| 417 |
+
is_subgraph: bool,
|
| 418 |
+
subgraph_name: Optional[str],
|
| 419 |
+
parent_wrapper: Optional[PythonWrapperCodegen],
|
| 420 |
+
partition_signatures: Optional[GraphPartitionSignature] = None,
|
| 421 |
+
):
|
| 422 |
+
# TODO - support subgraph codegen by lifting functions. Check the
|
| 423 |
+
# comment at CppWrapperCpu `codegen_subgraph` function.
|
| 424 |
+
return CppWrapperGpu()
|
| 425 |
+
|
| 426 |
+
def write_header(self):
|
| 427 |
+
if V.graph.is_const_graph:
|
| 428 |
+
# We do not write header for constant graph, it will be written by main module.
|
| 429 |
+
return
|
| 430 |
+
|
| 431 |
+
super().write_header()
|
| 432 |
+
self.header.splice(
|
| 433 |
+
maybe_hipify_code_wrapper(self.device_codegen.kernel_driver())
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
@cache_on_self
|
| 437 |
+
def write_tma_descriptor_helpers_once(self):
|
| 438 |
+
self.header.splice(self.device_codegen.tma_descriptor_helpers())
|
| 439 |
+
|
| 440 |
+
def write_get_raw_stream(self, device_idx: int, graph_name: str) -> str:
|
| 441 |
+
name = f"stream{device_idx}"
|
| 442 |
+
self.writeline(
|
| 443 |
+
maybe_hipify_code_wrapper(
|
| 444 |
+
f"{self.device_codegen.cpp_stream_type()} {name};"
|
| 445 |
+
)
|
| 446 |
+
)
|
| 447 |
+
self.writeline(
|
| 448 |
+
f"AOTI_TORCH_ERROR_CODE_CHECK({self.device_codegen.aoti_get_stream()}({device_idx}, (void**)&{name}));"
|
| 449 |
+
)
|
| 450 |
+
return name
|
| 451 |
+
|
| 452 |
+
def get_autotuning_input_name(self, idx):
|
| 453 |
+
return f"{self.autotune_input_prefix}_{idx}"
|
| 454 |
+
|
| 455 |
+
def codegen_inputs(self):
|
| 456 |
+
# See Note: [Input Alignment handling in Inductor]
|
| 457 |
+
#
|
| 458 |
+
# JIT Inductor does not guard on input alignment. It relies on copy_misaligned_inputs to
|
| 459 |
+
# copy misaligned inputs to aligned buffers. For AOTInductor, we need to do the same in cpp.
|
| 460 |
+
|
| 461 |
+
if config.is_fbcode():
|
| 462 |
+
# TODO: This is added because FC. Remove this once the newly added shim symbols,
|
| 463 |
+
# e.g. aoti_torch_clone_preserve_strides, have landed
|
| 464 |
+
return super().codegen_inputs()
|
| 465 |
+
|
| 466 |
+
if V.graph.aot_mode and V.graph.inputs_to_check:
|
| 467 |
+
for idx in V.graph.inputs_to_check:
|
| 468 |
+
input_name = V.graph.graph_input_names[idx]
|
| 469 |
+
assert input_name in V.graph.graph_inputs, (
|
| 470 |
+
f"{input_name} not found in graph inputs"
|
| 471 |
+
)
|
| 472 |
+
value = V.graph.graph_inputs[input_name]
|
| 473 |
+
assert isinstance(value, TensorBox), (
|
| 474 |
+
f"{input_name} is expected to be tensor but found as {type(value)}"
|
| 475 |
+
)
|
| 476 |
+
warn_msg = (
|
| 477 |
+
f"Input {idx} was compiled as {GPU_ALIGN_BYTES}-bytes aligned, "
|
| 478 |
+
"but it is not aligned at run time. Copying to an aligned tensor "
|
| 479 |
+
"to guarantee correctness, but expect a performance hit."
|
| 480 |
+
)
|
| 481 |
+
self.prefix.splice(
|
| 482 |
+
f"""
|
| 483 |
+
if ((reinterpret_cast<std::uintptr_t>({input_name}.data_ptr()) & ({GPU_ALIGN_BYTES} -1)) != 0) {{
|
| 484 |
+
AOTI_TORCH_WARN("{warn_msg}");
|
| 485 |
+
AtenTensorHandle {input_name}_aligned;
|
| 486 |
+
aoti_torch_clone_preserve_strides({input_name}, &{input_name}_aligned);
|
| 487 |
+
{input_name} = std::move(RAIIAtenTensorHandle({input_name}_aligned));
|
| 488 |
+
}}
|
| 489 |
+
"""
|
| 490 |
+
)
|
| 491 |
+
|
| 492 |
+
super().codegen_inputs()
|
| 493 |
+
|
| 494 |
+
def _define_kernel_helper(
|
| 495 |
+
self,
|
| 496 |
+
kernel_name: str,
|
| 497 |
+
kernel_body: str,
|
| 498 |
+
metadata: Optional[str] = None,
|
| 499 |
+
gpu: bool = True,
|
| 500 |
+
cpp_definition: Optional[str] = None,
|
| 501 |
+
):
|
| 502 |
+
if gpu:
|
| 503 |
+
self._kernel_name_to_body[kernel_name] = kernel_body
|
| 504 |
+
if config.triton.autotune_at_compile_time:
|
| 505 |
+
# Call PythonWrapperCodegen to create the autotune code block
|
| 506 |
+
PythonWrapperCodegen._define_kernel_helper(
|
| 507 |
+
self, kernel_name, kernel_body, metadata, gpu, cpp_definition
|
| 508 |
+
)
|
| 509 |
+
else:
|
| 510 |
+
return CppWrapperCpu._define_kernel_helper(
|
| 511 |
+
self, kernel_name, kernel_body, metadata, gpu, cpp_definition
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
def generate(self, is_inference):
|
| 515 |
+
with dynamo_timed("CppWrapperGpu.generate", log_pt2_compile_event=True):
|
| 516 |
+
return super().generate(is_inference)
|
| 517 |
+
|
| 518 |
+
def finalize_prefix(self):
|
| 519 |
+
"""Define the triton kernels now that autotuning is finished"""
|
| 520 |
+
old_prefix = self.prefix # new content should go at start of prefix
|
| 521 |
+
|
| 522 |
+
# Generating triton kernel callers can modify the prefix (cached dtypes),
|
| 523 |
+
# so do this before running finalize_prefix(), but put the generated code
|
| 524 |
+
# after the finalize_prefix() code.
|
| 525 |
+
self.prefix = IndentedBuffer()
|
| 526 |
+
for kernel in self._triton_call_wrappers.values():
|
| 527 |
+
self.prefix.writeline("\n")
|
| 528 |
+
kernel.generate(self)
|
| 529 |
+
triton_prefix = self.prefix
|
| 530 |
+
|
| 531 |
+
self.prefix = IndentedBuffer()
|
| 532 |
+
super().finalize_prefix()
|
| 533 |
+
|
| 534 |
+
self.prefix.splice(triton_prefix)
|
| 535 |
+
|
| 536 |
+
self.prefix.writeline("\n")
|
| 537 |
+
self.prefix.splice(old_prefix)
|
| 538 |
+
|
| 539 |
+
def generate_tma_descriptor(self, desc):
|
| 540 |
+
self.write_tma_descriptor_helpers_once()
|
| 541 |
+
|
| 542 |
+
if isinstance(desc, TMADescriptorExperimental):
|
| 543 |
+
self._generate_experimental_tma_descriptor(desc)
|
| 544 |
+
else:
|
| 545 |
+
assert isinstance(desc, TMADescriptorStable)
|
| 546 |
+
self._generate_stable_tma_descriptor(desc)
|
| 547 |
+
|
| 548 |
+
def _generate_experimental_tma_descriptor(self, desc):
|
| 549 |
+
# generate data pointer for the source tensor
|
| 550 |
+
source = self.generate_args_decl(
|
| 551 |
+
code=self,
|
| 552 |
+
call_args=[self.val_to_arg_str(desc.tensor)],
|
| 553 |
+
arg_types=[desc.tensor.get_dtype()],
|
| 554 |
+
arg_signatures=[None],
|
| 555 |
+
# these args are passed to initNDTMADescriptor, which is NOT a triton kernel
|
| 556 |
+
is_triton_kernel=False,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
desc_name = desc.name
|
| 560 |
+
self.writeline(f"alignas(64) CUtensorMap {desc_name};")
|
| 561 |
+
|
| 562 |
+
# `source` is in the form of `&var_x`, where `var_x` is the data pointer
|
| 563 |
+
# (CUdeviceptr); we dereference `source` and cast to `void*` to pass to
|
| 564 |
+
# the data pointer of the source tensor to the helper function
|
| 565 |
+
# `init{1,2}DTMADescriptor`
|
| 566 |
+
ptr = f"reinterpret_cast<void*>(*({source}))"
|
| 567 |
+
dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.dims)
|
| 568 |
+
block_dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.block_dims)
|
| 569 |
+
element_size = self.val_to_arg_str(desc.element_size)
|
| 570 |
+
fn = f"init{desc.rank}DTMADescriptor"
|
| 571 |
+
args = f"&{desc_name}, {ptr}, {dims}, {block_dims}, {element_size}"
|
| 572 |
+
self.writeline(f"{fn}({args});")
|
| 573 |
+
|
| 574 |
+
def _generate_stable_tma_descriptor(self, desc):
|
| 575 |
+
source = self.generate_args_decl(
|
| 576 |
+
code=self,
|
| 577 |
+
call_args=[self.val_to_arg_str(desc.tensor)],
|
| 578 |
+
arg_types=[desc.tensor.get_dtype()],
|
| 579 |
+
arg_signatures=[None],
|
| 580 |
+
# these args are passed to initNDTMADescriptor, which is NOT a triton kernel
|
| 581 |
+
is_triton_kernel=False,
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
desc_name = desc.name
|
| 585 |
+
# Pack the relevant information into a StableTMADescriptor struct.
|
| 586 |
+
# See [Note: AOTI TMA Stable handling] for more details.
|
| 587 |
+
self.writeline(f"alignas(64) StableTMADescriptor {desc_name};")
|
| 588 |
+
|
| 589 |
+
def fill_array(name, values):
|
| 590 |
+
for i, val in enumerate(values):
|
| 591 |
+
self.writeline(f"{name}[{i}] = {val};")
|
| 592 |
+
|
| 593 |
+
ptr = f"reinterpret_cast<void*>(*({source}))"
|
| 594 |
+
rank = len(desc.tensor.get_size())
|
| 595 |
+
|
| 596 |
+
fill_array(f"{desc_name}.block_shape", desc.block_shape)
|
| 597 |
+
fill_array(f"{desc_name}.global_shape", desc.tensor.get_size())
|
| 598 |
+
fill_array(f"{desc_name}.strides", desc.tensor.get_stride())
|
| 599 |
+
|
| 600 |
+
element_size = self.val_to_arg_str(desc.tensor.get_dtype().itemsize)
|
| 601 |
+
fn = "initTMADescriptor"
|
| 602 |
+
args = ", ".join(
|
| 603 |
+
str(x)
|
| 604 |
+
for x in [
|
| 605 |
+
f"&{desc_name}.m",
|
| 606 |
+
ptr,
|
| 607 |
+
element_size,
|
| 608 |
+
rank,
|
| 609 |
+
f"{desc_name}.block_shape",
|
| 610 |
+
f"{desc_name}.global_shape",
|
| 611 |
+
f"{desc_name}.strides",
|
| 612 |
+
]
|
| 613 |
+
)
|
| 614 |
+
self.writeline(f"{fn}({args});")
|
| 615 |
+
|
| 616 |
+
def generate_args_decl(
|
| 617 |
+
self,
|
| 618 |
+
code: Union[IndentedBuffer, Self],
|
| 619 |
+
call_args,
|
| 620 |
+
arg_types,
|
| 621 |
+
arg_signatures,
|
| 622 |
+
is_triton_kernel=True,
|
| 623 |
+
scratch_spaces: Optional[dict[str, int]] = None,
|
| 624 |
+
):
|
| 625 |
+
"""
|
| 626 |
+
Generates any declarations of args to pass into a kernel call, and then returns the arg names.
|
| 627 |
+
|
| 628 |
+
In more detail:
|
| 629 |
+
* declarations: e.g. this function has a side effect of generating lines like `auto var_0 = ...;`
|
| 630 |
+
* returns: a string with the list of args, e.g. "var_0, var_1"
|
| 631 |
+
|
| 632 |
+
call_args: list of call arguments
|
| 633 |
+
arg_types: list of argument types
|
| 634 |
+
arg_signatures: list with signatures of all the args
|
| 635 |
+
is_triton_kernel: whether these are passed into a triton kernel or not. In particular,
|
| 636 |
+
calls to triton kernels will have an additional global scratch space
|
| 637 |
+
arg injected at the front of the arg list.
|
| 638 |
+
"""
|
| 639 |
+
new_args: list[str] = []
|
| 640 |
+
|
| 641 |
+
# Add more cases for other types as needed
|
| 642 |
+
signature2dtype = {
|
| 643 |
+
"i32": "int32_t",
|
| 644 |
+
"i64": "int64_t",
|
| 645 |
+
"fp32": "float",
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
def signature_is_tma_desc(sig):
|
| 649 |
+
if not sig:
|
| 650 |
+
return False
|
| 651 |
+
if sig == "nvTmaDesc":
|
| 652 |
+
return True
|
| 653 |
+
if sig.startswith("tensordesc<"):
|
| 654 |
+
return True
|
| 655 |
+
return False
|
| 656 |
+
|
| 657 |
+
def process_tma_stable_arg(arg, arg_type, arg_signature, var_name):
|
| 658 |
+
# [Note: AOTI TMA Stable handling]
|
| 659 |
+
# For most args, a single arg passed to the python triton interface
|
| 660 |
+
# maps to a single arg in the cubin interface. However, for host-side
|
| 661 |
+
# TMA descriptors, a single python arg turns into 1 + 2 * N args in the
|
| 662 |
+
# cubin interface (where N is the rank).
|
| 663 |
+
#
|
| 664 |
+
# To do this: at TMA codegen time (for aoti), we generate a struct
|
| 665 |
+
# (StableTMADescriptor) containing the necessary information; and then
|
| 666 |
+
# when we call the function (i.e. here), we unpack the struct members.
|
| 667 |
+
code.writeline(f"auto {var_name} = {cexpr(arg)};")
|
| 668 |
+
|
| 669 |
+
result = []
|
| 670 |
+
result.append(f"&{var_name}.m")
|
| 671 |
+
|
| 672 |
+
# from https://github.com/triton-lang/triton/blob/16961b79bdac1b774b42d44e52fd55a266ec2866/third_party/nvidia/backend/driver.py#L111 # noqa: B950
|
| 673 |
+
match = re.match("tensordesc<([^[>]*)\\[([^]]*)\\]", arg_signature)
|
| 674 |
+
assert match is not None
|
| 675 |
+
shape = match.group(2)
|
| 676 |
+
ndim = shape.count(",") + 1
|
| 677 |
+
|
| 678 |
+
for i in range(ndim):
|
| 679 |
+
result.append(f"&{var_name}.block_shape[{i}]")
|
| 680 |
+
|
| 681 |
+
for i in range(ndim):
|
| 682 |
+
result.append(f"&{var_name}.strides[{i}]")
|
| 683 |
+
|
| 684 |
+
return result
|
| 685 |
+
|
| 686 |
+
def process_args(arg, arg_type, arg_signature=None):
|
| 687 |
+
var_name = f"var_{next(self.arg_var_id)}"
|
| 688 |
+
# ignore tma descriptors, as host-side TMA descriptors need
|
| 689 |
+
# to be passed to the compiled Triton kernel by value
|
| 690 |
+
if isinstance(arg_type, UnwrapUnspecArg) and not signature_is_tma_desc(
|
| 691 |
+
arg_signature
|
| 692 |
+
):
|
| 693 |
+
self.codegen_tensor_item(
|
| 694 |
+
arg_type.dtype,
|
| 695 |
+
arg,
|
| 696 |
+
var_name,
|
| 697 |
+
indented_buffer=code,
|
| 698 |
+
)
|
| 699 |
+
new_args.append(f"&{var_name}")
|
| 700 |
+
elif isinstance(arg_type, torch_dtype) and not signature_is_tma_desc(
|
| 701 |
+
arg_signature
|
| 702 |
+
):
|
| 703 |
+
device_ptr_type = self.device_codegen.cpp_device_ptr()
|
| 704 |
+
code.writeline(
|
| 705 |
+
maybe_hipify_code_wrapper(
|
| 706 |
+
f"{device_ptr_type} {var_name} = reinterpret_cast<{device_ptr_type}>({arg}.data_ptr());"
|
| 707 |
+
)
|
| 708 |
+
)
|
| 709 |
+
new_args.append(f"&{var_name}")
|
| 710 |
+
# For symbolic call arguments, examine the arg signatures from triton meta
|
| 711 |
+
# to explicitly cast to the right type
|
| 712 |
+
# Reason: `auto` can infer unexpected type against kernel input signature.
|
| 713 |
+
elif (
|
| 714 |
+
isinstance(arg_type, type(SymbolicCallArg))
|
| 715 |
+
and arg_signature is not None
|
| 716 |
+
and arg_signature in signature2dtype
|
| 717 |
+
):
|
| 718 |
+
code.writeline(
|
| 719 |
+
f"{signature2dtype[arg_signature]} {var_name} = {cexpr(arg)};"
|
| 720 |
+
)
|
| 721 |
+
new_args.append(f"&{var_name}")
|
| 722 |
+
elif arg_type in (sympy.Integer, int):
|
| 723 |
+
code.writeline(f"int {var_name} = {cexpr(arg)};")
|
| 724 |
+
new_args.append(f"&{var_name}")
|
| 725 |
+
elif arg_type in (sympy.Float, float):
|
| 726 |
+
code.writeline(f"float {var_name} = {cexpr(arg)};")
|
| 727 |
+
new_args.append(f"&{var_name}")
|
| 728 |
+
elif arg_signature and arg_signature.startswith("tensordesc<"):
|
| 729 |
+
new_args.extend(
|
| 730 |
+
process_tma_stable_arg(arg, arg_type, arg_signature, var_name)
|
| 731 |
+
)
|
| 732 |
+
else:
|
| 733 |
+
code.writeline(f"auto {var_name} = {cexpr(arg)};")
|
| 734 |
+
new_args.append(f"&{var_name}")
|
| 735 |
+
|
| 736 |
+
for arg, arg_type, arg_signature in zip_longest(
|
| 737 |
+
call_args, arg_types, arg_signatures
|
| 738 |
+
):
|
| 739 |
+
process_args(arg, arg_type, arg_signature)
|
| 740 |
+
|
| 741 |
+
for scratch_name, workspace_size in (scratch_spaces or {}).items():
|
| 742 |
+
if (
|
| 743 |
+
is_triton_kernel
|
| 744 |
+
and (
|
| 745 |
+
scratch := self.device_codegen.cpp_scratch(
|
| 746 |
+
next(self.arg_var_id),
|
| 747 |
+
workspace=TritonScratchWorkspace(
|
| 748 |
+
size=workspace_size,
|
| 749 |
+
generate_dtype_str=(
|
| 750 |
+
lambda: self.codegen_dtype(torch.uint8)
|
| 751 |
+
),
|
| 752 |
+
),
|
| 753 |
+
prefix=scratch_name,
|
| 754 |
+
)
|
| 755 |
+
)
|
| 756 |
+
is not None
|
| 757 |
+
):
|
| 758 |
+
scratch_def, scratch_var = scratch
|
| 759 |
+
code.writelines([maybe_hipify_code_wrapper(x) for x in scratch_def])
|
| 760 |
+
new_args.append(f"&{scratch_var}")
|
| 761 |
+
|
| 762 |
+
return ", ".join(new_args)
|
| 763 |
+
|
| 764 |
+
def _generate_kernel_call_helper(
|
| 765 |
+
self,
|
| 766 |
+
kernel_name: str,
|
| 767 |
+
call_args,
|
| 768 |
+
*,
|
| 769 |
+
device=None,
|
| 770 |
+
triton=True,
|
| 771 |
+
arg_types=None,
|
| 772 |
+
raw_keys=None,
|
| 773 |
+
raw_args=None,
|
| 774 |
+
triton_meta=None,
|
| 775 |
+
graph_name="",
|
| 776 |
+
original_fxnode_name=None,
|
| 777 |
+
):
|
| 778 |
+
"""
|
| 779 |
+
Override the default value of argument 'gpu' to True here.
|
| 780 |
+
generate_kernel_call can still be called with gpu=False because of
|
| 781 |
+
a mix of cpu kernels and gpu kernels.
|
| 782 |
+
"""
|
| 783 |
+
device = device or V.graph.get_current_device_or_throw()
|
| 784 |
+
if device.type == "cpu":
|
| 785 |
+
# Even in CppWrapperGpu, we may see cpp kernels
|
| 786 |
+
return CppWrapperCpu._generate_kernel_call_helper(
|
| 787 |
+
self,
|
| 788 |
+
kernel_name,
|
| 789 |
+
call_args,
|
| 790 |
+
device=device,
|
| 791 |
+
triton=triton,
|
| 792 |
+
arg_types=arg_types,
|
| 793 |
+
raw_keys=raw_keys,
|
| 794 |
+
raw_args=raw_args,
|
| 795 |
+
triton_meta=triton_meta,
|
| 796 |
+
)
|
| 797 |
+
|
| 798 |
+
if (
|
| 799 |
+
triton
|
| 800 |
+
and config.triton.autotune_at_compile_time
|
| 801 |
+
and kernel_name not in self.kernel_autotune_names
|
| 802 |
+
):
|
| 803 |
+
# Call PythonWrapperCodegen to create the autotune code block
|
| 804 |
+
PythonWrapperCodegen._generate_kernel_call_helper(
|
| 805 |
+
self,
|
| 806 |
+
kernel_name,
|
| 807 |
+
call_args,
|
| 808 |
+
device=device,
|
| 809 |
+
triton=triton,
|
| 810 |
+
arg_types=arg_types,
|
| 811 |
+
raw_keys=raw_keys,
|
| 812 |
+
raw_args=raw_args,
|
| 813 |
+
triton_meta=triton_meta,
|
| 814 |
+
original_fxnode_name=original_fxnode_name,
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
stream = (
|
| 818 |
+
"stream"
|
| 819 |
+
if V.graph.aot_mode
|
| 820 |
+
else self.write_get_raw_stream(device.index, graph_name)
|
| 821 |
+
)
|
| 822 |
+
|
| 823 |
+
if triton:
|
| 824 |
+
call_args, arg_types = self.prepare_triton_wrapper_args(
|
| 825 |
+
call_args,
|
| 826 |
+
# pyrefly: ignore [bad-argument-type]
|
| 827 |
+
arg_types,
|
| 828 |
+
)
|
| 829 |
+
wrapper_name = f"call_{kernel_name}"
|
| 830 |
+
if wrapper_name not in self._triton_call_wrappers:
|
| 831 |
+
self._triton_call_wrappers[wrapper_name] = DeferredTritonCallWrapper(
|
| 832 |
+
wrapper_name,
|
| 833 |
+
kernel_name,
|
| 834 |
+
self._kernel_name_to_body,
|
| 835 |
+
arg_types,
|
| 836 |
+
)
|
| 837 |
+
device_idx = "this->device_idx_" if V.graph.aot_mode else str(device.index)
|
| 838 |
+
call_args.append(device_idx)
|
| 839 |
+
call_args.append(stream)
|
| 840 |
+
if V.graph.aot_mode:
|
| 841 |
+
call_args.append("kernels")
|
| 842 |
+
call_args.append("this->cubin_dir_")
|
| 843 |
+
debug_printer_manager = V.graph.wrapper_code.debug_printer
|
| 844 |
+
debug_printer_manager.set_printer_args(
|
| 845 |
+
call_args[: len(arg_types)], kernel_name, arg_types, None
|
| 846 |
+
)
|
| 847 |
+
with debug_printer_manager:
|
| 848 |
+
self.writeline(f"{wrapper_name}({', '.join(call_args)});")
|
| 849 |
+
else:
|
| 850 |
+
casted = []
|
| 851 |
+
# pyrefly: ignore [no-matching-overload]
|
| 852 |
+
for arg_type, arg in zip(arg_types, call_args):
|
| 853 |
+
new_arg = arg
|
| 854 |
+
if arg_type.endswith("*") and arg != "nullptr":
|
| 855 |
+
new_arg = f"{arg}.data_ptr()"
|
| 856 |
+
# pyrefly: ignore [bad-argument-type]
|
| 857 |
+
casted.append(f"({arg_type}){cexpr(new_arg)}")
|
| 858 |
+
call_args_str = ", ".join(casted)
|
| 859 |
+
self.writeline(f"kernels.{kernel_name}({call_args_str}, {stream});")
|
| 860 |
+
|
| 861 |
+
@staticmethod
|
| 862 |
+
def prepare_triton_wrapper_args(
|
| 863 |
+
call_args: list[Any], arg_types: list[Any]
|
| 864 |
+
) -> tuple[list[Any], list[Any]]:
|
| 865 |
+
assert len(call_args) == len(arg_types), (call_args, arg_types)
|
| 866 |
+
new_args = []
|
| 867 |
+
new_args_types = []
|
| 868 |
+
for arg, arg_type in zip(call_args, arg_types):
|
| 869 |
+
if isinstance(arg, str):
|
| 870 |
+
if isinstance(arg_type, torch_dtype) and should_unwrap_unspec_arg(arg):
|
| 871 |
+
# dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar
|
| 872 |
+
arg_type = UnwrapUnspecArg(dtype=arg_type)
|
| 873 |
+
new_args.append(arg)
|
| 874 |
+
elif isinstance(arg, bool):
|
| 875 |
+
new_args.append(str(arg).lower())
|
| 876 |
+
elif isinstance(arg, (int, float, SymbolicCallArg)):
|
| 877 |
+
new_args.append(str(arg))
|
| 878 |
+
else:
|
| 879 |
+
new_args.append(cexpr(V.graph.sizevars.simplify(arg)))
|
| 880 |
+
new_args_types.append(arg_type)
|
| 881 |
+
return new_args, new_args_types
|
| 882 |
+
|
| 883 |
+
def make_zero_buffer(self, name):
|
| 884 |
+
return f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_zero_({name}.get()));"
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
@dataclasses.dataclass
|
| 888 |
+
class UnwrapUnspecArg:
|
| 889 |
+
"""Marker that we need to call .item() on the tensor"""
|
| 890 |
+
|
| 891 |
+
dtype: torch_dtype
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
|
| 3 |
+
import sympy
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.utils._ordered_set import OrderedSet
|
| 7 |
+
|
| 8 |
+
from ..ir import GraphPartitionSignature
|
| 9 |
+
from ..virtualized import V
|
| 10 |
+
from .cpp_wrapper_cpu import CppWrapperCpu
|
| 11 |
+
from .cpp_wrapper_gpu import CppWrapperGpu
|
| 12 |
+
from .wrapper import KernelCallLine, PythonWrapperCodegen
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class CppWrapperMps(CppWrapperGpu):
|
| 16 |
+
"""
|
| 17 |
+
Generates cpp wrapper for running on MPS and calls metal kernels
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
def __init__(self) -> None:
|
| 21 |
+
super().__init__()
|
| 22 |
+
self._used_kernel_names: OrderedSet[str] = OrderedSet()
|
| 23 |
+
self._lambda_counter: int = 0
|
| 24 |
+
|
| 25 |
+
@staticmethod
|
| 26 |
+
def create(
|
| 27 |
+
is_subgraph: bool,
|
| 28 |
+
subgraph_name: Optional[str],
|
| 29 |
+
parent_wrapper: Optional[PythonWrapperCodegen],
|
| 30 |
+
partition_signatures: Optional[GraphPartitionSignature] = None,
|
| 31 |
+
) -> "CppWrapperMps":
|
| 32 |
+
return CppWrapperMps()
|
| 33 |
+
|
| 34 |
+
def _generate_kernel_call_helper(
|
| 35 |
+
self,
|
| 36 |
+
kernel_name: str,
|
| 37 |
+
call_args: list[str],
|
| 38 |
+
*,
|
| 39 |
+
device: Optional[torch.device] = None,
|
| 40 |
+
triton: bool = True,
|
| 41 |
+
arg_types: Optional[tuple[Any, ...]] = None,
|
| 42 |
+
raw_keys: Optional[tuple[Any, ...]] = None,
|
| 43 |
+
raw_args: Optional[tuple[Any, ...]] = None,
|
| 44 |
+
triton_meta: Optional[dict[str, Any]] = None,
|
| 45 |
+
graph_name: str = "",
|
| 46 |
+
original_fxnode_name: Optional[str] = None,
|
| 47 |
+
) -> None:
|
| 48 |
+
"""
|
| 49 |
+
Generates MPS kernel call code. It should look something like:
|
| 50 |
+
```
|
| 51 |
+
auto mps_lib_0_lambda = [&](AOTIMetalKernelFunctionHandle handle) {
|
| 52 |
+
aoti_torch_mps_start_encoding(handle);
|
| 53 |
+
aoti_torch_mps_set_arg_tensor(handle, 0, buf0);
|
| 54 |
+
aoti_torch_mps_set_arg_tensor(handle, 1, arg0_1);
|
| 55 |
+
aoti_torch_mps_set_arg_tensor(handle, 2, arg1_1);
|
| 56 |
+
aoti_torch_mps_dispatch_single(handle, static_cast<uint64_t>(10LL));
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
std::function<void(AOTIMetalKernelFunctionHandle)> mps_lib_0_func_wrapper = mps_lib_0_lambda;
|
| 60 |
+
aoti_torch_mps_run_command_block(get_mps_lib_0_handle(), aoti_torch_mps_shared_callback, &mps_lib_0_func_wrapper);
|
| 61 |
+
```
|
| 62 |
+
"""
|
| 63 |
+
device = device or V.graph.get_current_device_or_throw()
|
| 64 |
+
if device.type == "cpu":
|
| 65 |
+
# Even in CppWrapperGpu, we may see cpp kernels
|
| 66 |
+
return CppWrapperCpu._generate_kernel_call_helper(
|
| 67 |
+
self,
|
| 68 |
+
kernel_name,
|
| 69 |
+
call_args,
|
| 70 |
+
device=device,
|
| 71 |
+
triton=triton,
|
| 72 |
+
arg_types=arg_types,
|
| 73 |
+
raw_keys=raw_keys,
|
| 74 |
+
raw_args=raw_args,
|
| 75 |
+
triton_meta=triton_meta,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
assert device.type == "mps"
|
| 79 |
+
|
| 80 |
+
assert arg_types is not None
|
| 81 |
+
|
| 82 |
+
new_args = []
|
| 83 |
+
for idx, (arg, arg_type) in enumerate(zip(call_args[:-2], arg_types[:-2])):
|
| 84 |
+
if isinstance(arg_type, torch.dtype):
|
| 85 |
+
new_args.append(f"aoti_torch_mps_set_arg_tensor(handle, {idx}, {arg});")
|
| 86 |
+
elif arg_type in (int, sympy.core.symbol.Symbol):
|
| 87 |
+
new_args.append(f"aoti_torch_mps_set_arg_int(handle, {idx}, {arg});")
|
| 88 |
+
else:
|
| 89 |
+
raise NotImplementedError(
|
| 90 |
+
f"Unsupported arg type {arg_type} for arg {arg} for kernel {kernel_name}"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
threads, group_size = call_args[-2], call_args[-1]
|
| 94 |
+
if threads is None:
|
| 95 |
+
raise NotImplementedError("No threads or group_size provided")
|
| 96 |
+
|
| 97 |
+
# Check if threads is a single value or an array-like structure
|
| 98 |
+
threads_str = str(threads)
|
| 99 |
+
is_single_value = (
|
| 100 |
+
threads_str.startswith("{")
|
| 101 |
+
and threads_str.endswith("}")
|
| 102 |
+
and threads_str.count(",") == 0
|
| 103 |
+
) or not threads_str.startswith(("{", "["))
|
| 104 |
+
|
| 105 |
+
if is_single_value:
|
| 106 |
+
# Extract single value from braces if present
|
| 107 |
+
if threads_str.startswith("{") and threads_str.endswith("}"):
|
| 108 |
+
single_value = threads_str[1:-1].strip() # Remove braces
|
| 109 |
+
else:
|
| 110 |
+
single_value = threads_str
|
| 111 |
+
|
| 112 |
+
if group_size is None:
|
| 113 |
+
new_args.append(
|
| 114 |
+
f"aoti_torch_mps_dispatch_single(handle, {single_value});"
|
| 115 |
+
)
|
| 116 |
+
else:
|
| 117 |
+
# Extract group size value if it's also in braces
|
| 118 |
+
group_size_str = str(group_size)
|
| 119 |
+
if group_size_str.startswith("{") and group_size_str.endswith("}"):
|
| 120 |
+
group_size_value = group_size_str[1:-1].strip()
|
| 121 |
+
else:
|
| 122 |
+
group_size_value = group_size_str
|
| 123 |
+
new_args.append(
|
| 124 |
+
f"aoti_torch_mps_dispatch_single_with_group_size(handle, {single_value}, {group_size_value});"
|
| 125 |
+
)
|
| 126 |
+
else:
|
| 127 |
+
# Handle array case - need to convert initializer list to array
|
| 128 |
+
# Use kernel name to make variable names unique
|
| 129 |
+
threads_var = f"{kernel_name}_threads_array"
|
| 130 |
+
group_size_var = f"{kernel_name}_group_size_array"
|
| 131 |
+
|
| 132 |
+
# Extract array size from the initializer list string
|
| 133 |
+
def get_array_size(array_str: str) -> int:
|
| 134 |
+
# Remove braces and whitespace
|
| 135 |
+
content = array_str.strip()
|
| 136 |
+
if content.startswith("{") and content.endswith("}"):
|
| 137 |
+
content = content[1:-1].strip()
|
| 138 |
+
|
| 139 |
+
if not content: # Empty array
|
| 140 |
+
return 0
|
| 141 |
+
|
| 142 |
+
# Count elements by counting commas, accounting for nested structures
|
| 143 |
+
depth = 0
|
| 144 |
+
comma_count = 0
|
| 145 |
+
for char in content:
|
| 146 |
+
if char in "({[<":
|
| 147 |
+
depth += 1
|
| 148 |
+
elif char in ")}]>":
|
| 149 |
+
depth -= 1
|
| 150 |
+
elif char == "," and depth == 0:
|
| 151 |
+
comma_count += 1
|
| 152 |
+
|
| 153 |
+
return comma_count + 1 # Number of elements = commas + 1
|
| 154 |
+
|
| 155 |
+
threads_size = get_array_size(threads_str)
|
| 156 |
+
|
| 157 |
+
if group_size is None:
|
| 158 |
+
new_args.append("{")
|
| 159 |
+
new_args.append(f" uint64_t {threads_var}[] = {threads};")
|
| 160 |
+
new_args.append(
|
| 161 |
+
f" aoti_torch_mps_dispatch_array(handle, {threads_var}, {threads_size});"
|
| 162 |
+
)
|
| 163 |
+
new_args.append("}")
|
| 164 |
+
else:
|
| 165 |
+
group_size_str = str(group_size)
|
| 166 |
+
group_size_size = get_array_size(group_size_str)
|
| 167 |
+
new_args.append("{")
|
| 168 |
+
new_args.append(f" uint64_t {threads_var}[] = {threads};")
|
| 169 |
+
new_args.append(f" uint64_t {group_size_var}[] = {group_size};")
|
| 170 |
+
dispatch_args = f"handle, {threads_var}, {threads_size}, {group_size_var}, {group_size_size}"
|
| 171 |
+
new_args.append(
|
| 172 |
+
f" aoti_torch_mps_dispatch_array_with_group_size({dispatch_args});"
|
| 173 |
+
)
|
| 174 |
+
new_args.append("}")
|
| 175 |
+
|
| 176 |
+
# debug printer related logic for cpp kernel type.
|
| 177 |
+
debug_printer_manager = V.graph.wrapper_code.debug_printer
|
| 178 |
+
debug_printer_manager.set_printer_args(
|
| 179 |
+
call_args[:-2],
|
| 180 |
+
kernel_name,
|
| 181 |
+
None,
|
| 182 |
+
None,
|
| 183 |
+
"cpp",
|
| 184 |
+
)
|
| 185 |
+
with debug_printer_manager:
|
| 186 |
+
self.write_mps_kernel_call(kernel_name, new_args)
|
| 187 |
+
|
| 188 |
+
def write_mps_kernel_call(self, name: str, call_args: list[str]) -> None:
|
| 189 |
+
# Generate unique variable names to avoid duplicate declarations
|
| 190 |
+
# when the same MPS lib is used multiple times
|
| 191 |
+
unique_suffix = self._lambda_counter
|
| 192 |
+
self._lambda_counter += 1
|
| 193 |
+
|
| 194 |
+
lambda_name = f"{name}_lambda_{unique_suffix}"
|
| 195 |
+
wrapper_name = f"{name}_func_wrapper_{unique_suffix}"
|
| 196 |
+
|
| 197 |
+
# Generate the function call code (in current location)
|
| 198 |
+
# Create lambda that captures by reference and pass its pointer through void*
|
| 199 |
+
self.writeline(
|
| 200 |
+
f"auto {lambda_name} = [&](AOTIMetalKernelFunctionHandle handle) {{"
|
| 201 |
+
)
|
| 202 |
+
self.writeline(" aoti_torch_mps_start_encoding(handle);")
|
| 203 |
+
|
| 204 |
+
# Output call args directly since we're capturing by reference
|
| 205 |
+
for call_arg in call_args:
|
| 206 |
+
self.writeline(f" {call_arg}")
|
| 207 |
+
self.writeline("};")
|
| 208 |
+
self.writeline("")
|
| 209 |
+
|
| 210 |
+
# Pass lambda pointer through void*
|
| 211 |
+
self.writeline(
|
| 212 |
+
f"std::function<void(AOTIMetalKernelFunctionHandle)> {wrapper_name} = {lambda_name};"
|
| 213 |
+
)
|
| 214 |
+
self.writeline(
|
| 215 |
+
f"aoti_torch_mps_run_command_block(get_{name}_handle(), aoti_torch_mps_shared_callback, &{wrapper_name});"
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def get_device_include_path(device: str) -> str:
|
| 220 |
+
assert V.graph.aot_mode
|
| 221 |
+
return (
|
| 222 |
+
"#include <torch/csrc/inductor/aoti_include/mps.h>\n"
|
| 223 |
+
"#include <torch/csrc/inductor/aoti_torch/c/shim_mps.h>"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
def codegen_additional_funcs(self) -> None:
|
| 227 |
+
"""
|
| 228 |
+
Generate thread-safe lazy singleton pattern for MPS shader libraries with RAII cleanup.
|
| 229 |
+
|
| 230 |
+
The generated code will look like:
|
| 231 |
+
```
|
| 232 |
+
AOTIMetalKernelFunctionHandle get_mps_lib_0_handle() {
|
| 233 |
+
static auto kernel_handle = []() {
|
| 234 |
+
AOTIMetalShaderLibraryHandle lib_handle = nullptr;
|
| 235 |
+
AOTIMetalKernelFunctionHandle kern_handle = nullptr;
|
| 236 |
+
|
| 237 |
+
aoti_torch_mps_create_shader_library(mps_lib_0_source, &lib_handle);
|
| 238 |
+
aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle);
|
| 239 |
+
|
| 240 |
+
// RAII wrapper with custom deleter
|
| 241 |
+
auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) {
|
| 242 |
+
if (h) aoti_torch_mps_delete_shader_library(h);
|
| 243 |
+
};
|
| 244 |
+
|
| 245 |
+
using LibDeleter = decltype(lib_deleter);
|
| 246 |
+
using LibPtr = std::unique_ptr<AOTIMetalShaderLibraryOpaque, LibDeleter>;
|
| 247 |
+
|
| 248 |
+
// Return pair of kernel handle and library smart pointer for cleanup
|
| 249 |
+
return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter));
|
| 250 |
+
}();
|
| 251 |
+
return kernel_handle.first;
|
| 252 |
+
}
|
| 253 |
+
```
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
# Add shimified handles and functions
|
| 257 |
+
shader_libraries: OrderedSet[str] = OrderedSet()
|
| 258 |
+
for line in self.lines:
|
| 259 |
+
if not isinstance(line, KernelCallLine):
|
| 260 |
+
continue
|
| 261 |
+
if line.device.type != "mps":
|
| 262 |
+
continue
|
| 263 |
+
|
| 264 |
+
# Extract library name from kernel name (e.g., "mps_lib_0" from kernel calls)
|
| 265 |
+
if line.kernel_name not in self._used_kernel_names:
|
| 266 |
+
self._used_kernel_names.add(line.kernel_name)
|
| 267 |
+
shader_libraries.add(line.kernel_name)
|
| 268 |
+
|
| 269 |
+
# NOTE: For shimified version, we expect the shader source constant to be generated
|
| 270 |
+
# by the existing MPS shader generation process, but instead of instantiating the
|
| 271 |
+
# DynamicMetalShaderLibrary directly, we'll use our shim functions.
|
| 272 |
+
# The existing codegen should produce something like:
|
| 273 |
+
# const char* mps_lib_0_source = R"MTL(...shader_source...)MTL";
|
| 274 |
+
# instead of:
|
| 275 |
+
# at::native::mps::DynamicMetalShaderLibrary mps_lib_0(R"MTL(...shader_source...)MTL");
|
| 276 |
+
|
| 277 |
+
# Generate thread-safe lazy singleton with RAII for each library
|
| 278 |
+
for lib_name in shader_libraries:
|
| 279 |
+
self.prefix.splice(f"""
|
| 280 |
+
AOTIMetalKernelFunctionHandle get_{lib_name}_handle() {{
|
| 281 |
+
static auto kernel_handle = []() {{
|
| 282 |
+
AOTIMetalShaderLibraryHandle lib_handle = nullptr;
|
| 283 |
+
AOTIMetalKernelFunctionHandle kern_handle = nullptr;
|
| 284 |
+
|
| 285 |
+
aoti_torch_mps_create_shader_library({lib_name}_source, &lib_handle);
|
| 286 |
+
aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle);
|
| 287 |
+
|
| 288 |
+
// RAII wrapper with custom deleter
|
| 289 |
+
auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) {{
|
| 290 |
+
if (h) aoti_torch_mps_delete_shader_library(h);
|
| 291 |
+
}};
|
| 292 |
+
|
| 293 |
+
using LibDeleter = decltype(lib_deleter);
|
| 294 |
+
using LibPtr = std::unique_ptr<AOTIMetalShaderLibraryOpaque, LibDeleter>;
|
| 295 |
+
|
| 296 |
+
// Return pair of kernel handle and library smart pointer for cleanup
|
| 297 |
+
return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter));
|
| 298 |
+
}}();
|
| 299 |
+
return kernel_handle.first;
|
| 300 |
+
}}
|
| 301 |
+
""")
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from textwrap import dedent
|
| 4 |
+
|
| 5 |
+
from .common import DeviceOpOverrides, register_device_op_overrides
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class CpuDeviceOpOverrides(DeviceOpOverrides):
|
| 9 |
+
def import_get_raw_stream_as(self, name: str) -> str:
|
| 10 |
+
return dedent(
|
| 11 |
+
"""
|
| 12 |
+
def get_raw_stream(_):
|
| 13 |
+
return 0
|
| 14 |
+
"""
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
def cpp_kernel_type(self) -> str:
|
| 18 |
+
return "void*"
|
| 19 |
+
|
| 20 |
+
def set_device(self, device_idx: int) -> str:
|
| 21 |
+
return "pass"
|
| 22 |
+
|
| 23 |
+
def synchronize(self) -> str:
|
| 24 |
+
return "pass"
|
| 25 |
+
|
| 26 |
+
def device_guard(self, device_idx: int) -> str:
|
| 27 |
+
return "pass"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
register_device_op_overrides("cpu", CpuDeviceOpOverrides())
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_cpp_scheduling.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import hashlib
|
| 3 |
+
import logging
|
| 4 |
+
from collections.abc import Sequence
|
| 5 |
+
from typing import cast
|
| 6 |
+
|
| 7 |
+
from torch._inductor.codegen.cuda.cutlass_python_evt import (
|
| 8 |
+
CutlassEVTCodegen,
|
| 9 |
+
MockCutlassHandler,
|
| 10 |
+
)
|
| 11 |
+
from torch._inductor.utils import Placeholder
|
| 12 |
+
from torch.utils._ordered_set import OrderedSet
|
| 13 |
+
|
| 14 |
+
from ...._dynamo.utils import counters
|
| 15 |
+
from ... import config
|
| 16 |
+
from ...codecache import code_hash, get_path
|
| 17 |
+
from ...ir import Buffer, ComputedBuffer, CUDATemplateBuffer, Pointwise
|
| 18 |
+
from ...scheduler import (
|
| 19 |
+
BaseSchedulerNode,
|
| 20 |
+
BaseScheduling,
|
| 21 |
+
FusedSchedulerNode,
|
| 22 |
+
SchedulerNode,
|
| 23 |
+
WhyNoFuse,
|
| 24 |
+
)
|
| 25 |
+
from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product
|
| 26 |
+
from ...virtualized import V
|
| 27 |
+
from ..common import BackendFeature, IndentedBuffer
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
log = logging.getLogger(__name__)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class WhyNoFuseNames(WhyNoFuse):
|
| 34 |
+
def __init__(self, name1: str, name2: str) -> None:
|
| 35 |
+
self.name1 = name1
|
| 36 |
+
self.name2 = name2
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class CUDACPPScheduling(BaseScheduling):
|
| 40 |
+
"""
|
| 41 |
+
Partial Scheduling implementation for CUDA C++ Kernels.
|
| 42 |
+
This class is intended to be used in combination with TritonScheduling,
|
| 43 |
+
and delegated to by CUDACombinedScheduling.
|
| 44 |
+
|
| 45 |
+
It handles fusion decisions and CUDA C++ specific template code generation.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def get_backend_features(cls, device) -> OrderedSet[BackendFeature]:
|
| 50 |
+
return OrderedSet()
|
| 51 |
+
|
| 52 |
+
def group_fn(self, sizes):
|
| 53 |
+
return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes)
|
| 54 |
+
|
| 55 |
+
@staticmethod
|
| 56 |
+
def is_cuda_cpp_template(node: BaseSchedulerNode) -> bool:
|
| 57 |
+
return isinstance(node, SchedulerNode) and isinstance(
|
| 58 |
+
node.node, CUDATemplateBuffer
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def is_cuda_cpp_fused_template(self, node: BaseSchedulerNode) -> bool:
|
| 62 |
+
return isinstance(node, FusedSchedulerNode) and self.is_cuda_cpp_template(node)
|
| 63 |
+
|
| 64 |
+
def can_fuse_vertical(
|
| 65 |
+
self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
|
| 66 |
+
) -> bool:
|
| 67 |
+
if self.is_cuda_cpp_template(node1) and isinstance(node2, BaseSchedulerNode):
|
| 68 |
+
assert node1.node, "node1.node should not be None"
|
| 69 |
+
return self._can_fuse_epilogue_impl(
|
| 70 |
+
cast(CUDATemplateBuffer, node1.node),
|
| 71 |
+
[],
|
| 72 |
+
node2, # type: ignore[arg-type]
|
| 73 |
+
)
|
| 74 |
+
elif self.is_cuda_cpp_fused_template(node1) and isinstance(
|
| 75 |
+
node2, BaseSchedulerNode
|
| 76 |
+
):
|
| 77 |
+
assert node1.node, "node1.node should not be None"
|
| 78 |
+
assert node2.node, "node2.node should not be None"
|
| 79 |
+
fnode1 = cast(FusedSchedulerNode, node1)
|
| 80 |
+
return self._can_fuse_epilogue_impl(
|
| 81 |
+
fnode1.get_template_node(), # type: ignore[arg-type]
|
| 82 |
+
self._unwrap_epilogue_nodes(fnode1),
|
| 83 |
+
node2, # type: ignore[arg-type]
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
def define_kernel(self, src_code: str, node_schedule) -> str:
|
| 89 |
+
wrapper = V.graph.wrapper_code
|
| 90 |
+
if src_code in wrapper.src_to_kernel:
|
| 91 |
+
kernel_name = wrapper.src_to_kernel[src_code]
|
| 92 |
+
else:
|
| 93 |
+
fused_name = (
|
| 94 |
+
get_fused_kernel_name(node_schedule, config.triton.descriptive_names)
|
| 95 |
+
if config.triton.descriptive_names
|
| 96 |
+
else ""
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
# use the original src_code as the key
|
| 100 |
+
kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8]
|
| 101 |
+
if fused_name == "fused":
|
| 102 |
+
# no EVT kernel, use the original kernel name
|
| 103 |
+
kernel_name = f"cutlass_{kernel_hash}"
|
| 104 |
+
else:
|
| 105 |
+
kernel_name = f"cutlass_{fused_name}_{kernel_hash}"
|
| 106 |
+
wrapper.src_to_kernel[src_code] = kernel_name
|
| 107 |
+
src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name)
|
| 108 |
+
|
| 109 |
+
_, _, kernel_path = get_path(code_hash(src_code), "py")
|
| 110 |
+
|
| 111 |
+
compile_wrapper = IndentedBuffer()
|
| 112 |
+
compile_wrapper.writeline("async_compile.cuda(r'''")
|
| 113 |
+
compile_wrapper.splice(src_code, strip=True)
|
| 114 |
+
compile_wrapper.writeline(
|
| 115 |
+
f"''', 'so', aot_compile={str(V.graph.aot_mode)})"
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
metadata_comment = f"# kernel path: {kernel_path}"
|
| 119 |
+
origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
|
| 120 |
+
metadata_comment += "\n" + origins + "\n" + detailed_origins
|
| 121 |
+
wrapper.define_kernel(
|
| 122 |
+
kernel_name, compile_wrapper.getvalue(), metadata_comment
|
| 123 |
+
)
|
| 124 |
+
return kernel_name
|
| 125 |
+
|
| 126 |
+
def codegen_template(
|
| 127 |
+
self,
|
| 128 |
+
template_node: BaseSchedulerNode,
|
| 129 |
+
epilogue_nodes: Sequence[BaseSchedulerNode],
|
| 130 |
+
prologue_nodes: Sequence[BaseSchedulerNode],
|
| 131 |
+
):
|
| 132 |
+
"""
|
| 133 |
+
Codegen a CUDA template, possibly with fused epilogues
|
| 134 |
+
"""
|
| 135 |
+
counters["inductor"]["cuda_epilogue_fusion_counter"] += len(epilogue_nodes)
|
| 136 |
+
assert self.is_cuda_cpp_template(template_node), (
|
| 137 |
+
"Template node passed to CUDAScheduler.codegen_template must be a SchedulerNode that wraps a CUDATemplateBuffer"
|
| 138 |
+
)
|
| 139 |
+
template_node = cast(SchedulerNode, template_node)
|
| 140 |
+
_, (_numel, rnumel) = template_node.group
|
| 141 |
+
assert rnumel == 1
|
| 142 |
+
ctb: CUDATemplateBuffer = cast(CUDATemplateBuffer, template_node.node)
|
| 143 |
+
epilogue_ir_nodes: list[Buffer] = [n.node for n in epilogue_nodes] # type: ignore[misc]
|
| 144 |
+
assert all(isinstance(n, ComputedBuffer) for n in epilogue_ir_nodes), (
|
| 145 |
+
"Epilogue nodes must all be instances of ir.ComputedBuffer"
|
| 146 |
+
)
|
| 147 |
+
kernel, render = ctb.make_kernel_render( # type: ignore[misc]
|
| 148 |
+
ctb, epilogue_nodes=epilogue_nodes
|
| 149 |
+
)
|
| 150 |
+
with kernel:
|
| 151 |
+
for node in [template_node, *epilogue_nodes]:
|
| 152 |
+
node.mark_run()
|
| 153 |
+
|
| 154 |
+
# typically there is a codegen pass which runs after mark_run
|
| 155 |
+
# for this kernel we've already generated the C++ code, but we still
|
| 156 |
+
# need to let the kernel know about loads/stores that occur in the fused
|
| 157 |
+
# kernel for memory planning to properly optimize allocations
|
| 158 |
+
ctb.emulate_store_fn()
|
| 159 |
+
for node in epilogue_ir_nodes:
|
| 160 |
+
with V.set_ops_handler(MockCutlassHandler(V.get_ops_handler())):
|
| 161 |
+
assert isinstance(
|
| 162 |
+
node, ComputedBuffer
|
| 163 |
+
) # Not sure why we need to do this again
|
| 164 |
+
node.get_store_function()(CutlassEVTCodegen.get_index_vars(node))
|
| 165 |
+
|
| 166 |
+
with V.set_kernel_handler(kernel):
|
| 167 |
+
src_code = render()
|
| 168 |
+
node_schedule = [template_node, *epilogue_nodes]
|
| 169 |
+
kernel_name = self.define_kernel(src_code, node_schedule)
|
| 170 |
+
|
| 171 |
+
# debug printing values of intermediate tensors
|
| 172 |
+
_, call_args, arg_signatures, _ = kernel.args.python_argdefs()
|
| 173 |
+
debug_printer_manager = V.graph.wrapper_code.debug_printer
|
| 174 |
+
debug_printer_manager.set_printer_args(
|
| 175 |
+
call_args, kernel_name, arg_signatures, kernel
|
| 176 |
+
)
|
| 177 |
+
with debug_printer_manager:
|
| 178 |
+
self.codegen_comment(node_schedule, kernel_name)
|
| 179 |
+
kernel.call_kernel(kernel_name, ctb)
|
| 180 |
+
|
| 181 |
+
V.graph.removed_buffers |= kernel.removed_buffers
|
| 182 |
+
self.free_buffers_in_scheduler()
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
def _unwrap_epilogue_nodes(
|
| 186 |
+
fused_node: FusedSchedulerNode,
|
| 187 |
+
) -> list[BaseSchedulerNode]:
|
| 188 |
+
nodes = fused_node.get_nodes()
|
| 189 |
+
template_node = fused_node.get_template_node()
|
| 190 |
+
assert all(n.node is not None for n in nodes), (
|
| 191 |
+
"All epilogue nodes should have an IRNode"
|
| 192 |
+
)
|
| 193 |
+
# pyrefly: ignore [redundant-cast]
|
| 194 |
+
return cast(
|
| 195 |
+
list[BaseSchedulerNode], [n for n in nodes if n.node is not template_node]
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
def _can_fuse_epilogue_impl(
|
| 199 |
+
self,
|
| 200 |
+
cuda_template_buffer: CUDATemplateBuffer,
|
| 201 |
+
existing_epilogue_nodes: list[BaseSchedulerNode],
|
| 202 |
+
node_to_fuse: BaseSchedulerNode,
|
| 203 |
+
) -> bool:
|
| 204 |
+
"""
|
| 205 |
+
Check if the given node can be fused with the epilogue. At the moment, Kernels
|
| 206 |
+
support fusion with Pointwise operations, wrapped in (named) ComputedBuffer nodes.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
cuda_template_buffer : A CUDATemplateBuffer object representing the CUDA template and it's result buffer
|
| 210 |
+
existing_epilogue_nodes : List[SchedulerNode]: The list of already fused epilogue nodes.
|
| 211 |
+
node_to_fuse: The SchedulerNode node to be checked if it can be fused with the epilogue.
|
| 212 |
+
Returns:
|
| 213 |
+
- bool: True if the given node can be fused with the epilogue, False otherwise.
|
| 214 |
+
|
| 215 |
+
"""
|
| 216 |
+
why = WhyNoFuseNames(cuda_template_buffer.get_name(), node_to_fuse.get_name())
|
| 217 |
+
|
| 218 |
+
scheduler_nodes_to_fuse = node_to_fuse.get_nodes()
|
| 219 |
+
|
| 220 |
+
assert isinstance(cuda_template_buffer, CUDATemplateBuffer)
|
| 221 |
+
|
| 222 |
+
# Checks on constituent nodes
|
| 223 |
+
for s_node in scheduler_nodes_to_fuse:
|
| 224 |
+
node = s_node.node
|
| 225 |
+
|
| 226 |
+
if not isinstance(node, ComputedBuffer):
|
| 227 |
+
why(f"{node} is not a ComputedBuffer")
|
| 228 |
+
return False
|
| 229 |
+
elif not isinstance(node.data, Pointwise):
|
| 230 |
+
why(f"{node} is not a Pointwise op")
|
| 231 |
+
return False
|
| 232 |
+
elif not node.get_computed_buffer_name(): # type: ignore[attr-defined]
|
| 233 |
+
why(f"{node} does not have a computed buffer name")
|
| 234 |
+
return False
|
| 235 |
+
|
| 236 |
+
name = node.get_computed_buffer_name() # type: ignore[attr-defined]
|
| 237 |
+
# dtype can differ, and strides can differ as long as they are broadcastable
|
| 238 |
+
if node.get_size() != cuda_template_buffer.get_size():
|
| 239 |
+
why(
|
| 240 |
+
f"{name}'s size: {node.get_size()} differs from {cuda_template_buffer.get_name()}'s \
|
| 241 |
+
size: {cuda_template_buffer.get_size()}"
|
| 242 |
+
)
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
assert len(
|
| 246 |
+
existing_epilogue_nodes
|
| 247 |
+
) or cuda_template_buffer.get_name() in OrderedSet(
|
| 248 |
+
[rd.name for rd in node_to_fuse.read_writes.reads]
|
| 249 |
+
), "First epilogue node must read from cuda template buffer"
|
| 250 |
+
|
| 251 |
+
if node_to_fuse.has_aliasing_or_mutation():
|
| 252 |
+
why(f"{node_to_fuse.get_name()} has aliasing or mutation")
|
| 253 |
+
return False
|
| 254 |
+
elif node_to_fuse.is_reduction():
|
| 255 |
+
why(
|
| 256 |
+
f"{node_to_fuse.get_name()} is a reduction which is not yet supported by EVT"
|
| 257 |
+
)
|
| 258 |
+
return False
|
| 259 |
+
elif (
|
| 260 |
+
not config.cuda.cutlass_epilogue_fusion_enabled
|
| 261 |
+
or not config.epilogue_fusion
|
| 262 |
+
):
|
| 263 |
+
why("cutlass epilogue fusion is not enabled")
|
| 264 |
+
return False
|
| 265 |
+
elif not cuda_template_buffer.supports_epilogue_fusion:
|
| 266 |
+
why("epilogue fusion is only supported for TMA-enabled gemm ops")
|
| 267 |
+
return False
|
| 268 |
+
|
| 269 |
+
try:
|
| 270 |
+
from torch._inductor.codegen.cuda.cutlass_python_evt import (
|
| 271 |
+
CutlassEVTCodegen,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
CutlassEVTCodegen.ir_to_evt_python_code(
|
| 275 |
+
cuda_template_buffer.get_name(),
|
| 276 |
+
existing_epilogue_nodes + list(node_to_fuse.get_nodes()),
|
| 277 |
+
OrderedSet(),
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
except NotImplementedError as e:
|
| 281 |
+
not_implemented_op = str(e)
|
| 282 |
+
if not_implemented_op.startswith("_op_"):
|
| 283 |
+
not_implemented_op = not_implemented_op[4:]
|
| 284 |
+
why(
|
| 285 |
+
f"Cannot fuse epilogue node {node_to_fuse} into {cuda_template_buffer.name}, \
|
| 286 |
+
likely due to unsupported operation: {not_implemented_op}" # noqa: G004, B950
|
| 287 |
+
)
|
| 288 |
+
return False
|
| 289 |
+
else: # Likely due to unsupported dtype.
|
| 290 |
+
why(
|
| 291 |
+
f"Cannot fuse epilogue node {node_to_fuse} into {cuda_template_buffer.name}. \
|
| 292 |
+
Reason: {not_implemented_op}" # noqa: G004, B950
|
| 293 |
+
)
|
| 294 |
+
return False
|
| 295 |
+
|
| 296 |
+
return True
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_env.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import logging
|
| 3 |
+
import shutil
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch._inductor.utils import clear_on_fresh_cache
|
| 8 |
+
|
| 9 |
+
from ... import config
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
log = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@clear_on_fresh_cache
|
| 16 |
+
@functools.lru_cache(1)
|
| 17 |
+
def get_cuda_arch() -> Optional[str]:
|
| 18 |
+
try:
|
| 19 |
+
cuda_arch = config.cuda.arch
|
| 20 |
+
if cuda_arch is None:
|
| 21 |
+
# Get Compute Capability of the first Visible device
|
| 22 |
+
major, minor = torch.cuda.get_device_capability(0)
|
| 23 |
+
return str(major * 10 + minor)
|
| 24 |
+
return str(cuda_arch)
|
| 25 |
+
except Exception:
|
| 26 |
+
log.exception("Error getting cuda arch")
|
| 27 |
+
return None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@clear_on_fresh_cache
|
| 31 |
+
@functools.lru_cache(1)
|
| 32 |
+
def is_datacenter_blackwell_arch() -> bool:
|
| 33 |
+
arch = get_cuda_arch()
|
| 34 |
+
if arch is None:
|
| 35 |
+
return False
|
| 36 |
+
arch_number = int(arch)
|
| 37 |
+
return arch_number >= 100 and arch_number < 110
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@clear_on_fresh_cache
|
| 41 |
+
@functools.lru_cache(1)
|
| 42 |
+
def get_cuda_version() -> Optional[str]:
|
| 43 |
+
try:
|
| 44 |
+
cuda_version = config.cuda.version
|
| 45 |
+
if cuda_version is None:
|
| 46 |
+
cuda_version = torch.version.cuda
|
| 47 |
+
return cuda_version
|
| 48 |
+
except Exception:
|
| 49 |
+
log.exception("Error getting cuda version")
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@functools.cache
|
| 54 |
+
def nvcc_exist(nvcc_path: Optional[str] = "nvcc") -> bool:
|
| 55 |
+
return nvcc_path is not None and shutil.which(nvcc_path) is not None
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_kernel.py
ADDED
|
@@ -0,0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import itertools
|
| 4 |
+
import logging
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Literal, Optional, TYPE_CHECKING, Union
|
| 9 |
+
|
| 10 |
+
from sympy import Expr, symbols
|
| 11 |
+
|
| 12 |
+
import torch._inductor.config as config
|
| 13 |
+
from torch import dtype as torch_dtype
|
| 14 |
+
from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu
|
| 15 |
+
from torch._inductor.scheduler import BaseSchedulerNode
|
| 16 |
+
from torch._inductor.utils import do_bench_using_profiling, OrderedSet, Placeholder
|
| 17 |
+
from torch.utils._sympy.value_ranges import ValueRanges
|
| 18 |
+
|
| 19 |
+
from .cutlass_utils import DTYPE_TO_CUTLASS_TYPE
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from .cuda_template import ArgInfo
|
| 24 |
+
|
| 25 |
+
from ...autotune_process import CUDABenchmarkRequest
|
| 26 |
+
from ...ir import (
|
| 27 |
+
Buffer,
|
| 28 |
+
ChoiceCaller,
|
| 29 |
+
CUDATemplateBuffer,
|
| 30 |
+
IRNode,
|
| 31 |
+
Layout,
|
| 32 |
+
PrimitiveInfoType,
|
| 33 |
+
ShapeAsConstantBuffer,
|
| 34 |
+
TensorBox,
|
| 35 |
+
)
|
| 36 |
+
from ...utils import sympy_product
|
| 37 |
+
from ...virtualized import V
|
| 38 |
+
from ..common import (
|
| 39 |
+
CSEVariable,
|
| 40 |
+
IndentedBuffer,
|
| 41 |
+
Kernel,
|
| 42 |
+
OpOverrides,
|
| 43 |
+
WorkspaceArg,
|
| 44 |
+
WorkspaceZeroMode,
|
| 45 |
+
)
|
| 46 |
+
from ..cpp_utils import CppPrinter, DTYPE_TO_CPP
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
if TYPE_CHECKING:
|
| 50 |
+
from torch._inductor.codegen.cuda.cuda_template import CUDATemplate
|
| 51 |
+
|
| 52 |
+
log = logging.getLogger(__name__)
|
| 53 |
+
|
| 54 |
+
cexpr = CppPrinter().doprint
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _normalize_idx(index: int, total_length: int) -> int:
|
| 58 |
+
return index if index >= 0 else index + total_length
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
ValidLayoutSymbols = Literal["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"]
|
| 62 |
+
ValidLayoutAttrs = Literal["size", "stride"]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@dataclass(frozen=True)
|
| 66 |
+
class LayoutArg:
|
| 67 |
+
node: IRNode
|
| 68 |
+
symbol: ValidLayoutSymbols
|
| 69 |
+
attr: ValidLayoutAttrs
|
| 70 |
+
dim: int
|
| 71 |
+
|
| 72 |
+
def matches(self, node, attr, dim) -> bool:
|
| 73 |
+
return self.node == node and self.attr == attr and self.dim == dim
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class CUDAKernel(Kernel):
|
| 77 |
+
"""
|
| 78 |
+
Baseclass for CUDA / Cutlass based Kernels
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
overrides = OpOverrides # type: ignore[assignment]
|
| 82 |
+
|
| 83 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 84 |
+
super().__init__(*args, **kwargs)
|
| 85 |
+
self.layout_args: dict[str, list[LayoutArg]] = defaultdict(list)
|
| 86 |
+
self.size_args: list[Union[Expr, int]] = []
|
| 87 |
+
# Mapping from arg name to IRNode.
|
| 88 |
+
self.named_nodes: dict[str, IRNode] = {}
|
| 89 |
+
|
| 90 |
+
def find_symbol(
|
| 91 |
+
self, node: IRNode, attr: ValidLayoutAttrs, dim: int
|
| 92 |
+
) -> Optional[str]:
|
| 93 |
+
arg = self.find_layout_arg(node, attr, dim)
|
| 94 |
+
return arg.symbol if arg else None
|
| 95 |
+
|
| 96 |
+
def find_layout_arg(
|
| 97 |
+
self, node: IRNode, attr: ValidLayoutAttrs, dim: int
|
| 98 |
+
) -> Optional[LayoutArg]:
|
| 99 |
+
matches = [
|
| 100 |
+
arg
|
| 101 |
+
for arg in itertools.chain.from_iterable(self.layout_args.values())
|
| 102 |
+
if arg.matches(node, attr, dim)
|
| 103 |
+
]
|
| 104 |
+
if len(matches) >= 1:
|
| 105 |
+
# Verify all matches have the same node, attribute, and dimension
|
| 106 |
+
# And if they come from the same node, whichever symbol we use is fine.
|
| 107 |
+
# if in runtime the logic changes, this would trigger guard
|
| 108 |
+
first_match = matches[0]
|
| 109 |
+
if not all(
|
| 110 |
+
match.node == first_match.node
|
| 111 |
+
and match.attr == first_match.attr
|
| 112 |
+
and match.dim == first_match.dim
|
| 113 |
+
for match in matches
|
| 114 |
+
):
|
| 115 |
+
raise AssertionError("All matching layout args should be identical")
|
| 116 |
+
return first_match
|
| 117 |
+
return None
|
| 118 |
+
|
| 119 |
+
def add_layout_arg(
|
| 120 |
+
self, symbol: ValidLayoutSymbols, node: IRNode, attr: ValidLayoutAttrs, dim: int
|
| 121 |
+
):
|
| 122 |
+
arg = LayoutArg(node, symbol, attr, dim)
|
| 123 |
+
self.layout_args[symbol].append(arg)
|
| 124 |
+
|
| 125 |
+
def init_layout_args(self) -> None:
|
| 126 |
+
X = self.named_nodes["X"]
|
| 127 |
+
W = self.named_nodes["W"]
|
| 128 |
+
Y = self.named_nodes["Y"]
|
| 129 |
+
Bias = self.named_nodes.get("Bias", None)
|
| 130 |
+
x_mdim = _normalize_idx(-2, len(X.get_size()))
|
| 131 |
+
x_kdim = _normalize_idx(-1, len(X.get_size()))
|
| 132 |
+
w_kdim = _normalize_idx(-2, len(W.get_size()))
|
| 133 |
+
w_ndim = _normalize_idx(-1, len(W.get_size()))
|
| 134 |
+
y_mdim = _normalize_idx(-2, len(Y.get_size()))
|
| 135 |
+
y_ndim = _normalize_idx(-1, len(Y.get_size()))
|
| 136 |
+
self.add_layout_arg("M", X, "size", x_mdim)
|
| 137 |
+
self.add_layout_arg("K", X, "size", x_kdim)
|
| 138 |
+
self.add_layout_arg("K", W, "size", w_kdim)
|
| 139 |
+
self.add_layout_arg("N", W, "size", w_ndim)
|
| 140 |
+
self.add_layout_arg("M", Y, "size", y_mdim)
|
| 141 |
+
self.add_layout_arg("N", Y, "size", y_ndim)
|
| 142 |
+
if len(X.get_size()) > 2:
|
| 143 |
+
self.add_layout_arg("B", X, "size", 0)
|
| 144 |
+
|
| 145 |
+
lda_dim = self.find_ld_idx(X)
|
| 146 |
+
ldb_dim = self.find_ld_idx(W)
|
| 147 |
+
ldc_dim = self.find_ld_idx(Bias) if Bias else None
|
| 148 |
+
ldd_dim = self.find_ld_idx(Y)
|
| 149 |
+
self.add_layout_arg("lda", X, "stride", lda_dim)
|
| 150 |
+
self.add_layout_arg("ldb", W, "stride", ldb_dim)
|
| 151 |
+
if Bias is not None and ldc_dim is not None:
|
| 152 |
+
self.add_layout_arg("ldc", Bias, "stride", ldc_dim)
|
| 153 |
+
self.add_layout_arg("ldd", Y, "stride", ldd_dim)
|
| 154 |
+
|
| 155 |
+
def get_layout_args(self) -> tuple[Union[Expr, int], ...]:
|
| 156 |
+
X = self.named_nodes["X"]
|
| 157 |
+
W = self.named_nodes["W"]
|
| 158 |
+
Y = self.named_nodes["Y"]
|
| 159 |
+
Bias = self.named_nodes.get("Bias", None)
|
| 160 |
+
mdim = _normalize_idx(-2, len(X.get_size()))
|
| 161 |
+
ndim = _normalize_idx(-1, len(W.get_size()))
|
| 162 |
+
kdim = _normalize_idx(-1, len(X.get_size()))
|
| 163 |
+
|
| 164 |
+
def get_ld(node) -> Union[Expr, int]:
|
| 165 |
+
dim = self.find_ld_idx(node)
|
| 166 |
+
return node.get_stride()[dim]
|
| 167 |
+
|
| 168 |
+
M = X.get_size()[mdim]
|
| 169 |
+
N = W.get_size()[ndim]
|
| 170 |
+
K = X.get_size()[kdim]
|
| 171 |
+
B = X.get_size()[0] if len(X.get_size()) > 2 else 1
|
| 172 |
+
LDA = get_ld(X)
|
| 173 |
+
LDB = get_ld(W)
|
| 174 |
+
LDC = get_ld(Bias) if Bias else 0
|
| 175 |
+
LDD = get_ld(Y)
|
| 176 |
+
return (M, N, K, B, LDA, LDB, LDC, LDD)
|
| 177 |
+
|
| 178 |
+
def get_dynamic_shape_args(self) -> list[Union[Expr, int]]:
|
| 179 |
+
return [*self.get_layout_args(), *self.size_args]
|
| 180 |
+
|
| 181 |
+
def get_offset_args(self) -> list[Expr]:
|
| 182 |
+
return [node.get_layout().offset for node in self.named_nodes.values()]
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
def find_ld_idx(node: IRNode) -> int:
|
| 186 |
+
strides = node.get_stride()
|
| 187 |
+
# Handle 1D tensor case
|
| 188 |
+
if V.graph.sizevars.statically_known_equals(strides[-1], 1):
|
| 189 |
+
return _normalize_idx(-2, len(strides))
|
| 190 |
+
|
| 191 |
+
assert V.graph.sizevars.statically_known_equals(strides[-2], 1), strides[-2]
|
| 192 |
+
return _normalize_idx(-1, len(strides))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class CUDATemplateKernel(CUDAKernel):
|
| 196 |
+
"""
|
| 197 |
+
Template kernels defined by CUDA / Cutlass in C++.
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
_EXTRA_CPP_ARGS = "size_t* workspace_size, uint8_t* workspace, cudaStream_t stream"
|
| 201 |
+
|
| 202 |
+
def __init__(
|
| 203 |
+
self,
|
| 204 |
+
kernel_name: str,
|
| 205 |
+
runtime_arg_info: list["ArgInfo"],
|
| 206 |
+
runtime_arg_values: list[Any],
|
| 207 |
+
) -> None:
|
| 208 |
+
"""
|
| 209 |
+
Initializes a new instance of the CUDATemplateKernel class.
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
kernel_name (str): The name of the kernel.
|
| 213 |
+
"""
|
| 214 |
+
super().__init__()
|
| 215 |
+
self.kernel_name = kernel_name
|
| 216 |
+
self.runtime_arg_info = runtime_arg_info
|
| 217 |
+
self.runtime_arg_values = runtime_arg_values
|
| 218 |
+
|
| 219 |
+
def check_not_null(self, node: IRNode) -> str:
|
| 220 |
+
"""
|
| 221 |
+
Generates code to check that a node is not null.
|
| 222 |
+
"""
|
| 223 |
+
if node is None:
|
| 224 |
+
return ""
|
| 225 |
+
|
| 226 |
+
size_str = self.size(node, 0, -1)
|
| 227 |
+
name_str = self.arg_name(node)
|
| 228 |
+
if name_str is None:
|
| 229 |
+
return ""
|
| 230 |
+
|
| 231 |
+
res = IndentedBuffer(initial_indent=2)
|
| 232 |
+
res.tabwidth = 1
|
| 233 |
+
res.splice(
|
| 234 |
+
f"""
|
| 235 |
+
{{
|
| 236 |
+
if (!{name_str}) {{
|
| 237 |
+
int64_t {name_str}_size = {size_str};
|
| 238 |
+
if ({name_str}_size > 0) {{
|
| 239 |
+
throw std::runtime_error("input {name_str} is null but size is not 0!");
|
| 240 |
+
}}
|
| 241 |
+
}}
|
| 242 |
+
}}
|
| 243 |
+
"""
|
| 244 |
+
)
|
| 245 |
+
return res.getvalue()
|
| 246 |
+
|
| 247 |
+
def get_signature(self) -> str:
|
| 248 |
+
return self.signature
|
| 249 |
+
|
| 250 |
+
def def_kernel(
|
| 251 |
+
self,
|
| 252 |
+
inputs: list[IRNode],
|
| 253 |
+
outputs: list[IRNode],
|
| 254 |
+
names_str: str = "",
|
| 255 |
+
input_reorder: Optional[list[int]] = None,
|
| 256 |
+
) -> str:
|
| 257 |
+
"""
|
| 258 |
+
Hook called from template code to generate function definition and
|
| 259 |
+
needed args.
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
inputs: List of input IRNodes
|
| 263 |
+
outputs: List of output IRNodes
|
| 264 |
+
names_str: Comma separated list of input + output argument names.
|
| 265 |
+
input_reorder: The actual order of input nodes.
|
| 266 |
+
e.g. The template might have input argument defined as [X, W, Bias],
|
| 267 |
+
and the actual input passed into this template could be [Bias, X, W].
|
| 268 |
+
In this case, the `input_reorder` would be [2, 0, 1].
|
| 269 |
+
additional_size_args: Additional size arguments for epilogue inputs
|
| 270 |
+
"""
|
| 271 |
+
# NB: name order matters here, it's used to match up offsets
|
| 272 |
+
names = [x.strip() for x in names_str.strip().split(",")]
|
| 273 |
+
if len(inputs) + len(outputs) != len(names):
|
| 274 |
+
raise RuntimeError(
|
| 275 |
+
f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}"
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
if input_reorder is not None:
|
| 279 |
+
assert len(inputs) == len(input_reorder)
|
| 280 |
+
else:
|
| 281 |
+
input_reorder = list(range(len(inputs)))
|
| 282 |
+
|
| 283 |
+
for idx in input_reorder:
|
| 284 |
+
name = names[idx]
|
| 285 |
+
node = inputs[idx]
|
| 286 |
+
if node is not None:
|
| 287 |
+
self.named_nodes[name] = node
|
| 288 |
+
self.args.input_buffers[node.get_name()] = name
|
| 289 |
+
|
| 290 |
+
free_symbols: OrderedSet[Expr] = OrderedSet()
|
| 291 |
+
for name, node in zip(names[len(inputs) : len(inputs) + len(outputs)], outputs):
|
| 292 |
+
if node is not None:
|
| 293 |
+
# NB: named nodes must be populated in the order of names
|
| 294 |
+
self.named_nodes[name] = node
|
| 295 |
+
self.args.output_buffers[node.get_name()] = name
|
| 296 |
+
|
| 297 |
+
if name not in (
|
| 298 |
+
"X",
|
| 299 |
+
"W",
|
| 300 |
+
"Bias",
|
| 301 |
+
"Y",
|
| 302 |
+
): # we handle these symbolic shapes explicitly
|
| 303 |
+
for expr in itertools.chain(node.get_size(), node.get_stride()):
|
| 304 |
+
if isinstance(expr, Expr):
|
| 305 |
+
for s in expr.free_symbols:
|
| 306 |
+
free_symbols.add(s) # type: ignore[arg-type]
|
| 307 |
+
|
| 308 |
+
arg_defs, *_ = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE)
|
| 309 |
+
|
| 310 |
+
self.init_layout_args()
|
| 311 |
+
size_vars = ["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"]
|
| 312 |
+
size_vars.extend(str(s) for s in free_symbols)
|
| 313 |
+
self.size_args.extend(free_symbols)
|
| 314 |
+
size_args = [f"const int {s}" for s in size_vars]
|
| 315 |
+
offset_args = [f"const int {name}_offset" for name in self.named_nodes]
|
| 316 |
+
runtime_arg_decls = ",".join(
|
| 317 |
+
[f"{arg.ty} {arg.name}" for arg in self.runtime_arg_info]
|
| 318 |
+
)
|
| 319 |
+
if runtime_arg_decls:
|
| 320 |
+
runtime_arg_decls += ", "
|
| 321 |
+
|
| 322 |
+
signature = (
|
| 323 |
+
f"int {self.kernel_name}({', '.join(arg_defs + size_args + offset_args)},\
|
| 324 |
+
{runtime_arg_decls}{self._EXTRA_CPP_ARGS})"
|
| 325 |
+
)
|
| 326 |
+
self.signature = signature
|
| 327 |
+
return signature
|
| 328 |
+
|
| 329 |
+
def call_kernel(
|
| 330 |
+
self,
|
| 331 |
+
name: str,
|
| 332 |
+
node: "CUDATemplateBuffer", # type: ignore[name-defined]
|
| 333 |
+
) -> None:
|
| 334 |
+
"""
|
| 335 |
+
Generates code to call the kernel through V.graph.wrapper_code.
|
| 336 |
+
used from within torch._inductor.wrapper.PythonWrapperCodegen
|
| 337 |
+
|
| 338 |
+
name: Name of kernel function.
|
| 339 |
+
node: The CUDATemplateBuffer node which contains information about the kernel, it's fused epilogue nodes
|
| 340 |
+
as well as all required inputs and outputs.
|
| 341 |
+
"""
|
| 342 |
+
wrapper = V.graph.wrapper_code
|
| 343 |
+
|
| 344 |
+
arg_types: list[Any]
|
| 345 |
+
if V.graph.cpp_wrapper:
|
| 346 |
+
# Make sure we initialize these kernels since they're exported as
|
| 347 |
+
# C-style symbol names.
|
| 348 |
+
assert isinstance(wrapper, CppWrapperCpu)
|
| 349 |
+
wrapper.initialized_kernels[name] = self
|
| 350 |
+
# We always originally initialize name with "KERNEL_NAME". So, we
|
| 351 |
+
# we replace with the real kernel name passed as an arg to this function.
|
| 352 |
+
self.signature = self.signature.replace(str(Placeholder.KERNEL_NAME), name)
|
| 353 |
+
_, call_args, arg_types = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE)
|
| 354 |
+
else:
|
| 355 |
+
_, call_args, _, arg_types = self.args.python_argdefs()
|
| 356 |
+
|
| 357 |
+
dynamic_shape_args = self.get_dynamic_shape_args()
|
| 358 |
+
offset_args = self.get_offset_args()
|
| 359 |
+
call_args.extend(dynamic_shape_args) # type: ignore[arg-type]
|
| 360 |
+
call_args.extend(offset_args) # type: ignore[arg-type]
|
| 361 |
+
for arg in self.runtime_arg_values:
|
| 362 |
+
call_args.append(str(arg))
|
| 363 |
+
arg_types.extend("const int" for _ in dynamic_shape_args)
|
| 364 |
+
arg_types.extend("const int" for _ in offset_args)
|
| 365 |
+
for arg in self.runtime_arg_info:
|
| 366 |
+
arg_types.append(arg.ty)
|
| 367 |
+
# dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar
|
| 368 |
+
for i in range(len(call_args)):
|
| 369 |
+
if V.graph.is_unspec_arg(call_args[i]):
|
| 370 |
+
call_args[i] = call_args[i] + ".item()"
|
| 371 |
+
elif isinstance(arg_types[i], torch_dtype):
|
| 372 |
+
call_args[i] = (
|
| 373 |
+
call_args[i]
|
| 374 |
+
if V.graph.cpp_wrapper
|
| 375 |
+
else f"c_void_p({call_args[i]}.data_ptr())"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
# workspace_size ptr is NULL to mark this call is not intended for retrieving workspace_size.
|
| 379 |
+
# workspace_size should have already been retrieved prior to this call.
|
| 380 |
+
# workspace_size is here.
|
| 381 |
+
call_args.append("nullptr" if V.graph.cpp_wrapper else "None")
|
| 382 |
+
if V.graph.cpp_wrapper:
|
| 383 |
+
arg_types.append("size_t*")
|
| 384 |
+
|
| 385 |
+
if node.get_workspace_size() > 0:
|
| 386 |
+
ws = WorkspaceArg(
|
| 387 |
+
count=node.get_workspace_size(),
|
| 388 |
+
device=V.graph.get_current_device_or_throw(),
|
| 389 |
+
zero_mode=WorkspaceZeroMode.UNINITIALIZED,
|
| 390 |
+
outer_name=WorkspaceArg.unique_name(),
|
| 391 |
+
)
|
| 392 |
+
wrapper.generate_workspace_allocation(ws)
|
| 393 |
+
workspace = str(ws.outer_name)
|
| 394 |
+
call_args.append(
|
| 395 |
+
workspace
|
| 396 |
+
if V.graph.cpp_wrapper
|
| 397 |
+
else f"c_void_p({workspace}.data_ptr())"
|
| 398 |
+
)
|
| 399 |
+
else:
|
| 400 |
+
ws = None
|
| 401 |
+
call_args.append("nullptr" if V.graph.cpp_wrapper else "None")
|
| 402 |
+
if V.graph.cpp_wrapper:
|
| 403 |
+
arg_types.append("uint8_t*")
|
| 404 |
+
|
| 405 |
+
wrapper.generate_kernel_call(
|
| 406 |
+
name,
|
| 407 |
+
call_args,
|
| 408 |
+
triton=False,
|
| 409 |
+
arg_types=arg_types,
|
| 410 |
+
)
|
| 411 |
+
if ws:
|
| 412 |
+
wrapper.generate_workspace_deallocation(ws)
|
| 413 |
+
|
| 414 |
+
def dtype(self, node: IRNode) -> Optional[str]:
|
| 415 |
+
"""
|
| 416 |
+
Generates code which represents dtype of a given node.
|
| 417 |
+
"""
|
| 418 |
+
|
| 419 |
+
if node is None:
|
| 420 |
+
return "void"
|
| 421 |
+
return DTYPE_TO_CPP.get(node.get_layout().dtype)
|
| 422 |
+
|
| 423 |
+
def cutlass_dtype(self, node: IRNode, default_dtype="void") -> Optional[str]:
|
| 424 |
+
# Helper method, called into from CUTLASSGemmTemplate
|
| 425 |
+
if node is None:
|
| 426 |
+
return default_dtype
|
| 427 |
+
from torch._inductor.codegen.cuda.cuda_template import CUTLASSTemplate
|
| 428 |
+
|
| 429 |
+
return CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]
|
| 430 |
+
|
| 431 |
+
def max_valid_index(self, node: IRNode, default=-1):
|
| 432 |
+
# Helper method, called into from CUTLASSGemmTemplate
|
| 433 |
+
if node is None:
|
| 434 |
+
return default
|
| 435 |
+
max_valid_offset = 0
|
| 436 |
+
for i in range(len(node.get_size())):
|
| 437 |
+
max_valid_offset += (node.get_size()[i] - 1) * node.get_stride()[i]
|
| 438 |
+
return max_valid_offset
|
| 439 |
+
|
| 440 |
+
def ptr(self, node: IRNode) -> str:
|
| 441 |
+
"""
|
| 442 |
+
Generates code which represents pointer of a given node.
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
if node is None:
|
| 446 |
+
return "nullptr"
|
| 447 |
+
arg_name = self.arg_name(node)
|
| 448 |
+
if arg_name is None:
|
| 449 |
+
return "nullptr"
|
| 450 |
+
return f"{arg_name} + {arg_name}_offset"
|
| 451 |
+
|
| 452 |
+
def size(
|
| 453 |
+
self,
|
| 454 |
+
node: IRNode,
|
| 455 |
+
start_index: int,
|
| 456 |
+
end_index: Optional[int] = None,
|
| 457 |
+
default_value: int = 0,
|
| 458 |
+
) -> str:
|
| 459 |
+
"""
|
| 460 |
+
Hook called from template code to get the size of an arg.
|
| 461 |
+
Generates code which represents size of a given node in [start_index, end_index).
|
| 462 |
+
If node is None, returns default_value.
|
| 463 |
+
|
| 464 |
+
TODO: Will add needed args to pass it in if it is dynamic.
|
| 465 |
+
"""
|
| 466 |
+
|
| 467 |
+
if node is None:
|
| 468 |
+
return str(default_value)
|
| 469 |
+
|
| 470 |
+
start_index = _normalize_idx(start_index, len(node.get_size()))
|
| 471 |
+
if end_index is None:
|
| 472 |
+
end_index = start_index
|
| 473 |
+
end_index = _normalize_idx(end_index, len(node.get_size()))
|
| 474 |
+
sizes = [
|
| 475 |
+
self.find_symbol(node, "size", dim=i) or node.get_size()[i]
|
| 476 |
+
for i in range(start_index, end_index + 1)
|
| 477 |
+
]
|
| 478 |
+
if len(sizes) == 0:
|
| 479 |
+
return str(default_value)
|
| 480 |
+
|
| 481 |
+
sizes = [symbols(v) if isinstance(v, str) else v for v in sizes]
|
| 482 |
+
val = sympy_product(sizes)
|
| 483 |
+
return val
|
| 484 |
+
|
| 485 |
+
def stride(self, node: IRNode, index: int, default_value: int = 0) -> str:
|
| 486 |
+
"""
|
| 487 |
+
Hook called from template code to get the stride of an arg.
|
| 488 |
+
Generates code which represents stride of a given node at index.
|
| 489 |
+
If node is None, returns default_value.
|
| 490 |
+
|
| 491 |
+
TODO: Will add needed args to pass it in if it is dynamic.
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
if node is None:
|
| 495 |
+
return str(default_value)
|
| 496 |
+
|
| 497 |
+
index = _normalize_idx(index, len(node.get_size()))
|
| 498 |
+
if index < 0:
|
| 499 |
+
return str(default_value)
|
| 500 |
+
|
| 501 |
+
stride = node.get_stride()[index]
|
| 502 |
+
if V.graph.sizevars.statically_known_leq(stride, 1):
|
| 503 |
+
return str(stride)
|
| 504 |
+
return self.find_symbol(node, "stride", dim=index) or str(stride)
|
| 505 |
+
|
| 506 |
+
def batch_stride(self, node: IRNode, default_value: int = 0) -> str:
|
| 507 |
+
"""
|
| 508 |
+
Hook called from template code to get the batch stride of an arg.
|
| 509 |
+
Returns 0 if batch dim is not present.
|
| 510 |
+
|
| 511 |
+
This method assumes that batch stride is the largest stride.
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
if node is None:
|
| 515 |
+
return str(default_value)
|
| 516 |
+
|
| 517 |
+
if len(node.get_size()) < 3:
|
| 518 |
+
return str(default_value)
|
| 519 |
+
|
| 520 |
+
batch_stride = node.get_stride()[0]
|
| 521 |
+
if V.graph.sizevars.statically_known_leq(batch_stride, 1):
|
| 522 |
+
return str(batch_stride)
|
| 523 |
+
|
| 524 |
+
return "{}*{}".format(
|
| 525 |
+
self.find_symbol(node, "size", dim=1) or node.get_size()[1],
|
| 526 |
+
self.find_symbol(node, "size", dim=2) or node.get_size()[2],
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
def row_or_column_stride(self, node: IRNode, default_value: int = 0) -> str:
|
| 530 |
+
"""
|
| 531 |
+
Hook called from template code to get the row or column stride of an arg.
|
| 532 |
+
This is required by some CUTLASS 2.X APIs.
|
| 533 |
+
If the node is in row_major, it returns stride[-2].
|
| 534 |
+
If the node is in column_major, it returns stride[-1].
|
| 535 |
+
|
| 536 |
+
TODO: Will add needed args to pass it in if it is dynamic.
|
| 537 |
+
"""
|
| 538 |
+
|
| 539 |
+
if node is None or len(node.get_stride()) < 2:
|
| 540 |
+
return str(default_value)
|
| 541 |
+
|
| 542 |
+
stride0 = node.get_stride()[-1]
|
| 543 |
+
stride1 = node.get_stride()[-2]
|
| 544 |
+
if stride0 == 1:
|
| 545 |
+
return cexpr(self.rename_indexing(stride1))
|
| 546 |
+
elif stride1 == 1:
|
| 547 |
+
return cexpr(self.rename_indexing(stride0))
|
| 548 |
+
else:
|
| 549 |
+
raise RuntimeError(
|
| 550 |
+
f"At least 1 stride should be 1. Strides: {node.get_stride()=}"
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
def load(self, name: str, index: Expr, mode: Any = None) -> CSEVariable:
|
| 554 |
+
"""
|
| 555 |
+
Mock load function for memory planning to optimize allocations properly.
|
| 556 |
+
"""
|
| 557 |
+
return self.create_cse_var(name, bounds=ValueRanges.unknown())
|
| 558 |
+
|
| 559 |
+
def store(self, name: str, index: Expr, value: Any, mode: Any = None) -> None:
|
| 560 |
+
"""
|
| 561 |
+
Mock store function for memory planning to optimize allocations properly.
|
| 562 |
+
"""
|
| 563 |
+
self.store_buffer_names.add(name)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
class CUDATemplateCaller(ChoiceCaller):
|
| 567 |
+
"""
|
| 568 |
+
CUDATemplateCaller
|
| 569 |
+
|
| 570 |
+
This class represents a caller for CUDA template kernels. It is a subclass of ChoiceCaller.
|
| 571 |
+
Attributes:
|
| 572 |
+
name (str): The name of the caller.
|
| 573 |
+
category (str): The category of the caller.
|
| 574 |
+
bmreq (CUDABenchmarkRequest): The benchmark request for the caller.
|
| 575 |
+
template_buffer (CUDATemplateBuffer): The template buffer for the caller.
|
| 576 |
+
"""
|
| 577 |
+
|
| 578 |
+
def __init__(
|
| 579 |
+
self,
|
| 580 |
+
name: str,
|
| 581 |
+
category: str,
|
| 582 |
+
input_nodes: list[Buffer],
|
| 583 |
+
layout: Layout,
|
| 584 |
+
make_kernel_render: Callable[
|
| 585 |
+
[CUDATemplateBuffer, Optional[list[BaseSchedulerNode]]],
|
| 586 |
+
tuple[CUDATemplateKernel, functools.partial[str]],
|
| 587 |
+
],
|
| 588 |
+
bmreq: CUDABenchmarkRequest,
|
| 589 |
+
supports_epilogue_fusion: bool,
|
| 590 |
+
template: "CUDATemplate", # type: ignore[name-defined]
|
| 591 |
+
info_kwargs: Optional[
|
| 592 |
+
dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]
|
| 593 |
+
], # type: ignore[type-arg]
|
| 594 |
+
description: str,
|
| 595 |
+
) -> None:
|
| 596 |
+
super().__init__(name, input_nodes, layout, description)
|
| 597 |
+
self.category = category
|
| 598 |
+
self.make_kernel_render = make_kernel_render
|
| 599 |
+
self.bmreq = bmreq
|
| 600 |
+
self.supports_epilogue_fusion = supports_epilogue_fusion
|
| 601 |
+
self.template = template
|
| 602 |
+
self.info_kwargs = info_kwargs
|
| 603 |
+
|
| 604 |
+
def precompile(self) -> None:
|
| 605 |
+
assert self.bmreq is not None
|
| 606 |
+
self.bmreq.precompile()
|
| 607 |
+
|
| 608 |
+
def benchmark(self, *args, out) -> float:
|
| 609 |
+
assert self.bmreq is not None
|
| 610 |
+
if config.profile_bandwidth_with_do_bench_using_profiling:
|
| 611 |
+
algo = self.bmreq.make_run_fn(*args, out=out)
|
| 612 |
+
return do_bench_using_profiling(algo)
|
| 613 |
+
return self.bmreq.benchmark(*args, out=out)
|
| 614 |
+
|
| 615 |
+
def __str__(self) -> str:
|
| 616 |
+
return f"CUDATemplateCaller(source_file={self.bmreq.source_file})"
|
| 617 |
+
|
| 618 |
+
def call_name(self) -> str:
|
| 619 |
+
return f"cuda_template_kernels.{self.name}"
|
| 620 |
+
|
| 621 |
+
def kernel_hash_key(self) -> str:
|
| 622 |
+
"""
|
| 623 |
+
Return kernel hash key that does not depend on swizzle.
|
| 624 |
+
"""
|
| 625 |
+
return "-".join(
|
| 626 |
+
[
|
| 627 |
+
self.category,
|
| 628 |
+
self.bmreq.hash_key,
|
| 629 |
+
]
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
def hash_key(self) -> str:
|
| 633 |
+
"""
|
| 634 |
+
Return kernel hash key that does not depend on swizzle.
|
| 635 |
+
"""
|
| 636 |
+
swizzle_str: str = (
|
| 637 |
+
str(self.info_kwargs.get("swizzle"))
|
| 638 |
+
if isinstance(self.info_kwargs, dict)
|
| 639 |
+
else "None"
|
| 640 |
+
)
|
| 641 |
+
return "-".join(
|
| 642 |
+
[
|
| 643 |
+
self.category,
|
| 644 |
+
self.bmreq.hash_key,
|
| 645 |
+
swizzle_str,
|
| 646 |
+
]
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
def info_dict(self) -> dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]:
|
| 650 |
+
"""
|
| 651 |
+
Information returned here is logged to the autotune log file when that is enabled.
|
| 652 |
+
|
| 653 |
+
In general, we should avoid calling this function as it is expensive to compute,
|
| 654 |
+
and can add up very fast.
|
| 655 |
+
"""
|
| 656 |
+
if self.info_kwargs is not None and "op" in self.info_kwargs:
|
| 657 |
+
op: Any = self.info_kwargs["op"]
|
| 658 |
+
return {
|
| 659 |
+
"backend": "CUDA",
|
| 660 |
+
"op_type": type(op).__name__,
|
| 661 |
+
"op_conf_name": str(op.configuration_name()),
|
| 662 |
+
"op_arch": str(op.arch),
|
| 663 |
+
"tile_shape": str(op.tile_description.tile_shape),
|
| 664 |
+
"epilogue_schedule": str(op.epilogue_schedule),
|
| 665 |
+
"kernel_schedule": str(op.kernel_schedule),
|
| 666 |
+
"element_accumulator": str(op.accumulator_type()),
|
| 667 |
+
"op_name": str(op.procedural_name()),
|
| 668 |
+
"instruction_shape": str(
|
| 669 |
+
op.tile_description.math_instruction.instruction_shape
|
| 670 |
+
),
|
| 671 |
+
"swizzle": str(self.info_kwargs["swizzle"]),
|
| 672 |
+
}
|
| 673 |
+
else:
|
| 674 |
+
return {"backend": "CUDA", "op_type": "unknown"}
|
| 675 |
+
|
| 676 |
+
def output_node(self) -> Union[TensorBox, ShapeAsConstantBuffer]:
|
| 677 |
+
self.bmreq.update_workspace_size()
|
| 678 |
+
return TensorBox.create(
|
| 679 |
+
CUDATemplateBuffer(
|
| 680 |
+
layout=self.layout,
|
| 681 |
+
inputs=self.input_nodes,
|
| 682 |
+
make_kernel_render=self.make_kernel_render,
|
| 683 |
+
workspace_size=self.bmreq.workspace_size,
|
| 684 |
+
supports_epilogue_fusion=self.supports_epilogue_fusion,
|
| 685 |
+
template=self.template,
|
| 686 |
+
)
|
| 687 |
+
)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_template.py
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import hashlib
|
| 4 |
+
import itertools
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from typing import Any, Optional, TYPE_CHECKING, Union
|
| 7 |
+
from typing_extensions import override
|
| 8 |
+
from unittest.mock import patch
|
| 9 |
+
|
| 10 |
+
import sympy
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
from torch._inductor import config
|
| 14 |
+
from torch._inductor.utils import clear_on_fresh_cache, Placeholder
|
| 15 |
+
from torch._logging import getArtifactLogger
|
| 16 |
+
|
| 17 |
+
from ...autotune_process import CUDABenchmarkRequest, TensorMeta
|
| 18 |
+
from ...ir import Buffer, CUDATemplateBuffer, IRNode, Layout
|
| 19 |
+
from ...utils import IndentedBuffer, unique
|
| 20 |
+
from ...virtualized import V
|
| 21 |
+
from ..common import KernelTemplate
|
| 22 |
+
from .cuda_kernel import CUDATemplateCaller, CUDATemplateKernel
|
| 23 |
+
from .cutlass_utils import DTYPE_TO_CUTLASS_TYPE
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
from ...scheduler import BaseSchedulerNode # noqa: TC004
|
| 28 |
+
else:
|
| 29 |
+
BaseSchedulerNode = Any
|
| 30 |
+
|
| 31 |
+
GemmOperation = Any
|
| 32 |
+
|
| 33 |
+
autotuning_log = getArtifactLogger(__name__, "autotuning")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass(frozen=True)
|
| 37 |
+
class ArgInfo:
|
| 38 |
+
name: str
|
| 39 |
+
ty: str
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@clear_on_fresh_cache
|
| 43 |
+
class CUDATemplate(KernelTemplate):
|
| 44 |
+
index_counter = itertools.count()
|
| 45 |
+
# dict of cache key to (code, size_args)
|
| 46 |
+
code_cache: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = {}
|
| 47 |
+
cache_clear = staticmethod(code_cache.clear)
|
| 48 |
+
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
name: str,
|
| 52 |
+
input_nodes: list[Buffer],
|
| 53 |
+
layout: Layout,
|
| 54 |
+
input_reorder: Optional[list[int]] = None,
|
| 55 |
+
) -> None:
|
| 56 |
+
"""
|
| 57 |
+
Baseclass for CUDA C++ Templates, derived from KernelTemplate.
|
| 58 |
+
Not to be instantiated directly.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
name (str): The name of the CUDATemplate object.
|
| 62 |
+
input_nodes (List[IRNode]): A list of input IRNodes.
|
| 63 |
+
layout (Layout): The layout of the output buffer / tensor.
|
| 64 |
+
input_reorder (Optional[List[int]]): An optional list that specifies
|
| 65 |
+
the order of the input nodes.
|
| 66 |
+
"""
|
| 67 |
+
super().__init__(name)
|
| 68 |
+
self.input_nodes = input_nodes
|
| 69 |
+
self.output_node: Buffer = Buffer(name="buf_out", layout=layout)
|
| 70 |
+
self.input_reorder = input_reorder
|
| 71 |
+
self.layout = layout
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
@functools.lru_cache(None)
|
| 75 |
+
# pyrefly: ignore [bad-override]
|
| 76 |
+
def _template_from_string(cls, source: str) -> Any:
|
| 77 |
+
return KernelTemplate._template_from_string(source)
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def supports_epilogue_fusion(op: GemmOperation) -> bool:
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
def make_key(self, name: str, input_key: str, layout_repr: str) -> str:
|
| 84 |
+
"""
|
| 85 |
+
Make a key for the code cache. The idea of the method is to cache
|
| 86 |
+
everything that matters but doesn't include runtime param values, i.e.,
|
| 87 |
+
self.get_runtime_arg_values().
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
kwargs: Additional keyword arguments. Including op (GemmOperation).
|
| 91 |
+
"""
|
| 92 |
+
return hashlib.sha256(
|
| 93 |
+
str(
|
| 94 |
+
(
|
| 95 |
+
input_key,
|
| 96 |
+
self.input_reorder,
|
| 97 |
+
# output layout, same as self.output_node.get_layout()
|
| 98 |
+
layout_repr,
|
| 99 |
+
self.get_runtime_arg_info(),
|
| 100 |
+
name,
|
| 101 |
+
)
|
| 102 |
+
).encode("utf-8")
|
| 103 |
+
).hexdigest()
|
| 104 |
+
|
| 105 |
+
def generate_code_and_args(
|
| 106 |
+
self, name: str, input_key: str, layout_repr: str, **kwargs
|
| 107 |
+
) -> tuple[str, tuple[int, ...]]:
|
| 108 |
+
"""
|
| 109 |
+
Generate code and args with caching. We cache the code even if runtime
|
| 110 |
+
args are different.
|
| 111 |
+
"""
|
| 112 |
+
key: Optional[str] = None
|
| 113 |
+
if config.cuda.enable_caching_codegen:
|
| 114 |
+
key = self.make_key(name=name, input_key=input_key, layout_repr=layout_repr)
|
| 115 |
+
|
| 116 |
+
if key is not None and key in self.code_cache:
|
| 117 |
+
code, size_args, offset_args = self.code_cache[key]
|
| 118 |
+
extra_args = tuple(
|
| 119 |
+
list(size_args)
|
| 120 |
+
+ list(offset_args)
|
| 121 |
+
+ list(self.get_runtime_arg_values(**kwargs))
|
| 122 |
+
)
|
| 123 |
+
return code, extra_args
|
| 124 |
+
|
| 125 |
+
kernel_name = str(Placeholder.KERNEL_NAME)
|
| 126 |
+
kernel = CUDATemplateKernel(
|
| 127 |
+
kernel_name=kernel_name,
|
| 128 |
+
runtime_arg_info=self.get_runtime_arg_info(),
|
| 129 |
+
runtime_arg_values=self.get_runtime_arg_values(**kwargs),
|
| 130 |
+
)
|
| 131 |
+
with patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)):
|
| 132 |
+
code = self.render(kernel=kernel, **kwargs)
|
| 133 |
+
_, call_args, _, _ = kernel.args.python_argdefs()
|
| 134 |
+
autotuning_log.debug("Generated Code:\n%s", code)
|
| 135 |
+
autotuning_log.debug(
|
| 136 |
+
"Args: cpp_argdefs: %s, python_argdefs: %s",
|
| 137 |
+
kernel.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE),
|
| 138 |
+
kernel.args.python_argdefs(),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
input_reorder = (
|
| 142 |
+
self.input_reorder
|
| 143 |
+
if self.input_reorder is not None
|
| 144 |
+
else list(range(len(self.input_nodes)))
|
| 145 |
+
)
|
| 146 |
+
expected_args = list(
|
| 147 |
+
unique(self.input_nodes[idx].get_name() for idx in input_reorder)
|
| 148 |
+
)
|
| 149 |
+
expected_args.extend([self.output_node.get_name()])
|
| 150 |
+
assert list(call_args)[: len(expected_args)] == expected_args, (
|
| 151 |
+
call_args,
|
| 152 |
+
expected_args,
|
| 153 |
+
)
|
| 154 |
+
V.graph.sizevars.size_hints(map(sympy.expand, call_args[len(expected_args) :]))
|
| 155 |
+
size_args = V.graph.sizevars.size_hints(kernel.get_dynamic_shape_args())
|
| 156 |
+
offset_args = V.graph.sizevars.size_hints(kernel.get_offset_args())
|
| 157 |
+
|
| 158 |
+
if key is not None:
|
| 159 |
+
self.code_cache[key] = code, size_args, offset_args
|
| 160 |
+
|
| 161 |
+
# extra args has runtime params, which shouldn't be cached
|
| 162 |
+
extra_args = tuple(
|
| 163 |
+
list(size_args) + list(offset_args) + self.get_runtime_arg_values(**kwargs)
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
return code, extra_args
|
| 167 |
+
|
| 168 |
+
def generate( # type: ignore[override]
|
| 169 |
+
self,
|
| 170 |
+
name: str,
|
| 171 |
+
description: str,
|
| 172 |
+
input_key: str,
|
| 173 |
+
layout_repr: str,
|
| 174 |
+
input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
|
| 175 |
+
output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
|
| 176 |
+
**kwargs,
|
| 177 |
+
) -> CUDATemplateCaller:
|
| 178 |
+
"""
|
| 179 |
+
Generates the CUDA template caller object for the given GEMM template and operation.
|
| 180 |
+
This CUDATemplateCaller may be used to call and benchmark the generated CUDA kernel
|
| 181 |
+
in a standalone manner to enable Autotuning.
|
| 182 |
+
|
| 183 |
+
Args:
|
| 184 |
+
description: op name followed by swizzle.
|
| 185 |
+
kwargs: Additional keyword arguments.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
A CUDATemplateCaller object representing the generated CUDA template caller.
|
| 189 |
+
"""
|
| 190 |
+
code, extra_args = self.generate_code_and_args(
|
| 191 |
+
name=name,
|
| 192 |
+
input_key=input_key,
|
| 193 |
+
layout_repr=layout_repr,
|
| 194 |
+
**kwargs,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
# not caching since kernel name is needed below
|
| 198 |
+
kernel_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()[:8]
|
| 199 |
+
kernel_name = f"cutlass_{kernel_hash}"
|
| 200 |
+
code = code.replace(self.name, kernel_name)
|
| 201 |
+
|
| 202 |
+
# create the BenchmarkRequest
|
| 203 |
+
bmreq = CUDABenchmarkRequest(
|
| 204 |
+
kernel_name=kernel_name,
|
| 205 |
+
input_tensor_meta=input_tensor_meta,
|
| 206 |
+
output_tensor_meta=output_tensor_meta,
|
| 207 |
+
extra_args=extra_args,
|
| 208 |
+
source_code=code,
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
# kwargs has "op" argument in case of CUTLASSGemmTemplate
|
| 212 |
+
op = kwargs["op"]
|
| 213 |
+
if not op:
|
| 214 |
+
supports_epilogue_fusion = False
|
| 215 |
+
else:
|
| 216 |
+
# epilogue fusion is only supported for TMA kernels
|
| 217 |
+
supports_epilogue_fusion = self.supports_epilogue_fusion(op)
|
| 218 |
+
|
| 219 |
+
def make_kernel_render(
|
| 220 |
+
template_node: CUDATemplateBuffer,
|
| 221 |
+
epilogue_nodes: Optional[list[BaseSchedulerNode]] = None,
|
| 222 |
+
) -> tuple[CUDATemplateKernel, functools.partial[str]]:
|
| 223 |
+
assert supports_epilogue_fusion or not epilogue_nodes, (
|
| 224 |
+
"epilogue fusion is not supported for this kernel"
|
| 225 |
+
)
|
| 226 |
+
kernel = CUDATemplateKernel(
|
| 227 |
+
kernel_name=str(Placeholder.KERNEL_NAME),
|
| 228 |
+
runtime_arg_info=self.get_runtime_arg_info(),
|
| 229 |
+
runtime_arg_values=self.get_runtime_arg_values(**kwargs),
|
| 230 |
+
)
|
| 231 |
+
render = functools.partial(
|
| 232 |
+
self.render,
|
| 233 |
+
kernel=kernel,
|
| 234 |
+
template_buffer_node=template_node,
|
| 235 |
+
epilogue_nodes=epilogue_nodes,
|
| 236 |
+
**kwargs, # includes "op" argument in case of CUTLASSGemmTemplate
|
| 237 |
+
)
|
| 238 |
+
return kernel, render
|
| 239 |
+
|
| 240 |
+
return CUDATemplateCaller(
|
| 241 |
+
kernel_name,
|
| 242 |
+
"cutlass_gemm",
|
| 243 |
+
self.input_nodes,
|
| 244 |
+
self.output_node.get_layout(),
|
| 245 |
+
make_kernel_render,
|
| 246 |
+
bmreq,
|
| 247 |
+
supports_epilogue_fusion,
|
| 248 |
+
self,
|
| 249 |
+
kwargs,
|
| 250 |
+
description,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
def header(self) -> IndentedBuffer:
|
| 254 |
+
res = IndentedBuffer()
|
| 255 |
+
res.splice(
|
| 256 |
+
"""
|
| 257 |
+
#include <exception>
|
| 258 |
+
#include <iostream>
|
| 259 |
+
#include <memory>
|
| 260 |
+
#include <random>
|
| 261 |
+
#include <vector>
|
| 262 |
+
"""
|
| 263 |
+
)
|
| 264 |
+
return res
|
| 265 |
+
|
| 266 |
+
def globals(self) -> IndentedBuffer:
|
| 267 |
+
res = IndentedBuffer()
|
| 268 |
+
res.splice(
|
| 269 |
+
"""
|
| 270 |
+
// We compile all models with -fvisibility=hidden. Any symbols that need to be
|
| 271 |
+
// exposed in the final shared library must be declared with PT_EXPORT to make
|
| 272 |
+
// them visible.
|
| 273 |
+
#ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++)
|
| 274 |
+
#define PT_EXPORT __attribute__((__visibility__("default")))
|
| 275 |
+
#else
|
| 276 |
+
#ifdef _WIN32
|
| 277 |
+
#define PT_EXPORT __declspec(dllexport)
|
| 278 |
+
#else
|
| 279 |
+
#define PT_EXPORT
|
| 280 |
+
#endif
|
| 281 |
+
#endif
|
| 282 |
+
"""
|
| 283 |
+
)
|
| 284 |
+
return res
|
| 285 |
+
|
| 286 |
+
def render(self, **kwargs) -> str:
|
| 287 |
+
raise NotImplementedError
|
| 288 |
+
|
| 289 |
+
def get_runtime_arg_info(self) -> list[ArgInfo]:
|
| 290 |
+
return []
|
| 291 |
+
|
| 292 |
+
def get_runtime_arg_values(self, **kwargs) -> list[Any]:
|
| 293 |
+
return []
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class CUTLASSTemplate(CUDATemplate):
|
| 297 |
+
"""
|
| 298 |
+
CUTLASSTemplate is a class that provides a template for generating CUTLASS Templates. Used as a baseclass for the
|
| 299 |
+
CUTLASSGemmTemplate, providing functionality that might also be relevant for non-GEMM CUTLASS Kernels.
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
def header(self) -> IndentedBuffer:
|
| 303 |
+
res = super().header()
|
| 304 |
+
res.splice(
|
| 305 |
+
"""
|
| 306 |
+
#include "cute/tensor.hpp"
|
| 307 |
+
#include "cutlass/cutlass.h"
|
| 308 |
+
#include "cutlass/numeric_types.h"
|
| 309 |
+
#include "cutlass/tensor_ref.h"
|
| 310 |
+
#include "cutlass/util/host_tensor.h"
|
| 311 |
+
#include "cutlass/util/reference/host/tensor_fill.h"
|
| 312 |
+
#include "cutlass/util/reference/device/tensor_fill.h"
|
| 313 |
+
#include "cutlass/util/device_memory.h"
|
| 314 |
+
"""
|
| 315 |
+
)
|
| 316 |
+
return res
|
| 317 |
+
|
| 318 |
+
def globals(self) -> IndentedBuffer:
|
| 319 |
+
res = super().globals()
|
| 320 |
+
res.splice(
|
| 321 |
+
"""
|
| 322 |
+
using namespace cute;
|
| 323 |
+
#define CUTLASS_CHECK(status) \\
|
| 324 |
+
{ \\
|
| 325 |
+
cutlass::Status error = status; \\
|
| 326 |
+
if (error != cutlass::Status::kSuccess) { \\
|
| 327 |
+
auto msg = std::string("[") + __FILE__ + "] Got cutlass error: " + \\
|
| 328 |
+
cutlassGetStatusString(error) + " at: " + std::to_string(__LINE__); \\
|
| 329 |
+
throw std::runtime_error(msg); \\
|
| 330 |
+
} \\
|
| 331 |
+
}
|
| 332 |
+
|
| 333 |
+
// Used as pass-through functor in EVT just for type casting / rounding
|
| 334 |
+
template <typename T>
|
| 335 |
+
struct identity_op {
|
| 336 |
+
CUTLASS_HOST_DEVICE
|
| 337 |
+
T operator()(T val) const { return val; }
|
| 338 |
+
};
|
| 339 |
+
|
| 340 |
+
"""
|
| 341 |
+
)
|
| 342 |
+
return res
|
| 343 |
+
|
| 344 |
+
def cute_int(self, int_str: str, var_name: str) -> str:
|
| 345 |
+
res = ""
|
| 346 |
+
if int_str in ("1", "1L"):
|
| 347 |
+
res = "cute::Int<1>{}"
|
| 348 |
+
else:
|
| 349 |
+
res = int_str
|
| 350 |
+
|
| 351 |
+
return f"{res} /* {var_name} */"
|
| 352 |
+
|
| 353 |
+
_DTYPE_TO_CUTLASS = {
|
| 354 |
+
torch.float32: "float",
|
| 355 |
+
torch.float64: "double",
|
| 356 |
+
torch.float16: "cutlass::half_t",
|
| 357 |
+
torch.int32: "int32_t",
|
| 358 |
+
torch.int16: "int16_t",
|
| 359 |
+
torch.int8: "int8_t",
|
| 360 |
+
torch.uint8: "uint8_t",
|
| 361 |
+
torch.bool: "bool",
|
| 362 |
+
torch.bfloat16: "cutlass::bfloat16_t",
|
| 363 |
+
torch.float8_e4m3fn: "cutlass::float_e4m3_t",
|
| 364 |
+
}
|
| 365 |
+
|
| 366 |
+
_DTYPE_TO_CUTLASS_SPARSE_META = {
|
| 367 |
+
torch.int32: "uint32_t",
|
| 368 |
+
torch.int16: "uint16_t",
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
def cutlass_type_cast(self, node: IRNode, ptr: str) -> str:
|
| 372 |
+
if node is None:
|
| 373 |
+
return ptr
|
| 374 |
+
else:
|
| 375 |
+
return f"({self._DTYPE_TO_CUTLASS.get(node.get_dtype())}*)({ptr})"
|
| 376 |
+
|
| 377 |
+
def cutlass_sparse_meta_type_cast(self, node: IRNode, ptr: str) -> str:
|
| 378 |
+
if node is None:
|
| 379 |
+
return ptr
|
| 380 |
+
else:
|
| 381 |
+
return (
|
| 382 |
+
f"({self._DTYPE_TO_CUTLASS_SPARSE_META.get(node.get_dtype())}*)({ptr})"
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
@override
|
| 386 |
+
def get_runtime_arg_info(self) -> list[ArgInfo]:
|
| 387 |
+
return [ArgInfo("swizzle", "const uint8_t")]
|
| 388 |
+
|
| 389 |
+
@override
|
| 390 |
+
def get_runtime_arg_values(self, **kwargs) -> list[Any]:
|
| 391 |
+
"""
|
| 392 |
+
Helper method to retrieve runtime args from generate kwargs
|
| 393 |
+
"""
|
| 394 |
+
return [kwargs[arg.name] for arg in self.get_runtime_arg_info()]
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_cache.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import functools
|
| 3 |
+
import hashlib
|
| 4 |
+
import inspect
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
import os
|
| 8 |
+
import time
|
| 9 |
+
from typing import Any, Optional
|
| 10 |
+
|
| 11 |
+
import torch._inductor.config as config
|
| 12 |
+
from torch._inductor.codecache import cutlass_key
|
| 13 |
+
from torch._inductor.codegen.cuda import cutlass_utils, serialization
|
| 14 |
+
from torch._inductor.codegen.cuda.cuda_env import get_cuda_arch, get_cuda_version
|
| 15 |
+
from torch._inductor.codegen.cuda.serialization import get_cutlass_operation_serializer
|
| 16 |
+
from torch._inductor.runtime.cache_dir_utils import cache_dir
|
| 17 |
+
from torch._inductor.utils import clear_on_fresh_cache
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
log = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
CONFIG_PREFIX: str = "configs"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def get_config_request_key(
|
| 27 |
+
arch: str,
|
| 28 |
+
cuda_version: str,
|
| 29 |
+
instantiation_level: str,
|
| 30 |
+
) -> str:
|
| 31 |
+
"""
|
| 32 |
+
Return a key for the full ops, based on cutlass key, arch, cuda version, instantiation level, and serialization.py file hash.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
# Get hash of serialization.py and cutlass_utils.py files using their module file paths
|
| 36 |
+
def get_file_hash(file_module):
|
| 37 |
+
file_path = inspect.getfile(file_module)
|
| 38 |
+
with open(file_path, "rb") as f:
|
| 39 |
+
return hashlib.sha256(f.read()).hexdigest()
|
| 40 |
+
|
| 41 |
+
serialization_hash = get_file_hash(serialization)
|
| 42 |
+
cutlass_utils_hash = get_file_hash(cutlass_utils)
|
| 43 |
+
|
| 44 |
+
hash_target = "-".join(
|
| 45 |
+
[
|
| 46 |
+
cutlass_key().hex(),
|
| 47 |
+
arch,
|
| 48 |
+
cuda_version,
|
| 49 |
+
instantiation_level,
|
| 50 |
+
serialization_hash,
|
| 51 |
+
cutlass_utils_hash,
|
| 52 |
+
]
|
| 53 |
+
)
|
| 54 |
+
return hashlib.sha256(hash_target.encode("utf-8")).hexdigest()[0:8]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _generate_config_filename(request_key: str) -> str:
|
| 58 |
+
"""
|
| 59 |
+
Generate a filename for the full ops.
|
| 60 |
+
"""
|
| 61 |
+
return f"{CONFIG_PREFIX}_{request_key}.json"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@clear_on_fresh_cache
|
| 65 |
+
@functools.cache
|
| 66 |
+
def maybe_fetch_ops() -> Optional[list[Any]]:
|
| 67 |
+
"""
|
| 68 |
+
Fetch ops from databases.
|
| 69 |
+
"""
|
| 70 |
+
if config.force_disable_caches:
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
# setup
|
| 74 |
+
arch: str = get_cuda_arch()
|
| 75 |
+
# get_cuda_version might return "12.4.0" or "12.4"
|
| 76 |
+
# but we want to use "12.4"
|
| 77 |
+
version: str = ".".join(get_cuda_version().split(".")[:2])
|
| 78 |
+
instantiation_level: str = config.cuda.cutlass_instantiation_level
|
| 79 |
+
|
| 80 |
+
# filename and filepath
|
| 81 |
+
request_key: str = get_config_request_key(arch, version, instantiation_level)
|
| 82 |
+
filename: str = _generate_config_filename(request_key)
|
| 83 |
+
filepath: str = os.path.join(cache_dir(), filename)
|
| 84 |
+
|
| 85 |
+
# try fetch
|
| 86 |
+
serialized_ops: Optional[list[str]] = None
|
| 87 |
+
start_time = time.time()
|
| 88 |
+
if os.path.isfile(filepath):
|
| 89 |
+
# locally
|
| 90 |
+
try:
|
| 91 |
+
with open(filepath) as f:
|
| 92 |
+
serialized_ops = json.load(f)
|
| 93 |
+
|
| 94 |
+
assert isinstance(serialized_ops, list), (
|
| 95 |
+
f"Expected serialized ops is a list, got {type(serialized_ops)}"
|
| 96 |
+
)
|
| 97 |
+
except Exception:
|
| 98 |
+
log.warning(
|
| 99 |
+
"Failed to load CUTLASS config %s from local cache",
|
| 100 |
+
filename,
|
| 101 |
+
exc_info=True,
|
| 102 |
+
)
|
| 103 |
+
serialized_ops = None
|
| 104 |
+
elif config.is_fbcode():
|
| 105 |
+
from torch._inductor.fb.cutlass_remote_cache import (
|
| 106 |
+
maybe_fetch_cutlass_configs_from_remote,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
# from remote
|
| 110 |
+
serialized_ops = maybe_fetch_cutlass_configs_from_remote(filepath)
|
| 111 |
+
|
| 112 |
+
if serialized_ops is None:
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
# deserialize
|
| 116 |
+
serializer = get_cutlass_operation_serializer()
|
| 117 |
+
full_ops = [serializer.deserialize(x) for x in serialized_ops] # type: ignore[union-attr]
|
| 118 |
+
log.info("Loaded ops from %s cache in %.3fs", filename, time.time() - start_time)
|
| 119 |
+
return full_ops
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/__init__.py
ADDED
|
File without changes
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__version__ = torch.version.cuda
|
| 5 |
+
|
| 6 |
+
from .cuda import * # noqa: F403
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/cuda.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code="no-untyped-def"
|
| 2 |
+
# flake8: noqa
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class CUdeviceptr:
|
| 7 |
+
pass
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CUstream:
|
| 11 |
+
def __init__(self, v):
|
| 12 |
+
pass
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class CUresult:
|
| 16 |
+
CUDA_SUCCESS = True
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class nvrtc:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def cuDeviceGetCount():
|
| 24 |
+
return (CUresult.CUDA_SUCCESS, torch.cuda.device_count())
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/cudart.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code="no-untyped-def"
|
| 2 |
+
import torch.cuda
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class cudaError_t:
|
| 6 |
+
cudaSuccess = True
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def cudaFree(n):
|
| 10 |
+
return (cudaError_t.cudaSuccess,)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def cudaGetDeviceProperties(d):
|
| 14 |
+
class DummyError:
|
| 15 |
+
value = False
|
| 16 |
+
|
| 17 |
+
return (DummyError(), torch.cuda.get_device_properties(d))
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/pydot/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code="var-annotated"
|
| 2 |
+
Dot = None
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/scipy/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# typing: ignore
|
| 2 |
+
# flake8: noqa
|
| 3 |
+
from .special import *
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/scipy/special.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code="var-annotated"
|
| 2 |
+
erf = None
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/evt_extensions.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable
|
| 2 |
+
from typing import Any, Union
|
| 3 |
+
|
| 4 |
+
from sympy import Expr
|
| 5 |
+
|
| 6 |
+
from torch._inductor.ir import (
|
| 7 |
+
ComputedBuffer,
|
| 8 |
+
InputBuffer,
|
| 9 |
+
is_contiguous_strides_for_shape,
|
| 10 |
+
)
|
| 11 |
+
from torch.utils._ordered_set import OrderedSet
|
| 12 |
+
|
| 13 |
+
from ..cutlass_utils import torch_dtype_to_cutlass_type, try_import_cutlass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
EpilogueFunctor = Any # EpilogueFunctor local class defined in _trace
|
| 17 |
+
Buffer = Union[ComputedBuffer, InputBuffer]
|
| 18 |
+
CutlassTupleType = Any # cutlass.backend.c_types.tuple_factory_.<locals>.TupleType
|
| 19 |
+
CutlassVisitorType = Any # cutlass.backend.c_types.visitor_factory.<locals>.VisitorType
|
| 20 |
+
CutlassArgType = (
|
| 21 |
+
Any # Can be a CutlassTupleType, CutlassVisitorType, EmptyByte, or ctype.c_void_p
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if try_import_cutlass():
|
| 26 |
+
import ast
|
| 27 |
+
import ctypes
|
| 28 |
+
import textwrap
|
| 29 |
+
from typing import Union
|
| 30 |
+
|
| 31 |
+
from cutlass_cppgen.backend.c_types import ( # type: ignore[import-not-found]
|
| 32 |
+
EmptyByte,
|
| 33 |
+
)
|
| 34 |
+
from cutlass_cppgen.backend.epilogue import ( # type: ignore[import-not-found]
|
| 35 |
+
dtype2ctype,
|
| 36 |
+
)
|
| 37 |
+
from cutlass_cppgen.backend.evt import ( # type: ignore[import-not-found]
|
| 38 |
+
EpilogueFunctorVisitor,
|
| 39 |
+
)
|
| 40 |
+
from cutlass_cppgen.backend.evt.backend.emitter_base import ( # type: ignore[import-not-found]
|
| 41 |
+
FusionCallbacks,
|
| 42 |
+
)
|
| 43 |
+
from cutlass_cppgen.backend.evt.backend.sm90_emitter import ( # type: ignore[import-not-found]
|
| 44 |
+
CollectiveEpilogue,
|
| 45 |
+
)
|
| 46 |
+
from cutlass_cppgen.backend.evt.frontend import ( # type: ignore[import-not-found]
|
| 47 |
+
PythonASTFrontend,
|
| 48 |
+
)
|
| 49 |
+
from cutlass_cppgen.backend.evt.ir.tensor import ( # type: ignore[import-not-found]
|
| 50 |
+
Tensor as CutlassTensor,
|
| 51 |
+
)
|
| 52 |
+
from cutlass_library import (
|
| 53 |
+
DataType,
|
| 54 |
+
EpilogueScheduleType,
|
| 55 |
+
LayoutType,
|
| 56 |
+
TileDescription,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
from torch._inductor.codegen.cuda import cuda_env
|
| 60 |
+
from torch._inductor.utils import IndentedBuffer
|
| 61 |
+
|
| 62 |
+
_CUTLASS_C_DTYPES = OrderedSet(dtype2ctype.values()) # type: ignore[var-annotated]
|
| 63 |
+
|
| 64 |
+
class EVTArgRenames:
|
| 65 |
+
"""Handles mapping buffer names to variable names in the cpp kernel signature and body"""
|
| 66 |
+
|
| 67 |
+
def __init__(self) -> None:
|
| 68 |
+
self.buf_renames: dict[str, str] = {}
|
| 69 |
+
|
| 70 |
+
def new_name(self, name: str) -> str:
|
| 71 |
+
if name in self.buf_renames:
|
| 72 |
+
return self.buf_renames[name]
|
| 73 |
+
else:
|
| 74 |
+
new_name = f"ptr_{len(self.buf_renames)}"
|
| 75 |
+
self.buf_renames[name] = new_name
|
| 76 |
+
return new_name
|
| 77 |
+
|
| 78 |
+
def get(self, name: str) -> str:
|
| 79 |
+
return self.buf_renames.get(name, name)
|
| 80 |
+
|
| 81 |
+
def create_example_tensors(
|
| 82 |
+
var_name_to_buffer_name: dict[str, str],
|
| 83 |
+
name_to_buffer: dict[str, Buffer],
|
| 84 |
+
size_hint_fn: Callable[[Union[Expr, int]], int],
|
| 85 |
+
) -> dict[str, CutlassTensor]:
|
| 86 |
+
def cutlass_tensor_from_buffer(
|
| 87 |
+
buffer: Buffer,
|
| 88 |
+
) -> CutlassTensor:
|
| 89 |
+
shape = buffer.get_layout().size
|
| 90 |
+
stride = buffer.get_layout().stride
|
| 91 |
+
shape = tuple(size_hint_fn(x) for x in shape)
|
| 92 |
+
stride = tuple(size_hint_fn(x) for x in stride)
|
| 93 |
+
|
| 94 |
+
is_row_major = is_contiguous_strides_for_shape(stride, shape)
|
| 95 |
+
is_column_major = is_contiguous_strides_for_shape(stride[::-1], shape[::-1])
|
| 96 |
+
|
| 97 |
+
if not is_row_major and not is_column_major:
|
| 98 |
+
raise RuntimeError(
|
| 99 |
+
f"Cannot create example tensor for {buffer.get_name()} with \
|
| 100 |
+
non-contiguous layout, received stride: {stride} and shape: {shape}"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
return CutlassTensor(
|
| 104 |
+
shape=shape,
|
| 105 |
+
layout_tag=(
|
| 106 |
+
LayoutType.RowMajor if is_row_major else LayoutType.ColumnMajor
|
| 107 |
+
),
|
| 108 |
+
element=torch_dtype_to_cutlass_type(buffer.get_layout().dtype),
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
return {
|
| 112 |
+
key: cutlass_tensor_from_buffer(name_to_buffer[name])
|
| 113 |
+
for key, name in var_name_to_buffer_name.items()
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
def trace(
|
| 117 |
+
fn_src: str,
|
| 118 |
+
example_tensors: dict[str, CutlassTensor],
|
| 119 |
+
accum_type: DataType,
|
| 120 |
+
output_type: DataType,
|
| 121 |
+
tile_description: TileDescription,
|
| 122 |
+
epilogue_schedule: EpilogueScheduleType,
|
| 123 |
+
name_to_buffer: dict[str, Buffer],
|
| 124 |
+
size_hint_fn: Callable[[Union[Expr, int]], int],
|
| 125 |
+
**kwargs: dict[str, Any],
|
| 126 |
+
) -> tuple[str, str, str, EVTArgRenames]:
|
| 127 |
+
cuda_arch = int(cuda_env.get_cuda_arch()) # type: ignore[arg-type]
|
| 128 |
+
assert cuda_arch >= 90, "Only SM90+ is supported for EVT"
|
| 129 |
+
epilogue_functor = _trace(fn_src, example_tensors, cuda_arch, **kwargs)
|
| 130 |
+
visitor = EpilogueFunctorVisitor(cuda_arch, epilogue_functor)
|
| 131 |
+
fusion_callbacks = FusionCallbacks(visitor.graph, cuda_arch, emit_CD=False)
|
| 132 |
+
collective_epilogue = CollectiveEpilogue(
|
| 133 |
+
tile_description,
|
| 134 |
+
epilogue_schedule,
|
| 135 |
+
accum_type,
|
| 136 |
+
output_type,
|
| 137 |
+
fusion_callbacks,
|
| 138 |
+
)
|
| 139 |
+
evt_name, evt_code = collective_epilogue.emit()
|
| 140 |
+
evt_args, arg_renames = _render_argument_type(
|
| 141 |
+
epilogue_functor, name_to_buffer, size_hint_fn
|
| 142 |
+
)
|
| 143 |
+
return evt_name, evt_args, evt_code, arg_renames
|
| 144 |
+
|
| 145 |
+
# Based off of
|
| 146 |
+
# https://github.com/NVIDIA/cutlass/blob/df18f5e4f5de76bed8be1de8e4c245f2f5ec3020/python/cutlass/epilogue/epilogue.py#L117
|
| 147 |
+
# This is modified to enable directly passing the source code of the epilogue vs getting it from a bona-fide python function
|
| 148 |
+
# The reason for this is that inspect.getsource does not work with functions defined at runtime via exec/eval
|
| 149 |
+
def _trace(
|
| 150 |
+
fn_src: str,
|
| 151 |
+
example_tensors: dict[str, CutlassTensor],
|
| 152 |
+
cc: int,
|
| 153 |
+
**kwargs: Any,
|
| 154 |
+
) -> EpilogueFunctor:
|
| 155 |
+
class EpilogueFunctor(PythonASTFrontend):
|
| 156 |
+
def __init__(self, cc: int, **kwargs: Any):
|
| 157 |
+
self.source = textwrap.dedent(fn_src)
|
| 158 |
+
super().__init__(cc, **kwargs)
|
| 159 |
+
|
| 160 |
+
def parse(
|
| 161 |
+
self,
|
| 162 |
+
example_inputs: dict[str, CutlassTensor],
|
| 163 |
+
) -> None:
|
| 164 |
+
self.example_inputs = example_inputs
|
| 165 |
+
self.ast = ast.parse(self.source)
|
| 166 |
+
# pyrefly: ignore [missing-attribute]
|
| 167 |
+
self.visit(self.ast)
|
| 168 |
+
|
| 169 |
+
cc = int(cuda_env.get_cuda_arch())
|
| 170 |
+
epilogue_functor = EpilogueFunctor(cc=cc, **kwargs)
|
| 171 |
+
epilogue_functor.trace(example_tensors)
|
| 172 |
+
return epilogue_functor
|
| 173 |
+
|
| 174 |
+
def _render_argument_type(
|
| 175 |
+
epilogue_functor: EpilogueFunctor,
|
| 176 |
+
name_to_buffer: dict[str, Buffer],
|
| 177 |
+
size_hint_fn: Callable[[Union[Expr, int]], int],
|
| 178 |
+
) -> tuple[str, EVTArgRenames]:
|
| 179 |
+
epilogue_thread_type = epilogue_functor.epilogue_thread_type
|
| 180 |
+
arg_renames = EVTArgRenames()
|
| 181 |
+
|
| 182 |
+
# Fragile, but this is the only way to guarantee t is expected type because t is a local class
|
| 183 |
+
def is_nested_visitor_type(t: type) -> bool:
|
| 184 |
+
return (
|
| 185 |
+
".".join([t.__module__, t.__qualname__])
|
| 186 |
+
== "cutlass_cppgen.backend.c_types.visitor_factory.<locals>.VisitorType"
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
buffer = IndentedBuffer()
|
| 190 |
+
with buffer.set_tabwidth(2):
|
| 191 |
+
|
| 192 |
+
def render_argument_type(name: str, t: CutlassArgType) -> None:
|
| 193 |
+
if issubclass(t, ctypes.c_byte):
|
| 194 |
+
buffer.writeline(f"{{}}, /* {name} */")
|
| 195 |
+
else:
|
| 196 |
+
fields = [
|
| 197 |
+
(
|
| 198 |
+
fname,
|
| 199 |
+
_get_arg_from_node(
|
| 200 |
+
ty, name_to_buffer[name], size_hint_fn, arg_renames
|
| 201 |
+
),
|
| 202 |
+
)
|
| 203 |
+
for fname, ty in t._fields_
|
| 204 |
+
]
|
| 205 |
+
field_strs = [
|
| 206 |
+
f"/* {fname} */ {str(field)}" for fname, field in fields
|
| 207 |
+
]
|
| 208 |
+
buffer.writeline(f"{{{', '.join(field_strs)}}}, /* {name} */")
|
| 209 |
+
|
| 210 |
+
def render_thread_type(name: str, t: CutlassArgType) -> None:
|
| 211 |
+
if is_nested_visitor_type(t):
|
| 212 |
+
buffer.writeline(f"{{ /* {name} */")
|
| 213 |
+
with buffer.indent():
|
| 214 |
+
for name, inner_t in t._fields_:
|
| 215 |
+
render_thread_type(name, inner_t)
|
| 216 |
+
buffer.writeline("},")
|
| 217 |
+
else:
|
| 218 |
+
render_argument_type(name, t)
|
| 219 |
+
|
| 220 |
+
# unroll the recursion once to address special case formatting
|
| 221 |
+
# namely, no ending comma and no indentation for the outermost thread type
|
| 222 |
+
buffer.writeline("{ /* thread */")
|
| 223 |
+
with buffer.indent(3):
|
| 224 |
+
if is_nested_visitor_type(epilogue_thread_type):
|
| 225 |
+
with buffer.indent():
|
| 226 |
+
for name, inner_t in epilogue_thread_type._fields_:
|
| 227 |
+
render_thread_type(name, inner_t)
|
| 228 |
+
else:
|
| 229 |
+
render_argument_type("thread", epilogue_thread_type)
|
| 230 |
+
buffer.writeline("}")
|
| 231 |
+
|
| 232 |
+
return buffer.getvalue(), arg_renames
|
| 233 |
+
|
| 234 |
+
def _get_arg_from_node(
|
| 235 |
+
arg_ty: type,
|
| 236 |
+
node: Buffer,
|
| 237 |
+
size_hint_fn: Callable[[Union[Expr, int]], int],
|
| 238 |
+
arg_renames: EVTArgRenames,
|
| 239 |
+
) -> str:
|
| 240 |
+
from ..cuda_template import CUTLASSTemplate
|
| 241 |
+
|
| 242 |
+
# Today, arguments are either a pointer to the
|
| 243 |
+
# node's memory, a stride tuple, the datatype
|
| 244 |
+
# Once again, need to check for local class type for stride tuple
|
| 245 |
+
if (
|
| 246 |
+
str(arg_ty)
|
| 247 |
+
== "<class 'cutlass_cppgen.backend.c_types.tuple_factory_.<locals>.TupleType'>"
|
| 248 |
+
):
|
| 249 |
+
DEFAULT_STRIDE_LEN = 3
|
| 250 |
+
assert len(node.get_layout().stride) <= DEFAULT_STRIDE_LEN
|
| 251 |
+
stride = [size_hint_fn(x) for x in node.get_layout().stride]
|
| 252 |
+
for _ in range(DEFAULT_STRIDE_LEN - len(stride)):
|
| 253 |
+
stride.append(0)
|
| 254 |
+
|
| 255 |
+
def render_stride(x: int) -> str:
|
| 256 |
+
# Handle EBO for 0 and 1
|
| 257 |
+
if x == 0:
|
| 258 |
+
return "_0{}"
|
| 259 |
+
elif x == 1:
|
| 260 |
+
return "_1{}"
|
| 261 |
+
else:
|
| 262 |
+
return str(x)
|
| 263 |
+
|
| 264 |
+
return f"{{{', '.join([render_stride(x) for x in stride])}}}"
|
| 265 |
+
|
| 266 |
+
elif issubclass(arg_ty, ctypes.c_void_p):
|
| 267 |
+
name = arg_renames.new_name(node.get_name())
|
| 268 |
+
return f"({CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]}*) ({name} + {name}_offset)"
|
| 269 |
+
elif (
|
| 270 |
+
arg_ty in _CUTLASS_C_DTYPES
|
| 271 |
+
): # Assumption: this is the element dtype, this holds for all cutlass ir nodes currently
|
| 272 |
+
return f"{CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]}(0)"
|
| 273 |
+
elif issubclass(arg_ty, EmptyByte):
|
| 274 |
+
return "{}"
|
| 275 |
+
|
| 276 |
+
raise NotImplementedError(f"Unsupported arg type: {arg_ty}")
|
miniconda3/envs/ladir/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cutlass_lib_extensions/gemm_operation_extensions.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: ignore-errors
|
| 2 |
+
from ..cutlass_utils import try_import_cutlass
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
# copied / modified from original at
|
| 6 |
+
# https://github.com/NVIDIA/cutlass/blob/8783c41851cd3582490e04e69e0cd756a8c1db7f/tools/library/scripts/gemm_operation.py#L658
|
| 7 |
+
|
| 8 |
+
if try_import_cutlass():
|
| 9 |
+
import enum
|
| 10 |
+
|
| 11 |
+
from cutlass_library.gemm_operation import * # noqa: F401, F403
|
| 12 |
+
from cutlass_library.library import * # noqa: F401, F403
|
| 13 |
+
|
| 14 |
+
_LOGGER = logging.getLogger(__name__)
|
| 15 |
+
|
| 16 |
+
class EmitGemmUniversal3xInstanceWithEVT:
|
| 17 |
+
"""Responsible for emitting a CUTLASS 3.x template definition"""
|
| 18 |
+
|
| 19 |
+
def __init__(self, operation_suffix="", evt_name=None):
|
| 20 |
+
self.operation_suffix = operation_suffix
|
| 21 |
+
self.includes = [
|
| 22 |
+
"cutlass/cutlass.h",
|
| 23 |
+
"cutlass/gemm/gemm.h",
|
| 24 |
+
"cutlass/numeric_types.h",
|
| 25 |
+
"cutlass/gemm/kernel/gemm_universal.hpp",
|
| 26 |
+
"cutlass/gemm/collective/collective_builder.hpp",
|
| 27 |
+
"cutlass/epilogue/collective/collective_builder.hpp",
|
| 28 |
+
]
|
| 29 |
+
self.builtin_epilogue_functor_template = """${epilogue_functor}<
|
| 30 |
+
${element_d},
|
| 31 |
+
${element_epilogue},
|
| 32 |
+
${element_c},
|
| 33 |
+
${element_epilogue}
|
| 34 |
+
>"""
|
| 35 |
+
|
| 36 |
+
self.evt_name = evt_name
|
| 37 |
+
self.gemm_template = """
|
| 38 |
+
using ${operation_name}_epilogue =
|
| 39 |
+
typename cutlass::epilogue::collective::CollectiveBuilder<
|
| 40 |
+
${arch}, ${opcode_class_epi},
|
| 41 |
+
cute::Shape<cute::_${tile_shape_m}, cute::_${tile_shape_n}, cute::_${tile_shape_k}>,
|
| 42 |
+
cute::Shape<${cluster_shape_m}, ${cluster_shape_n}, ${cluster_shape_k}>,
|
| 43 |
+
${epi_tile_mn},
|
| 44 |
+
${element_accumulator}, ${element_epilogue},
|
| 45 |
+
${element_c}, ${layout_c}, ${align_c},
|
| 46 |
+
${element_d}, ${layout_d}, ${align_d},
|
| 47 |
+
${epilogue_schedule},
|
| 48 |
+
${epilogue_functor}
|
| 49 |
+
>::CollectiveOp;
|
| 50 |
+
|
| 51 |
+
${mixed_dtype_prepare_code}
|
| 52 |
+
|
| 53 |
+
using ${operation_name}_mainloop =
|
| 54 |
+
typename cutlass::gemm::collective::CollectiveBuilder<
|
| 55 |
+
${arch}, ${opcode_class_main},
|
| 56 |
+
${element_a}, ${layout_a}, ${align_a},
|
| 57 |
+
${element_b}, ${layout_b}, ${align_b},
|
| 58 |
+
${element_accumulator},
|
| 59 |
+
cute::Shape<cute::_${tile_shape_m}, cute::_${tile_shape_n}, cute::_${tile_shape_k}>,
|
| 60 |
+
cute::Shape<${cluster_shape_m}, ${cluster_shape_n}, ${cluster_shape_k}>,
|
| 61 |
+
${stages},
|
| 62 |
+
${kernel_schedule}
|
| 63 |
+
>::CollectiveOp;
|
| 64 |
+
|
| 65 |
+
// Gemm operator ${operation_name}
|
| 66 |
+
using ${operation_name}_base = cutlass::gemm::kernel::GemmUniversal<
|
| 67 |
+
${problem_shape},
|
| 68 |
+
${operation_name}_mainloop,
|
| 69 |
+
${operation_name}_epilogue,
|
| 70 |
+
${tile_scheduler}>;
|
| 71 |
+
|
| 72 |
+
// Define named type
|
| 73 |
+
struct ${operation_name} :
|
| 74 |
+
public ${operation_name}_base { };
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
#
|
| 79 |
+
def instance_template(self):
|
| 80 |
+
return """
|
| 81 |
+
${compile_guard_start}
|
| 82 |
+
{
|
| 83 |
+
using GemmKernel = cutlass::gemm::device::GemmUniversalAdapter<${operation_name}>;
|
| 84 |
+
manifest.append(
|
| 85 |
+
new ${gemm_kind}<GemmKernel>("${operation_name}"));
|
| 86 |
+
}
|
| 87 |
+
${compile_guard_end}
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
def emit_block_scale_epilogue_functor(self, operation):
|
| 91 |
+
block_scaled_template = """
|
| 92 |
+
${epilogue_functor}<
|
| 93 |
+
${epi_vs},
|
| 94 |
+
${element_d},
|
| 95 |
+
${element_accumulator},
|
| 96 |
+
${element_sfd},
|
| 97 |
+
${layout_sfd},
|
| 98 |
+
${element_c},
|
| 99 |
+
${element_scalar}
|
| 100 |
+
>
|
| 101 |
+
"""
|
| 102 |
+
block_scaled_values = {
|
| 103 |
+
"epi_vs": str(operation.ScaleFactorVectorSize),
|
| 104 |
+
"element_d": str(DataTypeTag[operation.D.element]),
|
| 105 |
+
"element_sfd": str(DataTypeTag[operation.ScaleFactorD.element]),
|
| 106 |
+
"layout_sfd": LayoutTag[operation.ScaleFactorD.layout],
|
| 107 |
+
"epilogue_functor": EpilogueFunctor3xTag[
|
| 108 |
+
EpilogueFunctor3x.LinearCombinationBlockScaleFactor
|
| 109 |
+
],
|
| 110 |
+
"element_accumulator": str(DataTypeTag[operation.accumulator_type()]),
|
| 111 |
+
"element_scalar": str(DataTypeTag[operation.accumulator_type()]),
|
| 112 |
+
"element_c": str(DataTypeTag[operation.C.element]),
|
| 113 |
+
}
|
| 114 |
+
return SubstituteTemplate(block_scaled_template, block_scaled_values)
|
| 115 |
+
|
| 116 |
+
@staticmethod
|
| 117 |
+
def pointerize_if_grouped(operation, layout):
|
| 118 |
+
return layout if not is_grouped(operation.gemm_kind) else layout + "* "
|
| 119 |
+
|
| 120 |
+
@staticmethod
|
| 121 |
+
def problem_shape(operation):
|
| 122 |
+
gemm_shape_type = "cute::Shape<int,int,int,int>"
|
| 123 |
+
grouped_gemm_shape_type = "cute::Shape<int,int,int>"
|
| 124 |
+
grouped_gemm_shape_type = (
|
| 125 |
+
"cutlass::gemm::GroupProblemShape<" + grouped_gemm_shape_type + ">"
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
return (
|
| 129 |
+
gemm_shape_type
|
| 130 |
+
if not is_grouped(operation.gemm_kind)
|
| 131 |
+
else grouped_gemm_shape_type
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def emit(self, operation):
|
| 135 |
+
"""Given a gem operation, emits a template definition of the operation"""
|
| 136 |
+
|
| 137 |
+
opcode_class_main = operation.tile_description.math_instruction.opcode_class
|
| 138 |
+
opcode_class_epi = opcode_class_main
|
| 139 |
+
|
| 140 |
+
tile_shape = operation.tile_description.tile_shape
|
| 141 |
+
instruction_shape = (
|
| 142 |
+
operation.tile_description.math_instruction.instruction_shape
|
| 143 |
+
)
|
| 144 |
+
cluster_m = operation.tile_description.cluster_shape[0]
|
| 145 |
+
cluster_n = operation.tile_description.cluster_shape[1]
|
| 146 |
+
|
| 147 |
+
tile_shape_m, tile_shape_n, tile_shape_k = tile_shape
|
| 148 |
+
|
| 149 |
+
# account for static/dynamic cluster shapes
|
| 150 |
+
cta_m = tile_shape[0] // cluster_m if cluster_m > 0 else tile_shape[0]
|
| 151 |
+
cta_n = tile_shape[1] // cluster_n if cluster_n > 0 else tile_shape[1]
|
| 152 |
+
|
| 153 |
+
# Shape passed to epilogue builder
|
| 154 |
+
is_sm100_kernel = operation.arch == 100
|
| 155 |
+
if is_sm100_kernel:
|
| 156 |
+
cta_m_per_mma_instruction = (
|
| 157 |
+
2 if "2sm" in operation.procedural_name() else 1
|
| 158 |
+
)
|
| 159 |
+
if cluster_m <= 0:
|
| 160 |
+
cta_m = cta_m // cta_m_per_mma_instruction
|
| 161 |
+
|
| 162 |
+
if opcode_class_main in [
|
| 163 |
+
OpcodeClass.TensorOp,
|
| 164 |
+
OpcodeClass.BlockScaledTensorOp,
|
| 165 |
+
]:
|
| 166 |
+
tile_shape_m = instruction_shape[0]
|
| 167 |
+
tile_shape_n = instruction_shape[1]
|
| 168 |
+
|
| 169 |
+
# stage count set to zero indicates builder automatic stage selection
|
| 170 |
+
if operation.tile_description.stages > 0:
|
| 171 |
+
stage_count_string = f"cutlass::gemm::collective::StageCount<\
|
| 172 |
+
{str(operation.tile_description.stages)}>"
|
| 173 |
+
else:
|
| 174 |
+
stage_count_string = (
|
| 175 |
+
f"cutlass::gemm::collective::StageCountAutoCarveout<static_cast<int>(\
|
| 176 |
+
sizeof(typename {str(operation.procedural_name())}_epilogue::SharedStorage))>"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
epi_tile_mn = "cutlass::epilogue::collective::EpilogueTileAuto"
|
| 180 |
+
|
| 181 |
+
(
|
| 182 |
+
instance_layout_A,
|
| 183 |
+
instance_layout_B,
|
| 184 |
+
instance_layout_C,
|
| 185 |
+
instance_layout_D,
|
| 186 |
+
) = (
|
| 187 |
+
operation.A.layout,
|
| 188 |
+
operation.B.layout,
|
| 189 |
+
operation.C.layout,
|
| 190 |
+
operation.D.layout,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
# 3.0 profiler integration only supports trivial epilogues for now
|
| 194 |
+
epilogue_vector_length = 1
|
| 195 |
+
|
| 196 |
+
# Support built-in epilogue functors or user-defined functions
|
| 197 |
+
if isinstance(operation.epilogue_functor, enum.Enum):
|
| 198 |
+
values = {
|
| 199 |
+
"element_epilogue": str(DataTypeTag[operation.element_epilogue]),
|
| 200 |
+
"epilogue_functor": EpilogueFunctor3xTag[
|
| 201 |
+
operation.epilogue_functor
|
| 202 |
+
],
|
| 203 |
+
}
|
| 204 |
+
epilogue_functor = SubstituteTemplate(
|
| 205 |
+
self.builtin_epilogue_functor_template, values
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
if (
|
| 209 |
+
is_block_scaled(operation.gemm_kind)
|
| 210 |
+
and operation.ScaleFactorD.element != DataType.void
|
| 211 |
+
):
|
| 212 |
+
epilogue_functor = self.emit_block_scale_epilogue_functor(operation)
|
| 213 |
+
else:
|
| 214 |
+
epilogue_functor = self.epilogue_functor.emit_declaration()
|
| 215 |
+
|
| 216 |
+
if (
|
| 217 |
+
is_block_scaled(operation.gemm_kind)
|
| 218 |
+
and operation.ScaleFactorD.element != DataType.void
|
| 219 |
+
):
|
| 220 |
+
epilogue_functor = self.emit_block_scale_epilogue_functor(operation)
|
| 221 |
+
|
| 222 |
+
#
|
| 223 |
+
# Cutlass3x complex kernels' ElementA(B) is a tuple in collective mainloop builder,
|
| 224 |
+
# e.g. cute::tuple<Element, Transform>, Transform : cute::identity / cute::conjugate.
|
| 225 |
+
element_a = (
|
| 226 |
+
DataTypeTag[operation.A.element]
|
| 227 |
+
if not operation.is_complex()
|
| 228 |
+
else f"cute::tuple<{str(DataTypeTag[operation.A.element])},\
|
| 229 |
+
{str(ComplexTransformTag3x[operation.A.complex_transform])}>"
|
| 230 |
+
)
|
| 231 |
+
element_b = (
|
| 232 |
+
DataTypeTag[operation.B.element]
|
| 233 |
+
if not operation.is_complex()
|
| 234 |
+
else f"cute::tuple<{str(DataTypeTag[operation.B.element])},\
|
| 235 |
+
{str(ComplexTransformTag3x[operation.B.complex_transform])}>"
|
| 236 |
+
)
|
| 237 |
+
epilogue_schedule_type = EpilogueScheduleTag[operation.epilogue_schedule]
|
| 238 |
+
|
| 239 |
+
if opcode_class_main == OpcodeClass.BlockScaledTensorOp:
|
| 240 |
+
is_no_smem_epilogue = operation.epilogue_schedule in [
|
| 241 |
+
EpilogueScheduleType.NoSmemWarpSpecialized1Sm,
|
| 242 |
+
EpilogueScheduleType.NoSmemWarpSpecialized2Sm,
|
| 243 |
+
]
|
| 244 |
+
grouped = is_grouped(operation.gemm_kind)
|
| 245 |
+
if cta_n == 256 and operation.kernel_schedule == to_grouped_schedule(
|
| 246 |
+
KernelScheduleType.Nvf4TmaWarpSpecialized1SmSm100, grouped
|
| 247 |
+
):
|
| 248 |
+
epi_tile_mn = "cute::Shape<cute::_128,cute::_64>"
|
| 249 |
+
if not is_no_smem_epilogue:
|
| 250 |
+
epilogue_schedule_type = EpilogueScheduleTag[
|
| 251 |
+
to_grouped_schedule(
|
| 252 |
+
EpilogueScheduleType.TmaWarpSpecialized1Sm, grouped
|
| 253 |
+
)
|
| 254 |
+
]
|
| 255 |
+
if cta_n == 256 and operation.kernel_schedule == to_grouped_schedule(
|
| 256 |
+
KernelScheduleType.Nvf4TmaWarpSpecialized2SmSm100, grouped
|
| 257 |
+
):
|
| 258 |
+
epi_tile_mn = "cute::Shape<cute::_128,cute::_64>"
|
| 259 |
+
if not is_no_smem_epilogue:
|
| 260 |
+
epilogue_schedule_type = EpilogueScheduleTag[
|
| 261 |
+
to_grouped_schedule(
|
| 262 |
+
EpilogueScheduleType.TmaWarpSpecialized2Sm, grouped
|
| 263 |
+
)
|
| 264 |
+
]
|
| 265 |
+
element_a = f"cute::tuple<{str(element_a)},{str(DataTypeTag[operation.ScaleFactorA])}>"
|
| 266 |
+
element_b = f"cute::tuple<{str(element_b)},{str(DataTypeTag[operation.ScaleFactorB])}>"
|
| 267 |
+
|
| 268 |
+
operation_name_str = operation.procedural_name()
|
| 269 |
+
layout_a_str = LayoutTag[instance_layout_A]
|
| 270 |
+
layout_b_str = LayoutTag[instance_layout_B]
|
| 271 |
+
mixed_dtype_prepare_code = ""
|
| 272 |
+
if operation.mixed_input_mode is not None:
|
| 273 |
+
A_dtype = operation.A.element
|
| 274 |
+
B_dtype = operation.B.element
|
| 275 |
+
A_dtype_bits = DataTypeSize[A_dtype]
|
| 276 |
+
B_dtype_bits = DataTypeSize[B_dtype]
|
| 277 |
+
is_A_dtype_narrow = A_dtype_bits < B_dtype_bits
|
| 278 |
+
if is_A_dtype_narrow:
|
| 279 |
+
narrow_dtype, wide_dtype = (A_dtype, B_dtype)
|
| 280 |
+
narrow_dtype_bits, wide_dtype_bits = (A_dtype_bits, B_dtype_bits)
|
| 281 |
+
else:
|
| 282 |
+
narrow_dtype, wide_dtype = (B_dtype, A_dtype)
|
| 283 |
+
narrow_dtype_bits, wide_dtype_bits = (B_dtype_bits, A_dtype_bits)
|
| 284 |
+
|
| 285 |
+
narrow_tag = DataTypeTag[narrow_dtype]
|
| 286 |
+
wide_tag = DataTypeTag[wide_dtype]
|
| 287 |
+
scale_tag = DataTypeTag[wide_dtype]
|
| 288 |
+
zero_tag = DataTypeTag[wide_dtype]
|
| 289 |
+
|
| 290 |
+
do_shuffle = False
|
| 291 |
+
value_shuffle_str = ""
|
| 292 |
+
if narrow_dtype_bits == 4 and wide_dtype_bits == 16:
|
| 293 |
+
value_shuffle_str = "cute::Layout<cute::Shape<cute::_2,cute::_4>, \
|
| 294 |
+
cute::Stride<cute::_4,cute::_1>>"
|
| 295 |
+
do_shuffle = True
|
| 296 |
+
if narrow_dtype_bits == 8 and wide_dtype_bits == 16:
|
| 297 |
+
value_shuffle_str = "cute::Layout<cute::Shape<cute::_2,cute::_2>, \
|
| 298 |
+
cute::Stride<cute::_2,cute::_1>>"
|
| 299 |
+
do_shuffle = True
|
| 300 |
+
do_shuffle = operation.mixed_input_shuffle and do_shuffle
|
| 301 |
+
|
| 302 |
+
if do_shuffle:
|
| 303 |
+
if is_A_dtype_narrow:
|
| 304 |
+
stride_narrow_str = (
|
| 305 |
+
f"cutlass::detail::TagToStrideA_t<{layout_a_str}>"
|
| 306 |
+
)
|
| 307 |
+
layout_a_str = f"{operation_name_str}_LayoutNarrowReordered"
|
| 308 |
+
else:
|
| 309 |
+
stride_narrow_str = (
|
| 310 |
+
f"cutlass::detail::TagToStrideB_t<{layout_b_str}>"
|
| 311 |
+
)
|
| 312 |
+
layout_b_str = f"{operation_name_str}_LayoutNarrowReordered"
|
| 313 |
+
# The {operation_name_str}_ prefixs in mixed_dtype_prepare_code and
|
| 314 |
+
# layout_{a, b}_str are to prevent errors in Windows platform unity build
|
| 315 |
+
mixed_dtype_prepare_code = f"""
|
| 316 |
+
using {operation_name_str}_StrideNarrow = {stride_narrow_str};
|
| 317 |
+
using {operation_name_str}_ValueShuffle = {value_shuffle_str};
|
| 318 |
+
static constexpr int {operation_name_str}_NumShuffleAtoms = 1;
|
| 319 |
+
using {operation_name_str}_MmaAtomShape = \
|
| 320 |
+
cute::Layout<cute::Shape<cute::_1, cute::Int<{operation_name_str}_NumShuffleAtoms>>>;
|
| 321 |
+
using {operation_name_str}_LayoutAtomQuant = \
|
| 322 |
+
decltype(cutlass::compute_memory_reordering_atom<{wide_tag}, {operation_name_str}_MmaAtomShape, \
|
| 323 |
+
{operation_name_str}_ValueShuffle>());
|
| 324 |
+
using {operation_name_str}_LayoutNarrowReordered = \
|
| 325 |
+
decltype(cute::tile_to_shape({operation_name_str}_LayoutAtomQuant{{}}, \
|
| 326 |
+
cute::Layout<cute::Shape<int,int,int>, {operation_name_str}_StrideNarrow>{{}}));
|
| 327 |
+
"""
|
| 328 |
+
|
| 329 |
+
mixed_input_modes_to_element = {
|
| 330 |
+
MixedInputMode.ConvertOnly: narrow_tag,
|
| 331 |
+
MixedInputMode.ScaleOnly: f"cute::tuple<{narrow_tag}, {scale_tag}>",
|
| 332 |
+
MixedInputMode.ScaleWithZeroPoint: f"cute::tuple<{narrow_tag}, {scale_tag}, {zero_tag}>",
|
| 333 |
+
}
|
| 334 |
+
narrow_element = mixed_input_modes_to_element.get(
|
| 335 |
+
operation.mixed_input_mode, narrow_tag
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
if narrow_dtype == DataType.s4 and (
|
| 339 |
+
wide_dtype == DataType.e4m3 or wide_dtype == DataType.e5m2
|
| 340 |
+
):
|
| 341 |
+
narrow_element = (
|
| 342 |
+
f"cute::tuple<{narrow_tag}, cutlass::Array<{scale_tag}, 8>>"
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
if is_A_dtype_narrow:
|
| 346 |
+
element_a = narrow_element
|
| 347 |
+
else:
|
| 348 |
+
element_b = narrow_element
|
| 349 |
+
|
| 350 |
+
if self.evt_name:
|
| 351 |
+
epilogue_functor = self.evt_name
|
| 352 |
+
|
| 353 |
+
values = {
|
| 354 |
+
"operation_name": operation_name_str,
|
| 355 |
+
"operation_suffix": self.operation_suffix,
|
| 356 |
+
"problem_shape": self.problem_shape(operation),
|
| 357 |
+
"element_a": element_a,
|
| 358 |
+
"layout_a": self.pointerize_if_grouped(operation, layout_a_str),
|
| 359 |
+
"element_b": element_b,
|
| 360 |
+
"layout_b": self.pointerize_if_grouped(operation, layout_b_str),
|
| 361 |
+
"element_c": DataTypeTag[operation.C.element],
|
| 362 |
+
"layout_c": self.pointerize_if_grouped(
|
| 363 |
+
operation, LayoutTag[instance_layout_C]
|
| 364 |
+
),
|
| 365 |
+
"element_d": DataTypeTag[operation.D.element],
|
| 366 |
+
"layout_d": self.pointerize_if_grouped(
|
| 367 |
+
operation, LayoutTag[instance_layout_D]
|
| 368 |
+
),
|
| 369 |
+
"element_accumulator": DataTypeTag[operation.accumulator_type()],
|
| 370 |
+
"opcode_class_main": OpcodeClassTag[opcode_class_main],
|
| 371 |
+
"opcode_class_epi": OpcodeClassTag[opcode_class_epi],
|
| 372 |
+
"arch": f"cutlass::arch::Sm{operation.arch}",
|
| 373 |
+
"tile_shape_m": str(tile_shape_m),
|
| 374 |
+
"tile_shape_n": str(tile_shape_n),
|
| 375 |
+
"tile_shape_k": str(tile_shape_k),
|
| 376 |
+
"cluster_shape_m": "cute::_"
|
| 377 |
+
+ str(operation.tile_description.cluster_shape[0])
|
| 378 |
+
if operation.tile_description.cluster_shape[0] > 0
|
| 379 |
+
else "int",
|
| 380 |
+
"cluster_shape_n": "cute::_"
|
| 381 |
+
+ str(operation.tile_description.cluster_shape[1])
|
| 382 |
+
if operation.tile_description.cluster_shape[1] > 0
|
| 383 |
+
else "int",
|
| 384 |
+
"cluster_shape_k": "cute::_"
|
| 385 |
+
+ str(operation.tile_description.cluster_shape[2])
|
| 386 |
+
if operation.tile_description.cluster_shape[2] > 0
|
| 387 |
+
else "int",
|
| 388 |
+
"instruction_shape_m": str(instruction_shape[0]),
|
| 389 |
+
"instruction_shape_n": str(instruction_shape[1]),
|
| 390 |
+
"instruction_shape_k": str(instruction_shape[2]),
|
| 391 |
+
"kernel_schedule": str(KernelScheduleTag[operation.kernel_schedule]),
|
| 392 |
+
"epilogue_schedule": str(epilogue_schedule_type),
|
| 393 |
+
"epi_tile_mn": epi_tile_mn,
|
| 394 |
+
"epilogue_functor": epilogue_functor,
|
| 395 |
+
"stages": stage_count_string,
|
| 396 |
+
"align_a": str(operation.A.alignment),
|
| 397 |
+
"align_b": str(operation.B.alignment),
|
| 398 |
+
"align_c": str(operation.C.alignment),
|
| 399 |
+
"align_d": str(operation.D.alignment),
|
| 400 |
+
"transform_a": ComplexTransformTag[operation.A.complex_transform],
|
| 401 |
+
"transform_b": ComplexTransformTag[operation.B.complex_transform],
|
| 402 |
+
"math_operation": MathOperationTag[
|
| 403 |
+
operation.tile_description.math_instruction.math_operation
|
| 404 |
+
],
|
| 405 |
+
"epilogue_vector_length": str(epilogue_vector_length),
|
| 406 |
+
"element_epilogue": str(DataTypeTag[operation.element_epilogue]),
|
| 407 |
+
"tile_scheduler": str(TileSchedulerTag[operation.tile_scheduler]),
|
| 408 |
+
"mixed_dtype_prepare_code": mixed_dtype_prepare_code,
|
| 409 |
+
}
|
| 410 |
+
|
| 411 |
+
return SubstituteTemplate(self.gemm_template, values)
|
miniconda3/envs/ladir/lib/python3.10/site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import Generator, Iterable, Iterator, Sequence
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from os import linesep
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
|
| 7 |
+
import sympy
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch._inductor.virtualized as virtualized
|
| 11 |
+
from torch._inductor.ir import ComputedBuffer, Pointwise
|
| 12 |
+
from torch._inductor.ops_handler import DefaultHandler, WrapperHandler
|
| 13 |
+
from torch._inductor.scheduler import BaseSchedulerNode
|
| 14 |
+
from torch._inductor.utils import DelayReplaceLine, IndentedBuffer, OrderedSet
|
| 15 |
+
from torch._inductor.virtualized import OpsValue
|
| 16 |
+
|
| 17 |
+
from ...virtualized import V
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_ACCUMULATOR_ARG_NAME = "accum"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def scaled_mm_evt(
|
| 24 |
+
scale_A_name: str, scale_B_name: str, bias_name: Optional[str], output_name: str
|
| 25 |
+
) -> tuple[list[str], dict[str, Any], str]:
|
| 26 |
+
evt_read_names = [scale_A_name, scale_B_name]
|
| 27 |
+
var_name_to_buffer_name = {n: n for n in [scale_A_name, scale_B_name]}
|
| 28 |
+
var_name_to_buffer_name["D"] = output_name
|
| 29 |
+
var_name_to_buffer_name[_ACCUMULATOR_ARG_NAME] = output_name
|
| 30 |
+
expr = f"accum * {scale_A_name} * {scale_B_name}{linesep}"
|
| 31 |
+
if bias_name:
|
| 32 |
+
expr = f"({expr}) + {bias_name}"
|
| 33 |
+
evt_read_names.append(bias_name)
|
| 34 |
+
var_name_to_buffer_name[bias_name] = bias_name
|
| 35 |
+
|
| 36 |
+
evt_py_code = f"def fn(accum, {','.join(evt_read_names)}):{linesep}\
|
| 37 |
+
D = {expr}{linesep}\
|
| 38 |
+
return D{linesep}"
|
| 39 |
+
|
| 40 |
+
return evt_read_names, var_name_to_buffer_name, evt_py_code
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class CutlassEVTOpsMixIn:
|
| 44 |
+
@staticmethod
|
| 45 |
+
def _infix_bin_op(op: str, a: str, b: str) -> str:
|
| 46 |
+
return f"{a} {op} {b}"
|
| 47 |
+
|
| 48 |
+
@staticmethod
|
| 49 |
+
def _prefix_bin_op(op: str, a: str, b: str) -> str:
|
| 50 |
+
return f"{op}({a}, {b})"
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def _prefix_un_op(op: str, a: str) -> str:
|
| 54 |
+
return f"{op}({a})"
|
| 55 |
+
|
| 56 |
+
@staticmethod
|
| 57 |
+
def to_dtype(
|
| 58 |
+
x: str,
|
| 59 |
+
dtype: Any,
|
| 60 |
+
src_dtype: Optional[torch.dtype] = None,
|
| 61 |
+
use_compute_types: bool = False,
|
| 62 |
+
) -> str:
|
| 63 |
+
return x
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def constant(value: Any, dtype: Any) -> str:
|
| 67 |
+
raise NotImplementedError
|
| 68 |
+
|
| 69 |
+
@staticmethod
|
| 70 |
+
def mul(x0: str, x1: str) -> str:
|
| 71 |
+
return CutlassEVTOpsMixIn._infix_bin_op("*", x0, x1)
|
| 72 |
+
|
| 73 |
+
@staticmethod
|
| 74 |
+
def truediv(x0: str, x1: str) -> str:
|
| 75 |
+
return CutlassEVTOpsMixIn._infix_bin_op("/", x0, x1)
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
def ge(x0: str, x1: str) -> str:
|
| 79 |
+
raise NotImplementedError
|
| 80 |
+
|
| 81 |
+
@staticmethod
|
| 82 |
+
def add(x0: str, x1: str) -> str:
|
| 83 |
+
return CutlassEVTOpsMixIn._infix_bin_op("+", x0, x1)
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def relu(x0: str) -> str:
|
| 87 |
+
return CutlassEVTOpsMixIn._prefix_un_op("relu", x0)
|
| 88 |
+
|
| 89 |
+
@staticmethod
|
| 90 |
+
def sigmoid(x0: str) -> str:
|
| 91 |
+
return CutlassEVTOpsMixIn._prefix_un_op("sigmoid", x0)
|
| 92 |
+
|
| 93 |
+
@staticmethod
|
| 94 |
+
def sub(x0: str, x1: str) -> str:
|
| 95 |
+
return CutlassEVTOpsMixIn._infix_bin_op("-", x0, x1)
|
| 96 |
+
|
| 97 |
+
@staticmethod
|
| 98 |
+
def tanh(x0: str) -> str:
|
| 99 |
+
return CutlassEVTOpsMixIn._prefix_un_op("tanh", x0)
|
| 100 |
+
|
| 101 |
+
@staticmethod
|
| 102 |
+
def exp(x0: str) -> str:
|
| 103 |
+
return CutlassEVTOpsMixIn._prefix_un_op("exp", x0)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class MockCutlassHandler(CutlassEVTOpsMixIn, WrapperHandler):
|
| 107 |
+
"""Passthrough handler for cutlass ops, used for running epilogue nodes for memory planning"""
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class _AssignmentFormatter(DefaultHandler):
|
| 111 |
+
def __init__(self, parent_handler: "CutlassEVTCodegen"):
|
| 112 |
+
self.parent_handler = parent_handler
|
| 113 |
+
|
| 114 |
+
def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
|
| 115 |
+
# Handle op dispatch here
|
| 116 |
+
if hasattr(self.parent_handler, name):
|
| 117 |
+
fn = getattr(self.parent_handler, name)
|
| 118 |
+
line = fn(*args, **kwargs)
|
| 119 |
+
if name in ("load", "store"):
|
| 120 |
+
return OpsValue(line)
|
| 121 |
+
else:
|
| 122 |
+
var = self.parent_handler._tmp_var()
|
| 123 |
+
line = DelayReplaceLine(
|
| 124 |
+
var,
|
| 125 |
+
lambda: "D"
|
| 126 |
+
if var == self.parent_handler.last_stored_var_name
|
| 127 |
+
else var,
|
| 128 |
+
f"{var} = {line}",
|
| 129 |
+
)
|
| 130 |
+
self.parent_handler.body.writeline(line)
|
| 131 |
+
return OpsValue(var)
|
| 132 |
+
else:
|
| 133 |
+
raise NotImplementedError(name)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class CutlassEVTCodegen(CutlassEVTOpsMixIn):
|
| 137 |
+
"""
|
| 138 |
+
Notes:
|
| 139 |
+
* Used by CUTLASSGemmTemplate.
|
| 140 |
+
* This class should not be instantiated by users, it is intended to be used
|
| 141 |
+
by calling CutlassEVTCodegen.ir_to_evt_python_code(...)
|
| 142 |
+
which instantiates this class as an ops handler for virtualized.V.ops.[op-name]
|
| 143 |
+
* Extend this with more _op_<whatever> nodes to add support for new pointwise operations.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def __init__(self, accumulator_node_name: str, removed_buffers: OrderedSet[str]):
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
Initializes a CutlassEVTEpilogueArgumentFormatter object. Do not instantiate directly.
|
| 150 |
+
Use the CutlassEVTCodegen.ir_to_evt_python_code static method.
|
| 151 |
+
|
| 152 |
+
Args:
|
| 153 |
+
accumulator_node_name: The name of the accumulator node which should contain
|
| 154 |
+
the Matmul result before fusion according to the IR graph.
|
| 155 |
+
epilogue_nodes: The list of scheduler nodes to be fused into the epilogue
|
| 156 |
+
"""
|
| 157 |
+
self.accumulator_node_name: str = accumulator_node_name #
|
| 158 |
+
self.body: IndentedBuffer = IndentedBuffer(1) # The body buffer for codegen
|
| 159 |
+
self.var_counter: Iterator[int] = itertools.count()
|
| 160 |
+
self.store_name_to_value: dict[str, OpsValue] = (
|
| 161 |
+
dict()
|
| 162 |
+
) # Aliases for subexpression functors
|
| 163 |
+
self.reads: OrderedSet[str] = OrderedSet([])
|
| 164 |
+
# Used for creating example tensors
|
| 165 |
+
self.var_name_to_buffer_name: dict[str, str] = {
|
| 166 |
+
_ACCUMULATOR_ARG_NAME: accumulator_node_name
|
| 167 |
+
}
|
| 168 |
+
self.removed_buffers: OrderedSet[str] = removed_buffers
|
| 169 |
+
self.cur_node: Optional[ComputedBuffer] = None
|
| 170 |
+
self.name_to_buffer = V.graph.name_to_buffer | V.graph.graph_inputs
|
| 171 |
+
for name in V.graph.constants:
|
| 172 |
+
self.name_to_buffer[name] = V.graph.add_tensor_constant(
|
| 173 |
+
V.graph.constants[name], name
|
| 174 |
+
)
|
| 175 |
+
self.is_D_assigned = False
|
| 176 |
+
self.D_var_name = None
|
| 177 |
+
|
| 178 |
+
if accumulator_node_name not in removed_buffers:
|
| 179 |
+
# cannot return accumulator directly, so alias it
|
| 180 |
+
var = self._tmp_var()
|
| 181 |
+
self.body.writeline(f"{var} = {_ACCUMULATOR_ARG_NAME}")
|
| 182 |
+
self.store(accumulator_node_name, value=OpsValue(var))
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
def ir_to_evt_python_code(
|
| 186 |
+
cuda_template_node_name: str,
|
| 187 |
+
epilogue_nodes: list[BaseSchedulerNode],
|
| 188 |
+
removed_buffers: OrderedSet[str],
|
| 189 |
+
) -> tuple[list[str], list[str], dict[str, Any], str]:
|
| 190 |
+
codegen = CutlassEVTCodegen(cuda_template_node_name, removed_buffers)
|
| 191 |
+
handler = _AssignmentFormatter(codegen)
|
| 192 |
+
|
| 193 |
+
with virtualized.V.set_ops_handler(handler):
|
| 194 |
+
for s_node in epilogue_nodes:
|
| 195 |
+
node = s_node.node
|
| 196 |
+
assert isinstance(node, ComputedBuffer)
|
| 197 |
+
with codegen.set_cur_node(node):
|
| 198 |
+
index_vars = CutlassEVTCodegen.get_index_vars(node)
|
| 199 |
+
node.get_store_function()(index_vars)
|
| 200 |
+
|
| 201 |
+
codegen.finalize()
|
| 202 |
+
|
| 203 |
+
return (
|
| 204 |
+
codegen.get_reads(),
|
| 205 |
+
codegen.get_writes(),
|
| 206 |
+
codegen.get_renames(),
|
| 207 |
+
codegen.get_value(),
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
def get_value(self) -> str:
|
| 211 |
+
return linesep.join(
|
| 212 |
+
[
|
| 213 |
+
self._render_input_signature(),
|
| 214 |
+
self.body.getvalue(),
|
| 215 |
+
self._render_return_statement(),
|
| 216 |
+
]
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
def finalize(self) -> None:
|
| 220 |
+
# Rename the last store to D
|
| 221 |
+
# no other code references this store
|
| 222 |
+
# to workaround https://github.com/NVIDIA/cutlass/issues/2288
|
| 223 |
+
# Note: the delayed line will automatically rewrite the last assignment to
|
| 224 |
+
# be to D
|
| 225 |
+
buffer_name = self.var_name_to_buffer_name[self.last_stored_var_name]
|
| 226 |
+
self.var_name_to_buffer_name.pop(self.last_stored_var_name)
|
| 227 |
+
self.var_name_to_buffer_name["D"] = buffer_name
|
| 228 |
+
self.store_name_to_value[buffer_name] = OpsValue("D")
|
| 229 |
+
|
| 230 |
+
@contextmanager
|
| 231 |
+
def set_cur_node(self, node: ComputedBuffer) -> Generator[None, Any, Any]:
|
| 232 |
+
prev_node = self.cur_node
|
| 233 |
+
try:
|
| 234 |
+
self.cur_node = node
|
| 235 |
+
yield
|
| 236 |
+
finally:
|
| 237 |
+
self.cur_node = prev_node
|
| 238 |
+
|
| 239 |
+
def get_renames(self) -> dict[str, str]:
|
| 240 |
+
return dict(self.var_name_to_buffer_name)
|
| 241 |
+
|
| 242 |
+
def get_reads(self) -> list[str]:
|
| 243 |
+
return list(self.reads.difference(self.store_name_to_value.keys()))
|
| 244 |
+
|
| 245 |
+
def get_writes(self) -> list[str]:
|
| 246 |
+
return list(self.store_name_to_value.keys())
|
| 247 |
+
|
| 248 |
+
def load(self, name: str, index: Any) -> str:
|
| 249 |
+
self._check_indexing(name, index)
|
| 250 |
+
if name in self.store_name_to_value:
|
| 251 |
+
return self.store_name_to_value[name].value
|
| 252 |
+
elif name == self.accumulator_node_name:
|
| 253 |
+
return _ACCUMULATOR_ARG_NAME
|
| 254 |
+
else:
|
| 255 |
+
self.reads.add(name)
|
| 256 |
+
self.var_name_to_buffer_name[name] = name
|
| 257 |
+
return name
|
| 258 |
+
|
| 259 |
+
def store(
|
| 260 |
+
self, name: Any, index: Any = None, value: Any = None, mode: Any = None
|
| 261 |
+
) -> None:
|
| 262 |
+
if name not in self.removed_buffers:
|
| 263 |
+
if index:
|
| 264 |
+
self._check_indexing(name, index)
|
| 265 |
+
assert value.value != _ACCUMULATOR_ARG_NAME, (
|
| 266 |
+
"Cannot store accumulator arg name"
|
| 267 |
+
)
|
| 268 |
+
self.var_name_to_buffer_name[value.value] = name
|
| 269 |
+
self.store_name_to_value[name] = value
|
| 270 |
+
self.last_stored_var_name = value.value
|
| 271 |
+
return None
|
| 272 |
+
|
| 273 |
+
def _get_cur_node(self) -> ComputedBuffer:
|
| 274 |
+
assert self.cur_node
|
| 275 |
+
return self.cur_node
|
| 276 |
+
|
| 277 |
+
@staticmethod
|
| 278 |
+
def get_index_vars(node: ComputedBuffer) -> Sequence[sympy.Expr]:
|
| 279 |
+
data = node.data
|
| 280 |
+
# TODO mlazos: relax this, cutlass supports reductions and other ops
|
| 281 |
+
assert isinstance(data, Pointwise)
|
| 282 |
+
return data._index(data.ranges)
|
| 283 |
+
|
| 284 |
+
def _get_current_index_vars(self) -> Sequence[sympy.Expr]:
|
| 285 |
+
return self.get_index_vars(self._get_cur_node())
|
| 286 |
+
|
| 287 |
+
def _check_indexing(self, name: str, index: sympy.Expr) -> None:
|
| 288 |
+
# We only support indexing that matches the layout today because
|
| 289 |
+
# CUTLASS doesn't support arbitrary indexing
|
| 290 |
+
buffer_name = (
|
| 291 |
+
self.accumulator_node_name if name == _ACCUMULATOR_ARG_NAME else name
|
| 292 |
+
)
|
| 293 |
+
buffer = self.name_to_buffer[buffer_name]
|
| 294 |
+
index_strides = V.graph.sizevars.stride_vars(
|
| 295 |
+
index, self._get_current_index_vars()
|
| 296 |
+
)
|
| 297 |
+
stride = buffer.get_layout().stride
|
| 298 |
+
if not self._stride_compatible(stride, index_strides):
|
| 299 |
+
raise NotImplementedError(
|
| 300 |
+
f"Unsupported indexing for {name} with index {index}, index strides {index_strides}, and layout stride {stride}"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
def _stride_compatible(
|
| 304 |
+
self, left: Iterable[sympy.Expr], right: Iterable[sympy.Expr]
|
| 305 |
+
) -> bool:
|
| 306 |
+
return all(
|
| 307 |
+
sympy.Eq(l, r) or sympy.Eq(l, 0) or sympy.Eq(r, 0)
|
| 308 |
+
for l, r in (zip(left, right))
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
def _render_input_signature(self) -> str:
|
| 312 |
+
arguments = ", ".join(
|
| 313 |
+
[_ACCUMULATOR_ARG_NAME]
|
| 314 |
+
+ [name for name in self.reads if name != self.accumulator_node_name]
|
| 315 |
+
)
|
| 316 |
+
return f"def fn({arguments}):"
|
| 317 |
+
|
| 318 |
+
def _render_return_statement(self) -> str:
|
| 319 |
+
return_vars = OrderedSet(
|
| 320 |
+
op_v.value for op_v in self.store_name_to_value.values()
|
| 321 |
+
)
|
| 322 |
+
assert "D" in return_vars
|
| 323 |
+
return f"return {', '.join(return_vars)}"
|
| 324 |
+
|
| 325 |
+
def _tmp_var(self) -> str:
|
| 326 |
+
return f"tmp_{next(self.var_counter)}"
|