-
Notifications
You must be signed in to change notification settings - Fork 24
perf: optimize hipBLASLt grouped GEMM with algo tuning, enable grouped_gemm autotune hipblaslt support #284
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kyle-256
wants to merge
23
commits into
main
Choose a base branch
from
dev/kyle/improve_bf16_triton_gg
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
d253a59
fix: hipBLASLt grouped GEMM b_ptr desync for unbalanced experts
kyle-256 a5e11a8
perf: cache hipBLASLt algo to eliminate per-call heuristic search
kyle-256 7663ce2
fix: use hipMemcpy to read group_lens, eliminating GPU L2 cache coher…
kyle-256 459435f
perf: replace 4-stream concurrent dispatch with single-stream serial …
kyle-256 dffc8ae
perf: adaptive serial/parallel dispatch based on per-expert GEMM size
kyle-256 e26cd0d
perf: autotune hipBLASLt algo selection across top-8 heuristic candid…
kyle-256 b53512c
bench: add mild-unbalanced routing mode alongside extreme-unbalanced
kyle-256 00ea341
perf: stabilize autotune (warmup=10 bench=30) and fix pre_sync guard
kyle-256 a6c9ba4
perf: support CPU-side group_lens to eliminate blocking hipMemcpy
kyle-256 24cd094
perf: cache hipBLASLt descriptors in gemm_impl to reduce per-call ove…
kyle-256 4f31594
perf: make algo cache M-invariant to avoid re-autotune per MoE iteration
kyle-256 301bdf9
tmp save for other machines
kyle-256 ef3cc6b
chore: clean up PR — restore group_offs interface, remove temp files
kyle-256 01fa0a6
bench: add --balance CLI arg to bench_grouped_gemm_turbo.py
kyle-256 ff12e88
perf: enable hipBLASLt in BF16 grouped GEMM autotune
kyle-256 ea2a64b
perf: enable hipBLASLt in BF16 grouped GEMM autotune
kyle-256 2f3b74a
perf: warm hipBLASLt algo cache with balanced M for grouped GEMM
kyle-256 a69bf5d
code lint
kyle-256 b17b585
fix: add exact-shape fallback for hipBLASLt cache
kyle-256 03936e9
fix: harden hipBLASLt GEMM cache lifecycle
kyle-256 c3bda59
fix: isolate hipBLASLt grouped GEMM workspaces
kyle-256 e8c776a
update requirements.txt
kyle-256 5a29d07
fix: stabilize hipBLASLt runtime state in tests
kyle-256 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,205 @@ | ||
| ############################################################################### | ||
| # Copyright (c) 2025, Advanced Micro Devices, Inc. All rights reserved. | ||
| # | ||
| # See LICENSE for license information. | ||
| ############################################################################### | ||
|
|
||
| """GMM (grouped_gemm) BF16 Grouped GEMM Baseline Benchmark. | ||
|
|
||
| Reference: https://github.com/tgale96/grouped_gemm | ||
| """ | ||
|
|
||
| import argparse | ||
| from datetime import datetime | ||
|
|
||
| import grouped_gemm.ops as gmm_ops | ||
| import pandas as pd | ||
| import torch | ||
| import torch.utils.benchmark as benchmark | ||
|
kyle-256 marked this conversation as resolved.
|
||
| from config import ( | ||
| check_allclose, | ||
| gen_grouped_gemm_group_lens, | ||
| gen_grouped_gemm_test_cases, | ||
| get_platform_info, | ||
| grouped_gemm_ref, | ||
| ) | ||
| from tabulate import tabulate | ||
|
|
||
|
|
||
| def check_grouped_gemm_gmm_correctness(a, b, batch_sizes, grad_out, dtype): | ||
| """Check correctness of gmm forward and backward against reference.""" | ||
| out = gmm_ops.gmm(a, b, batch_sizes, trans_b=True) | ||
|
|
||
| group_lens = batch_sizes.to(device=a.device, dtype=torch.int64) | ||
| out_ref = grouped_gemm_ref(a.detach(), b.detach(), group_lens, trans_b=True) | ||
| fwd_correct = check_allclose(out.detach(), out_ref, dtype) | ||
|
|
||
| a_ref = a.detach().clone().requires_grad_() | ||
| b_ref = b.detach().clone().requires_grad_() | ||
| out_ref = grouped_gemm_ref(a_ref, b_ref, group_lens, trans_b=True) | ||
| out_ref.backward(grad_out) | ||
| out.backward(grad_out, retain_graph=True) | ||
| bwd_correct = check_allclose(a.grad, a_ref.grad, dtype) | ||
|
|
||
| a.grad = None | ||
|
|
||
| correct = fwd_correct and bwd_correct | ||
| status = "PASS" if correct else "FAIL" | ||
| print(f"Correctness Check: {status} (fwd={fwd_correct}, bwd={bwd_correct})") | ||
|
|
||
| return correct | ||
|
|
||
|
|
||
| def profile_grouped_gemm_gmm(B, M, N, K, dtype, balance=True, num_topk=None): | ||
| """Profile BF16 Grouped GEMM using grouped_gemm (gmm) library.""" | ||
| device = "cuda" | ||
| # batch_sizes must be on CPU for gmm | ||
| batch_sizes = gen_grouped_gemm_group_lens(B, M, balance=balance, num_topk=num_topk) | ||
|
kyle-256 marked this conversation as resolved.
|
||
| total_m = batch_sizes.sum().item() | ||
|
|
||
| a = torch.randn((total_m, K), dtype=dtype, device=device, requires_grad=True) | ||
| b = torch.randn((B, N, K), dtype=dtype, device=device, requires_grad=True) | ||
|
|
||
| out = gmm_ops.gmm(a, b, batch_sizes, trans_b=True) | ||
| grad_out = torch.randn_like(out) | ||
|
|
||
| correct = check_grouped_gemm_gmm_correctness(a, b, batch_sizes, grad_out, dtype) | ||
|
|
||
| def fwd_func(): | ||
| return gmm_ops.gmm(a, b, batch_sizes, trans_b=True) | ||
|
|
||
| def fwd_bwd_func(): | ||
| out = gmm_ops.gmm(a, b, batch_sizes, trans_b=True) | ||
| out.backward(grad_out) | ||
| a.grad = None | ||
| b.grad = None | ||
|
|
||
| fwd_total_flops = 2 * B * M * N * K | ||
| bwd_total_flops = 2 * fwd_total_flops | ||
|
|
||
| for _ in range(100): | ||
| fwd_bwd_func() | ||
| torch.cuda.synchronize() | ||
|
|
||
| fwd_timer = benchmark.Timer(stmt="fn()", globals={"fn": fwd_func}) | ||
| fwd_measurement = fwd_timer.timeit(200) | ||
|
|
||
| fwd_bwd_timer = benchmark.Timer(stmt="fn()", globals={"fn": fwd_bwd_func}) | ||
| fwd_bwd_measurement = fwd_bwd_timer.timeit(200) | ||
|
|
||
| fwd_mean_time_ms = fwd_measurement.mean * 1e3 | ||
| fwd_bwd_mean_time_ms = fwd_bwd_measurement.mean * 1e3 | ||
| bwd_mean_time_ms = fwd_bwd_mean_time_ms - fwd_mean_time_ms | ||
|
|
||
| fwd_tflops = fwd_total_flops / (fwd_mean_time_ms * 1e-3) / 1e12 | ||
| bwd_tflops = bwd_total_flops / (bwd_mean_time_ms * 1e-3) / 1e12 | ||
| print(f"Forward Mean time: {fwd_mean_time_ms:.3f} ms | TFLOPS: {fwd_tflops:.2f}") | ||
| print(f"Backward Mean time: {bwd_mean_time_ms:.3f} ms | TFLOPS: {bwd_tflops:.2f}") | ||
|
|
||
| return fwd_mean_time_ms, fwd_tflops, bwd_mean_time_ms, bwd_tflops, correct | ||
|
|
||
|
|
||
| def benchmark_grouped_gemm_gmm(output_csv=None): | ||
| platform, gpu_name = get_platform_info() | ||
|
|
||
| test_cases = gen_grouped_gemm_test_cases() | ||
|
|
||
| rows = [] | ||
| test_id = 0 | ||
| dtype = torch.bfloat16 | ||
|
|
||
| for case in test_cases: | ||
| test_id += 1 | ||
| B, M, N, K = case["B"], case["M"], case["N"], case["K"] | ||
|
|
||
| balance = case.get("balance", True) | ||
| balance_str = "balanced" if balance else "unbalanced" | ||
| print(f"\n{'='*60}") | ||
| print( | ||
| f"TestID: {test_id}, Case: {case['Case']}, B: {B}, M: {M}, N: {N}, K: {K}, dtype: bf16, {balance_str}" | ||
| ) | ||
| print(f"{'='*60}") | ||
|
|
||
| try: | ||
| fwd_time_ms, fwd_tflops, bwd_time_ms, bwd_tflops, correct = profile_grouped_gemm_gmm( | ||
| B=B, | ||
| M=M, | ||
| N=N, | ||
| K=K, | ||
| dtype=dtype, | ||
| balance=balance, | ||
| num_topk=case.get("num_topk"), | ||
| ) | ||
|
|
||
| row = { | ||
| "TestID": test_id, | ||
| "Platform": platform, | ||
| "GPU": gpu_name, | ||
| "Case": case["Case"], | ||
| "B": B, | ||
| "M": M, | ||
| "N": N, | ||
| "K": K, | ||
| "Dtype": "bf16", | ||
| "Balance": "Y" if balance else "N", | ||
| "Check": "PASS" if correct else "FAIL", | ||
| "Forward Time (ms)": f"{fwd_time_ms:.2f}", | ||
| "Forward TFLOPS": f"{fwd_tflops:.2f}", | ||
| "Backward Time (ms)": f"{bwd_time_ms:.2f}", | ||
| "Backward TFLOPS": f"{bwd_tflops:.2f}", | ||
| } | ||
| rows.append(row) | ||
|
|
||
| except Exception as e: | ||
| import traceback | ||
|
|
||
| print(f"Failed: {str(e)}") | ||
| traceback.print_exc() | ||
| row = { | ||
| "TestID": test_id, | ||
| "Platform": platform, | ||
| "GPU": gpu_name, | ||
| "Case": case["Case"], | ||
| "B": B, | ||
| "M": M, | ||
| "N": N, | ||
| "K": K, | ||
| "Dtype": "bf16", | ||
| "Balance": "Y" if balance else "N", | ||
| "Check": "ERROR", | ||
| "Forward Time (ms)": "ERROR", | ||
| "Forward TFLOPS": "0.00", | ||
| "Backward Time (ms)": "ERROR", | ||
| "Backward TFLOPS": "0.00", | ||
| } | ||
| rows.append(row) | ||
|
|
||
| results = pd.DataFrame(rows) | ||
| print("\nFinal Results:") | ||
| print(tabulate(results, headers="keys", tablefmt="grid", showindex=False)) | ||
|
|
||
| avg_fwd_tflops = results["Forward TFLOPS"].astype(float).mean() | ||
| avg_bwd_tflops = results["Backward TFLOPS"].astype(float).mean() | ||
| print(f"\nAverage Forward TFLOPS: {avg_fwd_tflops:.2f}") | ||
| print(f"Average Backward TFLOPS: {avg_bwd_tflops:.2f}") | ||
|
|
||
| if output_csv: | ||
| filename = output_csv | ||
| else: | ||
| timestamp = datetime.now().strftime("%Y%m%d") | ||
| filename = f"grouped_gemm_gmm_bf16_{timestamp}_{gpu_name}.csv" | ||
| results.to_csv(filename, index=False) | ||
| print(f"Results saved to {filename}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| parser = argparse.ArgumentParser(description="Benchmark grouped_gemm (gmm) BF16 Grouped GEMM") | ||
| parser.add_argument( | ||
| "--output", | ||
| "-o", | ||
| type=str, | ||
| default=None, | ||
| help="Output CSV filename", | ||
| ) | ||
| args = parser.parse_args() | ||
| benchmark_grouped_gemm_gmm(output_csv=args.output) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This benchmark unconditionally imports grouped_gemm.ops. If the optional
grouped_gemmdependency isn't installed, the whole script will fail immediately with ImportError. Consider wrapping the import in try/except and emitting a clear install hint (or documenting this dependency alongside the benchmark).