warp-lang 1.7.0__py3-none-manylinux_2_34_aarch64.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 (429) hide show
  1. warp/__init__.py +139 -0
  2. warp/__init__.pyi +1 -0
  3. warp/autograd.py +1142 -0
  4. warp/bin/warp-clang.so +0 -0
  5. warp/bin/warp.so +0 -0
  6. warp/build.py +557 -0
  7. warp/build_dll.py +405 -0
  8. warp/builtins.py +6855 -0
  9. warp/codegen.py +3969 -0
  10. warp/config.py +158 -0
  11. warp/constants.py +57 -0
  12. warp/context.py +6812 -0
  13. warp/dlpack.py +462 -0
  14. warp/examples/__init__.py +24 -0
  15. warp/examples/assets/bear.usd +0 -0
  16. warp/examples/assets/bunny.usd +0 -0
  17. warp/examples/assets/cartpole.urdf +110 -0
  18. warp/examples/assets/crazyflie.usd +0 -0
  19. warp/examples/assets/cube.usd +0 -0
  20. warp/examples/assets/nonuniform.usd +0 -0
  21. warp/examples/assets/nv_ant.xml +92 -0
  22. warp/examples/assets/nv_humanoid.xml +183 -0
  23. warp/examples/assets/nvidia_logo.png +0 -0
  24. warp/examples/assets/pixel.jpg +0 -0
  25. warp/examples/assets/quadruped.urdf +268 -0
  26. warp/examples/assets/rocks.nvdb +0 -0
  27. warp/examples/assets/rocks.usd +0 -0
  28. warp/examples/assets/sphere.usd +0 -0
  29. warp/examples/assets/square_cloth.usd +0 -0
  30. warp/examples/benchmarks/benchmark_api.py +389 -0
  31. warp/examples/benchmarks/benchmark_cloth.py +296 -0
  32. warp/examples/benchmarks/benchmark_cloth_cupy.py +96 -0
  33. warp/examples/benchmarks/benchmark_cloth_jax.py +105 -0
  34. warp/examples/benchmarks/benchmark_cloth_numba.py +161 -0
  35. warp/examples/benchmarks/benchmark_cloth_numpy.py +85 -0
  36. warp/examples/benchmarks/benchmark_cloth_paddle.py +94 -0
  37. warp/examples/benchmarks/benchmark_cloth_pytorch.py +94 -0
  38. warp/examples/benchmarks/benchmark_cloth_taichi.py +120 -0
  39. warp/examples/benchmarks/benchmark_cloth_warp.py +153 -0
  40. warp/examples/benchmarks/benchmark_gemm.py +164 -0
  41. warp/examples/benchmarks/benchmark_interop_paddle.py +166 -0
  42. warp/examples/benchmarks/benchmark_interop_torch.py +166 -0
  43. warp/examples/benchmarks/benchmark_launches.py +301 -0
  44. warp/examples/benchmarks/benchmark_tile_load_store.py +103 -0
  45. warp/examples/browse.py +37 -0
  46. warp/examples/core/example_cupy.py +86 -0
  47. warp/examples/core/example_dem.py +241 -0
  48. warp/examples/core/example_fluid.py +299 -0
  49. warp/examples/core/example_graph_capture.py +150 -0
  50. warp/examples/core/example_marching_cubes.py +194 -0
  51. warp/examples/core/example_mesh.py +180 -0
  52. warp/examples/core/example_mesh_intersect.py +211 -0
  53. warp/examples/core/example_nvdb.py +182 -0
  54. warp/examples/core/example_raycast.py +111 -0
  55. warp/examples/core/example_raymarch.py +205 -0
  56. warp/examples/core/example_render_opengl.py +193 -0
  57. warp/examples/core/example_sample_mesh.py +300 -0
  58. warp/examples/core/example_sph.py +411 -0
  59. warp/examples/core/example_torch.py +211 -0
  60. warp/examples/core/example_wave.py +269 -0
  61. warp/examples/fem/example_adaptive_grid.py +286 -0
  62. warp/examples/fem/example_apic_fluid.py +423 -0
  63. warp/examples/fem/example_burgers.py +261 -0
  64. warp/examples/fem/example_convection_diffusion.py +178 -0
  65. warp/examples/fem/example_convection_diffusion_dg.py +204 -0
  66. warp/examples/fem/example_deformed_geometry.py +172 -0
  67. warp/examples/fem/example_diffusion.py +196 -0
  68. warp/examples/fem/example_diffusion_3d.py +225 -0
  69. warp/examples/fem/example_diffusion_mgpu.py +220 -0
  70. warp/examples/fem/example_distortion_energy.py +228 -0
  71. warp/examples/fem/example_magnetostatics.py +240 -0
  72. warp/examples/fem/example_mixed_elasticity.py +291 -0
  73. warp/examples/fem/example_navier_stokes.py +261 -0
  74. warp/examples/fem/example_nonconforming_contact.py +298 -0
  75. warp/examples/fem/example_stokes.py +213 -0
  76. warp/examples/fem/example_stokes_transfer.py +262 -0
  77. warp/examples/fem/example_streamlines.py +352 -0
  78. warp/examples/fem/utils.py +1000 -0
  79. warp/examples/interop/example_jax_callable.py +116 -0
  80. warp/examples/interop/example_jax_ffi_callback.py +132 -0
  81. warp/examples/interop/example_jax_kernel.py +205 -0
  82. warp/examples/optim/example_bounce.py +266 -0
  83. warp/examples/optim/example_cloth_throw.py +228 -0
  84. warp/examples/optim/example_diffray.py +561 -0
  85. warp/examples/optim/example_drone.py +870 -0
  86. warp/examples/optim/example_fluid_checkpoint.py +497 -0
  87. warp/examples/optim/example_inverse_kinematics.py +182 -0
  88. warp/examples/optim/example_inverse_kinematics_torch.py +191 -0
  89. warp/examples/optim/example_softbody_properties.py +400 -0
  90. warp/examples/optim/example_spring_cage.py +245 -0
  91. warp/examples/optim/example_trajectory.py +227 -0
  92. warp/examples/sim/example_cartpole.py +143 -0
  93. warp/examples/sim/example_cloth.py +225 -0
  94. warp/examples/sim/example_cloth_self_contact.py +322 -0
  95. warp/examples/sim/example_granular.py +130 -0
  96. warp/examples/sim/example_granular_collision_sdf.py +202 -0
  97. warp/examples/sim/example_jacobian_ik.py +244 -0
  98. warp/examples/sim/example_particle_chain.py +124 -0
  99. warp/examples/sim/example_quadruped.py +203 -0
  100. warp/examples/sim/example_rigid_chain.py +203 -0
  101. warp/examples/sim/example_rigid_contact.py +195 -0
  102. warp/examples/sim/example_rigid_force.py +133 -0
  103. warp/examples/sim/example_rigid_gyroscopic.py +115 -0
  104. warp/examples/sim/example_rigid_soft_contact.py +140 -0
  105. warp/examples/sim/example_soft_body.py +196 -0
  106. warp/examples/tile/example_tile_cholesky.py +87 -0
  107. warp/examples/tile/example_tile_convolution.py +66 -0
  108. warp/examples/tile/example_tile_fft.py +55 -0
  109. warp/examples/tile/example_tile_filtering.py +113 -0
  110. warp/examples/tile/example_tile_matmul.py +85 -0
  111. warp/examples/tile/example_tile_mlp.py +383 -0
  112. warp/examples/tile/example_tile_nbody.py +199 -0
  113. warp/examples/tile/example_tile_walker.py +327 -0
  114. warp/fabric.py +355 -0
  115. warp/fem/__init__.py +106 -0
  116. warp/fem/adaptivity.py +508 -0
  117. warp/fem/cache.py +572 -0
  118. warp/fem/dirichlet.py +202 -0
  119. warp/fem/domain.py +411 -0
  120. warp/fem/field/__init__.py +125 -0
  121. warp/fem/field/field.py +619 -0
  122. warp/fem/field/nodal_field.py +326 -0
  123. warp/fem/field/restriction.py +37 -0
  124. warp/fem/field/virtual.py +848 -0
  125. warp/fem/geometry/__init__.py +32 -0
  126. warp/fem/geometry/adaptive_nanogrid.py +857 -0
  127. warp/fem/geometry/closest_point.py +84 -0
  128. warp/fem/geometry/deformed_geometry.py +221 -0
  129. warp/fem/geometry/element.py +776 -0
  130. warp/fem/geometry/geometry.py +362 -0
  131. warp/fem/geometry/grid_2d.py +392 -0
  132. warp/fem/geometry/grid_3d.py +452 -0
  133. warp/fem/geometry/hexmesh.py +911 -0
  134. warp/fem/geometry/nanogrid.py +571 -0
  135. warp/fem/geometry/partition.py +389 -0
  136. warp/fem/geometry/quadmesh.py +663 -0
  137. warp/fem/geometry/tetmesh.py +855 -0
  138. warp/fem/geometry/trimesh.py +806 -0
  139. warp/fem/integrate.py +2335 -0
  140. warp/fem/linalg.py +419 -0
  141. warp/fem/operator.py +293 -0
  142. warp/fem/polynomial.py +229 -0
  143. warp/fem/quadrature/__init__.py +17 -0
  144. warp/fem/quadrature/pic_quadrature.py +299 -0
  145. warp/fem/quadrature/quadrature.py +591 -0
  146. warp/fem/space/__init__.py +228 -0
  147. warp/fem/space/basis_function_space.py +468 -0
  148. warp/fem/space/basis_space.py +667 -0
  149. warp/fem/space/dof_mapper.py +251 -0
  150. warp/fem/space/function_space.py +309 -0
  151. warp/fem/space/grid_2d_function_space.py +177 -0
  152. warp/fem/space/grid_3d_function_space.py +227 -0
  153. warp/fem/space/hexmesh_function_space.py +257 -0
  154. warp/fem/space/nanogrid_function_space.py +201 -0
  155. warp/fem/space/partition.py +367 -0
  156. warp/fem/space/quadmesh_function_space.py +223 -0
  157. warp/fem/space/restriction.py +179 -0
  158. warp/fem/space/shape/__init__.py +143 -0
  159. warp/fem/space/shape/cube_shape_function.py +1105 -0
  160. warp/fem/space/shape/shape_function.py +133 -0
  161. warp/fem/space/shape/square_shape_function.py +926 -0
  162. warp/fem/space/shape/tet_shape_function.py +834 -0
  163. warp/fem/space/shape/triangle_shape_function.py +672 -0
  164. warp/fem/space/tetmesh_function_space.py +271 -0
  165. warp/fem/space/topology.py +424 -0
  166. warp/fem/space/trimesh_function_space.py +194 -0
  167. warp/fem/types.py +99 -0
  168. warp/fem/utils.py +420 -0
  169. warp/jax.py +187 -0
  170. warp/jax_experimental/__init__.py +16 -0
  171. warp/jax_experimental/custom_call.py +351 -0
  172. warp/jax_experimental/ffi.py +698 -0
  173. warp/jax_experimental/xla_ffi.py +602 -0
  174. warp/math.py +244 -0
  175. warp/native/array.h +1145 -0
  176. warp/native/builtin.h +1800 -0
  177. warp/native/bvh.cpp +492 -0
  178. warp/native/bvh.cu +791 -0
  179. warp/native/bvh.h +554 -0
  180. warp/native/clang/clang.cpp +536 -0
  181. warp/native/coloring.cpp +613 -0
  182. warp/native/crt.cpp +51 -0
  183. warp/native/crt.h +362 -0
  184. warp/native/cuda_crt.h +1058 -0
  185. warp/native/cuda_util.cpp +646 -0
  186. warp/native/cuda_util.h +307 -0
  187. warp/native/error.cpp +77 -0
  188. warp/native/error.h +36 -0
  189. warp/native/exports.h +1878 -0
  190. warp/native/fabric.h +245 -0
  191. warp/native/hashgrid.cpp +311 -0
  192. warp/native/hashgrid.cu +87 -0
  193. warp/native/hashgrid.h +240 -0
  194. warp/native/initializer_array.h +41 -0
  195. warp/native/intersect.h +1230 -0
  196. warp/native/intersect_adj.h +375 -0
  197. warp/native/intersect_tri.h +339 -0
  198. warp/native/marching.cpp +19 -0
  199. warp/native/marching.cu +514 -0
  200. warp/native/marching.h +19 -0
  201. warp/native/mat.h +2220 -0
  202. warp/native/mathdx.cpp +87 -0
  203. warp/native/matnn.h +343 -0
  204. warp/native/mesh.cpp +266 -0
  205. warp/native/mesh.cu +404 -0
  206. warp/native/mesh.h +1980 -0
  207. warp/native/nanovdb/GridHandle.h +366 -0
  208. warp/native/nanovdb/HostBuffer.h +590 -0
  209. warp/native/nanovdb/NanoVDB.h +6624 -0
  210. warp/native/nanovdb/PNanoVDB.h +3390 -0
  211. warp/native/noise.h +859 -0
  212. warp/native/quat.h +1371 -0
  213. warp/native/rand.h +342 -0
  214. warp/native/range.h +139 -0
  215. warp/native/reduce.cpp +174 -0
  216. warp/native/reduce.cu +364 -0
  217. warp/native/runlength_encode.cpp +79 -0
  218. warp/native/runlength_encode.cu +61 -0
  219. warp/native/scan.cpp +47 -0
  220. warp/native/scan.cu +53 -0
  221. warp/native/scan.h +23 -0
  222. warp/native/solid_angle.h +466 -0
  223. warp/native/sort.cpp +251 -0
  224. warp/native/sort.cu +277 -0
  225. warp/native/sort.h +33 -0
  226. warp/native/sparse.cpp +378 -0
  227. warp/native/sparse.cu +524 -0
  228. warp/native/spatial.h +657 -0
  229. warp/native/svd.h +702 -0
  230. warp/native/temp_buffer.h +46 -0
  231. warp/native/tile.h +2584 -0
  232. warp/native/tile_reduce.h +264 -0
  233. warp/native/vec.h +1426 -0
  234. warp/native/volume.cpp +501 -0
  235. warp/native/volume.cu +67 -0
  236. warp/native/volume.h +969 -0
  237. warp/native/volume_builder.cu +477 -0
  238. warp/native/volume_builder.h +52 -0
  239. warp/native/volume_impl.h +70 -0
  240. warp/native/warp.cpp +1082 -0
  241. warp/native/warp.cu +3636 -0
  242. warp/native/warp.h +381 -0
  243. warp/optim/__init__.py +17 -0
  244. warp/optim/adam.py +163 -0
  245. warp/optim/linear.py +1137 -0
  246. warp/optim/sgd.py +112 -0
  247. warp/paddle.py +407 -0
  248. warp/render/__init__.py +18 -0
  249. warp/render/render_opengl.py +3518 -0
  250. warp/render/render_usd.py +784 -0
  251. warp/render/utils.py +160 -0
  252. warp/sim/__init__.py +65 -0
  253. warp/sim/articulation.py +793 -0
  254. warp/sim/collide.py +2395 -0
  255. warp/sim/graph_coloring.py +300 -0
  256. warp/sim/import_mjcf.py +790 -0
  257. warp/sim/import_snu.py +227 -0
  258. warp/sim/import_urdf.py +579 -0
  259. warp/sim/import_usd.py +894 -0
  260. warp/sim/inertia.py +324 -0
  261. warp/sim/integrator.py +242 -0
  262. warp/sim/integrator_euler.py +1997 -0
  263. warp/sim/integrator_featherstone.py +2101 -0
  264. warp/sim/integrator_vbd.py +2048 -0
  265. warp/sim/integrator_xpbd.py +3292 -0
  266. warp/sim/model.py +4791 -0
  267. warp/sim/particles.py +121 -0
  268. warp/sim/render.py +427 -0
  269. warp/sim/utils.py +428 -0
  270. warp/sparse.py +2057 -0
  271. warp/stubs.py +3333 -0
  272. warp/tape.py +1203 -0
  273. warp/tests/__init__.py +1 -0
  274. warp/tests/__main__.py +4 -0
  275. warp/tests/assets/curlnoise_golden.npy +0 -0
  276. warp/tests/assets/mlp_golden.npy +0 -0
  277. warp/tests/assets/pixel.npy +0 -0
  278. warp/tests/assets/pnoise_golden.npy +0 -0
  279. warp/tests/assets/spiky.usd +0 -0
  280. warp/tests/assets/test_grid.nvdb +0 -0
  281. warp/tests/assets/test_index_grid.nvdb +0 -0
  282. warp/tests/assets/test_int32_grid.nvdb +0 -0
  283. warp/tests/assets/test_vec_grid.nvdb +0 -0
  284. warp/tests/assets/torus.nvdb +0 -0
  285. warp/tests/assets/torus.usda +105 -0
  286. warp/tests/aux_test_class_kernel.py +34 -0
  287. warp/tests/aux_test_compile_consts_dummy.py +18 -0
  288. warp/tests/aux_test_conditional_unequal_types_kernels.py +29 -0
  289. warp/tests/aux_test_dependent.py +29 -0
  290. warp/tests/aux_test_grad_customs.py +29 -0
  291. warp/tests/aux_test_instancing_gc.py +26 -0
  292. warp/tests/aux_test_module_unload.py +23 -0
  293. warp/tests/aux_test_name_clash1.py +40 -0
  294. warp/tests/aux_test_name_clash2.py +40 -0
  295. warp/tests/aux_test_reference.py +9 -0
  296. warp/tests/aux_test_reference_reference.py +8 -0
  297. warp/tests/aux_test_square.py +16 -0
  298. warp/tests/aux_test_unresolved_func.py +22 -0
  299. warp/tests/aux_test_unresolved_symbol.py +22 -0
  300. warp/tests/cuda/__init__.py +0 -0
  301. warp/tests/cuda/test_async.py +676 -0
  302. warp/tests/cuda/test_ipc.py +124 -0
  303. warp/tests/cuda/test_mempool.py +233 -0
  304. warp/tests/cuda/test_multigpu.py +169 -0
  305. warp/tests/cuda/test_peer.py +139 -0
  306. warp/tests/cuda/test_pinned.py +84 -0
  307. warp/tests/cuda/test_streams.py +634 -0
  308. warp/tests/geometry/__init__.py +0 -0
  309. warp/tests/geometry/test_bvh.py +200 -0
  310. warp/tests/geometry/test_hash_grid.py +221 -0
  311. warp/tests/geometry/test_marching_cubes.py +74 -0
  312. warp/tests/geometry/test_mesh.py +316 -0
  313. warp/tests/geometry/test_mesh_query_aabb.py +399 -0
  314. warp/tests/geometry/test_mesh_query_point.py +932 -0
  315. warp/tests/geometry/test_mesh_query_ray.py +311 -0
  316. warp/tests/geometry/test_volume.py +1103 -0
  317. warp/tests/geometry/test_volume_write.py +346 -0
  318. warp/tests/interop/__init__.py +0 -0
  319. warp/tests/interop/test_dlpack.py +729 -0
  320. warp/tests/interop/test_jax.py +371 -0
  321. warp/tests/interop/test_paddle.py +800 -0
  322. warp/tests/interop/test_torch.py +1001 -0
  323. warp/tests/run_coverage_serial.py +39 -0
  324. warp/tests/sim/__init__.py +0 -0
  325. warp/tests/sim/disabled_kinematics.py +244 -0
  326. warp/tests/sim/flaky_test_sim_grad.py +290 -0
  327. warp/tests/sim/test_collision.py +604 -0
  328. warp/tests/sim/test_coloring.py +258 -0
  329. warp/tests/sim/test_model.py +224 -0
  330. warp/tests/sim/test_sim_grad_bounce_linear.py +212 -0
  331. warp/tests/sim/test_sim_kinematics.py +98 -0
  332. warp/tests/sim/test_vbd.py +597 -0
  333. warp/tests/test_adam.py +163 -0
  334. warp/tests/test_arithmetic.py +1096 -0
  335. warp/tests/test_array.py +2972 -0
  336. warp/tests/test_array_reduce.py +156 -0
  337. warp/tests/test_assert.py +250 -0
  338. warp/tests/test_atomic.py +153 -0
  339. warp/tests/test_bool.py +220 -0
  340. warp/tests/test_builtins_resolution.py +1298 -0
  341. warp/tests/test_closest_point_edge_edge.py +327 -0
  342. warp/tests/test_codegen.py +810 -0
  343. warp/tests/test_codegen_instancing.py +1495 -0
  344. warp/tests/test_compile_consts.py +215 -0
  345. warp/tests/test_conditional.py +252 -0
  346. warp/tests/test_context.py +42 -0
  347. warp/tests/test_copy.py +238 -0
  348. warp/tests/test_ctypes.py +638 -0
  349. warp/tests/test_dense.py +73 -0
  350. warp/tests/test_devices.py +97 -0
  351. warp/tests/test_examples.py +482 -0
  352. warp/tests/test_fabricarray.py +996 -0
  353. warp/tests/test_fast_math.py +74 -0
  354. warp/tests/test_fem.py +2003 -0
  355. warp/tests/test_fp16.py +136 -0
  356. warp/tests/test_func.py +454 -0
  357. warp/tests/test_future_annotations.py +98 -0
  358. warp/tests/test_generics.py +656 -0
  359. warp/tests/test_grad.py +893 -0
  360. warp/tests/test_grad_customs.py +339 -0
  361. warp/tests/test_grad_debug.py +341 -0
  362. warp/tests/test_implicit_init.py +411 -0
  363. warp/tests/test_import.py +45 -0
  364. warp/tests/test_indexedarray.py +1140 -0
  365. warp/tests/test_intersect.py +73 -0
  366. warp/tests/test_iter.py +76 -0
  367. warp/tests/test_large.py +177 -0
  368. warp/tests/test_launch.py +411 -0
  369. warp/tests/test_lerp.py +151 -0
  370. warp/tests/test_linear_solvers.py +193 -0
  371. warp/tests/test_lvalue.py +427 -0
  372. warp/tests/test_mat.py +2089 -0
  373. warp/tests/test_mat_lite.py +122 -0
  374. warp/tests/test_mat_scalar_ops.py +2913 -0
  375. warp/tests/test_math.py +178 -0
  376. warp/tests/test_mlp.py +282 -0
  377. warp/tests/test_module_hashing.py +258 -0
  378. warp/tests/test_modules_lite.py +44 -0
  379. warp/tests/test_noise.py +252 -0
  380. warp/tests/test_operators.py +299 -0
  381. warp/tests/test_options.py +129 -0
  382. warp/tests/test_overwrite.py +551 -0
  383. warp/tests/test_print.py +339 -0
  384. warp/tests/test_quat.py +2315 -0
  385. warp/tests/test_rand.py +339 -0
  386. warp/tests/test_reload.py +302 -0
  387. warp/tests/test_rounding.py +185 -0
  388. warp/tests/test_runlength_encode.py +196 -0
  389. warp/tests/test_scalar_ops.py +105 -0
  390. warp/tests/test_smoothstep.py +108 -0
  391. warp/tests/test_snippet.py +318 -0
  392. warp/tests/test_sparse.py +582 -0
  393. warp/tests/test_spatial.py +2229 -0
  394. warp/tests/test_special_values.py +361 -0
  395. warp/tests/test_static.py +592 -0
  396. warp/tests/test_struct.py +734 -0
  397. warp/tests/test_tape.py +204 -0
  398. warp/tests/test_transient_module.py +93 -0
  399. warp/tests/test_triangle_closest_point.py +145 -0
  400. warp/tests/test_types.py +562 -0
  401. warp/tests/test_utils.py +588 -0
  402. warp/tests/test_vec.py +1487 -0
  403. warp/tests/test_vec_lite.py +80 -0
  404. warp/tests/test_vec_scalar_ops.py +2327 -0
  405. warp/tests/test_verify_fp.py +100 -0
  406. warp/tests/tile/__init__.py +0 -0
  407. warp/tests/tile/test_tile.py +780 -0
  408. warp/tests/tile/test_tile_load.py +407 -0
  409. warp/tests/tile/test_tile_mathdx.py +208 -0
  410. warp/tests/tile/test_tile_mlp.py +402 -0
  411. warp/tests/tile/test_tile_reduce.py +447 -0
  412. warp/tests/tile/test_tile_shared_memory.py +247 -0
  413. warp/tests/tile/test_tile_view.py +173 -0
  414. warp/tests/unittest_serial.py +47 -0
  415. warp/tests/unittest_suites.py +427 -0
  416. warp/tests/unittest_utils.py +468 -0
  417. warp/tests/walkthrough_debug.py +93 -0
  418. warp/thirdparty/__init__.py +0 -0
  419. warp/thirdparty/appdirs.py +598 -0
  420. warp/thirdparty/dlpack.py +145 -0
  421. warp/thirdparty/unittest_parallel.py +570 -0
  422. warp/torch.py +391 -0
  423. warp/types.py +5230 -0
  424. warp/utils.py +1137 -0
  425. warp_lang-1.7.0.dist-info/METADATA +516 -0
  426. warp_lang-1.7.0.dist-info/RECORD +429 -0
  427. warp_lang-1.7.0.dist-info/WHEEL +5 -0
  428. warp_lang-1.7.0.dist-info/licenses/LICENSE.md +202 -0
  429. warp_lang-1.7.0.dist-info/top_level.txt +1 -0
warp/tape.py ADDED
@@ -0,0 +1,1203 @@
1
+ # SPDX-FileCopyrightText: Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from collections import defaultdict, namedtuple
17
+ from typing import Dict, List
18
+
19
+ import warp as wp
20
+
21
+
22
+ class Tape:
23
+ """
24
+ Record kernel launches within a Tape scope to enable automatic differentiation.
25
+ Gradients can be computed after the operations have been recorded on the tape via
26
+ :meth:`Tape.backward()`.
27
+
28
+ Example
29
+ -------
30
+
31
+ .. code-block:: python
32
+
33
+ tape = wp.Tape()
34
+
35
+ # forward pass
36
+ with tape:
37
+ wp.launch(kernel=compute1, inputs=[a, b], device="cuda")
38
+ wp.launch(kernel=compute2, inputs=[c, d], device="cuda")
39
+ wp.launch(kernel=loss, inputs=[d, l], device="cuda")
40
+
41
+ # reverse pass
42
+ tape.backward(l)
43
+
44
+ Gradients can be accessed via the ``tape.gradients`` dictionary, e.g.:
45
+
46
+ .. code-block:: python
47
+
48
+ print(tape.gradients[a])
49
+
50
+ """
51
+
52
+ def __init__(self):
53
+ self.gradients = {}
54
+ self.launches = []
55
+ self.scopes = []
56
+
57
+ self.loss = None
58
+
59
+ def __enter__(self):
60
+ wp.context.init()
61
+
62
+ if wp.context.runtime.tape is not None:
63
+ raise RuntimeError("Warp: Error, entering a tape while one is already active")
64
+
65
+ wp.context.runtime.tape = self
66
+
67
+ return self
68
+
69
+ def __exit__(self, exc_type, exc_value, traceback):
70
+ if wp.context.runtime.tape is None:
71
+ raise RuntimeError("Warp: Error, ended tape capture, but tape not present")
72
+
73
+ wp.context.runtime.tape = None
74
+
75
+ # adj_outputs is a mapping from output tensor -> adjoint of the output
76
+ # after running backward the gradients of tensors may be retrieved by:
77
+ #
78
+ # adj_tensor = tape.gradients[tensor]
79
+ #
80
+ def backward(self, loss: wp.array = None, grads: dict = None):
81
+ """
82
+ Evaluate the backward pass of the recorded operations on the tape.
83
+ A single-element array ``loss`` or a dictionary of arrays ``grads``
84
+ can be provided to assign the incoming gradients for the reverse-mode
85
+ automatic differentiation pass.
86
+
87
+ Args:
88
+ loss (wp.array): A single-element array that holds the loss function value whose gradient is to be computed
89
+ grads (dict): A dictionary of arrays that map from Warp arrays to their incoming gradients
90
+
91
+ """
92
+ # if scalar loss is specified then initialize
93
+ # a 'seed' array for it, with gradient of one
94
+ if loss:
95
+ if loss.size > 1 or wp.types.type_length(loss.dtype) > 1:
96
+ raise RuntimeError("Can only return gradients for scalar loss functions.")
97
+
98
+ if not loss.requires_grad:
99
+ raise RuntimeError(
100
+ "Scalar loss arrays should have requires_grad=True set before calling Tape.backward()"
101
+ )
102
+
103
+ # set the seed grad to 1.0
104
+ loss.grad.fill_(1.0)
105
+
106
+ # simply apply dict grads to objects
107
+ # this is just for backward compat. with
108
+ # existing code before we added wp.array.grad attribute
109
+ if grads:
110
+ for a, g in grads.items():
111
+ if a.grad is None:
112
+ a.grad = g
113
+ else:
114
+ # ensure we can capture this backward pass in a CUDA graph
115
+ a.grad.assign(g)
116
+
117
+ # run launches backwards
118
+ for launch in reversed(self.launches):
119
+ if callable(launch):
120
+ launch()
121
+
122
+ else:
123
+ # kernel option takes precedence over module option
124
+ enable_backward = launch[0].options.get("enable_backward")
125
+ if enable_backward is False:
126
+ msg = f"Running the tape backwards may produce incorrect gradients because recorded kernel {launch[0].key} is configured with the option 'enable_backward=False'."
127
+ wp.utils.warn(msg)
128
+ elif enable_backward is None:
129
+ enable_backward = launch[0].module.options.get("enable_backward")
130
+ if enable_backward is False:
131
+ msg = f"Running the tape backwards may produce incorrect gradients because recorded kernel {launch[0].key} is defined in a module with the option 'enable_backward=False' set."
132
+ wp.utils.warn(msg)
133
+
134
+ kernel = launch[0]
135
+ dim = launch[1]
136
+ max_blocks = launch[2]
137
+ inputs = launch[3]
138
+ outputs = launch[4]
139
+ device = launch[5]
140
+ block_dim = launch[6]
141
+
142
+ adj_inputs = []
143
+ adj_outputs = []
144
+
145
+ # lookup adjoint inputs
146
+ for a in inputs:
147
+ adj_inputs.append(self.get_adjoint(a))
148
+
149
+ # lookup adjoint outputs, todo: only allocate outputs if necessary
150
+ for a in outputs:
151
+ adj_outputs.append(self.get_adjoint(a))
152
+
153
+ if enable_backward:
154
+ wp.launch(
155
+ kernel=kernel,
156
+ dim=dim,
157
+ inputs=inputs,
158
+ outputs=outputs,
159
+ adj_inputs=adj_inputs,
160
+ adj_outputs=adj_outputs,
161
+ device=device,
162
+ adjoint=True,
163
+ max_blocks=max_blocks,
164
+ block_dim=block_dim,
165
+ )
166
+
167
+ # record a kernel launch on the tape
168
+ def record_launch(self, kernel, dim, max_blocks, inputs, outputs, device, block_dim=0, metadata=None):
169
+ if metadata is None:
170
+ metadata = {}
171
+ self.launches.append([kernel, dim, max_blocks, inputs, outputs, device, block_dim, metadata])
172
+
173
+ def record_func(self, backward, arrays):
174
+ """
175
+ Records a custom function to be executed only in the backward pass.
176
+
177
+ Args:
178
+ backward (Callable): A callable Python object (can be any function) that will be executed in the backward pass.
179
+ arrays (list): A list of arrays that are used by the backward function. The tape keeps track of these to be able to zero their gradients in Tape.zero()
180
+ """
181
+ self.launches.append(backward)
182
+
183
+ for a in arrays:
184
+ if isinstance(a, wp.array) and a.grad:
185
+ self.gradients[a] = a.grad
186
+ else:
187
+ raise RuntimeError(
188
+ f"Array {a} is not of type wp.array or is missing a gradient array. Set array parameter requires_grad=True during instantiation."
189
+ )
190
+
191
+ def record_scope_begin(self, scope_name, metadata=None):
192
+ """
193
+ Begin a scope on the tape to group operations together. Scopes are only used in the visualization functions.
194
+ """
195
+ if metadata is None:
196
+ metadata = {}
197
+ self.scopes.append((len(self.launches), scope_name, metadata))
198
+
199
+ def record_scope_end(self, remove_scope_if_empty=True):
200
+ """
201
+ End a scope on the tape.
202
+
203
+ Args:
204
+ remove_scope_if_empty (bool): If True, the scope will be removed if no kernel launches were recorded within it.
205
+ """
206
+ if remove_scope_if_empty and self.scopes[-1][0] == len(self.launches):
207
+ self.scopes = self.scopes[:-1]
208
+ else:
209
+ self.scopes.append((len(self.launches), None, None))
210
+
211
+ def _check_kernel_array_access(self, kernel, args):
212
+ """Detect illegal inter-kernel write after read access patterns during launch capture"""
213
+ adj = kernel.adj
214
+ kernel_name = adj.fun_name
215
+ filename = adj.filename
216
+ lineno = adj.fun_lineno
217
+
218
+ for i, arg in enumerate(args):
219
+ if isinstance(arg, wp.array):
220
+ arg_name = adj.args[i].label
221
+
222
+ # we check write condition first because we allow (write --> read) within the same kernel
223
+ if adj.args[i].is_write:
224
+ arg.mark_write(arg_name=arg_name, kernel_name=kernel_name, filename=filename, lineno=lineno)
225
+
226
+ if adj.args[i].is_read:
227
+ arg.mark_read()
228
+
229
+ # returns the adjoint of a kernel parameter
230
+ def get_adjoint(self, a):
231
+ if not wp.types.is_array(a) and not isinstance(a, wp.codegen.StructInstance):
232
+ # if input is a simple type (e.g.: float, vec3, etc) or a non-Warp array,
233
+ # then no gradient needed (we only return gradients through Warp arrays and structs)
234
+ return None
235
+
236
+ elif wp.types.is_array(a) and a.grad:
237
+ # keep track of all gradients used by the tape (for zeroing)
238
+ # ignore the scalar loss since we don't want to clear its grad
239
+ self.gradients[a] = a.grad
240
+ return a.grad
241
+
242
+ elif isinstance(a, wp.codegen.StructInstance):
243
+ adj = a._cls()
244
+ for name, _ in a._cls.ctype._fields_:
245
+ if name.startswith("_"):
246
+ continue
247
+ if isinstance(a._cls.vars[name].type, wp.array):
248
+ arr = getattr(a, name)
249
+ if arr.grad:
250
+ grad = self.gradients[arr] = arr.grad
251
+ else:
252
+ grad = None
253
+ setattr(adj, name, grad)
254
+ else:
255
+ setattr(adj, name, getattr(a, name))
256
+
257
+ self.gradients[a] = adj
258
+ return adj
259
+
260
+ return None
261
+
262
+ def reset(self):
263
+ """
264
+ Clear all operations recorded on the tape and zero out all gradients.
265
+ """
266
+ self.launches = []
267
+ self.scopes = []
268
+ self.zero()
269
+ if wp.config.verify_autograd_array_access:
270
+ self._reset_array_read_flags()
271
+
272
+ def zero(self):
273
+ """
274
+ Zero out all gradients recorded on the tape.
275
+ """
276
+ for a, g in self.gradients.items():
277
+ if isinstance(a, wp.codegen.StructInstance):
278
+ for name in g._cls.vars:
279
+ if isinstance(g._cls.vars[name].type, wp.array) and g._cls.vars[name].requires_grad:
280
+ getattr(g, name).zero_()
281
+ else:
282
+ g.zero_()
283
+
284
+ def _reset_array_read_flags(self):
285
+ """
286
+ Reset all recorded array read flags to False
287
+ """
288
+ for a in self.gradients:
289
+ if isinstance(a, wp.array):
290
+ a.mark_init()
291
+
292
+ def visualize(
293
+ self,
294
+ filename: str = None,
295
+ simplify_graph=True,
296
+ hide_readonly_arrays=False,
297
+ array_labels: Dict[wp.array, str] = None,
298
+ choose_longest_node_name: bool = True,
299
+ ignore_graph_scopes: bool = False,
300
+ track_inputs: List[wp.array] = None,
301
+ track_outputs: List[wp.array] = None,
302
+ track_input_names: List[str] = None,
303
+ track_output_names: List[str] = None,
304
+ graph_direction: str = "LR",
305
+ ) -> str:
306
+ """
307
+ Visualize the recorded operations on the tape as a `GraphViz diagram <https://graphviz.org/>`_.
308
+
309
+ Example
310
+ -------
311
+
312
+ .. code-block:: python
313
+
314
+ import warp as wp
315
+
316
+ tape = wp.Tape()
317
+ with tape:
318
+ # record Warp kernel launches here
319
+ wp.launch(...)
320
+
321
+ dot_code = tape.visualize("tape.dot")
322
+
323
+ This function creates a GraphViz dot file that can be rendered into an image using the GraphViz command line tool, e.g. via
324
+
325
+ .. code-block:: bash
326
+
327
+ dot -Tpng tape.dot -o tape.png
328
+
329
+ Args:
330
+ filename (str): The filename to save the visualization to (optional).
331
+ simplify_graph (bool): If True, simplify the graph by detecting repeated kernel launch sequences and summarizing them in subgraphs.
332
+ hide_readonly_arrays (bool): If True, hide arrays that are not modified by any kernel launch.
333
+ array_labels (Dict[wp.array, str]): A dictionary mapping arrays to custom labels.
334
+ choose_longest_node_name (bool): If True, the automatic name resolution will aim to find the longest name for each array in the computation graph.
335
+ ignore_graph_scopes (bool): If True, ignore the scopes recorded on the tape when visualizing the graph.
336
+ track_inputs (List[wp.array]): A list of arrays to track as inputs in the graph to ensure they are shown regardless of the `hide_readonly_arrays` setting.
337
+ track_outputs (List[wp.array]): A list of arrays to track as outputs in the graph so that they remain visible.
338
+ track_input_names (List[str]): A list of custom names for the input arrays to track in the graph (used in conjunction with `track_inputs`).
339
+ track_output_names (List[str]): A list of custom names for the output arrays to track in the graph (used in conjunction with `track_outputs`).
340
+ graph_direction (str): The direction of the graph layout (default: "LR").
341
+
342
+ Returns:
343
+ str: The dot code representing the graph.
344
+
345
+ """
346
+ if track_output_names is None:
347
+ track_output_names = []
348
+ if track_input_names is None:
349
+ track_input_names = []
350
+ if track_outputs is None:
351
+ track_outputs = []
352
+ if track_inputs is None:
353
+ track_inputs = []
354
+ if array_labels is None:
355
+ array_labels = {}
356
+ return visualize_tape_graphviz(
357
+ self,
358
+ filename,
359
+ simplify_graph,
360
+ hide_readonly_arrays,
361
+ array_labels,
362
+ choose_longest_node_name,
363
+ ignore_graph_scopes,
364
+ track_inputs,
365
+ track_outputs,
366
+ track_input_names,
367
+ track_output_names,
368
+ graph_direction,
369
+ )
370
+
371
+
372
+ class TapeVisitor:
373
+ def emit_array_node(self, arr: wp.array, label: str, active_scope_stack: List[str], indent_level: int):
374
+ pass
375
+
376
+ def emit_kernel_launch_node(
377
+ self, kernel: wp.Kernel, kernel_launch_id: str, launch_data: dict, rendered: bool, indent_level: int
378
+ ):
379
+ pass
380
+
381
+ def emit_edge_array_kernel(self, arr: wp.array, kernel_launch_id: str, kernel_input_id: int, indent_level: int):
382
+ pass
383
+
384
+ def emit_edge_kernel_array(self, kernel_launch_id: str, kernel_output_id: int, arr: wp.array, indent_level: int):
385
+ pass
386
+
387
+ def emit_edge_array_array(self, src: wp.array, dst: wp.array, indent_level: int):
388
+ pass
389
+
390
+ def emit_scope_begin(self, active_scope_id: int, active_scope_name: str, metadata: dict, indent_level: int):
391
+ pass
392
+
393
+ def emit_scope_end(self, indent_level: int):
394
+ pass
395
+
396
+
397
+ def get_struct_vars(x: wp.codegen.StructInstance):
398
+ return {varname: getattr(x, varname) for varname, _ in x._cls.ctype._fields_}
399
+
400
+
401
+ class GraphvizTapeVisitor(TapeVisitor):
402
+ def __init__(self):
403
+ self.graphviz_lines = []
404
+ self.indent_str = "\t"
405
+ self.scope_classes = {}
406
+ self.max_indent = 0
407
+ # mapping from array pointer to kernel:port ID
408
+ self.pointer_to_port = {}
409
+ # set of inserted edges between kernel:port IDs
410
+ self.edges = set()
411
+ # set of inserted array nodes
412
+ self.array_nodes = set()
413
+
414
+ @staticmethod
415
+ def sanitize(s):
416
+ return (
417
+ s.replace("\n", " ")
418
+ .replace('"', " ")
419
+ .replace("'", " ")
420
+ .replace("[", "&#91;")
421
+ .replace("]", "&#93;")
422
+ .replace("`", "&#96;")
423
+ .replace(":", "&#58;")
424
+ .replace("\\", "\\\\")
425
+ .replace("/", "&#47;")
426
+ .replace("(", "&#40;")
427
+ .replace(")", "&#41;")
428
+ .replace(",", "")
429
+ .replace("{", "&#123;")
430
+ .replace("}", "&#125;")
431
+ .replace("<", "&#60;")
432
+ .replace(">", "&#62;")
433
+ )
434
+
435
+ @staticmethod
436
+ def dtype2str(dtype):
437
+ type_str = str(dtype)
438
+ if hasattr(dtype, "key"):
439
+ type_str = dtype.key
440
+ elif "'" in type_str:
441
+ type_str = type_str.split("'")[1]
442
+ return type_str
443
+
444
+ def emit_array_node(self, arr: wp.array, label: str, active_scope_stack: List[str], indent_level: int):
445
+ if arr.ptr in self.array_nodes:
446
+ return
447
+ if arr.ptr in self.pointer_to_port:
448
+ return
449
+ self.array_nodes.add(arr.ptr)
450
+ color = "lightgray"
451
+ if arr.requires_grad:
452
+ color = "#76B900"
453
+ options = [
454
+ f'label="{label}"',
455
+ "shape=ellipse",
456
+ "style=filled",
457
+ f'fillcolor="{color}"',
458
+ ]
459
+ chart_indent = self.indent_str * indent_level
460
+ arr_id = f"arr{arr.ptr}"
461
+ type_str = self.dtype2str(arr.dtype)
462
+ # type_str = self.sanitize(type_str)
463
+ # class_name = "array" if not arr.requires_grad else "array_grad"
464
+ # self.graphviz_lines.append(chart_indent + f'{arr_id}(["`{label}`"]):::{class_name}')
465
+ tooltip = f"Array {label} / ptr={arr.ptr}, shape={str(arr.shape)}, dtype={type_str}, requires_grad={arr.requires_grad}"
466
+ options.append(f'tooltip="{tooltip}"')
467
+ # self.graphviz_lines.append(chart_indent + f'click {arr_id} callback "{tooltip}"')
468
+ # self.max_indent = max(self.max_indent, indent_level)
469
+ self.graphviz_lines.append(f"{chart_indent}{arr_id} [{','.join(options)}];")
470
+
471
+ def emit_kernel_launch_node(
472
+ self, kernel: wp.Kernel, kernel_launch_id: str, launch_data: dict, rendered: bool, indent_level: int
473
+ ):
474
+ if not rendered:
475
+ return
476
+ chart_indent = self.indent_str * indent_level
477
+
478
+ table = []
479
+ table.append(
480
+ '<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" border="0" cellspacing="2" cellpadding="4" bgcolor="#888888" gradientangle="0">'
481
+ )
482
+ table.append(f'<TR><TD BGCOLOR="#ffffffaa" colspan="2" align="center"><b>{kernel.key}</b></TD></TR>')
483
+ num_inputs = len(launch_data["inputs"])
484
+ num_outputs = len(launch_data["outputs"])
485
+ nrows = max(num_inputs, num_outputs)
486
+ nargs = len(kernel.adj.args)
487
+ for i in range(nrows):
488
+ row = []
489
+ if i < num_inputs:
490
+ arg = kernel.adj.args[i]
491
+ port_id = f"in_{i}"
492
+ if isinstance(arg.type, wp.array):
493
+ tooltip = f"array: dtype={self.dtype2str(arg.type.dtype)}"
494
+ else:
495
+ tooltip = f"dtype={self.sanitize(self.dtype2str(arg.type))}"
496
+ row.append(
497
+ f'<TD PORT="{port_id}" BGCOLOR="#BBBBBB" align="left" title="{tooltip}"><font color="black">{arg.label}</font></TD>'
498
+ )
499
+ launch_data["inputs"][i]
500
+ # if var is not None and isinstance(var, wp.array):
501
+ # self.pointer_to_port[var.ptr] = f"{kernel_launch_id}:{port_id}"
502
+ else:
503
+ row.append('<TD BORDER="0"></TD>')
504
+ # if i >= nargs - 1:
505
+ # row.append('<TD></TD>')
506
+ # table.append(f'<TR>{row[0]}{row[1]}</TR>')
507
+ # break
508
+ if i < num_outputs and i + num_inputs < nargs:
509
+ arg = kernel.adj.args[i + num_inputs].label
510
+ port_id = f"out_{i}"
511
+ row.append(
512
+ f'<TD PORT="{port_id}" BGCOLOR="#BBBBBB" align="right"><font color="black">{arg}</font></TD>'
513
+ )
514
+ launch_data["outputs"][i]
515
+ # if var is not None and isinstance(var, wp.array):
516
+ # self.pointer_to_port[var.ptr] = f"{kernel_launch_id}:{port_id}"
517
+ else:
518
+ row.append('<TD BORDER="0"></TD>')
519
+ table.append(f"<TR>{row[0]}{row[1]}</TR>")
520
+ table.append("</TABLE>")
521
+
522
+ label = f"{chart_indent}\n".join(table)
523
+ node_attrs = f"label=<{label}>"
524
+ if "caller" in launch_data:
525
+ caller = launch_data["caller"]
526
+ node_attrs += f',tooltip="{self.sanitize(caller["file"])}:{caller["lineno"]} ({caller["func"]})"'
527
+
528
+ self.graphviz_lines.append(f"{chart_indent}{kernel_launch_id} [{node_attrs}];")
529
+
530
+ def emit_edge_array_kernel(self, arr_ptr: int, kernel_launch_id: str, kernel_input_id: int, indent_level: int):
531
+ chart_indent = self.indent_str * indent_level
532
+ if arr_ptr in self.pointer_to_port:
533
+ arr_id = self.pointer_to_port[arr_ptr]
534
+ elif arr_ptr in self.array_nodes:
535
+ arr_id = f"arr{arr_ptr}"
536
+ else:
537
+ return
538
+ target_id = f"{kernel_launch_id}:in_{kernel_input_id}"
539
+ if (arr_id, target_id) in self.edges:
540
+ return
541
+ self.edges.add((arr_id, target_id))
542
+ self.graphviz_lines.append(f"{chart_indent}{arr_id} -> {target_id}")
543
+
544
+ def emit_edge_kernel_array(self, kernel_launch_id: str, kernel_output_id: int, arr_ptr: int, indent_level: int):
545
+ chart_indent = self.indent_str * indent_level
546
+ if arr_ptr in self.pointer_to_port:
547
+ arr_id = self.pointer_to_port[arr_ptr]
548
+ elif arr_ptr in self.array_nodes:
549
+ arr_id = f"arr{arr_ptr}"
550
+ else:
551
+ return
552
+ source_id = f"{kernel_launch_id}:out_{kernel_output_id}"
553
+ if (source_id, arr_id) in self.edges:
554
+ return
555
+ self.edges.add((source_id, arr_id))
556
+ self.graphviz_lines.append(f"{chart_indent}{source_id} -> {arr_id};")
557
+
558
+ def emit_edge_array_array(self, src: wp.array, dst: wp.array, indent_level: int):
559
+ chart_indent = self.indent_str * indent_level
560
+ src_id = f"arr{src.ptr}"
561
+ dst_id = f"arr{dst.ptr}"
562
+ if (src_id, dst_id) in self.edges:
563
+ return
564
+ self.edges.add((src_id, dst_id))
565
+ self.graphviz_lines.append(f'{chart_indent}{src_id} -> {dst_id} [color="#0072B9",constraint=false];')
566
+
567
+ def emit_scope_begin(self, active_scope_id: int, active_scope_name: str, metadata: dict, indent_level: int):
568
+ chart_indent = self.indent_str * indent_level
569
+ scope_key = f"cluster{active_scope_id}"
570
+ scope_class = metadata.get("type", "scope")
571
+ self.graphviz_lines.append(f"{chart_indent}subgraph {scope_key} {{")
572
+ chart_indent += self.indent_str
573
+ self.graphviz_lines.append(f'{chart_indent}style="rounded,filled";')
574
+ if scope_class == "scope":
575
+ self.graphviz_lines.append(f'{chart_indent}fillcolor="#76B90022";')
576
+ self.graphviz_lines.append(f'{chart_indent}pencolor="#76B900";')
577
+ else:
578
+ self.graphviz_lines.append(f'{chart_indent}fillcolor="#0072B922";')
579
+ self.graphviz_lines.append(f'{chart_indent}pencolor="#0072B9";')
580
+ self.graphviz_lines.append(f"{chart_indent}label=<<b>{active_scope_name}</b>>;\n")
581
+
582
+ def emit_scope_end(self, indent_level: int):
583
+ chart_indent = self.indent_str * indent_level
584
+ self.graphviz_lines.append(f"{chart_indent}}};\n")
585
+
586
+
587
+ class ArrayStatsVisitor(TapeVisitor):
588
+ ArrayState = namedtuple("ArrayState", ["mean", "std", "min", "max"])
589
+
590
+ def __init__(self):
591
+ self.array_names = {}
592
+ self.launch_data = {}
593
+ self.launches = []
594
+ self.array_value_stats = []
595
+ self.array_grad_stats = []
596
+
597
+ def emit_array_node(self, arr: wp.array, label: str, active_scope_stack: List[str], indent_level: int):
598
+ if arr.device.is_capturing:
599
+ raise RuntimeError("Cannot record arrays while graph capturing is active.")
600
+ self.array_names[arr.ptr] = label
601
+
602
+ def emit_kernel_launch_node(
603
+ self, kernel: wp.Kernel, kernel_launch_id: str, launch_data: dict, rendered: bool, indent_level: int
604
+ ):
605
+ self.launch_data[kernel_launch_id] = launch_data
606
+ self.launches.append(kernel_launch_id)
607
+ value_stats = {}
608
+ grad_stats = {}
609
+ for output in launch_data["outputs"]:
610
+ if isinstance(output, wp.array):
611
+ arr_np = output.numpy()
612
+ value_stats[output.ptr] = self.ArrayState(
613
+ mean=arr_np.mean(), std=arr_np.std(), min=arr_np.min(), max=arr_np.max()
614
+ )
615
+ for input in launch_data["inputs"]:
616
+ if isinstance(input, wp.array) and input.requires_grad and input.grad is not None:
617
+ arr_np = input.grad.numpy()
618
+ grad_stats[input.ptr] = self.ArrayState(
619
+ mean=arr_np.mean(), std=arr_np.std(), min=arr_np.min(), max=arr_np.max()
620
+ )
621
+ self.array_value_stats.append(value_stats)
622
+ self.array_grad_stats.insert(0, grad_stats)
623
+
624
+
625
+ Launch = namedtuple(
626
+ "Launch", ["id", "kernel", "dim", "max_blocks", "inputs", "outputs", "device", "block_dim", "metadata"]
627
+ )
628
+ RepeatedSequence = namedtuple("RepeatedSequence", ["start", "end", "repetitions"])
629
+
630
+
631
+ def visit_tape(
632
+ tape: Tape,
633
+ visitor: TapeVisitor,
634
+ simplify_graph=True,
635
+ hide_readonly_arrays=False,
636
+ array_labels: Dict[wp.array, str] = None,
637
+ choose_longest_node_name: bool = True,
638
+ ignore_graph_scopes: bool = False,
639
+ track_inputs: List[wp.array] = None,
640
+ track_outputs: List[wp.array] = None,
641
+ track_input_names: List[str] = None,
642
+ track_output_names: List[str] = None,
643
+ ):
644
+ if track_output_names is None:
645
+ track_output_names = []
646
+ if track_input_names is None:
647
+ track_input_names = []
648
+ if track_outputs is None:
649
+ track_outputs = []
650
+ if track_inputs is None:
651
+ track_inputs = []
652
+ if array_labels is None:
653
+ array_labels = {}
654
+
655
+ def get_launch_id(launch):
656
+ kernel = launch[0]
657
+ suffix = ""
658
+ if len(launch) > 7:
659
+ metadata = launch[7]
660
+ # calling function helps to identify unique launches
661
+ if "caller" in metadata:
662
+ caller = metadata["caller"]
663
+ suffix = str(hash(caller["file"] + caller["func"] + str(caller["lineno"])))
664
+ return f"{kernel.module.name}.{kernel.key}{suffix}"
665
+
666
+ # exclude function calls, only consider kernel launches
667
+ kernel_launches = []
668
+ kernel_scopes = []
669
+
670
+ next_scope_id = 0
671
+ id_offset = 0
672
+ for i, launch in enumerate(tape.launches):
673
+ if isinstance(launch, list):
674
+ kernel_launches.append(launch)
675
+ else:
676
+ id_offset -= 1
677
+ while next_scope_id < len(tape.scopes) and i == tape.scopes[next_scope_id][0]:
678
+ scope = tape.scopes[next_scope_id]
679
+ # update scope launch index to account for removed function calls
680
+ new_scope = (scope[0] + id_offset, *scope[1:])
681
+ kernel_scopes.append(new_scope)
682
+ next_scope_id += 1
683
+
684
+ launch_structs = [
685
+ Launch(
686
+ id=get_launch_id(launch),
687
+ kernel=launch[0],
688
+ dim=launch[1],
689
+ max_blocks=launch[2],
690
+ inputs=launch[3],
691
+ outputs=launch[4],
692
+ device=launch[5],
693
+ block_dim=launch[6],
694
+ metadata=launch[7] if len(launch) > 7 else {},
695
+ )
696
+ for launch in kernel_launches
697
+ ]
698
+ launch_ids = [get_launch_id(launch) for launch in kernel_launches]
699
+
700
+ def get_repeating_sequences(sequence: List[str]):
701
+ # yield all consecutively repeating subsequences in descending order of length
702
+ for length in range(len(sequence) // 2 + 1, 0, -1):
703
+ for start in range(len(sequence) - length):
704
+ if sequence[start : start + length] == sequence[start + length : start + 2 * length]:
705
+ # we found a sequence that repeats at least once
706
+ candidate = RepeatedSequence(start, start + length, 2)
707
+ if length == 1:
708
+ # this repetition cannot be made up of smaller repetitions
709
+ yield candidate
710
+
711
+ # check if this sequence is made up entirely of smaller repetitions
712
+ for sl in range(1, length // 2 + 1):
713
+ # loop over subsequence lengths and check if they repeat
714
+ subseq = sequence[start : start + sl]
715
+ if all(
716
+ sequence[start + i * sl : start + (i + 1) * sl] == subseq for i in range(1, length // sl)
717
+ ):
718
+ rep_count = length // sl + 1
719
+ # check whether there are more repetitions beyond the previous end
720
+ for cstart in range(start + length, len(sequence) - sl, sl):
721
+ if sequence[cstart : cstart + sl] != subseq:
722
+ break
723
+ rep_count += 1
724
+ candidate = RepeatedSequence(start, start + sl, rep_count)
725
+ yield candidate
726
+ break
727
+
728
+ def process_sequence(sequence: List[str]) -> RepeatedSequence:
729
+ # find the longest contiguous repetition in the sequence
730
+ if len(sequence) < 2:
731
+ return None
732
+
733
+ for r in get_repeating_sequences(sequence):
734
+ rlen = r.end - r.start
735
+ rseq = sequence[r.start : r.end]
736
+ # ensure that the repetitions of this subsequence immediately follow each other
737
+ candidates = defaultdict(int) # mapping from start index to number of repetitions
738
+ curr_start = r.start
739
+ i = r.end
740
+ while i + rlen <= len(sequence):
741
+ if sequence[i : i + rlen] == rseq:
742
+ candidates[curr_start] += 1
743
+ i += rlen
744
+ else:
745
+ try:
746
+ curr_start = sequence.index(rseq, i)
747
+ i = curr_start + rlen
748
+ except ValueError:
749
+ break
750
+
751
+ if len(candidates) > 0:
752
+ start, reps = max(candidates.items(), key=lambda x: x[1])
753
+ return RepeatedSequence(start, start + rlen, reps + 1)
754
+
755
+ return None
756
+
757
+ repetitions = []
758
+
759
+ def find_sequences(sequence):
760
+ # recursively find repetitions in sequence
761
+ nonlocal repetitions
762
+
763
+ if len(sequence) == 0:
764
+ return
765
+
766
+ # find LRS in current sequence
767
+ longest_rep = process_sequence(sequence)
768
+ if longest_rep is None:
769
+ return
770
+
771
+ # process sequence up until the current LRS
772
+ find_sequences(sequence[: longest_rep.start])
773
+
774
+ # process repeated sequence
775
+ rstr = sequence[longest_rep.start : longest_rep.end]
776
+ if longest_rep.repetitions >= 2:
777
+ repetitions.append(longest_rep)
778
+
779
+ find_sequences(rstr)
780
+
781
+ # process remaining sequence
782
+ rlen = longest_rep.end - longest_rep.start
783
+ reps = longest_rep.repetitions
784
+ end_idx = longest_rep.start + (reps + 1) * rlen
785
+ if end_idx < len(sequence):
786
+ find_sequences(sequence[end_idx:])
787
+
788
+ return
789
+
790
+ find_sequences(launch_ids)
791
+
792
+ wrap_around_connections = set()
793
+
794
+ # mapping from array ptr to already existing array in a repetition
795
+ array_repeated = {}
796
+
797
+ array_to_launch = defaultdict(list)
798
+ launch_to_array = defaultdict(list)
799
+
800
+ if simplify_graph:
801
+ # mappings from unique launch string to index of first occurrence and vice versa
802
+ launch_to_index = {}
803
+ index_to_launch = {}
804
+
805
+ # new arrays of launches, scopes without repetitions
806
+ launches = []
807
+ scopes = []
808
+
809
+ def find_scope_end(scope_i):
810
+ opened_scopes = 0
811
+ for i in range(scope_i, len(kernel_scopes)):
812
+ scope = kernel_scopes[i]
813
+ if scope[1] is not None:
814
+ opened_scopes += 1
815
+ else:
816
+ opened_scopes -= 1
817
+ if opened_scopes == 0:
818
+ return scope[0]
819
+ return len(kernel_scopes)
820
+
821
+ def process_launches(kernel_launches, start_i, end_i, rep_i, scope_i, skipped_i):
822
+ nonlocal \
823
+ launches, \
824
+ scopes, \
825
+ launch_to_index, \
826
+ index_to_launch, \
827
+ wrap_around_connections, \
828
+ launch_to_array, \
829
+ array_to_launch
830
+ i = start_i # index of current launch
831
+ opened_scopes = 0
832
+ while i < end_i:
833
+ launch_id = launch_ids[i]
834
+
835
+ while (
836
+ scope_i < len(kernel_scopes)
837
+ and i >= kernel_scopes[scope_i][0]
838
+ and kernel_scopes[scope_i][1] is None
839
+ ):
840
+ # add any missing closing scopes before we go into a repeating sequence
841
+ scope = kernel_scopes[scope_i]
842
+ if opened_scopes >= 1:
843
+ scopes.append((scope[0] - skipped_i, *scope[1:]))
844
+ scope_i += 1
845
+ opened_scopes -= 1
846
+
847
+ # keep track of the mapping between arrays and kernel launch arguments
848
+ for arg_i, arg in enumerate(kernel_launches[i].inputs + kernel_launches[i].outputs):
849
+ if isinstance(arg, wp.array):
850
+ array_to_launch[arg.ptr].append((launch_id, arg_i))
851
+ launch_to_array[(launch_id, arg_i)].append(arg)
852
+
853
+ # handle repetitions
854
+ if rep_i < len(repetitions):
855
+ rep = repetitions[rep_i]
856
+ if i == rep.start:
857
+ rep_len = rep.end - rep.start
858
+ after_rep = rep.start + rep.repetitions * rep_len
859
+ # check if there is a scope that matches the entire repetition
860
+ skip_adding_repetition_scope = False
861
+ for scope_j in range(scope_i, len(kernel_scopes)):
862
+ scope = kernel_scopes[scope_j]
863
+ if scope[0] > rep.start:
864
+ break
865
+ if scope[0] == rep.start and scope[1] is not None:
866
+ # check if this scope also ends at the end of the repetition
867
+ scope_end = find_scope_end(scope_j)
868
+ if scope_end == after_rep:
869
+ # replace scope details
870
+ kernel_scopes[scope_j] = (
871
+ rep.start,
872
+ f"{scope[1]} (repeated {rep.repetitions}x)",
873
+ {"type": "repeated", "count": rep.repetitions},
874
+ )
875
+ skip_adding_repetition_scope = True
876
+ break
877
+
878
+ if not skip_adding_repetition_scope:
879
+ # add a new scope marking this repetition
880
+ scope_name = f"repeated {rep.repetitions}x"
881
+ scopes.append((len(launches), scope_name, {"type": "repeated", "count": rep.repetitions}))
882
+
883
+ # process repetition recursively to handle nested repetitions
884
+ process_launches(kernel_launches, rep.start, rep.end, rep_i + 1, scope_i, skipped_i)
885
+
886
+ if not skip_adding_repetition_scope:
887
+ # close the scope we just added marking this repetition
888
+ scopes.append((len(launches), None, None))
889
+
890
+ # collect all output arrays from the first iteration
891
+ output_arrays = {}
892
+ for j in range(i, i + rep_len):
893
+ launch = kernel_launches[j]
894
+ launch_id = launch_ids[j]
895
+ for k, arg in enumerate(launch.outputs):
896
+ arg_i = k + len(launch.inputs)
897
+ if isinstance(arg, wp.array):
898
+ output_arrays[arg.ptr] = arg
899
+ array_to_launch[arg.ptr].append((launch_id, arg_i))
900
+
901
+ # find out which output arrays feed back as inputs to the next iteration
902
+ # so we can add them as wrap-around connections
903
+ for j in range(i + rep_len, i + 2 * rep_len):
904
+ launch = kernel_launches[j]
905
+ launch_id = launch_ids[j]
906
+ for arg_i, arg in enumerate(launch.inputs):
907
+ if isinstance(arg, wp.array) and arg.ptr in output_arrays:
908
+ first_encountered_var = launch_to_array[(launch_id, arg_i)][0]
909
+ # print(array_to_launch[arg.ptr])
910
+ # array_to_launch[arg.ptr].append((launch_id, arg_i))
911
+ # launch_to_array[(launch_id, arg_i)].append(arg)
912
+ src_launch = array_to_launch[arg.ptr][-1]
913
+ src_arr = launch_to_array[src_launch][-1]
914
+ wrap_around_connections.add((src_arr.ptr, first_encountered_var.ptr))
915
+
916
+ # map arrays appearing as launch arguments in following repetitions to their first occurrence
917
+ skip_len = rep.repetitions * rep_len
918
+ for j in range(i + rep_len, i + skip_len):
919
+ launch = kernel_launches[j]
920
+ launch_id = launch_ids[j]
921
+ for arg_i, arg in enumerate(launch.inputs + launch.outputs):
922
+ if isinstance(arg, wp.array):
923
+ array_repeated[arg.ptr] = launch_to_array[(launch_id, arg_i)][0].ptr
924
+
925
+ # skip launches during these repetitions
926
+ i += skip_len
927
+ skipped_i += skip_len - rep_len
928
+ rep_i += 1
929
+
930
+ # skip scopes during the repetitions
931
+ while scope_i < len(kernel_scopes) and i > kernel_scopes[scope_i][0]:
932
+ scope_i += 1
933
+
934
+ continue
935
+
936
+ # add launch
937
+ launch = kernel_launches[i]
938
+ launch_id = launch_ids[i]
939
+ if launch_id not in launch_to_index:
940
+ # we encountered an unseen kernel
941
+ j = len(launch_to_index)
942
+ launch_to_index[launch_id] = j
943
+ index_to_launch[j] = launch_id
944
+ launches.append(launch)
945
+
946
+ while scope_i < len(kernel_scopes) and i >= kernel_scopes[scope_i][0]:
947
+ # add scopes encompassing the kernels we added so far
948
+ scope = kernel_scopes[scope_i]
949
+ if scope[1] is not None:
950
+ scopes.append((scope[0] - skipped_i, *scope[1:]))
951
+ opened_scopes += 1
952
+ else:
953
+ if opened_scopes >= 1:
954
+ # only add closing scope if there was an opening scope
955
+ scopes.append((scope[0] - skipped_i, *scope[1:]))
956
+ opened_scopes -= 1
957
+ scope_i += 1
958
+
959
+ i += 1
960
+
961
+ # close any remaining open scopes
962
+ for _ in range(opened_scopes):
963
+ scopes.append((end_i - skipped_i, None, None))
964
+
965
+ process_launches(launch_structs, 0, len(launch_structs), 0, 0, 0)
966
+
967
+ # end of simplify_graph
968
+ else:
969
+ launches = launch_structs
970
+ scopes = kernel_scopes
971
+
972
+ node_labels = {}
973
+ inserted_arrays = {} # mapping from array ptr to array
974
+ kernel_launch_count = defaultdict(int)
975
+ # array -> list of kernels that modify it
976
+ manipulated_nodes = defaultdict(list)
977
+
978
+ indent_level = 0
979
+
980
+ input_output_ptr = set()
981
+ for input in track_inputs:
982
+ input_output_ptr.add(input.ptr)
983
+ for output in track_outputs:
984
+ input_output_ptr.add(output.ptr)
985
+
986
+ def add_array_node(x: wp.array, name: str, active_scope_stack=None):
987
+ if active_scope_stack is None:
988
+ active_scope_stack = []
989
+ nonlocal node_labels
990
+ if x in array_labels:
991
+ name = array_labels[x]
992
+ if x.ptr in node_labels:
993
+ if x.ptr not in input_output_ptr:
994
+ # update name unless it is an input/output array
995
+ if choose_longest_node_name:
996
+ if len(name) > len(node_labels[x.ptr]):
997
+ node_labels[x.ptr] = name
998
+ else:
999
+ node_labels[x.ptr] = name
1000
+ return
1001
+
1002
+ visitor.emit_array_node(x, name, active_scope_stack, indent_level)
1003
+ node_labels[x.ptr] = name
1004
+ inserted_arrays[x.ptr] = x
1005
+
1006
+ for i, x in enumerate(track_inputs):
1007
+ if i < len(track_input_names):
1008
+ name = track_input_names[i]
1009
+ else:
1010
+ name = f"input_{i}"
1011
+ add_array_node(x, name)
1012
+ for i, x in enumerate(track_outputs):
1013
+ if i < len(track_output_names):
1014
+ name = track_output_names[i]
1015
+ else:
1016
+ name = f"output_{i}"
1017
+ add_array_node(x, name)
1018
+ # add arrays which are output of a kernel (used to simplify the graph)
1019
+ computed_nodes = set()
1020
+ for output in track_outputs:
1021
+ computed_nodes.add(output.ptr)
1022
+ active_scope_stack = []
1023
+ active_scope = None
1024
+ active_scope_id = -1
1025
+ active_scope_kernels = {}
1026
+ if not hasattr(tape, "scopes"):
1027
+ ignore_graph_scopes = True
1028
+ if not ignore_graph_scopes and len(scopes) > 0:
1029
+ active_scope = scopes[0]
1030
+ active_scope_id = 0
1031
+ for launch_id, launch in enumerate(launches):
1032
+ if active_scope is not None:
1033
+ if launch_id == active_scope[0]:
1034
+ if active_scope[1] is None:
1035
+ # end previous scope
1036
+ indent_level -= 1
1037
+ visitor.emit_scope_end(indent_level)
1038
+ active_scope_stack = active_scope_stack[:-1]
1039
+ else:
1040
+ # begin new scope
1041
+ active_scope_stack.append(f"scope{active_scope_id}")
1042
+ visitor.emit_scope_begin(active_scope_id, active_scope[1], active_scope[2], indent_level)
1043
+ indent_level += 1
1044
+ # check if we are in the next scope now
1045
+ while (
1046
+ not ignore_graph_scopes
1047
+ and active_scope_id < len(scopes) - 1
1048
+ and launch_id == scopes[active_scope_id + 1][0]
1049
+ ):
1050
+ active_scope_id += 1
1051
+ active_scope = scopes[active_scope_id]
1052
+ active_scope_kernels = {}
1053
+ if active_scope[1] is None:
1054
+ # end previous scope
1055
+ indent_level -= 1
1056
+ visitor.emit_scope_end(indent_level)
1057
+ active_scope_stack = active_scope_stack[:-1]
1058
+ else:
1059
+ # begin new scope
1060
+ active_scope_stack.append(f"scope{active_scope_id}")
1061
+ visitor.emit_scope_begin(active_scope_id, active_scope[1], active_scope[2], indent_level)
1062
+ indent_level += 1
1063
+
1064
+ kernel = launch.kernel
1065
+ launch_data = {
1066
+ "id": launch_id,
1067
+ "dim": launch.dim,
1068
+ "inputs": launch.inputs,
1069
+ "outputs": launch.outputs,
1070
+ "stack_trace": "",
1071
+ "kernel_launch_count": kernel_launch_count[kernel.key],
1072
+ }
1073
+ launch_data.update(launch.metadata)
1074
+
1075
+ rendered = not hide_readonly_arrays or ignore_graph_scopes or kernel.key not in active_scope_kernels
1076
+ if rendered:
1077
+ active_scope_kernels[kernel.key] = launch_id
1078
+
1079
+ if not ignore_graph_scopes and hide_readonly_arrays:
1080
+ k_id = f"kernel{active_scope_kernels[kernel.key]}"
1081
+ else:
1082
+ k_id = f"kernel{launch_id}"
1083
+
1084
+ visitor.emit_kernel_launch_node(kernel, k_id, launch_data, rendered, indent_level)
1085
+
1086
+ # loop over inputs and outputs to add them to the graph
1087
+ input_arrays = []
1088
+ for id, x in enumerate(launch.inputs):
1089
+ name = kernel.adj.args[id].label
1090
+ if isinstance(x, wp.array):
1091
+ if x.ptr is None:
1092
+ continue
1093
+ # if x.ptr in array_to_launch and len(array_to_launch[x.ptr]) > 1:
1094
+ # launch_arg_i = array_to_launch[x.ptr]
1095
+ # actual_input = launch_to_array[launch_arg_i][0]
1096
+ # visitor.emit_edge_array_kernel(actual_input.ptr, k_id, id, indent_level)
1097
+ if not hide_readonly_arrays or x.ptr in computed_nodes or x.ptr in input_output_ptr:
1098
+ xptr = x.ptr
1099
+ if xptr in array_repeated:
1100
+ xptr = array_repeated[xptr]
1101
+ else:
1102
+ add_array_node(x, name, active_scope_stack)
1103
+ # input_arrays.append(x.ptr)
1104
+ visitor.emit_edge_array_kernel(xptr, k_id, id, indent_level)
1105
+ elif isinstance(x, wp.codegen.StructInstance):
1106
+ for varname, var in get_struct_vars(x).items():
1107
+ if isinstance(var, wp.array):
1108
+ if not hide_readonly_arrays or var.ptr in computed_nodes or var.ptr in input_output_ptr:
1109
+ add_array_node(var, f"{name}.{varname}", active_scope_stack)
1110
+ input_arrays.append(var.ptr)
1111
+ xptr = var.ptr
1112
+ if xptr in array_repeated:
1113
+ xptr = array_repeated[xptr]
1114
+ visitor.emit_edge_array_kernel(xptr, k_id, id, indent_level)
1115
+ output_arrays = []
1116
+ for id, x in enumerate(launch.outputs):
1117
+ name = kernel.adj.args[id + len(launch.inputs)].label
1118
+ if isinstance(x, wp.array) and x.ptr is not None:
1119
+ add_array_node(x, name, active_scope_stack)
1120
+ output_arrays.append(x.ptr)
1121
+ computed_nodes.add(x.ptr)
1122
+ visitor.emit_edge_kernel_array(k_id, id, x.ptr, indent_level)
1123
+ elif isinstance(x, wp.codegen.StructInstance):
1124
+ for varname, var in get_struct_vars(x).items():
1125
+ if isinstance(var, wp.array):
1126
+ add_array_node(var, f"{name}.{varname}", active_scope_stack)
1127
+ output_arrays.append(var.ptr)
1128
+ computed_nodes.add(var.ptr)
1129
+ visitor.emit_edge_kernel_array(k_id, id, var.ptr, indent_level)
1130
+
1131
+ for output_x in output_arrays:
1132
+ # track how many kernels modify each array
1133
+ manipulated_nodes[output_x].append(kernel.key)
1134
+
1135
+ kernel_launch_count[kernel.key] += 1
1136
+
1137
+ # close any open scopes
1138
+ for _ in range(len(active_scope_stack)):
1139
+ indent_level -= 1
1140
+ visitor.emit_scope_end(indent_level)
1141
+
1142
+ # add additional edges between arrays
1143
+ for src, dst in wrap_around_connections:
1144
+ if src == dst or src not in inserted_arrays or dst not in inserted_arrays:
1145
+ continue
1146
+ visitor.emit_edge_array_array(inserted_arrays[src], inserted_arrays[dst], indent_level)
1147
+
1148
+
1149
+ def visualize_tape_graphviz(
1150
+ tape: Tape,
1151
+ filename: str,
1152
+ simplify_graph=True,
1153
+ hide_readonly_arrays=False,
1154
+ array_labels: Dict[wp.array, str] = None,
1155
+ choose_longest_node_name: bool = True,
1156
+ ignore_graph_scopes: bool = False,
1157
+ track_inputs: List[wp.array] = None,
1158
+ track_outputs: List[wp.array] = None,
1159
+ track_input_names: List[str] = None,
1160
+ track_output_names: List[str] = None,
1161
+ graph_direction: str = "LR",
1162
+ ):
1163
+ if track_output_names is None:
1164
+ track_output_names = []
1165
+ if track_input_names is None:
1166
+ track_input_names = []
1167
+ if track_outputs is None:
1168
+ track_outputs = []
1169
+ if track_inputs is None:
1170
+ track_inputs = []
1171
+ if array_labels is None:
1172
+ array_labels = {}
1173
+ visitor = GraphvizTapeVisitor()
1174
+ visit_tape(
1175
+ tape,
1176
+ visitor,
1177
+ simplify_graph,
1178
+ hide_readonly_arrays,
1179
+ array_labels,
1180
+ choose_longest_node_name,
1181
+ ignore_graph_scopes,
1182
+ track_inputs,
1183
+ track_outputs,
1184
+ track_input_names,
1185
+ track_output_names,
1186
+ )
1187
+
1188
+ chart = "\n".join(visitor.graphviz_lines)
1189
+ code = f"""digraph " " {{
1190
+ graph [fontname="Helvetica,Arial,sans-serif",tooltip=" "];
1191
+ node [style=rounded,shape=plaintext,fontname="Helvetica,Arial,sans-serif", margin="0.05,0.02", width=0, height=0, tooltip=" "];
1192
+ edge [fontname="Helvetica,Arial,sans-serif",tooltip=" "];
1193
+ rankdir={graph_direction};
1194
+
1195
+ {chart}
1196
+ }}
1197
+ """
1198
+
1199
+ if filename is not None:
1200
+ with open(filename, "w") as f:
1201
+ f.write(code)
1202
+
1203
+ return code