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 53 kB

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