Skip to content

Add support for conditional nodes in cuda graphs. - #130386

Closed
galv wants to merge 1 commit into
pytorch:mainfrom
galv:galv/cudagraphs-conditional-nodes-3
Closed

galv wants to merge 1 commit into
pytorch:mainfrom
galv:galv/cudagraphs-conditional-nodes-3

Conversation

@galv

@galv galv commented Jul 9, 2024 •

Copy link
Copy Markdown
Collaborator

This allows torch.cond and torch.while_loop to be captured in a single cuda graph. This is done by manually inserting conditional IF nodes and conditional WHILE nodes during stream capture. This approach is discussed here:

https://developer.nvidia.com/blog/dynamic-control-flow-in-cuda-graphs-with-conditional-nodes

Previously, data-depenent control flow would force the usage of cuda graph trees, since data-dependent control flow was done on the CPU. Now, data-dependent control flow is done on the GPU.

This work depends upon CUDA 12.4, since cuda graph conditional nodes were introduced in CUDA 12.4.

This works only with torch.compile(..., backend="eager") and torch.compile(..., backend="cudagraphs") backends right now. Notably, there is no inductor support at this time!

Conditional nodes for cuda graphs were first experimented with in https://arxiv.org/abs/2406.03791 . While this paper showed strong improvements in data-dependent workloads that were very CPU-overhead bound, the next place to look for improvement is horizontal and vertical kernel fusion, which can eventually be enabled automatically once conditional nodes work with backends like inductor. This PR is the first step towards that. I also expect this work to benefit more sophisticated models like autoregressive decoding of LLMs, at least for users that are using static shape kv-caches.

This is work done by @tingyangk and me.

We have a sophisticated example of RNN-T greedy decoding (the algorithm discussing in the paper) working with this new feature here: tingyangk/NeMo@975a806#diff-2c2a72c9a5392d4a6ea5149fea3ce7900b9fd2c630e460bbab94547379553ceaR376

Some design decisions:

  1. We initially implemented this by using the pypi cuda-python package. We changed to modifying CUDAGraph.cpp instead, and wrapping the new methods in pybind11 to expose them in python. This would presumably allow for triton's C++ code generator to call the relevant APIs. It also avoids a new dependency on cuda-python. As a nuisance, the "bodies" of conditional nodes need to be captured to new streams. Therefore, we need access to the stream capture mode of the currently capturing stream to pass to cudaStreamBeginCaptureToGraph().

  2. We expose the currently capturing CUDAGraph via a thread_local variable with the static method
    CUDAGraph::get_currently_capturing_graph(). Basically, since we don't pass the CUDAGraph at every step of a particular computation, we need to be able to access it to call the newly exposed APIs. There is a long doc string in CUDAGraph.cpp about this, but the TL;DR is that it may be more correct to have a global hash table mapping CUDAStreams to CUDAGraphs instead. It depends on whether or not pytorch code is ever expected to stream capture to a graph from more than one thread. I don't believe that any pytorch code today does this, but I may be mistaken.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @chenyang78 @kadeng @chauhang @amjames @rec

@galv
galv requested a review from eqy as a code owner July 9, 2024 22:27
@pytorch-bot

pytorch-bot Bot commented Jul 9, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/130386

Note: Links to docs will display an error until the docs builds have been completed.

❌ 8 New Failures, 3 Unrelated Failures

As of commit e0192ca with merge base 2ff98bc (image):

NEW FAILURES - The following jobs have failed:

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

UNSTABLE - The following job failed but was likely due to flakiness present on trunk and has been marked as unstable:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@linux-foundation-easycla

linux-foundation-easycla Bot commented Jul 9, 2024 •

Copy link
Copy Markdown

CLA Signed

The committers listed above are authorized under a signed CLA.

  • ✅ login: galv / name: Daniel Galvez (e0192ca)

@galv

galv commented Jul 9, 2024

Copy link
Copy Markdown
Collaborator Author

Comment thread torch/_dynamo/backends/cudagraphs.py Outdated

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@eellison can we get your advice on this issue? Presumably there is a way to grab the schema of a higher order op after speculate_subgraph() has been run, but we're not all that familiar with it torch dynamo.

You can reproduce the issue by commenting out

            if isinstance(n.target, HigherOrderOperator):
                continue

And running any of the newly added unit tests in this PR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@BoyuanFeng since you worked on 8bf0be7, can you give your opinion on whether simply skipping over a higher order op is appropriate to do when checking for input mutations? My impression is no.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked with @ydwu4.

Higher order op has 2 branches and we need to check input mutation for ops in each branch. These ops provide schema. Please reuse code here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These ops provide schema.

They don't have schema currently so we need to support them case by case.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @zou3519 on wanting to look at effects/schema of higher order op

Comment thread torch/csrc/cuda/Graph.cpp Outdated

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: Do we need to make wrappers for these new functions in

class graph:
for the sake of the docs ?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we intend to expose in user land. not needed for this pr. Good to update torch/_C/__init__.pyi.in though

@ydwu4

ydwu4 commented Jul 10, 2024

Copy link
Copy Markdown
Contributor

cc @aakhundov

Comment thread test/functorch/test_control_flow.py Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message is a little bit misleading, if we return self.flag, it's actually an input aliasing, which we haven't yet supported right now.

@ydwu4 ydwu4 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HOP front end part looks good to me.

@eqy eqy added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 10, 2024
@pytorch-bot

pytorch-bot Bot commented Jul 10, 2024

Copy link
Copy Markdown

Please seek CI approval before scheduling CIFlow labels

@pytorch-bot pytorch-bot Bot removed the ciflow/trunk Trigger trunk jobs on your pull request label Jul 10, 2024
Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Resolved
@eellison
eellison self-requested a review July 10, 2024 14:10
@galv
galv force-pushed the galv/cudagraphs-conditional-nodes-3 branch from 2ae7361 to 9dc4ca6 Compare July 18, 2024 21:39
@galv
galv requested a review from a team as a code owner July 18, 2024 21:39
@galv
galv force-pushed the galv/cudagraphs-conditional-nodes-3 branch from 9dc4ca6 to 3abbeca Compare July 18, 2024 21:49
@eqy eqy added ciflow/trunk Trigger trunk jobs on your pull request ciflow/periodic Trigger jobs ran periodically on master (periodic.yml) on the PR ciflow/inductor labels Jul 18, 2024

@eellison eellison left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very cool! nothing too blocking but have some comments

Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we push -1 here ?

Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Outdated
Comment on lines 431 to 442

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just for me to understand, are we capturing cond, true_block, or false_block ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This code is actually used to capture either true_block or false_block.

CUDA currently does not currently support an if-else conditional nodes (this is coming out in a later version of cuda, so it is a few months out), so as I mention elsewhere, I use two if conditional nodes, one for true_block and one for false_block, in order to implement torch.cond.

When you ask "are we capturing cond", I'm not sure if you refer to capturing the entirety of torch.cond or evaluation of the boolean predicate. But basically, the entirety of torch.cond will run in the stream that was being used when begin_capture_to_if_node() was called. The actual execution does not need to use either of the ancillary streams used to capture true_block or the false_block, since only one is going to execute. Therefore, the original cuda stream will be used, and thus there is no need for a "channel switch", which can cost overhead. It's just a quirk of implementation that a new stream is required to create the true_block and the fasle_block.

Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Resolved
Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could maybe factor out some of the conditional handle creation

Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

which dependencies are we capturing here ? the cond checking ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, in this case we are capturing a single kernel node which is called by the static method set_conditional_handle(). You can see in CUDAGraph.cu that this kernel calls the device function cudaGraphSetConditional(), which sets a special boolean global memory that the if conditional node will read to decide whether or not to execute its child graph.

An alternative would be to manually use the cuda graph API to add this kernel node directly, but then that would still need to call cudaStreamGetCaptureInfo() for that kernel node to know what nodes come before it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: pred.ndim == 0

Comment on lines 34 to 35

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think youd have to memory plan to avoid copy... not easily doable outside torch.compile

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think save the micro-optimizations till it works in inductor, but we could avoid the extra torch.logical_not kernel by having version set_conditional_handle_kernel that reads !value

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I considered this. My other consideration was that we would have to create two kernels, which takes up instruction memory space. So I was a little bit unsure of what the right approach was. Also bear in mind that once conditional nodes support if-else blocks, we could totally eliminate the extra kernel call for evaluating whether or not to go down the else block.

Comment thread torch/csrc/cuda/Graph.cpp Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we intend to expose in user land. not needed for this pr. Good to update torch/_C/__init__.pyi.in though

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just thinking out loud on the cuda caching allocator interactions (for this and if node).. I think it works as is because none of the carried values will be live in the next iteration.

What happens if the loop is never entered ? do we need to unify output data ptrs for this case ?

@galv
galv force-pushed the galv/cudagraphs-conditional-nodes-3 branch from 1f93f6c to 6c6d27e Compare July 19, 2024 19:36
@tingyangk
tingyangk force-pushed the galv/cudagraphs-conditional-nodes-3 branch 2 times, most recently from 22d8726 to ed7c376 Compare July 26, 2024 07:13
@eellison

eellison commented Aug 2, 2024

Copy link
Copy Markdown
Contributor

please re-request review when ready - I know you were thinking about torch.cond

@galv

galv commented Aug 2, 2024

Copy link
Copy Markdown
Collaborator Author

@eellison sure, @tingyangk is looking into figuring out input mutation checking #130386 (comment) and I am looking at adding a way to do warmup on all "basic blocks" of a graph with control flow, without side effects (probably via relaxed stream capture via a new TorchDispatchMode, as discussed). So don't expect a re-review until we iron those out.

@eellison

eellison commented Aug 6, 2024

Copy link
Copy Markdown
Contributor

cc @zou3519, do we have any restrictions on mutation in control flow that would simplify this ? Also, @galv, not sure what exactly target use cases are, but I will also mention that as part of inductor torch.cond we have existing facilities for warming up control flow and would not need to handle this.

@galv

galv commented Aug 7, 2024

Copy link
Copy Markdown
Collaborator Author

Also, @galv, not sure what exactly target use cases are, but I will also mention that as part of inductor torch.cond we have existing facilities for warming up control flow and would not need to handle this.

@eellison do you mind pointing me to a file I can read to learn more?

@zou3519

zou3519 commented Aug 8, 2024

Copy link
Copy Markdown
Contributor

cc @zou3519, do we have any restrictions on mutation in control flow that would simplify this ? Also, @galv, not sure what exactly target use cases are, but I will also mention that as part of inductor torch.cond we have existing facilities for warming up control flow and would not need to handle this.

When we get to Inductor, the cond operator should have no mutations in either subgraph. Does that help? (I haven't read the rest of the PR, am catching up)

@eellison

eellison commented Aug 8, 2024

Copy link
Copy Markdown
Contributor

@galv - we have code in aot_inductor to warmup triton kernels, but I realize it doesn't necessarily warm up kernels like cudnn which is needed here.

It might be simplest and easiest to iterate over both branches of the cond, instantiate tensors for each node, then run the target.

This allows torch.cond and torch.while_loop to be captured in a single
cuda graph. This is done by manually inserting conditional IF nodes
and conditional WHILE nodes during stream capture. This approach is
discussed here:

https://developer.nvidia.com/blog/dynamic-control-flow-in-cuda-graphs-with-conditional-nodes

Previously, data-depenent control flow would force the
usage of cuda graph trees, since data-dependent control flow was done
on the CPU. Now, data-dependent control flow is done on the GPU.

This work depends upon CUDA 12.4, since cuda graph conditional nodes
were introduced in CUDA 12.4.

This works only with torch.compile(..., backend="eager") and
torch.compile(..., backend="cudagraphs") backends right now. Notably,
there is no inductor support at this time!

Conditional nodes for cuda graphs were first experimented with in
https://arxiv.org/abs/2406.03791 . While this paper showed strong
improvements in data-dependent workloads that were very CPU-overhead
bound, the next place to look for improvement is horizontal and
vertical kernel fusion, which can eventually be enabled automatically
once conditional nodes work with backends like inductor. This PR is
the first step towards that. I also expect this work to benefit more
sophisticated models like autoregressive decoding of LLMs, at least
for users that are using static shape kv-caches.

This is work done by @tingyangk and me.

We have a sophisticated example of RNN-T greedy decoding (the
algorithm discussing in the paper) working with this new feature here:
tingyangk/NeMo@975a806#diff-2c2a72c9a5392d4a6ea5149fea3ce7900b9fd2c630e460bbab94547379553ceaR376

Some design decisions:

1. We initially implemented this by using the pypi cuda-python
package. We changed to modifying CUDAGraph.cpp instead, and wrapping
the new methods in pybind11 to expose them in python. This would
presumably allow for triton's C++ code generator to call the relevant
APIs. It also avoids a new dependency on cuda-python. As a nuisance,
the "bodies" of conditional nodes need to be captured to new streams.
Therefore, we need access to the stream capture mode of the currently
capturing stream to pass to cudaStreamBeginCaptureToGraph().

2. We expose the currently capturing CUDAGraph via a thread_local
variable with the static method
CUDAGraph::get_currently_capturing_graph(). Basically, since we don't
pass the CUDAGraph at every step of a particular computation, we need
to be able to access it to call the newly exposed APIs. There is a
long doc string in CUDAGraph.cpp about this, but the TL;DR is that it
may be more correct to have a global hash table mapping CUDAStreams to
CUDAGraphs instead. It depends on whether or not pytorch code is ever
expected to stream capture to a graph from more than one thread. I
don't believe that any pytorch code today does this, but I may be
mistaken.

Enable conditional nodes only for CUDA 12.4 and up.
@tingyangk
tingyangk force-pushed the galv/cudagraphs-conditional-nodes-3 branch from ed7c376 to e0192ca Compare August 15, 2024 04:14
@tingyangk
tingyangk requested a review from syed-ahmed as a code owner August 15, 2024 04:14
@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Oct 14, 2024
@github-actions github-actions Bot closed this Nov 13, 2024
pytorchmergebot pushed a commit that referenced this pull request Feb 11, 2025
…op (#140979)

This is a new PR for #130386 , which got stale and was closed. Since I force-pushed to that branch in order to rebase it on top of main, the PR can no longer be reopened, according to isaacs/github#361

I fixed the possibly-not-warmed-up problem described here: https://github.com/pytorch/pytorch/pull/130386/files#r1690856534

Since starting this, torch.cond and torch.while_loop now apparently have support for backward passes. I will look into what it might take to support that.

Pull Request resolved: #140979
Approved by: https://github.com/eqy, https://github.com/eellison
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/periodic Trigger jobs ran periodically on master (periodic.yml) on the PR ciflow/trunk Trigger trunk jobs on your pull request module: dynamo open source Stale

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants