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
{name: module} mapping. Each entry is registered via
add_module(key, module). Pass None (default) for an
empty dict.Attributes
_ modulesOrderedDict[str, Module | None]Notes
- Insertion order is preserved (backed by
OrderedDict). updateaccepts bothMapping[str, Module]andIterable[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
1Instance methods
8Remove all modules from the ModuleDict.
Apply the contained modules to the input.
Parameters
NoneReturns
TensorOutput tensor produced by the contained modules.
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
keystrkey is not registered. Default None.Returns
Module or NoneThe registered module, default if key is absent, or
None if the slot at key was explicitly cleared.
Return an iterable of (key, module) pairs in the ModuleDict.
Return an iterable over the keys of the ModuleDict.
Remove and return the module at the given index from the ModuleDict.
Update the ModuleDict with another mapping of modules.
Return an iterable over the modules in the ModuleDict.
Dunder methods
4Return the child module(s) at the given index or slice.
Iterate over the registered child modules.
Return the number of registered child modules.
Replace the child module at the given index.