Guide for Agents#
The guide below ships inside the pycunls package (python -m pycunls
guide prints it), so a coding agent that only has the installed wheel finds
it. It is the shortest path from a task to a correct solve: which entry point
to use, the conventions that cost a turn when missed, what to check after a
solve and how to fix the common failures.
pycunls: a guide for agents (and busy people)#
pycunls solves nonlinear least-squares problems on the GPU: minimize
0.5 * sum_i rho(|r_i(x)|^2) over states x (vectors, poses, rotations). This guide is in
the installed package: python -m pycunls guide prints it, python -m pycunls doctor checks
the environment. Every class and function also documents itself: help(pycunls.X),
pycunls.describe("SE3BetweenFactorBatch").
1. Pick the entry point#
You have |
Use |
Example |
|---|---|---|
data |
|
|
thousands of independent fits of the same model |
|
same |
outliers in a fit |
|
same |
parameters with physical limits |
|
same |
a fit that lands in a wrong local minimum (frequencies, phases) |
|
same |
poses / points / velocities linked by built-in factors (pose graph, bundle adjustment, ICP, PnP) |
|
below |
gross outliers in geometric matches (PnP, registration) |
|
|
hard constraints, MPC |
|
|
a robot (URDF or joint arrays): inverse kinematics with hard joint limits |
|
|
a robot objective of your own (look-at, stay above a table, clearance, a frame relative to an object pose) |
an existing factor on a link frame view through |
|
a robot with closed loops or mimic joints |
the same, plus |
|
a residual no built-in factor computes, inside a larger graph |
a Warp factor ( |
|
pycunls.catalog("factor") lists the built-in factors; pycunls.describe(name) gives one’s
states, residual, measurement layout and conventions.
2. Model fitting with fit#
import numpy as np, warp as wp, pycunls
@wp.func
def model(x: float, p: wp.vec3) -> float: # one sample: y = a exp(-b x) + c
return p[0] * wp.exp(-p[1] * x) + p[2]
res = pycunls.fit(model, x, y, p0=[1.0, 1.0, 0.0], sigma=0.02)
print(res.report())
res.params, res.param_errors, res.converged, res.reduced_chi2
The model is a Warp function of one sample (
@wp.func), with annotated types:xafloatorwp.vecN(one sample’s inputs),pawp.vecP(afloatfor one parameter;wp.types.vector(length=5, dtype=float)for sizes without a named type), the result afloatorwp.vecM(moutputs per sample). Usewp.exp,wp.sin, … inside. A Python or NumPy function is aTypeError.The Jacobian comes from Warp’s automatic differentiation, checked against central differences at
p0(jacobian="auto"; on a mismatch it warns and uses central differences).jacobian="autodiff"or"numeric"forces one.Batches:
yof shape(B, n)withxshared(n,)or per fit(B, n);p0(P,)or(B, P). Pad shorter fits with NaN iny. Results gain a leadingBaxis;res.convergedis per fit.Pass
sigma(the measurement noise) when you know it: thenreduced_chi2is about 1 for a model that explains the data, and clearly larger (say > 2) when it does not. Withoutsigma,param_errorsare scaled by the residual scatter (asscipy.optimize.curve_fit).starts=Kneeds finitebounds(starts are drawn in the box);starts=[[...], ...]gives them explicitly. The lowest objective wins per fit (res.start_index); starts where the model returns NaN never win.Any number of parameters per fit: past 4 declare
paswp.types.vector(length=P, dtype=float).A model given by an ODE: use its closed-form solution when there is one; otherwise integrate inside the model with a fixed-step scheme (e.g. RK4 from 0 to the sample’s
x,h = x / 16.0, in afor i in range(16)loop: Warp unrolls and differentiates loops of up to 16 steps; longer loops makejacobian="auto"fall back to central differences). Frequencies, phases and other periodic parameters make the cost multi-modal: giveboundsandstarts.
3. Graph problems with ProblemBuilder#
pb = pycunls.ProblemBuilder()
poses = pb.add_states(pycunls.SE3StateBatch, initial=T0, constant=[0]) # T0: (N, 4, 4)
pb.add_factors(pycunls.SE3BetweenFactorBatch, deltas, connect=(poses, edges)) # edges: (M, 2)
result = pb.solve() # Levenberg-Marquardt; diagnose() runs first
result.converged, result.message
T = result[poses] # (N, 4, 4) NumPy
print(result.evaluate()) # residual statistics per factor batch
Several state types: connect=[(cams, cam_ids), (points, point_ids)] (one index array per state
slot of the factor). One state batch and one factor batch:
pycunls.solve(pycunls.SE3BetweenFactorBatch, deltas, initial=T0, connect=edges, constant=[0]).
Options go by name: pb.solve(max_num_iterations=100, cost_tolerance=1e-10).
4. Conventions that cost a turn when missed#
GPU float32 arrays. The low-level API takes float32, C-contiguous GPU arrays:
wp.array(any__cuda_array_interface__array such as PyTorch or CuPy works too) or int device pointers.fitandProblemBuilderconvert NumPy for you. Read results back witha.numpy(); write into a bound buffer witha.assign(np_array).Streams. Warp work (uploads,
assign, kernels) runs on Warp’s current stream. Everystream=argument of pycunls accepts awp.Stream(or any__cuda_stream__object, or aCudaStream), so the simplest order is to solve on Warp’s stream itself:stream = wp.get_stream(); uploads, solves and reads then run in order without extra synchronization. With a separatepycunls.CudaStream(), callwp.synchronize_stream(wp.get_stream())beforeminimize.minimizesynchronizes its stream before returning, except on the real-time paths (MinimizerOptions.real_time, the augmented Lagrangian’sreal_time): read their results on the same stream, or synchronize it first.Devices. A problem runs on the device of its state arrays:
minimize,evaluate_batchand the state helpers make that device current themselves (problem.device), so nowp.ScopedDeviceis needed around them. Objects made without device arrays (WarpFactorBatch,ArticulationTopology,CudaStream()) use Warp’s current device: create them insidewp.ScopedDevice(device)on a multi-GPU machine.Poses are
world_from_body, row-major 4x4 (SE3) or 3x3 (SE2). Updates are on the right:T' = T Exp(delta); se(3) tangent order is[omega, v](rotation first), se(2)[v_x, v_y, theta].Between factors measure
Delta = T_right^-1 T_left, the inverse of the usual relative poseT_left^-1 T_right. GivenT_i^-1 T_jper edge(i, j), pass its inverse.Gauge freedom. Relative factors (between, reprojection, motion priors) leave the whole graph free to move: make one state constant (
constant=[0]) or add a prior.diagnose()warns about it.Capacity vs. active count (low-level API). Batches are constructed with a capacity and start with 0 active items: call
set_num_active_states(n[, num_const])andset_num_active_factors(n)before solving.Absolute tolerances.
cost_tolerance(1e-6) andstate_tolerance(1e-6, on the squared step) are absolute: with exact data or tiny residual units lower them, or the solve stops “converged” early (the message says which criterion fired).Reprojection observations are normalized image coordinates (intrinsics removed).
Keep arrays alive. Batches read the arrays you pass; do not let them be garbage collected.
Articulations.
joint_qholds each joint’s coordinates in joint order (quaternions x, y, z, w); write it withArticulationStateBatch.set_joint_q, read it withget_joint_q(both take astridefor instances inside a larger array);get_link_transformsgives every link’s world pose (position, quaternion x, y, z, w). Joint limits are hard bounds (solve withAugmentedLagrangianMinimizer). Loop-closing joints are not tree joints: add them as the equality constraintspycunls.articulation.loop_closurereturns.
5. After a solve: check, do not assume#
summary.converged()(orres.converged); if False, readsummary.message: it names the cause and the fix.summary.termination_reasonis apycunls.TerminationReason;summary.to_dict()is JSON-ready.Cost:
summary.initial_cost -> final_cost. A cost that barely moved from a bad start means a wrong layout, a wrong convention or a wrong Jacobian.Residuals:
pycunls.evaluate(problem)(orresult.evaluate()): RMS per factor batch should be near the measurement noise;worst_factorpoints at outliers.Custom factors:
pycunls.check_jacobians(problem)must reportokfor every batch.Model adequacy (fits):
res.reduced_chi2with the truesigma.
6. When it fails#
Symptom (message / reason) |
Likely cause |
Fix |
|---|---|---|
|
NumPy array to the low-level API |
|
|
wrong array shape or capacity |
check |
|
NaN/Inf in states or measurements, or a factor outside its domain |
|
|
singular system (gauge freedom, unconstrained state) or NaN at trial states |
|
|
wrong Jacobian or bad initial guess |
|
|
float32 round-off at the minimum |
usually fine: check residuals |
|
not finished |
raise |
|
forgot |
set the active counts |
|
bounds with GN/LM |
solve with |
|
pre-R580 driver |
install an R580+ driver; on CUDA 12 systems use the C++ library |
warning |
relative factors only |
|
fit: |
a Python/NumPy model |
rewrite it as |
fit: high |
the model does not explain the data |
change the model |
More detail: pycunls.log_to_python(verbosity=pycunls.Verbosity.Message) (or the environment
variable CUNLS_LOG_LEVEL=message) logs every iteration and the final message through Python’s
logging.
7. Low-level API in one screen#
import numpy as np, warp as wp, pycunls
poses = wp.array(T0, dtype=wp.float32) # (N, 4, 4)
const = wp.zeros(1, dtype=wp.int32) # state 0 fixed
states = pycunls.SE3StateBatch(poses, N, const, 1)
states.set_num_active_states(N, 1)
deltas_gpu = wp.array(deltas, dtype=wp.float32) # keep every array alive
between = pycunls.SE3BetweenFactorBatch(deltas_gpu, M)
between.set_num_active_factors(M)
problem = pycunls.Problem()
problem.add_state_batch(states)
edge_ids = wp.array(edges.reshape(-1), dtype=wp.int32)
problem.add_factor_batch(between, [states, states], edge_ids)
for issue in pycunls.diagnose(problem): # optional: catches most setup mistakes
print(issue)
wp.synchronize_stream(wp.get_stream()) # the uploads finish before the solve
summary = pycunls.LevenbergMarquardtMinimizer().minimize(pycunls.CudaStream(), problem)
print(summary.report())
T = poses.numpy() # poses is updated in place