|
| 1 | +""" |
| 2 | +xformers attention implementation for packing |
| 3 | +""" |
| 4 | + |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +import torch |
| 8 | +import xformers |
| 9 | +import xformers.ops.fmha |
| 10 | +from transformers.modeling_flash_attention_utils import ( |
| 11 | + _upad_input, |
| 12 | +) |
| 13 | + |
| 14 | +from axolotl.monkeypatch.utils import get_cu_seqlens_from_pos_ids |
| 15 | + |
| 16 | +xformers_attention = xformers.ops.fmha.memory_efficient_attention |
| 17 | + |
| 18 | + |
| 19 | +def xformers_attention_forward( |
| 20 | + module: torch.nn.Module, |
| 21 | + query: torch.Tensor, |
| 22 | + key: torch.Tensor, |
| 23 | + value: torch.Tensor, |
| 24 | + attention_mask: Optional[torch.Tensor] = None, |
| 25 | + position_ids: Optional[torch.LongTensor] = None, |
| 26 | + dropout: float = 0.0, # pylint: disable=unused-argument |
| 27 | + scaling: Optional[float] = None, # pylint: disable=unused-argument |
| 28 | + sliding_window: Optional[int] = None, # pylint: disable=unused-argument |
| 29 | + softcap: Optional[float] = None, # pylint: disable=unused-argument |
| 30 | + cu_seq_lens_q: Optional[torch.LongTensor] = None, |
| 31 | + cu_seq_lens_k: Optional[torch.LongTensor] = None, |
| 32 | + max_length_q: Optional[int] = None, |
| 33 | + max_length_k: Optional[int] = None, # pylint: disable=unused-argument |
| 34 | + **kwargs, # pylint: disable=unused-argument |
| 35 | +): |
| 36 | + # Get dimensions |
| 37 | + # query: [batch, heads, seq_len, hidden_dim] |
| 38 | + batch_size = query.size(0) |
| 39 | + query_length = query.shape[2] |
| 40 | + key_length = key.shape[2] |
| 41 | + |
| 42 | + # Default causal mask |
| 43 | + attn_bias = xformers.ops.LowerTriangularMask() |
| 44 | + |
| 45 | + # Check if we have sliding window attention |
| 46 | + has_sliding_window = sliding_window is not None and sliding_window < query_length |
| 47 | + |
| 48 | + # Transpose dimensions for xformers (Q: [b, h, s, d] -> [b, s, h, d]) |
| 49 | + query = query.transpose(1, 2) |
| 50 | + key = key.transpose(1, 2) |
| 51 | + value = value.transpose(1, 2) |
| 52 | + |
| 53 | + # Get GQA parameters |
| 54 | + num_attention_heads = module.config.num_attention_heads |
| 55 | + num_key_value_heads = module.config.num_key_value_heads |
| 56 | + head_dim = query.size(-1) |
| 57 | + is_gqa = num_attention_heads != num_key_value_heads |
| 58 | + n_groups = num_attention_heads // num_key_value_heads if is_gqa else 1 |
| 59 | + |
| 60 | + # If position_ids is provided and check all examples do not contain only 1 sequence, If tensor in increasing |
| 61 | + # then we probably have one sequence, otherwise it is packed. Additionally check we are in pre-fill/training stage. |
| 62 | + # Use `flash_attn_varlen_func` to prevent cross-example attention and also allow padding free approach |
| 63 | + if position_ids is not None and ( |
| 64 | + max_length_q is not None |
| 65 | + or (query_length != 1 and not (torch.diff(position_ids, dim=-1) >= 0).all()) |
| 66 | + ): |
| 67 | + if cu_seq_lens_q is None or cu_seq_lens_k is None: |
| 68 | + cu_seq_lens_q = get_cu_seqlens_from_pos_ids(position_ids)[0] |
| 69 | + cu_seq_lens_q = cu_seq_lens_q.squeeze() |
| 70 | + seq_lengths = cu_seq_lens_q[1:] - cu_seq_lens_q[:-1] |
| 71 | + attn_bias = ( |
| 72 | + xformers.ops.fmha.attn_bias.BlockDiagonalCausalMask.from_seqlens( |
| 73 | + q_seqlen=seq_lengths.tolist(), |
| 74 | + ) |
| 75 | + ) |
| 76 | + else: |
| 77 | + query = query.reshape(-1, query.size(-2), query.size(-1)) |
| 78 | + key = key.reshape(-1, key.size(-2), key.size(-1)) |
| 79 | + value = value.reshape(-1, value.size(-2), value.size(-1)) |
| 80 | + |
| 81 | + # Handle GQA |
| 82 | + if is_gqa: |
| 83 | + key = key.repeat_interleave(n_groups, dim=2) |
| 84 | + value = value.repeat_interleave(n_groups, dim=2) |
| 85 | + |
| 86 | + elif attention_mask is not None: |
| 87 | + query, key, value, _, cu_seq_lens, _ = _upad_input( |
| 88 | + query, key, value, attention_mask, query_length |
| 89 | + ) |
| 90 | + cu_seq_lens_q, cu_seq_lens_k = cu_seq_lens |
| 91 | + seq_lengths = [] |
| 92 | + for i in range(len(cu_seq_lens_q) - 1): |
| 93 | + seq_lengths.append(cu_seq_lens_q[i + 1] - cu_seq_lens_q[i]) |
| 94 | + attn_bias = xformers.ops.fmha.attn_bias.BlockDiagonalCausalMask.from_seqlens( |
| 95 | + q_seqlen=seq_lengths, |
| 96 | + kv_seqlen=seq_lengths, |
| 97 | + ) |
| 98 | + |
| 99 | + # Handle GQA |
| 100 | + if is_gqa: |
| 101 | + key = key.repeat_interleave(n_groups, dim=2) |
| 102 | + value = value.repeat_interleave(n_groups, dim=2) |
| 103 | + else: |
| 104 | + # Handle Group Query Attention (GQA) using view/expand approach from reference |
| 105 | + key = key.view(batch_size, key_length, num_key_value_heads, 1, head_dim) |
| 106 | + value = value.view(batch_size, key_length, num_key_value_heads, 1, head_dim) |
| 107 | + key = key.expand( |
| 108 | + batch_size, key_length, num_key_value_heads, n_groups, head_dim |
| 109 | + ) |
| 110 | + value = value.expand( |
| 111 | + batch_size, key_length, num_key_value_heads, n_groups, head_dim |
| 112 | + ) |
| 113 | + |
| 114 | + if module.training: |
| 115 | + key = key.reshape(batch_size, key_length, num_attention_heads, head_dim) |
| 116 | + value = value.reshape(batch_size, key_length, num_attention_heads, head_dim) |
| 117 | + |
| 118 | + if has_sliding_window: |
| 119 | + query = query.view( |
| 120 | + 1, batch_size * query_length, num_attention_heads, head_dim |
| 121 | + ) |
| 122 | + key = key.view( |
| 123 | + 1, batch_size * key_length, num_attention_heads, head_dim |
| 124 | + ) |
| 125 | + value = value.view( |
| 126 | + 1, batch_size * key_length, num_attention_heads, head_dim |
| 127 | + ) |
| 128 | + else: |
| 129 | + query = query.view( |
| 130 | + batch_size, query_length, num_key_value_heads, n_groups, head_dim |
| 131 | + ) |
| 132 | + |
| 133 | + # If we need a sliding window attention |
| 134 | + if has_sliding_window: |
| 135 | + query = query.view( |
| 136 | + 1, |
| 137 | + batch_size * query_length, |
| 138 | + num_key_value_heads, |
| 139 | + n_groups, |
| 140 | + head_dim, |
| 141 | + ) |
| 142 | + key = key.view( |
| 143 | + 1, batch_size * key_length, num_key_value_heads, n_groups, head_dim |
| 144 | + ) |
| 145 | + value = value.view( |
| 146 | + 1, batch_size * key_length, num_key_value_heads, n_groups, head_dim |
| 147 | + ) |
| 148 | + |
| 149 | + # Run the xformers attention |
| 150 | + attn_output = xformers_attention( |
| 151 | + query, |
| 152 | + key, |
| 153 | + value, |
| 154 | + attn_bias=attn_bias, |
| 155 | + ) |
| 156 | + |
| 157 | + attn_output = attn_output.view( |
| 158 | + batch_size, -1, attn_output.size(-2), attn_output.size(-1) |
| 159 | + ) |
| 160 | + return attn_output, None |
0 commit comments