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

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