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

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/.gitignore +1 -0
  2. .venv/.lock +0 -0
  3. .venv/bin/activate.bat +71 -0
  4. .venv/bin/activate.fish +124 -0
  5. .venv/bin/activate.nu +102 -0
  6. .venv/bin/activate.ps1 +82 -0
  7. .venv/bin/distro +10 -0
  8. .venv/bin/dotenv +10 -0
  9. .venv/bin/f2py +10 -0
  10. .venv/bin/hf-gradio +10 -0
  11. .venv/bin/huggingface-cli +10 -0
  12. .venv/bin/numpy-config +10 -0
  13. .venv/bin/rst2html +10 -0
  14. .venv/bin/rst2html5 +10 -0
  15. .venv/bin/rst2odt +10 -0
  16. .venv/bin/upload_theme +10 -0
  17. .venv/bin/uvicorn +10 -0
  18. .venv/bin/watchfiles +10 -0
  19. .venv/lib/python3.10/site-packages/torch/_inductor/__autotune_main__.py +33 -0
  20. .venv/lib/python3.10/site-packages/torch/_inductor/__init__.py +446 -0
  21. .venv/lib/python3.10/site-packages/torch/_inductor/analyze_preserves_zero_mask.py +166 -0
  22. .venv/lib/python3.10/site-packages/torch/_inductor/aoti_eager.py +299 -0
  23. .venv/lib/python3.10/site-packages/torch/_inductor/async_compile.py +755 -0
  24. .venv/lib/python3.10/site-packages/torch/_inductor/await_utils.py +178 -0
  25. .venv/lib/python3.10/site-packages/torch/_inductor/bounds.py +260 -0
  26. .venv/lib/python3.10/site-packages/torch/_inductor/choices.py +658 -0
  27. .venv/lib/python3.10/site-packages/torch/_inductor/codecache.py +0 -0
  28. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/__init__.py +0 -0
  29. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py +36 -0
  30. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/block_analysis.py +219 -0
  31. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/common.py +0 -0
  32. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp.py +0 -0
  33. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_bmm_template.py +263 -0
  34. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py +1090 -0
  35. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_gemm_template.py +1828 -0
  36. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py +514 -0
  37. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py +2232 -0
  38. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template.py +139 -0
  39. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template_kernel.py +622 -0
  40. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_utils.py +789 -0
  41. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py +0 -0
  42. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py +898 -0
  43. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py +897 -0
  44. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py +303 -0
  45. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py +30 -0
  46. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py +186 -0
  47. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/custom_extern_kernel_codegen.py +101 -0
  48. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/debug_utils.py +290 -0
  49. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/halide.py +1760 -0
  50. .venv/lib/python3.10/site-packages/torch/_inductor/codegen/memory_planning.py +816 -0
.venv/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *
.venv/.lock ADDED
File without changes
.venv/bin/activate.bat ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @REM Copyright (c) 2020-202x The virtualenv developers
2
+ @REM
3
+ @REM Permission is hereby granted, free of charge, to any person obtaining
4
+ @REM a copy of this software and associated documentation files (the
5
+ @REM "Software"), to deal in the Software without restriction, including
6
+ @REM without limitation the rights to use, copy, modify, merge, publish,
7
+ @REM distribute, sublicense, and/or sell copies of the Software, and to
8
+ @REM permit persons to whom the Software is furnished to do so, subject to
9
+ @REM the following conditions:
10
+ @REM
11
+ @REM The above copyright notice and this permission notice shall be
12
+ @REM included in all copies or substantial portions of the Software.
13
+ @REM
14
+ @REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ @REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ @REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ @REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ @REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ @REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ @REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ @REM This file is UTF-8 encoded, so we need to update the current code page while executing it
23
+ @for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
24
+
25
+ @if defined _OLD_CODEPAGE (
26
+ "%SystemRoot%\System32\chcp.com" 65001 > nul
27
+ )
28
+
29
+ @for %%i in ("/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv") do @set "VIRTUAL_ENV=%%~fi"
30
+
31
+ @set "VIRTUAL_ENV_PROMPT=openenv-fraud-detection"
32
+ @if NOT DEFINED VIRTUAL_ENV_PROMPT (
33
+ @for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
34
+ )
35
+
36
+ @if defined _OLD_VIRTUAL_PROMPT (
37
+ @set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
38
+ ) else (
39
+ @if not defined PROMPT (
40
+ @set "PROMPT=$P$G"
41
+ )
42
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
43
+ @set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
44
+ )
45
+ )
46
+ @if not defined VIRTUAL_ENV_DISABLE_PROMPT (
47
+ @set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
48
+ )
49
+
50
+ @REM Don't use () to avoid problems with them in %PATH%
51
+ @if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
52
+ @set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
53
+ :ENDIFVHOME
54
+
55
+ @set PYTHONHOME=
56
+
57
+ @REM if defined _OLD_VIRTUAL_PATH (
58
+ @if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
59
+ @set "PATH=%_OLD_VIRTUAL_PATH%"
60
+ :ENDIFVPATH1
61
+ @REM ) else (
62
+ @if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
63
+ @set "_OLD_VIRTUAL_PATH=%PATH%"
64
+ :ENDIFVPATH2
65
+
66
+ @set "PATH=%VIRTUAL_ENV%\bin;%PATH%"
67
+
68
+ @if defined _OLD_CODEPAGE (
69
+ "%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
70
+ @set _OLD_CODEPAGE=
71
+ )
.venv/bin/activate.fish ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.
23
+ # Do not run it directly.
24
+
25
+ function _bashify_path -d "Converts a fish path to something bash can recognize"
26
+ set fishy_path $argv
27
+ set bashy_path $fishy_path[1]
28
+ for path_part in $fishy_path[2..-1]
29
+ set bashy_path "$bashy_path:$path_part"
30
+ end
31
+ echo $bashy_path
32
+ end
33
+
34
+ function _fishify_path -d "Converts a bash path to something fish can recognize"
35
+ echo $argv | tr ':' '\n'
36
+ end
37
+
38
+ function deactivate -d 'Exit virtualenv mode and return to the normal environment.'
39
+ # reset old environment variables
40
+ if test -n "$_OLD_VIRTUAL_PATH"
41
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
42
+ if test (string sub -s 1 -l 1 $FISH_VERSION) -lt 3
43
+ set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH")
44
+ else
45
+ set -gx PATH $_OLD_VIRTUAL_PATH
46
+ end
47
+ set -e _OLD_VIRTUAL_PATH
48
+ end
49
+
50
+ if test -n "$_OLD_VIRTUAL_PYTHONHOME"
51
+ set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME"
52
+ set -e _OLD_VIRTUAL_PYTHONHOME
53
+ end
54
+
55
+ if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
56
+ and functions -q _old_fish_prompt
57
+ # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.
58
+ set -l fish_function_path
59
+
60
+ # Erase virtualenv's `fish_prompt` and restore the original.
61
+ functions -e fish_prompt
62
+ functions -c _old_fish_prompt fish_prompt
63
+ functions -e _old_fish_prompt
64
+ set -e _OLD_FISH_PROMPT_OVERRIDE
65
+ end
66
+
67
+ set -e VIRTUAL_ENV
68
+ set -e VIRTUAL_ENV_PROMPT
69
+
70
+ if test "$argv[1]" != 'nondestructive'
71
+ # Self-destruct!
72
+ functions -e pydoc
73
+ functions -e deactivate
74
+ functions -e _bashify_path
75
+ functions -e _fishify_path
76
+ end
77
+ end
78
+
79
+ # Unset irrelevant variables.
80
+ deactivate nondestructive
81
+
82
+ set -gx VIRTUAL_ENV '/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv'
83
+
84
+ # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling
85
+ if test (string sub -s 1 -l 1 $FISH_VERSION) -lt 3
86
+ set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)
87
+ else
88
+ set -gx _OLD_VIRTUAL_PATH $PATH
89
+ end
90
+ set -gx PATH "$VIRTUAL_ENV"'/bin' $PATH
91
+
92
+ # Prompt override provided?
93
+ # If not, just use the environment name.
94
+ if test -n 'openenv-fraud-detection'
95
+ set -gx VIRTUAL_ENV_PROMPT 'openenv-fraud-detection'
96
+ else
97
+ set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV")
98
+ end
99
+
100
+ # Unset `$PYTHONHOME` if set.
101
+ if set -q PYTHONHOME
102
+ set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
103
+ set -e PYTHONHOME
104
+ end
105
+
106
+ function pydoc
107
+ python -m pydoc $argv
108
+ end
109
+
110
+ if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
111
+ # Copy the current `fish_prompt` function as `_old_fish_prompt`.
112
+ functions -c fish_prompt _old_fish_prompt
113
+
114
+ function fish_prompt
115
+ # Run the user's prompt first; it might depend on (pipe)status.
116
+ set -l prompt (_old_fish_prompt)
117
+
118
+ printf '(%s) ' $VIRTUAL_ENV_PROMPT
119
+
120
+ string join -- \n $prompt # handle multi-line prompts
121
+ end
122
+
123
+ set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
124
+ end
.venv/bin/activate.nu ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ # virtualenv activation module:
23
+ # - Activate with `overlay use activate.nu`
24
+ # - Deactivate with `deactivate`, as usual
25
+ #
26
+ # To customize the overlay name, you can call `overlay use activate.nu as foo`, but then simply `deactivate` won't work
27
+ # because it is just an alias to hide the "activate" overlay. You'd need to call `overlay hide foo` manually.
28
+
29
+ module warning {
30
+ export-env {
31
+ const file = path self
32
+ error make -u {
33
+ msg: $"`($file | path basename)` is meant to be used with `overlay use`, not `source`"
34
+ }
35
+ }
36
+
37
+ }
38
+
39
+ use warning
40
+
41
+ export-env {
42
+
43
+ let nu_ver = (version | get version | split row '.' | take 2 | each { into int })
44
+ if $nu_ver.0 == 0 and $nu_ver.1 < 106 {
45
+ error make {
46
+ msg: 'virtualenv Nushell activation requires Nushell 0.106 or greater.'
47
+ }
48
+ }
49
+
50
+ def is-string [x] {
51
+ ($x | describe) == 'string'
52
+ }
53
+
54
+ def has-env [...names] {
55
+ $names | each {|n| $n in $env } | all {|i| $i }
56
+ }
57
+
58
+ def is-env-true [name: string] {
59
+ if (has-env $name) {
60
+ let val = ($env | get --optional $name)
61
+ if ($val | describe) == 'bool' {
62
+ $val
63
+ } else {
64
+ not ($val | is-empty)
65
+ }
66
+ } else {
67
+ false
68
+ }
69
+ }
70
+
71
+ let virtual_env = '/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv'
72
+ let bin = 'bin'
73
+ let path_name = if (has-env 'Path') { 'Path' } else { 'PATH' }
74
+ let venv_path = ([$virtual_env $bin] | path join)
75
+ let new_path = ($env | get $path_name | prepend $venv_path)
76
+ let virtual_env_prompt = if ('openenv-fraud-detection' | is-empty) {
77
+ ($virtual_env | path basename)
78
+ } else {
79
+ 'openenv-fraud-detection'
80
+ }
81
+ let new_env = { $path_name: $new_path VIRTUAL_ENV: $virtual_env VIRTUAL_ENV_PROMPT: $virtual_env_prompt }
82
+ let old_prompt_command = if (has-env 'PROMPT_COMMAND') { $env.PROMPT_COMMAND } else { '' }
83
+ let new_env = if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') {
84
+ $new_env
85
+ } else {
86
+ let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
87
+ let new_prompt = if (has-env 'PROMPT_COMMAND') {
88
+ if ('closure' in ($old_prompt_command | describe)) {
89
+ {|| $'($virtual_prefix)(do $old_prompt_command)' }
90
+ } else {
91
+ {|| $'($virtual_prefix)($old_prompt_command)' }
92
+ }
93
+ } else {
94
+ {|| $'($virtual_prefix)' }
95
+ }
96
+ $new_env | merge { PROMPT_COMMAND: $new_prompt VIRTUAL_PREFIX: $virtual_prefix }
97
+ }
98
+ load-env $new_env
99
+ }
100
+
101
+ export alias pydoc = python -m pydoc
102
+ export alias deactivate = overlay hide activate
.venv/bin/activate.ps1 ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2020-202x The virtualenv developers
2
+ #
3
+ # Permission is hereby granted, free of charge, to any person obtaining
4
+ # a copy of this software and associated documentation files (the
5
+ # "Software"), to deal in the Software without restriction, including
6
+ # without limitation the rights to use, copy, modify, merge, publish,
7
+ # distribute, sublicense, and/or sell copies of the Software, and to
8
+ # permit persons to whom the Software is furnished to do so, subject to
9
+ # the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be
12
+ # included in all copies or substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
22
+ $script:THIS_PATH = $myinvocation.mycommand.path
23
+ $script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent
24
+
25
+ function global:deactivate([switch] $NonDestructive) {
26
+ if (Test-Path variable:_OLD_VIRTUAL_PATH) {
27
+ $env:PATH = $variable:_OLD_VIRTUAL_PATH
28
+ Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global
29
+ }
30
+
31
+ if (Test-Path function:_old_virtual_prompt) {
32
+ $function:prompt = $function:_old_virtual_prompt
33
+ Remove-Item function:\_old_virtual_prompt
34
+ }
35
+
36
+ if ($env:VIRTUAL_ENV) {
37
+ Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue
38
+ }
39
+
40
+ if ($env:VIRTUAL_ENV_PROMPT) {
41
+ Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue
42
+ }
43
+
44
+ if (!$NonDestructive) {
45
+ # Self destruct!
46
+ Remove-Item function:deactivate
47
+ Remove-Item function:pydoc
48
+ }
49
+ }
50
+
51
+ function global:pydoc {
52
+ python -m pydoc $args
53
+ }
54
+
55
+ # unset irrelevant variables
56
+ deactivate -nondestructive
57
+
58
+ $VIRTUAL_ENV = $BASE_DIR
59
+ $env:VIRTUAL_ENV = $VIRTUAL_ENV
60
+
61
+ if ("openenv-fraud-detection" -ne "") {
62
+ $env:VIRTUAL_ENV_PROMPT = "openenv-fraud-detection"
63
+ }
64
+ else {
65
+ $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf )
66
+ }
67
+
68
+ New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH
69
+
70
+ $env:PATH = "$env:VIRTUAL_ENV/bin:" + $env:PATH
71
+ if (!$env:VIRTUAL_ENV_DISABLE_PROMPT) {
72
+ function global:_old_virtual_prompt {
73
+ ""
74
+ }
75
+ $function:_old_virtual_prompt = $function:prompt
76
+
77
+ function global:prompt {
78
+ # Add the custom prefix to the existing prompt
79
+ $previous_prompt_value = & $function:_old_virtual_prompt
80
+ ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value)
81
+ }
82
+ }
.venv/bin/distro ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from distro.distro import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/dotenv ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from dotenv.__main__ import cli
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(cli())
.venv/bin/f2py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from numpy.f2py.f2py2e import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/hf-gradio ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from hf_gradio.cli import app
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(app())
.venv/bin/huggingface-cli ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from huggingface_hub.cli.deprecated_cli import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/numpy-config ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from numpy._configtool import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/rst2html ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from docutils.core import rst2html
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(rst2html())
.venv/bin/rst2html5 ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from docutils.core import rst2html5
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(rst2html5())
.venv/bin/rst2odt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from docutils.core import rst2odt
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(rst2odt())
.venv/bin/upload_theme ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from gradio.themes.upload_theme import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/uvicorn ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from uvicorn.main import main
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(main())
.venv/bin/watchfiles ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/home/sumit-ghosh/Development/hackathons/meta-final-project/meta-hackathon/.venv/bin/python
2
+ # -*- coding: utf-8 -*-
3
+ import sys
4
+ from watchfiles.cli import cli
5
+ if __name__ == "__main__":
6
+ if sys.argv[0].endswith("-script.pyw"):
7
+ sys.argv[0] = sys.argv[0][:-11]
8
+ elif sys.argv[0].endswith(".exe"):
9
+ sys.argv[0] = sys.argv[0][:-4]
10
+ sys.exit(cli())
.venv/lib/python3.10/site-packages/torch/_inductor/__autotune_main__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+
5
+ from torch._inductor.autotune_process import TuningProcess
6
+ from torch._inductor.compile_worker.utils import _async_compile_initializer
7
+
8
+
9
+ log = logging.getLogger(__name__)
10
+
11
+
12
+ def main() -> None:
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument("--parent", type=int)
15
+ parser.add_argument("--read-fd", type=int)
16
+ parser.add_argument("--write-fd", type=int)
17
+ args = parser.parse_args()
18
+ read_pipe = os.fdopen(args.read_fd, "rb")
19
+ write_pipe = os.fdopen(args.write_fd, "wb")
20
+
21
+ try:
22
+ # Ensures the subprocess exits if the parent crashes:
23
+ _async_compile_initializer(args.parent)
24
+ TuningProcess.process_main(read_pipe, write_pipe)
25
+ except Exception:
26
+ log.exception("Uncaught exception in autotune subprocess")
27
+ finally:
28
+ read_pipe.close()
29
+ write_pipe.close()
30
+
31
+
32
+ if __name__ == "__main__":
33
+ main()
.venv/lib/python3.10/site-packages/torch/_inductor/__init__.py ADDED
@@ -0,0 +1,446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import logging
6
+ import os
7
+ from typing import Any, IO, Literal, Optional, TYPE_CHECKING, Union
8
+
9
+ import torch.fx
10
+
11
+ from .standalone_compile import CompiledArtifact # noqa: TC001
12
+
13
+
14
+ if TYPE_CHECKING:
15
+ from torch._inductor.utils import InputType
16
+ from torch.export import ExportedProgram
17
+ from torch.export.pt2_archive._package import AOTICompiledModel
18
+ from torch.export.pt2_archive._package_weights import Weights
19
+ from torch.types import FileLike
20
+
21
+ __all__ = [
22
+ "compile",
23
+ "list_mode_options",
24
+ "list_options",
25
+ "cudagraph_mark_step_begin",
26
+ "standalone_compile",
27
+ ]
28
+
29
+
30
+ log = logging.getLogger(__name__)
31
+
32
+
33
+ def compile(
34
+ gm: torch.fx.GraphModule,
35
+ example_inputs: list[InputType],
36
+ options: Optional[dict[str, Any]] = None,
37
+ ):
38
+ """
39
+ Compile a given FX graph with TorchInductor. This allows compiling
40
+ FX graphs captured without using TorchDynamo.
41
+
42
+ Args:
43
+ gm: The FX graph to compile.
44
+ example_inputs: List of tensor inputs.
45
+ options: Optional dict of config options. See `torch._inductor.config`.
46
+
47
+ Returns:
48
+ Callable with same behavior as gm but faster.
49
+ """
50
+ from .compile_fx import compile_fx
51
+
52
+ return compile_fx(gm, example_inputs, config_patches=options)
53
+
54
+
55
+ def aoti_compile_and_package(
56
+ exported_program: ExportedProgram,
57
+ _deprecated_unused_args=None,
58
+ _deprecated_unused_kwargs=None,
59
+ *,
60
+ package_path: Optional[FileLike] = None,
61
+ inductor_configs: Optional[dict[str, Any]] = None,
62
+ ) -> str:
63
+ """
64
+ Compiles the exported program with AOTInductor, and packages it into a .pt2
65
+ artifact specified by the input package_path. To load the package, you can
66
+ call ``torch._inductor.aoti_load_package(package_path)``.
67
+
68
+ An example usage is as follows:
69
+
70
+ .. code-block:: python
71
+
72
+ ep = torch.export.export(M(), ...)
73
+ aoti_file = torch._inductor.aoti_compile_and_package(
74
+ ep, package_path="my_package.pt2"
75
+ )
76
+ compiled_model = torch._inductor.aoti_load_package("my_package.pt2")
77
+
78
+ To compile and save multiple models into a single ``.pt2`` artifact, you can do
79
+ the following:
80
+
81
+ .. code-block:: python
82
+
83
+ ep1 = torch.export.export(M1(), ...)
84
+ aoti_file1 = torch._inductor.aot_compile(
85
+ ep1, ..., options={"aot_inductor.package": True}
86
+ )
87
+ ep2 = torch.export.export(M2(), ...)
88
+ aoti_file2 = torch._inductor.aot_compile(
89
+ ep2, ..., options={"aot_inductor.package": True}
90
+ )
91
+
92
+ from torch._inductor.package import package_aoti, load_package
93
+
94
+ package_aoti("my_package.pt2", {"model1": aoti_file1, "model2": aoti_file2})
95
+
96
+ compiled_model1 = load_package("my_package.pt2", "model1")
97
+ compiled_model2 = load_package("my_package.pt2", "model2")
98
+
99
+ Args:
100
+ exported_program: An exported program created through a call from torch.export
101
+ package_path: Optional specified path to the generated .pt2 artifact.
102
+ inductor_configs: Optional dictionary of configs to control inductor.
103
+
104
+ Returns:
105
+ Path to the generated artifact
106
+ """
107
+ from torch.export import ExportedProgram
108
+
109
+ from .debug import aot_inductor_minifier_wrapper
110
+
111
+ if not isinstance(exported_program, ExportedProgram):
112
+ raise ValueError("Only ExportedProgram is supported")
113
+
114
+ if exported_program.example_inputs is None:
115
+ raise RuntimeError(
116
+ "exported_program.example_inputs is required to be set in order "
117
+ "for AOTInductor compilation."
118
+ )
119
+
120
+ if _deprecated_unused_args is not None or _deprecated_unused_kwargs is not None:
121
+ log.warning(
122
+ "You no longer need to specify args/kwargs to aoti_compile_and_package "
123
+ "as we can get this information from exported_program.example_inputs."
124
+ )
125
+
126
+ assert (
127
+ package_path is None
128
+ or (
129
+ isinstance(package_path, (io.IOBase, IO))
130
+ and package_path.writable()
131
+ and package_path.seekable()
132
+ )
133
+ or (
134
+ isinstance(package_path, (str, os.PathLike))
135
+ and os.fspath(package_path).endswith(".pt2")
136
+ )
137
+ ), (
138
+ f"Expect package path to be a file ending in .pt2, is None, or is a buffer. Instead got {package_path}"
139
+ )
140
+
141
+ inductor_configs = inductor_configs or {}
142
+ inductor_configs["aot_inductor.package"] = True
143
+
144
+ if inductor_configs.get("aot_inductor.output_path"):
145
+ raise RuntimeError(
146
+ "Please pass in a package path to aot_inductor_compile() instead "
147
+ "of setting the aot_inductor.output_path config."
148
+ )
149
+
150
+ # a wrapper around aoti_compile_and_package_inner.
151
+ return aot_inductor_minifier_wrapper(
152
+ _aoti_compile_and_package_inner,
153
+ exported_program,
154
+ package_path=package_path,
155
+ inductor_configs=inductor_configs,
156
+ )
157
+
158
+
159
+ def _aoti_compile_and_package_inner(
160
+ gm: torch.nn.Module,
161
+ # flat_example_inputs: List[Any],
162
+ args: tuple[Any],
163
+ kwargs: Optional[dict[str, Any]] = None,
164
+ *,
165
+ load_and_run: bool = False,
166
+ check_accuracy: Optional[str] = None,
167
+ package_path: Optional[Union[str, io.BytesIO]] = None,
168
+ inductor_configs: Optional[dict[str, Any]] = None,
169
+ ):
170
+ """
171
+ See docstring for aoti_compile_and_package.
172
+
173
+ If `load_and_run` is True, this function will load the compiled model and run it.
174
+ This is for the minifier to check the correctness of the compiled model.
175
+
176
+ If `check_accuracy` is set, this function will check the accuracy of the compiled
177
+ model against gm. kwargs must be None if check_accuracy is set.
178
+ "strict_accuracy" means "we will minify any time we see anything that
179
+ diverges", whereas "accuracy" is more conservative, and will only minify if there
180
+ is a meaningful fp64 divergence
181
+ """
182
+
183
+ if check_accuracy:
184
+ assert kwargs is None or len(kwargs) == 0, (
185
+ "when checking for accuracy, the inputs must have been flattened and kwargs is None"
186
+ )
187
+
188
+ from .package import package_aoti
189
+
190
+ assert isinstance(gm, torch.fx.GraphModule)
191
+
192
+ kwargs = kwargs or {}
193
+
194
+ aoti_files = aot_compile(gm, args, kwargs, options=inductor_configs)
195
+ assert isinstance(aoti_files, list)
196
+
197
+ if package_path is None:
198
+ path = [
199
+ os.path.splitext(file)[0]
200
+ for file in aoti_files
201
+ if isinstance(file, str) and os.path.splitext(file)[1] == ".so"
202
+ ]
203
+ if len(path) == 0:
204
+ path = [
205
+ os.path.splitext(file)[0]
206
+ for file in aoti_files
207
+ if isinstance(file, str) and os.path.splitext(file)[1] == ".cpp"
208
+ ]
209
+ package_path = path[0] + ".pt2"
210
+
211
+ res = package_aoti(package_path, aoti_files)
212
+ assert res == package_path
213
+
214
+ if load_and_run or check_accuracy:
215
+ compiled_model = aoti_load_package(package_path)
216
+ if check_accuracy:
217
+ from torch._dynamo.debug_utils import AccuracyError, same_two_models
218
+
219
+ # This might look inverted but it's not. strict_accuracy means "we will
220
+ # minify any time we see anything that diverges", whereas accuracy is more
221
+ # conservative, and will only minify if there is a meaningful fp64
222
+ # divergence
223
+ not_strict_accuracy = check_accuracy == "accuracy"
224
+ if not same_two_models(
225
+ gm,
226
+ compiled_model, # type: ignore[arg-type]
227
+ args,
228
+ only_fwd=True,
229
+ require_fp64=not_strict_accuracy,
230
+ ignore_non_fp=not_strict_accuracy,
231
+ ):
232
+ raise AccuracyError("Bad accuracy detected")
233
+ else:
234
+ compiled_model(*args, **kwargs)
235
+
236
+ return package_path
237
+
238
+
239
+ def aoti_load_package(
240
+ path: FileLike, run_single_threaded: bool = False, device_index: int = -1
241
+ ) -> AOTICompiledModel:
242
+ """
243
+ Loads the model from the PT2 package.
244
+
245
+ If multiple models were packaged into the PT2, this will load the default
246
+ model. To load a specific model, you can directly call the load API
247
+
248
+ .. code-block:: python
249
+
250
+ from torch._inductor.package import load_package
251
+
252
+ compiled_model1 = load_package("my_package.pt2", "model1")
253
+ compiled_model2 = load_package("my_package.pt2", "model2")
254
+
255
+ Args:
256
+ path: Path to the .pt2 package
257
+ run_single_threaded (bool): Whether the model should be run without
258
+ thread synchronization logic. This is useful to avoid conflicts with
259
+ CUDAGraphs.
260
+ device_index (int): The index of the device to which the PT2 package is
261
+ to be loaded. By default, `device_index=-1` is used, which corresponds
262
+ to the device `cuda` when using CUDA. Passing `device_index=1` would
263
+ load the package to `cuda:1`, for example.
264
+ """
265
+ from torch._inductor.package import load_package
266
+
267
+ return load_package(
268
+ path, run_single_threaded=run_single_threaded, device_index=device_index
269
+ )
270
+
271
+
272
+ def aot_compile(
273
+ gm: torch.fx.GraphModule,
274
+ args: tuple[Any, ...],
275
+ kwargs: Optional[dict[str, Any]] = None,
276
+ *,
277
+ options: Optional[dict[str, Any]] = None,
278
+ ) -> Union[str, list[Union[str, Weights]], torch.fx.GraphModule]:
279
+ """
280
+ Ahead-of-time compile a given FX graph with TorchInductor into a shared library.
281
+
282
+ Args:
283
+ gm: The FX graph to compile.
284
+ args: Example arguments
285
+ kwargs: Example keyword arguments
286
+ options: Optional dict of config options. See `torch._inductor.config`.
287
+
288
+ Returns:
289
+ Path to the generated shared library, or a list of files generated by
290
+ AOTI if aot_inductor.package=True.
291
+ TODO: make it return a list by default
292
+ """
293
+ from .compile_fx import _aoti_flatten_inputs, compile_fx_aot
294
+
295
+ if hasattr(gm, "_guards_fn"):
296
+ # Do not compile the guards function, since it may contain checks
297
+ # that are not currently supported by AOTI. In particular, non-Tensor
298
+ # arguments are converted to None and will fail specialization checks.
299
+ node = next(iter(gm.graph.find_nodes(op="call_module", target="_guards_fn")))
300
+ gm.graph.erase_node(node)
301
+ delattr(gm, "_guards_fn")
302
+ gm.recompile()
303
+
304
+ flat_example_inputs, options = _aoti_flatten_inputs(
305
+ gm, args, kwargs, options=options
306
+ )
307
+ from torch._export.utils import _compiling_state_context
308
+
309
+ with _compiling_state_context():
310
+ return compile_fx_aot(
311
+ gm,
312
+ flat_example_inputs, # type: ignore[arg-type]
313
+ config_patches=options,
314
+ )
315
+
316
+
317
+ lite_mode_options = {
318
+ # Fallback by default unless users explicitly annotated with
319
+ # regional inductor compile.
320
+ "fallback_by_default": True,
321
+ "selective_decompose": True,
322
+ # Disable reorder optimizations
323
+ "reorder_for_peak_memory": False,
324
+ "reorder_for_compute_comm_overlap": False,
325
+ "triton.reorder_for_reducing_graph_partitions": False,
326
+ # Disable pre-, joint-, post-grad passes
327
+ "use_pre_grad_passes": False,
328
+ "use_joint_graph_passes": False,
329
+ "use_post_grad_passes": False,
330
+ # Disable dead code elimination (dce) and buffer reuse
331
+ "use_dce": False,
332
+ "allow_buffer_reuse": False,
333
+ }
334
+
335
+
336
+ def list_mode_options(
337
+ mode: Optional[str] = None, dynamic: Optional[bool] = None
338
+ ) -> dict[str, Any]:
339
+ r"""Returns a dictionary describing the optimizations that each of the available
340
+ modes passed to `torch.compile()` performs.
341
+
342
+ Args:
343
+ mode (str, optional): The mode to return the optimizations for.
344
+ If None, returns optimizations for all modes
345
+ dynamic (bool, optional): Whether dynamic shape is enabled.
346
+
347
+ Example::
348
+ >>> torch._inductor.list_mode_options()
349
+ """
350
+
351
+ mode_options: dict[str, dict[str, bool]] = {
352
+ "default": {},
353
+ # lite backend for opt-in optimizations
354
+ "lite": lite_mode_options,
355
+ # enable cudagraphs
356
+ "reduce-overhead": {
357
+ "triton.cudagraphs": True,
358
+ },
359
+ # enable max-autotune
360
+ "max-autotune-no-cudagraphs": {
361
+ "max_autotune": True,
362
+ "coordinate_descent_tuning": True,
363
+ },
364
+ # enable max-autotune
365
+ # enable cudagraphs
366
+ "max-autotune": {
367
+ "max_autotune": True,
368
+ "triton.cudagraphs": True,
369
+ "coordinate_descent_tuning": True,
370
+ },
371
+ }
372
+ try:
373
+ return mode_options[mode] if mode else mode_options
374
+ except KeyError as e:
375
+ raise RuntimeError(
376
+ f"Unrecognized mode={mode}, should be one of: {', '.join(mode_options.keys())}"
377
+ ) from e
378
+
379
+
380
+ def list_options() -> list[str]:
381
+ r"""Returns a dictionary describing the optimizations and debug configurations
382
+ that are available to `torch.compile()`.
383
+
384
+ The options are documented in `torch._inductor.config`.
385
+
386
+ Example::
387
+
388
+ >>> torch._inductor.list_options()
389
+ """
390
+
391
+ from torch._inductor import config
392
+
393
+ current_config: dict[str, Any] = config.get_config_copy()
394
+
395
+ return list(current_config.keys())
396
+
397
+
398
+ def cudagraph_mark_step_begin():
399
+ "Indicates that a new iteration of inference or training is about to begin."
400
+ from .cudagraph_trees import mark_step_begin
401
+
402
+ mark_step_begin()
403
+
404
+
405
+ def standalone_compile(
406
+ gm: torch.fx.GraphModule,
407
+ example_inputs: list[InputType],
408
+ *,
409
+ dynamic_shapes: Literal[
410
+ "from_example_inputs", "from_tracing_context", "from_graph"
411
+ ] = "from_graph",
412
+ options: Optional[dict[str, Any]] = None,
413
+ aot: bool = False, # AOT mode, which uses BundledAOTAutogradCache
414
+ ) -> CompiledArtifact:
415
+ """
416
+ Precompilation API for inductor.
417
+
418
+ .. code-block:: python
419
+
420
+ compiled_artifact = torch._inductor.standalone_compile(gm, args)
421
+ compiled_artifact.save(path=path, format="binary")
422
+
423
+ # Later on a new process
424
+ loaded = torch._inductor.CompiledArtifact.load(path=path, format="binary")
425
+ compiled_out = loaded(*args)
426
+
427
+ Args:
428
+ gm: Graph Module
429
+ example_inputs: Inputs for the graph module
430
+ dynamic_shapes: If "from_graph" (default), we will use the dynamic
431
+ shapes in the passed-in graph module.
432
+ If "from_tracing_context", we use the dynamic shape info in the
433
+ ambient tracing context.
434
+ If "from_example_inputs", we will specialize the graph on the
435
+ example_inputs.
436
+ options: Inductor compilation options
437
+
438
+ Returns:
439
+ CompiledArtifact that can be saved to disk or invoked directly.
440
+ """
441
+ from .standalone_compile import standalone_compile
442
+
443
+ options = options if options else {}
444
+ return standalone_compile(
445
+ gm, example_inputs, dynamic_shapes=dynamic_shapes, options=options, aot=aot
446
+ )
.venv/lib/python3.10/site-packages/torch/_inductor/analyze_preserves_zero_mask.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import itertools
3
+ from typing import Any, Optional, TYPE_CHECKING
4
+
5
+ import sympy
6
+
7
+ import torch
8
+ from torch._inductor import config
9
+ from torch._inductor.dtype_propagation import DtypePropagationOpsHandler
10
+ from torch._inductor.index_propagation import SymPyOps, TypedExpr
11
+
12
+ from .ops_handler import DefaultHandler
13
+ from .virtualized import StoreMode, V
14
+
15
+
16
+ if TYPE_CHECKING:
17
+ from torch._inductor.scheduler import SchedulerNode
18
+
19
+
20
+ def construct_symbol(count: int, dtype: torch.dtype) -> sympy.Symbol:
21
+ return sympy.Symbol(f"unknown_{count}")
22
+
23
+
24
+ class PreservesZeros(SymPyOps, DefaultHandler):
25
+ """
26
+ For prologue kernels where the loads are masked, does the final store of this kernel preserve
27
+ the zeros.
28
+ """
29
+
30
+ def __init__(self) -> None:
31
+ self.count = itertools.count(0)
32
+ self.store_preserves_zeros: Optional[bool] = None
33
+ self.dtype_prop = DtypePropagationOpsHandler()
34
+
35
+ def load(self, name: str, index: sympy.Expr) -> TypedExpr:
36
+ # In prologue fusion, all loads get broadcasted
37
+ dtype = self.dtype_prop.load(name, index)
38
+ return TypedExpr(
39
+ sympy.Float(0) if dtype.is_floating_point else sympy.Integer(0), dtype
40
+ )
41
+
42
+ def store(
43
+ self, name: str, index: sympy.Expr, value: TypedExpr, mode: "StoreMode" = None
44
+ ) -> None:
45
+ assert isinstance(self, PreservesZeros)
46
+ # should only have a single store in prologue
47
+ assert self.store_preserves_zeros is None
48
+ self.store_preserves_zeros = value.is_constant() and value.expr == 0
49
+
50
+ def indirect_indexing(self, *args: Any, **kwargs: Any) -> sympy.Expr:
51
+ return construct_symbol(next(self.count), torch.int32)
52
+
53
+ def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
54
+ from torch._inductor.codegen.common import OpDecompositions
55
+
56
+ if hasattr(OpDecompositions, name):
57
+ return getattr(OpDecompositions, name)(*args, **kwargs).value
58
+
59
+ dtype = getattr(self.dtype_prop, name)(*args, **kwargs)
60
+ return TypedExpr(construct_symbol(next(self.count), dtype), dtype)
61
+
62
+
63
+ def prologue_preserves_zero_mask(prologue: "SchedulerNode") -> bool:
64
+ """
65
+ Does this prologue preserve zero masks
66
+ """
67
+ preserves_zeros = PreservesZeros()
68
+ with V.set_ops_handler(preserves_zeros):
69
+ prologue._body(*prologue.get_ranges())
70
+
71
+ store_preserves_zeros = preserves_zeros.store_preserves_zeros
72
+ assert isinstance(store_preserves_zeros, bool)
73
+
74
+ return store_preserves_zeros
75
+
76
+
77
+ @dataclasses.dataclass
78
+ class DTypeContainer:
79
+ dtype: torch.dtype
80
+ is_scalar: bool = False
81
+
82
+
83
+ class RecordLowPrecisionOps(DefaultHandler):
84
+ def __init__(self, disallow_fp32_ops: bool = False) -> None:
85
+ self.disallow_fp32_ops = disallow_fp32_ops
86
+ self.low_precision_numeric_op = False
87
+ self.dtype_prop = DtypePropagationOpsHandler()
88
+ self.non_numeric_ops = (
89
+ "to_dtype",
90
+ "constant",
91
+ "where",
92
+ )
93
+
94
+ def load(self, name: str, index: sympy.Expr) -> DTypeContainer:
95
+ return DTypeContainer(self.dtype_prop.load(name, index))
96
+
97
+ @staticmethod
98
+ def store(
99
+ name: str, index: sympy.Expr, value: TypedExpr, mode: "StoreMode" = None
100
+ ) -> None:
101
+ pass
102
+
103
+ def check_bounds(
104
+ self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool
105
+ ) -> None:
106
+ pass
107
+
108
+ @staticmethod
109
+ # pyrefly: ignore [bad-override]
110
+ def indirect_indexing(*args: Any, **kwargs: Any) -> sympy.Expr:
111
+ return sympy.S.Zero
112
+
113
+ def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
114
+ out_dtype = getattr(self.dtype_prop, name)(*args, **kwargs)
115
+ out = DTypeContainer(out_dtype, is_scalar=(name == "constant"))
116
+ if name == "constant":
117
+ return DTypeContainer(torch.float, is_scalar=True)
118
+
119
+ uses_low_prec = any(
120
+ isinstance(dtype_cont, DTypeContainer)
121
+ and dtype_cont.dtype is not None
122
+ and low_prec_float(dtype_cont.dtype)
123
+ for dtype_cont in itertools.chain((out,), args, kwargs.values())
124
+ )
125
+
126
+ if uses_low_prec and name not in self.non_numeric_ops:
127
+ self.low_precision_numeric_op = True
128
+
129
+ if (
130
+ self.disallow_fp32_ops
131
+ and out.dtype in (torch.float32, torch.float64)
132
+ and not out.is_scalar
133
+ ):
134
+ self.low_precision_numeric_op = True
135
+
136
+ return out
137
+
138
+
139
+ def low_prec_float(dtype: torch.dtype) -> bool:
140
+ return dtype.is_floating_point and dtype.itemsize < 4
141
+
142
+
143
+ def can_codegen_without_upcasts(
144
+ prologue: "SchedulerNode",
145
+ disallow_fp32_ops: bool = False,
146
+ ) -> bool:
147
+ """
148
+ Can this prologue be run without `upcast_to_fp32` while preserving numerics.
149
+
150
+ This is only true if the node only contains dtype conversions, indexing, and other non-arithmetic operators.
151
+
152
+ If disallow_fp32_ops is True, then we also disallow ops that are explicitly computed in fp32 or fp64.
153
+ """
154
+ if prologue.get_operation_names() <= V.graph.low_precision_codegen_ops:
155
+ return True
156
+
157
+ low_prec_analysis = RecordLowPrecisionOps(disallow_fp32_ops)
158
+
159
+ # Need to turn off upcasting to do analysis of whether we can turn it off
160
+ with (
161
+ config.patch("triton.codegen_upcast_to_fp32", False),
162
+ V.set_ops_handler(low_prec_analysis),
163
+ ):
164
+ prologue._body(*prologue.get_ranges())
165
+
166
+ return not low_prec_analysis.low_precision_numeric_op
.venv/lib/python3.10/site-packages/torch/_inductor/aoti_eager.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ from collections.abc import Callable
5
+ from pathlib import Path
6
+ from typing import Any, Optional
7
+ from unittest import mock
8
+
9
+ import torch
10
+ import torch._export
11
+ from torch._inductor.utils import is_cpu_device
12
+
13
+ from .runtime.runtime_utils import cache_dir
14
+
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+ def aoti_eager_cache_dir(namespace: str, device: str) -> Path:
20
+ return Path(cache_dir()) / "aoti_eager" / namespace / device
21
+
22
+
23
+ def aoti_eager_op_conf_lock(op_func_name_with_overload: str) -> Any:
24
+ # Avoid circular import
25
+ from torch._inductor.codecache import get_lock_dir, LOCK_TIMEOUT
26
+ from torch.utils._filelock import FileLock
27
+
28
+ op_conf_lock_file = f"{op_func_name_with_overload}.lock"
29
+ lock_dir = get_lock_dir()
30
+ return FileLock(os.path.join(lock_dir, op_conf_lock_file), timeout=LOCK_TIMEOUT)
31
+
32
+
33
+ def load_aoti_eager_cache(
34
+ ns: str, op_func_name_with_overload: str, device_type: str
35
+ ) -> list[Optional[dict[str, Any]]]:
36
+ device_kernel_cache = aoti_eager_cache_dir(ns, device_type)
37
+ op_conf = device_kernel_cache / f"{op_func_name_with_overload}.json"
38
+ if not op_conf.exists():
39
+ return []
40
+
41
+ try:
42
+ with aoti_eager_op_conf_lock(op_func_name_with_overload):
43
+ with open(op_conf) as f:
44
+ json_data = json.load(f)
45
+ for item in json_data:
46
+ # Get absolution path for kernel library
47
+ kernel_lib_abs_path = device_kernel_cache / item["kernel_path"]
48
+ item["kernel_path"] = kernel_lib_abs_path.as_posix()
49
+
50
+ # Check if the kernel library exists
51
+ if not kernel_lib_abs_path.exists():
52
+ return []
53
+
54
+ for metadata in item["meta_info"]:
55
+ if metadata.get("is_dynamic"):
56
+ raise NotImplementedError(
57
+ "Only support static shape for now"
58
+ )
59
+ if (
60
+ "device_type" in metadata
61
+ and metadata["device_type"] == "cpu"
62
+ ):
63
+ metadata["device_index"] = -1
64
+ for dtype_key in ["dtype", "dtype_value"]:
65
+ if dtype_key in metadata:
66
+ metadata[dtype_key] = getattr(
67
+ torch, metadata[dtype_key].split(".")[-1]
68
+ )
69
+ if "layout_value" in metadata:
70
+ metadata["layout_value"] = getattr(
71
+ torch, metadata["layout_value"].split(".")[-1]
72
+ )
73
+ if "memory_format_value" in metadata:
74
+ metadata["memory_format_value"] = getattr(
75
+ torch, metadata["memory_format_value"].split(".")[-1]
76
+ )
77
+
78
+ return json_data
79
+ except Exception as e:
80
+ err_msg = f"Failed to load aoti eager cache: {e}"
81
+ log.exception(err_msg)
82
+ return []
83
+
84
+
85
+ def supported_builtin_dtype_torch_dtype() -> dict[type, torch.dtype]:
86
+ return {int: torch.int32, float: torch.float, bool: torch.bool}
87
+
88
+
89
+ def supported_scalar_types() -> tuple[type, ...]:
90
+ type_to_torch_dtype = supported_builtin_dtype_torch_dtype()
91
+ return tuple(type_to_torch_dtype.keys())
92
+
93
+
94
+ def extract_tensor_metadata(dynamic: bool, input: torch.Tensor) -> dict[str, Any]:
95
+ metadata: dict[str, Any] = {}
96
+ metadata["is_dynamic"] = dynamic
97
+
98
+ assert isinstance(input, torch.Tensor)
99
+ metadata["device_type"] = f"{input.device.type}"
100
+ if is_cpu_device([input]):
101
+ metadata["device_index"] = -1
102
+ else:
103
+ metadata["device_index"] = input.device.index
104
+ metadata["dtype"] = f"{input.dtype}"
105
+ metadata["sizes"] = list(input.size())
106
+ metadata["strides"] = list(input.stride())
107
+ metadata["requires_grad"] = input.requires_grad
108
+ metadata["dispatch_key_set"] = torch._C._dispatch_keys(input).raw_repr()
109
+ return metadata
110
+
111
+
112
+ def extract_tensor_list_metadata(
113
+ dynamic: bool,
114
+ input: list[torch.Tensor],
115
+ ) -> dict[str, Any]:
116
+ metadata_list = []
117
+ for item in input:
118
+ assert isinstance(item, torch.Tensor)
119
+ metadata_list.append(extract_tensor_metadata(dynamic, item))
120
+
121
+ metadata: dict[str, Any] = {}
122
+ metadata["tensor_list"] = metadata_list
123
+ return metadata
124
+
125
+
126
+ def extract_scalar_metadata(device_type: str, input: Any) -> dict[str, Any]:
127
+ assert isinstance(input, supported_scalar_types())
128
+ metadata: dict[str, Any] = {}
129
+ metadata["is_dynamic"] = False
130
+ # Scalar tensor
131
+ metadata["device_type"] = device_type
132
+ metadata["device_index"] = -1 if device_type == "cpu" else 0
133
+ type_to_torch_dtype = supported_builtin_dtype_torch_dtype()
134
+ metadata["dtype"] = f"{type_to_torch_dtype[type(input)]}"
135
+ metadata["scalar_value"] = input
136
+ return metadata
137
+
138
+
139
+ def extract_string_metadata(input: str) -> dict[str, Any]:
140
+ assert isinstance(input, str)
141
+ metadata: dict[str, Any] = {}
142
+ metadata["string_value"] = input
143
+ return metadata
144
+
145
+
146
+ def extract_dtype_metadata(input: torch.dtype) -> dict[str, Any]:
147
+ assert isinstance(input, torch.dtype)
148
+ metadata: dict[str, Any] = {}
149
+ metadata["dtype_value"] = f"{input}"
150
+ return metadata
151
+
152
+
153
+ def extract_device_metadata(input: torch.device) -> dict[str, Any]:
154
+ assert isinstance(input, torch.device)
155
+ metadata: dict[str, Any] = {}
156
+ metadata["device_type_value"] = f"{input.type}"
157
+ metadata["device_index_value"] = input.index
158
+ return metadata
159
+
160
+
161
+ def extract_layout_metadata(input: torch.layout) -> dict[str, Any]:
162
+ assert isinstance(input, torch.layout)
163
+ metadata: dict[str, Any] = {}
164
+ metadata["layout_value"] = f"{input}"
165
+ return metadata
166
+
167
+
168
+ def aoti_compile_with_persistent_cache(
169
+ ns: str,
170
+ op_func_name_with_overload: str,
171
+ device_type: str,
172
+ dynamic: bool,
173
+ f: Callable[..., Any],
174
+ args: tuple[Any],
175
+ kwargs: dict[str, Any],
176
+ *,
177
+ dynamic_shapes: Optional[dict[str, Any]] = None,
178
+ options: Optional[dict[str, Any]] = None,
179
+ remove_runtime_assertions: bool = False,
180
+ disable_constraint_solver: bool = False,
181
+ ) -> str:
182
+ """
183
+ Compile the given function with persistent cache for AOTI eager mode.
184
+ """
185
+ assert not dynamic, "Only support static shape for now"
186
+ flattened_inputs = list(args) + list(kwargs.values())
187
+ if not all(
188
+ isinstance(
189
+ input,
190
+ (
191
+ supported_scalar_types(),
192
+ torch.Tensor,
193
+ list,
194
+ str,
195
+ torch.dtype,
196
+ torch.device,
197
+ torch.layout,
198
+ ),
199
+ )
200
+ for input in flattened_inputs
201
+ ):
202
+ err_msg = f"Unsupported input types: {flattened_inputs}"
203
+ log.exception(err_msg)
204
+ raise NotImplementedError(err_msg)
205
+
206
+ for input in flattened_inputs:
207
+ if isinstance(input, list) and not all(
208
+ isinstance(item, torch.Tensor) for item in input
209
+ ):
210
+ err_msg = f"_impl_with_aoti_compile encounters unsupported input types: {flattened_inputs}"
211
+ log.exception(err_msg)
212
+ raise NotImplementedError(err_msg)
213
+
214
+ persistent_cache = aoti_eager_cache_dir(ns, device_type)
215
+ if not persistent_cache.exists():
216
+ persistent_cache.mkdir(parents=True)
217
+
218
+ persistent_cache_lib = persistent_cache / "lib"
219
+ if not persistent_cache_lib.exists():
220
+ persistent_cache_lib.mkdir()
221
+
222
+ with mock.patch.dict(
223
+ os.environ,
224
+ {"TORCHINDUCTOR_CACHE_DIR": persistent_cache_lib.absolute().as_posix()},
225
+ ):
226
+ try:
227
+ kernel_lib_path = torch._export.aot_compile(
228
+ f,
229
+ args,
230
+ kwargs,
231
+ dynamic_shapes=dynamic_shapes,
232
+ remove_runtime_assertions=remove_runtime_assertions,
233
+ disable_constraint_solver=disable_constraint_solver,
234
+ # Some operations may have non-Tensor parameters like int, float, bool. These
235
+ # non-Tensor parameters will not be the input of the graph. Therefore, we do
236
+ # need to keep the same signature.
237
+ same_signature=False,
238
+ )
239
+ assert isinstance(kernel_lib_path, str)
240
+
241
+ kernel_metadata_items = []
242
+
243
+ for idx, input in enumerate(flattened_inputs):
244
+ if isinstance(input, torch.Tensor):
245
+ metadata = extract_tensor_metadata(dynamic, input)
246
+ elif isinstance(input, list):
247
+ assert all(isinstance(item, torch.Tensor) for item in input)
248
+ metadata = extract_tensor_list_metadata(dynamic, input)
249
+ elif isinstance(input, supported_scalar_types()):
250
+ metadata = extract_scalar_metadata(device_type, input)
251
+ elif isinstance(input, str):
252
+ metadata = extract_string_metadata(input)
253
+ elif isinstance(input, torch.dtype):
254
+ metadata = extract_dtype_metadata(input)
255
+ elif isinstance(input, torch.device):
256
+ metadata = extract_device_metadata(input)
257
+ elif isinstance(input, torch.layout):
258
+ metadata = extract_layout_metadata(input)
259
+ else:
260
+ raise NotImplementedError(f"Unsupported input type: {type(input)}")
261
+
262
+ metadata["arg_order"] = idx
263
+ kernel_metadata_items.append(metadata)
264
+
265
+ kernel_meta_info: dict[str, Any] = {}
266
+ kernel_meta_info["meta_info"] = kernel_metadata_items
267
+ kernel_meta_info["kernel_path"] = (
268
+ Path(kernel_lib_path).relative_to(persistent_cache).as_posix()
269
+ )
270
+
271
+ json_data = []
272
+ update_json = True
273
+ op_conf = persistent_cache / f"{op_func_name_with_overload}.json"
274
+ mode = "r" if op_conf.exists() else "w"
275
+ with aoti_eager_op_conf_lock(op_func_name_with_overload):
276
+ with open(op_conf, mode) as op_conf_file:
277
+ try:
278
+ json_data = json.load(op_conf_file)
279
+ except Exception:
280
+ json_data = []
281
+
282
+ assert isinstance(json_data, list)
283
+ for item in json_data:
284
+ assert isinstance(item, dict)
285
+ # Same kernel meta info already exists in the json file
286
+ if item["meta_info"] == kernel_metadata_items:
287
+ update_json = False
288
+ break
289
+
290
+ if update_json:
291
+ json_data.append(kernel_meta_info)
292
+ with open(op_conf, "w") as op_conf_file:
293
+ json.dump(json_data, op_conf_file, indent=4)
294
+
295
+ return kernel_lib_path
296
+ except Exception as e:
297
+ err_msg = f"Failed to compile {op_func_name_with_overload}: {e}"
298
+ log.exception(err_msg)
299
+ return ""
.venv/lib/python3.10/site-packages/torch/_inductor/async_compile.py ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import atexit
5
+ import functools
6
+ import json
7
+ import logging
8
+ import multiprocessing
9
+ import os
10
+ import re
11
+ import sys
12
+ from concurrent.futures import Future, ThreadPoolExecutor
13
+ from concurrent.futures.process import BrokenProcessPool
14
+ from functools import partial
15
+ from time import time, time_ns
16
+ from typing import Any, Optional, TYPE_CHECKING
17
+
18
+ import torch
19
+ from torch._dynamo.device_interface import get_registered_device_interfaces
20
+ from torch._dynamo.utils import (
21
+ counters,
22
+ dynamo_timed,
23
+ get_metrics_context,
24
+ set_feature_use,
25
+ )
26
+ from torch._inductor import config
27
+ from torch._inductor.codecache import (
28
+ _load_triton_kernel_from_source,
29
+ code_hash,
30
+ CodeCacheFuture,
31
+ CppCodeCache,
32
+ CppPythonBindingsCodeCache,
33
+ CUDACodeCache,
34
+ HalideCodeCache,
35
+ LambdaFuture,
36
+ ROCmCodeCache,
37
+ StaticAutotunerFuture,
38
+ torch_key,
39
+ )
40
+ from torch._inductor.compile_worker.subproc_pool import (
41
+ AnyPool,
42
+ SubprocException,
43
+ SubprocPool,
44
+ )
45
+ from torch._inductor.compile_worker.tracked_process_pool import (
46
+ TrackedProcessPoolExecutor,
47
+ )
48
+ from torch._inductor.compile_worker.utils import _async_compile_initializer
49
+ from torch._inductor.runtime.compile_tasks import (
50
+ _set_triton_ptxas_path,
51
+ _worker_compile_triton,
52
+ )
53
+ from torch._inductor.utils import clear_on_fresh_cache
54
+ from torch._inductor.virtualized import V
55
+ from torch._utils_internal import log_triton_builds
56
+ from torch.hub import _Faketqdm, tqdm
57
+ from torch.utils._ordered_set import OrderedSet
58
+ from torch.utils._triton import has_triton_package
59
+
60
+
61
+ if TYPE_CHECKING:
62
+ from collections.abc import Callable
63
+
64
+ from torch._inductor.runtime.hints import HalideMeta
65
+ from torch._inductor.runtime.triton_heuristics import CachingAutotuner
66
+
67
+ # timing metrics for time spent in the compilation
68
+ _cumulative_compile_time = 0.0
69
+ _t0: Optional[float] = None
70
+
71
+ kernel_code_log = torch._logging.getArtifactLogger(__name__, "kernel_code")
72
+
73
+ log = logging.getLogger(__name__)
74
+
75
+ _triton_kernel_metrics: Optional[dict[str, dict[str, Any]]] = None
76
+
77
+ size_hints_regex = re.compile(
78
+ r"size_hints=(\{.*?\})",
79
+ )
80
+
81
+
82
+ def pre_fork_setup():
83
+ """
84
+ Setup that must be done prior to forking with a process pool.
85
+ """
86
+ # ensure properties have been calculated before processes
87
+ # are forked
88
+ caching_device_properties()
89
+
90
+ # Computing the triton key can be slow. If we call it before fork,
91
+ # it will be cached for the forked subprocesses.
92
+ from torch._inductor.runtime.triton_compat import HAS_TRITON, triton_key
93
+
94
+ if HAS_TRITON:
95
+ triton_key()
96
+
97
+
98
+ def caching_device_properties():
99
+ for _, device_interface in get_registered_device_interfaces():
100
+ if device_interface.is_available():
101
+ device_interface.Worker.get_device_properties()
102
+
103
+
104
+ def _compile_start() -> None:
105
+ global _t0, _triton_kernel_metrics
106
+ if _t0 is None:
107
+ _t0 = time()
108
+ if _triton_kernel_metrics is None:
109
+ _triton_kernel_metrics = {}
110
+
111
+
112
+ def _compile_end() -> None:
113
+ global _cumulative_compile_time, _t0, _triton_kernel_metrics
114
+ if _t0 is not None:
115
+ t1 = time()
116
+ _cumulative_compile_time += t1 - _t0
117
+ _t0 = None
118
+ # print("CUMULATIVE COMPILE TIME", _cumulative_compile_time)
119
+ if _triton_kernel_metrics:
120
+ # Log triton kernel info
121
+ sorted_info = dict(sorted(_triton_kernel_metrics.items()))
122
+ torch._logging.trace_structured(
123
+ "artifact",
124
+ metadata_fn=lambda: {
125
+ "name": "triton_kernel_info",
126
+ "encoding": "json",
127
+ },
128
+ payload_fn=lambda: json.dumps(sorted_info),
129
+ )
130
+ _triton_kernel_metrics = None
131
+
132
+
133
+ def _add_triton_kernel_info(kernel_name: str, info: dict[str, Any]):
134
+ global _triton_kernel_metrics
135
+ # Must be called between _compile_start and _compile_end
136
+ if _triton_kernel_metrics is not None:
137
+ _triton_kernel_metrics[kernel_name] = info
138
+
139
+
140
+ _IS_WINDOWS = sys.platform == "win32"
141
+
142
+ log = logging.getLogger(__name__)
143
+
144
+ # Used to keep track of all process pools invoked so far.
145
+ _pool_set = OrderedSet[AnyPool]()
146
+
147
+
148
+ def shutdown_compile_workers() -> None:
149
+ """Shut down all outstanding compile-worker pools."""
150
+ for pool in _pool_set:
151
+ pool.shutdown()
152
+ AsyncCompile._ready_future = None
153
+ after_fork()
154
+
155
+
156
+ def after_fork():
157
+ """Reset pools to initial state without shutting them down"""
158
+ _pool_set.clear()
159
+ AsyncCompile.process_pool.cache_clear()
160
+
161
+
162
+ try:
163
+ os.register_at_fork(after_in_child=after_fork)
164
+ except AttributeError:
165
+ pass # register_at_fork does not exists on windows
166
+
167
+
168
+ def get_compile_threads() -> int:
169
+ """
170
+ Temporary for internal rollout. Assign config.compile_threads lazily and return it.
171
+ TODO: remove after rollout.
172
+ """
173
+ if config.compile_threads is None:
174
+ config.compile_threads = config.decide_compile_threads()
175
+ return config.compile_threads
176
+
177
+
178
+ @clear_on_fresh_cache
179
+ class CompiledTritonKernels:
180
+ """
181
+ In memory cache for storing compiled triton kernels.
182
+
183
+ Each triton kernel is keyed by the hash of its source code. Each value stored
184
+ in the cache is a return value of AsyncCompile.triton().
185
+
186
+ Currently, the cache stores Future objects, but it should be generalizable for any kernels.
187
+ """
188
+
189
+ _cache: dict[str, CodeCacheFuture] = {}
190
+
191
+ @staticmethod
192
+ def key(kernel_src: str):
193
+ """
194
+ Generates a cache key given a triton kernel's full source code.
195
+ This source includes the inductor meta, compilation metadata, the kernel itself, etc.
196
+ `kernel_src` should be the exact string passed to async_compile.triton()'s first argument.
197
+ """
198
+ # Hashes the kernel source with torch_key into a single hash key
199
+ return code_hash(kernel_src, extra=torch_key())
200
+
201
+ @staticmethod
202
+ def save(kernel_src: str, future: CodeCacheFuture):
203
+ """
204
+ Saves a compiled triton kernel to the cache.
205
+ TODO: We store a LambdaFuture as that's the callable returned by async_compile.triton,
206
+ but the real type we want to return here is actually an abstract triton kernel.
207
+
208
+ TODO: Source code here is not just the kernel's source code, but also includes the inductor preamble, etc.
209
+ so it could be less strict.
210
+ """
211
+ key = CompiledTritonKernels.key(kernel_src)
212
+ CompiledTritonKernels._cache[key] = future
213
+
214
+ @staticmethod
215
+ def get(kernel_src: str) -> Optional[CodeCacheFuture]:
216
+ key = CompiledTritonKernels.key(kernel_src)
217
+ return CompiledTritonKernels._cache.get(key, None)
218
+
219
+ @staticmethod
220
+ def cache_clear():
221
+ CompiledTritonKernels._cache = {}
222
+
223
+ @staticmethod
224
+ def remove_future(kernel_src: str) -> None:
225
+ key = CompiledTritonKernels.key(kernel_src)
226
+
227
+ # Delete the LambdaFuture if there is one
228
+ if key in CompiledTritonKernels._cache:
229
+ del CompiledTritonKernels._cache[key]
230
+
231
+
232
+ class AsyncCompile:
233
+ """
234
+ Utilities to compile in thread pools or subprocess pools (in the case of Triton).
235
+ """
236
+
237
+ _ready_future: Optional[Future[Any]] = None
238
+
239
+ def __init__(self) -> None:
240
+ pass
241
+
242
+ @staticmethod
243
+ @functools.lru_cache(1)
244
+ def pool() -> ThreadPoolExecutor:
245
+ assert get_compile_threads() > 1
246
+ return ThreadPoolExecutor(get_compile_threads())
247
+
248
+ @staticmethod
249
+ def _get_ready():
250
+ """No-op function to help mark when the subprocess pool is ready."""
251
+ return "ready"
252
+
253
+ @staticmethod
254
+ @functools.lru_cache(1)
255
+ def process_pool() -> AnyPool:
256
+ assert get_compile_threads() > 1
257
+ AsyncCompile._ready_future = None
258
+ log.info(
259
+ "Creating '%s' pool with %d workers",
260
+ config.worker_start_method,
261
+ get_compile_threads(),
262
+ )
263
+
264
+ pool: AnyPool
265
+ if config.worker_start_method == "subprocess":
266
+ # Wrapper around ProcessPoolExecutor forks in a new process we control
267
+ pool = SubprocPool(
268
+ get_compile_threads(), quiesce=config.quiesce_async_compile_pool
269
+ )
270
+ else:
271
+ if config.worker_start_method == "spawn":
272
+ # Avoid creating pools in the spawned subprocs themselves:
273
+ os.environ["TORCH_WARM_POOL"] = "0"
274
+ pre_fork_setup()
275
+ ctx = multiprocessing.get_context(config.worker_start_method)
276
+ pool = TrackedProcessPoolExecutor(
277
+ get_compile_threads(),
278
+ mp_context=ctx,
279
+ initializer=partial(_async_compile_initializer, os.getpid()),
280
+ )
281
+ # when this pool is created in a subprocess object, the normal exit handler
282
+ # doesn't run, and we need to register our own handler.
283
+ # exitpriority has to be high, because another one of the finalizers will
284
+ # kill the worker thread that sends the shutdown message to the workers...
285
+ multiprocessing.util.Finalize(None, pool.shutdown, exitpriority=sys.maxsize)
286
+
287
+ _pool_set.add(pool)
288
+ return pool
289
+
290
+ @classmethod
291
+ def warm_pool(cls) -> None:
292
+ if get_compile_threads() <= 1:
293
+ return
294
+ _compile_start()
295
+ # Pool is created on first access. Note for a SubprocPool, the sidecar process starts,
296
+ # but its ProcessPoolExecutor does not initialize until a wakeup() call or the first
297
+ # job is submitted.
298
+ cls.process_pool()
299
+ _compile_end()
300
+
301
+ @classmethod
302
+ def wait_pool_ready(cls, timeout=120) -> None:
303
+ cls.use_process_pool()
304
+ if cls._ready_future is not None:
305
+ cls._ready_future.result(timeout=timeout)
306
+
307
+ @classmethod
308
+ def submit(cls, task: Callable[..., Any]) -> Any:
309
+ if get_compile_threads() <= 1:
310
+ return task()
311
+ return cls.pool().submit(task)
312
+
313
+ @classmethod
314
+ def use_process_pool(cls):
315
+ if get_compile_threads() <= 1:
316
+ return False
317
+
318
+ # Proton instrumentation backend requires compilation to happen in the main
319
+ # process so it can instrument the Triton IR during JIT compilation.
320
+ # Force synchronous compilation when proton profiling is enabled.
321
+ if config.triton.proton_profiling:
322
+ return False
323
+
324
+ # Create a dummy job to check if the pool is ready. Submit it here instead of at
325
+ # pool creation so we don't launch the full pool of worker subprocesses until
326
+ # we're sure they're needed.
327
+ if not cls._ready_future:
328
+ cls._ready_future = cls.process_pool().submit(cls._get_ready)
329
+ return cls._ready_future.done()
330
+
331
+ @classmethod
332
+ def wakeup(cls) -> None:
333
+ """
334
+ If using a SubprocPool, signal the sidecar process to start up its
335
+ ProcessPoolExecutor.
336
+ """
337
+ if not cls.use_process_pool():
338
+ return
339
+ pool = cls.process_pool()
340
+ if isinstance(pool, SubprocPool):
341
+ pool.wakeup()
342
+
343
+ def triton(self, kernel_name: str, source_code: str, device_str: str = "cuda"):
344
+ """
345
+ Async_compile.triton is more complicated than the other backends because
346
+ we're trying to optimize compile time as much as possible for this hot callsite.
347
+
348
+ First of all, the function is cached by CompiledTritonKernels; if there's a kernel
349
+ already compiled, we grab it directly from the cache and return.
350
+
351
+ Otherwise, if we have multiple compile threads, we kick off triton compilations on each
352
+ worker process by giving it a kernel and source code to compile. The worker initializes
353
+ a CachingAutotuner, runs triton compilation, and pickles the kernel back to us.
354
+ We use TritonCompileResult to represent the objects being pickled back to us by each
355
+ worker.
356
+
357
+ Some maybe not obvious things that are pickled back to us:
358
+ - Most of the time, we can avoid sending back CachingAutotuner.fn and other metadata
359
+ and do not have to pay the cost of loading the triton kernel on the parent. But certain
360
+ cases, like coordesc tuning and dynamic_scale_rblock, require us to reload the function
361
+ in the parent lazily when we require it.
362
+ - The AutotuneCache, if enabled, is constructed on each worker per triton config
363
+ and pickled by to us via `CachingAutotuner.save_cache_hook`.
364
+ """
365
+ load_kernel = functools.partial(
366
+ _load_triton_kernel_from_source, kernel_name, source_code
367
+ )
368
+
369
+ def reload_kernel_in_parent():
370
+ # Benchmark how often this happens
371
+ with dynamo_timed("reload_kernel_in_parent"):
372
+ return load_kernel()
373
+
374
+ counters["inductor"]["async_compile_cache_miss"] += 1
375
+
376
+ kernel_code_log.info("Triton Kernel:\n%s", source_code)
377
+ _compile_start()
378
+
379
+ if os.environ.get("TRITON_INTERPRET", "0") == "1":
380
+ return getattr(
381
+ torch._inductor.codecache.PyCodeCache.load(source_code), kernel_name
382
+ )
383
+
384
+ is_parallel = self.use_process_pool()
385
+ set_feature_use("parallel_compile_post_warmup", is_parallel)
386
+
387
+ compile_id = torch._guards.CompileContext.current_compile_id()
388
+ is_backward = getattr(V.graph, "is_backward", False)
389
+
390
+ if (future := CompiledTritonKernels.get(source_code)) is not None:
391
+ counters["inductor"]["async_compile_cache_hit"] += 1
392
+ # Set reload_kernel_from_src properly based on source_code
393
+ if isinstance(future, StaticAutotunerFuture):
394
+ # Remove the future now that we've cache hit
395
+ CompiledTritonKernels.remove_future(source_code)
396
+ future.reload_kernel_from_src = reload_kernel_in_parent
397
+ if is_parallel:
398
+ return future
399
+ else:
400
+ return future.result()
401
+
402
+ # Cache miss
403
+ if is_parallel:
404
+ # We want to support changing these env vars after (and while) the
405
+ # process pool is running, so pass them to the subprocess to reset.
406
+ env_vars = ["TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"]
407
+ extra_env = {v: os.environ[v] for v in env_vars if v in os.environ}
408
+ extra_config = {
409
+ "use_static_triton_launcher": torch._inductor.config.use_static_triton_launcher
410
+ }
411
+
412
+ if len(torch._inductor.config.autotune_lookup_table) > 0:
413
+ m = size_hints_regex.search(source_code)
414
+ if m:
415
+ size_hints_str = m.group(1)
416
+ else:
417
+ size_hints_str = str(None)
418
+
419
+ triton_src = source_code.split("@triton.jit\n")[1]
420
+ from torch._inductor.runtime.triton_heuristics import (
421
+ generate_lookup_hash_from_source_code,
422
+ )
423
+
424
+ fn_hash = generate_lookup_hash_from_source_code(
425
+ size_hints_str, triton_src
426
+ )
427
+
428
+ if fn_hash in torch._inductor.config.autotune_lookup_table:
429
+ extra_config["autotune_lookup_table"] = { # type: ignore[assignment]
430
+ fn_hash: torch._inductor.config.autotune_lookup_table[fn_hash]
431
+ }
432
+
433
+ task = self.process_pool().submit(
434
+ _worker_compile_triton,
435
+ load_kernel,
436
+ extra_env,
437
+ extra_config,
438
+ )
439
+
440
+ def get_result() -> CachingAutotuner:
441
+ try:
442
+ kernel, elapsed_us = task.result()
443
+ except SubprocException as e:
444
+ raise e.with_name(kernel_name) from e
445
+
446
+ # Now that we've compiled, we should clear the future
447
+ # so it can't be used again
448
+ kernel.set_compile_info(compile_id, is_backward)
449
+ CompiledTritonKernels.remove_future(source_code)
450
+
451
+ kernel.restore_after_unpickle(old_values=None)
452
+
453
+ kernel.precompile(
454
+ warm_cache_only=False,
455
+ reload_kernel=reload_kernel_in_parent,
456
+ static_triton_bundle_key=CompiledTritonKernels.key(source_code),
457
+ )
458
+ info = kernel.autotune_cache_info or {}
459
+ info["compile_time_us"] = elapsed_us
460
+ _add_triton_kernel_info(kernel_name, info)
461
+ get_metrics_context().add_top_n(
462
+ "triton_kernel_compile_times_us", kernel_name, elapsed_us
463
+ )
464
+ return kernel
465
+
466
+ future = LambdaFuture(get_result, future=task)
467
+ CompiledTritonKernels.save(source_code, future)
468
+ return future
469
+ else:
470
+ with dynamo_timed(
471
+ "async_compile.precompile",
472
+ log_pt2_compile_event=True,
473
+ dynamo_compile_column_us="triton_compile_time_us",
474
+ log_waitcounter=True,
475
+ waitcounter_name_override="compile_triton",
476
+ ):
477
+ fail = None
478
+ try:
479
+ start_ns = time_ns()
480
+ _set_triton_ptxas_path()
481
+ kernel = load_kernel()
482
+ kernel.set_compile_info(compile_id, is_backward)
483
+ kernel.precompile(
484
+ warm_cache_only=False,
485
+ static_triton_bundle_key=CompiledTritonKernels.key(source_code),
486
+ )
487
+ elapsed_us = (time_ns() - start_ns) // 1000
488
+ get_metrics_context().add_top_n(
489
+ "triton_kernel_compile_times_us", kernel_name, elapsed_us
490
+ )
491
+ info = kernel.autotune_cache_info or {}
492
+ info["compile_time_us"] = elapsed_us
493
+ _add_triton_kernel_info(kernel_name, info)
494
+ return kernel
495
+ except Exception as e:
496
+ fail = str(e)
497
+ raise
498
+ finally:
499
+ log_triton_builds(fail=fail)
500
+
501
+ def multi_kernel(self, *args, **kwargs) -> Any:
502
+ from torch._inductor.codegen.multi_kernel import MultiKernelCall
503
+
504
+ # no need to call this in parallel since the sub-kernels are already parallel tasks
505
+ return MultiKernelCall(*args, **kwargs)
506
+
507
+ def size_hint_multi_kernel(self, *args, **kwargs) -> Any:
508
+ from torch._inductor.codegen.multi_kernel import SizeHintMultiKernelCall
509
+
510
+ return SizeHintMultiKernelCall(*args, **kwargs)
511
+
512
+ def cpp(self, source_code: str):
513
+ kernel_code_log.info("CPP Kernel:\n%s", source_code)
514
+ if get_compile_threads() <= 1:
515
+ return CppCodeCache.load(source_code).kernel
516
+ else:
517
+ get_result = CppCodeCache.load_async(source_code, submit_fn=self.submit)
518
+ return LambdaFuture(lambda: get_result().kernel)
519
+
520
+ def cpp_pybinding(self, argtypes: list[str], source_code: str):
521
+ kernel_code_log.info("CPP+Bindings Kernel:\n%s", source_code)
522
+ if get_compile_threads() <= 1:
523
+ return CppPythonBindingsCodeCache.load_pybinding(argtypes, source_code)
524
+ else:
525
+ get_result = CppPythonBindingsCodeCache.load_pybinding_async(
526
+ argtypes, source_code, submit_fn=self.submit
527
+ )
528
+ return LambdaFuture(get_result)
529
+
530
+ def cuda(self, source_code, dst_file_ext, aot_compile=False):
531
+ kernel_code_log.info("CUDA Kernel:\n%s", source_code)
532
+
533
+ def task():
534
+ if aot_compile:
535
+ # We rely on JITInductor to compile the CUDA code,
536
+ # so that we can load it into AOTInductor.
537
+ output_path, *_ = CUDACodeCache.compile(source_code, "o")
538
+ CUDACodeCache.aot_kernels_o.append(output_path)
539
+ return CUDACodeCache.load(source_code, dst_file_ext)[0]
540
+
541
+ return self.submit(task)
542
+
543
+ def rocm(
544
+ self,
545
+ source_code,
546
+ dst_file_ext,
547
+ aot_compile=False,
548
+ ):
549
+ kernel_code_log.info("ROCm Kernel:\n%s", source_code)
550
+
551
+ def task():
552
+ if aot_compile:
553
+ output_path, *_ = ROCmCodeCache.compile(source_code, dst_file_ext="o")
554
+ ROCmCodeCache.aot_kernels_o.append(output_path)
555
+ if config.rocm.generate_test_runner:
556
+ _ = ROCmCodeCache.compile(source_code, dst_file_ext="exe")
557
+ return ROCmCodeCache.load(source_code, dst_file_ext)[0]
558
+
559
+ return self.submit(task)
560
+
561
+ def halide(self, meta: HalideMeta, source_code: str):
562
+ kernel_code_log.info("Halide Kernel:\n%r\n%s", meta, source_code)
563
+ if get_compile_threads() <= 1:
564
+ return HalideCodeCache.generate_halide(meta, source_code)
565
+ else:
566
+ get_result = HalideCodeCache.generate_halide_async(
567
+ meta, source_code, submit_fn=self.submit
568
+ )
569
+ return LambdaFuture(get_result)
570
+
571
+ def cutedsl(self, kernel_name: str, source_code: str):
572
+ """
573
+ Compile CuteDSL (CUTLASS Python DSL) kernels.
574
+
575
+ Args:
576
+ kernel_name: Name of the kernel to be defined
577
+ source_code: Source code of the CuteDSL kernel, as a string
578
+
579
+ Note:
580
+ CuteDSL currently requires source files to do its compilation, there we
581
+ use the PyCodeCache to write the source code to a file and load it.
582
+ """
583
+ from torch._inductor.codegen.cutedsl.cutedsl_kernel import (
584
+ CuteDSLKernelWrapper,
585
+ MAIN_SUFFIX,
586
+ )
587
+
588
+ kernel_code_log.info("CuteDSL Kernel:\n%s", source_code)
589
+
590
+ def task():
591
+ key, path = torch._inductor.codecache.PyCodeCache.write(source_code)
592
+ mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path)
593
+
594
+ # Find our special entry point named function
595
+ main_func_name = f"{kernel_name}_{MAIN_SUFFIX}"
596
+ if not hasattr(mod, main_func_name):
597
+ available = [name for name in dir(mod) if callable(getattr(mod, name))]
598
+ raise RuntimeError(
599
+ f"Could not find CuteDSL main kernel function '{main_func_name}'. Available callables: {available}"
600
+ )
601
+
602
+ return CuteDSLKernelWrapper(getattr(mod, main_func_name), kernel_path=path)
603
+
604
+ if get_compile_threads() <= 1:
605
+ return task()
606
+ else:
607
+ future = self.submit(task)
608
+ return LambdaFuture(lambda: future.result())
609
+
610
+ def pallas(self, kernel_name: str, source_code: str):
611
+ """
612
+ Compile Pallas (JAX experimental) kernels.
613
+
614
+ Args:
615
+ kernel_name: Name of the kernel to be defined
616
+ source_code: Source code of the Pallas kernel, as a string
617
+
618
+ Note:
619
+ Pallas kernels are Python code that uses JAX and Pallas APIs.
620
+ We use the PyCodeCache to write the source code to a file and load it.
621
+ """
622
+ from torch._inductor.codegen.pallas import MAIN_SUFFIX, PallasKernelWrapper
623
+
624
+ kernel_code_log.info("Pallas Kernel:\n%s", source_code)
625
+
626
+ def task():
627
+ key, path = torch._inductor.codecache.PyCodeCache.write(source_code)
628
+ mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path)
629
+
630
+ # Find our special entry point named function
631
+ main_func_name = f"{kernel_name}_{MAIN_SUFFIX}"
632
+ if not hasattr(mod, main_func_name):
633
+ available = [name for name in dir(mod) if callable(getattr(mod, name))]
634
+ raise RuntimeError(
635
+ f"Could not find Pallas main kernel function '{main_func_name}'. Available callables: {available}"
636
+ )
637
+
638
+ return PallasKernelWrapper(getattr(mod, main_func_name), kernel_path=path)
639
+
640
+ if get_compile_threads() <= 1:
641
+ return task()
642
+ else:
643
+ future = self.submit(task)
644
+ return LambdaFuture(lambda: future.result())
645
+
646
+ def nv_universal_gemm(self, kernel_name: str, source_code: str):
647
+ """
648
+ Compile NVIDIA Universal GEMM kernels.
649
+
650
+ Args:
651
+ kernel_name: Name of the kernel to be defined
652
+ source_code: Source code of the kernel, as a string
653
+
654
+ Note:
655
+ NVIDIA Universal GEMM kernels are Python code that calls the cutlass_api library.
656
+ We use the PyCodeCache to write the source code to a file and load it.
657
+ """
658
+ from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_kernel import (
659
+ NVUniversalGemmKernelWrapper,
660
+ )
661
+ from torch._inductor.codegen.nv_universal_gemm.nv_universal_gemm_scheduling import (
662
+ MAIN_SUFFIX,
663
+ )
664
+
665
+ kernel_code_log.info("NVIDIA Universal GEMM Kernel:\n%s", source_code)
666
+
667
+ def task():
668
+ key, path = torch._inductor.codecache.PyCodeCache.write(source_code)
669
+ mod = torch._inductor.codecache.PyCodeCache.load_by_key_path(key, path)
670
+
671
+ # Find our special entry point named function
672
+ main_func_name = f"{kernel_name}_{MAIN_SUFFIX}"
673
+ if not hasattr(mod, main_func_name):
674
+ available = [name for name in dir(mod) if callable(getattr(mod, name))]
675
+ raise RuntimeError(
676
+ f"Could not find NVIDIA Universal GEMM main kernel function "
677
+ f"'{main_func_name}'. Available callables: {available}"
678
+ )
679
+
680
+ return NVUniversalGemmKernelWrapper(
681
+ getattr(mod, main_func_name), kernel_path=path
682
+ )
683
+
684
+ if get_compile_threads() <= 1:
685
+ return task()
686
+ else:
687
+ future = self.submit(task)
688
+ return LambdaFuture(lambda: future.result())
689
+
690
+ def wait(self, scope: dict[str, Any]) -> None:
691
+ if get_compile_threads() > 1:
692
+ with dynamo_timed(
693
+ "async_compile.wait",
694
+ log_pt2_compile_event=True,
695
+ dynamo_compile_column_us="triton_compile_time_us",
696
+ log_waitcounter=True,
697
+ waitcounter_name_override="compile_triton",
698
+ ):
699
+ self._wait_futures(scope)
700
+
701
+ _compile_end()
702
+
703
+ def _wait_futures(self, scope: dict[str, Any]) -> None:
704
+ kernels = {
705
+ key: value
706
+ for key, value in scope.items()
707
+ if isinstance(value, (Future, CodeCacheFuture))
708
+ }
709
+ pbar = tqdm(
710
+ total=len(kernels),
711
+ desc="Inductor Compilation",
712
+ disable=config.disable_progress,
713
+ delay=0,
714
+ )
715
+ for key, result in kernels.items():
716
+ if config.verbose_progress and not isinstance(pbar, _Faketqdm):
717
+ pbar.set_postfix_str(key)
718
+ try:
719
+ kernel = result.result()
720
+ scope[key] = kernel
721
+ except BrokenProcessPool as e:
722
+ raise RuntimeError(
723
+ "A compilation subprocess exited unexpectedly. This "
724
+ "is likely due to a crash. To facilitate debugging, "
725
+ "you can re-run with TORCHINDUCTOR_COMPILE_THREADS=1 "
726
+ "to cause compilation to occur in the main process."
727
+ ) from e
728
+ pbar.update(1)
729
+
730
+
731
+ def maybe_warm_pool() -> None:
732
+ if (
733
+ os.environ.get("TORCH_TNT_IN_USE", "0") == "1"
734
+ or os.environ.get("TORCH_WARM_POOL", "1") != "1"
735
+ # The subprocess pool is only used for the Triton backend
736
+ or not has_triton_package()
737
+ # Skip for fbcode. We have internal reports of usages inside multiprocessing
738
+ # pools that lead a multiplicative number of compile subprocesses.
739
+ or config.is_fbcode()
740
+ ):
741
+ return
742
+
743
+ AsyncCompile.warm_pool()
744
+ # TODO: This starts the SubprocPool's internal process pool as early as possible at
745
+ # the expense of creating a bunch of worker processes that might not be needed. We
746
+ # could start them lazily if we're willing to lose a small amount of compile time.
747
+ AsyncCompile.wakeup()
748
+
749
+
750
+ # On exit give the workers a chance to clean themselves up. Without this the
751
+ # resource_tracker can complain about leaked semaphores coming from the
752
+ # ProcessPoolExecutor:
753
+ # UserWarning: resource_tracker: There appear to be 5 leaked semaphore objects
754
+ # to clean up at shutdown
755
+ atexit.register(shutdown_compile_workers)
.venv/lib/python3.10/site-packages/torch/_inductor/await_utils.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ import weakref
4
+ from asyncio import AbstractEventLoop, Future
5
+ from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterator
6
+ from contextlib import contextmanager, ExitStack
7
+ from contextvars import Context
8
+ from typing import Any, Optional, Protocol, TypeVar
9
+
10
+ from torch.utils._ordered_set import OrderedSet
11
+
12
+
13
+ T = TypeVar("T")
14
+ TCoro = Generator[Any, None, T]
15
+
16
+ if sys.version_info >= (3, 11):
17
+
18
+ class TaskFactory(Protocol):
19
+ def __call__(
20
+ self,
21
+ __loop: AbstractEventLoop,
22
+ __factory: Coroutine[None, None, object] | Generator[None, None, object],
23
+ __context: Context | None = None,
24
+ /,
25
+ ) -> asyncio.futures.Future[object]: ...
26
+
27
+ TaskFactoryType = TaskFactory
28
+ else:
29
+ TaskFactoryType = Callable[[AbstractEventLoop, Generator[TCoro, None, T]], Future] # type: ignore[valid-type]
30
+
31
+
32
+ def await_sync(awaitable: Awaitable[T]) -> T:
33
+ with get_loop() as loop:
34
+ return loop.run_until_complete(awaitable)
35
+
36
+
37
+ @contextmanager
38
+ def get_loop(
39
+ always_create_new_loop: bool = False,
40
+ ) -> Iterator[AbstractEventLoop]:
41
+ try:
42
+ loop = asyncio.get_event_loop()
43
+ except RuntimeError as re:
44
+ if "There is no current event loop in thread" in str(re):
45
+ with _new_loop() as loop:
46
+ yield loop
47
+ return
48
+ else:
49
+ raise
50
+
51
+ @contextmanager
52
+ def _restore_loop(
53
+ loop: asyncio.AbstractEventLoop,
54
+ ) -> Iterator[None]:
55
+ try:
56
+ yield
57
+ finally:
58
+ asyncio.set_event_loop(loop)
59
+
60
+ @contextmanager
61
+ def _restore_running_loop() -> Iterator[None]:
62
+ loop_from_events = asyncio.events._get_running_loop()
63
+ asyncio.events._set_running_loop(None)
64
+ try:
65
+ yield
66
+ finally:
67
+ asyncio.events._set_running_loop(loop_from_events)
68
+
69
+ with ExitStack() as stack:
70
+ if loop.is_running():
71
+ stack.enter_context(_restore_running_loop())
72
+ stack.enter_context(_restore_loop(loop=loop))
73
+ loop = stack.enter_context(_new_loop(loop.get_task_factory())) # type: ignore[arg-type]
74
+ elif loop.is_closed():
75
+ loop = stack.enter_context(_new_loop()) # type: ignore[arg-type]
76
+ elif always_create_new_loop:
77
+ stack.enter_context(_restore_loop(loop=loop))
78
+ loop = stack.enter_context(_new_loop()) # type: ignore[arg-type]
79
+ yield loop
80
+
81
+
82
+ @contextmanager
83
+ def _new_loop(
84
+ task_factory: Optional[TaskFactoryType] = None,
85
+ ) -> Iterator[asyncio.AbstractEventLoop]:
86
+ loop = asyncio.new_event_loop()
87
+ tasks = _patch_loop(loop)
88
+
89
+ if task_factory:
90
+ # pyre-ignore[6]
91
+ loop.set_task_factory(task_factory) # type: ignore[arg-type]
92
+
93
+ asyncio.set_event_loop(loop)
94
+ try:
95
+ yield loop
96
+ finally:
97
+ try:
98
+ _cancel_all_tasks(loop, tasks)
99
+ finally:
100
+ asyncio.set_event_loop(None)
101
+ loop.close()
102
+
103
+
104
+ def _cancel_all_tasks(
105
+ loop: AbstractEventLoop,
106
+ tasks: OrderedSet[Future], # type: ignore[type-arg]
107
+ ) -> None:
108
+ to_cancel = [task for task in tasks if not task.done()]
109
+
110
+ if not to_cancel:
111
+ return
112
+
113
+ # pyre-fixme[1001]: Awaitable assigned to `task` is never awaited.
114
+ for task in to_cancel:
115
+ task.cancel()
116
+
117
+ # pyrefly: ignore [bad-argument-type]
118
+ loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))
119
+
120
+ for task in to_cancel:
121
+ if task.cancelled():
122
+ continue
123
+ if task.exception() is not None:
124
+ loop.call_exception_handler(
125
+ {
126
+ "message": "unhandled exception during asyncio.run() shutdown",
127
+ "exception": task.exception(),
128
+ "task": task,
129
+ }
130
+ )
131
+
132
+
133
+ def _patch_loop(loop: AbstractEventLoop) -> OrderedSet[Future]: # type: ignore[type-arg]
134
+ tasks: weakref.WeakSet[Future] = weakref.WeakSet() # type: ignore[type-arg]
135
+
136
+ task_factories: list[Optional[TaskFactoryType]] = [None]
137
+
138
+ def _set_task_factory(factory: Optional[TaskFactoryType]) -> None:
139
+ task_factories[0] = factory
140
+
141
+ def _get_task_factory() -> Optional[TaskFactoryType]:
142
+ return task_factories[0]
143
+
144
+ def _safe_task_factory(
145
+ loop: AbstractEventLoop,
146
+ coro: TCoro, # type: ignore[type-arg]
147
+ *,
148
+ context: Context | None = None,
149
+ ) -> asyncio.Future: # type: ignore[valid-type, type-arg]
150
+ task_factory = task_factories[0]
151
+ if task_factory is None:
152
+ if sys.version_info >= (3, 11):
153
+ # pyrefly: ignore [bad-argument-type]
154
+ task = asyncio.Task(coro, loop=loop, context=context)
155
+ else:
156
+ task = asyncio.Task(coro, loop=loop)
157
+ # pyre-ignore[16]: `Task` has no attribute `_source_traceback`.
158
+ if task._source_traceback: # type: ignore[attr-defined]
159
+ del task._source_traceback[ # type: ignore[attr-defined]
160
+ -1
161
+ ] # pragma: no cover # type: ignore[attr-defined]
162
+ else:
163
+ if sys.version_info >= (3, 11):
164
+ task = task_factory(loop, coro, context=context) # type: ignore[arg-type, call-arg, assignment]
165
+ else:
166
+ task = task_factory(loop, coro) # type: ignore[arg-type]
167
+ # `Union[Task[Any], Future[Any]]`.
168
+ tasks.add(task)
169
+ return task
170
+
171
+ # pyre-ignore[6]
172
+ loop.set_task_factory(_safe_task_factory) # type: ignore[method-assign, arg-type]
173
+ # pyre-ignore[8]
174
+ loop.set_task_factory = _set_task_factory # type: ignore[method-assign, assignment]
175
+ # pyre-ignore[8]
176
+ loop.get_task_factory = _get_task_factory # type: ignore[method-assign, assignment]
177
+
178
+ return tasks # type: ignore[return-value]
.venv/lib/python3.10/site-packages/torch/_inductor/bounds.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import operator
3
+ from collections.abc import Callable
4
+ from functools import partial
5
+ from typing import Any, Optional, Union
6
+
7
+ import sympy
8
+ from sympy import Expr
9
+
10
+ import torch
11
+ from torch.utils._sympy.value_ranges import (
12
+ bound_sympy,
13
+ SymPyValueRangeAnalysis,
14
+ ValueRanges,
15
+ )
16
+
17
+ from ..utils._sympy.functions import PowByNatural
18
+ from ..utils._sympy.numbers import int_oo
19
+ from .loop_body import InterpreterShim, LoopBody, LoopBodyBlock
20
+ from .ops_handler import DefaultHandler, ReductionType, StoreMode
21
+ from .utils import cache_on_self, dominated_nodes
22
+ from .virtualized import V
23
+
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+
28
+ class BoundVars:
29
+ """
30
+ Performs Value Range Analysis on LoopBody's fx graph by calling BoundVars.run()
31
+ It exposes the ranges of the nodes in the `bounds` variable
32
+
33
+ Note. A current limitation of this analysis is that it just works on a per-loop basis.
34
+ We should be able to propagate the bounds between across the whole graph. This may benefit
35
+ the case a bounded variable is returned by a kernel and fed into another.
36
+ """
37
+
38
+ def __init__(self, loop_body: LoopBody) -> None:
39
+ def upper_bound(v: Union[Expr, int]) -> int:
40
+ return bound_sympy(v).upper if isinstance(v, Expr) else v
41
+
42
+ self.loop_body = loop_body
43
+ self.replacement_vals = {
44
+ k: ValueRanges[Expr](0, upper_bound(v) - 1)
45
+ for k, v in loop_body.var_ranges.items()
46
+ }
47
+ # avoid computing these values, pessimistically assume that they are unbounded
48
+ self.unbounded_vars = dominated_nodes(
49
+ node
50
+ for node in self.loop_body.get_nodes()
51
+ if node.target in ["load", "reduction", operator.getitem]
52
+ or "masked_subblock" in node.target
53
+ )
54
+ # To access this variable call `get_bounds()`
55
+ self._bounds: dict[torch.fx.Node, ValueRanges[Expr]] = {}
56
+
57
+ def __repr__(self) -> str:
58
+ return (
59
+ f"{self.__class__.__name__}("
60
+ f"loop_body={self.loop_body},\n "
61
+ f"replacement_vals={self.replacement_vals}, \n"
62
+ f"unbounded_vars={self.unbounded_vars}, \n"
63
+ f"_bounds={self._bounds})"
64
+ )
65
+
66
+ @cache_on_self
67
+ def get_bounds(self) -> dict[torch.fx.Node, ValueRanges[Expr]]:
68
+ submodules = self.swap_submodules(self.loop_body.submodules)
69
+
70
+ # Initialize the environment with the unbounded variables
71
+ for node in self.unbounded_vars:
72
+ # we need to evaluate masked_subblock to recurse, and we need to set indirect values
73
+ if not isinstance(node.target, str) or (
74
+ "masked_subblock" not in node.target
75
+ and "set_indirect" not in node.target
76
+ ):
77
+ self._bounds[node] = ValueRanges[Expr].unknown()
78
+
79
+ with V.set_ops_handler(ValueRangeAnalysis()):
80
+ interpreter = InterpreterShim(self.loop_body.root_block.graph, submodules)
81
+ log.debug("get_bounds:\n%s", self.loop_body.root_block.graph)
82
+ interpreter.run(V.get_ops_handler(), initial_env=self._bounds)
83
+ return self._bounds
84
+
85
+ def swap_submodules(
86
+ self, submodules: dict[str, Callable[..., Any]]
87
+ ) -> dict[str, Callable[..., ValueRanges[Expr]]]:
88
+ result: dict[str, Callable[..., ValueRanges[Expr]]] = {}
89
+ for key in submodules:
90
+ if key == "get_index":
91
+ result[key] = self.get_index
92
+ elif "masked_subblock" in key:
93
+ subblock = self.loop_body.subblocks[key]
94
+ # The result within the lambda will reference to the final
95
+ # set of modules at the end of the for-loop as it stores a reference to it
96
+
97
+ # bind subblock in a function because python lambdas close over by reference
98
+ # moving the lambda out of make_fn would close over the reference to subblock,
99
+ # so all lambdas would have the same subblock reference that is the final
100
+ # subblock in the loop
101
+ def make_fn(
102
+ subblock: LoopBodyBlock,
103
+ ) -> Callable[[Any, Any], ValueRanges[Expr]]:
104
+ return lambda mask, value: self.masked_subblock(
105
+ subblock, self._bounds, mask, value, result
106
+ )
107
+
108
+ result[key] = make_fn(subblock)
109
+ elif "set_indirect" in key:
110
+ idx = int(key[len("set_indirect") :])
111
+ var = self.loop_body.indirect_vars[idx]
112
+ indirect = partial(self.set_indirect, var)
113
+ result[key] = indirect
114
+ else:
115
+ assert "scan" in key
116
+ result[key] = submodules[key]
117
+
118
+ return result
119
+
120
+ def masked_subblock(
121
+ self,
122
+ subblock: LoopBodyBlock,
123
+ env: dict[torch.fx.Node, ValueRanges[Expr]],
124
+ mask: Any,
125
+ value: Any,
126
+ submodules: dict[str, Callable[..., Any]],
127
+ ) -> ValueRanges[Expr]:
128
+ interp = InterpreterShim(subblock.graph, submodules)
129
+ interp.run(V.get_ops_handler(), initial_env=env)
130
+ output = [node for node in subblock.graph.nodes if node.target == "output"]
131
+ assert len(output) == 1
132
+ # dont bother unioning with value since the load from buffer will be
133
+ # pessimistically assumed to be inf anyway
134
+ return interp.env[output[0]]
135
+
136
+ def set_indirect(self, old: Expr, new: ValueRanges[Expr]) -> ValueRanges[Expr]:
137
+ assert isinstance(new, ValueRanges)
138
+ self.replacement_vals[old] = new
139
+ return new
140
+
141
+ def get_index(self, name: str) -> ValueRanges[Expr]:
142
+ expr = self.loop_body.indexing_exprs[name]
143
+ bound = self.replacement_vals.get(expr)
144
+ if bound is None:
145
+ bound = bound_sympy(expr, self.replacement_vals)
146
+ # The following assertion is true at the time of this writing
147
+ # We don't assert is as to not execute bound_sympy when bound is not None
148
+ # assert bound is None or bound == bound_sympy(expr, self.replacement_vals)
149
+ self.replacement_vals[name] = bound
150
+ return bound
151
+
152
+
153
+ class ValueRangeAnalysis(SymPyValueRangeAnalysis, DefaultHandler):
154
+ def __init__(self) -> None:
155
+ self.name = "ValueRangeAnalysis"
156
+ boolean_operators = (
157
+ "xor",
158
+ "logical_and",
159
+ "logical_or",
160
+ "logical_not",
161
+ )
162
+ for op in boolean_operators:
163
+ setattr(self, op, self.bool_handler)
164
+
165
+ @staticmethod
166
+ def bool_handler(*args: Any, **kwargs: Any) -> ValueRanges[Any]:
167
+ # just assuming bools can have both values
168
+ return ValueRanges(sympy.false, sympy.true) # type: ignore[arg-type]
169
+
170
+ def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
171
+ # many ops are unlikely to show up in optimizable indexing compute,
172
+ # so we dont have full coverage
173
+ return ValueRanges.unknown()
174
+
175
+ def load(self, name: str, index: sympy.Expr) -> ValueRanges[Any]:
176
+ return ValueRanges.unknown()
177
+
178
+ def store(
179
+ self, name: str, index: sympy.Expr, value: Any, mode: StoreMode = None
180
+ ) -> None:
181
+ return
182
+
183
+ def reduction(
184
+ self,
185
+ dtype: torch.dtype,
186
+ src_dtype: torch.dtype,
187
+ reduction_type: ReductionType,
188
+ value: Any,
189
+ ) -> ValueRanges[Any]:
190
+ return ValueRanges.unknown()
191
+
192
+ @classmethod
193
+ def index_expr(cls, index: Any, dtype: torch.dtype) -> ValueRanges[Any]:
194
+ assert isinstance(index, ValueRanges)
195
+ return cls.to_dtype(index, dtype)
196
+
197
+ @staticmethod
198
+ def to_dtype(
199
+ x: Any,
200
+ dtype: torch.dtype,
201
+ src_dtype: Optional[torch.dtype] = None,
202
+ use_compute_types: bool = True,
203
+ ) -> ValueRanges[Any]:
204
+ x = ValueRanges.wrap(x)
205
+
206
+ if dtype == torch.bool:
207
+ if x.is_singleton():
208
+ return ValueRanges.wrap(x.lower != 0)
209
+ elif x.is_bool:
210
+ return x
211
+ elif 0 not in x:
212
+ return ValueRanges.wrap(sympy.true)
213
+ else:
214
+ return ValueRanges(sympy.false, sympy.true)
215
+
216
+ def cast(x: Any, dtype: torch.dtype) -> sympy.Expr:
217
+ # dtype is int or float
218
+ if dtype.is_floating_point:
219
+ return sympy.Float(x)
220
+ else:
221
+ if x in (int_oo, -int_oo):
222
+ return x
223
+ try:
224
+ return sympy.Integer(x)
225
+ except TypeError:
226
+ # inf cannot be cast to Integer
227
+ return x
228
+
229
+ if x.is_bool:
230
+ if x.is_singleton():
231
+ val = 1 if x.lower else 0
232
+ return ValueRanges.wrap(cast(val, dtype))
233
+ else:
234
+ return ValueRanges(cast(0, dtype), cast(1, dtype))
235
+ else:
236
+ # int to float or float to int
237
+ return ValueRanges(cast(x.lower, dtype), cast(x.upper, dtype))
238
+
239
+ @staticmethod
240
+ def square(x: Any) -> ValueRanges[Any]:
241
+ return ValueRanges.convex_min_zero_map(x, lambda y: PowByNatural(y, 2))
242
+
243
+ @staticmethod
244
+ def neg(x: Any) -> ValueRanges[Any]:
245
+ return ValueRanges.decreasing_map(x, operator.neg)
246
+
247
+ # TODO: this is slightly inaccurate because truncdiv operates at integer
248
+ # precision, but we're going through float truediv which means we can
249
+ # potentially lose precision on the bounds
250
+ @classmethod
251
+ def truncdiv(cls, a: Any, b: Any) -> ValueRanges[Any]:
252
+ x = cls.truediv(a, b)
253
+ if x == ValueRanges.unknown():
254
+ return x
255
+
256
+ return cls.trunc(x)
257
+
258
+ @classmethod
259
+ def sub(cls, a: Any, b: Any) -> ValueRanges[Any]:
260
+ return cls.add(a, cls.neg(b))
.venv/lib/python3.10/site-packages/torch/_inductor/choices.py ADDED
@@ -0,0 +1,658 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import dataclasses
4
+ import typing
5
+ from typing import Any, Optional, TYPE_CHECKING, Union
6
+
7
+ import sympy
8
+
9
+ import torch
10
+ from torch._inductor.runtime.runtime_utils import next_power_of_2
11
+ from torch._inductor.scheduler import MixOrderReduction
12
+ from torch.utils._sympy.value_ranges import bound_sympy
13
+
14
+ from . import config
15
+ from .codecache import write_text
16
+ from .kernel_inputs import KernelInputs # noqa: TC001
17
+ from .kernel_template_choice import make_ktc_generator
18
+ from .metrics import get_metric_table, is_metric_table_enabled
19
+ from .runtime.hints import DeviceProperties, ReductionHint
20
+ from .scheduler import BaseSchedulerNode, Scheduler, WhyNoFuse
21
+ from .select_algorithm import ExternKernelChoice
22
+ from .template_heuristics import get_template_heuristic
23
+ from .template_heuristics.triton import (
24
+ BaseConfigHeuristic,
25
+ CPUConfigHeuristic,
26
+ CUDAConfigHeuristic,
27
+ MTIAConfigHeuristic,
28
+ ROCmConfigHeuristic,
29
+ XPUConfigHeuristic,
30
+ )
31
+ from .utils import _use_autotune_backend
32
+ from .virtualized import V
33
+
34
+
35
+ if TYPE_CHECKING:
36
+ from collections.abc import Generator
37
+ from functools import partial
38
+
39
+ from triton import Config as TritonConfig
40
+
41
+ from .codegen.common import KernelTemplate
42
+ from .codegen.simd_kernel_features import SIMDKernelFeatures
43
+ from .codegen.triton import TritonKernel
44
+ from .ir import ChoiceCaller
45
+ from .kernel_template_choice import KernelTemplateChoice
46
+
47
+ from torch.utils._ordered_set import OrderedSet # isort: skip
48
+
49
+
50
+ class Sortable(typing.Protocol):
51
+ """Anything that can be used as a list.sort() key (int/tuple/etc)"""
52
+
53
+ def __lt__(self, other: typing.Self) -> bool: ...
54
+
55
+
56
+ @dataclasses.dataclass
57
+ class FusionScore:
58
+ template_score: int
59
+ node_type_score: bool
60
+ memory_score: int
61
+ proximity_score: int
62
+
63
+ def __lt__(self, other):
64
+ """
65
+ node_type_score has higher priority than memory_score unless
66
+ the memory_score differs too much
67
+ """
68
+ threshold = 16
69
+ if self.template_score != other.template_score:
70
+ return self.template_score < other.template_score
71
+
72
+ if (
73
+ max(self.memory_score, other.memory_score)
74
+ > min(self.memory_score, other.memory_score) * threshold
75
+ ):
76
+ return self.memory_score < other.memory_score
77
+
78
+ return (self.node_type_score, self.memory_score, self.proximity_score) < (
79
+ other.node_type_score,
80
+ other.memory_score,
81
+ other.proximity_score,
82
+ )
83
+
84
+
85
+ class InductorChoices:
86
+ """
87
+ This class contains a collection of default heuristics that effect performance of our generated
88
+ code. We try to not put correctness requirements in this file.
89
+
90
+ You can override the choices made here by doing:
91
+
92
+ class MyHeuristics(InductorChoices):
93
+ ...
94
+
95
+ torch._inductor.virtualized.V.set_choices_handler(MyHeuristics())
96
+ """
97
+
98
+ def get_config_heuristics(
99
+ self, device_type: Optional[str] = "cuda"
100
+ ) -> BaseConfigHeuristic:
101
+ if device_type == "cuda":
102
+ if torch.version.hip is None:
103
+ return CUDAConfigHeuristic()
104
+ else:
105
+ return ROCmConfigHeuristic()
106
+ elif device_type == "xpu":
107
+ return XPUConfigHeuristic()
108
+ elif device_type == "cpu":
109
+ return CPUConfigHeuristic()
110
+ elif device_type == "mtia":
111
+ return MTIAConfigHeuristic()
112
+ else:
113
+ return BaseConfigHeuristic()
114
+
115
+ # Conv configs
116
+ def get_conv_configs(
117
+ self, device_type: Optional[str] = "cuda"
118
+ ) -> partial[Generator[TritonConfig, None, None]]:
119
+ conv_heuristics = self.get_config_heuristics(device_type)
120
+ return conv_heuristics.get_conv_configs()
121
+
122
+ # Flex attention configs
123
+ # TODO(coconutruben): break out flexattention/decode configs into the new retrieval mechanism
124
+ def get_flex_attention_fwd_configs(
125
+ self, head_dim: int, dtype: torch.dtype, device_type: Optional[str] = "cuda"
126
+ ) -> list[Any]:
127
+ flex_heuristics = self.get_config_heuristics(device_type)
128
+ return flex_heuristics.get_flex_attn_fwd_configs(head_dim, dtype)
129
+
130
+ def get_flex_attention_bwd_configs(
131
+ self, head_dim: int, dtype: torch.dtype, device_type: Optional[str] = "cuda"
132
+ ) -> list[Any]:
133
+ flex_heuristics = self.get_config_heuristics(device_type)
134
+ return flex_heuristics.get_flex_attn_bwd_configs(head_dim, dtype)
135
+
136
+ def get_flex_decode_configs(
137
+ self, head_dim: int, dtype: torch.dtype, device_type: Optional[str] = "cuda"
138
+ ) -> list[Any]:
139
+ flex_heuristics = self.get_config_heuristics(device_type)
140
+ return flex_heuristics.get_flex_decode_configs(head_dim, dtype)
141
+
142
+ def _finalize_template_configs(
143
+ self,
144
+ template_choices: dict[str, Generator[KernelTemplateChoice, None, None]],
145
+ kernel_inputs: KernelInputs,
146
+ templates: list[Union[KernelTemplate, ExternKernelChoice]],
147
+ op_name: str,
148
+ kwarg_overrides: Optional[dict[str, dict[str, Any]]] = None,
149
+ ) -> list[KernelTemplateChoice]:
150
+ """
151
+ This method can be subclassed to perform any override/modification of the choices.
152
+ The incoming parameters are cheap (generators), so you can do any overrides without
153
+ incurring too much cost. Override this method to customize the kernel template choices
154
+ before they are converted to ChoiceCaller objects, which is expensive on template codegen.
155
+
156
+ The full list of arguments are here to facilitate any overrides you may want to do,
157
+ as they can be used to start from scratch for each template if so desired.
158
+
159
+ Args:
160
+ template_choices: Dictionary mapping template UIDs to generators of KernelTemplateChoice objects
161
+ kernel_inputs: MMKernelInputs containing input tensor nodes and matrix indices
162
+ templates: List of template objects (KernelTemplate or ExternKernelChoice) in use
163
+ op_name: Operation name (e.g., "bmm", "baddbmm", "addmm")
164
+ kwarg_overrides: Optional dict of kwargs to override for each template heuristic
165
+
166
+ Returns:
167
+ Flattened list of KernelTemplateChoice objects across all templates
168
+ """
169
+ choices: list[KernelTemplateChoice] = []
170
+ for choice_gen in template_choices.values():
171
+ choices.extend(choice_gen)
172
+ return choices
173
+
174
+ def get_ktc(
175
+ self,
176
+ kernel_inputs: KernelInputs,
177
+ template: Union[KernelTemplate, ExternKernelChoice],
178
+ op_name: str,
179
+ kwarg_overrides: Optional[dict[str, Any]] = None,
180
+ ) -> Generator[KernelTemplateChoice, None, None]:
181
+ """
182
+ Utility to get the KernelTemplateChoice generator for a specific input.
183
+
184
+ This is a per template/op call, whereas get_template_configs is an op wide call (all templates).
185
+ Consider when overriding/using at which level you need to make decisions
186
+ """
187
+ # Extract device_type from kernel_inputs
188
+ device_type = kernel_inputs.device_type
189
+ assert device_type is not None, "get_ktc requires a valid device type"
190
+ # Extract template_name from the template object
191
+ template_name = template.uid
192
+
193
+ # Get the appropriate template-specific heuristic
194
+ heuristic = get_template_heuristic(template_name, device_type, op_name)
195
+ cs = heuristic.get_template_configs(
196
+ kernel_inputs,
197
+ op_name,
198
+ )
199
+ # adjust the kernel inputs to the template-specific heuristic, if needed
200
+ # default here is to just return the kernel_inputs as is
201
+ inputs_val = heuristic.adjust_kernel_inputs(kernel_inputs, op_name)
202
+ extra_kwargs = heuristic.get_extra_kwargs(kernel_inputs, op_name)
203
+ # Create KernelTemplateChoice generator using the moved function
204
+ overrides = kwarg_overrides or {}
205
+ return make_ktc_generator(
206
+ template=template,
207
+ cs=cs,
208
+ extra_kwargs=extra_kwargs,
209
+ overrides=overrides,
210
+ layout=kernel_inputs.output_layout(),
211
+ inputs=inputs_val,
212
+ )
213
+
214
+ def _need_to_fix_layout(
215
+ self,
216
+ adjusted_choices: list[KernelTemplateChoice],
217
+ op_name: str,
218
+ ) -> bool:
219
+ """
220
+ Check if we need to fix the layout instead of keeping it flexible
221
+
222
+ Args:
223
+ ktc: KernelTemplateChoice object
224
+
225
+ Returns:
226
+ True if we need to fix the layout, False otherwise
227
+ """
228
+ # TODO: debug and fix
229
+ # NOTE: on mps, we see issues with flexible layouts on baddmm. This check just makes sure
230
+ # that for mps, everything stays as it was before this optimization
231
+ if len(adjusted_choices) > 0:
232
+ if adjusted_choices[0].inputs.device_type == "mps" and op_name not in [
233
+ "mm",
234
+ "addmm",
235
+ ]:
236
+ return True
237
+
238
+ # Since the following backends are not using get_mm_configs yet through the singular call,
239
+ if not (config.max_autotune or config.max_autotune_gemm):
240
+ # no danger of using other backends than ATEN
241
+ if not config.max_autotune_allow_flexible_layouts and op_name not in [
242
+ # The historical implementation for mm and addmm allowed had flexible layouts in the
243
+ # not max-autotune world
244
+ "mm",
245
+ "addmm",
246
+ ]:
247
+ # TODO: deprecate this by migrating users to the new behavior
248
+ return True
249
+ return False
250
+
251
+ if not config.max_autotune_allow_flexible_layouts:
252
+ # we always need to fix the layout
253
+ return True
254
+
255
+ # Since the following backends are not using get_template_configs yet through the singular call,
256
+ # we don't know if they are a valid choice or not. Instead, just skip the optimization
257
+ # defensively.
258
+ # TODO(coconutruben): remove this once CPP,CK,CUTLASS are supported
259
+ if _use_autotune_backend("CUTLASS"):
260
+ return True
261
+ if _use_autotune_backend("CK") or _use_autotune_backend("CKTILE"):
262
+ return True
263
+ if _use_autotune_backend("CPP"):
264
+ return True
265
+ return any(
266
+ not isinstance(ktc.template, ExternKernelChoice) for ktc in adjusted_choices
267
+ )
268
+
269
+ def get_template_configs(
270
+ self,
271
+ kernel_inputs: KernelInputs,
272
+ templates: list[Union[KernelTemplate, ExternKernelChoice]],
273
+ op_name: str,
274
+ kwarg_overrides: Optional[dict[str, dict[str, Any]]] = None,
275
+ ) -> list[ChoiceCaller]:
276
+ """
277
+ Get list of ChoiceCallers for MM templates using template-specific heuristics.
278
+
279
+ Args:
280
+ kernel_inputs: MMKernelInputs containing input tensor nodes and matrix indices
281
+ layout: Output layout
282
+ templates: List of template objects (KernelTemplate or ExternKernelChoice)
283
+ op_name: Operation name (e.g., "bmm", "baddbmm", "addmm", "mm_plus_mm")
284
+ kwarg_overrides: Optional dict of kwargs to override for each template heuristic,
285
+ indexed by template.uid. These only override the per config kwargs, not the extra kwargs
286
+ Returns:
287
+ List of ChoiceCaller objects from the templates
288
+ """
289
+ if kwarg_overrides is None:
290
+ kwarg_overrides = {}
291
+ input_tensors = kernel_inputs.nodes()
292
+ if len(input_tensors) < 2:
293
+ raise ValueError(f"Need at least 2 input tensors, got {len(input_tensors)}")
294
+ layout = kernel_inputs.output_layout()
295
+ # First pass: Create dict of template.uid to generator of KernelTemplateChoice objects
296
+ template_choices = {}
297
+ for template in templates:
298
+ template_choices[template.uid] = self.get_ktc(
299
+ kernel_inputs,
300
+ template,
301
+ op_name,
302
+ kwarg_overrides.get(template.uid, {}),
303
+ )
304
+
305
+ # Second pass: Adjust the template choices
306
+ adjusted_choices = self._finalize_template_configs(
307
+ template_choices,
308
+ kernel_inputs,
309
+ templates,
310
+ op_name,
311
+ kwarg_overrides,
312
+ )
313
+ # Layout optimization: if all choices are ExternKernelChoice and layout is FixedLayout, convert to FlexibleLayout
314
+ if self._need_to_fix_layout(adjusted_choices, op_name):
315
+ layout = kernel_inputs.output_layout(flexible=False)
316
+ for ktc in adjusted_choices:
317
+ ktc.layout = layout
318
+ # for good measure, delete the cached ChoiceCaller from the ktc if it existed.
319
+ # ExternKernelChoice are cheap to generate
320
+ if hasattr(ktc, "_choice"):
321
+ del ktc._choice
322
+ # Third pass: Convert to ChoiceCaller objects
323
+ return [ktc.choice for ktc in adjusted_choices if ktc.choice is not None]
324
+
325
+ def triton_kernel_kwargs(
326
+ self,
327
+ kernel_cls: type[TritonKernel],
328
+ features: SIMDKernelFeatures,
329
+ groups: list[sympy.Expr],
330
+ kernel_kwargs: dict[str, Any],
331
+ ) -> dict[str, Any]:
332
+ """Hook to change the kwargs passed to TritonKernel, used to apply fixed configurations"""
333
+ return kernel_kwargs
334
+
335
+ @staticmethod
336
+ def should_use_cooperative_reduction(features: SIMDKernelFeatures) -> bool:
337
+ """Heuristic to decide if a cooperative reduction should be used."""
338
+ if config.triton.force_cooperative_reductions:
339
+ return True
340
+ if (
341
+ not config.triton.cooperative_reductions
342
+ or V.graph.get_current_device_or_throw().type == "cpu"
343
+ ):
344
+ return False
345
+
346
+ xhint = V.graph.sizevars.optimization_hint(features.numel, fallback=2)
347
+ if xhint <= 8:
348
+ threshold = 32768 * xhint
349
+ elif xhint <= 16:
350
+ threshold = 2097152
351
+ else:
352
+ return False
353
+ # TODO(jansel): should this default on for dynamic shapes?
354
+ # TODO(laith) What if hint(features.reduction_numel) >= threshold ?
355
+ # shall we compare hints instead
356
+ return V.graph.sizevars.statically_known_geq(
357
+ features.reduction_numel, threshold
358
+ )
359
+
360
+ @staticmethod
361
+ def should_use_persistent_reduction(
362
+ features: SIMDKernelFeatures, cooperative_reduction: bool
363
+ ) -> bool:
364
+ """
365
+ Heuristic to decide if a persistent reduction should be used.
366
+ """
367
+ if not config.triton.persistent_reductions:
368
+ return False
369
+ threshold = {
370
+ ReductionHint.INNER: 1024,
371
+ }.get(features.get_reduction_hint(), 64)
372
+
373
+ if features.get_reduction_hint() not in (
374
+ ReductionHint.INNER,
375
+ ReductionHint.OUTER_TINY,
376
+ ):
377
+ bounds = bound_sympy(features.reduction_numel)
378
+ lower = bounds.lower
379
+ upper = bounds.upper
380
+
381
+ if not all(
382
+ (
383
+ (isinstance(bound, int) or bound.is_constant())
384
+ and not torch.utils._sympy.numbers.is_infinite(bound)
385
+ )
386
+ for bound in (lower, upper)
387
+ ):
388
+ return False
389
+
390
+ lower = next_power_of_2(int(lower))
391
+ upper = next_power_of_2(int(upper))
392
+
393
+ # If we are are coalescing on xblock (not ReductionHint.INNER) and this is not a tiny kernel
394
+ # (not ReductionHint.OUTER_TINY), do not use persistent reduction if it induces tile
395
+ # quantization. Persistent reduction forces rblock == rnumel, if the bounds between lower
396
+ # and upper are large, for the lower values we will be masking off large % of read/writes,
397
+ # when we could expand the coalescing xblock instead.
398
+ if lower != upper:
399
+ return False
400
+
401
+ if cooperative_reduction:
402
+ # The RSPLIT of cooperative reductions means each thread block is operating on fewer elements
403
+ # The default fallback will be used if optimizations hint is not provided. The default fallback
404
+ # is >> 32.
405
+ threshold *= 32 // min(
406
+ V.graph.sizevars.optimization_hint(features.numel), 32
407
+ )
408
+
409
+ # If multi_kernel is enabled, we do more aggressive persistent reduction.
410
+ # This may result in some persistent reductions slower than the
411
+ # corresponding non-persistent reductions. MultiKernel will do benchmarking
412
+ # to pick the faster one.
413
+ if config.triton.multi_kernel:
414
+ threshold *= 16
415
+
416
+ return V.graph.sizevars.statically_known_leq(
417
+ features.reduction_numel, threshold
418
+ ) # type: ignore[arg-types]
419
+
420
+ @staticmethod
421
+ def reduction_split_factor(
422
+ device: torch.device,
423
+ reduction_numel_hint: int,
424
+ numel_hint: int,
425
+ inner_reduction: bool,
426
+ ) -> int:
427
+ """Heuristic to decide the RSPLIT used for split reductions.
428
+ When a reduction has a small number of outputs there is not enough parallelism,
429
+ so we will do the reduction in two phases."""
430
+ props = DeviceProperties.create(device)
431
+ num_sm = props.multi_processor_count
432
+ warp_size = props.warp_size if props.warp_size is not None else 32
433
+ max_threads_per_sm = (
434
+ props.max_threads_per_multi_processor
435
+ if props.max_threads_per_multi_processor is not None
436
+ else 2048
437
+ )
438
+ min_elements_per_thread = warp_size
439
+ max_elements_per_thread = 512
440
+ threads_per_sm = max_threads_per_sm
441
+ min_elements_per_device = min_elements_per_thread * num_sm * threads_per_sm
442
+ max_elements_per_device = max_elements_per_thread * num_sm * threads_per_sm
443
+ num_warps = 8
444
+ num_threads = warp_size * num_warps
445
+
446
+ if inner_reduction:
447
+ # do heuristics that's close to eager mode for split inner reduction
448
+ # we leak reduction autotune configs here, and will need to refactor to avoid this later
449
+ if numel_hint >= 2 * num_sm: # don't split if there are enough outputs
450
+ return 1
451
+ if reduction_numel_hint <= 8192:
452
+ return 1
453
+ if reduction_numel_hint * numel_hint <= min_elements_per_device:
454
+ split_size = min_elements_per_thread
455
+ elif reduction_numel_hint * numel_hint < max_elements_per_device:
456
+ target_blocks = num_sm * threads_per_sm // (2 * num_threads)
457
+ blocks_per_output = (target_blocks + numel_hint - 1) // numel_hint
458
+ tmp_split_size = (
459
+ reduction_numel_hint + num_threads * blocks_per_output - 1
460
+ ) // (num_threads * blocks_per_output)
461
+ divisors = sympy.divisors(reduction_numel_hint)
462
+ closest = min(divisors, key=lambda x: abs(x - tmp_split_size))
463
+ if abs(closest - tmp_split_size) < 30:
464
+ # prefer even splits, but never smalle than min_elements_per_thread
465
+ split_size = max(closest, min_elements_per_thread)
466
+ else:
467
+ split_size = tmp_split_size
468
+ else:
469
+ divisors = sympy.divisors(reduction_numel_hint)
470
+ closest = min(divisors, key=lambda x: abs(x - max_elements_per_thread))
471
+ if abs(closest - max_elements_per_thread) < 50:
472
+ # prefer even splits
473
+ split_size = closest
474
+ else:
475
+ split_size = max_elements_per_thread
476
+ return (reduction_numel_hint + split_size * num_threads - 1) // (
477
+ split_size * num_threads
478
+ )
479
+ else:
480
+ # TODO the best heuristic currently has XBLOCK (corresponding to numel_hint) 128
481
+ # extend to even smaller number of outputs
482
+ rvals_per_thread = 4 # comes from heuristics, refactor to not leak here
483
+ xvals_per_block = 128
484
+ xblocks = (numel_hint + xvals_per_block - 1) // xvals_per_block
485
+ if reduction_numel_hint * numel_hint < min_elements_per_device:
486
+ split_size = min_elements_per_thread
487
+ elif reduction_numel_hint * numel_hint < max_elements_per_device:
488
+ target_blocks = num_sm * threads_per_sm // (num_threads)
489
+ target_blocks = (target_blocks + xblocks - 1) // xblocks
490
+ tmp_split_size = (
491
+ reduction_numel_hint + rvals_per_thread * target_blocks - 1
492
+ ) // (rvals_per_thread * target_blocks)
493
+ divisors = sympy.divisors(reduction_numel_hint)
494
+ closest = min(divisors, key=lambda x: abs(x - tmp_split_size))
495
+ if abs(tmp_split_size - closest) < 20:
496
+ split_size = max(closest, min_elements_per_thread)
497
+ else:
498
+ split_size = tmp_split_size
499
+ else:
500
+ divisors = sympy.divisors(reduction_numel_hint)
501
+ closest = min(divisors, key=lambda x: abs(x - max_elements_per_thread))
502
+ if abs(closest - max_elements_per_thread) < 50:
503
+ # prefer even splits
504
+ split_size = closest
505
+ else:
506
+ split_size = max_elements_per_thread
507
+
508
+ return (reduction_numel_hint + rvals_per_thread * split_size - 1) // (
509
+ rvals_per_thread * split_size
510
+ )
511
+
512
+ @staticmethod
513
+ def can_fuse(
514
+ scheduler: Scheduler,
515
+ node1: BaseSchedulerNode,
516
+ node2: BaseSchedulerNode,
517
+ shared_data_score: int,
518
+ ) -> bool:
519
+ """
520
+ Heuristics to prevent fusion applied to both horizontal and vertical fusions. Heuristics here should not
521
+ be needed for correctness and tweaking them may yield additional performance.
522
+
523
+ See also some related heuristics that can be changed via config:
524
+ - config.triton.tiling_prevents_pointwise_fusion
525
+ - config.triton.tiling_prevents_reduction_fusion
526
+ - config.aggressive_fusion (will cause this function to be called more times)
527
+ """
528
+ if shared_data_score == 0 and (
529
+ not config.aggressive_fusion or node1.is_reduction() or node2.is_reduction()
530
+ ):
531
+ if is_metric_table_enabled("fusion_failure_due_to_indexing_mismatch"):
532
+ common_buf_names: OrderedSet[str] = (
533
+ node1.read_writes.buffer_names() & node2.read_writes.buffer_names()
534
+ )
535
+ if len(common_buf_names) > 0:
536
+ get_metric_table("fusion_failure_due_to_indexing_mismatch").add_row(
537
+ # pyrefly: ignore [bad-argument-type]
538
+ lambda: {
539
+ "pre_grad_graph_id": V.graph.graph_id,
540
+ "post_grad_graph_id": V.graph.post_grad_graph_id,
541
+ "node1_name": node1.get_name(),
542
+ "node2_name": node2.get_name(),
543
+ "node1_debug_str": write_text(node1.debug_str()),
544
+ "node2_debug_str": write_text(node2.debug_str()),
545
+ "common_buffer_names": list(common_buf_names), # type: ignore[dict-item]
546
+ "failure_reason": scheduler.decide_fusion_fail_reason(
547
+ node1, node2, common_buf_names
548
+ ),
549
+ }
550
+ )
551
+
552
+ WhyNoFuse(node1, node2)("no shared data due to indexing mismatch")
553
+ return False
554
+ WhyNoFuse(node1, node2)("no shared data")
555
+ return False # heuristic not needed for correctness
556
+
557
+ if (
558
+ not node1.is_foreach()
559
+ and not node2.is_foreach()
560
+ and len(node1.get_nodes()) + len(node2.get_nodes()) > config.max_fusion_size
561
+ ):
562
+ WhyNoFuse(node1, node2)("exceeds max fusion")
563
+ return False # heuristic not needed for correctness
564
+
565
+ if scheduler.can_fusion_increase_peak_memory(node1, node2):
566
+ WhyNoFuse(node1, node2)("Fusion will increase peak memory")
567
+ return False
568
+
569
+ if (
570
+ config.max_fusion_unique_io_buffers is not None
571
+ and scheduler.fusion_prevent_too_many_reads_and_writes(
572
+ node1,
573
+ node2,
574
+ config.max_fusion_unique_io_buffers,
575
+ )
576
+ ):
577
+ WhyNoFuse(node1, node2)("fusion_prevent_too_many_reads_and_writes")
578
+ return False
579
+
580
+ return True
581
+
582
+ @staticmethod
583
+ def can_fuse_vertical(
584
+ scheduler: Scheduler,
585
+ node1: BaseSchedulerNode,
586
+ node2: BaseSchedulerNode,
587
+ shared_data_score: int,
588
+ ) -> bool:
589
+ """Hook for heuristics to prevent vertical (producer/consumer) fusions"""
590
+ return True
591
+
592
+ @staticmethod
593
+ def can_fuse_horizontal(
594
+ scheduler: Scheduler,
595
+ node1: BaseSchedulerNode,
596
+ node2: BaseSchedulerNode,
597
+ shared_data_score: int,
598
+ ) -> bool:
599
+ """Hook for heuristics to prevent horizontal (consumer/consumer) fusions"""
600
+ if MixOrderReduction.can_fuse(node1, node2):
601
+ # For mix order reduction, we disregard shared data or
602
+ # distance.
603
+ return True
604
+ if shared_data_score < config.score_fusion_memory_threshold:
605
+ WhyNoFuse(node1, node2)("score_fusion_memory_threshold")
606
+ return False
607
+ if scheduler.are_long_distant_nodes(node1, node2):
608
+ WhyNoFuse(node1, node2)(
609
+ "Nodes are too far away. Fusing them may increase peak memory."
610
+ )
611
+ return False
612
+ return True
613
+
614
+ @staticmethod
615
+ def score_fusion(
616
+ scheduler: Scheduler,
617
+ node1: BaseSchedulerNode,
618
+ node2: BaseSchedulerNode,
619
+ ) -> Sortable:
620
+ """
621
+ Assign a score (higher comes first) to the fusion of node1 and node2.
622
+ When different fusions conflict with each other, this is the way we
623
+ decide what order to run them in.
624
+
625
+ Our current score is based on:
626
+ - The type of fusion (template/reduction/etc)
627
+ - Estimate of the saved memory operations
628
+ - Fusions closer together in original graph order
629
+ """
630
+
631
+ memory_score, is_mix_order_reduction = typing.cast(
632
+ tuple[int, bool],
633
+ scheduler.score_fusion_memory(
634
+ node1, node2, return_is_mix_order_reduction=True
635
+ ),
636
+ )
637
+ proximity_score = -max(
638
+ abs(node1.min_order - node2.max_order),
639
+ abs(node2.min_order - node1.max_order),
640
+ )
641
+
642
+ # prologue fusion always last
643
+ if node2.is_template():
644
+ template_score = 0
645
+ else:
646
+ template_score = 1 + (
647
+ (node1.is_template() == config.epilogue_fusion_first)
648
+ and memory_score > 0
649
+ )
650
+
651
+ type_score = node1.is_reduction() == node2.is_reduction() and memory_score > 0
652
+
653
+ return FusionScore(
654
+ template_score,
655
+ type_score,
656
+ memory_score,
657
+ proximity_score,
658
+ )
.venv/lib/python3.10/site-packages/torch/_inductor/codecache.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/aoti_hipify_utils.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import torch
4
+
5
+
6
+ # It is not a good idea to directly apply hipify_torch to codegen, which will be vulnerable to cases like:
7
+ # "...
8
+ # from ..codecache import CudaKernelParamCache
9
+ # ..."
10
+ # In such cases, we do not need to hipify_torch the original class/file name in codegen/codecache
11
+
12
+
13
+ def maybe_hipify_code_wrapper(source_codes: str, force_hipify: bool = False) -> str:
14
+ if torch.version.hip is None and not force_hipify:
15
+ return source_codes
16
+
17
+ try:
18
+ from torch.utils.hipify.hipify_python import PYTORCH_MAP, PYTORCH_TRIE
19
+ except ImportError:
20
+ # hipify not available for non-AMD builds
21
+ return source_codes
22
+
23
+ def c2_repl(m: re.Match[str]) -> object:
24
+ return PYTORCH_MAP[m.group(0)]
25
+
26
+ # We need to redefine RE_PYTORCH_PREPROCESSOR here since in hipify_torch,
27
+ # it will apply positive lookbehind (?<=\W) to the pattern to avoid matching
28
+ # keyword at the beginning of code line. However, this can happen in codegen,
29
+ # which will cause the pattern to not match.
30
+
31
+ # Note that lookahead (?=\W) is still needed to keep hipification idomponent, for example
32
+ # we need to skip replacing "getStreamFromExternal" in "getStreamFromExternalMasqueradingAsCUDA"
33
+ RE_PYTORCH_PREPROCESSOR = re.compile(rf"({PYTORCH_TRIE.export_to_regex()})(?=\W)")
34
+
35
+ source_codes = RE_PYTORCH_PREPROCESSOR.sub(c2_repl, source_codes) # type: ignore[arg-type]
36
+ return source_codes
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/block_analysis.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import functools
3
+ import textwrap
4
+ from typing import Optional
5
+
6
+ import sympy
7
+ from sympy import Expr, Symbol
8
+
9
+ from torch.utils._ordered_set import OrderedSet
10
+ from torch.utils._sympy.functions import FloorDiv, ModularIndexing
11
+
12
+ from ..utils import sympy_dot, sympy_subs
13
+ from ..virtualized import V
14
+
15
+
16
+ class BlockPatternMatcher:
17
+ """
18
+ Matches block indexing expressions.
19
+ """
20
+
21
+ _indexing_wild_signed_int = functools.partial(
22
+ sympy.Wild, properties=[lambda x: x.is_integer]
23
+ )
24
+ _indexing_wild_unsigned_int = functools.partial(
25
+ sympy.Wild, properties=[lambda x: x.is_integer and x.is_nonnegative]
26
+ )
27
+
28
+ @classmethod
29
+ def get_subexpr_involving_symbol(cls, expr: Expr, symbol: Symbol) -> Expr:
30
+ """
31
+ Given a sympy expression, return the subexpression comprised only of terms
32
+ involving the specified symbol.
33
+
34
+ For example, if `expr` is `x * 5 + x ** 2 + y * 2 + 5`, and `symbol` is `x`,
35
+ this returns `x * 5 + x ** 2`.
36
+ """
37
+ expr = cls._preprocess(expr)
38
+ return sympy.S.Zero + sum(
39
+ term for term in sympy.Add.make_args(expr) if symbol in term.free_symbols
40
+ )
41
+
42
+ @staticmethod
43
+ def factor_index_expr(expr: sympy.Expr, index_var: Symbol) -> sympy.Expr:
44
+ """
45
+ Given an index expression, factor the expression around
46
+ - FloorDiv(index_var, ...)
47
+ - ModularIndexing(index_var, ...)
48
+ - xindex
49
+
50
+ e.g. FloorDiv(index_var, d0)*s0 + FloorDiv(index_var, d0)*s1 ->
51
+ FloorDiv(index_var, d0) * (s0 + s1)
52
+ """
53
+ centres = OrderedSet()
54
+ for sub in sympy.preorder_traversal(expr):
55
+ if isinstance(sub, FloorDiv) and sub.args[0] == index_var:
56
+ centres.add(sub)
57
+ elif isinstance(sub, ModularIndexing) and sub.args[0] == index_var:
58
+ centres.add(sub)
59
+ centres.add(index_var)
60
+
61
+ expr_out = expr
62
+ for c in centres:
63
+ expr_out = sympy.collect(expr_out, c)
64
+ return expr_out
65
+
66
+ @staticmethod
67
+ def get_slice_numels(dims: list[Expr]) -> list[Expr]:
68
+ """
69
+ Compute the cumulative size of each dimension's slice.
70
+ This proceeds from the last dim up to the second.
71
+ """
72
+ numels = collections.deque([sympy.S.One])
73
+ for dim in dims[:0:-1]:
74
+ numel = dim * numels[0]
75
+ numels.appendleft(numel)
76
+ return [*numels]
77
+
78
+ @staticmethod
79
+ def _preprocess(expr: Expr) -> Expr:
80
+ # Remove any Identity nodes, e.g. expand x + (5 * y) to x + 5 * y.
81
+ # Disable mul and multinomial as those expansions affect op trees:
82
+ # e.g. sympy expects to match Mul(a, b), but expansion has simplified
83
+ # to Add(...). Even though they may be algebraically equivalent,
84
+ # sympy `match` performs structural pattern matching
85
+ return expr.expand(mul=False, multinomial=False, identity=True)
86
+
87
+ @classmethod
88
+ def match_mod_div_block_expr(
89
+ cls,
90
+ index: Expr,
91
+ index_var: Symbol,
92
+ numel: Expr,
93
+ num_dims: int,
94
+ ) -> Optional[tuple[list[Expr], list[Expr], list[Expr]]]:
95
+ """
96
+ Matches modular indexing expressions, converting them to implied block dimensions and strides.
97
+ See triton.py for more information.
98
+
99
+ Warning: this function requires that `index`, `numel` and any other sympy
100
+ expression does not have precomputed replacements since otherwise block
101
+ pattern matching may fail.
102
+ See [Note: Precomputed replacements with BlockPatternMatch]
103
+ """
104
+ index = cls._preprocess(index)
105
+
106
+ # Pattern match to find the strides and offset.
107
+ wild_unsigned_int = functools.partial(
108
+ cls._indexing_wild_unsigned_int, exclude=[index_var]
109
+ )
110
+ wild_signed_int = functools.partial(
111
+ cls._indexing_wild_signed_int, exclude=[index_var]
112
+ )
113
+ dims: list[Expr] = [
114
+ wild_unsigned_int(f"dim_mod{idx}") for idx in range(num_dims)
115
+ ]
116
+ strides: list[Expr] = [
117
+ wild_signed_int(f"stride_mod{idx}") for idx in range(num_dims)
118
+ ]
119
+
120
+ # The first dimension's index is computed by division.
121
+ # The remaining are computed by modulo.
122
+ slice_numels = cls.get_slice_numels(dims[:num_dims])
123
+ block_index_exprs = [FloorDiv(index_var, slice_numels[0])] + [
124
+ ModularIndexing(index_var, numel, dim)
125
+ for dim, numel in zip(dims[1:], slice_numels[1:])
126
+ ]
127
+
128
+ # Calculate a linear index from block indices.
129
+ match_expr = sympy_dot(strides, block_index_exprs)
130
+
131
+ # Heuristic: if the number of dimensions is high, check that the minimum requirements
132
+ # are met before attempting an expensive full match. see triton.py:match_mod_div_block
133
+ # for more details. In short, here we check that each subexpression in sympy.Add contains
134
+ # only FloorDiv or ModularIndexing expressions.
135
+ if num_dims >= 5:
136
+ stride = sympy.symbols("stride", cls=wild_signed_int)
137
+ denom, other = sympy.symbols("denominator other", cls=wild_unsigned_int)
138
+ mod_div_pattern = stride * ModularIndexing(index_var, denom, other)
139
+ floor_div_pattern = stride * FloorDiv(index_var, denom)
140
+ first_dim_floor_div_matched = False
141
+ match_failed = False
142
+ for arg in sympy.Add.make_args(index):
143
+ if arg.match(floor_div_pattern):
144
+ # There should only be a single FloorDiv(index, denom) expression
145
+ # corresponding to the first dimension
146
+ if first_dim_floor_div_matched:
147
+ match_failed = True
148
+ break
149
+ first_dim_floor_div_matched = True
150
+ elif arg.match(mod_div_pattern):
151
+ continue
152
+ else:
153
+ match_failed = True
154
+ break
155
+
156
+ if match_failed:
157
+ return None
158
+
159
+ # Pattern match.
160
+ match = index.match(match_expr)
161
+ if match is None:
162
+ return None
163
+
164
+ # Provide default values for unmatched dims and strides.
165
+ for dim in dims[1:]:
166
+ if dim not in match:
167
+ match[dim] = sympy.S.One
168
+ for stride in strides[1:]:
169
+ if stride not in match:
170
+ match[stride] = sympy.S.Zero
171
+
172
+ # Replace wildcards with matched expressions.
173
+ dims = [dims[0]] + [match[dim] for dim in dims[1:]]
174
+ strides = [match[stride] for stride in strides]
175
+ slice_numels = cls.get_slice_numels(dims)
176
+ block_index_exprs = [sympy_subs(expr, match) for expr in block_index_exprs]
177
+
178
+ sizevars = V.graph.sizevars
179
+
180
+ # The leading dimension is not directly matched in our expression.
181
+ # We solve for it by dividing the range tree numel by the product of
182
+ # all other dimensions. We quit if they are not known to be divisible.
183
+ assert dims[0] not in match, "Expected not to match the leading dimension!"
184
+ if not sizevars.statically_known_multiple_of(numel, slice_numels[0]):
185
+ return None
186
+ dims[0] = numel / slice_numels[0]
187
+
188
+ # Sanity check that we can recover the index from the matched subexpressions.
189
+ matched_index = sympy_dot(strides, block_index_exprs)
190
+ assert sizevars.statically_known_equals(
191
+ matched_index,
192
+ index,
193
+ ), textwrap.dedent(
194
+ f"""
195
+ Invalid match!
196
+ Index: {index}
197
+ Matched expression: {matched_index}
198
+ """
199
+ )
200
+
201
+ return dims, strides, block_index_exprs
202
+
203
+ @classmethod
204
+ def match_affine_block_expr(
205
+ cls,
206
+ index: Expr,
207
+ index_var: Symbol,
208
+ ) -> Optional[Expr]:
209
+ """
210
+ Matches simple expressions of the form stride * index, returning the
211
+ stride.
212
+ """
213
+ index = cls._preprocess(index)
214
+ stride = cls._indexing_wild_signed_int(name="stride", exclude=[index_var])
215
+ m = index.match(index_var * stride)
216
+ if m is None:
217
+ return None
218
+
219
+ return m[stride]
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/common.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_bmm_template.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import itertools
4
+ from collections.abc import Callable
5
+ from typing import Any, Optional
6
+ from unittest.mock import patch
7
+
8
+ import sympy
9
+
10
+ from .. import ir
11
+ from ..select_algorithm import PartialRender
12
+ from ..virtualized import V
13
+ from .common import ArgName
14
+ from .cpp_gemm_template import CppGemmTemplate, GEMM_TEMPLATE
15
+ from .cpp_micro_gemm import LayoutType
16
+ from .cpp_template_kernel import CppTemplateKernel
17
+ from .cpp_utils import DTYPE_TO_CPP, GemmBlocking
18
+
19
+
20
+ # We pass all sizevars present in BY to the GEMM templates so variables are not renamed in the BMM definition
21
+ GEMM_SINGLE_THREAD_MM_STUB = r"""
22
+ {{kernel.def_kernel(
23
+ inputs={"X": X, "W": W},
24
+ outputs={"Y": Y_2d},
25
+ aliases=aliases,
26
+ function_name=kernel_name+"_single_thread_mm",
27
+ extra_sizevars=BY_sizevars + [b_index],
28
+ placeholder="<SINGLE_THREAD_MM_DEF_FOR_BMM>")}}"""
29
+
30
+ GEMM_THREADED_MM_STUB = r"""
31
+ {{kernel.def_kernel(
32
+ inputs={"X": X, "W": W},
33
+ outputs={"Y": Y_2d},
34
+ aliases=aliases,
35
+ function_name=kernel_name+"_threaded_mm",
36
+ extra_sizevars=BY_sizevars + [b_index],
37
+ placeholder="<THREADED_MM_DEF_FOR_BMM>")}}"""
38
+
39
+ BMM_TEMPLATE = r"""
40
+ {{ template.codegen_microkernel_def() }}
41
+ {{ template.codegen_single_thread_gemm() }}
42
+ {{ template.codegen_multi_thread_gemm() }}
43
+
44
+ extern "C"
45
+ {{kernel.def_kernel(inputs={"X": BX, "W": BW}, outputs={"Y": BY}, aliases=aliases)}}
46
+ {
47
+ const int64_t B = {{kernel.size(BY_2d, 0)}};
48
+ {%- if num_threads > 1 %}
49
+ constexpr int64_t num_threads = {{num_threads}};
50
+ int64_t B_single_thread_block = (B / num_threads) * num_threads;
51
+
52
+ #pragma omp parallel for num_threads({{num_threads}})
53
+ {%- else %}
54
+ int64_t B_single_thread_block = B;
55
+ {%- endif %}
56
+ for (int64_t b_start = 0; b_start < B_single_thread_block; ++b_start) {
57
+ {{template.get_gemm_function_call(
58
+ kernel,
59
+ kernel_name+"_single_thread_mm",
60
+ "<SINGLE_THREAD_CALL_FOR_BMM>",
61
+ b_index="b_start",
62
+ )}}
63
+ }
64
+ for (int64_t b_start = B_single_thread_block; b_start < B; ++b_start) {
65
+ {{template.get_gemm_function_call(
66
+ kernel,
67
+ kernel_name+"_threaded_mm",
68
+ "<THREADED_MM_CALL_FOR_BMM>",
69
+ b_index="b_start",
70
+ )}}
71
+ }
72
+ }
73
+ """
74
+
75
+
76
+ class CppBmmTemplate(CppGemmTemplate):
77
+ def __init__(
78
+ self,
79
+ input_nodes,
80
+ layout: ir.Layout,
81
+ num_threads: int,
82
+ register_blocking: GemmBlocking,
83
+ beta=1,
84
+ alpha=1,
85
+ has_bias=False,
86
+ epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
87
+ should_block_weights: bool = False,
88
+ name="bmm",
89
+ ):
90
+ """
91
+ In order to simplify the implementation and increase code reuse, the BMM template implements
92
+ two versions of the GEMM kernel: a single-threaded version and a multi-threaded version.
93
+ GEMM kernels are called in a loop over the batch dimension, with single-threaded GEMM calls
94
+ for all but the last (B % num_threads), which are handled by the multi-threaded GEMM kernel.
95
+
96
+ We use an extra sizevar `b_index` to index the batch dimension, which we pass into the GEMM
97
+ template as a sympy.Symbol. This allows us to slice the 3D batch tensors in the GEMM template
98
+ without any changes to the GEMM template itself.
99
+ """
100
+ super().__init__(
101
+ input_nodes,
102
+ layout,
103
+ num_threads,
104
+ register_blocking,
105
+ beta=beta,
106
+ alpha=alpha,
107
+ has_bias=has_bias,
108
+ epilogue_creator=epilogue_creator,
109
+ should_block_weights=should_block_weights,
110
+ name=name,
111
+ )
112
+ self.b_index = sympy.Symbol("s_b_index", integer=True, nonnegative=True)
113
+
114
+ @staticmethod
115
+ def get_padded_size(n, block_n, k, should_block_weight):
116
+ if should_block_weight:
117
+ # Tensor is constant or not contiguous, so we will pad and block
118
+ new_size, padded_n = CppGemmTemplate.get_padded_size(
119
+ n, block_n, k, should_block_weight
120
+ )
121
+ # Add the new batch dimension
122
+ new_size.insert(0, -1)
123
+ return new_size, padded_n
124
+ else:
125
+ new_size = [-1, k, n]
126
+ return new_size, n
127
+
128
+ @staticmethod
129
+ def check_if_block_weight(W, micro_gemm):
130
+ assert isinstance(W, ir.IRNode)
131
+ _, n = W.get_size()[-2:]
132
+ result = (
133
+ not W.get_layout().is_contiguous()
134
+ or W.get_name() in V.graph.constants
135
+ or (
136
+ n % micro_gemm.register_blocking.block_n != 0
137
+ and micro_gemm.get_b_layout != LayoutType.NORMAL
138
+ )
139
+ )
140
+ return result
141
+
142
+ def get_gemm_function_call(
143
+ self,
144
+ kernel: CppTemplateKernel,
145
+ function_name: str,
146
+ placeholder: str,
147
+ b_index: str,
148
+ ) -> str:
149
+ """
150
+ Similar to 'def_kernel' in cpp_template_kernel, but instead of generating a function definition,
151
+ generate a function call for the GEMM kernel.
152
+ Args:
153
+ placeholder: The string to replace the function call with
154
+ b_index: The index for slicing the 3D batch tensors
155
+ """
156
+
157
+ def hook():
158
+ arg_defs, call_args, _, _ = kernel.args.python_argdefs()
159
+ for i, buf in enumerate(call_args):
160
+ if buf == self.b_index:
161
+ arg_defs[i] = ArgName(b_index)
162
+ call = f"{function_name}({', '.join(x.full_name() for x in arg_defs)});"
163
+ return call
164
+
165
+ assert placeholder not in kernel.render_hooks
166
+ kernel.render_hooks[placeholder] = hook
167
+ return placeholder
168
+
169
+ def get_default_reindexers(self, epilogue_nodes):
170
+ def reindexer(args):
171
+ # if epilogue nodes exist, they have 3D ranges but args are 2D, so add 0 index
172
+ return [self.b_index] + args
173
+
174
+ return [reindexer] * len(epilogue_nodes)
175
+
176
+ def get_options(
177
+ self,
178
+ kernel: CppTemplateKernel,
179
+ template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
180
+ flag_template_buffer_has_other_users: Optional[bool] = None,
181
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
182
+ **kwargs,
183
+ ) -> dict[str, Any]:
184
+ options = super().get_options(
185
+ kernel=kernel,
186
+ template_buffer_node=template_buffer_node,
187
+ flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
188
+ epilogue_nodes=epilogue_nodes,
189
+ **kwargs,
190
+ )
191
+
192
+ BX, BW, BY = options["X"], options["W"], options["Y"]
193
+ options["BX"], options["BW"], options["BY"] = BX, BW, BY
194
+ options["BY_2d"] = options["Y_2d"]
195
+ for kword in ["X", "W", "GemmOut", "Y_2d"]:
196
+ options[kword] = kernel.select(options[kword], 0, self.b_index)
197
+ for kword in ["X", "W", "Y_2d"]:
198
+ options[kword + "_dtype"] = DTYPE_TO_CPP[options[kword].dtype]
199
+ options["b_index"] = self.b_index
200
+ options["BY_sizevars"] = [
201
+ s
202
+ for sym in itertools.chain(BY.get_size(), BY.get_stride())
203
+ if isinstance(sym, sympy.Expr)
204
+ for s in sym.free_symbols
205
+ ]
206
+ options["kernel_name"] = kernel.kernel_name
207
+
208
+ return options
209
+
210
+ def render( # type: ignore[override, return]
211
+ self,
212
+ kernel: CppTemplateKernel,
213
+ template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
214
+ flag_template_buffer_has_other_users: Optional[bool] = None,
215
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
216
+ **kwargs,
217
+ ) -> str:
218
+ options = self.get_options(
219
+ kernel=kernel,
220
+ template_buffer_node=template_buffer_node,
221
+ flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
222
+ epilogue_nodes=epilogue_nodes,
223
+ **kwargs,
224
+ )
225
+ self.render_options = options
226
+
227
+ with contextlib.ExitStack() as stack:
228
+ for buf in options["fake_buffers"]:
229
+ stack.enter_context(
230
+ patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf))
231
+ )
232
+ result = self._template_from_string(BMM_TEMPLATE).render(**options)
233
+
234
+ # Finalize the function definitions for the gemm routines
235
+ sub_mm_hooks = {
236
+ name: hook
237
+ for name, hook in kernel.render_hooks.items()
238
+ if "FOR_BMM" in name
239
+ }
240
+ result = PartialRender(result, sub_mm_hooks).finalize_all()
241
+ for name in sub_mm_hooks:
242
+ del kernel.render_hooks[name]
243
+ del kernel.args.sizevars[options["b_index"]]
244
+ return result
245
+
246
+ def codegen_single_thread_gemm(self):
247
+ stub = self._template_from_string(GEMM_SINGLE_THREAD_MM_STUB).render(
248
+ self.render_options
249
+ )
250
+ return stub + self._template_from_string(GEMM_TEMPLATE).render(
251
+ {**self.render_options, "num_threads": 1}
252
+ )
253
+
254
+ def codegen_multi_thread_gemm(self):
255
+ stub = self._template_from_string(GEMM_THREADED_MM_STUB).render(
256
+ self.render_options
257
+ )
258
+ return stub + self._template_from_string(GEMM_TEMPLATE).render(
259
+ self.render_options
260
+ )
261
+
262
+ def codegen_gemm_stub_def(self):
263
+ return ""
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_flex_attention_template.py ADDED
@@ -0,0 +1,1090 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import logging
4
+ import re
5
+ from typing import Optional
6
+ from unittest.mock import patch
7
+
8
+ import sympy
9
+
10
+ import torch
11
+ import torch.utils
12
+
13
+ from ...utils._ordered_set import OrderedSet
14
+ from .. import ir
15
+ from ..ir import TensorBox
16
+ from ..select_algorithm import DataProcessorTemplateWrapper
17
+ from ..utils import parallel_num_threads
18
+ from ..virtualized import V
19
+ from .cpp_template import CppTemplate
20
+ from .cpp_utils import GemmBlocking
21
+
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+ # TODO: reuse cpp codegen to generate below pointwise/reduction kernels
26
+ SOFTMAX_FUSIONS = r"""
27
+ // 1) out = exp(a - val)
28
+ // 2) val = sum(out)
29
+ template <typename T1, typename T2>
30
+ inline void {{kernel_name}}_exp_reduce_sum_fusion_kernel(
31
+ T1* a,
32
+ const int& size,
33
+ T2* out,
34
+ T1& val) {
35
+ auto vec_size = at::vec::Vectorized<T1>::size();
36
+ auto vec_max = at::vec::Vectorized<T1>(val);
37
+ T1 tmp_sum = 0;
38
+ auto vec_tmp_sum = at::vec::Vectorized<T1>(tmp_sum);
39
+ for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) {
40
+ auto tmp0 = at::vec::Vectorized<T1>::loadu(a + i);
41
+ auto tmp1 = tmp0 - vec_max;
42
+ auto tmp2 = tmp1.exp_u20();
43
+ vec_tmp_sum += tmp2;
44
+ at::native::_store(out + i, tmp2);
45
+ }
46
+ tmp_sum = at::vec::vec_reduce_all<T1>(
47
+ [](at::vec::Vectorized<T1>& x, at::vec::Vectorized<T1>& y) {
48
+ return x + y;
49
+ },
50
+ vec_tmp_sum);
51
+ for (long i = vec_size * (size / vec_size); i < size; i++) {
52
+ auto tmp0 = a[i];
53
+ auto tmp1 = tmp0 - val;
54
+ auto tmp2 = exp(tmp1);
55
+ tmp_sum += tmp2;
56
+ out[i] = tmp2;
57
+ }
58
+ val = tmp_sum;
59
+ }
60
+
61
+ // 1) out = a * scale
62
+ // 2) max = max(out)
63
+ template <typename scalar_t>
64
+ inline void {{kernel_name}}_mul_reduce_max_fusion_kernel(
65
+ const scalar_t* a,
66
+ const scalar_t& scale,
67
+ const int& size,
68
+ scalar_t* out,
69
+ scalar_t& max) {
70
+ auto vec_size = at::vec::Vectorized<scalar_t>::size();
71
+ auto vec_scale = at::vec::Vectorized<scalar_t>(scale);
72
+ scalar_t tmp_max = -std::numeric_limits<scalar_t>::infinity();
73
+ auto vec_tmp_max = at::vec::Vectorized<scalar_t>(tmp_max);
74
+ for (long i = 0; i < vec_size * (size / vec_size); i += vec_size) {
75
+ auto tmp0 = at::vec::Vectorized<scalar_t>::loadu(a + i);
76
+ auto tmp1 = tmp0 * vec_scale;
77
+ vec_tmp_max = at::vec::maximum(vec_tmp_max, tmp1);
78
+ at::native::_store(out + i, tmp1);
79
+ }
80
+ for (long i = vec_size * (size / vec_size); i < size; i++) {
81
+ auto tmp0 = a[i];
82
+ auto tmp1 = tmp0 * scale;
83
+ tmp_max = std::max(tmp_max, tmp1);
84
+ out[i] = tmp1;
85
+ }
86
+ max = std::max(
87
+ tmp_max,
88
+ at::vec::vec_reduce_all<scalar_t>(
89
+ [](at::vec::Vectorized<scalar_t>& x, at::vec::Vectorized<scalar_t>& y) {
90
+ return at::vec::maximum(x, y);
91
+ },
92
+ vec_tmp_max));
93
+ }
94
+
95
+ template <typename scalar_t>
96
+ static inline scalar_t* {{kernel_name}}_conditional_data_ptr(scalar_t* ptr, scalar_t* ptr2) {
97
+ TORCH_CHECK(ptr2 == nullptr);
98
+ return ptr;
99
+ }
100
+
101
+ template <typename scalar_t,
102
+ typename std::enable_if_t<c10::is_reduced_floating_point_v<scalar_t>, int> = 0>
103
+ static inline scalar_t* {{kernel_name}}_conditional_data_ptr(float* ptr, scalar_t* ptr2) {
104
+ return ptr2;
105
+ }
106
+
107
+ template <typename scalar_t>
108
+ inline void {{kernel_name}}_fill_stub(scalar_t* data, scalar_t val, int64_t size) {
109
+ using Vec = at::vec::Vectorized<scalar_t>;
110
+ Vec data_vec = Vec(val);
111
+ int64_t d = 0;
112
+ for (; d < size - (size % Vec::size()); d += Vec::size()) {
113
+ data_vec.store(data + d);
114
+ }
115
+ #if !defined(_MSC_VER) && !defined(COMPILING_FOR_MIN_SIZE)
116
+ # pragma unroll
117
+ #endif
118
+ for (; d < size; d++) {
119
+ data[d] = val;
120
+ }
121
+ }
122
+
123
+ // out = a * scale
124
+ template <typename scalar_t>
125
+ inline void {{kernel_name}}_mul_scale_kernel(
126
+ scalar_t* a,
127
+ scalar_t scale,
128
+ int64_t size) {
129
+ auto vec_size = at::vec::Vectorized<scalar_t>::size();
130
+ auto vec_scale = at::vec::Vectorized<scalar_t>(scale);
131
+ for (int64_t i = 0; i < vec_size * (size / vec_size); i += vec_size) {
132
+ auto tmp0 = at::vec::Vectorized<scalar_t>::loadu(a + i);
133
+ auto tmp1 = tmp0 * vec_scale;
134
+ at::native::_store(a + i, tmp1);
135
+ }
136
+ for (int64_t i = vec_size * (size / vec_size); i < size; i++) {
137
+ auto tmp0 = a[i];
138
+ auto tmp1 = tmp0 * scale;
139
+ a[i] = tmp1;
140
+ }
141
+ }
142
+
143
+ """
144
+
145
+ BRGEMM_PACK_FUNCTIONS = r"""
146
+ template <typename scalar_t>
147
+ inline void {{kernel_name}}_copy_value_with_pad(
148
+ const scalar_t* value_ptr,
149
+ scalar_t* dst_ptr,
150
+ int64_t rows,
151
+ int64_t cols,
152
+ int64_t prows,
153
+ int64_t pcols,
154
+ int64_t ldi) {
155
+ auto vec_size = at::vec::Vectorized<scalar_t>::size();
156
+ int64_t i = 0;
157
+ for (; i < rows; i++) {
158
+ int64_t j = 0;
159
+ for (; j < cols - (cols % vec_size); j += vec_size) {
160
+ auto vec_v =
161
+ at::vec::Vectorized<scalar_t>::loadu(value_ptr + i * ldi + j);
162
+ vec_v.store(dst_ptr + i * pcols + j);
163
+ }
164
+
165
+ if (j < cols) {
166
+ auto vec_v = at::vec::Vectorized<scalar_t>::loadu(
167
+ value_ptr + i * ldi + j, cols - j);
168
+ vec_v.store(dst_ptr + i * pcols + j, cols - j);
169
+ }
170
+
171
+ // col padding
172
+ auto psize = pcols - cols;
173
+ if (psize > 0) {
174
+ auto zero_vec = at::vec::Vectorized<scalar_t>(0);
175
+ int64_t pj = 0;
176
+ for (; pj < psize - (psize % vec_size); pj += vec_size) {
177
+ zero_vec.store(dst_ptr + i * pcols + cols + pj);
178
+ }
179
+ if (pj < psize) {
180
+ zero_vec.store(dst_ptr + i * pcols + cols + pj, psize - pj);
181
+ }
182
+ }
183
+ }
184
+ // row padding
185
+ for (; i < prows; i++) {
186
+ auto zero_vec = at::vec::Vectorized<scalar_t>(0);
187
+ int64_t j = 0;
188
+ for (; j < pcols - (pcols % vec_size); j += vec_size) {
189
+ zero_vec.store(dst_ptr + i * pcols + j);
190
+ }
191
+ if (j < pcols) {
192
+ zero_vec.store(dst_ptr + i * pcols + j, pcols - j);
193
+ }
194
+
195
+ }
196
+ }
197
+ """
198
+
199
+ MICRO_GEMM_TEMPLATE = r"""
200
+ GEMM_DEFINE
201
+ """
202
+
203
+ ALLOCATE_BUFFER = r"""
204
+ int64_t {{buffer_name}}_dtype_itemsize = c10::is_reduced_floating_point_v<{{buffer_dtype}}> ? 2 : 4;
205
+ auto& {{buffer_name}}_allocator = *at::getCPUAllocator();
206
+ auto {{buffer_name}}_work_data = {{buffer_name}}_allocator.allocate({{buffer_size}}*{{buffer_name}}_dtype_itemsize);
207
+ void* {{buffer_name}}_data_ptr = {{buffer_name}}_work_data.get();
208
+ {{buffer_dtype}}* {{buffer_name}} = ({{buffer_dtype}}*){{buffer_name}}_data_ptr;
209
+ """
210
+
211
+ FLEX_ATTENTION_TEMPLATE = r"""
212
+ {{template.header().getvalue()}}
213
+ #include <ATen/native/cpu/utils.h>
214
+ #include <ATen/native/CPUBlas.h>
215
+ #include <ATen/Context.h>
216
+ {{template.codegen_micro_gemm(kernel.kernel_name)}}
217
+ {{template.codegen_softmax_fusion(kernel.kernel_name)}}
218
+ {{template.codegen_brgemm_pack_function(kernel.kernel_name)}}
219
+ {%- set kernel_args = {"query": query, "key": key, "value": value,
220
+ "kv_num_blocks": kv_num_blocks, "kv_indices": kv_indices,
221
+ "full_kv_num_blocks": full_kv_num_blocks, "full_kv_indices": full_kv_indices } %}
222
+ {%- set kernel_args = template.update_kernel_args(kernel_args) %}
223
+
224
+ extern "C"
225
+ {{kernel.def_kernel(inputs=kernel_args, outputs={"output": output}, extra_sizevars=template.extra_sizevars)}}
226
+ {
227
+ {{ kernel.maybe_codegen_profile() }}
228
+ int64_t qBlockSize = {{qBlockSize}};
229
+ int64_t kvBlockSize = {{kvBlockSize}};
230
+ int64_t num_thread = {{num_thread}};
231
+
232
+ // dtypes of kernel and internal buffers
233
+ using scalar_t = {{kernel.dtype(query)}};
234
+ constexpr bool is_reduced_type = c10::is_reduced_floating_point_v<scalar_t>;
235
+ using accum_t = at::opmath_type<{{kernel.dtype(query)}}>;
236
+ using Vec = at::vec::Vectorized<accum_t>;
237
+ accum_t scaling_factor = {{scale}};
238
+ int64_t batchSize = {{kernel.size(query, 0)}};
239
+ int64_t qSize = {{kernel.size(query, 1)}};
240
+ int64_t num_head = {{kernel.size(query, 2)}};
241
+ int64_t headSize = {{kernel.size(query, 3)}};
242
+ int64_t batchSize_k = {{kernel.size(key, 0)}};
243
+ int64_t num_head_k = {{kernel.size(key, 2)}};
244
+ int64_t headSize_v = {{kernel.size(value, 3)}};
245
+ bool is_broadcast_bs_kv = batchSize != batchSize_k;
246
+ bool is_broadcast_head_kv = num_head != num_head_k;
247
+ int64_t gqa_shards = num_head / num_head_k;
248
+ int64_t bs_shards = batchSize / batchSize_k;
249
+
250
+ int64_t batchSize_kvi = {{kernel.size(kv_indices, 0)}};
251
+ int64_t num_head_kvi = {{kernel.size(kv_indices, 1)}};
252
+ int64_t block_num_kvi = {{kernel.size(kv_indices, 3)}};
253
+ bool is_broadcast_bs_kvi = batchSize != batchSize_kvi;
254
+ bool is_broadcast_head_kvi = num_head != num_head_kvi;
255
+ int64_t gqa_shards_kvi = num_head / num_head_kvi;
256
+ int64_t bs_shards_kvi = batchSize / batchSize_kvi;
257
+
258
+ int64_t kviStrideB = {{kernel.stride(kv_indices, 0)}};
259
+ int64_t kviStrideH = {{kernel.stride(kv_indices, 1)}};
260
+ int64_t kviStrideQ = {{kernel.stride(kv_indices, 2)}};
261
+
262
+ int64_t num_kviStrideB = {{kernel.stride(kv_num_blocks, 0)}};
263
+ int64_t num_kviStrideH = {{kernel.stride(kv_num_blocks, 1)}};
264
+
265
+ {%- if has_full_kv_block %}
266
+ int64_t full_kviStrideB = {{kernel.stride(full_kv_indices, 0)}};
267
+ int64_t full_kviStrideH = {{kernel.stride(full_kv_indices, 1)}};
268
+ int64_t full_kviStrideQ = {{kernel.stride(full_kv_indices, 2)}};
269
+
270
+ int64_t full_num_kviStrideB = {{kernel.stride(full_kv_num_blocks, 0)}};
271
+ int64_t full_num_kviStrideH = {{kernel.stride(full_kv_num_blocks, 1)}};
272
+ auto full_kv_indices_data = full_kv_indices;
273
+ auto full_kv_num_blocks_data = full_kv_num_blocks;
274
+ {%- endif %}
275
+
276
+ auto kv_num_blocks_data = kv_num_blocks;
277
+ auto kv_indices_data = kv_indices;
278
+
279
+ // Strides
280
+ int64_t qStrideB = {{kernel.stride(query, 0)}};
281
+ int64_t qStrideM = {{kernel.stride(query, 1)}};
282
+ int64_t qStrideH = {{kernel.stride(query, 2)}};
283
+ int64_t kStrideB = {{kernel.stride(key, 0)}};
284
+ int64_t kStrideN = {{kernel.stride(key, 1)}};
285
+ int64_t kStrideH = {{kernel.stride(key, 2)}};
286
+ int64_t vStrideB = {{kernel.stride(value, 0)}};
287
+ int64_t vStrideN = {{kernel.stride(value, 1)}};
288
+ int64_t vStrideH = {{kernel.stride(value, 2)}};
289
+ int64_t oStrideB = {{kernel.stride(output, 0)}};
290
+ int64_t oStrideM = {{kernel.stride(output, 2)}};
291
+ int64_t oStrideH = {{kernel.stride(output, 1)}};
292
+
293
+ int64_t kvSize = {{kernel.size(key, 1)}};
294
+
295
+ int64_t qSplitSize = qBlockSize;
296
+ int64_t kvSplitSize = kvBlockSize;
297
+
298
+
299
+ qSplitSize = qSplitSize > qSize ? qSize : qSplitSize;
300
+ kvSplitSize = kvSplitSize > kvSize ? kvSize : kvSplitSize;
301
+ int64_t qSlice = (qSize + qSplitSize - 1) / qSplitSize;
302
+ int64_t kvSlice = (kvSize + kvSplitSize - 1) / kvSplitSize;
303
+ int64_t kvTail = (kvSize - 1) % kvSplitSize + 1;
304
+
305
+ bool need_pack = false;
306
+ // Whether pack is needed for BFloat16/Half
307
+ if (is_reduced_type) {
308
+ // check platform ability
309
+ need_pack = std::is_same_v<scalar_t, at::BFloat16> ? at::native::cpublas::could_pack(at::kBFloat16)
310
+ : at::native::cpublas::could_pack(at::kHalf);
311
+ }
312
+ if (need_pack) {
313
+ // When the number of gemm is greater than the number of pack,
314
+ // the pack overhead can be overlapped.
315
+ int64_t thresh_size = 64;
316
+ need_pack = kvSize >= thresh_size && qSize >= thresh_size;
317
+ if (need_pack) {
318
+ double pack_size = batchSize * num_head * kvSize * headSize;
319
+ double qs_per_thread = (batchSize * num_head * qSlice + num_thread - 1) / num_thread;
320
+ double gemm_size_per_thread = qs_per_thread * qSplitSize * kvSize * headSize;
321
+ need_pack = gemm_size_per_thread / pack_size >= 4;
322
+ }
323
+ }
324
+ // Pad is needed for packing when K is not even
325
+ bool headSize_even = headSize % 2 == 0;
326
+ int64_t eheadSize = need_pack && !headSize_even ? headSize + 1: headSize;
327
+ int64_t ekvSplitSize = need_pack && (kvSplitSize % 2 != 0) ? kvSplitSize + 1 : kvSplitSize;
328
+ int64_t ekvTail = need_pack && (kvTail % 2 != 0) ? kvTail + 1 : kvTail;
329
+ int64_t kv_padding_size = (kvSize - 1) / kvSplitSize * ekvSplitSize + ekvTail;
330
+
331
+ // Allocate per thread temp buf (accumulate type)
332
+ int64_t _size_per_thread =
333
+ /* qk */ qSplitSize * kvSplitSize +
334
+ /* qk_max */ qSplitSize +
335
+ /* qk_sum */ qSplitSize +
336
+ /* dst */ qSplitSize * headSize_v;
337
+
338
+ // Inputs/outputs buffers
339
+ const scalar_t* q_data = query;
340
+ const scalar_t* k_data = key;
341
+ const scalar_t* v_data = value;
342
+ scalar_t* out_data = output;
343
+
344
+ // Buffers to store accum results, padding query and transpose/packing key/value
345
+ {{template.codegen_allocate_buffer("buf_data", "accum_t", "num_thread*_size_per_thread")}}
346
+ {{template.codegen_allocate_buffer("buf_reduced_data", "scalar_t", "num_thread*qSplitSize*ekvSplitSize")}}
347
+ {{template.codegen_allocate_buffer("key_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*eheadSize*kvSize")}}
348
+ {{template.codegen_allocate_buffer("value_reorder_ptr", "scalar_t", "batchSize_k*num_head_k*kv_padding_size*headSize_v")}}
349
+ {{template.codegen_allocate_buffer("transpose_buffer_ptr", "scalar_t", "num_thread*kvSplitSize*headSize")}}
350
+ {{template.codegen_allocate_buffer("query_padding_ptr", "scalar_t", "num_thread*qSplitSize*eheadSize")}}
351
+ if (need_pack) {
352
+ // Pack K, V
353
+ at::parallel_for(0, batchSize_k * num_head_k * kvSlice, 1, [&](int64_t begin, int64_t end) {
354
+ int ompIdx = at::get_thread_num();
355
+ int64_t i = 0, j = 0, l = 0, n = 0;
356
+ scalar_t* transpose_ptr = need_pack? transpose_buffer_ptr + ompIdx * kvSplitSize * headSize : nullptr;
357
+ at::native::data_index_init(begin, i, batchSize_k, j, num_head_k, l, kvSlice);
358
+ for ([[maybe_unused]] auto z : c10::irange(begin, end)) {
359
+ n = l * kvSplitSize;
360
+ int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n);
361
+ auto k_addr =
362
+ k_data + i * kStrideB + j * kStrideH + n * kStrideN;
363
+ auto v_addr =
364
+ v_data + i * vStrideB + j * vStrideH + n * vStrideN;
365
+ // transpose [cur_kvSplitSize, headSize] -> [headSize, cur_kvSplitSize]
366
+ at::native::utils::transpose<uint16_t>(
367
+ cur_kvSplitSize,
368
+ headSize,
369
+ /* src_ptr */
370
+ reinterpret_cast<const uint16_t*>(k_addr),
371
+ /* ld_src */ kStrideN,
372
+ /* dst */ reinterpret_cast<uint16_t*>(transpose_ptr),
373
+ /* ld_dst */ cur_kvSplitSize);
374
+
375
+ // Pack [headSize, cur_kvSplitSize]
376
+ at::vec::pack_vnni2(
377
+ /* src */ reinterpret_cast<const uint16_t*>(transpose_ptr),
378
+ /* dst */ reinterpret_cast<uint16_t*>(key_reorder_ptr + i * num_head_k * eheadSize * kvSize +
379
+ j * eheadSize * kvSize + n * eheadSize),
380
+ /* ld_src */ cur_kvSplitSize,
381
+ /* K */ headSize,
382
+ /* N */ cur_kvSplitSize);
383
+
384
+ // Pack [cur_kvSplitSize, headSize_v]
385
+ at::vec::pack_vnni2(
386
+ /* src */ reinterpret_cast<const uint16_t*>(v_addr),
387
+ /* dst */ reinterpret_cast<uint16_t*>(value_reorder_ptr +
388
+ i * num_head_k * kv_padding_size * headSize_v +
389
+ j * kv_padding_size * headSize_v + n * headSize_v),
390
+ /* ld_src */ vStrideN,
391
+ /* K */ cur_kvSplitSize,
392
+ /* N */ headSize_v);
393
+ // Move to the next query
394
+ at::native::data_index_step(i, batchSize_k, j, num_head_k, l, kvSlice);
395
+ }
396
+ });
397
+ }
398
+ // Attention loop below
399
+ at::parallel_for(0, batchSize * num_head * qSlice, 1, [&](int64_t begin, int64_t end) {
400
+ int64_t i = 0, j = 0, k = 0;
401
+ at::native::data_index_init(begin, i, batchSize, j, num_head, k, qSlice);
402
+ int ompIdx = at::get_thread_num();
403
+ accum_t* buf_ptr = buf_data + ompIdx * _size_per_thread;
404
+ accum_t* qk_data = buf_ptr;
405
+ accum_t* qk_max_data = qk_data + qSplitSize * kvSplitSize;
406
+ accum_t* qk_sum_data = qk_max_data + qSplitSize;
407
+ accum_t* dst_data = qk_sum_data + qSplitSize;
408
+ scalar_t *qk_reduced_data =
409
+ is_reduced_type
410
+ ? buf_reduced_data + ompIdx * qSplitSize * ekvSplitSize
411
+ : nullptr;
412
+ scalar_t* query_t_padding_ptr = (!headSize_even && need_pack)
413
+ ? query_padding_ptr + ompIdx * qSplitSize * eheadSize
414
+ : nullptr;
415
+
416
+ for ([[maybe_unused]] auto z : c10::irange(begin, end)) {
417
+ auto i_kvi = is_broadcast_bs_kvi ? i/bs_shards_kvi : i;
418
+ auto j_kvi = is_broadcast_head_kvi ? j/gqa_shards_kvi : j;
419
+ auto kv_logical_num_data = kv_num_blocks_data + i_kvi * num_kviStrideB +
420
+ j_kvi * num_kviStrideH + k;
421
+ int kv_indice_num = *kv_logical_num_data;
422
+ std::vector<int> kv_indice_list(kv_indice_num);
423
+ for(int kv_i = 0; kv_i < kv_indice_num; kv_i++){
424
+ auto kv_logical_data = kv_indices_data + i_kvi * kviStrideB +
425
+ j_kvi * kviStrideH + k*kviStrideQ + kv_i;
426
+ kv_indice_list[kv_i] = *kv_logical_data;
427
+ }
428
+ bool is_skip_kv = kv_indice_num > 0 ? false : true;
429
+ {%- if has_full_kv_block %}
430
+ auto full_kv_logical_num_data = full_kv_num_blocks_data + i_kvi * num_kviStrideB +
431
+ j_kvi * num_kviStrideH + k;
432
+ int full_kv_indice_num = *full_kv_logical_num_data;
433
+ std::vector<int> full_kv_indice_list(full_kv_indice_num);
434
+ for(int kv_i = 0; kv_i < full_kv_indice_num; kv_i++){
435
+ auto full_kv_logical_data = full_kv_indices_data + i_kvi * full_kviStrideB +
436
+ j_kvi * full_kviStrideH + k*full_kviStrideQ + kv_i;
437
+ full_kv_indice_list[kv_i] = *full_kv_logical_data;
438
+ }
439
+ is_skip_kv = kv_indice_num + full_kv_indice_num > 0 ? false : true;
440
+ {%- endif %}
441
+ int64_t m = k * qSplitSize;
442
+ int64_t cur_qSplitSize = std::min(qSplitSize, qSize - m);
443
+ if (!is_skip_kv){
444
+ // Initialize max and sum
445
+ {{kernel.kernel_name}}_fill_stub(qk_max_data,
446
+ -std::numeric_limits<accum_t>::infinity(), cur_qSplitSize);
447
+ {{kernel.kernel_name}}_fill_stub(qk_sum_data,
448
+ static_cast<accum_t>(0), cur_qSplitSize);
449
+
450
+ if (!headSize_even && need_pack) {
451
+ // Pad query if headSize is not even
452
+ {{kernel.kernel_name}}_copy_value_with_pad<scalar_t>(
453
+ q_data + i * qStrideB + j * qStrideH + m * qStrideM,
454
+ query_t_padding_ptr,
455
+ cur_qSplitSize,
456
+ headSize,
457
+ cur_qSplitSize,
458
+ eheadSize,
459
+ qStrideM
460
+ );
461
+ }
462
+ }
463
+
464
+ {%- if has_full_kv_block %}
465
+ for (int64_t n_idx = 0; n_idx < kv_indice_num + full_kv_indice_num ; n_idx += 1) {
466
+ auto n = n_idx < kv_indice_num ? kv_indice_list[n_idx]*kvSplitSize : full_kv_indice_list[n_idx - kv_indice_num]*kvSplitSize;
467
+ {%- else %}
468
+ for (int64_t n_idx = 0; n_idx < kv_indice_num ; n_idx += 1) {
469
+ auto n = kv_indice_list[n_idx]*kvSplitSize;
470
+ {%- endif %}
471
+
472
+ auto cur_n = n/kvSplitSize;
473
+ int64_t cur_kvSplitSize = std::min(kvSplitSize, kvSize - n);
474
+ int64_t cur_ekvSplitSize = (need_pack && cur_kvSplitSize % 2 != 0) ? cur_kvSplitSize + 1 : cur_kvSplitSize;
475
+
476
+ // Calculate scale * q @ k.T
477
+ auto i_kv = is_broadcast_bs_kv ? i/bs_shards : i;
478
+ auto j_kv = is_broadcast_head_kv ? j/gqa_shards : j;
479
+
480
+ if (!need_pack) {
481
+ auto k_addr =
482
+ k_data + i_kv * kStrideB + j_kv * kStrideH + n * kStrideN;
483
+
484
+ {{kernel.kernel_name}}_kernel_micro_gemm_transpose_b<static_cast<bool>(false)>(
485
+ q_data + i * qStrideB + j * qStrideH +
486
+ m * qStrideM,
487
+ k_addr,
488
+ qk_data,
489
+ cur_qSplitSize,
490
+ cur_kvSplitSize,
491
+ headSize,
492
+ qStrideM,
493
+ kStrideN,
494
+ cur_kvSplitSize);
495
+
496
+ } else {
497
+ at::native::cpublas::brgemm(
498
+ cur_qSplitSize,
499
+ cur_kvSplitSize,
500
+ eheadSize,
501
+ headSize_even ? qStrideM : eheadSize,
502
+ cur_kvSplitSize,
503
+ cur_kvSplitSize,
504
+ false,
505
+ !headSize_even
506
+ ? query_t_padding_ptr
507
+ : q_data + i * qStrideB + j * qStrideH + m * qStrideM,
508
+ key_reorder_ptr + i_kv * num_head_k * eheadSize * kvSize +
509
+ j_kv * eheadSize * kvSize + n * eheadSize,
510
+ qk_data,
511
+ need_pack);
512
+ }
513
+
514
+ {{kernel.kernel_name}}_mul_scale_kernel<accum_t>(qk_data, scaling_factor, cur_qSplitSize*cur_kvSplitSize);
515
+
516
+ {%- if score_mod and mask_mod %}
517
+ // TODO: reduce the number of calls of q_idx and kv_idx initialization
518
+ std::vector<int64_t> q_idx(cur_qSplitSize);
519
+ for (int64_t i = 0; i < cur_qSplitSize; ++i) {
520
+ q_idx[i] = m + i;
521
+ }
522
+
523
+ std::vector<int64_t> kv_idx(cur_kvSplitSize);
524
+ for (int64_t i = 0; i < cur_kvSplitSize; ++i) {
525
+ kv_idx[i] = n + i;
526
+ }
527
+
528
+ std::vector<int64_t> b_idx = {i};
529
+ std::vector<int64_t> h_idx = {j};
530
+
531
+ accum_t* in_ptr0 = qk_data;
532
+
533
+ auto in_ptr1 = b_idx.data();
534
+ auto in_ptr2 = h_idx.data();
535
+ auto in_ptr3 = q_idx.data();
536
+ auto in_ptr4 = kv_idx.data();
537
+
538
+ // apply score mod function
539
+ {
540
+ {{ template.generate_other_buffer("score_others", 0, "len_score_other", kernel.args) }}
541
+ accum_t* out_ptr{{score_buf_idx}} = in_ptr0;
542
+ {{ template.modification(score_mod, score_buf_name, score_buf_idx)|indent(12, false) }}
543
+ }
544
+
545
+ if ((std::find(kv_indice_list.begin(), kv_indice_list.end(), cur_n) != kv_indice_list.end()) ){
546
+ // Apply block mask, fill unused with -inf
547
+ {
548
+ {{ template.generate_other_buffer("mask_others", -1, "len_mask_other", kernel.args) }}
549
+ accum_t* out_ptr{{mask_buf_idx}} = in_ptr0;
550
+ {{ template.modification(mask_mod, mask_buf_name, mask_buf_idx)|indent(12, false) }}
551
+ }
552
+ }
553
+
554
+ {%- endif %}
555
+ // Update coefficients with Softmax
556
+ accum_t tmp_max = 0, tmp_sum = 0, exp_tmp = 0;
557
+ for (int64_t row = 0; row < cur_qSplitSize; ++row) {
558
+ // apply scaling factor and max per row in fusion
559
+ {{kernel.kernel_name}}_mul_reduce_max_fusion_kernel(
560
+ qk_data + row * cur_kvSplitSize,
561
+ static_cast<accum_t>(1),
562
+ cur_kvSplitSize,
563
+ qk_data + row * cur_kvSplitSize,
564
+ tmp_max);
565
+ tmp_max = qk_max_data[row] > tmp_max ? qk_max_data[row] : tmp_max;
566
+ if (tmp_max == -std::numeric_limits<accum_t>::infinity()) {
567
+ // to avoid `nan = exp2f(-inf - (-inf))`
568
+ {{kernel.kernel_name}}_fill_stub(
569
+ {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize,
570
+ static_cast<scalar_t>(0), cur_kvSplitSize);
571
+ } else {
572
+ tmp_sum = tmp_max;
573
+ // qk <- exp(qk - max) and sum per row
574
+ {{kernel.kernel_name}}_exp_reduce_sum_fusion_kernel(
575
+ qk_data + row * cur_kvSplitSize, cur_kvSplitSize,
576
+ {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data) + row * cur_ekvSplitSize,
577
+ tmp_sum);
578
+ // exp_tmp <- exp(max[row] - max)
579
+ exp_tmp = std::exp(qk_max_data[row] - tmp_max);
580
+ // sum[row] <- sum + exp_tmp * sum[row]
581
+ qk_sum_data[row] = tmp_sum + exp_tmp * qk_sum_data[row];
582
+ // max[row] <- max
583
+ qk_max_data[row] = tmp_max;
584
+ // dst <- dst * exp_tmp
585
+ if (n_idx > 0) {
586
+ at::vec::map<accum_t>(
587
+ [exp_tmp](Vec x) { return x * Vec(exp_tmp); },
588
+ dst_data + row * headSize_v,
589
+ dst_data + row * headSize_v,
590
+ headSize_v);
591
+ }
592
+ }
593
+ if (need_pack && cur_kvSplitSize % 2 != 0) {
594
+ // Pad: [qSplitSize, cur_kvSplitSize] -> [qSplitSize, cur_kvSplitSize + 1]
595
+ *(qk_reduced_data + row * (1 + cur_kvSplitSize) + cur_kvSplitSize) = scalar_t(0);
596
+ }
597
+ }
598
+ // Calculate Softmax(q @ k.T) @ v
599
+ if (!need_pack) {
600
+ auto v_addr =
601
+ v_data + i_kv * vStrideB + j_kv * vStrideH + n * vStrideN;
602
+ // Fallback Half brgemm is slower than micro gemm
603
+ if (!std::is_same_v<scalar_t, at::Half>) {
604
+ at::native::cpublas::brgemm(
605
+ cur_qSplitSize,
606
+ headSize_v,
607
+ cur_ekvSplitSize,
608
+ cur_ekvSplitSize,
609
+ vStrideN,
610
+ headSize_v,
611
+ n_idx > 0,
612
+ {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data),
613
+ v_addr,
614
+ dst_data,
615
+ need_pack);
616
+ } else {
617
+ if (n_idx > 0) {
618
+ {{kernel.kernel_name}}_kernel_micro_gemm<static_cast<bool>(true)>(
619
+ {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data),
620
+ v_addr,
621
+ dst_data,
622
+ cur_qSplitSize,
623
+ headSize_v,
624
+ cur_ekvSplitSize,
625
+ cur_ekvSplitSize,
626
+ vStrideN,
627
+ headSize_v);
628
+ } else {
629
+ {{kernel.kernel_name}}_kernel_micro_gemm<static_cast<bool>(false)>(
630
+ {{kernel.kernel_name}}_conditional_data_ptr(qk_data, qk_reduced_data),
631
+ v_addr,
632
+ dst_data,
633
+ cur_qSplitSize,
634
+ headSize_v,
635
+ cur_ekvSplitSize,
636
+ cur_ekvSplitSize,
637
+ vStrideN,
638
+ headSize_v);
639
+ }
640
+ }
641
+ } else {
642
+ int64_t psize = n / kvSplitSize * ekvSplitSize;
643
+ at::native::cpublas::brgemm(
644
+ cur_qSplitSize,
645
+ headSize_v,
646
+ cur_ekvSplitSize,
647
+ cur_ekvSplitSize,
648
+ headSize_v,
649
+ headSize_v,
650
+ n_idx > 0,
651
+ qk_reduced_data,
652
+ value_reorder_ptr +
653
+ i_kv * num_head_k * kv_padding_size * headSize_v +
654
+ j_kv * kv_padding_size * headSize_v + psize * headSize_v,
655
+ dst_data,
656
+ need_pack);
657
+ }
658
+ }
659
+
660
+ // dst <- dst / sum[row]
661
+ // reorder MHA output with strides
662
+ for (int64_t row = 0; row < cur_qSplitSize; ++row) {
663
+ // Row sums for full masked out rows are 0, we set them to 1
664
+ // in order to avoid NaNs in the output and instead set fully
665
+ // masked out rows to 0
666
+ qk_max_data[row] = qk_max_data[row] == -std::numeric_limits<accum_t>::infinity() ? 0 : qk_max_data[row];
667
+ qk_sum_data[row] = qk_sum_data[row] == 0 ? 1 : qk_sum_data[row];
668
+ accum_t sum_reciprocal = 1 / qk_sum_data[row];
669
+ at::vec::map<scalar_t>(
670
+ [sum_reciprocal, is_skip_kv](Vec x) { return is_skip_kv ? Vec(0.0) : x * Vec(sum_reciprocal); },
671
+ out_data + i * oStrideB + j * oStrideH + m * oStrideM + row * oStrideM,
672
+ dst_data + row * headSize_v,
673
+ headSize_v);
674
+ }
675
+
676
+ // Move to the next query
677
+ at::native::data_index_step(i, batchSize, j, num_head, k, qSlice);
678
+ }
679
+
680
+ at::native::cpublas::brgemm_release(need_pack);
681
+
682
+ });
683
+ }
684
+ """
685
+
686
+
687
+ class CppFlexAttentionTemplate(CppTemplate):
688
+ def __init__(
689
+ self,
690
+ input_nodes,
691
+ layout: ir.Layout,
692
+ scale,
693
+ score_mod,
694
+ mask_mod,
695
+ kv_block_size,
696
+ q_block_size,
697
+ has_other_buffer,
698
+ no_full_kv_block,
699
+ fake_buffers,
700
+ len_score_other,
701
+ len_mask_other,
702
+ kernel_input_name_to_buffer,
703
+ block_vars,
704
+ ) -> None:
705
+ assert layout.dtype in [torch.float, torch.bfloat16, torch.float16]
706
+ super().__init__("flex_attention", input_nodes, layout, parallel_num_threads())
707
+ self.scale = scale
708
+ self.score_mod = score_mod
709
+ self.mask_mod = mask_mod
710
+ self.score_buf_name = (
711
+ V.graph.register_buffer(self.score_mod) if self.score_mod else None
712
+ )
713
+ self.mask_buf_name = (
714
+ V.graph.register_buffer(self.mask_mod) if self.mask_mod else None
715
+ )
716
+
717
+ def get_idx(buf_name):
718
+ match = re.search(r"\d+", buf_name)
719
+ assert match, f"incorrect score buf name: {buf_name}"
720
+ return match.group()
721
+
722
+ self.score_buf_idx = (
723
+ get_idx(self.score_buf_name) if self.score_buf_name else None
724
+ )
725
+ self.mask_buf_idx = get_idx(self.mask_buf_name) if self.mask_buf_name else None
726
+ self.kv_block_size = kv_block_size
727
+ self.q_block_size = q_block_size
728
+ self.has_other_buffer = has_other_buffer
729
+ self.no_full_kv_block = no_full_kv_block
730
+ self.other_buffer_input_offset = 2
731
+ if self.no_full_kv_block:
732
+ self.other_buffer_input_offset = 0
733
+ self.fake_buffers = fake_buffers
734
+ self.len_score_other = len_score_other
735
+ self.len_mask_other = len_mask_other
736
+ self.kernel_input_name_to_buffer = kernel_input_name_to_buffer
737
+ self.block_vars = block_vars
738
+ self.extra_sizevars = list(
739
+ OrderedSet(
740
+ val
741
+ for val in self.kernel_input_name_to_buffer.values()
742
+ if isinstance(val, sympy.Symbol)
743
+ )
744
+ )
745
+ self.other_buf_start_idx = 5
746
+ self.score_mod_other_buffers = (
747
+ self.input_nodes[
748
+ self.other_buf_start_idx
749
+ + self.other_buffer_input_offset : self.other_buf_start_idx
750
+ + self.other_buffer_input_offset
751
+ + self.len_score_other
752
+ ]
753
+ if self.has_other_buffer
754
+ else None
755
+ )
756
+ self.mask_mod_other_buffers = (
757
+ self.input_nodes[
758
+ self.other_buf_start_idx
759
+ + self.other_buffer_input_offset
760
+ + self.len_score_other :
761
+ ]
762
+ if self.has_other_buffer
763
+ else None
764
+ )
765
+ self.other_ptr_data = {} # type: ignore[var-annotated]
766
+
767
+ def update_kernel_args(self, kernel_args):
768
+ kernel_args.update(
769
+ {
770
+ key: value
771
+ for key, value in self.kernel_input_name_to_buffer.items()
772
+ if not isinstance(value, sympy.Symbol)
773
+ }
774
+ )
775
+ return kernel_args
776
+
777
+ def generate_other_buffer(self, buf_list, start_offset, len_attr, kernel_args):
778
+ kernel_input_name_to_buffer_name = {
779
+ key: value if isinstance(value, sympy.Symbol) else value.get_name()
780
+ for key, value in self.kernel_input_name_to_buffer.items()
781
+ }
782
+
783
+ def get_arg(name):
784
+ return kernel_input_name_to_buffer_name.get(name)
785
+
786
+ def get_arg_name(name):
787
+ if isinstance(get_arg(name), sympy.Symbol):
788
+ return kernel_args.sizevars.get(get_arg(name))
789
+ return kernel_args.input_buffers.get(get_arg(name))
790
+
791
+ if not self.has_other_buffer:
792
+ return ""
793
+
794
+ if start_offset == -1:
795
+ start_offset = self.len_score_other
796
+
797
+ length = getattr(self, len_attr)
798
+ for i in range(length):
799
+ pointer = f"in_ptr{self.other_buf_start_idx + start_offset + i}"
800
+ buffer_key = f"{buf_list}_{i}"
801
+ if pointer not in self.other_ptr_data:
802
+ self.other_ptr_data[pointer] = (
803
+ get_arg_name(buffer_key),
804
+ get_arg(buffer_key),
805
+ )
806
+
807
+ return "\n".join(
808
+ f"auto {ptr} = {name};" for ptr, (name, _) in self.other_ptr_data.items()
809
+ )
810
+
811
+ def modification(self, subgraph_buffer, output_name, output_idx):
812
+ assert isinstance(subgraph_buffer, ir.ComputedBuffer)
813
+ subgraph_buffer_data = subgraph_buffer.data
814
+ from ..loop_body import LoopBody
815
+ from ..utils import sympy_index_symbol_with_prefix, SymT
816
+ from ..virtualized import V
817
+ from .cpp import CppKernelProxy, KernelGroup, ParallelDepth
818
+
819
+ kernel_group = KernelGroup()
820
+ kernel_input_args = {
821
+ "score": "in_ptr0",
822
+ "b": "in_ptr1",
823
+ "h": "in_ptr2",
824
+ "q_idx": "in_ptr3",
825
+ "kv_idx": "in_ptr4",
826
+ }
827
+ if self.has_other_buffer:
828
+ kernel_input_args.update(
829
+ {arg: ptr for ptr, (_, arg) in self.other_ptr_data.items()}
830
+ )
831
+
832
+ kernel_output_args = {output_name: f"out_ptr{output_idx}"}
833
+
834
+ args = kernel_group.args
835
+ for name, inp in kernel_input_args.items():
836
+ args.input_buffers[name] = inp
837
+
838
+ for name, inp in kernel_output_args.items():
839
+ args.output_buffers[name] = inp
840
+
841
+ for name in self.extra_sizevars:
842
+ args.sizevars[name] = f"k{name}"
843
+
844
+ kernel_group.args = args
845
+
846
+ cpp_kernel_proxy = CppKernelProxy(kernel_group)
847
+ bodies = []
848
+ var_sizes_list = []
849
+ var_sizes = tuple(subgraph_buffer.get_size())
850
+ var_ranges = {
851
+ sympy_index_symbol_with_prefix(SymT.INDEX, i): sz
852
+ for i, sz in enumerate(var_sizes)
853
+ }
854
+
855
+ dst_layout = subgraph_buffer.get_layout()
856
+ output_index = dst_layout.make_indexer()([*var_ranges.keys()])
857
+
858
+ def fn(*args):
859
+ V.ops.store(
860
+ output_name,
861
+ output_index,
862
+ subgraph_buffer_data.make_loader()(args).value,
863
+ )
864
+
865
+ body = LoopBody(
866
+ fn,
867
+ (list(var_ranges.keys())),
868
+ var_ranges,
869
+ list(var_ranges.keys()),
870
+ tuple(),
871
+ )
872
+
873
+ from ..loop_body import MemoryUsageType
874
+
875
+ assert all(
876
+ mem.buffer_name in kernel_group.args.input_buffers
877
+ for mem in body.memory_usage[MemoryUsageType.LOAD]
878
+ ), (
879
+ "All the buffers in the score and mask subgraph should be in kernel_group.args.input_buffers"
880
+ )
881
+
882
+ bodies.append(body)
883
+ var_sizes_list.append((var_sizes, ()))
884
+
885
+ cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list)
886
+
887
+ def max_parallel_depth():
888
+ return ParallelDepth(parallel_depth=0, start_depth=0)
889
+
890
+ # This loop is not parallelized since it is not the outermost loop.
891
+ with patch.object(
892
+ cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth
893
+ ):
894
+ kernel_group.finalize_kernel(cpp_kernel_proxy, [])
895
+ output_code = kernel_group.loops_code.getvalue()
896
+
897
+ var_q_symbol, var_kv_symbol = self.block_vars
898
+ # See [Note] Handle the case where the split sizes are not statically known.
899
+ # We don't know the value of qBlockSize and rkvBlockSize during compilation time
900
+ # thus we've represented them by symbols.
901
+ # We change the symbol strings back to "cur_qSplitSize" and "cur_kvSplitSize"
902
+ # in the generated code thus they'll be filled with the real value during runtime.
903
+ if var_q_symbol in kernel_group.args.sizevars:
904
+ output_code = output_code.replace(
905
+ kernel_group.args.sizevars[var_q_symbol], "cur_qSplitSize"
906
+ )
907
+ if var_kv_symbol in kernel_group.args.sizevars:
908
+ output_code = output_code.replace(
909
+ kernel_group.args.sizevars[var_kv_symbol], "cur_kvSplitSize"
910
+ )
911
+
912
+ return output_code
913
+
914
+ @staticmethod
915
+ def add_choices(
916
+ choices,
917
+ input_nodes,
918
+ layout,
919
+ scale,
920
+ score_mod,
921
+ mask_mod,
922
+ kv_block_size,
923
+ q_block_size,
924
+ has_other_buffer,
925
+ no_full_kv_block,
926
+ fake_buffers,
927
+ len_score_other,
928
+ len_mask_other,
929
+ kernel_input_name_to_buffer,
930
+ block_vars,
931
+ ):
932
+ def preprocessor(input_nodes, layout):
933
+ return input_nodes, layout
934
+
935
+ def postprocessor(output):
936
+ return output
937
+
938
+ template = DataProcessorTemplateWrapper(
939
+ CppFlexAttentionTemplate,
940
+ preprocessor,
941
+ postprocessor,
942
+ input_nodes=input_nodes,
943
+ layout=layout,
944
+ scale=scale,
945
+ score_mod=score_mod,
946
+ mask_mod=mask_mod,
947
+ kv_block_size=kv_block_size,
948
+ q_block_size=q_block_size,
949
+ has_other_buffer=has_other_buffer,
950
+ no_full_kv_block=no_full_kv_block,
951
+ fake_buffers=fake_buffers,
952
+ len_score_other=len_score_other,
953
+ len_mask_other=len_mask_other,
954
+ kernel_input_name_to_buffer=kernel_input_name_to_buffer,
955
+ block_vars=block_vars,
956
+ )
957
+ template.maybe_append_choice(choices)
958
+ return template
959
+
960
+ def apply_score_mod(self, score, b, h, q_idx, kv_idx):
961
+ return self.score_mod.graph_module(score, b, h, q_idx, kv_idx).item()
962
+
963
+ def render( # type: ignore[override,return]
964
+ self,
965
+ kernel,
966
+ template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
967
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
968
+ **kwargs,
969
+ ) -> str:
970
+ if epilogue_nodes is not None and epilogue_nodes != []:
971
+ raise NotImplementedError(
972
+ "Unsupported for `epilogue_nodes` in CppFlexAttentionTemplate."
973
+ )
974
+ # Query (Batch x Num_heads x Q_seq_len x Dim_per_head)
975
+ # -> (Batch x Q_seq_len x Num_heads x Dim_per_head)
976
+ # Key (Batch x Num_heads x KV_seq_len x Dim_per_head)
977
+ # -> (Batch x KV_seq_len x Num_heads x Dim_per_head)
978
+ # Value (Batch x Num_heads x KV_seq_len x Dim_per_head)
979
+ # -> (Batch x KV_seq_len x Num_heads x Dim_per_head)
980
+
981
+ query = kernel.permute(self.input_nodes[0], [0, 2, 1, 3])
982
+ key = kernel.permute(self.input_nodes[1], [0, 2, 1, 3])
983
+ value = kernel.permute(self.input_nodes[2], [0, 2, 1, 3])
984
+ self.accumulate_dtype = torch.float
985
+ self.input_dtype = query.layout.dtype
986
+
987
+ num_threads = parallel_num_threads()
988
+ assert isinstance(self.output_node, ir.IRNode)
989
+ buf_out = TensorBox.create(self.output_node)
990
+ if template_buffer_node is not None:
991
+ buf_out = template_buffer_node
992
+ options = dict(
993
+ query=query,
994
+ key=key,
995
+ value=value,
996
+ kv_num_blocks=self.input_nodes[3],
997
+ kv_indices=self.input_nodes[4],
998
+ full_kv_num_blocks=(
999
+ self.input_nodes[5] if not self.no_full_kv_block else None
1000
+ ),
1001
+ full_kv_indices=self.input_nodes[6] if not self.no_full_kv_block else None,
1002
+ score_mod_other_buffers=self.score_mod_other_buffers,
1003
+ mask_mod_other_buffers=self.mask_mod_other_buffers,
1004
+ scale=self.scale,
1005
+ has_full_kv_block=not self.no_full_kv_block,
1006
+ accumulate_dtype=self.accumulate_dtype,
1007
+ query_dtype=self.input_dtype,
1008
+ kvBlockSize=self.kv_block_size,
1009
+ qBlockSize=self.q_block_size,
1010
+ template=self,
1011
+ output=buf_out,
1012
+ kernel=kernel,
1013
+ num_thread=num_threads,
1014
+ score_mod=self.score_mod,
1015
+ mask_mod=self.mask_mod,
1016
+ score_buf_name=self.score_buf_name,
1017
+ mask_buf_name=self.mask_buf_name,
1018
+ score_buf_idx=self.score_buf_idx,
1019
+ mask_buf_idx=self.mask_buf_idx,
1020
+ )
1021
+ with contextlib.ExitStack() as stack:
1022
+ for buf in self.fake_buffers:
1023
+ stack.enter_context(
1024
+ patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf))
1025
+ )
1026
+ return self._template_from_string(FLEX_ATTENTION_TEMPLATE).render(**options)
1027
+
1028
+ def codegen_softmax_fusion(self, kernel_name: str):
1029
+ # TODO: use inductor IR to rewrite those fusions
1030
+ return self._template_from_string(SOFTMAX_FUSIONS).render(
1031
+ dict(kernel_name=kernel_name)
1032
+ )
1033
+
1034
+ def codegen_brgemm_pack_function(self, kernel_name: str):
1035
+ # TODO: make them general for common bmm templates
1036
+ return self._template_from_string(BRGEMM_PACK_FUNCTIONS).render(
1037
+ dict(kernel_name=kernel_name)
1038
+ )
1039
+
1040
+ def codegen_allocate_buffer(self, buffer_name: str, buffer_dtype, buffer_size):
1041
+ return self._template_from_string(ALLOCATE_BUFFER).render(
1042
+ dict(
1043
+ buffer_name=buffer_name,
1044
+ buffer_dtype=buffer_dtype,
1045
+ buffer_size=buffer_size,
1046
+ )
1047
+ )
1048
+
1049
+ def micro_gemm_define(self, kernel_name: str):
1050
+ from torch._inductor.codegen.cpp_gemm_template import (
1051
+ CppTemplateKernel,
1052
+ parallel_num_threads,
1053
+ )
1054
+ from torch._inductor.codegen.cpp_micro_gemm import CppMicroGemmFP32Vec
1055
+ from torch._inductor.virtualized import V
1056
+
1057
+ micro_gemm_trans = CppMicroGemmFP32Vec(
1058
+ kernel_name + "_kernel_micro_gemm_transpose_b",
1059
+ self.input_dtype,
1060
+ self.input_dtype,
1061
+ self.accumulate_dtype,
1062
+ self.accumulate_dtype,
1063
+ GemmBlocking(1, 16, 1),
1064
+ 1,
1065
+ True,
1066
+ True,
1067
+ )
1068
+
1069
+ micro_gemm = CppMicroGemmFP32Vec(
1070
+ kernel_name + "_kernel_micro_gemm",
1071
+ self.input_dtype,
1072
+ self.input_dtype,
1073
+ self.accumulate_dtype,
1074
+ self.accumulate_dtype,
1075
+ GemmBlocking(1, 16, 1),
1076
+ 1,
1077
+ True,
1078
+ False,
1079
+ )
1080
+
1081
+ with V.set_graph_handler(V.graph):
1082
+ kernel = CppTemplateKernel("cpp_micro_gemm", parallel_num_threads())
1083
+ code_trans = micro_gemm_trans.codegen_define(kernel)
1084
+ code = micro_gemm.codegen_define(kernel)
1085
+ return code + code_trans
1086
+
1087
+ def codegen_micro_gemm(self, kernel_name: str):
1088
+ micro_gemm = self.micro_gemm_define(kernel_name)
1089
+ GEMM_SOURCE_CODE = MICRO_GEMM_TEMPLATE.replace("GEMM_DEFINE", micro_gemm)
1090
+ return self._template_from_string(GEMM_SOURCE_CODE).render()
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_gemm_template.py ADDED
@@ -0,0 +1,1828 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import logging
4
+ import math
5
+ from collections.abc import Callable
6
+ from functools import lru_cache
7
+ from typing import Any, cast, Optional, TypeVar, Union
8
+ from unittest.mock import patch
9
+
10
+ import torch
11
+ import torch.utils
12
+ from torch.utils._ordered_set import OrderedSet
13
+
14
+ from ..._dynamo.utils import counters
15
+ from .. import config, ir, lowering as L
16
+ from ..kernel.mm_common import mm_args
17
+ from ..select_algorithm import DataProcessorTemplateWrapper
18
+ from ..utils import (
19
+ has_free_symbols,
20
+ is_same_mkldnn_tensor,
21
+ is_same_tensor,
22
+ parallel_num_threads,
23
+ )
24
+ from ..virtualized import ops, V
25
+ from .cpp import get_export_declaration
26
+ from .cpp_micro_gemm import (
27
+ CppMicroBrgemm,
28
+ CppMicroGemm,
29
+ CppMicroGemmAMX,
30
+ CppMicroGemmFP32Vec,
31
+ create_micro_gemm,
32
+ is_int8_woq_gemm_small_m_dim_corner_case,
33
+ LayoutType,
34
+ )
35
+ from .cpp_template import CppTemplate
36
+ from .cpp_template_kernel import CppTemplateKernel
37
+ from .cpp_utils import (
38
+ create_epilogue_with_attr,
39
+ DTYPE_TO_CPP,
40
+ GemmBlocking,
41
+ get_gemm_template_output_and_compute_dtype,
42
+ )
43
+
44
+
45
+ log = logging.getLogger(__name__)
46
+
47
+ GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK = r"""
48
+ constexpr int64_t num_threads = {{num_threads}};
49
+ constexpr int64_t N = {{N}};
50
+ constexpr int64_t K = {{K}};
51
+ constexpr int64_t Mr = {{micro_gemm.register_blocking.block_m}};
52
+ constexpr int64_t Nr = {{micro_gemm.register_blocking.block_n}};
53
+ constexpr int64_t Kr = {{micro_gemm.register_blocking.block_k}};
54
+ constexpr int64_t Nr_blocks = (N + Nr - 1) / Nr;
55
+ constexpr int64_t Kr_blocks = (K + Kr - 1) / Kr;
56
+ {%- if is_dynamic_M %}
57
+ const int64_t M = {{kernel.size(GemmOut, 0)}};
58
+ const int64_t Mr_blocks = (M + Mr - 1) / Mr;
59
+ {%- else %}
60
+ constexpr int64_t M = {{kernel.size(GemmOut, 0)}};
61
+ constexpr int64_t Mr_blocks = (M + Mr - 1) / Mr;
62
+ {%- endif %}
63
+ """
64
+
65
+ GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED = r"""
66
+ {%- if is_dynamic_M %}
67
+ {%- if num_threads > 1 %}
68
+ int64_t Mt_blocks, Nt_blocks, Kt_blocks;
69
+ mm_get_thread_blocking(num_threads, {{config.cpp.gemm_max_k_slices}}, M, N, K, Mr, Nr, Kr, Mt_blocks, Nt_blocks, Kt_blocks);
70
+ {%- else %}
71
+ const auto Mt_blocks = Mr_blocks;
72
+ const auto Nt_blocks = Nr_blocks;
73
+ const auto Kt_blocks = Kr_blocks;
74
+ {%- endif %}
75
+ int64_t Mc_blocks, Nc_blocks, Kc_blocks;
76
+ uint32_t L1_cache_size = {{L1_cache_size}};
77
+ uint32_t L2_cache_size = {{L2_cache_size}};
78
+ mm_get_cache_blocking<{{kernel.dtype(X)}}, {{kernel.dtype(W)}}>(
79
+ num_threads,
80
+ M,
81
+ N,
82
+ K,
83
+ Mr,
84
+ Nr,
85
+ Kr,
86
+ Mt_blocks,
87
+ Nt_blocks,
88
+ Kt_blocks,
89
+ Mc_blocks,
90
+ Nc_blocks,
91
+ Kc_blocks,
92
+ L1_cache_size,
93
+ L2_cache_size
94
+ );
95
+ const int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks;
96
+ const int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks;
97
+ const int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks;
98
+ const int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks;
99
+ const int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks;
100
+ {%- else %}
101
+ constexpr int64_t Mt_blocks = {{template.thread_blocking(num_threads).block_m}};
102
+ constexpr int64_t Nt_blocks = {{template.thread_blocking(num_threads).block_n}};
103
+ constexpr int64_t Kt_blocks = {{template.thread_blocking(num_threads).block_k}};
104
+ constexpr int64_t Mc_blocks = {{template.cache_blocking(num_threads).block_m}};
105
+ constexpr int64_t Nc_blocks = {{template.cache_blocking(num_threads).block_n}};
106
+ constexpr int64_t Kc_blocks = {{template.cache_blocking(num_threads).block_k}};
107
+ constexpr int64_t num_Mc_blocks = (Mr_blocks + Mc_blocks - 1) / Mc_blocks;
108
+ constexpr int64_t num_Nc_blocks = (Nr_blocks + Nc_blocks - 1) / Nc_blocks;
109
+ constexpr int64_t num_Mt_blocks = (Mr_blocks + Mt_blocks - 1) / Mt_blocks;
110
+ constexpr int64_t num_Nt_blocks = (Nr_blocks + Nt_blocks - 1) / Nt_blocks;
111
+ constexpr int64_t num_Kt_blocks = (Kr_blocks + Kt_blocks - 1) / Kt_blocks;
112
+ {%- endif %}
113
+ {%- if is_woq_int4 %}
114
+ int64_t group_size = *q_group_size;
115
+ {%- endif %}
116
+
117
+ // make sure all partitions are assigned
118
+ {{kernel.assert_function}}(
119
+ Mt_blocks * Nt_blocks * Kt_blocks * {{num_threads}} >= Mr_blocks * Nr_blocks * Kr_blocks,
120
+ "Not all partitions are assigned."
121
+ );
122
+ """
123
+
124
+ GEMM_TEMPLATE_MULTI_THREADS_PARAMS = r"""
125
+ const int tid = omp_get_thread_num();
126
+ const int64_t k_group_id = tid / num_Kt_blocks;
127
+ const int64_t k_slice_id = tid % num_Kt_blocks;
128
+ const int64_t n_group_id = k_group_id / num_Nt_blocks;
129
+ const int64_t n_slice_id = k_group_id % num_Nt_blocks;
130
+ const int64_t k_block_start = k_slice_id * Kt_blocks;
131
+ const int64_t k_block_end = std::min(k_block_start + Kt_blocks, Kr_blocks);
132
+ const int64_t n_block_start = n_slice_id * Nt_blocks;
133
+ const int64_t n_block_end = std::min(n_block_start + Nt_blocks, Nr_blocks);
134
+ const int64_t m_block_start = std::min(n_group_id * Mt_blocks, Mr_blocks);
135
+ const int64_t m_block_end = std::min(m_block_start + Mt_blocks, Mr_blocks);
136
+ const int64_t num_Mc_blocks_per_thread = (m_block_end - m_block_start + Mc_blocks - 1) / Mc_blocks;
137
+ """
138
+
139
+ GEMM_TEMPLATE_SINGLE_THREAD_PARAMS = r"""
140
+ constexpr int tid = 0;
141
+ constexpr int64_t k_group_id = 0;
142
+ constexpr int64_t k_slice_id = 0;
143
+ constexpr int64_t n_group_id = 0;
144
+ constexpr int64_t n_slice_id = 0;
145
+ constexpr int64_t m_block_start = 0;
146
+ constexpr int64_t n_block_start = 0;
147
+ constexpr int64_t n_block_end = Nr_blocks;
148
+ constexpr int64_t k_block_start = 0;
149
+ constexpr int64_t k_block_end = Kr_blocks;
150
+ {%- if is_dynamic_M %}
151
+ const int64_t num_Mc_blocks_per_thread = num_Mc_blocks;
152
+ const int64_t m_block_end = Mr_blocks;
153
+ {%- else %}
154
+ constexpr int64_t num_Mc_blocks_per_thread = num_Mc_blocks;
155
+ constexpr int64_t m_block_end = Mr_blocks;
156
+ {%- endif %}
157
+ """
158
+
159
+ GEMM_TEMPLATE_M_LOOP_PARAMS = r"""
160
+ const int64_t my_mc_block_id = (mc_block_id + n_slice_id) % num_Mc_blocks_per_thread;
161
+ const int64_t mc = m_block_start + my_mc_block_id * Mc_blocks;
162
+ const int64_t m_start = mc * Mr;
163
+ const int64_t m_end = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M);
164
+ const int64_t m_size = m_end - m_start;
165
+ """
166
+
167
+ GEMM_TEMPLATE_N_LOOP_PARAMS = r"""
168
+ const int64_t n_start = nc * Nr;
169
+ const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N);
170
+ const int64_t n_size = n_end - n_start;
171
+ // NB: assume we pad N, nc_block_end won't exceed padded N here.
172
+ const int64_t nc_block_end = std::min(nc + Nc_blocks, n_block_end);
173
+ """
174
+
175
+ GEMM_TEMPLATE_MICROKERNEL_DEF = r"""
176
+ {{template.header().getvalue()}}
177
+
178
+ {{micro_gemm.codegen_define(kernel)}}
179
+ """
180
+
181
+ GEMM_TEMPLATE_STUB_DEF = r"""
182
+ {%- if x_scale is not none %}
183
+ {%- set kernel_args = {"X": X, "W": W, "inp": inp, "x_scale": x_scale, "x_zp": x_zp, "w_scale": w_scale, "w_zp": w_zp,} %}
184
+ {%- elif is_woq_int4 %}
185
+ {%- set kernel_args = {"X": X, "W": W, "q_group_size": q_group_size, "qscale_and_zeros": qscale_and_zeros} %}
186
+ {%- else %}
187
+ {%- set kernel_args = {"X": X, "W": W, "inp": inp} %}
188
+ {%- endif %}
189
+
190
+ extern "C" {{export_declaration}}
191
+ {{kernel.def_kernel(inputs=kernel_args, outputs={"Y": Y}, aliases=aliases)}}
192
+ """
193
+
194
+ GEMM_TEMPLATE = r"""
195
+ {{ template.codegen_gemm_stub_def() }}
196
+ {
197
+ {{ kernel.maybe_codegen_profile() }}
198
+ {{ template.codegen_blocks(
199
+ num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W
200
+ ) }}
201
+
202
+ {%- if maybe_k_slicing %}
203
+ std::unique_ptr<std::unique_ptr<{{DTYPE_TO_CPP[acc_buf_dtype]}}[]>[]> local_buf_ptrs;
204
+ if (num_Kt_blocks > 1) {
205
+ local_buf_ptrs.reset(new std::unique_ptr<{{DTYPE_TO_CPP[acc_buf_dtype]}}[]>[num_Mc_blocks * num_Nc_blocks * num_Kt_blocks]);
206
+ }
207
+ {%- endif %}
208
+
209
+ {%- if num_threads > 1 %}
210
+ #pragma omp parallel num_threads({{num_threads}})
211
+ {
212
+ {{ template.codegen_multi_threads_params()|indent(8, false) }}
213
+ {%- else %}
214
+ {
215
+ {{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }}
216
+ {%- endif %}
217
+ {{ micro_gemm.codegen_init(kernel) }}
218
+ {%- if use_local_acc %}
219
+ {%- set acc_buf_name = "local_acc_buf" %}
220
+ {{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }}
221
+ {%- endif %}
222
+ for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) {
223
+ {{ template.codegen_m_loop_params()|indent(12, false) }}
224
+ for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) {
225
+ {{ template.codegen_n_loop_params()|indent(16, false) }}
226
+ {%- if use_local_acc %}
227
+ {%- set acc = kernel.local_buffers[acc_buf_name] %}
228
+ {{ kernel.reinit_buffer_if_null(acc_buf_name) }}
229
+ {%- else %}
230
+ {%- set acc = kernel.slice_nd(GemmOut, [("m_start", "m_end"), ("n_start", "n_end")]) %}
231
+ {%- endif %}
232
+ for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) {
233
+ int64_t k_start = kc * Kr;
234
+ int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K);
235
+ {%- set tile_X = kernel.slice_nd(X, [("m_start", "m_end"), ("k_start", "k_end")]) %}
236
+ for (int64_t nci = nc; nci < nc_block_end; nci++) {
237
+ {%- set acc_slice = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")]) %}
238
+ {%- if template.should_block_weights and not is_woq_int4 %}
239
+ {%- set tile_W_3d = kernel.slice_nd(W, [("nci", "nci + 1"), ("k_start", "k_end"), ()]) %}
240
+ {%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %}
241
+ {%- else %}
242
+ {%- if is_woq_int4 %}
243
+ {%- set tile_W = kernel.slice_nd(W, [("nci * Nr", "(nci + 1) * Nr"), ("k_start * Nr / 2", "k_end * Nr / 2")]) %}
244
+ {%- set tile_qparam = kernel.slice_nd(
245
+ qscale_and_zeros, [("k_start // group_size", "k_end // group_size"), ("nci * Nr", "(nci + 1) * Nr"), ()]) %}
246
+ {%- else %}
247
+ {%- set tile_W = kernel.slice_nd(W, [("k_start", "k_end"), ("n_start", "n_start + n_size")]) %}
248
+ {%- set tile_qparam = None %}
249
+ {%- endif %}
250
+ {%- endif %}
251
+ if (kc == k_block_start) {
252
+ {{ micro_gemm.codegen_call(kernel,
253
+ tile_X,
254
+ tile_W,
255
+ acc_slice,
256
+ accum=False,
257
+ qscale_and_zeros=tile_qparam)|indent(28, false)
258
+ }}
259
+ } else {
260
+ {{ micro_gemm.codegen_call(kernel,
261
+ tile_X,
262
+ tile_W,
263
+ acc_slice,
264
+ accum=True,
265
+ qscale_and_zeros=tile_qparam)|indent(28, false)
266
+ }}
267
+ }
268
+ }
269
+ }
270
+ {%- if maybe_k_slicing %}
271
+ if (num_Kt_blocks > 1) {
272
+ const int64_t mxn_cache_block_id = (mc / Mc_blocks) * num_Nc_blocks + nc;
273
+ local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + k_slice_id].reset(
274
+ {{ kernel.release_buffer(acc_buf_name) }});
275
+ } else
276
+ {%- endif %}
277
+ {
278
+ {%- set tile_Y = kernel.slice_nd(Y_2d, [("m_start", "m_end"), ("n_start", "n_end")]) %}
279
+ {%- set tile_acc = kernel.slice_nd(acc, [("0", "m_end - m_start"), ("0", "n_end - n_start")]) %}
280
+ {{ kernel.store_output(
281
+ tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers
282
+ )|indent(20, false)
283
+ }}
284
+ }
285
+ }
286
+ }
287
+ {%- if maybe_k_slicing %}
288
+ if (num_Kt_blocks > 1) {
289
+ #pragma omp barrier
290
+ for (int64_t mc = m_block_start; mc < m_block_end; mc += Mc_blocks) {
291
+ // We slice M-dim and each thread in the k-slicing group works on a slice
292
+ const int64_t m_start_unsliced = mc * Mr;
293
+ const int64_t m_end_unsliced = std::min(std::min(mc + Mc_blocks, m_block_end) * Mr, M);
294
+ const int64_t m_size_unsliced = m_end_unsliced - m_start_unsliced;
295
+ const int64_t m_slice_size = (m_size_unsliced + num_Kt_blocks - 1) / num_Kt_blocks;
296
+ const int64_t m_start = std::min(m_start_unsliced + m_slice_size * k_slice_id, m_end_unsliced);
297
+ const int64_t m_end = std::min(m_start_unsliced + m_slice_size * (k_slice_id + 1), m_end_unsliced);
298
+ const int64_t m_size = m_end - m_start;
299
+ const int64_t m_offset = m_start - m_start_unsliced;
300
+ for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) {
301
+ const int64_t n_start = nc * Nr;
302
+ const int64_t n_end = std::min(std::min(nc + Nc_blocks, n_block_end) * Nr, N);
303
+ const int64_t n_size = n_end - n_start;
304
+ const int64_t mxn_cache_block_id = (mc / Mc_blocks) * num_Nc_blocks + nc;
305
+ auto {{acc_buf_name}} = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks].get();
306
+ for (int64_t other_slice = 1; other_slice < num_Kt_blocks; other_slice++) {
307
+ auto other_acc = local_buf_ptrs[mxn_cache_block_id * num_Kt_blocks + other_slice].get();
308
+ for (int64_t m = m_offset; m < m_offset + m_size; m++) {
309
+ #pragma omp simd
310
+ for (int64_t n = 0; n < n_size; n++) {
311
+ {{acc_buf_name}}[m*Nr + n] += other_acc[m*Nr + n];
312
+ }
313
+ }
314
+ }
315
+ {%- set tile_acc_m_slice = kernel.slice_nd(tile_acc, [("m_offset", "m_offset + m_end - m_start"), ()]) %}
316
+ {{ kernel.store_output(
317
+ tile_Y, tile_acc_m_slice, GemmOut, epilogue_nodes, offsets=("m_start", "n_start"), reindexers=reindexers
318
+ )|indent(20, false)
319
+ }}
320
+ }
321
+ }
322
+ }
323
+ {%- endif %}
324
+ {{ micro_gemm.codegen_finalize(kernel) }}
325
+ }
326
+ }
327
+ """
328
+
329
+ SMALL_M_GEMM_TEMPLATE = r"""
330
+ {{ template.codegen_gemm_stub_def() }}
331
+ {
332
+ {{ kernel.maybe_codegen_profile() }}
333
+ {{ template.codegen_blocks(
334
+ num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOut, config, L1_cache_size, L2_cache_size, X, W
335
+ ) }}
336
+ # pragma omp parallel
337
+ {
338
+ #pragma omp for nowait
339
+ for (int64_t nr_block_id = 0; nr_block_id < Nr_blocks; nr_block_id++) {
340
+ // Handle one output M * Nr block in each thread
341
+ int64_t n_start = nr_block_id * Nr;
342
+ int64_t n_end = (nr_block_id + 1) * Nr;
343
+ {%- if use_local_acc %}
344
+ {%- set acc_buf_name = "local_acc_buf" %}
345
+ {{ kernel.define_stack_allocated_buffer(acc_buf_name, ["M", "Nr"], acc_buf_dtype) }}
346
+ {%- set acc = kernel.local_buffers[acc_buf_name] %}
347
+ {%- else %}
348
+ {%- set acc = kernel.slice_nd(GemmOut, [(0, "M"), ("n_start", "n_end")]) %}
349
+ {%- endif %}
350
+ for (int64_t kr_block_id = 0; kr_block_id < Kr_blocks; kr_block_id++) {
351
+ // this loop is not parallelized
352
+ int64_t k_start = kr_block_id * Kr;
353
+ int64_t k_end = std::min((kr_block_id + 1) * Kr, K);
354
+ {%- set tile_X = kernel.slice_nd(X, [(0, "M"), ("k_start", "k_end")]) %}
355
+ {%- set tile_W_3d = kernel.slice_nd(W, [("nr_block_id", "nr_block_id + 1"), ("k_start", "k_end"), ()]) %}
356
+ {%- set tile_W = kernel.view(tile_W_3d, ["k_end - k_start", micro_gemm.register_blocking.block_n]) %}
357
+ if C10_UNLIKELY(kr_block_id == 0) {
358
+ {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=False, prefetch=True)|indent(20, false) }}
359
+ } else if C10_UNLIKELY(k_end == K) {
360
+ {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=False)|indent(20, false) }}
361
+ } else {
362
+ {{ micro_gemm.codegen_call(kernel, tile_X, tile_W, acc, accum=True, prefetch=True)|indent(20, false) }}
363
+ }
364
+ }
365
+ {%- set tile_Y = kernel.slice_nd(Y_2d, [("0", "M"), ("n_start", "n_end")]) %}
366
+ {%- set tile_acc = kernel.slice_nd(acc, [("0", "M"), ("0", "n_end - n_start")]) %}
367
+ {{ kernel.store_output(
368
+ tile_Y, tile_acc, GemmOut, epilogue_nodes, offsets=("0", "n_start"), reindexers=reindexers
369
+ )|indent(20, false) }}
370
+ }
371
+ }
372
+ }
373
+ """
374
+
375
+
376
+ def _is_int8_gemm(inputs):
377
+ return (
378
+ isinstance(inputs[0], ir.IRNode)
379
+ and inputs[0].get_dtype() in [torch.uint8, torch.int8]
380
+ ) or (
381
+ isinstance(inputs[0], torch.Tensor)
382
+ and inputs[0].dtype in [torch.uint8, torch.int8]
383
+ )
384
+
385
+
386
+ def get_padded_n(n, block_n):
387
+ return (n + block_n - 1) // block_n * block_n
388
+
389
+
390
+ _T = TypeVar("_T", ir.IRNode, torch.Tensor)
391
+
392
+
393
+ def transpose_w(W: _T, trans_w: bool) -> _T:
394
+ """
395
+ Transpose W based on the trans_w flag.
396
+ """
397
+ if isinstance(W, ir.IRNode):
398
+ if trans_w:
399
+ if not isinstance(W, ir.TensorBox):
400
+ # pyrefly: ignore [bad-assignment]
401
+ W = ir.TensorBox(W)
402
+ W = L.permute(W, [1, 0])
403
+ else:
404
+ if trans_w:
405
+ assert isinstance(W, torch.Tensor)
406
+ # pyrefly: ignore [bad-assignment]
407
+ W = W.transpose(0, 1)
408
+ # pyrefly: ignore [bad-return]
409
+ return W
410
+
411
+
412
+ def expand_bias(B: Optional[_T], X: _T) -> Optional[_T]:
413
+ """
414
+ Expand Bias to the same size of X.
415
+ """
416
+ if B is not None:
417
+ if isinstance(B, ir.IRNode):
418
+ if not isinstance(B, ir.TensorBox):
419
+ # pyrefly: ignore [bad-assignment]
420
+ B = ir.TensorBox(B)
421
+ assert hasattr(X, "get_size")
422
+ # pyrefly: ignore [missing-attribute]
423
+ B = L.expand(B, (X.get_size()[0], B.get_size()[-1]))
424
+ else:
425
+ assert isinstance(B, torch.Tensor)
426
+ assert isinstance(X, torch.Tensor)
427
+ # pyrefly: ignore [bad-assignment]
428
+ B = B.expand(X.shape[0], B.shape[-1])
429
+ return B
430
+
431
+
432
+ def prune_tensors(input_nodes: list[ir.IRNode], new_input_nodes: list[ir.IRNode]):
433
+ """
434
+ Prune unused tensors from `V.graph` since the GEMM Template use new packed weight.
435
+ """
436
+
437
+ def share_storage(base_tensor: torch.Tensor, comp_tensor: torch.Tensor):
438
+ return base_tensor.is_mkldnn == comp_tensor.is_mkldnn and (
439
+ is_same_tensor(base_tensor, comp_tensor)
440
+ or is_same_mkldnn_tensor(base_tensor, comp_tensor)
441
+ )
442
+
443
+ def get_candidates(input_nodes, new_input_nodes):
444
+ # Only Constant Buffer like weight and bias might be changed in GEMM Template.
445
+ # The Inductor IR Node may changed, but still share the storage. For example:
446
+ # bias in bfloat16 case which only do the expand
447
+ return [
448
+ node
449
+ for node in input_nodes
450
+ if (
451
+ node not in new_input_nodes
452
+ and isinstance(node, (ir.TensorBox, ir.StorageBox))
453
+ and node.get_name() in V.graph.constants
454
+ and not any(
455
+ (
456
+ isinstance(new_node, (ir.TensorBox, ir.StorageBox))
457
+ and new_node.get_name() in V.graph.constants
458
+ and share_storage(
459
+ V.graph.constants[node.get_name()],
460
+ V.graph.constants[new_node.get_name()],
461
+ )
462
+ )
463
+ for new_node in new_input_nodes
464
+ )
465
+ )
466
+ ]
467
+
468
+ for candidate_node in get_candidates(input_nodes, new_input_nodes):
469
+ # By using the new packed weight for the GEMM template, we can prune the
470
+ # old weight if it has no other users. This saves memory but makes the FX graph
471
+ # non-retraceable. To support retracing, we can add a repack node to the
472
+ # FX graph. For example:
473
+ # mkldnn._linear_pointwise <- repack_linear_wgt <- packed_wgt_for_template
474
+ candidate_tensor_users = 0
475
+ candidate_tensor = V.graph.constants[candidate_node.get_name()]
476
+ for node in reversed(V.graph.graph.nodes):
477
+ # Case may happen when the candidate tensor is used by more than 1 get_attr node
478
+ # https://github.com/pytorch/pytorch/issues/134998
479
+ if node.op == "get_attr" and hasattr(
480
+ V.graph.module, node.target
481
+ ): # candidate tensor might already be deleted
482
+ comp_tensor = getattr(V.graph.module, node.target)
483
+ if isinstance(comp_tensor, torch.Tensor) and share_storage(
484
+ candidate_tensor, comp_tensor
485
+ ):
486
+ candidate_tensor_users += 1
487
+
488
+ for node in reversed(V.graph.graph.nodes):
489
+ # The get_attr node has only 1 user fx node
490
+ # The candidate tensor has been used by only 1 get_attr node
491
+ if (
492
+ node.op == "get_attr"
493
+ and node.target == candidate_node.get_name()
494
+ and len(node.users) == 1
495
+ and candidate_tensor_users == 1
496
+ ):
497
+ del V.graph.constants[node.target]
498
+ delattr(V.graph.module, node.target)
499
+ delattr(V.graph.graph.owning_module, node.target)
500
+ counters["inductor"]["select_algorithm_weight_prune"] += 1
501
+
502
+
503
+ def gen_2d_view_of_epilogue_buf(
504
+ Y: ir.Buffer,
505
+ template_buffer: ir.Buffer,
506
+ epilogue_nodes: list[ir.IRNode],
507
+ reindexers: list[Optional[Callable[[list[Any]], list[Any]]]],
508
+ default_reindexers: list[Optional[Callable[[list[Any]], list[Any]]]],
509
+ ) -> tuple[
510
+ Union[ir.Buffer, ir.ReinterpretView],
511
+ list[Optional[Callable[[list[Any]], list[Any]]]],
512
+ ]:
513
+ """
514
+ The dimension and the indexing could be different between the GEMM output, i.e. `template_buffer`, which is
515
+ 2D with MxN) and the output from the template after epilogues, i.e. `Y`. In the GEMM template code,
516
+ we are not aware of the dimension and the indexing of the epilogues and always work on 2D tiles according to
517
+ the indexing of the GEMM output.
518
+ In this function, we return a 2D buffer (`Y_2d`) according to GEMM output (reinterpreted from `Y` if needed) and
519
+ build a reindexer that converts the indexing of `Y` into `Y_2d`.
520
+ """
521
+ Y_2d: Union[ir.Buffer, ir.ReinterpretView] = Y
522
+ if (
523
+ Y.get_size() == template_buffer.get_size()
524
+ and Y.get_stride() == template_buffer.get_stride()
525
+ ):
526
+ reindexers.extend(default_reindexers)
527
+ Y_2d = Y
528
+ else:
529
+
530
+ def get_reindexer(epilogue_node, default_reindexer=None):
531
+ # From template_buffer to epilogue_node_ordered (ordered by stride decreasingly, in dense format), for example:
532
+ # template_buffer:
533
+ # size (324, 512), stride (512, 1)
534
+ # epilogue_node_ordered (ordered by stride decreasingly, in dense format):
535
+ # size (1, 18, 18, 512), stride (165888, 9216, 512, 1)
536
+ stride_order = list(
537
+ ir.get_stride_order(
538
+ V.graph.sizevars.size_hints(epilogue_node.get_stride())
539
+ )
540
+ )
541
+ fill_order = ir.stride_order2fill_order(stride_order)
542
+ reversed_fill_order = list(reversed(fill_order))
543
+ size_with_stride_ordered_decreasingly = [
544
+ epilogue_node.get_size()[i] for i in reversed_fill_order
545
+ ]
546
+ reshape_reindex = ir.View.dynamic_reshape_indexer(
547
+ size_with_stride_ordered_decreasingly,
548
+ template_buffer.get_size(),
549
+ )
550
+ if default_reindexer:
551
+ reshape_reindex = ir.fuse_reindexing(reshape_reindex, default_reindexer)
552
+
553
+ # From epilogue_node_ordered (ordered by stride decreasingly, in dense format) to epilogue_node, for example:
554
+ # epilogue_node_ordered (ordered by stride decreasingly, in dense format):
555
+ # size (1, 18, 18, 512), stride (165888, 9216, 512, 1)
556
+ # epilogue_node:
557
+ # size (1, 18, 18, 512), stride (165888, 1, 9216, 512)
558
+ from_stride_ordered_decreasingly_to_epilogue_node_order = [
559
+ (len(stride_order) - 1) - stride_order[i]
560
+ for i in range(len(stride_order))
561
+ ]
562
+ stride_reindex = ir.same_reorder(
563
+ from_stride_ordered_decreasingly_to_epilogue_node_order
564
+ )
565
+
566
+ reindexer = ir.fuse_reindexing(stride_reindex, reshape_reindex) # type: ignore[var-annotated]
567
+ return reindexer
568
+
569
+ if default_reindexers is None:
570
+ default_reindexers = [None] * len(epilogue_nodes)
571
+ new_reindexers = [
572
+ get_reindexer(epilogue_node, default_reindexer)
573
+ for epilogue_node, default_reindexer in zip(
574
+ epilogue_nodes, default_reindexers
575
+ )
576
+ ]
577
+ reindexers.extend(new_reindexers)
578
+ if isinstance(Y, ir.BaseView):
579
+ storage = ir.StorageBox(Y.unwrap_view())
580
+ else:
581
+ assert isinstance(Y, ir.Buffer)
582
+ storage = ir.StorageBox(Y)
583
+ Y_2d = ir.ReinterpretView(data=storage, layout=template_buffer.get_layout())
584
+ return Y_2d, reindexers
585
+
586
+
587
+ class CppGemmTemplate(CppTemplate):
588
+ """
589
+ GEMM Template for Inductor CPP Backend.
590
+ """
591
+
592
+ def __init__(
593
+ self,
594
+ input_nodes,
595
+ layout: ir.Layout,
596
+ num_threads: int,
597
+ register_blocking: GemmBlocking,
598
+ beta=1,
599
+ alpha=1,
600
+ has_bias=False,
601
+ epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
602
+ should_block_weights: bool = True,
603
+ name="packed_gemm",
604
+ ) -> None:
605
+ assert layout.dtype in [
606
+ torch.float,
607
+ torch.bfloat16,
608
+ torch.half,
609
+ torch.uint8,
610
+ torch.int8,
611
+ ]
612
+ super().__init__(
613
+ name,
614
+ input_nodes,
615
+ layout,
616
+ num_threads,
617
+ epilogue_creator=epilogue_creator,
618
+ )
619
+ self.beta = beta
620
+ self.alpha = alpha
621
+ self.has_bias = has_bias
622
+ self.register_blocking = register_blocking
623
+ m, n = layout.size[-2:]
624
+ k = input_nodes[0].get_size()[-1]
625
+ self.m, self.n, self.k = m, n, k
626
+ self.padded_n = get_padded_n(n, self.register_blocking.block_n)
627
+ self.is_dynamic_M = has_free_symbols((m,))
628
+ self.should_block_weights = should_block_weights
629
+ self.thread_blocking = self.make_thread_blocking_cache()
630
+ self.cache_blocking = self.make_cache_blocking_cache()
631
+
632
+ def make_thread_blocking_cache(self):
633
+ cache = lru_cache()(self._thread_blocking)
634
+
635
+ def thread_blocking(num_threads: int) -> GemmBlocking:
636
+ return cache(num_threads)
637
+
638
+ return thread_blocking
639
+
640
+ def _thread_blocking(self, num_threads: int) -> GemmBlocking:
641
+ """
642
+ NOTE [Thread blocking in Cpp GEMM]
643
+ We use simple heuristics to decide the thread blocking:
644
+ 1. Make sure all threads are occupied as much as possible.
645
+ 2. For (m, n) blocks, favor more square-sized thread blocks for better data reuse.
646
+ 3. If (m, n) blocks cannot occupy all the threads, we consider k-slicing.
647
+ TODO(jgong5): allow tuning various blocking options
648
+ """
649
+
650
+ def get_factors(number):
651
+ factors = []
652
+ for i in range(int(number**0.5), 0, -1):
653
+ if number % i == 0:
654
+ factors.append(number // i)
655
+ factors.append(i)
656
+ return factors
657
+
658
+ def get_blocking(m_factor, n_factor, k_factor, m_blocks, n_blocks, k_blocks):
659
+ thread_block_k = math.ceil(k_blocks / k_factor)
660
+ thread_block_n = math.ceil(n_blocks / n_factor)
661
+ thread_block_m = math.ceil(m_blocks / m_factor)
662
+ return GemmBlocking(thread_block_m, thread_block_n, thread_block_k)
663
+
664
+ assert not self.is_dynamic_M, (
665
+ "Unable to determine thread blocking for dynamic M."
666
+ )
667
+ register_blocking = self.register_blocking
668
+ m_blocks = math.ceil(self.m / register_blocking.block_m)
669
+ n_blocks = math.ceil(self.n / register_blocking.block_n)
670
+ k_blocks = math.ceil(self.k / register_blocking.block_k)
671
+ factors = get_factors(num_threads)
672
+ assert len(factors) > 0
673
+
674
+ if config.cpp.gemm_thread_factors is not None:
675
+ factors = [int(i) for i in config.cpp.gemm_thread_factors.split(",")]
676
+ assert len(factors) == 3
677
+ assert math.prod(factors) == self.num_threads
678
+ return get_blocking(
679
+ factors[0], factors[1], factors[2], m_blocks, n_blocks, k_blocks
680
+ )
681
+
682
+ # we favor square-sized thread blocks for good data reuse
683
+ def get_better_blocking(blocking, best_blocking):
684
+ if best_blocking is None:
685
+ best_blocking = blocking
686
+ else:
687
+ block_m_size = blocking.block_m * register_blocking.block_m
688
+ block_n_size = blocking.block_n * register_blocking.block_n
689
+ best_block_m_size = best_blocking.block_m * register_blocking.block_m
690
+ best_block_n_size = best_blocking.block_n * register_blocking.block_n
691
+ if blocking.block_k > best_blocking.block_k:
692
+ best_blocking = blocking
693
+ elif (
694
+ blocking.block_k == best_blocking.block_k
695
+ and block_m_size + block_n_size
696
+ < best_block_m_size + best_block_n_size
697
+ ):
698
+ best_blocking = blocking
699
+ return best_blocking
700
+
701
+ best_blocking = None
702
+ # check if we can have a thread-blocking to occupy all threads without k-slicing
703
+ for n_factor in factors:
704
+ m_factor = num_threads // n_factor
705
+ if n_blocks >= n_factor and m_blocks >= m_factor:
706
+ blocking = get_blocking(
707
+ m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks
708
+ )
709
+ best_blocking = get_better_blocking(blocking, best_blocking)
710
+
711
+ if best_blocking is None:
712
+ for k_factor in factors:
713
+ if k_blocks >= k_factor and (
714
+ config.cpp.gemm_max_k_slices == 0
715
+ or k_factor <= config.cpp.gemm_max_k_slices
716
+ ):
717
+ n_factors = get_factors(num_threads // k_factor)
718
+ for n_factor in n_factors:
719
+ m_factor = (num_threads // k_factor) // n_factor
720
+ if n_blocks >= n_factor and m_blocks >= m_factor:
721
+ blocking = get_blocking(
722
+ m_factor,
723
+ n_factor,
724
+ k_factor,
725
+ m_blocks,
726
+ n_blocks,
727
+ k_blocks,
728
+ )
729
+ best_blocking = get_better_blocking(blocking, best_blocking)
730
+
731
+ if best_blocking is None:
732
+ for n_factor in factors:
733
+ m_factor = num_threads // n_factor
734
+ if n_blocks >= n_factor or m_blocks >= m_factor:
735
+ blocking = get_blocking(
736
+ m_factor, n_factor, 1, m_blocks, n_blocks, k_blocks
737
+ )
738
+ best_blocking = get_better_blocking(blocking, best_blocking)
739
+
740
+ assert best_blocking is not None
741
+ return best_blocking
742
+
743
+ def make_cache_blocking_cache(self):
744
+ cache = lru_cache()(self._cache_blocking)
745
+
746
+ def cache_blocking(num_threads: int) -> GemmBlocking:
747
+ return cache(num_threads)
748
+
749
+ return cache_blocking
750
+
751
+ def _cache_blocking(self, num_threads: int) -> GemmBlocking:
752
+ def get_cache_blocking(register_blocking, thread_blocking):
753
+ Mr = register_blocking.block_m
754
+ Nr = register_blocking.block_n
755
+ Kr = register_blocking.block_k
756
+
757
+ Mt_blocks = thread_blocking.block_m
758
+ Nt_blocks = thread_blocking.block_n
759
+ Kt_blocks = thread_blocking.block_k
760
+
761
+ if config.cpp.gemm_cache_blocking is not None:
762
+ blockings = [int(i) for i in config.cpp.gemm_cache_blocking.split(",")]
763
+ assert len(blockings) == 3
764
+ Mc_blocks, Nc_blocks, Kc_blocks = blockings
765
+ return (
766
+ min(Mc_blocks, Mt_blocks),
767
+ min(Nc_blocks, Nt_blocks),
768
+ min(Kc_blocks, Kt_blocks),
769
+ )
770
+
771
+ # The ratios below are empirically determined to decide
772
+ # the effective sizes of L1 and L2.
773
+ # TODO: tune the factor here
774
+ L1_limit_factor = 0.8
775
+ L2_limit_factor = 0.5
776
+
777
+ L1_cache_size = torch.cpu.get_capabilities().get(
778
+ "l1d_cache_size", 0
779
+ ) # per core cache size in Bytes
780
+ assert L1_cache_size > 0, (
781
+ f"Expect L1_cache_size > 0 but got {L1_cache_size}"
782
+ )
783
+ L1 = L1_cache_size * L1_limit_factor
784
+
785
+ L2_cache_size = torch.cpu.get_capabilities().get(
786
+ "l2_cache_size", 0
787
+ ) # per core cache size in Bytes
788
+ assert L2_cache_size > 0, (
789
+ f"Expect L2_cache_size > 0 but got {L2_cache_size}"
790
+ )
791
+ L2 = L2_cache_size * L2_limit_factor
792
+
793
+ def get_num_byte(dtype):
794
+ return torch.tensor([], dtype=dtype).element_size()
795
+
796
+ dtype_A = self.input_nodes[0].get_dtype()
797
+ dtype_B = self.input_nodes[1].get_dtype()
798
+ num_byte_A = get_num_byte(dtype_A)
799
+ num_byte_B = get_num_byte(dtype_B)
800
+ if dtype_A is torch.bfloat16 and dtype_B is torch.int8 and Kr != 1:
801
+ # We will cache dequantized weights (BF16) in L1D for AMX micro-kernel.
802
+ # In this case, the choice of the micro-kernel being used can't be decoupled from
803
+ # the cache blocking.
804
+ # TODO: Decouple the choice of micro-kernel from cache blocking
805
+ num_byte_B *= num_byte_A
806
+
807
+ # NOTE [CPP GEMM Cache Blocking Algorithm]
808
+ # Our overall strategy is to
809
+ # 1) Make cache blocks of B L1-reside and reused by multiple rows of A, i.e. Mc.
810
+ # Here, B is Kc x Nr where Nr is a single register block. We use L1 size to
811
+ # decide Kc. We want to make Mc large enough to better reuse B.
812
+ # 2) Make cache blocks of A L2-reside, which would limit Mc. We want to reuse A
813
+ # along N, where we have two sub-strategies (see notes below) to decide Mc and Nc.
814
+
815
+ # Step 1: Decide Kc assuming B block is L1-reside.
816
+ size_cache_B = Kr * Kt_blocks * Nr * num_byte_B
817
+
818
+ Kc_blocks = Kt_blocks
819
+ if size_cache_B > L1:
820
+ Kc_blocks = math.floor(L1 / (Kr * Nr * num_byte_B))
821
+
822
+ if (
823
+ config.cpp.use_small_dequant_buffer
824
+ and dtype_A is torch.bfloat16
825
+ and Mt_blocks == 1
826
+ ):
827
+ if dtype_B is torch.uint8:
828
+ # A16W4
829
+ # Make a small dequant_B buffer for woq int4 [q_group_size, Nr]
830
+ # Since when Mt_blocks == 1, L1-reside B block can't be reused by A.
831
+ if Kc_blocks * Kr >= self.q_group_size():
832
+ Kc_blocks = self.q_group_size() // Kr
833
+
834
+ elif dtype_B is torch.int8:
835
+ # A16W8
836
+ # Make A, B, C buffer in L1
837
+ A_buf_size_div_K = self.m * num_byte_A
838
+ B_buf_size_div_K = Nr * num_byte_B
839
+ # assume acc in float32/int32 and Mc_blocks = Nc_blocks = 1
840
+ C_buf_size = Mr * Nr * 4
841
+ K_block_size = (L1 - C_buf_size) // (
842
+ A_buf_size_div_K + B_buf_size_div_K
843
+ )
844
+ if Kc_blocks * Kr >= K_block_size:
845
+ Kc_blocks = (K_block_size + Kr - 1) // Kr
846
+
847
+ # Step 2: Decide Mc assuming A block is L2-reside.
848
+ min_Mc_ratio = 2 # TODO(jgong5): something to tune?
849
+ min_Mc_blocks = math.ceil(min_Mc_ratio * Mr / Nr)
850
+ assert min_Mc_blocks >= 1
851
+ Kt_bytes = Kt_blocks * Kr * num_byte_A
852
+ if min_Mc_blocks * Mr * Kt_bytes < L2:
853
+ # Strategy 1: A (Mc x Kt) resides in L2 and reused by all Nt
854
+ # when Nc_blocks is kept 1. Mc should be large enough (>= min_Mc_blocks)
855
+ # to reuse B (Kc x Nr) in L1. This makes C (Mc x Nr) small enough to reside
856
+ # in L1.
857
+ Mc_blocks = min(Mt_blocks, math.floor(L2 / (Mr * Kt_bytes)))
858
+ Nc_blocks = 1
859
+ else:
860
+ # Strategy 2: Kt is too large to hold A (Mc x Kt) in L2, we reuse
861
+ # A (Mc x Kc) in L2 by B (Kc x Nc). C (Mc x Nc) resides in L2.
862
+ Mc_blocks = Mt_blocks
863
+ Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks)
864
+ Nc_bytes = Nc_blocks * Nr * 4 # assume C or acc is float32/int32
865
+ Kc_bytes = Kc_blocks * Kr * num_byte_A
866
+ if Mc_blocks * Mr * (Kc_bytes + Nc_bytes) > L2:
867
+ # The following is the solution for 4*Mc*Nc + Mc*Kc_bytes = L2,
868
+ # assuming Mc == Nc for good data reuse.
869
+ M_max = (math.sqrt(Kc_bytes * Kc_bytes + 16 * L2) - Kc_bytes) / 8
870
+ if M_max < Mc_blocks * Mr:
871
+ Mc_blocks = math.floor(M_max / Mr)
872
+ Nc_blocks = min(math.ceil(Mc_blocks * Mr / Nr), Nt_blocks)
873
+
874
+ return Mc_blocks, Nc_blocks, Kc_blocks
875
+
876
+ assert not self.is_dynamic_M, (
877
+ "Unable to determine cache blocking for dynamic M."
878
+ )
879
+ register_blocking = self.register_blocking
880
+ thread_blocking = self.thread_blocking(num_threads)
881
+
882
+ return GemmBlocking(*get_cache_blocking(register_blocking, thread_blocking))
883
+
884
+ def log_blockings(self):
885
+ log.debug(f"Register blocking: {self.register_blocking}") # noqa: G004
886
+ if self.is_dynamic_M:
887
+ # thread and cache blockings are determined at runtime for dynamic shapes
888
+ return
889
+ log.debug(
890
+ f"Cache blocking: {self.cache_blocking(self.num_threads)}" # noqa: G004
891
+ )
892
+ thread_blocking = self.thread_blocking(self.num_threads)
893
+ log.debug(f"Thread blocking: {thread_blocking}") # noqa: G004
894
+
895
+ def get_occupancy():
896
+ m_blocks = math.ceil(self.m / self.register_blocking.block_m)
897
+ n_blocks = math.ceil(self.n / self.register_blocking.block_n)
898
+ k_blocks = math.ceil(self.k / self.register_blocking.block_k)
899
+ m = math.ceil(m_blocks / thread_blocking.block_m)
900
+ n = math.ceil(n_blocks / thread_blocking.block_n)
901
+ k = math.ceil(k_blocks / thread_blocking.block_k)
902
+ return (m, n, k)
903
+
904
+ log.debug(
905
+ f"Number of threads: {self.num_threads}, occupancy: {get_occupancy()}" # noqa: G004
906
+ )
907
+
908
+ def maybe_k_slicing(self):
909
+ if self.num_threads == 1:
910
+ return False
911
+ if self.is_dynamic_M:
912
+ # TODO(jgong5): perhaps use size hint to decide?
913
+ return True
914
+ register_blocking = self.register_blocking
915
+ k_blocks = math.ceil(self.k / register_blocking.block_k)
916
+ thread_blocking = self.thread_blocking(self.num_threads)
917
+ return k_blocks > thread_blocking.block_k
918
+
919
+ @classmethod
920
+ def add_choices(
921
+ cls,
922
+ choices,
923
+ layout,
924
+ input_nodes,
925
+ beta=1,
926
+ alpha=1,
927
+ has_bias=False,
928
+ trans_w=False,
929
+ input_indices=None,
930
+ epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
931
+ act_mapping: Optional[dict[int, ir.IRNode]] = None,
932
+ ):
933
+ """
934
+ Add choices for the GEMM template.
935
+ """
936
+ # Fast path to save the epilogue calculation when x_scale/x_zp/w_scale are constant
937
+ use_int8_fast_compensation_path = _is_int8_gemm(input_nodes) and all(
938
+ (
939
+ isinstance(input_nodes[idx], ir.TensorBox)
940
+ and isinstance(input_nodes[idx].data.data, ir.ConstantBuffer)
941
+ )
942
+ for idx in [1, 2, 4]
943
+ )
944
+
945
+ if input_indices is None:
946
+ input_indices = list(range(len(input_nodes)))
947
+
948
+ def reorder_and_filter(inputs, layout_or_out):
949
+ if has_bias:
950
+ assert len(input_indices) >= 3
951
+ # Assume the input order is [inp, x, w] and we reorder it to [x, w, inp]
952
+ inp_idx = input_indices[0]
953
+ x_idx = input_indices[1]
954
+ w_idx = input_indices[2]
955
+ return [
956
+ inputs[x_idx],
957
+ inputs[w_idx],
958
+ inputs[inp_idx],
959
+ *[inputs[idx] for idx in input_indices[3:]],
960
+ ], layout_or_out
961
+ elif len(inputs) >= len(input_indices):
962
+ assert len(input_indices) >= 2
963
+ return [inputs[idx] for idx in input_indices], layout_or_out
964
+ else:
965
+ # For when input is used for x and w, i.e. X@X.T or similar
966
+ # Assumes the first input is the only input
967
+ assert len(inputs) == 1
968
+ return [inputs[0]] * len(input_indices), layout_or_out
969
+
970
+ new_inputs, new_layout = reorder_and_filter(input_nodes, layout)
971
+ is_mkldnn_wgt = (
972
+ new_inputs[1].get_name() in V.graph.constants
973
+ and V.graph.constants[new_inputs[1].get_name()].is_mkldnn
974
+ )
975
+ if is_mkldnn_wgt:
976
+ # It shouldn't happen as viewing an mkldnn tensor, we can extend the
977
+ # implementation if it does.
978
+ assert not isinstance(new_inputs[1], ir.BaseView)
979
+ # Note that the layout of MKLDNN Tensor is with the wrong stride
980
+ view_size = new_inputs[1].layout.size
981
+ view_stride = new_inputs[1].layout.stride
982
+ view_offset = new_inputs[1].layout.offset
983
+
984
+ def maybe_to_dense(inputs, layout_or_out):
985
+ new_inputs = list(inputs)
986
+ if isinstance(inputs[1], torch.Tensor):
987
+ W = inputs[1]
988
+ new_inputs[1] = W.to_dense() if W.is_mkldnn else W
989
+ return new_inputs, layout_or_out
990
+
991
+ def normalize_shapes(inputs, layout_or_out):
992
+ new_inputs = list(inputs)
993
+ if not is_mkldnn_wgt and isinstance(new_inputs[1], torch.Tensor):
994
+ if has_free_symbols(view_size):
995
+ # If batch size B is dynamic, we need to set the batch size and possibly stride
996
+ assert not has_free_symbols(view_size[1:])
997
+ view_size[:] = V.graph.sizevars.size_hints(view_size)
998
+ view_stride[:] = V.graph.sizevars.size_hints(view_stride)
999
+ # With the assumptation that W is the storage of unwrap view
1000
+ # thus view it back here
1001
+ new_inputs[1] = new_inputs[1].as_strided(
1002
+ view_size, view_stride, view_offset
1003
+ )
1004
+
1005
+ if not trans_w:
1006
+ return new_inputs, layout_or_out
1007
+ X = new_inputs[0]
1008
+ W = new_inputs[1]
1009
+ B = new_inputs[2] if has_bias else None
1010
+ W = transpose_w(W, trans_w)
1011
+ B = expand_bias(B, X) # type:ignore[arg-type]
1012
+ new_inputs[1] = W
1013
+ if B is not None:
1014
+ new_inputs[2] = B
1015
+ return new_inputs, layout_or_out
1016
+
1017
+ # TODO(jgong5): decide proper number of threads per problem size
1018
+ num_threads = parallel_num_threads()
1019
+ new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout))
1020
+ m, n, k, *_ = mm_args(
1021
+ new_inputs[0],
1022
+ new_inputs[1],
1023
+ mat2_transposed=cls.is_woq_int4(),
1024
+ use_4x2_dim=cls.is_woq_int4(),
1025
+ )
1026
+ output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
1027
+ new_inputs[0].get_dtype()
1028
+ )
1029
+ micro_gemm = create_micro_gemm(
1030
+ "micro_gemm",
1031
+ m,
1032
+ n,
1033
+ k,
1034
+ input_dtype=new_inputs[0].get_dtype(),
1035
+ input2_dtype=new_inputs[1].get_dtype(),
1036
+ output_dtype=output_dtype,
1037
+ compute_dtype=compute_dtype,
1038
+ alpha=alpha,
1039
+ num_threads=num_threads,
1040
+ use_ref=not cls.is_woq_int4(),
1041
+ q_group_size=cls.q_group_size(),
1042
+ )
1043
+ assert micro_gemm is not None
1044
+ pre_block_weights = cls.check_if_block_weight(new_inputs[1], micro_gemm)
1045
+ micro_gemm.use_local_vnni_blocking(not pre_block_weights)
1046
+ only_one_input = (
1047
+ input_nodes[0] == input_nodes[1] if len(input_nodes) > 1 else False
1048
+ ) and not pre_block_weights # If weights are blocked, use the second input
1049
+
1050
+ def preprocessor(inputs, layout):
1051
+ new_inputs, new_layout = normalize_shapes(
1052
+ *maybe_to_dense(*reorder_and_filter(inputs, layout))
1053
+ )
1054
+ if only_one_input and isinstance(new_inputs[0], torch.Tensor):
1055
+ return new_inputs[1:], new_layout
1056
+ return cls.prep_weight(
1057
+ new_inputs,
1058
+ new_layout,
1059
+ # pyrefly: ignore [bad-argument-type]
1060
+ micro_gemm,
1061
+ pre_block_weights,
1062
+ use_int8_fast_compensation_path,
1063
+ )
1064
+
1065
+ def postprocessor(output):
1066
+ if isinstance(output, ir.TensorBox):
1067
+ # prepack the weight as input to the template buffer
1068
+ template_buffer = ir.InputsKernel.unwrap_storage_for_input(output)
1069
+ assert isinstance(template_buffer, ir.CppTemplateBuffer)
1070
+ new_input_nodes, _ = reorder_and_filter(input_nodes, layout)
1071
+
1072
+ W_node = new_input_nodes[1]
1073
+ if W_node.get_name() not in V.graph.constants:
1074
+ return output
1075
+ W = V.graph.constants[W_node.get_name()]
1076
+ new_input_nodes[1] = W
1077
+ new_input_nodes, new_layout = normalize_shapes(
1078
+ *maybe_to_dense(new_input_nodes, layout)
1079
+ )
1080
+ new_input_nodes, _ = cls.prep_weight(
1081
+ new_input_nodes,
1082
+ new_layout,
1083
+ # pyrefly: ignore [bad-argument-type]
1084
+ micro_gemm,
1085
+ pre_block_weights,
1086
+ use_int8_fast_compensation_path,
1087
+ skip_int8_compensation=True,
1088
+ )
1089
+ W_packed = new_input_nodes[1]
1090
+ W_packed_constant = V.graph.add_tensor_constant(W_packed)
1091
+ new_input_nodes[1] = W_packed_constant
1092
+
1093
+ # Prune unused tensors
1094
+ prune_tensors(input_nodes, new_input_nodes)
1095
+
1096
+ template_buffer.inputs[1] = ir.InputsKernel.unwrap_storage_for_input(
1097
+ W_packed_constant
1098
+ )
1099
+ return output
1100
+
1101
+ template = DataProcessorTemplateWrapper(
1102
+ cls,
1103
+ preprocessor,
1104
+ postprocessor,
1105
+ input_nodes=input_nodes,
1106
+ layout=layout,
1107
+ num_threads=num_threads,
1108
+ register_blocking=micro_gemm.register_blocking,
1109
+ beta=beta,
1110
+ alpha=alpha,
1111
+ has_bias=has_bias,
1112
+ epilogue_creator=epilogue_creator,
1113
+ should_block_weights=pre_block_weights,
1114
+ name=micro_gemm.__class__.__name__,
1115
+ )
1116
+ template.maybe_append_choice(choices)
1117
+ return template
1118
+
1119
+ @staticmethod
1120
+ def get_padded_size(n, block_n, k, should_block_weight):
1121
+ padded_n = get_padded_n(n, block_n)
1122
+ # We assume that all GEMM weight tensors should be blocked and padded
1123
+ new_size = [padded_n // block_n, k, block_n]
1124
+ return new_size, padded_n
1125
+
1126
+ @staticmethod
1127
+ def _maybe_remove_storage_offset(node: ir.IRNode):
1128
+ if node.get_layout().offset == 0:
1129
+ return node
1130
+ # node may be contiguous but still have a non-zero storage offset.
1131
+ # GEMM_TEMPLATE emits code like:
1132
+ # W.data_ptr[node.offset + ...]
1133
+ # but runtime W.data_ptr (after normalize_shapes()) already includes this offset.
1134
+ # To avoid double-offsetting, we remove the offset in the node also in the generated code.
1135
+ # W.data_ptr[...]
1136
+ return ir.ExternKernel.copy_input(node)
1137
+
1138
+ @classmethod
1139
+ def prep_weight(
1140
+ cls,
1141
+ inputs,
1142
+ layout: ir.Layout,
1143
+ micro_gemm: CppMicroGemm,
1144
+ should_block_weight: bool,
1145
+ use_int8_fast_compensation_path: bool = False,
1146
+ skip_int8_compensation: bool = False,
1147
+ ):
1148
+ """
1149
+ NOTE Weight prep consists of 2 separate steps:
1150
+ 1. Blocking the weight tensor into a 3D shape: [n//block_n, k, block_n]
1151
+ This is always done if the weight tensor is constant, i.e. for all GEMM and some BMM.
1152
+ For BMM, we also block non-contiguous weight tensors, since they would be reshaped anyway.
1153
+ This assumes that blocked, contiguous weights will be more efficient for the GEMM kernel,
1154
+ and is worth the overhead of reshape and blocking.
1155
+
1156
+ This blocking includes additional padding, when n is not a multiple of block_n.
1157
+ This padding allows a more efficient microkernel implementation. For BMM, this is only done
1158
+ if reshape would happen anyway, i.e. if the weight tensor is constant, is not contiguous,
1159
+ or is using AMX VNNI layout.
1160
+ 2. Packing the weight tensor into a VNNI-friendly shape. For constant input,
1161
+ this is done at the same time as the weight blocking.
1162
+
1163
+ At compile time, the constant weight tensors are blocked and packed. For non-constant tensors (e.g. BMM)
1164
+ which will be blocked (non-contiguous or VNNI-layout tensors), the weight tensor is blocked and packed at runtime.
1165
+
1166
+ CppBmmTemplate overrides the methods get_padded_size, and block_weight in order to accommodate
1167
+ an additional dimension for the batch size and to determine if the weight tensor should be blocked.
1168
+ """
1169
+ W = inputs[1]
1170
+ new_inputs = list(inputs)
1171
+ if cls.is_woq_int4():
1172
+ assert (
1173
+ len(W.get_size()) == 2
1174
+ if isinstance(W, ir.IRNode)
1175
+ else len(W.shape) == 2
1176
+ )
1177
+ n, k = W.get_size() if isinstance(W, ir.IRNode) else W.shape
1178
+ else:
1179
+ k, n = W.get_size()[-2:] if isinstance(W, ir.IRNode) else W.shape[-2:]
1180
+ _, block_n, _ = micro_gemm.register_blocking
1181
+ new_size, padded_n = cls.get_padded_size(n, block_n, k, should_block_weight)
1182
+ padding = padded_n - n
1183
+
1184
+ if should_block_weight and not cls.is_woq_int4():
1185
+ blocked_w = cls.block_weight(W, new_size, padding)
1186
+ new_inputs[1] = cls.pack_vnni_weight(blocked_w, micro_gemm, new_size)
1187
+ elif should_block_weight:
1188
+ assert cls.is_woq_int4()
1189
+ new_inputs[1] = cls.block_weight(W, new_size, padding)
1190
+ elif isinstance(W, ir.IRNode):
1191
+ # Require W layout to be fixed & contiguous, happens inplace.
1192
+ ir.ExternKernel.require_contiguous(W)
1193
+ new_inputs[1] = cls._maybe_remove_storage_offset(W)
1194
+
1195
+ if not skip_int8_compensation and _is_int8_gemm(new_inputs):
1196
+ BCompensate = None
1197
+ x_w_scale = None
1198
+
1199
+ def _get_compensation_node(W, use_int8_fast_compensation_path):
1200
+ BCompensate = V.graph.add_tensor_constant(
1201
+ V.graph.constants[W.get_name() + "_BMatrixCompens"],
1202
+ W.get_name() + "_BMatrixCompens",
1203
+ )
1204
+ x_w_scale = None
1205
+ if use_int8_fast_compensation_path:
1206
+ x_w_scale = V.graph.add_tensor_constant(
1207
+ V.graph.constants[W.get_name() + "_x_w_compens"],
1208
+ W.get_name() + "_x_w_compens",
1209
+ )
1210
+ return BCompensate, x_w_scale
1211
+
1212
+ if use_int8_fast_compensation_path:
1213
+ # new_inputs has been reordered: [x, w, optional[bias], x_scale, x_zp, w_scale, w_zp]
1214
+ x_scale = new_inputs[-4]
1215
+ x_zp = new_inputs[-3]
1216
+ w_scale = new_inputs[-2]
1217
+ if isinstance(W, ir.IRNode):
1218
+ BCompensate, x_w_scale = _get_compensation_node(
1219
+ W, use_int8_fast_compensation_path
1220
+ )
1221
+ else:
1222
+ # Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate
1223
+ BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment]
1224
+ assert all(
1225
+ isinstance(item, torch.Tensor)
1226
+ for item in (x_scale, x_zp, w_scale)
1227
+ )
1228
+ BCompensate = BCompensate * x_scale * w_scale * x_zp
1229
+ x_w_scale = x_scale * w_scale
1230
+ new_inputs.append(BCompensate)
1231
+ new_inputs.append(x_w_scale)
1232
+ else:
1233
+ if isinstance(W, ir.IRNode):
1234
+ BCompensate, _ = _get_compensation_node(
1235
+ W, use_int8_fast_compensation_path
1236
+ )
1237
+ else:
1238
+ # Use the original W, not the blocked_w in new_inputs[1] to calculate BCompensate
1239
+ BCompensate = torch.sum(W.to_dense().to(torch.float), dim=0) # type: ignore[assignment]
1240
+ new_inputs.append(BCompensate)
1241
+ return new_inputs, layout
1242
+
1243
+ @staticmethod
1244
+ def check_if_block_weight(W, micro_gemm):
1245
+ return True
1246
+
1247
+ @classmethod
1248
+ def block_weight(cls, W, new_size, padding):
1249
+ # These are separated into two methods to allow subclasses to override them separately
1250
+ if isinstance(W, ir.IRNode):
1251
+ if W.get_name() in V.graph.constants:
1252
+ # Create a new buffer, representing the constant blocked tensor
1253
+ blocked_w = ir.Buffer(
1254
+ name=W.get_name(), # Borrow the registered buffer name
1255
+ layout=ir.FixedLayout(
1256
+ W.get_device_or_error(),
1257
+ W.get_dtype(),
1258
+ new_size,
1259
+ ir.FlexibleLayout.contiguous_strides(new_size),
1260
+ 0,
1261
+ ),
1262
+ )
1263
+ else:
1264
+ if not isinstance(W, ir.TensorBox):
1265
+ W = ir.TensorBox(W)
1266
+ permute_dims = list(range(len(new_size)))
1267
+ permute_dims[-2], permute_dims[-3] = permute_dims[-3], permute_dims[-2]
1268
+ permute_size = list(new_size)
1269
+ permute_size[-2], permute_size[-3] = permute_size[-3], permute_size[-2]
1270
+ blocked_w = L.constant_pad_nd(W, (0, padding))
1271
+ blocked_w = L.permute(
1272
+ L.view(blocked_w, permute_size), # type: ignore[arg-type]
1273
+ permute_dims,
1274
+ )
1275
+ else:
1276
+ assert isinstance(W, torch.Tensor)
1277
+ # Pad the weight tensor and reshape it into a 3D blocked shape
1278
+ blocked_size = list(new_size)
1279
+ blocked_size[-2], blocked_size[-3] = blocked_size[-3], blocked_size[-2]
1280
+ blocked_w = (
1281
+ torch.nn.functional.pad(W, (0, padding)) # type: ignore[assignment]
1282
+ .reshape(*blocked_size)
1283
+ .transpose(-3, -2)
1284
+ .contiguous()
1285
+ )
1286
+ return blocked_w
1287
+
1288
+ @classmethod
1289
+ def pack_vnni_weight(cls, W, micro_gemm, new_size):
1290
+ # WOQ INT4 weights are reordered in microkernel so do not pack them here
1291
+ should_pack = (
1292
+ micro_gemm.get_b_layout() != LayoutType.NORMAL
1293
+ and not micro_gemm.is_woq_int4()
1294
+ )
1295
+
1296
+ # These are separated into two methods to allow subclasses to override them separately
1297
+ if isinstance(W, ir.IRNode):
1298
+ if isinstance(W, ir.Buffer) and W.get_name() in V.graph.constants:
1299
+ return W
1300
+ k = new_size[-2]
1301
+ if not isinstance(W, ir.TensorBox):
1302
+ W = ir.TensorBox(W)
1303
+ if should_pack:
1304
+ permute_dims = list(range(len(new_size) + 1))
1305
+ permute_dims[-1], permute_dims[-2] = permute_dims[-2], permute_dims[-1]
1306
+ vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2
1307
+ vnni_view_size = list(new_size)
1308
+ vnni_view_size[-2] = k // vnni_size
1309
+ vnni_view_size.insert(-1, vnni_size)
1310
+ W = L.view(
1311
+ L.permute(L.view(W, vnni_view_size), permute_dims),
1312
+ new_size,
1313
+ )
1314
+ W = ir.ExternKernel.realize_input(W)
1315
+ W = ir.ExternKernel.require_contiguous(W)
1316
+ return W
1317
+ else:
1318
+ k = new_size[-2]
1319
+ # Apply VNNI packing to the weight tensor
1320
+ if should_pack:
1321
+ # TODO: Move VNNI weight packing for non-constant tensors into the template,
1322
+ # to improve cache locality and avoid full-tensor copy.
1323
+ layout_str = (
1324
+ "VNNI4"
1325
+ if micro_gemm.get_b_layout() == LayoutType.VNNI4
1326
+ else "VNNI2"
1327
+ )
1328
+ assert micro_gemm.get_b_layout() in [
1329
+ LayoutType.VNNI2,
1330
+ LayoutType.VNNI4,
1331
+ ], f"We only support {layout_str} for now"
1332
+ vnni_size = 4 if micro_gemm.get_b_layout() == LayoutType.VNNI4 else 2
1333
+ assert k % vnni_size == 0, (
1334
+ f"k should be divisible by vnni_size for {layout_str} layout"
1335
+ )
1336
+ vnni_view_size = list(new_size)
1337
+ vnni_view_size[-2] = k // vnni_size
1338
+ vnni_view_size.insert(-1, vnni_size)
1339
+ W = W.view(vnni_view_size).transpose(-1, -2).contiguous().view(new_size)
1340
+ # normalize stride to be "contiguous_strides" per size
1341
+ # this avoids the problems in L.view during template codegen
1342
+ new_stride = [1]
1343
+ for sz in reversed(W.shape[1:]):
1344
+ new_stride.insert(0, new_stride[0] * sz)
1345
+ W = W.as_strided(W.shape, new_stride)
1346
+ return W
1347
+
1348
+ def get_default_reindexers(self, epilogue_nodes):
1349
+ return [None] * len(epilogue_nodes)
1350
+
1351
+ def get_options(
1352
+ self,
1353
+ kernel: CppTemplateKernel,
1354
+ template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
1355
+ flag_template_buffer_has_other_users: Optional[bool] = None,
1356
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
1357
+ ) -> dict[str, Any]:
1358
+ assert len(self.input_nodes) >= 2
1359
+
1360
+ int8_gemm = self.input_nodes[0].get_dtype() in [torch.uint8, torch.int8]
1361
+ x_scale = None
1362
+ x_zp = None
1363
+ w_scale = None
1364
+ w_zp = None
1365
+ inp = None
1366
+ q_group_size_node = None
1367
+ qscale_and_zeros = None
1368
+ if int8_gemm:
1369
+ X, W = self.input_nodes[0], self.input_nodes[1]
1370
+ bias_idx = 2 if self.has_bias else 1
1371
+ inp = self.input_nodes[bias_idx] if self.has_bias else None
1372
+ x_scale = self.input_nodes[bias_idx + 1]
1373
+ x_zp = self.input_nodes[bias_idx + 2]
1374
+ w_scale = self.input_nodes[bias_idx + 3]
1375
+ w_zp = self.input_nodes[bias_idx + 4]
1376
+ Y = self.output_node
1377
+ elif self.is_woq_int4():
1378
+ X, W = self.input_nodes[0], self.input_nodes[1]
1379
+ Y = self.output_node
1380
+ q_group_size_node = self.input_nodes[2]
1381
+ qscale_and_zeros = self.input_nodes[3]
1382
+ else:
1383
+ X, W = self.input_nodes[0], self.input_nodes[1]
1384
+ Y = self.output_node
1385
+ inp = self.input_nodes[2] if self.has_bias else None
1386
+
1387
+ template_buffer_has_other_users = None
1388
+
1389
+ if template_buffer_node is not None:
1390
+ # Use the updated prepacked weight buffer
1391
+ W = template_buffer_node.inputs[1]
1392
+ Y = template_buffer_node
1393
+
1394
+ assert flag_template_buffer_has_other_users is not None
1395
+ template_buffer_has_other_users = flag_template_buffer_has_other_users
1396
+
1397
+ template_buffer = Y
1398
+ gemm_output_buffer = template_buffer
1399
+
1400
+ epilogues: list[ir.IRNode] = []
1401
+ reindexers: list[Optional[Callable[[list[Any]], list[Any]]]] = []
1402
+ epilogue_creators: list[Callable[[ir.Buffer], ir.Pointwise]] = []
1403
+ fake_buffers: list[ir.Buffer] = []
1404
+ Y_aliases: OrderedSet[str] = OrderedSet()
1405
+
1406
+ use_local_acc = (
1407
+ self.layout.dtype != torch.float
1408
+ or template_buffer_has_other_users
1409
+ or int8_gemm
1410
+ or self.padded_n != self.n
1411
+ or self.maybe_k_slicing()
1412
+ or (epilogue_nodes and epilogue_nodes[-1].get_dtype() != self.layout.dtype)
1413
+ )
1414
+
1415
+ # TODO(jgong5): for int8 gemm, bias-add is handled outside of gemm template,
1416
+ # but we'd better move it here to align with fp.
1417
+ if inp is not None and self.beta != 0 and not int8_gemm:
1418
+ # add an epilogue for bias add
1419
+ def _bias_add_epilogue(buf):
1420
+ return create_epilogue_with_attr(
1421
+ buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype
1422
+ )
1423
+
1424
+ epilogue_creators.append(_bias_add_epilogue)
1425
+
1426
+ if self.epilogue_creator is not None:
1427
+ epilogue_creators.append(self.epilogue_creator)
1428
+
1429
+ # When the GEMM output buffer is localized but it has users other than the epilogue nodes,
1430
+ # we need to copy the value in the GEMM output local buffer to a global buffer.
1431
+ def need_copy_from_local_to_global_buffer_epilogue(
1432
+ use_local_acc, template_buffer_has_other_users, epilogue_creators
1433
+ ):
1434
+ # The GEMM output buffer is a global buffer, thus copy is not needed.
1435
+ if not use_local_acc:
1436
+ return False
1437
+
1438
+ # The possible value of template_buffer_has_other_users is (None, False, True)
1439
+ # It is None when generating the gemm template during autotune and it will have value during scheduler codegen.
1440
+ # extra copy_from_local_to_global_buffer_epilogue is not needed in either of the below two cases:
1441
+ # 1. template_buffer_has_other_users is None (i.e. when doing the codegen during autotune)
1442
+ # 2. template_buffer_has_other_users is False, which means it's safe to keep the value in the
1443
+ # GEMM output buffer in local buffer only (no users outside of the epilogues will use its value).
1444
+ if not template_buffer_has_other_users:
1445
+ return False
1446
+
1447
+ # When bias is not None or self.epilogue_creator is not None,
1448
+ # there will be epilogue_creators after the GEMM.
1449
+ # The GEMM output buffer is localized while
1450
+ # the output buffer of the epilogue_creators is a global buffer.
1451
+ if epilogue_creators:
1452
+ return False
1453
+
1454
+ return True
1455
+
1456
+ if need_copy_from_local_to_global_buffer_epilogue(
1457
+ use_local_acc, template_buffer_has_other_users, epilogue_creators
1458
+ ):
1459
+
1460
+ def copy_from_local_to_global_buffer_epilogue(input_buffer: ir.Buffer):
1461
+ dtype = self.layout.dtype
1462
+ input_loader = input_buffer.make_loader()
1463
+
1464
+ def copy_inner(index):
1465
+ input = input_loader(index)
1466
+ result = ops.to_dtype(input, dtype)
1467
+ return result
1468
+
1469
+ return ir.Pointwise(
1470
+ device=input_buffer.get_device_or_error(),
1471
+ dtype=self.layout.dtype,
1472
+ inner_fn=copy_inner,
1473
+ ranges=input_buffer.get_size(),
1474
+ )
1475
+
1476
+ epilogue_creators.append(copy_from_local_to_global_buffer_epilogue)
1477
+
1478
+ # NOTE [How CPP GEMM template epilogues are organized]
1479
+ # gemm_output_buffer
1480
+ # --> zero or more in-template epilogues (created by `epilogue_creators`) -->
1481
+ # template_buffer
1482
+ # --> zero or more out-of-template epilogues (`epilogue_nodes`) -->
1483
+ # Y
1484
+ if epilogue_creators:
1485
+ assert isinstance(template_buffer, ir.IRNode)
1486
+ gemm_output_name = f"{template_buffer.get_name()}_GemmOut"
1487
+ gemm_output_buffer = ir.Buffer(
1488
+ name=gemm_output_name,
1489
+ # pyrefly: ignore [missing-attribute]
1490
+ layout=template_buffer.layout,
1491
+ )
1492
+ current_input_buffer = gemm_output_buffer
1493
+ for i, creator in enumerate(epilogue_creators):
1494
+ if i == len(epilogue_creators) - 1:
1495
+ buffer_name = template_buffer.get_name()
1496
+ else:
1497
+ buffer_name = f"{gemm_output_name}_epilogue_{i}"
1498
+ epilogues.append(
1499
+ ir.ComputedBuffer(
1500
+ name=buffer_name,
1501
+ # pyrefly: ignore [missing-attribute]
1502
+ layout=template_buffer.layout,
1503
+ data=creator(current_input_buffer),
1504
+ )
1505
+ )
1506
+ fake_buffers.append(current_input_buffer)
1507
+ Y_aliases.add(current_input_buffer.get_name())
1508
+ reindexers.append(None)
1509
+ if i < len(epilogue_creators) - 1:
1510
+ current_input_buffer = ir.Buffer(
1511
+ name=buffer_name,
1512
+ # pyrefly: ignore [missing-attribute]
1513
+ layout=template_buffer.layout,
1514
+ )
1515
+
1516
+ assert isinstance(Y, (ir.Buffer, ir.ReinterpretView))
1517
+ Y_2d: Union[ir.Buffer, ir.ReinterpretView] = Y
1518
+
1519
+ if epilogue_nodes:
1520
+ if not template_buffer_has_other_users:
1521
+ assert isinstance(template_buffer, ir.IRNode)
1522
+ Y_aliases.add(template_buffer.get_name())
1523
+ epilogues.extend(epilogue_nodes)
1524
+ assert Y.get_numel() == epilogues[-1].get_numel()
1525
+ Y = cast(ir.Buffer, epilogues[-1])
1526
+ assert isinstance(template_buffer, ir.Buffer)
1527
+ Y_2d, reindexers = gen_2d_view_of_epilogue_buf(
1528
+ Y,
1529
+ template_buffer,
1530
+ epilogue_nodes,
1531
+ reindexers,
1532
+ default_reindexers=self.get_default_reindexers(epilogue_nodes),
1533
+ )
1534
+
1535
+ output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
1536
+ X.get_dtype()
1537
+ )
1538
+ micro_gemm = create_micro_gemm(
1539
+ f"{kernel.kernel_name}_micro_gemm",
1540
+ self.m,
1541
+ self.n,
1542
+ self.k,
1543
+ input_dtype=X.get_dtype(),
1544
+ input2_dtype=W.get_dtype(),
1545
+ output_dtype=output_dtype,
1546
+ compute_dtype=compute_dtype,
1547
+ alpha=self.alpha,
1548
+ num_threads=self.num_threads,
1549
+ use_ref=not self.is_woq_int4(),
1550
+ q_group_size=self.q_group_size(),
1551
+ )
1552
+ assert micro_gemm is not None
1553
+ micro_gemm.use_local_vnni_blocking(not self.should_block_weights)
1554
+ assert self.register_blocking == micro_gemm.register_blocking
1555
+ self.log_blockings()
1556
+ if isinstance(micro_gemm, CppMicroGemmAMX):
1557
+ counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1
1558
+ if isinstance(micro_gemm, CppMicroBrgemm):
1559
+ counters["inductor"]["cpp_micro_brgemm_counter"] += 1
1560
+
1561
+ L1_cache_size = torch.cpu.get_capabilities().get(
1562
+ "l1d_cache_size", 0
1563
+ ) # per core cache size in Bytes
1564
+ assert L1_cache_size > 0, f"Expect L1_cache_size > 0 but got {L1_cache_size}"
1565
+
1566
+ L2_cache_size = torch.cpu.get_capabilities().get(
1567
+ "l2_cache_size", 0
1568
+ ) # per core cache size in Bytes
1569
+ assert L2_cache_size > 0, f"Expect L2_cache_size > 0 but got {L2_cache_size}"
1570
+
1571
+ options = dict(
1572
+ X=X,
1573
+ W=W,
1574
+ inp=inp,
1575
+ Y=Y,
1576
+ N=self.n,
1577
+ K=self.k,
1578
+ PADDED_N=self.padded_n,
1579
+ GemmOut=gemm_output_buffer,
1580
+ aliases={alias: Y.get_name() for alias in Y_aliases},
1581
+ beta=self.beta,
1582
+ alpha=self.alpha,
1583
+ num_threads=self.num_threads,
1584
+ micro_gemm=micro_gemm,
1585
+ is_dynamic_M=self.is_dynamic_M,
1586
+ template=self,
1587
+ kernel=kernel,
1588
+ export_declaration=get_export_declaration(),
1589
+ epilogue_nodes=epilogues,
1590
+ reindexers=reindexers,
1591
+ Y_2d=Y_2d,
1592
+ use_local_acc=use_local_acc,
1593
+ maybe_k_slicing=self.maybe_k_slicing(),
1594
+ x_scale=x_scale,
1595
+ x_zp=x_zp,
1596
+ w_scale=w_scale,
1597
+ w_zp=w_zp,
1598
+ acc_buf_dtype=torch.int32 if int8_gemm else torch.float,
1599
+ DTYPE_TO_CPP=DTYPE_TO_CPP,
1600
+ L1_cache_size=L1_cache_size,
1601
+ L2_cache_size=L2_cache_size,
1602
+ config=config,
1603
+ fake_buffers=fake_buffers,
1604
+ is_woq_int4=self.is_woq_int4(),
1605
+ q_group_size=q_group_size_node,
1606
+ qscale_and_zeros=qscale_and_zeros,
1607
+ )
1608
+ return options
1609
+
1610
+ def is_int8_woq_gemm_small_m_dim(
1611
+ self,
1612
+ X: ir.ReinterpretView,
1613
+ W: ir.ReinterpretView,
1614
+ N,
1615
+ K,
1616
+ micro_gemm,
1617
+ ):
1618
+ """Use SMALL_M_GEMM_TEMPLATE"""
1619
+ return (
1620
+ isinstance(micro_gemm, CppMicroGemmFP32Vec)
1621
+ and is_int8_woq_gemm_small_m_dim_corner_case(
1622
+ micro_gemm, X.get_size()[0], N, K
1623
+ )
1624
+ and X.get_dtype() is torch.bfloat16
1625
+ and W.get_dtype() is torch.int8
1626
+ )
1627
+
1628
+ def render( # type: ignore[override, return]
1629
+ self,
1630
+ kernel: CppTemplateKernel,
1631
+ template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
1632
+ flag_template_buffer_has_other_users: Optional[bool] = None,
1633
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
1634
+ **kwargs,
1635
+ ) -> str:
1636
+ options = self.get_options(
1637
+ kernel=kernel,
1638
+ template_buffer_node=template_buffer_node,
1639
+ flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
1640
+ epilogue_nodes=epilogue_nodes,
1641
+ )
1642
+ self.render_options = options
1643
+
1644
+ with contextlib.ExitStack() as stack:
1645
+ for buf in options["fake_buffers"]:
1646
+ stack.enter_context(
1647
+ patch.object(V.graph, "get_dtype", self._fake_get_dtype(buf))
1648
+ )
1649
+ if not options["is_dynamic_M"] and self.is_int8_woq_gemm_small_m_dim(
1650
+ options["X"],
1651
+ options["W"],
1652
+ options["N"],
1653
+ options["K"],
1654
+ options["micro_gemm"],
1655
+ ):
1656
+ template_str = SMALL_M_GEMM_TEMPLATE
1657
+ else:
1658
+ template_str = GEMM_TEMPLATE
1659
+ return self._template_from_string(template_str).render(**options)
1660
+
1661
+ def codegen_blocks(
1662
+ self,
1663
+ num_threads,
1664
+ N,
1665
+ K,
1666
+ micro_gemm,
1667
+ is_dynamic_M,
1668
+ kernel,
1669
+ GemmOut,
1670
+ config,
1671
+ L1_cache_size,
1672
+ L2_cache_size,
1673
+ X,
1674
+ W,
1675
+ ):
1676
+ options = dict(
1677
+ num_threads=num_threads,
1678
+ N=N,
1679
+ K=K,
1680
+ micro_gemm=micro_gemm,
1681
+ is_dynamic_M=is_dynamic_M,
1682
+ kernel=kernel,
1683
+ GemmOut=GemmOut,
1684
+ config=config,
1685
+ L1_cache_size=L1_cache_size,
1686
+ L2_cache_size=L2_cache_size,
1687
+ template=self,
1688
+ X=X,
1689
+ W=W,
1690
+ is_woq_int4=self.is_woq_int4(),
1691
+ )
1692
+ template_str = GEMM_TEMPLATE_INIT_BLOCKING_BASIC_BLOCK
1693
+ if not (
1694
+ not is_dynamic_M
1695
+ and self.is_int8_woq_gemm_small_m_dim(X, W, N, K, micro_gemm)
1696
+ ):
1697
+ template_str += GEMM_TEMPLATE_INIT_BLOCKING_EXTENDED
1698
+ return self._template_from_string(template_str).render(options)
1699
+
1700
+ def codegen_microkernel_def(self):
1701
+ return self._template_from_string(GEMM_TEMPLATE_MICROKERNEL_DEF).render(
1702
+ self.render_options
1703
+ )
1704
+
1705
+ def codegen_gemm_stub_def(self):
1706
+ microkernel = self.codegen_microkernel_def()
1707
+ return microkernel + self._template_from_string(GEMM_TEMPLATE_STUB_DEF).render(
1708
+ self.render_options
1709
+ )
1710
+
1711
+ def codegen_multi_threads_params(self):
1712
+ return self._template_from_string(GEMM_TEMPLATE_MULTI_THREADS_PARAMS).render()
1713
+
1714
+ def codegen_single_thread_params(self, is_dynamic_M):
1715
+ options = dict(
1716
+ is_dynamic_M=is_dynamic_M,
1717
+ )
1718
+ return self._template_from_string(GEMM_TEMPLATE_SINGLE_THREAD_PARAMS).render(
1719
+ options
1720
+ )
1721
+
1722
+ def codegen_m_loop_params(self):
1723
+ return self._template_from_string(GEMM_TEMPLATE_M_LOOP_PARAMS).render()
1724
+
1725
+ def codegen_n_loop_params(self):
1726
+ return self._template_from_string(GEMM_TEMPLATE_N_LOOP_PARAMS).render()
1727
+
1728
+ @classmethod
1729
+ def is_woq_int4(cls):
1730
+ return False
1731
+
1732
+ @classmethod
1733
+ def q_group_size(cls):
1734
+ return None
1735
+
1736
+
1737
+ class CppWoqInt4GemmTemplateMeta(type):
1738
+ def __getitem__(cls, q_group_size):
1739
+ class CppWoqInt4GemmTemplateInstance(CppGemmTemplate):
1740
+ def __init__(
1741
+ self,
1742
+ *args,
1743
+ **kwargs,
1744
+ ) -> None:
1745
+ super().__init__(
1746
+ *args,
1747
+ **kwargs,
1748
+ )
1749
+
1750
+ @classmethod
1751
+ def is_woq_int4(cls):
1752
+ return True
1753
+
1754
+ @classmethod
1755
+ def q_group_size(cls):
1756
+ return q_group_size
1757
+
1758
+ @staticmethod
1759
+ def check_if_block_weight(W, micro_gemm):
1760
+ # For WOQ INT4, weight is already packed
1761
+ # However, for AMX microkernel, we want to change the blocking of weight
1762
+ from .cpp_micro_gemm import CppMicroGemmWoQInt4Amx
1763
+
1764
+ return isinstance(micro_gemm, CppMicroGemmWoQInt4Amx)
1765
+
1766
+ @classmethod
1767
+ def block_weight(cls, W, new_size, padding):
1768
+ # This method is called only if AMX microkernels are used.
1769
+ # In this case, we unpack and repack weight so that block_n=32
1770
+ # the format of packed weight is described here:
1771
+ # https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L583
1772
+ if isinstance(W, ir.IRNode):
1773
+ # in this case, we do nothing
1774
+ ir.ExternKernel.require_contiguous(W)
1775
+ blocked_w = W
1776
+ else:
1777
+ # in this case, we unpack and repack weight
1778
+ assert isinstance(W, torch.Tensor)
1779
+ assert W.dim() == 2
1780
+ N = W.size(0)
1781
+ K = W.size(-1) * 2
1782
+ G = cls.q_group_size()
1783
+ # x and qscales_and_zeros are in bfloat16 instead of float to use the optimized kernel
1784
+ # so that the unpacking process is faster
1785
+ x = torch.eye(K).bfloat16()
1786
+ # Here we use scale=1 and qzero=8 because we want to unpack weight
1787
+ # without dequantizing it. The qzero here is 8 instead of 0 because
1788
+ # int4 values are converted to [-7, 8] in the _weight_int4pack_mm_for_cpu kernel:
1789
+ # https://github.com/pytorch/pytorch/blob/32eee8ed225d9f10fbbcb38c24b8b44c24c0c97c/aten/src/ATen/native/cpu/int4mm_kernel.cpp#L95
1790
+ qscales_and_zeros = (
1791
+ torch.tensor([1.0, 8.0])
1792
+ .bfloat16()
1793
+ .expand(K // G, N, 2)
1794
+ .contiguous()
1795
+ )
1796
+ # shape: [K, N]
1797
+ unpacked_w = torch.ops.aten._weight_int4pack_mm_for_cpu(
1798
+ x,
1799
+ W,
1800
+ G,
1801
+ qscales_and_zeros,
1802
+ ).to(torch.uint8)
1803
+ block_n = 32
1804
+ # shape: [N // block_n, K, block_n]
1805
+ w_blocked = (
1806
+ unpacked_w.view(K, N // block_n, block_n)
1807
+ .permute(1, 0, 2)
1808
+ .contiguous()
1809
+ )
1810
+ # pack 2 int4 -> 1 int8
1811
+ # block_n: [a0, a1, ..., a15, b0, b1, ..., b15]
1812
+ # -> [(a0 & 0xf) | (b0 << 4), (a1 & 0xf) | (b1 << 4), ...]
1813
+ # shape: [N // block_n, K, 2, block_n // 2]
1814
+ w_blocked = w_blocked.view(N // block_n, K, 2, block_n // 2)
1815
+ # shape: [N // block_n, K, block_n // 2]
1816
+ w_blocked_packed = (w_blocked[:, :, 0, :] & 0xF) | (
1817
+ w_blocked[:, :, 1, :] << 4
1818
+ )
1819
+ # shape: [N, K // 2]
1820
+ blocked_w = w_blocked_packed.view(N, K // 2)
1821
+
1822
+ return blocked_w
1823
+
1824
+ return CppWoqInt4GemmTemplateInstance
1825
+
1826
+
1827
+ class CppWoqInt4GemmTemplate(metaclass=CppWoqInt4GemmTemplateMeta):
1828
+ pass
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_grouped_gemm_template.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import logging
3
+ from collections.abc import Callable
4
+ from typing import Any, cast, Optional, TypeVar
5
+ from unittest.mock import patch
6
+
7
+ import torch
8
+ import torch.utils
9
+ from torch.utils._ordered_set import OrderedSet
10
+
11
+ from ..._dynamo.utils import counters
12
+ from .. import config, ir
13
+ from ..kernel.mm_common import mm_args
14
+ from ..select_algorithm import ChoiceCaller, DataProcessorTemplateWrapper
15
+ from ..utils import parallel_num_threads
16
+ from ..virtualized import V
17
+ from .cpp import get_export_declaration
18
+ from .cpp_gemm_template import (
19
+ CppGemmTemplate,
20
+ expand_bias,
21
+ gen_2d_view_of_epilogue_buf,
22
+ prune_tensors,
23
+ transpose_w,
24
+ )
25
+ from .cpp_micro_gemm import CppMicroGemmAMX, create_micro_gemm
26
+ from .cpp_template_kernel import CppTemplateKernel
27
+ from .cpp_utils import (
28
+ create_epilogue_with_attr,
29
+ DTYPE_TO_CPP,
30
+ GemmBlocking,
31
+ get_gemm_template_output_and_compute_dtype,
32
+ )
33
+
34
+
35
+ log = logging.getLogger(__name__)
36
+
37
+ GEMM_TEMPLATE = r"""
38
+ {{template.header().getvalue()}}
39
+ {{micro_gemm.codegen_define(kernel)}}
40
+
41
+ extern "C" {{export_declaration}}
42
+ {{kernel.def_kernel(inputs=kernel_args, outputs=Y_list, aliases=aliases)}}
43
+ {
44
+ {{kernel.maybe_codegen_profile()}}
45
+ {{ template.codegen_blocks(
46
+ num_threads, N, K, micro_gemm, is_dynamic_M, kernel, GemmOuts[0], config, L1_cache_size, L2_cache_size, X_list[0], W_list[0]
47
+ ) }}
48
+ {%- if num_threads > 1 %}
49
+ #pragma omp parallel num_threads({{num_threads}})
50
+ {
51
+ {{ template.codegen_multi_threads_params()|indent(8, false) }}
52
+ {%- else %}
53
+ {
54
+ {{ template.codegen_single_thread_params(is_dynamic_M)|indent(8, false) }}
55
+ {%- endif %}
56
+ {{ micro_gemm.codegen_init(kernel) }}
57
+ {%- set acc_buf_name_list=[] %}
58
+ {%- set acc_buf_name_prefix = "local_acc_buf_" %}
59
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
60
+ {%- set acc_buf_name = acc_buf_name_prefix + gemm_idx|string %}
61
+ {{ kernel.define_buffer(acc_buf_name, ["Mc_blocks*Mr", "Nc_blocks*Nr"], acc_buf_dtype) }}
62
+ {%- set acc_buf_name_list=acc_buf_name_list.append(acc_buf_name) %}
63
+ {%- endfor %}
64
+ for (int64_t mc_block_id = 0; mc_block_id < num_Mc_blocks_per_thread; mc_block_id++) {
65
+ {{ template.codegen_m_loop_params()|indent(12, false) }}
66
+ for (int64_t nc = n_block_start; nc < n_block_end; nc += Nc_blocks) {
67
+ {{ template.codegen_n_loop_params()|indent(16, false) }}
68
+ {%- set acc_list=[] %}
69
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
70
+ {%- set acc_list = acc_list.append( kernel.local_buffers[acc_buf_name_list[gemm_idx]] ) %}
71
+ {{ kernel.reinit_buffer_if_null(acc_buf_name_list[gemm_idx]) }}
72
+ {%- endfor %}
73
+ for (int64_t kc = k_block_start; kc < k_block_end; kc += Kc_blocks) {
74
+ int64_t k_start = kc * Kr;
75
+ int64_t k_end = std::min(std::min(kc + Kc_blocks, k_block_end) * Kr, K);
76
+ {%- set tile_X_list=[] %}
77
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
78
+ {%- set tile_X_list = tile_X_list.append( kernel.slice_nd(X_list[gemm_idx], [("m_start", "m_end"), ("k_start", "k_end")]) ) %}
79
+ {%- endfor %}
80
+ for (int64_t nci = nc; nci < nc_block_end; nci++) {
81
+ {%- set tile_W_3d_list=[] %}
82
+ {%- set tile_W_list=[] %}
83
+ {%- set acc_slice_list=[] %}
84
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
85
+ {%- set acc_slice_list = acc_slice_list.append(
86
+ kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("(nci - nc)*Nr", "(nci - nc + 1)*Nr")])
87
+ ) %}
88
+ {%- set tile_W_3d_list = tile_W_3d_list.append(
89
+ kernel.slice_nd(W_list[gemm_idx], [("nci", "nci + 1"), ("k_start", "k_end"), ()])
90
+ ) %}
91
+ {%- endfor %}
92
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
93
+ {%- set tile_W_list = tile_W_list.append(
94
+ kernel.view(tile_W_3d_list[gemm_idx], ["k_end - k_start", micro_gemm.register_blocking.block_n])
95
+ ) %}
96
+ {%- endfor %}
97
+ if (kc == k_block_start) {
98
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
99
+ {{ micro_gemm.codegen_call(
100
+ kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=False
101
+ )|indent(28, false) }}
102
+ {%- endfor %}
103
+ } else {
104
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
105
+ {{ micro_gemm.codegen_call(
106
+ kernel, tile_X_list[gemm_idx], tile_W_list[gemm_idx], acc_slice_list[gemm_idx], accum=True
107
+ )|indent(28, false) }}
108
+ {%- endfor %}
109
+ }
110
+ }
111
+ }
112
+ {
113
+ {%- set tile_acc_list = [] %}
114
+ {%- set tile_Y_list = [] %}
115
+ {%- for gemm_idx in range(0, gemm_grouped_num, 1) %}
116
+ {%- set tile_acc_list = tile_acc_list.append(
117
+ kernel.slice_nd(acc_list[gemm_idx], [("0", "m_end - m_start"), ("0", "n_end - n_start")])
118
+ ) %}
119
+ {%- set tile_Y_list = tile_Y_list.append(
120
+ kernel.slice_nd(Y_2d_list[gemm_idx], [("m_start", "m_end"), ("n_start", "n_end")])
121
+ ) %}
122
+ {%- endfor %}
123
+ {{ kernel.store_outputs(
124
+ tile_Y_list,
125
+ tile_acc_list,
126
+ GemmOuts,
127
+ epilogue_nodes,
128
+ offsets=("m_start", "n_start"),
129
+ reindexers=reindexers,
130
+ multi_output_buffers=multi_output_buffers
131
+ )|indent(20, false)
132
+ }}
133
+ }
134
+ }
135
+ }
136
+ {{ micro_gemm.codegen_finalize(kernel) }}
137
+ }
138
+ }
139
+ """
140
+
141
+
142
+ def get_deduplicated_act(act_mapping: dict[int, ir.IRNode]) -> list[ir.IRNode]:
143
+ act_deduplicated = []
144
+ act_deduplicated_name: OrderedSet[str] = OrderedSet()
145
+ for act_idx in range(len(act_mapping.values())):
146
+ act = act_mapping[act_idx]
147
+ if act.get_name() not in act_deduplicated_name:
148
+ act_deduplicated.append(act)
149
+ act_deduplicated_name.add(act.get_name())
150
+ return act_deduplicated
151
+
152
+
153
+ class CppGroupedGemmTemplate(CppGemmTemplate):
154
+ def __init__(
155
+ self,
156
+ input_nodes: list[ir.IRNode],
157
+ layout: ir.Layout,
158
+ num_threads: int,
159
+ register_blocking: GemmBlocking,
160
+ beta: int = 1,
161
+ alpha: int = 1,
162
+ has_bias: bool = False,
163
+ epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
164
+ act_mapping: Optional[dict[int, ir.IRNode]] = None,
165
+ gemm_grouped_num: int = 1,
166
+ ) -> None:
167
+ """
168
+ Template for Group of GEMMs:
169
+ * Each GEMM has the same dimensions (m, n, k) and the same leading dimensions (lda, ldb, ldc)
170
+ for their A, B, and C matrices.
171
+ * Each GEMM has distinct or shared activations, has distinct weight, has unique bias or no bias, has distinct epilogues.
172
+ * In the current implementation, the outputs of all GEMMs are accumulated using pointwise epilogues.
173
+ This behavior can be extended in the future if needed.
174
+ """
175
+ super().__init__(
176
+ input_nodes,
177
+ layout,
178
+ num_threads,
179
+ register_blocking,
180
+ beta,
181
+ alpha,
182
+ has_bias,
183
+ epilogue_creator,
184
+ )
185
+ self.act_mapping = act_mapping
186
+ self.gemm_grouped_num = gemm_grouped_num
187
+ # pyrefly: ignore [bad-override]
188
+ self.output_node: list[ir.Buffer] = [
189
+ ir.Buffer(name="buf_out" + str(idx), layout=layout)
190
+ for idx in range(gemm_grouped_num)
191
+ ]
192
+
193
+ @classmethod
194
+ # pyrefly: ignore [bad-override]
195
+ def add_choices(
196
+ cls,
197
+ choices: list[ChoiceCaller],
198
+ layout: ir.Layout,
199
+ input_nodes: list[ir.IRNode],
200
+ beta: int = 1,
201
+ alpha: int = 1,
202
+ has_bias: tuple[bool, ...] = (False, False),
203
+ trans_w: bool = False,
204
+ input_indices: Optional[list[int]] = None,
205
+ epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
206
+ act_mapping: Optional[dict[int, ir.IRNode]] = None, # gemm idx to its act buf
207
+ ) -> DataProcessorTemplateWrapper:
208
+ # Input nodes order: x, optional[x1], ... w0, w1, ... optional[b0], optional[b1], ...
209
+ gemm_grouped_num = len(has_bias)
210
+ assert act_mapping
211
+ act_deduplicated = get_deduplicated_act(act_mapping)
212
+ wgt_start_idx = len(act_deduplicated)
213
+ bias_start_idx = wgt_start_idx + gemm_grouped_num
214
+ input_indices = list(range(len(input_nodes)))
215
+
216
+ _T = TypeVar("_T", ir.IRNode, torch.Tensor)
217
+ _U = TypeVar("_U", ir.Layout, torch.Tensor)
218
+
219
+ def reorder_and_filter(
220
+ inputs: list[_T],
221
+ layout_or_out: _U,
222
+ ) -> tuple[list[_T], _U]:
223
+ assert input_indices is not None, "input_indices must be set"
224
+ return [inputs[idx] for idx in input_indices], layout_or_out
225
+
226
+ new_inputs, new_layout = reorder_and_filter(input_nodes, layout)
227
+
228
+ def maybe_to_dense(
229
+ inputs: list[_T],
230
+ layout_or_out: _U,
231
+ ) -> tuple[list[_T], _U]:
232
+ new_inputs = list(inputs)
233
+ for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num):
234
+ if isinstance(inputs[idx], torch.Tensor):
235
+ W = inputs[idx]
236
+ assert isinstance(W, torch.Tensor), "W must be a torch.Tensor"
237
+ # pyrefly: ignore [unsupported-operation]
238
+ new_inputs[idx] = W.to_dense() if W.is_mkldnn else W
239
+ return new_inputs, layout_or_out
240
+
241
+ def normalize_shapes(
242
+ inputs: list[_T],
243
+ layout_or_out: _U,
244
+ ) -> tuple[list[_T], _U]:
245
+ new_inputs: list[_T] = list(inputs)
246
+ if not trans_w:
247
+ return new_inputs, layout_or_out
248
+ X = new_inputs[0]
249
+ for wgt_idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num):
250
+ new_input = new_inputs[wgt_idx]
251
+ new_inputs[wgt_idx] = transpose_w(new_input, trans_w)
252
+ for bias_idx in range(bias_start_idx, len(new_inputs)):
253
+ # pyrefly: ignore [bad-argument-type]
254
+ new_bias = expand_bias(new_inputs[bias_idx], X)
255
+ assert new_bias is not None
256
+ # pyrefly: ignore [unsupported-operation]
257
+ new_inputs[bias_idx] = new_bias
258
+ return new_inputs, layout_or_out
259
+
260
+ num_threads = parallel_num_threads()
261
+ new_inputs, _ = normalize_shapes(*maybe_to_dense(new_inputs, new_layout))
262
+ m, n, k, *_ = mm_args(new_inputs[0], new_inputs[wgt_start_idx])
263
+ output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
264
+ new_inputs[0].get_dtype()
265
+ )
266
+ micro_gemm = create_micro_gemm(
267
+ "micro_gemm",
268
+ m,
269
+ n,
270
+ k,
271
+ input_dtype=new_inputs[0].get_dtype(),
272
+ input2_dtype=new_inputs[wgt_start_idx].get_dtype(),
273
+ output_dtype=output_dtype,
274
+ compute_dtype=compute_dtype,
275
+ alpha=alpha,
276
+ num_threads=num_threads,
277
+ )
278
+ assert micro_gemm is not None
279
+ _, block_n, _ = micro_gemm.register_blocking
280
+ new_size, padded_n = cls.get_padded_size(
281
+ n, block_n, k, should_block_weight=True
282
+ )
283
+ padding = padded_n - n
284
+
285
+ def pack_weight(
286
+ inputs: list[_T],
287
+ layout_or_out: _U,
288
+ ) -> tuple[list[_T], _U]:
289
+ new_W_list = []
290
+ new_inputs = list(inputs)
291
+ W_list = new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num]
292
+ for W in W_list:
293
+ blocked_w = cls.block_weight(W, new_size, padding)
294
+ new_W_list.append(cls.pack_vnni_weight(blocked_w, micro_gemm, new_size))
295
+ new_inputs[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = new_W_list
296
+ return new_inputs, layout_or_out
297
+
298
+ def preprocessor(
299
+ inputs: list[_T],
300
+ layout: _U,
301
+ ) -> tuple[list[_T], _U]:
302
+ return pack_weight(
303
+ *normalize_shapes(*maybe_to_dense(*reorder_and_filter(inputs, layout)))
304
+ )
305
+
306
+ def postprocessor(output: _T) -> _T:
307
+ if isinstance(output, ir.TensorBox):
308
+ template_buffer = ir.InputsKernel.unwrap_storage_for_input(output)
309
+ assert isinstance(template_buffer, ir.CppTemplateBuffer)
310
+ new_input_nodes, _ = reorder_and_filter(input_nodes, layout)
311
+ W_nodes = new_input_nodes[
312
+ wgt_start_idx : wgt_start_idx + gemm_grouped_num
313
+ ]
314
+ W_tensor = []
315
+ for W_node in W_nodes:
316
+ assert W_node.get_name() in V.graph.constants
317
+ # pyrefly: ignore [bad-argument-type]
318
+ W_tensor.append(V.graph.constants[W_node.get_name()])
319
+ # pyrefly: ignore [unsupported-operation]
320
+ new_input_nodes[wgt_start_idx : wgt_start_idx + gemm_grouped_num] = (
321
+ W_tensor # type: ignore[assignment]
322
+ )
323
+ new_input_nodes, _ = pack_weight(
324
+ *normalize_shapes(*maybe_to_dense(new_input_nodes, layout))
325
+ )
326
+ # Prune unused tensors
327
+ prune_tensors(input_nodes, new_input_nodes)
328
+ for idx in range(wgt_start_idx, wgt_start_idx + gemm_grouped_num):
329
+ W_packed = new_input_nodes[idx]
330
+ assert isinstance(W_packed, torch.Tensor)
331
+ W_packed_constant = V.graph.add_tensor_constant(W_packed)
332
+ template_buffer.inputs[idx] = (
333
+ ir.InputsKernel.unwrap_storage_for_input(W_packed_constant)
334
+ )
335
+
336
+ return output
337
+
338
+ template = DataProcessorTemplateWrapper(
339
+ CppGroupedGemmTemplate,
340
+ preprocessor,
341
+ postprocessor,
342
+ input_nodes=input_nodes,
343
+ layout=layout,
344
+ num_threads=num_threads,
345
+ register_blocking=micro_gemm.register_blocking,
346
+ beta=beta,
347
+ alpha=alpha,
348
+ has_bias=has_bias,
349
+ epilogue_creator=epilogue_creator,
350
+ act_mapping=act_mapping,
351
+ gemm_grouped_num=gemm_grouped_num,
352
+ )
353
+ template.maybe_append_choice(choices)
354
+ return template
355
+
356
+ def render( # type: ignore[override,return,no-untyped-def]
357
+ self,
358
+ kernel: CppTemplateKernel,
359
+ template_buffer_node: Optional[ir.CppTemplateBuffer] = None,
360
+ flag_template_buffer_has_other_users: Optional[bool] = None,
361
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
362
+ **kwargs,
363
+ ) -> str:
364
+ assert self.act_mapping
365
+ act_deduplicated = get_deduplicated_act(self.act_mapping)
366
+ wgt_start_idx = len(act_deduplicated)
367
+ bias_start_idx = wgt_start_idx + self.gemm_grouped_num
368
+ X_list = list(self.act_mapping.values())
369
+ W_list = self.input_nodes[wgt_start_idx : wgt_start_idx + self.gemm_grouped_num]
370
+ inp_list = []
371
+ cur_idx = bias_start_idx
372
+ for inp_idx in range(self.gemm_grouped_num):
373
+ inp = None
374
+ # pyrefly: ignore [bad-index, index-error]
375
+ if self.has_bias[inp_idx]:
376
+ inp = self.input_nodes[cur_idx]
377
+ cur_idx += 1
378
+ inp_list.append(inp)
379
+
380
+ Y_list = self.output_node
381
+ multi_output_buffers = None
382
+ if template_buffer_node is not None:
383
+ W_list = template_buffer_node.inputs[
384
+ wgt_start_idx : wgt_start_idx + self.gemm_grouped_num
385
+ ]
386
+ assert isinstance(template_buffer_node.outputs, list)
387
+ Y_list = template_buffer_node.outputs
388
+ counters["inductor"]["cpp_grouped_gemm_template"] += 1
389
+ multi_output_buffers = template_buffer_node.outputs
390
+
391
+ template_buffer = Y_list[0]
392
+ fake_buffers: list[ir.Buffer] = []
393
+ Y_2d_list = Y_list
394
+ output_dtype, compute_dtype = get_gemm_template_output_and_compute_dtype(
395
+ X_list[0].get_dtype()
396
+ )
397
+ micro_gemm = create_micro_gemm(
398
+ f"{kernel.kernel_name}_micro_gemm",
399
+ self.m,
400
+ self.n,
401
+ self.k,
402
+ input_dtype=X_list[0].get_dtype(),
403
+ input2_dtype=W_list[0].get_dtype(),
404
+ output_dtype=output_dtype,
405
+ compute_dtype=compute_dtype,
406
+ alpha=self.alpha,
407
+ num_threads=self.num_threads,
408
+ )
409
+ assert micro_gemm is not None
410
+ assert self.register_blocking == micro_gemm.register_blocking
411
+ self.log_blockings()
412
+ if isinstance(micro_gemm, CppMicroGemmAMX):
413
+ counters["inductor"]["cpp_micro_gemm_amx_counter"] += 1
414
+
415
+ L1_cache_size = torch.cpu.get_capabilities().get(
416
+ "l1d_cache_size", 0
417
+ ) # per core cache size in Bytes
418
+ assert L1_cache_size > 0, f"Expect L1_cache_size > 0 but got {L1_cache_size}"
419
+
420
+ L2_cache_size = torch.cpu.get_capabilities().get(
421
+ "l2_cache_size", 0
422
+ ) # per core cache size in Bytes
423
+ assert L2_cache_size > 0, f"Expect L2_cache_size > 0 but got {L2_cache_size}"
424
+
425
+ epilogues: list[ir.IRNode] = []
426
+ reindexers: list[Optional[Callable[[list[Any]], list[Any]]]] = []
427
+ gemm_output_buffers: list[ir.Buffer] = []
428
+ for out_buf_idx in range(self.gemm_grouped_num):
429
+ gemm_output_name = f"{template_buffer.get_name()}_GemmOut" + str(
430
+ out_buf_idx
431
+ )
432
+ gemm_output_buffers.append(
433
+ ir.Buffer(name=gemm_output_name, layout=template_buffer.layout)
434
+ )
435
+
436
+ assert not self.epilogue_creator, (
437
+ "epilogue_creator is not supported yet in Grouped GEMM Template"
438
+ )
439
+
440
+ kernel_args: dict[str, Optional[ir.IRNode]] = {}
441
+ for x_idx in range(wgt_start_idx):
442
+ kernel_args["X" + str(x_idx)] = act_deduplicated[x_idx]
443
+ for w_idx in range(self.gemm_grouped_num):
444
+ kernel_args["W" + str(w_idx)] = W_list[w_idx]
445
+ for inp_idx in range(self.gemm_grouped_num):
446
+ kernel_args["inp" + str(inp_idx)] = inp_list[inp_idx]
447
+
448
+ def _bias_add_epilogue(buf: ir.IRNode, inp: ir.IRNode) -> ir.Pointwise:
449
+ return create_epilogue_with_attr(
450
+ buf, "bias_add", other=inp, beta=self.beta, dtype=self.layout.dtype
451
+ )
452
+
453
+ for gemm_idx, inp in enumerate(inp_list):
454
+ if inp:
455
+ buffer_name = Y_list[gemm_idx].get_name()
456
+ epilogues.append(
457
+ ir.ComputedBuffer(
458
+ name=buffer_name,
459
+ layout=template_buffer.layout,
460
+ data=_bias_add_epilogue(gemm_output_buffers[gemm_idx], inp),
461
+ )
462
+ )
463
+ reindexers.append(None)
464
+
465
+ if epilogue_nodes:
466
+ epilogues.extend(epilogue_nodes)
467
+ for epilogue_node in epilogue_nodes:
468
+ Y = cast(ir.Buffer, epilogue_node)
469
+ _, reindexers = gen_2d_view_of_epilogue_buf(
470
+ Y,
471
+ template_buffer,
472
+ [
473
+ epilogue_node,
474
+ ],
475
+ reindexers,
476
+ default_reindexers=[
477
+ None,
478
+ ],
479
+ )
480
+
481
+ options = dict(
482
+ N=self.n,
483
+ K=self.k,
484
+ PADDED_N=self.padded_n,
485
+ aliases={},
486
+ beta=self.beta,
487
+ alpha=self.alpha,
488
+ num_threads=self.num_threads,
489
+ micro_gemm=micro_gemm,
490
+ is_dynamic_M=self.is_dynamic_M,
491
+ template=self,
492
+ kernel=kernel,
493
+ export_declaration=get_export_declaration(),
494
+ acc_buf_dtype=torch.float,
495
+ DTYPE_TO_CPP=DTYPE_TO_CPP,
496
+ L1_cache_size=L1_cache_size,
497
+ L2_cache_size=L2_cache_size,
498
+ config=config,
499
+ epilogue_nodes=epilogues,
500
+ GemmOuts=gemm_output_buffers,
501
+ reindexers=reindexers,
502
+ kernel_args=kernel_args,
503
+ X_list=X_list,
504
+ W_list=W_list,
505
+ gemm_grouped_num=self.gemm_grouped_num,
506
+ Y_list={"Y" + str(idx): Y for idx, Y in enumerate(Y_list)},
507
+ Y_2d_list=Y_2d_list,
508
+ multi_output_buffers=multi_output_buffers,
509
+ )
510
+ with contextlib.ExitStack() as stack:
511
+ stack.enter_context(
512
+ patch.object(V.graph, "get_dtype", self._fake_get_dtype(fake_buffers))
513
+ )
514
+ return self._template_from_string(GEMM_TEMPLATE).render(**options)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_micro_gemm.py ADDED
@@ -0,0 +1,2232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import dataclasses
3
+ import operator
4
+ import sys
5
+ from collections.abc import Callable
6
+ from enum import Enum
7
+ from typing import Optional
8
+
9
+ import torch
10
+
11
+ from .. import cpp_builder, ir
12
+ from ..cpu_vec_isa import (
13
+ pick_vec_isa,
14
+ VecAMX,
15
+ VecAVX2,
16
+ VecAVX512,
17
+ VecAVX512VNNI,
18
+ VecISA,
19
+ VecNEON,
20
+ VecSVE256,
21
+ )
22
+ from ..utils import IndentedBuffer, parallel_num_threads
23
+ from ..virtualized import V
24
+ from .common import KernelTemplate
25
+ from .cpp_template_kernel import CppTemplateKernel
26
+ from .cpp_utils import DTYPE_TO_CPP, GemmBlocking, value_to_cpp
27
+
28
+
29
+ class LayoutType(Enum):
30
+ NORMAL = 0
31
+ VNNI2 = 1
32
+ VNNI4 = 2
33
+
34
+
35
+ _IS_WINDOWS = sys.platform == "win32"
36
+
37
+
38
+ def get_restrict_keyword() -> str:
39
+ if _IS_WINDOWS:
40
+ # https://learn.microsoft.com/en-us/cpp/cpp/extension-restrict?view=msvc-170
41
+ return "__restrict"
42
+ else:
43
+ return "__restrict__"
44
+
45
+
46
+ class CppMicroGemm:
47
+ """
48
+ A class that codegens a kernel that computes small-sized matrix multiplication.
49
+
50
+ A micro GEMM kernel is responsible for register blocking, instruction selection,
51
+ and other CPU architecture-specific optimizations.
52
+
53
+ The subclasses need to override `codegen_define` to define the kernel function
54
+ that is called by the code generated by `codegen_call`.
55
+ """
56
+
57
+ # TODO(jgong5): support constant shapes and lds as template args.
58
+ DECLARE_KERNEL = r"""
59
+ template <bool accum, bool prefetch=false>
60
+ inline void {{kernel_name}}(
61
+ {%- if kernel_extra_args_declare %}
62
+ {{kernel_extra_args_declare}}
63
+ {%- endif %}
64
+ const {{input_t}}* {{restrict_keyword}} A,
65
+ const {{input2_t}}* {{restrict_keyword}} B,
66
+ {{output_t}}* {{restrict_keyword}} C,
67
+ int64_t M,
68
+ int64_t N,
69
+ int64_t K,
70
+ int64_t lda,
71
+ int64_t ldb,
72
+ int64_t ldc
73
+ )
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ name,
79
+ input_dtype,
80
+ input2_dtype,
81
+ output_dtype,
82
+ compute_dtype,
83
+ register_blocking,
84
+ alpha=1,
85
+ ) -> None:
86
+ self.name = name
87
+ self.input_dtype = input_dtype
88
+ assert input2_dtype is not None
89
+ self.input2_dtype = input2_dtype
90
+ self.output_dtype = output_dtype
91
+ self.compute_dtype = compute_dtype
92
+ self.register_blocking = register_blocking
93
+ self.alpha = alpha
94
+ self.pack_vnni_B_locally = False
95
+
96
+ def get_common_options(self):
97
+ if self.input_dtype in [torch.uint8, torch.int8]:
98
+ assert self.compute_dtype == torch.int32
99
+ assert self.output_dtype == torch.int32
100
+ assert self.input2_dtype == torch.int8
101
+ return {
102
+ "torch": torch,
103
+ "kernel_name": self.name,
104
+ "input_dtype": self.input_dtype,
105
+ "input2_dtype": self.input2_dtype,
106
+ "output_dtype": self.output_dtype,
107
+ "compute_dtype": self.compute_dtype,
108
+ "input_t": DTYPE_TO_CPP[self.input_dtype],
109
+ "input2_t": DTYPE_TO_CPP[self.input2_dtype],
110
+ "output_t": DTYPE_TO_CPP[self.output_dtype],
111
+ "compute_t": DTYPE_TO_CPP[self.compute_dtype],
112
+ "alpha": self.alpha,
113
+ "kernel_extra_args_declare": self.get_kernel_extra_args_declare(),
114
+ "int8_gemm": self.input_dtype in [torch.uint8, torch.int8],
115
+ "vnni_size": 4 if self.input_dtype in [torch.uint8, torch.int8] else 2,
116
+ "restrict_keyword": get_restrict_keyword(),
117
+ "pack_vnni_B_locally": self.pack_vnni_B_locally,
118
+ "template": self,
119
+ "is_woq_int4": self.is_woq_int4(),
120
+ }
121
+
122
+ def get_kernel_declaration(self):
123
+ options = self.get_common_options()
124
+ return KernelTemplate._template_from_string(self.DECLARE_KERNEL).render(options)
125
+
126
+ def get_kernel_extra_args_declare(self) -> str:
127
+ return ""
128
+
129
+ def get_kernel_extra_args(self, **kwargs) -> list[str]:
130
+ return []
131
+
132
+ def codegen_define(self, kernel: CppTemplateKernel) -> str:
133
+ raise NotImplementedError
134
+
135
+ def codegen_call(
136
+ self,
137
+ kernel: CppTemplateKernel,
138
+ A: ir.Buffer,
139
+ B: ir.Buffer,
140
+ C: ir.Buffer,
141
+ accum: bool,
142
+ prefetch: bool = False,
143
+ **kwargs_for_extra_args,
144
+ ) -> str:
145
+ """
146
+ Generate the code for calling the templated kernel that computes
147
+ `C += alpha * A @ B` if `accum` is True, or `C = alpha * A @ B` otherwise.
148
+ """
149
+ A_ptr = f"&({kernel.index(A, [0, 0])})"
150
+ B_ptr = f"&({kernel.index(B, [0, 0])})"
151
+ C_ptr = f"&({kernel.index(C, [0, 0])})"
152
+ M = kernel.size(C, 0)
153
+ N = kernel.size(C, 1)
154
+ K = kernel.size(A, 1)
155
+ lda = kernel.stride(A, 0)
156
+ ldb = kernel.stride(B, 0)
157
+ ldc = kernel.stride(C, 0)
158
+ res = IndentedBuffer()
159
+ res.writeline(
160
+ f"{self.name}<{value_to_cpp(accum, 'bool')}, {value_to_cpp(prefetch, 'bool')}>("
161
+ )
162
+ with res.indent():
163
+ kwargs_for_extra_args.update({"kernel": kernel})
164
+ extra_args = self.get_kernel_extra_args(**kwargs_for_extra_args)
165
+ for arg in extra_args:
166
+ res.writeline(arg)
167
+ res.writeline(f"{A_ptr},")
168
+ res.writeline(f"{B_ptr},")
169
+ res.writeline(f"{C_ptr},")
170
+ res.writeline(f"{M},")
171
+ res.writeline(f"{N},")
172
+ res.writeline(f"{K},")
173
+ res.writeline(f"{lda},")
174
+ res.writeline(f"{ldb},")
175
+ res.writeline(f"{ldc}")
176
+ res.writeline(");")
177
+ return res.getvalue()
178
+
179
+ def use_local_vnni_blocking(self, should_block_weight: bool):
180
+ self.pack_vnni_B_locally = should_block_weight
181
+
182
+ def codegen_init(
183
+ self,
184
+ kernel: CppTemplateKernel,
185
+ ) -> str:
186
+ return ""
187
+
188
+ def codegen_finalize(
189
+ self,
190
+ kernel: CppTemplateKernel,
191
+ ) -> str:
192
+ return ""
193
+
194
+ def get_b_layout(self) -> LayoutType:
195
+ return LayoutType.NORMAL
196
+
197
+ ALLOCATE_WEIGHT_BUFFER = r"""
198
+ {%- if is_msvc_compiler %}
199
+ // MSVC doesn't support stack-allocated dynamic-sized arrays, so using heap memory here.
200
+ auto heap_deq_b_buf_ptr = std::make_unique<{{buffer_dtype}}[]>({{buffer_size}});
201
+ {{buffer_dtype}}* {{buffer_name}} = heap_deq_b_buf_ptr.get();
202
+ {%- else %}
203
+ // It's safe to use a stack-allocated array since the blocking strategy would
204
+ // require us to allocate an array that's smaller than the size of L1D cache,
205
+ // and the default per thread max stack size on Linux is quite higher,
206
+ // so we need not worry about stack overflow.
207
+ alignas(4096) {{buffer_dtype}} {{buffer_name}}[{{buffer_size}}];
208
+ {%- endif %}
209
+ """
210
+
211
+ def codegen_allocate_weight_buffer(
212
+ self, buffer_name: str, buffer_dtype: str, *size_args
213
+ ) -> str:
214
+ buffer_size = " * ".join(map(str, size_args))
215
+ return KernelTemplate._template_from_string(self.ALLOCATE_WEIGHT_BUFFER).render(
216
+ {
217
+ "buffer_name": buffer_name,
218
+ "buffer_dtype": buffer_dtype,
219
+ "buffer_size": buffer_size,
220
+ "is_msvc_compiler": cpp_builder.is_msvc_cl(),
221
+ }
222
+ )
223
+
224
+ def is_woq_int4(self):
225
+ return False
226
+
227
+
228
+ @dataclasses.dataclass
229
+ class CppMicroGemmConfig:
230
+ input_dtype: torch.dtype
231
+ input2_dtype: torch.dtype
232
+ output_dtype: torch.dtype
233
+ compute_dtype: torch.dtype
234
+ vec_isa_cls: type[VecISA]
235
+ register_blocking: GemmBlocking
236
+ extra_check: Optional[Callable[..., bool]] = None
237
+
238
+
239
+ micro_gemm_configs: dict[type[CppMicroGemm], list[CppMicroGemmConfig]] = {}
240
+
241
+
242
+ def register_micro_gemm(*configs):
243
+ def inner(cls):
244
+ assert cls not in micro_gemm_configs, (
245
+ f"Duplicate micro_gemm registration for {cls}"
246
+ )
247
+ assert len(configs) > 0, f"No micro_gemm configs provided for {cls}"
248
+ micro_gemm_configs[cls] = list(configs)
249
+ return cls
250
+
251
+ return inner
252
+
253
+
254
+ def generate_gemm_config(
255
+ vec_isa_cls,
256
+ register_blockings,
257
+ input_dtype=torch.float,
258
+ input2_dtype=None,
259
+ output_dtype=None,
260
+ compute_dtype=None,
261
+ extra_check=None,
262
+ ):
263
+ if output_dtype is None:
264
+ output_dtype = input_dtype
265
+ if compute_dtype is None:
266
+ compute_dtype = output_dtype
267
+ if input2_dtype is None:
268
+ input2_dtype = input_dtype
269
+ return [
270
+ CppMicroGemmConfig(
271
+ input_dtype,
272
+ input2_dtype,
273
+ output_dtype,
274
+ compute_dtype,
275
+ vec_isa_cls,
276
+ GemmBlocking(*blocking),
277
+ extra_check,
278
+ )
279
+ for blocking in register_blockings
280
+ ]
281
+
282
+
283
+ class CppMicroGemmRef(CppMicroGemm):
284
+ """
285
+ A reference implementation of the CppMicroGemm class with naive C++ code.
286
+ It is used for correctness debugging.
287
+ """
288
+
289
+ TEMPLATE_ENTRY = r"""
290
+ {{declare_kernel}} {
291
+ for (int64_t m = 0; m < M; ++m) {
292
+ for (int64_t n = 0; n < N; ++n) {
293
+ {{compute_t}} result = accum ? C[m * ldc + n] : 0;
294
+ for (int64_t k = 0; k < K; ++k) {
295
+ result += ({{compute_t}})A[m * lda + k] * ({{compute_t}})B[k * ldb + n] * {{alpha}};
296
+ }
297
+ C[m * ldc + n] = result;
298
+ }
299
+ }
300
+ }
301
+ """
302
+
303
+ def __init__(
304
+ self, name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha
305
+ ) -> None:
306
+ super().__init__(
307
+ name,
308
+ input_dtype,
309
+ input2_dtype,
310
+ output_dtype,
311
+ compute_dtype,
312
+ GemmBlocking(1, 1, 1),
313
+ alpha,
314
+ )
315
+
316
+ def codegen_define(self, kernel: CppTemplateKernel) -> str:
317
+ options = {
318
+ "declare_kernel": self.get_kernel_declaration(),
319
+ **self.get_common_options(),
320
+ }
321
+ return KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options)
322
+
323
+
324
+ def is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k):
325
+ return (
326
+ k % config.register_blocking.block_k == 0
327
+ and n % config.register_blocking.block_n == 0
328
+ and m < 16
329
+ )
330
+
331
+
332
+ # extra check for small M dimension for int8 WoQ case
333
+ def check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs):
334
+ return is_int8_woq_gemm_small_m_dim_corner_case(config, m, n, k) and not kwargs.get(
335
+ "dynamic_M", False
336
+ )
337
+
338
+
339
+ # For int8 WoQ GEMM with small M, we use different blockings that shouldn't be used otherwise
340
+ def do_not_use_with_small_m_for_int8_woq(config, m, n, k, alpha, num_threads, **kwargs):
341
+ return not check_int8_woq_small_m_dim(config, m, n, k, alpha, num_threads, **kwargs)
342
+
343
+
344
+ @register_micro_gemm(
345
+ *generate_gemm_config(
346
+ VecAVX512,
347
+ [(8, 48, 1), (8, 32, 1), (16, 16, 1)],
348
+ input_dtype=torch.float,
349
+ ),
350
+ *generate_gemm_config(
351
+ VecAVX512,
352
+ [(8, 48, 1), (8, 32, 1), (16, 16, 1)],
353
+ input_dtype=torch.bfloat16,
354
+ output_dtype=torch.float,
355
+ ),
356
+ *generate_gemm_config(
357
+ VecAVX512,
358
+ [(8, 48, 1), (8, 32, 1), (16, 16, 1)],
359
+ input_dtype=torch.half,
360
+ output_dtype=torch.float,
361
+ ),
362
+ *generate_gemm_config(
363
+ VecAVX512,
364
+ [(8, 48, 1), (8, 32, 1), (16, 16, 1)],
365
+ input_dtype=torch.bfloat16,
366
+ input2_dtype=torch.int8,
367
+ output_dtype=torch.float,
368
+ compute_dtype=torch.float,
369
+ extra_check=do_not_use_with_small_m_for_int8_woq,
370
+ ),
371
+ *generate_gemm_config(
372
+ VecAVX512,
373
+ [
374
+ (4, 32, 64),
375
+ (8, 32, 64),
376
+ ],
377
+ input_dtype=torch.bfloat16,
378
+ input2_dtype=torch.int8,
379
+ output_dtype=torch.float,
380
+ compute_dtype=torch.float,
381
+ extra_check=check_int8_woq_small_m_dim,
382
+ ),
383
+ *generate_gemm_config(
384
+ VecAVX2,
385
+ [(4, 24, 1), (4, 16, 1), (8, 8, 1)],
386
+ input_dtype=torch.float,
387
+ ),
388
+ *generate_gemm_config(
389
+ VecAVX2,
390
+ [(4, 24, 1), (4, 16, 1), (8, 8, 1)],
391
+ input_dtype=torch.bfloat16,
392
+ output_dtype=torch.float,
393
+ ),
394
+ *generate_gemm_config(
395
+ VecAVX2,
396
+ [(4, 24, 1), (4, 16, 1), (8, 8, 1)],
397
+ input_dtype=torch.half,
398
+ output_dtype=torch.float,
399
+ ),
400
+ *generate_gemm_config(
401
+ VecAVX2,
402
+ [(4, 24, 1), (4, 16, 1), (8, 8, 1)],
403
+ input_dtype=torch.bfloat16,
404
+ input2_dtype=torch.int8,
405
+ output_dtype=torch.float,
406
+ compute_dtype=torch.float,
407
+ extra_check=do_not_use_with_small_m_for_int8_woq,
408
+ ),
409
+ *generate_gemm_config(
410
+ VecAVX2,
411
+ [
412
+ (2, 16, 64),
413
+ (4, 16, 64),
414
+ ],
415
+ input_dtype=torch.bfloat16,
416
+ input2_dtype=torch.int8,
417
+ output_dtype=torch.float,
418
+ compute_dtype=torch.float,
419
+ extra_check=check_int8_woq_small_m_dim,
420
+ ),
421
+ *generate_gemm_config(
422
+ VecNEON,
423
+ [(4, 24, 1), (4, 16, 1), (8, 8, 1)],
424
+ input_dtype=torch.float,
425
+ input2_dtype=torch.float,
426
+ output_dtype=torch.float,
427
+ compute_dtype=torch.float,
428
+ ),
429
+ *generate_gemm_config(
430
+ VecSVE256,
431
+ [(4, 24, 1), (4, 16, 1), (8, 8, 1)],
432
+ input_dtype=torch.float,
433
+ input2_dtype=torch.float,
434
+ output_dtype=torch.float,
435
+ compute_dtype=torch.float,
436
+ ),
437
+ )
438
+ class CppMicroGemmFP32Vec(CppMicroGemm):
439
+ """
440
+ This class generates the code for micro gemm using fp32 vec instructions for compute.
441
+ It supports input types of torch.float, torch.bfloat16, and torch.half with fp32 output.
442
+ The output of the microkernel is in FP32, but it would be converted to BF16/FP16 in the template,
443
+ if the desired output is BF16/FP16.
444
+ """
445
+
446
+ TEMPLATE_ENTRY = r"""
447
+ {{declare_kernel}} {
448
+ using Vectorized = at::vec::Vectorized<{{compute_t}}>;
449
+ constexpr auto VLEN = Vectorized::size();
450
+ {{kernel.assert_function}}({{block_n}} % VLEN == 0, "block_n dimension must be multiple of Vector size");
451
+ {{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}");
452
+ // TODO(jgong5): loop unroll for M and N
453
+ for (int64_t m = 0; m < M; m += {{block_m}}) {
454
+ int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
455
+ for (int64_t n = 0; n < N; n += {{block_n}}) {
456
+ int64_t block_n = std::min<int64_t>(N - n, {{block_n}});
457
+ if (block_m == {{block_m}} && block_n == {{block_n}}) {
458
+ {%- if not trans_b %}
459
+ {{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum, prefetch>(
460
+ {%- else %}
461
+ {{kernel_name}}_transpose_b_kernel<{{block_m}}, {{block_n}}, accum, prefetch>(
462
+ {%- endif %}
463
+ A + m * lda,
464
+ {%- if not trans_b %}
465
+ B + n,
466
+ {%- else %}
467
+ B + n * ldb,
468
+ {%- endif %}
469
+ C + m * ldc + n,
470
+ K,
471
+ lda,
472
+ ldb,
473
+ ldc
474
+ );
475
+ {%- if tail_n %}
476
+ } else if (block_n == {{block_n}}){
477
+ {%- else %}
478
+ } else {
479
+ {%- endif %}
480
+ switch (block_m) {
481
+ {%- for b in range(block_m - 1, 0, -1) %}
482
+ case {{b}}:
483
+ {%- if not trans_b %}
484
+ {{kernel_name}}_kernel<{{b}}, {{block_n}}, accum, prefetch>(
485
+ {%- else %}
486
+ {{kernel_name}}_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>(
487
+ {%- endif %}
488
+ A + m * lda,
489
+ {%- if not trans_b %}
490
+ B + n,
491
+ {%- else %}
492
+ B + n * ldb,
493
+ {%- endif %}
494
+ C + m * ldc + n,
495
+ K,
496
+ lda,
497
+ ldb,
498
+ ldc
499
+ );
500
+ break;
501
+ {%- endfor %}
502
+ default:
503
+ {{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}");
504
+ }
505
+
506
+ {%- if tail_n %}
507
+ } else {
508
+ switch (block_m) {
509
+ {%- for b in range(block_m, 0, -1) %}
510
+ case {{b}}:
511
+ {%- if not trans_b %}
512
+ {{kernel_name}}_ntail_kernel<{{b}}, {{block_n}}, accum, prefetch>(
513
+ {%- else %}
514
+ {{kernel_name}}_ntail_transpose_b_kernel<{{b}}, {{block_n}}, accum, prefetch>(
515
+ {%- endif %}
516
+ A + m * lda,
517
+ {%- if not trans_b %}
518
+ B + n,
519
+ {%- else %}
520
+ B + n * ldb,
521
+ {%- endif %}
522
+ C + m * ldc + n,
523
+ block_n,
524
+ K,
525
+ lda,
526
+ ldb,
527
+ ldc
528
+ );
529
+ break;
530
+ {%- endfor %}
531
+ default:
532
+ {{kernel.assert_function}}(false, "Unsupported block_m: {{block_m}}");
533
+ }
534
+ }
535
+ {%- else %}
536
+ }
537
+ {%- endif %}
538
+ }
539
+ }
540
+ }
541
+ """
542
+
543
+ TEMPLATE_KERNEL = r"""
544
+
545
+ template <int64_t BLOCK_M, int64_t BLOCK_N, bool accum, bool prefetch=false>
546
+ {%- if not trans_b %}
547
+ {%- if tail_n %}
548
+ inline void {{kernel_name}}_ntail_kernel(
549
+ {%- else %}
550
+ inline void {{kernel_name}}_kernel(
551
+ {%- endif %}
552
+ {%- else %}
553
+ {%- if tail_n %}
554
+ inline void {{kernel_name}}_ntail_transpose_b_kernel(
555
+ {%- else %}
556
+ inline void {{kernel_name}}_transpose_b_kernel(
557
+ {%- endif %}
558
+ {%- endif %}
559
+ const {{input_t}}* {{restrict_keyword}} A,
560
+ const {{input2_t}}* {{restrict_keyword}} B,
561
+ {{output_t}}* {{restrict_keyword}} C,
562
+ {%- if tail_n %}
563
+ int64_t N,
564
+ {%- endif %}
565
+ int64_t K,
566
+ int64_t lda,
567
+ int64_t ldb,
568
+ int64_t ldc
569
+ ) {
570
+ using Vectorized = at::vec::Vectorized<{{compute_t}}>;
571
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
572
+ using VectorizedIn = at::vec::Vectorized<{{input_t}}>;
573
+ {%- endif %}
574
+
575
+ {%- if not trans_b %}
576
+ constexpr auto VLEN = Vectorized::size();
577
+ constexpr auto ROWS = BLOCK_M;
578
+ constexpr auto COLS = BLOCK_N / VLEN;
579
+
580
+ Vectorized va;
581
+ at::vec::VectorizedN<{{compute_t}}, COLS> vb;
582
+ at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc;
583
+
584
+ {%- if tail_n %}
585
+ int64_t rCOLS = (N + VLEN - 1) / VLEN;
586
+ int ntail = N % VLEN;
587
+ {%- endif %}
588
+ auto loadc = [&](auto i) {
589
+ if constexpr (accum) {
590
+ constexpr int row = i / COLS;
591
+ constexpr int col = i % COLS;
592
+ {%- if tail_n %}
593
+ int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN;
594
+ if (col < rCOLS) {
595
+ vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN, load_size);
596
+ }
597
+ {%- else %}
598
+ vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN);
599
+ {%- endif %}
600
+ } else {
601
+ vc[i] = Vectorized(0.0f);
602
+ }
603
+ };
604
+ c10::ForcedUnroll<ROWS * COLS>{}(loadc);
605
+
606
+ auto compute = [&, COLS](auto i, int k) {
607
+ constexpr int row = i / COLS;
608
+ constexpr int col = i % COLS;
609
+ {%- if tail_n %}
610
+ int load_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN;
611
+ {%- endif %}
612
+ if constexpr (col == 0) {
613
+ {%- if alpha != 1 %}
614
+ va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k]) * {{alpha}});
615
+ {%- else %}
616
+ va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + k]));
617
+ {%- endif %}
618
+ }
619
+
620
+ if constexpr (row == 0) {
621
+ {%- if tail_n %}
622
+ if (col < rCOLS) {
623
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
624
+ auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, load_size);
625
+ vb[col] = at::vec::convert<{{compute_t}}>(b);
626
+ {%- elif input2_dtype == torch.int8 %}
627
+ // Convert VLEN int8 elements to int32, and then fp32
628
+ auto b32 = at::vec::convert_to_int32<int8_t>(B + k * ldb + col * VLEN, load_size);
629
+ vb[col] = at::vec::convert<float>(b32);
630
+ {%- else %}
631
+ vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN, load_size);
632
+ {%- endif %}
633
+ } else {
634
+ vb[col] = Vectorized(0.0f);
635
+ }
636
+
637
+ {%- else %}
638
+
639
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
640
+ auto b = VectorizedIn::loadu(B + k * ldb + col * VLEN, VLEN);
641
+ vb[col] = at::vec::convert<{{compute_t}}>(b);
642
+ {%- elif input2_dtype == torch.int8 %}
643
+ // Convert VLEN int8 elements to int32, and then fp32
644
+ auto b32 = at::vec::convert_to_int32<int8_t>(B + k * ldb + col * VLEN);
645
+ if constexpr (prefetch) {
646
+ _mm_prefetch(B + (k + {{block_k}}) * ldb + col * VLEN, _MM_HINT_T0);
647
+ }
648
+ vb[col] = at::vec::convert<float>(b32);
649
+ {%- else %}
650
+ vb[col] = Vectorized::loadu(B + k * ldb + col * VLEN);
651
+ {%- endif %}
652
+ {%- endif %}
653
+
654
+ }
655
+
656
+ constexpr int idx = row * COLS + col;
657
+ {%- if tail_n %}
658
+ if (col < rCOLS) {
659
+ vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]);
660
+ }
661
+ {%- else %}
662
+ vc[idx] = at::vec::fmadd(va, vb[col], vc[idx]);
663
+ {%- endif %}
664
+ };
665
+
666
+ for (int k = 0; k < K; ++k) {
667
+ c10::ForcedUnroll<ROWS * COLS>{}(compute, k);
668
+ }
669
+
670
+ // store to C
671
+ auto storec = [&](auto i) {
672
+ constexpr int row = i / COLS;
673
+ constexpr int col = i % COLS;
674
+ {%- if tail_n %}
675
+ int store_size = (col == rCOLS - 1 && ntail != 0) ? ntail : VLEN;
676
+ if (col < rCOLS) {
677
+ vc[i].store(C + row * ldc + col * VLEN, store_size);
678
+ }
679
+ {%- else %}
680
+ vc[i].store(C + row * ldc + col * VLEN);
681
+ {%- endif %}
682
+ };
683
+ c10::ForcedUnroll<ROWS * COLS>{}(storec);
684
+
685
+ {%- else %}
686
+ // Use 2 implementations for the transposed B:
687
+ // First implementation:
688
+ // Transpose first and then perform outer product calculation in sub-blocks,
689
+ // which introduces an additional transpose overhead of [K, N] compared to the non-transpose version.
690
+ // Second implementation:
691
+ // Directly perform inner product calculation in sub-blocks,
692
+ // which introduces an additional vector reduction of [M, N] compared to the non-transpose version.
693
+ // Therefore, when M * N / (K * N) is large, the first implementation has better performance.
694
+ {%- if tail_n %}
695
+ if (K % Vectorized::size() == 0 && N % Vectorized::size() == 0 && 24 * BLOCK_M > K) {
696
+ {%- else %}
697
+ if (K % Vectorized::size() == 0 && 24 * BLOCK_M > K) {
698
+ {%- endif %}
699
+ // First implementation:
700
+ constexpr auto VLEN = Vectorized::size();
701
+ constexpr auto ROWS = BLOCK_M;
702
+ constexpr auto COLS = BLOCK_N / VLEN;
703
+ int _K = K / VLEN;
704
+ Vectorized va;
705
+ at::vec::VectorizedN<{{compute_t}}, VLEN> vb;
706
+ at::vec::VectorizedN<{{compute_t}}, ROWS*COLS> vc;
707
+ auto loadc = [&](auto i) {
708
+ if constexpr (accum) {
709
+ constexpr int row = i / COLS;
710
+ constexpr int col = i % COLS;
711
+ vc[i] = Vectorized::loadu(C + row * ldc + col * VLEN);
712
+ } else {
713
+ vc[i] = Vectorized(0.0f);
714
+ }
715
+ };
716
+ c10::ForcedUnroll<ROWS * COLS>{}(loadc);
717
+ auto unroll_loadB = [&](auto i, const {{input2_t}}* {{restrict_keyword}} src_ptr) {
718
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
719
+ auto b = VectorizedIn::loadu(src_ptr + i * ldb, VLEN);
720
+ vb[i] = at::vec::convert<{{compute_t}}>(b);
721
+ {%- elif input2_dtype == torch.int8 %}
722
+ auto b32 = at::vec::convert_to_int32<int8_t>(src_ptr + i * ldb, VLEN);
723
+ vb[i] = at::vec::convert<float>(b32);
724
+ {%- else %}
725
+ vb[i] = Vectorized::loadu(src_ptr + i * ldb, VLEN);
726
+ {%- endif %}
727
+ };
728
+ auto compute_trans = [&, COLS](auto i, int k) {
729
+ constexpr int row = i % ROWS;
730
+ constexpr int col = i / ROWS;
731
+ constexpr int e_col = col * VLEN;
732
+ int idk = k * VLEN;
733
+ if constexpr (row == 0) {
734
+ c10::ForcedUnroll<VLEN>{}(unroll_loadB, B + e_col * ldb + idk);
735
+ at::vec::transpose_block(vb);
736
+ }
737
+ constexpr int idx = row * COLS + col;
738
+ {{kernel.unroll_pragma(16)}}
739
+ for (int j = 0; j < VLEN; j++) {
740
+ {%- if alpha != 1 %}
741
+ va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j]) * {{alpha}});
742
+ {%- else %}
743
+ va = Vectorized(static_cast<{{compute_t}}>(A[row * lda + idk + j]));
744
+ {%- endif %}
745
+ vc[idx] = at::vec::fmadd(va, vb[j], vc[idx]);
746
+ }
747
+ };
748
+ for (int k = 0; k < _K; ++k) {
749
+ c10::ForcedUnroll<ROWS * COLS>{}(compute_trans, k);
750
+ }
751
+ // store to C
752
+ auto storec = [&](auto i) {
753
+ constexpr int row = i / COLS;
754
+ constexpr int col = i % COLS;
755
+ vc[i].store(C + row * ldc + col * VLEN);
756
+ };
757
+ c10::ForcedUnroll<ROWS * COLS>{}(storec);
758
+ } else {
759
+ // Second implementation
760
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
761
+ constexpr auto VLEN = VectorizedIn::size();
762
+ {%- else %}
763
+ constexpr auto VLEN = Vectorized::size();
764
+ {%- endif %}
765
+ int _K = (K + VLEN - 1) / VLEN;
766
+ // sub-block size of BLOCK_N and BLOCK_M
767
+ constexpr int sM = {{sub_block_m}};
768
+ constexpr int sN = {{sub_block_n}};
769
+ {%- if tail_n %}
770
+ int bN = (N + sN - 1) / sN;
771
+ {%- else %}
772
+ constexpr int bN = (BLOCK_N + sN - 1) / sN;
773
+ {%- endif %}
774
+ constexpr int bM = (BLOCK_M + sM - 1) / sM;
775
+
776
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
777
+ at::vec::VectorizedN<{{compute_t}}, 2> va;
778
+ at::vec::VectorizedN<{{compute_t}}, 2 * sN> vb;
779
+ {%- else %}
780
+ at::vec::Vectorized<{{compute_t}}> va;
781
+ at::vec::VectorizedN<{{compute_t}}, sN> vb;
782
+ {%- endif %}
783
+ at::vec::VectorizedN<{{compute_t}}, sN * sM> vmid;
784
+
785
+ {%- if tail_n %}
786
+ int ntail = N % sN;
787
+ {%- else %}
788
+ constexpr int ntail = BLOCK_N % sN;
789
+ {%- endif %}
790
+ constexpr int mtail = BLOCK_M % sM;
791
+ int ktail = K % VLEN;
792
+
793
+ auto compute_trans = [&](int m, int n, int k) {
794
+ {%- if tail_n %}
795
+ int e_n = (n == bN - 1 && ntail != 0) ? (N - n * sN) : sN;
796
+ {%- else %}
797
+ int e_n = (n == bN - 1 && ntail != 0) ? (BLOCK_N - n * sN) : sN;
798
+ {%- endif %}
799
+ int e_m = (m == bM - 1 && mtail != 0) ? (BLOCK_M - m * sM) : sM;
800
+ int e_k = (k == _K - 1 && ktail != 0) ? (K - k * VLEN) : VLEN;
801
+ {{kernel.unroll_pragma(sub_block_n)}}
802
+ for (int i = 0; i < e_n; i++) {
803
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
804
+ auto b = VectorizedIn::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k);
805
+ std::tie(vb[2 * i], vb[2 * i + 1]) = at::vec::convert_to_float<{{input_t}}>(b);
806
+ {%- elif input2_dtype == torch.int8 %}
807
+ auto b32 = at::vec::convert_to_int32<int8_t>(B + (sN * n + i) * ldb + k * VLEN, e_k);
808
+ vb[i] = at::vec::convert<float>(b32);
809
+ {%- else %}
810
+ vb[i] = Vectorized::loadu(B + (sN * n + i) * ldb + k * VLEN, e_k);
811
+ {%- endif %}
812
+ }
813
+
814
+ {{kernel.unroll_pragma(sub_block_m)}}
815
+ for (int s = 0; s < e_m; s++) {
816
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
817
+ auto a = VectorizedIn::loadu(A + (sM * m + s) * lda + k * VLEN, e_k);
818
+ std::tie(va[0], va[1]) = at::vec::convert_to_float<{{input_t}}>(a);
819
+ {%- elif input2_dtype == torch.int8 %}
820
+ auto a32 = at::vec::convert_to_int32<int8_t>(A + (sM * m + s) * lda + k * VLEN, e_k);
821
+ va = at::vec::convert<float>(a32);
822
+ {%- else %}
823
+ va = Vectorized::loadu(A + (sM * m + s) * lda + k * VLEN, e_k);
824
+ {%- endif %}
825
+
826
+ {%- if alpha != 1 %}
827
+ va = va * Vectorized({{alpha}});
828
+ {%- endif %}
829
+ if (k == 0) {
830
+ {{kernel.unroll_pragma(sub_block_n)}}
831
+ for (int i = 0; i < e_n; i++) {
832
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
833
+ vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], Vectorized(0.0f));
834
+ vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]);
835
+ {%- else %}
836
+ vmid[sN * s + i] = at::vec::fmadd(va, vb[i], Vectorized(0.0f));
837
+ {%- endif %}
838
+ }
839
+ } else {
840
+ {{kernel.unroll_pragma(sub_block_n)}}
841
+ for (int i = 0; i < e_n; i++) {
842
+ {%- if input2_dtype in [torch.bfloat16, torch.float16] %}
843
+ vmid[sN * s + i] = at::vec::fmadd(va[0], vb[2 * i], vmid[sN * s + i]);
844
+ vmid[sN * s + i] = at::vec::fmadd(va[1], vb[2 * i + 1], vmid[sN * s + i]);
845
+ {%- else %}
846
+ vmid[sN * s + i] = at::vec::fmadd(va, vb[i], vmid[sN * s + i]);
847
+ {%- endif %}
848
+ }
849
+ }
850
+ }
851
+
852
+ // store to C
853
+ if (k == _K - 1) {
854
+ {{kernel.unroll_pragma(sub_block_m)}}
855
+ for (int s = 0; s < e_m; s++) {
856
+ {{kernel.unroll_pragma(sub_block_n)}}
857
+ for (int i = 0; i < e_n; i++) {
858
+ auto v = at::vec::vec_reduce_all([](Vectorized& x, Vectorized& y) { return x + y; }, vmid[sN * s + i]);
859
+ if constexpr (accum) {
860
+ auto c = *(C + (sM * m + s) * ldc + sN * n + i);
861
+ *(C + (sM * m + s) * ldc + sN * n + i) = c + v;
862
+ } else {
863
+ *(C + (sM * m + s) * ldc + sN * n + i) = v;
864
+ }
865
+ }
866
+ }
867
+ }
868
+ };
869
+
870
+ for (int n = 0; n < bN; ++n) {
871
+ for (int m = 0; m < bM; ++m) {
872
+ for (int k = 0; k < _K; ++k) {
873
+ compute_trans(m, n, k);
874
+ }
875
+ }
876
+ }
877
+ }
878
+ {%- endif %}
879
+ }
880
+ """
881
+
882
+ # set trans_b to generate gemm that supports transposed B matrix
883
+ # set tail_n to support the tail of N
884
+ # TODO add trans_b support for other micro gemms
885
+ # and move setting of trans_b to the init of CppMicroGemm
886
+ def __init__(
887
+ self,
888
+ name,
889
+ input_dtype,
890
+ input2_dtype,
891
+ output_dtype,
892
+ compute_dtype,
893
+ register_blocking,
894
+ alpha=1,
895
+ tail_n=False,
896
+ trans_b=False,
897
+ ) -> None:
898
+ super().__init__(
899
+ name,
900
+ input_dtype,
901
+ input2_dtype,
902
+ output_dtype,
903
+ compute_dtype,
904
+ register_blocking,
905
+ alpha,
906
+ )
907
+ self.tail_n = tail_n
908
+ # trans_b is only supported on platforms that
909
+ # support avx512 or avx2 since transpose_block is
910
+ # only implemented on these platforms
911
+ if trans_b:
912
+ vec_isa = pick_vec_isa()
913
+ assert issubclass(vec_isa.__class__, VecAVX512) or issubclass(
914
+ vec_isa.__class__, VecAVX2
915
+ )
916
+ self.trans_b = trans_b
917
+
918
+ def codegen_define(self, kernel: CppTemplateKernel) -> str:
919
+ options = {
920
+ "declare_kernel": self.get_kernel_declaration(),
921
+ "kernel": kernel,
922
+ "block_m": self.register_blocking.block_m,
923
+ "block_n": self.register_blocking.block_n,
924
+ "block_k": self.register_blocking.block_k,
925
+ "trans_b": False,
926
+ "tail_n": False,
927
+ "restrict_keyword": get_restrict_keyword(),
928
+ **self.get_common_options(),
929
+ }
930
+ if self.trans_b:
931
+ # TODO supports tuning of sub_block_m/sub_block_n
932
+ # to get better performance for specific shapes
933
+ sub_block_m = min(1, self.register_blocking.block_m)
934
+ sub_block_n = min(4, self.register_blocking.block_n)
935
+ # update options to generate kernel with trans_b and sub-block size
936
+ options.update(
937
+ {
938
+ "trans_b": self.trans_b,
939
+ "sub_block_m": sub_block_m,
940
+ "sub_block_n": sub_block_n,
941
+ }
942
+ )
943
+ result = KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
944
+ options
945
+ )
946
+ # update options to generate the kernel for the tail of N
947
+ if self.tail_n:
948
+ options.update(
949
+ {
950
+ "tail_n": self.tail_n,
951
+ }
952
+ )
953
+ result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
954
+ options
955
+ )
956
+ result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(
957
+ options
958
+ )
959
+ return result
960
+
961
+
962
+ def check_vnni_extra(config, m, n, k, alpha, num_threads, **kwargs):
963
+ assert config.input_dtype == torch.uint8 and config.input2_dtype == torch.int8
964
+ vnni_size = 4
965
+ return k % vnni_size == 0
966
+
967
+
968
+ @register_micro_gemm(
969
+ *generate_gemm_config(
970
+ VecAVX512VNNI,
971
+ # (block_m, block_n, block_k)
972
+ [(6, 64, 4)],
973
+ input_dtype=torch.uint8,
974
+ input2_dtype=torch.int8,
975
+ output_dtype=torch.int32,
976
+ compute_dtype=torch.int32,
977
+ extra_check=check_vnni_extra,
978
+ ),
979
+ )
980
+ class CppMicroGemmAVX512VNNI(CppMicroGemm):
981
+ """
982
+ This class generates the code for micro gemm using AVX512 VNNI instructions for compute.
983
+ It supports u8s8s32 GEMM only.
984
+ AVX512_VNNI ISA has been available since the 3rd gen of Intel Xeon.
985
+ """
986
+
987
+ TEMPLATE_ENTRY = r"""
988
+ {{declare_kernel}} {
989
+ {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
990
+ {{kernel.assert_function}}(K % {{vnni_size}} == 0, "K dimension must be multiple of {{vnni_size}}");
991
+ constexpr int64_t M_BLOCK = {{block_m}};
992
+ const int64_t M_TAIL = M % M_BLOCK;
993
+ const int64_t M_MAIN = M - M_TAIL;
994
+ for (int64_t m = 0; m < M_MAIN; m += M_BLOCK) {
995
+ for (int64_t n = 0; n < N; n += {{block_n}}) {
996
+ {{kernel_name}}_kernel<M_BLOCK, {{block_n}}, accum>(
997
+ A + m * lda,
998
+ B + n,
999
+ C + m * ldc + n,
1000
+ K,
1001
+ lda,
1002
+ ldb,
1003
+ ldc
1004
+ );
1005
+ }
1006
+ }
1007
+ if (M_TAIL > 0) {
1008
+ switch (M_TAIL) {
1009
+ {%- for m_tail in range(block_m - 1, 0, -1) %}
1010
+ case ({{m_tail}}):
1011
+ for (int64_t n = 0; n < N; n += {{block_n}}) {
1012
+ {{kernel_name}}_kernel<{{m_tail}}, {{block_n}}, accum>(
1013
+ A + M_MAIN * lda,
1014
+ B + n,
1015
+ C + M_MAIN * ldc + n,
1016
+ K,
1017
+ lda,
1018
+ ldb,
1019
+ ldc
1020
+ );
1021
+ }
1022
+ break;
1023
+ {%- endfor %}
1024
+ default:
1025
+ {{kernel.assert_function}}(false, "Unsupported M_TAIL: {}", M_TAIL);
1026
+ } // switch M_TAIL
1027
+ } // if M_TAIL
1028
+ }
1029
+ """
1030
+
1031
+ TEMPLATE_KERNEL = r"""
1032
+ template <int64_t M, int64_t N, bool accum>
1033
+ inline void {{kernel_name}}_kernel(
1034
+ const {{input_t}}* {{restrict_keyword}} A,
1035
+ const {{input2_t}}* {{restrict_keyword}} B,
1036
+ {{output_t}}* {{restrict_keyword}} C,
1037
+ int64_t K,
1038
+ int64_t lda,
1039
+ int64_t ldb,
1040
+ int64_t ldc
1041
+ ) {
1042
+ constexpr const int COLS = N / {{vec_len}};
1043
+ __m512i va;
1044
+ __m512i vb[COLS];
1045
+ __m512i vc[M * COLS];
1046
+
1047
+ c10::ForcedUnroll<M * COLS>{}([&](auto i) { vc[i] = _mm512_setzero_epi32(); });
1048
+
1049
+ auto compute = [&](auto i, int k) {
1050
+ constexpr const int row = i / COLS;
1051
+ constexpr const int col = i % COLS;
1052
+
1053
+ if constexpr (col == 0) {
1054
+ va = _mm512_set1_epi32(*(int32_t*)(A + row * lda + k));
1055
+ }
1056
+
1057
+ if constexpr (row == 0) {
1058
+ // B block in VNNI layout: [K / {{vnni_size}}, N, {{vnni_size}}]
1059
+ int64_t offset = k * ldb + col * {{vec_len}} * {{vnni_size}};
1060
+ vb[col] = _mm512_loadu_si512((__m512i const*)(B + offset));
1061
+ }
1062
+ vc[i] = _mm512_dpbusd_epi32(vc[i], va, vb[col]);
1063
+ };
1064
+
1065
+ // Accumulate along k
1066
+ constexpr const int k_unroll = 2;
1067
+ int k = 0;
1068
+ int k_limit = K / {{vnni_size}} / k_unroll;
1069
+ for (; k < k_limit; k++) {
1070
+ c10::ForcedUnroll<k_unroll>{}(
1071
+ [&](auto i) {
1072
+ c10::ForcedUnroll<M * COLS>{}(compute, {{vnni_size}} * (k * k_unroll + i));
1073
+ }
1074
+ );
1075
+ }
1076
+ k *= {{vnni_size}} * k_unroll;
1077
+ for (; k < K; k += {{vnni_size}}) {
1078
+ c10::ForcedUnroll<M * COLS>{}(compute, k);
1079
+ }
1080
+
1081
+ // Store to C
1082
+ auto store_c = [&](auto i) {
1083
+ constexpr const int row = i / COLS;
1084
+ constexpr const int col = i % COLS;
1085
+ if constexpr (accum) {
1086
+ __m512i vc_old = _mm512_loadu_si512((__m512i const*)(C + row * ldc + col * {{vec_len}}));
1087
+ vc[i] = _mm512_add_epi32(vc[i], vc_old);
1088
+ }
1089
+ _mm512_storeu_si512((__m512i*)(C + row * ldc + col * {{vec_len}}), vc[i]);
1090
+ };
1091
+ c10::ForcedUnroll<M * COLS>{}(store_c);
1092
+ }
1093
+ """
1094
+
1095
+ def __init__(
1096
+ self,
1097
+ name,
1098
+ input_dtype,
1099
+ input2_dtype,
1100
+ output_dtype,
1101
+ compute_dtype,
1102
+ register_blocking,
1103
+ alpha=1,
1104
+ ) -> None:
1105
+ super().__init__(
1106
+ name,
1107
+ input_dtype,
1108
+ input2_dtype,
1109
+ output_dtype,
1110
+ compute_dtype,
1111
+ register_blocking,
1112
+ alpha,
1113
+ )
1114
+ assert input_dtype == torch.uint8 and input2_dtype == torch.int8, (
1115
+ f"Only u8s8s32 GEMM is supported by AVX512VNNI microkernel, got A:{input_dtype}, B:{input2_dtype}, C:{output_dtype}."
1116
+ )
1117
+
1118
+ def codegen_define(self, kernel: CppTemplateKernel) -> str:
1119
+ options = {
1120
+ "declare_kernel": self.get_kernel_declaration(),
1121
+ "kernel": kernel,
1122
+ "block_m": self.register_blocking.block_m,
1123
+ "block_n": self.register_blocking.block_n,
1124
+ "block_k": self.register_blocking.block_k,
1125
+ "restrict_keyword": get_restrict_keyword(),
1126
+ "vec_len": 16, # = 512 / 32 for C
1127
+ **self.get_common_options(),
1128
+ }
1129
+ return KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
1130
+ options
1131
+ ) + KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(options)
1132
+
1133
+ def get_b_layout(self):
1134
+ return LayoutType.VNNI4
1135
+
1136
+
1137
+ # extra check for CppMicroGemmAMX
1138
+ def check_amx_extra(config, m, n, k, alpha, num_threads, **kwargs):
1139
+ vnni_size = 4 if config.input_dtype in [torch.uint8, torch.int8] else 2
1140
+ return k % vnni_size == 0 and alpha == 1
1141
+
1142
+
1143
+ def check_int8_bf16_amx_extra(config, m, n, k, alpha, num_threads, **kwargs):
1144
+ # We need avx512_bf16 to dequant int8 to bf16
1145
+ vec_isa = kwargs.get("vec_isa")
1146
+ assert vec_isa is not None
1147
+ return vec_isa.is_avx512_bf16_supported() and check_amx_extra(
1148
+ config, m, n, k, alpha, num_threads, **kwargs
1149
+ )
1150
+
1151
+
1152
+ # amx_fp16 need to be checked separately since it is not always supported when amx is supported
1153
+ def check_amx_fp16_extra(config, m, n, k, alpha, num_threads, **kwargs):
1154
+ assert config.input_dtype == torch.float16 and config.output_dtype == torch.float
1155
+ vec_isa = kwargs.get("vec_isa")
1156
+ assert vec_isa is not None
1157
+ vnni_size = 2
1158
+ return vec_isa.is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1
1159
+
1160
+
1161
+ @register_micro_gemm(
1162
+ *generate_gemm_config(
1163
+ VecAMX,
1164
+ [(32, 32, 64), (48, 16, 64)],
1165
+ input_dtype=torch.int8,
1166
+ input2_dtype=torch.int8,
1167
+ output_dtype=torch.int32,
1168
+ compute_dtype=torch.int32,
1169
+ extra_check=check_amx_extra,
1170
+ ),
1171
+ *generate_gemm_config(
1172
+ VecAMX,
1173
+ [(32, 32, 32), (48, 16, 32)],
1174
+ input_dtype=torch.bfloat16,
1175
+ input2_dtype=torch.int8,
1176
+ output_dtype=torch.float,
1177
+ compute_dtype=torch.float,
1178
+ extra_check=check_int8_bf16_amx_extra,
1179
+ ),
1180
+ *generate_gemm_config(
1181
+ VecAMX,
1182
+ [(32, 16, 32), (32, 32, 32), (48, 16, 32), (16, 48, 32)],
1183
+ input_dtype=torch.bfloat16,
1184
+ output_dtype=torch.float,
1185
+ extra_check=check_amx_extra,
1186
+ ),
1187
+ *generate_gemm_config(
1188
+ VecAMX,
1189
+ [(32, 32, 32), (48, 16, 32), (16, 48, 32)],
1190
+ input_dtype=torch.float16,
1191
+ output_dtype=torch.float,
1192
+ extra_check=check_amx_fp16_extra,
1193
+ ),
1194
+ *generate_gemm_config(
1195
+ VecAMX,
1196
+ [(32, 32, 64), (48, 16, 64)],
1197
+ input_dtype=torch.uint8,
1198
+ input2_dtype=torch.int8,
1199
+ output_dtype=torch.int32,
1200
+ compute_dtype=torch.int32,
1201
+ extra_check=check_amx_extra,
1202
+ ),
1203
+ )
1204
+ class CppMicroGemmAMX(CppMicroGemm):
1205
+ """
1206
+ This class generates the code for micro gemm using Advanced Matrix extension (AMX)
1207
+ instructions available in 4th generation Intel Xeon for compute.
1208
+ It supports input types of torch.bfloat16 with fp32 output.
1209
+ """
1210
+
1211
+ TEMPLATE_ENTRY = r"""
1212
+ {{declare_kernel}} {
1213
+ {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
1214
+ {{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2");
1215
+ {%- if pack_vnni_B_locally %}
1216
+ {{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K", block_n)}}
1217
+ {%- endif %}
1218
+ {%- if use_cached_dequantized_B %}
1219
+ // Create a stack-allocated buffer for tiles of B.
1220
+ // Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements.
1221
+ // we cache K * {{block_n}} elements of dequantized B
1222
+ {{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}}
1223
+ const auto buf_size = K * {{block_n}};
1224
+ auto load_dequantized_B = [&](int base_idx) {
1225
+ // Load a tile of B & cache it in L1D.
1226
+ {{input2_t}}* base_addr = const_cast<{{input2_t}}*>(B) + base_idx;
1227
+ for (int idx_dq = 0, idx_q = 0; idx_dq < buf_size; idx_q += ldb, idx_dq += {{block_n}}) {
1228
+ {%- for vec_idx in range(0, block_n, 32) %}
1229
+ _mm_prefetch(base_addr + idx_q + 64 * ldb, _MM_HINT_T0);
1230
+ {%- if (block_n - vec_idx) >= 32 %}
1231
+ // 1) Load 32 x int8
1232
+ __m256i v8 = _mm256_loadu_si256((const __m256i*)(base_addr + idx_q + {{vec_idx}}));
1233
+ // 2) Extract two halves
1234
+ __m128i v8_lo = _mm256_extracti128_si256(v8, 0);
1235
+ __m128i v8_hi = _mm256_extracti128_si256(v8, 1);
1236
+ // 3) Widen each half to i32
1237
+ __m512i v32_lo = _mm512_cvtepi8_epi32(v8_lo);
1238
+ __m512i v32_hi = _mm512_cvtepi8_epi32(v8_hi);
1239
+ // 4) Convert to f32
1240
+ __m512 f_lo = _mm512_cvtepi32_ps(v32_lo);
1241
+ __m512 f_hi = _mm512_cvtepi32_ps(v32_hi);
1242
+ // 5) f32 -> bf16 (round-to-nearest-even) and pack 32 lanes to 512b
1243
+ // Packs the second operand (f_lo) into the lower 16 bf16 lanes and the first (f_hi) into the upper 16.
1244
+ __m512i bf = (__m512i)_mm512_cvtne2ps_pbh(f_hi, f_lo);
1245
+ // 6) Store 32 x bf16 (512 bits)
1246
+ _mm512_storeu_si512((__m512i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf);
1247
+ {%- elif (block_n - vec_idx) >= 16 %}
1248
+ // 1) Load 16 x int8 (128 bits)
1249
+ __m128i v8 = _mm_loadu_si128((const __m128i*)(base_addr + idx_q + {{vec_idx}}));
1250
+ // 2) Widen: 16 x i8 -> 16 x i32
1251
+ __m512i v32 = _mm512_cvtepi8_epi32(v8);
1252
+ // 3) Convert to f32
1253
+ __m512 f32 = _mm512_cvtepi32_ps(v32);
1254
+ // 4) Convert f32 -> bf16 (round-to-nearest-even)
1255
+ __m256i bf16 = (__m256i)_mm512_cvtneps_pbh(f32);
1256
+ // 5) Store 16 x bf16 (256 bits)
1257
+ _mm256_storeu_si256((__m256i*)(dequantized_B_buf + idx_dq + {{vec_idx}}), bf16);
1258
+ {%- else %}
1259
+ auto b_int8_tail = at::vec::Vectorized<int8_t>::loadu(
1260
+ base_addr + idx_q + {{block_n - (block_n % 32)}},
1261
+ static_cast<int64_t>({{block_n % 32}})
1262
+ );
1263
+ auto b_bf16_tail = at::vec::convert<{{input_t}}>(b_int8_tail);
1264
+ b_bf16_tail.store(
1265
+ dequantized_B_buf + idx_dq + {{block_n - (block_n % 32)}},
1266
+ static_cast<int64_t>({{block_n % 32}})
1267
+ );
1268
+ {%- endif %}
1269
+ {%- endfor %}
1270
+ }
1271
+ };
1272
+ {%- endif %}
1273
+ // The ldb would not be block_n if N != block_n
1274
+ {%- if use_cached_dequantized_B or pack_vnni_B_locally %}
1275
+ const int64_t updated_ldb = {{block_n}};
1276
+ {%- else %}
1277
+ const int64_t updated_ldb = ldb;
1278
+ {%- endif %}
1279
+ // TODO(jgong5): loop unroll for M and N
1280
+ for (int64_t n = 0; n < N; n += {{block_n}}) {
1281
+ {%- if pack_vnni_B_locally %}
1282
+ // Pack non-constant weights into VNNI interleaved format in packed_B_buf
1283
+ at::vec::pack_vnni2(B + n, packed_B_buf, ldb, K, {{block_n}});
1284
+ {%- elif use_cached_dequantized_B %}
1285
+ // Dequantize K * block_n int8 B elements into BF16
1286
+ load_dequantized_B(n);
1287
+ {%- endif %}
1288
+ for (int64_t m = 0; m < M; m += {{block_m}}) {
1289
+ int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
1290
+ int64_t m_tail = m;
1291
+ {%- for num_rows in range(block_m, 0, -16) %}
1292
+ {%- if num_rows != block_m %}
1293
+ else
1294
+ {%- endif %}
1295
+ if (block_m >= {{num_rows}}) {
1296
+ {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}<accum>(
1297
+ amx_state,
1298
+ A + m * lda,
1299
+ {%- if use_cached_dequantized_B %}
1300
+ dequantized_B_buf,
1301
+ {%- elif pack_vnni_B_locally %}
1302
+ packed_B_buf,
1303
+ {%- else %}
1304
+ B + n,
1305
+ {%- endif %}
1306
+ C + m * ldc + n,
1307
+ K,
1308
+ lda,
1309
+ updated_ldb,
1310
+ ldc,
1311
+ 16
1312
+ );
1313
+ block_m -= {{num_rows}};
1314
+ m_tail += {{num_rows}};
1315
+ }
1316
+ {%- endfor %}
1317
+ if (block_m > 0) {
1318
+ {{kernel_name}}_amx_kernel_16_{{num_columns}}<accum>(
1319
+ amx_state,
1320
+ A + m_tail * lda,
1321
+ {%- if use_cached_dequantized_B %}
1322
+ dequantized_B_buf,
1323
+ {%- elif pack_vnni_B_locally %}
1324
+ packed_B_buf,
1325
+ {%- else %}
1326
+ B + n,
1327
+ {%- endif %}
1328
+ C + m_tail * ldc + n,
1329
+ K,
1330
+ lda,
1331
+ updated_ldb,
1332
+ ldc,
1333
+ block_m
1334
+ );
1335
+ }
1336
+ }
1337
+ }
1338
+ }
1339
+ """
1340
+
1341
+ TEMPLATE_KERNEL = r"""
1342
+
1343
+ template <bool accum, bool prefetch=false>
1344
+ inline void {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}(
1345
+ AMXState& amx_state,
1346
+ const {{input_t}}* {{restrict_keyword}} A,
1347
+ {%- if use_cached_dequantized_B %}
1348
+ const {{input_t}}* {{restrict_keyword}} B,
1349
+ {%- else %}
1350
+ const {{input2_t}}* {{restrict_keyword}} B,
1351
+ {%- endif %}
1352
+ {{output_t}}* {{restrict_keyword}} C,
1353
+ int64_t K,
1354
+ int64_t lda,
1355
+ int64_t ldb,
1356
+ int64_t ldc,
1357
+ uint8_t tilecfg_rows
1358
+ ) {
1359
+ // TODO(jgong5): add prefetch hint for A, B, C
1360
+ auto loadconfig = [](const amx_tilecfg& cfg) {
1361
+ _tile_loadconfig(&cfg);
1362
+ };
1363
+ const auto last_k_offset = K / {{block_k}} * {{block_k}};
1364
+ const auto tail_k_size = K - last_k_offset;
1365
+ if C10_LIKELY (last_k_offset > 0) {
1366
+ amx_state.configure(tilecfg_rows, 64, {{num_rows}} / 16, {{num_columns}}, loadconfig);
1367
+ } else {
1368
+ amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig);
1369
+ }
1370
+ auto load_c = [&]() {
1371
+ {%- for tile_row in range(num_rows // 16) %}
1372
+ {%- for tile_col in range(num_columns) %}
1373
+ {%- set tile_idx = tile_row * num_columns + tile_col %}
1374
+ _tile_loadd({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}}));
1375
+ {%- endfor %}
1376
+ {%- endfor %}
1377
+ };
1378
+ auto zero_c = [&]() {
1379
+ {%- for tile_row in range(num_rows // 16) %}
1380
+ {%- for tile_col in range(num_columns) %}
1381
+ {%- set tile_idx = tile_row * num_columns + tile_col %}
1382
+ _tile_zero({{tile_idx}});
1383
+ {%- endfor %}
1384
+ {%- endfor %}
1385
+ };
1386
+
1387
+ if constexpr (accum) {
1388
+ load_c();
1389
+ } else {
1390
+ zero_c();
1391
+ }
1392
+
1393
+ auto compute = [&](int k) {
1394
+ {%- set tile_offset_a = num_rows // 16 * num_columns %}
1395
+ {%- set tile_offset_b = tile_offset_a + num_rows // 16 %}
1396
+ {%- for tile_row in range(num_rows // 16) %}
1397
+ {%- for tile_col in range(num_columns) %}
1398
+ {%- set tile_idx_a = tile_offset_a + tile_row %}
1399
+ {%- set tile_idx_b = tile_offset_b + tile_col %}
1400
+ {%- set tile_idx_c = tile_row * num_columns + tile_col %}
1401
+ {%- if tile_col == 0 %}
1402
+ _tile_stream_loadd({{tile_idx_a}}, A + {{tile_row * 16}} * lda + k, lda * sizeof({{input_t}}));
1403
+ {%- endif %}
1404
+ {%- if tile_row == 0 %}
1405
+ _tile_loadd({{tile_idx_b}}, B + k * ldb + {{tile_col * 16 * vnni_size}}, ldb * {{vnni_size}} * sizeof({{input_t}}));
1406
+ {%- endif %}
1407
+ {%- if int8_gemm %}
1408
+ {%- if input_dtype == torch.int8 %}
1409
+ _tile_dpbssd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
1410
+ {%- else %}
1411
+ _tile_dpbusd({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
1412
+ {%- endif %}
1413
+ {%- else %}
1414
+ {%- if input_dtype == torch.float16 %}
1415
+ _tile_dpfp16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
1416
+ {%- else %}
1417
+ _tile_dpbf16ps({{tile_idx_c}}, {{tile_idx_a}}, {{tile_idx_b}});
1418
+ {%- endif %}
1419
+ {%- endif %}
1420
+ {%- endfor %}
1421
+ {%- endfor %}
1422
+ };
1423
+
1424
+ {{kernel.unroll_pragma(4)}}
1425
+ for (int k = 0; k < last_k_offset; k += {{block_k}}) {
1426
+ compute(k);
1427
+ }
1428
+
1429
+ auto store_c = [&]() {
1430
+ // store to C
1431
+ {%- for tile_row in range(num_rows // 16) %}
1432
+ {%- for tile_col in range(num_columns) %}
1433
+ {%- set tile_idx = tile_row * num_columns + tile_col %}
1434
+ _tile_stored({{tile_idx}}, C + {{tile_row * 16}} * ldc + {{tile_col * 16}}, ldc * sizeof({{output_t}}));
1435
+ {%- endfor %}
1436
+ {%- endfor %}
1437
+ };
1438
+
1439
+ // TODO(jgong5): move tail k computation to separate loopnest to save tile configuration overhead
1440
+ if C10_UNLIKELY (tail_k_size > 0) {
1441
+ if C10_LIKELY (last_k_offset > 0) {
1442
+ store_c();
1443
+ amx_state.configure(tilecfg_rows, tail_k_size * sizeof({{input_t}}), {{num_rows}} / 16, {{num_columns}}, loadconfig);
1444
+ load_c();
1445
+ }
1446
+ compute(last_k_offset);
1447
+ }
1448
+
1449
+ store_c();
1450
+ }
1451
+ """
1452
+
1453
+ def codegen_define(self, kernel: CppTemplateKernel) -> str:
1454
+ block_m, block_n, block_k = self.register_blocking
1455
+ assert block_m % 16 == 0, "Only support block_m % 16 == 0 for AMX"
1456
+ assert block_n % 16 == 0, "Only support block_n % 16 == 0 for AMX"
1457
+ if self.input_dtype in [torch.uint8, torch.int8]:
1458
+ assert block_k == 64, "Only support block_k = 64 for AMX INT8"
1459
+ else:
1460
+ assert block_k == 32, "Only support block_k = 32 for AMX Bfloat16/Float16"
1461
+ num_columns = block_n // 16
1462
+ options = {
1463
+ "declare_kernel": self.get_kernel_declaration(),
1464
+ "use_cached_dequantized_B": (
1465
+ self.input_dtype == torch.bfloat16
1466
+ and self.input2_dtype in [torch.int8, torch.uint8]
1467
+ ),
1468
+ "kernel": kernel,
1469
+ "block_m": block_m,
1470
+ "block_n": block_n,
1471
+ "block_k": block_k,
1472
+ "num_columns": num_columns,
1473
+ "restrict_keyword": get_restrict_keyword(),
1474
+ **self.get_common_options(),
1475
+ }
1476
+ result = ""
1477
+ for num_rows in range(block_m, 0, -16):
1478
+ amx_kernel_options = {**options, "num_rows": num_rows}
1479
+ result += KernelTemplate._template_from_string(self.TEMPLATE_KERNEL).render(
1480
+ amx_kernel_options
1481
+ )
1482
+ result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(
1483
+ options
1484
+ )
1485
+ return result
1486
+
1487
+ def codegen_init(
1488
+ self,
1489
+ kernel: CppTemplateKernel,
1490
+ ) -> str:
1491
+ return "AMXState amx_state;"
1492
+
1493
+ def codegen_finalize(
1494
+ self,
1495
+ kernel: CppTemplateKernel,
1496
+ ) -> str:
1497
+ return "amx_state.release([]() { _tile_release(); });"
1498
+
1499
+ def get_kernel_extra_args_declare(self) -> str:
1500
+ return "AMXState& amx_state,"
1501
+
1502
+ def get_kernel_extra_args(self, **kwargs) -> list[str]:
1503
+ return ["amx_state,"]
1504
+
1505
+ def get_b_layout(self):
1506
+ if self.input_dtype in [torch.uint8, torch.int8]:
1507
+ return LayoutType.VNNI4
1508
+ else:
1509
+ return LayoutType.VNNI2
1510
+
1511
+
1512
+ # extra check for CppMicroBrgemm
1513
+ def check_brgemm_extra(config, m, n, k, alpha, num_threads, **kwargs):
1514
+ assert config.input_dtype == torch.half and config.output_dtype == torch.float
1515
+ vnni_size = 2
1516
+ # use brgemm for Half when amx_fp16 is supported
1517
+ return torch.cpu._is_amx_fp16_supported() and k % vnni_size == 0 and alpha == 1
1518
+
1519
+
1520
+ @register_micro_gemm(
1521
+ *generate_gemm_config(
1522
+ VecAMX,
1523
+ [(32, 32, 32), (48, 16, 32), (16, 48, 32)],
1524
+ input_dtype=torch.half,
1525
+ output_dtype=torch.float,
1526
+ extra_check=check_brgemm_extra,
1527
+ ),
1528
+ )
1529
+ class CppMicroBrgemm(CppMicroGemm):
1530
+ """
1531
+ This class generates the code for micro gemm using oneDNN brgemm.
1532
+ It supports input types of torch.half.
1533
+ """
1534
+
1535
+ TEMPLATE_ENTRY = r"""
1536
+ #include <ATen/native/CPUBlas.h>
1537
+ {{declare_kernel}} {
1538
+ {%- if pack_vnni_B_locally %}
1539
+ {{template.codegen_allocate_weight_buffer("packed_B_buf", input2_t, "K * N")}}
1540
+ at::vec::pack_vnni2(B, packed_B_buf, ldb, K, N);
1541
+ {%- endif %}
1542
+ at::native::cpublas::brgemm(
1543
+ M, N, K,
1544
+ {%- if pack_vnni_B_locally %}
1545
+ lda, N, ldc,
1546
+ {%- else %}
1547
+ lda, ldb, ldc,
1548
+ {%- endif %}
1549
+ accum,
1550
+ A,
1551
+ {%- if pack_vnni_B_locally %}
1552
+ packed_B_buf,
1553
+ {%- else %}
1554
+ B,
1555
+ {%- endif %}
1556
+ C);
1557
+ }
1558
+ """
1559
+
1560
+ def codegen_define(self, kernel: CppTemplateKernel) -> str:
1561
+ options = {
1562
+ "declare_kernel": self.get_kernel_declaration(),
1563
+ "kernel": kernel,
1564
+ "block_m": self.register_blocking.block_m,
1565
+ "block_n": self.register_blocking.block_n,
1566
+ "block_k": self.register_blocking.block_k,
1567
+ "restrict_keyword": get_restrict_keyword(),
1568
+ **self.get_common_options(),
1569
+ }
1570
+ result = ""
1571
+ result += KernelTemplate._template_from_string(self.TEMPLATE_ENTRY).render(
1572
+ options
1573
+ )
1574
+ return result
1575
+
1576
+ def codegen_finalize(
1577
+ self,
1578
+ kernel: CppTemplateKernel,
1579
+ ) -> str:
1580
+ return "at::native::cpublas::brgemm_release();"
1581
+
1582
+ def get_b_layout(self):
1583
+ assert self.input_dtype == torch.half and torch.cpu._is_amx_fp16_supported()
1584
+ return LayoutType.VNNI2
1585
+
1586
+
1587
+ def check_woq_int4_extra(config, m, n, k, alpha, num_threads, **kwargs):
1588
+ if alpha != 1:
1589
+ return False
1590
+ q_group_size = kwargs.get("q_group_size")
1591
+ assert q_group_size is not None
1592
+ if (
1593
+ q_group_size not in [32, 64, 128]
1594
+ or k % q_group_size != 0
1595
+ or config.register_blocking.block_k > q_group_size
1596
+ ):
1597
+ return False
1598
+ return k % config.register_blocking.block_k == 0 and n % 64 == 0
1599
+
1600
+
1601
+ @register_micro_gemm(
1602
+ # TODO: support float/half input
1603
+ *generate_gemm_config(
1604
+ VecAVX512,
1605
+ [(4, 64, 32), (4, 64, 64), (4, 64, 128)],
1606
+ input_dtype=torch.bfloat16,
1607
+ input2_dtype=torch.uint8,
1608
+ output_dtype=torch.float,
1609
+ compute_dtype=torch.float,
1610
+ extra_check=check_woq_int4_extra,
1611
+ ),
1612
+ )
1613
+ class CppMicroGemmWoQInt4Avx512(CppMicroGemmFP32Vec):
1614
+ """
1615
+ This class generates the code for WoQ int4 micro gemm using AVX512 intrinsics.
1616
+ It is based on the corresponding ATen kernel.
1617
+ Shape of packed weight = [N // 64, K, 32], viewed as [N, K // 2]
1618
+ Shape of packed ScalesAndZeros = [K // group_size, N, 2]
1619
+ """
1620
+
1621
+ TEMPLATE_ENTRY = r"""
1622
+ {{declare_kernel}} {
1623
+ {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
1624
+ {{kernel.assert_function}}(K % {{block_k}} == 0, "K dimension must be multiple of {{block_k}}");
1625
+ auto group_size = q_group_size;
1626
+ for (int64_t m = 0; m < M; m += {{block_m}}) {
1627
+ int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
1628
+ for (int64_t n = 0; n < N; n += {{block_n}}) {
1629
+ if (block_m == {{block_m}}) {
1630
+ {{kernel_name}}_kernel<{{block_m}}, {{block_n}}, accum>(
1631
+ A + m * lda,
1632
+ reinterpret_cast<const uint8_t*>(B) + n * ldb,
1633
+ C + m * ldc + n,
1634
+ K,
1635
+ lda,
1636
+ /* ldb */ {{block_n}} / 2,
1637
+ ldc,
1638
+ group_size,
1639
+ ScaleAndZeros + n * 2,
1640
+ lds,
1641
+ k_start
1642
+ );
1643
+ } else {
1644
+ switch (block_m) {
1645
+ {%- for b in range(block_m - 1, 0, -1) %}
1646
+ case {{b}}:
1647
+ {{kernel_name}}_kernel<{{b}}, {{block_n}}, accum>(
1648
+ A + m * lda,
1649
+ reinterpret_cast<const uint8_t*>(B) + n * ldb,
1650
+ C + m * ldc + n,
1651
+ K,
1652
+ lda,
1653
+ /* ldb */ {{block_n}} / 2,
1654
+ ldc,
1655
+ group_size,
1656
+ ScaleAndZeros + n * 2,
1657
+ lds,
1658
+ k_start
1659
+ );
1660
+ break;
1661
+ {%- endfor %}
1662
+ default:
1663
+ {{kernel.assert_function}}(false, "Unsupported block_m: ", block_m);
1664
+ }
1665
+ }
1666
+ }
1667
+ }
1668
+ }
1669
+ """
1670
+
1671
+ TEMPLATE_KERNEL = r"""
1672
+ inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) {
1673
+ return (k_start + index) % group_size == 0;
1674
+ }
1675
+
1676
+ inline __m128i {{kernel_name}}_convert_int4_to_int8(const uint8_t* data) {
1677
+ __m128i tmp = _mm_loadu_si64((const __m128i*)data);
1678
+ __m128i bytes = _mm_cvtepu8_epi16(tmp);
1679
+ const __m128i lowMask = _mm_set1_epi8(0xF);
1680
+ __m128i high = _mm_andnot_si128(lowMask, bytes);
1681
+ __m128i low = _mm_and_si128(lowMask, bytes);
1682
+ high = _mm_slli_epi16(high, 4);
1683
+ bytes = _mm_or_si128(low, high);
1684
+ return bytes;
1685
+ }
1686
+
1687
+ template <int64_t BLOCK_M, int64_t BLOCK_N, bool accum>
1688
+ inline void {{kernel_name}}_kernel(
1689
+ const {{input_t}}* {{restrict_keyword}} A,
1690
+ const uint8_t* {{restrict_keyword}} B,
1691
+ {{output_t}}* {{restrict_keyword}} C,
1692
+ int64_t K,
1693
+ int64_t lda,
1694
+ int64_t ldb,
1695
+ int64_t ldc,
1696
+ int64_t q_group_size,
1697
+ const at::BFloat16* {{restrict_keyword}} ScaleAndZeros,
1698
+ int64_t lds, // leading dimension of ScaleAndZeros
1699
+ int64_t k_start) {
1700
+ constexpr int BLOCK_K = {{block_k}};
1701
+ constexpr int ROWS = BLOCK_M;
1702
+ constexpr int COLS = BLOCK_N / 16;
1703
+
1704
+ const int PREFETCH_SIZE_K = 16 * 4;
1705
+ const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K;
1706
+
1707
+ // number of blocks on K
1708
+ const int KB = K / BLOCK_K;
1709
+
1710
+ __m512 va;
1711
+ __m512 vb[COLS];
1712
+ __m512 vc[ROWS * COLS];
1713
+ __m512 scale[COLS];
1714
+ __m512 zero[COLS];
1715
+
1716
+ // Lookup table to de-quantize int4 values to bf16.
1717
+ // Values are dequantized as truly int4 [-8, 7] range;
1718
+ //
1719
+ // dequant = (bf16(int4_value) * bf16_scale) + bf16_zero
1720
+ //
1721
+ static const __m512 lut = _mm512_set_ps(
1722
+ 7.0f, 6.0f, 5.0f, 4.0f,
1723
+ 3.0f, 2.0f, 1.0f, 0.0f,
1724
+ -1.0f, -2.0f, -3.0f, -4.0f,
1725
+ -5.0f, -6.0f, -7.0f, -8.0f);
1726
+
1727
+ // index for transpose
1728
+ static const __m512i idx1 = _mm512_set_epi32(
1729
+ 30, 28, 26, 24, 22, 20, 18, 16,
1730
+ 14, 12, 10, 8, 6, 4, 2, 0);
1731
+ static const __m512i idx2 = _mm512_set_epi32(
1732
+ 31, 29, 27, 25, 23, 21, 19, 17,
1733
+ 15, 13, 11, 9, 7, 5, 3, 1);
1734
+
1735
+ // load scale and zero point
1736
+ auto load_scale_and_zeros = [&](int i, int _kb) {
1737
+ // load 2x bfloat16 vector
1738
+ __m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i));
1739
+ _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0);
1740
+
1741
+ // convert to 2x f32 vector
1742
+ __m512 a, b;
1743
+ at::vec::cvtbf16_fp32(t, a, b);
1744
+
1745
+ // transpose scale_and_zero from {16, 2} to {2, 16}
1746
+ // inputs:
1747
+ // a: {s0, z0, s1, z1, ..., s7, z7}
1748
+ // b: {s8, z8, s9, z9, ..., s15, z15}
1749
+ // output:
1750
+ // scale: {s0, s1, s2, ..., s15}
1751
+ // zero: {z0, z1, z2, ..., z15}
1752
+ scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b);
1753
+ zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b);
1754
+ };
1755
+
1756
+ auto loadc = [&](auto i) {
1757
+ if constexpr (accum) {
1758
+ constexpr int row = i / COLS;
1759
+ constexpr int col = i % COLS;
1760
+ vc[i] = _mm512_loadu_ps(C + row * ldc + col * 16);
1761
+ } else {
1762
+ vc[i] = _mm512_setzero_ps();
1763
+ }
1764
+ };
1765
+ c10::ForcedUnroll<ROWS * COLS>{}(loadc);
1766
+
1767
+ auto compute = [&, COLS](auto i, int k) {
1768
+ constexpr int row = i / COLS;
1769
+ constexpr int col = i % COLS;
1770
+
1771
+ if constexpr (col == 0) {
1772
+ float aa = static_cast<float>(A[row * lda + k]);
1773
+ _mm_prefetch(A + row * lda + k + PREFETCH_SIZE_K, _MM_HINT_T0);
1774
+ va = _mm512_set1_ps(aa);
1775
+ }
1776
+
1777
+ if constexpr (row == 0) {
1778
+ if constexpr (COLS == 4) {
1779
+ // when BLOCK_N = 64, handle each row at a time
1780
+ // to reduce de-quantize overhead.
1781
+ if constexpr (col == 0) {
1782
+ __m256i b4 = _mm256_loadu_si256((__m256i*)(B + k * ldb));
1783
+ _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb, _MM_HINT_T0);
1784
+
1785
+ __m512i b32 = _mm512_cvtepu8_epi32(_mm256_castsi256_si128(b4));
1786
+ vb[0] = _mm512_permutexvar_ps(b32, lut);
1787
+ vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]);
1788
+ vb[2] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut);
1789
+ vb[2] = _mm512_fmadd_ps(vb[2], scale[2], zero[2]);
1790
+
1791
+ b32 = _mm512_cvtepu8_epi32(_mm256_extracti128_si256(b4, 1));
1792
+ vb[1] = _mm512_permutexvar_ps(b32, lut);
1793
+ vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]);
1794
+ vb[3] = _mm512_permutexvar_ps(_mm512_srli_epi32(b32, 4), lut);
1795
+ vb[3] = _mm512_fmadd_ps(vb[3], scale[3], zero[3]);
1796
+ }
1797
+ } else {
1798
+ __m128i b8 = {{kernel_name}}_convert_int4_to_int8(B + k * ldb + col * 8);
1799
+ __m512i b32 = _mm512_cvtepu8_epi32(b8);
1800
+ vb[col] = _mm512_permutexvar_ps(b32, lut);
1801
+ vb[col] = _mm512_fmadd_ps(vb[col], scale[col], zero[col]);
1802
+ }
1803
+ }
1804
+
1805
+ constexpr int idx = row * COLS + col;
1806
+ vc[idx] = _mm512_fmadd_ps(va, vb[col], vc[idx]);
1807
+ };
1808
+
1809
+ for (int k = 0, kb = 0; k < K; ++k) {
1810
+ if ({{kernel_name}}_is_block_start(k, k_start, q_group_size)) {
1811
+ c10::ForcedUnroll<COLS>{}(load_scale_and_zeros, kb++);
1812
+ }
1813
+ c10::ForcedUnroll<ROWS * COLS>{}(compute, k);
1814
+ }
1815
+
1816
+ //store to C
1817
+ auto storec = [&, COLS](auto i) {
1818
+ constexpr int row = i / COLS;
1819
+ constexpr int col = i % COLS;
1820
+ _mm512_storeu_ps(C + row * ldc + col * 16, vc[i]);
1821
+ };
1822
+ c10::ForcedUnroll<ROWS * COLS>{}(storec);
1823
+ }
1824
+ """
1825
+
1826
+ def get_kernel_extra_args_declare(self) -> str:
1827
+ return (
1828
+ "const int64_t q_group_size,\n"
1829
+ " const at::BFloat16* __restrict__ ScaleAndZeros,\n"
1830
+ " const int64_t lds,\n"
1831
+ " int64_t k_start,"
1832
+ )
1833
+
1834
+ def get_kernel_extra_args(self, **kwargs) -> list[str]:
1835
+ assert "kernel" in kwargs
1836
+ assert "qscale_and_zeros" in kwargs
1837
+ kernel = kwargs["kernel"]
1838
+ qscale_and_zeros = kwargs["qscale_and_zeros"]
1839
+ return [
1840
+ "group_size,",
1841
+ f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),",
1842
+ "N * 2,", # lds
1843
+ "k_start,",
1844
+ ]
1845
+
1846
+ def is_woq_int4(self):
1847
+ return True
1848
+
1849
+
1850
+ @register_micro_gemm(
1851
+ *generate_gemm_config(
1852
+ VecAMX,
1853
+ [ # (block_m, block_n, block_k)
1854
+ (16, 32, 32),
1855
+ (32, 32, 32),
1856
+ ],
1857
+ input_dtype=torch.bfloat16,
1858
+ input2_dtype=torch.uint8,
1859
+ output_dtype=torch.float,
1860
+ compute_dtype=torch.float,
1861
+ extra_check=check_amx_extra,
1862
+ ),
1863
+ )
1864
+ class CppMicroGemmWoQInt4Amx(CppMicroGemmAMX):
1865
+ """
1866
+ This class generates the code for WoQ int4 micro gemm using AMX intrinsics,
1867
+ which are available on 4th and newer generations of Intel Xeon.
1868
+ Shape of packed weight = [N // 32, K, 16], viewed as [N, K // 2]
1869
+ Shape of packed ScalesAndZeros = [K // group_size, N, 2]
1870
+ Reuse TEMPLATE_KERNEL of CppMicroGemmAMX.
1871
+ """
1872
+
1873
+ TEMPLATE_ENTRY = r"""
1874
+ inline bool {{kernel_name}}_is_block_start(int index, int k_start, int group_size) {
1875
+ // check if (k_start + index) % group_size == 0, assuming group_size = 32/64/128
1876
+ return ((k_start + index) & (group_size - 1)) == 0;
1877
+ }
1878
+
1879
+ {{declare_kernel}} {
1880
+ {{kernel.assert_function}}(N % {{block_n}} == 0, "N dimension must be multiple of {{block_n}}");
1881
+ {{kernel.assert_function}}(K % 2 == 0, "K dimension must be multiple of 2");
1882
+ {{kernel.assert_function}}({{block_n}} == 32, "block_n must be 32 for WOQ int4");
1883
+
1884
+ // Create a stack-allocated buffer for tiles of B.
1885
+ // Except maybe for the tail-case, an AMX tile of B has 16x32 BF16 elements.
1886
+ // we cache K * {{block_n}} elements of dequantized B
1887
+ {{template.codegen_allocate_weight_buffer("dequantized_B_buf", input_t, "K", block_n)}}
1888
+
1889
+ constexpr int BLOCK_K = {{block_k}};
1890
+ constexpr int64_t BLOCK_N = {{block_n}};
1891
+ constexpr int COLS = BLOCK_N / 16;
1892
+ const int PREFETCH_SIZE_K = 16 * 4;
1893
+ const int PREFETCH_SIZE_KB = (PREFETCH_SIZE_K + BLOCK_K - 1) / BLOCK_K;
1894
+ const int KB = K / BLOCK_K;
1895
+
1896
+ __m512i b32[COLS * 2];
1897
+ __m512 vb[COLS * 2];
1898
+ __m512 scale[COLS];
1899
+ __m512 zero[COLS];
1900
+
1901
+ // Lookup table to de-quantize int4 values to bf16.
1902
+ // Values are dequantized as truly int4 [-8, 7] range;
1903
+ //
1904
+ // dequant = (bf16(int4_value) * bf16_scale) + bf16_zero
1905
+ //
1906
+ static const __m512 lut = _mm512_set_ps(
1907
+ 7.0f, 6.0f, 5.0f, 4.0f,
1908
+ 3.0f, 2.0f, 1.0f, 0.0f,
1909
+ -1.0f, -2.0f, -3.0f, -4.0f,
1910
+ -5.0f, -6.0f, -7.0f, -8.0f);
1911
+
1912
+ // index for transpose
1913
+ static const __m512i idx1 = _mm512_set_epi32(
1914
+ 30, 28, 26, 24, 22, 20, 18, 16,
1915
+ 14, 12, 10, 8, 6, 4, 2, 0);
1916
+ static const __m512i idx2 = _mm512_set_epi32(
1917
+ 31, 29, 27, 25, 23, 21, 19, 17,
1918
+ 15, 13, 11, 9, 7, 5, 3, 1);
1919
+
1920
+ // Indices for VNNI layout conversion
1921
+ __m512i idx_low = _mm512_set_epi32(
1922
+ 0x17,
1923
+ 0x07,
1924
+ 0x16,
1925
+ 0x06,
1926
+ 0x15,
1927
+ 0x05,
1928
+ 0x14,
1929
+ 0x04,
1930
+ 0x13,
1931
+ 0x03,
1932
+ 0x12,
1933
+ 0x02,
1934
+ 0x11,
1935
+ 0x01,
1936
+ 0x10,
1937
+ 0x00);
1938
+ __m512i idx_high = _mm512_set_epi32(
1939
+ 0x1f,
1940
+ 0x0f,
1941
+ 0x1e,
1942
+ 0x0e,
1943
+ 0x1d,
1944
+ 0x0d,
1945
+ 0x1c,
1946
+ 0x0c,
1947
+ 0x1b,
1948
+ 0x0b,
1949
+ 0x1a,
1950
+ 0x0a,
1951
+ 0x19,
1952
+ 0x09,
1953
+ 0x18,
1954
+ 0x08);
1955
+
1956
+ // load scale and zero point
1957
+ auto load_scale_and_zeros = [&](int i, int _kb) {
1958
+ // load 2x bfloat16 vector
1959
+ __m512i t = _mm512_loadu_si512((__m512i*)(ScaleAndZeros + _kb * lds + 32 * i));
1960
+ _mm_prefetch(ScaleAndZeros + (_kb + PREFETCH_SIZE_KB) * lds + 32 * i, _MM_HINT_T0);
1961
+
1962
+ // convert to 2x f32 vector
1963
+ __m512 a, b;
1964
+ at::vec::cvtbf16_fp32(t, a, b);
1965
+
1966
+ // transpose scale_and_zero from {16, 2} to {2, 16}
1967
+ // inputs:
1968
+ // a: {s0, z0, s1, z1, ..., s7, z7}
1969
+ // b: {s8, z8, s9, z9, ..., s15, z15}
1970
+ // output:
1971
+ // scale: {s0, s1, s2, ..., s15}
1972
+ // zero: {z0, z1, z2, ..., z15}
1973
+ scale[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx1, b);
1974
+ zero[i] = _mm512_mask_permutex2var_ps(a, 0xffff, idx2, b);
1975
+ };
1976
+
1977
+ // Dequantize a B block of 2 * block_n into bf16
1978
+ // So, it handles k and k+1 at the same time
1979
+ auto dequantize_B = [&](int n) {
1980
+ constexpr int64_t ldb_int4 = BLOCK_N / 2; // 16
1981
+ for (int k = 0, kb = 0; k < K; k += 2) {
1982
+ // Since block_k must be 32 for AMX microkernels, k_start may not be
1983
+ // a multiple of q_group_size. In that case, we need to load scales
1984
+ // and zero points immediately when k == 0 here
1985
+ if ({{kernel_name}}_is_block_start(k, k_start, q_group_size) || k == 0) {
1986
+ c10::ForcedUnroll<COLS>{}(load_scale_and_zeros, kb++);
1987
+ }
1988
+
1989
+ _mm_prefetch(B + (k + PREFETCH_SIZE_K) * ldb_int4, _MM_HINT_T0);
1990
+
1991
+ // load 256 bits = 64 elements in int4
1992
+ __m128i b4 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + k * ldb_int4));
1993
+ b32[0] = _mm512_cvtepu8_epi32(b4);
1994
+ b32[1] = _mm512_srli_epi32(b32[0], 4);
1995
+ vb[0] = _mm512_permutexvar_ps(b32[0] , lut);
1996
+ vb[0] = _mm512_fmadd_ps(vb[0], scale[0], zero[0]);
1997
+ vb[1] = _mm512_permutexvar_ps(b32[1], lut);
1998
+ vb[1] = _mm512_fmadd_ps(vb[1], scale[1], zero[1]);
1999
+
2000
+ __m128i b4_2 = _mm_loadu_si128((__m128i*)(B + n / 2 * K + (k + 1) * ldb_int4));
2001
+ b32[0 + COLS] = _mm512_cvtepu8_epi32(b4_2);
2002
+ b32[1 + COLS] = _mm512_srli_epi32(b32[0 + COLS], 4);
2003
+ vb[0 + COLS] = _mm512_permutexvar_ps(b32[0 + COLS] , lut);
2004
+ vb[0 + COLS] = _mm512_fmadd_ps(vb[0 + COLS], scale[0], zero[0]);
2005
+ vb[1 + COLS] = _mm512_permutexvar_ps(b32[1 + COLS], lut);
2006
+ vb[1 + COLS] = _mm512_fmadd_ps(vb[1 + COLS], scale[1], zero[1]);
2007
+
2008
+ for (int i = 0; i < COLS; i++) {
2009
+ // convert to VNNI
2010
+ auto low = _mm512_permutex2var_ps(vb[i], idx_low, vb[i + COLS]);
2011
+ auto high = _mm512_permutex2var_ps(vb[i], idx_high, vb[i + COLS]);
2012
+ // convert lower 16 float32 values to bfloat16
2013
+ auto v0_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(low));
2014
+ // convert higher 16 float32 values to bfloat16
2015
+ auto v1_bf16 = reinterpret_cast<__m256i>(_mm512_cvtneps_pbh(high));
2016
+ // combine the lower 16 and higher 16 bfloat16 values
2017
+ auto v = _mm512_castsi256_si512(v0_bf16);
2018
+ v = _mm512_inserti64x4(v, v1_bf16, 1);
2019
+ // store the VNNI format bfloat16 values
2020
+ {{input_t}}* addr = dequantized_B_buf + k * 32 + (i % 2) * 32;
2021
+ _mm512_storeu_si512(addr, v);
2022
+ }
2023
+ }
2024
+ };
2025
+
2026
+ for (int64_t n = 0; n < N; n += {{block_n}}) {
2027
+ // Dequantize K * block_n int8 B elements into BF16
2028
+ dequantize_B(n);
2029
+ for (int64_t m = 0; m < M; m += {{block_m}}) {
2030
+ int64_t block_m = std::min<int64_t>(M - m, {{block_m}});
2031
+ int64_t m_tail = m;
2032
+ {%- for num_rows in range(block_m, 0, -16) %}
2033
+ {%- if num_rows != block_m %}
2034
+ else
2035
+ {%- endif %}
2036
+ if (block_m >= {{num_rows}}) {
2037
+ {{kernel_name}}_amx_kernel_{{num_rows}}_{{num_columns}}<accum>(
2038
+ amx_state,
2039
+ A + m * lda,
2040
+ dequantized_B_buf + n * K,
2041
+ C + m * ldc + n,
2042
+ K,
2043
+ lda,
2044
+ {{block_n}},
2045
+ ldc,
2046
+ 16
2047
+ );
2048
+ block_m -= {{num_rows}};
2049
+ m_tail += {{num_rows}};
2050
+ }
2051
+ {%- endfor %}
2052
+ if (block_m > 0) {
2053
+ {{kernel_name}}_amx_kernel_16_{{num_columns}}<accum>(
2054
+ amx_state,
2055
+ A + m_tail * lda,
2056
+ dequantized_B_buf + n * K,
2057
+ C + m_tail * ldc + n,
2058
+ K,
2059
+ lda,
2060
+ {{block_n}},
2061
+ ldc,
2062
+ block_m
2063
+ );
2064
+ }
2065
+ } // for m
2066
+ } // for n
2067
+ }
2068
+ """
2069
+
2070
+ def get_kernel_extra_args_declare(self) -> str:
2071
+ return (
2072
+ "AMXState& amx_state,\n"
2073
+ " const int64_t q_group_size,\n"
2074
+ " const c10::BFloat16* __restrict__ ScaleAndZeros,\n"
2075
+ " const int64_t lds,\n"
2076
+ " int64_t k_start,"
2077
+ )
2078
+
2079
+ def get_kernel_extra_args(self, **kwargs) -> list[str]:
2080
+ assert "kernel" in kwargs
2081
+ assert "qscale_and_zeros" in kwargs
2082
+ kernel = kwargs["kernel"]
2083
+ qscale_and_zeros = kwargs["qscale_and_zeros"]
2084
+ return [
2085
+ "amx_state,",
2086
+ "group_size,",
2087
+ f"&({kernel.index(qscale_and_zeros, [0, 0, 0])}),",
2088
+ "N * 2,", # lds
2089
+ "k_start,",
2090
+ ]
2091
+
2092
+ def is_woq_int4(self):
2093
+ return True
2094
+
2095
+
2096
+ def create_micro_gemm(
2097
+ name,
2098
+ m,
2099
+ n,
2100
+ k,
2101
+ input_dtype,
2102
+ input2_dtype,
2103
+ output_dtype=None,
2104
+ compute_dtype=None,
2105
+ alpha=1,
2106
+ num_threads=-1,
2107
+ use_ref=True,
2108
+ q_group_size=None,
2109
+ ) -> Optional[CppMicroGemm]:
2110
+ """
2111
+ Based on the provided info, try to find the config of the micro-kernel that would
2112
+ deliver the best performance in terms of lower latency for this case.
2113
+ """
2114
+
2115
+ def create_from_config(cls, config: CppMicroGemmConfig):
2116
+ return cls(
2117
+ name,
2118
+ config.input_dtype,
2119
+ config.input2_dtype,
2120
+ config.output_dtype,
2121
+ config.compute_dtype,
2122
+ config.register_blocking,
2123
+ alpha,
2124
+ )
2125
+
2126
+ def skip_amx_kernel_for_woq(dynamic_M):
2127
+ # For WoQ GEMM, AMX micro-kernel may not perform well if m is small.
2128
+ # Exception: for dynamic shapes, we consider using the AMX micro-kernel.
2129
+ if (
2130
+ dynamic_M
2131
+ or input_dtype != torch.bfloat16
2132
+ or input2_dtype not in [torch.int8, torch.uint8]
2133
+ ):
2134
+ return False
2135
+ m_threshold = 5
2136
+ return m < m_threshold
2137
+
2138
+ assert isinstance(n, int) or n.is_number, n
2139
+ assert isinstance(k, int) or k.is_number, k
2140
+ from ..utils import has_free_symbols
2141
+
2142
+ dynamic_M = has_free_symbols((m,))
2143
+ m = V.graph.sizevars.optimization_hint(m, fallback=1)
2144
+ assert isinstance(m, int) or m.is_number, m
2145
+ if output_dtype is None:
2146
+ output_dtype = input_dtype
2147
+ if compute_dtype is None:
2148
+ compute_dtype = output_dtype
2149
+ if num_threads < 0:
2150
+ num_threads = parallel_num_threads()
2151
+ vec_isa = pick_vec_isa()
2152
+ matched_configs = []
2153
+ for cls, configs in micro_gemm_configs.items():
2154
+ for config in configs:
2155
+ if not issubclass(vec_isa.__class__, config.vec_isa_cls):
2156
+ continue
2157
+ if (
2158
+ config.input_dtype == input_dtype
2159
+ and config.compute_dtype == compute_dtype
2160
+ and config.input2_dtype == input2_dtype
2161
+ and config.output_dtype == output_dtype
2162
+ # The output_dtype here is the output dtype of the micro-kernel.
2163
+ # In some cases, the actual output dtype of the op for which the micro-kernel
2164
+ # is being created would be same as that of the activation, but the micro-kernels
2165
+ # compute output in Float/int32, which is converted in the GEMM template. This is
2166
+ # subject to change in the future.
2167
+ ):
2168
+ if config.extra_check is not None and not config.extra_check(
2169
+ config,
2170
+ m,
2171
+ n,
2172
+ k,
2173
+ alpha,
2174
+ num_threads,
2175
+ dynamic_M=dynamic_M,
2176
+ q_group_size=q_group_size,
2177
+ vec_isa=vec_isa,
2178
+ ):
2179
+ continue
2180
+ block_m, block_n, block_k = config.register_blocking
2181
+ if config.vec_isa_cls == VecAMX and skip_amx_kernel_for_woq(dynamic_M):
2182
+ continue
2183
+ # Criteria on the ranking of configurations
2184
+ # 1. ISA: AMX > VNNI > VEC
2185
+ # 2. Dividable by block sizes (block_m, block_n, block_k)
2186
+ # 3. Number of mxn blocks is large enough to occupy all the threads
2187
+ # 4. Register blocks are larger
2188
+ isa_score = 0
2189
+ if config.vec_isa_cls == VecAMX:
2190
+ isa_score += 2
2191
+ elif config.vec_isa_cls == VecAVX512VNNI:
2192
+ isa_score += 1
2193
+ dividable_score = 0
2194
+ if m % block_m == 0:
2195
+ dividable_score += 1
2196
+ if n % block_n == 0:
2197
+ dividable_score += 1
2198
+ if k % block_k == 0:
2199
+ dividable_score += 1
2200
+ occupancy_score = 0
2201
+ n_blocks = (n + block_n - 1) // block_n
2202
+ total_mxn_blocks = n_blocks * ((m + block_m - 1) // block_m)
2203
+ if n_blocks >= num_threads:
2204
+ occupancy_score += 1
2205
+ if total_mxn_blocks >= num_threads:
2206
+ occupancy_score += 1
2207
+ register_bytes = (
2208
+ block_m * block_n * config.compute_dtype.itemsize
2209
+ + (block_m * block_k + block_k * block_n)
2210
+ * config.input_dtype.itemsize
2211
+ )
2212
+ size_score = register_bytes
2213
+ # if number of mxn blocks can not occupy all the threads,
2214
+ # we favor smaller register blocks.
2215
+ if occupancy_score == 0:
2216
+ size_score = 0 - register_bytes
2217
+ matched_configs.append(
2218
+ (
2219
+ (isa_score, dividable_score, occupancy_score, size_score),
2220
+ cls,
2221
+ config,
2222
+ )
2223
+ )
2224
+ if len(matched_configs) == 0:
2225
+ if use_ref:
2226
+ return CppMicroGemmRef(
2227
+ name, input_dtype, input2_dtype, output_dtype, compute_dtype, alpha
2228
+ )
2229
+ else:
2230
+ return None
2231
+ # TODO(jgong5): allow autotuning on choices of configs
2232
+ return create_from_config(*max(matched_configs, key=operator.itemgetter(0))[1:])
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import ctypes
3
+ import functools
4
+ import itertools
5
+ import logging
6
+ import sys
7
+ from collections.abc import Callable, Iterable
8
+ from typing import Optional, Union
9
+ from unittest.mock import patch
10
+
11
+ import sympy
12
+
13
+ from .. import config, ir
14
+ from ..autotune_process import CppBenchmarkRequest, TensorMeta
15
+ from ..utils import IndentedBuffer, Placeholder, unique
16
+ from ..virtualized import V
17
+ from .common import KernelTemplate
18
+ from .cpp_template_kernel import CppTemplateCaller, CppTemplateKernel
19
+
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ class CppTemplate(KernelTemplate):
25
+ index_counter = itertools.count()
26
+
27
+ def __init__(
28
+ self,
29
+ name: str,
30
+ input_nodes,
31
+ layout: ir.Layout,
32
+ num_threads: int,
33
+ epilogue_creator: Optional[Callable[[ir.Buffer], ir.Pointwise]] = None,
34
+ ) -> None:
35
+ super().__init__(name)
36
+ self.input_nodes = input_nodes
37
+ self.index = next(self.index_counter)
38
+ self.output_node: Union[ir.Buffer, list[ir.Buffer]] = ir.Buffer(
39
+ name=f"buf_out{self.index}", layout=layout
40
+ )
41
+ self.layout = layout
42
+ self.num_threads = num_threads
43
+ self.epilogue_creator = epilogue_creator
44
+
45
+ def generate(self, **kwargs):
46
+ kernel_name = f"cpp_{self.name}"
47
+ with (
48
+ patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)),
49
+ patch.object(ir.FlexibleLayout, "allow_indexing", True),
50
+ V.graph.set_current_device(self.layout.device),
51
+ CppTemplateKernel(
52
+ kernel_name=kernel_name, num_threads=self.num_threads
53
+ ) as kernel,
54
+ ):
55
+ code = kernel.render(self, **kwargs)
56
+ _, call_args, _, _ = kernel.args.python_argdefs()
57
+ log.debug("Generated Code:\n%s", code)
58
+ log.debug(
59
+ "Args: cpp_argdefs: %s, python_argdefs: %s",
60
+ kernel.args.cpp_argdefs(),
61
+ kernel.args.python_argdefs(),
62
+ )
63
+
64
+ expected_args = list(
65
+ unique(input_node.get_name() for input_node in self.input_nodes)
66
+ )
67
+ if isinstance(self.output_node, Iterable):
68
+ expected_args.extend([node.get_name() for node in self.output_node])
69
+ else:
70
+ expected_args.extend([self.output_node.get_name()])
71
+ assert list(call_args)[: len(expected_args)] == expected_args, (
72
+ call_args,
73
+ expected_args,
74
+ )
75
+ extra_args = V.graph.sizevars.size_hints(
76
+ map(sympy.expand, call_args[len(expected_args) :])
77
+ )
78
+ # Cast the size hint from int to ctypes.c_ulonglong explicitly
79
+ # since in cpp kernel, we bind it to C long
80
+ extra_args = tuple(ctypes.c_ulonglong(x) for x in extra_args)
81
+
82
+ kernel_hash_name = f"cpp_{self.name}_{self.index}"
83
+
84
+ # Create the BenchmarkRequest for CPP
85
+ bmreq = CppBenchmarkRequest(
86
+ kernel_name=kernel_name,
87
+ input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes),
88
+ output_tensor_meta=TensorMeta.from_irnodes(self.output_node),
89
+ extra_args=extra_args,
90
+ source_code=code,
91
+ )
92
+
93
+ def make_kernel_render(
94
+ template_node: ir.CppTemplateBuffer,
95
+ flag_template_buffer_has_other_users: bool,
96
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
97
+ ):
98
+ kernel = CppTemplateKernel(
99
+ kernel_name=str(Placeholder.KERNEL_NAME), num_threads=self.num_threads
100
+ )
101
+ render = functools.partial(
102
+ kernel.render,
103
+ self,
104
+ template_buffer_node=template_node,
105
+ flag_template_buffer_has_other_users=flag_template_buffer_has_other_users,
106
+ epilogue_nodes=epilogue_nodes,
107
+ **kwargs,
108
+ )
109
+ return kernel, render
110
+
111
+ return CppTemplateCaller(
112
+ kernel_hash_name,
113
+ self.name,
114
+ self.input_nodes,
115
+ # pyrefly: ignore [bad-index, index-error]
116
+ self.output_node[0].get_layout()
117
+ if isinstance(self.output_node, Iterable)
118
+ else self.output_node.get_layout(),
119
+ make_kernel_render,
120
+ bmreq,
121
+ self,
122
+ )
123
+
124
+ def header(self) -> IndentedBuffer:
125
+ res = IndentedBuffer()
126
+ res.writeline("#include <torch/csrc/inductor/cpp_prefix.h>")
127
+ # TODO: add c10::ForcedUnroll test to test_aoti_abi_check
128
+ res.splice("""#include <c10/util/Unroll.h>""")
129
+ res.splice("""#include <torch/csrc/inductor/aoti_torch/c/shim.h>""")
130
+ enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [
131
+ "linux",
132
+ "win32",
133
+ ]
134
+ if enable_kernel_profile:
135
+ res.writelines(["#include <torch/csrc/inductor/aoti_runtime/utils.h>"])
136
+ return res
137
+
138
+ def render(self, **kwargs) -> str:
139
+ raise NotImplementedError
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_template_kernel.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import itertools
3
+ from collections.abc import Callable, Iterable
4
+ from typing import Any, Optional, Union
5
+ from unittest.mock import patch
6
+
7
+ import sympy
8
+ from sympy.parsing.sympy_parser import parse_expr
9
+
10
+ import torch
11
+ from torch._inductor.utils import do_bench_using_profiling
12
+ from torch.utils._ordered_set import OrderedSet
13
+ from torch.utils._sympy.symbol import SymT
14
+
15
+ from .. import config, cpp_builder, ir, lowering as L
16
+ from ..autotune_process import CppBenchmarkRequest
17
+ from ..loop_body import LoopBody
18
+ from ..select_algorithm import PartialRender
19
+ from ..utils import sympy_index_symbol, sympy_index_symbol_with_prefix
20
+ from ..virtualized import V
21
+ from .common import REMOVED
22
+ from .cpp import CppKernel, CppKernelProxy, KernelGroup, ParallelDepth
23
+ from .cpp_utils import cexpr_index, DTYPE_TO_CPP, LocalBufferContext
24
+
25
+
26
+ def parse_expr_with_index_symbols(expr):
27
+ if isinstance(expr, sympy.Expr):
28
+ return expr
29
+ elif isinstance(expr, (list, tuple)):
30
+ return [parse_expr_with_index_symbols(e) for e in expr]
31
+ else:
32
+ expr = parse_expr(str(expr))
33
+ int_symbols = {sym: sympy_index_symbol(sym.name) for sym in expr.free_symbols}
34
+ return expr.subs(int_symbols)
35
+
36
+
37
+ def wrap_with_tensorbox(node) -> ir.TensorBox:
38
+ return (
39
+ ir.TensorBox.create(node) if isinstance(node, ir.Buffer) else ir.TensorBox(node)
40
+ )
41
+
42
+
43
+ class CppTemplateKernel(CppKernel):
44
+ def __init__(self, kernel_name, num_threads):
45
+ super().__init__(None, num_threads)
46
+ self.kernel_name = kernel_name
47
+ self.render_hooks = {}
48
+ self.local_buffers = {}
49
+
50
+ def render(self, template, **kwargs):
51
+ return PartialRender(
52
+ template.render(kernel=self, **kwargs), self.render_hooks
53
+ ).finalize_all()
54
+
55
+ def def_kernel(
56
+ self,
57
+ inputs: dict[str, ir.Buffer],
58
+ outputs: dict[str, ir.Buffer],
59
+ aliases: Optional[dict[str, str]] = None,
60
+ function_name: str = "",
61
+ extra_sizevars: Optional[list[sympy.Expr]] = None,
62
+ placeholder: str = "<DEF_KERNEL>",
63
+ ) -> str:
64
+ if len(function_name) == 0:
65
+ function_name = str(self.kernel_name)
66
+ for name, inp in inputs.items():
67
+ if inp is not None:
68
+ self.args.input_buffers[inp.get_name()] = name
69
+ for name, out in outputs.items():
70
+ self.args.output_buffers[out.get_name()] = name
71
+ if aliases is not None:
72
+ for alias, orig in aliases.items():
73
+ if orig in self.args.input_buffers:
74
+ self.args.input_buffers[alias] = self.args.input_buffers[orig]
75
+ if orig in self.args.output_buffers:
76
+ self.args.output_buffers[alias] = self.args.output_buffers[orig]
77
+
78
+ unique_sizevars = OrderedSet(
79
+ s
80
+ for input in inputs.values()
81
+ if input is not None
82
+ for sym in itertools.chain(input.get_size(), input.get_stride())
83
+ if isinstance(sym, sympy.Expr)
84
+ for s in sym.free_symbols
85
+ )
86
+ unique_sizevars.update(
87
+ s
88
+ for sym in extra_sizevars or []
89
+ if isinstance(sym, sympy.Expr)
90
+ for s in sym.free_symbols
91
+ )
92
+ unique_sizevars.update(
93
+ s
94
+ for output in outputs.values()
95
+ for sym in itertools.chain(output.get_size(), output.get_stride())
96
+ if isinstance(sym, sympy.Expr)
97
+ for s in sym.free_symbols
98
+ )
99
+ sizevars = sorted(unique_sizevars, key=str)
100
+ for sizevar in sizevars:
101
+ self.args.sizevars[sizevar] = f"k{sizevar}"
102
+
103
+ def hook():
104
+ # remove all aliases before generate function definition
105
+ if aliases is not None:
106
+ for alias in aliases:
107
+ if alias in self.args.input_buffers:
108
+ raise AssertionError(
109
+ f"input_buffers cannot be removed: {alias}"
110
+ )
111
+ if alias in self.args.output_buffers:
112
+ self.args.output_buffers[alias] = REMOVED
113
+ cpp_argdefs, _, _ = self.args.cpp_argdefs()
114
+ return f"void {function_name}({', '.join(cpp_argdefs)})"
115
+
116
+ assert placeholder not in self.render_hooks
117
+ self.render_hooks[placeholder] = hook
118
+ return placeholder
119
+
120
+ def call_kernel(self, name: str, node: ir.CppTemplateBuffer):
121
+ wrapper = V.graph.wrapper_code
122
+ _, call_args, arg_types = self.args.cpp_argdefs()
123
+ wrapper.generate_kernel_call(name, call_args, triton=False, arg_types=arg_types)
124
+
125
+ def dtype(self, node: ir.Buffer) -> str:
126
+ return DTYPE_TO_CPP[node.get_dtype()]
127
+
128
+ def acc_dtype(self, node: ir.Buffer) -> str:
129
+ if node.get_dtype() in [torch.float32, torch.bfloat16, torch.half]:
130
+ return "float"
131
+ else:
132
+ raise NotImplementedError(f"Unsupported dtype: {node.get_dtype()}")
133
+
134
+ def size(self, node: ir.Buffer, dim: int) -> str:
135
+ return cexpr_index(self.rename_indexing(node.get_size()[dim]))
136
+
137
+ def stride(self, node: ir.Buffer, dim: int) -> str:
138
+ return cexpr_index(self.rename_indexing(node.get_stride()[dim]))
139
+
140
+ def index(self, node: ir.Buffer, indices: list[Any]) -> str:
141
+ indexer = node.get_layout().as_fixed().make_indexer()
142
+ index = indexer(parse_expr_with_index_symbols(indices))
143
+ index = self.rename_indexing(index)
144
+ outer_name = node.get_name()
145
+ inner_name = (
146
+ outer_name
147
+ if outer_name in self.local_buffers
148
+ else self.args.input(node.get_name())
149
+ )
150
+ return f"{inner_name}[{cexpr_index(index)}]"
151
+
152
+ def slice_nd(self, node, ranges: list[tuple[Any, Any]]) -> ir.ReinterpretView:
153
+ """
154
+ Slice the given node with a list of ranges (start and end) corresponding to its dims.
155
+ The dim is not sliced if the corresponding range is empty.
156
+ """
157
+ assert len(ranges) == len(node.get_size()), f"{ranges=}, {node=}"
158
+ sliced = wrap_with_tensorbox(node)
159
+ for dim, _range in enumerate(ranges):
160
+ if len(_range) == 0:
161
+ continue
162
+ assert len(_range) == 2
163
+ start, end = parse_expr_with_index_symbols(_range)
164
+ sliced = L.slice_(sliced, dim, start, end, clamp=False)
165
+ assert isinstance(sliced, ir.TensorBox)
166
+ assert isinstance(sliced.data, ir.ReinterpretView), sliced.data
167
+ return sliced.data
168
+
169
+ def select(self, node, dim: int, idx: int) -> ir.ReinterpretView:
170
+ # We avoid using L.select here because we need clamp=False so the dim after slicing
171
+ # is 1 instead of a sympy expression of symbol - dim_size.
172
+ node = wrap_with_tensorbox(node)
173
+ idx = ir.View.handle_negative_index(idx, node.get_size()[dim])
174
+ sliced = L.squeeze(L.slice_(node, dim, idx, idx + 1, clamp=False), dim)
175
+ assert isinstance(sliced.data, ir.ReinterpretView), sliced.data
176
+ return sliced.data
177
+
178
+ def view(self, node, sizes: list[Any]) -> ir.IRNode:
179
+ node = wrap_with_tensorbox(node)
180
+ sizes = parse_expr_with_index_symbols(sizes)
181
+ return L.view(node, sizes).data # type: ignore[arg-type]
182
+
183
+ def permute(self, node, dims):
184
+ node = wrap_with_tensorbox(node)
185
+ permuted = L.permute(node, dims).data
186
+ assert isinstance(permuted, ir.ReinterpretView)
187
+ return permuted
188
+
189
+ def maybe_codegen_profile(self) -> str:
190
+ if config.cpp.enable_kernel_profile:
191
+ graph_id = V.graph.graph_id
192
+ prefix = "graph_" + str(graph_id) + "_" if graph_id is not None else ""
193
+ handle_str = (
194
+ "torch::aot_inductor::RAIIAtenRecordFunctionHandle "
195
+ f'record_{prefix}{self.kernel_name}_("{prefix}{self.kernel_name}", nullptr);'
196
+ )
197
+ return handle_str
198
+ else:
199
+ return ""
200
+
201
+ def unroll_pragma(self, unroll):
202
+ if cpp_builder.is_gcc():
203
+ return f"#pragma GCC unroll {unroll}"
204
+ else:
205
+ return f"#pragma unroll {unroll}"
206
+
207
+ def define_buffer(self, name, sizes: list[Any], dtype=torch.float) -> str:
208
+ """Define kernel local buffer"""
209
+ sizes = parse_expr_with_index_symbols(sizes)
210
+ buf = ir.Buffer(
211
+ name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes)
212
+ )
213
+ self.local_buffers[name] = buf
214
+ ctype = f"{DTYPE_TO_CPP[dtype]}"
215
+ numel = f"{cexpr_index(buf.get_numel())}"
216
+ return f"auto _{name} = std::make_unique<{ctype}[]>({numel}); auto {name} = _{name}.get();"
217
+
218
+ def define_stack_allocated_buffer(
219
+ self, name, sizes: list[Any], dtype=torch.float
220
+ ) -> str:
221
+ """Define stack-allocated buffer"""
222
+ sizes = parse_expr_with_index_symbols(sizes)
223
+ buf = ir.Buffer(
224
+ name=name, layout=ir.FixedLayout(torch.device("cpu"), dtype, sizes)
225
+ )
226
+ self.local_buffers[name] = buf
227
+ ctype = f"{DTYPE_TO_CPP[dtype]}"
228
+ numel = f"{cexpr_index(buf.get_numel())}"
229
+ return f"alignas(64) {ctype} _{name}[{numel}]; {ctype}* {name} = _{name};"
230
+
231
+ def reinit_buffer_if_null(self, name):
232
+ """Reinit the previously defined local buffer if it is null"""
233
+ assert name in self.local_buffers
234
+ buf = self.local_buffers[name]
235
+ ctype = f"{DTYPE_TO_CPP[buf.layout.dtype]}"
236
+ numel = f"{cexpr_index(buf.get_numel())}"
237
+ return f"if (_{name} == nullptr) {{ _{name} = std::make_unique<{ctype}[]>({numel}); {name} = _{name}.get(); }}"
238
+
239
+ def release_buffer(self, name):
240
+ """Codegen the code to release the ownership of a local buffer to others"""
241
+ assert name in self.local_buffers
242
+ return f"_{name}.release()"
243
+
244
+ def store_pointwise_nodes(
245
+ self,
246
+ dst: ir.Buffer,
247
+ nodes: list[ir.IRNode],
248
+ offsets: Optional[list[sympy.Expr]] = None,
249
+ reindexers: Optional[list[Optional[Callable[[list[Any]], list[Any]]]]] = None,
250
+ ) -> str:
251
+ var_sizes = (tuple(dst.get_size()), ())
252
+ var_ranges = {
253
+ sympy_index_symbol_with_prefix(SymT.INDEX, i): sz
254
+ for i, sz in enumerate(var_sizes[0])
255
+ }
256
+ if not offsets:
257
+ offsets = [sympy.S.Zero] * len(var_sizes[0])
258
+ if not reindexers:
259
+ reindexers = [None] * len(nodes)
260
+ assert len(offsets) == len(var_sizes[0])
261
+ output_index = dst.get_layout().make_indexer()([*var_ranges.keys()])
262
+ kernel_group = KernelGroup()
263
+ kernel_group.args = self.args
264
+ cpp_kernel_proxy = CppKernelProxy(kernel_group)
265
+ bodies = []
266
+ var_sizes_list = []
267
+ for i, node in enumerate(nodes):
268
+ output_name = node.get_name() if i < len(nodes) - 1 else dst.get_name()
269
+ node = node.data if isinstance(node, ir.ComputedBuffer) else node
270
+ assert isinstance(node, ir.Pointwise), node
271
+
272
+ def fn(*args):
273
+ assert len(args) == 2
274
+ assert len(args[0]) == len(var_sizes[0])
275
+ assert len(args[1]) == 0
276
+ new_args = [arg + offset for arg, offset in zip(args[0], offsets)] # type: ignore[arg-type]
277
+ if reindexers[i] is not None:
278
+ new_args = reindexers[i](new_args) # type: ignore[misc]
279
+ V.ops.store(
280
+ output_name,
281
+ output_index,
282
+ node.make_loader()(new_args).value,
283
+ )
284
+
285
+ body = LoopBody(
286
+ fn,
287
+ (list(var_ranges.keys()), ()),
288
+ var_ranges,
289
+ list(var_ranges.keys()),
290
+ tuple(),
291
+ )
292
+ bodies.append(body)
293
+ var_sizes_list.append(var_sizes)
294
+
295
+ cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list)
296
+
297
+ def max_parallel_depth():
298
+ return ParallelDepth(parallel_depth=0, start_depth=0)
299
+
300
+ # This loop is not parallelized since it is not the outermost loop.
301
+ with patch.object(
302
+ cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth
303
+ ):
304
+ kernel_group.finalize_kernel(cpp_kernel_proxy, [])
305
+ return kernel_group.loops_code.getvalue()
306
+
307
+ def store_grouped_gemm_pointwise_nodes(
308
+ self,
309
+ dst: tuple[ir.Buffer],
310
+ nodes: list[ir.IRNode],
311
+ offsets: list[sympy.Expr],
312
+ reindexers: list[Optional[Callable[[list[Any]], list[Any]]]],
313
+ output_names: list[str],
314
+ ) -> str:
315
+ ref_dst = dst[0]
316
+ var_sizes = (tuple(ref_dst.get_size()), ())
317
+ var_ranges = {
318
+ sympy_index_symbol_with_prefix(SymT.INDEX, i): sz
319
+ for i, sz in enumerate(var_sizes[0])
320
+ }
321
+ assert offsets, "offsets should be set outside"
322
+ assert all(len(offset) == len(var_sizes[0]) for offset in offsets)
323
+ output_index = ref_dst.get_layout().make_indexer()([*var_ranges.keys()])
324
+ kernel_group = KernelGroup()
325
+ kernel_group.args = self.args
326
+ cpp_kernel_proxy = CppKernelProxy(kernel_group)
327
+ bodies = []
328
+ var_sizes_list = []
329
+ for i, node in enumerate(nodes):
330
+ output_name = output_names[i]
331
+ node = node.data if isinstance(node, ir.ComputedBuffer) else node
332
+ assert isinstance(node, ir.Pointwise), node
333
+
334
+ def fn(*args):
335
+ assert len(args) == 2
336
+ assert len(args[0]) == len(var_sizes[0])
337
+ assert len(args[1]) == 0
338
+ new_args = [arg + offset for arg, offset in zip(args[0], offsets[i])] # type: ignore[arg-type]
339
+ if reindexers[i] is not None:
340
+ new_args = reindexers[i](new_args) # type: ignore[misc]
341
+ V.ops.store(
342
+ output_name,
343
+ output_index,
344
+ node.make_loader()(new_args).value,
345
+ )
346
+
347
+ body = LoopBody(
348
+ fn,
349
+ (list(var_ranges.keys()), ()),
350
+ var_ranges,
351
+ list(var_ranges.keys()),
352
+ tuple(),
353
+ )
354
+ bodies.append(body)
355
+ var_sizes_list.append(var_sizes)
356
+
357
+ cpp_kernel_proxy.codegen_loop_bodies(bodies, var_sizes_list)
358
+
359
+ def max_parallel_depth():
360
+ return ParallelDepth(parallel_depth=0, start_depth=0)
361
+
362
+ # This loop is not parallelized since it is not the outermost loop.
363
+ with patch.object(
364
+ cpp_kernel_proxy.loop_nest, "max_parallel_depth", max_parallel_depth
365
+ ):
366
+ kernel_group.finalize_kernel(cpp_kernel_proxy, [])
367
+ return kernel_group.loops_code.getvalue()
368
+
369
+ def store_output(
370
+ self,
371
+ dst: ir.Buffer,
372
+ src: ir.Buffer,
373
+ orig_src: Optional[ir.Buffer] = None,
374
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
375
+ offsets: Optional[list[Any]] = None,
376
+ reindexers: Optional[list[Optional[Callable[[list[Any]], list[Any]]]]] = None,
377
+ ):
378
+ """
379
+ Store the `src` buffer to the `dst` buffer. The size of `src` and `dst` should match.
380
+ If `epilogue_nodes` is provided, the `src` buffer is firstly computed with the epilogues
381
+ before stored to `dst`. The `epilogues_nodes` are all pointwise.
382
+
383
+ Notes:
384
+ 1. `src` and `dst` buffer could be the same buffer in which case we are doing in-place compute
385
+ and stores. In case `epilogue_nodes` are not provided, we do nothing.
386
+ 2. The `epilogue_nodes`, if exist, have computations on `src` before storing to `dst` but since
387
+ they come form the original Inductor IR, they might need to be adjusted before working with
388
+ `src` and `dst` as outlined below:
389
+ a) `src` or `dst` buffer could be a sub-slice of the ranges the `epilogue_nodes`work on.
390
+ In this case, the `offsets` could be provided to adjust the indices passed to
391
+ `epilogue_nodes` during codegen and the data ranges are also configured according to
392
+ the sizes of `src` and `dst`.
393
+ b) `dst` might be indexed in a different way as the `epilogue_nodes`, hence a `reindexer` is
394
+ needed on the indices to `epilogue_nodes` to match the indexing of `dst`.
395
+ c) If `src` is local, we need to add a local buffer for it and localize the `orig_src` buffer
396
+ in `epilogue_nodes` with `src`.
397
+ """
398
+ assert isinstance(dst, (ir.Buffer, ir.ReinterpretView))
399
+ assert dst.get_size() == src.get_size(), f"{dst=}, {src=}"
400
+ if offsets:
401
+ offsets = parse_expr_with_index_symbols(offsets)
402
+ if epilogue_nodes:
403
+ with LocalBufferContext(self.args) as scope:
404
+ assert orig_src is not None
405
+ if orig_src.get_name() != src.get_name():
406
+ scope.add_local_buffer(
407
+ src,
408
+ [
409
+ orig_src,
410
+ ],
411
+ )
412
+ epilogue_nodes = scope.localize_nodes(epilogue_nodes)
413
+ return self.store_pointwise_nodes(
414
+ dst,
415
+ epilogue_nodes, # type: ignore[arg-type]
416
+ offsets,
417
+ reindexers,
418
+ )
419
+ else:
420
+ if dst.get_name() != src.get_name():
421
+ # src is local
422
+ copy = L.copy(dst, src).data.data
423
+ with LocalBufferContext(self.args) as scope:
424
+ scope.add_local_buffer(src)
425
+
426
+ return self.store_pointwise_nodes(dst, [copy])
427
+ else:
428
+ assert dst.layout == src.layout, f"{dst=}, {src=}"
429
+ return ""
430
+
431
+ def store_outputs(
432
+ self,
433
+ dst: tuple[ir.Buffer],
434
+ src: tuple[ir.IRNode],
435
+ orig_src: Optional[tuple[ir.IRNode]] = None,
436
+ epilogue_nodes: Optional[list[ir.IRNode]] = None,
437
+ offsets: Optional[list[Any]] = None,
438
+ reindexers: Optional[list[Optional[Callable[[list[Any]], list[Any]]]]] = None,
439
+ multi_output_buffers: Optional[tuple[ir.MultiOutput, ...]] = None,
440
+ ):
441
+ assert isinstance(dst, Iterable)
442
+ assert all(_dst.get_size() == _src.get_size() for _src, _dst in zip(src, dst))
443
+ if offsets:
444
+ offsets = parse_expr_with_index_symbols(offsets)
445
+ gemm_num = len(src)
446
+ final_offsets = []
447
+ output_names = []
448
+ if epilogue_nodes:
449
+ if not reindexers:
450
+ reindexers = [None] * len(epilogue_nodes)
451
+ with LocalBufferContext(self.args) as scope:
452
+ assert orig_src is not None
453
+ localize_epilogue_nodes = []
454
+ all_read_names = []
455
+ for epilogue in epilogue_nodes:
456
+ all_read_names.extend(list(epilogue.get_read_names()))
457
+ localize_epilogue_nodes.extend(scope.localize_nodes(epilogue_nodes))
458
+ final_offsets.extend([offsets] * len(localize_epilogue_nodes))
459
+ output_names.extend(
460
+ [node.get_name() for node in localize_epilogue_nodes]
461
+ )
462
+ for gemm_idx in range(gemm_num):
463
+ if orig_src[gemm_idx].get_name() != src[gemm_idx].get_name():
464
+ if orig_src[gemm_idx].get_name() in all_read_names or (
465
+ multi_output_buffers
466
+ and multi_output_buffers[gemm_idx].get_name()
467
+ in all_read_names
468
+ ):
469
+ # If any of the Epilogue nodes use this GEMM output, let's localize the GEMM output
470
+ global_buffers = [orig_src[gemm_idx]]
471
+ if (
472
+ multi_output_buffers
473
+ and multi_output_buffers[gemm_idx].get_name()
474
+ in all_read_names
475
+ and orig_src[gemm_idx].get_name() not in all_read_names
476
+ ):
477
+ # Epilogue might directly read the MultiOutput, Locallize MultiOutput to the local Buffer
478
+ # if this MultiOutput has not been stored by in-template epilogue
479
+ # otherwise, use the cse store cache if it will be stored before used
480
+ global_buffers.append(multi_output_buffers[gemm_idx])
481
+ scope.add_local_buffer(
482
+ src[gemm_idx],
483
+ global_buffers,
484
+ )
485
+ else:
486
+ scope.add_local_buffer(src[gemm_idx])
487
+ localize_epilogue_nodes.extend(
488
+ [L.copy(dst[gemm_idx], src[gemm_idx]).data.data]
489
+ )
490
+ reindexers.append(None)
491
+ output_names.append(dst[gemm_idx].get_name())
492
+ final_offsets.append(
493
+ [sympy.S.Zero] * len(dst[gemm_idx].get_size())
494
+ )
495
+ res = self.store_grouped_gemm_pointwise_nodes(
496
+ dst,
497
+ localize_epilogue_nodes,
498
+ final_offsets,
499
+ reindexers,
500
+ output_names=output_names,
501
+ )
502
+ for gemm_idx in range(gemm_num):
503
+ if (
504
+ multi_output_buffers
505
+ and multi_output_buffers[gemm_idx].get_name() in all_read_names
506
+ ):
507
+ # If the MultiOutput is used in the Epilogue, let's remove it from args
508
+ multi_output_name = multi_output_buffers[gemm_idx].get_name()
509
+ if (
510
+ multi_output_name in self.args.output_buffers
511
+ and self.args.output_buffers[multi_output_name]
512
+ is not REMOVED
513
+ ):
514
+ self.remove_buffer(multi_output_name)
515
+ return res
516
+ else:
517
+ if dst[0].get_name() != src[0].get_name():
518
+ copy_list = []
519
+ with LocalBufferContext(self.args) as scope:
520
+ for _src, _dst in zip(src, dst):
521
+ copy_list.extend([L.copy(_dst, _src).data.data])
522
+ scope.add_local_buffer(_src)
523
+ output_names.append(_dst.get_name())
524
+ final_offsets.append([sympy.S.Zero] * len(_dst.get_size()))
525
+ reindexers = [None] * len(copy_list)
526
+ return self.store_grouped_gemm_pointwise_nodes(
527
+ dst,
528
+ nodes=copy_list,
529
+ offsets=final_offsets,
530
+ reindexers=reindexers,
531
+ output_names=output_names,
532
+ )
533
+ else:
534
+ assert all(
535
+ _src.get_name() == _dst.get_name() for _src, _dst in zip(src, dst)
536
+ )
537
+ assert all(
538
+ _src.get_layout() == _dst.get_layout()
539
+ for _src, _dst in zip(src, dst)
540
+ )
541
+ return ""
542
+
543
+ def check_bounds(self, expr, size, lower, upper):
544
+ # CppTemplateKernel does not need codegen related operations
545
+ return
546
+
547
+
548
+ class CppTemplateCaller(ir.ChoiceCaller):
549
+ """
550
+ CppTemplateCaller
551
+
552
+ This class represents a caller for CPP template kernels. It is a subclass of ir.ChoiceCaller.
553
+ Attributes:
554
+ name (str): The name of the caller.
555
+ category (str): The category of the caller.
556
+ bmreq (CppBenchmarkRequest): The benchmark request for the caller.
557
+ template_buffer (ir.CppTemplateBuffer): The template buffer for the caller.
558
+ """
559
+
560
+ def __init__(
561
+ self,
562
+ name: str,
563
+ category: str,
564
+ input_nodes: list[ir.Buffer],
565
+ layout: ir.Layout,
566
+ make_kernel_render: Callable[
567
+ [
568
+ ir.CppTemplateBuffer,
569
+ bool,
570
+ Optional[list[ir.IRNode]],
571
+ ],
572
+ str,
573
+ ],
574
+ bmreq: CppBenchmarkRequest,
575
+ template: "CppTemplate", # type: ignore[name-defined] # noqa: F821
576
+ info_kwargs: Optional[
577
+ dict[str, Union[ir.PrimitiveInfoType, list[ir.PrimitiveInfoType]]]
578
+ ] = None,
579
+ ):
580
+ super().__init__(name, input_nodes, layout, description="")
581
+ self.category = category
582
+ self.make_kernel_render = make_kernel_render
583
+ self.bmreq = bmreq
584
+ self.template = template
585
+ self.info_kwargs = info_kwargs
586
+
587
+ def precompile(self) -> None:
588
+ assert self.bmreq is not None
589
+ self.bmreq.precompile()
590
+
591
+ def benchmark(self, *args, out) -> float:
592
+ assert self.bmreq is not None
593
+ if config.profile_bandwidth_with_do_bench_using_profiling:
594
+ algo = self.bmreq.make_run_fn(*args, out=out)
595
+ return do_bench_using_profiling(algo)
596
+ return self.bmreq.benchmark(*args, out=out)
597
+
598
+ def hash_key(self) -> str:
599
+ return "-".join(
600
+ [
601
+ self.category,
602
+ self.bmreq.hash_key,
603
+ ]
604
+ )
605
+
606
+ def info_dict(
607
+ self,
608
+ ) -> dict[str, Union[ir.PrimitiveInfoType, list[ir.PrimitiveInfoType]]]:
609
+ return {"backend": "CPP", "op_type": "unknown"}
610
+
611
+ def output_node(self) -> ir.TensorBox:
612
+ buffer = ir.CppTemplateBuffer(
613
+ layout=self.layout,
614
+ inputs=self.input_nodes,
615
+ make_kernel_render=self.make_kernel_render,
616
+ template=self.template,
617
+ choice=self,
618
+ )
619
+ # Pass KTC annotation to the buffer for encoding
620
+ if "ktc" in self.annotations:
621
+ buffer.annotations["ktc"] = self.annotations["ktc"]
622
+ return ir.TensorBox.create(buffer)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_utils.py ADDED
@@ -0,0 +1,789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import dataclasses
4
+ import functools
5
+ import math
6
+ import sys
7
+ from collections import namedtuple
8
+ from collections.abc import Callable, Sequence
9
+ from typing import Any, Optional
10
+ from unittest.mock import patch
11
+
12
+ import sympy
13
+
14
+ import torch
15
+ from torch._prims_common import is_integer_dtype
16
+ from torch.utils._ordered_set import OrderedSet
17
+ from torch.utils._sympy.printers import CppPrinter as _CppPrinter
18
+ from torch.utils._sympy.symbol import symbol_is_type, SymT
19
+ from torch.utils._sympy.value_ranges import ValueRanges
20
+
21
+ from .. import ir
22
+ from ..dependencies import Dep
23
+ from ..loop_body import LoopBody
24
+ from ..scheduler import BaseSchedulerNode, SchedulerBuffer
25
+ from ..shape_propagation import BlockShapeType
26
+ from ..utils import IndentedBuffer, sympy_index_symbol_with_prefix, sympy_subs
27
+ from ..virtualized import ops, OpsValue, V
28
+ from .common import CSEVariable, Kernel, KernelArgs, OptimizationContext
29
+
30
+
31
+ DTYPE_TO_CPP = {
32
+ torch.float32: "float",
33
+ torch.float64: "double",
34
+ torch.float16: "at::Half",
35
+ torch.int64: "int64_t",
36
+ torch.int32: "int32_t",
37
+ torch.int16: "int16_t",
38
+ torch.int8: "int8_t",
39
+ torch.uint64: "uint64_t",
40
+ torch.uint32: "uint32_t",
41
+ torch.uint16: "uint16_t",
42
+ torch.uint8: "uint8_t",
43
+ torch.bool: "bool",
44
+ torch.bfloat16: "at::BFloat16",
45
+ torch.complex32: "at::complex<at::Half>",
46
+ torch.complex64: "at::complex<float>",
47
+ torch.complex128: "at::complex<double>",
48
+ torch.float8_e4m3fn: "at::Float8_e4m3fn",
49
+ torch.float8_e5m2: "at::Float8_e5m2",
50
+ torch.float8_e4m3fnuz: "at::Float8_e4m3fnuz",
51
+ torch.float8_e5m2fnuz: "at::Float8_e5m2fnuz",
52
+ }
53
+
54
+ DTYPE_TO_ATEN = {
55
+ torch.float32: "at::kFloat",
56
+ torch.float64: "at::kDouble",
57
+ torch.float16: "at::kHalf",
58
+ torch.int64: "at::kLong",
59
+ torch.int32: "at::kInt",
60
+ torch.int16: "at::kShort",
61
+ torch.int8: "at::kChar",
62
+ torch.uint64: "at::kUInt64",
63
+ torch.uint32: "at::kUInt32",
64
+ torch.uint16: "at::kUInt16",
65
+ torch.uint8: "at::kByte",
66
+ torch.uint32: "at::kUInt32",
67
+ torch.uint64: "at::kUInt64",
68
+ torch.bool: "at::kBool",
69
+ torch.bfloat16: "at::kBFloat16",
70
+ torch.complex32: "at::kComplexHalf",
71
+ torch.complex64: "at::kComplexFloat",
72
+ torch.complex128: "at::kComplexDouble",
73
+ torch.float8_e4m3fn: "at::kFloat8_e4m3fn",
74
+ torch.float8_e5m2: "at::kFloat8_e5m2",
75
+ torch.float8_e4m3fnuz: "at::kFloat8_e4m3fnuz",
76
+ torch.float8_e5m2fnuz: "at::kFloat8_e5m2fnuz",
77
+ }
78
+
79
+ DEVICE_TO_ATEN = {
80
+ "meta": "at::kMeta",
81
+ "cpu": "at::kCPU",
82
+ "cuda": "at::kCUDA",
83
+ "xpu": "at::kXPU",
84
+ "mps": "at::kMPS",
85
+ }
86
+
87
+ LAYOUT_TO_ATEN = {
88
+ torch.strided: "at::kStrided",
89
+ torch._mkldnn: "at::kMkldnn", # type: ignore[attr-defined]
90
+ }
91
+
92
+ # matches c10/core/DeviceType.h
93
+ DEVICE_TO_INT = {"cpu": 0, "cuda": 1}
94
+
95
+ _IS_WINDOWS = sys.platform == "win32"
96
+
97
+ INDEX_TYPE = "int64_t"
98
+
99
+ GemmBlocking = namedtuple("GemmBlocking", ["block_m", "block_n", "block_k"])
100
+
101
+
102
+ def get_promote_dtype(args):
103
+ return (
104
+ # pyrefly: ignore [no-matching-overload]
105
+ functools.reduce(
106
+ torch.promote_types, # type: ignore[arg-type]
107
+ [n.dtype for n in args if isinstance(n, CppCSEVariable)],
108
+ )
109
+ if all(n.dtype is not None for n in args if isinstance(n, CppCSEVariable))
110
+ else None # not enough info to calculate the promote dtype
111
+ )
112
+
113
+
114
+ def promote_args(new_args):
115
+ def promote_arg(arg, promote_type):
116
+ if (
117
+ isinstance(arg, CppCSEVariable)
118
+ and arg.dtype
119
+ and promote_type
120
+ and arg.dtype != promote_type
121
+ ):
122
+ arg = ops.to_dtype(arg, promote_type)
123
+ arg = arg.value if isinstance(arg, OpsValue) else arg
124
+ arg.dtype = promote_type
125
+ return arg
126
+
127
+ promote_type = get_promote_dtype(new_args)
128
+ promote_fn = functools.partial(
129
+ promote_arg,
130
+ promote_type=promote_type,
131
+ )
132
+ if (
133
+ all(
134
+ new_arg.dtype is not None
135
+ for new_arg in new_args
136
+ if isinstance(new_arg, CppCSEVariable)
137
+ )
138
+ and promote_type
139
+ ):
140
+ new_args = list(map(promote_fn, new_args))
141
+ return new_args
142
+
143
+
144
+ class CppCSEVariable(CSEVariable):
145
+ def __init__(
146
+ self,
147
+ name,
148
+ bounds: ValueRanges[Any],
149
+ dtype: Optional[torch.dtype] = None,
150
+ shape: BlockShapeType = None,
151
+ ) -> None:
152
+ super().__init__(name, bounds, dtype, shape=shape)
153
+ self.is_vec = False
154
+ self.dependent_itervars = OrderedSet[sympy.Symbol]()
155
+
156
+ def __repr__(self) -> str:
157
+ return (
158
+ f"CppCSEVariable(name: {self.name}, bounds: {self.bounds}, is_vec: {self.is_vec}, dtype: {self.dtype}, "
159
+ f"dependent_itervars: {self.dependent_itervars})"
160
+ )
161
+
162
+ def update_on_args(self, name, args, kwargs):
163
+ if name == "load":
164
+ # args[2] is index
165
+ self._set_dependent_itervars(args[2])
166
+ else:
167
+ # propagate relevant itervars and is_vec from args
168
+ self.dependent_itervars.update(
169
+ *[
170
+ arg.dependent_itervars
171
+ for arg in args
172
+ if isinstance(arg, CppCSEVariable)
173
+ ]
174
+ )
175
+ if name == "index_expr":
176
+ self._set_dependent_itervars(args[0])
177
+ if any(arg.is_vec for arg in args if isinstance(arg, CppCSEVariable)):
178
+ self.is_vec = True
179
+
180
+ def _set_dependent_itervars(self, index: sympy.Expr):
181
+ """
182
+ Set the relevant itervars for this variable based on the `index` expression.
183
+ This includes the itervars directly used in the `index` as well as relevant itervars
184
+ of other cse variables used in the `index`.
185
+ """
186
+ for s in index.free_symbols:
187
+ if s in V.kernel.itervars:
188
+ self.dependent_itervars.add(s) # type: ignore[arg-type]
189
+ elif s.name in V.kernel.cse.varname_map: # type: ignore[attr-defined]
190
+ self.dependent_itervars.update(
191
+ V.kernel.cse.varname_map[s.name].dependent_itervars # type: ignore[attr-defined]
192
+ )
193
+
194
+ def depends_on(self, itervar: sympy.Symbol):
195
+ return itervar in self.dependent_itervars
196
+
197
+
198
+ class CppPrinter(_CppPrinter):
199
+ def doprint(self, expr, *, simplify: bool = True, p=True):
200
+ # TODO: why are people passing strings to the printer here :think:
201
+ if simplify and isinstance(expr, sympy.Expr) and hasattr(V.graph, "sizevars"):
202
+ expr = V.graph.sizevars.simplify(expr)
203
+ return super().doprint(expr)
204
+
205
+ def parenthesize(self, item: sympy.Expr, level: int, strict: bool = False) -> str:
206
+ if isinstance(item, sympy.Mod):
207
+ # use parenthesis to enforce precedence.
208
+ # in sympy 1.13.3, -2*Mod(x,y) becomes -2*x%y, which is wrong.
209
+ # pyrefly: ignore [missing-attribute]
210
+ return f"({self._print(item)})"
211
+ else:
212
+ return super().parenthesize(item, level, strict)
213
+
214
+
215
+ # A function to print, useful for printing sympy symbols.
216
+ cexpr = CppPrinter().doprint
217
+
218
+
219
+ def cexpr_index(index):
220
+ return f"static_cast<{INDEX_TYPE}>({cexpr(index)})"
221
+
222
+
223
+ def value_to_cpp(value, cpp_type):
224
+ if value == float("-inf"):
225
+ return f"-std::numeric_limits<{cpp_type}>::infinity()"
226
+ elif value == float("inf"):
227
+ return f"std::numeric_limits<{cpp_type}>::infinity()"
228
+ elif isinstance(value, bool):
229
+ return f"static_cast<{cpp_type}>({str(value).lower()})"
230
+ elif math.isnan(value):
231
+ return f"std::numeric_limits<{cpp_type}>::quiet_NaN()"
232
+ else:
233
+ return f"static_cast<{cpp_type}>({repr(value)})"
234
+
235
+
236
+ def rewrite_index_for_function(
237
+ localize_buffer_handler: "LocalizeBufferHandler",
238
+ index: sympy.Expr,
239
+ global_buf_name: str,
240
+ ):
241
+ # Local buffer at the inner dimensions
242
+ snode = V.graph.scheduler.name_to_buf[global_buf_name].defining_op
243
+ assert snode is not None
244
+ local_buf = localize_buffer_handler.global_to_local[global_buf_name]
245
+ scheduler_nodes = snode.get_nodes()
246
+ _, (group, reduction_group) = max(
247
+ scheduler_nodes, key=lambda x: int(x.is_reduction())
248
+ ).group
249
+ call_ranges = tuple(group) + tuple(reduction_group)
250
+ indices_to_keep = [
251
+ f"x{len(call_ranges) - (idx + 1)}"
252
+ for idx in range(len(local_buf.get_layout().size))
253
+ ]
254
+ sorted_symbols = sorted(index.free_symbols, key=lambda s: s.name) # type: ignore[attr-defined]
255
+ replacements = {}
256
+ for x in sorted_symbols:
257
+ if x.name.startswith("x") and x.name not in indices_to_keep: # type: ignore[attr-defined]
258
+ # Only keep index used by local buffer
259
+ replacements[x] = sympy.core.numbers.Zero()
260
+ index = sympy_subs(index, replacements) # type: ignore[arg-type]
261
+ return index
262
+
263
+
264
+ def rewrite_index_for_nodes(
265
+ localize_buffer_handler: "LocalizeBufferHandler",
266
+ index: sympy.Expr,
267
+ global_buf_name: str,
268
+ ):
269
+ used_vars = OrderedSet(
270
+ s for s in index.free_symbols if symbol_is_type(s, SymT.INDEX)
271
+ )
272
+ index_vars = []
273
+ local_buf = localize_buffer_handler.global_to_local[global_buf_name]
274
+ for i in range(len(local_buf.get_size())):
275
+ var = sympy_index_symbol_with_prefix(SymT.INDEX, i)
276
+ index_vars.append(var if var in used_vars else 0)
277
+ index = local_buf.get_layout().make_indexer()(index_vars)
278
+ return index
279
+
280
+
281
+ class LocalizeBufferHandler(V.WrapperHandler): # type: ignore[name-defined]
282
+ def __init__(
283
+ self,
284
+ inner,
285
+ global_to_local: dict[str, ir.Buffer],
286
+ rewrite_index: Callable[["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr],
287
+ ) -> None:
288
+ super().__init__(inner)
289
+ self.global_to_local = global_to_local
290
+ self.rewrite_index = rewrite_index
291
+
292
+ def localize(self, name: str, index: sympy.Expr):
293
+ if self.global_to_local and name in self.global_to_local:
294
+ assert self.rewrite_index is not None
295
+ index = self.rewrite_index(self, index, name)
296
+ name = self.global_to_local[name].get_name()
297
+ return name, index
298
+
299
+ def load(self, name: str, index: sympy.Expr):
300
+ return self._inner.load(*self.localize(name, index))
301
+
302
+ def store(self, name, index, value, mode=None):
303
+ local_buffer_name, local_buffer_index = self.localize(name, index)
304
+ res = self._inner.store(local_buffer_name, local_buffer_index, value, mode)
305
+ if (
306
+ self.global_to_local
307
+ and name in self.global_to_local
308
+ and isinstance(V.kernel, Kernel)
309
+ ):
310
+ # Remove name of local buffer from Kernel.store_buffer_names
311
+ # local_buffer_name is added to Kernel.store_buffer_names in Kernel.CSEProxy.store.
312
+ V.kernel.store_buffer_names.discard(local_buffer_name)
313
+ return res
314
+
315
+ def store_reduction(self, name, index, value):
316
+ # pyrefly: ignore [bad-argument-count]
317
+ return self._inner.store_reduction(*self.localize(name, index), value)
318
+
319
+
320
+ class LocalBufferContext:
321
+ """
322
+ This class creates a context that helps to generate code involving Inductor IR with
323
+ function local buffers. These buffers are constructed during the codegen process and
324
+ are used to store intermediate results such as local accumulators. We do not want to
325
+ add them to `V.graph` since they are not global and we do not want to add them as
326
+ function arguments either. So we patch the codegen processes under this scope to support
327
+ these buffers without exposure to the outside world.
328
+ """
329
+
330
+ def __init__(self, kernel_args: KernelArgs) -> None:
331
+ self.kernel_args = kernel_args
332
+ self.exit_stack = contextlib.ExitStack()
333
+ # map local buffer name to local buffer
334
+ self.local_buffers: dict[str, ir.Buffer] = {}
335
+ # map global buffer name to global buffer
336
+ self.global_buffers: dict[str, ir.Buffer] = {}
337
+ # map global buffer name to local buffer
338
+ self.global_to_local: dict[str, ir.Buffer] = {}
339
+ # record the global buffers that are removed by this LocalBufferContext
340
+ self.removed_buffers: OrderedSet[str] = OrderedSet()
341
+
342
+ def __enter__(self):
343
+ self.exit_stack.__enter__()
344
+ original_get_dtype = V.graph.get_dtype
345
+
346
+ def get_dtype(name):
347
+ if name in self.local_buffers:
348
+ return self.local_buffers[name].get_dtype()
349
+ return original_get_dtype(name)
350
+
351
+ self.exit_stack.enter_context(patch.object(V.graph, "get_dtype", get_dtype))
352
+
353
+ original_input = self.kernel_args.input
354
+
355
+ def input(name):
356
+ if name in self.local_buffers:
357
+ return name
358
+ return original_input(name)
359
+
360
+ self.exit_stack.enter_context(patch.object(self.kernel_args, "input", input))
361
+
362
+ original_output = self.kernel_args.output
363
+
364
+ def output(name):
365
+ if name in self.local_buffers:
366
+ return name
367
+ return original_output(name)
368
+
369
+ self.exit_stack.enter_context(patch.object(self.kernel_args, "output", output))
370
+
371
+ # Set current LocalBufferContext into V
372
+ self.exit_stack.enter_context(V.set_local_buffer_context(self))
373
+
374
+ return self
375
+
376
+ def __exit__(self, exc_type, exc_val, exc_tb):
377
+ self.local_buffers.clear()
378
+ self.exit_stack.__exit__(exc_type, exc_val, exc_tb)
379
+
380
+ def add_local_buffer(
381
+ self, local_buffer: ir.Buffer, global_buffers: Optional[list[ir.Buffer]] = None
382
+ ):
383
+ assert local_buffer.get_name() not in self.local_buffers
384
+ self.local_buffers[local_buffer.get_name()] = local_buffer
385
+ if global_buffers:
386
+ for global_buffer in global_buffers:
387
+ global_buffer_name = global_buffer.get_name()
388
+ assert (
389
+ global_buffer_name not in self.global_buffers
390
+ and global_buffer_name not in self.global_to_local
391
+ )
392
+ self.global_buffers[global_buffer_name] = global_buffer
393
+ self.global_to_local[global_buffer_name] = local_buffer
394
+ if global_buffer_name not in V.graph.removed_buffers:
395
+ # Record the global buffers that are removed by this LocalBufferContext
396
+ # since which may need to restore. Refer to issue:
397
+ # https://github.com/pytorch/pytorch/issues/144186
398
+ self.removed_buffers.add(global_buffer_name)
399
+ V.graph.removed_buffers.add(global_buffer_name)
400
+
401
+ def localize_function(
402
+ self,
403
+ fn: Callable[..., Any],
404
+ rewrite_index: Callable[
405
+ ["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr
406
+ ] = rewrite_index_for_function,
407
+ ):
408
+ def inner(*args, **kwargs):
409
+ with V.set_ops_handler(
410
+ LocalizeBufferHandler(
411
+ V.get_ops_handler(),
412
+ global_to_local=self.global_to_local,
413
+ rewrite_index=rewrite_index,
414
+ )
415
+ ):
416
+ return fn(*args, **kwargs)
417
+
418
+ return inner
419
+
420
+ def localize_nodes(
421
+ self,
422
+ nodes: list[ir.IRNode],
423
+ rewrite_index: Callable[
424
+ ["LocalizeBufferHandler", sympy.Expr, str], sympy.Expr
425
+ ] = rewrite_index_for_nodes,
426
+ ) -> list[ir.IRNode]:
427
+ """
428
+ Given `local_buf` and `global_buf` registered in current `LocalBufferContext`
429
+ though the method of `add_local_buffer`, localizes the `global_buf` to `local_buf`
430
+ for the given `nodes` and returns a new list of IR nodes that work on `local_buf`
431
+ instead of `global_buf`, i.e., all the loads and stores are redirected to
432
+ `local_buf`. This helps the fused loops to work on smaller-sized local buffers
433
+ for better data locality.
434
+
435
+ The data access of `local_buf` is assumed to be contiguous with the
436
+ same order as the `global_buf`.
437
+ """
438
+ assert len(nodes) > 0
439
+
440
+ def wrap_inner_fn_for_node(node: ir.IRNode):
441
+ loops = node.data if isinstance(node, ir.ComputedBuffer) else node
442
+ assert isinstance(loops, ir.Loops)
443
+ new_inner_fn = self.localize_function(
444
+ loops.inner_fn,
445
+ rewrite_index,
446
+ )
447
+
448
+ new_loops = dataclasses.replace(loops, inner_fn=new_inner_fn)
449
+ if isinstance(node, ir.ComputedBuffer):
450
+ new_node = ir.ComputedBuffer(
451
+ name=node.get_name(), layout=node.get_layout(), data=new_loops
452
+ )
453
+ else:
454
+ new_node = new_loops # type: ignore[assignment]
455
+
456
+ return new_node
457
+
458
+ return [wrap_inner_fn_for_node(node) for node in nodes]
459
+
460
+
461
+ def unify_mask_base_type(
462
+ buffer: IndentedBuffer,
463
+ vars: tuple[CSEVariable, ...],
464
+ dtype=torch.float,
465
+ ):
466
+ """
467
+ Given list of cse variables,
468
+ Cast each to new mask base dtype and return casted cse variable.
469
+ """
470
+ new_vars = (
471
+ V.kernel.cse.generate(
472
+ buffer,
473
+ f"{V.kernel._get_mask_cast(var, dtype)}",
474
+ )
475
+ for var in vars
476
+ )
477
+ return new_vars
478
+
479
+
480
+ def may_unify_binary_op_mask_type(a, b):
481
+ """
482
+ Given two cse variables, when dtype is bool, unify them to the same mask dtype and return casted cse variable.
483
+ """
484
+ if a.dtype == torch.bool:
485
+ assert b.dtype == torch.bool
486
+ mask_dtype = torch.int32
487
+ return unify_mask_base_type(V.kernel.compute, (a, b), mask_dtype)
488
+ return a, b
489
+
490
+
491
+ def codegen_rand(offset, code, rand_function, dst_dtype=torch.float32):
492
+ assert is_integer_dtype(offset.dtype)
493
+ code.writeline("[&]()")
494
+ with code.indent():
495
+ code.writeline(
496
+ f"{DTYPE_TO_CPP[offset.dtype]} offset[{V.kernel.tiling_factor}];"
497
+ )
498
+ code.writeline(f"{DTYPE_TO_CPP[dst_dtype]} result[{V.kernel.tiling_factor}];")
499
+ code.writeline(f"{offset}.store(offset);")
500
+ code.writeline(
501
+ f"for( {DTYPE_TO_CPP[offset.dtype]} offset_idx = 0; offset_idx < {V.kernel.tiling_factor}; offset_idx++ )"
502
+ )
503
+ with code.indent():
504
+ code.writeline(rand_function)
505
+ num_vectors = V.kernel._get_num_vectors(dtype=dst_dtype)
506
+ if num_vectors == 1:
507
+ code.writeline(
508
+ f"return at::vec::Vectorized<{DTYPE_TO_CPP[dst_dtype]}>::loadu(result);"
509
+ )
510
+ else:
511
+ code.writeline(
512
+ f"return at::vec::VectorizedN<{DTYPE_TO_CPP[dst_dtype]}, {num_vectors}>::loadu(result);"
513
+ )
514
+ code.writeline("()")
515
+ return code
516
+
517
+
518
+ def get_gemm_template_output_and_compute_dtype(input_dtype):
519
+ if input_dtype in [torch.uint8, torch.int8]:
520
+ return (torch.int32, torch.int32)
521
+ else:
522
+ return (torch.float32, torch.float32)
523
+
524
+
525
+ def create_epilogue_with_attr(input_buffer, attr, **kwargs):
526
+ input_loader = input_buffer.make_loader()
527
+ dtype = input_buffer.get_dtype()
528
+ if attr == "relu":
529
+
530
+ def inner_fn(index):
531
+ input = input_loader(index)
532
+ zero = ops.constant(0, dtype)
533
+ return ops.maximum(input, zero)
534
+
535
+ elif attr == "gelu":
536
+ assert "algorithm" in kwargs
537
+ if kwargs["algorithm"] == "none":
538
+
539
+ def inner_fn(index):
540
+ input = input_loader(index)
541
+ if dtype != torch.float:
542
+ input = ops.to_dtype(input, torch.float)
543
+ half = ops.constant(0.5, torch.float)
544
+ one = ops.constant(1.0, torch.float)
545
+ const = ops.constant(0.7071067811865476, torch.float)
546
+ result = input * half * (ops.erf(input * const) + one)
547
+ if dtype != torch.float:
548
+ result = ops.to_dtype(result, dtype)
549
+ return result
550
+
551
+ else:
552
+ assert kwargs["algorithm"] == "tanh"
553
+
554
+ def inner_fn(index):
555
+ input = input_loader(index)
556
+ if dtype != torch.float:
557
+ input = ops.to_dtype(input, torch.float)
558
+ half = ops.constant(0.5, torch.float)
559
+ one = ops.constant(1.0, torch.float)
560
+ const1 = ops.constant(0.7978845608028654, torch.float)
561
+ const2 = ops.constant(0.044715, torch.float)
562
+ result = (
563
+ half
564
+ * input
565
+ * (
566
+ one
567
+ + ops.tanh(const1 * (input + const2 * input * input * input))
568
+ )
569
+ )
570
+ if dtype != torch.float:
571
+ result = ops.to_dtype(result, dtype)
572
+ return result
573
+
574
+ elif attr == "swish":
575
+
576
+ def inner_fn(index):
577
+ input = input_loader(index)
578
+ result = input * ops.sigmoid(input)
579
+ return result
580
+
581
+ elif attr == "sigmoid":
582
+
583
+ def inner_fn(index):
584
+ return ops.sigmoid(input_loader(index))
585
+
586
+ elif attr == "tanh":
587
+
588
+ def inner_fn(index):
589
+ return ops.tanh(input_loader(index))
590
+
591
+ elif attr == "hardswish" or attr == "hardsigmoid":
592
+
593
+ def hardsigmoid_float(input):
594
+ zero = ops.constant(0, torch.float)
595
+ six = ops.constant(6, torch.float)
596
+ three = ops.constant(3, torch.float)
597
+ one_over_six = ops.constant(0.16666666666666666, torch.float)
598
+ max = ops.maximum(input + three, zero)
599
+ min = ops.minimum(max, six)
600
+ return min * one_over_six
601
+
602
+ def inner_fn(index):
603
+ input = input_loader(index)
604
+ if dtype != torch.float:
605
+ input = ops.to_dtype(input, torch.float)
606
+ result = hardsigmoid_float(input)
607
+ if attr == "hardswish":
608
+ result = input * result
609
+ if dtype != torch.float:
610
+ result = ops.to_dtype(result, dtype)
611
+ return result
612
+
613
+ elif attr == "leaky_relu":
614
+ assert "scalars" in kwargs
615
+ assert len(kwargs["scalars"]) == 1
616
+ negative_slope = kwargs["scalars"][0]
617
+
618
+ def inner_fn(index):
619
+ input = input_loader(index)
620
+ if dtype != torch.float:
621
+ input = ops.to_dtype(input, torch.float)
622
+ zero = ops.constant(0, torch.float)
623
+ result = ops.where(
624
+ input > zero, input, input * ops.constant(negative_slope, torch.float)
625
+ )
626
+ if dtype != torch.float:
627
+ result = ops.to_dtype(result, dtype)
628
+ return result
629
+
630
+ elif attr == "hardtanh":
631
+ assert "scalars" in kwargs
632
+ assert len(kwargs["scalars"]) == 2
633
+ min_value = kwargs["scalars"][0]
634
+ max_value = kwargs["scalars"][1]
635
+
636
+ def inner_fn(index):
637
+ input = input_loader(index)
638
+ if dtype != torch.float:
639
+ input = ops.to_dtype(input, torch.float)
640
+ result = ops.minimum(
641
+ ops.maximum(input, ops.constant(min_value, torch.float)),
642
+ ops.constant(max_value, torch.float),
643
+ )
644
+ if dtype != torch.float:
645
+ result = ops.to_dtype(result, dtype)
646
+ return result
647
+
648
+ elif attr in ["add", "sub", "mul"]:
649
+ assert "other" in kwargs
650
+ other = kwargs["other"]
651
+ num_input_dims = len(input_buffer.get_size())
652
+ num_other_dims = len(other.get_size())
653
+ dims_diff = num_input_dims - num_other_dims
654
+ other_loader = other.make_loader()
655
+
656
+ def inner_fn(index):
657
+ op = getattr(ops, attr)
658
+ if dims_diff != 0:
659
+ return op(input_loader(index), other_loader(index[dims_diff:]))
660
+ else:
661
+ return op(input_loader(index), other_loader(index))
662
+
663
+ elif attr == "bias_add":
664
+ assert "other" in kwargs
665
+ assert "beta" in kwargs
666
+ assert "dtype" in kwargs
667
+ beta = kwargs["beta"]
668
+ other = kwargs["other"]
669
+ dtype = kwargs["dtype"]
670
+ bias_loader = other.make_loader()
671
+
672
+ def inner_fn(index):
673
+ bias = bias_loader(index)
674
+ input = input_loader(index)
675
+ if beta != 1:
676
+ result = ops.constant(beta, torch.float) * bias + input
677
+ else:
678
+ result = bias + input
679
+ return result
680
+
681
+ else:
682
+ raise ValueError(f"Unsupported epilogue attribute: {attr}")
683
+ return ir.Pointwise(
684
+ device=input_buffer.get_device(),
685
+ dtype=dtype,
686
+ inner_fn=inner_fn,
687
+ ranges=input_buffer.get_size(),
688
+ )
689
+
690
+
691
+ def _get_loop_body(fn_list):
692
+ if all(isinstance(fn, LoopBody) for fn in fn_list):
693
+ loop_bodies = fn_list
694
+ else:
695
+ if hasattr(fn_list[0], "original_fn"):
696
+ # For the case of local buffer, we wrap the fn with localize_function
697
+ assert all(hasattr(fn, "original_fn") for fn in fn_list)
698
+ assert all(
699
+ isinstance(fn.original_fn.args[0]._body, LoopBody) for fn in fn_list
700
+ )
701
+ loop_bodies = [fn.original_fn.args[0]._body for fn in fn_list]
702
+ else:
703
+ assert all(isinstance(fn, functools.partial) for fn in fn_list)
704
+ assert all(isinstance(fn.args[0]._body, LoopBody) for fn in fn_list)
705
+ loop_bodies = [fn.args[0]._body for fn in fn_list]
706
+ assert loop_bodies is not None
707
+ return loop_bodies
708
+
709
+
710
+ def _get_dtype_from_loopbodies(loop_bodies):
711
+ dtypes = OrderedSet[torch.dtype]()
712
+ for loop_body in loop_bodies:
713
+ graphs = [loop_body.root_block.graph] + [
714
+ body.graph for body in list(loop_body.subblocks.values())
715
+ ]
716
+ for graph in graphs:
717
+ for node in graph.nodes:
718
+ if node.op != "call_method":
719
+ continue
720
+ dtypes.add(node.meta[OptimizationContext.key].dtype)
721
+ return dtypes
722
+
723
+
724
+ def template_fusion_with_epilogues_supported(
725
+ template: BaseSchedulerNode, epilogues: list[BaseSchedulerNode]
726
+ ) -> tuple[bool, bool]:
727
+ def _get_indexes_of_template_buf_read(
728
+ epilogue_node: ir.Operation, template_buf_names: list[str]
729
+ ) -> list[sympy.Expr]:
730
+ return [
731
+ read.index
732
+ for read in epilogue_node.get_reads()
733
+ if read.name in template_buf_names
734
+ ]
735
+
736
+ def _check_supported_and_same_indexes(
737
+ index_of_template_buf_read: Sequence[sympy.Expr],
738
+ epilogue_writes: OrderedSet[Dep],
739
+ ) -> tuple[bool, bool]:
740
+ num_indexes = len(OrderedSet(index_of_template_buf_read))
741
+
742
+ if num_indexes > 1:
743
+ same_index = False
744
+ supported = False # Different read indexes not supported
745
+ elif num_indexes == 0:
746
+ same_index = True
747
+ supported = True # No reads, automatically supported
748
+ elif num_indexes == 1:
749
+ iotbr = index_of_template_buf_read[0]
750
+ same_index = all(write.index == iotbr for write in epilogue_writes)
751
+ # TODO: Add support of fusion when the read of template buffer and the write of epilogue output
752
+ # in the epilogue node don't have the same index and change supported to True
753
+ supported = same_index
754
+ else:
755
+ raise AssertionError("Should not reach here")
756
+
757
+ return supported, same_index
758
+
759
+ def _template_fusion_supported(
760
+ template_outputs: Sequence[SchedulerBuffer], epilogue_nodes: list[ir.Operation]
761
+ ) -> tuple[bool, bool]:
762
+ template_buf_names = [x.get_name() for x in template_outputs]
763
+ indexes_of_template_buf_reads = [
764
+ _get_indexes_of_template_buf_read(epilogue_node, template_buf_names)
765
+ for epilogue_node in epilogue_nodes
766
+ ]
767
+ epilogue_nodes_writes = [
768
+ epilogue_node.get_read_writes().writes for epilogue_node in epilogue_nodes
769
+ ]
770
+
771
+ results = [
772
+ _check_supported_and_same_indexes(reads, writes)
773
+ for reads, writes in zip(
774
+ indexes_of_template_buf_reads, epilogue_nodes_writes
775
+ )
776
+ ]
777
+ supported, same_indexes = zip(*results)
778
+ return all(supported), all(same_indexes)
779
+
780
+ assert template.is_template()
781
+ template_outputs = template.get_outputs()
782
+
783
+ epilogue_nodes = [
784
+ n.node
785
+ for epilogue in epilogues
786
+ for n in epilogue.get_nodes()
787
+ if n.node is not None
788
+ ]
789
+ return _template_fusion_supported(template_outputs, epilogue_nodes)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_cpu_array_ref.py ADDED
@@ -0,0 +1,898 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from collections.abc import Callable, Sequence
3
+ from typing import Any, Optional, Union
4
+
5
+ import sympy
6
+
7
+ import torch
8
+ import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
9
+ import torch._ops
10
+
11
+ from .. import config, ir
12
+ from ..utils import sympy_product
13
+ from ..virtualized import V
14
+ from .cpp_utils import DTYPE_TO_CPP
15
+ from .cpp_wrapper_cpu import CppWrapperCpu
16
+ from .wrapper import (
17
+ BufferLike,
18
+ EnterSubgraphLine,
19
+ ExitSubgraphLine,
20
+ MemoryPlanningLine,
21
+ MemoryPlanningState,
22
+ PythonWrapperCodegen,
23
+ )
24
+
25
+
26
+ BufferName = str
27
+
28
+ # Default thread stack sizes vary by platform:
29
+ # - Linux: 8 MB
30
+ # - macOS: 512 KB
31
+ # - Windows: 1 MB
32
+ # Just pick something comfortably smaller than the smallest for now.
33
+ MAX_STACK_ALLOCATION_SIZE = 1024 * 100
34
+
35
+
36
+ class CppWrapperCpuArrayRef(CppWrapperCpu):
37
+ """
38
+ Generates cpp wrapper for running on CPU and calls cpp kernels
39
+
40
+ This class is forked from CppWrapperCpu, with a difference that tensors may be
41
+ represented as ArrayRef, see torch/csrc/inductor/aoti_runtime/arrayref_tensor.h
42
+ """
43
+
44
+ def __init__(self):
45
+ super().__init__()
46
+ assert self.device == "cpu", "ArrayRefTensor only supported on CPU!"
47
+ self.allow_stack_allocation = config.aot_inductor.allow_stack_allocation
48
+ self.stack_allocated_buffers: dict[BufferName, BufferLike] = {}
49
+
50
+ @staticmethod
51
+ def create(
52
+ is_subgraph: bool,
53
+ subgraph_name: Optional[str],
54
+ parent_wrapper: Optional[PythonWrapperCodegen],
55
+ partition_signatures: Optional[ir.GraphPartitionSignature] = None,
56
+ ):
57
+ # TODO - support subgraph codegen by lifting functions. Check the
58
+ # comment at CppWrapperCpu `codegen_subgraph` function.
59
+ return CppWrapperCpuArrayRef()
60
+
61
+ @staticmethod
62
+ def get_input_cpp_type(input):
63
+ assert config.aot_inductor.use_minimal_arrayref_interface
64
+
65
+ if isinstance(input, sympy.Expr):
66
+ from ..graph import may_get_constant_buffer_dtype
67
+
68
+ dtype = may_get_constant_buffer_dtype(input)
69
+ assert dtype is not None, f"Failed to get the dtype of sympy.Expr: {input}"
70
+ return DTYPE_TO_CPP[dtype]
71
+ return f"ArrayRefTensor<{DTYPE_TO_CPP[input.get_dtype()]}>"
72
+
73
+ @staticmethod
74
+ def get_device_include_path(device: str) -> str:
75
+ assert device == "cpu", "ArrayRef only supported on CPU!"
76
+ if V.graph.aot_mode:
77
+ return "#include <torch/csrc/inductor/aoti_include/array_ref.h>"
78
+ return "#include <torch/csrc/inductor/cpp_wrapper/array_ref.h>"
79
+
80
+ def codegen_input_numel_asserts(self):
81
+ for name, buf in V.graph.graph_inputs.items():
82
+ if isinstance(buf, sympy.Expr):
83
+ continue
84
+
85
+ # comparing strides for 0 size tensor is tricky. Ignore them for now.
86
+ if sympy_product(buf.get_size()) == 0:
87
+ continue
88
+ numel = buf.get_numel()
89
+ self.prefix.writeline(f"assert_numel({name}, {numel});")
90
+
91
+ def generate_extern_kernel_alloc(self, *args, **kwargs):
92
+ # Disable stack allocation for extern kernels.
93
+ self.allow_stack_allocation = False
94
+ super().generate_extern_kernel_alloc(*args, **kwargs)
95
+
96
+ def generate_extern_kernel_out(self, *args, **kwargs):
97
+ # Disable stack allocation for extern kernels.
98
+ self.allow_stack_allocation = False
99
+ super().generate_extern_kernel_out(*args, **kwargs)
100
+
101
+ def generate_fallback_kernel(self, node: ir.FallbackKernel) -> None:
102
+ # Disable stack allocation for extern kernels.
103
+ self.allow_stack_allocation = False
104
+ super().generate_fallback_kernel(node)
105
+
106
+ def _generate_kernel_call_helper(
107
+ self,
108
+ kernel_name: str,
109
+ call_args,
110
+ *,
111
+ device=None,
112
+ triton=True,
113
+ arg_types=None,
114
+ raw_keys=None,
115
+ raw_args=None,
116
+ triton_meta=None,
117
+ inductor_meta=None,
118
+ graph_name="",
119
+ original_fxnode_name=None,
120
+ ):
121
+ """
122
+ Generates kernel call code.
123
+
124
+ triton: Defines whether the GPU backend uses Triton for codegen.
125
+ Otherwise it uses the CUDA language for codegen.
126
+ Only valid when cuda == True.
127
+ """
128
+ assert not triton, (
129
+ "CppWrapperCpuArrayRef.generate_kernel_call does not support GPU"
130
+ )
131
+ assert arg_types is not None and len(call_args) == len(arg_types), (
132
+ "Mismatch call_args and arg_types in generate_kernel_call"
133
+ )
134
+ new_args = []
135
+ for idx, arg in enumerate(call_args):
136
+ if "*" in arg_types[idx]:
137
+ var_name = f"var_{next(self.arg_var_id)}"
138
+ self.writeline(f"auto* {var_name} = get_data_ptr_wrapper({arg});")
139
+ new_args.append(f"({arg_types[idx]})({var_name})")
140
+ else:
141
+ # arg is a scalar
142
+ new_args.append(arg)
143
+ # debug printer related logic for cpp kernel type.
144
+ debug_printer_manager = V.graph.wrapper_code.debug_printer
145
+ debug_printer_manager.set_printer_args(
146
+ call_args,
147
+ kernel_name,
148
+ None,
149
+ None,
150
+ "cpp",
151
+ )
152
+ with debug_printer_manager:
153
+ self.writeline(self.wrap_kernel_call(kernel_name, new_args))
154
+
155
+ def write_wrapper_decl(self):
156
+ inputs_len = len(V.graph.graph_inputs.keys())
157
+ if V.graph.aot_mode:
158
+ if (
159
+ config.aot_inductor.use_minimal_arrayref_interface
160
+ and not V.graph.is_const_graph
161
+ ):
162
+ input_cpp_types = ", ".join(
163
+ f"{CppWrapperCpuArrayRef.get_input_cpp_type(x)}"
164
+ for x in V.graph.graph_inputs.values()
165
+ )
166
+ output_arrayref_types = ", ".join(
167
+ f"ArrayRefTensor<{DTYPE_TO_CPP[x.get_dtype()]}>"
168
+ for x in V.graph.graph_outputs
169
+ )
170
+
171
+ self.prefix.splice(
172
+ f"""
173
+ using AOTInductorModelInputs = std::tuple<{input_cpp_types}>;
174
+ using AOTInductorModelOutputs = std::tuple<{output_arrayref_types}>;
175
+ """
176
+ )
177
+
178
+ if V.graph.const_module:
179
+ self.header.splice(V.graph.const_module.wrapper_code.header)
180
+
181
+ assert V.graph.const_wrapper_code is not None
182
+ self.prefix.splice(V.graph.const_wrapper_code)
183
+
184
+ assert V.graph.const_kernel_code is not None
185
+ self.kernel_declarations.splice(V.graph.const_kernel_code)
186
+
187
+ if V.graph.is_const_graph:
188
+ self.prefix.splice(
189
+ """
190
+ void AOTInductorModel::_const_run_impl(
191
+ std::vector<AtenTensorHandle>& output_handles,
192
+ DeviceStreamType stream,
193
+ AOTIProxyExecutorHandle proxy_executor
194
+ ) {
195
+ """
196
+ )
197
+ else:
198
+ if not config.aot_inductor.use_runtime_constant_folding:
199
+ # If we do not split the constant graph, we'll just create
200
+ # an empty implementation when wrapping the main module.
201
+ self.prefix.splice(
202
+ """
203
+ void AOTInductorModel::_const_run_impl(
204
+ std::vector<AtenTensorHandle>& output_handles,
205
+ DeviceStreamType stream,
206
+ AOTIProxyExecutorHandle proxy_executor
207
+ ) {}
208
+
209
+ """
210
+ )
211
+
212
+ run_impl_proto = """
213
+ void AOTInductorModel::run_impl(
214
+ AtenTensorHandle*
215
+ input_handles, // array of input AtenTensorHandle; handles
216
+ // are stolen; the array itself is borrowed
217
+ AtenTensorHandle*
218
+ output_handles, // array for writing output AtenTensorHandle; handles
219
+ // will be stolen by the caller; the array itself is
220
+ // borrowed
221
+ DeviceStreamType stream,
222
+ AOTIProxyExecutorHandle proxy_executor
223
+ ) {
224
+ """
225
+
226
+ self.generate_input_output_runtime_checks()
227
+ run_impl_proto += """
228
+ __check_inputs_outputs(input_handles, output_handles);
229
+ """
230
+
231
+ if config.aot_inductor.use_minimal_arrayref_interface:
232
+ self.prefix.splice(
233
+ """
234
+ template <>
235
+ AOTInductorModelOutputs AOTInductorModel::run_impl_minimal_arrayref_interface<
236
+ AOTInductorModelInputs, AOTInductorModelOutputs>(
237
+ const AOTInductorModelInputs& inputs,
238
+ DeviceStreamType stream,
239
+ AOTIProxyExecutorHandle proxy_executor
240
+ ) {
241
+ """
242
+ )
243
+ self.suffix.splice(run_impl_proto)
244
+ self.suffix.splice(
245
+ """
246
+ AOTInductorModelInputs inputs;
247
+ convert_handles_to_inputs(input_handles, inputs);
248
+ auto outputs = run_impl_minimal_arrayref_interface<AOTInductorModelInputs, AOTInductorModelOutputs>(
249
+ inputs, stream, proxy_executor);
250
+ // NOTE: outputs is full of ArrayRef to thread_local storage. If in the future we need this
251
+ // interface to perform well for a DSO using the minimal arrayref interface, all we need
252
+ // to do is provide ThreadLocalCachedTensor for each one!
253
+ convert_outputs_to_handles(outputs, output_handles);
254
+ }
255
+ """
256
+ )
257
+
258
+ self.suffix.splice(
259
+ """
260
+ extern "C" AOTIRuntimeError AOTInductorModelRunMinimalArrayrefInterface(
261
+ AOTInductorModelHandle model_handle,
262
+ const AOTInductorModelInputs& inputs,
263
+ AOTInductorModelOutputs& outputs) {
264
+ auto model = reinterpret_cast<torch::aot_inductor::AOTInductorModel*>(model_handle);
265
+ CONVERT_EXCEPTION_TO_ERROR_CODE({
266
+ outputs = model->run_impl_minimal_arrayref_interface<AOTInductorModelInputs, AOTInductorModelOutputs>(
267
+ inputs,
268
+ (torch::aot_inductor::DeviceStreamType)nullptr,
269
+ nullptr);
270
+ })
271
+ }
272
+ """
273
+ )
274
+ else:
275
+ self.prefix.splice(run_impl_proto)
276
+ else:
277
+ # cpp entry function for JIT with cpp wrapper
278
+ self.prefix.splice(
279
+ """
280
+ void inductor_entry_impl(
281
+ AtenTensorHandle*
282
+ input_handles, // array of input AtenTensorHandle; handles
283
+ // are stolen; the array itself is borrowed
284
+ AtenTensorHandle*
285
+ output_handles // array for writing output AtenTensorHandle; handles
286
+ // will be stolen by the caller; the array itself is
287
+ // borrowed)
288
+ ) {
289
+ """
290
+ )
291
+ with self.prefix.indent():
292
+ # assign inputs and outputs in both cases so the later codegen can be simplified
293
+ if not config.aot_inductor.use_minimal_arrayref_interface:
294
+ if not V.graph.is_const_graph:
295
+ if V.graph.aot_mode:
296
+ num_args = len(V.graph.graph_inputs)
297
+ else:
298
+ # Weights are promoted in the JIT mode
299
+ num_args = len(V.graph.graph_inputs) + len(V.graph.constants)
300
+ # release GIL to support multiple instances inference (in different threads of the same process)
301
+ self.prefix.splice("py::gil_scoped_release_simple release;")
302
+
303
+ self.prefix.splice(
304
+ f"""
305
+ auto inputs = steal_from_raw_handles_to_raii_handles(input_handles, {num_args});
306
+ """
307
+ )
308
+
309
+ if inputs_len != 0:
310
+ for idx, input_key in enumerate(V.graph.graph_inputs.keys()):
311
+ if config.aot_inductor.use_minimal_arrayref_interface:
312
+ self.prefix.writeline(
313
+ f"auto {input_key} = std::get<{idx}>(inputs);"
314
+ )
315
+ continue
316
+ # unwrap input tensor back to scalar
317
+ if isinstance(V.graph.graph_inputs[input_key], sympy.Expr):
318
+ from ..graph import may_get_constant_buffer_dtype
319
+
320
+ dtype = may_get_constant_buffer_dtype(
321
+ V.graph.graph_inputs[input_key] # type: ignore[arg-type]
322
+ )
323
+ assert dtype is not None, (
324
+ "Fails to get the dtype of the sympy.Expr"
325
+ )
326
+ self.codegen_tensor_item(
327
+ dtype, f"inputs[{idx}]", input_key, self.prefix
328
+ )
329
+ else:
330
+ self.prefix.writeline(
331
+ f"auto {input_key} = std::move(inputs[{idx}]);"
332
+ )
333
+
334
+ assert all(
335
+ isinstance(v, torch.Tensor) for v in list(V.graph.constants.values())
336
+ ), "Expect all constants to be Tensor"
337
+ for idx, constants_key in enumerate(V.graph.constants.keys()):
338
+ if V.graph.aot_mode:
339
+ # Weights are stored in constants_ and owned by RAIIAtenTensorHandle there.
340
+ # Don't call std::move here because it will cause constants_ to lose the ownership.
341
+ self.prefix.writeline(
342
+ f"""auto {constants_key} = constants_->at({idx});"""
343
+ )
344
+ else:
345
+ # Append constants as inputs to the graph
346
+ constants_idx = inputs_len + idx
347
+ self.prefix.writeline(
348
+ f"auto {constants_key} = std::move(inputs[{constants_idx}]);"
349
+ )
350
+
351
+ self.codegen_inputs()
352
+
353
+ if V.graph.aot_mode:
354
+ if not V.graph.is_const_graph:
355
+ if config.aot_inductor.use_minimal_arrayref_interface:
356
+ # TODO: input shape checking for regular tensor interface as well?
357
+ self.codegen_input_numel_asserts()
358
+ else:
359
+ self.prefix.writeline("inputs.clear();")
360
+ self.prefix.writeline(
361
+ "[[maybe_unused]] auto& kernels = static_cast<AOTInductorModelKernels&>(*this->kernels_.get());"
362
+ )
363
+
364
+ def generate_return(self, output_refs: list[str]):
365
+ cst_names = V.graph.constants.keys()
366
+ arr_iface = (
367
+ not V.graph.is_const_graph
368
+ and config.aot_inductor.use_minimal_arrayref_interface
369
+ ) # For brevity.
370
+
371
+ def use_thread_local_cached_output_tensor(idx, output):
372
+ cached_output_name = f"cached_output_{next(self.cached_output_id)}"
373
+ cache_type = "Array" if arr_iface else "Tensor"
374
+ self.wrapper_call.writeline(
375
+ f"thread_local ThreadLocalCachedOutput{cache_type}<std::decay_t<decltype({output})>> "
376
+ f"{cached_output_name}({output});"
377
+ )
378
+ if arr_iface:
379
+ self.wrapper_call.writeline(
380
+ f"{cached_output_name}.copy_data_from({output});"
381
+ )
382
+ output_entry = f"std::get<{idx}>(output_arrayref_tensors)"
383
+ element_type = f"std::decay_t<decltype({output_entry}.data()[0])>"
384
+ self.wrapper_call.writeline(
385
+ f"{output_entry} = {cached_output_name}.arrayref_tensor<{element_type}>();"
386
+ )
387
+ else:
388
+ self.wrapper_call.writeline(
389
+ f"{cached_output_name}.copy_data_from({output});"
390
+ )
391
+ self.wrapper_call.writeline(
392
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_uninitialized_tensor(&output_handles[{idx}]));"
393
+ )
394
+ self.wrapper_call.writeline(
395
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_assign_tensors({cached_output_name}.tensor(), "
396
+ f"output_handles[{idx}]));"
397
+ )
398
+
399
+ if arr_iface:
400
+ self.wrapper_call.writeline(
401
+ "AOTInductorModelOutputs output_arrayref_tensors;"
402
+ )
403
+
404
+ output2idx: dict[str, int] = {}
405
+ for idx, output in enumerate(output_refs):
406
+ if output == "nullptr":
407
+ continue
408
+
409
+ is_constant_buffer = output in cst_names
410
+ output_buffer = V.graph.graph_outputs[idx]
411
+ if isinstance(output_buffer, ir.BaseView):
412
+ output_storage = output_buffer.unwrap_view()
413
+ assert isinstance(output_storage, (ir.BaseView, ir.MutableBox))
414
+ if isinstance(output_storage.data, ir.ConstantBuffer):
415
+ is_constant_buffer = True
416
+
417
+ if isinstance(output_buffer, ir.ShapeAsConstantBuffer):
418
+ # Need to wrap scalar into tensor as the main function returns a vector of tensors
419
+ output_tensor = self.codegen_scalar_to_tensor(output)
420
+ self.wrapper_call.writeline(
421
+ f"output_handles[{idx}] = {output_tensor}.release();"
422
+ )
423
+ continue
424
+
425
+ output_is_tensor_handle_expr = (
426
+ f"std::is_same_v<std::decay_t<decltype({output})>,"
427
+ "RAIIAtenTensorHandle> || "
428
+ f"std::is_same_v<std::decay_t<decltype({output})>,"
429
+ "AtenTensorHandle> || "
430
+ f"std::is_same_v<std::decay_t<decltype({output})>,"
431
+ "ConstantHandle>"
432
+ )
433
+ self.wrapper_call.writeline(
434
+ f"if constexpr ({output_is_tensor_handle_expr}) {{"
435
+ )
436
+ with self.wrapper_call.indent():
437
+ if arr_iface:
438
+ cached_output_name = f"cached_output_{next(self.cached_output_id)}"
439
+ self.wrapper_call.writeline(
440
+ f"thread_local RAIIAtenTensorHandle {cached_output_name};"
441
+ )
442
+ if is_constant_buffer:
443
+ # NOTE(return_constant): In some rare cases where we return
444
+ # a constant, we have to return a copy of this constant,
445
+ # because (1) constants are not owned by the Model instance
446
+ # (2) constants remain the same cross inference runs,
447
+ # assuming they are not updated at runtime Basically, we
448
+ # cannot release or transfer the ownership of any original
449
+ # constant to the user.
450
+ self.wrapper_call.writeline(
451
+ f"AtenTensorHandle {cached_output_name}_tmp;"
452
+ )
453
+ self.wrapper_call.writeline(
454
+ f"aoti_torch_clone({output}, &{cached_output_name}_tmp);"
455
+ )
456
+ self.wrapper_call.writeline(
457
+ f"{cached_output_name} = {cached_output_name}_tmp;"
458
+ )
459
+ else:
460
+ self.wrapper_call.writeline(
461
+ f"{cached_output_name} = {output}.release();"
462
+ )
463
+ self.wrapper_call.writeline(
464
+ f"convert_handle_to_arrayref_tensor({cached_output_name}, "
465
+ f"std::get<{idx}>(output_arrayref_tensors));"
466
+ )
467
+ else:
468
+ if is_constant_buffer:
469
+ # See NOTE(return_constant) above.
470
+ self.wrapper_call.writeline(
471
+ f"aoti_torch_clone({output}, &output_handles[{idx}]);"
472
+ )
473
+ else:
474
+ if output in output2idx:
475
+ src_idx = output2idx[output]
476
+ self.wrapper_call.writeline(
477
+ f"output_handles[{idx}] = output_handles[{src_idx}];"
478
+ )
479
+ else:
480
+ self.wrapper_call.writeline(
481
+ f"output_handles[{idx}] = {output}.release();"
482
+ )
483
+ self.wrapper_call.writeline("} else {")
484
+ with self.wrapper_call.indent():
485
+ use_thread_local_cached_output_tensor(idx, output)
486
+ self.wrapper_call.writeline("}")
487
+
488
+ if output not in output2idx:
489
+ output2idx[output] = idx
490
+ if arr_iface:
491
+ self.wrapper_call.writeline("return output_arrayref_tensors;")
492
+
493
+ def memory_plan(self):
494
+ from .memory_planning import MemoryPlanner
495
+
496
+ self.lines = MemoryPlanner(self).plan(self.lines)
497
+ # TODO: integrate memory planning & stack allocation?
498
+ self.allow_stack_allocation = False
499
+
500
+ def memory_plan_reuse(self):
501
+ out_names = V.graph.get_output_names()
502
+
503
+ while (
504
+ self.lines
505
+ and isinstance(self.lines[-1], MemoryPlanningLine)
506
+ # TODO: this seems legit, NullLine has no node
507
+ and self.lines[-1].node.name not in out_names # type: ignore[attr-defined]
508
+ ):
509
+ # these lines will be pointless
510
+ self.lines.pop()
511
+
512
+ # codegen allocations in two passes
513
+ planning_states = [MemoryPlanningState()]
514
+ past_planning_states = []
515
+ for i in range(len(self.lines)):
516
+ line = self.lines[i]
517
+ if isinstance(line, MemoryPlanningLine):
518
+ self.lines[i] = line.plan(planning_states[-1])
519
+ elif isinstance(line, EnterSubgraphLine):
520
+ planning_states.append(MemoryPlanningState())
521
+ elif isinstance(line, ExitSubgraphLine):
522
+ past_planning_states.append(planning_states.pop())
523
+ past_planning_states.append(planning_states.pop())
524
+ assert len(planning_states) == 0
525
+
526
+ # conservatively use the sum of all allocated buffer sizes
527
+ # in potentially nested scopes as the total allocated size
528
+ total_allocated_buffer_size = sum(
529
+ s.total_allocated_buffer_size for s in past_planning_states
530
+ )
531
+
532
+ self.allow_stack_allocation = (
533
+ self.allow_stack_allocation is not False
534
+ and config.aot_inductor.allow_stack_allocation
535
+ and total_allocated_buffer_size <= MAX_STACK_ALLOCATION_SIZE
536
+ )
537
+
538
+ def can_stack_allocate_buffer(self, buffer):
539
+ return (
540
+ self.allow_stack_allocation
541
+ and buffer.get_device().type == "cpu"
542
+ and self.can_prove_buffer_has_static_shape(buffer)
543
+ and ir.is_contiguous_strides_for_shape(
544
+ buffer.get_stride(), buffer.get_size()
545
+ )
546
+ )
547
+
548
+ def make_buffer_free(self, buffer):
549
+ return (
550
+ ""
551
+ if isinstance(buffer.get_output_spec(), ir.MultiOutputLayout)
552
+ or (V.graph.aot_mode and buffer.get_name() in self.stack_allocated_buffers)
553
+ or (
554
+ config.aot_inductor.use_minimal_arrayref_interface
555
+ and V.graph.aot_mode
556
+ and buffer.get_name() in V.graph.graph_inputs
557
+ )
558
+ else f"{buffer.get_name()}.reset();"
559
+ )
560
+
561
+ def make_buffer_allocation(self, buffer):
562
+ return self.make_allocation(
563
+ buffer.get_name(),
564
+ buffer.get_device(),
565
+ buffer.get_dtype(),
566
+ buffer.get_size(),
567
+ buffer.get_stride(),
568
+ buffer if self.can_stack_allocate_buffer(buffer) else None,
569
+ buffer.get_is_pinned(),
570
+ )
571
+
572
+ def make_allocation(
573
+ self,
574
+ name,
575
+ device,
576
+ dtype,
577
+ shape,
578
+ stride,
579
+ buffer_if_can_stack_allocate=None,
580
+ is_pinned=False,
581
+ ):
582
+ orig_stride = stride
583
+ device_str = self.codegen_device(device)
584
+ dtype_code = self.codegen_dtype(dtype)
585
+ size = self.codegen_shape_tuple(shape)
586
+ stride = self.codegen_shape_tuple(orig_stride)
587
+ size_array_var = self.codegen_int_array_var(
588
+ size,
589
+ self.wrapper_call.writeline,
590
+ known_statically=self.is_statically_known_list_of_ints(shape),
591
+ graph=self.get_codegened_graph(),
592
+ )
593
+ stride_array_var = self.codegen_int_array_var(
594
+ stride,
595
+ self.wrapper_call.writeline,
596
+ known_statically=self.is_statically_known_list_of_ints(orig_stride),
597
+ graph=self.get_codegened_graph(),
598
+ )
599
+ device_type, device_id = device_str.split(",")
600
+ device_idx = "this->device_idx_" if V.graph.aot_mode else device_id
601
+ if buffer_if_can_stack_allocate is not None:
602
+ self.stack_allocated_buffers[name] = buffer_if_can_stack_allocate
603
+ cpp_type = DTYPE_TO_CPP[dtype]
604
+ numel = buffer_if_can_stack_allocate.get_numel()
605
+ # Note: we don't zero storage because empty_strided doesn't zero either.
606
+ self.wrapper_call.writeline(f"{cpp_type} {name}_storage[{numel}];")
607
+ args = [
608
+ f"{name}_storage",
609
+ size_array_var,
610
+ stride_array_var,
611
+ device_type,
612
+ device_idx,
613
+ ]
614
+ return f"ArrayRefTensor<{cpp_type}> {name}({', '.join(args)});"
615
+
616
+ args = [
617
+ str(len(shape)),
618
+ size_array_var,
619
+ stride_array_var,
620
+ dtype_code,
621
+ device_type,
622
+ device_idx,
623
+ f"&{name}_handle",
624
+ ]
625
+
626
+ self.wrapper_call.writeline(f"AtenTensorHandle {name}_handle;")
627
+ pinned_str = "_pinned" if is_pinned else ""
628
+ self.wrapper_call.writeline(
629
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_empty_strided{pinned_str}({', '.join(args)}));"
630
+ )
631
+
632
+ return f"RAIIAtenTensorHandle {name}({name}_handle);"
633
+
634
+ def make_buffer_reuse(self, old: BufferLike, new: BufferLike, delete_old: bool):
635
+ assert old.get_dtype() == new.get_dtype()
636
+ old_name = old.get_name()
637
+ new_name = new.get_name()
638
+ del_line = ";"
639
+ if old_name not in V.graph.get_output_names() and delete_old:
640
+ del_line = f"; {self.make_buffer_free(old)}"
641
+
642
+ if old.get_size() == new.get_size() and old.get_stride() == new.get_stride():
643
+ if old_name in self.stack_allocated_buffers:
644
+ self.stack_allocated_buffers[new_name] = new
645
+ return self.codegen_exact_buffer_reuse(old_name, new_name, del_line)
646
+
647
+ reinterpret_view = self.codegen_reinterpret_view(
648
+ old, new.get_size(), new.get_stride(), 0, self.wrapper_call.writeline
649
+ )
650
+ if reinterpret_view in self.stack_allocated_buffers:
651
+ self.stack_allocated_buffers[new_name] = new
652
+ # The only way to get into this case is via an exact buffer reuse, since all
653
+ # other options result in a new tensor handle.
654
+ return self.codegen_exact_buffer_reuse(old_name, new_name, del_line)
655
+ return f"{self.declare}{new_name} = {reinterpret_view}{del_line} // reuse"
656
+
657
+ def _assert_safe_to_use_borrow_arrayref_tensor_as_tensor(self):
658
+ # Borrowing arguments to shim functions is only safe because we know
659
+ # that the arguments can't be stack-allocated. Otherwise, to be sure
660
+ # we can't return a dangling pointer, we need to either 1) be
661
+ # certain that the shim function cannot return an alias of a
662
+ # borrowed argument, or 2) be certain that the returned Tensor from
663
+ # the shim function cannot escape.
664
+ assert self.is_safe_to_use_borrow_arrayref_tensor_as_tensor(), (
665
+ "borrowing arguments to shim functions is unsafe with "
666
+ "stack allocation on! (see comment above this assertion)"
667
+ )
668
+
669
+ def is_safe_to_use_borrow_arrayref_tensor_as_tensor(self):
670
+ return not self.allow_stack_allocation and not self.stack_allocated_buffers
671
+
672
+ def generate_c_shim_extern_kernel_call(
673
+ self, kernel: str, args: list[str], device: str, **_
674
+ ) -> None:
675
+ # In the abi_compatible mode, we call fallback aten ops through a C shim layer
676
+ # Setting self.allow_stack_allocation to False because the exchange between
677
+ # ArrayRefTensor and at::Tensor is still fragile.
678
+ self.allow_stack_allocation = False
679
+
680
+ wrapped_args = []
681
+ for arg in args:
682
+ # We only really *need* borrow_arrayref_tensor_as_tensor for
683
+ # ArrayRefTensors. The code flowing into here uses `0` for nullptr, which
684
+ # borrow_arrayref_tensor_as_tensor would blindly coerce to int, so just
685
+ # avoid wrapping integers. Name matching is to find tensor is hacky, but
686
+ # fixing all the ArrayRefTensor issues is not a priority for now.
687
+ if isinstance(arg, str) and arg.startswith(
688
+ ("buf", "arg", "wrap_with_raii_handle_if_needed")
689
+ ):
690
+ self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor()
691
+ arg = f"borrow_arrayref_tensor_as_tensor({arg})"
692
+ wrapped_args.append(arg)
693
+
694
+ super().generate_c_shim_extern_kernel_call(
695
+ kernel, wrapped_args, device, debug_args=args
696
+ )
697
+
698
+ def generate_scatter_fallback(self, node: ir.ScatterFallback):
699
+ # No stack allocation when there is a fallback op
700
+ self.allow_stack_allocation = False
701
+ super().generate_scatter_fallback(node)
702
+
703
+ def _generate_scatter_fallback(
704
+ self,
705
+ output,
706
+ inputs,
707
+ cpp_kernel_name,
708
+ python_kernel_name,
709
+ src_is_tensor,
710
+ reduce,
711
+ kwargs,
712
+ device,
713
+ ):
714
+ reduce = self._get_scatter_reduce_enum(reduce)
715
+
716
+ # call the ABI shim function instead of the ATen one
717
+ self.add_device_include(device)
718
+ cpp_kernel_name = self.get_c_shim_func_name(cpp_kernel_name, device)
719
+
720
+ # TODO: consider remove "_out" and add missing inplace variants to fallback_ops.py
721
+ cpp_kernel_name = cpp_kernel_name.replace("__", "_") + "_out"
722
+ self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor()
723
+ inputs_wrapped = [
724
+ (f"borrow_arrayref_tensor_as_tensor({x})" if isinstance(x, str) else str(x))
725
+ for x in inputs
726
+ ]
727
+ line = f"{cpp_kernel_name}(borrow_arrayref_tensor_as_tensor({output}), {','.join(inputs_wrapped)}"
728
+
729
+ if python_kernel_name.startswith("aten.scatter_reduce"):
730
+ line += f", {','.join(kwargs)}"
731
+ else:
732
+ if src_is_tensor:
733
+ if reduce:
734
+ line += f", {V.graph.wrapper_code.val_to_arg_str(reduce)}"
735
+ else:
736
+ assert reduce is None, (
737
+ "Expect reduce to be None for aten.scatter_ with scalar src"
738
+ )
739
+ line += ");"
740
+ self.writeline(line)
741
+
742
+ def generate_index_put_fallback(self, node: ir.IndexPutFallback) -> None:
743
+ # No stack allocation when there is a fallback op
744
+ self.allow_stack_allocation = False
745
+ super().generate_index_put_fallback(node)
746
+
747
+ def _generate_index_put_fallback(self, kernel, x, indices, values, accumulate):
748
+ self._assert_safe_to_use_borrow_arrayref_tensor_as_tensor()
749
+ # TODO: update aoti_torch_index_put_out in ir.py to use autogen out version
750
+ # See the comment in codegen_reinterpret_view about why having something like
751
+ # RAIIAtenTensorHandle(tmp_tensor_handle_2) in a tmp array can cause the corresponding
752
+ # tensor prematurely deallocated, thus the temporary array trick here.
753
+ indices_str = self._generate_temporary_array_pointer(
754
+ "AtenTensorHandle",
755
+ [f"borrow_arrayref_tensor_as_tensor({i})" for i in indices],
756
+ )
757
+ args = [
758
+ f"borrow_arrayref_tensor_as_tensor({x})",
759
+ indices_str,
760
+ str(len(indices)),
761
+ f"borrow_arrayref_tensor_as_tensor({values})",
762
+ accumulate,
763
+ ]
764
+ args.insert(
765
+ 0, f"borrow_arrayref_tensor_as_tensor({x})"
766
+ ) # set x as the output tensor, this fallback mutates x.
767
+ self.writeline(self.wrap_kernel_call(kernel, args))
768
+
769
+ def generate_fallback_kernel_with_runtime_lookup(
770
+ self,
771
+ buf_name: str,
772
+ python_kernel_name: str,
773
+ get_args: Callable[[], Sequence[str]],
774
+ op_overload: Union[torch._ops.OpOverload, torch._ops.HigherOrderOperator],
775
+ raw_args: Sequence[Any],
776
+ outputs: Sequence[ir.Buffer],
777
+ ) -> None:
778
+ # No stack allocation when there is a fallback op
779
+ self.allow_stack_allocation = False
780
+ super().generate_fallback_kernel_with_runtime_lookup(
781
+ buf_name, python_kernel_name, get_args, op_overload, raw_args, outputs
782
+ )
783
+
784
+ def codegen_device_copy(self, src, dst, non_blocking: Union[bool, str]):
785
+ # aoti_torch_tensor_copy_ takes AtenTensorHandle as input,
786
+ # while stack-allocation results in ArrayRefTensor
787
+ # so disable stack allocation here
788
+ self.allow_stack_allocation = False
789
+ self.writeline(
790
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_copy_(expensive_copy_to_tensor_if_needed({dst}), {src}, {non_blocking}));"
791
+ )
792
+
793
+ def codegen_reinterpret_view(
794
+ self,
795
+ data,
796
+ size,
797
+ stride,
798
+ offset,
799
+ writeline: Callable[..., None],
800
+ dtype=None,
801
+ ) -> str:
802
+ """Returns a newly-created, temporary RAII tensor handle containing the
803
+ reinterpreted tensor data. Callers of this function are responsible for saving
804
+ the handle if persistent access is needed."""
805
+ dim = str(len(size))
806
+
807
+ def create_reinterpret_call() -> str:
808
+ args = [
809
+ f"{data.get_name()}",
810
+ dim,
811
+ self.codegen_int_array_var(
812
+ self.codegen_shape_tuple(size),
813
+ writeline,
814
+ known_statically=self.is_statically_known_list_of_ints(size),
815
+ graph=self.get_codegened_graph(),
816
+ ),
817
+ self.codegen_int_array_var(
818
+ self.codegen_shape_tuple(stride),
819
+ writeline,
820
+ known_statically=self.is_statically_known_list_of_ints(stride),
821
+ graph=self.get_codegened_graph(),
822
+ ),
823
+ offset,
824
+ ]
825
+ return f"wrap_with_raii_handle_if_needed(reinterpret_tensor_wrapper({', '.join(args)}))"
826
+
827
+ def create_new_tensor_handle() -> tuple[str, list[str]]:
828
+ # Calling reset() on ArrayRefTensor does nothing, since the array is
829
+ # const-allocated on the stack. Thus, it's safe to return a reference to
830
+ # the original array.
831
+ if (name := data.get_name()) in self.stack_allocated_buffers:
832
+ return name, []
833
+
834
+ tmp_AtenTensorHandle = f"tmp_{name}_{next(self.tmp_tensor_id)}"
835
+ tmp_call_strs = [
836
+ f"AtenTensorHandle {tmp_AtenTensorHandle};",
837
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_new_tensor_handle({data.get_name()}, &{tmp_AtenTensorHandle}));",
838
+ ]
839
+ return f"RAIIAtenTensorHandle({tmp_AtenTensorHandle})", tmp_call_strs
840
+
841
+ if (
842
+ size == data.layout.size
843
+ and stride == data.layout.stride
844
+ and offset == data.layout.offset
845
+ and (dtype is None or dtype == data.dtype)
846
+ ):
847
+ final_tensor_str, call_strs = create_new_tensor_handle()
848
+ for line in call_strs:
849
+ writeline(line)
850
+ return final_tensor_str
851
+
852
+ return super().codegen_reinterpret_view(
853
+ data, size, stride, offset, writeline, dtype
854
+ )
855
+
856
+ def val_to_arg_str(self, val, type_=None) -> str:
857
+ if (
858
+ val is not None
859
+ and isinstance(type_, torch.OptionalType)
860
+ and isinstance(type_.getElementType(), torch.TensorType)
861
+ ):
862
+ # Handle optional tensors as a special case, as in the parent class.
863
+ base_handle = self.val_to_arg_str(val, torch.TensorType)
864
+ if config.aot_inductor.use_minimal_arrayref_interface:
865
+ if self.is_safe_to_use_borrow_arrayref_tensor_as_tensor():
866
+ base_handle = f"borrow_arrayref_tensor_as_tensor({base_handle})"
867
+ else:
868
+ base_handle = f"copy_arrayref_tensor_to_tensor({base_handle})"
869
+ return f"&temporary_reference({base_handle}.get())"
870
+
871
+ return super().val_to_arg_str(val, type_)
872
+
873
+ def codegen_tensor_item(
874
+ self, dtype: torch.dtype, tensor: str, scalar: str, indented_buffer=None
875
+ ):
876
+ dtype_str = str(dtype).split(".")[-1]
877
+ writer = indented_buffer or self
878
+
879
+ if dtype == torch.float16 or dtype == torch.bfloat16:
880
+ scalar_tmp = f"{scalar}_tmp"
881
+ writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar_tmp};")
882
+
883
+ # We know that item_ doesn't alias the input, so borrowing should be safe.
884
+ tensor = f"borrow_arrayref_tensor_as_tensor({tensor})"
885
+
886
+ writer.writeline(
887
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar_tmp}));"
888
+ )
889
+ writer.writeline(f"float {scalar} = float({scalar_tmp});")
890
+ else:
891
+ writer.writeline(f"{DTYPE_TO_CPP[dtype]} {scalar};")
892
+
893
+ # We know that item_ doesn't alias the input, so borrowing should be safe.
894
+ tensor = f"borrow_arrayref_tensor_as_tensor({tensor})"
895
+
896
+ writer.writeline(
897
+ f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_item_{dtype_str}({tensor}, &{scalar}));"
898
+ )
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_gpu.py ADDED
@@ -0,0 +1,897 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import dataclasses
5
+ import re
6
+ import sys
7
+ from itertools import count, zip_longest
8
+ from typing import Any, Optional, Union
9
+ from typing_extensions import Self
10
+
11
+ import sympy
12
+
13
+ import torch
14
+ from torch import dtype as torch_dtype
15
+ from torch._inductor.codecache import get_cpp_wrapper_cubin_path_name
16
+ from torch._inductor.runtime.runtime_utils import dynamo_timed
17
+
18
+ from .. import config
19
+ from ..codecache import CudaKernelParamCache
20
+ from ..ir import (
21
+ GraphPartitionSignature,
22
+ TensorBox,
23
+ TMADescriptorExperimental,
24
+ TMADescriptorStable,
25
+ )
26
+ from ..utils import (
27
+ cache_on_self,
28
+ get_gpu_type,
29
+ GPU_ALIGN_BYTES,
30
+ IndentedBuffer,
31
+ XPU_KERNEL_FORMAT,
32
+ )
33
+ from ..virtualized import V
34
+ from .aoti_hipify_utils import maybe_hipify_code_wrapper
35
+ from .common import get_device_op_overrides, TritonScratchWorkspace
36
+ from .cpp_utils import cexpr
37
+ from .cpp_wrapper_cpu import CppWrapperCpu
38
+ from .multi_kernel import MultiKernelCall
39
+ from .triton_utils import should_unwrap_unspec_arg
40
+ from .wrapper import PythonWrapperCodegen, SymbolicCallArg
41
+
42
+
43
+ _cpp_string_literal_escapes = {
44
+ "\\": "\\\\",
45
+ '"': '\\"',
46
+ "\n": "\\n",
47
+ "\t": "\\t",
48
+ "\r": "\\r",
49
+ }
50
+ _cpp_string_literal_pattern = re.compile(r'["\\\n\t\r]')
51
+
52
+
53
+ def cpp_string_literal(s: str) -> str:
54
+ escaped = _cpp_string_literal_pattern.sub(
55
+ lambda match: _cpp_string_literal_escapes[match.group(0)], s
56
+ )
57
+ return f'"{escaped}"'
58
+
59
+
60
+ TRITON_SIGNATURE_TO_CPP = {
61
+ "i32": "int32_t",
62
+ "i64": "int64_t",
63
+ "fp32": "float",
64
+ "fp64": "double",
65
+ }
66
+
67
+
68
+ def signature_is_tma_desc(sig: Optional[str]) -> bool:
69
+ """Check if a Triton signature represents a TMA descriptor."""
70
+ if not sig:
71
+ return False
72
+ if sig == "nvTmaDesc":
73
+ return True
74
+ if sig.startswith("tensordesc<"):
75
+ return True
76
+ return False
77
+
78
+
79
+ @dataclasses.dataclass
80
+ class DeferredTritonCallWrapper:
81
+ """
82
+ When using cpp wrapper, GPU kernel load and launch needs to wait for Triton kernels
83
+ to be tuned and stored as cubin files, so use a deferred generating the final wrapper around
84
+ the triton kernel until right before the prefix is written.
85
+ """
86
+
87
+ wrapper_name: str
88
+ kernel_name: str
89
+ kernel_name_to_body: dict[str, str]
90
+ arg_types: list[Any]
91
+
92
+ def generate(self, wrapper: CppWrapperGpu):
93
+ """
94
+ Generate the GPU kernel definition, as well as load and launch code.
95
+ """
96
+ prefix = wrapper.prefix
97
+ if self.kernel_name.startswith("multi_kernel_"):
98
+ # MultiKernel will select one kernel after running the autotune block
99
+ self.kernel_name = MultiKernelCall.lookup_choice(self.kernel_name)
100
+ params = CudaKernelParamCache.get(self.kernel_name)
101
+ assert params, f"CudaKernelParamCache not populated for {self.kernel_name}"
102
+ def_args = params["def_args"]
103
+ arg_types = self.arg_types
104
+ inductor_meta = params["inductor_meta"]
105
+
106
+ if "extra_launcher_args" in inductor_meta and len(def_args) > len(arg_types):
107
+ # extra_launcher_args should already be in def_args
108
+ assert len(def_args) == len(arg_types) - len(
109
+ inductor_meta["extra_launcher_args"]
110
+ )
111
+ arg_types = arg_types + [SymbolicCallArg] * len(
112
+ inductor_meta["extra_launcher_args"]
113
+ )
114
+
115
+ if not V.graph.aot_mode:
116
+ prefix.writeline(
117
+ maybe_hipify_code_wrapper(
118
+ f"static {wrapper.device_codegen.cpp_kernel_type()} {self.kernel_name} = nullptr;"
119
+ )
120
+ )
121
+ kernel_var_name = self.kernel_name
122
+ else:
123
+ kernel_var_name = f"kernels_.{self.kernel_name}"
124
+
125
+ # tensors can be RAIIAtenTensorHandle or ConstantHandle, so make them template types
126
+ template_types = [
127
+ f"typename {name}_type_"
128
+ for name, arg_type in zip(def_args, arg_types)
129
+ if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg))
130
+ ]
131
+ if V.graph.aot_mode:
132
+ template_types.append("typename kernels_type_")
133
+ if template_types:
134
+ prefix.writeline(f"template <{', '.join(template_types)}>")
135
+ prefix.writeline(f"static inline void {self.wrapper_name}(")
136
+ with prefix.indent():
137
+ assert len(def_args) == len(arg_types), (def_args, arg_types)
138
+ for name, arg_type in zip(def_args, arg_types):
139
+ if isinstance(arg_type, (torch_dtype, UnwrapUnspecArg)):
140
+ prefix.writeline(f"const {name}_type_& {name},")
141
+ elif issubclass(arg_type, (SymbolicCallArg, sympy.Expr, int)):
142
+ prefix.writeline(f"int64_t {name},")
143
+ elif arg_type is float:
144
+ prefix.writeline(f"float {name},")
145
+ elif arg_type is bool:
146
+ prefix.writeline(f"bool {name},")
147
+ else:
148
+ raise ValueError(f"Unexpected arg type {arg_type}")
149
+ prefix.writeline("int32_t device_idx_,")
150
+ prefix.writeline(
151
+ maybe_hipify_code_wrapper(
152
+ f"{wrapper.device_codegen.cpp_stream_type()} stream_,"
153
+ )
154
+ )
155
+ if V.graph.aot_mode:
156
+ prefix.writeline("kernels_type_& kernels_,")
157
+ prefix.writeline(
158
+ "const std::optional<std::string>& cubin_dir_ = std::nullopt"
159
+ )
160
+ prefix.writeline("){")
161
+ with prefix.indent():
162
+ if V.graph.aot_mode:
163
+ # Emit the original Triton kernel for debugging purposes
164
+ prefix.writeline("/*")
165
+ prefix.splice(self.kernel_name_to_body[self.kernel_name])
166
+ prefix.writeline("*/")
167
+ self.generate_grid(prefix, inductor_meta, params)
168
+ self.generate_load_kernel(prefix, kernel_var_name, params)
169
+ self.generate_launch_kernel(prefix, wrapper, kernel_var_name, params)
170
+ prefix.writeline("}")
171
+
172
+ if not config.aot_inductor.embed_kernel_binary:
173
+ # Ensure the cubin file is included in the package
174
+ V.graph.wrapper_code.additional_files.append(
175
+ params[get_cpp_wrapper_cubin_path_name()]
176
+ )
177
+
178
+ def generate_grid(
179
+ self,
180
+ prefix: IndentedBuffer,
181
+ inductor_meta: dict[str, Any],
182
+ params: dict[str, Any],
183
+ ):
184
+ from ..runtime.triton_heuristics import GridExpr
185
+
186
+ grid = GridExpr.from_meta(inductor_meta, params["config"], mode="cpp")
187
+ for line in grid.prefix:
188
+ prefix.writeline(line)
189
+ prefix.splice(
190
+ f"""\
191
+ uint32_t grid_0 = {grid.x_grid};
192
+ uint32_t grid_1 = {grid.y_grid};
193
+ uint32_t grid_2 = {grid.z_grid};
194
+ """
195
+ )
196
+ prefix.writeline("if (grid_0 == 0 || grid_1 == 0 || grid_2 == 0) return;")
197
+
198
+ def generate_load_kernel(self, prefix, kernel_var_name, params):
199
+ prefix.writeline(f"if ({kernel_var_name} == nullptr) {{")
200
+ with prefix.indent():
201
+ embed_kernel_args = [f"__{params['inductor_meta']['kernel_name']}_start"]
202
+ if torch.xpu.is_available():
203
+ # XPU needs the end address of the kernel to calculate the size of the kernel binary.
204
+ embed_kernel_args.append(
205
+ f"__{params['inductor_meta']['kernel_name']}_end"
206
+ )
207
+
208
+ if V.graph.aot_mode and config.aot_inductor.embed_kernel_binary:
209
+ load_kernel_args = [
210
+ *embed_kernel_args,
211
+ cpp_string_literal(params["mangled_name"]),
212
+ str(params["shared_mem"]),
213
+ ]
214
+ if torch.xpu.is_available():
215
+ is_spv = "true" if XPU_KERNEL_FORMAT == "spv" else "false"
216
+ if config.aot_inductor.emit_multi_arch_kernel:
217
+ is_spv = "true"
218
+ load_kernel_args.append(is_spv)
219
+ else:
220
+ load_kernel_args = [
221
+ cpp_string_literal(params[get_cpp_wrapper_cubin_path_name()]),
222
+ cpp_string_literal(params["mangled_name"]),
223
+ str(params["shared_mem"]),
224
+ "cubin_dir_",
225
+ ]
226
+
227
+ prefix.writeline(
228
+ f"{kernel_var_name} = loadKernel({', '.join(load_kernel_args)}); "
229
+ )
230
+ prefix.writeline("}")
231
+
232
+ def generate_launch_kernel(self, prefix, wrapper, kernel_var_name, params):
233
+ """
234
+ Generate the GPU kernel launching code.
235
+ This is where all the call args being sorted out and generated.
236
+ If enable_kernel_profile is enabled, all args related information would be packed in this function.
237
+ """
238
+ triton_meta = params["triton_meta"]
239
+ assert len(self.arg_types) == len(params["def_args"]), (
240
+ self.arg_types,
241
+ params["def_args"],
242
+ )
243
+ arg_type_lookup = dict(zip(params["def_args"], self.arg_types))
244
+ # difference between Python and C++ wrapper: C++ wrapper strips out equal_to_1 constants
245
+ call_args = [
246
+ name for name in params["call_args"] if name not in triton_meta["constants"]
247
+ ]
248
+ arg_types = [arg_type_lookup[name] for name in call_args]
249
+ arg_signatures = [triton_meta["signature"][name] for name in call_args]
250
+ scratch_spaces = {
251
+ name: params[name]
252
+ for name in ["global_scratch", "profile_scratch"]
253
+ if params.get(name, None) is not None
254
+ }
255
+ call_args_str = wrapper.generate_args_decl(
256
+ prefix,
257
+ call_args,
258
+ arg_types,
259
+ arg_signatures,
260
+ scratch_spaces=scratch_spaces,
261
+ )
262
+ prefix.writeline(f"void* kernel_args_[] = {{{call_args_str}}};")
263
+ launch_kernel_args = [
264
+ kernel_var_name,
265
+ "grid_0",
266
+ "grid_1",
267
+ "grid_2",
268
+ str(params["num_warps"]),
269
+ str(params["shared_mem"]),
270
+ "kernel_args_",
271
+ "stream_",
272
+ ]
273
+ if wrapper.device == "xpu":
274
+ launch_kernel_args.append(str(params["threads_per_warp"]))
275
+
276
+ enable_kernel_profile = config.cpp.enable_kernel_profile and sys.platform in [
277
+ "linux",
278
+ "win32",
279
+ ]
280
+ if enable_kernel_profile:
281
+ normalized_kernel_name = re.sub(r"[^a-zA-Z0-9_]", "_", f"{kernel_var_name}")
282
+ prefix.writeline("{")
283
+ with prefix.indent():
284
+ prefix.writelines(
285
+ [
286
+ f"std::unordered_map<std::string, C10IValueHandle> kwargs_{normalized_kernel_name};",
287
+ "",
288
+ ]
289
+ )
290
+ # Add launch args info
291
+ record_launch_kernel_args = [
292
+ ("grid_0", "grid_0"),
293
+ ("grid_1", "grid_1"),
294
+ ("grid_2", "grid_2"),
295
+ ("num_warps", str(params["num_warps"])),
296
+ ("shared_mem", str(params["shared_mem"])),
297
+ ]
298
+ for k, v in record_launch_kernel_args:
299
+ arg_name = f"{normalized_kernel_name}_{k}"
300
+ prefix.writelines(
301
+ [
302
+ f"// Create c10::IValue for {k}",
303
+ f"C10IValueHandle tmp_{arg_name};",
304
+ f"aoti_torch_int64_to_ivalue({v}, &tmp_{arg_name});",
305
+ f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});",
306
+ f'kwargs_{normalized_kernel_name}.emplace("{k}", RAII_{arg_name});',
307
+ ]
308
+ )
309
+
310
+ # Add input info (This copies the logic from args_decl)
311
+ curr_arg_id = -1
312
+ total_args = []
313
+ ordered_argsname = []
314
+
315
+ def write_dummy_scalar_ivalue(arg_name):
316
+ # We only care about the shape, therefore we create a dummy scalar here.
317
+ prefix.writelines(
318
+ [
319
+ f"// Create c10::IValue for arg_{curr_arg_id}",
320
+ f"C10IValueHandle tmp_{arg_name};",
321
+ f"aoti_torch_int64_to_ivalue(0, &tmp_{arg_name});",
322
+ f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});",
323
+ ]
324
+ )
325
+ # pyrefly: ignore [bad-argument-type]
326
+ total_args.append(f"tmp_{arg_name}")
327
+
328
+ def process_args_for_input_shape(arg, arg_type, arg_signature=None):
329
+ nonlocal curr_arg_id
330
+ curr_arg_id += 1
331
+ arg_name = f"{normalized_kernel_name}_arg_{curr_arg_id}"
332
+ # ignore tma descriptors, as host-side TMA descriptors need
333
+ # to be passed to the compiled Triton kernel by value
334
+ if isinstance(
335
+ arg_type, UnwrapUnspecArg
336
+ ) and not signature_is_tma_desc(arg_signature):
337
+ write_dummy_scalar_ivalue(arg_name)
338
+ elif isinstance(
339
+ arg_type, torch_dtype
340
+ ) and not signature_is_tma_desc(arg_signature):
341
+ # This is an at::Tensor.
342
+ prefix.writelines(
343
+ [
344
+ f"// Create c10::IValue for arg_{curr_arg_id}",
345
+ f"C10IValueHandle tmp_{arg_name};",
346
+ f"aoti_torch_tensor_to_ivalue({arg}, &tmp_{arg_name});",
347
+ f"RAIIC10IValueHandle RAII_{arg_name}(tmp_{arg_name});",
348
+ ]
349
+ )
350
+ # pyrefly: ignore [bad-argument-type]
351
+ total_args.append(f"tmp_{arg_name}")
352
+ elif (
353
+ isinstance(arg_type, type(SymbolicCallArg))
354
+ and arg_signature is not None
355
+ and arg_signature in TRITON_SIGNATURE_TO_CPP
356
+ ) or arg_type in (sympy.Integer, int, sympy.Float, float):
357
+ write_dummy_scalar_ivalue(arg_name)
358
+ elif arg_signature and arg_signature.startswith("tensordesc<"):
359
+ # Skip tma related args
360
+ pass
361
+ else:
362
+ write_dummy_scalar_ivalue(arg_name)
363
+
364
+ # Add input name and shape information
365
+ for arg, arg_type, arg_signature in zip_longest(
366
+ call_args, arg_types, arg_signatures
367
+ ):
368
+ # pyrefly: ignore [bad-argument-type]
369
+ ordered_argsname.append(f'"{arg}"')
370
+ process_args_for_input_shape(arg, arg_type, arg_signature)
371
+
372
+ # Add input name into kwargs
373
+ name_var = f"{normalized_kernel_name}_input_names"
374
+ prefix.writelines(
375
+ [
376
+ "// Create c10::IValue for input names",
377
+ f"C10IValueHandle tmp_{name_var};",
378
+ f"std::vector<const char*> {name_var}({{{', '.join(ordered_argsname)}}});",
379
+ f"aoti_torch_strlist_to_ivalue({name_var}.data(), {len(ordered_argsname)}, &tmp_{name_var});",
380
+ f"RAIIC10IValueHandle RAII_{name_var}(tmp_{name_var});",
381
+ f'kwargs_{normalized_kernel_name}.emplace("Input Args", RAII_{name_var});',
382
+ ]
383
+ )
384
+
385
+ inputs_info_ = f"{normalized_kernel_name}_inputs_info_"
386
+ # We pass in the non-RAII handles, since C10 doesn't automatically free them.
387
+ # The RAII will make sure they get freed when they are out of scope.
388
+ tmp_args = ",".join(total_args)
389
+ prefix.writelines(
390
+ [
391
+ "// Aggregate all c10::IValue for inputs",
392
+ f"std::vector<C10IValueHandle> {inputs_info_}({{{tmp_args}}});",
393
+ ]
394
+ )
395
+
396
+ # Start recording Function
397
+ prefix.writelines(
398
+ [
399
+ "",
400
+ (
401
+ "torch::aot_inductor::RAIIAtenRecordFunctionHandle "
402
+ f"record_{normalized_kernel_name}_"
403
+ f'("{kernel_var_name}", '
404
+ f"reinterpret_cast<IValueMapHandle>(&kwargs_{normalized_kernel_name}), "
405
+ f"{inputs_info_});"
406
+ ),
407
+ "",
408
+ f"launchKernel({', '.join(launch_kernel_args)});",
409
+ ]
410
+ )
411
+ prefix.writeline("}")
412
+ else:
413
+ prefix.writeline(f"launchKernel({', '.join(launch_kernel_args)});")
414
+
415
+
416
+ class CppWrapperGpu(CppWrapperCpu):
417
+ """
418
+ Generates cpp wrapper for running on GPU and calls CUDA kernels
419
+ """
420
+
421
+ def __init__(self) -> None:
422
+ self.device = get_gpu_type()
423
+ self.device_codegen = get_device_op_overrides(self.device)
424
+ super().__init__()
425
+ self.grid_id = count()
426
+ self._kernel_name_to_body: dict[str, str] = {}
427
+ self._triton_call_wrappers: dict[str, DeferredTritonCallWrapper] = {}
428
+ self.autotune_input_prefix = "_REAL_AUTOTUNE_INPUT"
429
+
430
+ @staticmethod
431
+ def create(
432
+ is_subgraph: bool,
433
+ subgraph_name: Optional[str],
434
+ parent_wrapper: Optional[PythonWrapperCodegen],
435
+ partition_signatures: Optional[GraphPartitionSignature] = None,
436
+ ):
437
+ # TODO - support subgraph codegen by lifting functions. Check the
438
+ # comment at CppWrapperCpu `codegen_subgraph` function.
439
+ return CppWrapperGpu()
440
+
441
+ def write_header(self):
442
+ if V.graph.is_const_graph:
443
+ # We do not write header for constant graph, it will be written by main module.
444
+ return
445
+
446
+ super().write_header()
447
+ self.header.splice(
448
+ maybe_hipify_code_wrapper(self.device_codegen.kernel_driver())
449
+ )
450
+
451
+ @cache_on_self
452
+ def write_tma_descriptor_helpers_once(self):
453
+ self.header.splice(self.device_codegen.tma_descriptor_helpers())
454
+
455
+ def write_get_raw_stream(self, device_idx: int, graph_name: str) -> str:
456
+ name = f"stream{device_idx}"
457
+ self.writeline(
458
+ maybe_hipify_code_wrapper(
459
+ f"{self.device_codegen.cpp_stream_type()} {name};"
460
+ )
461
+ )
462
+ self.writeline(
463
+ f"AOTI_TORCH_ERROR_CODE_CHECK({self.device_codegen.aoti_get_stream()}({device_idx}, (void**)&{name}));"
464
+ )
465
+ return name
466
+
467
+ def get_autotuning_input_name(self, idx):
468
+ return f"{self.autotune_input_prefix}_{idx}"
469
+
470
+ def codegen_inputs(self):
471
+ # See Note: [Input Alignment handling in Inductor]
472
+ #
473
+ # JIT Inductor does not guard on input alignment. It relies on copy_misaligned_inputs to
474
+ # copy misaligned inputs to aligned buffers. For AOTInductor, we need to do the same in cpp.
475
+
476
+ if config.is_fbcode():
477
+ # TODO: This is added because FC. Remove this once the newly added shim symbols,
478
+ # e.g. aoti_torch_clone_preserve_strides, have landed
479
+ return super().codegen_inputs()
480
+
481
+ if V.graph.aot_mode and V.graph.inputs_to_check:
482
+ for idx in V.graph.inputs_to_check:
483
+ input_name = V.graph.graph_input_names[idx]
484
+ assert input_name in V.graph.graph_inputs, (
485
+ f"{input_name} not found in graph inputs"
486
+ )
487
+ value = V.graph.graph_inputs[input_name]
488
+ assert isinstance(value, TensorBox), (
489
+ f"{input_name} is expected to be tensor but found as {type(value)}"
490
+ )
491
+ warn_msg = (
492
+ f"Input {idx} was compiled as {GPU_ALIGN_BYTES}-bytes aligned, "
493
+ "but it is not aligned at run time. Copying to an aligned tensor "
494
+ "to guarantee correctness, but expect a performance hit."
495
+ )
496
+ self.prefix.splice(
497
+ f"""
498
+ if ((reinterpret_cast<std::uintptr_t>({input_name}.data_ptr()) & ({GPU_ALIGN_BYTES} -1)) != 0) {{
499
+ AOTI_TORCH_WARN("{warn_msg}");
500
+ AtenTensorHandle {input_name}_aligned;
501
+ aoti_torch_clone_preserve_strides({input_name}, &{input_name}_aligned);
502
+ {input_name} = std::move(RAIIAtenTensorHandle({input_name}_aligned));
503
+ }}
504
+ """
505
+ )
506
+
507
+ super().codegen_inputs()
508
+
509
+ def _define_kernel_helper(
510
+ self,
511
+ kernel_name: str,
512
+ kernel_body: str,
513
+ metadata: Optional[str] = None,
514
+ gpu: bool = True,
515
+ cpp_definition: Optional[str] = None,
516
+ ):
517
+ if gpu:
518
+ self._kernel_name_to_body[kernel_name] = kernel_body
519
+ if config.triton.autotune_at_compile_time:
520
+ # Call PythonWrapperCodegen to create the autotune code block
521
+ PythonWrapperCodegen._define_kernel_helper(
522
+ self, kernel_name, kernel_body, metadata, gpu, cpp_definition
523
+ )
524
+ else:
525
+ return CppWrapperCpu._define_kernel_helper(
526
+ self, kernel_name, kernel_body, metadata, gpu, cpp_definition
527
+ )
528
+
529
+ def generate(self, is_inference):
530
+ with dynamo_timed("CppWrapperGpu.generate", log_pt2_compile_event=True):
531
+ return super().generate(is_inference)
532
+
533
+ def finalize_prefix(self):
534
+ """Define the triton kernels now that autotuning is finished"""
535
+ old_prefix = self.prefix # new content should go at start of prefix
536
+
537
+ # Generating triton kernel callers can modify the prefix (cached dtypes),
538
+ # so do this before running finalize_prefix(), but put the generated code
539
+ # after the finalize_prefix() code.
540
+ self.prefix = IndentedBuffer()
541
+ for kernel in self._triton_call_wrappers.values():
542
+ self.prefix.writeline("\n")
543
+ kernel.generate(self)
544
+ triton_prefix = self.prefix
545
+
546
+ self.prefix = IndentedBuffer()
547
+ super().finalize_prefix()
548
+
549
+ self.prefix.splice(triton_prefix)
550
+
551
+ self.prefix.writeline("\n")
552
+ self.prefix.splice(old_prefix)
553
+
554
+ def generate_tma_descriptor(self, desc):
555
+ self.write_tma_descriptor_helpers_once()
556
+
557
+ if isinstance(desc, TMADescriptorExperimental):
558
+ self._generate_experimental_tma_descriptor(desc)
559
+ else:
560
+ assert isinstance(desc, TMADescriptorStable)
561
+ self._generate_stable_tma_descriptor(desc)
562
+
563
+ def _generate_experimental_tma_descriptor(self, desc):
564
+ # generate data pointer for the source tensor
565
+ source = self.generate_args_decl(
566
+ code=self,
567
+ call_args=[self.val_to_arg_str(desc.tensor)],
568
+ arg_types=[desc.tensor.get_dtype()],
569
+ arg_signatures=[None],
570
+ # these args are passed to initNDTMADescriptor, which is NOT a triton kernel
571
+ is_triton_kernel=False,
572
+ )
573
+
574
+ desc_name = desc.name
575
+ self.writeline(f"alignas(64) CUtensorMap {desc_name};")
576
+
577
+ # `source` is in the form of `&var_x`, where `var_x` is the data pointer
578
+ # (CUdeviceptr); we dereference `source` and cast to `void*` to pass to
579
+ # the data pointer of the source tensor to the helper function
580
+ # `init{1,2}DTMADescriptor`
581
+ ptr = f"reinterpret_cast<void*>(*({source}))"
582
+ dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.dims)
583
+ block_dims = ", ".join(self.val_to_arg_str(dim) for dim in desc.block_dims)
584
+ element_size = self.val_to_arg_str(desc.element_size)
585
+ fn = f"init{desc.rank}DTMADescriptor"
586
+ args = f"&{desc_name}, {ptr}, {dims}, {block_dims}, {element_size}"
587
+ self.writeline(f"{fn}({args});")
588
+
589
+ def _generate_stable_tma_descriptor(self, desc):
590
+ source = self.generate_args_decl(
591
+ code=self,
592
+ call_args=[self.val_to_arg_str(desc.tensor)],
593
+ arg_types=[desc.tensor.get_dtype()],
594
+ arg_signatures=[None],
595
+ # these args are passed to initNDTMADescriptor, which is NOT a triton kernel
596
+ is_triton_kernel=False,
597
+ )
598
+
599
+ desc_name = desc.name
600
+ # Pack the relevant information into a StableTMADescriptor struct.
601
+ # See [Note: AOTI TMA Stable handling] for more details.
602
+ self.writeline(f"alignas(64) StableTMADescriptor {desc_name};")
603
+
604
+ def fill_array(name, values):
605
+ for i, val in enumerate(values):
606
+ self.writeline(f"{name}[{i}] = {val};")
607
+
608
+ ptr = f"reinterpret_cast<void*>(*({source}))"
609
+ rank = len(desc.tensor.get_size())
610
+
611
+ fill_array(f"{desc_name}.block_shape", desc.block_shape)
612
+ fill_array(f"{desc_name}.global_shape", desc.tensor.get_size())
613
+ fill_array(f"{desc_name}.strides", desc.tensor.get_stride())
614
+
615
+ element_size = self.val_to_arg_str(desc.tensor.get_dtype().itemsize)
616
+ fn = "initTMADescriptor"
617
+ args = ", ".join(
618
+ str(x)
619
+ for x in [
620
+ f"&{desc_name}.m",
621
+ ptr,
622
+ element_size,
623
+ rank,
624
+ f"{desc_name}.block_shape",
625
+ f"{desc_name}.global_shape",
626
+ f"{desc_name}.strides",
627
+ ]
628
+ )
629
+ self.writeline(f"{fn}({args});")
630
+
631
+ def generate_args_decl(
632
+ self,
633
+ code: Union[IndentedBuffer, Self],
634
+ call_args,
635
+ arg_types,
636
+ arg_signatures,
637
+ is_triton_kernel=True,
638
+ scratch_spaces: Optional[dict[str, int]] = None,
639
+ ):
640
+ """
641
+ Generates any declarations of args to pass into a kernel call, and then returns the arg names.
642
+
643
+ In more detail:
644
+ * declarations: e.g. this function has a side effect of generating lines like `auto var_0 = ...;`
645
+ * returns: a string with the list of args, e.g. "var_0, var_1"
646
+
647
+ call_args: list of call arguments
648
+ arg_types: list of argument types
649
+ arg_signatures: list with signatures of all the args
650
+ is_triton_kernel: whether these are passed into a triton kernel or not. In particular,
651
+ calls to triton kernels will have an additional global scratch space
652
+ arg injected at the front of the arg list.
653
+ """
654
+ new_args: list[str] = []
655
+
656
+ def process_tma_stable_arg(arg, arg_type, arg_signature, var_name):
657
+ # [Note: AOTI TMA Stable handling]
658
+ # For most args, a single arg passed to the python triton interface
659
+ # maps to a single arg in the cubin interface. However, for host-side
660
+ # TMA descriptors, a single python arg turns into 1 + 2 * N args in the
661
+ # cubin interface (where N is the rank).
662
+ #
663
+ # To do this: at TMA codegen time (for aoti), we generate a struct
664
+ # (StableTMADescriptor) containing the necessary information; and then
665
+ # when we call the function (i.e. here), we unpack the struct members.
666
+ code.writeline(f"auto {var_name} = {cexpr(arg)};")
667
+
668
+ result = []
669
+ result.append(f"&{var_name}.m")
670
+
671
+ # from https://github.com/triton-lang/triton/blob/16961b79bdac1b774b42d44e52fd55a266ec2866/third_party/nvidia/backend/driver.py#L111 # noqa: B950
672
+ match = re.match("tensordesc<([^[>]*)\\[([^]]*)\\]", arg_signature)
673
+ assert match is not None
674
+ shape = match.group(2)
675
+ ndim = shape.count(",") + 1
676
+
677
+ for i in range(ndim):
678
+ result.append(f"&{var_name}.block_shape[{i}]")
679
+
680
+ for i in range(ndim):
681
+ result.append(f"&{var_name}.strides[{i}]")
682
+
683
+ return result
684
+
685
+ def process_args(arg, arg_type, arg_signature=None):
686
+ var_name = f"var_{next(self.arg_var_id)}"
687
+ # ignore tma descriptors, as host-side TMA descriptors need
688
+ # to be passed to the compiled Triton kernel by value
689
+ if isinstance(arg_type, UnwrapUnspecArg) and not signature_is_tma_desc(
690
+ arg_signature
691
+ ):
692
+ self.codegen_tensor_item(
693
+ arg_type.dtype,
694
+ arg,
695
+ var_name,
696
+ indented_buffer=code,
697
+ )
698
+ new_args.append(f"&{var_name}")
699
+ elif isinstance(arg_type, torch_dtype) and not signature_is_tma_desc(
700
+ arg_signature
701
+ ):
702
+ device_ptr_type = self.device_codegen.cpp_device_ptr()
703
+ code.writeline(
704
+ maybe_hipify_code_wrapper(
705
+ f"{device_ptr_type} {var_name} = reinterpret_cast<{device_ptr_type}>({arg}.data_ptr());"
706
+ )
707
+ )
708
+ new_args.append(f"&{var_name}")
709
+ # For symbolic call arguments, examine the arg signatures from triton meta
710
+ # to explicitly cast to the right type
711
+ # Reason: `auto` can infer unexpected type against kernel input signature.
712
+ elif (
713
+ isinstance(arg_type, type(SymbolicCallArg))
714
+ and arg_signature is not None
715
+ and arg_signature in TRITON_SIGNATURE_TO_CPP
716
+ ):
717
+ code.writeline(
718
+ f"{TRITON_SIGNATURE_TO_CPP[arg_signature]} {var_name} = {cexpr(arg)};"
719
+ )
720
+ new_args.append(f"&{var_name}")
721
+ elif arg_type in (sympy.Integer, int):
722
+ code.writeline(f"int {var_name} = {cexpr(arg)};")
723
+ new_args.append(f"&{var_name}")
724
+ elif arg_type in (sympy.Float, float):
725
+ # Use signature type if available, otherwise default to float
726
+ cpp_type = TRITON_SIGNATURE_TO_CPP.get( # pyrefly: ignore[no-matching-overload]
727
+ arg_signature, "float"
728
+ )
729
+ code.writeline(f"{cpp_type} {var_name} = {cexpr(arg)};")
730
+ new_args.append(f"&{var_name}")
731
+ elif arg_signature and arg_signature.startswith("tensordesc<"):
732
+ new_args.extend(
733
+ process_tma_stable_arg(arg, arg_type, arg_signature, var_name)
734
+ )
735
+ else:
736
+ code.writeline(f"auto {var_name} = {cexpr(arg)};")
737
+ new_args.append(f"&{var_name}")
738
+
739
+ for arg, arg_type, arg_signature in zip_longest(
740
+ call_args, arg_types, arg_signatures
741
+ ):
742
+ process_args(arg, arg_type, arg_signature)
743
+
744
+ for scratch_name, workspace_size in (scratch_spaces or {}).items():
745
+ if (
746
+ is_triton_kernel
747
+ and (
748
+ scratch := self.device_codegen.cpp_scratch(
749
+ next(self.arg_var_id),
750
+ workspace=TritonScratchWorkspace(
751
+ size=workspace_size,
752
+ generate_dtype_str=(
753
+ lambda: self.codegen_dtype(torch.uint8)
754
+ ),
755
+ ),
756
+ prefix=scratch_name,
757
+ )
758
+ )
759
+ is not None
760
+ ):
761
+ scratch_def, scratch_var = scratch
762
+ code.writelines([maybe_hipify_code_wrapper(x) for x in scratch_def])
763
+ new_args.append(f"&{scratch_var}")
764
+
765
+ return ", ".join(new_args)
766
+
767
+ def _generate_kernel_call_helper(
768
+ self,
769
+ kernel_name: str,
770
+ call_args,
771
+ *,
772
+ device=None,
773
+ triton=True,
774
+ arg_types=None,
775
+ raw_keys=None,
776
+ raw_args=None,
777
+ triton_meta=None,
778
+ inductor_meta=None,
779
+ graph_name="",
780
+ original_fxnode_name=None,
781
+ ):
782
+ """
783
+ Override the default value of argument 'gpu' to True here.
784
+ generate_kernel_call can still be called with gpu=False because of
785
+ a mix of cpu kernels and gpu kernels.
786
+ """
787
+ device = device or V.graph.get_current_device_or_throw()
788
+ if device.type == "cpu":
789
+ # Even in CppWrapperGpu, we may see cpp kernels
790
+ return CppWrapperCpu._generate_kernel_call_helper(
791
+ self,
792
+ kernel_name,
793
+ call_args,
794
+ device=device,
795
+ triton=triton,
796
+ arg_types=arg_types,
797
+ raw_keys=raw_keys,
798
+ raw_args=raw_args,
799
+ triton_meta=triton_meta,
800
+ inductor_meta=inductor_meta,
801
+ )
802
+
803
+ if (
804
+ triton
805
+ and config.triton.autotune_at_compile_time
806
+ and kernel_name not in self.kernel_autotune_names
807
+ ):
808
+ # Call PythonWrapperCodegen to create the autotune code block
809
+ PythonWrapperCodegen._generate_kernel_call_helper(
810
+ self,
811
+ kernel_name,
812
+ call_args,
813
+ device=device,
814
+ triton=triton,
815
+ arg_types=arg_types,
816
+ raw_keys=raw_keys,
817
+ raw_args=raw_args,
818
+ triton_meta=triton_meta,
819
+ inductor_meta=inductor_meta,
820
+ original_fxnode_name=original_fxnode_name,
821
+ )
822
+
823
+ stream = (
824
+ "stream"
825
+ if V.graph.aot_mode
826
+ else self.write_get_raw_stream(device.index, graph_name)
827
+ )
828
+
829
+ if triton:
830
+ call_args, arg_types = self.prepare_triton_wrapper_args(
831
+ call_args,
832
+ # pyrefly: ignore [bad-argument-type]
833
+ arg_types,
834
+ )
835
+ wrapper_name = f"call_{kernel_name}"
836
+ if wrapper_name not in self._triton_call_wrappers:
837
+ self._triton_call_wrappers[wrapper_name] = DeferredTritonCallWrapper(
838
+ wrapper_name,
839
+ kernel_name,
840
+ self._kernel_name_to_body,
841
+ arg_types,
842
+ )
843
+ device_idx = "this->device_idx_" if V.graph.aot_mode else str(device.index)
844
+ call_args.append(device_idx)
845
+ call_args.append(stream)
846
+ if V.graph.aot_mode:
847
+ call_args.append("kernels")
848
+ call_args.append("this->cubin_dir_")
849
+ debug_printer_manager = V.graph.wrapper_code.debug_printer
850
+ debug_printer_manager.set_printer_args(
851
+ call_args[: len(arg_types)], kernel_name, arg_types, None
852
+ )
853
+ with debug_printer_manager:
854
+ self.writeline(f"{wrapper_name}({', '.join(call_args)});")
855
+ else:
856
+ casted = []
857
+ # pyrefly: ignore [no-matching-overload]
858
+ for arg_type, arg in zip(arg_types, call_args):
859
+ new_arg = arg
860
+ if arg_type.endswith("*") and arg != "nullptr":
861
+ new_arg = f"{arg}.data_ptr()"
862
+ # pyrefly: ignore [bad-argument-type]
863
+ casted.append(f"({arg_type}){cexpr(new_arg)}")
864
+ call_args_str = ", ".join(casted)
865
+ self.writeline(f"kernels.{kernel_name}({call_args_str}, {stream});")
866
+
867
+ @staticmethod
868
+ def prepare_triton_wrapper_args(
869
+ call_args: list[Any], arg_types: list[Any]
870
+ ) -> tuple[list[Any], list[Any]]:
871
+ assert len(call_args) == len(arg_types), (call_args, arg_types)
872
+ new_args = []
873
+ new_args_types = []
874
+ for arg, arg_type in zip(call_args, arg_types):
875
+ if isinstance(arg, str):
876
+ if isinstance(arg_type, torch_dtype) and should_unwrap_unspec_arg(arg):
877
+ # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar
878
+ arg_type = UnwrapUnspecArg(dtype=arg_type)
879
+ new_args.append(arg)
880
+ elif isinstance(arg, bool):
881
+ new_args.append(str(arg).lower())
882
+ elif isinstance(arg, (int, float, SymbolicCallArg)):
883
+ new_args.append(str(arg))
884
+ else:
885
+ new_args.append(cexpr(V.graph.sizevars.simplify(arg)))
886
+ new_args_types.append(arg_type)
887
+ return new_args, new_args_types
888
+
889
+ def make_zero_buffer(self, name):
890
+ return f"AOTI_TORCH_ERROR_CODE_CHECK(aoti_torch_zero_({name}.get()));"
891
+
892
+
893
+ @dataclasses.dataclass
894
+ class UnwrapUnspecArg:
895
+ """Marker that we need to call .item() on the tensor"""
896
+
897
+ dtype: torch_dtype
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpp_wrapper_mps.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Optional
2
+
3
+ import sympy
4
+
5
+ import torch
6
+ from torch.utils._ordered_set import OrderedSet
7
+
8
+ from ..ir import GraphPartitionSignature
9
+ from ..virtualized import V
10
+ from .cpp_wrapper_cpu import CppWrapperCpu
11
+ from .cpp_wrapper_gpu import CppWrapperGpu
12
+ from .wrapper import KernelCallLine, PythonWrapperCodegen
13
+
14
+
15
+ class CppWrapperMps(CppWrapperGpu):
16
+ """
17
+ Generates cpp wrapper for running on MPS and calls metal kernels
18
+ """
19
+
20
+ def __init__(self) -> None:
21
+ super().__init__()
22
+ self._used_kernel_names: OrderedSet[str] = OrderedSet()
23
+ self._lambda_counter: int = 0
24
+
25
+ @staticmethod
26
+ def create(
27
+ is_subgraph: bool,
28
+ subgraph_name: Optional[str],
29
+ parent_wrapper: Optional[PythonWrapperCodegen],
30
+ partition_signatures: Optional[GraphPartitionSignature] = None,
31
+ ) -> "CppWrapperMps":
32
+ return CppWrapperMps()
33
+
34
+ def _generate_kernel_call_helper(
35
+ self,
36
+ kernel_name: str,
37
+ call_args: list[str],
38
+ *,
39
+ device: Optional[torch.device] = None,
40
+ triton: bool = True,
41
+ arg_types: Optional[tuple[Any, ...]] = None,
42
+ raw_keys: Optional[tuple[Any, ...]] = None,
43
+ raw_args: Optional[tuple[Any, ...]] = None,
44
+ triton_meta: Optional[dict[str, Any]] = None,
45
+ inductor_meta: Optional[dict[str, Any]] = None,
46
+ graph_name: str = "",
47
+ original_fxnode_name: Optional[str] = None,
48
+ ) -> None:
49
+ """
50
+ Generates MPS kernel call code. It should look something like:
51
+ ```
52
+ auto mps_lib_0_lambda = [&](AOTIMetalKernelFunctionHandle handle) {
53
+ aoti_torch_mps_start_encoding(handle);
54
+ aoti_torch_mps_set_arg_tensor(handle, 0, buf0);
55
+ aoti_torch_mps_set_arg_tensor(handle, 1, arg0_1);
56
+ aoti_torch_mps_set_arg_tensor(handle, 2, arg1_1);
57
+ aoti_torch_mps_dispatch_single(handle, static_cast<uint64_t>(10LL));
58
+ };
59
+
60
+ std::function<void(AOTIMetalKernelFunctionHandle)> mps_lib_0_func_wrapper = mps_lib_0_lambda;
61
+ aoti_torch_mps_run_command_block(get_mps_lib_0_handle(), aoti_torch_mps_shared_callback, &mps_lib_0_func_wrapper);
62
+ ```
63
+ """
64
+ device = device or V.graph.get_current_device_or_throw()
65
+ if device.type == "cpu":
66
+ # Even in CppWrapperGpu, we may see cpp kernels
67
+ return CppWrapperCpu._generate_kernel_call_helper(
68
+ self,
69
+ kernel_name,
70
+ call_args,
71
+ device=device,
72
+ triton=triton,
73
+ arg_types=arg_types,
74
+ raw_keys=raw_keys,
75
+ raw_args=raw_args,
76
+ triton_meta=triton_meta,
77
+ inductor_meta=inductor_meta,
78
+ )
79
+
80
+ assert device.type == "mps"
81
+
82
+ assert arg_types is not None
83
+
84
+ new_args = []
85
+ for idx, (arg, arg_type) in enumerate(zip(call_args[:-2], arg_types[:-2])):
86
+ if isinstance(arg_type, torch.dtype):
87
+ new_args.append(f"aoti_torch_mps_set_arg_tensor(handle, {idx}, {arg});")
88
+ elif arg_type in (int, sympy.core.symbol.Symbol):
89
+ new_args.append(f"aoti_torch_mps_set_arg_int(handle, {idx}, {arg});")
90
+ else:
91
+ raise NotImplementedError(
92
+ f"Unsupported arg type {arg_type} for arg {arg} for kernel {kernel_name}"
93
+ )
94
+
95
+ threads, group_size = call_args[-2], call_args[-1]
96
+ if threads is None:
97
+ raise NotImplementedError("No threads or group_size provided")
98
+
99
+ # Check if threads is a single value or an array-like structure
100
+ threads_str = str(threads)
101
+ is_single_value = (
102
+ threads_str.startswith("{")
103
+ and threads_str.endswith("}")
104
+ and threads_str.count(",") == 0
105
+ ) or not threads_str.startswith(("{", "["))
106
+
107
+ if is_single_value:
108
+ # Extract single value from braces if present
109
+ if threads_str.startswith("{") and threads_str.endswith("}"):
110
+ single_value = threads_str[1:-1].strip() # Remove braces
111
+ else:
112
+ single_value = threads_str
113
+
114
+ if group_size is None:
115
+ new_args.append(
116
+ f"aoti_torch_mps_dispatch_single(handle, {single_value});"
117
+ )
118
+ else:
119
+ # Extract group size value if it's also in braces
120
+ group_size_str = str(group_size)
121
+ if group_size_str.startswith("{") and group_size_str.endswith("}"):
122
+ group_size_value = group_size_str[1:-1].strip()
123
+ else:
124
+ group_size_value = group_size_str
125
+ new_args.append(
126
+ f"aoti_torch_mps_dispatch_single_with_group_size(handle, {single_value}, {group_size_value});"
127
+ )
128
+ else:
129
+ # Handle array case - need to convert initializer list to array
130
+ # Use kernel name to make variable names unique
131
+ threads_var = f"{kernel_name}_threads_array"
132
+ group_size_var = f"{kernel_name}_group_size_array"
133
+
134
+ # Extract array size from the initializer list string
135
+ def get_array_size(array_str: str) -> int:
136
+ # Remove braces and whitespace
137
+ content = array_str.strip()
138
+ if content.startswith("{") and content.endswith("}"):
139
+ content = content[1:-1].strip()
140
+
141
+ if not content: # Empty array
142
+ return 0
143
+
144
+ # Count elements by counting commas, accounting for nested structures
145
+ depth = 0
146
+ comma_count = 0
147
+ for char in content:
148
+ if char in "({[<":
149
+ depth += 1
150
+ elif char in ")}]>":
151
+ depth -= 1
152
+ elif char == "," and depth == 0:
153
+ comma_count += 1
154
+
155
+ return comma_count + 1 # Number of elements = commas + 1
156
+
157
+ threads_size = get_array_size(threads_str)
158
+
159
+ if group_size is None:
160
+ new_args.append("{")
161
+ new_args.append(f" uint64_t {threads_var}[] = {threads};")
162
+ new_args.append(
163
+ f" aoti_torch_mps_dispatch_array(handle, {threads_var}, {threads_size});"
164
+ )
165
+ new_args.append("}")
166
+ else:
167
+ group_size_str = str(group_size)
168
+ group_size_size = get_array_size(group_size_str)
169
+ new_args.append("{")
170
+ new_args.append(f" uint64_t {threads_var}[] = {threads};")
171
+ new_args.append(f" uint64_t {group_size_var}[] = {group_size};")
172
+ dispatch_args = f"handle, {threads_var}, {threads_size}, {group_size_var}, {group_size_size}"
173
+ new_args.append(
174
+ f" aoti_torch_mps_dispatch_array_with_group_size({dispatch_args});"
175
+ )
176
+ new_args.append("}")
177
+
178
+ # debug printer related logic for cpp kernel type.
179
+ debug_printer_manager = V.graph.wrapper_code.debug_printer
180
+ debug_printer_manager.set_printer_args(
181
+ call_args[:-2],
182
+ kernel_name,
183
+ None,
184
+ None,
185
+ "cpp",
186
+ )
187
+ with debug_printer_manager:
188
+ self.write_mps_kernel_call(kernel_name, new_args)
189
+
190
+ def write_mps_kernel_call(self, name: str, call_args: list[str]) -> None:
191
+ # Generate unique variable names to avoid duplicate declarations
192
+ # when the same MPS lib is used multiple times
193
+ unique_suffix = self._lambda_counter
194
+ self._lambda_counter += 1
195
+
196
+ lambda_name = f"{name}_lambda_{unique_suffix}"
197
+ wrapper_name = f"{name}_func_wrapper_{unique_suffix}"
198
+
199
+ # Generate the function call code (in current location)
200
+ # Create lambda that captures by reference and pass its pointer through void*
201
+ self.writeline(
202
+ f"auto {lambda_name} = [&](AOTIMetalKernelFunctionHandle handle) {{"
203
+ )
204
+ self.writeline(" aoti_torch_mps_start_encoding(handle);")
205
+
206
+ # Output call args directly since we're capturing by reference
207
+ for call_arg in call_args:
208
+ self.writeline(f" {call_arg}")
209
+ self.writeline("};")
210
+ self.writeline("")
211
+
212
+ # Pass lambda pointer through void*
213
+ self.writeline(
214
+ f"std::function<void(AOTIMetalKernelFunctionHandle)> {wrapper_name} = {lambda_name};"
215
+ )
216
+ self.writeline(
217
+ f"aoti_torch_mps_run_command_block(get_{name}_handle(), aoti_torch_mps_shared_callback, &{wrapper_name});"
218
+ )
219
+
220
+ @staticmethod
221
+ def get_device_include_path(device: str) -> str:
222
+ assert V.graph.aot_mode
223
+ return (
224
+ "#include <torch/csrc/inductor/aoti_include/mps.h>\n"
225
+ "#include <torch/csrc/inductor/aoti_torch/c/shim_mps.h>"
226
+ )
227
+
228
+ def codegen_additional_funcs(self) -> None:
229
+ """
230
+ Generate thread-safe lazy singleton pattern for MPS shader libraries with RAII cleanup.
231
+
232
+ The generated code will look like:
233
+ ```
234
+ AOTIMetalKernelFunctionHandle get_mps_lib_0_handle() {
235
+ static auto kernel_handle = []() {
236
+ AOTIMetalShaderLibraryHandle lib_handle = nullptr;
237
+ AOTIMetalKernelFunctionHandle kern_handle = nullptr;
238
+
239
+ aoti_torch_mps_create_shader_library(mps_lib_0_source, &lib_handle);
240
+ aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle);
241
+
242
+ // RAII wrapper with custom deleter
243
+ auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) {
244
+ if (h) aoti_torch_mps_delete_shader_library(h);
245
+ };
246
+
247
+ using LibDeleter = decltype(lib_deleter);
248
+ using LibPtr = std::unique_ptr<AOTIMetalShaderLibraryOpaque, LibDeleter>;
249
+
250
+ // Return pair of kernel handle and library smart pointer for cleanup
251
+ return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter));
252
+ }();
253
+ return kernel_handle.first;
254
+ }
255
+ ```
256
+ """
257
+
258
+ # Add shimified handles and functions
259
+ shader_libraries: OrderedSet[str] = OrderedSet()
260
+ for line in self.lines:
261
+ if not isinstance(line, KernelCallLine):
262
+ continue
263
+ if line.device.type != "mps":
264
+ continue
265
+
266
+ # Extract library name from kernel name (e.g., "mps_lib_0" from kernel calls)
267
+ if line.kernel_name not in self._used_kernel_names:
268
+ self._used_kernel_names.add(line.kernel_name)
269
+ shader_libraries.add(line.kernel_name)
270
+
271
+ # NOTE: For shimified version, we expect the shader source constant to be generated
272
+ # by the existing MPS shader generation process, but instead of instantiating the
273
+ # DynamicMetalShaderLibrary directly, we'll use our shim functions.
274
+ # The existing codegen should produce something like:
275
+ # const char* mps_lib_0_source = R"MTL(...shader_source...)MTL";
276
+ # instead of:
277
+ # at::native::mps::DynamicMetalShaderLibrary mps_lib_0(R"MTL(...shader_source...)MTL");
278
+
279
+ # Generate thread-safe lazy singleton with RAII for each library
280
+ for lib_name in shader_libraries:
281
+ self.prefix.splice(f"""
282
+ AOTIMetalKernelFunctionHandle get_{lib_name}_handle() {{
283
+ static auto kernel_handle = []() {{
284
+ AOTIMetalShaderLibraryHandle lib_handle = nullptr;
285
+ AOTIMetalKernelFunctionHandle kern_handle = nullptr;
286
+
287
+ aoti_torch_mps_create_shader_library({lib_name}_source, &lib_handle);
288
+ aoti_torch_mps_get_kernel_function(lib_handle, "generated_kernel", &kern_handle);
289
+
290
+ // RAII wrapper with custom deleter
291
+ auto lib_deleter = [](AOTIMetalShaderLibraryHandle h) {{
292
+ if (h) aoti_torch_mps_delete_shader_library(h);
293
+ }};
294
+
295
+ using LibDeleter = decltype(lib_deleter);
296
+ using LibPtr = std::unique_ptr<AOTIMetalShaderLibraryOpaque, LibDeleter>;
297
+
298
+ // Return pair of kernel handle and library smart pointer for cleanup
299
+ return std::make_pair(kern_handle, LibPtr(lib_handle, lib_deleter));
300
+ }}();
301
+ return kernel_handle.first;
302
+ }}
303
+ """)
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cpu_device_op_overrides.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from textwrap import dedent
4
+
5
+ from .common import DeviceOpOverrides, register_device_op_overrides
6
+
7
+
8
+ class CpuDeviceOpOverrides(DeviceOpOverrides):
9
+ def import_get_raw_stream_as(self, name: str) -> str:
10
+ return dedent(
11
+ """
12
+ def get_raw_stream(_):
13
+ return 0
14
+ """
15
+ )
16
+
17
+ def cpp_kernel_type(self) -> str:
18
+ return "void*"
19
+
20
+ def set_device(self, device_idx: int) -> str:
21
+ return "pass"
22
+
23
+ def synchronize(self) -> str:
24
+ return "pass"
25
+
26
+ def device_guard(self, device_idx: int) -> str:
27
+ return "pass"
28
+
29
+
30
+ register_device_op_overrides("cpu", CpuDeviceOpOverrides())
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/cuda_combined_scheduling.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Optional, TYPE_CHECKING, Union
5
+
6
+ from ..scheduler import (
7
+ BaseSchedulerNode,
8
+ BaseScheduling,
9
+ FusedSchedulerNode,
10
+ Scheduler,
11
+ SchedulerNode,
12
+ )
13
+ from .cutedsl.cutedsl_scheduling import CuteDSLScheduling
14
+ from .cutlass.scheduling import CUTLASSScheduling
15
+ from .nv_universal_gemm.nv_universal_gemm_scheduling import NVUniversalGemmScheduling
16
+ from .rocm.rocm_cpp_scheduling import ROCmCPPScheduling
17
+ from .triton import TritonScheduling
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from collections.abc import Sequence
22
+ from typing import TypeAlias
23
+
24
+ from sympy import Expr
25
+
26
+ import torch
27
+ from torch.utils._ordered_set import OrderedSet
28
+
29
+ from .common import BackendFeature
30
+
31
+ _IntLike: TypeAlias = Union[int, Expr]
32
+
33
+
34
+ class CUDACombinedScheduling(BaseScheduling):
35
+ """
36
+ Scheduler for CUDA Kernels, which delegates calls as appropriate
37
+ to the CUDA-C++ and Triton Schedulers, which both work for CUDA devices
38
+ and use a unified-wrapper for codegen.
39
+
40
+ If Scheduling code needs to be specialized for the case of mixed Triton / CUDA C++ code,
41
+ this would also be the place to do it.
42
+ """
43
+
44
+ def __init__(self, scheduler: Optional[Scheduler]) -> None:
45
+ super().__init__(scheduler)
46
+ self._triton_scheduling = TritonScheduling(scheduler)
47
+ self._cutlass_scheduling = CUTLASSScheduling(scheduler)
48
+ self._rocm_cpp_scheduling = ROCmCPPScheduling(scheduler)
49
+ self._cutedsl_scheduling = CuteDSLScheduling(scheduler)
50
+ self._nv_universal_gemm_scheduling = NVUniversalGemmScheduling(scheduler)
51
+
52
+ def get_backend_features(self, device: torch.device) -> OrderedSet[BackendFeature]:
53
+ return self._triton_scheduling.get_backend_features(device)
54
+
55
+ def choose_node_backend(self, node: BaseSchedulerNode) -> BaseScheduling:
56
+ if self._cutlass_scheduling.is_cutlass_template(node):
57
+ return self._cutlass_scheduling
58
+ if self._rocm_cpp_scheduling.is_rocm_cpp_template(node):
59
+ return self._rocm_cpp_scheduling
60
+ if self._cutedsl_scheduling.is_cutedsl_template(node):
61
+ return self._cutedsl_scheduling
62
+ if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(node):
63
+ return self._nv_universal_gemm_scheduling
64
+ return self._triton_scheduling
65
+
66
+ def can_fuse_vertical(
67
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
68
+ ) -> bool:
69
+ if self._cutlass_scheduling.can_fuse_vertical(node1, node2):
70
+ return True
71
+ elif self._cutlass_scheduling.is_cutlass_template(
72
+ node1
73
+ ) or self._cutlass_scheduling.is_cutlass_template(node2):
74
+ return False
75
+ # CuteDSL doesn't support vertical fusion currently
76
+ elif self._cutedsl_scheduling.is_cutedsl_template(
77
+ node1
78
+ ) or self._cutedsl_scheduling.is_cutedsl_template(node2):
79
+ return False
80
+ # NVIDIA Universal GEMM doesn't support vertical fusion currently
81
+ elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(
82
+ node1
83
+ ) or self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(node2):
84
+ return False
85
+ return self._triton_scheduling.can_fuse_vertical(node1, node2)
86
+
87
+ def can_fuse_horizontal(
88
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
89
+ ) -> bool:
90
+ for node in (node1, node2):
91
+ if self._cutlass_scheduling.is_cutlass_template(node):
92
+ return self._cutlass_scheduling.can_fuse_horizontal(
93
+ node1, node2
94
+ ) # always False at the moment
95
+ if self._cutedsl_scheduling.is_cutedsl_template(node):
96
+ return self._cutedsl_scheduling.can_fuse_horizontal(
97
+ node1, node2
98
+ ) # always False at the moment
99
+ if self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(node):
100
+ return self._nv_universal_gemm_scheduling.can_fuse_horizontal(
101
+ node1, node2
102
+ ) # always False at the moment
103
+ return self._triton_scheduling.can_fuse_horizontal(node1, node2)
104
+
105
+ def group_fn(
106
+ self, sizes: Sequence[Sequence[_IntLike]]
107
+ ) -> tuple[tuple[_IntLike, ...], ...]:
108
+ return self._triton_scheduling.group_fn(sizes)
109
+
110
+ def codegen_template(
111
+ self,
112
+ template_node: BaseSchedulerNode,
113
+ epilogue_nodes: Sequence[BaseSchedulerNode],
114
+ prologue_nodes: Sequence[BaseSchedulerNode],
115
+ ) -> Optional[str]:
116
+ if self._cutlass_scheduling.is_cutlass_template(template_node):
117
+ assert not prologue_nodes
118
+ return self._cutlass_scheduling.codegen_template(
119
+ template_node, epilogue_nodes, prologue_nodes
120
+ )
121
+ elif self._rocm_cpp_scheduling.is_rocm_cpp_template(template_node):
122
+ assert not epilogue_nodes
123
+ assert not prologue_nodes
124
+ return self._rocm_cpp_scheduling.codegen_template(
125
+ template_node, epilogue_nodes, prologue_nodes
126
+ )
127
+ elif self._cutedsl_scheduling.is_cutedsl_template(template_node):
128
+ # TODO remove this when we add epilogue support
129
+ assert not epilogue_nodes
130
+ assert not prologue_nodes
131
+ return self._cutedsl_scheduling.codegen_template(
132
+ template_node, epilogue_nodes, prologue_nodes
133
+ )
134
+ elif self._nv_universal_gemm_scheduling.is_nv_universal_gemm_template(
135
+ template_node
136
+ ):
137
+ # NVIDIA Universal GEMM doesn't support epilogue/prologue fusion yet
138
+ assert not epilogue_nodes
139
+ assert not prologue_nodes
140
+ return self._nv_universal_gemm_scheduling.codegen_template(
141
+ template_node, epilogue_nodes, prologue_nodes
142
+ )
143
+ else:
144
+ return self._triton_scheduling.codegen_template(
145
+ template_node, epilogue_nodes, prologue_nodes
146
+ )
147
+
148
+ def codegen_mix_order_reduction(self, node):
149
+ return self._triton_scheduling.codegen_mix_order_reduction(node)
150
+
151
+ def codegen_node(self, node: Union[FusedSchedulerNode, SchedulerNode]) -> None:
152
+ return self._triton_scheduling.codegen_node(node)
153
+
154
+ def codegen_sync(self) -> None:
155
+ return self._triton_scheduling.codegen_sync()
156
+
157
+ def flush(self) -> None:
158
+ return self._triton_scheduling.flush()
159
+
160
+ def codegen_combo_kernel(self, *args: Any, **kwargs: Any) -> None:
161
+ return self._triton_scheduling.codegen_combo_kernel(*args, **kwargs)
162
+
163
+ def benchmark_fused_nodes(
164
+ self, nodes: Sequence[BaseSchedulerNode]
165
+ ) -> tuple[float, str]:
166
+ return self._triton_scheduling.benchmark_fused_nodes(nodes)
167
+
168
+ def benchmark_codegened_module(self, module):
169
+ return self._triton_scheduling.benchmark_codegened_module(module)
170
+
171
+ def generate_kernel_code_from_nodes(
172
+ self,
173
+ nodes: Sequence[Any],
174
+ benchmark_kernel: bool = False,
175
+ hint_override: Optional[int] = None,
176
+ ) -> str:
177
+ return self._triton_scheduling.generate_kernel_code_from_nodes(
178
+ nodes, benchmark_kernel, hint_override=hint_override
179
+ )
180
+
181
+ def benchmark_combo_kernel(
182
+ self, node_list: Sequence[BaseSchedulerNode], node_benchmark_results
183
+ ) -> tuple[float, float, list[Optional[str]]]:
184
+ return self._triton_scheduling.benchmark_combo_kernel(
185
+ node_list, node_benchmark_results
186
+ )
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/custom_extern_kernel_codegen.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom extern kernel codegen registry.
3
+
4
+ This module provides a registry that maps operators to their custom codegen
5
+ implementations. This allows us to keep all custom implementations in one place
6
+ and easily extend support for both Python and C++ wrappers.
7
+
8
+ To add a new custom implementation:
9
+ 1. Create a codegen function with signature:
10
+ def my_codegen(node: ir.FallbackKernel, writeline: Callable[[str], None]) -> None:
11
+ 2. Register it in CUSTOM_EXTERN_KERNEL_CODEGEN with the operator name as key
12
+
13
+ Example:
14
+ CUSTOM_EXTERN_KERNEL_CODEGEN = {
15
+ "torch.ops.higher_order.print": CustomCodegen(
16
+ python=generate_print_python,
17
+ cpp=generate_print_cpp, # Optional
18
+ ),
19
+ }
20
+
21
+ Usage:
22
+ codegen = CUSTOM_EXTERN_KERNEL_CODEGEN[op]
23
+ codegen.python(node, writeline) # Direct attribute access
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from dataclasses import dataclass
29
+ from typing import Any, TYPE_CHECKING
30
+
31
+
32
+ if TYPE_CHECKING:
33
+ from collections.abc import Callable
34
+
35
+ from .. import ir
36
+
37
+ # Type alias for codegen function signature (only used for type checking)
38
+ CodegenFunc = Callable[[ir.FallbackKernel, Callable[[str], None]], None]
39
+
40
+
41
+ @dataclass
42
+ class CustomCodegen:
43
+ """
44
+ Container for custom codegen implementations.
45
+
46
+ Attributes:
47
+ python: Codegen function for Python wrapper (optional)
48
+ cpp: Codegen function for C++ wrapper (optional)
49
+ """
50
+
51
+ python: Any = None
52
+ cpp: Any = None
53
+
54
+
55
+ def generate_print_python(
56
+ node: ir.FallbackKernel,
57
+ writeline: Callable[[str], None],
58
+ ) -> None:
59
+ """
60
+ Generate a builtin print call for the print HOP fallback (Python wrapper).
61
+
62
+ This function generates Python code that calls the builtin print function
63
+ with format string interpolation.
64
+
65
+ Args:
66
+ node: The FallbackKernel IR node representing the print HOP call.
67
+ writeline: A function that writes a line of code to the output buffer.
68
+
69
+ Example generated code:
70
+ print('x = {}, y = {}'.format(buf0, buf1))
71
+ print('x = {x}, y = {y}'.format(x=buf0, y=buf1))
72
+ print('x = {}, y = {y}'.format(buf0, y=buf1))
73
+ """
74
+ codegen_args: list[str] = node.codegen_args()
75
+ codegen_kwargs: list[str] = node.codegen_kwargs()
76
+
77
+ # First arg is the format string
78
+ if not codegen_args:
79
+ raise ValueError(
80
+ "generate_print_python requires a format string as the first positional argument"
81
+ )
82
+ format_str: str = codegen_args[0]
83
+
84
+ # Remaining args are positional arguments for .format()
85
+ positional_args = codegen_args[1:]
86
+
87
+ args_str = ", ".join(positional_args + codegen_kwargs)
88
+ writeline(
89
+ f"print({format_str}.format({args_str}))"
90
+ if args_str
91
+ else f"print({format_str})"
92
+ )
93
+
94
+
95
+ # Registry mapping operator names to their custom codegen implementations
96
+ # Usage: CUSTOM_EXTERN_KERNEL_CODEGEN[op_name].python(node, writeline)
97
+ CUSTOM_EXTERN_KERNEL_CODEGEN: dict[str, CustomCodegen] = {
98
+ "torch.ops.higher_order.print": CustomCodegen(
99
+ python=generate_print_python,
100
+ ),
101
+ }
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/debug_utils.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import functools
5
+ import logging
6
+ import os
7
+ from enum import Enum
8
+ from typing import Optional, TYPE_CHECKING
9
+
10
+ import torch
11
+ from torch import dtype as torch_dtype
12
+
13
+ from .. import config
14
+ from ..virtualized import V
15
+ from .multi_kernel import MultiKernel
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Callable
20
+
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+
25
+ def _print_debugging_tensor_value_info(msg, arg):
26
+ # helper for printing debugging stats for intermediate tensor values
27
+ # at jit inductor level codegen
28
+ max_numel_to_print = 64
29
+ print(msg)
30
+ if not isinstance(arg, torch.Tensor):
31
+ print("Value: ", arg)
32
+ return
33
+ numel = arg.float().numel()
34
+ # print the debug printing stats
35
+ if numel <= max_numel_to_print:
36
+ print(arg)
37
+ print("Number of elements: ", numel)
38
+ print("Size: ", arg.float().size())
39
+ print("Dtype: ", arg.float().mean().item())
40
+ print("Mean: ", arg.float().mean().item())
41
+ print("Min: ", arg.float().min().item())
42
+ print("Max: ", arg.float().max().item())
43
+ print("Std: ", arg.float().std().item())
44
+
45
+
46
+ # AOTI debug printing related configs
47
+ class IntermediateValueDebuggingLevel(Enum):
48
+ # OFF: No intermediate tensor value debug info will be printed or saved.
49
+ OFF = "0"
50
+ # LEVEL 1: Save all intermediate tensor values to individual `.pt` files. No debug printing will be displayed.
51
+ SAVE_ONLY = "1"
52
+ # LEVEL 2: Print all intermediate tensor values by default to the console. No debug saving will be performed.
53
+ PRINT_ONLY = "2"
54
+ # LEVEL 3: Print all kernel names to the console only. No debug saving/printing for input tensor value info will be performed.
55
+ # This mode can be helpful in cases when you just want to pinpointing what kernel is running into a CUDA IMA issue, etc.
56
+ PRINT_KERNEL_NAMES_ONLY = "3"
57
+
58
+
59
+ class DebugPrinterManager:
60
+ def __init__(
61
+ self,
62
+ debug_printer_level,
63
+ use_array_ref: bool,
64
+ writeline: Optional[Callable[..., None]] = None,
65
+ args_to_print_or_save: Optional[list[str]] = None,
66
+ kernel_name: str = "",
67
+ kernel=None,
68
+ arg_signatures: Optional[list[type]] = None,
69
+ kernel_type=None,
70
+ ):
71
+ self.debug_printer_level = IntermediateValueDebuggingLevel(debug_printer_level)
72
+ self.use_array_ref = use_array_ref
73
+ if args_to_print_or_save is None:
74
+ args_to_print_or_save = []
75
+ self.args_to_print_or_save = args_to_print_or_save
76
+ self.kernel_name = kernel_name
77
+ self.arg_signatures: Optional[list[type]] = None
78
+ self.kernel = kernel
79
+ self.filtered_kernel_names_to_print = self._get_debug_filtered_kernel_names()
80
+ self.kernel_type = None
81
+
82
+ def __enter__(self):
83
+ self._perform_debug_print_or_save_helper(
84
+ self.args_to_print_or_save,
85
+ self.kernel_name,
86
+ before_launch=True,
87
+ arg_signatures=self.arg_signatures,
88
+ )
89
+
90
+ def __exit__(self, args_to_print_or_save, kernel_name, arg_signatures):
91
+ self._perform_debug_print_or_save_helper(
92
+ args_to_print_or_save,
93
+ kernel_name,
94
+ before_launch=False,
95
+ arg_signatures=arg_signatures,
96
+ )
97
+
98
+ def _perform_debug_print_or_save_helper(
99
+ self,
100
+ args_to_print_or_save,
101
+ kernel_name,
102
+ before_launch,
103
+ arg_signatures: Optional[list[type]] = None,
104
+ ):
105
+ if self.debug_printer_level == IntermediateValueDebuggingLevel.OFF:
106
+ return
107
+ if self.debug_printer_level == IntermediateValueDebuggingLevel.SAVE_ONLY:
108
+ # by default save all the tensor values before launch
109
+ self.codegen_intermediate_tensor_value_save(
110
+ self.args_to_print_or_save,
111
+ self.kernel_name,
112
+ before_launch,
113
+ arg_signatures=self.arg_signatures,
114
+ )
115
+ if self.debug_printer_level == IntermediateValueDebuggingLevel.PRINT_ONLY:
116
+ # by default print all the tensor values before launch
117
+ self.codegen_intermediate_tensor_value_print(
118
+ self.args_to_print_or_save,
119
+ self.kernel_name,
120
+ before_launch,
121
+ arg_signatures=self.arg_signatures,
122
+ )
123
+ if (
124
+ self.debug_printer_level
125
+ == IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY
126
+ ):
127
+ # Print all kernel names to the console only
128
+ self.codegen_intermediate_tensor_value_print(
129
+ [],
130
+ self.kernel_name,
131
+ before_launch,
132
+ )
133
+
134
+ @functools.lru_cache # noqa: B019
135
+ def _get_debug_filtered_kernel_names(self) -> list[str]:
136
+ if config.aot_inductor.filtered_kernel_names is None:
137
+ return []
138
+ return [
139
+ x.strip()
140
+ for x in config.aot_inductor.filtered_kernel_names.lower().split(",")
141
+ ]
142
+
143
+ def set_printer_args(
144
+ self,
145
+ args_to_print_or_save: list[str],
146
+ kernel_name: str,
147
+ arg_signatures: Optional[list[type]],
148
+ kernel,
149
+ kernel_type=None,
150
+ ):
151
+ # Note: MultiKernel debug printing is not supported for now
152
+ if isinstance(kernel, MultiKernel):
153
+ log.info(
154
+ "MultiKernel type is not supported in AOTI debug printer tool yet."
155
+ )
156
+ self.debug_printer_level = IntermediateValueDebuggingLevel.OFF
157
+
158
+ self.kernel_type = kernel_type
159
+ # Note: if the kernel type is an extern kernel (or cpp kernel), we do a special handling to
160
+ # get the list of args_to_print_or_save
161
+ # TODO: Find a more reliable way to detect kernel args types to print for extern kernel calls
162
+ if kernel_type == "extern":
163
+ args_to_print_or_save_extern = [
164
+ arg
165
+ for arg in args_to_print_or_save
166
+ if isinstance(arg, str) and arg.startswith(("buf", "arg"))
167
+ ]
168
+ self.args_to_print_or_save = args_to_print_or_save_extern
169
+ elif kernel_type == "cpp":
170
+ self.args_to_print_or_save = [
171
+ (
172
+ f"copy_arrayref_tensor_to_tensor({arg})"
173
+ if self.use_array_ref
174
+ else arg
175
+ )
176
+ for arg in args_to_print_or_save
177
+ if isinstance(arg, str) and arg.startswith(("buf", "arg"))
178
+ ]
179
+ else:
180
+ self.args_to_print_or_save = args_to_print_or_save
181
+ self.kernel_name = kernel_name
182
+ self.arg_signatures = arg_signatures
183
+ self.kernel = kernel
184
+
185
+ def codegen_model_inputs_value_print(self, input_args_to_print: list[str]) -> None:
186
+ if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY:
187
+ return
188
+ for arg in input_args_to_print:
189
+ if V.graph.cpp_wrapper:
190
+ V.graph.wrapper_code.prefix.writeline(
191
+ f'aoti_torch_print_tensor_handle({arg}, "aoti_model_inputs - {arg}");'
192
+ )
193
+
194
+ def codegen_intermediate_tensor_value_save(
195
+ self,
196
+ args_to_save,
197
+ kernel_name,
198
+ before_launch=True,
199
+ arg_signatures: Optional[list[type]] = None,
200
+ ) -> None:
201
+ for i, arg in enumerate(args_to_save):
202
+ if arg_signatures is not None and not isinstance(
203
+ arg_signatures[i], torch_dtype
204
+ ):
205
+ # infer from the arg data type (has torch.dtype) to see if it is a tensor type
206
+ continue
207
+ launch_prefix = "before_launch" if before_launch else "after_launch"
208
+ if V.graph.cpp_wrapper:
209
+ V.graph.wrapper_code.writeline(
210
+ f'aoti_torch_save_tensor_handle({arg}, "{arg}", "{launch_prefix}", "{kernel_name}");'
211
+ )
212
+ else:
213
+ cwd = os.getcwd()
214
+ saved_dir = cwd + "/tmp/jit_inductor/"
215
+ if not os.path.exists(saved_dir):
216
+ log.info(
217
+ "Creating directory to save inductor intermediate tensor values."
218
+ )
219
+ os.makedirs(saved_dir)
220
+ # Save the model to the directory
221
+ saved_path = saved_dir + f"{launch_prefix}_{kernel_name}_{arg}.pt"
222
+ log.info(
223
+ "Saved intermediate tensor %s for %s to %s",
224
+ arg,
225
+ kernel_name,
226
+ saved_path,
227
+ )
228
+ line = f"torch.save({arg}, '{saved_path}')"
229
+ V.graph.wrapper_code.writeline(line)
230
+
231
+ def codegen_intermediate_tensor_value_print(
232
+ self,
233
+ args_to_print,
234
+ kernel_name,
235
+ before_launch=True,
236
+ arg_signatures: Optional[list[type]] = None,
237
+ ) -> None:
238
+ launch_prefix = "before_launch" if before_launch else "after_launch"
239
+
240
+ # if the debug printing level is PRINT_KERNEL_NAMES_ONLY
241
+ # we only print the kernel name to the console
242
+ if (
243
+ self.debug_printer_level
244
+ == IntermediateValueDebuggingLevel.PRINT_KERNEL_NAMES_ONLY
245
+ ):
246
+ if V.graph.cpp_wrapper:
247
+ V.graph.wrapper_code.writeline(
248
+ f'printf("[ {launch_prefix}: {kernel_name} ]\\n");'
249
+ )
250
+ return
251
+
252
+ if self.debug_printer_level != IntermediateValueDebuggingLevel.PRINT_ONLY:
253
+ return
254
+ for i, arg in enumerate(args_to_print):
255
+ # when debug printing is enabled i.e. IntermediateValueDebuggingLevel.PRINT_ONLY,
256
+ # check if filtered kernel name list is provided
257
+ if (
258
+ len(self.filtered_kernel_names_to_print) > 0
259
+ and kernel_name.lower() not in self.filtered_kernel_names_to_print
260
+ ):
261
+ continue
262
+ if V.graph.cpp_wrapper:
263
+ if arg_signatures is not None and isinstance(
264
+ arg_signatures[i], torch_dtype
265
+ ):
266
+ # infer from the arg data type (has torch.dtype) to see if it is a tensor type
267
+ V.graph.wrapper_code.writeline(
268
+ f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");'
269
+ )
270
+ elif arg_signatures is not None and isinstance(
271
+ arg_signatures[i],
272
+ (
273
+ type(torch._inductor.codegen.wrapper.SymbolicCallArg),
274
+ type(int),
275
+ type(float),
276
+ type(bool),
277
+ ),
278
+ ):
279
+ V.graph.wrapper_code.writeline(
280
+ f'printf("[ {launch_prefix} - {kernel_name} - {arg}: %ld ]", {arg}); printf("\\\\n");'
281
+ )
282
+ else:
283
+ if arg_signatures is None and self.kernel_type in ("cpp", "extern"):
284
+ V.graph.wrapper_code.writeline(
285
+ f'aoti_torch_print_tensor_handle({arg}, "{launch_prefix} - {kernel_name} - {arg}");'
286
+ )
287
+ else:
288
+ V.graph.wrapper_code.writeline(
289
+ f'_print_debugging_tensor_value_info("inductor: {launch_prefix} - {kernel_name} - {arg}", {arg})'
290
+ )
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/halide.py ADDED
@@ -0,0 +1,1760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import dataclasses
5
+ import functools
6
+ import itertools
7
+ import logging
8
+ import re
9
+ from collections import defaultdict
10
+ from math import inf
11
+ from typing import Any, cast, Optional, TYPE_CHECKING, Union
12
+
13
+ import sympy
14
+
15
+ import torch
16
+ import torch._logging
17
+
18
+ from ..._prims_common import is_integer_dtype
19
+ from ...utils._ordered_set import OrderedSet
20
+ from ...utils._sympy.functions import FloorDiv, ModularIndexing
21
+ from ...utils._sympy.symbol import symbol_is_type, SymT
22
+ from ...utils._sympy.value_ranges import ValueRanges
23
+ from .. import config, ir
24
+ from ..codecache import HalideCodeCache
25
+ from ..ir import get_reduction_combine_fn
26
+ from ..metrics import is_metric_table_enabled, log_kernel_metadata
27
+ from ..ops_handler import AddParenHandler
28
+ from ..runtime.hints import HalideInputSpec, HalideMeta
29
+ from ..utils import (
30
+ get_bounds_index_expr,
31
+ get_kernel_metadata,
32
+ parallel_num_threads,
33
+ sympy_index_symbol,
34
+ sympy_subs,
35
+ )
36
+ from ..virtualized import _ops as ops, V
37
+ from .common import (
38
+ BackendFeature,
39
+ CSEVariable,
40
+ DeferredLine,
41
+ IndentedBuffer,
42
+ KernelArgType,
43
+ OpOverrides,
44
+ PythonPrinter,
45
+ SizeArg,
46
+ TensorArg,
47
+ )
48
+ from .cpp import DTYPE_TO_CPP
49
+ from .cpp_utils import cexpr
50
+ from .simd import constant_repr, SIMDKernel, SIMDScheduling
51
+
52
+
53
+ if TYPE_CHECKING:
54
+ from collections.abc import Callable, Sequence
55
+
56
+ from ..ops_handler import ReductionType, StoreMode
57
+ from ..shape_propagation import BlockShapeType
58
+
59
+ log = logging.getLogger(__name__)
60
+
61
+
62
+ def halide_constant(val):
63
+ if isinstance(val, int) and not (-2147483648 <= val <= 2147483647):
64
+ info = torch.iinfo(torch.int64)
65
+ if val == info.min:
66
+ return "hl.Int(64).min()"
67
+ if val == info.max:
68
+ return "hl.Int(64).max()"
69
+ return f"hl.i64({val!r})"
70
+ if isinstance(val, float):
71
+ return f"hl.f64({constant_repr(val)})"
72
+ return repr(val)
73
+
74
+
75
+ class Unsupported(RuntimeError):
76
+ def __init__(self, thing) -> None:
77
+ super().__init__(f"halide backend does not support: {thing}")
78
+
79
+
80
+ class HalidePrinter(PythonPrinter): # noqa: docstring_linter
81
+ @staticmethod
82
+ def cast_index(expr):
83
+ return f"hl.cast({V.kernel.index_dtype}, {expr})"
84
+
85
+ @staticmethod
86
+ def cast_float(expr):
87
+ return f"hl.cast(hl.Float(32), {expr})"
88
+
89
+ def _print_Float(self, expr):
90
+ return f"hl.f32({expr})"
91
+
92
+ def _print_ToFloat(self, expr):
93
+ assert len(expr.args) == 1
94
+ # pyrefly: ignore [missing-attribute]
95
+ return f"hl.f32({self._print(expr.args[0])})"
96
+
97
+ def _print_floor(self, expr):
98
+ assert len(expr.args) == 1
99
+ # pyrefly: ignore [missing-attribute]
100
+ return self.cast_index(f"hl.floor({self._print(expr.args[0])})")
101
+
102
+ _print_FloorToInt = _print_floor
103
+
104
+ def _print_Trunc(self, expr):
105
+ assert len(expr.args) == 1
106
+ # pyrefly: ignore [missing-attribute]
107
+ return self.cast_index(f"hl.trunc({self._print(expr.args[0])})")
108
+
109
+ _print_TruncToInt = _print_Trunc
110
+
111
+ def _print_ceiling(self, expr):
112
+ assert len(expr.args) == 1
113
+ # pyrefly: ignore [missing-attribute]
114
+ return self.cast_index(f"hl.ceil({self._print(expr.args[0])})")
115
+
116
+ def _helper_sqrt(self, expr):
117
+ # pyrefly: ignore [missing-attribute]
118
+ return f"hl.sqrt({self.cast_float(self._print(expr))})"
119
+
120
+ def _print_Where(self, expr):
121
+ c = self.doprint(expr.args[0])
122
+ p = self.doprint(expr.args[1])
123
+ q = self.doprint(expr.args[2])
124
+ return f"hl.select({c}, {p}, {q})"
125
+
126
+ def _print_Min(self, expr):
127
+ if len(expr.args) == 1:
128
+ # pyrefly: ignore [missing-attribute]
129
+ return self._print(expr.args[0])
130
+
131
+ mid = len(expr.args) // 2
132
+ # pyrefly: ignore [missing-attribute]
133
+ a = self._print(sympy.Min(*expr.args[:mid]))
134
+ # pyrefly: ignore [missing-attribute]
135
+ b = self._print(sympy.Min(*expr.args[mid:]))
136
+ return f"hl.min({a}, {b})"
137
+
138
+ def _print_Max(self, expr):
139
+ if len(expr.args) == 1:
140
+ # pyrefly: ignore [missing-attribute]
141
+ return self._print(expr.args[0])
142
+
143
+ mid = len(expr.args) // 2
144
+ # pyrefly: ignore [missing-attribute]
145
+ a = self._print(sympy.Max(*expr.args[:mid]))
146
+ # pyrefly: ignore [missing-attribute]
147
+ b = self._print(sympy.Max(*expr.args[mid:]))
148
+
149
+ return f"hl.max({a}, {b})"
150
+
151
+ def _print_Abs(self, expr):
152
+ assert len(expr.args) == 1
153
+ # pyrefly: ignore [missing-attribute]
154
+ return self.cast_index(f"hl.abs({self._print(expr.args[0])})")
155
+
156
+ def _print_OpaqueUnaryFn_cos(self, expr):
157
+ assert len(expr.args) == 1
158
+ # pyrefly: ignore [missing-attribute]
159
+ return f"hl.cos({self._print(expr.args[0])})"
160
+
161
+ def _print_OpaqueUnaryFn_cosh(self, expr):
162
+ assert len(expr.args) == 1
163
+ # pyrefly: ignore [missing-attribute]
164
+ return f"hl.cosh({self._print(expr.args[0])})"
165
+
166
+ def _print_OpaqueUnaryFn_acos(self, expr):
167
+ assert len(expr.args) == 1
168
+ # pyrefly: ignore [missing-attribute]
169
+ return f"hl.acos({self._print(expr.args[0])})"
170
+
171
+ def _print_OpaqueUnaryFn_sin(self, expr):
172
+ assert len(expr.args) == 1
173
+ # pyrefly: ignore [missing-attribute]
174
+ return f"hl.sin({self._print(expr.args[0])})"
175
+
176
+ def _print_OpaqueUnaryFn_sinh(self, expr):
177
+ assert len(expr.args) == 1
178
+ # pyrefly: ignore [missing-attribute]
179
+ return f"hl.sinh({self._print(expr.args[0])})"
180
+
181
+ def _print_OpaqueUnaryFn_asin(self, expr):
182
+ assert len(expr.args) == 1
183
+ # pyrefly: ignore [missing-attribute]
184
+ return f"hl.asin({self._print(expr.args[0])})"
185
+
186
+ def _print_OpaqueUnaryFn_tan(self, expr):
187
+ assert len(expr.args) == 1
188
+ # pyrefly: ignore [missing-attribute]
189
+ return f"hl.tan({self._print(expr.args[0])})"
190
+
191
+ def _print_OpaqueUnaryFn_tanh(self, expr):
192
+ assert len(expr.args) == 1
193
+ # pyrefly: ignore [missing-attribute]
194
+ return f"hl.tanh({self._print(expr.args[0])})"
195
+
196
+ def _print_OpaqueUnaryFn_atan(self, expr):
197
+ assert len(expr.args) == 1
198
+ # pyrefly: ignore [missing-attribute]
199
+ return f"hl.atan({self._print(expr.args[0])})"
200
+
201
+ def _print_OpaqueUnaryFn_log2(self, expr):
202
+ raise NotImplementedError("log2")
203
+
204
+ def _print_FloorDiv(self, expr):
205
+ if expr.is_integer:
206
+ return super()._print_FloorDiv(expr)
207
+
208
+ x, div = expr.args
209
+ x = self.cast_float(self.doprint(x))
210
+ div = self.cast_float(self.doprint(div))
211
+ return self.cast_index(f"hl.floor({x} / {div})")
212
+
213
+ def _print_Round(self, expr):
214
+ assert len(expr.args) == 1
215
+ # pyrefly: ignore [missing-attribute]
216
+ return self.cast_index(f"hl.round({self._print(expr.args[0])})")
217
+
218
+ _print_RoundToInt = _print_Round
219
+
220
+ def _print_IntTrueDiv(self, expr):
221
+ a, b = expr.args
222
+ # force a cast to float
223
+ return f"({a}) / ({b}+hl.f32(0))"
224
+
225
+ def _print_RoundDecimal(self, expr):
226
+ val, n = expr.args
227
+ # pyrefly: ignore [missing-attribute]
228
+ val = self._print(val)
229
+ n = int(n)
230
+ return f"hl.f32({10.0 ** (-n)!r})*hl.round(({val})*hl.f32({10.0**n!r}))"
231
+
232
+
233
+ texpr = HalidePrinter().doprint
234
+ pexpr = PythonPrinter().doprint
235
+
236
+
237
+ _halide_type = {
238
+ torch.bool: "hl.Bool()",
239
+ torch.bfloat16: "hl.BFloat(16)",
240
+ torch.float16: "hl.Float(16)",
241
+ torch.float32: "hl.Float(32)",
242
+ torch.float64: "hl.Float(64)",
243
+ torch.int8: "hl.Int(8)",
244
+ torch.int16: "hl.Int(16)",
245
+ torch.int32: "hl.Int(32)",
246
+ torch.int64: "hl.Int(64)",
247
+ torch.uint8: "hl.UInt(8)",
248
+ torch.uint16: "hl.UInt(16)",
249
+ torch.uint32: "hl.UInt(32)",
250
+ torch.uint64: "hl.UInt(64)",
251
+ }
252
+
253
+
254
+ def halide_type(dtype):
255
+ return _halide_type[dtype]
256
+
257
+
258
+ def halide_acc_type(dtype):
259
+ if is_integer_dtype(dtype) and dtype.is_signed and dtype != torch.int64:
260
+ dtype = torch.int32
261
+ if dtype in (torch.float16, torch.bfloat16):
262
+ dtype = torch.float32
263
+ return halide_type(dtype)
264
+
265
+
266
+ class HalideOverrides(OpOverrides):
267
+ @staticmethod
268
+ def to_dtype(
269
+ x,
270
+ dtype: torch.dtype,
271
+ src_dtype: Optional[torch.dtype] = None,
272
+ use_compute_types=True,
273
+ ):
274
+ if dtype == torch.bool:
275
+ return f"({x} != 0)"
276
+ return f"hl.cast({halide_type(dtype)}, {x})"
277
+
278
+ @staticmethod
279
+ def to_dtype_bitcast(x, dtype: torch.dtype, src_dtype: torch.dtype):
280
+ if src_dtype in (torch.float16, torch.bfloat16):
281
+ x = f"hl.cast({halide_type(src_dtype)}, {x})" # body compute is upcast to fp32
282
+ line = f"hl.reinterpret({halide_type(dtype)}, {x})"
283
+ if dtype in (torch.float16, torch.bfloat16):
284
+ line = f"hl.cast(hl.Float(32), {line})"
285
+ return line
286
+
287
+ @classmethod
288
+ def constant(cls, value, dtype):
289
+ return cls.to_dtype(halide_constant(value), dtype)
290
+
291
+ @staticmethod
292
+ def abs(x):
293
+ return f"hl.abs({x})"
294
+
295
+ @staticmethod
296
+ def exp(x):
297
+ if not hasattr(x, "name"):
298
+ return f"hl.exp({x})"
299
+ return f"hl.fast_exp(hl.cast(hl.Float(32), {x})) if {x.name}.type().bits() <= 32 else hl.exp({x})"
300
+
301
+ @staticmethod
302
+ def sqrt(x):
303
+ return f"hl.sqrt({x})"
304
+
305
+ @staticmethod
306
+ def minimum(a, b):
307
+ # return f"hl.min({a}, {b})" <== handles nan wrong
308
+ if not hasattr(a, "name"):
309
+ return f"hl.min({a}, {b})"
310
+ b = f"hl.cast({a.name}.type(), {b})"
311
+ return f"hl.select(({a}<{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.min({a}, {b})"
312
+
313
+ @staticmethod
314
+ def maximum(a, b):
315
+ # return f"hl.max({a}, {b})" <== handles nan wrong
316
+ if not hasattr(a, "name"):
317
+ return f"hl.max({a}, {b})"
318
+ b = f"hl.cast({a.name}.type(), {b})"
319
+ return f"hl.select(({a}>{b})|hl.is_nan({a}), {a}, {b}) if {a.name}.type().is_float() else hl.max({a}, {b})"
320
+
321
+ @staticmethod
322
+ def where(a, b, c):
323
+ if hasattr(b, "name"):
324
+ c = f"hl.cast({b.name}.type(), {c})"
325
+ return f"hl.select({a}, {b}, {c})"
326
+
327
+ @staticmethod
328
+ def cos(x):
329
+ return f"hl.cos({x})"
330
+
331
+ @staticmethod
332
+ def sin(x):
333
+ return f"hl.sin({x})"
334
+
335
+ @staticmethod
336
+ def lgamma(x):
337
+ raise Unsupported("lgamma")
338
+
339
+ @staticmethod
340
+ def erf(x):
341
+ return f"hl.erf({x})"
342
+
343
+ @staticmethod
344
+ def cosh(x):
345
+ return f"hl.cosh({x})"
346
+
347
+ @staticmethod
348
+ def sinh(x):
349
+ return f"hl.sinh({x})"
350
+
351
+ @staticmethod
352
+ def acos(x):
353
+ return f"hl.acos({x})"
354
+
355
+ @staticmethod
356
+ def acosh(x):
357
+ return f"hl.acosh({x})"
358
+
359
+ @staticmethod
360
+ def asin(x):
361
+ return f"hl.asin({x})"
362
+
363
+ @staticmethod
364
+ def asinh(x):
365
+ return f"hl.asinh({x})"
366
+
367
+ @staticmethod
368
+ def atan2(x, y):
369
+ return f"hl.atan2({x}, {y})"
370
+
371
+ @staticmethod
372
+ def atan(x):
373
+ return f"hl.atan({x})"
374
+
375
+ @staticmethod
376
+ def atanh(x):
377
+ return f"hl.atanh({x})"
378
+
379
+ @staticmethod
380
+ def copysign(x, y):
381
+ raise Unsupported("copysign")
382
+
383
+ @staticmethod
384
+ def erfinv(x):
385
+ raise Unsupported("erfinv")
386
+
387
+ @staticmethod
388
+ def hypot(x, y):
389
+ return f"hl.hypot({x}, {y})"
390
+
391
+ @staticmethod
392
+ def nextafter(x, y):
393
+ raise Unsupported("nextafter")
394
+
395
+ @staticmethod
396
+ def logical_and(a, b):
397
+ return f"{a} & {b}"
398
+
399
+ @staticmethod
400
+ def logical_not(a):
401
+ return f"{a} == 0"
402
+
403
+ @staticmethod
404
+ def logical_or(a, b):
405
+ return f"{a} | {b}"
406
+
407
+ @staticmethod
408
+ def logical_xor(a, b):
409
+ return f"({a} ^ {b})"
410
+
411
+ @staticmethod
412
+ def bitwise_and(a, b):
413
+ return f"{a} & {b}"
414
+
415
+ @staticmethod
416
+ def bitwise_not(a):
417
+ return f"~{a}"
418
+
419
+ @staticmethod
420
+ def bitwise_or(a, b):
421
+ return f"{a} | {b}"
422
+
423
+ @staticmethod
424
+ def bitwise_xor(a, b):
425
+ return f"{a} ^ {b}"
426
+
427
+ @staticmethod
428
+ def bitwise_left_shift(a, b):
429
+ return f"{a} << {b}"
430
+
431
+ @staticmethod
432
+ def bitwise_right_shift(a, b):
433
+ return f"{a} >> {b}"
434
+
435
+ @staticmethod
436
+ def rand(seed, offset):
437
+ return f"halide_helpers.rand({seed}, {offset})"
438
+
439
+ @staticmethod
440
+ def randn(seed, offset):
441
+ return f"halide_helpers.randn({seed}, {offset})"
442
+
443
+ @staticmethod
444
+ def randint64(seed, offset, low, high):
445
+ return f"halide_helpers.randint64({seed}, {offset}, {low}, {high})"
446
+
447
+ @staticmethod
448
+ def load_seed(name, offset):
449
+ return f"{ops.load(name, 0)} + {V.kernel.args.seed_offset('load_seed_offset', offset)}"
450
+
451
+ @staticmethod
452
+ def rsqrt(x):
453
+ # return f"hl.fast_inverse_sqrt({x})" <== accuracy issues
454
+ return f"1./hl.sqrt({x})"
455
+
456
+ @staticmethod
457
+ def tan(x):
458
+ return f"hl.tan({x})"
459
+
460
+ @staticmethod
461
+ def tanh(x):
462
+ return f"hl.tanh({x})"
463
+
464
+ @staticmethod
465
+ def signbit(x):
466
+ return f"(hl.reinterpret(hl.UInt(32), hl.cast(hl.Float(32), {x})) >> 31) != 0"
467
+
468
+ @staticmethod
469
+ def fmod(a, b):
470
+ # TODO(jansel): find a better way to do this, builtin % has wrong sign
471
+ return f"{a} - hl.trunc({a}/{b})*{b}"
472
+
473
+ @staticmethod
474
+ def pow(a, b):
475
+ return f"hl.pow({a}, {b})" # hl.fast_pow fails accuracy
476
+
477
+ @staticmethod
478
+ def ldexp(x, n):
479
+ raise Unsupported("ldexp")
480
+
481
+ @staticmethod
482
+ def log(x):
483
+ return f"hl.log({x})" # hl.fast_log fails accuracy
484
+
485
+ @staticmethod
486
+ def log2(x):
487
+ raise NotImplementedError("log2")
488
+
489
+ @staticmethod
490
+ def isinf(x):
491
+ # workaround https://github.com/halide/Halide/issues/8309
492
+ return f"hl.is_inf(hl.cast(hl.Float(32), {x}))"
493
+
494
+ @staticmethod
495
+ def isnan(x):
496
+ # workaround https://github.com/halide/Halide/issues/8309
497
+ return f"hl.is_nan(hl.cast(hl.Float(32), {x}))"
498
+
499
+ @staticmethod
500
+ def round(x):
501
+ return f"hl.round({x})"
502
+
503
+ @staticmethod
504
+ def floor(x):
505
+ return f"hl.floor({x})"
506
+
507
+ @staticmethod
508
+ def int_truediv(a, b):
509
+ return f"({a}) / ({b} + hl.f32(0))"
510
+
511
+ @staticmethod
512
+ def floordiv(a, b):
513
+ # TODO(jansel): find a better ways to do this, the select-based trick from triton.py didn't work
514
+ return (
515
+ f"hl.floor(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})"
516
+ )
517
+
518
+ @classmethod
519
+ def sign(cls, x):
520
+ left = ops.to_dtype(ops.lt("0", x), torch.int8)
521
+ right = ops.to_dtype(ops.lt(x, "0"), torch.int8)
522
+ sub = ops.sub(left, right)
523
+ return f"hl.cast({x.name}.type(), {sub})"
524
+
525
+ @staticmethod
526
+ def trunc(x):
527
+ return f"hl.trunc({x})"
528
+
529
+ @staticmethod
530
+ def truncdiv(a, b):
531
+ # this causes crashes with floating point exception, see test_div_zero_dim_cpu
532
+ # return f"hl.div_round_to_zero({a}, {b})"
533
+ return (
534
+ f"hl.trunc(hl.cast(hl.Float(max(32, {a.name}.type().bits())), {a}) / {b})"
535
+ )
536
+
537
+ @staticmethod
538
+ def ceil(x):
539
+ return f"hl.ceil({x})"
540
+
541
+ @staticmethod
542
+ def relu(x):
543
+ return f"hl.max({x}, 0)"
544
+
545
+ @classmethod
546
+ def index_expr(cls, expr, dtype):
547
+ index = V.kernel.prepare_indexing(expr)
548
+ var = V.kernel.genfunc(
549
+ V.kernel.index_to_str(index),
550
+ V.kernel.used_dims_from_index(index),
551
+ bounds=get_bounds_index_expr(expr),
552
+ )
553
+ if dtype not in (torch.int32, torch.int64):
554
+ return ops.to_dtype(var, dtype)
555
+ return var
556
+
557
+ @classmethod
558
+ def indirect_indexing(cls, index_var, size, check=True, wrap_neg=True):
559
+ # TODO(jansel): Halide only supports 32-bit indexing, we should error on overflow
560
+ index_var = ops.to_dtype(index_var, torch.int32)
561
+ index_var = ops.halide_clamp(index_var, size, check)
562
+ index_var.indirect_indexing_size = size
563
+ return sympy_index_symbol(str(index_var))
564
+
565
+ @classmethod
566
+ def halide_clamp(cls, value, size, check):
567
+ end = V.kernel.kexpr(V.kernel.rename_indexing(size) - 1)
568
+ if not isinstance(size, (int, sympy.Integer)):
569
+ end = f"hl.cast({value.name}.type(), {end})"
570
+ # Skip unsafe_promise_clamped to workaround: https://github.com/halide/Halide/issues/8261#issuecomment-2148835692
571
+ # return f"hl.unsafe_promise_clamped({value}, 0, {end})"
572
+ return f"hl.clamp({value}, 0, {end})"
573
+
574
+ @staticmethod
575
+ def masked(mask, body, other):
576
+ with V.kernel.mask_loads(mask, other) as new_mask:
577
+ result = body()
578
+
579
+ if result.bounds.is_bool:
580
+ other = bool(other)
581
+
582
+ # Take dtype from result to prevent accidental promotion
583
+ other = V.kernel.genfunc(
584
+ f"hl.cast({result.name}.type(), {halide_constant(other)})",
585
+ [],
586
+ bounds=ValueRanges.wrap(other),
587
+ shape=result.shape,
588
+ )
589
+ # TODO(jansel): look into removing the where in the same places triton does
590
+ return ops.where(new_mask, result, other)
591
+
592
+ @staticmethod
593
+ def frexp(x):
594
+ raise NotImplementedError("frexp")
595
+
596
+ @staticmethod
597
+ def device_assert_async(cond, msg):
598
+ raise NotImplementedError("device_assert_async")
599
+
600
+ @staticmethod
601
+ # pyrefly: ignore [bad-override]
602
+ def partial_accumulate(
603
+ name: str,
604
+ reduction_type: str,
605
+ value: CSEVariable,
606
+ extra_meta: dict[str, Any],
607
+ ) -> None:
608
+ raise NotImplementedError
609
+
610
+
611
+ HalideOverrides._initialize_pointwise_overrides("halide")
612
+
613
+
614
+ class HalideCSEVariable(CSEVariable):
615
+ undefined_re = re.compile(r"\b(tmp\d+)\[\?\]")
616
+
617
+ def __init__(
618
+ self,
619
+ name,
620
+ bounds: ValueRanges[Any],
621
+ dtype: Optional[torch.dtype] = None,
622
+ shape: BlockShapeType = None,
623
+ ) -> None:
624
+ super().__init__(name, bounds, dtype, shape=shape)
625
+ self.used_dims: Optional[list[sympy.Symbol]] = None
626
+
627
+ def update_on_args(self, name, args, kwargs):
628
+ used = OrderedSet(self.used_dims or ())
629
+ for arg in itertools.chain(args, kwargs.values()):
630
+ if isinstance(arg, HalideCSEVariable):
631
+ assert arg.used_dims is not None, (name, arg, args)
632
+ used.update(arg.used_dims)
633
+ self.used_dims = V.kernel.sort_used_dims(used)
634
+
635
+ def index_str(self, dims):
636
+ if len(dims) == 0:
637
+ return f"{self.name}[()]"
638
+ # Reversed since Halide is column major
639
+ return f"{self.name}[{', '.join(map(str, dims))}]"
640
+
641
+ def __str__(self) -> str:
642
+ if self.used_dims is None:
643
+ # This will get recomputed and replaced in codegen_kernel()
644
+ return f"{self.name}[?]"
645
+ return self.index_str(self.used_dims)
646
+
647
+ def subs_str(self, replacements):
648
+ assert self.used_dims is not None and all(
649
+ isinstance(x, sympy.Expr) for x in self.used_dims
650
+ )
651
+ return self.index_str([replacements.get(n, n) for n in self.used_dims])
652
+
653
+
654
+ @dataclasses.dataclass
655
+ class DimensionInfo:
656
+ expr: Optional[sympy.Expr]
657
+ size: sympy.Expr
658
+ stride: sympy.Expr
659
+
660
+ def __init__(self, expr, size, stride) -> None:
661
+ super().__init__()
662
+ if V.graph.sizevars.statically_known_lt(stride, 0):
663
+ stride = -stride
664
+ expr = -expr
665
+ self.expr = expr
666
+ self.size = size
667
+ self.stride = stride
668
+
669
+ def index_str(self, replacements=None, zero_vars=False):
670
+ assert self.expr is not None
671
+ expr = self.expr
672
+ if zero_vars and expr == 0:
673
+ return "hl.Var()"
674
+ if replacements:
675
+ replacements = {**replacements}
676
+ # pyrefly: ignore [missing-attribute]
677
+ for sym in expr.free_symbols:
678
+ if symbol_is_type(sym, SymT.TMP):
679
+ assert isinstance(sym, sympy.Symbol)
680
+ var = V.kernel.lookup_cse_var(sym.name)
681
+ assert isinstance(var, HalideCSEVariable)
682
+ replacements[sym] = sympy_index_symbol(var.subs_str(replacements))
683
+ expr = sympy_subs(expr, replacements)
684
+ return V.kernel.index_to_str(expr)
685
+
686
+
687
+ def eq(left, right):
688
+ if V.graph.sizevars.statically_known_equals(left, right):
689
+ return True
690
+ try:
691
+ a = V.graph.sizevars.size_hint_or_throw(left)
692
+ b = V.graph.sizevars.size_hint_or_throw(right)
693
+ except TypeError: # unbacked symints
694
+ return False
695
+ if a == b:
696
+ V.graph.sizevars.check_equals(left, right)
697
+ return a == b
698
+
699
+
700
+ def lt(left, right):
701
+ if V.graph.sizevars.statically_known_lt(left, right):
702
+ return True
703
+ try:
704
+ a = V.graph.sizevars.size_hint_or_throw(left)
705
+ b = V.graph.sizevars.size_hint_or_throw(right)
706
+ except TypeError: # unbacked symints
707
+ gcd = sympy.gcd(left, right)
708
+ if gcd == left:
709
+ return left != right
710
+ return False
711
+ if a < b:
712
+ V.graph.sizevars.check_lt(left, right)
713
+ return a < b
714
+
715
+
716
+ class HalideKernel(SIMDKernel):
717
+ overrides = HalideOverrides # type: ignore[assignment]
718
+ kexpr: Callable[[sympy.Expr], str] = texpr
719
+
720
+ def __init__(
721
+ self,
722
+ tiling: dict[str, sympy.Expr],
723
+ **kwargs,
724
+ ) -> None:
725
+ super().__init__(tiling, **kwargs)
726
+ # For halide, we just write directly to the body
727
+ self.compute = self.body
728
+ self.loads = self.body
729
+ self.stores = self.body
730
+ self.indexing_code_dom = IndentedBuffer()
731
+ self.needs_dom_indexing = self.inside_reduction
732
+ self.has_reduction = self.inside_reduction
733
+ self.buffer_dimensions: dict[str, list[DimensionInfo]] = {}
734
+ self.buffer_offsets: dict[str, sympy.Expr] = {}
735
+ # {h0: size1, h1: size2, ...}
736
+ self.halide_vars: dict[sympy.Symbol, sympy.Expr] = {}
737
+ # {x0: h0, x1: h1+10*h2, ...}
738
+ self.index_replacements: dict[sympy.Expr, sympy.Expr] = {}
739
+ # {h1: hr1, ...}
740
+ self.reduction_renames: dict[sympy.Symbol, sympy.Symbol] = {}
741
+ # {"i": {h0: hi0}, "o": ...}
742
+ self.dom_renames: dict[str, dict[sympy.Symbol, sympy.Symbol]] = {}
743
+ # {"in_ptr0": ["in_ptr0_view0"], ...}
744
+ self.buffer_aliases: dict[str, list[str]] = defaultdict(list)
745
+ self.has_indirect_indexing = False
746
+
747
+ def dtype_to_str(self, dtype: torch.dtype) -> str:
748
+ return halide_type(dtype)
749
+
750
+ # pyrefly: ignore [bad-override]
751
+ def create_cse_var(self, name, bounds=None, dtype=None, shape=None):
752
+ self.body.writeline(f"{name} = hl.Func({name!r})")
753
+ # pyrefly: ignore [bad-argument-type]
754
+ return HalideCSEVariable(name, bounds, dtype, shape)
755
+
756
+ def finalize_indexing(self, indices: Sequence[sympy.Expr]):
757
+ """
758
+ Hook called right before codegen with every index that will be
759
+ used in the fused kernel.
760
+
761
+ This populates self.halide_vars/index_replacements/reduction_renames which is an alternate indexing
762
+ scheme that avoids using divide and modulus. Instead of xindex/yindex/rindex
763
+ we base indexing on a larger number of vars whose product combines to those.
764
+
765
+ This function populates self.halide_vars, self.index_replacements, and self.reduction_renames
766
+ """
767
+ assert not (
768
+ self.index_replacements or self.halide_vars or self.reduction_renames
769
+ )
770
+ size_hint = functools.partial(V.graph.sizevars.size_hint, fallback=inf) # type: ignore[arg-type]
771
+ # pyrefly: ignore [bad-assignment]
772
+ indices = dict.fromkeys(map(super().prepare_indexing, indices))
773
+ all_used_symbols = OrderedSet[Any]()
774
+ sym_to_node = {
775
+ n.symbol(): n
776
+ for n in itertools.chain.from_iterable(
777
+ [tree.nodes.values() for tree in self.range_trees]
778
+ )
779
+ }
780
+
781
+ def simplify(expr):
782
+ return sympy.simplify(
783
+ V.graph.sizevars.remove_precomputed_replacements(expr)
784
+ )
785
+
786
+ def visit_modular_indexing(base, divisor, modulus):
787
+ if base in sym_to_node:
788
+ node = sym_to_node[base]
789
+ all_used_symbols.add(
790
+ node.root.lookup(
791
+ node.divisor * divisor,
792
+ V.graph.sizevars.evaluate_min(
793
+ modulus, FloorDiv(node.length, divisor)
794
+ ),
795
+ ).symbol()
796
+ )
797
+
798
+ def visit_floor_div(base, divisor):
799
+ if base in sym_to_node:
800
+ node = sym_to_node[base]
801
+ all_used_symbols.add(
802
+ node.root.lookup(
803
+ node.divisor * divisor,
804
+ FloorDiv(node.length, divisor),
805
+ ).symbol()
806
+ )
807
+
808
+ # first figure out all_used_symbols to do dead symbol elimination
809
+ for index in indices:
810
+ if index.has(ModularIndexing):
811
+ index.replace(
812
+ ModularIndexing(
813
+ sympy.Wild("base"),
814
+ sympy.Wild("divisor"),
815
+ sympy.Wild("modulus"),
816
+ ),
817
+ visit_modular_indexing,
818
+ )
819
+ if index.has(FloorDiv):
820
+ index.replace(
821
+ FloorDiv(
822
+ sympy.Wild("base"),
823
+ sympy.Wild("divisor"),
824
+ ),
825
+ visit_floor_div,
826
+ )
827
+ all_used_symbols.update(super().prepare_indexing(index).free_symbols)
828
+
829
+ self.has_indirect_indexing = any(
830
+ symbol_is_type(sym, SymT.INDIRECT) for sym in all_used_symbols
831
+ )
832
+
833
+ had_fallback = False
834
+ for tree in reversed(self.range_trees):
835
+ nodes = [n for n in tree.nodes.values() if n.symbol() in all_used_symbols]
836
+ nodes.sort(key=lambda n: size_hint(n.divisor))
837
+ if not nodes:
838
+ nodes.append(tree.lookup(1, tree.numel))
839
+ handled_count = 0
840
+ divisor = sympy.S.One
841
+ added_sym_size = []
842
+ # decide on a minimal set of symbols and put them in self.halide_vars
843
+ while handled_count < len(nodes) and not eq(tree.numel, divisor):
844
+ sizes_to_add = [
845
+ simplify(n.length) for n in nodes if eq(n.divisor, divisor)
846
+ ]
847
+ handled_count += len(sizes_to_add)
848
+ assert sizes_to_add, nodes
849
+ end = divisor * functools.reduce(
850
+ V.graph.sizevars.evaluate_max, sizes_to_add
851
+ )
852
+ sizes_to_add.extend(
853
+ [
854
+ simplify(n.divisor / divisor)
855
+ for n in nodes
856
+ if lt(divisor, n.divisor) and lt(n.divisor, end)
857
+ ]
858
+ )
859
+ # pyrefly: ignore [bad-assignment]
860
+ while sizes_to_add:
861
+ next_size = functools.reduce(sympy.gcd, sizes_to_add)
862
+ if eq(next_size, 1):
863
+ # sizes share no common factors, e.g [2, 21, 42, 441, 889056]
864
+ # TODO(jansel): we should just prevent fusion in cases that hit this
865
+ next_size = simplify(tree.numel / divisor)
866
+ assert not eq(next_size, 1)
867
+ sizes_to_add = []
868
+ handled_count = len(nodes)
869
+ had_fallback = True
870
+ sym = sympy_index_symbol(f"h{len(self.halide_vars)}")
871
+ # pyrefly: ignore [missing-argument]
872
+ if tree.is_reduction:
873
+ self.reduction_renames[sym] = sympy_index_symbol(
874
+ f"hr{len(self.halide_vars)}"
875
+ )
876
+ self.halide_vars[sym] = next_size
877
+ added_sym_size.append((sym, next_size))
878
+ divisor *= next_size
879
+ new_sizes = [n.length for n in nodes if eq(n.divisor, divisor)]
880
+ handled_count += len(new_sizes)
881
+ prior_len = len(sizes_to_add)
882
+ sizes_to_add = [
883
+ sympy.simplify(s / next_size)
884
+ for s in sizes_to_add
885
+ if not eq(s, next_size)
886
+ ]
887
+ assert len(sizes_to_add) < prior_len or prior_len == 0
888
+ sizes_to_add.extend(new_sizes)
889
+
890
+ # create a mapping to the new set of symbols in self.index_replacements
891
+ for node in nodes:
892
+ try:
893
+ idx = 0
894
+ divisor = 1
895
+ while not eq(node.divisor, divisor):
896
+ sym, size = added_sym_size[idx]
897
+ idx += 1
898
+ divisor *= size
899
+ length = 1
900
+ expr = sympy.S.Zero
901
+ while not eq(node.length, length):
902
+ sym, size = added_sym_size[idx]
903
+ idx += 1
904
+ expr += length * sym
905
+ length *= size
906
+ self.index_replacements[node.symbol()] = expr
907
+ except IndexError:
908
+ assert had_fallback
909
+ full_index = sympy.S.Zero
910
+ stride = sympy.S.One
911
+ for sym, size in added_sym_size:
912
+ full_index += stride * sym
913
+ stride *= size
914
+ self.index_replacements[node.symbol()] = (
915
+ V.graph.sizevars.simplify_with_ranges(
916
+ ModularIndexing(full_index, node.divisor, node.length),
917
+ self.halide_vars, # type: ignore[arg-type]
918
+ )
919
+ )
920
+
921
+ # codegen the variable definitions
922
+ for sym in self.halide_vars:
923
+ self.indexing_code.writeline(f"{sym} = hl.Var({sym.name!r})")
924
+ if self.reduction_renames:
925
+ self.codegen_rdom(
926
+ "rdom",
927
+ {rv: self.halide_vars[v] for v, rv in self.reduction_renames.items()},
928
+ )
929
+
930
+ def setup_dom_indexing(self):
931
+ """RDom based indexing uses explicit iteration ranges for Func updates"""
932
+ prefix = "i" if self.inside_reduction else "o"
933
+ if prefix in self.dom_renames:
934
+ return self.dom_renames[prefix]
935
+
936
+ renames = {}
937
+ for var in self.halide_vars:
938
+ if not self.inside_reduction and var in self.reduction_renames:
939
+ continue
940
+ m = re.match(r"^h(\d+)$", var.name)
941
+ assert m
942
+ renames[var] = sympy_index_symbol(f"h{prefix}{m.group(1)}")
943
+
944
+ self.codegen_rdom(
945
+ f"{prefix}dom", {rv: self.halide_vars[v] for v, rv in renames.items()}
946
+ )
947
+
948
+ self.dom_renames[prefix] = renames
949
+ return renames
950
+
951
+ def codegen_rdom(self, name, vars):
952
+ rsizes = [
953
+ f"hl.Range(0, {self.kexpr(self.rename_indexing(size))})"
954
+ for size in vars.values()
955
+ ]
956
+ self.indexing_code.writeline(f"{name} = hl.RDom([{', '.join(rsizes)}])")
957
+ for i, rsym in enumerate(vars.keys()):
958
+ self.indexing_code.writeline(f"{rsym} = {name}[{i}]")
959
+
960
+ def prepare_indexing(
961
+ self,
962
+ index: sympy.Expr,
963
+ ):
964
+ index = super().prepare_indexing(index)
965
+ index = sympy_subs(index, self.index_replacements)
966
+ return V.graph.sizevars.simplify_with_ranges(index, self.halide_vars) # type: ignore[arg-type]
967
+
968
+ def sym_size(self, sym):
969
+ """The size of an index symbol"""
970
+ if symbol_is_type(sym, SymT.TMP):
971
+ return self.lookup_cse_var(sym.name).indirect_indexing_size
972
+ return self.halide_vars[sym]
973
+
974
+ def indexing_to_dimensions(self, var: str, index: sympy.Expr, is_store: bool):
975
+ """Convert address-based indexing into dimensions using self.halide_vars"""
976
+ symbols = []
977
+ for sym in sorted(index.free_symbols, key=lambda x: x.name): # type: ignore[attr-defined]
978
+ if symbol_is_type(sym, (SymT.HALIDE, SymT.TMP)):
979
+ symbols.append(sym)
980
+ else:
981
+ assert symbol_is_type(
982
+ sym,
983
+ (
984
+ SymT.UNBACKED_INT,
985
+ SymT.SIZE,
986
+ SymT.PRECOMPUTED_SIZE,
987
+ ),
988
+ ), sym
989
+
990
+ # group the expression by variables used
991
+ offset = sympy.S.Zero
992
+ split_expr = dict.fromkeys(symbols, sympy.S.Zero)
993
+ split_failed: list[tuple[list[sympy.Symbol], sympy.Expr]] = []
994
+ index = sympy.expand(self.rename_indexing(index))
995
+ for part in index.args if isinstance(index, sympy.Add) else [index]:
996
+ part_vars = [v for v in part.free_symbols if v in split_expr]
997
+ if len(part_vars) == 0:
998
+ offset += part
999
+ elif len(part_vars) == 1:
1000
+ split_expr[part_vars[0]] += part
1001
+ else:
1002
+ new_split_failed = []
1003
+ for i in range(len(split_failed)):
1004
+ assert split_failed[i] is not None
1005
+ other_vars, other_part = split_failed[i]
1006
+ if OrderedSet(other_vars) & OrderedSet(part_vars):
1007
+ part_vars.extend([v for v in other_vars if v not in part_vars])
1008
+ part += other_part
1009
+ else:
1010
+ new_split_failed.append((other_vars, other_part))
1011
+ split_failed = [*new_split_failed, (part_vars, part)]
1012
+
1013
+ def expr_to_dimension(expr, syms):
1014
+ expr = sympy.factor(expr)
1015
+ if len(syms) == 1:
1016
+ stride_wild = sympy.Wild("wild", exclude=symbols)
1017
+ m = expr.match(stride_wild * syms[0])
1018
+ if m:
1019
+ return DimensionInfo(
1020
+ syms[0], self.sym_size(syms[0]), m[stride_wild]
1021
+ )
1022
+ assert not is_store, expr
1023
+ length = sympy.simplify(
1024
+ sympy_subs(expr, {sym: self.sym_size(sym) - 1 for sym in syms}) + 1
1025
+ )
1026
+ stride = sympy.S.One
1027
+ if isinstance(expr, sympy.Mul):
1028
+ for term in expr.args:
1029
+ if isinstance(term, sympy.Integer):
1030
+ stride *= term
1031
+ expr = sympy.simplify(expr / term)
1032
+ length = sympy.simplify(sympy.ceiling(length / term))
1033
+ return DimensionInfo(expr, length, stride)
1034
+
1035
+ # try to turn each group into a strided access
1036
+ dims = []
1037
+ for syms, expr in split_failed:
1038
+ for v in syms:
1039
+ expr += split_expr.pop(v)
1040
+ dims.append(expr_to_dimension(expr, syms))
1041
+ for sym, expr in split_expr.items():
1042
+ dims.append(expr_to_dimension(expr, [sym]))
1043
+ dims.sort(key=lambda d: V.graph.sizevars.size_hint(d.stride, fallback=inf)) # type: ignore[arg-type]
1044
+
1045
+ if not dims: # scalar load/store
1046
+ if self.has_indirect_indexing:
1047
+ # workaround https://github.com/halide/Halide/issues/8338
1048
+ dims.append(DimensionInfo(sympy.S.Zero, 1, 1))
1049
+ elif not V.graph.sizevars.statically_known_equals(dims[0].stride, 1):
1050
+ # Halide assumes dimension 0 is stride == 1, so add a dummy dimension
1051
+ dims.insert(
1052
+ 0, DimensionInfo(sympy.S.Zero, 1 if is_store else dims[0].stride, 1)
1053
+ )
1054
+
1055
+ if dims and not is_store:
1056
+ if var in self.buffer_offsets and V.graph.sizevars.statically_known_geq(
1057
+ offset, self.buffer_offsets[var]
1058
+ ):
1059
+ # reuse the existing offset to avoid needing an input alias
1060
+ self.apply_offset_to_dimension(dims, offset - self.buffer_offsets[var])
1061
+ offset = self.buffer_offsets[var]
1062
+ elif V.graph.sizevars.statically_known_gt(
1063
+ offset, 0
1064
+ ): # TODO(jansel): negative offsets
1065
+ # roll the offset into the dimensions for cleaner indexing
1066
+ self.apply_offset_to_dimension(dims, offset)
1067
+ offset = 0
1068
+
1069
+ orig_var = var
1070
+ for i in itertools.count():
1071
+ if self.install_dims(var, dims, offset, is_store):
1072
+ return var, dims
1073
+ assert not is_store
1074
+ var = f"{orig_var}_view{i}"
1075
+ if var not in self.buffer_aliases[orig_var]:
1076
+ self.buffer_aliases[orig_var].append(var)
1077
+
1078
+ def install_dims(self, var, dims, offset, is_store):
1079
+ """Try to set self.buffer_dimensions[var], return True on success"""
1080
+ if var not in self.buffer_dimensions:
1081
+ self.buffer_dimensions[var] = dims
1082
+ self.buffer_offsets[var] = offset
1083
+ return True
1084
+ if self.buffer_offsets[var] != offset or len(
1085
+ self.buffer_dimensions[var]
1086
+ ) != len(dims):
1087
+ return False
1088
+ if is_store:
1089
+ return self.buffer_dimensions[var] == dims
1090
+ for old, new in zip(self.buffer_dimensions[var], dims):
1091
+ if old.stride != new.stride:
1092
+ return False
1093
+ if old.size != new.size or old.expr != new.expr:
1094
+ old.size = V.graph.sizevars.evaluate_max(old.size, new.size)
1095
+ old.expr = None
1096
+ return True
1097
+
1098
+ def apply_offset_to_dimension(self, dims, offset):
1099
+ if offset == 0:
1100
+ return
1101
+ for i in reversed(range(len(dims))):
1102
+ if dims[i].stride == 1 or V.graph.sizevars.statically_known_geq(
1103
+ offset, dims[i].stride
1104
+ ):
1105
+ part = FloorDiv(offset, dims[i].stride)
1106
+ offset -= part * dims[i].stride
1107
+ dims[i].expr += part
1108
+ assert offset == 0
1109
+
1110
+ def used_dims_from_index(self, index: sympy.Expr):
1111
+ """Detect which range trees are used to populate HalideCSEVariable.used_dims"""
1112
+ used_dims = OrderedSet[sympy.Symbol]()
1113
+ for sym in index.free_symbols:
1114
+ assert isinstance(sym, sympy.Symbol)
1115
+ if symbol_is_type(sym, SymT.TMP):
1116
+ # indirect indexing
1117
+ cse_var = self.lookup_cse_var(sym.name)
1118
+ assert (
1119
+ isinstance(cse_var, HalideCSEVariable)
1120
+ and cse_var.used_dims is not None
1121
+ )
1122
+ used_dims.update(cse_var.used_dims)
1123
+ elif symbol_is_type(sym, SymT.HALIDE):
1124
+ used_dims.add(sym)
1125
+ elif symbol_is_type(
1126
+ sym, (SymT.UNBACKED_INT, SymT.SIZE, SymT.PRECOMPUTED_SIZE, SymT.INDEX)
1127
+ ):
1128
+ pass
1129
+ else:
1130
+ raise NotImplementedError(f"unhandled symbol {sym}")
1131
+ return self.sort_used_dims(used_dims)
1132
+
1133
+ def sort_used_dims(self, used_dims):
1134
+ assert all(isinstance(x, sympy.Expr) for x in used_dims)
1135
+ ordered = [
1136
+ sym
1137
+ for sym in itertools.chain(
1138
+ self.halide_vars, self.reduction_renames.values()
1139
+ )
1140
+ if sym in used_dims
1141
+ ]
1142
+ assert len(ordered) == len(used_dims)
1143
+ return ordered
1144
+
1145
+ def make_index_str(self, dims, replacements=None, zero_vars=False):
1146
+ index_str = ", ".join(d.index_str(replacements, zero_vars) for d in dims)
1147
+ if len(dims) == 0:
1148
+ index_str = "()"
1149
+ elif len(dims) == 1:
1150
+ # workaround for https://github.com/halide/Halide/issues/8299
1151
+ index_str = f"{index_str},"
1152
+ return index_str
1153
+
1154
+ def load(self, name: str, index: sympy.Expr):
1155
+ """Codegen a load from an InputBuffer"""
1156
+ var = self.args.input(name)
1157
+ index = self.prepare_indexing(index)
1158
+ var, dims = self.indexing_to_dimensions(var, index, False)
1159
+ line = f"{var}[{self.make_index_str(dims)}]"
1160
+ dtype = V.graph.get_dtype(name)
1161
+ if dtype in (torch.float16, torch.bfloat16):
1162
+ dtype = torch.float32
1163
+ line = f"hl.cast(hl.Float(32), {line})"
1164
+
1165
+ if self._load_mask:
1166
+ assert (
1167
+ isinstance(self._load_mask, HalideCSEVariable)
1168
+ and self._load_mask.used_dims is not None
1169
+ )
1170
+ used_dims = OrderedSet(
1171
+ (*self.used_dims_from_index(index), *self._load_mask.used_dims)
1172
+ )
1173
+ result = self.newfunc(self.sort_used_dims(used_dims))
1174
+ if result.used_dims:
1175
+ self.body.writeline(f"{result.name}_mask = hl.RDom([hl.Range(0, 1)])")
1176
+ self.body.writeline(f"{result.name}_mask.where({self._load_mask})")
1177
+ other = self.kexpr(self._load_other or 0) # type: ignore[arg-type]
1178
+ self.body.writeline(
1179
+ f"{result} = hl.cast({halide_type(dtype)}, {other})"
1180
+ )
1181
+ self.body.writeline(
1182
+ f"{result} = {line} + hl.cast({halide_type(dtype)}, {result.name}_mask)"
1183
+ )
1184
+ else:
1185
+ # scalar case
1186
+ self.body.writeline(
1187
+ f"{result} = hl.select({self._load_mask}, {line}, hl.cast({halide_type(dtype)}, 0))"
1188
+ )
1189
+ return result
1190
+ else:
1191
+ return self.genfunc(line, self.used_dims_from_index(index))
1192
+
1193
+ def lookup_cse_var(self, name: str):
1194
+ return self.cse.varname_map[re.sub(r"\[.*", "", name)]
1195
+
1196
+ def store(
1197
+ self, name: str, index: sympy.Expr, value: CSEVariable, mode: StoreMode = None
1198
+ ) -> None:
1199
+ """Codegen a store to an OutputBuffer"""
1200
+ assert isinstance(value, HalideCSEVariable)
1201
+ var = self.args.output(name)
1202
+ index = self.prepare_indexing(index)
1203
+ var, dims = self.indexing_to_dimensions(var, index, True)
1204
+ if self.is_indirect_indexing(index) or mode is not None:
1205
+ replacements = self.setup_dom_indexing()
1206
+ index_str = self.make_index_str(dims, replacements)
1207
+ value_str = value.subs_str(replacements)
1208
+ undef_dims = (", ".join(["hl.Var()"] * len(dims))) or "()"
1209
+ self.body.writeline(
1210
+ DeferredLine(name, f"{var}[{undef_dims}] = hl.undef({var}.type())")
1211
+ )
1212
+ else:
1213
+ index_str = self.make_index_str(dims, zero_vars=True)
1214
+ value_str = str(value)
1215
+
1216
+ dtype = V.graph.get_dtype(name)
1217
+ if mode is None:
1218
+ line = f"{var}[{index_str}] = hl.cast({halide_type(dtype)}, {value_str})"
1219
+ elif mode == "atomic_add":
1220
+ line = f"{var}[{index_str}] += hl.cast({halide_type(dtype)}, {value_str})"
1221
+ else:
1222
+ raise NotImplementedError(f"store mode={mode}")
1223
+ self.body.writeline(DeferredLine(name, line))
1224
+
1225
+ def reduction(
1226
+ self,
1227
+ dtype: torch.dtype,
1228
+ src_dtype: torch.dtype,
1229
+ reduction_type: ReductionType,
1230
+ value: Union[CSEVariable, tuple[CSEVariable, ...]],
1231
+ ) -> Union[CSEVariable, tuple[CSEVariable, ...]]:
1232
+ """Codegen a reduction operation"""
1233
+ assert self.inside_reduction
1234
+ assert not self._load_mask
1235
+ cache_key = (src_dtype, reduction_type, value)
1236
+ if cache_key in self.cse.reduction_cache:
1237
+ return self.cse.reduction_cache[cache_key]
1238
+
1239
+ if isinstance(value, tuple):
1240
+ assert reduction_type == "welford_combine"
1241
+ self.cse.reduction_cache[cache_key] = result_tuple = (
1242
+ self.welford_combine_impl(*value)
1243
+ )
1244
+ return result_tuple
1245
+
1246
+ assert isinstance(value, HalideCSEVariable) and value.used_dims is not None
1247
+ reduction_vars = OrderedSet(self.reduction_renames)
1248
+ result_var = self.newfunc(
1249
+ [v for v in value.used_dims if v not in reduction_vars],
1250
+ )
1251
+ if reduction_vars - OrderedSet(value.used_dims):
1252
+ value = self.genfunc(
1253
+ f"{value}",
1254
+ self.sort_used_dims(OrderedSet((*value.used_dims, *reduction_vars))),
1255
+ shape=value.shape,
1256
+ )
1257
+ value_str = value.subs_str(self.reduction_renames)
1258
+ default = ir.Reduction.default_accumulator(reduction_type, src_dtype)
1259
+ acc_type = halide_acc_type(dtype)
1260
+
1261
+ if reduction_type in ("argmax", "argmin"):
1262
+ index = f"{result_var.name}_{reduction_type}"
1263
+ self.body.writeline(f"{index} = hl.{reduction_type}(rdom, {value_str})")
1264
+ # turn the N-D argmax index into a 1-D one
1265
+ parts = []
1266
+ stride = 1
1267
+ for i, sym in enumerate(self.reduction_renames):
1268
+ # pyrefly: ignore [bad-argument-type]
1269
+ parts.append(f"{index}[{i}]")
1270
+ if stride != 1:
1271
+ # pyrefly: ignore [unsupported-operation]
1272
+ parts[-1] += f"*{stride}"
1273
+ stride *= self.halide_vars[sym]
1274
+ self.body.writeline(f"{result_var} = {' + '.join(parts)}")
1275
+ elif reduction_type == "welford_reduce":
1276
+ # TODO(jansel): implement welford_reduce without fallback
1277
+ result_var = self.welford_reduce_fallback(dtype, value)
1278
+ else:
1279
+ combine_fn = get_reduction_combine_fn(reduction_type, acc_type)
1280
+ with V.set_ops_handler(AddParenHandler(HalideOverrides())):
1281
+ combine_str = combine_fn(result_var, value_str) # type: ignore[arg-type]
1282
+ default_str = f"hl.cast({acc_type}, {halide_constant(default)})"
1283
+ self.body.writeline(f"{result_var} = {default_str}")
1284
+ self.body.writeline(f"{result_var} = {combine_str}")
1285
+
1286
+ self.cse.reduction_cache[cache_key] = result_var
1287
+ return result_var
1288
+
1289
+ def welford_combine_impl(self, mean, m2, weight):
1290
+ assert isinstance(mean, HalideCSEVariable) and mean.used_dims is not None
1291
+ assert isinstance(m2, HalideCSEVariable) and m2.used_dims is not None
1292
+ assert isinstance(weight, HalideCSEVariable) and weight.used_dims is not None
1293
+ used_dims = OrderedSet(
1294
+ (*mean.used_dims, *m2.used_dims, *weight.used_dims) or self.halide_vars
1295
+ )
1296
+ used_dims -= OrderedSet(self.reduction_renames)
1297
+ result_var = self.newfunc(self.sort_used_dims(used_dims))
1298
+ default = [f"hl.cast({x.name}.type(), 0)" for x in (mean, m2, weight)]
1299
+ pfx = result_var.name
1300
+ self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(default)}])")
1301
+ self.body.writeline(f"{pfx}_mean_1 = {result_var}[0]")
1302
+ self.body.writeline(f"{pfx}_m2_1 = {result_var}[1]")
1303
+ self.body.writeline(f"{pfx}_weight_1 = {result_var}[2]")
1304
+ self.body.writeline(f"{pfx}_mean_2 = {mean.subs_str(self.reduction_renames)}")
1305
+ self.body.writeline(f"{pfx}_m2_2 = {m2.subs_str(self.reduction_renames)}")
1306
+ self.body.writeline(
1307
+ f"{pfx}_weight_2 = {weight.subs_str(self.reduction_renames)}"
1308
+ )
1309
+ self.body.writeline(f"{pfx}_delta = {pfx}_mean_2 - {pfx}_mean_1")
1310
+ self.body.writeline(f"{pfx}_new_weight = {pfx}_weight_1 + {pfx}_weight_2")
1311
+ self.body.writeline(
1312
+ f"{pfx}_w2_over_w = hl.select({pfx}_new_weight == 0.0, 0.0, {pfx}_weight_2 / {pfx}_new_weight)"
1313
+ )
1314
+ update = [
1315
+ f"{pfx}_mean_1 + {pfx}_delta * {pfx}_w2_over_w",
1316
+ f"{pfx}_m2_1 + {pfx}_m2_2 + {pfx}_delta * {pfx}_delta * {pfx}_weight_1 * {pfx}_w2_over_w",
1317
+ f"{pfx}_new_weight",
1318
+ ]
1319
+ self.body.writeline(f"{result_var} = hl.Tuple([{', '.join(update)}])")
1320
+
1321
+ unpacked = []
1322
+ for i in range(3):
1323
+ unpacked.append(self.newfunc(result_var.used_dims))
1324
+ self.body.writeline(f"{unpacked[-1]} = {result_var}[{i}]")
1325
+ return tuple(unpacked)
1326
+
1327
+ def scan(
1328
+ self,
1329
+ dtypes: tuple[torch.dtype, ...],
1330
+ combine_fn: Callable[
1331
+ [tuple[CSEVariable, ...], tuple[CSEVariable, ...]], tuple[CSEVariable, ...]
1332
+ ],
1333
+ values_orig: tuple[CSEVariable, ...],
1334
+ ) -> tuple[CSEVariable, ...]:
1335
+ assert self.inside_reduction
1336
+ assert len(dtypes) == len(values_orig)
1337
+ values: list[HalideCSEVariable] = []
1338
+ all_used_dims = OrderedSet[sympy.Symbol]()
1339
+
1340
+ for value in values_orig:
1341
+ assert isinstance(value, HalideCSEVariable) and value.used_dims is not None
1342
+ if OrderedSet(value.used_dims) & OrderedSet(self.reduction_renames):
1343
+ values.append(value)
1344
+ else:
1345
+ values.append(
1346
+ self.genfunc(
1347
+ f"{value}",
1348
+ [*value.used_dims, [*self.reduction_renames][:1]],
1349
+ shape=value.shape,
1350
+ )
1351
+ )
1352
+ all_used_dims.update(value.used_dims)
1353
+ result_var = self.newfunc(self.sort_used_dims(all_used_dims))
1354
+ assert result_var.used_dims and OrderedSet(result_var.used_dims) & OrderedSet(
1355
+ self.reduction_renames
1356
+ )
1357
+ initial = [
1358
+ f"hl.cast({halide_acc_type(dtype)}, {value})"
1359
+ for dtype, value in zip(dtypes, values)
1360
+ ]
1361
+
1362
+ length = self.kexpr(self.rename_indexing(self.range_trees[-1].numel))
1363
+ scan_dom = f"{result_var.name}_rdom"
1364
+ scan = f"{scan_dom}.x"
1365
+ self.body.writeline(f"{scan_dom} = hl.RDom([hl.Range(1, {length})])")
1366
+
1367
+ assert len(self.reduction_renames) == 1, (
1368
+ "multi-dimensional scan not implemented"
1369
+ )
1370
+ (scan_var,) = [*self.reduction_renames] # type: ignore[misc]
1371
+ scan_renames_cur = {scan_var: sympy_index_symbol(scan)}
1372
+ scan_renames_pri = {scan_var: sympy_index_symbol(scan) - 1}
1373
+
1374
+ if len(values) == 1:
1375
+
1376
+ def maybe_tuple(x):
1377
+ return x[0]
1378
+
1379
+ read_left = [result_var.subs_str(scan_renames_pri)]
1380
+ read_right = [result_var.subs_str(scan_renames_cur)]
1381
+ else:
1382
+
1383
+ def maybe_tuple(x):
1384
+ return f"hl.Tuple([{', '.join(x)}])"
1385
+
1386
+ read_left = [
1387
+ result_var.subs_str(scan_renames_pri) + f"[{i}]"
1388
+ for i in range(len(values))
1389
+ ]
1390
+ read_right = [
1391
+ result_var.subs_str(scan_renames_cur) + f"[{i}]"
1392
+ for i in range(len(values))
1393
+ ]
1394
+
1395
+ self.body.writeline(f"{result_var} = {maybe_tuple(initial)}")
1396
+
1397
+ # Disable CSE for update fn
1398
+ with V.set_ops_handler(AddParenHandler(HalideOverrides())):
1399
+ combine_str = combine_fn(read_left, read_right) # type: ignore[arg-type]
1400
+ self.body.writeline(
1401
+ f"{result_var.subs_str(scan_renames_cur)} = {maybe_tuple(combine_str)}"
1402
+ )
1403
+
1404
+ if len(values) == 1:
1405
+ return (result_var,)
1406
+
1407
+ unpack_vars = [self.newfunc(self.sort_used_dims(all_used_dims)) for _ in values]
1408
+ for i, v in enumerate(unpack_vars):
1409
+ self.body.writeline(f"{v} = {result_var}[{i}]")
1410
+ return tuple(unpack_vars)
1411
+
1412
+ def genfunc(
1413
+ self,
1414
+ line,
1415
+ used_dims,
1416
+ *,
1417
+ bounds=ValueRanges.unknown(),
1418
+ shape: BlockShapeType = None,
1419
+ ) -> HalideCSEVariable:
1420
+ var = self.cse.generate(self.body, line, bounds=bounds, shape=shape)
1421
+ assert isinstance(var, HalideCSEVariable)
1422
+ var.used_dims = used_dims
1423
+ return var
1424
+
1425
+ def newfunc(self, used_dims, *, shape: BlockShapeType = None) -> HalideCSEVariable:
1426
+ var = self.cse.newvar(shape=shape)
1427
+ assert isinstance(var, HalideCSEVariable)
1428
+ var.used_dims = used_dims
1429
+ return var
1430
+
1431
+ def halide_buffer_numel(self, name: str):
1432
+ """
1433
+ We map all tensors to 1D buffers in Halide since Halide has trouble representing some strides that PyTorch
1434
+ supports. If there are gaps in the underlying layout the numel we pass to Halide includes the gaps while
1435
+ PyTorch's numel excludes them.
1436
+ """
1437
+ return V.graph.get_buffer(name).get_layout().storage_size()
1438
+
1439
+ def halide_argdefs(self):
1440
+ """
1441
+ Halide requires scalar inputs before outputs, so need to reorder args.
1442
+ """
1443
+
1444
+ def arg_order(arg_tuple):
1445
+ _call_str, arg = arg_tuple
1446
+ if isinstance(arg, SizeArg):
1447
+ return 1 # this would normally be at the end, move it to middle
1448
+ elif "out_ptr" in arg.name:
1449
+ return 2
1450
+ else:
1451
+ assert "in_ptr" in arg.name
1452
+ return 0
1453
+
1454
+ result: list[tuple[Optional[str], KernelArgType]] = []
1455
+ _, a, b, _ = self.args.python_argdefs()
1456
+ for call_str, arg in sorted(zip(a, b), key=arg_order):
1457
+ result.append((call_str, arg))
1458
+ if isinstance(arg, TensorArg):
1459
+ assert arg.offset == 0 and arg.alias_of is None
1460
+ result.extend(
1461
+ (
1462
+ None,
1463
+ TensorArg(
1464
+ alias,
1465
+ arg.buffer,
1466
+ arg.dtype,
1467
+ arg.offset,
1468
+ alias_of=arg.name,
1469
+ ),
1470
+ )
1471
+ for alias in self.buffer_aliases.get(arg.name, ())
1472
+ )
1473
+ return result
1474
+
1475
+ def halide_kernel_meta(self) -> HalideMeta:
1476
+ """Compute metadata required by codecache.py"""
1477
+ argtypes = []
1478
+ for _, arg in self.halide_argdefs():
1479
+ if isinstance(arg, SizeArg):
1480
+ shape = None
1481
+ stride = None
1482
+ offset = None
1483
+ dtype = "long"
1484
+ else:
1485
+ shape = [
1486
+ cexpr(self.rename_indexing(x.size))
1487
+ for x in self.buffer_dimensions[arg.name]
1488
+ ]
1489
+ stride = [
1490
+ cexpr(self.rename_indexing(x.stride))
1491
+ for x in self.buffer_dimensions[arg.name]
1492
+ ]
1493
+ assert len(shape) == len(stride)
1494
+ offset = cexpr(self.buffer_offsets[arg.name])
1495
+ dtype = f"{DTYPE_TO_CPP[arg.dtype]}*"
1496
+ argtypes.append(
1497
+ HalideInputSpec(
1498
+ dtype,
1499
+ arg.name,
1500
+ shape=shape,
1501
+ stride=stride,
1502
+ offset=offset,
1503
+ alias_of=arg.alias_of,
1504
+ )
1505
+ )
1506
+
1507
+ current_device = V.graph.get_current_device_or_throw()
1508
+ if current_device.type == "cpu":
1509
+ target = [config.halide.cpu_target]
1510
+ scheduler = config.halide.scheduler_cpu
1511
+ scheduler_flags = {
1512
+ "parallelism": parallel_num_threads(),
1513
+ }
1514
+ cuda_device = None
1515
+ else:
1516
+ assert current_device.type == "cuda", "only cpu/cuda supported"
1517
+ assert current_device.index <= 0, "only default device supported"
1518
+ target = [config.halide.gpu_target]
1519
+ scheduler = config.halide.scheduler_cuda
1520
+ capability = torch.cuda.get_device_properties(current_device)
1521
+ if "cuda_capability" not in target[0]:
1522
+ for major, minor in [(8, 6), (8, 0), (7, 5), (7, 0), (6, 1)]:
1523
+ if capability.major >= major and capability.minor >= minor:
1524
+ target.append(f"cuda_capability_{major}{minor}")
1525
+ break
1526
+ target.append("user_context")
1527
+ scheduler_flags = {
1528
+ "parallelism": capability.multi_processor_count,
1529
+ # TODO(jansel): explore other flags, see:
1530
+ # grep parser.parse ~/Halide/src/autoschedulers/anderson2021/AutoSchedule.cpp
1531
+ }
1532
+ cuda_device = max(0, current_device.index)
1533
+
1534
+ # strict_float is requires for correctness
1535
+ target.append("strict_float")
1536
+
1537
+ # without this we will initialize cuda once per kernel and hit errors
1538
+ target.append("no_runtime")
1539
+
1540
+ if not config.halide.asserts:
1541
+ target.append("no_asserts")
1542
+
1543
+ if config.halide.debug:
1544
+ target.append("debug")
1545
+
1546
+ if "64" in self.index_dtype:
1547
+ # TODO(jansel): it is unclear if this does anything, since input sizes are still int32
1548
+ target.append("large_buffers")
1549
+
1550
+ return HalideMeta(
1551
+ argtypes,
1552
+ target="-".join(target),
1553
+ scheduler=scheduler,
1554
+ scheduler_flags=scheduler_flags, # type: ignore[arg-type]
1555
+ cuda_device=cuda_device,
1556
+ )
1557
+
1558
+ def codegen_kernel(self, name=None):
1559
+ """Called at the end to generate a final kernel string"""
1560
+ if self.args.inplace_buffers:
1561
+ raise Unsupported("inplace_buffers")
1562
+ meta = self.halide_kernel_meta() # ensure needed args are added early
1563
+ code = IndentedBuffer()
1564
+ code.splice(
1565
+ """
1566
+ import halide as hl
1567
+ from torch._inductor.runtime import halide_helpers
1568
+ from math import inf, nan
1569
+
1570
+ @hl.generator(name="kernel")
1571
+ class Kernel:
1572
+ """,
1573
+ strip=True,
1574
+ )
1575
+ code.do_indent()
1576
+ for _, arg in self.halide_argdefs():
1577
+ if isinstance(arg, SizeArg):
1578
+ code.writeline(f"{arg.name} = hl.InputScalar({self.index_dtype})")
1579
+ else:
1580
+ assert arg.buffer, arg
1581
+ argcls = "hl.OutputBuffer" if "out" in arg.name else "hl.InputBuffer"
1582
+ argtype = halide_type(arg.dtype)
1583
+ ndim = len(self.buffer_dimensions[arg.name])
1584
+ code.writeline(f"{arg.name} = {argcls}({argtype}, {ndim})")
1585
+ code.splice(
1586
+ """
1587
+ def generate(g):
1588
+ """
1589
+ )
1590
+ code.do_indent()
1591
+ for _, arg in self.halide_argdefs():
1592
+ code.writeline(f"{arg.name} = g.{arg.name}")
1593
+ for old, new in self.args.aliases():
1594
+ code.writeline(f"{old} = {new}")
1595
+ code.splice(self.indexing_code)
1596
+
1597
+ def update_index(m):
1598
+ var = cast(HalideCSEVariable, self.cse.varname_map[m.group(1)])
1599
+ assert var.used_dims is not None, var
1600
+ return str(var)
1601
+
1602
+ for line in self.body._lines:
1603
+ if isinstance(line, str):
1604
+ # fill in missing indices
1605
+ line = HalideCSEVariable.undefined_re.sub(update_index, line)
1606
+ code.writeline(line)
1607
+ code.writeline("")
1608
+ code.writeline("assert g.using_autoscheduler()")
1609
+
1610
+ for _, arg in self.halide_argdefs():
1611
+ # fallback=1 below because halide requires buffers to be at least as large as the estimates
1612
+ # This causes crashes if our estimate is greater than the vector length
1613
+ # https://github.com/halide/Halide/issues/3103
1614
+ if isinstance(arg, SizeArg):
1615
+ hint = V.graph.sizevars.size_hint(arg.expr, fallback=1)
1616
+ code.writeline(f"{arg.name}.set_estimate({hint})")
1617
+ else:
1618
+ dims = self.buffer_dimensions[arg.name]
1619
+ range_hints = []
1620
+ for i, dim in enumerate(dims):
1621
+ hint = self._autoscheduler_workarounds(
1622
+ V.graph.sizevars.size_hint(dim.size, fallback=1), dims
1623
+ )
1624
+ # pyrefly: ignore [bad-argument-type]
1625
+ range_hints.append(f"hl.Range(0, {hint})")
1626
+ if "out" not in arg.name:
1627
+ code.writeline(f"{arg.name}.dim({i}).set_min(0)")
1628
+ try:
1629
+ code.writeline(
1630
+ f"{arg.name}.dim({i}).set_stride({int(dim.stride)})"
1631
+ )
1632
+ except TypeError:
1633
+ pass # not integer
1634
+ try:
1635
+ code.writeline(
1636
+ f"{arg.name}.dim({i}).set_extent({int(dim.size)})"
1637
+ )
1638
+ except TypeError:
1639
+ pass # not integer
1640
+ code.writeline(f"{arg.name}.set_estimates([{', '.join(range_hints)}])")
1641
+
1642
+ code.do_unindent(2)
1643
+ code.splice(
1644
+ """
1645
+ if __name__ == "__main__":
1646
+ hl.main()
1647
+ """.rstrip(),
1648
+ )
1649
+ if meta.scheduler:
1650
+ code.splice(
1651
+ f"""
1652
+ else:
1653
+ hl.load_plugin({HalideCodeCache.find_libautoschedule(meta.scheduler)!r})
1654
+ target = hl.Target({meta.target!r})
1655
+ autoscheduler = hl.AutoschedulerParams({meta.scheduler!r}, {meta.scheduler_flags!r})
1656
+ with hl.GeneratorContext(target, autoscheduler):
1657
+ gen = Kernel()
1658
+ pipeline = gen._build_pipeline()
1659
+ # gen.compile_to_callable() does not run the autoscheduler
1660
+ pipeline.apply_autoscheduler(target, autoscheduler)
1661
+ kernel = pipeline.compile_to_callable([
1662
+ gen._get_input_parameter(a.name)._to_argument()
1663
+ for a in gen._get_arginfos()
1664
+ if a.dir == hl.ArgInfoDirection.Input
1665
+ ], target)
1666
+ """,
1667
+ strip=True,
1668
+ )
1669
+ else:
1670
+ code.splice(
1671
+ f"""
1672
+ else:
1673
+ with hl.GeneratorContext(hl.Target({meta.target!r})):
1674
+ kernel = Kernel().compile_to_callable()
1675
+ """,
1676
+ strip=True,
1677
+ )
1678
+ return code.getvalue()
1679
+
1680
+ @staticmethod
1681
+ def _autoscheduler_workarounds(n, dims):
1682
+ if (
1683
+ len(dims) == 1
1684
+ and config.halide.scheduler_cuda == "Anderson2021"
1685
+ and V.graph.get_current_device_or_throw().type == "cuda"
1686
+ ):
1687
+ # workaround https://github.com/halide/Halide/issues/8246
1688
+ n = max(2, n)
1689
+ return n
1690
+
1691
+ def call_kernel(self, name: str, node=None, deallocate_ws: bool = True):
1692
+ """Codegen a call to this kernel"""
1693
+ wrapper = V.graph.wrapper_code
1694
+ call_args = [f"{n}" for n, arg in self.halide_argdefs() if arg.alias_of is None]
1695
+ current_device = V.graph.get_current_device_or_throw()
1696
+ if current_device.type == "cuda":
1697
+ stream_name = wrapper.write_get_raw_stream(
1698
+ current_device.index, V.graph.name
1699
+ )
1700
+ call_args.append(stream_name)
1701
+ wrapper.generate_kernel_call(
1702
+ name,
1703
+ call_args,
1704
+ device=current_device,
1705
+ triton=False,
1706
+ )
1707
+
1708
+ def generate_assert(self, check):
1709
+ return False # TODO(jansel): support asserts
1710
+
1711
+ def check_bounds(
1712
+ self, expr: sympy.Expr, size: sympy.Expr, lower: bool, upper: bool
1713
+ ):
1714
+ pass # TODO(jansel): support asserts
1715
+
1716
+
1717
+ class HalideScheduling(SIMDScheduling):
1718
+ kernel_type = HalideKernel # type: ignore[arg-type,assignment]
1719
+
1720
+ @classmethod
1721
+ def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]:
1722
+ result = OrderedSet(
1723
+ [
1724
+ BackendFeature.TUPLE_REDUCTION,
1725
+ BackendFeature.PREFER_STORE_LOOP_ORDER,
1726
+ BackendFeature.REDUCE_TO_SINGLE_ELEMENT,
1727
+ ]
1728
+ )
1729
+ if config.halide.scan_kernels:
1730
+ result.add(BackendFeature.SCAN)
1731
+ return result
1732
+
1733
+ def define_kernel(self, src_code, node_schedule, kernel):
1734
+ """Codegen kernel definition to go in output wrapper code"""
1735
+ wrapper = V.graph.wrapper_code
1736
+ if src_code in wrapper.src_to_kernel:
1737
+ kernel_name = wrapper.src_to_kernel[src_code]
1738
+ else:
1739
+ kernel_name = f"halide_kernel_{wrapper.next_kernel_suffix()}"
1740
+ wrapper.src_to_kernel[src_code] = kernel_name
1741
+ wrapper.add_import_once(
1742
+ "from torch._inductor.runtime.hints import HalideMeta, HalideInputSpec"
1743
+ )
1744
+
1745
+ compile_wrapper = IndentedBuffer()
1746
+ compile_wrapper.writeline(
1747
+ f"async_compile.halide({kernel.halide_kernel_meta()!r}, '''"
1748
+ )
1749
+ compile_wrapper.splice(src_code, strip=True)
1750
+ compile_wrapper.writeline("''')")
1751
+
1752
+ origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
1753
+ metadata_comment = f"{origins}\n{detailed_origins}"
1754
+ wrapper.define_kernel(
1755
+ kernel_name, compile_wrapper.getvalue(), metadata_comment
1756
+ )
1757
+ if is_metric_table_enabled("kernel_metadata"):
1758
+ log_kernel_metadata(kernel_name, "", src_code)
1759
+
1760
+ return kernel_name
.venv/lib/python3.10/site-packages/torch/_inductor/codegen/memory_planning.py ADDED
@@ -0,0 +1,816 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import collections
5
+ import dataclasses
6
+ import itertools
7
+ import pprint
8
+ from typing import Any, Optional, Protocol, TYPE_CHECKING
9
+
10
+ import sympy
11
+
12
+ import torch
13
+ from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
14
+ from torch.utils._ordered_set import OrderedSet
15
+
16
+ from .. import config
17
+ from ..utils import _align, align, cache_on_self, CachedMethod, IndentedBuffer
18
+ from ..virtualized import V
19
+ from .wrapper import (
20
+ AllocateLine,
21
+ BufferLike,
22
+ FreeIfNotReusedLine,
23
+ MemoryPlanningLine,
24
+ NullLine,
25
+ ReuseLine,
26
+ )
27
+
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Iterable
31
+
32
+
33
+ @dataclasses.dataclass
34
+ class LiveRange:
35
+ """
36
+ A range where a given tensor is live. Begin and end are both counters
37
+ representing points in the program of grouped memory operations.
38
+ Begin is inclusive, end is exclusive.
39
+
40
+ Invariant: begin <= end
41
+ """
42
+
43
+ begin: float # int | +/-inf
44
+ end: float # int | +/-inf
45
+
46
+ def contains(self, other: LiveRange):
47
+ """Is other entirely within self"""
48
+ return self.begin <= other.begin and other.end <= self.end
49
+
50
+ def join(self, other: LiveRange):
51
+ """Combine two ranges using a union operation"""
52
+ return LiveRange(min(self.begin, other.begin), max(self.end, other.end))
53
+
54
+ def __len__(self):
55
+ return self.end - self.begin
56
+
57
+
58
+ class LiveRanges:
59
+ """
60
+ A collection of LiveRange regions, allowing for non-contiguous
61
+ live regions.
62
+
63
+ Invariant: LiveRanges.ranges is in sorted order and non-overlapping
64
+ """
65
+
66
+ def __init__(self, ranges: Iterable[LiveRange]):
67
+ ranges = [*sorted(ranges, key=lambda x: x.begin)]
68
+ self.ranges = ranges[:1]
69
+ for r in ranges[1:]:
70
+ assert self.ranges[-1].begin <= r.begin
71
+ if self.ranges[-1].end >= r.begin:
72
+ self.ranges[-1] = LiveRange.join(self.ranges[-1], r)
73
+ else:
74
+ self.ranges.append(r)
75
+
76
+ def overlaps(self, other: LiveRanges):
77
+ """Check if any pair of ranges in self and other overlap"""
78
+ left = collections.deque(self.ranges)
79
+ right = collections.deque(other.ranges)
80
+ while left and right:
81
+ if left[0].begin > right[0].begin:
82
+ left, right = right, left
83
+ assert left[0].begin <= right[0].begin
84
+ if left[0].end > right[0].begin:
85
+ return True
86
+ left.popleft()
87
+ return False
88
+
89
+ @property
90
+ def begin(self):
91
+ return self.ranges[0].begin
92
+
93
+ @property
94
+ def end(self):
95
+ return self.ranges[-1].end
96
+
97
+ def __repr__(self):
98
+ return f"{self.__class__.__name__}([{', '.join(map(repr, self.ranges))}])"
99
+
100
+
101
+ class AllocationTreeNode:
102
+ """
103
+ Abstract base class for nodes in allocation pool.
104
+ """
105
+
106
+ def allocate(self, block: Allocation, is_last: bool) -> bool:
107
+ """
108
+ Try to assign block to a memory location in this bool. Return True if
109
+ an assignment was made.
110
+ """
111
+ return False
112
+
113
+ def get_live_ranges(self) -> LiveRanges:
114
+ """Aggregate LiveRanges for all objects below this in tree"""
115
+ raise NotImplementedError
116
+
117
+ def get_size_hint(self) -> int:
118
+ """Number of bytes used for example inputs"""
119
+ raise NotImplementedError
120
+
121
+ def get_symbolic_size(self) -> sympy.Expr:
122
+ """Number of bytes needed at runtime"""
123
+ raise NotImplementedError
124
+
125
+ def finalize(self, pool, offset) -> AllocationTreeNode:
126
+ """Called after all allocations have been made"""
127
+ return self
128
+
129
+ def is_empty(self):
130
+ return False
131
+
132
+
133
+ @dataclasses.dataclass
134
+ class Allocation(AllocationTreeNode):
135
+ """
136
+ Represents memory allocated to a given node in the allocation pool.
137
+ """
138
+
139
+ node: BufferLike
140
+ live_range: LiveRange
141
+ size_hint: int
142
+ symbolic_size: sympy.Expr
143
+ allocated: bool = False
144
+ pool: Optional[AllocationPool] = None
145
+ offset: Optional[sympy.Expr] = None
146
+ earliest_available: Optional[float] = None
147
+
148
+ def __post_init__(self) -> None:
149
+ has_unbacked_sym = False
150
+ for s in self.node.get_layout().size:
151
+ if free_unbacked_symbols(s):
152
+ has_unbacked_sym = True
153
+ break
154
+
155
+ if has_unbacked_sym:
156
+ self.earliest_available = self.get_live_ranges().begin
157
+
158
+ @property
159
+ def device(self):
160
+ return self.node.get_device()
161
+
162
+ def get_live_ranges(self):
163
+ return LiveRanges([self.live_range])
164
+
165
+ def get_size_hint(self):
166
+ return self.size_hint
167
+
168
+ def get_symbolic_size(self):
169
+ return self.symbolic_size
170
+
171
+ def mark_allocated(self):
172
+ assert not self.allocated
173
+ self.allocated = True
174
+
175
+ def finalize(self, pool, offset):
176
+ assert self.pool is None and self.offset is None
177
+ self.pool = pool
178
+ self.offset = offset
179
+ return self
180
+
181
+ def codegen_alloc_from_pool(self, wrapper):
182
+ assert self.pool
183
+ node = self.node
184
+ shape = tuple(node.get_size())
185
+ stride = tuple(node.get_stride())
186
+ return wrapper.codegen_alloc_from_pool(
187
+ self.pool.name, self.offset, node.get_dtype(), shape, stride
188
+ )
189
+
190
+ def __repr__(self):
191
+ return (
192
+ f"{self.__class__.__name__}("
193
+ f"node={self.node.get_name()}, "
194
+ f"live_range={self.live_range}, "
195
+ f"size_hint={self.size_hint}, "
196
+ f"symbolic_size={self.symbolic_size}, "
197
+ f"pool={self.pool.name if self.pool else None}, "
198
+ f"offset={self.offset})"
199
+ )
200
+
201
+ def get_earliest_available(self):
202
+ return self.earliest_available
203
+
204
+
205
+ @dataclasses.dataclass
206
+ class Empty(AllocationTreeNode):
207
+ """
208
+ Placeholder to represent empty space in the allocation pool.
209
+ Only exists to get the size_hint correct in parent nodes.
210
+ """
211
+
212
+ size_hint: int
213
+
214
+ def get_live_ranges(self):
215
+ return LiveRanges([])
216
+
217
+ def get_size_hint(self):
218
+ return self.size_hint
219
+
220
+ def get_symbolic_size(self):
221
+ return 0
222
+
223
+ def is_empty(self):
224
+ return True
225
+
226
+
227
+ class MemorySplitProtocol(Protocol):
228
+ get_live_ranges: CachedMethod[[], LiveRanges]
229
+ get_size_hint: CachedMethod[[], int]
230
+ get_symbolic_size: CachedMethod[[], sympy.Expr]
231
+
232
+ def _allocate(self, block: Allocation, is_last: bool) -> bool: ...
233
+
234
+
235
+ class ClearCacheOnAllocateMixin(MemorySplitProtocol):
236
+ """
237
+ Helper to assist in caching get_live_ranges, get_size_hint, and
238
+ get_symbolic_size.
239
+ """
240
+
241
+ def allocate(self, block: Allocation, is_last: bool):
242
+ is_allocated = self._allocate(block, is_last)
243
+ if is_allocated:
244
+ self.clear_cache()
245
+ return is_allocated
246
+
247
+ def clear_cache(self):
248
+ self.get_live_ranges.clear_cache(self)
249
+ self.get_size_hint.clear_cache(self)
250
+ self.get_symbolic_size.clear_cache(self)
251
+
252
+
253
+ @dataclasses.dataclass
254
+ class TemporalSplit(ClearCacheOnAllocateMixin, AllocationTreeNode):
255
+ """
256
+ Contains a list of allocations not overlapping in LiveRanges.
257
+
258
+ Invariant: no pair (a,b) in self.allocations will have:
259
+ a.get_live_ranges().overlaps(b.get_live_ranges())
260
+ """
261
+
262
+ allocations: list[AllocationTreeNode]
263
+
264
+ def _allocate(self, block: Allocation, is_last: bool):
265
+ slot_size = self.get_size_hint()
266
+ block_size = block.get_size_hint()
267
+ if not is_last and block_size > slot_size:
268
+ return False # doesn't fit
269
+
270
+ block_live = block.get_live_ranges()
271
+ overlapping = [
272
+ s for s in self.allocations if s.get_live_ranges().overlaps(block_live)
273
+ ]
274
+ if len(overlapping) > 1:
275
+ # TODO(jansel): we could try harder here by merging overlapping in space
276
+ return False
277
+ elif len(overlapping) == 1:
278
+ return overlapping[0].allocate(block, is_last)
279
+ else:
280
+ block.mark_allocated()
281
+
282
+ if len(self.allocations) == 1 and isinstance(self.allocations[-1], Empty):
283
+ self.allocations.pop()
284
+
285
+ if slot_size == block_size:
286
+ # perfect fit
287
+ self.allocations.append(block)
288
+ elif slot_size > block_size:
289
+ self.allocations.append(
290
+ SpatialSplit.create(block, slot_size - block_size)
291
+ )
292
+ else: # grow this allocation
293
+ assert is_last
294
+ self.allocations = [
295
+ *(
296
+ SpatialSplit.create(a, block_size - slot_size)
297
+ for a in self.allocations
298
+ ),
299
+ block,
300
+ ]
301
+ return True
302
+
303
+ @cache_on_self
304
+ def get_live_ranges(self) -> LiveRanges:
305
+ return LiveRanges(
306
+ itertools.chain.from_iterable(
307
+ x.get_live_ranges().ranges for x in self.allocations
308
+ )
309
+ )
310
+
311
+ @cache_on_self
312
+ def get_size_hint(self) -> int:
313
+ if not self.allocations:
314
+ return 0
315
+ return max(x.get_size_hint() for x in self.allocations)
316
+
317
+ @cache_on_self
318
+ def get_symbolic_size(self) -> sympy.Expr:
319
+ if not self.allocations:
320
+ return 0 # type: ignore[return-value]
321
+ return sympy.Max(*[x.get_symbolic_size() for x in self.allocations])
322
+
323
+ def is_empty(self):
324
+ return len(self.allocations) == 1 and self.allocations[0].is_empty()
325
+
326
+ def finalize(self, pool, offset):
327
+ self.allocations = [block.finalize(pool, offset) for block in self.allocations]
328
+ self.clear_cache()
329
+ if len(self.allocations) == 1:
330
+ return self.allocations[0]
331
+ return self
332
+
333
+
334
+ @dataclasses.dataclass
335
+ class SpatialSplit(ClearCacheOnAllocateMixin, AllocationTreeNode):
336
+ """
337
+ Contains two allocations, left and right, that do not overlap in space.
338
+ Right will be allocated immediately after left in memory.
339
+ """
340
+
341
+ left: TemporalSplit
342
+ right: TemporalSplit
343
+
344
+ @staticmethod
345
+ def create(left, extra_space):
346
+ assert isinstance(left, AllocationTreeNode)
347
+ assert isinstance(extra_space, int) and extra_space >= 1
348
+ return SpatialSplit(TemporalSplit([left]), TemporalSplit([Empty(extra_space)]))
349
+
350
+ def _allocate(self, block: Allocation, is_last: bool):
351
+ return self.left.allocate(block, False) or self.right.allocate(block, is_last)
352
+
353
+ @cache_on_self
354
+ def get_live_ranges(self):
355
+ return LiveRanges(
356
+ itertools.chain(
357
+ self.left.get_live_ranges().ranges, self.right.get_live_ranges().ranges
358
+ )
359
+ )
360
+
361
+ @cache_on_self
362
+ def get_size_hint(self) -> int:
363
+ return _align(self.left.get_size_hint()) + self.right.get_size_hint()
364
+
365
+ @cache_on_self
366
+ def get_symbolic_size(self) -> sympy.Expr:
367
+ return align(self.left.get_symbolic_size()) + self.right.get_symbolic_size()
368
+
369
+ def finalize(self, pool, offset):
370
+ self.left = self.left.finalize(pool, offset)
371
+ self.right = self.right.finalize(
372
+ pool, offset + align(self.left.get_symbolic_size())
373
+ )
374
+ self.clear_cache()
375
+ if self.right.is_empty():
376
+ return self.left
377
+ return self
378
+
379
+
380
+ @dataclasses.dataclass
381
+ class AllocationPool:
382
+ """
383
+ Represents a pool of allocations that will be generated by a single
384
+ call to torch.empty.
385
+ """
386
+
387
+ device: torch.device
388
+ root: TemporalSplit
389
+ can_expand: bool = True
390
+ restrict_live_range: Optional[LiveRange] = None
391
+ name: Optional[str] = None
392
+ names_to_del: list[str] = dataclasses.field(default_factory=list)
393
+ creation_cache: dict[str, str] = dataclasses.field(default_factory=dict)
394
+
395
+ def __post_init__(self) -> None:
396
+ for block in self.root.allocations:
397
+ if isinstance(block, Allocation):
398
+ self.update_restrict_live_range(block)
399
+
400
+ def allocate(self, block: Allocation, is_last: bool):
401
+ if (
402
+ self.restrict_live_range is not None
403
+ and not self.restrict_live_range.contains(block.live_range)
404
+ ):
405
+ return False
406
+
407
+ block_earliest_available = block.get_earliest_available()
408
+ pool_begin = self.root.get_live_ranges().begin
409
+ if block_earliest_available and block_earliest_available > pool_begin:
410
+ return False
411
+
412
+ is_last = self.can_expand and is_last
413
+ if self.root.allocate(block, is_last):
414
+ self.update_restrict_live_range(block)
415
+ return True
416
+
417
+ if is_last:
418
+ return self.allocate_at_end(block)
419
+
420
+ return False
421
+
422
+ def update_restrict_live_range(self, block: Allocation):
423
+ if block_earliest_available := block.get_earliest_available():
424
+ if self.restrict_live_range is None:
425
+ self.restrict_live_range = LiveRange(
426
+ block_earliest_available, float("inf")
427
+ )
428
+ else:
429
+ self.restrict_live_range = LiveRange(
430
+ min(self.restrict_live_range.begin, block_earliest_available),
431
+ self.restrict_live_range.end,
432
+ )
433
+
434
+ def allocate_at_end(self, block):
435
+ block.mark_allocated()
436
+ self.root = TemporalSplit([SpatialSplit(self.root, TemporalSplit([block]))])
437
+ self.update_restrict_live_range(block)
438
+ return True
439
+
440
+ def finalize(self, name):
441
+ assert not self.name
442
+ self.name = name
443
+ self.names_to_del.append(name)
444
+ self.root.finalize(self, 0)
445
+
446
+ def codegen_create(self, wrapper, code: IndentedBuffer):
447
+ assert self.name
448
+ nbytes = self.root.get_symbolic_size()
449
+ for block in self.root.allocations:
450
+ if isinstance(block, Allocation) and nbytes == block.get_symbolic_size():
451
+ node = block.node
452
+ code.writeline(
453
+ wrapper.make_allocation(
454
+ self.name,
455
+ device=self.device,
456
+ dtype=node.get_dtype(),
457
+ shape=tuple(node.get_size()),
458
+ stride=tuple(node.get_stride()),
459
+ )
460
+ )
461
+ return
462
+ else:
463
+ code.writeline(
464
+ wrapper.make_allocation(
465
+ self.name,
466
+ device=self.device,
467
+ dtype=torch.uint8,
468
+ shape=(nbytes,),
469
+ stride=(1,),
470
+ )
471
+ )
472
+
473
+ def codegen_destroy(self, wrapper, code: IndentedBuffer):
474
+ code.writeline(wrapper.make_free_by_names(self.names_to_del))
475
+
476
+ def __eq__(self, other):
477
+ return self is other
478
+
479
+ def __hash__(self):
480
+ return id(self)
481
+
482
+
483
+ @dataclasses.dataclass
484
+ class AllocationPools:
485
+ """
486
+ Collection of many AllocationPool objects grouped by device.
487
+ """
488
+
489
+ device_to_pools: dict[torch.device, list[AllocationPool]] = dataclasses.field(
490
+ default_factory=dict
491
+ )
492
+
493
+ def get_pools(self, block):
494
+ if block.device not in self.device_to_pools:
495
+ self.device_to_pools[block.device] = []
496
+ return self.device_to_pools[block.device]
497
+
498
+ def allocate(self, block: Allocation):
499
+ pools = self.get_pools(block)
500
+
501
+ for pool in pools:
502
+ if pool.allocate(block, is_last=pool is pools[-1]):
503
+ return
504
+
505
+ # everything is full, make a new pool
506
+ pools.append(
507
+ AllocationPool(
508
+ block.device,
509
+ TemporalSplit([block]),
510
+ can_expand=config.memory_pool != "none",
511
+ )
512
+ )
513
+ block.mark_allocated()
514
+
515
+ def allocate_output(self, block: Allocation):
516
+ """Outputs get different pools so memory gets freed properly"""
517
+ pools = self.get_pools(block)
518
+ if pools and config.memory_pool in ("outputs", "combined"):
519
+ pools[-1].allocate_at_end(block)
520
+ else:
521
+ # create a new pool
522
+ block.mark_allocated()
523
+ pools.append(
524
+ AllocationPool(
525
+ block.device,
526
+ TemporalSplit([block]),
527
+ can_expand=config.memory_pool == "combined",
528
+ )
529
+ )
530
+
531
+ def finalize(self):
532
+ """Called at the end of allocation process"""
533
+ for i, pool in enumerate(
534
+ itertools.chain.from_iterable(self.device_to_pools.values())
535
+ ):
536
+ pool.finalize(f"pool{i}")
537
+
538
+ def pprint(self):
539
+ for pool in itertools.chain.from_iterable(self.device_to_pools.values()):
540
+ print()
541
+ print(pool.name)
542
+ print(pool.root.get_live_ranges())
543
+ pprint.pprint(pool.root)
544
+
545
+
546
+ class BufferGroup:
547
+ """
548
+ Due to inplace reuse an allocated buffer can have many names.
549
+ This tracks these collections of buffers sharing underlying memory.
550
+ """
551
+
552
+ def __init__(self, node: BufferLike):
553
+ self.node = node
554
+ self.names = [node.get_name()]
555
+ self.is_output = False
556
+ self.allocation: Optional[Allocation] = None
557
+ self.live_range = LiveRange(float("inf"), -float("inf"))
558
+
559
+ def update_usage(self, timestep: int):
560
+ """Expand self.live_range to include timestep"""
561
+ self.live_range = LiveRange(
562
+ min(timestep, self.live_range.begin),
563
+ max(timestep, self.live_range.end),
564
+ )
565
+
566
+ def sym_nbytes(self):
567
+ return self.node.get_layout().storage_size() * self.node.get_dtype().itemsize
568
+
569
+ def make_allocation(self):
570
+ assert not self.allocation, "multiple allocations"
571
+ assert isinstance(self.live_range.begin, int), "live ranges not computed"
572
+ nbytes = self.sym_nbytes()
573
+ # For now, fallback value will be used if we encounter an unbacked SymInt. The longer-term plan is to have
574
+ # size_hint() use better heuristics for unbackeds, at which point the fallback value will be ignored.
575
+ size_hint = V.graph.sizevars.optimization_hint(nbytes, fallback=64)
576
+ self.allocation = Allocation(
577
+ self.node,
578
+ self.live_range,
579
+ size_hint=size_hint,
580
+ symbolic_size=nbytes,
581
+ )
582
+
583
+ def __repr__(self):
584
+ return (
585
+ f"{self.__class__.__name__}({self.names!r}, is_output={self.is_output}, "
586
+ f"live_range={self.live_range}"
587
+ )
588
+
589
+
590
+ @dataclasses.dataclass
591
+ class PoolMemoryPlanningLine(MemoryPlanningLine):
592
+ """Abstract base class for {Alloc,Dealloc}FromPoolLine"""
593
+
594
+ group: BufferGroup
595
+ timestep: Optional[int] = None
596
+
597
+ @property
598
+ def node(self):
599
+ return self.group.node
600
+
601
+
602
+ @dataclasses.dataclass
603
+ class AllocFromPoolLine(PoolMemoryPlanningLine):
604
+ """Similar to AllocationLine, but takes memory from a pool"""
605
+
606
+ is_first_pool_usage: bool = False
607
+
608
+ def codegen(self, code: IndentedBuffer):
609
+ allocation = self.group.allocation
610
+ assert allocation and allocation.pool
611
+ pool = allocation.pool
612
+ name = self.node.get_name()
613
+
614
+ if self.is_first_pool_usage:
615
+ pool.codegen_create(self.wrapper, code)
616
+
617
+ pool.names_to_del.extend(self.group.names)
618
+ alloc_from_pool, allocation_lines_to_write = allocation.codegen_alloc_from_pool(
619
+ self.wrapper
620
+ )
621
+ code.writelines(allocation_lines_to_write)
622
+ if alloc_from_pool in pool.creation_cache:
623
+ code.writeline(
624
+ self.wrapper.make_tensor_alias(
625
+ name, pool.creation_cache[alloc_from_pool], "alloc"
626
+ )
627
+ )
628
+ else:
629
+ pool.creation_cache[alloc_from_pool] = name
630
+ code.writeline(
631
+ f"{self.wrapper.declare}{name} = {alloc_from_pool}{self.wrapper.ending}"
632
+ )
633
+
634
+
635
+ @dataclasses.dataclass
636
+ class DeallocFromPoolLine(PoolMemoryPlanningLine):
637
+ """Similar to FreeIfNotReusedLine, but takes memory from a pool"""
638
+
639
+ is_last_pool_usage: bool = False
640
+
641
+ def codegen(self, code: IndentedBuffer):
642
+ if self.is_last_pool_usage:
643
+ assert self.group.allocation and self.group.allocation.pool
644
+ self.group.allocation.pool.codegen_destroy(self.wrapper, code)
645
+
646
+
647
+ @dataclasses.dataclass
648
+ class MemoryPlanner:
649
+ """
650
+ Coordination object to run memory planning passes during wrapper
651
+ codegen.
652
+ """
653
+
654
+ wrapper: Any
655
+ pools: AllocationPools = dataclasses.field(default_factory=AllocationPools)
656
+ buffer_groups: Optional[list[BufferGroup]] = None
657
+
658
+ def plan(self, lines: list[Any]) -> list[Any]:
659
+ """Call all the memory planning passes in sequence"""
660
+ lines = [*lines]
661
+ self.drop_removed_buffers(lines)
662
+ self.convert_to_pool_lines(lines)
663
+ self.compute_live_ranges(lines)
664
+ self.allocate_groups()
665
+ self.mark_first_last_usage(lines)
666
+ return lines
667
+
668
+ def drop_removed_buffers(self, lines):
669
+ """
670
+ Replace any memory planning lines in V.graph.removed_buffers with NullLine
671
+ """
672
+ # drop any removed buffers
673
+ for i, line in enumerate(lines):
674
+ if isinstance(line, (AllocateLine, FreeIfNotReusedLine, ReuseLine)):
675
+ if line.node.get_name() in V.graph.removed_buffers:
676
+ lines[i] = NullLine(self.wrapper)
677
+
678
+ def compute_buffer_groups(self, lines):
679
+ """
680
+ Populates self.buffer_groups with BufferGroup objects that join
681
+ allocations with common storage (due to inplace reuse) into a
682
+ single object.
683
+ """
684
+ name_to_group = {}
685
+ for line in lines:
686
+ if isinstance(line, AllocateLine):
687
+ name = line.node.get_name()
688
+ assert name not in name_to_group
689
+ name_to_group[name] = BufferGroup(line.node)
690
+ elif isinstance(line, ReuseLine):
691
+ old_name = line.node.get_name()
692
+ new_name = line.reused_as.get_name()
693
+ assert new_name not in name_to_group
694
+ # TODO(jansel): we should support reusing buffers created via ExternKernelAlloc
695
+ if old_name in name_to_group:
696
+ name_to_group[old_name].names.append(new_name)
697
+ name_to_group[new_name] = name_to_group[old_name]
698
+
699
+ outputs = OrderedSet(V.graph.get_output_names())
700
+ unique_groups = [*{id(g): g for g in name_to_group.values()}.values()]
701
+ for group in unique_groups:
702
+ group.is_output = any(x in outputs for x in group.names)
703
+
704
+ assert self.buffer_groups is None
705
+ self.buffer_groups = unique_groups
706
+ return name_to_group
707
+
708
+ def convert_to_pool_lines(self, lines):
709
+ """
710
+ Convert AllocateLine/FreeIfNotReusedLine/ReuseLine into their
711
+ pool-based counterparts.
712
+ """
713
+ name_to_group = self.compute_buffer_groups(lines)
714
+ for i, line in enumerate(lines):
715
+ if isinstance(line, AllocateLine):
716
+ if line.node.get_name() in name_to_group:
717
+ lines[i] = AllocFromPoolLine(
718
+ self.wrapper, name_to_group[line.node.get_name()]
719
+ )
720
+ elif isinstance(line, FreeIfNotReusedLine):
721
+ assert not line.is_reused
722
+ if line.node.get_name() in name_to_group:
723
+ lines[i] = DeallocFromPoolLine(
724
+ self.wrapper, name_to_group[line.node.get_name()]
725
+ )
726
+ elif isinstance(line, ReuseLine):
727
+ if line.node.get_name() in name_to_group:
728
+ line.delete_old = False
729
+
730
+ def compute_live_ranges(self, lines):
731
+ """Populate every BufferGroup.live_ranges field based on first/last usage"""
732
+ timestep = 0
733
+ worklist = collections.deque(lines)
734
+ while worklist:
735
+ if isinstance(worklist[0], MemoryPlanningLine):
736
+ timestep += 1
737
+ while worklist and isinstance(worklist[0], MemoryPlanningLine):
738
+ line = worklist.popleft()
739
+ if isinstance(line, PoolMemoryPlanningLine):
740
+ line.group.update_usage(timestep)
741
+ line.timestep = timestep
742
+ else:
743
+ worklist.popleft()
744
+
745
+ timestep += 1
746
+ assert self.buffer_groups is not None
747
+ for group in self.buffer_groups:
748
+ if group.is_output:
749
+ group.update_usage(timestep)
750
+
751
+ def allocate_groups(self):
752
+ """
753
+ Assign every allocation to a specific location in a specific AllocationPool.
754
+ """
755
+ assert config.memory_pool in ("none", "intermediates", "outputs", "combined")
756
+ assert self.buffer_groups is not None
757
+
758
+ for group in self.buffer_groups:
759
+ group.make_allocation()
760
+
761
+ outputs: list[Allocation] = []
762
+ intermediates: list[Allocation] = []
763
+ for group in self.buffer_groups:
764
+ assert group.allocation
765
+ if group.is_output and config.memory_pool != "combined":
766
+ outputs.append(group.allocation)
767
+ else:
768
+ intermediates.append(group.allocation)
769
+
770
+ for block in sorted(
771
+ outputs,
772
+ key=lambda x: (
773
+ x.size_hint,
774
+ -len(x.live_range),
775
+ ),
776
+ ):
777
+ self.pools.allocate_output(block)
778
+
779
+ for block in sorted(
780
+ intermediates,
781
+ key=lambda x: (
782
+ -x.size_hint,
783
+ -len(x.live_range),
784
+ ),
785
+ ):
786
+ self.pools.allocate(block)
787
+
788
+ self.pools.finalize()
789
+
790
+ def mark_first_last_usage(self, lines):
791
+ """
792
+ Populate the AllocFromPoolLine.is_first_pool_usage and
793
+ DeallocFromPoolLine.is_last_pool_usage fields so that pools
794
+ are created/destroyed.
795
+ """
796
+ seen = OrderedSet[AllocationPool]()
797
+ for line in lines:
798
+ if isinstance(line, AllocFromPoolLine):
799
+ assert line.group.allocation
800
+ pool = line.group.allocation.pool
801
+ assert pool is not None
802
+ if pool not in seen:
803
+ line.is_first_pool_usage = True
804
+ seen.add(pool)
805
+
806
+ seen = OrderedSet[AllocationPool]()
807
+ for line in reversed(lines):
808
+ if isinstance(line, DeallocFromPoolLine):
809
+ assert line.group.allocation
810
+ pool = line.group.allocation.pool
811
+ assert pool is not None
812
+ if pool not in seen:
813
+ line.is_last_pool_usage = (
814
+ pool.root.get_live_ranges().end <= line.timestep
815
+ )
816
+ seen.add(pool)