š Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): per-op Convention blocks for transform warps, with convention-pinning tests (#3924)
Dmytro Mishkinb193c4ffd107
diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rstindex 1b398d969..acb8bc163 100644--- a/docs/source/geometry.transform.rst+++ b/docs/source/geometry.transform.rst@@ -22,6 +22,8 @@ Warp operators.. autofunction:: warp_grid.. autofunction:: warp_grid3d.. autofunction:: remap+.. autofunction:: homography_warp+.. autofunction:: homography_warp3dImage 2d transforms-------------------@@ -35,6 +37,7 @@ Image 2d transforms.. autofunction:: vflip.. autofunction:: rot180.. autofunction:: resize+.. autofunction:: resize_to_be_divisible.. autofunction:: rescale.. autofunction:: elastic_transform2d.. autofunction:: pyrdown@@ -42,6 +45,12 @@ Image 2d transforms.. autofunction:: build_pyramid.. autofunction:: build_laplacian_pyramid+Image 3d transforms+-------------------++.. autofunction:: affine3d+.. autofunction:: rotate3d+Matrix transformations----------------------@@ -49,6 +58,7 @@ Matrix transformations.. autofunction:: get_perspective_transform3d.. autofunction:: get_projective_transform.. autofunction:: get_rotation_matrix2d+.. autofunction:: get_translation_matrix2d.. autofunction:: get_shear_matrix2d.. autofunction:: get_shear_matrix3d.. autofunction:: get_affine_matrix2d@@ -83,6 +93,7 @@ Module.. autoclass:: Resize.. autoclass:: Rescale.. autoclass:: Affine+.. autoclass:: BaseWarper.. autoclass:: HomographyWarperdiff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex fc71e6e45..068df0d20 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -144,13 +144,18 @@ def affine(.. image:: _static/img/warp_affine.png+ Convention:+ - ``matrix`` is the sourceādestination **pixel** affine matrix :math:`(B, 2, 3)`+ - align_corners: ``True`` by default+ - padding_mode: ``'zeros'`` by default+Args:tensor: The image tensor to be warped in shapes of- :math:`(H, W)`, :math:`(D, H, W)` and :math:`(B, C, H, W)`.+ :math:`(C, H, W)` or :math:`(B, C, H, W)`.matrix: The 2x3 affine transformation matrix.mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -197,14 +202,19 @@ def affine3d() -> torch.Tensor:r"""Apply an affine transformation to the 3d volume.+ Convention:+ - ``matrix`` is the sourceādestination **pixel** affine matrix :math:`(B, 3, 4)`+ - align_corners: ``False`` by default+ - padding_mode: ``'zeros'`` by default+Args:tensor: The image tensor to be warped in shapes of- :math:`(D, H, W)`, :math:`(C, D, H, W)` and :math:`(B, C, D, H, W)`.+ :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`.matrix: The affine transformation matrix with shape :math:`(B, 3, 4)`.mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- `` 'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ `` 'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -256,6 +266,12 @@ def rotate(.. image:: _static/img/rotate.png+ Convention:+ - ``center`` is ``(x, y)`` in pixels, origin at top-left; defaults to the tensor center+ - positive ``angle`` rotates counter-clockwise as displayed (y-down image axes)+ - align_corners: ``True`` by default+ - padding_mode: ``'zeros'`` by default+Args:tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.angle: The angle through which to rotate. The tensor@@ -266,7 +282,7 @@ def rotate(mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -321,6 +337,12 @@ def rotate3d() -> torch.Tensor:r"""Rotate 3D the tensor anti-clockwise about the centre.+ Convention:+ - ``center`` is ``(x, y, z)`` in pixels, origin at the top-left of the first depth+ slice (``z = 0``); defaults to the tensor center+ - align_corners: ``False`` by default+ - padding_mode: ``'zeros'`` by default+Args:tensor: The image tensor to be warped in shapes of :math:`(B, C, D, H, W)`.yaw: The yaw angle through which to rotate. The tensor@@ -330,12 +352,12 @@ def rotate3d(roll: The roll angle through which to rotate. The tensormust have a shape of (B), where B is batch size.center: The center through which to rotate. The tensor- must have a shape of (B, 2), where B is batch size and last- dimension contains cx and cy.+ must have a shape of (B, 3), where B is batch size and last+ dimension contains x, y and z.mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -387,6 +409,11 @@ def translate(.. image:: _static/img/translate.png+ Convention:+ - ``translation`` is ``(dx, dy)`` in pixels+ - align_corners: ``True`` by default+ - padding_mode: ``'zeros'`` by default+Args:tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.translation: tensor containing the amount of pixels to@@ -395,7 +422,7 @@ def translate(mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -437,6 +464,11 @@ def scale(.. image:: _static/img/scale.png+ Convention:+ - ``center`` is ``(x, y)`` in pixels, origin at top-left; defaults to the tensor center+ - align_corners: ``True`` by default+ - padding_mode: ``'zeros'`` by default+Args:tensor: The image tensor to be warped in shapes of :math:`(B, C, H, W)`.scale_factor: The scale factor apply. The tensor@@ -449,7 +481,7 @@ def scale(mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -498,6 +530,11 @@ def shear(.. image:: _static/img/shear.png+ Convention:+ - ``shear`` is ``(shx, shy)``+ - align_corners: ``False`` by default+ - padding_mode: ``'zeros'`` by default+Args:tensor: The image tensor to be skewed with shape of :math:`(B, C, H, W)`.shear: tensor containing the angle to shear@@ -506,7 +543,7 @@ def shear(mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -560,6 +597,12 @@ def resize(.. image:: _static/img/resize.png+ Convention:+ - input: :math:`(*, H, W)`; ``size`` is ``(h, w)``+ - align_corners: ``None`` by default (follows ``torch.nn.functional.interpolate``;+ note :func:`warp_perspective`/:func:`rotate` default ``True``)+ - ``side`` resizing preserves aspect ratio using the named side+Args:input: The image tensor to be skewed with shape of :math:`(..., H, W)`.`...` means there can be any number of dimensions.@@ -643,6 +686,11 @@ def resize_to_be_divisible() -> torch.Tensor:"""Resize the input tensor to be divisible by a certain factor.+ Convention:+ - align_corners: ``None`` by default; see the convention block of :func:`resize`+ - rounds ``height``/``width`` to the nearest multiple of ``divisible_factor`` before+ delegating to :func:`resize`+Args:input (torch.Tensor): Input tensor to be resized.divisible_factor (int): The factor to which the image should be divisible.@@ -678,15 +726,20 @@ def rescale(.. image:: _static/img/rescale.png+ Convention:+ - ``factor`` is ``(factor_h, factor_w)`` when a pair ā height first (contrast+ :func:`scale`, whose ``scale_factor`` is x-first)+ - align_corners: ``None`` by default (follows ``torch.nn.functional.interpolate``;+ see the convention block of :func:`resize`)+ - delegates to :func:`resize` after converting ``factor`` to an output ``size``+Args:input: The image tensor to be scale with shape of :math:`(B, C, H, W)`.- factor: Desired scaling factor in each direction. If scalar, the value is used- for both the x- and y-direction.+ factor: Desired scaling factor as ``(factor_h, factor_w)`` ā height first. If a single+ float, the value is used for both height and width (an ``int`` raises ``TypeError``).interpolation: algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` |``'bicubic'`` | ``'trilinear'`` | ``'area'``.align_corners: interpolation flag.- side: Corresponding side if ``size`` is an integer. Can be one of ``'short'``, ``'long'``, ``'vert'``,- or ``'horz'``.antialias: if True, then image will be filtered with Gaussian before downscaling.No effect for upscaling.@@ -713,6 +766,10 @@ def rescale(class Resize(nn.Module):r"""Resize the input torch.Tensor to the given size.+ Convention:+ - align_corners: ``None`` by default, matching :func:`resize`+ - See the convention block of :func:`resize`.+Args:size: Desired output size. If size is a sequence like (h, w),output size will be matched to this. If size is an int, smaller edge of the image will@@ -783,6 +840,10 @@ class Resize(nn.Module):class Affine(nn.Module):r"""Apply multiple elementary affine transforms simultaneously.+ Convention:+ - align_corners: ``True`` by default, matching :func:`affine`+ - See the convention block of :func:`affine`.+Args:angle: Angle in degrees for counter-clockwise rotation around the center. The tensormust have a shape of (B), where B is the batch size.@@ -799,7 +860,7 @@ class Affine(nn.Module):mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Raises:@@ -896,14 +957,17 @@ class Affine(nn.Module):class Rescale(nn.Module):r"""Rescale the input torch.Tensor with the given factor.+ Convention:+ - align_corners: ``True`` by default (differs from function :func:`rescale`, whose default+ is ``None``)+ - See the convention block of :func:`rescale`.+Args:- factor: Desired scaling factor in each direction. If scalar, the value is used- for both the x- and y-direction.+ factor: Desired scaling factor as ``(factor_h, factor_w)`` ā height first. If a single+ float, the value is used for both height and width (an ``int`` raises ``TypeError``).interpolation: algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` |``'bicubic'`` | ``'trilinear'`` | ``'area'``.align_corners: interpolation flag.- side: Corresponding side if ``size`` is an integer. Can be one of ``'short'``, ``'long'``, ``'vert'``,- or ``'horz'``.antialias: if True, then image will be filtered with Gaussian before downscaling.No effect for upscaling.@@ -951,6 +1015,10 @@ class Rescale(nn.Module):class Rotate(nn.Module):r"""Rotate the tensor anti-clockwise about the centre.+ Convention:+ - align_corners: ``True`` by default, matching :func:`rotate`+ - See the convention block of :func:`rotate`.+Args:angle: The angle through which to rotate. The tensormust have a shape of (B), where B is batch size.@@ -960,7 +1028,7 @@ class Rotate(nn.Module):mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -1009,6 +1077,10 @@ class Rotate(nn.Module):class Translate(nn.Module):r"""Translate the tensor in pixel units.+ Convention:+ - align_corners: ``True`` by default, matching :func:`translate`+ - See the convention block of :func:`translate`.+Args:translation: tensor containing the amount of pixels totranslate in the x and y direction. The tensor must have a shape of@@ -1016,7 +1088,7 @@ class Translate(nn.Module):mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -1062,6 +1134,10 @@ class Translate(nn.Module):class Scale(nn.Module):r"""Scale the tensor by a factor.+ Convention:+ - align_corners: ``True`` by default, matching :func:`scale`+ - See the convention block of :func:`scale`.+Args:scale_factor: The scale factor apply. The tensormust have a shape of (B) or (B, 2), where B is batch size.@@ -1073,7 +1149,7 @@ class Scale(nn.Module):mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:@@ -1121,6 +1197,11 @@ class Scale(nn.Module):class Shear(nn.Module):r"""Shear the tensor.+ Convention:+ - align_corners: ``True`` by default (differs from function :func:`shear`, whose default is+ ``False``)+ - See the convention block of :func:`shear`.+Args:shear: tensor containing the angle to shearin the x and y direction. The tensor must have a shape of@@ -1128,7 +1209,7 @@ class Shear(nn.Module):mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.Returns:diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.pyindex 595b034f8..a601c05a3 100644--- a/kornia/geometry/transform/homography_warper.py+++ b/kornia/geometry/transform/homography_warper.py@@ -32,7 +32,12 @@ __all__ = ["BaseWarper", "HomographyWarper"]class BaseWarper(nn.Module):- """Provide a base class for homography-based image warping."""+ """Provide a base class for homography-based image warping.++ Convention:+ - subclasses receive ``src_homo_dst`` as the destinationāsource homography++ """def __init__(self, height: int, width: int, *args: Any, **kwargs: Any) -> None:super().__init__(*args, **kwargs)@@ -74,14 +79,18 @@ class HomographyWarper(BaseWarper):.. math::- X_{dst} = H_{src}^{\{dst\}} * X_{src}+ X_{src} = H_{src}^{\{dst\}} * X_{dst}++ Convention:+ - align_corners: ``False`` by default, matching :func:`homography_warp`+ - See the convention block of :func:`homography_warp`.Args:height: The height of the destination torch.Tensor.width: The width of the destination torch.Tensor.mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.normalized_coordinates: whether to use a grid with normalized coordinates.align_corners: interpolation flag.@@ -117,7 +126,7 @@ class HomographyWarper(BaseWarper):Args:src_homo_dst: Homography or homographies (stacked) totransform all points in the grid. Shape of the homography- has to be :math:`(1, 3, 3)` or :math:`(N, 1, 3, 3)`.+ has to be :math:`(1, 3, 3)`, :math:`(N, 3, 3)` or :math:`(N, 1, 3, 3)`.The homography assumes normalized coordinates [-1, 1] ifnormalized_coordinates is True.diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 7cd4ba7dd..966b5e6bf 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -86,18 +86,26 @@ def warp_perspective(\frac{M^{-1}_{21} x + M^{-1}_{22} y + M^{-1}_{23}}{M^{-1}_{31} x + M^{-1}_{32} y + M^{-1}_{33}}\right )+ Convention:+ - input: :math:`(B, C, H, W)`; ``dsize`` is ``(h, w)``+ - ``M`` is the sourceādestination **pixel** homography :math:`(B, 3, 3)`+ (contrast :func:`homography_warp`, which by default consumes destinationāsource normalized)+ - coordinates: ``(x, y)``, pixel centers, origin at top-left+ - align_corners: ``True`` by default+ - padding_mode: ``'zeros'`` by default+Args:src: input image with shape :math:`(B, C, H, W)`.M: transformation matrix with shape :math:`(B, 3, 3)`.dsize: size of the output image (height, width).mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.- padding_mode: padding mode for outside grid values ``'torch.zeros'`` | ``'border'`` | ``'reflection'``+ padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``| ``'fill'``.align_corners: interpolation flag.fill_value: torch.Tensor of shape :math:`(3)` that fills the padding area. Only supported for RGB.Returns:- the warped input image :math:`(B, C, H, W)`.+ the warped input image :math:`(B, C, h, w)`, spatial sizes given by ``dsize``.Example:>>> img = torch.rand(1, 4, 5, 6)@@ -183,21 +191,30 @@ def warp_affine(the specified matrix:.. math::- \text{dst}(x, y) = \text{src} \left( M_{11} x + M_{12} y + M_{13} ,- M_{21} x + M_{22} y + M_{23} \right )+ \text{dst}(x, y) = \text{src} \left( M^{-1}_{11} x + M^{-1}_{12} y + M^{-1}_{13} ,+ M^{-1}_{21} x + M^{-1}_{22} y + M^{-1}_{23} \right )++ where :math:`M^{-1}` is the inverse of the :math:`3 \times 3` homogeneous extension of ``M``.++ Convention:+ - input: :math:`(B, C, H, W)`; ``dsize`` is ``(h, w)``+ - ``M`` is the sourceādestination **pixel** affine matrix :math:`(B, 2, 3)`+ - coordinates: ``(x, y)``, pixel centers, origin at top-left+ - align_corners: ``True`` by default+ - padding_mode: ``'zeros'`` by defaultArgs:src: input torch.Tensor of shape :math:`(B, C, H, W)`.M: affine transformation of shape :math:`(B, 2, 3)`.dsize: size of the output image (height, width).mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.- padding_mode: padding mode for outside grid values ``'torch.zeros'`` | ``'border'`` | ``'reflection'``+ padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``| ``'fill'``.align_corners : mode for grid_generation.fill_value: torch.Tensor of shape :math:`(C)` or :math:`(1)` that fills the padding area.Returns:- the warped torch.Tensor with shape :math:`(B, C, H, W)`.+ the warped torch.Tensor with shape :math:`(B, C, h, w)`, spatial sizes given by ``dsize``... note::This function is often used in conjunction with :func:`get_rotation_matrix2d`,@@ -306,11 +323,19 @@ def _fill_and_warp(def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:r"""Compute the grid to warp the coordinates grid by the homography/ies.+ Convention:+ - ``grid`` coordinates: ``(x, y)`` (last dim), shape :math:`(1, H, W, 2)` or :math:`(N, H, W, 2)`+ - ``src_homo_dst`` is the destinationāsource homography :math:`(1, 3, 3)`,+ :math:`(N, 3, 3)` or :math:`(N, 1, 3, 3)`+ - only the :math:`(1, H, W, 2)` grid broadcasts over homography batches; a batched grid+ requires a matching batch of :math:`N` homographies+Args:- grid: Unwrapped grid of the shape :math:`(1, H, W, 2)`.+ grid: Unwrapped grid of the shape :math:`(1, H, W, 2)`, or :math:`(N, H, W, 2)` with a+ matching batch of :math:`N` homographies.src_homo_dst: Homography or homographies (stacked) totransform all points in the grid. Shape of the homography- has to be :math:`(1, 3, 3)` or :math:`(N, 1, 3, 3)`.+ has to be :math:`(1, 3, 3)`, :math:`(N, 3, 3)` or :math:`(N, 1, 3, 3)`.Returns:the transformed grid of shape :math:`(N, H, W, 2)`.@@ -331,14 +356,23 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:r"""Compute the grid to warp the coordinates grid by the homography/ies.+ Convention:+ - ``grid`` coordinates: ``(x, y, z)`` (last dim), shape :math:`(1, D, H, W, 3)` or+ :math:`(N, D, H, W, 3)`+ - ``src_homo_dst`` is the destinationāsource homography :math:`(1, 4, 4)`,+ :math:`(N, 4, 4)` or :math:`(N, 1, 4, 4)`+ - only the :math:`(1, D, H, W, 3)` grid broadcasts over homography batches; a batched+ grid requires a matching batch of :math:`N` homographies+Args:- grid: Unwrapped grid of the shape :math:`(1, D, H, W, 3)`.+ grid: Unwrapped grid of the shape :math:`(1, D, H, W, 3)`, or :math:`(N, D, H, W, 3)`+ with a matching batch of :math:`N` homographies.src_homo_dst: Homography or homographies (stacked) totransform all points in the grid. Shape of the homography- has to be :math:`(1, 4, 4)` or :math:`(N, 1, 4, 4)`.+ has to be :math:`(1, 4, 4)`, :math:`(N, 4, 4)` or :math:`(N, 1, 4, 4)`.Returns:- the transformed grid of shape :math:`(N, H, W, 3)`.+ the transformed grid of shape :math:`(N, D, H, W, 3)`."""batch_size: int = src_homo_dst.size(0)@@ -457,6 +491,11 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor1 \\\end{bmatrix}+ Convention:+ - points: ``(x, y)``, pixel centers, origin at top-left; shape :math:`(B, 4, 2)`+ - returns the sourceādestination **pixel** homography :math:`(B, 3, 3)`+ (contrast :func:`homography_warp`, which by default consumes destinationāsource normalized)+Args:points_src: coordinates of quadrangle vertices in the source image with shape :math:`(B, 4, 2)`.points_dst: coordinates of the corresponding quadrangle vertices in@@ -509,6 +548,11 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torcThe transformation maps the rotation center to itselfIf this is not the target, adjust the shift.+ Convention:+ - ``center`` is ``(x, y)`` in pixels, origin at top-left+ - positive ``angle`` rotates counter-clockwise as displayed (y-down image axes)+ - returns :math:`(B, 2, 3)` affine matrix in pixel coordinates+Args:center: center of the rotation in the source image with shape :math:`(B, 2)`.angle: rotation angle in degrees. Positive values mean@@ -596,6 +640,12 @@ def remap(.. math::\text{dst}(x, y) = \text{src}(map_x(x, y), map_y(x, y))+ Convention:+ - input: :math:`(B, C, H, W)`; ``map_x``/``map_y`` are :math:`(B, H, W)` pixel coordinates+ unless ``normalized_coordinates=True``+ - align_corners: ``None`` by default, resolved to ``False`` internally+ - padding_mode: ``'zeros'`` by default+Args:image: the torch.Tensor to remap with shape (B, C, H, W).Where C is the number of channels.@@ -606,7 +656,7 @@ def remap(mode: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: mode for grid_generation.normalized_coordinates: whether the input coordinates arenormalized in the range of [-1, 1].@@ -666,6 +716,10 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:The result is also a 2x3 matrix of the same type as M.+ Convention:+ - ``matrix`` is a :math:`(B, 2, 3)` affine transform in any coordinate convention+ (pixel or normalized) ā pure matrix inversion; the result stays in the input's convention+Args:matrix: original affine transform. The torch.Tensor must bein the shape of :math:`(B, 2, 3)`.@@ -699,6 +753,12 @@ def get_affine_matrix2d() -> torch.Tensor:r"""Compose affine matrix from the components.+ Convention:+ - ``center`` is ``(x, y)`` in pixels, origin at top-left+ - positive ``angle`` rotates **clockwise** as displayed ā this function negates ``angle``+ before delegating to :func:`get_rotation_matrix2d`, whose convention is CCW-positive+ - returns :math:`(B, 3, 3)` affine matrix in pixel coordinates+Args:translations: torch.Tensor containing the translation vector with shape :math:`(B, 2)`.center: torch.Tensor containing the center vector with shape :math:`(B, 2)`.@@ -730,6 +790,9 @@ def get_affine_matrix2d(def get_translation_matrix2d(translations: torch.Tensor) -> torch.Tensor:r"""Compose translation matrix from the components.+ Convention:+ - ``translations`` is ``(dx, dy)`` in pixels; returns :math:`(B, 3, 3)` affine matrix in pixel coordinates+Args:translations: torch.Tensor containing the translation vector with shape :math:`(B, 2)`.@@ -752,7 +815,7 @@ def get_translation_matrix2d(translations: torch.Tensor) -> torch.Tensor:def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None, sy: Optional[torch.Tensor] = None) -> torch.Tensor:- r"""Compose shear matrix Bx4x4 from the components.+ r"""Compose shear matrix Bx3x3 from the components.Note: Ordered shearing, shear x-axis then y-axis.@@ -762,6 +825,10 @@ def get_shear_matrix2d(a & ab + 1 \\\end{bmatrix}+ Convention:+ - ``center`` is ``(x, y)`` in pixels, origin at top-left+ - returns :math:`(B, 3, 3)` affine matrix in pixel coordinates+Args:center: shearing center coordinates of (x, y).sx: shearing angle along x axis in radiants.@@ -816,6 +883,14 @@ def get_affine_matrix3d() -> torch.Tensor:r"""Compose 3d affine matrix from the components.+ Convention:+ - ``center`` is ``(x, y, z)`` in pixels, origin at the top-left of the first depth+ slice (``z = 0``)+ - ``angles`` are negated before delegating to :func:`get_projective_transform`, whose own+ rotation convention follows the right-hand rule (see+ :func:`kornia.geometry.conversions.axis_angle_to_rotation_matrix`)+ - returns :math:`(B, 4, 4)` affine matrix in pixel coordinates+Args:translations: torch.Tensor containing the translation vector (dx,dy,dz) with shape :math:`(B, 3)`.center: torch.Tensor containing the center vector (x,y,z) with shape :math:`(B, 3)`.@@ -831,10 +906,10 @@ def get_affine_matrix3d(szy: torch.Tensor containing the shear factor in the zy-direction with shape :math:`(B)`.Returns:- the 3d affine transformation matrix :math:`(B, 3, 3)`.+ the 3d affine transformation matrix :math:`(B, 4, 4)`... note::- This function is often used in conjunction with :func:`warp_perspective`.+ This function is often used in conjunction with :func:`warp_perspective3d`."""transform: torch.Tensor = get_projective_transform(center, -angles, scale)@@ -879,7 +954,12 @@ def get_shear_matrix3d(s = S_{xy}S_{zx} + (S_{xy}S_{yx} + 1)S_{zy}t = S_{xz}S_{zx} + (S_{xz}S_{yx} + S_{yz})S_{zy} + 1- Params:+ Convention:+ - ``center`` is ``(x, y, z)`` in pixels, origin at the top-left of the first depth+ slice (``z = 0``)+ - returns :math:`(B, 4, 4)` affine matrix in pixel coordinates++ Args:center: shearing center coordinates of (x, y, z).sxy: shearing angle along x axis, towards y plane in radiants.sxz: shearing angle along x axis, towards z plane in radiants.@@ -976,6 +1056,12 @@ def warp_affine3d(.. warning::This API signature it is experimental and might suffer some changes in the future.+ Convention:+ - input: :math:`(B, C, D, H, W)`; ``dsize`` is ``(d, h, w)``+ - ``M`` is the sourceādestination **pixel** affine matrix :math:`(B, 3, 4)`+ - align_corners: ``True`` by default+ - padding_mode: ``'zeros'`` by default+Args:src : input torch.Tensor of shape :math:`(B, C, D, H, W)`.M: projective transformation matrix of shape :math:`(B, 3, 4)`.@@ -983,11 +1069,12 @@ def warp_affine3d(flags: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values- ``'torch.zeros'`` | ``'border'`` | ``'reflection'``.+ ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners : mode for grid_generation.Returns:- torch.Tensor: the warped 3d torch.tensor with shape :math:`(B, C, D, H, W)`.+ torch.Tensor: the warped 3d torch.tensor with shape :math:`(B, C, d, h, w)`, spatial sizes+ given by ``dsize``... note::This function is often used in conjunction with :func:`get_perspective_transform3d`.@@ -1026,6 +1113,9 @@ def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:Concatenates the batch of rotations and translations such that :math:`P = [R | t]`.+ Convention:+ - returns the concatenation :math:`[R | t]` with shape :math:`(*, 3, 4)`+Args:rmat: the rotation matrix with shape :math:`(*, 3, 3)`.tvec: the translation vector with shape :math:`(*, 3, 1)`.@@ -1050,6 +1140,14 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:The function computes the projection matrix given the center and angles per axis.+ Convention:+ - ``center`` is ``(x, y, z)`` in pixels, origin at the top-left of the first depth+ slice (``z = 0``)+ - rotation follows the right-hand rule (see+ :func:`kornia.geometry.conversions.axis_angle_to_rotation_matrix`); a positive rotation+ about +z is **clockwise on screen** (y-down image axes) ā opposite of :func:`get_rotation_matrix2d`+ - returns the projection matrix :math:`(B, 3, 4)` in pixel coordinates+Args:center: center of the rotation (x,y,z) in the source with shape :math:`(B, 3)`.angles: axis angle vector containing the rotation angles in degrees in the form@@ -1155,6 +1253,10 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & x_7 & y_7 & z_7 & 1 & -x_7*w_7 & -y_7*w_7 & -z_7 * w_7 \\\end{pmatrix}+ Convention:+ - points: ``(x, y, z)``, pixel centers, origin at the top-left of the first depth slice; shape :math:`(B, 8, 3)`+ - returns the sourceādestination **pixel** homography :math:`(B, 4, 4)`+Args:src: coordinates of quadrangle vertices in the source image with shape :math:`(B, 8, 3)`.dst: coordinates of the corresponding quadrangle vertices in@@ -1326,15 +1428,21 @@ def warp_perspective3d(the specified matrix:.. math::- \text{dst} (x, y) = \text{src} \left(- \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} ,- \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}}- \right )+ \text{dst}(x, y, z) = \text{src}\left( \pi\left( M^{-1} \cdot (x, y, z, 1)^{T} \right) \right)++ where :math:`\pi` divides by the fourth (homogeneous) coordinate.++ Convention:+ - input: :math:`(B, C, D, H, W)`; ``dsize`` is ``(d, h, w)``+ - ``M`` is the sourceādestination **pixel** homography :math:`(B, 4, 4)`+ - align_corners: ``False`` by default (differs from the 2D :func:`warp_perspective`,+ whose default is ``True``)+ - border_mode: ``'zeros'`` by defaultArgs:src: input image with shape :math:`(B, C, D, H, W)`.M: transformation matrix with shape :math:`(B, 4, 4)`.- dsize: size of the output image (height, width).+ dsize: size of the output image (depth, height, width).flags: interpolation mode to calculate output values``'bilinear'`` | ``'nearest'``.border_mode: padding mode for outside grid values@@ -1342,7 +1450,7 @@ def warp_perspective3d(align_corners: interpolation flag.Returns:- the warped input image :math:`(B, C, D, H, W)`.+ the warped input image :math:`(B, C, d, h, w)`, spatial sizes given by ``dsize``... note::This function is often used in conjunction with :func:`get_perspective_transform3d`.@@ -1377,12 +1485,26 @@ def homography_warp() -> torch.Tensor:r"""Warp image patches or tensors by normalized 2D homographies.- See :class:`~kornia.geometry.warp.HomographyWarper` for details.+ See :class:`~kornia.geometry.transform.HomographyWarper` for details.++ Convention:+ - input: :math:`(N, C, H, W)`+ - ``src_homo_dst`` is the destinationāsource homography :math:`(N, 3, 3)`, in normalized+ :math:`[-1, 1]` coordinates by default (``normalized_coordinates=True``), when+ ``normalized_homography=True`` (default); with ``normalized_homography=False`` it is+ consumed as the sourceādestination **pixel** homography, exactly like+ :func:`warp_perspective`+ - ``dsize`` is ``(h, w)``+ - align_corners: ``False`` by default; ``mode``: ``'bilinear'`` by default (both only+ honored when ``normalized_homography=True`` ā the pixel-homography path currently+ forces ``align_corners=True`` and ``mode='bilinear'``)+ - padding_mode: ``'zeros'`` by defaultArgs:patch_src: The image or torch.Tensor to warp. Should be from source of shape :math:`(N, C, H, W)`.- src_homo_dst: The homography or torch.stack of homographies from destination to source of shape- :math:`(N, 3, 3)`.+ src_homo_dst: The homography or torch.stack of homographies of shape :math:`(N, 3, 3)` ā+ destination to source when ``normalized_homography=True`` (default), source to+ destination (pixel) when ``normalized_homography=False``.dsize:if homography normalized: The height and width of the image to warp.if homography not normalized: size of the output image (height, width).@@ -1390,7 +1512,8 @@ def homography_warp(padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.normalized_coordinates: Whether the homography assumes [-1, 1] normalized coordinates or not.- normalized_homography: show is homography normalized.+ normalized_homography: whether ``src_homo_dst`` is a normalized (destinationāsource)+ homography (``True``, default) or a pixel sourceādestination homography (``False``).Return:Patch sampled at locations from source to destination.@@ -1453,11 +1576,18 @@ def homography_warp3d() -> torch.Tensor:r"""Warp image patches or tensors by normalized 3D homographies.+ Convention:+ - input: :math:`(N, C, D, H, W)`; ``dsize`` is ``(d, h, w)``+ - ``src_homo_dst`` is the destinationāsource homography :math:`(N, 4, 4)`, in normalized+ :math:`[-1, 1]` coordinates by default (``normalized_coordinates=True``)+ - align_corners: ``False`` by default+ - padding_mode: ``'zeros'`` by default+Args:patch_src: The image or torch.Tensor to warp. Should be from source of shape :math:`(N, C, D, H, W)`.src_homo_dst: The homography or torch.stack of homographies from destination to source of shape:math:`(N, 4, 4)`.- dsize: The height and width of the image to warp.+ dsize: The depth, height and width of the volume to warp.mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.align_corners: interpolation flag.@@ -1467,9 +1597,9 @@ def homography_warp3d(Patch sampled at locations from source to destination.Example:- >>> input = torch.rand(1, 3, 32, 32)- >>> homography = torch.eye(3).view(1, 3, 3)- >>> output = homography_warp(input, homography, (32, 32))+ >>> input = torch.rand(1, 3, 8, 32, 32)+ >>> homography = torch.eye(4).view(1, 4, 4)+ >>> output = homography_warp3d(input, homography, (8, 32, 32))"""if not src_homo_dst.device == patch_src.device:diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.pyindex 3ba4e47b6..53c4d5bff 100644--- a/tests/geometry/transform/test_affine.py+++ b/tests/geometry/transform/test_affine.py@@ -188,6 +188,42 @@ class TestResize(BaseTester):out = kornia.geometry.transform.resize(inp, 10, align_corners=False, side="horz")assert out.shape == (1, 3, 4, 10)+ def test_convention_align_corners_default_none(self, device, dtype):+ # resize's bare default align_corners=None behaves like align_corners=False (no test in the+ # suite exercises the bare default; every other call here passes align_corners=False explicitly).+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("hardcoded-literal pin only reliable at float32/float64 precision")+ # Snippet used to generate expected:+ # inp_x = torch.arange(20, dtype=torch.float32) / 20.0+ # inp = inp_x[None].T @ inp_x[None]+ # inp = inp[None, None]+ # expected = kornia.geometry.transform.resize(inp, (5, 5), antialias=False) # no align_corners passed+ inp_x = torch.arange(20, device=device, dtype=dtype) / 20.0+ inp = inp_x[None].T @ inp_x[None]+ inp = inp[None, None]+ out = kornia.geometry.transform.resize(inp, (5, 5), antialias=False)+ expected = torch.tensor(+ [+ [+ [+ [0.0056, 0.0206, 0.0356, 0.0506, 0.0656],+ [0.0206, 0.0756, 0.1306, 0.1856, 0.2406],+ [0.0356, 0.1306, 0.2256, 0.3206, 0.4156],+ [0.0506, 0.1856, 0.3206, 0.4556, 0.5906],+ [0.0656, 0.2406, 0.4156, 0.5906, 0.7656],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(out, expected, atol=1e-3, rtol=1e-3)+ # the output above cannot distinguish None from False (they interpolate identically), so+ # the documented default is additionally pinned on the signature itself+ import inspect++ assert inspect.signature(kornia.geometry.transform.resize).parameters["align_corners"].default is None+def test_gradcheck(self, device):# test parametersnew_size = 4@@ -315,6 +351,24 @@ class TestRotate(BaseTester):transform = kornia.geometry.transform.Rotate(angle, align_corners=True)self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)+ def test_convention_align_corners_default_true(self, device, dtype):+ # rotate/Rotate's bare default align_corners=True (every other test in this class passes+ # align_corners=True explicitly to Rotate; this exercises the bare default).+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("hardcoded-literal pin only reliable at float32/float64 precision")+ # Snippet used to generate expected:+ # inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]])+ # angle = torch.tensor([90.0])+ # expected = kornia.geometry.transform.Rotate(angle)(inp) # no align_corners passed+ inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], device=device, dtype=dtype)+ expected = torch.tensor([[[0.0, 0.0], [4.0, 6.0], [3.0, 5.0], [0.0, 0.0]]], device=device, dtype=dtype)+ angle = torch.tensor([90.0], device=device, dtype=dtype)+ transform = kornia.geometry.transform.Rotate(angle)+ self.assert_close(transform(inp), expected, atol=1e-4, rtol=1e-4)+ # the function's own bare default must match (class and function defaults can diverge+ # in this module ā see Rescale vs rescale ā so both APIs are pinned independently)+ self.assert_close(kornia.geometry.transform.rotate(inp, angle), expected, atol=1e-4, rtol=1e-4)+def test_gradcheck(self, device):# test parametersangle = torch.tensor([90.0], device=device, dtype=torch.float64)diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.pyindex 79fc26679..fe9670f59 100644--- a/tests/geometry/transform/test_homography_warper.py+++ b/tests/geometry/transform/test_homography_warper.py@@ -178,6 +178,48 @@ class TestHomographyWarper(BaseTester):self.assert_close(patch_src[..., -1, 0], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)self.assert_close(patch_src[..., -1, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)+ def test_convention_align_corners_default_false(self, device, dtype):+ # HomographyWarper's bare default align_corners=False (every HomographyWarper construction in+ # this file passes align_corners=True explicitly; this exercises the bare default), warping an+ # identity homography over a padding_mode="zeros" grid so that align_corners visibly changes output.+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("hardcoded-literal pin only reliable at float32/float64 precision")+ # Snippet used to generate expected:+ # height, width = 4, 5+ # patch_src = torch.arange(float(height * width)).view(1, 1, height, width)+ # dst_homo_src = torch.eye(3)[None]+ # warper = kornia.geometry.transform.HomographyWarper(height, width) # no align_corners passed+ # expected = warper(patch_src, dst_homo_src)+ height, width = 4, 5+ patch_src = torch.arange(float(height * width), device=device, dtype=dtype).view(1, 1, height, width)+ dst_homo_src = eye_like(3, patch_src)+ warper = kornia.geometry.transform.HomographyWarper(height, width)+ patch_dst = warper(patch_src, dst_homo_src)+ expected = torch.tensor(+ [+ [+ [+ [0.0000, 0.3750, 1.0000, 1.6250, 1.0000],+ [2.0833, 4.9167, 6.1667, 7.4167, 4.0833],+ [5.4167, 11.5833, 12.8333, 14.0833, 7.4167],+ [3.7500, 7.8750, 8.5000, 9.1250, 4.7500],+ ]+ ]+ ],+ device=device,+ dtype=dtype,+ )+ self.assert_close(patch_dst, expected, atol=1e-3, rtol=1e-3)+ # the literal above cannot distinguish False from None (grid_sample treats them alike), so+ # the documented defaults are additionally pinned on the signatures of both APIs+ import inspect++ assert (+ inspect.signature(kornia.geometry.transform.HomographyWarper.__init__).parameters["align_corners"].default+ is False+ )+ assert inspect.signature(kornia.geometry.transform.homography_warp).parameters["align_corners"].default is False+@pytest.mark.parametrize("shape", [(4, 5), (2, 6), (4, 3), (5, 7)])def test_translation(self, shape, device, dtype):# create input datadiff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.pyindex 6a593128b..9ed55a3a2 100644--- a/tests/geometry/transform/test_imgwarp.py+++ b/tests/geometry/transform/test_imgwarp.py@@ -192,6 +192,24 @@ class TestRotationMatrix2d(BaseTester):# evaluate function gradientself.gradcheck(kornia.geometry.get_rotation_matrix2d, (center, angle, scale))+ def test_convention_center_xy_order(self, device, dtype):+ # get_rotation_matrix2d's center is (x, y): using an asymmetric center (cx=3, cy=1) with 90deg+ # rotation and unit scale numerically distinguishes x-first from y-first ordering, since+ # swapping cx/cy would flip the sign/magnitude of M[..., 0, 2] and M[..., 1, 2].+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("hardcoded-literal pin only reliable at float32/float64 precision")+ # Snippet used to generate expected:+ # center = torch.tensor([[3.0, 1.0]])+ # angle = torch.tensor([90.0])+ # scale = torch.tensor([[1.0, 1.0]])+ # expected = kornia.geometry.get_rotation_matrix2d(center, angle, scale)+ center = torch.tensor([[3.0, 1.0]], device=device, dtype=dtype)+ angle = torch.tensor([90.0], device=device, dtype=dtype)+ scale = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)+ M = kornia.geometry.get_rotation_matrix2d(center, angle, scale)+ expected = torch.tensor([[[0.0, 1.0, 2.0], [-1.0, 0.0, 4.0]]], device=device, dtype=dtype)+ self.assert_close(M, expected, atol=1e-4, rtol=1e-4)+class TestWarpAffine(BaseTester):def test_smoke(self, device, dtype):@@ -395,6 +413,32 @@ class TestWarpPerspective(BaseTester):img_a = kornia.geometry.transform.homography_warp(img_b, homo_ab, (h, w), normalized_homography=False)self.assert_close(img_a, expected, atol=1e-4, rtol=1e-4)+ def test_convention_normalize_invert_equivalence(self, device, dtype):+ # homography_warp's default normalized_homography=True path (normalize the pixel homography,+ # invert it, then warp with normalized coordinates) is equivalent to warp_perspective's raw+ # pixel-homography path, given matching align_corners. Input size and dsize are deliberately+ # asymmetric: with equal square sizes normalize and invert commute, so the operation ORDER+ # (the conventions-page pitfall) would be invisible; at 4x6 -> (3, 5) the inverted order+ # diverges from this literal by 15.0.+ # Snippet used to generate expected:+ # x = torch.arange(24.0).view(1, 1, 4, 6)+ # H = torch.tensor([[[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]])+ # expected = kornia.geometry.transform.warp_perspective(x, H, (3, 5), align_corners=True)+ x = torch.arange(24.0, device=device, dtype=dtype).view(1, 1, 4, 6)+ H = torch.tensor([[[1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ expected = torch.tensor(+ [[[[0.0, 0.0, 1.0, 2.0, 3.0], [0.0, 6.0, 7.0, 8.0, 9.0], [0.0, 12.0, 13.0, 14.0, 15.0]]]],+ device=device,+ dtype=dtype,+ )++ wp = kornia.geometry.transform.warp_perspective(x, H, (3, 5), align_corners=True)+ self.assert_close(wp, expected, atol=1e-4, rtol=1e-4)++ Hn = kornia.geometry.conversions.normalize_homography(H, (4, 6), (3, 5))+ hw = kornia.geometry.transform.homography_warp(x, _torch_inverse_cast(Hn), (3, 5), align_corners=True)+ self.assert_close(hw, expected, atol=1e-4, rtol=1e-4)+def test_rotation_inverse(self, device, dtype):h, w = 4, 4img_b = torch.rand(1, 1, h, w, device=device, dtype=dtype)