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

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

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台