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)
>>> # Dispatch dynamically at runtime:
>>> logits = model(x, task="classification")
**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
>>> for name, branch in router.items():
... print(name, branch)Used by 1
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.
Method on the ModuleDict module.
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.