feat: try to fix compilation
Browse files- modeling_bert.py +1 -2
- patched_padding_bert.py +39 -0
modeling_bert.py
CHANGED
@@ -28,9 +28,8 @@ from transformers.models.bert.modeling_bert import (
|
|
28 |
BaseModelOutputWithPoolingAndCrossAttentions,
|
29 |
BertForPreTrainingOutput,
|
30 |
)
|
31 |
-
|
32 |
from flash_attn.bert_padding import (
|
33 |
-
index_first_axis,
|
34 |
index_first_axis_residual,
|
35 |
pad_input,
|
36 |
unpad_input,
|
|
|
28 |
BaseModelOutputWithPoolingAndCrossAttentions,
|
29 |
BertForPreTrainingOutput,
|
30 |
)
|
31 |
+
from .patched_padding_bert import index_first_axis
|
32 |
from flash_attn.bert_padding import (
|
|
|
33 |
index_first_axis_residual,
|
34 |
pad_input,
|
35 |
unpad_input,
|
patched_padding_bert.py
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Source https://github.com/Dao-AILab/flash-attention/blob/87a1277653fc55cd615f5341255e00c69d5c00a1/flash_attn/bert_padding.py
|
2 |
+
|
3 |
+
We replace the gather in `IndexFirstAxis.forward` with an indexing operation
|
4 |
+
"""
|
5 |
+
import torch
|
6 |
+
from einops import rearrange, repeat
|
7 |
+
|
8 |
+
class IndexFirstAxis(torch.autograd.Function):
|
9 |
+
@staticmethod
|
10 |
+
def forward(ctx, input, indices, indexing=False):
|
11 |
+
ctx.save_for_backward(indices)
|
12 |
+
assert input.ndim >= 2
|
13 |
+
ctx.first_axis_dim, other_shape = input.shape[0], input.shape[1:]
|
14 |
+
# second_dim = other_shape.numel()
|
15 |
+
# TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
|
16 |
+
# return input[indices]
|
17 |
+
#return torch.gather(
|
18 |
+
# rearrange(input, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim)
|
19 |
+
#).reshape(-1, *other_shape)
|
20 |
+
return input[indices]
|
21 |
+
|
22 |
+
@staticmethod
|
23 |
+
def backward(ctx, grad_output):
|
24 |
+
(indices,) = ctx.saved_tensors
|
25 |
+
assert grad_output.ndim >= 2
|
26 |
+
other_shape = grad_output.shape[1:]
|
27 |
+
grad_output = rearrange(grad_output, "b ... -> b (...)")
|
28 |
+
grad_input = torch.zeros(
|
29 |
+
[ctx.first_axis_dim, grad_output.shape[1]],
|
30 |
+
device=grad_output.device,
|
31 |
+
dtype=grad_output.dtype,
|
32 |
+
)
|
33 |
+
# TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
|
34 |
+
# grad_input[indices] = grad_output
|
35 |
+
grad_input.scatter_(0, repeat(indices, "z -> z d", d=grad_output.shape[1]), grad_output)
|
36 |
+
return grad_input.reshape(ctx.first_axis_dim, *other_shape), None
|
37 |
+
|
38 |
+
|
39 |
+
index_first_axis = IndexFirstAxis.apply
|