Skip to Content
OchreML
Core & Containers

Module & ModuleList

PyTorch-style base class for neural network layers and models, plus ModuleList for indexed submodule registration.

ochreml.nn.Module is the base class for all neural network layers and custom architectures in ochreml.nn. ochreml.nn.ModuleList stores an ordered sequence of Module instances while ensuring all child parameters are tracked automatically.

Import & Signatures

import ochreml.nn as nn

class MyModel(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.blocks = nn.ModuleList([nn.Linear(32, 32), nn.Linear(32, 32)])

    def forward(self, x: nn.Tensor) -> nn.Tensor:
        for block in self.blocks:
            x = block(x).relu()
        return x

Module Methods

MethodSignatureDescription
forward(*args, **kwargs)Override in subclasses; called via model(*args, **kwargs).
parameters(recurse=True) -> list[Parameter]Returns all registered trainable parameters.
named_parameters(prefix="", recurse=True) -> list[tuple[str, Parameter]]Returns (dotted_name, Parameter) pairs.
num_parameters() -> intTotal scalar count across all parameters.
children / modules() -> Iterator[Module]Iterates direct child modules or the entire tree.
register_parameter(name, param)Explicitly register a Parameter.
register_buffer(name, tensor)Register non-trainable state (e.g., BatchNorm2d running stats).
add_module(name, module)Explicitly register a child Module.
train / evaltrain(mode=True) / eval()Recursively sets training flag (affects Dropout, BatchNorm2d, ResidualBlock).
zero_grad() -> NoneClears .grad on all parameters.
state_dict() -> dict[str, Any]Exports parameter NumPy arrays and registered buffers.
load_state_dict(state_dict, strict=True) -> tuple[list[str], list[str]]Loads weights/buffers in-place; returns (missing, unexpected).
to(device=None, dtype=None) -> ModuleMoves parameters and updates module device/dtype.

ModuleList Methods

  • nn.ModuleList(modules=None)
  • append(module) / extend(modules)
  • Supports len(ml), indexing (ml[i]), and iteration (for m in ml:).

Usage Example

import ochreml.nn as nn

model = MyModel()
print("Parameter count:", model.num_parameters())

state = model.state_dict()
missing, unexpected = model.load_state_dict(state, strict=True)
model.to(device="cpu", dtype="float32")

On this page