phoebeklett commited on
Commit
dd6bd5b
1 Parent(s): ca9f198

Delete attention.py

Browse files
Files changed (1) hide show
  1. attention.py +0 -770
attention.py DELETED
@@ -1,770 +0,0 @@
1
- # Adapted from https://github.com/mosaicml/llm-foundry
2
- # Classes changed: MultiheadAttention
3
- # Functions changed: scaled_multihead_dot_product_attention, build_alibi_bias, build_attn_bias
4
- # SPDX-License-Identifier: Apache-2.0
5
-
6
- """Attention layers."""
7
- import math
8
- import warnings
9
- from typing import Optional
10
- import torch
11
- import torch.nn as nn
12
- from einops import rearrange
13
- from packaging import version
14
- from torch import nn
15
- from torch.linalg import vector_norm
16
- from llmfoundry.models.layers.norm import LPLayerNorm
17
- from torch.nn import functional as F
18
-
19
- def _reset_is_causal(num_query_tokens: int, num_key_tokens: int,
20
- original_is_causal: bool):
21
- # disable causal when it is not needed
22
- # necessary for flash & triton for generation with kv_cache
23
- if original_is_causal and num_query_tokens != num_key_tokens:
24
- if num_query_tokens != 1:
25
- raise NotImplementedError(
26
- 'MPT does not support query and key with different number of tokens, unless number of query tokens is 1.'
27
- )
28
- else:
29
- return False
30
- return original_is_causal
31
-
32
-
33
- def scaled_multihead_dot_product_attention(
34
- query,
35
- key,
36
- value,
37
- n_heads,
38
- past_key_value=None,
39
- long_range_past_key_value=None,
40
- softmax_scale=None,
41
- attn_bias=None,
42
- attn_bias_ae=None,
43
- key_padding_mask=None,
44
- is_causal=False,
45
- dropout_p=0.0,
46
- training=False,
47
- needs_weights=False,
48
- multiquery=False,
49
- topk=None,
50
- faiss_indexes=None,
51
- n_layers=None,
52
- current_layer=None,
53
- mask_by_sim=False,
54
- sim_threshold=0.0
55
- ):
56
- q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
57
- kv_n_heads = 1 if multiquery else n_heads
58
- k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
59
- v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
60
-
61
- had_kv=False
62
- if past_key_value is not None:
63
- # attn_impl: flash & triton use kernels which expect input shape [b, s, h, d_head].
64
- # kv_cache is therefore stored using that shape.
65
- # attn_impl: torch stores the kv_cache in the ordering which is most advantageous
66
- # for its attn computation ie
67
- # keys are stored as tensors with shape [b, h, d_head, s] and
68
- # values are stored as tensors with shape [b, h, s, d_head]
69
- if len(past_key_value) != 0:
70
- k = torch.cat([past_key_value[0], k], dim=3)
71
- v = torch.cat([past_key_value[1], v], dim=2)
72
- had_kv=True
73
-
74
- past_key_value = (k, v)
75
-
76
- b, h, s_q, d = q.shape
77
- s_k = k.size(-1)
78
-
79
- if softmax_scale is None:
80
- softmax_scale = 1 / math.sqrt(d)
81
-
82
- attn_weight = q.matmul(k) * softmax_scale
83
-
84
- if attn_bias is not None:
85
- # clamp to 0 necessary for torch 2.0 compile()
86
- _s_q = max(0, attn_bias.size(2) - s_q)
87
- _s_k = max(0, attn_bias.size(3) - s_k)
88
- attn_bias = attn_bias[:, :, _s_q:, _s_k:]
89
-
90
- if (attn_bias.size(-1) != 1 and
91
- attn_bias.size(-1) != s_k) or (attn_bias.size(-2) != 1 and
92
- attn_bias.size(-2) != s_q):
93
- raise RuntimeError(
94
- f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.'
95
- )
96
- attn_weight = attn_weight + attn_bias
97
-
98
- if needs_weights: #will return memory indices w/attention weights
99
- reshaped_idx = None
100
- if long_range_past_key_value is not None or faiss_indexes is not None:
101
- if long_range_past_key_value is not None: #manual memories
102
-
103
- k_cache, v_cache = long_range_past_key_value
104
- s_cache = k_cache.size(-1)
105
-
106
- k_cache = k_cache.to(k.device)
107
- v_cache = v_cache.to(k.device)
108
-
109
- q_n = q/vector_norm(q, ord=2, dim=-1, keepdim=True)
110
- k_n = k_cache/vector_norm(k_cache, ord=2, dim=-2, keepdim=True)
111
-
112
- sim = q_n.matmul(k_n)
113
- if s_cache<topk:
114
- topk = s_cache #number of tokens in cache < topk
115
- val, idx = torch.topk(sim, k=topk, dim=-1)
116
-
117
- reshaped_idx = idx.reshape(b, h, s_q * topk)
118
-
119
- selected_k = k_cache.gather(dim=-1, index=reshaped_idx.unsqueeze(-2).expand(-1, -1, d, -1))
120
- selected_v = v_cache.gather(dim=-2, index=reshaped_idx.unsqueeze(-1).expand(-1, -1, -1, d))
121
-
122
- sim_mask = rearrange(~ (val > sim_threshold).bool(), 'b h s i -> b h (s i)').unsqueeze(-2).expand(-1, -1, s_q, -1)
123
- min_val = torch.finfo(selected_k.dtype).min
124
-
125
- elif faiss_indexes is not None: #faiss indexes
126
-
127
- kn_index, kv_index = faiss_indexes
128
- q_n = q/vector_norm(q, ord=2, dim=-1, keepdim=True)
129
-
130
- one_hot_encodings = F.one_hot(torch.arange(0, n_heads*n_layers, device=q.device))*10
131
- q_n = torch.concat([rearrange(q_n, 'b h s d -> b (h s) d', h=n_heads), one_hot_encodings[n_heads*current_layer:n_heads*(current_layer+1)].unsqueeze(0).repeat_interleave(repeats=q.size(-2), dim=-2)], dim=-1).squeeze()
132
-
133
- D, I = kn_index.search(q_n.to('cpu').numpy(), k=topk)
134
-
135
- selected_k=rearrange(torch.tensor(kv_index.reconstruct_batch(I.flatten()))[:,:d], '(h s) d -> 1 h d s', h=32).to(q.device)
136
- selected_v=rearrange(torch.tensor(kv_index.reconstruct_batch(I.flatten()))[:,d:], '(h s) d -> 1 h s d', h=32).to(q.device)
137
-
138
- s_k_ae = selected_k.size(-1)
139
- s_k += s_k_ae
140
- attn_weight_cache = q.matmul(selected_k) * softmax_scale
141
- if mask_by_sim:
142
- attn_weight_cache = attn_weight_cache.masked_fill(sim_mask, min_val)
143
-
144
- if attn_bias_ae is not None: #add alibi bias to memories
145
- _s_q = max(0, attn_bias_ae.size(2) - s_q)
146
- _s_k = max(0, attn_bias_ae.size(3) - s_k_ae)
147
- attn_bias_ae = attn_bias_ae[:, :, _s_q:, _s_k:]
148
-
149
- if (attn_bias_ae.size(-1) != 1 and
150
- attn_bias_ae.size(-1) != s_k_ae) or (attn_bias_ae.size(-2) != 1 and
151
- attn_bias_ae.size(-2) != s_q):
152
- raise RuntimeError(
153
- f'attn_bias (shape: {attn_bias_ae.shape}) is expected to broadcast to shape: {attn_weight_cache.shape}.'
154
- )
155
- attn_weight_cache = attn_weight_cache + attn_bias_ae
156
-
157
- attn_weight = torch.cat([attn_weight_cache, attn_weight], dim=-1)
158
- v = torch.cat([selected_v, v], dim=-2)
159
-
160
- min_val = torch.finfo(q.dtype).min
161
-
162
- if key_padding_mask is not None:
163
- if attn_bias is not None:
164
- warnings.warn(
165
- 'Propogating key_padding_mask to the attention module ' +\
166
- 'and applying it within the attention module can cause ' +\
167
- 'unneccessary computation/memory usage. Consider integrating ' +\
168
- 'into attn_bias once and passing that to each attention ' +\
169
- 'module instead.'
170
- )
171
- attn_weight = attn_weight.masked_fill(
172
- ~key_padding_mask.view((b, 1, 1, s_k)), min_val)
173
-
174
- def _create_active_externalism_mask(k, s_q, device):
175
- mask = torch.zeros(s_q, s_q * k, device=device, dtype=torch.bool)
176
- for i in range(s_q):
177
- mask[i, i * k : (i + 1) * k] = 1
178
- return ~mask
179
-
180
- if is_causal and (not q.size(2) == 1):
181
- s = max(s_q, s_k)
182
- causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
183
- causal_mask = causal_mask.tril()
184
- causal_mask = causal_mask.to(torch.bool)
185
- causal_mask = ~causal_mask
186
- causal_mask = causal_mask[-s_q:, -s_k:]
187
-
188
- if long_range_past_key_value is not None:
189
- mask = _create_active_externalism_mask(k=topk,s_q=s_q, device=attn_weight.device)
190
- s=s_q
191
- if had_kv:
192
- s += (past_key_value[0][0].size(-1) -s_q)
193
- causal_mask = torch.cat([mask, causal_mask[:,-s:]], dim=1)
194
-
195
- attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k),
196
- min_val)
197
-
198
- attn_weight = torch.softmax(attn_weight, dim=-1)
199
-
200
- if dropout_p:
201
- attn_weight = torch.nn.functional.dropout(attn_weight,
202
- p=dropout_p,
203
- training=training,
204
- inplace=True)
205
-
206
- out = attn_weight.to(v.dtype).matmul(v)
207
- out = rearrange(out, 'b h s d -> b s (h d)')
208
-
209
- if needs_weights:
210
- return out, attn_weight, past_key_value, reshaped_idx
211
- return out, None, past_key_value, None
212
-
213
-
214
- def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
215
- for tensor in tensors:
216
- if tensor.dtype not in valid_dtypes:
217
- raise TypeError(f'{tensor.dtype=} must be in {valid_dtypes=}.')
218
- if not tensor.is_cuda:
219
- raise TypeError(f'Inputs must be cuda tensors ({tensor.is_cuda=}).')
220
-
221
-
222
- def flash_attn_fn(
223
- query,
224
- key,
225
- value,
226
- n_heads,
227
- past_key_value=None,
228
- softmax_scale=None,
229
- attn_bias=None,
230
- key_padding_mask=None,
231
- is_causal=False,
232
- dropout_p=0.0,
233
- training=False,
234
- needs_weights=False,
235
- multiquery=False,
236
- ):
237
- try:
238
- from flash_attn import bert_padding, flash_attn_interface # type: ignore # yapf: disable # isort: skip
239
- except:
240
- raise RuntimeError('Please install flash-attn==1.0.3.post0')
241
-
242
- check_valid_inputs(query, key, value)
243
-
244
- if past_key_value is not None:
245
- if len(past_key_value) != 0:
246
- key = torch.cat([past_key_value[0], key], dim=1)
247
- value = torch.cat([past_key_value[1], value], dim=1)
248
-
249
- past_key_value = (key, value)
250
-
251
- if attn_bias is not None:
252
- # clamp to 0 necessary for torch 2.0 compile()
253
- _s_q = max(0, attn_bias.size(2) - query.size(1))
254
- _s_k = max(0, attn_bias.size(3) - key.size(1))
255
- attn_bias = attn_bias[:, :, _s_q:, _s_k:]
256
-
257
- if attn_bias is not None:
258
- raise NotImplementedError(f'attn_bias not implemented for flash attn.')
259
-
260
- batch_size, seqlen = query.shape[:2]
261
-
262
- if key_padding_mask is None:
263
- key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
264
- query_padding_mask = key_padding_mask[:, -query.size(1):]
265
-
266
- query_unpad, indices_q, cu_seqlens_q, max_seqlen_q = bert_padding.unpad_input(
267
- query, query_padding_mask)
268
- query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
269
-
270
- key_unpad, _, cu_seqlens_k, max_seqlen_k = bert_padding.unpad_input(
271
- key, key_padding_mask)
272
- key_unpad = rearrange(key_unpad,
273
- 'nnz (h d) -> nnz h d',
274
- h=1 if multiquery else n_heads)
275
-
276
- value_unpad, _, _, _ = bert_padding.unpad_input(value, key_padding_mask)
277
- value_unpad = rearrange(value_unpad,
278
- 'nnz (h d) -> nnz h d',
279
- h=1 if multiquery else n_heads)
280
-
281
- if multiquery:
282
- # Expanding a tensor does not allocate new memory, but only creates a new
283
- # view on the existing tensor where a dimension of size one is expanded
284
- # to a larger size by setting the stride to 0.
285
- # - pytorch docs
286
- #
287
- # hopefully the kernels can utilize this and we're jot just wasting BW here
288
- key_unpad = key_unpad.expand(key_unpad.size(0), n_heads,
289
- key_unpad.size(-1))
290
- value_unpad = value_unpad.expand(value_unpad.size(0), n_heads,
291
- value_unpad.size(-1))
292
-
293
- dropout_p = dropout_p if training else 0.0
294
-
295
- reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
296
-
297
- output_unpad = flash_attn_interface.flash_attn_unpadded_func(
298
- query_unpad,
299
- key_unpad,
300
- value_unpad,
301
- cu_seqlens_q,
302
- cu_seqlens_k,
303
- max_seqlen_q,
304
- max_seqlen_k,
305
- dropout_p,
306
- softmax_scale=softmax_scale,
307
- causal=reset_is_causal,
308
- return_attn_probs=needs_weights)
309
-
310
- output = bert_padding.pad_input(
311
- rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size,
312
- seqlen)
313
- return output, None, past_key_value
314
-
315
-
316
- def triton_flash_attn_fn(
317
- query,
318
- key,
319
- value,
320
- n_heads,
321
- past_key_value=None,
322
- softmax_scale=None,
323
- attn_bias=None,
324
- key_padding_mask=None,
325
- is_causal=False,
326
- dropout_p=0.0,
327
- training=False,
328
- needs_weights=False,
329
- multiquery=False,
330
- ):
331
- try:
332
- from llmfoundry.models.layers.flash_attn_triton import flash_attn_func
333
- except:
334
- _installed = False
335
- if version.parse(torch.__version__) < version.parse('2.0.0'):
336
- _installed = True
337
- # if torch1.13.1 revert to using triton flash attn from HazyResearch
338
- # with flash-attn==1.0.3.post0 and triton==2.0.0.dev20221202
339
- try:
340
- from flash_attn.flash_attn_triton import flash_attn_func
341
- except:
342
- _installed = False
343
- if not _installed:
344
- # installing triton-pre-mlir works for both torch1.13.1 and torch2.0+
345
- # default recommendation is to install this variant
346
- raise RuntimeError(
347
- 'Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU '
348
- 'and `pip install .[gpu]` if installing from llm-foundry source or '
349
- '`pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` '
350
- 'if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). '
351
- 'Note: (1) requires you have CMake and PyTorch already installed.'
352
- )
353
-
354
- check_valid_inputs(query, key, value)
355
-
356
- if past_key_value is not None:
357
- if len(past_key_value) != 0:
358
- key = torch.cat([past_key_value[0], key], dim=1)
359
- value = torch.cat([past_key_value[1], value], dim=1)
360
-
361
- past_key_value = (key, value)
362
-
363
- if attn_bias is not None:
364
- # clamp to 0 necessary for torch 2.0 compile()
365
- _s_q = max(0, attn_bias.size(2) - query.size(1))
366
- _s_k = max(0, attn_bias.size(3) - key.size(1))
367
- attn_bias = attn_bias[:, :, _s_q:, _s_k:]
368
-
369
- if dropout_p:
370
- raise NotImplementedError(
371
- f'Dropout not implemented for attn_impl: triton.')
372
-
373
- if needs_weights:
374
- raise NotImplementedError(
375
- f'attn_impl: triton cannot return attn weights.')
376
-
377
- if key_padding_mask is not None:
378
- warnings.warn(
379
- 'Propagating key_padding_mask to the attention module ' +\
380
- 'and applying it within the attention module can cause ' +\
381
- 'unnecessary computation/memory usage. Consider integrating ' +\
382
- 'into attn_bias once and passing that to each attention ' +\
383
- 'module instead.'
384
- )
385
- b_size, s_k = key_padding_mask.shape[:2]
386
-
387
- if attn_bias is None:
388
- attn_bias = query.new_zeros(b_size, 1, 1, s_k)
389
-
390
- attn_bias = attn_bias.masked_fill(
391
- ~key_padding_mask.view((b_size, 1, 1, s_k)),
392
- torch.finfo(query.dtype).min)
393
-
394
- query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
395
- key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
396
- value = rearrange(value,
397
- 'b s (h d) -> b s h d',
398
- h=1 if multiquery else n_heads)
399
-
400
- if multiquery:
401
- # Expanding a tensor does not allocate new memory, but only creates a new
402
- # view on the existing tensor where a dimension of size one is expanded
403
- # to a larger size by setting the stride to 0.
404
- # - pytorch docs
405
- #
406
- # hopefully the kernels can utilize this and we're jot just wasting BW here
407
- key = key.expand(*key.shape[:2], n_heads, key.size(-1))
408
- value = value.expand(*value.shape[:2], n_heads, value.size(-1))
409
-
410
- reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
411
- attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal,
412
- softmax_scale)
413
-
414
- output = attn_output.view(*attn_output.shape[:2], -1)
415
-
416
- return output, None, past_key_value
417
-
418
-
419
- class MultiheadAttention(nn.Module):
420
- """Multi-head self attention.
421
-
422
- Using torch or triton attention implemetation enables user to also use
423
- additive bias.
424
- """
425
-
426
- def __init__(
427
- self,
428
- d_model: int,
429
- n_heads: int,
430
- attn_impl: str = 'triton',
431
- clip_qkv: Optional[float] = None,
432
- qk_ln: bool = False,
433
- softmax_scale: Optional[float] = None,
434
- attn_pdrop: float = 0.0,
435
- low_precision_layernorm: bool = False,
436
- verbose: int = 0,
437
- device: Optional[str] = None,
438
- ):
439
- super().__init__()
440
-
441
- self.attn_impl = attn_impl
442
- self.clip_qkv = clip_qkv
443
- self.qk_ln = qk_ln
444
-
445
- self.d_model = d_model
446
- self.n_heads = n_heads
447
- self.softmax_scale = softmax_scale
448
- if self.softmax_scale is None:
449
- self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
450
- self.attn_dropout_p = attn_pdrop
451
-
452
- self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
453
- # for param init fn; enables shape based init of fused layers
454
- fuse_splits = (d_model, 2 * d_model)
455
- self.Wqkv._fused = (0, fuse_splits) # type: ignore
456
-
457
- if self.qk_ln:
458
- layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
459
- self.q_ln = layernorm_class(self.d_model, device=device)
460
- self.k_ln = layernorm_class(self.d_model, device=device)
461
-
462
- if self.attn_impl == 'flash':
463
- self.attn_fn = flash_attn_fn
464
- elif self.attn_impl == 'triton':
465
- self.attn_fn = triton_flash_attn_fn
466
- if verbose:
467
- warnings.warn(
468
- 'While `attn_impl: triton` can be faster than `attn_impl: flash` ' +\
469
- 'it uses more memory. When training larger models this can trigger ' +\
470
- 'alloc retries which hurts performance. If encountered, we recommend ' +\
471
- 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.'
472
- )
473
- elif self.attn_impl == 'torch':
474
- self.attn_fn = scaled_multihead_dot_product_attention
475
- if torch.cuda.is_available() and verbose:
476
- warnings.warn(
477
- 'Using `attn_impl: torch`. If your model does not use `alibi` or ' +\
478
- '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' +\
479
- 'we recommend using `attn_impl: triton`.'
480
- )
481
- else:
482
- raise ValueError(f'{attn_impl=} is an invalid setting.')
483
-
484
- self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
485
- self.out_proj._is_residual = True # type: ignore
486
-
487
- def forward(
488
- self,
489
- x,
490
- past_key_value=None,
491
- long_range_past_key_value=None,
492
- attn_bias=None,
493
- attn_bias_ae=None,
494
- attention_mask=None,
495
- is_causal=True,
496
- needs_weights=False,
497
- topk=None,
498
- faiss_indexes=None,
499
- n_layers=None,
500
- current_layer=None,
501
- mask_by_sim=None,
502
- sim_threshold=None
503
- ):
504
- qkv = self.Wqkv(x)
505
-
506
- if self.clip_qkv:
507
- qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
508
-
509
- query, key, value = qkv.chunk(3, dim=2)
510
-
511
- key_padding_mask = attention_mask
512
-
513
- if self.qk_ln:
514
- # Applying layernorm to qk
515
- dtype = query.dtype
516
- query = self.q_ln(query).to(dtype)
517
- key = self.k_ln(key).to(dtype)
518
-
519
- context, attn_weights, past_key_value, reshaped_idx = self.attn_fn(
520
- query,
521
- key,
522
- value,
523
- self.n_heads,
524
- past_key_value=past_key_value,
525
- long_range_past_key_value=long_range_past_key_value,
526
- softmax_scale=self.softmax_scale,
527
- attn_bias=attn_bias,
528
- attn_bias_ae=attn_bias_ae,
529
- key_padding_mask=key_padding_mask,
530
- is_causal=is_causal,
531
- dropout_p=self.attn_dropout_p,
532
- training=self.training,
533
- needs_weights=needs_weights,
534
- topk=topk,
535
- faiss_indexes=faiss_indexes,
536
- n_layers=n_layers,
537
- current_layer=current_layer,
538
- mask_by_sim=mask_by_sim,
539
- sim_threshold=sim_threshold
540
- )
541
-
542
- return self.out_proj(context), attn_weights, past_key_value, reshaped_idx
543
-
544
-
545
- class MultiQueryAttention(nn.Module):
546
- """Multi-Query self attention.
547
-
548
- Using torch or triton attention implemetation enables user to also use
549
- additive bias.
550
- """
551
-
552
- def __init__(
553
- self,
554
- d_model: int,
555
- n_heads: int,
556
- attn_impl: str = 'triton',
557
- clip_qkv: Optional[float] = None,
558
- qk_ln: bool = False,
559
- softmax_scale: Optional[float] = None,
560
- attn_pdrop: float = 0.0,
561
- low_precision_layernorm: bool = False,
562
- verbose: int = 0,
563
- device: Optional[str] = None,
564
- ):
565
- super().__init__()
566
-
567
- self.attn_impl = attn_impl
568
- self.clip_qkv = clip_qkv
569
- self.qk_ln = qk_ln
570
-
571
- self.d_model = d_model
572
- self.n_heads = n_heads
573
- self.head_dim = d_model // n_heads
574
- self.softmax_scale = softmax_scale
575
- if self.softmax_scale is None:
576
- self.softmax_scale = 1 / math.sqrt(self.head_dim)
577
- self.attn_dropout_p = attn_pdrop
578
-
579
- # NOTE: if we ever want to make attn TensorParallel, I'm pretty sure we'll
580
- # want to split Wqkv into Wq and Wkv where Wq can be TensorParallel but
581
- # Wkv shouldn't be TensorParallel
582
- # - vchiley
583
- self.Wqkv = nn.Linear(
584
- d_model,
585
- d_model + 2 * self.head_dim,
586
- device=device,
587
- )
588
- # for param init fn; enables shape based init of fused layers
589
- fuse_splits = (d_model, d_model + self.head_dim)
590
- self.Wqkv._fused = (0, fuse_splits) # type: ignore
591
-
592
- if self.qk_ln:
593
- layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
594
- self.q_ln = layernorm_class(d_model, device=device)
595
- self.k_ln = layernorm_class(self.head_dim, device=device)
596
-
597
- if self.attn_impl == 'flash':
598
- self.attn_fn = flash_attn_fn
599
- elif self.attn_impl == 'triton':
600
- self.attn_fn = triton_flash_attn_fn
601
- if verbose:
602
- warnings.warn(
603
- 'While `attn_impl: triton` can be faster than `attn_impl: flash` ' +\
604
- 'it uses more memory. When training larger models this can trigger ' +\
605
- 'alloc retries which hurts performance. If encountered, we recommend ' +\
606
- 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.'
607
- )
608
- elif self.attn_impl == 'torch':
609
- self.attn_fn = scaled_multihead_dot_product_attention
610
- if torch.cuda.is_available() and verbose:
611
- warnings.warn(
612
- 'Using `attn_impl: torch`. If your model does not use `alibi` or ' +\
613
- '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' +\
614
- 'we recommend using `attn_impl: triton`.'
615
- )
616
- else:
617
- raise ValueError(f'{attn_impl=} is an invalid setting.')
618
-
619
- self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
620
- self.out_proj._is_residual = True # type: ignore
621
-
622
- def forward(
623
- self,
624
- x,
625
- past_key_value=None,
626
- attn_bias=None,
627
- attention_mask=None,
628
- is_causal=True,
629
- needs_weights=False,
630
- ):
631
- qkv = self.Wqkv(x)
632
-
633
- if self.clip_qkv:
634
- qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
635
-
636
- query, key, value = qkv.split(
637
- [self.d_model, self.head_dim, self.head_dim], dim=2)
638
-
639
- key_padding_mask = attention_mask
640
-
641
- if self.qk_ln:
642
- # Applying layernorm to qk
643
- dtype = query.dtype
644
- query = self.q_ln(query).to(dtype)
645
- key = self.k_ln(key).to(dtype)
646
-
647
- context, attn_weights, past_key_value = self.attn_fn(
648
- query,
649
- key,
650
- value,
651
- self.n_heads,
652
- past_key_value=past_key_value,
653
- softmax_scale=self.softmax_scale,
654
- attn_bias=attn_bias,
655
- key_padding_mask=key_padding_mask,
656
- is_causal=is_causal,
657
- dropout_p=self.attn_dropout_p,
658
- training=self.training,
659
- needs_weights=needs_weights,
660
- multiquery=True,
661
- )
662
-
663
- return self.out_proj(context), attn_weights, past_key_value
664
-
665
-
666
- def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal,
667
- use_sequence_id):
668
- if attn_impl == 'flash':
669
- return None
670
- elif attn_impl in ['torch', 'triton']:
671
- if alibi:
672
- if (prefix_lm or not causal) or use_sequence_id:
673
- return (1, n_heads, seq_len, seq_len)
674
- return (1, n_heads, 1, seq_len)
675
- elif prefix_lm or use_sequence_id:
676
- return (1, 1, seq_len, seq_len)
677
- return None
678
- else:
679
- raise ValueError(f'{attn_impl=} is an invalid setting.')
680
-
681
-
682
- def build_attn_bias(
683
- attn_impl,
684
- n_heads,
685
- seq_len,
686
- attn_bias=None,
687
- causal=False,
688
- alibi=False,
689
- alibi_bias_max=8,
690
- for_ae=False,
691
- topk=0,
692
- device=None,
693
- dtype=None
694
- ):
695
- if attn_impl == 'flash':
696
- return None
697
- elif attn_impl in ['torch', 'triton']:
698
- if alibi:
699
- # in place add alibi to attn bias
700
- if attn_bias is not None:
701
- attn_bias = attn_bias.add(
702
- build_alibi_bias(
703
- n_heads,
704
- seq_len,
705
- full=not causal,
706
- alibi_bias_max=alibi_bias_max,
707
- device=device,
708
- dtype=dtype,
709
- for_ae=for_ae,
710
- topk=topk
711
- ))
712
- else: #for memories
713
- attn_bias = build_alibi_bias(
714
- n_heads,
715
- seq_len,
716
- full=not causal,
717
- alibi_bias_max=alibi_bias_max,
718
- for_ae=for_ae,
719
- topk=topk)
720
- return attn_bias
721
-
722
-
723
- def gen_slopes(n_heads, alibi_bias_max=8, device=None):
724
- _n_heads = 2**math.ceil(math.log2(n_heads))
725
- m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
726
- m = m.mul(alibi_bias_max / _n_heads)
727
- slopes = (1. / torch.pow(2, m))
728
-
729
- if _n_heads != n_heads:
730
- # if n_heads is not a power of two,
731
- # Huggingface and FasterTransformer calculate slopes normally,
732
- # then return this strided concatenation of slopes
733
- slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
734
-
735
- return slopes.view(1, n_heads, 1, 1)
736
-
737
-
738
- def build_alibi_bias(
739
- n_heads,
740
- seq_len,
741
- full=False,
742
- alibi_bias_max=8,
743
- device=None,
744
- dtype=None,
745
- for_ae=False,
746
- topk=0
747
- ):
748
- if not for_ae:
749
- alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32,
750
- device=device).view(1, 1, 1, seq_len)
751
- else:
752
- alibi_bias = torch.tensor(-seq_len, dtype=torch.int32,
753
- device=device).repeat(seq_len*topk).view(1, 1, 1, seq_len*(topk))
754
- if full:
755
- # generate 1 x Heads x SeqLen x SeqLen alibi bias mask
756
- # otherwise the mask is 1 x Heads x 1 x SeqLen (which is broadcast to the appropriate size)
757
- alibi_bias = alibi_bias - torch.arange(
758
- 1 - seq_len, 1, dtype=torch.int32, device=device).view(
759
- 1, 1, seq_len, 1)
760
- alibi_bias = alibi_bias.abs().mul(-1)
761
-
762
- slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
763
- alibi_bias = alibi_bias * slopes
764
- return alibi_bias.to(dtype=dtype)
765
-
766
-
767
- ATTN_CLASS_REGISTRY = {
768
- 'multihead_attention': MultiheadAttention,
769
- 'multiquery_attention': MultiQueryAttention,
770
- }