Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/152622
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ❌ 7 New FailuresAs of commit 76f5622 with merge base a3ec6d6 ( NEW FAILURES - The following jobs have failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Aww, you rewrote the git history to squash away all my commits to #137318 😭 😛 What I wrote on PyTorch Slack:https://pytorch.slack.com/archives/C07JATB2YBD/p1742326076497109?thread_ts=1742029859.056189&cid=C07JATB2YBD
I'm sorry to say but overall I feel as though going deeper into DWARF debug symbols is barking up the wrong tree. The reasons you give are probably a deal-breaker: nvcc code needing to compile with no optimizations, and needing to expose that private API. Let's be clear on what exactly the concern is: a false positive where we rewrite actual data because we wrongly concluded it was a pointer into one of our allocations. We can forget about false negatives because we can conclude as an ABI guarantee that all pointer types shall have 8-byte alignment. So, my first claim is that the only plausible correctness issue to worry about is that we have edited "too many" kernel launches. We are confident we will never edit "too few". My second claim: There is no plausible way to guarantee 100% correctness unless you capture the graph twice with slightly different allocations. The reason has to do with partially uninitialized memory. As a simple example, see here, where a datatype that is frequently passed into various kernels used to have a large swath of uninitialized memory, which sometimes might contain a valid pointer. This is a motivating example that demonstrates that device pointers can easily show up in uninitialized memory. Now, you may say that this is not actually a correctness issue, because overwriting uninitialized memory is perfectly permissible, and won't change kernel behavior. That's true, if and only if all 8 bytes of the pointer were uninitialized. I wrote a comment here describing an early attempt to resolve this, and also see the above Slack conversation. To summarize: you can imagine something like a uint8 or a uint16 that is passed to a kernel. For alignment reasons, since it's a struct field let's say, it gets padded to 8 bytes before the next struct field. The uint16 is, let's say, all zeros, and let's say that the tensor that we misidentify it as happened to be 65536-byte aligned. When we replay, our new tensor is not 65536-byte aligned, and we wrongly overwrite the uint16 field to a new value. I think this is very implausible but if you want 100% correctness you have to detect it. Also, same goes for passing a regular const int64 to a kernel, that just happens to be a valid device pointer to one of your allocations. Similarly very implausible, but similarly needs to be detected if you want 100% correctness. In both cases, there is no plausible solution other than capturing the graph twice. This was your initial version, and even though the code of comparing two captured graphs was nasty, I think it's the best solution still. (ONLY IF you need 100% correctness guaranteed, if you don't need 100% then the latest version of #137318 is fine). To create this 100% correctness guarantee, you need to capture the graph twice, and your dynamic allocations need to have a difference in each of their base ptrs that is congruent to 128 modulo 256. I know you don't like this but I think it's necessary. Here's some pseudocode, I'm ambivalent as to whether this should go in a python wrapper or in cudagraph or what. This guarantees that the least significant byte of every dynamic tensor is different, meaning that correctness is 100% guaranteed because you can't false positive on a 1-byte-real-7-bytes-uninitialized slice of memory, because the least significant byte of every dynamic tensor changed between the two allocations while the 1 byte real won't have changed. All that being said - I think these cases are implausible and targeting 100% correctness guaranteed is overkill. Possibly 128-byte alignment changes the kernels, this would be detected easily since the graphs will be unequal. Therefore, here's how I see it: Torch has a lot of kernels, some in Cuda, some in Triton, and users can write their own kernels that could/should be capturable too. Requiring all these kernels to be built with optimizations off is probably a deal-breaker. And it doesn't achieve much anyway - it only prevents two incredibly unlikely scenarios (1. the user passes in an int64 that by pure chance happens to match a device pointer or 2. the scenario with the 8 bytes of memory of which only 1 or 2 are initialized). Of those two unlikely scenarios, the first could happen in Triton, it could happen in any language, but it's just so unlikely. The second scenario could only plausibly happen in Cuda. Therefore, the DWARF approach is probably not worth it. The gain is very small: it prevents an extremely unlikely/contrived scenario, and only for code compiled by nvcc with all optimizations off and debug symbols on. The cost is a bunch of extra code, and delaying the feature upon exposing an internal API ( My suggestion: IF you need 100% correctness against the false positive scenarios, you need to capture twice as detailed above. I think this is unnecessary, it could be added as a feature in the future. The better route would be to solve both issues that cuda graphs face: not just the dynamic replay of input/output tensors, but also the memory savings from discarding the private pool, and only remaking the internal allocations upon replay. My source for this claim is @eellison 's comment here and my reply here. This is already implemented as of this commit: 3caed70 (just see the todo at the very top). In my opinion this would make the PR fit way better into the torch use cases. But if you don't want to do that in one PR, I would just suggest that you set up the Python-side API in such a way that making the allocations ephemeral is a feature that could be added in the future without a user-facing API break. This would mean in practice that you'd need some kind of wrapper / decorator on your function, like how we had in the test.py, rather than a python (Also it looks like compared to my version, in your version there are some skeptical comments, let me explain. In this code, there is an assumption already enforced that the DynamicGraphAllocations do not overlap with each other. We want the last one that begins before our ptr. Using the std library, we can find the first one that begins after our ptr. If that's the beginning of the list, we return nullopt. Otherwise, we decrement the iterator, and check if our pointer actually resides within that range, returning it if so.) |
To be clear, there is no fundamental reason why you have to turn off optimizations to get debug symbols. I can understand why someone made this decision many years ago, since no one in their right mind would use debug symbols as a way to introspect their program, and also because the line numbers in debug symbols are not very helpful when optimizations are turned on. What we care about, the types of parameters, doesn't care about optimizations, fortunately. With the passage of time, however, we can move beyond a prototype based on dwarf debug symbols, if we change the nvcc compiler to emit the relevant type information for arguments in the ELF file itself (you could probably do a very simple compressed representation where you use run length encoding, I imagine). The compiler already does something like this, BTW. It's how the cuLaunchKernel() knows the size and offset of each parameter in the parameter buffer, despite having a type erased API. But I have to prove to the compiler team that a parameterized cuda graph launch can be done 100% robustly before they invest in that. Regarding APIs being private, it's just conservative programming practice to keep your API small, since you basically have to stick with it forever once its public. There are lots of stakeholders that need to be convinced of things on both NVIDIA and the pytorch side, so this is the cost of things for now. Sorry :(
Actually, I have thought about this. I made an "is_equal()" function that compares to cuda graphs for equality. It does this by checking that every non-padding bit of every parameter in every kernel node is the same between the two graphs. Because of the dwarf debugging info, we now know where the padding is. If this check does not pass on two cuda graphs captured on the exact same inputs, it prints a helpful error message pointing out the parameter that is wrong: https://github.com/pytorch/pytorch/pull/152622/files#diff-d7302d133bb5e0890fc94de9aeea4d9d442555a3b40772c9db10edb5cf36a35cR957-R969 This check allowed me find this case where data is not initialized properly for example: https://github.com/pytorch/pytorch/pull/152622/files#diff-c97a73b68ed661333310fc795dfadc61738d01d157e9f19962d591b607c96028R33-R34 So to be clear, I do think that using this API may impose some constraints on users (e.g., don't have uninitialized non-padding memory), but I don't think those are particularly difficult to fulfill. I'm still not opposed to the pointer diffing method. I actually did investigate doing it a while back in such a way that we can control the virtual address of every single allocation (!) using the torch.cuda.Mempool API, but it's very broken right now and basically not usable with cuda graphs unfortunately #146431 Someone's actually working on fixing it right now, though so maybe it is time to retry. One of the cool things is that we can create the virtual addresses during stream capture via cuMemReserveAddress(), and then "back" them with physical memory via cuMemMap() only if it is necessary, BTW. I need to think through your strategy more, so thanks for writing it out. I think that it may require capturing three cuda graphs instead of 2, but I'm not 100% sure yet. To be clear, I'm happy to ditch the dwarf debug strategy if there is a way to robustly do this otherwise. Though overall I think that having multiple approaches is very good because that increases confidence in the robustness of this. |
Gotcha, large company bureaucracy. I wish you the best of luck, I can commiserate
I think this is interesting, and I don't think it's a dealbreaker either way. It's good that it prints out the location of the mismatch for sure. Possibly an option to override it, for if the behavior is in a 3rd party library that's hard to modify?
That's how the original version of our previous PR worked e.g. here. It didn't quite work out because there was a bunch of code that disliked being passed a fake pointer. The idea then was: if you're going to have to pass "real" device pointers (that the cuda driver will attest to being real and in the virtual space allocated by your process), then you might as well use the real cuda caching allocator. That's what led me to the conclusion of making real allocations, possibly with a 128-byte offset if we really really want to care about uninitialized padding. And if you're going to log real allocations, then fulfilling the "wish list" by allowing the private allocation pool to be discarded is probably a good idea. If you're looking to sweeten the deal and make this PR more appealing to stakeholders, my opinion (just an opinion) would be that allowing the internal/intermediary allocations to be remade on every replay (not just the input/output allocations) is a great way to do it. Very high bang for your buck. Fixes both of the issues that eelison mentioned. And it would actually be compilable / mergable today, which is the most important part, because what you have here depends on (currently) private APIs. And you would just need to go back a few commits in the old PR to see the code for it (to this one). And then after that, you'd have more leverage to make your asks to get these APIs exposed and the type information saved by nvcc to the ELF, because torch is already using the feature, you're just asking for what you need to make it more reliable. |
|
Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as |
d722904 to
127d720
Compare
| TORCH_INTERNAL_ASSERT(allocations_[i].alloc_idx == i); | ||
| // TORCH_CHECK(dynamic_tensors[i].is_contiguous(), "All tensors must be contiguous"); | ||
| // TODO ^ this isn't quite right. really, the assert should be that the stride is the same as the original input arg. | ||
| // TORCH_CHECK(dynamic_tensors[i].nbytes() == allocations_[i].size, "Prefilled tensors must be same shape"); |
There was a problem hiding this comment.
I think it is very scary / dubious to comment out these two TORCH_CHECKS ^ ^^
There was a problem hiding this comment.
Outputs can overlap with inputs. While working on the torchbench benchmarks, I found that this is a fairly common case.
For example, it's not uncommon to see something like this:
def foo(x):
return x[1:]
I added support for that in a very sloppy way here: https://github.com/pytorch/pytorch/pull/152622/files#diff-cbda127114b86d36ed63c8b1fabf31722834aba8a857653d88780a1291c5f6b3R316-R325
It's possible that inputs can alias each other as well, but I prevent that from happening by creating new input allocations just for stream capture: https://github.com/pytorch/pytorch/pull/152622/files#diff-cbda127114b86d36ed63c8b1fabf31722834aba8a857653d88780a1291c5f6b3R196
I suppose there is a possibility that an output could be part of an input whose index is in static_input_idxs, which I'm not sure if I handle yet explicitly. I really need to unit test such things explicitly TBH.
There was a problem hiding this comment.
Hm I think that's a little different though? That would be these lines:
for (size_t i = 1; i < sorted_allocations.size(); i++) {
auto prev = sorted_allocations[i - 1];
TORCH_CHECK(prev.ptr + prev.size <= sorted_allocations[i].ptr, "Dynamic tensors may not overlap");
}which you kept.
These ones make sure that when you swap out an original tensor for a new one, the new one is the same dtype, shape, and stride as the original
There was a problem hiding this comment.
It's a bit of a curt answer, but I'm in hack mode right now. I am making a lot of changes somewhat speculatively as I try to get all of the benchmarks in torchbench to run accurate and with good performance. So I'm messing with a ton of things.
There was a problem hiding this comment.
yeah that's totally fair, sorry for bothering, you've got this pr marked as draft so I shouldn't nitpick
python-side cuda graphs without copies Fix up getting type information data. I need to fix the case in is_equal() where a struct has two arrays following each other back to back. is_equal() now works correctly. Dynamic graph replay now works with output tensors. Successfully detect pointers using type information, not just 8-byte aligned guessing.
Need to add support for multiple different input shapes to the same function (like cudagraph trees does). Need to make output allocation faster.
…fore manual instantiation.
…s now run correctly.
…an elementwise kernel.
The problem was that torch.Tensor.nbytes does not count the number of bytes backing the Tensor. It backs the "virtual" count of bytes accessed tye the tensor's view. This can be larger than expected when using non-contiguous strides (like for broadcasting).
Also fixes hf_BigBird and hf_Bart. Unfortunately, not all training runs are completing correctly, though.
Problem was that I assumed that the two graphs would never have overlapping allocations. I was not guaranteeing this since the static_inputs of the first graph would be deleted before the static_outputs of the seocnd graph were created.
127d720 to
76f5622
Compare

This is a follow on to #137318 .
The main concern with that PR was robustness: We had no real way of knowing whether or not a particular 8-byte aligned 8-byte value in a parameter was really a pointer. This made it basically impossible to 100% guarantee correctness of replacing the arguments of a cuda graph, since you might accidentally replace a false positive. However, the compiler does in fact know the types of every argument to a cuda kernel; the only way this is exposed right now is via dwarf debug information, so I parsed the dwarf debug information.
Disappointingly, this PR cannot be built on its own. I am currently depending upon a private API to get the ELF file holding a given cuda kernel (since that elf file contains the dwarf debug information we need) that sits in a header file called etbl_private.h (which I did not upload). Exposing internal APIs publicly will take time.
Another challenge with this PR is that it requires you to build all CUDA code with nvcc's "-G" flag. This creates dwarf debug symbols, but at the cost of disabling optimizations. This both slows down compilation and means we don't benefit from this change yet, since your kernels will be way slower.
A final concern is that this doesn't work with code generated via compilers other than nvcc. In particular, triton doesn't seem to generate dwarf debug symbols. I'm not very concerned about this right now, since triton's kernels apparently have very simple parameters (just basic types no structs): https://github.com/triton-lang/triton/blob/bb60d9efe15534c1d0514e19cdf5da14d38779a2/third_party/nvidia/backend/driver.py#L100-L122
That may all sound underwhelming, but I hope this paves the way towards calling cuda graphs as if they are functions. (i.e., you will no longer have to worry about an errant graph.replay() call clobbering an output value from a previous graph.replay()). The ability to reliably detect pointers in a cuda graph also would allow us to prevent cuda graphed code from "hogging" memory from non cuda graphed code. This is because we could "unmap" the physical memory backing virtual addresses of temporary allocations in a cuda graph. It remains to be seen whether this can be done perfomantly @eellison .
I hope this dovetails nicely with @BoyuanFeng 's work on inductor graph partition and removing all of the constraints and workarounds in cudagraph trees.
@eellison @BoyuanFeng @leijurv @zdevito
cc @H-Huang @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @chenyang78 @kadeng @muchulee8 @amjames @chauhang @aakhundov