Haiyang Liu commited on
Commit
bb59369
·
verified ·
1 Parent(s): d378637

Upload models/tools/attention.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. models/tools/attention.py +188 -0
models/tools/attention.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved.
2
+ import torch
3
+
4
+ try:
5
+ import flash_attn_interface
6
+
7
+ FLASH_ATTN_3_AVAILABLE = True
8
+ except ModuleNotFoundError:
9
+ FLASH_ATTN_3_AVAILABLE = False
10
+
11
+ try:
12
+ import flash_attn
13
+
14
+ FLASH_ATTN_2_AVAILABLE = True
15
+ except ModuleNotFoundError:
16
+ FLASH_ATTN_2_AVAILABLE = False
17
+
18
+ import warnings
19
+
20
+ __all__ = [
21
+ "flash_attention",
22
+ "attention",
23
+ ]
24
+
25
+
26
+ def flash_attention(
27
+ q,
28
+ k,
29
+ v,
30
+ q_lens=None,
31
+ k_lens=None,
32
+ dropout_p=0.0,
33
+ softmax_scale=None,
34
+ q_scale=None,
35
+ causal=False,
36
+ window_size=(-1, -1),
37
+ deterministic=False,
38
+ dtype=torch.bfloat16,
39
+ version=None,
40
+ ):
41
+ """
42
+ q: [B, Lq, Nq, C1].
43
+ k: [B, Lk, Nk, C1].
44
+ v: [B, Lk, Nk, C2]. Nq must be divisible by Nk.
45
+ q_lens: [B].
46
+ k_lens: [B].
47
+ dropout_p: float. Dropout probability.
48
+ softmax_scale: float. The scaling of QK^T before applying softmax.
49
+ causal: bool. Whether to apply causal attention mask.
50
+ window_size: (left right). If not (-1, -1), apply sliding window local attention.
51
+ deterministic: bool. If True, slightly slower and uses more memory.
52
+ dtype: torch.dtype. Apply when dtype of q/k/v is not float16/bfloat16.
53
+ """
54
+ half_dtypes = (torch.float16, torch.bfloat16)
55
+ assert dtype in half_dtypes
56
+ assert q.device.type == "cuda" and q.size(-1) <= 256
57
+
58
+ # params
59
+ b, lq, lk, out_dtype = q.size(0), q.size(1), k.size(1), q.dtype
60
+
61
+ def half(x):
62
+ return x if x.dtype in half_dtypes else x.to(dtype)
63
+
64
+ # preprocess query
65
+ if q_lens is None:
66
+ q = half(q.flatten(0, 1))
67
+ q_lens = torch.tensor([lq] * b, dtype=torch.int32).to(
68
+ device=q.device, non_blocking=True
69
+ )
70
+ else:
71
+ q = half(torch.cat([u[:v] for u, v in zip(q, q_lens)]))
72
+
73
+ # preprocess key, value
74
+ if k_lens is None:
75
+ k = half(k.flatten(0, 1))
76
+ v = half(v.flatten(0, 1))
77
+ k_lens = torch.tensor([lk] * b, dtype=torch.int32).to(
78
+ device=k.device, non_blocking=True
79
+ )
80
+ else:
81
+ k = half(torch.cat([u[:v] for u, v in zip(k, k_lens)]))
82
+ v = half(torch.cat([u[:v] for u, v in zip(v, k_lens)]))
83
+
84
+ q = q.to(v.dtype)
85
+ k = k.to(v.dtype)
86
+
87
+ if q_scale is not None:
88
+ q = q * q_scale
89
+
90
+ if version is not None and version == 3 and not FLASH_ATTN_3_AVAILABLE:
91
+ warnings.warn(
92
+ "Flash attention 3 is not available, use flash attention 2 instead."
93
+ )
94
+
95
+ # apply attention
96
+ if (version is None or version == 3) and FLASH_ATTN_3_AVAILABLE:
97
+ # Note: dropout_p, window_size are not supported in FA3 now.
98
+ x = flash_attn_interface.flash_attn_varlen_func(
99
+ q=q,
100
+ k=k,
101
+ v=v,
102
+ cu_seqlens_q=torch.cat([q_lens.new_zeros([1]), q_lens])
103
+ .cumsum(0, dtype=torch.int32)
104
+ .to(q.device, non_blocking=True),
105
+ cu_seqlens_k=torch.cat([k_lens.new_zeros([1]), k_lens])
106
+ .cumsum(0, dtype=torch.int32)
107
+ .to(q.device, non_blocking=True),
108
+ seqused_q=None,
109
+ seqused_k=None,
110
+ max_seqlen_q=lq,
111
+ max_seqlen_k=lk,
112
+ softmax_scale=softmax_scale,
113
+ causal=causal,
114
+ deterministic=deterministic,
115
+ )[0].unflatten(0, (b, lq))
116
+ else:
117
+ assert FLASH_ATTN_2_AVAILABLE
118
+ x = flash_attn.flash_attn_varlen_func(
119
+ q=q,
120
+ k=k,
121
+ v=v,
122
+ cu_seqlens_q=torch.cat([q_lens.new_zeros([1]), q_lens])
123
+ .cumsum(0, dtype=torch.int32)
124
+ .to(q.device, non_blocking=True),
125
+ cu_seqlens_k=torch.cat([k_lens.new_zeros([1]), k_lens])
126
+ .cumsum(0, dtype=torch.int32)
127
+ .to(q.device, non_blocking=True),
128
+ max_seqlen_q=lq,
129
+ max_seqlen_k=lk,
130
+ dropout_p=dropout_p,
131
+ softmax_scale=softmax_scale,
132
+ causal=causal,
133
+ window_size=window_size,
134
+ deterministic=deterministic,
135
+ ).unflatten(0, (b, lq))
136
+
137
+ # output
138
+ return x.type(out_dtype)
139
+
140
+
141
+ def attention(
142
+ q,
143
+ k,
144
+ v,
145
+ q_lens=None,
146
+ k_lens=None,
147
+ dropout_p=0.0,
148
+ softmax_scale=None,
149
+ q_scale=None,
150
+ causal=False,
151
+ window_size=(-1, -1),
152
+ deterministic=False,
153
+ dtype=torch.bfloat16,
154
+ fa_version=None,
155
+ ):
156
+ if FLASH_ATTN_2_AVAILABLE or FLASH_ATTN_3_AVAILABLE:
157
+ return flash_attention(
158
+ q=q,
159
+ k=k,
160
+ v=v,
161
+ q_lens=q_lens,
162
+ k_lens=k_lens,
163
+ dropout_p=dropout_p,
164
+ softmax_scale=softmax_scale,
165
+ q_scale=q_scale,
166
+ causal=causal,
167
+ window_size=window_size,
168
+ deterministic=deterministic,
169
+ dtype=dtype,
170
+ version=fa_version,
171
+ )
172
+ else:
173
+ if q_lens is not None or k_lens is not None:
174
+ warnings.warn(
175
+ "Padding mask is disabled when using scaled_dot_product_attention. It can have a significant impact on performance."
176
+ )
177
+ attn_mask = None
178
+
179
+ q = q.transpose(1, 2).to(dtype)
180
+ k = k.transpose(1, 2).to(dtype)
181
+ v = v.transpose(1, 2).to(dtype)
182
+
183
+ out = torch.nn.functional.scaled_dot_product_attention(
184
+ q, k, v, attn_mask=attn_mask, is_causal=causal, dropout_p=dropout_p
185
+ )
186
+
187
+ out = out.transpose(1, 2).contiguous()
188
+ return out