"""Native Torch weighted CE on reviewed paint/background; unknown contributes zero.""" import math def weighted_paint_cross_entropy(logits, target, class_weights): """Mean divides by summed valid class weights, including BG-only batches. Weights are supplied by a frozen TRAIN-only recipe; this function never estimates them from evaluation labels or adjusts a prediction threshold. Torch is optional until training calls this function. """ import torch from torch.nn import functional as functional if len(class_weights) != 2 or any( not math.isfinite(float(w)) or float(w) <= 0 for w in class_weights ): raise ValueError("Two finite positive class weights required") if logits.ndim != 4 or logits.shape[1] != 2: raise ValueError("Native NCHW logits with two classes required") if target.shape != (logits.shape[0], *logits.shape[2:]): raise ValueError("Native NHW target must match logits") if target.dtype != torch.long: raise ValueError("Integer class indices required") valid = target != 255 if not bool(valid.any()): raise ValueError("All-unknown loss forbidden") if not bool(((target == 0) | (target == 1) | ~valid).all()): raise ValueError("Target classes must be 0, 1 or 255") weights = logits.new_tensor(class_weights) if not bool(torch.isfinite(weights).all() & (weights > 0).all()): raise ValueError("Class weights not representable in logits dtype") return functional.cross_entropy( logits, target, weight=weights, ignore_index=255, reduction="mean" )