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

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