Use EMAModuleWrapper for Target Representation Routing
mainThe EMAModuleWrapper is designed for complex, nested module trees (common in self-supervised learning). It automatically routes the outputs of target EMA submodules into the forward pass of specified online submodules.
How it works:
When you call ema(x), the wrapper identifies the specified submodules and injects their corresponding EMA teacher outputs as keyword arguments (defaulting to ema_output) into the online module's forward method.
Configuration via ema_module_kwargs:
- Simple Mapping:
{'online_path': 'target_path'}. The output oftarget_pathis passed toonline_pathasema_output. - Advanced Mapping:
{'online_path': {'ema_module_path': 'target_path', 'ema_kwarg': 'custom_name'}}. This allows you to specify a custom keyword argument name for the injected output.
Multi-view SSL:
For scenarios where the student and teacher receive different augmented views, you can pass ema_args or ema_kwargs during the call: ema(student_input, ema_args = teacher_input).
from ema_pytorch import EMAModuleWrapper
# Example: Mapping branch_a.block1 to use branch_b.block1 as its teacher
ema = EMAModuleWrapper(
model,
beta = 0.99,
ema_module_kwargs = {
'branch_a.block1': 'branch_b.block1',
'branch_a.block2': 'branch_b.block2'
}
)
# Forwarding injects EMA outputs into the specified blocks
out, loss = ema(x)
# For multi-view SSL
out, loss = ema(student_input, ema_args = teacher_input)