liveBook · Manning

Nn.ModuleList

As explained in Inside Deep Learning: Math, Algorithms, Models

A PyTorch container that stores submodules in a list so they are registered and iterated over as model components.

nn.ModuleList groups variable numbers of PyTorch submodules while keeping them available for indexed iteration. It is useful when the forward pass must manually run a sequence, such as stacked GRUCell layers processing one time step at a time. section 7.5.1

A layered recurrent model uses ModuleList for both recurrent layers and their matching normalization layers:

  • Create the first GRUCell with embedding-sized input, then create layers-1 additional cells with hidden_size input and output. section 7.5.1
  • Create one LayerNorm per recurrent layer in a second ModuleList. section 7.5.1
  • Loop over the lists by index, update each hidden state, normalize it, and pass the result to the next layer. section 7.5.1

Two-layer character autoregression

A character model can define `self.layers = nn.ModuleList([nn.GRUCell(embd_size, hidden_size)] + [nn.GRUCell(hidden_size, hidden_size) for _ in range(layers-1)])` and matching normalization layers. Its `step` method loops through `range(len(self.layers))`, updates each hidden state, and sends the final activation to `self.pred_class`. The model therefore supports a configurable number of recurrent layers while processing each character sequentially. section 7.5.1

ModuleList favors explicit control over convenience: cell-based processing is slower than whole-sequence RNN modules, but it accommodates inputs whose lengths are unknown or variable. section 7.5.1

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Explains construction, indexed iteration, hidden-state updates, and normalization, but does not develop ModuleList internals.
Examples
Demonstrates stacked GRUCells for character prediction and suggests storing candidate hidden layers for manifold mixup.
What it assumes
Assumes familiarity with PyTorch modules, GRUCell inputs, hidden states, and forward methods.
What you can do after
Builds configurable PyTorch module sequences and runs their components explicitly by layer.
How it connects
Connects ModuleList to GRUCell, LayerNorm, hidden states, autoregressive models, residual blocks, and manifold mixup.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.