Repository navigation
Conversation
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.
🔗 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 FailureAs of commit 518e270 with merge base 235f7e0 ( 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. |
This PR needs a
|
|
@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: Lines 13 to 26 in 51fc069 You can force the differences to be unique, as follows: codeHowever, what if the function allocates? Instead, I suggested having a special capture mode in CUDACachingAllocator. Similar to A simple version could return e.g. 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 |
|
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 The usage for each kernel argument would be stored in some data structure, looking something like this (example of
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 |
devNode's (hidden) struct fields were not getting initialized correctly before. Things are working now in both test.py and test2.py
|
bumping this to make sure we don't lose it |
|
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)) |
|
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:
|
|
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:
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:
(Note: it's now ~10Kb of GPU memory per cuda graph kernel invocation) Do you have any updated measurements for 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. |
|
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.
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 I agree that dynamic shapes should be out of scope. |
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.
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. |
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!
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)
```
|
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. |
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.
| 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]; |
There was a problem hiding this comment.
No. I want a struct of arrays (thus, "SOA") to maximize the number of coalesced global memory accesses.
| // 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
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