Differentiable simulation with PyTorch
Use uipc.torch to fit physical parameters to observations of a simulation.
You define the design variables, their physical meaning, the state values to
observe and a scalar loss. libuipc runs the trajectory on its CUDA backend and
computes a first-order adjoint. PyTorch propagates that derivative through
your parameter map and accumulates the result in parameter.U().grad.
Build this checkout with the CUDA backend and Python bindings enabled, and install PyTorch in the interpreter that loads that build. CPU PyTorch tensors work with the native CUDA simulation. See the installation and gradient check or the native feature interface for C++ and NumPy.
From a design variable to a loss
| Value | Who defines it | Particle example |
|---|---|---|
U |
Trainable PyTorch parameter returned by parameter.U() |
One design variable initially equal to 1 |
P = u2p(U) |
Differentiable map into a fixed-length vector of physical parameters | P[0] = 2 * U[0] gives an initial velocity of 2 m/s |
| Input binding | An integer diff/... attribute on the relevant scene entity |
diff/velocity = [0, -1, -1] binds the particle's x velocity to P[0] |
Y = model() |
Values of the global state DoFs selected after each forward frame | Particle x position at frames 1 and 2 |
L(Y) |
A PyTorch scalar that scores the observations | Half the squared error of the terminal x position |
The binding index and the DoF index belong to two different arrays. An
input binding of 0 means “read physical parameter P[0]”. A value of -1 keeps that
component independent of the design. For an output, read the geometry's
builtin.dof_offset after world initialization and select indices into the
assembled simulation state. A one-point particle can coincidentally have both
indices equal to zero. Adding another body can change the DoF offset. See
supported input attributes and parameter domains.
Run a forward, a backward and an update
The particle starts at the origin with zero gravity. At time step 0.1 s,
U = 1 gives vx = 2, so its first two x positions are 0.2 and 0.4.
The terminal target is 0.6. Since x₂ = 0.4 U, the expected gradient is
(0.4 - 0.6) * 0.4 = -0.08. One SGD update at learning rate 1 yields
U = 1.08 and a new terminal x of 0.432.
From the repository root, run
"""Differentiate two particle positions with respect to one initial-velocity design."""
from tempfile import TemporaryDirectory
import numpy as np
import torch
from uipc import Engine, Logger, Scene, World, builtin, view
from uipc.constitution import Particle
from uipc.geometry import pointcloud
from uipc.torch import DiffSimLR, DiffSimModule, DiffSimParameter
def fit_velocity(workspace):
config = Scene.default_config()
config["dt"] = 0.1
config["gravity"] = [[0.0], [0.0], [0.0]]
config["contact"]["enable"] = False
config["newton"]["semi_implicit"]["enable"] = 0
config["newton"]["velocity_tol"] = 1e-9
scene = Scene(config)
# U has one trainable entry. P[0] = 2 * U[0] is the physical x velocity.
parameter = DiffSimParameter(scene, 1, u2p=lambda u: 2.0 * u)
with torch.no_grad():
parameter.U().fill_(1.0)
parameter.sync()
mesh = pointcloud(np.zeros((1, 3), dtype=np.float64))
Particle().apply_to(mesh, 1000.0, 0.001)
mesh.vertices().create("mass", 1.0)
mesh.vertices().create("diff/velocity", np.array([0, -1, -1], dtype=np.int32))
slot, _ = scene.objects().create("particle").geometries().create(mesh)
engine = Engine("cuda", workspace)
world = World(engine)
world.init(scene)
assert world.is_valid()
# Read the global x DoF after initialization. Select it at both frames.
offset = int(np.asarray(view(slot.geometry().meta().find(builtin.dof_offset))).item())
def select(info):
if not engine.frame_stats()["converged"]:
raise RuntimeError(f"Forward frame {info.frame()} did not converge")
return torch.tensor([offset], dtype=torch.int32)
model = DiffSimModule(world, end_frame=2, parm=parameter, dof_select=select)
optimizer = torch.optim.SGD(model.parameters(), lr=1.0)
feasibility = DiffSimLR(model, optimizer)
optimizer.zero_grad()
positions = model()
loss = 0.5 * (positions[-1] - 0.6).square()
loss.backward()
grad = parameter.U().grad.item()
torch.testing.assert_close(positions, positions.new_tensor([0.2, 0.4]))
assert abs(grad + 0.08) < 1e-8
optimizer.step() # DiffSimLR checks the proposed physical parameters here.
with torch.no_grad():
updated = model()
torch.testing.assert_close(updated[-1], updated.new_tensor(0.432))
print(f"x = {positions.detach().tolist()}, dL/dU = {grad:.6f}")
print(f"Updated terminal x = {updated[-1].item():.6f}")
if __name__ == "__main__":
Logger.set_level(Logger.Level.Warn)
with TemporaryDirectory(prefix="uipc-diff-") as workspace:
fit_velocity(workspace)
The C++ API exposes the same physical-parameter update, forward recording, DoF selection and adjoint operations individually. See the complete C++ program in Native differentiable simulation.
The runnable Python source checks the outputs and gradient. To adapt it to a new problem, change these three parts.
- Bind the inputs before
world.init(scene). Construct oneDiffSimParameter(scene, size, u2p=...)on a scene with an empty parameter collection.sizecounts entries in U.u2preturns a floating-point tensor whose flattened length sets the size of P. The identity map is the default. Set initial design values undertorch.no_grad(), then callparameter.sync()before initialization. Create the integer binding attributes on the geometry or contact table. Reusing an index shares a physical parameter across its bindings. - Choose observations at frame zero. After
world.init(scene), constructDiffSimModule(world, end_frame, parameter, dof_select). The constructor requires the parameter's scene to be the one attached to the world, even if another scene has the same number of parameters. This check precedes saving frame zero or applying any values. On each subsequent forward, the callback receivesinfo.frame()after advancing. Frames are numbered from 1 throughend_frame. Return a 1Dint32orint64tensor of valid global DoF indices, orNoneto skip that frame. To select only the terminal observation, return indices only wheninfo.frame() == end_frame. - Build the loss from the returned tensor. Each call to
model()restores frame zero, applies the current physical values and runs the entire horizon. Its 1D float64 output concatenates the selected values in frame order and, within each frame, in the callback's index order. For a fixed count per selected frame, reshape explicitly, for exampleY.reshape(n_samples, 3)for three translation coordinates. Keep these operations in PyTorch when they participate in the loss. Useworld.retrieve()separately to inspect scene geometry or update a viewer.
parameter.U() and the model.U property refer to the same trainable tensor.
parameter.physical_values() evaluates the map using the current design.
Call parameter.sync() after editing the initial design before initialization.
For manual updates to an initialized world, first recover frame zero. The
module handles recovery and synchronization itself for each rollout. Its
output lives on the physical parameter tensor's device. At the native API
boundary the adapter stages contiguous CPU buffers and returns the adjoint
gradient to the physical parameter tensor's device.
Use a separate writable engine workspace for each world. The module checks that its initial dump and each recovery succeed. An incomplete or unavailable checkpoint raises an error before the next design is simulated. A failed overwrite can invalidate that frame on disk; earlier completed frames remain available. Recover from the same scene layout and simulation configuration.
For FEM vertices in a geometry's DoF block, the xyz indices for vertex j
start at offset + 3*j. An affine body has 12 entries per instance, beginning
with translation t and continuing with the three rows of its linear map
A. To score a point at local position X, compute t + A @ X with tensor
operations. This distinction matters for a mesh whose center is offset from
its local origin.
What backward differentiates
Calling loss.backward() supplies the output seed dL/dY to the native
adjoint. The backend replays the recorded frames, solves for the gradient
with respect to P, and restores the live forward state. PyTorch applies the
Jacobian of u2p to propagate that result back to U. In column-vector
notation, for a loss depending on the selected observations,
The native API returns the product of the transposed simulation Jacobian and
the output seed, without materializing that Jacobian in Python. PyTorch also
handles direct loss terms such as loss = tracking_loss + weight * model.U.square().sum().
Use optimizer.zero_grad() before a fresh gradient. For a vector output,
Y.backward(seed) accepts a seed of the same shape as Y.
| Action in one world | Effect on the recorded trajectory |
|---|---|
Call model() with gradients enabled and a trainable physical map |
Records the trajectory and output selection for this forward. Every frame must converge for backward. |
| Call backward repeatedly on the same output | Use retain_graph=True on earlier backwards. The native trajectory must still have the same version. |
Call model() again, advance the world, change output selection, synchronize parameters, successfully recover, or write positions/velocities with a state accessor |
Previous output tensors still hold their numerical values. Their native trajectory version is stale for backward. Consume their gradients first. |
Call model() under torch.no_grad() |
Re-simulates and returns observations for evaluation. This also replaces the world's previous trajectory. |
| Recover a nonzero checkpoint | Ordinary forward stepping can continue. Full trajectory gradients require a new recording from frame zero. |
One live World owns one trajectory. For independent trajectories that must coexist, give each world its own scene, parameter instance and engine workspace. A single world can also process several losses sequentially by running each forward/backward pair before the next forward. The native adjoint supports first-order derivatives.
Who chooses the optimization step?
loss.backward() computes a derivative. The outer optimizer uses it to
propose the next U. For SGD that can be a negative-gradient step. For
L-BFGS the direction also uses curvature estimates. An L-BFGS closure should
clear gradients, call model(), build the loss and call backward at each
trial design. Reusing an output from an earlier closure evaluates a different
trajectory.
DiffSimLR(model, optimizer) installs a post-step hook. Construct it once
after creating the optimizer, as in the example. Calling optimizer.step()
triggers this check automatically. Starting from the
last accepted design, the hook tests the physical parameters produced by the
proposed update and can shorten the step in design space for feasibility. It
re-evaluates the actual mapped candidate at each trial. Optimizer learning
rate and loss decrease are separate decisions. With L-BFGS, closure evaluations
take place inside the optimizer step, before that post-step hook. A trial
can still leave the model's valid domain or fail forward convergence. Newton and its line search run
inside each simulated frame to solve for the state.
The companion example frontend guide
explains how to run the GUI, check gradients and read results. The examples
define their own objectives and outer optimizers. For example,
case 1 optimizes the striker's initial velocity against the receiver's terminal
translation. Its --optimizer pure_gradient_descent option selects the outer
update rule in the examples runner.
Checks when adapting an example
| Symptom | What to inspect |
|---|---|
| A missing-feature error at module construction | Verify the interpreter loads this checkout's bindings and CUDA backend. Create the scene's diff parameter collection before world initialization. |
| Correct output shape, unexpected values | Check the geometry's global offset, frame selection, component order, local-to-world transform and the target's units. |
| Backward reports that the trajectory has been replaced | Inspect calls between forward and backward, including previews, retries, sync() and checkpoint recovery. Recompute the output and its loss together. |
| Forward fails to converge or the adjoint misses its residual target | Inspect engine.frame_stats() per frame and the solver configuration. Use a supported model and a feasible design. |
| A gradient is zero or disagrees with a numerical check | Verify the selected component is bound to P, can change under the physical constraints, and can affect the observation by the selected frame. Keep u2p and the loss connected to autograd. Compare against centered differences at multiple step sizes with the same frame-zero scene, time step and loss. Contact switches can change the local derivative. |
The Python parameter map, autograd function and optimizer hook are in
python/src/uipc/torch/diff_sim_module.py. The native feature interfaces
used by that adapter are in include/uipc/diff_sim/.