-
Notifications
You must be signed in to change notification settings - Fork 806
Bitmap topk #3009
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
Merged
Merged
Bitmap topk #3009
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
4071d8d
initial impl
tdophung d033dcd
Register XLA FFI AttrDecoding for JAXX_Routing_Map_Format
tdophung b2928ac
Merge branch 'NVIDIA:main' into bitmap_topk
tdophung 889c161
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] aaee513
add plumbing from pytorch side, change all internal functions to usin…
tdophung 2769576
Merge branch 'main' into bitmap_topk
tdophung 600a30f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 22ae793
Merge branch 'main' into bitmap_topk
tdophung ba78cf0
address all comments
tdophung 4ff6844
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] af30717
Merge branch 'main' into bitmap_topk
tdophung 5572c97
[PyTorch] Address PR #3009 review: remove .view() calls, int routing_…
tdophung 94ef4fa
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 5057f81
[PyTorch] Fix routing_map_format validator: pybind11 enum is not an i…
tdophung 091a252
[PyTorch][JAX][Common] Clean up review-style comments in router code
tdophung b2589f5
remove remaining useless comments
tdophung 32a2ecf
Merge remote-tracking branch 'nvidia/main' into bitmap_topk
tdophung 5bf2aea
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 51c832b
small comment change
tdophung 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
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
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 |
|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |
| import torch | ||
| from typing import Optional | ||
| from transformer_engine.pytorch.router import ( | ||
| RoutingMapFormat, | ||
| fused_topk_with_score_function, | ||
| fused_compute_score_for_moe_aux_loss, | ||
| fused_moe_aux_loss, | ||
|
|
@@ -458,6 +459,145 @@ def test_fused_moe_aux_loss(dtype, num_tokens, num_experts, topk): | |
| torch.testing.assert_close(probs.grad, probs_clone.grad, atol=atol, rtol=rtol) | ||
|
|
||
|
|
||
| # ============================================================================= | ||
| # Test: routing_map BITMAP_U8 vs BYTEMAP parity (fwd + bwd) | ||
| # Mirrors tests/jax/test_fused_router.py::test_topk_bitmap_vs_bytemap. | ||
| # ============================================================================= | ||
|
|
||
|
|
||
| def _bytemap_to_bitmap_u8(bytemap: torch.Tensor) -> torch.Tensor: | ||
| """Reference packer: bool[T, E] -> uint8[T, ceil(E/8)] LSB-first. | ||
|
|
||
| Matches numpy.packbits(..., bitorder='little'), which is what the JAX-side | ||
| parity test uses. | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The comment about JAX is not needed. |
||
| """ | ||
| flat = bytemap.to(torch.uint8).cpu().numpy() | ||
| import numpy as np | ||
|
|
||
| return torch.from_numpy(np.packbits(flat, axis=-1, bitorder="little")).to(bytemap.device) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("dtype", [torch.float32]) | ||
| @pytest.mark.parametrize( | ||
| "num_tokens,num_experts,topk", | ||
| [(128, 32, 4), (256, 128, 8), (256, 130, 8), (128, 1024, 16)], | ||
| ) | ||
| @pytest.mark.parametrize("score_function", ["softmax", "sigmoid", "sqrtsoftplus"]) | ||
| def test_topk_bitmap_vs_bytemap(dtype, num_tokens, num_experts, topk, score_function): | ||
| """fused_topk_with_score_function should produce identical probs and an | ||
| LSB-packed bitmap routing_map when routing_map_format=BITMAP_U8, and | ||
| backward gradients should match the bytemap path exactly.""" | ||
| if topk >= num_experts: | ||
| pytest.skip(f"topk ({topk}) >= num_experts ({num_experts})") | ||
| if score_function in ("sigmoid", "sqrtsoftplus"): | ||
| offset = torch.arange(-num_tokens // 2, num_tokens // 2, dtype=dtype, device="cuda") * 1e-4 | ||
| logits = ( | ||
| torch.arange(-num_experts // 2, num_experts // 2, device="cuda", dtype=dtype) * 1e-2 | ||
| ) | ||
| logits = logits.unsqueeze(0).repeat(num_tokens, 1) + offset.unsqueeze(1) | ||
| else: | ||
| logits = ( | ||
| torch.arange( | ||
| -num_tokens * num_experts // 2, | ||
| num_tokens * num_experts // 2, | ||
| device="cuda", | ||
| dtype=dtype, | ||
| ) | ||
| * 1e-4 | ||
| ) | ||
| logits = logits.view(num_tokens, num_experts) | ||
|
|
||
| logits_byte = logits.detach().clone().requires_grad_(True) | ||
| logits_bit = logits.detach().clone().requires_grad_(True) | ||
|
|
||
| probs_byte, routing_map_byte = fused_topk_with_score_function( | ||
| logits=logits_byte, | ||
| topk=topk, | ||
| use_pre_softmax=False, | ||
| num_groups=None, | ||
| group_topk=None, | ||
| scaling_factor=None, | ||
| score_function=score_function, | ||
| expert_bias=None, | ||
| routing_map_format=RoutingMapFormat.BYTEMAP, | ||
| ) | ||
| probs_bit, routing_map_bit = fused_topk_with_score_function( | ||
| logits=logits_bit, | ||
| topk=topk, | ||
| use_pre_softmax=False, | ||
| num_groups=None, | ||
| group_topk=None, | ||
| scaling_factor=None, | ||
| score_function=score_function, | ||
| expert_bias=None, | ||
| routing_map_format=RoutingMapFormat.BITMAP_U8, | ||
| ) | ||
|
|
||
| assert probs_byte.dtype == probs_bit.dtype | ||
| torch.testing.assert_close(probs_byte, probs_bit, atol=0.0, rtol=0.0) | ||
|
|
||
| expected_shape = (num_tokens, (num_experts + 7) // 8) | ||
| assert ( | ||
| routing_map_bit.shape == expected_shape | ||
| ), f"Bitmap shape {tuple(routing_map_bit.shape)} != {expected_shape}" | ||
| assert routing_map_bit.dtype == torch.uint8 | ||
| assert routing_map_byte.dtype == torch.bool | ||
|
|
||
| packed_expected = _bytemap_to_bitmap_u8(routing_map_byte) | ||
| torch.testing.assert_close(routing_map_bit, packed_expected, atol=0, rtol=0) | ||
|
|
||
| # Backward parity: grad of probs.sum() must be bit-identical across formats. | ||
| probs_byte.sum().backward() | ||
| probs_bit.sum().backward() | ||
| torch.testing.assert_close(logits_byte.grad, logits_bit.grad, atol=0.0, rtol=0.0) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("dtype", [torch.float32]) | ||
| @pytest.mark.parametrize( | ||
| "num_tokens,num_experts,topk", | ||
| [(128, 32, 4), (256, 128, 8), (256, 130, 8)], | ||
| ) | ||
| @pytest.mark.parametrize("score_function", ["softmax", "sigmoid", "sqrtsoftplus"]) | ||
| def test_score_for_aux_loss_bitmap_vs_bytemap(dtype, num_tokens, num_experts, topk, score_function): | ||
| """fused_compute_score_for_moe_aux_loss: bitmap routing_map must equal | ||
| LSB-packed bytemap; scores must be bit-identical across formats.""" | ||
| if topk >= num_experts: | ||
| pytest.skip(f"topk ({topk}) >= num_experts ({num_experts})") | ||
| offset = torch.arange(-num_tokens // 2, num_tokens // 2, dtype=dtype, device="cuda") * 1e-4 | ||
| logits = torch.arange(-num_experts // 2, num_experts // 2, device="cuda", dtype=dtype) * 1e-2 | ||
| logits = logits.unsqueeze(0).repeat(num_tokens, 1) + offset.unsqueeze(1) | ||
|
|
||
| logits_byte = logits.detach().clone().requires_grad_(True) | ||
| logits_bit = logits.detach().clone().requires_grad_(True) | ||
|
|
||
| routing_map_byte, scores_byte = fused_compute_score_for_moe_aux_loss( | ||
| logits=logits_byte, | ||
| topk=topk, | ||
| score_function=score_function, | ||
| routing_map_format="bytemap", | ||
| ) | ||
| routing_map_bit, scores_bit = fused_compute_score_for_moe_aux_loss( | ||
| logits=logits_bit, | ||
| topk=topk, | ||
| score_function=score_function, | ||
| routing_map_format="bitmap_u8", | ||
| ) | ||
|
|
||
| torch.testing.assert_close(scores_byte, scores_bit, atol=0.0, rtol=0.0) | ||
|
|
||
| expected_shape = (num_tokens, (num_experts + 7) // 8) | ||
| assert routing_map_bit.shape == expected_shape | ||
| assert routing_map_bit.dtype == torch.uint8 | ||
| assert routing_map_byte.dtype == torch.bool | ||
| packed_expected = _bytemap_to_bitmap_u8(routing_map_byte) | ||
| torch.testing.assert_close(routing_map_bit, packed_expected, atol=0, rtol=0) | ||
|
|
||
| # Backward parity through scores. | ||
| scores_byte.sum().backward() | ||
| scores_bit.sum().backward() | ||
| torch.testing.assert_close(logits_byte.grad, logits_bit.grad, atol=0.0, rtol=0.0) | ||
|
|
||
|
|
||
| def profile_topk_softmax( | ||
| dtype, | ||
| num_tokens, | ||
|
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.