Skip to content

Initial work on "cuda graphs with arguments". - #137318

Closed
galv wants to merge 25 commits into
pytorch:mainfrom
galv:dgalvez/cudagraph-with-arguments
Closed

galv wants to merge 25 commits into
pytorch:mainfrom
galv:dgalvez/cudagraph-with-arguments

Conversation

@galv

@galv galv commented Oct 3, 2024 •

Copy link
Copy Markdown
Collaborator

Right now, users must have "static" inputs that act as "staging buffers" when they use cuda graphs in pytorch. The use must do something like this before launching a cuda graph:

static_input.copy_(input)

Because cuda graphs' arguments are "fixed" or "frozen".

This change proposes dynamically dynamically changing the kernel arguments of the kernel nodes to point to new tensor addresses, thus skipping copies. This is likely to be beneficial in terms of performance compared to copying when the user has several tensors to copy or a large amount of memory to copy. This uses a CUDA 12.4 API, cudaGraphKernelNodeUpdatesApply, to do this update in an efficient way.

There are still a lot of warts in here. I gather the information with some ABI-related tricks (CUDA kernels follow a System-V x86_64 ABI for calling conventions; thus we know that 8-byte pointers are 8-byte aligned, or "naturally aligned"), but I still don't use cudaGraphKernelNodeUpdatesApply to actually apply the update yet. I will consider adding this in the "cudagraphs" torch.compile backend at some point, as an option, since such a change is transparent to users and can be easily disabled (versus the "raw" cuda graphs interface). In addition, there can be false positives right now in the way that I gather which kernel arguments correspond to tensors. Perhaps modifying CUDACachingAllocator to use tagged pointers are the better approach to eliminate the chance of false positives.

The work is woefully incomplete right now.

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

Right now, users must have "static" inputs that act as "staging
buffers" when they use cuda graphs in pytorch. The use must do
something like this before launching a cuda graph:

`static_input.copy_(input)`

Because cuda graphs' arguments are "fixed" or "frozen".

This change proposes dynamically dynamically changing the kernel
arguments of the kernel nodes to point to new tensor addresses, thus
skipping copies. This is likely to be beneficial in terms of
performance compared to copying when the user has several tensors to
copy or a large amount of memory to copy. This uses a CUDA 12.4 API,
cudaGraphKernelNodeUpdatesApply, to do this update in an efficient way.

There are still a lot of warts in here. And it is incomplete. I gather
the information with some ABI-related tricks, but I still don't use
cudaGraphKernelNodeUpdatesApply to actually apply the update yet. In
addition, there can be false positives right now in the way that I
gather which kernel arguments correspond to tensors. Perhaps modifying
CUDACachingAllocator to use tagged pointers are the better approach
to eliminate the chance of false positives.

The work is woefully incomplete right now.
@pytorch-bot

pytorch-bot Bot commented Oct 3, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 12 New Failures, 1 Unrelated Failure

As of commit 518e270 with merge base 235f7e0 (image):

NEW FAILURES - The following jobs have failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@github-actions

github-actions Bot commented Oct 3, 2024

Copy link
Copy Markdown
Contributor

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@galv

galv commented Oct 3, 2024

Copy link
Copy Markdown
Collaborator Author

@zdevito @eellison

@leijurv

leijurv commented Oct 3, 2024

Copy link
Copy Markdown

@galv and I were talking about this pointer difference technique - I think it can work nearly as-is for the input tensors, but I don't think it can work for any allocations made during capture.

Inspired by this example:

x_static1 = torch.zeros(8, device="cuda")
y_static1 = torch.ones(8, device="cuda")
with torch.cuda.graph(g1):
z_static1 = x_static1 + y_static1
x_static2 = torch.zeros(8, device="cuda")
y_static2 = torch.ones(8, device="cuda")
with torch.cuda.graph(g2):
z_static2 = x_static2 + y_static2
# NOTE: This has a false positive for me right now. x_static1.data_ptr - x_static2.data_ptr == y_static1.data_ptr - y_static2.data_ptr
updates = torch.create_device_updates(g1, g2, [(x_static1, x_static2), (y_static1, y_static2), (z_static1, z_static2)])
I noted that the differences will be equal since each one grabs a 512 byte block from the allocator.

You can force the differences to be unique, as follows:

code
import torch
x_static1 = torch.zeros((8, 10), device="cuda")
y_static1 = torch.ones((8, 1), device="cuda")
x_static2 = torch.zeros((8, 10), device="cuda")
y_static2 = torch.ones((8, 1), device="cuda")
print("X", x_static2.data_ptr() - x_static1.data_ptr())
print("Y", y_static2.data_ptr() - y_static1.data_ptr())
# not unique, prints 1024 1024

def tensor_pairs_with_distinct_offsets(shapes):
    first_run = [torch.empty(shape, device="cuda") for shape in shapes]
    claimed_diffs = set()
    second_run = []
    for i, shape in enumerate(shapes):
        buffer = []
        while True:
            tensor = torch.empty(shape, device="cuda")
            diff = tensor.data_ptr() - first_run[i].data_ptr()
            if diff in claimed_diffs:
                # force the caching allocator to go somewhere, anywhere, else
                buffer.append(torch.empty(1, device="cuda"))
            else:
                claimed_diffs.add(diff)
                second_run.append(tensor)
                break
    return first_run, second_run

run1, run2 = tensor_pairs_with_distinct_offsets([(8, 10), (8, 1)])
x_static1, y_static1 = run1
x_static2, y_static2 = run2
print("X", x_static2.data_ptr() - x_static1.data_ptr())
print("Y", y_static2.data_ptr() - y_static1.data_ptr())
# unique, prints 1024 2048

However, what if the function allocates? z_static1 = x_static1 + y_static1 makes only one allocation for the output, but imagine z_static1 = (x_static1 + y_static1) + 1. Those two intermediary allocations would happen in a fresh PrivatePool each time, meaning their offsets from each other would probably be constant, meaning intermediate_0 would be indistinguishable from intermediate_1, ....

Instead, I suggested having a special capture mode in CUDACachingAllocator. Similar to captures_underway, except for a totally different purpose. Instead of locking in some memory addresses that will live for the duration of the graph, we'll instead return dummy sentinel values, and log (probably a callback to CUDAGraph.cpp) what allocations happened. Then, when we're introspecting the graph nodes, we can easily cross-reference against our allocation log, and realize which tensor is which.

A simple version could return e.g. allocationIdx * 2**40, then we can tell which tensor is which from // 2**40. The idea is that kernel(tensor[123:]) needs to be matched to the allocation of tensor, even though the data_ptr is now offset by 123. And you probably won't slice a tensor by 1 terabyte.

A more complicated version could still use pointer differences. Run it once where every allocation returns 0. Then a second time where every allocation returns allocationIdx. By subtracting the two runs, we can identify which kernel argument was which allocation, independent of whatever slicing happened (kernel(tensor[123:])). And we can guarantee that each allocation has a distinct difference, because we fixed allocationIdx - 0 to be unique per allocation. So, for example, if we observed the first run as 123 and the second run as 130, this would identify a kernel that takes the 8th allocation (allocationIdx = 130 - 123 = 7), with an offset of tensor[123:].

@leijurv

leijurv commented Oct 3, 2024 •

Copy link
Copy Markdown

I believe the inputs (x_static1, ...) should also be specially allocated in this way, again so that their usage can be tracked too. So we'd wrap the function (e.g. when doing @torch.compile(mode="fancy-updatable-graphs")), and pass in dummy tensors with sentinel data_ptr values.

The usage for each kernel argument would be stored in some data structure, looking something like this (example of (in1 + in2) + 1)

  • Input tensor 1, used as argument 0 to kernel launch 0
  • Input tensor 2, used as argument 1 to kernel launch 0
  • Allocated tensor 1, used as argument 2 to kernel launch 0, used as argument 0 to kernel launch 1
  • Allocated tensor 2, returned as output, used as argument 1 to kernel launch 1

This could live on CPU or GPU, unsure. But the idea would be that whenever we want to invoke this graph with new tensors (with the same shape), we'd allocate these two tensors, collect up all our data_ptrs, and launch a graph surgery kernel that bundles all 4 of these updates into a list of cudaGraphKernelNodeUpdates that we pass to cudaGraphKernelNodeUpdatesApply, then we'd be free to launch the graphexec and just return the output tensor.

@ezyang
ezyang self-requested a review October 12, 2024 02:43
@ezyang

ezyang commented Oct 12, 2024

Copy link
Copy Markdown
Contributor

bumping this to make sure we don't lose it

@ezyang

ezyang commented Oct 12, 2024

Copy link
Copy Markdown
Contributor

@leijurv

leijurv commented Oct 12, 2024 •

Copy link
Copy Markdown

Thank you for the interest! That script you linked to does work (but, it's not quite ready for review yet).

Latest version is here: leijurv/pytorch@main...cabfe79#diff-3665d65394f4f58a56a256ad6dd8621c68118d90fe56a19387e251c19cec2d2eR4-R30

def make_dynamic(func):
    graph = None
    def wrapper(*args):
        nonlocal graph
        if graph is None:
            graph = torch.cuda.CUDAGraph()
            with torch.cuda.graph(graph, dynamic_graph=True):
                func(*args)
            graph.become_dynamic(args)
        graph.replay_dynamic(args)
    return wrapper

@make_dynamic
def myFuncSimple(a):
    print("myFuncSimple is running")
    a += 1

test = torch.zeros(8)

for i in range(10):
    myFuncSimple(test)
assert torch.equal(test, torch.full((8,), 10))

for i in range(10):
    test = test.clone() # force the tensor to a new memory location
    myFuncSimple(test)
assert torch.equal(test, torch.full((8,), 20))

@ezyang
ezyang requested a review from ngimel October 15, 2024 14:06
@linux-foundation-easycla

linux-foundation-easycla Bot commented Oct 17, 2024 •

Copy link
Copy Markdown

CLA Signed

The committers listed above are authorized under a signed CLA.

@galv

galv commented Oct 17, 2024 •

Copy link
Copy Markdown
Collaborator Author

I want to thank @leijurv for carrying this across the finish line in terms of being a functional proof-of-concept. My original code just demonstrated a way to discover the offsets of pointer arguments you might want to replace, but did not actually do the update. The current way of discovering point argument offsets is still not fully robust (it can have false positives), but I believe this is solvable via some clever techniques combining the torch.cuda.Mempool API and the low level cuMemMap APIs in the CUDA driver and I would prefer to verify that this has value in terms of speed up, reduced memory usage, and/or better UX to some part of pytorch before perfecting that.

The hope is that it can possibly do some of the following:

  1. Reduce cuda graph launch overhead for graphs with large inputs by replacing copy_() calls with much smaller writes to a few addresses in memory. I am investigating this in the context of resnet50 right now, but have discovered that cudaGraphLaunch() has a higher latency than expected, much higher than copying in inputs, so I am investigating that first.
  2. Reduce cuda graph node on-device memory usage when combined with a while loop conditional node via Add support for conditional nodes in cuda graphs. #130386 , to "roll up" loops (by default, they are unrolled for stream capture) for cases where a layer is repeated several times with the same input and output shape.
  3. Possibly we can work around this issue in cuda graph trees where we have to rewarmup nodes described here:
    # warming up a function and subsequentally recording may use different memory addresses
    # because both depend on the state of the caching allocator. if we warm up graph A,
    # then warm up graph B and make more allocations, the subsequent recording of A will not
    # necessarily use the same addresses as in the warm up. Thus any warm up of a node can only
    # be followed by warm up runs.
    I suspect this is the most valuable use of this work.
  4. It could also reduce memory usage for inputs and outputs by a small amount when using cuda graphs. Some users have complained about how copying data in and out of a cuda graph increases memory usage because an extra allocation for your inputs and outputs is required. However, I don't think this is necessarily easy to do.

@eellison

Copy link
Copy Markdown
Contributor

Very cool work! Here is more motivation for this from the torch.compile cudagraphs perspective:

There are two primary reasons why IMO we cannot turn on cudagraphs by default in torch.compile today:

  1. Cudagraphs uses a separate memory pool from pytorch eager. if you are torch.compiling only part of your model, the memory from the cuda graph region will not be usable with the eager region. The duplication of memory pools can (and has) led to OOMs.

  2. This pr mentions updating the input addresses without an explicit copy. This also applies to outputs. When you use cudagraphs the outputs are fixed just like the inputs. This means if you invoke a cuda graph twice, the result from the first invocation is implicitly written over. We have some error checking for that in torch.compile, and an API workaround, but the problem remains. It's especially an issue when you are torch.compiling multiple separate graphs.

If we could resolve those issues, then we could turn it on cudagraphs by default in torch.compile. That would be a huge win. Eliding the input copy is nice but in my experience not a huge perf loss as you are maybe seeing with resnet.

The big question for me is if we have a path forward to turn this always on.

@zdevito previously looked into something along these lines, and his experience was:

Patching CUDA Graphs If we had a CUDA graph with these launches in them, we can now edit it so that pointers go to different buffers, even for cublas and cudnn calls where we do not know much about the kernels. This would let us, for instance, use different output buffers if previous outputs to the cuda graph were still allocated.

It also looks like this would be a way to patch cuda graphs on the fly so that we can reuse them for different layers of the network. This could be useful since each CUDA graph kernel invocation takes 64kB of GPU memory at the moment, making it infeasible to have many big graphs for many sizes. Unfortunately, the current patching function for graphs cudaGraphExecKernelSetParams takes about 700ns per kernel call to be patched, making it too slow to use for on-the-fly patching.

(Note: it's now ~10Kb of GPU memory per cuda graph kernel invocation)

Do you have any updated measurements for cudaGraphExecKernelSetParams ?

Other misc thoughts:

When we invoke the backward in torch.compile it's important to release the memory of the inputs. So we'd need to release memory from inputs at the same time as we allocate memory from outputs, and make sure that that the input memory is not used until the cuda graph is invoked. This is doable.. but doesn't exist today.

I don't think dynamic shapes should be in scope. You'll need to recompute launch parameters outside of just memory addresses and shapes. At that point, we could look into padding to multiple. Or do a better job of reducting overhead in the the cpp inductor code generation. maybe with memory planning / single cuda caching allocation & avoiding construction tensor impls and just pass data ptrs around.

@leijurv

leijurv commented Oct 18, 2024 •

Copy link
Copy Markdown

We went through several revisions of how to do dynamic cuda graphs. The current code in this PR is the simplest version - it captures only once, and it doesn't mess with the allocator at all. The only thing it allows is rewriting the tensors that you pass into the function (which could be used either as inputs or outputs). So, it does address #2 of your issues, but it does not address #1.

For #1, we do have an earlier revision that got rid of the private pool entirely. The basic idea was 1. allocate into a private pool during graph capture 2. record those allocations using a callback 3. determine which arguments to which kernels were from which allocations 4. discard the private pool. Then, when it's time to replay the graph, we remake the allocations in the main pool, and rewrite all the kernels accordingly. See here and here. Since the private pool is discarded after capture, this solves the memory usage issue. We ended up removing this so that we could make a simpler PR that didn't require modifying CUDACachingAllocator, but, if it's a useful feature we can bring it back! I believe it solves both of your primary issues.

Unfortunately, the current patching function for graphs cudaGraphExecKernelSetParams takes about 700ns per kernel call to be patched, making it too slow to use for on-the-fly patching.

I admit I'm unfamiliar with the tradeoffs here - I don't understand why 700ns per patch is too slow, that seems blindingly fast to me? You'd only need to call it a handful of times per launch, as little as once for the input and once for the output?

Anyway, we don't use cudaGraphExecKernelSetParams. We are using cudaGraphKernelNodeUpdatesApply, which is called from __device__, and on top of that, it allows you to batch many updates in a single call. See here. In practice, this means that all your updates should be a single kernel launch, then that kernel will apply them in batches (perhaps even in parallel). (Note that this only applies to kernel nodes - if you have a cudaMemcpyAsync or cudaMemsetAsync upon a dynamic tensor then those updates have to fall back to a slower __host__ update path). Also note that the device side update is very powerful: kernels can modify the launch parameters of other kernels within the same graph. See a demonstration here (output here), in which we use a "while" node to demonstrate that a kernel can change the gridDim and arguments of the next node in the graph, on the fly while the graph is executing.

I agree that dynamic shapes should be out of scope.

@galv

galv commented Oct 18, 2024

Copy link
Copy Markdown
Collaborator Author

Eliding the input copy is nice but in my experience not a huge perf loss as you are maybe seeing with resnet.

My hope was that I could start with something simple that didn't touch other code that could benefit from this change. But it looks like eliding input copies is so far not as useful as I had imagined.

If we could resolve those issues, then we could turn it on cudagraphs by default in torch.compile. That would be a huge win.

This seems like the task that we should focus on achieving. I frankly don't understand inductor or cudagraph trees at a well enough right now to know what precisely we might want to change to achieve turning on cuda graphs by default, so I am studying up on cudagraph_trees.py right now!

BTW, regional compilation in pytorch 2.5 may fit in well with #2. I had previously though that we would need to make a variant of torch.nn.Sequential called torch.nn.RepeatedSequential to make detecting the while loop, but if the code for detected repeated regions is already robust, then perhaps that is not so far away.

@eellison

Copy link
Copy Markdown
Contributor

I admit I'm unfamiliar with the tradeoffs here - I don't understand why 700ns per patch is too slow, that seems blindingly fast to me? You'd only need to call it a handful of times per launch, as little as once for the input and once for the output?

Anyway, we don't use cudaGraphExecKernelSetParams. We are using cudaGraphKernelNodeUpdatesApply

My guess is the issue here is calling this for many nodes on the graph instead of just once. But sounds like it's not an issue today!

I frankly don't understand inductor or cudagraph trees at a well enough right now to know what precisely we might want to change to achieve turning on cuda graphs by default, so I am studying up on cudagraph_trees.py right now!

The details of cudagraph trees are less important if we are able to use the eager allocator and update memory addresses. Cudagraph trees is basically working around those restrictions, as well as cuda graph memory not being tracked on execution. In any case there is an explainer here.

The important inductor/torch.compile consideration is that we have separate graphs between forward and backward, with activations being an input to backward..

Moving forward - @galv, @leijurv - what do we want to target ? does interopability with eager allocator sound okay, or are trying to get just the first part landed ? I'm happy to help but will be finishing up a couple of other things for a few more week. we could potentially land in stages or wait till something more complete is ready and iterate in side repro.

Also curious to hear from @zdevito when he gets a chance.

Previously, they would just silently fail (!).

Make replay_dynamic() work with triton-generated kernels. We need to
use the driver API for cuGraphKernelNodeGetParams for reasons
described in CUDAGraph.cpp.

This now works as expected (a will have the value of 1 after running):

```
import torch

from torch._inductor import config
config.triton.cudagraph_trees = False
config.triton.cudagraphs_elide_input_output_copies = True

@torch.compile(mode="reduce-overhead")
def mutate_foo(a):
    a.add_(1)
    return a.clone()

a = torch.zeros(1, device="cuda")
for _ in range(1):
    a_plus_1 = mutate_foo(a)
    print(_, a)
    print(a_plus_1)
```
@galv

galv commented Oct 22, 2024

Copy link
Copy Markdown
Collaborator Author

Latest commit 8b26cdd makes the following work as expected when config.triton.cudagraph_trees = False.

I did it as a warmup while learning cudagraph trees.

import torch

from torch._inductor import config
config.triton.cudagraph_trees = False
config.triton.cudagraphs_elide_input_output_copies = True

@torch.compile(mode="reduce-overhead")
def mutate_foo(a):
    a.add_(1)
    return a.clone()

a = torch.zeros(1, device="cuda")
for _ in range(1):
    a_plus_1 = mutate_foo(a)
    print(_, a)
    print(a_plus_1)

@BoyuanFeng
BoyuanFeng self-requested a review October 22, 2024 19:37
galv and others added 2 commits October 24, 2024 03:12
Move cudaGraphUpload out of the critical path.

Rewrite dynamic_graph_updater_kernel to dynamic_graph_updater_kernel2
based on the fact that we are updating only pointer arguments and a
quick analysis in nsight compute demonstrating that the kernel is
limited by memory loads.

For my small file, test_cuda_graph_input_mutation2.py the time of the
kernel goes from 5.0 microseconds to 2.8 microseconds. Not
comprehensive. But I pursued this becuase I wanted to see how fast
this can be compared to copying the input and output tensors. Not bad!
But also not comprehensive.
Comment thread aten/src/ATen/cuda/CUDAGraph.h Outdated
static constexpr size_t MAX_NUM_UPDATES = (KERNEL_PARAM_LIMIT_BYTES - sizeof(size_t)) / PER_UPDATE;

size_t num_updates;
// should this a struct? like: KernelUpdate updates[MAX_NUM_UPDATES];

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.

No. I want a struct of arrays (thus, "SOA") to maximize the number of coalesced global memory accesses.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Gotcha!

Comment thread aten/src/ATen/cuda/CUDAGraph.h Outdated
// Even on Cuda 12.4, Torch supports compute capability down to sm_50
// However, large parameter support was only added in sm_70
// https://developer.nvidia.com/blog/cuda-12-1-supports-large-kernel-parameters/
#if (__CUDA_ARCH__ >= 700)

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 is a good idea, but it is error prone unfortunately. We currently reference this struct in CUDAGraph.cpp and CUDAGraph.cu (and potentially every files that may include CUDAGraph.h). What will happen is that the host code will set KERNEL_PARAM_LIMIT_BYTES to 4096, which is fine for Pascal and older, but will cause problems for Volta and newer code, since the host and device layouts of this type won't match. AFAIK, there is no way for the host compiler to "know" for which devices the same code is being compiled.

Anyway, honestly just using KERNEL_PARAM_LIMIT_BYTES=4096 may be fine. Looks like that gives us 73 updates. I would like to get stats on that when running torchbench, but my hunch is that 73 is enough. (And of course, we can call the kernel multiple times, as you are doing).

Anyway, it looks like we can do 73 updates in a cross-platform way. That is probably okay for now TBH.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I believe we can use templates to have it both ways, and pick at runtime: 518e270

73 is low, especially in the scenario where the private pool is discarded and all allocations are rewritten (not just inputs/outputs)

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

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.

5 participants