PyTorch torch.nn.ModuleList Function
PyTorch torch.nn Reference Manual
torch.nn.ModuleList is a container in PyTorch for storing a list of modules.
It is similar to a Python list, but automatically registers all submodules.
Function definition
torch.nn.ModuleList(modules=None)
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
class
Net
(
nn.
Module
)
:
def
init
(
self
)
:
super
(
Net
,
self
)
.
init
(
)
self
.
layers
=
nn.
ModuleList
(
[
nn.
Linear
(
10
,
20
)
,
nn.
Linear
(
20
,
20
)
,
nn.
Linear
(
20
,
5
)
]
)
def
forward
(
self
,
x
)
:
for
layer
in
self
.
layers
:
x
=
layer
(
x
)
return
x
model
=
Net
(
)
x
=
torch.
randn
(
4
,
10
)
output
=
model
(
x
)
(
"Input:"
,
x.
shape
)
(
"Output:"
,
output.
shape
)
(
"Number of parameters:"
,
sum
(
p.
numel
(
)
for
p
in
model.
parameters
(
)
)
)
Example 2: Dynamically building layers
Example
import
torch
import
torch.
nn
as
nn
class
DynamicNet
(
nn.
Module
)
:
def
init
(
self
,
num_layers
,
dim
)
:
super
(
DynamicNet
,
self
)
.
init
(
)
self
.
layers
=
nn.
ModuleList
(
)
for
i
in
range
(
num_layers
)
:
in_dim
=
dim
if
i
==
0
else
dim
self
.
layers
.
append
(
nn.
Linear
(
in_dim
,
dim
)
)
def
forward
(
self
,
x
)
:
for
i
,
layer
in
enumerate
(
self
.
layers
)
:
x
=
layer
(
x
)
if
i <
;
len
(
self
.
layers
)
1
:
x
=
torch.
relu
(
x
)
return
x
model
=
DynamicNet
(
num_layers
=
5
,
dim
=
64
)
(
"Number of layers:"
,
len
(
model.
layers
)
)
(
"Total parameters:"
,
sum
(
p.
numel
(
)
for
p
in
model.
parameters
(
)
)
)
Example 3: Comparison with Sequential
Example
import
torch
import
torch.
nn
as
nn
ModuleList - flexible
mlist
=
nn.
ModuleList
(
[
nn.
Linear
(
10
,
20
)
,
nn.
ReLU
(
)
,
nn.
Linear
(
20
,
5
)
]
)
Sequential - fixed order
seq
=
nn.
Sequential
(
nn.
Linear
(
10
,
20
)
,
nn.
ReLU
(
)
,
nn.
Linear
(
20
,
5
)
)
(
"ModuleList index access:"
,
mlist
[
0
]
)
(
"Sequential index access:"
,
seq
[
0
]
)
(
"nModuleList is iterable but has no forward"
)
(
"Sequential can be called directly"
)
Use Cases
- Multi-layer networks: Dynamic construction
- Recurrent structures: Shared layers
- Complex models: Require custom control flow
Note: You must use nn.ModuleList rather than a Python list.