Skip to content

[ROCm] enable CK backend for bf16/fp16 on gfx11 - #143971

Closed
jfactory07 wants to merge 6 commits into
pytorch:mainfrom
ROCm:gfx11-ck
Closed

jfactory07 wants to merge 6 commits into
pytorch:mainfrom
ROCm:gfx11-ck

Conversation

@jfactory07

@jfactory07 jfactory07 commented Dec 30, 2024 •

Copy link
Copy Markdown
Contributor

@pytorch-bot

pytorch-bot Bot commented Dec 30, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 1 Pending, 1 Unrelated Failure

As of commit de21e88 with merge base 790f93d (image):

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

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

@linux-foundation-easycla

linux-foundation-easycla Bot commented Dec 30, 2024 •

Copy link
Copy Markdown

CLA Signed

The committers listed above are authorized under a signed CLA.

@jfactory07

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Dec 30, 2024
@jfactory07
jfactory07 marked this pull request as ready for review January 3, 2025 03:57
@jfactory07

Copy link
Copy Markdown
Contributor Author

@jeffdaily please help to review it.



auto stream = at::cuda::getCurrentHIPStream().stream();
#if 1

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Why are we keeping the #else condition dead code here?

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.

it is useful to performance tuning, so I keep it.

@jeffdaily jeffdaily changed the title enable CK backend for fp16 on Gfx11 [ROCm] enable CK backend for fp16 on gfx11 Jan 3, 2025
@pytorch-bot pytorch-bot Bot added ciflow/rocm module: rocm AMD GPU support for Pytorch labels Jan 3, 2025
@jeffdaily

Copy link
Copy Markdown
Collaborator

This is challenging to approve since we do not have gfx11-enabled CI runners to verify the changes.

@jfactory07

Copy link
Copy Markdown
Contributor Author

This is challenging to approve since we do not have gfx11-enabled CI runners to verify the changes.

it shouldn't break anything, since CK backend is disabled by default.

@jithunnair-amd

Copy link
Copy Markdown
Collaborator

This is challenging to approve since we do not have gfx11-enabled CI runners to verify the changes.

it shouldn't break anything, since CK backend is disabled by default.

That might be so, but in the absence of testing in CI, can you please attach some results with this PR's changes on your local gfx11 node?

@jfactory07

Copy link
Copy Markdown
Contributor Author

This is challenging to approve since we do not have gfx11-enabled CI runners to verify the changes.

it shouldn't break anything, since CK backend is disabled by default.

That might be so, but in the absence of testing in CI, can you please attach some results with this PR's changes on your local gfx11 node?

can you tell my the test command ? I have tested it on vLLM inference.

@jithunnair-amd

Copy link
Copy Markdown
Collaborator

This is challenging to approve since we do not have gfx11-enabled CI runners to verify the changes.

it shouldn't break anything, since CK backend is disabled by default.

That might be so, but in the absence of testing in CI, can you please attach some results with this PR's changes on your local gfx11 node?

can you tell my the test command ? I have tested it on vLLM inference.

Assuming that exercises the ops being enabled for CK here, maybe some diagnostic output that shows CK kernels being invoked and also maybe some numbers on how CK backend performs compared to the non-CK backend?

@jfactory07

jfactory07 commented Jan 6, 2025 •

Copy link
Copy Markdown
Contributor Author

This is challenging to approve since we do not have gfx11-enabled CI runners to verify the changes.

it shouldn't break anything, since CK backend is disabled by default.

That might be so, but in the absence of testing in CI, can you please attach some results with this PR's changes on your local gfx11 node?

can you tell my the test command ? I have tested it on vLLM inference.

Assuming that exercises the ops being enabled for CK here, maybe some diagnostic output that shows CK kernels being invoked and also maybe some numbers on how CK backend performs compared to the non-CK backend?

ok, here is my local test and output on gfx1100:

def test_gemm(m, n , k,  do_profile)
    torch.set_default_device("cuda:0")
    dtype = torch.float16

    weight = torch.randn(n, k, dtype=dtype)
    x = torch.randn(m, k, dtype=dtype)

    flop = 2 * m * n * k
    
    start_event = torch.cuda.Event(enable_timing=True)  
    end_event = torch.cuda.Event(enable_timing=True)  

    torch.backends.cuda.preferred_blas_library('ck')
    torch.mm(x, weight.t()) #warm up
    start_event.record()
    out = torch.mm(x, weight.t())
    end_event.record() 
    torch.cuda.synchronize()
    torch.backends.cuda.preferred_blas_library('hipblaslt')

    elapsed_time_ms = start_event.elapsed_time(end_event) 
    print(f"CK time: {elapsed_time_ms:.3f}")
    print(f"CK tflops: {flop/1.0e9/elapsed_time_ms:.3f}")
        
    if do_profile:
        start_event = torch.cuda.Event(enable_timing=True)  
        end_event = torch.cuda.Event(enable_timing=True)  
        ref_out = torch.mm(x, weight.t())#warm up
        start_event.record()  
        ref_out = torch.mm(x, weight.t())
        end_event.record() 
        torch.cuda.synchronize()
        elapsed_time_ms = start_event.elapsed_time(end_event) 
        print(f"hipblas time: {elapsed_time_ms:.3f}")
        print(f"hipblas tflops: {flop/1.0e9/elapsed_time_ms:.3f}")

 test_gemm(4633, 27648, 5120, True)

here is the output:

CK time: 15.675
CK tflops: 83.682
hipblas time: 20.566
hipblas tflops: 63.779

@cpuhrsch cpuhrsch added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jan 7, 2025
@FeepingCreature

FeepingCreature commented Jan 14, 2025 •

Copy link
Copy Markdown

Hi! I've built this branch, and if I try to run SDXL in ComfyUI with the ck blas backend, it immediately runs into RuntimeError: wrong! device_gemm with the specified compilation parameters does not support this GEMM problem .

I don't see where the printf ends up.

edit: Update/correction: it's not the wrong! message from this PR; I think the CK backend just doesn't play well with comfy or sdxl.

edit: Ah it doesn't even hit the half code in this PR because ComfyUI fails with some 32-bit float ops before it can even get to the half float ones, and I can't pick and choose the blas backend. preferred_blas_library('ck') just falls over. For what it's worth, the failing geometry is error shape = 1 1280 1280 TRANSA=1 TRANSB=0.

edit: Yep, it happens on the shipped nightly pytorch as well.

@jfactory07

Copy link
Copy Markdown
Contributor Author

Hi! I've built this branch, and if I try to run SDXL in ComfyUI with the ck blas backend, it immediately runs into RuntimeError: wrong! device_gemm with the specified compilation parameters does not support this GEMM problem .

I don't see where the printf ends up.

edit: Update/correction: it's not the wrong! message from this PR; I think the CK backend just doesn't play well with comfy or sdxl.

edit: Ah it doesn't even hit the half code in this PR because ComfyUI fails with some 32-bit float ops before it can even get to the half float ones, and I can't pick and choose the blas backend. preferred_blas_library('ck') just falls over. For what it's worth, the failing geometry is error shape = 1 1280 1280 TRANSA=1 TRANSB=0.

edit: Yep, it happens on the shipped nightly pytorch as well.

hi @FeepingCreature ,
please note this PR only enable FP16 CK backend on gfx1100. So please make sure add preferred_blas_library('ck') before FP16 GEMM.

@FeepingCreature

FeepingCreature commented Jan 14, 2025 •

Copy link
Copy Markdown

Well it should still use the existing non-wmma gemm code otherwise, if I'm reading the diff right? And afaict that already falls over with the ck backend when running comfyui sdxl against it, so even if I have, say, a model with fp16 unet and fp32 vae I can't even get to the wmma code for the unet, cause the non-wmma non-fp16 ck gemm code already doesn't work with the vae anyway.

Not relevant for this PR at any rate.

@jfactory07

jfactory07 commented Jan 14, 2025 •

Copy link
Copy Markdown
Contributor Author

Well it should still use the existing non-wmma gemm code otherwise, if I'm reading the diff right? And afaict that already falls over with the ck backend when running comfyui sdxl against it, so even if I have, say, a model with fp16 unet and fp32 vae I can't even get to the wmma code for the unet, cause the non-wmma non-fp16 ck gemm code already doesn't work with the vae anyway.

Not relevant for this PR at any rate.

The existing non-wmma gemm code only works on MI series.

@gel-crabs

Copy link
Copy Markdown

It works if you set the CK backend to choose, say, hipBLASLt instead of CK for FP32 in CUDABlas.cpp. Sadly WMMA does not have any instructions for FP32 so it can't be implemented at all.

It does work correctly with BF16 if you repeat the changes for ck_gemm_half.hip in ck_gemm_bfloat16.hip.

Here's the patch explaining what I mean; no device checks, certainly not PR material but it does work if you're only using GFX11.

gfx11ckfix.patch.txt

Also, I'm on gfx1101; with all the instances of gfx1100 replaced with gfx1101 in the 2 patch files it is faster than hipBLASLt.

CK time: 24.423 CK tflops: 53.706 hipblas time: 27.439 hipblas tflops: 47.803

@jfactory07

Copy link
Copy Markdown
Contributor Author

It works if you set the CK backend to choose, say, hipBLASLt instead of CK for FP32 in CUDABlas.cpp. Sadly WMMA does not have any instructions for FP32 so it can't be implemented at all.

It does work correctly with BF16 if you repeat the changes for ck_gemm_half.hip in ck_gemm_bfloat16.hip.

Here's the patch explaining what I mean; no device checks, certainly not PR material but it does work if you're only using GFX11.

gfx11ckfix.patch.txt

Also, I'm on gfx1101; with all the instances of gfx1100 replaced with gfx1101 in the 2 patch files it is faster than hipBLASLt.

CK time: 24.423 CK tflops: 53.706 hipblas time: 27.439 hipblas tflops: 47.803

Thanks for your test on gfx1101. Good to know gfx1101 also has uplift with CK GEMM.
You are right, there isn't WMMA instruction for FP32 on gfx11.

@FeepingCreature

FeepingCreature commented Jan 15, 2025 •

Copy link
Copy Markdown

Can confirm it works with the @gel-crabs patch on my gfx1100. ComfyUI SDXL 1024x1024 (torch.compiled, stable over 3 runs):

  • without torch.backends.cuda.preferred_blas_library('ck'): 4.07it/s, 5.68s
  • with torch.backends.cuda.preferred_blas_library('ck'): 4.33it/s, 5.38s

and printf debugging confirms it hits the wmma branch.

(Though with 2048x2048 it falls over with !!! Exception during processing !!! CUDA error: HIPBLAS_STATUS_INTERNAL_ERROR when calling hipblasLtMatmul with transpose_mat1 1 transpose_mat2 0 m 65536 n 65536 k 512 lda 512 ldb 512 ldc 65536 abcType 0 computeType 2 scaleType 0.)

@jfactory07 jfactory07 closed this Jan 15, 2025
@jfactory07 jfactory07 reopened this Jan 15, 2025
@jfactory07
jfactory07 requested a review from eqy as a code owner January 15, 2025 06:05
@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Mar 17, 2025

Copy link
Copy Markdown

Pull workflow has not been scheduled for the PR yet. It could be because author doesn't have permissions to run those or skip-checks keywords were added to PR/commits, aborting merge. Please get/give approval for the workflows and/or remove skip ci decorators before next merge attempt. If you think this is a mistake, please contact PyTorch Dev Infra.

@FeepingCreature

FeepingCreature commented Mar 17, 2025 •

Copy link
Copy Markdown

To be safe, I reran my ComfyUI SDXL benchs with this branch rebased on main:

  • torch.compile, no ck: 4.47it/s
  • torch.compile, prefer ck: 4.72it/s

Pretty much same difference as before.

Though if I turn on PYTORCH_TUNABLEOP_ENABLED, they both go up to ~5.18it/s and become nearly-equal. Does TunableOp select the ck version on its own?

And of course, FlashAttention trounces both, with a peak 5.7it/s with tuning and torch.compile.

@jeffdaily

Copy link
Copy Markdown
Collaborator

Though if I turn on PYTORCH_TUNABLEOP_ENABLED, they both go up to ~5.18it/s and become nearly-equal. Does TunableOp select the ck version on its own?

TunableOp does not consider CK GEMM currently, only roc/hipblas or hipblaslt.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased gfx11-ck onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via git checkout gfx11-ck && git pull --rebase)

@gel-crabs

Copy link
Copy Markdown

To be safe, I reran my ComfyUI SDXL benchs with this branch rebased on main:

* torch.compile, no ck: 4.47it/s

* torch.compile, prefer ck: 4.72it/s

Pretty much same difference as before.

Though if I turn on PYTORCH_TUNABLEOP_ENABLED, they both go up to ~5.18it/s and become nearly-equal. Does TunableOp select the ck version on its own?

And of course, FlashAttention trounces both, with a peak 5.7it/s with tuning and torch.compile.

When the preferred BLAS library is set to CK, TunableOp chooses "Default" as the fastest solution for practically every GemmAndBiasTunableOp problem, i.e. what it would be if TunableOp was off. Otherwise it would be rocblas/hipblaslt solutions.

CK is being selected, but not specifically, just as the default solution if that makes sense.

@jeffdaily

Copy link
Copy Markdown
Collaborator

When the preferred BLAS library is set to CK, TunableOp chooses "Default" as the fastest solution for practically every GemmAndBiasTunableOp problem, i.e. what it would be if TunableOp was off. Otherwise it would be rocblas/hipblaslt solutions.

CK is being selected, but not specifically, just as the default solution if that makes sense.

Aha, yes, that makes sense. We had postponed adding CK to TunableOp because there is the 1) quick/easy way, and 2) the comprehensive way to do it. The quick/easy would be to run the few CK GEMM implementations we have in the CK backend of torch.mm within TunableOp. The comprehensive approach would mimic what onnxruntime is doing which is to compile all possible combinations of CK params and try them all. Doing (2) would cause the already long compile time of ROCm torch to balloon into something prohibitive. But I think we can do (1). I will add (1) to a TODO list.

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Mar 18, 2025
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

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

@jfactory07

Copy link
Copy Markdown
Contributor Author

When the preferred BLAS library is set to CK, TunableOp chooses "Default" as the fastest solution for practically every GemmAndBiasTunableOp problem, i.e. what it would be if TunableOp was off. Otherwise it would be rocblas/hipblaslt solutions.
CK is being selected, but not specifically, just as the default solution if that makes sense.

Aha, yes, that makes sense. We had postponed adding CK to TunableOp because there is the 1) quick/easy way, and 2) the comprehensive way to do it. The quick/easy would be to run the few CK GEMM implementations we have in the CK backend of torch.mm within TunableOp. The comprehensive approach would mimic what onnxruntime is doing which is to compile all possible combinations of CK params and try them all. Doing (2) would cause the already long compile time of ROCm torch to balloon into something prohibitive. But I think we can do (1). I will add (1) to a TODO list.

HI Jeff,
I think it would be best if CK could also provide an API like hipBLASlt that returns the best algorithm because:

  1. If CK implements a new GEMM kernel, clients such as Torch or ONNX Runtime would need to modify their code.
  2. It would reduce redundancy in client code, as Torch or ONNX Runtime wouldn't need to maintain similar code.

pytorchmergebot pushed a commit that referenced this pull request Oct 27, 2026
### Summary

The CK GEMM supported-architecture allowlist currently lives hardcoded in three
places: `torch_filter_ck_gemm_arches` (cmake/public/utils.cmake), the runtime
check `at::Context::ckGemmSupported()`, and the `gemm_internal_ck` dispatch in
`ck_gemm_{half,bfloat16}.hip`. Keeping them in sync is manual, and the
gfx11/gfx12 WMMA path (#143971) can only be re-enabled by editing source in
several spots.

This PR makes the list a single source of truth:

- A new CMake cache variable `TORCH_CK_GEMM_ARCH_LIST` (default
  `gfx90a;gfx942;gfx950`) drives the `ck_gemm` build arch filter and is surfaced
  to C++ through a generated `ATen/ROCmCKGEMMConfig.h` header, mirroring the
  existing `AT_ROCM_CK_SDPA_ARCHS` mechanism. It is forwarded from the
  environment via `cmake/EnvVarForwarding.cmake`.
- `Context.cpp` parses the list once through a shared `parseArchList` helper
  used by both `ckSDPASupported()` and `ckGemmSupported()`.
- The `.hip` dispatch calls `at::globalContext().ckGemmSupported()` instead of
  re-parsing the list, so the header include, the parser, and the fallback are
  removed from both `.hip` files.

A WMMA arch can now be opted back in at both build and run time without patching
source, e.g. `TORCH_CK_GEMM_ARCH_LIST="gfx90a;gfx942;gfx950;gfx1200"`.

### BC-breaking

No. Default behavior is unchanged -- the default list is the same three archs
that were previously hardcoded.

### Supporting maintainer

@jeffdaily (requested this refactor in review).

### Test plan

CMake wiring, standalone project including `cmake/public/utils.cmake`:
- default: `torch_filter_ck_gemm_arches` filters
  `gfx942;gfx1250-strict;gfx950;gfx1200` to `gfx942;gfx950`; generated header
  `#define TORCH_CK_GEMM_ARCH_LIST "gfx90a,gfx942,gfx950"`.
- override `TORCH_CK_GEMM_ARCH_LIST="gfx90a;gfx942;gfx950;gfx1200"`: filter keeps
  `gfx942;gfx950;gfx1200`; header `"gfx90a,gfx942,gfx950,gfx1200"`.

Full build:
```
PYTORCH_ROCM_ARCH="gfx90a gfx942 gfx950" pip install -e . --no-build-isolation -v
```
rc=0, 0 failed. `ck_gemm_half.hip.o` offload bundle = `gfx90a,gfx942,gfx950`;
`libtorch_hip.so` links (the `ck_gemm` -> `Context::ckGemmSupported()` cross-TU
call resolves).

Pull Request resolved: #201113
Approved by: https://github.com/jeffdaily

Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Jeff Daily <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request Merged module: rocm AMD GPU support for Pytorch open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants