diff --git a/tests/models/test_transformer.py b/tests/models/test_transformer.py index 405a0602..12259672 100755 --- a/tests/models/test_transformer.py +++ b/tests/models/test_transformer.py @@ -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]) @@ -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) diff --git a/the_well/benchmark/models/avit/__init__.py b/the_well/benchmark/models/avit/__init__.py index ce2de96e..02ef85c2 100755 --- a/the_well/benchmark/models/avit/__init__.py +++ b/the_well/benchmark/models/avit/__init__.py @@ -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: