Skip to content
Open
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
30 changes: 30 additions & 0 deletions docs/source/networks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -343,6 +343,11 @@ Layers

.. currentmodule:: monai.networks.layers

`LayerNormNd`
~~~~~~~~~~~~~
.. autoclass:: LayerNormNd
:members:

`ChannelPad`
~~~~~~~~~~~~
.. autoclass:: ChannelPad
Expand Down Expand Up @@ -467,6 +472,31 @@ Nets
.. autoclass:: AHNet
:members:

`ConvNeXt`
~~~~~~~~~~
.. autoclass:: ConvNeXt
:members:

`ConvNeXtTiny`
~~~~~~~~~~~~~~
.. autoclass:: ConvNeXtTiny

`ConvNeXtSmall`
~~~~~~~~~~~~~~~
.. autoclass:: ConvNeXtSmall

`ConvNeXtBase`
~~~~~~~~~~~~~~
.. autoclass:: ConvNeXtBase

`ConvNeXtLarge`
~~~~~~~~~~~~~~~
.. autoclass:: ConvNeXtLarge

`ConvNeXtXLarge`
~~~~~~~~~~~~~~~~
.. autoclass:: ConvNeXtXLarge

`DenseNet`
~~~~~~~~~~
.. autoclass:: DenseNet
Expand Down
1 change: 1 addition & 0 deletions monai/networks/layers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .factories import Act, Conv, Dropout, LayerFactory, Norm, Pad, Pool, RelPosEmbedding, split_args
from .filtering import BilateralFilter, PHLFilter, TrainableBilateralFilter, TrainableJointBilateralFilter
from .gmm import GaussianMixtureModel
from .layer_norm_nd import LayerNormNd
from .simplelayers import (
LLTM,
ApplyFilter,
Expand Down
46 changes: 46 additions & 0 deletions monai/networks/layers/layer_norm_nd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import torch
import torch.nn as nn


class LayerNormNd(nn.Module):
"""
Layer normalization over the channel dimension of a channels-first tensor.

`torch.nn.LayerNorm` normalizes over the trailing dimensions, so it expects a channels-last layout
such as ``(batch, *spatial, channel)``. Convolutional feature maps in MONAI are channels-first,
``(batch, channel, *spatial)``, and this module normalizes those over the channel dimension only,
for any number of spatial dimensions.

Args:
num_channels: number of channels of the input, i.e. the size of dimension 1.
spatial_dims: number of spatial dimensions of the input image.
eps: value added to the denominator for numerical stability.
"""

def __init__(self, num_channels: int, spatial_dims: int, eps: float = 1e-6) -> None:
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(num_channels))
self.bias = nn.Parameter(torch.zeros(num_channels))
# broadcast the affine parameters against (batch, channel, *spatial); precomputed so that the
# module is scriptable without inspecting the rank of the input at runtime.
self.param_shape = [1, num_channels] + [1] * spatial_dims
Comment on lines +33 to +40

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Reject invalid layer dimensions.

Negative spatial_dims produces an affine shape that can broadcast over the wrong axis; num_channels=0 also creates an unusable layer. Validate both and add invalid-argument tests.

Proposed fix
     def __init__(self, num_channels: int, spatial_dims: int, eps: float = 1e-6) -> None:
         super().__init__()
+        if num_channels <= 0:
+            raise ValueError("num_channels must be positive.")
+        if spatial_dims < 0:
+            raise ValueError("spatial_dims must be non-negative.")
         self.eps = eps

As per path instructions, “Examine code for logical error or inconsistencies” and ensure modified definitions have unit tests.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def __init__(self, num_channels: int, spatial_dims: int, eps: float = 1e-6) -> None:
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(num_channels))
self.bias = nn.Parameter(torch.zeros(num_channels))
# broadcast the affine parameters against (batch, channel, *spatial); precomputed so that the
# module is scriptable without inspecting the rank of the input at runtime.
self.param_shape = [1, num_channels] + [1] * spatial_dims
def __init__(self, num_channels: int, spatial_dims: int, eps: float = 1e-6) -> None:
super().__init__()
if num_channels <= 0:
raise ValueError("num_channels must be positive.")
if spatial_dims < 0:
raise ValueError("spatial_dims must be non-negative.")
self.eps = eps
self.weight = nn.Parameter(torch.ones(num_channels))
self.bias = nn.Parameter(torch.zeros(num_channels))
# broadcast the affine parameters against (batch, channel, *spatial); precomputed so that the
# module is scriptable without inspecting the rank of the input at runtime.
self.param_shape = [1, num_channels] + [1] * spatial_dims
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@monai/networks/layers/layer_norm_nd.py` around lines 33 - 40, Validate
num_channels and spatial_dims at the start of LayerNormND.__init__, rejecting
zero or negative channel counts and negative spatial dimensions before creating
parameters or param_shape; preserve valid-dimension behavior and add unit tests
covering each invalid argument.

Source: Path instructions


def forward(self, x: torch.Tensor) -> torch.Tensor:
mean = x.mean(dim=1, keepdim=True)
var = (x - mean).pow(2).mean(dim=1, keepdim=True)
x = (x - mean) / torch.sqrt(var + self.eps)
return self.weight.view(self.param_shape) * x + self.bias.view(self.param_shape)
19 changes: 19 additions & 0 deletions monai/networks/nets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,25 @@
from .basic_unetplusplus import BasicUNetPlusPlus, BasicUnetPlusPlus, BasicunetPlusPlus, basicunetplusplus
from .classifier import Classifier, Critic, Discriminator
from .controlnet import ControlNet
from .convnext import (
ConvNeXt,
Convnext,
Convnext_base,
Convnext_large,
Convnext_small,
Convnext_tiny,
Convnext_xlarge,
ConvNeXtBase,
ConvNeXtLarge,
ConvNeXtSmall,
ConvNeXtTiny,
ConvNeXtXLarge,
convnext_base,
convnext_large,
convnext_small,
convnext_tiny,
convnext_xlarge,
)
from .daf3d import DAF3D
from .densenet import (
DenseNet,
Expand Down
Loading