Skip to content
class

Module

extends_StateDictHookMixin
Module()

Base class for all neural network modules.

Every custom model should subclass this and implement forward. Submodules assigned as attributes are tracked automatically.

Notes

Attribute routing: Setting an attribute follows this priority order:

  1. If the value is a lucid.nn.Parameter → stored in _parameters.
  2. If the name is a registered parameter → the value must be None, which empties the slot; anything else is a TypeError.
  3. If the value is a Module → stored in _modules.
  4. If the name is a registered submodule → the value must be None.
  5. If the value is a lucid.nn.Buffer → registered as a buffer, persistent or not as the Buffer says. If the name is a registered buffer → the value must be a lucid.Tensor or None, and the buffer keeps its persistence.
  6. Otherwise → plain Python attribute.

To register a non-parameter tensor (e.g. a running mean), call register_buffer explicitly. Assigning to a name that is already registered replaces the value in its slot: the name keeps its position in named_parameters, named_buffers, named_children and state_dict, so layer.weight += 1 under lucid.no_grad leaves the order an optimizer or a position-paired average was built from untouched. A name leaves its registry through del, not through assignment.

Examples

>>> import lucid
>>> import lucid.nn as nn
>>> class MLP(nn.Module):
...     def __init__(self):
...         super().__init__()
...         self.fc1 = nn.Linear(10, 20)
...         self.fc2 = nn.Linear(20, 1)
...
...     def forward(self, x):
...         return self.fc2(lucid.relu(self.fc1(x)))
...
>>> model = MLP()
>>> model(lucid.randn(4, 10)).shape
(4, 1)

Used by 59

… 47 more

Constructors

2
dunder

__init__

→None
__init__()

Initialise the instance. See the class docstring for parameter semantics.

dunder

__call__

→R
__call__(args: P.args = (), kwargs: P.kwargs = {})

Run forward with the registered hooks around it.

Always call the module rather than forward directly: forward pre-hooks, forward hooks and backward hooks only run on this path. The arguments and the return type are those of the subclass's own forward.

Instance methods

46

In-place ops

1
fn

requires_grad_

→Self
requires_grad_(requires_grad: bool = True)

Set requires_grad for all parameters.

Dunder methods

1
dunder

__repr__

→str
__repr__()

Return a developer-facing string representation of the instance.