Skip to content
Open
Show file tree
Hide file tree
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
26 changes: 26 additions & 0 deletions tests/models/test_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import torch

from the_well.benchmark.models import AViT
from the_well.benchmark.models.avit import AxialAttentionBlock


@pytest.mark.parametrize("dim_in", [1, 3, 5])
Expand All @@ -27,3 +28,28 @@ def test_avit(dim_in, dim_out, n_spatial_dims, spatial_resolution):
*spatial_resolution,
dim_out,
)


@pytest.mark.parametrize("n_spatial_dims", [2, 3])
def test_axial_attention_mixes_along_every_axis(n_spatial_dims):
"""A change to one token must reach every token on its axis-aligned lines."""
torch.manual_seed(0)
block = AxialAttentionBlock(
hidden_dim=48, num_heads=2, n_spatial_dims=n_spatial_dims
).eval()
block.gamma.data.fill_(1.0) # layer scale starts at 1e-6
grid = (8, 4) if n_spatial_dims == 2 else (6, 4, 5)
x = torch.randn(1, *grid, 48)
index = (5, 3) if n_spatial_dims == 2 else (4, 2, 3)
x_perturbed = x.clone()
# A random vector, not a constant shift, which the pre-LayerNorm would remove
x_perturbed[(0, *index)] += torch.randn(48)
with torch.no_grad():
changed = (block(x_perturbed) - block(x)).abs().amax(-1)[0] > 1e-4

expected = torch.zeros(grid, dtype=torch.bool)
for axis in range(n_spatial_dims):
line = list(index)
line[axis] = slice(None)
expected[tuple(line)] = True
assert torch.equal(changed, expected)
2 changes: 1 addition & 1 deletion the_well/benchmark/models/avit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def __init__(
self.head_split = "b h w (he c) -> b h w he c"
self.spatial_permutations = [
("b h w he c -> b h he w c", "b h he w c -> b h w (he c)"),
("b h he w c -> b h w he c", "b h w he c -> b h w (he c)"),
("b h he w c -> b w he h c", "b w he h c -> b h w (he c)"),
]

elif n_spatial_dims == 3:
Expand Down