Skip to content

Commit a754db2

Browse files
author
xFormers Bot
committed
[fmha] LowerTriangularFromBottomRightLocalAttentionMask
ghstack-source-id: a7ff2da Pull Request resolved: https://github.com/fairinternal/xformers/pull/933 __original_commit__ = fairinternal/xformers@9801b557e356e5c032f5af064e00f22dafe164bf
1 parent d8be2ed commit a754db2

6 files changed

Lines changed: 73 additions & 8 deletions

File tree

69.1 KB
Loading

‎xformers/attn_bias_utils.py‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def create_attn_bias(
4343
if bias_type is None or isinstance(None, bias_type):
4444
return None
4545
r = random.Random("-".join(map(str, [batch_size, q_len, kv_len, dtype, fmt])))
46+
window_size = {0: 3, 1: 128, 2: 300}[r.randint(0, 2)]
4647
if bias_type is torch.Tensor:
4748
if fmt == "BMK":
4849
batch_size *= num_heads
@@ -81,6 +82,8 @@ def create_attn_bias(
8182
return bias_type()
8283
if bias_type is fmha.attn_bias.LowerTriangularFromBottomRightMask:
8384
return bias_type()
85+
if bias_type is fmha.attn_bias.LowerTriangularFromBottomRightLocalAttentionMask:
86+
return bias_type(window_size)
8487
if bias_type is fmha.attn_bias.LowerTriangularMaskWithTensorBias:
8588
attn_bias = _create_aligned_bias(
8689
batch_size,
@@ -107,13 +110,6 @@ def create_attn_bias(
107110
]:
108111
# These bias types are not supported in BMK format
109112
assert fmt in ["BMGHK", "BMHK"]
110-
111-
window_size = None
112-
if bias_type in {
113-
fmha.attn_bias.BlockDiagonalCausalLocalAttentionMask,
114-
fmha.attn_bias.BlockDiagonalCausalLocalAttentionFromBottomRightMask,
115-
}:
116-
window_size = {0: 3, 1: 128, 2: 300}[r.randint(0, 2)]
117113
max_q_minus_k = None
118114
if bias_type in {
119115
fmha.attn_bias.BlockDiagonalCausalFromBottomRightMask,

‎xformers/ops/fmha/attn_bias.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,9 @@ def materialize(
112112
return _materialize_causal_mask(shape, dtype=dtype, device=device)
113113

114114
def add_bias(self, bias: torch.Tensor) -> "LowerTriangularMaskWithTensorBias":
115+
"""
116+
Creates a new causal mask with an arbitrary ``torch.Tensor`` bias
117+
"""
115118
return LowerTriangularMaskWithTensorBias(bias)
116119

117120

@@ -145,6 +148,60 @@ def materialize(
145148
shape, dtype=dtype, device=device, from_bottomright=True
146149
)
147150

151+
def make_local_attention(
152+
self, window_size: int
153+
) -> "LowerTriangularFromBottomRightLocalAttentionMask":
154+
"""
155+
Create a new bias which combines local + causal attention.
156+
157+
See :attr:`LowerTriangularFromBottomRightLocalAttentionMask`
158+
"""
159+
return LowerTriangularFromBottomRightLocalAttentionMask(window_size)
160+
161+
162+
@dataclass
163+
class LowerTriangularFromBottomRightLocalAttentionMask(
164+
LowerTriangularFromBottomRightMask
165+
):
166+
"""
167+
A mask that combines both :attr:`LowerTriangularFromBottomRightMask` and
168+
local attention.
169+
170+
A query whose distance from the final query is X cannot attend to a key
171+
whose distance to the final key is either of:
172+
173+
* less than X (i.e. "causal attention", same as :attr:`LowerTriangularFromBottomRightMask`)
174+
* greater than X + window_size (i.e. "local attention")
175+
176+
177+
.. figure:: /_static/causal_bottom_right_local.png
178+
179+
The mask from :attr:`LowerTriangularFromBottomRightLocalAttentionMask`.
180+
The green area is calculated, and the grey area is masked out.
181+
"""
182+
183+
_window_size: int
184+
185+
def __post_init__(self) -> None:
186+
if self._window_size <= 0:
187+
raise ValueError(
188+
f"Expected `window_size > 0`, but window_size={self._window_size}"
189+
)
190+
191+
def materialize(
192+
self,
193+
shape: Tuple[int, ...],
194+
dtype: torch.dtype = torch.float32,
195+
device: Union[str, torch.device] = "cpu",
196+
) -> torch.Tensor:
197+
return _materialize_causal_mask(
198+
shape,
199+
dtype=dtype,
200+
device=device,
201+
window_size=self._window_size,
202+
from_bottomright=True,
203+
)
204+
148205

149206
class LowerTriangularMaskWithTensorBias(LowerTriangularMask):
150207
"""A lower-triangular (aka causal) mask with an additive bias"""

‎xformers/ops/fmha/common.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ def attn_operator_flop(
400400

401401
class AttentionBwOpBase(AttentionOpBase):
402402
ERROR_ATOL: Mapping[torch.dtype, float] = {
403-
torch.float: 5e-4,
403+
torch.float: 6e-4,
404404
torch.half: 9e-2,
405405
torch.bfloat16: 0.7,
406406
}

‎xformers/ops/fmha/cutlass.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
BlockDiagonalCausalMask,
2121
BlockDiagonalCausalWithOffsetPaddedKeysMask,
2222
BlockDiagonalMask,
23+
LowerTriangularFromBottomRightLocalAttentionMask,
2324
LowerTriangularFromBottomRightMask,
2425
LowerTriangularMask,
2526
LowerTriangularMaskWithTensorBias,
@@ -144,6 +145,7 @@ def _custom_mask_type(bias: Optional[Union[torch.Tensor, AttentionBias]]) -> int
144145
bias,
145146
(
146147
LowerTriangularFromBottomRightMask,
148+
LowerTriangularFromBottomRightLocalAttentionMask,
147149
attn_bias.BlockDiagonalCausalFromBottomRightMask,
148150
BlockDiagonalCausalWithOffsetPaddedKeysMask,
149151
BlockDiagonalCausalLocalAttentionFromBottomRightMask,
@@ -169,6 +171,7 @@ class FwOp(AttentionFwOpBase):
169171
torch.Tensor,
170172
LowerTriangularMask,
171173
LowerTriangularFromBottomRightMask,
174+
LowerTriangularFromBottomRightLocalAttentionMask,
172175
LowerTriangularMaskWithTensorBias,
173176
BlockDiagonalMask,
174177
BlockDiagonalCausalMask,
@@ -281,6 +284,7 @@ def apply_bmhk(
281284
(
282285
BlockDiagonalCausalLocalAttentionMask,
283286
BlockDiagonalCausalLocalAttentionFromBottomRightMask,
287+
LowerTriangularFromBottomRightLocalAttentionMask,
284288
),
285289
)
286290
else None,
@@ -348,6 +352,8 @@ class BwOp(AttentionBwOpBase):
348352
torch.Tensor,
349353
LowerTriangularMask,
350354
LowerTriangularFromBottomRightMask,
355+
# TODO: Still some bugs in the BW pass for that one
356+
# LowerTriangularFromBottomRightLocalAttentionMask,
351357
# TODO: Fix handling of gradient through the fMHA autograd function
352358
# LowerTriangularMaskWithTensorBias,
353359
BlockDiagonalMask,
@@ -455,6 +461,7 @@ def apply(cls, ctx: Context, inp: Inputs, grad: torch.Tensor) -> Gradients:
455461
(
456462
BlockDiagonalCausalLocalAttentionMask,
457463
BlockDiagonalCausalLocalAttentionFromBottomRightMask,
464+
LowerTriangularFromBottomRightLocalAttentionMask,
458465
),
459466
)
460467
else None,

‎xformers/ops/fmha/flash.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
BlockDiagonalCausalLocalAttentionMask,
1919
BlockDiagonalCausalMask,
2020
BlockDiagonalMask,
21+
LowerTriangularFromBottomRightLocalAttentionMask,
2122
LowerTriangularFromBottomRightMask,
2223
LowerTriangularMask,
2324
)
@@ -285,6 +286,7 @@ def _is_causal(attn_bias: Optional[Union[torch.Tensor, AttentionBias]]) -> bool:
285286
(
286287
LowerTriangularMask,
287288
LowerTriangularFromBottomRightMask,
289+
LowerTriangularFromBottomRightLocalAttentionMask,
288290
BlockDiagonalCausalMask,
289291
BlockDiagonalCausalLocalAttentionMask,
290292
BlockDiagonalCausalFromBottomRightMask,
@@ -301,6 +303,8 @@ def _window_size(attn_bias: Optional[Union[torch.Tensor, AttentionBias]]) -> int
301303
return attn_bias._window_size or 0
302304
if isinstance(attn_bias, BlockDiagonalCausalLocalAttentionFromBottomRightMask):
303305
return attn_bias._window_size
306+
if isinstance(attn_bias, LowerTriangularFromBottomRightLocalAttentionMask):
307+
return attn_bias._window_size
304308
return 0
305309

306310

@@ -360,6 +364,7 @@ class FwOp(AttentionFwOpBase):
360364
type(None),
361365
LowerTriangularMask,
362366
LowerTriangularFromBottomRightMask,
367+
LowerTriangularFromBottomRightLocalAttentionMask,
363368
BlockDiagonalMask,
364369
BlockDiagonalCausalMask,
365370
BlockDiagonalCausalLocalAttentionMask,

0 commit comments

Comments
 (0)