π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(augmentation): broadcast in RandomErasing instead of repeat-materializing (#3828)
Edgar Riba1b2d6664d31e
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.pyindex f55be6c6a..32294e8cc 100644--- a/kornia/augmentation/_2d/intensity/erasing.py+++ b/kornia/augmentation/_2d/intensity/erasing.py@@ -93,12 +93,15 @@ class RandomErasing(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:- _, c, h, w = input.size()- values = params["values"].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)+ _, _, h, w = input.size()+ # Broadcast the per-sample fill value (B, 1, 1, 1) and the single-channel mask (B, 1, H, W)+ # directly in `torch.where` instead of `repeat`-materializing both to full (B, C, H, W).+ # `where` broadcasts to the input shape, so the result is identical while allocating two+ # small tensors instead of two image-sized ones.+ values = params["values"].view(-1, 1, 1, 1).to(input)bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])- mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W- mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W+ mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input) # (B, 1, H, W)transformed = torch.where(mask == 1.0, values, input)return transformed@@ -109,14 +112,14 @@ class RandomErasing(IntensityAugmentationBase2D):flags: Dict[str, Any],transform: Optional[torch.Tensor] = None,) -> torch.Tensor:- _, c, h, w = input.size()+ _, _, h, w = input.size()- values = params["values"][..., None, None, None].repeat(1, *input.shape[1:]).to(input)- # Erase the corresponding areas on masks.- values = values.zero_()+ # Erase the corresponding areas on masks (fill with zeros). Broadcast a scalar zero and the+ # single-channel mask (B, 1, H, W) in `torch.where` rather than `repeat`-materializing full+ # (B, C, H, W) tensors β same result, two small allocations instead of two image-sized ones.+ values = torch.zeros((), dtype=input.dtype, device=input.device)bboxes = bbox_generator(params["xs"], params["ys"], params["widths"], params["heights"])- mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W- mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W+ mask = bbox_to_mask(bboxes, w, h).unsqueeze(1).to(input) # (B, 1, H, W)transformed = torch.where(mask == 1.0, values, input)return transformed