Native differentiable simulation features
Use the native features when your C++ application or Python solver owns the
objective and supplies its derivative. The CUDA backend advances a scene for
physical parameters P, collects the requested output coordinates in a
vector y, and computes a gradient for a scalar loss L(y). In PyTorch the
adapter supplies the output derivative for you. See the
PyTorch frontend tutorial.
For a first installation, follow the build and native gradient check. The C++ interface does not require Python bindings, and the NumPy interface does not require PyTorch.
From an initial velocity to a loss gradient
The following programs move one particle in free space for two steps of
0.02 seconds. A single physical parameter sets its initial x velocity.
At frame zero the example updates this parameter to 0.5. It selects the
particle's x coordinate at frame two and uses the loss
L = 0.5 * (x - 0.07)^2. The analytic result is x = 0.02 and
dL/dP = (0.02 - 0.07) * 0.04 = -0.002.
Open the source files directly or use the language tabs below. C++ source and Python source.
#include <cmath>
#include <filesystem>
#include <iostream>
#include <uipc/uipc.h>
#include <uipc/builtin/backend_name.h>
#include <uipc/constitution/particle.h>
#include <uipc/diff_sim/adjoint_method_feature.h>
#include <uipc/diff_sim/enable_grad_feature.h>
#include <uipc/diff_sim/update_parameter_feature.h>
using namespace uipc;
template <typename T>
backend::BufferView host_buffer(span<T> values)
{
return {reinterpret_cast<backend::HandleT>(values.data()),
0,
values.size(),
sizeof(T),
sizeof(T),
builtin::none};
}
int main(int argc, char** argv)
{
using namespace uipc::core;
using namespace uipc::geometry;
using namespace uipc::diff_sim;
if(argc != 2)
{
std::cerr << "Pass the directory containing the CUDA backend module.\n";
return 1;
}
auto library_config = uipc::default_config();
library_config["module_dir"] = std::filesystem::absolute(argv[1]).string();
uipc::init(library_config);
const std::string workspace = "output/docs/native_adjoint_cpp";
std::filesystem::create_directories(workspace);
Engine engine{"cuda", workspace};
World world{engine};
auto config = Scene::default_config();
config["dt"] = 0.02;
config["gravity"] = Vector3{0, 0, 0};
config["contact"]["enable"] = false;
config["newton"]["semi_implicit"]["enable"] = 0;
config["newton"]["velocity_tol"] = 1e-10;
config["newton"]["velocity_tol_relative"] = 0.0;
config["linear_system"]["tol_rate"] = 1e-12;
Scene scene{config};
auto& parameters = scene.diff_sim().parameters();
parameters.resize(1);
view(parameters)[0] = 0.2;
vector<Vector3> points{Vector3::Zero()};
auto mesh = pointcloud(points);
label_surface(mesh);
constitution::Particle{}.apply_to(mesh, 1000.0, 0.001);
mesh.vertices().create<Float>("mass", 1.0);
mesh.vertices().create<Vector3i>("diff/velocity", Vector3i{0, -1, -1});
auto [slot, rest] = scene.objects().create("particle")->geometries().create(mesh);
world.init(scene);
if(!world.is_valid() || !world.dump())
return 1;
auto recording = world.features().find<EnableGradFeature>();
auto update = world.features().find<UpdateParameterFeature>();
auto adjoint = world.features().find<AdjointMethodFeature>();
if(!recording || !update || !adjoint || !world.recover(0))
return 1;
vector<Float> physical{0.5}; // initial x velocity for this rollout
update->update(host_buffer<Float>(physical));
recording->with_grad();
auto offset = slot->geometry().meta().find<IndexT>(builtin::dof_offset)->view()[0];
vector<IndexT> selected;
for(SizeT frame = 1; frame <= 2; ++frame)
{
world.advance();
if(!world.is_valid() || world.frame() != frame
|| !engine.frame_stats().at("converged").get<bool>())
return 1;
if(frame == 2)
selected.push_back(offset);
adjoint->select_dofs(frame, host_buffer<IndexT>(selected));
}
recording->no_grad();
vector<Float> output(1), gradient(1);
adjoint->receive_dofs(host_buffer<Float>(output));
vector<Float> seed{output[0] - 0.07}; // dL/dy for L = (y - 0.07)^2 / 2
adjoint->compute_dLdP(host_buffer<Float>(gradient), host_buffer<Float>(seed));
std::cout << "x = " << output[0] << ", dL/dP = " << gradient[0] << '\n';
return std::abs(output[0] - 0.02) < 1e-10 && std::abs(gradient[0] + 0.002) < 1e-10 ? 0 : 1;
}
Link against this checkout's uipc::uipc target with the CUDA backend built.
Pass the directory containing its backend modules as the first argument
to the executable.
from pathlib import Path
import numpy as np
from uipc import Engine, Scene, World, builtin, view
from uipc.backend import BufferView
from uipc.constitution import Particle
from uipc.diff_sim import AdjointMethodFeature, EnableGradFeature, UpdateParameterFeature
from uipc.geometry import label_surface, pointcloud
def host_buffer(values):
assert values.ndim == 1 and values.flags.c_contiguous
return BufferView(values.ctypes.data, 0, values.size, values.itemsize,
values.itemsize, builtin.none)
workspace = Path("output/docs/native_adjoint_python")
workspace.mkdir(parents=True, exist_ok=True)
engine = Engine("cuda", str(workspace))
world = World(engine)
cfg = Scene.default_config()
cfg["dt"] = 0.02
cfg["gravity"] = [[0.0], [0.0], [0.0]]
cfg["contact"]["enable"] = False
cfg["newton"]["semi_implicit"]["enable"] = 0
cfg["newton"]["velocity_tol"] = 1e-10
cfg["newton"]["velocity_tol_relative"] = 0.0
cfg["linear_system"]["tol_rate"] = 1e-12
scene = Scene(cfg)
parameters = scene.diff_sim().parameters()
parameters.resize(1)
view(parameters)[:] = [0.2]
mesh = pointcloud(np.zeros((1, 3)))
label_surface(mesh)
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)
world.init(scene)
if not world.is_valid() or not world.dump():
raise RuntimeError("Could not initialize and save frame zero")
recording = world.features().find(EnableGradFeature)
update = world.features().find(UpdateParameterFeature)
adjoint = world.features().find(AdjointMethodFeature)
assert all(feature is not None for feature in (recording, update, adjoint))
if not world.recover(0):
raise RuntimeError("Could not restore frame zero")
physical = np.array([0.5], dtype=np.float64)
update.update(host_buffer(physical))
offset = int(view(slot.geometry().meta().find(builtin.dof_offset)).item())
recording.with_grad()
try:
for frame in (1, 2):
world.advance()
assert world.is_valid() and world.frame() == frame and engine.frame_stats()["converged"]
indices = np.array([offset] if frame == 2 else [], dtype=np.int32)
adjoint.select_dofs(frame, host_buffer(indices))
finally:
recording.no_grad()
output = np.empty(1, dtype=np.float64)
adjoint.receive_dofs(host_buffer(output))
seed = output - 0.07 # dL/dy for L = (y - 0.07)^2 / 2
gradient = np.empty(1, dtype=np.float64)
adjoint.compute_dLdP(host_buffer(gradient), host_buffer(seed))
print(f"x = {output[0]:.8f}, dL/dP = {gradient[0]:.8f}")
np.testing.assert_allclose([output[0], gradient[0]], [0.02, -0.002], rtol=0, atol=1e-10)
With this checkout's Python package installed, run
python docs/tutorial/code/differentiable_native.py from the checkout.
Call order and buffer sizes
- Before
world.init(scene), access the mutablescene.diff_sim(), resize its parameter collection to sizeN, set its initial physical values, and attach index attributes such asdiff/velocityto the model. Here[0, -1, -1]binds the x component toP[0]and leaves y and z constant. Initialization connects the indices, broadcasts the values, and fixes the parameter layout. See the supported parameter bindings. - After initialization, resolve the features through
world.features()and dump frame zero. To start a new design evaluation, recover frame zero and callUpdateParameterFeature.update(P)with allNphysical values. The snapshot restores the frame's motion state. The update synchronizes the design you actually want to evaluate. - Call
EnableGradFeature.with_grad()before the first advance of a differentiated rollout. After each advance, check the world and frame convergence, then callselect_dofs(frame, indices)for that frame, starting at frame 1. Select once per frame, using valid indices into that frame's global DoF vector. A rejected selection leaves its cursor and version unchanged, so a corrected call can be retried. Supply an empty index buffer for an unobserved frame. Callno_grad()after the last advance, or before a forward-only rollout. - Let
Mbe the sum of the per-frame selection lengths. CallAdjointMethodFeature.receive_dofs(y)with space forMscalars. The order is frame order followed by the order of your index list within each frame. Readtrajectory_version()after the last selection if your application retains outputs for a later backward call. - Compute a seed
s = dL/dyof lengthMfrom your objective. Allocate an output of lengthNand callcompute_dLdP(gradient, seed). The result is(dy/dP)^T sin physical-parameter order. Repeating an output index adds its seed contributions. If your loss also depends directly onP, add that explicit derivative in the caller.
| Native buffer | Element type | Length |
|---|---|---|
| Physical parameters, trial parameters, returned physical gradient | Float / float64 |
N |
| Frame-local output indices | IndexT / int32 |
Selected count for the current frame |
| Selected values and output seed | Float / float64 |
M |
An index in select_dofs addresses the assembled coordinates of the current
frame. Read the geometry's builtin.dof_offset metadata after world
initialization. FEM vertex v starts at offset + 3*v. An affine instance
i starts at offset + 12*i, with three translation entries followed by the
nine linear-transform entries in row order. An off-center body point with
local coordinates r is at translation + A * r in world space.
The examples wrap contiguous host arrays with builtin.none, zero element
offset, and element size and stride both set to the scalar byte size. A
BufferView borrows its storage. Keep the underlying arrays alive through
the native call, including the output buffers. A native caller wrapping
contiguous CUDA storage uses builtin.cuda and a device pointer.
For interleaved storage, specify the element stride in bytes. Both
element_offset and subview offsets count logical elements. Selected
outputs and gradients are copied to the caller's destination after the native
operation succeeds. Provide exactly the requested number of elements with
the scalar type listed above.
The separate FEM and affine state accessors also accept strided host or CUDA
destinations for their copy_*_to methods. Each destination element is one
native Vector3 (FEM) or column-major Matrix4x4 (affine), with room for
the number of requested vertices or bodies. Use these methods to inspect live
state, and use select_dofs to connect observations to an adjoint seed.
Feasibility and trajectory lifetime
LearningRateFeature.learning_rate(trial_P) evaluates a physical proposal
at frame zero and restores the current physical values after the query.
A result of 1 allows the full proposal. A smaller fraction calls for a
shorter step. For a nonlinear design-to-physical map, recompute the physical
parameters at the shorter design step and check that actual candidate again.
Evaluate the objective separately to choose an improving step.
Keep the trajectory unchanged between receiving outputs and computing their
derivative. Another advance, a new output selection, a parameter update, a
successful recovery, or a write to FEM/affine state through its accessor
changes the trajectory version. A native caller retaining y can compare
the saved version with the current one before submitting dL/dy.
Repeated backward calls on the same complete trajectory may use different
seeds. Both the forward convergence test and the adjoint residual test must
pass for a supported gradient.
To differentiate after loading a nonzero checkpoint or skipping a recording
frame, recover frame zero and record all frames again. Checkpoints contain
live simulation state, while reverse traversal uses the full recorded
trajectory. For forward-only observations after recovery, advance once and
resume selecting at the frame following the checkpoint. Received output then
contains only the new suffix. Keep the default static_case=false for multi-frame rollouts,
including relaxation with velocity reset. The native static_case=true
entry accepts a one-frame sensitivity and retains that step's inertia.