|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +import torch |
| 7 | +from torch import Tensor |
| 8 | +from torch.nn import Linear, Sequential |
| 9 | + |
| 10 | + |
| 11 | +class ResidualMLP(torch.nn.Module): |
| 12 | + r"""Two-layer MLP with a learned linear residual projection. |
| 13 | +
|
| 14 | + .. math:: |
| 15 | +
|
| 16 | + \operatorname{MLP}_2(x) + \operatorname{Linear}(x) |
| 17 | +
|
| 18 | + Args: |
| 19 | + in_channels: The number of input channels. |
| 20 | + hidden_channels: The number of hidden channels in the MLP. |
| 21 | + out_channels: The number of output channels. |
| 22 | + activation: The activation in the MLP. |
| 23 | + bias: Whether to learn additive biases. |
| 24 | + device: The device. |
| 25 | + dtype: The dtype. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, |
| 30 | + in_channels: int, |
| 31 | + hidden_channels: int, |
| 32 | + out_channels: int, |
| 33 | + activation: torch.nn.Module, |
| 34 | + bias: bool = True, |
| 35 | + device: torch.device | str | None = None, |
| 36 | + dtype: torch.dtype | None = None, |
| 37 | + ) -> None: |
| 38 | + super().__init__() |
| 39 | + factory_kwargs: dict[str, Any] = { |
| 40 | + "bias": bias, |
| 41 | + "device": device, |
| 42 | + "dtype": dtype, |
| 43 | + } |
| 44 | + self.mlp = Sequential( |
| 45 | + Linear(in_channels, hidden_channels, **factory_kwargs), |
| 46 | + activation, |
| 47 | + Linear(hidden_channels, out_channels, **factory_kwargs), |
| 48 | + ) |
| 49 | + self.res = Linear(in_channels, out_channels, **factory_kwargs) |
| 50 | + |
| 51 | + def forward(self, x: Tensor) -> Tensor: |
| 52 | + r"""The forward pass. |
| 53 | +
|
| 54 | + Args: |
| 55 | + x: The tensor. |
| 56 | + """ |
| 57 | + return self.mlp(x) + self.res(x) |
0 commit comments