warp-lang 1.0.2__py3-none-win_amd64.whl → 1.2.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of warp-lang might be problematic. Click here for more details.

Files changed (356) hide show
  1. warp/__init__.py +108 -97
  2. warp/__init__.pyi +1 -1
  3. warp/bin/warp-clang.dll +0 -0
  4. warp/bin/warp.dll +0 -0
  5. warp/build.py +88 -113
  6. warp/build_dll.py +383 -375
  7. warp/builtins.py +3693 -3354
  8. warp/codegen.py +2925 -2792
  9. warp/config.py +40 -36
  10. warp/constants.py +49 -45
  11. warp/context.py +5409 -5102
  12. warp/dlpack.py +442 -442
  13. warp/examples/__init__.py +16 -16
  14. warp/examples/assets/bear.usd +0 -0
  15. warp/examples/assets/bunny.usd +0 -0
  16. warp/examples/assets/cartpole.urdf +110 -110
  17. warp/examples/assets/crazyflie.usd +0 -0
  18. warp/examples/assets/cube.usd +0 -0
  19. warp/examples/assets/nv_ant.xml +92 -92
  20. warp/examples/assets/nv_humanoid.xml +183 -183
  21. warp/examples/assets/quadruped.urdf +267 -267
  22. warp/examples/assets/rocks.nvdb +0 -0
  23. warp/examples/assets/rocks.usd +0 -0
  24. warp/examples/assets/sphere.usd +0 -0
  25. warp/examples/benchmarks/benchmark_api.py +381 -383
  26. warp/examples/benchmarks/benchmark_cloth.py +278 -277
  27. warp/examples/benchmarks/benchmark_cloth_cupy.py +88 -88
  28. warp/examples/benchmarks/benchmark_cloth_jax.py +97 -100
  29. warp/examples/benchmarks/benchmark_cloth_numba.py +146 -142
  30. warp/examples/benchmarks/benchmark_cloth_numpy.py +77 -77
  31. warp/examples/benchmarks/benchmark_cloth_pytorch.py +86 -86
  32. warp/examples/benchmarks/benchmark_cloth_taichi.py +112 -112
  33. warp/examples/benchmarks/benchmark_cloth_warp.py +145 -146
  34. warp/examples/benchmarks/benchmark_launches.py +293 -295
  35. warp/examples/browse.py +29 -29
  36. warp/examples/core/example_dem.py +232 -219
  37. warp/examples/core/example_fluid.py +291 -267
  38. warp/examples/core/example_graph_capture.py +142 -126
  39. warp/examples/core/example_marching_cubes.py +186 -174
  40. warp/examples/core/example_mesh.py +172 -155
  41. warp/examples/core/example_mesh_intersect.py +203 -193
  42. warp/examples/core/example_nvdb.py +174 -170
  43. warp/examples/core/example_raycast.py +103 -90
  44. warp/examples/core/example_raymarch.py +197 -178
  45. warp/examples/core/example_render_opengl.py +183 -141
  46. warp/examples/core/example_sph.py +403 -387
  47. warp/examples/core/example_torch.py +219 -181
  48. warp/examples/core/example_wave.py +261 -248
  49. warp/examples/fem/bsr_utils.py +378 -380
  50. warp/examples/fem/example_apic_fluid.py +432 -389
  51. warp/examples/fem/example_burgers.py +262 -0
  52. warp/examples/fem/example_convection_diffusion.py +180 -168
  53. warp/examples/fem/example_convection_diffusion_dg.py +217 -209
  54. warp/examples/fem/example_deformed_geometry.py +175 -159
  55. warp/examples/fem/example_diffusion.py +199 -173
  56. warp/examples/fem/example_diffusion_3d.py +178 -152
  57. warp/examples/fem/example_diffusion_mgpu.py +219 -214
  58. warp/examples/fem/example_mixed_elasticity.py +242 -222
  59. warp/examples/fem/example_navier_stokes.py +257 -243
  60. warp/examples/fem/example_stokes.py +218 -192
  61. warp/examples/fem/example_stokes_transfer.py +263 -249
  62. warp/examples/fem/mesh_utils.py +133 -109
  63. warp/examples/fem/plot_utils.py +292 -287
  64. warp/examples/optim/example_bounce.py +258 -246
  65. warp/examples/optim/example_cloth_throw.py +220 -209
  66. warp/examples/optim/example_diffray.py +564 -536
  67. warp/examples/optim/example_drone.py +862 -835
  68. warp/examples/optim/example_inverse_kinematics.py +174 -168
  69. warp/examples/optim/example_inverse_kinematics_torch.py +183 -169
  70. warp/examples/optim/example_spring_cage.py +237 -231
  71. warp/examples/optim/example_trajectory.py +221 -199
  72. warp/examples/optim/example_walker.py +304 -293
  73. warp/examples/sim/example_cartpole.py +137 -129
  74. warp/examples/sim/example_cloth.py +194 -186
  75. warp/examples/sim/example_granular.py +122 -111
  76. warp/examples/sim/example_granular_collision_sdf.py +195 -186
  77. warp/examples/sim/example_jacobian_ik.py +234 -214
  78. warp/examples/sim/example_particle_chain.py +116 -105
  79. warp/examples/sim/example_quadruped.py +191 -180
  80. warp/examples/sim/example_rigid_chain.py +195 -187
  81. warp/examples/sim/example_rigid_contact.py +187 -177
  82. warp/examples/sim/example_rigid_force.py +125 -125
  83. warp/examples/sim/example_rigid_gyroscopic.py +107 -95
  84. warp/examples/sim/example_rigid_soft_contact.py +132 -122
  85. warp/examples/sim/example_soft_body.py +188 -177
  86. warp/fabric.py +337 -335
  87. warp/fem/__init__.py +61 -27
  88. warp/fem/cache.py +403 -388
  89. warp/fem/dirichlet.py +178 -179
  90. warp/fem/domain.py +262 -263
  91. warp/fem/field/__init__.py +100 -101
  92. warp/fem/field/field.py +148 -149
  93. warp/fem/field/nodal_field.py +298 -299
  94. warp/fem/field/restriction.py +22 -21
  95. warp/fem/field/test.py +180 -181
  96. warp/fem/field/trial.py +183 -183
  97. warp/fem/geometry/__init__.py +16 -19
  98. warp/fem/geometry/closest_point.py +69 -70
  99. warp/fem/geometry/deformed_geometry.py +270 -271
  100. warp/fem/geometry/element.py +748 -744
  101. warp/fem/geometry/geometry.py +184 -186
  102. warp/fem/geometry/grid_2d.py +380 -373
  103. warp/fem/geometry/grid_3d.py +437 -435
  104. warp/fem/geometry/hexmesh.py +953 -953
  105. warp/fem/geometry/nanogrid.py +455 -0
  106. warp/fem/geometry/partition.py +374 -376
  107. warp/fem/geometry/quadmesh_2d.py +532 -532
  108. warp/fem/geometry/tetmesh.py +840 -840
  109. warp/fem/geometry/trimesh_2d.py +577 -577
  110. warp/fem/integrate.py +1684 -1615
  111. warp/fem/operator.py +190 -191
  112. warp/fem/polynomial.py +214 -213
  113. warp/fem/quadrature/__init__.py +2 -2
  114. warp/fem/quadrature/pic_quadrature.py +243 -245
  115. warp/fem/quadrature/quadrature.py +295 -294
  116. warp/fem/space/__init__.py +179 -292
  117. warp/fem/space/basis_space.py +522 -489
  118. warp/fem/space/collocated_function_space.py +100 -105
  119. warp/fem/space/dof_mapper.py +236 -236
  120. warp/fem/space/function_space.py +148 -145
  121. warp/fem/space/grid_2d_function_space.py +148 -267
  122. warp/fem/space/grid_3d_function_space.py +167 -306
  123. warp/fem/space/hexmesh_function_space.py +253 -352
  124. warp/fem/space/nanogrid_function_space.py +202 -0
  125. warp/fem/space/partition.py +350 -350
  126. warp/fem/space/quadmesh_2d_function_space.py +261 -369
  127. warp/fem/space/restriction.py +161 -160
  128. warp/fem/space/shape/__init__.py +90 -15
  129. warp/fem/space/shape/cube_shape_function.py +728 -738
  130. warp/fem/space/shape/shape_function.py +102 -103
  131. warp/fem/space/shape/square_shape_function.py +611 -611
  132. warp/fem/space/shape/tet_shape_function.py +565 -567
  133. warp/fem/space/shape/triangle_shape_function.py +429 -429
  134. warp/fem/space/tetmesh_function_space.py +224 -292
  135. warp/fem/space/topology.py +297 -295
  136. warp/fem/space/trimesh_2d_function_space.py +153 -221
  137. warp/fem/types.py +77 -77
  138. warp/fem/utils.py +495 -495
  139. warp/jax.py +166 -141
  140. warp/jax_experimental.py +341 -339
  141. warp/native/array.h +1081 -1025
  142. warp/native/builtin.h +1603 -1560
  143. warp/native/bvh.cpp +402 -398
  144. warp/native/bvh.cu +533 -525
  145. warp/native/bvh.h +430 -429
  146. warp/native/clang/clang.cpp +496 -464
  147. warp/native/crt.cpp +42 -32
  148. warp/native/crt.h +352 -335
  149. warp/native/cuda_crt.h +1049 -1049
  150. warp/native/cuda_util.cpp +549 -540
  151. warp/native/cuda_util.h +288 -203
  152. warp/native/cutlass_gemm.cpp +34 -34
  153. warp/native/cutlass_gemm.cu +372 -372
  154. warp/native/error.cpp +66 -66
  155. warp/native/error.h +27 -27
  156. warp/native/exports.h +187 -0
  157. warp/native/fabric.h +228 -228
  158. warp/native/hashgrid.cpp +301 -278
  159. warp/native/hashgrid.cu +78 -77
  160. warp/native/hashgrid.h +227 -227
  161. warp/native/initializer_array.h +32 -32
  162. warp/native/intersect.h +1204 -1204
  163. warp/native/intersect_adj.h +365 -365
  164. warp/native/intersect_tri.h +322 -322
  165. warp/native/marching.cpp +2 -2
  166. warp/native/marching.cu +497 -497
  167. warp/native/marching.h +2 -2
  168. warp/native/mat.h +1545 -1498
  169. warp/native/matnn.h +333 -333
  170. warp/native/mesh.cpp +203 -203
  171. warp/native/mesh.cu +292 -293
  172. warp/native/mesh.h +1887 -1887
  173. warp/native/nanovdb/GridHandle.h +366 -0
  174. warp/native/nanovdb/HostBuffer.h +590 -0
  175. warp/native/nanovdb/NanoVDB.h +6624 -4782
  176. warp/native/nanovdb/PNanoVDB.h +3390 -2553
  177. warp/native/noise.h +850 -850
  178. warp/native/quat.h +1112 -1085
  179. warp/native/rand.h +303 -299
  180. warp/native/range.h +108 -108
  181. warp/native/reduce.cpp +156 -156
  182. warp/native/reduce.cu +348 -348
  183. warp/native/runlength_encode.cpp +61 -61
  184. warp/native/runlength_encode.cu +46 -46
  185. warp/native/scan.cpp +30 -30
  186. warp/native/scan.cu +36 -36
  187. warp/native/scan.h +7 -7
  188. warp/native/solid_angle.h +442 -442
  189. warp/native/sort.cpp +94 -94
  190. warp/native/sort.cu +97 -97
  191. warp/native/sort.h +14 -14
  192. warp/native/sparse.cpp +337 -337
  193. warp/native/sparse.cu +544 -544
  194. warp/native/spatial.h +630 -630
  195. warp/native/svd.h +562 -562
  196. warp/native/temp_buffer.h +30 -30
  197. warp/native/vec.h +1177 -1133
  198. warp/native/volume.cpp +529 -297
  199. warp/native/volume.cu +58 -32
  200. warp/native/volume.h +960 -538
  201. warp/native/volume_builder.cu +446 -425
  202. warp/native/volume_builder.h +34 -19
  203. warp/native/volume_impl.h +61 -0
  204. warp/native/warp.cpp +1057 -1052
  205. warp/native/warp.cu +2949 -2828
  206. warp/native/warp.h +321 -305
  207. warp/optim/__init__.py +9 -9
  208. warp/optim/adam.py +120 -120
  209. warp/optim/linear.py +1104 -939
  210. warp/optim/sgd.py +104 -92
  211. warp/render/__init__.py +10 -10
  212. warp/render/render_opengl.py +3356 -3204
  213. warp/render/render_usd.py +768 -749
  214. warp/render/utils.py +152 -150
  215. warp/sim/__init__.py +52 -59
  216. warp/sim/articulation.py +685 -685
  217. warp/sim/collide.py +1594 -1590
  218. warp/sim/import_mjcf.py +489 -481
  219. warp/sim/import_snu.py +220 -221
  220. warp/sim/import_urdf.py +536 -516
  221. warp/sim/import_usd.py +887 -881
  222. warp/sim/inertia.py +316 -317
  223. warp/sim/integrator.py +234 -233
  224. warp/sim/integrator_euler.py +1956 -1956
  225. warp/sim/integrator_featherstone.py +1917 -1991
  226. warp/sim/integrator_xpbd.py +3288 -3312
  227. warp/sim/model.py +4473 -4314
  228. warp/sim/particles.py +113 -112
  229. warp/sim/render.py +417 -403
  230. warp/sim/utils.py +413 -410
  231. warp/sparse.py +1289 -1227
  232. warp/stubs.py +2192 -2469
  233. warp/tape.py +1162 -225
  234. warp/tests/__init__.py +1 -1
  235. warp/tests/__main__.py +4 -4
  236. warp/tests/assets/test_index_grid.nvdb +0 -0
  237. warp/tests/assets/torus.usda +105 -105
  238. warp/tests/aux_test_class_kernel.py +26 -26
  239. warp/tests/aux_test_compile_consts_dummy.py +10 -10
  240. warp/tests/aux_test_conditional_unequal_types_kernels.py +21 -21
  241. warp/tests/aux_test_dependent.py +20 -22
  242. warp/tests/aux_test_grad_customs.py +21 -23
  243. warp/tests/aux_test_reference.py +9 -11
  244. warp/tests/aux_test_reference_reference.py +8 -10
  245. warp/tests/aux_test_square.py +15 -17
  246. warp/tests/aux_test_unresolved_func.py +14 -14
  247. warp/tests/aux_test_unresolved_symbol.py +14 -14
  248. warp/tests/disabled_kinematics.py +237 -239
  249. warp/tests/run_coverage_serial.py +31 -31
  250. warp/tests/test_adam.py +155 -157
  251. warp/tests/test_arithmetic.py +1088 -1124
  252. warp/tests/test_array.py +2415 -2326
  253. warp/tests/test_array_reduce.py +148 -150
  254. warp/tests/test_async.py +666 -656
  255. warp/tests/test_atomic.py +139 -141
  256. warp/tests/test_bool.py +212 -149
  257. warp/tests/test_builtins_resolution.py +1290 -1292
  258. warp/tests/test_bvh.py +162 -171
  259. warp/tests/test_closest_point_edge_edge.py +227 -228
  260. warp/tests/test_codegen.py +562 -553
  261. warp/tests/test_compile_consts.py +217 -101
  262. warp/tests/test_conditional.py +244 -246
  263. warp/tests/test_copy.py +230 -215
  264. warp/tests/test_ctypes.py +630 -632
  265. warp/tests/test_dense.py +65 -67
  266. warp/tests/test_devices.py +89 -98
  267. warp/tests/test_dlpack.py +528 -529
  268. warp/tests/test_examples.py +403 -378
  269. warp/tests/test_fabricarray.py +952 -955
  270. warp/tests/test_fast_math.py +60 -54
  271. warp/tests/test_fem.py +1298 -1278
  272. warp/tests/test_fp16.py +128 -130
  273. warp/tests/test_func.py +336 -337
  274. warp/tests/test_generics.py +596 -571
  275. warp/tests/test_grad.py +885 -640
  276. warp/tests/test_grad_customs.py +331 -336
  277. warp/tests/test_hash_grid.py +208 -164
  278. warp/tests/test_import.py +37 -39
  279. warp/tests/test_indexedarray.py +1132 -1134
  280. warp/tests/test_intersect.py +65 -67
  281. warp/tests/test_jax.py +305 -307
  282. warp/tests/test_large.py +169 -164
  283. warp/tests/test_launch.py +352 -354
  284. warp/tests/test_lerp.py +217 -261
  285. warp/tests/test_linear_solvers.py +189 -171
  286. warp/tests/test_lvalue.py +419 -493
  287. warp/tests/test_marching_cubes.py +63 -65
  288. warp/tests/test_mat.py +1799 -1827
  289. warp/tests/test_mat_lite.py +113 -115
  290. warp/tests/test_mat_scalar_ops.py +2905 -2889
  291. warp/tests/test_math.py +124 -193
  292. warp/tests/test_matmul.py +498 -499
  293. warp/tests/test_matmul_lite.py +408 -410
  294. warp/tests/test_mempool.py +186 -190
  295. warp/tests/test_mesh.py +281 -324
  296. warp/tests/test_mesh_query_aabb.py +226 -241
  297. warp/tests/test_mesh_query_point.py +690 -702
  298. warp/tests/test_mesh_query_ray.py +290 -303
  299. warp/tests/test_mlp.py +274 -276
  300. warp/tests/test_model.py +108 -110
  301. warp/tests/test_module_hashing.py +111 -0
  302. warp/tests/test_modules_lite.py +36 -39
  303. warp/tests/test_multigpu.py +161 -163
  304. warp/tests/test_noise.py +244 -248
  305. warp/tests/test_operators.py +248 -250
  306. warp/tests/test_options.py +121 -125
  307. warp/tests/test_peer.py +131 -137
  308. warp/tests/test_pinned.py +76 -78
  309. warp/tests/test_print.py +52 -54
  310. warp/tests/test_quat.py +2084 -2086
  311. warp/tests/test_rand.py +324 -288
  312. warp/tests/test_reload.py +207 -217
  313. warp/tests/test_rounding.py +177 -179
  314. warp/tests/test_runlength_encode.py +188 -190
  315. warp/tests/test_sim_grad.py +241 -0
  316. warp/tests/test_sim_kinematics.py +89 -97
  317. warp/tests/test_smoothstep.py +166 -168
  318. warp/tests/test_snippet.py +303 -266
  319. warp/tests/test_sparse.py +466 -460
  320. warp/tests/test_spatial.py +2146 -2148
  321. warp/tests/test_special_values.py +362 -0
  322. warp/tests/test_streams.py +484 -473
  323. warp/tests/test_struct.py +708 -675
  324. warp/tests/test_tape.py +171 -148
  325. warp/tests/test_torch.py +741 -743
  326. warp/tests/test_transient_module.py +85 -87
  327. warp/tests/test_types.py +554 -659
  328. warp/tests/test_utils.py +488 -499
  329. warp/tests/test_vec.py +1262 -1268
  330. warp/tests/test_vec_lite.py +71 -73
  331. warp/tests/test_vec_scalar_ops.py +2097 -2099
  332. warp/tests/test_verify_fp.py +92 -94
  333. warp/tests/test_volume.py +961 -736
  334. warp/tests/test_volume_write.py +338 -265
  335. warp/tests/unittest_serial.py +38 -37
  336. warp/tests/unittest_suites.py +367 -359
  337. warp/tests/unittest_utils.py +434 -578
  338. warp/tests/unused_test_misc.py +69 -71
  339. warp/tests/walkthrough_debug.py +85 -85
  340. warp/thirdparty/appdirs.py +598 -598
  341. warp/thirdparty/dlpack.py +143 -143
  342. warp/thirdparty/unittest_parallel.py +563 -561
  343. warp/torch.py +321 -295
  344. warp/types.py +4941 -4450
  345. warp/utils.py +1008 -821
  346. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/LICENSE.md +126 -126
  347. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/METADATA +365 -400
  348. warp_lang-1.2.0.dist-info/RECORD +359 -0
  349. warp/examples/assets/cube.usda +0 -42
  350. warp/examples/assets/sphere.usda +0 -56
  351. warp/examples/assets/torus.usda +0 -105
  352. warp/examples/fem/example_convection_diffusion_dg0.py +0 -194
  353. warp/native/nanovdb/PNanoVDBWrite.h +0 -295
  354. warp_lang-1.0.2.dist-info/RECORD +0 -352
  355. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/WHEEL +0 -0
  356. {warp_lang-1.0.2.dist-info → warp_lang-1.2.0.dist-info}/top_level.txt +0 -0
warp/tests/test_mat.py CHANGED
@@ -1,1827 +1,1799 @@
1
- # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
2
- # NVIDIA CORPORATION and its licensors retain all intellectual property
3
- # and proprietary rights in and to this software, related documentation
4
- # and any modifications thereto. Any use, reproduction, disclosure or
5
- # distribution of this software and related documentation without an express
6
- # license agreement from NVIDIA CORPORATION is strictly prohibited.
7
-
8
- import unittest
9
-
10
- import numpy as np
11
-
12
- import warp as wp
13
- from warp.tests.unittest_utils import *
14
-
15
- wp.init()
16
-
17
- np_signed_int_types = [
18
- np.int8,
19
- np.int16,
20
- np.int32,
21
- np.int64,
22
- np.byte,
23
- ]
24
-
25
- np_float_types = [np.float16, np.float32, np.float64]
26
-
27
-
28
- def randvals(rng, shape, dtype):
29
- if dtype in np_float_types:
30
- return rng.standard_normal(size=shape).astype(dtype)
31
- elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]:
32
- return rng.integers(1, high=3, size=shape, dtype=dtype)
33
- return rng.integers(1, high=5, size=shape, dtype=dtype)
34
-
35
-
36
- kernel_cache = dict()
37
-
38
-
39
- def getkernel(func, suffix=""):
40
- key = func.__name__ + "_" + suffix
41
- if key not in kernel_cache:
42
- kernel_cache[key] = wp.Kernel(func=func, key=key)
43
- return kernel_cache[key]
44
-
45
-
46
- def get_select_kernel(dtype):
47
- def output_select_kernel_fn(
48
- input: wp.array(dtype=dtype),
49
- index: int,
50
- out: wp.array(dtype=dtype),
51
- ):
52
- out[0] = input[index]
53
-
54
- return getkernel(output_select_kernel_fn, suffix=dtype.__name__)
55
-
56
- wp.launch(kernel, dim=1, inputs=[])
57
-
58
-
59
- def test_anon_constructor_error_shape_keyword_missing(test, device):
60
- @wp.kernel
61
- def kernel():
62
- wp.matrix(1.0, 2.0, 3.0)
63
-
64
- with test.assertRaisesRegex(
65
- RuntimeError,
66
- r"shape keyword must be specified when calling matrix\(\) function$",
67
- ):
68
- wp.launch(
69
- kernel,
70
- dim=1,
71
- inputs=[],
72
- device=device,
73
- )
74
-
75
-
76
- def test_anon_constructor_error_dtype_keyword_missing(test, device):
77
- @wp.kernel
78
- def kernel():
79
- wp.matrix(shape=(3, 3))
80
-
81
- with test.assertRaisesRegex(
82
- RuntimeError,
83
- r"matrix\(\) must have dtype as a keyword argument if it has no " r"positional arguments$",
84
- ):
85
- wp.launch(
86
- kernel,
87
- dim=1,
88
- inputs=[],
89
- device=device,
90
- )
91
-
92
-
93
- def test_anon_constructor_error_shape_mismatch(test, device):
94
- @wp.kernel
95
- def kernel():
96
- wp.matrix(
97
- wp.matrix(shape=(1, 2), dtype=float),
98
- shape=(3, 4),
99
- dtype=float,
100
- )
101
-
102
- with test.assertRaisesRegex(
103
- RuntimeError,
104
- r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 4\) vs \(1, 2\)$",
105
- ):
106
- wp.launch(
107
- kernel,
108
- dim=1,
109
- inputs=[],
110
- device=device,
111
- )
112
-
113
-
114
- def test_anon_constructor_error_invalid_arg_count(test, device):
115
- @wp.kernel
116
- def kernel():
117
- wp.matrix(1.0, 2.0, 3.0, shape=(2, 2), dtype=float)
118
-
119
- with test.assertRaisesRegex(
120
- RuntimeError,
121
- r"Wrong number of arguments for matrix\(\) function, must initialize "
122
- r"with either a scalar value, or m\*n values$",
123
- ):
124
- wp.launch(
125
- kernel,
126
- dim=1,
127
- inputs=[],
128
- device=device,
129
- )
130
-
131
-
132
- def test_tpl_constructor_error_incompatible_sizes(test, device):
133
- @wp.kernel
134
- def kernel():
135
- wp.mat33(wp.mat22(1.0, 2.0, 3.0, 4.0))
136
-
137
- with test.assertRaisesRegex(
138
- RuntimeError,
139
- r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 3\) vs \(2, 2\)$",
140
- ):
141
- wp.launch(
142
- kernel,
143
- dim=1,
144
- inputs=[],
145
- device=device,
146
- )
147
-
148
-
149
- def test_tpl_constructor_error_invalid_scalar_type(test, device):
150
- @wp.kernel
151
- def kernel():
152
- wp.mat22(1, 2, 3, 4)
153
-
154
- with test.assertRaisesRegex(
155
- RuntimeError,
156
- r"Wrong scalar type for mat 2,2,<class 'warp.types.float32'> constructor$",
157
- ):
158
- wp.launch(
159
- kernel,
160
- dim=1,
161
- inputs=[],
162
- device=device,
163
- )
164
-
165
-
166
- def test_tpl_constructor_error_invalid_vector_count(test, device):
167
- @wp.kernel
168
- def kernel():
169
- wp.mat22(wp.vec3(1.0, 2.0, 3.0))
170
-
171
- with test.assertRaisesRegex(
172
- RuntimeError,
173
- r"Wrong number of vectors when attempting to construct a matrix " r"with column vectors$",
174
- ):
175
- wp.launch(
176
- kernel,
177
- dim=1,
178
- inputs=[],
179
- device=device,
180
- )
181
-
182
-
183
- def test_tpl_constructor_error_invalid_vector_shape(test, device):
184
- @wp.kernel
185
- def kernel():
186
- wp.mat22(wp.vec3(1.0, 2.0, 3.0), wp.vec3(4.0, 5.0, 6.0))
187
-
188
- with test.assertRaisesRegex(
189
- RuntimeError,
190
- r"Wrong vector row count when attempting to construct a matrix " r"with column vectors$",
191
- ):
192
- wp.launch(
193
- kernel,
194
- dim=1,
195
- inputs=[],
196
- device=device,
197
- )
198
-
199
-
200
- def test_tpl_constructor_error_invalid_arg_count(test, device):
201
- @wp.kernel
202
- def kernel():
203
- wp.mat22(1.0, 2.0, 3.0)
204
-
205
- with test.assertRaisesRegex(
206
- RuntimeError,
207
- r"Wrong number of scalars when attempting to construct a matrix " r"from a list of components$",
208
- ):
209
- wp.launch(
210
- kernel,
211
- dim=1,
212
- inputs=[],
213
- device=device,
214
- )
215
-
216
-
217
- def test_tpl_ops_with_anon(test, device):
218
- mat22f = wp.mat((2, 2), dtype=float)
219
-
220
- m = wp.mat22f(1.0, 2.0, 3.0, 4.0)
221
- m += mat22f(2.0, 3.0, 4.0, 5.0)
222
- m -= mat22f(3.0, 4.0, 5.0, 6.0)
223
- test.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
224
-
225
- m = mat22f(1.0, 2.0, 3.0, 4.0)
226
- m += wp.mat22f(2.0, 3.0, 4.0, 5.0)
227
- m -= wp.mat22f(3.0, 4.0, 5.0, 6.0)
228
- test.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
229
-
230
-
231
- def test_py_arithmetic_ops(test, device, dtype):
232
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
233
-
234
- def make_mat(*args):
235
- if wptype in wp.types.int_types:
236
- # Cast to the correct integer type to simulate wrapping.
237
- return tuple(tuple(wptype._type_(x).value for x in row) for row in args)
238
-
239
- return args
240
-
241
- def make_vec(*args):
242
- if wptype in wp.types.int_types:
243
- # Cast to the correct integer type to simulate wrapping.
244
- return tuple(wptype._type_(x).value for x in args)
245
-
246
- return args
247
-
248
- mat_cls = wp.mat((3, 3), wptype)
249
- vec_cls = wp.vec(3, wptype)
250
-
251
- m = mat_cls(((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
252
- test.assertSequenceEqual(+m, make_mat((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
253
- test.assertSequenceEqual(-m, make_mat((1, -2, -3), (-4, 5, -6), (-7, -8, 9)))
254
- test.assertSequenceEqual(m + mat_cls((5, 5, 5) * 3), make_mat((4, 7, 8), (9, 0, 11), (12, 13, -4)))
255
- test.assertSequenceEqual(m - mat_cls((5, 5, 5) * 3), make_mat((-6, -3, -2), (-1, -10, 1), (2, 3, -14)))
256
- test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(20, 25, 30))
257
- test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(20, 25, 30))
258
- test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(50, 25, 0))
259
- test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(50, 25, 0))
260
-
261
- m = mat_cls(((2, 4, 6), (8, 10, 12), (14, 16, 18)))
262
- test.assertSequenceEqual(m * wptype(2), make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
263
- test.assertSequenceEqual(wptype(2) * m, make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
264
- test.assertSequenceEqual(m / wptype(2), make_mat((1, 2, 3), (4, 5, 6), (7, 8, 9)))
265
- test.assertSequenceEqual(wptype(5040) / m, make_mat((2520, 1260, 840), (630, 504, 420), (360, 315, 280)))
266
- test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(60, 150, 240))
267
- test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(60, 150, 240))
268
- test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(120, 150, 180))
269
- test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(120, 150, 180))
270
-
271
-
272
- def test_quat_constructor(test, device, dtype, register_kernels=False):
273
- rng = np.random.default_rng(123)
274
-
275
- tol = {
276
- np.float16: 1.0e-3,
277
- np.float32: 1.0e-6,
278
- np.float64: 1.0e-8,
279
- }.get(dtype, 0)
280
-
281
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
282
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
283
- vec4 = wp.types.vector(length=4, dtype=wptype)
284
- vec3 = wp.types.vector(length=3, dtype=wptype)
285
- quat = wp.types.quaternion(dtype=wptype)
286
-
287
- output_select_kernel = get_select_kernel(wptype)
288
-
289
- def check_mat_quat_constructor(
290
- p: wp.array(dtype=vec3),
291
- r: wp.array(dtype=quat),
292
- s: wp.array(dtype=vec3),
293
- outcomponents: wp.array(dtype=wptype),
294
- outcomponents_alt: wp.array(dtype=wptype),
295
- ):
296
- m = mat44(p[0], r[0], s[0])
297
-
298
- R = wp.transpose(wp.quat_to_matrix(r[0]))
299
- c0 = s[0][0] * R[0]
300
- c1 = s[0][1] * R[1]
301
- c2 = s[0][2] * R[2]
302
- m_alt = mat44(
303
- vec4(c0[0], c0[1], c0[2], wptype(0.0)),
304
- vec4(c1[0], c1[1], c1[2], wptype(0.0)),
305
- vec4(c2[0], c2[1], c2[2], wptype(0.0)),
306
- vec4(p[0][0], p[0][1], p[0][2], wptype(1.0)),
307
- )
308
-
309
- idx = 0
310
- for i in range(4):
311
- for j in range(4):
312
- outcomponents[idx] = m[i, j]
313
- outcomponents_alt[idx] = m_alt[i, j]
314
- idx = idx + 1
315
-
316
- kernel = getkernel(check_mat_quat_constructor, suffix=dtype.__name__)
317
-
318
- if register_kernels:
319
- return
320
-
321
- # translation:
322
- p = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
323
-
324
- # generate a normalized quaternion for the rotation:
325
- r = rng.standard_normal(size=(1, 4))
326
- r /= np.linalg.norm(r)
327
- r = wp.array(r.astype(dtype), dtype=quat, requires_grad=True, device=device)
328
-
329
- # scale:
330
- s = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
331
-
332
- # just going to generate the matrix using the constructor, then
333
- # more manually, and make sure the values/gradients are the same:
334
- outcomponents = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
335
- outcomponents_alt = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
336
- wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
337
- assert_np_equal(outcomponents.numpy(), outcomponents_alt.numpy(), tol=1.0e-6)
338
-
339
- idx = 0
340
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
341
- out_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
342
- for i in range(4):
343
- for j in range(4):
344
- tape = wp.Tape()
345
- with tape:
346
- wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
347
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
348
- wp.launch(
349
- output_select_kernel, dim=1, inputs=[outcomponents_alt, idx], outputs=[out_alt], device=device
350
- )
351
-
352
- tape.backward(loss=out)
353
- p_grad = 1.0 * tape.gradients[p].numpy()[0]
354
- r_grad = 1.0 * tape.gradients[r].numpy()[0]
355
- s_grad = 1.0 * tape.gradients[s].numpy()[0]
356
- tape.zero()
357
-
358
- tape.backward(loss=out_alt)
359
- p_grad_alt = 1.0 * tape.gradients[p].numpy()[0]
360
- r_grad_alt = 1.0 * tape.gradients[r].numpy()[0]
361
- s_grad_alt = 1.0 * tape.gradients[s].numpy()[0]
362
- tape.zero()
363
-
364
- assert_np_equal(p_grad, p_grad_alt, tol=tol)
365
- assert_np_equal(r_grad, r_grad_alt, tol=tol)
366
- assert_np_equal(s_grad, s_grad_alt, tol=tol)
367
-
368
- idx = idx + 1
369
-
370
-
371
- def test_negation(test, device, dtype, register_kernels=False):
372
- rng = np.random.default_rng(123)
373
-
374
- tol = {
375
- np.float16: 1.0e-2,
376
- np.float32: 1.0e-6,
377
- np.float64: 1.0e-8,
378
- }.get(dtype, 0)
379
-
380
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
381
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
382
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
383
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
384
- mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
385
-
386
- output_select_kernel = get_select_kernel(wptype)
387
-
388
- def check_mat_negation(
389
- m2: wp.array(dtype=mat22),
390
- m3: wp.array(dtype=mat33),
391
- m4: wp.array(dtype=mat44),
392
- m5: wp.array(dtype=mat55),
393
- outcomponents: wp.array(dtype=wptype),
394
- ):
395
- mat2 = -m2[0]
396
- mat3 = -m3[0]
397
- mat4 = -m4[0]
398
- mat5 = -m5[0]
399
-
400
- # multiply outputs by 2 so we've got something to backpropagate:
401
- idx = 0
402
- for i in range(2):
403
- for j in range(2):
404
- outcomponents[idx] = wptype(2) * mat2[i, j]
405
- idx = idx + 1
406
-
407
- for i in range(3):
408
- for j in range(3):
409
- outcomponents[idx] = wptype(2) * mat3[i, j]
410
- idx = idx + 1
411
-
412
- for i in range(4):
413
- for j in range(4):
414
- outcomponents[idx] = wptype(2) * mat4[i, j]
415
- idx = idx + 1
416
-
417
- for i in range(5):
418
- for j in range(5):
419
- outcomponents[idx] = wptype(2) * mat5[i, j]
420
- idx = idx + 1
421
-
422
- kernel = getkernel(check_mat_negation, suffix=dtype.__name__)
423
-
424
- if register_kernels:
425
- return
426
-
427
- m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
428
- m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
429
- m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
430
- m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
431
- outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
432
-
433
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
434
-
435
- assert_np_equal(outcomponents.numpy()[:4], -2 * m2.numpy().reshape(-1), tol=tol)
436
- assert_np_equal(outcomponents.numpy()[4:13], -2 * m3.numpy().reshape(-1), tol=tol)
437
- assert_np_equal(outcomponents.numpy()[13:29], -2 * m4.numpy().reshape(-1), tol=tol)
438
- assert_np_equal(outcomponents.numpy()[29:54], -2 * m5.numpy().reshape(-1), tol=tol)
439
-
440
- if dtype in np_float_types:
441
- idx = 0
442
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
443
- for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
444
- for i in range(dim):
445
- for j in range(dim):
446
- tape = wp.Tape()
447
- with tape:
448
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
449
- wp.launch(
450
- output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
451
- )
452
- tape.backward(loss=out)
453
- expectedresult = np.zeros((dim, dim), dtype=dtype)
454
- expectedresult[i, j] = -2
455
- assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
456
- tape.zero()
457
- idx = idx + 1
458
-
459
-
460
- def test_subtraction(test, device, dtype, register_kernels=False):
461
- rng = np.random.default_rng(123)
462
-
463
- tol = {
464
- np.float16: 5.0e-3,
465
- np.float32: 1.0e-6,
466
- np.float64: 1.0e-8,
467
- }.get(dtype, 0)
468
-
469
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
470
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
471
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
472
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
473
- mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
474
-
475
- output_select_kernel = get_select_kernel(wptype)
476
-
477
- def check_mat_sub(
478
- s2: wp.array(dtype=mat22),
479
- s3: wp.array(dtype=mat33),
480
- s4: wp.array(dtype=mat44),
481
- s5: wp.array(dtype=mat55),
482
- v2: wp.array(dtype=mat22),
483
- v3: wp.array(dtype=mat33),
484
- v4: wp.array(dtype=mat44),
485
- v5: wp.array(dtype=mat55),
486
- outcomponents: wp.array(dtype=wptype),
487
- ):
488
- v2result = v2[0] - s2[0]
489
- v3result = v3[0] - s3[0]
490
- v4result = v4[0] - s4[0]
491
- v5result = v5[0] - s5[0]
492
-
493
- # multiply outputs by 2 so we've got something to backpropagate:
494
- idx = 0
495
- for i in range(2):
496
- for j in range(2):
497
- outcomponents[idx] = wptype(2) * v2result[i, j]
498
- idx = idx + 1
499
-
500
- for i in range(3):
501
- for j in range(3):
502
- outcomponents[idx] = wptype(2) * v3result[i, j]
503
- idx = idx + 1
504
-
505
- for i in range(4):
506
- for j in range(4):
507
- outcomponents[idx] = wptype(2) * v4result[i, j]
508
- idx = idx + 1
509
-
510
- for i in range(5):
511
- for j in range(5):
512
- outcomponents[idx] = wptype(2) * v5result[i, j]
513
- idx = idx + 1
514
-
515
- kernel = getkernel(check_mat_sub, suffix=dtype.__name__)
516
-
517
- if register_kernels:
518
- return
519
-
520
- s2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
521
- s3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
522
- s4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
523
- s5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
524
- v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
525
- v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
526
- v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
527
- v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
528
- outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
529
-
530
- wp.launch(
531
- kernel,
532
- dim=1,
533
- inputs=[
534
- s2,
535
- s3,
536
- s4,
537
- s5,
538
- v2,
539
- v3,
540
- v4,
541
- v5,
542
- ],
543
- outputs=[outcomponents],
544
- device=device,
545
- )
546
-
547
- assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() - s2.numpy()).reshape(-1), tol=tol)
548
- assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() - s3.numpy()).reshape(-1), tol=tol)
549
- assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() - s4.numpy()).reshape(-1), tol=tol)
550
- assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() - s5.numpy()).reshape(-1), tol=10 * tol)
551
-
552
- if dtype in np_float_types:
553
- idx = 0
554
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
555
- for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
556
- for i in range(dim):
557
- for j in range(dim):
558
- tape = wp.Tape()
559
- with tape:
560
- wp.launch(
561
- kernel,
562
- dim=1,
563
- inputs=[
564
- s2,
565
- s3,
566
- s4,
567
- s5,
568
- v2,
569
- v3,
570
- v4,
571
- v5,
572
- ],
573
- outputs=[outcomponents],
574
- device=device,
575
- )
576
- wp.launch(
577
- output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
578
- )
579
- tape.backward(loss=out)
580
- expectedresult = np.zeros((dim, dim), dtype=dtype)
581
- expectedresult[i, j] = 2
582
- assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=10 * tol)
583
- expectedresult[i, j] = -2
584
- assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=10 * tol)
585
- tape.zero()
586
-
587
- idx = idx + 1
588
-
589
-
590
- def test_determinant(test, device, dtype, register_kernels=False):
591
- rng = np.random.default_rng(123)
592
-
593
- tol = {
594
- np.float16: 5.0e-3,
595
- np.float32: 1.0e-6,
596
- np.float64: 1.0e-8,
597
- }.get(dtype, 0)
598
-
599
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
600
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
601
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
602
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
603
-
604
- def check_mat_det(
605
- v2: wp.array(dtype=mat22),
606
- v3: wp.array(dtype=mat33),
607
- v4: wp.array(dtype=mat44),
608
- det2: wp.array(dtype=wptype),
609
- det3: wp.array(dtype=wptype),
610
- det4: wp.array(dtype=wptype),
611
- ):
612
- # multiply outputs by 2 so we've got something to backpropagate:
613
- det2[0] = wptype(2) * wp.determinant(v2[0])
614
- det3[0] = wptype(2) * wp.determinant(v3[0])
615
- det4[0] = wptype(2) * wp.determinant(v4[0])
616
-
617
- kernel = getkernel(check_mat_det, suffix=dtype.__name__)
618
- if register_kernels:
619
- return
620
-
621
- v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
622
- v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
623
- v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
624
- det2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
625
- det3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
626
- det4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
627
-
628
- tape = wp.Tape()
629
- with tape:
630
- wp.launch(
631
- kernel,
632
- dim=1,
633
- inputs=[
634
- v2,
635
- v3,
636
- v4,
637
- ],
638
- outputs=[
639
- det2,
640
- det3,
641
- det4,
642
- ],
643
- device=device,
644
- )
645
-
646
- if dtype in np_float_types:
647
- assert_np_equal(det2.numpy()[0], 2 * np.linalg.det(v2.numpy()[0].astype(np.float64)), tol=100 * tol)
648
- assert_np_equal(det3.numpy()[0], 2 * np.linalg.det(v3.numpy()[0].astype(np.float64)), tol=100 * tol)
649
- assert_np_equal(det4.numpy()[0], 2 * np.linalg.det(v4.numpy()[0].astype(np.float64)), tol=420 * tol)
650
- else:
651
- assert_np_equal(det2.numpy()[0], 2 * np.around(np.linalg.det(v2.numpy()[0])).astype(int))
652
- assert_np_equal(det3.numpy()[0], 2 * np.around(np.linalg.det(v3.numpy()[0])).astype(int))
653
- assert_np_equal(det4.numpy()[0], 2 * np.around(np.linalg.det(v4.numpy()[0])).astype(int))
654
-
655
- if dtype in np_float_types:
656
- # determinant derivative formula is annoying so finite differences?
657
- tape.backward(loss=det2)
658
- v2grads = 1.0 * tape.gradients[v2].numpy()[0]
659
- tape.zero()
660
-
661
- tape.backward(loss=det3)
662
- v3grads = 1.0 * tape.gradients[v3].numpy()[0]
663
- tape.zero()
664
-
665
- tape.backward(loss=det4)
666
- v4grads = 1.0 * tape.gradients[v4].numpy()[0]
667
- tape.zero()
668
-
669
- # finite differences are also annoying hence the large tolerance...
670
- # absolute nightmare in float16 too innit...
671
- dx = 0.01 if dtype == np.float16 else 0.0001
672
- fdtol = 2.0e-1 if dtype == np.float16 else 2.0e-3
673
- for i in range(2):
674
- for j in range(2):
675
- v2test = v2.numpy()
676
- v2test[0, i, j] += dx
677
- wp.launch(
678
- kernel,
679
- dim=1,
680
- inputs=[
681
- wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
682
- v3,
683
- v4,
684
- ],
685
- outputs=[
686
- det2,
687
- det3,
688
- det4,
689
- ],
690
- device=device,
691
- )
692
- dplus = det2.numpy()[0]
693
- v2test[0, i, j] -= 2.0 * dx
694
- wp.launch(
695
- kernel,
696
- dim=1,
697
- inputs=[
698
- wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
699
- v3,
700
- v4,
701
- ],
702
- outputs=[
703
- det2,
704
- det3,
705
- det4,
706
- ],
707
- device=device,
708
- )
709
- dminus = det2.numpy()[0]
710
- assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v2grads[i, j] / dplus, tol=fdtol)
711
-
712
- for i in range(3):
713
- for j in range(3):
714
- v3test = v3.numpy()
715
- v3test[0, i, j] += dx
716
- wp.launch(
717
- kernel,
718
- dim=1,
719
- inputs=[
720
- v2,
721
- wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
722
- v4,
723
- ],
724
- outputs=[
725
- det2,
726
- det3,
727
- det4,
728
- ],
729
- device=device,
730
- )
731
- dplus = det3.numpy()[0]
732
- v3test[0, i, j] -= 2.0 * dx
733
- wp.launch(
734
- kernel,
735
- dim=1,
736
- inputs=[
737
- v2,
738
- wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
739
- v4,
740
- ],
741
- outputs=[
742
- det2,
743
- det3,
744
- det4,
745
- ],
746
- device=device,
747
- )
748
- dminus = det3.numpy()[0]
749
- assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v3grads[i, j] / dplus, tol=fdtol)
750
-
751
- for i in range(4):
752
- for j in range(4):
753
- v4test = v4.numpy()
754
- v4test[0, i, j] += dx
755
- wp.launch(
756
- kernel,
757
- dim=1,
758
- inputs=[
759
- v2,
760
- v3,
761
- wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
762
- ],
763
- outputs=[
764
- det2,
765
- det3,
766
- det4,
767
- ],
768
- device=device,
769
- )
770
- dplus = det4.numpy()[0]
771
- v4test[0, i, j] -= 2.0 * dx
772
- wp.launch(
773
- kernel,
774
- dim=1,
775
- inputs=[
776
- v2,
777
- v3,
778
- wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
779
- ],
780
- outputs=[
781
- det2,
782
- det3,
783
- det4,
784
- ],
785
- device=device,
786
- )
787
- dminus = det4.numpy()[0]
788
- assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v4grads[i, j] / dplus, tol=fdtol)
789
-
790
-
791
- # Unused. Why?
792
- # def test_get_diag(test, device, dtype, register_kernels=False):
793
- # tol = {
794
- # np.float16: 1.0e-3,
795
- # np.float32: 1.0e-6,
796
- # np.float64: 1.0e-8,
797
- # }.get(dtype, 0)
798
- #
799
- # wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
800
- # mat55 = wp.types.vector(shape=(5, 5), dtype=wptype)
801
- #
802
- # output_select_kernel = get_select_kernel(wptype)
803
- #
804
- # def check_mat_diag(
805
- # m55: wp.array(dtype=mat55),
806
- # outcomponents: wp.array(dtype=wptype),
807
- # ):
808
- # # multiply outputs by 2 so we've got something to backpropagate:
809
- # vec5result = wptype(2) * wp.get_diag(m55[0])
810
- #
811
- # idx = 0
812
- # for i in range(5):
813
- # outcomponents[idx] = vec5result[i]
814
- # idx = idx + 1
815
- #
816
- # kernel = getkernel(check_mat_diag, suffix=dtype.__name__)
817
- #
818
- # if register_kernels:
819
- # return
820
- #
821
- # m55 = wp.array(randvals((1, 5, 5), dtype), dtype=mat55, requires_grad=True, device=device)
822
- # outcomponents = wp.zeros(5, dtype=wptype, requires_grad=True, device=device)
823
- # out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
824
- #
825
- # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
826
- #
827
- # assert_np_equal(outcomponents.numpy(), 2 * np.diag(m55.numpy()[0]), tol=tol)
828
- #
829
- # if dtype in np_float_types:
830
- # idx = 0
831
- # for i in range(5):
832
- # tape = wp.Tape()
833
- # with tape:
834
- # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
835
- # wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
836
- # tape.backward(loss=out)
837
- # expectedresult = np.zeros((5, 5), dtype=dtype)
838
- # expectedresult[i, i] = 2
839
- # assert_np_equal(tape.gradients[m55].numpy()[0], expectedresult, tol=10 * tol)
840
- # tape.zero()
841
- #
842
- # idx = idx + 1
843
-
844
-
845
- def test_inverse(test, device, dtype, register_kernels=False):
846
- rng = np.random.default_rng(123)
847
-
848
- tol = {
849
- np.float16: 5.0e-2,
850
- np.float32: 1.0e-5,
851
- np.float64: 1.0e-8,
852
- }.get(dtype, 0)
853
-
854
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
855
- mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
856
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
857
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
858
-
859
- output_select_kernel = get_select_kernel(wptype)
860
-
861
- def check_mat_inverse(
862
- m2: wp.array(dtype=mat22),
863
- m3: wp.array(dtype=mat33),
864
- m4: wp.array(dtype=mat44),
865
- outcomponents: wp.array(dtype=wptype),
866
- ):
867
- m2result = wp.inverse(m2[0])
868
- m3result = wp.inverse(m3[0])
869
- m4result = wp.inverse(m4[0])
870
-
871
- # multiply outputs by 2 so we've got something to backpropagate:
872
- idx = 0
873
- for i in range(2):
874
- for j in range(2):
875
- outcomponents[idx] = wptype(2) * m2result[i, j]
876
- idx = idx + 1
877
-
878
- for i in range(3):
879
- for j in range(3):
880
- outcomponents[idx] = wptype(2) * m3result[i, j]
881
- idx = idx + 1
882
-
883
- for i in range(4):
884
- for j in range(4):
885
- outcomponents[idx] = wptype(2) * m4result[i, j]
886
- idx = idx + 1
887
-
888
- kernel = getkernel(check_mat_inverse, suffix=dtype.__name__)
889
-
890
- if register_kernels:
891
- return
892
-
893
- m2 = wp.array(
894
- 2 * (randvals(rng, [1, 2, 2], dtype) + 0.2 * np.eye(2)), dtype=mat22, requires_grad=True, device=device
895
- )
896
- m3 = wp.array(
897
- 2 * (randvals(rng, [1, 3, 3], dtype) + 0.2 * np.eye(3)), dtype=mat33, requires_grad=True, device=device
898
- )
899
- m4 = wp.array(
900
- 2 * (randvals(rng, [1, 4, 4], dtype) + 0.2 * np.eye(4)), dtype=mat44, requires_grad=True, device=device
901
- )
902
-
903
- outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4, dtype=wptype, requires_grad=True, device=device)
904
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
905
-
906
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
907
-
908
- assert_np_equal(outcomponents.numpy()[:4], 2 * np.linalg.inv(m2.numpy()[0].astype(np.float64)), tol=tol)
909
- assert_np_equal(outcomponents.numpy()[4:13], 2 * np.linalg.inv(m3.numpy()[0].astype(np.float64)), tol=5 * tol)
910
- assert_np_equal(outcomponents.numpy()[13:], 2 * np.linalg.inv(m4.numpy()[0].astype(np.float64)), tol=5 * tol)
911
-
912
- if dtype in np_float_types:
913
- # check gradients:
914
- idx = 0
915
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
916
- for dim, input in [(2, m2), (3, m3), (4, m4)]:
917
- minv = np.linalg.inv(input.numpy()[0].astype(np.float64))
918
- for i in range(dim):
919
- for j in range(dim):
920
- tape = wp.Tape()
921
- with tape:
922
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
923
- wp.launch(
924
- output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
925
- )
926
- tape.backward(loss=out)
927
- d = np.zeros((dim, dim))
928
- d[j, i] = 2
929
- assert_np_equal(
930
- tape.gradients[input].numpy()[0], -np.matmul(minv, np.matmul(d, minv)).T, tol=10 * tol
931
- )
932
- tape.zero()
933
-
934
- idx = idx + 1
935
-
936
- # let's check 2x2 using different formulae just for (in)sanity's sake:
937
- m = m2.numpy()[0]
938
-
939
- det = m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]
940
- expected = 2 * np.array([[m[1, 1], -m[0, 1]], [-m[1, 0], m[0, 0]]], dtype=dtype) / det
941
- assert_np_equal(expected, outcomponents.numpy()[:4], tol=tol)
942
-
943
- # 0,0 component is this:
944
- # 2 * m[1,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
945
- assert_np_equal(2 * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[0], tol=tol)
946
-
947
- tape = wp.Tape()
948
- with tape:
949
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
950
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 0], outputs=[out], device=device)
951
-
952
- if dtype in np_float_types:
953
- tape.backward(loss=out)
954
- g = tape.gradients[m2].numpy()[0]
955
- assert_np_equal(-2 * m[1, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
956
- assert_np_equal(2 * m[1, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
957
- assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
958
- assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
959
- tape.zero()
960
-
961
- # 0,1 component is this:
962
- # -2 * m[0,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
963
- assert_np_equal(-2 * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[1], tol=tol)
964
-
965
- tape = wp.Tape()
966
- with tape:
967
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
968
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 1], outputs=[out], device=device)
969
- if dtype in np_float_types:
970
- tape.backward(loss=out)
971
- g = tape.gradients[m2].numpy()[0]
972
- assert_np_equal(2 * m[0, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
973
- assert_np_equal(-2 * m[0, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
974
- assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
975
- assert_np_equal(-2 * m[1, 1] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
976
- tape.zero()
977
-
978
- # 1,0 component is this:
979
- # -2 * m[1,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
980
- assert_np_equal(-2 * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[2], tol=tol)
981
-
982
- tape = wp.Tape()
983
- with tape:
984
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
985
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 2], outputs=[out], device=device)
986
-
987
- if dtype in np_float_types:
988
- tape.backward(loss=out)
989
- g = tape.gradients[m2].numpy()[0]
990
- assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
991
- assert_np_equal(-2 * m[0, 0] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
992
- assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
993
- assert_np_equal(-2 * m[1, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
994
- tape.zero()
995
-
996
- # 1,1 component is this:
997
- # 2 * m[0,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
998
- assert_np_equal(2 * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[3], tol=tol)
999
-
1000
- tape = wp.Tape()
1001
- with tape:
1002
- wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
1003
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 3], outputs=[out], device=device)
1004
-
1005
- if dtype in np_float_types:
1006
- tape.backward(loss=out)
1007
- g = tape.gradients[m2].numpy()[0]
1008
- assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
1009
- assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
1010
- assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
1011
- assert_np_equal(-2 * m[0, 0] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
1012
- tape.zero()
1013
-
1014
-
1015
- def test_svd(test, device, dtype, register_kernels=False):
1016
- rng = np.random.default_rng(123)
1017
-
1018
- tol = {
1019
- np.float16: 1.0e-3,
1020
- np.float32: 1.0e-6,
1021
- np.float64: 1.0e-6,
1022
- }.get(dtype, 0)
1023
-
1024
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1025
- vec3 = wp.types.vector(length=3, dtype=wptype)
1026
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1027
-
1028
- def check_mat_svd(
1029
- m3: wp.array(dtype=mat33),
1030
- Uout: wp.array(dtype=mat33),
1031
- sigmaout: wp.array(dtype=vec3),
1032
- Vout: wp.array(dtype=mat33),
1033
- outcomponents: wp.array(dtype=wptype),
1034
- ):
1035
- U = mat33()
1036
- sigma = vec3()
1037
- V = mat33()
1038
-
1039
- wp.svd3(m3[0], U, sigma, V)
1040
-
1041
- Uout[0] = U
1042
- sigmaout[0] = sigma
1043
- Vout[0] = V
1044
-
1045
- # multiply outputs by 2 so we've got something to backpropagate:
1046
- idx = 0
1047
- for i in range(3):
1048
- for j in range(3):
1049
- outcomponents[idx] = wptype(2) * U[i, j]
1050
- idx = idx + 1
1051
-
1052
- for i in range(3):
1053
- outcomponents[idx] = wptype(2) * sigma[i]
1054
- idx = idx + 1
1055
-
1056
- for i in range(3):
1057
- for j in range(3):
1058
- outcomponents[idx] = wptype(2) * V[i, j]
1059
- idx = idx + 1
1060
-
1061
- kernel = getkernel(check_mat_svd, suffix=dtype.__name__)
1062
-
1063
- output_select_kernel = get_select_kernel(wptype)
1064
-
1065
- if register_kernels:
1066
- return
1067
-
1068
- m3 = wp.array(randvals(rng, [1, 3, 3], dtype) + np.eye(3), dtype=mat33, requires_grad=True, device=device)
1069
-
1070
- outcomponents = wp.zeros(2 * 3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1071
- Uout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1072
- sigmaout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1073
- Vout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1074
-
1075
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1076
-
1077
- Uout_np = Uout.numpy()[0].astype(np.float64)
1078
- sigmaout_np = np.diag(sigmaout.numpy()[0].astype(np.float64))
1079
- Vout_np = Vout.numpy()[0].astype(np.float64)
1080
-
1081
- assert_np_equal(
1082
- np.matmul(Uout_np, np.matmul(sigmaout_np, Vout_np.T)), m3.numpy()[0].astype(np.float64), tol=30 * tol
1083
- )
1084
-
1085
- if dtype == np.float16:
1086
- # I'm not even going to bother testing the gradients for float16
1087
- # because the rounding errors are terrible...
1088
- return
1089
-
1090
- # check gradients:
1091
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1092
- idx = 0
1093
- for idx in range(3 * 3 + 3 + 3 * 3):
1094
- tape = wp.Tape()
1095
- with tape:
1096
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1097
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1098
- tape.backward(out)
1099
- m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1100
-
1101
- tape.zero()
1102
-
1103
- dx = 0.0001
1104
- fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1105
- for ii in range(3):
1106
- for jj in range(3):
1107
- m3test = 1.0 * m3.numpy()
1108
- m3test[0, ii, jj] += dx
1109
- wp.launch(
1110
- kernel,
1111
- dim=1,
1112
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1113
- outputs=[Uout, sigmaout, Vout, outcomponents],
1114
- device=device,
1115
- )
1116
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1117
- plusval = out.numpy()[0]
1118
-
1119
- m3test = 1.0 * m3.numpy()
1120
- m3test[0, ii, jj] -= dx
1121
- wp.launch(
1122
- kernel,
1123
- dim=1,
1124
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1125
- outputs=[Uout, sigmaout, Vout, outcomponents],
1126
- device=device,
1127
- )
1128
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1129
- minusval = out.numpy()[0]
1130
-
1131
- assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1132
-
1133
-
1134
- def test_qr(test, device, dtype, register_kernels=False):
1135
- rng = np.random.default_rng(123)
1136
-
1137
- tol = {
1138
- np.float16: 2.0e-3,
1139
- np.float32: 1.0e-6,
1140
- np.float64: 1.0e-6,
1141
- }.get(dtype, 0)
1142
-
1143
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1144
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1145
-
1146
- def check_mat_qr(
1147
- m3: wp.array(dtype=mat33),
1148
- Qout: wp.array(dtype=mat33),
1149
- Rout: wp.array(dtype=mat33),
1150
- outcomponents: wp.array(dtype=wptype),
1151
- ):
1152
- Q = mat33()
1153
- R = mat33()
1154
-
1155
- wp.qr3(m3[0], Q, R)
1156
-
1157
- Qout[0] = Q
1158
- Rout[0] = R
1159
-
1160
- # multiply outputs by 2 so we've got something to backpropagate:
1161
- idx = 0
1162
- for i in range(3):
1163
- for j in range(3):
1164
- outcomponents[idx] = wptype(2) * Q[i, j]
1165
- idx = idx + 1
1166
-
1167
- for i in range(3):
1168
- for j in range(3):
1169
- outcomponents[idx] = wptype(2) * R[i, j]
1170
- idx = idx + 1
1171
-
1172
- kernel = getkernel(check_mat_qr, suffix=dtype.__name__)
1173
- output_select_kernel = get_select_kernel(wptype)
1174
-
1175
- if register_kernels:
1176
- return
1177
-
1178
- m3 = wp.array(0.5 * (randvals(rng, [1, 3, 3], dtype) + np.eye(3)), dtype=mat33, requires_grad=True, device=device)
1179
-
1180
- outcomponents = wp.zeros(2 * 3 * 3, dtype=wptype, requires_grad=True, device=device)
1181
- Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1182
- Rout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1183
-
1184
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1185
-
1186
- Qout_np = Qout.numpy()[0].astype(np.float64)
1187
- Rout_np = Rout.numpy()[0].astype(np.float64)
1188
-
1189
- # check it's actually a q and an r:
1190
- assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3, dtype=np.float64), tol=tol)
1191
- assert_np_equal(Rout_np[1, [0]], np.zeros(1, dtype=np.float64), tol=tol)
1192
- assert_np_equal(Rout_np[2, [0, 1]], np.zeros(2, dtype=np.float64), tol=tol)
1193
-
1194
- # check it's a factorization:
1195
- assert_np_equal(np.matmul(Qout_np, Rout_np), m3.numpy()[0].astype(np.float64), tol=30 * tol)
1196
-
1197
- if dtype == np.float16:
1198
- # I'm not even going to bother testing the gradients for float16
1199
- # because the rounding errors are terrible...
1200
- return
1201
-
1202
- # check gradients:
1203
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1204
- idx = 0
1205
- for idx in range(len(outcomponents)):
1206
- tape = wp.Tape()
1207
- with tape:
1208
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1209
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1210
- tape.backward(out)
1211
- m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1212
-
1213
- tape.zero()
1214
-
1215
- dx = 0.0001
1216
- fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1217
- for ii in range(3):
1218
- for jj in range(3):
1219
- m3test = 1.0 * m3.numpy()
1220
- m3test[0, ii, jj] += dx
1221
- wp.launch(
1222
- kernel,
1223
- dim=1,
1224
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1225
- outputs=[Qout, Rout, outcomponents],
1226
- device=device,
1227
- )
1228
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1229
- plusval = out.numpy()[0]
1230
-
1231
- m3test = 1.0 * m3.numpy()
1232
- m3test[0, ii, jj] -= dx
1233
- wp.launch(
1234
- kernel,
1235
- dim=1,
1236
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1237
- outputs=[Qout, Rout, outcomponents],
1238
- device=device,
1239
- )
1240
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1241
- minusval = out.numpy()[0]
1242
-
1243
- assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1244
-
1245
-
1246
- def test_eig(test, device, dtype, register_kernels=False):
1247
- rng = np.random.default_rng(123)
1248
-
1249
- tol = {
1250
- np.float16: 4.0e-2,
1251
- np.float32: 1.0e-5,
1252
- np.float64: 1.0e-5,
1253
- }.get(dtype, 0)
1254
-
1255
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1256
- vec3 = wp.types.vector(length=3, dtype=wptype)
1257
- mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1258
-
1259
- def check_mat_eig(
1260
- m3: wp.array(dtype=mat33),
1261
- Qout: wp.array(dtype=mat33),
1262
- dout: wp.array(dtype=vec3),
1263
- outcomponents: wp.array(dtype=wptype),
1264
- ):
1265
- Q = mat33()
1266
- d = vec3()
1267
-
1268
- wp.eig3(m3[0] + wp.transpose(m3[0]), Q, d)
1269
-
1270
- Qout[0] = Q
1271
- dout[0] = d
1272
-
1273
- # multiply outputs by 2 so we've got something to backpropagate:
1274
- idx = 0
1275
- for i in range(3):
1276
- for j in range(3):
1277
- outcomponents[idx] = wptype(2) * Q[i, j]
1278
- idx = idx + 1
1279
-
1280
- for i in range(3):
1281
- outcomponents[idx] = wptype(2) * d[i]
1282
- idx = idx + 1
1283
-
1284
- kernel = getkernel(check_mat_eig, suffix=dtype.__name__)
1285
- output_select_kernel = get_select_kernel(wptype)
1286
-
1287
- if register_kernels:
1288
- return
1289
-
1290
- m3_np = randvals(rng, [1, 3, 3], dtype) + np.eye(3, dtype=dtype)
1291
- m3 = wp.array(m3_np, dtype=mat33, requires_grad=True, device=device)
1292
-
1293
- outcomponents = wp.zeros(3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1294
- Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1295
- dout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1296
-
1297
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1298
-
1299
- Qout_np = Qout.numpy()[0].astype(np.float64)
1300
- dout_np = dout.numpy()[0].astype(np.float64)
1301
- Dout_np = np.diag(dout_np)
1302
-
1303
- # check Q is orthogonal:
1304
- assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3), tol=tol)
1305
-
1306
- # check Q contains eigenvectors:
1307
- assert_np_equal(np.matmul(Qout_np, np.matmul(Dout_np, Qout_np.T)), (m3_np[0] + m3_np[0].transpose()), tol=tol)
1308
-
1309
- if dtype == np.float16:
1310
- # I'm not even going to bother testing the gradients for float16
1311
- # because the rounding errors are terrible...
1312
- return
1313
-
1314
- # check gradients:
1315
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1316
- idx = 0
1317
- for idx in range(len(outcomponents)):
1318
- tape = wp.Tape()
1319
- with tape:
1320
- wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1321
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1322
- tape.backward(out)
1323
- m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1324
-
1325
- tape.zero()
1326
-
1327
- dx = 0.0001
1328
- fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1329
- for ii in range(3):
1330
- for jj in range(3):
1331
- m3test = 1.0 * m3.numpy()
1332
- m3test[0, ii, jj] += dx
1333
- wp.launch(
1334
- kernel,
1335
- dim=1,
1336
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1337
- outputs=[Qout, dout, outcomponents],
1338
- device=device,
1339
- )
1340
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1341
- plusval = out.numpy()[0]
1342
-
1343
- m3test = 1.0 * m3.numpy()
1344
- m3test[0, ii, jj] -= dx
1345
- wp.launch(
1346
- kernel,
1347
- dim=1,
1348
- inputs=[wp.array(m3test, dtype=mat33, device=device)],
1349
- outputs=[Qout, dout, outcomponents],
1350
- device=device,
1351
- )
1352
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1353
- minusval = out.numpy()[0]
1354
-
1355
- assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1356
-
1357
-
1358
- def test_skew(test, device, dtype, register_kernels=False):
1359
- rng = np.random.default_rng(123)
1360
-
1361
- tol = {
1362
- np.float16: 1.0e-3,
1363
- np.float32: 1.0e-6,
1364
- np.float64: 1.0e-8,
1365
- }.get(dtype, 0)
1366
-
1367
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1368
- vec3 = wp.types.vector(length=3, dtype=wptype)
1369
-
1370
- output_select_kernel = get_select_kernel(wptype)
1371
-
1372
- def check_mat_skew(
1373
- v3: wp.array(dtype=vec3),
1374
- outcomponents: wp.array(dtype=wptype),
1375
- ):
1376
- m3result = wp.skew(v3[0])
1377
-
1378
- # multiply outputs by 2 so we've got something to backpropagate:
1379
- idx = 0
1380
- for i in range(3):
1381
- for j in range(3):
1382
- outcomponents[idx] = wptype(2) * m3result[i, j]
1383
- idx = idx + 1
1384
-
1385
- kernel = getkernel(check_mat_skew, suffix=dtype.__name__)
1386
-
1387
- if register_kernels:
1388
- return
1389
-
1390
- v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1391
-
1392
- outcomponents = wp.zeros(3 * 3, dtype=wptype, requires_grad=True, device=device)
1393
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1394
-
1395
- wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1396
-
1397
- # make sure it gives you a cross product matrix:
1398
- crossprodmat = outcomponents.numpy().reshape(3, 3)
1399
- v = np.array([1, 0, 0])
1400
- assert_np_equal(
1401
- np.matmul(crossprodmat, np.array([1, 0, 0])).reshape(-1),
1402
- 2 * np.cross(v3.numpy()[0], np.array([1, 0, 0])),
1403
- tol=tol,
1404
- )
1405
- assert_np_equal(
1406
- np.matmul(crossprodmat, np.array([0, 1, 0])).reshape(-1),
1407
- 2 * np.cross(v3.numpy()[0], np.array([0, 1, 0])),
1408
- tol=tol,
1409
- )
1410
- assert_np_equal(
1411
- np.matmul(crossprodmat, np.array([0, 0, 1])).reshape(-1),
1412
- 2 * np.cross(v3.numpy()[0], np.array([0, 0, 1])),
1413
- tol=tol,
1414
- )
1415
-
1416
- # check it another way:
1417
- x0 = v3.numpy()[0, 0]
1418
- x1 = v3.numpy()[0, 1]
1419
- x2 = v3.numpy()[0, 2]
1420
- crossprodmat_expected = np.array(
1421
- [
1422
- [0, -x2, x1],
1423
- [x2, 0, -x0],
1424
- [-x1, x0, 0],
1425
- ],
1426
- dtype=dtype,
1427
- )
1428
- assert_np_equal(crossprodmat, 2 * crossprodmat_expected, tol=tol)
1429
-
1430
- if dtype in np_float_types:
1431
- idx = 0
1432
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1433
-
1434
- for i in range(3):
1435
- for j in range(3):
1436
- tape = wp.Tape()
1437
- with tape:
1438
- wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1439
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1440
- tape.backward(loss=out)
1441
- if i == j:
1442
- assert_np_equal(tape.gradients[v3].numpy()[0], np.zeros(3))
1443
- elif [i, j] == [0, 1]:
1444
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, -2]))
1445
- elif [i, j] == [1, 0]:
1446
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, 2]))
1447
- elif [i, j] == [0, 2]:
1448
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 2, 0]))
1449
- elif [i, j] == [2, 0]:
1450
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, -2, 0]))
1451
- elif [i, j] == [1, 2]:
1452
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([-2, 0, 0]))
1453
- elif [i, j] == [2, 1]:
1454
- assert_np_equal(tape.gradients[v3].numpy()[0], np.array([2, 0, 0]))
1455
- tape.zero()
1456
-
1457
- idx = idx + 1
1458
-
1459
-
1460
- def test_transform_point(test, device, dtype, register_kernels=False):
1461
- rng = np.random.default_rng(123)
1462
-
1463
- tol = {
1464
- np.float16: 5.0e-3,
1465
- np.float32: 1.0e-6,
1466
- np.float64: 1.0e-8,
1467
- }.get(dtype, 0)
1468
-
1469
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1470
- vec3 = wp.types.vector(length=3, dtype=wptype)
1471
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1472
-
1473
- output_select_kernel = get_select_kernel(wptype)
1474
-
1475
- def check_mat_transform_point(
1476
- v3: wp.array(dtype=vec3),
1477
- m4: wp.array(dtype=mat44),
1478
- outcomponents: wp.array(dtype=wptype),
1479
- ):
1480
- # multiply outputs by 2 so we've got something to backpropagate:
1481
- presult = wptype(2) * wp.transform_point(m4[0], v3[0])
1482
-
1483
- outcomponents[0] = presult[0]
1484
- outcomponents[1] = presult[1]
1485
- outcomponents[2] = presult[2]
1486
-
1487
- kernel = getkernel(check_mat_transform_point, suffix=dtype.__name__)
1488
-
1489
- if register_kernels:
1490
- return
1491
-
1492
- v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1493
- m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1494
-
1495
- outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1496
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1497
-
1498
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1499
-
1500
- v3homog = np.ones(4, dtype=dtype)
1501
- v3homog[:3] = v3.numpy()[0]
1502
- assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1503
-
1504
- if dtype in np_float_types:
1505
- for j in range(3):
1506
- tape = wp.Tape()
1507
- with tape:
1508
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1509
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1510
- tape.backward(loss=out)
1511
-
1512
- assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1513
- expected = np.zeros((4, 4), dtype=dtype)
1514
- expected[j, :3] = 2 * v3.numpy()
1515
- expected[j, 3] = 2
1516
- assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1517
-
1518
- tape.zero()
1519
-
1520
-
1521
- def test_transform_vector(test, device, dtype, register_kernels=False):
1522
- rng = np.random.default_rng(123)
1523
-
1524
- tol = {
1525
- np.float16: 5.0e-3,
1526
- np.float32: 1.0e-6,
1527
- np.float64: 1.0e-8,
1528
- }.get(dtype, 0)
1529
-
1530
- wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1531
- vec3 = wp.types.vector(length=3, dtype=wptype)
1532
- mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1533
-
1534
- output_select_kernel = get_select_kernel(wptype)
1535
-
1536
- def check_mat_transform_vector(
1537
- v3: wp.array(dtype=vec3),
1538
- m4: wp.array(dtype=mat44),
1539
- outcomponents: wp.array(dtype=wptype),
1540
- ):
1541
- # multiply outputs by 2 so we've got something to backpropagate:
1542
- presult = wptype(2) * wp.transform_vector(m4[0], v3[0])
1543
-
1544
- outcomponents[0] = presult[0]
1545
- outcomponents[1] = presult[1]
1546
- outcomponents[2] = presult[2]
1547
-
1548
- kernel = getkernel(check_mat_transform_vector, suffix=dtype.__name__)
1549
-
1550
- if register_kernels:
1551
- return
1552
-
1553
- v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1554
- m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1555
-
1556
- outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1557
- out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1558
-
1559
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1560
-
1561
- v3homog = np.zeros(4, dtype=dtype)
1562
- v3homog[:3] = v3.numpy()[0]
1563
- assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1564
-
1565
- if dtype in np_float_types:
1566
- for j in range(3):
1567
- tape = wp.Tape()
1568
- with tape:
1569
- wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1570
- wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1571
- tape.backward(loss=out)
1572
-
1573
- assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1574
- expected = np.zeros((4, 4), dtype=dtype)
1575
- expected[j, :3] = 2 * v3.numpy()
1576
- assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1577
-
1578
- tape.zero()
1579
-
1580
-
1581
- # Test matrix constructors using explicit type (float16)
1582
- # note that these tests are specifically not using generics / closure
1583
- # args to create kernels dynamically (like the rest of this file)
1584
- # as those use different code paths to resolve arg types which
1585
- # has lead to regressions.
1586
- @wp.kernel
1587
- def test_constructors_explicit_precision():
1588
- # construction for custom matrix types
1589
- eye = wp.identity(dtype=wp.float16, n=2)
1590
- zeros = wp.matrix(shape=(2, 2), dtype=wp.float16)
1591
- custom = wp.matrix(wp.float16(0.0), wp.float16(1.0), wp.float16(2.0), wp.float16(3.0), shape=(2, 2))
1592
-
1593
- for i in range(2):
1594
- for j in range(2):
1595
- if i == j:
1596
- wp.expect_eq(eye[i, j], wp.float16(1.0))
1597
- else:
1598
- wp.expect_eq(eye[i, j], wp.float16(0.0))
1599
-
1600
- wp.expect_eq(zeros[i, j], wp.float16(0.0))
1601
- wp.expect_eq(custom[i, j], wp.float16(i) * wp.float16(2.0) + wp.float16(j))
1602
-
1603
-
1604
- mat32d = wp.mat(shape=(3, 2), dtype=wp.float64)
1605
-
1606
-
1607
- @wp.kernel
1608
- def test_matrix_constructor_value_func():
1609
- a = wp.mat22()
1610
- b = wp.matrix(a, shape=(2, 2))
1611
- c = mat32d()
1612
- d = mat32d(c, shape=(3, 2))
1613
- e = mat32d(wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0))
1614
- f = mat32d(
1615
- wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1616
- wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1617
- )
1618
-
1619
-
1620
- # Same as above but with a default (float/int) type
1621
- # which tests some different code paths that
1622
- # need to ensure types are correctly canonicalized
1623
- # during codegen
1624
- @wp.kernel
1625
- def test_constructors_default_precision():
1626
- # construction for default (float) matrix types
1627
- eye = wp.identity(dtype=float, n=2)
1628
- zeros = wp.matrix(shape=(2, 2), dtype=float)
1629
- custom = wp.matrix(0.0, 1.0, 2.0, 3.0, shape=(2, 2))
1630
-
1631
- for i in range(2):
1632
- for j in range(2):
1633
- if i == j:
1634
- wp.expect_eq(eye[i, j], 1.0)
1635
- else:
1636
- wp.expect_eq(eye[i, j], 0.0)
1637
-
1638
- wp.expect_eq(zeros[i, j], 0.0)
1639
- wp.expect_eq(custom[i, j], float(i) * 2.0 + float(j))
1640
-
1641
-
1642
- @wp.kernel
1643
- def test_matrix_mutation(expected: wp.types.matrix(shape=(10, 3), dtype=float)):
1644
- m = wp.matrix(shape=(10, 3), dtype=float)
1645
-
1646
- # test direct element indexing
1647
- m[0, 0] = 1.0
1648
- m[0, 1] = 2.0
1649
- m[0, 2] = 3.0
1650
-
1651
- # The nested indexing (matrix->vector->scalar) below does not
1652
- # currently modify m because m[0] returns row vector by
1653
- # value rather than reference, this is different from NumPy
1654
- # which always returns by ref. Not clear how we can support
1655
- # this as well as auto-diff.
1656
-
1657
- # m[0][1] = 2.0
1658
- # m[0][2] = 3.0
1659
-
1660
- # test setting rows
1661
- for i in range(1, 10):
1662
- m[i] = m[i - 1] + wp.vec3(1.0, 2.0, 3.0)
1663
-
1664
- wp.expect_eq(m, expected)
1665
-
1666
-
1667
- CONSTANT_SHAPE_ROWS = wp.constant(10)
1668
- CONSTANT_SHAPE_COLS = wp.constant(10)
1669
-
1670
-
1671
- # tests that we can use global constants in shape keyword argument
1672
- # for matrix constructor
1673
- @wp.kernel
1674
- def test_constructors_constant_shape():
1675
- m = wp.matrix(shape=(CONSTANT_SHAPE_ROWS, CONSTANT_SHAPE_COLS), dtype=float)
1676
-
1677
- for i in range(CONSTANT_SHAPE_ROWS):
1678
- for j in range(CONSTANT_SHAPE_COLS):
1679
- m[i, j] = float(i * j)
1680
-
1681
-
1682
- devices = get_test_devices()
1683
-
1684
-
1685
- class TestMat(unittest.TestCase):
1686
- pass
1687
-
1688
-
1689
- add_kernel_test(TestMat, test_constructors_explicit_precision, dim=1, devices=devices)
1690
- add_kernel_test(TestMat, test_constructors_default_precision, dim=1, devices=devices)
1691
- add_kernel_test(TestMat, test_constructors_constant_shape, dim=1, devices=devices)
1692
- add_kernel_test(TestMat, test_matrix_constructor_value_func, dim=1, devices=devices)
1693
-
1694
- mat103 = wp.types.matrix(shape=(10, 3), dtype=float)
1695
- add_kernel_test(
1696
- TestMat,
1697
- test_matrix_mutation,
1698
- dim=1,
1699
- inputs=[
1700
- mat103(
1701
- 1.0,
1702
- 2.0,
1703
- 3.0,
1704
- 2.0,
1705
- 4.0,
1706
- 6.0,
1707
- 3.0,
1708
- 6.0,
1709
- 9.0,
1710
- 4.0,
1711
- 8.0,
1712
- 12.0,
1713
- 5.0,
1714
- 10.0,
1715
- 15.0,
1716
- 6.0,
1717
- 12.0,
1718
- 18.0,
1719
- 7.0,
1720
- 14.0,
1721
- 21.0,
1722
- 8.0,
1723
- 16.0,
1724
- 24.0,
1725
- 9.0,
1726
- 18.0,
1727
- 27.0,
1728
- 10.0,
1729
- 20.0,
1730
- 30.0,
1731
- )
1732
- ],
1733
- devices=devices,
1734
- )
1735
-
1736
- for dtype in np_signed_int_types + np_float_types:
1737
- add_function_test_register_kernel(
1738
- TestMat, f"test_negation_{dtype.__name__}", test_negation, devices=devices, dtype=dtype
1739
- )
1740
- add_function_test_register_kernel(
1741
- TestMat, f"test_subtraction_{dtype.__name__}", test_subtraction, devices=devices, dtype=dtype
1742
- )
1743
-
1744
- add_function_test(
1745
- TestMat,
1746
- "test_anon_constructor_error_shape_keyword_missing",
1747
- test_anon_constructor_error_shape_keyword_missing,
1748
- devices=devices,
1749
- )
1750
- add_function_test(
1751
- TestMat,
1752
- "test_anon_constructor_error_dtype_keyword_missing",
1753
- test_anon_constructor_error_dtype_keyword_missing,
1754
- devices=devices,
1755
- )
1756
- add_function_test(
1757
- TestMat,
1758
- "test_anon_constructor_error_shape_mismatch",
1759
- test_anon_constructor_error_shape_mismatch,
1760
- devices=devices,
1761
- )
1762
- add_function_test(
1763
- TestMat,
1764
- "test_anon_constructor_error_invalid_arg_count",
1765
- test_anon_constructor_error_invalid_arg_count,
1766
- devices=devices,
1767
- )
1768
- add_function_test(
1769
- TestMat,
1770
- "test_tpl_constructor_error_incompatible_sizes",
1771
- test_tpl_constructor_error_incompatible_sizes,
1772
- devices=devices,
1773
- )
1774
- add_function_test(
1775
- TestMat,
1776
- "test_tpl_constructor_error_invalid_scalar_type",
1777
- test_tpl_constructor_error_invalid_scalar_type,
1778
- devices=devices,
1779
- )
1780
- add_function_test(
1781
- TestMat,
1782
- "test_tpl_constructor_error_invalid_vector_count",
1783
- test_tpl_constructor_error_invalid_vector_count,
1784
- devices=devices,
1785
- )
1786
- add_function_test(
1787
- TestMat,
1788
- "test_tpl_constructor_error_invalid_vector_shape",
1789
- test_tpl_constructor_error_invalid_vector_shape,
1790
- devices=devices,
1791
- )
1792
- add_function_test(
1793
- TestMat,
1794
- "test_tpl_constructor_error_invalid_arg_count",
1795
- test_tpl_constructor_error_invalid_arg_count,
1796
- devices=devices,
1797
- )
1798
- add_function_test(TestMat, "test_tpl_ops_with_anon", test_tpl_ops_with_anon)
1799
-
1800
- for dtype in np_float_types:
1801
- add_function_test(
1802
- TestMat, f"test_py_arithmetic_ops_{dtype.__name__}", test_py_arithmetic_ops, devices=None, dtype=dtype
1803
- )
1804
- add_function_test_register_kernel(
1805
- TestMat, f"test_quat_constructor_{dtype.__name__}", test_quat_constructor, devices=devices, dtype=dtype
1806
- )
1807
- add_function_test_register_kernel(
1808
- TestMat, f"test_inverse_{dtype.__name__}", test_inverse, devices=devices, dtype=dtype
1809
- )
1810
- add_function_test_register_kernel(TestMat, f"test_svd_{dtype.__name__}", test_svd, devices=devices, dtype=dtype)
1811
- add_function_test_register_kernel(TestMat, f"test_qr_{dtype.__name__}", test_qr, devices=devices, dtype=dtype)
1812
- add_function_test_register_kernel(TestMat, f"test_eig_{dtype.__name__}", test_eig, devices=devices, dtype=dtype)
1813
- add_function_test_register_kernel(
1814
- TestMat, f"test_transform_point_{dtype.__name__}", test_transform_point, devices=devices, dtype=dtype
1815
- )
1816
- add_function_test_register_kernel(
1817
- TestMat, f"test_transform_vector_{dtype.__name__}", test_transform_vector, devices=devices, dtype=dtype
1818
- )
1819
- add_function_test_register_kernel(
1820
- TestMat, f"test_determinant_{dtype.__name__}", test_determinant, devices=devices, dtype=dtype
1821
- )
1822
- add_function_test_register_kernel(TestMat, f"test_skew_{dtype.__name__}", test_skew, devices=devices, dtype=dtype)
1823
-
1824
-
1825
- if __name__ == "__main__":
1826
- wp.build.clear_kernel_cache()
1827
- unittest.main(verbosity=2, failfast=True)
1
+ # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
2
+ # NVIDIA CORPORATION and its licensors retain all intellectual property
3
+ # and proprietary rights in and to this software, related documentation
4
+ # and any modifications thereto. Any use, reproduction, disclosure or
5
+ # distribution of this software and related documentation without an express
6
+ # license agreement from NVIDIA CORPORATION is strictly prohibited.
7
+
8
+ import unittest
9
+
10
+ import numpy as np
11
+
12
+ import warp as wp
13
+ from warp.tests.unittest_utils import *
14
+
15
+ np_signed_int_types = [
16
+ np.int8,
17
+ np.int16,
18
+ np.int32,
19
+ np.int64,
20
+ np.byte,
21
+ ]
22
+
23
+ np_float_types = [np.float16, np.float32, np.float64]
24
+
25
+
26
+ def randvals(rng, shape, dtype):
27
+ if dtype in np_float_types:
28
+ return rng.standard_normal(size=shape).astype(dtype)
29
+ elif dtype in [np.int8, np.uint8, np.byte, np.ubyte]:
30
+ return rng.integers(1, high=3, size=shape, dtype=dtype)
31
+ return rng.integers(1, high=5, size=shape, dtype=dtype)
32
+
33
+
34
+ kernel_cache = {}
35
+
36
+
37
+ def getkernel(func, suffix=""):
38
+ key = func.__name__ + "_" + suffix
39
+ if key not in kernel_cache:
40
+ kernel_cache[key] = wp.Kernel(func=func, key=key)
41
+ return kernel_cache[key]
42
+
43
+
44
+ def get_select_kernel(dtype):
45
+ def output_select_kernel_fn(
46
+ input: wp.array(dtype=dtype),
47
+ index: int,
48
+ out: wp.array(dtype=dtype),
49
+ ):
50
+ out[0] = input[index]
51
+
52
+ return getkernel(output_select_kernel_fn, suffix=dtype.__name__)
53
+
54
+
55
+ def test_anon_constructor_error_shape_keyword_missing(test, device):
56
+ @wp.kernel
57
+ def kernel():
58
+ wp.matrix(1.0, 2.0, 3.0)
59
+
60
+ with test.assertRaisesRegex(
61
+ RuntimeError,
62
+ r"shape keyword must be specified when calling matrix\(\) function$",
63
+ ):
64
+ wp.launch(
65
+ kernel,
66
+ dim=1,
67
+ inputs=[],
68
+ device=device,
69
+ )
70
+
71
+
72
+ def test_anon_constructor_error_dtype_keyword_missing(test, device):
73
+ @wp.kernel
74
+ def kernel():
75
+ wp.matrix(shape=(3, 3))
76
+
77
+ with test.assertRaisesRegex(
78
+ RuntimeError,
79
+ r"matrix\(\) must have dtype as a keyword argument if it has no " r"positional arguments$",
80
+ ):
81
+ wp.launch(
82
+ kernel,
83
+ dim=1,
84
+ inputs=[],
85
+ device=device,
86
+ )
87
+
88
+
89
+ def test_anon_constructor_error_shape_mismatch(test, device):
90
+ @wp.kernel
91
+ def kernel():
92
+ wp.matrix(
93
+ wp.matrix(shape=(1, 2), dtype=float),
94
+ shape=(3, 4),
95
+ dtype=float,
96
+ )
97
+
98
+ with test.assertRaisesRegex(
99
+ RuntimeError,
100
+ r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 4\) vs \(1, 2\)$",
101
+ ):
102
+ wp.launch(
103
+ kernel,
104
+ dim=1,
105
+ inputs=[],
106
+ device=device,
107
+ )
108
+
109
+
110
+ def test_anon_constructor_error_invalid_arg_count(test, device):
111
+ @wp.kernel
112
+ def kernel():
113
+ wp.matrix(1.0, 2.0, 3.0, shape=(2, 2), dtype=float)
114
+
115
+ with test.assertRaisesRegex(
116
+ RuntimeError,
117
+ r"Wrong number of arguments for matrix\(\) function, must initialize "
118
+ r"with either a scalar value, or m\*n values$",
119
+ ):
120
+ wp.launch(
121
+ kernel,
122
+ dim=1,
123
+ inputs=[],
124
+ device=device,
125
+ )
126
+
127
+
128
+ def test_tpl_constructor_error_incompatible_sizes(test, device):
129
+ @wp.kernel
130
+ def kernel():
131
+ wp.mat33(wp.mat22(1.0, 2.0, 3.0, 4.0))
132
+
133
+ with test.assertRaisesRegex(
134
+ RuntimeError,
135
+ r"Incompatible matrix sizes for casting copy constructor, " r"\(3, 3\) vs \(2, 2\)$",
136
+ ):
137
+ wp.launch(
138
+ kernel,
139
+ dim=1,
140
+ inputs=[],
141
+ device=device,
142
+ )
143
+
144
+
145
+ def test_tpl_constructor_error_invalid_scalar_type(test, device):
146
+ @wp.kernel
147
+ def kernel():
148
+ wp.mat22(1, 2, 3, 4)
149
+
150
+ with test.assertRaisesRegex(
151
+ RuntimeError,
152
+ r"Wrong scalar type for mat 2,2,<class 'warp.types.float32'> constructor$",
153
+ ):
154
+ wp.launch(
155
+ kernel,
156
+ dim=1,
157
+ inputs=[],
158
+ device=device,
159
+ )
160
+
161
+
162
+ def test_tpl_constructor_error_invalid_vector_count(test, device):
163
+ @wp.kernel
164
+ def kernel():
165
+ wp.mat22(wp.vec3(1.0, 2.0, 3.0))
166
+
167
+ with test.assertRaisesRegex(
168
+ RuntimeError,
169
+ r"Wrong number of vectors when attempting to construct a matrix " r"with column vectors$",
170
+ ):
171
+ wp.launch(
172
+ kernel,
173
+ dim=1,
174
+ inputs=[],
175
+ device=device,
176
+ )
177
+
178
+
179
+ def test_tpl_constructor_error_invalid_vector_shape(test, device):
180
+ @wp.kernel
181
+ def kernel():
182
+ wp.mat22(wp.vec3(1.0, 2.0, 3.0), wp.vec3(4.0, 5.0, 6.0))
183
+
184
+ with test.assertRaisesRegex(
185
+ RuntimeError,
186
+ r"Wrong vector row count when attempting to construct a matrix " r"with column vectors$",
187
+ ):
188
+ wp.launch(
189
+ kernel,
190
+ dim=1,
191
+ inputs=[],
192
+ device=device,
193
+ )
194
+
195
+
196
+ def test_tpl_constructor_error_invalid_arg_count(test, device):
197
+ @wp.kernel
198
+ def kernel():
199
+ wp.mat22(1.0, 2.0, 3.0)
200
+
201
+ with test.assertRaisesRegex(
202
+ RuntimeError,
203
+ r"Wrong number of scalars when attempting to construct a matrix " r"from a list of components$",
204
+ ):
205
+ wp.launch(
206
+ kernel,
207
+ dim=1,
208
+ inputs=[],
209
+ device=device,
210
+ )
211
+
212
+
213
+ def test_py_arithmetic_ops(test, device, dtype):
214
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
215
+
216
+ def make_mat(*args):
217
+ if wptype in wp.types.int_types:
218
+ # Cast to the correct integer type to simulate wrapping.
219
+ return tuple(tuple(wptype._type_(x).value for x in row) for row in args)
220
+
221
+ return args
222
+
223
+ def make_vec(*args):
224
+ if wptype in wp.types.int_types:
225
+ # Cast to the correct integer type to simulate wrapping.
226
+ return tuple(wptype._type_(x).value for x in args)
227
+
228
+ return args
229
+
230
+ mat_cls = wp.mat((3, 3), wptype)
231
+ vec_cls = wp.vec(3, wptype)
232
+
233
+ m = mat_cls(((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
234
+ test.assertSequenceEqual(+m, make_mat((-1, 2, 3), (4, -5, 6), (7, 8, -9)))
235
+ test.assertSequenceEqual(-m, make_mat((1, -2, -3), (-4, 5, -6), (-7, -8, 9)))
236
+ test.assertSequenceEqual(m + mat_cls((5, 5, 5) * 3), make_mat((4, 7, 8), (9, 0, 11), (12, 13, -4)))
237
+ test.assertSequenceEqual(m - mat_cls((5, 5, 5) * 3), make_mat((-6, -3, -2), (-1, -10, 1), (2, 3, -14)))
238
+ test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(20, 25, 30))
239
+ test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(20, 25, 30))
240
+ test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(50, 25, 0))
241
+ test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(50, 25, 0))
242
+
243
+ m = mat_cls(((2, 4, 6), (8, 10, 12), (14, 16, 18)))
244
+ test.assertSequenceEqual(m * wptype(2), make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
245
+ test.assertSequenceEqual(wptype(2) * m, make_mat((4, 8, 12), (16, 20, 24), (28, 32, 36)))
246
+ test.assertSequenceEqual(m / wptype(2), make_mat((1, 2, 3), (4, 5, 6), (7, 8, 9)))
247
+ test.assertSequenceEqual(wptype(5040) / m, make_mat((2520, 1260, 840), (630, 504, 420), (360, 315, 280)))
248
+ test.assertSequenceEqual(m * vec_cls(5, 5, 5), make_vec(60, 150, 240))
249
+ test.assertSequenceEqual(m @ vec_cls(5, 5, 5), make_vec(60, 150, 240))
250
+ test.assertSequenceEqual(vec_cls(5, 5, 5) * m, make_vec(120, 150, 180))
251
+ test.assertSequenceEqual(vec_cls(5, 5, 5) @ m, make_vec(120, 150, 180))
252
+
253
+
254
+ def test_quat_constructor(test, device, dtype, register_kernels=False):
255
+ rng = np.random.default_rng(123)
256
+
257
+ tol = {
258
+ np.float16: 1.0e-3,
259
+ np.float32: 1.0e-6,
260
+ np.float64: 1.0e-8,
261
+ }.get(dtype, 0)
262
+
263
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
264
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
265
+ vec4 = wp.types.vector(length=4, dtype=wptype)
266
+ vec3 = wp.types.vector(length=3, dtype=wptype)
267
+ quat = wp.types.quaternion(dtype=wptype)
268
+
269
+ output_select_kernel = get_select_kernel(wptype)
270
+
271
+ def check_mat_quat_constructor(
272
+ p: wp.array(dtype=vec3),
273
+ r: wp.array(dtype=quat),
274
+ s: wp.array(dtype=vec3),
275
+ outcomponents: wp.array(dtype=wptype),
276
+ outcomponents_alt: wp.array(dtype=wptype),
277
+ ):
278
+ m = mat44(p[0], r[0], s[0])
279
+
280
+ R = wp.transpose(wp.quat_to_matrix(r[0]))
281
+ c0 = s[0][0] * R[0]
282
+ c1 = s[0][1] * R[1]
283
+ c2 = s[0][2] * R[2]
284
+ m_alt = mat44(
285
+ vec4(c0[0], c0[1], c0[2], wptype(0.0)),
286
+ vec4(c1[0], c1[1], c1[2], wptype(0.0)),
287
+ vec4(c2[0], c2[1], c2[2], wptype(0.0)),
288
+ vec4(p[0][0], p[0][1], p[0][2], wptype(1.0)),
289
+ )
290
+
291
+ idx = 0
292
+ for i in range(4):
293
+ for j in range(4):
294
+ outcomponents[idx] = m[i, j]
295
+ outcomponents_alt[idx] = m_alt[i, j]
296
+ idx = idx + 1
297
+
298
+ kernel = getkernel(check_mat_quat_constructor, suffix=dtype.__name__)
299
+
300
+ if register_kernels:
301
+ return
302
+
303
+ # translation:
304
+ p = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
305
+
306
+ # generate a normalized quaternion for the rotation:
307
+ r = rng.standard_normal(size=(1, 4))
308
+ r /= np.linalg.norm(r)
309
+ r = wp.array(r.astype(dtype), dtype=quat, requires_grad=True, device=device)
310
+
311
+ # scale:
312
+ s = wp.array(rng.standard_normal(size=(1, 3)).astype(dtype), dtype=vec3, requires_grad=True, device=device)
313
+
314
+ # just going to generate the matrix using the constructor, then
315
+ # more manually, and make sure the values/gradients are the same:
316
+ outcomponents = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
317
+ outcomponents_alt = wp.zeros(4 * 4, dtype=wptype, requires_grad=True, device=device)
318
+ wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
319
+ assert_np_equal(outcomponents.numpy(), outcomponents_alt.numpy(), tol=1.0e-6)
320
+
321
+ idx = 0
322
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
323
+ out_alt = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
324
+ for _i in range(4):
325
+ for _j in range(4):
326
+ tape = wp.Tape()
327
+ with tape:
328
+ wp.launch(kernel, dim=1, inputs=[p, r, s], outputs=[outcomponents, outcomponents_alt], device=device)
329
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
330
+ wp.launch(
331
+ output_select_kernel, dim=1, inputs=[outcomponents_alt, idx], outputs=[out_alt], device=device
332
+ )
333
+
334
+ tape.backward(loss=out)
335
+ p_grad = 1.0 * tape.gradients[p].numpy()[0]
336
+ r_grad = 1.0 * tape.gradients[r].numpy()[0]
337
+ s_grad = 1.0 * tape.gradients[s].numpy()[0]
338
+ tape.zero()
339
+
340
+ tape.backward(loss=out_alt)
341
+ p_grad_alt = 1.0 * tape.gradients[p].numpy()[0]
342
+ r_grad_alt = 1.0 * tape.gradients[r].numpy()[0]
343
+ s_grad_alt = 1.0 * tape.gradients[s].numpy()[0]
344
+ tape.zero()
345
+
346
+ assert_np_equal(p_grad, p_grad_alt, tol=tol)
347
+ assert_np_equal(r_grad, r_grad_alt, tol=tol)
348
+ assert_np_equal(s_grad, s_grad_alt, tol=tol)
349
+
350
+ idx = idx + 1
351
+
352
+
353
+ def test_negation(test, device, dtype, register_kernels=False):
354
+ rng = np.random.default_rng(123)
355
+
356
+ tol = {
357
+ np.float16: 1.0e-2,
358
+ np.float32: 1.0e-6,
359
+ np.float64: 1.0e-8,
360
+ }.get(dtype, 0)
361
+
362
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
363
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
364
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
365
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
366
+ mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
367
+
368
+ output_select_kernel = get_select_kernel(wptype)
369
+
370
+ def check_mat_negation(
371
+ m2: wp.array(dtype=mat22),
372
+ m3: wp.array(dtype=mat33),
373
+ m4: wp.array(dtype=mat44),
374
+ m5: wp.array(dtype=mat55),
375
+ outcomponents: wp.array(dtype=wptype),
376
+ ):
377
+ mat2 = -m2[0]
378
+ mat3 = -m3[0]
379
+ mat4 = -m4[0]
380
+ mat5 = -m5[0]
381
+
382
+ # multiply outputs by 2 so we've got something to backpropagate:
383
+ idx = 0
384
+ for i in range(2):
385
+ for j in range(2):
386
+ outcomponents[idx] = wptype(2) * mat2[i, j]
387
+ idx = idx + 1
388
+
389
+ for i in range(3):
390
+ for j in range(3):
391
+ outcomponents[idx] = wptype(2) * mat3[i, j]
392
+ idx = idx + 1
393
+
394
+ for i in range(4):
395
+ for j in range(4):
396
+ outcomponents[idx] = wptype(2) * mat4[i, j]
397
+ idx = idx + 1
398
+
399
+ for i in range(5):
400
+ for j in range(5):
401
+ outcomponents[idx] = wptype(2) * mat5[i, j]
402
+ idx = idx + 1
403
+
404
+ kernel = getkernel(check_mat_negation, suffix=dtype.__name__)
405
+
406
+ if register_kernels:
407
+ return
408
+
409
+ m2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
410
+ m3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
411
+ m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
412
+ m5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
413
+ outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
414
+
415
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
416
+
417
+ assert_np_equal(outcomponents.numpy()[:4], -2 * m2.numpy().reshape(-1), tol=tol)
418
+ assert_np_equal(outcomponents.numpy()[4:13], -2 * m3.numpy().reshape(-1), tol=tol)
419
+ assert_np_equal(outcomponents.numpy()[13:29], -2 * m4.numpy().reshape(-1), tol=tol)
420
+ assert_np_equal(outcomponents.numpy()[29:54], -2 * m5.numpy().reshape(-1), tol=tol)
421
+
422
+ if dtype in np_float_types:
423
+ idx = 0
424
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
425
+ for dim, input in [(2, m2), (3, m3), (4, m4), (5, m5)]:
426
+ for i in range(dim):
427
+ for j in range(dim):
428
+ tape = wp.Tape()
429
+ with tape:
430
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4, m5], outputs=[outcomponents], device=device)
431
+ wp.launch(
432
+ output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
433
+ )
434
+ tape.backward(loss=out)
435
+ expectedresult = np.zeros((dim, dim), dtype=dtype)
436
+ expectedresult[i, j] = -2
437
+ assert_np_equal(tape.gradients[input].numpy()[0], expectedresult)
438
+ tape.zero()
439
+ idx = idx + 1
440
+
441
+
442
+ def test_subtraction(test, device, dtype, register_kernels=False):
443
+ rng = np.random.default_rng(123)
444
+
445
+ tol = {
446
+ np.float16: 5.0e-3,
447
+ np.float32: 1.0e-6,
448
+ np.float64: 1.0e-8,
449
+ }.get(dtype, 0)
450
+
451
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
452
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
453
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
454
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
455
+ mat55 = wp.types.matrix(shape=(5, 5), dtype=wptype)
456
+
457
+ output_select_kernel = get_select_kernel(wptype)
458
+
459
+ def check_mat_sub(
460
+ s2: wp.array(dtype=mat22),
461
+ s3: wp.array(dtype=mat33),
462
+ s4: wp.array(dtype=mat44),
463
+ s5: wp.array(dtype=mat55),
464
+ v2: wp.array(dtype=mat22),
465
+ v3: wp.array(dtype=mat33),
466
+ v4: wp.array(dtype=mat44),
467
+ v5: wp.array(dtype=mat55),
468
+ outcomponents: wp.array(dtype=wptype),
469
+ ):
470
+ v2result = v2[0] - s2[0]
471
+ v3result = v3[0] - s3[0]
472
+ v4result = v4[0] - s4[0]
473
+ v5result = v5[0] - s5[0]
474
+
475
+ # multiply outputs by 2 so we've got something to backpropagate:
476
+ idx = 0
477
+ for i in range(2):
478
+ for j in range(2):
479
+ outcomponents[idx] = wptype(2) * v2result[i, j]
480
+ idx = idx + 1
481
+
482
+ for i in range(3):
483
+ for j in range(3):
484
+ outcomponents[idx] = wptype(2) * v3result[i, j]
485
+ idx = idx + 1
486
+
487
+ for i in range(4):
488
+ for j in range(4):
489
+ outcomponents[idx] = wptype(2) * v4result[i, j]
490
+ idx = idx + 1
491
+
492
+ for i in range(5):
493
+ for j in range(5):
494
+ outcomponents[idx] = wptype(2) * v5result[i, j]
495
+ idx = idx + 1
496
+
497
+ kernel = getkernel(check_mat_sub, suffix=dtype.__name__)
498
+
499
+ if register_kernels:
500
+ return
501
+
502
+ s2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
503
+ s3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
504
+ s4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
505
+ s5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
506
+ v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
507
+ v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
508
+ v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
509
+ v5 = wp.array(randvals(rng, [1, 5, 5], dtype), dtype=mat55, requires_grad=True, device=device)
510
+ outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4 + 5 * 5, dtype=wptype, requires_grad=True, device=device)
511
+
512
+ wp.launch(
513
+ kernel,
514
+ dim=1,
515
+ inputs=[
516
+ s2,
517
+ s3,
518
+ s4,
519
+ s5,
520
+ v2,
521
+ v3,
522
+ v4,
523
+ v5,
524
+ ],
525
+ outputs=[outcomponents],
526
+ device=device,
527
+ )
528
+
529
+ assert_np_equal(outcomponents.numpy()[:4], 2 * (v2.numpy() - s2.numpy()).reshape(-1), tol=tol)
530
+ assert_np_equal(outcomponents.numpy()[4:13], 2 * (v3.numpy() - s3.numpy()).reshape(-1), tol=tol)
531
+ assert_np_equal(outcomponents.numpy()[13:29], 2 * (v4.numpy() - s4.numpy()).reshape(-1), tol=tol)
532
+ assert_np_equal(outcomponents.numpy()[29:54], 2 * (v5.numpy() - s5.numpy()).reshape(-1), tol=10 * tol)
533
+
534
+ if dtype in np_float_types:
535
+ idx = 0
536
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
537
+ for dim, in1, in2 in [(2, s2, v2), (3, s3, v3), (4, s4, v4), (5, s5, v5)]:
538
+ for i in range(dim):
539
+ for j in range(dim):
540
+ tape = wp.Tape()
541
+ with tape:
542
+ wp.launch(
543
+ kernel,
544
+ dim=1,
545
+ inputs=[
546
+ s2,
547
+ s3,
548
+ s4,
549
+ s5,
550
+ v2,
551
+ v3,
552
+ v4,
553
+ v5,
554
+ ],
555
+ outputs=[outcomponents],
556
+ device=device,
557
+ )
558
+ wp.launch(
559
+ output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
560
+ )
561
+ tape.backward(loss=out)
562
+ expectedresult = np.zeros((dim, dim), dtype=dtype)
563
+ expectedresult[i, j] = 2
564
+ assert_np_equal(tape.gradients[in2].numpy()[0], expectedresult, tol=10 * tol)
565
+ expectedresult[i, j] = -2
566
+ assert_np_equal(tape.gradients[in1].numpy()[0], expectedresult, tol=10 * tol)
567
+ tape.zero()
568
+
569
+ idx = idx + 1
570
+
571
+
572
+ def test_determinant(test, device, dtype, register_kernels=False):
573
+ rng = np.random.default_rng(123)
574
+
575
+ tol = {
576
+ np.float16: 5.0e-3,
577
+ np.float32: 1.0e-6,
578
+ np.float64: 1.0e-8,
579
+ }.get(dtype, 0)
580
+
581
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
582
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
583
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
584
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
585
+
586
+ def check_mat_det(
587
+ v2: wp.array(dtype=mat22),
588
+ v3: wp.array(dtype=mat33),
589
+ v4: wp.array(dtype=mat44),
590
+ det2: wp.array(dtype=wptype),
591
+ det3: wp.array(dtype=wptype),
592
+ det4: wp.array(dtype=wptype),
593
+ ):
594
+ # multiply outputs by 2 so we've got something to backpropagate:
595
+ det2[0] = wptype(2) * wp.determinant(v2[0])
596
+ det3[0] = wptype(2) * wp.determinant(v3[0])
597
+ det4[0] = wptype(2) * wp.determinant(v4[0])
598
+
599
+ kernel = getkernel(check_mat_det, suffix=dtype.__name__)
600
+ if register_kernels:
601
+ return
602
+
603
+ v2 = wp.array(randvals(rng, [1, 2, 2], dtype), dtype=mat22, requires_grad=True, device=device)
604
+ v3 = wp.array(randvals(rng, [1, 3, 3], dtype), dtype=mat33, requires_grad=True, device=device)
605
+ v4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
606
+ det2 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
607
+ det3 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
608
+ det4 = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
609
+
610
+ tape = wp.Tape()
611
+ with tape:
612
+ wp.launch(
613
+ kernel,
614
+ dim=1,
615
+ inputs=[
616
+ v2,
617
+ v3,
618
+ v4,
619
+ ],
620
+ outputs=[
621
+ det2,
622
+ det3,
623
+ det4,
624
+ ],
625
+ device=device,
626
+ )
627
+
628
+ if dtype in np_float_types:
629
+ assert_np_equal(det2.numpy()[0], 2 * np.linalg.det(v2.numpy()[0].astype(np.float64)), tol=100 * tol)
630
+ assert_np_equal(det3.numpy()[0], 2 * np.linalg.det(v3.numpy()[0].astype(np.float64)), tol=100 * tol)
631
+ assert_np_equal(det4.numpy()[0], 2 * np.linalg.det(v4.numpy()[0].astype(np.float64)), tol=420 * tol)
632
+ else:
633
+ assert_np_equal(det2.numpy()[0], 2 * np.around(np.linalg.det(v2.numpy()[0])).astype(int))
634
+ assert_np_equal(det3.numpy()[0], 2 * np.around(np.linalg.det(v3.numpy()[0])).astype(int))
635
+ assert_np_equal(det4.numpy()[0], 2 * np.around(np.linalg.det(v4.numpy()[0])).astype(int))
636
+
637
+ if dtype in np_float_types:
638
+ # determinant derivative formula is annoying so finite differences?
639
+ tape.backward(loss=det2)
640
+ v2grads = 1.0 * tape.gradients[v2].numpy()[0]
641
+ tape.zero()
642
+
643
+ tape.backward(loss=det3)
644
+ v3grads = 1.0 * tape.gradients[v3].numpy()[0]
645
+ tape.zero()
646
+
647
+ tape.backward(loss=det4)
648
+ v4grads = 1.0 * tape.gradients[v4].numpy()[0]
649
+ tape.zero()
650
+
651
+ # finite differences are also annoying hence the large tolerance...
652
+ # absolute nightmare in float16 too innit...
653
+ dx = 0.01 if dtype == np.float16 else 0.0001
654
+ fdtol = 2.0e-1 if dtype == np.float16 else 2.0e-3
655
+ for i in range(2):
656
+ for j in range(2):
657
+ v2test = v2.numpy()
658
+ v2test[0, i, j] += dx
659
+ wp.launch(
660
+ kernel,
661
+ dim=1,
662
+ inputs=[
663
+ wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
664
+ v3,
665
+ v4,
666
+ ],
667
+ outputs=[
668
+ det2,
669
+ det3,
670
+ det4,
671
+ ],
672
+ device=device,
673
+ )
674
+ dplus = det2.numpy()[0]
675
+ v2test[0, i, j] -= 2.0 * dx
676
+ wp.launch(
677
+ kernel,
678
+ dim=1,
679
+ inputs=[
680
+ wp.array(v2test, dtype=v2.dtype, requires_grad=True, device=device),
681
+ v3,
682
+ v4,
683
+ ],
684
+ outputs=[
685
+ det2,
686
+ det3,
687
+ det4,
688
+ ],
689
+ device=device,
690
+ )
691
+ dminus = det2.numpy()[0]
692
+ assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v2grads[i, j] / dplus, tol=fdtol)
693
+
694
+ for i in range(3):
695
+ for j in range(3):
696
+ v3test = v3.numpy()
697
+ v3test[0, i, j] += dx
698
+ wp.launch(
699
+ kernel,
700
+ dim=1,
701
+ inputs=[
702
+ v2,
703
+ wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
704
+ v4,
705
+ ],
706
+ outputs=[
707
+ det2,
708
+ det3,
709
+ det4,
710
+ ],
711
+ device=device,
712
+ )
713
+ dplus = det3.numpy()[0]
714
+ v3test[0, i, j] -= 2.0 * dx
715
+ wp.launch(
716
+ kernel,
717
+ dim=1,
718
+ inputs=[
719
+ v2,
720
+ wp.array(v3test, dtype=v3.dtype, requires_grad=True, device=device),
721
+ v4,
722
+ ],
723
+ outputs=[
724
+ det2,
725
+ det3,
726
+ det4,
727
+ ],
728
+ device=device,
729
+ )
730
+ dminus = det3.numpy()[0]
731
+ assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v3grads[i, j] / dplus, tol=fdtol)
732
+
733
+ for i in range(4):
734
+ for j in range(4):
735
+ v4test = v4.numpy()
736
+ v4test[0, i, j] += dx
737
+ wp.launch(
738
+ kernel,
739
+ dim=1,
740
+ inputs=[
741
+ v2,
742
+ v3,
743
+ wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
744
+ ],
745
+ outputs=[
746
+ det2,
747
+ det3,
748
+ det4,
749
+ ],
750
+ device=device,
751
+ )
752
+ dplus = det4.numpy()[0]
753
+ v4test[0, i, j] -= 2.0 * dx
754
+ wp.launch(
755
+ kernel,
756
+ dim=1,
757
+ inputs=[
758
+ v2,
759
+ v3,
760
+ wp.array(v4test, dtype=v4.dtype, requires_grad=True, device=device),
761
+ ],
762
+ outputs=[
763
+ det2,
764
+ det3,
765
+ det4,
766
+ ],
767
+ device=device,
768
+ )
769
+ dminus = det4.numpy()[0]
770
+ assert_np_equal((dplus - dminus) / (2.0 * dx * dplus), v4grads[i, j] / dplus, tol=fdtol)
771
+
772
+
773
+ # Unused. Why?
774
+ # def test_get_diag(test, device, dtype, register_kernels=False):
775
+ # tol = {
776
+ # np.float16: 1.0e-3,
777
+ # np.float32: 1.0e-6,
778
+ # np.float64: 1.0e-8,
779
+ # }.get(dtype, 0)
780
+ #
781
+ # wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
782
+ # mat55 = wp.types.vector(shape=(5, 5), dtype=wptype)
783
+ #
784
+ # output_select_kernel = get_select_kernel(wptype)
785
+ #
786
+ # def check_mat_diag(
787
+ # m55: wp.array(dtype=mat55),
788
+ # outcomponents: wp.array(dtype=wptype),
789
+ # ):
790
+ # # multiply outputs by 2 so we've got something to backpropagate:
791
+ # vec5result = wptype(2) * wp.get_diag(m55[0])
792
+ #
793
+ # idx = 0
794
+ # for i in range(5):
795
+ # outcomponents[idx] = vec5result[i]
796
+ # idx = idx + 1
797
+ #
798
+ # kernel = getkernel(check_mat_diag, suffix=dtype.__name__)
799
+ #
800
+ # if register_kernels:
801
+ # return
802
+ #
803
+ # m55 = wp.array(randvals((1, 5, 5), dtype), dtype=mat55, requires_grad=True, device=device)
804
+ # outcomponents = wp.zeros(5, dtype=wptype, requires_grad=True, device=device)
805
+ # out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
806
+ #
807
+ # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
808
+ #
809
+ # assert_np_equal(outcomponents.numpy(), 2 * np.diag(m55.numpy()[0]), tol=tol)
810
+ #
811
+ # if dtype in np_float_types:
812
+ # idx = 0
813
+ # for i in range(5):
814
+ # tape = wp.Tape()
815
+ # with tape:
816
+ # wp.launch(kernel, dim=1, inputs=[m55], outputs=[outcomponents], device=device)
817
+ # wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
818
+ # tape.backward(loss=out)
819
+ # expectedresult = np.zeros((5, 5), dtype=dtype)
820
+ # expectedresult[i, i] = 2
821
+ # assert_np_equal(tape.gradients[m55].numpy()[0], expectedresult, tol=10 * tol)
822
+ # tape.zero()
823
+ #
824
+ # idx = idx + 1
825
+
826
+
827
+ def test_inverse(test, device, dtype, register_kernels=False):
828
+ rng = np.random.default_rng(123)
829
+
830
+ tol = {
831
+ np.float16: 5.0e-2,
832
+ np.float32: 1.0e-5,
833
+ np.float64: 1.0e-8,
834
+ }.get(dtype, 0)
835
+
836
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
837
+ mat22 = wp.types.matrix(shape=(2, 2), dtype=wptype)
838
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
839
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
840
+
841
+ output_select_kernel = get_select_kernel(wptype)
842
+
843
+ def check_mat_inverse(
844
+ m2: wp.array(dtype=mat22),
845
+ m3: wp.array(dtype=mat33),
846
+ m4: wp.array(dtype=mat44),
847
+ outcomponents: wp.array(dtype=wptype),
848
+ ):
849
+ m2result = wp.inverse(m2[0])
850
+ m3result = wp.inverse(m3[0])
851
+ m4result = wp.inverse(m4[0])
852
+
853
+ # multiply outputs by 2 so we've got something to backpropagate:
854
+ idx = 0
855
+ for i in range(2):
856
+ for j in range(2):
857
+ outcomponents[idx] = wptype(2) * m2result[i, j]
858
+ idx = idx + 1
859
+
860
+ for i in range(3):
861
+ for j in range(3):
862
+ outcomponents[idx] = wptype(2) * m3result[i, j]
863
+ idx = idx + 1
864
+
865
+ for i in range(4):
866
+ for j in range(4):
867
+ outcomponents[idx] = wptype(2) * m4result[i, j]
868
+ idx = idx + 1
869
+
870
+ kernel = getkernel(check_mat_inverse, suffix=dtype.__name__)
871
+
872
+ if register_kernels:
873
+ return
874
+
875
+ m2 = wp.array(
876
+ 2 * (randvals(rng, [1, 2, 2], dtype) + 0.2 * np.eye(2)), dtype=mat22, requires_grad=True, device=device
877
+ )
878
+ m3 = wp.array(
879
+ 2 * (randvals(rng, [1, 3, 3], dtype) + 0.2 * np.eye(3)), dtype=mat33, requires_grad=True, device=device
880
+ )
881
+ m4 = wp.array(
882
+ 2 * (randvals(rng, [1, 4, 4], dtype) + 0.2 * np.eye(4)), dtype=mat44, requires_grad=True, device=device
883
+ )
884
+
885
+ outcomponents = wp.zeros(2 * 2 + 3 * 3 + 4 * 4, dtype=wptype, requires_grad=True, device=device)
886
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
887
+
888
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
889
+
890
+ assert_np_equal(outcomponents.numpy()[:4], 2 * np.linalg.inv(m2.numpy()[0].astype(np.float64)), tol=tol)
891
+ assert_np_equal(outcomponents.numpy()[4:13], 2 * np.linalg.inv(m3.numpy()[0].astype(np.float64)), tol=5 * tol)
892
+ assert_np_equal(outcomponents.numpy()[13:], 2 * np.linalg.inv(m4.numpy()[0].astype(np.float64)), tol=5 * tol)
893
+
894
+ if dtype in np_float_types:
895
+ # check gradients:
896
+ idx = 0
897
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
898
+ for dim, input in [(2, m2), (3, m3), (4, m4)]:
899
+ minv = np.linalg.inv(input.numpy()[0].astype(np.float64))
900
+ for i in range(dim):
901
+ for j in range(dim):
902
+ tape = wp.Tape()
903
+ with tape:
904
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
905
+ wp.launch(
906
+ output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device
907
+ )
908
+ tape.backward(loss=out)
909
+ d = np.zeros((dim, dim))
910
+ d[j, i] = 2
911
+ assert_np_equal(
912
+ tape.gradients[input].numpy()[0], -np.matmul(minv, np.matmul(d, minv)).T, tol=10 * tol
913
+ )
914
+ tape.zero()
915
+
916
+ idx = idx + 1
917
+
918
+ # let's check 2x2 using different formulae just for (in)sanity's sake:
919
+ m = m2.numpy()[0]
920
+
921
+ det = m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]
922
+ expected = 2 * np.array([[m[1, 1], -m[0, 1]], [-m[1, 0], m[0, 0]]], dtype=dtype) / det
923
+ assert_np_equal(expected, outcomponents.numpy()[:4], tol=tol)
924
+
925
+ # 0,0 component is this:
926
+ # 2 * m[1,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
927
+ assert_np_equal(2 * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[0], tol=tol)
928
+
929
+ tape = wp.Tape()
930
+ with tape:
931
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
932
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 0], outputs=[out], device=device)
933
+
934
+ if dtype in np_float_types:
935
+ tape.backward(loss=out)
936
+ g = tape.gradients[m2].numpy()[0]
937
+ assert_np_equal(-2 * m[1, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
938
+ assert_np_equal(2 * m[1, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
939
+ assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
940
+ assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
941
+ tape.zero()
942
+
943
+ # 0,1 component is this:
944
+ # -2 * m[0,1] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
945
+ assert_np_equal(-2 * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[1], tol=tol)
946
+
947
+ tape = wp.Tape()
948
+ with tape:
949
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
950
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 1], outputs=[out], device=device)
951
+ if dtype in np_float_types:
952
+ tape.backward(loss=out)
953
+ g = tape.gradients[m2].numpy()[0]
954
+ assert_np_equal(2 * m[0, 1] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
955
+ assert_np_equal(-2 * m[0, 1] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
956
+ assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
957
+ assert_np_equal(-2 * m[1, 1] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
958
+ tape.zero()
959
+
960
+ # 1,0 component is this:
961
+ # -2 * m[1,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
962
+ assert_np_equal(-2 * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[2], tol=tol)
963
+
964
+ tape = wp.Tape()
965
+ with tape:
966
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
967
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 2], outputs=[out], device=device)
968
+
969
+ if dtype in np_float_types:
970
+ tape.backward(loss=out)
971
+ g = tape.gradients[m2].numpy()[0]
972
+ assert_np_equal(2 * m[1, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
973
+ assert_np_equal(-2 * m[0, 0] * m[1, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
974
+ assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
975
+ assert_np_equal(-2 * m[1, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
976
+ tape.zero()
977
+
978
+ # 1,1 component is this:
979
+ # 2 * m[0,0] / (m[0,0]*m[1,1] - m[1,0] * m[0,1])
980
+ assert_np_equal(2 * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]), outcomponents.numpy()[3], tol=tol)
981
+
982
+ tape = wp.Tape()
983
+ with tape:
984
+ wp.launch(kernel, dim=1, inputs=[m2, m3, m4], outputs=[outcomponents], device=device)
985
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, 3], outputs=[out], device=device)
986
+
987
+ if dtype in np_float_types:
988
+ tape.backward(loss=out)
989
+ g = tape.gradients[m2].numpy()[0]
990
+ assert_np_equal(-2 * m[0, 1] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 0], tol=tol)
991
+ assert_np_equal(2 * m[0, 0] * m[0, 1] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 0], tol=tol)
992
+ assert_np_equal(2 * m[0, 0] * m[1, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[0, 1], tol=tol)
993
+ assert_np_equal(-2 * m[0, 0] * m[0, 0] / (m[0, 0] * m[1, 1] - m[1, 0] * m[0, 1]) ** 2, g[1, 1], tol=tol)
994
+ tape.zero()
995
+
996
+
997
+ def test_svd(test, device, dtype, register_kernels=False):
998
+ rng = np.random.default_rng(123)
999
+
1000
+ tol = {
1001
+ np.float16: 1.0e-3,
1002
+ np.float32: 1.0e-6,
1003
+ np.float64: 1.0e-6,
1004
+ }.get(dtype, 0)
1005
+
1006
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1007
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1008
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1009
+
1010
+ def check_mat_svd(
1011
+ m3: wp.array(dtype=mat33),
1012
+ Uout: wp.array(dtype=mat33),
1013
+ sigmaout: wp.array(dtype=vec3),
1014
+ Vout: wp.array(dtype=mat33),
1015
+ outcomponents: wp.array(dtype=wptype),
1016
+ ):
1017
+ U = mat33()
1018
+ sigma = vec3()
1019
+ V = mat33()
1020
+
1021
+ wp.svd3(m3[0], U, sigma, V)
1022
+
1023
+ Uout[0] = U
1024
+ sigmaout[0] = sigma
1025
+ Vout[0] = V
1026
+
1027
+ # multiply outputs by 2 so we've got something to backpropagate:
1028
+ idx = 0
1029
+ for i in range(3):
1030
+ for j in range(3):
1031
+ outcomponents[idx] = wptype(2) * U[i, j]
1032
+ idx = idx + 1
1033
+
1034
+ for i in range(3):
1035
+ outcomponents[idx] = wptype(2) * sigma[i]
1036
+ idx = idx + 1
1037
+
1038
+ for i in range(3):
1039
+ for j in range(3):
1040
+ outcomponents[idx] = wptype(2) * V[i, j]
1041
+ idx = idx + 1
1042
+
1043
+ kernel = getkernel(check_mat_svd, suffix=dtype.__name__)
1044
+
1045
+ output_select_kernel = get_select_kernel(wptype)
1046
+
1047
+ if register_kernels:
1048
+ return
1049
+
1050
+ m3 = wp.array(randvals(rng, [1, 3, 3], dtype) + np.eye(3), dtype=mat33, requires_grad=True, device=device)
1051
+
1052
+ outcomponents = wp.zeros(2 * 3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1053
+ Uout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1054
+ sigmaout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1055
+ Vout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1056
+
1057
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1058
+
1059
+ Uout_np = Uout.numpy()[0].astype(np.float64)
1060
+ sigmaout_np = np.diag(sigmaout.numpy()[0].astype(np.float64))
1061
+ Vout_np = Vout.numpy()[0].astype(np.float64)
1062
+
1063
+ assert_np_equal(
1064
+ np.matmul(Uout_np, np.matmul(sigmaout_np, Vout_np.T)), m3.numpy()[0].astype(np.float64), tol=30 * tol
1065
+ )
1066
+
1067
+ if dtype == np.float16:
1068
+ # I'm not even going to bother testing the gradients for float16
1069
+ # because the rounding errors are terrible...
1070
+ return
1071
+
1072
+ # check gradients:
1073
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1074
+ idx = 0
1075
+ for idx in range(3 * 3 + 3 + 3 * 3):
1076
+ tape = wp.Tape()
1077
+ with tape:
1078
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Uout, sigmaout, Vout, outcomponents], device=device)
1079
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1080
+ tape.backward(out)
1081
+ m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1082
+
1083
+ tape.zero()
1084
+
1085
+ dx = 0.0001
1086
+ fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1087
+ for ii in range(3):
1088
+ for jj in range(3):
1089
+ m3test = 1.0 * m3.numpy()
1090
+ m3test[0, ii, jj] += dx
1091
+ wp.launch(
1092
+ kernel,
1093
+ dim=1,
1094
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1095
+ outputs=[Uout, sigmaout, Vout, outcomponents],
1096
+ device=device,
1097
+ )
1098
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1099
+ plusval = out.numpy()[0]
1100
+
1101
+ m3test = 1.0 * m3.numpy()
1102
+ m3test[0, ii, jj] -= dx
1103
+ wp.launch(
1104
+ kernel,
1105
+ dim=1,
1106
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1107
+ outputs=[Uout, sigmaout, Vout, outcomponents],
1108
+ device=device,
1109
+ )
1110
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1111
+ minusval = out.numpy()[0]
1112
+
1113
+ assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1114
+
1115
+
1116
+ def test_qr(test, device, dtype, register_kernels=False):
1117
+ rng = np.random.default_rng(123)
1118
+
1119
+ tol = {
1120
+ np.float16: 2.0e-3,
1121
+ np.float32: 1.0e-6,
1122
+ np.float64: 1.0e-6,
1123
+ }.get(dtype, 0)
1124
+
1125
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1126
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1127
+
1128
+ def check_mat_qr(
1129
+ m3: wp.array(dtype=mat33),
1130
+ Qout: wp.array(dtype=mat33),
1131
+ Rout: wp.array(dtype=mat33),
1132
+ outcomponents: wp.array(dtype=wptype),
1133
+ ):
1134
+ Q = mat33()
1135
+ R = mat33()
1136
+
1137
+ wp.qr3(m3[0], Q, R)
1138
+
1139
+ Qout[0] = Q
1140
+ Rout[0] = R
1141
+
1142
+ # multiply outputs by 2 so we've got something to backpropagate:
1143
+ idx = 0
1144
+ for i in range(3):
1145
+ for j in range(3):
1146
+ outcomponents[idx] = wptype(2) * Q[i, j]
1147
+ idx = idx + 1
1148
+
1149
+ for i in range(3):
1150
+ for j in range(3):
1151
+ outcomponents[idx] = wptype(2) * R[i, j]
1152
+ idx = idx + 1
1153
+
1154
+ kernel = getkernel(check_mat_qr, suffix=dtype.__name__)
1155
+ output_select_kernel = get_select_kernel(wptype)
1156
+
1157
+ if register_kernels:
1158
+ return
1159
+
1160
+ m3 = wp.array(0.5 * (randvals(rng, [1, 3, 3], dtype) + np.eye(3)), dtype=mat33, requires_grad=True, device=device)
1161
+
1162
+ outcomponents = wp.zeros(2 * 3 * 3, dtype=wptype, requires_grad=True, device=device)
1163
+ Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1164
+ Rout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1165
+
1166
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1167
+
1168
+ Qout_np = Qout.numpy()[0].astype(np.float64)
1169
+ Rout_np = Rout.numpy()[0].astype(np.float64)
1170
+
1171
+ # check it's actually a q and an r:
1172
+ assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3, dtype=np.float64), tol=tol)
1173
+ assert_np_equal(Rout_np[1, [0]], np.zeros(1, dtype=np.float64), tol=tol)
1174
+ assert_np_equal(Rout_np[2, [0, 1]], np.zeros(2, dtype=np.float64), tol=tol)
1175
+
1176
+ # check it's a factorization:
1177
+ assert_np_equal(np.matmul(Qout_np, Rout_np), m3.numpy()[0].astype(np.float64), tol=30 * tol)
1178
+
1179
+ if dtype == np.float16:
1180
+ # I'm not even going to bother testing the gradients for float16
1181
+ # because the rounding errors are terrible...
1182
+ return
1183
+
1184
+ # check gradients:
1185
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1186
+ idx = 0
1187
+ for idx in range(len(outcomponents)):
1188
+ tape = wp.Tape()
1189
+ with tape:
1190
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, Rout, outcomponents], device=device)
1191
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1192
+ tape.backward(out)
1193
+ m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1194
+
1195
+ tape.zero()
1196
+
1197
+ dx = 0.0001
1198
+ fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1199
+ for ii in range(3):
1200
+ for jj in range(3):
1201
+ m3test = 1.0 * m3.numpy()
1202
+ m3test[0, ii, jj] += dx
1203
+ wp.launch(
1204
+ kernel,
1205
+ dim=1,
1206
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1207
+ outputs=[Qout, Rout, outcomponents],
1208
+ device=device,
1209
+ )
1210
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1211
+ plusval = out.numpy()[0]
1212
+
1213
+ m3test = 1.0 * m3.numpy()
1214
+ m3test[0, ii, jj] -= dx
1215
+ wp.launch(
1216
+ kernel,
1217
+ dim=1,
1218
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1219
+ outputs=[Qout, Rout, outcomponents],
1220
+ device=device,
1221
+ )
1222
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1223
+ minusval = out.numpy()[0]
1224
+
1225
+ assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1226
+
1227
+
1228
+ def test_eig(test, device, dtype, register_kernels=False):
1229
+ rng = np.random.default_rng(123)
1230
+
1231
+ tol = {
1232
+ np.float16: 4.0e-2,
1233
+ np.float32: 1.0e-5,
1234
+ np.float64: 1.0e-5,
1235
+ }.get(dtype, 0)
1236
+
1237
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1238
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1239
+ mat33 = wp.types.matrix(shape=(3, 3), dtype=wptype)
1240
+
1241
+ def check_mat_eig(
1242
+ m3: wp.array(dtype=mat33),
1243
+ Qout: wp.array(dtype=mat33),
1244
+ dout: wp.array(dtype=vec3),
1245
+ outcomponents: wp.array(dtype=wptype),
1246
+ ):
1247
+ Q = mat33()
1248
+ d = vec3()
1249
+
1250
+ wp.eig3(m3[0] + wp.transpose(m3[0]), Q, d)
1251
+
1252
+ Qout[0] = Q
1253
+ dout[0] = d
1254
+
1255
+ # multiply outputs by 2 so we've got something to backpropagate:
1256
+ idx = 0
1257
+ for i in range(3):
1258
+ for j in range(3):
1259
+ outcomponents[idx] = wptype(2) * Q[i, j]
1260
+ idx = idx + 1
1261
+
1262
+ for i in range(3):
1263
+ outcomponents[idx] = wptype(2) * d[i]
1264
+ idx = idx + 1
1265
+
1266
+ kernel = getkernel(check_mat_eig, suffix=dtype.__name__)
1267
+ output_select_kernel = get_select_kernel(wptype)
1268
+
1269
+ if register_kernels:
1270
+ return
1271
+
1272
+ m3_np = randvals(rng, [1, 3, 3], dtype) + np.eye(3, dtype=dtype)
1273
+ m3 = wp.array(m3_np, dtype=mat33, requires_grad=True, device=device)
1274
+
1275
+ outcomponents = wp.zeros(3 * 3 + 3, dtype=wptype, requires_grad=True, device=device)
1276
+ Qout = wp.zeros(1, dtype=mat33, requires_grad=True, device=device)
1277
+ dout = wp.zeros(1, dtype=vec3, requires_grad=True, device=device)
1278
+
1279
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1280
+
1281
+ Qout_np = Qout.numpy()[0].astype(np.float64)
1282
+ dout_np = dout.numpy()[0].astype(np.float64)
1283
+ Dout_np = np.diag(dout_np)
1284
+
1285
+ # check Q is orthogonal:
1286
+ assert_np_equal(np.matmul(Qout_np.T, Qout_np), np.eye(3), tol=tol)
1287
+
1288
+ # check Q contains eigenvectors:
1289
+ assert_np_equal(np.matmul(Qout_np, np.matmul(Dout_np, Qout_np.T)), (m3_np[0] + m3_np[0].transpose()), tol=tol)
1290
+
1291
+ if dtype == np.float16:
1292
+ # I'm not even going to bother testing the gradients for float16
1293
+ # because the rounding errors are terrible...
1294
+ return
1295
+
1296
+ # check gradients:
1297
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1298
+ idx = 0
1299
+ for idx in range(len(outcomponents)):
1300
+ tape = wp.Tape()
1301
+ with tape:
1302
+ wp.launch(kernel, dim=1, inputs=[m3], outputs=[Qout, dout, outcomponents], device=device)
1303
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1304
+ tape.backward(out)
1305
+ m3grads = 1.0 * tape.gradients[m3].numpy()[0]
1306
+
1307
+ tape.zero()
1308
+
1309
+ dx = 0.0001
1310
+ fdtol = 5.0e-4 if dtype == np.float64 else 2.0e-2
1311
+ for ii in range(3):
1312
+ for jj in range(3):
1313
+ m3test = 1.0 * m3.numpy()
1314
+ m3test[0, ii, jj] += dx
1315
+ wp.launch(
1316
+ kernel,
1317
+ dim=1,
1318
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1319
+ outputs=[Qout, dout, outcomponents],
1320
+ device=device,
1321
+ )
1322
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1323
+ plusval = out.numpy()[0]
1324
+
1325
+ m3test = 1.0 * m3.numpy()
1326
+ m3test[0, ii, jj] -= dx
1327
+ wp.launch(
1328
+ kernel,
1329
+ dim=1,
1330
+ inputs=[wp.array(m3test, dtype=mat33, device=device)],
1331
+ outputs=[Qout, dout, outcomponents],
1332
+ device=device,
1333
+ )
1334
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1335
+ minusval = out.numpy()[0]
1336
+
1337
+ assert_np_equal((plusval - minusval) / (2 * dx), m3grads[ii, jj], tol=fdtol)
1338
+
1339
+
1340
+ def test_skew(test, device, dtype, register_kernels=False):
1341
+ rng = np.random.default_rng(123)
1342
+
1343
+ tol = {
1344
+ np.float16: 1.0e-3,
1345
+ np.float32: 1.0e-6,
1346
+ np.float64: 1.0e-8,
1347
+ }.get(dtype, 0)
1348
+
1349
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1350
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1351
+
1352
+ output_select_kernel = get_select_kernel(wptype)
1353
+
1354
+ def check_mat_skew(
1355
+ v3: wp.array(dtype=vec3),
1356
+ outcomponents: wp.array(dtype=wptype),
1357
+ ):
1358
+ m3result = wp.skew(v3[0])
1359
+
1360
+ # multiply outputs by 2 so we've got something to backpropagate:
1361
+ idx = 0
1362
+ for i in range(3):
1363
+ for j in range(3):
1364
+ outcomponents[idx] = wptype(2) * m3result[i, j]
1365
+ idx = idx + 1
1366
+
1367
+ kernel = getkernel(check_mat_skew, suffix=dtype.__name__)
1368
+
1369
+ if register_kernels:
1370
+ return
1371
+
1372
+ v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1373
+
1374
+ outcomponents = wp.zeros(3 * 3, dtype=wptype, requires_grad=True, device=device)
1375
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1376
+
1377
+ wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1378
+
1379
+ # make sure it gives you a cross product matrix:
1380
+ crossprodmat = outcomponents.numpy().reshape(3, 3)
1381
+ v = np.array([1, 0, 0])
1382
+ assert_np_equal(
1383
+ np.matmul(crossprodmat, np.array([1, 0, 0])).reshape(-1),
1384
+ 2 * np.cross(v3.numpy()[0], np.array([1, 0, 0])),
1385
+ tol=tol,
1386
+ )
1387
+ assert_np_equal(
1388
+ np.matmul(crossprodmat, np.array([0, 1, 0])).reshape(-1),
1389
+ 2 * np.cross(v3.numpy()[0], np.array([0, 1, 0])),
1390
+ tol=tol,
1391
+ )
1392
+ assert_np_equal(
1393
+ np.matmul(crossprodmat, np.array([0, 0, 1])).reshape(-1),
1394
+ 2 * np.cross(v3.numpy()[0], np.array([0, 0, 1])),
1395
+ tol=tol,
1396
+ )
1397
+
1398
+ # check it another way:
1399
+ x0 = v3.numpy()[0, 0]
1400
+ x1 = v3.numpy()[0, 1]
1401
+ x2 = v3.numpy()[0, 2]
1402
+ crossprodmat_expected = np.array(
1403
+ [
1404
+ [0, -x2, x1],
1405
+ [x2, 0, -x0],
1406
+ [-x1, x0, 0],
1407
+ ],
1408
+ dtype=dtype,
1409
+ )
1410
+ assert_np_equal(crossprodmat, 2 * crossprodmat_expected, tol=tol)
1411
+
1412
+ if dtype in np_float_types:
1413
+ idx = 0
1414
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1415
+
1416
+ for i in range(3):
1417
+ for j in range(3):
1418
+ tape = wp.Tape()
1419
+ with tape:
1420
+ wp.launch(kernel, dim=1, inputs=[v3], outputs=[outcomponents], device=device)
1421
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, idx], outputs=[out], device=device)
1422
+ tape.backward(loss=out)
1423
+ if i == j:
1424
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.zeros(3))
1425
+ elif [i, j] == [0, 1]:
1426
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, -2]))
1427
+ elif [i, j] == [1, 0]:
1428
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 0, 2]))
1429
+ elif [i, j] == [0, 2]:
1430
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, 2, 0]))
1431
+ elif [i, j] == [2, 0]:
1432
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([0, -2, 0]))
1433
+ elif [i, j] == [1, 2]:
1434
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([-2, 0, 0]))
1435
+ elif [i, j] == [2, 1]:
1436
+ assert_np_equal(tape.gradients[v3].numpy()[0], np.array([2, 0, 0]))
1437
+ tape.zero()
1438
+
1439
+ idx = idx + 1
1440
+
1441
+
1442
+ def test_transform_point(test, device, dtype, register_kernels=False):
1443
+ rng = np.random.default_rng(123)
1444
+
1445
+ tol = {
1446
+ np.float16: 5.0e-3,
1447
+ np.float32: 1.0e-6,
1448
+ np.float64: 1.0e-8,
1449
+ }.get(dtype, 0)
1450
+
1451
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1452
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1453
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1454
+
1455
+ output_select_kernel = get_select_kernel(wptype)
1456
+
1457
+ def check_mat_transform_point(
1458
+ v3: wp.array(dtype=vec3),
1459
+ m4: wp.array(dtype=mat44),
1460
+ outcomponents: wp.array(dtype=wptype),
1461
+ ):
1462
+ # multiply outputs by 2 so we've got something to backpropagate:
1463
+ presult = wptype(2) * wp.transform_point(m4[0], v3[0])
1464
+
1465
+ outcomponents[0] = presult[0]
1466
+ outcomponents[1] = presult[1]
1467
+ outcomponents[2] = presult[2]
1468
+
1469
+ kernel = getkernel(check_mat_transform_point, suffix=dtype.__name__)
1470
+
1471
+ if register_kernels:
1472
+ return
1473
+
1474
+ v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1475
+ m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1476
+
1477
+ outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1478
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1479
+
1480
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1481
+
1482
+ v3homog = np.ones(4, dtype=dtype)
1483
+ v3homog[:3] = v3.numpy()[0]
1484
+ assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1485
+
1486
+ if dtype in np_float_types:
1487
+ for j in range(3):
1488
+ tape = wp.Tape()
1489
+ with tape:
1490
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1491
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1492
+ tape.backward(loss=out)
1493
+
1494
+ assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1495
+ expected = np.zeros((4, 4), dtype=dtype)
1496
+ expected[j, :3] = 2 * v3.numpy()
1497
+ expected[j, 3] = 2
1498
+ assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1499
+
1500
+ tape.zero()
1501
+
1502
+
1503
+ def test_transform_vector(test, device, dtype, register_kernels=False):
1504
+ rng = np.random.default_rng(123)
1505
+
1506
+ tol = {
1507
+ np.float16: 5.0e-3,
1508
+ np.float32: 1.0e-6,
1509
+ np.float64: 1.0e-8,
1510
+ }.get(dtype, 0)
1511
+
1512
+ wptype = wp.types.np_dtype_to_warp_type[np.dtype(dtype)]
1513
+ vec3 = wp.types.vector(length=3, dtype=wptype)
1514
+ mat44 = wp.types.matrix(shape=(4, 4), dtype=wptype)
1515
+
1516
+ output_select_kernel = get_select_kernel(wptype)
1517
+
1518
+ def check_mat_transform_vector(
1519
+ v3: wp.array(dtype=vec3),
1520
+ m4: wp.array(dtype=mat44),
1521
+ outcomponents: wp.array(dtype=wptype),
1522
+ ):
1523
+ # multiply outputs by 2 so we've got something to backpropagate:
1524
+ presult = wptype(2) * wp.transform_vector(m4[0], v3[0])
1525
+
1526
+ outcomponents[0] = presult[0]
1527
+ outcomponents[1] = presult[1]
1528
+ outcomponents[2] = presult[2]
1529
+
1530
+ kernel = getkernel(check_mat_transform_vector, suffix=dtype.__name__)
1531
+
1532
+ if register_kernels:
1533
+ return
1534
+
1535
+ v3 = wp.array(randvals(rng, [1, 3], dtype), dtype=vec3, requires_grad=True, device=device)
1536
+ m4 = wp.array(randvals(rng, [1, 4, 4], dtype), dtype=mat44, requires_grad=True, device=device)
1537
+
1538
+ outcomponents = wp.zeros(3, dtype=wptype, requires_grad=True, device=device)
1539
+ out = wp.zeros(1, dtype=wptype, requires_grad=True, device=device)
1540
+
1541
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1542
+
1543
+ v3homog = np.zeros(4, dtype=dtype)
1544
+ v3homog[:3] = v3.numpy()[0]
1545
+ assert_np_equal(outcomponents.numpy(), 2 * np.matmul(m4.numpy()[0], v3homog)[:3], tol=10 * tol)
1546
+
1547
+ if dtype in np_float_types:
1548
+ for j in range(3):
1549
+ tape = wp.Tape()
1550
+ with tape:
1551
+ wp.launch(kernel, dim=1, inputs=[v3, m4], outputs=[outcomponents], device=device)
1552
+ wp.launch(output_select_kernel, dim=1, inputs=[outcomponents, j], outputs=[out], device=device)
1553
+ tape.backward(loss=out)
1554
+
1555
+ assert_np_equal(2 * m4.numpy()[0, j, :3], tape.gradients[v3].numpy(), tol=tol)
1556
+ expected = np.zeros((4, 4), dtype=dtype)
1557
+ expected[j, :3] = 2 * v3.numpy()
1558
+ assert_np_equal(tape.gradients[m4].numpy(), expected, tol=tol)
1559
+
1560
+ tape.zero()
1561
+
1562
+
1563
+ # Test matrix constructors using explicit type (float16)
1564
+ # note that these tests are specifically not using generics / closure
1565
+ # args to create kernels dynamically (like the rest of this file)
1566
+ # as those use different code paths to resolve arg types which
1567
+ # has lead to regressions.
1568
+ @wp.kernel
1569
+ def test_constructors_explicit_precision():
1570
+ # construction for custom matrix types
1571
+ eye = wp.identity(dtype=wp.float16, n=2)
1572
+ zeros = wp.matrix(shape=(2, 2), dtype=wp.float16)
1573
+ custom = wp.matrix(wp.float16(0.0), wp.float16(1.0), wp.float16(2.0), wp.float16(3.0), shape=(2, 2))
1574
+
1575
+ for i in range(2):
1576
+ for j in range(2):
1577
+ if i == j:
1578
+ wp.expect_eq(eye[i, j], wp.float16(1.0))
1579
+ else:
1580
+ wp.expect_eq(eye[i, j], wp.float16(0.0))
1581
+
1582
+ wp.expect_eq(zeros[i, j], wp.float16(0.0))
1583
+ wp.expect_eq(custom[i, j], wp.float16(i) * wp.float16(2.0) + wp.float16(j))
1584
+
1585
+
1586
+ mat32d = wp.mat(shape=(3, 2), dtype=wp.float64)
1587
+
1588
+
1589
+ @wp.kernel
1590
+ def test_matrix_constructor_value_func():
1591
+ a = wp.mat22()
1592
+ b = wp.matrix(a, shape=(2, 2))
1593
+ c = mat32d()
1594
+ d = mat32d(c, shape=(3, 2))
1595
+ e = mat32d(wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0), wp.float64(1.0), wp.float64(2.0))
1596
+ f = mat32d(
1597
+ wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1598
+ wp.vec3d(wp.float64(1.0), wp.float64(2.0), wp.float64(3.0)),
1599
+ )
1600
+
1601
+
1602
+ # Same as above but with a default (float/int) type
1603
+ # which tests some different code paths that
1604
+ # need to ensure types are correctly canonicalized
1605
+ # during codegen
1606
+ @wp.kernel
1607
+ def test_constructors_default_precision():
1608
+ # construction for default (float) matrix types
1609
+ eye = wp.identity(dtype=float, n=2)
1610
+ zeros = wp.matrix(shape=(2, 2), dtype=float)
1611
+ custom = wp.matrix(0.0, 1.0, 2.0, 3.0, shape=(2, 2))
1612
+
1613
+ for i in range(2):
1614
+ for j in range(2):
1615
+ if i == j:
1616
+ wp.expect_eq(eye[i, j], 1.0)
1617
+ else:
1618
+ wp.expect_eq(eye[i, j], 0.0)
1619
+
1620
+ wp.expect_eq(zeros[i, j], 0.0)
1621
+ wp.expect_eq(custom[i, j], float(i) * 2.0 + float(j))
1622
+
1623
+
1624
+ @wp.kernel
1625
+ def test_matrix_mutation(expected: wp.types.matrix(shape=(10, 3), dtype=float)):
1626
+ m = wp.matrix(shape=(10, 3), dtype=float)
1627
+
1628
+ # test direct element indexing
1629
+ m[0, 0] = 1.0
1630
+ m[0, 1] = 2.0
1631
+ m[0, 2] = 3.0
1632
+
1633
+ # The nested indexing (matrix->vector->scalar) below does not
1634
+ # currently modify m because m[0] returns row vector by
1635
+ # value rather than reference, this is different from NumPy
1636
+ # which always returns by ref. Not clear how we can support
1637
+ # this as well as auto-diff.
1638
+
1639
+ # m[0][1] = 2.0
1640
+ # m[0][2] = 3.0
1641
+
1642
+ # test setting rows
1643
+ for i in range(1, 10):
1644
+ m[i] = m[i - 1] + wp.vec3(1.0, 2.0, 3.0)
1645
+
1646
+ wp.expect_eq(m, expected)
1647
+
1648
+
1649
+ CONSTANT_SHAPE_ROWS = wp.constant(10)
1650
+ CONSTANT_SHAPE_COLS = wp.constant(10)
1651
+
1652
+
1653
+ # tests that we can use global constants in shape keyword argument
1654
+ # for matrix constructor
1655
+ @wp.kernel
1656
+ def test_constructors_constant_shape():
1657
+ m = wp.matrix(shape=(CONSTANT_SHAPE_ROWS, CONSTANT_SHAPE_COLS), dtype=float)
1658
+
1659
+ for i in range(CONSTANT_SHAPE_ROWS):
1660
+ for j in range(CONSTANT_SHAPE_COLS):
1661
+ m[i, j] = float(i * j)
1662
+
1663
+
1664
+ devices = get_test_devices()
1665
+
1666
+
1667
+ class TestMat(unittest.TestCase):
1668
+ def test_tpl_ops_with_anon(self):
1669
+ mat22f = wp.mat((2, 2), dtype=float)
1670
+
1671
+ m = wp.mat22f(1.0, 2.0, 3.0, 4.0)
1672
+ m += mat22f(2.0, 3.0, 4.0, 5.0)
1673
+ m -= mat22f(3.0, 4.0, 5.0, 6.0)
1674
+ self.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
1675
+
1676
+ m = mat22f(1.0, 2.0, 3.0, 4.0)
1677
+ m += wp.mat22f(2.0, 3.0, 4.0, 5.0)
1678
+ m -= wp.mat22f(3.0, 4.0, 5.0, 6.0)
1679
+ self.assertSequenceEqual(m, ((0.0, 1.0), (2.0, 3.0)))
1680
+
1681
+
1682
+ add_kernel_test(TestMat, test_constructors_explicit_precision, dim=1, devices=devices)
1683
+ add_kernel_test(TestMat, test_constructors_default_precision, dim=1, devices=devices)
1684
+ add_kernel_test(TestMat, test_constructors_constant_shape, dim=1, devices=devices)
1685
+ add_kernel_test(TestMat, test_matrix_constructor_value_func, dim=1, devices=devices)
1686
+
1687
+ mat103 = wp.types.matrix(shape=(10, 3), dtype=float)
1688
+ add_kernel_test(
1689
+ TestMat,
1690
+ test_matrix_mutation,
1691
+ dim=1,
1692
+ inputs=[
1693
+ mat103(
1694
+ 1.0, 2.0, 3.0,
1695
+ 2.0, 4.0, 6.0,
1696
+ 3.0, 6.0, 9.0,
1697
+ 4.0, 8.0, 12.0,
1698
+ 5.0, 10.0, 15.0,
1699
+ 6.0, 12.0, 18.0,
1700
+ 7.0, 14.0, 21.0,
1701
+ 8.0, 16.0, 24.0,
1702
+ 9.0, 18.0, 27.0,
1703
+ 10.0, 20.0, 30.0,
1704
+ )
1705
+ ],
1706
+ devices=devices,
1707
+ ) # fmt: skip
1708
+
1709
+ for dtype in np_signed_int_types + np_float_types:
1710
+ add_function_test_register_kernel(
1711
+ TestMat, f"test_negation_{dtype.__name__}", test_negation, devices=devices, dtype=dtype
1712
+ )
1713
+ add_function_test_register_kernel(
1714
+ TestMat, f"test_subtraction_{dtype.__name__}", test_subtraction, devices=devices, dtype=dtype
1715
+ )
1716
+
1717
+ add_function_test(
1718
+ TestMat,
1719
+ "test_anon_constructor_error_shape_keyword_missing",
1720
+ test_anon_constructor_error_shape_keyword_missing,
1721
+ devices=devices,
1722
+ )
1723
+ add_function_test(
1724
+ TestMat,
1725
+ "test_anon_constructor_error_dtype_keyword_missing",
1726
+ test_anon_constructor_error_dtype_keyword_missing,
1727
+ devices=devices,
1728
+ )
1729
+ add_function_test(
1730
+ TestMat,
1731
+ "test_anon_constructor_error_shape_mismatch",
1732
+ test_anon_constructor_error_shape_mismatch,
1733
+ devices=devices,
1734
+ )
1735
+ add_function_test(
1736
+ TestMat,
1737
+ "test_anon_constructor_error_invalid_arg_count",
1738
+ test_anon_constructor_error_invalid_arg_count,
1739
+ devices=devices,
1740
+ )
1741
+ add_function_test(
1742
+ TestMat,
1743
+ "test_tpl_constructor_error_incompatible_sizes",
1744
+ test_tpl_constructor_error_incompatible_sizes,
1745
+ devices=devices,
1746
+ )
1747
+ add_function_test(
1748
+ TestMat,
1749
+ "test_tpl_constructor_error_invalid_scalar_type",
1750
+ test_tpl_constructor_error_invalid_scalar_type,
1751
+ devices=devices,
1752
+ )
1753
+ add_function_test(
1754
+ TestMat,
1755
+ "test_tpl_constructor_error_invalid_vector_count",
1756
+ test_tpl_constructor_error_invalid_vector_count,
1757
+ devices=devices,
1758
+ )
1759
+ add_function_test(
1760
+ TestMat,
1761
+ "test_tpl_constructor_error_invalid_vector_shape",
1762
+ test_tpl_constructor_error_invalid_vector_shape,
1763
+ devices=devices,
1764
+ )
1765
+ add_function_test(
1766
+ TestMat,
1767
+ "test_tpl_constructor_error_invalid_arg_count",
1768
+ test_tpl_constructor_error_invalid_arg_count,
1769
+ devices=devices,
1770
+ )
1771
+
1772
+ for dtype in np_float_types:
1773
+ add_function_test(
1774
+ TestMat, f"test_py_arithmetic_ops_{dtype.__name__}", test_py_arithmetic_ops, devices=None, dtype=dtype
1775
+ )
1776
+ add_function_test_register_kernel(
1777
+ TestMat, f"test_quat_constructor_{dtype.__name__}", test_quat_constructor, devices=devices, dtype=dtype
1778
+ )
1779
+ add_function_test_register_kernel(
1780
+ TestMat, f"test_inverse_{dtype.__name__}", test_inverse, devices=devices, dtype=dtype
1781
+ )
1782
+ add_function_test_register_kernel(TestMat, f"test_svd_{dtype.__name__}", test_svd, devices=devices, dtype=dtype)
1783
+ add_function_test_register_kernel(TestMat, f"test_qr_{dtype.__name__}", test_qr, devices=devices, dtype=dtype)
1784
+ add_function_test_register_kernel(TestMat, f"test_eig_{dtype.__name__}", test_eig, devices=devices, dtype=dtype)
1785
+ add_function_test_register_kernel(
1786
+ TestMat, f"test_transform_point_{dtype.__name__}", test_transform_point, devices=devices, dtype=dtype
1787
+ )
1788
+ add_function_test_register_kernel(
1789
+ TestMat, f"test_transform_vector_{dtype.__name__}", test_transform_vector, devices=devices, dtype=dtype
1790
+ )
1791
+ add_function_test_register_kernel(
1792
+ TestMat, f"test_determinant_{dtype.__name__}", test_determinant, devices=devices, dtype=dtype
1793
+ )
1794
+ add_function_test_register_kernel(TestMat, f"test_skew_{dtype.__name__}", test_skew, devices=devices, dtype=dtype)
1795
+
1796
+
1797
+ if __name__ == "__main__":
1798
+ wp.build.clear_kernel_cache()
1799
+ unittest.main(verbosity=2, failfast=True)