Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

minor change to align with paper for better readliness #3

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions flash_pytorch/flash_pytorch.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ def forward(
j - sequence dimension (target)
"""

b, n, device, g = x.shape[0], x.shape[-2], x.device, self.group_size
b, n, device, c = x.shape[0], x.shape[-2], x.device, self.group_size

# prenorm

Expand Down Expand Up @@ -299,24 +299,23 @@ def forward(

# padding for groups

padding = padding_to_multiple_of(n, g)
padding = padding_to_multiple_of(n, c)

if padding > 0:
quad_q, quad_k, lin_q, lin_k, v = map(lambda t: F.pad(t, (0, 0, 0, padding), value = 0.), (quad_q, quad_k, lin_q, lin_k, v))

mask = default(mask, torch.ones((b, n), device = device, dtype = torch.bool))
mask = F.pad(mask, (0, padding), value = False)

# group along sequence

quad_q, quad_k, lin_q, lin_k, v = map(lambda t: rearrange(t, 'b (g n) d -> b g n d', n = self.group_size), (quad_q, quad_k, lin_q, lin_k, v))
quad_q, quad_k, lin_q, lin_k, v = map(lambda t: rearrange(t, 'b (g c) d -> b g c d', c = c), (quad_q, quad_k, lin_q, lin_k, v))

if exists(mask):
mask = rearrange(mask, 'b (g j) -> b g 1 j', j = g)
mask = rearrange(mask, 'b (g c) -> b g 1 c', c = c)

# calculate quadratic attention output

sim = einsum('... i d, ... j d -> ... i j', quad_q, quad_k) / g
sim = einsum('... i d, ... j d -> ... i j', quad_q, quad_k) / c

sim = sim + self.rel_pos_bias(sim)

Expand All @@ -327,15 +326,15 @@ def forward(
attn = attn.masked_fill(~mask, 0.)

if self.causal:
causal_mask = torch.ones((g, g), dtype = torch.bool, device = device).triu(1)
causal_mask = torch.ones((c,c), dtype = torch.bool, device = device).triu(1)
attn = attn.masked_fill(causal_mask, 0.)

quad_out = einsum('... i j, ... j d -> ... i d', attn, v)

# calculate linear attention output

if self.causal:
lin_kv = einsum('b g n d, b g n e -> b g d e', lin_k, v) / g
lin_kv = einsum('b g n d, b g n e -> b g d e', lin_k, v) / c

# exclusive cumulative sum along group dimension

Expand Down