-
Notifications
You must be signed in to change notification settings - Fork 31.9k
Add padding-free to bamba #35861
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
ArthurZucker
merged 13 commits into
huggingface:main
from
garrett361:bamba-hf-padding-free-pr
May 20, 2025
Merged
Add padding-free to bamba #35861
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
810e69a
add seq_idx and fa kwargs
garrett361 fc16221
update tests
garrett361 1293027
docs and grad ckpt support
garrett361 e9fd986
fmt
garrett361 a8a953d
better names
garrett361 ea6b8bf
test_raise_missing_padding_free_kwarg_errs
garrett361 f978ca2
+ seq_idx in doc strings
garrett361 2350e54
padding free training docs
garrett361 b73c1a1
add link to pr plots
garrett361 a6627e0
raise err on attn_mask with padding free
garrett361 a47588a
rm raising missing padding free err test
garrett361 b59e5c9
BambaFlashAttentionKwargs
garrett361 289d204
run modular util for modular_granitemoehybrid.py
garrett361 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
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 | ||
|---|---|---|---|---|
|
|
@@ -19,7 +19,8 @@ | |||
| # limitations under the License. | ||||
| """PyTorch Bamba model.""" | ||||
|
|
||||
| from typing import Optional, Tuple, Union | ||||
| from functools import partial | ||||
| from typing import Optional, Tuple, TypedDict, Union | ||||
|
|
||||
| import torch | ||||
| import torch.utils.checkpoint | ||||
|
|
@@ -46,7 +47,12 @@ | |||
| from ...modeling_attn_mask_utils import AttentionMaskConverter | ||||
| from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast | ||||
| from ...modeling_utils import PreTrainedModel | ||||
| from ...utils import auto_docstring, can_return_tuple, logging | ||||
| from ...processing_utils import Unpack | ||||
| from ...utils import ( | ||||
| auto_docstring, | ||||
| can_return_tuple, | ||||
| logging, | ||||
| ) | ||||
| from ...utils.import_utils import is_causal_conv1d_available, is_flash_attn_2_available, is_mamba_2_ssm_available | ||||
| from .configuration_bamba import BambaConfig | ||||
|
|
||||
|
|
@@ -71,6 +77,31 @@ | |||
| logger = logging.get_logger(__name__) | ||||
|
|
||||
|
|
||||
| class BambaFlashAttentionKwargs(TypedDict, total=False): | ||||
| """ | ||||
| Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage. | ||||
| Use cases include padding-free training and fewer `torch.compile` graph breaks. | ||||
|
|
||||
| Attributes: | ||||
| cu_seq_lens_q (`torch.LongTensor`) | ||||
| Gets cumulative sequence length for query state. | ||||
| cu_seq_lens_k (`torch.LongTensor`) | ||||
| Gets cumulative sequence length for key state. | ||||
| max_length_q (`int`): | ||||
| Maximum sequence length for query state. | ||||
| max_length_k (`int`): | ||||
| Maximum sequence length for key state. | ||||
| seq_idx (`torch.IntTensor): | ||||
| Index of each packed sequence. | ||||
| """ | ||||
|
|
||||
| cu_seq_lens_q: torch.LongTensor | ||||
| cu_seq_lens_k: torch.LongTensor | ||||
| max_length_q: int | ||||
| max_length_k: int | ||||
| seq_idx: torch.IntTensor | ||||
|
|
||||
|
|
||||
| # Adapted from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache for the v2 mixer | ||||
| class HybridMambaAttentionDynamicCache(modeling_jamba.HybridMambaAttentionDynamicCache): | ||||
| """ | ||||
|
|
@@ -278,6 +309,7 @@ def cuda_kernels_forward( | |||
| cache_params: Optional[HybridMambaAttentionDynamicCache] = None, | ||||
| cache_position: Optional[torch.LongTensor] = None, | ||||
| attention_mask: Optional[torch.Tensor] = None, | ||||
| seq_idx: Optional[torch.IntTensor] = None, | ||||
| ): | ||||
| # 1. Gated MLP's linear projection | ||||
| hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask) | ||||
|
|
@@ -360,7 +392,7 @@ def cuda_kernels_forward( | |||
| A, | ||||
| D=self.D, | ||||
| chunk_size=self.chunk_size, | ||||
| seq_idx=None, # was seq_idx | ||||
| seq_idx=seq_idx, | ||||
| activation=self.activation, | ||||
| rmsnorm_weight=self.norm.weight, | ||||
| rmsnorm_eps=self.norm.variance_epsilon, | ||||
|
|
@@ -401,6 +433,7 @@ def cuda_kernels_forward( | |||
| weight=self.conv1d.weight.squeeze(1), | ||||
| bias=self.conv1d.bias, | ||||
| activation=self.activation, | ||||
| seq_idx=seq_idx, | ||||
| ).transpose(1, 2) | ||||
|
|
||||
| hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask) | ||||
|
|
@@ -420,7 +453,7 @@ def cuda_kernels_forward( | |||
| chunk_size=self.chunk_size, | ||||
| D=self.D, | ||||
| z=None, | ||||
| seq_idx=None, | ||||
| seq_idx=seq_idx, | ||||
| return_final_states=True, | ||||
| dt_bias=self.dt_bias, | ||||
| dt_softplus=True, | ||||
|
|
@@ -654,9 +687,15 @@ def forward( | |||
| cache_params: Optional[HybridMambaAttentionDynamicCache] = None, | ||||
| cache_position: Optional[torch.LongTensor] = None, | ||||
| attention_mask: Optional[torch.Tensor] = None, | ||||
| seq_idx: Optional[torch.IntTensor] = None, | ||||
| **kwargs, | ||||
| ): | ||||
| if is_fast_path_available and "cuda" in self.in_proj.weight.device.type: | ||||
| return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask) | ||||
| return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask, seq_idx) | ||||
| if seq_idx is not None: | ||||
| raise NotImplementedError( | ||||
| "`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`" | ||||
| ) | ||||
| dtype = hidden_states.dtype | ||||
| if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1: | ||||
| # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66 | ||||
|
|
@@ -701,7 +740,7 @@ def forward( | |||
| use_cache: Optional[bool] = False, | ||||
| cache_position: Optional[torch.LongTensor] = None, | ||||
| position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC | ||||
| **kwargs, | ||||
| **kwargs: Unpack[BambaFlashAttentionKwargs], | ||||
| ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: | ||||
| """ | ||||
| Args: | ||||
|
|
@@ -721,8 +760,8 @@ def forward( | |||
| Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`, | ||||
| with `head_dim` being the embedding dimension of each attention head. | ||||
| kwargs (`dict`, *optional*): | ||||
| Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code | ||||
| into the model | ||||
| Arbitrary kwargs. Can be used to provide `BambaFlashAttentionKwargs` for | ||||
| padding-free training and/or improve torch.compile performance. | ||||
| """ | ||||
|
|
||||
| residual = hidden_states | ||||
|
|
@@ -736,6 +775,7 @@ def forward( | |||
| cache_params=past_key_value, | ||||
| cache_position=cache_position, | ||||
| attention_mask=attention_mask, | ||||
| **kwargs, | ||||
| ) | ||||
| self_attn_weights = None | ||||
| elif self.layer_type == "attention": | ||||
|
|
@@ -838,7 +878,7 @@ def forward( | |||
| output_attentions: Optional[bool] = None, | ||||
| output_hidden_states: Optional[bool] = None, | ||||
| cache_position: Optional[torch.LongTensor] = None, | ||||
| **kwargs, # NOOP kwargs, for now | ||||
| **kwargs: Unpack[BambaFlashAttentionKwargs], | ||||
| ) -> BaseModelOutputWithPast: | ||||
| output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions | ||||
| output_hidden_states = ( | ||||
|
|
@@ -890,7 +930,7 @@ def forward( | |||
|
|
||||
| if self.gradient_checkpointing and self.training: | ||||
| layer_outputs = self._gradient_checkpointing_func( | ||||
| decoder_layer.__call__, | ||||
| partial(decoder_layer.__call__, **kwargs), | ||||
| hidden_states, | ||||
| layer_mask, | ||||
| position_ids, | ||||
|
|
@@ -910,6 +950,7 @@ def forward( | |||
| use_cache=use_cache, | ||||
| cache_position=cache_position, | ||||
| position_embeddings=position_embeddings, | ||||
| **kwargs, | ||||
|
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.
Suggested change
Unnecessary? |
||||
| ) | ||||
|
|
||||
| hidden_states = layer_outputs[0] | ||||
|
|
||||
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.
prob unpack here
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.
Unpackthe**kwargs? These**kwargsare just a catch-all for the non-seq_idxkwargs inBambaFlashAttentionKwargsbecause theBambaMixerlayer only usesseq_idx, whileBambaAttentionuses the rest.Do you want me to do
**kwargs: Unpack[FlashAttentionKwargs]even though the kwargs are unused?