-
Notifications
You must be signed in to change notification settings - Fork 4k
Fuse per-sequence AlltoAll into a unified one in GDN forward #4913
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
xuantengh
wants to merge
9
commits into
NVIDIA:main
Choose a base branch
from
xuantengh:xuantengh/gdn_a2a
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.
+300
−85
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
c8a4148
refactor a2a op to reuse existing code from mapping.py
xuantengh 330ac30
fuse per-seq a2a into a unified one
xuantengh 3194659
use qwen3 model config for testing
xuantengh 670bae8
add head perm
xuantengh da59a45
fix test
xuantengh 2c77843
move unused function to test file
xuantengh 9e83836
update comments
xuantengh 155ee8e
move head_perm to forward
xuantengh a0044a5
add lru cache
xuantengh 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,7 @@ | |
|
|
||
| import logging | ||
| from dataclasses import dataclass, replace | ||
| from functools import lru_cache | ||
| from typing import List, Optional, Tuple, Union | ||
|
|
||
| import torch | ||
|
|
@@ -342,40 +343,40 @@ def forward( | |
| nvtx_range_pop(suffix="in_proj") | ||
|
|
||
| # CP All to All: CP to HP | ||
| if packed_seq_params is not None and packed_seq_params.qkv_format == 'thd': | ||
| unpacked_qkvzba = _unpack_sequence(qkvzba, cu_seqlens_q // self.cp_size, dim=0) | ||
| outputs = [] | ||
| for qkvzba_i in unpacked_qkvzba: | ||
| qkvzba_i = tensor_a2a_cp2hp( | ||
| qkvzba_i, | ||
| seq_dim=0, | ||
| head_dim=-1, | ||
| cp_group=self.pg_collection.cp, | ||
| split_sections=[ | ||
| self.qk_dim_local_tp, | ||
| self.qk_dim_local_tp, | ||
| self.v_dim_local_tp, | ||
| self.v_dim_local_tp, | ||
| self.num_value_heads // self.tp_size, | ||
| self.num_value_heads // self.tp_size, | ||
| ], | ||
| ) | ||
| outputs.append(qkvzba_i) | ||
| qkvzba = torch.cat(outputs, dim=0) | ||
| else: | ||
| qkvzba = tensor_a2a_cp2hp( | ||
| qkvzba, | ||
| seq_dim=0, | ||
| head_dim=-1, | ||
| cp_group=self.pg_collection.cp, | ||
| split_sections=[ | ||
| if self.cp_size > 1: | ||
| # # Pre-permute head dim so a single unsectioned a2a is equivalent to per-section a2a. | ||
| head_perm = _build_head_perm_for_split_sections( | ||
| ( | ||
| self.qk_dim_local_tp, | ||
| self.qk_dim_local_tp, | ||
| self.v_dim_local_tp, | ||
| self.v_dim_local_tp, | ||
| self.num_value_heads // self.tp_size, | ||
| self.num_value_heads // self.tp_size, | ||
| ], | ||
| ), | ||
| self.pg_collection.cp.size(), | ||
| torch.cuda.current_device(), | ||
| ) | ||
| qkvzba = qkvzba.index_select(-1, head_perm) | ||
| if packed_seq_params is not None and packed_seq_params.qkv_format == 'thd': | ||
| qkvzba = tensor_a2a_cp2hp( | ||
| qkvzba, | ||
| seq_dim=0, | ||
| head_dim=-1, | ||
| cp_group=self.pg_collection.cp, | ||
| undo_attention_load_balancing=False, | ||
| ) | ||
| if self.cp_size > 1: | ||
| # Permute at the seq dim so that a single unsectioned a2a | ||
| # is equivalent to per-sequence a2a. | ||
| # This also folds the ``_undo_attention_load_balancing`` step. | ||
| thd_cp_a2a_idx, thd_cp_a2a_inv = _build_thd_cp_a2a_perm( | ||
| cu_seqlens_q, self.cp_size, seq_len | ||
| ) | ||
| qkvzba = qkvzba.index_select(0, thd_cp_a2a_idx) | ||
| else: | ||
| qkvzba = tensor_a2a_cp2hp( | ||
| qkvzba, seq_dim=0, head_dim=-1, cp_group=self.pg_collection.cp | ||
| ) | ||
|
|
||
| # Transpose: s b x --> b s x | ||
|
|
@@ -489,14 +490,15 @@ def forward( | |
|
|
||
| # CP all to all: HP to CP | ||
| if packed_seq_params is not None and packed_seq_params.qkv_format == 'thd': | ||
| unpacked_norm_out = _unpack_sequence(norm_out, cu_seqlens_q, dim=0) | ||
| outputs = [] | ||
| for norm_out_i in unpacked_norm_out: | ||
| norm_out_i = tensor_a2a_hp2cp( | ||
| norm_out_i, seq_dim=0, head_dim=-1, cp_group=self.pg_collection.cp | ||
| ) | ||
| outputs.append(norm_out_i) | ||
| norm_out = torch.cat(outputs, dim=0) | ||
| if self.cp_size > 1: | ||
| norm_out = norm_out.index_select(0, thd_cp_a2a_inv) | ||
| norm_out = tensor_a2a_hp2cp( | ||
| norm_out, | ||
| seq_dim=0, | ||
| head_dim=-1, | ||
| cp_group=self.pg_collection.cp, | ||
| redo_attention_load_balancing=False, | ||
| ) | ||
| else: | ||
| norm_out = tensor_a2a_hp2cp( | ||
| norm_out, seq_dim=0, head_dim=-1, cp_group=self.pg_collection.cp | ||
|
|
@@ -574,7 +576,7 @@ def _compute_g_and_beta(self, A_log_local_cp, dt_bias_local_cp, alpha, beta): | |
|
|
||
| def _resolve_cu_seqlens( | ||
| self, cu_seqlens_padded, cu_seqlens_actual, total_seq_len, name, cp_size: int = 1 | ||
| ): | ||
| ) -> torch.Tensor: | ||
| """Resolve cu_seqlens for packed sequence all-to-all, handling alignment padding.""" | ||
| if cu_seqlens_padded is not None: | ||
| cu_seqlens = cu_seqlens_padded | ||
|
|
@@ -696,16 +698,62 @@ def _backward_out_proj(self): | |
| self.out_proj.backward_dw() | ||
|
|
||
|
|
||
| def _unpack_sequence(x, cu_seqlens, dim=1): | ||
| unpacked_x = [] | ||
| cu_seqlens_list = cu_seqlens.tolist() | ||
| num_seqs = len(cu_seqlens_list) - 1 | ||
| for i in range(num_seqs): | ||
| idx_start = cu_seqlens_list[i] | ||
| idx_end = cu_seqlens_list[i + 1] | ||
| chunked_index = [slice(None)] * dim + [slice(idx_start, idx_end)] | ||
| unpacked_x.append(x[tuple(chunked_index)]) | ||
| return unpacked_x | ||
| def _build_thd_cp_a2a_perm( | ||
| cu_seqlens: torch.Tensor, cp_size: int, t_global: int | ||
| ) -> Tuple[torch.Tensor, torch.Tensor]: | ||
| cu = cu_seqlens.to(dtype=torch.long) | ||
| t_local = t_global // cp_size | ||
|
|
||
| positions = torch.arange(t_global, device=cu.device) | ||
| seq_idx = torch.bucketize(positions, cu[1:], right=True) | ||
| seq_lens = torch.diff(cu) | ||
| halves = seq_lens // (2 * cp_size) # per-sequence half-chunk size | ||
| local_starts = cu[:-1] // cp_size | ||
|
xuantengh marked this conversation as resolved.
|
||
| global_starts = cu[:-1] | ||
|
|
||
| half_i = halves[seq_idx] | ||
| pos_in_seq = positions - global_starts[seq_idx] | ||
|
|
||
| natural_chunk = pos_in_seq // half_i # in [0, 2*cp) | ||
| offset = pos_in_seq - natural_chunk * half_i | ||
|
|
||
| # Invert the ordering produced by `_undo_attention_load_balancing`: | ||
| # natural_chunk < cp: load_balanced = 2 * natural_chunk | ||
| # natural_chunk >= cp: load_balanced = 4*cp - 2*natural_chunk - 1 | ||
| lb_chunk = torch.where( | ||
| natural_chunk < cp_size, 2 * natural_chunk, 4 * cp_size - 2 * natural_chunk - 1 | ||
| ) | ||
|
|
||
| # In the per-sequence load-balanced layout each rank owns load-balanced | ||
| # chunks (2r) and (2r+1), in that order, of every sequence. | ||
| rank = lb_chunk // 2 | ||
| half_within_rank = lb_chunk - 2 * rank | ||
| k = half_within_rank * half_i + offset | ||
|
|
||
| idx = rank * t_local + local_starts[seq_idx] + k | ||
|
|
||
| inv = torch.empty_like(idx) | ||
| inv[idx] = positions | ||
|
|
||
| return idx, inv | ||
|
|
||
|
|
||
| @lru_cache(maxsize=8) | ||
| def _build_head_perm_for_split_sections( | ||
|
xuantengh marked this conversation as resolved.
|
||
| split_sections: Tuple[int], cp_size: int, device: torch.device | ||
|
Contributor
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. Same nit as before, but also, the type should be |
||
| ) -> torch.Tensor: | ||
| assert all( | ||
| s % cp_size == 0 for s in split_sections | ||
| ), f"split_sections {split_sections} must be divisible by cp_size {cp_size} for GDN" | ||
| offset = 0 | ||
| parts = [] | ||
| for s in split_sections: | ||
| parts.append( | ||
| torch.arange(offset, offset + s, device=device, dtype=torch.long).view(cp_size, -1) | ||
| ) | ||
| offset += s | ||
|
|
||
| return torch.cat(parts, dim=-1).view(-1) | ||
|
|
||
|
|
||
| #################### | ||
|
|
||
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.
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.
Nit: let's move toward new-style type specification using built-in
tupleinstead oftyping.Tuple.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.
Should I convert all type annotation (
Optional,Tuple, etc.) in this file to modern one?