Skip to content

Commit 21ab521

Browse files
BakaryGibbaclaude
andauthored
Add spatial and channel-spatial SE layers and use them in Quicknat (#9278)
Fixes #9276. ### Description `Quicknat` imported `SpatialSELayer` and `ChannelSpatialSELayer` from `squeeze_and_excitation`, which is not on PyPI. The SSE and CSSE options could not be used, and the test class that covers them was always skipped. - Add `SpatialSELayer` (sSE) and `ChannelSpatialSELayer` (scSE) to `monai/networks/blocks/squeeze_and_excitation.py`, following Roy et al., "Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks" (https://arxiv.org/abs/1803.02579). Both support 1D, 2D and 3D. sSE is a 1x1 convolution to one channel followed by a sigmoid. scSE takes the element-wise maximum of `ChannelSELayer` and `SpatialSELayer`, as in the package Quicknat was written against. - Export both from `monai.networks.blocks` and add them to `docs/source/networks.rst`. - `Quicknat.get_selayer` uses the new layers, and the `optional_import` is removed. - `tests/networks/nets/test_quicknat.py`: the `skipUnless` is removed, so the CSE, SSE and CSSE shape tests now run. - `tests/networks/blocks/test_se_blocks.py`: shape, value and TorchScript tests for both new layers. One thing came up while doing this. With the skip removed, `TestQuicknat.test_script` fails because `Quicknat` was never TorchScript compatible: `ConvConcatDenseBlock.forward` uses `continue` inside a loop over child modules, and `Encoder`/`Decoder` call `super().forward()`. That needs a refactor of those blocks, so I've kept it out of this PR and marked the test with `unittest.skip` and the reason. I'm happy to open a separate issue for it, or follow up with a PR. Note on checkpoints: Quicknat models saved with `se_block="SSE"` or `"CSSE"` against the external package use different `state_dict` keys (`cSE`/`sSE`, and `fc1`/`fc2` inside the channel branch) and will not load strictly. That package was never on PyPI or a MONAI dependency, so this only affects source installs of it. `se_block="CSE"` and `None` are unchanged. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [x] New tests added to cover the changes. - [x] In-line docstrings updated. - [x] Documentation updated. Tested locally (CPU, PyTorch 2.15.0): `python -m unittest tests.networks.nets.test_quicknat tests.networks.blocks.test_se_blocks tests.networks.blocks.test_se_block` gives 48 tests OK, 1 skipped (`test_script` above). `ruff check` is clean. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Bakary Gibba <162592884+BakaryGibba@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 202d9f7 commit 21ab521

7 files changed

Lines changed: 188 additions & 23 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ All notable changes to MONAI are documented in this file.
44
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
55

66
## [Unreleased]
7+
### Added
8+
* `SpatialSELayer` and `ChannelSpatialSELayer` in `monai.networks.blocks`: spatial (sSE) and concurrent spatial and channel (scSE) squeeze-and-excitation layers for 1D, 2D and 3D inputs, based on ["Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks"](https://arxiv.org/abs/1803.02579). (#9278)
9+
### Fixed
10+
* `Quicknat` no longer depends on the unpublished `squeeze_and_excitation` package for `se_block="SSE"` and `"CSSE"`. Checkpoints saved with that package for these two options use different `state_dict` keys and will not load strictly. (#9276)
11+
* `ChannelSELayer` raises `ValueError` instead of `ZeroDivisionError` when `r=0`.
712

813
## [1.6.2] - 2026-11-18
914
### Addressed Security Advisories

‎docs/source/networks.rst‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,16 @@ Blocks
165165
.. autoclass:: ResidualSELayer
166166
:members:
167167

168+
`Spatial Squeeze-and-Excitation`
169+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170+
.. autoclass:: SpatialSELayer
171+
:members:
172+
173+
`Channel-Spatial Squeeze-and-Excitation`
174+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
175+
.. autoclass:: ChannelSpatialSELayer
176+
:members:
177+
168178
`Squeeze-and-Excitation Block`
169179
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
170180
.. autoclass:: SEBlock

‎monai/networks/blocks/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,11 +44,13 @@
4444
from .spatialattention import SpatialAttentionBlock
4545
from .squeeze_and_excitation import (
4646
ChannelSELayer,
47+
ChannelSpatialSELayer,
4748
ResidualSELayer,
4849
SEBlock,
4950
SEBottleneck,
5051
SEResNetBottleneck,
5152
SEResNeXtBottleneck,
53+
SpatialSELayer,
5254
)
5355
from .transformerblock import TransformerBlock
5456
from .unetr_block import UnetrBasicBlock, UnetrPrUpBlock, UnetrUpBlock

‎monai/networks/blocks/squeeze_and_excitation.py‎

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ def __init__(
5858
pool_type = Pool[Pool.ADAPTIVEAVG, spatial_dims]
5959
self.avg_pool = pool_type(1) # spatial size (1, 1, ...)
6060

61-
channels = int(in_channels // r)
61+
channels = int(in_channels // r) if r > 0 else 0
6262
if channels <= 0:
6363
raise ValueError(f"r must be positive and smaller than in_channels, got r={r} in_channels={in_channels}.")
6464

@@ -127,6 +127,71 @@ def __init__(
127127
)
128128

129129

130+
class SpatialSELayer(nn.Module):
131+
"""
132+
Channel squeeze and spatial excitation (sSE) block based on:
133+
"Roy et al., Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks,
134+
https://arxiv.org/abs/1803.02579".
135+
136+
A 1x1 convolution squeezes the channels into one map, which is passed through a sigmoid and used to
137+
recalibrate every spatial location of the input.
138+
139+
Args:
140+
spatial_dims: number of spatial dimensions, could be 1, 2, or 3.
141+
in_channels: number of input channels.
142+
"""
143+
144+
def __init__(self, spatial_dims: int, in_channels: int) -> None:
145+
super().__init__()
146+
conv_type = Conv[Conv.CONV, spatial_dims]
147+
self.conv = conv_type(in_channels, 1, kernel_size=1)
148+
self.sigmoid = nn.Sigmoid()
149+
150+
def forward(self, x: torch.Tensor) -> torch.Tensor:
151+
"""
152+
Args:
153+
x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]).
154+
155+
Returns:
156+
The input recalibrated per spatial location, with the same shape as ``x``.
157+
"""
158+
return x * self.sigmoid(self.conv(x))
159+
160+
161+
class ChannelSpatialSELayer(nn.Module):
162+
"""
163+
Concurrent spatial and channel squeeze and excitation (scSE) block based on:
164+
"Roy et al., Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks,
165+
https://arxiv.org/abs/1803.02579".
166+
167+
The outputs of :py:class:`ChannelSELayer` and :py:class:`SpatialSELayer` are combined with an
168+
element-wise maximum.
169+
170+
Args:
171+
spatial_dims: number of spatial dimensions, could be 1, 2, or 3.
172+
in_channels: number of input channels.
173+
r: the reduction ratio of the channel squeeze. Defaults to 2.
174+
175+
Raises:
176+
ValueError: When ``r`` is nonpositive or larger than ``in_channels``.
177+
"""
178+
179+
def __init__(self, spatial_dims: int, in_channels: int, r: int = 2) -> None:
180+
super().__init__()
181+
self.cse = ChannelSELayer(spatial_dims=spatial_dims, in_channels=in_channels, r=r)
182+
self.sse = SpatialSELayer(spatial_dims=spatial_dims, in_channels=in_channels)
183+
184+
def forward(self, x: torch.Tensor) -> torch.Tensor:
185+
"""
186+
Args:
187+
x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]).
188+
189+
Returns:
190+
The element-wise maximum of the channel and spatial SE outputs, with the same shape as ``x``.
191+
"""
192+
return torch.max(self.cse(x), self.sse(x))
193+
194+
130195
class SEBlock(nn.Module):
131196
"""
132197
Residual module enhanced with Squeeze-and-Excitation::

‎monai/networks/nets/quicknat.py‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,6 @@
2222
from monai.networks.layers.factories import Act, Norm
2323
from monai.networks.layers.simplelayers import SkipConnection
2424
from monai.networks.layers.utils import get_dropout_layer, get_pool_layer
25-
from monai.utils import optional_import
26-
27-
# Lazy import to avoid dependency
28-
se1, flag = optional_import("squeeze_and_excitation")
2925

3026
__all__ = ["Quicknat"]
3127

@@ -347,6 +343,10 @@ class Quicknat(nn.Module):
347343
pool: kernel size of the pooling layer,
348344
stride_pool: stride for the pooling layer.
349345
se_block: Squeeze and Excite block type to include. Use ``None`` or ``"None"`` to disable it; valid enabled values are ``"CSE"``, ``"SSE"``, and ``"CSSE"``.
346+
``"SSE"`` and ``"CSSE"`` now use :py:class:`monai.networks.blocks.SpatialSELayer` and
347+
:py:class:`monai.networks.blocks.ChannelSpatialSELayer` instead of the external
348+
``squeeze_and_excitation`` package, so weights saved with that package for these two options
349+
have different ``state_dict`` keys and will not load with ``strict=True``.
350350
drop_out: dropout ratio. Defaults to no dropout.
351351
act: activation type and arguments. Defaults to PReLU.
352352
norm: feature normalization type and arguments. Defaults to instance norm.
@@ -434,19 +434,14 @@ def get_selayer(self, n_filters, se_block_type="None"):
434434
Args:
435435
n_filters: encoding half of the layer
436436
se_block_type: defaults to None. Valid options are None, CSE, SSE, CSSE
437-
Returns: Appropriate SEBlock. SSE and CSSE not implemented in Monai yet.
437+
Returns: Appropriate SEBlock, or None when ``se_block_type`` is None or "None".
438438
"""
439439
if se_block_type == "CSE":
440440
return se.ChannelSELayer(2, n_filters)
441-
# not implemented in squeeze_and_excitation in monai use other squeeze_and_excitation import:
442-
elif se_block_type == "SSE" or se_block_type == "CSSE":
443-
# Throw error if squeeze_and_excitation is not installed
444-
if not flag:
445-
raise ImportError("Please install squeeze_and_excitation locally to use SpatialSELayer")
446-
if se_block_type == "SSE":
447-
return se1.SpatialSELayer(n_filters)
448-
else:
449-
return se1.ChannelSpatialSELayer(n_filters)
441+
elif se_block_type == "SSE":
442+
return se.SpatialSELayer(2, n_filters)
443+
elif se_block_type == "CSSE":
444+
return se.ChannelSpatialSELayer(2, n_filters)
450445
else:
451446
return None
452447

‎tests/networks/blocks/test_se_blocks.py‎

Lines changed: 93 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
from parameterized import parameterized
1818

1919
from monai.networks import eval_mode
20-
from monai.networks.blocks import ChannelSELayer, ResidualSELayer
20+
from monai.networks.blocks import ChannelSELayer, ChannelSpatialSELayer, ResidualSELayer, SpatialSELayer
2121
from tests.test_utils import test_script_save
2222

2323
TEST_CASES = [ # single channel 3D, batch 16
@@ -54,9 +54,15 @@ def test_script(self):
5454
test_data = torch.randn(input_shape)
5555
test_script_save(net, test_data)
5656

57-
def test_ill_arg(self):
57+
@parameterized.expand([[100], [0], [-1]])
58+
def test_ill_arg(self, r):
59+
"""Verify a nonpositive reduction ratio, or one larger than the channel count, is rejected.
60+
61+
Args:
62+
r: the invalid reduction ratio.
63+
"""
5864
with self.assertRaises(ValueError):
59-
ChannelSELayer(spatial_dims=1, in_channels=4, r=100)
65+
ChannelSELayer(spatial_dims=1, in_channels=4, r=r)
6066

6167

6268
class TestResidualSELayer(unittest.TestCase):
@@ -74,5 +80,89 @@ def test_script(self):
7480
test_script_save(net, test_data)
7581

7682

83+
TEST_CASES_SPATIAL = [
84+
[{"spatial_dims": 1, "in_channels": 4}, (16, 4, 63), (16, 4, 63)],
85+
[{"spatial_dims": 2, "in_channels": 4}, (7, 4, 64, 48), (7, 4, 64, 48)],
86+
[{"spatial_dims": 3, "in_channels": 10}, (2, 10, 32, 24, 48), (2, 10, 32, 24, 48)],
87+
]
88+
89+
90+
class TestSpatialSELayer(unittest.TestCase):
91+
"""Test the channel squeeze and spatial excitation layer."""
92+
93+
@parameterized.expand(TEST_CASES_SPATIAL)
94+
def test_shape(self, input_param, input_shape, expected_shape):
95+
"""Verify the output keeps the input shape.
96+
97+
Args:
98+
input_param: constructor arguments for the layer.
99+
input_shape: shape of the random input tensor.
100+
expected_shape: expected shape of the output.
101+
"""
102+
net = SpatialSELayer(**input_param)
103+
with eval_mode(net):
104+
result = net(torch.randn(input_shape))
105+
self.assertEqual(result.shape, expected_shape)
106+
107+
def test_value(self):
108+
"""The input is scaled by the sigmoid of a single-channel 1x1 convolution."""
109+
net = SpatialSELayer(spatial_dims=2, in_channels=3)
110+
x = torch.randn(2, 3, 8, 8)
111+
with eval_mode(net):
112+
result = net(x)
113+
expected = x * torch.sigmoid(net.conv(x))
114+
self.assertEqual(net.conv.out_channels, 1)
115+
self.assertTrue(torch.allclose(result, expected))
116+
117+
def test_script(self):
118+
"""Verify the layer can be saved with TorchScript."""
119+
input_param, input_shape, _ = TEST_CASES_SPATIAL[1]
120+
net = SpatialSELayer(**input_param)
121+
test_script_save(net, torch.randn(input_shape))
122+
123+
124+
class TestChannelSpatialSELayer(unittest.TestCase):
125+
"""Test the concurrent spatial and channel squeeze and excitation layer."""
126+
127+
@parameterized.expand([[{**p, "r": 2}, i, o] for p, i, o in TEST_CASES_SPATIAL])
128+
def test_shape(self, input_param, input_shape, expected_shape):
129+
"""Verify the output keeps the input shape.
130+
131+
Args:
132+
input_param: constructor arguments for the layer.
133+
input_shape: shape of the random input tensor.
134+
expected_shape: expected shape of the output.
135+
"""
136+
net = ChannelSpatialSELayer(**input_param)
137+
with eval_mode(net):
138+
result = net(torch.randn(input_shape))
139+
self.assertEqual(result.shape, expected_shape)
140+
141+
def test_value(self):
142+
"""The output is the element-wise maximum of the channel and spatial SE outputs."""
143+
net = ChannelSpatialSELayer(spatial_dims=2, in_channels=4)
144+
x = torch.randn(2, 4, 8, 8)
145+
with eval_mode(net):
146+
result = net(x)
147+
expected = torch.max(net.cse(x), net.sse(x))
148+
self.assertTrue(torch.allclose(result, expected))
149+
150+
def test_script(self):
151+
"""Verify the layer can be saved with TorchScript."""
152+
input_param, input_shape, _ = TEST_CASES_SPATIAL[1]
153+
net = ChannelSpatialSELayer(**input_param)
154+
test_script_save(net, torch.randn(input_shape))
155+
156+
@parameterized.expand([[100], [0]])
157+
def test_ill_arg(self, r):
158+
"""Verify an invalid reduction ratio is rejected.
159+
160+
Args:
161+
r: the invalid reduction ratio.
162+
"""
163+
with self.assertRaises(ValueError):
164+
ChannelSpatialSELayer(spatial_dims=2, in_channels=4, r=r)
165+
166+
77167
if __name__ == "__main__":
78168
unittest.main()

‎tests/networks/nets/test_quicknat.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,8 @@
1919
from monai.networks import eval_mode
2020
from monai.networks.nets import Quicknat
2121
from monai.networks.nets.quicknat import SkipConnectionWithIdx
22-
from monai.utils import optional_import
2322
from tests.test_utils import test_script_save
2423

25-
_, has_se = optional_import("squeeze_and_excitation")
26-
2724

2825
class _DoubleWithIdx(torch.nn.Module):
2926
"""Double tensor values using QuickNAT's indexed-module signature."""
@@ -93,17 +90,18 @@ def test_forward_without_optional_se_dependency(self):
9390
self.assertEqual(result.shape, (1, 2, 32, 32))
9491

9592

96-
@unittest.skipUnless(has_se, "squeeze_and_excitation not installed")
9793
class TestQuicknat(unittest.TestCase):
9894
@parameterized.expand(TEST_CASES)
9995
def test_shape(self, input_param, input_shape, expected_shape):
10096
device = "cuda" if torch.cuda.is_available() else "cpu"
101-
print(input_param)
10297
net = Quicknat(**input_param).to(device)
10398
with eval_mode(net):
10499
result = net(torch.randn(input_shape).to(device))
105100
self.assertEqual(result.shape, expected_shape)
106101

102+
@unittest.skip(
103+
"Quicknat is not TorchScript compatible: its blocks call super().forward() and skip modules with continue."
104+
)
107105
def test_script(self):
108106
net = Quicknat(num_classes=1, num_channels=1)
109107
test_data = torch.randn(16, 1, 32, 32)

0 commit comments

Comments
 (0)