Skip to content

Implement cuda graphs implementation of torch.cond and torch.while_loop - #140979

Closed
galv wants to merge 15 commits into
pytorch:mainfrom
galv:galv/cudagraphs-conditional-nodes-3
Closed

galv wants to merge 15 commits into
pytorch:mainfrom
galv:galv/cudagraphs-conditional-nodes-3

Conversation

@galv

@galv galv commented Nov 18, 2024 •

Copy link
Copy Markdown
Collaborator

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.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @yf225 @chenyang78 @kadeng @muchulee8 @amjames @chauhang @aakhundov @StrongerXi @ColinPeppler @desertfire

@galv
galv requested review from a team, eqy, syed-ahmed and zou3519 as code owners November 18, 2024 21:05
@pytorch-bot

pytorch-bot Bot commented Nov 18, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit ee03af1 with merge base 93316cf (image):
💚 Looks good so far! There are no failures yet. 💚

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

Comment thread repros/repro_out_grapharg.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.

TODO: Remove this.

Comment thread repros/repro_tuple_out.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.

TODO: Remove this.

@eellison
eellison self-requested a review November 19, 2024 01:45
@galv
galv marked this pull request as draft November 20, 2024 08:04
@galv

galv commented Nov 20, 2024

Copy link
Copy Markdown
Collaborator Author

I converted this to a draft because the change that added a backward pass to torch.cond made me realize that there are a few issues in my design. In particular, I assumed that all stream capture would occur on one thread, but in fact it is normal behavior for the backward pass to use one or more new threads.

@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.

looks good! a few 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.

Where do we call cudaStreamDestroy ? I don't see it.

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.

It is inside end_capture_to_conditional_node. https://github.com/pytorch/pytorch/pull/140979/files#diff-d7302d133bb5e0890fc94de9aeea4d9d442555a3b40772c9db10edb5cf36a35cR561

Another possibility is to make this return a unique_ptr<cudaStream_t> with a custom destructor. That would be a little bit awkward since the std::stack<at::cuda::CUDAStreamGuard> conditional_node_streams_ would need an additional stack just containing these unique pointers (CUDAStreamGuard lacks a move constructor, so I'm not sure that having a std::pair of CUDAStreamGuard and a unique_ptr would work here).

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.

So I did try your suggestion: 7cdced5

To be honest, I think it makes things more opaque and confusing in this instance to use smart pointers. In particular, I almost accidentally depended upon the ordering of calculation of the arguments of a function here (std::move(child_stream) means that *child_stream might return NULL): 7cdced5#diff-d7302d133bb5e0890fc94de9aeea4d9d442555a3b40772c9db10edb5cf36a35cR456-R462

I'm thinking of reverting the change personally, but would be happy to keep it if you feel strongly about it.

Comment thread torch/_dynamo/backends/debugging.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.

nit: any reason to pass the stream in here instead of instantiate inside ? it's not used anywhere else

Comment thread torch/_higher_order_ops/cond.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.

Since we're already making a custom TorchDispatchMode to do the warmup, could we put this logic in that class to avoid cudagraphs leaking here ?

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.

Good idea. I think I encountered some weirdness, that is described here: https://github.com/pytorch/pytorch/pull/140979/files#diff-4093d24068320f82997aecfaf4260aa495e3b4322e178cb5625f9555e3f8b0f5R388-R392

and here:

#140322

But let me take a second look. I would be happy to make that change, assuming there is nothing standing in the way.

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 #140322 is blocking we can do as a follow up

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 did what you suggested. Unfortunately we cannot use code within __torch_dispatch__ right now to dispatch ops in a different way, but we can use py_impl(MyTorchDispatchMode) to do this right now, so I went with that workaround, though it is a little bit ugly because it causes some circular dependencies and separates code that should all sit in one single class. It should probably be redone once #140322 is handled. You can see how I do it for cond here: https://github.com/pytorch/pytorch/pull/140979/files#diff-4093d24068320f82997aecfaf4260aa495e3b4322e178cb5625f9555e3f8b0f5R384-R408

Note that I use two TorchDispatchModes, one for warmup, and one for making sure that I do stream capture appropriately for conditional nodes. I automatically enter CUDAGraphCaptureControlFlowOpDispatchMode in the enter method of torch.cuda.graph. This unfortunately means that users who use CUDAGraph.capture_begin() and CUDAGraph.capture_end() instead of torch.cuda.graph() won't be able to capture conditional ops. I don't think this is a problem to be honest. Do you think it is?

Comment thread torch/_subclasses/fake_tensor.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.

Could we also prevent cuda graph stream logic from leaking into fake tensors by updating the __torch_dispatch__ logic ?

Inside __torch_dispatch__, instantiate inputs to to_real_tensor, then map back outputs to Fake ? We can also do the thread_cuda_stream_capture_mode in it.

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 have to admit, I don't understand your suggestion here.

Basically, as I understand FakeTensors don't always know how to do correct shape inference for some operations. One of these is torch.stft. In this situation, real tensors are instantiated, the operation is run, and then fake tensors are constructed using metadata from the output real tensors. run_fallback_kernel(), the function I modified, is the function that is used to do this in FakeTensorMode, so I think I might be already be doing what you're asking for. Let me know if this makes sense at all!

I encountered this issue because I work a lot on audio data. You can see a unit test here at test/functorch/test_control_flow_cuda_initialization.py's test_cond_stft: https://github.com/pytorch/pytorch/pull/140979/files#diff-ce3a6ac7310a0a222e113af989463fe8f5bd7394a13a9cbfa58cfc0a7ceb494eR55

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 test there is not using Fake Tensors, so this code is not touched.

I guess taking a step back - I don't think we should do first run support of cuda graph. The general pytorch constraint is you need to have warmed up your model on the first run, then you can capture. There are a number of tests along these lines cublasCreate etc.

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 might try to resolve this in a follow up

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.

The test there is not using Fake Tensors, so this code is not touched.

Actually, that test is using fake tensors in order to compute the output shape of the stft operation. But anyway I agree this is a bit sketchy, looking back on this.

Comment thread torch/cuda/graphs.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.

This is currently only set to False in ControlFlowOpWarmupDispatchMode. So, I guess the use case there is that someone if capturing a cuda graph in eager and calls into a torch.compile wrapped function ? Wouldn't we expect that they should have already warmed up the function once prior to capture ?

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.

Fundamentally, the challenge is that my current approach to this can cause two distinct cuda stream captures to happen at the same time.

First of all, pytorch never actually intended for more than one stream capture to be possible, from what I can see. This is clearly stated in the documentation of torch.cuda.graph() See here: https://github.com/pytorch/pytorch/pull/140979/files#diff-39e542d87359e7d5381d036cbcea9ec759fbe469578bcdc5693ce6cfab7f1a54R187-R188 If torch.cuda.graph is constructed without a stream, every call to init will use the same single cuda stream. And calling cudaStreamBeginCapture() on an already capturing stream will fail.

As you see, entering the torch.cuda.graph() context manager will call torch.cuda.synchronize(). Unfortunately, torch.cuda.synchronize() will basically call cudaStreamSynchronize() on every stream in the cuda context, and cudaStreamSynchronize() will invalidate stream capture for a capturing stream.

That is why I added this boolean flag, since my "warmup" TorchDispatchMode will always start a second stream capture when another stream capture is already going on.

Unfortunately, there is more to it than that.

The warmup TorchDispatchMode does two things:

  1. It ensures that all conditionally-executed code paths are "warmed up" by running them at least once.
  2. It avoids side effects while doing (1) by "stubbing" out all kernel launches via doing relaxed stream capture (side effects are not acceptable because I don't want both sides of an if-else statement to execute. That would never happen during normal execution, and could therefore put the program into an undefined state).

Unfortunately, even though I do relaxed stream capture on the second stream, the first stream caputre may be in global or thread local stream capture mode. There is no way to temporarily "turn off" stream capture on a stream and then turn it back on right now (though in principle, I see no reason why we couldn't do it). This means that unsafe actions done during the warmup will still invalidate the first stream's capture. Thus, I need to change the thread's capture mode to relaxed at various points, which I'm not happy with.

Pytorch has succeeded so far with just using the torch.cuda.graph() context manager for capturing (though someone could use torch.cuda.CUDAGraph()'s APIs directly). This is the first time that what code we want to execute will differ depending upon whether a stream is capturing or not.

I can probably keep running with pytorch's current assumption that only one stream can do capture at a time if the user passed me a function describing the work that they wanted to do. I would then make a wrapper function over that uses torch.cuda.graph() twice, sequentially, once in relaxed mode, and then again in the user-requested mode.

As you can see, there are unfortunately quite a few annoying details here. But I am inclined to agree with you that there is probably an easier, safer way to do this.

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.

That is why I added this boolean flag, since my "warmup" TorchDispatchMode will always start a second stream capture when another stream capture is already going on.

I think a lot of these problems stem from trying to do warmup when stream capture is already on.

Comment thread torch/cuda/graphs.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.

For appropriately rare situations, i would lean towards not supporting until it becomes an actual issue. Or at least have tests for these edge cases to be sure we are correctly handling.

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.

Makes sense. I'm inclined to just undo this change to be honest. I'm worried about causing an unexpected behavior or error by stuffing too much into this PR. Developers in the know can simply pass in their own cuda stream torch.cuda.graph() to prevent trying to restart stream capture on the same stream.

@galv
galv requested a review from bdhirsh as a code owner December 2, 2024 06:40
Comment thread aten/src/ATen/cuda/CUDAGraph.cpp Resolved
@galv

galv commented Dec 3, 2024

Copy link
Copy Markdown
Collaborator Author

@pytorchbot label "release notes: cuda"

@pytorch-bot pytorch-bot Bot added the release notes: cuda release notes category label Dec 3, 2024
@galv

galv commented Dec 3, 2024

Copy link
Copy Markdown
Collaborator Author

@eqy do you know how I can run CI? It's pretty helpful not to have to run the entire test suite locally.

@galv
galv force-pushed the galv/cudagraphs-conditional-nodes-3 branch from 1097032 to da3a7bc Compare December 3, 2024 19:09
Comment thread aten/src/ATen/cuda/CUDAGraph.cu Resolved
Comment thread torch/_dynamo/convert_frame.py Outdated
# unavoidable. Presumably even under stream
# capture, we still want to save and restore the
# rng state.
cuda_rng_state = torch.cuda.default_generators[

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: Make sure that resetting the cuda rng state works as intended when doing stream capture. Frankly, I'm not even sure what the intended behavior is supposed to be. This is the first time that a code sequence like:

with torch.cuda.graph(g):
    torch.compile(f)

is being done.

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.

VLLM runs torch.compile and captures it afterwards. The recommendation (as with other cudagraphs) is that you should warmup the run first, then compile.

torch.compile(f)
with torch.cuda.graph(g):
    torch.compile(f)

Should we revert this ?

@galv
galv force-pushed the galv/cudagraphs-conditional-nodes-3 branch from 81f2d44 to 630af47 Compare February 20, 2025 06:16
@facebook-github-bot

Copy link
Copy Markdown
Contributor

@eellison has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@tlrmchlsmth

Copy link
Copy Markdown

Looking forward to trying this out in vLLM once it lands!

@galv

galv commented Apr 7, 2025

Copy link
Copy Markdown
Collaborator Author

@tlrmchlsmth unfortunately I never succeeded in getting a reproducer from @huydhn Since the failure is internal to Meta and there is no externally working reproducer, unfortunately I've put this on hold.

Let me know what you're thinking of doing this with this. If you want simply to minimize the overhead of the GPU synchronizing with the GPU when you check for termination at the end of every iteration, #146145 and #146924 combined will allow for that in an interesting way. However, it will increase memory usage due to unrolling your loop a few iterations, and I know that device memory usage from cuda graph nodes has been a problem in vLLM before.

@BoyuanFeng
BoyuanFeng self-requested a review April 7, 2025 22:54
@github-actions

github-actions Bot commented Jun 6, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants