.. _forward_mode_jets: Forward-mode jets ================= .. currentmodule:: warp .. admonition:: Experimental Forward-mode jets are experimental and subject to change without a formal deprecation cycle. A forward-mode *jet* carries a value and its derivatives along a fixed number of directions. The number of directions is the jet's *width*. Pass jets to a :func:`@wp.func ` to compute the value and derivatives in the same forward pass. With generic argument types, the same function can accept plain values and jets. .. _jets_when_to_use: When to use jets ---------------- Jets fit local derivatives with a small, fixed number of directions. First-order jets give Jacobians or directional derivatives. Second-order jets also give Hessians. For the gradient of a scalar loss over many inputs or a state sized at runtime, use :ref:`reverse mode ` instead. One backward sweep gives the gradient with respect to all inputs. Jets are a good fit when many outputs share work. For a function with three inputs and 32 outputs, a width-3 jet carries the three directions through one forward pass. A row-by-row reverse-mode Jacobian takes 32 backward sweeps. Jets can also compute a Jacobian-vector product directly from a chosen direction. To choose between jets and reverse mode for a specific derivative, see :ref:`choosing_a_differentiation_tool`. .. _a-small-first-example: Example: Sums and differences ----------------------------- Consider :math:`u = a + b` and :math:`v = a - b` at :math:`a = 2, b = 3`. A width-2 :func:`wp.JetSpace ` gives one derivative direction per input. Inside the kernel, ``sum_difference_space.seed()`` turns the input values into jets and sets their ``grad`` fields to the two rows of the identity matrix. Read the Jacobian rows from ``u.grad`` and ``v.grad`` during the forward pass and store them in a regular output array. The ``grad`` fields belong to the jets themselves. The output array uses the default ``requires_grad=False``. .. testcode:: import warp as wp sum_difference_space = wp.JetSpace((wp.float32, wp.float32)) # One direction per input. @wp.kernel(enable_backward=False) def sum_difference(jacobian: wp.array[sum_difference_space.grad_type_scalar]): # Coordinate directions: a.grad = (1, 0), b.grad = (0, 1). a, b = sum_difference_space.seed(2.0, 3.0) u = a + b v = a - b jacobian[0] = u.grad jacobian[1] = v.grad jacobian = wp.zeros(2, dtype=sum_difference_space.grad_type_scalar) wp.launch(sum_difference, dim=1, outputs=[jacobian]) print(f"jacobian =\n{jacobian.numpy()}") .. testoutput:: jacobian = [[ 1. 1.] [ 1. -1.]] .. note:: Set ``enable_backward=False`` on :func:`@wp.kernel ` to skip compiling the adjoint if you only need the forward pass. This works for kernels that compute derivatives with jets or :func:`wp.grad ` in the forward pass. Keep backward code enabled if the kernel needs to run backward on a :class:`wp.Tape `. How jets carry derivatives -------------------------- A first-order jet has the form .. math:: x = \text{value} + \sum_{q=1}^{w} \text{grad}_q \, \varepsilon_q where the *width* :math:`w` is the number of directions and each :math:`\varepsilon_q` is a formal infinitesimal. Their products vanish, so :math:`\varepsilon_q \varepsilon_r = 0` for all :math:`q, r`. When two jets multiply, their values multiply and their derivatives combine by the product rule. The coefficient :math:`\text{grad}_q` of the result is its derivative along direction :math:`q`. The ``grad`` field holds one derivative for each of the :math:`w` directions, with one row for each component of a vector value. Seed the jets along the coordinate axes to get the usual gradient or Jacobian. :func:`wp.JetSpace ` creates first-order jets. :func:`wp.JetSpace2 ` creates second-order jets, which retain the products :math:`\varepsilon_q \varepsilon_r` and drop terms of degree three and above. A second-order jet carries a dense Hessian. - :func:`wp.JetSpace ` returns a namespace for a *jet space*, called ``J`` in the examples. The namespace contains compatible jet types that share the same derivative directions and seeding helpers such as ``J.seed()``. - A *jet type* describes a kind of value, such as ``J.scalar`` for a scalar, ``J.vec2`` for a two-component vector, or ``J.mat22`` for a 2x2 matrix. Inputs and intermediates of the same kind use the same type within a space. - A *jet* is an instance of one of those types. The seeding helpers create jets inside a kernel. For a jet ``a``, ``a.value`` and ``a.grad`` hold its value and derivatives. A ``J.vec2`` jet stores its derivatives in a ``J.grad_type_vec2``, a plain Warp :math:`2 \times w` matrix with one row per component. Branching on jet values ^^^^^^^^^^^^^^^^^^^^^^^ To compare two scalar jets, write ``wp.value(a) < wp.value(b)``. The same expression works with plain floats because :func:`wp.value() ` returns either the jet's value or the original float. The result of the branch carries the derivatives of the selected expression. Arithmetic overloads that accept a plain operand treat it as a constant. When selecting between jets with ``wp.where``, use branches of the same jet type. To use a plain value as one branch, wrap it with the appropriate constant helper. In a ``float32`` space, ``wp.where(wp.value(a) > 0.0, a, J.constant(0.0))`` selects between two scalar jets. .. _inverse-kinematics-example: Example: Inverse kinematics --------------------------- Consider a two-link arm in 2D. Its four degrees of freedom are the two components of ``base_pos``, the ``shoulder_angle`` measured from the x-axis, and the ``elbow_angle`` relative to the upper arm. To bring the end of the arm to ``target_pos``, use the difference between the end position and the target as the least-squares residual. Write ``residual`` with generic argument types so it accepts plain values and jets. A kernel or another :func:`@wp.func ` can seed the inputs in a width-4 jet space, one direction per scalar component. The gradient of the returned jet is the residual's Jacobian. .. testcode:: from typing import Any import numpy as np import warp as wp J = wp.JetSpace((wp.vec2, wp.float32, wp.float32)) # width 4 @wp.func def residual(base_pos: Any, shoulder_angle: Any, elbow_angle: Any, target_pos: wp.vec2): # Both links have unit length. elbow_pos = base_pos + wp.cos(shoulder_angle) * wp.vec2(1.0, 0.0) + wp.sin(shoulder_angle) * wp.vec2(0.0, 1.0) forearm_angle = shoulder_angle + elbow_angle end_pos = elbow_pos + wp.cos(forearm_angle) * wp.vec2(1.0, 0.0) + wp.sin(forearm_angle) * wp.vec2(0.0, 1.0) return end_pos - target_pos @wp.kernel(enable_backward=False) def residual_jacobian( base_pos: wp.array[wp.vec2], shoulder_angle: wp.array[float], elbow_angle: wp.array[float], target_pos: wp.array[wp.vec2], jacobian: wp.array[J.grad_type_vec2], # a vec2 jet's gradients: 2x4 here ): tid = wp.tid() jet_base_pos, jet_shoulder_angle, jet_elbow_angle = J.seed(base_pos[tid], shoulder_angle[tid], elbow_angle[tid]) jet_residual = residual(jet_base_pos, jet_shoulder_angle, jet_elbow_angle, target_pos[tid]) jacobian[tid] = jet_residual.grad base_pos = wp.array([[0.0, 0.0]], dtype=wp.vec2) shoulder_angle = wp.array([np.radians(45.0)], dtype=float) elbow_angle = wp.array([np.radians(-45.0)], dtype=float) target_pos = wp.array([[-0.5, 0.5]], dtype=wp.vec2) jacobian = wp.zeros(1, dtype=J.grad_type_vec2) wp.launch(residual_jacobian, dim=1, inputs=[base_pos, shoulder_angle, elbow_angle, target_pos], outputs=[jacobian]) print(f"jacobian =\n{np.round(jacobian.numpy()[0], 4)}") .. testoutput:: jacobian = [[ 1. 0. -0.7071 0. ] [ 0. 1. 1.7071 1. ]] The rows correspond to the x and y components of the residual. The columns correspond to the x and y coordinates of the base, the shoulder angle, and the elbow angle. Expressions such as ``end_pos - target_pos`` and calls to ``wp.sin()`` work with jets in the same function. The target is a plain value, so Warp treats it as a constant when differentiating the residual. Slots and seeding ----------------- 1. Choose the slots. Pass one type per input to :func:`wp.JetSpace `. Supported types include scalars, ``vec2``, ``vec3``, :ref:`quaternions `, and matrices of shape ``mat22``, ``mat33``, ``mat32``, or ``mat23``. The default width is the total number of scalar components. For example, ``(wp.vec2, wp.float32, wp.float32)`` gives width 4. Two ``vec3`` endpoints of a spring give width 6. 2. Seed the inputs. In the kernel, pass one value per slot to ``J.seed()``. Each input component gets a unit seed in its own direction. The directions follow slot order, then component order within each slot, with matrix components ordered row-major. 3. Read the derivatives. The result jet's ``value`` field holds the function value and its ``grad`` field holds the Jacobian. For a vector result, each row corresponds to an output component and each column to an input component. Matrix jets flatten their output entries in row-major order, so a ``mat22`` result has four rows. Each intermediate jet carries derivatives for every direction, so wider spaces can increase register pressure and compilation time. For mesh contact, a local edge-edge or point-triangle constraint uses four ``vec3`` vertex positions, giving width 12. Look up jet types ^^^^^^^^^^^^^^^^^ For a Warp value type ``X``, the namespace provides the jet type ``J.X`` and the type of its ``grad`` field, ``J.grad_type_X``. For example, a ``vec2`` value gives these types. .. list-table:: :header-rows: 1 * - Type - Namespace attribute - Host lookup * - Jet for a ``vec2`` value - ``J.vec2`` - ``J.jet_type(wp.vec2)`` * - Type of its ``grad`` field - ``J.grad_type_vec2`` - ``J.grad_type(wp.vec2)`` Use the attributes inside a kernel or :func:`@wp.func `. The host lookup calls also work in annotations. ``J.vec2`` is the type of any ``vec2`` jet in that space, including intermediate results. Its ``grad`` field is a :math:`2 \times w` matrix for a space of width :math:`w`. Construct jets from components ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use jet-space helpers to construct jets from components. For example, use ``J.make_vec3(a, b, c)`` with three scalar jets or ``J.make_mat33()`` with three column jets in a first-order space. The ordinary ``wp.vec3()`` and ``wp.mat33()`` constructors expect plain values. You can also assign components of an existing jet, as in ``v[i] = s`` or ``F[i, j] = s``. Width and directional --------------------- To compute Jacobian-vector products (JVPs) directly, set the ``width`` of :func:`wp.JetSpace ` to the number of directions you need and supply those directions explicitly. ``J.seed()`` is available only when the width equals the total number of scalar components in the slots. Pass ``J.directional()`` the same input values as ``J.seed()``, followed by ``width * len(slots)`` direction values. For each direction, pass one value per slot in slot order, using the slot's type. These values initialize the ``grad`` fields. The output gradients give the Jacobian times each direction vector. Suppose the shoulder angle increases as the elbow angle decreases at the same rate. Use scalar slots for ``shoulder_angle`` and ``elbow_angle`` and set ``width=1`` for the single direction ``(1, -1)``. The default width for these slots is ``2``. The directional derivative is the shoulder angle column of the Jacobian minus the elbow angle column. The forearm keeps its orientation, so the end of the arm and the elbow move by the same displacement. .. testcode:: Jd = wp.JetSpace((wp.float32, wp.float32), width=1) @wp.kernel(enable_backward=False) def residual_directional_derivative( base_pos: wp.array[wp.vec2], shoulder_angle: wp.array[float], elbow_angle: wp.array[float], target_pos: wp.array[wp.vec2], residual_jvp: wp.array[Jd.grad_type_vec2], ): tid = wp.tid() # Increase the shoulder angle and decrease the elbow angle at the same rate. jet_shoulder_angle, jet_elbow_angle = Jd.directional(shoulder_angle[tid], elbow_angle[tid], 1.0, -1.0) jet_residual = residual(base_pos[tid], jet_shoulder_angle, jet_elbow_angle, target_pos[tid]) residual_jvp[tid] = jet_residual.grad residual_jvp = wp.zeros(1, dtype=Jd.grad_type_vec2) wp.launch( residual_directional_derivative, dim=1, inputs=[base_pos, shoulder_angle, elbow_angle, target_pos], outputs=[residual_jvp], ) print("residual_jvp =", np.round(residual_jvp.numpy()[0, :, 0], 4)) .. testoutput:: residual_jvp = [-0.7071 0.7071] Component-wise seeding ^^^^^^^^^^^^^^^^^^^^^^ To seed scalar variables individually, pass the number of scalars to the constructor, as in ``wp.JetSpace(4)``. The width defaults to that count and can be set explicitly with ``width``. Call ``J.variable(x, direction)`` to create a scalar jet with value ``x`` and a unit derivative along ``direction``. .. testcode:: Jn = wp.JetSpace(4) # four scalars, width 4 @wp.kernel(enable_backward=False) def sum_of_cubes_gradient(x: wp.array2d[float], gradient: wp.array[Jn.grad_type_scalar]): tid = wp.tid() total = Jn.constant(0.0) for k in range(4): xk = Jn.variable(x[tid, k], k) total = total + xk * xk * xk gradient[tid] = total.grad x = wp.array([[1.0, 2.0, 3.0, 4.0]], dtype=float) gradient = wp.zeros(1, dtype=Jn.grad_type_scalar) wp.launch(sum_of_cubes_gradient, dim=1, inputs=[x], outputs=[gradient]) print("gradient =", gradient.numpy()[0]) .. testoutput:: gradient = [ 3. 12. 27. 48.] .. _jets_rotations: Rotations --------- - For derivatives with respect to quaternion components, use a :class:`wp.quat ` slot. It seeds one direction for each of the four components, treating them as independent. - For derivatives along the rotation axes, seed a ``vec3`` rotation vector and use ``J.exp_map()`` to map it to a unit quaternion. The map is smooth at zero. In the following example, ``theta`` is a rotation vector seeded at ``theta = 0``. Rotating ``x = (1, 0, 0)`` gives the derivatives of the rotated point along the three rotation axes. .. testcode:: rotation_space = wp.JetSpace((wp.vec3,)) # a rotation vector, width 3 @wp.kernel(enable_backward=False) def rotation_derivative(out: wp.array[rotation_space.grad_type_vec3]): theta = rotation_space.seed(wp.vec3(0.0, 0.0, 0.0)) x = wp.quat_rotate(rotation_space.exp_map(theta), wp.vec3(1.0, 0.0, 0.0)) out[0] = x.grad # row r: derivatives of component r along the three rotation axes out = wp.zeros(1, dtype=rotation_space.grad_type_vec3) wp.launch(rotation_derivative, dim=1, outputs=[out]) print(out.numpy()[0]) .. testoutput:: [[ 0. 0. 0.] [ 0. 0. 1.] [ 0. -1. 0.]] The second and third columns show that a rotation about ``y`` moves the point along ``-z`` and a rotation about ``z`` moves it along ``+y``. Quaternion operations ^^^^^^^^^^^^^^^^^^^^^ First- and second-order quaternion jets support these operations with jet or plain operands where applicable. - Use ``+``, ``-``, negation, scaling, the Hamilton product ``*``, and indexing. In a blend ``(1 - t) * q0 + t * q1``, use a jet scalar for ``t`` and plain quaternions for the endpoints to differentiate along the blend parameter. - Rotate vectors with :func:`wp.quat_rotate() ` and :func:`wp.quat_rotate_inv() `. Other quaternion functions include :func:`wp.quat_inverse() `, :func:`wp.dot() `, :func:`wp.length() `, and :func:`wp.normalize() `. - Construct a quaternion with :func:`wp.quat_from_axis_angle() `, ``J.make_quat()`` from four scalar jets, or ``J.constant_quat()`` from a plain quaternion. For an intrinsic Newton step on a rotation ``q0``, evaluate ``J.exp_map(theta) * q0`` with the jet seeded at ``theta = 0``, then update ``q0`` with the step from the solve. For a Newton solve using second-order quaternion jets, see `example_quat_shape_align.py `__, which runs with ``python -m warp.examples.optim.example_quat_shape_align``. .. _jets_hessians: Hessians -------- A second-order jet from :func:`wp.JetSpace2 ` carries the function value, gradient, and Hessian together. You can also compute the Hessian one row at a time by combining first-order jets from :func:`wp.JetSpace ` with :class:`wp.Tape ` or :func:`wp.grad `. Reverse mode alone gives first derivatives in Warp. Pass the input types to :func:`wp.JetSpace2 ` and seed one value per slot as you would with :func:`wp.JetSpace `. Second-order slots can be scalars, ``vec2``, ``vec3``, or ``quat``. The total number of scalar components in the slots sets the width. ``JetSpace2`` has no ``width`` argument or ``directional()`` helper. For a second-order scalar jet, the types of the gradient ``grad`` and dense Hessian ``hess`` are ``J2.grad_type_scalar`` and ``J2.hess_type_scalar``. The following kernel reads both fields and the energy value from the same jet. .. testcode:: J2 = wp.JetSpace2((wp.vec3, wp.vec3)) # width 6 @wp.func def spring_energy(a: Any, b: Any): d = a - b return 0.5 * (wp.length(d) - 1.0) ** 2 @wp.kernel(enable_backward=False) def hessian( x0: wp.array[wp.vec3], x1: wp.array[wp.vec3], val: wp.array[float], grad: wp.array[J2.grad_type_scalar], hess: wp.array[J2.hess_type_scalar], ): i = wp.tid() jet_x0, jet_x1 = J2.seed(x0[i], x1[i]) f = spring_energy(jet_x0, jet_x1) val[i] = f.value grad[i] = f.grad hess[i] = f.hess # A spring of rest length one, stretched to length two along x. x0 = wp.array([[0.0, 0.0, 0.0]], dtype=wp.vec3) x1 = wp.array([[2.0, 0.0, 0.0]], dtype=wp.vec3) val = wp.zeros(1, dtype=float) grad = wp.zeros(1, dtype=J2.grad_type_scalar) hess = wp.zeros(1, dtype=J2.hess_type_scalar) wp.launch(hessian, dim=1, inputs=[x0, x1], outputs=[val, grad, hess]) second_order_hessian = hess.numpy()[0] print("val =", val.numpy()[0]) print("grad =", grad.numpy()[0]) print(f"hess =\n{second_order_hessian}") .. testoutput:: val = 0.5 grad = [-1. 0. 0. 1. 0. 0.] hess = [[ 1. 0. 0. -1. 0. 0. ] [ 0. 0.5 0. 0. -0.5 0. ] [ 0. 0. 0.5 0. 0. -0.5] [-1. 0. 0. 1. 0. 0. ] [ 0. -0.5 0. 0. 0.5 0. ] [ 0. 0. -0.5 0. 0. 0.5]] Reverse-over-forward ^^^^^^^^^^^^^^^^^^^^ :func:`wp.JetSpace2 ` computes the dense Hessian in one forward pass. The number of Hessian entries it carries grows quadratically with the width. For wider jets, you can compute the Hessian one row at a time with reverse mode and width-1 first-order jets. Warp can differentiate the jet arithmetic and seeding helpers with :func:`wp.grad ` on a :func:`@wp.func ` inside a kernel or with :class:`wp.Tape ` across kernels. ``wp.grad`` over ``wp.JetSpace`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For positions :math:`x` and direction :math:`v`, use width-1 jets to compute the scalar directional derivative :math:`g(x, v)` of the energy :math:`E(x)`. Applying :func:`wp.grad ` to that scalar function gives .. math:: \begin{aligned} g(x, v) &= \nabla E(x)^\mathsf{T} v, \\ \nabla_x g(x, v) &= H(x)v, \qquad \nabla_v g(x, v) = \nabla E(x). \end{aligned} - The position adjoints give the Hessian-vector product. Set :math:`v = e_j` for each input coordinate :math:`j`. The product gives column :math:`j`, which the example stores as row :math:`j` because the Hessian is symmetric. - The direction adjoints give the gradient of the energy. The example uses only the position adjoints to fill the Hessian. .. testcode:: J1 = wp.JetSpace((wp.vec3, wp.vec3), width=1) @wp.func def directional_derivative(x0: wp.vec3, x1: wp.vec3, v0: wp.vec3, v1: wp.vec3): # A width-1 jet along the direction (v0, v1): the scalar dE . v. jet_x0, jet_x1 = J1.directional(x0, x1, v0, v1) return spring_energy(jet_x0, jet_x1).grad[0] @wp.kernel(enable_backward=False) def grad_over_jet_hessian( x0: wp.array[wp.vec3], x1: wp.array[wp.vec3], hess: wp.array3d[float], ): i = wp.tid() for j in range(6): # The unit direction e_j over the six coordinates. v0 = wp.vec3(0.0) v1 = wp.vec3(0.0) if j < 3: v0[j] = 1.0 else: v1[j - 3] = 1.0 # The gradient of dE . e_j with respect to (x0, x1) is row j of the Hessian. hv0, hv1, _v0_adj, _v1_adj = wp.grad(directional_derivative)(x0[i], x1[i], v0, v1) for k in range(3): hess[i, j, k] = hv0[k] hess[i, j, 3 + k] = hv1[k] hess = wp.zeros((1, 6, 6), dtype=float) wp.launch(grad_over_jet_hessian, dim=1, inputs=[x0, x1], outputs=[hess]) np.testing.assert_allclose(hess.numpy()[0], second_order_hessian, rtol=1.0e-6, atol=1.0e-6) During each iteration the width-1 jet carries one directional derivative per scalar component. The output array holds all :math:`n^2` Hessian entries for :math:`n` inputs. ``wp.Tape`` over ``wp.JetSpace`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Use a :class:`wp.Tape ` when the computation spans multiple kernel launches. Arrays can carry jets from one kernel to the next. Record the evaluation of the directional derivative on the tape. Each ``tape.backward()`` then gives one Hessian row in the input adjoints. .. testcode:: @wp.kernel def spring_directional_derivative( x0: wp.array[wp.vec3], x1: wp.array[wp.vec3], v0: wp.array[wp.vec3], v1: wp.array[wp.vec3], out: wp.array[float], ): i = wp.tid() out[i] = directional_derivative(x0[i], x1[i], v0[i], v1[i]) x0 = wp.array([[0.0, 0.0, 0.0]], dtype=wp.vec3, requires_grad=True) x1 = wp.array([[2.0, 0.0, 0.0]], dtype=wp.vec3, requires_grad=True) out = wp.zeros(1, dtype=float, requires_grad=True) hess = np.zeros((1, 6, 6)) tape = wp.Tape() for j in range(6): e = np.zeros((1, 6)) e[:, j] = 1.0 v0 = wp.array(e[:, :3], dtype=wp.vec3) v1 = wp.array(e[:, 3:], dtype=wp.vec3) with tape: wp.launch(spring_directional_derivative, dim=1, inputs=[x0, x1, v0, v1], outputs=[out]) # The adjoints of x0 and x1 are row j of the Hessian. tape.backward(grads={out: wp.ones(1, dtype=float)}) hess[:, j, :3] = x0.grad.numpy() hess[:, j, 3:] = x1.grad.numpy() tape.reset() np.testing.assert_allclose(hess[0], second_order_hessian, rtol=1.0e-6, atol=1.0e-6) Hessian-vector products ~~~~~~~~~~~~~~~~~~~~~~~ To compute a Hessian-vector product, seed the width-1 jet with the vector :math:`v` and take one backward pass. This computes :math:`H v` directly. The row-by-row methods above use the same calculation with coordinate vectors. .. testcode:: @wp.kernel(enable_backward=False) def hessian_vector_product( x0: wp.array[wp.vec3], x1: wp.array[wp.vec3], v0: wp.array[wp.vec3], v1: wp.array[wp.vec3], hv: wp.array2d[wp.vec3], ): i = wp.tid() # The gradient of dE . v with respect to the inputs is H v. hv0, hv1, _v0_adj, _v1_adj = wp.grad(directional_derivative)(x0[i], x1[i], v0[i], v1[i]) hv[i, 0] = hv0 hv[i, 1] = hv1 v0 = wp.array([[0.0, 0.0, 0.0]], dtype=wp.vec3) v1 = wp.array([[1.0, 1.0, 0.0]], dtype=wp.vec3) hv = wp.zeros((1, 2), dtype=wp.vec3) wp.launch(hessian_vector_product, dim=1, inputs=[x0, x1, v0, v1], outputs=[hv]) print("hv =", hv.numpy().reshape(6)) .. testoutput:: hv = [-1. -0.5 0. 1. 0.5 0. ] .. _jets_custom_derivatives: Custom derivatives ------------------ A built-in needs a jet overload to accept a jet argument. For example, :func:`wp.mesh_query_point() ` expects a plain query point. If you only use an operation to choose a branch, evaluate it on plain values. If you need derivatives through it, express the computation using operations that accept jets or supply a custom derivative. A custom derivative can also save work when differentiating each step of a computation is expensive. Example: Ellipsoid closest point ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ For a query point :math:`q` outside an ellipsoid with semi-axes :math:`a`, the closest point :math:`p` has components :math:`p_i = a_i^2 q_i / (a_i^2 + t)`. To find the Lagrange multiplier :math:`t`, solve .. math:: f(t, q) = \sum_i \left( \frac{a_i q_i}{a_i^2 + t} \right)^2 - 1 = 0. Differentiate each Newton step ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Newton's method can find the root in a few steps. The functions in this example accept both plain values and jets. Seed the query to compute the derivative through each Newton step. .. testcode:: # One derivative direction per query coordinate. Jq = wp.JetSpace((wp.vec3,)) @wp.func def ellipsoid_newton_step(query: Any, axes: wp.vec3, t: Any): d = wp.cw_mul(axes, axes) + t * wp.vec3(1.0) u = wp.cw_div(wp.cw_mul(axes, query), d) f = wp.dot(u, u) - 1.0 df_dt = -2.0 * wp.dot(u, wp.cw_div(u, d)) return t - f / df_dt @wp.func def ellipsoid_point(query: Any, axes: wp.vec3, t: Any): axes2 = wp.cw_mul(axes, axes) return wp.cw_div(wp.cw_mul(axes2, query), axes2 + t * wp.vec3(1.0)) @wp.kernel(enable_backward=False) def ellipsoid_point_jacobian( query: wp.array[wp.vec3], axes: wp.vec3, jacobian: wp.array[Jq.grad_type_vec3], ): tid = wp.tid() jet_query = Jq.seed(query[tid]) jet_t = Jq.constant(0.0) # Each Newton step propagates the derivatives. for _ in range(20): jet_t = ellipsoid_newton_step(jet_query, axes, jet_t) jacobian[tid] = ellipsoid_point(jet_query, axes, jet_t).grad axes = wp.vec3(1.0, 0.5, 0.25) query = wp.array([[2.0, 1.0, 0.5]], dtype=wp.vec3) jacobian = wp.zeros(1, dtype=Jq.grad_type_vec3) wp.launch( ellipsoid_point_jacobian, dim=1, inputs=[query, axes], outputs=[jacobian], ) print(f"jacobian =\n{np.round(jacobian.numpy()[0], 4)}") .. testoutput:: jacobian = [[ 0.0921 -0.1095 -0.0182] [-0.1095 0.1459 -0.0054] [-0.0182 -0.0054 0.0505]] Differentiate at convergence ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ At the root, :math:`f(t, q) = 0`, so the implicit function theorem gives .. math:: \frac{\partial t}{\partial q} = -\left( \frac{\partial f}{\partial t} \right)^{-1} \frac{\partial f}{\partial q}. 1. Solve for :math:`t` with plain values. 2. Seed the query with jets. 3. Starting from the converged :math:`t`, take one Newton step with the jet query. Since :math:`f` vanishes at the root, this step returns a jet with value :math:`t` and the derivative above. Evaluate the closest point with that jet and read its Jacobian from ``grad``. Both passes use the same generic functions. .. testcode:: @wp.kernel(enable_backward=False) def ellipsoid_point_implicit_jacobian( query: wp.array[wp.vec3], axes: wp.vec3, jacobian: wp.array[Jq.grad_type_vec3], ): tid = wp.tid() t = float(0.0) # Solve for t using plain values. for _ in range(20): t = ellipsoid_newton_step(query[tid], axes, t) jet_query = Jq.seed(query[tid]) # One step with jets gives the derivative at convergence. jet_t = ellipsoid_newton_step(jet_query, axes, t) jacobian[tid] = ellipsoid_point(jet_query, axes, jet_t).grad wp.launch( ellipsoid_point_implicit_jacobian, dim=1, inputs=[query, axes], outputs=[jacobian], ) print(f"jacobian =\n{np.round(jacobian.numpy()[0], 4)}") .. testoutput:: jacobian = [[ 0.0921 -0.1095 -0.0182] [-0.1095 0.1459 -0.0054] [-0.0182 -0.0054 0.0505]] Limitations ----------- Type and width requirements ^^^^^^^^^^^^^^^^^^^^^^^^^^^ * Choose the width when you create the jet space on the host. The number of derivative directions is fixed inside the kernel. * All slots in a space must share a floating-point scalar type. Keep indices and other discrete inputs as ordinary integers. Current gaps ^^^^^^^^^^^^ * ``JetSpace2`` has no matrix jet types. Split a matrix input into columns or scalars and express the matrix computation in terms of those components. To use the supported matrix operations directly, combine first-order matrix jets with reverse mode. * Warp does not support forward-over-reverse. A :func:`wp.grad ` call can compile with a jet input. The returned adjoints describe sensitivities to the fields of the input jet. They do not give the forward derivative of the gradient. For second derivatives, see :ref:`jets_hessians`.