{"record":{"id":"c3b8d23f18392808","repo":"open-mmlab/mmdetection","slug":"avg-factor-can-not-be-used-with-reduction-sum","errorCode":null,"errorMessage":"avg_factor can not be used with reduction=\"sum\"","messagePattern":"avg_factor can not be used with reduction=\"sum\"","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mmdet/models/losses/utils.py","lineNumber":64,"sourceCode":"        Tensor: Processed loss values.\n    \"\"\"\n    # if weight is specified, apply element-wise weight\n    if weight is not None:\n        loss = loss * weight\n\n    # if avg_factor is not specified, just reduce the loss\n    if avg_factor is None:\n        loss = reduce_loss(loss, reduction)\n    else:\n        # if reduction is mean, then average the loss by avg_factor\n        if reduction == 'mean':\n            # Avoid causing ZeroDivisionError when avg_factor is 0.0,\n            # i.e., all labels of an image belong to ignore index.\n            eps = torch.finfo(torch.float32).eps\n            loss = loss.sum() / (avg_factor + eps)\n        # if reduction is 'none', then do nothing, otherwise raise an error\n        elif reduction != 'none':\n            raise ValueError('avg_factor can not be used with reduction=\"sum\"')\n    return loss\n\n\ndef weighted_loss(loss_func: Callable) -> Callable:\n    \"\"\"Create a weighted version of a given loss function.\n\n    To use this decorator, the loss function must have the signature like\n    `loss_func(pred, target, **kwargs)`. The function only needs to compute\n    element-wise loss without any reduction. This decorator will add weight\n    and reduction arguments to the function. The decorated function will have\n    the signature like `loss_func(pred, target, weight=None, reduction='mean',\n    avg_factor=None, **kwargs)`.\n\n    :Example:\n\n    >>> import torch\n    >>> @weighted_loss\n    >>> def l1_loss(pred, target):","sourceCodeStart":46,"sourceCodeEnd":82,"githubUrl":"https://github.com/open-mmlab/mmdetection/blob/cfd5d3a985b0249de009b67d04f37263e11cdf3d/mmdet/models/losses/utils.py#L46-L82","documentation":"weight_reduce_loss raises ValueError when both avg_factor is provided and reduction='sum'. Dividing by avg_factor while also asking for a raw sum is contradictory, so the combination is explicitly rejected.","triggerScenarios":"A loss call such as FocalLoss or CrossEntropyLoss forward(..., avg_factor=num_pos, reduction='sum') from a custom head that computes its own normalization.","commonSituations":"Custom dense heads passing both avg_factor and reduction='sum' in loss calls; overriding loss functions or targetassigners that forward both kwargs.","solutions":["Use reduction='mean' together with avg_factor (the standard path)","Or keep reduction='sum' and drop avg_factor, dividing manually afterwards"],"exampleFix":"# before\nloss = self.loss_cls(pred, target, avg_factor=avg_factor, reduction='sum')\n# after\nloss = self.loss_cls(pred, target, avg_factor=avg_factor, reduction='mean')","handlingStrategy":"validation","validationCode":"assert not (avg_factor is not None and reduction == 'sum'), 'avg_factor incompatible with reduction=sum'","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Pass avg_factor only with reduction='mean'/'none'","Review custom head loss calls for both kwargs"],"tags":["mmdet","loss","reduction","avg-factor"],"backgroundTag":"invalid-argument-combination","analyzedSha":"cfd5d3a985b0249de009b67d04f37263e11cdf3d","analyzedAt":"2026-08-27T20:54:20.183Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}