Sumitwarrior7 commited on
Commit
b9789b4
·
verified ·
1 Parent(s): 48090b8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/__init__.py +0 -0
  2. .venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py +296 -0
  3. .venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_PadMMA100.py +109 -0
  4. .venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic.py +318 -0
  5. .venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py +340 -0
  6. .venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/learned_heuristic_controller.py +119 -0
  7. .venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/learnedheuristic_interface.py +89 -0
  8. .venv/lib/python3.10/site-packages/torch/_inductor/autotune_process.py +1391 -0
  9. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp +488 -0
  10. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/__init__.py +0 -0
  11. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/compile_utils.py +268 -0
  12. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/cuda_env.py +55 -0
  13. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py +364 -0
  14. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/__init__.py +8 -0
  15. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py +29 -0
  16. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py +607 -0
  17. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py +397 -0
  18. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py +141 -0
  19. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py +200 -0
  20. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/__init__.py +0 -0
  21. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/cache.py +121 -0
  22. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py +2005 -0
  23. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/kernel.py +688 -0
  24. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__init__.py +0 -0
  25. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__init__.py +0 -0
  26. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/__init__.py +6 -0
  27. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cuda.py +24 -0
  28. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/cuda/cudart.py +17 -0
  29. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py +2 -0
  30. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py +3 -0
  31. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py +2 -0
  32. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py +276 -0
  33. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py +411 -0
  34. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/python_evt.py +326 -0
  35. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/scheduling.py +296 -0
  36. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/serialization.py +507 -0
  37. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/template.py +379 -0
  38. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/utils.py +480 -0
  39. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/mtia/__init__.py +0 -0
  40. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py +20 -0
  41. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py +17 -0
  42. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py +88 -0
  43. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py +555 -0
  44. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py +293 -0
  45. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py +153 -0
  46. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py +42 -0
  47. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py +979 -0
  48. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py +100 -0
  49. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/xpu/__init__.py +0 -0
  50. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py +67 -0
.venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/artifacts/_MMRankingA100.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)]
.venv/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
.venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ profiled_time: Callable[[], dict[ChoiceCaller, float]],
290
+ precompile_times: dict[ChoiceCaller, float],
291
+ ) -> None:
292
+ current_inputs_key = create_inputs_key(input_nodes)
293
+ if current_inputs_key != ah_inputs_key:
294
+ return
295
+ current_precompile_key = create_precompile_key(
296
+ name, current_inputs_key, choices
297
+ )
298
+ if current_precompile_key != ah_precompile_key:
299
+ return
300
+ for choice, time in timings.items():
301
+ self.save_data(choice.autoheuristic_id(), time)
302
+
303
+ inputs_key = create_inputs_key(input_nodes)
304
+ precompile_key = create_precompile_key(self.name, inputs_key, choices)
305
+ feedback_saver = partial(store_global_feedback, inputs_key, precompile_key)
306
+ add_feedback_saver(feedback_saver)
307
+
308
+ def get_choice_caller(self) -> Optional[ChoiceCaller]:
309
+ choice = self.get_choice()
310
+ return self.choicestr2choice.get(choice, None)
311
+
312
+ def get_top_k_choices_caller(
313
+ self, top_k: int, always_included: Optional[list[str]] = None
314
+ ) -> Optional[list[ChoiceCaller]]:
315
+ choices = self.get_top_k_choices(top_k, always_included)
316
+ if choices is None:
317
+ return None
318
+ return [self.choicestr2choice[choice] for choice in choices]
.venv/lib/python3.10/site-packages/torch/_inductor/autoheuristic/autoheuristic_utils.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.fp32_precision == "tf32"
340
+ context.add_feature("using_tf32", using_tf32, is_categorical=True)
.venv/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
.venv/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 []
.venv/lib/python3.10/site-packages/torch/_inductor/autotune_process.py ADDED
@@ -0,0 +1,1391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import atexit
5
+ import ctypes
6
+ import dataclasses
7
+ import functools
8
+ import logging
9
+ import multiprocessing as mp
10
+ import os
11
+ import pickle
12
+ import queue
13
+ import selectors
14
+ import subprocess
15
+ import sys
16
+ import threading
17
+ import time
18
+ import warnings
19
+ from collections.abc import Callable, Iterable, Sequence
20
+ from concurrent.futures import Future, ProcessPoolExecutor, ThreadPoolExecutor
21
+ from ctypes import byref, c_size_t, c_void_p, CDLL
22
+ from typing import Any, IO, Optional, TYPE_CHECKING, Union
23
+
24
+ import torch
25
+ import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
26
+ from torch._dynamo.device_interface import get_interface_for_device
27
+ from torch._dynamo.testing import rand_strided
28
+ from torch._inductor import ir
29
+ from torch._inductor.codecache import (
30
+ CppCodeCache,
31
+ CUDACodeCache,
32
+ DLLWrapper,
33
+ get_hash,
34
+ PyCodeCache,
35
+ )
36
+ from torch._inductor.compile_worker.timer import Timer
37
+ from torch._inductor.utils import (
38
+ do_bench_using_profiling,
39
+ get_gpu_type,
40
+ get_ld_library_path,
41
+ is_gpu,
42
+ python_subprocess_env,
43
+ )
44
+ from torch._logging import getArtifactLogger
45
+ from torch.utils._ordered_set import OrderedSet
46
+
47
+
48
+ # Inactivity timeout for AutotuneProcessPool in seconds.
49
+ # Default: 600 seconds (10 minutes). Set to 0 to disable.
50
+ AUTOTUNE_POOL_INACTIVITY_TIMEOUT = int(
51
+ os.environ.get("TORCHINDUCTOR_AUTOTUNE_POOL_INACTIVITY_TIMEOUT", "600")
52
+ )
53
+
54
+ if TYPE_CHECKING:
55
+ from types import ModuleType
56
+
57
+ from torch._inductor.select_algorithm import (
58
+ ChoiceCaller,
59
+ PartialRender,
60
+ TritonTemplateCaller,
61
+ )
62
+
63
+ from . import config
64
+ from .runtime.benchmarking import benchmarker
65
+ from .virtualized import V
66
+
67
+
68
+ CUDA_VISIBLE_DEVICES = "CUDA_VISIBLE_DEVICES"
69
+
70
+ autotuning_log = getArtifactLogger(__name__, "autotuning")
71
+
72
+
73
+ class NonzeroWorkspaceNotSupportedError(Exception):
74
+ pass
75
+
76
+
77
+ class TuningProcess:
78
+ """
79
+ Class to launch and interact with a benchmarking subprocess.
80
+ """
81
+
82
+ @staticmethod
83
+ def process_main(read_pipe: IO[bytes], write_pipe: IO[bytes]) -> None:
84
+ """
85
+ Entry point for the child process.
86
+ """
87
+ autotuning_log.debug(
88
+ "Started autotune subprocess %s. Visible devices: %s",
89
+ os.getpid(),
90
+ os.environ.get(CUDA_VISIBLE_DEVICES),
91
+ )
92
+
93
+ def workloop():
94
+ while True:
95
+ job, extra_env = TuningProcess.recv(read_pipe)
96
+ if job is None:
97
+ # None is a sentinel for the child to shut down
98
+ break
99
+ try:
100
+ if extra_env:
101
+ os.environ.update(extra_env)
102
+ result = job()
103
+ except Exception as e:
104
+ result = e
105
+ TuningProcess.send(result, write_pipe)
106
+
107
+ try:
108
+ workloop()
109
+ except EOFError:
110
+ # The parent closed the pipe
111
+ pass
112
+
113
+ @staticmethod
114
+ def send(
115
+ obj: Any, write_pipe: IO[bytes], extra_env: dict[str, str] | None = None
116
+ ) -> None:
117
+ pickle.dump((obj, extra_env), write_pipe)
118
+ write_pipe.flush()
119
+
120
+ @staticmethod
121
+ def recv(read_pipe: IO[bytes]) -> Any:
122
+ return pickle.load(read_pipe)
123
+
124
+ def __init__(self, device: Optional[int]):
125
+ self.device = device
126
+ self.start()
127
+
128
+ def start(self):
129
+ """
130
+ Start the benchmarking subprocess.
131
+ """
132
+ entry = os.path.join(os.path.dirname(__file__), "__autotune_main__.py")
133
+
134
+ subproc_read_fd, write_fd = os.pipe()
135
+ read_fd, subproc_write_fd = os.pipe()
136
+ self.write_pipe = os.fdopen(write_fd, "wb")
137
+ self.read_pipe = os.fdopen(read_fd, "rb")
138
+
139
+ self.selector = selectors.DefaultSelector()
140
+ self.selector.register(self.read_pipe, selectors.EVENT_READ)
141
+
142
+ cmd = [
143
+ sys.executable,
144
+ entry,
145
+ f"--parent={os.getpid()}",
146
+ f"--read-fd={str(subproc_read_fd)}",
147
+ f"--write-fd={str(subproc_write_fd)}",
148
+ ]
149
+ env = {
150
+ **python_subprocess_env(),
151
+ # We shouldn't be using the Triton async compile subprocess pool,
152
+ # but as a precaution set the env var that disables its creation.
153
+ "TORCH_WARM_POOL": "0",
154
+ # Some internal usages need a modified LD_LIBRARY_PATH.
155
+ "LD_LIBRARY_PATH": get_ld_library_path(),
156
+ # This will cause the subprocs to profile using the profiler.
157
+ "TORCHINDUCTOR_PROFILE_WITH_DO_BENCH_USING_PROFILING": "1"
158
+ if config.profile_bandwidth_with_do_bench_using_profiling
159
+ else "0",
160
+ }
161
+ if self.device is not None:
162
+ env[CUDA_VISIBLE_DEVICES] = str(self.device)
163
+ self.process = subprocess.Popen(
164
+ cmd,
165
+ env=env,
166
+ pass_fds=(subproc_read_fd, subproc_write_fd),
167
+ )
168
+ os.close(subproc_read_fd)
169
+ os.close(subproc_write_fd)
170
+
171
+ self.running = True
172
+
173
+ def alive(self) -> bool:
174
+ """
175
+ True if the subprocess is still running.
176
+ """
177
+ return self.running and self.process.poll() is None
178
+
179
+ def put(self, req: Any, extra_env: dict[str, str] | None = None) -> None:
180
+ """
181
+ Push a work item to the child process.
182
+ """
183
+ if not self.alive():
184
+ self.start()
185
+ TuningProcess.send(req, self.write_pipe, extra_env=extra_env)
186
+
187
+ def get(self, timeout: float = 120.0) -> Any:
188
+ """
189
+ Get a response from the child process. Raises TimeoutError on timeout;
190
+ raises EOFError if the subprocess crashes.
191
+ """
192
+ try:
193
+ if not self.selector.select(timeout):
194
+ raise TimeoutError(f"Timeout in autotune subprocess {self.process.pid}")
195
+ result, _ = TuningProcess.recv(self.read_pipe)
196
+ except TimeoutError:
197
+ self.kill()
198
+ raise
199
+ except EOFError:
200
+ # The subprocess crashed
201
+ self.close()
202
+ raise
203
+ except Exception:
204
+ autotuning_log.exception(
205
+ "Unexpected exception in autotune subprocess %s", self.process.pid
206
+ )
207
+ self.kill()
208
+ raise
209
+
210
+ if isinstance(result, Exception):
211
+ raise result
212
+ return result
213
+
214
+ def shutdown(self, wait: bool = True) -> None:
215
+ """
216
+ Signal the child process to shut down gracefully.
217
+ """
218
+ if self.alive():
219
+ TuningProcess.send(None, self.write_pipe)
220
+ if wait:
221
+ self.wait()
222
+
223
+ def wait(self) -> None:
224
+ """
225
+ Wait for the child process to exit.
226
+ """
227
+ if self.alive():
228
+ self.process.wait()
229
+ self.close()
230
+
231
+ def close(self) -> None:
232
+ """
233
+ Close resources.
234
+ """
235
+ self.selector.close()
236
+ self.read_pipe.close()
237
+ self.write_pipe.close()
238
+ self.running = False
239
+
240
+ def kill(self) -> None:
241
+ """
242
+ Send a SIGKILL to the child process.
243
+ """
244
+ if self.alive():
245
+ autotuning_log.error(
246
+ "Sending SIGKILL to autotune subprocess %d",
247
+ self.process.pid,
248
+ )
249
+ self.process.kill()
250
+ self.close()
251
+
252
+ def restart(self) -> None:
253
+ """
254
+ Gracefully restarts the child process.
255
+ """
256
+ self.shutdown(wait=True)
257
+ self.start()
258
+
259
+
260
+ class TuningProcessPool:
261
+ """
262
+ Maintains a pool of TuningProcesses to benchmark kernels in parallel
263
+ across devices. By default, we create one TuningProcess per device and
264
+ set the sub-process environment to make only that device visible.
265
+ """
266
+
267
+ def __init__(self) -> None:
268
+ """
269
+ Start the child processes.
270
+ """
271
+ devices = self.get_device_list()
272
+ autotuning_log.debug("Sub-process autotune device list: %s", devices)
273
+
274
+ # Launch the child processes.
275
+ self.processes = [TuningProcess(device=device) for device in devices]
276
+
277
+ self.process_queue: queue.Queue[TuningProcess] = queue.Queue()
278
+ for p in self.processes:
279
+ self.process_queue.put(p)
280
+
281
+ # Use a thread pool to manage distributing work to the subprocesses.
282
+ # Threads block on an available process, so it makes sense to match
283
+ # the number of threads with the number of devices.
284
+ self.executor = ThreadPoolExecutor(max_workers=len(devices))
285
+
286
+ @staticmethod
287
+ def get_device_list() -> Sequence[Optional[int]]:
288
+ """
289
+ Gather the list of devices to be used in the pool.
290
+ """
291
+ if not config.autotune_multi_device:
292
+ # Don't use multiple devices
293
+ return [None]
294
+
295
+ gpu_type = get_gpu_type()
296
+ device_interface = get_interface_for_device(gpu_type)
297
+ count = device_interface.device_count()
298
+
299
+ # If the user specified the visible devices in the env, use those.
300
+ if CUDA_VISIBLE_DEVICES in os.environ:
301
+ devices = [int(d) for d in os.environ[CUDA_VISIBLE_DEVICES].split(",")]
302
+ assert len(devices) <= count
303
+ return devices
304
+
305
+ return list(range(count))
306
+
307
+ def shutdown(self) -> None:
308
+ """
309
+ Signal all child processes to exit.
310
+ """
311
+ self.executor.shutdown()
312
+
313
+ for p in self.processes:
314
+ p.shutdown(wait=False)
315
+ for p in self.processes:
316
+ p.wait()
317
+
318
+ def target(self, choice: TritonTemplateCaller) -> float:
319
+ """
320
+ Entry point for the thread-pool helper threads: Wait for an open TuningProcess,
321
+ remove it from the queue, execute the benchmark in that subprocess, and return
322
+ the TuningProcess to the queue.
323
+ """
324
+ assert choice.bmreq is not None
325
+
326
+ env_vars = ["TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"]
327
+ extra_env = {v: os.environ[v] for v in env_vars if v in os.environ}
328
+ process = self.process_queue.get()
329
+ process.put(choice.bmreq.benchmark, extra_env=extra_env)
330
+ try:
331
+ return process.get(
332
+ config.max_autotune_subproc_result_timeout_seconds,
333
+ )
334
+ except TimeoutError:
335
+ warnings.warn(
336
+ f"Timed out benchmarking choice '{choice}'. It will be ignored. "
337
+ "Please debug the root cause in case the choice can bring perf gains."
338
+ )
339
+ # Set to INF so this choice will be ignored
340
+ return float("inf")
341
+ except Exception as process_exception:
342
+ warnings.warn(
343
+ f"Failed to benchmark choice '{choice}'. It will be ignored. "
344
+ "Please debug the root cause in case the choice can bring perf gains."
345
+ )
346
+ # An unspecified launch failure (cudaErrorLaunchFailure) corrupts the
347
+ # CUDA context, making it unrecoverable. All subsequent CUDA calls will
348
+ # fail as well. The process must be restarted to restore CUDA functionality.
349
+ if "cudaErrorLaunchFailure" in str(process_exception):
350
+ process.restart()
351
+ # Set to INF so this choice will be ignored
352
+ return float("inf")
353
+ finally:
354
+ self.process_queue.put(process)
355
+
356
+ def benchmark(
357
+ self,
358
+ choices: list[TritonTemplateCaller],
359
+ ) -> dict[TritonTemplateCaller, float]:
360
+ """
361
+ Benchmark each choice in a separate process.
362
+ """
363
+
364
+ # Use a ThreadExecutorPool to spread the work across the subprocesses and
365
+ # to grab subprocesses as soon as they're free.
366
+ results = dict(zip(choices, self.executor.map(self.target, choices)))
367
+
368
+ return results
369
+
370
+
371
+ LayoutOrBuffer = Union[ir.Layout, ir.Buffer]
372
+
373
+
374
+ @dataclasses.dataclass
375
+ class TensorMeta:
376
+ device: torch.device
377
+ dtype: torch.dtype
378
+ sizes: torch._prims_common.ShapeType
379
+ strides: torch._prims_common.StrideType
380
+ offset: int
381
+ name: Optional[str] = None
382
+
383
+ @classmethod
384
+ def from_irnodes(
385
+ cls, irnodes: Union[LayoutOrBuffer, Sequence[LayoutOrBuffer]]
386
+ ) -> Union[TensorMeta, list[TensorMeta]]:
387
+ if isinstance(irnodes, Sequence):
388
+ result: list[Any] = [cls.from_irnodes(x) for x in irnodes]
389
+ assert all(isinstance(x, TensorMeta) for x in result)
390
+ return result
391
+
392
+ node = irnodes
393
+ if isinstance(node, ir.Layout):
394
+ node = ir.Buffer(name="fake", layout=node)
395
+
396
+ dtype = node.get_dtype()
397
+ assert dtype is not None
398
+ device = node.get_device()
399
+ assert device is not None
400
+
401
+ return TensorMeta(
402
+ device=device,
403
+ dtype=dtype,
404
+ sizes=V.graph.sizevars.optimization_hints(node.get_size()),
405
+ strides=V.graph.sizevars.optimization_hints(node.get_stride()),
406
+ offset=V.graph.sizevars.optimization_hint(node.get_layout().offset),
407
+ name=node.get_name(),
408
+ )
409
+
410
+ def to_tensor(self) -> torch.Tensor:
411
+ return rand_strided(
412
+ self.sizes,
413
+ self.strides,
414
+ device=self.device,
415
+ dtype=self.dtype,
416
+ extra_size=self.offset,
417
+ )
418
+
419
+
420
+ @dataclasses.dataclass
421
+ class BenchmarkRequest:
422
+ """
423
+ Only handle triton template benchmark for now. The extern kernel benchmark
424
+ can be done inside the same process since they usually don't cause crash.
425
+
426
+ Important: Instances of this class and subclasses have to be serializable
427
+ across process boundaries. Do not put CUDA Tensors in here!
428
+ """
429
+
430
+ def __init__(
431
+ self,
432
+ kernel_name: str,
433
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
434
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
435
+ extra_args: Iterable[Any],
436
+ ) -> None:
437
+ # the kernel name defined in the module
438
+ self.kernel_name = kernel_name
439
+
440
+ if isinstance(input_tensor_meta, TensorMeta):
441
+ self.input_tensor_meta: list[TensorMeta] = [input_tensor_meta]
442
+ else:
443
+ self.input_tensor_meta: list[TensorMeta] = input_tensor_meta
444
+
445
+ if output_tensor_meta and isinstance(output_tensor_meta, (tuple, list)):
446
+ if len(output_tensor_meta) > 1:
447
+ # Each output with same meta for Grouped GEMM
448
+ assert all(
449
+ getattr(output_tensor_meta[0], attr) == getattr(x, attr)
450
+ for x in output_tensor_meta
451
+ for attr in ["device", "dtype", "sizes", "strides", "offset"]
452
+ )
453
+ self.output_tensor_meta = output_tensor_meta[0]
454
+ else:
455
+ # pyrefly: ignore [bad-assignment]
456
+ self.output_tensor_meta: TensorMeta = output_tensor_meta
457
+
458
+ self.extra_args = extra_args
459
+
460
+ def make_run_fn(
461
+ self, *input_tensors: torch.Tensor, out: torch.Tensor
462
+ ) -> Callable[[], None]:
463
+ raise NotImplementedError
464
+
465
+ def cleanup_run_fn(self) -> None:
466
+ pass
467
+
468
+ def do_bench(
469
+ self,
470
+ fn,
471
+ *input_tensors: torch.Tensor,
472
+ out: Optional[torch.Tensor] = None,
473
+ ) -> float:
474
+ raise NotImplementedError
475
+
476
+ def benchmark(
477
+ self,
478
+ *input_tensors: torch.Tensor,
479
+ out: Optional[torch.Tensor] = None,
480
+ ) -> float:
481
+ debug = autotuning_log.isEnabledFor(logging.DEBUG)
482
+ if debug:
483
+ start_ts = time.time()
484
+
485
+ # create args and out tensor
486
+ if out is None:
487
+ assert self.input_tensor_meta and self.output_tensor_meta, (
488
+ "Input and output tensor meta must be populated when input_tensors is empty"
489
+ )
490
+ assert len(input_tensors) == 0
491
+ input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta)
492
+ out = self.output_tensor_meta.to_tensor()
493
+
494
+ if debug:
495
+ create_tensor_elapse = time.time() - start_ts # type: ignore[possibly-undefined]
496
+ start_ts = time.time()
497
+ try:
498
+ fn = self.make_run_fn(*input_tensors, out=out)
499
+ except NonzeroWorkspaceNotSupportedError:
500
+ # Skipping all ops with nonzero workspace requirements
501
+ autotuning_log.info("Skipping op due to nonzero workspace requirement")
502
+ return float("inf")
503
+
504
+ if debug:
505
+ load_elapse = time.time() - start_ts # type: ignore[possibly-undefined]
506
+ start_ts = time.time()
507
+
508
+ res = self.do_bench(fn, *input_tensors, out)
509
+
510
+ if debug:
511
+ bench_elapse = time.time() - start_ts # type: ignore[possibly-undefined]
512
+ autotuning_log.debug(
513
+ "InChildProcess %s: load %f, create tensor %f, bench %f",
514
+ str(self),
515
+ load_elapse, # type: ignore[possibly-undefined]
516
+ create_tensor_elapse, # type: ignore[possibly-undefined]
517
+ bench_elapse,
518
+ )
519
+ self.cleanup_run_fn()
520
+ return res
521
+
522
+
523
+ class _TestBenchmarkRequest(BenchmarkRequest):
524
+ """
525
+ Supports unit testing. Defined in this file instead of the test file so the
526
+ TuningProcess sub-process can unpickle these objects.
527
+ """
528
+
529
+ def __init__(
530
+ self,
531
+ result: float = 0.0,
532
+ device: Optional[int] = None,
533
+ sleep: Optional[float] = None,
534
+ exc: Optional[Exception] = None,
535
+ crash: bool = False,
536
+ ):
537
+ self.result = result
538
+ self.device = device
539
+ self.sleep = sleep
540
+ self.exc = exc
541
+ self.crash = crash
542
+
543
+ def benchmark(
544
+ self, *input_tensors: torch.Tensor, out: Optional[torch.Tensor] = None
545
+ ) -> float:
546
+ if self.device is not None:
547
+ assert os.environ.get(CUDA_VISIBLE_DEVICES, None) == str(self.device)
548
+ if self.sleep:
549
+ time.sleep(self.sleep)
550
+ if self.exc:
551
+ raise self.exc
552
+ if self.crash:
553
+ sys.exit(1)
554
+ return self.result
555
+
556
+
557
+ class GPUDeviceBenchmarkMixin:
558
+ def do_bench(
559
+ self,
560
+ fn,
561
+ *input_tensors: torch.Tensor,
562
+ out: Optional[torch.Tensor] = None,
563
+ ) -> float:
564
+ device_idx_set = OrderedSet(
565
+ tensor.device.index
566
+ for tensor in [*input_tensors, out]
567
+ if isinstance(tensor, torch.Tensor)
568
+ and is_gpu(tensor.device.type)
569
+ and tensor.device.index is not None
570
+ )
571
+ assert len(device_idx_set) <= 1, f"Can not mix devices {device_idx_set}"
572
+ device_type = next(
573
+ (
574
+ tensor.device.type
575
+ for tensor in input_tensors
576
+ if is_gpu(tensor.device.type)
577
+ ),
578
+ "cuda",
579
+ )
580
+ device_interface = get_interface_for_device(device_type)
581
+ if len(device_idx_set) == 1:
582
+ device_idx = next(iter(device_idx_set))
583
+ else:
584
+ device_idx = device_interface.current_device()
585
+ with device_interface.device(device_idx): # type: ignore[attr-defined]
586
+ res = benchmarker.benchmark(fn, device=device_type)
587
+ device_interface.synchronize() # shake out any CUDA errors
588
+
589
+ return res
590
+
591
+
592
+ class CPUDeviceBenchmarkMixin:
593
+ def do_bench(
594
+ self,
595
+ fn,
596
+ *input_tensors: torch.Tensor,
597
+ out: Optional[torch.Tensor] = None,
598
+ ) -> float:
599
+ return benchmarker.benchmark_cpu(fn)
600
+
601
+
602
+ class TritonBenchmarkRequest(BenchmarkRequest):
603
+ """
604
+ Represents a standalone benchmark request for a Triton Template.
605
+
606
+ Important: Instances of this class have to be serializable
607
+ across process boundaries. Do not put CUDA Tensors in here!
608
+ """
609
+
610
+ def __init__(
611
+ self,
612
+ kernel_name: str,
613
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
614
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
615
+ extra_args: Iterable[Any],
616
+ module_path: str, # the path of the module defining the triton kernel
617
+ module_cache_key: str,
618
+ num_stages: int,
619
+ num_warps: int,
620
+ num_consumer_groups: int = 0,
621
+ num_buffers_warp_spec: int = 0,
622
+ matrix_instr_nonkdim: int = 0, # only used for hip to choose the shape of mfma instruction.
623
+ waves_per_eu: int = 0, # only used for hip to schedule waves per execution unit
624
+ kpack: int = 0, # ROCm specific gemm parameter
625
+ workspace_size: Optional[int] = None, # size of workspace buffer in bytes
626
+ workspace_zero_fill: bool = False, # whether to zero-fill workspace
627
+ ) -> None:
628
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
629
+ self.module_path = module_path
630
+ self.module_cache_key = module_cache_key
631
+ self.num_stages = num_stages
632
+ self.num_warps = num_warps
633
+ self.num_consumer_groups = num_consumer_groups
634
+ self.num_buffers_warp_spec = num_buffers_warp_spec
635
+ self.matrix_instr_nonkdim = matrix_instr_nonkdim
636
+ self.waves_per_eu = waves_per_eu
637
+ self.kpack = kpack
638
+ self.workspace_size = workspace_size
639
+ self.workspace_zero_fill = workspace_zero_fill
640
+
641
+ def make_run_fn(
642
+ self, *input_tensors: torch.Tensor, out: torch.Tensor
643
+ ) -> Callable[[], None]:
644
+ mod = PyCodeCache.load_by_key_path(self.module_cache_key, self.module_path)
645
+ autotuning_log.debug(
646
+ "benchmark module key: %s, path: %s",
647
+ self.module_cache_key,
648
+ self.module_path,
649
+ )
650
+
651
+ run_method = getattr(mod, self.kernel_name).run
652
+ extra_args = list(self.extra_args)
653
+
654
+ # Recreate workspace tensor if needed (for TMA templates)
655
+ # The workspace tensor couldn't be pickled, so we recreate it here
656
+ # It should be inserted before the grid values (last 3 elements)
657
+ if self.workspace_size is not None:
658
+ from torch._inductor.select_algorithm import WORKSPACE_ARG_PLACEHOLDER
659
+
660
+ workspace_tensor = torch.empty(
661
+ (self.workspace_size,),
662
+ dtype=torch.uint8,
663
+ device=out.device,
664
+ )
665
+ if self.workspace_zero_fill:
666
+ workspace_tensor.zero_()
667
+ workspace_index = extra_args.index(WORKSPACE_ARG_PLACEHOLDER)
668
+ extra_args[workspace_index] = workspace_tensor
669
+
670
+ run_method.__self__.with_bandwidth_info = False
671
+
672
+ # Newer version of triton add warmup argument to JITFunction.run.
673
+ # This code handles backward-compatibility.
674
+ warmup_arg = {}
675
+ import inspect
676
+
677
+ if "warmup" in inspect.signature(run_method).parameters:
678
+ warmup_arg["warmup"] = False
679
+
680
+ if out.device.type == "cpu":
681
+ stream = 0
682
+ else:
683
+ device_type = out.device.type
684
+ device_interface = get_interface_for_device(device_type)
685
+ stream = device_interface.get_raw_stream(
686
+ self.output_tensor_meta.device.index
687
+ )
688
+
689
+ if isinstance(
690
+ getattr(mod, self.kernel_name),
691
+ torch._inductor.runtime.triton_heuristics.DebugAutotuner,
692
+ ):
693
+ return functools.partial(
694
+ run_method,
695
+ *input_tensors,
696
+ out,
697
+ *extra_args,
698
+ **warmup_arg,
699
+ stream=stream,
700
+ )
701
+ else:
702
+ return functools.partial(
703
+ run_method,
704
+ *input_tensors,
705
+ out,
706
+ *extra_args,
707
+ **warmup_arg,
708
+ stream=stream,
709
+ benchmark_run=True,
710
+ )
711
+
712
+ def precompile(self):
713
+ mod = PyCodeCache.load_by_key_path(self.module_cache_key, self.module_path)
714
+ getattr(mod, self.kernel_name).precompile()
715
+
716
+ def __str__(self) -> str:
717
+ return f"{self.kernel_name=}, {self.module_path=}, {self.module_cache_key=}"
718
+
719
+
720
+ class TritonGPUBenchmarkRequest(GPUDeviceBenchmarkMixin, TritonBenchmarkRequest):
721
+ pass
722
+
723
+
724
+ class TritonCPUBenchmarkRequest(CPUDeviceBenchmarkMixin, TritonBenchmarkRequest):
725
+ pass
726
+
727
+
728
+ class ExternKernelBenchmarkRequest(BenchmarkRequest):
729
+ """
730
+ A class to handle extern kernel benchmark requests. This allows extern kernels
731
+ (like aten::mm) to be benchmarked in a subprocess, similar to Triton kernels.
732
+
733
+ Important: Instances of this class have to be serializable across
734
+ process boundaries. Do not put CUDA Tensors in here!
735
+ """
736
+
737
+ def __init__(
738
+ self,
739
+ kernel_name: str,
740
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
741
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
742
+ extra_args: Iterable[Any],
743
+ callable_path: str, # Module path to the callable (e.g., "extern_kernels.mm")
744
+ kwargs: Optional[dict[str, Any]] = None,
745
+ has_out_variant: bool = True,
746
+ ) -> None:
747
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
748
+ self.callable_path = callable_path
749
+ self.kwargs = kwargs or {}
750
+ self.has_out_variant = has_out_variant
751
+
752
+ def make_run_fn(
753
+ self, *input_tensors: torch.Tensor, out: torch.Tensor
754
+ ) -> Callable[[], None]:
755
+ fn = self.to_callable()
756
+ if self.has_out_variant:
757
+ # For out=variant, pass output as keyword arg
758
+ return functools.partial(fn, *input_tensors, out=out)
759
+ else:
760
+ # For non-out variant, just call with inputs
761
+ return functools.partial(fn, *input_tensors)
762
+
763
+ def benchmark(
764
+ self, *input_tensors: torch.Tensor, out: Optional[torch.Tensor] = None
765
+ ):
766
+ if out is not None and out.numel() == 0:
767
+ # no need to run the kernel of do benchmarking
768
+ return 0.0
769
+ if self.has_out_variant or len(input_tensors) == 0:
770
+ return super().benchmark(*input_tensors, out=out)
771
+ else:
772
+ algo = self.to_callable()
773
+ out_new = algo(*input_tensors)
774
+ if out is not None:
775
+ torch._C._dynamo.guards.assert_size_stride(
776
+ out_new, tuple(out.size()), tuple(out.stride())
777
+ )
778
+ out.copy_(out_new) # for correctness checking
779
+ if config.profile_bandwidth_with_do_bench_using_profiling:
780
+ return do_bench_using_profiling(lambda: algo(*input_tensors))
781
+ return benchmarker.benchmark(algo, input_tensors, {})
782
+
783
+ def precompile(self) -> None:
784
+ # Extern kernels don't need precompilation - they're already compiled
785
+ pass
786
+
787
+ def to_callable(self):
788
+ # While ExternKernelChoice also has a to_callable method,
789
+ # we avoid calling the ExternKernelChoice version here to make sure
790
+ # this is picklable
791
+ from torch._inductor.select_algorithm import extern_kernels
792
+
793
+ fn = getattr(extern_kernels, self.kernel_name)
794
+ if self.kwargs:
795
+ return functools.partial(fn, **self.kwargs)
796
+
797
+ return fn
798
+
799
+ def __str__(self) -> str:
800
+ return f"ExternKernelBenchmarkRequest({self.callable_path})"
801
+
802
+
803
+ class ExternKernelGPUBenchmarkRequest(
804
+ GPUDeviceBenchmarkMixin, ExternKernelBenchmarkRequest
805
+ ):
806
+ pass
807
+
808
+
809
+ class ExternKernelCPUBenchmarkRequest(
810
+ CPUDeviceBenchmarkMixin, ExternKernelBenchmarkRequest
811
+ ):
812
+ pass
813
+
814
+
815
+ class CUTLASSBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest):
816
+ """
817
+ A class to handle CUDA (CUTLASS) benchmark requests. This class is for
818
+ managing the lifecycle of a CUDA kernel benchmark, including compiling
819
+ the source code, managing workspace memory, and executing the kernel.
820
+
821
+ Important: Instances of this class have to be serializable across
822
+ process boundaries. Do not put CUDA Tensors in here!
823
+ """
824
+
825
+ def __init__(
826
+ self,
827
+ kernel_name: str,
828
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
829
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
830
+ extra_args: Iterable[Any],
831
+ source_code: str,
832
+ device_type: str = "cuda",
833
+ ) -> None:
834
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
835
+ self.source_code = source_code
836
+ self.workspace_size: int = 0
837
+ self.workspace: Optional[torch.Tensor] = None
838
+ self.DLL: Optional[DLLWrapper] = None
839
+ self._workspace_size_updated = False
840
+ self.hash_key: str = ""
841
+ self.source_file: str = ""
842
+ self.device_type = device_type
843
+ self.codecache_cls = CUDACodeCache
844
+ self.device_interface = get_interface_for_device(device_type)
845
+ self.hash_key, self.source_file = self.codecache_cls.write(
846
+ self.source_code, "so"
847
+ )
848
+
849
+ def precompile(self):
850
+ """
851
+ Precompile the CUDA source code to populate the CUDACodeCache.
852
+ This may happen in a separate thread pool.
853
+ """
854
+ autotuning_log.debug("Precompiling %s", self)
855
+ CUDACodeCache.compile(self.source_code, "so")
856
+ autotuning_log.debug("Done precompiling %s", self)
857
+
858
+ def make_run_fn(
859
+ self, *input_tensors: torch.Tensor, out: torch.Tensor
860
+ ) -> Callable[[], None]:
861
+ """
862
+ Create a function to run the CUDA/XPU kernel with the given input and output tensors.
863
+ """
864
+
865
+ self.ensure_dll_loaded()
866
+ self.update_workspace_size()
867
+ args = [c_void_p(tensor.data_ptr()) for tensor in list(input_tensors) + [out]]
868
+ autotuning_log.debug(
869
+ "make_run_fn: self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s",
870
+ self.kernel_name,
871
+ self.source_file,
872
+ self.hash_key,
873
+ self.DLL,
874
+ args,
875
+ self.extra_args,
876
+ )
877
+ current_stream = self.device_interface.current_stream()
878
+ stream_ptr = c_void_p(current_stream.cuda_stream) # type: ignore[attr-defined]
879
+ run_method = getattr(self.DLL, self.kernel_name)
880
+ workspace_ptr = c_void_p(0)
881
+ if self.workspace_size > 0:
882
+ self.workspace = torch.zeros(
883
+ (self.workspace_size + 7) // 8,
884
+ dtype=torch.float64,
885
+ device=out.device,
886
+ )
887
+ workspace_ptr = c_void_p(self.workspace.data_ptr())
888
+
889
+ # Generate partial function.
890
+ ret = functools.partial(
891
+ run_method,
892
+ *args,
893
+ *self.extra_args,
894
+ None, # null workspace size ptr
895
+ workspace_ptr, # set workspace ptr,
896
+ stream_ptr,
897
+ )
898
+
899
+ # sanity check to make sure we cleanup run fn properly
900
+ try:
901
+ ret()
902
+ except RuntimeError as e:
903
+ err_msg = str(e)
904
+
905
+ def raise_runtime_error():
906
+ raise RuntimeError(err_msg)
907
+
908
+ self.cleanup_run_fn()
909
+ return raise_runtime_error
910
+
911
+ return ret
912
+
913
+ def update_workspace_size(self) -> None:
914
+ if self._workspace_size_updated:
915
+ return
916
+ self.ensure_dll_loaded()
917
+ unique_input_count = len(
918
+ dict.fromkeys(meta.name for meta in self.input_tensor_meta)
919
+ )
920
+ args = [c_void_p(None) for _ in range(unique_input_count + 1)]
921
+ current_stream = self.device_interface.current_stream()
922
+ stream_ptr = c_void_p(current_stream.cuda_stream) # type: ignore[attr-defined]
923
+
924
+ run_method = getattr(self.DLL, self.kernel_name)
925
+ # Retrieve workspace_size and initialize workspace.
926
+ c_workspace_size = c_size_t()
927
+ run_method(
928
+ *args, # input ptrs and output ptrs
929
+ *self.extra_args,
930
+ byref(
931
+ c_workspace_size
932
+ ), # set workspace size ptr to retrieve workspace size
933
+ None, # null workspace ptr
934
+ stream_ptr,
935
+ )
936
+ self.device_interface.synchronize() # shake out any device errors
937
+ self.workspace_size = c_workspace_size.value
938
+ autotuning_log.debug(
939
+ "update_workspace_size called: new workspace size=%d, self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s", # noqa: B950
940
+ self.workspace_size,
941
+ self.kernel_name,
942
+ self.source_file,
943
+ self.hash_key,
944
+ self.DLL,
945
+ args,
946
+ self.extra_args,
947
+ )
948
+ self._workspace_size_updated = True
949
+
950
+ def ensure_dll_loaded(self):
951
+ if self.DLL is None:
952
+ self.DLL, self.hash_key, self.source_file = self.codecache_cls.load(
953
+ self.source_code, "so"
954
+ )
955
+
956
+ def cleanup_run_fn(self) -> None:
957
+ if self.DLL is not None:
958
+ self.DLL.close()
959
+ self.DLL = None
960
+ self.workspace = None
961
+
962
+ def __str__(self) -> str:
963
+ return f"{self.kernel_name=}, {self.source_file=}, {self.hash_key=}"
964
+
965
+
966
+ class CppBenchmarkRequest(CPUDeviceBenchmarkMixin, BenchmarkRequest):
967
+ # Important: Instances of this class have to be serializable
968
+ # across process boundaries. Do not put Tensors in here!
969
+
970
+ def __init__(
971
+ self,
972
+ kernel_name: str,
973
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
974
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
975
+ extra_args: Iterable[Any],
976
+ source_code: str,
977
+ ) -> None:
978
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
979
+ self.source_code = source_code
980
+ self.hash_key = get_hash(source_code)
981
+ self.DLL: Optional[Union[CDLL, ModuleType]] = None
982
+
983
+ def precompile(self):
984
+ # Prepopulate CppCodeCache
985
+ # may happen in separate Threadpool
986
+ autotuning_log.debug("Precompiling %s", self)
987
+ CppCodeCache.load(self.source_code, device_type="cpu")
988
+ autotuning_log.debug("Done precompiling %s", self)
989
+
990
+ def make_run_fn(
991
+ self, *input_tensors: torch.Tensor, out: torch.Tensor
992
+ ) -> Callable[[], None]:
993
+ # TODO(jgong5): use CppPythonBindingsCodeCache for better binding perf
994
+ self.DLL = CppCodeCache.load(self.source_code, device_type="cpu")
995
+ args = [tensor.data_ptr() for tensor in list(input_tensors) + [out]]
996
+ autotuning_log.debug(
997
+ "make_run_fn: self.kernel_name=%s, self.DLL=%s, args=%s, self.extra_args=%s",
998
+ self.kernel_name,
999
+ self.DLL,
1000
+ args,
1001
+ self.extra_args,
1002
+ )
1003
+ run_method = getattr(self.DLL, self.kernel_name)
1004
+ # Assume only size with type ctypes.c_ulonglong in extra_args
1005
+ assert all(isinstance(arg, ctypes.c_ulonglong) for arg in self.extra_args)
1006
+ run_method.argtypes = [ctypes.c_ulonglong] * (
1007
+ len(args) + len(list(self.extra_args))
1008
+ )
1009
+
1010
+ # Generate partial function.
1011
+ return functools.partial(
1012
+ run_method,
1013
+ *args,
1014
+ *self.extra_args,
1015
+ )
1016
+
1017
+ def __str__(self) -> str:
1018
+ return f"{self.kernel_name=}"
1019
+
1020
+
1021
+ class CuteDSLBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest):
1022
+ """Benchmark request for CuteDSL (CUTLASS Python DSL) kernels."""
1023
+
1024
+ def __init__(
1025
+ self,
1026
+ kernel_name: str,
1027
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
1028
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
1029
+ extra_args: tuple[Any, ...],
1030
+ source_code: PartialRender,
1031
+ ) -> None:
1032
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
1033
+
1034
+ finalized_code = source_code.finalize_all()
1035
+ self.module_cache_key, self.module_path = PyCodeCache.write(finalized_code)
1036
+
1037
+ def make_run_fn(
1038
+ self, *input_tensors: torch.Tensor, out: torch.Tensor
1039
+ ) -> Callable[[], None]:
1040
+ """
1041
+ Create a function to run the CuteDSL kernel with the given input and output tensors.
1042
+ Similar to TritonBenchmarkRequest.make_run_fn but for CuteDSL kernels.
1043
+ """
1044
+ mod = PyCodeCache.load_by_key_path(self.module_cache_key, self.module_path)
1045
+
1046
+ # Logic replicated async_compile
1047
+ from .codegen.cutedsl.cutedsl_kernel import MAIN_SUFFIX
1048
+
1049
+ main_func_name = f"{self.kernel_name}_{MAIN_SUFFIX}"
1050
+
1051
+ if not hasattr(mod, main_func_name):
1052
+ available = [name for name in dir(mod) if callable(getattr(mod, name))]
1053
+ raise RuntimeError(
1054
+ f"Could not find CuteDSL main kernel function '{main_func_name}'. Available callables: {available}"
1055
+ )
1056
+
1057
+ kernel_func = getattr(mod, main_func_name)
1058
+
1059
+ def run_kernel():
1060
+ device_interface = get_interface_for_device("cuda")
1061
+ stream = device_interface.get_raw_stream(out.device.index)
1062
+ return kernel_func(*input_tensors, out, stream=stream)
1063
+
1064
+ return run_kernel
1065
+
1066
+
1067
+ @functools.cache
1068
+ def get_tuning_process_pool() -> TuningProcessPool:
1069
+ pool = TuningProcessPool()
1070
+ atexit.register(pool.shutdown)
1071
+ return pool
1072
+
1073
+
1074
+ def benchmark_in_sub_process(
1075
+ choices: list[TritonTemplateCaller],
1076
+ ) -> dict[TritonTemplateCaller, float]:
1077
+ """
1078
+ Do benchmarking in a subprocess and return the perf number (latency).
1079
+ """
1080
+ return get_tuning_process_pool().benchmark(choices)
1081
+
1082
+
1083
+ class AutotuneProcessPool:
1084
+ """
1085
+ Singleton pool manager for running autotuning (precompilation + benchmarking)
1086
+ in a separate process.
1087
+ """
1088
+
1089
+ _instance: Optional[AutotuneProcessPool] = None
1090
+ _lock: threading.Lock = threading.Lock()
1091
+ _shutdown_for_inactivity: bool = False
1092
+
1093
+ def __init__(self):
1094
+ self._pool: ProcessPoolExecutor | None = self._init_pool()
1095
+ self._warmup_future: Future[Any] | None = None
1096
+ self._warmup_start_time: float | None = None
1097
+ self._timer: Timer | None = self._init_timer()
1098
+
1099
+ @classmethod
1100
+ def get_instance(cls):
1101
+ """Get or create the singleton pool instance."""
1102
+ if cls._instance is None:
1103
+ with cls._lock:
1104
+ if cls._instance is None:
1105
+ # num_workers=1 to avoid GPU contention during benchmarking
1106
+ cls._instance = cls()
1107
+ return cls._instance
1108
+
1109
+ @property
1110
+ def pool(self):
1111
+ """Get the process pool."""
1112
+ assert config.pipeline_max_autotune_gemm, (
1113
+ "To use AutotuneProcessPool, pipeline_max_autotune_gemm must be enabled"
1114
+ )
1115
+ if self._pool is None:
1116
+ self._pool = self._init_pool()
1117
+ self._timer = self._init_timer()
1118
+ return self._pool
1119
+
1120
+ def _init_timer(self) -> Timer | None:
1121
+ if AUTOTUNE_POOL_INACTIVITY_TIMEOUT > 0:
1122
+ return Timer(AUTOTUNE_POOL_INACTIVITY_TIMEOUT, self._on_inactivity_timeout)
1123
+ return None
1124
+
1125
+ def _record_activity(self) -> None:
1126
+ if self._timer is not None:
1127
+ self._timer.record_call()
1128
+
1129
+ def _on_inactivity_timeout(self) -> None:
1130
+ autotuning_log.info(
1131
+ "AutotuneProcessPool shutting down due to inactivity (timeout=%ds)",
1132
+ AUTOTUNE_POOL_INACTIVITY_TIMEOUT,
1133
+ )
1134
+
1135
+ with self._lock:
1136
+ if self._pool is not None:
1137
+ self._pool.shutdown(wait=False)
1138
+ self._pool = None
1139
+ self._timer = None
1140
+
1141
+ # Mark that the pool was shut down for inactivity.
1142
+ # This prevents the pool from being recreated on recompiles
1143
+ # which likely do not require large amounts of autotuning.
1144
+ AutotuneProcessPool._shutdown_for_inactivity = True
1145
+
1146
+ def _init_pool(self):
1147
+ """
1148
+ Get or create the process pool.
1149
+
1150
+ Uses ProcessPoolExecutor with 'spawn' context for CUDA safety.
1151
+ ProcessPoolExecutor is lazily initialized - workers are not spawned
1152
+ until the first submit() call, making this property non-blocking.
1153
+ """
1154
+ # Use 'spawn' context to avoid CUDA fork issues
1155
+ # Workers are spawned lazily on first submit(), not here
1156
+ ctx = mp.get_context("spawn")
1157
+ pool = ProcessPoolExecutor(
1158
+ max_workers=1,
1159
+ mp_context=ctx,
1160
+ )
1161
+ atexit.register(self._shutdown)
1162
+ autotuning_log.info("AutotuneProcessPool created (workers spawn lazily)")
1163
+
1164
+ return pool
1165
+
1166
+ def warm_up(self) -> Future[Any]:
1167
+ """
1168
+ Submit a warmup job to eagerly spawn workers and initialize CUDA.
1169
+
1170
+ This is optional - call it early to hide spawn latency.
1171
+ Returns the warmup future which can be ignored or awaited.
1172
+ """
1173
+ if self._warmup_future is None:
1174
+ with self._lock:
1175
+ if self._warmup_future is None:
1176
+ self._warmup_start_time = time.perf_counter()
1177
+ self._warmup_future = self.pool.submit(
1178
+ _init_autotune_subprocess,
1179
+ allow_tf32=torch.backends.cuda.matmul.allow_tf32,
1180
+ )
1181
+ self._warmup_future.add_done_callback(self._on_warmup_complete)
1182
+ autotuning_log.info("Warmup job submitted")
1183
+ # pyrefly: ignore[bad-return]
1184
+ return self._warmup_future
1185
+
1186
+ def _on_warmup_complete(self, future: Future[Any]) -> None:
1187
+ """Callback invoked when the warmup job completes."""
1188
+ warmup_elapsed_time = None
1189
+ if self._warmup_start_time is not None:
1190
+ warmup_elapsed_time = time.perf_counter() - self._warmup_start_time
1191
+
1192
+ try:
1193
+ result = future.result()
1194
+ autotuning_log.info(
1195
+ "AutotuneProcessPool warmup completed successfully in %.4f seconds: %s",
1196
+ warmup_elapsed_time,
1197
+ result,
1198
+ )
1199
+ except Exception as e:
1200
+ autotuning_log.error(
1201
+ "AutotuneProcessPool warmup failed after %.4f seconds",
1202
+ warmup_elapsed_time,
1203
+ )
1204
+ raise e
1205
+
1206
+ def submit(self, fn, *args, **kwargs) -> Future[Any]:
1207
+ """Submit a job to the pool and return a Future."""
1208
+ future = self.pool.submit(fn, *args, **kwargs)
1209
+ if self._timer is not None:
1210
+ future.add_done_callback(lambda _: self._record_activity())
1211
+ return future
1212
+
1213
+ def _shutdown(self):
1214
+ """Shutdown the pool on exit."""
1215
+ if self._timer is not None:
1216
+ self._timer.quit()
1217
+ self._timer = None
1218
+ if self._pool is not None:
1219
+ self._pool.shutdown(wait=False)
1220
+ self._pool = None
1221
+
1222
+ @classmethod
1223
+ def shutdown_instance(cls):
1224
+ """Explicitly shutdown the singleton instance."""
1225
+ if cls._instance is not None:
1226
+ with cls._lock:
1227
+ if cls._instance is not None:
1228
+ cls._instance._shutdown()
1229
+ cls._instance = None
1230
+
1231
+
1232
+ def use_pipelined_autotuning() -> bool:
1233
+ return (
1234
+ config.pipeline_max_autotune_gemm
1235
+ and not AutotuneProcessPool._shutdown_for_inactivity
1236
+ )
1237
+
1238
+
1239
+ def _init_autotune_subprocess(allow_tf32: bool) -> bool:
1240
+ """
1241
+ Warmup function run in the autotune subprocess.
1242
+ """
1243
+ import torch
1244
+
1245
+ # Initialize dummy tensor for CUDA context
1246
+ if torch.cuda.is_available():
1247
+ torch.zeros(1, device="cuda")
1248
+
1249
+ torch.backends.cuda.matmul.allow_tf32 = allow_tf32
1250
+
1251
+ return True
1252
+
1253
+
1254
+ def run_autotune_in_subprocess(
1255
+ benchmark_request: BenchmarkRequest,
1256
+ ) -> float:
1257
+ """
1258
+ Run autotuning benchmarks in a subprocess.
1259
+
1260
+ This function is submitted to AutotuneProcessPool and runs in isolation
1261
+ to prevent GPU contention with the main compilation process.
1262
+
1263
+ Args:
1264
+ picklable_choices: List of picklable choice information
1265
+
1266
+ Returns:
1267
+ timing
1268
+ """
1269
+
1270
+ try:
1271
+ # Run the benchmark directly - bmreq is already a BenchmarkRequest
1272
+ timing = benchmark_request.benchmark()
1273
+
1274
+ return timing
1275
+
1276
+ except Exception:
1277
+ autotuning_log.error(
1278
+ "Failed to benchmark choice %s",
1279
+ benchmark_request,
1280
+ )
1281
+ # Use infinity for failed benchmarks so they're not selected
1282
+ return float("inf")
1283
+
1284
+
1285
+ class PrecompileThreadPool:
1286
+ """
1287
+ Thread pool for running precompilation asynchronously.
1288
+
1289
+ This allows the main compilation process to continue while
1290
+ precompilation happens in background threads.
1291
+ """
1292
+
1293
+ _instance: Optional[PrecompileThreadPool] = None
1294
+ _lock = threading.Lock()
1295
+
1296
+ def __init__(self, max_workers: int = 4):
1297
+ self._executor = ThreadPoolExecutor(max_workers=max_workers)
1298
+
1299
+ @classmethod
1300
+ def get_instance(cls) -> PrecompileThreadPool:
1301
+ from torch._inductor.select_algorithm import get_num_workers
1302
+
1303
+ if cls._instance is None:
1304
+ with cls._lock:
1305
+ if cls._instance is None:
1306
+ cls._instance = cls(get_num_workers())
1307
+ return cls._instance
1308
+
1309
+ def submit(self, fn, *args, **kwargs):
1310
+ return self._executor.submit(fn, *args, **kwargs)
1311
+
1312
+ def _shutdown(self, wait: bool = False):
1313
+ return self._executor.shutdown(wait=wait)
1314
+
1315
+ @classmethod
1316
+ def shutdown_instance(cls) -> None:
1317
+ if cls._instance is not None:
1318
+ with cls._lock:
1319
+ if cls._instance is not None:
1320
+ cls._instance._shutdown(wait=False)
1321
+ cls._instance = None
1322
+
1323
+
1324
+ class AsyncAutotuner:
1325
+ """
1326
+ Handles asynchronous autotuning of kernel choices in a separate process.
1327
+
1328
+ This class manages the lifecycle of autotuning:
1329
+ 1. Accepts precompiled choices from the main process
1330
+ 2. Submits benchmarking work to AutotuneProcessPool
1331
+ 3. Returns results via a Future
1332
+
1333
+ Usage:
1334
+ autotuner = AsyncAutotuner(choices)
1335
+ autotuner.start() # Kicks off async benchmarking
1336
+ timings = autotuner.get_results() # Blocks until complete
1337
+ """
1338
+
1339
+ choice_hash_to_future = {}
1340
+
1341
+ @staticmethod
1342
+ def get_choice_hash(choice: ChoiceCaller, inputs_key: str) -> str:
1343
+ return choice.hash_key() + inputs_key
1344
+
1345
+ @classmethod
1346
+ def start(cls, choices: list[ChoiceCaller], inputs_key: str):
1347
+ """
1348
+ Start asynchronous autotuning in a subprocess.
1349
+
1350
+ This method:
1351
+ 1. Extracts picklable benchmark requests from choices
1352
+ 2. Submits benchmarking work to AutotuneProcessPool
1353
+ 3. Returns immediately (non-blocking)
1354
+ """
1355
+
1356
+ for choice in choices:
1357
+ choice_hash = AsyncAutotuner.get_choice_hash(choice, inputs_key)
1358
+
1359
+ if choice_hash in AsyncAutotuner.choice_hash_to_future:
1360
+ continue
1361
+
1362
+ assert getattr(choice, "bmreq", None) is not None, (
1363
+ "bmreq is None for choice"
1364
+ )
1365
+
1366
+ autotune_future = AutotuneProcessPool.get_instance().submit(
1367
+ run_autotune_in_subprocess,
1368
+ choice.bmreq,
1369
+ )
1370
+
1371
+ AsyncAutotuner.choice_hash_to_future[choice_hash] = autotune_future
1372
+
1373
+ @classmethod
1374
+ def get_results(
1375
+ cls, choices: list[ChoiceCaller], inputs_key: str
1376
+ ) -> dict[ChoiceCaller, float]:
1377
+ """
1378
+ Get autotuning results, blocking until complete.
1379
+
1380
+ Args:
1381
+ timeout: Maximum time to wait in seconds. None means wait forever.
1382
+
1383
+ Returns:
1384
+ Dict mapping ChoiceCaller to benchmark timing
1385
+ """
1386
+
1387
+ timings = {}
1388
+ for choice in choices:
1389
+ choice_hash = AsyncAutotuner.get_choice_hash(choice, inputs_key)
1390
+ timings[choice] = AsyncAutotuner.choice_hash_to_future[choice_hash].result()
1391
+ return timings
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_runtime/interface.cpp ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/compile_utils.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ import os
4
+ import shutil
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import torch
9
+ from torch._inductor import config
10
+ from torch._inductor.codegen.cuda import cuda_env
11
+ from torch._inductor.cpp_builder import _set_gpu_runtime_env, _transform_cuda_paths
12
+ from torch._inductor.utils import is_linux
13
+
14
+
15
+ if config.is_fbcode():
16
+ from triton.fb.build import build_paths
17
+
18
+
19
+ log = logging.getLogger(__name__)
20
+ autotuning_log = torch._logging.getArtifactLogger(__name__, "autotuning")
21
+
22
+
23
+ def use_re_build() -> bool:
24
+ """
25
+ Use for CUTLASS compilation only right now.
26
+ """
27
+ if config.is_fbcode() and not cuda_env.nvcc_exist(_cuda_compiler()):
28
+ from triton.fb.re_build_helper import should_build_locally
29
+
30
+ return not should_build_locally()
31
+ return False
32
+
33
+
34
+ def _cutlass_path() -> str:
35
+ if config.is_fbcode():
36
+ from libfb.py import parutil
37
+
38
+ return parutil.get_dir_path("cutlass-4-headers")
39
+ else:
40
+ return config.cutlass.cutlass_dir
41
+
42
+
43
+ def _cutlass_paths() -> list[str]:
44
+ return [
45
+ "include",
46
+ "tools/library/include",
47
+ "tools/library/src",
48
+ "tools/util/include",
49
+ ]
50
+
51
+
52
+ def _clone_cutlass_paths(build_root: str) -> list[str]:
53
+ paths = _cutlass_paths()
54
+ cutlass_root = _cutlass_path()
55
+ for path in _cutlass_paths():
56
+ old_path = os.path.join(cutlass_root, path)
57
+ new_path = os.path.join(build_root, path)
58
+ shutil.copytree(old_path, new_path, dirs_exist_ok=True)
59
+ return paths
60
+
61
+
62
+ def _cutlass_include_paths() -> list[str]:
63
+ cutlass_path = _cutlass_path()
64
+ return [
65
+ # Use realpath to get canonical absolute paths, in order not to mess up cache keys
66
+ os.path.realpath(os.path.join(cutlass_path, path))
67
+ for path in _cutlass_paths()
68
+ ]
69
+
70
+
71
+ def _cuda_compiler() -> Optional[str]:
72
+ if cuda_env.nvcc_exist(config.cuda.cuda_cxx):
73
+ return config.cuda.cuda_cxx
74
+ if config.is_fbcode():
75
+ return os.path.join(build_paths.sdk_home, "bin", "nvcc")
76
+ if cuda_env.nvcc_exist(os.getenv("CUDACXX")):
77
+ return os.getenv("CUDACXX", "")
78
+ if cuda_env.nvcc_exist(os.getenv("CUDA_HOME")):
79
+ return os.path.realpath(os.path.join(os.getenv("CUDA_HOME", ""), "bin/nvcc"))
80
+ return "nvcc"
81
+
82
+
83
+ def _cuda_lib_options() -> list[str]:
84
+ """
85
+ Util function for CUTLASS backend to find the correct CUDA libraries.
86
+ """
87
+ _set_gpu_runtime_env() # cpp_extension consults the env
88
+ from torch.utils import cpp_extension
89
+
90
+ lpaths = cpp_extension.library_paths(device_type="cuda")
91
+ if use_re_build():
92
+ lpaths += [
93
+ build_paths.sdk_lib,
94
+ os.path.join(build_paths.sdk_lib, "stubs"),
95
+ ]
96
+ extra_ldflags: list[str] = []
97
+ if is_linux():
98
+ _transform_cuda_paths(lpaths)
99
+ for path in lpaths:
100
+ if "torch/lib" in path:
101
+ # don't want to depend on pytorch
102
+ continue
103
+ extra_ldflags.append(f"-L{path}")
104
+ # -rpath ensures the DLL can find its dependencies when loaded, even
105
+ # if the library path is non-standard.
106
+ # But do not add the stubs folder to rpath as the driver is expected to be found at runtime
107
+ if os.path.basename(path) != "stubs":
108
+ extra_ldflags.extend(["-Xlinker", f"-rpath={path}"])
109
+ extra_ldflags.append("-lcuda")
110
+ extra_ldflags.append("-lcudart")
111
+ else:
112
+ raise NotImplementedError(
113
+ "Unsupported env, failed to find cuda libs! Currently only Linux is supported."
114
+ )
115
+ return extra_ldflags
116
+
117
+
118
+ def _nvcc_host_compiler_options() -> list[str]:
119
+ return [
120
+ "-fPIC",
121
+ "-fno-strict-aliasing",
122
+ "-fvisibility=hidden",
123
+ "-Wconversion",
124
+ ]
125
+
126
+
127
+ def _nvcc_arch_as_compile_option() -> str:
128
+ arch = cuda_env.get_cuda_arch()
129
+ if arch == "90":
130
+ # Required by cutlass compilation.
131
+ return "90a"
132
+ if arch == "103":
133
+ return "100f"
134
+ if arch == "100":
135
+ return "100a"
136
+ if arch == "120":
137
+ return "120a"
138
+ return arch
139
+
140
+
141
+ def _nvcc_compiler_options() -> list[str]:
142
+ arch = _nvcc_arch_as_compile_option()
143
+ code = [f"sm_{arch}", f"compute_{arch}"]
144
+ if config.cuda.enable_cuda_lto:
145
+ code += [f"lto_{arch}"]
146
+ options = [
147
+ "-t=0",
148
+ "-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1",
149
+ "-DCUTLASS_ENABLE_SM90_EXTENDED_MMA_SHAPES=1",
150
+ "-DCUTE_SM90_EXTENDED_MMA_SHAPES_ENABLED",
151
+ "-w",
152
+ f"-gencode=arch=compute_{arch},code=[{','.join(code)}]",
153
+ config.cutlass.compile_opt_level,
154
+ "-std=c++17",
155
+ "--expt-relaxed-constexpr",
156
+ "-DNDEBUG",
157
+ ]
158
+ if config.is_fbcode():
159
+ options.extend(["-ccbin", os.path.dirname(build_paths.gcc)])
160
+ if config.cutlass.enable_debug_info:
161
+ options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"])
162
+ if config.cuda.enable_ptxas_info:
163
+ options.extend(
164
+ [
165
+ "--keep", # Keep the intermediate files for debugging (including ptx, sass, cubin etc.)
166
+ "--ptxas-options=--warn-on-local-memory-usage", # warn us if local memory is used in CUDA Kernels
167
+ "--ptxas-options=--warn-on-spills", # warn us if register spilling happens in CUDA Kernels
168
+ "--resource-usage", # Report on CUDA resource usage (shared mem, registers etc.)
169
+ "--source-in-ptx",
170
+ ]
171
+ ) # Annotate the ptx file with source information
172
+ if config.cutlass.use_fast_math:
173
+ options.extend(
174
+ [
175
+ "--use_fast_math",
176
+ "-DCUTLASS_USE_TANH_FOR_SIGMOID=1",
177
+ ]
178
+ )
179
+ return options
180
+
181
+
182
+ def cuda_compile_command(
183
+ src_files: list[str],
184
+ dst_file: str,
185
+ dst_file_ext: str,
186
+ extra_args: list[str] | None = None,
187
+ ) -> str:
188
+ if extra_args is None:
189
+ extra_args = []
190
+ if use_re_build():
191
+ build_path = os.path.dirname(dst_file)
192
+ include_paths = _clone_cutlass_paths(build_path)
193
+ src_files = [os.path.basename(src_file) for src_file in src_files]
194
+ dst_file = os.path.basename(dst_file)
195
+ else:
196
+ include_paths = _cutlass_include_paths()
197
+ cuda_lib_options = _cuda_lib_options()
198
+ nvcc_host_compiler_options = _nvcc_host_compiler_options()
199
+ nvcc_compiler_options = _nvcc_compiler_options()
200
+ options = (
201
+ nvcc_compiler_options
202
+ + extra_args
203
+ + [
204
+ f"-Xcompiler {opt}" if "=" in opt else f"-Xcompiler={opt}"
205
+ for opt in nvcc_host_compiler_options
206
+ ]
207
+ + ["-I" + path for path in include_paths]
208
+ + cuda_lib_options
209
+ )
210
+ src_file = " ".join(src_files)
211
+ res = ""
212
+ if dst_file_ext == "o":
213
+ res = f"{_cuda_compiler()} {' '.join(options)} -c -o {dst_file} {src_file}"
214
+ elif dst_file_ext == "so":
215
+ options.append("-shared")
216
+ res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}"
217
+ elif dst_file_ext == "exe":
218
+ res = f"{_cuda_compiler()} {' '.join(options)} -o {dst_file} {src_file}"
219
+ else:
220
+ raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!")
221
+ if log.isEnabledFor(logging.DEBUG):
222
+ log.debug("CUDA command: %s", res)
223
+ else:
224
+ autotuning_log.debug("CUDA command: %s", res)
225
+ return res
226
+
227
+
228
+ class CUDACompileSourceCapturingContext:
229
+ # Helper class for Benchmarking and Testing CUTLASS Kernels in isolation.
230
+ # Can be used to capture the sourcecode passed to CUDACodeCache.compile
231
+
232
+ def __init__(self):
233
+ self.sources = []
234
+ self._compile_patch = None
235
+
236
+ def __enter__(self, *args, **kwargs):
237
+ import unittest.mock as mock
238
+
239
+ import torch._inductor.codecache
240
+
241
+ _compile_method_orig = torch._inductor.codecache.CUDACodeCache.compile
242
+
243
+ def my_compile(
244
+ source_code, dst_file_ext, extra_args: Optional[list[str]] = None
245
+ ):
246
+ self.sources.append(source_code)
247
+ return _compile_method_orig(source_code, dst_file_ext)
248
+
249
+ # pyrefly: ignore [bad-assignment]
250
+ self._compile_patch = mock.patch(
251
+ "torch._inductor.codecache.CUDACodeCache.compile", my_compile
252
+ )
253
+ self._compile_patch.__enter__(*args, **kwargs) # type: ignore[union-attr]
254
+ return self
255
+
256
+ def __exit__(self, *args, **kwargs):
257
+ self._compile_patch.__exit__(*args, **kwargs) # type: ignore[union-attr]
258
+
259
+
260
+ def cuda_standalone_runner_compile_command(srcpath: Path, exepath: Path):
261
+ # returns command string to compile a (captured) CUDA GEMM Kernel source to a standalone executable that's ready to run
262
+ # Passes the correct preprocessor define to nvcc to ensure the standalone runner is enabled.
263
+
264
+ extra_args = ["-DGENERATE_STANDALONE_RUNNER=1", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"]
265
+ compile_command = cuda_compile_command(
266
+ [str(srcpath)], str(exepath), "exe", extra_args=extra_args
267
+ )
268
+ return compile_command
.venv/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
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda/device_op_overrides.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+ import torch
6
+
7
+ from ..common import (
8
+ DeviceOpOverrides,
9
+ register_device_op_overrides,
10
+ TritonScratchWorkspace,
11
+ )
12
+
13
+
14
+ class CUDADeviceOpOverrides(DeviceOpOverrides):
15
+ """
16
+ CUDA-specific codegen functions, see DeviceOpOverrides for details
17
+ """
18
+
19
+ def import_get_raw_stream_as(self, name: str) -> str:
20
+ return f"from torch._C import _cuda_getCurrentRawStream as {name}"
21
+
22
+ def set_device(self, device_idx: int) -> str:
23
+ return f"torch.cuda.set_device({device_idx})"
24
+
25
+ def synchronize(self) -> str:
26
+ return "torch.cuda.synchronize()"
27
+
28
+ def device_guard(self, device_idx: int) -> str:
29
+ return f"torch.cuda._DeviceGuard({device_idx})"
30
+
31
+ def cpp_device_guard(self) -> str:
32
+ return "at::cuda::CUDAGuard"
33
+
34
+ def cpp_aoti_device_guard(self) -> str:
35
+ return "AOTICudaGuard"
36
+
37
+ def cpp_stream_guard(self) -> str:
38
+ return "at::cuda::CUDAStreamGuard"
39
+
40
+ def cpp_aoti_stream_guard(self) -> str:
41
+ return "AOTICudaStreamGuard"
42
+
43
+ def cpp_getStreamFromExternal(self) -> str:
44
+ return "at::cuda::getStreamFromExternal"
45
+
46
+ def kernel_header(self) -> str:
47
+ source_codes = """
48
+ #include <c10/cuda/CUDAGuard.h>
49
+ #include <c10/cuda/CUDAStream.h>
50
+ #include <ATen/cuda/EmptyTensor.h>
51
+ """
52
+ return source_codes
53
+
54
+ def kernel_driver(self) -> str:
55
+ source_codes = """
56
+ #define CUDA_DRIVER_CHECK(EXPR) \\
57
+ do { \\
58
+ CUresult code = EXPR; \\
59
+ const char *msg; \\
60
+ CUresult code_get_error = cuGetErrorString(code, &msg); \\
61
+ if (code_get_error != CUDA_SUCCESS) { \\
62
+ throw std::runtime_error( \\
63
+ std::string("CUDA driver error: ") + \\
64
+ std::string("invalid error code!")); \\
65
+ } \\
66
+ if (code != CUDA_SUCCESS) { \\
67
+ throw std::runtime_error( \\
68
+ std::string("CUDA driver error: ") + \\
69
+ std::string(msg)); \\
70
+ } \\
71
+ } while (0);
72
+
73
+ static inline CUfunction loadKernel(
74
+ std::string filePath,
75
+ const std::string &funcName,
76
+ uint32_t sharedMemBytes,
77
+ const std::optional<std::string> &cubinDir = std::nullopt) {
78
+ if (cubinDir) {
79
+ std::filesystem::path p1{*cubinDir};
80
+ std::filesystem::path p2{filePath};
81
+ filePath = (p1 / p2.filename()).string();
82
+ }
83
+
84
+ CUmodule mod;
85
+ CUfunction func;
86
+ CUDA_DRIVER_CHECK(cuModuleLoad(&mod, filePath.c_str()));
87
+ CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str()));
88
+ if (sharedMemBytes > 0) {
89
+ CUDA_DRIVER_CHECK(cuFuncSetAttribute(
90
+ func,
91
+ CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
92
+ sharedMemBytes
93
+ ))
94
+ }
95
+ return func;
96
+ }
97
+
98
+ static inline CUfunction loadKernel(const void* start, const std::string &funcName, uint32_t sharedMemBytes) {
99
+ CUmodule mod;
100
+ CUfunction func;
101
+ CUDA_DRIVER_CHECK(cuModuleLoadData(&mod, start));
102
+ CUDA_DRIVER_CHECK(cuModuleGetFunction(&func, mod, funcName.c_str()));
103
+ if (sharedMemBytes > 0) {
104
+ CUDA_DRIVER_CHECK(cuFuncSetAttribute(
105
+ func,
106
+ CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
107
+ sharedMemBytes
108
+ ))
109
+ }
110
+ return func;
111
+ }
112
+
113
+ static inline void launchKernel(
114
+ CUfunction func,
115
+ uint32_t gridX,
116
+ uint32_t gridY,
117
+ uint32_t gridZ,
118
+ uint32_t numWarps,
119
+ uint32_t sharedMemBytes,
120
+ void* args[],
121
+ cudaStream_t stream) {
122
+ CUDA_DRIVER_CHECK(cuLaunchKernel(
123
+ func, gridX, gridY, gridZ, 32*numWarps, 1, 1, sharedMemBytes, stream, args, nullptr
124
+ ));
125
+ }
126
+ """
127
+ if torch.version.hip is not None:
128
+ # Adjusting the warp size to GPU supported wavefront size on AMD GPU
129
+ prop = torch.cuda.get_device_properties(torch.cuda.current_device())
130
+ source_codes = source_codes.replace(
131
+ "32*numWarps", str(prop.warp_size) + "*numWarps"
132
+ )
133
+ return source_codes
134
+
135
+ def tma_descriptor_helpers(self) -> str:
136
+ """
137
+ CUDA helper functions for initializing TMA Descriptors on host side
138
+ """
139
+ if torch.version.hip is not None:
140
+ raise RuntimeError("Host-side TMA descriptors not supported on HIP.")
141
+
142
+ # helper functions for initializing 1D and 2D TMA descriptors in C++. borrowed from the Triton code here:
143
+ # Old APIs (fill(1|2)DTMADescriptor):
144
+ # https://github.com/triton-lang/triton/blob/6af4f88591c85de079d8a36a4d7dba67918e2b39/third_party/nvidia/backend/driver.c#L283
145
+ # New APIs (fillTMADescriptor):
146
+ # https://github.com/triton-lang/triton/blob/main/third_party/nvidia/backend/driver.c#L283
147
+ return """
148
+ #if !defined(USE_ROCM) && defined(CUDA_VERSION) && CUDA_VERSION >= 12000
149
+ [[maybe_unused]] static void init1DTMADescriptor(
150
+ CUtensorMap* m,
151
+ void* globalAddress,
152
+ uint64_t dim,
153
+ uint32_t blockDim,
154
+ uint32_t elementSize) {
155
+ uint64_t dims[1] = {dim};
156
+ uint64_t globalStrides[1] = {dim * elementSize};
157
+ uint32_t tensorDims[1] = {blockDim};
158
+ uint32_t elementStrides[1] = {1};
159
+
160
+ CUtensorMapDataType type;
161
+ switch (elementSize) {
162
+ case 1:
163
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT8;
164
+ break;
165
+ case 2:
166
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT16;
167
+ break;
168
+ case 4:
169
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT32;
170
+ break;
171
+ default:
172
+ throw std::runtime_error("elementSize must be 1, 2, or 4");
173
+ }
174
+
175
+ if (elementSize * blockDim < 32) {
176
+ throw std::runtime_error("block size too small");
177
+ }
178
+
179
+ int rank = 1;
180
+
181
+ CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled(
182
+ m, type, rank, globalAddress, dims,
183
+ globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE,
184
+ CU_TENSOR_MAP_SWIZZLE_NONE, CU_TENSOR_MAP_L2_PROMOTION_NONE,
185
+ CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE));
186
+ }
187
+
188
+ [[maybe_unused]] static void init2DTMADescriptor(
189
+ CUtensorMap* m,
190
+ void* globalAddress,
191
+ uint64_t dim1,
192
+ uint64_t dim0,
193
+ uint32_t blockDim1,
194
+ uint32_t blockDim0,
195
+ uint32_t elementSize) {
196
+ uint64_t dims[2] = {dim0, dim1};
197
+ uint32_t tensorDims[2] = {blockDim0, blockDim1};
198
+ uint64_t globalStrides[2] = {dims[0] * elementSize,
199
+ dims[0] * dims[1] * elementSize};
200
+ uint32_t elementStrides[2] = {1, 1};
201
+
202
+ CUtensorMapDataType type;
203
+ switch (elementSize) {
204
+ case 1:
205
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT8;
206
+ break;
207
+ case 2:
208
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT16;
209
+ break;
210
+ case 4:
211
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT32;
212
+ break;
213
+ default:
214
+ throw std::runtime_error("elementSize must be 1, 2, or 4");
215
+ }
216
+
217
+ int rank = 2;
218
+
219
+ CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
220
+ uint32_t contigDimSizeInByte = elementSize * tensorDims[0];
221
+ if (contigDimSizeInByte >= 128) {
222
+ swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
223
+ } else if (contigDimSizeInByte >= 64) {
224
+ swizzle = CU_TENSOR_MAP_SWIZZLE_64B;
225
+ } else if (contigDimSizeInByte >= 32) {
226
+ swizzle = CU_TENSOR_MAP_SWIZZLE_32B;
227
+ } else {
228
+ throw std::runtime_error("block size too small");
229
+ }
230
+
231
+ if (contigDimSizeInByte > 128) {
232
+ tensorDims[0] = 128 / elementSize;
233
+ }
234
+
235
+ CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled(
236
+ m, type, rank, globalAddress, dims,
237
+ globalStrides, tensorDims, elementStrides, CU_TENSOR_MAP_INTERLEAVE_NONE,
238
+ swizzle, CU_TENSOR_MAP_L2_PROMOTION_L2_128B,
239
+ CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE));
240
+ }
241
+
242
+ [[maybe_unused]] static void initTMADescriptor(
243
+ CUtensorMap* m,
244
+ void* globalAddress,
245
+ int elemSize,
246
+ int rank,
247
+ uint32_t* blockSize,
248
+ uint64_t* shape,
249
+ uint64_t* stride
250
+ ) {
251
+ uint32_t elementStrides[5] = {1, 1, 1, 1, 1};
252
+ uint32_t blockSizeInt[5];
253
+ uint64_t shapeInt[5];
254
+ uint64_t stridesLL[5];
255
+
256
+ // Reorder blockSize (reverse the order)
257
+ for (int i = 0; i < rank; ++i) {
258
+ blockSizeInt[rank - i - 1] = blockSize[i];
259
+ }
260
+
261
+ // Reorder shape (reverse the order)
262
+ for (int i = 0; i < rank; ++i) {
263
+ shapeInt[rank - i - 1] = shape[i];
264
+ }
265
+
266
+ // Reorder and calculate strides
267
+ for (int i = 0; i + 1 < rank; ++i) {
268
+ stridesLL[rank - i - 2] = elemSize * stride[i];
269
+ }
270
+ stridesLL[rank - 1] =
271
+ shapeInt[rank - 1] * (rank == 1 ? elemSize : stridesLL[rank - 2]);
272
+
273
+ CUtensorMapDataType type;
274
+ // In Triton this is computed ahead of time; but for simplicity
275
+ // in the PyTorch version we copied this code from the old
276
+ // TMA API handling (i.e. init2DTMADescriptor)
277
+ switch (elemSize) {
278
+ case 1:
279
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT8;
280
+ break;
281
+ case 2:
282
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT16;
283
+ break;
284
+ case 4:
285
+ type = CU_TENSOR_MAP_DATA_TYPE_UINT32;
286
+ break;
287
+ default:
288
+ throw std::runtime_error("elemSize must be 1, 2, or 4");
289
+ }
290
+
291
+ // Calculate the size of the most contiguous dimension in bytes
292
+ CUtensorMapSwizzle swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
293
+ uint32_t contigDimSizeInByte = elemSize * blockSizeInt[0];
294
+ if (rank == 1) {
295
+ // rank 1 should not be swizzled
296
+ swizzle = CU_TENSOR_MAP_SWIZZLE_NONE;
297
+ } else if (contigDimSizeInByte >= 128) {
298
+ swizzle = CU_TENSOR_MAP_SWIZZLE_128B;
299
+ } else if (contigDimSizeInByte >= 64) {
300
+ swizzle = CU_TENSOR_MAP_SWIZZLE_64B;
301
+ } else if (contigDimSizeInByte >= 32) {
302
+ swizzle = CU_TENSOR_MAP_SWIZZLE_32B;
303
+ } else {
304
+ throw std::runtime_error("block size too small");
305
+ }
306
+
307
+ CUDA_DRIVER_CHECK(cuTensorMapEncodeTiled(
308
+ m, type, rank, globalAddress,
309
+ shapeInt, stridesLL, blockSizeInt, elementStrides,
310
+ CU_TENSOR_MAP_INTERLEAVE_NONE, (CUtensorMapSwizzle)swizzle,
311
+ CU_TENSOR_MAP_L2_PROMOTION_L2_128B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE));
312
+ }
313
+
314
+ struct StableTMADescriptor {
315
+ CUtensorMap m;
316
+ uint32_t block_shape[5];
317
+ uint64_t global_shape[5];
318
+ uint64_t strides[5];
319
+ };
320
+ #endif
321
+ """
322
+
323
+ def cpp_stream_type(self) -> str:
324
+ return "cudaStream_t"
325
+
326
+ def aoti_get_stream(self) -> str:
327
+ return "aoti_torch_get_current_cuda_stream"
328
+
329
+ def cpp_kernel_type(self) -> str:
330
+ return "CUfunction"
331
+
332
+ def cpp_device_ptr(self) -> str:
333
+ return "CUdeviceptr"
334
+
335
+ def cpp_scratch(
336
+ self, idx: int, workspace: TritonScratchWorkspace, prefix: Optional[str] = None
337
+ ) -> Optional[tuple[list[str], str]]:
338
+ prefix = f"{prefix}_" if prefix else ""
339
+ var_name = f"{prefix}scratch_{idx}"
340
+ if workspace.size > 0:
341
+ size_array = f"int64_t {var_name}_size[] = {{{workspace.size}}};"
342
+ stride_array = f"int64_t {var_name}_stride[] = {{1}};"
343
+ device_type = "cached_torch_device_type_cuda"
344
+ device_idx = "device_idx_"
345
+
346
+ return (
347
+ [
348
+ f"{size_array}",
349
+ f"{stride_array}",
350
+ f"AtenTensorHandle {var_name}_handle;",
351
+ (
352
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided(1, {var_name}_size, {var_name}_stride, "
353
+ f"{workspace.generate_dtype_str()}, {device_type}, {device_idx}, &{var_name}_handle));"
354
+ ),
355
+ f"RAIIAtenTensorHandle {var_name}_tensor({var_name}_handle);",
356
+ f"CUdeviceptr {var_name} = reinterpret_cast<CUdeviceptr>({var_name}_tensor.data_ptr());",
357
+ ],
358
+ var_name,
359
+ )
360
+ else:
361
+ return [f"CUdeviceptr {var_name} = 0;"], var_name
362
+
363
+
364
+ register_device_op_overrides("cuda", CUDADeviceOpOverrides())
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from .cutedsl_template import CuteDSLTemplate, CuteDSLTemplateCaller
3
+
4
+
5
+ __all__ = [
6
+ "CuteDSLTemplate",
7
+ "CuteDSLTemplateCaller",
8
+ ]
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/_cutedsl_utils.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: disable-error-code=import-not-found
2
+ # pyrefly: ignore [import-error, missing-import]
3
+ import cutlass.cute as cute
4
+
5
+
6
+ @cute.jit # type: ignore[misc]
7
+ def ssa_to_indexable(ssa_value: cute.TensorSSA, dtype: str) -> cute.Numeric:
8
+ """
9
+ Convert SSA form to indexable non-SSA form.
10
+
11
+ Workaround for lack of gather support: SSA values cannot be used directly
12
+ as indices in tensor loads. This converts SSA → fragment → scalar for indexing.
13
+ """
14
+ frag = cute.make_rmem_tensor(1, dtype)
15
+ frag.store(ssa_value)
16
+ return frag[0]
17
+
18
+
19
+ @cute.jit # type: ignore[misc]
20
+ def result_to_ssa(value: cute.Numeric, dtype: str) -> cute.TensorSSA:
21
+ """
22
+ Convert non-SSA result back to SSA form.
23
+
24
+ After performing operations with non-SSA values (like indexed loads),
25
+ convert the result back to SSA form for further computation.
26
+ """
27
+ frag = cute.make_rmem_tensor(1, dtype)
28
+ frag[0] = value
29
+ return frag.load()
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_kernel.py ADDED
@@ -0,0 +1,607 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import dataclasses
4
+ import logging
5
+ import textwrap
6
+ from collections.abc import Callable
7
+ from typing import Any, Optional
8
+
9
+ import sympy
10
+
11
+ import torch
12
+ from torch._inductor import config
13
+ from torch._inductor.codegen.common import (
14
+ CSE,
15
+ CSEVariable,
16
+ IndentedBuffer,
17
+ Kernel,
18
+ ValueRanges,
19
+ )
20
+ from torch._inductor.ir import (
21
+ BaseView,
22
+ Buffer,
23
+ ComputedBuffer,
24
+ ExternKernel,
25
+ InputBuffer,
26
+ MutableBox,
27
+ ReinterpretView,
28
+ )
29
+ from torch._inductor.ops_handler import StoreMode
30
+ from torch._inductor.utils import OrderedSet
31
+ from torch._inductor.virtualized import V
32
+
33
+ from ...utils import sympy_index_symbol
34
+ from .cutedsl_op_overrides import CuteDSLOpOverrides
35
+
36
+
37
+ # TODO setting the 'main' kernel w/ this suffix. We have 3 should probably just auto generate this
38
+ MAIN_SUFFIX = "main"
39
+
40
+
41
+ log = logging.getLogger(__name__)
42
+ kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code")
43
+
44
+
45
+ class CuteDSLKernelWrapper:
46
+ """Wrapper to provide .run() interface for CuteDSL kernels"""
47
+
48
+ def __init__(
49
+ self, kernel_fn: Callable[..., Any], kernel_path: Optional[str] = None
50
+ ):
51
+ self.kernel_fn = kernel_fn
52
+ self.kernel_path = kernel_path
53
+ kernel_code_log.info("CuteDSL kernel path: %s", kernel_path)
54
+
55
+ def run(self, *args, stream=None, **kwargs):
56
+ """
57
+ Execute the CuteDSL kernel.
58
+
59
+ Args:
60
+ *args: Arguments to pass to the kernel function
61
+ stream: CUDA stream to pass to the kernel function
62
+ **kwargs: Additional keyword arguments for the kernel
63
+
64
+ Returns:
65
+ Result of the kernel execution
66
+ """
67
+ return self.kernel_fn(*args, stream=stream, **kwargs)
68
+
69
+
70
+ @dataclasses.dataclass
71
+ class CuteDSLSubgraphInfo:
72
+ """Minimal subgraph info for CuteDSL kernels."""
73
+
74
+ body: IndentedBuffer
75
+ template_mask: Optional[str] = None
76
+ template_out: Optional[str] = None
77
+ cse: Optional[CSE[Any]] = None
78
+
79
+ def __post_init__(self):
80
+ self.only_copy_if_non_none_fields = ("cse",)
81
+
82
+ def to_dict(self):
83
+ return {
84
+ field.name: getattr(self, field.name) for field in dataclasses.fields(self)
85
+ }
86
+
87
+
88
+ class CuteDSLTemplateKernel(Kernel):
89
+ """
90
+ Template kernel implementation for CuteDSL (CUTLASS Python DSL).
91
+ Handles code generation and argument management for CuteDSL CUDA kernels.
92
+ Provides CuteDSL-specific functionality for tensor conversion and kernel configuration.
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ kernel_name: str,
98
+ input_nodes: list[Buffer],
99
+ output_node: Buffer,
100
+ subgraphs: Optional[list[Buffer]] = None,
101
+ ) -> None:
102
+ # Call parent Kernel constructor
103
+ super().__init__()
104
+ self.kernel_name = kernel_name
105
+ self.input_nodes = input_nodes
106
+ self.output_node = output_node
107
+ self.subgraphs = subgraphs
108
+ self.subgraph_bodies: dict[str, CuteDSLSubgraphInfo] = {}
109
+
110
+ # Template attributes
111
+ self.body: IndentedBuffer = IndentedBuffer()
112
+ self.template_mask: Optional[str] = None
113
+ self.template_out: Optional[str] = None
114
+ self.template_indices: Optional[list[Any]] = None
115
+ self.render_hooks: dict[str, Any] = {}
116
+
117
+ # TODO Additional attributes needed by template system
118
+ self.prologue_fused_inputs: OrderedSet[str] = OrderedSet()
119
+ self.prologue_fused_inputs_preserve_zero: OrderedSet[str] = OrderedSet()
120
+ self.named_input_nodes: dict[str, Buffer] = {}
121
+
122
+ # Create named input nodes mapping
123
+ for i, input_node in enumerate(input_nodes):
124
+ node_name = getattr(input_node, "name", f"input_{i}")
125
+ self.named_input_nodes[node_name] = input_node
126
+
127
+ self.cse = CSE(name_prefix="tmp")
128
+
129
+ # Track all tensor buffers added during modification processing
130
+ self.collected_tensor_buffers: list[str] = []
131
+
132
+ def kexpr(self, expr: sympy.Expr) -> str:
133
+ """Convert sympy expression to CuteDSL string representation."""
134
+ return str(expr)
135
+
136
+ def gen_imports(self) -> str:
137
+ """Generate common imports for CuteDSL templates."""
138
+ imports = IndentedBuffer()
139
+ imports.splice(
140
+ """
141
+ import torch
142
+ import cutlass
143
+ import cutlass.cute as cute
144
+ from cutlass.cute.runtime import from_dlpack
145
+ import cuda.bindings.driver as cuda
146
+ from cutlass._mlir.dialects import math as mlir_math
147
+ import operator
148
+ from torch._inductor.codegen.cutedsl._cutedsl_utils import ssa_to_indexable, result_to_ssa
149
+ """
150
+ )
151
+ return imports.getvalue()
152
+
153
+ def gen_defines(self, **kwargs) -> str:
154
+ """Generate CuteDSL parameter definitions from kwargs, similar to Triton's gen_defines."""
155
+ params = IndentedBuffer()
156
+ for name, val in kwargs.items():
157
+ params.writeline(f"{name}: cutlass.Constexpr = {val}")
158
+ return params.getvalue()
159
+
160
+ def render(self, template, **kwargs):
161
+ from torch._inductor.select_algorithm import PartialRender
162
+
163
+ """Render the kernel using the template, returning PartialRender object with hooks."""
164
+ # Available {{}} hooks for jinja rendering
165
+ template_env = {
166
+ "def_kernel": self.def_kernel,
167
+ "gen_defines": lambda: self.gen_defines(**kwargs),
168
+ "get_output": self.get_output,
169
+ "get_tensor_buffers": self.get_tensor_buffers,
170
+ "unpack_buffers": self.unpack_buffers,
171
+ "modification": self.modification,
172
+ "set_cute_hash": self.set_cute_hash,
173
+ }
174
+
175
+ # Render the template with the environment and provided kwargs
176
+ rendered_code = template.render(
177
+ kernel_name=self.kernel_name,
178
+ input_nodes=self.input_nodes,
179
+ output_node=self.output_node,
180
+ **template_env,
181
+ **kwargs,
182
+ )
183
+
184
+ # Always prepend the common imports
185
+ imports = self.gen_imports()
186
+ full_code = imports + rendered_code
187
+
188
+ return PartialRender(full_code, self.render_hooks)
189
+
190
+ @contextlib.contextmanager
191
+ def set_subgraph_body(self, body_name: str):
192
+ """Set the active subgraph body for template processing."""
193
+ assert all(
194
+ hasattr(self, field.name)
195
+ for field in dataclasses.fields(CuteDSLSubgraphInfo)
196
+ )
197
+ old_state = {
198
+ key.name: getattr(self, key.name)
199
+ for key in dataclasses.fields(CuteDSLSubgraphInfo)
200
+ }
201
+
202
+ if body_name not in self.subgraph_bodies:
203
+ self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo(
204
+ body=IndentedBuffer(),
205
+ template_mask=None,
206
+ template_out=None,
207
+ cse=None,
208
+ )
209
+
210
+ subgraph = self.subgraph_bodies[body_name]
211
+ for key, value in subgraph.to_dict().items():
212
+ if value is None and key in getattr(
213
+ subgraph, "only_copy_if_non_none_fields", ()
214
+ ):
215
+ continue
216
+ setattr(self, key, value)
217
+
218
+ try:
219
+ yield
220
+ finally:
221
+ # Save current state back to subgraph
222
+ self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo(
223
+ **{
224
+ key.name: getattr(self, key.name)
225
+ for key in dataclasses.fields(CuteDSLSubgraphInfo)
226
+ }
227
+ )
228
+ # Restore old state
229
+ for key, value in old_state.items():
230
+ setattr(self, key, value)
231
+
232
+ @contextlib.contextmanager
233
+ def create_subgraph_body(self, body_name: str, *, clear_cse: bool = False):
234
+ """Create a new subgraph body for template processing."""
235
+ assert body_name not in self.subgraph_bodies, (
236
+ f"Subgraph body '{body_name}' already exists"
237
+ )
238
+ new_cse = self.cse.clone() if clear_cse else None
239
+ self.subgraph_bodies[body_name] = CuteDSLSubgraphInfo(
240
+ body=IndentedBuffer(),
241
+ template_mask=None,
242
+ template_out=None,
243
+ cse=new_cse,
244
+ )
245
+ with self.set_subgraph_body(body_name):
246
+ yield
247
+
248
+ def _get_reinterpret_view(self, node) -> ReinterpretView | None:
249
+ """Extract or convert to ReinterpretView from a node, handling all views."""
250
+ while isinstance(node, MutableBox):
251
+ node = node.data
252
+ if isinstance(node, BaseView):
253
+ return ExternKernel.convert_to_reinterpret_view(node)
254
+ return None
255
+
256
+ def def_kernel(self, *argnames):
257
+ """Define kernel function signature for CuteDSL templates.
258
+
259
+ When inputs are ReinterpretViews of the same underlying buffer (e.g., Q/K/V
260
+ from fused QKV projection), we generate separate arguments for each input
261
+ even though they share the same underlying buffer.
262
+ """
263
+ renames = IndentedBuffer(initial_indent=1)
264
+
265
+ # Track template input args - each input gets its own arg even if buffers are shared
266
+ self._template_input_args: list[tuple[str, Buffer]] = []
267
+ self._seen_input_args: OrderedSet[str] = OrderedSet()
268
+
269
+ for i, input_node in enumerate(self.input_nodes):
270
+ buf_name = input_node.get_name()
271
+ # Register with args system (may deduplicate, but we track separately)
272
+ self.args.input(buf_name)
273
+
274
+ if i < len(argnames):
275
+ template_name = argnames[i]
276
+ arg_name = f"arg_{template_name}"
277
+ self.args.input_buffers[buf_name] = arg_name
278
+ renames.writeline(f"{template_name} = {arg_name}")
279
+ self._template_input_args.append((arg_name, input_node))
280
+ self._seen_input_args.add(arg_name)
281
+
282
+ if self.output_node:
283
+ self.args.output(self.output_node.get_name())
284
+
285
+ def hook():
286
+ # Generate signature with template input args plus additional args (output, sizevars)
287
+ code = IndentedBuffer()
288
+ code.writeline(f"# Kernel function signature: {self.kernel_name}")
289
+
290
+ # Start with template input args
291
+ params = [arg_name for arg_name, _ in self._template_input_args]
292
+
293
+ # Get additional args from python_argdefs (output, sizevars, etc.)
294
+ arg_defs, _, _, _ = self.args.python_argdefs()
295
+ for arg_def in arg_defs:
296
+ if arg_def.full_name() not in self._seen_input_args:
297
+ params.append(arg_def.full_name())
298
+
299
+ params.append("stream")
300
+ code.writeline(
301
+ f"def {self.kernel_name}_{MAIN_SUFFIX}({', '.join(params)}):"
302
+ )
303
+ with code.indent():
304
+ code.splice(renames.getvalue())
305
+ return code.getvalue()
306
+
307
+ assert "<DEF_KERNEL>" not in self.render_hooks
308
+ # Placeholder-based rendering: hook will be called when template encounters "<DEF_KERNEL>"
309
+ self.render_hooks["<DEF_KERNEL>"] = hook
310
+ return "<DEF_KERNEL>"
311
+
312
+ def get_output(self):
313
+ """Get the actual argument name for the output buffer."""
314
+ assert self.output_node, "Output node must exist to get output buffer name"
315
+ buf_name = self.output_node.get_name()
316
+ output = self.args.output_buffers.get(buf_name, None)
317
+ if output is None:
318
+ raise ValueError(f"Output buffer '{buf_name}' not found in args")
319
+ return output
320
+
321
+ def set_cute_hash(self, func_name: str, suffix: str = ""):
322
+ """Generate code to set __cute_hash__ on a codegen function.
323
+
324
+ This allows hash_callable in flash_attn to skip expensive runtime hashing
325
+ for Inductor-generated functions. The hash is based on the kernel name
326
+ which already contains a unique hash suffix.
327
+ """
328
+ hash_value = f"{self.kernel_name}_{suffix}" if suffix else self.kernel_name
329
+ return f'{func_name}.__cute_hash__ = "{hash_value}"'
330
+
331
+ def get_tensor_buffers(self):
332
+ """Get list of tensor buffer names that were collected during modifications."""
333
+ return self.collected_tensor_buffers
334
+
335
+ def unpack_buffers(self, buffer_list_name: str, *, indent_width: int = 4):
336
+ """Generate buffer unpacking code via render hook."""
337
+
338
+ def hook():
339
+ tensor_buffers = self.get_tensor_buffers()
340
+ if not tensor_buffers:
341
+ return ""
342
+
343
+ # Generate unpacking assignments: in_ptr4 = buffers[0], etc.
344
+ unpacking_lines = []
345
+ for i, buffer_name in enumerate(tensor_buffers):
346
+ # pyrefly: ignore [bad-argument-type]
347
+ unpacking_lines.append(f"{buffer_name} = {buffer_list_name}[{i}]")
348
+
349
+ indent = " " * indent_width
350
+ return "\n" + indent + ("\n" + indent).join(unpacking_lines)
351
+
352
+ # Register the hook and return placeholder
353
+ placeholder = "<UNPACK_BUFFERS>"
354
+ # TODO: I think double invoking is fine for this specific hook
355
+ # assert placeholder not in self.render_hooks
356
+ self.render_hooks[placeholder] = hook
357
+ return placeholder
358
+
359
+ def call_kernel(self, name: str, node=None):
360
+ """Call the kernel function. Simplified version of TritonTemplateKernel.call_kernel.
361
+
362
+ For inputs that are ReinterpretViews (e.g., Q/K/V slices from fused QKV),
363
+ we generate reinterpret_tensor() calls to properly handle the views.
364
+ """
365
+ wrapper = V.graph.wrapper_code
366
+
367
+ # Build call args matching the signature generated in `def_kernel`
368
+ call_args = []
369
+ arg_types = []
370
+
371
+ for _, input_node in self._template_input_args:
372
+ reinterpret_view = self._get_reinterpret_view(input_node)
373
+ if reinterpret_view is not None:
374
+ call_args.append(reinterpret_view.codegen_reference())
375
+ else:
376
+ call_args.append(input_node.get_name())
377
+ arg_types.append(V.graph.get_dtype(input_node.get_name()))
378
+
379
+ # Add additional args from python_argdefs (output, sizevars, ..)
380
+ orig_arg_defs, orig_call_args, _, orig_arg_types = self.args.python_argdefs()
381
+ for arg_def, call_arg, arg_type in zip(
382
+ orig_arg_defs, orig_call_args, orig_arg_types
383
+ ):
384
+ # dedupe
385
+ if arg_def.full_name() not in self._seen_input_args:
386
+ call_args.append(call_arg)
387
+ arg_types.append(arg_type)
388
+
389
+ # TODO this karg really should not be called `triton`
390
+ wrapper.generate_kernel_call(name, call_args, triton=True, arg_types=arg_types)
391
+
392
+ def _get_subgraph(self, subgraph_number: int):
393
+ """Get subgraph by number for modification processing."""
394
+ assert isinstance(subgraph_number, int)
395
+ assert isinstance(self.subgraphs, list)
396
+ assert subgraph_number < len(self.subgraphs), (
397
+ f"Invalid subgraph number provided to create_modification, {subgraph_number} must be < {len(self.subgraphs)}"
398
+ )
399
+ assert self.body.getvalue() == "", (
400
+ "Body should be clear before adding a modification"
401
+ )
402
+ return self.subgraphs[subgraph_number]
403
+
404
+ def modification(
405
+ self,
406
+ subgraph_number: int,
407
+ output_name: Optional[str],
408
+ mask: Optional[str] = None,
409
+ **fixed_inputs,
410
+ ) -> str:
411
+ """Generate CuteDSL code for a subgraph modification."""
412
+ # Find unique name to avoid collisions between multiple modifications of same subgraph
413
+ num = 0
414
+ while f"mod_{subgraph_number}_{num}" in self.subgraph_bodies:
415
+ num += 1
416
+
417
+ with self.create_subgraph_body(f"mod_{subgraph_number}_{num}", clear_cse=True):
418
+ subgraph = self._get_subgraph(subgraph_number)
419
+ modification_handler = ModificationWrapperCuteDSL(
420
+ self, subgraph_number, fixed_inputs, mask
421
+ )
422
+ with V.set_kernel_handler(self), V.set_ops_handler(modification_handler):
423
+ assert isinstance(subgraph, (ComputedBuffer, list)), (
424
+ f"Expected ComputedBuffer or List[ComputedBuffer], got {type(subgraph)}"
425
+ )
426
+
427
+ if isinstance(subgraph, list):
428
+ raise NotImplementedError(
429
+ "Scatter graphs are not supported for CuteDSL"
430
+ )
431
+
432
+ if isinstance(subgraph.data, InputBuffer):
433
+ # grad_score_mod can be InputBuffers
434
+ out = subgraph.data.make_loader()(())
435
+ else:
436
+ # Inline a pointwise lowering into the template
437
+ out = subgraph.data.inner_fn(())
438
+
439
+ if output_name is not None:
440
+ assert out is not None, (
441
+ f"Expected computation result for named output {output_name}"
442
+ )
443
+ self.body.writeline(f"{output_name} = {out.value}")
444
+ else:
445
+ # Side-effect only: no output assignment (currently only for scatter operations)
446
+ raise NotImplementedError(
447
+ "Side-effect only modifications not yet supported for CuteDSL"
448
+ )
449
+
450
+ # Add Buffers that were added during modification
451
+ self.collected_tensor_buffers.extend(modification_handler.tensor_buffers)
452
+
453
+ return self.body.getvalue()
454
+
455
+
456
+ class ModificationWrapperCuteDSL(V.WrapperHandler): # type: ignore[name-defined]
457
+ """
458
+ Wrapper handler that enables CuteDSL code generation during subgraph modifications.
459
+
460
+ This class sits between the PyTorch IR and CuteDSL code generation, providing:
461
+ 1. Operation substitution: converts PyTorch ops to CuteDSL equivalents via CuteDSLOpOverrides
462
+ 2. Placeholder handling: resolves fixed_inputs during template processing
463
+ 3. Limited operation support: currently restricted to pointwise operations
464
+
465
+ """
466
+
467
+ def __init__(
468
+ self,
469
+ kernel,
470
+ subgraph_number: int,
471
+ fixed_inputs: dict[str, Any],
472
+ mask: Optional[str],
473
+ ):
474
+ cutedsl_ops = CuteDSLOpOverrides()
475
+ super().__init__(cutedsl_ops)
476
+ self.name = f"CuteDSLPlaceholderSubstitution_{subgraph_number}"
477
+ self.kernel = kernel
478
+ self.fixed_inputs = fixed_inputs
479
+ self.mask = mask
480
+ # Track tensor buffers that get added during modification processing
481
+ self.tensor_buffers: list[str] = []
482
+
483
+ def _get_input_dtype(self, name: str) -> torch.dtype:
484
+ """Get the dtype for an input from the kernel's named_input_nodes."""
485
+ if name in self.kernel.named_input_nodes:
486
+ return self.kernel.named_input_nodes[name].dtype
487
+ # TODO: Fallback for common dimension names - should be replaced with proper dtype tracking
488
+ return torch.float32 if name not in ("b", "h", "m", "n") else torch.int32
489
+
490
+ def load(self, name: str, index: sympy.Expr):
491
+ """Handle loading from tensor or fixed(template args) input for CuteDSL."""
492
+ from torch._inductor.kernel.flex.flex_flash_attention import HierarchicalIndex
493
+
494
+ if name not in self.fixed_inputs:
495
+ var = self._add_kernel_input(name)
496
+ buffer = V.graph.get_buffer(name)
497
+ var_dtype = buffer.dtype
498
+
499
+ cute_dtype = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(
500
+ var_dtype, "cutlass.Float32"
501
+ )
502
+ idx_vars = [
503
+ self._emit_scalar_fragment(
504
+ self.kernel.kexpr(self.kernel.rename_indexing(dim_index)),
505
+ "cutlass.Int32",
506
+ torch.int32,
507
+ )
508
+ for dim_index in (
509
+ index.args if isinstance(index, HierarchicalIndex) else (index,)
510
+ )
511
+ ]
512
+
513
+ val_frag = self.kernel.cse.newvar(dtype=var_dtype)
514
+ self.kernel.body.writeline(
515
+ f"{val_frag} = cute.make_rmem_tensor(1, {cute_dtype})"
516
+ )
517
+ self.kernel.body.writeline(
518
+ f"{val_frag}[0] = ({var}[{', '.join(idx_vars)}])"
519
+ )
520
+
521
+ final_expr = f"{val_frag}.load()"
522
+
523
+ if (
524
+ var_dtype in (torch.float16, torch.bfloat16)
525
+ and config.triton.codegen_upcast_to_fp32
526
+ ):
527
+ final_expr = f"({final_expr}).to(cutlass.Float32)"
528
+ var_dtype = torch.float32
529
+
530
+ out = self.kernel.cse.generate(
531
+ self.kernel.body,
532
+ final_expr,
533
+ dtype=var_dtype,
534
+ bounds=ValueRanges.unknown(),
535
+ )
536
+ return out
537
+
538
+ value = self.fixed_inputs[name]
539
+ dtype = self._get_input_dtype(name)
540
+
541
+ return self.kernel.cse.generate(
542
+ self.kernel.body, value, bounds=ValueRanges.unknown(), dtype=dtype
543
+ )
544
+
545
+ def _emit_scalar_fragment(
546
+ self, expr_str: str, cute_dtype: str, torch_dtype: torch.dtype
547
+ ) -> str:
548
+ """
549
+ Convert SSA expression to indexable scalar for tensor loads.
550
+
551
+ Workaround for lack of gather support: SSA values cannot be used directly
552
+ as indices. This generates code to convert SSA → indexable scalar.
553
+ """
554
+ result = self.kernel.cse.newvar(dtype=torch_dtype)
555
+ self.kernel.body.writeline(
556
+ f"{result} = ssa_to_indexable({expr_str}, {cute_dtype})"
557
+ )
558
+ return str(result)
559
+
560
+ def indirect_indexing(self, index_var: str, size, check, wrap_neg=True):
561
+ """Convert index variable to symbolic form."""
562
+ return sympy_index_symbol(str(index_var))
563
+
564
+ # pyrefly: ignore [bad-override]
565
+ def store(
566
+ self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None
567
+ ) -> str:
568
+ raise NotImplementedError(
569
+ "Store operations not supported - CuteDSL limited to read-only operations"
570
+ )
571
+
572
+ def _add_kernel_input(self, name: str):
573
+ """Add name as input to kernel and return input ref."""
574
+ # Get the remapped name that will be used in the kernel
575
+ remapped_name = self.kernel.args.input(name)
576
+ # Track the remapped name for later collection
577
+ if remapped_name not in self.tensor_buffers:
578
+ self.tensor_buffers.append(remapped_name)
579
+ return remapped_name
580
+
581
+ def _process_indexing(self, index):
582
+ """Process and rename indexing, adding symbols as kernel inputs."""
583
+ renamed = self.kernel.rename_indexing(index)
584
+ return self.kernel.kexpr(renamed)
585
+
586
+ def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
587
+ try:
588
+ return getattr(self._inner, name)(*args, **kwargs)
589
+ except NotImplementedError as e:
590
+ bar = "=" * 80
591
+ msg = textwrap.dedent(f"""
592
+ {bar}
593
+ UNSUPPORTED CUTEDSL OPERATION: '{name}'
594
+ {bar}
595
+ This operation is not yet implemented in Inductor.
596
+
597
+ Please open an issue at: https://github.com/pytorch/pytorch/issues
598
+ with the following information:
599
+
600
+ Operation: {name}
601
+ Args: {args!r}
602
+ Kwargs: {kwargs!r}
603
+
604
+ Title your issue: [CuteDSL] Missing operation: {name}
605
+ {bar}
606
+ """).strip()
607
+ raise NotImplementedError(msg) from e
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ CuteDSL-specific operation overrides for pointwise operations.
4
+
5
+ This module provides CuteDSL implementations of common operations used in
6
+ template kernels, particularly for flex attention modifications.
7
+ """
8
+
9
+ import math
10
+ from typing import Optional, Union
11
+
12
+ import sympy
13
+
14
+ import torch
15
+ from torch._inductor.codegen.common import CSEVariable, OpOverrides
16
+ from torch._inductor.virtualized import OpsValue, V
17
+ from torch.utils._sympy.value_ranges import ValueRanges
18
+
19
+
20
+ CuteDSLArg = Union[CSEVariable, str]
21
+
22
+
23
+ def upcast_compute_type(dtype: torch.dtype) -> torch.dtype:
24
+ """Maybe upcast [b]float16 to float32"""
25
+ if dtype in (torch.float16, torch.bfloat16):
26
+ return torch.float32
27
+ return dtype
28
+
29
+
30
+ class CuteDSLOpOverrides(OpOverrides):
31
+ """
32
+ CuteDSL-specific operation overrides that generate code using CuteDSL syntax.
33
+
34
+ CuteDSL TensorSSA objects have built-in operator overloads (__add__, __mul__, etc.)
35
+ and math functions (cute.math.exp, cute.math.sqrt, etc.)
36
+ """
37
+
38
+ TORCH_TO_CUTE_DTYPE = {
39
+ torch.float16: "cutlass.Float16",
40
+ torch.bfloat16: "cutlass.BFloat16",
41
+ torch.float32: "cutlass.Float32",
42
+ torch.float64: "cutlass.Float64",
43
+ torch.int8: "cutlass.Int8",
44
+ torch.int16: "cutlass.Int16",
45
+ torch.int32: "cutlass.Int32",
46
+ torch.int64: "cutlass.Int64",
47
+ torch.bool: "cutlass.Boolean",
48
+ torch.float8_e4m3fn: "cutlass.Float8E4M3FN",
49
+ torch.float8_e5m2: "cutlass.Float8E5M2",
50
+ }
51
+
52
+ # Math constants
53
+ LOG2_E = 1.4426950408889634 # 1/ln(2) for converting natural exp to base-2 exp
54
+
55
+ @staticmethod
56
+ def _get_cse_var(arg: CuteDSLArg) -> Optional[CSEVariable]:
57
+ """Extract CSEVariable from arg if it's a tensor (either direct or wrapped in OpsValue)."""
58
+ if isinstance(arg, CSEVariable):
59
+ return arg
60
+ if isinstance(arg, OpsValue) and isinstance(arg.value, CSEVariable):
61
+ return arg.value
62
+ return None
63
+
64
+ @staticmethod
65
+ def _ensure_tensor_ssa(arg: CuteDSLArg, template_tensor: CuteDSLArg) -> str:
66
+ """
67
+ Convert scalar arguments to TensorSSA using cute.full_like if needed.
68
+
69
+ Args:
70
+ arg: The argument to check (CSEVariable for tensors, str for scalars, or OpsValue wrapper)
71
+ template_tensor: A tensor argument to use as template for full_like
72
+
73
+ Returns:
74
+ String representation suitable for CuteDSL operations
75
+ """
76
+ if isinstance(arg, CSEVariable):
77
+ return str(arg)
78
+
79
+ if isinstance(arg, OpsValue) and isinstance(arg.value, CSEVariable):
80
+ return str(arg.value)
81
+
82
+ if isinstance(template_tensor, CSEVariable):
83
+ return f"cute.full_like({template_tensor}, {arg})"
84
+
85
+ return str(arg)
86
+
87
+ @staticmethod
88
+ def _extract_dtype_and_bounds(
89
+ *args: CuteDSLArg,
90
+ ) -> tuple[Optional[torch.dtype], ValueRanges[sympy.Expr]]:
91
+ """Extract dtype and bounds from CSEVariable arguments (including OpsValue wrappers)."""
92
+ for arg in args:
93
+ cse_var = CuteDSLOpOverrides._get_cse_var(arg)
94
+ if cse_var is not None:
95
+ return cse_var.dtype, cse_var.bounds
96
+ return None, ValueRanges.unknown()
97
+
98
+ @staticmethod
99
+ def _apply_binary_op(a: CuteDSLArg, b: CuteDSLArg, op_format: str) -> CuteDSLArg:
100
+ """
101
+ Apply a binary operation with automatic scalar-to-tensor conversion.
102
+
103
+ CuteDSL requires both operands to be TensorSSA objects for tensor operations.
104
+ This helper automatically converts scalar arguments to TensorSSA using
105
+ cute.full_like when at least one argument is a tensor (CSEVariable or OpsValue).
106
+
107
+ Args:
108
+ a: First operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper)
109
+ b: Second operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper)
110
+ op_format: Format string with {a} and {b} placeholders for the operation
111
+
112
+ Returns:
113
+ CSEVariable if at least one operand is a tensor, otherwise string
114
+ """
115
+ # Check for CSEVariable directly or wrapped in OpsValue
116
+ tensor_arg = CuteDSLOpOverrides._get_cse_var(
117
+ a
118
+ ) or CuteDSLOpOverrides._get_cse_var(b)
119
+ if tensor_arg is not None:
120
+ a_ssa = CuteDSLOpOverrides._ensure_tensor_ssa(a, tensor_arg)
121
+ b_ssa = CuteDSLOpOverrides._ensure_tensor_ssa(b, tensor_arg)
122
+ result_expr = op_format.format(a=a_ssa, b=b_ssa)
123
+
124
+ dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(a, b)
125
+
126
+ # Create and return CSEVariable using CSE generation for caching
127
+ return V.kernel.cse.generate(
128
+ V.kernel.body, result_expr, bounds=bounds, dtype=dtype
129
+ )
130
+
131
+ return op_format.format(a=a, b=b)
132
+
133
+ @staticmethod
134
+ def _apply_unary_op(x: CuteDSLArg, op_format: str) -> CuteDSLArg:
135
+ """
136
+ Apply a unary operation, returning CSEVariable if input is a tensor.
137
+
138
+ Args:
139
+ x: Input operand (CSEVariable for tensors, str for scalars, or OpsValue wrapper)
140
+ op_format: Format string with {x} placeholder for the operation
141
+
142
+ Returns:
143
+ CSEVariable if input is a tensor, otherwise string
144
+ """
145
+ cse_var = CuteDSLOpOverrides._get_cse_var(x)
146
+ if cse_var is not None:
147
+ result_expr = op_format.format(x=str(cse_var))
148
+ return V.kernel.cse.generate(
149
+ V.kernel.body, result_expr, bounds=cse_var.bounds, dtype=cse_var.dtype
150
+ )
151
+
152
+ return op_format.format(x=x)
153
+
154
+ @staticmethod
155
+ def constant(value: Union[bool, float, int], dtype: torch.dtype) -> str:
156
+ """Generate CuteDSL constant representation."""
157
+ if value == float("-inf"):
158
+ return "float('-inf')"
159
+ elif value == float("inf"):
160
+ return "float('inf')"
161
+ elif math.isnan(value):
162
+ return "float('nan')"
163
+ return repr(value)
164
+
165
+ @staticmethod
166
+ def add(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
167
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} + {b})")
168
+
169
+ @staticmethod
170
+ def mul(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
171
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} * {b})")
172
+
173
+ @staticmethod
174
+ def sub(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
175
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} - {b})")
176
+
177
+ @staticmethod
178
+ def truediv(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
179
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} / {b})")
180
+
181
+ @staticmethod
182
+ def floordiv(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
183
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} // {b})")
184
+
185
+ @staticmethod
186
+ def mod(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
187
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} % {b})")
188
+
189
+ @staticmethod
190
+ def remainder(a, b):
191
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} % {b})")
192
+
193
+ @staticmethod
194
+ def exp(x: CuteDSLArg) -> CuteDSLArg:
195
+ """Exponential using CuteDSL cute.math.exp function."""
196
+ return CuteDSLOpOverrides._apply_unary_op(
197
+ x, f"cute.math.exp2({{x}} * {CuteDSLOpOverrides.LOG2_E})"
198
+ )
199
+
200
+ @staticmethod
201
+ def sqrt(x: CuteDSLArg) -> CuteDSLArg:
202
+ """Square root using CuteDSL cute.math.sqrt function."""
203
+ return CuteDSLOpOverrides._apply_unary_op(x, "cute.math.sqrt({x})")
204
+
205
+ @staticmethod
206
+ def log(x: CuteDSLArg) -> CuteDSLArg:
207
+ """Natural logarithm using CuteDSL cute.math.log function."""
208
+ return CuteDSLOpOverrides._apply_unary_op(x, "cute.math.log({x})")
209
+
210
+ @staticmethod
211
+ def cos(x: CuteDSLArg) -> CuteDSLArg:
212
+ """Cosine using CuteDSL cute.math.cos function."""
213
+ return CuteDSLOpOverrides._apply_unary_op(x, "cute.math.cos({x})")
214
+
215
+ @staticmethod
216
+ def sin(x: CuteDSLArg) -> CuteDSLArg:
217
+ """Sine using CuteDSL cute.math.sin function."""
218
+ return CuteDSLOpOverrides._apply_unary_op(x, "cute.math.sin({x})")
219
+
220
+ @staticmethod
221
+ def erf(x: CuteDSLArg) -> CuteDSLArg:
222
+ """Error function using CuteDSL cute.math.erf function."""
223
+ return CuteDSLOpOverrides._apply_unary_op(x, "cute.math.erf({x})")
224
+
225
+ @staticmethod
226
+ def maximum(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
227
+ raise NotImplementedError("TODO: maximum is not supported yet for TensorSSA")
228
+
229
+ @staticmethod
230
+ def minimum(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
231
+ raise NotImplementedError("TODO: minimum is not supported yet for TensorSSA")
232
+
233
+ @staticmethod
234
+ def where(
235
+ condition: CuteDSLArg,
236
+ a: CuteDSLArg,
237
+ b: CuteDSLArg,
238
+ ) -> CuteDSLArg:
239
+ """Conditional selection - handles CSEVariable, OpsValue, and string inputs."""
240
+ # Find a tensor argument to use as template for full_like
241
+ # Priority: use 'a' if it's a tensor, else use 'b', else condition
242
+ tensor_arg = (
243
+ CuteDSLOpOverrides._get_cse_var(a)
244
+ or CuteDSLOpOverrides._get_cse_var(b)
245
+ or CuteDSLOpOverrides._get_cse_var(condition)
246
+ )
247
+
248
+ if tensor_arg is not None:
249
+ a_ssa = CuteDSLOpOverrides._ensure_tensor_ssa(a, tensor_arg)
250
+ b_ssa = CuteDSLOpOverrides._ensure_tensor_ssa(b, tensor_arg)
251
+ cond_ssa = CuteDSLOpOverrides._ensure_tensor_ssa(condition, tensor_arg)
252
+ result_expr = f"cute.where({cond_ssa}, {a_ssa}, {b_ssa})"
253
+
254
+ dtype, bounds = CuteDSLOpOverrides._extract_dtype_and_bounds(
255
+ a, b, condition
256
+ )
257
+
258
+ return V.kernel.cse.generate(
259
+ V.kernel.body, result_expr, bounds=bounds, dtype=dtype
260
+ )
261
+
262
+ return f"cute.where({condition}, {a}, {b})"
263
+
264
+ @staticmethod
265
+ def pow(a: CuteDSLArg, b: CuteDSLArg):
266
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "({a} ** {b})")
267
+
268
+ @staticmethod
269
+ def abs(x: CuteDSLArg) -> CuteDSLArg:
270
+ """Absolute value using CuteDSL cute.math.abs function."""
271
+ if isinstance(x, CSEVariable):
272
+ x_dtype = x.dtype
273
+ elif isinstance(x, OpsValue) and isinstance(x.value, CSEVariable):
274
+ x_dtype = x.value.dtype
275
+ else:
276
+ x_dtype = torch.float32
277
+
278
+ abs_op = (
279
+ "mlir_math.absf"
280
+ if x_dtype in (torch.float16, torch.bfloat16, torch.float32)
281
+ else "mlir_math.absi"
282
+ )
283
+ return CuteDSLOpOverrides._apply_unary_op(
284
+ x,
285
+ f"cute.TensorSSA({abs_op}({{x}}), {{x}}.shape, {{x}}.dtype)",
286
+ )
287
+
288
+ @staticmethod
289
+ def neg(x: CuteDSLArg) -> CuteDSLArg:
290
+ """Negation using CuteDSL TensorSSA __neg__ operator."""
291
+ # TODO: See https://github.com/NVIDIA/cutlass/issues/2584
292
+ return CuteDSLOpOverrides._apply_unary_op(
293
+ x, "cute.TensorSSA(-{x}, {x}.shape, {x}.dtype)"
294
+ )
295
+
296
+ @staticmethod
297
+ def to_dtype(
298
+ x: CuteDSLArg, dtype: torch.dtype, src_dtype=None, use_compute_types=True
299
+ ) -> CuteDSLArg:
300
+ """Type conversion using CuteDSL TensorSSA.to(Type[Numeric]).
301
+
302
+ Maps torch dtypes to cutlass.cute.typing numeric types and emits
303
+ `{x}.to(cute.typing.<Type>)`.
304
+
305
+ Raises NotImplementedError for unsigned integer and unsupported dtypes.
306
+ """
307
+ # Always convert up from bf16 and fp16 TODO on configuring
308
+ dtype = upcast_compute_type(dtype)
309
+
310
+ cute_type = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(dtype)
311
+ if cute_type is None:
312
+ raise NotImplementedError(
313
+ f"CuteDSL dtype cast not implemented for torch dtype: {dtype}"
314
+ )
315
+
316
+ if isinstance(x, CSEVariable):
317
+ result_expr = f"{str(x)}.to({cute_type})"
318
+ return V.kernel.cse.generate(
319
+ V.kernel.body, result_expr, bounds=x.bounds, dtype=dtype
320
+ )
321
+
322
+ return f"{x}.to({cute_type})"
323
+
324
+ @staticmethod
325
+ def tanh(x0: CuteDSLArg) -> CuteDSLArg:
326
+ """Hyperbolic tangent using CuteDSL cute.math.tanh function."""
327
+ return CuteDSLOpOverrides._apply_unary_op(x0, "cute.math.tanh({x})")
328
+
329
+ # Logical operations
330
+ @staticmethod
331
+ def logical_and(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg:
332
+ return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} & {b})")
333
+
334
+ @staticmethod
335
+ def logical_or(x0: CuteDSLArg, x1: CuteDSLArg) -> CuteDSLArg:
336
+ return CuteDSLOpOverrides._apply_binary_op(x0, x1, "({a} | {b})")
337
+
338
+ # Bitwise operations (override parent class to properly CSE)
339
+ @staticmethod
340
+ # pyrefly: ignore [bad-override]
341
+ def bitwise_and(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg:
342
+ return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} & {b})")
343
+
344
+ @staticmethod
345
+ # pyrefly: ignore [bad-override]
346
+ def bitwise_or(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg:
347
+ return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} | {b})")
348
+
349
+ @staticmethod
350
+ # pyrefly: ignore [bad-override]
351
+ def bitwise_xor(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg:
352
+ return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} ^ {b})")
353
+
354
+ @staticmethod
355
+ # pyrefly: ignore [bad-override]
356
+ def bitwise_not(x: CuteDSLArg) -> CuteDSLArg:
357
+ return CuteDSLOpOverrides._apply_unary_op(x, "(~{x})")
358
+
359
+ @staticmethod
360
+ # pyrefly: ignore [bad-override]
361
+ def bitwise_left_shift(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg:
362
+ return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} << {b})")
363
+
364
+ @staticmethod
365
+ # pyrefly: ignore [bad-override]
366
+ def bitwise_right_shift(x: CuteDSLArg, y: CuteDSLArg) -> CuteDSLArg:
367
+ return CuteDSLOpOverrides._apply_binary_op(x, y, "({a} >> {b})")
368
+
369
+ @staticmethod
370
+ def logical_not(a):
371
+ """Logical NOT."""
372
+ return CuteDSLOpOverrides._apply_unary_op(a, "({x} == 0)")
373
+
374
+ # Comparison operations
375
+ @staticmethod
376
+ def eq(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
377
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.eq({a}, {b})")
378
+
379
+ @staticmethod
380
+ def ne(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
381
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.ne({a}, {b})")
382
+
383
+ @staticmethod
384
+ def lt(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
385
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.lt({a}, {b})")
386
+
387
+ @staticmethod
388
+ def le(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
389
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.le({a}, {b})")
390
+
391
+ @staticmethod
392
+ def gt(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
393
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.gt({a}, {b})")
394
+
395
+ @staticmethod
396
+ def ge(a: CuteDSLArg, b: CuteDSLArg) -> CuteDSLArg:
397
+ return CuteDSLOpOverrides._apply_binary_op(a, b, "operator.ge({a}, {b})")
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_scheduling.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.utils import Placeholder
8
+ from torch.utils._ordered_set import OrderedSet
9
+
10
+ from ... import config
11
+ from ...codecache import code_hash, get_path
12
+ from ...ir import CuteDSLTemplateBuffer
13
+ from ...scheduler import (
14
+ BaseSchedulerNode,
15
+ BaseScheduling,
16
+ FusedSchedulerNode,
17
+ SchedulerNode,
18
+ )
19
+ from ...select_algorithm import PartialRender
20
+ from ...utils import get_fused_kernel_name, get_kernel_metadata
21
+ from ...virtualized import V
22
+ from ..common import BackendFeature, IndentedBuffer
23
+
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+
28
+ class CuteDSLScheduling(BaseScheduling):
29
+ """
30
+ Scheduling implementation for CuteDSL (CUTLASS Python DSL) kernels.
31
+ This class is intended to be used in combination with other schedulers,
32
+ and delegated to by CUDACombinedScheduling.
33
+ """
34
+
35
+ @classmethod
36
+ def get_backend_features(cls, device) -> OrderedSet[BackendFeature]:
37
+ return OrderedSet()
38
+
39
+ @staticmethod
40
+ def is_cutedsl_template(node: BaseSchedulerNode) -> bool:
41
+ """Check if a node is a CuteDSL template."""
42
+ return isinstance(node, SchedulerNode) and isinstance(
43
+ node.node, CuteDSLTemplateBuffer
44
+ )
45
+
46
+ def is_cutedsl_fused_template(self, node: BaseSchedulerNode) -> bool:
47
+ """Check if a node is a fused CuteDSL template."""
48
+ return isinstance(node, FusedSchedulerNode) and self.is_cutedsl_template(node)
49
+
50
+ def can_fuse_vertical(
51
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
52
+ ) -> bool:
53
+ """
54
+ TODO CuteDSL doesn't support vertical fusion yet.
55
+ This could be extended in the future for epilogue fusion.
56
+ """
57
+ return False
58
+
59
+ def define_kernel(self, src_code_str: str, node_schedule) -> str:
60
+ """Produce the kernel string
61
+ Args:
62
+ src_code_str: The finalized kernel code string
63
+ node_schedule: List of nodes in the schedule
64
+
65
+ Note:
66
+ This is a little weird since async_compile.cutedsl() has to write the string to
67
+ a file in order to cute compile it. Feels bad to have two...
68
+ """
69
+ wrapper = V.graph.wrapper_code
70
+
71
+ # Use the string as the key for caching
72
+ if src_code_str in wrapper.src_to_kernel:
73
+ kernel_name = wrapper.src_to_kernel[src_code_str]
74
+ else:
75
+ fused_name = (
76
+ get_fused_kernel_name(node_schedule, config.triton.descriptive_names)
77
+ if config.triton.descriptive_names
78
+ else ""
79
+ )
80
+
81
+ kernel_hash = hashlib.sha256(src_code_str.encode("utf-8")).hexdigest()[:8]
82
+ if fused_name == "fused":
83
+ kernel_name = f"cutedsl_{kernel_hash}"
84
+ else:
85
+ kernel_name = f"cutedsl_{fused_name}_{kernel_hash}"
86
+ wrapper.src_to_kernel[src_code_str] = kernel_name
87
+ src_code_str = src_code_str.replace(
88
+ str(Placeholder.KERNEL_NAME), kernel_name
89
+ )
90
+
91
+ _, _, kernel_path = get_path(code_hash(src_code_str), "py")
92
+
93
+ compile_wrapper = IndentedBuffer()
94
+ compile_wrapper.writeline(f"async_compile.cutedsl({kernel_name!r}, r'''")
95
+ compile_wrapper.splice(src_code_str, strip=True)
96
+ compile_wrapper.writeline("''')")
97
+
98
+ metadata_comment = f"# kernel path: {kernel_path}"
99
+ origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
100
+ metadata_comment += "\n" + origins + "\n" + detailed_origins
101
+ wrapper.define_kernel(
102
+ kernel_name, compile_wrapper.getvalue(), metadata_comment
103
+ )
104
+ return kernel_name
105
+
106
+ def codegen_template(
107
+ self,
108
+ template_node: BaseSchedulerNode,
109
+ epilogue_nodes: Sequence[BaseSchedulerNode],
110
+ prologue_nodes: Sequence[BaseSchedulerNode],
111
+ ):
112
+ """
113
+ Codegen a CuteDSL template. Currently doesn't support fusion.
114
+ """
115
+ assert self.is_cutedsl_template(template_node), (
116
+ "Template node passed to CuteDSLScheduling.codegen_template must be a "
117
+ "SchedulerNode that wraps a CuteDSLTemplateBuffer"
118
+ )
119
+ # TODO remove when supported
120
+ assert not epilogue_nodes, "CuteDSL doesn't support epilogue fusion yet"
121
+ assert not prologue_nodes, "CuteDSL doesn't support prologue fusion yet"
122
+
123
+ template_node = cast(SchedulerNode, template_node)
124
+ ctb: CuteDSLTemplateBuffer = cast(CuteDSLTemplateBuffer, template_node.node)
125
+
126
+ kernel, render = ctb.make_kernel_render(ctb) # type: ignore[misc]
127
+ template_node.mark_run()
128
+ src_code = render()
129
+ # Finalize PartialRender if needed
130
+ if isinstance(src_code, PartialRender):
131
+ src_code_str = src_code.finalize_all()
132
+ else:
133
+ src_code_str = src_code
134
+
135
+ with V.set_kernel_handler(kernel):
136
+ node_schedule = [template_node]
137
+ kernel_name = self.define_kernel(src_code_str, node_schedule)
138
+ self.codegen_comment(node_schedule, kernel_name)
139
+ kernel.call_kernel(kernel_name, ctb)
140
+ V.graph.removed_buffers |= kernel.removed_buffers
141
+ self.free_buffers_in_scheduler()
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutedsl/cutedsl_template.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import itertools
4
+ from collections.abc import Iterable
5
+ from typing import Any, Optional
6
+ from unittest.mock import patch
7
+
8
+ from torch._inductor.utils import Placeholder
9
+ from torch._inductor.virtualized import V
10
+ from torch._logging import getArtifactLogger
11
+
12
+ from ...autotune_process import CuteDSLBenchmarkRequest, TensorMeta
13
+ from ...ir import Buffer, ChoiceCaller, CuteDSLTemplateBuffer, IRNode, Layout, TensorBox
14
+ from ..common import KernelTemplate
15
+ from .cutedsl_kernel import CuteDSLTemplateKernel
16
+
17
+
18
+ log = getArtifactLogger(__name__, "output_code")
19
+
20
+
21
+ class CuteDSLTemplate(KernelTemplate):
22
+ """Template for generating CuteDSL (CUTLASS Python DSL) kernels."""
23
+
24
+ kernel_type: type[Any] = CuteDSLTemplateKernel
25
+ index_counter = itertools.count()
26
+ all_templates: dict[str, "CuteDSLTemplate"] = {}
27
+
28
+ def __init__(
29
+ self,
30
+ name: str,
31
+ source: str,
32
+ subgraph_fn: Optional[Any] = None,
33
+ mask_fn: Optional[Any] = None,
34
+ ) -> None:
35
+ super().__init__(name)
36
+ self.source = source
37
+ self.subgraph_fn = subgraph_fn
38
+ self.mask_fn = mask_fn
39
+ self.template = CuteDSLTemplate._template_from_string(source)
40
+ assert name not in self.all_templates, f"duplicate template name, {name}"
41
+ CuteDSLTemplate.all_templates[name] = self
42
+
43
+ @staticmethod
44
+ @functools.lru_cache(None)
45
+ # pyrefly: ignore [bad-override]
46
+ def _template_from_string(source: str) -> Any:
47
+ return KernelTemplate._template_from_string(source)
48
+
49
+ def maybe_append_choice(
50
+ self, choices: list[Any], **kwargs: Any
51
+ ) -> Optional[NotImplementedError]:
52
+ """
53
+ Maybe generates a new ChoiceCaller and appends it into existing choices.
54
+ Returns None if success, otherwise returns the error.
55
+ """
56
+ try:
57
+ choices.append(self.generate(**kwargs))
58
+ return None
59
+ except NotImplementedError as e:
60
+ log.debug("CuteDSL template choice generation failed: %s", e) # noqa: G200
61
+ return e
62
+ except Exception as e:
63
+ log.debug("CuteDSL template choice generation error: %s", e) # noqa: G200
64
+ return NotImplementedError(f"CuteDSL template failed: {e}")
65
+
66
+ def generate(self, **kwargs: Any) -> ChoiceCaller:
67
+ """Generate the CuteDSL kernel caller."""
68
+ input_nodes = kwargs.pop("input_nodes")
69
+ layout = kwargs.pop("layout")
70
+ mutated_inputs = kwargs.pop("mutated_inputs", None)
71
+ subgraphs = kwargs.pop("subgraphs", None)
72
+
73
+ kernel_name = f"cutedsl_{self.name}_{next(self.index_counter)}"
74
+
75
+ if self.template is None:
76
+ raise RuntimeError("Template compilation failed (Jinja2 required)")
77
+
78
+ self.output_node: Buffer = Buffer(name="buf_out", layout=layout)
79
+ # Patch V.graph.get_dtype to handle the fake buf_out buffer
80
+ with patch.object(
81
+ V.graph, "get_dtype", KernelTemplate._fake_get_dtype(self.output_node)
82
+ ):
83
+ kernel = self.kernel_type(
84
+ kernel_name=kernel_name,
85
+ input_nodes=input_nodes,
86
+ output_node=self.output_node,
87
+ subgraphs=subgraphs,
88
+ )
89
+ code = kernel.render(self.template, **kwargs)
90
+
91
+ log.debug("Generated CuteDSL Code:\n%s", code)
92
+
93
+ bmreq = CuteDSLBenchmarkRequest(
94
+ kernel_name=kernel_name,
95
+ input_tensor_meta=TensorMeta.from_irnodes(input_nodes),
96
+ output_tensor_meta=TensorMeta.from_irnodes(self.output_node),
97
+ extra_args=tuple(),
98
+ source_code=code,
99
+ )
100
+
101
+ def make_kernel_render(out_node, hint_override: Optional[int] = None):
102
+ """
103
+ Factory function that creates a kernel renderer for the final output.
104
+
105
+ This closure captures the current template and parameters, but allows
106
+ the output node to be specified later. This is used during the final
107
+ kernel selection phase when the actual output buffer is available.
108
+ """
109
+ render_kernel = self.kernel_type(
110
+ kernel_name=str(Placeholder.KERNEL_NAME),
111
+ input_nodes=input_nodes,
112
+ output_node=out_node,
113
+ subgraphs=subgraphs,
114
+ )
115
+
116
+ def render():
117
+ return render_kernel.render(self.template, **kwargs)
118
+
119
+ return render_kernel, render
120
+
121
+ return CuteDSLTemplateCaller(
122
+ name=kernel_name,
123
+ input_nodes=input_nodes,
124
+ layout=layout,
125
+ make_kernel_render=make_kernel_render,
126
+ bmreq=bmreq,
127
+ template=self,
128
+ mutated_inputs=mutated_inputs,
129
+ )
130
+
131
+
132
+ class CuteDSLTemplateCaller(ChoiceCaller):
133
+ """Caller for CuteDSL templates that integrates with the autotuning system."""
134
+
135
+ def __init__(
136
+ self,
137
+ name: str,
138
+ input_nodes: list[Buffer],
139
+ layout: Layout,
140
+ make_kernel_render: Any,
141
+ bmreq: CuteDSLBenchmarkRequest,
142
+ template: "CuteDSLTemplate",
143
+ mutated_inputs: Optional[Iterable[IRNode]] = None,
144
+ ):
145
+ super().__init__(
146
+ name=name,
147
+ input_nodes=input_nodes,
148
+ layout=layout,
149
+ description=f"CuteDSL template {name}",
150
+ )
151
+ self.make_kernel_render = make_kernel_render
152
+ self.bmreq = bmreq
153
+ self.template = template
154
+ self.mutated_inputs = mutated_inputs
155
+
156
+ def __str__(self) -> str:
157
+ return f"CuteDSLTemplateCaller({self.name})"
158
+
159
+ def benchmark(self, *args, out) -> float:
160
+ """Benchmark the kernel execution."""
161
+ return self.bmreq.benchmark(*args, out=out)
162
+
163
+ def output_node(self) -> TensorBox:
164
+ """Create the output node for this template choice."""
165
+ buffer = CuteDSLTemplateBuffer(
166
+ layout=self.layout,
167
+ inputs=self.input_nodes,
168
+ make_kernel_render=self.make_kernel_render,
169
+ template=self.template,
170
+ mutated_inputs=self.mutated_inputs,
171
+ )
172
+ # Pass KTC annotation to the buffer for encoding
173
+ if "ktc" in self.annotations:
174
+ buffer.annotations["ktc"] = self.annotations["ktc"]
175
+ return TensorBox.create(buffer)
176
+
177
+ def call_name(self) -> str:
178
+ """Return the kernel call name."""
179
+ return self.name
180
+
181
+ def to_callable(self) -> Any:
182
+ """Return callable that can execute this kernel."""
183
+ return self.make_kernel_render
184
+
185
+ def hash_key(self) -> str:
186
+ """Return unique hash key for this choice."""
187
+ return "-".join(
188
+ [
189
+ self.name.rsplit("_", 1)[0],
190
+ self.bmreq.module_cache_key,
191
+ ]
192
+ )
193
+
194
+ def info_dict(self) -> dict[str, Any]:
195
+ """Return information about this kernel."""
196
+ return {
197
+ "name": self.name,
198
+ "backend": "CuteDSL",
199
+ "template": self.template.name,
200
+ }
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/cache.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.cuda_env import get_cuda_arch, get_cuda_version
14
+ from torch._inductor.codegen.cutlass import serialization, utils
15
+ from torch._inductor.codegen.cutlass.serialization import (
16
+ get_cutlass_operation_serializer,
17
+ )
18
+ from torch._inductor.runtime.cache_dir_utils import cache_dir
19
+ from torch._inductor.utils import clear_on_fresh_cache
20
+
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+
25
+ CONFIG_PREFIX: str = "configs"
26
+
27
+
28
+ def get_config_request_key(
29
+ arch: str,
30
+ cuda_version: str,
31
+ instantiation_level: str,
32
+ ) -> str:
33
+ """
34
+ Return a key for the full ops, based on cutlass key, arch, cuda version, instantiation level, and serialization.py file hash.
35
+ """
36
+
37
+ # Get hash of serialization.py and cutlass_utils.py files using their module file paths
38
+ def get_file_hash(file_module):
39
+ file_path = inspect.getfile(file_module)
40
+ with open(file_path, "rb") as f:
41
+ return hashlib.sha256(f.read()).hexdigest()
42
+
43
+ serialization_hash = get_file_hash(serialization)
44
+ cutlass_utils_hash = get_file_hash(utils)
45
+
46
+ hash_target = "-".join(
47
+ [
48
+ cutlass_key().hex(),
49
+ arch,
50
+ cuda_version,
51
+ instantiation_level,
52
+ serialization_hash,
53
+ cutlass_utils_hash,
54
+ ]
55
+ )
56
+ return hashlib.sha256(hash_target.encode("utf-8")).hexdigest()[0:8]
57
+
58
+
59
+ def _generate_config_filename(request_key: str) -> str:
60
+ """
61
+ Generate a filename for the full ops.
62
+ """
63
+ return f"{CONFIG_PREFIX}_{request_key}.json"
64
+
65
+
66
+ @clear_on_fresh_cache
67
+ @functools.cache
68
+ def maybe_fetch_ops() -> Optional[list[Any]]:
69
+ """
70
+ Fetch ops from databases.
71
+ """
72
+ if config.force_disable_caches:
73
+ return None
74
+
75
+ # setup
76
+ arch: str = get_cuda_arch()
77
+ # get_cuda_version might return "12.4.0" or "12.4"
78
+ # but we want to use "12.4"
79
+ version: str = ".".join(get_cuda_version().split(".")[:2])
80
+ instantiation_level: str = config.cutlass.cutlass_instantiation_level
81
+
82
+ # filename and filepath
83
+ request_key: str = get_config_request_key(arch, version, instantiation_level)
84
+ filename: str = _generate_config_filename(request_key)
85
+ filepath: str = os.path.join(cache_dir(), filename)
86
+
87
+ # try fetch
88
+ serialized_ops: Optional[list[str]] = None
89
+ start_time = time.time()
90
+ if os.path.isfile(filepath):
91
+ # locally
92
+ try:
93
+ with open(filepath) as f:
94
+ serialized_ops = json.load(f)
95
+
96
+ assert isinstance(serialized_ops, list), (
97
+ f"Expected serialized ops is a list, got {type(serialized_ops)}"
98
+ )
99
+ except Exception:
100
+ log.warning(
101
+ "Failed to load CUTLASS config %s from local cache",
102
+ filename,
103
+ exc_info=True,
104
+ )
105
+ serialized_ops = None
106
+ elif config.is_fbcode():
107
+ from torch._inductor.fb.cutlass_remote_cache import (
108
+ maybe_fetch_cutlass_configs_from_remote,
109
+ )
110
+
111
+ # from remote
112
+ serialized_ops = maybe_fetch_cutlass_configs_from_remote(filepath)
113
+
114
+ if serialized_ops is None:
115
+ return None
116
+
117
+ # deserialize
118
+ serializer = get_cutlass_operation_serializer()
119
+ full_ops = [serializer.deserialize(x) for x in serialized_ops] # type: ignore[union-attr]
120
+ log.info("Loaded ops from %s cache in %.3fs", filename, time.time() - start_time)
121
+ return full_ops
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/gemm_template.py ADDED
@@ -0,0 +1,2005 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import enum
4
+ import functools
5
+ import logging
6
+ import re
7
+ import time
8
+ from abc import ABC, abstractmethod
9
+ from typing import Any, Optional, Union
10
+
11
+ import torch
12
+ import torch.utils._pytree as pytree
13
+ from torch._inductor.autotune_process import TensorMeta
14
+ from torch._inductor.codegen.cutlass.cache import maybe_fetch_ops
15
+ from torch._inductor.codegen.wrapper import PythonWrapperCodegen
16
+ from torch._inductor.runtime.runtime_utils import dynamo_timed
17
+ from torch._inductor.scheduler import BaseSchedulerNode
18
+ from torch._inductor.select_algorithm import create_inputs_key
19
+ from torch._inductor.utils import clear_on_fresh_cache
20
+
21
+ from ... import ir
22
+ from ...config import cutlass as inductor_cutlass_config
23
+ from ...ir import (
24
+ Buffer,
25
+ ChoiceCaller,
26
+ CUTLASSTemplateBuffer,
27
+ FixedLayout,
28
+ IRNode,
29
+ Layout,
30
+ ReinterpretView,
31
+ )
32
+ from ...utils import is_dynamic, Placeholder
33
+ from ...virtualized import V
34
+ from ..common import IndentedBuffer
35
+ from . import utils as cutlass_utils
36
+ from .kernel import CUTLASSTemplateKernel
37
+ from .python_evt import CutlassEVTCodegen, scaled_mm_evt
38
+ from .template import CUTLASSTemplate
39
+ from .utils import (
40
+ ACCUMULATOR_DTYPES,
41
+ dtype_match,
42
+ torch_dtype_to_cutlass_type,
43
+ XW_DTYPES,
44
+ )
45
+
46
+
47
+ GemmOperation = Any
48
+ EVTArgRenames = Any
49
+
50
+ log = logging.getLogger(__name__)
51
+
52
+ # Jinja template for GEMM Kernel, used by the CUTLASSGemm3xTemplate class below.
53
+ GEMM_TEMPLATE_CUTLASS_3X = r"""
54
+ {{template.header().getvalue()}}
55
+ {{template.globals().getvalue()}}
56
+ {{epilogue_visitor_tree}}
57
+ {{instance_definition}}
58
+ // When workspace_size is not a nullptr, populates requested workspace_size and returns.
59
+ // Otherwise, computes the Gemm kernel using the given workspace ptr.
60
+ extern "C" {
61
+ PT_EXPORT {{kernel_call_signature}} {
62
+ try {
63
+ using ElementComputeEpilogue = {{instance_type}}::ElementAccumulator;
64
+ using coord_t = cutlass::gemm::GemmCoord::Index;
65
+ static cutlass::KernelHardwareInfo hw_info;
66
+ if (hw_info.sm_count == 0) {
67
+ hw_info.sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(0);
68
+ CUTLASS_TRACE_HOST("Query result for SM count per device: " << hw_info.sm_count);
69
+ }
70
+ {{dynamic_cluster}}
71
+ {{instance_type}}::Arguments arguments;
72
+ {{template.render_gemm_arguments(argument_template, epilogue_template, should_swap_xw,
73
+ X, W, Bias, Y, alpha, beta, kernel, epilogue_args)}}
74
+ {{instance_type}} gemm_op;
75
+ if (workspace_size) {
76
+ *workspace_size = gemm_op.get_workspace_size(arguments);
77
+ return 0;
78
+ }
79
+ // check for null pointers after workspace size, since querying workspace size doesn't require valid data pointers
80
+ #ifndef CUTLASS_BACKEND_DISABLE_CHECKS
81
+ {
82
+ auto status = gemm_op.can_implement(arguments);
83
+ CUTLASS_CHECK(status);
84
+ }
85
+ #endif
86
+ #ifdef CUTLASS_DEBUG_TRACE_LEVEL
87
+ #if CUTLASS_DEBUG_TRACE_LEVEL == 1
88
+ {
89
+ // Print the maximum number of active blocks per SM for the kernel if CUTLASS_DEBUG_TRACE_LEVEL == 1
90
+ // we don't need a print statement, it's happening inside the function.
91
+ gemm_op.maximum_active_blocks();
92
+ }
93
+ #endif
94
+ #endif
95
+ {
96
+ auto status = gemm_op.initialize(arguments, workspace, stream);
97
+ CUTLASS_CHECK(status);
98
+ }
99
+ {
100
+ auto status = gemm_op(stream);
101
+ CUTLASS_CHECK(status);
102
+ }
103
+ }
104
+ catch (std::exception& e) {
105
+ std::cerr << "Runtime error: " << e.what() << std::endl;
106
+ return -1;
107
+ }
108
+ catch (...) {
109
+ return -1;
110
+ }
111
+ return 0;
112
+ }
113
+ }
114
+
115
+ // configuration name: {{op_conf_name}}
116
+ """
117
+
118
+ # Jinja template for Cutlass 3.x GEMM Kernel arguments, used by the CUTLASSGemmTemplate class below.
119
+ GEMM_ARGS_CUTLASS_3X = r"""
120
+ // Initialize GemmUniversal3xInstance arguments.
121
+ arguments = {
122
+ {{template.gemm_mode()}}, // GemmUniversalMode mode
123
+ {
124
+ static_cast<coord_t>({{M}}),
125
+ static_cast<coord_t>({{N}}),
126
+ static_cast<coord_t>(K),
127
+ static_cast<coord_t>(B)
128
+ }, // ProblemShape problem_shape
129
+ {
130
+ {{template.cutlass_type_cast(X, kernel.ptr(X))}}, // ElementA const* ptr_A
131
+ {
132
+ {{template.cute_int(kernel.stride(X, -2), "stride_x0")}},
133
+ {{template.cute_int(kernel.stride(X, -1), "stride_x1")}},
134
+ {{template.cute_int(kernel.batch_stride(X), "batch_stride_x")}}
135
+ }, // StrideA dA
136
+ {{template.cutlass_type_cast(W, kernel.ptr(W))}}, // ElementB const* ptr_B
137
+ {
138
+ {{template.cute_int(kernel.stride(W, -1), "stride_w1")}},
139
+ {{template.cute_int(kernel.stride(W, -2), "stride_w0")}},
140
+ {{template.cute_int(kernel.batch_stride(W), "batch_stride_w")}}
141
+ }, // StrideB dB
142
+ }, // MainloopArguments mainloop
143
+ {{epilogue_arguments}},
144
+ hw_info
145
+ };
146
+ arguments.scheduler.max_swizzle_size = swizzle;
147
+ """
148
+
149
+ # Jinja template for Cutlass 3.x GEMM Kernel arguments if epilogue fusion is applied,
150
+ # used by the CUTLASSGemmTemplate class below.
151
+ GEMM_ARGS_CUTLASS_3X_EPILOGUE = r"""
152
+ // see https://tinyurl.com/4rk89z48
153
+ {
154
+ {{epilogue_args}}, // thread, typename FusionCallbacks::Arguments ( EVT ) or ThreadEpilogueOp::Params (non-EVT )
155
+ {{template.cutlass_type_cast(Bias, kernel.ptr(Bias))}}, // ElementC const* ptr_C
156
+ {
157
+ {{template.cute_int(kernel.stride(Bias, -2, 1), "stride_bias0")}},
158
+ {{template.cute_int(kernel.stride(Bias, -1, 1), "stride_bias1")}},
159
+ {{template.cute_int(kernel.batch_stride(Bias), "batch_stride_bias")}}
160
+ }, // StrideC dC
161
+ {{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, // ElementD const* ptr_D
162
+ {
163
+ {{template.cute_int(kernel.stride(Y, -2), "stride_y0")}},
164
+ {{template.cute_int(kernel.stride(Y, -1), "stride_y1")}},
165
+ {{template.cute_int(kernel.batch_stride(Y), "batch_stride_y")}}
166
+ }, // StrideD dD
167
+ }, // EpilogueArguments epilogue
168
+ """
169
+
170
+ # Jinja template for GEMM Kernel, used by the CUTLASS2xGemmTemplate class below.
171
+ GEMM_TEMPLATE_CUTLASS_2X = r"""
172
+ {{template.header().getvalue()}}
173
+ {{template.globals().getvalue()}}
174
+ {{instance_definition}}
175
+ // When workspace_size is not a nullptr, populates requested workspace_size and returns.
176
+ // Otherwise, computes the Gemm kernel using the given workspace ptr.
177
+ extern "C" {
178
+ PT_EXPORT {{kernel_call_signature}} {
179
+ try {
180
+ int B = {{kernel.size(Y, 0, -3, default_value=1)}};
181
+ using ElementComputeEpilogue = {{instance_type}}::ElementAccumulator;
182
+ using coord_t = cutlass::gemm::GemmCoord::Index;
183
+ static cutlass::KernelHardwareInfo hw_info;
184
+ if (hw_info.sm_count == 0) {
185
+ hw_info.sm_count = cutlass::KernelHardwareInfo::query_device_multiprocessor_count(0);
186
+ CUTLASS_TRACE_HOST("Query result for SM count per device: " << hw_info.sm_count);
187
+ }
188
+ {{instance_type}}::Arguments arguments;
189
+ {{template.render_gemm_arguments(instance_type, argument_template, epilogue_template, should_swap_xw,
190
+ X, W, Bias, Meta, Y, alpha, beta, kernel, epilogue_args)}}
191
+ {{instance_type}} gemm_op;
192
+ if (workspace_size) {
193
+ *workspace_size = gemm_op.get_workspace_size(arguments);
194
+ return 0;
195
+ }
196
+
197
+ // check for null pointers after workspace size, since querying workspace size doesn't require valid data pointers
198
+ #ifndef CUTLASS_BACKEND_DISABLE_CHECKS
199
+ {
200
+ auto status = gemm_op.can_implement(arguments);
201
+ CUTLASS_CHECK(status);
202
+ }
203
+ #endif
204
+ #ifdef CUTLASS_DEBUG_TRACE_LEVEL
205
+ #if CUTLASS_DEBUG_TRACE_LEVEL == 1
206
+ {
207
+ // Print the maximum number of active blocks per SM for the kernel if CUTLASS_DEBUG_TRACE_LEVEL == 1
208
+ // we don't need a print statement, it's happening inside the function.
209
+ gemm_op.maximum_active_blocks();
210
+ }
211
+ #endif
212
+ #endif
213
+
214
+ {
215
+ auto status = gemm_op.initialize(arguments, workspace, stream);
216
+ CUTLASS_CHECK(status);
217
+ }
218
+ {
219
+ auto status = gemm_op(stream);
220
+ CUTLASS_CHECK(status);
221
+ }
222
+ }
223
+ catch (std::exception& e) {
224
+ std::cerr << "Runtime error: " << e.what() << std::endl;
225
+ return -1;
226
+ }
227
+ catch (...) {
228
+ return -1;
229
+ }
230
+ return 0;
231
+ }
232
+ }
233
+ """
234
+
235
+ # Jinja template for Cutlass 2.x GEMM Kernel arguments, used by the CUTLASS2xGemmTemplate class below.
236
+ GEMM_ARGS_CUTLASS_2X = r"""
237
+ int64_t batch_stride_x = {{kernel.stride(X, -3)}};
238
+ int64_t row_stride_x = {{kernel.row_or_column_stride(X)}};
239
+ int64_t batch_stride_w = {{kernel.stride(W, -3)}};
240
+ int64_t row_stride_w = {{kernel.row_or_column_stride(W)}};
241
+ int64_t batch_stride_bias = {{kernel.stride(Bias, -3)}};
242
+ int64_t row_stride_bias = {{kernel.row_or_column_stride(Bias)}};
243
+ int64_t batch_stride_y = {{kernel.stride(Y, -3)}};
244
+ int64_t row_stride_y = {{kernel.row_or_column_stride(Y)}};
245
+ // Initialize GemmUniversalInstance arguments.
246
+ arguments = {
247
+ {{template.gemm_mode()}}, // GemmUniversalMode mode
248
+ {
249
+ static_cast<coord_t>(M),
250
+ static_cast<coord_t>(N),
251
+ static_cast<coord_t>(K)
252
+ }, // GemmCoord problem_size
253
+ {{split_k if split_k > 1 else 'B'}}, // int batch_count
254
+ {ElementComputeEpilogue({{alpha}}), ElementComputeEpilogue({{beta}})}, // typename EpilogueOutputOp::Params epilogue
255
+ {{template.cutlass_type_cast(X, kernel.ptr(X))}}, // void const * ptr_A
256
+ {{template.cutlass_type_cast(W, kernel.ptr(W))}}, // void const * ptr_B
257
+ {{template.cutlass_type_cast(Bias, kernel.ptr(Bias))}}, // void const * ptr_C
258
+ {{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, // void * ptr_D
259
+ batch_stride_x, // int64_t batch_stride_A
260
+ batch_stride_w, // int64_t batch_stride_B
261
+ batch_stride_bias, // int64_t batch_stride_C
262
+ batch_stride_y, // int64_t batch_stride_D
263
+ row_stride_x, // typename LayoutA::Stride::LongIndex lda
264
+ row_stride_w, // typename LayoutB::Stride::LongIndex ldb
265
+ row_stride_bias, // typename LayoutC::Stride::LongIndex ldc
266
+ row_stride_y, // typename LayoutC::Stride::LongIndex ldd
267
+ };
268
+ """
269
+
270
+ GEMM_ARGS_SPARSE_CUTLASS_2X = r"""
271
+ using TensorRefA = cutlass::TensorRef<{{instance_type}}::ElementA,
272
+ {{instance_type}}::LayoutA>;
273
+ using TensorRefB = cutlass::TensorRef<{{instance_type}}::ElementB,
274
+ {{instance_type}}::LayoutB>;
275
+ using TensorRefC = cutlass::TensorRef<{{instance_type}}::ElementC,
276
+ {{instance_type}}::LayoutC>;
277
+ using TensorRefE = cutlass::TensorRef<{{instance_type}}::ElementE,
278
+ {{instance_type}}::LayoutE>;
279
+ // Note that "X" and "W" names may be misleading here. Namely, for
280
+ // sparse GEMM, the first argument is always sparse, while typically
281
+ // weight matrix, implied by name "W" will be sparse in
282
+ // applications. Thus, just remember that here: "X" refers to first
283
+ // argument, that is sparse, and "W" to second, that is dense.
284
+ TensorRefA X_ref({{template.cutlass_type_cast(X, kernel.ptr(X))}}, {{kernel.row_or_column_stride(X)}});
285
+ TensorRefB W_ref({{template.cutlass_type_cast(W, kernel.ptr(W))}}, {{kernel.row_or_column_stride(W)}});
286
+ TensorRefC Y_ref({{template.cutlass_type_cast(Y, kernel.ptr(Y))}}, {{kernel.row_or_column_stride(Y)}});
287
+ TensorRefE Meta_ref({{template.cutlass_sparse_meta_type_cast(Meta, kernel.ptr(Meta))}},
288
+ TensorRefE::Layout::packed({ {{kernel.size(Meta, 0)}}, {{kernel.size(Meta, 1)}} }));
289
+ // Initialize GemmSparse arguments.
290
+ arguments = {
291
+ {
292
+ static_cast<coord_t>(M),
293
+ static_cast<coord_t>(N),
294
+ static_cast<coord_t>(2 * K),
295
+ }, // GemmCoord problem_size
296
+ X_ref, // TensorRef<ElementA const, LayoutA> ref_A
297
+ W_ref, // TensorRef<ElementB const, LayoutB> ref_B
298
+ Y_ref, // TensorRef<ElementC const, LayoutC> ref_C
299
+ Y_ref, // TensorRef<ElementC, LayoutC> ref_D
300
+ Meta_ref, // TensorRef<ElementE const, LayoutE> ref_E
301
+ {ElementComputeEpilogue({{alpha}}), ElementComputeEpilogue({{beta}})}, // typename EpilogueOutputOp::Params epilogue,
302
+ };
303
+ """
304
+
305
+ # Additional includes which are necessary if the standalone test / debug runner is generated as well
306
+ GEMM_STANDALONE_RUNNER_ADDITIONAL_INCLUDES = r"""
307
+ #ifdef GENERATE_STANDALONE_RUNNER
308
+ #include "cutlass/util/distribution.h"
309
+ #include "cutlass/util/host_tensor.h"
310
+ #include "cutlass/util/packed_stride.hpp"
311
+ #include "cutlass/util/tensor_view_io.h"
312
+ #include "cutlass/util/reference/device/gemm_complex.h"
313
+ #include "cutlass/util/reference/device/tensor_compare.h"
314
+ #include "cutlass/util/reference/device/tensor_fill.h"
315
+ #include <iostream>
316
+ #endif
317
+ """
318
+
319
+ # Jinja template for the standalone runner that may be generated as part of the code.
320
+ GEMM_STANDALONE_RUNNER_TEMPLATE = r"""
321
+ #ifdef GENERATE_STANDALONE_RUNNER
322
+ /// Helper to initialize a block of device data
323
+ template <class Element>
324
+ bool initialize_block(
325
+ cutlass::DeviceAllocation<Element>& block,
326
+ uint64_t seed, float max=1.0, float min=-1.0) {
327
+ if (block.size()<=0) return false;
328
+ Element scope_max(static_cast<Element>(max)), scope_min(static_cast<Element>(min));
329
+ cutlass::reference::device::BlockFillRandomUniform(
330
+ (Element*)block.get(), block.size(), seed, scope_max, scope_min);
331
+
332
+ return true;
333
+ }
334
+
335
+ {% if Meta is defined and Meta is not none %}
336
+ template <class Element>
337
+ bool initialize_block_meta(
338
+ cutlass::DeviceAllocation<Element>& block,
339
+ uint64_t seed) {
340
+ if (block.size()<=0) return false;
341
+ cutlass::reference::device::BlockFillRandomSparseMeta(
342
+ (Element*)block.get(), block.size(), seed, {{instance_type}}::kMetaSizeInBits);
343
+ return true;
344
+ }
345
+ {% endif %}
346
+
347
+ extern "C" int run_standalone(uint64_t seed, int repetitions) {
348
+ std::cout << "Starting GEMM Standalone test run with seed " << seed << std::endl;
349
+ size_t workspace_size = 0;
350
+ size_t* workspace_size_ptr = &workspace_size;
351
+
352
+ int M = {{kernel.get_layout_args()[0]}};
353
+ int N = {{kernel.get_layout_args()[1]}};
354
+ int K = {{kernel.get_layout_args()[2]}};
355
+ int B = {{kernel.get_layout_args()[3]}};
356
+ int lda = {{kernel.get_layout_args()[4]}};
357
+ int ldb = {{kernel.get_layout_args()[5]}};
358
+ int ldc = {{kernel.get_layout_args()[6]}};
359
+ int ldd = {{kernel.get_layout_args()[7]}};
360
+ uint8_t swizzle = {{kernel.runtime_arg_values[0]}};
361
+
362
+ using ElementA = {{kernel.cutlass_dtype(X)}};
363
+ using ElementB = {{kernel.cutlass_dtype(W)}};
364
+ using ElementC = {{kernel.cutlass_dtype(Bias, default_dtype='uint8_t')}}; // may not be void
365
+ using ElementD = {{kernel.cutlass_dtype(Y)}};
366
+ {% if Meta is defined and Meta is not none %}
367
+ using ElementE = {{kernel.cutlass_dtype(Meta)}};
368
+ {% endif %}
369
+
370
+ cutlass::DeviceAllocation<ElementA> X_data({{kernel.max_valid_index(X)+1}});
371
+ initialize_block(X_data, seed++);
372
+ cutlass::DeviceAllocation<ElementB> W_data({{kernel.max_valid_index(W)+1}});
373
+ initialize_block(W_data, seed++);
374
+ cutlass::DeviceAllocation<ElementC> Bias_data({{kernel.max_valid_index(Bias)+1}});
375
+ initialize_block(Bias_data, seed++);
376
+ cutlass::DeviceAllocation<ElementD> Y_data({{kernel.max_valid_index(Y)+1}});
377
+ {% if Meta is defined and Meta is not none %}
378
+ cutlass::DeviceAllocation<ElementE> Meta_data({{kernel.max_valid_index(Meta)+1}});
379
+ initialize_block_meta(Meta_data, seed++);
380
+ {% endif %}
381
+
382
+ cutlass::DeviceAllocation<uint8_t> workspace_data;
383
+ // Call once with workspace_size_ptr set to get workspace size
384
+
385
+ std::cout << "Calling once to get workspace size" << std::endl;
386
+ {{test_call_statement}};
387
+ // Allocate workspace if necessary
388
+ if (workspace_size > 0) {
389
+ workspace_data.reset(workspace_size);
390
+ std::cout << "Allocated workspace size of " << workspace_size << " bytes" << std::endl;
391
+ }
392
+ std::cout << "Calling Kernel as {{test_call_statement}};" << std::endl;
393
+ workspace_size_ptr = nullptr;
394
+ for (int i=0; i<repetitions; i++) {
395
+ {{test_call_statement}};
396
+ }
397
+ cudaError_t result = cudaDeviceSynchronize();
398
+ if (result != cudaSuccess) {
399
+ std::cerr << "Device synchronize failed with error "
400
+ << cudaGetErrorString(result) << std::endl;
401
+ return result;
402
+ }
403
+ return 0;
404
+ }
405
+
406
+ int main(int argc, char** argv) {
407
+ // warmup
408
+ run_standalone(1, 2);
409
+ // repeat
410
+ return run_standalone(2, 10);
411
+ }
412
+
413
+ #endif
414
+ """ # noqa: B950
415
+
416
+
417
+ @clear_on_fresh_cache
418
+ class CUTLASSGemmTemplate(CUTLASSTemplate, ABC):
419
+ """
420
+ CUTLASS GEMM Template, which is used to generate CUTLASS GEMM kernels
421
+ including those which allow flexible fusions with epilogues.
422
+ """
423
+
424
+ filtered_ops_cache: dict[str, list[Any]] = {}
425
+ cache_clear = staticmethod(filtered_ops_cache.clear)
426
+
427
+ def __init__(
428
+ self,
429
+ input_nodes: list[Buffer],
430
+ layout: Layout,
431
+ alpha: float,
432
+ beta: float,
433
+ input_reorder: Optional[list[int]] = None,
434
+ use_fast_accum: Optional[bool] = None,
435
+ ) -> None:
436
+ """
437
+ Args:
438
+ input_nodes (List[Buffer]): List of input nodes of the GEMM kernel.
439
+ layout (Layout): Layout type of the resulting output node.
440
+ alpha (float): The scaling factor for the product of the inputs in the GEMM operation.
441
+ beta (float): The scaling factor applied to the output matrix.
442
+ input_reorder (Optional[List[int]]): Specifies the reordering of the input nodes. If not provided,
443
+ no reordering is performed. Defaults to None.
444
+ """
445
+ super().__init__(
446
+ str(Placeholder.KERNEL_NAME), input_nodes, layout, input_reorder
447
+ )
448
+ self.alpha = alpha
449
+ self.beta = beta
450
+ self.use_fast_accum = use_fast_accum
451
+ assert 2 <= len(input_nodes) <= 5
452
+ assert self._are_inputs_layout_compatible(
453
+ [node.get_layout() for node in input_nodes]
454
+ )
455
+
456
+ self.cache_key: str = create_inputs_key(self.input_nodes)
457
+
458
+ @staticmethod
459
+ @abstractmethod
460
+ def add_cutlass_gemm_choices(
461
+ choices: list[ChoiceCaller],
462
+ layout: ir.Layout,
463
+ input_nodes: list[Buffer],
464
+ alpha: Union[float, int] = 1,
465
+ beta: Union[float, int] = 0,
466
+ input_reorder: Optional[list[int]] = None,
467
+ use_fast_accum: Optional[bool] = None,
468
+ **extra_kwargs,
469
+ ) -> None:
470
+ raise NotImplementedError
471
+
472
+ @staticmethod
473
+ @abstractmethod
474
+ def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821
475
+ raise NotImplementedError
476
+
477
+ @staticmethod
478
+ @abstractmethod
479
+ def _has_tma_epilogue(self) -> bool:
480
+ raise NotImplementedError
481
+
482
+ @abstractmethod
483
+ def _get_template(self) -> str:
484
+ raise NotImplementedError
485
+
486
+ @abstractmethod
487
+ def _get_template_args(
488
+ self,
489
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
490
+ ) -> tuple[str, Optional[str]]:
491
+ raise NotImplementedError
492
+
493
+ @abstractmethod
494
+ def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool:
495
+ raise NotImplementedError
496
+
497
+ @abstractmethod
498
+ def _shape_match(
499
+ self,
500
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
501
+ ) -> bool:
502
+ raise NotImplementedError
503
+
504
+ @abstractmethod
505
+ def _alignment_match(
506
+ self,
507
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
508
+ ) -> bool:
509
+ raise NotImplementedError
510
+
511
+ @abstractmethod
512
+ def _set_bias_layout_and_alignment(
513
+ self,
514
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
515
+ ) -> bool:
516
+ raise NotImplementedError
517
+
518
+ @abstractmethod
519
+ def _define_gemm_instance(
520
+ self,
521
+ op: GemmOperation,
522
+ evt_name: Optional[str] = None,
523
+ ) -> tuple[str, str]:
524
+ raise NotImplementedError
525
+
526
+ @abstractmethod
527
+ def _get_extra_inputs_and_names(
528
+ self,
529
+ op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821
530
+ ) -> tuple[Optional[Buffer], list[Optional[Buffer]], list[str]]:
531
+ raise NotImplementedError
532
+
533
+ @abstractmethod
534
+ def _update_arg_names_for_test_call_statement(
535
+ self,
536
+ arg_names: list[str],
537
+ input_nodes: list[Buffer],
538
+ ) -> list[str]:
539
+ raise NotImplementedError
540
+
541
+ def _add_cutlass_gemm_choices(
542
+ self,
543
+ choices: list[ChoiceCaller],
544
+ layout: ir.Layout,
545
+ input_nodes: list[Buffer],
546
+ alpha: Union[float, int] = 1,
547
+ beta: Union[float, int] = 0,
548
+ input_reorder: Optional[list[int]] = None,
549
+ **extra_kwargs,
550
+ ) -> None:
551
+ """
552
+ Adds Cutlass GEMM configurations choices to the auto-tuning list.
553
+
554
+ This function mutates the passed list of choices by appending the choices for Cutlass GEMM configs to it.
555
+
556
+ Args:
557
+ choices (list): The list to which choices are appended.
558
+ layout (ir.Layout): The layout configuration.
559
+ input_nodes (list): The list of input nodes.
560
+ alpha (float,int): Scaling factor, defaults to 1.
561
+ beta (float,int): Offset, defaults to 0.
562
+ input_reorder (list, optional): Order of the inputs, defaults to None.
563
+ **extra_kwargs: Additional keyword arguments.
564
+
565
+ """
566
+
567
+ ops = self.gen_ops()
568
+
569
+ # pre-computation
570
+ layout_repr: str = str(layout)
571
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]] = (
572
+ TensorMeta.from_irnodes(self.input_nodes)
573
+ )
574
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]] = (
575
+ TensorMeta.from_irnodes(self.output_node)
576
+ )
577
+
578
+ with dynamo_timed("CUTLASSGemmTemplate.maybe_append_choice"):
579
+ for name, op in ops:
580
+ for (
581
+ swizzle
582
+ ) in inductor_cutlass_config.cutlass_max_profiling_swizzle_options:
583
+ description = f"{name} swizzle={swizzle}"
584
+ self.maybe_append_choice(
585
+ choices,
586
+ op=op,
587
+ name=name,
588
+ description=description,
589
+ input_key=self.cache_key,
590
+ layout_repr=layout_repr,
591
+ input_tensor_meta=input_tensor_meta,
592
+ output_tensor_meta=output_tensor_meta,
593
+ swizzle=swizzle,
594
+ )
595
+
596
+ if len(ops) == 0:
597
+ log.info(
598
+ "No suitable Cutlass GEMM configs found, fallbacks used "
599
+ "( len(ops)=%d, output_layout=%s, input_layouts=%s, input_strides=%s )",
600
+ len(ops),
601
+ layout,
602
+ [node.get_layout() for node in input_nodes],
603
+ [node.get_stride() for node in input_nodes],
604
+ )
605
+ log.debug(
606
+ "Added %d Cutlass gemm configs.",
607
+ len(ops),
608
+ )
609
+
610
+ def header(self) -> IndentedBuffer:
611
+ """
612
+ Returns a buffer containing CUDA C++ code for the header section of the CUTLASS GEMM template.
613
+ This section primarily includes the necessary header files.
614
+
615
+ Returns:
616
+ IndentedBuffer: An instance of IndentedBuffer that contains the generated CUDA C++ header code.
617
+ """
618
+ res = super().header()
619
+ res.splice(
620
+ """
621
+ #include "cutlass/gemm/gemm.h"
622
+ #include "cutlass/gemm/device/gemm_universal.h"
623
+ #include "cutlass/gemm/device/gemm_universal_adapter.h"
624
+ #include "cutlass/gemm/kernel/gemm_universal.hpp"
625
+ #include "cutlass/gemm/device/gemm_sparse.h"
626
+ #include "cutlass/gemm/collective/collective_builder.hpp"
627
+ #include "cutlass/epilogue/collective/collective_builder.hpp"
628
+ #include "cutlass/epilogue/collective/default_epilogue.hpp"
629
+ #include "cutlass/epilogue/thread/linear_combination.h"
630
+ #include "cutlass/epilogue/thread/activation.h"
631
+ #include "cutlass/gemm/dispatch_policy.hpp"
632
+ #include "cutlass/gemm/kernel/tile_scheduler.hpp"
633
+ #include "cutlass/tensor_ref.h"
634
+ #include "cutlass/util/distribution.h"
635
+ #include "cutlass/util/packed_stride.hpp"
636
+ #include "cutlass/util/tensor_view_io.h"
637
+ """
638
+ )
639
+ if inductor_cutlass_config.generate_test_runner and not is_dynamic(
640
+ *self.input_nodes, self.output_node
641
+ ):
642
+ res.splice(GEMM_STANDALONE_RUNNER_ADDITIONAL_INCLUDES)
643
+ return res
644
+
645
+ @staticmethod
646
+ def cutlass_layout(torch_layout: ir.Layout) -> "Optional[cutlass_lib.LayoutType]": # type: ignore[name-defined] # noqa: F821
647
+ """
648
+ Converts an ir.Layout instance into the corresponding cutlass_library.LayoutType enum value
649
+ (RowMajor, ColumnMajor, or None if no matching value is found ).
650
+
651
+ Args:
652
+ torch_layout (ir.Layout): The layout that needs to be looked up.
653
+
654
+ Returns:
655
+ cutlass_lib.LayoutType: The converted layout corresponding to the `torch_layout` or None if no matching
656
+ value is found.
657
+ """
658
+ assert cutlass_utils.try_import_cutlass()
659
+ import cutlass_library.library as cutlass_lib
660
+
661
+ if V.graph.sizevars.statically_known_equals(torch_layout.stride[-1], 1):
662
+ return cutlass_lib.LayoutType.RowMajor
663
+ elif V.graph.sizevars.statically_known_equals(torch_layout.stride[-2], 1):
664
+ return cutlass_lib.LayoutType.ColumnMajor
665
+ else:
666
+ return None
667
+
668
+ @staticmethod
669
+ def flip_cutlass_layout(
670
+ cutlass_layout: "cutlass_lib.LayoutType", # type: ignore[name-defined] # noqa: F821
671
+ ) -> "cutlass_lib.LayoutType": # type: ignore[name-defined] # noqa: F821
672
+ """Helper method: Flips a given cutlass layout (cutlass_lib.LayoutType) from RowMajor
673
+ to ColumnMajor or vice versa"""
674
+ assert cutlass_utils.try_import_cutlass()
675
+ import cutlass_library.library as cutlass_lib
676
+
677
+ if cutlass_layout == cutlass_lib.LayoutType.RowMajor:
678
+ return cutlass_lib.LayoutType.ColumnMajor
679
+ else:
680
+ return cutlass_lib.LayoutType.RowMajor
681
+
682
+ @staticmethod
683
+ @functools.lru_cache(32)
684
+ def layout_match(
685
+ torch_layout: ir.Layout,
686
+ cutlass_layout: "cutlass_lib.LayoutType", # type: ignore[name-defined] # noqa: F821
687
+ ) -> bool:
688
+ """Helper Method: Determines whether a given torch layout matches a given Cutlass layout"""
689
+ return CUTLASSGemmTemplate.cutlass_layout(torch_layout) == cutlass_layout
690
+
691
+ @staticmethod
692
+ def set_layout(tensor_desc: "TensorDescription", torch_layout: ir.Layout) -> None: # type: ignore[name-defined] # noqa: F821
693
+ """
694
+ Helper method: Sets the layout of a given tensor description to match the given torch layout
695
+ """
696
+ if CUTLASSGemmTemplate.layout_match(torch_layout, tensor_desc.layout):
697
+ return
698
+ tensor_desc.layout = CUTLASSGemmTemplate.cutlass_layout(torch_layout)
699
+
700
+ @staticmethod
701
+ def set_alignment(torch_layout, op_element) -> bool:
702
+ """
703
+ Helper method to update the alignment of a given CUTLASS GEMM op operand's element.
704
+
705
+ This method modifies the alignment of the given Cutlass GEMM op operand's element to match the
706
+ layout of the corresponding ir.Buffer node.
707
+
708
+ Args:
709
+ torch_layout: The layout of the corresponding ir.Buffer node.
710
+ op_element: The Cutlass GEMM op operand's element whose alignment is to be updated.
711
+
712
+ Returns:
713
+ bool: True if the alignment was successfully updated, False otherwise.
714
+ """
715
+ alignment = cutlass_utils.get_max_alignment(torch_layout)
716
+ cuda_arch = cutlass_utils.get_cuda_arch()
717
+ if cuda_arch and int(cuda_arch) >= 90 and alignment < op_element.alignment:
718
+ return False
719
+ else:
720
+ op_element.alignment = alignment
721
+ return True
722
+
723
+ @staticmethod
724
+ def should_swap_XW(
725
+ bias: IRNode,
726
+ ) -> bool:
727
+ """
728
+ Helper method to determine whether we should do an explicit transpose by switching the order of the
729
+ matmul operands. This might be necessary when we can't otherwise arrive at the right memory
730
+ layout for the given Bias operand.
731
+
732
+ Note: This method is a workaround for CUDA Errors that seemingly non-deterministically
733
+ occurred in practice in some CUTLASS GEMM Kernels with Linear epilogues that have a bias term.
734
+ it might make sense to check on newer Cutlass releases whether it makes sense to keep
735
+ returning True in certain cases or whether it becomes unnecessary.
736
+ """
737
+ # If bias is row major, swap all M and N dimensions
738
+ if (
739
+ bias is not None
740
+ and len(bias.get_stride()) >= 2
741
+ and bias.get_stride()[-1] in (0, 1)
742
+ ):
743
+ log.debug("GEMM Layout swapped X and W -> explicit transpose")
744
+ return True
745
+ return False
746
+
747
+ @staticmethod
748
+ def swap_XW(
749
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
750
+ ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821
751
+ """
752
+ Swap operands X and W (aka operans A and B) of the GEMM operation. This
753
+ requires transposing the operands, which is done by swapping the strides.
754
+ Note that we don't change the apparent external layout, just the operand layout.
755
+ this is intentional.
756
+ """
757
+ new_op = copy.deepcopy(op)
758
+ new_op.A.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.A.layout)
759
+ new_op.B.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.B.layout)
760
+ new_op.A, new_op.B = new_op.B, new_op.A
761
+ new_op.C.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.C.layout)
762
+ new_op.D.layout = CUTLASSGemmTemplate.flip_cutlass_layout(new_op.D.layout)
763
+ return new_op
764
+
765
+ def fix_op_layout(
766
+ self,
767
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
768
+ X: Buffer,
769
+ W: Buffer,
770
+ Bias: Optional[Buffer],
771
+ Y: Union[Buffer, ReinterpretView],
772
+ ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821
773
+ # This is a workaround to deal with cases where the input layouts have changed
774
+ # between autotuning and rendering. This happens if the inputs layout
775
+ # are FlexibleLayout instances. In this case, we need to update the
776
+ # op's input layouts. It is a hack, because now the op
777
+ # we benchmarked is not the same as the op we render,
778
+ # but there is no simple way to fix this in the autotuner, since that would
779
+ # potentially disable other optimizations.
780
+ a_layout = X.get_layout()
781
+ b_layout = W.get_layout()
782
+ c_layout = Bias.get_layout() if Bias is not None else None
783
+
784
+ d_layout = copy.deepcopy(Y.get_layout())
785
+ match_list = [
786
+ CUTLASSGemmTemplate.layout_match(buf.get_layout(), op_layout)
787
+ for buf, op_layout in zip(
788
+ (X, W, Bias, Y),
789
+ (op.A.layout, op.B.layout, op.C.layout, op.D.layout),
790
+ )
791
+ if buf is not None
792
+ ]
793
+ all_match = all(match_list)
794
+ if all_match:
795
+ return op
796
+ log.warning(
797
+ f"Cutlass GEMM Layout change: Input and/or output layouts have changed between autotuning/retuning and call to render on {self}. Applying workaround. This can lead to suboptimal performance. Match List: {match_list}" # noqa: G004, B950
798
+ )
799
+ new_op = copy.deepcopy(op)
800
+
801
+ if a_layout is not None:
802
+ new_op.A.layout = CUTLASSGemmTemplate.cutlass_layout(a_layout)
803
+ if b_layout is not None:
804
+ new_op.B.layout = CUTLASSGemmTemplate.cutlass_layout(b_layout)
805
+ if c_layout is not None:
806
+ new_op.C.layout = CUTLASSGemmTemplate.cutlass_layout(c_layout)
807
+ new_op.C.element = cutlass_utils.torch_dtype_to_cutlass_type(c_layout.dtype)
808
+ if d_layout is not None:
809
+ new_op.D.layout = CUTLASSGemmTemplate.cutlass_layout(d_layout)
810
+ return new_op
811
+
812
+ def _dtype_match(
813
+ self,
814
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
815
+ ) -> bool:
816
+ """
817
+ Checking dtypes of A, B, acc, D here.
818
+
819
+ Empirically speaking, CUTLASS2x ops have same dtype for C and D.
820
+ """
821
+ X = self.input_nodes[0]
822
+ W = self.input_nodes[1]
823
+
824
+ accumulator_torch_dtype = cutlass_utils.get_accumulator_dtype(
825
+ [X.get_dtype(), W.get_dtype()],
826
+ )
827
+ if not (
828
+ cutlass_utils.dtype_match(X.get_dtype(), op.A.element)
829
+ and cutlass_utils.dtype_match(W.get_dtype(), op.B.element)
830
+ and cutlass_utils.dtype_match(
831
+ self.output_node.get_layout().dtype, op.D.element
832
+ )
833
+ and cutlass_utils.dtype_match(
834
+ accumulator_torch_dtype, op.accumulator_type()
835
+ )
836
+ ):
837
+ return False
838
+
839
+ return True
840
+
841
+ @classmethod
842
+ def global_filter_ops(
843
+ cls,
844
+ ops: list["cutlass_library.gemm_op.GemmOperation"], # type: ignore[name-defined] # noqa: F821
845
+ ) -> list["cutlass_library.gemm_op.GemmOperation"]: # type: ignore[name-defined] # noqa: F821
846
+ """
847
+ Filter ops without using information about the torch op, input nodes and output node.
848
+ """
849
+ assert cutlass_utils.try_import_cutlass()
850
+ import cutlass_library.library as cutlass_lib # type: ignore[import]
851
+
852
+ # Skip simt kernels
853
+ ops = [
854
+ op
855
+ for op in ops
856
+ if op.tile_description.math_instruction.opcode_class
857
+ != cutlass_lib.OpcodeClass.Simt
858
+ ]
859
+
860
+ # only keep the set of row x column ops
861
+ # for other layout, we modify in place in filter_op, after deepcopy
862
+ ops = [
863
+ op
864
+ for op in ops
865
+ if op.A.layout.name == "RowMajor" and op.B.layout.name == "ColumnMajor"
866
+ ]
867
+
868
+ # filter by supported accumulator types
869
+ ops = [
870
+ op
871
+ for op in ops
872
+ if any(
873
+ dtype_match(torch_dtype, op.accumulator_type())
874
+ for torch_dtype in ACCUMULATOR_DTYPES
875
+ )
876
+ ]
877
+
878
+ # check if dtypes of A and B are supported
879
+ ops = [
880
+ op
881
+ for op in ops
882
+ if any(dtype_match(torch_dtype, op.A.element) for torch_dtype in XW_DTYPES)
883
+ and any(dtype_match(torch_dtype, op.B.element) for torch_dtype in XW_DTYPES)
884
+ ]
885
+
886
+ return ops
887
+
888
+ def filter_op(
889
+ self,
890
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
891
+ ) -> "cutlass_library.gemm_op.GemmOperation": # type: ignore[name-defined] # noqa: F821
892
+ """
893
+ Helper method:
894
+
895
+ Determines whether a given Cutlass GEMM op definition is suitable for the current
896
+ input / output of the operation that this template is supposed to implement.
897
+
898
+ Takes memory layout, dtype and support for EVT operations into account,
899
+ and filters potentially problematic ops.
900
+
901
+ Returns None if the op is not suitable, otherwise returns the op to be used, which might
902
+ have been mutated.
903
+ """
904
+
905
+ if op.gemm_kind not in self._get_supported_ops():
906
+ return None
907
+
908
+ X = self.input_nodes[0]
909
+ W = self.input_nodes[1]
910
+
911
+ # Filter ops according to the shape match.
912
+ if not self._shape_match(op):
913
+ return None
914
+
915
+ # Filter ops by dtypes.
916
+ if not self._dtype_match(op):
917
+ return None
918
+
919
+ # Filter ops by alignment.
920
+ if not self._alignment_match(op):
921
+ log.debug(
922
+ "Skipping due to alignment mismatch. op: %s", op.configuration_name()
923
+ )
924
+ return None
925
+
926
+ # only use stream k for static shape
927
+ if op.tile_scheduler.name == "StreamK":
928
+ static_shape = PythonWrapperCodegen.statically_known_list_of_ints_or_none(
929
+ tuple(X.get_size()) + tuple(W.get_size())
930
+ )
931
+ if not static_shape:
932
+ return None
933
+
934
+ # Update op.
935
+ op = copy.deepcopy(op)
936
+
937
+ # set layouts for X and W
938
+ self.set_layout(op.A, X.get_layout())
939
+ self.set_layout(op.B, W.get_layout())
940
+
941
+ # Set output layout.
942
+ op.D.layout = CUTLASSGemmTemplate.cutlass_layout(self.output_node.get_layout())
943
+
944
+ # Filter ops by alignments and set alignments.
945
+ status = (
946
+ self.set_alignment(X.get_layout(), op.A)
947
+ and self.set_alignment(W.get_layout(), op.B)
948
+ and self.set_alignment(self.output_node.get_layout(), op.D)
949
+ )
950
+ if not status:
951
+ log.debug(
952
+ "Skipping due to alignment setting failure. op: %s",
953
+ op.configuration_name(),
954
+ )
955
+ return None
956
+
957
+ if inductor_cutlass_config.cutlass_tma_only and not self._has_tma_epilogue(op):
958
+ return None
959
+
960
+ # Set epilogue.
961
+ # TODO: update epilogue functor according to epilogues.
962
+ op.element_epilogue = op.accumulator_type()
963
+
964
+ if self.use_fast_accum is not None:
965
+ is_op_fast_accum = "fastaccum" in op.configuration_name()
966
+ if self.use_fast_accum ^ is_op_fast_accum:
967
+ return None
968
+
969
+ # Set bias layout and alignment.
970
+ status = self._set_bias_layout_and_alignment(op)
971
+ if not status:
972
+ log.debug(
973
+ "Skipping due to bias layout and alignment setting failure. op: %s",
974
+ op.configuration_name(),
975
+ )
976
+ return None
977
+
978
+ # Apply regex filters at the end when configuration name doesn't change anymore
979
+ if inductor_cutlass_config.cutlass_op_allowlist_regex:
980
+ if not re.search(
981
+ inductor_cutlass_config.cutlass_op_allowlist_regex,
982
+ op.configuration_name(),
983
+ ):
984
+ return None
985
+ if inductor_cutlass_config.cutlass_op_denylist_regex is not None:
986
+ if re.search(
987
+ inductor_cutlass_config.cutlass_op_denylist_regex,
988
+ op.configuration_name(),
989
+ ):
990
+ return None
991
+
992
+ return op
993
+
994
+ def gen_ops(self) -> "list[tuple[str, cutlass_gemm_op.GemmOperation]]": # type: ignore[name-defined] # noqa: F821
995
+ """
996
+ Creates a list of Cutlass GemmOperation instances that match the operation this template is designed to represent.
997
+ The matching is carried out with respect to the input and output specifications of the operation.
998
+
999
+ No function arguments.
1000
+
1001
+ Returns:
1002
+ List[tuple[str, cutlass_gemm_op.GemmOperation]]: A list of (cutlass_name, GemmOperation)
1003
+ tuples that are compatible with the operation requirements of this template.
1004
+ """
1005
+ assert cutlass_utils.try_import_cutlass()
1006
+ import cutlass_library.gemm_operation as cutlass_gemm_op
1007
+
1008
+ if self.cache_key in self.filtered_ops_cache:
1009
+ log.debug("Using cached ops for %s", self.cache_key)
1010
+ return self.filtered_ops_cache[self.cache_key]
1011
+
1012
+ with dynamo_timed("CUTLASSGemmTemplate.maybe_fetch_ops"):
1013
+ maybe_ops = maybe_fetch_ops()
1014
+ if maybe_ops is None:
1015
+ log.debug("Cannot fetch ops from cache, generating ops from scratch")
1016
+ full_ops = cutlass_utils.gen_ops()
1017
+ ops = pytree.tree_flatten(full_ops)[0]
1018
+ else:
1019
+ log.debug("Using cached ops from cache")
1020
+ ops = maybe_ops
1021
+
1022
+ ops = self.global_filter_ops(ops)
1023
+
1024
+ res: dict[str, cutlass_gemm_op.GemmOperation] = {}
1025
+ start_time = time.time()
1026
+ for op in ops:
1027
+ # if changed, need to also change CUTLASS_OPERATION_KIND
1028
+ assert isinstance(op, cutlass_gemm_op.GemmOperation)
1029
+ filter_res = self.filter_op(op)
1030
+ if (
1031
+ filter_res is not None
1032
+ and res.get(filter_res.configuration_name()) is None
1033
+ ):
1034
+ res[filter_res.configuration_name()] = filter_res
1035
+ log.info(
1036
+ "Got cutlass configs: total number of ops: %d. Filtering took %.2f seconds",
1037
+ len(res),
1038
+ time.time() - start_time,
1039
+ )
1040
+ sorted_res = sorted(res.items())
1041
+ ret_res = sorted_res[: inductor_cutlass_config.cutlass_max_profiling_configs]
1042
+ if len(self.filtered_ops_cache) < 50:
1043
+ self.filtered_ops_cache[self.cache_key] = ret_res
1044
+ else:
1045
+ log.debug("Not caching ops since filtered_ops_cache has reached size 50.")
1046
+ return ret_res
1047
+
1048
+ def gemm_mode(self) -> str:
1049
+ """
1050
+ Returns a Cutlass GEMM mode string for the current operation, dependent on whether this op implements
1051
+ a batched GEMM or a simple GEMM without batch dimension.
1052
+
1053
+ Returns:
1054
+ str: A string indicating the Cutlass GEMM mode. If the output node has more than two dimensions,
1055
+ "cutlass::gemm::GemmUniversalMode::kBatched" is returned, otherwise
1056
+ "cutlass::gemm::GemmUniversalMode::kGemm" is returned.
1057
+ """
1058
+ sizes = self.output_node.get_size()
1059
+ if len(sizes) > 2:
1060
+ return "cutlass::gemm::GemmUniversalMode::kBatched"
1061
+ else:
1062
+ return "cutlass::gemm::GemmUniversalMode::kGemm"
1063
+
1064
+ def _dynamic_cluster_block(self, op: "cutlass_gemm_op.GemmOperation") -> str: # type: ignore[name-defined] # noqa: F821
1065
+ """
1066
+ Temporary workaround for CUTLASS GEMMs that encode cluster shape as runtime values.
1067
+
1068
+ For dynamic-cluster kernels, CUTLASS expects `KernelHardwareInfo.cluster_shape` and
1069
+ `KernelHardwareInfo.cluster_shape_fallback` to be populated with valid runtime values.
1070
+ Today we provide a single global preferred/fallback pair (configurable via env),
1071
+ which is sufficient for correctness but is not performance-optimal.
1072
+
1073
+ Note: This is intentionally minimal because this code path is transitional. Cluster-shape
1074
+ selection should ultimately be handled in the CuTe/DSL implementation rather than
1075
+ investing heavily in the legacy CUTLASS template pipeline.
1076
+ """
1077
+ shape = getattr(getattr(op, "tile_description", None), "cluster_shape", None)
1078
+ if not shape or len(shape) < 2 or (shape[0] > 0 and shape[1] > 0):
1079
+ return ""
1080
+
1081
+ preferred = inductor_cutlass_config.cutlass_dynamic_cluster_shape
1082
+ fallback = inductor_cutlass_config.cutlass_dynamic_cluster_fallback
1083
+
1084
+ cluster_k = shape[2] if len(shape) > 2 and shape[2] > 0 else preferred[2]
1085
+ preferred = (preferred[0], preferred[1], cluster_k)
1086
+ fallback_k = fallback[2] if len(fallback) > 2 and fallback[2] > 0 else cluster_k
1087
+ fallback = (fallback[0], fallback[1], fallback_k)
1088
+
1089
+ return (
1090
+ f" hw_info.cluster_shape = {{{preferred[0]}, {preferred[1]}, {preferred[2]}}};\n"
1091
+ f" hw_info.cluster_shape_fallback = {{{fallback[0]}, {fallback[1]}, {fallback[2]}}};"
1092
+ )
1093
+
1094
+ def render( # type: ignore[override]
1095
+ self,
1096
+ kernel: CUTLASSTemplateKernel,
1097
+ op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821
1098
+ template_buffer_node: Optional[CUTLASSTemplateBuffer] = None,
1099
+ epilogue_nodes: Optional[list[BaseSchedulerNode]] = None,
1100
+ **kwargs,
1101
+ ) -> str:
1102
+ """
1103
+ The primary entry point for the code rendering process used in this template.
1104
+ Renders the Cutlass based CUDA C++ code for the GEMM Kernel that this template is designed to implement,
1105
+ including potentially fused epilogues.
1106
+
1107
+ Args:
1108
+ kernel (CUTLASSTemplateKernel): The kernel to be rendered.
1109
+ op (cutlass_gemm_op.GemmOperation, optional): A GEMM operation that is required to be compatible with the
1110
+ input and output definitions as well as a possible epilogue. Defaults to None.
1111
+ **kwargs: Additional keyword arguments. Currently unused.
1112
+
1113
+ Returns:
1114
+ str: Cutlass based CUDA C++ code fragment as a string, to be used by the current
1115
+ CUTLASSTemplateKernel or autotuning code.
1116
+
1117
+ Note:
1118
+ All inputs and their corresponding buffer addresses and names take precedence over previously
1119
+ passed inputs to the template at construction time. However, they should be layout compatible.
1120
+ """
1121
+ assert cutlass_utils.try_import_cutlass()
1122
+ import cutlass_library.gemm_operation as cutlass_gemm_op
1123
+ import cutlass_library.library as cutlass_lib
1124
+
1125
+ assert isinstance(op, cutlass_gemm_op.GemmOperation), (
1126
+ "op argument is required and has to be an instance of GemmOperation"
1127
+ )
1128
+
1129
+ if epilogue_nodes and not self._has_tma_epilogue(op):
1130
+ raise NotImplementedError(
1131
+ "Non-TMA epilogue visitor tree is not supported in Cutlass."
1132
+ )
1133
+
1134
+ assert len(self.input_nodes) >= 2 and self.output_node is not None
1135
+ X, W = self.input_nodes[0], self.input_nodes[1]
1136
+ for input_node in self.input_nodes:
1137
+ if not isinstance(X.layout, FixedLayout):
1138
+ input_node.freeze_layout()
1139
+
1140
+ Y = self.output_node
1141
+ if template_buffer_node is not None:
1142
+ Y = template_buffer_node
1143
+
1144
+ Bias, extra_inputs, extra_names = self._get_extra_inputs_and_names(op)
1145
+
1146
+ # Define Kernel call signature
1147
+ # Important: This step also populates Kernel name to node mapping data structures,
1148
+ # which are required further below ( for example by the template renderer )
1149
+ inputs = [X, W, Bias, *extra_inputs]
1150
+ names = ["X", "W", "Bias", *extra_names] + ["Y"]
1151
+ names_str = ",".join(names)
1152
+ if self.input_reorder is not None:
1153
+ input_reorder = self.input_reorder
1154
+ else:
1155
+ input_reorder = None
1156
+
1157
+ # The layouts might have changed between autotuning and this call if they were FlexibleLayout
1158
+ # we need to adapt, which might lead to suboptimal performance.
1159
+ op = self.fix_op_layout(op, X, W, Bias, Y)
1160
+
1161
+ # to make op mutable without affecting others
1162
+ op = copy.deepcopy(op)
1163
+ is_scaled_mm = len(self.input_nodes) in (4, 5)
1164
+ if Bias is not None and not is_scaled_mm:
1165
+ assert Bias.get_dtype() == X.get_dtype()
1166
+ # This might have been set to void during filtering, when the assumption was still that there's no C
1167
+ # operand
1168
+ op.C.element = op.A.element
1169
+
1170
+ assert op.C.element == op.D.element, (
1171
+ f"Expect C and D to have the same dtype, found {op.C.element} and {op.D.element}"
1172
+ )
1173
+
1174
+ argument_template, epilogue_template = self._get_template_args(op)
1175
+ should_swap_xw: bool = False
1176
+ if Bias is not None and self._has_tma_epilogue(op):
1177
+ if (
1178
+ op.epilogue_schedule
1179
+ != cutlass_lib.EpilogueScheduleType.EpilogueTransposed
1180
+ and self.should_swap_XW(Bias)
1181
+ ):
1182
+ # TMA epilogue requires bias vector in column major to get best perf.
1183
+ op = self.swap_XW(op)
1184
+ should_swap_xw = True
1185
+
1186
+ name_to_buffer = {node.get_name(): node for node in self.input_nodes}
1187
+ # handle the fake output buffer during lowering
1188
+ name_to_buffer[Y.get_name()] = Y # type: ignore[assignment]
1189
+
1190
+ if epilogue_nodes or is_scaled_mm:
1191
+ if epilogue_nodes:
1192
+ (
1193
+ input_names,
1194
+ output_names,
1195
+ var_name_to_buffer_name,
1196
+ evt_py_code,
1197
+ ) = CutlassEVTCodegen.ir_to_evt_python_code(
1198
+ Y.get_name(), epilogue_nodes, V.kernel.removed_buffers
1199
+ )
1200
+
1201
+ # TODO: mlazos remove this by returning buffer metadata from
1202
+ # ir_to_evt_python code
1203
+ for name, buf in (
1204
+ V.graph.name_to_buffer | V.graph.graph_inputs
1205
+ ).items():
1206
+ if name not in name_to_buffer:
1207
+ name_to_buffer[name] = buf # type: ignore[assignment]
1208
+
1209
+ D_output_name = var_name_to_buffer_name["D"]
1210
+ D_output_buffer = name_to_buffer[D_output_name]
1211
+ Y = D_output_buffer # type: ignore[assignment]
1212
+ # Interestingly, I don't think the rest of the layout matters here since we
1213
+ # use the properties of the Y buffer to fill in D's properties in the epilogue
1214
+ # args. This is needed though because it defines types expected in the epilogue args.
1215
+ op.D.element = cutlass_utils.torch_dtype_to_cutlass_type(
1216
+ D_output_buffer.get_dtype()
1217
+ )
1218
+
1219
+ assert output_names, "There should be at least one write"
1220
+
1221
+ epilogue_inputs = [name_to_buffer[name] for name in input_names]
1222
+ outputs = [name_to_buffer[name] for name in output_names]
1223
+ else: # Scaled MM, we read the two scale matrices (and optional bias) and write a single output
1224
+ bias = None if len(self.input_nodes) < 5 else self.input_nodes[4]
1225
+ bias_name = bias.get_name() if bias else None
1226
+
1227
+ (
1228
+ evt_read_names,
1229
+ var_name_to_buffer_name,
1230
+ evt_py_code,
1231
+ ) = scaled_mm_evt(
1232
+ self.input_nodes[2].get_name(), # scale_A
1233
+ self.input_nodes[3].get_name(), # scale_B
1234
+ bias_name,
1235
+ Y.get_name(),
1236
+ )
1237
+
1238
+ input_names = list(evt_read_names)
1239
+ output_names = [] # We only need Y
1240
+ epilogue_inputs = [self.input_nodes[2], self.input_nodes[3]]
1241
+ if bias:
1242
+ epilogue_inputs.append(bias)
1243
+ outputs = []
1244
+
1245
+ acc_dtype = cutlass_utils.get_accumulator_dtype(
1246
+ [X.get_dtype(), W.get_dtype()]
1247
+ )
1248
+ assert acc_dtype, "Could not determine accumulator dtype"
1249
+
1250
+ evt_name, evt_args, evt_code, evt_arg_renames = self._render_evt(
1251
+ op,
1252
+ evt_py_code,
1253
+ var_name_to_buffer_name,
1254
+ name_to_buffer,
1255
+ Y.get_dtype(),
1256
+ acc_dtype,
1257
+ )
1258
+
1259
+ inputs = [
1260
+ X,
1261
+ W,
1262
+ Bias,
1263
+ *epilogue_inputs, # type: ignore[list-item]
1264
+ Y,
1265
+ *extra_inputs,
1266
+ ]
1267
+ input_names = [evt_arg_renames.get(name) for name in input_names]
1268
+ output_names = [evt_arg_renames.get(name) for name in output_names]
1269
+
1270
+ names_str = ",".join(
1271
+ ["X", "W", "Bias", *input_names, "Y", *output_names, *extra_names]
1272
+ )
1273
+ else:
1274
+ evt_name = None
1275
+ outputs = [Y]
1276
+ evt_args = f"{{ElementComputeEpilogue({self.alpha}), ElementComputeEpilogue({self.beta})}}"
1277
+ evt_code = ""
1278
+
1279
+ kernel_call_signature = kernel.def_kernel(
1280
+ inputs=inputs, # type: ignore[arg-type]
1281
+ outputs=outputs, # type: ignore[arg-type]
1282
+ names_str=names_str,
1283
+ input_reorder=input_reorder,
1284
+ )
1285
+
1286
+ test_call_statement = self.test_call_statement(kernel, inputs, names_str)
1287
+
1288
+ instance_definition, instance_type = self._define_gemm_instance(op, evt_name)
1289
+ dynamic_cluster = self._dynamic_cluster_block(op)
1290
+
1291
+ options = {
1292
+ "alpha": self.alpha,
1293
+ "beta": self.beta,
1294
+ "X": X,
1295
+ "W": W,
1296
+ "Y": Y,
1297
+ "kernel_call_signature": kernel_call_signature,
1298
+ "Bias": Bias,
1299
+ "epilogue_template": epilogue_template,
1300
+ "argument_template": argument_template,
1301
+ "should_swap_xw": should_swap_xw,
1302
+ "template": self,
1303
+ "kernel": kernel,
1304
+ "instance_definition": instance_definition,
1305
+ "instance_type": instance_type,
1306
+ "input_reorder": self.input_reorder,
1307
+ "epilogue_args": evt_args,
1308
+ "test_call_statement": test_call_statement,
1309
+ "op_conf_name": op.configuration_name(),
1310
+ "epilogue_visitor_tree": evt_code,
1311
+ "dynamic_cluster": dynamic_cluster,
1312
+ }
1313
+ options.update(dict(zip(extra_names, extra_inputs)))
1314
+ res = self._template_from_string(self._get_template()).render(**options)
1315
+ if inductor_cutlass_config.generate_test_runner and not is_dynamic(
1316
+ X, W, Y, Bias
1317
+ ):
1318
+ test_runner_code = self._template_from_string(
1319
+ GEMM_STANDALONE_RUNNER_TEMPLATE
1320
+ ).render(**options)
1321
+ res += "\n\n" + test_runner_code
1322
+
1323
+ # splice to remove trailing spaces in each line
1324
+ buf = IndentedBuffer()
1325
+ buf.splice(res)
1326
+ return buf.getvalue()
1327
+
1328
+ def test_call_statement(
1329
+ self,
1330
+ kernel,
1331
+ input_nodes,
1332
+ names_str: str = "",
1333
+ ) -> str:
1334
+ """
1335
+ Helper method to render the Cutlass CUDA C++ code required for calling the GEMM operation in the standalone
1336
+ test runner that might also be generated along with the rest of the code, if the corresponding config is
1337
+ enabled.
1338
+
1339
+ Returns a C++ statement that calls the GEMM operation with the correct arguments.
1340
+ """
1341
+ _, __, arg_types = kernel.args.cpp_argdefs(cutlass_utils.DTYPE_TO_CUTLASS_TYPE)
1342
+ arg_names = [name.strip() for name in names_str.strip().split(",")]
1343
+ arg_names = self._update_arg_names_for_test_call_statement(
1344
+ arg_names, input_nodes
1345
+ )
1346
+ arguments = [
1347
+ f"(({arg_type}){arg_name}_data.get())"
1348
+ for arg_type, arg_name in zip(arg_types, arg_names)
1349
+ ]
1350
+ return f"{kernel.kernel_name}({', '.join(arguments)}, M, N, K, B, lda, ldb, ldc, ldd, 0, 0, 0, swizzle, workspace_size_ptr, (uint8_t*)workspace_data.get(), 0);" # noqa: B950
1351
+
1352
+ def _render_evt(
1353
+ self,
1354
+ op: GemmOperation,
1355
+ evt_py_code: str,
1356
+ buffer_renames: dict[str, str],
1357
+ name_to_buffer: dict[str, Buffer],
1358
+ output_dtype: torch.dtype,
1359
+ accumulator_dtype: torch.dtype,
1360
+ ) -> tuple[str, str, str, EVTArgRenames]: # type: ignore[name-defined] # noqa: F821
1361
+ raise NotImplementedError("_render_evt in CUTLASSGemmTemplate not implemented")
1362
+
1363
+
1364
+ class CUTLASS3xGemmTemplate(CUTLASSGemmTemplate):
1365
+ """
1366
+ CUTLASS 3x GEMM Template, which is used to generate CUTLASS GEMM kernels
1367
+ including those which allow flexible fusions with epilogues.
1368
+ """
1369
+
1370
+ @staticmethod
1371
+ def add_cutlass_gemm_choices(
1372
+ choices: list[ChoiceCaller],
1373
+ layout: ir.Layout,
1374
+ input_nodes: list[Buffer],
1375
+ alpha: Union[float, int] = 1,
1376
+ beta: Union[float, int] = 0,
1377
+ input_reorder: Optional[list[int]] = None,
1378
+ use_fast_accum: Optional[bool] = None,
1379
+ **extra_kwargs,
1380
+ ) -> None:
1381
+ template = CUTLASS3xGemmTemplate(
1382
+ input_nodes,
1383
+ layout,
1384
+ alpha,
1385
+ beta,
1386
+ input_reorder,
1387
+ use_fast_accum,
1388
+ )
1389
+ template._add_cutlass_gemm_choices(
1390
+ choices, layout, input_nodes, alpha, beta, input_reorder, **extra_kwargs
1391
+ )
1392
+
1393
+ @staticmethod
1394
+ @functools.lru_cache(1)
1395
+ def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821
1396
+ import cutlass_library.library as cutlass_lib
1397
+
1398
+ return [cutlass_lib.GemmKind.Universal3x]
1399
+
1400
+ def _get_template(self) -> str:
1401
+ return GEMM_TEMPLATE_CUTLASS_3X
1402
+
1403
+ def _get_template_args(
1404
+ self,
1405
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1406
+ ) -> tuple[str, Optional[str]]:
1407
+ return (GEMM_ARGS_CUTLASS_3X, GEMM_ARGS_CUTLASS_3X_EPILOGUE)
1408
+
1409
+ @staticmethod
1410
+ def _has_tma_epilogue( # noqa: F821 # type: ignore[arg-type,name-defined]
1411
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined,arg-type] # noqa: F821
1412
+ ) -> bool: # type: ignore[name-defined]
1413
+ """Helper method: Determine whether a given Cutlass GEMM op has a TMA Epilogue"""
1414
+ assert cutlass_utils.try_import_cutlass()
1415
+ import cutlass_library.library as cutlass_lib
1416
+
1417
+ result = False
1418
+ if op.gemm_kind == cutlass_lib.GemmKind.Universal3x:
1419
+ epilogue_schedule_str = str(op.epilogue_schedule).split(".")[-1]
1420
+ result = epilogue_schedule_str.lower().startswith("tma")
1421
+ return result
1422
+
1423
+ @staticmethod
1424
+ def supports_epilogue_fusion(op: GemmOperation) -> bool:
1425
+ return CUTLASS3xGemmTemplate._has_tma_epilogue(op)
1426
+
1427
+ def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool:
1428
+ """
1429
+ Evaluates whether input layouts are compatible for General Matrix Multiply (GEMM).
1430
+
1431
+ This function checks compatibility of A, B, and possibly C operand layouts for
1432
+ a General Matrix Multiply (GEMM) operation, expressed as 'alpha * matmul(A, B) + beta * C'.
1433
+ It verifies requirements such as matching data types, minimum rank, and suitability
1434
+ for broadcasting, as defined by PyTorch operations like `torch.matmul`, `torch.aten.mm`,
1435
+ `addmm`, `bmm`, `baddbmm`, etc.
1436
+
1437
+ Args:
1438
+ layouts (List[Layout]): List containing 2 or 3 Layout objects representing
1439
+ the input matrices A, B, and possibly C.
1440
+
1441
+ Returns:
1442
+ bool: True if layouts are GEMM compatible, otherwise False.
1443
+ """
1444
+ assert 2 <= len(layouts) <= 5
1445
+ # Check if A and B are compatible
1446
+ A_layout, B_layout = layouts[:2]
1447
+ if len(A_layout.size) < 1:
1448
+ return False
1449
+ if len(B_layout.size) < 1:
1450
+ return False
1451
+ A_size = list(V.graph.sizevars.size_hints(A_layout.size))
1452
+ B_size = list(V.graph.sizevars.size_hints(B_layout.size))
1453
+ if len(A_size) < 2:
1454
+ A_size.insert(0, 1)
1455
+ if len(B_size) < 2:
1456
+ A_size.insert(1, 1)
1457
+ # Are batch dims broadcastable?
1458
+ while len(A_size) < len(B_size):
1459
+ A_size.insert(0, 1)
1460
+ while len(B_size) < len(A_size):
1461
+ B_size.insert(0, 1)
1462
+ K = max(A_size[-1], B_size[-2])
1463
+ M = A_size[-2]
1464
+ N = B_size[-1]
1465
+ if K != A_size[-1] and A_size[-1] != 1:
1466
+ return False
1467
+ if K != B_size[-2] and B_size[-1] != 1:
1468
+ return False
1469
+ # check batch dim broadcastable
1470
+ for i in range(len(A_size) - 2):
1471
+ if A_size[i] != B_size[i] and A_size[i] != 1 and B_size[i] != 1:
1472
+ return False
1473
+ if len(layouts) == 3:
1474
+ C_layout = layouts[2]
1475
+ C_size = [V.graph.sizevars.size_hint(i) for i in C_layout.size]
1476
+ while len(C_size) < len(A_size):
1477
+ C_size.insert(0, 1)
1478
+ # check batch dims
1479
+ for i in range(len(A_size) - 2):
1480
+ bd = max(A_size[i], B_size[i])
1481
+ if bd != C_size[i] and C_size[i] != 1:
1482
+ return False
1483
+ if len(C_size) > len(A_size):
1484
+ # This may happen if the last elements of C are contiguous and
1485
+ # their multiplied size equals the last dim size of B
1486
+ if M != C_size[len(A_size) - 2] and C_size[len(A_size) - 2] != 1:
1487
+ return False
1488
+ remaining_size = 1
1489
+ for i in range(len(A_size) - 1, len(C_size)):
1490
+ remaining_size *= C_size[i]
1491
+ if N != remaining_size and remaining_size != 1:
1492
+ return False
1493
+ return True
1494
+ assert len(C_size) == len(A_size)
1495
+ if M != C_size[-2] and C_size[-2] != 1:
1496
+ return False
1497
+ if N != C_size[-1] and C_size[-1] != 1:
1498
+ return False
1499
+ return True
1500
+
1501
+ def _render_evt(
1502
+ self,
1503
+ op: GemmOperation,
1504
+ evt_py_code: str,
1505
+ var_name_to_buffer_name: dict[str, str],
1506
+ name_to_buffer: dict[str, Buffer],
1507
+ output_dtype: torch.dtype,
1508
+ accumulator_dtype: torch.dtype,
1509
+ ) -> tuple[str, str, str, EVTArgRenames]:
1510
+ from .lib_extensions.evt_extensions import create_example_tensors, trace
1511
+
1512
+ acc_dtype = torch_dtype_to_cutlass_type(accumulator_dtype)
1513
+ output_dtype = torch_dtype_to_cutlass_type(output_dtype)
1514
+
1515
+ examples = create_example_tensors(
1516
+ var_name_to_buffer_name,
1517
+ name_to_buffer, # type: ignore[arg-type]
1518
+ V.graph.sizevars.size_hint,
1519
+ )
1520
+ evt_name, evt_args, evt_code, arg_renames = trace(
1521
+ evt_py_code,
1522
+ examples,
1523
+ acc_dtype,
1524
+ output_dtype,
1525
+ op.tile_description, # type: ignore[attr-defined]
1526
+ op.epilogue_schedule, # type: ignore[attr-defined]
1527
+ {k: name_to_buffer[v] for k, v in var_name_to_buffer_name.items()}, # type: ignore[arg-type,misc]
1528
+ V.graph.sizevars.size_hint,
1529
+ )
1530
+
1531
+ return (
1532
+ evt_name,
1533
+ evt_args,
1534
+ evt_code,
1535
+ arg_renames,
1536
+ )
1537
+
1538
+ def _shape_match(
1539
+ self,
1540
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1541
+ ) -> bool:
1542
+ return True
1543
+
1544
+ def _alignment_match(
1545
+ self,
1546
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1547
+ ) -> bool:
1548
+ return True
1549
+
1550
+ def _set_bias_layout_and_alignment(
1551
+ self,
1552
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1553
+ ) -> bool:
1554
+ import cutlass_library.library as cutlass_lib
1555
+
1556
+ has_bias = len(self.input_nodes) == 3 and self.input_nodes[2] is not None
1557
+ if has_bias:
1558
+ Bias = self.input_nodes[2]
1559
+ # bias dtype
1560
+ op.C.element = cutlass_utils.torch_dtype_to_cutlass_type(
1561
+ Bias.get_layout().dtype
1562
+ )
1563
+
1564
+ # Bias layout
1565
+ bias_layout = CUTLASSGemmTemplate.cutlass_layout(Bias.get_layout())
1566
+ op.C.layout = bias_layout
1567
+
1568
+ # Bias alignment
1569
+ status = self.set_alignment(Bias.get_layout(), op.C)
1570
+ if not status:
1571
+ return False
1572
+ else:
1573
+ op.C.element = cutlass_lib.DataType.void
1574
+ return True
1575
+
1576
+ def _define_gemm_instance(
1577
+ self,
1578
+ op: GemmOperation,
1579
+ evt_name: Optional[str] = None,
1580
+ ) -> tuple[str, str]:
1581
+ """Defines and renders the Cutlass / CUDA C++ code for a given GEMM operation instance.
1582
+
1583
+ This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply
1584
+ forms a core part of a number of scientific applications, so this efficient and adaptable implementation is
1585
+ crucial.
1586
+
1587
+ Args:
1588
+ op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering.
1589
+
1590
+ Returns:
1591
+ tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++
1592
+ code (render) and the second part is the string that specifies the operation type.
1593
+ """
1594
+ assert cutlass_utils.try_import_cutlass()
1595
+ import cutlass_library.library as cutlass_lib
1596
+
1597
+ from .lib_extensions import gemm_operation_extensions as gemm_extensions
1598
+
1599
+ emitter = gemm_extensions.EmitGemmUniversal3xInstanceWithEVT(evt_name=evt_name) # type: ignore[call-arg]
1600
+
1601
+ if not hasattr(op, "epilogue_functor") or not isinstance(
1602
+ op.epilogue_functor, enum.Enum
1603
+ ):
1604
+ op = copy.deepcopy(op)
1605
+ op.epilogue_functor = cutlass_lib.EpilogueFunctor.LinearCombination
1606
+
1607
+ op_def = emitter.emit(op)
1608
+ pattern = re.compile(r"\s*struct\s(.*?)\s:")
1609
+ decl = [line for line in op_def.split("\n") if "struct " in line][-1]
1610
+
1611
+ match = pattern.match(decl)
1612
+ if match is None:
1613
+ raise RuntimeError("Invalid Gemm config: \n" + op_def)
1614
+ op_type = match.groups()[0]
1615
+ if op.gemm_kind == cutlass_lib.GemmKind.Universal3x:
1616
+ op_def += f"\n using {op_type}_device_type = cutlass::gemm::device::GemmUniversalAdapter<{op_type}>;\n"
1617
+ op_type = f"{op_type}_device_type"
1618
+
1619
+ return op_def, op_type
1620
+
1621
+ def _get_extra_inputs_and_names(
1622
+ self,
1623
+ op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821
1624
+ ) -> tuple[Optional[Buffer], list[Optional[Buffer]], list[str]]:
1625
+ Bias = self.input_nodes[2] if len(self.input_nodes) == 3 else None
1626
+ inputs: list[Optional[Buffer]] = []
1627
+ names: list[str] = []
1628
+ return (Bias, inputs, names)
1629
+
1630
+ def _update_arg_names_for_test_call_statement(
1631
+ self,
1632
+ arg_names: list[str],
1633
+ input_nodes: list[Buffer],
1634
+ ) -> list[str]:
1635
+ if input_nodes[2] is None:
1636
+ del arg_names[2]
1637
+ else:
1638
+ # Reorder them as Bias, A, B
1639
+ if self.input_reorder is not None:
1640
+ arg_names[0 : len(self.input_reorder)] = [
1641
+ arg_names[i] for i in self.input_reorder
1642
+ ]
1643
+ return arg_names
1644
+
1645
+ def render_gemm_arguments(
1646
+ self,
1647
+ argument_template: str,
1648
+ epilogue_template: str,
1649
+ should_swap_xw: bool,
1650
+ X: IRNode,
1651
+ W: IRNode,
1652
+ Bias: IRNode,
1653
+ Y: IRNode,
1654
+ alpha: float,
1655
+ beta: float,
1656
+ kernel: CUTLASSTemplateKernel,
1657
+ epilogue_args,
1658
+ ) -> str:
1659
+ """
1660
+ Render the Cutlass CUDA C++ code required for passing arguments to the GEMM operation.
1661
+
1662
+ Args:
1663
+ argument_template (str): Template for the GEMM operation arguments.
1664
+ epilogue_template (str): Template for the epilogue arguments.
1665
+ should_swap_xw (bool): Determines whether X, W operands should be swapped. If True, applies an explicit
1666
+ transpose operation to X and W.
1667
+ X (IRNode): The X input tensor.
1668
+ W (IRNode): The W input tensor.
1669
+ Bias (IRNode): The bias tensor.
1670
+ Y (IRNode): The output tensor.
1671
+ alpha (float): Scaling factor for the product of the inputs.
1672
+ beta (float): Scaling factor for the output tensor.
1673
+ kernel (CUTLASSTemplateKernel): CUDA Template kernel for the operation.
1674
+ epilogue_args (any): Additional arguments for the epilogue state.
1675
+
1676
+ Returns:
1677
+ str: A block of CUDA C++ code as a string, ready to be used as arguments for the GEMM operation.
1678
+
1679
+ Note: If `should_swap_xw` is True, a transpose operation will be applied to the X, W, Bias, and Y
1680
+ tensors. This operation also implies the M and N dimensions of Bias and GEMM output to be swapped
1681
+ before the function call.
1682
+ """
1683
+ options = {
1684
+ "alpha": alpha,
1685
+ "beta": beta,
1686
+ "X": X,
1687
+ "W": W,
1688
+ "Y": Y,
1689
+ "Bias": Bias,
1690
+ "template": self,
1691
+ "kernel": kernel,
1692
+ "M": "M",
1693
+ "N": "N",
1694
+ "epilogue_args": epilogue_args,
1695
+ }
1696
+ assert epilogue_template is not None
1697
+
1698
+ if should_swap_xw:
1699
+ # Swap
1700
+ def clone_with_transposed_stride(node: IRNode) -> IRNode:
1701
+ old_layout = node.get_layout()
1702
+ new_stride = list(old_layout.stride) # type: ignore[union-attr]
1703
+ new_stride[-2], new_stride[-1] = new_stride[-1], new_stride[-2]
1704
+ assert old_layout.device is not None
1705
+ new_layout = FixedLayout(
1706
+ old_layout.device,
1707
+ old_layout.dtype,
1708
+ list(old_layout.size), # type: ignore[union-attr]
1709
+ new_stride,
1710
+ old_layout.offset, # type: ignore[union-attr]
1711
+ )
1712
+ return Buffer(name=node.get_name(), layout=new_layout)
1713
+
1714
+ new_X = clone_with_transposed_stride(X)
1715
+ new_W = clone_with_transposed_stride(W)
1716
+ new_Bias = clone_with_transposed_stride(Bias)
1717
+ new_Y = clone_with_transposed_stride(Y)
1718
+ options["X"], options["W"], options["Bias"], options["Y"] = (
1719
+ new_W,
1720
+ new_X,
1721
+ new_Bias,
1722
+ new_Y,
1723
+ )
1724
+ options["M"], options["N"] = "N", "M"
1725
+
1726
+ epilogue_arguments = self._template_from_string(epilogue_template).render(
1727
+ **options
1728
+ )
1729
+ arguments = self._template_from_string(argument_template).render(
1730
+ epilogue_arguments=epilogue_arguments, **options
1731
+ )
1732
+
1733
+ return arguments
1734
+
1735
+
1736
+ class CUTLASS2xGemmTemplate(CUTLASSGemmTemplate):
1737
+ """CUTLASS 2x GEMM Template, which is used to generate CUTLASS 2x GEMM kernels"""
1738
+
1739
+ def __init__(
1740
+ self,
1741
+ input_nodes: list[Buffer],
1742
+ layout: Layout,
1743
+ alpha: float,
1744
+ beta: float,
1745
+ input_reorder: Optional[list[int]] = None,
1746
+ ):
1747
+ super().__init__(input_nodes, layout, alpha, beta, input_reorder)
1748
+
1749
+ @staticmethod
1750
+ def add_cutlass_gemm_choices(
1751
+ choices: list[ChoiceCaller],
1752
+ layout: ir.Layout,
1753
+ input_nodes: list[Buffer],
1754
+ alpha: Union[float, int] = 1,
1755
+ beta: Union[float, int] = 0,
1756
+ input_reorder: Optional[list[int]] = None,
1757
+ use_fast_accum: Optional[bool] = False,
1758
+ **extra_kwargs,
1759
+ ) -> None:
1760
+ template = CUTLASS2xGemmTemplate(
1761
+ input_nodes, layout, alpha, beta, input_reorder
1762
+ )
1763
+ template._add_cutlass_gemm_choices(
1764
+ choices, layout, input_nodes, alpha, beta, input_reorder, **extra_kwargs
1765
+ )
1766
+
1767
+ @staticmethod
1768
+ def _get_supported_ops() -> "list[cutlass_library.gemm_operation.GemmOperation]": # type: ignore[name-defined] # noqa: F821
1769
+ import cutlass_library.library as cutlass_lib
1770
+
1771
+ return [cutlass_lib.GemmKind.Universal, cutlass_lib.GemmKind.Sparse]
1772
+
1773
+ @staticmethod
1774
+ def _has_tma_epilogue(self) -> bool:
1775
+ return False
1776
+
1777
+ def _get_template(self) -> str:
1778
+ return GEMM_TEMPLATE_CUTLASS_2X
1779
+
1780
+ def _get_template_args(
1781
+ self,
1782
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1783
+ ) -> tuple[str, Optional[str]]:
1784
+ import cutlass_library.library as cutlass_lib
1785
+
1786
+ if op.gemm_kind == cutlass_lib.GemmKind.Sparse:
1787
+ return (GEMM_ARGS_SPARSE_CUTLASS_2X, None)
1788
+
1789
+ return (GEMM_ARGS_CUTLASS_2X, None)
1790
+
1791
+ def _are_inputs_layout_compatible(self, layouts: list[Layout]) -> bool:
1792
+ """
1793
+ Evaluates whether input layouts are compatible for set of operations supported by this class.
1794
+
1795
+ Args:
1796
+ layouts (List[Layout]): List containing Layout objects representing
1797
+ the input matrices.
1798
+
1799
+ Returns:
1800
+ bool: True if layouts are GEMM compatible, otherwise False.
1801
+ """
1802
+ assert len(layouts) == 2 or len(layouts) == 3
1803
+ # Check if A and B are compatible
1804
+ A_layout, B_layout = layouts[:2]
1805
+ if len(A_layout.size) != 2:
1806
+ return False
1807
+ if len(B_layout.size) != 2:
1808
+ return False
1809
+ A_size = [int(i) for i in A_layout.size]
1810
+ B_size = [int(i) for i in B_layout.size]
1811
+ K = max(A_size[1], B_size[0])
1812
+ return (K == A_size[1] or K == 2 * A_size[1]) and K == B_size[0]
1813
+
1814
+ def _shape_match(
1815
+ self,
1816
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1817
+ ) -> bool:
1818
+ import cutlass_library.library as cutlass_lib
1819
+
1820
+ X, W = self.input_nodes[0], self.input_nodes[1]
1821
+
1822
+ if op.gemm_kind == cutlass_lib.GemmKind.Sparse:
1823
+ return X.get_size()[1] * 2 == W.get_size()[0]
1824
+
1825
+ return X.get_size()[1] == W.get_size()[0]
1826
+
1827
+ def _alignment_match(
1828
+ self,
1829
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1830
+ ) -> bool:
1831
+ import cutlass_library.library as cutlass_lib
1832
+
1833
+ if op.gemm_kind != cutlass_lib.GemmKind.Sparse:
1834
+ return True
1835
+
1836
+ # SparseGemm in CUTLASS has specific alignment check that for
1837
+ # small k could make some of the choices throw kMisalignedOperand
1838
+ # CUTLASS error when run, see:
1839
+ # https://github.com/NVIDIA/cutlass/blob/e01b9b5029b7caca5a43c29f7d2714d7cf1dcae8/include/cutlass/gemm/kernel/sparse_gemm.h#L198-L200 # noqa: B950
1840
+ # So, let's skip these choices if that would be the case.
1841
+ X = self.input_nodes[0]
1842
+ return (X.get_size()[1] * 2) % op.tile_description.tile_shape[2] == 0
1843
+
1844
+ def _set_bias_layout_and_alignment(
1845
+ self,
1846
+ op: "cutlass_library.gemm_op.GemmOperation", # type: ignore[name-defined] # noqa: F821
1847
+ ) -> bool:
1848
+ import cutlass_library.library as cutlass_lib
1849
+
1850
+ if op.gemm_kind == cutlass_lib.GemmKind.Sparse:
1851
+ op.C.layout = op.D.layout
1852
+ return True
1853
+
1854
+ if len(self.input_nodes) >= 3 and self.input_nodes[2] is not None:
1855
+ Bias = self.input_nodes[2]
1856
+ bias_layout = CUTLASSGemmTemplate.cutlass_layout(Bias.get_layout())
1857
+ if bias_layout != op.D.layout:
1858
+ # For cutlass2, bias and output layout must match
1859
+ return False
1860
+ if not self.set_alignment(Bias.get_layout(), op.C):
1861
+ return False
1862
+ else:
1863
+ op.C.layout = op.D.layout
1864
+ return True
1865
+
1866
+ def _define_gemm_instance(
1867
+ self,
1868
+ op: GemmOperation,
1869
+ evt_name: Optional[str] = None,
1870
+ ) -> tuple[str, str]:
1871
+ """Defines and renders the Cutlass / CUDA C++ code for a given GEMM operation instance.
1872
+
1873
+ This function uses the Cutlass library to generate key parts of the codegen process. General Matrix Multiply
1874
+ forms a core part of a number of scientific applications, so this efficient and adaptable implementation is
1875
+ crucial.
1876
+
1877
+ Args:
1878
+ op (cutlass_library.gemm_op.GemmOperation): This is the core GEMM operation that we are defining and rendering.
1879
+
1880
+ Returns:
1881
+ tuple[str, str]: A tuple where the first part is a string that constitutes the defined GEMM operation in C++
1882
+ code (render) and the second part is the string that specifies the operation type.
1883
+ """
1884
+ assert cutlass_utils.try_import_cutlass()
1885
+ import cutlass_library.gemm_operation as cutlass_gemm_op
1886
+ import cutlass_library.library as cutlass_lib
1887
+
1888
+ if op.gemm_kind == cutlass_lib.GemmKind.Sparse:
1889
+ emitter = cutlass_gemm_op.EmitSparseGemmInstance()
1890
+ else:
1891
+ emitter = cutlass_gemm_op.EmitGemmInstance()
1892
+ op_def = emitter.emit(op)
1893
+ op_def = op_def.replace(
1894
+ "cutlass::gemm::device::Gemm", "cutlass::gemm::device::GemmUniversal"
1895
+ )
1896
+ if op.gemm_kind != cutlass_lib.GemmKind.Sparse:
1897
+ op_def = op_def.replace("false,", "")
1898
+ pattern = re.compile(r"\s*using\s(.*?)\s=")
1899
+ decl = op_def.split("\n")[2]
1900
+
1901
+ match = pattern.match(decl)
1902
+ if match is None:
1903
+ raise RuntimeError("Invalid Gemm config: \n" + op_def)
1904
+ op_type = match.groups()[0]
1905
+ return op_def, op_type
1906
+
1907
+ def _get_extra_inputs_and_names(
1908
+ self,
1909
+ op: "cutlass_gemm_op.GemmOperation" = None, # type: ignore[name-defined] # noqa: F821
1910
+ ) -> tuple[Optional[Buffer], list[Optional[Buffer]], list[str]]:
1911
+ import cutlass_library.library as cutlass_lib
1912
+
1913
+ if op.gemm_kind == cutlass_lib.GemmKind.Sparse:
1914
+ Bias = None
1915
+ Meta = self.input_nodes[2]
1916
+ else:
1917
+ Bias = None if len(self.input_nodes) == 2 else self.input_nodes[2]
1918
+ Meta = None
1919
+ inputs = [Meta]
1920
+ names = ["Meta"]
1921
+ return (Bias, inputs, names)
1922
+
1923
+ def _update_arg_names_for_test_call_statement(
1924
+ self,
1925
+ arg_names: list[str],
1926
+ input_nodes: list[Buffer],
1927
+ ) -> list[str]:
1928
+ if input_nodes[3] is None:
1929
+ del arg_names[3]
1930
+ if input_nodes[2] is None:
1931
+ del arg_names[2]
1932
+ return arg_names
1933
+
1934
+ def render_gemm_arguments(
1935
+ self,
1936
+ instance_type: str,
1937
+ argument_template: str,
1938
+ epilogue_template: str,
1939
+ should_swap_xw: bool,
1940
+ X: IRNode,
1941
+ W: IRNode,
1942
+ Bias: IRNode,
1943
+ Meta: IRNode,
1944
+ Y: IRNode,
1945
+ alpha: float,
1946
+ beta: float,
1947
+ kernel: CUTLASSTemplateKernel,
1948
+ epilogue_args,
1949
+ ) -> str:
1950
+ """
1951
+ Render the Cutlass CUDA C++ code required for passing arguments to the GEMM operation.
1952
+
1953
+ Args:
1954
+ instance_type (str): GEMM instance type.
1955
+ argument_template (str): Template for the GEMM operation arguments.
1956
+ epilogue_template (str): Template for the epilogue arguments.
1957
+ should_swap_xw (bool): Determines whether X, W operands should be swapped. If True, applies an explicit
1958
+ transpose operation to X and W.
1959
+ X (IRNode): The X input tensor.
1960
+ W (IRNode): The W input tensor.
1961
+ Bias (IRNode): The bias tensor.
1962
+ Meta (IRNode): The meta tensor.
1963
+ Y (IRNode): The output tensor.
1964
+ alpha (float): Scaling factor for the product of the inputs.
1965
+ beta (float): Scaling factor for the output tensor.
1966
+ kernel (CUTLASSTemplateKernel): CUDA Template kernel for the operation.
1967
+ epilogue_args (any): Additional arguments for the epilogue state.
1968
+
1969
+ Returns:
1970
+ str: A block of CUDA C++ code as a string, ready to be used as arguments for the GEMM operation.
1971
+
1972
+ Note: If `should_swap_xw` is True, a transpose operation will be applied to the X, W, Bias, and Y
1973
+ tensors. This operation also implies the M and N dimensions of Bias and GEMM output to be swapped
1974
+ before the function call.
1975
+ """
1976
+ options = {
1977
+ "instance_type": instance_type,
1978
+ "alpha": alpha,
1979
+ "beta": beta,
1980
+ "X": X,
1981
+ "W": W,
1982
+ "Y": Y,
1983
+ "Bias": Bias,
1984
+ "Meta": Meta,
1985
+ "template": self,
1986
+ "kernel": kernel,
1987
+ "M": "M",
1988
+ "N": "N",
1989
+ "epilogue_args": epilogue_args,
1990
+ }
1991
+
1992
+ if epilogue_template is None:
1993
+ arguments = self._template_from_string(argument_template).render(
1994
+ split_k=1, **options
1995
+ )
1996
+ return arguments
1997
+
1998
+ epilogue_arguments = self._template_from_string(epilogue_template).render(
1999
+ **options
2000
+ )
2001
+ arguments = self._template_from_string(argument_template).render(
2002
+ epilogue_arguments=epilogue_arguments, **options
2003
+ )
2004
+
2005
+ return arguments
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/kernel.py ADDED
@@ -0,0 +1,688 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 .utils import DTYPE_TO_CUTLASS_TYPE
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from .template import ArgInfo
24
+
25
+ from ...autotune_process import CUTLASSBenchmarkRequest
26
+ from ...ir import (
27
+ Buffer,
28
+ ChoiceCaller,
29
+ CUTLASSTemplateBuffer,
30
+ IRNode,
31
+ Layout,
32
+ PrimitiveInfoType,
33
+ TensorBox,
34
+ )
35
+ from ...utils import sympy_product
36
+ from ...virtualized import V
37
+ from ..common import (
38
+ CSEVariable,
39
+ IndentedBuffer,
40
+ Kernel,
41
+ OpOverrides,
42
+ WorkspaceArg,
43
+ WorkspaceZeroMode,
44
+ )
45
+ from ..cpp_utils import CppPrinter, DTYPE_TO_CPP
46
+
47
+
48
+ if TYPE_CHECKING:
49
+ from torch._inductor.codegen.cutlass.template import CUTLASSTemplate
50
+
51
+ log = logging.getLogger(__name__)
52
+
53
+ cexpr = CppPrinter().doprint
54
+
55
+
56
+ def _normalize_idx(index: int, total_length: int) -> int:
57
+ return index if index >= 0 else index + total_length
58
+
59
+
60
+ ValidLayoutSymbols = Literal["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"]
61
+ ValidLayoutAttrs = Literal["size", "stride"]
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class LayoutArg:
66
+ node: IRNode
67
+ symbol: ValidLayoutSymbols
68
+ attr: ValidLayoutAttrs
69
+ dim: int
70
+
71
+ def matches(self, node, attr, dim) -> bool:
72
+ return self.node == node and self.attr == attr and self.dim == dim
73
+
74
+
75
+ class CUTLASSKernel(Kernel):
76
+ """
77
+ Baseclass for Cutlass based Kernels
78
+ """
79
+
80
+ overrides = OpOverrides # type: ignore[assignment]
81
+
82
+ def __init__(self, *args, **kwargs) -> None:
83
+ super().__init__(*args, **kwargs)
84
+ self.layout_args: dict[str, list[LayoutArg]] = defaultdict(list)
85
+ self.size_args: list[Union[Expr, int]] = []
86
+ # Mapping from arg name to IRNode.
87
+ self.named_nodes: dict[str, IRNode] = {}
88
+
89
+ def find_symbol(
90
+ self, node: IRNode, attr: ValidLayoutAttrs, dim: int
91
+ ) -> Optional[str]:
92
+ arg = self.find_layout_arg(node, attr, dim)
93
+ return arg.symbol if arg else None
94
+
95
+ def find_layout_arg(
96
+ self, node: IRNode, attr: ValidLayoutAttrs, dim: int
97
+ ) -> Optional[LayoutArg]:
98
+ matches = [
99
+ arg
100
+ for arg in itertools.chain.from_iterable(self.layout_args.values())
101
+ if arg.matches(node, attr, dim)
102
+ ]
103
+ if len(matches) >= 1:
104
+ # Verify all matches have the same node, attribute, and dimension
105
+ # And if they come from the same node, whichever symbol we use is fine.
106
+ # if in runtime the logic changes, this would trigger guard
107
+ first_match = matches[0]
108
+ if not all(
109
+ match.node == first_match.node
110
+ and match.attr == first_match.attr
111
+ and match.dim == first_match.dim
112
+ for match in matches
113
+ ):
114
+ raise AssertionError("All matching layout args should be identical")
115
+ return first_match
116
+ return None
117
+
118
+ def add_layout_arg(
119
+ self, symbol: ValidLayoutSymbols, node: IRNode, attr: ValidLayoutAttrs, dim: int
120
+ ):
121
+ arg = LayoutArg(node, symbol, attr, dim)
122
+ self.layout_args[symbol].append(arg)
123
+
124
+ def init_layout_args(self) -> None:
125
+ X = self.named_nodes["X"]
126
+ W = self.named_nodes["W"]
127
+ Y = self.named_nodes["Y"]
128
+ Bias = self.named_nodes.get("Bias", None)
129
+ x_mdim = _normalize_idx(-2, len(X.get_size()))
130
+ x_kdim = _normalize_idx(-1, len(X.get_size()))
131
+ w_kdim = _normalize_idx(-2, len(W.get_size()))
132
+ w_ndim = _normalize_idx(-1, len(W.get_size()))
133
+ y_mdim = _normalize_idx(-2, len(Y.get_size()))
134
+ y_ndim = _normalize_idx(-1, len(Y.get_size()))
135
+ self.add_layout_arg("M", X, "size", x_mdim)
136
+ self.add_layout_arg("K", X, "size", x_kdim)
137
+ self.add_layout_arg("K", W, "size", w_kdim)
138
+ self.add_layout_arg("N", W, "size", w_ndim)
139
+ self.add_layout_arg("M", Y, "size", y_mdim)
140
+ self.add_layout_arg("N", Y, "size", y_ndim)
141
+ if len(X.get_size()) > 2:
142
+ self.add_layout_arg("B", X, "size", 0)
143
+
144
+ lda_dim = self.find_ld_idx(X)
145
+ ldb_dim = self.find_ld_idx(W)
146
+ ldc_dim = self.find_ld_idx(Bias) if Bias else None
147
+ ldd_dim = self.find_ld_idx(Y)
148
+ self.add_layout_arg("lda", X, "stride", lda_dim)
149
+ self.add_layout_arg("ldb", W, "stride", ldb_dim)
150
+ if Bias is not None and ldc_dim is not None:
151
+ self.add_layout_arg("ldc", Bias, "stride", ldc_dim)
152
+ self.add_layout_arg("ldd", Y, "stride", ldd_dim)
153
+
154
+ def get_layout_args(self) -> tuple[Union[Expr, int], ...]:
155
+ X = self.named_nodes["X"]
156
+ W = self.named_nodes["W"]
157
+ Y = self.named_nodes["Y"]
158
+ Bias = self.named_nodes.get("Bias", None)
159
+ mdim = _normalize_idx(-2, len(X.get_size()))
160
+ ndim = _normalize_idx(-1, len(W.get_size()))
161
+ kdim = _normalize_idx(-1, len(X.get_size()))
162
+
163
+ def get_ld(node) -> Union[Expr, int]:
164
+ dim = self.find_ld_idx(node)
165
+ return node.get_stride()[dim]
166
+
167
+ M = X.get_size()[mdim]
168
+ N = W.get_size()[ndim]
169
+ K = X.get_size()[kdim]
170
+ B = X.get_size()[0] if len(X.get_size()) > 2 else 1
171
+ LDA = get_ld(X)
172
+ LDB = get_ld(W)
173
+ LDC = get_ld(Bias) if Bias else 0
174
+ LDD = get_ld(Y)
175
+ return (M, N, K, B, LDA, LDB, LDC, LDD)
176
+
177
+ def get_dynamic_shape_args(self) -> list[Union[Expr, int]]:
178
+ return [*self.get_layout_args(), *self.size_args]
179
+
180
+ def get_offset_args(self) -> list[Expr]:
181
+ return [node.get_layout().offset for node in self.named_nodes.values()]
182
+
183
+ @staticmethod
184
+ def find_ld_idx(node: IRNode) -> int:
185
+ strides = node.get_stride()
186
+ # Handle 1D tensor case
187
+ if V.graph.sizevars.statically_known_equals(strides[-1], 1):
188
+ return _normalize_idx(-2, len(strides))
189
+
190
+ assert V.graph.sizevars.statically_known_equals(strides[-2], 1), strides[-2]
191
+ return _normalize_idx(-1, len(strides))
192
+
193
+
194
+ class CUTLASSTemplateKernel(CUTLASSKernel):
195
+ """
196
+ Template kernels defined by Cutlass in C++.
197
+ """
198
+
199
+ _EXTRA_CPP_ARGS = "size_t* workspace_size, uint8_t* workspace, cudaStream_t stream"
200
+
201
+ def __init__(
202
+ self,
203
+ kernel_name: str,
204
+ runtime_arg_info: list["ArgInfo"],
205
+ runtime_arg_values: list[Any],
206
+ ) -> None:
207
+ """
208
+ Initializes a new instance of the CUTLASSTemplateKernel class.
209
+
210
+ Args:
211
+ kernel_name (str): The name of the kernel.
212
+ """
213
+ super().__init__()
214
+ self.kernel_name = kernel_name
215
+ self.runtime_arg_info = runtime_arg_info
216
+ self.runtime_arg_values = runtime_arg_values
217
+
218
+ def check_not_null(self, node: IRNode) -> str:
219
+ """
220
+ Generates code to check that a node is not null.
221
+ """
222
+ if node is None:
223
+ return ""
224
+
225
+ size_str = self.size(node, 0, -1)
226
+ name_str = self.arg_name(node)
227
+ if name_str is None:
228
+ return ""
229
+
230
+ res = IndentedBuffer(initial_indent=2)
231
+ res.tabwidth = 1
232
+ res.splice(
233
+ f"""
234
+ {{
235
+ if (!{name_str}) {{
236
+ int64_t {name_str}_size = {size_str};
237
+ if ({name_str}_size > 0) {{
238
+ throw std::runtime_error("input {name_str} is null but size is not 0!");
239
+ }}
240
+ }}
241
+ }}
242
+ """
243
+ )
244
+ return res.getvalue()
245
+
246
+ def get_signature(self) -> str:
247
+ return self.signature
248
+
249
+ def def_kernel(
250
+ self,
251
+ inputs: list[IRNode],
252
+ outputs: list[IRNode],
253
+ names_str: str = "",
254
+ input_reorder: Optional[list[int]] = None,
255
+ ) -> str:
256
+ """
257
+ Hook called from template code to generate function definition and
258
+ needed args.
259
+
260
+ Args:
261
+ inputs: List of input IRNodes
262
+ outputs: List of output IRNodes
263
+ names_str: Comma separated list of input + output argument names.
264
+ input_reorder: The actual order of input nodes.
265
+ e.g. The template might have input argument defined as [X, W, Bias],
266
+ and the actual input passed into this template could be [Bias, X, W].
267
+ In this case, the `input_reorder` would be [2, 0, 1].
268
+ additional_size_args: Additional size arguments for epilogue inputs
269
+ """
270
+ # NB: name order matters here, it's used to match up offsets
271
+ names = [x.strip() for x in names_str.strip().split(",")]
272
+ if len(inputs) + len(outputs) != len(names):
273
+ raise RuntimeError(
274
+ f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}"
275
+ )
276
+
277
+ if input_reorder is not None:
278
+ assert len(inputs) == len(input_reorder)
279
+ else:
280
+ input_reorder = list(range(len(inputs)))
281
+
282
+ for idx in input_reorder:
283
+ name = names[idx]
284
+ node = inputs[idx]
285
+ if node is not None:
286
+ self.named_nodes[name] = node
287
+ self.args.input_buffers[node.get_name()] = name
288
+
289
+ free_symbols: OrderedSet[Expr] = OrderedSet()
290
+ for name, node in zip(names[len(inputs) : len(inputs) + len(outputs)], outputs):
291
+ if node is not None:
292
+ # NB: named nodes must be populated in the order of names
293
+ self.named_nodes[name] = node
294
+ self.args.output_buffers[node.get_name()] = name
295
+
296
+ if name not in (
297
+ "X",
298
+ "W",
299
+ "Bias",
300
+ "Y",
301
+ ): # we handle these symbolic shapes explicitly
302
+ for expr in itertools.chain(node.get_size(), node.get_stride()):
303
+ if isinstance(expr, Expr):
304
+ for s in expr.free_symbols:
305
+ free_symbols.add(s) # type: ignore[arg-type]
306
+
307
+ arg_defs, *_ = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE)
308
+
309
+ self.init_layout_args()
310
+ size_vars = ["M", "N", "K", "B", "lda", "ldb", "ldc", "ldd"]
311
+ size_vars.extend(str(s) for s in free_symbols)
312
+ self.size_args.extend(free_symbols)
313
+ size_args = [f"const int {s}" for s in size_vars]
314
+ offset_args = [f"const int {name}_offset" for name in self.named_nodes]
315
+ runtime_arg_decls = ",".join(
316
+ [f"{arg.ty} {arg.name}" for arg in self.runtime_arg_info]
317
+ )
318
+ if runtime_arg_decls:
319
+ runtime_arg_decls += ", "
320
+
321
+ signature = (
322
+ f"int {self.kernel_name}({', '.join(arg_defs + size_args + offset_args)},\
323
+ {runtime_arg_decls}{self._EXTRA_CPP_ARGS})"
324
+ )
325
+ self.signature = signature
326
+ return signature
327
+
328
+ def call_kernel(
329
+ self,
330
+ name: str,
331
+ node: "CUTLASSTemplateBuffer", # type: ignore[name-defined]
332
+ ) -> None:
333
+ """
334
+ Generates code to call the kernel through V.graph.wrapper_code.
335
+ used from within torch._inductor.wrapper.PythonWrapperCodegen
336
+
337
+ name: Name of kernel function.
338
+ node: The CUTLASSTemplateBuffer node which contains information about the kernel, it's fused epilogue nodes
339
+ as well as all required inputs and outputs.
340
+ """
341
+ wrapper = V.graph.wrapper_code
342
+
343
+ arg_types: list[Any]
344
+ if V.graph.cpp_wrapper:
345
+ # Make sure we initialize these kernels since they're exported as
346
+ # C-style symbol names.
347
+ assert isinstance(wrapper, CppWrapperCpu)
348
+ wrapper.initialized_kernels[name] = self
349
+ # We always originally initialize name with "KERNEL_NAME". So, we
350
+ # we replace with the real kernel name passed as an arg to this function.
351
+ self.signature = self.signature.replace(str(Placeholder.KERNEL_NAME), name)
352
+ _, call_args, arg_types = self.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE)
353
+ else:
354
+ _, call_args, _, arg_types = self.args.python_argdefs()
355
+
356
+ dynamic_shape_args = self.get_dynamic_shape_args()
357
+ offset_args = self.get_offset_args()
358
+ call_args.extend(dynamic_shape_args) # type: ignore[arg-type]
359
+ call_args.extend(offset_args) # type: ignore[arg-type]
360
+ for arg in self.runtime_arg_values:
361
+ call_args.append(str(arg))
362
+ arg_types.extend("const int" for _ in dynamic_shape_args)
363
+ arg_types.extend("const int" for _ in offset_args)
364
+ for arg in self.runtime_arg_info:
365
+ arg_types.append(arg.ty)
366
+ # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar
367
+ for i in range(len(call_args)):
368
+ if V.graph.is_unspec_arg(call_args[i]):
369
+ call_args[i] = call_args[i] + ".item()"
370
+ elif isinstance(arg_types[i], torch_dtype):
371
+ call_args[i] = (
372
+ call_args[i]
373
+ if V.graph.cpp_wrapper
374
+ else f"c_void_p({call_args[i]}.data_ptr())"
375
+ )
376
+
377
+ # workspace_size ptr is NULL to mark this call is not intended for retrieving workspace_size.
378
+ # workspace_size should have already been retrieved prior to this call.
379
+ # workspace_size is here.
380
+ call_args.append("nullptr" if V.graph.cpp_wrapper else "None")
381
+ if V.graph.cpp_wrapper:
382
+ arg_types.append("size_t*")
383
+
384
+ if node.get_workspace_size() > 0:
385
+ ws = WorkspaceArg(
386
+ count=node.get_workspace_size(),
387
+ device=V.graph.get_current_device_or_throw(),
388
+ zero_mode=WorkspaceZeroMode.UNINITIALIZED,
389
+ outer_name=WorkspaceArg.unique_name(),
390
+ )
391
+ wrapper.generate_workspace_allocation(ws)
392
+ workspace = str(ws.outer_name)
393
+ call_args.append(
394
+ workspace
395
+ if V.graph.cpp_wrapper
396
+ else f"c_void_p({workspace}.data_ptr())"
397
+ )
398
+ else:
399
+ ws = None
400
+ call_args.append("nullptr" if V.graph.cpp_wrapper else "None")
401
+ if V.graph.cpp_wrapper:
402
+ arg_types.append("uint8_t*")
403
+
404
+ wrapper.generate_kernel_call(
405
+ name,
406
+ call_args,
407
+ triton=False,
408
+ arg_types=arg_types,
409
+ )
410
+ if ws:
411
+ wrapper.generate_workspace_deallocation(ws)
412
+
413
+ def dtype(self, node: IRNode) -> Optional[str]:
414
+ """
415
+ Generates code which represents dtype of a given node.
416
+ """
417
+
418
+ if node is None:
419
+ return "void"
420
+ return DTYPE_TO_CPP.get(node.get_layout().dtype)
421
+
422
+ def cutlass_dtype(self, node: IRNode, default_dtype="void") -> Optional[str]:
423
+ # Helper method, called into from CUTLASSGemmTemplate
424
+ if node is None:
425
+ return default_dtype
426
+ from torch._inductor.codegen.cutlass.template import CUTLASSTemplate
427
+
428
+ return CUTLASSTemplate._DTYPE_TO_CUTLASS[node.get_layout().dtype]
429
+
430
+ def max_valid_index(self, node: IRNode, default=-1):
431
+ # Helper method, called into from CUTLASSGemmTemplate
432
+ if node is None:
433
+ return default
434
+ max_valid_offset = 0
435
+ for i in range(len(node.get_size())):
436
+ max_valid_offset += (node.get_size()[i] - 1) * node.get_stride()[i]
437
+ return max_valid_offset
438
+
439
+ def ptr(self, node: IRNode) -> str:
440
+ """
441
+ Generates code which represents pointer of a given node.
442
+ """
443
+
444
+ if node is None:
445
+ return "nullptr"
446
+ arg_name = self.arg_name(node)
447
+ if arg_name is None:
448
+ return "nullptr"
449
+ return f"{arg_name} + {arg_name}_offset"
450
+
451
+ def size(
452
+ self,
453
+ node: IRNode,
454
+ start_index: int,
455
+ end_index: Optional[int] = None,
456
+ default_value: int = 0,
457
+ ) -> str:
458
+ """
459
+ Hook called from template code to get the size of an arg.
460
+ Generates code which represents size of a given node in [start_index, end_index).
461
+ If node is None, returns default_value.
462
+
463
+ TODO: Will add needed args to pass it in if it is dynamic.
464
+ """
465
+
466
+ if node is None:
467
+ return str(default_value)
468
+
469
+ start_index = _normalize_idx(start_index, len(node.get_size()))
470
+ if end_index is None:
471
+ end_index = start_index
472
+ end_index = _normalize_idx(end_index, len(node.get_size()))
473
+ sizes = [
474
+ self.find_symbol(node, "size", dim=i) or node.get_size()[i]
475
+ for i in range(start_index, end_index + 1)
476
+ ]
477
+ if len(sizes) == 0:
478
+ return str(default_value)
479
+
480
+ sizes = [symbols(v) if isinstance(v, str) else v for v in sizes]
481
+ val = sympy_product(sizes)
482
+ return val
483
+
484
+ def stride(self, node: IRNode, index: int, default_value: int = 0) -> str:
485
+ """
486
+ Hook called from template code to get the stride of an arg.
487
+ Generates code which represents stride of a given node at index.
488
+ If node is None, returns default_value.
489
+
490
+ TODO: Will add needed args to pass it in if it is dynamic.
491
+ """
492
+
493
+ if node is None:
494
+ return str(default_value)
495
+
496
+ index = _normalize_idx(index, len(node.get_size()))
497
+ if index < 0:
498
+ return str(default_value)
499
+
500
+ stride = node.get_stride()[index]
501
+ if V.graph.sizevars.statically_known_leq(stride, 1):
502
+ return str(stride)
503
+ return self.find_symbol(node, "stride", dim=index) or str(stride)
504
+
505
+ def batch_stride(self, node: IRNode, default_value: int = 0) -> str:
506
+ """
507
+ Hook called from template code to get the batch stride of an arg.
508
+ Returns 0 if batch dim is not present.
509
+
510
+ This method assumes that batch stride is the largest stride.
511
+ """
512
+
513
+ if node is None:
514
+ return str(default_value)
515
+
516
+ if len(node.get_size()) < 3:
517
+ return str(default_value)
518
+
519
+ batch_stride = node.get_stride()[0]
520
+ if V.graph.sizevars.statically_known_leq(batch_stride, 1):
521
+ return str(batch_stride)
522
+
523
+ return "{}*{}".format(
524
+ self.find_symbol(node, "size", dim=1) or node.get_size()[1],
525
+ self.find_symbol(node, "size", dim=2) or node.get_size()[2],
526
+ )
527
+
528
+ def row_or_column_stride(self, node: IRNode, default_value: int = 0) -> str:
529
+ """
530
+ Hook called from template code to get the row or column stride of an arg.
531
+ This is required by some CUTLASS 2.X APIs.
532
+ If the node is in row_major, it returns stride[-2].
533
+ If the node is in column_major, it returns stride[-1].
534
+
535
+ TODO: Will add needed args to pass it in if it is dynamic.
536
+ """
537
+
538
+ if node is None or len(node.get_stride()) < 2:
539
+ return str(default_value)
540
+
541
+ stride0 = node.get_stride()[-1]
542
+ stride1 = node.get_stride()[-2]
543
+ if stride0 == 1:
544
+ return cexpr(self.rename_indexing(stride1))
545
+ elif stride1 == 1:
546
+ return cexpr(self.rename_indexing(stride0))
547
+ else:
548
+ raise RuntimeError(
549
+ f"At least 1 stride should be 1. Strides: {node.get_stride()=}"
550
+ )
551
+
552
+ def load(self, name: str, index: Expr, mode: Any = None) -> CSEVariable:
553
+ """
554
+ Mock load function for memory planning to optimize allocations properly.
555
+ """
556
+ return self.create_cse_var(name, bounds=ValueRanges.unknown())
557
+
558
+ def store(self, name: str, index: Expr, value: Any, mode: Any = None) -> None:
559
+ """
560
+ Mock store function for memory planning to optimize allocations properly.
561
+ """
562
+ self.store_buffer_names.add(name)
563
+
564
+
565
+ class CUTLASSTemplateCaller(ChoiceCaller):
566
+ """
567
+ CUTLASSTemplateCaller
568
+
569
+ This class represents a caller for CUTLASS template kernels. It is a subclass of ChoiceCaller.
570
+ Attributes:
571
+ name (str): The name of the caller.
572
+ category (str): The category of the caller.
573
+ bmreq (CUTLASSBenchmarkRequest): The benchmark request for the caller.
574
+ template_buffer (CUTLASSTemplateBuffer): The template buffer for the caller.
575
+ """
576
+
577
+ def __init__(
578
+ self,
579
+ name: str,
580
+ category: str,
581
+ input_nodes: list[Buffer],
582
+ layout: Layout,
583
+ make_kernel_render: Callable[
584
+ [CUTLASSTemplateBuffer, Optional[list[BaseSchedulerNode]]],
585
+ tuple[CUTLASSTemplateKernel, functools.partial[str]],
586
+ ],
587
+ bmreq: CUTLASSBenchmarkRequest,
588
+ supports_epilogue_fusion: bool,
589
+ template: "CUTLASSTemplate", # type: ignore[name-defined]
590
+ info_kwargs: Optional[
591
+ dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]
592
+ ], # type: ignore[type-arg]
593
+ description: str,
594
+ ) -> None:
595
+ super().__init__(name, input_nodes, layout, description)
596
+ self.category = category
597
+ self.make_kernel_render = make_kernel_render
598
+ self.bmreq = bmreq
599
+ self.supports_epilogue_fusion = supports_epilogue_fusion
600
+ self.template = template
601
+ self.info_kwargs = info_kwargs
602
+
603
+ def precompile(self) -> None:
604
+ assert self.bmreq is not None
605
+ self.bmreq.precompile()
606
+
607
+ def benchmark(self, *args, out) -> float:
608
+ assert self.bmreq is not None
609
+ if config.profile_bandwidth_with_do_bench_using_profiling:
610
+ algo = self.bmreq.make_run_fn(*args, out=out)
611
+ return do_bench_using_profiling(algo)
612
+ return self.bmreq.benchmark(*args, out=out)
613
+
614
+ def __str__(self) -> str:
615
+ return f"CUTLASSTemplateCaller(source_file={self.bmreq.source_file})"
616
+
617
+ def call_name(self) -> str:
618
+ return f"cutlass_template_kernels.{self.name}"
619
+
620
+ def kernel_hash_key(self) -> str:
621
+ """
622
+ Return kernel hash key that does not depend on swizzle.
623
+ """
624
+ return "-".join(
625
+ [
626
+ self.category,
627
+ self.bmreq.hash_key,
628
+ ]
629
+ )
630
+
631
+ def hash_key(self) -> str:
632
+ """
633
+ Return kernel hash key that does not depend on swizzle.
634
+ """
635
+ swizzle_str: str = (
636
+ str(self.info_kwargs.get("swizzle"))
637
+ if isinstance(self.info_kwargs, dict)
638
+ else "None"
639
+ )
640
+ return "-".join(
641
+ [
642
+ self.category,
643
+ self.bmreq.hash_key,
644
+ swizzle_str,
645
+ ]
646
+ )
647
+
648
+ def info_dict(self) -> dict[str, Union[PrimitiveInfoType, list[PrimitiveInfoType]]]:
649
+ """
650
+ Information returned here is logged to the autotune log file when that is enabled.
651
+
652
+ In general, we should avoid calling this function as it is expensive to compute,
653
+ and can add up very fast.
654
+ """
655
+ if self.info_kwargs is not None and "op" in self.info_kwargs:
656
+ op: Any = self.info_kwargs["op"]
657
+ return {
658
+ "backend": "CUDA",
659
+ "op_type": type(op).__name__,
660
+ "op_conf_name": str(op.configuration_name()),
661
+ "op_arch": str(op.arch),
662
+ "tile_shape": str(op.tile_description.tile_shape),
663
+ "epilogue_schedule": str(op.epilogue_schedule),
664
+ "kernel_schedule": str(op.kernel_schedule),
665
+ "element_accumulator": str(op.accumulator_type()),
666
+ "op_name": str(op.procedural_name()),
667
+ "instruction_shape": str(
668
+ op.tile_description.math_instruction.instruction_shape
669
+ ),
670
+ "swizzle": str(self.info_kwargs["swizzle"]),
671
+ }
672
+ else:
673
+ return {"backend": "CUDA", "op_type": "unknown"}
674
+
675
+ def output_node(self) -> TensorBox:
676
+ self.bmreq.update_workspace_size()
677
+ buffer = CUTLASSTemplateBuffer(
678
+ layout=self.layout,
679
+ inputs=self.input_nodes,
680
+ make_kernel_render=self.make_kernel_render,
681
+ workspace_size=self.bmreq.workspace_size,
682
+ supports_epilogue_fusion=self.supports_epilogue_fusion,
683
+ template=self.template,
684
+ )
685
+ # Pass KTC annotation to the buffer for encoding
686
+ if "ktc" in self.annotations:
687
+ buffer.annotations["ktc"] = self.annotations["ktc"]
688
+ return TensorBox.create(buffer)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/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
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/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())
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/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))
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/pydot/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # mypy: disable-error-code="var-annotated"
2
+ Dot = None
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # typing: ignore
2
+ # flake8: noqa
3
+ from .special import *
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/cutlass_mock_imports/scipy/special.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # mypy: disable-error-code="var-annotated"
2
+ erf = None
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/evt_extensions.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ..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 ..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}")
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/lib_extensions/gemm_operation_extensions.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+ from ..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)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/python_evt.py ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from collections.abc 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
+ cutlass_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(cutlass_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)}"
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/scheduling.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.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, CUTLASSTemplateBuffer, 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 CUTLASSScheduling(BaseScheduling):
40
+ """
41
+ Partial Scheduling implementation for cutlass 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 cutlass 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_cutlass_template(node: BaseSchedulerNode) -> bool:
57
+ return isinstance(node, SchedulerNode) and isinstance(
58
+ node.node, CUTLASSTemplateBuffer
59
+ )
60
+
61
+ def is_cutlass_fused_template(self, node: BaseSchedulerNode) -> bool:
62
+ return isinstance(node, FusedSchedulerNode) and self.is_cutlass_template(node)
63
+
64
+ def can_fuse_vertical(
65
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
66
+ ) -> bool:
67
+ if self.is_cutlass_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(CUTLASSTemplateBuffer, node1.node),
71
+ [],
72
+ node2, # type: ignore[arg-type]
73
+ )
74
+ elif self.is_cutlass_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 cutlass template, possibly with fused epilogues
134
+ """
135
+ counters["inductor"]["cutlass_epilogue_fusion_counter"] += len(epilogue_nodes)
136
+ assert self.is_cutlass_template(template_node), (
137
+ "Template node passed to CUTLASSScheduling.codegen_template must be a SchedulerNode that wraps a CUTLASSTemplateBuffer"
138
+ )
139
+ template_node = cast(SchedulerNode, template_node)
140
+ _, (_numel, rnumel) = template_node.group
141
+ assert rnumel == 1
142
+ ctb: CUTLASSTemplateBuffer = cast(CUTLASSTemplateBuffer, 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
+ cutlass_template_buffer: CUTLASSTemplateBuffer,
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
+ cutlass_template_buffer : A CUTLASSTemplateBuffer object representing the CUTLASS 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(
217
+ cutlass_template_buffer.get_name(), node_to_fuse.get_name()
218
+ )
219
+
220
+ scheduler_nodes_to_fuse = node_to_fuse.get_nodes()
221
+
222
+ assert isinstance(cutlass_template_buffer, CUTLASSTemplateBuffer)
223
+
224
+ # Checks on constituent nodes
225
+ for s_node in scheduler_nodes_to_fuse:
226
+ node = s_node.node
227
+
228
+ if not isinstance(node, ComputedBuffer):
229
+ why(f"{node} is not a ComputedBuffer")
230
+ return False
231
+ elif not isinstance(node.data, Pointwise):
232
+ why(f"{node} is not a Pointwise op")
233
+ return False
234
+ elif not node.get_computed_buffer_name(): # type: ignore[attr-defined]
235
+ why(f"{node} does not have a computed buffer name")
236
+ return False
237
+
238
+ name = node.get_computed_buffer_name() # type: ignore[attr-defined]
239
+ # dtype can differ, and strides can differ as long as they are broadcastable
240
+ if node.get_size() != cutlass_template_buffer.get_size():
241
+ why(
242
+ f"{name}'s size: {node.get_size()} differs from {cutlass_template_buffer.get_name()}'s \
243
+ size: {cutlass_template_buffer.get_size()}"
244
+ )
245
+ return False
246
+
247
+ assert len(
248
+ existing_epilogue_nodes
249
+ ) or cutlass_template_buffer.get_name() in OrderedSet(
250
+ [rd.name for rd in node_to_fuse.read_writes.reads]
251
+ ), "First epilogue node must read from cutlass template buffer"
252
+
253
+ if node_to_fuse.has_aliasing_or_mutation():
254
+ why(f"{node_to_fuse.get_name()} has aliasing or mutation")
255
+ return False
256
+ elif node_to_fuse.is_reduction():
257
+ why(
258
+ f"{node_to_fuse.get_name()} is a reduction which is not yet supported by EVT"
259
+ )
260
+ return False
261
+ elif (
262
+ not config.cutlass.cutlass_epilogue_fusion_enabled
263
+ or not config.epilogue_fusion
264
+ ):
265
+ why("cutlass epilogue fusion is not enabled")
266
+ return False
267
+ elif not cutlass_template_buffer.supports_epilogue_fusion:
268
+ why("epilogue fusion is only supported for TMA-enabled gemm ops")
269
+ return False
270
+
271
+ try:
272
+ from torch._inductor.codegen.cutlass.python_evt import CutlassEVTCodegen
273
+
274
+ CutlassEVTCodegen.ir_to_evt_python_code(
275
+ cutlass_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 {cutlass_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 {cutlass_template_buffer.name}. \
292
+ Reason: {not_implemented_op}" # noqa: G004, B950
293
+ )
294
+ return False
295
+
296
+ return True
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/serialization.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import json
4
+ from enum import Enum
5
+ from typing import Any, Optional
6
+
7
+ from torch._inductor.codegen.cutlass.utils import try_import_cutlass
8
+
9
+
10
+ class CUTLASSOperationSerializer:
11
+ """Serializes and deserializes CUTLASS GEMM operations to/from JSON.
12
+
13
+ Handles GemmOperation objects and their nested components (TileDescription, TensorDescription).
14
+ """
15
+
16
+ # not used, but keeping in case we want to generalize the serializer
17
+ _SUPPORTED_CLASSES: list[str] = [
18
+ "GemmOperation",
19
+ "GemmKind",
20
+ "TileDescription",
21
+ "TensorDescription",
22
+ "DataType",
23
+ "EpilogueFunctor",
24
+ "EpilogueFunctor3x",
25
+ "SwizzlingFunctor",
26
+ "KernelScheduleType",
27
+ "EpilogueScheduleType",
28
+ "TileSchedulerType",
29
+ ]
30
+
31
+ @classmethod
32
+ def serialize(cls, operation: "GemmOperation") -> str: # type: ignore[name-defined] # noqa: F821
33
+ """Serialize a GEMM operation to JSON string.
34
+
35
+ Args:
36
+ operation: GemmOperation object
37
+
38
+ Returns:
39
+ str: JSON string representation of the operation
40
+ """
41
+ assert operation.__class__.__qualname__ == "GemmOperation", (
42
+ "Only GemmOperation objects are supported via the main API"
43
+ )
44
+ return json.dumps(cls._gemm_operation_to_json(operation))
45
+
46
+ @classmethod
47
+ def deserialize(cls, json_str: str) -> "GemmOperation": # type: ignore[name-defined] # noqa: F821
48
+ """Deserialize JSON string to a GEMM operation.
49
+
50
+ Args:
51
+ json_str: JSON string of a GEMM operation
52
+
53
+ Returns:
54
+ GemmOperation: Reconstructed operation
55
+ """
56
+ json_dict = json.loads(json_str)
57
+ return cls._json_to_gemm_operation(json_dict)
58
+
59
+ @classmethod
60
+ def _gemm_operation_to_json(cls, operation: "GemmOperation") -> dict[str, Any]: # type: ignore[name-defined] # noqa: F821
61
+ """Convert GemmOperation to JSON-serializable dict.
62
+
63
+ Args:
64
+ operation: GemmOperation object
65
+
66
+ Returns:
67
+ dict: Dictionary representation
68
+ """
69
+ from cutlass_library.library import TensorDescription
70
+
71
+ # Create the main dictionary with required and optional parameters
72
+ result = {
73
+ # Required parameters
74
+ "gemm_kind": cls._enum_to_json(operation.gemm_kind),
75
+ "arch": operation.arch,
76
+ "tile_description": cls._tile_description_to_json(
77
+ operation.tile_description
78
+ ),
79
+ "A": cls._tensor_description_to_json(operation.A),
80
+ "B": cls._tensor_description_to_json(operation.B),
81
+ "C": cls._tensor_description_to_json(operation.C),
82
+ "element_epilogue": cls._enum_to_json(operation.element_epilogue),
83
+ # Optional parameters
84
+ "epilogue_functor": cls._enum_to_json(operation.epilogue_functor),
85
+ "swizzling_functor": cls._enum_to_json(operation.swizzling_functor),
86
+ "D": cls._tensor_description_to_json(operation.D) if operation.D else None,
87
+ "kernel_schedule": cls._enum_to_json(operation.kernel_schedule),
88
+ "epilogue_schedule": cls._enum_to_json(operation.epilogue_schedule),
89
+ "tile_scheduler": cls._enum_to_json(operation.tile_scheduler),
90
+ }
91
+
92
+ # Process optional attributes
93
+ optional_attrs = [
94
+ "mixed_input_mode",
95
+ "mixed_input_shuffle",
96
+ "ScaleFactorA",
97
+ "ScaleFactorB",
98
+ "ScaleFactorD",
99
+ "ScaleFactorMVecSize",
100
+ "ScaleFactorNVecSize",
101
+ "ScaleFactorKVecSize",
102
+ "ScaleFactorVectorSize",
103
+ "is_3x",
104
+ ]
105
+
106
+ for attr in optional_attrs:
107
+ if not hasattr(operation, attr):
108
+ continue
109
+
110
+ value = getattr(operation, attr)
111
+
112
+ if isinstance(value, TensorDescription):
113
+ result[attr] = cls._tensor_description_to_json(value)
114
+ elif isinstance(value, Enum):
115
+ result[attr] = cls._enum_to_json(value)
116
+ else:
117
+ result[attr] = value
118
+
119
+ return result
120
+
121
+ @classmethod
122
+ def _json_to_gemm_operation(cls, json_dict: dict[str, Any]) -> "GemmOperation": # type: ignore[name-defined] # noqa: F821
123
+ """Convert JSON dict to GemmOperation object.
124
+
125
+ Args:
126
+ json_dict: Dictionary representation
127
+
128
+ Returns:
129
+ GemmOperation: Reconstructed object
130
+ """
131
+ from cutlass_library import DataType
132
+ from cutlass_library.gemm_operation import GemmKind, GemmOperation
133
+ from cutlass_library.library import (
134
+ EpilogueFunctor,
135
+ EpilogueFunctor3x,
136
+ EpilogueScheduleType,
137
+ KernelScheduleType,
138
+ MixedInputMode,
139
+ SwizzlingFunctor,
140
+ TileSchedulerType,
141
+ )
142
+
143
+ # Extract constructor parameters from the JSON dictionary
144
+ gemm_kind = cls._json_to_enum(json_dict["gemm_kind"], GemmKind)
145
+ arch = json_dict["arch"]
146
+ tile_description = cls._json_to_tile_description(json_dict["tile_description"])
147
+ A = cls._json_to_tensor_description(json_dict.get("A"), "A")
148
+ B = cls._json_to_tensor_description(json_dict.get("B"), "B")
149
+ C = cls._json_to_tensor_description(json_dict.get("C"), "C")
150
+ element_epilogue = cls._json_to_enum(json_dict["element_epilogue"], DataType)
151
+
152
+ # Get optional parameters with defaults
153
+ epilogue_functor = cls._json_to_enum(
154
+ json_dict.get("epilogue_functor"),
155
+ EpilogueFunctor3x if json_dict.get("is_3x") else EpilogueFunctor,
156
+ )
157
+ swizzling_functor = cls._json_to_enum(
158
+ json_dict.get("swizzling_functor"), SwizzlingFunctor
159
+ )
160
+ D = cls._json_to_tensor_description(json_dict.get("D"), "D")
161
+ kernel_schedule = cls._json_to_enum(
162
+ json_dict.get("kernel_schedule"), KernelScheduleType
163
+ )
164
+ epilogue_schedule = cls._json_to_enum(
165
+ json_dict.get("epilogue_schedule"), EpilogueScheduleType
166
+ )
167
+ tile_scheduler = cls._json_to_enum(
168
+ json_dict.get("tile_scheduler"), TileSchedulerType
169
+ )
170
+
171
+ mixed_input_mode = cls._json_to_enum(
172
+ json_dict.get("mixed_input_mode"), MixedInputMode
173
+ )
174
+ mixed_input_shuffle = json_dict.get("mixed_input_shuffle", False)
175
+
176
+ # Scale factors
177
+ ScaleFactorA = cls._json_to_enum(json_dict.get("ScaleFactorA"), DataType)
178
+ ScaleFactorB = cls._json_to_enum(json_dict.get("ScaleFactorB"), DataType)
179
+
180
+ ScaleFactorD = None
181
+ if "ScaleFactorD" in json_dict and "ScaleFactorVectorSize" in json_dict:
182
+ ScaleFactorD = {
183
+ "tensor": cls._json_to_tensor_description(
184
+ json_dict.get("ScaleFactorD"), "ScaleFactorD"
185
+ ),
186
+ "vector_size": json_dict.get("ScaleFactorVectorSize"),
187
+ }
188
+
189
+ ScaleFactorMVecSize = json_dict.get("ScaleFactorMVecSize")
190
+ ScaleFactorNVecSize = json_dict.get("ScaleFactorNVecSize")
191
+ ScaleFactorKVecSize = json_dict.get("ScaleFactorKVecSize")
192
+
193
+ # Create the GemmOperation with the extracted parameters
194
+ operation = GemmOperation(
195
+ gemm_kind=gemm_kind,
196
+ arch=arch,
197
+ tile_description=tile_description,
198
+ A=A,
199
+ B=B,
200
+ C=C,
201
+ element_epilogue=element_epilogue,
202
+ epilogue_functor=epilogue_functor,
203
+ swizzling_functor=swizzling_functor,
204
+ D=D,
205
+ kernel_schedule=kernel_schedule,
206
+ epilogue_schedule=epilogue_schedule,
207
+ tile_scheduler=tile_scheduler,
208
+ mixed_input_mode=mixed_input_mode,
209
+ mixed_input_shuffle=mixed_input_shuffle,
210
+ ScaleFactorA=ScaleFactorA,
211
+ ScaleFactorB=ScaleFactorB,
212
+ ScaleFactorD=ScaleFactorD,
213
+ ScaleFactorMVecSize=ScaleFactorMVecSize,
214
+ ScaleFactorNVecSize=ScaleFactorNVecSize,
215
+ ScaleFactorKVecSize=ScaleFactorKVecSize,
216
+ )
217
+
218
+ return operation
219
+
220
+ @classmethod
221
+ @functools.lru_cache(None)
222
+ def _tile_description_to_json(cls, tile_desc: "TileDescription") -> str: # type: ignore[name-defined] # noqa: F821
223
+ """
224
+ Convert TileDescription to JSON string.
225
+
226
+ Args:
227
+ tile_desc: TileDescription object
228
+
229
+ Returns:
230
+ str: JSON string representation
231
+ """
232
+
233
+ # Create the main dictionary with field names matching TileDescription constructor parameters
234
+ result = {
235
+ "threadblock_shape": tile_desc.threadblock_shape,
236
+ "stages": tile_desc.stages,
237
+ "warp_count": tile_desc.warp_count,
238
+ "math_instruction": cls._math_instruction_to_json(
239
+ tile_desc.math_instruction
240
+ ),
241
+ "min_compute": tile_desc.minimum_compute_capability, # Store as min_compute for constructor
242
+ "max_compute": tile_desc.maximum_compute_capability, # Store as max_compute for constructor
243
+ "cluster_shape": tile_desc.cluster_shape,
244
+ "explicit_vector_sizes": tile_desc.explicit_vector_sizes,
245
+ }
246
+
247
+ # Add tile_shape if it exists and differs from threadblock_shape
248
+ if (
249
+ hasattr(tile_desc, "tile_shape")
250
+ and tile_desc.tile_shape != tile_desc.threadblock_shape
251
+ ):
252
+ result["tile_shape"] = tile_desc.tile_shape
253
+
254
+ return json.dumps(result)
255
+
256
+ @classmethod
257
+ @functools.lru_cache(None)
258
+ def _json_to_tile_description(
259
+ cls, json_dict: Optional[str]
260
+ ) -> Optional["TileDescription"]: # type: ignore[name-defined] # noqa: F821
261
+ """
262
+ Convert JSON dict to TileDescription object.
263
+
264
+ Args:
265
+ json_dict: Dictionary representation
266
+
267
+ Returns:
268
+ TileDescription: Reconstructed object
269
+ """
270
+ if json_dict is None:
271
+ return None
272
+
273
+ tile_dict = json.loads(json_dict)
274
+
275
+ from cutlass_library.library import TileDescription
276
+
277
+ math_instruction = cls._json_to_math_instruction(tile_dict["math_instruction"])
278
+
279
+ # Get compute capability values, checking both naming conventions
280
+ min_compute = tile_dict.get(
281
+ "min_compute", tile_dict.get("minimum_compute_capability")
282
+ )
283
+ max_compute = tile_dict.get(
284
+ "max_compute", tile_dict.get("maximum_compute_capability")
285
+ )
286
+
287
+ # Get cluster shape with default value
288
+ cluster_shape = tile_dict.get("cluster_shape", [1, 1, 1])
289
+
290
+ # Create the TileDescription object
291
+ tile_desc = TileDescription(
292
+ threadblock_shape=tile_dict["threadblock_shape"],
293
+ stages=tile_dict["stages"],
294
+ warp_count=tile_dict["warp_count"],
295
+ math_instruction=math_instruction,
296
+ min_compute=min_compute,
297
+ max_compute=max_compute,
298
+ cluster_shape=cluster_shape,
299
+ explicit_vector_sizes=tile_dict.get("explicit_vector_sizes"),
300
+ )
301
+
302
+ # Set tile_shape if it exists and differs from threadblock_shape
303
+ if (
304
+ "tile_shape" in tile_dict
305
+ and tile_dict["tile_shape"] != tile_dict["threadblock_shape"]
306
+ ):
307
+ tile_desc.tile_shape = tile_dict["tile_shape"]
308
+
309
+ return tile_desc
310
+
311
+ @classmethod
312
+ @functools.lru_cache(None)
313
+ def _math_instruction_to_json(
314
+ cls,
315
+ math_instruction: Optional["MathInstruction"], # type: ignore[name-defined] # noqa: F821
316
+ ) -> Optional[str]:
317
+ """Convert MathInstruction to JSON string.
318
+
319
+ Args:
320
+ math_instruction: MathInstruction object
321
+
322
+ Returns:
323
+ Optional[str]: JSON string representation or None
324
+ """
325
+ if math_instruction is None:
326
+ return None
327
+
328
+ result = {
329
+ "instruction_shape": math_instruction.instruction_shape,
330
+ "element_a": cls._enum_to_json(math_instruction.element_a),
331
+ "element_b": cls._enum_to_json(math_instruction.element_b),
332
+ "element_accumulator": cls._enum_to_json(
333
+ math_instruction.element_accumulator
334
+ ),
335
+ "opcode_class": cls._enum_to_json(math_instruction.opcode_class),
336
+ "math_operation": cls._enum_to_json(math_instruction.math_operation),
337
+ "element_scale_factor": cls._enum_to_json(
338
+ math_instruction.element_scale_factor
339
+ ),
340
+ }
341
+
342
+ return json.dumps(result)
343
+
344
+ @classmethod
345
+ @functools.lru_cache(None)
346
+ def _json_to_math_instruction(
347
+ cls, json_dict: Optional[str]
348
+ ) -> Optional["MathInstruction"]: # type: ignore[name-defined] # noqa: F821
349
+ """Convert JSON string to MathInstruction object.
350
+
351
+ Args:
352
+ json_dict: JSON string representation
353
+
354
+ Returns:
355
+ Optional[MathInstruction]: Reconstructed object or None
356
+ """
357
+ if json_dict is None:
358
+ return None
359
+
360
+ from cutlass_library import DataType
361
+ from cutlass_library.library import MathInstruction, MathOperation, OpcodeClass
362
+
363
+ mi_dict = json.loads(json_dict)
364
+
365
+ # Convert string enum names back to enum values
366
+ element_a = cls._json_to_enum(mi_dict["element_a"], DataType)
367
+ element_b = cls._json_to_enum(mi_dict["element_b"], DataType)
368
+ element_acc = cls._json_to_enum(mi_dict["element_accumulator"], DataType)
369
+
370
+ # Get the opcode_class enum
371
+ opcode_class = cls._json_to_enum(mi_dict["opcode_class"], OpcodeClass)
372
+
373
+ # Get the math_operation enum
374
+ math_op = cls._json_to_enum(mi_dict["math_operation"], MathOperation)
375
+
376
+ # Create the MathInstruction object
377
+ math_instruction_obj = MathInstruction(
378
+ instruction_shape=mi_dict["instruction_shape"],
379
+ element_a=element_a,
380
+ element_b=element_b,
381
+ element_accumulator=element_acc,
382
+ opcode_class=opcode_class,
383
+ math_operation=math_op,
384
+ )
385
+
386
+ # Add element_scale_factor if it exists
387
+ if (
388
+ "element_scale_factor" in mi_dict
389
+ and mi_dict["element_scale_factor"] is not None
390
+ ):
391
+ math_instruction_obj.element_scale_factor = cls._json_to_enum(
392
+ mi_dict["element_scale_factor"], DataType
393
+ )
394
+
395
+ return math_instruction_obj
396
+
397
+ @classmethod
398
+ @functools.lru_cache(None)
399
+ def _tensor_description_to_json(
400
+ cls,
401
+ tensor_desc: Optional["TensorDescription"], # type: ignore[name-defined] # noqa: F821
402
+ ) -> Optional[str]:
403
+ """Convert TensorDescription to JSON string.
404
+
405
+ Args:
406
+ tensor_desc: TensorDescription object
407
+
408
+ Returns:
409
+ Optional[str]: JSON string representation or None
410
+ """
411
+ if tensor_desc is None:
412
+ return None
413
+
414
+ result = {
415
+ "element": cls._enum_to_json(tensor_desc.element),
416
+ "layout": cls._enum_to_json(tensor_desc.layout),
417
+ "alignment": tensor_desc.alignment,
418
+ "complex_transform": cls._enum_to_json(tensor_desc.complex_transform),
419
+ }
420
+
421
+ return json.dumps(result)
422
+
423
+ @classmethod
424
+ @functools.lru_cache(None)
425
+ def _json_to_tensor_description(
426
+ cls,
427
+ json_dict: Optional[str],
428
+ tensor_name: Optional[str] = None,
429
+ ) -> Optional["TensorDescription"]: # type: ignore[name-defined] # noqa: F821
430
+ """Convert JSON string to TensorDescription object.
431
+
432
+ Args:
433
+ json_dict: JSON string representation
434
+ tensor_name: Name of the tensor to avoid cache in the same op
435
+
436
+ Returns:
437
+ Optional[TensorDescription]: Reconstructed object or None
438
+ """
439
+ if json_dict is None:
440
+ return None
441
+
442
+ tensor_dict = json.loads(json_dict)
443
+
444
+ from cutlass_library import DataType
445
+ from cutlass_library.library import (
446
+ ComplexTransform,
447
+ LayoutType,
448
+ TensorDescription,
449
+ )
450
+
451
+ element = cls._json_to_enum(tensor_dict["element"], DataType)
452
+ layout = cls._json_to_enum(tensor_dict["layout"], LayoutType)
453
+ alignment = tensor_dict["alignment"]
454
+ complex_transform = cls._json_to_enum(
455
+ tensor_dict["complex_transform"], ComplexTransform
456
+ )
457
+
458
+ return TensorDescription(element, layout, alignment, complex_transform)
459
+
460
+ @classmethod
461
+ @functools.lru_cache(None)
462
+ def _enum_to_json(cls, enum_value: Optional[Enum]) -> Optional[str]:
463
+ """Convert enum value to JSON string.
464
+
465
+ Args:
466
+ enum_value: Enum value
467
+
468
+ Returns:
469
+ Optional[str]: JSON string representation or None
470
+ """
471
+ if enum_value is None:
472
+ return None
473
+
474
+ result = {
475
+ "type": enum_value.__class__.__name__,
476
+ "name": enum_value.name,
477
+ }
478
+
479
+ return json.dumps(result)
480
+
481
+ @classmethod
482
+ @functools.lru_cache(None)
483
+ def _json_to_enum(cls, json_dict: Optional[str], enum_class: Any) -> Optional[Enum]:
484
+ """Convert JSON string to enum value.
485
+
486
+ Format: {name: "EnumName", value: 1}
487
+
488
+ Args:
489
+ json_dict: JSON string representation
490
+ enum_class: Target enum class
491
+
492
+ Returns:
493
+ Optional[Enum]: Reconstructed enum value or None
494
+ """
495
+ if json_dict is None:
496
+ return None
497
+
498
+ enum_dict = json.loads(json_dict)
499
+
500
+ return enum_class[enum_dict["name"]]
501
+
502
+
503
+ @functools.lru_cache(1)
504
+ def get_cutlass_operation_serializer() -> Optional[CUTLASSOperationSerializer]:
505
+ if not try_import_cutlass():
506
+ return None
507
+ return CUTLASSOperationSerializer()
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/template.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 unittest.mock import patch
8
+
9
+ import sympy
10
+
11
+ import torch
12
+ from torch._inductor import config
13
+ from torch._inductor.utils import clear_on_fresh_cache, Placeholder
14
+ from torch._logging import getArtifactLogger
15
+
16
+ from ...autotune_process import CUTLASSBenchmarkRequest, TensorMeta
17
+ from ...ir import Buffer, CUTLASSTemplateBuffer, IRNode, Layout
18
+ from ...utils import IndentedBuffer, unique
19
+ from ...virtualized import V
20
+ from ..common import KernelTemplate
21
+ from .kernel import CUTLASSTemplateCaller, CUTLASSTemplateKernel
22
+ from .utils import DTYPE_TO_CUTLASS_TYPE
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ from ...scheduler import BaseSchedulerNode # noqa: TC004
27
+ else:
28
+ BaseSchedulerNode = Any
29
+
30
+ GemmOperation = Any
31
+
32
+ autotuning_log = getArtifactLogger(__name__, "autotuning")
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ArgInfo:
37
+ name: str
38
+ ty: str
39
+
40
+
41
+ @clear_on_fresh_cache
42
+ class CUTLASSTemplate(KernelTemplate):
43
+ """
44
+ CUTLASSTemplate is a class that provides a template for generating CUTLASS Templates. Used as a baseclass for the
45
+ CUTLASSGemmTemplate, providing functionality that might also be relevant for non-GEMM CUTLASS Kernels.
46
+ """
47
+
48
+ index_counter = itertools.count()
49
+ # dict of cache key to (code, size_args)
50
+ code_cache: dict[str, tuple[str, tuple[int, ...], tuple[int, ...]]] = {}
51
+ cache_clear = staticmethod(code_cache.clear)
52
+
53
+ def __init__(
54
+ self,
55
+ name: str,
56
+ input_nodes: list[Buffer],
57
+ layout: Layout,
58
+ input_reorder: Optional[list[int]] = None,
59
+ device_type: str = "cuda",
60
+ ) -> None:
61
+ """
62
+ Baseclass for CUTLASS C++ Templates, derived from KernelTemplate.
63
+ Not to be instantiated directly.
64
+
65
+ Args:
66
+ name (str): The name of the CUTLASSTemplate object.
67
+ input_nodes (List[IRNode]): A list of input IRNodes.
68
+ layout (Layout): The layout of the output buffer / tensor.
69
+ input_reorder (Optional[List[int]]): An optional list that specifies
70
+ the order of the input nodes.
71
+ """
72
+ super().__init__(name)
73
+ self.input_nodes = input_nodes
74
+ self.output_node: Buffer = Buffer(name="buf_out", layout=layout)
75
+ self.input_reorder = input_reorder
76
+ self.layout = layout
77
+ self.device_type = device_type
78
+
79
+ @classmethod
80
+ @functools.lru_cache(None)
81
+ # pyrefly: ignore [bad-override]
82
+ def _template_from_string(cls, source: str) -> Any:
83
+ return KernelTemplate._template_from_string(source)
84
+
85
+ @staticmethod
86
+ def supports_epilogue_fusion(op: GemmOperation) -> bool:
87
+ return False
88
+
89
+ def make_key(self, name: str, input_key: str, layout_repr: str) -> str:
90
+ """
91
+ Make a key for the code cache. The idea of the method is to cache
92
+ everything that matters but doesn't include runtime param values, i.e.,
93
+ self.get_runtime_arg_values().
94
+
95
+ Args:
96
+ kwargs: Additional keyword arguments. Including op (GemmOperation).
97
+ """
98
+ return hashlib.sha256(
99
+ str(
100
+ (
101
+ input_key,
102
+ self.input_reorder,
103
+ # output layout, same as self.output_node.get_layout()
104
+ layout_repr,
105
+ self.get_runtime_arg_info(),
106
+ name,
107
+ )
108
+ ).encode("utf-8")
109
+ ).hexdigest()
110
+
111
+ def generate_code_and_args(
112
+ self, name: str, input_key: str, layout_repr: str, **kwargs
113
+ ) -> tuple[str, tuple[int, ...]]:
114
+ """
115
+ Generate code and args with caching. We cache the code even if runtime
116
+ args are different.
117
+ """
118
+ key: Optional[str] = None
119
+ if config.cutlass.enable_caching_codegen:
120
+ key = self.make_key(name=name, input_key=input_key, layout_repr=layout_repr)
121
+
122
+ if key is not None and key in self.code_cache:
123
+ code, size_args, offset_args = self.code_cache[key]
124
+ extra_args = tuple(
125
+ list(size_args)
126
+ + list(offset_args)
127
+ + list(self.get_runtime_arg_values(**kwargs))
128
+ )
129
+ return code, extra_args
130
+
131
+ kernel_name = str(Placeholder.KERNEL_NAME)
132
+ kernel = CUTLASSTemplateKernel(
133
+ kernel_name=kernel_name,
134
+ runtime_arg_info=self.get_runtime_arg_info(),
135
+ runtime_arg_values=self.get_runtime_arg_values(**kwargs),
136
+ )
137
+ with patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)):
138
+ code = self.render(kernel=kernel, **kwargs)
139
+ _, call_args, _, _ = kernel.args.python_argdefs()
140
+ autotuning_log.debug("Generated Code:\n%s", code)
141
+ autotuning_log.debug(
142
+ "Args: cpp_argdefs: %s, python_argdefs: %s",
143
+ kernel.args.cpp_argdefs(DTYPE_TO_CUTLASS_TYPE),
144
+ kernel.args.python_argdefs(),
145
+ )
146
+
147
+ input_reorder = (
148
+ self.input_reorder
149
+ if self.input_reorder is not None
150
+ else list(range(len(self.input_nodes)))
151
+ )
152
+ expected_args = list(
153
+ unique(self.input_nodes[idx].get_name() for idx in input_reorder)
154
+ )
155
+ expected_args.extend([self.output_node.get_name()])
156
+ assert list(call_args)[: len(expected_args)] == expected_args, (
157
+ call_args,
158
+ expected_args,
159
+ )
160
+ V.graph.sizevars.size_hints(map(sympy.expand, call_args[len(expected_args) :]))
161
+ size_args = V.graph.sizevars.size_hints(kernel.get_dynamic_shape_args())
162
+ offset_args = V.graph.sizevars.size_hints(kernel.get_offset_args())
163
+
164
+ if key is not None:
165
+ self.code_cache[key] = code, size_args, offset_args
166
+
167
+ # extra args has runtime params, which shouldn't be cached
168
+ extra_args = tuple(
169
+ list(size_args) + list(offset_args) + self.get_runtime_arg_values(**kwargs)
170
+ )
171
+
172
+ return code, extra_args
173
+
174
+ def generate( # type: ignore[override]
175
+ self,
176
+ name: str,
177
+ description: str,
178
+ input_key: str,
179
+ layout_repr: str,
180
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
181
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
182
+ **kwargs,
183
+ ) -> CUTLASSTemplateCaller:
184
+ """
185
+ Generates the CUDA template caller object for the given GEMM template and operation.
186
+ This CUTLASSTemplateCaller may be used to call and benchmark the generated CUDA kernel
187
+ in a standalone manner to enable Autotuning.
188
+
189
+ Args:
190
+ description: op name followed by swizzle.
191
+ kwargs: Additional keyword arguments.
192
+
193
+ Returns:
194
+ A CUTLASSTemplateCaller object representing the generated CUDA template caller.
195
+ """
196
+ code, extra_args = self.generate_code_and_args(
197
+ name=name,
198
+ input_key=input_key,
199
+ layout_repr=layout_repr,
200
+ **kwargs,
201
+ )
202
+
203
+ # not caching since kernel name is needed below
204
+ kernel_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()[:8]
205
+ kernel_name = f"cutlass_{kernel_hash}"
206
+ code = code.replace(self.name, kernel_name)
207
+
208
+ # create the BenchmarkRequest
209
+ bmreq = CUTLASSBenchmarkRequest(
210
+ kernel_name=kernel_name,
211
+ input_tensor_meta=input_tensor_meta,
212
+ output_tensor_meta=output_tensor_meta,
213
+ extra_args=extra_args,
214
+ source_code=code,
215
+ device_type=self.device_type,
216
+ )
217
+
218
+ # kwargs has "op" argument in case of CUTLASSGemmTemplate
219
+ op = kwargs["op"]
220
+ if not op:
221
+ supports_epilogue_fusion = False
222
+ else:
223
+ # epilogue fusion is only supported for TMA kernels
224
+ supports_epilogue_fusion = self.supports_epilogue_fusion(op)
225
+
226
+ def make_kernel_render(
227
+ template_node: CUTLASSTemplateBuffer,
228
+ epilogue_nodes: Optional[list[BaseSchedulerNode]] = None,
229
+ ) -> tuple[CUTLASSTemplateKernel, functools.partial[str]]:
230
+ assert supports_epilogue_fusion or not epilogue_nodes, (
231
+ "epilogue fusion is not supported for this kernel"
232
+ )
233
+ kernel = CUTLASSTemplateKernel(
234
+ kernel_name=str(Placeholder.KERNEL_NAME),
235
+ runtime_arg_info=self.get_runtime_arg_info(),
236
+ runtime_arg_values=self.get_runtime_arg_values(**kwargs),
237
+ )
238
+ render = functools.partial(
239
+ self.render,
240
+ kernel=kernel,
241
+ template_buffer_node=template_node,
242
+ epilogue_nodes=epilogue_nodes,
243
+ **kwargs, # includes "op" argument in case of CUTLASSGemmTemplate
244
+ )
245
+ return kernel, render
246
+
247
+ return CUTLASSTemplateCaller(
248
+ kernel_name,
249
+ "cutlass_gemm",
250
+ self.input_nodes,
251
+ self.output_node.get_layout(),
252
+ make_kernel_render,
253
+ bmreq,
254
+ supports_epilogue_fusion,
255
+ self,
256
+ kwargs,
257
+ description,
258
+ )
259
+
260
+ def header(self) -> IndentedBuffer:
261
+ res = IndentedBuffer()
262
+ res.splice(
263
+ """
264
+ #include <exception>
265
+ #include <iostream>
266
+ #include <memory>
267
+ #include <random>
268
+ #include <vector>
269
+ """
270
+ )
271
+ res.splice(
272
+ """
273
+ #include "cute/tensor.hpp"
274
+ #include "cutlass/cutlass.h"
275
+ #include "cutlass/numeric_types.h"
276
+ #include "cutlass/tensor_ref.h"
277
+ #include "cutlass/util/host_tensor.h"
278
+ #include "cutlass/util/reference/host/tensor_fill.h"
279
+ #include "cutlass/util/reference/device/tensor_fill.h"
280
+ #include "cutlass/util/device_memory.h"
281
+ """
282
+ )
283
+ return res
284
+
285
+ def globals(self) -> IndentedBuffer:
286
+ res = IndentedBuffer()
287
+ res.splice(
288
+ """
289
+ // We compile all models with -fvisibility=hidden. Any symbols that need to be
290
+ // exposed in the final shared library must be declared with PT_EXPORT to make
291
+ // them visible.
292
+ #ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++)
293
+ #define PT_EXPORT __attribute__((__visibility__("default")))
294
+ #else
295
+ #ifdef _WIN32
296
+ #define PT_EXPORT __declspec(dllexport)
297
+ #else
298
+ #define PT_EXPORT
299
+ #endif
300
+ #endif
301
+ """
302
+ )
303
+ res.splice(
304
+ """
305
+ using namespace cute;
306
+ #define CUTLASS_CHECK(status) \\
307
+ { \\
308
+ cutlass::Status error = status; \\
309
+ if (error != cutlass::Status::kSuccess) { \\
310
+ auto msg = std::string("[") + __FILE__ + "] Got cutlass error: " + \\
311
+ cutlassGetStatusString(error) + " at: " + std::to_string(__LINE__); \\
312
+ throw std::runtime_error(msg); \\
313
+ } \\
314
+ }
315
+
316
+ // Used as pass-through functor in EVT just for type casting / rounding
317
+ template <typename T>
318
+ struct identity_op {
319
+ CUTLASS_HOST_DEVICE
320
+ T operator()(T val) const { return val; }
321
+ };
322
+
323
+ """
324
+ )
325
+ return res
326
+
327
+ def cute_int(self, int_str: str, var_name: str) -> str:
328
+ res = ""
329
+ if int_str in ("1", "1L"):
330
+ res = "cute::Int<1>{}"
331
+ else:
332
+ res = int_str
333
+
334
+ return f"{res} /* {var_name} */"
335
+
336
+ _DTYPE_TO_CUTLASS = {
337
+ torch.float32: "float",
338
+ torch.float64: "double",
339
+ torch.float16: "cutlass::half_t",
340
+ torch.int32: "int32_t",
341
+ torch.int16: "int16_t",
342
+ torch.int8: "int8_t",
343
+ torch.uint8: "uint8_t",
344
+ torch.bool: "bool",
345
+ torch.bfloat16: "cutlass::bfloat16_t",
346
+ torch.float8_e4m3fn: "cutlass::float_e4m3_t",
347
+ torch.float8_e5m2: "cutlass::float_e5m2_t",
348
+ }
349
+
350
+ _DTYPE_TO_CUTLASS_SPARSE_META = {
351
+ torch.int32: "uint32_t",
352
+ torch.int16: "uint16_t",
353
+ }
354
+
355
+ def cutlass_type_cast(self, node: IRNode, ptr: str) -> str:
356
+ if node is None:
357
+ return ptr
358
+ else:
359
+ return f"({self._DTYPE_TO_CUTLASS.get(node.get_dtype())}*)({ptr})"
360
+
361
+ def cutlass_sparse_meta_type_cast(self, node: IRNode, ptr: str) -> str:
362
+ if node is None:
363
+ return ptr
364
+ else:
365
+ return (
366
+ f"({self._DTYPE_TO_CUTLASS_SPARSE_META.get(node.get_dtype())}*)({ptr})"
367
+ )
368
+
369
+ def render(self, **kwargs) -> str:
370
+ raise NotImplementedError
371
+
372
+ def get_runtime_arg_info(self) -> list[ArgInfo]:
373
+ return [ArgInfo("swizzle", "const uint8_t")]
374
+
375
+ def get_runtime_arg_values(self, **kwargs) -> list[Any]:
376
+ """
377
+ Helper method to retrieve runtime args from generate kwargs
378
+ """
379
+ return [kwargs[arg.name] for arg in self.get_runtime_arg_info()]
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cutlass/utils.py ADDED
@@ -0,0 +1,480 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import atexit
3
+ import functools
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import sys
8
+ import time
9
+ from dataclasses import dataclass
10
+ from typing import Any, Optional
11
+ from typing_extensions import TypeIs
12
+
13
+ import sympy
14
+
15
+ import torch
16
+ from torch._inductor.runtime.runtime_utils import dynamo_timed
17
+ from torch._inductor.utils import clear_on_fresh_cache
18
+ from torch.utils._ordered_set import OrderedSet
19
+
20
+ from ... import config
21
+ from ...ir import Layout
22
+ from ...runtime.runtime_utils import cache_dir
23
+ from ...virtualized import V
24
+ from ..cuda.cuda_env import get_cuda_arch, get_cuda_version
25
+
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ CUTLASS_OPERATION_KIND: str = "gemm"
30
+ ACCUMULATOR_DTYPES: OrderedSet[torch.dtype] = OrderedSet([torch.float, torch.int32])
31
+ XW_DTYPES: OrderedSet[torch.dtype] = OrderedSet(
32
+ [torch.half, torch.bfloat16, torch.float8_e4m3fn, torch.int8, torch.float8_e5m2]
33
+ )
34
+
35
+
36
+ @atexit.register
37
+ def move_cutlass_compiled_cache() -> None:
38
+ """Move CUTLASS compiled cache file to the cache directory if it exists."""
39
+ if try_import_cutlass.cache_info().currsize == 0:
40
+ return
41
+
42
+ try:
43
+ import cutlass_cppgen # type: ignore[import-not-found]
44
+ except ImportError:
45
+ return
46
+
47
+ # Check if the CACHE_FILE attribute exists in cutlass_cppgen and if the file exists
48
+ if not hasattr(cutlass_cppgen, "CACHE_FILE") or not os.path.exists(
49
+ cutlass_cppgen.CACHE_FILE
50
+ ):
51
+ return
52
+
53
+ try:
54
+ filename = os.path.basename(cutlass_cppgen.CACHE_FILE)
55
+ shutil.move(cutlass_cppgen.CACHE_FILE, os.path.join(cache_dir(), filename))
56
+ log.debug("Moved CUTLASS compiled cache file to %s", cache_dir())
57
+ except OSError:
58
+ log.warning("Failed to move CUTLASS compiled cache file", exc_info=True)
59
+
60
+
61
+ def _rename_cutlass_import(content: str, cutlass_modules: list[str]) -> str:
62
+ for cutlass_module in cutlass_modules:
63
+ content = content.replace(
64
+ f"from {cutlass_module} import ",
65
+ f"from cutlass_library.{cutlass_module} import ",
66
+ )
67
+ return content
68
+
69
+
70
+ @functools.cache
71
+ def try_import_cutlass() -> bool:
72
+ """
73
+ We want to support three ways of passing in CUTLASS:
74
+ 1. fbcode, handled by the internal build system.
75
+ 2. User specifies cutlass_dir. The default is ../third_party/cutlass/,
76
+ which is the directory when developers build from source.
77
+ """
78
+ if config.is_fbcode():
79
+ try:
80
+ import cutlass_cppgen # type: ignore[import-not-found] # noqa: F401
81
+ import cutlass_library # type: ignore[import-not-found]
82
+ except ImportError as e:
83
+ log.warning( # noqa: G200
84
+ "Failed to import CUTLASS packages in fbcode: %s, ignoring the CUTLASS backend.",
85
+ str(e),
86
+ )
87
+ return False
88
+
89
+ return True
90
+
91
+ # Copy CUTLASS python scripts to a temp dir and add the temp dir to Python search path.
92
+ # This is a temporary hack to avoid CUTLASS module naming conflicts.
93
+ # TODO(ipiszy): remove this hack when CUTLASS solves Python scripts packaging structure issues.
94
+
95
+ # TODO(mlazos): epilogue visitor tree currently lives in python/cutlass,
96
+ # but will be moved to python/cutlass_library in the future (later 2025)
97
+ def path_join(path0, path1):
98
+ return os.path.abspath(os.path.join(path0, path1))
99
+
100
+ # contains both cutlass and cutlass_library
101
+ # we need cutlass for eVT
102
+ cutlass_python_path = path_join(config.cutlass.cutlass_dir, "python")
103
+ torch_root = os.path.abspath(os.path.dirname(torch.__file__))
104
+ mock_src_path = os.path.join(
105
+ torch_root,
106
+ "_inductor",
107
+ "codegen",
108
+ "cutlass",
109
+ "lib_extensions",
110
+ "cutlass_mock_imports",
111
+ )
112
+
113
+ cutlass_library_src_path = path_join(cutlass_python_path, "cutlass_library")
114
+ cutlass_cppgen_src_path = path_join(cutlass_python_path, "cutlass_cppgen")
115
+ pycute_src_path = path_join(cutlass_python_path, "pycute")
116
+
117
+ tmp_cutlass_full_path = os.path.abspath(os.path.join(cache_dir(), "torch_cutlass"))
118
+
119
+ dst_link_library = path_join(tmp_cutlass_full_path, "cutlass_library")
120
+ dst_link_cutlass_cppgen = path_join(tmp_cutlass_full_path, "cutlass_cppgen")
121
+ dst_link_pycute = path_join(tmp_cutlass_full_path, "pycute")
122
+
123
+ # mock modules to import cutlass
124
+ mock_modules = ["cuda", "scipy", "pydot"]
125
+
126
+ if os.path.isdir(cutlass_python_path):
127
+ if tmp_cutlass_full_path not in sys.path:
128
+
129
+ def link_and_append(dst_link, src_path, parent_dir):
130
+ if os.path.lexists(dst_link):
131
+ assert os.path.islink(dst_link), (
132
+ f"{dst_link} is not a symlink. Try to remove {dst_link} manually and try again."
133
+ )
134
+ assert os.path.realpath(os.readlink(dst_link)) == os.path.realpath(
135
+ src_path,
136
+ ), f"Symlink at {dst_link} does not point to {src_path}"
137
+ else:
138
+ os.makedirs(parent_dir, exist_ok=True)
139
+ os.symlink(src_path, dst_link)
140
+
141
+ if parent_dir not in sys.path:
142
+ sys.path.append(parent_dir)
143
+
144
+ link_and_append(
145
+ dst_link_library, cutlass_library_src_path, tmp_cutlass_full_path
146
+ )
147
+ link_and_append(
148
+ dst_link_cutlass_cppgen, cutlass_cppgen_src_path, tmp_cutlass_full_path
149
+ )
150
+ link_and_append(dst_link_pycute, pycute_src_path, tmp_cutlass_full_path)
151
+
152
+ for module in mock_modules:
153
+ link_and_append(
154
+ path_join(tmp_cutlass_full_path, module), # dst_link
155
+ path_join(mock_src_path, module), # src_path
156
+ tmp_cutlass_full_path, # parent
157
+ )
158
+
159
+ try:
160
+ import cutlass_cppgen # type: ignore[import-not-found] # noqa: F401, F811
161
+ import cutlass_library.generator # noqa: F401
162
+ import cutlass_library.library # noqa: F401
163
+ import cutlass_library.manifest # noqa: F401
164
+ import pycute # type: ignore[import-not-found] # noqa: F401
165
+
166
+ return True
167
+ except ImportError as e:
168
+ log.debug( # noqa: G200
169
+ "Failed to import CUTLASS packages: %s, ignoring the CUTLASS backend.",
170
+ str(e),
171
+ )
172
+ else:
173
+ log.debug(
174
+ "Failed to import CUTLASS packages: CUTLASS repo does not exist: %s",
175
+ cutlass_python_path,
176
+ )
177
+ return False
178
+
179
+
180
+ @functools.lru_cache(8)
181
+ def _normalize_cuda_arch(arch: str) -> str:
182
+ arch_num = arch
183
+ if isinstance(arch, str):
184
+ digits = "".join(ch for ch in arch if ch.isdigit())
185
+ if not digits:
186
+ raise ValueError(f"Unrecognized cuda arch: {arch}")
187
+ arch_num = int(digits)
188
+ else:
189
+ arch_num = int(arch)
190
+
191
+ if arch_num > 103:
192
+ log.warning("Detected CUDA architecture > 103: %s. Please file an issue.", arch)
193
+ return str(arch_num)
194
+ if arch_num >= 103:
195
+ return "103"
196
+ if arch_num >= 100:
197
+ return "100"
198
+ if arch_num >= 90:
199
+ return "90"
200
+ if arch_num >= 80:
201
+ return "80"
202
+ if arch_num >= 75:
203
+ return "75"
204
+ if arch_num >= 70:
205
+ return "70"
206
+ raise NotImplementedError(f"Unsupported cuda arch: {arch}")
207
+
208
+
209
+ @dataclass
210
+ class CUTLASSArgs:
211
+ """
212
+ CUTLASS args used to initialize a CUTLASS Manifest.
213
+ """
214
+
215
+ architectures: Optional[str] = None
216
+ cuda_version: Optional[str] = None
217
+ instantiation_level: Optional[str] = None
218
+ operations: Optional[str] = None
219
+
220
+ build_dir = ""
221
+ curr_build_dir = ""
222
+ generator_target = ""
223
+ kernels = "all"
224
+ ignore_kernels = ""
225
+ exclude_kernels = ""
226
+ # TODO: these three look dead?
227
+ kernel_filter_file: None = None
228
+ selected_kernel_list: None = None
229
+ interface_dir: None = None
230
+ filter_by_cc = True
231
+ disable_full_archs_compilation = False
232
+
233
+ def __post_init__(self):
234
+ if self.architectures is None or self.cuda_version is None:
235
+ raise RuntimeError(
236
+ f"{self.architectures=} or {self.cuda_version=} is None!"
237
+ )
238
+ self.architectures = _normalize_cuda_arch(self.architectures)
239
+
240
+
241
+ @clear_on_fresh_cache
242
+ @functools.cache
243
+ def _gen_ops_cached(arch, version) -> dict[Any, Any]:
244
+ # Note: Cache needs to be specific for cuda architecture and version
245
+
246
+ # Import cutlass python scripts.
247
+ assert try_import_cutlass()
248
+ import cutlass_library.generator as cutlass_generator
249
+ import cutlass_library.manifest as cutlass_manifest
250
+
251
+ if arch is None or version is None:
252
+ log.error(
253
+ "Cannot detect cuda arch %s or cuda version %s. "
254
+ "Will discard all cutlass ops. "
255
+ "Please consider setting _inductor.cuda.arch and _inductor.cuda.version configs.",
256
+ arch,
257
+ version,
258
+ )
259
+ return {}
260
+ arch = _normalize_cuda_arch(arch)
261
+ gen_arch = (
262
+ "100" if arch == "103" else arch
263
+ ) # CUTLASS SM103 generator only covers NVFB4; fallback to SM100 set
264
+ instantiation_level: str = config.cutlass.cutlass_instantiation_level
265
+ args = CUTLASSArgs(
266
+ architectures=gen_arch,
267
+ cuda_version=version,
268
+ instantiation_level=instantiation_level,
269
+ operations=CUTLASS_OPERATION_KIND,
270
+ )
271
+ manifest = cutlass_manifest.Manifest(args)
272
+
273
+ start_time = time.time()
274
+ if gen_arch == "100":
275
+ if hasattr(cutlass_generator, "GenerateSM100"):
276
+ cutlass_generator.GenerateSM100(manifest, args.cuda_version)
277
+ cutlass_generator.GenerateSM90(manifest, args.cuda_version)
278
+ else:
279
+ try:
280
+ func = getattr(cutlass_generator, "GenerateSM" + gen_arch)
281
+ func(manifest, args.cuda_version)
282
+ except AttributeError as e:
283
+ raise NotImplementedError(
284
+ "Arch " + gen_arch + " is not supported by current cutlass lib."
285
+ ) from e
286
+
287
+ log.info(
288
+ "CUTLASS library generated a dict of %d operation kinds in %.2f seconds",
289
+ len(manifest.operations),
290
+ time.time() - start_time,
291
+ )
292
+ return manifest.operations
293
+
294
+
295
+ def gen_ops() -> dict[Any, Any]:
296
+ """
297
+ Generates all supported CUTLASS operations.
298
+ """
299
+ with dynamo_timed("cutlass_utils.gen_ops"):
300
+ arch = get_cuda_arch()
301
+ version = get_cuda_version()
302
+ return _gen_ops_cached(arch, version)
303
+
304
+
305
+ from ..cpp_utils import DTYPE_TO_CPP
306
+
307
+
308
+ DTYPE_TO_CUTLASS_TYPE = {
309
+ **DTYPE_TO_CPP,
310
+ torch.float16: "__half",
311
+ torch.bfloat16: "__nv_bfloat16",
312
+ torch.float8_e4m3fn: "__nv_fp8_e4m3",
313
+ torch.float8_e5m2: "__nv_fp8_e5m2",
314
+ }
315
+
316
+
317
+ @functools.lru_cache(32)
318
+ def torch_dtype_to_cutlass_type(
319
+ torch_dtype: torch.dtype,
320
+ ) -> "cutlass_library.library.DataType": # type: ignore[name-defined] # noqa: F821
321
+ # Import cutlass python scripts.
322
+ assert try_import_cutlass()
323
+ import cutlass_library # type: ignore[import]
324
+
325
+ if torch_dtype == torch.float:
326
+ return cutlass_library.library.DataType.f32
327
+ elif torch_dtype == torch.half:
328
+ return cutlass_library.library.DataType.f16
329
+ elif torch_dtype == torch.bfloat16:
330
+ return cutlass_library.library.DataType.bf16
331
+ else:
332
+ raise NotImplementedError(f"Unsupported data type: {torch_dtype=}")
333
+
334
+
335
+ @functools.lru_cache(32)
336
+ def dtype_match(
337
+ torch_dtype: Optional[torch.dtype],
338
+ cutlass_dtype: "cutlass_library.library.DataType", # type: ignore[name-defined] # noqa: F821
339
+ ) -> bool:
340
+ # Import cutlass python scripts.
341
+ assert try_import_cutlass()
342
+ import cutlass_library
343
+
344
+ if torch_dtype == torch.float:
345
+ return (
346
+ cutlass_dtype == cutlass_library.library.DataType.f32
347
+ or cutlass_dtype == cutlass_library.library.DataType.tf32
348
+ )
349
+ elif torch_dtype == torch.half:
350
+ return cutlass_dtype == cutlass_library.library.DataType.f16
351
+ elif torch_dtype == torch.bfloat16:
352
+ return cutlass_dtype == cutlass_library.library.DataType.bf16
353
+ elif torch_dtype == torch.int8:
354
+ return cutlass_dtype == cutlass_library.library.DataType.s8
355
+ elif torch_dtype == torch.uint8:
356
+ return cutlass_dtype == cutlass_library.library.DataType.u8
357
+ elif torch_dtype == torch.int32:
358
+ return cutlass_dtype == cutlass_library.library.DataType.s32
359
+ elif torch_dtype == torch.float8_e4m3fn:
360
+ return cutlass_dtype == cutlass_library.library.DataType.e4m3
361
+ elif torch_dtype == torch.float8_e5m2:
362
+ return cutlass_dtype == cutlass_library.library.DataType.e5m2
363
+ else:
364
+ return False
365
+
366
+
367
+ def get_accumulator_dtype(
368
+ input_torch_dtypes: list[torch.dtype],
369
+ ) -> Optional[torch.dtype]:
370
+ """
371
+ Given a pair of input torch dtypes, returns the inferred accumulator torch dtype.
372
+ """
373
+
374
+ assert OrderedSet(input_torch_dtypes) <= XW_DTYPES, (
375
+ f"{input_torch_dtypes=} is not supported"
376
+ )
377
+
378
+ if len(input_torch_dtypes) != 2:
379
+ return None
380
+
381
+ if OrderedSet(input_torch_dtypes) == OrderedSet(
382
+ [torch.float8_e5m2, torch.float8_e4m3fn]
383
+ ):
384
+ return torch.float
385
+
386
+ torch_dtype = None
387
+ if input_torch_dtypes[0] == input_torch_dtypes[1]:
388
+ torch_dtype = input_torch_dtypes[0]
389
+ else:
390
+ size0 = torch.tensor([], dtype=input_torch_dtypes[0]).element_size()
391
+ size1 = torch.tensor([], dtype=input_torch_dtypes[1]).element_size()
392
+ if size0 > size1:
393
+ dtype0, dtype1 = input_torch_dtypes
394
+ else:
395
+ dtype1, dtype0 = input_torch_dtypes
396
+ if dtype0 in [torch.half, torch.bfloat16] and dtype1 in [
397
+ torch.int8,
398
+ torch.uint8,
399
+ ]:
400
+ torch_dtype = dtype0
401
+
402
+ if torch_dtype in (
403
+ torch.float16,
404
+ torch.bfloat16,
405
+ torch.float,
406
+ torch.float8_e4m3fn,
407
+ torch.float8_e5m2,
408
+ ):
409
+ accumulator_dtype = torch.float
410
+ elif torch_dtype == torch.int8:
411
+ accumulator_dtype = torch.int32
412
+ else:
413
+ raise NotImplementedError(f"Unsupported data types: {input_torch_dtypes=}")
414
+
415
+ assert accumulator_dtype in ACCUMULATOR_DTYPES, (
416
+ f"{accumulator_dtype=} is not supported"
417
+ )
418
+ return accumulator_dtype
419
+
420
+
421
+ @functools.lru_cache(32)
422
+ def get_alignments(torch_dtype: torch.dtype) -> list[int]:
423
+ """
424
+ Returns all possible valid CUTLASS alignments in terms of the number of elements for a given dtype.
425
+ CUTLASS gemm / conv SM80 APIs support 16 bytes max alignment, and 2 bytes min alignment.
426
+ """
427
+
428
+ if torch_dtype in (torch.half, torch.bfloat16):
429
+ return [8, 4, 2, 1]
430
+ elif torch_dtype == torch.float:
431
+ return [4, 2, 1]
432
+ elif torch_dtype in (
433
+ torch.uint8,
434
+ torch.int8,
435
+ torch.float8_e4m3fn,
436
+ torch.float8_e5m2,
437
+ ):
438
+ return [16, 8, 4, 2]
439
+ elif torch_dtype == torch.int32:
440
+ return [4, 2, 1]
441
+ else:
442
+ raise NotImplementedError(f"unsupported {torch_dtype=} for alignments")
443
+
444
+
445
+ def get_max_alignment(inductor_layout: Layout) -> int:
446
+ """
447
+ Returns the max alignment (in terms of number of elements) for a given Inductor Layout.
448
+ """
449
+
450
+ dtype = inductor_layout.dtype
451
+ size = inductor_layout.size
452
+ offset = inductor_layout.offset
453
+
454
+ def is_static_int(number: object) -> TypeIs[int | sympy.Integer]:
455
+ return isinstance(number, (int | sympy.Integer))
456
+
457
+ def a_factor_of(x, alignment):
458
+ if is_static_int(x) and is_static_int(alignment):
459
+ return x % alignment == 0
460
+ rem = sympy.Mod(x, alignment)
461
+ return V.graph.sizevars.evaluate_expr(sympy.Eq(rem, 0))
462
+
463
+ try:
464
+ contiguous_dim = inductor_layout.stride.index(1)
465
+ except ValueError:
466
+ # No dim with stride 1 found, return 1
467
+ return 1
468
+ alignments = get_alignments(dtype)
469
+ for alignment in alignments:
470
+ if not a_factor_of(size[contiguous_dim], alignment) or not a_factor_of(
471
+ offset, alignment
472
+ ):
473
+ continue
474
+ if all(
475
+ (dim == contiguous_dim)
476
+ or a_factor_of(inductor_layout.stride[dim], alignment)
477
+ for dim in range(len(size))
478
+ ):
479
+ return alignment
480
+ return 1
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/mtia/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/mtia/device_op_overrides.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ..common import DeviceOpOverrides, register_device_op_overrides
4
+
5
+
6
+ class MTIADeviceOpOverrides(DeviceOpOverrides):
7
+ def import_get_raw_stream_as(self, name: str) -> str:
8
+ return f"from torch._C import _mtia_getCurrentRawStream as {name}"
9
+
10
+ def set_device(self, device_idx: int) -> str:
11
+ return f"torch.mtia.set_device({device_idx})"
12
+
13
+ def synchronize(self) -> str:
14
+ return "torch.mtia.synchronize()"
15
+
16
+ def device_guard(self, device_idx: int) -> str:
17
+ return f"torch.mtia.device({device_idx})"
18
+
19
+
20
+ register_device_op_overrides("mtia", MTIADeviceOpOverrides())
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from .nv_universal_gemm import (
3
+ add_nv_universal_gemm_choices,
4
+ add_nv_universal_grouped_gemm_choices,
5
+ add_nv_universal_scaled_gemm_choices,
6
+ GemmVariant,
7
+ NVUniversalGemmCaller,
8
+ )
9
+
10
+
11
+ __all__ = [
12
+ "GemmVariant",
13
+ "NVUniversalGemmCaller",
14
+ "add_nv_universal_gemm_choices",
15
+ "add_nv_universal_grouped_gemm_choices",
16
+ "add_nv_universal_scaled_gemm_choices",
17
+ ]
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/kernel_cache.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Global kernel cache for NVIDIA Universal GEMM.
4
+
5
+ This module provides a lazy-initialized cache for cutlass_api kernels,
6
+ avoiding expensive manifest scans on every kernel lookup.
7
+
8
+ The first call to get_kernel_by_name() loads all kernels from cutlass_api
9
+ (~10 seconds) and builds a name->kernel dict. Subsequent calls use the
10
+ dict for O(1) lookup (~0.1 μs).
11
+ """
12
+
13
+ import logging
14
+ from collections.abc import Callable
15
+ from typing import Any, Optional
16
+
17
+
18
+ log = logging.getLogger(__name__)
19
+
20
+ # Global cache: kernel_name -> kernel object
21
+ _kernel_by_name_cache: Optional[dict[str, Any]] = None
22
+
23
+
24
+ def _build_kernel_cache() -> dict[str, Any]:
25
+ """Build the kernel name -> kernel object cache."""
26
+ import cutlass_api
27
+
28
+ log.debug("Building NVGEMM kernel cache (this may take a few seconds)...")
29
+ all_kernels = cutlass_api.get_kernels()
30
+ cache = {k.metadata.kernel_name: k for k in all_kernels}
31
+ log.debug("NVGEMM kernel cache built: %d kernels", len(cache))
32
+ return cache
33
+
34
+
35
+ def get_compatible_kernels(
36
+ args: Any,
37
+ cc: int,
38
+ metadata_filter: Optional[Callable[[Any], bool]] = None,
39
+ ) -> list[Any]:
40
+ """Get kernels compatible with the given arguments from the cache."""
41
+ global _kernel_by_name_cache
42
+
43
+ if _kernel_by_name_cache is None:
44
+ _kernel_by_name_cache = _build_kernel_cache()
45
+
46
+ compatible = []
47
+ for kernel in _kernel_by_name_cache.values():
48
+ if kernel.metadata.min_cc > cc:
49
+ continue
50
+
51
+ if metadata_filter is not None and not metadata_filter(kernel.metadata):
52
+ continue
53
+
54
+ status = kernel.supports(args)
55
+ if status.error is not None:
56
+ continue
57
+ compatible.append(kernel)
58
+
59
+ log.debug(
60
+ "Found %d compatible kernels from cache of %d total",
61
+ len(compatible),
62
+ len(_kernel_by_name_cache),
63
+ )
64
+ return compatible
65
+
66
+
67
+ def get_kernel_by_name(kernel_name: str) -> Any:
68
+ """Get a cutlass_api kernel by name using the global cache."""
69
+ global _kernel_by_name_cache
70
+
71
+ if _kernel_by_name_cache is None:
72
+ _kernel_by_name_cache = _build_kernel_cache()
73
+
74
+ return _kernel_by_name_cache.get(kernel_name)
75
+
76
+
77
+ def ensure_cache_initialized() -> None:
78
+ """Ensure the kernel cache is initialized."""
79
+ global _kernel_by_name_cache
80
+
81
+ if _kernel_by_name_cache is None:
82
+ _kernel_by_name_cache = _build_kernel_cache()
83
+
84
+
85
+ def clear_cache() -> None:
86
+ """Clear the kernel cache."""
87
+ global _kernel_by_name_cache
88
+ _kernel_by_name_cache = None
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ NVIDIA Universal GEMM (NVGEMM) backend for PyTorch Inductor.
4
+
5
+ This module provides integration with the cutlass_api library to enable
6
+ high-performance GEMM kernels for NVIDIA GPUs.
7
+ """
8
+
9
+ import itertools
10
+ from enum import auto, Enum
11
+ from typing import Any, Optional, Union
12
+
13
+ import torch
14
+ from torch._inductor import config
15
+ from torch._inductor.autotune_process import (
16
+ BenchmarkRequest,
17
+ GPUDeviceBenchmarkMixin,
18
+ TensorMeta,
19
+ )
20
+ from torch._inductor.codegen.cuda.cuda_env import get_cuda_arch
21
+ from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_utils import (
22
+ to_cutlass_scale_mode,
23
+ )
24
+ from torch._inductor.ir import Buffer, ChoiceCaller, Layout, TensorBox
25
+ from torch._inductor.kernel_inputs import MMKernelInputs
26
+ from torch._inductor.template_heuristics.nv_universal_gemm import get_nvgemm_heuristics
27
+ from torch._inductor.utils import ensure_nv_universal_gemm_available
28
+ from torch._logging import getArtifactLogger
29
+
30
+
31
+ log = getArtifactLogger(__name__, "output_code")
32
+
33
+
34
+ class GemmVariant(Enum):
35
+ """
36
+ Enum for different GEMM operation types supported by NVIDIA Universal GEMM.
37
+ """
38
+
39
+ GEMM = auto()
40
+
41
+ GROUPED_GEMM = auto()
42
+
43
+ SCALED_GEMM = auto()
44
+
45
+ @property
46
+ def op_name(self) -> str:
47
+ """Return the operation name for logging and naming."""
48
+ if self == GemmVariant.GROUPED_GEMM:
49
+ return "nv_universal_grouped_gemm"
50
+ if self == GemmVariant.SCALED_GEMM:
51
+ return "nv_universal_scaled_gemm"
52
+ return "nv_universal_gemm"
53
+
54
+ @property
55
+ def arguments_class_name(self) -> str:
56
+ """Return the cutlass_api arguments class name."""
57
+ if self == GemmVariant.GROUPED_GEMM:
58
+ return "GroupedGemmArguments"
59
+ return "GemmArguments"
60
+
61
+
62
+ class NVUniversalGemmBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest):
63
+ """Benchmark request for NVIDIA Universal GEMM kernels."""
64
+
65
+ def __init__(
66
+ self,
67
+ kernel_name: str,
68
+ input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
69
+ output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
70
+ kernel, # cutlass_api.Kernel object
71
+ accumulator_type: torch.dtype,
72
+ variant: GemmVariant,
73
+ workspace_size: int = 0,
74
+ scale_type_a: Optional[Any] = None,
75
+ scale_type_b: Optional[Any] = None,
76
+ swizzle_type_a: Optional[Any] = None,
77
+ swizzle_type_b: Optional[Any] = None,
78
+ ) -> None:
79
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, ())
80
+ self.kernel = kernel
81
+ self.accumulator_type = accumulator_type
82
+ self._compiled_artifact = None
83
+ self._workspace: Optional[torch.Tensor] = None
84
+ self.workspace_size = workspace_size
85
+ self.variant = variant
86
+ self.scale_type_a = scale_type_a
87
+ self.scale_type_b = scale_type_b
88
+ self.swizzle_type_a = swizzle_type_a
89
+ self.swizzle_type_b = swizzle_type_b
90
+
91
+ def benchmark(
92
+ self,
93
+ *input_tensors: torch.Tensor,
94
+ out: Optional[torch.Tensor] = None,
95
+ ) -> float:
96
+ """Benchmark the NVIDIA Universal GEMM kernel.
97
+
98
+ Override the base class to always create tensors from input_tensor_meta.
99
+ This is necessary because input_nodes may be ReinterpretViews that share
100
+ the same underlying buffer name. The autotuning framework deduplicates
101
+ inputs by name (in AlgorithmSelectorCache.get_inputs()), resulting in
102
+ fewer tensors than expected. By always creating from input_tensor_meta,
103
+ we ensure each input gets its own tensor with the correct size/stride/offset
104
+ from the view's layout.
105
+ """
106
+ # Always create tensors from input_tensor_meta, ignoring passed-in tensors
107
+ input_tensors = tuple(x.to_tensor() for x in self.input_tensor_meta)
108
+ if out is None:
109
+ out = self.output_tensor_meta.to_tensor()
110
+
111
+ fn = self.make_run_fn(*input_tensors, out=out)
112
+ return self.do_bench(fn, *input_tensors, out=out)
113
+
114
+ def make_run_fn(self, *input_tensors: torch.Tensor, out: torch.Tensor):
115
+ """Create a function to run the NVIDIA Universal GEMM kernel."""
116
+ import cutlass_api
117
+
118
+ args = self._create_gemm_arguments(cutlass_api, input_tensors, out)
119
+
120
+ if self._compiled_artifact is None:
121
+ self._compiled_artifact = self.kernel.compile(args)
122
+ artifact = self._compiled_artifact
123
+ kernel = self.kernel
124
+
125
+ # Allocate workspace if needed
126
+ if self.workspace_size > 0:
127
+ self._workspace = torch.empty(
128
+ self.workspace_size, device=out.device, dtype=torch.int8
129
+ )
130
+ else:
131
+ self._workspace = None
132
+
133
+ workspace = self._workspace
134
+
135
+ def run_kernel():
136
+ stream = torch.cuda.current_stream()
137
+ kernel.run(
138
+ args,
139
+ artifact,
140
+ stream=stream,
141
+ workspace=workspace,
142
+ assume_supported_args=True,
143
+ )
144
+
145
+ return run_kernel
146
+
147
+ def _create_gemm_arguments(self, cutlass_api, input_tensors, out):
148
+ """Create the appropriate GemmArguments based on variant."""
149
+ if self.variant == GemmVariant.GROUPED_GEMM:
150
+ a, b, offsets = input_tensors
151
+ return cutlass_api.arguments.GroupedGemmArguments(
152
+ a,
153
+ b,
154
+ out,
155
+ accumulator_type=self.accumulator_type,
156
+ offsets=offsets,
157
+ )
158
+ elif self.variant == GemmVariant.SCALED_GEMM:
159
+ from cutlass_api.arguments import ScaledTensor
160
+
161
+ scale_mode_a, swizzle_mode_a = to_cutlass_scale_mode(
162
+ self.scale_type_a, self.swizzle_type_a
163
+ )
164
+ scale_mode_b, swizzle_mode_b = to_cutlass_scale_mode(
165
+ self.scale_type_b, self.swizzle_type_b
166
+ )
167
+
168
+ a, b, scale_a, scale_b = input_tensors
169
+ scaled_a = ScaledTensor(a, scale_a, scale_mode_a, swizzle_mode_a)
170
+ scaled_b = ScaledTensor(b, scale_b, scale_mode_b, swizzle_mode_b)
171
+ return cutlass_api.arguments.GemmArguments(
172
+ scaled_a,
173
+ scaled_b,
174
+ out,
175
+ accumulator_type=self.accumulator_type,
176
+ )
177
+ else:
178
+ a, b = input_tensors
179
+ return cutlass_api.arguments.GemmArguments(
180
+ a,
181
+ b,
182
+ out,
183
+ accumulator_type=self.accumulator_type,
184
+ )
185
+
186
+ def cleanup_run_fn(self) -> None:
187
+ self._workspace = None
188
+
189
+
190
+ class NVUniversalGemmCaller(ChoiceCaller):
191
+ """
192
+ ChoiceCaller for NVIDIA Universal GEMM kernels.
193
+
194
+ Wraps a cutlass_api kernel and integrates with Inductor's autotuning.
195
+ """
196
+
197
+ index_counter = itertools.count()
198
+
199
+ def __init__(
200
+ self,
201
+ name: str,
202
+ input_nodes: list[Buffer],
203
+ layout: Layout,
204
+ kernel, # cutlass_api.Kernel object
205
+ accumulator_type: torch.dtype,
206
+ variant: GemmVariant,
207
+ workspace_size: int = 0,
208
+ scale_type_a: Optional[Any] = None,
209
+ scale_type_b: Optional[Any] = None,
210
+ swizzle_type_a: Optional[Any] = None,
211
+ swizzle_type_b: Optional[Any] = None,
212
+ ) -> None:
213
+ super().__init__(
214
+ name=name,
215
+ input_nodes=input_nodes,
216
+ layout=layout,
217
+ description=f"{variant.op_name} {kernel.metadata.kernel_name}",
218
+ )
219
+ self.kernel = kernel
220
+ self.accumulator_type = accumulator_type
221
+ self.workspace_size = workspace_size
222
+ self.variant = variant
223
+ self.scale_type_a = scale_type_a
224
+ self.scale_type_b = scale_type_b
225
+ self.swizzle_type_a = swizzle_type_a
226
+ self.swizzle_type_b = swizzle_type_b
227
+
228
+ output_buffer = Buffer(name=f"{variant.op_name}_out", layout=layout)
229
+
230
+ self.bmreq = NVUniversalGemmBenchmarkRequest(
231
+ kernel_name=name,
232
+ input_tensor_meta=TensorMeta.from_irnodes(input_nodes),
233
+ output_tensor_meta=TensorMeta.from_irnodes(output_buffer),
234
+ kernel=kernel,
235
+ accumulator_type=accumulator_type,
236
+ workspace_size=workspace_size,
237
+ variant=variant,
238
+ scale_type_a=scale_type_a,
239
+ scale_type_b=scale_type_b,
240
+ swizzle_type_a=swizzle_type_a,
241
+ swizzle_type_b=swizzle_type_b,
242
+ )
243
+
244
+ def __str__(self) -> str:
245
+ return f"NVUniversalGemmCaller({self.kernel.metadata.kernel_name})"
246
+
247
+ def benchmark(self, *args, out) -> float:
248
+ return self.bmreq.benchmark(*args, out=out)
249
+
250
+ def output_node(self) -> TensorBox:
251
+ from torch._inductor.ir import NVUniversalGemmBuffer
252
+
253
+ buffer = NVUniversalGemmBuffer(
254
+ layout=self.layout,
255
+ inputs=self.input_nodes,
256
+ kernel=self.kernel,
257
+ accumulator_type=self.accumulator_type,
258
+ workspace_size=self.workspace_size,
259
+ variant=self.variant,
260
+ scale_type_a=self.scale_type_a,
261
+ scale_type_b=self.scale_type_b,
262
+ swizzle_type_a=self.swizzle_type_a,
263
+ swizzle_type_b=self.swizzle_type_b,
264
+ )
265
+ # Pass KTC annotation to the buffer for encoding
266
+ if "ktc" in self.annotations:
267
+ buffer.annotations["ktc"] = self.annotations["ktc"]
268
+ return TensorBox.create(buffer)
269
+
270
+ def call_name(self) -> str:
271
+ return self.name
272
+
273
+ def to_callable(self):
274
+ return self.bmreq.make_run_fn
275
+
276
+ def hash_key(self) -> str:
277
+ return f"{self.variant.op_name}_{self.kernel.metadata.kernel_name}"
278
+
279
+ def info_dict(self) -> dict[str, Any]:
280
+ return {
281
+ "name": self.name,
282
+ "backend": self.variant.op_name,
283
+ "kernel_name": self.kernel.metadata.kernel_name,
284
+ }
285
+
286
+
287
+ def _create_dummy_tensor_from_layout(layout: Layout) -> Optional[torch.Tensor]:
288
+ """
289
+ Create a FakeTensor from a Layout for kernel filtering.
290
+
291
+ Uses Layout.get_example() which creates FakeTensors within V.fake_mode,
292
+ avoiding real CUDA memory allocation. cutlass_api only needs shape/stride/dtype
293
+ metadata for its supports() checks.
294
+ """
295
+ try:
296
+ return layout.get_example()
297
+ except Exception:
298
+ return None
299
+
300
+
301
+ def _exclude_efc_kernels(metadata) -> bool:
302
+ """
303
+ Filter out EFC kernels.
304
+
305
+ EFC kernels support custom epilogue operations but have additional overhead.
306
+ Since NVGEMM doesn't support epilogue fusion yet (see nv_universal_gemm_scheduling.py),
307
+ we use non-EFC kernels which are equivalent for identity epilogue (out = acc).
308
+ TODO(nikhilap): Remove this filter once NVGEMM supports epilogue fusion.
309
+ """
310
+ return "EFC" not in metadata.kernel_class.__name__
311
+
312
+
313
+ def _add_nv_gemm_choices_impl(
314
+ choices: list[ChoiceCaller],
315
+ layout: Layout,
316
+ input_nodes: list[Buffer],
317
+ variant: GemmVariant,
318
+ accumulator_type: torch.dtype,
319
+ mm_inputs: Optional[MMKernelInputs] = None,
320
+ scale_type_a: Optional[Any] = None,
321
+ scale_type_b: Optional[Any] = None,
322
+ swizzle_type_a: Optional[Any] = None,
323
+ swizzle_type_b: Optional[Any] = None,
324
+ ) -> None:
325
+ """
326
+ Unified implementation for adding NVIDIA Universal GEMM choices.
327
+
328
+ Args:
329
+ choices: List to append ChoiceCaller objects to
330
+ layout: Output layout
331
+ input_nodes: Input tensor nodes
332
+ variant: The GEMM variant (determines behavior)
333
+ accumulator_type: Accumulator dtype
334
+ mm_inputs: Optional MMKernelInputs for heuristics
335
+ scale_type_a: ScalingType for A (required for SCALED_GEMM)
336
+ scale_type_b: ScalingType for B (required for SCALED_GEMM)
337
+ swizzle_type_a: SwizzleType for A (required for SCALED_GEMM)
338
+ swizzle_type_b: SwizzleType for B (required for SCALED_GEMM)
339
+ """
340
+ import cutlass_api
341
+
342
+ from torch._inductor.codegen.nv_universal_gemm.kernel_cache import (
343
+ get_compatible_kernels,
344
+ )
345
+
346
+ # Create dummy tensors for cutlass_api's supports() checks
347
+ dummy_tensors = [
348
+ _create_dummy_tensor_from_layout(node.get_layout()) for node in input_nodes
349
+ ]
350
+ out_tensor = _create_dummy_tensor_from_layout(layout)
351
+
352
+ if any(t is None for t in dummy_tensors) or out_tensor is None:
353
+ log.debug("Failed to create dummy tensors for %s", variant.op_name)
354
+ return
355
+
356
+ if variant == GemmVariant.GROUPED_GEMM:
357
+ a_tensor, b_tensor, offs_tensor = dummy_tensors
358
+ assert b_tensor is not None
359
+ args = cutlass_api.arguments.GroupedGemmArguments(
360
+ a_tensor,
361
+ b_tensor,
362
+ out_tensor,
363
+ accumulator_type=accumulator_type,
364
+ offsets=offs_tensor,
365
+ )
366
+ elif variant == GemmVariant.SCALED_GEMM:
367
+ from cutlass_api.arguments import ScaledTensor
368
+
369
+ scale_mode_a, swizzle_mode_a = to_cutlass_scale_mode(
370
+ scale_type_a, swizzle_type_a
371
+ )
372
+ scale_mode_b, swizzle_mode_b = to_cutlass_scale_mode(
373
+ scale_type_b, swizzle_type_b
374
+ )
375
+ if scale_mode_a is None or scale_mode_b is None:
376
+ return
377
+
378
+ a_tensor, b_tensor, scale_a_tensor, scale_b_tensor = dummy_tensors
379
+ scaled_a = ScaledTensor(
380
+ a_tensor,
381
+ scale_a_tensor,
382
+ scale_mode_a,
383
+ swizzle_mode_a,
384
+ )
385
+ scaled_b = ScaledTensor(
386
+ b_tensor,
387
+ scale_b_tensor,
388
+ scale_mode_b,
389
+ swizzle_mode_b,
390
+ )
391
+ args = cutlass_api.arguments.GemmArguments(
392
+ scaled_a,
393
+ scaled_b,
394
+ out_tensor,
395
+ accumulator_type=accumulator_type,
396
+ )
397
+ else:
398
+ a_tensor, b_tensor = dummy_tensors
399
+ args = cutlass_api.arguments.GemmArguments(
400
+ a_tensor,
401
+ b_tensor,
402
+ out_tensor,
403
+ accumulator_type=accumulator_type,
404
+ )
405
+
406
+ cc = get_cuda_arch()
407
+ if cc is None:
408
+ log.debug("Failed to get CUDA arch")
409
+ return
410
+ cc_int = int(cc)
411
+
412
+ kernels = get_compatible_kernels(args, cc_int, metadata_filter=_exclude_efc_kernels)
413
+ if not kernels:
414
+ log.debug("No compatible %s kernels found", variant.op_name)
415
+ return
416
+
417
+ max_configs = config.nvgemm_max_profiling_configs or len(kernels)
418
+ if variant in (GemmVariant.GEMM, GemmVariant.SCALED_GEMM) and mm_inputs is not None:
419
+ heuristics = get_nvgemm_heuristics()
420
+ kernels = heuristics.filter_kernels(
421
+ kernels, mm_inputs, max_configs, accumulator_type
422
+ )
423
+ else:
424
+ # TODO(nikhilap): Enable heuristics for grouped GEMM
425
+ # when nvMatmulHeuristics adds support
426
+ kernels = kernels[:max_configs]
427
+
428
+ # Add callers for each kernel
429
+ num_added = 0
430
+ for kernel in kernels:
431
+ name = f"{variant.op_name}_{next(NVUniversalGemmCaller.index_counter)}"
432
+ workspace_size = kernel.get_workspace_size(args)
433
+ try:
434
+ caller = NVUniversalGemmCaller(
435
+ name=name,
436
+ input_nodes=input_nodes,
437
+ layout=layout,
438
+ kernel=kernel,
439
+ accumulator_type=accumulator_type,
440
+ workspace_size=workspace_size,
441
+ variant=variant,
442
+ scale_type_a=scale_type_a,
443
+ scale_type_b=scale_type_b,
444
+ swizzle_type_a=swizzle_type_a,
445
+ swizzle_type_b=swizzle_type_b,
446
+ )
447
+ choices.append(caller)
448
+ num_added += 1
449
+ except Exception:
450
+ log.debug("Failed to create %s choice", variant.op_name, exc_info=True)
451
+
452
+ log.debug("Added %d %s choices", num_added, variant.op_name)
453
+
454
+
455
+ def add_nv_universal_gemm_choices(
456
+ choices: list[ChoiceCaller],
457
+ layout: Layout,
458
+ inputs: MMKernelInputs,
459
+ accumulator_type: Optional[torch.dtype] = None,
460
+ ) -> None:
461
+ """
462
+ Add NVIDIA Universal GEMM kernels to the autotune choices.
463
+
464
+ Thin wrapper around _add_nv_gemm_choices_impl for regular GEMM.
465
+ """
466
+ if not ensure_nv_universal_gemm_available():
467
+ log.debug("cutlass_api not available, skipping NVIDIA Universal GEMM choices")
468
+ return
469
+
470
+ _add_nv_gemm_choices_impl(
471
+ choices=choices,
472
+ layout=layout,
473
+ input_nodes=inputs.nodes(),
474
+ variant=GemmVariant.GEMM,
475
+ accumulator_type=accumulator_type or torch.float32,
476
+ mm_inputs=inputs,
477
+ )
478
+
479
+
480
+ def add_nv_universal_grouped_gemm_choices(
481
+ choices: list[ChoiceCaller],
482
+ layout: Layout,
483
+ input_nodes: list[Buffer],
484
+ accumulator_type: Optional[torch.dtype] = None,
485
+ ) -> None:
486
+ """
487
+ Add NVIDIA Universal Grouped GEMM kernels to the autotune choices.
488
+
489
+ Thin wrapper around _add_nv_gemm_choices_impl for grouped GEMM.
490
+
491
+ For grouped GEMM (contiguous offset variant):
492
+ - A is (TotalM, K) with problems stacked along M
493
+ - B is (G, K, N) where B[i] is the weight for problem i
494
+ - offsets is (G,) marking where each problem ends in A
495
+ - Output is (TotalM, N)
496
+ """
497
+ if not ensure_nv_universal_gemm_available():
498
+ log.debug(
499
+ "cutlass_api not available, skipping NVIDIA Universal Grouped GEMM choices"
500
+ )
501
+ return
502
+
503
+ _add_nv_gemm_choices_impl(
504
+ choices=choices,
505
+ layout=layout,
506
+ input_nodes=input_nodes,
507
+ variant=GemmVariant.GROUPED_GEMM,
508
+ accumulator_type=accumulator_type or torch.float32,
509
+ )
510
+
511
+
512
+ def add_nv_universal_scaled_gemm_choices(
513
+ choices: list[ChoiceCaller],
514
+ layout: Layout,
515
+ input_nodes: list[Buffer],
516
+ accumulator_type: Optional[torch.dtype] = None,
517
+ kernel_inputs: Optional[MMKernelInputs] = None,
518
+ ) -> None:
519
+ """
520
+ Add NVIDIA Universal Scaled GEMM (FP8) kernels to the autotune choices.
521
+
522
+ The scaling type is inferred from the input shapes/dtypes.
523
+ If the scaling mode is unsupported by NVGEMM, this function returns without
524
+ adding any choices.
525
+ """
526
+ if not ensure_nv_universal_gemm_available():
527
+ return
528
+
529
+ from torch._inductor.utils import infer_scale_swizzle_ir
530
+
531
+ if len(input_nodes) < 4:
532
+ return
533
+
534
+ mat_a, mat_b, scale_a, scale_b = input_nodes[:4]
535
+
536
+ scale_type_a, swizzle_type_a = infer_scale_swizzle_ir(mat_a, scale_a)
537
+ scale_type_b, swizzle_type_b = infer_scale_swizzle_ir(
538
+ mat_b, scale_b, transpose=True
539
+ )
540
+
541
+ if scale_type_a is None or scale_type_b is None:
542
+ return
543
+
544
+ _add_nv_gemm_choices_impl(
545
+ choices=choices,
546
+ layout=layout,
547
+ input_nodes=input_nodes,
548
+ variant=GemmVariant.SCALED_GEMM,
549
+ accumulator_type=accumulator_type or torch.float32,
550
+ mm_inputs=kernel_inputs,
551
+ scale_type_a=scale_type_a,
552
+ scale_type_b=scale_type_b,
553
+ swizzle_type_a=swizzle_type_a,
554
+ swizzle_type_b=swizzle_type_b,
555
+ )
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_kernel.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ NVIDIA Universal GEMM kernel code generation.
4
+
5
+ This module generates Python code that calls cutlass_api to execute GEMM operations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from typing import Any, Optional, TYPE_CHECKING, Union
12
+
13
+ from torch._inductor.codegen.common import (
14
+ IndentedBuffer,
15
+ Kernel,
16
+ WorkspaceArg,
17
+ WorkspaceZeroMode,
18
+ )
19
+ from torch._inductor.codegen.cutedsl.cutedsl_op_overrides import CuteDSLOpOverrides
20
+ from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_utils import (
21
+ to_cutlass_scale_mode,
22
+ )
23
+ from torch._inductor.ir import (
24
+ BaseView,
25
+ Buffer,
26
+ ExternKernel,
27
+ MutableBox,
28
+ ReinterpretView,
29
+ )
30
+ from torch._inductor.virtualized import V
31
+ from torch.utils._ordered_set import OrderedSet
32
+
33
+
34
+ if TYPE_CHECKING:
35
+ from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm import GemmVariant
36
+
37
+
38
+ log = logging.getLogger(__name__)
39
+
40
+
41
+ class NVUniversalGemmKernelWrapper:
42
+ """Wrapper to provide .run() interface for NVIDIA Universal GEMM kernels."""
43
+
44
+ def __init__(self, kernel_fn, kernel_path: Optional[str] = None):
45
+ self.kernel_fn = kernel_fn
46
+ self.kernel_path = kernel_path
47
+
48
+ def run(self, *args, stream=None, **kwargs):
49
+ """Execute the NVIDIA Universal GEMM kernel."""
50
+ return self.kernel_fn(*args, stream=stream, **kwargs)
51
+
52
+
53
+ class NVUniversalGemmKernel(Kernel):
54
+ """
55
+ Kernel implementation for NVIDIA Universal GEMM.
56
+
57
+ Generates Python code that calls cutlass_api to execute GEMM operations.
58
+ Unlike CuteDSL which uses Jinja templates, this generates simpler direct
59
+ Python code.
60
+ """
61
+
62
+ def __init__(
63
+ self,
64
+ kernel_name: str,
65
+ input_nodes: list[Buffer],
66
+ output_node: Buffer,
67
+ kernel_metadata: dict[str, Any],
68
+ accumulator_type: Any,
69
+ variant: GemmVariant,
70
+ workspace_size: int = 0,
71
+ scale_type_a: Optional[Any] = None,
72
+ scale_type_b: Optional[Any] = None,
73
+ swizzle_type_a: Optional[Any] = None,
74
+ swizzle_type_b: Optional[Any] = None,
75
+ ) -> None:
76
+ super().__init__()
77
+ self.kernel_name = kernel_name
78
+ self.input_nodes = input_nodes
79
+ self.output_node = output_node
80
+ self.kernel_metadata = kernel_metadata
81
+ self.accumulator_type = accumulator_type
82
+ self.workspace_size = workspace_size
83
+ self.variant = variant
84
+ self.scale_type_a = scale_type_a
85
+ self.scale_type_b = scale_type_b
86
+ self.swizzle_type_a = swizzle_type_a
87
+ self.swizzle_type_b = swizzle_type_b
88
+
89
+ self._template_input_args: list[tuple[str, Buffer]] = []
90
+ self._seen_input_args: OrderedSet[str] = OrderedSet()
91
+
92
+ for i, input_node in enumerate(input_nodes):
93
+ param_name = f"in_ptr{i}"
94
+ self._template_input_args.append((param_name, input_node))
95
+ self._seen_input_args.add(param_name)
96
+
97
+ def render(self) -> str:
98
+ """
99
+ Render the NVIDIA Universal GEMM kernel code as a Python source string.
100
+
101
+ Generates Python code that:
102
+ 1. Looks up the cutlass_api kernel by name from the manifest (cached in
103
+ _nv_universal_gemm_kernel_cache to avoid repeated manifest searches)
104
+ 2. Creates GemmArguments with the input/output tensors and accumulator type
105
+ 3. Compiles the kernel for the specific tensor shapes/dtypes (cached in
106
+ _nv_universal_gemm_artifact_cache keyed by (shape, dtype) tuple)
107
+ 4. Runs the kernel with the compiled artifact and CUDA stream
108
+
109
+ The caching strategy ensures:
110
+ - Kernel lookup happens once per unique kernel name
111
+ - Compilation happens once per unique (shape, dtype) combination
112
+ - Runtime execution is just the kernel.run() call with cached artifact
113
+
114
+ Returns:
115
+ Python source code string to be written to a .py file and loaded
116
+ via async_compile.nv_universal_gemm()
117
+ """
118
+ from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm import (
119
+ GemmVariant,
120
+ )
121
+
122
+ kernel_name_str = self.kernel_metadata["kernel_name"]
123
+ is_grouped = self.variant == GemmVariant.GROUPED_GEMM
124
+ is_scaled = self.variant == GemmVariant.SCALED_GEMM
125
+
126
+ acc_dtype_str = CuteDSLOpOverrides.TORCH_TO_CUTE_DTYPE.get(
127
+ self.accumulator_type, "cutlass.Float32"
128
+ )
129
+
130
+ input_params = [f"in_ptr{i}" for i, _ in enumerate(self.input_nodes)]
131
+ input_params.append("out_ptr0")
132
+ if self.workspace_size > 0:
133
+ input_params.append("workspace")
134
+ input_params.append("stream=None")
135
+ params_str = ", ".join(input_params)
136
+
137
+ workspace_arg = "workspace" if self.workspace_size > 0 else "None"
138
+
139
+ var_prefix = self.variant.op_name.upper()
140
+ cache_var = f"_{var_prefix}_compiled_cache"
141
+ kernel_name_var = f"_{var_prefix}_KERNEL_NAME"
142
+
143
+ extra_imports = ""
144
+ if is_scaled:
145
+ extra_imports = """from cutlass_api.arguments import ScaledTensor
146
+ from cutlass_api.library import ScaleMode, ScaleSwizzleMode"""
147
+
148
+ # Variant-specific code generation:
149
+ # - cache_key_code: expression for cache key
150
+ # - create_args_code: code to create Arguments object
151
+ if is_grouped:
152
+ cache_key_code = "(in_ptr0.shape, in_ptr0.dtype, in_ptr1.shape, in_ptr1.dtype, in_ptr2.shape)"
153
+ create_args_code = f"""args = cutlass_api.arguments.GroupedGemmArguments(
154
+ in_ptr0,
155
+ in_ptr1,
156
+ out_ptr0,
157
+ accumulator_type={acc_dtype_str},
158
+ offsets=in_ptr2,
159
+ )"""
160
+ elif is_scaled:
161
+ scale_mode_a, swizzle_mode_a = to_cutlass_scale_mode(
162
+ self.scale_type_a, self.swizzle_type_a
163
+ )
164
+ scale_mode_b, swizzle_mode_b = to_cutlass_scale_mode(
165
+ self.scale_type_b, self.swizzle_type_b
166
+ )
167
+ scale_mode_a_str = scale_mode_a.name if scale_mode_a else ""
168
+ scale_mode_b_str = scale_mode_b.name if scale_mode_b else ""
169
+ swizzle_mode_a_str = swizzle_mode_a.name if swizzle_mode_a else ""
170
+ swizzle_mode_b_str = swizzle_mode_b.name if swizzle_mode_b else ""
171
+ cache_key_code = "(in_ptr0.shape, in_ptr0.dtype, in_ptr1.shape, in_ptr1.dtype, in_ptr2.shape, in_ptr3.shape)"
172
+ create_args_code = f"""scaled_a = ScaledTensor(
173
+ in_ptr0, in_ptr2, ScaleMode.{scale_mode_a_str}, ScaleSwizzleMode.{swizzle_mode_a_str}
174
+ )
175
+ scaled_b = ScaledTensor(
176
+ in_ptr1, in_ptr3, ScaleMode.{scale_mode_b_str}, ScaleSwizzleMode.{swizzle_mode_b_str}
177
+ )
178
+ args = cutlass_api.arguments.GemmArguments(
179
+ scaled_a,
180
+ scaled_b,
181
+ out_ptr0,
182
+ accumulator_type={acc_dtype_str},
183
+ )"""
184
+ else:
185
+ cache_key_code = (
186
+ "(in_ptr0.shape, in_ptr0.dtype, in_ptr1.shape, in_ptr1.dtype)"
187
+ )
188
+ create_args_code = f"""args = cutlass_api.arguments.GemmArguments(
189
+ in_ptr0,
190
+ in_ptr1,
191
+ out_ptr0,
192
+ accumulator_type={acc_dtype_str},
193
+ )"""
194
+
195
+ code = IndentedBuffer()
196
+ code.splice(
197
+ f"""
198
+ import cutlass
199
+ import cutlass_api
200
+ from torch._inductor.codegen.nv_universal_gemm.kernel_cache import get_kernel_by_name
201
+ {extra_imports}
202
+
203
+ {kernel_name_var} = "{kernel_name_str}"
204
+ # Maps (shape, dtype, shape, dtype, ...) -> compiled kernel artifact
205
+ {cache_var} = {{}}
206
+
207
+ def {self.kernel_name}_main({params_str}):
208
+ global {cache_var}
209
+
210
+ kernel = get_kernel_by_name({kernel_name_var})
211
+ if kernel is None:
212
+ raise RuntimeError(f"Could not find kernel: {{{kernel_name_var}}}")
213
+
214
+ {create_args_code}
215
+
216
+ cache_key = {cache_key_code}
217
+ artifact = {cache_var}.get(cache_key)
218
+ if artifact is None:
219
+ artifact = kernel.compile(args)
220
+ {cache_var}[cache_key] = artifact
221
+
222
+ kernel.run(args, artifact, stream=stream, workspace={workspace_arg}, assume_supported_args=True)
223
+ """
224
+ )
225
+
226
+ return code.getvalue()
227
+
228
+ def _get_reinterpret_view(self, node) -> Optional[ReinterpretView]:
229
+ """Extract or convert to ReinterpretView from a node, handling all views."""
230
+ while isinstance(node, MutableBox):
231
+ node = node.data
232
+ if isinstance(node, BaseView):
233
+ return ExternKernel.convert_to_reinterpret_view(node)
234
+ return None
235
+
236
+ def call_kernel(self, name: str, node=None):
237
+ """
238
+ Generate the kernel call in the wrapper code.
239
+
240
+ Similar to CuteDSLTemplateKernel.call_kernel but simplified for NVIDIA Universal GEMM.
241
+ """
242
+ wrapper = V.graph.wrapper_code
243
+
244
+ call_args: list[str] = []
245
+ arg_types: list[Any] = []
246
+ raw_args: list[Union[Buffer, ReinterpretView, None]] = []
247
+
248
+ for _, input_node in self._template_input_args:
249
+ reinterpret_view = self._get_reinterpret_view(input_node)
250
+ if reinterpret_view is not None:
251
+ call_args.append(reinterpret_view.codegen_reference())
252
+ # Pass the ReinterpretView as raw_arg so autotune_at_compile_time
253
+ # can use it to generate example tensors
254
+ raw_args.append(reinterpret_view)
255
+ else:
256
+ call_args.append(input_node.get_name())
257
+ raw_args.append(input_node)
258
+ arg_types.append(V.graph.get_dtype(input_node.get_name()))
259
+
260
+ output_name = self.output_node.get_name()
261
+ call_args.append(output_name)
262
+ arg_types.append(V.graph.get_dtype(output_name))
263
+ raw_args.append(None) # Output buffer is findable by name
264
+
265
+ # Allocate workspace if needed
266
+ ws: Optional[WorkspaceArg] = None
267
+ if self.workspace_size > 0:
268
+ ws = WorkspaceArg(
269
+ count=self.workspace_size,
270
+ device=V.graph.get_current_device_or_throw(),
271
+ zero_mode=WorkspaceZeroMode.UNINITIALIZED,
272
+ outer_name=WorkspaceArg.unique_name(),
273
+ )
274
+ wrapper.generate_workspace_allocation(ws)
275
+ call_args.append(ws.outer_name)
276
+ arg_types.append(ws.dtype)
277
+ raw_args.append(None)
278
+
279
+ # Generate the kernel call using triton=True for Python-based kernels
280
+ # Pass raw_keys as None list to match raw_args length
281
+ # TODO(nikhilap) We don't use autotune_args like the Triton path
282
+ wrapper.generate_kernel_call(
283
+ name,
284
+ call_args,
285
+ triton=True,
286
+ arg_types=arg_types,
287
+ raw_args=raw_args,
288
+ raw_keys=[None] * len(raw_args),
289
+ )
290
+
291
+ # Deallocate workspace after kernel call
292
+ if ws is not None:
293
+ wrapper.generate_workspace_deallocation(ws)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_scheduling.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ NVIDIA Universal GEMM scheduling for PyTorch Inductor.
4
+ """
5
+
6
+ import hashlib
7
+ import logging
8
+ from collections.abc import Sequence
9
+ from typing import cast
10
+
11
+ from torch._inductor.utils import (
12
+ get_fused_kernel_name,
13
+ get_kernel_metadata,
14
+ Placeholder,
15
+ )
16
+ from torch.utils._ordered_set import OrderedSet
17
+
18
+ from ... import config
19
+ from ...codecache import code_hash, get_path
20
+ from ...ir import NVUniversalGemmBuffer
21
+ from ...scheduler import (
22
+ BaseSchedulerNode,
23
+ BaseScheduling,
24
+ FusedSchedulerNode,
25
+ SchedulerNode,
26
+ )
27
+ from ...virtualized import V
28
+ from ..common import BackendFeature, IndentedBuffer
29
+
30
+
31
+ log = logging.getLogger(__name__)
32
+
33
+ MAIN_SUFFIX = "main"
34
+
35
+
36
+ class NVUniversalGemmScheduling(BaseScheduling):
37
+ """
38
+ Scheduling implementation for NVIDIA Universal GEMM kernels.
39
+
40
+ This class is intended to be used in combination with other schedulers,
41
+ and delegated to by CUDACombinedScheduling.
42
+ """
43
+
44
+ @classmethod
45
+ def get_backend_features(cls, device) -> OrderedSet[BackendFeature]:
46
+ return OrderedSet()
47
+
48
+ @staticmethod
49
+ def is_nv_universal_gemm_template(node: BaseSchedulerNode) -> bool:
50
+ """Check if a node is a NVIDIA Universal GEMM template."""
51
+ return isinstance(node, SchedulerNode) and isinstance(
52
+ node.node, NVUniversalGemmBuffer
53
+ )
54
+
55
+ def is_nv_universal_gemm_fused_template(self, node: BaseSchedulerNode) -> bool:
56
+ """Check if a node is a fused NVIDIA Universal GEMM template."""
57
+ return isinstance(
58
+ node, FusedSchedulerNode
59
+ ) and self.is_nv_universal_gemm_template(node)
60
+
61
+ def can_fuse_vertical(
62
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
63
+ ) -> bool:
64
+ # NVIDIA Universal GEMM templates don't support vertical fusion yet
65
+ return False
66
+
67
+ def can_fuse_horizontal(
68
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
69
+ ) -> bool:
70
+ # NVIDIA Universal GEMM templates don't support horizontal fusion yet
71
+ return False
72
+
73
+ def define_kernel(self, src_code: str, node_schedule) -> str:
74
+ """
75
+ Define a NVIDIA Universal GEMM kernel by writing source code and generating wrapper.
76
+
77
+ Based on CuteDSLScheduling.define_kernel.
78
+ """
79
+ wrapper = V.graph.wrapper_code
80
+
81
+ # Use the string as the key for caching
82
+ if src_code in wrapper.src_to_kernel:
83
+ return wrapper.src_to_kernel[src_code]
84
+
85
+ fused_name = (
86
+ get_fused_kernel_name(node_schedule, config.triton.descriptive_names)
87
+ if config.triton.descriptive_names
88
+ else ""
89
+ )
90
+
91
+ kernel_hash = hashlib.sha256(src_code.encode("utf-8")).hexdigest()[:8]
92
+ if fused_name == "fused":
93
+ kernel_name = f"nv_universal_gemm_{kernel_hash}"
94
+ else:
95
+ kernel_name = f"nv_universal_gemm_{fused_name}_{kernel_hash}"
96
+
97
+ wrapper.src_to_kernel[src_code] = kernel_name
98
+
99
+ src_code = src_code.replace(str(Placeholder.KERNEL_NAME), kernel_name)
100
+
101
+ _, _, kernel_path = get_path(code_hash(src_code), "py")
102
+
103
+ compile_wrapper = IndentedBuffer()
104
+ compile_wrapper.writeline(
105
+ f"async_compile.nv_universal_gemm({kernel_name!r}, r'''"
106
+ )
107
+ compile_wrapper.splice(src_code, strip=True)
108
+ compile_wrapper.writeline("''')")
109
+
110
+ metadata_comment = f"# kernel path: {kernel_path}"
111
+ origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
112
+ metadata_comment += "\n" + origins + "\n" + detailed_origins
113
+ wrapper.define_kernel(kernel_name, compile_wrapper.getvalue(), metadata_comment)
114
+
115
+ return kernel_name
116
+
117
+ def codegen_template(
118
+ self,
119
+ template_node: BaseSchedulerNode,
120
+ epilogue_nodes: Sequence[BaseSchedulerNode],
121
+ prologue_nodes: Sequence[BaseSchedulerNode],
122
+ ):
123
+ """
124
+ Codegen a NVIDIA Universal GEMM template. Currently doesn't support fusion.
125
+ """
126
+ assert self.is_nv_universal_gemm_template(template_node), (
127
+ "Template node passed to NVUniversalGemmScheduling.codegen_template must be a "
128
+ "SchedulerNode that wraps a NVUniversalGemmBuffer"
129
+ )
130
+ # TODO: add support for fusion when needed
131
+ assert not epilogue_nodes, (
132
+ "NVIDIA Universal GEMM doesn't support epilogue fusion yet"
133
+ )
134
+ assert not prologue_nodes, (
135
+ "NVIDIA Universal GEMM doesn't support prologue fusion yet"
136
+ )
137
+
138
+ template_node = cast(SchedulerNode, template_node)
139
+ ctb: NVUniversalGemmBuffer = cast(NVUniversalGemmBuffer, template_node.node)
140
+
141
+ assert ctb.make_kernel_render is not None
142
+ kernel, render = ctb.make_kernel_render(ctb)
143
+ template_node.mark_run()
144
+ src_code = render()
145
+
146
+ with V.set_kernel_handler(kernel):
147
+ node_schedule = [template_node]
148
+ kernel_name = self.define_kernel(src_code, node_schedule)
149
+
150
+ self.codegen_comment(node_schedule, kernel_name)
151
+ kernel.call_kernel(kernel_name, ctb)
152
+ V.graph.removed_buffers |= kernel.removed_buffers
153
+ self.free_buffers_in_scheduler()
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm_utils.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ Utility functions for NVIDIA Universal GEMM.
4
+ """
5
+
6
+ from typing import Any, Optional
7
+
8
+ from torch.nn.functional import ScalingType, SwizzleType
9
+
10
+
11
+ def to_cutlass_scale_mode(
12
+ scale_type: Any, swizzle_type: Any
13
+ ) -> tuple[Optional[Any], Optional[Any]]:
14
+ """
15
+ Map PyTorch ScalingType/SwizzleType to cutlass_api ScaleMode/ScaleSwizzleMode.
16
+
17
+ Args:
18
+ scale_type: ScalingType from torch.nn.functional
19
+ swizzle_type: SwizzleType from torch.nn.functional
20
+
21
+ Returns:
22
+ Tuple of (ScaleMode, ScaleSwizzleMode) from cutlass_api.library,
23
+ or (None, None) if the types are not supported.
24
+
25
+ The returned enum objects can be used directly with cutlass_api, or their
26
+ .name attribute can be used for codegen (e.g., scale_mode.name -> "Blockwise1x32").
27
+
28
+ NOTE:
29
+ Currently on Blackwell (SM100), NVGEMM only supports MXFP8 scaling modes.
30
+ Update this mapping when additional scaling modes are added.
31
+ """
32
+ from cutlass_api.library import ScaleMode, ScaleSwizzleMode
33
+
34
+ scale_mode_map = {
35
+ ScalingType.BlockWise1x32: ScaleMode.Blockwise1x32,
36
+ ScalingType.BlockWise1x16: ScaleMode.Blockwise1x16,
37
+ }
38
+ swizzle_mode_map = {
39
+ SwizzleType.SWIZZLE_32_4_4: ScaleSwizzleMode.Swizzle32x4x4,
40
+ SwizzleType.NO_SWIZZLE: ScaleSwizzleMode.SwizzleNone,
41
+ }
42
+ return scale_mode_map.get(scale_type), swizzle_mode_map.get(swizzle_type)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/rocm/ck_tile_universal_gemm_template.py ADDED
@@ -0,0 +1,979 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs, disable-error-code="attr-defined, valid-type"
2
+ import functools
3
+ import logging
4
+ import random
5
+ from dataclasses import asdict, dataclass
6
+ from typing import Any
7
+
8
+ import torch
9
+ from torch._inductor import config
10
+ from torch._inductor.codegen.rocm.ck_tile_template import CKTileTemplate
11
+ from torch._inductor.codegen.rocm.rocm_kernel import ROCmTemplateKernel
12
+ from torch._inductor.codegen.rocm.rocm_template import ArgInfo
13
+ from torch._inductor.ir import Buffer, Layout
14
+ from torch.utils._ordered_set import OrderedSet
15
+
16
+ from ...utils import IndentedBuffer
17
+
18
+
19
+ log = logging.getLogger(__name__)
20
+
21
+
22
+ def is_static_int(number):
23
+ import sympy
24
+
25
+ return isinstance(number, (int, sympy.Integer))
26
+
27
+
28
+ def torch_layout_to_ck_layout(torch_layout):
29
+ if torch_layout.stride[-1] == 1:
30
+ return "Row"
31
+ elif torch_layout.stride[-2] == 1:
32
+ return "Col"
33
+ else:
34
+ return None
35
+
36
+
37
+ @dataclass
38
+ class CKTileGemmOperation:
39
+ layout_a: str
40
+ layout_b: str
41
+ layout_c: str
42
+
43
+ datatype_a: str
44
+ datatype_b: str
45
+ datatype_c: str
46
+
47
+ tile_m: int
48
+ tile_n: int
49
+ tile_k: int
50
+
51
+ warp_m: int
52
+ warp_n: int
53
+ warp_k: int
54
+
55
+ warp_tile_m: int
56
+ warp_tile_n: int
57
+ warp_tile_k: int
58
+
59
+ m_is_padded: str
60
+ n_is_padded: str
61
+ k_is_padded: str
62
+
63
+ pipeline: str
64
+ scheduler: str
65
+ epilogue: str
66
+
67
+ def layout_repr(self):
68
+ return f"{self.layout_a[0]}{self.layout_b[0]}{self.layout_c[0]}"
69
+
70
+ def dtype_repr(self):
71
+ return f"{self.datatype_a}{self.datatype_b}{self.datatype_c}"
72
+
73
+ def tile_sizes(self):
74
+ return "_".join(
75
+ [
76
+ f"{self.tile_m}{self.tile_n}{self.tile_k}",
77
+ f"{self.warp_m}{self.warp_n}{self.warp_k}",
78
+ f"{self.warp_tile_m}{self.warp_tile_n}{self.warp_tile_k}",
79
+ ]
80
+ )
81
+
82
+ def name(self):
83
+ return "ck_tile_gemm_universal_" + "_".join(
84
+ [
85
+ f"{self.layout_repr()}",
86
+ f"{self.dtype_repr()}",
87
+ f"{self.tile_sizes()}",
88
+ f"{self.pipeline}",
89
+ f"{self.scheduler}",
90
+ f"{self.epilogue}",
91
+ ]
92
+ )
93
+
94
+ def dict_items(self):
95
+ return asdict(self).items()
96
+
97
+
98
+ @functools.cache
99
+ def ops():
100
+ """
101
+ Generate the supported instance dataclasses
102
+ """
103
+ import itertools
104
+
105
+ compute_v3_instances = [
106
+ CKTileGemmOperation(
107
+ layout_a=layout_a,
108
+ layout_b=layout_b,
109
+ layout_c=layout_c,
110
+ datatype_a=datatype_a,
111
+ datatype_b=datatype_b,
112
+ datatype_c=datatype_c,
113
+ tile_m=tile_m,
114
+ tile_n=tile_n,
115
+ tile_k=tile_k,
116
+ warp_m=warp_m,
117
+ warp_n=warp_n,
118
+ warp_k=warp_k,
119
+ warp_tile_m=warp_tile_m,
120
+ warp_tile_n=warp_tile_n,
121
+ warp_tile_k=warp_tile_k,
122
+ m_is_padded=m_is_padded,
123
+ n_is_padded=n_is_padded,
124
+ k_is_padded=k_is_padded,
125
+ pipeline="CompV3",
126
+ scheduler="Intrawave",
127
+ epilogue=epilogue,
128
+ )
129
+ for (layout_a, layout_b, layout_c) in [
130
+ ("Row", "Row", "Row"),
131
+ ("Row", "Col", "Row"),
132
+ ]
133
+ for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3]
134
+ for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)]
135
+ for (warp_m, warp_n, warp_k) in [(2, 2, 1)]
136
+ for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)]
137
+ for m_is_padded in ["true", "false"]
138
+ for n_is_padded in ["true", "false"]
139
+ for k_is_padded in ["true", "false"]
140
+ for epilogue in ["Default", "CShuffle"]
141
+ ]
142
+
143
+ compute_v4_instances = [
144
+ CKTileGemmOperation(
145
+ layout_a=layout_a,
146
+ layout_b=layout_b,
147
+ layout_c=layout_c,
148
+ datatype_a=datatype_a,
149
+ datatype_b=datatype_b,
150
+ datatype_c=datatype_c,
151
+ tile_m=tile_m,
152
+ tile_n=tile_n,
153
+ tile_k=tile_k,
154
+ warp_m=warp_m,
155
+ warp_n=warp_n,
156
+ warp_k=warp_k,
157
+ warp_tile_m=warp_tile_m,
158
+ warp_tile_n=warp_tile_n,
159
+ warp_tile_k=warp_tile_k,
160
+ m_is_padded=m_is_padded,
161
+ n_is_padded=n_is_padded,
162
+ k_is_padded=k_is_padded,
163
+ pipeline="CompV4",
164
+ scheduler="Intrawave",
165
+ epilogue=epilogue,
166
+ )
167
+ for (layout_a, layout_b, layout_c) in [
168
+ ("Row", "Row", "Row"),
169
+ ("Row", "Col", "Row"),
170
+ ]
171
+ for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3]
172
+ for (tile_m, tile_n, tile_k) in [
173
+ (256, 256, 32)
174
+ ] # half the tile size since it has double buffering
175
+ for (warp_m, warp_n, warp_k) in [(2, 2, 1)]
176
+ for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)]
177
+ for m_is_padded in ["true", "false"]
178
+ for n_is_padded in ["true", "false"]
179
+ for k_is_padded in ["true", "false"]
180
+ for epilogue in ["Default", "CShuffle"]
181
+ ]
182
+
183
+ mem_instances = [
184
+ CKTileGemmOperation(
185
+ layout_a=layout_a,
186
+ layout_b=layout_b,
187
+ layout_c=layout_c,
188
+ datatype_a=datatype_a,
189
+ datatype_b=datatype_b,
190
+ datatype_c=datatype_c,
191
+ tile_m=tile_m,
192
+ tile_n=tile_n,
193
+ tile_k=tile_k,
194
+ warp_m=warp_m,
195
+ warp_n=warp_n,
196
+ warp_k=warp_k,
197
+ warp_tile_m=warp_tile_m,
198
+ warp_tile_n=warp_tile_n,
199
+ warp_tile_k=warp_tile_k,
200
+ m_is_padded=m_is_padded,
201
+ n_is_padded=n_is_padded,
202
+ k_is_padded=k_is_padded,
203
+ pipeline="Mem",
204
+ scheduler=scheduler,
205
+ epilogue=epilogue,
206
+ )
207
+ for (layout_a, layout_b, layout_c) in [
208
+ ("Row", "Row", "Row"),
209
+ ("Row", "Col", "Row"),
210
+ ]
211
+ for (datatype_a, datatype_b, datatype_c) in [("FP16",) * 3, ("BF16",) * 3]
212
+ for (tile_m, tile_n, tile_k) in [(256, 256, 32), (256, 256, 64)]
213
+ for (warp_m, warp_n, warp_k) in [(2, 2, 1)]
214
+ for (warp_tile_m, warp_tile_n, warp_tile_k) in [(32, 32, 16)]
215
+ for m_is_padded in ["true", "false"]
216
+ for n_is_padded in ["true", "false"]
217
+ for k_is_padded in ["true", "false"]
218
+ for scheduler in ["Intrawave", "Interwave"]
219
+ for epilogue in ["Default", "CShuffle"]
220
+ ]
221
+
222
+ return list(
223
+ itertools.chain(compute_v3_instances, compute_v4_instances, mem_instances)
224
+ )
225
+
226
+
227
+ class CKTileGemmTemplate(CKTileTemplate):
228
+ """
229
+ This class is used for rendering CK-Tile Universal GEMM kernels
230
+ """
231
+
232
+ gemm_template = r"""{{version_comment}}
233
+ {{headers}}
234
+ {{globals}}
235
+ {{instance_definition}}
236
+ extern "C" {
237
+ PT_EXPORT {{kernel_definition}} {
238
+
239
+ using {{instance_namespace}}::BaseGemmPipeline;
240
+ using {{instance_namespace}}::TilePartitioner;
241
+
242
+ constexpr auto TileK = {{instance_namespace}}::TileK;
243
+ constexpr auto kPrefetchStages = BaseGemmPipeline::PrefetchStages;
244
+
245
+ const auto BiasTerms = std::array<const void*, 0> ();
246
+ const auto BiasStrides = std::array<int32_t, 0> ();
247
+
248
+ auto kargs = ck_tile::UniversalGemmKernelArgs<> {
249
+ {X},
250
+ {W},
251
+ BiasTerms,
252
+ Y,
253
+ M,
254
+ N,
255
+ K,
256
+ {LDA},
257
+ {LDB},
258
+ BiasStrides,
259
+ LDC,
260
+ kBatch
261
+ };
262
+
263
+ if (workspace_size) {
264
+ *workspace_size = 0;
265
+ return 0;
266
+ }
267
+
268
+ // run the kernel
269
+ const auto dispatch = [&](const auto has_hot_loop_, const auto tail_number_) constexpr {
270
+ using Kernel = {{instance_namespace}}::Kernel<has_hot_loop_.value, tail_number_.value>;
271
+
272
+ if (!Kernel::IsSupportedArgument(kargs)) {
273
+ // we do our best to statically avoid this case in `filter_op`
274
+ throw std::runtime_error("invalid argument");
275
+ }
276
+ auto stream_config = ck_tile::stream_config{stream};
277
+ auto grid_size = Kernel::GridSize(M, N, kBatch);
278
+ constexpr auto block_size = Kernel::BlockSize();
279
+ constexpr auto lds_bytes = 0;
280
+ constexpr auto kBlockPerCU = 1;
281
+ auto gemm = ck_tile::make_kernel<block_size.x, kBlockPerCU>(Kernel{}, grid_size, block_size, lds_bytes, kargs);
282
+ float elapsed_time = ck_tile::launch_kernel(stream_config, gemm);
283
+ };
284
+
285
+ const ck_tile::index_t k_grain = kBatch * TileK;
286
+ const ck_tile::index_t K_split = (K + k_grain - 1) / k_grain * TileK;
287
+ const ck_tile::index_t num_loop = TilePartitioner::GetLoopNum(K_split);
288
+ const bool has_hot_loop = BaseGemmPipeline::BlockHasHotloop(num_loop);
289
+ const ck_tile::TailNumber tail_num = BaseGemmPipeline::GetBlockLoopTailNum(num_loop);
290
+
291
+ {{rendered_dispatch}}
292
+
293
+ return 0;
294
+ } // kernel definition
295
+ } // extern C
296
+ """
297
+
298
+ def __init__(
299
+ self,
300
+ input_nodes: list[Buffer],
301
+ layout: Layout,
302
+ ) -> None:
303
+ super().__init__(
304
+ "ck_tile_gemm_template",
305
+ input_nodes=input_nodes,
306
+ layout=layout,
307
+ )
308
+
309
+ def header(self) -> IndentedBuffer:
310
+ res = super().header()
311
+ res.splice(
312
+ """
313
+ // CK GEMM header(s)
314
+
315
+ #include "ck_tile/ops/gemm.hpp"
316
+ #include "ck_tile/ops/epilogue.hpp"
317
+ """
318
+ )
319
+ return res
320
+
321
+ def globals(self) -> IndentedBuffer:
322
+ res = super().globals()
323
+ res.splice(
324
+ """
325
+ // CK GEMM globals
326
+
327
+ using Row = ck_tile::tensor_layout::gemm::RowMajor;
328
+ using Col = ck_tile::tensor_layout::gemm::ColumnMajor;
329
+
330
+ template <ck_tile::index_t PrefetchStages, typename Dispatcher>
331
+ void dispatch_memory_pipeline_hot_loop(const ck_tile::TailNumber tail_num, Dispatcher dispatch)
332
+ {
333
+ if(tail_num == ck_tile::TailNumber::One)
334
+ {
335
+ dispatch(ck_tile::bool_constant<true>{},
336
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::One>{});
337
+ }
338
+ else if(tail_num == ck_tile::TailNumber::Full)
339
+ {
340
+ dispatch(ck_tile::bool_constant<true>{},
341
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Full>{});
342
+ }
343
+
344
+ if constexpr(PrefetchStages > 2)
345
+ {
346
+ if(tail_num == ck_tile::TailNumber::Two)
347
+ {
348
+ dispatch(ck_tile::bool_constant<true>{},
349
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Two>{});
350
+ }
351
+ }
352
+ if constexpr(PrefetchStages > 3)
353
+ {
354
+ if(tail_num == ck_tile::TailNumber::Three)
355
+ {
356
+ dispatch(ck_tile::bool_constant<true>{},
357
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Three>{});
358
+ }
359
+ }
360
+ if constexpr(PrefetchStages > 4)
361
+ {
362
+ if(tail_num == ck_tile::TailNumber::Four)
363
+ {
364
+ dispatch(ck_tile::bool_constant<true>{},
365
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Four>{});
366
+ }
367
+ }
368
+ if constexpr(PrefetchStages > 5)
369
+ {
370
+ if(tail_num == ck_tile::TailNumber::Five)
371
+ {
372
+ dispatch(ck_tile::bool_constant<true>{},
373
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Five>{});
374
+ }
375
+ }
376
+ if constexpr(PrefetchStages > 6)
377
+ {
378
+ if(tail_num == ck_tile::TailNumber::Six)
379
+ {
380
+ dispatch(ck_tile::bool_constant<true>{},
381
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Six>{});
382
+ }
383
+ }
384
+ if constexpr(PrefetchStages > 7)
385
+ {
386
+ if(tail_num == ck_tile::TailNumber::Seven)
387
+ {
388
+ dispatch(ck_tile::bool_constant<true>{},
389
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::Seven>{});
390
+ }
391
+ }
392
+ }
393
+ """
394
+ )
395
+ return res
396
+
397
+ def check_dtypes(self, op: "CKTileGemmOperation"):
398
+ X_dtype, W_dtype, out_dtype = [
399
+ T.get_layout().dtype for T in [*self.input_nodes, self.output_node]
400
+ ]
401
+ if op.datatype_a != self._TORCH_DTYPE_TO_CK[X_dtype]:
402
+ return False
403
+ if op.datatype_b != self._TORCH_DTYPE_TO_CK[W_dtype]:
404
+ return False
405
+ if op.datatype_c != self._TORCH_DTYPE_TO_CK[out_dtype]:
406
+ return False
407
+ return True
408
+
409
+ def check_layouts(self, op: "CKTileGemmOperation"):
410
+ X_layout, W_layout, out_layout = [
411
+ torch_layout_to_ck_layout(T.get_layout())
412
+ for T in [*self.input_nodes, self.output_node]
413
+ ]
414
+ if op.layout_a != X_layout:
415
+ return False
416
+ if op.layout_b != W_layout:
417
+ return False
418
+ if op.layout_c != out_layout:
419
+ return False
420
+ return True
421
+
422
+ def get_gemm_problem_size(self):
423
+ X_size, W_size = [T.get_layout().size for T in [*self.input_nodes]]
424
+
425
+ M, K = X_size
426
+ _, N = W_size
427
+
428
+ return M, N, K
429
+
430
+ def check_block_tiles(self, op: "CKTileGemmOperation"):
431
+ """
432
+ The contiguous dimension of a tensor must be divisible by the block tile size
433
+ This helper function enforces it for the inputs and the output.
434
+ """
435
+ M, N, K = self.get_gemm_problem_size()
436
+
437
+ def check(dim_size, tile_size, is_padded):
438
+ if (
439
+ is_static_int(dim_size)
440
+ and dim_size % tile_size != 0
441
+ and is_padded == "false"
442
+ ):
443
+ return False
444
+ return True
445
+
446
+ if op.layout_a == "Row":
447
+ # handle in kBatch check
448
+ return True
449
+ elif op.layout_a == "Col":
450
+ if not check(M, op.tile_m, op.m_is_padded):
451
+ return False
452
+ else:
453
+ raise AssertionError(f"Invalid layout {op.layout_a=}")
454
+
455
+ if op.layout_b == "Row":
456
+ if not check(N, op.tile_n, op.n_is_padded):
457
+ return False
458
+ elif op.layout_b == "Col":
459
+ # handle in kBatch check
460
+ return True
461
+ else:
462
+ raise AssertionError(f"Invalid {op.layout_b=}")
463
+
464
+ if op.layout_c == "Row":
465
+ if not check(N, op.tile_n, op.n_is_padded):
466
+ return False
467
+ elif op.layout_c == "Col":
468
+ if not check(M, op.tile_m, op.m_is_padded):
469
+ return False
470
+ else:
471
+ raise AssertionError(f"Invalid layout {op.layout_c=}")
472
+
473
+ return True
474
+
475
+ def check_alignments(self, op: "CKTileGemmOperation"):
476
+ """
477
+ The contiguous dimension of a tensor must be divisible by the vector load size.
478
+ """
479
+ M, N, K = self.get_gemm_problem_size()
480
+
481
+ def max_alignment(contiguous_elements_per_tile, elements_per_thread, ck_dtype):
482
+ for vector_load_bytes in (16, 8, 4, 2, 1):
483
+ alignment = vector_load_bytes // self.ck_dtype_to_size[ck_dtype]
484
+ if (
485
+ alignment > 0
486
+ and contiguous_elements_per_tile % alignment == 0
487
+ and elements_per_thread % alignment == 0
488
+ ):
489
+ return alignment
490
+
491
+ threads_per_block = (
492
+ op.warp_m * op.warp_n * op.warp_k * self.gfx9_threads_per_warp
493
+ )
494
+ a_elements_per_thread = op.tile_m * op.tile_k / threads_per_block
495
+ b_elements_per_thread = op.tile_n * op.tile_k / threads_per_block
496
+
497
+ if op.layout_a == "Row":
498
+ # K is contiguous tensor dimension
499
+ a_max_vector_size = max_alignment(
500
+ op.tile_k, a_elements_per_thread, op.datatype_a
501
+ )
502
+ if is_static_int(K) and K % a_max_vector_size != 0:
503
+ return False
504
+ elif op.layout_a == "Col":
505
+ # M is contiguous tensor dimension
506
+ a_max_vector_size = max_alignment(
507
+ op.tile_m, a_elements_per_thread, op.datatype_a
508
+ )
509
+ if is_static_int(M) and M % a_max_vector_size != 0:
510
+ return False
511
+ else:
512
+ raise AssertionError(f"Invalid layout {op.layout_a=}")
513
+
514
+ if op.layout_b == "Row":
515
+ # N is contiguous tensor dimension
516
+ b_max_vector_size = max_alignment(
517
+ op.tile_n, b_elements_per_thread, op.datatype_b
518
+ )
519
+ if is_static_int(N) and N % b_max_vector_size != 0:
520
+ return False
521
+ elif op.layout_b == "Col":
522
+ # K is contiguous tensor dimension
523
+ b_max_vector_size = max_alignment(
524
+ op.tile_k, b_elements_per_thread, op.datatype_b
525
+ )
526
+ if is_static_int(K) and K % b_max_vector_size != 0:
527
+ return False
528
+ else:
529
+ raise AssertionError(f"Invalid layout {op.layout_b=}")
530
+
531
+ # the `default` epilogue writes C to memory by 1 tensor element
532
+ # (divisibility check not necessary)
533
+ # the `cshuffle` epilogue writes C to memory by 16 bytes
534
+ # (so the contiguous C dimension size must be divisible by the number of tensor elements in 16 bytes)
535
+ if op.epilogue == "CShuffle":
536
+ if (
537
+ op.layout_c == "Row"
538
+ and is_static_int(N)
539
+ and N % (16 / self.ck_dtype_to_size[op.datatype_c]) != 0
540
+ ):
541
+ return False
542
+
543
+ return True
544
+
545
+ def check_warp_tiles(self, op: "CKTileGemmOperation"):
546
+ if op.tile_m % (op.warp_m * op.warp_tile_m) != 0:
547
+ return False
548
+ if op.tile_n % (op.warp_n * op.warp_tile_n) != 0:
549
+ return False
550
+ if op.tile_k % (op.warp_k * op.warp_tile_k) != 0:
551
+ return False
552
+ return True
553
+
554
+ def check_block_tile_size(self, op: "CKTileGemmOperation"):
555
+ # assuming LDS size is 64KB
556
+ if op.pipeline == "CompV4":
557
+ max_block_tile_size = 2**15
558
+ else:
559
+ max_block_tile_size = 2**16
560
+
561
+ block_tile_size = (
562
+ self.ck_dtype_to_size[op.datatype_a] * op.tile_m * op.tile_k
563
+ + self.ck_dtype_to_size[op.datatype_b] * op.tile_n * op.tile_k
564
+ )
565
+ if block_tile_size > max_block_tile_size:
566
+ return False
567
+ return True
568
+
569
+ def filter_op(self, op: "CKTileGemmOperation"):
570
+ """
571
+ Determines whether a given op definition is suitable for the current
572
+ input / output of the operation that this template implements.
573
+
574
+ Filter is based on inputs' dtype, layout and statically inferred size.
575
+
576
+ Returns None if the op is not suitable, otherwise returns the op to be used.
577
+ """
578
+ if not self.check_dtypes(op):
579
+ return None
580
+ if not self.check_layouts(op):
581
+ return None
582
+ if not self.check_block_tiles(op):
583
+ return None
584
+ if not self.check_alignments(op):
585
+ return None
586
+
587
+ return op
588
+
589
+ def emit_ck_instance(self, op: "CKTileGemmOperation"):
590
+ """
591
+ This method is used to generate code which defines the type alias for the generated kernel class
592
+ """
593
+ template_definition = r"""
594
+ // Gemm operator {{operation_name}}
595
+
596
+ namespace {{operation_name}} {
597
+ // block tile
598
+ constexpr int32_t TileM = {{tile_m}};
599
+ constexpr int32_t TileN = {{tile_n}};
600
+ constexpr int32_t TileK = {{tile_k}};
601
+ // warps per block
602
+ constexpr int32_t WarpM = {{warp_m}};
603
+ constexpr int32_t WarpN = {{warp_n}};
604
+ constexpr int32_t WarpK = {{warp_k}};
605
+ // xdl tile
606
+ constexpr int32_t WarpTileM = {{warp_tile_m}};
607
+ constexpr int32_t WarpTileN = {{warp_tile_n}};
608
+ constexpr int32_t WarpTileK = {{warp_tile_k}};
609
+
610
+ constexpr bool kPadM = {{m_is_padded}};
611
+ constexpr bool kPadN = {{n_is_padded}};
612
+ constexpr bool kPadK = {{k_is_padded}};
613
+
614
+ using ALayout = {{layout_a}};
615
+ using BLayout = {{layout_b}};
616
+ using CLayout = {{layout_c}};
617
+
618
+ using ADataType = {{datatype_a}};
619
+ using BDataType = {{datatype_b}};
620
+ using CDataType = {{datatype_c}};
621
+ using AccDataType = F32;
622
+
623
+ constexpr bool permuteA = false;
624
+ constexpr bool permuteB = false;
625
+ constexpr bool DoubleSmemBuffer = {{has_double_smem_buffer}};
626
+ constexpr bool TransposeC = false;
627
+
628
+ constexpr int kBlockPerCu = 1;
629
+ constexpr ck_tile::index_t TilePartitionerGroupNum = 8;
630
+ constexpr ck_tile::index_t TilePartitionerM01 = 4;
631
+
632
+ using GemmShape =
633
+ ck_tile::TileGemmShape<ck_tile::sequence<TileM, TileN, TileK>,
634
+ ck_tile::sequence<WarpM, WarpN, WarpK>,
635
+ ck_tile::sequence<WarpTileM, WarpTileN, WarpTileK>,
636
+ permuteA,
637
+ permuteB>;
638
+
639
+ using TilePartitioner =
640
+ ck_tile::GemmSpatiallyLocalTilePartitioner<GemmShape,
641
+ TilePartitionerGroupNum,
642
+ TilePartitionerM01>;
643
+
644
+ using Traits =
645
+ ck_tile::TileGemmTraits<kPadM, kPadN, kPadK, ALayout, BLayout, CLayout>;
646
+
647
+ using GemmUniversalTraits =
648
+ ck_tile::TileGemmUniversalTraits<kPadM, kPadN, kPadK, DoubleSmemBuffer,
649
+ ALayout, BLayout, CLayout, TransposeC>;
650
+
651
+ using GemmPipelineProblem =
652
+ ck_tile::GemmPipelineProblem<ADataType, BDataType, AccDataType, GemmShape, Traits>;
653
+
654
+ {{rendered_scheduler}}
655
+
656
+ template<bool has_hot_loop_v, ck_tile::TailNumber tail_number_v>
657
+ using UniversalGemmProblem =
658
+ ck_tile::UniversalGemmPipelineProblem<ADataType,
659
+ BDataType,
660
+ AccDataType,
661
+ GemmShape,
662
+ GemmUniversalTraits,
663
+ scheduler,
664
+ has_hot_loop_v,
665
+ tail_number_v>;
666
+
667
+ {{rendered_pipeline}}
668
+
669
+ {{rendered_epilogue}}
670
+
671
+ template<bool has_hot_loop_v, ck_tile::TailNumber tail_number_v>
672
+ using Kernel = ck_tile::GemmKernel<TilePartitioner, GemmPipeline<has_hot_loop_v, tail_number_v>, GemmEpilogue>;
673
+ }
674
+
675
+ """
676
+
677
+ def render_epilogue(epilogue_type):
678
+ if epilogue_type == "Default":
679
+ return r"""
680
+ using EpilogueProblem = ck_tile::DefaultGemm2DEpilogueProblem<ADataType,
681
+ BDataType,
682
+ AccDataType,
683
+ CDataType,
684
+ CLayout,
685
+ kPadM,
686
+ kPadN,
687
+ WarpTileM,
688
+ WarpTileN,
689
+ WarpTileK,
690
+ TransposeC>;
691
+ using GemmEpilogue = ck_tile::DefaultGemm2DEpilogue<EpilogueProblem>;
692
+ """
693
+ elif epilogue_type == "CShuffle":
694
+ return r"""
695
+ constexpr auto kMemoryOperation = ck_tile::memory_operation_enum::set;
696
+ using DsDataType = ck_tile::tuple<>; // no bias terms for vanilla GEMM
697
+ using DsLayout = ck_tile::tuple<>;
698
+ constexpr auto ELayout = CLayout;
699
+ using CDEElementWise = ck_tile::element_wise::PassThrough; // no-op
700
+ using EpilogueProblem = ck_tile::CShuffleEpilogueProblem<ADataType,
701
+ BDataType,
702
+ DsDataType,
703
+ AccDataType,
704
+ CDataType,
705
+ DsLayout,
706
+ ELayout,
707
+ CDEElementWise,
708
+ GemmPipelineProblem::kBlockSize,
709
+ TileM,
710
+ TileN,
711
+ WarpM,
712
+ WarpN,
713
+ WarpTileM,
714
+ WarpTileN,
715
+ WarpTileK,
716
+ TransposeC,
717
+ kMemoryOperation>;
718
+
719
+ using GemmEpilogue = ck_tile::CShuffleEpilogue<EpilogueProblem>;
720
+ """
721
+ else:
722
+ raise AssertionError("Epilogue must be set")
723
+
724
+ def render_pipeline(pipeline_type):
725
+ return rf"""
726
+ using BaseGemmPipeline = ck_tile::BaseGemmPipelineAgBgCr{pipeline_type}<GemmPipelineProblem>;
727
+
728
+ template<bool has_hot_loop_v, ck_tile::TailNumber tail_number_v>
729
+ using GemmPipeline = ck_tile::GemmPipelineAgBgCr{pipeline_type}<UniversalGemmProblem<has_hot_loop_v, tail_number_v>>;
730
+ """
731
+
732
+ def render_scheduler(scheduler_type):
733
+ return rf"""
734
+ constexpr auto scheduler = ck_tile::GemmPipelineScheduler::{scheduler_type};
735
+ """
736
+
737
+ rendered_definition = self._template_from_string(template_definition).render(
738
+ operation_name=op.name(),
739
+ **asdict(op),
740
+ rendered_scheduler=render_scheduler(op.scheduler),
741
+ rendered_pipeline=render_pipeline(op.pipeline),
742
+ rendered_epilogue=render_epilogue(op.epilogue),
743
+ has_double_smem_buffer=("true" if op.pipeline == "CompV4" else "false"),
744
+ )
745
+ return rendered_definition
746
+
747
+ def render( # type: ignore[override]
748
+ self, kernel: ROCmTemplateKernel, op: "CKTileGemmOperation", **kwargs
749
+ ) -> str:
750
+ """
751
+ The primary entry point for the code rendering process used in this template.
752
+ """
753
+ epilogue_nodes = kwargs.get("epilogue_nodes")
754
+ assert epilogue_nodes is None or 0 == len(epilogue_nodes)
755
+ template_buffer_node = kwargs.get("template_buffer_node")
756
+ if template_buffer_node is not None:
757
+ self.output_node = template_buffer_node
758
+ assert 2 == len(self.input_nodes)
759
+ X, W = self.input_nodes
760
+ Y = self.output_node
761
+
762
+ instance_definition = self.emit_ck_instance(op)
763
+
764
+ version_comment = rf"""/**
765
+ * Generated code for CK inductor backend
766
+ * See {type(self).__module__}.{type(self).__qualname__}
767
+ *
768
+ * Template instance {op}
769
+ *
770
+ * {torch.__version__=}
771
+ * torch.version.git_version={getattr(torch.version, "git_version", "None")}
772
+ */
773
+ """
774
+
775
+ def render_dispatch(pipeline_type, op_name):
776
+ switch_tailnum_template = r"""
777
+ switch (tail_num) {
778
+ {% for tail_num in valid_tailnums %}
779
+ case ck_tile::TailNumber::{{tail_num}}:
780
+ dispatch({{has_hot_loop}},
781
+ ck_tile::integral_constant<ck_tile::TailNumber, ck_tile::TailNumber::{{tail_num}}>{});
782
+ break;
783
+ {% endfor %}
784
+ default:
785
+ std::ostringstream err;
786
+ err << "Unsupported dispatch: "
787
+ << "Pipeline: " << "{{pipeline}}"
788
+ << "Prefetch stages: " << kPrefetchStages
789
+ << "Tail num: " << tail_num;
790
+ throw std::runtime_error(err.str());
791
+ } // switch tail_num
792
+ """
793
+ dispatch_template = r"""
794
+ if (has_hot_loop) {
795
+ {{rendered_with_hot_loop}}
796
+ }
797
+ else { // has_hot_loop == false
798
+ {{rendered_without_hot_loop}}
799
+ } // if has_hot_loop
800
+ """
801
+ if pipeline_type == "CompV3":
802
+ return self._template_from_string(dispatch_template).render(
803
+ rendered_with_hot_loop=self._template_from_string(
804
+ switch_tailnum_template
805
+ ).render(
806
+ has_hot_loop="ck_tile::integral_constant<bool, true>{}",
807
+ valid_tailnums=("Full", "Odd", "Even"),
808
+ pipeline=pipeline_type,
809
+ ),
810
+ rendered_without_hot_loop=self._template_from_string(
811
+ switch_tailnum_template
812
+ ).render(
813
+ has_hot_loop="ck_tile::integral_constant<bool, false>{}",
814
+ valid_tailnums=("Full", "Odd", "Even"),
815
+ pipeline=pipeline_type,
816
+ ),
817
+ )
818
+ elif pipeline_type == "Mem":
819
+ return self._template_from_string(dispatch_template).render(
820
+ rendered_with_hot_loop="dispatch_memory_pipeline_hot_loop<kPrefetchStages>(tail_num, dispatch);",
821
+ rendered_without_hot_loop=self._template_from_string(
822
+ switch_tailnum_template
823
+ ).render(
824
+ has_hot_loop="ck_tile::integral_constant<bool, false>{}",
825
+ valid_tailnums=("Full", "Odd", "Even"),
826
+ pipeline=pipeline_type,
827
+ ),
828
+ )
829
+ elif pipeline_type == "CompV4":
830
+ return self._template_from_string(dispatch_template).render(
831
+ rendered_with_hot_loop=self._template_from_string(
832
+ switch_tailnum_template
833
+ ).render(
834
+ has_hot_loop="ck_tile::integral_constant<bool, true>{}",
835
+ valid_tailnums=("Two", "Three"),
836
+ pipeline=pipeline_type,
837
+ ),
838
+ rendered_without_hot_loop=self._template_from_string(
839
+ switch_tailnum_template
840
+ ).render(
841
+ has_hot_loop="ck_tile::integral_constant<bool, false>{}",
842
+ valid_tailnums=("Full", "Odd", "Even"),
843
+ pipeline=pipeline_type,
844
+ ),
845
+ )
846
+ else:
847
+ raise AssertionError(f"Pipeline {pipeline_type} is not supported")
848
+
849
+ return self._template_from_string(self.gemm_template).render(
850
+ headers=self.header().getvalue(),
851
+ globals=self.globals().getvalue(),
852
+ instance_definition=instance_definition,
853
+ kernel_definition=kernel.def_kernel(
854
+ inputs=[X, W], # type: ignore[list-item]
855
+ outputs=[Y],
856
+ names_str="X, W, Y",
857
+ size_args=[
858
+ f"int32_t {arg}" for arg in ["M", "N", "K", "LDA", "LDB", "LDC"]
859
+ ],
860
+ ),
861
+ instance_namespace=op.name(),
862
+ version_comment=version_comment,
863
+ rendered_dispatch=render_dispatch(op.pipeline, op.name()),
864
+ )
865
+
866
+ def gen_ops(self):
867
+ """
868
+ Creates a list of `CKTileGemmOperation` instances that match the GEMM operation this template represents.
869
+ The instances are guaranteed to have the correct layout, dtype and dimension padding for the GEMM input arguments.
870
+
871
+ An instance may invalidate the GEMM configuration at runtime.
872
+ Such instances will be assigned +inf runtime by the autotune process.
873
+ """
874
+ instances = ops()
875
+ if not instances:
876
+ raise AssertionError(
877
+ "No Composable Kernel Universal GEMM instances found. "
878
+ "Please check if the library is installed."
879
+ )
880
+ filtered_instances = list(filter(self.filter_op, instances))
881
+ # NB: when using a fixed list order, most likely we will pick the subset of instances
882
+ # which are very similar to each other. Randomizing the choice seems to solve this.
883
+ random.seed(-11)
884
+ chosen_instances = (
885
+ random.sample(
886
+ filtered_instances,
887
+ min(len(filtered_instances), config.rocm.ck_tile_max_profiling_configs),
888
+ )
889
+ if config.rocm.ck_tile_max_profiling_configs
890
+ else filtered_instances
891
+ )
892
+ log.debug(
893
+ "generated %d ck instances after sample: %s",
894
+ len(chosen_instances),
895
+ chosen_instances,
896
+ )
897
+ return chosen_instances
898
+
899
+ @staticmethod
900
+ def add_choices(
901
+ choices,
902
+ layout,
903
+ input_nodes,
904
+ ):
905
+ """
906
+ Add Composable Kernel Universal GEMM instance choices to the auto-tuning list.
907
+ """
908
+ template = CKTileGemmTemplate(
909
+ input_nodes,
910
+ layout,
911
+ )
912
+ ops = template.gen_ops()
913
+ for op in ops:
914
+ for k_batch in template.k_batch_choices(op):
915
+ template.maybe_append_choice(
916
+ choices,
917
+ op=op,
918
+ kBatch=k_batch,
919
+ )
920
+
921
+ def k_batch_choices(self, op: "CKTileGemmOperation") -> tuple[int, ...]:
922
+ """
923
+ Returns a list of k_batch choices for the template.
924
+ """
925
+ default_choices = (1, 2, 4, 8, 16, 32)
926
+
927
+ def check(dim_size, tile_size, is_padded):
928
+ if (
929
+ is_static_int(dim_size)
930
+ and dim_size % tile_size != 0
931
+ and is_padded == "false"
932
+ ):
933
+ return False
934
+ return True
935
+
936
+ _, _, K, _, _, _ = self.size_args()
937
+ if op.layout_a == "Row" or op.layout_b == "Col":
938
+ choices = tuple(
939
+ filter(
940
+ lambda k_batch: check(K, op.tile_k * k_batch, op.k_is_padded),
941
+ default_choices,
942
+ )
943
+ )
944
+ else:
945
+ choices = default_choices
946
+
947
+ if op.epilogue == "Default":
948
+ choices = (1,)
949
+
950
+ return choices
951
+
952
+ def size_args(self):
953
+ """
954
+ Sizes and strides to be used for the kernel call
955
+ """
956
+ X = self.input_nodes[0]
957
+ W = self.input_nodes[1]
958
+ Y = self.output_node
959
+
960
+ M = X.get_size()[0]
961
+ K = X.get_size()[1]
962
+ N = W.get_size()[1]
963
+ LDA = X.get_stride()[0 if X.get_stride()[1] == 1 else 1]
964
+ LDB = W.get_stride()[0 if W.get_stride()[1] == 1 else 1]
965
+ LDC = Y.get_stride()[0 if Y.get_stride()[1] == 1 else 1]
966
+
967
+ return M, N, K, LDA, LDB, LDC
968
+
969
+ def get_runtime_arg_info(self) -> list[ArgInfo]:
970
+ return [ArgInfo("kBatch", "int32_t")]
971
+
972
+ def get_runtime_arg_values(self, **kwargs: Any) -> list[Any]:
973
+ # maybe_append_choice kwarg for k_batch must match the name of the argument
974
+ arg_names = OrderedSet([arg.name for arg in self.get_runtime_arg_info()])
975
+ if not arg_names.issubset(kwargs):
976
+ raise ValueError(
977
+ "Missing runtime arguments: " + ", ".join(arg_names - kwargs.keys())
978
+ )
979
+ return [kwargs[k] for k in arg_names]
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ from collections.abc import Sequence
4
+ from typing import cast
5
+
6
+ from ... import config
7
+ from ...codecache import code_hash, get_path
8
+ from ...scheduler import BaseSchedulerNode, BaseScheduling, SchedulerNode
9
+ from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product
10
+ from ...virtualized import V
11
+ from ..common import IndentedBuffer
12
+ from .rocm_template_buffer import ROCmTemplateBuffer
13
+
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ class ROCmCPPScheduling(BaseScheduling):
19
+ """
20
+ Partial Scheduling implementation for ROCm C++ Kernels.
21
+ This class is intended to be used in combination with TritonScheduling,
22
+ and delegated to by CUDACombinedScheduling.
23
+
24
+ It handles fusion decisions and ROCm C++ specific template code generation.
25
+ """
26
+
27
+ def group_fn(self, sizes):
28
+ return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes)
29
+
30
+ @staticmethod
31
+ def is_rocm_cpp_template(node: BaseSchedulerNode) -> bool:
32
+ return isinstance(node, SchedulerNode) and isinstance(
33
+ node.node, ROCmTemplateBuffer
34
+ )
35
+
36
+ def can_fuse_vertical(
37
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
38
+ ) -> bool:
39
+ return False
40
+
41
+ def define_kernel(self, src_code: str, node_schedule) -> str:
42
+ wrapper = V.graph.wrapper_code
43
+ if src_code in wrapper.src_to_kernel:
44
+ kernel_name = wrapper.src_to_kernel[src_code]
45
+ else:
46
+ fused_name = (
47
+ get_fused_kernel_name(node_schedule, config.triton.descriptive_names)
48
+ if config.triton.descriptive_names
49
+ else ""
50
+ )
51
+ kernel_name = "_".join(["rocm", fused_name, wrapper.next_kernel_suffix()])
52
+ # use the original src_code as the key
53
+ wrapper.src_to_kernel[src_code] = kernel_name
54
+ src_code = src_code.replace("KERNEL_NAME", kernel_name)
55
+
56
+ _, _, kernel_path = get_path(code_hash(src_code), "py")
57
+
58
+ compile_wrapper = IndentedBuffer()
59
+ compile_wrapper.writeline("async_compile.rocm(r'''")
60
+ compile_wrapper.splice(src_code, strip=True)
61
+ compile_wrapper.writeline(
62
+ f"''', 'so', aot_compile={str(V.graph.aot_mode)})"
63
+ )
64
+
65
+ metadata_comment = f"# kernel path: {kernel_path}"
66
+ origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
67
+ metadata_comment += "\n" + origins + "\n" + detailed_origins
68
+ wrapper.define_kernel(
69
+ kernel_name, compile_wrapper.getvalue(), metadata_comment
70
+ )
71
+ return kernel_name
72
+
73
+ def codegen_template(
74
+ self,
75
+ template_node: BaseSchedulerNode,
76
+ epilogue_nodes: Sequence[BaseSchedulerNode],
77
+ prologue_nodes: Sequence[BaseSchedulerNode],
78
+ ):
79
+ """
80
+ Codegen a ROCm template, possibly with fused epilogues
81
+ """
82
+ assert self.is_rocm_cpp_template(template_node), (
83
+ "Template node passed to ROCmScheduler.codegen_template must be a SchedulerNode that wraps a ROCmTemplateBuffer"
84
+ )
85
+ template_node = cast(SchedulerNode, template_node)
86
+ _, (_numel, rnumel) = template_node.group
87
+ assert rnumel == 1
88
+ ctb: ROCmTemplateBuffer = cast(ROCmTemplateBuffer, template_node.node)
89
+ kernel, render = ctb.make_kernel_render(ctb) # type: ignore[misc]
90
+ with kernel:
91
+ template_node.mark_run()
92
+ src_code = render()
93
+
94
+ with V.set_kernel_handler(kernel):
95
+ node_schedule = [template_node]
96
+ kernel_name = self.define_kernel(src_code, node_schedule)
97
+ self.codegen_comment(node_schedule, kernel_name)
98
+ kernel.call_kernel(kernel_name, ctb)
99
+ V.graph.removed_buffers |= kernel.removed_buffers
100
+ self.free_buffers_in_scheduler()
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/xpu/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+ from ..common import (
6
+ DeviceOpOverrides,
7
+ register_device_op_overrides,
8
+ TritonScratchWorkspace,
9
+ )
10
+
11
+
12
+ class XPUDeviceOpOverrides(DeviceOpOverrides):
13
+ def import_get_raw_stream_as(self, name: str) -> str:
14
+ return f"from torch._C import _xpu_getCurrentRawStream as {name}"
15
+
16
+ def set_device(self, device_idx: int) -> str:
17
+ return f"torch.xpu.set_device({device_idx})"
18
+
19
+ def synchronize(self) -> str:
20
+ return "torch.xpu.synchronize()"
21
+
22
+ def device_guard(self, device_idx: int) -> str:
23
+ return f"torch.xpu._DeviceGuard({device_idx})"
24
+
25
+ def cpp_device_guard(self) -> str:
26
+ return "at::DeviceGuard"
27
+
28
+ def cpp_aoti_device_guard(self) -> str:
29
+ return "AOTIXpuGuard"
30
+
31
+ def cpp_stream_guard(self) -> str:
32
+ return "at::xpu::XPUStreamGuard"
33
+
34
+ def cpp_aoti_stream_guard(self) -> str:
35
+ return "AOTIXpuStreamGuard"
36
+
37
+ def cpp_getStreamFromExternal(self) -> str:
38
+ return "at::xpu::getStreamFromExternal"
39
+
40
+ def kernel_header(self) -> str:
41
+ source_codes = """
42
+ #include <torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h>
43
+ """
44
+ return source_codes
45
+
46
+ def kernel_driver(self) -> str:
47
+ return ""
48
+
49
+ def cpp_stream_type(self) -> str:
50
+ return "sycl::queue*"
51
+
52
+ def aoti_get_stream(self) -> str:
53
+ return "aoti_torch_get_current_xpu_stream"
54
+
55
+ def cpp_kernel_type(self) -> str:
56
+ return "std::unique_ptr<sycl::kernel>"
57
+
58
+ def cpp_device_ptr(self) -> str:
59
+ return "void *"
60
+
61
+ def cpp_scratch(
62
+ self, idx: int, workspace: TritonScratchWorkspace, prefix: Optional[str] = None
63
+ ) -> Optional[tuple[list[str], str]]:
64
+ return [f"void *global_scratch_{idx} = 0;"], f"global_scratch_{idx}"
65
+
66
+
67
+ register_device_op_overrides("xpu", XPUDeviceOpOverrides())