You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_functional.py 44 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363
  1. # -*- coding: utf-8 -*-
  2. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  3. #
  4. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  5. #
  6. # Unless required by applicable law or agreed to in writing,
  7. # software distributed under the License is distributed on an
  8. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. import itertools
  10. import platform
  11. from functools import partial
  12. import numpy as np
  13. import pytest
  14. from utils import opr_test
  15. import megengine.amp as amp
  16. import megengine.config as config
  17. import megengine.core.ops.builtin as builtin
  18. import megengine.core.tensor.dtype as dtype
  19. import megengine.functional as F
  20. import megengine.jit as jit
  21. from megengine import Parameter, Tensor, is_cuda_available, tensor
  22. from megengine.core._trace_option import use_symbolic_shape
  23. from megengine.core.autodiff.grad import Grad
  24. from megengine.core.tensor.utils import make_shape_tuple
  25. from megengine.device import get_device_count
  26. from megengine.module import LayerNorm
  27. _assert_allclose = partial(np.testing.assert_allclose, atol=5e-6, rtol=5e-6)
  28. def test_where():
  29. maskv0 = np.array([[1, 0], [0, 1]], dtype=np.bool_)
  30. xv0 = np.array([[1, np.inf], [np.nan, 4]], dtype=np.float32)
  31. yv0 = np.array([[5, 6], [7, 8]], dtype=np.float32)
  32. maskv1 = np.array([[1, 0, 1], [1, 0, 0], [1, 1, 0]], dtype=np.bool_)
  33. xv1 = np.array([[1, np.inf, 2], [0, np.nan, 4], [1, 5, 7]], dtype=np.float32)
  34. yv1 = np.array([[5, 6, 9], [2, 7, 8], [2, 1, 9]], dtype=np.float32)
  35. cases = [
  36. {"input": [maskv0, xv0, yv0]},
  37. {"input": [maskv1, xv1, yv1]},
  38. ]
  39. opr_test(cases, F.where, ref_fn=np.where, test_trace=False)
  40. maskv2 = np.array([1, 1, 1], dtype=np.bool_)
  41. xv2 = np.array([1, 3, 2], dtype=np.float32)
  42. yv2 = np.array([5, 6, 9], dtype=np.float32)
  43. maskv3 = np.array([0, 0, 0], dtype=np.bool_)
  44. xv3 = np.array([1, 3, 2], dtype=np.float32)
  45. yv3 = np.array([5, 6, 9], dtype=np.float32)
  46. cases = [
  47. {"input": [maskv2, xv2, yv2]},
  48. {"input": [maskv3, xv3, yv3]},
  49. ]
  50. opr_test(cases, F.where, ref_fn=np.where, test_trace=False)
  51. def test_dropout():
  52. from megengine.autodiff import GradManager
  53. from megengine.core._imperative_rt.ops import set_global_rng_seed
  54. def test_dropout_with_shape(shape, rate):
  55. data = tensor(np.ones(shape, dtype=np.float32))
  56. gm = GradManager().attach([data])
  57. with gm:
  58. out = F.nn.dropout(data, rate, training=True)
  59. gm.backward(out, tensor(np.ones(shape, dtype=np.float32)))
  60. assert not out.numpy().all()
  61. np.testing.assert_allclose(out.numpy(), data.grad.numpy(), 1e-7, 1e-7)
  62. def test_multiple_dropout(shape, rate):
  63. data = tensor(np.ones(shape, dtype=np.float32))
  64. gm = GradManager().attach([data])
  65. with gm:
  66. out1 = F.nn.dropout(data, rate, training=True)
  67. out2 = F.nn.dropout(out1, rate, training=True)
  68. out3 = F.nn.dropout(out2, rate, training=True)
  69. gm.backward(out3, tensor(np.ones(shape, dtype=np.float32)))
  70. np.testing.assert_allclose(out3.numpy(), data.grad.numpy(), 1e-7, 1e-7)
  71. def test_dropout_seed(shape, rate):
  72. data = tensor(np.random.randn(*shape), dtype="float32")
  73. set_global_rng_seed(111)
  74. out1 = F.nn.dropout(data, rate, training=True)
  75. out2 = F.nn.dropout(data, rate, training=True)
  76. assert not (out1.numpy() == out2.numpy()).all()
  77. set_global_rng_seed(111)
  78. out3 = F.nn.dropout(data, rate, training=True)
  79. assert (out1.numpy() == out3.numpy()).all()
  80. set_global_rng_seed(222)
  81. out4 = F.nn.dropout(data, rate, training=True)
  82. assert not (out1.numpy() == out4.numpy()).all()
  83. test_dropout_with_shape([13, 17, 63, 21], 0.4)
  84. test_dropout_with_shape([16, 32, 64], 0.3)
  85. test_multiple_dropout([1024], 0.2)
  86. test_dropout_seed([16, 32], 0.2)
  87. def test_matinv():
  88. shape1 = (5, 5)
  89. shape2 = (3, 9, 9)
  90. data1 = np.random.random(shape1).astype("float32")
  91. data2 = np.random.random(shape2).astype("float32")
  92. # make matrix diagonally dominant for numerical stability
  93. data1 += (np.eye(shape1[0]) * shape1[0]).astype("float32")
  94. data2 += np.broadcast_to((np.eye(shape2[1]) * shape2[1]).astype("float32"), shape2)
  95. cases = [
  96. {"input": data1},
  97. {"input": data2},
  98. ]
  99. opr_test(
  100. cases,
  101. F.matinv,
  102. compare_fn=lambda x, y: np.testing.assert_allclose(x.numpy(), y, rtol=1e-4),
  103. ref_fn=np.linalg.inv,
  104. )
  105. def test_matmul():
  106. shape1 = 3
  107. shape2 = 3
  108. shape3 = (3, 5)
  109. shape4 = (5, 6)
  110. data1 = np.random.random(shape1).astype("float32")
  111. data2 = np.random.random(shape2).astype("float32")
  112. data3 = np.random.random(shape3).astype("float32")
  113. data4 = np.random.random(shape4).astype("float32")
  114. cases = [
  115. {"input": [data1, data2]},
  116. {"input": [data2, data3]},
  117. {"input": [data3, data4]},
  118. ]
  119. opr_test(cases, F.matmul, ref_fn=np.matmul)
  120. batch_size = 10
  121. shape1 = (2,)
  122. shape2 = (batch_size, 2, 3)
  123. shape3 = (batch_size, 3, 4)
  124. shape4 = (batch_size, 10, 4, 2)
  125. shape5 = (batch_size, 10, 2, 4)
  126. data1 = np.random.random(shape1).astype("float32")
  127. data2 = np.random.random(shape2).astype("float32")
  128. data3 = np.random.random(shape3).astype("float32")
  129. data4 = np.random.random(shape4).astype("float32")
  130. data5 = np.random.random(shape5).astype("float32")
  131. cases = [
  132. {"input": [data1, data2]},
  133. {"input": [data2, data3]},
  134. {"input": [data3, data4]},
  135. {"input": [data4, data5]},
  136. ]
  137. opr_test(cases, F.matmul, ref_fn=np.matmul)
  138. opr_test(
  139. [{"input": [data1, data4]}],
  140. F.matmul,
  141. ref_fn=lambda x, y: np.matmul(x, y.transpose(0, 1, 3, 2)),
  142. transpose_b=True,
  143. )
  144. opr_test(
  145. [{"input": [data3, data2]}],
  146. F.matmul,
  147. ref_fn=lambda x, y: np.matmul(x.transpose(0, 2, 1), y.transpose(0, 2, 1)),
  148. transpose_a=True,
  149. transpose_b=True,
  150. )
  151. @pytest.mark.parametrize(
  152. "shape_a, shape_b", [((0,), (0,)), ((10, 0), (0, 10)), ((3, 10, 0), (3, 0, 10)),],
  153. )
  154. @pytest.mark.parametrize("is_symbolic", [None, True, False])
  155. def test_matmul_empty_tensor(shape_a, shape_b, is_symbolic):
  156. def func(a, b):
  157. return F.matmul(a, b)
  158. if is_symbolic is not None:
  159. func = jit.trace(symbolic=is_symbolic)(func)
  160. a = tensor(np.random.randn(*shape_a))
  161. b = tensor(np.random.randn(*shape_b))
  162. for _ in range(3):
  163. out = func(a, b)
  164. assert np.all(out.numpy() == 0)
  165. if is_symbolic is None:
  166. break
  167. def test_interpolate():
  168. def linear_interpolate():
  169. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  170. out = F.vision.interpolate(inp, scale_factor=2.0, mode="linear")
  171. out2 = F.vision.interpolate(inp, 4, mode="linear")
  172. np.testing.assert_allclose(
  173. out.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  174. )
  175. np.testing.assert_allclose(
  176. out2.numpy(), np.array([[[1.0, 1.25, 1.75, 2.0]]], dtype=np.float32)
  177. )
  178. def many_batch_interpolate():
  179. inp = tensor(np.arange(1, 9, dtype=np.float32).reshape(2, 1, 2, 2))
  180. out = F.vision.interpolate(inp, [4, 4])
  181. out2 = F.vision.interpolate(inp, scale_factor=2.0)
  182. np.testing.assert_allclose(out.numpy(), out2.numpy())
  183. def assign_corner_interpolate():
  184. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  185. out = F.vision.interpolate(inp, [4, 4], align_corners=True)
  186. out2 = F.vision.interpolate(inp, scale_factor=2.0, align_corners=True)
  187. np.testing.assert_allclose(out.numpy(), out2.numpy())
  188. def error_shape_linear_interpolate():
  189. inp = tensor(np.arange(1, 5, dtype=np.float32).reshape(1, 1, 2, 2))
  190. with pytest.raises(ValueError):
  191. F.vision.interpolate(inp, scale_factor=2.0, mode="linear")
  192. def inappropriate_scale_linear_interpolate():
  193. inp = tensor(np.arange(1, 3, dtype=np.float32).reshape(1, 1, 2))
  194. with pytest.raises(ValueError):
  195. F.vision.interpolate(inp, scale_factor=[2.0, 3.0], mode="linear")
  196. linear_interpolate()
  197. many_batch_interpolate()
  198. assign_corner_interpolate()
  199. error_shape_linear_interpolate()
  200. inappropriate_scale_linear_interpolate()
  201. def _save_to(self, name="grad"):
  202. def callback(grad):
  203. setattr(self, name, grad)
  204. return callback
  205. def _gen_roi_inp():
  206. inp_feat = np.random.randn(2, 32, 256, 256)
  207. rois = np.zeros((4, 5))
  208. rois[:, 0] = [0, 0, 1, 1]
  209. rois[:, 1:3] = np.random.rand(4, 2) * 100
  210. rois[:, 3:] = np.random.rand(4, 2) * 100 + 150
  211. inp_feat = tensor(inp_feat)
  212. rois = tensor(rois)
  213. return inp_feat, rois
  214. def test_roi_align():
  215. inp_feat, rois = _gen_roi_inp()
  216. with Grad() as grad:
  217. grad.wrt(inp_feat, callback=_save_to(inp_feat))
  218. output_shape = (7, 7)
  219. out_feat = F.vision.roi_align(
  220. inp_feat,
  221. rois,
  222. output_shape=output_shape,
  223. mode="average",
  224. spatial_scale=1.0 / 4,
  225. sample_points=2,
  226. aligned=True,
  227. )
  228. assert make_shape_tuple(out_feat.shape) == (
  229. rois.shape[0],
  230. inp_feat.shape[1],
  231. *output_shape,
  232. )
  233. grad(out_feat, tensor(F.ones_like(out_feat)))
  234. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  235. def _gen_correlation(random=True, constant=1, image_shape=(2, 1, 160, 160)):
  236. if random:
  237. inp_feat1 = np.random.randn(
  238. image_shape[0], image_shape[1], image_shape[2], image_shape[3]
  239. )
  240. inp_feat2 = np.random.randn(
  241. image_shape[0], image_shape[1], image_shape[2], image_shape[3]
  242. )
  243. else:
  244. inp_feat1 = np.ones(image_shape) * constant
  245. inp_feat2 = np.ones(image_shape) * constant
  246. return tensor(inp_feat1), tensor(inp_feat2)
  247. def test_correlation():
  248. ##test case 0 check the grad shape
  249. data1, data2 = _gen_correlation()
  250. with Grad() as grad:
  251. grad.wrt(data1, callback=_save_to(data1))
  252. out_feat = F.vision.correlation(
  253. data1,
  254. data2,
  255. kernel_size=5,
  256. max_displacement=4,
  257. stride1=2,
  258. stride2=2,
  259. pad_size=2,
  260. is_multiply=True,
  261. )
  262. grad(out_feat, tensor(F.ones_like(out_feat)))
  263. assert make_shape_tuple(data1.grad.shape) == make_shape_tuple(data1.shape)
  264. ##test case 1 from https://github.com/NVIDIA/flownet2-pytorch/issues/194
  265. data1, data2 = _gen_correlation(random=False, image_shape=(1, 1, 3, 3))
  266. out_feat = F.vision.correlation(
  267. data1,
  268. data2,
  269. kernel_size=3,
  270. max_displacement=0,
  271. stride1=1,
  272. stride2=1,
  273. pad_size=0,
  274. is_multiply=True,
  275. )
  276. assert abs(out_feat.sum() - 1) < 1e-9
  277. ##test case 2 check same image subduction
  278. data1, data2 = _gen_correlation(random=False, image_shape=(1, 1, 3, 3))
  279. out_feat = F.vision.correlation(
  280. data1,
  281. data2,
  282. kernel_size=3,
  283. max_displacement=0,
  284. stride1=1,
  285. stride2=1,
  286. pad_size=0,
  287. is_multiply=False,
  288. )
  289. assert out_feat.sum() < 1e-9
  290. ##test case 3 check same image subduction
  291. data1, data2 = _gen_correlation(random=False, image_shape=(1, 1, 3, 3))
  292. out_feat = F.vision.correlation(
  293. data1,
  294. data2,
  295. kernel_size=3,
  296. max_displacement=0,
  297. stride1=1,
  298. stride2=1,
  299. pad_size=0,
  300. is_multiply=False,
  301. )
  302. assert out_feat.sum() < 1e-9
  303. ##test case 4 check correlation
  304. data1, _ = _gen_correlation(
  305. random=False, image_shape=(1, 1, 220, 220), constant=2.0
  306. )
  307. _, data2 = _gen_correlation(
  308. random=False, image_shape=(1, 1, 220, 220), constant=1.0
  309. )
  310. out_feat = F.vision.correlation(
  311. data1,
  312. data2,
  313. kernel_size=3,
  314. max_displacement=2,
  315. stride1=1,
  316. stride2=2,
  317. pad_size=0,
  318. is_multiply=False,
  319. )
  320. assert abs(out_feat.mean() - 1) < 1e-9
  321. def test_roi_pooling():
  322. inp_feat, rois = _gen_roi_inp()
  323. with Grad() as grad:
  324. grad.wrt(inp_feat, callback=_save_to(inp_feat))
  325. output_shape = (7, 7)
  326. out_feat = F.vision.roi_pooling(
  327. inp_feat, rois, output_shape=output_shape, mode="max", scale=1.0 / 4,
  328. )
  329. assert make_shape_tuple(out_feat.shape) == (
  330. rois.shape[0],
  331. inp_feat.shape[1],
  332. *output_shape,
  333. )
  334. grad(out_feat, tensor(F.ones_like(out_feat)))
  335. assert make_shape_tuple(inp_feat.grad.shape) == make_shape_tuple(inp_feat.shape)
  336. def test_adaptive_avg_pool2d():
  337. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  338. oshp = (2, 2)
  339. with Grad() as grad:
  340. grad.wrt(inp, callback=_save_to(inp))
  341. outp = F.adaptive_avg_pool2d(inp, oshp,)
  342. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  343. np.testing.assert_equal(
  344. outp.numpy(), np.array([[[[2.5, 4.5], [10.5, 12.5]]]], dtype=np.float32)
  345. )
  346. grad(outp, tensor(F.ones_like(outp)))
  347. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  348. np.testing.assert_equal(
  349. inp.grad.numpy(),
  350. np.array(
  351. [
  352. [
  353. [
  354. [0.25, 0.25, 0.25, 0.25],
  355. [0.25, 0.25, 0.25, 0.25],
  356. [0.25, 0.25, 0.25, 0.25],
  357. [0.25, 0.25, 0.25, 0.25],
  358. ]
  359. ]
  360. ],
  361. dtype=np.float32,
  362. ),
  363. )
  364. def test_adaptive_max_pool2d():
  365. inp = tensor(np.arange(0, 16, dtype=np.float32).reshape(1, 1, 4, 4))
  366. oshp = (2, 2)
  367. with Grad() as grad:
  368. grad.wrt(inp, callback=_save_to(inp))
  369. outp = F.adaptive_max_pool2d(inp, oshp,)
  370. assert make_shape_tuple(outp.shape) == (inp.shape[0], inp.shape[1], *oshp,)
  371. np.testing.assert_equal(
  372. outp.numpy(), np.array([[[[5, 7], [13, 15]]]], dtype=np.float32)
  373. )
  374. grad(outp, tensor(F.ones_like(outp)))
  375. assert make_shape_tuple(inp.grad.shape) == make_shape_tuple(inp.shape)
  376. np.testing.assert_equal(
  377. inp.grad.numpy(),
  378. np.array(
  379. [
  380. [
  381. [
  382. [0.0, 0.0, 0.0, 0.0],
  383. [0.0, 1.0, 0.0, 1.0],
  384. [0.0, 0.0, 0.0, 0.0],
  385. [0.0, 1.0, 0.0, 1.0],
  386. ]
  387. ]
  388. ],
  389. dtype=np.float32,
  390. ),
  391. )
  392. def test_one_hot():
  393. def onehot_low_dimension():
  394. inp = tensor(np.arange(1, 4, dtype=np.int32))
  395. out = F.one_hot(inp, num_classes=4)
  396. np.testing.assert_allclose(
  397. out.numpy(), np.eye(4, dtype=np.int32)[np.arange(1, 4, dtype=np.int32)]
  398. )
  399. def onehot_high_dimension():
  400. arr = np.array(
  401. [[3, 2, 4, 4, 2, 4, 0, 4, 4, 1], [4, 1, 1, 3, 2, 2, 4, 2, 4, 3]],
  402. dtype=np.int32,
  403. )
  404. inp = tensor(arr)
  405. out = F.one_hot(inp, 10)
  406. np.testing.assert_allclose(out.numpy(), np.eye(10, dtype=np.int32)[arr])
  407. onehot_low_dimension()
  408. onehot_high_dimension()
  409. def test_interpolate_fastpath():
  410. # check shape
  411. test_cases = [
  412. [(1, 1, 10, 10), (5, 5)],
  413. [(1, 3, 10, 10), (20, 20)],
  414. [(10, 1, 10, 10), (1, 1)],
  415. [(10, 10, 1, 1), (10, 10)],
  416. ]
  417. for inp_shape, target_shape in test_cases:
  418. x = tensor(np.random.randn(*inp_shape), dtype=np.float32)
  419. out = F.vision.interpolate(x, target_shape, mode="bilinear")
  420. assert out.shape[0] == x.shape[0] and out.shape[1] == x.shape[1]
  421. assert out.shape[2] == target_shape[0] and out.shape[3] == target_shape[1]
  422. # check value
  423. x = tensor(np.ones((3, 3, 10, 10)), dtype=np.float32)
  424. out = F.vision.interpolate(x, (15, 5), mode="bilinear")
  425. np.testing.assert_equal(out.numpy(), np.ones((3, 3, 15, 5)).astype(np.float32))
  426. np_x = np.arange(32)
  427. x = tensor(np_x).astype(np.float32).reshape(1, 1, 32, 1)
  428. out = F.vision.interpolate(x, (1, 1), mode="bilinear")
  429. np.testing.assert_equal(out.item(), np_x.mean())
  430. @pytest.mark.parametrize("dt", [np.float32, np.int8, np.uint8, np.float16])
  431. def test_warp_perspective(dt):
  432. inp_shape = (1, 1, 4, 4)
  433. x = tensor(np.arange(16, dtype=dt).reshape(inp_shape))
  434. M_shape = (1, 3, 3)
  435. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  436. M = tensor(
  437. np.array(
  438. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  439. ).reshape(M_shape)
  440. )
  441. outp = F.vision.warp_perspective(x, M, (2, 2))
  442. np.testing.assert_equal(outp.numpy(), np.array([[[[5, 6], [9, 10]]]], dtype=dt))
  443. @pytest.mark.parametrize("dt", [np.float32, np.int8, np.uint8, np.float16])
  444. def test_warp_perspective_mat_idx(dt):
  445. inp_shape = (2, 1, 4, 4)
  446. x = tensor(np.arange(32, dtype=dt).reshape(inp_shape))
  447. M_shape = (1, 3, 3)
  448. # M defines a translation: dst(1, 1, h, w) = rst(1, 1, h+1, w+1)
  449. M = tensor(
  450. np.array(
  451. [[1.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]], dtype=np.float32
  452. ).reshape(M_shape)
  453. )
  454. M = F.concat([M,] * 4, 0)
  455. outp = F.vision.warp_perspective(x, M, (2, 2), mat_idx=[0, 1, 1, 0])
  456. np.testing.assert_equal(
  457. outp.numpy(),
  458. np.array(
  459. [
  460. [[[5, 6], [9, 10]]],
  461. [[[21, 22], [25, 26]]],
  462. [[[21, 22], [25, 26]]],
  463. [[[5, 6], [9, 10]]],
  464. ],
  465. dtype=dt,
  466. ),
  467. )
  468. def test_warp_affine():
  469. inp_shape = (1, 3, 3, 3)
  470. x = tensor(np.arange(27, dtype=np.float32).reshape(inp_shape))
  471. weightv = [[[1.26666667, 0.6, -83.33333333], [-0.33333333, 1, 66.66666667]]]
  472. outp = F.vision.warp_affine(x, tensor(weightv), (2, 2), border_mode="wrap")
  473. res = np.array(
  474. [
  475. [
  476. [[7.875, 8.875, 9.875], [8.90625, 9.90625, 10.90625]],
  477. [[18.75, 19.75, 20.75], [14.90625, 15.90625, 16.90625]],
  478. ]
  479. ],
  480. dtype=np.float32,
  481. )
  482. if not is_cuda_available():
  483. np.testing.assert_almost_equal(outp.numpy(), res, 5)
  484. def test_remap():
  485. inp_shape = (1, 1, 4, 4)
  486. inp = tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  487. map_xy_shape = (1, 2, 2, 2)
  488. map_xy = tensor(
  489. np.array(
  490. [[[1.0, 0.0], [0.0, 1.0]], [[0.0, 1.0], [0.0, 1.0]]], dtype=np.float32
  491. ).reshape(map_xy_shape)
  492. )
  493. outp = F.vision.remap(inp, map_xy)
  494. np.testing.assert_equal(
  495. outp.numpy(), np.array([[[[1.0, 4.0], [4.0, 4.0]]]], dtype=np.float32)
  496. )
  497. def test_binary_cross_entropy():
  498. data1_shape = (2, 2)
  499. label1_shape = (2, 2)
  500. data2_shape = (2, 3)
  501. label2_shape = (2, 3)
  502. def sigmoid(x):
  503. return 1 / (1 + np.exp(-x))
  504. def compare_fn(x, y):
  505. np.testing.assert_allclose(x.numpy(), y, atol=5e-4)
  506. np.random.seed(123)
  507. data1 = np.random.uniform(size=data1_shape).astype(np.float32)
  508. label1 = np.random.uniform(size=label1_shape).astype(np.float32)
  509. expect1 = np.array([0.6361], dtype=np.float32)
  510. np.random.seed(123)
  511. data2 = np.random.uniform(size=data2_shape).astype(np.float32)
  512. label2 = np.random.uniform(size=label2_shape).astype(np.float32)
  513. expect2 = np.array([0.6750], dtype=np.float32)
  514. cases = [
  515. {"input": [data1, label1], "output": expect1,},
  516. {"input": [data2, label2], "output": expect2,},
  517. ]
  518. opr_test(cases, F.nn.binary_cross_entropy, compare_fn=compare_fn)
  519. cases = [
  520. {"input": [sigmoid(data1), label1], "output": expect1,},
  521. {"input": [sigmoid(data2), label2], "output": expect2,},
  522. ]
  523. opr_test(
  524. cases,
  525. partial(F.nn.binary_cross_entropy, with_logits=False),
  526. compare_fn=compare_fn,
  527. )
  528. def test_hinge_loss():
  529. np.random.seed(123)
  530. # case with L1 norm
  531. cases = []
  532. for shape in [(2, 2), (2, 3)]:
  533. data = np.random.uniform(size=shape).astype(np.float32)
  534. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  535. expect = np.clip(0, np.inf, 1 - data * label).sum(axis=1).mean()
  536. cases.append({"input": [data, label], "output": expect})
  537. opr_test(cases, F.nn.hinge_loss)
  538. # cases with L2 norm
  539. cases = []
  540. for shape in [(2, 2), (2, 3)]:
  541. data = np.random.uniform(size=shape).astype(np.float32)
  542. label = 2 * np.random.randint(0, 1, size=shape).astype(np.float32) - 1
  543. expect = ((np.clip(0, np.inf, 1 - data * label) ** 2).sum(axis=1)).mean()
  544. cases.append({"input": [data, label], "output": expect})
  545. def hinge_loss_with_l2_norm(pred, label):
  546. return F.nn.hinge_loss(pred, label, "L2")
  547. opr_test(cases, hinge_loss_with_l2_norm)
  548. @pytest.mark.parametrize("is_symbolic", [None, False, True])
  549. def test_nms(is_symbolic):
  550. def fn(inp, scores):
  551. return F.vision.nms(
  552. inp,
  553. scores=scores,
  554. iou_thresh=0.5,
  555. max_output=None if is_symbolic is None else 4,
  556. )
  557. if is_symbolic is not None:
  558. fn = jit.trace(symbolic=is_symbolic)(fn)
  559. x = np.array(
  560. [
  561. [0, 0, 100, 100],
  562. [10, 10, 100, 100],
  563. [50, 50, 100, 100],
  564. [100, 100, 150, 150],
  565. ],
  566. dtype=np.float32,
  567. )
  568. inp = tensor(x)
  569. scores = tensor([0.5, 0.8, 0.9, 0.6], dtype=np.float32)
  570. for _ in range(3):
  571. result = fn(inp, scores=scores)
  572. np.testing.assert_equal(result.numpy(), np.array([2, 1, 3], dtype=np.int32))
  573. x = np.array([], dtype=np.float32,).reshape(0, 4)
  574. inp = tensor(x)
  575. scores = tensor([], dtype=np.float32)
  576. for _ in range(3):
  577. result = fn(inp, scores=scores)
  578. np.testing.assert_equal(result.numpy(), np.array([], dtype=np.int32))
  579. @pytest.mark.skipif(
  580. get_device_count("gpu") > 0, reason="cuda does not support nchw int8"
  581. )
  582. def test_conv_bias():
  583. inp_scale = 1.5
  584. w_scale = 2.5
  585. outp_scale = 1.5
  586. inp_dtype = dtype.qint8(inp_scale)
  587. w_dtype = dtype.qint8(w_scale)
  588. b_dtype = dtype.qint32(inp_scale * w_scale)
  589. out_dtype = dtype.qint8(outp_scale)
  590. def run(
  591. N,
  592. IC,
  593. OC,
  594. IH,
  595. IW,
  596. KH,
  597. KW,
  598. PH,
  599. PW,
  600. SH,
  601. SW,
  602. has_bias=True,
  603. nonlinear_mode="identity",
  604. ):
  605. inp_v = np.random.normal(size=(N, IC, IH, IW))
  606. w_v = np.random.normal(size=(OC, IC, KH, KW))
  607. b_v = np.random.normal(size=(1, OC, 1, 1))
  608. inp_scale = dtype.get_scale(inp_dtype)
  609. w_scale = dtype.get_scale(w_dtype)
  610. b_scale = dtype.get_scale(b_dtype)
  611. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  612. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  613. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  614. inp_int8 = tensor(inpv, dtype=inp_dtype)
  615. w_int8 = Parameter(wv, dtype=w_dtype)
  616. b_int32 = Parameter(bv, dtype=b_dtype)
  617. inp_fp32 = inp_int8.astype("float32")
  618. w_fp32 = w_int8.astype("float32")
  619. b_fp32 = b_int32.astype("float32")
  620. def convert_to_nchw4(var):
  621. var = F.reshape(
  622. var, (var.shape[0], var.shape[1] // 4, 4, var.shape[2], var.shape[3])
  623. )
  624. var = F.transpose(var, (0, 1, 3, 4, 2))
  625. return var
  626. def run_conv2d(inp, w, b):
  627. O = F.conv2d(
  628. inp, w, b if has_bias else None, stride=(SH, SW), padding=(PH, PW),
  629. )
  630. if nonlinear_mode == "relu":
  631. return F.relu(O)
  632. else:
  633. return O
  634. def run_conv_bias(inp, w, b, format="NCHW"):
  635. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  636. if format == "NCHW4":
  637. inp = convert_to_nchw4(inp)
  638. w = convert_to_nchw4(w)
  639. b = convert_to_nchw4(b)
  640. return F.quantized.conv_bias_activation(
  641. inp,
  642. w,
  643. b,
  644. stride=(SH, SW),
  645. padding=(PH, PW),
  646. dtype=out_dtype,
  647. nonlinear_mode=nonlinear_mode,
  648. )
  649. format = "NCHW4" if is_cuda_available() else "NCHW"
  650. expected = run_conv2d(inp_fp32, w_fp32, b_fp32)
  651. expected = expected.astype(out_dtype).astype("float32")
  652. result = run_conv_bias(inp_int8, w_int8, b_int32, format=format).astype(
  653. "float32"
  654. )
  655. if format == "NCHW4":
  656. result = F.transpose(result, (0, 1, 4, 2, 3))
  657. expected = F.flatten(expected)
  658. result = F.flatten(result)
  659. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  660. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1, False)
  661. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1, False)
  662. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False)
  663. run(1, 4, 4, 24, 33, 1, 1, 2, 3, 1, 1)
  664. run(10, 12, 24, 46, 46, 1, 1, 2, 1, 3, 1)
  665. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2)
  666. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, False, "relu")
  667. run(10, 36, 8, 46, 26, 2, 2, 2, 1, 1, 2, True, "relu")
  668. @pytest.mark.skipif(get_device_count("gpu") > 0, reason="no int8 algorithm on cuda")
  669. def test_batch_conv_bias():
  670. inp_scale = 1.5
  671. w_scale = 2.5
  672. outp_scale = 1.5
  673. inp_dtype = dtype.qint8(inp_scale)
  674. w_dtype = dtype.qint8(w_scale)
  675. b_dtype = dtype.qint32(inp_scale * w_scale)
  676. out_dtype = dtype.qint8(outp_scale)
  677. def run(
  678. N, IC, OC, IH, IW, KH, KW, PH, PW, SH, SW, has_bias=True,
  679. ):
  680. inp_v = np.random.normal(size=(N, IC, IH, IW))
  681. w_v = np.random.normal(size=(N, OC, IC, KH, KW))
  682. b_v = np.random.normal(size=(1, OC, 1, 1))
  683. inp_scale = dtype.get_scale(inp_dtype)
  684. w_scale = dtype.get_scale(w_dtype)
  685. b_scale = dtype.get_scale(b_dtype)
  686. inpv = dtype.convert_to_qint8(inp_v * inp_scale, inp_dtype)
  687. wv = dtype.convert_to_qint8(w_v * w_scale, w_dtype)
  688. bv = dtype.convert_to_qint32(b_v * b_scale, b_dtype)
  689. inp_int8 = tensor(inpv, dtype=inp_dtype)
  690. w_int8 = Parameter(wv, dtype=w_dtype)
  691. b_int32 = Parameter(bv, dtype=b_dtype)
  692. inp_fp32 = inp_int8.astype("float32")
  693. w_fp32 = w_int8.astype("float32")
  694. b_fp32 = b_int32.astype("float32")
  695. def run_batch_conv_bias(inp, w, b):
  696. b = b if has_bias else Parameter(np.zeros_like(b.numpy()))
  697. result = F.quantized.batch_conv_bias_activation(
  698. inp, w, b, stride=(SH, SW), padding=(PH, PW), dtype=out_dtype,
  699. )
  700. return result.astype("float32")
  701. expected = F.conv2d(inp_fp32, w_fp32[0], b_fp32 if has_bias else None)[0]
  702. expected = expected.astype(out_dtype).astype("float32")
  703. expected = F.flatten(expected)
  704. result = run_batch_conv_bias(inp_int8, w_int8, b_int32)
  705. result = F.flatten(result)
  706. np.testing.assert_allclose(result.numpy(), expected.numpy(), atol=outp_scale)
  707. run(1, 4, 4, 5, 5, 3, 3, 0, 0, 1, 1, True)
  708. def test_conv2d_autocast():
  709. """check amp's result is equal to manually converted result"""
  710. amp.enabled = True
  711. inp = tensor(np.random.randn(1, 3, 224, 224), dtype=np.float32)
  712. weight = tensor(np.random.randn(64, 3, 7, 7), dtype=np.float32)
  713. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  714. amp.enabled = False
  715. expected = F.conv2d(
  716. inp.astype("float16"),
  717. weight.astype("float16"),
  718. None,
  719. (2, 2),
  720. (3, 3),
  721. (1, 1),
  722. 1,
  723. compute_mode="float32",
  724. )
  725. assert out.dtype == np.float16
  726. assert expected.dtype == np.float16
  727. np.testing.assert_allclose(out.numpy(), expected.numpy())
  728. def test_conv2d_zero_stride_numpy_array():
  729. inp = np.random.randn(3, 224, 224).astype(np.float32)
  730. inp = inp[np.newaxis, :]
  731. inp = tensor(inp, dtype=np.float32)
  732. weight = tensor(np.random.randn(16, 3, 3, 3), dtype=np.float32)
  733. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  734. def test_conv3d_zero_stride_numpy_array():
  735. inp = np.random.randn(3, 224, 224, 224).astype(np.float32)
  736. inp = inp[np.newaxis, :]
  737. inp = tensor(inp, dtype=np.float32)
  738. weight = tensor(np.random.randn(16, 3, 3, 3, 3), dtype=np.float32)
  739. out = F.conv3d(inp, weight, None, (2, 2, 2), (3, 3, 3), (1, 1, 1), 1)
  740. out.numpy()
  741. def test_conv1d():
  742. inp = tensor(np.ones((2, 2, 4), dtype=np.float32))
  743. weight = tensor(np.ones((3, 2, 2), dtype=np.float32))
  744. out = F.conv1d(inp, weight, None, 2, 0, 1, 1)
  745. np.testing.assert_equal(
  746. out.numpy(),
  747. np.array(
  748. [[[4, 4], [4, 4], [4, 4]], [[4, 4], [4, 4], [4, 4]]], dtype=np.float32
  749. ),
  750. )
  751. def test_batchnorm2d_autocast():
  752. """check amp's result is equal to manually converted result"""
  753. amp.enabled = True
  754. tshape = (1, 3, 224, 224)
  755. pshape = (1, 3, 1, 1)
  756. inp = tensor(np.random.randn(*tshape), dtype=np.float32)
  757. weight = tensor(np.ones(pshape, dtype=np.float32))
  758. bias = tensor(np.zeros(pshape, dtype=np.float32))
  759. out = F.batch_norm(inp, weight=weight, bias=bias, training=True, inplace=False)
  760. amp.enabled = False
  761. expected = F.batch_norm(
  762. inp.astype("float16"),
  763. weight=weight,
  764. bias=bias,
  765. training=True,
  766. inplace=False,
  767. compute_mode="float32",
  768. )
  769. assert out.dtype == np.float16
  770. assert expected.dtype == np.float16
  771. np.testing.assert_allclose(out.numpy(), expected.numpy())
  772. def test_conv3d():
  773. inp = tensor(np.ones((2, 2, 4, 4, 4), dtype=np.float32))
  774. weight = tensor(np.ones((3, 2, 2, 2, 2), dtype=np.float32))
  775. out = F.conv3d(inp, weight, None, 2, 0, 1, 1)
  776. np.testing.assert_equal(
  777. out.numpy(), np.ones((2, 3, 2, 2, 2), dtype=np.float32) * 16
  778. )
  779. def test_condtake():
  780. x = np.array([[1, 2, 3], [4, 5, 6]])
  781. y = np.array([[True, False, True], [False, True, True]])
  782. xx = tensor(x)
  783. yy = tensor(y)
  784. val, idx = F.cond_take(yy, xx)
  785. np.testing.assert_equal(val.numpy(), x[y])
  786. np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])
  787. @pytest.mark.parametrize("is_symbolic", [None, False, True])
  788. def test_condtake(is_symbolic):
  789. shapes = [
  790. (3, 3, 3),
  791. (0,),
  792. (3, 0, 3),
  793. ]
  794. def fn(mask, data):
  795. return F.cond_take(mask, data)
  796. if is_symbolic is not None:
  797. fn = jit.trace(symbolic=is_symbolic)(fn)
  798. for shp in shapes:
  799. x_np = np.random.randn(*shp).astype("float32")
  800. mask_np = x_np > 0
  801. x = tensor(x_np)
  802. mask = tensor(mask_np)
  803. ref_out = x_np[mask_np]
  804. ref_idx = mask_np.flatten().nonzero()[0]
  805. for i in range(3):
  806. out, idx = fn(mask, x)
  807. np.testing.assert_equal(out.numpy(), ref_out)
  808. np.testing.assert_equal(idx.numpy(), ref_idx)
  809. if is_symbolic is None:
  810. break
  811. def test_condtake_is_same():
  812. op1 = builtin.CondTake()
  813. op2 = builtin.CondTake()
  814. assert op1 == op2
  815. def test_nms_is_same():
  816. op1 = builtin.NMSKeep(0.7, 100)
  817. op2 = builtin.NMSKeep(0.7, 100)
  818. op3 = builtin.NMSKeep(0.8, 100)
  819. op4 = builtin.NMSKeep(0.7, 200)
  820. assert op1 == op2
  821. assert op1 != op3
  822. assert op1 != op4
  823. assert op3 != op4
  824. def test_argmxx_on_inf():
  825. def run_argmax():
  826. x = F.zeros((100, 100))
  827. x[:] = -float("inf")
  828. idxs = F.argmax(x, axis=0)
  829. return idxs
  830. def run_argmin():
  831. x = F.zeros((100, 100))
  832. x[:] = float("inf")
  833. idxs = F.argmin(x, axis=0)
  834. return idxs
  835. assert all(run_argmax() >= 0)
  836. assert all(run_argmin() >= 0)
  837. def test_deformable_psroi_pooling():
  838. inp = np.random.random((1, 256, 64, 64)).astype("float32")
  839. rois = np.random.random((1, 5)).astype("float32")
  840. trans = np.random.random((24, 2, 7, 7)).astype("float32")
  841. pooled_h = 7
  842. pooled_w = 7
  843. sample_per_part = 4
  844. no_trans = False
  845. part_size = 7
  846. spatial_scale = 1.0 / 64
  847. trans_std = 0.1
  848. y = F.deformable_psroi_pooling(
  849. tensor(inp),
  850. tensor(rois),
  851. tensor(trans),
  852. no_trans,
  853. part_size,
  854. pooled_h,
  855. pooled_w,
  856. sample_per_part,
  857. spatial_scale,
  858. trans_std,
  859. )
  860. def test_cvt_color():
  861. def rgb2gray(rgb):
  862. return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])
  863. def bgr2gray(bgr):
  864. return np.dot(bgr[..., :3], [0.114, 0.587, 0.299])
  865. inp = np.random.randn(3, 3, 3, 3).astype(np.float32)
  866. out = np.expand_dims(rgb2gray(inp), 3).astype(np.float32)
  867. x = tensor(inp)
  868. y = F.vision.cvt_color(x, mode="RGB2GRAY")
  869. np.testing.assert_allclose(y.numpy(), out, atol=1e-5)
  870. out1 = np.expand_dims(bgr2gray(inp), 3).astype(np.float32)
  871. y1 = F.vision.cvt_color(x, mode="BGR2GRAY")
  872. np.testing.assert_allclose(y1.numpy(), out1, atol=1e-5)
  873. @pytest.mark.parametrize("val", [2, [2,], [2, 3]])
  874. def test_ones(val):
  875. shp = tensor(val)
  876. np_shp = np.array(val)
  877. np.testing.assert_equal(F.ones(shp), np.ones(np_shp))
  878. def test_assert_equal():
  879. shape = (2, 3, 4, 5)
  880. x = F.ones(shape, dtype=np.float32)
  881. y = F.zeros(shape, dtype=np.float32) + 1.00001
  882. z = F.utils._assert_equal(x, y)
  883. def test_assert_not_equal():
  884. shape = (2, 3, 4, 5)
  885. x = F.ones(shape, dtype=np.float32)
  886. y = F.zeros(shape, dtype=np.float32) + 1.1
  887. with pytest.raises(RuntimeError):
  888. z = F.utils._assert_equal(x, y)
  889. def test_neg_axis():
  890. x = tensor(np.random.normal(0, 1, (32, 5)))
  891. y = F.argmax(x, axis=-1)
  892. yy = F.argmax(x, axis=1)
  893. np.testing.assert_equal(y.numpy(), yy.numpy())
  894. y = F.argmax(x, axis=(-1, -2))
  895. yy = F.argmax(x, axis=(0, 1))
  896. np.testing.assert_equal(y.numpy(), yy.numpy())
  897. y = F.argmin(x, axis=(-1, -2))
  898. yy = F.argmin(x, axis=(0, 1))
  899. np.testing.assert_equal(y.numpy(), yy.numpy())
  900. def test_sliding_window():
  901. N, C, H, W = 2, 3, 7, 8
  902. inp = np.random.normal(size=(N, C, H, W))
  903. ph, pw = 1, 2
  904. sh, sw = 2, 1
  905. wh, ww = 3, 2
  906. dh, dw = 1, 3
  907. s = lambda i, p, s, d, w: (i + p * 2 - (w - 1) * d - 1) // s + 1
  908. inp_pad = np.zeros((N, C, H + ph * 2, W + pw * 2))
  909. inp_pad[:, :, ph : H + ph, pw : W + pw] = inp
  910. gt_out = np.empty(
  911. (N, C, s(H, ph, sh, dh, wh), s(W, pw, sw, dw, ww), wh, ww), dtype=np.float32
  912. )
  913. for n, c, oh, ow in itertools.product(*map(range, gt_out.shape[:4])):
  914. ih, iw = oh * sh, ow * sw
  915. gt_out[n, c, oh, ow, :] = inp_pad[
  916. n, c, ih : ih + (wh - 1) * dh + 1 : dh, iw : iw + (ww - 1) * dw + 1 : dw
  917. ]
  918. out = F.sliding_window(
  919. tensor(inp), (wh, ww), padding=(ph, pw), stride=(sh, sw), dilation=(dh, dw)
  920. )
  921. np.testing.assert_equal(gt_out, out.numpy())
  922. def test_sliding_window_transpose():
  923. N, C, H, W = 2, 3, 7, 8
  924. ph, pw = 1, 2
  925. sh, sw = 2, 1
  926. wh, ww = 3, 2
  927. dh, dw = 1, 3
  928. s = lambda i, p, s, d, w: (i + p * 2 - (w - 1) * d - 1) // s + 1
  929. inp = np.random.normal(
  930. size=(N, C, s(H, ph, sh, dh, wh), s(W, pw, sw, dw, ww), wh, ww)
  931. ).astype(np.float32)
  932. gt_out = np.zeros((N, C, H, W), dtype=np.float32)
  933. for n, c in itertools.product(*map(range, inp.shape[:2])):
  934. oh = 0
  935. for ih in range(-ph, H + ph - dh * (wh - 1), sh):
  936. ow = 0
  937. for iw in range(-pw, W + pw - dw * (ww - 1), sw):
  938. for kh, kw in itertools.product(*map(range, inp.shape[-2:])):
  939. ih2 = ih + dh * kh
  940. iw2 = iw + dw * kw
  941. if ih2 >= 0 and ih2 < H and iw2 >= 0 and iw2 < W:
  942. gt_out[n, c, ih2, iw2] += inp[n, c, oh, ow, kh, kw]
  943. ow += 1
  944. oh += 1
  945. out = F.sliding_window_transpose(
  946. tensor(inp),
  947. (H, W),
  948. (wh, ww),
  949. padding=(ph, pw),
  950. stride=(sh, sw),
  951. dilation=(dh, dw),
  952. )
  953. np.testing.assert_equal(gt_out, out.numpy())
  954. def test_pad():
  955. src = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)
  956. dst = np.pad(src, ((2, 2), (2, 2)), "constant")
  957. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "CONSTANT")
  958. np.testing.assert_allclose(res, dst, atol=1e-5)
  959. dst = np.pad(src, ((2, 2), (2, 2)), "constant", constant_values=3)
  960. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "CONSTANT", constant_value=3)
  961. np.testing.assert_allclose(res, dst, atol=1e-5)
  962. dst = np.pad(src, ((2, 2), (2, 2)), "edge")
  963. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "EDGE")
  964. np.testing.assert_allclose(res, dst, atol=1e-5)
  965. dst = np.pad(src, ((2, 2), (2, 2)), "reflect")
  966. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "REFLECT")
  967. np.testing.assert_allclose(res, dst, atol=1e-5)
  968. def pixel_shuffle(data, r):
  969. high_dim = data.shape[:-3]
  970. data = data.reshape(-1, data.shape[-3], data.shape[-2], data.shape[-1])
  971. inn, ic, ih, iw = data.shape
  972. res = np.zeros((inn, int(ic / (r * r)), ih * r, iw * r))
  973. for n in range(inn):
  974. for c in range(ic):
  975. for h in range(ih):
  976. for w in range(iw):
  977. res[
  978. n,
  979. int(c / r / r),
  980. h * r + int((c % (r * r)) / r),
  981. w * r + c % r,
  982. ] = data[n, c, h, w]
  983. if len(high_dim) > 0:
  984. res = res.reshape((*high_dim, int(ic / r / r), ih * r, iw * r))
  985. else:
  986. res = res[0]
  987. return res
  988. def test_pixel_shuffle():
  989. # ndim = 3
  990. inp = np.arange(16 * 3 * 3).reshape(16, 3, 3)
  991. out = F.pixel_shuffle(tensor(inp), upscale_factor=4)
  992. golden = pixel_shuffle(inp, 4)
  993. np.testing.assert_equal(out.numpy(), golden)
  994. inp_float = np.float32(inp)
  995. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=2)
  996. golden = pixel_shuffle(inp_float, 2)
  997. np.testing.assert_equal(out.numpy(), golden)
  998. # ndim = 4
  999. inp = np.arange(3 * 18 * 3 * 3).reshape(3, 18, 3, 3)
  1000. out = F.pixel_shuffle(tensor(inp), upscale_factor=3)
  1001. golden = pixel_shuffle(inp, 3)
  1002. np.testing.assert_equal(out.numpy(), golden)
  1003. inp_float = np.float32(inp)
  1004. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=3)
  1005. golden = pixel_shuffle(inp_float, 3)
  1006. np.testing.assert_equal(out.numpy(), golden)
  1007. # ndim = 5
  1008. inp = np.arange(5 * 3 * 20 * 3 * 4).reshape(5, 3, 20, 3, 4)
  1009. out = F.pixel_shuffle(tensor(inp), upscale_factor=2)
  1010. golden = pixel_shuffle(inp, 2)
  1011. np.testing.assert_equal(out.numpy(), golden)
  1012. inp_float = np.float32(inp)
  1013. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=2)
  1014. golden = pixel_shuffle(inp_float, 2)
  1015. np.testing.assert_equal(out.numpy(), golden)
  1016. # ndim = 6
  1017. inp = np.arange(6 * 5 * 3 * 25 * 3 * 4).reshape(6, 5, 3, 25, 3, 4)
  1018. out = F.pixel_shuffle(tensor(inp), upscale_factor=5)
  1019. golden = pixel_shuffle(inp, 5)
  1020. np.testing.assert_equal(out.numpy(), golden)
  1021. inp_float = np.float32(inp)
  1022. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=5)
  1023. golden = pixel_shuffle(inp_float, 5)
  1024. np.testing.assert_equal(out.numpy(), golden)
  1025. # ndim = 7
  1026. inp = np.arange(2 * 3 * 5 * 3 * 20 * 3 * 4).reshape(2, 3, 5, 3, 20, 3, 4)
  1027. out = F.pixel_shuffle(tensor(inp), upscale_factor=2)
  1028. golden = pixel_shuffle(inp, 2)
  1029. np.testing.assert_equal(out.numpy(), golden)
  1030. inp_float = np.float32(inp)
  1031. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=2)
  1032. golden = pixel_shuffle(inp_float, 2)
  1033. np.testing.assert_equal(out.numpy(), golden)
  1034. @pytest.mark.parametrize("type", ["int32", "float32"])
  1035. @pytest.mark.parametrize("is_symbolic", [False, True])
  1036. def test_pixel_shuffle_symbolic(is_symbolic, type):
  1037. def fn(inp, upscale_factor):
  1038. return F.pixel_shuffle(inp, upscale_factor=upscale_factor)
  1039. if is_symbolic is not None:
  1040. fn = jit.trace(symbolic=is_symbolic)(fn)
  1041. inp = tensor(np.arange(3 * 4 * 5 * 5).reshape(3, 4, 5, 5).astype(type))
  1042. golden = pixel_shuffle(inp, 2)
  1043. for _ in range(3):
  1044. out = fn(inp, 2)
  1045. np.testing.assert_equal(out.numpy(), golden)
  1046. if is_symbolic is None:
  1047. break
  1048. def test_set_conv2d_config():
  1049. """check setting config by contextmanager is equal to manually converted result"""
  1050. config._compute_mode = "float32"
  1051. inp = tensor(np.random.randn(1, 3, 224, 224), dtype=np.float16)
  1052. weight = tensor(np.random.randn(64, 3, 7, 7), dtype=np.float16)
  1053. config_out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  1054. config._compute_mode = "default"
  1055. with config._override(compute_mode="float32"):
  1056. context_out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  1057. expected = F.conv2d(
  1058. inp, weight, None, (2, 2), (3, 3), (1, 1), 1, compute_mode="float32",
  1059. )
  1060. np.testing.assert_allclose(config_out.numpy(), expected.numpy())
  1061. np.testing.assert_allclose(context_out.numpy(), expected.numpy())
  1062. def test_set_warp_perspective_config():
  1063. config._conv_format = "NHWC"
  1064. inp_shape = (1, 1, 4, 4)
  1065. inp = Tensor(np.arange(16, dtype=np.float32).reshape(inp_shape))
  1066. M_shape = (1, 3, 3)
  1067. M = Tensor(np.random.randn(3, 3), dtype=np.float32).reshape(M_shape)
  1068. config_out = F.vision.warp_perspective(inp, M, (2, 2))
  1069. config._conv_format = "default"
  1070. with config._override(conv_format="NHWC"):
  1071. context_out = F.vision.warp_perspective(inp, M, (2, 2))
  1072. expected = F.vision.warp_perspective(inp, M, (2, 2), format="NHWC")
  1073. np.testing.assert_allclose(config_out.numpy(), expected.numpy())
  1074. np.testing.assert_allclose(context_out.numpy(), expected.numpy())
  1075. @pytest.mark.parametrize("stride", [(1, 1)])
  1076. @pytest.mark.parametrize("padding", [(1, 1)])
  1077. @pytest.mark.parametrize("dilation", [(1, 1)])
  1078. @pytest.mark.parametrize("ksize", [(3, 3)])
  1079. @pytest.mark.parametrize("groups", [1, 2])
  1080. def test_local_conv2d(stride, padding, dilation, ksize, groups):
  1081. batch_size, in_channels, out_channels = 2, 4, 8
  1082. input_height, input_width = 10, 10
  1083. output_height = (input_height + padding[0] * 2 - ksize[0]) // stride[0] + 1
  1084. output_width = (input_width + padding[1] * 2 - ksize[1]) // stride[1] + 1
  1085. def local_conv2d_np(data, weight, stride, padding, dialtion):
  1086. # naive calculation use numpy
  1087. # only test output_height == input_height, output_width == input_width
  1088. data = np.pad(data, ((0, 0), (0, 0), (1, 1), (1, 1)))
  1089. expected = np.zeros(
  1090. (batch_size, out_channels, output_height, output_width), dtype=np.float32,
  1091. )
  1092. ic_group_size = in_channels // groups
  1093. oc_group_size = out_channels // groups
  1094. for n, oc, oh, ow in itertools.product(
  1095. *map(range, [batch_size, out_channels, output_height, output_width])
  1096. ):
  1097. ih, iw = oh * stride[0], ow * stride[1]
  1098. g_id = oc // oc_group_size
  1099. expected[n, oc, ih, iw] = np.sum(
  1100. data[
  1101. n,
  1102. g_id * ic_group_size : (g_id + 1) * ic_group_size,
  1103. ih : ih + ksize[0],
  1104. iw : iw + ksize[1],
  1105. ]
  1106. * weight[g_id, oh, ow, :, :, :, oc % oc_group_size]
  1107. )
  1108. return expected
  1109. data = np.random.rand(batch_size, in_channels, input_height, input_width).astype(
  1110. "float32"
  1111. )
  1112. weight = np.random.rand(
  1113. groups,
  1114. output_height,
  1115. output_width,
  1116. in_channels // groups,
  1117. *ksize,
  1118. out_channels // groups,
  1119. ).astype("float32")
  1120. output = F.local_conv2d(
  1121. tensor(data),
  1122. tensor(weight),
  1123. None,
  1124. stride=stride,
  1125. padding=padding,
  1126. dilation=dilation,
  1127. )
  1128. ref = local_conv2d_np(data, weight, stride, padding, dilation)
  1129. np.testing.assert_almost_equal(output.numpy(), ref, 5)