-
Notifications
You must be signed in to change notification settings - Fork 3
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
Feature: Heterogeneous Normalized Attention #153
Draft
JakobEliasWagner
wants to merge
4
commits into
main
Choose a base branch
from
feature/heterogeneous-normalized-attention-block
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
86 changes: 86 additions & 0 deletions
86
src/continuiti/networks/heterogeneous_normalized_attention.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
""" | ||
`continuiti.networks.heterogeneous_normalized_attention` | ||
|
||
Heterogeneous normalized attention block introduced by Hao et al. (https://proceedings.mlr.press/v202/hao23c). | ||
""" | ||
|
||
import torch | ||
import torch.nn as nn | ||
from torch.nn.functional import softmax | ||
from typing import Optional | ||
|
||
from .attention import UniformMaskAttention | ||
|
||
|
||
class HeterogeneousNormalizedAttention(UniformMaskAttention): | ||
r"""Heterogeneous normalized attention with uniform masks. | ||
|
||
Computes the normalization coefficient alpha for attention mechanisms, as proposed by Hao et al. in "GNOT: A | ||
General Neural Operator Transformer for Operator Learning" (https://proceedings.mlr.press/v202/hao23c). The | ||
attention score is calculated by normalizing the keys and queries | ||
$$\tilde{q}_i = Softmax(\frac{\exp(q_{i,j})}{\sum_j\exp(q_{i,j})}$$, | ||
$$\tilde{k}_i = Softmax(\frac{\exp(k_{i,j})}{\sum_j\exp(k_{i,j})}$$, and then calculating the attention without | ||
softmax using $$z_t=\sum_i \frac{\tilde{q}_t \cdot \tilde{k}_i}{\sum_j \tilde{q}_t \cdot \tilde{k}_j}\cdot v_i$$. | ||
The computational cost for this is O((M+N)n_e^2) (M=number of keys/values, N=number of queries, n_e=embedding_dim), | ||
now is linear with respect to the sequence length. | ||
|
||
Args: | ||
tau: Temperature parameter controlling the sharpness of the softmax operation. | ||
""" | ||
|
||
def __init__(self, tau: float = 1.0, dropout_p: float = 0.0): | ||
super().__init__() | ||
self.tau = tau | ||
self.dropout = nn.Dropout(p=dropout_p) | ||
|
||
def forward( | ||
self, | ||
query: torch.Tensor, | ||
key: torch.Tensor, | ||
value: torch.Tensor, | ||
attn_mask: Optional[torch.Tensor] = None, | ||
) -> torch.Tensor: | ||
r"""Forward pass. | ||
Args: | ||
query: Tensor of shape (batch_size, ..., d_q, embedding_dim). | ||
key: Tensor of shape (batch_size, ..., d_kv, embedding_dim). | ||
value: Tensor of shape (batch_size, ..., d_kv, embedding_dim). | ||
attn_mask: Attention mask of shape (batch_size, ..., d_kv). A boolean mask where a True indicates that | ||
a value should be taken into consideration in the calculations. | ||
Returns: | ||
Attention output of shape (batch_size, ..., d_q, e_dim). | ||
""" | ||
assert ( | ||
query.ndim == key.ndim | ||
), "Number of dimensions in queries and keys should match." | ||
assert ( | ||
query.ndim == value.ndim | ||
), "Number of dimensions in queries and values should match." | ||
|
||
if attn_mask is not None: | ||
attn_mask = attn_mask.unsqueeze(-1) | ||
key = torch.masked_fill(key, attn_mask.logical_not(), float("-inf")) | ||
value = torch.masked_fill(value, attn_mask.logical_not(), 0.0) | ||
|
||
q_tilde = softmax(query, dim=-1) | ||
if attn_mask is not None: | ||
q_tilde = torch.nan_to_num( | ||
q_tilde, nan=0.0 | ||
) # masking might ignore queries entirely resulting in nan in softmax | ||
|
||
k_tilde = softmax(key / self.tau, dim=-1) | ||
if attn_mask is not None: | ||
k_tilde = torch.nan_to_num( | ||
k_tilde, nan=0.0 | ||
) # masking might ignore keys entirely resulting in nan in softmax | ||
|
||
alpha = torch.matmul(q_tilde, k_tilde.transpose(-1, -2)) | ||
alpha = torch.sum(alpha, dim=-1, keepdim=True) | ||
if attn_mask is not None: | ||
alpha[alpha == 0.0] = 1.0 # numerical stability | ||
|
||
mat = k_tilde * value | ||
mat = self.dropout(mat) | ||
mat = torch.sum(mat, dim=-2, keepdim=True) | ||
|
||
return q_tilde * mat / alpha |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
import pytest | ||
import torch | ||
from torch.nn.functional import scaled_dot_product_attention | ||
|
||
from continuiti.networks import HeterogeneousNormalizedAttention | ||
|
||
|
||
@pytest.fixture(scope="module") | ||
def random_query_key_value_pair(): | ||
batch_size = 3 | ||
query_size = 5 | ||
key_val_size = 7 | ||
hidden_dim = 11 | ||
|
||
query = torch.rand(batch_size, query_size, hidden_dim) | ||
key = torch.rand(batch_size, key_val_size, hidden_dim) | ||
value = torch.rand(batch_size, key_val_size, hidden_dim) | ||
|
||
return query, key, value | ||
|
||
|
||
class TestHeterogeneousNormalized: | ||
def test_can_initialize(self): | ||
_ = HeterogeneousNormalizedAttention() | ||
assert True | ||
|
||
def test_shape_correct(self, random_query_key_value_pair): | ||
query, key, value = random_query_key_value_pair | ||
|
||
attn = HeterogeneousNormalizedAttention() | ||
|
||
out = attn(query, key, value) | ||
gt_out = scaled_dot_product_attention(query, key, value) | ||
|
||
assert out.shape == gt_out.shape | ||
|
||
def test_gradient_flow(self, random_query_key_value_pair): | ||
query, key, value = random_query_key_value_pair | ||
query.requires_grad = True | ||
key.requires_grad = True | ||
value.requires_grad = True | ||
|
||
attn = HeterogeneousNormalizedAttention() | ||
|
||
out = attn(query, key, value) | ||
|
||
out.sum().backward() | ||
|
||
assert query.grad is not None, "Gradients not flowing to query" | ||
assert key.grad is not None, "Gradients not flowing to key" | ||
assert value.grad is not None, "Gradients not flowing to value" | ||
|
||
def test_zero_input(self, random_query_key_value_pair): | ||
query, key, value = random_query_key_value_pair | ||
attn = HeterogeneousNormalizedAttention() | ||
out = attn(query, key, torch.zeros(value.shape)) | ||
assert torch.allclose(torch.zeros(out.shape), out) | ||
|
||
def test_mask_forward(self, random_query_key_value_pair): | ||
query, key, value = random_query_key_value_pair | ||
attn = HeterogeneousNormalizedAttention() | ||
|
||
# masks in the operator setting should be always block tensors with the upper left block of the last two | ||
# dimensions being True. The dimensions of the True block corresponds to the numbers of sensors and evaluations. | ||
mask = [] | ||
mask = torch.rand(query.size(0), key.size(1)) >= 0.2 | ||
|
||
out = attn(query, key, value, mask) | ||
|
||
assert isinstance(out, torch.Tensor) | ||
|
||
def test_mask_correct(self, random_query_key_value_pair): | ||
query, key, value = random_query_key_value_pair | ||
attn = HeterogeneousNormalizedAttention() | ||
|
||
out_gt = attn(query, key, value) | ||
|
||
key_rand = torch.rand(key.shape) | ||
key_masked = torch.cat([key, key_rand], dim=1) | ||
|
||
value_rand = torch.rand(value.shape) | ||
value_masked = torch.cat([value, value_rand], dim=1) | ||
|
||
true_mask = torch.ones(value.size(0), value.size(1), dtype=torch.bool) | ||
attn_mask = torch.cat([true_mask, ~true_mask], dim=1) | ||
|
||
out_masked = attn(query, key_masked, value_masked, attn_mask) | ||
|
||
assert torch.allclose(out_gt, out_masked) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Math does not render well in docs