winglian commited on
Commit
6cb2310
1 Parent(s): c5b0af1

copy xformers attn from ooba since we removed dep on alpaca_lora_4bit

Browse files
src/axolotl/monkeypatch/llama_attn_hijack_xformers.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ Directly copied the code from https://raw.githubusercontent.com/oobabooga/text-generation-webui/main/modules/llama_attn_hijack.py and made some adjustments
3
+ '''
4
+
5
+ import logging
6
+ import math
7
+ from typing import Optional, Tuple
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import transformers.models.llama.modeling_llama
12
+
13
+ try:
14
+ import xformers.ops
15
+ except Exception:
16
+ logging.error("xformers not found! Please install it before trying to use it.")
17
+
18
+
19
+ def hijack_llama_attention():
20
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = xformers_forward
21
+ logging.info("Replaced attention with xformers_attention")
22
+
23
+
24
+ def hijack_llama_sdp_attention():
25
+ transformers.models.llama.modeling_llama.LlamaAttention.forward = sdp_attention_forward
26
+ logging.info("Replaced attention with sdp_attention")
27
+
28
+
29
+ def xformers_forward(
30
+ self,
31
+ hidden_states: torch.Tensor,
32
+ attention_mask: Optional[torch.Tensor] = None,
33
+ position_ids: Optional[torch.LongTensor] = None,
34
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
35
+ output_attentions: bool = False,
36
+ use_cache: bool = False,
37
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
38
+ bsz, q_len, _ = hidden_states.size()
39
+
40
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
41
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
42
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
43
+
44
+ kv_seq_len = key_states.shape[-2]
45
+ if past_key_value is not None:
46
+ kv_seq_len += past_key_value[0].shape[-2]
47
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
48
+ query_states, key_states = transformers.models.llama.modeling_llama.apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
49
+ # [bsz, nh, t, hd]
50
+
51
+ if past_key_value is not None:
52
+ # reuse k, v, self_attention
53
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
54
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
55
+
56
+ past_key_value = (key_states, value_states) if use_cache else None
57
+
58
+ # We only apply xformers optimizations if we don't need to output the whole attention matrix
59
+ if not output_attentions:
60
+ query_states = query_states.transpose(1, 2)
61
+ key_states = key_states.transpose(1, 2)
62
+ value_states = value_states.transpose(1, 2)
63
+
64
+ # This is a nasty hack. We know attention_mask in transformers is either LowerTriangular or all Zeros.
65
+ # We therefore check if one element in the upper triangular portion is zero. If it is, then the mask is all zeros.
66
+ if attention_mask is None or attention_mask[0, 0, 0, 1] == 0:
67
+ # input and output should be of form (bsz, q_len, num_heads, head_dim)
68
+ attn_output = xformers.ops.memory_efficient_attention(query_states, key_states, value_states, attn_bias=None)
69
+ else:
70
+ # input and output should be of form (bsz, q_len, num_heads, head_dim)
71
+ attn_output = xformers.ops.memory_efficient_attention(query_states, key_states, value_states, attn_bias=xformers.ops.LowerTriangularMask())
72
+ attn_weights = None
73
+ else:
74
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
75
+
76
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
77
+ raise ValueError(
78
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
79
+ f" {attn_weights.size()}"
80
+ )
81
+
82
+ if attention_mask is not None:
83
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
84
+ raise ValueError(
85
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
86
+ )
87
+ attn_weights = attn_weights + attention_mask
88
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
89
+
90
+ # upcast attention to fp32
91
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
92
+ attn_output = torch.matmul(attn_weights, value_states)
93
+
94
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
95
+ raise ValueError(
96
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
97
+ f" {attn_output.size()}"
98
+ )
99
+
100
+ attn_output = attn_output.transpose(1, 2)
101
+
102
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
103
+ attn_output = self.o_proj(attn_output)
104
+ return attn_output, attn_weights, past_key_value
105
+
106
+
107
+ def sdp_attention_forward(
108
+ self,
109
+ hidden_states: torch.Tensor,
110
+ attention_mask: Optional[torch.Tensor] = None,
111
+ position_ids: Optional[torch.LongTensor] = None,
112
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
113
+ output_attentions: bool = False,
114
+ use_cache: bool = False,
115
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
116
+ bsz, q_len, _ = hidden_states.size()
117
+
118
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
119
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
120
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
121
+
122
+ kv_seq_len = key_states.shape[-2]
123
+ if past_key_value is not None:
124
+ kv_seq_len += past_key_value[0].shape[-2]
125
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
126
+ query_states, key_states = transformers.models.llama.modeling_llama.apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
127
+ # [bsz, nh, t, hd]
128
+
129
+ if past_key_value is not None:
130
+ # reuse k, v, self_attention
131
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
132
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
133
+
134
+ past_key_value = (key_states, value_states) if use_cache else None
135
+
136
+ # We only apply sdp attention if we don't need to output the whole attention matrix
137
+ if not output_attentions:
138
+ attn_output = torch.nn.functional.scaled_dot_product_attention(query_states, key_states, value_states, attn_mask=attention_mask, is_causal=False)
139
+ attn_weights = None
140
+ else:
141
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
142
+
143
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
144
+ raise ValueError(
145
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
146
+ f" {attn_weights.size()}"
147
+ )
148
+
149
+ if attention_mask is not None:
150
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
151
+ raise ValueError(
152
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
153
+ )
154
+ attn_weights = attn_weights + attention_mask
155
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
156
+
157
+ # upcast attention to fp32
158
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
159
+ attn_output = torch.matmul(attn_weights, value_states)
160
+
161
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
162
+ raise ValueError(
163
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
164
+ f" {attn_output.size()}"
165
+ )
166
+
167
+ attn_output = attn_output.transpose(1, 2)
168
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
169
+
170
+ attn_output = self.o_proj(attn_output)
171
+
172
+ return attn_output, attn_weights, past_key_value
src/axolotl/utils/models.py CHANGED
@@ -97,12 +97,19 @@ def load_model(
97
  logging.info("patching with flash attention")
98
  replace_llama_attn_with_flash_attn()
99
  elif is_llama_derived_model and cfg.xformers_attention:
100
- from alpaca_lora_4bit.monkeypatch.llama_attn_hijack_xformers import (
101
  hijack_llama_attention,
102
  )
103
 
104
  logging.info("patching with xformers attention")
105
  hijack_llama_attention()
 
 
 
 
 
 
 
106
 
107
  if cfg.bf16:
108
  torch_dtype = torch.bfloat16
 
97
  logging.info("patching with flash attention")
98
  replace_llama_attn_with_flash_attn()
99
  elif is_llama_derived_model and cfg.xformers_attention:
100
+ from axolotl.monkeypatch.llama_attn_hijack_xformers import (
101
  hijack_llama_attention,
102
  )
103
 
104
  logging.info("patching with xformers attention")
105
  hijack_llama_attention()
106
+ elif is_llama_derived_model and cfg.sdp_attention:
107
+ from axolotl.monkeypatch.llama_attn_hijack_xformers import (
108
+ hijack_llama_sdp_attention,
109
+ )
110
+
111
+ logging.info("patching with sdp attention")
112
+ hijack_llama_sdp_attention()
113
 
114
  if cfg.bf16:
115
  torch_dtype = torch.bfloat16