vision.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import paddle
  15. from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode
  16. from paddle.base.framework import (
  17. in_dygraph_mode,
  18. in_dynamic_or_pir_mode,
  19. in_pir_mode,
  20. )
  21. from ...base.data_feeder import check_variable_and_dtype
  22. from ...base.layer_helper import LayerHelper
  23. from ...common_ops_import import Variable
  24. from ...device import get_cudnn_version, is_compiled_with_rocm
  25. __all__ = []
  26. def affine_grid(theta, out_shape, align_corners=True, name=None):
  27. """
  28. It generates a grid of (x,y) or (x,y,z) coordinates using the parameters of
  29. the affine transformation that correspond to a set of points where
  30. the input feature map should be sampled to produce the transformed
  31. output feature map.
  32. Args:
  33. theta (Tensor): A tensor with shape [N, 2, 3] or [N, 3, 4]. It contains a batch of affine transform parameters.
  34. The data type can be float32 or float64.
  35. out_shape (Tensor | list | tuple): Type can be a 1-D Tensor, list, or tuple. It is used to represent the shape of the output in an affine transformation, in the format ``[N, C, H, W]`` or ``[N, C, D, H, W]``.
  36. When the format is ``[N, C, H, W]``, it represents the batch size, number of channels, height and width. When the format is ``[N, C, D, H, W]``, it represents the batch size, number of channels, depth, height and width.
  37. The data type must be int32.
  38. align_corners(bool, optional): if True, aligns the centers of the 4 (4D) or 8 (5D) corner pixels of the input and output tensors, and preserves the value of the corner pixels. Default: True
  39. name(str, optional): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  40. Returns:
  41. Tensor, A Tensor with shape [batch_size, H, W, 2] or [batch, D, H, W, 3] while ('D')'H', 'W' are the (depth)height, width of feature map in affine transformation. The data type is the same as `theta`.
  42. Examples:
  43. .. code-block:: python
  44. >>> import paddle
  45. >>> import paddle.nn.functional as F
  46. >>> # theta.shape = [1, 2, 3]
  47. >>> theta = paddle.to_tensor([[[-0.7, -0.4, 0.3],
  48. ... [ 0.6, 0.5, 1.5]]], dtype="float32")
  49. >>> y_t = F.affine_grid(
  50. ... theta,
  51. ... [1, 2, 3, 3],
  52. ... align_corners=False
  53. ... )
  54. >>> print(y_t)
  55. Tensor(shape=[1, 3, 3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  56. [[[[ 1.03333330, 0.76666665],
  57. [ 0.56666672, 1.16666663],
  58. [ 0.10000002, 1.56666672]],
  59. [[ 0.76666665, 1.09999990],
  60. [ 0.30000001, 1.50000000],
  61. [-0.16666666, 1.90000010]],
  62. [[ 0.50000000, 1.43333328],
  63. [ 0.03333333, 1.83333337],
  64. [-0.43333334, 2.23333335]]]])
  65. """
  66. if not isinstance(theta, (Variable, paddle.pir.Value)):
  67. raise TypeError("The theta should be a Tensor.")
  68. cudnn_version = get_cudnn_version()
  69. if cudnn_version is not None and cudnn_version >= 6000 and align_corners:
  70. use_cudnn = True
  71. else:
  72. use_cudnn = False
  73. if theta.shape[1] == 3:
  74. use_cudnn = False
  75. if is_compiled_with_rocm():
  76. use_cudnn = (
  77. False # ROCM platform do not have MIOPEN kernel for affine_grid
  78. )
  79. if in_dynamic_mode():
  80. _out_shape = (
  81. out_shape.tolist() if isinstance(out_shape, Variable) else out_shape
  82. )
  83. theta = theta._use_gpudnn(use_cudnn)
  84. return _C_ops.affine_grid(theta, _out_shape, align_corners)
  85. elif in_pir_mode():
  86. return _C_ops.affine_grid(
  87. theta,
  88. out_shape,
  89. align_corners,
  90. )
  91. else:
  92. helper = LayerHelper('affine_grid', **locals())
  93. check_variable_and_dtype(
  94. theta, 'theta', ['float32', 'float64'], 'affine_grid'
  95. )
  96. out = helper.create_variable_for_type_inference(dtype=theta.dtype)
  97. ipts = {'Theta': theta}
  98. attrs = {"align_corners": align_corners, "use_cudnn": use_cudnn}
  99. if isinstance(out_shape, Variable):
  100. ipts['OutputShape'] = out_shape
  101. check_variable_and_dtype(
  102. out_shape, 'out_shape', ['int32'], 'affine_grid'
  103. )
  104. else:
  105. attrs['output_shape'] = out_shape
  106. helper.append_op(
  107. type='affine_grid',
  108. inputs=ipts,
  109. outputs={'Output': out},
  110. attrs=None if len(attrs) == 0 else attrs,
  111. )
  112. return out
  113. def grid_sample(
  114. x,
  115. grid,
  116. mode='bilinear',
  117. padding_mode='zeros',
  118. align_corners=True,
  119. name=None,
  120. ):
  121. """
  122. Sample input X by using bilinear interpolation or
  123. nearest interpolation based on flow field grid, which is usually
  124. generated by :code:`affine_grid` . When the input X is 4-D Tensor,
  125. the grid of shape [N, H, W, 2] is the concatenation of (x, y)
  126. coordinates with shape [N, H, W] each, where x is indexing the 4th
  127. dimension (in width dimension) of input data x and y is indexing
  128. the 3rd dimension (in height dimension), finally results is the
  129. bilinear interpolation or nearest value of 4 nearest corner
  130. points. The output tensor shape will be [N, C, H, W]. When the input X
  131. is 5-D Tensor, the grid of shape [N, D, H, W, 3] is the concatenation
  132. of (x, y, z) coordinates with shape [N, D, H, W] each, where x is
  133. indexing the 5th dimension (in width dimension) of input data x, y is
  134. indexing the 4th dimension (in height dimension) and z is indexing the
  135. 3rd dimension (in depth dimension) finally results is the bilinear
  136. interpolation or nearest value of 8 nearest corner points. The output
  137. tensor shape will be [N, C, D, H, W].
  138. Step 1:
  139. Get (x, y) grid coordinates and scale to [0, H-1/W-1].
  140. .. code-block:: text
  141. grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1)
  142. grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1)
  143. Step 2:
  144. Indices input data X with grid (x, y) in each [H, W] area, and bilinear
  145. interpolate point value by 4 nearest points or nearest interpolate point value
  146. by nearest point.
  147. .. code-block:: text
  148. wn ------- y_n ------- en
  149. | | |
  150. | d_n |
  151. | | |
  152. x_w --d_w-- grid--d_e-- x_e
  153. | | |
  154. | d_s |
  155. | | |
  156. ws ------- y_s ------- wn
  157. For bilinear interpolation:
  158. x_w = floor(x) // west side x coord
  159. x_e = x_w + 1 // east side x coord
  160. y_n = floor(y) // north side y coord
  161. y_s = y_s + 1 // south side y coord
  162. d_w = grid_x - x_w // distance to west side
  163. d_e = x_e - grid_x // distance to east side
  164. d_n = grid_y - y_n // distance to north side
  165. d_s = y_s - grid_y // distance to south side
  166. wn = X[:, :, y_n, x_w] // north-west point value
  167. en = X[:, :, y_n, x_e] // north-east point value
  168. ws = X[:, :, y_s, x_w] // south-east point value
  169. es = X[:, :, y_s, x_w] // north-east point value
  170. output = wn * d_e * d_s + en * d_w * d_s
  171. + ws * d_e * d_n + es * d_w * d_n
  172. Args:
  173. x(Tensor): The input tensor, which is a 4-d tensor with shape
  174. [N, C, H, W] or a 5-d tensor with shape [N, C, D, H, W],
  175. N is the batch size, C is the channel number,
  176. D, H and W is the feature depth, height and width.
  177. The data type is float32 or float64.
  178. grid(Tensor): Input grid tensor, which is a 4-d tensor with shape [N, grid_H,
  179. grid_W, 2] or a 5-d tensor with shape [N, grid_D, grid_H,
  180. grid_W, 3]. The data type is float32 or float64.
  181. mode(str, optional): The interpolation method which can be 'bilinear' or 'nearest'.
  182. Default: 'bilinear'.
  183. padding_mode(str, optional) The padding method used when source index
  184. is out of input images. It can be 'zeros', 'reflection' and 'border'.
  185. Default: zeros.
  186. align_corners(bool, optional): If `align_corners` is true, it will projects
  187. -1 and 1 to the centers of the corner pixels. Otherwise, it will
  188. projects -1 and 1 to the image edges.
  189. name(str, optional): For detailed information, please refer
  190. to :ref:`api_guide_Name`. Usually name is no need to set and
  191. None by default.
  192. Returns:
  193. Tensor, The shape of output is [N, C, grid_H, grid_W] or [N, C, grid_D, grid_H, grid_W] in which `grid_D` is the depth of grid,
  194. `grid_H` is the height of grid and `grid_W` is the width of grid. The data type is same as input tensor.
  195. Examples:
  196. .. code-block:: python
  197. >>> import paddle
  198. >>> import paddle.nn.functional as F
  199. >>> # x shape=[1, 1, 3, 3]
  200. >>> x = paddle.to_tensor([[[[-0.6, 0.8, -0.5],
  201. ... [-0.5, 0.2, 1.2],
  202. ... [ 1.4, 0.3, -0.2]]]], dtype='float64')
  203. >>> # grid.shape = [1, 3, 4, 2]
  204. >>> grid = paddle.to_tensor([[[[ 0.2, 0.3],
  205. ... [-0.4, -0.3],
  206. ... [-0.9, 0.3],
  207. ... [-0.9, -0.6]],
  208. ... [[ 0.4, 0.1],
  209. ... [ 0.9, -0.8],
  210. ... [ 0.4, 0.5],
  211. ... [ 0.5, -0.2]],
  212. ... [[ 0.1, -0.8],
  213. ... [-0.3, -1. ],
  214. ... [ 0.7, 0.4],
  215. ... [ 0.2, 0.8]]]], dtype='float64')
  216. >>> y_t = F.grid_sample(
  217. ... x,
  218. ... grid,
  219. ... mode='bilinear',
  220. ... padding_mode='border',
  221. ... align_corners=True
  222. ... )
  223. >>> print(y_t)
  224. Tensor(shape=[1, 1, 3, 4], dtype=float64, place=Place(cpu), stop_gradient=True,
  225. [[[[ 0.34000000, 0.01600000, 0.08600000, -0.44800000],
  226. [ 0.55000000, -0.07600000, 0.35000000, 0.59000000],
  227. [ 0.59600000, 0.38000000, 0.52000000, 0.24000000]]]])
  228. """
  229. _modes = ['bilinear', 'nearest']
  230. _padding_modes = ['zeros', 'reflection', 'border']
  231. if mode not in _modes:
  232. raise ValueError(
  233. f"The mode of grid sample function should be in {_modes}, but got: {mode}"
  234. )
  235. if padding_mode not in _padding_modes:
  236. raise ValueError(
  237. f"The padding mode of grid sample function should be in {_padding_modes}, but got: {padding_mode}"
  238. )
  239. if not isinstance(align_corners, bool):
  240. raise ValueError(
  241. f"The align corners should be bool, but got: {align_corners}"
  242. )
  243. cudnn_version = get_cudnn_version()
  244. use_cudnn = False
  245. if (
  246. not is_compiled_with_rocm()
  247. and (cudnn_version is not None)
  248. and align_corners
  249. and mode == 'bilinear'
  250. and padding_mode == 'zeros'
  251. ):
  252. use_cudnn = True
  253. # CUDNN always computes gradients for all inputs
  254. x.stop_gradient = False
  255. grid.stop_gradient = False
  256. if len(grid.shape) == 5:
  257. use_cudnn = False
  258. if in_dynamic_or_pir_mode():
  259. return _C_ops.grid_sample(x, grid, mode, padding_mode, align_corners)
  260. else:
  261. helper = LayerHelper("grid_sample", **locals())
  262. check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'grid_sample')
  263. check_variable_and_dtype(
  264. grid, 'grid', ['float32', 'float64'], 'grid_sample'
  265. )
  266. ipts = {'X': x, 'Grid': grid}
  267. attrs = {
  268. 'mode': mode,
  269. 'padding_mode': padding_mode,
  270. 'align_corners': align_corners,
  271. 'use_cudnn': use_cudnn,
  272. }
  273. out = helper.create_variable_for_type_inference(x.dtype)
  274. helper.append_op(
  275. type='grid_sampler',
  276. inputs=ipts,
  277. attrs=attrs,
  278. outputs={'Output': out},
  279. )
  280. return out
  281. def pixel_shuffle(x, upscale_factor, data_format="NCHW", name=None):
  282. """
  283. This API implements pixel shuffle operation.
  284. See more details in :ref:`PixelShuffle <api_paddle_nn_PixelShuffle>` .
  285. Parameters:
  286. x(Tensor): 4-D tensor, the data type should be float32 or float64.
  287. upscale_factor(int): factor to increase spatial resolution.
  288. data_format (str, optional): The data format of the input and output data. An optional string from: ``"NCHW"``, ``"NHWC"``. When it is ``"NCHW"``, the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. Default: ``"NCHW"``.
  289. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  290. Returns:
  291. Out(tensor): Reshaped tensor according to the new dimension.
  292. Examples:
  293. .. code-block:: python
  294. >>> import paddle
  295. >>> import paddle.nn.functional as F
  296. >>> x = paddle.randn(shape=[2,9,4,4])
  297. >>> out_var = F.pixel_shuffle(x, 3)
  298. >>> print(out_var.shape)
  299. [2, 1, 12, 12]
  300. """
  301. if not isinstance(upscale_factor, int):
  302. raise TypeError("upscale factor must be int type")
  303. if data_format not in ["NCHW", "NHWC"]:
  304. raise ValueError(
  305. "Attr(data_format) should be 'NCHW' or 'NHWC'."
  306. f"But receive Attr(data_format): {data_format} "
  307. )
  308. if in_dynamic_or_pir_mode():
  309. return _C_ops.pixel_shuffle(x, upscale_factor, data_format)
  310. else:
  311. helper = LayerHelper("pixel_shuffle", **locals())
  312. check_variable_and_dtype(
  313. x, 'x', ['float16', 'float32', 'float64'], 'pixel_shuffle'
  314. )
  315. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  316. helper.append_op(
  317. type="pixel_shuffle",
  318. inputs={"X": x},
  319. outputs={"Out": out},
  320. attrs={
  321. "upscale_factor": upscale_factor,
  322. "data_format": data_format,
  323. },
  324. )
  325. return out
  326. def pixel_unshuffle(x, downscale_factor, data_format="NCHW", name=None):
  327. """
  328. This API implements pixel unshuffle operation.
  329. See more details in :ref:`PixelUnShuffle <api_paddle_nn_PixelUnshuffle>` .
  330. Parameters:
  331. x (Tensor): 4-D tensor, the data type should be float32 or float64.
  332. downscale_factor (int): Factor to decrease spatial resolution.
  333. data_format (str, optional): The data format of the input and output data. An optional string of ``'NCHW'`` or ``'NHWC'``. When it is ``'NCHW'``, the data is stored in the order of [batch_size, input_channels, input_height, input_width]. Default: ``'NCHW'``.
  334. name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  335. Returns:
  336. Out (Tensor): Reshaped tensor according to the new dimension.
  337. Examples:
  338. .. code-block:: python
  339. >>> import paddle
  340. >>> import paddle.nn.functional as F
  341. >>> x = paddle.randn([2, 1, 12, 12])
  342. >>> out = F.pixel_unshuffle(x, 3)
  343. >>> print(out.shape)
  344. [2, 9, 4, 4]
  345. """
  346. if len(x.shape) != 4:
  347. raise ValueError(
  348. f"Input x should be 4D tensor, but received x with the shape of {x.shape}"
  349. )
  350. if not isinstance(downscale_factor, int):
  351. raise TypeError("Downscale factor must be int type")
  352. if downscale_factor <= 0:
  353. raise ValueError("Downscale factor must be positive")
  354. if data_format not in ["NCHW", "NHWC"]:
  355. raise ValueError(
  356. "Attr(data_format) should be 'NCHW' or 'NHWC'."
  357. f"But receive Attr(data_format): {data_format} "
  358. )
  359. if in_dygraph_mode():
  360. return _legacy_C_ops.pixel_unshuffle(
  361. x, "downscale_factor", downscale_factor, "data_format", data_format
  362. )
  363. helper = LayerHelper("pixel_unshuffle", **locals())
  364. check_variable_and_dtype(
  365. x, 'x', ['float16', 'float32', 'float64', 'uint16'], 'pixel_unshuffle'
  366. )
  367. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  368. helper.append_op(
  369. type="pixel_unshuffle",
  370. inputs={"X": x},
  371. outputs={"Out": out},
  372. attrs={
  373. "downscale_factor": downscale_factor,
  374. "data_format": data_format,
  375. },
  376. )
  377. return out
  378. def channel_shuffle(x, groups, data_format="NCHW", name=None):
  379. """
  380. This API implements channel shuffle operation.
  381. See more details in :ref:`api_paddle_nn_ChannelShuffle`.
  382. Parameters:
  383. x (Tensor): 4-D tensor, the data type should be float32 or float64.
  384. groups (int): Number of groups to divide channels in.
  385. data_format (str, optional): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width].
  386. name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  387. Returns:
  388. Out (Tensor): Rearranged tensor keeping the original tensor shape.
  389. Examples:
  390. .. code-block:: python
  391. >>> import paddle
  392. >>> import paddle.nn.functional as F
  393. >>> x = paddle.arange(0, 0.6, 0.1, 'float32')
  394. >>> x = paddle.reshape(x, [1, 6, 1, 1])
  395. >>> print(x)
  396. Tensor(shape=[1, 6, 1, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  397. [[[[0. ]],
  398. [[0.10000000]],
  399. [[0.20000000]],
  400. [[0.30000001]],
  401. [[0.40000001]],
  402. [[0.50000000]]]])
  403. >>> y = F.channel_shuffle(x, 3)
  404. >>> print(y)
  405. Tensor(shape=[1, 6, 1, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  406. [[[[0. ]],
  407. [[0.20000000]],
  408. [[0.40000001]],
  409. [[0.10000000]],
  410. [[0.30000001]],
  411. [[0.50000000]]]])
  412. """
  413. if len(x.shape) != 4:
  414. raise ValueError(
  415. f"Input x should be 4D tensor, but received x with the shape of {x.shape}"
  416. )
  417. if not isinstance(groups, int):
  418. raise TypeError("groups must be int type")
  419. if groups <= 0:
  420. raise ValueError("groups must be positive")
  421. if data_format not in ["NCHW", "NHWC"]:
  422. raise ValueError(
  423. "Attr(data_format) should be 'NCHW' or 'NHWC'."
  424. f"But receive Attr(data_format): {data_format} "
  425. )
  426. if in_dynamic_or_pir_mode():
  427. return _C_ops.channel_shuffle(x, groups, data_format)
  428. helper = LayerHelper("channel_shuffle", **locals())
  429. check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'channel_shuffle')
  430. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  431. helper.append_op(
  432. type="channel_shuffle",
  433. inputs={"X": x},
  434. outputs={"Out": out},
  435. attrs={"groups": groups, "data_format": data_format},
  436. )
  437. return out