Skip to content

Commit 1713e89

Browse files
committed
Add SwinUNETR flash attention equivalence test
Assert the SwinViT encoder features with use_flash_attention=True match the default path, in float64 for a tight bit-level comparison. Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk>
1 parent 8ffd186 commit 1713e89

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

tests/networks/nets/test_swin_unetr.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,19 @@ def test_invalid_input_shape(self):
101101
with self.assertRaises(ValueError):
102102
net_2d(torch.randn(1, 1, 48, 33)) # 33 is not divisible by 32
103103

104+
@skipUnless(has_einops, "Requires einops")
105+
def test_flash_attention(self):
106+
input_param = {"in_channels": 1, "out_channels": 2, "feature_size": 12, "spatial_dims": 3}
107+
net_ref = SwinUNETR(use_flash_attention=False, **input_param).double()
108+
net_flash = SwinUNETR(use_flash_attention=True, **input_param).double()
109+
net_flash.load_state_dict(net_ref.state_dict())
110+
x = torch.randn(1, 1, 64, 64, 64, dtype=torch.float64)
111+
with eval_mode(net_ref, net_flash):
112+
ref = net_ref.swinViT(x, net_ref.normalize)
113+
out = net_flash.swinViT(x, net_flash.normalize)
114+
for a, b in zip(ref, out, strict=True):
115+
assert_allclose(a, b, atol=1e-6, rtol=1e-6, type_test=False)
116+
104117
def test_patch_merging(self):
105118
dim = 10
106119
t = PatchMerging(dim)(torch.zeros((1, 21, 20, 20, dim)))

0 commit comments

Comments
 (0)