nablaengine 1.0.2__py3-none-any.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.
Files changed (136) hide show
  1. nablaengine/__init__.py +4 -0
  2. nablaengine/_fixtures/README.md +19 -0
  3. nablaengine/_fixtures/data/mf_s0.npz +0 -0
  4. nablaengine/_fixtures/mjlab/LICENSE +27 -0
  5. nablaengine/_fixtures/mjlab/README.md +113 -0
  6. nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
  7. nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
  8. nablaengine/_optional.py +30 -0
  9. nablaengine/_paths.py +38 -0
  10. nablaengine/actuators/__init__.py +169 -0
  11. nablaengine/actuators/bam.py +306 -0
  12. nablaengine/actuators/bam_params/LICENSE +202 -0
  13. nablaengine/actuators/bam_params/xl330/m6.json +19 -0
  14. nablaengine/boxbox.py +259 -0
  15. nablaengine/ccd.py +1122 -0
  16. nablaengine/checks.py +376 -0
  17. nablaengine/cuda.py +483 -0
  18. nablaengine/dist_query.py +628 -0
  19. nablaengine/dual.py +223 -0
  20. nablaengine/dyn_query.py +685 -0
  21. nablaengine/engines.py +114 -0
  22. nablaengine/envs/__init__.py +24 -0
  23. nablaengine/envs/brax.py +165 -0
  24. nablaengine/envs/convert.py +771 -0
  25. nablaengine/envs/dmc.py +523 -0
  26. nablaengine/envs/env.py +233 -0
  27. nablaengine/envs/kin.py +371 -0
  28. nablaengine/envs/ops.py +134 -0
  29. nablaengine/envs/rewards.py +57 -0
  30. nablaengine/fixtures.py +243 -0
  31. nablaengine/forest_engine/__init__.py +0 -0
  32. nablaengine/forest_engine/adjoint.py +1726 -0
  33. nablaengine/forest_engine/adjoint_contact.py +493 -0
  34. nablaengine/forest_engine/bam_hooks.py +248 -0
  35. nablaengine/forest_engine/body_params.py +1007 -0
  36. nablaengine/forest_engine/capacity_diag.py +116 -0
  37. nablaengine/forest_engine/ccd_coop.py +250 -0
  38. nablaengine/forest_engine/chol_blk.py +80 -0
  39. nablaengine/forest_engine/contact_forces.py +142 -0
  40. nablaengine/forest_engine/contact_vjp.py +462 -0
  41. nablaengine/forest_engine/convex.py +1331 -0
  42. nablaengine/forest_engine/cylinder.py +73 -0
  43. nablaengine/forest_engine/dist_device.py +923 -0
  44. nablaengine/forest_engine/dyn_device.py +696 -0
  45. nablaengine/forest_engine/ellipsoid.py +179 -0
  46. nablaengine/forest_engine/elliptic.py +272 -0
  47. nablaengine/forest_engine/equality.py +842 -0
  48. nablaengine/forest_engine/floss.py +148 -0
  49. nablaengine/forest_engine/foot_offset.py +368 -0
  50. nablaengine/forest_engine/free_gyro.py +288 -0
  51. nablaengine/forest_engine/host.py +530 -0
  52. nablaengine/forest_engine/kdof64.py +127 -0
  53. nablaengine/forest_engine/kinematics.py +320 -0
  54. nablaengine/forest_engine/margin.py +167 -0
  55. nablaengine/forest_engine/margin_convex.py +326 -0
  56. nablaengine/forest_engine/midphase.py +439 -0
  57. nablaengine/forest_engine/model_hooks.py +913 -0
  58. nablaengine/forest_engine/motor_hooks.py +50 -0
  59. nablaengine/forest_engine/muscle.py +485 -0
  60. nablaengine/forest_engine/nb128.py +118 -0
  61. nablaengine/forest_engine/nb64.py +163 -0
  62. nablaengine/forest_engine/noslip.py +1124 -0
  63. nablaengine/forest_engine/nv128.py +1944 -0
  64. nablaengine/forest_engine/object_size.py +283 -0
  65. nablaengine/forest_engine/replay_guard.py +40 -0
  66. nablaengine/forest_engine/root_spread.py +126 -0
  67. nablaengine/forest_engine/solref.py +74 -0
  68. nablaengine/forest_engine/source.py +1464 -0
  69. nablaengine/forest_engine/sparse_pattern.py +527 -0
  70. nablaengine/forest_engine/spatial.py +1045 -0
  71. nablaengine/forest_engine/step.py +3083 -0
  72. nablaengine/forest_engine/surrogate.py +498 -0
  73. nablaengine/forest_engine/tape.py +199 -0
  74. nablaengine/forest_engine/tendon.py +845 -0
  75. nablaengine/forest_engine/terrain.py +1059 -0
  76. nablaengine/forest_engine/world_forces.py +166 -0
  77. nablaengine/forest_engine/world_params.py +230 -0
  78. nablaengine/g1_engine/__init__.py +0 -0
  79. nablaengine/g1_engine/adjoint.py +1661 -0
  80. nablaengine/g1_engine/adjoint_contact.py +577 -0
  81. nablaengine/g1_engine/bam_hooks.py +596 -0
  82. nablaengine/g1_engine/condim4.py +245 -0
  83. nablaengine/g1_engine/contact_forces.py +500 -0
  84. nablaengine/g1_engine/cylccd.py +1158 -0
  85. nablaengine/g1_engine/cylinder.py +216 -0
  86. nablaengine/g1_engine/elliptic.py +565 -0
  87. nablaengine/g1_engine/exact_replay.py +61 -0
  88. nablaengine/g1_engine/host.py +358 -0
  89. nablaengine/g1_engine/kinematics.py +320 -0
  90. nablaengine/g1_engine/mesh.py +305 -0
  91. nablaengine/g1_engine/mesh_tables.py +79 -0
  92. nablaengine/g1_engine/model_hooks.py +919 -0
  93. nablaengine/g1_engine/motor_hooks.py +70 -0
  94. nablaengine/g1_engine/replay_guard.py +55 -0
  95. nablaengine/g1_engine/source.py +1107 -0
  96. nablaengine/g1_engine/sphbox.py +93 -0
  97. nablaengine/g1_engine/step.py +3716 -0
  98. nablaengine/g1_engine/tape.py +173 -0
  99. nablaengine/g1_engine/world_params.py +447 -0
  100. nablaengine/identity.py +401 -0
  101. nablaengine/jax_ffi.py +2536 -0
  102. nablaengine/model/__init__.py +1 -0
  103. nablaengine/model/capability.py +694 -0
  104. nablaengine/model/fields.py +317 -0
  105. nablaengine/model/gravcomp.py +64 -0
  106. nablaengine/model/invweight.py +145 -0
  107. nablaengine/motor.py +143 -0
  108. nablaengine/object_geometry.py +609 -0
  109. nablaengine/params.py +258 -0
  110. nablaengine/provenance.py +196 -0
  111. nablaengine/reference/__init__.py +0 -0
  112. nablaengine/reference/adjoint_groups.py +226 -0
  113. nablaengine/reference/jax64.py +690 -0
  114. nablaengine/reference/warp_physics.py +262 -0
  115. nablaengine/sensors/__init__.py +4 -0
  116. nablaengine/sensors/cameras.py +285 -0
  117. nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
  118. nablaengine/sensors/data/livox_mid360.npz +0 -0
  119. nablaengine/sensors/g1.py +521 -0
  120. nablaengine/sensors/jax_rays.py +364 -0
  121. nablaengine/sensors/optix_rays.py +725 -0
  122. nablaengine/sensors/raycore.py +630 -0
  123. nablaengine/sensors/raygrad.py +374 -0
  124. nablaengine/sensors/raygrad_cuda.py +191 -0
  125. nablaengine/sensors/robot_mesh.py +273 -0
  126. nablaengine/sensors/torch_rays.py +275 -0
  127. nablaengine/terrain.py +424 -0
  128. nablaengine/torch_ffi.py +1328 -0
  129. nablaengine/workdir.py +37 -0
  130. nablaengine-1.0.2.dist-info/METADATA +236 -0
  131. nablaengine-1.0.2.dist-info/RECORD +136 -0
  132. nablaengine-1.0.2.dist-info/WHEEL +5 -0
  133. nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
  134. nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
  135. nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
  136. nablaengine-1.0.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,374 @@
1
+ """First-order gradients of ray hit distances (shared by jax_rays and torch_rays; written for jax.numpy and torch)."""
2
+ MIN_COS = 1e-2
3
+ ID_SHIFT, ID_MASK = 24, (1 << 24) - 1
4
+ CAT_OBJECT, CAT_ROBOT = 3, 4
5
+
6
+
7
+ def qmat(xp, q):
8
+ """Rotation matrices (..., 3, 3) of unit quaternions q (..., 4) (w, x, y, z), as G1Sensors._qmat."""
9
+ w, x, y, z = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
10
+ return xp.stack([xp.stack([1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], -1),
11
+ xp.stack([2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], -1),
12
+ xp.stack([2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], -1)], -2)
13
+
14
+
15
+
16
+ def _ein(xp, *args):
17
+ if xp.__name__ == "jax.numpy":
18
+ import jax
19
+ return xp.einsum(*args, precision=jax.lax.Precision.HIGHEST)
20
+ return xp.einsum(*args)
21
+
22
+ def _gather(xp, a, idx):
23
+ B, N = idx.shape
24
+ tail = tuple(a.shape[2:])
25
+ flat = a.reshape(B, a.shape[1], -1)
26
+ C = flat.shape[2]
27
+ if xp.__name__ == "torch":
28
+ out = xp.gather(flat, 1, idx.long()[..., None].expand(B, N, C))
29
+ else:
30
+ out = xp.take_along_axis(flat, xp.broadcast_to(idx[..., None], (B, N, C)), axis=1, mode="fill", fill_value=0)
31
+ return out.reshape((B, N) + tail)
32
+
33
+
34
+ def _none(xp, M):
35
+ return 0 if xp.__name__ == "torch" else M
36
+
37
+
38
+ def _rays(xp, pos, rot, off, dirs):
39
+ o = pos[:, None, :] + _ein(xp, "bij,nj->bni", rot, off)
40
+ r = _ein(xp, "bij,nj->bni", rot, dirs)
41
+ return o, r
42
+
43
+
44
+ def _arange(xp, n, like):
45
+ return xp.arange(n, device=like.device) if xp.__name__ == "torch" else xp.arange(n)
46
+
47
+
48
+ def residuals(xp, pos, rot, off, dirs, xpos, xquat, objects, dist, gid, nrm, mbody, min_cos=MIN_COS):
49
+ """The constants of the tangent map at the primal point (no gradient through them): w = n / (n . r) (0 where not
50
+ valid: misses, grazing), t, the hit point and normal, the object slot one-hot of each hit (B, N, K) with the hit
51
+ point and normal in the slot's frame, the robot body of each hit with the hit point and normal in the body's
52
+ frame. nrm: the normal the tangent maps use (the RGB: facing the camera)."""
53
+ o, r = _rays(xp, pos, rot, off, dirs)
54
+ hit = o + dist[..., None] * r
55
+ den = (nrm * r).sum(-1)
56
+ valid = (dist >= 0) & (abs(den) >= min_cos)
57
+ inv = xp.where(valid, 1.0 / xp.where(valid, den, xp.ones_like(den)), xp.zeros_like(den))
58
+ cat, idx = gid >> ID_SHIFT, gid & ID_MASK
59
+ hitm = dist >= 0
60
+ res = dict(w=nrm * inv[..., None], dist=dist, hit=hit, nrm=nrm)
61
+ K = objects.shape[1]
62
+ if K:
63
+ oh = (hitm & (cat == CAT_OBJECT))[..., None] & (idx[..., None] == _arange(xp, K, idx))
64
+ res["oh"] = oh.to(dist.dtype) if xp.__name__ == "torch" else oh.astype(dist.dtype)
65
+ P, Ro = objects[..., 0:3], objects[..., 3:12].reshape(objects.shape[:2] + (3, 3))
66
+ loc = _ein(xp, "bkji,bnj->bnki", Ro, hit) - _ein(xp, "bkji,bkj->bki", Ro, P)[:, None]
67
+ res["oloc"] = _ein(xp, "bnk,bnki->bni", res["oh"], loc)
68
+ res["onloc"] = _ein(xp, "bnk,bkji,bnj->bni", res["oh"], Ro, nrm)
69
+ nm = mbody.shape[0]
70
+ res["rob"] = hitm & (cat == CAT_ROBOT)
71
+ gi = idx.clip(0, nm - 1)
72
+ bidx = mbody[gi.long() if xp.__name__ == "torch" else gi]
73
+ res["bidx"] = xp.where(res["rob"], bidx.to(idx.dtype) if xp.__name__ == "torch" else bidx,
74
+ xp.full_like(idx, _none(xp, xpos.shape[1])))
75
+ Rb = qmat(xp, _gather(xp, xquat, res["bidx"]))
76
+ res["rloc"] = _ein(xp, "bnji,bnj->bni", Rb, hit - _gather(xp, xpos, res["bidx"]))
77
+ res["rnloc"] = _ein(xp, "bnji,bnj->bni", Rb, nrm)
78
+ return res
79
+
80
+
81
+ def tangent_dist(xp, pos, rot, off, dirs, xpos, xquat, objects, res):
82
+ """A function of the inputs whose derivative at the primal point is the first-order dt (its value has no
83
+ meaning): -w . (o + t r - x), x the hit's material point (moving with its object slot or robot body; static
84
+ surfaces: no term)."""
85
+ w, t = res["w"], res["dist"]
86
+ g = -(w * pos[:, None]).sum(-1) - _ein(xp, "bni,bij,nj->bn", w, rot, off) \
87
+ - t * _ein(xp, "bni,bij,nj->bn", w, rot, dirs)
88
+ if "oh" in res:
89
+ P, Ro = objects[..., 0:3], objects[..., 3:12].reshape(objects.shape[:2] + (3, 3))
90
+ g = g + _ein(xp, "bnk,bni,bki->bn", res["oh"], w, P) + _ein(xp, "bnk,bni,bkij,bnj->bn", res["oh"], w, Ro,
91
+ res["oloc"])
92
+ Rb = qmat(xp, _gather(xp, xquat, res["bidx"]))
93
+ xr = _gather(xp, xpos, res["bidx"]) + _ein(xp, "bnij,bnj->bni", Rb, res["rloc"])
94
+ return g + xp.where(res["rob"], (w * xr).sum(-1), xp.zeros_like(g))
95
+
96
+
97
+
98
+ def vjp_torch(u, pos, rot, off, dirs, xpos, xquat, objects, dist, gid, nrm, mbody, min_cos, need):
99
+ """The transpose of tangent_dist's derivative in closed form for PyTorch (autograd through residuals /
100
+ tangent_dist is several times slower): cotangents of (pos, rot, off, dirs, xpos, xquat, objects) for dist's
101
+ cotangent u (B, N), None where need[i] is False. Moving surfaces are handled on their rays only (index_add)."""
102
+ import torch
103
+ B, N = dist.shape
104
+ o, r = _rays(torch, pos, rot, off, dirs)
105
+ den = (nrm * r).sum(-1)
106
+ valid = (dist >= 0) & (den.abs() >= min_cos)
107
+ W = torch.where(valid, u / torch.where(valid, den, torch.ones_like(den)), torch.zeros_like(den))[..., None] * nrm
108
+ Wt = W * dist[..., None]
109
+ out = [None] * 7
110
+ if need[0]:
111
+ out[0] = -W.sum(1)
112
+ if need[1]:
113
+ out[1] = -(torch.einsum("bni,nj->bij", W, off) + torch.einsum("bni,nj->bij", Wt, dirs))
114
+ if need[2]:
115
+ out[2] = -torch.einsum("bni,bij->nj", W, rot)
116
+ if need[3]:
117
+ out[3] = -torch.einsum("bni,bij->nj", Wt, rot)
118
+ cat, idx = gid >> ID_SHIFT, (gid & ID_MASK).long()
119
+
120
+ def subset(c):
121
+ sel = (valid & (cat == c)).reshape(-1).nonzero().squeeze(1)
122
+ b = sel // N
123
+ hit = o.reshape(-1, 3)[sel] + dist.reshape(-1)[sel, None] * r.reshape(-1, 3)[sel]
124
+ return sel, b, hit, W.reshape(-1, 3)[sel]
125
+
126
+ K = objects.shape[1]
127
+ if need[6]:
128
+ g = torch.zeros(B * K, 12, device=u.device, dtype=u.dtype)
129
+ if K:
130
+ sel, b, hit, Ws = subset(CAT_OBJECT)
131
+ k = idx.reshape(-1)[sel].clamp(0, K - 1)
132
+ ob = objects[b, k]
133
+ Ro = ob[:, 3:12].reshape(-1, 3, 3)
134
+ loc = torch.einsum("sji,sj->si", Ro, hit - ob[:, 0:3])
135
+ g.index_add_(0, b * K + k, torch.cat([Ws, (Ws[:, :, None] * loc[:, None, :]).flatten(1)], 1))
136
+ out[6] = torch.cat([g.reshape(B, K, 12), torch.zeros(B, K, objects.shape[2] - 12, device=u.device,
137
+ dtype=u.dtype)], 2)
138
+ if need[4] or need[5]:
139
+ nb = xpos.shape[1]
140
+ sel, b, hit, Ws = subset(CAT_ROBOT)
141
+ body = mbody[idx.reshape(-1)[sel].clamp(0, mbody.shape[0] - 1)]
142
+ Rb = qmat(torch, xquat[b, body])
143
+ loc = torch.einsum("sji,sj->si", Rb, hit - xpos[b, body])
144
+ key = b * nb + body
145
+ if need[4]:
146
+ out[4] = torch.zeros(B * nb, 3, device=u.device, dtype=u.dtype).index_add_(0, key, Ws).reshape(B, nb, 3)
147
+ if need[5]:
148
+ gR = torch.zeros(B * nb, 9, device=u.device, dtype=u.dtype).index_add_(
149
+ 0, key, (Ws[:, :, None] * loc[:, None, :]).flatten(1)).reshape(B, nb, 3, 3)
150
+ with torch.enable_grad():
151
+ q = xquat.detach().requires_grad_(True)
152
+ out[5], = torch.autograd.grad(qmat(torch, q), q, gR)
153
+ return out
154
+
155
+
156
+
157
+ from dataclasses import dataclass
158
+
159
+
160
+ @dataclass(frozen=True)
161
+ class ImageSpec:
162
+ """An image sensor's layout for the smoothed gradient and the fused backward: kind "depth" | "height" | "rgb",
163
+ H x W pixels; projection ptype 0 pinhole (col = cx - p0 Y / X, row = cy - p1 Z / X of the hit in the sensor frame)
164
+ or 1 grid (col = X p0, row = Y p0); the value V = (x - c) . (R a_cam + a_world)."""
165
+ kind: str
166
+ H: int
167
+ W: int
168
+ ptype: int
169
+ p0: float
170
+ p1: float
171
+ a_cam: tuple = (0.0, 0.0, 0.0)
172
+ a_world: tuple = (0.0, 0.0, 0.0)
173
+
174
+
175
+ def image_spec(sensor, kind):
176
+ """ImageSpec of a cameras.DepthCamera (kind "depth" or "rgb") or cameras.HeightScan (kind "height")."""
177
+ import numpy as np
178
+ if kind == "height":
179
+ nx = len(np.arange(-sensor.size[0] / 2, sensor.size[0] / 2 + sensor.resolution * 0.5, sensor.resolution))
180
+ ny = len(np.arange(-sensor.size[1] / 2, sensor.size[1] / 2 + sensor.resolution * 0.5, sensor.resolution))
181
+ return ImageSpec("height", ny, nx, 1, 1.0 / sensor.resolution, 0.0, a_world=(0.0, 0.0, -1.0))
182
+ fx = sensor.width / 2 / np.tan(np.radians(sensor.hfov) / 2)
183
+ fy = sensor.height / 2 / np.tan(np.radians(sensor.vfov) / 2)
184
+ return ImageSpec(kind, sensor.height, sensor.width, 0, float(fx), float(fy),
185
+ a_cam=(1.0, 0.0, 0.0) if kind == "depth" else (0.0, 0.0, 0.0))
186
+
187
+
188
+ _MATS = {}
189
+
190
+
191
+ def smoothing_mats(n, sigma):
192
+ """(G, D) (n, n) float32 NumPy: the 1-D Gaussian of sigma (cells; truncated at 3 sigma, edge-replicated border:
193
+ the padded weights fold onto the border cell; sigma 0: identity) and the central difference (one-sided at the
194
+ border)."""
195
+ import numpy as np
196
+ key = (n, float(sigma))
197
+ if key not in _MATS:
198
+ G = np.zeros((n, n))
199
+ if sigma > 0:
200
+ r = int(np.ceil(3 * sigma))
201
+ k = np.exp(-0.5 * (np.arange(-r, r + 1) / sigma) ** 2)
202
+ k /= k.sum()
203
+ for i in range(n):
204
+ for m, km in zip(range(-r, r + 1), k):
205
+ G[i, min(max(i + m, 0), n - 1)] += km
206
+ else:
207
+ G = np.eye(n)
208
+ D = np.zeros((n, n))
209
+ if n > 1:
210
+ for i in range(n):
211
+ lo, hi = max(i - 1, 0), min(i + 1, n - 1)
212
+ D[i, hi] += 1.0 / (hi - lo)
213
+ D[i, lo] -= 1.0 / (hi - lo)
214
+ _MATS[key] = (G.astype(np.float32), D.astype(np.float32))
215
+ return _MATS[key]
216
+
217
+
218
+ class Smoother:
219
+ """The separable smoothing of (B, H, W[, C]) images: S = Gv I Gu^T, its image gradient (d/dcol, d/drow) and the
220
+ transposes (xp: jax.numpy or torch; the matrices on like's device)."""
221
+
222
+ def __init__(self, xp, H, W, sigma, like=None):
223
+ Gv, Dv = smoothing_mats(H, sigma)
224
+ Gu, Du = smoothing_mats(W, sigma)
225
+ if xp.__name__ == "torch":
226
+ t = lambda a: xp.as_tensor(a, device=like.device)
227
+ else:
228
+ t = xp.asarray
229
+ self.xp, self.Gv, self.Gu, self.Dv, self.Du = xp, t(Gv), t(Gu), t(Dv), t(Du)
230
+
231
+ def g(self, x):
232
+ return _ein(self.xp, "ij,bjk...,lk->bil...", self.Gv, x, self.Gu)
233
+
234
+ def gt(self, x):
235
+ return _ein(self.xp, "ji,bjk...,kl->bil...", self.Gv, x, self.Gu)
236
+
237
+ def grad(self, S):
238
+ return _ein(self.xp, "bik...,lk->bil...", S, self.Du), _ein(self.xp, "ij,bjk...->bik...", self.Dv, S)
239
+
240
+
241
+ def _sl(axis, a, b, nd):
242
+ return tuple(slice(a, b) if i == axis else slice(None) for i in range(nd))
243
+
244
+
245
+ def _pad_axis(xp, x, axis, before):
246
+ shp = list(x.shape)
247
+ shp[axis] = 1
248
+ z = xp.zeros(tuple(shp), dtype=x.dtype, **({"device": x.device} if xp.__name__ == "torch" else {}))
249
+ parts = [z, x] if before else [x, z]
250
+ return xp.cat(parts, axis) if xp.__name__ == "torch" else xp.concatenate(parts, axis)
251
+
252
+
253
+ def _interfaces(xp, img, m, t, axis):
254
+ nd = m.ndim
255
+ A, B = _sl(axis, None, -1, nd), _sl(axis, 1, None, nd)
256
+ ma, mb = m[A] > 0, m[B] > 0
257
+ pick_a = ma & (~mb | (t[A] <= t[B]))
258
+ J = img[_sl(axis, 1, None, img.ndim)] - img[_sl(axis, None, -1, img.ndim)]
259
+ return J, pick_a
260
+
261
+
262
+ def _half_weights(xp, n, like, axis, nd):
263
+ import numpy as np
264
+ w = np.full(n, 0.5, np.float32)
265
+ if n > 1:
266
+ w[0] = w[-1] = 1.0
267
+ shp = [1] * nd
268
+ shp[axis] = n
269
+ w = w.reshape(shp)
270
+ return xp.as_tensor(w, device=like.device) if xp.__name__ == "torch" else xp.asarray(w)
271
+
272
+
273
+ def _flux(xp, img, m, t, vel, axis):
274
+ J, pick_a = _interfaces(xp, img, m, t, axis)
275
+ nd = m.ndim
276
+ v = xp.where(pick_a, vel[_sl(axis, None, -1, nd)], vel[_sl(axis, 1, None, nd)])
277
+ if img.ndim == 4:
278
+ v = v[..., None]
279
+ f = J * v
280
+ w = _half_weights(xp, img.shape[axis], img, axis, img.ndim)
281
+ return (_pad_axis(xp, f, axis, False) + _pad_axis(xp, f, axis, True)) * w
282
+
283
+
284
+ def _flux_t(xp, img, m, t, c, axis):
285
+ J, pick_a = _interfaces(xp, img, m, t, axis)
286
+ w = _half_weights(xp, img.shape[axis], img, axis, img.ndim)
287
+ cw = c * w
288
+ g = (cw[_sl(axis, None, -1, img.ndim)] + cw[_sl(axis, 1, None, img.ndim)]) * J
289
+ if img.ndim == 4:
290
+ g = g.sum(-1)
291
+ z = xp.zeros_like(g)
292
+ return _pad_axis(xp, xp.where(pick_a, g, z), axis, False) + _pad_axis(xp, xp.where(pick_a, z, g), axis, True)
293
+
294
+
295
+ def image_tangent(sm, img, m, t, dV, dcol, drow):
296
+ """dS (B, H, W[, C]) of the smoothed image for per-pixel tangents dV (B, H, W[, C]) of the value and dcol, drow
297
+ (B, H, W) of the image coordinates; m (B, H, W) the moving-value mask (float), t (B, H, W) the ray distances
298
+ (sm: a Smoother; sigma 0: the unsmoothed image's)."""
299
+ xp = sm.xp
300
+ mm = m[..., None] if img.ndim == 4 else m
301
+ return sm.g(mm * dV - _flux(xp, img, m, t, dcol, 2) - _flux(xp, img, m, t, drow, 1))
302
+
303
+
304
+ def image_transpose(sm, img, m, t, c):
305
+ """The transpose of image_tangent for the cotangent c of S: (per-pixel cotangent of dV (shape of img), of dcol,
306
+ of drow (B, H, W))."""
307
+ xp = sm.xp
308
+ ct = sm.gt(c)
309
+ mm = m[..., None] if img.ndim == 4 else m
310
+ return mm * ct, -_flux_t(xp, img, m, t, ct, 2), -_flux_t(xp, img, m, t, ct, 1)
311
+
312
+
313
+ def functionals(xp, pos, rot, off, dirs, xpos, xquat, objects, res, spec, light=None):
314
+ """Per-ray functions of the inputs whose derivatives at the primal point are the per-ray tangents the fused
315
+ backward transposes (their values have no meaning): dict(t: the hit distance's first order (tangent_dist), V: the
316
+ hit's value, col / row: its image coordinates, ndl: (-light) . n of its (turning) normal)."""
317
+ out = dict(t=tangent_dist(xp, pos, rot, off, dirs, xpos, xquat, objects, res))
318
+ x = res["hit"]
319
+ n = res["nrm"]
320
+ if "oh" in res:
321
+ P, Ro = objects[..., 0:3], objects[..., 3:12].reshape(objects.shape[:2] + (3, 3))
322
+ sel = res["oh"].sum(-1)[..., None] > 0
323
+ xo = _ein(xp, "bnk,bki->bni", res["oh"], P) + _ein(xp, "bnk,bkij,bnj->bni", res["oh"], Ro, res["oloc"])
324
+ no = _ein(xp, "bnk,bkij,bnj->bni", res["oh"], Ro, res["onloc"])
325
+ x, n = xp.where(sel, xo, x), xp.where(sel, no, n)
326
+ Rb = qmat(xp, _gather(xp, xquat, res["bidx"]))
327
+ xr = _gather(xp, xpos, res["bidx"]) + _ein(xp, "bnij,bnj->bni", Rb, res["rloc"])
328
+ nr = _ein(xp, "bnij,bnj->bni", Rb, res["rnloc"])
329
+ rob = res["rob"][..., None]
330
+ x, n = xp.where(rob, xr, x), xp.where(rob, nr, n)
331
+ xc = x - pos[:, None]
332
+ ac = _ein(xp, "bij,j->bi", rot, xp.asarray(spec.a_cam, dtype=rot.dtype) if xp.__name__ != "torch"
333
+ else xp.tensor(spec.a_cam, dtype=rot.dtype, device=rot.device))
334
+ aw = (xp.asarray(spec.a_world, dtype=rot.dtype) if xp.__name__ != "torch"
335
+ else xp.tensor(spec.a_world, dtype=rot.dtype, device=rot.device))
336
+ out["V"] = (xc * ac[:, None]).sum(-1) + (xc * aw).sum(-1)
337
+ xcam = _ein(xp, "bji,bnj->bni", rot, xc)
338
+ if spec.ptype == 0:
339
+ X = xp.where(res["dist"] >= 0, xcam[..., 0], xp.ones_like(xcam[..., 0]))
340
+ out["col"] = -spec.p0 * xcam[..., 1] / X
341
+ out["row"] = -spec.p1 * xcam[..., 2] / X
342
+ else:
343
+ out["col"], out["row"] = spec.p0 * xcam[..., 0], spec.p0 * xcam[..., 1]
344
+ if light is not None:
345
+ lt = xp.asarray(light, dtype=rot.dtype) if xp.__name__ != "torch" else xp.tensor(light, dtype=rot.dtype,
346
+ device=rot.device)
347
+ out["ndl"] = -(n * lt).sum(-1)
348
+ return out
349
+
350
+
351
+ def depth_value(xp, camera, housing, dirs):
352
+ """value_fn for cast_image of a depth camera (cameras.DepthCamera; the ops of G1Sensors' depth): image (B, H, W)
353
+ z-depth (0 invalid), aux the seg ids."""
354
+ H, W = camera.height, camera.width
355
+
356
+ def fn(d, gid, nrm, pos, rot):
357
+ d = xp.where(d >= 0, d + housing, -xp.ones_like(d))
358
+ z = d * dirs[:, 0]
359
+ ok = (d >= 0) & (z >= camera.min_depth) & (z <= camera.max_depth)
360
+ return (xp.where(ok, z, xp.zeros_like(z)).reshape(-1, H, W),
361
+ xp.where(d >= 0, gid, -xp.ones_like(gid)).reshape(-1, H, W), ok.reshape(-1, H, W), None, nrm)
362
+ return fn
363
+
364
+
365
+ def height_value(xp, scan):
366
+ """value_fn for cast_image of a height scan (cameras.HeightScan; the ops of G1Sensors' height scan): image (B, ny,
367
+ nx), aux the hit mask."""
368
+ spec = image_spec(scan, "height")
369
+
370
+ def fn(d, gid, nrm, pos, rot):
371
+ hit_z = pos[:, None, 2] + scan.offset_z - xp.where(d >= 0, d, xp.full_like(d, scan.max_distance))
372
+ img = (pos[:, None, 2] - hit_z).reshape(pos.shape[0], spec.H, spec.W)
373
+ return img, (d >= 0).reshape(img.shape), (d >= 0).reshape(img.shape), None, nrm
374
+ return fn
@@ -0,0 +1,191 @@
1
+ """The fused CUDA backward of the ray gradients (sensors/raygrad): one block per world sums every ray's contribution to
2
+ the cotangents of the sensor frame (pos 3, rot 9), of each body (position 3, rotation matrix 9) and of each object
3
+ slot (position 3, rotation 9) in shared memory; no per-ray tangent is materialised."""
4
+ import ctypes
5
+ import hashlib
6
+ import os
7
+ import subprocess
8
+
9
+ from nablaengine.sensors import raycore
10
+
11
+ SOURCE = r"""
12
+ #include <cuda_runtime.h>
13
+ #include <math.h>
14
+ struct VjpArgs {
15
+ int B, N, nbody, K, nmesh, ncoef, ptype;
16
+ float p0, p1, min_cos;
17
+ float acam[3], awld[3], light[3];
18
+ };
19
+ __device__ __forceinline__ float dot3(const float* a, const float* b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
20
+ __device__ __forceinline__ void mv3(const float* A, const float* v, float* o) {
21
+ for (int i = 0; i < 3; i++) o[i] = A[3 * i] * v[0] + A[3 * i + 1] * v[1] + A[3 * i + 2] * v[2];
22
+ }
23
+ __device__ __forceinline__ void mtv3(const float* A, const float* v, float* o) {
24
+ for (int i = 0; i < 3; i++) o[i] = A[i] * v[0] + A[3 + i] * v[1] + A[6 + i] * v[2];
25
+ }
26
+ __device__ __forceinline__ void qmat(const float* q, float* R) { // as G1Sensors._qmat (not normalised)
27
+ const float w = q[0], x = q[1], y = q[2], z = q[3];
28
+ R[0] = 1 - 2 * (y * y + z * z); R[1] = 2 * (x * y - z * w); R[2] = 2 * (x * z + y * w);
29
+ R[3] = 2 * (x * y + z * w); R[4] = 1 - 2 * (x * x + z * z); R[5] = 2 * (y * z - x * w);
30
+ R[6] = 2 * (x * z - y * w); R[7] = 2 * (y * z + x * w); R[8] = 1 - 2 * (x * x + y * y);
31
+ }
32
+ #define VJP_BLOCK 256
33
+ __global__ void __launch_bounds__(VJP_BLOCK) k_ray_vjp(VjpArgs A, const float* pos, const float* rot,
34
+ const float* off, const float* dir, const float* xpos, const float* xquat, const float* obj, const int* mbody,
35
+ const float* dist, const int* gid, const float* nrm, const float* coef, float* out) {
36
+ extern __shared__ float sh[];
37
+ const int w = blockIdx.x, S = 12 + 12 * (A.nbody + A.K);
38
+ for (int i = threadIdx.x; i < S; i += blockDim.x) sh[i] = 0.f;
39
+ __syncthreads();
40
+ const float* P = pos + 3 * w;
41
+ const float* R = rot + 9 * w;
42
+ float acc[12];
43
+ for (int k = 0; k < 12; k++) acc[k] = 0.f;
44
+ for (int n = threadIdx.x; n < A.N; n += blockDim.x) {
45
+ const long long id = (long long)w * A.N + n;
46
+ const float t = dist[id];
47
+ if (!(t >= 0.f)) continue;
48
+ const float* cf = coef + id * A.ncoef;
49
+ const float at = cf[0], av = A.ncoef > 1 ? cf[1] : 0.f, bu = A.ncoef > 1 ? cf[2] : 0.f,
50
+ bv = A.ncoef > 1 ? cf[3] : 0.f, an = A.ncoef > 4 ? cf[4] : 0.f;
51
+ if (at == 0.f && av == 0.f && bu == 0.f && bv == 0.f && an == 0.f) continue;
52
+ const float nn[3] = {nrm[3 * id], nrm[3 * id + 1], nrm[3 * id + 2]};
53
+ float xcam[3], xc[3], r[3];
54
+ for (int k = 0; k < 3; k++) xcam[k] = off[3 * n + k] + t * dir[3 * n + k];
55
+ mv3(R, xcam, xc);
56
+ mv3(R, dir + 3 * n, r);
57
+ const float den = dot3(nn, r);
58
+ const float ft = fabsf(den) >= A.min_cos ? at / den : 0.f;
59
+ float s[3] = {av * A.acam[0], av * A.acam[1], av * A.acam[2]};
60
+ if (bu != 0.f || bv != 0.f) {
61
+ if (A.ptype == 0) {
62
+ const float iX = 1.f / xcam[0];
63
+ s[0] += (bu * A.p0 * xcam[1] + bv * A.p1 * xcam[2]) * iX * iX;
64
+ s[1] -= bu * A.p0 * iX;
65
+ s[2] -= bv * A.p1 * iX;
66
+ } else {
67
+ s[0] += bu * A.p0;
68
+ s[1] += bv * A.p0;
69
+ }
70
+ }
71
+ float Rs[3], gx[3];
72
+ mv3(R, s, Rs);
73
+ for (int k = 0; k < 3; k++) gx[k] = ft * nn[k] + Rs[k] + av * A.awld[k];
74
+ for (int i = 0; i < 3; i++) {
75
+ acc[i] -= gx[i];
76
+ for (int j = 0; j < 3; j++) acc[3 + 3 * i + j] += xc[i] * s[j] - ft * nn[i] * xcam[j];
77
+ }
78
+ const int g = gid[id], cat = g >> 24, idx = g & 0xFFFFFF;
79
+ int slot = -1;
80
+ const float* sp = nullptr;
81
+ float RS[9];
82
+ if (cat == 3 && idx < A.K) {
83
+ slot = A.nbody + idx;
84
+ sp = obj + ((size_t)w * A.K + idx) * 15;
85
+ for (int k = 0; k < 9; k++) RS[k] = sp[3 + k];
86
+ } else if (cat == 4 && idx < A.nmesh) {
87
+ const int b = mbody[idx];
88
+ slot = b;
89
+ sp = xpos + ((size_t)w * A.nbody + b) * 3;
90
+ qmat(xquat + ((size_t)w * A.nbody + b) * 4, RS);
91
+ }
92
+ if (slot >= 0) {
93
+ float d[3], loc[3], nl[3];
94
+ for (int k = 0; k < 3; k++) d[k] = P[k] + xc[k] - sp[k];
95
+ mtv3(RS, d, loc);
96
+ mtv3(RS, nn, nl);
97
+ float* o = sh + 12 + 12 * slot;
98
+ for (int i = 0; i < 3; i++) {
99
+ atomicAdd(o + i, gx[i]);
100
+ for (int j = 0; j < 3; j++) atomicAdd(o + 3 + 3 * i + j, gx[i] * loc[j] - an * A.light[i] * nl[j]);
101
+ }
102
+ }
103
+ }
104
+ for (int k = 0; k < 12; k++) {
105
+ float v = acc[k];
106
+ for (int m = 16; m > 0; m >>= 1) v += __shfl_down_sync(0xffffffffu, v, m);
107
+ if ((threadIdx.x & 31) == 0) atomicAdd(sh + k, v);
108
+ }
109
+ __syncthreads();
110
+ for (int i = threadIdx.x; i < S; i += blockDim.x) out[(size_t)w * S + i] = sh[i];
111
+ }
112
+ extern "C" int dk_ray_vjp(cudaStream_t st, const VjpArgs* A, const float* pos, const float* rot, const float* off,
113
+ const float* dir, const float* xpos, const float* xquat, const float* obj, const int* mbody,
114
+ const float* dist, const int* gid, const float* nrm, const float* coef, float* out) {
115
+ if (A->B <= 0) return 0;
116
+ const size_t shm = sizeof(float) * (12 + 12 * (size_t)(A->nbody + A->K));
117
+ if (shm > 48 * 1024) return 2;
118
+ k_ray_vjp<<<A->B, VJP_BLOCK, shm, st>>>(*A, pos, rot, off, dir, xpos, xquat, obj, mbody, dist, gid, nrm, coef, out);
119
+ return cudaGetLastError() == cudaSuccess ? 0 : 1;
120
+ }
121
+ extern "C" int dk_ray_vjp_args_size() { return (int)sizeof(VjpArgs); }
122
+ """
123
+
124
+ FFI_SOURCE = r"""
125
+ #include "xla/ffi/api/ffi.h"
126
+ namespace ffi = xla::ffi;
127
+ using BufF = ffi::Buffer<ffi::F32>;
128
+ using BufI = ffi::Buffer<ffi::S32>;
129
+ static ffi::Error vjp_impl(cudaStream_t st, BufF pos, BufF rot, BufF off, BufF dir, BufF xpos, BufF xquat, BufF obj,
130
+ BufI mbody, BufF dist, BufI gid, BufF nrm, BufF coef, int32_t ptype, int32_t nmesh,
131
+ float p0, float p1, float min_cos, float ac0, float ac1, float ac2, float aw0, float aw1,
132
+ float aw2, float l0, float l1, float l2, ffi::Result<BufF> out) {
133
+ const auto dd = dist.dimensions(), dx = xpos.dimensions(), dob = obj.dimensions(), dc = coef.dimensions();
134
+ if (dd.size() != 2 || dx.size() != 3 || dob.size() != 3 || dc.size() != 3)
135
+ return ffi::Error::InvalidArgument("shapes");
136
+ VjpArgs A;
137
+ A.B = (int)dd[0]; A.N = (int)dd[1]; A.nbody = (int)dx[1]; A.K = (int)dob[1]; A.nmesh = nmesh;
138
+ A.ncoef = (int)dc[2]; A.ptype = ptype; A.p0 = p0; A.p1 = p1; A.min_cos = min_cos;
139
+ A.acam[0] = ac0; A.acam[1] = ac1; A.acam[2] = ac2; A.awld[0] = aw0; A.awld[1] = aw1; A.awld[2] = aw2;
140
+ A.light[0] = l0; A.light[1] = l1; A.light[2] = l2;
141
+ int rc = dk_ray_vjp(st, &A, pos.typed_data(), rot.typed_data(), off.typed_data(), dir.typed_data(),
142
+ xpos.typed_data(), xquat.typed_data(), A.K ? obj.typed_data() : nullptr, mbody.typed_data(),
143
+ dist.typed_data(), gid.typed_data(), nrm.typed_data(), coef.typed_data(), out->typed_data());
144
+ return rc ? ffi::Error(ffi::ErrorCode::kInternal, "dk_ray_vjp") : ffi::Error::Success();
145
+ }
146
+ XLA_FFI_DEFINE_HANDLER_SYMBOL(DkRayVjp, vjp_impl,
147
+ ffi::Ffi::Bind().Ctx<ffi::PlatformStream<cudaStream_t>>()
148
+ .Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>().Arg<BufF>()
149
+ .Arg<BufI>().Arg<BufF>().Arg<BufI>().Arg<BufF>().Arg<BufF>()
150
+ .Attr<int32_t>("ptype").Attr<int32_t>("nmesh")
151
+ .Attr<float>("p0").Attr<float>("p1").Attr<float>("min_cos")
152
+ .Attr<float>("ac0").Attr<float>("ac1").Attr<float>("ac2")
153
+ .Attr<float>("aw0").Attr<float>("aw1").Attr<float>("aw2")
154
+ .Attr<float>("l0").Attr<float>("l1").Attr<float>("l2")
155
+ .Ret<BufF>());
156
+ """
157
+
158
+
159
+ class VjpArgs(ctypes.Structure):
160
+ _fields_ = [(k, ctypes.c_int) for k in ("B", "N", "nbody", "K", "nmesh", "ncoef", "ptype")] + \
161
+ [(k, ctypes.c_float) for k in ("p0", "p1", "min_cos")] + [(k, ctypes.c_float * 3) for k in ("acam", "awld",
162
+ "light")]
163
+
164
+
165
+ def build(arch, include=None):
166
+ """The backward's shared library for arch (sm_XY), cached by source (raycore.cache_dir); include: XLA's FFI
167
+ headers for the JAX variant (handler DkRayVjp)."""
168
+ from nablaengine import cuda
169
+ nvcc = cuda.nvcc()
170
+ flags = ["-O3", f"-arch={arch}", "-std=c++17", "-shared", "-Xcompiler", "-fPIC", "-cudart", "static"]
171
+ text = SOURCE + (FFI_SOURCE if include is not None else "")
172
+ if include is not None:
173
+ flags.append(f"-I{include}")
174
+ key = hashlib.sha256((text + " ".join(flags) + nvcc).encode()).hexdigest()[:20]
175
+ out = raycore.cache_dir() / f"libdk_rayvjp{'_jax' if include else ''}_{arch}_{key}.so"
176
+ if not out.exists():
177
+ src = out.with_suffix(".cu")
178
+ src.write_text(text)
179
+ tmp = out.with_suffix(f".tmp{os.getpid()}.so")
180
+ subprocess.run([nvcc, *flags, "-o", str(tmp), str(src)], check=True)
181
+ os.replace(tmp, out)
182
+ return out
183
+
184
+
185
+ def params(spec=None, min_cos=1e-2, light=(0.0, 0.0, 0.0)):
186
+ """(ptype, the 12 floats p0, p1, min_cos, a_cam, a_world, light) of an image spec (raygrad.ImageSpec; None: the
187
+ hit distance alone)."""
188
+ import numpy as np
189
+ if spec is None:
190
+ return 0, np.array([0, 0, min_cos] + [0] * 9, np.float32)
191
+ return spec.ptype, np.array([spec.p0, spec.p1, min_cos, *spec.a_cam, *spec.a_world, *light], np.float32)