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

Flash attention #7977

Merged
merged 12 commits into from
Aug 6, 2024
9 changes: 7 additions & 2 deletions monai/networks/blocks/crossattention.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,13 @@ def forward(self, x: torch.Tensor, context: Optional[torch.Tensor] = None):

if self.use_flash_attention:
x = torch.nn.functional.scaled_dot_product_attention(
q, k, v, scale=self.scale, dropout_p=self.dropout_rate, is_causal=self.causal
).contiguous()
query=q.transpose(1, 2),
KumoLiu marked this conversation as resolved.
Show resolved Hide resolved
key=k.transpose(1, 2),
value=v.transpose(1, 2),
scale=self.scale,
dropout_p=self.dropout_rate,
is_causal=self.causal,
).transpose(1, 2)
else:
att_mat = torch.einsum("blxd,blyd->blxy", q, k) * self.scale
# apply relative positional embedding if defined
Expand Down
9 changes: 7 additions & 2 deletions monai/networks/blocks/selfattention.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,13 @@ def forward(self, x):

if self.use_flash_attention:
x = F.scaled_dot_product_attention(
q, k, v, scale=self.scale, dropout_p=self.dropout_rate, is_causal=self.causal
)
query=q.transpose(1, 2),
KumoLiu marked this conversation as resolved.
Show resolved Hide resolved
key=k.transpose(1, 2),
value=v.transpose(1, 2),
scale=self.scale,
dropout_p=self.dropout_rate,
is_causal=self.causal,
).transpose(1, 2)
else:
att_mat = torch.einsum("blxd,blyd->blxy", q, k) * self.scale

Expand Down
Loading