Skip to content
class

ModuleDict

extendsModule
ModuleDict(modules: Mapping[str, M] | None = None)

A dict-like container that registers all child modules under string keys.

ModuleDict maps arbitrary string keys to Module objects and integrates them fully with the Lucid module system: parameters(), state_dict(), and device/dtype transfers all traverse into the registered modules transparently.

Unlike Sequential and ModuleList, the keys are user-defined strings rather than integers, making ModuleDict well-suited for multi-task or multi-branch architectures where branches have semantic names.

forward is not defined — the user dispatches to specific branches by key in the enclosing module's forward.

Parameters

modulesdict[str, Module] or None= None
Initial {name: module} mapping. Each entry is registered via add_module(key, module). Pass None (default) for an empty dict.

Attributes

_modulesOrderedDict[str, Module | None]
Internal ordered mapping from string key to child module.

Notes

  • Insertion order is preserved (backed by OrderedDict).
  • update accepts both Mapping[str, Module] and Iterable[tuple[str, Module]].

Examples

**Multi-task prediction heads keyed by task name:**
>>> import lucid
>>> import lucid.nn as nn
>>>
>>> class MultiTaskModel(nn.Module):
...     def __init__(self, shared_dim: int) -> None:
...         super().__init__()
...         self.backbone = nn.Linear(shared_dim, 256)
...         self.heads = nn.ModuleDict({
...             "classification": nn.Linear(256, 10),
...             "regression":     nn.Linear(256, 1),
...             "segmentation":   nn.Linear(256, 64),
...         })
...
...     def forward(self, x: lucid.Tensor, task: str) -> lucid.Tensor:
...         feat = lucid.nn.functional.relu(self.backbone(x))
...         return self.heads[task](feat)
>>>
>>> model = MultiTaskModel(shared_dim=512)
>>> x = lucid.randn(4, 512)
>>> # Dispatch dynamically at runtime:
>>> logits = model(x, task="classification")
>>> logits.shape
(4, 10)
**Conditional gating — adding/removing branches at runtime:**
>>> router = nn.ModuleDict({"low": nn.Linear(64, 32)})
>>> router["high"] = nn.Linear(64, 128)   # register a new branch
>>> router.pop("low")                      # remove old branch
Linear(in_features=64, out_features=32, bias=True)
>>> for name, branch in router.items():
...     print(name, branch)
high Linear(in_features=64, out_features=128, bias=True)

Used by 2

Constructors

1
dunder

__init__

→None
__init__(modules: Mapping[str, M] | None = None)

Initialise the ModuleDict module. See the class docstring for parameter semantics.

Instance methods

8
fn

clear

→None
clear()

Remove all modules from the ModuleDict.

fn

forward

→Tensor
forward(args: object = ())

Apply the contained modules to the input.

Parameters

None
No description.

Returns

Tensor

Output tensor produced by the contained modules.

fn

get

→Module or None
get(key: str, default: M | None = None)

Return the module at key, or default if key is absent.

Checked by membership, not by the stored value being None -- an entry explicitly set to None (a cleared slot that keeps its place in named_children) is a present value in its own right and must come back as None, not silently swapped for default.

Parameters

keystr
Name to look up.
defaultModule= None
Returned when key is not registered. Default None.

Returns

Module or None

The registered module, default if key is absent, or None if the slot at key was explicitly cleared.

fn

items

→ItemsView[str, M]
items()

Return an iterable of (key, module) pairs in the ModuleDict.

fn

keys

→KeysView[str]
keys()

Return an iterable over the keys of the ModuleDict.

fn

pop

→M
pop(key: str)

Remove and return the module at the given index from the ModuleDict.

fn

update

→None
update(modules: Mapping[str, M] | Iterable[tuple[str, M]])

Update the ModuleDict with another mapping of modules.

fn

values

→ValuesView[M]
values()

Return an iterable over the modules in the ModuleDict.

Dunder methods

4
dunder

__getitem__

→M
__getitem__(key: str)

Return the child module(s) at the given index or slice.

dunder

__iter__

→Iterator[str]
__iter__()

Iterate over the registered child modules.

dunder

__len__

→int
__len__()

Return the number of registered child modules.

dunder

__setitem__

→None
__setitem__(key: str, module: M)

Replace the child module at the given index.