Repository navigation
[WIP] M*G Triton group gemm for MoE training - #967
Conversation
| for expert_idx, count in enumerate(token_counts): | ||
| if count > 0: | ||
| end_idx = start_idx + count | ||
| # Take this expert's outputs and reshape to [count, hidden_dim] | ||
| expert_output = hidden_outputs[ | ||
| start_idx:end_idx, | ||
| expert_idx * self.hidden_dim : (expert_idx + 1) * self.hidden_dim, | ||
| ] | ||
| reshaped_hidden_outputs.append(expert_output) | ||
| start_idx = end_idx | ||
|
|
||
| # Concatenate all reshaped outputs | ||
| hidden_outputs = torch.cat(reshaped_hidden_outputs, dim=0) |
There was a problem hiding this comment.
Curious, what is this reshape for? Shouldn't hidden_outputs be already of shape [count, hidden_dim] ?
| if provider == "pytorch_reference": | ||
| # Warmup | ||
| torch.cuda.synchronize() | ||
| compute_reference_forward(x, w, m_sizes) | ||
| torch.cuda.synchronize() | ||
|
|
||
| # Benchmark | ||
| start_time = time.time() | ||
| for _ in range(10): # Average over 10 runs | ||
| compute_reference_forward(x, w, m_sizes) | ||
| torch.cuda.synchronize() | ||
| end_time = time.time() | ||
| else: # Optimized kernel | ||
| # Warmup | ||
| torch.cuda.synchronize() | ||
| grouped_gemm_forward(x, w, m_sizes) | ||
| torch.cuda.synchronize() | ||
|
|
||
| # Benchmark | ||
| start_time = time.time() | ||
| for _ in range(10): # Average over 10 runs | ||
| grouped_gemm_forward(x, w, m_sizes) | ||
| torch.cuda.synchronize() | ||
| end_time = time.time() |
There was a problem hiding this comment.
From this comparison it seems we are treating w as individual expert, because compute_reference_forward does so. If that's the case, should we pass a list/concat of w's to grouped_gemm_forward? Alternatively, if w is already a grouped matrix, we can ask compute_reference_forward to take a slice of w in each matmul it performs.
| # Verify that the sum of m_sizes matches M_total | ||
| sum_m_sizes = m_sizes.sum().item() | ||
| assert ( | ||
| M_total == sum_m_sizes | ||
| ), f"Sum of m_sizes ({sum_m_sizes}) must match M_total ({M_total})" |
There was a problem hiding this comment.
Shall we remove this check when in production? .item() is a CPU sync.
Also, in production, can we allow M_total to be bigger than m_sizes.sum()? The program may have a pre-allocated receive space that can be bigger than the number of tokens it receives. If the group gemm kernel performs computation based on m_sizes, we still wouldn't waste computation.
| # Process this group | ||
| n_size = N |
There was a problem hiding this comment.
Hmm, here we are treating N as individual expert size again.
|
I think I have better understanding of this PR now. We are treating the aggregated token input as m * G -- this is great, and fits the need of MoE Token Choice. But the proposed |
Yes working on exactly that atm :) |
…anual load/store all working.
…older grid stride kernels
8bf3124 to
6390a9e
Compare
kwen2501
left a comment
There was a problem hiding this comment.
Thanks for putting together the kernel!
As discussed, we have some fixes in #1045. We can land this PR first then apply the fix.
Oh lastly, let's have a follow-up PR later to clean the folder. (Or import from torchao entirely). But we can do it later.
### Summary Integrating the M*G Group GEMM kernel by @lessw2020 in #967. This kernel requires tokens for the same expert to reside together. So we need to permute the received tokens before the GEMM. We also need to make sure each token group's length (i.e. `m_sizes`) meet the alignment requirement of the Group GEMM. This requires padding some unused index (like `-1`) into the permutation indices. With this integration, we remove a few CPU sync points in the original program, for example, getting the `received` length, and slicing the chunk of tokens for each expert. And most obviously, we removed the for loop needed to perform matmul for all local experts. ### TODO The generation of permutation indices are in CPU right now. We should write a kernel for it. ### Test ``` $ torchrun --standalone --nproc-per-node 4 generate.py Combining expert weights for Group GEMM Combining expert weights for Group GEMM Combining expert weights for Group GEMM ...... Output: You are a helpful assistant. User: What is 2+2? Assistant: 2 + 2 equals 4. ```
M * G Group GEMM in Triton, which is very likely more efficient for all2all style MoE training with token choice routing. Note: credit - TMAHelper class, AutoTuning, and flat global style indexed forward kernels are derived from FBGemm: See: https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/experimental/gemm/triton_gemm Speedups for forward, BF16 for DS v3 shapes over looping matmul with PyTorch: <img width="461" alt="Screenshot 2025-03-21 at 10 01 55 AM" src="https://github.com/user-attachments/assets/ef0c9d50-b010-43ce-b529-f458a5b0ecdb" /> <img width="549" alt="flat_index_barchart_speedup" src="https://github.com/user-attachments/assets/2b4cfbc9-7443-4e6b-b2a2-51d9745b0fd0" /> and tflops: <img width="638" alt="flat_index_bf16_pytorch" src="https://github.com/user-attachments/assets/525938d3-e8e0-46b1-9123-b7f161039f7e" /> This PR has: 1 - Forward and Backward M*G Group GEmm support for BF16 / Float16 2 - FP8 is todo 3 - TMA and Autotuning are Todo. 4 - Unit Tests - forward pass added, needs backward. Forward Pass Unit Tests: ~~~ Testing BF16 M*G GroupGeMM with G=1, M=64 Testing BF16 M*G GroupGeMM with G=1, M=512 Testing BF16 M*G GroupGeMM with G=1, M=1024 Testing BF16 M*G GroupGeMM with G=4, M=64 Testing BF16 M*G GroupGeMM with G=4, M=512 Testing BF16 M*G GroupGeMM with G=4, M=1024 Testing BF16 M*G GroupGeMM with G=16, M=64 Testing BF16 M*G GroupGeMM with G=16, M=512 Testing BF16 M*G GroupGeMM with G=16, M=1024 .Testing BF16 M*G Deepseek shape: G=4, M=2048, N=4096, K=7168 Testing BF16 M*G Deepseek shape: G=4, M=2048, N=7168, K=2048 Testing BF16 M*G Deepseek shape: G=8, M=512, N=4096, K=7168 Testing BF16 M*G Deepseek shape: G=8, M=512, N=7168, K=2048 . ---------------------------------------------------------------------- Ran 2 tests in 2.622s OK ~~~ Right now I do verification with a mod of the previous fast debug script from my N*G but modified for M*G. With this I have verified forward and backward on all the main DeepSeek v3 shapes: ~~~ ===== Testing DeepSeek Config 4 ===== 2025-03-15 16:19:10,494 - INFO - G=8, M=4096, K=2048, N=7168 2025-03-15 16:19:10,508 - INFO - Input x shape: torch.Size([4096, 2048]), Weight w shape: torch.Size([7168, 2048]) 2025-03-15 16:19:10,657 - INFO - Forward result shape: torch.Size([4096, 7168]) 2025-03-15 16:19:11,013 - INFO - Largest Forward output difference: 0.0 at (np.int64(0), np.int64(0)) 2025-03-15 16:19:11,013 - INFO - Values: 73.75 vs 73.75 2025-03-15 16:19:11,028 - INFO - ✓ SUCCESS: Forward output matches PyTorch reference 2025-03-15 16:19:11,028 - INFO - Starting grouped_gemm_backward with optimized scheduling 2025-03-15 16:19:11,028 - INFO - K dimension: 2048 2025-03-15 16:19:11,150 - INFO - EVEN_K optimization enabled: True (K=2048) 2025-03-15 16:19:11,151 - INFO - Computing grad_x with optimized kernel (TMA=False) 2025-03-15 16:19:11,151 - INFO - Kernel run success: grad_x computation successful 2025-03-15 16:19:11,151 - INFO - Computing grad_w with optimized kernel 2025-03-15 16:19:11,151 - INFO - Kernel run success: grad_w computation successful 2025-03-15 16:19:11,506 - INFO - Largest grad_x difference: 0.25 at (np.int64(2), np.int64(843)) 2025-03-15 16:19:11,506 - INFO - Values: 282.25 vs 282.5 2025-03-15 16:19:11,520 - INFO - ✓ SUCCESS: grad_x matches PyTorch reference 2025-03-15 16:19:11,547 - INFO - Largest grad_w difference: 0.375 at (np.int64(707), np.int64(1871)) 2025-03-15 16:19:11,547 - INFO - Values: 186.5 vs 186.125 2025-03-15 16:19:11,561 - INFO - ✓ SUCCESS: grad_w matches PyTorch reference 2025-03-15 16:19:11,561 - INFO - ✓ SUCCESS: Config 4 passed all tests! 2025-03-15 16:19:11,561 - INFO - ===== Test Results Summary ===== 2025-03-15 16:19:11,561 - INFO - Config 1: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - Config 2: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - Config 3: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - Config 4: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,562 - INFO - DeepSeek configs tests all succeeded ~~~
### Summary Integrating the M*G Group GEMM kernel by @lessw2020 in pytorch#967. This kernel requires tokens for the same expert to reside together. So we need to permute the received tokens before the GEMM. We also need to make sure each token group's length (i.e. `m_sizes`) meet the alignment requirement of the Group GEMM. This requires padding some unused index (like `-1`) into the permutation indices. With this integration, we remove a few CPU sync points in the original program, for example, getting the `received` length, and slicing the chunk of tokens for each expert. And most obviously, we removed the for loop needed to perform matmul for all local experts. ### TODO The generation of permutation indices are in CPU right now. We should write a kernel for it. ### Test ``` $ torchrun --standalone --nproc-per-node 4 generate.py Combining expert weights for Group GEMM Combining expert weights for Group GEMM Combining expert weights for Group GEMM ...... Output: You are a helpful assistant. User: What is 2+2? Assistant: 2 + 2 equals 4. ```
M * G Group GEMM in Triton, which is very likely more efficient for all2all style MoE training with token choice routing. Note: credit - TMAHelper class, AutoTuning, and flat global style indexed forward kernels are derived from FBGemm: See: https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/experimental/gemm/triton_gemm Speedups for forward, BF16 for DS v3 shapes over looping matmul with PyTorch: <img width="461" alt="Screenshot 2025-03-21 at 10 01 55 AM" src="https://github.com/user-attachments/assets/ef0c9d50-b010-43ce-b529-f458a5b0ecdb" /> <img width="549" alt="flat_index_barchart_speedup" src="https://github.com/user-attachments/assets/2b4cfbc9-7443-4e6b-b2a2-51d9745b0fd0" /> and tflops: <img width="638" alt="flat_index_bf16_pytorch" src="https://github.com/user-attachments/assets/525938d3-e8e0-46b1-9123-b7f161039f7e" /> This PR has: 1 - Forward and Backward M*G Group GEmm support for BF16 / Float16 2 - FP8 is todo 3 - TMA and Autotuning are Todo. 4 - Unit Tests - forward pass added, needs backward. Forward Pass Unit Tests: ~~~ Testing BF16 M*G GroupGeMM with G=1, M=64 Testing BF16 M*G GroupGeMM with G=1, M=512 Testing BF16 M*G GroupGeMM with G=1, M=1024 Testing BF16 M*G GroupGeMM with G=4, M=64 Testing BF16 M*G GroupGeMM with G=4, M=512 Testing BF16 M*G GroupGeMM with G=4, M=1024 Testing BF16 M*G GroupGeMM with G=16, M=64 Testing BF16 M*G GroupGeMM with G=16, M=512 Testing BF16 M*G GroupGeMM with G=16, M=1024 .Testing BF16 M*G Deepseek shape: G=4, M=2048, N=4096, K=7168 Testing BF16 M*G Deepseek shape: G=4, M=2048, N=7168, K=2048 Testing BF16 M*G Deepseek shape: G=8, M=512, N=4096, K=7168 Testing BF16 M*G Deepseek shape: G=8, M=512, N=7168, K=2048 . ---------------------------------------------------------------------- Ran 2 tests in 2.622s OK ~~~ Right now I do verification with a mod of the previous fast debug script from my N*G but modified for M*G. With this I have verified forward and backward on all the main DeepSeek v3 shapes: ~~~ ===== Testing DeepSeek Config 4 ===== 2025-03-15 16:19:10,494 - INFO - G=8, M=4096, K=2048, N=7168 2025-03-15 16:19:10,508 - INFO - Input x shape: torch.Size([4096, 2048]), Weight w shape: torch.Size([7168, 2048]) 2025-03-15 16:19:10,657 - INFO - Forward result shape: torch.Size([4096, 7168]) 2025-03-15 16:19:11,013 - INFO - Largest Forward output difference: 0.0 at (np.int64(0), np.int64(0)) 2025-03-15 16:19:11,013 - INFO - Values: 73.75 vs 73.75 2025-03-15 16:19:11,028 - INFO - ✓ SUCCESS: Forward output matches PyTorch reference 2025-03-15 16:19:11,028 - INFO - Starting grouped_gemm_backward with optimized scheduling 2025-03-15 16:19:11,028 - INFO - K dimension: 2048 2025-03-15 16:19:11,150 - INFO - EVEN_K optimization enabled: True (K=2048) 2025-03-15 16:19:11,151 - INFO - Computing grad_x with optimized kernel (TMA=False) 2025-03-15 16:19:11,151 - INFO - Kernel run success: grad_x computation successful 2025-03-15 16:19:11,151 - INFO - Computing grad_w with optimized kernel 2025-03-15 16:19:11,151 - INFO - Kernel run success: grad_w computation successful 2025-03-15 16:19:11,506 - INFO - Largest grad_x difference: 0.25 at (np.int64(2), np.int64(843)) 2025-03-15 16:19:11,506 - INFO - Values: 282.25 vs 282.5 2025-03-15 16:19:11,520 - INFO - ✓ SUCCESS: grad_x matches PyTorch reference 2025-03-15 16:19:11,547 - INFO - Largest grad_w difference: 0.375 at (np.int64(707), np.int64(1871)) 2025-03-15 16:19:11,547 - INFO - Values: 186.5 vs 186.125 2025-03-15 16:19:11,561 - INFO - ✓ SUCCESS: grad_w matches PyTorch reference 2025-03-15 16:19:11,561 - INFO - ✓ SUCCESS: Config 4 passed all tests! 2025-03-15 16:19:11,561 - INFO - ===== Test Results Summary ===== 2025-03-15 16:19:11,561 - INFO - Config 1: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - Config 2: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - Config 3: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - Config 4: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Forward pass: ✓ PASSED 2025-03-15 16:19:11,561 - INFO - - Backward pass: ✓ PASSED 2025-03-15 16:19:11,562 - INFO - DeepSeek configs tests all succeeded ~~~
### Summary Integrating the M*G Group GEMM kernel by @lessw2020 in pytorch#967. This kernel requires tokens for the same expert to reside together. So we need to permute the received tokens before the GEMM. We also need to make sure each token group's length (i.e. `m_sizes`) meet the alignment requirement of the Group GEMM. This requires padding some unused index (like `-1`) into the permutation indices. With this integration, we remove a few CPU sync points in the original program, for example, getting the `received` length, and slicing the chunk of tokens for each expert. And most obviously, we removed the for loop needed to perform matmul for all local experts. ### TODO The generation of permutation indices are in CPU right now. We should write a kernel for it. ### Test ``` $ torchrun --standalone --nproc-per-node 4 generate.py Combining expert weights for Group GEMM Combining expert weights for Group GEMM Combining expert weights for Group GEMM ...... Output: You are a helpful assistant. User: What is 2+2? Assistant: 2 + 2 equals 4. ```
M * G Group GEMM in Triton, which is very likely more efficient for all2all style MoE training with token choice routing.
Note: credit - TMAHelper class, AutoTuning, and flat global style indexed forward kernels are derived from FBGemm:
See: https://github.com/pytorch/FBGEMM/blob/main/fbgemm_gpu/experimental/gemm/triton_gemm
Speedups for forward, BF16 for DS v3 shapes over looping matmul with PyTorch:

and tflops:

This PR has:
1 - Forward and Backward M*G Group GEmm support for BF16 / Float16
2 - FP8 is todo
3 - TMA and Autotuning are Todo.
4 - Unit Tests - forward pass added, needs backward.
Forward Pass Unit Tests:
Right now I do verification with a mod of the previous fast debug script from my NG but modified for MG. With this I have verified forward and backward on all the main DeepSeek v3 shapes: