Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

replacing .repeat(...) with .expand(...) (#2059)

nitaifingerhutbe3fd5841a4c
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 41682eb10..b491ab836 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -75,7 +75,7 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
B, _, H, W = shape
if self.same_on_batch:
- noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).repeat(B, 1, 1, 1)
+ noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).expand(B, 2, H, W)
else:
noise = torch.rand(B, 2, H, W, device=self.device, dtype=self.dtype)
return dict(noise=noise * 2 - 1)
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index d546cbeda..fb7c3a479 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -57,7 +57,7 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
w: int = int(params["forward_input_shape"][-1])
flip_mat: Tensor = torch.tensor([[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype)
- return flip_mat.repeat(input.size(0), 1, 1)
+ return flip_mat.expand(input.shape[0], 3, 3)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index b5818aae0..f9a8f5805 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -3,9 +3,10 @@ from typing import Any, Dict, List, Optional, Tuple, Union
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
-from kornia.core import Tensor, as_tensor, eye
+from kornia.core import Tensor, as_tensor
from kornia.geometry.transform import affine
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
+from kornia.utils.misc import eye_like
class RandomRotation(GeometricAugmentationBase2D):
@@ -81,7 +82,7 @@ class RandomRotation(GeometricAugmentationBase2D):
rotation_mat: Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))
# rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
- trans_mat: Tensor = eye(3, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)
+ trans_mat: Tensor = eye_like(3, input, shared_memory=False)
trans_mat[:, 0] = rotation_mat[:, 0]
trans_mat[:, 1] = rotation_mat[:, 1]
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index 597f3194c..7bb82df92 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -53,7 +53,7 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
B, _, _, _ = shape
- src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).repeat(B, 1, 1) # Bx5x2
+ src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2
dst = src + self.dist.rsample(src.shape)
return dict(src=src, dst=dst)
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index d51077a1c..539196878 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -50,7 +50,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
h: int = int(params["forward_input_shape"][-2])
flip_mat: Tensor = torch.tensor([[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype)
- return flip_mat.repeat(input.size(0), 1, 1)
+ return flip_mat.expand(input.shape[0], 3, 3)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index 5bd6f7d63..a704985b0 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -71,7 +71,7 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
flip_mat: Tensor = torch.tensor(
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
)
- return flip_mat.repeat(input.size(0), 1, 1)
+ return flip_mat.expand(input.shape[0], 4, 4)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
index a57963445..480032c11 100644
--- a/kornia/augmentation/_3d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -65,7 +65,7 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
flip_mat: Tensor = torch.tensor(
[[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
)
- return flip_mat.repeat(input.size(0), 1, 1)
+ return flip_mat.expand(input.shape[0], 4, 4)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
index 43b2cef3d..3b09d5873 100644
--- a/kornia/augmentation/_3d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -71,7 +71,7 @@ class RandomVerticalFlip3D(AugmentationBase3D):
flip_mat: Tensor = torch.tensor(
[[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
)
- return flip_mat.repeat(input.size(0), 1, 1)
+ return flip_mat.expand(input.shape[0], 4, 4)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index 4f6207a5d..3625cec59 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -46,9 +46,9 @@ def spvs_coarse(data, config):
# 2. warp grids
# create kpts in meshgrid and resize them to image resolution
- grid_pt0_c = create_meshgrid(h0, w0, False, device).reshape(1, h0 * w0, 2).repeat(N, 1, 1) # [N, hw, 2]
+ grid_pt0_c = create_meshgrid(h0, w0, False, device).reshape(1, h0 * w0, 2).expand(N, h0 * w0, 2) # [N, hw, 2]
grid_pt0_i = scale0 * grid_pt0_c
- grid_pt1_c = create_meshgrid(h1, w1, False, device).reshape(1, h1 * w1, 2).repeat(N, 1, 1)
+ grid_pt1_c = create_meshgrid(h1, w1, False, device).reshape(1, h1 * w1, 2).expand(N, h1 * w1, 2)
grid_pt1_i = scale1 * grid_pt1_c
# mask padded region to (0, 0), so no need to manually mask conf_matrix_gt
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 5db341a95..dea623083 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -52,7 +52,7 @@ class BlurPool2D(Module):
def forward(self, input: Tensor) -> Tensor:
# To align the logic with the whole lib
kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
- return _blur_pool_by_kernel2d(input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride)
+ return _blur_pool_by_kernel2d(input, kernel.repeat((input.shape[1], 1, 1, 1)), self.stride)
class MaxBlurPool2D(Module):
@@ -181,21 +181,21 @@ def max_blur_pool2d(
"""
if not len(input.shape) == 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
- kernel = get_pascal_kernel_2d(kernel_size, norm=True).repeat((input.size(1), 1, 1, 1)).to(input)
+ kernel = get_pascal_kernel_2d(kernel_size, norm=True).repeat((input.shape[1], 1, 1, 1)).to(input)
return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size, ceil_mode)
def _blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int):
"""Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- if not (len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2)):
+ if not (len(kernel.shape) == 4 and kernel.shape[-1] == kernel.shape[-2]):
raise AssertionError(f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}")
padding: Tuple[int, int] = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
- return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.size(1))
+ return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.shape[1])
def _max_blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int, max_pool_size: int, ceil_mode: bool):
"""Compute max_blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- if not (len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2)):
+ if not (len(kernel.shape) == 4 and kernel.shape[-1] == kernel.shape[-2]):
raise AssertionError(f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}")
# compute local maxima
input = F.max_pool2d(input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index d5c9d50fe..e70e3d469 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -9,6 +9,7 @@ from kornia.constants import pi
from kornia.core import Tensor, concatenate, pad, stack, tensor, where
from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils.helpers import _torch_inverse_cast
+from kornia.utils.misc import eye_like
__all__ = [
"rad2deg",
@@ -337,9 +338,7 @@ def angle_axis_to_rotation_matrix(angle_axis: Tensor) -> Tensor:
mask_neg = (~mask).type_as(theta2)
# create output pose matrix
- batch_size = angle_axis.shape[0]
- rotation_matrix = torch.eye(3).to(angle_axis.device).type_as(angle_axis)
- rotation_matrix = rotation_matrix.view(1, 3, 3).repeat(batch_size, 1, 1)
+ rotation_matrix = eye_like(3, angle_axis, shared_memory=False)
# fill output matrix with masked values
rotation_matrix[..., :3, :3] = mask_pos * rotation_matrix_normal + mask_neg * rotation_matrix_taylor
return rotation_matrix # Nx3x3
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 16dfafcb1..e26d019e8 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -6,6 +6,7 @@ import torch.nn as nn
from kornia.filters import gaussian_blur2d
from kornia.utils import _extract_device_dtype
from kornia.utils.image import perform_keep_shape_image
+from kornia.utils.misc import eye_like
from .imgwarp import get_affine_matrix2d, get_projective_transform, get_rotation_matrix2d, warp_affine, warp_affine3d
@@ -86,8 +87,7 @@ def _compute_rotation_matrix3d(
def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:
"""Compute affine matrix for translation."""
- matrix: torch.Tensor = torch.eye(3, device=translation.device, dtype=translation.dtype)
- matrix = matrix.repeat(translation.shape[0], 1, 1)
+ matrix: torch.Tensor = eye_like(3, translation, shared_memory=False)
dx, dy = torch.chunk(translation, chunks=2, dim=-1)
matrix[..., 0, 2:3] += dx
@@ -104,8 +104,7 @@ def _compute_scaling_matrix(scale: torch.Tensor, center: torch.Tensor) -> torch.
def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:
"""Compute affine matrix for shearing."""
- matrix: torch.Tensor = torch.eye(3, device=shear.device, dtype=shear.dtype)
- matrix = matrix.repeat(shear.shape[0], 1, 1)
+ matrix: torch.Tensor = eye_like(3, shear, shared_memory=False)
shx, shy = torch.chunk(shear, chunks=2, dim=-1)
matrix[..., 0, 1:2] += shx
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index f7fb46b15..d9f35e9a1 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -118,7 +118,9 @@ def warp_perspective(
# this piece of code substitutes F.affine_grid since it does not support 3x3
grid = (
- create_meshgrid(h_out, w_out, normalized_coordinates=True, device=src.device).to(src.dtype).repeat(B, 1, 1, 1)
+ create_meshgrid(h_out, w_out, normalized_coordinates=True, device=src.device)
+ .to(src.dtype)
+ .expand(B, h_out, w_out, 2)
)
grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid)
@@ -917,7 +919,7 @@ def get_projective_transform(center: Tensor, angles: Tensor, scales: Tensor) ->
rmat = rmat @ scaling_matrix.to(rmat)
# define matrix to move forth and back to origin
- from_origin_mat = eye(4)[None].repeat(rmat.shape[0], 1, 1).type_as(center) # Bx4x4
+ from_origin_mat = eye_like(4, rmat, shared_memory=False) # Bx4x4
from_origin_mat[..., :3, -1] += center
to_origin_mat = from_origin_mat.clone()
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index c5ea03402..2ff677c54 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -87,7 +87,7 @@ def check_is_tensor(obj):
def create_rectified_fundamental_matrix(batch_size):
"""Create a batch of rectified fundamental matrices of shape Bx3x3."""
F_rect = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
- F_repeat = F_rect.repeat(batch_size, 1, 1)
+ F_repeat = F_rect.expand(batch_size, 3, 3)
return F_repeat
diff --git a/kornia/utils/misc.py b/kornia/utils/misc.py
index 04a3a7f24..b81977b9b 100644
--- a/kornia/utils/misc.py
+++ b/kornia/utils/misc.py
@@ -1,16 +1,22 @@
import torch
-def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:
+def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.
Args:
n: the number of rows :math:`(N)`.
input: image tensor that will determine the batch size of the output matrix.
The expected shape is :math:`(B, *)`.
+ shared_memory: when set, all samples in the batch will share the same memory.
Returns:
The identity matrix with the same batch size as the input :math:`(B, N, N)`.
+
+ Notes:
+ When the dimension to expand is of size 1, using torch.expand(...) yields the same tensor as torch.repeat(...)
+ without using extra memory. Thus, when the tensor obtained by this method will be later assigned -
+ use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
"""
if n <= 0:
raise AssertionError(type(n), n)
@@ -18,19 +24,25 @@ def eye_like(n: int, input: torch.Tensor) -> torch.Tensor:
raise AssertionError(input.shape)
identity = torch.eye(n, device=input.device, dtype=input.dtype)
- return identity[None].repeat(input.shape[0], 1, 1)
+ return identity[None].expand(input.shape[0], n, n) if shared_memory else identity[None].repeat(input.shape[0], 1, 1)
-def vec_like(n, tensor):
+def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False):
r"""Return a 2-D tensor with a vector containing zeros with the same batch size as the input.
Args:
n: the number of rows :math:`(N)`.
tensor: image tensor that will determine the batch size of the output matrix.
The expected shape is :math:`(B, *)`.
+ shared_memory: when set, all samples in the batch will share the same memory.
Returns:
The vector with the same batch size as the input :math:`(B, N, 1)`.
+
+ Notes:
+ When the dimension to expand is of size 1, using torch.expand(...) yields the same tensor as torch.repeat(...)
+ without using extra memory. Thus, when the tensor obtained by this method will be later assigned -
+ use this method with shared_memory=False, otherwise, prefer using it with shared_memory=True.
"""
if n <= 0:
raise AssertionError(type(n), n)
@@ -38,4 +50,4 @@ def vec_like(n, tensor):
raise AssertionError(tensor.shape)
vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
- return vec[None].repeat(tensor.shape[0], 1, 1)
+ return vec[None].expand(tensor.shape[0], n, 1) if shared_memory else vec[None].repeat(tensor.shape[0], 1, 1)