|
| 1 | +# Copyright (c) MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import unittest |
| 15 | +from unittest import skipUnless |
| 16 | + |
| 17 | +import torch |
| 18 | +from parameterized import parameterized |
| 19 | + |
| 20 | +from monai.networks import eval_mode |
| 21 | +from monai.networks.blocks.cablock import CABlock, FeedForward |
| 22 | +from monai.utils import optional_import |
| 23 | +from tests.test_utils import SkipIfBeforePyTorchVersion, assert_allclose |
| 24 | + |
| 25 | +einops, has_einops = optional_import("einops") |
| 26 | + |
| 27 | + |
| 28 | +TEST_CASES_CAB = [] |
| 29 | +for spatial_dims in [2, 3]: |
| 30 | + for dim in [32, 64, 128]: |
| 31 | + for num_heads in [2, 4, 8]: |
| 32 | + for bias in [True, False]: |
| 33 | + test_case = [ |
| 34 | + { |
| 35 | + "spatial_dims": spatial_dims, |
| 36 | + "dim": dim, |
| 37 | + "num_heads": num_heads, |
| 38 | + "bias": bias, |
| 39 | + "flash_attention": False, |
| 40 | + }, |
| 41 | + (2, dim, *([16] * spatial_dims)), |
| 42 | + (2, dim, *([16] * spatial_dims)), |
| 43 | + ] |
| 44 | + TEST_CASES_CAB.append(test_case) |
| 45 | + |
| 46 | + |
| 47 | +TEST_CASES_FEEDFORWARD = [ |
| 48 | + # Test different spatial dims, dimensions and expansion factors |
| 49 | + [{"spatial_dims": 2, "dim": 64, "ffn_expansion_factor": 2.0, "bias": True}, (2, 64, 32, 32)], |
| 50 | + [{"spatial_dims": 3, "dim": 128, "ffn_expansion_factor": 1.5, "bias": False}, (2, 128, 16, 16, 16)], |
| 51 | + [{"spatial_dims": 2, "dim": 256, "ffn_expansion_factor": 1.0, "bias": True}, (1, 256, 64, 64)], |
| 52 | +] |
| 53 | + |
| 54 | + |
| 55 | +class TestFeedForward(unittest.TestCase): |
| 56 | + |
| 57 | + @parameterized.expand(TEST_CASES_FEEDFORWARD) |
| 58 | + def test_shape(self, input_param, input_shape): |
| 59 | + net = FeedForward(**input_param) |
| 60 | + with eval_mode(net): |
| 61 | + result = net(torch.randn(input_shape)) |
| 62 | + self.assertEqual(result.shape, input_shape) |
| 63 | + |
| 64 | + def test_gating_mechanism(self): |
| 65 | + net = FeedForward(spatial_dims=2, dim=32, ffn_expansion_factor=2.0, bias=True) |
| 66 | + x = torch.ones(1, 32, 16, 16) |
| 67 | + out = net(x) |
| 68 | + self.assertNotEqual(torch.sum(out), torch.sum(x)) |
| 69 | + |
| 70 | + |
| 71 | +class TestCABlock(unittest.TestCase): |
| 72 | + |
| 73 | + @parameterized.expand(TEST_CASES_CAB) |
| 74 | + @skipUnless(has_einops, "Requires einops") |
| 75 | + def test_shape(self, input_param, input_shape, expected_shape): |
| 76 | + net = CABlock(**input_param) |
| 77 | + with eval_mode(net): |
| 78 | + result = net(torch.randn(input_shape)) |
| 79 | + self.assertEqual(result.shape, expected_shape) |
| 80 | + |
| 81 | + @skipUnless(has_einops, "Requires einops") |
| 82 | + def test_invalid_spatial_dims(self): |
| 83 | + with self.assertRaises(ValueError): |
| 84 | + CABlock(spatial_dims=4, dim=64, num_heads=4, bias=True) |
| 85 | + |
| 86 | + @SkipIfBeforePyTorchVersion((2, 0)) |
| 87 | + @skipUnless(has_einops, "Requires einops") |
| 88 | + def test_flash_attention(self): |
| 89 | + device = "cuda" if torch.cuda.is_available() else "cpu" |
| 90 | + block = CABlock(spatial_dims=2, dim=64, num_heads=4, bias=True, flash_attention=True).to(device) |
| 91 | + x = torch.randn(2, 64, 32, 32).to(device) |
| 92 | + output = block(x) |
| 93 | + self.assertEqual(output.shape, x.shape) |
| 94 | + |
| 95 | + @skipUnless(has_einops, "Requires einops") |
| 96 | + def test_temperature_parameter(self): |
| 97 | + block = CABlock(spatial_dims=2, dim=64, num_heads=4, bias=True) |
| 98 | + self.assertTrue(isinstance(block.temperature, torch.nn.Parameter)) |
| 99 | + self.assertEqual(block.temperature.shape, (4, 1, 1)) |
| 100 | + |
| 101 | + @skipUnless(has_einops, "Requires einops") |
| 102 | + def test_qkv_transformation_2d(self): |
| 103 | + block = CABlock(spatial_dims=2, dim=64, num_heads=4, bias=True) |
| 104 | + x = torch.randn(2, 64, 32, 32) |
| 105 | + qkv = block.qkv(x) |
| 106 | + self.assertEqual(qkv.shape, (2, 192, 32, 32)) |
| 107 | + |
| 108 | + @skipUnless(has_einops, "Requires einops") |
| 109 | + def test_qkv_transformation_3d(self): |
| 110 | + block = CABlock(spatial_dims=3, dim=64, num_heads=4, bias=True) |
| 111 | + x = torch.randn(2, 64, 16, 16, 16) |
| 112 | + qkv = block.qkv(x) |
| 113 | + self.assertEqual(qkv.shape, (2, 192, 16, 16, 16)) |
| 114 | + |
| 115 | + @SkipIfBeforePyTorchVersion((2, 0)) |
| 116 | + @skipUnless(has_einops, "Requires einops") |
| 117 | + def test_flash_vs_normal_attention(self): |
| 118 | + device = "cuda" if torch.cuda.is_available() else "cpu" |
| 119 | + block_flash = CABlock(spatial_dims=2, dim=64, num_heads=4, bias=True, flash_attention=True).to(device) |
| 120 | + block_normal = CABlock(spatial_dims=2, dim=64, num_heads=4, bias=True, flash_attention=False).to(device) |
| 121 | + |
| 122 | + block_normal.load_state_dict(block_flash.state_dict()) |
| 123 | + |
| 124 | + x = torch.randn(2, 64, 32, 32).to(device) |
| 125 | + with torch.no_grad(): |
| 126 | + out_flash = block_flash(x) |
| 127 | + out_normal = block_normal(x) |
| 128 | + |
| 129 | + assert_allclose(out_flash, out_normal, atol=1e-4) |
| 130 | + |
| 131 | + @skipUnless(has_einops, "Requires einops") |
| 132 | + def test_deterministic_small_input(self): |
| 133 | + block = CABlock(spatial_dims=2, dim=2, num_heads=1, bias=False) |
| 134 | + with torch.no_grad(): |
| 135 | + block.qkv.conv.weight.data.fill_(1.0) |
| 136 | + block.qkv_dwconv.conv.weight.data.fill_(1.0) |
| 137 | + block.temperature.data.fill_(1.0) |
| 138 | + block.project_out.conv.weight.data.fill_(1.0) |
| 139 | + |
| 140 | + x = torch.tensor([[[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]], dtype=torch.float32) |
| 141 | + |
| 142 | + output = block(x) |
| 143 | + # Channel attention: sum([1..8]) * (qkv_conv=1) * (dwconv=1) * (attn_weights=1) * (proj=1) = 36 * 2 = 72 |
| 144 | + expected = torch.full_like(x, 72.0) |
| 145 | + |
| 146 | + assert_allclose(output, expected, atol=1e-6) |
| 147 | + |
| 148 | + |
| 149 | +if __name__ == "__main__": |
| 150 | + unittest.main() |
0 commit comments