Skip to content

Commit 9704aed

Browse files
committed
add ability to set flash = True on RIN
1 parent a90bc8e commit 9704aed

File tree

4 files changed

+143
-7
lines changed

4 files changed

+143
-7
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,3 +149,12 @@ sampled_images.shape # (4, 3, 128, 128)
149149
year = {2023}
150150
}
151151
```
152+
153+
```bibtex
154+
@inproceedings{dao2022flashattention,
155+
title = {Flash{A}ttention: Fast and Memory-Efficient Exact Attention with {IO}-Awareness},
156+
author = {Dao, Tri and Fu, Daniel Y. and Ermon, Stefano and Rudra, Atri and R{\'e}, Christopher},
157+
booktitle = {Advances in Neural Information Processing Systems},
158+
year = {2022}
159+
}
160+
```

rin_pytorch/attend.py

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
from functools import wraps
2+
from packaging import version
3+
from collections import namedtuple
4+
5+
import torch
6+
from torch import nn, einsum
7+
import torch.nn.functional as F
8+
9+
from einops import rearrange, reduce
10+
11+
# constants
12+
13+
FlashAttentionConfig = namedtuple('FlashAttentionConfig', ['enable_flash', 'enable_math', 'enable_mem_efficient'])
14+
15+
# helpers
16+
17+
def exists(val):
18+
return val is not None
19+
20+
def once(fn):
21+
called = False
22+
@wraps(fn)
23+
def inner(x):
24+
nonlocal called
25+
if called:
26+
return
27+
called = True
28+
return fn(x)
29+
return inner
30+
31+
print_once = once(print)
32+
33+
# main class
34+
35+
class Attend(nn.Module):
36+
def __init__(
37+
self,
38+
dropout = 0.,
39+
flash = False
40+
):
41+
super().__init__()
42+
self.dropout = dropout
43+
self.attn_dropout = nn.Dropout(dropout)
44+
45+
self.flash = flash
46+
assert not (flash and version.parse(torch.__version__) < version.parse('2.0.0')), 'in order to use flash attention, you must be using pytorch 2.0 or above'
47+
48+
# determine efficient attention configs for cuda and cpu
49+
50+
self.cpu_config = FlashAttentionConfig(True, True, True)
51+
self.cuda_config = None
52+
53+
if not torch.cuda.is_available() or not flash:
54+
return
55+
56+
device_properties = torch.cuda.get_device_properties(torch.device('cuda'))
57+
58+
if device_properties.major == 8 and device_properties.minor == 0:
59+
print_once('A100 GPU detected, using flash attention if input tensor is on cuda')
60+
self.cuda_config = FlashAttentionConfig(True, False, False)
61+
else:
62+
print_once('Non-A100 GPU detected, using math or mem efficient attention if input tensor is on cuda')
63+
self.cuda_config = FlashAttentionConfig(False, True, True)
64+
65+
def flash_attn(self, q, k, v, mask = None):
66+
_, heads, q_len, _, k_len, is_cuda, device = *q.shape, k.shape[-2], q.is_cuda, q.device
67+
68+
# Check if mask exists and expand to compatible shape
69+
# The mask is B L, so it would have to be expanded to B H N L
70+
71+
if exists(mask):
72+
mask = mask.expand(-1, heads, q_len, -1)
73+
74+
# Check if there is a compatible device for flash attention
75+
76+
config = self.cuda_config if is_cuda else self.cpu_config
77+
78+
# pytorch 2.0 flash attn: q, k, v, mask, dropout, softmax_scale
79+
80+
with torch.backends.cuda.sdp_kernel(**config._asdict()):
81+
out = F.scaled_dot_product_attention(
82+
q, k, v,
83+
attn_mask = mask,
84+
dropout_p = self.dropout if self.training else 0.
85+
)
86+
87+
return out
88+
89+
def forward(self, q, k, v, mask = None):
90+
"""
91+
einstein notation
92+
b - batch
93+
h - heads
94+
n, i, j - sequence length (base sequence length, source, target)
95+
d - feature dimension
96+
"""
97+
98+
q_len, k_len, device = q.shape[-2], k.shape[-2], q.device
99+
100+
scale = q.shape[-1] ** -0.5
101+
102+
if exists(mask) and mask.ndim != 4:
103+
mask = rearrange(mask, 'b j -> b 1 1 j')
104+
105+
if self.flash:
106+
return self.flash_attn(q, k, v, mask = mask)
107+
108+
# similarity
109+
110+
sim = einsum(f"b h i d, b h j d -> b h i j", q, k) * scale
111+
112+
# key padding mask
113+
114+
if exists(mask):
115+
sim = sim.masked_fill(~mask, -torch.finfo(sim.dtype).max)
116+
117+
# attention
118+
119+
attn = sim.softmax(dim=-1)
120+
attn = self.attn_dropout(attn)
121+
122+
# aggregate values
123+
124+
out = einsum(f"b h i j, b h j d -> b h i d", attn, v)
125+
126+
return out

rin_pytorch/rin_pytorch.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
from einops import rearrange, reduce, repeat
1919
from einops.layers.torch import Rearrange
2020

21+
from rin_pytorch.attend import Attend
22+
2123
from PIL import Image
2224
from tqdm.auto import tqdm
2325
from ema_pytorch import EMA
@@ -166,7 +168,8 @@ def __init__(
166168
dim_head = 32,
167169
norm = False,
168170
norm_context = False,
169-
time_cond_dim = None
171+
time_cond_dim = None,
172+
flash = False
170173
):
171174
super().__init__()
172175
hidden_dim = dim_head * heads
@@ -194,6 +197,8 @@ def __init__(
194197
self.to_kv = nn.Linear(dim_context, hidden_dim * 2, bias = False)
195198
self.to_out = nn.Linear(hidden_dim, dim, bias = False)
196199

200+
self.attend = Attend(flash = flash)
201+
197202
def forward(
198203
self,
199204
x,
@@ -217,12 +222,8 @@ def forward(
217222
qkv = (self.to_q(x), *self.to_kv(context).chunk(2, dim = -1))
218223
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = h), qkv)
219224

220-
q = q * self.scale
221-
222-
sim = einsum('b h i d, b h j d -> b h i j', q, k)
223-
attn = sim.softmax(dim = -1)
225+
out = self.attend(q, k, v)
224226

225-
out = einsum('b h i j, b h j d -> b h i d', attn, v)
226227
out = rearrange(out, 'b h n d -> b n (h d)')
227228
return self.to_out(out)
228229

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
setup(
44
name = 'RIN-pytorch',
55
packages = find_packages(exclude=[]),
6-
version = '0.7.4',
6+
version = '0.7.5',
77
license='MIT',
88
description = 'RIN - Recurrent Interface Network - Pytorch',
99
author = 'Phil Wang',

0 commit comments

Comments
 (0)