@@ -258,6 +258,11 @@ def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
258258 if orig_pred_ch == 1 and self .ignore_index is not None :
259259 warnings .warn ("single channel prediction, `ignore_index` is applied to label-encoded targets." )
260260
261+ if not (self .to_onehot_y and orig_pred_ch != 1 ):
262+ if not (orig_pred_ch == 1 and y_true .shape [1 ] == 1 ):
263+ if y_true .shape != y_pred .shape :
264+ raise ValueError (f"ground truth has different shape ({ y_true .shape } ) from input ({ y_pred .shape } )" )
265+
261266 # Preserve original target before any channel conversions so sentinel ignore
262267 # values (e.g., 255) are detected correctly on label-encoded inputs.
263268 original_y_true = y_true
@@ -266,15 +271,6 @@ def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
266271 if y_pred .shape [1 ] == 1 :
267272 y_pred = torch .cat ([1 - y_pred , y_pred ], dim = 1 )
268273
269- # Early shape validation: if we are not about to convert `y_true` to one-hot,
270- # ensure shapes already match before any further tensor value operations.
271- # Allow the common binary case where `y_pred` is single-channel (expanded later)
272- # and `y_true` is label-encoded single-channel.
273- if not (self .to_onehot_y and orig_pred_ch != 1 ):
274- if not (orig_pred_ch == 1 and y_true .shape [1 ] == 1 ):
275- if y_true .shape != y_pred .shape :
276- raise ValueError (f"ground truth has different shape ({ y_true .shape } ) from input ({ y_pred .shape } )" )
277-
278274 if self .to_onehot_y and orig_pred_ch != 1 :
279275 if self .ignore_index is not None and (self .ignore_index < 0 or self .ignore_index >= self .num_classes ):
280276 # Replace sentinel ignore_index with a valid class before one_hot
0 commit comments