Dynamic layer collections
A model has a variable number of repeated or heterogeneous layers that should remain registered as children.
PyTorch · Class
ModuleList stores child modules in a list-like container while registering them with the parent module. It supports indexed access and iteration, but the enclosing module controls how the children are executed.
ModuleList is a container for child modules that behaves like a Python list while registering those children with the parent module. It is useful when a model needs indexed or iterative access but must define its own forward computation.
class torch.nn.modules.container.ModuleList(*modules=None*)| Name | Type | Description |
|---|---|---|
modules | iterable | Optional iterable of modules to add initially. |
A ModuleList container; append, extend, and insert return Self as documented for those methods.
import torch
from torch import nn
class BlockStack(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.ModuleList([
nn.Linear(4, 4),
nn.ReLU(),
nn.Linear(4, 2),
])
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
model = BlockStack()
print(model(torch.randn(3, 4)).shape)Stores heterogeneous layers while explicitly controlling their execution order.
A model has a variable number of repeated or heterogeneous layers that should remain registered as children.
Forward computation needs indexing, loops, branching, or custom combinations instead of fixed sequential execution.
Modules are added or reordered after container construction.
ModuleList stores child modules in an indexed, list-like container. Unlike ordinary Python lists, its children are registered, so Module methods can discover and manage them.
Follow-up: What happens if layers must be applied automatically in sequence? Use Sequential when its built-in sequential behavior matches the architecture; ModuleList is preferable when forward needs custom control.
Construct it with an optional iterable of modules, then access elements by integer index or iterate over them. You can also add modules later with append, extend, or insert.
Follow-up: How would you add one module at a specific position? Call insert(index, module), which places the module before the specified index.
ModuleList itself is a container and does not specify a computation graph. The enclosing Module's forward method decides whether to iterate, select by index, branch, or combine its contained modules.
Follow-up: How can you implement a depth-dependent path? Select or iterate over the required indices in forward, while keeping all candidate modules registered in the ModuleList.
torch.nn.Moduletorch.nn.Sequentialappendextendinsert