ModuleDict
ModuleModuleDict(modules: dict[str, Module] | 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{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)Methods (13)
__init__
→None__init__(modules: dict[str, Module] | None = None)Initialise the ModuleDict module. See the class docstring for parameter semantics.
keys
→KeysView[str]keys()Return an iterable over the keys of the ModuleDict.
items
→ItemsView[str, Module]items()Return an iterable of (key, module) pairs in the ModuleDict.
values
→ValuesView[Module]values()Return an iterable over the modules in the ModuleDict.
get
→Module | Noneget(key: str, default: Module | None = None)Method on the ModuleDict module.
pop
→Modulepop(key: str)Remove and return the module at the given index from the ModuleDict.
clear
→Noneclear()Remove all modules from the ModuleDict.
update
→Noneupdate(modules: Mapping[str, Module] | Iterable[tuple[str, Module]])Update the ModuleDict with another mapping of modules.
forward
→Tensorforward(args: object = ())Apply the contained modules to the input.
Parameters
NoneReturns
TensorOutput tensor produced by the contained modules.
__getitem__
→Module__getitem__(key: str)Return the child module(s) at the given index or slice.
__setitem__
→None__setitem__(key: str, module: Module)Replace the child module at the given index.
__len__
→int__len__()Return the number of registered child modules.
__iter__
→Iterator[str]__iter__()Iterate over the registered child modules.