Skip to content

Commit 76285e4

Browse files
committed
fix(training): register custom torchmetrics via nn.ModuleDict so state moves to device
1 parent a30c65b commit 76285e4

1 file changed

Lines changed: 11 additions & 0 deletions

File tree

deeptab/training/lightning_module.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,17 @@ def __init__(
205205
# Store custom metrics
206206
self.train_metrics = train_metrics or {}
207207
self.val_metrics = val_metrics or {}
208+
# torchmetrics ``Metric`` objects are ``nn.Module`` subclasses that hold
209+
# internal state tensors. Register them as submodules so Lightning moves
210+
# that state to the training device; otherwise the state stays on CPU and
211+
# raises a device-mismatch error on GPU/MPS. Plain-callable metrics carry
212+
# no device state and are left untouched.
213+
self._train_metric_modules = nn.ModuleDict(
214+
{name: metric for name, metric in self.train_metrics.items() if isinstance(metric, nn.Module)}
215+
)
216+
self._val_metric_modules = nn.ModuleDict(
217+
{name: metric for name, metric in self.val_metrics.items() if isinstance(metric, nn.Module)}
218+
)
208219

209220
# Scheduler / monitoring config
210221
self.scheduler_type = scheduler_type

0 commit comments

Comments
 (0)