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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  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. @pytest.mark.parametrize("bias", [True, False])
  768. def test_region_restricted_conv_forward_backward_naive(bias):
  769. import megengine as mge
  770. import megengine.module as M
  771. from megengine.autodiff import GradManager
  772. handle = "cpu0"
  773. src_1 = np.arange(8).reshape(1, 2, 2, 2).astype(np.float32)
  774. filter_1 = np.arange(8).reshape(2, 1, 1, 2, 2).astype(np.float32)
  775. rin_1 = np.array([1, 1, 1, 1]).reshape(1, 2, 2).astype(np.int32)
  776. rout_1 = np.array([1]).reshape(1, 1, 1).astype(np.int32)
  777. cpu_src = tensor(src_1, device=handle)
  778. cpu_filter = tensor(filter_1, device=handle)
  779. gm = GradManager().attach([cpu_src, cpu_filter])
  780. cpu_bias = (
  781. tensor(np.ones((1, 2, 1, 1), dtype=np.float32), device=handle) if bias else None
  782. )
  783. with gm:
  784. cpu_out = F.region_restricted_conv(
  785. cpu_src,
  786. cpu_filter,
  787. tensor(rin_1, device=handle),
  788. tensor(rout_1, device=handle),
  789. bias=cpu_bias,
  790. groups=2,
  791. )
  792. gm.backward(cpu_out, tensor(np.ones((1, 2, 1, 1)), device=handle))
  793. if cpu_bias is not None:
  794. cpu_out = cpu_out - cpu_bias
  795. np.testing.assert_allclose(cpu_out, np.array([14, 126]).reshape(1, 2, 1, 1))
  796. np.testing.assert_allclose(
  797. cpu_src.grad, np.array([0, 1, 2, 3, 4, 5, 6, 7]).reshape(1, 2, 2, 2)
  798. )
  799. np.testing.assert_allclose(
  800. cpu_filter.grad, np.array([0, 1, 2, 3, 4, 5, 6, 7]).reshape(2, 1, 1, 2, 2)
  801. )
  802. @pytest.mark.skipif(
  803. not is_cuda_available(), reason="rrconv cuda kernel requires cuda available"
  804. )
  805. @pytest.mark.parametrize("bias", [True, False])
  806. def test_region_restricted_conv_forward_backward_cuda(bias):
  807. import megengine as mge
  808. import megengine.module as M
  809. from megengine.autodiff import GradManager
  810. import megengine.distributed as dist
  811. # params
  812. handle = "gpu0"
  813. N = 1
  814. GROUP = 3
  815. FH = FW = 2
  816. IH = IW = 2
  817. OH = OW = 1
  818. ICPG = OCPG = 1
  819. grad_shape = (N, GROUP * ICPG, IH, IW)
  820. src_shape = grad_shape
  821. filter_shape = (GROUP, OCPG, ICPG, FH, FW)
  822. diff_shape = (N, GROUP * OCPG, OH, OW)
  823. rin_shape = (N, IH, IW)
  824. rout_shape = (N, OH, OW)
  825. def reduce(shape):
  826. mul = 1
  827. for x in shape:
  828. mul *= x
  829. return mul
  830. def get_groundtruth():
  831. src = tensor(
  832. np.arange(reduce(src_shape)).reshape(src_shape).astype(np.float32),
  833. device="cpu0",
  834. )
  835. filter = tensor(np.ones(filter_shape).astype(np.float32), device="cpu0")
  836. rin = tensor(np.ones(rin_shape).astype(np.int32), device="cpu0")
  837. rout = tensor(np.ones(rout_shape).astype(np.int32), device="cpu0")
  838. bias_cpu = (
  839. tensor(np.ones((1, GROUP * OCPG, 1, 1)).astype(np.float32), device="cpu0")
  840. if bias
  841. else None
  842. )
  843. gm = GradManager().attach([src, filter])
  844. with gm:
  845. expected_out = F.region_restricted_conv(
  846. src, filter, rin, rout, bias=bias_cpu, groups=GROUP
  847. )
  848. gm.backward(
  849. expected_out,
  850. tensor(np.ones(diff_shape, dtype=np.float32), device="cpu0"),
  851. )
  852. return src, filter, expected_out
  853. expected_src, expected_filter, expected_out = get_groundtruth()
  854. src = tensor(
  855. np.arange(reduce(src_shape)).reshape(src_shape).astype(np.float32),
  856. device=handle,
  857. )
  858. filter = tensor(np.ones(filter_shape).astype(np.float32), device=handle)
  859. rin = tensor(np.ones(rin_shape).astype(np.int32), device=handle)
  860. rout = tensor(np.ones(rout_shape).astype(np.int32), device=handle)
  861. bias_gpu = (
  862. tensor(np.ones((1, GROUP * OCPG, 1, 1)).astype(np.float32), device=handle)
  863. if bias
  864. else None
  865. )
  866. gm = GradManager().attach([src, filter])
  867. with gm:
  868. gpu_out = F.region_restricted_conv(
  869. src, filter, rin, rout, bias=bias_gpu, groups=GROUP
  870. )
  871. gm.backward(gpu_out, tensor(np.ones(diff_shape), device=handle))
  872. np.testing.assert_allclose(src.grad, expected_src.grad)
  873. np.testing.assert_allclose(filter.grad, expected_filter.grad)
  874. np.testing.assert_allclose(gpu_out, expected_out)
  875. @pytest.mark.skipif(
  876. not is_cuda_available(), reason="rrconv cuda kernel requires cuda available"
  877. )
  878. @pytest.mark.parametrize("bias", [True, False])
  879. def test_region_restricted_conv_forward_backward_uint8(bias):
  880. import megengine as mge
  881. import megengine.module as M
  882. from megengine.autodiff import GradManager
  883. # params
  884. handle = "gpu0"
  885. N = 1
  886. GROUP = 2
  887. FH = FW = 1
  888. IH = IW = 4
  889. OH = OW = 4
  890. ICPG = OCPG = 1
  891. grad_shape = (N, GROUP * ICPG, IH, IW)
  892. src_shape = grad_shape
  893. filter_shape = (GROUP, OCPG, ICPG, FH, FW)
  894. diff_shape = (N, GROUP * OCPG, OH, OW)
  895. rin_shape = (N, IH, IW)
  896. rout_shape = (N, OH, OW)
  897. def reduce(shape):
  898. mul = 1
  899. for x in shape:
  900. mul *= x
  901. return mul
  902. def get_groundtruth():
  903. src = tensor(
  904. np.arange(reduce(src_shape)).reshape(src_shape).astype(np.float32),
  905. device="cpu0",
  906. )
  907. filter = tensor(np.ones(filter_shape).astype(np.float32), device="cpu0")
  908. rin = tensor(np.ones(rin_shape).astype(np.int32), device="cpu0")
  909. rout = tensor(np.ones(rout_shape).astype(np.int32), device="cpu0")
  910. bias_cpu = (
  911. tensor(np.ones((1, GROUP * OCPG, 1, 1)).astype(np.float32), device="cpu0")
  912. if bias
  913. else None
  914. )
  915. gm = GradManager().attach([src, filter])
  916. with gm:
  917. expected_out = F.region_restricted_conv(
  918. src, filter, rin, rout, bias=bias_cpu, groups=GROUP
  919. )
  920. gm.backward(
  921. expected_out,
  922. tensor(np.ones(diff_shape, dtype=np.float32), device="cpu0"),
  923. )
  924. return src, filter, expected_out
  925. expected_src, expected_filter, expected_out = get_groundtruth()
  926. # forward and dgrad/wgrad
  927. src = tensor(
  928. np.arange(reduce(src_shape)).reshape(src_shape).astype(np.float32),
  929. device=handle,
  930. )
  931. filter = tensor(np.ones(filter_shape).astype(np.float32), device=handle)
  932. rin = tensor(np.ones(rin_shape).astype(np.uint8), device=handle)
  933. rout = tensor(np.ones(rout_shape).astype(np.uint8), device=handle)
  934. bias_gpu = (
  935. tensor(np.ones((1, GROUP * OCPG, 1, 1)).astype(np.float32), device=handle)
  936. if bias
  937. else None
  938. )
  939. gm = GradManager().attach([src, filter])
  940. with gm:
  941. gpu_out = F.region_restricted_conv(
  942. src, filter, rin, rout, bias=bias_gpu, groups=GROUP
  943. )
  944. gm.backward(
  945. gpu_out, tensor(np.ones(diff_shape, dtype=np.float32), device=handle)
  946. )
  947. # assert uint8 gpu result close to cpu result
  948. np.testing.assert_allclose(src.grad, expected_src.grad)
  949. np.testing.assert_allclose(filter.grad, expected_filter.grad)
  950. np.testing.assert_allclose(gpu_out, expected_out)
  951. def test_conv2d_autocast():
  952. """check amp's result is equal to manually converted result"""
  953. amp.enabled = True
  954. inp = tensor(np.random.randn(1, 3, 224, 224), dtype=np.float32)
  955. weight = tensor(np.random.randn(64, 3, 7, 7), dtype=np.float32)
  956. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  957. amp.enabled = False
  958. expected = F.conv2d(
  959. inp.astype("float16"),
  960. weight.astype("float16"),
  961. None,
  962. (2, 2),
  963. (3, 3),
  964. (1, 1),
  965. 1,
  966. compute_mode="float32",
  967. )
  968. assert out.dtype == np.float16
  969. assert expected.dtype == np.float16
  970. np.testing.assert_allclose(out.numpy(), expected.numpy())
  971. def test_conv2d_zero_stride_numpy_array():
  972. inp = np.random.randn(3, 224, 224).astype(np.float32)
  973. inp = inp[np.newaxis, :]
  974. inp = tensor(inp, dtype=np.float32)
  975. weight = tensor(np.random.randn(16, 3, 3, 3), dtype=np.float32)
  976. out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  977. def test_conv3d_zero_stride_numpy_array():
  978. inp = np.random.randn(3, 224, 224, 224).astype(np.float32)
  979. inp = inp[np.newaxis, :]
  980. inp = tensor(inp, dtype=np.float32)
  981. weight = tensor(np.random.randn(16, 3, 3, 3, 3), dtype=np.float32)
  982. out = F.conv3d(inp, weight, None, (2, 2, 2), (3, 3, 3), (1, 1, 1), 1)
  983. out.numpy()
  984. @pytest.mark.parametrize("bias", [True, False])
  985. def test_conv1d(bias):
  986. inp = tensor(np.ones((2, 2, 4), dtype=np.float32))
  987. weight = tensor(np.ones((3, 2, 2), dtype=np.float32))
  988. bias = tensor(np.ones((1, 3, 1), dtype=np.float32)) if bias else None
  989. out = F.conv1d(inp, weight, bias, 2, 0, 1, 1)
  990. np.testing.assert_equal(
  991. out.numpy(),
  992. np.array([[[5, 5], [5, 5], [5, 5]], [[5, 5], [5, 5], [5, 5]]], dtype=np.float32)
  993. if bias is not None
  994. else np.array(
  995. [[[4, 4], [4, 4], [4, 4]], [[4, 4], [4, 4], [4, 4]]], dtype=np.float32
  996. ),
  997. )
  998. def test_batchnorm2d_autocast():
  999. """check amp's result is equal to manually converted result"""
  1000. amp.enabled = True
  1001. tshape = (1, 3, 224, 224)
  1002. pshape = (1, 3, 1, 1)
  1003. inp = tensor(np.random.randn(*tshape), dtype=np.float32)
  1004. weight = tensor(np.ones(pshape, dtype=np.float32))
  1005. bias = tensor(np.zeros(pshape, dtype=np.float32))
  1006. out = F.batch_norm(inp, weight=weight, bias=bias, training=True, inplace=False)
  1007. amp.enabled = False
  1008. expected = F.batch_norm(
  1009. inp.astype("float16"), weight=weight, bias=bias, training=True, inplace=False,
  1010. )
  1011. assert out.dtype == np.float16
  1012. assert expected.dtype == np.float16
  1013. np.testing.assert_allclose(out.numpy(), expected.numpy())
  1014. @pytest.mark.parametrize("bias", [True, False])
  1015. def test_conv3d(bias):
  1016. inp = tensor(np.ones((2, 2, 4, 4, 4), dtype=np.float32))
  1017. weight = tensor(np.ones((3, 2, 2, 2, 2), dtype=np.float32))
  1018. bias = tensor(np.ones((1, 3, 1, 1, 1), dtype=np.float32)) if bias else None
  1019. out = F.conv3d(inp, weight, bias, 2, 0, 1, 1)
  1020. target = np.ones((2, 3, 2, 2, 2), dtype=np.float32) * 16
  1021. target = target + 1 if bias is not None else target
  1022. np.testing.assert_equal(out.numpy(), target)
  1023. def test_condtake():
  1024. x = np.array([[1, 2, 3], [4, 5, 6]])
  1025. y = np.array([[True, False, True], [False, True, True]])
  1026. xx = tensor(x)
  1027. yy = tensor(y)
  1028. val, idx = F.cond_take(yy, xx)
  1029. np.testing.assert_equal(val.numpy(), x[y])
  1030. np.testing.assert_equal(idx.numpy(), np.where(y.reshape(-1))[0])
  1031. @pytest.mark.parametrize("is_symbolic", [None, False, True])
  1032. def test_condtake(is_symbolic):
  1033. shapes = [
  1034. (3, 3, 3),
  1035. (0,),
  1036. (3, 0, 3),
  1037. ]
  1038. def fn(mask, data):
  1039. return F.cond_take(mask, data)
  1040. if is_symbolic is not None:
  1041. fn = jit.trace(symbolic=is_symbolic)(fn)
  1042. for shp in shapes:
  1043. x_np = np.random.randn(*shp).astype("float32")
  1044. mask_np = x_np > 0
  1045. x = tensor(x_np)
  1046. mask = tensor(mask_np)
  1047. ref_out = x_np[mask_np]
  1048. ref_idx = mask_np.flatten().nonzero()[0]
  1049. for i in range(3):
  1050. out, idx = fn(mask, x)
  1051. np.testing.assert_equal(out.numpy(), ref_out)
  1052. np.testing.assert_equal(idx.numpy(), ref_idx)
  1053. if is_symbolic is None:
  1054. break
  1055. def test_condtake_is_same():
  1056. op1 = builtin.CondTake()
  1057. op2 = builtin.CondTake()
  1058. assert op1 == op2
  1059. def test_nms_is_same():
  1060. op1 = builtin.NMSKeep(0.7, 100)
  1061. op2 = builtin.NMSKeep(0.7, 100)
  1062. op3 = builtin.NMSKeep(0.8, 100)
  1063. op4 = builtin.NMSKeep(0.7, 200)
  1064. assert op1 == op2
  1065. assert op1 != op3
  1066. assert op1 != op4
  1067. assert op3 != op4
  1068. def test_argmxx_on_inf():
  1069. def run_argmax():
  1070. x = F.zeros((100, 100))
  1071. x[:] = -float("inf")
  1072. idxs = F.argmax(x, axis=0)
  1073. return idxs
  1074. def run_argmin():
  1075. x = F.zeros((100, 100))
  1076. x[:] = float("inf")
  1077. idxs = F.argmin(x, axis=0)
  1078. return idxs
  1079. assert all(run_argmax() >= 0)
  1080. assert all(run_argmin() >= 0)
  1081. def test_deformable_psroi_pooling():
  1082. inp = np.random.random((1, 256, 64, 64)).astype("float32")
  1083. rois = np.random.random((1, 5)).astype("float32")
  1084. trans = np.random.random((24, 2, 7, 7)).astype("float32")
  1085. pooled_h = 7
  1086. pooled_w = 7
  1087. sample_per_part = 4
  1088. no_trans = False
  1089. part_size = 7
  1090. spatial_scale = 1.0 / 64
  1091. trans_std = 0.1
  1092. y = F.deformable_psroi_pooling(
  1093. tensor(inp),
  1094. tensor(rois),
  1095. tensor(trans),
  1096. no_trans,
  1097. part_size,
  1098. pooled_h,
  1099. pooled_w,
  1100. sample_per_part,
  1101. spatial_scale,
  1102. trans_std,
  1103. )
  1104. def test_cvt_color():
  1105. def rgb2gray(rgb):
  1106. return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])
  1107. def bgr2gray(bgr):
  1108. return np.dot(bgr[..., :3], [0.114, 0.587, 0.299])
  1109. inp = np.random.randn(3, 3, 3, 3).astype(np.float32)
  1110. out = np.expand_dims(rgb2gray(inp), 3).astype(np.float32)
  1111. x = tensor(inp)
  1112. y = F.vision.cvt_color(x, mode="RGB2GRAY")
  1113. np.testing.assert_allclose(y.numpy(), out, atol=1e-5)
  1114. out1 = np.expand_dims(bgr2gray(inp), 3).astype(np.float32)
  1115. y1 = F.vision.cvt_color(x, mode="BGR2GRAY")
  1116. np.testing.assert_allclose(y1.numpy(), out1, atol=1e-5)
  1117. @pytest.mark.parametrize("val", [2, [2,], [2, 3]])
  1118. def test_ones(val):
  1119. shp = tensor(val)
  1120. np_shp = np.array(val)
  1121. np.testing.assert_equal(F.ones(shp), np.ones(np_shp))
  1122. def test_assert_equal():
  1123. shape = (2, 3, 4, 5)
  1124. x = F.ones(shape, dtype=np.float32)
  1125. y = F.zeros(shape, dtype=np.float32) + 1.00001
  1126. z = F.utils._assert_equal(x, y)
  1127. def test_assert_not_equal():
  1128. shape = (2, 3, 4, 5)
  1129. x = F.ones(shape, dtype=np.float32)
  1130. y = F.zeros(shape, dtype=np.float32) + 1.1
  1131. with pytest.raises(RuntimeError):
  1132. z = F.utils._assert_equal(x, y)
  1133. def test_neg_axis():
  1134. x = tensor(np.random.normal(0, 1, (32, 5)))
  1135. y = F.argmax(x, axis=-1)
  1136. yy = F.argmax(x, axis=1)
  1137. np.testing.assert_equal(y.numpy(), yy.numpy())
  1138. y = F.argmax(x, axis=(-1, -2))
  1139. yy = F.argmax(x, axis=(0, 1))
  1140. np.testing.assert_equal(y.numpy(), yy.numpy())
  1141. y = F.argmin(x, axis=(-1, -2))
  1142. yy = F.argmin(x, axis=(0, 1))
  1143. np.testing.assert_equal(y.numpy(), yy.numpy())
  1144. def test_sliding_window():
  1145. N, C, H, W = 2, 3, 7, 8
  1146. inp = np.random.normal(size=(N, C, H, W))
  1147. ph, pw = 1, 2
  1148. sh, sw = 2, 1
  1149. wh, ww = 3, 2
  1150. dh, dw = 1, 3
  1151. s = lambda i, p, s, d, w: (i + p * 2 - (w - 1) * d - 1) // s + 1
  1152. inp_pad = np.zeros((N, C, H + ph * 2, W + pw * 2))
  1153. inp_pad[:, :, ph : H + ph, pw : W + pw] = inp
  1154. gt_out = np.empty(
  1155. (N, C, s(H, ph, sh, dh, wh), s(W, pw, sw, dw, ww), wh, ww), dtype=np.float32
  1156. )
  1157. for n, c, oh, ow in itertools.product(*map(range, gt_out.shape[:4])):
  1158. ih, iw = oh * sh, ow * sw
  1159. gt_out[n, c, oh, ow, :] = inp_pad[
  1160. n, c, ih : ih + (wh - 1) * dh + 1 : dh, iw : iw + (ww - 1) * dw + 1 : dw
  1161. ]
  1162. out = F.sliding_window(
  1163. tensor(inp), (wh, ww), padding=(ph, pw), stride=(sh, sw), dilation=(dh, dw)
  1164. )
  1165. np.testing.assert_equal(gt_out, out.numpy())
  1166. def test_sliding_window_transpose():
  1167. N, C, H, W = 2, 3, 7, 8
  1168. ph, pw = 1, 2
  1169. sh, sw = 2, 1
  1170. wh, ww = 3, 2
  1171. dh, dw = 1, 3
  1172. s = lambda i, p, s, d, w: (i + p * 2 - (w - 1) * d - 1) // s + 1
  1173. inp = np.random.normal(
  1174. size=(N, C, s(H, ph, sh, dh, wh), s(W, pw, sw, dw, ww), wh, ww)
  1175. ).astype(np.float32)
  1176. gt_out = np.zeros((N, C, H, W), dtype=np.float32)
  1177. for n, c in itertools.product(*map(range, inp.shape[:2])):
  1178. oh = 0
  1179. for ih in range(-ph, H + ph - dh * (wh - 1), sh):
  1180. ow = 0
  1181. for iw in range(-pw, W + pw - dw * (ww - 1), sw):
  1182. for kh, kw in itertools.product(*map(range, inp.shape[-2:])):
  1183. ih2 = ih + dh * kh
  1184. iw2 = iw + dw * kw
  1185. if ih2 >= 0 and ih2 < H and iw2 >= 0 and iw2 < W:
  1186. gt_out[n, c, ih2, iw2] += inp[n, c, oh, ow, kh, kw]
  1187. ow += 1
  1188. oh += 1
  1189. out = F.sliding_window_transpose(
  1190. tensor(inp),
  1191. (H, W),
  1192. (wh, ww),
  1193. padding=(ph, pw),
  1194. stride=(sh, sw),
  1195. dilation=(dh, dw),
  1196. )
  1197. np.testing.assert_equal(gt_out, out.numpy())
  1198. def test_pad():
  1199. src = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32)
  1200. dst = np.pad(src, ((2, 2), (2, 2)), "constant")
  1201. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "CONSTANT")
  1202. np.testing.assert_allclose(res, dst, atol=1e-5)
  1203. dst = np.pad(src, ((2, 2), (2, 2)), "constant", constant_values=3)
  1204. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "CONSTANT", constant_value=3)
  1205. np.testing.assert_allclose(res, dst, atol=1e-5)
  1206. dst = np.pad(src, ((2, 2), (2, 2)), "edge")
  1207. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "EDGE")
  1208. np.testing.assert_allclose(res, dst, atol=1e-5)
  1209. dst = np.pad(src, ((2, 2), (2, 2)), "reflect")
  1210. res = F.nn.pad(tensor(src), ((2, 2), (2, 2)), "REFLECT")
  1211. np.testing.assert_allclose(res, dst, atol=1e-5)
  1212. def pixel_shuffle(data, r):
  1213. high_dim = data.shape[:-3]
  1214. data = data.reshape(-1, data.shape[-3], data.shape[-2], data.shape[-1])
  1215. inn, ic, ih, iw = data.shape
  1216. res = np.zeros((inn, int(ic / (r * r)), ih * r, iw * r))
  1217. for n in range(inn):
  1218. for c in range(ic):
  1219. for h in range(ih):
  1220. for w in range(iw):
  1221. res[
  1222. n,
  1223. int(c / r / r),
  1224. h * r + int((c % (r * r)) / r),
  1225. w * r + c % r,
  1226. ] = data[n, c, h, w]
  1227. if len(high_dim) > 0:
  1228. res = res.reshape((*high_dim, int(ic / r / r), ih * r, iw * r))
  1229. else:
  1230. res = res[0]
  1231. return res
  1232. def test_pixel_shuffle():
  1233. # ndim = 3
  1234. inp = np.arange(16 * 3 * 3).reshape(16, 3, 3)
  1235. out = F.pixel_shuffle(tensor(inp), upscale_factor=4)
  1236. golden = pixel_shuffle(inp, 4)
  1237. np.testing.assert_equal(out.numpy(), golden)
  1238. inp_float = np.float32(inp)
  1239. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=2)
  1240. golden = pixel_shuffle(inp_float, 2)
  1241. np.testing.assert_equal(out.numpy(), golden)
  1242. # ndim = 4
  1243. inp = np.arange(3 * 18 * 3 * 3).reshape(3, 18, 3, 3)
  1244. out = F.pixel_shuffle(tensor(inp), upscale_factor=3)
  1245. golden = pixel_shuffle(inp, 3)
  1246. np.testing.assert_equal(out.numpy(), golden)
  1247. inp_float = np.float32(inp)
  1248. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=3)
  1249. golden = pixel_shuffle(inp_float, 3)
  1250. np.testing.assert_equal(out.numpy(), golden)
  1251. # ndim = 5
  1252. inp = np.arange(5 * 3 * 20 * 3 * 4).reshape(5, 3, 20, 3, 4)
  1253. out = F.pixel_shuffle(tensor(inp), upscale_factor=2)
  1254. golden = pixel_shuffle(inp, 2)
  1255. np.testing.assert_equal(out.numpy(), golden)
  1256. inp_float = np.float32(inp)
  1257. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=2)
  1258. golden = pixel_shuffle(inp_float, 2)
  1259. np.testing.assert_equal(out.numpy(), golden)
  1260. # ndim = 6
  1261. inp = np.arange(6 * 5 * 3 * 25 * 3 * 4).reshape(6, 5, 3, 25, 3, 4)
  1262. out = F.pixel_shuffle(tensor(inp), upscale_factor=5)
  1263. golden = pixel_shuffle(inp, 5)
  1264. np.testing.assert_equal(out.numpy(), golden)
  1265. inp_float = np.float32(inp)
  1266. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=5)
  1267. golden = pixel_shuffle(inp_float, 5)
  1268. np.testing.assert_equal(out.numpy(), golden)
  1269. # ndim = 7
  1270. inp = np.arange(2 * 3 * 5 * 3 * 20 * 3 * 4).reshape(2, 3, 5, 3, 20, 3, 4)
  1271. out = F.pixel_shuffle(tensor(inp), upscale_factor=2)
  1272. golden = pixel_shuffle(inp, 2)
  1273. np.testing.assert_equal(out.numpy(), golden)
  1274. inp_float = np.float32(inp)
  1275. out = F.pixel_shuffle(tensor(inp_float), upscale_factor=2)
  1276. golden = pixel_shuffle(inp_float, 2)
  1277. np.testing.assert_equal(out.numpy(), golden)
  1278. @pytest.mark.parametrize("type", ["int32", "float32"])
  1279. @pytest.mark.parametrize("is_symbolic", [False, True])
  1280. def test_pixel_shuffle_symbolic(is_symbolic, type):
  1281. def fn(inp, upscale_factor):
  1282. return F.pixel_shuffle(inp, upscale_factor=upscale_factor)
  1283. if is_symbolic is not None:
  1284. fn = jit.trace(symbolic=is_symbolic)(fn)
  1285. inp = tensor(np.arange(3 * 4 * 5 * 5).reshape(3, 4, 5, 5).astype(type))
  1286. golden = pixel_shuffle(inp, 2)
  1287. for _ in range(3):
  1288. out = fn(inp, 2)
  1289. np.testing.assert_equal(out.numpy(), golden)
  1290. if is_symbolic is None:
  1291. break
  1292. def test_set_conv2d_config():
  1293. """check setting config by contextmanager is equal to manually converted result"""
  1294. config._compute_mode = "float32"
  1295. inp = tensor(np.random.randn(1, 3, 224, 224), dtype=np.float16)
  1296. weight = tensor(np.random.randn(64, 3, 7, 7), dtype=np.float16)
  1297. config_out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  1298. config._compute_mode = "default"
  1299. with config._override(compute_mode="float32"):
  1300. context_out = F.conv2d(inp, weight, None, (2, 2), (3, 3), (1, 1), 1)
  1301. expected = F.conv2d(
  1302. inp, weight, None, (2, 2), (3, 3), (1, 1), 1, compute_mode="float32",
  1303. )
  1304. np.testing.assert_allclose(config_out.numpy(), expected.numpy())
  1305. np.testing.assert_allclose(context_out.numpy(), expected.numpy())
  1306. @pytest.mark.parametrize("stride", [(1, 1)])
  1307. @pytest.mark.parametrize("padding", [(1, 1)])
  1308. @pytest.mark.parametrize("dilation", [(1, 1)])
  1309. @pytest.mark.parametrize("ksize", [(3, 3)])
  1310. @pytest.mark.parametrize("groups", [1, 2])
  1311. def test_local_conv2d(stride, padding, dilation, ksize, groups):
  1312. batch_size, in_channels, out_channels = 2, 4, 8
  1313. input_height, input_width = 10, 10
  1314. output_height = (input_height + padding[0] * 2 - ksize[0]) // stride[0] + 1
  1315. output_width = (input_width + padding[1] * 2 - ksize[1]) // stride[1] + 1
  1316. def local_conv2d_np(data, weight, stride, padding, dialtion):
  1317. # naive calculation use numpy
  1318. # only test output_height == input_height, output_width == input_width
  1319. data = np.pad(data, ((0, 0), (0, 0), (1, 1), (1, 1)))
  1320. expected = np.zeros(
  1321. (batch_size, out_channels, output_height, output_width), dtype=np.float32,
  1322. )
  1323. ic_group_size = in_channels // groups
  1324. oc_group_size = out_channels // groups
  1325. for n, oc, oh, ow in itertools.product(
  1326. *map(range, [batch_size, out_channels, output_height, output_width])
  1327. ):
  1328. ih, iw = oh * stride[0], ow * stride[1]
  1329. g_id = oc // oc_group_size
  1330. expected[n, oc, ih, iw] = np.sum(
  1331. data[
  1332. n,
  1333. g_id * ic_group_size : (g_id + 1) * ic_group_size,
  1334. ih : ih + ksize[0],
  1335. iw : iw + ksize[1],
  1336. ]
  1337. * weight[g_id, oh, ow, :, :, :, oc % oc_group_size]
  1338. )
  1339. return expected
  1340. data = np.random.rand(batch_size, in_channels, input_height, input_width).astype(
  1341. "float32"
  1342. )
  1343. weight = np.random.rand(
  1344. groups,
  1345. output_height,
  1346. output_width,
  1347. in_channels // groups,
  1348. *ksize,
  1349. out_channels // groups,
  1350. ).astype("float32")
  1351. output = F.local_conv2d(
  1352. tensor(data),
  1353. tensor(weight),
  1354. None,
  1355. stride=stride,
  1356. padding=padding,
  1357. dilation=dilation,
  1358. )
  1359. ref = local_conv2d_np(data, weight, stride, padding, dilation)
  1360. np.testing.assert_almost_equal(output.numpy(), ref, 5)
  1361. def test_conv_transpose2d():
  1362. m = ConvTranspose2d(
  1363. 16, 33, (3, 5), output_padding=(1, 2), stride=(2, 3), padding=(4, 2)
  1364. )
  1365. @trace(symbolic=True)
  1366. def fwd(inp: Tensor):
  1367. return m(inp)
  1368. input = Tensor(np.random.rand(20, 16, 50, 100))
  1369. output = fwd(input)
  1370. output_shape = Tensor(output.shape)
  1371. np.testing.assert_equal(
  1372. output_shape.numpy(), np.array([20, 33, 94, 300], dtype=np.int32)
  1373. )
  1374. def test_conv_transpose3d():
  1375. m = ConvTranspose3d(
  1376. 16, 33, (3, 5, 2), output_padding=(2, 1, 1), stride=(3, 2, 2), padding=(0, 4, 2)
  1377. )
  1378. @trace(symbolic=True)
  1379. def fwd(inp: Tensor):
  1380. return m(inp)
  1381. input = Tensor(np.random.rand(20, 16, 10, 50, 100))
  1382. output = fwd(input)
  1383. output_shape = Tensor(output.shape)
  1384. np.testing.assert_equal(
  1385. output_shape.numpy(), np.array([20, 33, 32, 96, 197], dtype=np.int32)
  1386. )