Skip to content
Merged
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ All notable changes to MONAI are documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).

## [Unreleased]
### Added
* `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)
### Fixed
* `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)
* `ChannelSELayer` raises `ValueError` instead of `ZeroDivisionError` when `r=0`.

## [1.6.2] - 2026-11-18
### Addressed Security Advisories
Expand Down
10 changes: 10 additions & 0 deletions docs/source/networks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,16 @@ Blocks
.. autoclass:: ResidualSELayer
:members:

`Spatial Squeeze-and-Excitation`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: SpatialSELayer
:members:

`Channel-Spatial Squeeze-and-Excitation`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: ChannelSpatialSELayer
:members:

`Squeeze-and-Excitation Block`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. autoclass:: SEBlock
Expand Down
2 changes: 2 additions & 0 deletions monai/networks/blocks/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@
from .spatialattention import SpatialAttentionBlock
from .squeeze_and_excitation import (
ChannelSELayer,
ChannelSpatialSELayer,
ResidualSELayer,
SEBlock,
SEBottleneck,
SEResNetBottleneck,
SEResNeXtBottleneck,
SpatialSELayer,
)
from .transformerblock import TransformerBlock
from .unetr_block import UnetrBasicBlock, UnetrPrUpBlock, UnetrUpBlock
Expand Down
67 changes: 66 additions & 1 deletion monai/networks/blocks/squeeze_and_excitation.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def __init__(
pool_type = Pool[Pool.ADAPTIVEAVG, spatial_dims]
self.avg_pool = pool_type(1) # spatial size (1, 1, ...)

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

Expand Down Expand Up @@ -127,6 +127,71 @@ def __init__(
)


class SpatialSELayer(nn.Module):
"""
Channel squeeze and spatial excitation (sSE) block based on:
"Roy et al., Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks,
https://arxiv.org/abs/1803.02579".

A 1x1 convolution squeezes the channels into one map, which is passed through a sigmoid and used to
recalibrate every spatial location of the input.

Args:
spatial_dims: number of spatial dimensions, could be 1, 2, or 3.
in_channels: number of input channels.
"""

def __init__(self, spatial_dims: int, in_channels: int) -> None:
super().__init__()
Comment thread
ericspod marked this conversation as resolved.
Resolved
conv_type = Conv[Conv.CONV, spatial_dims]
self.conv = conv_type(in_channels, 1, kernel_size=1)
self.sigmoid = nn.Sigmoid()

def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]).

Returns:
The input recalibrated per spatial location, with the same shape as ``x``.
"""
return x * self.sigmoid(self.conv(x))


class ChannelSpatialSELayer(nn.Module):
"""
Concurrent spatial and channel squeeze and excitation (scSE) block based on:
"Roy et al., Concurrent Spatial and Channel Squeeze & Excitation in Fully Convolutional Networks,
https://arxiv.org/abs/1803.02579".

The outputs of :py:class:`ChannelSELayer` and :py:class:`SpatialSELayer` are combined with an
element-wise maximum.

Args:
spatial_dims: number of spatial dimensions, could be 1, 2, or 3.
in_channels: number of input channels.
r: the reduction ratio of the channel squeeze. Defaults to 2.

Raises:
ValueError: When ``r`` is nonpositive or larger than ``in_channels``.
"""

def __init__(self, spatial_dims: int, in_channels: int, r: int = 2) -> None:
super().__init__()
self.cse = ChannelSELayer(spatial_dims=spatial_dims, in_channels=in_channels, r=r)
self.sse = SpatialSELayer(spatial_dims=spatial_dims, in_channels=in_channels)

def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x: in shape (batch, in_channels, spatial_1[, spatial_2, ...]).

Returns:
The element-wise maximum of the channel and spatial SE outputs, with the same shape as ``x``.
"""
return torch.max(self.cse(x), self.sse(x))


class SEBlock(nn.Module):
"""
Residual module enhanced with Squeeze-and-Excitation::
Expand Down
23 changes: 9 additions & 14 deletions monai/networks/nets/quicknat.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,6 @@
from monai.networks.layers.factories import Act, Norm
from monai.networks.layers.simplelayers import SkipConnection
from monai.networks.layers.utils import get_dropout_layer, get_pool_layer
from monai.utils import optional_import

# Lazy import to avoid dependency
se1, flag = optional_import("squeeze_and_excitation")

__all__ = ["Quicknat"]

Expand Down Expand Up @@ -347,6 +343,10 @@ class Quicknat(nn.Module):
pool: kernel size of the pooling layer,
stride_pool: stride for the pooling layer.
se_block: Squeeze and Excite block type to include. Use ``None`` or ``"None"`` to disable it; valid enabled values are ``"CSE"``, ``"SSE"``, and ``"CSSE"``.
``"SSE"`` and ``"CSSE"`` now use :py:class:`monai.networks.blocks.SpatialSELayer` and
:py:class:`monai.networks.blocks.ChannelSpatialSELayer` instead of the external
``squeeze_and_excitation`` package, so weights saved with that package for these two options
have different ``state_dict`` keys and will not load with ``strict=True``.
drop_out: dropout ratio. Defaults to no dropout.
act: activation type and arguments. Defaults to PReLU.
norm: feature normalization type and arguments. Defaults to instance norm.
Expand Down Expand Up @@ -434,19 +434,14 @@ def get_selayer(self, n_filters, se_block_type="None"):
Args:
n_filters: encoding half of the layer
se_block_type: defaults to None. Valid options are None, CSE, SSE, CSSE
Returns: Appropriate SEBlock. SSE and CSSE not implemented in Monai yet.
Returns: Appropriate SEBlock, or None when ``se_block_type`` is None or "None".
"""
if se_block_type == "CSE":
return se.ChannelSELayer(2, n_filters)
# not implemented in squeeze_and_excitation in monai use other squeeze_and_excitation import:
elif se_block_type == "SSE" or se_block_type == "CSSE":
# Throw error if squeeze_and_excitation is not installed
if not flag:
raise ImportError("Please install squeeze_and_excitation locally to use SpatialSELayer")
if se_block_type == "SSE":
return se1.SpatialSELayer(n_filters)
else:
return se1.ChannelSpatialSELayer(n_filters)
elif se_block_type == "SSE":
return se.SpatialSELayer(2, n_filters)
elif se_block_type == "CSSE":
return se.ChannelSpatialSELayer(2, n_filters)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
else:
return None

Expand Down
96 changes: 93 additions & 3 deletions tests/networks/blocks/test_se_blocks.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from parameterized import parameterized

from monai.networks import eval_mode
from monai.networks.blocks import ChannelSELayer, ResidualSELayer
from monai.networks.blocks import ChannelSELayer, ChannelSpatialSELayer, ResidualSELayer, SpatialSELayer
from tests.test_utils import test_script_save

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

def test_ill_arg(self):
@parameterized.expand([[100], [0], [-1]])
def test_ill_arg(self, r):
"""Verify a nonpositive reduction ratio, or one larger than the channel count, is rejected.

Args:
r: the invalid reduction ratio.
"""
with self.assertRaises(ValueError):
ChannelSELayer(spatial_dims=1, in_channels=4, r=100)
ChannelSELayer(spatial_dims=1, in_channels=4, r=r)


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


TEST_CASES_SPATIAL = [
[{"spatial_dims": 1, "in_channels": 4}, (16, 4, 63), (16, 4, 63)],
[{"spatial_dims": 2, "in_channels": 4}, (7, 4, 64, 48), (7, 4, 64, 48)],
[{"spatial_dims": 3, "in_channels": 10}, (2, 10, 32, 24, 48), (2, 10, 32, 24, 48)],
]


class TestSpatialSELayer(unittest.TestCase):
"""Test the channel squeeze and spatial excitation layer."""

@parameterized.expand(TEST_CASES_SPATIAL)
def test_shape(self, input_param, input_shape, expected_shape):
"""Verify the output keeps the input shape.

Args:
input_param: constructor arguments for the layer.
input_shape: shape of the random input tensor.
expected_shape: expected shape of the output.
"""
net = SpatialSELayer(**input_param)
with eval_mode(net):
result = net(torch.randn(input_shape))
self.assertEqual(result.shape, expected_shape)

def test_value(self):
"""The input is scaled by the sigmoid of a single-channel 1x1 convolution."""
net = SpatialSELayer(spatial_dims=2, in_channels=3)
x = torch.randn(2, 3, 8, 8)
with eval_mode(net):
result = net(x)
expected = x * torch.sigmoid(net.conv(x))
self.assertEqual(net.conv.out_channels, 1)
self.assertTrue(torch.allclose(result, expected))

def test_script(self):
"""Verify the layer can be saved with TorchScript."""
input_param, input_shape, _ = TEST_CASES_SPATIAL[1]
net = SpatialSELayer(**input_param)
test_script_save(net, torch.randn(input_shape))


class TestChannelSpatialSELayer(unittest.TestCase):
"""Test the concurrent spatial and channel squeeze and excitation layer."""

@parameterized.expand([[{**p, "r": 2}, i, o] for p, i, o in TEST_CASES_SPATIAL])
def test_shape(self, input_param, input_shape, expected_shape):
"""Verify the output keeps the input shape.

Args:
input_param: constructor arguments for the layer.
input_shape: shape of the random input tensor.
expected_shape: expected shape of the output.
"""
net = ChannelSpatialSELayer(**input_param)
with eval_mode(net):
result = net(torch.randn(input_shape))
self.assertEqual(result.shape, expected_shape)

def test_value(self):
"""The output is the element-wise maximum of the channel and spatial SE outputs."""
net = ChannelSpatialSELayer(spatial_dims=2, in_channels=4)
x = torch.randn(2, 4, 8, 8)
with eval_mode(net):
result = net(x)
expected = torch.max(net.cse(x), net.sse(x))
self.assertTrue(torch.allclose(result, expected))

def test_script(self):
"""Verify the layer can be saved with TorchScript."""
input_param, input_shape, _ = TEST_CASES_SPATIAL[1]
net = ChannelSpatialSELayer(**input_param)
test_script_save(net, torch.randn(input_shape))

@parameterized.expand([[100], [0]])
def test_ill_arg(self, r):
"""Verify an invalid reduction ratio is rejected.

Args:
r: the invalid reduction ratio.
"""
with self.assertRaises(ValueError):
ChannelSpatialSELayer(spatial_dims=2, in_channels=4, r=r)


if __name__ == "__main__":
unittest.main()
8 changes: 3 additions & 5 deletions tests/networks/nets/test_quicknat.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,8 @@
from monai.networks import eval_mode
from monai.networks.nets import Quicknat
from monai.networks.nets.quicknat import SkipConnectionWithIdx
from monai.utils import optional_import
from tests.test_utils import test_script_save

_, has_se = optional_import("squeeze_and_excitation")


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


@unittest.skipUnless(has_se, "squeeze_and_excitation not installed")
class TestQuicknat(unittest.TestCase):
@parameterized.expand(TEST_CASES)
def test_shape(self, input_param, input_shape, expected_shape):
device = "cuda" if torch.cuda.is_available() else "cpu"
print(input_param)
net = Quicknat(**input_param).to(device)
with eval_mode(net):
result = net(torch.randn(input_shape).to(device))
self.assertEqual(result.shape, expected_shape)

@unittest.skip(
"Quicknat is not TorchScript compatible: its blocks call super().forward() and skip modules with continue."
)
def test_script(self):
net = Quicknat(num_classes=1, num_channels=1)
test_data = torch.randn(16, 1, 32, 32)
Expand Down
Loading