Skip to content

[Inductor Cutlass backend] Improved GEMM template - #124577

Closed
kadeng wants to merge 11 commits into
gh/kadeng/56/basefrom
gh/kadeng/56/head
Closed

kadeng wants to merge 11 commits into
gh/kadeng/56/basefrom
gh/kadeng/56/head

Conversation

@kadeng

@kadeng kadeng commented Apr 21, 2024 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Improves the Cutlass backend GEMM template:

  • Adds code which allows to create stand-alone test runners for Cutlass GEMM Kernels, which allows (manual) debugging of, for example, CUDA IMA errors or similar problems which occur in practice. Includes some utility code and tests to actually compile and run these standalone tests.
  • Cleans up the GEMM template code through various refactorings
  • Eliminates code sections and options that are unneccessary now that epilogue fusions are being removed.
  • Limits the scope of a workaround for (flaky) Cutlass issues with bias broadcasting to neccessary cases.
  • Puts some CPU runtime checks into #if / #endif blocks, such that it's possible to compile CUTLASS Kernels with lower CPU overhead.
  • Add documentation comments

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 21, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 2 Unrelated Failures

As of commit 08d4aed with merge base 7d94f52 (image):

NEW FAILURE - The following job has failed:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

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

kadeng added 2 commits April 22, 2024 11:30
[ghstack-poisoned]
[ghstack-poisoned]
@kadeng
kadeng marked this pull request as ready for review April 23, 2024 08:25
@kadeng
kadeng requested a review from ipiszy April 23, 2024 08:26
@lezcano
lezcano requested a review from alexsamardzic April 23, 2024 08:28
@alexsamardzic

Copy link
Copy Markdown
Collaborator

Am looking into this one, and previous two PRs in the stack; my question is: what is a general direction here? Namely, I can see EVT epilogues related code is removed, also it seems only 3.x GEMM instances will be generated, etc. On the other side, I have a PR adding support for sparse MM, that is not ported to 3.x interface in CUTLASS, also plan to work on other stuff here related to sparse and mixed data-types GEMM that would need 2.x EVT epilogue support. So, looking at the changes at the moment, it seems to me that I'd have to revert some of the removed stuff, but I guess I may be missing the big picture, that's why I'm asking...

@kadeng

kadeng commented Apr 23, 2024

Copy link
Copy Markdown
Contributor Author

@alexsamardzic

Hi Alex, the removal of the EVT-based epilogue code was based on a case-study that I did a while ago. It turned out that using and especially dynamically generating EVT-based epilogues was not worth the hassles this introduced.

Cutlass 2.x Kernels (not mixed mode) in general showed no performance advantage over using CuBLAS / ATen or Triton in my study. Which is not that surprising considering that CuBLAS can use Cutlass Kernels itself, but is not quite up to date when it comes to the Cutlass version.

All of that said, if you have a usecase for 2.x Cutlass Kernels that Cutlass 3.x cannot cover well, I would propose to create a copy / fork of CUTLASSGemmTemplate (maybe call it CUTLASS2xGemmTemplate or such) for this case in your PR since it would otherwise make the individual classes a lot more complicated to maintain and test, considering the degree of if / else logic that is neccessary to maintain Cutlass 2.x and Cutlass 3.x support in a single class. You could then add the corresponding choices to the autotuner within CUTLASS2xGemmTemplate within mm.py / tuned_mixed_mm as neccessary.

When creating CUTLASS2xGemmTemplate, you could take the old version of the class (e.g. before this change) and simplify it by removing 3.x support.

Does that make sense for you?

kadeng added 2 commits April 23, 2024 20:17
[ghstack-poisoned]
[ghstack-poisoned]
@alexsamardzic

Copy link
Copy Markdown
Collaborator

Thanks for the clarification. Do you have pointer to the results of this case study of yours? I agree that for ordinary GEMMs, cuBLAS or Triton should be on par with CUTLASS. On the other side, in my limited and anecdotal benchmarking of CUTLASS 3.x API functionality vs. CUTLASS 2.x API functionality (note that I'm talking about 3.x and 2.x APIs here, and not CUTLASS releases, because in CUTLASS 3.x releases, it's still possible to use CUTLASS 2.x API, and my benchmarking was using the same CUTLASS release for both APIs), I haven't seen much of a difference, so I'm asking about the benchmarking results as I would be interested in any CUTLASS 3.x API performance advantage over larger set of shapes/data-types.

If using CUTLASS through 3.x API doesn't have much of performance advantage over cuBLAS/Triton, than this is just an additional argument that CUTLASS is not that interesting for auto-tuning of plain GEMM operators (other arguments: CUTLASS candidate kernels are slow to compile, could fail in run time that CUTLASS-based auto-tuning Inductor code doesn't handle gracefully at the moment, etc.). The main advantage of auto-tuned CUTLASS kernels should be when GEMM itself is fused with other operations (like de-quantization in case of mixed data-types) and/or for operators like sparse semi-structured that are not supported by cuBLAS/Triton. But for cases like these, EVT epilogues are needed. Now, I understand the rationale behind your changes, and I can indeed proceed with a separate CUTLASSGemmTemplate class for my use cases. But some of these (mixed data-types, for some combinations of data-types) could in principle already work with 3.x API, and for others (sparse semi-structured) CUTLASS may support them through 3.x API in the future, and EVT epilogues would have to be re-introduced in this part of the functionality that this PR is removing it from.

@kadeng

kadeng commented Apr 24, 2024 •

Copy link
Copy Markdown
Contributor Author

Thanks for the clarification. Do you have pointer to the results of this case study of yours?

It's not public since it involves details of Meta-internal production models. But I can easily summarize the relevant findings here for you. If you want to know more, we can move the discussion to Slack.

It was based on a codebase that was considerably more capable than what you see in this diff stack. Most importantly, it could really dynamically generate complex epilogues with additional tensor inputs, and I have done whole-model benchmarks, microbenchmarks and section profiling with it ( with and without CUDA Graphs ).

I agree that for ordinary GEMMs, cuBLAS or Triton should be on par with CUTLASS.

Yes, that's also what I found. Usually one of these is at least on-par with Cutlass if you apply Autotuning to all three, and the problem shapes are small enough ( rule of thumb: BATCHSIZE x M x N x K has 10 decimal digits or less ). For larger shapes, Cutlass 3.x SM90 TMA-enabled Kernels start to have a clear advantage on H100+.

It's about the SM90 TMA Kernels. The Cutlass 3.x API does not have a performance advantage as such, actually it can have a slightly higher CPU overhead. But that doesn't matter once you bring in CUDA Graphs to eliminate that.

The main advantage of auto-tuned CUTLASS kernels should be when GEMM itself is fused with other operations (like de-quantization in case of mixed data-types) and/or for operators like sparse semi-structured that are not supported by cuBLAS/Triton.

Yes and no. The SM90 TMA Kernels are worthwile even on plain GEMMs / BMMs. For everything else, this is also what we thought initially. And here it gets a bit complicated since it involves complex performance tradeoffs in the context of Kernels and entire model architectures.

Just to make it clear: It's the dynamic generation of EVT functors via Inductor-based operator fusion and translation of inductor IR / Pointwise ops into corresponding EVT-functors that's being removed. If you want to introduce manually written and tested EVT-functors for specific usecases ( say, mixed-mode GEMMs, quantized ops etc. ) it should still be possible, but might require customized GEMM templates, that could then also take additional inputs ( say, vectors of row-wise / column-wise scaling factors).

So, why are we removing dynamic generation of EVT-functors? Here are a few reasons:

1.) Performance

This is not neccessarily evident from microbenchmarks, but if you do whole-model benchmarks of inductor-lowered models where CPU overhead has been eliminated via CUDA Graphs, the remaining performance improvement is typically on the order of 0.0% to 0.4%.

Why?: Let's imagine we have a simple model architecture that looks like this:

Inputs -> Matmul1 -> Op1 -> Op2 -> Op3 -> Op4 -> Op5 -> Matmul2 -> Op6 -> Op7 -> Op8 -> Matmul3 -> Op9 -> Op10

If you use Inductor with Triton, even if you disable epilogue fusion entirely, it will often fuse intermediate operations entirely, so we get:

Inputs -> Matmul1 -> TritonFUSED1 -> Matmul2 -> TritonFUSED2-> Matmul3 -> TritonFUSED3

Let's now imagine we have GEMM epilogue fusion. But this operator fusion is not as capable as Triton at fusing operators (because it doesn't cover general reductions and is limited to the GEMM Kernel grid layout), and therefore cannot fuse all ops between the Matmuls. It would look like this:

Inputs -> Fused(Matmul1+Op1+Op2) -> TritonFUSED1 -> Fused(Matmul2+Op6) -> TritonFUSED2-> Fused(Matmul3+Op9) -> Op10

If you look at this, the number of Kernels remains the same. The only thing that's changed is where the GPU memory transfer happens ( yes, for mixed mode or quantized, this can be important. Less so if the dtype is constant). Even if we can save a memory transfer and Kernel launch here or there, the performance benefit of that is small, considering how fast the HBM memory has become, and Kernel launch overheads are neglible if we use CUDA Graphs.

And while Cutlass is often faster than Triton on Matmuls, it's certainly not faster on simple elementwise operations or reductions. Actually, the opposite can happen. Fast Kernels can become slow if you add arbitrary epilogues:

  • Cutlass SM90 TMA GEMM Kernels do not have a grid layout that's ideal for epilogue computations. It's certainly not useable for most reductions.
  • If additional inputs ( auxiliary inputs ) are required, they require shared memory, registers or on-the-fly memory access. Either of these cases can trash the performance of a fast GEMM Kernel that already uses shared mem and registers to the max.

The more operations / aux. inputs you fuse, the more likely it becomes that the resulting performance is really bad. So we have to measure performance impact of every fusion, and with high probability we decide against fusion. So we end up with partially fused operator chains as in the example above, even if we theoretically could fuse more.

The theoretical roofline performance improvement through epilogue fusion for the same models is also very small, even if we make the unrealistic assumption that we can save one memory transfer ( loading of the GEMM output) and one kernel launch for all GEMMs in the entire model. This has changed when you go from A100 to H100 due to memory bandwidth improvements. Additionally, CUDA Graphs eliminate almost all the Kernel launch overhead, so there's not much to gain either.

2.) Stability & Numerics

When generating epilogues, my experience was that I was stepping into untested territory. The degrees of freedom are very high for code that basically has no safety net. Consequently, I encountered CUDA IMAs or even infinite loops with generated epilogues. Or even worse than that, numerical correctness issues.

I would recommend to test every single combination of EVT epilogue functors and inputs for performance impact and stability on the specific Cutlass Kernels and the problem shape, dtype and hardware architecture you want to run them with.

3.) Complexity & Maintainability

The amount of code neccessary and the complexity of it is rather high. Maintaining all of this in Inductor, and keeping it compatible with the evolving capabilities of the Triton backend (say, dynamic shapes) would have been a very challenging endeavour. We discussed this a bit and found it not to be worth it, considering the points above.

But some of these (mixed data-types, for some combinations of data-types) could in principle already work with 3.x API, and for others (sparse semi-structured) CUTLASS may support them through 3.x API in the future, and EVT epilogues would have to be re-introduced in this part of the functionality that this PR is removing it from.

That's right. I would still recommend to write specialized implementations for these and test them well both with respect to performance, stability and correctness instead of relying on general codegen that cannot guarantee either.

kadeng added 4 commits April 24, 2024 19:34
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
layout for the given Bias operand.
"""
# If bias is row major, swap all M and N dimensions
if (

@kadeng kadeng Apr 25, 2024 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Note: this method has always been (since original implementation by yingz) a workaround for CUDA errors that occurred in some CUTLASS GEMM Kernels with linear epilogue. This is not something I can reproduce in unit tests. This new variant of the workaround is more limited in scope and does not just pass the unit tests, it is also more battle-tested in practice (e.g. in large model conversion) than the old variant.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Cleaned up the diff a bit to make it easier to review. See also comments above.

kadeng added 2 commits April 25, 2024 11:04
[ghstack-poisoned]
[ghstack-poisoned]
@kadeng

kadeng commented Apr 25, 2024

Copy link
Copy Markdown
Contributor Author

The current test failure appears unrelated, as it looks like the rocm CI job was cancelled or timed out ( KeyboardInterrupt )

@kadeng

kadeng commented Apr 26, 2024

Copy link
Copy Markdown
Contributor Author

@jansel Thanks for reviewing. This was likely the biggest single diff in the stack.

@kadeng

kadeng commented Apr 26, 2024

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge --ignore-current

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 26, 2024
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 3 checks: pull / linux-focal-py3.12-clang10 / test (dynamo, 3, 3, linux.2xlarge), pull / linux-focal-cuda12.1-py3.10-gcc9 / test (default, 4, 5, linux.4xlarge.nvidia.gpu), inductor / rocm6.0-py3.8-inductor / test (inductor, 1, 1, linux.rocm.gpu.2)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@alexsamardzic

Copy link
Copy Markdown
Collaborator

Thanks for sharing all the details (and sorry for the late reply, I was off couple days). I understand the rationale, and since several PRs from this stack are already merged, I'll try to proceed along the proposed line of separate GEMM template class. Admittedly, the Ampere and/or CUTLASS 2.x architecture specific stuff, that my interest is in primarily, will be obsoleted at some point, but for now I hope it may be still valuable to cover with some auto-tuning support.

petrex pushed a commit to petrex/pytorch that referenced this pull request May 3, 2024
Improves the Cutlass backend GEMM template:

 * Adds code which allows to create stand-alone test runners for Cutlass GEMM Kernels, which allows (manual) debugging of, for example, CUDA IMA errors or similar problems which occur in practice. Includes some utility code and tests to actually compile and run these standalone tests.
 * Cleans up the GEMM template code through various refactorings
 * Eliminates code sections and options that are unneccessary now that epilogue fusions are being removed.
 * Limits the scope of a workaround for (flaky) Cutlass issues with bias broadcasting to neccessary cases.
 * Puts some CPU runtime checks into #if / #endif blocks, such that it's possible to compile CUTLASS Kernels with lower CPU overhead.
 * Add documentation comments

Pull Request resolved: pytorch#124577
Approved by: https://github.com/jansel
ghstack dependencies: pytorch#124576
fathnd pushed a commit to fathnd/homomorphic that referenced this pull request May 5, 2024
Improves the Cutlass backend GEMM template:

 * Adds code which allows to create stand-alone test runners for Cutlass GEMM Kernels, which allows (manual) debugging of, for example, CUDA IMA errors or similar problems which occur in practice. Includes some utility code and tests to actually compile and run these standalone tests.
 * Cleans up the GEMM template code through various refactorings
 * Eliminates code sections and options that are unneccessary now that epilogue fusions are being removed.
 * Add documentation comments

ghstack-source-id: 3c510cf
Pull Request resolved: pytorch/pytorch#124577
@github-actions
github-actions Bot deleted the gh/kadeng/56/head branch June 3, 2024 01:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants