Repository navigation
[triton] Work out a triton kernel's mutated args once, at trace time - #193227
anijain2305 wants to merge 22 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/193227
Note: Links to docs will display an error until the docs builds have been completed. ❌ You can merge normally! (3 Unrelated Failures), 1 Unclassified FailureAs of commit 744a1d7 with merge base b7c1d9a ( UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:
BROKEN TRUNK - The following jobs failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This PR needs a
|
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
| _accessed_tensors_cache: dict[Any, TensorAccesses] = {} | ||
|
|
||
|
|
||
| def _accessed_tensors_cache_key( |
There was a problem hiding this comment.
nit: naming: do we really call this "accessed tensors"? I think the thing you're caching is the ttir mutation analysis
| # kernel source decide the result, while the particular tensors do not - and the | ||
| # names it reports are the kernel's own formal parameters, so they mean the same | ||
| # thing at every call site. | ||
| _accessed_tensors_cache: dict[Any, TensorAccesses] = {} |
| import sympy | ||
| from triton.runtime.autotuner import Autotuner | ||
|
|
||
| parts: list[Any] = [] |
There was a problem hiding this comment.
it's a bit difficult for me to reason about this cache key.
- an alternative is that the triton kernel hop just passes down which tensors are being mutated (I think it might do this already)? and we stop trying to do the ttir analysis over and over again
- naively i would have thought we just cache on the id of the triton kernel
|
I opened #193703 for an orthogonal single-analysis failure mode in the TTIR access walk. This PR correctly removes repeated rediscovery across consumers and launch sites, but The issue includes a synthetic shared-DAG reproducer and a proposed fail-closed repair: memoized per- It would be useful for this PR's analysis-count coverage to remain separate from a traversal-complexity regression test, so both properties stay pinned. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
| analyze_kernel_access.reset() | ||
| get_tma_stores.reset() | ||
|
|
||
| @unittest.skipUnless( |
There was a problem hiding this comment.
here is an alternative design. the triton_kernel_hop takes in a mutation_analysis: tuple[tuple[str, ...], bool] | None argument. Maybe it should never be None, but if it's None, we do the mutation analysis. if it is passed in, then we don't need to do the mutation analysis anymore. thoughts?
my goal is to get rid of the cache and the cache invalidation, because that seems complicated
[ghstack-poisoned]
Working out which arguments a user-defined triton kernel writes, and whether an epilogue can be fused into it, means compiling the kernel to TTIR and walking the result - roughly 100ms per kernel. Four consumers each asked for it independently: functionalization via get_mutated_tensors, two places in inductor lowering, and the UserDefinedTritonKernel IR node. Nothing handed the answer between them, so the same fact was rediscovered at every stage: 56 queries to compute 8 answers on one model, about 5.9s. Work it out once, where the graph node is created, and record it on the node as mutated_arg_names and can_fuse_epilogue. Every consumer now reads it instead of re-deriving it, and the analysis runs 4 times instead of 56. Two places create these nodes and both need it: Dynamo's DynamoTritonHOPifier.call_HOP, and TracingTritonHOPifier.call_HOP for kernels traced outside Dynamo. The second is the one that matters for models that launch kernels inside a custom autograd.Function, where Dynamo never sees the launch - patching only the Dynamo path leaves such models deriving it as before. Both go through analyze_kernel_launch. That helper is cached, and the cache is doing real work rather than papering over the design: launch sites far outnumber distinct kernel signatures - 48 nodes covering 8 signatures on one model - so computing per node without one would run 48 analyses to produce 8 answers, worse than the 56 we started with. What the node argument removes is rediscovery across consumers; the cache removes rediscovery across launch sites. Both are needed, and together they get to 4. Keying that cache on the kernel alone - its id, or its source - would be wrong rather than merely coarse, which the second test pins down. constexprs are compile-time constants, so they decide what TTIR exists at all: a kernel whose tl.store sits under `if DO_STORE` reports out_ptr written for DO_STORE=True and nothing written for DO_STORE=False, from one kernel object. An id-keyed cache that saw the False launch first would report no mutation for the True one, and functionalization would skip the clone. So the key covers what generate_ttir actually feeds Triton - kernel source, argument dtypes, constexpr values - which is narrower than the arguments, because generate_ttir normalizes SymInts to 2 and tensors to an empty tensor of the same dtype first. The node arguments are optional and best effort. A graph need not have come from either tracer - one loaded from a cache predating them, or built by hand, carries neither - and the analysis itself can fail, in which case nothing is recorded and consumers derive it as before. They are threaded through triton_kernel_wrapper_functional too, so they survive functionalization and the post-grad pass that decomposes the functional node back into a mutation node. Note that a dropped argument is invisible to correctness tests, since the fallback is correct and merely slower; it shows up as analysis count, not as a failure. Test plan: ``` python test/inductor/test_triton_kernels.py python test/export/test_serialize.py -k triton python test/dynamo/test_functions.py -k triton python test/dynamo/test_aot_autograd_cache.py -k triton ``` 427 tests in test_triton_kernels.py, failure set identical to a run with the change reverted (2 errors and 2 failures, pre-existing on this aarch64 host: test_i64_input, test_triton_kernel_to_cpu, and two tma_capture_and_functionalize variants). The other three suites pass. test_launch_analysis_reuses_result declares a kernel locally, so nothing can have populated the cache for it, counts calls to generate_ttir while asking the same question twice, and asserts the repeat is served without recompiling to TTIR. It then asks with a different constexpr and asserts that one is analyzed, so an over-broad key cannot pass. test_ttir_analysis_depends_on_constexprs pins the DO_STORE case above. Also checked directly that the value recorded on the node matches what the analysis returns for the same launch, and that a compiled kernel's numerics are unchanged. On one model the analysis count goes 56 -> 4 and cold compile time drops by about 4.8s. This PR was authored with the assistance of an AI coding agent. ghstack-source-id: 12f0f3a Pull-Request: #193227
Working out which arguments a user-defined triton kernel writes, and whether an epilogue can be fused into it, means compiling the kernel to TTIR and walking the result - roughly 100ms per kernel. Four consumers each asked for it independently: functionalization via get_mutated_tensors, two places in inductor lowering, and the UserDefinedTritonKernel IR node. Nothing handed the answer between them, so the same fact was rediscovered at every stage: 56 queries to compute 8 answers on one model, about 5.9s. Work it out once, where the graph node is created, and record it on the node as mutated_arg_names and can_fuse_epilogue. Every consumer now reads it instead of re-deriving it, and the analysis runs 4 times instead of 56. Two places create these nodes and both need it: Dynamo's DynamoTritonHOPifier.call_HOP, and TracingTritonHOPifier.call_HOP for kernels traced outside Dynamo. The second is the one that matters for models that launch kernels inside a custom autograd.Function, where Dynamo never sees the launch - patching only the Dynamo path leaves such models deriving it as before. Both go through analyze_kernel_launch. That helper is cached, and the cache is doing real work rather than papering over the design: launch sites far outnumber distinct kernel signatures - 48 nodes covering 8 signatures on one model - so computing per node without one would run 48 analyses to produce 8 answers, worse than the 56 we started with. What the node argument removes is rediscovery across consumers; the cache removes rediscovery across launch sites. Both are needed, and together they get to 4. Keying that cache on the kernel alone - its id, or its source - would be wrong rather than merely coarse, which the second test pins down. constexprs are compile-time constants, so they decide what TTIR exists at all: a kernel whose tl.store sits under `if DO_STORE` reports out_ptr written for DO_STORE=True and nothing written for DO_STORE=False, from one kernel object. An id-keyed cache that saw the False launch first would report no mutation for the True one, and functionalization would skip the clone. So the key covers what generate_ttir actually feeds Triton - kernel source, argument dtypes, constexpr values - which is narrower than the arguments, because generate_ttir normalizes SymInts to 2 and tensors to an empty tensor of the same dtype first. The node arguments are optional and best effort. A graph need not have come from either tracer - one loaded from a cache predating them, or built by hand, carries neither - and the analysis itself can fail, in which case nothing is recorded and consumers derive it as before. They are threaded through triton_kernel_wrapper_functional too, so they survive functionalization and the post-grad pass that decomposes the functional node back into a mutation node. Note that a dropped argument is invisible to correctness tests, since the fallback is correct and merely slower; it shows up as analysis count, not as a failure. Test plan: ``` python test/inductor/test_triton_kernels.py python test/export/test_serialize.py -k triton python test/dynamo/test_functions.py -k triton python test/dynamo/test_aot_autograd_cache.py -k triton ``` 427 tests in test_triton_kernels.py, failure set identical to a run with the change reverted (2 errors and 2 failures, pre-existing on this aarch64 host: test_i64_input, test_triton_kernel_to_cpu, and two tma_capture_and_functionalize variants). The other three suites pass. test_launch_analysis_reuses_result declares a kernel locally, so nothing can have populated the cache for it, counts calls to generate_ttir while asking the same question twice, and asserts the repeat is served without recompiling to TTIR. It then asks with a different constexpr and asserts that one is analyzed, so an over-broad key cannot pass. test_ttir_analysis_depends_on_constexprs pins the DO_STORE case above. Also checked directly that the value recorded on the node matches what the analysis returns for the same launch, and that a compiled kernel's numerics are unchanged. On one model the analysis count goes 56 -> 4 and cold compile time drops by about 4.8s. This PR was authored with the assistance of an AI coding agent. ghstack-source-id: 12f0f3a Pull-Request: #193227
Working out which arguments a user-defined triton kernel writes, and whether an epilogue can be fused into it, means compiling the kernel to TTIR and walking the result - roughly 100ms per kernel. Four consumers each asked for it independently: functionalization via get_mutated_tensors, two places in inductor lowering, and the UserDefinedTritonKernel IR node. Nothing handed the answer between them, so the same fact was rediscovered at every stage: 56 queries to compute 8 answers on one model, about 5.9s. Work it out once, where the graph node is created, and record it on the node as mutated_arg_names and can_fuse_epilogue. Every consumer now reads it instead of re-deriving it, and the analysis runs 4 times instead of 56. Two places create these nodes and both need it: Dynamo's DynamoTritonHOPifier.call_HOP, and TracingTritonHOPifier.call_HOP for kernels traced outside Dynamo. The second is the one that matters for models that launch kernels inside a custom autograd.Function, where Dynamo never sees the launch - patching only the Dynamo path leaves such models deriving it as before. Both go through analyze_kernel_launch. That helper is cached, and the cache is doing real work rather than papering over the design: launch sites far outnumber distinct kernel signatures - 48 nodes covering 8 signatures on one model - so computing per node without one would run 48 analyses to produce 8 answers, worse than the 56 we started with. What the node argument removes is rediscovery across consumers; the cache removes rediscovery across launch sites. Both are needed, and together they get to 4. Keying that cache on the kernel alone - its id, or its source - would be wrong rather than merely coarse, which the second test pins down. constexprs are compile-time constants, so they decide what TTIR exists at all: a kernel whose tl.store sits under `if DO_STORE` reports out_ptr written for DO_STORE=True and nothing written for DO_STORE=False, from one kernel object. An id-keyed cache that saw the False launch first would report no mutation for the True one, and functionalization would skip the clone. So the key covers what generate_ttir actually feeds Triton - kernel source, argument dtypes, constexpr values - which is narrower than the arguments, because generate_ttir normalizes SymInts to 2 and tensors to an empty tensor of the same dtype first. The node arguments are optional and best effort. A graph need not have come from either tracer - one loaded from a cache predating them, or built by hand, carries neither - and the analysis itself can fail, in which case nothing is recorded and consumers derive it as before. They are threaded through triton_kernel_wrapper_functional too, so they survive functionalization and the post-grad pass that decomposes the functional node back into a mutation node. Note that a dropped argument is invisible to correctness tests, since the fallback is correct and merely slower; it shows up as analysis count, not as a failure. Test plan: ``` python test/inductor/test_triton_kernels.py python test/export/test_serialize.py -k triton python test/dynamo/test_functions.py -k triton python test/dynamo/test_aot_autograd_cache.py -k triton ``` 427 tests in test_triton_kernels.py, failure set identical to a run with the change reverted (2 errors and 2 failures, pre-existing on this aarch64 host: test_i64_input, test_triton_kernel_to_cpu, and two tma_capture_and_functionalize variants). The other three suites pass. test_launch_analysis_reuses_result declares a kernel locally, so nothing can have populated the cache for it, counts calls to generate_ttir while asking the same question twice, and asserts the repeat is served without recompiling to TTIR. It then asks with a different constexpr and asserts that one is analyzed, so an over-broad key cannot pass. test_ttir_analysis_depends_on_constexprs pins the DO_STORE case above. Also checked directly that the value recorded on the node matches what the analysis returns for the same launch, and that a compiled kernel's numerics are unchanged. On one model the analysis count goes 56 -> 4 and cold compile time drops by about 4.8s. This PR was authored with the assistance of an AI coding agent. ghstack-source-id: 12f0f3a Pull-Request: #193227
[ghstack-poisoned]
Working out which arguments a user-defined triton kernel writes, and whether an epilogue can be fused into it, means compiling the kernel to TTIR and walking the result - roughly 100ms per kernel. Four consumers each asked for it independently: functionalization via get_mutated_tensors, two places in inductor lowering, and the UserDefinedTritonKernel IR node. Nothing handed the answer between them, so the same fact was rediscovered at every stage: 56 queries to compute 8 answers on one model, about 5.9s. Work it out once, where the graph node is created, and record it on the node as mutated_arg_names and can_fuse_epilogue. Every consumer now reads it instead of re-deriving it, and the analysis runs 4 times instead of 56. Two places create these nodes and both need it: Dynamo's DynamoTritonHOPifier.call_HOP, and TracingTritonHOPifier.call_HOP for kernels traced outside Dynamo. The second is the one that matters for models that launch kernels inside a custom autograd.Function, where Dynamo never sees the launch - patching only the Dynamo path leaves such models deriving it as before. Both go through analyze_kernel_launch. That helper is cached, and the cache is doing real work rather than papering over the design: launch sites far outnumber distinct kernel signatures - 48 nodes covering 8 signatures on one model - so computing per node without one would run 48 analyses to produce 8 answers, worse than the 56 we started with. What the node argument removes is rediscovery across consumers; the cache removes rediscovery across launch sites. Both are needed, and together they get to 4. Keying that cache on the kernel alone - its id, or its source - would be wrong rather than merely coarse, which the second test pins down. constexprs are compile-time constants, so they decide what TTIR exists at all: a kernel whose tl.store sits under `if DO_STORE` reports out_ptr written for DO_STORE=True and nothing written for DO_STORE=False, from one kernel object. An id-keyed cache that saw the False launch first would report no mutation for the True one, and functionalization would skip the clone. So the key covers what generate_ttir actually feeds Triton - kernel source, argument dtypes, constexpr values - which is narrower than the arguments, because generate_ttir normalizes SymInts to 2 and tensors to an empty tensor of the same dtype first. The node arguments are optional and best effort. A graph need not have come from either tracer - one loaded from a cache predating them, or built by hand, carries neither - and the analysis itself can fail, in which case nothing is recorded and consumers derive it as before. They are threaded through triton_kernel_wrapper_functional too, so they survive functionalization and the post-grad pass that decomposes the functional node back into a mutation node. Note that a dropped argument is invisible to correctness tests, since the fallback is correct and merely slower; it shows up as analysis count, not as a failure. Test plan: ``` python test/inductor/test_triton_kernels.py python test/export/test_serialize.py -k triton python test/dynamo/test_functions.py -k triton python test/dynamo/test_aot_autograd_cache.py -k triton ``` 427 tests in test_triton_kernels.py, failure set identical to a run with the change reverted (2 errors and 2 failures, pre-existing on this aarch64 host: test_i64_input, test_triton_kernel_to_cpu, and two tma_capture_and_functionalize variants). The other three suites pass. test_launch_analysis_reuses_result declares a kernel locally, so nothing can have populated the cache for it, counts calls to generate_ttir while asking the same question twice, and asserts the repeat is served without recompiling to TTIR. It then asks with a different constexpr and asserts that one is analyzed, so an over-broad key cannot pass. test_ttir_analysis_depends_on_constexprs pins the DO_STORE case above. Also checked directly that the value recorded on the node matches what the analysis returns for the same launch, and that a compiled kernel's numerics are unchanged. On one model the analysis count goes 56 -> 4 and cold compile time drops by about 4.8s. This PR was authored with the assistance of an AI coding agent. ghstack-source-id: d41ce63 Pull-Request: #193227
[ghstack-poisoned]
Working out which arguments a user-defined triton kernel writes, and whether an
epilogue can be fused into it, means compiling the kernel to TTIR and walking the
result - tens of milliseconds per kernel, about 90ms on the model below. Four
consumers each asked for it independently: functionalization via
get_mutated_tensors, two places in inductor lowering, and the
UserDefinedTritonKernel IR node. Nothing handed the answer between them, so the
same fact was rediscovered at every stage.
Work it out once, where the graph node is created, and record it on the node as a
single `mutation_analysis: tuple[tuple[str, ...], bool] | None` argument. Every
consumer reads it instead of re-deriving it.
Two places create these nodes and both need it: Dynamo's
DynamoTritonHOPifier.call_HOP, and TracingTritonHOPifier.call_HOP for kernels
traced outside Dynamo. The second is the one that matters for models that launch
kernels inside a custom autograd.Function, where Dynamo never sees the launch -
patching only the Dynamo path leaves such models deriving it as before.
The argument and the cache remove different duplication, so both earn their keep.
Time spent inside identify_accessed_tensors on a cold compile of one model:
before 56 analyses 5000 ms
argument only 48 analyses 2450 ms
argument plus cache 4 analyses 449 ms
The argument is what takes 56 -> 48: consumers stop re-deriving per launch site,
and each analysis also gets cheaper because Dynamo calls it with fake tensors
rather than inductor calling it with TensorBoxes. The cache is what takes 48 -> 4,
collapsing that model's 48 launch sites onto its 4 distinct kernel signatures.
Keying that cache on the kernel alone - its id, or its source - would be wrong
rather than merely coarse, which the second test pins down. constexprs are
compile-time constants, so they decide what TTIR exists at all: a kernel whose
tl.store sits under `if DO_STORE` reports out_ptr written for DO_STORE=True and
nothing written for DO_STORE=False, from one kernel object. An id-keyed cache
that saw the False launch first would report no mutation for the True one, and
functionalization would skip the clone. So the key covers what generate_ttir
actually feeds Triton - kernel source, argument dtypes, constexpr values - which
is narrower than the arguments, because generate_ttir normalizes SymInts to 2 and
tensors to an empty tensor of the same dtype first.
The cache needs no invalidation. kernel_side_table.reset_table() resets index to
kernel maps, while this is keyed on the kernel's source and the constexprs, so a
kernel swapped in later gets a different key rather than a stale answer. Its size
is bounded where entries are written.
The node argument is optional and best effort. A graph need not have come from
either tracer - one loaded from a cache predating it, or built by hand, carries
nothing - and the analysis itself can fail, in which case nothing is recorded and
consumers derive it as before. It is threaded through
triton_kernel_wrapper_functional too, so it survives functionalization and the
post-grad pass that decomposes the functional node back into a mutation node.
Note that a dropped argument is invisible to correctness tests, since the
fallback is correct and merely slower; it shows up as analysis count, not as a
failure.
Test plan:
```
python -m pytest -q -p no:randomly test/inductor/test_triton_kernels.py
# 400 passed, 2 failed, 25 skipped
python -m pytest -q -p no:randomly test/test_fx.py
# 576 passed, 209 failed
```
Both failure sets are identical to a run with the change reverted. The two
test_triton_kernels failures are tma_capture_and_functionalize variants and the
test_fx ones are environmental, all pre-existing on this host.
test_ttir_mutation_analysis_reuses_result declares a kernel locally, so nothing
can have populated the cache for it, counts calls to generate_ttir while asking
the same question twice, and asserts the repeat is served without recompiling to
TTIR. It then asks with a different constexpr and asserts that one is analyzed,
so an over-broad key cannot pass. test_ttir_analysis_depends_on_constexprs pins
the DO_STORE case above.
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: 8f9abf6
Pull-Request: #193227
[ghstack-poisoned]
Working out which arguments a user-defined triton kernel writes, and whether an
epilogue can be fused into it, means compiling the kernel to TTIR and walking the
result - tens of milliseconds per kernel, about 90ms on the model below. Four
consumers each asked for it independently: functionalization via
get_mutated_tensors, two places in inductor lowering, and the
UserDefinedTritonKernel IR node. Nothing handed the answer between them, so the
same fact was rediscovered at every stage.
Work it out once, where the graph node is created, and record it on the node as a
single `mutation_analysis: tuple[tuple[str, ...], bool] | None` argument. Every
consumer reads it instead of re-deriving it.
Two places create these nodes and both need it: Dynamo's
DynamoTritonHOPifier.call_HOP, and TracingTritonHOPifier.call_HOP for kernels
traced outside Dynamo. The second is the one that matters for models that launch
kernels inside a custom autograd.Function, where Dynamo never sees the launch -
patching only the Dynamo path leaves such models deriving it as before.
The argument and the cache remove different duplication, so both earn their keep.
Time spent inside identify_accessed_tensors on a cold compile of one model:
before 56 analyses 5000 ms
argument only 48 analyses 2450 ms
argument plus cache 4 analyses 449 ms
The argument is what takes 56 -> 48: consumers stop re-deriving per launch site,
and each analysis also gets cheaper because Dynamo calls it with fake tensors
rather than inductor calling it with TensorBoxes. The cache is what takes 48 -> 4,
collapsing that model's 48 launch sites onto its 4 distinct kernel signatures.
Keying that cache on the kernel alone - its id, or its source - would be wrong
rather than merely coarse, which the second test pins down. constexprs are
compile-time constants, so they decide what TTIR exists at all: a kernel whose
tl.store sits under `if DO_STORE` reports out_ptr written for DO_STORE=True and
nothing written for DO_STORE=False, from one kernel object. An id-keyed cache
that saw the False launch first would report no mutation for the True one, and
functionalization would skip the clone. So the key covers what generate_ttir
actually feeds Triton - kernel source, argument dtypes, constexpr values - which
is narrower than the arguments, because generate_ttir normalizes SymInts to 2 and
tensors to an empty tensor of the same dtype first.
The cache needs no invalidation. kernel_side_table.reset_table() resets index to
kernel maps, while this is keyed on the kernel's source and the constexprs, so a
kernel swapped in later gets a different key rather than a stale answer. Its size
is bounded where entries are written.
The node argument is optional and best effort. A graph need not have come from
either tracer - one loaded from a cache predating it, or built by hand, carries
nothing - and the analysis itself can fail, in which case nothing is recorded and
consumers derive it as before. It is threaded through
triton_kernel_wrapper_functional too, so it survives functionalization and the
post-grad pass that decomposes the functional node back into a mutation node.
Note that a dropped argument is invisible to correctness tests, since the
fallback is correct and merely slower; it shows up as analysis count, not as a
failure.
Test plan:
```
python -m pytest -q -p no:randomly test/inductor/test_triton_kernels.py
# 400 passed, 2 failed, 25 skipped
python -m pytest -q -p no:randomly test/test_fx.py
# 576 passed, 209 failed
```
Both failure sets are identical to a run with the change reverted. The two
test_triton_kernels failures are tma_capture_and_functionalize variants and the
test_fx ones are environmental, all pre-existing on this host.
test_ttir_mutation_analysis_reuses_result declares a kernel locally, so nothing
can have populated the cache for it, counts calls to generate_ttir while asking
the same question twice, and asserts the repeat is served without recompiling to
TTIR. It then asks with a different constexpr and asserts that one is analyzed,
so an over-broad key cannot pass. test_ttir_analysis_depends_on_constexprs pins
the DO_STORE case above.
This PR was authored with the assistance of an AI coding agent.
ghstack-source-id: 00b42ca
Pull-Request: #193227
| ] = {} | ||
|
|
||
|
|
||
| def ttir_mutation_analysis_cache_key( |
There was a problem hiding this comment.
this seems way too brittle for us. codex suggested trying to reuse the triton compilation cache key, which does seem more robust to me:
Yes. Triton has two relevant keys:
- ASTSource.hash(): hashes the kernel dependency hash, argument signature, constexpr constants, and specialization attributes.
- triton.compiler.compiler.get_cache_key(...): additionally includes the Triton version, backend, backend options, and cache-
invalidating environment variables.
Using Triton’s canonical key would be substantially safer than duplicating its logic here. A good design would refactor
generate_ttir() into:
prepare ASTSource + backend/options
↓
compute Triton key
↓
check mutation-analysis cache
↓ miss
generate TTIR and analyze
It should also clear or version the analysis cache when register_kernel_access_op() changes the interpretation of TTIR.
The caveat is that get_cache_key is private and may differ across supported Triton versions. Even so, adapting that API in one
compatibility helper is less brittle than maintaining an independent approximation of Triton’s compilation inputs.
There was a problem hiding this comment.
If it is too hard to do this, then make some explicit way for the user to tell us the mutation information and skip the TTIR analysis to avoid needing to cache anything. I don't want to trade off potential silent incorrectness for faster compile times
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
Stack from ghstack (oldest at bottom):
Working out which arguments a user-defined triton kernel writes, and whether an
epilogue can be fused into it, means compiling the kernel to TTIR and walking the
result - tens of milliseconds per kernel, about 90ms on the model below. Four
consumers each asked for it independently: functionalization via
get_mutated_tensors, two places in inductor lowering, and the
UserDefinedTritonKernel IR node. Nothing handed the answer between them, so the
same fact was rediscovered at every stage.
Work it out once, where the graph node is created, and record it on the node as a
single
mutation_analysis: tuple[tuple[str, ...], bool] | Noneargument. Everyconsumer reads it instead of re-deriving it.
Two places create these nodes and both need it: Dynamo's
DynamoTritonHOPifier.call_HOP, and TracingTritonHOPifier.call_HOP for kernels
traced outside Dynamo. The second is the one that matters for models that launch
kernels inside a custom autograd.Function, where Dynamo never sees the launch -
patching only the Dynamo path leaves such models deriving it as before.
The argument and the cache remove different duplication, so both earn their keep.
Time spent inside identify_accessed_tensors on a cold compile of one model:
The argument is what takes 56 -> 48: consumers stop re-deriving per launch site,
and each analysis also gets cheaper because Dynamo calls it with fake tensors
rather than inductor calling it with TensorBoxes. The cache is what takes 48 -> 4,
collapsing that model's 48 launch sites onto its 4 distinct kernel signatures.
Keying that cache on the kernel alone - its id, or its source - would be wrong
rather than merely coarse, which the second test pins down. constexprs are
compile-time constants, so they decide what TTIR exists at all: a kernel whose
tl.store sits under
if DO_STOREreports out_ptr written for DO_STORE=True andnothing written for DO_STORE=False, from one kernel object. An id-keyed cache
that saw the False launch first would report no mutation for the True one, and
functionalization would skip the clone. So the key covers what generate_ttir
actually feeds Triton - kernel source, argument dtypes, constexpr values - which
is narrower than the arguments, because generate_ttir normalizes SymInts to 2 and
tensors to an empty tensor of the same dtype first.
The cache needs no invalidation. kernel_side_table.reset_table() resets index to
kernel maps, while this is keyed on the kernel's source and the constexprs, so a
kernel swapped in later gets a different key rather than a stale answer. Its size
is bounded where entries are written.
The node argument is optional and best effort. A graph need not have come from
either tracer - one loaded from a cache predating it, or built by hand, carries
nothing - and the analysis itself can fail, in which case nothing is recorded and
consumers derive it as before. It is threaded through
triton_kernel_wrapper_functional too, so it survives functionalization and the
post-grad pass that decomposes the functional node back into a mutation node.
Note that a dropped argument is invisible to correctness tests, since the
fallback is correct and merely slower; it shows up as analysis count, not as a
failure.
Test plan:
Both failure sets are identical to a run with the change reverted. The two
test_triton_kernels failures are tma_capture_and_functionalize variants and the
test_fx ones are environmental, all pre-existing on this host.
test_ttir_mutation_analysis_reuses_result declares a kernel locally, so nothing
can have populated the cache for it, counts calls to generate_ttir while asking
the same question twice, and asserts the repeat is served without recompiling to
TTIR. It then asks with a different constexpr and asserts that one is analyzed,
so an over-broad key cannot pass. test_ttir_analysis_depends_on_constexprs pins
the DO_STORE case above.
This PR was authored with the assistance of an AI coding agent.
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @azahed98