diff --git a/.gitignore b/.gitignore index 1ccd263..92c542c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,8 @@ # Project Specific scripts/benchmark/self_collision/cache/ -scripts/playground/recordings/ .worktrees/ runs/ +MUJOCO_LOG.TXT # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/AGENTS.md b/AGENTS.md index 89ee618..8379017 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,6 @@ - Write the simplest correct code. - Use straightforward control flow. -- Minimize lines of code. Fewer lines is a goal. - Keep answers and explanations as SHORT and SIMPLE as possible. 2. Validate every change diff --git a/README.md b/README.md index e90e791..cd557a1 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@

- RoboKit + RoboKit

@@ -14,48 +14,62 @@ that compose freely. Built-in tasks such as IK, motion planning, and retargeting real robots.

- Thousands of robots solving in parallel
+ Thousands of robots solving in parallel
Thousands of robots solving in parallel.

## Benchmarks

- RoboKit speedups: IK 12× vs PyRoKi; motion planning 3.5× vs cuRobo; hand retargeting 27× vs PyRoKi; humanoid retargeting 4× vs GMR; physics retargeting 2.8× vs SPIDER; grasp synthesis 60× vs Dex1B; rendering calibration 57× vs EasyHEC on the easy split. + RoboKit speedups: locomotion MPC 3.4× vs DIAL-MPC; IK 12× vs PyRoKi; motion planning 3.5× vs cuRobo; hand retargeting 27× vs PyRoKi; humanoid retargeting 4× vs GMR; physics retargeting 3.5× vs SPIDER; grasp synthesis 60× vs Dex1B; RL time to score 1.7× vs mjlab; rendering calibration 57× vs EasyHEC on the easy split.

Bars are wall-clock time on the same task, baseline normalized to full width. Check the paper for benchmark details. -## Optimization with Simulation +## Optimization/Learning with Simulation + + + + +
- Pen Spinning
- Pen Spinning A Sharpa hand spins a pen in its fingers. + NIST Assembly
+ NIST Assembly RL A Franka puts six NIST board parts in place, one after another (3× speed).
- Cube Rotation
- Cube Rotation A LEAP hand turns a cube to random goals. + Pen Spinning
+ Pen Spinning MPC A Sharpa hand spins a pen in its fingers.
- Notebook Opening
- Notebook Opening Two XHands open a hinged ARCTIC notebook. + Box Carrying
+ Box Carrying MPC A G1 lifts and carries a box.
- Box Carrying
- Box Carrying A G1 lifts and carries a box. + Rough Terrain
+ Rough Terrain RL A Go1 walks up and down stairs, following the green velocity command.
- Climbing
- Climbing A G1 climbs a box on hands and knees. + Cube Turning
+ Cube Turning MPC A palm-up Wuji hand tumbles a cube through 90° turns.
- Jumping
- Jumping A Go2 lands four 40 cm jumps on target footholds. + Climbing
+ Climbing MPC A G1 climbs a box on hands and knees. +
+ Lift
+ Lift RL A YAM arm carries a cube to target positions (red dot). +
+ Notebook Opening
+ Notebook Opening MPC Two XHands open a hinged ARCTIC notebook. +
+ Jumping
+ Jumping MPC A Go2 lands four 40 cm jumps on target footholds.
@@ -65,29 +79,29 @@ Check the paper for benchmark details. @@ -95,7 +109,7 @@ Check the paper for benchmark details. ## How it works -[![RoboKit framework](https://raw.githubusercontent.com/openrobokit/robokit/main/docs/assets/robokit-framework.webp)](https://github.com/openrobokit/robokit) +[![RoboKit framework](https://openrobokit.com/assets/docs/robokit/assets/robokit-framework.webp)](https://github.com/openrobokit/robokit) | Component | Role | Read more | | --- | --- | --- | diff --git a/docs/assets/built-in-tasks/grasp-optimization.webp b/docs/assets/built-in-tasks/grasp-optimization.webp deleted file mode 100644 index 46ad634..0000000 Binary files a/docs/assets/built-in-tasks/grasp-optimization.webp and /dev/null differ diff --git a/docs/assets/built-in-tasks/hand-eye-calibration.webp b/docs/assets/built-in-tasks/hand-eye-calibration.webp deleted file mode 100644 index 5f888b8..0000000 Binary files a/docs/assets/built-in-tasks/hand-eye-calibration.webp and /dev/null differ diff --git a/docs/assets/built-in-tasks/hand-retargeting.webp b/docs/assets/built-in-tasks/hand-retargeting.webp deleted file mode 100644 index a5cf3cb..0000000 Binary files a/docs/assets/built-in-tasks/hand-retargeting.webp and /dev/null differ diff --git a/docs/assets/built-in-tasks/humanoid-retargeting.webp b/docs/assets/built-in-tasks/humanoid-retargeting.webp deleted file mode 100644 index 2742883..0000000 Binary files a/docs/assets/built-in-tasks/humanoid-retargeting.webp and /dev/null differ diff --git a/docs/assets/built-in-tasks/ik.webp b/docs/assets/built-in-tasks/ik.webp deleted file mode 100644 index 12dc862..0000000 Binary files a/docs/assets/built-in-tasks/ik.webp and /dev/null differ diff --git a/docs/assets/built-in-tasks/motion-planning.webp b/docs/assets/built-in-tasks/motion-planning.webp deleted file mode 100644 index 19b6b65..0000000 Binary files a/docs/assets/built-in-tasks/motion-planning.webp and /dev/null differ diff --git a/docs/assets/robokit-banner.webp b/docs/assets/robokit-banner.webp deleted file mode 100644 index b7d9b6f..0000000 Binary files a/docs/assets/robokit-banner.webp and /dev/null differ diff --git a/docs/assets/robokit-benchmarks.webp b/docs/assets/robokit-benchmarks.webp deleted file mode 100644 index bb56ee6..0000000 Binary files a/docs/assets/robokit-benchmarks.webp and /dev/null differ diff --git a/docs/assets/robokit-framework.webp b/docs/assets/robokit-framework.webp deleted file mode 100644 index d42230d..0000000 Binary files a/docs/assets/robokit-framework.webp and /dev/null differ diff --git a/docs/assets/robokit-teaser.webp b/docs/assets/robokit-teaser.webp deleted file mode 100644 index 02d90c7..0000000 Binary files a/docs/assets/robokit-teaser.webp and /dev/null differ diff --git a/docs/assets/simulation/cube.webp b/docs/assets/simulation/cube.webp deleted file mode 100644 index 28a182e..0000000 Binary files a/docs/assets/simulation/cube.webp and /dev/null differ diff --git a/docs/assets/simulation/g1-box.webp b/docs/assets/simulation/g1-box.webp deleted file mode 100644 index ce557eb..0000000 Binary files a/docs/assets/simulation/g1-box.webp and /dev/null differ diff --git a/docs/assets/simulation/g1-climb.webp b/docs/assets/simulation/g1-climb.webp deleted file mode 100644 index 079b0f9..0000000 Binary files a/docs/assets/simulation/g1-climb.webp and /dev/null differ diff --git a/docs/assets/simulation/go2.webp b/docs/assets/simulation/go2.webp deleted file mode 100644 index 3302e6c..0000000 Binary files a/docs/assets/simulation/go2.webp and /dev/null differ diff --git a/docs/assets/simulation/notebook.webp b/docs/assets/simulation/notebook.webp deleted file mode 100644 index 0b3da84..0000000 Binary files a/docs/assets/simulation/notebook.webp and /dev/null differ diff --git a/docs/assets/simulation/pen.webp b/docs/assets/simulation/pen.webp deleted file mode 100644 index de243a3..0000000 Binary files a/docs/assets/simulation/pen.webp and /dev/null differ diff --git a/docs/concepts/conventions.md b/docs/concepts/conventions.md index 349d544..39153c6 100644 --- a/docs/concepts/conventions.md +++ b/docs/concepts/conventions.md @@ -2,8 +2,8 @@ ## SE(3) Representation -- **Quaternion**: Scalar first ordering $(q_w, q_x, q_y, q_z)$. -- **7D Pose**: Translation first, rotation second: $(x, y, z, q_w, q_x, q_y, q_z)$. +- **Quaternion**: Scalar first ordering $(q_w, q_x, q_y, q_z)$ (follows MuJoCo). +- **7D Pose**: Translation first, rotation second: $(x, y, z, q_w, q_x, q_y, q_z)$ (follows MuJoCo's free-joint `qpos`). ## Twist Representation @@ -22,16 +22,16 @@ Example (3 instances × 2 candidates): `[i0s0, i0s1, i1s0, i1s1, i2s0, i2s1]` **Utility functions:** -| Function | Purpose | Example | -| ------------------- | ---------------------------------------- | ------------------------------- | -| `warp_utils.repeat` | Expand instances for multiple candidates | `[i0, i1]` → `[i0, i0, i1, i1]` | -| `warp_utils.tile` | Expand candidate table for multiple instances | `[s0, s1]` → `[s0, s1, s0, s1]` | +| Function | Purpose | Example | +| ------------------- | ------------------------------- | ------------------------------- | +| `warp_utils.repeat` | Expand instances for candidates | `[i0, i1]` → `[i0, i0, i1, i1]` | +| `warp_utils.tile` | Expand candidates for instances | `[s0, s1]` → `[s0, s1, s0, s1]` | ## Notation ### Transformations -- `T_dst_src` denotes transformations $\mathbf{T}_{\mathrm{dst}\leftarrow\mathrm{src}} \in SE(3)$ that map vectors from source to destination frame: $\mathbf{p}^{\mathrm{dst}} = \mathbf{T}_{\mathrm{dst}\leftarrow\mathrm{src}}\, \mathbf{p}^{\mathrm{src}}$. +- `T_dst_src` is a transform $\mathbf{T}_{\mathrm{dst}\leftarrow\mathrm{src}} \in SE(3)$ from the source to the destination frame: $\mathbf{p}^{\mathrm{dst}} = \mathbf{T}_{\mathrm{dst}\leftarrow\mathrm{src}}\, \mathbf{p}^{\mathrm{src}}$. - Components: - `t_dst_src`: Translation vector $(x, y, z)$ - `q_wxyz_dst_src`: Rotation quaternion $(q_w, q_x, q_y, q_z)$ diff --git a/docs/concepts/geom.md b/docs/concepts/geom.md index e3434be..e49f686 100644 --- a/docs/concepts/geom.md +++ b/docs/concepts/geom.md @@ -1,9 +1,8 @@ # Geometry -`robokit.geom` runs batched SDF queries against scenes built from mixed geometric -representations. Each query point gets its signed distance to the scene (negative inside, -positive outside), the surface normal, and the closest surface point. Collision terms, -motion planning, and grasp optimization build on it. +`robokit.geom` runs batched SDF queries against scenes of mixed geometry types. Each query +point gets its signed distance (negative inside), the surface normal and the closest surface +point. Collision terms, motion planning and grasp optimization build on it. ## Overview @@ -39,22 +38,22 @@ assert scene.num_scenes == 1 # docs: endhide ``` -`update` never reallocates: buffers keep their identity, so a query captured in a CUDA graph -keeps working after the environment moves. +`update` copies in place and never reallocates. A query captured in a CUDA graph keeps working +after the scene moves. ## Geom Types -| Geom | Elements | SDF | -| ------------- | ----------------------------- | --------------------------------- | -| `BoxGeom` | half extents | analytical | -| `SphereGeom` | radii | analytical | -| `PlaneGeom` | local `z=0` halfspaces, posed | analytical | -| `CapsuleGeom` | radii + half heights | analytical | -| `MeshGeom` | triangle meshes | mesh BVH, optional baked-SDF tier | -| `VolumeGeom` | pre-baked `SdfVolume` grids | NanoVDB trilinear sample | +| Geom | Elements | SDF | +| ------------- | ----------------------------- | ---------------------- | +| `BoxGeom` | half extents | analytical | +| `SphereGeom` | radii | analytical | +| `PlaneGeom` | local `z=0` halfspaces, posed | analytical | +| `CapsuleGeom` | radii + half heights | analytical | +| `MeshGeom` | triangle meshes | mesh BVH or baked grid | +| `VolumeGeom` | pre-baked `SdfVolume` grids | trilinear grid sample | -Every geom takes `scene_offsets` (which scene owns which elements), optional `poses` / `scales`, -and an optional `capacity` to grow later without reallocating CUDA memory. +Every geom takes `scene_offsets`, which assign its elements to scenes. `poses` and `scales` are +optional. Set `capacity` to add elements later without reallocating. ## Query @@ -82,17 +81,16 @@ np.testing.assert_allclose(sdf.numpy(), [0.5]) # docs: endhide ``` -- Batching: one `WarpScene` holds `num_scenes` independent scenes; `scene_offsets` (CSR) or a - per-point `scene_indices` maps each query point to its scene. +- Batching: one `WarpScene` holds `num_scenes` independent scenes. `scene_offsets` or per-point + `scene_indices` map each query point to its scene. - Masking: `query_mask` skips masked points. -- Gradients: `query_sdf_torch(points, offsets, poses={geom: T})` is differentiable with respect - to the points and any pose/scale overrides. +- Gradients: `query_sdf_torch(points, offsets, poses={geom: T})` is differentiable in the points + and any pose or scale overrides. ### Mesh Level-of-Detail -Mesh queries speed up significantly with a baked signed distance grid: -`MeshGeom(enable_sdf=True, sdf_voxel_size=0.01)` bakes one per mesh, disk-cached under -`~/.robokit/sdf_cache`. Queries then cascade: +A baked SDF grid speeds up mesh queries. `MeshGeom(enable_sdf=True, sdf_voxel_size=0.01)` bakes +one per mesh and caches it under `~/.robokit/sdf_cache`. Queries then cascade: ``` outside the padded AABB -> AABB distance + padding diff --git a/docs/concepts/optimization.md b/docs/concepts/optimization.md index 093f367..ed6ddd5 100644 --- a/docs/concepts/optimization.md +++ b/docs/concepts/optimization.md @@ -1,14 +1,13 @@ # Optimization `robokit.opt` solves batched nonlinear optimization problems on the GPU. Variables live on -manifolds, costs come from `robokit.terms` (least-squares residuals or general cost -gradients). IK, motion planning, retargeting, hand-eye calibration, grasp synthesis build -on it. +manifolds. Costs come from `robokit.terms`. IK, motion planning, retargeting, hand-eye +calibration and grasp synthesis build on it. ## Overview -Three parts: a **solver** keeps a population of candidates per problem; an **optimizer** -moves each candidate; a **sampler** draws the tangent noise applied to them. +A **solver** keeps a population of candidates per problem. An **optimizer** moves each +candidate. A **sampler** draws tangent noise around them. ```mermaid flowchart TD @@ -50,8 +49,8 @@ flowchart LR - **score**: the tasks cost every candidate. - **select**: keep the best candidates per problem. -Each method is a schedule over these four. Multi-candidate LM: optimize, score, select. MPPI: sample, -score. ES: sample, score, select. +Each method is a schedule over these four. Multi-candidate LM: optimize, score, select. +MPPI: sample, score. ES: sample, score, select. ```python # docs: hide @@ -66,7 +65,7 @@ q_init = np.mean(robot.spec.actuated_joint_limits, axis=1).astype(np.float32)[No from robokit.lie.se3 import SE3Var from robokit.opt.lbfgs_optimizer import LBFGSOptimizer from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.var_values import VarKey, VarValues from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask @@ -82,7 +81,7 @@ ee = robot.spec.link_names.index("panda_hand") target = initial.get_T_world_link(ee) ee_traj = SE3Var(wp.clone(target)) ee_task = ConfigurationTask(T_world_base_rest=target, base_weight=1.0, include_joints=False, var_key=Key.EE) -cfg = PopulationSolverConfig(num_iters=2, num_candidates=[1], optimizer=LMOptimizerConfig()) +cfg = PopulationSolverConfig(stages=[Stage(2, 1, LMOptimizerConfig())]) seed_values = VarValues({VarKey.ROBOT: robot.state(q_init)}) # docs: endhide state = robot.state(q=q_init) # a Var leaf @@ -105,8 +104,7 @@ assert np.isfinite(best_costs.numpy()).all() ## Variables `Var` is an optimizable value on a manifold, such as joint angles or an SE(3) pose. -`VarValues` maps names to `Var` instances and presents them to optimizers and tasks as one -combined variable. +`VarValues` maps keys to `Var` instances. Optimizers and tasks see it as one variable. ```mermaid flowchart LR @@ -118,38 +116,38 @@ flowchart LR Common methods: -- `integrate(delta, out=None)`: Integrate a tangent step `delta` into the variable. Each `Var` defines its tangent integration: joint angles use addition, while poses use the exponential map with right multiplication, `T·exp(δ)`. -- `accept(mask, proposed)` accepts proposed batch elements and preserves rejected ones. -- `invalidate()` marks underlying `Var` instances as changed, invalidating their caches. +- `integrate(delta, out=None)` applies a tangent step. Joint angles add it; poses use `T·exp(δ)`. +- `accept(mask, proposed)` takes the proposed rows where `mask` is set and keeps the rest. +- `invalidate()` marks the `Var` instances as changed and invalidates their caches. -Note: `VarValues` lays out tangent columns contiguously in insertion order. For example: +`VarValues` lays out tangent columns in insertion order: ``` tangent columns: [ robot (T=7) | ee (T=6) ] offset=0 offset=7 ``` -Subclass `VarValues` to give a group its own tangent or sampling rule: one variable is -optimized and the rest follow from it, so the tangent covers only the free one. +Subclass `VarValues` to give a group its own tangent or sampling rule. For example, one +variable is optimized and the rest follow from it; the tangent then covers only the free one. ## Tasks -Tasks come from `robokit.terms`. Two sibling interfaces under a shared `Task` base class: +Tasks come from `robokit.terms`. Both interfaces subclass `Task`: | Term | Contract | Consumed by | | -------------- | ---------------------------------- | --------------------------- | | `ResidualTask` | residual vector `r` (+ Jacobian) | LM; GD/LBFGS residual modes | | `GradientTask` | per-batch scalar cost (+ gradient) | GD/LBFGS | -Variants: `SparseTask` extends `ResidualTask` with a sparse Jacobian. `EagerTask` extends -`ResidualTask` with hooks for work outside captured CUDA graphs. +`SparseTask` is a `ResidualTask` with a sparse Jacobian. `EagerTask` is a `ResidualTask` with +hooks for work outside captured CUDA graphs. -Task interfaces can be mixed. For example, `SmoothnessTask(ResidualTask, GradientTask)` -supports both residual and direct-gradient evaluation. +A task can implement both. `SmoothnessTask(ResidualTask, GradientTask)` gives residuals and +gradients. ## Optimizers -Optimizers come from `robokit.opt`. Three families share one lifecycle: +Optimizers come from `robokit.opt`. All three share one lifecycle: ```python # docs: hide @@ -172,18 +170,18 @@ assert callable(Optimizer.solve) # docs: endhide ``` -| Optimizer | Method | -| ---------------- | ----------------------------------------------------- | -| `LMOptimizer` | Damped Gauss–Newton; Cholesky or matrix-free CG step | -| `LBFGSOptimizer` | Limited-memory quasi-Newton with line search | -| `GDOptimizer` | GD, Adam, or AdamW | +| Optimizer | Method | +| ---------------- | ------------------------------------ | +| `LMOptimizer` | Damped Gauss–Newton (Cholesky or CG) | +| `LBFGSOptimizer` | Quasi-Newton with line search | +| `GDOptimizer` | GD, Adam, or AdamW | One optimization step: -1. Updated `VarValues` invalidate their derived caches. -2. The optimizer calls each task's `precompute()` serially. -3. Tasks compute costs and optional derivatives in parallel when enabled. -4. The optimizer updates the values or accepts or rejects a proposal. +1. Changed `VarValues` invalidate their caches. +2. The optimizer calls each task's `precompute()`, one at a time. +3. Tasks compute costs and derivatives, in parallel when enabled. +4. The optimizer updates the values, or accepts or rejects a proposal. ## Samplers @@ -213,16 +211,15 @@ assert callable(Sampler.sample) # docs: endhide ``` -| Sampler | Draws | -| ----------------- | -------------------------------------------------------------------------- | -| `RobertsSampler` | An even, low-discrepancy spread; no move | -| `GaussianSampler` | `num_draws` normals around a mean it moves by the scores (MPPI, ES) | -| `ContactSampler` | Each candidate and a copy with fresh contacts; the better one stays (grasp) | +| Sampler | Draws | +| ----------------- | -------------------------------------------------------- | +| `RobertsSampler` | A low-discrepancy spread; no move | +| `GaussianSampler` | Normals around a mean moved by the scores (MPPI, ES) | +| `ContactSampler` | A copy with fresh contacts; the better one stays (grasp) | ## Solvers -A solver composes sampler configs and optimizer configs into a schedule over global iterations. -It constructs runtime samplers during setup; device arrays and active-DOF masks belong to the runtime solver: +A solver runs sampler and optimizer configs as a schedule of stages: ```python # docs: hide @@ -244,14 +241,16 @@ assert callable(PopulationSolver.solve) Each iteration of `solve`: -1. **sample**, at `sample_at`: each sampler moves its candidates by the last scores, then draws new ones. -2. **optimize**: the current segment's optimizer steps every candidate. +1. **sample**, per `Stage.sample_every`: each sampler moves its candidates by the last scores, + then draws new ones. +2. **optimize**: the stage's optimizer steps every candidate. 3. **score**: the tasks, or the score term, cost every candidate. -4. **select**, at `select_at`: keep the best `num_candidates[k + 1]` per problem; the next segment's optimizer takes over. +4. **select**, at each new stage: keep its best `num_candidates` per problem; its optimizer takes + over. ```python # docs: hide -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.lm_optimizer import LMOptimizerConfig lm = LMOptimizerConfig() @@ -264,13 +263,13 @@ mppi = GaussianSamplerConfig(num_draws=64) contacts = ContactSamplerConfig() # multi-candidate LM: Roberts noise spreads 64 candidates at iteration 0, LM steps them, selects narrow 64 → 4 → 1 -PopulationSolverConfig(num_iters=16, samplers=[roberts], sample_at=[0], select_at=[6, 16], num_candidates=[64, 4, 1]) +PopulationSolverConfig(stages=[Stage(6, 64, sample_every=6), Stage(10, 4), Stage(0, 1)], samplers=[roberts]) # MPPI: every iteration moves each candidate by its draws' scores and draws again; a last sample # after the final score moves it once more, and the solve ends on the moved candidates -PopulationSolverConfig(num_iters=6, samplers=[mppi], sample_at=range(7), num_candidates=[1]) +PopulationSolverConfig(stages=[Stage(6)], samplers=[mppi]) # grasp LM: every 8 iterations each candidate is joined by a copy with fresh contacts, LM steps both, # and the next sample keeps the better; the final select picks one of the last pair -PopulationSolverConfig(num_iters=64, optimizer=lm, samplers=[contacts], sample_at=range(0, 64, 8), num_candidates=[1]) +PopulationSolverConfig(stages=[Stage(64, 1, lm, sample_every=8)], samplers=[contacts]) # docs: hide assert contacts.num_draws == 2 # docs: endhide diff --git a/docs/concepts/robot.md b/docs/concepts/robot.md index d73f258..5be3c49 100644 --- a/docs/concepts/robot.md +++ b/docs/concepts/robot.md @@ -1,17 +1,15 @@ # Robot -`robokit.robo` provides a simple, differentiable interface for kinematic computations. -It splits the work among three classes: +`robokit.robo` computes differentiable kinematics. It splits the work among three classes: -| Type | Role | Holds | -| --------------------- | ----------------- | --------------------------------------------------------------- | -| `Robot` | Compute | Kinematic computation methods; stateless | -| `RobotSpec` | Model data | Kinematic structure, geometry, and inertia; fixed after loading | -| └─ `RobotSpecTensors` | Device model data | Same as `RobotSpec`, but stored on a device | -| `RobotState` | Values | Batched joint and base values, plus computed results | +| Type | Role | Holds | +| --------------------- | ----------------- | ---------------------------------------------- | +| `Robot` | Compute | Kinematics methods; stateless | +| `RobotSpec` | Model data | Structure, geometry, inertia; fixed after load | +| └─ `RobotSpecTensors` | Device model data | `RobotSpec` on a device | +| `RobotState` | Values | Batched joint and base values, and results | -Most users only touch `Robot`, `robot.spec`, and `RobotState`; `RobotSpecTensors` -is used internally. +Use `Robot`, `robot.spec` and `RobotState`. `RobotSpecTensors` is internal. ```python from robot_descriptions.loaders.yourdfpy import load_robot_description @@ -35,7 +33,7 @@ assert state.q.shape[-1] == len(joint_names) ## State -A `RobotState` holds a single configuration, a batch of configurations, or a batch of trajectories: +A `RobotState` holds one configuration, a batch of them, or a batch of trajectories: ```python # docs: hide @@ -61,8 +59,7 @@ assert trajectory_state.q.shape == (1, 3, robot.spec.num_actuated_joints) # docs: endhide ``` -`q` is ordered by `robot.spec.actuated_joint_names`; mimic joints are not included. Result -buffers are allocated lazily on first use, so unused results cost no memory. +`q` follows `robot.spec.actuated_joint_names` and excludes mimic joints. ## Computation @@ -77,14 +74,13 @@ buffers are allocated lazily on first use, so unused results cost no memory. | `transform_collision_spheres(state)` | sphere and bounding-sphere world centers | | `transform_collision_capsules(state)` | link capsule world endpoints | -Any method that needs link transforms runs forward kinematics first if the state -does not have it yet. A fixed-base Jacobian has shape `[..., 6, num_dofs]`; a -floating-base Jacobian prepends six base columns. +Methods that need link transforms run forward kinematics first when the state lacks them. A +fixed-base Jacobian has shape `[..., 6, num_dofs]`. A floating-base Jacobian adds six base +columns in front. ## Torch -The Torch interface works on plain tensors, without a `RobotState`, and supports -gradients: +The Torch interface takes plain tensors instead of a `RobotState` and supports gradients: ```python # docs: hide diff --git a/docs/dev.md b/docs/dev.md index f2b929f..c55ef51 100644 --- a/docs/dev.md +++ b/docs/dev.md @@ -10,7 +10,7 @@ cd robokit uv sync ``` -PyTorch is optional. For examples that need it, select the extra matching your CUDA toolkit: +PyTorch is optional. For examples that need it, pick the extra for your CUDA toolkit: ```shell uv sync --extra pt-cu126 # CUDA 12.6 @@ -23,9 +23,9 @@ See [Installation](guide/installation.md#extras) for other extras. ## Git Workflow -Create your own branch for development. Use pull requests with **squash merge** to merge to `main`. -Delete your branch after merging. Run `make ci` before committing for formatting, linting, type -checking, pytest, and doctests. It defaults to `pt-cu126`; use `make ci PT=pt-cpu` for CPU-only PyTorch. +Work on your own branch. Merge to `main` through a pull request with **squash merge**, then delete +the branch. Run `make ci` before committing; it formats, lints, type-checks and runs all tests. It +defaults to `pt-cu126`; use `make ci PT=pt-cpu` for CPU-only PyTorch. ## Formatting, Linting, and Type Checking @@ -42,7 +42,9 @@ checking, pytest, and doctests. It defaults to `pt-cu126`; use `make ci PT=pt-cp uv run pyright ``` -Warp specializes thread dimensions and scalar/vector indexing when compiling kernels; its Python stubs cannot express every specialization. Keep any necessary Pyright exclusions on the specific kernel expression, leaving host code checked. Autograd wrappers narrow optional gradient buffers only where allocation is guaranteed. +Warp's stubs cannot type every kernel expression. Put a needed Pyright ignore on that expression +only; keep host code checked. In autograd wrappers, narrow optional gradient buffers only where they +are always allocated. ## Function Naming @@ -58,7 +60,8 @@ Warp kernels and functions additionally: - Suffix by type: `*_kernel` for `@wp.kernel`, `*_func` for `@wp.func`. - Verbs also include `transform` / `integrate` / `accept`. -- Variant tags before the suffix, fixed order: representation (`matrix`), algorithm (`sequential` / `local` / `accum`), then `backward`. +- Variant tags before the suffix, fixed order: representation (`matrix`), algorithm + (`sequential` / `local` / `accum`), then `backward`. ## Variable Naming @@ -66,13 +69,14 @@ Use the public [notation](concepts/conventions.md): `T_dst_src`, `t_dst_src`, `q_wxyz_dst_src`, and `q` for joint positions. - Keep `wxyz` in quaternion parameter names to indicate ordering. -- Avoid `pose`, `tf`, or similar terms, except in `robokit.xform`, whose conversions take `tf_mat` and `pose7`. +- Avoid `pose`, `tf`, or similar terms, except in `robokit.xform`, whose conversions take + `tf_mat` and `pose7`. - Use `T_dst_src` for batched transformations, not `Ts_dst_src`. ## Comments and Docstrings -Use single-line separators for sections, the short bracket form for class sections and -substantial phases in long functions. +Use the full-width separator for sections. Use the short form for class sections and long phases +inside a function. ```python # --- kernels ---------------------------------------------------------------- @@ -85,8 +89,8 @@ Use lowercase fragments for section labels and short code comments: # skip the normal/closest math (~2x faster) ``` -Use normal sentence capitalization and punctuation for complete explanatory prose. Preserve proper names, -acronyms, and identifiers. Write section labels using full words. +Write full-sentence comments with normal capitalization and punctuation. Keep proper names, +acronyms and identifiers as they are. Spell out words in section labels. Use Google-style docstrings (`Args:` / `Returns:` / `Raises:` sections) with single-backtick inline code. @@ -102,8 +106,8 @@ uv run scripts/test_docs.py ### Markdown Examples -Each Python fence runs independently. Include imports, small sample inputs, and assertions. -Wrap setup or checks in `# docs: hide` / `# docs: endhide` to keep the short view concise: +Each Python fence runs on its own. Include imports, small sample inputs and assertions. +Wrap setup and checks in `# docs: hide` / `# docs: endhide` to hide them from the short view: ```text # docs: hide @@ -115,18 +119,15 @@ assert total == 6 # docs: endhide ``` -The website's **Full** button reveals the complete code; **Copy** always copies it. -`scripts/test_docs.py` executes that code with xdoctest and reports passed, skipped, and failed blocks. -Examples that download assets use a hidden `# xdoctest: +SKIP`. Optional examples use hidden -`# xdoctest: +REQUIRES(...)` directives: `ROBOKIT_BODY_MODELS` for local body models, `ROBOKIT_CUDA_DOCS=1` -for CUDA/nvdiffrast, and `ROBOKIT_PARAHOME_DOCS=1` for prepared ParaHome data. -Skipped blocks are still checked for valid Python syntax. -To check the website's copied code after importing and building it, run -`uv run scripts/test_docs.py /path/to/robokit-website/_page/docs/robokit`. +The website shows the short view; **Full** and **Copy** use the complete code. `scripts/test_docs.py` +runs every fence with xdoctest. Hide `# xdoctest: +SKIP` in examples that download assets, and +`# xdoctest: +REQUIRES(...)` in optional ones: `ROBOKIT_CUDA_DOCS=1` for CUDA, `ROBOKIT_BODY_MODELS` for +body models, `ROBOKIT_PARAHOME_DOCS=1` for ParaHome. To test the website's copies, run +`uv run scripts/test_docs.py /_page/docs/robokit`. ### Doctest -Ensure public functions have corresponding doctests: +Give every public function a doctest: ```python # docs: hide @@ -161,16 +162,17 @@ torch.testing.assert_close(quaternion_multiply(q, q), torch.tensor([0.7071068, 0 ### Pytest -Tests use local fixtures; Hugging Face calls are blocked before collection. +Tests use local fixtures. Hugging Face calls are blocked. -To test original MANO PKL conversion and CPU engine parity using [locally supplied models](guide/assets.md#user-provided-body-models): +To test MANO PKL conversion and CPU engine parity with +[local body models](guide/assets.md#user-provided-body-models): ```shell ROBOKIT_BODY_MODELS="$HOME/.robokit/body_models" CUDA_VISIBLE_DEVICES='' \ uv run pytest tests/assets/test_body_models.py tests/smplx/test_mano_engine.py -q --no-cov ``` -Aggregate test cases into a single class, and compare results across different implementations: +Group test cases into one class. Compare results across implementations: ```python # docs: hide @@ -219,19 +221,17 @@ TestQuaternionToMatrix().test_identity_quaternion() ## Documentation Assets -Keep README and overview images in `docs/assets/`, with the six task previews in `built-in-tasks/`. -These pages use relative image paths. Gallery recordings remain in the website repository. -The website imports their URLs and bundles these files only into its ignored `_page/` build output. -Update assets here, then run `make import PROJECT=robokit SRC=/path/to/robokit` -in the website checkout, pointing `SRC` at this branch or worktree; do not keep -website source copies. +README and docs images load from `https://openrobokit.com/assets/docs/robokit/assets/`, so the repository stays light; the task previews are under `built-in-tasks/`. +Pages link them by relative path. Gallery recordings stay in the website repository. +Update assets here, then run `make import PROJECT=robokit SRC=/path/to/robokit` in the website +checkout, with `SRC` pointing at this branch or worktree. Do not keep copies in the website source. ## Asset Authoring -Robot descriptions, datasets, and collision configs are hosted at +Robot descriptions, datasets and collision configs live at [openrobokit/robokit](https://huggingface.co/datasets/openrobokit/robokit). -Import named asset modules to use their static path symbols. See -[Built-in Robots & Datasets](guide/assets.md) for loading assets and using `fetch()` for dynamic paths. +Import an asset module to use its path symbols. See +[Built-in Robots & Datasets](guide/assets.md) for loading assets and `fetch()`. ### Layout @@ -264,34 +264,33 @@ Import named asset modules to use their static path symbols. See └── hf_repo/ # writable authoring checkout ``` -Robot files are type-major: one robot's URDF, collision spheres, and contact points live under -different top-level `robots/` subdirs keyed by the same robot name. +Robot files are type-major. One robot's URDF, collision spheres and contact points sit in +different `robots/` subdirs under the same robot name. -Datasets use lowercase source names under `datasets//`; clips and object meshes from the same source -share that folder. Their access modules live in `robokit.assets.datasets`. +Each dataset source gets a lowercase `datasets//` folder for its clips and object meshes. +Its access module lives in `robokit.assets.datasets`. ### Robot asset naming - RoboKit-generated files use `_[_...]`; directories use `_`. - Common modifiers, in order: `glb`, `floating_base`, `no_mimic`. -- Python modules stay side-neutral. Side-specific symbols end in `_RIGHT` or `_LEFT`; no +- Python modules stay side-neutral. Side-specific symbols end in `_RIGHT` or `_LEFT`. Add no unsuffixed aliases. - Variant-specific symbols use a prefix, such as `ARM_URDF_PATH` and `ARM_REST_Q`. -- `REST_Q` explicitly maps every actuated joint name to its rest position. -- Arms, humanoids, and end effectors expose `MOUNT_LINK_NAME` and `MOUNT_COORD_SPEC`. Bilateral - models use `_RIGHT` and `_LEFT`. The link's local frame is the mounting frame; the spec defines - its semantic outward and right axes and optional `mount_point_xyz`, expressed in that link's frame. -- End effectors additionally expose `EE_COORD_SPEC` as a `HandCoordinateSpec` or - `GripperCoordinateSpec`; `MOUNT_COORD_SPEC` is derived from it, including `mount_point_xyz`. +- `REST_Q` maps every actuated joint name to its rest position. +- Arms, humanoids and end effectors expose `MOUNT_LINK_NAME` and `MOUNT_COORD_SPEC`, with `_RIGHT` + and `_LEFT` on bilateral models. The link's frame is the mounting frame. The spec gives its + outward and right axes and an optional `mount_point_xyz`, all in that frame. +- End effectors also expose `EE_COORD_SPEC`, a `HandCoordinateSpec` or `GripperCoordinateSpec`. + Their `MOUNT_COORD_SPEC`, including `mount_point_xyz`, is derived from it. - Display names use ` Right` or ` Left`; side-neutral assets omit the side. ### Self-collision ignore sets -`scripts/geom/self_collision/generate_ignore.py` classifies link pairs by sampling configurations -and writes `ignore..{yml,srdf}` for one robot. Run it per model and backend, writing into -the writable checkout; `capsule` needs the URDF/MJCF only, `sphere` needs collision spheres that -cover the whole model: +`scripts/geom/self_collision/generate_ignore.py` writes `ignore..{yml,srdf}` for one +robot. Run it per model and backend, into the writable checkout. `capsule` needs only the URDF/MJCF; +`sphere` also needs collision spheres that cover the whole model: ```shell uv run scripts/geom/self_collision/generate_ignore.py --backend capsule \ @@ -300,12 +299,13 @@ uv run scripts/geom/self_collision/generate_ignore.py --backend sphere -- --out-dir ~/.robokit/hf_repo/robots/self_collision/ --out-stem ignore ``` -Expose each file as `SPHERE_`/`CAPSULE_SELF_COLLISION_IGNORE_PATH` (`MJ_` prefix for MJCF variants). -The `fcl` backend (pinocchio meshes) is ground truth for the self-collision benchmark, not shipped. +Expose each file as `SPHERE_`/`CAPSULE_SELF_COLLISION_IGNORE_PATH`, with an `MJ_` prefix for MJCF +variants. The `fcl` backend is not shipped. ### Publishing Assets -Keep upstream license files and copyright notices beside copied assets, including each assembly component's notices. +Keep upstream license files and copyright notices beside copied assets, including those of each +assembly component. Create the writable checkout, edit `robokit_assets/`, then commit and push: @@ -316,11 +316,11 @@ git add -A && git commit -m "add " && git push git rev-parse HEAD ``` -Keep the type-major layout above. In the same RoboKit change, expose the path from -`src/robokit/assets//.py` and set the pinned commit in +Keep the type-major layout above. In the same RoboKit change, expose the path in +`src/robokit/assets//.py`. Set the pinned commit in `src/robokit/assets/__init__.py` to the printed hash. > [!NOTE] -> `checkout()` prepares the writable dataset in `~/.robokit/hf_repo` and exposes it as +> `checkout()` clones the writable checkout to `~/.robokit/hf_repo` and links it as > `./robokit_assets`. Binary assets use Git LFS. Before adding a new binary extension, run > `git lfs track "*."`. diff --git a/docs/guide/assets.md b/docs/guide/assets.md index a6eed9f..d214761 100644 --- a/docs/guide/assets.md +++ b/docs/guide/assets.md @@ -1,7 +1,7 @@ # Built-in Robots & Datasets -Robot descriptions and datasets for robokit. They live in the -HuggingFace dataset [`openrobokit/robokit`](https://huggingface.co/datasets/openrobokit/robokit). +Robot descriptions and datasets live in the HuggingFace dataset +[`openrobokit/robokit`](https://huggingface.co/datasets/openrobokit/robokit). Assets are under their own licenses; see [license files and outstanding gaps](https://huggingface.co/datasets/openrobokit/robokit/blob/6c7d94e4ace25a1ec674cce237ef90ff9c159f22/LICENSES.md). @@ -30,9 +30,9 @@ assert unitree_g1.URDF_PATH.is_file() ### Self-collision ignore sets -Link pairs that always touch — adjacent links, geometry that overlaps by construction — are listed -per robot so self-collision terms skip them. Sets are generated per geometry representation, so -match the symbol to the `SelfCollisionTask` representation you use (`sphere` is its default): +Each robot lists the link pairs that always touch, so self-collision terms skip them. Each +geometry representation has its own set. Match it to your `SelfCollisionTask` representation +(`sphere` by default): ```python # docs: hide @@ -52,13 +52,14 @@ assert robot.spec.has_collision_spheres # docs: endhide ``` -MJCF variants carry `MJ_CAPSULE_...` sets only; robots without collision spheres have no sphere set. +MJCF variants have only `MJ_CAPSULE_...` sets. Robots without collision spheres have no sphere set. For asset layout and authoring, see the [Development Guide](../dev.md). ## Robots -Licenses refer to upstream assets; `—` means unavailable or unspecified. Sides are shown only for one-sided availability. +Licenses are upstream. `—` means unavailable or unspecified. A side, such as `(right)`, means only +that side is available. ### Arms @@ -101,6 +102,10 @@ Licenses refer to upstream assets; `—` means unavailable or unspecified. Sides + + + + @@ -140,6 +145,7 @@ Licenses refer to upstream assets; `—` means unavailable or unspecified. Sides + @@ -149,8 +155,8 @@ Licenses refer to upstream assets; `—` means unavailable or unspecified. Sides ## User-provided body models Download [MANO](https://mano.is.tue.mpg.de/) or [SMPL-X](https://smpl-x.is.tue.mpg.de/) -from its official website after accepting its license. Place the variants you need under -`~/.robokit/body_models/`, or set `ROBOKIT_BODY_MODELS` to another root folder: +from its official website after accepting its license. Put the files you need under +`~/.robokit/body_models/`, or set `ROBOKIT_BODY_MODELS` to another folder: - `mano/MANO_RIGHT.pkl` or `mano/MANO_LEFT.pkl` - `smplx/SMPLX_NEUTRAL.npz`, `smplx/SMPLX_MALE.npz`, or `smplx/SMPLX_FEMALE.npz` @@ -168,5 +174,5 @@ assert hand is not None and body is not None # docs: endhide ``` -NPZs load directly. PKLs convert once beside the unchanged originals; the folder must be writable. -Missing models raise an error with setup instructions; RoboKit never downloads them. +NPZs load directly. PKLs convert once beside the originals, so the folder must be writable. +RoboKit never downloads body models. diff --git a/docs/guide/full_body_retargeting.md b/docs/guide/full_body_retargeting.md index 0c70c4a..a2fe0d3 100644 --- a/docs/guide/full_body_retargeting.md +++ b/docs/guide/full_body_retargeting.md @@ -1,7 +1,8 @@ # Full-Body Retargeting -| Whole-body tracking with object contacts. | A ParaHome cutting-board clip retargeted whole-body. | +| ![Whole-body tracking with object contacts](https://openrobokit.com/assets/docs/robokit/assets/gallery/humanoid_retargeting_contact.webp) | ![A ParaHome cutting-board clip retargeted whole-body](https://openrobokit.com/assets/docs/robokit/assets/gallery/full_body_retargeting.webp) | | --- | --- | +| Whole-body tracking with object contacts. | A ParaHome cutting-board clip retargeted whole-body. | `robokit.helpers.full_body_retargeting` maps a captured human-object interaction onto a diff --git a/docs/guide/hand_eye_calibration.md b/docs/guide/hand_eye_calibration.md index be9d6fa..6790115 100644 --- a/docs/guide/hand_eye_calibration.md +++ b/docs/guide/hand_eye_calibration.md @@ -1,10 +1,11 @@ # Hand-Eye Calibration +![Initial, predicted, and ground-truth camera extrinsics overlaid on a ManiSkill capture](https://openrobokit.com/assets/docs/robokit/assets/gallery/hec_sim.webp) -`robokit.helpers.hand_eye_calibration` solves the camera extrinsic (OpenCV `T_camera_base`) from robot -silhouette masks and/or depth maps. Given N images with known joint positions `q`, it -renders the robot with nvdiffrast and aligns the rendered masks to the targets with a -coarse-to-fine multi-candidate Levenberg-Marquardt solver, no calibration board needed. + +`robokit.helpers.hand_eye_calibration` solves the camera extrinsic (OpenCV `T_camera_base`) from +robot masks and/or depth maps. It renders the robot with nvdiffrast at N known joint positions `q` +and aligns the renders to your images. No calibration board is needed. ## Overview @@ -68,15 +69,14 @@ assert torch.isfinite(predicted).all() # docs: endhide ``` -`masks` are `[N, H, W]` float robot silhouettes, `q` is `[N, num_dofs]` in -`robot.spec.actuated_joint_names` order, `initial` is a rough `[4, 4]` guess -(up to ~35 cm / 45 deg off is fine with the default config). +`masks` are `[N, H, W]` float robot silhouettes. `q` is `[N, num_dofs]` in +`robot.spec.actuated_joint_names` order. `initial` is a rough `[4, 4]` guess; the default config +handles up to ~35 cm / 45 deg of error. ## Common variants -**Mounted camera.** For a camera on a moving mount (e.g. wrist cam), pass per-sample -`T_mount_base`; the solve then happens in the mount frame and returns -`T_camera_mount`. See +**Mounted camera.** For a camera on a moving mount, such as a wrist camera, pass per-sample +`T_mount_base`. The solver then returns `T_camera_mount`. See [src/robokit/examples/hand_eye_calibration/02_sim_mounted.py](../../src/robokit/examples/hand_eye_calibration/02_sim_mounted.py): ```python @@ -114,9 +114,8 @@ assert torch.isfinite(predicted).all() # docs: endhide ``` -**Depth.** Each `PyramidLevel` has a `use_depth` flag. Enable it on the fine levels -for an RGB-D polish, or on every level for depth-only (masks omitted; pass robot-only -depth with 0 = invalid). See +**Depth.** Use `presets.rgbd` to add depth on the fine levels, or `presets.depth` for depth only. +For depth only, omit masks and pass robot-only depth, with 0 marking invalid pixels. See [src/robokit/examples/hand_eye_calibration/03_sim_depth.py](../../src/robokit/examples/hand_eye_calibration/03_sim_depth.py): ```python @@ -161,19 +160,14 @@ assert torch.isfinite(predicted).all() # docs: endhide ``` -`presets.rgb_single_level` runs the full-resolution RGB level with the coarse-to-fine preset's -total iteration budget; the benchmark uses it for the single-level comparison. - -`presets.rgb` / `presets.rgbd` / `presets.depth` are prebuilt configs; for a custom -schedule set `use_depth` per `PyramidLevel`, and `depth_weight` on the mask-alignment task in `config.terms`. +For a custom schedule, set `use_depth` per `PyramidLevel`. Set `depth_weight` on the mask task +in `config.terms`. -**Model offsets.** The extrinsic is not the only unknown: encoder zero offsets and an -unknown arm/hand adapter both shift the rendered robot, and a camera-only solve can only -absorb them by biasing the extrinsic. Swap the pyramid's mask task for -`MaskAlignmentOffsetTask` and those become variables too - `offset_joints` frees the zero -of existing joints, `offset_link` frees the transform a link hangs from (a virtual six-dof -joint). See [05_sim_offsets.py](../../src/robokit/examples/hand_eye_calibration/05_sim_offsets.py), -using `--offset joints` or `--offset mount`: +**Model offsets.** Encoder zero offsets and an unknown mount also shift the rendered robot. To solve +for them with the extrinsic, swap the pyramid's mask task for `MaskAlignmentOffsetTask`: +`offset_joints` frees joint zeros, and `offset_link` frees the transform a link hangs from. See +[05_sim_offsets.py](../../src/robokit/examples/hand_eye_calibration/05_sim_offsets.py) with +`--offset joints` or `--offset mount`: ```python # docs: hide @@ -218,18 +212,15 @@ assert torch.isfinite(predicted).all() and torch.isfinite(delta_q).all() # docs: endhide ``` -`config.terms` holds every cost term, mask alignment included; each one is handed the -solve's data and walks the pyramid itself. +`config.terms` holds every cost term, mask alignment included. -`offset_link_dofs` keeps only part of the mount twist (translation- or rotation-only). -Weakly observable dofs - a roll about a round wrist flange - drift unless the `ConfigurationTask` -holds them near nominal. +Set `offset_link_dofs` to free only the mount's translation or rotation. Weakly observable dofs, +such as roll about a round wrist flange, drift; the `ConfigurationTask` holds them near nominal. **Real hardware.** [src/robokit/examples/hand_eye_calibration/04_real_xarm.py](../../src/robokit/examples/hand_eye_calibration/04_real_xarm.py) -runs the full pipeline on an xArm + RealSense: capture images at a set of joint -configurations, segment the arm with SAM2, drag an initial guess in viser, then solve. -Larger initial errors need more candidates; it bumps `candidate_noise_t/r` and the solver's -`num_candidates` and iterations over the defaults. +runs the full pipeline on an xArm + RealSense. It captures images at several joint configurations, +segments the arm with SAM2, takes an initial guess dragged in viser, then solves. For larger initial +errors, raise `candidate_noise_t/r`, `num_candidates` and iterations, as the example does. **Unknown frame qpos.** Fit q from silhouette views of one frame. @@ -239,19 +230,17 @@ Larger initial errors need more candidates; it bumps `candidate_noise_t/r` and t | `presets.rgb_qpos` | Qpos; camera is fixed | | `presets.rgb_qpos_camera` | Qpos and camera | -Pass `target_masks[V,H,W]` and optional initial `q[J]`; read `last_q[J]`. +Pass `target_masks[V,H,W]` and an optional initial `q[J]`. Read the result from `last_q[J]`. Omit `q` to search the full joint limits. [Frame and trajectory comparison](../../src/robokit/examples/hand_eye_calibration/06_sim_qpos.py). -**Joint trajectories (experimental).** `QposTrajectoryCalibrator` fits -`last_q[T,J]` from `masks[T,V,H,W]` and -`timestamps[T]`, with velocity and acceleration smoothing. -Use `presets.rgb_qpos_trajectory` for fixed cameras, or -`presets.rgb_qpos_trajectory_camera` to also refine static cameras. +**Joint trajectories (experimental).** `QposTrajectoryCalibrator` fits a smooth `last_q[T,J]` +from `masks[T,V,H,W]` and `timestamps[T]`. Use `presets.rgb_qpos_trajectory` for fixed cameras, +or `presets.rgb_qpos_trajectory_camera` to also refine static cameras. -Both APIs accept image keypoints through `keypoint_links` and -`target_keypoints`; NaNs mark missing points. +Both APIs also take image keypoints through `keypoint_links` and `target_keypoints`. NaNs mark +missing points. [Trajectory example](../../src/robokit/examples/hand_eye_calibration/06_sim_qpos.py) · [Benchmark](../../scripts/benchmark/hand_eye_calibration/README.md). diff --git a/docs/guide/hand_retargeting.md b/docs/guide/hand_retargeting.md index 011a70c..bc70168 100644 --- a/docs/guide/hand_retargeting.md +++ b/docs/guide/hand_retargeting.md @@ -1,9 +1,12 @@ # Hand Retargeting -| An XHand on an xArm7 replaying a captured hand motion. | Hand-object retargeting across three datasets. | +| ![An XHand on an xArm7 replaying a captured hand motion](https://openrobokit.com/assets/docs/robokit/assets/gallery/hand_retargeting.webp) | ![Hand-object retargeting across three datasets](https://openrobokit.com/assets/docs/robokit/assets/gallery/hand_retargeting_contact.webp) | | --- | --- | +| An XHand on an xArm7 replaying a captured hand motion. | Hand-object retargeting across three datasets. | -`robokit.helpers.hand_retargeting` maps ordered hand points to robot states. Online retargeting solves one frame at a time; offline retargeting jointly solves a trajectory. Complete programs are in [`src/robokit/examples/hand_retargeting`](../../src/robokit/examples/hand_retargeting/). +`robokit.helpers.hand_retargeting` maps ordered hand points to robot states. Online retargeting +solves one frame at a time. Offline retargeting solves a whole trajectory. Complete programs are in +[`src/robokit/examples/hand_retargeting`](../../src/robokit/examples/hand_retargeting/). ## How Retargeting Works @@ -21,7 +24,7 @@ flowchart LR ## Presets -Each robot preset is a module with a shared hand specification and separate workflow configurations. +Each robot preset is a module with one hand spec and a config per workflow. ```python from robokit.helpers.hand_retargeting.presets import shadow @@ -35,25 +38,19 @@ assert online_wrist_config.reference_origin == "wrist" # docs: endhide ``` -The point axis follows `spec.target_names`; it does not assume a MANO layout. +Order points as `spec.target_names`. The MANO layout is not assumed. | Workflow | NumPy input | Output | | --- | --- | --- | | Online | `(K, 3)` or `(B, K, 3)` | `(B, 7 + Q)` | | Offline | `(T, K, 3)` or `(B, T, K, 3)` | `(T, 7 + Q)` or `(B, T, 7 + Q)` | -Here `B` is batch size, `T` is frame count, `K` is `len(spec.target_names)`, and `Q` is the number of actuated robot joints. Each output packs the base transform `(x, y, z, qw, qx, qy, qz)` before the joints. +`B` is batch size, `T` frame count, `K` is `len(spec.target_names)`, and `Q` actuated joints. +Each output row is the base transform `(x, y, z, qw, qx, qy, qz)` followed by the joints. ## Online Retargeting -Objective parameters belong to tasks in `config.terms`. A template names the -helper inputs it reads with `HandContext` members, and the retargeter builds every -template the same way. The correspondence templates read `POINTS`, or `VECTORS` and -`DIRECTIONS`, which hold every ordered target pair; their weights, keyed by target or -by `(origin link, task link, origin target, task target)`, pick the rows. Smoothness -reads `PREVIOUS_STATE` and ramps in with `FRAME`; the rest pose reads `REST_Q`. Names -such as `positions` or `smoothness` only label the presets' templates for -`config.task(name)`. For example: +A preset's costs are tasks in `config.terms`; change one by name: ```python # docs: hide @@ -67,17 +64,11 @@ config.task("smoothness").weight = 0.1 config.task("rest").weight = 0.01 ``` -The offline retargeter builds every template in `config.terms` the same way, from -`HandContext` inputs such as `CONTACT_LINKS`, `ROOT_POSE` or `REFERENCE_Q`. One config -is one problem: `contact_config()` and `refine_config()` derive the contact and -refinement problems from a tracking config. Wrist presets carry their own task list; -coordinate centering and sampling remain configuration settings. Use -`config.task(name).dense_task` to configure a trajectory wrapper's per-pose task. +Offline configs work the same way. `contact_config()` and `refine_config()` derive the contact and +refinement problems from a tracking config. -Online retargeting follows `__init__ → warmup → solve → reset`. The caller owns the frame loop. -Each solve processes one frame. The first frame after warmup/reset has no temporal -cost; later frames are smoothed against the preceding solution. An explicit -`init_state` changes the optimization seed without replacing that history. +Online retargeting follows `__init__ → warmup → solve → reset`, one frame per `solve`; the caller owns +the loop. Each frame after the first is smoothed against the previous solution. ```python # docs: hide @@ -123,13 +114,14 @@ assert np.isfinite(qpos).all() # docs: endhide ``` -See [`01_online.py`](../../src/robokit/examples/hand_retargeting/01_online.py), [`05_online_batch.py`](../../src/robokit/examples/hand_retargeting/05_online_batch.py), and [`03_batch.py`](../../src/robokit/examples/hand_retargeting/03_batch.py). +See [`01_online.py`](../../src/robokit/examples/hand_retargeting/01_online.py), +[`05_online_batch.py`](../../src/robokit/examples/hand_retargeting/05_online_batch.py), and +[`03_batch.py`](../../src/robokit/examples/hand_retargeting/03_batch.py). ### Wrist Tracking -Pass an `online_wrist` preset to `HandRetargeterOnline` to jointly track wrist pose and -finger joints. Floating hands accept world keypoints and return the base transform in -that same world frame: +Pass an `online_wrist` preset to `HandRetargeterOnline` to track the wrist pose and finger joints +together. Floating hands take world points and return the base transform in the world frame: ```python # docs: hide @@ -168,18 +160,14 @@ assert np.isfinite(qpos).all() # docs: endhide ``` -`reference_origin="world"` is the default. The wrist presets use `"wrist"`: the solver -subtracts wrist translation internally and restores it in the output, keeping streaming -history relative to the moving wrist. The coordinate axes are not rotated. -`init_state` and `compute_costs(state)` also use world coordinates. Fixed-base arm rigs -use points and states in the robot base frame; they do not subtract wrist translation. - -Wrist presets use `HandRetargeterOnlineConfig`. Tune tracking with `position_weights` and -`direction_weights`; `base_smoothness_weight` controls wrist smoothing for floating hands. +Wrist presets set `reference_origin="wrist"`; the default is `"world"`. Inputs and outputs stay +in world coordinates either way, including `init_state` and `compute_costs(state)`. Fixed-base arm +rigs take points and states in the robot base frame. ## Offline Retargeting -`solve_numpy()` warms the solver for the input batch and trajectory shape. The Warp API uses `warmup(batch_size=B, num_frames=T)` before `solve()`. +`solve_numpy()` warms up for its input shape. The Warp API needs +`warmup(batch_size=B, num_frames=T)` before `solve()`. ```python # docs: hide @@ -223,15 +211,16 @@ assert np.isfinite(qpos).all() # docs: endhide ``` -`root_quat_wxyz` is optional unless an active task reads the root pose, as the default `root_rotation` does. The caller splits long trajectories into chunks when needed. +Pass `root_quat_wxyz` when a task reads the root pose; the default `root_rotation` task does. +Split long trajectories into chunks yourself. -Each retargeter solves its config's `terms`, whose `HandContext` placeholders name the inputs the helper fills: target points, contact links, the root pose, and so on. Any task built from those placeholders joins the solve. - -See [`02_offline.py`](../../src/robokit/examples/hand_retargeting/02_offline.py) and [`04_arm.py`](../../src/robokit/examples/hand_retargeting/04_arm.py). +See [`02_offline.py`](../../src/robokit/examples/hand_retargeting/02_offline.py) and +[`04_arm.py`](../../src/robokit/examples/hand_retargeting/04_arm.py). ## Contact and Collision -Contact solves add one contact point and mask per `spec.contact_target_names` entry. `contact_config()` derives the contact-tracking problem from a tracking config, and `refine_config()` derives an anchored refinement that keeps the result near `init_state`. +Contact solves take one contact point and mask per `spec.contact_target_names` entry. Wrap a +tracking config with `contact_config()`. Use `refine_config()` to keep the result near `init_state`. ```python # docs: hide @@ -286,10 +275,12 @@ assert np.isfinite(qpos).all() # docs: endhide ``` -Supplying `init_state` starts from that trajectory; the refinement config's `anchor` tasks keep the result near it, and its smoothness follows that trajectory's motion. - -The caller owns the optional `WarpScene`. Offline scene collision is active when a scene is supplied and `config.task("collision").weight` is nonzero. Online self-collision instead uses the robot collision spheres, `config.task("self_collision").weight`, and the skip pairs loaded via `Robot.load(self_collision_ignore_path=...)`. +Pass `init_state` to start from a trajectory; the refinement keeps the result near it. -See [`06_contact.py`](../../src/robokit/examples/hand_retargeting/06_contact.py) and the batched DexYCB mesh example [`07_batch_contact.py`](../../src/robokit/examples/hand_retargeting/07_batch_contact.py). +Pass a `WarpScene` for scene collision; `config.task("collision").weight` sets its cost. Self-collision +uses the robot's collision spheres and the skip pairs from `Robot.load(self_collision_ignore_path=...)`. -Run `uv run src/robokit/examples/hand_retargeting/07_batch_contact.py --output-dir PATH` to process every right-hand DexYCB capture in batches of 64. It sorts clips by length, pads each batch to its longest clip, masks padded frames, and swaps object meshes in the same scene. It writes one NPZ per capture and skips completed outputs on restart. +See [`06_contact.py`](../../src/robokit/examples/hand_retargeting/06_contact.py). +[`07_batch_contact.py`](../../src/robokit/examples/hand_retargeting/07_batch_contact.py) retargets +every right-hand DexYCB capture and writes one NPZ per capture: +`uv run src/robokit/examples/hand_retargeting/07_batch_contact.py --output-dir PATH`. diff --git a/docs/guide/humanoid_retargeting.md b/docs/guide/humanoid_retargeting.md index 9482f8c..24bb841 100644 --- a/docs/guide/humanoid_retargeting.md +++ b/docs/guide/humanoid_retargeting.md @@ -1,28 +1,19 @@ # Humanoid Retargeting -| Two-feet jump retargeted to a G1 humanoid. | A cha-cha dance retargeted to an H1-2 humanoid. | +| ![Two-feet jump retargeted to a G1 humanoid](https://openrobokit.com/assets/docs/robokit/assets/gallery/humanoid_retargeting.webp) | ![A cha-cha dance retargeted to a G1 humanoid](https://openrobokit.com/assets/docs/robokit/assets/gallery/humanoid_retargeting_h1_2.webp) | | --- | --- | +| Two-feet jump retargeted to a G1 humanoid. | A cha-cha dance retargeted to a G1 humanoid. | -`robokit.helpers.humanoid_retargeting` maps human motion onto a floating-base humanoid -robot. Online retargeting solves one frame at a time inside a control loop; offline -retargeting optimizes a whole trajectory at once. +`robokit.helpers.humanoid_retargeting` maps human motion onto a floating-base humanoid. Online +retargeting solves one frame at a time. Offline retargeting solves a whole trajectory at once. -This tutorial covers both workflows. The snippets assume `robot`, `device`, `motion`, and -`human_heights` are already defined; complete runnable examples and visualizations are in +The snippets assume `robot`, `device`, `motion`, and `human_heights` exist. Complete examples are in [`src/robokit/examples/humanoid_retargeting`](../../src/robokit/examples/humanoid_retargeting/). ## How Retargeting Works -Each solve takes human joint transforms and follows three steps: - -1. Map each human joint transform to a robot-link target, scaled by the robot-to-human - height ratio. -2. Optimize the floating base and joints for tracking, joint limits, smoothness, and - velocity limits. -3. Pack the best state as a base pose followed by joint positions. - -Online solves seed each frame from the previous one. Offline solves warm-start every frame -with IK, then run one sparse optimization over all frames jointly. +Each solve scales human joint transforms to robot-link targets by the robot-to-human height +ratio. It then optimizes the floating base and joints and returns the best state. ```mermaid flowchart TD @@ -42,23 +33,21 @@ flowchart TD PACK --> OUT ``` -Every pose is a translation-first 7D pose `(x, y, z, qw, qx, qy, qz)`, and the joint axis -follows `retargeter.human_joint_names`. +Poses are 7D `(x, y, z, qw, qx, qy, qz)`. The joint axis follows `retargeter.human_joint_names`. | Workflow | NumPy input | Output | | --- | --- | --- | | Online | `(B, J, 7)` per frame | `(B, 7 + Q)` | | Offline | `(B, T, J, 7)` | `(B, T, 7 + Q)` | -Here `B` is batch size, `T` is frame count, `J` is human joints, and `Q` is robot joints. -Each output row packs the base pose before the joint positions. `human_heights` has shape -`(B,)`; omitting it uses the preset's assumed height. +`B` is batch size, `T` frame count, `J` human joints, and `Q` robot joints. Each output row is the +base pose followed by joint positions. `human_heights` has shape `(B,)`. Omit it to use the +preset's assumed height. ## Presets -A preset is a `HumanoidRetargeterOnlineConfig` pairing a robot with a human motion source: -the link mapping, per-joint scales, and term weights. Presets exist for the G1, GR3, H1-2, -and BHL robots. +A preset is a `HumanoidRetargeterOnlineConfig` for one robot and one human motion source. Presets +exist for the G1, GR3, H1-2, and BHL robots. ```python # docs: hide @@ -73,11 +62,8 @@ assert g1_smplh.interaction_terms # docs: endhide ``` -Presets are dataclasses; derive a variant with `dataclasses.replace(...)` instead of -mutating one. Each task in `config.terms` names the inputs it reads with `HumanoidContext` -members (`TARGET_LINKS`, `TARGETS`, `PREVIOUS_STATE`, `SCENE`, ...); the retargeter builds -every active template once per solver stage, so any task built from those inputs joins -the solve. Weights scale residuals, keyed by link or joint name where a task supports it. +Derive a variant with `dataclasses.replace(...)`; do not mutate a preset. Costs are tasks in +`config.terms`. Some task weights take a dict keyed by link or joint name. ## Online Retargeting @@ -116,27 +102,26 @@ assert np.isfinite(qpos).all() # docs: endhide ``` -Omitting `robot` loads it from the config. `warmup` builds the solver for its batch size; -the first solve then captures the CUDA graph, so run one throwaway solve and `reset()` -before a timed loop. `solve()` is the Warp-native interface. +Omit `robot` to load it from the config. The first solve captures the CUDA graph. Before a timed +loop, run one throwaway solve and call `reset()`. `solve()` is the Warp API. -`reset()` clears the temporal state between clips. `reset(T_world_base=...)` also seeds the -floating base, which matters when the first frame is far from the origin (see -[`08_terrain.py`](../../src/robokit/examples/humanoid_retargeting/08_terrain.py)). +Call `reset()` between clips. `reset(T_world_base=...)` also seeds the floating base. Use it when +the first frame is far from the origin; see +[`08_terrain.py`](../../src/robokit/examples/humanoid_retargeting/08_terrain.py). See [`01_online.py`](../../src/robokit/examples/humanoid_retargeting/01_online.py). ### Online Batches -Call `warmup(batch_size=B)` and pass one `(B, J, 7)` frame per iteration. Streams advance -in lockstep; repeat the last frame of shorter streams. The batch size is fixed after -`warmup`; create a new retargeter to change it. +Call `warmup(batch_size=B)` and pass one `(B, J, 7)` frame per iteration. Streams advance in +lockstep. Repeat the last frame of shorter streams. The batch size is fixed after `warmup`; create +a new retargeter to change it. See [`06_online_batch.py`](../../src/robokit/examples/humanoid_retargeting/06_online_batch.py). ## Collision Avoidance -The caller owns the `WarpScene`; tasks in `config.terms` enable collision costs: +Weight the `collision` task and pass your own `WarpScene`: ```python # docs: hide @@ -168,20 +153,18 @@ assert retargeter.config.task("collision").weight == 1000.0 # docs: endhide ``` -The `collision` task keeps robot collision spheres away from scene geometry and -requires a scene; the `self_collision` task works without one. Both need robot collision -spheres, which loading the robot from the config includes. Move obstacles with -`geom.update(...)`; the scene layout is fixed after `warmup`. +The `collision` task needs a scene. The `self_collision` task does not. Both need robot collision +spheres; a robot loaded from the config has them. Move obstacles with `geom.update(...)`. The scene +layout is fixed after `warmup`. See [`02_collision.py`](../../src/robokit/examples/humanoid_retargeting/02_collision.py) and [`03_self_collision.py`](../../src/robokit/examples/humanoid_retargeting/03_self_collision.py). ## Contact-aware Retargeting -Contact-aware retargeting preserves the relative arrangement of the mapped human joints and -points sampled on a moving object. It requires an interaction preset such as `g1_smplh`, a -scene whose single mesh is the object, and `batch_size=1`. Set the first target before -`warmup`, then update it before each solve: +Contact-aware retargeting keeps the human joints' layout relative to points on a moving object. +It needs an interaction preset such as `g1_smplh`, a scene with the object as its only mesh, and +`batch_size=1`. Set the first target before `warmup`. Update it before each solve: ```python # docs: hide @@ -222,17 +205,15 @@ assert np.isfinite(qpos).all() # docs: endhide ``` -`object_geom.update(...)` moves the object in the scene; `set_frame(...)` moves the -interaction target. The first target fixes the vertex count. +Move the scene object with `object_geom.update(...)`. Move the interaction target with +`set_frame(...)`. The first target fixes the vertex count. See [`07_contact.py`](../../src/robokit/examples/humanoid_retargeting/07_contact.py). ## Offline Retargeting -Offline retargeting jointly optimizes all frames. It takes the mapping config of the -online solver for its targets, plus an offline config whose `terms` it solves. Those -templates read `HumanoidContext` inputs such as `TARGET_LINKS` and `TARGETS`; the -`positions` and `orientations` tasks weight each mapped link by name: +Offline retargeting optimizes all frames jointly. Pass an online mapping config for the targets +and an offline config for the tasks: ```python # docs: hide @@ -266,18 +247,16 @@ assert np.isfinite(qpos).all() # docs: endhide ``` -The mapping config must not carry online-only interaction or correspondence settings; -its tasks are online-only too, while its velocity limits and output clamp apply offline as well. Configure a `TrajectorySelfCollisionTask` in the offline -task list for offline self-collision, and `warm_start` for the per-frame IK seed. -`solve_numpy(...)` warms up for its input shape automatically; the Warp path requires -`warmup(batch_size=B, num_frames=T)` before `solve()`. +The mapping config must not set interaction or correspondence options. Its tasks apply online +only; its velocity limits and output clamp also apply offline. For offline self-collision, add a +`TrajectorySelfCollisionTask` to the offline tasks. `solve_numpy(...)` warms up for its input +shape. The Warp path needs `warmup(batch_size=B, num_frames=T)` before `solve()`. See [`04_offline.py`](../../src/robokit/examples/humanoid_retargeting/04_offline.py). ### Batch Clips -For clips of unequal length, repeat the final frame to a common length and pass the real -lengths: +Pad shorter clips by repeating their last frame. Pass the real lengths: ```python # docs: hide diff --git a/docs/guide/ik.md b/docs/guide/ik.md index 9485b65..9a043b0 100644 --- a/docs/guide/ik.md +++ b/docs/guide/ik.md @@ -1,23 +1,22 @@ # IK -| An arm tracking a dragged target. | A humanoid tracking hand targets while balancing. | +| ![An arm tracking a dragged target](https://openrobokit.com/assets/docs/robokit/assets/gallery/ik.webp) | ![A humanoid tracking hand targets while balancing](https://openrobokit.com/assets/docs/robokit/assets/gallery/ik_legged.webp) | | --- | --- | +| An arm tracking a dragged target. | A humanoid tracking hand targets while balancing. | -`robokit.helpers.ik` solves inverse kinematics with features including multiple target -links, floating bases, joint limits, smoothness, collision avoidance, and so on. +`robokit.helpers.ik` solves inverse kinematics. It handles multiple target links, floating +bases, joint limits, smoothness, and collision avoidance. -This tutorial covers the main IK workflows. The snippets assume `robot`, `device`, and -target data are already defined; complete runnable examples and visualizations are in +The snippets assume `robot`, `device`, and targets are defined. Runnable examples are in [`src/robokit/examples/ik`](../../src/robokit/examples/ik/). ## How IK Works -Each solve takes target link poses and an optional initial state, then follows three steps: +Each solve takes target link poses and an optional initial state: -1. Sample candidate robot states near the initial state. -2. Run the configured optimizer (Levenberg-Marquardt by default) to reduce pose errors and - other costs. -3. Keep the best candidates and return them as a `RobotState`. +1. Sample candidate states near the initial state. +2. Optimize pose errors and other costs (Levenberg-Marquardt by default). +3. Return the best candidates as a `RobotState`. ```mermaid flowchart TD @@ -39,9 +38,8 @@ flowchart TD ## Basic IK -An `IKSolver` combines a configuration, a robot, and `target_links`: one name/index or a -sequence of names/indices. Links resolve to indices during construction. `presets.basic` -includes position, rotation, and joint-limit terms. +An `IKSolver` takes a configuration, a robot, and `target_links`: one or more link names or +indices. `presets.basic` has position, rotation, and joint-limit terms. Pass the target as a translation-first 7D pose: @@ -69,11 +67,10 @@ assert np.isfinite(q).all() # docs: endhide ``` -The first solve builds the solver for its batch size. Call `ik.warmup(batch_size=1)` before -the first solve when that setup cost must happen outside a control loop. Create a new `IK` -to change the batch size. +The first solve builds the solver for its batch size. Call `ik.warmup(batch_size=1)` to build +it before a control loop. Create a new `IK` to change the batch size. -`solve()` is the Warp-native interface. +`solve()` takes Warp arrays. ### Tracking IK @@ -109,9 +106,8 @@ assert np.isfinite(state.q.numpy()).all() # docs: endhide ``` -`init_state` centers the new samples near the previous answer. `prev_state` supplies the -reference for temporal terms and lets the solver keep the previous answer when it scores -better than the new one. +`init_state` centers new samples on the previous answer. `prev_state` feeds temporal terms. +The solver keeps the previous answer if it scores better. ### Custom Terms @@ -148,29 +144,16 @@ assert ik.config.task("smoothness_task_0").weight == 1.0 # docs: endhide ``` -An argument the solver fills holds an `IKContext` member: `TARGET_LINKS` and `TARGET` are -the target links and the poses passed to `solve`, `PREVIOUS_STATE` is its `prev_state`, and -`REST_Q`/`REST_BASE` are its `rest_state`, `SCENE` is the solver's `scene`, and `SCENE_INDICES` is -the `scene_indices` passed to `solve`. Other terms add constraints or preferences. Use `add_score()` for candidate selection without changing optimization. -Scores normally apply at every selection. Set `solver.rank_final=True` to keep earlier -selections on the optimization cost and return the final candidates in stable score order. - -`CompositeTask(tasks, thresholds=[...])` combines constraints and scores. A numeric -threshold requires every absolute residual of that child to pass; `None` makes the -child a weighted score. Passing candidates rank first, with stable input order for ties. -Without `thresholds`, the existing residual concatenation is unchanged. Composite children -read the solver's values like other terms; `num_candidates=IKContext.NUM_SOLUTIONS` groups -candidates by target. - -Motion planning uses `FrameTask(residual_mode="distance")` on the solver's targets for translation/angle errors, -`PositionLimit(joint_limits=...)` for explicit bounds, scene collision constraints, and -`ConfigurationTask` for distance ranking. +Arguments the solver fills hold `IKContext` members, such as `TARGET` (the poses passed to +`solve`), `PREVIOUS_STATE` (its `prev_state`), and `SCENE` (the solver's scene). Use `add_score()` +to rank candidates without changing the optimization. +`CompositeTask(tasks, thresholds=[...])` mixes constraints and scores. A numeric threshold makes a +child a constraint; `None` makes it a score. Candidates that pass every constraint rank first. ## Batch IK -Batch IK solves several targets in one call. Add a leading batch dimension to the target -array: +Add a leading batch dimension to solve several targets in one call: ```python # docs: hide @@ -194,13 +177,12 @@ assert q_batch.shape == (2, robot.spec.num_actuated_joints) # docs: endhide ``` -The output shape is `(batch * ik.num_solutions, dofs)`. All presets return one solution per -target. A custom final stage may retain more; those solutions use instance-major order. +The output shape is `(batch * ik.num_solutions, dofs)`. Presets return one solution per target. +A custom final stage can keep more, in instance-major order. ## Multiple Target Links -Pass multiple link names to solve for several links together. Each target row matches the -link at the same position in `links`: +Pass several link names to solve them together. Target row `i` belongs to `links[i]`: ```python # docs: hide @@ -235,14 +217,13 @@ assert state.q.shape[0] == 1 # docs: endhide ``` -To give the links different importance, pass per-link weights to `PositionTask` or -`RotationTask`, such as `weight=[20.0, 5.0]`. +Pass per-link weights to `PositionTask` or `RotationTask`, such as `weight=[20.0, 5.0]`. ## Floating Base -Set `enable_T_world_base=True` to optimize six base DOFs along with the joints. A value of -zero in `base_active_mask` locks that DOF; the following configuration allows planar base -motion and locks z, roll, and pitch: +Set `enable_T_world_base=True` to optimize the base pose with the joints. A zero in +`base_active_mask` locks that DOF. This config allows planar base motion and locks z, roll, and +pitch: ```python # docs: hide @@ -287,8 +268,7 @@ assert np.isfinite(T_world_base).all() # docs: endhide ``` -`base_init_sample_range` sets the translation noise of each axis around the initial base -pose. Its default `(0.1, 0.1, 0.0)` samples x and y but not z. +`base_init_sample_range` sets the per-axis translation noise around the initial base pose. ## Collision Avoidance @@ -342,8 +322,8 @@ only when the layout changes. ## Runtime Changes -Every term receives a name such as `position_task_0`. For terms that support runtime weight -updates, use that name to change the weight without rebuilding the solver: +Each term gets a name such as `position_task_0`. Use it to change a supported term's weight +without rebuilding the solver: ```python # docs: hide @@ -384,6 +364,5 @@ assert np.isfinite(state.q.numpy()).all() # docs: endhide ``` -`set_active_joint_mask()` and `set_active_base_mask()` can also lock DOFs at runtime. Other -structural changes, including links, terms, solver stages, collision margins, and scene -layout, require a new `IK`. +`set_active_joint_mask()` and `set_active_base_mask()` lock DOFs at runtime. Changing links, +terms, solver stages, collision margins, or scene layout needs a new `IK`. diff --git a/docs/guide/installation.md b/docs/guide/installation.md index 6f26165..6df9287 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -1,6 +1,6 @@ # Installation -RoboKit needs Python 3.8 or newer; CI tests 3.8 through 3.14 at the oldest allowed and newest dependency versions. +RoboKit needs Python 3.8 or newer. === "uv" ```shell @@ -28,9 +28,9 @@ To work on RoboKit itself, follow the [Development Guide](../dev.md#setup). | Extra | What it adds | | --- | --- | -| `mj` | MJCF loading through `mujoco`; MJCF assembly needs mujoco 3.3.4 or newer (Python 3.9+). | -| `mjwarp` | MuJoCo Warp, for SimMPC's rollouts (Python 3.10+). | -| `pt-cu126`, `pt-cu118`, `pt-cu128`, `pt-cpu` | PyTorch, for the parts that need it; pick the one matching your CUDA toolkit. | +| `mj` | MJCF loading (assembly needs mujoco 3.3.4+, Python 3.9+). | +| `mjwarp` | MuJoCo Warp for SimMPC (Python 3.10+). | +| `pt-cu126`, `pt-cu118`, `pt-cu128`, `pt-cpu` | PyTorch for your CUDA toolkit. | The mask-alignment term and camera calibration also need `nvdiffrast` built for your exact PyTorch and CUDA, such as `pip install "nvdiffrast==0.3.3+pt2.11.0cu126" --extra-index-url https://jianglongye.github.io/torch_packages_builder`. diff --git a/docs/guide/motion_planning.md b/docs/guide/motion_planning.md index 7711d1a..4feaade 100644 --- a/docs/guide/motion_planning.md +++ b/docs/guide/motion_planning.md @@ -1,30 +1,28 @@ # Motion Planning -| Planning around a shelf. | A humanoid reaching around a box while balancing. | +| ![Planning around a shelf](https://openrobokit.com/assets/docs/robokit/assets/gallery/motion_plan.webp) | ![A G1 humanoid squatting and reaching around a raised box](https://openrobokit.com/assets/docs/robokit/assets/gallery/motion_plan_humanoid.webp) | | --- | --- | +| Planning around a shelf. | A humanoid reaching around a box while balancing. | `robokit.helpers.motion_plan` plans a collision-free joint trajectory from a start state to -a goal pose or joint state. Offline planning solves one motion, batch planning solves several -motions together, and online planning repeatedly updates a trajectory while the robot moves. +a goal pose or joint state. Offline planning solves one motion. Batch planning solves several at +once. Online planning updates a trajectory while the robot moves. -This tutorial explains each workflow before showing the planner calls that implement it. The -snippets assume `robot`, `scene`, `device`, and `start_q` are already defined; complete runnable -setups and visualizations are in [`src/robokit/examples/motion_plan`](../../src/robokit/examples/motion_plan/). +The snippets assume `robot`, `scene`, `device`, and `start_q` are defined. Runnable examples and +visualizations are in [`src/robokit/examples/motion_plan`](../../src/robokit/examples/motion_plan/). ## How Planning Works -`MotionPlanner` follows one pipeline: +`MotionPlanner` runs four steps: -1. For a pose goal, `IK` finds goal joint states. A joint-state goal skips IK. -2. The planner samples initial trajectories from the start state to those goals. -3. `GradientTrajectoryOptimizer` or `MppiTrajectoryOptimizer` refines the trajectories for - the goal, collisions, joint limits, and smoothness. -4. `solve_online()` returns the trajectory directly. `solve_offline()` first retimes it with - the last optimizer stage's `retime`, if set. +1. For a pose goal, `IK` finds goal joint states. A joint goal skips IK. +2. The planner samples initial trajectories from the start to those goals. +3. `GradientTrajectoryOptimizer` or `MppiTrajectoryOptimizer` refines them for the goal, + collisions, joint limits, and smoothness. +4. `solve_online()` returns the trajectory. `solve_offline()` first retimes it, if the last stage + sets `retime`. -`MotionPlanner` prepares one IK goal per trajectory candidate before calling the optimizer. -For each batch element, four IK goals and sixteen trajectory candidates assign four consecutive -candidates to each goal. The trajectory candidate count must be divisible by the IK goal count. +The trajectory candidate count must be divisible by the IK goal count. ```mermaid flowchart TD @@ -47,7 +45,7 @@ flowchart TD ## Basic Example -Plan from a start configuration to a hand pose past a box, then sample the plan at a 50 Hz control rate: +Plan to a hand pose past a box, then sample the plan at 50 Hz: ```python # docs: hide @@ -89,18 +87,18 @@ assert np.isfinite(q_control).all() and motion_time > 0 ``` The scene layout and batch size are fixed once the planner allocates its buffers. Move obstacles -with `box.update(...)`; rebuild the planner only when the layout or batch size changes. +with `box.update(...)`; build a new planner only when the layout or batch size changes. ## Offline Planning -`solve_offline_numpy()` and `solve_offline_torch()` take an ordered list of waypoints: the first is -the start, the last the goal. Each waypoint is a joint array `q` or a dict `{link_name: T_world_target}` -of 7D poses or 4x4 matrices. Inputs may carry a leading batch dimension, as in +`solve_offline_numpy()` and `solve_offline_torch()` take a list of waypoints. The first is the start; +the last is the goal. Each waypoint is a joint array `q` or a dict `{link_name: T_world_target}` of +7D poses or 4x4 matrices. Inputs may have a leading batch dimension; see [Batch Planning](#batch-planning). ### Joint Goals -A joint goal skips goal IK, so it takes a joint preset: +A joint goal skips goal IK. Use a joint preset: ```python # docs: hide @@ -160,58 +158,49 @@ The planner then: 1. Solves IK for each pose waypoint, seeded from its neighbors. 2. Optimizes one trajectory with every waypoint locked on a frame; the robot passes through without stopping. -3. Splits frames by the time each part needs, so a short segment takes fewer: the straight lines' before - the solve, then the first stage's paths', which the later stages smooth (`resplit_waypoints=False` keeps - an even split). +3. Gives each segment frames by the time it needs (`resplit_waypoints=False` splits them evenly). 4. Retimes the whole trajectory. -`waypoint_indices` gives each waypoint's frame. Pose waypoints become fixed joint configurations -before optimization, by the planner's goal IK resting at the neighboring waypoints; `planner.ik` solves IK alone, best answer -first. Pose waypoints name the planner's target links. -[`10_waypoints.py`](../../src/robokit/examples/motion_plan/10_waypoints.py) compares one global -optimization with per-segment ones, and -[`12_interpolated_waypoints.py`](../../src/robokit/examples/motion_plan/12_interpolated_waypoints.py) +`waypoint_indices` gives each waypoint's frame. Pose waypoints name the planner's target links; +`planner.ik` solves their IK alone. [`10_waypoints.py`](../../src/robokit/examples/motion_plan/10_waypoints.py) compares one global +optimization with per-segment ones, and [`12_interpolated_waypoints.py`](../../src/robokit/examples/motion_plan/12_interpolated_waypoints.py) shows resplitting. Three options take one entry per segment, waypoint `i` to `i + 1`: -- `segment_check_collision`: False drops world collision there, so a grasp may touch the scene: - `[start_q, pre_grasp_q, grasp_q]` with `(True, False)` plans a collision-free path to the - pre-grasp and a free final approach. -- `segment_fixed_duration`: seconds fix a segment's time. It gets `round(duration / dt)` frames in the - solve, so its neighbors are smoothed against its true speed, keeps them through the resplit, and - `interpolate` plays it over that time; None segments share the remaining frames and are retimed. The - durations must fit in `num_timesteps`, and fill it when every segment has one. -- `segment_locked`: True keeps the segment's frames on the straight line between its waypoints, - e.g. a 1.5 s hold while a gripper closes: `segment_fixed_duration=(None, 1.5)`, `segment_locked=(False, True)`. +- `segment_check_collision=False` ignores the scene there, e.g. for the final grasp approach of + `[start_q, pre_grasp_q, grasp_q]` with `(True, False)`. +- `segment_fixed_duration` fixes a segment's time in seconds; `None` segments are retimed. The + durations must fit in `num_timesteps`. +- `segment_locked=True` keeps a segment on the straight line between its waypoints, e.g. a 1.5 s hold + while a gripper closes: `segment_fixed_duration=(None, 1.5)`, `segment_locked=(False, True)`. -`set_active_joint_mask` before the first solve also limits collision Jacobians to the active joints, e.g. one arm of -a bimanual model. Fewer queries than the planner's first batch are padded to it. +To plan for some joints only, such as one arm of a bimanual robot, call `set_active_joint_mask` before +the first solve. ### Speed and Control Rate -Offline plans are retimed to the fastest motion the robot's velocity limits and the planner's -`acceleration_limit` and `jerk_limit` allow, -with one step for every frame. `RetimeConfig.speed_scale` runs at a fraction of that speed: `0.5` -takes twice as long. `result.interpolate(dt, speed_scale)` samples a plan every `dt` seconds, with -each waypoint among the samples; its `speed_scale` slows the plan further without replanning. +Offline plans are retimed to the fastest motion within the robot's velocity limits and the +planner's `acceleration_limit` and `jerk_limit`. `RetimeConfig.speed_scale` runs slower: `0.5` +takes twice as long. `result.interpolate(dt, speed_scale)` samples the plan every `dt` seconds and +keeps each waypoint as a sample. Its `speed_scale` slows the plan further without replanning. [`11_interpolated_speed.py`](../../src/robokit/examples/motion_plan/11_interpolated_speed.py) sets both with Viser sliders. ## Batch Planning -Batch planning solves several start-goal pairs in one call. Starts and goals gain a leading -batch dimension, while `scene_indices[i]` selects the collision scene used by query `i`. -The number of queries and the number of scenes are independent. +Batch planning solves several start-goal pairs in one call. Starts and goals get a leading batch +dimension. `scene_indices[i]` picks the collision scene for query `i`; queries and scenes need not +match in number. -For example, the following batch contains four planning queries routed to two scenes: +Here four queries use two scenes: ```text query: 0 1 2 3 scene_indices: 0 0 1 1 ``` -The planning call itself does not change: +The call is the same: ```python # docs: hide @@ -267,17 +256,16 @@ assert np.isfinite(q_traj_batch).all() # docs: endhide ``` -For a shared scene, use a one-scene `WarpScene` and fill `scene_indices` with zeros. A scene -may combine boxes, meshes, and other geometry types; the per-query mapping remains the same. +For a shared scene, use a one-scene `WarpScene` and fill `scene_indices` with zeros. A scene can +mix boxes, meshes, and other geometry. ## Online Planning -Online planning runs in a control loop. Each iteration plans from the current robot state, -executes the next trajectory waypoint, and uses that new state for the next iteration. -Goals and obstacle poses may be updated before every solve. +Online planning runs in a control loop. Each step plans from the current state and moves the +robot to the next trajectory frame. Goals and obstacle poses may change before any solve. -MPPI retains its trajectory and action distribution between updates. The caller solves goal IK -when the pose target changes and passes that joint goal into each planning update. +MPPI keeps its trajectory between solves. Solve goal IK when the pose target changes and pass the +result as `target_q`. ```python # docs: hide @@ -336,18 +324,17 @@ assert np.isfinite(current.q.numpy()).all() # docs: endhide ``` -For L-BFGS, use `presets.online_pose_lbfgs`. It can solve pose IK internally, so `target_q` may be -omitted. +For L-BFGS, use `presets.online_pose_lbfgs`. It solves pose IK itself, so `target_q` is optional. -For moving environments, update geometry with `geom.update(...)` before the next solve. Tight -control loops should preallocate their input Warp arrays instead of allocating them inside the loop. +To move obstacles, call `geom.update(...)` before the next solve. In tight loops, allocate input +Warp arrays once, outside the loop. ## Customization ### Objectives -Each optimizer stage holds a list of tasks; weights, collision margins and limits live on them. -Edit a copy of a preset: +Each optimizer stage holds a list of tasks with their weights, margins and limits. Edit a copy of +a preset: ```python from copy import deepcopy @@ -359,8 +346,8 @@ stage.task("collision").margin = 0.03 stage.task("position_limit").dense_task.weight = 200.0 ``` -For a new objective, list only the tasks you want. An argument set to a `MotionPlanContext` member, -such as `ctx.TARGET` or `ctx.START_Q`, is filled by the stage for each query: +For a new objective, list only the tasks you want. Arguments set to a `MotionPlanContext` member, +such as `ctx.TARGET` or `ctx.START_Q`, are filled in for each query: ```python from robokit.helpers.motion_plan import GradientTrajectoryOptimizerConfig, MotionPlanContext as ctx @@ -383,12 +370,10 @@ Goal IK has its own task list, `config.goal_ik.terms`. ### Point clouds and depth -`SdfVolume.from_mesh`, `from_points`, and `from_depth` construct collision grids. -XYZ samples mark occupied cells; depth supplies free-space evidence and fuses -projective distances using camera intrinsics and `T_world_camera` (OpenCV axes: -right, down, forward). Both input types can update the same volume. Points add -occupied cells; subsequent depth observations may clear them. Unknown space is -free by default; use `unknown_is_occupied=True` on each update to block it. +`SdfVolume.from_mesh`, `from_points`, and `from_depth` build collision grids. Points mark occupied +cells. Depth also marks free space, given the camera `intrinsics` and `T_world_camera` (OpenCV axes: +right, down, forward), so later depth can clear old points. Unknown space is free; pass +`unknown_is_occupied=True` to block it. ```python # docs: hide @@ -410,21 +395,15 @@ scene = WarpScene(1, "cuda:0").add(VolumeGeom([volume], np.array([0, 1], dtype=n volume.update(depth=depth, intrinsics=intrinsics, T_world_camera=T_world_camera) ``` -Pass `scene` to the planner. Updates preserve volume IDs and captured collision -graphs; `reset=True` forgets old observations. Fusion options apply per call. -Bounds, device and resolution stay fixed; create a new volume and call -`VolumeGeom.update` to change them. Bounds crop observations rather than forming -workspace walls. All updates use Warp jump flooding with two refinement passes -(approximate distances); there is no CPU EDT path. Pass device Warp arrays -(`vec3` points or a 2D `float32` depth image) to avoid input uploads. Intrinsics -and camera transforms also accept `wp.mat33` and `wp.mat44`; transforms must be -rigid. Save/load preserves fusion history. Keep calibration with partial clouds: -XYZ alone cannot identify free space. +Pass `scene` to the planner and call `volume.update` as observations arrive; `reset=True` forgets old +ones. Bounds, device and resolution are fixed; to change them, create a new volume and call +`VolumeGeom.update`. Bounds crop observations; they are not walls. Pass device Warp arrays to avoid +uploads. Points alone cannot mark free space, so add calibrated depth when you can. ### Humanoids -`presets.humanoid_offline_lbfgs`, `humanoid_online_lbfgs` and `humanoid_online_mppi` plan both hands of a -floating-base humanoid (`goal_ik.enable_T_world_base=True`) with its feet planted. Their named -`feet_position`, `feet_rotation`, `balance` and `posture` terms are stubs to complete once the standing pose is -known, through `config.goal_ik.task(name)` and `config.stages[0].task(name)`; examples 08 and 09 show how. -Floating-base results also carry `T_world_base_traj`. +`presets.humanoid_offline_lbfgs`, `humanoid_online_lbfgs` and `humanoid_online_mppi` plan both +hands of a floating-base humanoid with its feet planted. Their `feet_position`, `feet_rotation`, +`balance` and `posture` terms are stubs. Fill them in once the standing pose is known, through +`config.goal_ik.task(name)` and `config.stages[0].task(name)`; examples 08 and 09 show how. +Floating-base results also include `T_world_base_traj`. diff --git a/docs/guide/overview.md b/docs/guide/overview.md index e6d3029..3eeeec4 100644 --- a/docs/guide/overview.md +++ b/docs/guide/overview.md @@ -1,30 +1,40 @@ -![RoboKit](../assets/robokit-banner.webp) - -![Thousands of robots solving in parallel](../assets/robokit-teaser.webp) +![RoboKit](https://openrobokit.com/assets/docs/robokit/assets/robokit-banner.webp) RoboKit is a high-performance, general-purpose toolkit for versatile robotic tasks. It scales from one problem to thousands in parallel. It provides a library of cost terms and optimizers that compose freely. Built-in tasks such as IK, motion planning, and retargeting are validated on real robots. -## Key features - -- **Scalable.** One problem or thousands of seeds, solved in one call. Sparse Jacobians scale - to long trajectories. -- **Composable.** Any cost term works with any optimizer. Pick Gauss-Newton for IK and - L-BFGS for trajectories, and reuse the same terms in both. -- **Geometry and rendering.** Built for uncompromising performance. Hybrid voxel-mesh SDF queries and - coarse-to-fine collision and rendering schedules cut the cost of every iteration. -- **GPU-accelerated.** Every kernel is written in [Warp](https://github.com/NVIDIA/warp), a - significant speedup over prior frameworks. -- **Any robot.** URDF or MJCF, fixed or floating base, mimic joints. Curated models ship with - [collision spheres](assets.md). -- **Differentiable.** Gradients flow through kinematics and every cost. Terms plug into Torch, - so optimization can be distilled into policies. +![Thousands of robots solving in parallel](https://openrobokit.com/assets/docs/robokit/assets/robokit-teaser.webp) + +*Thousands of robots solving in parallel.* + +## Benchmarks + +![RoboKit speedups: locomotion MPC 3.4× vs DIAL-MPC; IK 12× vs PyRoKi; motion planning 3.5× vs cuRobo; hand retargeting 27× vs PyRoKi; humanoid retargeting 4× vs GMR; physics retargeting 3.5× vs SPIDER; grasp synthesis 60× vs Dex1B; RL time to score 1.7× vs mjlab; rendering calibration 57× vs EasyHEC on the easy split.](https://openrobokit.com/assets/docs/robokit/assets/robokit-benchmarks.webp) + +Bars are wall-clock time on the same task, baseline normalized to full width. +Check the paper for benchmark details. + +## Optimization/Learning with Simulation + +| [![NIST Assembly](https://openrobokit.com/assets/docs/robokit/assets/simulation/nist.webp)](../../src/robokit/examples/rl/14_nist_assembly.py) | [![Rough Terrain](https://openrobokit.com/assets/docs/robokit/assets/simulation/go1-rough.webp)](../../src/robokit/examples/rl/02_rough_joystick.py) | [![Pen Spinning](https://openrobokit.com/assets/docs/robokit/assets/simulation/pen.webp)](../../src/robokit/examples/sim_mpc/07_sharpa_pen.py) | +| --- | --- | --- | +| **[NIST Assembly](../../src/robokit/examples/rl/14_nist_assembly.py)** `RL` A Franka puts six NIST board parts in place, one after another (3× speed). | **[Rough Terrain](../../src/robokit/examples/rl/02_rough_joystick.py)** `RL` A Go1 walks up and down stairs, following the green velocity command. | **[Pen Spinning](../../src/robokit/examples/sim_mpc/07_sharpa_pen.py)** `MPC` A Sharpa hand spins a pen in its fingers. | +| [![Notebook Opening](https://openrobokit.com/assets/docs/robokit/assets/simulation/notebook.webp)](../../src/robokit/examples/sim_mpc/02_xhand_arctic.py) | [![Box Carrying](https://openrobokit.com/assets/docs/robokit/assets/simulation/g1-box.webp)](../../src/robokit/examples/sim_mpc/04_g1_carry.py) | [![Climbing](https://openrobokit.com/assets/docs/robokit/assets/simulation/g1-climb.webp)](../../src/robokit/examples/sim_mpc/03_g1_climb.py) | +| **[Notebook Opening](../../src/robokit/examples/sim_mpc/02_xhand_arctic.py)** `MPC` Two XHands open a hinged ARCTIC notebook. | **[Box Carrying](../../src/robokit/examples/sim_mpc/04_g1_carry.py)** `MPC` A G1 lifts and carries a box. | **[Climbing](../../src/robokit/examples/sim_mpc/03_g1_climb.py)** `MPC` A G1 climbs a box on hands and knees. | + +## Optimization with Analytic Objectives + +| [![IK](https://openrobokit.com/assets/docs/robokit/assets/built-in-tasks/ik.webp)](ik.md) | [![Motion planning](https://openrobokit.com/assets/docs/robokit/assets/built-in-tasks/motion-planning.webp)](motion_planning.md) | [![Hand-eye calibration](https://openrobokit.com/assets/docs/robokit/assets/built-in-tasks/hand-eye-calibration.webp)](hand_eye_calibration.md) | +| --- | --- | --- | +| **[IK](ik.md)** Multi-link targets, fixed or floating base. | **[Motion Planning](motion_planning.md)** Collision-free trajectories, offline or online. | **[Hand-Eye Calibration](hand_eye_calibration.md)** Camera pose from rendered robot masks. | +| [![Humanoid retargeting](https://openrobokit.com/assets/docs/robokit/assets/built-in-tasks/humanoid-retargeting.webp)](humanoid_retargeting.md) | [![Hand retargeting](https://openrobokit.com/assets/docs/robokit/assets/built-in-tasks/hand-retargeting.webp)](hand_retargeting.md) | [![Grasp optimization](https://openrobokit.com/assets/docs/robokit/assets/built-in-tasks/grasp-optimization.webp)](../../src/robokit/examples/grasp/) | +| **[Humanoid Retargeting](humanoid_retargeting.md)** Human motion capture to a humanoid. | **[Hand Retargeting](hand_retargeting.md)** Human hand motion to a robot hand. | **[Grasp Optimization](../../src/robokit/examples/grasp/)** Force-closure grasps for any hand or body. | ## How it works -![RoboKit framework](../assets/robokit-framework.webp) +![RoboKit framework](https://openrobokit.com/assets/docs/robokit/assets/robokit-framework.webp) | Component | Role | Read more | | --- | --- | --- | @@ -34,18 +44,21 @@ real robots. | Acceleration | Fast geometry and rendering for contact-rich and calibration tasks. | [Geometry](../concepts/geom.md) | | Distillation | Train policies on solver outputs for even faster inference. | | -## Built-in tasks +## Installation -| [![IK](../assets/built-in-tasks/ik.webp)](ik.md) | [![Motion planning](../assets/built-in-tasks/motion-planning.webp)](motion_planning.md) | [![Hand-eye calibration](../assets/built-in-tasks/hand-eye-calibration.webp)](hand_eye_calibration.md) | -| --- | --- | --- | -| **[IK](ik.md)** Multi-link targets, fixed or floating base. | **[Motion Planning](motion_planning.md)** Collision-free trajectories, offline or online. | **[Hand-Eye Calibration](hand_eye_calibration.md)** Camera pose from rendered robot masks. | -| [![Humanoid retargeting](../assets/built-in-tasks/humanoid-retargeting.webp)](humanoid_retargeting.md) | [![Hand retargeting](../assets/built-in-tasks/hand-retargeting.webp)](hand_retargeting.md) | [![Grasp optimization](../assets/built-in-tasks/grasp-optimization.webp)](../../src/robokit/examples/grasp/) | -| **[Humanoid Retargeting](humanoid_retargeting.md)** Human motion capture to a humanoid. | **[Hand Retargeting](hand_retargeting.md)** Human hand motion to a robot hand. | **[Grasp Optimization](../../src/robokit/examples/grasp/)** Force-closure grasps for any hand or body. | +Requires Python 3.8 or newer: + +```shell +uv add robokit # or: pip install robokit +``` + +PyTorch is optional. See [Installation](installation.md) for source installs and extras. ## Quick links - [Quickstart](quickstart.md) - [Installation](installation.md) +- [Development](../dev.md) - [GitHub](https://github.com/openrobokit/robokit) ## Citation diff --git a/docs/guide/quickstart.md b/docs/guide/quickstart.md index 1d4089a..0a48520 100644 --- a/docs/guide/quickstart.md +++ b/docs/guide/quickstart.md @@ -10,14 +10,17 @@ uvx --from robokit python -m robokit.gallery.ik Drag targets, switch robots, and adjust weights. Replace `ik` with any gallery below. -| **`ik`** Drag targets and tune IK weights. | **`ik_legged`** Balance humanoids and quadrupeds. | **`motion_plan`** Plan motions around obstacles. | +| ![IK target tracking and robot switching](https://openrobokit.com/assets/docs/robokit/assets/gallery/ik.webp) | ![Humanoid tracking hand targets while balancing](https://openrobokit.com/assets/docs/robokit/assets/gallery/ik_legged.webp) | ![Motion planning around a shelf](https://openrobokit.com/assets/docs/robokit/assets/gallery/motion_plan.webp) | | --- | --- | --- | +| **`ik`** Drag targets and tune IK weights. | **`ik_legged`** Balance humanoids and quadrupeds. | **`motion_plan`** Plan motions around obstacles. | -| **`humanoid_retargeting`** Retarget human motion to humanoids. | **`humanoid_retargeting_contact`** Retarget humanoids with object contacts. | **`hand_retargeting_contact`** Retarget hands with object contacts. | +| ![Human motion retargeted to a G1 humanoid](https://openrobokit.com/assets/docs/robokit/assets/gallery/humanoid_retargeting.webp) | ![Humanoid moving a clothes stand with contact constraints](https://openrobokit.com/assets/docs/robokit/assets/gallery/humanoid_retargeting_contact.webp) | ![Hand-object retargeting across DexMachina, GigaHands, and OakInk2](https://openrobokit.com/assets/docs/robokit/assets/gallery/hand_retargeting_contact.webp) | | --- | --- | --- | +| **`humanoid_retargeting`** Retarget human motion to humanoids. | **`humanoid_retargeting_contact`** Retarget humanoids with object contacts. | **`hand_retargeting_contact`** Retarget hands with object contacts. | -| **`hand_retargeting`** Retarget hands onto any base, online or offline. | **`robot_models`** Browse robots, collision spheres, and frames. | **`full_body_retargeting`** Retarget whole-body human-object interaction. | +| ![XHand on an xArm7 replaying a captured hand motion](https://openrobokit.com/assets/docs/robokit/assets/gallery/hand_retargeting.webp) | ![KUKA iiwa arm moving through a smooth joint motion](https://openrobokit.com/assets/docs/robokit/assets/gallery/robot_models.webp) | ![A ParaHome cutting-board clip retargeted whole-body](https://openrobokit.com/assets/docs/robokit/assets/gallery/full_body_retargeting.webp) | | --- | --- | --- | +| **`hand_retargeting`** Retarget hands onto any base, online or offline. | **`robot_models`** Browse robots, collision spheres, and frames. | **`full_body_retargeting`** Retarget whole-body human-object interaction. | ## Solve one IK problem @@ -37,7 +40,7 @@ state = ik.solve_numpy(T_world_target) print(state.q.numpy()[0]) # joint positions ``` -`IK` picks the GPU when one is visible and falls back to the CPU otherwise. +`IK` uses the GPU when one is visible, else the CPU. ## More examples @@ -53,8 +56,8 @@ Paths are relative to [`src/robokit/examples`](../../src/robokit/examples/). | [`hand_eye_calibration`](../../src/robokit/examples/hand_eye_calibration/) | [`01_sim_rgb.py`](../../src/robokit/examples/hand_eye_calibration/01_sim_rgb.py), [`02_sim_mounted.py`](../../src/robokit/examples/hand_eye_calibration/02_sim_mounted.py), [`03_sim_depth.py`](../../src/robokit/examples/hand_eye_calibration/03_sim_depth.py), [`04_real_xarm.py`](../../src/robokit/examples/hand_eye_calibration/04_real_xarm.py), [`05_sim_offsets.py`](../../src/robokit/examples/hand_eye_calibration/05_sim_offsets.py), [`06_sim_qpos.py`](../../src/robokit/examples/hand_eye_calibration/06_sim_qpos.py) | | [`grasp`](../../src/robokit/examples/grasp/) | [`01_basic.py`](../../src/robokit/examples/grasp/01_basic.py), [`02_annealed_gd.py`](../../src/robokit/examples/grasp/02_annealed_gd.py) | | [`geom`](../../src/robokit/examples/geom/) | [`01_basic.py`](../../src/robokit/examples/geom/01_basic.py), [`02_robot.py`](../../src/robokit/examples/geom/02_robot.py), [`03_heterogeneous_batch.py`](../../src/robokit/examples/geom/03_heterogeneous_batch.py), [`04_lod.py`](../../src/robokit/examples/geom/04_lod.py) | -| [`opt`](../../src/robokit/examples/opt/) | [`01_rosenbrock.py`](../../src/robokit/examples/opt/01_rosenbrock.py), [`02_solvers.py`](../../src/robokit/examples/opt/02_solvers.py), [`03_multi_candidate.py`](../../src/robokit/examples/opt/03_multi_candidate.py), [`04_curve_fit.py`](../../src/robokit/examples/opt/04_curve_fit.py), [`05_mpc_pendulum.py`](../../src/robokit/examples/opt/05_mpc_pendulum.py), [`06_mpc_navigation.py`](../../src/robokit/examples/opt/06_mpc_navigation.py) | -| [`sim_mpc`](../../src/robokit/examples/sim_mpc/) | [`01_sharpa_oakink.py`](../../src/robokit/examples/sim_mpc/01_sharpa_oakink.py), [`02_xhand_arctic.py`](../../src/robokit/examples/sim_mpc/02_xhand_arctic.py), [`03_xhand_arctic_articulated.py`](../../src/robokit/examples/sim_mpc/03_xhand_arctic_articulated.py), [`04_g1_climb.py`](../../src/robokit/examples/sim_mpc/04_g1_climb.py), [`05_g1_carry.py`](../../src/robokit/examples/sim_mpc/05_g1_carry.py), [`06_g1_amass.py`](../../src/robokit/examples/sim_mpc/06_g1_amass.py), [`07_leap_cube.py`](../../src/robokit/examples/sim_mpc/07_leap_cube.py), [`08_sharpa_pen.py`](../../src/robokit/examples/sim_mpc/08_sharpa_pen.py), [`09_sharpa_cube.py`](../../src/robokit/examples/sim_mpc/09_sharpa_cube.py), [`10_h1_jog.py`](../../src/robokit/examples/sim_mpc/10_h1_jog.py), [`11_go2_jump.py`](../../src/robokit/examples/sim_mpc/11_go2_jump.py), [`12_fr3_push.py`](../../src/robokit/examples/sim_mpc/12_fr3_push.py), [`13_fr3_balance.py`](../../src/robokit/examples/sim_mpc/13_fr3_balance.py), [`14_batch.py`](../../src/robokit/examples/sim_mpc/14_batch.py), [`15_demo_repair.py`](../../src/robokit/examples/sim_mpc/15_demo_repair.py) | +| [`opt`](../../src/robokit/examples/opt/) | [`01_rosenbrock.py`](../../src/robokit/examples/opt/01_rosenbrock.py), [`02_solvers.py`](../../src/robokit/examples/opt/02_solvers.py), [`03_multi_candidate.py`](../../src/robokit/examples/opt/03_multi_candidate.py), [`04_curve_fit.py`](../../src/robokit/examples/opt/04_curve_fit.py), [`05_mpc_pendulum.py`](../../src/robokit/examples/opt/05_mpc_pendulum.py), [`06_mpc_navigation.py`](../../src/robokit/examples/opt/06_mpc_navigation.py), [`07_ilqr_pendulum.py`](../../src/robokit/examples/opt/07_ilqr_pendulum.py) | +| [`sim_mpc`](../../src/robokit/examples/sim_mpc/) | [`01_sharpa_oakink.py`](../../src/robokit/examples/sim_mpc/01_sharpa_oakink.py), [`02_xhand_arctic.py`](../../src/robokit/examples/sim_mpc/02_xhand_arctic.py), [`03_g1_climb.py`](../../src/robokit/examples/sim_mpc/03_g1_climb.py), [`04_g1_carry.py`](../../src/robokit/examples/sim_mpc/04_g1_carry.py), [`05_g1_amass.py`](../../src/robokit/examples/sim_mpc/05_g1_amass.py), [`06_leap_cube.py`](../../src/robokit/examples/sim_mpc/06_leap_cube.py), [`07_sharpa_pen.py`](../../src/robokit/examples/sim_mpc/07_sharpa_pen.py), [`08_sharpa_coin.py`](../../src/robokit/examples/sim_mpc/08_sharpa_coin.py), [`09_sharpa_cap.py`](../../src/robokit/examples/sim_mpc/09_sharpa_cap.py), [`10_wuji_cube.py`](../../src/robokit/examples/sim_mpc/10_wuji_cube.py), [`11_h1_jog.py`](../../src/robokit/examples/sim_mpc/11_h1_jog.py), [`12_go2_jump.py`](../../src/robokit/examples/sim_mpc/12_go2_jump.py), [`13_fr3_push.py`](../../src/robokit/examples/sim_mpc/13_fr3_push.py), [`14_fr3_balance.py`](../../src/robokit/examples/sim_mpc/14_fr3_balance.py), [`15_batch.py`](../../src/robokit/examples/sim_mpc/15_batch.py), [`16_demo_repair.py`](../../src/robokit/examples/sim_mpc/16_demo_repair.py), [`18_g1_flip.py`](../../src/robokit/examples/sim_mpc/18_g1_flip.py) | Example usage: diff --git a/docs/guide/rl.md b/docs/guide/rl.md new file mode 100644 index 0000000..76ca14b --- /dev/null +++ b/docs/guide/rl.md @@ -0,0 +1,128 @@ +# RL + +| ![A G1 tracking a LAFAN1 dance](https://openrobokit.com/assets/docs/robokit/assets/rl/g1-tracking.webp) | ![A Go1 following joystick commands](https://openrobokit.com/assets/docs/robokit/assets/rl/go1-joystick.webp) | +| --- | --- | +| A G1 tracks a LAFAN1 dance. | A Go1 follows joystick commands. | + +`robokit.helpers.rl` trains policies on batched GPU simulations, with features including PPO, CUDA-graphed +updates, and coarse-to-fine physics. + +This tutorial covers the main RL workflows. The examples' envs run on +[MuJoCo Warp](https://github.com/google-deepmind/mujoco_warp) (`MjWarpSim`); install it with the `mj` and `mjwarp` +[extras](installation.md#extras), and PyTorch with a `pt-*` extra. Complete runnable examples are in +[`src/robokit/examples/rl`](../../src/robokit/examples/rl/). + +## How RL Works + +Each PPO update follows three steps: + +1. Roll the actor out for `horizon` steps in every world of the env. +2. Update the actor and the critic on that rollout over several epochs. +3. Adapt the learning rate to the policy's KL divergence. + +```mermaid +flowchart TD + INPUT[Input

Env of batched GPU worlds] + + subgraph TRAINING[Training] + direction TB + ROLL[1. Roll out the actor] + UPDATE[2. Update actor and critic] + ADAPT[3. Adapt the learning rate] + ROLL --> UPDATE --> ADAPT + ADAPT -->|repeat| ROLL + end + + ACTOR[Return the actor] + + INPUT --> ROLL + ADAPT --> ACTOR +``` + +The env's tensors stay on the GPU, so no step waits for the host. After a few warm-up updates, each +update replays as one CUDA graph. + +## Environments + +An env implements `Env`: `n` worlds, the actor's and the critic's observation sizes (`obs_dims`), the action +`bound`, and the `names` of its reward terms. Its methods take and return GPU tensors: + +| Method | What it does | +| --- | --- | +| `obs()` | Returns the actor's and the critic's observations. | +| `step(action)` | Acts; returns the reward, terminated and truncated flags per world, and each reward term's mean. | +| `reset(mask)` | Resets the masked worlds. | +| `curriculum(step)` | Moves the curriculum to `step` env steps. | + +The examples wrap `MjWarpSim` worlds and read `sim.data.torch.qpos`, `qvel` and `ctrl`, zero-copy torch views. + +## Basic PPO + +A `PPO` holds an actor and a critic. Each `update(env)` rolls out once and updates once; the caller owns +the loop. This trains on a toy env where actions near zero pay: + +```python +# docs: hide +# xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS==1,module:torch) +from types import SimpleNamespace + +import torch + +obs, done = torch.zeros(64, 3, device="cuda"), torch.zeros(64, dtype=torch.bool, device="cuda") +env = SimpleNamespace( + n=64, + obs_dims=(3, 3), + bound=torch.ones(2, device="cuda"), + names=["effort"], + obs=lambda: (obs, obs), + step=lambda a: (-(a**2).sum(1), done, done, (a**2).mean()[None]), + reset=id, + curriculum=id, +) +# docs: endhide +from robokit.helpers.rl import ppo + +learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig()) +for _ in range(10): + learner.update(env) + +score = ppo.evaluate(env, learner.actor, steps=100) # each reward term's mean per step, and terminations +# docs: hide +assert set(score) == {"effort", "terminations"} +# docs: endhide +``` + +`learner.actor(obs)` returns the mean action. `PPOConfig` holds the PPO settings, such as `horizon`, `epochs`, `minibatches`, `lr`, `kl`, `entropy`, and `hidden`. + +### Coarse-to-Fine Training + +A policy can train on cheaper physics first. Build the coarse env's scene with `MjWarpSim.build_coarse_spec` and a +`CoarseConfig`, then let `train` mix it in: over the first half of the time, an update draws it with a chance falling to 0. + +```python +# docs: hide +# xdoctest: +SKIP +# docs: endhide +actor = learner.train(fine, minutes, coarse_env=coarse, coarse=0.5) +``` + +## Examples + +| Example | Task | +| --- | --- | +| [`01_joystick.py`](../../src/robokit/examples/rl/01_joystick.py) | A Go1 or G1 tracks twist commands. | +| [`02_rough_joystick.py`](../../src/robokit/examples/rl/02_rough_joystick.py) | A Go1 or G1 tracks twist commands on rough terrain. | +| [`03_lift.py`](../../src/robokit/examples/rl/03_lift.py) | A Yam arm carries a cube to random targets. | +| [`04_go1_getup.py`](../../src/robokit/examples/rl/04_go1_getup.py) | A Go1 stands up from a random pose. | +| [`05_panda_pick.py`](../../src/robokit/examples/rl/05_panda_pick.py) | A Panda picks up a cube and brings it to a target. | +| [`06_leap_reorient.py`](../../src/robokit/examples/rl/06_leap_reorient.py) | A LEAP hand turns a cube to goal after goal. | +| [`07_aloha_handover.py`](../../src/robokit/examples/rl/07_aloha_handover.py) | Two ALOHA arms pass a box between grippers. | +| [`08_g1_tracking.py`](../../src/robokit/examples/rl/08_g1_tracking.py) | A G1 tracks a LAFAN1 dance. | +| [`09_go1_handstand.py`](../../src/robokit/examples/rl/09_go1_handstand.py) | A Go1 balances on its front feet. | +| [`10_h1_gait.py`](../../src/robokit/examples/rl/10_h1_gait.py) | An H1 walks at a commanded step rate and swing height. | +| [`11_aloha_peg.py`](../../src/robokit/examples/rl/11_aloha_peg.py) | Two ALOHA arms push a peg into a socket. | +| [`12_panda_cabinet.py`](../../src/robokit/examples/rl/12_panda_cabinet.py) | A Panda pulls a drawer open. | +| [`13_cartpole.py`](../../src/robokit/examples/rl/13_cartpole.py) | A cart swings up and balances a pole. | +| [`14_nist_assembly.py`](../../src/robokit/examples/rl/14_nist_assembly.py) | A Panda inserts pegs and meshes gears on the NIST assembly board. | + +Run one with `uv run src/robokit/examples/rl/13_cartpole.py swingup --minutes 1`. diff --git a/docs/guide/sim_mpc.md b/docs/guide/sim_mpc.md index 682ade7..850d2e6 100644 --- a/docs/guide/sim_mpc.md +++ b/docs/guide/sim_mpc.md @@ -1,38 +1,53 @@ # Sim MPC -`robokit.helpers.sim_mpc` is a sampling model-predictive controller for simulated scenes. It samples control -offsets around a reference, rolls every draw out in parallel simulated worlds, and moves the plan toward the draws -with the lowest cost. One preset tracks motion capture on humanoids, legged gaits, hand-object clips and pushing -tasks; only the scene, the reference and the costs change. - -The planner never touches a simulator: a binding runs its worlds. `MjWarpSim` in `robokit.helpers.sim_mpc.mjwarp` -runs [MuJoCo Warp](https://github.com/google-deepmind/mujoco_warp), and `robokit.helpers.sim_mpc.newton` runs -[Newton](https://github.com/newton-physics/newton). The costs are `robokit.terms` tasks that read the binding's -arrays. MuJoCo Warp is not a RoboKit extra, so add it to the run: -`uv run --with mujoco --with mujoco-warp python script.py`. SimMPC runs on the current Warp device: a CUDA GPU, where -every sim step replays a captured CUDA graph, or the CPU (`wp.ScopedDevice("cpu")`), which is much slower. +| ![A G1 lifting and carrying a box](https://openrobokit.com/assets/docs/robokit/assets/simulation/g1-box.webp) | ![A Sharpa hand spinning a pen](https://openrobokit.com/assets/docs/robokit/assets/simulation/pen.webp) | +| --- | --- | +| A G1 lifts and carries a box. | A Sharpa hand spins a pen in its fingers. | + +`robokit.helpers.sim_mpc` is sampling MPC in simulation, with features including motion-capture +tracking, legged gaits, hand-object manipulation, pushing, and batched scenes. + +This tutorial covers the main SimMPC workflows. Rollouts run in +[MuJoCo Warp](https://github.com/google-deepmind/mujoco_warp) (`MjWarpSim`) or +[Newton](https://github.com/newton-physics/newton) (`robokit.sim.newton.NewtonSim`); install MuJoCo Warp with +the `mj` and `mjwarp` [extras](installation.md#extras). Complete runnable examples are in [`src/robokit/examples/sim_mpc`](../../src/robokit/examples/sim_mpc/). ## How SimMPC Works -Controls are `ctrl_ref` plus an offset interpolated through nodes every `node_steps` sim steps. Each control -period starts from the executed state: +Each `plan(data, t0)` starts from the given state, then follows four steps: -1. Draw `num_samples` node offsets around the plan; draw zero is the plan itself. -2. Roll every draw out for `horizon_steps` and sum the cost each term adds per step. -3. Move the plan to the cost-weighted mean and redraw, until the best draw stops improving or - `max_iterations` is reached. -4. Score the moved plan; if it costs over 4 temperatures more than the best draw, keep the best draw. -5. Execute the first `ctrl_steps` of the plan in one world and shift the plan forward. +1. Sample control offsets around the current plan; draw zero is the plan itself. +2. Roll every draw out in parallel worlds for `horizon_steps` and sum its costs. +3. Move the plan toward the low-cost draws, until it stops improving or reaches `max_iterations`. +4. Return the first `ctrl_steps` commands and shift the plan forward. -Each plan is one `PopulationSolver` solve with a `GaussianSampler`, robokit's MPPI that motion planning also runs; -SimMPC turns on their options that motion planning leaves off: the temperature from the best 20% of draws, the -mean over those draws only, per-iteration noise decay, the plateau stop (`min_improvement`, `patience`) and draws -clamped to `ctrl_range`. Ranking, annealing and redrawing stay on the device, so iterations queue without waiting -for the host. +```mermaid +flowchart TD + INPUT[Input

Current state
Sim step t0] -## Basic Example + subgraph PLANNING[Planning] + direction TB + SAMPLE[1. Sample control offsets] + ROLL[2. Roll out and score] + MOVE[3. Move the plan] + SAMPLE --> ROLL --> MOVE + MOVE -->|repeat| SAMPLE + end -`SimMPCConfig` holds the per-task numbers (samples, horizon, nodes, iterations). This drives a cart on a slide joint from `x = 0` to `x = 0.3`: + OUTPUT[Return the next commands] + + INPUT --> SAMPLE + MOVE --> OUTPUT +``` + +Controls are `ctrl_ref` plus offsets interpolated between nodes every `node_steps` sim steps. The +sampler is robokit's MPPI, the one motion planning runs. SimMPC runs on the current Warp device; on a +CUDA GPU every sim step replays a captured CUDA graph, and the CPU is much slower. + +## Basic SimMPC + +A `SimMPC` combines a `SimMPCConfig`, a planning simulator, and `ctrl_ref`. This drives a cart on a +slide joint from `x = 0` to `x = 0.3`: ```python # docs: hide @@ -41,7 +56,7 @@ for the host. import mujoco import numpy as np from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.sim import MjWarpSim from robokit.terms import SensorTask model = mujoco.MjModel.from_xml_string(""" @@ -61,58 +76,61 @@ data = mujoco.MjData(model) mujoco.mj_forward(model, data) steps = 100 -config = SimMPCConfig(num_samples=64, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=4) +config = SimMPCConfig(num_samples=64, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=4, ctrl_std=0.1) ctrl_ref = np.zeros((steps + config.horizon_steps, model.nu)) # a row for every step a horizon reaches sensor_ref = np.full((len(ctrl_ref), model.nsensordata), 0.3) -costs = [SensorTask(sensor_ref, weight={"x": 100.0})] -mpc = SimMPC(MjWarpSim(model, data), ctrl_ref, ctrl_std=np.full(model.nu, 0.1), costs=costs, config=config) -(rollout,), (plans,) = mpc.solve(steps) # one rollout and one plan list per instance +config.add(SensorTask(sensor_ref, weight={"x": 100.0})) +mpc = SimMPC(config, MjWarpSim(model, 1, data), ctrl_ref) # plans on resized copies of this simulator +(rollout,), (plans,) = mpc.execute(MjWarpSim(model, 1, data), steps) # one rollout and one plan list per instance qpos = rollout["qpos"] # (steps, nq), row k is the state at sim step k # docs: hide assert qpos.shape == (steps, model.nq) and rollout["ctrl"].shape == (steps, model.nu) assert abs(qpos[-1, 0] - 0.3) < 0.05, qpos[-1, 0] # docs: endhide + +# or execute the commands yourself, here in MuJoCo on the CPU +mpc = SimMPC(config, MjWarpSim(model, 1, data), ctrl_ref) +for t0 in range(0, steps, config.ctrl_steps): + commands, infos = mpc.plan(data, t0) # (ctrl_steps, batch_size, nu); the plan then shifts by ctrl_steps + for command in commands.numpy()[:, 0]: + data.ctrl[:] = command + mujoco.mj_step(model, data) +# docs: hide +assert abs(data.qpos[0] - 0.3) < 0.05, data.qpos[0] +# docs: endhide ``` -`solve` returns, per instance, the executed world's `time`, `qpos`, `qvel` and `sensordata` at every sim step `k` -(row 0 is the initial state), the `ctrl` applied during step `k`, and one info dict per plan with its iterations and -costs. `ctrl_std` is the node noise per actuator at the first free node; it grows to `std_growth` times that at the -last. Controls are clipped to the actuator limits before execution, recording and cost evaluation. +`execute(sim, num_steps)` runs the closed loop on `sim` and returns each instance's executed `time`, +`qpos`, `qvel`, `sensordata` and `ctrl` at every sim step, plus one info dict per plan. `plan(data, t0)` +takes a simulator's `data` or one `mujoco.MjData`; `t0` indexes `ctrl_ref` and the references. -`SimMPCConfig` lists every setting. -`MjWarpSim` takes the MuJoCo-only settings: `cpu_execute=True` executes in MuJoCo on the CPU and plans on MuJoCo Warp, -`plan_ls_parallel` line-searches that many step sizes at once in rollouts, and `nconmax` and `njmax` size the -contact and constraint buffers. +`ctrl_std` sets each actuator's sampling noise, and `ctrl_range` bounds the commands (default: the +actuator ranges). SimMPC resizes the planning simulator into its worlds, so size its contact buffers +up front: `MjWarpSim(model, 1, data, nconmax=..., njmax=...)`. ## Costs -A cost is a `Task` whose `compute_weighted_cost(var_values, out_cost=out)` launches Warp kernels adding -each world's cost into `out` after a step. Its constructor takes arrays, numbers and names only; the binding fills -the `SimContext` values it reads (clock, `qpos`, `qvel`, `ctrl`, `sensordata`, body poses, contacts, and the model's -joints, sensors, bodies and geoms), and the planner resolves a copy for each world set. Row `k` of a reference -array describes sim step `k`. Stepping from `k` to `k + 1`, `StateTask` compares the new `qpos` with -`qpos_ref[k + 1]`, and `SensorTask` compares `sensordata`, which MuJoCo evaluates before integrating, with -`sensor_ref[k]`, so its rows line up with the `sensordata` that `solve` returns. +A cost is a `robokit.terms` task that reads the simulator's arrays after each step. Row `k` of a +reference array describes sim step `k`, matching the rows `execute` returns. | Term | Per step | | --- | --- | -| `StateTask(qpos_ref, qvel_ref, dof_weight)` | Norm of the weighted `qpos` error (free and ball joints by rotation) plus `vel_weight` times the `qvel` error; optional penetration and contact-schedule terms. `squared=True` squares the `qpos` term; `pose_tolerance` is a dead zone on free and ball-joint pose coordinates. | -| `SensorTask(sensor_ref, weight)` | `sum_s w_s * ‖sensordata_s - sensor_ref[k]_s‖²` over the named sensors; `norm=True` takes the unsquared norm instead. `weight` maps sensor names to a scalar or one value per component, or is a `(T, nsensordata)` array. `residual` selects `linear`, `angle`, `quaternion`, yaw or `heading` errors; `hinge=h` takes `max(cost_s - h, 0)` per sensor. | -| `ControlTask(weight, ctrl_ref)` | `sum(weight * (ctrl - ctrl_ref[k])²)` over the applied controls (`ctrl_ref` defaults to zero); `norm=True` takes `‖weight * (ctrl - ctrl_ref[k])‖` instead. | -| `AlignTask(origin, sensor, target_ref, weight)` | `weight * (1 + u·v / (‖u‖‖v‖))` with `u = sensor - origin` and `v = target_ref[k] - origin` over `components` (default x and y), for pushing an object toward a goal. | -| `ContactTask(geoms, target, radius, allowed, weight, penalty, margin)` | `-weight * clip(1 - dist, 0, 1)` for each contact of `geoms[i]` inside the disc `target[k, i]` of `radius[k, i]`, and `penalty` for a touch within `margin` outside every `allowed[k, i]` disc `(x, y, r)`. | -| `GraspTask(gripper, obj, offset, weight)` | `weight[k]` times the distance from body `gripper` to body `obj` plus `offset[k]`, in the object's frame unless `object_frame=False`, ignoring distances within `tolerance`. | - -A term's `terminal_scale`, unless None, replaces `SimMPCConfig.terminal_scale` for it at the horizon's last step -(0 drops it there). `StateTask`, `SensorTask` and `ControlTask` take `running_scale`; 0 with an explicit -`terminal_scale` makes a terminal-only cost. `freeze_reference=True` on `StateTask`, `SensorTask` or `AlignTask` -holds the target at the plan's start. - -A new cost subclasses `Task`: its constructor stores `SimContext` placeholders (e.g. -`self.qpos = SimContext.QPOS`) beside its own settings, `resolve` swaps them for the binding's arrays and builds any -device buffers, and `compute_weighted_cost` launches its kernels. Since terms read only `SimContext` values, they -can be checked without a simulator: +| `StateTask(qpos_ref, qvel_ref, dof_weight)` | Weighted `qpos` and `qvel` error to the reference. | +| `SensorTask(sensor_ref, weight)` | Weighted error of the named sensors to the reference. | +| `ControlTask(weight, ctrl_ref)` | Weighted squared deviation of the controls from `ctrl_ref`. | +| `AlignTask(origin, sensor, target_ref, weight)` | Pushes an object toward a goal. | +| `ContactTask(geoms, target, radius, allowed, weight, penalty, margin)` | Rewards contacts in target discs (or a `box` around each target, at a `height`); penalizes touches outside allowed ones. | +| `GraspTask(gripper, obj, offset, weight)` | Distance from a gripper body to an object body. | + +`config.add(term, running_scale=1.0, terminal_scale=None)` scales a term at every step and at the +horizon's last step; `running_scale=0` makes it terminal-only. + +### Custom Costs + +A new cost subclasses `Task`: its constructor stores `SimContext` placeholders, `resolve` swaps them +for the simulator's arrays, and `compute_weighted_cost` launches Warp kernels. Terms read only +`SimContext` values, so one can be checked without a simulator: ```python import numpy as np @@ -133,51 +151,32 @@ assert np.allclose(out.numpy(), [4.5, 1.0]) # docs: endhide ``` -Contacts exist only near a geom, so to reward a foot before it lands give `plan_model` geoms that detect far -contacts but push only at the usual distance. Before MuJoCo 3.10 contacts are detected within `margin` and push -within `margin - gap` (e.g. `margin="1" gap="0.999"`); from 3.10 they are detected within `margin + gap` and push -within `margin` (e.g. `margin="0.001" gap="0.999"`). `MjWarpSim`'s `plan_model` must match `model`'s `nq`, `nv`, -`nu` and `nsensordata`; rollouts step it and the executed world steps `model`. - -## Batches - -`SimMPCConfig.batch_size` plans several instances of one model at once, for example clips of one scene. Pass -`MjWarpSim` one `MjData` per instance, `ctrl_ref` as `(batch_size, T, nu)` (or `(T, nu)` to share it), and give a -term's reference arrays a leading instance axis (`qpos_ref` `(batch_size, T, nq)`); references without one are -shared. Rollout worlds are instance-major, `instance * num_samples * num_replicas + sample * num_replicas + -replica`, with one executed world per instance. Every instance keeps its own plan, sampler, temperature, mean -validation and executed state; they iterate together, and with `min_improvement` they stop once every instance has -stalled. `solve(num_steps)` also takes one length per instance: an instance plans while its next plan starts before -its length, and once the last active instance is `k - 1`, only the first `k` keep rollout worlds, so order the -instances longest first. `solve` returns one rollout and one plan list per instance, each as long as its instance ran. - -Instances whose scenes differ, such as one hand with a different object each, share one model: -`model, parameters = batch_models([mujoco.MjSpec.from_file(path) for path in scenes])` builds it from the instance -with the most geoms, adds the others' meshes, and returns each instance's geoms, inertias, sites and contact pairs -for `MjWarpSim(model, datas, instance_parameters=parameters)`. A geom an instance lacks never collides there (rays -and renders still see it), and geom ids follow the template. The scenes must share bodies, joints, actuators, sensors -and sites. +## Faster Planning -## Control Maps +The planning simulator may be cheaper than the executed one if `nq`, `nv`, `nu` and `nsensordata` +match: + +- `MjWarpSim.build_coarse_spec(spec, CoarseConfig(max_hull_vertices, qpos_ref))` caps each mesh's convex hull and + keeps only the contact pairs that come near along the motion. +- `config.stages` runs `SimMPCStage(iters, dt)` stages in order. `dt=[(0.25, None), (1.0, 0.04)]` steps + the first quarter of the horizon at the timestep and the rest at 40 ms. By default, SimMPC picks 4x or + 2x steps when their rollouts stay close to fine ones. -A `control_map(model, data, clock)` passed to `MjWarpSim` turns the sampled commands in `data.ctrl` into actuator -controls before every planning and execution step. `CartesianControl(model, body, ...)` reads the first six commands -as a world-frame twist of `body`, adds feedback toward `position_ref` and `q_wxyz_ref` with `position_gain` and -`rotation_gain`, and solves damped least squares for joint velocities. The scene needs scalar joint actuators that -take velocity commands. +Contacts exist only near a geom. To reward a foot before it lands, give the planning model geoms that +detect far but push at the usual distance: `margin="1" gap="0.999"` before MuJoCo 3.10, and +`margin="0.001" gap="0.999"` from 3.10. -## Randomized Planning +## Batch Planning -Set `num_replicas` to roll each draw out in several worlds and average their costs. `MjWarpSim`'s -`plan_parameters`, such as `{"geom_friction": friction}`, give each replica its own model values (a leading replica -dimension, after an instance one for values of each instance); execution keeps the original model. `initial_state_std={"qpos": ..., "qvel": ...}` adds Gaussian noise -to each replica's start state, shared by every draw and redrawn each iteration. +`SimMPCConfig.batch_size` plans several instances of one model at once, such as several clips of one +scene. Give `plan` one state per instance; `ctrl_ref` and reference arrays take a leading instance axis, +or are shared without one. Rollout worlds are instance-major. -## Simulator Bindings +Instances whose scenes differ, such as one hand with a different object each, plan on +`MjWarpSim(specs, [1] * batch_size)`. The scenes must share bodies, joints, actuators and sensors. + +## Control Maps -A binding implements `SimBinding`: `build` allocates the "rollout", "validation" and "execution" world sets, -`set_active_instances` rebuilds the rollout and validation sets for fewer instances, `context` returns a world set's -`SimContext` values, `reset` copies the executed states into a world set with replica noise, `set_time` sets its -clock, `step` maps, clips and applies the commands the planner wrote into `SimContext.CTRL`, and `read_execution` -returns the executed rows. `reset` and `step` launch device work only, so the -planner captures them in CUDA graphs. +`SimMPCConfig.control_map(sim, clock)` turns sampled commands into actuator controls before every step. +`CartesianControl(model, body, ...)` reads the first six commands as a world-frame twist of `body` and +solves damped least squares for joint velocities; the scene needs velocity actuators on scalar joints. diff --git a/docs/nav.yml b/docs/nav.yml index b901530..4fe7695 100644 --- a/docs/nav.yml +++ b/docs/nav.yml @@ -5,11 +5,11 @@ - {id: overview, file: guide/overview.md, nav: Overview} - {id: quickstart, file: guide/quickstart.md} - {id: install, file: guide/installation.md} + - {id: rl, file: guide/rl.md} + - {id: sim-mpc, file: guide/sim_mpc.md} - {id: ik, file: guide/ik.md} - {id: motion-planning, file: guide/motion_planning.md} - - {id: sim-mpc, file: guide/sim_mpc.md} - {id: humanoid-retargeting, file: guide/humanoid_retargeting.md} - - {id: full-body-retargeting, file: guide/full_body_retargeting.md} - {id: hand-retargeting, file: guide/hand_retargeting.md} - {id: hand_eye_calibration, file: guide/hand_eye_calibration.md} - {id: ref-assets, file: guide/assets.md} diff --git a/docs/reference/api/optimization.md b/docs/reference/api/optimization.md index 71cbc79..717bd2e 100644 --- a/docs/reference/api/optimization.md +++ b/docs/reference/api/optimization.md @@ -27,6 +27,7 @@ normal matrix. ::: robokit.opt.population_solver.PopulationSolver ::: robokit.opt.population_solver.PopulationSolverConfig +::: robokit.opt.population_solver.Stage ::: robokit.opt.sampler.SamplerConfig ::: robokit.opt.sampler.RobertsSamplerConfig diff --git a/docs/reference/api/sim_mpc.md b/docs/reference/api/sim_mpc.md index 45fd514..f76d55c 100644 --- a/docs/reference/api/sim_mpc.md +++ b/docs/reference/api/sim_mpc.md @@ -2,10 +2,11 @@ ::: robokit.helpers.sim_mpc.SimMPC ::: robokit.helpers.sim_mpc.SimMPCConfig -::: robokit.helpers.sim_mpc.SimBinding +::: robokit.helpers.sim_mpc.CartesianControl +::: robokit.helpers.sim_mpc.sim_context -::: robokit.helpers.sim_mpc.mjwarp.MjWarpSim -::: robokit.helpers.sim_mpc.mjwarp.CartesianControl +::: robokit.sim.Sim +::: robokit.sim.MjWarpSim ::: robokit.terms.SimContext ::: robokit.terms.StateTask diff --git a/docs/reference/opt/gd.md b/docs/reference/opt/gd.md index be4227b..3d966ca 100644 --- a/docs/reference/opt/gd.md +++ b/docs/reference/opt/gd.md @@ -20,15 +20,12 @@ $$ ## Adam / AdamW -AdamW is Adam with `weight_decay` > 0. Under either update rule, `gradient_clip` clamps each entry of -$g_t$ and `weight_decay` adds the decoupled decay below. +AdamW is Adam with `weight_decay` > 0. In GD and Adam, `gradient_clip` clamps each entry of +$g_t$, and `weight_decay` adds the decoupled decay below. -$m$ and $v$ are the first- and second-moment estimates, computed as exponential -moving averages of $g$ and $g^2$ with decay rates $\beta_1$ and $\beta_2$. -Because both are initialized to zero, their early estimates are pulled toward -zero. The corrected values $\widehat{m}_t$ and $\widehat{v}_t$ remove this -effect by dividing by the accumulated observation weights, $1-\beta_1^t$ and -$1-\beta_2^t$. +$m$ and $v$ are moving averages of $g$ and $g^2$, with decay rates $\beta_1$ and $\beta_2$. +Both start at zero, so early estimates lean toward zero. $\widehat{m}_t$ and $\widehat{v}_t$ +correct this by dividing by $1-\beta_1^t$ and $1-\beta_2^t$. $$ \begin{array}{l} diff --git a/docs/reference/opt/lbfgs.md b/docs/reference/opt/lbfgs.md index d19ccc2..2164054 100644 --- a/docs/reference/opt/lbfgs.md +++ b/docs/reference/opt/lbfgs.md @@ -5,13 +5,10 @@ on manifold-valued variables. Source: `src/robokit/opt/lbfgs_optimizer.py`. ## Overview -Starting from initial variable $\mathbf{x}$, L-BFGS computes its cost -$c(\mathbf{x})$ and gradient $\mathbf{g}=\nabla c(\mathbf{x})$. At each -iteration, it uses $\mathbf{g}$ and the history to compute a descent direction -$\mathbf{d}$. With no history, $\mathbf{d}$ follows $-\mathbf{g}$; the retained history -then adjusts that direction using observed curvature. The line search chooses -a step size $\alpha^*$, and the optimizer updates $\mathbf{x}$ by -$\alpha^*\mathbf{d}$. +For the variable $\mathbf{x}$, each iteration computes the cost $c(\mathbf{x})$ and gradient +$\mathbf{g}=\nabla c(\mathbf{x})$. $\mathbf{g}$ and the history give a descent direction +$\mathbf{d}$. With no history, $\mathbf{d}$ follows $-\mathbf{g}$. A line search picks a step +size $\alpha^*$, and $\mathbf{x}$ moves by $\alpha^*\mathbf{d}$. ```mermaid flowchart TB @@ -24,23 +21,19 @@ flowchart TB ## Descent direction -L-BFGS computes the descent direction $\mathbf{d}$ from the current gradient -$\mathbf{g}$ and a limited history of previous steps. At optimizer iteration -$t$, the update from $\mathbf{x}_t$ to $\mathbf{x}_{t+1}$ produces one history -pair: +The direction $\mathbf{d}$ comes from the gradient $\mathbf{g}$ and a short history of steps. +Iteration $t$, from $\mathbf{x}_t$ to $\mathbf{x}_{t+1}$, adds one history pair: -- $\mathbf{s}_t = \alpha_t^* \mathbf{d}_t$: the tangent-space update applied to - $\mathbf{x}_t$. -- $\mathbf{y}_t = \mathbf{g}_{t+1} - \mathbf{g}_t$: the gradient change caused - by $\mathbf{s}_t$. - In local coordinates, the first-order Taylor expansion of the gradient is +- $\mathbf{s}_t = \alpha_t^* \mathbf{d}_t$: the tangent step applied to $\mathbf{x}_t$. +- $\mathbf{y}_t = \mathbf{g}_{t+1} - \mathbf{g}_t$: the gradient change from $\mathbf{s}_t$. + To first order, $$ \mathbf{g}(\mathbf{x}_t+\mathbf{s}_t) \approx \mathbf{g}(\mathbf{x}_t)+J_{\mathbf{g}}(\mathbf{x}_t)\mathbf{s}_t. $$ - Here, the gradient Jacobian is the cost Hessian, + The gradient Jacobian is the cost Hessian, $J_{\mathbf{g}}(\mathbf{x})=H(\mathbf{x})=\nabla^2 c(\mathbf{x})$, so $\mathbf{y}_t\approx H(\mathbf{x}_t)\mathbf{s}_t$. @@ -54,9 +47,8 @@ A\approx H(\mathbf{x})^{-1}, \mathbf{d}=-A\mathbf{g}. $$ -For the update below, $i$ indexes retained history pairs from oldest to newest. -Let $A_i$ be the approximation after incorporating $i$ pairs, with -$A_0=\gamma I$. BFGS incorporates pair $i$ using +Below, $i$ indexes the history pairs, oldest first. $A_i$ is the approximation after $i$ +pairs, with $A_0=\gamma I$. BFGS adds pair $i$ by $$ A_{i+1}=V_iA_iV_i^\top+\rho_i \mathbf{s}_i \mathbf{s}_i^\top, @@ -66,20 +58,18 @@ V_i=I-\rho_i \mathbf{s}_i \mathbf{y}_i^\top, \rho_i=\frac{1}{\mathbf{y}_i^\top \mathbf{s}_i}. $$ -The optimizer uses this update only when -$\mathbf{y}_i^\top\mathbf{s}_i>0$; otherwise, it discards the pair. For an -accepted pair, the update enforces $A_{i+1}\mathbf{y}_i=\mathbf{s}_i$ while -keeping $A_{i+1}$ symmetric and positive definite. +A pair is used only when $\mathbf{y}_i^\top\mathbf{s}_i>0$; otherwise it is dropped. The +update enforces $A_{i+1}\mathbf{y}_i=\mathbf{s}_i$ and keeps $A_{i+1}$ symmetric positive +definite.
Why does the update work? 1. Why does it enforce $A_{i+1}\mathbf{y}_i=\mathbf{s}_i$? -Because $\rho_i(\mathbf{y}_i^\top \mathbf{s}_i)=1$, +Since $\rho_i(\mathbf{y}_i^\top \mathbf{s}_i)=1$, $V_i^\top \mathbf{y}_i=\mathbf{y}_i-\rho_i\mathbf{y}_i -(\mathbf{y}_i^\top \mathbf{s}_i)=\mathbf{0}$. Substituting this into the update -gives +(\mathbf{y}_i^\top \mathbf{s}_i)=\mathbf{0}$. Substituting into the update gives $$ A_{i+1}\mathbf{y}_i @@ -89,9 +79,9 @@ A_{i+1}\mathbf{y}_i =\mathbf{s}_i. $$ -2. Why it stays symmetric and positive definite? +2. Why does it stay symmetric positive definite? -When $A_i$ is symmetric positive definite, both $V_iA_iV_i^\top$ and +Let $A_i$ be symmetric positive definite. Then $V_iA_iV_i^\top$ and $\rho_i\mathbf{s}_i\mathbf{s}_i^\top$ are symmetric. If $\mathbf{y}_i^\top\mathbf{s}_i>0$, then $\rho_i>0$, and for any nonzero $\mathbf{z}$, @@ -102,27 +92,22 @@ $$ +\rho_i(\mathbf{s}_i^\top \mathbf{z})^2>0. $$ -Thus, $A_{i+1}$ remains symmetric positive definite. +So $A_{i+1}$ stays symmetric positive definite.
-After incorporating all retained pairs, the resulting $A$ approximates -$H(\mathbf{x})^{-1}$ and gives the descent direction -$\mathbf{d}=-A\mathbf{g}$. Since only $A\mathbf{g}$ is needed, L-BFGS avoids -constructing the $n\times n$ matrix $A$ and instead uses the two-loop recursion -over $m$ history pairs. This requires $O(mn)$ memory and $O(mn)$ operations, -where $m\ll n$. +After all pairs, $A$ approximates $H(\mathbf{x})^{-1}$ and gives $\mathbf{d}=-A\mathbf{g}$. +L-BFGS never builds the $n\times n$ matrix $A$. A two-loop recursion over $m$ history pairs +computes $A\mathbf{g}$ in $O(mn)$ memory and $O(mn)$ operations, where $m\ll n$. -**Normalization.** `normalize_direction=False` preserves the direction's magnitude -by default. Set it to `True` to rescale the direction to unit length before the -line search. +**Normalization.** By default, `normalize_direction=False` keeps the direction's length. Set it +to `True` to scale the direction to unit length before the line search.
How does the matrix update become two loops? -The direction requires $A_m\mathbf{g}$, where $m$ is the number of retained -history pairs. Repeatedly expanding $A_m\mathbf{g}$ using the BFGS update rule -gives +The direction needs $A_m\mathbf{g}$, where $m$ is the number of history pairs. Expanding +$A_m\mathbf{g}$ with the BFGS update gives $$ \begin{aligned} @@ -145,11 +130,8 @@ V_{m-2}A_{m-2}(V_{m-2}^\top V_{m-1}^\top\mathbf{g}) \end{aligned} $$ -First, we want to compute this vector product -$V_0^\top\cdots V_{m-1}^\top\mathbf{g}$. For simplicity, define -$\mathbf{q}_0=V_0^\top\cdots V_{m-1}^\top\mathbf{g}$. - -Compute this product using the update rule from $\mathbf{q}_{i+1}$ to +The first loop computes the product $V_0^\top\cdots V_{m-1}^\top\mathbf{g}$. Define +$\mathbf{q}_0=V_0^\top\cdots V_{m-1}^\top\mathbf{g}$. Each step goes from $\mathbf{q}_{i+1}$ to $\mathbf{q}_i$: $$ @@ -159,14 +141,11 @@ $$ -\rho_i\mathbf{y}_i(\mathbf{s}_i^\top\mathbf{q}_{i+1}). $$ -Starting from $\mathbf{q}_m=\mathbf{g}$, the first loop applies this rule -backward from $i=m-1$ to $i=0$, producing $\mathbf{q}_0$. - -Second, we want to evaluate the remaining parts, starting from -$A_0\mathbf{q}_0$. For simplicity, define -$\mathbf{r}_0=A_0\mathbf{q}_0=\gamma\mathbf{q}_0$. +Starting from $\mathbf{q}_m=\mathbf{g}$, the loop runs backward from $i=m-1$ to $i=0$ and +yields $\mathbf{q}_0$. -Compute the remaining terms using the update rule from $\mathbf{r}_i$ to +The second loop evaluates the remaining terms, starting from $A_0\mathbf{q}_0$. Define +$\mathbf{r}_0=A_0\mathbf{q}_0=\gamma\mathbf{q}_0$. Each step goes from $\mathbf{r}_i$ to $\mathbf{r}_{i+1}$: $$ @@ -177,10 +156,10 @@ $$ (\mathbf{s}_i^\top\mathbf{q}_{i+1}-\mathbf{y}_i^\top\mathbf{r}_i). $$ -Starting from $\mathbf{r}_0$, the second loop applies this rule forward from -$i=0$ to $i=m-1$, producing $\mathbf{r}_m=A_m\mathbf{g}$. +Starting from $\mathbf{r}_0$, the loop runs forward from $i=0$ to $i=m-1$ and yields +$\mathbf{r}_m=A_m\mathbf{g}$. -The corresponding pseudocode: +Pseudocode: $$ \begin{array}{l} @@ -200,11 +179,10 @@ $$
-**Initial scale.** The starting approximation is $A_0=\gamma I$, where -$\gamma$ can be fixed. A common adaptive choice, -[Barzilai-Borwein scaling](https://en.wikipedia.org/wiki/Barzilai%E2%80%93Borwein_method), -uses the newest history pair $(\mathbf{s}_{m-1},\mathbf{y}_{m-1})$ and chooses -$\gamma$ so $\gamma\mathbf{y}_{m-1}$ best approximates $\mathbf{s}_{m-1}$: +**Initial scale.** The start is $A_0=\gamma I$, with $\gamma$ fixed or adaptive. +[Barzilai-Borwein scaling](https://en.wikipedia.org/wiki/Barzilai%E2%80%93Borwein_method) +picks $\gamma$ from the newest pair $(\mathbf{s}_{m-1},\mathbf{y}_{m-1})$, so +$\gamma\mathbf{y}_{m-1}$ best fits $\mathbf{s}_{m-1}$: $$ \gamma @@ -214,8 +192,7 @@ $$ ## Line search -The optimizer evaluates a predefined set of candidate step sizes $\alpha_j$ -together and selects +The line search tries a fixed set of step sizes $\alpha_j$ at once and picks $$ \alpha^* @@ -238,7 +215,6 @@ $$ Since $A$ is positive definite, $\mathbf{g}^\top A\mathbf{g}>0, \mathbf{g}^\top\mathbf{d}<0$. The [Armijo condition](https://en.wikipedia.org/wiki/Wolfe_conditions) $c(\mathbf{x}\oplus\alpha_j\mathbf{d})\le -c(\mathbf{x})+c_1\alpha_j\mathbf{g}^\top\mathbf{d}$ therefore requires the -actual decrease to be at least $c_1$ of the predicted first-order decrease. The -Armijo parameter $c_1$ defaults to $10^{-4}$; a larger value requires more -decrease. +c(\mathbf{x})+c_1\alpha_j\mathbf{g}^\top\mathbf{d}$ requires the actual decrease to be at least +$c_1$ of the predicted first-order decrease. $c_1$ defaults to $10^{-4}$; a larger value +requires more decrease. diff --git a/docs/reference/opt/lm.md b/docs/reference/opt/lm.md index 3dce1c1..7934903 100644 --- a/docs/reference/opt/lm.md +++ b/docs/reference/opt/lm.md @@ -7,16 +7,13 @@ on manifold-valued variables. Source: ## Overview -Starting from the current variable -$\mathbf{x}$, LM computes the residual vector $\mathbf{r}(\mathbf{x})$, the cost -$c(\mathbf{x})=\frac12\|\mathbf{r}(\mathbf{x})\|^2$, and the residual Jacobian -$J$. From these it computes a damped step $\boldsymbol{\delta}$ and applies it -to obtain a candidate $\widehat{\mathbf{x}}=\mathbf{x}\oplus\boldsymbol{\delta}$. -Since the step comes from an approximation of the cost near $\mathbf{x}$, the -candidate is not trusted directly: LM compares how much the cost actually -dropped with how much the approximation said it would drop. That comparison -decides whether $\widehat{\mathbf{x}}$ replaces $\mathbf{x}$ and whether the -damping $\lambda$ grows or shrinks. +For the variable $\mathbf{x}$, each iteration computes the residual vector +$\mathbf{r}(\mathbf{x})$, the cost $c(\mathbf{x})=\frac12\|\mathbf{r}(\mathbf{x})\|^2$ and the +residual Jacobian $J$. These give a damped step $\boldsymbol{\delta}$ and a candidate +$\widehat{\mathbf{x}}=\mathbf{x}\oplus\boldsymbol{\delta}$. The step comes from a model of the +cost near $\mathbf{x}$, so LM compares the actual cost drop with the predicted one. The +comparison decides whether $\widehat{\mathbf{x}}$ replaces $\mathbf{x}$ and whether the damping +$\lambda$ grows or shrinks. ```mermaid flowchart TB @@ -30,27 +27,25 @@ flowchart TB ## LM step **[Gauss-Newton](https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm).** -For the nonlinear least-squares cost -$c(\mathbf{x})=\frac12\|\mathbf{r}(\mathbf{x})\|^2$, the first-order Taylor -approximation under a tangent-space step $\boldsymbol{\delta}$ is +For the cost $c(\mathbf{x})=\frac12\|\mathbf{r}(\mathbf{x})\|^2$ and a tangent step +$\boldsymbol{\delta}$, to first order $\mathbf{r}(\mathbf{x}\oplus\boldsymbol{\delta})\approx \mathbf{r}(\mathbf{x})+J\boldsymbol{\delta}$. -This gives the Gauss-Newton subproblem $\min_{\boldsymbol{\delta}}\; +This gives the subproblem $\min_{\boldsymbol{\delta}}\; \frac12\|\mathbf{r}(\mathbf{x})+J\boldsymbol{\delta}\|^2$, with gradient -$J^\top(\mathbf{r}(\mathbf{x})+J\boldsymbol{\delta})$. Setting the gradient to zero yields -the normal equations +$J^\top(\mathbf{r}(\mathbf{x})+J\boldsymbol{\delta})$. Setting it to zero gives the normal +equations $$ J^\top J\boldsymbol{\delta}=-J^\top\mathbf{r}(\mathbf{x}). $$ -Gauss-Newton computes $\boldsymbol{\delta}$ by solving this linear system, -producing the candidate $\widehat{\mathbf{x}}= -\mathbf{x}\oplus\boldsymbol{\delta}$. (This can also be understood as a +Solving it for $\boldsymbol{\delta}$ gives the candidate $\widehat{\mathbf{x}}= +\mathbf{x}\oplus\boldsymbol{\delta}$. This is a [Newton-like step](https://en.wikipedia.org/wiki/Newton%27s_method_in_optimization): -$J^\top\mathbf{r}(\mathbf{x})=\nabla c(\mathbf{x})$, while -$J^\top J\approx H(\mathbf{x})=\nabla^2c(\mathbf{x})$.) +$J^\top\mathbf{r}(\mathbf{x})=\nabla c(\mathbf{x})$ and +$J^\top J\approx H(\mathbf{x})=\nabla^2c(\mathbf{x})$. **Levenberg-Marquardt.** LM adds a penalty for large steps: @@ -67,28 +62,18 @@ $$ =-J^\top\mathbf{r}(\mathbf{x}). $$ -A larger $\lambda$ therefore produces a more cautious step. The default -`linear_solver="cholesky"` solves this system exactly with batched Cholesky, -banded when the terms' sparsity allows; `"cg"` uses matrix-free conjugate -gradient, stopping once the residual falls below a tolerance or an iteration -cap derived from the tangent dimension is reached. +A larger $\lambda$ gives a smaller step. The default `linear_solver="cholesky"` solves this +system exactly. `"cg"` uses matrix-free conjugate gradient and stops at a tolerance or an +iteration cap. -`linear_solver="torch_cholesky"` optionally factors dense normal equations with -PyTorch/cuSolver in float64, then applies the float32 step through the same LM -acceptance rule. It requires PyTorch and runs eagerly; native Warp remains the -default. This is useful for wide coupled systems where native factorization -dominates runtime. It does not change the residuals or supply initial values. - -Normal accumulation tiles both residual rows and tangent columns when a full -normal block exceeds the shared-memory budget. Wide systems use the same -objective and Cholesky step without requiring a full normal matrix in one tile. -The accumulation tile loops remain dynamic to keep compilation bounded. +`linear_solver="torch_cholesky"` factors the dense normal equations with PyTorch in float64. It +needs PyTorch and runs eagerly. Use it for wide coupled systems where factorization dominates +runtime. ## [Trust region](https://en.wikipedia.org/wiki/Trust_region) -LM evaluates the candidate $\widehat{\mathbf{x}}$. The actual reduction is -$c(\mathbf{x})-c(\widehat{\mathbf{x}})$. The reduction predicted by the local -Gauss-Newton model is +At the candidate $\widehat{\mathbf{x}}$, the actual reduction is +$c(\mathbf{x})-c(\widehat{\mathbf{x}})$. The Gauss-Newton model predicts $$ \begin{aligned} @@ -100,28 +85,24 @@ $$ \end{aligned} $$ -For $\Delta c_{\mathrm{pred}}>0$, the gain ratio compares the actual and predicted -reductions: +For $\Delta c_{\mathrm{pred}}>0$, the gain ratio compares the two: $$ \rho=\frac{c(\mathbf{x})-c(\widehat{\mathbf{x}})} {\Delta c_{\mathrm{pred}}+\epsilon}. $$ -Here, $\epsilon\ge0$ is a small numerical stabilizer, with default $10^{-8}$; -$0$ uses the exact ratio. A $\rho$ near $1$ means the local model predicted the -cost reduction accurately. LM accepts the candidate exactly when +$\epsilon\ge0$ is a small stabilizer, $10^{-8}$ by default; $0$ gives the exact ratio. A +$\rho$ near $1$ means the model was accurate. LM accepts the candidate exactly when $$ \boxed{\text{accept}\iff \Delta c_{\mathrm{pred}}>0\ \land\ \rho\ge\rho_{\min}}. $$ -The default is $\rho_{\min}=10^{-3}$. With damping update factor $\nu>1$, -acceptance keeps $\widehat{\mathbf{x}}$ and sets -$\lambda\leftarrow\lambda/\nu$ (less damping, larger next step); rejection keeps -$\mathbf{x}$ and sets $\lambda\leftarrow\lambda\nu$ (more damping, smaller next -step). +The default is $\rho_{\min}=10^{-3}$. With damping factor $\nu>1$, acceptance keeps +$\widehat{\mathbf{x}}$ and sets $\lambda\leftarrow\lambda/\nu$ for a larger next step. +Rejection keeps $\mathbf{x}$ and sets $\lambda\leftarrow\lambda\nu$ for a smaller one. ## Algorithm diff --git a/docs/reference/terms/force_closure_task.md b/docs/reference/terms/force_closure_task.md index 830a60a..5ec6c68 100644 --- a/docs/reference/terms/force_closure_task.md +++ b/docs/reference/terms/force_closure_task.md @@ -16,7 +16,7 @@ $$ \in\mathbb{R}^6. $$ -`WarpScene` supplies unit surface normals and their analytical position Jacobians. Triangle face normals are held fixed within the selected face. Voxel normals differentiate the normalized trilinear SDF gradient; primitive normals differentiate their analytical geometry. Derivatives are discontinuous at face, voxel-cell, and closest-object switches. +`WarpScene` supplies unit surface normals and their position Jacobians. Mesh face normals are constant within a face. Derivatives jump where the closest face, voxel cell or object changes. ## Jacobian @@ -33,4 +33,4 @@ $$ \end{bmatrix}. $$ -For mesh face normals, $\mathbf{N}_i=0$ and this reduces to the frozen-normal torque Jacobian. Optional contact-force weights scale each contact's force and torque; residual weights scale the six output components. No finite-difference queries are used. +For mesh face normals, $\mathbf{N}_i=0$. Optional contact-force weights scale each contact's force and torque. Residual weights scale the six outputs. diff --git a/docs/reference/terms/frame_vector_task.md b/docs/reference/terms/frame_vector_task.md index 0debd1c..24f7d85 100644 --- a/docs/reference/terms/frame_vector_task.md +++ b/docs/reference/terms/frame_vector_task.md @@ -24,7 +24,7 @@ $$ \|\mathbf{d}^{\mathrm{cur}}_{w,i}\|. $$ -The plain residual is $\mathbf{e}_i$. Optional Huber and soft-gate settings transform and scale this error. +Optional Huber and soft-gate settings transform and scale $\mathbf{e}_i$. ## Jacobian diff --git a/docs/reference/terms/manipulability_task.md b/docs/reference/terms/manipulability_task.md index 8b00fd5..1967044 100644 --- a/docs/reference/terms/manipulability_task.md +++ b/docs/reference/terms/manipulability_task.md @@ -32,4 +32,4 @@ $$ \frac{\partial\det(\mathbf{A})}{\partial q_j}. $$ -The implementation differentiates every column of $\mathbf{J}^p_w$ analytically. Floating-base columns are left zero. +Every column of $\mathbf{J}^p_w$ is differentiated analytically. Floating-base columns are zero. diff --git a/docs/reference/terms/mask_alignment_task.md b/docs/reference/terms/mask_alignment_task.md index 846b62f..1c3952f 100644 --- a/docs/reference/terms/mask_alignment_task.md +++ b/docs/reference/terms/mask_alignment_task.md @@ -25,4 +25,4 @@ $$ \frac{\partial(u,v)}{\partial\boldsymbol{\xi}}. $$ -$\partial(u,v)/\partial\boldsymbol{\xi}$ is the derivative of the projected coordinates $(u,v)$ under the camera twist. For interior pixels, the code uses $\frac{\partial M^{\mathrm{cur}}}{\partial u}=\frac{M^{\mathrm{cur}}_{u+1,v}-M^{\mathrm{cur}}_{u-1,v}}{2}$ and $\frac{\partial M^{\mathrm{cur}}}{\partial v}=\frac{M^{\mathrm{cur}}_{u,v+1}-M^{\mathrm{cur}}_{u,v-1}}{2}$. The task sums $\mathbf{J}^\top\mathbf{J}$ and $\mathbf{J}^\top\mathbf{e}$ over pixels without storing $\mathbf{J}$. +$\partial(u,v)/\partial\boldsymbol{\xi}$ is how the projected pixel $(u,v)$ moves with the camera twist. Interior pixels use $\frac{\partial M^{\mathrm{cur}}}{\partial u}=\frac{M^{\mathrm{cur}}_{u+1,v}-M^{\mathrm{cur}}_{u-1,v}}{2}$ and $\frac{\partial M^{\mathrm{cur}}}{\partial v}=\frac{M^{\mathrm{cur}}_{u,v+1}-M^{\mathrm{cur}}_{u,v-1}}{2}$. The task sums $\mathbf{J}^\top\mathbf{J}$ and $\mathbf{J}^\top\mathbf{e}$ over pixels without storing $\mathbf{J}$. diff --git a/docs/reference/terms/position_limit.md b/docs/reference/terms/position_limit.md index f7b8b80..be4aeed 100644 --- a/docs/reference/terms/position_limit.md +++ b/docs/reference/terms/position_limit.md @@ -39,4 +39,4 @@ $$ \end{cases} $$ -The `sqrt_abs` derivative multiplies an active row by $1/(2\sqrt{e_i+\epsilon})$. The `exp_barrier` mode differentiates its expression directly. +`sqrt_abs` multiplies an active row by $1/(2\sqrt{e_i+\epsilon})$. `exp_barrier` differentiates its expression directly. diff --git a/docs/reference/terms/scene_collision_task.md b/docs/reference/terms/scene_collision_task.md index bb3fbbc..310d452 100644 --- a/docs/reference/terms/scene_collision_task.md +++ b/docs/reference/terms/scene_collision_task.md @@ -23,9 +23,9 @@ e_i= \mathbf{e}\in\mathbb{R}^N, $$ -The quadratic branch provides a smooth transition to zero at `margin`. Here, $N$ is the number of selected spheres and $\epsilon=10^{-6}$. +The quadratic branch reaches zero smoothly at `margin`. $N$ is the number of selected spheres and $\epsilon=10^{-6}$. -`plain` uses $e_i=\max(\mathtt{margin}-s_i,0)$, while `surface_distance` uses $e_i=|s_i|$ to pull the sphere toward contact. +`plain` uses $e_i=\max(\mathtt{margin}-s_i,0)$. `surface_distance` uses $e_i=|s_i|$ to pull the sphere toward contact. ## Jacobian @@ -44,7 +44,7 @@ $$ \mathbf{v}_{w,j}+\boldsymbol{\omega}_{w,j}\times\mathbf{c}_{w,i}. $$ -Using whichever world-frame scene normal $\mathbf{n}_{w,i}$ `WarpScene` returns: +With the world-frame scene normal $\mathbf{n}_{w,i}$ from `WarpScene`: $$ J_{ij} diff --git a/docs/reference/terms/scene_distance_task.md b/docs/reference/terms/scene_distance_task.md index a3ee53f..6b662b9 100644 --- a/docs/reference/terms/scene_distance_task.md +++ b/docs/reference/terms/scene_distance_task.md @@ -12,7 +12,7 @@ $$ It is zero on the scene surface and increases on either side. -`sqrt_abs` instead uses $e_i=\sqrt{|s_i|+\epsilon}$ to achieve L1 regularization. +`sqrt_abs` uses $e_i=\sqrt{|s_i|+\epsilon}$ for L1 regularization. ## Jacobian diff --git a/docs/reference/terms/smoothness_task.md b/docs/reference/terms/smoothness_task.md index 1371626..2c3b5d8 100644 --- a/docs/reference/terms/smoothness_task.md +++ b/docs/reference/terms/smoothness_task.md @@ -5,8 +5,7 @@ and `src/robokit/terms/sparse/trajectory_smoothness_task.py`. ## Dense -`SmoothnessTask` compares one configuration against the previous one. It is per-pose: -the previous state is supplied at construction, not read from a trajectory. +`SmoothnessTask` compares one configuration with the previous one, given at construction. ### Residual @@ -74,8 +73,8 @@ $$ \frac{c_j}{\Delta t^{\,p}}. $$ -Each row has $p+1$ nonzeros, all in the joint columns of the frames it spans. The base -columns stay zero for this joint block. +Each row has $p+1$ nonzeros, in the joint columns of the frames it spans. Base columns stay +zero. With `base_weight`, `order=1` also smooths consecutive floating-base transforms: diff --git a/pyproject.toml b/pyproject.toml index 57343d6..dbaa5f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "robokit" -version = "1.0.0rc1" +version = "1.0.0" authors = [{ name = "RoboKit Organization", email = "jianglong.yeh@gmail.com" }] description = "RoboKit is a high-performance, general-purpose toolkit for versatile robotic tasks." readme = "README.md" @@ -90,7 +90,7 @@ robokit = [ [tool.ruff] line-length = 120 -extend-exclude = ["ref"] # untracked reference checkouts; never format or lint them +extend-exclude = ["ref", "media_*"] # untracked reference checkouts and the bpy render code (own env) [tool.ruff.lint] select = [ @@ -131,7 +131,7 @@ lines-after-imports = 2 [tool.pytest.ini_options] addopts = "--durations=10" pythonpath = ["."] -norecursedirs = ["scripts", ".worktrees", "ref", "runs"] +norecursedirs = ["scripts", ".worktrees", "ref", "runs", "media_*"] markers = ["torch: requires PyTorch", "slow: long-running; skipped on PRs and by make ci, run on main/weekly"] [[tool.uv.index]] diff --git a/scripts/benchmark/hand_retargeting_online/dex_wrapper.py b/scripts/benchmark/hand_retargeting_online/dex_wrapper.py index 7716128..50569fd 100644 --- a/scripts/benchmark/hand_retargeting_online/dex_wrapper.py +++ b/scripts/benchmark/hand_retargeting_online/dex_wrapper.py @@ -1,11 +1,10 @@ # ruff: noqa: E402, I001 """Dex-retargeting wrapper: keypoints -> (qpos, per-frame times, joint names). -Supports two variants: +Supports three variants: - "position": the stock position retargeting config with a dummy floating base. - "vector": the stock vector retargeting config (4 wrist->fingertip pairs). -- "dexpilot": the DexPilot formulation (adds fingertip<->fingertip pair terms with - projection/gating for better pinch behavior). +- "dexpilot": the DexPilot formulation (adds fingertip<->fingertip pair terms with projection/gating for better pinch behavior). """ import enum diff --git a/scripts/benchmark/humanoid_retargeting/run_benchmark.py b/scripts/benchmark/humanoid_retargeting/run_benchmark.py index 84816b3..1c0e6c0 100644 --- a/scripts/benchmark/humanoid_retargeting/run_benchmark.py +++ b/scripts/benchmark/humanoid_retargeting/run_benchmark.py @@ -20,8 +20,7 @@ Evaluation: 1. Solve each sequence `num_runs` times; score the final run using our G1 URDF. -2. Compare 8 limb-link FK positions with the human, scaled by the robot/human leg-length ratio: relative to the pelvis - (MPJPE), and in the world after one similarity alignment per 100-frame segment (WA-MPJPE, as in WHAM and GVHMR). +2. Compare 8 limb-link FK positions with the human, scaled by the robot/human leg-length ratio: relative to the pelvis (MPJPE), and in the world after one similarity alignment per 100-frame segment (WA-MPJPE, as in WHAM and GVHMR). 3. Measure URDF joint-limit violations and joint acceleration. 4. Save joints and scores in outputs/ for inspect_cases.py. diff --git a/scripts/benchmark/motion_plan/benchmark.py b/scripts/benchmark/motion_plan/benchmark.py index a414420..2bf95a1 100644 --- a/scripts/benchmark/motion_plan/benchmark.py +++ b/scripts/benchmark/motion_plan/benchmark.py @@ -32,18 +32,10 @@ """The motion-plan benchmark: RoboKit vs cuRobo on robometrics, one neutral judge, one results.csv. Protocol (fair): -- Both methods plan with cuRobo's Panda spheres (`curobo_collision_spheres.yaml`); fingers locked at the - judged opening (0.04 motion_benchmaker / 0.025 mpinets, matching cuRobo's lock_joints). -- RoboKit: public `offline_pose_lbfgs` preset, four candidates, with built-in collision retry timed inside the solve; - it plans and retimes under the judge's acceleration limit (15) and a jerk limit of 150, below the judge's 500. - cuRobo: official benchmark settings (20 attempts, graph fallback, TF32). -- Judge: cuRobo's own success test for EVERY method, on the returned trajectories: cuRobo FK + spheres - (franka.yml + spheres/franka_mesh.yml, buffer 0); every frame free of world collision (OBB world), - self-collision, joint limits (+0.2 rad as curobo_benchmark.py; sr_strict: none), velocity / - acceleration 15 / jerk 500 on cuRobo's 5-point derivatives; reach 5 mm, sin(angle/2) 0.05, - all on cuRobo's own 25 ms linear interpolation of the plan, as MotionGen decides. - Motion time drops cuRobo's padded still frames; jerk is cuRobo's central stencil (both match cuRobo exactly). - One row per config in results.csv, mean +/- std over --runs. +- Both methods plan with cuRobo's Panda spheres (`curobo_collision_spheres.yaml`); fingers locked at the judged opening (0.04 motion_benchmaker / 0.025 mpinets, matching cuRobo's lock_joints). +- RoboKit: public `offline_pose_lbfgs` preset, four candidates, with built-in collision retry timed inside the solve; it plans and retimes under the judge's acceleration limit (15) and a jerk limit of 150, below the judge's 500. +- cuRobo: official benchmark settings (20 attempts, graph fallback, TF32). +- Judge: cuRobo's own success test for EVERY method, on the returned trajectories: cuRobo FK + spheres (franka.yml + spheres/franka_mesh.yml, buffer 0); every frame free of world collision (OBB world), self-collision, joint limits (+0.2 rad as curobo_benchmark.py; sr_strict: none), velocity / acceleration 15 / jerk 500 on cuRobo's 5-point derivatives; reach 5 mm, sin(angle/2) 0.05, all on cuRobo's own 25 ms linear interpolation of the plan, as MotionGen decides. Motion time drops cuRobo's padded still frames; jerk is cuRobo's central stencil (both match cuRobo exactly). One row per config in results.csv, mean +/- std over --runs. Usage: uv run scripts/benchmark/motion_plan/benchmark.py --config robokit-primitive --gpu 0 @@ -630,8 +622,7 @@ def judge_trajectory( # --- configs ---------------------------------------------------------------- -# A config may add a "plugin" module for variants kept outside this file: prepare(cfg, datasets) -> datasets, -# solve(planner, problems, spec, cfg) -> (metrics, paths, extras), score(extra, q, jerk) -> passed, finish(cfg). +# A config may add a "plugin" module for variants kept outside this file: prepare(cfg, datasets) -> datasets, solve(planner, problems, spec, cfg) -> (metrics, paths, extras), score(extra, q, jerk) -> passed, finish(cfg). CONFIGS = { "robokit-primitive": {"backend": "robokit"}, "curobo-primitive": {"backend": "curobo"}, diff --git a/scripts/humanoid_retargeting/alignment/align.py b/scripts/humanoid_retargeting/alignment/align.py index b5e1aee..0956c58 100644 --- a/scripts/humanoid_retargeting/alignment/align.py +++ b/scripts/humanoid_retargeting/alignment/align.py @@ -3,9 +3,7 @@ Session: 1. Pick a pose; missing robot poses are seeded by IK. 2. Match it with joint sliders, "IK init", or "Mirror". -3. Read the match: target spheres and residual lines colored green (matched) to red - (off), a per-pose and a per-link error table, and limb-direction warnings that expose a - mismatched pair (the one error scales/offsets cannot absorb), +3. Read the match: target spheres and residual lines colored green (matched) to red (off), a per-pose and a per-link error table, and limb-direction warnings that expose a mismatched pair (the one error scales/offsets cannot absorb). 4. Save both Python alignment presets. Usage (from repo root; open the printed URL / SSH-forward the port): diff --git a/src/robokit/__init__.py b/src/robokit/__init__.py index d757205..6e16ab8 100644 --- a/src/robokit/__init__.py +++ b/src/robokit/__init__.py @@ -1,9 +1,16 @@ import logging +import os +import tempfile import rich from rich.logging import RichHandler +# --- CUDA: coredump mode avoids NVIDIA's multi-process, multi-stream CUDA graph fault (TensorRT#3633) ------- +os.environ.setdefault("CUDA_ENABLE_COREDUMP_ON_EXCEPTION", "1") +os.environ.setdefault("CUDA_ENABLE_LIGHTWEIGHT_COREDUMP", "1") +os.environ.setdefault("CUDA_COREDUMP_FILE", os.path.join(tempfile.gettempdir(), "robokit-cuda-%h-%p.nvcudmp")) + # --- logging --------------------------------------------------------------- rich.reconfigure(log_path=False) @@ -14,6 +21,6 @@ logger.addHandler(RichHandler(console=rich.get_console(), show_path=False, log_time_format="[%X]")) -__version__ = "1.0.0rc1" +__version__ = "1.0.0" __all__ = ["__version__"] diff --git a/src/robokit/assets/__init__.py b/src/robokit/assets/__init__.py index 88bf088..31e4cd2 100644 --- a/src/robokit/assets/__init__.py +++ b/src/robokit/assets/__init__.py @@ -1,6 +1,4 @@ -"""RoboKit asset access: import per-asset static paths for checked names; MANO/SMPL-X models remain local. - -The pinned `openrobokit/robokit` dataset has `robots/` and `datasets/` under three local roles: +"""RoboKit asset access: import per-asset static paths for checked names; MANO/SMPL-X models remain local. The pinned `openrobokit/robokit` dataset has `robots/` and `datasets/` under three local roles: - `assets/`: extension-preserving runtime paths created by `fetch`. - `hf_cache/`: Hugging Face-managed blobs and snapshots. @@ -22,7 +20,7 @@ ASSETS_DIR = ROBOKIT_HOME / "assets" HF_CACHE_DIR = ROBOKIT_HOME / "hf_cache" HF_REPO_DIR = ROBOKIT_HOME / "hf_repo" -REVISION = "6c7d94e4ace25a1ec674cce237ef90ff9c159f22" +REVISION = "045838f22292b6931f7bc7490959925b1495a77c" def fetch( @@ -31,9 +29,7 @@ def fetch( repo_id: str = HF_REPO_ID, home: Optional[Path] = None, ) -> Path: - """Fetch `patterns` at the pinned or supplied `revision` and return the asset root. - - Other HF dataset repos pass `repo_id`, a pinned `revision`, and their own `home` (default: `ROBOKIT_HOME`). + """Fetch `patterns` at the pinned or supplied `revision` and return the asset root. Other HF dataset repos pass `repo_id`, a pinned `revision`, and their own `home` (default: `ROBOKIT_HOME`). Fetch sequence: 1. Reuse completed local pattern sets without network access. @@ -45,9 +41,6 @@ def fetch( >>> d = fetch(["robots/collision_spheres/g1/**"]) # doctest: +SKIP >>> spheres = d / "robots/collision_spheres/g1/collision_spheres.yaml" # doctest: +SKIP """ - from filelock import FileLock - from huggingface_hub import HfApi, snapshot_download - if patterns and any(p == "body_models" or p.startswith("body_models/") for p in patterns): raise ValueError( "Body models are user-provided, not fetched from HF. Use robokit.smplx.load_mano/load_smplx " @@ -59,8 +52,11 @@ def fetch( local = assets_dir / revision key = hashlib.sha1("\n".join(sorted(patterns) if patterns else ["(all)"]).encode()).hexdigest() marker = local / ".done" / key - if marker.exists(): + if marker.exists(): # the warm path: no Hub imports (~0.2 s a process) return local + from filelock import FileLock + from huggingface_hub import HfApi, snapshot_download + lock = assets_dir / ".locks" / revision lock.parent.mkdir(parents=True, exist_ok=True) with FileLock(lock): diff --git a/src/robokit/assets/datasets/nist_assembly.py b/src/robokit/assets/datasets/nist_assembly.py new file mode 100644 index 0000000..e59a46d --- /dev/null +++ b/src/robokit/assets/datasets/nist_assembly.py @@ -0,0 +1,8 @@ +"""NIST Assembly Task Board 1 assets from AssembleNIST: six task scenes, point tables and reset banks.""" + +from pathlib import Path + +from robokit.assets import fetch + + +DIR: Path = fetch(["datasets/nist_assembly/**"]) / "datasets/nist_assembly" diff --git a/src/robokit/assets/robots/arms/yam.py b/src/robokit/assets/robots/arms/yam.py index cc5365e..d62347b 100644 --- a/src/robokit/assets/robots/arms/yam.py +++ b/src/robokit/assets/robots/arms/yam.py @@ -15,6 +15,8 @@ ] ) URDF_PATH: Path = _DIR / "robots/robot_description/arms/yam/yam.urdf" +_MJ_DIR = "robots/robot_mj_description/arms/yam" +MJCF_PATH: Path = fetch([f"{_MJ_DIR}/**"]) / f"{_MJ_DIR}/yam.xml" COLLISION_SPHERE_PATH: Path = _DIR / "robots/collision_spheres/yam/collision_spheres.yaml" CAPSULE_SELF_COLLISION_IGNORE_PATH: Path = _DIR / "robots/self_collision/yam/ignore.capsule.yml" SPHERE_SELF_COLLISION_IGNORE_PATH: Path = _DIR / "robots/self_collision/yam/ignore.sphere.yml" diff --git a/src/robokit/assets/robots/assembly/composed.py b/src/robokit/assets/robots/assembly/composed.py index 3386346..7eff2b0 100644 --- a/src/robokit/assets/robots/assembly/composed.py +++ b/src/robokit/assets/robots/assembly/composed.py @@ -1,8 +1,4 @@ -"""Any base (arm or humanoid) with any end effector, assembled at runtime and cached per asset revision. - -`BASES` and `EES` name the parts that can be mounted; `assemble(base, ee)` builds the URDF and merged collision -spheres of one pair once and caches them under `ASSEMBLY_DIR`. -""" +"""Any base (arm or humanoid) with any end effector, assembled at runtime and cached per asset revision. `BASES` and `EES` name the parts that can be mounted; `assemble(base, ee)` builds the URDF and merged collision spheres of one pair once and caches them under `ASSEMBLY_DIR`.""" from dataclasses import dataclass from functools import lru_cache @@ -88,16 +84,7 @@ class Part: @lru_cache(maxsize=None) def assemble(base: str, ee: str) -> Tuple[Path, Optional[Path], str]: - """Assemble `base` + `ee` into a cached URDF plus merged collision spheres; returns them and the ee root link. - - The rotation comes from the two mount specs. The offset comes from their mount points; a part that declares - none gets one from its mount-link mesh, pushed out so nothing sits behind the flange. - - The ee hangs off the base by its ROOT link, not its mount link: a floating grasp is a pose of the hand URDF's - root, so the root is the link IK has to aim, and for the hands whose root sits above the mount link (xhand, - ability, leap, orca, schunk) the two frames differ by a rotation, an offset, or both. Folding `T_root_mount` - into the mount joint leaves the mount link exactly where the mount specs put it. - """ + """Assemble `base` + `ee` into a cached URDF plus merged collision spheres; returns them and the ee root link. The rotation comes from the two mount specs. The offset comes from their mount points; a part that declares none gets one from its mount-link mesh, pushed out so nothing sits behind the flange. The ee hangs off the base by its ROOT link, not its mount link: a floating grasp is a pose of the hand URDF's root, so the root is the link IK has to aim, and for the hands whose root sits above the mount link (xhand, ability, leap, orca, schunk) the two frames differ by a rotation, an offset, or both. Folding `T_root_mount` into the mount joint leaves the mount link exactly where the mount specs put it.""" base_part, ee_part = BASES[base], EES[ee] out_dir = ASSEMBLY_DIR / f"{base}_{ee}" urdf = out_dir / f"{base}_{ee}.urdf" diff --git a/src/robokit/assets/robots/end_effectors/sharpa_hand.py b/src/robokit/assets/robots/end_effectors/sharpa_hand.py index 5e63510..ab9e2e3 100644 --- a/src/robokit/assets/robots/end_effectors/sharpa_hand.py +++ b/src/robokit/assets/robots/end_effectors/sharpa_hand.py @@ -23,6 +23,9 @@ URDF_PATH_LEFT: Path = _DIR / "robots/robot_description/end_effectors/sharpa_hand/left_sharpa_wave.urdf" MJCF_PATH_RIGHT: Path = _DIR / "robots/robot_mj_description/end_effectors/sharpa_hand/right_hand.xml" MJCF_PATH_LEFT: Path = _DIR / "robots/robot_mj_description/end_effectors/sharpa_hand/left_hand.xml" +# the same hands with the finger collision capsules and cylinders refit to the visual meshes (see its CHANGELOG) +MJCF_PATH_RIGHT_FIT: Path = _DIR / "robots/robot_mj_description/end_effectors/sharpa_hand/right_hand_fit.xml" +MJCF_PATH_LEFT_FIT: Path = _DIR / "robots/robot_mj_description/end_effectors/sharpa_hand/left_hand_fit.xml" COLLISION_SPHERE_PATH_RIGHT: Path = _DIR / "robots/collision_spheres/sharpa_hand_right/collision_spheres.yaml" COLLISION_SPHERE_PATH_LEFT: Path = _DIR / "robots/collision_spheres/sharpa_hand_left/collision_spheres.yaml" CONTACT_POINTS_DIR_RIGHT: Path = _DIR / "robots/contact_points/sharpa_hand_right" diff --git a/src/robokit/assets/robots/end_effectors/wuji_hand.py b/src/robokit/assets/robots/end_effectors/wuji_hand.py new file mode 100644 index 0000000..dd8f90c --- /dev/null +++ b/src/robokit/assets/robots/end_effectors/wuji_hand.py @@ -0,0 +1,43 @@ +"""Wuji Hand 1 assets (Wuji Technology, MIT): the URDF and MJCF of the same release; Hand 2.2 is `wuji_hand_2_2`.""" + +from pathlib import Path +from typing import Dict + +from robokit.assets import fetch +from robokit.utils.ee_coord_utils import HandCoordinateSpec + + +_DIR = fetch( + [ + "robots/robot_description/end_effectors/wuji_hand/**", + "robots/robot_mj_description/end_effectors/wuji_hand/**", + "robots/collision_spheres/wuji_hand_right/**", + "robots/collision_spheres/wuji_hand_left/**", + "robots/contact_points/wuji_hand_right/**", + "robots/contact_points/wuji_hand_left/**", + "robots/self_collision/wuji_hand_right/**", + "robots/self_collision/wuji_hand_left/**", + ] +) +URDF_PATH_RIGHT: Path = _DIR / "robots/robot_description/end_effectors/wuji_hand/wuji_hand_right.urdf" +URDF_PATH_LEFT: Path = _DIR / "robots/robot_description/end_effectors/wuji_hand/wuji_hand_left.urdf" +MJCF_PATH_RIGHT: Path = _DIR / "robots/robot_mj_description/end_effectors/wuji_hand/wuji_hand_right.xml" +MJCF_PATH_LEFT: Path = _DIR / "robots/robot_mj_description/end_effectors/wuji_hand/wuji_hand_left.xml" +COLLISION_SPHERE_PATH_RIGHT: Path = _DIR / "robots/collision_spheres/wuji_hand_right/collision_spheres.yaml" +COLLISION_SPHERE_PATH_LEFT: Path = _DIR / "robots/collision_spheres/wuji_hand_left/collision_spheres.yaml" +CONTACT_POINTS_PATH_RIGHT: Path = _DIR / "robots/contact_points/wuji_hand_right/contact_points.json" +CONTACT_POINTS_PATH_LEFT: Path = _DIR / "robots/contact_points/wuji_hand_left/contact_points.json" +SPHERE_SELF_COLLISION_IGNORE_PATH_RIGHT: Path = _DIR / "robots/self_collision/wuji_hand_right/ignore.sphere.yml" +SPHERE_SELF_COLLISION_IGNORE_PATH_LEFT: Path = _DIR / "robots/self_collision/wuji_hand_left/ignore.sphere.yml" +CAPSULE_SELF_COLLISION_IGNORE_PATH_RIGHT: Path = _DIR / "robots/self_collision/wuji_hand_right/ignore.capsule.yml" +CAPSULE_SELF_COLLISION_IGNORE_PATH_LEFT: Path = _DIR / "robots/self_collision/wuji_hand_left/ignore.capsule.yml" +MOUNT_LINK_NAME_RIGHT: str = "right_palm_link" +MOUNT_LINK_NAME_LEFT: str = "left_palm_link" +EE_COORD_SPEC_RIGHT = HandCoordinateSpec(palm_forward_axis="x", four_fingers_up_axis="z") +EE_COORD_SPEC_LEFT = HandCoordinateSpec(palm_forward_axis="x", four_fingers_up_axis="z") +MOUNT_COORD_SPEC_RIGHT = EE_COORD_SPEC_RIGHT.mount_spec +MOUNT_COORD_SPEC_LEFT = EE_COORD_SPEC_LEFT.mount_spec +# finger 1 is the thumb; joints 1-4 run from the palm out, and the thumb's first joint cannot reach 0 +REST_Q_RIGHT: Dict[str, float] = {f"right_finger{i}_joint{j}": 0.0 for i in range(1, 6) for j in range(1, 5)} +REST_Q_RIGHT["right_finger1_joint1"] = 0.0475 +REST_Q_LEFT: Dict[str, float] = {name.replace("right_", "left_", 1): value for name, value in REST_Q_RIGHT.items()} diff --git a/src/robokit/assets/robots/end_effectors/wuji_hand_2_2.py b/src/robokit/assets/robots/end_effectors/wuji_hand_2_2.py new file mode 100644 index 0000000..3aeab0d --- /dev/null +++ b/src/robokit/assets/robots/end_effectors/wuji_hand_2_2.py @@ -0,0 +1,49 @@ +"""Wuji Hand 2.2 assets (Wuji Technology, MIT): Hand 2.1 plus a tactile pad link on each fingertip; Hand 1 is `wuji_hand`.""" + +from pathlib import Path +from typing import Dict + +from robokit.assets import fetch +from robokit.utils.ee_coord_utils import HandCoordinateSpec + + +_DIR = fetch( + [ + "robots/robot_description/end_effectors/wuji_hand_2_2/**", + "robots/robot_mj_description/end_effectors/wuji_hand_2_2/**", + "robots/collision_spheres/wuji_hand_2_2_right/**", + "robots/collision_spheres/wuji_hand_2_2_left/**", + "robots/contact_points/wuji_hand_2_2_right/**", + "robots/contact_points/wuji_hand_2_2_left/**", + "robots/self_collision/wuji_hand_2_2_right/**", + "robots/self_collision/wuji_hand_2_2_left/**", + ] +) +URDF_PATH_RIGHT: Path = _DIR / "robots/robot_description/end_effectors/wuji_hand_2_2/wuji_hand_2_2_right.urdf" +URDF_PATH_LEFT: Path = _DIR / "robots/robot_description/end_effectors/wuji_hand_2_2/wuji_hand_2_2_left.urdf" +MJCF_PATH_RIGHT: Path = _DIR / "robots/robot_mj_description/end_effectors/wuji_hand_2_2/wuji_hand_2_2_right.xml" +MJCF_PATH_LEFT: Path = _DIR / "robots/robot_mj_description/end_effectors/wuji_hand_2_2/wuji_hand_2_2_left.xml" +COLLISION_SPHERE_PATH_RIGHT: Path = _DIR / "robots/collision_spheres/wuji_hand_2_2_right/collision_spheres.yaml" +COLLISION_SPHERE_PATH_LEFT: Path = _DIR / "robots/collision_spheres/wuji_hand_2_2_left/collision_spheres.yaml" +CONTACT_POINTS_PATH_RIGHT: Path = _DIR / "robots/contact_points/wuji_hand_2_2_right/contact_points.json" +CONTACT_POINTS_PATH_LEFT: Path = _DIR / "robots/contact_points/wuji_hand_2_2_left/contact_points.json" +SPHERE_SELF_COLLISION_IGNORE_PATH_RIGHT: Path = _DIR / "robots/self_collision/wuji_hand_2_2_right/ignore.sphere.yml" +SPHERE_SELF_COLLISION_IGNORE_PATH_LEFT: Path = _DIR / "robots/self_collision/wuji_hand_2_2_left/ignore.sphere.yml" +CAPSULE_SELF_COLLISION_IGNORE_PATH_RIGHT: Path = _DIR / "robots/self_collision/wuji_hand_2_2_right/ignore.capsule.yml" +CAPSULE_SELF_COLLISION_IGNORE_PATH_LEFT: Path = _DIR / "robots/self_collision/wuji_hand_2_2_left/ignore.capsule.yml" +MOUNT_LINK_NAME_RIGHT: str = "r_mount" +MOUNT_LINK_NAME_LEFT: str = "l_mount" +EE_COORD_SPEC_RIGHT = HandCoordinateSpec(palm_forward_axis="y", four_fingers_up_axis="-z") +EE_COORD_SPEC_LEFT = HandCoordinateSpec(palm_forward_axis="-y", four_fingers_up_axis="-z") +MOUNT_COORD_SPEC_RIGHT = EE_COORD_SPEC_RIGHT.mount_spec +MOUNT_COORD_SPEC_LEFT = EE_COORD_SPEC_LEFT.mount_spec +REST_Q_RIGHT: Dict[str, float] = dict.fromkeys( + ["r_thumb_cmc_flex", "r_thumb_cmc_abd", "r_thumb_mcp", "r_thumb_ip"] + + [ + f"r_{finger}_{joint}" + for finger in ("index_finger", "middle_finger", "ring_finger", "pinky") + for joint in ("mcp_flex", "mcp_abd", "pip", "dip") + ], + 0.0, +) +REST_Q_LEFT: Dict[str, float] = {"l_" + name[2:]: value for name, value in REST_Q_RIGHT.items()} diff --git a/src/robokit/assets/robots/humanoids/booster_k1.py b/src/robokit/assets/robots/humanoids/booster_k1.py index 15695ef..c6618f5 100644 --- a/src/robokit/assets/robots/humanoids/booster_k1.py +++ b/src/robokit/assets/robots/humanoids/booster_k1.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/booster_k1/**", "robots/collision_spheres/booster_k1/**", "robots/self_collision/booster_k1/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/booster_k1/K1_serial.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/booster_k1/full_body.yaml" diff --git a/src/robokit/assets/robots/humanoids/booster_t1.py b/src/robokit/assets/robots/humanoids/booster_t1.py index a921f69..b623986 100644 --- a/src/robokit/assets/robots/humanoids/booster_t1.py +++ b/src/robokit/assets/robots/humanoids/booster_t1.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/booster_t1/**", "robots/collision_spheres/booster_t1/**", "robots/self_collision/booster_t1/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/booster_t1/booster_t1.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/booster_t1/full_body.yaml" diff --git a/src/robokit/assets/robots/humanoids/engineai_pm01.py b/src/robokit/assets/robots/humanoids/engineai_pm01.py index 95be8a1..0c7814b 100644 --- a/src/robokit/assets/robots/humanoids/engineai_pm01.py +++ b/src/robokit/assets/robots/humanoids/engineai_pm01.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/engineai_pm01/**", "robots/collision_spheres/engineai_pm01/**", "robots/self_collision/engineai_pm01/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/engineai_pm01/engineai_pm01.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/engineai_pm01/full_body.yaml" diff --git a/src/robokit/assets/robots/humanoids/pal_talos.py b/src/robokit/assets/robots/humanoids/pal_talos.py index 16676be..3d5fd31 100644 --- a/src/robokit/assets/robots/humanoids/pal_talos.py +++ b/src/robokit/assets/robots/humanoids/pal_talos.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/pal_talos/**", "robots/collision_spheres/pal_talos/**", "robots/self_collision/pal_talos/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/pal_talos/pal_talos.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/pal_talos/full_body.yaml" diff --git a/src/robokit/assets/robots/humanoids/pnd_adam_lite.py b/src/robokit/assets/robots/humanoids/pnd_adam_lite.py index d051c45..ba0ad7f 100644 --- a/src/robokit/assets/robots/humanoids/pnd_adam_lite.py +++ b/src/robokit/assets/robots/humanoids/pnd_adam_lite.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/pnd_adam_lite/**", "robots/collision_spheres/pnd_adam_lite/**", "robots/self_collision/pnd_adam_lite/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/pnd_adam_lite/pnd_adam_lite.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/pnd_adam_lite/full_body.yaml" diff --git a/src/robokit/assets/robots/humanoids/tienkung_lite.py b/src/robokit/assets/robots/humanoids/tienkung_lite.py index d245211..05118af 100644 --- a/src/robokit/assets/robots/humanoids/tienkung_lite.py +++ b/src/robokit/assets/robots/humanoids/tienkung_lite.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/tienkung_lite/**", "robots/collision_spheres/tienkung_lite/**", "robots/self_collision/tienkung_lite/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/tienkung_lite/tienkung_lite.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/tienkung_lite/full_body.yaml" diff --git a/src/robokit/assets/robots/humanoids/toddlerbot_2xc.py b/src/robokit/assets/robots/humanoids/toddlerbot_2xc.py index d7ff194..0408903 100644 --- a/src/robokit/assets/robots/humanoids/toddlerbot_2xc.py +++ b/src/robokit/assets/robots/humanoids/toddlerbot_2xc.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/toddlerbot_2xc/**", "robots/collision_spheres/toddlerbot_2xc/**", "robots/self_collision/toddlerbot_2xc/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/toddlerbot_2xc/toddlerbot_2xc.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/toddlerbot_2xc/full_body.yaml" diff --git a/src/robokit/assets/robots/humanoids/unitree_g1.py b/src/robokit/assets/robots/humanoids/unitree_g1.py index e5cc27c..7a4907a 100644 --- a/src/robokit/assets/robots/humanoids/unitree_g1.py +++ b/src/robokit/assets/robots/humanoids/unitree_g1.py @@ -18,6 +18,8 @@ _SPHERES = _DIR / "robots/collision_spheres/g1" URDF_PATH: Path = _MODEL / "g1_29dof.urdf" +_MJ_DIR = "robots/robot_mj_description/humanoids/g1" +MJCF_PATH: Path = fetch([f"{_MJ_DIR}/**"]) / f"{_MJ_DIR}/g1.xml" URDF_SPHEREHAND_PATH: Path = _MODEL / "g1_29dof_spherehand.urdf" COLLISION_SPHERE_PATH: Path = _SPHERES / "collision_spheres.yaml" diff --git a/src/robokit/assets/robots/humanoids/unitree_h1.py b/src/robokit/assets/robots/humanoids/unitree_h1.py index b023963..5e6bb87 100644 --- a/src/robokit/assets/robots/humanoids/unitree_h1.py +++ b/src/robokit/assets/robots/humanoids/unitree_h1.py @@ -12,8 +12,7 @@ "robots/robot_description/humanoids/unitree_h1/**", "robots/collision_spheres/unitree_h1/**", "robots/self_collision/unitree_h1/**", - ], - revision="dcbf429363f2bdf9ac69b56d6b7a3e8d42cd462c", + ] ) URDF_PATH: Path = _DIR / "robots/robot_description/humanoids/unitree_h1/unitree_h1.urdf" COLLISION_SPHERE_FULL_BODY_PATH: Path = _DIR / "robots/collision_spheres/unitree_h1/full_body.yaml" diff --git a/src/robokit/assets/robots/quadrupeds/__init__.py b/src/robokit/assets/robots/quadrupeds/__init__.py new file mode 100644 index 0000000..1326e74 --- /dev/null +++ b/src/robokit/assets/robots/quadrupeds/__init__.py @@ -0,0 +1 @@ +"""Quadruped asset modules.""" diff --git a/src/robokit/assets/robots/quadrupeds/unitree_go1.py b/src/robokit/assets/robots/quadrupeds/unitree_go1.py new file mode 100644 index 0000000..f33dc4c --- /dev/null +++ b/src/robokit/assets/robots/quadrupeds/unitree_go1.py @@ -0,0 +1,9 @@ +"""Unitree Go1 quadruped assets.""" + +from pathlib import Path + +from robokit.assets import fetch + + +_MJ_DIR = "robots/robot_mj_description/quadrupeds/go1" +MJCF_PATH: Path = fetch([f"{_MJ_DIR}/**"]) / f"{_MJ_DIR}/go1.xml" diff --git a/src/robokit/examples/grasp/01_basic.py b/src/robokit/examples/grasp/01_basic.py index 9b4f717..ff5fce9 100644 --- a/src/robokit/examples/grasp/01_basic.py +++ b/src/robokit/examples/grasp/01_basic.py @@ -15,7 +15,7 @@ from robokit.helpers.grasp import ContactSamplerConfig, ContactVar from robokit.lie.se3 import se3_to_matrix from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.var_values import VarKey, VarValues from robokit.robo.robot import Robot from robokit.robo.robot_spec import load_link_points @@ -121,11 +121,8 @@ def main(): solver = PopulationSolver( [terms], PopulationSolverConfig( - num_iters=64, - optimizer=LMOptimizerConfig(lm_lambda=1.0), + stages=[Stage(64, 1, LMOptimizerConfig(lm_lambda=1.0), sample_every=8)], samplers=[ContactSamplerConfig()], - sample_at=range(0, 64, 8), - num_candidates=[1], cuda_graph_mode="iter", ), device, diff --git a/src/robokit/examples/hand_eye_calibration/01_sim_rgb.py b/src/robokit/examples/hand_eye_calibration/01_sim_rgb.py index 0f4e6cd..938a5b1 100644 --- a/src/robokit/examples/hand_eye_calibration/01_sim_rgb.py +++ b/src/robokit/examples/hand_eye_calibration/01_sim_rgb.py @@ -47,7 +47,7 @@ def main(): ax.imshow(overlay) ax.set_title(label) ax.axis("off") - out_path = Path("results") / "01_sim_rgb.png" + out_path = Path("runs") / "01_sim_rgb.png" out_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(out_path, bbox_inches="tight") print(f"Overlay saved to {out_path}") diff --git a/src/robokit/examples/hand_eye_calibration/02_sim_mounted.py b/src/robokit/examples/hand_eye_calibration/02_sim_mounted.py index 31ceb34..b19f70b 100644 --- a/src/robokit/examples/hand_eye_calibration/02_sim_mounted.py +++ b/src/robokit/examples/hand_eye_calibration/02_sim_mounted.py @@ -49,7 +49,7 @@ def main(): ax.imshow(overlay) ax.set_title(label) ax.axis("off") - out_path = Path("results") / "02_sim_mounted.png" + out_path = Path("runs") / "02_sim_mounted.png" out_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(out_path, bbox_inches="tight") print(f"Overlay saved to {out_path}") diff --git a/src/robokit/examples/hand_eye_calibration/03_sim_depth.py b/src/robokit/examples/hand_eye_calibration/03_sim_depth.py index fb7301f..0f401a1 100644 --- a/src/robokit/examples/hand_eye_calibration/03_sim_depth.py +++ b/src/robokit/examples/hand_eye_calibration/03_sim_depth.py @@ -47,7 +47,7 @@ def main(): ax.imshow(overlay) ax.set_title(label) ax.axis("off") - out_path = Path("results") / "03_sim_depth.png" + out_path = Path("runs") / "03_sim_depth.png" out_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(out_path, bbox_inches="tight") print(f"Overlay saved to {out_path}") diff --git a/src/robokit/examples/hand_eye_calibration/04_real_xarm.py b/src/robokit/examples/hand_eye_calibration/04_real_xarm.py index 05c4097..74ec3ac 100644 --- a/src/robokit/examples/hand_eye_calibration/04_real_xarm.py +++ b/src/robokit/examples/hand_eye_calibration/04_real_xarm.py @@ -18,7 +18,7 @@ uv run src/robokit/examples/hand_eye_calibration/04_real_xarm.py \ --arm xarm6 \ --qpos-file path/to/xarm6_qpos.npy \ - --initial-camera-pose-file results/real_xarm6//initial_camera_pose_opencv.json + --initial-camera-pose-file runs/real_xarm6//initial_camera_pose_opencv.json """ import datetime @@ -186,7 +186,7 @@ class Args: xarm_ip: Optional[str] = None realsense_serial: Optional[str] = None output_dir: Optional[str] = None - """Override output dir. Defaults to results/real_.""" + """Override output dir. Defaults to runs/real_.""" run_id: str = field(default_factory=lambda: datetime.date.today().isoformat()) """Run subfolder under the output dir; defaults to YYYY-MM-DD, or accepts a custom rig/experiment tag.""" @@ -256,7 +256,7 @@ def capture(args: Args) -> dict: def main(args: Args): wp.init() - default_out = Path("results") / f"real_{args.arm}" + default_out = Path("runs") / f"real_{args.arm}" out_dir = (Path(args.output_dir) if args.output_dir else default_out) / args.run_id out_dir.mkdir(parents=True, exist_ok=True) @@ -399,9 +399,12 @@ def decide(stage: Stage, cache_paths: List[Path]) -> Tuple[bool, str]: ], solver=replace( HandEyeCalibratorConfig().solver, - num_iters=30 + 20 + 20 + 20 + 60, - select_at=[30, 30 + 20, 30 + 20 + 20, 30 + 20 + 20 + 20], - num_candidates=[64, 16, 8, 4, 1], + stages=[ + replace(stage, iters=iters, num_candidates=width) + for stage, iters, width in zip( + HandEyeCalibratorConfig().solver.stages, (30, 20, 20, 20, 60), (64, 16, 8, 4, 1) + ) + ], ), ), ) diff --git a/src/robokit/examples/hand_eye_calibration/05_sim_offsets.py b/src/robokit/examples/hand_eye_calibration/05_sim_offsets.py index 8436b38..3bf496c 100644 --- a/src/robokit/examples/hand_eye_calibration/05_sim_offsets.py +++ b/src/robokit/examples/hand_eye_calibration/05_sim_offsets.py @@ -23,10 +23,9 @@ # nvdiffrast = { index = "torch-packages-builder" } # /// # pyright: reportMissingImports=false -"""Fit camera extrinsics together with joint encoder bias or an arm/hand mount offset. +"""Fit camera extrinsics together with joint encoder bias or an arm/hand mount offset; both modes compare against camera-only fitting. -Run with CUDA: uv run src/robokit/examples/hand_eye_calibration/05_sim_offsets.py --offset joints -Use --offset mount for the xArm7+Inspire adapter. Both modes compare against camera-only fitting. +Run with CUDA: uv run src/robokit/examples/hand_eye_calibration/05_sim_offsets.py --offset joints; use --offset mount for the xArm7+Inspire adapter. """ from dataclasses import replace diff --git a/src/robokit/examples/hand_eye_calibration/06_sim_qpos.py b/src/robokit/examples/hand_eye_calibration/06_sim_qpos.py index e6dd988..4282a14 100644 --- a/src/robokit/examples/hand_eye_calibration/06_sim_qpos.py +++ b/src/robokit/examples/hand_eye_calibration/06_sim_qpos.py @@ -22,10 +22,9 @@ # torch = { index = "pytorch-cu126" } # nvdiffrast = { index = "torch-packages-builder" } # /// -"""Compare independent frame fits with a coupled trajectory from calibrated silhouettes. +"""Compare independent frame fits with a coupled trajectory from calibrated silhouettes; saves source/per-frame/trajectory masks and metrics under runs/hand_eye_calibration/. Run with CUDA: uv run src/robokit/examples/hand_eye_calibration/06_sim_qpos.py -Saves source/per-frame/trajectory masks and metrics under runs/hand_eye_calibration/. """ import json diff --git a/src/robokit/examples/hand_retargeting/07_batch_contact.py b/src/robokit/examples/hand_retargeting/07_batch_contact.py index e592379..92e36f0 100644 --- a/src/robokit/examples/hand_retargeting/07_batch_contact.py +++ b/src/robokit/examples/hand_retargeting/07_batch_contact.py @@ -176,7 +176,7 @@ def pad(name: str) -> np.ndarray: def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( - "--output-dir", type=Path, default=Path("results/dexycb"), help="NPZ output directory (default: %(default)s)" + "--output-dir", type=Path, default=Path("runs/dexycb"), help="NPZ output directory (default: %(default)s)" ) parser.add_argument("--batch-size", type=int, default=64, help="captures per solve") parser.add_argument("--limit", type=int, default=0, help="first N captures; zero processes all") diff --git a/src/robokit/examples/humanoid_retargeting/11_full_body_batch.py b/src/robokit/examples/humanoid_retargeting/11_full_body_batch.py index 341c866..2e07c34 100644 --- a/src/robokit/examples/humanoid_retargeting/11_full_body_batch.py +++ b/src/robokit/examples/humanoid_retargeting/11_full_body_batch.py @@ -55,7 +55,7 @@ def load_clip(path: Path) -> RetargetingPlayback: def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( - "--output-dir", type=Path, default=Path("results/parahome"), help="NPZ output directory (default: %(default)s)" + "--output-dir", type=Path, default=Path("runs/parahome"), help="NPZ output directory (default: %(default)s)" ) parser.add_argument("--batch-size", type=int, default=32, help="clips per solve (default: 32)") parser.add_argument("--limit", type=int, help="first N indexed clips (default: two batches); zero processes all") diff --git a/src/robokit/examples/ik/07_mimic_joints.py b/src/robokit/examples/ik/07_mimic_joints.py index b213a67..a45ff64 100644 --- a/src/robokit/examples/ik/07_mimic_joints.py +++ b/src/robokit/examples/ik/07_mimic_joints.py @@ -10,7 +10,7 @@ from robokit.helpers.ik import IKContext, IKSolver, IKSolverConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.robo import Robot from robokit.terms.dense.position_limit import PositionLimit from robokit.terms.dense.position_task import PositionTask @@ -31,10 +31,7 @@ def main(): config = ( IKSolverConfig( solver=PopulationSolverConfig( - num_iters=30, - num_candidates=[1], - optimizer=LMOptimizerConfig(lm_lambda=1.0), - cuda_graph_mode="full", + stages=[Stage(30, 1, LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="full" ), ) .add(PositionTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, weight=1.0)) diff --git a/src/robokit/examples/ik/10_humanoid.py b/src/robokit/examples/ik/10_humanoid.py index 07c4fc4..6e62e3d 100644 --- a/src/robokit/examples/ik/10_humanoid.py +++ b/src/robokit/examples/ik/10_humanoid.py @@ -10,7 +10,7 @@ from robokit.helpers.ik import IKContext, IKSolver, IKSolverConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.robo import Robot from robokit.terms.dense.com_position_task import ComPositionTask @@ -47,13 +47,10 @@ def main(): IKSolverConfig( enable_T_world_base=True, solver=PopulationSolverConfig( - num_iters=10 + 16, - select_at=[10, 10 + 16], - num_candidates=[64, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(10, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(16, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="full", ), diff --git a/src/robokit/examples/ik/13_pixel.py b/src/robokit/examples/ik/13_pixel.py index 46f3f0b..d8c7512 100644 --- a/src/robokit/examples/ik/13_pixel.py +++ b/src/robokit/examples/ik/13_pixel.py @@ -1,10 +1,4 @@ -"""Pixel IK example: the hand follows a path drawn in a fixed camera's image. - -The red target pixel moves once along the gray path on the camera's image plane ("Replay" runs it again). -`PixelTask` puts the hand origin (green) on the red ray from the camera through that pixel while `RotationTask` -keeps the hand pointing down; smoothness picks the depth along the ray. Untick "Use pixels" and the hand ignores -the path. -""" +"""Pixel IK example: the hand follows a path drawn in a fixed camera's image. The red target pixel moves once along the gray path on the camera's image plane ("Replay" runs it again). `PixelTask` puts the hand origin (green) on the red ray from the camera through that pixel while `RotationTask` keeps the hand pointing down; smoothness picks the depth along the ray. Untick "Use pixels" and the hand ignores the path.""" import time diff --git a/src/robokit/examples/motion_plan/08_humanoid_online.py b/src/robokit/examples/motion_plan/08_humanoid_online.py index a1c3979..0f380d7 100644 --- a/src/robokit/examples/motion_plan/08_humanoid_online.py +++ b/src/robokit/examples/motion_plan/08_humanoid_online.py @@ -1,12 +1,11 @@ -"""Track G1 hand goals while keeping feet planted; --solver mppi samples accelerations instead of using gradients.""" +"""Track G1 hand goals while keeping feet planted; MPPI samples accelerations around the planted stance.""" import time from copy import deepcopy -from typing import Literal, Sequence +from typing import Sequence import numpy as np import trimesh -import tyro import viser import warp as wp import yourdfpy @@ -59,7 +58,7 @@ def stand( return config -def main(solver: Literal["lbfgs", "mppi"] = "lbfgs"): +def main(): wp.init() device = "cuda:0" if wp.is_cuda_available() else "cpu" @@ -88,8 +87,7 @@ def main(solver: Literal["lbfgs", "mppi"] = "lbfgs"): ) # --- planner: the preset holds every humanoid task and weight; `stand` plants it at home --- - preset = presets.humanoid_online_mppi if solver == "mppi" else presets.humanoid_online_lbfgs - config = stand(preset, robot, FOOT_LINKS, home_q[0], home_base[0]) + config = stand(presets.humanoid_online_mppi, robot, FOOT_LINKS, home_q[0], home_base[0]) planner = MotionPlanner(config, robot, TARGET_LINKS, scene=scene, device=device) planner.warmup(1) @@ -143,4 +141,4 @@ def main(solver: Literal["lbfgs", "mppi"] = "lbfgs"): if __name__ == "__main__": - tyro.cli(main) + main() diff --git a/src/robokit/examples/motion_plan/10_waypoints.py b/src/robokit/examples/motion_plan/10_waypoints.py index f8231e4..3305467 100644 --- a/src/robokit/examples/motion_plan/10_waypoints.py +++ b/src/robokit/examples/motion_plan/10_waypoints.py @@ -53,14 +53,19 @@ def main( self_collision_ignore_path=franka_panda.SPHERE_SELF_COLLISION_IGNORE_PATH, ) # No scene obstacles, to focus on the ordered hard anchors; deterministic LM makes middle-anchor smoothing visible. - lm = cast(GradientTrajectoryOptimizerConfig, presets.offline_pose_lm.stages[0]).solver.optimizer + lm = cast(GradientTrajectoryOptimizerConfig, presets.offline_pose_lm.stages[0]).solver.stages[0].optimizer stage = cast(GradientTrajectoryOptimizerConfig, presets.offline_joint_lbfgs.stages[0]) config = dataclasses.replace( presets.offline_joint_lbfgs, cuda_graph="stages" if device != "cpu" else "none", init_sample_range=0, stages=( - dataclasses.replace(stage, solver=dataclasses.replace(stage.solver, num_candidates=[1], optimizer=lm)), + dataclasses.replace( + stage, + solver=dataclasses.replace( + stage.solver, stages=[dataclasses.replace(stage.solver.stages[0], num_candidates=1, optimizer=lm)] + ), + ), ), ) planner = MotionPlanner(config, robot, "panda_hand", device=device) diff --git a/src/robokit/examples/motion_plan/13_pc_depth.py b/src/robokit/examples/motion_plan/13_pc_depth.py index 0e0c031..fdbeb58 100644 --- a/src/robokit/examples/motion_plan/13_pc_depth.py +++ b/src/robokit/examples/motion_plan/13_pc_depth.py @@ -51,8 +51,7 @@ def _build_observations() -> Tuple[WarpScene, wp.mat33, List[Tuple[wp.array, wp. """Render four views: PC uses all four; depth uses the first for partial observation. Returns: - Ground-truth scene, camera intrinsics, and `(depth, world XYZ, T_world_camera)` views. - Depth and XYZ are GPU arrays in meters; camera axes are right, down, forward. + Ground-truth scene, camera intrinsics, and `(depth, world XYZ, T_world_camera)` views; depth and XYZ are GPU arrays in meters; camera axes are right, down, forward. """ box = trimesh.creation.box((0.08, 0.5, 0.4)).apply_translation((0.45, 0, 0.2)) mesh = wp.Mesh(wp.array(box.vertices, dtype=wp.vec3), wp.array(box.faces.ravel(), dtype=int)) diff --git a/src/robokit/examples/opt/01_rosenbrock.py b/src/robokit/examples/opt/01_rosenbrock.py index 9d725d6..233c38b 100644 --- a/src/robokit/examples/opt/01_rosenbrock.py +++ b/src/robokit/examples/opt/01_rosenbrock.py @@ -117,7 +117,7 @@ def record_path(_: int, values: VarValues, __: wp.array): plt.ylabel("y") plt.legend() plt.tight_layout() - out_path = Path("results") / "01_rosenbrock.png" + out_path = Path("runs") / "01_rosenbrock.png" out_path.parent.mkdir(parents=True, exist_ok=True) plt.savefig(out_path, dpi=150) plt.close() diff --git a/src/robokit/examples/opt/02_solvers.py b/src/robokit/examples/opt/02_solvers.py index f3f4bda..2efe1b6 100644 --- a/src/robokit/examples/opt/02_solvers.py +++ b/src/robokit/examples/opt/02_solvers.py @@ -7,7 +7,7 @@ import warp as wp -from robokit.opt import PopulationSolver, PopulationSolverConfig, VarValues, VectorVar +from robokit.opt import PopulationSolver, PopulationSolverConfig, Stage, VarValues, VectorVar from robokit.opt.gd_optimizer import AnnealedGDConfig, AnnealedGDOptimizer from robokit.opt.lbfgs_optimizer import LBFGSOptimizer, LBFGSOptimizerConfig from robokit.opt.lm_optimizer import LMOptimizer, LMOptimizerConfig @@ -99,9 +99,7 @@ def solve(name: str, iterations: int) -> float: ) solver = PopulationSolver( [[task]], - PopulationSolverConfig( - num_iters=iterations, num_candidates=[1], cuda_graph_mode="none", samplers=[sampler] - ), + PopulationSolverConfig(stages=[Stage(iterations)], cuda_graph_mode="none", samplers=[sampler]), device, ) else: diff --git a/src/robokit/examples/opt/03_multi_candidate.py b/src/robokit/examples/opt/03_multi_candidate.py index eeac788..0bd8f75 100644 --- a/src/robokit/examples/opt/03_multi_candidate.py +++ b/src/robokit/examples/opt/03_multi_candidate.py @@ -12,7 +12,7 @@ from robokit.opt import VarValues, VectorVar from robokit.opt.lbfgs_optimizer import LBFGSOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.terms.task import GradientTask, ResidualTask @@ -101,11 +101,9 @@ def main(): solver = PopulationSolver( terms=[[task]], config=PopulationSolverConfig( - num_iters=300, - num_candidates=[len(initial)], + stages=[Stage(300, len(initial), LBFGSOptimizerConfig(gradient_mode="analytic_gradient"))], cuda_graph_mode="none", use_early_stopping=False, - optimizer=LBFGSOptimizerConfig(gradient_mode="analytic_gradient"), ), device=wp.get_device("cuda"), ) @@ -142,7 +140,7 @@ def main(): plt.ylabel("y") plt.legend() plt.tight_layout() - out_path = Path("results") / "03_multi_candidate.png" + out_path = Path("runs") / "03_multi_candidate.png" out_path.parent.mkdir(parents=True, exist_ok=True) plt.savefig(out_path, dpi=150) plt.close() diff --git a/src/robokit/examples/opt/04_curve_fit.py b/src/robokit/examples/opt/04_curve_fit.py index 8d48662..c995208 100644 --- a/src/robokit/examples/opt/04_curve_fit.py +++ b/src/robokit/examples/opt/04_curve_fit.py @@ -120,7 +120,7 @@ def main(): plt.ylabel("y") plt.legend() plt.tight_layout() - out_path = Path("results") / "04_curve_fit.png" + out_path = Path("runs") / "04_curve_fit.png" out_path.parent.mkdir(parents=True, exist_ok=True) plt.savefig(out_path, dpi=150) plt.close() diff --git a/src/robokit/examples/opt/05_mpc_pendulum.py b/src/robokit/examples/opt/05_mpc_pendulum.py index 74699bd..0092ecf 100644 --- a/src/robokit/examples/opt/05_mpc_pendulum.py +++ b/src/robokit/examples/opt/05_mpc_pendulum.py @@ -10,7 +10,7 @@ from matplotlib.animation import FuncAnimation, PillowWriter from matplotlib.artist import Artist -from robokit.opt import PopulationSolver, PopulationSolverConfig, VarValues, VectorVar +from robokit.opt import PopulationSolver, PopulationSolverConfig, Stage, VarValues, VectorVar from robokit.opt.sampler import GaussianSampler, GaussianSamplerConfig from robokit.opt.var_values import VarKey from robokit.terms.task import Task @@ -64,7 +64,7 @@ def main(): solver = PopulationSolver( [task], # pyright: ignore[reportArgumentType] The solver also accepts cost-only Tasks. PopulationSolverConfig( - num_iters=4, + stages=[Stage(4)], cuda_graph_mode="none", use_early_stopping=False, samplers=[GaussianSamplerConfig(var_key=VarKey.ACTION, num_draws=512, init_std=STD, gamma=0.0, seed=seed)], @@ -121,7 +121,7 @@ def update(frame: int) -> Tuple[Artist, ...]: cursor.set_xdata([times[frame], times[frame]]) return rod, clock, *cursors - path = Path("results/05_mpc_pendulum.webp") + path = Path("runs/05_mpc_pendulum.webp") path.parent.mkdir(parents=True, exist_ok=True) fig.tight_layout() animation = FuncAnimation(fig, update, frames=len(states), interval=50) diff --git a/src/robokit/examples/opt/06_mpc_navigation.py b/src/robokit/examples/opt/06_mpc_navigation.py index 4450ed3..6f9f35c 100644 --- a/src/robokit/examples/opt/06_mpc_navigation.py +++ b/src/robokit/examples/opt/06_mpc_navigation.py @@ -11,7 +11,7 @@ from matplotlib.artist import Artist from matplotlib.patches import Circle -from robokit.opt import PopulationSolver, PopulationSolverConfig, VarValues, VectorVar +from robokit.opt import PopulationSolver, PopulationSolverConfig, Stage, VarValues, VectorVar from robokit.opt.sampler import GaussianSampler, GaussianSamplerConfig from robokit.opt.var_values import VarKey from robokit.terms.task import Task @@ -70,7 +70,7 @@ def main(): solver = PopulationSolver( [task], # pyright: ignore[reportArgumentType] The solver also accepts cost-only Tasks. PopulationSolverConfig( - num_iters=4, + stages=[Stage(4)], cuda_graph_mode="none", use_early_stopping=False, samplers=[GaussianSamplerConfig(var_key=VarKey.ACTION, num_draws=512, init_std=STD, gamma=0.0, seed=seed)], @@ -127,7 +127,7 @@ def update(frame: int) -> Tuple[Artist, ...]: ax.set_title(f"t = {frame * 0.1:.1f} s") return trajectory, robot, ax.title - path = Path("results/06_mpc_navigation.webp") + path = Path("runs/06_mpc_navigation.webp") path.parent.mkdir(parents=True, exist_ok=True) fig.tight_layout() animation = FuncAnimation(fig, update, frames=len(states), interval=100) diff --git a/src/robokit/examples/opt/07_ilqr_pendulum.py b/src/robokit/examples/opt/07_ilqr_pendulum.py new file mode 100644 index 0000000..ced77f2 --- /dev/null +++ b/src/robokit/examples/opt/07_ilqr_pendulum.py @@ -0,0 +1,121 @@ +# pyright: reportArgumentType=false, reportOperatorIssue=false +"""Pendulum swing-up with iLQR: optimize torques, execute one step, shift, repeat (as `05_mpc_pendulum.py` with MPPI).""" + +from pathlib import Path +from typing import Tuple, cast + +import matplotlib.pyplot as plt +import numpy as np +import warp as wp +from matplotlib.animation import FuncAnimation, PillowWriter +from matplotlib.artist import Artist + +from robokit.opt import VarValues, VectorVar +from robokit.opt.ilqr_optimizer import Dynamics, ILQROptimizer, ILQROptimizerConfig +from robokit.opt.var_values import Var, VarKey +from robokit.terms.task import ResidualTask + + +INITIAL = np.array([np.pi, 0.0], np.float32) +LIMIT = 2.0 + + +@wp.func +def _step_func(x: wp.vec2, u: float) -> wp.vec2: + # Angle zero is upright; unit mass/length, gravity 10, semi-implicit Euler. + velocity = wp.clamp(x[1] + 0.05 * (15.0 * wp.sin(x[0]) + 3.0 * u), -8.0, 8.0) + return wp.vec2(x[0] + 0.05 * velocity, velocity) + + +@wp.kernel +def _step_kernel(x: wp.array2d(dtype=float), u: wp.array2d(dtype=float), out: wp.array2d(dtype=float)): + i = wp.tid() + y = _step_func(wp.vec2(x[i, 0], x[i, 1]), u[i, 0]) + out[i, 0] = y[0] # pyright: ignore[reportIndexIssue] + out[i, 1] = y[1] # pyright: ignore[reportIndexIssue] + + +@wp.kernel +def _residual_kernel(x: wp.array2d(dtype=float), u: wp.array2d(dtype=float), o: int, r: wp.array2d(dtype=float)): + i = wp.tid() + r[i, o] = wp.sqrt(40.0) * wp.sin(0.5 * x[i, 0]) + r[i, o + 1] = wp.sqrt(0.2) * x[i, 1] + r[i, o + 2] = 0.2 * u[i, 0] + + +class Pendulum(Dynamics): + """States: `VectorVar`s of (angle, velocity); one bounded torque.""" + + def __init__(self): + super().__init__(nu=1, ctrl_range=np.array([[-LIMIT, LIMIT]])) + + def step(self, x: Var, u: wp.array, x_next: Var, finite_differences: bool = False): + ins = [cast(VectorVar, x).x, u] + wp.launch(_step_kernel, x.batch_size, inputs=ins, outputs=[cast(VectorVar, x_next).x], device=u.device) + + +class SwingUpCost(ResidualTask): + """Per step, `0.5 |r|^2 = 10 (1 - cos angle) + 0.1 velocity^2 + 0.02 torque^2`.""" + + @property + def residual_dim(self) -> int: + return 3 + + def compute_weighted_residual(self, var_values: VarValues, *, out_residual: wp.array, row_offset: int = 0): + x, u = (cast(VectorVar, var_values.get(key)).x for key in (VarKey.STATE, VarKey.ACTION)) + wp.launch(_residual_kernel, x.shape[0], inputs=[x, u, row_offset], outputs=[out_residual], device=x.device) + return out_residual + + +def main(): + device, steps = "cuda" if wp.is_cuda_available() else "cpu", 250 + optimizer = ILQROptimizer(Pendulum(), [SwingUpCost()], ILQROptimizerConfig(max_iter=2), device=device) + # 64 torques (3.2 s), starting with a push: hanging still, the cost has no gradient for iLQR to follow + plan = VectorVar(wp.full((1, 64), 0.5, device=device)) + state, states, controls = INITIAL.copy(), [INITIAL.copy()], [] + for step in range(steps): + optimizer.set_start(VectorVar(wp.array(state[None], dtype=float, device=device))) + optimizer.solve(plan, shift=None if step == 0 else 1.0) # then warm-started one step on + u = float(plan.x.numpy()[0, 0]) + state = np.array(_step_func(wp.vec2(*state), u), np.float32) + states.append(state.copy()) + controls.append(u) + states, controls = np.array(states), np.array(controls) + angle = np.arctan2(np.sin(states[:, 0]), np.cos(states[:, 0])) + assert np.max(np.abs(angle[-20:])) < 0.2 and np.max(np.abs(states[-20:, 1])) < 0.5 + assert np.max(np.abs(controls)) <= LIMIT + print(f"pendulum: angle={angle[-1]:.4f} velocity={states[-1, 1]:.4f} torque_max={np.abs(controls).max():.3f}") + plt.switch_backend("Agg") + fig, axes = plt.subplot_mosaic( + [["pendulum", "angle"], ["pendulum", "torque"]], figsize=(9, 4), gridspec_kw={"width_ratios": [1, 1.5]} + ) + axes["pendulum"].set(xlim=(-1.2, 1.2), ylim=(-1.2, 1.2), aspect="equal", xlabel="x (m)", ylabel="y (m)") + axes["pendulum"].plot([0, 0], [0, 1], "--", color="0.7", label="upright") + (rod,) = axes["pendulum"].plot([], [], "o-", linewidth=3, markersize=10) + clock = axes["pendulum"].set_title("") + times = np.arange(steps + 1) * 0.05 + axes["angle"].plot(times, angle) + axes["angle"].set_ylabel("angle from upright (rad)") + axes["torque"].sharex(axes["angle"]) + axes["torque"].step(times, np.r_[controls, controls[-1]], where="post") + axes["torque"].set(xlabel="time (s)", ylabel="torque (Nm)") + cursors = [axes[name].axvline(0, color="tab:red", alpha=0.7) for name in ("angle", "torque")] + + def update(frame: int) -> Tuple[Artist, ...]: + rod.set_data([0, np.sin(states[frame, 0])], [0, np.cos(states[frame, 0])]) + clock.set_text(f"t = {times[frame]:.2f} s") + for cursor in cursors: + cursor.set_xdata([times[frame], times[frame]]) + return rod, clock, *cursors + + path = Path("runs/07_ilqr_pendulum.webp") + path.parent.mkdir(parents=True, exist_ok=True) + fig.tight_layout() + animation = FuncAnimation(fig, update, frames=len(states), interval=50) + animation.save(path, writer=PillowWriter(fps=20)) + plt.close(fig) + print(f"saved=\n{path}") + + +if __name__ == "__main__": + main() diff --git a/src/robokit/examples/rl/01_joystick.py b/src/robokit/examples/rl/01_joystick.py new file mode 100644 index 0000000..ba3899b --- /dev/null +++ b/src/robokit/examples/rl/01_joystick.py @@ -0,0 +1,441 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Joystick: a Unitree Go1 or G1 learns to track twist commands on flat ground, on 4096 MuJoCo Warp worlds. + +Example usage: + uv run src/robokit/examples/rl/01_joystick.py go1 --minutes 1 # Go1 + uv run src/robokit/examples/rl/01_joystick.py g1 --minutes 4 # G1 + uv run src/robokit/examples/rl/01_joystick.py g1 --minutes 4 --energy 0.001 # G1, a smoother gait + uv run src/robokit/examples/rl/01_joystick.py go1 --coarse 0 # full physics throughout +""" + +import math +import re +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Dict, List, Literal, Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import mujoco_warp as mjw # pyright: ignore[reportMissingImports] +import numpy as np +import torch +import tyro + +from robokit.assets.robots.humanoids import unitree_g1 +from robokit.assets.robots.quadrupeds import unitree_go1 +from robokit.helpers.rl import Env, fastsac, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class JoystickConfig: + """The joystick task and its training: the robot, the worlds, the power penalty, the learner and its time.""" + + mjcf_path: Path # the robot's MJCF + impratio: float # solver impratio + cone: mujoco.mjtCone # friction cone + home: List[float] # initial qpos: the base's pose, then the joint angles + foot_contact_type: mujoco.mjtObj # the feet's terrain contacts are those of geoms or of body subtrees + foot_contacts: List[str] # their names + foot_sites: List[str] + imu_site: str # where the actor's base velocity is measured + torso: str # the body levelled by the upright reward, its center of mass randomized + foot_geoms: str # foot collision geoms, a pattern; their friction is randomized + foot_friction: List[Tuple[float, float]] # ranges: sliding uniform, torsional and rolling log-uniform + pose_std: Dict[str, Tuple[float, float, float]] # pose reward widths by joint name, rad: standing, walking, running + weights: Dict[str, float] = field(default_factory=dict) # extra reward weights + worlds: int = 4096 # MjWarpSim worlds + energy: float = 0.0 # the weight of the mechanical power penalty + algo: Literal["ppo", "fastsac"] = "ppo" # the learner + minutes: float = 1.0 # wall time to train, compilation included + coarse: float = 0.5 # the share of PPO's time that mixes in coarse physics (`coarse_physics`), less and less often + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + # Coarse physics (`CoarseConfig`): only the feet ("{feet}") and terrain collide, 20 ms steps + coarse_physics: CoarseConfig = CoarseConfig( + collide="robot/{feet}|(?!robot/).*", pyramidal=True, timestep=0.02, iterations=5, ls_iterations=10 + ) + + +GO1 = JoystickConfig( + mjcf_path=unitree_go1.MJCF_PATH, + impratio=10.0, + cone=mujoco.mjtCone.mjCONE_ELLIPTIC, + home=[0, 0, 0.278, 1, 0, 0, 0, *[0.1, 0.9, -1.8, -0.1, 0.9, -1.8] * 2], + foot_contact_type=mujoco.mjtObj.mjOBJ_GEOM, + foot_contacts=[f"{leg}_foot_collision" for leg in ("FR", "FL", "RR", "RL")], + foot_sites=["FR", "FL", "RR", "RL"], + imu_site="imu", + torso="trunk", + foot_geoms=r"(FR|FL|RR|RL)_foot_collision", + foot_friction=[(0.3, 1.5), (1e-4, 2e-2), (1e-5, 5e-3)], + pose_std=dict(hip=(0.05, 0.3, 0.3), thigh=(0.05, 0.3, 0.3), calf=(0.1, 0.6, 0.6)), +) +G1 = JoystickConfig( + mjcf_path=unitree_g1.MJCF_PATH, + impratio=1.0, + cone=mujoco.mjtCone.mjCONE_PYRAMIDAL, + # each leg: hip pitch, roll and yaw, knee, ankle pitch and roll + home=[0, 0, 0.76, 1, 0, 0, 0, *[-0.312, 0, 0, 0.669, -0.363, 0] * 2] + + [0, 0, 0, 0.2, 0.2, 0, 0.6, 0, 0, 0, 0.2, -0.2, 0, 0.6, 0, 0, 0], + foot_contact_type=mujoco.mjtObj.mjOBJ_XBODY, + foot_contacts=["left_ankle_roll_link", "right_ankle_roll_link"], + foot_sites=["left_foot", "right_foot"], + imu_site="imu_in_pelvis", + torso="torso_link", + foot_geoms=r"(left|right)_foot[1-7]_collision", + foot_friction=[(0.3, 1.2)], + pose_std=dict( + hip_pitch=(0.05, 0.3, 0.5), + hip_roll=(0.05, 0.15, 0.2), + hip_yaw=(0.05, 0.15, 0.2), + knee=(0.05, 0.35, 0.6), + ankle_pitch=(0.05, 0.25, 0.35), + ankle_roll=(0.05, 0.1, 0.15), + waist_yaw=(0.05, 0.2, 0.3), + waist_roll=(0.05, 0.08, 0.08), + waist_pitch=(0.05, 0.1, 0.2), + wrist=(0.05, 0.3, 0.3), + shoulder_pitch=(0.05, 0.15, 0.5), + shoulder_roll=(0.05, 0.15, 0.2), + shoulder_yaw=(0.05, 0.1, 0.15), + elbow=(0.05, 0.15, 0.35), + ), + weights=dict(body_ang_vel=-0.05, angular_momentum=-0.02, self_collisions=-1.0), +) + + +class Joystick(Env): + """Velocity tracking on flat ground for `config`'s robot, in the full physics or the `coarse` one.""" + + def __init__(self, config: JoystickConfig, coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + robot_spec = mjscene.build_robot_spec(config.mjcf_path, prefix="robot/") + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)], floor=False, timestep=0.005) + scene_spec.option.iterations = 10 + scene_spec.option.ls_iterations = 20 + scene_spec.option.ccd_iterations = 50 + scene_spec.option.impratio = config.impratio + scene_spec.option.cone = config.cone + terrain = scene_spec.worldbody.add_body(name="terrain") + terrain.add_geom(name="terrain", type=mujoco.mjtGeom.mjGEOM_PLANE, size=[0.0, 0.0, 0.01]) + # the initial state: each actuator holds its joint's home angle + home = np.array(config.home) + model = scene_spec.compile() + scene_spec.add_key(name="init_state", qpos=home, ctrl=home[model.jnt_qposadr[model.actuator_trnid[:, 0]]]) + for part in config.foot_contacts: # each foot's contact flag and net force against the terrain + for reading in ("found", "force"): + mjscene.build_contact_sensor( + scene_spec, + f"foot_contact_{part}_{reading}", + (config.foot_contact_type, f"robot/{part}"), + (mujoco.mjtObj.mjOBJ_BODY, "terrain"), + data=(reading,), + reduce="netforce", + ) + if coarse is not None: + coarse = replace(coarse, collide=coarse.collide.replace("{feet}", config.foot_geoms)) + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(self.substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="init_state", njmax=300) + self.sim = sim + sim.opt.contact_sensor_maxmatch = 64 # contacts a contact sensor can match + sim.opt.warn_overflow &= ~int(mjw.OverflowType.ITERATIONS | mjw.OverflowType.LS_ITERATIONS) # capped on purpose + sim.set_torch_stream() + robot = sim.build_entity("robot/", soft_joint_pos_limit_factor=0.9) # 90% of each joint's range is penalty-free + self.robot = robot + self.device = robot.device + self.feet_contact = sim.build_contact_sensor("foot_contact", track_air_time=True) + self.self_collision = sim.build_contact_sensor("robot/self_collision") # the G1's, from its MJCF + + # --- set up actions --- + # a joint target is its home angle + a quarter of its actuator's effort / stiffness per unit of action + effort = mjm.actuator_forcerange[robot.actuator_ids, 1] / mjm.actuator_gainprm[robot.actuator_ids, 0] # rad + self.action_scale = torch.tensor(0.25 * effort, device=self.device, dtype=torch.float32) + self.action_offset = robot.data.default_joint_pos[robot.actuated_ids] + lo, hi = robot.data.soft_joint_pos_limits[robot.actuated_ids].T + self.bound = torch.maximum(self.action_offset - lo, hi - self.action_offset) / self.action_scale # for FastSAC + + # --- randomize --- + robot.data.encoder_bias.uniform_(-0.015, 0.015) # rad + # foot friction: one draw per world for all feet + foot_geoms = [g for g in range(mjm.ngeom) if re.fullmatch(f"robot/{config.foot_geoms}", mjm.geom(g).name)] + for axis, (lo, hi) in enumerate(config.foot_friction): # sliding uniform, torsional and rolling log-uniform + sim.set_random("geom_friction", (foot_geoms, axis), lo, hi, log=axis > 0) + self.torso = robot.find_bodies([config.torso])[0] + torso_body = robot.body_ids[self.torso] + sim.set_random("body_ipos", (torso_body,), (-0.025, -0.025, -0.03), (0.025, 0.025, 0.03), add=True) # m + + # --- set up rewards --- + # each term's weight; terms are per second + weights = dict( + track_linear_velocity=2.0, + track_angular_velocity=2.0, + upright=1.0, + pose=1.0, + dof_pos_limits=-1.0, + action_rate_l2=-0.1, + foot_clearance=-2.0, + foot_swing_height=-0.25, + foot_slip=-0.1, + soft_landing=-1e-5, + **config.weights, + ) + if config.energy: + weights["energy"] = -config.energy + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.feet = robot.find_sites(config.foot_sites) + self.angmom = sim.get_sensor("robot/root_angmom") if "angular_momentum" in weights else None # the G1's + pose_std = [next(std for key, std in config.pose_std.items() if key in name) for name in robot.joint_names] + self.pose_std = torch.tensor(pose_std, device=self.device).T # (standing, walking, running) x joint + + # --- set up resets, pushes and commands --- + reset_range = torch.tensor(((-0.5, 0.5), (-0.5, 0.5), (0.01, 0.05), (-3.14, 3.14)), device=self.device) + self.reset_low = reset_range[:, 0] # m, m, m, rad: offsets of the base's x, y, z and yaw + self.reset_high = reset_range[:, 1] + self.push_range = torch.tensor((0.5, 0.5, 0.4, 0.52, 0.52, 0.78), device=self.device) # m/s x, y, z; rad/s + self.command_ranges = torch.zeros(3, 2, device=self.device) # x, y (m/s) and yaw (rad/s), set by `curriculum` + self.curriculum_ranges = None # the ranges `curriculum` last set + + # --- set up observations --- + joints = len(robot.joint_names) + actions = len(robot.actuator_ids) + feet = len(self.feet) + # the actor's noise on each observation + noise = [0.5] * 3 + [0.2] * 3 + [0.05] * 3 # base velocity (m/s), angular velocity (rad/s), gravity + noise += [0.01] * joints + [1.5] * joints # joint angles (rad) and velocities (rad/s) + noise += [0.0] * (actions + 3) # the last action and the command + self.obs_noise = torch.tensor(noise, device=self.device) + self.obs_dims = (len(noise), len(noise) + 6 * feet) # the critic also sees each foot's contact state + imu_site = robot.site_ids[robot.find_sites([config.imu_site])[0]] + self.imu_pos_b = torch.tensor( + mjm.site_pos[imu_site][None], device=self.device, dtype=torch.float32 + ) # on the base + + # --- initialize state --- + self.action = torch.zeros(n, actions, device=self.device) + self.last_action = torch.zeros(n, actions, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.command = torch.zeros(n, 3, device=self.device) + self.command_time_left = torch.zeros(n, device=self.device) + self.target_heading = torch.zeros(n, device=self.device) + self.is_heading = torch.zeros(n, dtype=torch.bool, device=self.device) + self.is_standing = torch.zeros(n, dtype=torch.bool, device=self.device) + self.push_time_left = torch.zeros(n, device=self.device) + self.swing_peak = torch.zeros(n, feet, device=self.device) + self.foot_height = torch.zeros(n, feet, device=self.device) + self.curriculum(0) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """Command curriculum: the x and yaw speed ranges widen after 5000 and 10000 iterations of 24 env steps.""" + ranges = [(-1.0, 1.0), (-1.0, 1.0), (-0.5, 0.5)] + if step >= 5000 * 24: + ranges[0] = (-1.5, 2.0) + ranges[2] = (-0.7, 0.7) + if step >= 10000 * 24: + ranges[0] = (-2.0, 3.0) + if ranges != self.curriculum_ranges: + self.curriculum_ranges = ranges + self.command_ranges.copy_(torch.tensor(ranges)) + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Target the home angles + scale * `action`, as the biased encoders read them; step; score; push.""" + self.last_action.copy_(self.action) + self.action.copy_(action) + bias = self.robot.data.encoder_bias[:, self.robot.actuated_ids] + self.robot.set_joint_position_target(action * self.action_scale + self.action_offset - bias) + self.sim.step() + reward, terminated, timeout, terms = self.score() + self.push() + return reward, terminated, timeout, terms + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, advance the commands, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards, terminations, timeouts and each reward term's mean after a step.""" + robot = self.robot.data + contact = self.feet_contact + self.steps += 1 + + # --- foot contacts --- + contact.update() + in_contact = contact.data.found > 0 + landed = contact.compute_first_contact(self.config.control_dt) # touched down during this step + swing_peak = torch.maximum(self.swing_peak, self.foot_height) + self.swing_peak.copy_(torch.where(in_contact, self.swing_peak, swing_peak)) + foot_speed = robot.site_lin_vel_w[:, self.feet, :2].norm(dim=-1) # horizontal + + # --- rewards --- + command_speed = self.command[:, :2].norm(dim=1) + self.command[:, 2].abs() + moving = (command_speed > 0.05).float() # the foot terms count only when commanded to move + gait = (command_speed >= 0.05).long() + (command_speed >= 1.5).long() # standing, walking or running + lin_vel_b = robot.root_link_lin_vel_b + ang_vel_b = robot.root_link_ang_vel_b + lin_vel_error = ((self.command[:, :2] - lin_vel_b[:, :2]) ** 2).sum(1) + lin_vel_b[:, 2] ** 2 + ang_vel_error = (self.command[:, 2] - ang_vel_b[:, 2]) ** 2 + (ang_vel_b[:, :2] ** 2).sum(1) + low, high = robot.soft_joint_pos_limits.T + out_of_limits = (low - robot.joint_pos).clamp(min=0.0) + (robot.joint_pos - high).clamp(min=0.0) + torso_tilt = robot.body_link_mat_w[:, self.torso, 2, :2] # the z components of the torso's x and y axes + terms = dict( + track_linear_velocity=torch.exp(-lin_vel_error / 0.5**2), + track_angular_velocity=torch.exp(-ang_vel_error / 0.5), + upright=torch.exp(-(torso_tilt**2).sum(1) / 0.2), + pose=torch.exp(-((robot.joint_pos - robot.default_joint_pos) ** 2 / self.pose_std[gait] ** 2).mean(1)), + body_ang_vel=(robot.body_link_ang_vel_w[:, self.torso, :2] ** 2).sum(1), + dof_pos_limits=out_of_limits.sum(1), + action_rate_l2=((self.action - self.last_action) ** 2).sum(1), + foot_clearance=((self.foot_height - 0.1).abs() * foot_speed).sum(1) * moving, + foot_swing_height=((self.swing_peak / 0.1 - 1) ** 2 * landed).sum(1) * moving, + foot_slip=(foot_speed**2 * in_contact).sum(1) * moving, + soft_landing=(contact.data.force.norm(dim=-1) * landed).sum(1) * moving, + energy=(robot.qfrc_actuator * robot.joint_vel).abs().sum(1), # W + ) + if self.angmom is not None: + terms["angular_momentum"] = (self.angmom**2).sum(1) + if self.self_collision.primary_names: # substeps with a self-contact over 10 N + hits = self.self_collision.data.force_history.norm(dim=-1) > 10.0 + terms["self_collisions"] = hits.any(-1).sum(0).float() + self.swing_peak.copy_(torch.where(landed, 0.0, self.swing_peak)) # a new swing starts + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + reward = (term_values * self.weights[:, None] * self.config.control_dt).sum(0) + + # --- terminations --- + qvel = self.sim.data.torch.qvel + diverged = ~qvel.isfinite().all(1) | (qvel.abs() > 100.0).any(1) # the physics blew up + fell = (-robot.projected_gravity_b[:, 2]).clamp(-1.0, 1.0).acos() > math.radians(70.0) # tilted past 70° + timeout = self.steps >= 1000 # 20 s episodes + return reward, diverged | fell, timeout, term_values.mean(1) + + @torch.compile + def push(self): + """Every 1 to 3 s, add a random twist to the base's velocity.""" + self.push_time_left -= self.config.control_dt + push = self.push_time_left < 1e-6 + next_push = 1.0 + 2.0 * torch.rand(self.n, device=self.device) # s + self.push_time_left.copy_(torch.where(push, next_push, self.push_time_left)) + kick = (2 * torch.rand(self.n, 6, device=self.device) - 1) * self.push_range + self.robot.write_root_link_velocity_to_sim(self.robot.data.root_link_vel_w + kick, push) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Reset the masked worlds near home and resample commands, with masked writes only.""" + robot = self.robot + + # --- robot: the base at home, randomly shifted and turned; the joints at home; nothing moving --- + offset = self.reset_low + (self.reset_high - self.reset_low) * torch.rand(self.n, 4, device=self.device) + yaw = offset[:, 3] + zero = torch.zeros_like(yaw) + q_wxyz_world_base = torch.stack([(yaw / 2).cos(), zero, zero, (yaw / 2).sin()], 1) + t_world_base = robot.data.default_root_state[:3] + offset[:, :3] + robot.write_root_link_pose_to_sim(torch.cat([t_world_base, q_wxyz_world_base], 1), mask) + robot.write_root_link_velocity_to_sim(torch.zeros(self.n, 6, device=self.device), mask) + home = robot.data.default_joint_pos.clamp(*robot.data.soft_joint_pos_limits.T) + robot.write_joint_state_to_sim(home, torch.zeros_like(home), mask) + warmstart = self.sim.data.torch.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + + # --- episode: steps, foot contacts, actions and the next push --- + self.steps.masked_fill_(mask, 0) + self.feet_contact.reset(mask) + for state in (self.swing_peak, self.action, self.last_action): + state.copy_(torch.where(mask[:, None], 0.0, state)) + next_push = 1.0 + 2.0 * torch.rand(self.n, device=self.device) # s + self.push_time_left.copy_(torch.where(mask, next_push, self.push_time_left)) + + # --- commands: new ones on reset and every 3 to 8 s --- + self.command_time_left.copy_( + torch.where(mask, self.command_time_left, self.command_time_left - self.config.control_dt) + ) + new = mask | (self.command_time_left <= 0) + low, high = self.command_ranges.T + sampled = low + (high - low) * torch.rand(self.n, 3, device=self.device) + forward_only = torch.rand(self.n, device=self.device) <= 0.2 # 20%: walk forward at 0.3 m/s or more + forward = torch.zeros_like(sampled) + forward[:, 0] = sampled[:, 0].abs().clamp(min=0.3) + command = torch.where(forward_only[:, None], forward, sampled) + self.command.copy_(torch.where(new[:, None], command, self.command)) + target_heading = math.pi * (2 * torch.rand(self.n, device=self.device) - 1) + self.target_heading.copy_(torch.where(new, target_heading, self.target_heading)) + is_heading = (torch.rand(self.n, device=self.device) <= 0.3) & ~forward_only # 30%: turn to the target heading + self.is_heading.copy_(torch.where(new, is_heading, self.is_heading)) + is_standing = torch.rand(self.n, device=self.device) <= 0.1 # 10%: stand still + self.is_standing.copy_(torch.where(new, is_standing, self.is_standing)) + command_time = 3.0 + 5.0 * torch.rand(self.n, device=self.device) # s + self.command_time_left.copy_(torch.where(new, command_time, self.command_time_left)) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's (noisy, encoder-biased) and the critic's observations, after steering to the target headings.""" + robot = self.robot.data + contact = self.feet_contact.data + + # --- heading commands: a yaw speed toward the target heading --- + heading_error = self.target_heading - robot.heading_w + heading_error = torch.atan2(heading_error.sin(), heading_error.cos()) # wrapped to [-pi, pi] + yaw_speed = (0.5 * heading_error).clamp(*self.command_ranges[2]) # rad/s + self.command[:, 2] = torch.where(self.is_heading, yaw_speed, self.command[:, 2]) + self.command.masked_fill_(self.is_standing[:, None], 0.0) + + # --- observations --- + imu_lin_vel_b = robot.root_link_lin_vel_b + torch.linalg.cross(robot.root_link_ang_vel_b, self.imu_pos_b) + self.foot_height.copy_(robot.site_pos_w[:, self.feet, 2].clamp(0.0, 1.0)) # above the plane + fresh = self.steps.eq(0)[:, None] # contact sensors are stale after a reset; the feet start in the air + in_contact = (contact.found > 0) & ~fresh + contact_force = (contact.force * ~fresh[..., None]).flatten(1) + actor = [ + imu_lin_vel_b, + robot.root_link_ang_vel_b, + robot.projected_gravity_b, + robot.joint_pos_biased - robot.default_joint_pos, + robot.joint_vel, + self.action, + self.command, + ] + critic = [ + imu_lin_vel_b, + robot.root_link_ang_vel_b, + robot.projected_gravity_b, + robot.joint_pos - robot.default_joint_pos, + robot.joint_vel, + self.action, + self.command, + self.foot_height, + contact.current_air_time, + in_contact.float(), + contact_force.sign() * contact_force.abs().log1p(), + ] + noise = self.obs_noise * (2 * torch.rand(self.n, len(self.obs_noise), device=self.device) - 1) + return torch.cat(actor, 1) + noise, torch.cat(critic, 1) + + +if __name__ == "__main__": + config = tyro.cli(tyro.extras.subcommand_type_from_defaults(dict(go1=GO1, g1=G1))) + env = Joystick(config) # the full physics, where the policy is scored + if config.algo == "fastsac": + actor = fastsac.train(env, config.minutes) + else: + coarse_env = Joystick(config, coarse=config.coarse_physics) if config.coarse else None + actor = ppo.PPO(env.obs_dims, len(env.bound)).train(env, config.minutes, coarse_env, config.coarse) + print(ppo.evaluate(env, actor)) diff --git a/src/robokit/examples/rl/02_rough_joystick.py b/src/robokit/examples/rl/02_rough_joystick.py new file mode 100644 index 0000000..40dcb3f --- /dev/null +++ b/src/robokit/examples/rl/02_rough_joystick.py @@ -0,0 +1,646 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Rough joystick: a Unitree Go1 or G1 learns to track twist commands over stairs, slopes and bumps with a height scan. + +Example usage: + uv run src/robokit/examples/rl/02_rough_joystick.py go1 --minutes 10 # Go1 + uv run src/robokit/examples/rl/02_rough_joystick.py g1 --minutes 20 # G1 + uv run src/robokit/examples/rl/02_rough_joystick.py go1 --coarse 0.5 # coarse physics mixed in +""" + +import math +import re +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Dict, List, Literal, Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import mujoco_warp as mjw # pyright: ignore[reportMissingImports] +import numpy as np +import torch +import tyro +import warp as wp + +from robokit.assets.robots.humanoids import unitree_g1 +from robokit.assets.robots.quadrupeds import unitree_go1 +from robokit.helpers.rl import Env, fastsac, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class JoystickConfig: + """The rough joystick task and its training: the robot, its scan, the worlds, the power penalty, the learner.""" + + mjcf_path: Path # the robot's MJCF + impratio: float # solver impratio + cone: mujoco.mjtCone # friction cone + home: List[float] # initial qpos: the base's pose, then the joint angles + foot_contact_type: mujoco.mjtObj # the feet's terrain contacts are those of geoms or of body subtrees + foot_contacts: List[str] # their names + foot_sites: List[str] + imu_site: str # where the actor's base velocity is measured + torso: str # the body levelled by the upright reward, its center of mass randomized + foot_geoms: str # foot collision geoms, a pattern; their friction is randomized + foot_friction: List[Tuple[float, float]] # ranges: sliding uniform, torsional and rolling log-uniform + pose_std: Dict[str, Tuple[float, float, float]] # pose reward widths by joint name, rad: standing, walking, running + scan: str # the body below which a 1.6 x 1.0 m grid of rays at 0.1 m looks down + ring: Tuple[float, int] # each foot's ray ring: its radius (m) and its rays around a center ray + nconmax: int # contacts per world + normal: bool # level the upright reward to the terrain's normal, else to up + fell: bool # end an episode on a tilt, else on an `illegal` contact + contacts: Dict[str, str] = field(default_factory=dict) # by term, geoms whose terrain contacts count; see `fell` + weights: Dict[str, float] = field(default_factory=dict) # extra reward weights + worlds: int = 4096 # MjWarpSim worlds + energy: float = 0.0 # the weight of the mechanical power penalty + algo: Literal["ppo", "fastsac"] = "ppo" # the learner + minutes: float = 1.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + # Coarse physics, off by default (`CoarseConfig`): only the feet ("{feet}") and terrain collide + coarse_physics: CoarseConfig = CoarseConfig(collide="robot/{feet}|(?!robot/).*", pyramidal=True) + # The terrain's columns and the share of robots spawning on each; robots start on rows 0 to 5 of difficulty + terrains: Dict[str, float] = field( + default_factory=lambda: dict( + flat=0.2, stairs=0.2, stairs_inv=0.2, slope=0.1, slope_inv=0.1, random_rough=0.1, wave=0.1 + ) + ) + tile: float = 8.0 # m, each sub-terrain's square + rows: int = 10 # rows of difficulty 0 to 1 + border: float = 20.0 # m, the flat border around the grid + + +GO1 = JoystickConfig( + mjcf_path=unitree_go1.MJCF_PATH, + impratio=10.0, + cone=mujoco.mjtCone.mjCONE_ELLIPTIC, + home=[0, 0, 0.278, 1, 0, 0, 0, *[0.1, 0.9, -1.8, -0.1, 0.9, -1.8] * 2], + foot_contact_type=mujoco.mjtObj.mjOBJ_GEOM, + foot_contacts=[f"{leg}_foot_collision" for leg in ("FR", "FL", "RR", "RL")], + foot_sites=["FR", "FL", "RR", "RL"], + imu_site="imu", + torso="trunk", + foot_geoms=r"(FR|FL|RR|RL)_foot_collision", + foot_friction=[(0.3, 1.5), (1e-4, 2e-2), (1e-5, 5e-3)], + pose_std=dict(hip=(0.05, 0.3, 0.3), thigh=(0.05, 0.3, 0.3), calf=(0.1, 0.6, 0.6)), + scan="trunk", + ring=(0.04, 4), + nconmax=35, + normal=True, + fell=False, + contacts=dict( + shank_collision=r"(FR|FL|RR|RL)_calf_collision[12]", + trunk_head_collision=r"(trunk|head)_collision", + illegal=r"(FR|FL|RR|RL)_thigh_collision[123]", + ), + weights=dict(self_collisions=-0.1, shank_collision=-0.1, trunk_head_collision=-0.1), +) +G1 = JoystickConfig( + mjcf_path=unitree_g1.MJCF_PATH, + impratio=1.0, + cone=mujoco.mjtCone.mjCONE_PYRAMIDAL, + # each leg: hip pitch, roll and yaw, knee, ankle pitch and roll + home=[0, 0, 0.76, 1, 0, 0, 0, *[-0.312, 0, 0, 0.669, -0.363, 0] * 2] + + [0, 0, 0, 0.2, 0.2, 0, 0.6, 0, 0, 0, 0.2, -0.2, 0, 0.6, 0, 0, 0], + foot_contact_type=mujoco.mjtObj.mjOBJ_XBODY, + foot_contacts=["left_ankle_roll_link", "right_ankle_roll_link"], + foot_sites=["left_foot", "right_foot"], + imu_site="imu_in_pelvis", + torso="torso_link", + foot_geoms=r"(left|right)_foot[1-7]_collision", + foot_friction=[(0.3, 1.2)], + pose_std=dict( + hip_pitch=(0.05, 0.3, 0.5), + hip_roll=(0.05, 0.15, 0.2), + hip_yaw=(0.05, 0.15, 0.2), + knee=(0.05, 0.35, 0.6), + ankle_pitch=(0.05, 0.25, 0.35), + ankle_roll=(0.05, 0.1, 0.15), + waist_yaw=(0.05, 0.2, 0.3), + waist_roll=(0.05, 0.08, 0.08), + waist_pitch=(0.05, 0.1, 0.2), + wrist=(0.05, 0.3, 0.3), + shoulder_pitch=(0.05, 0.15, 0.5), + shoulder_roll=(0.05, 0.15, 0.2), + shoulder_yaw=(0.05, 0.1, 0.15), + elbow=(0.05, 0.15, 0.35), + ), + scan="pelvis", + ring=(0.03, 6), + nconmax=70, + normal=False, + fell=True, + weights=dict(body_ang_vel=-0.05, angular_momentum=-0.02, self_collisions=-1.0), +) + + +class Joystick(Env): + """Velocity tracking on rough terrain for `config`'s robot, in the full physics or the `coarse` one.""" + + def __init__(self, config: JoystickConfig, coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + robot_spec = mjscene.build_robot_spec(config.mjcf_path, prefix="robot/") + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)], floor=False, timestep=0.005) + scene_spec.option.iterations = 10 + scene_spec.option.ls_iterations = 20 + scene_spec.option.ccd_iterations = 500 + scene_spec.option.impratio = config.impratio + scene_spec.option.cone = config.cone + # the body "terrain": a column of tiles per kind, a row per difficulty; each tile's spawn origin + origins = mjscene.build_terrain( + scene_spec, list(config.terrains), rows=config.rows, tile=config.tile, border=config.border + ) + # the initial state: each actuator holds its joint's home angle + home = np.array(config.home) + model = scene_spec.compile() + scene_spec.add_key(name="init_state", qpos=home, ctrl=home[model.jnt_qposadr[model.actuator_trnid[:, 0]]]) + for part in config.foot_contacts: # each foot's contact flag and net force against the terrain + for reading in ("found", "force"): + mjscene.build_contact_sensor( + scene_spec, + f"foot_contact_{part}_{reading}", + (config.foot_contact_type, f"robot/{part}"), + (mujoco.mjtObj.mjOBJ_BODY, "terrain"), + data=(reading,), + reduce="netforce", + ) + for term, pattern in config.contacts.items(): # each matching geom's contact flag and force against the terrain + geoms = [geom.name for geom in scene_spec.geoms if re.fullmatch(f"robot/{pattern}", geom.name)] + for geom in geoms: + for reading in ("found", "force"): + mjscene.build_contact_sensor( + scene_spec, + f"{term}_{geom.removeprefix('robot/')}_{reading}", + (mujoco.mjtObj.mjOBJ_GEOM, geom), + (mujoco.mjtObj.mjOBJ_BODY, "terrain"), + data=(reading,), + ) + if not any(sensor.name.startswith("robot/self_collision_") for sensor in scene_spec.sensors): + scan_subtree = (mujoco.mjtObj.mjOBJ_XBODY, f"robot/{config.scan}") # the Go1's: the scan body's subtree + for reading in ("found", "force"): # its contacts with itself + name = f"robot/self_collision_{config.scan}_{reading}" + mjscene.build_contact_sensor(scene_spec, name, scan_subtree, scan_subtree, data=(reading,)) + if coarse is not None: + coarse = replace(coarse, collide=coarse.collide.replace("{feet}", config.foot_geoms)) + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(self.substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim( + mjm, + n, + substeps=self.substeps, + key="init_state", + njmax=1500 if coarse is None else 300, + nconmax=config.nconmax, + ) + self.sim = sim + sim.opt.contact_sensor_maxmatch = 500 # contacts a contact sensor can match + sim.opt.warn_overflow &= ~int(mjw.OverflowType.ITERATIONS | mjw.OverflowType.LS_ITERATIONS) # capped on purpose + sim.set_torch_stream() + robot = sim.build_entity("robot/", soft_joint_pos_limit_factor=0.9) # 90% of each joint's range is penalty-free + self.robot = robot + self.device = robot.device + self.feet_contact = sim.build_contact_sensor("foot_contact", track_air_time=True) + self.self_collision = sim.build_contact_sensor( + "robot/self_collision" + ) # the G1's from its MJCF, else the scan body's + self.terrain_contacts = {term: sim.build_contact_sensor(term) for term in config.contacts} + + # --- set up actions --- + # a joint target is its home angle + a quarter of its actuator's effort / stiffness per unit of action + effort = mjm.actuator_forcerange[robot.actuator_ids, 1] / mjm.actuator_gainprm[robot.actuator_ids, 0] # rad + self.action_scale = torch.tensor(0.25 * effort, device=self.device, dtype=torch.float32) + self.action_offset = robot.data.default_joint_pos[robot.actuated_ids] + lo, hi = robot.data.soft_joint_pos_limits[robot.actuated_ids].T + self.bound = torch.maximum(self.action_offset - lo, hi - self.action_offset) / self.action_scale # for FastSAC + + # --- randomize --- + robot.data.encoder_bias.uniform_(-0.015, 0.015) # rad + # foot friction: one draw per world for all feet + foot_geoms = [g for g in range(mjm.ngeom) if re.fullmatch(f"robot/{config.foot_geoms}", mjm.geom(g).name)] + for axis, (lo, hi) in enumerate(config.foot_friction): # sliding uniform, torsional and rolling log-uniform + sim.set_random("geom_friction", (foot_geoms, axis), lo, hi, log=axis > 0) + self.torso = robot.find_bodies([config.torso])[0] + torso_body = robot.body_ids[self.torso] + sim.set_random("body_ipos", (torso_body,), (-0.025, -0.025, -0.03), (0.025, 0.025, 0.03), add=True) # m + + # --- set up rewards --- + # each term's weight; terms are per second + weights = dict( + track_linear_velocity=2.0, + track_angular_velocity=2.0, + upright=1.0, + pose=1.0, + dof_pos_limits=-1.0, + action_rate_l2=-0.1, + foot_clearance=-2.0, + foot_swing_height=-0.25, + foot_slip=-0.1, + soft_landing=-1e-5, + **config.weights, + ) + if config.energy: + weights["energy"] = -config.energy + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.feet = robot.find_sites(config.foot_sites) + self.angmom = sim.get_sensor("robot/root_angmom") if "angular_momentum" in weights else None # the G1's + pose_std = [next(std for key, std in config.pose_std.items() if key in name) for name in robot.joint_names] + self.pose_std = torch.tensor(pose_std, device=self.device).T # (standing, walking, running) x joint + + # --- set up resets, pushes and commands --- + reset_range = torch.tensor(((-0.5, 0.5), (-0.5, 0.5), (0.01, 0.05), (-3.14, 3.14)), device=self.device) + self.reset_low = reset_range[:, 0] # m, m, m, rad: offsets of the base's x, y, z and yaw + self.reset_high = reset_range[:, 1] + self.push_range = torch.tensor((0.5, 0.5, 0.4, 0.52, 0.52, 0.78), device=self.device) # m/s x, y, z; rad/s + self.command_ranges = torch.zeros(3, 2, device=self.device) # x, y (m/s) and yaw (rad/s), set by `curriculum` + self.curriculum_ranges = None # the ranges `curriculum` last set + + # --- set up terrain curriculum --- + # each world's column by share: at least one each, then by largest remainder; its row is its level + share = np.array(list(config.terrains.values())) * (n - len(config.terrains)) + whole = np.floor(share) + counts = 1 + whole.astype(int) + counts[np.argsort(whole - share)[: n - counts.sum()]] += 1 + columns = torch.arange(len(config.terrains), device=self.device) + self.terrain_columns = torch.repeat_interleave(columns, torch.tensor(counts, device=self.device)) + self.terrain_origins = torch.tensor(origins, device=self.device, dtype=torch.float32) # (rows, columns, 3) + self.levels = torch.zeros(n, dtype=torch.long, device=self.device) # each world's row + self.hold_levels = torch.ones((), dtype=torch.bool, device=self.device) # through the next reset + + # --- set up height scan --- + # rays down from the scan body (a grid, x fastest), then from each foot (a ring, its center first) + feet = len(self.feet) + grid_x = torch.linspace(-0.8, 0.8, 17) # m + grid_y = torch.linspace(-0.5, 0.5, 11) + grid_xy = torch.meshgrid(grid_x, grid_y, indexing="xy") + grid = torch.stack([*grid_xy, torch.zeros(len(grid_y), len(grid_x))], -1).reshape(-1, 3) + ring_radius = config.ring[0] # m + ring_angle = 2 * math.pi * torch.arange(config.ring[1]) / config.ring[1] + ring_xyz = torch.stack([ring_radius * ring_angle.cos(), ring_radius * ring_angle.sin(), 0 * ring_angle], 1) + ring = torch.cat([torch.zeros(1, 3), ring_xyz]) + self.ray_offsets = torch.cat([grid, ring.repeat(feet, 1)]).to(self.device) # in each frame, turned by its yaw + self.scan_rays = len(grid) + self.scan_body = robot.find_bodies([config.scan])[0] + self.foot_site_ids = [robot.site_ids[foot] for foot in self.feet] + # each ray's frame (0: the scan body, 1 + f: foot f) and the body it ignores + self.ray_frame = torch.tensor([0] * len(grid) + [1 + f for f in range(feet) for _ in ring], device=self.device) + foot_bodies = mjm.site_bodyid[self.foot_site_ids].tolist() + exclude = [robot.body_ids[self.scan_body]] * len(grid) + [body for body in foot_bodies for _ in ring] + rays = len(self.ray_offsets) + self.ray_origin = torch.zeros(n, rays, 3, device=self.device) # m, set by `obs` + self.ray_dist = torch.zeros(n, rays, device=self.device) # m to the first hit, -1 on a miss + self.ray_normal = torch.zeros(n, rays, 3, device=self.device) # each hit surface's normal + ray_direction = torch.tensor([0.0, 0.0, -1.0], device=self.device).repeat(n, rays, 1) # straight down + self.rays = dict( # the `mjw.rays` arguments, on the tensors above + pnt=wp.from_torch(self.ray_origin, dtype=wp.vec3), + vec=wp.from_torch(ray_direction, dtype=wp.vec3), + bodyexclude=wp.array(exclude, dtype=int, device=sim.device), + dist=wp.from_torch(self.ray_dist), + geomid=wp.zeros((n, rays), dtype=int, device=sim.device), + normal=wp.from_torch(self.ray_normal, dtype=wp.vec3), + geomgroup=wp.types.vector(6, wp.float32)(-1.0, 0.0, 0.0, 0.0, 0.0, 0.0), # geom group 0 only + flg_static=True, # static geoms too: the terrain + ) + self.render_context = mjw.create_render_context( + mjm, + n, + cam_res=[], + render_rgb=[], + render_depth=[], + render_seg=[], + use_textures=False, + use_shadows=False, + enabled_geom_groups=[0], + cam_active=[False] * mjm.ncam, + ) + self.normal_rays = torch.linspace(0, len(grid) - 1, 32, device=self.device).long() # the upright term's plane + + # --- set up observations --- + joints = len(robot.joint_names) + actions = len(robot.actuator_ids) + # the actor's noise on each observation + noise = [0.5] * 3 + [0.2] * 3 + [0.05] * 3 # base velocity (m/s), angular velocity (rad/s), gravity + noise += [0.01] * joints + [1.5] * joints # joint angles (rad) and velocities (rad/s) + noise += [0.0] * (actions + 3) # the last action and the command + noise += [0.1 / 5.0] * self.scan_rays # the height scan, m, scaled as it + self.obs_noise = torch.tensor(noise, device=self.device) + self.obs_dims = (len(noise), len(noise) + 6 * feet) # the critic also sees each foot's contact state + imu_site = robot.site_ids[robot.find_sites([config.imu_site])[0]] + self.imu_pos_b = torch.tensor( + mjm.site_pos[imu_site][None], device=self.device, dtype=torch.float32 + ) # on the base + + # --- initialize state --- + self.action = torch.zeros(n, actions, device=self.device) + self.last_action = torch.zeros(n, actions, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.command = torch.zeros(n, 3, device=self.device) + self.command_time_left = torch.zeros(n, device=self.device) + self.target_heading = torch.zeros(n, device=self.device) + self.is_heading = torch.zeros(n, dtype=torch.bool, device=self.device) + self.is_standing = torch.zeros(n, dtype=torch.bool, device=self.device) + self.push_time_left = torch.zeros(n, device=self.device) + self.swing_peak = torch.zeros(n, feet, device=self.device) + self.foot_height = torch.zeros(n, feet, device=self.device) + self.episode_start = torch.zeros(n, 2, device=self.device) # m, the base's x and y + self.commanded_xy = torch.zeros(n, 2, device=self.device) # m, the commanded displacement so far + self.terrain_normal = torch.tensor([0.0, 0.0, 1.0], device=self.device).repeat(n, 1) + self.curriculum(0) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """Command and terrain curricula: speed ranges widen after 5000 and 10000 iterations of 24 env steps.""" + ranges = [(-1.0, 1.0), (-1.0, 1.0), (-0.5, 0.5)] + if step >= 5000 * 24: + ranges[0] = (-1.5, 2.0) + ranges[2] = (-0.7, 0.7) + if step >= 10000 * 24: + ranges[0] = (-2.0, 3.0) + if ranges != self.curriculum_ranges: + self.curriculum_ranges = ranges + self.command_ranges.copy_(torch.tensor(ranges)) + if step == 0: # terrain levels from 0 to 5, held through the next reset + self.levels.copy_(torch.randint(0, 6, (self.n,), device=self.device)) + self.hold_levels.fill_(True) + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Target the home angles + scale * `action`, as the biased encoders read them; step; score; push.""" + self.last_action.copy_(self.action) + self.action.copy_(action) + bias = self.robot.data.encoder_bias[:, self.robot.actuated_ids] + self.robot.set_joint_position_target(action * self.action_scale + self.action_offset - bias) + self.sim.step() + reward, terminated, timeout, terms = self.score() + self.push() + return reward, terminated, timeout, terms + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, advance the commands, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards, terminations, timeouts and each reward term's mean after a step.""" + robot = self.robot.data + contact = self.feet_contact + self.steps += 1 + + # --- foot contacts --- + contact.update() + in_contact = contact.data.found > 0 + landed = contact.compute_first_contact(self.config.control_dt) # touched down during this step + swing_peak = torch.maximum(self.swing_peak, self.foot_height) + self.swing_peak.copy_(torch.where(in_contact, self.swing_peak, swing_peak)) + foot_speed = robot.site_lin_vel_w[:, self.feet, :2].norm(dim=-1) # horizontal + + # --- rewards --- + command_speed = self.command[:, :2].norm(dim=1) + self.command[:, 2].abs() + moving = (command_speed > 0.05).float() # the foot terms count only when commanded to move + gait = (command_speed >= 0.05).long() + (command_speed >= 1.5).long() # standing, walking or running + lin_vel_b = robot.root_link_lin_vel_b + ang_vel_b = robot.root_link_ang_vel_b + lin_vel_error = ((self.command[:, :2] - lin_vel_b[:, :2]) ** 2).sum(1) + lin_vel_b[:, 2] ** 2 + ang_vel_error = (self.command[:, 2] - ang_vel_b[:, 2]) ** 2 + (ang_vel_b[:, :2] ** 2).sum(1) + low, high = robot.soft_joint_pos_limits.T + out_of_limits = (low - robot.joint_pos).clamp(min=0.0) + (robot.joint_pos - high).clamp(min=0.0) + # the terrain's normal in the torso's frame, its x and y: the torso's tilt off it + torso_tilt = torch.einsum("nji,nj->ni", robot.body_link_mat_w[:, self.torso], self.terrain_normal)[:, :2] + terms = dict( + track_linear_velocity=torch.exp(-lin_vel_error / 0.5**2), + track_angular_velocity=torch.exp(-ang_vel_error / 0.5), + upright=torch.exp(-(torso_tilt**2).sum(1) / 0.2), + pose=torch.exp(-((robot.joint_pos - robot.default_joint_pos) ** 2 / self.pose_std[gait] ** 2).mean(1)), + body_ang_vel=(robot.body_link_ang_vel_w[:, self.torso, :2] ** 2).sum(1), + dof_pos_limits=out_of_limits.sum(1), + action_rate_l2=((self.action - self.last_action) ** 2).sum(1), + foot_clearance=((self.foot_height - 0.1).abs() * foot_speed).sum(1) * moving, + foot_swing_height=((self.swing_peak / 0.1 - 1) ** 2 * landed).sum(1) * moving, + foot_slip=(foot_speed**2 * in_contact).sum(1) * moving, + soft_landing=(contact.data.force.norm(dim=-1) * landed).sum(1) * moving, + energy=(robot.qfrc_actuator * robot.joint_vel).abs().sum(1), # W + ) + collisions = dict(self_collisions=self.self_collision, **self.terrain_contacts) + if self.angmom is not None: + terms["angular_momentum"] = (self.angmom**2).sum(1) + for term, sensor in collisions.items(): # substeps with a contact over 10 N + hits = sensor.data.force_history.norm(dim=-1) > 10.0 + terms[term] = hits.any(-1).sum(0).float() + self.swing_peak.copy_(torch.where(landed, 0.0, self.swing_peak)) # a new swing starts + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + reward = (term_values * self.weights[:, None] * self.config.control_dt).sum(0) + + # --- terminations --- + qvel = self.sim.data.torch.qvel + diverged = ~qvel.isfinite().all(1) | (qvel.abs() > 100.0).any(1) # the physics blew up + if self.config.fell: + fell = (-robot.projected_gravity_b[:, 2]).clamp(-1.0, 1.0).acos() > math.radians(70.0) # tilted past 70° + else: + fell = terms["illegal"] > 0 # an illegal contact with the terrain + base_xy = self.robot.data.root_link_pos_w[:, :2].abs() # m + off_terrain = base_xy[:, 0] > self.config.rows * self.config.tile / 2 + self.config.border - 0.3 + off_terrain |= base_xy[:, 1] > len(self.config.terrains) * self.config.tile / 2 + self.config.border - 0.3 + timeout = (self.steps >= 1000) | off_terrain # 20 s episodes; off the terrain: a timeout + + # --- commanded displacement, in the world frame, for the terrain curriculum --- + heading_cos = robot.heading_w.cos() + heading_sin = robot.heading_w.sin() + command_x_w = heading_cos * self.command[:, 0] - heading_sin * self.command[:, 1] + command_y_w = heading_sin * self.command[:, 0] + heading_cos * self.command[:, 1] + self.commanded_xy += torch.stack([command_x_w, command_y_w], 1) * self.config.control_dt + return reward, diverged | fell, timeout, term_values.mean(1) + + @torch.compile + def push(self): + """Every 1 to 3 s, add a random twist to the base's velocity.""" + self.push_time_left -= self.config.control_dt + push = self.push_time_left < 1e-6 + next_push = 1.0 + 2.0 * torch.rand(self.n, device=self.device) # s + self.push_time_left.copy_(torch.where(push, next_push, self.push_time_left)) + kick = (2 * torch.rand(self.n, 6, device=self.device) - 1) * self.push_range + self.robot.write_root_link_velocity_to_sim(self.robot.data.root_link_vel_w + kick, push) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Move the masked worlds' levels, reset them near their tile's home, resample commands; masked writes only.""" + robot = self.robot + + # --- terrain level --- + base_xy = robot.data.root_link_pos_w[:, :2] + walked = (base_xy - self.episode_start).norm(dim=1) + time_left = (20.0 - self.steps * self.config.control_dt).clamp(min=0.0) # s of the episode + commanded = self.commanded_xy.norm(dim=1) + self.command[:, :2].norm(dim=1) * time_left # m, over the episode + # up a level after walking 80% of the commanded way (at most half a tile), down after under half + up = (walked > (0.8 * commanded).clamp(max=self.config.tile / 2)) & (commanded >= 1.0) & ~self.hold_levels + down = (walked < 0.5 * commanded) & ~up & ~self.hold_levels + level = self.levels + up.long() - down.long() + rows = self.config.rows + level = torch.where(level >= rows, torch.randint_like(level, rows), level.clamp(min=0)) # past the top: any + self.levels.copy_(torch.where(mask, level, self.levels)) + self.hold_levels.fill_(False) + origin = self.terrain_origins[self.levels, self.terrain_columns] + + # --- robot: the base at its tile's home, randomly shifted and turned; the joints at home; nothing moving --- + offset = self.reset_low + (self.reset_high - self.reset_low) * torch.rand(self.n, 4, device=self.device) + yaw = offset[:, 3] + zero = torch.zeros_like(yaw) + q_wxyz_world_base = torch.stack([(yaw / 2).cos(), zero, zero, (yaw / 2).sin()], 1) + t_world_base = robot.data.default_root_state[:3] + origin + offset[:, :3] + robot.write_root_link_pose_to_sim(torch.cat([t_world_base, q_wxyz_world_base], 1), mask) + robot.write_root_link_velocity_to_sim(torch.zeros(self.n, 6, device=self.device), mask) + home = robot.data.default_joint_pos.clamp(*robot.data.soft_joint_pos_limits.T) + robot.write_joint_state_to_sim(home, torch.zeros_like(home), mask) + warmstart = self.sim.data.torch.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + + # --- episode: steps, foot contacts, actions, the next push, the start and the commanded way --- + self.steps.masked_fill_(mask, 0) + self.feet_contact.reset(mask) + for state in (self.swing_peak, self.action, self.last_action, self.commanded_xy): + state.copy_(torch.where(mask[:, None], 0.0, state)) + next_push = 1.0 + 2.0 * torch.rand(self.n, device=self.device) # s + self.push_time_left.copy_(torch.where(mask, next_push, self.push_time_left)) + self.episode_start.copy_(torch.where(mask[:, None], t_world_base[:, :2], self.episode_start)) + + # --- commands: new ones on reset and every 3 to 8 s --- + self.command_time_left.copy_( + torch.where(mask, self.command_time_left, self.command_time_left - self.config.control_dt) + ) + new = mask | (self.command_time_left <= 0) + low, high = self.command_ranges.T + sampled = low + (high - low) * torch.rand(self.n, 3, device=self.device) + forward_only = torch.rand(self.n, device=self.device) <= 0.2 # 20%: walk forward at 0.3 m/s or more + forward = torch.zeros_like(sampled) + forward[:, 0] = sampled[:, 0].abs().clamp(min=0.3) + command = torch.where(forward_only[:, None], forward, sampled) + self.command.copy_(torch.where(new[:, None], command, self.command)) + target_heading = math.pi * (2 * torch.rand(self.n, device=self.device) - 1) + self.target_heading.copy_(torch.where(new, target_heading, self.target_heading)) + is_heading = (torch.rand(self.n, device=self.device) <= 0.3) & ~forward_only # 30%: turn to the target heading + self.is_heading.copy_(torch.where(new, is_heading, self.is_heading)) + is_standing = torch.rand(self.n, device=self.device) <= 0.1 # 10%: stand still + self.is_standing.copy_(torch.where(new, is_standing, self.is_standing)) + command_time = 3.0 + 5.0 * torch.rand(self.n, device=self.device) # s + self.command_time_left.copy_(torch.where(new, command_time, self.command_time_left)) + + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """Cast the scan's and the feet's rays down from their frames, turned by each frame's yaw, then observe.""" + robot = self.robot.data + frame_pos = torch.cat([robot.body_link_pos_w[:, [self.scan_body]], robot.site_pos_w[:, self.feet]], 1) + frame_mat = torch.cat([robot.body_link_mat_w[:, [self.scan_body]], robot.site_mat_w[:, self.feet]], 1) + ray_frame_mat = frame_mat[:, self.ray_frame] + ray_yaw = torch.atan2(ray_frame_mat[..., 1, 0], ray_frame_mat[..., 0, 0]) + ray_cos = ray_yaw.cos() + ray_sin = ray_yaw.sin() + offset_x = self.ray_offsets[:, 0] + offset_y = self.ray_offsets[:, 1] + ray_offset_x_w = ray_cos * offset_x - ray_sin * offset_y + ray_offset_y_w = ray_sin * offset_x + ray_cos * offset_y + ray_offset_w = torch.stack([ray_offset_x_w, ray_offset_y_w, torch.zeros_like(ray_yaw)], -1) + self.ray_origin.copy_(frame_pos[:, self.ray_frame] + ray_offset_w) + self.sim.compute_rays(self.render_context, **self.rays) + return self.observe() + + @torch.compile + def observe(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's (noisy, encoder-biased) and the critic's observations, after steering to the target headings.""" + robot = self.robot.data + contact = self.feet_contact.data + + # --- heading commands: a yaw speed toward the target heading --- + heading_error = self.target_heading - robot.heading_w + heading_error = torch.atan2(heading_error.sin(), heading_error.cos()) # wrapped to [-pi, pi] + yaw_speed = (0.5 * heading_error).clamp(*self.command_ranges[2]) # rad/s + self.command[:, 2] = torch.where(self.is_heading, yaw_speed, self.command[:, 2]) + self.command.masked_fill_(self.is_standing[:, None], 0.0) + + # --- height scan and foot heights --- + scan = self.ray_dist[:, : self.scan_rays] # m, -1 on a miss + scan_hit = (scan >= 0) & (scan <= 5.0) + height_scan = torch.where(scan_hit, scan, 5.0) / 5.0 # misses read the scan's 5 m range; scaled by 1/5 + foot_dist = self.ray_dist[:, self.scan_rays :].view(self.n, len(self.feet), -1) + foot_hit = (foot_dist >= 0) & (foot_dist <= 1.0) + inside = self.ray_normal[:, self.scan_rays :, 2].view(self.n, len(self.feet), -1) < 0 # hit a backface + foot_dist = torch.where(foot_hit & inside, 0.0, foot_dist) + # a missed ray reads 1 m, or the foot's height above z 0 if all of its rays miss + foot_miss = torch.where(foot_hit.any(-1, keepdim=True), 1.0, robot.site_pos_w[:, self.feet, 2:].clamp(0.0, 1.0)) + self.foot_height.copy_(torch.where(foot_hit, foot_dist, foot_miss).min(-1).values) + + # --- terrain normal: a plane fit to 32 of the scan's hits, else up --- + if self.config.normal: + fit_hit = scan_hit[:, self.normal_rays] + hit_points = self.ray_origin[:, self.normal_rays].clone() + hit_points[..., 2] -= scan[:, self.normal_rays].clamp(min=0.0) # the rays point straight down + hits = fit_hit.sum(1) + mean = (hit_points * fit_hit[..., None]).sum(1) / hits.clamp(min=1)[:, None] + centered = (hit_points - mean[:, None]) * fit_hit[..., None] + covariance = torch.einsum("bni,bnj->bij", centered, centered) + finite = covariance.isfinite().all(-1).all(-1) + covariance = torch.where(finite[:, None, None], covariance, torch.eye(3, device=self.device)) + eigenvalues, eigenvectors = torch.linalg.eigh(covariance) # ascending + normal = eigenvectors[:, :, 0] / eigenvectors[:, :, 0].norm(dim=-1, keepdim=True).clamp(min=1e-8) + normal = torch.where(normal[:, 2:] < 0, -normal, normal) # pointing up + eps = torch.finfo(eigenvalues.dtype).eps + planar = eigenvalues[:, 0] / eigenvalues[:, 1].clamp(min=eps) < 0.1 + spread = eigenvalues[:, 1] > eigenvalues[:, 2].clamp(min=eps) * 1e-6 + good = planar & spread & finite & (hits >= 3) + self.terrain_normal.copy_(torch.where(good[:, None], normal, torch.eye(3, device=self.device)[2])) + + # --- observations --- + imu_lin_vel_b = robot.root_link_lin_vel_b + torch.linalg.cross(robot.root_link_ang_vel_b, self.imu_pos_b) + fresh = self.steps.eq(0)[:, None] # contact sensors are stale after a reset; the feet start in the air + in_contact = (contact.found > 0) & ~fresh + contact_force = (contact.force * ~fresh[..., None]).flatten(1) + actor = [ + imu_lin_vel_b, + robot.root_link_ang_vel_b, + robot.projected_gravity_b, + robot.joint_pos_biased - robot.default_joint_pos, + robot.joint_vel, + self.action, + self.command, + height_scan, + ] + critic = [ + imu_lin_vel_b, + robot.root_link_ang_vel_b, + robot.projected_gravity_b, + robot.joint_pos - robot.default_joint_pos, + robot.joint_vel, + self.action, + self.command, + height_scan, + self.foot_height, + contact.current_air_time, + in_contact.float(), + contact_force.sign() * contact_force.abs().log1p(), + ] + noise = self.obs_noise * (2 * torch.rand(self.n, len(self.obs_noise), device=self.device) - 1) + return torch.cat(actor, 1) + noise, torch.cat(critic, 1) + + +if __name__ == "__main__": + config = tyro.cli(tyro.extras.subcommand_type_from_defaults(dict(go1=GO1, g1=G1))) + env = Joystick(config) # the full physics, where the policy is scored + if config.algo == "fastsac": + actor = fastsac.train(env, config.minutes) + else: + coarse_env = Joystick(config, coarse=config.coarse_physics) if config.coarse else None + actor = ppo.PPO(env.obs_dims, len(env.bound)).train(env, config.minutes, coarse_env, config.coarse) + print(ppo.evaluate(env, actor)) diff --git a/src/robokit/examples/rl/03_lift.py b/src/robokit/examples/rl/03_lift.py new file mode 100644 index 0000000..82c6c9b --- /dev/null +++ b/src/robokit/examples/rl/03_lift.py @@ -0,0 +1,255 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Lift: a YAM arm learns to carry a cube to random targets with PPO on 4096 MuJoCo Warp worlds, then is scored. + +Example usage: + uv run src/robokit/examples/rl/03_lift.py --minutes 3 + uv run src/robokit/examples/rl/03_lift.py --coarse 0 # full physics throughout +""" + +import re +from dataclasses import dataclass +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import mujoco_warp as mjw # pyright: ignore[reportMissingImports] +import torch +import tyro + +from robokit.assets.robots.arms import yam +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class LiftConfig: + """The cube lift: its control step, its coarse physics, the worlds and PPO's time.""" + + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + # Coarse physics (`CoarseConfig`): only finger pads, cube and floor collide, 20 ms steps + coarse_physics: CoarseConfig = CoarseConfig( + collide=r"robot/[lr]f_down\d+_collision|cube|floor", + pyramidal=True, + timestep=0.02, + iterations=5, + ls_iterations=10, + ) + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 3.0 # wall time to train, compilation included + coarse: float = 0.5 # the share of PPO's time that mixes in coarse physics (`coarse_physics`), less and less often + + +class Lift(Env): + """The cube lift on `config.worlds` worlds, in the full physics or the `coarse` one.""" + + def __init__(self, config: LiftConfig = LiftConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + robot_spec = mjscene.build_robot_spec(yam.MJCF_PATH, prefix="robot/") + T_world_base = (0.0, 0.0, 0.01, 1.0, 0.0, 0.0, 0.0) # the arm 1 cm above the floor + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)]) + scene_spec.option.impratio = 10.0 + scene_spec.option.cone = mujoco.mjtCone.mjCONE_ELLIPTIC + scene_spec.option.iterations = 10 + scene_spec.option.ls_iterations = 20 + scene_spec.option.ccd_iterations = 50 + cube = scene_spec.worldbody.add_body(name="cube") # a 4 cm cube + cube.add_freejoint(name="cube") + cube.add_geom(name="cube", type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.02] * 3, mass=0.05, rgba=[0.8, 0.2, 0.2, 1]) + # the initial state: the arm at home (rad; the fingers in m), the cube at the origin + home = [0.0, 1.047, 1.05, -0.9, 0.0, 0.0, 0.01875, -0.01875] + scene_spec.add_key(name="init_state", qpos=[*home, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]) + # the contact force between link 6's subtree, the gripper, and the floor + link_6 = (mujoco.mjtObj.mjOBJ_XBODY, "robot/link_6") + floor = (mujoco.mjtObj.mjOBJ_GEOM, "floor") + mjscene.build_contact_sensor(scene_spec, "floor_contact_link_6_force", link_6, floor, data=("force",)) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(self.substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="init_state", njmax=600, nconmax=55) + self.sim = sim + sim.opt.contact_sensor_maxmatch = 64 # contacts a contact sensor can match + sim.opt.warn_overflow &= ~int(mjw.OverflowType.ITERATIONS | mjw.OverflowType.LS_ITERATIONS) # capped on purpose + sim.set_torch_stream() + robot = sim.build_entity("robot/", soft_joint_pos_limit_factor=0.9) # 90% of each joint's range is penalty-free + self.robot = robot + self.device = robot.device + self.cube = sim.build_entity("cube") + self.floor_contact = sim.build_contact_sensor("floor_contact") + + # --- set up actions --- + # a joint target is its home angle + a quarter of its actuator's effort / stiffness per unit of action + effort = mjm.actuator_forcerange[robot.actuator_ids, 1] / mjm.actuator_gainprm[robot.actuator_ids, 0] # rad + self.action_scale = torch.tensor(0.25 * effort, device=self.device, dtype=torch.float32) + self.action_offset = robot.data.default_joint_pos[robot.actuated_ids] + lo, hi = robot.data.soft_joint_pos_limits[robot.actuated_ids].T + self.bound = torch.maximum(self.action_offset - lo, hi - self.action_offset) / self.action_scale # for FastSAC + + # --- randomize --- + # each fingertip pad's friction: sliding uniform, torsional and rolling log-uniform + pattern = r"robot/[lr]f_down(6|7|8|9|10|11)_collision" + pads = [g for g in range(mjm.ngeom) if re.fullmatch(pattern, mjm.geom(g).name)] + for axis, (low, high) in enumerate(((0.3, 1.5), (1e-4, 2e-2), (1e-5, 5e-3))): + sim.set_random("geom_friction", (pads, axis), [low] * len(pads), [high] * len(pads), log=axis > 0) + + # --- set up rewards --- + # each term's weight; terms are per second; `curriculum` raises the joint velocity penalty + weights = dict(lift=1.0, lift_precise=1.0, action_rate_l2=-0.01, joint_pos_limits=-10.0, joint_vel_hinge=-0.01) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.joint_vel_weight = None # the weight `curriculum` last set + self.grasp_site = robot.find_sites(["grasp_site"])[0] + + # --- set up targets --- + target_range = torch.tensor(((0.3, 0.5), (-0.2, 0.2), (0.2, 0.4)), device=self.device) + self.target_low = target_range[:, 0] # m: the target's x, y, z + self.target_high = target_range[:, 1] + cube_range = torch.tensor(((0.2, 0.4), (-0.2, 0.2), (0.02, 0.05), (-3.14, 3.14)), device=self.device) + self.cube_low = cube_range[:, 0] # m, m, m, rad: the cube's x, y, z and yaw + self.cube_high = cube_range[:, 1] + + # --- set up observations --- + joints = len(robot.joint_names) + actions = len(robot.actuator_ids) + # the actor's noise on each observation + noise = [0.01] * joints + [1.5] * joints # joint angles (rad) and velocities (rad/s) + noise += [0.01] * 6 + [0.0] * actions # the cube from the gripper and to the target (m), the last action + self.obs_noise = torch.tensor(noise, device=self.device) + self.obs_dims = (len(noise), len(noise)) + + # --- initialize state --- + self.action = torch.zeros(n, actions, device=self.device) + self.last_action = torch.zeros(n, actions, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.target = torch.zeros(n, 3, device=self.device) + self.target_time_left = torch.zeros(n, device=self.device) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """Reward curriculum: the joint velocity penalty grows after 500 and 1000 iterations of 24 env steps.""" + weight = -0.01 + if step >= 500 * 24: + weight = -0.1 + if step >= 1000 * 24: + weight = -1.0 + if weight != self.joint_vel_weight: + self.joint_vel_weight = weight + self.weights[self.names.index("joint_vel_hinge")] = weight + + def at_goal(self) -> torch.Tensor: + """1 where the cube is within 5 cm of the target, else 0, per world.""" + cube_pos = self.cube.data.root_link_pos_w + return ((self.target - cube_pos).norm(dim=1) < 0.05).float() + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Target the home angles + scale * `action`; step; score.""" + self.last_action.copy_(self.action) + self.action.copy_(action) + self.robot.set_joint_position_target(action * self.action_scale + self.action_offset) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, advance the targets, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards, terminations, timeouts and each reward term's mean after a step.""" + robot = self.robot.data + self.steps += 1 + + # --- rewards --- + gripper_pos = robot.site_pos_w[:, self.grasp_site] + cube_pos = self.cube.data.root_link_pos_w + target_error = ((self.target - cube_pos) ** 2).sum(1) # m^2 + reach = torch.exp(-((gripper_pos - cube_pos) ** 2).sum(1) / 0.2**2) # the gripper at the cube + low, high = robot.soft_joint_pos_limits.T + out_of_limits = (low - robot.joint_pos).clamp(min=0.0) + (robot.joint_pos - high).clamp(min=0.0) + terms = dict( + lift=reach * (1 + torch.exp(-target_error / 0.3**2)), + lift_precise=torch.exp(-target_error / 0.05**2), + action_rate_l2=((self.action - self.last_action) ** 2).sum(1), + joint_pos_limits=out_of_limits.sum(1), + joint_vel_hinge=((robot.joint_vel.abs() - 0.5).clamp(min=0.0) ** 2).sum(1), + ) + term_values = torch.stack([terms[name] for name in self.names]) + reward = (torch.nan_to_num(term_values * self.weights[:, None]) * self.config.control_dt).sum(0) + + # --- terminations --- + hit_floor = (self.floor_contact.data.force_history.norm(dim=-1) > 10.0).any(-1).any(0) # over 10 N in a substep + timeout = self.steps >= 1000 # 20 s episodes + return reward, hit_floor, timeout, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Reset the masked worlds near home and resample targets, with masked writes only.""" + robot = self.robot + + # --- robot: the joints at home, nothing moving --- + home = robot.data.default_joint_pos.clamp(*robot.data.soft_joint_pos_limits.T) + robot.write_joint_state_to_sim(home, torch.zeros_like(home), mask) + warmstart = self.sim.data.torch.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + + # --- episode: steps and actions --- + self.steps.masked_fill_(mask, 0) + for state in (self.action, self.last_action): + state.copy_(torch.where(mask[:, None], 0.0, state)) + + # --- targets: new ones on reset and every 8 to 12 s, each with the cube respawned at rest --- + self.target_time_left.copy_( + torch.where(mask, self.target_time_left, self.target_time_left - self.config.control_dt) + ) + new = mask | (self.target_time_left <= 0) + target = self.target_low + (self.target_high - self.target_low) * torch.rand(self.n, 3, device=self.device) + self.target.copy_(torch.where(new[:, None], target, self.target)) + spawn = self.cube_low + (self.cube_high - self.cube_low) * torch.rand(self.n, 4, device=self.device) + yaw = spawn[:, 3] + zero = torch.zeros_like(yaw) + q_wxyz_world_cube = torch.stack([(yaw / 2).cos(), zero, zero, (yaw / 2).sin()], 1) + self.cube.write_root_link_pose_to_sim(torch.cat([spawn[:, :3], q_wxyz_world_cube], 1), new) + self.cube.write_root_link_velocity_to_sim(torch.zeros(self.n, 6, device=self.device), new) + target_time = 8.0 + 4.0 * torch.rand(self.n, device=self.device) # s + self.target_time_left.copy_(torch.where(new, target_time, self.target_time_left)) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's (noisy) and the critic's observations: joints, the cube's offsets, the last action.""" + robot = self.robot.data + cube_pos = self.cube.data.root_link_pos_w + state = [ + robot.joint_pos - robot.default_joint_pos, + robot.joint_vel, + cube_pos - robot.site_pos_w[:, self.grasp_site], + self.target - cube_pos, + self.action, + ] + critic = torch.cat(state, 1) + noise = self.obs_noise * (2 * torch.rand(self.n, len(self.obs_noise), device=self.device) - 1) + return critic + noise, critic + + +if __name__ == "__main__": + config = tyro.cli(LiftConfig) + env = Lift(config) # the full physics, where the policy is scored + coarse_env = Lift(config, coarse=config.coarse_physics) if config.coarse else None + learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig(entropy=0.005)) + actor = learner.train(env, config.minutes, coarse_env, config.coarse) + print(ppo.evaluate(env, actor, dict(at_goal=env.at_goal))) diff --git a/src/robokit/examples/rl/04_go1_getup.py b/src/robokit/examples/rl/04_go1_getup.py new file mode 100644 index 0000000..40ebe5a --- /dev/null +++ b/src/robokit/examples/rl/04_go1_getup.py @@ -0,0 +1,296 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Go1 getup: a Unitree Go1 dropped in a random pose learns to stand up with PPO on 4096 MuJoCo Warp worlds. + +Example usage: + uv run src/robokit/examples/rl/04_go1_getup.py --minutes 5 + uv run src/robokit/examples/rl/04_go1_getup.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +import math +from dataclasses import dataclass +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import torch +import tyro +import warp as wp + +from robokit.assets.robots.quadrupeds import unitree_go1 +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class GetupConfig: + """The getup: its control step, episode and coarse physics, the worlds and PPO's time.""" + + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 300 # env steps per episode: 6 s + # Coarse physics (`CoarseConfig`): only the floor, feet and trunk collide, pyramidal cones + coarse_physics: CoarseConfig = CoarseConfig( + collide="floor|robot/(FR|FL|RR|RL)_foot_collision|robot/trunk_collision", pyramidal=True + ) + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 5.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + + +class Getup(Env): + """Go1 getup on `config.worlds` worlds, in the full physics or the `coarse` one.""" + + def __init__(self, config: GetupConfig = GetupConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + # the Go1 on a floor: 4 ms Euler steps, 1 solver iteration, PD joint targets + robot_spec = mjscene.build_robot_spec(unitree_go1.MJCF_PATH, prefix="robot/") + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)], timestep=0.004) + scene_spec.geom("floor").friction = (0.6, 0.005, 1e-4) + scene_spec.option.integrator = mujoco.mjtIntegrator.mjINT_EULER + scene_spec.option.iterations = 1 + scene_spec.option.ls_iterations = 5 + scene_spec.option.ccd_iterations = 20 + scene_spec.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_EULERDAMP + # feet and floor with 3D contacts, the floor's friction winning; the rest frictionless + for geom in scene_spec.geoms: + geom.condim = 3 if geom.name == "floor" or geom.name.endswith("_foot_collision") else 1 + geom.priority = 1 if geom.name == "floor" else 0 + for actuator in list(scene_spec.actuators): # replaced by position actuators in joint order + scene_spec.delete(actuator) + for leg in ("FR", "FL", "RR", "RL"): + for part, frictionloss, force in (("hip", 0.3, 23.7), ("thigh", 0.3, 23.7), ("calf", 1.0, 35.55)): + joint = scene_spec.joint(f"robot/{leg}_{part}_joint") + joint.damping = [0.5, 0.0, 0.0] + joint.armature = 0.005 + joint.frictionloss = frictionloss + actuator = scene_spec.add_actuator( + name=joint.name, target=joint.name, trntype=mujoco.mjtTrn.mjTRN_JOINT + ) + actuator.set_to_position(kp=35.0) + actuator.forcelimited = mujoco.mjtLimited.mjLIMITED_TRUE + actuator.forcerange = [-force, force] + actuator.ctrllimited = mujoco.mjtLimited.mjLIMITED_TRUE + actuator.ctrlrange = joint.range + # the scene's only sensors, at the IMU site: gyro, accelerometer, local linear and global angular velocity + sensors = [ + mujoco.mjtSensor.mjSENS_GYRO, + mujoco.mjtSensor.mjSENS_ACCELEROMETER, + mujoco.mjtSensor.mjSENS_VELOCIMETER, + mujoco.mjtSensor.mjSENS_FRAMEANGVEL, + ] + for sensor_type in sensors: + scene_spec.add_sensor(type=sensor_type, objtype=mujoco.mjtObj.mjOBJ_SITE, objname="robot/imu") + stand = [0.1, 0.9, -1.8, -0.1, 0.9, -1.8] * 2 # rad: the standing joint angles + scene_spec.add_key(name="home", qpos=[0.0, 0.0, 0.278, 1.0, 0.0, 0.0, 0.0, *stand], ctrl=stand) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(self.substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="home", njmax=250, nconmax=30) + self.sim = sim + sim.set_torch_stream() + robot = sim.build_entity( + "robot/", soft_joint_pos_limit_factor=0.95 + ) # 95% of each joint's range is penalty-free + self.robot = robot + self.device = robot.device + data = sim.data.torch + # what a reset restores: positions, velocities, sensors and actuator forces, all the Go1's + self.state = [data.qpos, data.qvel, data.sensordata, data.actuator_force] + + # --- set up actions --- + joints = len(robot.joint_names) + actions = len(robot.actuator_ids) + self.bound = torch.ones(actions, device=self.device) # actions in [-1, 1] + + # --- randomize --- + # floor friction, joint friction, armature and zero pose, masses, the trunk's center of mass and mass + sim.set_random("geom_friction", (mjm.geom("floor").id, 0), 0.4, 1.0) + joint_dofs = robot.data.joint_v_adr + wp.to_torch(sim.model.dof_frictionloss)[:, joint_dofs] *= 0.9 + 0.2 * torch.rand(n, joints, device=self.device) + wp.to_torch(sim.model.dof_armature)[:, joint_dofs] *= 1.0 + 0.05 * torch.rand(n, joints, device=self.device) + sim.set_random("qpos0", (robot.data.joint_q_adr.tolist(),), [-0.05] * joints, [0.05] * joints, add=True) # rad + wp.to_torch(sim.model.body_mass)[:] *= 0.9 + 0.2 * torch.rand(n, mjm.nbody, device=self.device) + sim.set_random("body_ipos", (robot.root_body,), [-0.05] * 3, [0.05] * 3, add=True) # m + sim.set_random("body_mass", (robot.root_body,), -1.0, 1.0, add=True) # kg; then set_const for all the above + + # --- set up rewards --- + # each term's weight; terms are per second + weights = dict( + orientation=1.0, + torso_height=1.0, + posture=1.0, + stand_still=1.0, + action_rate=-0.001, + dof_pos_limits=-0.1, + torques=-1e-5, + dof_acc=-2.5e-7, + dof_vel=-0.1, + ) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.imu = robot.find_sites(["imu"])[0] # on the trunk, its axes the trunk's + + # --- set up observations --- + # the actor's noise on its gyro (rad/s), gravity, joint angles (rad) and velocities (rad/s); none on the action + self.obs_noise = torch.tensor([0.2] * 3 + [0.05] * 3 + [0.03] * joints + [1.5] * joints, device=self.device) + self.obs_dims = (42, 91) # the critic adds the sensors, joints, torques and the trunk's height + + # --- initialize state --- + self.action = torch.zeros(n, actions, device=self.device) + self.last_action = torch.zeros(n, actions, device=self.device) + self.action_before_last = torch.zeros(n, actions, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.reward = torch.zeros(n, device=self.device) # the last step's, per world + self.standing = torch.zeros(n, device=self.device) # 1 where upright at the standing height after the last step + + # --- set up the reset pool --- + # 16 * n states, 60% dropped from 0.5 m in random poses, the rest at home, each settled for 0.5 s + joint_low = torch.tensor(mjm.jnt_range[robot.joint_ids, 0], device=self.device, dtype=torch.float32) + joint_high = torch.tensor(mjm.jnt_range[robot.joint_ids, 1], device=self.device, dtype=torch.float32) + t_world_drop = torch.tensor([0.0, 0.0, 0.5], device=self.device).expand(n, 3) + pool = [] + for _ in range(16): + dropped = torch.rand(n, 1, device=self.device) < 0.6 + q_wxyz_world_drop = torch.randn(n, 4, device=self.device) # a uniform rotation, once normalized + q_wxyz_world_drop = q_wxyz_world_drop / (q_wxyz_world_drop.norm(dim=1, keepdim=True) + 1e-6) + T_world_drop = torch.cat([t_world_drop, q_wxyz_world_drop], 1) + robot.write_root_link_pose_to_sim(torch.where(dropped, T_world_drop, robot.data.default_root_state[:7])) + joint_pos = joint_low + (joint_high - joint_low) * torch.rand(n, joints, device=self.device) + joint_pos = torch.where(dropped, joint_pos, robot.data.default_joint_pos) + robot.write_joint_state_to_sim(joint_pos, torch.zeros_like(joint_pos)) + robot.write_root_link_velocity_to_sim(-0.5 + torch.rand(n, 6, device=self.device)) # m/s, rad/s + robot.set_joint_position_target(joint_pos) + data.qacc_warmstart.zero_() + for _ in range(round(0.5 / config.control_dt)): + sim.step() + pool.append(torch.cat([field.clone() for field in self.state], 1)) + self.pool = torch.cat(pool) + self.state_widths = [field.shape[1] for field in self.state] + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None: the getup has no curriculum.""" + + def episode_reward(self) -> torch.Tensor: + """The per-step reward times the episode length, per world.""" + return self.reward * self.config.episode + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Target the current joint angles + 0.5 * `action`, clipped to [-1, 1]; step; score.""" + action = action.clamp(-1.0, 1.0) + self.action_before_last.copy_(self.last_action) + self.last_action.copy_(self.action) + self.action.copy_(action) + self.robot.set_joint_position_target(self.robot.data.joint_pos + 0.5 * action) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards from the (one substep stale) derived quantities; terminated only where the physics blew up.""" + robot = self.robot.data + data = self.sim.data.torch + self.steps += 1 + + # --- rewards --- + gravity_b = robot.projected_gravity_b # in the IMU's frame, the trunk's + tilt_error = (gravity_b[:, :2] ** 2).sum(1) + (gravity_b[:, 2] + 1.0) ** 2 # from (0, 0, -1), upright + height = robot.site_pos_w[:, self.imu, 2].clamp(max=0.275) # m: the IMU's, up to the standing height + upright = tilt_error < 0.01 + standing = upright & (0.275 - height < 0.005) + joint_error = robot.joint_pos - robot.default_joint_pos + low, high = robot.soft_joint_pos_limits.T + out_of_limits = (low - robot.joint_pos).clamp(min=0.0) + (robot.joint_pos - high).clamp(min=0.0) + action_rate = self.action - self.last_action + action_accel = self.action - 2 * self.last_action + self.action_before_last + torque = data.actuator_force + terms = dict( + orientation=torch.exp(-2.0 * tilt_error), + torso_height=height.exp() - 1.0, + posture=upright * torch.exp(-0.5 * (joint_error**2).sum(1)), + stand_still=standing * torch.exp(-0.5 * (self.action**2).sum(1)), + action_rate=(action_rate**2).sum(1) + (action_accel**2).sum(1), + dof_pos_limits=out_of_limits.sum(1), + torques=torque.norm(dim=1) + torque.abs().sum(1), + dof_acc=(data.qacc[:, robot.joint_v_adr] ** 2).sum(1), + dof_vel=((robot.joint_vel.abs() - 2 * math.pi).clamp(min=0.0) ** 2).sum(1), + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + reward = ((term_values * self.weights[:, None]).sum(0) * self.config.control_dt).clamp(0.0, 1e4) + self.reward.copy_(reward) + self.standing.copy_(standing.float()) + + # --- terminations --- + diverged = ~data.qvel.isfinite().all(1) # the physics blew up + timeout = self.steps >= self.config.episode + return reward, diverged, timeout, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Draw the masked worlds' states from the pool, with masked writes only.""" + # --- simulator: a pooled state, no warm start --- + drawn = self.pool[torch.randint(len(self.pool), (self.n,), device=self.device)] + for field, value in zip(self.state, drawn.split(self.state_widths, 1)): + field.copy_(torch.where(mask[:, None], value, field)) + warmstart = self.sim.data.torch.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + + # --- episode: steps and actions --- + self.steps.masked_fill_(mask, 0) + for state in (self.action, self.last_action, self.action_before_last): + state.copy_(torch.where(mask[:, None], 0.0, state)) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's (noisy; its last action lags a step) and the critic's observations.""" + robot = self.robot.data + data = self.sim.data.torch + imu = data.sensordata # gyro, accelerometer, local linear and global angular velocity + joint_error = robot.joint_pos - robot.default_joint_pos + clean = torch.cat([imu[:, :3], robot.projected_gravity_b, joint_error, robot.joint_vel], 1) + actor = torch.cat([clean + self.obs_noise * (2 * torch.rand_like(clean) - 1), self.last_action], 1) + height = robot.site_pos_w[:, self.imu, 2:] # m: the IMU's + critic = torch.cat([actor, imu, robot.joint_pos, robot.joint_vel, data.actuator_force, height], 1) + return actor, critic + + +if __name__ == "__main__": + config = tyro.cli(GetupConfig) + env = Getup(config) # the full physics, where the policy is scored + coarse_env = Getup(config, coarse=config.coarse_physics) if config.coarse else None + # PPO settings for this task; tanh-squashed actions, their entropy keeping the means off saturation + ppo_config = ppo.PPOConfig( + std="state", + squash_entropy=True, + gamma=0.97, + entropy=0.01, + lr=3e-4, + lr_range=(3e-4, 3e-4), + horizon=20, + minibatches=32, + epochs=4, + ) + actor = ppo.PPO(env.obs_dims, len(env.bound), ppo_config).train(env, config.minutes, coarse_env, config.coarse) + metrics = dict(episode_reward=env.episode_reward, standing=env.standing.clone) + print(ppo.evaluate(env, actor, metrics, steps=3 * config.episode)) diff --git a/src/robokit/examples/rl/05_panda_pick.py b/src/robokit/examples/rl/05_panda_pick.py new file mode 100644 index 0000000..1551de4 --- /dev/null +++ b/src/robokit/examples/rl/05_panda_pick.py @@ -0,0 +1,285 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Panda pick: a Franka Panda learns with PPO on 4096 MuJoCo Warp worlds to lift a cube to a random target 20-40 cm up. + +Example usage: + uv run src/robokit/examples/rl/05_panda_pick.py --minutes 5 + uv run src/robokit/examples/rl/05_panda_pick.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +from dataclasses import dataclass +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import numpy as np +import torch +import tyro + +from robokit.assets.robots.arms import franka_panda +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class PandaPickConfig: + """The pick: its control step, episode and coarse physics, the worlds and PPO's time.""" + + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 150 # env steps per episode: 3 s + # Coarse physics (`CoarseConfig`): only the finger pads, hand capsule, box and floor collide + coarse_physics: CoarseConfig = CoarseConfig( + collide="left_finger_pad|right_finger_pad|hand_capsule|box|floor", pyramidal=True + ) + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 5.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + + +class PandaPick(Env): + """Cube pick and lift on `config.worlds` worlds, in the full physics or the `coarse` one.""" + + def __init__(self, config: PandaPickConfig = PandaPickConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + # the Panda with its hand, a 4x4x6 cm cube on the floor, 5 ms steps + robot_spec = mjscene.build_robot_spec(franka_panda.URDF_PATH) + for geom in robot_spec.geoms: # only the finger pads and a hand capsule collide + geom.contype = 0 + geom.conaffinity = 0 + for side in ("left", "right"): + pad = robot_spec.body(f"panda_{side}finger").geoms[3] + pad.name = f"{side}_finger_pad" + pad.conaffinity = 3 + for joint, damping in zip(robot_spec.joints, [40, 40, 40, 40, 2, 2, 2, 10, 10]): # the fingers last + joint.damping = [damping, 0, 0] + joint.armature = 0.1 + q_wxyz_link7_hand = [0.9238795, 0, 0, -0.3826834] # the hand frame, 10.7 cm along link 7 + link7 = robot_spec.body("panda_link7") + q_wxyz_link7_capsule = np.zeros(4) + mujoco.mju_mulQuat(q_wxyz_link7_capsule, q_wxyz_link7_hand, [0.7071068, 0.7071068, 0, 0]) + link7.add_geom( + name="hand_capsule", + type=mujoco.mjtGeom.mjGEOM_CAPSULE, + size=[0.04, 0.06, 0], + pos=[0, 0, 0.137], + quat=q_wxyz_link7_capsule, + contype=0, + conaffinity=1, + group=3, + ) + link7.add_site(name="panda_gripper", pos=[0, 0, 0.207], quat=q_wxyz_link7_hand) # the robot's "gripper" + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)]) + box_body = scene_spec.worldbody.add_body(name="box", pos=[0.5, 0, 0.03]) + box_body.add_freejoint(name="box") + box_body.add_geom( + name="box", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[0.02, 0.02, 0.03], + rgba=[0, 1, 0, 1], + friction=[1, 0.03, 0.003], + contype=2, + solref=[0.01, 1], + ) + scene_spec.option.iterations = 5 + scene_spec.option.ls_iterations = 8 + scene_spec.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_EULERDAMP + gains = [(1000, 20, 100)] * 2 + [(750, 4, 100)] * 2 + [(300, 2, 12)] * 3 # kp, kv, force limit per arm joint + for i, (kp, kv, force) in enumerate(gains): + joint = scene_spec.joint(f"panda_joint{i + 1}") + actuator = scene_spec.add_actuator( + name=f"actuator{i + 1}", + target=joint.name, + trntype=mujoco.mjtTrn.mjTRN_JOINT, + ctrlrange=joint.range, + forcerange=[-force, force], + ) + actuator.set_to_position(kp=kp, kv=kv) + scene_spec.add_actuator( + name="actuator8", + target="panda_finger_joint1", + trntype=mujoco.mjtTrn.mjTRN_JOINT, + ctrlrange=[0, 0.04], + forcerange=[-200, 200], + gainprm=[350] + [0] * 9, + biastype=mujoco.mjtBias.mjBIAS_AFFINE, + biasprm=[0, -350, -10] + [0] * 7, + ) + floor = (mujoco.mjtObj.mjOBJ_GEOM, "floor") + for geom in ("left_finger_pad", "right_finger_pad", "hand_capsule"): # contact found, reduced to the closest + hand_geom = (mujoco.mjtObj.mjOBJ_GEOM, geom) + mjscene.build_contact_sensor(scene_spec, f"floor_contact_{geom}_found", hand_geom, floor, reduce="mindist") + home = [0, 0.3, 0, -1.57079, 0, 2.0, -0.7853] # rad: the arm joint targets + # the fingers open (m) and the box 70 cm ahead; each actuator holds its joint's home angle + scene_spec.add_key(name="home", qpos=home + [0.04, 0.04, 0.7, 0, 0.03, 1, 0, 0, 0], ctrl=home + [0.04]) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(self.substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="home", njmax=128, nconmax=24) + self.sim = sim + sim.set_torch_stream() + robot = sim.build_entity("panda_") # every actuator is the Panda's, in joint order + self.robot = robot + self.device = robot.device + self.box = sim.build_entity("box") + self.floor_contact = sim.build_contact_sensor("floor_contact") + + # --- set up actions --- + # each action moves its actuator's target (`ctrl`) by up to 0.04 (rad, m) within the control range + ctrl_range = torch.tensor(mjm.actuator_ctrlrange[robot.actuator_ids], device=self.device, dtype=torch.float32) + self.ctrl_low = ctrl_range[:, 0] + self.ctrl_high = ctrl_range[:, 1] + self.home_target = robot.data.default_joint_pos[robot.actuated_ids] # the key's `ctrl` + self.bound = torch.ones(len(robot.actuator_ids), device=self.device) # tanh-squashed actions + + # --- set up rewards --- + # each term's weight; the reward is per step + weights = dict(gripper_box=4.0, box_target=8.0, no_floor_collision=0.25, robot_target_qpos=0.3) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.gripper = robot.find_sites(["gripper"])[0] + # the box's target orientation, upright: the identity's first two rows + self.box_target_rows = torch.tensor([1.0, 0, 0, 0, 1, 0], device=self.device) + + # --- set up resets --- + self.box_home = self.box.data.default_root_state[:3] # m + # offsets from it (m): the cube's in the plane, the target's 20 to 40 cm above + self.spawn_low = torch.tensor(((-0.2, -0.2, 0.0), (-0.2, -0.2, 0.2)), device=self.device) + self.spawn_high = torch.tensor(((0.2, 0.2, 0.0), (0.2, 0.2, 0.4)), device=self.device) + + # --- set up observations --- + # the whole state, the gripper and the box, their offsets, the box's tilt and the joint targets' errors + dims = mjm.nq + mjm.nv + 3 + 6 + 6 + 3 + 3 + 6 + mjm.nu + self.obs_dims = (dims, dims) + + # --- initialize state --- + self.target = torch.zeros(n, 3, device=self.device) + self.reached = torch.zeros(n, device=self.device) # 1 once the gripper reached the box + self.reward = torch.zeros(n, device=self.device) # the last step's, per world + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None: the pick has no curriculum.""" + + def at_target(self) -> torch.Tensor: + """1 where the cube is within 5 cm of the target, else 0, per world.""" + box_pos = self.box.data.root_link_pos_w + return ((self.target - box_pos).norm(dim=1) < 0.05).float() + + def episode_reward(self) -> torch.Tensor: + """The per-step reward times the episode length, per world.""" + return self.reward * self.config.episode + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Move the joint targets by 0.04 * `action` (clamped to [-1, 1]) within their range; step; score.""" + target = self.robot.data.joint_pos_target + 0.04 * action.clamp(-1, 1) + self.robot.set_joint_position_target(target.clamp(self.ctrl_low, self.ctrl_high)) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Per-step rewards; the episode ends when the cube leaves the 1 m box or the physics turns NaN.""" + robot = self.robot.data + data = self.sim.data.torch + self.steps += 1 + + # --- rewards --- + box_pos = self.box.data.root_link_pos_w + box_rows = self.box.data.body_link_mat_w[:, 0].flatten(1)[:, :6] # its orientation's first two rows + gripper_distance = (box_pos - robot.site_pos_w[:, self.gripper]).norm(dim=1) + self.reached.copy_(torch.maximum(self.reached, (gripper_distance < 0.012).float())) + target_error = 0.9 * (self.target - box_pos).norm(dim=1) + 0.1 * (self.box_target_rows - box_rows).norm(dim=1) + arm_error = robot.joint_pos[:, :7] - robot.default_joint_pos[:7] # the arm's 7 joints, the fingers after + on_floor = (self.floor_contact.data.found > 0).any(1) # a finger pad or the hand + terms = dict( + gripper_box=1 - torch.tanh(5 * gripper_distance), + box_target=(1 - torch.tanh(5 * target_error)) * self.reached, + no_floor_collision=1 - on_floor.float(), + robot_target_qpos=1 - torch.tanh(arm_error.norm(dim=1)), + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + self.reward.copy_((term_values * self.weights[:, None]).sum(0).clamp(-1e4, 1e4)) + + # --- terminations --- + diverged = data.qpos.isnan().any(1) | data.qvel.isnan().any(1) + out_of_bounds = (box_pos.abs() > 1.0).any(1) | (box_pos[:, 2] < 0.0) + timeout = self.steps >= self.config.episode + return self.reward, out_of_bounds | diverged, timeout, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Reset the masked worlds at home, the cube moved in the plane, a new target above it; masked writes only.""" + robot = self.robot + data = self.sim.data.torch + + # --- robot: the joints and their targets at home, nothing moving --- + home = robot.data.default_joint_pos + robot.write_joint_state_to_sim(home, torch.zeros_like(home), mask) + robot.set_joint_position_target(torch.where(mask[:, None], self.home_target, robot.data.joint_pos_target)) + data.qacc_warmstart.copy_(torch.where(mask[:, None], 0.0, data.qacc_warmstart)) + + # --- box and target: the box at rest in its home orientation --- + spawn_range = self.spawn_high - self.spawn_low + spawn = self.box_home + self.spawn_low + spawn_range * torch.rand(self.n, 2, 3, device=self.device) + q_wxyz_world_box = self.box.data.default_root_state[3:7].expand(self.n, 4) + self.box.write_root_link_pose_to_sim(torch.cat([spawn[:, 0], q_wxyz_world_box], 1), mask) + self.box.write_root_link_velocity_to_sim(torch.zeros(self.n, 6, device=self.device), mask) + self.target.copy_(torch.where(mask[:, None], spawn[:, 1], self.target)) + + # --- episode --- + self.reached.masked_fill_(mask, 0.0) + self.steps.masked_fill_(mask, 0) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The state observation, for the actor and the critic alike.""" + robot = self.robot.data + data = self.sim.data.torch + box_pos = self.box.data.root_link_pos_w + gripper_pos = robot.site_pos_w[:, self.gripper] + R_world_box = self.box.data.body_link_mat_w[:, 0].flatten(1) + R_world_gripper = robot.site_mat_w[:, self.gripper].flatten(1) + state = [ + data.qpos, # the Panda's joints, then the box's free joint + data.qvel, + gripper_pos, + R_world_gripper[:, 3:], + R_world_box[:, 3:], + box_pos - gripper_pos, + self.target - box_pos, + self.box_target_rows - R_world_box[:, :6], + robot.joint_pos_target - robot.joint_pos[:, self.robot.actuated_ids], # the joint targets' errors + ] + obs = torch.cat(state, 1) + return obs, obs + + +if __name__ == "__main__": + config = tyro.cli(PandaPickConfig) + env = PandaPick(config) # the full physics, where the policy is scored + coarse_env = PandaPick(config, coarse=config.coarse_physics) if config.coarse else None + learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig(gamma=0.97, entropy=0.02)) + actor = learner.train(env, config.minutes, coarse_env, config.coarse) + print(ppo.evaluate(env, actor, dict(episode_reward=env.episode_reward, at_target=env.at_target))) diff --git a/src/robokit/examples/rl/06_leap_reorient.py b/src/robokit/examples/rl/06_leap_reorient.py new file mode 100644 index 0000000..4a23f11 --- /dev/null +++ b/src/robokit/examples/rl/06_leap_reorient.py @@ -0,0 +1,359 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Leap reorient: a LEAP hand learns to turn a cube to goal after goal with PPO on 4096 MuJoCo Warp worlds. + +Example usage: + uv run src/robokit/examples/rl/06_leap_reorient.py --minutes 30 + uv run src/robokit/examples/rl/06_leap_reorient.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +import itertools +import math +import re +from dataclasses import dataclass +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import torch +import tyro +import warp as wp + +from robokit.assets.robots.end_effectors import leap_hand +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene +from robokit.xform.warp.torch_wrappers import ( + quaternion_invert, + quaternion_multiply, + quaternion_to_axis_angle, + quaternion_to_matrix, +) + + +@dataclass(frozen=True) +class LeapReorientConfig: + """The reorientation: its control step, episode and coarse physics, the worlds and PPO's time.""" + + control_dt: float = 0.05 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 1000 # env steps per episode: 50 s + # Coarse physics (`CoarseConfig`): only the cube, palm, fingertip pads, distal and middle links collide + coarse_physics: CoarseConfig = CoarseConfig( + collide=r"cube|robot/(palm_lower_\d+|.._tip|(dip|fingertip)(_\d)?_\d+|thumb_fingertip_\d+)", pyramidal=True + ) + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 30.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + + +class LeapReorient(Env): + """Cube reorientation on `config.worlds` worlds, in the full physics or the `coarse` one.""" + + def __init__(self, config: LeapReorientConfig = LeapReorientConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + # the hand: URDF links with soft contacts, padded fingertips, damped joints with geared-motor limits + hand_spec = mjscene.build_robot_spec(leap_hand.URDF_PATH_RIGHT, prefix="robot/") + for body in hand_spec.bodies: + for index, geom in enumerate(list(body.geoms)): + if geom.type == mujoco.mjtGeom.mjGEOM_MESH: # the URDF's fingertip meshes: replaced by the pads below + hand_spec.delete(geom) + continue + geom.name = f"{body.name}_{index}" + geom.friction = [0.2, 0.005, 0.0001] + geom.solref = [0.02, 1.5] + geom.solimp = [0.9, 0.99, 0.001, 0.5, 2.0] + # fingertip pads: boxes on the distal links, named as the sites at their tips (pad pos, pad quat, tip pos) + finger = ((-0.0013, -0.0336, 0.0145), (0.7036, 0.7096, -0.0292, -0.0252), (0, -0.05, 0.015)) + thumb = ((-0.0013, -0.0456, -0.0145), (0.7081, 0.7051, -0.0295, -0.0244), (0, -0.06, -0.015)) + distal = dict(if_tip="fingertip", mf_tip="fingertip_2", rf_tip="fingertip_3", th_tip="thumb_fingertip") + for tip, link in distal.items(): + pad_pos, pad_quat, tip_pos = thumb if tip == "th_tip" else finger + body = hand_spec.body(f"robot/{link}") + body.add_geom( + name=f"robot/{tip}", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[0.01, 0.012, 0.016], + pos=pad_pos, + quat=pad_quat, + friction=[0.7, 0.05, 0.0002], + solref=[0.02, 1.5], + solimp=[0.9, 0.99, 0.001, 0.5, 2.0], + ) + body.add_site(name=f"robot/{tip}", pos=tip_pos) + for joint in hand_spec.joints: + joint.damping = [0.2, 0.0, 0.0] + joint.armature = 0.00149376 + joint.frictionloss = 0.02 + joint.actfrclimited = mujoco.mjtLimited.mjLIMITED_TRUE + joint.actfrcrange = [-0.2196, 0.2196] # N m + # the hand palm up, the cube above it, a goal marker, a grasp site; 10 ms Euler steps + T_world_base = (0.0318, 0.0075, -0.0272, 0.0, 0.8184, 0.0, 0.5746) # the URDF base, palm up, fingers along +x + scene_spec = mjscene.build_scene_spec([(hand_spec, T_world_base)], floor=False, timestep=0.01) + cube_body = scene_spec.worldbody.add_body(name="cube", pos=[0.11, 0.0, 0.1]) + cube_body.add_freejoint(name="cube") + cube_body.add_geom( + name="cube", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[0.035] * 3, + mass=0.108, + rgba=[0.8, 0.3, 0.2, 1], + friction=[0.3, 0.05, 0.0001], + ) + goal_body = scene_spec.worldbody.add_body(name="goal", mocap=True, pos=[0.325, 0.17, 0.0475]) + goal_body.add_geom( + type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.035] * 3, contype=0, conaffinity=0, rgba=[0.2, 0.6, 0.9, 0.3] + ) + scene_spec.worldbody.add_site(name="grasp_site", pos=[0.11, 0.0, 0.03]) + for joint in hand_spec.joints: + actuator = scene_spec.add_actuator(name=joint.name, target=joint.name, trntype=mujoco.mjtTrn.mjTRN_JOINT) + actuator.set_to_position(kp=3.0, inheritrange=True) + # the palm touches only the fingertips, the finger bases never touch each other + bases = r"robot/(mcp_joint|pip|dip|thumb_temp_base|thumb_pip|thumb_dip)(_\d)?" + for body in hand_spec.bodies: + if re.fullmatch(bases, body.name): + scene_spec.add_exclude(bodyname1="robot/palm_lower", bodyname2=body.name) + knuckles = ["robot/mcp_joint", "robot/mcp_joint_2", "robot/mcp_joint_3", "robot/thumb_temp_base"] + for first, second in itertools.combinations(knuckles, 2): + scene_spec.add_exclude(bodyname1=first, bodyname2=second) + home = [0.8, 0.0, 0.8, 0.8] * 3 + [0.8, 0.8, 0.8, 0.0] # rad: index, middle, ring (mcp, rot, pip, dip), thumb + cube_home = [0.1, 0.0, 0.05, 0.810967, -0.00262895, -0.585086, -0.000254303] + scene_spec.add_key( + name="home", qpos=home + cube_home, ctrl=home, mpos=[0.25, 0.16, 0.0], mquat=[1.0, 0.0, 0.0, 0.0] + ) + scene_spec.option.integrator = mujoco.mjtIntegrator.mjINT_EULER + scene_spec.option.iterations = 5 + scene_spec.option.ls_iterations = 8 + scene_spec.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_EULERDAMP + scene_spec.option.ccd_iterations = 10 + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(self.substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="home", njmax=200, nconmax=30) # per world + self.sim = sim + sim.set_torch_stream() + robot = sim.build_entity("robot/") # the hand, no root; every actuator is the hand's, in joint order + self.robot = robot + self.device = robot.device + self.cube = sim.build_entity("cube") + self.grasp_site = mjm.site("grasp_site").id # on the world, above the palm + self.q_wxyz_world_goal = sim.data.torch.mocap_quat[:, 0] # a view: the goal marker's orientation + + # --- set up actions --- + # each action moves its joint's target (`ctrl`) by up to 0.5 rad within its range + joints = len(robot.joint_names) + ctrl_range = torch.tensor(mjm.actuator_ctrlrange[robot.actuator_ids], device=self.device, dtype=torch.float32) + self.ctrl_low = ctrl_range[:, 0] + self.ctrl_high = ctrl_range[:, 1] + self.bound = torch.ones(len(robot.actuator_ids), device=self.device) # tanh policies act in [-1, 1] + + # --- randomize --- + # fingertip friction (one draw for all four), the cube's inertia and center of mass, the hand's joints, masses + fingertips = ["th_tip", "if_tip", "mf_tip", "rf_tip"] + sim.set_random("geom_friction", ([mjm.geom(f"robot/{tip}").id for tip in fingertips], 0), 0.5, 1.0) + cube_inertia_scale = 0.8 + 0.4 * torch.rand(n, 1, device=self.device) + wp.to_torch(sim.model.body_inertia)[:, self.cube.root_body] *= cube_inertia_scale + bodies = len(robot.body_ids) + wp.to_torch(sim.model.body_mass)[:, robot.body_ids] *= 0.9 + 0.2 * torch.rand(n, bodies, device=self.device) + joint_dofs = robot.data.joint_v_adr + wp.to_torch(sim.model.dof_frictionloss)[:, joint_dofs] *= 0.5 + 1.5 * torch.rand(n, joints, device=self.device) + wp.to_torch(sim.model.dof_armature)[:, joint_dofs] *= 1.0 + 0.05 * torch.rand(n, joints, device=self.device) + wp.to_torch(sim.model.dof_damping)[:, joint_dofs] *= 0.8 + 0.4 * torch.rand(n, joints, device=self.device) + gain = wp.to_torch(sim.model.actuator_gainprm) + bias = wp.to_torch(sim.model.actuator_biasprm) + stiffness = gain[:, :, 0] * (0.8 + 0.4 * torch.rand(n, joints, device=self.device)) + gain[:, :, 0] = stiffness + bias[:, :, 1] = -stiffness + sim.set_random("body_ipos", (self.cube.root_body,), [-5e-3] * 3, [5e-3] * 3, add=True) # m; then set_const + + # --- set up rewards --- + # each term's weight; terms are per second, success pays 100 once + weights = dict( + orientation=5.0, + position=0.5, + termination=-100.0, + hand_pose=-0.5, + action_rate=-1e-3, + energy=-1e-3, + success=100.0 / config.control_dt, + ) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + + # --- set up observations --- + self.fingertips = robot.find_sites(fingertips) + self.obs_dims = (3 * joints + 9, 3 * joints + 9 + 2 * joints + 12 + 15) # the critic adds the exact state + + # --- initialize state --- + self.action = torch.zeros(n, joints, device=self.device) + self.last_action = torch.zeros(n, joints, device=self.device) + self.action_before_last = torch.zeros(n, joints, device=self.device) + self.goal_spin = torch.zeros(n, 3, device=self.device) # rad/s: the goal's, set on each success + self.q_wxyz_world_shown_goal = torch.zeros(n, 4, device=self.device) # the goal the observations show + self.tally = torch.zeros(2, n, device=self.device) # first-episode metrics (see `score`) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.in_first_episode = torch.zeros(n, dtype=torch.bool, device=self.device) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None: the reorientation has no curriculum.""" + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Move each joint target by 0.5 rad * `action` (in [-1, 1]) within its range; step; score.""" + action = action.clamp(-1.0, 1.0) + self.action_before_last.copy_(self.last_action) + self.last_action.copy_(self.action) + self.action.copy_(action) + target = self.robot.data.joint_pos_target + 0.5 * action + self.robot.set_joint_position_target(target.clamp(self.ctrl_low, self.ctrl_high)) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Rewards and terminations from the (one substep stale) cube pose; a reached goal spins on to a new one.""" + robot = self.robot.data + data = self.sim.data.torch + self.steps += 1 + + # --- rewards --- + cube_pos = self.cube.data.root_link_pos_w + q_wxyz_error = quaternion_multiply( + data.xquat[:, self.cube.root_body], quaternion_invert(self.q_wxyz_world_goal) + ) + angle_error = quaternion_to_axis_angle(q_wxyz_error).norm(dim=1) # rad + success = angle_error < 0.1 + palm_distance = (data.site_xpos[:, self.grasp_site] - cube_pos).norm(dim=1) + fell = (cube_pos[:, 2] < -0.05) | ~data.qpos.isfinite().all(1) | ~data.qvel.isfinite().all(1) + action_rate = self.action - self.last_action + action_accel = self.action - 2 * self.last_action + self.action_before_last + terms = dict( + orientation=1 - 0.9 * (angle_error - 0.2).clamp(min=0.0) / math.pi, # linear tolerances + position=(1 - 0.9 * (palm_distance - 0.02).clamp(min=0.0) / 0.05).clamp(min=0.0), + termination=fell.float(), + hand_pose=((robot.joint_pos - robot.default_joint_pos) ** 2).sum(1), + action_rate=(action_rate**2).sum(1) + (action_accel**2).sum(1), + energy=(robot.joint_vel.abs() * data.actuator_force.abs()).sum(1), + success=success.float(), + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + reward = (term_values * self.weights[:, None] * self.config.control_dt).sum(0) + + # --- goals: the observations show this one; a reached goal spins on at 1 to 5 rad/s, 20% slower each step --- + self.q_wxyz_world_shown_goal.copy_(self.q_wxyz_world_goal) + spin = 1.0 + 4.0 * torch.rand(self.n, 3, device=self.device) # rad/s + self.goal_spin.copy_(torch.where(success[:, None], spin, 0.8 * self.goal_spin)) + speed = self.goal_spin.norm(dim=1, keepdim=True) + half_angle = speed * self.config.control_dt # half of the 2-step rotation integrated per step + q_wxyz_turn = torch.cat([half_angle.cos(), self.goal_spin / speed.clamp(min=1e-9) * half_angle.sin()], 1) + q_wxyz_world_goal = quaternion_multiply(self.q_wxyz_world_goal, q_wxyz_turn) + self.q_wxyz_world_goal.copy_(q_wxyz_world_goal / q_wxyz_world_goal.norm(dim=1, keepdim=True)) + + # --- terminations --- + timeout = self.steps >= self.config.episode + # the first episode's per-step shares of the reward and successes: their means over 1000 steps, its totals + self.tally.copy_(self.config.episode * torch.stack([reward, success.float()]) * self.in_first_episode) + self.in_first_episode &= ~(fell | timeout) + return reward, fell, timeout, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Masked writes only: the hand near home, cube and goal in random orientations; a full reset starts a tally.""" + robot = self.robot + data = self.sim.data.torch + + # --- uniform random rotations (Shoemake's): the goal's and the cube's --- + draw = torch.rand(self.n, 2, 3, device=self.device) + radius_1 = (1 - draw[..., 0]).sqrt() + radius_2 = draw[..., 0].sqrt() + angle_1 = 2 * math.pi * draw[..., 1] + angle_2 = 2 * math.pi * draw[..., 2] + q_wxyz_random = torch.stack( + [radius_1 * angle_1.sin(), radius_1 * angle_1.cos(), radius_2 * angle_2.sin(), radius_2 * angle_2.cos()], -1 + ) + + # --- hand: the joints near home, their targets on them, nothing moving --- + noise = 0.1 * torch.randn(self.n, len(robot.joint_ids), device=self.device) # rad + hand = (robot.data.default_joint_pos + noise).clamp(self.ctrl_low, self.ctrl_high) + robot.write_joint_state_to_sim(hand, torch.zeros_like(hand), mask) + robot.set_joint_position_target(torch.where(mask[:, None], hand, robot.data.joint_pos_target)) + data.qacc_warmstart.copy_(torch.where(mask[:, None], 0.0, data.qacc_warmstart)) + + # --- cube: within 1 cm of its home position, turned at random, at rest --- + cube_pos = self.cube.data.default_root_state[:3] + (-0.01 + 0.02 * torch.rand(self.n, 3, device=self.device)) + self.cube.write_root_link_pose_to_sim(torch.cat([cube_pos, q_wxyz_random[:, 1]], 1), mask) + self.cube.write_root_link_velocity_to_sim(torch.zeros(self.n, 6, device=self.device), mask) + + # --- goal and episode --- + for goal in (self.q_wxyz_world_goal, self.q_wxyz_world_shown_goal): + goal.copy_(torch.where(mask[:, None], q_wxyz_random[:, 0], goal)) + for state in (self.goal_spin, self.action, self.last_action, self.action_before_last): + state.copy_(torch.where(mask[:, None], 0.0, state)) + self.steps.masked_fill_(mask, 0) + self.in_first_episode |= mask.all() + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's noisy joints, target errors, cube pose error and last action; the critic's adds exact state.""" + robot = self.robot.data + data = self.sim.data.torch + palm_pos = data.site_xpos[:, self.grasp_site] + cube_pos = self.cube.data.root_link_pos_w + q_wxyz_world_cube = data.xquat[:, self.cube.root_body] + joint_pos = robot.joint_pos + noisy_joint_pos = joint_pos + 0.05 * (2 * torch.rand_like(joint_pos) - 1) # rad + noisy_cube_pos = cube_pos + 0.02 * (2 * torch.rand_like(cube_pos) - 1) # m + noisy_q_wxyz = q_wxyz_world_cube + 0.1 * torch.randn_like(q_wxyz_world_cube) + noisy_q_wxyz = noisy_q_wxyz / noisy_q_wxyz.norm(dim=1, keepdim=True) + goal_inverse = quaternion_invert(self.q_wxyz_world_shown_goal) + noisy_rotation_error = quaternion_to_matrix(quaternion_multiply(noisy_q_wxyz, goal_inverse))[:, 1:].flatten(1) + actor = torch.cat( + [ + noisy_joint_pos, + noisy_joint_pos - robot.joint_pos_target, # from the joint targets + palm_pos - noisy_cube_pos, + noisy_rotation_error, + self.last_action, + ], + 1, + ) + fingertips = robot.site_pos_w[:, self.fingertips] - palm_pos[:, None] # the grasp site's frame is the world's + critic = [ + actor, + joint_pos, + robot.joint_vel, + fingertips.flatten(1), + palm_pos - cube_pos, + quaternion_to_matrix(quaternion_multiply(q_wxyz_world_cube, goal_inverse))[:, 1:].flatten(1), + self.cube.data.root_link_vel_w, # linear, then angular + ] + return actor, torch.cat(critic, 1) + + +if __name__ == "__main__": + config = tyro.cli(LeapReorientConfig) + env = LeapReorient(config) # the full physics, where the policy is scored + coarse_env = LeapReorient(config, coarse=config.coarse_physics) if config.coarse else None + ppo_config = ppo.PPOConfig(horizon=40, epochs=4, minibatches=32) # gamma, entropy, MLPs: the defaults + actor = ppo.PPO(env.obs_dims, len(env.bound), ppo_config).train(env, config.minutes, coarse_env, config.coarse) + # first episodes span `evaluate`'s 1000 steps: the mean of `tally`'s per-step shares is the episode total + metrics = dict(episode_reward=env.tally[0].clone, successes=env.tally[1].clone) + print(ppo.evaluate(env, actor, metrics)) diff --git a/src/robokit/examples/rl/07_aloha_handover.py b/src/robokit/examples/rl/07_aloha_handover.py new file mode 100644 index 0000000..18f63da --- /dev/null +++ b/src/robokit/examples/rl/07_aloha_handover.py @@ -0,0 +1,339 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Aloha handover: two ALOHA arms learn to pass a box between their grippers and carry it to a target, on 2048 worlds. + +Example usage: + uv run src/robokit/examples/rl/07_aloha_handover.py --minutes 10 + uv run src/robokit/examples/rl/07_aloha_handover.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +from dataclasses import dataclass +from functools import partial +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import torch +import tyro + +from robokit.assets.robots.assembly import agilex_aloha +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class HandoverConfig: + """The handover task and its training: control, gains, home, the box's start, the worlds and the learner's time.""" + + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 250 # env steps per episode + # Arm joints 1 to 6 and the gripper: position gains (N m/rad, N/m) and joint damping + gains: Tuple[Tuple[float, float], ...] = ( + (100.0, 6.0), + (150.0, 8.0), + (120.0, 6.0), + (40.0, 2.0), + (20.0, 1.0), + (20.0, 1.0), + (200.0, 10.0), + ) + # Home: each arm's joints 1 to 6 put its gripper 13 cm above the box (x -/+ 0.16 m), pointing down, fingers open + home_arm: Tuple[float, ...] = (-0.0138, 1.715, 1.7168, -1.5721, 0.0002, -0.0115) + # Coarse physics, off by default (`CoarseConfig`): only the colliding geoms, pyramidal cones + coarse_physics: CoarseConfig = CoarseConfig( + collide=r"table|box|(left|right)/(finger7|finger8|gripper)", pyramidal=True + ) + action_scale: float = 0.015 # the joint targets' change per step per unit of action + box_range: Tuple[float, float] = (0.05, 0.1) # m: the box starts up to this far from home in x and y + worlds: int = 2048 # MjWarpSim worlds + minutes: float = 10.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + + +class AlohaHandOver(Env): + """Box handover between two ALOHA arms, in the full physics or the `coarse` one.""" + + def __init__(self, config: HandoverConfig = HandoverConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + self.action_scale = config.action_scale + + # --- build scene --- + # two ALOHA arms facing each other across a table + robots = [] + for side, T_world_base in ( + ("left", (-0.469, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0)), + ("right", (0.469, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)), + ): + arm_spec = mjscene.build_robot_spec(agilex_aloha.MJCF_PATH, prefix=f"{side}/", body="fr_link1") + base = arm_spec.body(f"{side}/fr_link1") + base.pos = [0.0, 0.0, 0.0] + base.quat = [1.0, 0.0, 0.0, 0.0] + robots.append((arm_spec, T_world_base)) + scene_spec = mjscene.build_scene_spec(robots, floor=False, timestep=0.005) + table = scene_spec.worldbody.add_body(name="table", pos=[0, 0, -0.05]) + table.add_geom(name="table", type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.61, 0.37, 0.05], rgba=[0.6, 0.5, 0.4, 1.0]) + scene_spec.option.iterations = 10 + scene_spec.option.ls_iterations = 10 + scene_spec.option.impratio = 5.0 + for actuator in list(scene_spec.actuators): # replaced by joint position actuators + scene_spec.delete(actuator) + for side in ("left", "right"): + for body in scene_spec.bodies: + if body.name.startswith(f"{side}/"): + body.gravcomp = 1.0 + for geom in body.geoms: # only the gripper collides + geom.contype = 0 + geom.conaffinity = int(body.name[-1] in "678") + for i, (kp, damping) in enumerate(config.gains, 1): + joint = scene_spec.joint(f"{side}/fr_joint{i}") + joint.damping = [damping, 0.0, 0.0] + joint.armature = 0.01 + scene_spec.add_actuator( + name=f"{side}/joint{i}", + target=joint.name, + trntype=mujoco.mjtTrn.mjTRN_JOINT, + gainprm=[kp, *[0.0] * 9], + biastype=mujoco.mjtBias.mjBIAS_AFFINE, + biasprm=[0.0, -kp, *[0.0] * 8], + ctrlrange=joint.range, + ctrllimited=mujoco.mjtLimited.mjLIMITED_TRUE, + ) + finger = scene_spec.joint(f"{side}/fr_joint8") + finger.damping = [config.gains[-1][1], 0.0, 0.0] + finger.armature = 0.01 + scene_spec.add_equality( + type=mujoco.mjtEq.mjEQ_JOINT, + objtype=mujoco.mjtObj.mjOBJ_JOINT, + name1=finger.name, + name2=f"{side}/fr_joint7", + data=[0.0, 1.0, *[0.0] * 10], # the second finger follows the first + ) + scene_spec.body(f"{side}/fr_link6").add_site(name=f"{side}/gripper", pos=[0.135, 0.0, 0.0]) + scene_spec.body(f"{side}/fr_link6").first_geom().name = f"{side}/gripper" + for link in (7, 8): # each finger's contact flag against the table + scene_spec.body(f"{side}/fr_link{link}").first_geom().name = f"{side}/finger{link}" + mjscene.build_contact_sensor( + scene_spec, + f"table_contact_{side}/finger{link}_found", + (mujoco.mjtObj.mjOBJ_GEOM, "table"), + (mujoco.mjtObj.mjOBJ_GEOM, f"{side}/finger{link}"), + reduce="mindist", + ) + # a 4 x 3 x 6 cm box on the table + box_home = (-0.16, 0.0, 0.03, 1.0, 0.0, 0.0, 0.0) + box = scene_spec.worldbody.add_body(name="box", pos=box_home[:3]) + box.add_freejoint(name="box") + box.add_geom( + name="box", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[0.02, 0.015, 0.03], + mass=0.044, + rgba=[1.0, 0.0, 0.0, 1.0], + friction=[1.0, 0.05, 0.001], + condim=4, + solref=[0.01, 1.0], + ) + box.add_site(name="box_top", pos=[0.0, 0.0, 0.02]) + box.add_site(name="box_bottom", pos=[0.0, 0.0, -0.02]) + # the initial state: the arms at home with their fingers open (m), each actuator holding its joint's angle + arm_home = [*config.home_arm, 0.037, 0.037] + arm_ctrl = [*config.home_arm, 0.037] + scene_spec.add_key(name="home", qpos=[*arm_home, *arm_home, *box_home], ctrl=[*arm_ctrl, *arm_ctrl]) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(self.substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="home", njmax=128, nconmax=32) + self.sim = sim + sim.set_torch_stream() + self.left = sim.build_entity("left/") + self.right = sim.build_entity("right/") + self.box = sim.build_entity("box") # its sites: "_top", "_bottom" + self.device = self.left.device + self.table_contact = sim.build_contact_sensor("table_contact") # the fingers' + + # --- set up actions --- + # each step moves the joint targets, the left arm's then the right's, within their ranges + actuators = self.left.actuator_ids + self.right.actuator_ids + target_range = torch.tensor(mjm.actuator_ctrlrange[actuators], device=self.device, dtype=torch.float32) + self.target_low = target_range[:, 0] + self.target_high = target_range[:, 1] + self.target_low[6] = 0.01 # an aid to finger exploration: the left gripper never closes fully + self.home_target = torch.cat([arm.data.default_joint_pos[arm.actuated_ids] for arm in (self.left, self.right)]) + self.bound = torch.ones(len(actuators), device=self.device) # actions in [-1, 1] + + # --- set up rewards --- + weights = dict(gripper_box=1.0, box_handover=4.0, handover_target=8.0, no_table_collision=0.3) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.gripper = self.left.find_sites(["gripper"])[0] # the arms are alike: the same index on both + self.wrist = self.left.find_bodies(["fr_link6"])[0] # the gripper site's body, whose frame is the site's + self.fingers = [self.left.joint_names.index(f"fr_joint{i}") for i in (7, 8)] + self.box_top, self.box_bottom = self.box.find_sites(["_top", "_bottom"]) + self.box_width = float(mjm.geom("box").size[1]) + self.handover = torch.tensor((0.0, 0.0, 0.24), device=self.device) # m + + # --- set up resets --- + self.box_home = torch.tensor(box_home, device=self.device) + self.box_range = torch.tensor(config.box_range, device=self.device) + self.target_center = torch.tensor((0.2, 0.0, 0.25), device=self.device) # m + + # --- set up observations --- + # the whole state, the finger openings and 38 values on the box, the grippers, the target and the time + self.obs_dims = (mjm.nq + mjm.nv + 38,) * 2 # the critic's the same + + # --- initialize state --- + self.joint_target = torch.zeros(n, len(actuators), device=self.device) + self.box_target = torch.zeros(n, 3, device=self.device) + self.best_potential = torch.zeros(n, device=self.device) # this episode's + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.picked = torch.zeros(n, dtype=torch.bool, device=self.device) # the box lifted this episode + # `counted`, `success`: the rewards and end state of each world's first episode since a full reset + self.counted = torch.zeros(n, device=self.device) + self.success = torch.zeros(n, device=self.device) + self.alive = torch.zeros(n, dtype=torch.bool, device=self.device) # in that first episode + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None: the task has no curriculum.""" + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Move the joint targets by `action_scale` * `action`, clipped to [-1, 1], within their ranges; step; score.""" + moved = self.joint_target + self.action_scale * action.clamp(-1.0, 1.0) + self.joint_target.copy_(torch.clamp(moved, self.target_low, self.target_high)) + self.left.set_joint_position_target(self.joint_target[:, : len(self.config.gains)]) + self.right.set_joint_position_target(self.joint_target[:, len(self.config.gains) :]) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards (potential rise, handover bonus, drop penalty), terminations, timeouts and terms' means.""" + data = self.sim.data.torch + box = self.box.data + box_pos = box.root_link_pos_w + left_gripper = self.left.data.site_pos_w[:, self.gripper] + right_gripper = self.right.data.site_pos_w[:, self.gripper] + + # --- rewards --- + before = (box_pos[:, 0] < -0.1).float() # the box left of the handover point + past = (box_pos[:, 0] >= 0.0).float() # the box right of it + between = (1 - before) * (1 - past) + left_grasp = torch.exp(-10 * (box.site_pos_w[:, self.box_top] - left_gripper).norm(dim=-1)) * (before + between) + right_near = torch.exp(-10 * (box.site_pos_w[:, self.box_bottom] - right_gripper).norm(dim=-1)) + right_grasp = right_near * (between + 2 * past) # biased past the handover point + box_at_handover = torch.exp(-10 * (box_pos - self.handover).norm(dim=-1)) + left_at_handover = torch.exp(-10 * (left_gripper - self.handover).norm(dim=-1)) + box_at_target = torch.exp(-10 * (self.box_target - box_pos).norm(dim=-1)) + left_withdrawn = torch.sigmoid(-100 * left_gripper[:, 0]) # a logistic step: the left gripper left of x 0 + box_across = torch.sigmoid(100 * (box_pos[:, 0] - 0.1)) # the box right of x 0.1 m + terms = dict( + gripper_box=left_grasp + right_grasp, + box_handover=torch.maximum(box_at_handover, left_at_handover * past), + handover_target=box_at_target * right_grasp * left_withdrawn, + no_table_collision=1 - (self.table_contact.data.found > 0).any(1).float(), + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) * self.weights[:, None] + potential = term_values.sum(0) / self.weights.sum() # the weighted terms' mean + bonus = 0.02 * potential * left_withdrawn * box_across + rise = (potential - self.best_potential).clamp(min=0.0) # over its best this episode + reward = torch.where(self.steps == 0, 0.0, rise + bonus) # none on an episode's first step + self.best_potential.copy_(torch.maximum(potential, self.best_potential)) + self.picked |= box_pos[:, 2] > 0.15 # m + dropped = self.picked & (box_pos[:, 2] < 0.05) # penalized, and ends the episode + reward = reward - 0.1 * dropped.float() + + # --- terminations --- + diverged = ~(data.qpos.isfinite().all(1) & data.qvel.isfinite().all(1)) # the physics blew up + off_table = (box_pos.abs() > 1.0).any(1) | (box_pos[:, 2] < 0.0) + terminated = off_table | diverged | dropped + self.steps += 1 + timeout = self.steps >= self.config.episode + self.counted.copy_(reward * self.alive) + at_target = (self.box_target - box_pos).norm(dim=1) < 0.05 # m + self.success.copy_((self.alive & (terminated | timeout) & at_target).float()) + return reward, terminated, timeout, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Reset the masked worlds with masked writes only: the arms at home, the box moved, a new target.""" + data = self.sim.data.torch + + # --- arms: at home and at rest, their targets at home --- + for arm in (self.left, self.right): + home = arm.data.default_joint_pos + arm.write_joint_state_to_sim(home, torch.zeros_like(home), mask) + self.joint_target.copy_(torch.where(mask[:, None], self.home_target, self.joint_target)) + + # --- box: at home, moved up to `box_range` in x and y, at rest --- + box_offset = self.box_range * (2 * torch.rand(self.n, 2, device=self.device) - 1) + box_pose = torch.cat([self.box_home[:2] + box_offset, self.box_home[2:].expand(self.n, 5)], 1) + self.box.write_root_link_pose_to_sim(box_pose, mask) + self.box.write_root_link_velocity_to_sim(torch.zeros(self.n, 6, device=self.device), mask) + warmstart = data.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + + # --- episode: the target, the best potential, steps, the lift and the counted episodes --- + box_target = self.target_center + 0.15 * (2 * torch.rand(self.n, 3, device=self.device) - 1) + box_target[:, 0].clamp_(min=0.15) # up to 15 cm from the center along each axis, at x >= 0.15 m + self.box_target.copy_(torch.where(mask[:, None], box_target, self.box_target)) + self.best_potential.masked_fill_(mask, 0.0) + self.steps.masked_fill_(mask, 0) + self.picked.masked_fill_(mask, False) + self.alive.copy_(mask.all() | (self.alive & ~mask)) # a full reset starts the episodes the metrics count + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's observations, the critic's the same: the state, finger openings, sites, frames, progress.""" + data = self.sim.data.torch + left = self.left.data + right = self.right.data + box = self.box.data + obs = torch.cat( + [ + data.qpos, # both arms' joints, then the box's free joint + data.qvel, + left.joint_pos[:, self.fingers] - self.box_width, # the finger openings past the box's width + right.joint_pos[:, self.fingers] - self.box_width, + box.site_pos_w[:, self.box_top], + box.site_pos_w[:, self.box_bottom], + left.site_pos_w[:, self.gripper], + left.body_link_mat_w[:, self.wrist, 1:].flatten(1), # the frames' rows 2 and 3 + right.site_pos_w[:, self.gripper], + right.body_link_mat_w[:, self.wrist, 1:].flatten(1), + box.body_link_mat_w[:, 0, 1:].flatten(1), + box.root_link_pos_w - self.box_target, # the box's offset from the target + self.steps[:, None] / self.config.episode, # the progress + ], + 1, + ) + return obs, obs + + +if __name__ == "__main__": + config = tyro.cli(HandoverConfig) + env = AlohaHandOver(config) # the full physics, where the policy is scored + coarse_env = AlohaHandOver(config, coarse=config.coarse_physics) if config.coarse else None + learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig(gamma=0.97, hidden=(256, 256, 256))) + actor = learner.train(env, config.minutes, coarse_env, config.coarse) + # each metric times the steps: its sum over each world's first episode + episode_reward = partial(torch.mul, env.counted, config.episode) + success = partial(torch.mul, env.success, config.episode) + print(ppo.evaluate(env, actor, dict(episode_reward=episode_reward, success=success), steps=config.episode)) diff --git a/src/robokit/examples/rl/08_g1_tracking.py b/src/robokit/examples/rl/08_g1_tracking.py new file mode 100644 index 0000000..44a1d40 --- /dev/null +++ b/src/robokit/examples/rl/08_g1_tracking.py @@ -0,0 +1,424 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""G1 tracking: a Unitree G1 learns to track a LAFAN1 dance on 4096 MuJoCo Warp worlds, scored on tracking errors. + +Example usage: + uv run src/robokit/examples/rl/08_g1_tracking.py --minutes 10 + uv run src/robokit/examples/rl/08_g1_tracking.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +import functools +import urllib.request +from dataclasses import dataclass +from pathlib import Path +from typing import Optional, Tuple + +import mujoco_warp as mjw # pyright: ignore[reportMissingImports] +import numpy as np +import torch +import tyro + +from robokit.assets import ROBOKIT_HOME +from robokit.assets.robots.humanoids import unitree_g1 +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene +from robokit.xform.numpy import quaternion_to_matrix + + +@dataclass(frozen=True) +class TrackingConfig: + """The tracking task and its training: the reference motion, the worlds and the learner's time.""" + + motion_url: str = ( + "https://storage.googleapis.com/mjlab_beta/lafan_dance1_subject1.npz" # the npz, in the scene's order + ) + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 10.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 500 # env steps per episode (10 s) + # The tracked bodies + bodies: Tuple[str, ...] = ( + "pelvis", + "left_hip_roll_link", + "left_knee_link", + "left_ankle_roll_link", + "right_hip_roll_link", + "right_knee_link", + "right_ankle_roll_link", + "torso_link", + "left_shoulder_roll_link", + "left_elbow_link", + "left_wrist_yaw_link", + "right_shoulder_roll_link", + "right_elbow_link", + "right_wrist_yaw_link", + ) + ee: Tuple[int, ...] = (3, 6, 10, 13) # the ankles and wrists, whose heights end an episode + # The tracking errors and success rate + metrics: Tuple[str, ...] = ("mpkpe", "r_mpkpe", "joint_vel_error", "ee_pos_error", "ee_ori_error", "success") + # Coarse physics, off by default (`CoarseConfig`): only the feet and the floor collide + coarse_physics: CoarseConfig = CoarseConfig(collide=r"robot/(left|right)_foot[1-7]_collision|floor", pyramidal=True) + + +class G1Tracking(Env): + """G1 motion tracking on flat ground, in the full physics or the `coarse` one.""" + + def __init__(self, config: TrackingConfig = TrackingConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + self.anchor = config.bodies.index("torso_link") # the body the reference is re-anchored to + self.ee = list(config.ee) # a list, for advanced indexing + + # --- build scene --- + robot_spec = mjscene.build_robot_spec(unitree_g1.MJCF_PATH, prefix="robot/") + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)]) + scene_spec.option.iterations = 10 + scene_spec.option.ls_iterations = 20 + scene_spec.option.ccd_iterations = 50 + # the initial state, standing: each actuator holds its joint's home angle + leg = [-0.312, 0.0, 0.0, 0.669, -0.363, 0.0] # hip pitch, roll and yaw, knee, ankle pitch and roll + arms = [0.2, 0.2, 0, 0.6, 0, 0, 0, 0.2, -0.2, 0, 0.6, 0, 0, 0] # each shoulder's, elbow's and wrist's + home = np.array([0, 0, 0.76, 1, 0, 0, 0, *leg, *leg, 0, 0, 0, *arms]) # the base, the legs, the waist, the arms + model = scene_spec.compile() + scene_spec.add_key(name="init_state", qpos=home, ctrl=home[model.jnt_qposadr[model.actuator_trnid[:, 0]]]) + for sensor in [s for s in scene_spec.sensors if not s.name.startswith("robot/self_collision")]: + scene_spec.delete(sensor) # only the self-collision sensor + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="init_state", njmax=250, nconmax=35) + self.sim = sim + sim.opt.contact_sensor_maxmatch = 64 # contacts a contact sensor can match + sim.opt.warn_overflow &= ~int(mjw.OverflowType.ITERATIONS | mjw.OverflowType.LS_ITERATIONS) # capped on purpose + sim.set_torch_stream() + robot = sim.build_entity("robot/", soft_joint_pos_limit_factor=0.9) # 90% of each joint's range is penalty-free + self.robot = robot + self.device = robot.device + self.self_collision = sim.build_contact_sensor("robot/self_collision") # the G1's, from its MJCF + + # --- set up actions --- + # a joint target is its home angle + a quarter of its actuator's effort / stiffness per unit of action + effort = mjm.actuator_forcerange[robot.actuator_ids, 1] / mjm.actuator_gainprm[robot.actuator_ids, 0] # rad + self.action_scale = torch.tensor(0.25 * effort, device=self.device, dtype=torch.float32) + self.action_offset = robot.data.default_joint_pos[robot.actuated_ids] + lo, hi = robot.data.soft_joint_pos_limits[robot.actuated_ids].T + self.bound = torch.maximum(self.action_offset - lo, hi - self.action_offset) / self.action_scale # for FastSAC + + # --- randomize --- + robot.data.encoder_bias.uniform_(-0.01, 0.01) # rad + # foot friction: one draw per world for all feet + foot_geoms = [ + g for g in range(mjm.ngeom) if mjm.geom(g).name.startswith(("robot/left_foot", "robot/right_foot")) + ] + sim.set_random("geom_friction", (foot_geoms, 0), 0.3, 1.2) + torso_body = robot.body_ids[robot.find_bodies(["torso_link"])[0]] + sim.set_random("body_ipos", (torso_body,), (-0.025, -0.05, -0.05), (0.025, 0.05, 0.05), add=True) # m + + # --- load the reference motion --- + path = ROBOKIT_HOME / "motions" / Path(config.motion_url).name + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + part = path.with_suffix(".part") # a whole file or none + urllib.request.urlretrieve(config.motion_url, part) + part.replace(path) + motion = np.load(path) + self.bodies = robot.find_bodies(config.bodies) # the npz's bodies are the robot's, in its order + self.ref_joint_pos = torch.tensor(motion["joint_pos"], device=self.device, dtype=torch.float32) + self.ref_joint_vel = torch.tensor(motion["joint_vel"], device=self.device, dtype=torch.float32) + self.ref_q_wxyz_world_base = torch.tensor(motion["body_quat_w"][:, 0], device=self.device, dtype=torch.float32) + self.ref_body_pos_w = torch.tensor( + motion["body_pos_w"][:, self.bodies], device=self.device, dtype=torch.float32 + ) + ref_body_mat_w = quaternion_to_matrix(motion["body_quat_w"][:, self.bodies]) + self.ref_body_mat_w = torch.tensor(ref_body_mat_w, device=self.device, dtype=torch.float32) + ref_body_lin_vel_w = motion["body_lin_vel_w"][:, self.bodies] + self.ref_body_lin_vel_w = torch.tensor(ref_body_lin_vel_w, device=self.device, dtype=torch.float32) + ref_body_ang_vel_w = motion["body_ang_vel_w"][:, self.bodies] + self.ref_body_ang_vel_w = torch.tensor(ref_body_ang_vel_w, device=self.device, dtype=torch.float32) + self.bins = len(self.ref_joint_pos) // round(1 / config.control_dt) + 1 # adaptive sampling's: one per second + + # --- set up rewards --- + # each term's weight; terms are per second + weights = dict( + motion_global_root_pos=0.5, + motion_global_root_ori=0.5, + motion_body_pos=1.0, + motion_body_ori=1.0, + motion_body_lin_vel=1.0, + motion_body_ang_vel=1.0, + action_rate_l2=-0.1, + joint_limit=-10.0, + self_collisions=-10.0, + ) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + + # --- set up resets and pushes --- + push = (0.5, 0.5, 0.2, 0.52, 0.52, 0.78) # m/s x, y, z; rad/s roll, pitch, yaw: pushes and reset velocities + offsets = (0.05, 0.05, 0.01, 0.1, 0.1, 0.2) # m x, y, z; rad roll, pitch, yaw: reset offsets + self.push_range = torch.tensor(push, device=self.device) + self.reset_range = torch.tensor(offsets + push, device=self.device) + + # --- set up observations --- + joints = len(robot.joint_names) + actions = len(robot.actuator_ids) + # the actor's noise on each observation + noise = [0.0] * 2 * joints # the reference's joint angles and velocities + noise += [0.25] * 3 + [0.05] * 6 # the reference anchor's position (m) and orientation in the robot's + noise += [0.5] * 3 + [0.2] * 3 # base velocity (m/s), angular velocity (rad/s) + noise += [0.01] * joints + [0.5] * joints + [0.0] * actions # joint angles (rad), velocities, the last action + self.obs_noise = torch.tensor(noise, device=self.device) + self.obs_dims = (len(noise), len(noise) + 9 * len(config.bodies)) # the critic also sees each body's pose + imu_site = robot.site_ids[robot.find_sites(["imu_in_pelvis"])[0]] + self.imu_pos_b = torch.tensor(mjm.site_pos[imu_site][None], device=self.device, dtype=torch.float32) + + # --- initialize state --- + self.action = torch.zeros(n, actions, device=self.device) + self.last_action = torch.zeros(n, actions, device=self.device) + self.push_time_left = torch.zeros(n, device=self.device) + self.errors = torch.zeros(len(config.metrics), n, device=self.device) + self.fail_rate = torch.zeros(self.bins, device=self.device) + self.frame = torch.zeros(n, dtype=torch.long, device=self.device) # the reference's + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.failed = torch.zeros(n, dtype=torch.bool, device=self.device) + self.anchored_ref_pos = torch.zeros(n, len(config.bodies), 3, device=self.device) # re-anchored by `obs` + self.anchored_ref_mat = torch.zeros(n, len(config.bodies), 3, 3, device=self.device) + # each tracking error per world, for `ppo.evaluate` + self.metrics = { + name: functools.partial(torch.select, self.errors, 0, i) for i, name in enumerate(config.metrics) + } + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """No curriculum; at step 0 (a fresh start, or `ppo.evaluate`) adaptive sampling forgets its failures.""" + if step == 0: + self.fail_rate.zero_() + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Target the home angles + scale * `action`, as the biased encoders read them; step; score and push.""" + self.last_action.copy_(self.action) + self.action.copy_(action) + bias = self.robot.data.encoder_bias[:, self.robot.actuated_ids] + self.robot.set_joint_position_target(action * self.action_scale + self.action_offset - bias) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, advance the motion, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards, terminations, timeouts and each term's mean after a step, at the step's reference frame.""" + robot = self.robot.data + data = self.sim.data.torch + frame = self.frame + anchor = self.anchor + ee = self.ee + self.steps += 1 + + # --- bodies and their references --- + body_pos = robot.body_link_pos_w[:, self.bodies] + body_mat = robot.body_link_mat_w[:, self.bodies] + body_lin_vel = robot.body_link_lin_vel_w[:, self.bodies] # of each body's origin + ref_pos = self.ref_body_pos_w[frame] + ref_mat = self.ref_body_mat_w[frame] + anchored_pos = self.anchored_ref_pos + # each body's rotation from its re-anchored reference, then from its reference, R = ref @ body.T, elementwise + reference = torch.stack([self.anchored_ref_mat, ref_mat]) + twice_sin = torch.linalg.cross(reference.mT, body_mat.mT.expand_as(reference), dim=-1).sum(-2).norm(dim=-1) + twice_cos = (reference * body_mat).sum((-2, -1)) - 1 # trace(R) - 1 + angle = torch.atan2(twice_sin, twice_cos) # rad + body_angle = angle[0] + anchor_angle = angle[1][:, anchor] + + # --- rewards --- + joint_pos = robot.joint_pos + low, high = robot.soft_joint_pos_limits.T + lin_vel_error = ((self.ref_body_lin_vel_w[frame] - body_lin_vel) ** 2).sum(-1) + ang_vel_error = ((self.ref_body_ang_vel_w[frame] - robot.body_link_ang_vel_w[:, self.bodies]) ** 2).sum(-1) + terms = dict( + motion_global_root_pos=torch.exp(-((ref_pos[:, anchor] - body_pos[:, anchor]) ** 2).sum(1) / 0.3**2), + motion_global_root_ori=torch.exp(-(anchor_angle**2) / 0.4**2), + motion_body_pos=torch.exp(-((anchored_pos - body_pos) ** 2).sum(-1).mean(1) / 0.3**2), + motion_body_ori=torch.exp(-(body_angle**2).mean(1) / 0.4**2), + motion_body_lin_vel=torch.exp(-lin_vel_error.mean(1) / 1.0**2), + motion_body_ang_vel=torch.exp(-ang_vel_error.mean(1) / 3.14**2), + action_rate_l2=((self.action - self.last_action) ** 2).sum(1), + joint_limit=((low - joint_pos).clamp(min=0.0) + (joint_pos - high).clamp(min=0.0)).sum(1), + # substeps with a self-contact over 10 N + self_collisions=(self.self_collision.data.force_history.norm(dim=-1) > 10.0).any(-1).sum(0).float(), + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + reward = (term_values * self.weights[:, None] * self.config.control_dt).sum(0) + + # --- terminations --- + qvel = data.qvel + diverged = ~qvel.isfinite().all(1) | (qvel.abs() > 100.0).any(1) # the physics blew up + anchor_off = (ref_pos[:, anchor, 2] - body_pos[:, anchor, 2]).abs() > 0.25 # m + anchor_tilted = (ref_mat[:, anchor, 2, 2] - body_mat[:, anchor, 2, 2]).abs() > 0.8 + ends_off = ((anchored_pos[:, ee, 2] - body_pos[:, ee, 2]).abs() > 0.25).any(1) # the ankles' or wrists' heights + fell = anchor_off | anchor_tilted | ends_off | diverged + self.failed.copy_(fell) + timeout = self.steps >= self.config.episode + + # --- tracking errors, for `metrics` --- + errors = [ + (ref_pos - body_pos).norm(dim=-1).mean(1), + (anchored_pos - body_pos).norm(dim=-1).mean(1), + (self.ref_joint_vel[frame] - robot.joint_vel).pow(2).mean(1).sqrt(), + (anchored_pos - body_pos)[:, ee].norm(dim=-1).mean(1), + body_angle[:, ee].mean(1), + (timeout & ~fell) * float(self.config.episode), # success, summed over an episode by `ppo.evaluate`'s means + ] + self.errors.copy_(torch.stack(errors)) + + # --- push: every 1 to 3 s, a random twist added to the base's velocity --- + self.push_time_left -= self.config.control_dt + push = self.push_time_left < 1e-6 + next_push = 1.0 + 2.0 * torch.rand(self.n, device=self.device) # s + self.push_time_left.copy_(torch.where(push, next_push, self.push_time_left)) + kick = (2 * torch.rand(self.n, 6, device=self.device) - 1) * self.push_range + self.robot.write_root_link_velocity_to_sim(robot.root_link_vel_w + kick, push) + return reward, fell, timeout, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Start the masked worlds at a perturbed frame drawn by adaptive sampling; advance the other frames.""" + robot = self.robot + data = self.sim.data.torch + frames = len(self.ref_joint_pos) + bins = self.bins + + # --- adaptive sampling: count failures (terminated, not timed out) at their frames' bins; draw frames --- + failed = (mask & self.failed).float() + failed_bins = (self.frame * bins // frames).clamp(max=bins - 1) + failures = torch.zeros(bins, device=self.device).scatter_add_(0, failed_bins, failed) + # sampling weights: 1 s bins of the motion, by their failure rates + cdf = (self.fail_rate + 0.1 / bins).cumsum(0) + drawn = torch.searchsorted(cdf, torch.rand(self.n, 1, device=self.device) * cdf[-1]).squeeze(1) + drawn_bin = drawn.clamp(max=bins - 1) + start = ( + ((drawn_bin + torch.rand(self.n, device=self.device)) / bins * (frames - 1)).long().clamp(max=frames - 2) + ) + self.fail_rate.copy_(0.001 * failures + 0.999 * self.fail_rate) + wrap = (self.frame + 1 >= frames) & ~mask # past the motion's end: a drawn frame too, in the same episode + restart = mask | wrap + + # --- robot: the start frame's base pose and velocity and joint state, perturbed --- + offset = (2 * torch.rand(self.n, 12, device=self.device) - 1) * self.reset_range + cos_roll, cos_pitch, cos_yaw = (offset[:, 3:6] / 2).cos().T + sin_roll, sin_pitch, sin_yaw = (offset[:, 3:6] / 2).sin().T + q_wxyz_tilt = torch.stack( + [ + cos_yaw * cos_roll * cos_pitch + sin_yaw * sin_roll * sin_pitch, + cos_yaw * sin_roll * cos_pitch - sin_yaw * cos_roll * sin_pitch, + cos_yaw * cos_roll * sin_pitch + sin_yaw * sin_roll * cos_pitch, + sin_yaw * cos_roll * cos_pitch - cos_yaw * sin_roll * sin_pitch, + ], + 1, + ) + q_wxyz_ref = self.ref_q_wxyz_world_base[start] + # the Hamilton product: the reference's orientation, then the tilt + w_tilt = q_wxyz_tilt[:, :1] + xyz_tilt = q_wxyz_tilt[:, 1:] + w_ref = q_wxyz_ref[:, :1] + xyz_ref = q_wxyz_ref[:, 1:] + w_base = w_tilt * w_ref - (xyz_tilt * xyz_ref).sum(1, keepdim=True) + xyz_base = w_tilt * xyz_ref + w_ref * xyz_tilt + torch.cross(xyz_tilt, xyz_ref, dim=1) + q_wxyz_world_base = torch.cat([w_base, xyz_base], 1) + t_world_base = self.ref_body_pos_w[start, 0] + offset[:, :3] + robot.write_root_link_pose_to_sim(torch.cat([t_world_base, q_wxyz_world_base], 1), restart) + lin_vel_w = self.ref_body_lin_vel_w[start, 0] + offset[:, 6:9] + ang_vel_w = self.ref_body_ang_vel_w[start, 0] + offset[:, 9:] + robot.write_root_link_velocity_to_sim(torch.cat([lin_vel_w, ang_vel_w], 1), restart) + joint_offset = 0.1 * (2 * torch.rand(self.n, len(robot.joint_names), device=self.device) - 1) # rad + joint_pos = (self.ref_joint_pos[start] + joint_offset).clamp(*robot.data.soft_joint_pos_limits.T) + robot.write_joint_state_to_sim(joint_pos, self.ref_joint_vel[start], restart) + warmstart = data.qacc_warmstart + warmstart.copy_(torch.where(restart[:, None], 0.0, warmstart)) + + # --- episode: actions, the reference frame, steps and the next push --- + for state in (self.action, self.last_action): + state.copy_(torch.where(mask[:, None], 0.0, state)) + self.frame.copy_(torch.where(mask, start + 1, torch.where(wrap, start, self.frame + 1))) + self.steps.masked_fill_(mask, 0) + next_push = 1.0 + 2.0 * torch.rand(self.n, device=self.device) # s + self.push_time_left.copy_(torch.where(mask, next_push, self.push_time_left)) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's (noisy, encoder-biased) and the critic's observations, after re-anchoring the reference.""" + robot = self.robot.data + frame = self.frame + anchor = self.anchor + ref_pos = self.ref_body_pos_w[frame] + ref_mat = self.ref_body_mat_w[frame] + body_pos = robot.body_link_pos_w[:, self.bodies] + body_mat = robot.body_link_mat_w[:, self.bodies] + + # --- re-anchor the reference: to the robot's anchor body's horizontal position and heading --- + R_heading = body_mat[:, anchor] @ ref_mat[:, anchor].mT + yaw = torch.atan2(R_heading[:, 1, 0], R_heading[:, 0, 0]) + zero = torch.zeros_like(yaw) + one = torch.ones_like(yaw) + R_yaw = torch.stack([yaw.cos(), -yaw.sin(), zero, yaw.sin(), yaw.cos(), zero, zero, zero, one], 1) + R_yaw = R_yaw.view(self.n, 1, 3, 3) + origin = torch.cat([body_pos[:, anchor, :2], ref_pos[:, anchor, 2:]], 1)[:, None] + self.anchored_ref_pos.copy_(origin + (R_yaw @ (ref_pos - ref_pos[:, anchor, None])[..., None]).squeeze(-1)) + self.anchored_ref_mat.copy_(R_yaw @ ref_mat) + + # --- observations --- + R_anchor_world = body_mat[:, anchor].mT + anchor_pos = (R_anchor_world @ (ref_pos[:, anchor] - body_pos[:, anchor])[..., None]).squeeze(-1) + anchor_ori = (R_anchor_world @ ref_mat[:, anchor])[..., :2].flatten(1) # the reference anchor's, two columns + body_pos_b = (R_anchor_world[:, None] @ (body_pos - body_pos[:, anchor, None])[..., None]).flatten(1) + body_ori_b = (R_anchor_world[:, None] @ body_mat)[..., :2].flatten(1) + imu_lin_vel_b = robot.root_link_lin_vel_b + torch.linalg.cross(robot.root_link_ang_vel_b, self.imu_pos_b) + command = torch.cat([self.ref_joint_pos[frame], self.ref_joint_vel[frame]], 1) + actor = [ + command, + anchor_pos, + anchor_ori, + imu_lin_vel_b, + robot.root_link_ang_vel_b, + robot.joint_pos_biased - robot.default_joint_pos, + robot.joint_vel, + self.action, + ] + critic = [ + command, + anchor_pos, + anchor_ori, + body_pos_b, + body_ori_b, + imu_lin_vel_b, + robot.root_link_ang_vel_b, + robot.joint_pos - robot.default_joint_pos, + robot.joint_vel, + self.action, + ] + noise = self.obs_noise * (2 * torch.rand(self.n, len(self.obs_noise), device=self.device) - 1) + return torch.cat(actor, 1) + noise, torch.cat(critic, 1) + + +if __name__ == "__main__": + config = tyro.cli(TrackingConfig) + env = G1Tracking(config) # the full physics, where the policy is scored + coarse_env = G1Tracking(config, coarse=config.coarse_physics) if config.coarse else None + learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig(entropy=0.005)) + actor = learner.train(env, config.minutes, coarse_env, config.coarse) + print(ppo.evaluate(env, actor, env.metrics)) diff --git a/src/robokit/examples/rl/09_go1_handstand.py b/src/robokit/examples/rl/09_go1_handstand.py new file mode 100644 index 0000000..75eeab6 --- /dev/null +++ b/src/robokit/examples/rl/09_go1_handstand.py @@ -0,0 +1,276 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Go1 handstand: a Unitree Go1 learns to balance on its front feet on 4096 MuJoCo Warp worlds. + +Example usage: + uv run src/robokit/examples/rl/09_go1_handstand.py --minutes 5 + uv run src/robokit/examples/rl/09_go1_handstand.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +from dataclasses import dataclass +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import torch +import tyro + +from robokit.assets.robots.quadrupeds import unitree_go1 +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class HandstandConfig: + """The handstand task and its training: the control rate, the trunk's height, the worlds and the learner's time.""" + + action_scale: float = 0.3 # rad: the joint targets' change per step per unit of action + height: float = 0.55 # m: the trunk height the height reward grows up to + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 5.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 500 # env steps per episode (10 s) + legs: Tuple[str, ...] = ("FR", "FL", "RR", "RL") # leg order + # The front legs' hip, thigh and calf geoms: on the floor, they end an episode + front: Tuple[str, ...] = tuple( + f"{leg}_{part}_collision{k}" + for leg in ("FL", "FR") + for part, k in (("calf", 1), ("calf", 2), ("thigh", 1), ("thigh", 2), ("thigh", 3), ("hip", "")) + ) + # Coarse physics, off by default (`CoarseConfig`): only the floor, feet, trunk and front legs + coarse_physics: CoarseConfig = CoarseConfig( + collide="floor|robot/(FR|FL|RR|RL)_foot_collision|robot/trunk_collision|robot/F[LR]_.*", pyramidal=True + ) + + +class Go1Handstand(Env): + """Go1 handstand on flat ground, in the full physics or the `coarse` one.""" + + def __init__(self, config: HandstandConfig = HandstandConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + self.action_scale = config.action_scale + self.height = config.height + + # --- build scene --- + # the Go1 on a floor: 4 ms Euler steps, 1 solver iteration + robot_spec = mjscene.build_robot_spec(unitree_go1.MJCF_PATH, prefix="robot/") + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)], timestep=0.004) + scene_spec.geom("floor").friction = (0.6, 0.005, 1e-4) + scene_spec.option.integrator = mujoco.mjtIntegrator.mjINT_EULER + scene_spec.option.iterations = 1 + scene_spec.option.ls_iterations = 5 + scene_spec.option.ccd_iterations = 20 + scene_spec.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_EULERDAMP + for ( + geom + ) in scene_spec.geoms: # feet and floor: 3D contacts, the floor's friction winning; the rest frictionless + geom.condim = 3 if geom.name == "floor" or geom.name.endswith("_foot_collision") else 1 + geom.priority = 1 if geom.name == "floor" else 0 + for actuator in list(scene_spec.actuators): # replaced by position actuators in joint order + scene_spec.delete(actuator) + for leg in config.legs: + for part, frictionloss, force in (("hip", 0.3, 23.7), ("thigh", 0.3, 23.7), ("calf", 1.0, 35.55)): + joint = scene_spec.joint(f"robot/{leg}_{part}_joint") + joint.damping = [0.5, 0.0, 0.0] + joint.armature = 0.005 + joint.frictionloss = frictionloss + actuator = scene_spec.add_actuator( + name=joint.name, target=joint.name, trntype=mujoco.mjtTrn.mjTRN_JOINT + ) + actuator.set_to_position(kp=35.0) + actuator.forcelimited = mujoco.mjtLimited.mjLIMITED_TRUE + actuator.forcerange = [-force, force] + actuator.ctrllimited = mujoco.mjtLimited.mjLIMITED_TRUE + actuator.ctrlrange = joint.range + scene_spec.add_sensor( + name="accelerometer", + type=mujoco.mjtSensor.mjSENS_ACCELEROMETER, + objtype=mujoco.mjtObj.mjOBJ_SITE, + objname="robot/imu", + ) + floor = (mujoco.mjtObj.mjOBJ_GEOM, "floor") + for leg in config.legs: # each foot's contact flag against the floor + foot = (mujoco.mjtObj.mjOBJ_GEOM, f"robot/{leg}_foot_collision") + mjscene.build_contact_sensor(scene_spec, f"foot_contact_{leg}_found", foot, floor, reduce="mindist") + for part in config.front: # each front-leg geom's contact flag against the floor + geom = (mujoco.mjtObj.mjOBJ_GEOM, f"robot/{part}") + mjscene.build_contact_sensor(scene_spec, f"leg_contact_{part}_found", geom, floor, reduce="mindist") + home = [0.1, 0.9, -1.8, -0.1, 0.9, -1.8] * 2 # standing joint angles (rad), in leg order + scene_spec.add_key(name="home", qpos=[0.0, 0.0, 0.278, 1.0, 0.0, 0.0, 0.0, *home], ctrl=home) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="home", njmax=200, nconmax=30) + self.sim = sim + sim.set_torch_stream() + robot = sim.build_entity("robot/", soft_joint_pos_limit_factor=0.9) # 90% of each joint's range is penalty-free + self.robot = robot + self.device = robot.device + self.feet_contact = sim.build_contact_sensor("foot_contact") # touching the floor costs + self.leg_contact = sim.build_contact_sensor( + "leg_contact" + ) # a front leg's hip, thigh or calf on the floor ends it + + # --- randomize --- + sim.set_random("geom_friction", (mjm.geom("floor").id, 0), 0.4, 1.0) + dofs = robot.data.joint_v_adr.tolist() + frictionloss = mjm.dof_frictionloss[dofs] + sim.set_random("dof_frictionloss", (dofs,), 0.9 * frictionloss, 1.1 * frictionloss) + armature = mjm.dof_armature[dofs] + sim.set_random("dof_armature", (dofs,), armature, 1.05 * armature) + joints = len(robot.joint_names) + sim.set_random("qpos0", (robot.data.joint_q_adr.tolist(),), [-0.05] * joints, [0.05] * joints, add=True) # rad + trunk_body = robot.body_ids[robot.find_bodies(["trunk"])[0]] + sim.set_random("body_ipos", (trunk_body,), [-0.05] * 3, [0.05] * 3, add=True) # m: the center of mass + mass = mjm.body_mass[robot.body_ids] + sim.set_random("body_mass", (robot.body_ids,), 0.9 * mass, 1.1 * mass) + sim.set_random("body_mass", (trunk_body,), -1.0, 1.0, add=True) # kg + + # --- set up rewards --- + # each term's weight; terms are per second + weights = dict(height=1.0, orientation=1.0, contact=-0.1, dof_pos_limits=-0.5, pose=-0.1) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.trunk = robot.find_bodies(["trunk"])[0] + self.imu = robot.find_sites(["imu"])[0] # on the trunk, its frame the trunk's + self.hind_legs = [i for i, name in enumerate(robot.joint_names) if name.startswith(("RR", "RL"))] + + # --- set up observations --- + actions = len(robot.actuator_ids) + # the actor's noise on each observation + noise = [0.1] * 3 + [0.2] * 3 + [0.05] * 3 # IMU velocity (m/s), angular velocity (rad/s), gravity + noise += [0.01] * joints + [1.5] * joints # joint angles (rad) and velocities (rad/s) + self.obs_noise = torch.tensor(noise, device=self.device) + actor_dims = len(noise) + actions # and the last action but one + # the critic also sees 4 more velocities and accelerations, the joints, their torques and the trunk's height + self.obs_dims = (actor_dims, actor_dims + 4 * 3 + 2 * joints + actions + 1) + imu_site = robot.site_ids[self.imu] + self.imu_pos_b = torch.tensor(mjm.site_pos[imu_site][None], device=self.device, dtype=torch.float32) + self.accelerometer = sim.get_sensor("accelerometer") # (nworld, 3) view: the IMU's + self.bound = torch.ones(actions, device=self.device) # actions in [-1, 1] + + # --- initialize state --- + self.joint_target = torch.zeros(n, actions, device=self.device) + self.action = torch.zeros(n, actions, device=self.device) + self.last_action = torch.zeros(n, actions, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.tally = torch.zeros(n, device=self.device) # per-step shares of each world's first episode's return + self.live = torch.zeros(n, dtype=torch.bool, device=self.device) # in the first episode since a full reset + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None: the task has no curriculum.""" + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Move the joint targets by `action_scale` * `action`, clipped to [-1, 1]; step; score.""" + action = action.clamp(-1.0, 1.0) + self.last_action.copy_(self.action) + self.action.copy_(action) + self.joint_target += self.action_scale * action + self.robot.set_joint_position_target(self.joint_target) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards, terminations, timeouts and each reward term's mean after a step.""" + robot = self.robot.data # terms and terminations read the same derived quantities, one substep stale + self.steps += 1 + + # --- rewards --- + R_world_trunk = robot.body_link_mat_w[:, self.trunk] + joint_pos = robot.joint_pos + low, high = robot.soft_joint_pos_limits.T + terms = dict( + height=torch.exp(robot.site_pos_w[:, self.imu, 2].clamp(max=self.height) - self.height), # m: the trunk's + orientation=(0.5 - 0.5 * R_world_trunk[:, 2, 0]) ** 2, # the trunk's forward axis down + contact=(self.feet_contact.data.found > 0).any(1).float(), + dof_pos_limits=((low - joint_pos).clamp(min=0.0) + (joint_pos - high).clamp(min=0.0)).sum(1), + pose=((joint_pos - robot.default_joint_pos)[:, self.hind_legs] ** 2).sum(1), + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + reward = ((term_values * self.weights[:, None]).sum(0) * self.config.control_dt).clamp(0.0, 1e4) + + # --- terminations --- + upside_down = R_world_trunk[:, 2, 2] < -0.25 + leg_down = (self.leg_contact.data.found > 0).any(1) + diverged = ~self.sim.data.torch.qvel.isfinite().all(1) # the physics blew up + fell = upside_down | leg_down | diverged + timeout = self.steps >= self.config.episode + self.tally.copy_(self.config.episode * reward * self.live) + self.live &= ~(fell | timeout) + return reward, fell, timeout, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Reset the masked worlds with masked writes only: standing at home, moved, turned and moving at random.""" + robot = self.robot + data = self.sim.data.torch + + # --- robot: the base at home, moved, turned and moving; the joints at home and at rest --- + offset = 0.5 * (2 * torch.rand(self.n, 8, device=self.device) - 1) # m x, y; m/s and rad/s, world frame + yaw = 3.14 * (2 * torch.rand(self.n, device=self.device) - 1) + zero = torch.zeros_like(yaw) + q_wxyz_world_base = torch.stack([(yaw / 2).cos(), zero, zero, (yaw / 2).sin()], 1) # home's is the identity + t_world_base = robot.data.default_root_state[:3] + torch.stack([offset[:, 0], offset[:, 1], zero], 1) + robot.write_root_link_pose_to_sim(torch.cat([t_world_base, q_wxyz_world_base], 1), mask) + robot.write_root_link_velocity_to_sim(offset[:, 2:], mask) + home = robot.data.default_joint_pos + robot.write_joint_state_to_sim(home, torch.zeros_like(home), mask) + self.joint_target.copy_(torch.where(mask[:, None], home, self.joint_target)) + warmstart = data.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + + # --- episode: actions, steps and the tally --- + for state in (self.action, self.last_action): + state.copy_(torch.where(mask[:, None], 0.0, state)) + self.steps.masked_fill_(mask, 0) + self.live |= mask.all() # a full reset (as `ppo.evaluate`'s) starts tallying first episodes + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's (noisy; its last action a step older) and the critic's observations.""" + robot = self.robot.data + ang_vel_b = robot.root_link_ang_vel_b + # the IMU's velocities come from the base's, exact after a reset too + imu_lin_vel_b = robot.root_link_lin_vel_b + torch.linalg.cross(ang_vel_b, self.imu_pos_b) + joint_pos = robot.joint_pos + joint_vel = robot.joint_vel + sensed = [imu_lin_vel_b, ang_vel_b, robot.projected_gravity_b, joint_pos - robot.default_joint_pos, joint_vel] + sensed = torch.cat(sensed, 1) + noise = self.obs_noise * (2 * torch.rand_like(sensed) - 1) + actor = torch.cat([sensed + noise, self.last_action], 1) + fresh = self.steps.eq(0)[:, None] # actuator forces are stale after a reset: zero, at rest + joint_torque = torch.where(fresh, 0.0, robot.qfrc_actuator) + acceleration = self.accelerometer + height = robot.site_pos_w[:, self.imu, 2:] + ang_vel_w = robot.root_link_vel_w[:, 3:] + critic = [actor, ang_vel_b, acceleration, imu_lin_vel_b, ang_vel_w, joint_pos, joint_vel, joint_torque, height] + return actor, torch.cat(critic, 1) + + +if __name__ == "__main__": + config = tyro.cli(HandstandConfig) + env = Go1Handstand(config) # the full physics, where the policy is scored + coarse_env = Go1Handstand(config, coarse=config.coarse_physics) if config.coarse else None + ppo_config = ppo.PPOConfig(entropy=0.001, lr=3e-4, lr_range=(3e-4, 3e-4)) # a fixed rate + actor = ppo.PPO(env.obs_dims, len(env.bound), ppo_config).train(env, config.minutes, coarse_env, config.coarse) + # a world's first episode spans at most `config.episode` steps: the mean of its per-step shares is its return + print(ppo.evaluate(env, actor, dict(episode_reward=env.tally.clone), steps=config.episode)) diff --git a/src/robokit/examples/rl/10_h1_gait.py b/src/robokit/examples/rl/10_h1_gait.py new file mode 100644 index 0000000..367e93d --- /dev/null +++ b/src/robokit/examples/rl/10_h1_gait.py @@ -0,0 +1,305 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""H1 gait: a Unitree H1 learns to walk at joystick commands with a given step rate and swing height, on 8192 worlds. + +Example usage: + uv run src/robokit/examples/rl/10_h1_gait.py --minutes 5 + uv run src/robokit/examples/rl/10_h1_gait.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +import math +import re +from dataclasses import dataclass +from functools import partial +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import numpy as np +import torch +import tyro + +from robokit.assets.robots.humanoids import unitree_h1 +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class GaitConfig: + """The gait task and its training: the control rate, the observation noise, the worlds and the learner's time.""" + + action_scale: float = 0.3 # rad: the joint targets' change per step per unit of action + noise_level: float = 0.6 # the scale of the actor's observation noise + worlds: int = 8192 # MjWarpSim worlds + minutes: float = 5.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 1000 # env steps per episode (20 s) + # Coarse physics, off by default (`CoarseConfig`): only the feet and the floor collide + coarse_physics: CoarseConfig = CoarseConfig(collide=r"floor|robot/(left|right)_foot[1-3]", pyramidal=True) + # Home joint angles: each leg's hip yaw, roll, pitch, knee and ankle, then the torso and the arms + home_joint_pos: Tuple[float, ...] = (0.0, 0.0, -0.267, 0.8, -0.543) * 2 + ( + 0.0, + 0.0, + 0.2, + 0.0, + 1.14, + 0.0, + -0.2, + 0.0, + 1.14, + ) + + +class H1Gait(Env): + """H1 joystick gait tracking on flat ground, in the full physics or the `coarse` one.""" + + def __init__(self, config: GaitConfig = GaitConfig(), coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + self.action_scale = config.action_scale + + # --- build scene --- + # the H1 URDF with position actuators; only its foot capsules collide, its meshes dropped + robot_spec = mjscene.build_robot_spec(unitree_h1.URDF_PATH, prefix="robot/") + for geom in list(robot_spec.geoms): + robot_spec.delete(geom) + for mesh in list(robot_spec.meshes): + robot_spec.delete(mesh) + for joint in robot_spec.joints: + joint.damping = [1.0, 0.0, 0.0] + joint.armature = 0.1 + leg = any(part in joint.name for part in ("hip", "knee", "ankle")) + actuator = robot_spec.add_actuator(name=joint.name, target=joint.name, trntype=mujoco.mjtTrn.mjTRN_JOINT) + actuator.ctrlrange = joint.range + actuator.forcerange = joint.actfrcrange + actuator.set_to_position(kp=800.0 if leg else 400.0, dampratio=1.0) # the legs, then the torso and arms + robot_spec.body("robot/pelvis").add_freejoint(name="robot/root") + robot_spec.body("robot/imu_link").add_site(name="robot/imu") + capsules = ( # heel, sole, toe in the ankle frame + (-0.035, 0, -0.056, 0.02, 0, -0.045), + (0.02, 0, -0.045, 0.115, 0, -0.056), + (0.14, -0.03, -0.056, 0.14, 0.03, -0.056), + ) + for side in ("left", "right"): + ankle = robot_spec.body(f"robot/{side}_ankle_link") + ankle.add_site(name=f"robot/{side}_foot", pos=[0.02, 0.0, -0.045]) + for i, fromto in enumerate(capsules): + ankle.add_geom( + name=f"robot/{side}_foot{i + 1}", + type=mujoco.mjtGeom.mjGEOM_CAPSULE, + size=[0.014, 0, 0], + fromto=fromto, + contype=0, + conaffinity=1, + mass=0.0, + ) + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)], timestep=0.004) + scene_spec.option.integrator = mujoco.mjtIntegrator.mjINT_EULER # 4 ms Euler steps, 1 solver iteration + scene_spec.option.iterations = 1 + scene_spec.option.ls_iterations = 5 + scene_spec.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_EULERDAMP + floor = (mujoco.mjtObj.mjOBJ_GEOM, "floor") + for side in ("left", "right"): # each foot capsule's contact flag against the floor + for i in (1, 2, 3): + capsule = (mujoco.mjtObj.mjOBJ_GEOM, f"robot/{side}_foot{i}") + name = f"foot_contact_{side}_foot{i}_found" + mjscene.build_contact_sensor(scene_spec, name, capsule, floor, reduce="mindist") + home = np.concatenate([[0.0, 0.0, 0.97, 1.0, 0.0, 0.0, 0.0], config.home_joint_pos]) + scene_spec.add_key(name="home", qpos=home, ctrl=config.home_joint_pos) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.substeps = round(config.control_dt / mjm.opt.timestep) + sim = MjWarpSim(mjm, n, substeps=self.substeps, key="home", njmax=51, nconmax=12) + self.sim = sim + sim.set_torch_stream() + robot = sim.build_entity("robot/") + self.robot = robot + self.device = robot.device + self.feet_contact = sim.build_contact_sensor("foot_contact") # the left foot's 3 capsules, then the right's + + # --- set up actions --- + # each step moves the joint targets within the joint ranges, from zero after a reset + target_range = torch.tensor(mjm.actuator_ctrlrange[robot.actuator_ids], device=self.device, dtype=torch.float32) + self.target_low = target_range[:, 0] + self.target_high = target_range[:, 1] + self.bound = torch.ones(len(robot.actuator_ids), device=self.device) # actions in [-1, 1] + + # --- set up rewards --- + # each term's weight; terms are per second + weights = dict(feet_phase=5.0, tracking_lin_vel=3.5, tracking_ang_vel=0.75, pose=-2.5, action_rate=-0.01) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.posed = [i for i, name in enumerate(robot.joint_names) if not re.search("hip_pitch|knee", name)] + self.pose_weights = torch.tensor([5.0] * 6 + [2.0] + [1.0] * 8, device=self.device) # legs, torso, arms + self.feet = robot.find_sites(["left_foot", "right_foot"]) + self.imu_body = robot.find_bodies(["imu_link"])[0] # on the torso; the IMU site's frame is its + self.imu_site = robot.find_sites(["imu"])[0] + + # --- set up commands and gaits --- + self.command_scale = torch.tensor([1.5, 0.5, 1.0], device=self.device) # m/s forward, lateral; rad/s yaw + self.start_phase = torch.tensor([0.0, math.pi], device=self.device) # the left foot's, the right's + + # --- set up observations --- + joints = len(robot.joint_names) + # the actor's noise on each observation + noise = [0.2] * 3 + [0.05] * 3 # gyro (rad/s), up vector + noise += [0.01] * joints + [1.5] * joints # joint angles (rad) and velocities (rad/s) + self.obs_noise = config.noise_level * torch.tensor(noise, device=self.device) + # then the last action but one, the command, joint velocities, target errors, foot contacts, phases and gait + self.obs_dims = (len(noise) + 3 * joints + 3 + 2 + 7,) * 2 # the critic's the same + + # --- initialize state --- + self.joint_target = torch.zeros(n, joints, device=self.device) + self.action = torch.zeros(n, joints, device=self.device) + self.last_action = torch.zeros(n, joints, device=self.device) + self.action_before_last = torch.zeros(n, joints, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.command = torch.zeros(n, 3, device=self.device) + self.phase = torch.zeros(n, 2, device=self.device) # rad: each foot's + self.gait = torch.zeros(n, 3, device=self.device) # step rate (Hz), gait (0: walk), swing height (m) + # `counted`: the rewards of each world's first episode since a full reset + self.counted = torch.zeros(n, device=self.device) + self.alive = torch.zeros(n, dtype=torch.bool, device=self.device) # in that first episode + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None: the task has no curriculum.""" + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Move the joint targets by `action_scale` * `action`, clipped to [-1, 1], within the joint ranges; step.""" + action = action.clamp(-1.0, 1.0) + self.action_before_last.copy_(self.last_action) + self.last_action.copy_(self.action) + self.action.copy_(action) + moved = self.joint_target + self.action_scale * action + self.joint_target.copy_(moved.clamp(self.target_low, self.target_high)) + self.robot.set_joint_position_target(self.joint_target) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds, then refresh the kinematics the observations read.""" + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The rewards, terminations, timeouts and each reward term's mean after a step.""" + robot = self.robot.data + self.steps += 1 + + # --- command and phases --- + command = self.command_scale * (2 * torch.rand(self.n, 3, device=self.device) - 1) + command = torch.where(command.abs() < 0.1, 0.0, command) # each zeroed under 0.1 + # resampled once, after step 501 + self.command.copy_(torch.where((self.steps == 502)[:, None], command, self.command)) + phase = self.phase + 2 * math.pi * self.config.control_dt * self.gait[:, :1] + phase = torch.remainder(phase + math.pi, 2 * math.pi) - math.pi # wrapped to [-pi, pi) + self.phase.copy_(torch.where((self.steps > 1)[:, None], phase, self.phase)) + + # --- IMU --- + R_world_imu = robot.body_link_mat_w[:, self.imu_body] + imu_lin_vel_b = torch.einsum("nji,nj->ni", R_world_imu, robot.site_lin_vel_w[:, self.imu_site]) + imu_ang_vel_b = torch.einsum("nji,nj->ni", R_world_imu, robot.body_link_ang_vel_w[:, self.imu_body]) + + # --- rewards --- + # each foot's swing height: a cubic Bezier up, then down + swing = (self.phase + math.pi) / (2 * math.pi) + height = self.gait[:, 2:] + up = 2 * swing + down = 2 * swing - 1 + rising = height * (up**3 + 3 * up**2 * (1 - up)) + falling = height - height * (down**3 + 3 * down**2 * (1 - down)) + swing_height = torch.where(swing <= 0.5, rising, falling) + joint_error = robot.joint_pos - robot.default_joint_pos + action_rate = ((self.last_action - self.action_before_last) ** 2).sum(1) + action_change = ((self.last_action - 2 * self.action_before_last + self.action) ** 2).sum(1) + terms = dict( + feet_phase=torch.exp(-((robot.site_pos_w[:, self.feet, 2] - swing_height) ** 2).sum(1) / 0.01), + tracking_lin_vel=torch.exp(-((self.command[:, :2] - imu_lin_vel_b[:, :2]) ** 2).sum(1) / 0.5), + tracking_ang_vel=torch.exp(-((self.command[:, 2] - imu_ang_vel_b[:, 2]) ** 2) / 0.5), + pose=(joint_error[:, self.posed] ** 2 * self.pose_weights).sum(1), + action_rate=action_rate + action_change, + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + reward = ((term_values * self.weights[:, None]).sum(0) * self.config.control_dt).clamp(min=0.0) + + # --- terminations --- + data = self.sim.data.torch + diverged = ~(data.qpos.isfinite().all(1) & data.qvel.isfinite().all(1)) # the physics blew up + joint_pos = robot.joint_pos + out_of_range = ((joint_pos < self.target_low) | (joint_pos > self.target_high)).any(1) + tilted = R_world_imu[:, 2, 2] < 0.85 # the torso's up vector tilted over 32 degrees + terminated = out_of_range | tilted | diverged + self.counted.copy_(reward * self.alive) + return reward, terminated, self.steps >= self.config.episode, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Reset the masked worlds with masked writes only: at home and at rest, zero joint targets, a new gait.""" + robot = self.robot + + # --- robot: at home and at rest, the joint targets zero --- + robot.write_root_link_pose_to_sim(robot.data.default_root_state[:7].expand(self.n, 7), mask) + robot.write_root_link_velocity_to_sim(torch.zeros(self.n, 6, device=self.device), mask) + home = robot.data.default_joint_pos + robot.write_joint_state_to_sim(home, torch.zeros_like(home), mask) + warmstart = self.sim.data.torch.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + for state in (self.joint_target, self.action, self.last_action, self.action_before_last): + state.copy_(torch.where(mask[:, None], 0.0, state)) + + # --- gait: the command, step rate, swing height and phases --- + command = self.command_scale * (2 * torch.rand(self.n, 3, device=self.device) - 1) + command = torch.where(command.abs() < 0.1, 0.0, command) # each zeroed under 0.1 + self.command.copy_(torch.where(mask[:, None], command, self.command)) + step_rate = 0.5 + 1.5 * torch.rand(self.n, device=self.device) # Hz + swing_height = 0.08 + 0.32 * torch.rand(self.n, device=self.device) # m + gait = torch.stack([step_rate, torch.zeros_like(step_rate), swing_height], 1) + self.gait.copy_(torch.where(mask[:, None], gait, self.gait)) + self.phase.copy_(torch.where(mask[:, None], self.start_phase, self.phase)) + self.steps.masked_fill_(mask, 0) + # a full reset (as `ppo.evaluate`'s) starts the counted episodes + self.alive.copy_(mask.all() | (self.alive & ~mask)) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's observations, noisy sensors then the exact state; the critic's the same.""" + robot = self.robot.data + fresh = self.steps.eq(0)[:, None] # after a reset: velocities and contacts are stale; at rest, both feet down + R_world_imu = robot.body_link_mat_w[:, self.imu_body] + gyro = torch.einsum("nji,nj->ni", R_world_imu, robot.body_link_ang_vel_w[:, self.imu_body]) + gyro = torch.where(fresh, 0.0, gyro) + up = R_world_imu[:, :, 2] + joint_pos = robot.joint_pos + joint_vel = robot.joint_vel + sensed = torch.cat([gyro, up, joint_pos - robot.default_joint_pos, joint_vel], 1) + noisy = sensed + self.obs_noise * (2 * torch.rand_like(sensed) - 1) + capsule_contact = (self.feet_contact.data.found > 0).view(self.n, 2, 3) + foot_contact = (capsule_contact.any(2) | fresh).float() # left, right + gait = [self.phase.cos(), self.phase.sin(), self.gait] + target_error = joint_pos - self.joint_target + obs = torch.cat([noisy, self.last_action, self.command, joint_vel, target_error, foot_contact, *gait], 1) + return obs, obs + + +if __name__ == "__main__": + config = tyro.cli(GaitConfig) + env = H1Gait(config) # the full physics, where the policy is scored + coarse_env = H1Gait(config, coarse=config.coarse_physics) if config.coarse else None + learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig(gamma=0.97)) + actor = learner.train(env, config.minutes, coarse_env, config.coarse) + # each metric times the steps: its sum over each world's first episode + metrics = dict(episode_reward=partial(torch.mul, env.counted, config.episode)) + print(ppo.evaluate(env, actor, metrics, steps=config.episode)) diff --git a/src/robokit/examples/rl/11_aloha_peg.py b/src/robokit/examples/rl/11_aloha_peg.py new file mode 100644 index 0000000..1af9846 --- /dev/null +++ b/src/robokit/examples/rl/11_aloha_peg.py @@ -0,0 +1,364 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Aloha peg insertion: two ALOHA arms learn with PPO to lift a socket and a peg and push the peg in, in the air. + +Example usage: + uv run src/robokit/examples/rl/11_aloha_peg.py --minutes 15 + uv run src/robokit/examples/rl/11_aloha_peg.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +from dataclasses import dataclass +from functools import partial +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import torch +import tyro +import warp as wp + +from robokit.assets.robots.assembly import agilex_aloha +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class AlohaPegConfig: + """The peg insertion's training: the worlds and the learner's time.""" + + worlds: int = 1024 # MjWarpSim worlds + minutes: float = 15.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + physics_dt: float = 0.0025 # s per physics step, each with its own control update + repeat: int = 2 # physics steps per action + episode: int = 500 # actions per episode + # Arm joints 1 to 6 and the gripper: position gains (N m/rad, N/m) and joint damping + gains: Tuple[Tuple[float, float], ...] = ( + (100.0, 6.0), + (150.0, 8.0), + (120.0, 6.0), + (40.0, 2.0), + (20.0, 1.0), + (20.0, 1.0), + (200.0, 10.0), + ) + # Home: each arm's joints 1 to 6 put its gripper 13 cm above x -/+ 0.16 m, pointing down, fingers open + home_arm: Tuple[float, ...] = (-0.0138, 1.715, 1.7168, -1.5721, 0.0002, -0.0115) + # Coarse physics (`CoarseConfig`): only the colliding geoms (grippers, peg, socket, table) and pyramidal cones + coarse_physics: CoarseConfig = CoarseConfig( + collide=r"table|peg|wall|socket-[BTLR]|(left|right)/(finger7|finger8|gripper)", pyramidal=True + ) + + +class AlohaPeg(Env): + """Peg insertion on `config.worlds` worlds, in the full physics or the `coarse` one.""" + + def __init__(self, config: AlohaPegConfig, coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + self.control_dt = config.repeat * config.physics_dt # s per policy action + + # --- build scene --- + # two arms facing each other across a table, an open socket (9.6 x 4.4 x 4.4 cm, a wall at its back), a peg + robots = [] + for side, T_world_base in ( + ("left", (-0.469, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0)), + ("right", (0.469, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0)), + ): + arm_spec = mjscene.build_robot_spec(agilex_aloha.MJCF_PATH, prefix=f"{side}/", body="fr_link1") + base = arm_spec.body(f"{side}/fr_link1") + base.pos = [0.0, 0.0, 0.0] + base.quat = [1.0, 0.0, 0.0, 0.0] + robots.append((arm_spec, T_world_base)) + scene_spec = mjscene.build_scene_spec(robots, floor=False, timestep=config.physics_dt) + table = scene_spec.worldbody.add_body(name="table", pos=[0, 0, -0.05]) + table.add_geom(name="table", type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.61, 0.37, 0.05], rgba=[0.6, 0.5, 0.4, 1.0]) + scene_spec.option.iterations = 10 + scene_spec.option.ls_iterations = 10 + scene_spec.option.impratio = 5.0 + for actuator in list(scene_spec.actuators): # the MJCF's, replaced below + scene_spec.delete(actuator) + for side in ("left", "right"): + for body in scene_spec.bodies: + if body.name.startswith(f"{side}/"): + body.gravcomp = 1.0 + for geom in body.geoms: + geom.contype = 0 + geom.conaffinity = int(body.name[-1] in "678") # only the gripper collides + for i, (kp, damping) in enumerate(config.gains, 1): # joint position actuators + joint = scene_spec.joint(f"{side}/fr_joint{i}") + joint.damping = [damping, 0.0, 0.0] + joint.armature = 0.01 + scene_spec.add_actuator( + name=f"{side}/joint{i}", + target=joint.name, + trntype=mujoco.mjtTrn.mjTRN_JOINT, + gainprm=[kp, *[0.0] * 9], + biastype=mujoco.mjtBias.mjBIAS_AFFINE, + biasprm=[0.0, -kp, *[0.0] * 8], + ctrlrange=joint.range, + ctrllimited=mujoco.mjtLimited.mjLIMITED_TRUE, + ) + finger = scene_spec.joint(f"{side}/fr_joint8") + finger.damping = [config.gains[-1][1], 0.0, 0.0] + finger.armature = 0.01 + scene_spec.add_equality( + type=mujoco.mjtEq.mjEQ_JOINT, + objtype=mujoco.mjtObj.mjOBJ_JOINT, + name1=finger.name, + name2=f"{side}/fr_joint7", + data=[0.0, 1.0, *[0.0] * 10], # the second finger follows the first + ) + scene_spec.body(f"{side}/fr_link6").add_site(name=f"{side}/gripper", pos=[0.135, 0.0, 0.0]) + scene_spec.body(f"{side}/fr_link6").first_geom().name = f"{side}/gripper" + for link in (7, 8): # each finger's table contact + scene_spec.body(f"{side}/fr_link{link}").first_geom().name = f"{side}/finger{link}" + mjscene.build_contact_sensor( + scene_spec, + f"table_{side}/finger{link}_found", + (mujoco.mjtObj.mjOBJ_GEOM, "table"), + (mujoco.mjtObj.mjOBJ_GEOM, f"{side}/finger{link}"), + reduce="mindist", + ) + peg_home = (0.136, 0.0, 0.0108, 1.0, 0.0, 0.0, 0.0) + peg = scene_spec.worldbody.add_body(name="peg", pos=peg_home[:3]) + peg.add_freejoint(name="peg") + peg.add_geom( + name="peg", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[0.048, 0.01, 0.01], + mass=0.044, + rgba=[1.0, 0.0, 0.0, 1.0], + friction=[1.0, 0.05, 0.001], + ) + peg.add_site(name="peg_end1", pos=[0.048, 0.0, 0.0]) + peg.add_site(name="peg_end2", pos=[-0.048, 0.0, 0.0]) + socket_home = (-0.147, 0.0, 0.0228, 1.0, 0.0, 0.0, 0.0) + socket = scene_spec.worldbody.add_body(name="socket", pos=socket_home[:3]) + socket.add_freejoint(name="socket") + walls = dict( + B=((0, 0, -0.02), (0.048, 0.022, 0.002)), + T=((0, 0, 0.02), (0.048, 0.022, 0.002)), + L=((0, -0.02, 0), (0.048, 0.002, 0.018)), + R=((0, 0.02, 0), (0.048, 0.002, 0.018)), + ) + for name, (pos, size) in walls.items(): + socket.add_geom( + name=f"socket-{name}", + type=mujoco.mjtGeom.mjGEOM_BOX, + pos=pos, + size=size, + mass=0.016, + rgba=[0.2, 0.4, 0.9, 1.0], + ) + socket.add_geom( + name="wall", + type=mujoco.mjtGeom.mjGEOM_BOX, + pos=[-0.044, 0, 0], + size=[0.004, 0.018, 0.018], + mass=0.006, + rgba=[1.0, 0.0, 0.0, 1.0], + ) + socket.add_site(name="socket_entrance", pos=[0.048, 0.0, 0.0]) + socket.add_site(name="socket_rear", pos=[0.0, 0.0, 0.0]) + for geom in [*socket.geoms, scene_spec.geom("peg")]: + geom.condim = 4 + geom.solref = [0.01, 1.0] + geom.friction = [1.0, 0.05, 0.001] + arm_home = [*config.home_arm, 0.037, 0.037] # m: fingers open + arm_ctrl = [*config.home_arm, 0.037] + home_qpos = [*arm_home, *arm_home, *peg_home, *socket_home] # the arms, the peg, the socket + scene_spec.add_key(name="home", qpos=home_qpos, ctrl=[*arm_ctrl, *arm_ctrl]) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + self.repeat = max(1, round(self.control_dt / mjm.opt.timestep)) # physics steps per action + # control steps per physics step: each one's reward and control change + self.step_scale = config.repeat / self.repeat + sim = MjWarpSim(mjm, n, key="home", njmax=256, nconmax=32) + self.sim = sim + sim.set_torch_stream() + self.left = sim.build_entity("left/") + self.right = sim.build_entity("right/") + self.device = self.left.device + self.table_contact = sim.build_contact_sensor("table") # the fingers' + + # --- set up actions --- + # each control step moves the controls 0.005 times the action (in [-1, 1]) within their ranges + ctrl_range = torch.tensor(mjm.actuator_ctrlrange, device=self.device, dtype=torch.float32) + self.ctrl_low = ctrl_range[:, 0] + self.ctrl_high = ctrl_range[:, 1] + self.bound = torch.ones(mjm.nu, device=self.device) + + # --- set up rewards --- + weights = dict( + left_reward=1.0, + right_reward=1.0, + left_target_qpos=0.3, + right_target_qpos=0.3, + no_table_collision=0.3, + socket_z_up=0.5, + peg_z_up=0.5, + socket_entrance_reward=4.0, + peg_end2_reward=4.0, + peg_insertion_reward=8.0, + ) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.socket = mjm.body("socket").id + self.peg = mjm.body("peg").id + self.left_gripper = self.left.find_sites(["gripper"])[0] + self.right_gripper = self.right.find_sites(["gripper"])[0] + self.socket_entrance = mjm.site("socket_entrance").id + self.socket_rear = mjm.site("socket_rear").id + self.peg_end = mjm.site("peg_end2").id + self.socket_goal = torch.tensor((-0.05, 0.0, 0.15), device=self.device) # m + self.peg_goal = torch.tensor((0.05, 0.0, 0.15), device=self.device) + + # --- set up resets --- + self.socket_q_adr = int(mjm.joint("socket").qposadr[0]) + self.peg_q_adr = int(mjm.joint("peg").qposadr[0]) + + # --- set up observations --- + dim = mjm.nq + mjm.nv + 24 + self.obs_dims = (dim, dim) # the critic's the same + + # --- initialize state --- + # `counted`, `success`: each first episode's rewards and end state since a full reset + self.counted = torch.zeros(n, device=self.device) + self.success = torch.zeros(n, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.alive = torch.zeros(n, dtype=torch.bool, device=self.device) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None: the task has no curriculum.""" + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Per repeated control step: move the controls by 0.005 x `action` (clipped to [-1, 1]), step, score.""" + delta = self.step_scale * 0.005 * action.clamp(-1.0, 1.0) + ctrl = self.sim.data.torch.ctrl # the targets: every actuator is an arm's + reward = torch.zeros(self.n, device=self.device) + for _ in range(self.repeat): + ctrl.copy_(torch.clamp(ctrl + delta, self.ctrl_low, self.ctrl_high)) + self.sim.step() + scored = self.score() + reward += self.step_scale * scored[0] # the rewards add up + # the last physics step's terminations count + _, terminated, inserted, term_values = scored # pyright: ignore[reportPossiblyUnbound] + self.steps += 1 + truncated = self.steps >= self.config.episode + self.counted.copy_(reward * self.alive) + self.success.copy_((self.alive & (terminated | truncated) & inserted).float()) + return reward, terminated, truncated, term_values + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds to the home keyframe, move the socket and the peg, then refresh the kinematics.""" + self.sim.reset(wp.from_torch(mask)) + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """A control step's reward, the weighted terms' mean; terminations; whether the peg is in; each term's mean.""" + data = self.sim.data.torch + left = self.left.data + right = self.right.data + socket = data.xpos[:, self.socket] + peg = data.xpos[:, self.peg] + up = data.xmat[:, :, 2, 2] # each body's z axis' z + rear = data.site_xpos[:, self.socket_rear] + peg_end = data.site_xpos[:, self.peg_end] + axis = data.site_xpos[:, self.socket_entrance] - rear + along = ((peg_end - rear) * axis).sum(1, keepdim=True) / ((axis * axis).sum(1, keepdim=True) + 1e-6) + aligned = (peg_end - rear - along * axis).norm(dim=1) < 0.005 # m: the peg's end on the socket's axis + depth = (peg_end - rear).norm(dim=1) # m: from the socket's middle; its mouth is 4.8 cm out + + # --- rewards --- + errors = dict( # each error (m, or 1 - a z axis' z), its tolerance and its margin + left_gripper=((socket - left.site_pos_w[:, self.left_gripper]).norm(dim=1), 0.001, 0.3), + right_gripper=((peg - right.site_pos_w[:, self.right_gripper]).norm(dim=1), 0.001, 0.3), + socket_lift=((self.socket_goal - socket).norm(dim=1), 0.01, 0.15), + peg_lift=((self.peg_goal - peg).norm(dim=1), 0.01, 0.15), + insertion=(depth, 0.001, 0.1), + socket_tilt=(1.0 - up[:, self.socket], 0.01, 0.03), + peg_tilt=(1.0 - up[:, self.peg], 0.01, 0.03), + ) + near = {} # 1 for an error within its tolerance, falling linearly to 0.1 a margin past it, then to 0 + for name, (error, tolerance, margin) in errors.items(): + near[name] = (1 - 0.9 * (error - tolerance).clamp(min=0.0) / margin).clamp(min=0.0) + left_offset = (left.joint_pos[:, :6] - left.default_joint_pos[:6]).norm(dim=1) # rad: joints 1 to 6 off home + right_offset = (right.joint_pos[:, :6] - right.default_joint_pos[:6]).norm(dim=1) + home_offset = torch.stack([left_offset, right_offset], 1) + at_home = 0.1 ** (((home_offset - 0.01).clamp(min=0.0) / 2.0) ** 2) # 1 within 0.01, 0.1 at 2 past (Gaussian) + both_near = near["left_gripper"] * near["right_gripper"] + terms = dict( + left_reward=near["left_gripper"], + right_reward=near["right_gripper"], + left_target_qpos=at_home[:, 0] * both_near, + right_target_qpos=at_home[:, 1] * both_near, + no_table_collision=1 - (self.table_contact.data.found > 0).any(1).float(), + socket_z_up=near["socket_tilt"] * near["socket_lift"], + peg_z_up=near["peg_tilt"] * near["peg_lift"], + socket_entrance_reward=near["socket_lift"], + peg_end2_reward=near["peg_lift"], + peg_insertion_reward=near["insertion"] * aligned, + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) * self.weights[:, None] + + # --- terminations --- + diverged = ~(data.qpos.isfinite().all(1) & data.qvel.isfinite().all(1)) + out = (socket.abs() > 1.0).any(1) | (peg.abs() > 1.0).any(1) # the socket or the peg left 1 m bounds + reward = term_values.sum(0) / self.weights.sum() + return reward, out | diverged, aligned & (depth < 0.04), term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Move the socket and the peg each up to 10 cm in x and y from home; masked writes only.""" + qpos = self.sim.data.torch.qpos + for q_adr in (self.socket_q_adr, self.peg_q_adr): + offset = 0.2 * torch.rand(self.n, 2, device=self.device) - 0.1 # m + qpos[:, q_adr : q_adr + 2] += mask[:, None] * offset + self.steps.masked_fill_(mask, 0) + self.alive.copy_(mask.all() | (self.alive & ~mask)) # a full reset starts the episodes the metrics count + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """Joints, grippers, socket and peg, the socket's mouth, the peg's end, the socket's and the peg's z rows.""" + data = self.sim.data.torch + z_row = data.xmat[:, :, 2, :] # each body's + obs = [ + data.qpos, + data.qvel, + self.left.data.site_pos_w[:, self.left_gripper], + data.xpos[:, self.socket], + self.right.data.site_pos_w[:, self.right_gripper], + data.xpos[:, self.peg], + data.site_xpos[:, self.socket_entrance], + data.site_xpos[:, self.peg_end], + z_row[:, self.socket], + z_row[:, self.peg], + ] + obs = torch.cat(obs, 1) + return obs, obs # the critic's the same + + +if __name__ == "__main__": + config = tyro.cli(AlohaPegConfig) + env = AlohaPeg(config) # the full physics, where the policy is scored + coarse_env = AlohaPeg(config, coarse=config.coarse_physics) if config.coarse else None + # discount, policy widths, unroll length and a state-dependent, tanh-squashed std + learner_config = ppo.PPOConfig(gamma=0.97, hidden=(256, 256, 256, 256), horizon=40, std="state") + actor = ppo.PPO(env.obs_dims, len(env.bound), learner_config).train(env, config.minutes, coarse_env, config.coarse) + # each step's metric x steps: sums over each episode + episode_reward = partial(torch.mul, env.counted, config.episode) + success = partial(torch.mul, env.success, config.episode) + print(ppo.evaluate(env, actor, dict(episode_reward=episode_reward, success=success), steps=config.episode)) diff --git a/src/robokit/examples/rl/12_panda_cabinet.py b/src/robokit/examples/rl/12_panda_cabinet.py new file mode 100644 index 0000000..019e4b5 --- /dev/null +++ b/src/robokit/examples/rl/12_panda_cabinet.py @@ -0,0 +1,284 @@ +# /// script +# requires-python = ">=3.12" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Panda cabinet: a Franka Panda learns with PPO on 4096 MuJoCo Warp worlds to pull a drawer open to a random depth. + +Example usage: + uv run src/robokit/examples/rl/12_panda_cabinet.py --minutes 5 + uv run src/robokit/examples/rl/12_panda_cabinet.py --coarse 0.5 # coarse physics mixed in over the first half +""" + +import math +from dataclasses import dataclass +from functools import partial +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import numpy as np +import torch +import tyro +import warp as wp + +from robokit.assets.robots.arms import franka_panda +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class PandaCabinetConfig: + """The drawer task's training: the worlds and the learner's time.""" + + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 5.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + control_dt: float = 0.02 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 150 # steps per episode + # Coarse physics (`CoarseConfig`): only the hand, drawer, cabinet face and floor collide + coarse_physics: CoarseConfig = CoarseConfig( + collide="robot/(left_finger_pad|right_finger_pad|hand_capsule)|handle|shelf|barrier|floor", pyramidal=True + ) + + +class PandaCabinet(Env): + """Drawer opening on `config.worlds` worlds, in the full physics or the `coarse` one.""" + + def __init__(self, config: PandaCabinetConfig, coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + # the Panda with its hand, a drawer behind a cabinet face 52 cm ahead, 5 ms steps + robot_spec = mjscene.build_robot_spec(franka_panda.URDF_PATH, prefix="robot/") + for geom in robot_spec.geoms: # only the finger pads and a hand capsule collide + geom.contype = 0 + geom.conaffinity = 0 + for side in ("left", "right"): + pad = robot_spec.body(f"robot/panda_{side}finger").geoms[3] + pad.name = f"robot/{side}_finger_pad" + pad.conaffinity = 3 + for joint, damping in zip(robot_spec.joints, [40, 40, 40, 40, 2, 2, 2, 10, 10]): # the fingers last + joint.damping = [damping, 0, 0] + joint.armature = 0.1 + q_wxyz_link7_hand = [0.9238795, 0, 0, -0.3826834] # the hand frame, 10.7 cm along link 7 + link7 = robot_spec.body("robot/panda_link7") + q_wxyz_link7_capsule = np.zeros(4) + mujoco.mju_mulQuat(q_wxyz_link7_capsule, q_wxyz_link7_hand, [0.7071068, 0.7071068, 0, 0]) + link7.add_geom( + name="robot/hand_capsule", + type=mujoco.mjtGeom.mjGEOM_CAPSULE, + size=[0.04, 0.06, 0], + pos=[0, 0, 0.137], + quat=q_wxyz_link7_capsule, + contype=0, + conaffinity=3, + group=3, + ) + link7.add_site(name="robot/gripper", pos=[0, 0, 0.207], quat=q_wxyz_link7_hand) + T_world_base = (0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0) + scene_spec = mjscene.build_scene_spec([(robot_spec, T_world_base)]) + handle = scene_spec.worldbody.add_body(name="handle", pos=[0.5, 0, 0.5]) # the drawer: a handle on a slide + handle.add_joint( + name="drawer", type=mujoco.mjtJoint.mjJNT_SLIDE, axis=[1, 0, 0], range=[-0.5, 0], damping=[0.1, 0, 0] + ) + handle.add_geom(name="handle", type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.01, 0.08, 0.01], rgba=[0, 1, 0, 1]) + handle.add_geom( + name="shelf", + type=mujoco.mjtGeom.mjGEOM_BOX, + size=[0.1, 0.2, 0.01], + pos=[0.03, 0, 0], + quat=[0.7071068, 0, -0.7071068, 0], + rgba=[0, 1, 0, 0.2], + ) + barrier = scene_spec.worldbody.add_body(name="barrier", pos=[0.52, 0, 0]) # the cabinet face, facing the robot + barrier.add_geom( + name="barrier", + type=mujoco.mjtGeom.mjGEOM_PLANE, + size=[0, 0, 0.01], + quat=[0.7071068, 0, -0.7071068, 0], + group=5, + ) + for name in ("handle", "shelf", "barrier"): + scene_spec.geom(name).contype = 2 + scene_spec.geom(name).friction = [1, 0.03, 0.003] + scene_spec.geom(name).solref = [0.01, 1] + scene_spec.option.iterations = 5 + scene_spec.option.ls_iterations = 8 + scene_spec.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_EULERDAMP + gains = [(1000, 20, 100)] * 2 + [(750, 4, 100)] * 2 + [(300, 2, 12)] * 3 # kp, kv, force limit per arm joint + for i, (kp, kv, force) in enumerate(gains): + joint = scene_spec.joint(f"robot/panda_joint{i + 1}") + actuator = scene_spec.add_actuator( + name=f"actuator{i + 1}", + target=joint.name, + trntype=mujoco.mjtTrn.mjTRN_JOINT, + ctrlrange=joint.range, + forcerange=[-force, force], + ) + actuator.set_to_position(kp=kp, kv=kv) + scene_spec.add_actuator( + name="actuator8", + target="robot/panda_finger_joint1", + trntype=mujoco.mjtTrn.mjTRN_JOINT, + ctrlrange=[0, 0.04], + forcerange=[-200, 200], + gainprm=[350] + [0] * 9, + biastype=mujoco.mjtBias.mjBIAS_AFFINE, + biasprm=[0, -350, -10] + [0] * 7, + ) + for part in ("left_finger_pad", "right_finger_pad", "hand_capsule"): # each one's contact with the cabinet face + mjscene.build_contact_sensor( + scene_spec, + f"barrier_{part}_found", + (mujoco.mjtObj.mjOBJ_GEOM, "barrier"), + (mujoco.mjtObj.mjOBJ_GEOM, f"robot/{part}"), + reduce="mindist", + ) + scene_spec.add_key(name="upright", qpos=[0] * 10, ctrl=[0] * 8) # the arm upright, aiming there, drawer shut + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + substeps = round(config.control_dt / mjm.opt.timestep) + sim = MjWarpSim(mjm, n, substeps=substeps, key="upright", njmax=128, nconmax=12) + self.sim = sim + sim.set_torch_stream() + robot = sim.build_entity("robot/") + self.robot = robot + self.device = robot.device + self.barrier_contact = sim.build_contact_sensor("barrier") + + # --- set up actions --- + # each action moves its actuator's target by up to 0.04 (rad, m) within the control range + ctrl_range = torch.tensor(mjm.actuator_ctrlrange[robot.actuator_ids], device=self.device, dtype=torch.float32) + self.ctrl_low = ctrl_range[:, 0] + self.ctrl_high = ctrl_range[:, 1] + self.bound = torch.ones(len(robot.actuator_ids), device=self.device) # tanh-squashed actions + + # --- set up rewards --- + weights = dict(gripper_box=4.0, box_target=8.0, no_barrier_collision=0.25, robot_target_qpos=0.3) + self.names = list(weights) + self.weights = torch.tensor(list(weights.values()), device=self.device) + self.handle = mjm.body("handle").id + self.gripper = robot.find_sites(["gripper"])[0] + + # --- set up resets --- + spawn_range = [[-1.0, -1.0, -1.0, -2.0, -1.0, 0.0, -1.0], [1.0, 1.0, 1.0, 0.0, 1.0, 2.0, 1.0]] # x 30 degrees + spawn_range = torch.tensor(spawn_range, device=self.device) * math.radians(30) + self.spawn_low = spawn_range[0] # rad: the arm joints' offsets from upright + self.spawn_high = spawn_range[1] + self.target_home = torch.tensor([0.3, 0.0, 0.5], device=self.device) # m: the handle's target; x moves +-0.1 + + # --- set up observations --- + self.eye = torch.tensor([1.0, 0, 0, 0, 1, 0], device=self.device) # the target orientation's first two rows + dim = mjm.nq + mjm.nv + 3 + 6 + 6 + 3 + 3 + 6 + mjm.nu + self.obs_dims = (dim, dim) + + # --- initialize state --- + self.target = torch.zeros(n, 3, device=self.device) + self.reached = torch.zeros(n, device=self.device) + self.opened = torch.zeros(n, device=self.device) + self.reward = torch.zeros(n, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """None.""" + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Move the actuator targets by 0.04 * `action` (clamped to [-1, 1]) within their ranges, step, score.""" + target = self.robot.data.joint_pos_target + 0.04 * action.clamp(-1, 1) + self.robot.set_joint_position_target(target.clamp(self.ctrl_low, self.ctrl_high)) + self.sim.step() + return self.score() + + def reset(self, mask: torch.Tensor): + """Reset the masked worlds to upright with the drawer shut, perturb them, then refresh the kinematics.""" + self.sim.reset(wp.from_torch(mask)) + self.restart(mask) + self.sim.kinematics() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Per-step rewards and `opened`; the episode ends as the handle leaves the 1 m box or the physics turns NaN.""" + data = self.sim.data.torch + robot = self.robot.data + self.steps += 1 + + # --- rewards --- + handle = data.xpos[:, self.handle] + gripper_to_handle = (handle - robot.site_pos_w[:, self.gripper]).norm(dim=1) + handle_to_target = (self.target - handle).norm(dim=1) + self.reached.copy_(torch.maximum(self.reached, (gripper_to_handle < 0.012).float())) # reached it once + self.opened.copy_((handle_to_target < 0.05).float()) + arm_offset = robot.joint_pos[:, :7] - robot.default_joint_pos[:7] + terms = dict( + gripper_box=1 - torch.tanh(5 * gripper_to_handle), + box_target=(1 - torch.tanh(5 * handle_to_target)) * self.reached, + no_barrier_collision=1 - (self.barrier_contact.data.found > 0).any(1).float(), + robot_target_qpos=1 - torch.tanh(arm_offset.norm(dim=1)), + ) + term_values = torch.nan_to_num(torch.stack([terms[name] for name in self.names])) + self.reward.copy_((term_values * self.weights[:, None]).sum(0).clamp(-1e4, 1e4)) + + # --- terminations --- + diverged = data.qpos.isnan().any(1) | data.qvel.isnan().any(1) + out = (handle.abs() > 1.0).any(1) | (handle[:, 2] < 0.0) # the handle left the 1 m box + return self.reward, out | diverged, self.steps >= self.config.episode, term_values.mean(1) + + @torch.compile + def restart(self, mask: torch.Tensor): + """Masked writes only: the arm joints offset from upright and aiming there, a new handle target.""" + robot = self.robot + spawn = self.spawn_low + (self.spawn_high - self.spawn_low) * torch.rand(self.n, 7, device=self.device) + offset = torch.zeros(self.n, len(robot.joint_names), device=self.device) + offset[:, :7] = spawn # the arm joints', not the fingers' + joint_pos = robot.data.default_joint_pos + offset + robot.write_joint_state_to_sim(joint_pos, torch.zeros_like(joint_pos), mask) + joint_target = torch.where(mask[:, None], joint_pos[:, robot.actuated_ids], robot.data.joint_pos_target) + robot.set_joint_position_target(joint_target) # each target at its joint + target = self.target_home.repeat(self.n, 1) + target[:, 0] += 0.2 * torch.rand(self.n, device=self.device) - 0.1 + self.target.copy_(torch.where(mask[:, None], target, self.target)) + self.reached.masked_fill_(mask, 0.0) + self.steps.masked_fill_(mask, 0) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The state observation, for the actor and the critic alike.""" + data = self.sim.data.torch + robot = self.robot.data + handle = data.xpos[:, self.handle] + gripper = robot.site_pos_w[:, self.gripper] + R_world_handle = data.xmat[:, self.handle].flatten(1) + R_world_gripper = robot.site_mat_w[:, self.gripper].flatten(1) + obs = [ + data.qpos, + data.qvel, + gripper, + R_world_gripper[:, 3:], + R_world_handle[:, 3:], + handle - gripper, + self.target - handle, + self.eye - R_world_handle[:, :6], + robot.joint_pos_target - robot.joint_pos[:, self.robot.actuated_ids], # each actuator's target error + ] + obs = torch.cat(obs, 1) + return obs, obs + + +if __name__ == "__main__": + config = tyro.cli(PandaCabinetConfig) + env = PandaCabinet(config) # the full physics, where the policy is scored + coarse_env = PandaCabinet(config, coarse=config.coarse_physics) if config.coarse else None + learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig(gamma=0.97, entropy=0.02)) + actor = learner.train(env, config.minutes, coarse_env, config.coarse) + # the return per episode at each step's reward, and the share of worlds with the drawer open + metrics = dict(episode_reward=partial(torch.mul, env.reward, config.episode), opened=env.opened.clone) + print(ppo.evaluate(env, actor, metrics, steps=config.episode)) diff --git a/src/robokit/examples/rl/13_cartpole.py b/src/robokit/examples/rl/13_cartpole.py new file mode 100644 index 0000000..c7f13b7 --- /dev/null +++ b/src/robokit/examples/rl/13_cartpole.py @@ -0,0 +1,177 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +"""Cartpole: a cart learns to swing up (or balance) a pole with PPO on 4096 MuJoCo Warp worlds, then is scored. + +Example usage: + uv run src/robokit/examples/rl/13_cartpole.py swingup --minutes 1 + uv run src/robokit/examples/rl/13_cartpole.py balance + uv run src/robokit/examples/rl/13_cartpole.py swingup --coarse 0.5 # coarse physics mixed in over the first half +""" + +import math +from dataclasses import dataclass +from functools import partial +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import torch +import tyro + +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim, mjscene + + +@dataclass(frozen=True) +class CartpoleConfig: + """The cartpole task and its training: the start, the worlds and the learner's time.""" + + home: Tuple[float, float] # initial qpos: the cart's position (m) and the pole's angle (rad, 0 upright) + reset_offset: Tuple[float, float] # half-widths of the uniform offsets added to `home` on reset (m, rad) + worlds: int = 4096 # MjWarpSim worlds + minutes: float = 1.0 # wall time to train, compilation included + coarse: float = 0.0 # the share of PPO's time that mixes in coarse physics (`coarse_physics`) + control_dt: float = 0.05 # s per policy action; physics steps are `mjm.opt.timestep` + episode: int = 1000 # steps per episode + # Coarse physics (`CoarseConfig`): 25 ms physics steps (nothing collides) + coarse_physics: CoarseConfig = CoarseConfig(timestep=0.025) + + +SWINGUP = CartpoleConfig(home=(0.0, math.pi), reset_offset=(0.0, 0.034)) # from hanging down +BALANCE = CartpoleConfig(home=(0.0, 0.0), reset_offset=(0.1, 0.034)) # from near upright + + +class Cartpole(Env): + """The swingup (or balance) on `config.worlds` worlds, in the full physics or the `coarse` one.""" + + def __init__(self, config: CartpoleConfig, coarse: Optional[CoarseConfig] = None): + n = config.worlds + self.n = n + self.config = config + + # --- build scene --- + # a 1 kg cart on a 3.6 m slider 1 m up, a 1 m 0.1 kg pole, a 10 N motor; 10 ms steps, no contacts + scene_spec = mjscene.build_scene_spec(floor=False, timestep=0.01) + scene_spec.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_CONTACT + cart = scene_spec.worldbody.add_body(name="cartpole/cart", pos=[0.0, 0.0, 1.0]) + cart.add_joint( + name="cartpole/slider", + type=mujoco.mjtJoint.mjJNT_SLIDE, + axis=[1.0, 0.0, 0.0], + limited=mujoco.mjtLimited.mjLIMITED_TRUE, + range=[-1.8, 1.8], + solref_limit=[0.08, 1.0], + damping=5e-4, + ) + cart.add_geom(name="cart", type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.2, 0.15, 0.1], mass=1.0) + pole = cart.add_body(name="cartpole/pole") + pole.add_joint(name="cartpole/hinge", axis=[0.0, 1.0, 0.0], damping=2e-6) + pole.add_geom( + name="pole", type=mujoco.mjtGeom.mjGEOM_CAPSULE, fromto=[0, 0, 0, 0, 0, 1], size=[0.045, 0, 0], mass=0.1 + ) + scene_spec.add_actuator( + name="slide", + target="cartpole/slider", + trntype=mujoco.mjtTrn.mjTRN_JOINT, + gear=[10.0, 0, 0, 0, 0, 0], + ctrllimited=mujoco.mjtLimited.mjLIMITED_TRUE, + ctrlrange=[-1.0, 1.0], + ) + if coarse is not None: + scene_spec = MjWarpSim.build_coarse_spec(scene_spec, coarse) + + # --- build simulator --- + mjm = scene_spec.compile() + self.mjm = mjm + substeps = round(config.control_dt / mjm.opt.timestep) + assert abs(substeps * mjm.opt.timestep - config.control_dt) < 1e-9, ( + "the control step must be a timestep multiple" + ) + sim = MjWarpSim(mjm, n, substeps=substeps) + self.sim = sim + sim.set_torch_stream() + cartpole = sim.build_entity("cartpole/") # joints: the slider, then the hinge + self.cartpole = cartpole + self.device = cartpole.device + + # --- set up actions --- + self.bound = torch.ones(1, device=self.device) # the motor's control range + + # --- set up rewards --- + self.names = ["smooth_reward"] + + # --- set up resets --- + self.home = torch.tensor(config.home, device=self.device) + self.reset_offset = torch.tensor(config.reset_offset, device=self.device) + + # --- set up observations --- + self.obs_dims = (5, 5) + + # --- initialize state --- + self.action = torch.zeros(n, 1, device=self.device) + self.reward = torch.zeros(n, device=self.device) + self.steps = torch.zeros(n, dtype=torch.long, device=self.device) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + + def curriculum(self, step: int): + """Spread episodes that are in step, as after a full reset, over their length.""" + spread = torch.randint_like(self.steps, self.config.episode) + self.steps.copy_(torch.where((self.steps == self.steps[0]).all(), spread, self.steps)) + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Push the cart with `action` x 10 N, as MuJoCo clamps the control to [-1, 1]; step; score.""" + self.action.copy_(action) + self.sim.data.torch.ctrl.copy_(action) + self.sim.step() + return self.score() + + @torch.compile + def score(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The smooth reward: upright x centered x small control x small pole velocity; no terminations.""" + cartpole = self.cartpole.data + self.steps += 1 + cart_position = cartpole.joint_pos[:, 0] + pole_angle = cartpole.joint_pos[:, 1] + pole_speed = cartpole.joint_vel[:, 1] + control = self.action[:, 0] + centered = (1 + 0.1 ** ((cart_position / 2.0) ** 2)) / 2 # Gaussian: 0.1 at the margin + slow = (1 + 0.1 ** ((pole_speed / 5.0) ** 2)) / 2 + smooth = (pole_angle.cos() + 1) / 2 * centered * (4 + (1 - control**2).clamp(min=0.0)) / 5 * slow + self.reward.copy_(smooth * self.config.control_dt) + timeout = self.steps >= self.config.episode + return self.reward, torch.zeros_like(timeout), timeout, smooth.mean()[None] + + @torch.compile + def reset(self, mask: torch.Tensor): + """Each joint at home plus a uniform offset, a uniform velocity in +-0.01; masked writes.""" + offset = self.reset_offset * (2 * torch.rand(self.n, 2, device=self.device) - 1) + velocity = 0.01 * (2 * torch.rand(self.n, 2, device=self.device) - 1) + self.cartpole.write_joint_state_to_sim(self.home + offset, velocity, mask) + warmstart = self.sim.data.torch.qacc_warmstart + warmstart.copy_(torch.where(mask[:, None], 0.0, warmstart)) + self.steps.masked_fill_(mask, 0) + + @torch.compile + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """Cart position, the pole angle's cosine and sine, cart and pole velocities, for actor and critic alike.""" + cartpole = self.cartpole.data + cart_position = cartpole.joint_pos[:, 0] + pole_angle = cartpole.joint_pos[:, 1] + cart_speed = cartpole.joint_vel[:, 0] + pole_speed = cartpole.joint_vel[:, 1] + obs = torch.stack([cart_position, pole_angle.cos(), pole_angle.sin(), cart_speed, pole_speed], 1) + return obs, obs + + +if __name__ == "__main__": + config = tyro.cli(tyro.extras.subcommand_type_from_defaults(dict(swingup=SWINGUP, balance=BALANCE))) + env = Cartpole(config) # the full physics, where the policy is scored + coarse_env = Cartpole(config, coarse=config.coarse_physics) if config.coarse else None + learner = ppo.PPO(env.obs_dims, len(env.bound), ppo.PPOConfig(hidden=(64, 64), horizon=32, normalize=False)) + actor = learner.train(env, config.minutes, coarse_env, config.coarse) + # the return per episode at each step's reward (at most 50) + print(ppo.evaluate(env, actor, dict(episode_reward=partial(torch.mul, env.reward, config.episode)), config.episode)) diff --git a/src/robokit/examples/rl/14_nist_assembly.py b/src/robokit/examples/rl/14_nist_assembly.py new file mode 100644 index 0000000..a8c5d6f --- /dev/null +++ b/src/robokit/examples/rl/14_nist_assembly.py @@ -0,0 +1,514 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp,pt-cu126]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +# pyright: reportOptionalMemberAccess=false +# pyright: reportCallIssue=false +# pyright: reportArgumentType=false +"""AssembleNIST's six NIST board assemblies (suniique/assembly-nist): PPO on coarse physics, scored on fine. + +Example usage: + uv run src/robokit/examples/rl/14_nist_assembly.py --minutes 75 + uv run src/robokit/examples/rl/14_nist_assembly.py --eval runs/nist/model_001150.pt + uv run src/robokit/examples/rl/14_nist_assembly.py --eval runs/nist/model_001150.pt --eval-mean # mean actions +""" + +import copy +import math +import time +import xml.etree.ElementTree as ET +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Optional, Tuple + +import mujoco # pyright: ignore[reportMissingImports] +import numpy as np +import torch +import tyro +import warp as wp +from torch import nn + +from robokit.assets.datasets import nist_assembly +from robokit.helpers.rl import Env, ppo +from robokit.sim import CoarseConfig, MjWarpSim +from robokit.xform.warp.torch_wrappers import quaternion_to_matrix + + +@dataclass(frozen=True) +class NistConfig: + """Train on coarse physics, saving checkpoints, or score checkpoint `eval` on fine physics.""" + + data: Path = nist_assembly.DIR # AssembleNIST's task scenes, point tables and reset banks + control_dt: float = 0.04 # s per action + grip_open: float = 0.04 # gripper targets, m per finger + grip_close: float = -0.01 + history: int = 5 # proprio frames observed + # Coarse physics: only the part, fixture, obstacles within 8 cm, board, table, hand and fingers collide + coarse_physics: CoarseConfig = CoarseConfig( + collide=r"(\w+_)?(part\d+|fix\d+|obst_near_\w+)|board|table|hand|(left|right)_finger", + condim=3, + condim_geoms="(left|right)_finger", + timestep=0.0025, + min_timeconst=0.005, # the gears' stiff contacts back to the others' + min_impedance_width=0.0005, + pyramidal=True, + iterations=4, + ls_iterations=4, + ) + eval: str = "" # a checkpoint to score instead of training, by AssembleNIST's evaluation + eval_seeds: int = 5 # the evaluation's draws: per seed, `eval_draws` episodes per task + eval_draws: int = 32 + eval_mean: bool = False # mean actions; AssembleNIST's evaluation samples them + run_dir: str = "runs/nist" # where training saves a checkpoint every 50 iterations + worlds: int = 8192 # MjWarpSim worlds to train on + minutes: float = 75.0 # wall time to train + seed: int = 0 # torch's + + +class Nist(Env): + """The tasks on `config.worlds` worlds, fine or `coarse` physics, episodes from bank `states` of tasks `task_of`.""" + + def __init__( + self, config: NistConfig, states: np.ndarray, task_of: np.ndarray, coarse: Optional[CoarseConfig] = None + ): + self.config = config + n = config.worlds + self.n = n + tables = np.load(config.data / "tables.npz") + self.tasks = [str(task) for task in tables["tasks"]] + + # --- build scene --- + # the scenes at 0.5 ms: one with every task's geoms, then each task's; a world takes its task's rows on reset + roots = [] + task_geoms = {"fix": ".//body[@name='fixture']", "part": ".//body[@name='part']", "obst": "worldbody"} + for task in self.tasks: + root = ET.fromstring((config.data / f"{task}.xml").read_text()) + root.find("compiler").set("meshdir", str(config.data / "assets")) + meshes = {mesh.get("name"): mesh for mesh in root.find("asset").findall("mesh") if mesh.get("name")} + # the task's geoms and meshes get its name, and join the first scene + for prefix, path in task_geoms.items(): + for geom in root.find(path).findall("geom"): + if not geom.get("name", "").startswith(prefix): # the table and board are in every scene + continue + mesh = meshes.get(geom.get("mesh")) + geom.set("name", f"{task}_{geom.get('name')}") + if prefix != "obst" and mesh is not None: # obstacle meshes are named by asset already + mesh.attrib["name"] = f"{task}_{mesh.attrib['name']}" + geom.attrib["mesh"] = mesh.attrib["name"] + if roots: + roots[0].find(path).append(copy.deepcopy(geom)) + if mesh is not None and roots[0].find(f"asset/mesh[@name='{mesh.get('name')}']") is None: + roots[0].find("asset").append(copy.deepcopy(mesh)) + sensor = ET.SubElement(root, "sensor") # the arm joints' positions, then velocities, after each substep + for kind in ("jointpos", "jointvel"): + for i in range(7): + ET.SubElement(sensor, kind, joint=f"joint{i + 1}") + if not roots: # the first task's scene also starts the scene with every task's geoms + roots.append(copy.deepcopy(root)) + roots.append(root) + scene_specs = [mujoco.MjSpec.from_string(ET.tostring(root, encoding="unicode")) for root in roots] + if coarse is not None: + scene_specs = [MjWarpSim.build_coarse_spec(scene_spec, coarse) for scene_spec in scene_specs] + + # --- build simulator --- + self.horizon = round(15.0 / config.control_dt) # 15 s episodes + substeps = round(config.control_dt / scene_specs[0].option.timestep) + worlds = [n] + [0] * len(self.tasks) # all in the first scene's model + njmax = 2048 if coarse is None else 480 + nconmax = 512 if coarse is None else 96 + sim = MjWarpSim(scene_specs, worlds, substeps=substeps, njmax=njmax, nconmax=nconmax) + self.sim = sim + if coarse is not None: + sim.opt.warn_overflow = 0 # constraints past njmax are dropped, as in AssembleNIST's run + sim.set_torch_stream() + self.device = sim.data.torch.qpos.device + mjm = sim.mjm + + # --- set up actions --- + # arm joint targets: the joints + scale x action, within the joint ranges; a latched gripper target + arm_joints = [mjm.joint(f"joint{i + 1}") for i in range(7)] + self.arm_joints = [joint.id for joint in arm_joints] + self.arm_q_adr = torch.tensor([joint.qposadr[0] for joint in arm_joints], device=self.device) + self.arm_v_adr = torch.tensor([joint.dofadr[0] for joint in arm_joints], device=self.device) + joint_range = np.array([joint.range for joint in arm_joints]) + joint_range = torch.tensor(joint_range, dtype=torch.float32, device=self.device) + self.joint_low = joint_range[:, 0] + self.joint_high = joint_range[:, 1] + self.action_scale = torch.tensor([0.05, 0.05, 0.05, 0.06, 0.07, 0.1, 0.17], device=self.device) # rad + self.bound = torch.ones(8, device=self.device) + + # --- set up rewards --- + # the arm gains, for the control cost's mean torques, and limits + self.stiffness = torch.tensor([600.0, 600.0, 600.0, 600.0, 250.0, 150.0, 50.0], device=self.device) + self.damping = torch.tensor([50.0, 50.0, 50.0, 50.0, 30.0, 25.0, 15.0], device=self.device) + self.torque_limit = torch.tensor([87.0, 87.0, 87.0, 87.0, 12.0, 12.0, 12.0], device=self.device) # N m + self.speed_limit = torch.tensor([2.175, 2.175, 2.175, 2.175, 2.61, 2.61, 2.61], device=self.device) # rad/s + # each task's success keypoints in the part's frame, and their assembled positions + self.keypoints = torch.tensor(tables["keypoints"], device=self.device) + self.keypoint_goals = torch.tensor(tables["keypoint_goals"], device=self.device) + self.part_q_adr = int(mjm.joint("part_free").qposadr[0]) + self.names = ["success", "cost", "safety"] + + # --- set up resets --- + # the reset bank and Success Guided Sampling, its CDF for draws on the GPU; diverged worlds go to `qpos0` + self.bank = torch.tensor(states[:, 1 : 1 + mjm.nq + mjm.nv], dtype=torch.float32, device=self.device) + self.bank_task = torch.as_tensor(task_of, device=self.device) + self.outcomes = np.zeros((len(states), 50), dtype=np.uint8) # each entry's last 50 episodes' successes + self.visits = np.zeros(len(states), dtype=np.int64) + self.cdf = torch.zeros(len(states), dtype=torch.float64, device=self.device) + self.log = [] # (entry, success, ended) per reset since the last `curriculum` + self.qpos0 = wp.to_torch(sim.model.qpos0) # each world its task's, set on reset + + # --- set up observations --- + # the points `Net` places: each task's part and mating geometry (in its frame and the world's), the fingers' + self.points = {k: torch.tensor(v, device=self.device) for k, v in tables.items() if k.endswith("_points")} + # observation: task, tcp position and rotation, part's position and rotation, fingers, proprio frames + self.split = (1, 3, 9, 12, 2, config.history * 30) # a proprio frame: tcp pose 7, twist 6, joints 9, action 8 + self.obs_dims = (sum(self.split), sum(self.split)) + finger_joints = [mjm.joint(f"finger_joint{i + 1}") for i in range(2)] + self.finger_q_adr = torch.tensor([joint.qposadr[0] for joint in finger_joints], device=self.device) + self.hand = mjm.body("hand").id + self.tcp = mjm.site("tcp").id + self.events = [torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)] # rollout, update + self.episodes = 0 # those ended in the last rollout + self.success_rate = 0.0 # of the episodes ended in the last rollout + + # --- initialize state --- + # per world: task, reset-bank entry, step, success, gripper latch, last action, proprio history + self.task = torch.zeros(n, dtype=torch.long, device=self.device) + self.entry = torch.zeros_like(self.task) + self.steps = torch.zeros_like(self.task) + self.succeeded = torch.zeros(n, dtype=torch.bool, device=self.device) + self.gripper_target = torch.zeros(n, device=self.device) + self.last_action = torch.zeros(n, 8, device=self.device) + self.proprio_history = torch.zeros(n, config.history, 30, device=self.device) + self.curriculum(0) + self.reset(torch.ones(n, dtype=torch.bool, device=self.device)) + self.log.clear() + desync = np.random.default_rng(7).integers(0, self.horizon, n) # staggered episode clocks + self.steps = torch.as_tensor(desync, device=self.device) + + def curriculum(self, step: int): + """Record the episodes ended since the last call; weight entries 1e-4 + sqrt(p (1 - p)), p their success.""" + if self.log: + entries, outcomes, ended = torch.cat(self.log, 1).cpu().numpy() # the one host sync, once per update + done = ended > 0 + for entry, outcome in zip(entries[done], outcomes[done]): # in order: an entry may end several episodes + self.outcomes[entry, self.visits[entry] % 50] = outcome + self.visits[entry] += 1 + self.episodes = int(ended.sum()) + self.success_rate = float(outcomes[done].mean()) if done.any() else 0.0 + self.log.clear() + success = self.outcomes.sum(1) / np.clip(self.visits, 1, 50) + weights = 1e-4 + np.sqrt(success * (1 - success)) + self.cdf.copy_(torch.as_tensor(np.cumsum(weights) / weights.sum())) + self.events[0].record() + + def proprio(self) -> torch.Tensor: + """The proprio frame: tcp position, quaternion and twist, joints, fingers, last action.""" + data = self.sim.data.torch + joint_vel = data.qvel[:, self.arm_v_adr] + tcp = data.site_xpos[:, self.tcp] + axis = data.xaxis[:, self.arm_joints] + anchor = data.xanchor[:, self.arm_joints] + tcp_lin_vel = (joint_vel[..., None] * torch.linalg.cross(axis, tcp[:, None] - anchor)).sum(1) + tcp_ang_vel = (axis * joint_vel[..., None]).sum(1) + q_wxyz_world_hand = data.xquat[:, self.hand] + q_wxyz_world_hand = q_wxyz_world_hand * torch.where(q_wxyz_world_hand[:, 1:2] < 0, -1.0, 1.0) # x >= 0 + joints = [data.qpos[:, self.arm_q_adr], data.qpos[:, self.finger_q_adr]] + return torch.cat([tcp, q_wxyz_world_hand, tcp_lin_vel, tcp_ang_vel, *joints, self.last_action], 1) + + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """The control step: reward success minus control cost; end on success or a safety failure, or at 15 s.""" + data = self.sim.data.torch + + # --- act --- + arm_target = data.qpos[:, self.arm_q_adr] + self.action_scale * action[:, :7] + arm_target = torch.clamp(arm_target, self.joint_low, self.joint_high) + data.ctrl[:, :7] = arm_target + gripper_target = torch.where( + action[:, 7] < -0.5, self.config.grip_close, self.gripper_target + ) # |action| <= 0.5 keeps it + self.gripper_target = torch.where(action[:, 7] > 0.5, self.config.grip_open, gripper_target) + data.ctrl[:, 7] = self.gripper_target + self.sim.step() + # the arm joints after each substep: the sensors after substep k hold the state after substep k - 1 + sensors = data.substep_sensordata + joint_pos = torch.cat([sensors[1:, :, :7].transpose(0, 1), data.qpos[:, None, self.arm_q_adr]], 1) + joint_vel = torch.cat([sensors[1:, :, 7:].transpose(0, 1), data.qvel[:, None, self.arm_v_adr]], 1) + + # --- diverged physics (NaN or past 1e10) back to the defaults, as CPU MuJoCo does --- + diverged = ~(torch.cat([data.qpos, data.qvel], 1).abs() < 1e10).all(1) + data.qpos.copy_(torch.where(diverged[:, None], self.qpos0, data.qpos)) + data.qvel.masked_fill_(diverged[:, None], 0.0) + self.sim.kinematics() + + # --- rewards --- + # the cost of actions, joint speeds and mean torques; success: every keypoint within 1 mm of its assembled place + torque = self.stiffness * (arm_target[:, None] - joint_pos) - self.damping * joint_vel + torque = torch.clamp(torque, -self.torque_limit, self.torque_limit).mean(1) + torque = torch.where(diverged[:, None], 0.0, torque) + speed = data.qvel[:, self.arm_v_adr] + effort = ( + (action**2).sum(1) + ((speed / self.speed_limit) ** 2).sum(1) + ((torque / self.torque_limit) ** 2).sum(1) + ) + cost = 2e-5 * effort + part = data.qpos[:, self.part_q_adr : self.part_q_adr + 7] + R_world_part = quaternion_to_matrix(part[:, 3:]) + keypoints = part[:, None, :3] + self.keypoints[self.task] @ R_world_part.transpose(1, 2) + distance = (keypoints - self.keypoint_goals[self.task]).norm(dim=2).max(1).values + unsafe = (joint_vel.abs() > self.speed_limit).any(2).any(1) | diverged # an arm joint over its speed limit + self.succeeded = (distance < 0.001) & ~unsafe + + # --- terminations --- + self.steps = self.steps + 1 + self.last_action = action + self.proprio_history = torch.cat([self.proprio_history[:, 1:], self.proprio()[:, None]], 1) + timeout = (self.steps >= self.horizon) & ~self.succeeded & ~unsafe + terms = torch.stack([self.succeeded.float().mean(), cost.mean(), unsafe.float().mean()]) + return self.succeeded.float() - cost, self.succeeded | unsafe, timeout, terms + + def reset(self, mask: torch.Tensor, entry: Optional[torch.Tensor] = None): + """Start the masked worlds from reset-bank entries (`entry`, else the sampler's), logging the ended episodes.""" + data = self.sim.data.torch + if entry is None: + draw = torch.rand(self.n, dtype=torch.float64, device=self.device) + entry = torch.searchsorted(self.cdf, draw).clamp(max=len(self.cdf) - 1) + self.log.append(torch.stack([self.entry, self.succeeded.long(), mask.long()])) + self.entry = torch.where(mask, entry, self.entry) + self.task = self.bank_task[self.entry] + + # --- scene: the task's model rows (scene 0 has every task's geoms); `reset` then places its static geoms --- + self.sim.set_scene(wp.from_torch(mask), wp.from_torch((self.task + 1).int())) + self.sim.reset(wp.from_torch(mask)) + + # --- state: the bank's state, gripper latch (closed unless open), cleared last action and history --- + nq = data.qpos.shape[1] + state = self.bank[self.entry] + data.qpos.copy_(torch.where(mask[:, None], state[:, :nq], data.qpos)) + data.qvel.copy_(torch.where(mask[:, None], state[:, nq:], data.qvel)) + self.sim.kinematics() + open = data.qpos[:, self.finger_q_adr].mean(1) > 0.036 + gripper_target = torch.where(open, self.config.grip_open, self.config.grip_close) + self.gripper_target = torch.where(mask, gripper_target, self.gripper_target) + self.last_action = self.last_action * ~mask[:, None] + self.steps = self.steps * ~mask + self.proprio_history = torch.where(mask[:, None, None], self.proprio()[:, None], self.proprio_history) + + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: + """The compact observation (`split`), which `Net` turns into point clouds; the critic's is the same.""" + data = self.sim.data.torch + self.events[1].record() + obs = [ + self.task[:, None], + data.site_xpos[:, self.tcp], + data.site_xmat[:, self.tcp].flatten(1), + data.qpos[:, self.part_q_adr : self.part_q_adr + 3], + quaternion_to_matrix(data.qpos[:, self.part_q_adr + 3 : self.part_q_adr + 7]).flatten(1), + data.qpos[:, self.finger_q_adr], + self.proprio_history.flatten(1), + ] + obs = torch.cat(obs, 1) + return obs, obs + + +class RunningNorm(nn.Module): + """The running normalization of the proprio, clipped to 10 standard deviations.""" + + mean: torch.Tensor + var: torch.Tensor + count: torch.Tensor + + def __init__(self, dim: int): + super().__init__() + self.register_buffer("mean", torch.zeros(dim)) + self.register_buffer("var", torch.ones(dim)) + self.register_buffer("count", torch.tensor(1e-4)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return ((x - self.mean) / torch.sqrt(self.var + 1e-5)).clamp(-10.0, 10.0) + + @torch.no_grad() + def update(self, x: torch.Tensor): + """Merge the statistics of the proprio of observations `x`, in place and without host syncs.""" + proprio = x[:, -self.mean.shape[0] :] + samples = proprio.shape[0] + delta = proprio.mean(0) - self.mean + total = self.count + samples + batch_var = proprio.var(0, unbiased=False) + self.var.copy_((self.var * self.count + batch_var * samples + delta**2 * self.count * samples / total) / total) + self.mean.add_(delta * samples / total) + self.count.copy_(total) + + +class ResBlock(nn.Module): + """SimBa's residual block: x + MLP(LayerNorm(x)).""" + + def __init__(self, dim: int = 256, expansion: int = 1024): + super().__init__() + self.ln = nn.LayerNorm(dim) + self.fc1 = nn.Linear(dim, expansion) + self.fc2 = nn.Linear(expansion, dim) + self.act = nn.SiLU() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return x + self.fc2(self.act(self.fc1(self.ln(x)))) + + +class SimBa(nn.Module): + """AlphaNIST's network (SimBa, Lee et al. 2025): a point encoder, then residual blocks on points and proprio.""" + + def __init__(self, out: int, points: int, proprio: int, hidden: int = 256): + super().__init__() + self.enc = nn.Sequential(nn.Linear(3 * points, 256), nn.ELU(), nn.Linear(256, 128), nn.ELU()) + self.inp = nn.Linear(128 + proprio, hidden) + self.blocks = nn.Sequential(ResBlock(hidden), ResBlock(hidden)) + self.ln = nn.LayerNorm(hidden) + self.head = nn.Linear(hidden, out) + + +class Policy(nn.Module): + """AssembleNIST's actor-critic, named as its checkpoints: SimBa actor and critic, a log-std.""" + + def __init__(self, points: int, proprio: int, init_std: float = 1.0): + super().__init__() + self.norm = RunningNorm(proprio) + self.actor = SimBa(8, points, proprio) + self.critic = SimBa(1, points, proprio) + self.log_std = nn.Parameter(torch.full((8,), math.log(init_std))) + nn.init.orthogonal_(self.actor.head.weight, 0.01) + nn.init.zeros_(self.actor.head.bias) + nn.init.orthogonal_(self.critic.head.weight, 1.0) + nn.init.zeros_(self.critic.head.bias) + + +class Net(nn.Module): + """The policy's actor (with its log-std) or critic, on `Nist`'s observations, for robokit's PPO.""" + + def __init__(self, policy: Policy, env: "Nist", critic: bool = False): + super().__init__() + self.obs_normalizer = policy.norm # shared; PPO updates it after each update + self.net = policy.critic if critic else policy.actor + self.log_std = policy.log_std + self.points = env.points + self.split = env.split + self.finger_axis = env.points["left_finger_points"].new_tensor([0.0, 1.0, 0.0]) # the fingers open along y + self.state_std = False + + def forward(self, x: torch.Tensor) -> torch.Tensor: + task, tcp_pos, R_world_tcp, part, fingers, proprio = x.split(self.split, 1) + # the part's and mating geometry's points, then the fingers', in the tcp frame, in dm + task = task[:, 0].long() + R_world_part = part[:, 3:].reshape(-1, 3, 3) + part_points = part[:, None, :3] + self.points["part_points"][task] @ R_world_part.transpose(1, 2) + world_points = torch.cat([part_points, self.points["mating_points"][task]], 1) + left = self.points["left_finger_points"] + fingers[:, :1, None] * self.finger_axis + right = self.points["right_finger_points"] - fingers[:, 1:, None] * self.finger_axis + tcp_points = (world_points - tcp_pos[:, None]) @ R_world_tcp.reshape(-1, 3, 3) + points = 10.0 * torch.cat([tcp_points, left, right], 1).flatten(1) + hidden = self.net.inp(torch.cat([self.net.enc(points), self.obs_normalizer(proprio)], -1)) + with torch.autocast("cuda", torch.bfloat16): # only the residual blocks, as AssembleNIST's run + hidden = self.net.blocks(hidden) + return self.net.head(self.net.ln(hidden)) + + def dist(self, x: torch.Tensor, std_range: Tuple[float, float]) -> Tuple[torch.Tensor, torch.Tensor]: + std = self.log_std.clamp(math.log(std_range[0]), math.log(std_range[1])).exp() # clamped in log space + return self(x), std + + +if __name__ == "__main__": + config = tyro.cli(NistConfig) + learner_config = ppo.PPOConfig( # AssembleNIST's + gamma=0.995, + lam=0.95, + clip=0.2, + value_coef=1.0, + entropy=0.005, + lr=1e-4, + lr_range=(1e-5, 1e-3), + kl=0.08, # 8x AssembleNIST's target: the rate stays at its cap + epochs=5, + minibatches=4, + max_grad=1.0, + grad_clip="joint", + reshuffle=True, + horizon=32, + std_range=(1e-3, 2.0), + ) + torch.manual_seed(config.seed) + tasks = [str(task) for task in np.load(config.data / "tables.npz")["tasks"]] + if config.eval: + # AssembleNIST's evaluation: per seed s, rng(10_000 + s) draws each task's eval-bank entries in turn; one + # episode each on fine physics, a success if assembled within 15 s without a safety failure; ± the seeds' std + banks = [np.load(config.data / "banks" / f"{task}_eval.npz") for task in tasks] + states = np.concatenate([bank["states"] for bank in banks]) + task_of = np.concatenate([np.full(len(bank["states"]), k) for k, bank in enumerate(banks)]) + offsets = np.cumsum([0] + [len(bank["states"]) for bank in banks]) + entries = [] + for seed in range(config.eval_seeds): + rng = np.random.default_rng(10_000 + seed) + entries += [ + offsets[k] + rng.integers(0, len(bank["states"]), config.eval_draws) for k, bank in enumerate(banks) + ] + entries = np.concatenate(entries) + env = Nist(replace(config, worlds=len(entries)), states, task_of) + points = sum(len(points) if points.ndim == 2 else points.shape[1] for points in env.points.values()) + policy = Policy(points, env.split[-1]).cuda() + policy.load_state_dict(torch.load(config.eval, map_location="cuda", weights_only=True)["model"]) + actor = Net(policy, env) + env.reset(torch.ones(env.n, dtype=torch.bool, device=env.device), torch.as_tensor(entries, device=env.device)) + ended = torch.zeros(env.n, dtype=torch.bool, device=env.device) + success = torch.zeros_like(ended) + with torch.no_grad(): + for _ in range(env.horizon): # an ended episode keeps stepping; its outcome is kept + mean, std = actor.dist(env.obs()[0], learner_config.std_range) + _, terminated, timeout, _ = env.step(mean if config.eval_mean else mean + std * torch.randn_like(mean)) + success |= ~ended & env.succeeded + ended |= terminated | timeout + family = np.concatenate([bank["family"] for bank in banks])[entries] + success = success.cpu().numpy() + per_seed = success.reshape(config.eval_seeds, -1).mean(1) + actions = "mean" if config.eval_mean else "sampled" + print(f"{actions} actions, {len(success)} episodes: success {per_seed.mean():.3f} ± {per_seed.std():.3f}") + print("tasks:", {task: round(float(success[task_of[entries] == k].mean()), 3) for k, task in enumerate(tasks)}) + families = ("loose", "pickup", "inhand", "partial", "near") # AssembleNIST's reset families, bank["family"] + print("families:", {name: round(float(success[family == i].mean()), 3) for i, name in enumerate(families)}) + else: + states = [] # the training banks: the first 640 entries of each task's reset family + task_of = [] + for k, name in enumerate(tasks): + bank = np.load(config.data / "banks" / f"{name}_train.npz") + keep = np.zeros(len(bank["family"]), dtype=bool) + for family in np.unique(bank["family"]): + keep[np.flatnonzero(bank["family"] == family)[:640]] = True + states.append(bank["states"][keep]) + task_of.append(np.full(keep.sum(), k)) + env = Nist(config, np.concatenate(states), np.concatenate(task_of), coarse=config.coarse_physics) + points = sum(len(points) if points.ndim == 2 else points.shape[1] for points in env.points.values()) + policy = Policy(points, env.split[-1]).cuda() + actor = Net(policy, env) + critic = Net(policy, env, critic=True) + learner = ppo.PPO(env.obs_dims, len(env.bound), learner_config, actor=actor, critic=critic) + end = torch.cuda.Event(enable_timing=True) + Path(config.run_dir).mkdir(parents=True, exist_ok=True) + start = time.perf_counter() + while time.perf_counter() - start < config.minutes * 60: # `PPO.train`'s loop, with logs and checkpoints + learner.update(env) + end.record() + end.synchronize() + it = learner.it + if it % 10 == 0 or it <= 3: + rollout = env.events[0].elapsed_time(env.events[1]) / 1e3 + update = env.events[1].elapsed_time(end) / 1e3 + lr = float(learner.opt.param_groups[0]["lr"]) + std = float(policy.log_std.exp().mean()) + print( + f"it {it} {time.perf_counter() - start:.0f} s: rollout {rollout:.2f} s update {update:.2f} s, " + f"success {env.success_rate:.3f} of {env.episodes} episodes, lr {lr:.1e}, std {std:.3f}", + flush=True, + ) + if it % 50 == 0: + torch.save(dict(model=policy.state_dict(), it=it), Path(config.run_dir) / f"model_{it:06d}.pt") diff --git a/src/robokit/examples/sim_mpc/01_sharpa_oakink.py b/src/robokit/examples/sim_mpc/01_sharpa_oakink.py index e922569..9f4cac2 100644 --- a/src/robokit/examples/sim_mpc/01_sharpa_oakink.py +++ b/src/robokit/examples/sim_mpc/01_sharpa_oakink.py @@ -7,7 +7,10 @@ # /// # pyright: reportMissingImports=false # pyright: reportArgumentType=false -"""SimMPC: a Sharpa hand lifts an OakInk object, tracking a human clip that robokit retargets kinematically.""" +"""SimMPC: a Sharpa hand lifts an OakInk object, tracking a human clip that robokit retargets kinematically. + +SPIDER: https://arxiv.org/abs/2511.09484. +""" import time from dataclasses import replace @@ -24,9 +27,9 @@ from robokit.helpers.hand_retargeting import HandRetargeterOffline, HandSpec, refine_config from robokit.helpers.hand_retargeting.presets._common import FIVE_FINGERTIPS from robokit.helpers.hand_retargeting.presets.sharpa import _LINKS, offline, spec -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage from robokit.robo import Robot +from robokit.sim import MjWarpSim from robokit.terms import StateTask from robokit.utils.visualize_utils import ViserMjcf from robokit.xform.numpy import quaternion_apply, quaternion_invert, quaternion_multiply, quaternion_to_matrix @@ -50,16 +53,14 @@ def main(): clip = np.load(root / HUMAN / "trajectory_keypoints.npz") print(f"loaded {len(clip['qpos_obj_right'])} frames of {CLIP}") - # --- scene: the Sharpa on six position-controlled base joints, the object free on a small plate; SPIDER's - # contact pairs, and its run's solver settings --- + # --- scene: the Sharpa on six position-controlled base joints, the object free on a small plate; SPIDER's contact pairs, and its run's solver settings --- scene = mujoco.MjSpec.from_file(str(root / SCENE / "scene.xml")) scene.meshdir = f"{(root / SCENE / scene.meshdir).resolve()}/" # absolute, for the viewer's copy scene.option.iterations, scene.option.integrator = 20, mujoco.mjtIntegrator.mjINT_IMPLICITFAST model = scene.compile() print(f"scene: {model.nq} qpos, {model.nu} actuators") - # --- retarget: the wrist and fingertips to the Sharpa's base pose and 22 joints, in the object's frame, where a - # collision term keeps the hand out of the static object mesh --- + # --- retarget: the wrist and fingertips to the Sharpa's base pose and 22 joints, in the object's frame, where a collision term keeps the hand out of the static object mesh --- T_world_object = clip["qpos_obj_right"] q_wxyz_object_world = quaternion_invert(T_world_object[:, 3:]) identity = wp.array(np.eye(4, dtype=np.float32)[None], dtype=wp.mat44) @@ -108,17 +109,19 @@ def main(): cost = StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), np.array(weight)) ctrl_std = np.where(np.arange(model.nu) < 6, 0.02, 0.2) # base, fingers config = SimMPCConfig( - num_samples=1024, horizon_steps=200, node_steps=50, ctrl_steps=25, max_iterations=16, min_improvement=-1.0, - std_growth=2.0, noise_decay=0.75, terminal_scale=1.0, - ) # fmt: skip + num_samples=1024, horizon_steps=200, node_steps=50, ctrl_steps=25, + stages=[SimMPCStage(15, [(0.5, None), (1.0, 0.02)]), SimMPCStage(1)], # 1.28x faster + min_improvement=-1.0, + std_growth=2.0, noise_decay=0.75, terminal_scale=1.0, ctrl_std=ctrl_std, + ).add(cost) # fmt: skip steps = (len(qpos_ref) - config.horizon_steps) // config.ctrl_steps * config.ctrl_steps print("building SimMPC (the first run compiles kernels) ...") - sim = MjWarpSim(model, state, njmax=350) - mpc = SimMPC(sim, ctrl_ref, ctrl_std, [cost], config, ctrl_range=model.actuator_ctrlrange) + sim = MjWarpSim(model, 1, state, nconmax=120, njmax=350) + mpc = SimMPC(config, sim, ctrl_ref) print(f"planning {steps / 100:.1f} s of motion ...") start = time.perf_counter() report = lambda plans: plans[0]["t0"] % 50 or print(f" t={plans[0]['t0'] / 100:.1f} s: cost {plans[0]['plan_cost']:.3f}") # fmt: skip - (rollout,), _ = mpc.solve(steps, callback=report) + (rollout,), _ = mpc.execute(sim, steps, callback=report) # --- check: SPIDER's success, a mean object error within 10 cm and 0.5 rad --- q, q_ref = rollout["qpos"][:, -4:], qpos_ref[:steps, -4:] diff --git a/src/robokit/examples/sim_mpc/02_xhand_arctic.py b/src/robokit/examples/sim_mpc/02_xhand_arctic.py index 10ab080..71b8aea 100644 --- a/src/robokit/examples/sim_mpc/02_xhand_arctic.py +++ b/src/robokit/examples/sim_mpc/02_xhand_arctic.py @@ -6,12 +6,21 @@ # robokit = { path = "../../../..", editable = true } # /// # pyright: reportMissingImports=false -"""SimMPC: two XHands pick up a box, tracking a human ARCTIC clip that robokit retargets kinematically.""" +"""SimMPC: two XHands hold an articulated ARCTIC notebook up and turn its cover, tracking a clip robokit retargets. + +ARCTIC and MANO are licensed, so bring your own: +- ARCTIC (https://arctic.is.tue.mpg.de): `--arctic-root` holds `raw_seqs/s05` and `meta/object_vtemplates/notebook`. +- MANO (https://mano.is.tue.mpg.de): `MANO_RIGHT.pkl` and `MANO_LEFT.pkl` in `~/.robokit/body_models/mano`. + +SPIDER: https://arxiv.org/abs/2511.09484. +""" import time +from pathlib import Path import mujoco import numpy as np +import tyro import viser import warp as wp @@ -20,47 +29,87 @@ from robokit.helpers.hand_retargeting import HandRetargeterOffline, HandSpec from robokit.helpers.hand_retargeting.presets._common import FIVE_FINGERTIPS from robokit.helpers.hand_retargeting.presets.xhand import _LINKS, offline, spec -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage from robokit.robo import Robot +from robokit.sim import MjWarpSim +from robokit.smplx import BodyModelSpecTensors, BodyModelState, body_lbs_warp, load_mano from robokit.terms import StateTask from robokit.utils.ee_coord_utils import HandCoordinateSpec from robokit.utils.visualize_utils import ViserMjcf -from robokit.xform.numpy import quaternion_to_matrix +from robokit.xform.numpy import axis_angle_to_matrix, matrix_to_quaternion, quaternion_to_matrix from robokit.xform.numpy.rotation_conversions import matrix_to_euler_angles REPO, REVISION = "retarget/retarget_example", "8b0cdf2b24cc86d1c859050c5b0317ddbec59a63" # SPIDER's released data -CLIP = "s01-box_use_01" # two human hands pick up a box; 121 frames, 33 ms apart -HUMAN, SCENE = f"processed/arcticv2/mano/bimanual/{CLIP}/0", f"processed/arcticv2/xhand/bimanual/{CLIP}" -BOX, HANDS = "processed/arcticv2/assets/objects/box_bottom", "processed/gigahand/assets" # XHands: in GigaHands +SCENE, HANDS = "processed/arcticv2/xhand/bimanual/s01-box_use_01", "processed/gigahand/assets" # XHands: in GigaHands +SEQUENCE, FRAMES = "s05/notebook_use_01", slice(305, 380) # 2.5 s at 30 Hz +FLOOR_Z = 1.0924 # m in ARCTIC's world: the lowest point of the clip's hands +LID_FRICTION = 0.17 # N m, assumed: near gravity's peak, so the cover barely falls +R_MANO_PALM = dict( # SPIDER's offsets from MANO's wrist to the XHand's palm + right=np.array([[0.0, 0.0, -1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), + left=np.array([[0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]]), +) TARGETS = ("wrist", *FIVE_FINGERTIPS) -def main(): +def main(arctic_root: Path): wp.config.log_level = wp.LOG_WARNING # no per-module load lines wp.init() - # --- data: each human hand's wrist pose and five fingertips, the box's pose, and SPIDER's XHand scene --- - files = [f"{HUMAN}/trajectory_keypoints.npz", f"{SCENE}/scene.xml", f"{BOX}/**", f"{HANDS}/robots/xhand/**"] - root = fetch(files, REVISION, REPO) - clip = np.load(root / HUMAN / "trajectory_keypoints.npz") - print(f"loaded {len(clip['qpos_obj_right'])} frames of {CLIP}") - - # --- scene: both XHands on six position-controlled base joints each, the box free on the floor (a second, - # massless object body is unused); SPIDER's contact pairs, and its run's solver settings --- + # --- data: the object's pose and lid angle, MANO's parameters for each hand, SPIDER's XHand scene --- + root = fetch([f"{SCENE}/scene.xml", f"{HANDS}/robots/xhand/**"], REVISION, REPO) + arctic = np.load(arctic_root / f"raw_seqs/{SEQUENCE}.object.npy", allow_pickle=True).astype(float) + mano = np.load(arctic_root / f"raw_seqs/{SEQUENCE}.mano.npy", allow_pickle=True).item() + lid_range, arctic = (arctic[:, 0].min(), arctic[:, 0].max()), arctic[FRAMES] # angle, axis-angle, translation in mm + num_frames = len(arctic) + print(f"loaded {num_frames} frames of {SEQUENCE}") + # each quaternion in the previous one's hemisphere, so interpolating them is safe + continuous = lambda q: q * np.cumprod(np.r_[1.0, np.sign(np.sum(q[1:] * q[:-1], 1))])[:, None] + + # --- scene: both XHands on six position-controlled base joints each, SPIDER's contact pairs and solver settings; its box and unused massless body give way to a free base with the lid hinged to it, one convex hull each --- scene = mujoco.MjSpec.from_file(str(root / SCENE / "scene.xml")) + pairs = [(p.geomname1, p.condim, p.friction.copy()) for p in scene.pairs if p.geomname2 == "right_object_0"] + for element in [*(p for p in scene.pairs if "_object_" in p.geomname2), scene.body("right_object"), + scene.body("left_object"), *(m for m in scene.meshes if m.file.startswith("objects"))]: # fmt: skip + scene.delete(element) for mesh in scene.meshes: # absolute mesh paths, so the viewer's copy finds them - mesh.file = str(root / (HANDS if mesh.file.startswith("robots") else "processed/arcticv2/assets") / mesh.file) + mesh.file = str(root / HANDS / mesh.file) scene.meshdir = "" + base = scene.worldbody.add_body(name="base") + base.add_joint(name="object_base", type=mujoco.mjtJoint.mjJNT_FREE, armature=1e-4, frictionloss=1e-4) + lid = base.add_body(name="lid") + lid.add_joint(name="object_lid", type=mujoco.mjtJoint.mjJNT_HINGE, axis=[0, 0, -1], range=lid_range, + limited=mujoco.mjtLimited.mjLIMITED_TRUE, armature=1e-4, frictionloss=LID_FRICTION) # fmt: skip + for part, file, body in [("base", "bottom", base), ("lid", "top", lid)]: + scene.add_mesh(name=part, file=str(arctic_root / f"meta/object_vtemplates/notebook/{file}.obj"), + scale=[1e-3] * 3, maxhullvert=32, inertia=mujoco.mjtMeshInertia.mjMESH_INERTIA_CONVEX) # fmt: skip + body.add_geom(name=part, type=mujoco.mjtGeom.mjGEOM_MESH, meshname=part, density=1000, rgba=[1, 1, 1, 1]) + for geom, condim, friction in pairs: + scene.add_pair(geomname1=geom, geomname2=part, condim=condim, friction=friction) + # softer fingers (kp / 30) and wrists (kp / 10), inertia to match: the same motion, far gentler on contact + wrist = lambda name: "forearm_" in name and "forearm_t" not in name + for joint in scene.joints: + joint.armature = 0.033 if "_hand_" in joint.name else 0.1 if wrist(joint.name) else joint.armature + for actuator in scene.actuators: + if "forearm_t" not in actuator.name: + kp = 100 if wrist(actuator.name) else 10 + actuator.gainprm[0], actuator.biasprm[1] = kp, -kp o = scene.option o.timestep, o.iterations, o.integrator = 0.01, 20, mujoco.mjtIntegrator.mjINT_IMPLICITFAST model = scene.compile() - print(f"scene: {model.nq} qpos, {model.nu} actuators") + print(f"scene: {model.nq} qpos, {model.nu} actuators, {model.npair} contact pairs") - # --- retarget: each hand's wrist and fingertips to its XHand's base pose and 12 joints --- - ref = np.zeros((len(clip["qpos_obj_right"]), model.nq)) + # --- retarget: MANO's wrist and fingertips to each XHand's base pose and 12 joints --- + ref = np.zeros((num_frames, model.nq)) for side in ("right", "left"): + hand, mano_spec = mano[side], load_mano(side=side) # ARCTIC poses are relative to MANO's mean hand + rot, pose, trans = (np.asarray(hand[k], float)[FRAMES] for k in ("rot", "pose", "trans")) + full_pose = np.c_[rot, pose + mano_spec.metadata["hands_mean"]].reshape(num_frames, 16, 3) + mano_state = BodyModelState(np.tile(hand["shape"], (num_frames, 1)), full_pose, trans) + posed = body_lbs_warp(BodyModelSpecTensors(mano_spec, str(wp.get_preferred_device())), mano_state) + lift = [0.0, 0.0, -FLOOR_Z] + wrist, tips = posed["T_world_joint"].numpy()[:, 0, :3] + lift, posed["landmarks"].numpy() + lift + q_wxyz = continuous(matrix_to_quaternion(axis_angle_to_matrix(rot) @ R_MANO_PALM[side])) robot = Robot.load(str(getattr(xhand, f"URDF_PATH_{side.upper()}"))) links = {n: _LINKS[n].replace("right_", f"{side}_") for n in TARGETS} hand_spec = HandSpec( @@ -69,58 +118,71 @@ def main(): contact_target_names=FIVE_FINGERTIPS, root_link_coord_spec=spec.root_link_coord_spec, target_coord_spec=spec.target_coord_spec if side == "right" else HandCoordinateSpec("-y", "x"), ) # fmt: skip - points = np.concatenate([clip[f"qpos_wrist_{side}"][:, None, :3], clip[f"qpos_finger_{side}"][..., :3]], 1) - packed = HandRetargeterOffline(offline, robot, hand_spec).solve_numpy(points, clip[f"qpos_wrist_{side}"][:, 3:]) + points = np.concatenate([wrist[:, None], tips], 1) + packed = HandRetargeterOffline(offline, robot, hand_spec).solve_numpy(points, q_wxyz) T_world_link = robot.forward_kinematics_numpy(packed[:, 7:], packed[:, :7]) T_world_hand = T_world_link[:, robot.link_names.index(links["wrist"])] # the scene's hand body - base = model.jnt_qposadr[model.joint(f"{side[0].upper()}_forearm_tx_link_joint").id] - ref[:, base : base + 3] = T_world_hand[:, :3] + base_adr = model.jnt_qposadr[model.joint(f"{side[0].upper()}_forearm_tx_link_joint").id] + ref[:, base_adr : base_adr + 3] = T_world_hand[:, :3] euler = np.unwrap(matrix_to_euler_angles(quaternion_to_matrix(T_world_hand[:, 3:]), "rzxy"), axis=0) - ref[:, base + 3 : base + 6] = euler * [1, 1, -1] # roll about z, pitch about x, yaw about -y + ref[:, base_adr + 3 : base_adr + 6] = euler * [1, 1, -1] # roll about z, pitch about x, yaw about -y ref[:, model.jnt_qposadr[[model.joint(n).id for n in robot.spec.actuated_joint_names]]] = packed[:, 7:] - box, quat = model.nq - 14, clip["qpos_obj_right"][:, 3:] # the box's free joint, then the unused body's - quat = quat * np.sign(np.sum(quat * quat[:1], 1))[:, None] - ref[:, box:] = np.c_[clip["qpos_obj_right"][:, :3], quat, clip["qpos_obj_left"]] + obj = model.nq - 8 # the base's free joint, then the lid's hinge + ref[:, obj : obj + 3] = arctic[:, 4:7] / 1000 + [0.0, 0.0, -FLOOR_Z] + ref[:, obj + 3 : obj + 7] = continuous(matrix_to_quaternion(axis_angle_to_matrix(arctic[:, 1:4]))) + ref[:, -1] = arctic[:, 0] # --- reference: upsampled to the 10 ms sim step, then held while the horizon runs past the clip --- end = len(ref) - 1 t = np.r_[np.arange(0, end, 0.3), np.full(300, end)] qpos_ref = np.stack([np.interp(t, np.arange(len(ref)), c) for c in ref.T], 1) - qpos_ref[:, box + 3 : box + 7] /= np.linalg.norm(qpos_ref[:, box + 3 : box + 7], axis=1, keepdims=True) + qpos_ref[:, obj + 3 : obj + 7] /= np.linalg.norm(qpos_ref[:, obj + 3 : obj + 7], axis=1, keepdims=True) ctrl_ref = qpos_ref[:, model.jnt_qposadr[model.actuator_trnid[:, 0]]] state = mujoco.MjData(model) - state.qpos[:], state.ctrl[:] = qpos_ref[0], ctrl_ref[0] + state.qpos[:] = qpos_ref[0] + for _ in range(100): # XHands are thicker than human hands: contact pushes them out of the object, pinned here + state.qpos[obj:], state.qvel[-7:], state.ctrl[:] = qpos_ref[0, obj:], 0, ctrl_ref[0] + mujoco.mj_step(model, state) + state.time, state.qvel[:] = 0.0, 0.0 mujoco.mj_forward(model, state) - # --- SimMPC: track the hands and the box, weighting the box most; SPIDER's sampling budget --- + # --- SimMPC: track the hands, the object and its lid, weighting the object most, and reward each hand for touching the object; a 1 s plan refined 6 times, replanned every 0.25 s --- names = [model.joint(model.dof_jntid[i]).name for i in range(model.nv)] weight = [1.0 if "object" in n else 0.1 if "forearm_t" in n else 0.03 if "forearm" in n else 0.003 for n in names] - weight[-9:-6] = weight[-3:] = [0.3] * 3 # object rotations - cost = StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), np.array(weight)) + weight[-4:-1] = [0.3] * 3 # the base's rotation + geoms = [model.geom(i).name for i in range(model.ngeom)] + target, touch = np.array([g in ("base", "lid") for g in geoms]), np.ones(len(qpos_ref)) + hands = [np.array([g.startswith(f"collision_hand_{side}") for g in geoms]) for side in ("right", "left")] + contacts = [(hand, target, touch, 0.05) for hand in hands] + cost = StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), np.array(weight), contacts=contacts) ctrl_std = np.where(["forearm" in model.actuator(i).name for i in range(model.nu)], 0.02, 0.2) config = SimMPCConfig( - num_samples=1024, horizon_steps=300, node_steps=100, ctrl_steps=150, max_iterations=4, min_improvement=-1.0, - std_growth=2.0, noise_decay=0.3, terminal_scale=1.0, - ) # fmt: skip - steps = (len(qpos_ref) - config.horizon_steps) // config.ctrl_steps * config.ctrl_steps + num_samples=1024, horizon_steps=100, node_steps=25, ctrl_steps=25, + stages=[SimMPCStage(5, [(0.25, None), (1.0, 0.02)]), SimMPCStage(1)], # 1.33x faster + min_improvement=-1.0, + std_growth=2.0, noise_decay=0.3, terminal_scale=1.0, ctrl_std=ctrl_std, + ).add(cost) # fmt: skip + steps = (len(qpos_ref) - 300) // config.ctrl_steps * config.ctrl_steps # the clip, not the hold past it print("building SimMPC (the first run compiles kernels) ...") - sim = MjWarpSim(model, state, nconmax=256, njmax=768) - mpc = SimMPC(sim, ctrl_ref, ctrl_std, [cost], config, ctrl_range=model.actuator_ctrlrange) + sim = MjWarpSim(model, 1, state, nconmax=256, njmax=768) + mpc = SimMPC(config, sim, ctrl_ref) print(f"planning {steps / 100:.1f} s of motion ...") start = time.perf_counter() report = lambda plans: print(f" t={plans[0]['t0'] / 100:.1f} s: cost {plans[0]['plan_cost']:.3f}") - (rollout,), _ = mpc.solve(steps, callback=report) - - # --- check: SPIDER's success, a mean box error within 10 cm and 0.5 rad --- - q, q_ref = rollout["qpos"][:, box + 3 : box + 7], qpos_ref[:steps, box + 3 : box + 7] - position = np.linalg.norm(rollout["qpos"][:, box : box + 3] - qpos_ref[:steps, box : box + 3], axis=1).mean() - rotation = np.mean(2 * np.arccos(np.clip(np.abs(np.sum(q * q_ref, 1)), 0, 1))) - lift = rollout["qpos"][:, box + 2].max() - qpos_ref[0, box + 2] + (rollout,), _ = mpc.execute(sim, steps, callback=report) + + # --- check: SPIDER's success, a mean object error within 10 cm and 0.5 rad; held up; the lid against the human's --- + q, q_ref = rollout["qpos"][:, obj + 3 : obj + 7], qpos_ref[:steps, obj + 3 : obj + 7] + position = np.linalg.norm(rollout["qpos"][:, obj : obj + 3] - qpos_ref[:steps, obj : obj + 3], axis=1) + rotation = 2 * np.arccos(np.clip(np.abs(np.sum(q * q_ref, 1)), 0, 1)) + lid_error = np.abs(rollout["qpos"][:, -1] - qpos_ref[:steps, -1]) + dropped = bool(np.any(rollout["qpos"][:, obj + 2] < qpos_ref[:steps, obj + 2] - 0.1)) # 10 cm under the human's print( - f"box: {'pass' if position <= 0.1 and rotation <= 0.5 else 'fail'}, lifted {100 * lift:.1f} cm, " - f"mean error {100 * position:.1f} cm (<= 10) and {rotation:.2f} rad (<= 0.5)" + f"notebook: {'pass' if position.mean() <= 0.1 and rotation.mean() <= 0.5 and not dropped else 'fail'}, " + f"{'dropped' if dropped else 'held up'}, mean/max error {100 * position.mean():.1f}/{100 * position.max():.1f} " + f"cm, {rotation.mean():.2f}/{rotation.max():.2f} rad, lid {lid_error.mean():.2f}/{lid_error.max():.2f} rad" ) - print(f"planned in {time.perf_counter() - start:.0f} s") + print(f"planned in {time.perf_counter() - start:.1f} s") # --- viewer: replay the simulated motion, or the kinematic reference it tracks --- server = viser.ViserServer() @@ -136,4 +198,4 @@ def main(): if __name__ == "__main__": - main() + tyro.cli(main) diff --git a/src/robokit/examples/sim_mpc/04_g1_climb.py b/src/robokit/examples/sim_mpc/03_g1_climb.py similarity index 89% rename from src/robokit/examples/sim_mpc/04_g1_climb.py rename to src/robokit/examples/sim_mpc/03_g1_climb.py index 980592f..7ed6fd6 100644 --- a/src/robokit/examples/sim_mpc/04_g1_climb.py +++ b/src/robokit/examples/sim_mpc/03_g1_climb.py @@ -22,8 +22,8 @@ from robokit.helpers.humanoid_retargeting import HumanoidRetargeterOnline, build_interaction_mesh_frame from robokit.helpers.humanoid_retargeting.loaders import load_mocap_clip from robokit.helpers.humanoid_retargeting.presets.g1_mocap import G1_HEIGHT, g1_mocap -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import SensorTask, StateTask from robokit.utils.visualize_utils import ViserMjcf from robokit.utils.warp_utils import wp_vec7 @@ -73,8 +73,7 @@ def main(): retargeted.append(retargeter.solve_numpy(frame[None])[0]) print(f"retargeted in {time.perf_counter() - start:.0f} s") - # --- scene: the G1 scene, where only feet and hands touch the floor, and a cuboid fit to each box, which feet, - # hands and knees touch like the floor; position sensors on the feet and palms --- + # --- scene: the G1 scene, where only feet and hands touch the floor, and a cuboid fit to each box, which feet, hands and knees touch like the floor; position sensors on the feet and palms --- root = fetch([G1, "processed/amass/assets/robots/unitree_g1/**"], REVISION, REPO) scene = mujoco.MjSpec.from_file(str(root / G1)) scene.meshdir = str((root / G1).parent / scene.meshdir) # absolute, so the viewer's copy finds the meshes @@ -104,8 +103,8 @@ def main(): # --- reference: upsampled from 30 Hz to the 50 Hz sim step, held for a horizon past the end --- config = SimMPCConfig( - num_samples=2048, horizon_steps=40, node_steps=5, ctrl_steps=5, max_iterations=16, min_improvement=0.01, - patience=1, std_growth=2.0, noise_decay=0.1 ** (1 / 16), terminal_scale=1.0, + num_samples=2048, horizon_steps=40, node_steps=5, ctrl_steps=5, stages=[SimMPCStage(16)], min_improvement=0.01, + patience=1, std_growth=2.0, noise_decay=0.1 ** (1 / 16), terminal_scale=1.0, ctrl_std=0.05, ) # fmt: skip ref = np.stack(retargeted)[START:] # retargeted from the first frame, so the start pose has settled ref[1:, 3:7] *= np.cumprod(np.sign(np.sum(ref[1:, 3:7] * ref[:-1, 3:7], 1)))[:, None] # no quaternion sign flips @@ -122,20 +121,17 @@ def main(): state.qpos[:], state.ctrl[:] = qpos_ref[0], qpos_ref[0, 7:] mujoco.mj_forward(model, state) - # --- SimMPC: track the pelvis (position weighted 3x) and joints, and the feet and palms in the world, so a foot - # clears a box edge where the reference lifts it; the reference joints are the commands --- - costs = [ - StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), np.r_[3.0, 3.0, 3.0, np.ones(model.nv - 3)]), - SensorTask(np.array(sensor_ref), dict.fromkeys(SITES, 10.0)), - ] + # --- SimMPC: track the pelvis (position weighted 3x) and joints, and the feet and palms in the world, so a foot clears a box edge where the reference lifts it; the reference joints are the commands --- + config.add(StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), np.r_[3.0, 3.0, 3.0, np.ones(model.nv - 3)])) + config.add(SensorTask(np.array(sensor_ref), dict.fromkeys(SITES, 10.0))) steps = (n - 1) // config.ctrl_steps * config.ctrl_steps print("building SimMPC (the first run compiles kernels) ...") - limits = np.where(model.actuator_ctrllimited[:, None] > 0, model.actuator_ctrlrange, [-np.inf, np.inf]) - mpc = SimMPC(MjWarpSim(model, state), qpos_ref[:, 7:], np.full(model.nu, 0.05), costs, config, ctrl_range=limits) + sim = MjWarpSim(model, 1, state, nconmax=120, njmax=500) + mpc = SimMPC(config, sim, qpos_ref[:, 7:]) print(f"planning {steps / 50:.1f} s of motion ...") start = time.perf_counter() report = lambda p: p[0]["t0"] % 50 or print(f" t={p[0]['t0'] / 50:.1f} s: cost {p[0]['plan_cost']:.3f}") - (rollout,), _ = mpc.solve(steps, callback=report) + (rollout,), _ = mpc.execute(sim, steps, callback=report) # --- check: pelvis and joint errors; no fall; standing on the box at the end --- sim, ref = rollout["qpos"], qpos_ref[:steps] diff --git a/src/robokit/examples/sim_mpc/03_xhand_arctic_articulated.py b/src/robokit/examples/sim_mpc/03_xhand_arctic_articulated.py deleted file mode 100644 index a5d331c..0000000 --- a/src/robokit/examples/sim_mpc/03_xhand_arctic_articulated.py +++ /dev/null @@ -1,199 +0,0 @@ -# /// script -# requires-python = ">=3.10" -# dependencies = ["robokit[mjwarp]"] -# -# [tool.uv.sources] -# robokit = { path = "../../../..", editable = true } -# /// -# pyright: reportMissingImports=false -"""SimMPC: two XHands hold an articulated ARCTIC notebook up and turn its cover, tracking a clip robokit retargets. - -ARCTIC and MANO are licensed, so bring your own: -- ARCTIC (https://arctic.is.tue.mpg.de): `--arctic-root` holds `raw_seqs/s05` and `meta/object_vtemplates/notebook`. -- MANO (https://mano.is.tue.mpg.de): `MANO_RIGHT.pkl` and `MANO_LEFT.pkl` in `~/.robokit/body_models/mano`. -""" - -import time -from pathlib import Path - -import mujoco -import numpy as np -import tyro -import viser -import warp as wp - -from robokit.assets import fetch -from robokit.assets.robots.end_effectors import xhand -from robokit.helpers.hand_retargeting import HandRetargeterOffline, HandSpec -from robokit.helpers.hand_retargeting.presets._common import FIVE_FINGERTIPS -from robokit.helpers.hand_retargeting.presets.xhand import _LINKS, offline, spec -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim -from robokit.robo import Robot -from robokit.smplx import BodyModelSpecTensors, BodyModelState, body_lbs_warp, load_mano -from robokit.terms import StateTask -from robokit.utils.ee_coord_utils import HandCoordinateSpec -from robokit.utils.visualize_utils import ViserMjcf -from robokit.xform.numpy import axis_angle_to_matrix, matrix_to_quaternion, quaternion_to_matrix -from robokit.xform.numpy.rotation_conversions import matrix_to_euler_angles - - -REPO, REVISION = "retarget/retarget_example", "8b0cdf2b24cc86d1c859050c5b0317ddbec59a63" # SPIDER's released data -SCENE, HANDS = "processed/arcticv2/xhand/bimanual/s01-box_use_01", "processed/gigahand/assets" # XHands: in GigaHands -SEQUENCE, FRAMES = "s05/notebook_use_01", slice(305, 380) # 2.5 s at 30 Hz -FLOOR_Z = 1.0924 # m in ARCTIC's world: the lowest point of the clip's hands -LID_FRICTION = 0.17 # N m, assumed: near gravity's peak, so the cover barely falls -R_MANO_PALM = dict( # SPIDER's offsets from MANO's wrist to the XHand's palm - right=np.array([[0.0, 0.0, -1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), - left=np.array([[0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0]]), -) -TARGETS = ("wrist", *FIVE_FINGERTIPS) - - -def main(arctic_root: Path): - wp.config.log_level = wp.LOG_WARNING # no per-module load lines - wp.init() - - # --- data: the object's pose and lid angle, MANO's parameters for each hand, SPIDER's XHand scene --- - root = fetch([f"{SCENE}/scene.xml", f"{HANDS}/robots/xhand/**"], REVISION, REPO) - arctic = np.load(arctic_root / f"raw_seqs/{SEQUENCE}.object.npy", allow_pickle=True).astype(float) - mano = np.load(arctic_root / f"raw_seqs/{SEQUENCE}.mano.npy", allow_pickle=True).item() - lid_range, arctic = (arctic[:, 0].min(), arctic[:, 0].max()), arctic[FRAMES] # angle, axis-angle, translation in mm - num_frames = len(arctic) - print(f"loaded {num_frames} frames of {SEQUENCE}") - # each quaternion in the previous one's hemisphere, so interpolating them is safe - continuous = lambda q: q * np.cumprod(np.r_[1.0, np.sign(np.sum(q[1:] * q[:-1], 1))])[:, None] - - # --- scene: both XHands on six position-controlled base joints each, SPIDER's contact pairs and solver settings; - # its box and unused massless body give way to a free base with the lid hinged to it, one convex hull each --- - scene = mujoco.MjSpec.from_file(str(root / SCENE / "scene.xml")) - pairs = [(p.geomname1, p.condim, p.friction.copy()) for p in scene.pairs if p.geomname2 == "right_object_0"] - for element in [*(p for p in scene.pairs if "_object_" in p.geomname2), scene.body("right_object"), - scene.body("left_object"), *(m for m in scene.meshes if m.file.startswith("objects"))]: # fmt: skip - scene.delete(element) - for mesh in scene.meshes: # absolute mesh paths, so the viewer's copy finds them - mesh.file = str(root / HANDS / mesh.file) - scene.meshdir = "" - base = scene.worldbody.add_body(name="base") - base.add_joint(name="object_base", type=mujoco.mjtJoint.mjJNT_FREE, armature=1e-4, frictionloss=1e-4) - lid = base.add_body(name="lid") - lid.add_joint(name="object_lid", type=mujoco.mjtJoint.mjJNT_HINGE, axis=[0, 0, -1], range=lid_range, - limited=mujoco.mjtLimited.mjLIMITED_TRUE, armature=1e-4, frictionloss=LID_FRICTION) # fmt: skip - for part, file, body in [("base", "bottom", base), ("lid", "top", lid)]: - scene.add_mesh(name=part, file=str(arctic_root / f"meta/object_vtemplates/notebook/{file}.obj"), - scale=[1e-3] * 3, maxhullvert=32, inertia=mujoco.mjtMeshInertia.mjMESH_INERTIA_CONVEX) # fmt: skip - body.add_geom(name=part, type=mujoco.mjtGeom.mjGEOM_MESH, meshname=part, density=1000, rgba=[1, 1, 1, 1]) - for geom, condim, friction in pairs: - scene.add_pair(geomname1=geom, geomname2=part, condim=condim, friction=friction) - # softer fingers (kp / 30) and wrists (kp / 10), inertia to match: the same motion, far gentler on contact - wrist = lambda name: "forearm_" in name and "forearm_t" not in name - for joint in scene.joints: - joint.armature = 0.033 if "_hand_" in joint.name else 0.1 if wrist(joint.name) else joint.armature - for actuator in scene.actuators: - if "forearm_t" not in actuator.name: - kp = 100 if wrist(actuator.name) else 10 - actuator.gainprm[0], actuator.biasprm[1] = kp, -kp - o = scene.option - o.timestep, o.iterations, o.integrator = 0.01, 20, mujoco.mjtIntegrator.mjINT_IMPLICITFAST - model = scene.compile() - print(f"scene: {model.nq} qpos, {model.nu} actuators, {model.npair} contact pairs") - - # --- retarget: MANO's wrist and fingertips to each XHand's base pose and 12 joints --- - ref = np.zeros((num_frames, model.nq)) - for side in ("right", "left"): - hand, mano_spec = mano[side], load_mano(side=side) # ARCTIC poses are relative to MANO's mean hand - rot, pose, trans = (np.asarray(hand[k], float)[FRAMES] for k in ("rot", "pose", "trans")) - full_pose = np.c_[rot, pose + mano_spec.metadata["hands_mean"]].reshape(num_frames, 16, 3) - mano_state = BodyModelState(np.tile(hand["shape"], (num_frames, 1)), full_pose, trans) - posed = body_lbs_warp(BodyModelSpecTensors(mano_spec, str(wp.get_preferred_device())), mano_state) - lift = [0.0, 0.0, -FLOOR_Z] - wrist, tips = posed["T_world_joint"].numpy()[:, 0, :3] + lift, posed["landmarks"].numpy() + lift - q_wxyz = continuous(matrix_to_quaternion(axis_angle_to_matrix(rot) @ R_MANO_PALM[side])) - robot = Robot.load(str(getattr(xhand, f"URDF_PATH_{side.upper()}"))) - links = {n: _LINKS[n].replace("right_", f"{side}_") for n in TARGETS} - hand_spec = HandSpec( - floating_base=True, target_names=TARGETS, target_link_names=links, - target_chains=tuple(("wrist", tip) for tip in FIVE_FINGERTIPS), root_target_name="wrist", - contact_target_names=FIVE_FINGERTIPS, root_link_coord_spec=spec.root_link_coord_spec, - target_coord_spec=spec.target_coord_spec if side == "right" else HandCoordinateSpec("-y", "x"), - ) # fmt: skip - points = np.concatenate([wrist[:, None], tips], 1) - packed = HandRetargeterOffline(offline, robot, hand_spec).solve_numpy(points, q_wxyz) - T_world_link = robot.forward_kinematics_numpy(packed[:, 7:], packed[:, :7]) - T_world_hand = T_world_link[:, robot.link_names.index(links["wrist"])] # the scene's hand body - base_adr = model.jnt_qposadr[model.joint(f"{side[0].upper()}_forearm_tx_link_joint").id] - ref[:, base_adr : base_adr + 3] = T_world_hand[:, :3] - euler = np.unwrap(matrix_to_euler_angles(quaternion_to_matrix(T_world_hand[:, 3:]), "rzxy"), axis=0) - ref[:, base_adr + 3 : base_adr + 6] = euler * [1, 1, -1] # roll about z, pitch about x, yaw about -y - ref[:, model.jnt_qposadr[[model.joint(n).id for n in robot.spec.actuated_joint_names]]] = packed[:, 7:] - obj = model.nq - 8 # the base's free joint, then the lid's hinge - ref[:, obj : obj + 3] = arctic[:, 4:7] / 1000 + [0.0, 0.0, -FLOOR_Z] - ref[:, obj + 3 : obj + 7] = continuous(matrix_to_quaternion(axis_angle_to_matrix(arctic[:, 1:4]))) - ref[:, -1] = arctic[:, 0] - - # --- reference: upsampled to the 10 ms sim step, then held while the horizon runs past the clip --- - end = len(ref) - 1 - t = np.r_[np.arange(0, end, 0.3), np.full(300, end)] - qpos_ref = np.stack([np.interp(t, np.arange(len(ref)), c) for c in ref.T], 1) - qpos_ref[:, obj + 3 : obj + 7] /= np.linalg.norm(qpos_ref[:, obj + 3 : obj + 7], axis=1, keepdims=True) - ctrl_ref = qpos_ref[:, model.jnt_qposadr[model.actuator_trnid[:, 0]]] - state = mujoco.MjData(model) - state.qpos[:] = qpos_ref[0] - for _ in range(100): # XHands are thicker than human hands: contact pushes them out of the object, pinned here - state.qpos[obj:], state.qvel[-7:], state.ctrl[:] = qpos_ref[0, obj:], 0, ctrl_ref[0] - mujoco.mj_step(model, state) - state.time, state.qvel[:] = 0.0, 0.0 - mujoco.mj_forward(model, state) - - # --- SimMPC: track the hands, the object and its lid, weighting the object most, and reward each hand for touching - # the object; a 1 s plan refined 6 times, replanned every 0.25 s --- - names = [model.joint(model.dof_jntid[i]).name for i in range(model.nv)] - weight = [1.0 if "object" in n else 0.1 if "forearm_t" in n else 0.03 if "forearm" in n else 0.003 for n in names] - weight[-4:-1] = [0.3] * 3 # the base's rotation - geoms = [model.geom(i).name for i in range(model.ngeom)] - target, touch = np.array([g in ("base", "lid") for g in geoms]), np.ones(len(qpos_ref)) - hands = [np.array([g.startswith(f"collision_hand_{side}") for g in geoms]) for side in ("right", "left")] - contacts = [(hand, target, touch, 0.05) for hand in hands] - cost = StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), np.array(weight), contacts=contacts) - ctrl_std = np.where(["forearm" in model.actuator(i).name for i in range(model.nu)], 0.02, 0.2) - config = SimMPCConfig( - num_samples=1024, horizon_steps=100, node_steps=25, ctrl_steps=25, max_iterations=6, min_improvement=-1.0, - std_growth=2.0, noise_decay=0.3, terminal_scale=1.0, - ) # fmt: skip - steps = (len(qpos_ref) - 300) // config.ctrl_steps * config.ctrl_steps # the clip, not the hold past it - print("building SimMPC (the first run compiles kernels) ...") - sim = MjWarpSim(model, state, nconmax=256, njmax=768) - mpc = SimMPC(sim, ctrl_ref, ctrl_std, [cost], config, ctrl_range=model.actuator_ctrlrange) - print(f"planning {steps / 100:.1f} s of motion ...") - start = time.perf_counter() - report = lambda plans: print(f" t={plans[0]['t0'] / 100:.1f} s: cost {plans[0]['plan_cost']:.3f}") - (rollout,), _ = mpc.solve(steps, callback=report) - - # --- check: SPIDER's success, a mean object error within 10 cm and 0.5 rad; held up; the lid against the human's --- - q, q_ref = rollout["qpos"][:, obj + 3 : obj + 7], qpos_ref[:steps, obj + 3 : obj + 7] - position = np.linalg.norm(rollout["qpos"][:, obj : obj + 3] - qpos_ref[:steps, obj : obj + 3], axis=1) - rotation = 2 * np.arccos(np.clip(np.abs(np.sum(q * q_ref, 1)), 0, 1)) - lid_error = np.abs(rollout["qpos"][:, -1] - qpos_ref[:steps, -1]) - dropped = bool(np.any(rollout["qpos"][:, obj + 2] < qpos_ref[:steps, obj + 2] - 0.1)) # 10 cm under the human's - print( - f"notebook: {'pass' if position.mean() <= 0.1 and rotation.mean() <= 0.5 and not dropped else 'fail'}, " - f"{'dropped' if dropped else 'held up'}, mean/max error {100 * position.mean():.1f}/{100 * position.max():.1f} " - f"cm, {rotation.mean():.2f}/{rotation.max():.2f} rad, lid {lid_error.mean():.2f}/{lid_error.max():.2f} rad" - ) - print(f"planned in {time.perf_counter() - start:.0f} s") - - # --- viewer: replay the simulated motion, or the kinematic reference it tracks --- - server = viser.ViserServer() - print("replaying; Ctrl+C to stop") - server.scene.add_grid("/ground", width=1.0, height=1.0) - reference = server.gui.add_checkbox("Show kinematic reference", False) - viewer = ViserMjcf(server, scene.to_xml()) - while True: - for k in range(0, steps, 2): - viewer.update_qpos(qpos_ref[k] if reference.value else rollout["qpos"][k]) - time.sleep(2 * model.opt.timestep) - time.sleep(1.0) # hold the last frame before replaying - - -if __name__ == "__main__": - tyro.cli(main) diff --git a/src/robokit/examples/sim_mpc/05_g1_carry.py b/src/robokit/examples/sim_mpc/04_g1_carry.py similarity index 91% rename from src/robokit/examples/sim_mpc/05_g1_carry.py rename to src/robokit/examples/sim_mpc/04_g1_carry.py index 73088e4..d29875f 100644 --- a/src/robokit/examples/sim_mpc/05_g1_carry.py +++ b/src/robokit/examples/sim_mpc/04_g1_carry.py @@ -22,8 +22,8 @@ from robokit.helpers.humanoid_retargeting import HumanoidRetargeterOnline, build_interaction_mesh_frame from robokit.helpers.humanoid_retargeting.loaders import load_omomo_clip from robokit.helpers.humanoid_retargeting.presets.g1_smplh import G1_HEIGHT, g1_smplh -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import StateTask from robokit.utils.visualize_utils import ViserMjcf from robokit.utils.warp_utils import wp_vec7 @@ -80,8 +80,7 @@ def main(): retargeted.append(retargeter.solve_numpy(T_world_human[i : i + 1])[0]) print(f"retargeted in {time.perf_counter() - start:.0f} s") - # --- scene: the G1 scene, where only feet and hands touch the floor, and a 1 kg cuboid fit to the box in its - # clip frame; it rests on the floor, and the feet, hands, arms, legs and torso touch it --- + # --- scene: the G1 scene, where only feet and hands touch the floor, and a 1 kg cuboid fit to the box in its clip frame; it rests on the floor, and the feet, hands, arms, legs and torso touch it --- root = fetch([G1, "processed/amass/assets/robots/unitree_g1/**"], REVISION, REPO) scene = mujoco.MjSpec.from_file(str(root / G1)) scene.meshdir = str((root / G1).parent / scene.meshdir) # absolute, so the viewer's copy finds the meshes @@ -109,11 +108,10 @@ def main(): model = scene.compile() print(f"scene: {model.nq} qpos, {model.nu} actuators") - # --- reference: robot and box upsampled from 30 Hz to the 50 Hz sim step, held for a horizon past the end; the - # start is the first frame --- + # --- reference: robot and box upsampled from 30 Hz to the 50 Hz sim step, held for a horizon past the end; the start is the first frame --- config = SimMPCConfig( - num_samples=2048, horizon_steps=40, node_steps=5, ctrl_steps=5, max_iterations=16, min_improvement=0.01, - patience=1, std_growth=2.0, noise_decay=0.1 ** (1 / 16), terminal_scale=1.0, + num_samples=2048, horizon_steps=40, node_steps=5, ctrl_steps=5, stages=[SimMPCStage(16)], min_improvement=0.01, + patience=1, std_growth=2.0, noise_decay=0.1 ** (1 / 16), terminal_scale=1.0, ctrl_std=0.05, ) # fmt: skip ref = np.c_[np.stack(retargeted), T_world_object_vec7] for a in (3, 39): # no sign flips between neighboring quaternions @@ -130,15 +128,15 @@ def main(): # --- SimMPC: track the pelvis and box positions (3x), the joints and the box rotation --- weight = np.r_[3.0, 3.0, 3.0, np.ones(32), 3.0, 3.0, 3.0, 1.0, 1.0, 1.0] - cost = StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), weight) + config.add(StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), weight)) steps = (n - 1) // config.ctrl_steps * config.ctrl_steps print("building SimMPC (the first run compiles kernels) ...") - limits = np.where(model.actuator_ctrllimited[:, None] > 0, model.actuator_ctrlrange, [-np.inf, np.inf]) - mpc = SimMPC(MjWarpSim(model, state), qpos_ref[:, 7:36], np.full(model.nu, 0.05), [cost], config, ctrl_range=limits) + sim = MjWarpSim(model, 1, state, nconmax=120, njmax=500) + mpc = SimMPC(config, sim, qpos_ref[:, 7:36]) print(f"planning {steps / 50:.1f} s of motion ...") start = time.perf_counter() report = lambda p: p[0]["t0"] % 50 or print(f" t={p[0]['t0'] / 50:.1f} s: cost {p[0]['plan_cost']:.3f}") - (rollout,), _ = mpc.solve(steps, callback=report) + (rollout,), _ = mpc.execute(sim, steps, callback=report) # --- check: pelvis error, no fall, the box lifted and set down within 10 cm of its goal --- sim, ref = rollout["qpos"], qpos_ref[:steps] diff --git a/src/robokit/examples/sim_mpc/06_g1_amass.py b/src/robokit/examples/sim_mpc/05_g1_amass.py similarity index 89% rename from src/robokit/examples/sim_mpc/06_g1_amass.py rename to src/robokit/examples/sim_mpc/05_g1_amass.py index 43aa745..8840973 100644 --- a/src/robokit/examples/sim_mpc/06_g1_amass.py +++ b/src/robokit/examples/sim_mpc/05_g1_amass.py @@ -16,8 +16,8 @@ import warp as wp from robokit.assets import fetch -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import StateTask from robokit.utils.visualize_utils import ViserMjcf @@ -52,17 +52,17 @@ def main(): # --- SimMPC: track the pelvis (position weighted 3x) and joints, around the reference joints as commands --- cost = StateTask(qpos_ref, np.zeros((len(qpos_ref), model.nv)), np.r_[3.0, 3.0, 3.0, np.ones(model.nv - 3)]) config = SimMPCConfig( - num_samples=2048, horizon_steps=48, node_steps=6, ctrl_steps=6, max_iterations=16, min_improvement=0.01, - patience=1, std_growth=2.0, noise_decay=0.1 ** (1 / 16), terminal_scale=1.0, - ) # fmt: skip + num_samples=2048, horizon_steps=48, node_steps=6, ctrl_steps=6, stages=[SimMPCStage(16)], min_improvement=0.01, + patience=1, std_growth=2.0, noise_decay=0.1 ** (1 / 16), terminal_scale=1.0, ctrl_std=0.05, + ).add(cost) # fmt: skip steps = -(-len(qpos_ref) // config.ctrl_steps) * config.ctrl_steps print("building SimMPC (the first run compiles kernels) ...") - limits = np.where(model.actuator_ctrllimited[:, None] > 0, model.actuator_ctrlrange, [-np.inf, np.inf]) - mpc = SimMPC(MjWarpSim(model, state), qpos_ref[:, 7:], np.full(model.nu, 0.05), [cost], config, ctrl_range=limits) + sim = MjWarpSim(model, 1, state, nconmax=120, njmax=500) + mpc = SimMPC(config, sim, qpos_ref[:, 7:]) print(f"planning {steps / 60:.1f} s of motion ...") start = time.perf_counter() report = lambda p: p[0]["t0"] % 30 or print(f" t={p[0]['t0'] / 60:.1f} s: cost {p[0]['plan_cost']:.3f}") - (rollout,), _ = mpc.solve(steps, callback=report) + (rollout,), _ = mpc.execute(sim, steps, callback=report) # --- check: pelvis and joint errors at the clip's frames (each frame two sim steps); no fall --- sim = rollout["qpos"][1::2][:n] diff --git a/src/robokit/examples/sim_mpc/07_leap_cube.py b/src/robokit/examples/sim_mpc/06_leap_cube.py similarity index 88% rename from src/robokit/examples/sim_mpc/07_leap_cube.py rename to src/robokit/examples/sim_mpc/06_leap_cube.py index 81fc043..96c2f9f 100644 --- a/src/robokit/examples/sim_mpc/07_leap_cube.py +++ b/src/robokit/examples/sim_mpc/06_leap_cube.py @@ -7,7 +7,7 @@ # /// # pyright: reportMissingImports=false # pyright: reportArgumentType=false -"""SimMPC: a palm-up LEAP hand turns a cube in hand to one random goal after another, as in DROP and Judo.""" +"""SimMPC: a palm-up LEAP hand turns a cube in hand to one random goal after another.""" import time @@ -17,8 +17,8 @@ import warp as wp from robot_descriptions import leap_hand_mj_description -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import SensorTask from robokit.utils.visualize_utils import ViserMjcf @@ -62,7 +62,7 @@ def main(): cube = scene.worldbody.add_body(name="cube", pos=[0.11, 0, 0.1]) cube.add_freejoint(name="cube") cube.add_geom( - type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.035] * 3, mass=0.108, friction=[0.3, 0.05, 0.01], contype=1, + name="cube", type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.035] * 3, mass=0.108, friction=[0.3, 0.05, 0.01], contype=1, conaffinity=2, solref=[0.01, 1.5], solimp=[0.0, 0.95, 0.001, 0.5, 2], rgba=[0.9, 0.5, 0.1, 1], gap=0.002, # cancels the hand's margin: hand-cube contacts still act at contact ) # fmt: skip @@ -92,24 +92,23 @@ def draw(last: np.ndarray) -> np.ndarray: ref[0, 0, a : a + 4] = goal sensor_ref = wp.array(ref, dtype=float) - # --- SimMPC: hold the cube over the palm, turn it gently toward the goal; a 1 s plan refined 3 times --- + # --- SimMPC: hold the cube over the palm, turn it gently toward the goal; a 0.8 s plan refined 3 times --- cupped = np.where(np.isin(np.arange(model.nu) % 4, [1]) & (np.arange(model.nu) < 12), 0.0, 0.8) # rest pose cupped[15] = 0.0 # thumb tip joint ctrl_ref = np.tile(cupped, (STEPS + 101, 1)) - costs = [ - SensorTask(sensor_ref, dict(quat=0.05), residual="quaternion", freeze_reference=True), - SensorTask(sensor_ref, dict(position=50.0), freeze_reference=True), - ] config = SimMPCConfig( - num_samples=64, horizon_steps=100, node_steps=34, ctrl_steps=4, max_iterations=3, interpolation="cubic", - terminal_scale=1.0, + num_samples=64, horizon_steps=80, node_steps=27, ctrl_steps=5, interpolation="cubic", + stages=[SimMPCStage(3, [(0.25, None), (1.0, 0.02)])], + terminal_scale=1.0, ctrl_std=0.2, qpos_std=0.005, ) # fmt: skip + config.add(SensorTask(sensor_ref, dict(quat=0.05), residual="quaternion", freeze_reference=True)) + config.add(SensorTask(sensor_ref, dict(position=50.0), freeze_reference=True)) state = mujoco.MjData(model) state.qpos[:16], state.ctrl[:] = cupped, cupped mujoco.mj_forward(model, state) - sim = MjWarpSim(model, state, initial_state_std=dict(qpos=0.005), nconmax=64, njmax=512) print("building SimMPC (the first run compiles kernels) ...") - mpc = SimMPC(sim, ctrl_ref, np.full(model.nu, 0.2), costs, config, ctrl_range=model.actuator_ctrlrange) + sim = MjWarpSim(model, 1, state, nconmax=64, njmax=512) + mpc = SimMPC(config, sim, ctrl_ref) # --- after each control period: a cube within 0.4 rad of its goal gets the next one --- goals, reached = [], 0 @@ -117,7 +116,7 @@ def draw(last: np.ndarray) -> np.ndarray: def next_goal(plan: list): nonlocal goal, reached goals.extend([goal] * config.ctrl_steps) - q = sim.data["execution"].qpos.numpy()[0, -4:] + q = sim.data.qpos.numpy()[0, -4:] if 2 * np.arccos(min(abs(q @ goal), 1.0)) < 0.4: reached += 1 goal = draw(goal) @@ -126,7 +125,7 @@ def next_goal(plan: list): print(f"planning {STEPS / 100:.0f} s of motion ...") start = time.perf_counter() - (rollout,), _ = mpc.solve(STEPS, callback=next_goal) + (rollout,), _ = mpc.execute(sim, STEPS, callback=next_goal) dropped = bool(np.any(rollout["qpos"][:, -5] < -0.05)) print(f"cube: {'pass' if reached >= 3 and not dropped else 'fail'}, {reached} goals reached in " f"{STEPS / 100:.0f} s, {'dropped' if dropped else 'never dropped'}") # fmt: skip diff --git a/src/robokit/examples/sim_mpc/08_sharpa_pen.py b/src/robokit/examples/sim_mpc/07_sharpa_pen.py similarity index 60% rename from src/robokit/examples/sim_mpc/08_sharpa_pen.py rename to src/robokit/examples/sim_mpc/07_sharpa_pen.py index 0f8a26f..68cb5d0 100644 --- a/src/robokit/examples/sim_mpc/08_sharpa_pen.py +++ b/src/robokit/examples/sim_mpc/07_sharpa_pen.py @@ -17,25 +17,25 @@ import warp as wp from robokit.assets.robots.end_effectors import sharpa_hand -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim -from robokit.terms import ControlTask, SensorTask +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim +from robokit.terms import ControlTask, SensorTask, SupportTask from robokit.utils.visualize_utils import ViserMjcf STEPS = 3000 # 15 s at the 5 ms step -SPIN, TURNS = 2 * np.pi / 2.5, 3.2 # rad/s about the palm normal, the pen lags it; turns before holding still +PACE, LEAD, TURNS = 2.7, 2.0, 3.2 # scheduled heading rate, rad/s; most it leads the pen, rad; turns before holding GRASP = [1.5843, 0.3491, 0.0697, -0.1677, 0.0732, 0.4392, 0.05, 0.6964, 0.5714, 0.4968, 0.0136, 0.5307, 0.4322, 0.5143, -0.0161, 0.4301, 0.351, 0.0586, 0.3965, -0.013, 0.6135, 0.5184] # fingertips under the pen # fmt: skip PEN_POS, PEN_QUAT = [0.1438, 0.0047, 0.5836], [0.7438, 0.0, 0.0, 0.6684] +SKIN = 0.0025 # contact starts 2.5 mm out: the pen rests that far off the fingers, which meet it a step early def main(): wp.config.log_level = wp.LOG_WARNING # no per-module load lines wp.init() - # --- scene: the hand palm-up 0.5 m high, friction 1, stiff against itself (solmix 0 leaves the pen's contacts to - # the pen's defaults); a 14 cm, 9 mm thick, 10 g pen across the fingertips --- + # --- scene: the hand palm-up 0.5 m high, friction 1, stiff against itself (solmix 0 leaves the pen's contacts to the pen's defaults); a 14 cm, 9 mm thick, 10 g pen across the fingertips --- scene = mujoco.MjSpec.from_file(str(sharpa_hand.MJCF_PATH_RIGHT)) for mesh in scene.meshes: # absolute mesh paths, so the viewer's copy finds them mesh.file = str(sharpa_hand.MJCF_PATH_RIGHT.parent / scene.meshdir / mesh.file) @@ -50,8 +50,8 @@ def main(): pen.add_freejoint() pen.add_geom( name="pen", type=mujoco.mjtGeom.mjGEOM_CAPSULE, size=[0.0045, 0.0655, 0], - quat=[np.sqrt(0.5), 0, np.sqrt(0.5), 0], - mass=0.01, friction=[1.0, 0.005, 1e-4], condim=4, rgba=[0.15, 0.45, 0.9, 1], + quat=[np.sqrt(0.5), 0, np.sqrt(0.5), 0], solref=[0.01, 1.0], solimp=[0.99, 0.999, 0.001, 0.5, 2], + margin=SKIN, mass=0.01, friction=[1.0, 0.005, 1e-4], condim=4, rgba=[0.15, 0.45, 0.9, 1], ) # fmt: skip body = mujoco.mjtObj.mjOBJ_XBODY # the body frame: the pen's inertial axes are arbitrary about its length scene.add_sensor(name="pos", type=mujoco.mjtSensor.mjSENS_FRAMEPOS, objtype=body, objname="pen") @@ -63,63 +63,53 @@ def main(): mujoco.mj_step(model, state) print(f"scene: {model.nq} qpos, {model.nu} actuators; pen settled at {np.round(state.qpos[22:25], 3)}") - # --- SimMPC: each plan's heading leads the pen's at SPIN, up to TURNS; its centre stays, its axis flat --- - H, axis, pos = 120, model.sensor("axis").adr[0], model.sensor("pos").adr[0] + # --- SimMPC: the heading runs on a clock, up to LEAD ahead of the pen and TURNS in all; centre stays, axis flat --- + H, axis, pos = 100, model.sensor("axis").adr[0], model.sensor("pos").adr[0] ref = np.zeros((1, STEPS + H + 1, model.nsensordata), np.float32) ref[0, :, pos : pos + 3] = state.qpos[22:25] sensor_ref = wp.array(ref, dtype=float) ctrl_ref = np.tile(GRASP, (ref.shape[1], 1)) - costs = [ - SensorTask(sensor_ref, dict(axis=20.0), residual="heading", terminal_scale=10.0), - SensorTask(sensor_ref, dict(axis=[0.0, 0.0, 50.0])), - SensorTask(sensor_ref, dict(pos=5000.0)), - ControlTask(0.01, ctrl_ref), - ] + ctrl_ref[:, 0] -= 0.15 # the thumb rests clear of the pen, so the fingers carry it + ctrl_std = np.full(model.nu, 0.12) + ctrl_std[model.actuator_gainprm[:, 0] < 2] *= 2 # the weak distal joints need twice the noise to move a fingertip config = SimMPCConfig( - num_samples=64, horizon_steps=H, node_steps=40, ctrl_steps=4, max_iterations=2, interpolation="cubic", - terminal_scale=1.0, + num_samples=128, horizon_steps=H, node_steps=25, ctrl_steps=8, interpolation="cubic", + stages=[SimMPCStage(2, [(0.5, None), (1.0, 0.01)])], # 1.18x faster, same turns + std_growth=1.0, terminal_scale=1.0, ctrl_std=ctrl_std, ) # fmt: skip - sim = MjWarpSim(model, state, nconmax=96, njmax=600) + config.add(SensorTask(sensor_ref, dict(axis=60.0), residual="heading"), terminal_scale=10.0) + config.add(SensorTask(sensor_ref, dict(axis=[0.0, 0.0, 400.0]))) + config.add(SensorTask(sensor_ref, dict(pos=[20000.0, 20000.0, 100000.0]))) + config.add(ControlTask(0.22, ctrl_ref)) # the pull back to the grasp keeps the pen from wedging in ring and pinky + # while the thumb (the last group) is off the pen, two of the other fingers hold it + config.add(SupportTask("pen", ["_index_", "_middle_", "_ring_", "_pinky_", "_thumb_"], 2, 10.0, SKIN, free=True)) clock, heading = 0, np.arctan2(*state.xmat[model.body("pen").id][[3, 0]]) - final = heading + 2 * np.pi * TURNS + first, final = heading, heading + 2 * np.pi * TURNS def lead(plan: list): nonlocal clock, heading if plan: - w, x, y, z = sim.data["execution"].qpos.numpy()[0, 25:29] + w, x, y, z = sim.data.qpos.numpy()[0, 25:29] angle = np.arctan2(2 * (x * y + w * z), 1 - 2 * (y**2 + z**2)) heading += (angle - heading + np.pi) % (2 * np.pi) - np.pi clock += config.ctrl_steps - angles = np.minimum(heading + SPIN * model.opt.timestep * np.arange(H + 1), final) + angles = first + PACE * model.opt.timestep * (clock + np.arange(H + 1)) + angles = np.minimum(np.minimum(angles, heading + LEAD), final) ref[0, clock : clock + H + 1, axis : axis + 2] = np.stack([np.cos(angles), np.sin(angles)], 1) sensor_ref.assign(ref) lead([]) print("building SimMPC (the first run compiles kernels) ...") - mpc = SimMPC(sim, ctrl_ref, np.full(model.nu, 0.15), costs, config, ctrl_range=model.actuator_ctrlrange) + sim = MjWarpSim(model, 1, state, nconmax=48, njmax=300) + mpc = SimMPC(config, sim, ctrl_ref) print(f"planning {STEPS * model.opt.timestep:.0f} s of motion ...") start = time.perf_counter() - (rollout,), _ = mpc.solve(STEPS, callback=lead) + (rollout,), _ = mpc.execute(sim, STEPS, callback=lead) planned = time.perf_counter() - start - - # --- score: net turns, drop, tilt, and the deepest finger-finger overlap replayed in MuJoCo --- - pen_axis = rollout["sensordata"][:, axis : axis + 3] - turns = np.unwrap(np.arctan2(pen_axis[:, 1], pen_axis[:, 0])) - turns = (turns[-1] - turns[0]) / (2 * np.pi) + turns = np.unwrap(np.arctan2(rollout["sensordata"][:, axis + 1], rollout["sensordata"][:, axis])) dropped = bool(np.any(rollout["qpos"][:, 24] < state.qpos[24] - 0.03)) - tilt = np.degrees(np.arcsin(np.clip(np.abs(pen_axis[:, 2]), 0, 1))).max() - hand_only = scene.copy() - hand_only.geom("pen").contype = hand_only.geom("pen").conaffinity = 0 - check = hand_only.compile() - data, overlap = mujoco.MjData(check), 0.0 - for q in rollout["qpos"]: - data.qpos[:] = q - mujoco.mj_kinematics(check, data) - mujoco.mj_collision(check, data) - overlap = max(overlap, -data.contact.dist.min(initial=0.0)) - ok = turns >= 3 and not dropped and tilt <= 45 and overlap <= 0.002 - print(f"pen: {'pass' if ok else 'fail'}, {turns:.2f} turns in {STEPS * model.opt.timestep:.0f} s, max tilt " - f"{tilt:.0f} deg, finger overlap {1000 * overlap:.1f} mm, {'dropped' if dropped else 'never dropped'}") # fmt: skip + print(f"pen: {(turns[-1] - turns[0]) / (2 * np.pi):.2f} turns in {STEPS * model.opt.timestep:.0f} s, " + f"{'dropped' if dropped else 'never dropped'}") # fmt: skip print(f"planned in {planned:.0f} s") # --- viewer: replay the simulated motion --- diff --git a/src/robokit/examples/sim_mpc/08_sharpa_coin.py b/src/robokit/examples/sim_mpc/08_sharpa_coin.py new file mode 100644 index 0000000..478a8f5 --- /dev/null +++ b/src/robokit/examples/sim_mpc/08_sharpa_coin.py @@ -0,0 +1,253 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +# pyright: reportMissingImports=false +# pyright: reportArgumentType=false +"""SimMPC: a palm-down Sharpa Wave hand walks a 2-euro coin across the backs of its fingers, flipping it at each one. Each seed starts from reset noise and passes with one round trip (index to pinky and back, every crossing a flip of at least 150 deg), no drop before it, the coin never 2 mm into the hand, jitter at most 5 rad/s^2 and no two hand shapes overlapping by over 1 mm. Seed 10000 plans 12 s in 93 s on an RTX 4090.""" + +import time + +import mujoco +import numpy as np +import tyro +import viser +import warp as wp + +from robokit.assets.robots.end_effectors import sharpa_hand +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim +from robokit.terms import ControlTask, SensorTask +from robokit.utils.visualize_utils import ViserMjcf + + +STEPS = 2400 # 12 s at the 5 ms step +FLIP, LEAD, DWELL = 0.6, 0.5, 0.1 # s per flip; the plan's phase leads the coin's by at most LEAD; s on a finger +ORDER = [0, 1, 2, 3, 2, 1] # goal k rests the coin on finger ORDER[k % 6]: index (0) to pinky (3) and back +GRASP = np.array([0.6, 0.0, 0.3, 0.0, 0.3, 0.35, -0.1, 0.3, 0.2, 0.35, -0.04, 0.3, 0.2, 0.35, 0.04, 0.3, 0.2, 0.0, 0.35, + 0.1, 0.3, 0.2]) # fingers slightly curled and spread, 1.5-3 mm apart # fmt: skip +# a flip against its phase s: lateral progress to the next finger, lift (m) and roll (rad), from earlier plans' flips +KEYS = np.array([ + [0.0, 0.15, 0.35, 0.55, 0.8, 1.0], # s + [0.0, 0.1, 0.25, 0.55, 0.9, 1.0], # progress + [0.0, 0.0, 0.002, 0.003, 0.002, 0.0], # lift + [0.0, 0.43, 0.85, 1.45, 2.3, np.pi], # roll +]) # fmt: skip + + +def main(seeds: int = 1, seed0: int = 0): + """Plan `seeds` seeds from `seed0` at once, score each, and replay the first.""" + wp.config.log_level = wp.LOG_WARNING # no per-module load lines + wp.init() + joints = np.array([[5, 6], [9, 10], [13, 14], [18, 19]]) # each finger's flexion and side swing + half, skin = 0.0011, 0.001 # the coin's half thickness; contact starts 1 mm out, so it rests that far off + + # --- scene: the hand palm down 0.5 m high (fingers along +x, the index at +y), friction 1, stiff against itself; the coin flat on the back of the index's proximal phalanx --- + scene = mujoco.MjSpec.from_file(str(sharpa_hand.MJCF_PATH_RIGHT)) + for mesh in scene.meshes: # absolute mesh paths, so the viewer's copy finds them + mesh.file = str(sharpa_hand.MJCF_PATH_RIGHT.parent / scene.meshdir / mesh.file) + scene.meshdir, scene.option.timestep = "", 0.005 + root = scene.body("right_hand_C_MC") + root.pos, root.quat = [0, 0, 0.5], [np.sqrt(0.5), 0, np.sqrt(0.5), 0] + for geom in scene.geoms: + if geom.contype or geom.conaffinity: + geom.friction, geom.solmix = [1.0, 0.005, 1e-4], 0.0 + geom.solref, geom.solimp[:3] = [0.01, 1.0], [0.99, 0.999, 0.001] + coin = scene.worldbody.add_body(name="coin") # a 2-euro coin: 25.75 mm across, 2.2 mm thick, 8.5 g + coin.add_freejoint() + coin.add_geom( + name="coin", type=mujoco.mjtGeom.mjGEOM_CYLINDER, size=[0.012875, half, 0], solref=[0.01, 1.0], + solimp=[0.99, 0.999, 0.001, 0.5, 2], margin=skin, mass=0.0085, friction=[1.0, 0.005, 1e-4], condim=4, + rgba=[0.85, 0.68, 0.2, 1], + ) # fmt: skip + body = mujoco.mjtObj.mjOBJ_XBODY + scene.add_sensor(name="pos", type=mujoco.mjtSensor.mjSENS_FRAMEPOS, objtype=body, objname="coin") + scene.add_sensor(name="normal", type=mujoco.mjtSensor.mjSENS_FRAMEZAXIS, objtype=body, objname="coin") + for j in scene.joints[:22]: # the hand joints' speeds, for a smoothing cost + scene.add_sensor( + name=j.name, type=mujoco.mjtSensor.mjSENS_JOINTVEL, objtype=mujoco.mjtObj.mjOBJ_JOINT, objname=j.name + ) + model = scene.compile() + plan = scene.copy() # planned on the capsules and the coin, with a capped solver; executed on every shape + plan.option.iterations, plan.option.ls_iterations = 8, 8 + for geom in plan.geoms: + if geom.type != mujoco.mjtGeom.mjGEOM_CAPSULE and geom.name != "coin": + geom.contype = geom.conaffinity = 0 + fingers = ("thumb", "index", "middle", "ring", "pinky") + coin_geom, names = model.geom("coin").id, [model.body(model.geom_bodyid[g]).name for g in range(model.ngeom)] + owner = np.array([next((i for i, f in enumerate(fingers) if f"_{f}_" in n), 5) for n in names]) # 5: the palm + + # --- starts: 0.03 rad on the joints, 2 mm and 8 deg of tilt on the coin, a 1 s settle; kept if flat, fingers apart + probe, index = mujoco.MjData(model), model.geom("right_index_PP_fit").id + probe.qpos[:22] = GRASP + mujoco.mj_forward(model, probe) + start = probe.geom_xpos[index] + [0, -0.003, model.geom_size[index, 0] + half + skin + 0.002] + B, states = seeds, [] + for b in range(B): + rng = np.random.default_rng(seed0 + b) + while len(states) == b: + state, q = mujoco.MjData(model), GRASP + rng.uniform(-0.03, 0.03, 22) + tilt = rng.uniform(-np.radians(8), np.radians(8)) + state.qpos[:22], state.ctrl[:] = q, q + state.qpos[22:25] = start + [*rng.uniform(-0.002, 0.002, 2), 0] + state.qpos[25:29] = [np.cos(tilt / 2), np.sin(tilt / 2), 0, 0] + for _ in range(200): + mujoco.mj_step(model, state) + g = owner[state.contact.geom[: state.ncon]] + kiss = np.any((g[:, 0] != g[:, 1]) & np.isin(g, [1, 2, 3, 4]).all(1)) # two fingers touch + flat = state.xmat[model.body("coin").id][8] > np.cos(np.radians(30)) + if flat and not kiss and np.linalg.norm(state.qvel[22:25]) < 0.02: + states.append(state) + + # --- each finger's centreline and the coin's resting height on it, at the coin's x --- + pp = [model.geom(f"right_{f}_PP_fit").id for f in fingers[1:]] + x0, lines = np.array([s.qpos[22] for s in states]), np.array([s.geom_xpos[pp, 1] for s in states]) + axis = np.array([s.geom_xmat[pp].reshape(-1, 3, 3)[:, :, 2] for s in states]) # the capsules' axes + centre = np.array([s.geom_xpos[pp] for s in states]) + tops = centre[..., 2] + (x0[:, None] - centre[..., 0]) * axis[..., 2] / axis[..., 0] + model.geom_size[pp, 0] + tops, slope = tops + half + skin, np.arctan2(-axis[..., 2], axis[..., 0]).mean(1) + lanes = lines + [-0.004, 0, 0, 0.004] # the coin rests 4 mm inside the index and pinky, else it falls off + + def flip_ref(k: np.ndarray, u: np.ndarray) -> tuple: + """The coin's centre and face normal in crossing `k` (goal k to k + 1) at phase `u` of the flip shape.""" + a, b = np.take(ORDER, k % 6)[:, None], np.take(ORDER, (k + 1) % 6)[:, None] + go, lift, roll = (np.interp(np.clip(u, 0, 1), KEYS[0], KEYS[i]) for i in (1, 2, 3)) + y = lanes[rows, a] + (lanes[rows, b] - lanes[rows, a]) * go + z = tops[rows, a] + (tops[rows, b] - tops[rows, a]) * go + lift + roll, sl = np.pi * a + np.sign(b - a) * roll, slope[:, None] # the face normal tips the way the coin goes + normal = np.stack([np.cos(roll) * np.sin(sl), -np.sin(roll), np.cos(roll) * np.cos(sl)], -1) + return np.stack(np.broadcast_arrays(x0[:, None], y, z), -1), normal + + # --- SimMPC: track the coin through the flip to the next goal, the phase at most LEAD ahead of the coin's; the fingers get a feed-forward (the finger the coin leaves rises) and their side swing stays within 0.06 rad; the plan looks 0.88 s ahead, over a whole flip; three iterations a plan with shrinking noise cut stalls, all at the sim's step (coarser steps lose the coin) --- + H, pos, nrm, dt = 176, model.sensor("pos").adr[0], model.sensor("normal").adr[0], model.opt.timestep + rows = np.arange(B)[:, None] + ref = np.zeros((B, STEPS + H + 1, model.nsensordata), np.float32) + sensor_ref = wp.array(ref, dtype=float) + ctrl_ref = np.tile(GRASP.astype(np.float32), (B, ref.shape[1], 1)) + ctrl_wp = wp.array(ctrl_ref, dtype=float) + weight = np.full(model.nu, 0.2) + weight[joints[:, 1]] = 20.0 + ctrl_std = np.full(model.nu, 0.12) + ctrl_std[model.actuator_gainprm[:, 0] < 2] *= 2 # the weak distal joints need twice the noise to move a fingertip + ctrl_range = model.actuator_ctrlrange.copy() + side = [*joints[:, 1], 17] # the side swings and the pinky's cupping stay within 0.06 rad, so fingers rarely touch + ctrl_range[side] = GRASP[side, None] + [-0.06, 0.06] + config = SimMPCConfig( + ctrl_std=ctrl_std, ctrl_range=ctrl_range, batch_size=B, num_samples=128, horizon_steps=H, node_steps=50, + ctrl_steps=12, stages=[SimMPCStage(3)], std_growth=1.0, noise_decay=0.6, interpolation="cubic", terminal_scale=1.0, + seed=seed0, + ) # fmt: skip + speeds = {j.name: 0.1 for j in scene.joints[:22]} # a small cost on joint speed keeps the hand smooth + config.add(SensorTask(sensor_ref, dict(pos=20000.0, normal=20.0) | speeds)).add(ControlTask(weight, ctrl_wp)) + sim = MjWarpSim(model, B, states[0], nconmax=64, njmax=400) + for f in ("time", "qpos", "qvel", "act", "qacc_warmstart"): # each seed from its start + getattr(sim.data, f).assign(np.stack([getattr(s, f) for s in states])) + clock, goal, s, s_coin, mpc = 0, np.zeros(B, int), np.zeros(B), np.zeros(B), None + + def lead(plan: list): + nonlocal clock + if plan: # the goal is reached when its finger pushes on the coin, within 6 mm of its line, 45 deg of its face + clock += config.ctrl_steps + c, n = sim.data.qpos.numpy()[:, 22:25], sim.data.sensordata.numpy()[:, nrm : nrm + 3] + m = int(sim.data.nacon.numpy()[0]) + pair, world = sim.data.contact.geom.numpy()[:m], sim.data.contact.worldid.numpy()[:m] + hit = (pair == coin_geom).any(1) & (sim.data.contact.dist.numpy()[:m] < skin) + touching = np.zeros((B, 6), bool) + touching[world[hit], owner[np.where(pair[hit, 0] == coin_geom, pair[hit, 1], pair[hit, 0])]] = True + a, b = np.take(ORDER, goal % 6), np.take(ORDER, (goal + 1) % 6) + reached = touching[np.arange(B), b + 1] & (np.abs(c[:, 1] - lines[np.arange(B), b]) <= 0.006) + reached &= np.where(goal % 2, 1.0, -1.0) * n[:, 2] >= np.cos(np.pi / 4) + # the coin's phase: the lesser of what its progress across and its roll reach on the flip shape + go = (c[:, 1] - lanes[np.arange(B), a]) / (lanes[np.arange(B), b] - lanes[np.arange(B), a]) + roll = np.arccos(np.clip((n * flip_ref(goal, np.zeros((B, 1)))[1][:, 0]).sum(1), -1, 1)) + s_coin[:] = np.minimum(np.interp(go, KEYS[1], KEYS[0]), np.interp(roll, KEYS[3], KEYS[0])) + s[:] = np.minimum(s + config.ctrl_steps * dt / FLIP, s_coin + LEAD) + goal[:] += reached & (goal < 12) + s[:] = np.where(reached, -DWELL / FLIP, s) + s[:] = np.where(goal >= 12, -1.0, s) # after two round trips, hold the coin face up on the index + s_coin[:] = np.where(reached, s, s_coin) + u = np.minimum(s[:, None] + dt / FLIP * np.arange(H + 1), (s_coin + LEAD)[:, None]) + ref[:, clock : clock + H + 1, pos : pos + 3], ref[:, clock : clock + H + 1, nrm : nrm + 3] = flip_ref(goal, u) + sensor_ref.assign(ref) + # feed-forward over the flip (flexion, side swing): the finger the coin leaves rises, the one it lands on dips + a, b = np.take(ORDER, goal % 6), np.take(ORDER, (goal + 1) % 6) + bump = np.sin(np.pi * np.clip(u, 0, 1))[..., None] + target = np.tile(GRASP.astype(np.float32), (B, H + 1, 1)) + for i in range(B): + target[i][:, joints[a[i]]] += bump[i] * [-0.3, 0.0] + target[i][:, joints[b[i]]] += bump[i] * [0.06, 0.0] + prev = ctrl_ref[:, max(clock - 1, 0)] + for t in range(H + 1): # eased in over 50 ms + prev = ctrl_ref[:, clock + t] = prev + (target[:, t] - prev) * 0.1 + ctrl_wp.assign(ctrl_ref) + if mpc is not None: + mpc.ctrl_ref.assign(ctrl_ref) + + lead([]) + print("building SimMPC (the first run compiles kernels) ...") + mpc = SimMPC(config, MjWarpSim(plan.compile(), 1, states[0], nconmax=64, njmax=400), ctrl_ref) + print(f"planning {STEPS * dt:.0f} s of motion ...") + start = time.perf_counter() + rollouts, _ = mpc.execute(sim, STEPS, callback=lead) + print(f"planned in {time.perf_counter() - start:.0f} s") + + # --- score each seed on the executed shapes: a part of the hand pushes on the coin over 2 mN; a drop is 0.3 s with no push or the coin 5 cm below its start; each goal's face is its flattest normal while it holds --- + hand_only = scene.copy() + hand_only.geom("coin").contype = hand_only.geom("coin").conaffinity = 0 + check, passed = hand_only.compile(), 0 + cd, forward, force = mujoco.MjData(check), mujoco.MjData(model), np.zeros(6) + for b, x in enumerate(rollouts): + q, n, T = x["qpos"], x["sensordata"][:, nrm : nrm + 3], STEPS + touch, overlap, pierce, free = np.zeros((T, 6), bool), 0.0, 0.0, np.zeros(T, int) + for t in range(T): + forward.qpos[:], forward.qvel[:], forward.ctrl[:] = q[t], x["qvel"][t], x["ctrl"][t] + mujoco.mj_forward(model, forward) + for c in range(forward.ncon): + con = forward.contact[c] + if coin_geom in (con.geom1, con.geom2): + mujoco.mj_contactForce(model, forward, c, force) + touch[t, owner[con.geom1 + con.geom2 - coin_geom]] |= force[0] > 0.002 + pierce = max(pierce, -con.dist) + cd.qpos[:] = q[t] + mujoco.mj_kinematics(check, cd) + mujoco.mj_collision(check, cd) + overlap = max(overlap, -cd.contact.dist[: cd.ncon].min(initial=0.0)) + free[t] = 0 if touch[t].any() else free[t - 1] + 1 + drop = np.flatnonzero((free * dt >= 0.3) | (q[:, 24] - q[0, 24] < -0.05)) + k, reach = 0, [0] + for t in range(T): + f = ORDER[(k + 1) % 6] + if touch[t, f + 1] and abs(q[t, 23] - lines[b, f]) <= 0.006 and (-1) ** (k + 1) * n[t, 2] >= np.sqrt(0.5): + k, reach = k + 1, reach + [t] + flat = [] + for j, (t0, t1) in enumerate(zip(reach, reach[1:] + [T])): + f = ORDER[j % 6] + ok = touch[t0:t1, f + 1] & (np.abs(q[t0:t1, 23] - lines[b, f]) <= 0.006) + flat.append(n[t0 + np.where(ok, (-1) ** j * n[t0:t1, 2], -2.0).argmax()]) + turns = [float(np.degrees(np.arccos(np.clip(u @ v, -1, 1)))) for u, v in zip(flat, flat[1:])] + jitter = np.sqrt(np.mean(np.diff(q[::4, :22], 2, axis=0) ** 2)) / 0.02**2 + trip = k >= 6 and min(turns[:6]) >= 150 and pierce <= 0.002 and (drop[:1] > reach[6]).all() + ok = bool(trip and jitter <= 5 and overlap <= 0.001) + passed += ok + print(f"seed {seed0 + b}: {'pass' if ok else 'fail'}; {k} goals, turns {np.round(turns)}, coin " + f"{1000 * pierce:.1f} mm in, jitter {jitter:.1f} rad/s^2, overlap {1000 * overlap:.1f} mm") # fmt: skip + print(f"{passed}/{B} seeds pass") + if B > 1: + return + + # --- viewer: replay the simulated motion --- + server = viser.ViserServer() + print("replaying; Ctrl+C to stop") + viewer = ViserMjcf(server, scene.to_xml()) + while True: + for k in range(0, STEPS, 4): + viewer.update_qpos(rollouts[0]["qpos"][k]) + time.sleep(4 * dt) + time.sleep(1.0) # hold the last frame before replaying + + +if __name__ == "__main__": + tyro.cli(main) diff --git a/src/robokit/examples/sim_mpc/09_sharpa_cap.py b/src/robokit/examples/sim_mpc/09_sharpa_cap.py new file mode 100644 index 0000000..450bf9b --- /dev/null +++ b/src/robokit/examples/sim_mpc/09_sharpa_cap.py @@ -0,0 +1,224 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +# pyright: reportMissingImports=false +# pyright: reportArgumentType=false +"""SimMPC: a palm-down Sharpa Wave hand unscrews a bottle cap in 60 deg thumb-and-finger twists, with no training. Each seed starts from reset noise on the joints and the bottle's place and tilt, and passes with two turns in 15 s, no hand shape 2 mm into the cap or bottle, jitter at most 5 rad/s^2, no two hand shapes overlapping by over 1 mm, the cap within 15 deg of its reference (median) and no two of the four fingers touching. Held-out seeds 20000-20023 pass 23/24 in each of two runs; one seed plans 15 s in 59 s on an RTX 3090.""" + +import time + +import mujoco +import numpy as np +import tyro +import viser +import warp as wp + +from robokit.assets.robots.end_effectors import sharpa_hand +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim +from robokit.terms import ContactTask, ControlTask, SensorTask, StateTask, SupportTask +from robokit.utils.visualize_utils import ViserMjcf + + +STEPS = 3000 # 15 s at the 5 ms step +STEP, PERIOD, TURN, COUNT = np.radians(60), 0.8, 0.45, 14 # each twist: 60 deg over 0.45 s of every 0.8 s; 14 in all +GRASP = np.array([0.8408, 0.0874, 0.4856, -0.0684, 0.2538, 0.5119, -0.0032, 0.4689, 0.3745, 0.4867, -0.0119, 0.8655, + 0.3462, 0.9, 0.1, 1.1, 0.7, 0.1, 0.9, 0.2444, 1.1, 0.7]) # thumb opposite index, middle # fmt: skip + + +def reference(phase: np.ndarray) -> np.ndarray: + """The cap's planned turn, rad, at each phase, s: COUNT minimum-jerk twists of STEP, each held while fingers reset. + + Example: + >>> np.degrees(reference(np.array([0.0, 0.225, 0.6, 1.025, 50.0]))).round(1).tolist() + [0.0, 30.0, 60.0, 90.0, 840.0] + """ + k = np.minimum(phase // PERIOD, COUNT) + u = np.clip((phase - k * PERIOD) / TURN, 0, 1) + return STEP * (k + (k < COUNT) * u**3 * (10 - 15 * u + 6 * u**2)) + + +def main(seeds: int = 1, seed0: int = 0): + """Plan `seeds` seeds from `seed0` at once, score each, and replay the first.""" + wp.config.log_level = wp.LOG_WARNING # no per-module load lines + wp.init() + centre, skin = np.array([0.0, 0.0, 0.205]), 0.001 # the cap's centre, the bottle below it; contact starts 1 mm out + fingers = ("thumb", "index", "middle", "ring", "pinky") # the first three twist the cap + + # --- scene: the hand palm-down over a fixed 500 ml PET bottle, friction 1, stiff against itself; the 30 x 12 mm, 2.5 g cap of a 28 mm neck turns on a hinge with a cracked-open cap's 0.05 N m running torque, and a slide coupled to it by the 3 mm thread pitch lifts it as it turns --- + scene = mujoco.MjSpec.from_file(str(sharpa_hand.MJCF_PATH_RIGHT)) + for mesh in scene.meshes: # absolute mesh paths, so the viewer's copy finds them + mesh.file = str(sharpa_hand.MJCF_PATH_RIGHT.parent / scene.meshdir / mesh.file) + scene.meshdir, scene.option.timestep = "", 0.005 + root = scene.body("right_hand_C_MC") + root.pos, root.quat = [-0.0823, -0.1084, 0.2861], [0.6424, -0.2343, 0.6933, 0.2274] + for geom in scene.geoms: + if geom.contype or geom.conaffinity: + geom.friction, geom.solmix = [1.0, 0.005, 1e-4], 0.0 + geom.solref, geom.solimp[:3] = [0.01, 1.0], [0.99, 0.999, 0.001] + stiff = dict(friction=[1.0, 0.005, 1e-4], solref=[0.01, 1.0], solimp=[0.99, 0.999, 0.001, 0.5, 2]) + cylinder = mujoco.mjtGeom.mjGEOM_CYLINDER + bottle = scene.worldbody.add_body(name="bottle", pos=centre) # its frame is the cap's centre, so tilts pivot there + for name, radius, half, z in [("body", 0.0325, 0.085, -0.12), ("neck", 0.0125, 0.0145, -0.0205), + ("ring", 0.0165, 0.001, -0.015)]: # radius, half height, z; m # fmt: skip + bottle.add_geom(name=f"bottle_{name}", type=cylinder, size=[radius, half, 0], pos=[0, 0, z], + contype=2, conaffinity=1, margin=skin, rgba=[0.75, 0.88, 0.95, 0.5], **stiff) # fmt: skip + cap = bottle.add_body(name="cap") + cap.add_joint(name="lift", type=mujoco.mjtJoint.mjJNT_SLIDE, axis=[0, 0, 1]) + firm = [0.9999, 0.9999, 0.001, 0.5, 2] # MuJoCo's default would let the light cap creep at 26 rad/s at 0.02 N m + cap.add_joint(name="turn", type=mujoco.mjtJoint.mjJNT_HINGE, axis=[0, 0, 1], frictionloss=0.05, damping=5e-4, + solref_friction=[0.01, 1.0], solimp_friction=firm, limited=True, range=[-0.05, 1e3], + solref_limit=[0.01, 1.0], solimp_limit=firm) # seated, it cannot tighten further # fmt: skip + cap.add_geom(name="cap", type=cylinder, size=[0.015, 0.006, 0], mass=0.0025, contype=4, conaffinity=1, + margin=skin, condim=4, rgba=[0.9, 0.2, 0.15, 1], **stiff) # fmt: skip + cap.add_geom(type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.013, 0.002, 5e-4], pos=[0, 0, 0.006], contype=0, conaffinity=0, + density=0, rgba=[1, 1, 1, 1]) # a stripe across the top shows the turn # fmt: skip + thread = scene.add_equality(type=mujoco.mjtEq.mjEQ_JOINT, name1="turn", name2="lift") # turn = 2 pi lift / pitch + thread.data[1], thread.solref, thread.solimp[:3] = 2 * np.pi / 0.003, [0.01, 1.0], [0.99, 0.999, 0.001] + for actuator in scene.actuators: # twice the servos' damping, calmer fingers; their speeds, for the plan's cost + actuator.biasprm[2] *= 2 + scene.add_sensor(name=actuator.name, type=mujoco.mjtSensor.mjSENS_ACTUATORVEL, + objtype=mujoco.mjtObj.mjOBJ_ACTUATOR, objname=actuator.name) # fmt: skip + for f in fingers[:3]: # where the thumb, index and middle tips are, for the plan's cost on their height + scene.add_sensor(name=f, type=mujoco.mjtSensor.mjSENS_FRAMEPOS, objtype=mujoco.mjtObj.mjOBJ_XBODY, + objname=f"right_{f}_DP") # fmt: skip + scene.add_sensor(name="turn", type=mujoco.mjtSensor.mjSENS_JOINTPOS, objtype=mujoco.mjtObj.mjOBJ_JOINT, + objname="turn") # fmt: skip + plan = scene.copy() # planned on the capsules, cap and bottle, with a capped solver; executed on every shape + plan.option.iterations, plan.option.ls_iterations = 8, 8 + for geom in plan.geoms: + kept = geom.type == mujoco.mjtGeom.mjGEOM_CAPSULE or geom.name.endswith("VL_fit") # links and knuckles + if not kept and not geom.name.startswith(("cap", "bottle")): + geom.contype = geom.conaffinity = 0 + + # --- starts: 0.03 rad on the joints, 2 mm on the bottle's place and 5 deg of tilt about x and y, a 1 s settle --- + B, specs, plans, models, states, hold = seeds, [], [], [], [], GRASP.copy() + hold[[0, 5, 9]] += 0.1 # the commands press the thumb, index and middle onto the cap + hold[[6, 10]] += [-0.05, 0.05] # and hold the index and middle a little apart + for b in range(B): + rng = np.random.default_rng(seed0 + b) + q, place = GRASP + rng.uniform(-0.03, 0.03, 22), centre + rng.uniform(-0.002, 0.002, 3) + quat = np.array([1.0, 0, 0, 0]) + mujoco.mju_quatIntegrate(quat, [*rng.uniform(-np.radians(5), np.radians(5), 2), 0.0], 1.0) + for spec, out in ((scene.copy(), specs), (plan.copy(), plans)): + spec.body("bottle").pos, spec.body("bottle").quat = place, quat + out.append(spec) + models.append(specs[-1].compile()) + states.append(mujoco.MjData(models[-1])) + states[-1].qpos[:22], states[-1].ctrl[:] = q, hold + q - GRASP + for _ in range(200): + mujoco.mj_step(models[-1], states[-1]) + model = models[0] + print(f"scene: {model.nq} qpos, {model.nu} actuators; cap at {np.degrees(states[0].qpos[23]):.1f} deg") + + # --- SimMPC: track the reference on a phase clock; the twisting tips stay at the rim's height, two on the cap; touches by the lower phalanges, of the bottle and between fingers cost, and the fingertips' a little; the joints are kept slow, and the ring and pinky barely explored --- + H, turn, dt = 100, model.sensor("turn").adr[0], model.opt.timestep + tips = [model.sensor(f).adr[0] + 2 for f in fingers[:3]] + height = np.array([[s.xpos[model.body(f"right_{f}_DP").id, 2] for f in fingers[:3]] for s in states]) + ref = np.zeros((B, STEPS + H + 1, model.nsensordata), np.float32) + sensor_ref = wp.array(ref, dtype=float) + ctrl_ref = np.tile(hold, (ref.shape[1], 1)) + ctrl_std = np.full(model.nu, 0.09) + ctrl_std[13:] *= 0.2 # the ring and pinky stay out of the twist + config = SimMPCConfig( # one iteration of 512 draws a plan, weighted by their cheapest 10% + ctrl_std=ctrl_std, batch_size=B, num_samples=512, horizon_steps=H, node_steps=25, ctrl_steps=8, + stages=[SimMPCStage(1)], elite_ratio=0.1, interpolation="cubic", std_growth=1.0, terminal_scale=1.0, + seed=seed0, + ) # fmt: skip + links = [geom.name for geom in scene.geoms if geom.name.endswith("_fit") or geom.name.startswith("bottle")] + tip_geoms = [f"right_{f}_fingertip_collision" for f in fingers[:3]] + config.add(SensorTask(sensor_ref, dict(turn=60.0)), terminal_scale=10.0) + config.add(SensorTask(sensor_ref, {actuator.name: 0.1 for actuator in scene.actuators})) # their references are 0 + config.add(SensorTask(sensor_ref, {f: [0, 0, 1e5] for f in fingers[:3]}, hinge=1e5 * 0.003**2)) # 3 mm of the rim + config.add(ControlTask(1.0, ctrl_ref)) + config.add(ContactTask(links, np.zeros((1, len(links), 2)), np.zeros((1, len(links))), penalty=20.0, margin=skin)) + config.add(SupportTask("cap", [f"{f}_fingertip" for f in fingers[:3]], 2, 5.0, skin)) # two of them on the cap + config.add(ContactTask(tip_geoms, np.zeros((1, 3, 2)), np.zeros((1, 3)), penalty=5.0, margin=skin)) + names = [mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, model.geom_bodyid[g]) or "" for g in range(model.ngeom)] + of = {f: np.array([f"_{f}_" in n for n in names]) for f in fingers} + rest = of["index"] | of["middle"] | of["ring"] | of["pinky"] + for a, b in [(of["thumb"], rest), (of["index"] | of["ring"], of["middle"] | of["pinky"])]: # any touch costs + config.add(StateTask(np.zeros((1, model.nq)), np.zeros((1, model.nv)), np.zeros(model.nv), + penetration_groups=(a, b), penetration_scale=1e7, margin=-0.002)) # fmt: skip + sim = MjWarpSim(specs, [1] * B, nconmax=48, njmax=300) # each seed's bottle where its draw put it + for f in ("time", "qpos", "qvel", "act", "qacc_warmstart"): # each seed from its start + getattr(sim.data, f).assign(np.stack([getattr(s, f) for s in states])) + clock, phase, first = 0, np.zeros(B), np.array([s.qpos[23] for s in states]) + + def lead(plan: list): + nonlocal clock + angle = sim.data.qpos.numpy()[:, 23] - first + if plan: # the phase advances unless the cap lags its reference by over 0.35 rad + clock += config.ctrl_steps + phase[reference(phase + config.ctrl_steps * dt) <= angle + 0.35] += config.ctrl_steps * dt + p = phase[:, None] + dt * np.arange(H + 1) + ref[:, clock : clock + H + 1, turn] = first[:, None] + reference(p) + lift = reference(p)[..., None] * 0.003 / (2 * np.pi) # the cap rises 3 mm a turn; the tips stay at its rim + ref[:, clock : clock + H + 1, tips] = height[:, None] + lift + sensor_ref.assign(ref) + + lead([]) + print("building SimMPC (the first run compiles kernels) ...") + # planned on `plans` + mpc = SimMPC(config, MjWarpSim(plans, [1] * B, nconmax=48, njmax=300), ctrl_ref) + print(f"planning {STEPS * dt:.0f} s of motion ...") + start = time.perf_counter() + rollouts, _ = mpc.execute(sim, STEPS, callback=lead) + print(f"planned in {time.perf_counter() - start:.0f} s") + + # --- score each seed on the executed shapes (CPU MuJoCo): depths into the cap and bottle, every second state; overlaps and touches between fingers, every state --- + finger = [next((i for i, f in enumerate(fingers) if f"_{f}_" in n), -1) for n in names] + objects = {model.geom(n).id for n in ("cap", "bottle_body", "bottle_neck", "bottle_ring")} + cap_geom = model.geom("cap").id + hand_only = scene.copy() + for geom in hand_only.geoms: + if geom.name.startswith(("cap", "bottle")): + geom.contype = geom.conaffinity = 0 + check, passed = hand_only.compile(), 0 + for b, x in enumerate(rollouts): + q, forward, cd = x["qpos"], mujoco.MjData(models[b]), mujoco.MjData(check) + depth, overlap, touches = {"cap": 0.0, "bottle": 0.0}, 0.0, 0 + for t in range(STEPS): + cd.qpos[:] = q[t] + mujoco.mj_kinematics(check, cd) + mujoco.mj_collision(check, cd) + for con in cd.contact[: cd.ncon]: + overlap, f1, f2 = max(overlap, -con.dist), finger[con.geom1], finger[con.geom2] + touches += f1 > 0 and f2 > 0 and f1 != f2 # two of the four fingers touch + if t % 2 == 0: + forward.qpos[:], forward.qvel[:], forward.ctrl[:] = q[t], x["qvel"][t], x["ctrl"][t] + mujoco.mj_forward(models[b], forward) + for con in forward.contact[: forward.ncon]: + if con.geom1 in objects or con.geom2 in objects: + key = "cap" if cap_geom in (con.geom1, con.geom2) else "bottle" + depth[key] = max(depth[key], -con.dist) + net = q[-1, 23] - q[0, 23] + jitter = np.sqrt(np.mean(np.diff(q[::4, :22], 2, axis=0) ** 2)) / 0.02**2 + error = np.degrees(np.median(np.abs(q[:, 23] - ref[b, :STEPS, turn]))) # to the planner's reference + ok = bool(net >= 4 * np.pi and max(depth.values()) <= 0.002 and jitter <= 5 and overlap <= 0.001) + ok &= bool(error <= 15 and touches == 0) + passed += ok + print(f"seed {seed0 + b}: {'pass' if ok else 'fail'}; {net / (2 * np.pi):.2f} turns, {error:.1f} deg off, " + f"cap {1000 * depth['cap']:.1f} mm and bottle {1000 * depth['bottle']:.1f} mm in, jitter {jitter:.1f} " + f"rad/s^2, overlap {1000 * overlap:.1f} mm, {touches} finger touches") # fmt: skip + print(f"{passed}/{B} seeds pass") + if B > 1: + return + + # --- viewer: replay the simulated motion --- + server = viser.ViserServer() + print("replaying; Ctrl+C to stop") + viewer = ViserMjcf(server, specs[0].to_xml()) + while True: + for k in range(0, STEPS, 4): + viewer.update_qpos(rollouts[0]["qpos"][k]) + time.sleep(4 * dt) + time.sleep(1.0) # hold the last frame before replaying + + +if __name__ == "__main__": + tyro.cli(main) diff --git a/src/robokit/examples/sim_mpc/09_sharpa_cube.py b/src/robokit/examples/sim_mpc/10_wuji_cube.py similarity index 67% rename from src/robokit/examples/sim_mpc/09_sharpa_cube.py rename to src/robokit/examples/sim_mpc/10_wuji_cube.py index 1a2dd15..7ff3f66 100644 --- a/src/robokit/examples/sim_mpc/09_sharpa_cube.py +++ b/src/robokit/examples/sim_mpc/10_wuji_cube.py @@ -7,7 +7,7 @@ # /// # pyright: reportMissingImports=false # pyright: reportArgumentType=false -"""SimMPC: a palm-up Sharpa Wave hand tumbles a 5.5 cm cube through 90 deg turns about x, y and z, with no training.""" +"""SimMPC: a palm-up Wuji Hand 2.2 tumbles a 5.5 cm cube through 90 deg turns about x, y and z, with no training.""" import time @@ -16,9 +16,9 @@ import viser import warp as wp -from robokit.assets.robots.end_effectors import sharpa_hand -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.assets.robots.end_effectors import wuji_hand_2_2 +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import ControlTask, SensorTask from robokit.utils.visualize_utils import ViserMjcf @@ -26,9 +26,11 @@ STEPS = 4000 # 20 s at the 5 ms step HALF = 0.0275 # the cube's half width, m AXES = dict(x=[1.0, 0, 0], y=[0, 1.0, 0], z=[0, 0, 1.0]) # the goals turn about these in turn -GRASP = np.array([1.4445, -0.1589, -0.2534, -0.2884, 0.6587, 0.3551, -0.0365, 0.9138, 0.6397, 0.3408, -0.0403, 0.6072, - 0.425, 0.3934, -0.0002, 0.7814, 0.547, 0.2346, 0.5312, 0.078, 0.6275, 0.4392]) # cupped round the cube # fmt: skip -CUBE_POS, CUBE_QUAT = [0.0987, -0.0142, 0.5487], [0.9379, -0.0135, -0.0066, 0.3465] +GRASP = np.array([0.1323, -1.1366, 1.1103, 1.1261, 0.5087, -0.1223, 0.8138, 0.5697, 0.5484, -0.0178, 1.0374, 0.7264, + 0.4018, -0.0639, 0.5755, 0.4028, 0.4431, 0.0927, 0.3608, 0.2524]) # the hand settled round the cube # fmt: skip +HOLD = np.array([0.1886, -1.1457, 1.0919, 1.1201, 0.5781, -0.1243, 0.8197, 0.6191, -0.0173, 1.0349, 0.4888, -0.0593, + 0.5915, 0.511, 0.097, 0.3807]) # the commands that keep it there, a little deeper: they squeeze # fmt: skip +CUBE_POS, CUBE_QUAT = [0.0874, -0.0074, 0.539], [0.8336, 0.0267, 0.0519, 0.5493] FACES = [([1, 0, 0], (220, 40, 40)), ([-1, 0, 0], (245, 140, 30)), ([0, 1, 0], (40, 170, 80)), ([0, -1, 0], (40, 100, 220)), ([0, 0, 1], (245, 245, 245)), ([0, 0, -1], (245, 215, 40))] # fmt: skip @@ -37,14 +39,14 @@ def main(): wp.config.log_level = wp.LOG_WARNING # no per-module load lines wp.init() - # --- scene: the hand palm-up 0.5 m high, friction 1, stiff against itself (solmix 0 leaves the cube's contacts to - # the cube's defaults); a 50 g cube in the cupped fingers, a coloured plate on each face --- - scene = mujoco.MjSpec.from_file(str(sharpa_hand.MJCF_PATH_RIGHT)) + # --- scene: the hand palm-up 0.5 m high (palm normal +y to world +z, fingers -z to +x), friction 1, stiff against itself; a 50 g cube in the cupped fingers, a coloured plate on each face --- + scene = mujoco.MjSpec.from_file(str(wuji_hand_2_2.MJCF_PATH_RIGHT)) for mesh in scene.meshes: # absolute mesh paths, so the viewer's copy finds them - mesh.file = str(sharpa_hand.MJCF_PATH_RIGHT.parent / scene.meshdir / mesh.file) + mesh.file = str(wuji_hand_2_2.MJCF_PATH_RIGHT.parent / scene.meshdir / mesh.file) scene.meshdir, scene.option.timestep = "", 0.005 - root = scene.body("right_hand_C_MC") - root.pos, root.quat = [0, 0, 0.5], [0, np.sqrt(0.5), 0, np.sqrt(0.5)] + scene.option.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST # the fingers are light; implicit damping holds + root = scene.body("r_mount") + root.pos, root.quat = [0, 0, 0.5], [-0.5, -0.5, 0.5, 0.5] for geom in scene.geoms: if geom.contype or geom.conaffinity: geom.friction, geom.solmix = [1.0, 0.005, 1e-4], 0.0 @@ -60,21 +62,21 @@ def main(): scene.add_sensor(name="pos", type=mujoco.mjtSensor.mjSENS_FRAMEPOS, objtype=body, objname="cube") scene.add_sensor(name="quat", type=mujoco.mjtSensor.mjSENS_FRAMEQUAT, objtype=body, objname="cube") # as in a person's finger, the last joint follows the one before it - for finger in ("index", "middle", "ring", "pinky"): - scene.delete(scene.actuator(f"right_{finger}_DIP")) - scene.add_equality(type=mujoco.mjtEq.mjEQ_JOINT, objtype=mujoco.mjtObj.mjOBJ_JOINT, name1=f"right_{finger}_DIP", - name2=f"right_{finger}_PIP", data=[0, 0.7, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # fmt: skip + for finger in ("index_finger", "middle_finger", "ring_finger", "pinky"): + scene.delete(next(actuator for actuator in scene.actuators if actuator.target == f"r_{finger}_dip")) + coupling = scene.add_equality(type=mujoco.mjtEq.mjEQ_JOINT, objtype=mujoco.mjtObj.mjOBJ_JOINT, + name1=f"r_{finger}_dip", name2=f"r_{finger}_pip") # fmt: skip + coupling.data[1] = 0.7 # DIP = 0.7 PIP; the data length differs across MuJoCo versions for actuator in scene.actuators: # calmer fingers: twice the servo damping, and a speed sensor for the plan's cost actuator.biasprm[2] *= 2 scene.add_sensor(name=actuator.name, type=mujoco.mjtSensor.mjSENS_ACTUATORVEL, objtype=mujoco.mjtObj.mjOBJ_ACTUATOR, objname=actuator.name) # fmt: skip model = scene.compile() state = mujoco.MjData(model) - grasp = GRASP[model.actuator_trnid[:, 0]] - state.qpos[:22], state.ctrl[:] = GRASP, grasp + state.qpos[:20], state.ctrl[:] = GRASP, HOLD for _ in range(200): # let the cube settle into the grasp for 1 s mujoco.mj_step(model, state) - print(f"scene: {model.nq} qpos, {model.nu} actuators; cube settled at {np.round(state.qpos[22:25], 3)}") + print(f"scene: {model.nq} qpos, {model.nu} actuators; cube settled at {np.round(state.qpos[20:23], 3)}") # --- goals: each one 90 deg about the next axis from the last; the planner reads the current one in place --- def turned(q_wxyz: np.ndarray, index: int) -> np.ndarray: @@ -83,16 +85,15 @@ def turned(q_wxyz: np.ndarray, index: int) -> np.ndarray: mujoco.mju_mulQuat(out, turn, q_wxyz) return out - goal, reached = turned(state.qpos[25:29], 0), [] + goal, reached = turned(state.qpos[23:27], 0), [] a, pos = model.sensor("quat").adr[0], model.sensor("pos").adr[0] ref = np.zeros((1, 1, model.nsensordata), np.float32) - ref[0, 0, a : a + 4], ref[0, 0, pos : pos + 3] = goal, state.qpos[22:25] + ref[0, 0, a : a + 4], ref[0, 0, pos : pos + 3] = goal, state.qpos[20:23] sensor_ref = wp.array(ref, dtype=float) - # --- SimMPC: hold the cube's centre, turn it to the goal, keep the fingers near the grasp and slow; a 0.9 s plan - # with 0.3 s nodes, refined twice; wide noise is what keeps it from stalling --- + # --- SimMPC: hold the cube's centre, turn it to the goal, keep the fingers near the grasp and slow; a 0.9 s plan with 0.3 s nodes, refined twice; wide noise is what keeps it from stalling --- H = 180 - ctrl_ref = np.tile(grasp, (STEPS + H + 1, 1)) + ctrl_ref = np.tile(HOLD, (STEPS + H + 1, 1)) costs = [ SensorTask(sensor_ref, dict(quat=5.0), residual="quaternion", freeze_reference=True), SensorTask(sensor_ref, dict(pos=5000.0), freeze_reference=True), @@ -100,17 +101,19 @@ def turned(q_wxyz: np.ndarray, index: int) -> np.ndarray: ControlTask(0.02, ctrl_ref), ] config = SimMPCConfig( - num_samples=128, horizon_steps=H, node_steps=60, ctrl_steps=4, max_iterations=2, std_growth=1.0, - interpolation="cubic", terminal_scale=1.0, seed=1, + num_samples=128, horizon_steps=H, node_steps=60, ctrl_steps=12, std_growth=1.0, + stages=[SimMPCStage(2, [(0.25, None), (1.0, 0.02)])], + interpolation="cubic", terminal_scale=1.0, seed=0, ctrl_std=0.12, ) # fmt: skip - sim = MjWarpSim(model, state, nconmax=96, njmax=600) + for cost in costs: + config.add(cost) goals = [] # --- after each control period: a cube within 0.4 rad of its goal gets the next one --- def next_goal(plan: list): nonlocal goal goals.extend([goal] * config.ctrl_steps) - q_wxyz = sim.data["execution"].qpos.numpy()[0, 25:29] + q_wxyz = sim.data.qpos.numpy()[0, 23:27] if 2 * np.arccos(min(abs(q_wxyz @ goal), 1.0)) < 0.4: reached.append(len(goals) * model.opt.timestep) goal = turned(goal, len(reached)) @@ -118,17 +121,17 @@ def next_goal(plan: list): sensor_ref.assign(ref) print("building SimMPC (the first run compiles kernels) ...") - mpc = SimMPC(sim, ctrl_ref, np.full(model.nu, 0.12), costs, config, ctrl_range=model.actuator_ctrlrange) + sim = MjWarpSim(model, 1, state, nconmax=96, njmax=600) # plans on copies of it, executes on it + mpc = SimMPC(config, sim, ctrl_ref) print(f"planning {STEPS * model.opt.timestep:.0f} s of motion ...") start = time.perf_counter() - (rollout,), _ = mpc.solve(STEPS, callback=next_goal) + (rollout,), _ = mpc.execute(sim, STEPS, callback=next_goal) planned = time.perf_counter() - start - # --- score: goals, the slowest 5 s, drop, the deepest finger-finger overlap, and jitter, the joints' RMS - # acceleration at 50 Hz: the LEAP cube's is 4.24 rad/s^2 --- + # --- score: goals, the slowest 5 s, drop, the deepest finger-finger overlap, and jitter, the joints' RMS acceleration at 50 Hz: the LEAP cube's is 4.24 rad/s^2 --- slowest = np.histogram(reached, bins=np.arange(0, 20.1, 5))[0].min() - dropped = bool(np.any(rollout["qpos"][:, 24] < state.qpos[24] - 0.05)) - jitter = np.sqrt(np.mean(np.diff(rollout["qpos"][::4, :22], 2, axis=0) ** 2)) / 0.02**2 + dropped = bool(np.any(rollout["qpos"][:, 22] < state.qpos[22] - 0.05)) + jitter = np.sqrt(np.mean(np.diff(rollout["qpos"][::4, :20], 2, axis=0) ** 2)) / 0.02**2 hand_only = scene.copy() hand_only.geom("cube").contype = hand_only.geom("cube").conaffinity = 0 check = hand_only.compile() @@ -148,7 +151,7 @@ def next_goal(plan: list): server = viser.ViserServer() print("replaying; Ctrl+C to stop") viewer = ViserMjcf(server, scene.to_xml()) - ghost = server.scene.add_frame("/goal", show_axes=False, position=(0.12, 0.15, 0.6)) + ghost = server.scene.add_frame("/goal", show_axes=False, position=(0.09, 0.13, 0.6)) for i, (axis, color) in enumerate(FACES): dimensions, position = np.where(axis, 1e-3, 2 * HALF), (HALF - 5e-4) * np.array(axis) server.scene.add_box(f"/goal/{i}", color=color, dimensions=dimensions, position=position) diff --git a/src/robokit/examples/sim_mpc/10_h1_jog.py b/src/robokit/examples/sim_mpc/11_h1_jog.py similarity index 88% rename from src/robokit/examples/sim_mpc/10_h1_jog.py rename to src/robokit/examples/sim_mpc/11_h1_jog.py index 1f276c3..7044ab7 100644 --- a/src/robokit/examples/sim_mpc/10_h1_jog.py +++ b/src/robokit/examples/sim_mpc/11_h1_jog.py @@ -17,8 +17,8 @@ import warp as wp from robot_descriptions import h1_mj_description -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import SensorTask from robokit.utils.visualize_utils import ViserMjcf @@ -30,8 +30,7 @@ def main(): wp.config.log_level = wp.LOG_WARNING # no per-module load lines wp.init() - # --- scene: Menagerie's H1 touching the floor with one capsule per foot, and PD servos (kp 200, or 60 on the - # ankles and arms, kd = kp / 40) whose torques clip to the motors' limits, their targets to the jog's ranges --- + # --- scene: Menagerie's H1 touching the floor with one capsule per foot, and PD servos (kp 200, or 60 on the ankles and arms, kd = kp / 40) whose torques clip to the motors' limits, their targets to the jog's ranges --- scene = mujoco.MjSpec.from_file(str(Path(h1_mj_description.MJCF_PATH).parent / "scene.xml")) scene.meshdir = str(Path(h1_mj_description.MJCF_PATH).parent / "assets") # absolute, for the viewer's copy scene.option.timestep, scene.option.iterations, scene.option.ls_iterations = DT, 2, 5 @@ -71,8 +70,7 @@ def main(): mujoco.mj_resetDataKeyframe(model, state, 0) # standing, knees bent mujoco.mj_forward(model, state) - # --- targets: forward speed ramping to 2 m/s, the torso at 1.3 m, upright, heading 0, alternating 20 cm foot - # lifts at 2 Hz (each foot down 30% of a cycle), and small torques --- + # --- targets: forward speed ramping to 2 m/s, the torso at 1.3 m, upright, heading 0, alternating 20 cm foot lifts at 2 Hz (each foot down 30% of a cycle), and small torques --- T = STEPS + 64 # the horizon runs past the episode t = np.arange(T) * DT velocity = np.minimum(SPEED * t / 3.0, SPEED) @@ -106,20 +104,22 @@ def main(): # --- SimMPC: replan every step over a 0.5 s horizon of 6 nodes --- limits = model.actuator_ctrlrange config = SimMPCConfig( - num_samples=2048, horizon_steps=25, node_steps=5, ctrl_steps=1, max_iterations=4, init_iterations=10, + num_samples=2048, horizon_steps=25, node_steps=5, ctrl_steps=1, init_iterations=10, + stages=[SimMPCStage(4, [(0.25, None), (1.0, 0.04)])], # 1.4x faster, tracking error 0.009 vs 0.017 fine min_improvement=-np.inf, std_growth=1.0, noise_decay=0.5, min_std=1e-6, - terminal_scale=1.0, + terminal_scale=1.0, ctrl_std=(limits[:, 1] - limits[:, 0]) / 2, interpolation=basis, ) # fmt: skip + for cost in costs: + config.add(cost) print("building SimMPC (the first run compiles kernels) ...") - ctrl_ref, ctrl_std = np.tile(limits.mean(1), (T, 1)), (limits[:, 1] - limits[:, 0]) / 2 - mpc = SimMPC(MjWarpSim(model, state), ctrl_ref, ctrl_std, costs, config, spline_basis=basis, ctrl_range=limits) + sim = MjWarpSim(model, 1, state, nconmax=120, njmax=500) # plans on copies of it, executes on it + mpc = SimMPC(config, sim, np.tile(limits.mean(1), (T, 1))) print(f"planning {STEPS * DT:.0f} s of motion ...") start = time.perf_counter() report = lambda plans: plans[0]["t0"] % 50 or print(f" t={plans[0]['t0'] * DT:.0f} s: cost {plans[0]['plan_cost']:.3f}") # fmt: skip - (rollout,), _ = mpc.solve(STEPS, callback=report) + (rollout,), _ = mpc.execute(sim, STEPS, callback=report) - # --- check: mean squared velocity error (forward and sideways, plus the yaw rate in degrees/s scaled by pi/180), - # and no fall (pelvis tipped past ~73 deg or torso below 0.5 m) --- + # --- check: mean squared velocity error (forward and sideways, plus the yaw rate in degrees/s scaled by pi/180), and no fall (pelvis tipped past ~73 deg or torso below 0.5 m) --- data = rollout["sensordata"] error = np.sum((data[:, adr["torso_vel"] :][:, :2] - np.c_[velocity[:STEPS], 0 * velocity[:STEPS]]) ** 2, 1) error = np.mean(error + (data[:, adr["torso_gyro"] + 2] * np.pi / 180) ** 2) diff --git a/src/robokit/examples/sim_mpc/11_go2_jump.py b/src/robokit/examples/sim_mpc/12_go2_jump.py similarity index 86% rename from src/robokit/examples/sim_mpc/11_go2_jump.py rename to src/robokit/examples/sim_mpc/12_go2_jump.py index d8494af..c39a681 100644 --- a/src/robokit/examples/sim_mpc/11_go2_jump.py +++ b/src/robokit/examples/sim_mpc/12_go2_jump.py @@ -6,7 +6,10 @@ # robokit = { path = "../../../..", editable = true } # /// # pyright: reportMissingImports=false -"""SimMPC: a torque-driven Unitree Go2 makes four 40 cm jumps, landing each one's feet inside 10 cm target circles.""" +"""SimMPC: a torque-driven Unitree Go2 makes four 40 cm jumps, landing each one's feet inside 10 cm target circles. + +DIAL-MPC: https://arxiv.org/abs/2409.15610. +""" import time from pathlib import Path @@ -18,15 +21,14 @@ from robot_descriptions import go2_mj_description from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.sim import MjWarpSim from robokit.terms import ContactTask, SensorTask from robokit.utils.visualize_utils import ViserMjcf FEET, FOOT_RADIUS = ("FR", "FL", "RR", "RL"), 0.033 # holds the foot mesh, with room for the soft contact's 1 cm sink STEPS, STAGE, DT = 400, 50, 0.02 # 8 s; a jump each second (50 steps of 20 ms) -# floor capsules (fromto, radius) in each link's frame, fitted to the meshes: the whole thigh below the hip head, and the -# calf's floor side (its arch always faces up), ending at the foot sphere so that the foot still lands +# floor capsules (fromto, radius) in each link's frame, fitted to the meshes: the whole thigh below the hip head, and the calf's floor side (its arch always faces up), ending at the foot sphere so that the foot still lands CAPSULES = {"thigh": ([-0.01, 0, -0.05, -0.0025, 0, -0.2], 0.03), "calf": ([0, 0, 0.01, 0.001, 0, -0.195], 0.02)} @@ -34,8 +36,7 @@ def main(): wp.config.log_level = wp.LOG_WARNING # no per-module load lines wp.init() - # --- scene: Menagerie's Go2 with a heavier base, light joint damping, only the legs meeting the floor, and PD - # servos (kp 30, no torque limit) on the joints, their targets clipped to the jump's joint ranges --- + # --- scene: Menagerie's Go2 with a heavier base, light joint damping, only the legs meeting the floor, and PD servos (kp 30, no torque limit) on the joints, their targets clipped to the jump's joint ranges --- scene = mujoco.MjSpec.from_file(str(Path(go2_mj_description.MJCF_PATH).parent / "scene_mjx.xml")) scene.meshdir = str(Path(go2_mj_description.MJCF_PATH).parent / "assets") # absolute, for the viewer's copy scene.option.timestep, scene.option.iterations, scene.option.impratio = DT, 2, 1.0 @@ -90,8 +91,7 @@ def main(): SensorTask(sensor_ref, {"torso_pos": 1.0, "torso_zaxis": 1.0, **{f: [10.0, 10.0, 0.0] for f in FEET}}), SensorTask(sensor_ref, {"heading": 0.3}, residual="heading"), ContactTask(FEET, circles[stage], np.full((T, 4), 0.1), allowed[None], weight=0.1, penalty=0.1, margin=0.001), - ] # pull the feet over the stage's circles (at their edge as hard as a landing pays), reward feet down inside - # them, and penalize touches outside every circle + ] # pull the feet over the stage's circles (at their edge as hard as a landing pays), reward feet down inside them, and penalize touches outside every circle # --- nodes: a quadratic not-a-knot spline through 6 nodes over the horizon, as a (steps + 1, nodes) basis --- x, xs = np.linspace(0, 20, 6), np.arange(20 + 1.0) @@ -110,22 +110,23 @@ def main(): # --- SimMPC: replan every step over a 0.4 s horizon of 6 nodes --- limits = model.actuator_ctrlrange - ctrl_ref = np.tile(limits.mean(1), (T, 1)) - ctrl_std = 0.9**4 * (limits[:, 1] - limits[:, 0]) / 2 config = SimMPCConfig( - num_samples=2048, horizon_steps=20, node_steps=4, ctrl_steps=1, max_iterations=2, init_iterations=10, + num_samples=1229, horizon_steps=20, node_steps=4, ctrl_steps=1, init_iterations=10, # 0.6x DIAL's 2048 + elite_ratio=0.02, # the DIAL benchmark's config min_improvement=-np.inf, std_growth=0.9**-4, noise_decay=0.5, min_std=1e-6, - terminal_scale=1.0, + terminal_scale=1.0, ctrl_std=0.9**4 * (limits[:, 1] - limits[:, 0]) / 2, interpolation=basis, ) # fmt: skip + for cost in costs: + config.add(cost) print("building SimMPC (the first run compiles kernels) ...") - mpc = SimMPC(MjWarpSim(model, state), ctrl_ref, ctrl_std, costs, config, spline_basis=basis, ctrl_range=limits) + sim = MjWarpSim(model, 1, state, nconmax=120, njmax=500) # plans on copies of it, executes on it + mpc = SimMPC(config, sim, np.tile(limits.mean(1), (T, 1))) print(f"planning {STEPS * DT:.0f} s of motion ...") start = time.perf_counter() report = lambda plans: plans[0]["t0"] % STAGE or print(f" t={plans[0]['t0'] * DT:.0f} s: cost {plans[0]['plan_cost']:.3f}") # fmt: skip - (rollout,), _ = mpc.solve(STEPS, callback=report) + (rollout,), _ = mpc.execute(sim, STEPS, callback=report) - # --- check: per landing, the worst step of its contact window (0.5-0.9 s into the stage) scores 0.1 per foot - # down inside its circle, minus 0.1 per foot down elsewhere (the previous circle excepted); 0.4 is perfect --- + # --- check: per landing, the worst step of its contact window (0.5-0.9 s into the stage) scores 0.1 per foot down inside its circle, minus 0.1 per foot down elsewhere (the previous circle excepted); 0.4 is perfect --- feet = np.stack([rollout["sensordata"][:, adr[f] : adr[f] + 3] for f in FEET], 1) k = np.arange(len(feet)) inside = np.sum((feet[:, None, :, :2] - circles[None, :, :, :2]) ** 2, -1) <= 0.1**2 # (step, stage, foot) diff --git a/src/robokit/examples/sim_mpc/12_fr3_push.py b/src/robokit/examples/sim_mpc/13_fr3_push.py similarity index 82% rename from src/robokit/examples/sim_mpc/12_fr3_push.py rename to src/robokit/examples/sim_mpc/13_fr3_push.py index 0ae9bfb..04f0d32 100644 --- a/src/robokit/examples/sim_mpc/12_fr3_push.py +++ b/src/robokit/examples/sim_mpc/13_fr3_push.py @@ -18,8 +18,8 @@ import warp as wp from robot_descriptions import fr3_mj_description -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import CartesianControl, MjWarpSim +from robokit.helpers.sim_mpc import CartesianControl, SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import AlignTask, SensorTask, StateTask from robokit.utils.visualize_utils import ViserMjcf from robokit.xform.numpy import quaternion_apply, quaternion_invert, quaternion_multiply @@ -46,7 +46,9 @@ def main(): actuator.inheritrange, actuator.ctrlrange = 0.0, [-limit, limit] actuator.forcelimited, actuator.forcerange = True, scene.joint(actuator.target).actfrcrange pusher = scene.body("fr3_link7").add_body(name="pusher", pos=[0, 0, 0.107]) - pusher.add_geom(type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.01, 0.01, 0.0625], pos=[0, 0, 0.0625], conaffinity=0) + pusher.add_geom( + name="stick", type=mujoco.mjtGeom.mjGEOM_BOX, size=[0.01, 0.01, 0.0625], pos=[0, 0, 0.0625], conaffinity=0 + ) pusher.add_body(name="tip", pos=[0, 0, 0.125]).add_geom( size=[0.015, 0, 0], friction=[0.01, 0.005, 1e-4], solref=[0.03, 1.1], solimp=[0.5, 0.95, 0.002, 0.5, 2], conaffinity=0, @@ -80,36 +82,34 @@ def main(): mujoco.mj_forward(model, state) print(f"scene: {model.nq} qpos, {model.nu} actuators") - # --- SimMPC: sample the pusher's planar velocity, mapped to joint velocities that hold it upright 3.9 cm up; - # costs: the block's center to the goal's (50 per m) and its angle (5 per rad), the tip near the block and - # behind it as seen from the goal --- + # --- SimMPC: sample the pusher's planar velocity, mapped to joint velocities that hold it upright 3.9 cm up; costs: the block's center to the goal's (50 per m) and its angle (5 per rad), the tip near the block and behind it as seen from the goal --- T = STEPS + 50 # past the end by one horizon goal_com = np.asarray(GOAL[:3]) + quaternion_apply(np.asarray(GOAL[3:]), model.body("block").ipos) sensor_ref = np.zeros((T, model.nsensordata)) sensor_ref[:, model.sensor("block").adr[0] : model.sensor("block").adr[0] + 3] = goal_com qpos_ref, qvel_ref = np.tile(QPOS0[:7] + GOAL, (T, 1)), np.zeros((T, model.nv)) - costs = [ - SensorTask(sensor_ref, {"block": 50.0}, norm=True, terminal_scale=501.0), - StateTask(qpos_ref, qvel_ref, np.r_[[0] * 10, 5, 5, 5], terminal_scale=501.0), - SensorTask(sensor_ref, {f"tip_to_side_{i}": 0.05 for i in range(3)}, norm=True, terminal_scale=1.0), - AlignTask("block", "tip", np.tile(goal_com, (T, 1)), weight=0.9, terminal_scale=1.0), - ] control = CartesianControl( model, "tip", position_ref=[0, 0, 0.039], q_wxyz_ref=[0, 0.7071, 0.7071, 0], position_gain=[0, 0, 1], rotation_gain=[1, 1, 1], ) # fmt: skip + ctrl_range = np.array([[-0.25, 0.25]] * 2 + [[0.0, 0.0]] * 5) # x, y velocity in m/s; the other commands unused config = SimMPCConfig( - num_samples=64, horizon_steps=50, node_steps=17, ctrl_steps=10, max_iterations=1, std_growth=1.0, - interpolation="cubic", settle_steps=2, + num_samples=64, horizon_steps=50, node_steps=17, ctrl_steps=10, std_growth=1.0, + stages=[SimMPCStage(1, [(0.25, None), (1.0, 0.02)])], + interpolation="cubic", settle_steps=2, terminal_scale=1.0, ctrl_std=np.r_[0.3, 0.3, [0] * 5], + ctrl_range=ctrl_range, control_map=control, ) # fmt: skip + config.add(SensorTask(sensor_ref, {"block": 50.0}, norm=True), terminal_scale=501.0) + config.add(StateTask(qpos_ref, qvel_ref, np.r_[[0] * 10, 5, 5, 5]), terminal_scale=501.0) + config.add(SensorTask(sensor_ref, {f"tip_to_side_{i}": 0.05 for i in range(3)}, norm=True)) + config.add(AlignTask("block", "tip", np.tile(goal_com, (T, 1)), weight=0.9)) print("building SimMPC (the first run compiles kernels) ...") - sim = MjWarpSim(model, state, control_map=control, nconmax=42, njmax=147) - ctrl_range = [[-0.25, 0.25]] * 2 + [[0.0, 0.0]] * 5 # x, y velocity in m/s; the other commands unused - mpc = SimMPC(sim, np.zeros((T, model.nu)), np.r_[0.3, 0.3, [0] * 5], costs, config, ctrl_range=ctrl_range) + sim = MjWarpSim(model, 1, state, nconmax=42, njmax=147) # plans on copies of it, executes on it + mpc = SimMPC(config, sim, np.zeros((T, model.nu))) print(f"planning {STEPS / 100:.0f} s of motion ...") start = time.perf_counter() report = lambda plans: plans[0]["t0"] % 200 or print(f" t={plans[0]['t0'] / 100:.0f} s: cost {plans[0]['plan_cost']:.1f}") # fmt: skip - (rollout,), _ = mpc.solve(STEPS, callback=report) + (rollout,), _ = mpc.execute(sim, STEPS, callback=report) planned = time.perf_counter() - start # --- check: over the last 1 s the block's center stays within 2 cm of the goal's, its angle within 0.2 rad --- diff --git a/src/robokit/examples/sim_mpc/13_fr3_balance.py b/src/robokit/examples/sim_mpc/14_fr3_balance.py similarity index 78% rename from src/robokit/examples/sim_mpc/13_fr3_balance.py rename to src/robokit/examples/sim_mpc/14_fr3_balance.py index 180a96e..7b0f901 100644 --- a/src/robokit/examples/sim_mpc/13_fr3_balance.py +++ b/src/robokit/examples/sim_mpc/14_fr3_balance.py @@ -11,26 +11,29 @@ import time from pathlib import Path +from typing import Literal import mujoco import numpy as np +import tyro import viser import warp as wp from robot_descriptions import fr3_mj_description -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import SensorTask, StateTask from robokit.utils.visualize_utils import ViserMjcf STEPS, PHASE, REST = 1000, 11.458, 0.04415 # 10 s at 100 Hz; drift phase (s); the ball's resting height on the plate -# start (BAMPC's balance benchmark at seed 11): the arm holds the plate level with the ball resting on it +# start (seed 11): the arm holds the plate level with the ball resting on it QPOS0 = [1.37404, -1.40987, -0.97431, -2.5512, 2.16327, 1.74726, 2.01986, 0.30211, 0.02328, 0.74355, -0.47285, 0, 0, -0.88115] # fmt: skip -PASS = 0.0061 # accumulated squared error BAMPC's 2,800-sample MPPI reaches from this start in 10 s +PASS = 0.0061 # accumulated squared error a 2,800-sample MPPI reaches from this start in 10 s -def main(): +def main(planner: Literal["mppi", "ilqr"] = "mppi"): + """Balance the ball with MPPI or iLQR (`--planner ilqr`) on the same costs.""" wp.config.log_level = wp.LOG_WARNING # no per-module load lines wp.init() @@ -78,25 +81,24 @@ def main(): drift = 0.04 * np.sin(2 * np.pi * 0.06 * t) goal = np.c_[0.05 + drift, 0.04 + drift, np.full_like(t, REST)] - # --- SimMPC: sample joint velocities; costs: the ball's squared distance to the goal (30 per m^2) and the arm's - # distance to its level-plate pose (15 per rad); each plan holds the goal it starts from --- + # --- SimMPC: sample joint velocities (iLQR: refine them, each held 0.05 s, slower, over a shorter horizon); costs: the ball's squared distance to the goal (30 per m^2) and the arm's distance to its level-plate pose (15 per rad); each plan holds the goal it starts from --- held, qpos_ref, qvel_ref = dict(freeze_reference=True), np.tile(QPOS0, (len(t), 1)), np.zeros((len(t), model.nv)) - costs = [ - SensorTask(goal, {"ball_on_plate": 30.0}, terminal_scale=701.0, **held), - StateTask(qpos_ref, qvel_ref, np.r_[[15] * 7, [0] * 6], terminal_scale=1.0, **held), - ] + ilqr = planner == "ilqr" config = SimMPCConfig( - num_samples=2800, horizon_steps=60, node_steps=20, ctrl_steps=5, max_iterations=1, std_growth=1.0, - interpolation="cubic", + num_samples=1400, horizon_steps=40 if ilqr else 60, node_steps=5 if ilqr else 20, ctrl_steps=5, + stages=[SimMPCStage(1)] if ilqr else [SimMPCStage(2, [(0.25, None), (1.0, 0.02)])], std_growth=1.0, + interpolation="cubic", terminal_scale=1.0, ctrl_std=0.3, + ctrl_range=(0.3 if ilqr else 0.6) * model.actuator_ctrlrange, planner=planner, # of the joint speed limits ) # fmt: skip + config.add(SensorTask(goal, {"ball_on_plate": 30.0}, **held), terminal_scale=701.0) + config.add(StateTask(qpos_ref, qvel_ref, np.r_[[15] * 7, [0] * 6], **held)) print("building SimMPC (the first run compiles kernels) ...") - sim = MjWarpSim(model, state, nconmax=3, njmax=39) - ctrl_range = 0.6 * model.actuator_ctrlrange # sample within 60% of the joint speed limits - mpc = SimMPC(sim, np.zeros((len(t), model.nu)), np.full(model.nu, 0.3), costs, config, ctrl_range=ctrl_range) + sim = MjWarpSim(model, 1, state, nconmax=3, njmax=39) # plans on copies of it, executes on it + mpc = SimMPC(config, sim, np.zeros((len(t), model.nu))) print(f"planning {STEPS / 100:.0f} s of motion ...") start = time.perf_counter() report = lambda plans: plans[0]["t0"] % 200 or print(f" t={plans[0]['t0'] / 100:.0f} s: cost {plans[0]['plan_cost']:.2f}") # fmt: skip - (rollout,), _ = mpc.solve(STEPS, callback=report) + (rollout,), _ = mpc.execute(sim, STEPS, callback=report) planned = time.perf_counter() - start # --- check: the ball never drops 16 cm below the plate; its squared distance to the goal, every 0.05 s x 0.05 s --- @@ -128,4 +130,4 @@ def main(): if __name__ == "__main__": - main() + tyro.cli(main) diff --git a/src/robokit/examples/sim_mpc/14_batch.py b/src/robokit/examples/sim_mpc/15_batch.py similarity index 89% rename from src/robokit/examples/sim_mpc/14_batch.py rename to src/robokit/examples/sim_mpc/15_batch.py index 0a4f232..c5866a0 100644 --- a/src/robokit/examples/sim_mpc/14_batch.py +++ b/src/robokit/examples/sim_mpc/15_batch.py @@ -7,7 +7,10 @@ # /// # pyright: reportMissingImports=false # pyright: reportArgumentType=false -"""SimMPC batch: one Sharpa right hand tracks four retargeted OakInk-v2 clips, each with its own object, at once.""" +"""SimMPC batch: one Sharpa right hand tracks four retargeted OakInk-v2 clips, each with its own object, at once. + +SPIDER: https://arxiv.org/abs/2511.09484. +""" import glob import time @@ -25,9 +28,9 @@ from robokit.helpers.hand_retargeting import HandRetargeterOffline, HandSpec, refine_config from robokit.helpers.hand_retargeting.presets._common import FIVE_FINGERTIPS from robokit.helpers.hand_retargeting.presets.sharpa import _LINKS, offline, spec -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim, batch_models +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage from robokit.robo import Robot +from robokit.sim import MjWarpSim from robokit.terms import StateTask from robokit.utils.visualize_utils import ViserMjcf from robokit.xform.numpy import quaternion_apply, quaternion_invert, quaternion_multiply, quaternion_to_matrix @@ -51,8 +54,7 @@ def main(): root = fetch(files, REVISION, REPO) clips = {n: np.load(root / clip_dir(n) / "trajectory_keypoints.npz") for n in CLIPS} - # --- scenes: the Sharpa on six position-controlled base joints and the clip's object free on a table; the scenes - # differ in the object's meshes, geoms and inertia, and the table's height --- + # --- scenes: the Sharpa on six position-controlled base joints and the clip's object free on a table; the scenes differ in the object's meshes, geoms and inertia, and the table's height --- specs = [] for name, clip in clips.items(): scene = mujoco.MjSpec.from_file(str(sharpa_hand.MJCF_PATH_RIGHT)) @@ -91,11 +93,10 @@ def main(): scene.add_mesh(name=f"object_{k}", file=path) body.add_geom(type=mujoco.mjtGeom.mjGEOM_MESH, meshname=f"object_{k}", group=3, contype=0, conaffinity=3) specs.append(scene) - model, parameters = batch_models(specs) # one model of the four scenes, and each one's own values of it - print(f"batched scenes: {model.nq} qpos, {model.nu} actuators, per-instance {', '.join(parameters)}") + model = specs[0].compile() # the joints and actuators every scene shares + print(f"{len(specs)} scenes: {model.nq} qpos, {model.nu} actuators") - # --- retarget: the wrist and fingertips to the Sharpa's base pose and 22 joints, in the object's frame, where a - # collision term keeps the hand out of the static object mesh --- + # --- retarget: the wrist and fingertips to the Sharpa's base pose and 22 joints, in the object's frame, where a collision term keeps the hand out of the static object mesh --- config = replace(offline, terms=[*offline.terms, refine_config(offline).task("collision")]) robot = Robot.load( str(sharpa_hand.URDF_PATH_RIGHT), load_collision_spheres=True, @@ -140,11 +141,6 @@ def main(): qpos_ref = np.stack([np.stack([np.interp(t, np.arange(len(r)), c) for c in r.T], 1) for r in refs]) qpos_ref[..., -4:] /= np.linalg.norm(qpos_ref[..., -4:], axis=-1, keepdims=True) ctrl_ref = qpos_ref[..., model.jnt_qposadr[model.actuator_trnid[:, 0]]] - states = [] - for b in range(len(CLIPS)): - state = mujoco.MjData(model) - state.qpos[:], state.ctrl[:] = qpos_ref[b, 0], ctrl_ref[b, 0] - states.append(state) # --- SimMPC: one batch of the four clips; each instance tracks its own hand and object references --- names = [model.joint(model.dof_jntid[i]).name for i in range(model.nv)] @@ -156,18 +152,20 @@ def main(): cost = StateTask(qpos_ref, np.zeros((len(t), model.nv)), np.array(weight)) ctrl_std = np.where([model.actuator(i).name[:4] in ("pos_", "rot_") for i in range(model.nu)], 0.02, 0.06) config = SimMPCConfig( - batch_size=len(CLIPS), num_samples=256, horizon_steps=200, node_steps=40, ctrl_steps=40, max_iterations=8, - min_improvement=0.0, std_growth=2.0, noise_decay=0.93, terminal_scale=1.0, + batch_size=len(CLIPS), num_samples=256, horizon_steps=200, node_steps=40, ctrl_steps=40, + stages=[SimMPCStage(8)], + min_improvement=0.0, std_growth=2.0, noise_decay=0.93, terminal_scale=1.0, ctrl_std=ctrl_std, ) # fmt: skip + config.add(cost) steps = (len(t) - config.horizon_steps) // config.ctrl_steps * config.ctrl_steps - limits = np.where(model.actuator_ctrllimited[:, None] > 0, model.actuator_ctrlrange, [-np.inf, np.inf]) print("building SimMPC (the first run compiles kernels) ...") - sim = MjWarpSim(model, states, instance_parameters=parameters) - mpc = SimMPC(sim, ctrl_ref, ctrl_std, [cost], config, ctrl_range=limits) + sim = MjWarpSim(specs, [1] * len(specs), nconmax=120, njmax=500) # one scene per clip; plans on copies of it + sim.data.qpos.assign(qpos_ref[:, 0]) # each clip's start + mpc = SimMPC(config, sim, ctrl_ref) print(f"planning {steps / 100:.1f} s of motion for {len(CLIPS)} clips at once ...") start = time.perf_counter() report = lambda plans: print(f" t={plans[0]['t0'] / 100:.1f} s: costs", *[f"{p['plan_cost']:.3f}" for p in plans]) - rollouts, _ = mpc.solve(steps, callback=report) + rollouts, _ = mpc.execute(sim, steps, callback=report) print(f"planned in {time.perf_counter() - start:.0f} s") for name, rollout, ref in zip(CLIPS, rollouts, qpos_ref): error = np.linalg.norm(rollout["qpos"][:, -7:-4] - ref[:steps, -7:-4], axis=1) diff --git a/src/robokit/examples/sim_mpc/15_demo_repair.py b/src/robokit/examples/sim_mpc/16_demo_repair.py similarity index 72% rename from src/robokit/examples/sim_mpc/15_demo_repair.py rename to src/robokit/examples/sim_mpc/16_demo_repair.py index 2c70009..dd9756a 100644 --- a/src/robokit/examples/sim_mpc/15_demo_repair.py +++ b/src/robokit/examples/sim_mpc/16_demo_repair.py @@ -6,11 +6,7 @@ # robokit = { path = "../../../..", editable = true } # /// # pyright: reportMissingImports=false -"""SimMPC: repair a noisy robot demonstration, a Panda fitting a square nut onto its peg (MimicGen Square D0). - -The demonstration's recorded arm joints get a smooth 0.05 rad per-joint offset, standing in for joints fitted from -video. Replayed open-loop they miss the nut; SimMPC samples offsets around them to track the demo's nut motion. -""" +"""SimMPC: repair a noisy robot demonstration, a Panda fitting a square nut onto its peg (MimicGen Square D0). The demonstration's recorded arm joints get a smooth 0.05 rad per-joint offset, standing in for joints fitted from video; replayed open-loop they miss the nut, so SimMPC samples offsets around them to track the demo's nut motion.""" import re import time @@ -22,8 +18,8 @@ import warp as wp from robokit.assets import fetch -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig -from robokit.helpers.sim_mpc.mjwarp import MjWarpSim +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim from robokit.terms import ControlTask, GraspTask, StateTask from robokit.utils.visualize_utils import ViserMjcf @@ -43,21 +39,22 @@ def main(): states, actions = demo["states"], demo["actions"] print(f"loaded {len(states)} steps of a Square D0 Panda demo") - # --- scene: the demo's own XML; no arm self-collisions, no air (NaN forces on MuJoCo Warp), no contacts for the - # round nut parked under the table, the arm's torque motors as joint position servos --- + # --- scene: the demo's own XML; no arm self-collisions, no air (NaN forces on MuJoCo Warp), no contacts for the round nut parked under the table, the arm's torque motors as joint position servos --- xml = (root / "square_d0_panda_demo0.xml").read_text().replace('file="', f'file="{root}/') links = re.findall(r'' for i, a in enumerate(links) for b in links[i + 1 :]) xml = xml.replace("", f"{pairs}") - model = mujoco.MjModel.from_xml_string(xml) - model.opt.timestep, model.opt.density, model.opt.viscosity = DT, 0.0, 0.0 - model.opt.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST - for i in range(model.ngeom): - if model.body(model.geom_bodyid[i]).name.startswith("RoundNut"): - model.geom_contype[i] = model.geom_conaffinity[i] = 0 - arm = model.actuator_biastype == mujoco.mjtBias.mjBIAS_NONE # the gripper's actuators are already servos - model.actuator_gainprm[arm, 0], model.actuator_biasprm[arm, :3] = 2000.0, [0.0, -2000.0, -200.0] - model.actuator_biastype[arm], model.actuator_ctrllimited[arm] = mujoco.mjtBias.mjBIAS_AFFINE, 0 + scene = mujoco.MjSpec.from_string(xml) + scene.option.timestep, scene.option.density, scene.option.viscosity = DT, 0.0, 0.0 + scene.option.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST + for geom in scene.geoms: + if geom.parent.name.startswith("RoundNut"): + geom.contype = geom.conaffinity = 0 + arm = np.array([a.biastype == mujoco.mjtBias.mjBIAS_NONE for a in scene.actuators]) # the gripper's are servos + for actuator in [a for a, is_arm in zip(scene.actuators, arm) if is_arm]: + actuator.gainprm[0], actuator.biasprm[:3] = 2000.0, [0.0, -2000.0, -200.0] + actuator.biastype, actuator.ctrllimited = mujoco.mjtBias.mjBIAS_AFFINE, mujoco.mjtLimited.mjLIMITED_FALSE + model = scene.compile() joints = model.actuator_trnid[:, 0] nut = model.body("SquareNut_main").id adr, dof = model.jnt_qposadr[model.body_jntadr[nut]], model.jnt_dofadr[model.body_jntadr[nut]] @@ -80,9 +77,9 @@ def main(): qpos_ref[:, adr + 3 : adr + 7] /= np.linalg.norm(qpos_ref[:, adr + 3 : adr + 7], axis=1, keepdims=True) observed = qpos_ref.copy() observed[:, model.jnt_qposadr[joints[arm]]] = upsample(q[:, arm]) # what the joint pull follows - start_state = mujoco.MjData(model) - start_state.qpos[:], start_state.qvel[:], start_state.ctrl[:] = qpos_demo[0], qvel_demo[0], ctrl_ref[0] - mujoco.mj_forward(model, start_state) + state = mujoco.MjData(model) + state.qpos[:], state.qvel[:], state.ctrl[:] = qpos_demo[0], qvel_demo[0], ctrl_ref[0] + mujoco.mj_forward(model, state) # --- open-loop: the observed targets, stepped in MuJoCo --- data, open_loop = mujoco.MjData(model), [] @@ -93,11 +90,11 @@ def main(): open_loop.append(data.qpos.copy()) open_loop = np.array(open_loop) - # --- SimMPC: track the nut from the first close, the gripper's offset from the nut around the grasp, and pull - # weakly toward the observed joints --- + # --- SimMPC: track the nut from the first close, the gripper's offset from the nut around the grasp, and pull weakly toward the observed joints --- config = SimMPCConfig( - num_samples=512, horizon_steps=500, node_steps=125, ctrl_steps=125, max_iterations=8, min_improvement=0.005, - patience=1, + num_samples=512, horizon_steps=500, node_steps=125, ctrl_steps=125, min_improvement=0.005, + stages=[SimMPCStage(8, [(0.25, None), (1.0, 0.004)])], + patience=1, ctrl_std=arm * 0.015, ) # fmt: skip pad = config.horizon_steps + config.ctrl_steps extend = lambda x: np.vstack([x, np.repeat(x[-1:], pad, 0)]) @@ -121,15 +118,20 @@ def main(): gripper, nut, extend(upsample(offset)), on * 1.0, tolerance=0.005 * (1 + carrying), object_frame=False ), ] + for cost in costs: + config.add(cost) print("building SimMPC (the first run compiles kernels) ...") - # plan on MuJoCo Warp, execute in MuJoCo on the CPU, as the open-loop replay does - sim = MjWarpSim(model, start_state, nconmax=400, njmax=2000, cpu_execute=True) - mpc = SimMPC(sim, extend(ctrl_ref), arm * 0.015, costs, config) + mpc = SimMPC(config, MjWarpSim(model, 1, state, nconmax=400, njmax=2000), extend(ctrl_ref)) print(f"planning {len(ctrl_ref) * DT:.1f} s of motion ...") - begin = time.perf_counter() - report = lambda plans: print(f" t={plans[0]['t0'] * DT:.2f} s: cost {plans[0]['plan_cost']:.3f}") - (rollout,), _ = mpc.solve(len(ctrl_ref) + 1, callback=report) - repaired = rollout["qpos"][1 : len(ctrl_ref) + 1] + begin, repaired = time.perf_counter(), [] + for t0 in range(0, len(ctrl_ref), config.ctrl_steps): # plan on MuJoCo Warp, step in MuJoCo as the open-loop does + commands, (plan,) = mpc.plan(state, t0) + print(f" t={t0 * DT:.2f} s: cost {plan['plan_cost']:.3f}") + for ctrl in commands.numpy()[:, 0]: + state.ctrl[:] = ctrl + mujoco.mj_step(model, state) + repaired.append(state.qpos.copy()) + repaired = np.array(repaired[: len(ctrl_ref)]) for name, qpos in [("open-loop", open_loop), ("SimMPC", repaired)]: error = np.linalg.norm(qpos[-1, adr : adr + 3] - qpos_ref[-1, adr : adr + 3]) print(f"{name}: nut ends {100 * error:.1f} cm from the demo's, {'pass' if error < 0.02 else 'fail'} (< 2 cm)") diff --git a/src/robokit/examples/sim_mpc/18_g1_flip.py b/src/robokit/examples/sim_mpc/18_g1_flip.py new file mode 100644 index 0000000..5e448fa --- /dev/null +++ b/src/robokit/examples/sim_mpc/18_g1_flip.py @@ -0,0 +1,137 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +# pyright: reportMissingImports=false +"""SimMPC: a Unitree G1 backflips in physics with iLQR, tracking the mocap flip of mjbatch's `examples/g1_flip.py`.""" + +import time +import urllib.request +from pathlib import Path + +import mujoco +import numpy as np +import viser +import warp as wp +from robot_descriptions import g1_mj_description +from scipy.optimize import nnls + +from robokit.assets import ROBOKIT_HOME +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig +from robokit.opt.ilqr_optimizer import ILQROptimizerConfig +from robokit.sim import MjWarpSim +from robokit.terms import ControlTask, SensorTask +from robokit.utils.visualize_utils import ViserMjcf + + +REVISION = "4cba7799b0e5265cdb96f6d520a491ace4dad9ae" # kevinzakka/mjbatch: the G1 on torque motors, and the clip +FRAMES, SUB, LIFT = 200, 2, 0.001 # clip frames tracked (50 Hz; the ankles roll after 200); sim steps a frame; feet up +BODIES = ( # bodies the cost tracks, mjbatch's + "pelvis", "torso_link", "left_hip_roll_link", "left_knee_link", "left_ankle_roll_link", "right_hip_roll_link", + "right_knee_link", "right_ankle_roll_link", "left_shoulder_roll_link", "left_elbow_link", + "right_shoulder_roll_link", "right_elbow_link", +) # fmt: skip +# weights per m^2, rad^2, (m/s)^2, (rad/s)^2 and (N m)^2: mjbatch's, but body positions and orientations twice theirs; the pelvis's position loose in x and y, tight in z +W_POS, W_ROOT, W_ROT, W_VEL, W_ANG, W_CTRL = 200.0, [1.0, 1.0, 1000.0], 200.0, 5.0, 1.0, 1e-2 +PASS = 0.03 # mean body position error (m) relative to the pelvis; mjbatch's iLQR reaches 0.020 + + +def main(): + wp.config.log_level = wp.LOG_WARNING # no per-module load lines + wp.init() + + # --- data: mjbatch's G1 on menagerie's meshes, with frame sensors on the tracked bodies, and its retargeted flip --- + root = ROBOKIT_HOME / "mjbatch" / REVISION + root.mkdir(parents=True, exist_ok=True) + for name in ("g1.xml", "theme.xml", "flip.npz"): + if not (root / name).exists(): + url = f"https://raw.githubusercontent.com/kevinzakka/mjbatch/{REVISION}/examples/assets/{name}" + urllib.request.urlretrieve(url, root / name) + scene = mujoco.MjSpec.from_file(str(root / "g1.xml")) + scene.meshdir = str(Path(g1_mj_description.PACKAGE_PATH) / "assets") + for body in BODIES: # position, orientation and velocities, in the world + for kind in ("POS", "QUAT", "LINVEL", "ANGVEL"): + kind_type, xbody = getattr(mujoco.mjtSensor, f"mjSENS_FRAME{kind}"), mujoco.mjtObj.mjOBJ_XBODY + scene.add_sensor(name=f"{body}_{kind}", type=kind_type, objtype=xbody, objname=body) + model = scene.compile() + clip = {k: v.astype(float) for k, v in np.load(root / "flip.npz").items()} + print(f"scene: {model.nq} qpos, {model.nu} torque motors; clip: {FRAMES} of {len(clip['joint_pos'])} frames") + + # --- reference: the clip's states (free joint spin in the pelvis frame) halfway between frames, as a knot's costs read the state one sim step in; their sensor readings, and torques by inverse dynamics as mjbatch's warm start, with the contact forces that best explain the pelvis's rows (nonnegative least squares), since MuJoCo's come from the clip's foot penetration, far over the limits --- + keep, data = model.jnt_bodyid[1:] - 2, mujoco.MjData(model) # the clip's columns of the model's hinges + qpos = np.c_[clip["body_pos_w"][:, 0] + [0, 0, LIFT], clip["body_quat_w"][:, 0], clip["joint_pos"][:, keep]] + qvel = np.c_[clip["body_lin_vel_w"][:, 0], clip["body_ang_vel_w"][:, 0], clip["joint_vel"][:, keep]] + for q, v in zip(qpos, qvel): + mujoco.mju_normalize4(q[3:7]) + mujoco.mju_rotVecQuat(v[3:6], v[3:6].copy(), q[3:7] * [1, -1, -1, -1]) + sensor_ref, torque, limit = [], [], model.actuator_ctrlrange[:, 1] + for t in range(FRAMES + 1): + data.qpos[:], data.qvel[:] = (qpos[t] + qpos[t + 1]) / 2, (qvel[t] + qvel[t + 1]) / 2 + data.qacc[:] = (qvel[t + 1] - qvel[t]) * clip["fps"][0] + mujoco.mju_normalize4(data.qpos[3:7]) + mujoco.mj_inverse(model, data) + contact = data.efc_type[: data.nefc] == mujoco.mjtConstraint.mjCNSTR_CONTACT_PYRAMIDAL + J = data.efc_J.reshape(-1, model.nv)[: data.nefc][contact] + force = data.qfrc_inverse + data.qfrc_constraint # without the contacts + A = np.r_[J[:, :6].T, J[:, 6:].T / limit[:, None], 1e-3 * np.eye(len(J))] + f = nnls(A, np.r_[force[:6], force[6:] / limit, np.zeros(len(J))])[0] if len(J) else [] + sensor_ref.append(data.sensordata.copy()) + torque.append(np.clip(force[6:] - J[:, 6:].T @ f, -limit, limit)) + sensor_ref = np.repeat(sensor_ref, SUB, axis=0) + data.qpos[:], data.qvel[:] = qpos[0], qvel[0] + mujoco.mj_forward(model, data) + + # --- SimMPC: iLQR on torques held a frame, 50 frames ahead, planned every 10 frames, 20 iterations (no CUDA graph, whose capture alone takes 50 s); mjbatch's costs (quadratic where it is robust): the bodies' positions relative to the pelvis, the pelvis's own, their orientations and velocities, and the torques --- + weight = {"pelvis_POS": W_ROOT} | {f"{b}_{k}": w for b in BODIES for k, w in (("LINVEL", W_VEL), ("ANGVEL", W_ANG))} + config = SimMPCConfig( + horizon_steps=50 * SUB, node_steps=SUB, ctrl_steps=10 * SUB, max_iterations=20, terminal_scale=1.0, + planner="ilqr", ilqr=ILQROptimizerConfig( + improve=True, feedback_search=False, feedback_cap=0.1, min_regularization=1.0, cuda_graph_mode="none" + ), + ) # fmt: skip + config.add(SensorTask(sensor_ref, {f"{b}_POS": W_POS for b in BODIES[1:]}, relative="pelvis_POS")) + config.add(SensorTask(sensor_ref, weight)) # pyright: ignore[reportArgumentType] + config.add(SensorTask(sensor_ref, {f"{b}_QUAT": W_ROT for b in BODIES}, residual="quaternion")) + config.add(ControlTask(W_CTRL)) + print("building SimMPC (the first run compiles kernels) ...") + sim = MjWarpSim(model, 1, data, nconmax=64, njmax=256) # plans on copies of it, executes on it + mpc = SimMPC(config, sim, np.repeat(torque, SUB, axis=0)) + print(f"planning {FRAMES / 50:.0f} s of motion ...") + start = time.perf_counter() + report = lambda p: p[0]["t0"] % 50 or print(f" t={p[0]['t0'] / 100:.1f} s: cost {p[0]['plan_cost']:.2f}") + (rollout,), _ = mpc.execute(sim, FRAMES * SUB, callback=report) + planned = time.perf_counter() - start + + # --- check: each frame's tracked bodies relative to the pelvis, against the clip's; the torso upright at the end --- + ids, xpos = [model.body(b).id for b in BODIES], [] + for q in rollout["qpos"][::SUB]: + data.qpos[:] = q + mujoco.mj_kinematics(model, data) + xpos.append(data.xpos[ids].copy()) + xpos, target = np.array(xpos), clip["body_pos_w"][:FRAMES, np.array(ids) - 1] + [0, 0, LIFT] + error = np.linalg.norm((xpos - xpos[:, :1]) - (target - target[:, :1]), axis=2).mean() + upright = data.xmat[model.body("torso_link").id][8] # z of the torso's up axis at the last frame + print( + f"flip: {'pass' if error <= PASS and upright >= 0.9 else 'FAIL'}, body error {100 * error:.1f} cm " + f"(pass <= {100 * PASS:.0f}), torso up {upright:.2f} at the end (pass >= 0.9)" + ) + print(f"planned in {planned:.0f} s") + + # --- viewer: replay the simulated motion, or the clip it tracks --- + server = viser.ViserServer() + print("replaying; Ctrl+C to stop") + server.scene.add_grid("/ground", width=4.0, height=4.0) + reference = server.gui.add_checkbox("Show the clip", False) + viewer = ViserMjcf(server, scene.to_xml()) + while True: + for k in range(0, FRAMES * SUB, SUB): + viewer.update_qpos(qpos[k // SUB] if reference.value else rollout["qpos"][k]) + time.sleep(SUB * model.opt.timestep) + time.sleep(1.0) # hold the last frame before replaying + + +if __name__ == "__main__": + main() diff --git a/src/robokit/examples/sim_mpc/19_sharpa_screwdriver.py b/src/robokit/examples/sim_mpc/19_sharpa_screwdriver.py new file mode 100644 index 0000000..514d397 --- /dev/null +++ b/src/robokit/examples/sim_mpc/19_sharpa_screwdriver.py @@ -0,0 +1,253 @@ +# /// script +# requires-python = ">=3.10" +# dependencies = ["robokit[mjwarp]"] +# +# [tool.uv.sources] +# robokit = { path = "../../../..", editable = true } +# /// +# pyright: reportMissingImports=false +# pyright: reportArgumentType=false +"""SimMPC: a palm-down Sharpa Wave hand twirls a free precision screwdriver to drive a slotted screw two turns.""" + +import copy +import time + +import mujoco +import numpy as np +import viser +import warp as wp + +from robokit.assets.robots.end_effectors import sharpa_hand +from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig, SimMPCStage +from robokit.sim import MjWarpSim +from robokit.terms import ContactTask, ControlTask, SensorTask, StateTask, SupportTask +from robokit.utils.visualize_utils import ViserMjcf + + +STEPS = 1500 # 15 s at the 10 ms step +QUARTER, GOALS = np.pi / 2, 9 # goals every quarter turn up to 2.25 turns: the one after next past the screw's angle +PERIOD, DUTY, PACE = 1.5, 0.6, 1.2 # thumb, middle push in turn for 60% of every 1.5 s; a quarter per 1.2 s at most +HOLD = 4.0 # while the tool tilts over 4 deg (until back under 3), the twirl stops and the fingers right it +PRESS = 0.001 # the fingertips aim 1 mm below where they first held the handle, pressing the blade into the slot +# a tripod grip, solved at the start: per tip, where its collision capsule touches the driver (geom, height mm, angle +# deg, radius mm, in the driver's frame), at what gap (mm), with which point of its pad (mm, in its body's frame) +GRASP_AT = dict(thumb=("handle", 82.173, -130.83, 8, -4.411, [26.466, 6.138, 6.444]), + index=("handle", 80.065, 85.14, 8, 0.386, [22.121, -2.476, 5.163]), + middle=("handle", 79.515, -13.17, 8, 0.097, [21.882, -1.922, -5.702])) # fmt: skip +CURL = [1.1, 0.15, 1.2, 0.8, 0.15, 1.0, 0.33, 1.1, 0.7] # the ring and pinky, loosely curled +ROOT_POS, ROOT_QUAT = [-0.0682, -0.0790, 0.2779], [0.6182, -0.2554, 0.7151, 0.2030] +HEAD, SLOT, SKIN = 0.0973, 0.0013, 0.001 # the screw head's top above the floor; the slot's depth; the 1 mm skin; m +TIPS = ("thumb", "index", "middle") # the fingertips that twist the handle + + +def main(): + wp.config.log_level = wp.LOG_WARNING # no per-module load lines + wp.init() + + # --- scene: the hand palm-down over an M5 x 0.8 slotted cheese-head screw (8.5 mm head, 1.2 x 1.3 mm slot) in a + # fixed block, turning on a hinge with 0.02 N m of running torque and sinking 0.8 mm a turn on a slide coupled to + # it; a free 4 mm precision screwdriver (0.8 x 4.0 blade, 4 x 40 mm shaft, 16 x 70 mm handle, 12 x 6 mm swivel cap, + # 18 g) stands in the slot, and only the blade's contact with the slot turns the screw --- + scene = mujoco.MjSpec.from_file(str(sharpa_hand.MJCF_PATH_RIGHT_FIT)) # its finger capsules fitted to the meshes + for mesh in scene.meshes: # absolute mesh paths, so the viewer's copy finds them + mesh.file = str(sharpa_hand.MJCF_PATH_RIGHT_FIT.parent / scene.meshdir / mesh.file) + scene.meshdir, scene.option.timestep = "", 0.01 + root = scene.body("right_hand_C_MC") + root.pos, root.quat = ROOT_POS, ROOT_QUAT + for geom in scene.geoms: + if geom.contype or geom.conaffinity: + geom.friction, geom.solmix = [1.0, 0.005, 1e-4], 0.0 + geom.solref, geom.solimp[:3] = [0.01, 1.0], [0.99, 0.999, 0.001] + stiff = dict(solref=[0.01, 1.0], solimp=[0.99, 0.999, 0.001, 0.5, 2]) + soft = dict(friction=[1.0, 0.005, 1e-4], margin=SKIN, **stiff) # what the fingers touch + steel = dict(friction=[0.3, 0.005, 1e-4], **stiff) # blade and slot + cyl, box = mujoco.mjtGeom.mjGEOM_CYLINDER, mujoco.mjtGeom.mjGEOM_BOX + block = scene.worldbody.add_body(name="block", pos=[0, 0, HEAD - 0.0173]) + block.add_geom(name="block", type=box, size=[0.02, 0.02, 0.01], contype=2, conaffinity=1, rgba=[0.6, 0.62, 0.66, 1], + **soft) # fmt: skip + screw = block.add_body(name="screw", pos=[0, 0, 0.0173]) # its frame: the head's top centre, the slot along x + screw.add_joint(name="sink", type=mujoco.mjtJoint.mjJNT_SLIDE, axis=[0, 0, -1], limited=True, range=[-0.001, 0.004]) + firm = [0.9999, 0.9999, 0.001, 0.5, 2] # MuJoCo's default would let the light screw creep + screw.add_joint(name="turn", type=mujoco.mjtJoint.mjJNT_HINGE, axis=[0, 0, -1], frictionloss=0.02, damping=1e-5, + solref_friction=[0.01, 1.0], solimp_friction=firm) # tightens clockwise seen from above # fmt: skip + gold = [0.85, 0.7, 0.3, 1] + screw.add_geom(name="screw_head", type=cyl, size=[0.00425, 0.001, 0], pos=[0, 0, -SLOT - 0.001], mass=0.0012, + contype=4, conaffinity=1, rgba=gold, **steel) # fmt: skip + for side in (-1, 1): # the cheeks either side of the slot + screw.add_geom(name=f"screw_cheek{side + 1}", type=box, size=[0.0035, 0.001825, SLOT / 2], + pos=[0, side * 0.002425, -SLOT / 2], mass=0.0003, contype=4, conaffinity=1, rgba=gold, + **steel) # fmt: skip + thread = scene.add_equality(type=mujoco.mjtEq.mjEQ_JOINT, name1="turn", name2="sink") # turn = 2 pi sink / pitch + thread.data[1], thread.solref, thread.solimp[:3] = 2 * np.pi / 0.0008, [0.01, 1.0], [0.99, 0.999, 0.001] + tool = scene.worldbody.add_body(name="tool", pos=[0, 0, HEAD - SLOT]) # its frame: the blade tip + tool.add_freejoint(name="tool") + tool.add_site(name="tip", size=[1e-4, 0, 0], rgba=[0, 0, 0, 0]) + grey, red = [0.75, 0.76, 0.8, 1], [0.85, 0.15, 0.12, 1] + tool.add_geom(name="blade", type=box, size=[0.002, 0.0004, 0.002], pos=[0, 0, 0.002], mass=0.0001, contype=8, + conaffinity=4, rgba=grey, **steel) # fmt: skip + tool.add_geom(name="shaft", type=cyl, size=[0.002, 0.02, 0], pos=[0, 0, 0.024], mass=0.0039, contype=8, + conaffinity=7, rgba=grey, **soft) # fmt: skip + tool.add_geom(name="handle", type=cyl, size=[0.008, 0.035, 0], pos=[0, 0, 0.079], mass=0.013, contype=8, + conaffinity=7, rgba=red, **soft) # fmt: skip + cap = tool.add_body(name="cap", pos=[0, 0, 0.114]) + cap.add_joint(name="swivel", type=mujoco.mjtJoint.mjJNT_HINGE, axis=[0, 0, 1], damping=1e-5) + cap.add_geom(name="cap", type=cyl, size=[0.006, 0.003, 0], pos=[0, 0, 0.003], mass=0.0008, contype=8, + conaffinity=7, rgba=[0.15, 0.15, 0.17, 1], **soft) # fmt: skip + for actuator in scene.actuators: # twice the servos' damping, calmer fingers; their speeds, for the plan's cost + actuator.biasprm[2] *= 2 + scene.add_sensor(name=actuator.name, type=mujoco.mjtSensor.mjSENS_ACTUATORVEL, + objtype=mujoco.mjtObj.mjOBJ_ACTUATOR, objname=actuator.name) # fmt: skip + for f in TIPS: # where the thumb, index and middle tips are, for the plan's cost on their height + scene.add_sensor(name=f, type=mujoco.mjtSensor.mjSENS_FRAMEPOS, objtype=mujoco.mjtObj.mjOBJ_XBODY, + objname=f"right_{f}_DP") # fmt: skip + for f in TIPS: # the tips' gaps to the handle + scene.add_sensor(name=f"gap_{f}", type=mujoco.mjtSensor.mjSENS_GEOMDIST, objtype=mujoco.mjtObj.mjOBJ_GEOM, + objname=f"right_{f}_fingertip_collision", reftype=mujoco.mjtObj.mjOBJ_GEOM, refname="handle", + cutoff=0.05) # fmt: skip + scene.add_sensor(name="turn", type=mujoco.mjtSensor.mjSENS_JOINTPOS, objtype=mujoco.mjtObj.mjOBJ_JOINT, + objname="turn") # fmt: skip + scene.add_sensor(name="up", type=mujoco.mjtSensor.mjSENS_FRAMEZAXIS, objtype=mujoco.mjtObj.mjOBJ_BODY, + objname="tool") # fmt: skip + scene.add_sensor(name="seat", type=mujoco.mjtSensor.mjSENS_FRAMEPOS, objtype=mujoco.mjtObj.mjOBJ_SITE, objname="tip", + reftype=mujoco.mjtObj.mjOBJ_BODY, refname="screw") # the blade's tip in the screw's frame # fmt: skip + model = scene.compile() + plan = scene.copy() # planned on the capsules, the screwdriver, screw and block, with a capped solver + plan.option.iterations, plan.option.ls_iterations = 8, 8 + plan.option.disableflags |= mujoco.mjtDisableBit.mjDSBL_NATIVECCD # box-box as a primitive, not convex + plan.geom("screw_head").type, plan.geom("screw_head").size = box, [0.00425, 0.00425, 0.001] # blade on it: box-box + for geom in plan.geoms: + kept = geom.type == mujoco.mjtGeom.mjGEOM_CAPSULE or geom.name.endswith("VL_fit") # links and knuckles + if not kept and not geom.name.startswith(("screw", "block", "blade", "shaft", "handle", "cap")): + geom.contype = geom.conaffinity = 0 + plan_model = plan.compile() + + # --- start: the fingers close on the screwdriver for 1 s while it is held seated (heavy, no gravity), then free --- + state, heavy = mujoco.MjData(model), copy.copy(model) + grasp, tool_b, start = np.r_[[0.5] * 13, CURL], model.body("tool").id, time.perf_counter() + for f, rows in (("thumb", [0, 1, 2, 3, 4]), ("index", [5, 6, 7, 8]), ("middle", [9, 10, 11, 12])): + geom, z, angle, r, gap, pad = GRASP_AT[f] # damped least squares on the finger's joints + tip, a = model.geom(f"right_{f}_fingertip_collision"), np.radians(angle) + target = np.r_[r * np.cos(a), r * np.sin(a), z, gap, pad] / 1000 + + def miss(q: np.ndarray) -> np.ndarray: # the tip's point on the driver (its frame), gap and pad point, off + state.qpos[:22], ft = q, np.zeros(6) + mujoco.mj_kinematics(model, state) + g = mujoco.mj_geomDistance(model, state, tip.id, model.geom(geom).id, 1.0, ft) + R, b = state.xmat[tool_b].reshape(3, 3), model.geom_bodyid[tip.id] + on_pad = state.xmat[b].reshape(3, 3).T @ (ft[:3] - state.xpos[b]) + return np.r_[R.T @ (ft[3:] - state.xpos[tool_b]), g, on_pad] - target + + for _ in range(60): + e, J = miss(grasp), np.zeros((7, len(rows))) + for k, j in enumerate(rows): + J[:, k] = (miss(grasp + 1e-5 * (np.arange(22) == j)) - e) / 1e-5 + dq = np.linalg.solve(J.T @ J + 1e-6 * np.eye(len(rows)), J.T @ e) + grasp[rows] = np.clip(grasp[rows] - dq * min(1, 0.2 / (np.abs(dq).max() + 1e-12)), *model.jnt_range[rows].T) + print(f"{f} on the handle within {1000 * np.linalg.norm(miss(grasp)):.4f} mm") + print(f"tripod grip solved in {time.perf_counter() - start:.2f} s") + hold = grasp.copy() + hold[[3, 5, 9, 7, 8, 11, 12]] += [0.1, 0.1, 0.1, 0.15, 0.15, 0.15, 0.15] # the commands press the tips onto it + hold[[6, 10]] += [-0.05, 0.05] # and hold the index and middle a little apart + tb, tool_q, dof = model.body("tool").id, model.joint("tool").qposadr[0], model.joint("tool").dofadr[0] + heavy.body_mass[tb], heavy.body_inertia[tb], heavy.opt.gravity = ( + 1e4 * model.body_mass[tb], + 1e4 * model.body_inertia[tb], + 0, + ) + state.qpos[:22], state.ctrl[:] = grasp, hold + placed = state.qpos[tool_q : tool_q + 7].copy() + for _ in range(100): + mujoco.mj_step(heavy, state) + state.qpos[tool_q : tool_q + 7], state.qvel[dof : dof + 6] = placed, 0.0 + mujoco.mj_forward(model, state) + + # --- SimMPC: the screw chases the quarter turn after next; the fingers twirl the handle without opening, the thumb + # and middle pushing in turn; the tips stay at their height (pressing PRESS lower) and on the handle; the + # handle stays upright and its blade at the slot's centre; touches by the lower phalanges, of the block, screw and + # cap, by the ring and pinky tips, and between fingers cost; the joints are kept slow, the ring and pinky still --- + H, turn_q = 50, model.joint("turn").qposadr[0] + turn, tips = model.sensor("turn").adr[0], [model.sensor(f).adr[0] + 2 for f in TIPS] + height = np.array([state.xpos[model.body(f"right_{f}_DP").id, 2] for f in TIPS]) + ref = np.zeros((1, STEPS + H + 1, model.nsensordata), np.float32) + ref[0, :, model.sensor("up").adr[0] + 2], ref[0, :, model.sensor("seat").adr[0] + 2] = 1.0, -SLOT + sensor_ref, grip = wp.array(ref, dtype=float), wp.zeros((1, ref.shape[1], 3), dtype=float) + ctrl_ref = np.tile(hold, (ref.shape[1], 1)) + links = [g.name for g in scene.geoms if g.name.endswith("_fit") or g.name.startswith(("block", "screw", "cap"))] + links += ["right_ring_fingertip_collision", "right_pinky_fingertip_collision"] + tip_geoms = [f"right_{f}_fingertip_collision" for f in TIPS] + ctrl_std = np.full(model.nu, 0.09) + ctrl_std[13:] *= 0.2 # the ring and pinky stay out of the twist + config = SimMPCConfig( + ctrl_std=ctrl_std, ctrl_range=model.actuator_ctrlrange, num_samples=128, horizon_steps=H, node_steps=12, + ctrl_steps=4, interpolation="cubic", std_growth=1.0, terminal_scale=1.0, stages=[SimMPCStage(2)], # at the timestep + ) # fmt: skip + config.add(SensorTask(sensor_ref, dict(turn=50.0)), terminal_scale=10.0) + costs = [ + SensorTask(sensor_ref, {actuator.name: 0.1 for actuator in scene.actuators}), # their references are 0 + SensorTask(sensor_ref, {f: [0, 0, 1e5] for f in TIPS}, hinge=1e5 * 0.0005**2), # within 0.5 mm of it + SensorTask(sensor_ref, dict(up=[8000.0] * 3, seat=[1e7] * 3)), + ControlTask(1.0, ctrl_ref), + ContactTask(links, np.zeros((1, len(links), 2)), np.zeros((1, len(links))), penalty=20.0, margin=SKIN), + SupportTask("handle", [f"{f}_fingertip" for f in TIPS], 2, 20.0, SKIN), # two of them stay on the handle + ContactTask(["cap"], np.zeros((1, 1, 2)), np.zeros((1, 1)), penalty=200.0, margin=SKIN), # hands off the cap + SensorTask(sensor_ref, dict(gap_thumb=1e6, gap_index=1e6), hinge=1e6 * 0.003**2), # tips within 3 mm of it + SensorTask(sensor_ref, dict(gap_middle=1e7), hinge=1e7 * 0.003**2), # the middle, which drifts, held harder + # a fingertip's touch costs 5, and earns 10 while `grip` is 1 + ContactTask(tip_geoms, np.zeros((1, 3, 2)), grip, weight=20.0, penalty=10.0, margin=SKIN), + ] + names = [mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, model.geom_bodyid[g]) or "" for g in range(model.ngeom)] + of = {f: np.array([f"_{f}_" in n for n in names]) for f in ("thumb", "index", "middle", "ring", "pinky")} + fingers = of["index"] | of["middle"] | of["ring"] | of["pinky"] + for a, b in [(of["thumb"], fingers), (of["index"] | of["ring"], of["middle"] | of["pinky"])]: # any touch costs + costs.append(StateTask(np.zeros((1, model.nq)), np.zeros((1, model.nv)), np.zeros(model.nv), + penetration_groups=(a, b), penetration_scale=1e8, margin=-0.002)) # fmt: skip + for term in costs: + config.add(term) + sim = MjWarpSim(model, 1, state, nconmax=96, njmax=600) # executes; the plan's rollouts run on `plan_model` + clock, first, twirl, holding = 0, state.qpos[turn_q], 0.0, False + + def lead(plan: list): + nonlocal clock, twirl, holding + q = sim.data.qpos.numpy()[0] if plan else state.qpos + angle, dt = q[turn_q] - first, model.opt.timestep + clock += config.ctrl_steps if plan else 0 + tilt = np.degrees(np.arccos(np.clip(1 - 2 * (q[tool_q + 4] ** 2 + q[tool_q + 5] ** 2), -1, 1))) + holding = tilt > HOLD - 1 if holding else tilt > HOLD # then all three hold and the screw keeps its angle + twirl += 0.0 if holding or not plan else config.ctrl_steps * dt # the twirl's clock, stopped while holding + t = twirl + np.arange(H + 1) * dt + goal = min(np.floor(angle / QUARTER) + 2, np.floor(twirl / PACE) + 2, GOALS) + ref[0, clock : clock + H + 1, turn] = first + (angle if holding else goal * QUARTER) + ref[0][clock : clock + H + 1, tips] = height - angle * 0.0008 / (2 * np.pi) - PRESS # sinking 0.8 mm a turn + sensor_ref.assign(ref) + g = np.zeros((1, ref.shape[1], 3)) + g[0, clock : clock + H + 1] = holding | ((t[:, None] / PERIOD + [0.0, 0.0, 0.5]) % 1 < [DUTY, 2.0, DUTY]) + grip.assign(g) + + lead([]) + print("building SimMPC (the first run compiles kernels) ...") + mpc = SimMPC(config, MjWarpSim(plan_model, 1, state, nconmax=96, njmax=600), ctrl_ref) + print(f"planning {STEPS * model.opt.timestep:.0f} s of motion ...") + start = time.perf_counter() + (rollout,), _ = mpc.execute(sim, STEPS, callback=lead) + planned = time.perf_counter() - start + q = rollout["qpos"] + jitter = np.sqrt(np.mean(np.diff(q[::2, :22], 2, axis=0) ** 2)) / 0.02**2 # 20 ms apart + print(f"planned in {planned:.0f} s; the screw turned {(q[-1, turn_q] - q[0, turn_q]) / (2 * np.pi):.2f} times, " + f"jitter {jitter:.1f} rad/s^2") # fmt: skip + + # --- viewer: replay the simulated motion --- + server = viser.ViserServer() + print("replaying; Ctrl+C to stop") + viewer = ViserMjcf(server, scene.to_xml()) + for name in ("visual", "collision"): # toggles: the drawn meshes, the collision shapes + box = server.gui.add_checkbox(f"Show {name}", name == "visual") + box.on_update(lambda _, b=box, n=name: setattr(viewer, f"show_{n}", b.value)) + while True: + for k in range(0, STEPS, 2): + viewer.update_qpos(rollout["qpos"][k]) + time.sleep(2 * model.opt.timestep) + time.sleep(1.0) # hold the last frame before replaying + + +if __name__ == "__main__": + main() diff --git a/src/robokit/gallery/ik_legged.py b/src/robokit/gallery/ik_legged.py index cdb040e..0f70e44 100644 --- a/src/robokit/gallery/ik_legged.py +++ b/src/robokit/gallery/ik_legged.py @@ -13,7 +13,7 @@ from robokit.helpers.ik import IKContext, IKSolver, IKSolverConfig from robokit.lie.se3 import se3_compose from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.robo import Robot, RobotState from robokit.terms.dense.com_position_task import ComPositionTask @@ -142,13 +142,10 @@ def build_scene( IKSolverConfig( enable_T_world_base=True, solver=PopulationSolverConfig( - num_iters=10 + 16, - select_at=[10, 10 + 16], - num_candidates=[64, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(10, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(16, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="full", ), diff --git a/src/robokit/gallery/motion_plan.py b/src/robokit/gallery/motion_plan.py index 28550bb..f878af2 100644 --- a/src/robokit/gallery/motion_plan.py +++ b/src/robokit/gallery/motion_plan.py @@ -243,7 +243,10 @@ def load_planner( stage = base.stages[0] trajectory_optimizer = dataclasses.replace( stage, - solver=dataclasses.replace(stage.solver, num_iters=max_iter, num_candidates=[num_candidates]), + solver=dataclasses.replace( + stage.solver, + stages=[dataclasses.replace(stage.solver.stages[0], iters=max_iter, num_candidates=num_candidates)], + ), terms=deepcopy(stage.terms), ) if solver == "mppi": diff --git a/src/robokit/gallery/robot_models.py b/src/robokit/gallery/robot_models.py index ee00759..ea736cb 100644 --- a/src/robokit/gallery/robot_models.py +++ b/src/robokit/gallery/robot_models.py @@ -159,6 +159,31 @@ "MJCF_PATH_RIGHT", "COLLISION_SPHERE_PATH_RIGHT", ), + "Wuji Hand Right": ( + "robokit.assets.robots.end_effectors.wuji_hand", + "URDF_PATH_RIGHT", + "COLLISION_SPHERE_PATH_RIGHT", + ), + "Wuji Hand Left": ( + "robokit.assets.robots.end_effectors.wuji_hand", + "URDF_PATH_LEFT", + "COLLISION_SPHERE_PATH_LEFT", + ), + "Wuji Hand 2.2 Right": ( + "robokit.assets.robots.end_effectors.wuji_hand_2_2", + "URDF_PATH_RIGHT", + "COLLISION_SPHERE_PATH_RIGHT", + ), + "Wuji Hand 2.2 Left": ( + "robokit.assets.robots.end_effectors.wuji_hand_2_2", + "URDF_PATH_LEFT", + "COLLISION_SPHERE_PATH_LEFT", + ), + "Wuji Hand 2.2 Right (MJCF)": ( + "robokit.assets.robots.end_effectors.wuji_hand_2_2", + "MJCF_PATH_RIGHT", + "COLLISION_SPHERE_PATH_RIGHT", + ), "YAM Gripper": ( "robokit.assets.robots.end_effectors.yam_gripper", "URDF_PATH", diff --git a/src/robokit/geom/covering_spheres.py b/src/robokit/geom/covering_spheres.py new file mode 100644 index 0000000..c7b048e --- /dev/null +++ b/src/robokit/geom/covering_spheres.py @@ -0,0 +1,23 @@ +"""Spheres covering a box or a cylinder, the collision geometry of a held object.""" + +from typing import Literal, Optional, Sequence + +import numpy as np + + +def _compute_covering_spheres( + shape: Literal["box", "cylinder"], size: Sequence[float], T_frame_shape: Optional[np.ndarray] = None +) -> np.ndarray: + """Spheres `(n, 4)` `(x, y, z, radius)` covering a box (half extents) or a z-axis cylinder (radius, half height), + posed by 4x4 `T_frame_shape`: each encloses a cell of a grid no wider than the larger of the smallest half extent + and a quarter of the largest, so it bulges past each face by up to the radius less half the cell (e.g. 0.37 h for + a cube of half side h).""" + half = np.array([*size] if shape == "box" else [size[0], size[0], size[1]], dtype=np.float64) + counts = np.ceil(2 * half / max(half.min(), half.max() / 4) - 1e-9).astype(int) + cell = 2 * half / counts + centers = (np.indices(counts).reshape(3, -1).T + 0.5) * cell - half + if shape == "cylinder": # the cells that reach it + centers = centers[np.linalg.norm(np.maximum(np.abs(centers[:, :2]) - cell[:2] / 2, 0), axis=1) < size[0]] + T = np.eye(4) if T_frame_shape is None else np.asarray(T_frame_shape) + points = centers @ T[:3, :3].T + T[:3, 3] + return np.c_[points, np.full(len(points), 0.5 * np.linalg.norm(cell))] diff --git a/src/robokit/geom/scene.py b/src/robokit/geom/scene.py index c21644e..0fb3977 100644 --- a/src/robokit/geom/scene.py +++ b/src/robokit/geom/scene.py @@ -147,32 +147,19 @@ def query_sdf( Args: points: Query points, any shape (flattened to n internally). - scene_offsets: CSR boundaries into the flat points, int32, length num_scenes+1. - Pass exactly one of `scene_offsets` / `scene_indices`. - scene_indices: Scene id of each point, int32, one per point. Skips the - derivation launch, so hot loops pass a pre-built map here. - query_mask: Optional per-point gate, int32, length n. Points with mask 0 skip - every geom kernel. - distance_only: Skip the normal/closest computation (~2x faster) and return - only signed distances. - out_signed_dists: Optional preallocated output; required shape n. Hot loops and - CUDA-graph capture pass all `out_*` so no allocation happens per call. + scene_offsets: CSR boundaries into the flat points, int32, length num_scenes+1. Pass exactly one of `scene_offsets` / `scene_indices`. + scene_indices: Scene id of each point, int32, one per point. Skips the derivation launch, so hot loops pass a pre-built map here. + query_mask: Optional per-point gate, int32, length n. Points with mask 0 skip every geom kernel. + distance_only: Skip the normal/closest computation (~2x faster) and return only signed distances. + out_signed_dists: Optional preallocated output; required shape n. Hot loops and CUDA-graph capture pass all `out_*` so no allocation happens per call. out_normals: Optional preallocated output, shape n. out_closest_points: Optional preallocated output, shape n. - out_normal_jacobians: Optional preallocated `wp.mat33` output, one per point. - Entry (i, j) is the derivative of normal component i with respect to - point coordinate j. Mesh face normals have zero derivatives; voxel and - primitive normals use analytical derivatives of the active query branch. - Derivatives at cell, face, or closest-object switches are discontinuous. + out_normal_jacobians: Optional preallocated `wp.mat33` output, one per point. Entry (i, j) is the derivative of normal component i with respect to point coordinate j. Mesh face normals have zero derivatives; voxel and primitive normals use analytical derivatives of the active query branch. Derivatives at cell, face, or closest-object switches are discontinuous. record_tape: Record the launches on an active `wp.Tape`; False keeps the query off the gradient. - out_observed: Optional device bool array, one per point. True when every sensor map in - the scene has observed the queried voxel; outside a sensor map or masked out is False. Meshes and - analytical geometry leave this status unchanged. Unknown status never skips distance checks. + out_observed: Optional device bool array, one per point. True when every sensor map in the scene has observed the queried voxel; outside a sensor map or masked out is False. Meshes and analytical geometry leave this status unchanged. Unknown status never skips distance checks. Returns: - Flat `(n,)` views: `signed_dists` if `distance_only`, else - `(signed_dists, normals, closest_points)`. Points in an empty scene get - `MAX_DIST` distance and zero normals. + Flat `(n,)` views: `signed_dists` if `distance_only`, else `(signed_dists, normals, closest_points)`. Points in an empty scene get `MAX_DIST` distance and zero normals. """ if (scene_offsets is None) == (scene_indices is None): raise ValueError("query_sdf requires exactly one of scene_offsets or scene_indices.") @@ -280,16 +267,11 @@ def query_sdf_torch( Args: query_points: Query points, shape (n, 3), differentiable. scene_offsets: CSR boundaries into the points, length num_scenes+1. - poses: Optional per-geom pose overrides, (count, 4, 4) tensors keyed by - attached geom. Overridden geoms are queried on these poses and receive - gradients; other geoms use their stored (non-differentiable) transforms. - scales: Optional per-geom scale overrides, (count,) tensors keyed by - attached geom. Same semantics as `poses`. + poses: Optional per-geom pose overrides, (count, 4, 4) tensors keyed by attached geom. Overridden geoms are queried on these poses and receive gradients; other geoms use their stored (non-differentiable) transforms. + scales: Optional per-geom scale overrides, (count,) tensors keyed by attached geom. Same semantics as `poses`. Returns: - `(signed_dists, normals, closest_points)` torch tensors, shapes (n,), (n, 3), - (n, 3). Gradients flow to `query_points` and to the `poses`/`scales` tensors - of whichever geom is closest at each point. + `(signed_dists, normals, closest_points)` torch tensors, shapes (n,), (n, 3), (n, 3). Gradients flow to `query_points` and to the `poses`/`scales` tensors of whichever geom is closest at each point. """ import torch diff --git a/src/robokit/geom/sdf_volume.py b/src/robokit/geom/sdf_volume.py index d5d4f38..5e61022 100644 --- a/src/robokit/geom/sdf_volume.py +++ b/src/robokit/geom/sdf_volume.py @@ -23,11 +23,7 @@ # --- volume ---------------------------------------------------------------- @dataclass class SdfVolume: - """Signed-distance grid with mesh, XYZ, and calibrated-depth builders. - - XYZ updates add occupied cells. Depth fuses observations and may clear old - samples along observed rays. Both refresh the same collision grid in place. - Observation weights determine known/unknown status. Each update sets the unknown-space policy. + """Signed-distance grid with mesh, XYZ, and calibrated-depth builders. XYZ updates add occupied cells. Depth fuses observations and may clear old samples along observed rays. Both refresh the same collision grid in place. Observation weights determine known/unknown status. Each update sets the unknown-space policy. Example: >>> # xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS) @@ -255,8 +251,7 @@ def update( 2. Reset observations: clear fusion history when `reset=True`. 3. Fuse depth: average calibrated projective distances; observed free rays may clear old obstacles. 4. Mark points: add occupied cells after depth fusion, preserving unseen observations. - 5. Refresh collision grid: classify observations and unknown space, then write the signed - ESDF in place using approximate jump flooding with two refinement passes. + 5. Refresh collision grid: classify observations and unknown space, then write the signed ESDF in place using approximate jump flooding with two refinement passes. Args: points: Optional `(N, 3)` NumPy XYZ samples or device Warp `vec3` array; invalid/outside points are ignored. @@ -270,8 +265,7 @@ def update( unknown_is_occupied: Treat unobserved cells and space outside the map as occupied until the next update. Returns: - `self`, retaining bounds, resolution and volume ID so captured collision queries remain valid. - Options apply only to this call; an update without inputs refreshes the retained observations. + `self`, retaining bounds, resolution and volume ID so captured collision queries remain valid. Options apply only to this call; an update without inputs refreshes the retained observations. Raises: ValueError: The volume lacks fusion history, or parameters or input array metadata are invalid. diff --git a/src/robokit/helpers/full_body_retargeting/config.py b/src/robokit/helpers/full_body_retargeting/config.py index f58dea2..d12317b 100644 --- a/src/robokit/helpers/full_body_retargeting/config.py +++ b/src/robokit/helpers/full_body_retargeting/config.py @@ -11,7 +11,7 @@ from robokit.helpers.humanoid_retargeting.config import HumanoidRetargeterOfflineConfig from robokit.helpers.ik.config import IKContext, IKSolverConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.robo import Robot from robokit.terms.dense.position_limit import PositionLimit @@ -76,7 +76,7 @@ class FullBodyRetargetingConfig: default_factory=lambda: ( IKSolverConfig( solver=PopulationSolverConfig( - num_iters=15, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=1.0), cuda_graph_mode="full" + stages=[Stage(15, optimizer=LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="full" ), sampler=RobertsSamplerConfig(keep_first=True, scale=0.0), ) diff --git a/src/robokit/helpers/full_body_retargeting/retargeting.py b/src/robokit/helpers/full_body_retargeting/retargeting.py index 16f5b8d..f5ec7a2 100644 --- a/src/robokit/helpers/full_body_retargeting/retargeting.py +++ b/src/robokit/helpers/full_body_retargeting/retargeting.py @@ -1,12 +1,9 @@ -"""Full-body driver: `FullBodyClip` -> qpos `[T, 7 + dof + 7 * num_objects]`. - -Every stage runs per engaged hand, so one- and two-handed clips take the same path: +"""Full-body driver: `FullBodyClip` -> qpos `[T, 7 + dof + 7 * num_objects]`; every stage runs per engaged hand, so one- and two-handed clips take the same path: 1. hand pass - captured MANO keypoints onto the standalone hand, in the native world; 2. body pass - whole-body tracking with each grasp wrist injected as a high-weight target track; 3. arm snap - an arm-only IK puts each palm exactly at the hand-pass pose; -4. contact refine - fingers re-solve at the achieved wrist against that hand's object, with - sphere-vs-mesh collision. Stages 2-4 iterate twice so the body absorbs the wrist correction. +4. contact refine - fingers re-solve at the achieved wrist against that hand's object, with sphere-vs-mesh collision. Stages 2-4 iterate twice so the body absorbs the wrist correction. """ from dataclasses import replace @@ -99,8 +96,7 @@ def solve( Args: clip: Loaded interaction clip. max_frames: Frame cap; 0 keeps all frames. - hand_trajectories: Optional externally solved standalone-hand trajectories per side; - each replaces that side's hand pass and skips its contact refine. + hand_trajectories: Optional externally solved standalone-hand trajectories per side; each replaces that side's hand pass and skips its contact refine. scene_clearance: Push the solved body out of penetrated scene parts. Returns: @@ -406,8 +402,12 @@ def _solve_body_batch( # Arm IK has independent frames, so pack valid frames without temporal padding. key = (tuple(sides), sum(lengths), external_hands) if self._arm_ik_key != key: - iters = self.config.arm_snap_trajectory_iters if external_hands else self.config.arm_snap.solver.num_iters - ik_cfg = replace(self.config.arm_snap, solver=replace(self.config.arm_snap.solver, num_iters=iters)) + solver = self.config.arm_snap.solver + if external_hands: + solver = replace( + solver, stages=[replace(solver.stages[0], iters=self.config.arm_snap_trajectory_iters)] + ) + ik_cfg = replace(self.config.arm_snap, solver=solver) links = [side[0].upper() + "_" + name for side in sides for name in (_HAND_BASE_LINK, *_ORIENTATION_LINKS)] self._arm_ik = IKSolver(ik_cfg, robot=self.body_robot, target_links=links, device=self.device) active = { diff --git a/src/robokit/helpers/full_body_retargeting/scene_clearance.py b/src/robokit/helpers/full_body_retargeting/scene_clearance.py index 13e8db5..4ff5eec 100644 --- a/src/robokit/helpers/full_body_retargeting/scene_clearance.py +++ b/src/robokit/helpers/full_body_retargeting/scene_clearance.py @@ -13,7 +13,7 @@ from robokit.helpers.ik import IKSolver from robokit.helpers.ik.config import IKContext, IKSolverConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.robo import Robot from robokit.smplx import SMPLX_JOINT_NAMES @@ -130,7 +130,7 @@ def is_core(link_name: str) -> bool: enable_T_world_base=True, base_active_mask=(0.0,) * 6, solver=PopulationSolverConfig( - num_iters=20, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=1.0), cuda_graph_mode="none" + stages=[Stage(20, optimizer=LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="none" ), sampler=RobertsSamplerConfig(keep_first=True, scale=0.0), ) diff --git a/src/robokit/helpers/grasp/grasp_var.py b/src/robokit/helpers/grasp/grasp_var.py index 48ce6c4..be251bc 100644 --- a/src/robokit/helpers/grasp/grasp_var.py +++ b/src/robokit/helpers/grasp/grasp_var.py @@ -175,10 +175,10 @@ def clone(self) -> "ContactVar": setattr(clone, name, wp.clone(getattr(self, name))) return clone - def view(self, batch_size: int) -> "ContactVar": + def view(self, batch_size: int, offset: int = 0) -> "ContactVar": view = copy.copy(self) for name in ("indices", "points", "link_indices", "rand_states"): - setattr(view, name, getattr(self, name)[:batch_size]) + setattr(view, name, getattr(self, name)[offset : offset + batch_size]) return view def integrate( diff --git a/src/robokit/helpers/hand_eye_calibration/calibrator.py b/src/robokit/helpers/hand_eye_calibration/calibrator.py index 4029188..5d65e9c 100644 --- a/src/robokit/helpers/hand_eye_calibration/calibrator.py +++ b/src/robokit/helpers/hand_eye_calibration/calibrator.py @@ -25,7 +25,7 @@ ) from robokit.lie.se3 import SE3Var, se3_from_matrix, se3_to_matrix from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSampler from robokit.opt.var_values import Var, VarKey, VarValues from robokit.robo import Robot @@ -421,9 +421,13 @@ def _build( self._keypoint_solver = PopulationSolver( [term], PopulationSolverConfig( - num_iters=self.config.keypoint_warmup_iters, - num_candidates=[first_num_candidates], - optimizer=LMOptimizerConfig(lm_lambda=0.01, early_stopping_interval=0), + stages=[ + Stage( + self.config.keypoint_warmup_iters, + first_num_candidates, + LMOptimizerConfig(lm_lambda=0.01, early_stopping_interval=0), + ) + ], use_early_stopping=False, cuda_graph_mode="none", ), diff --git a/src/robokit/helpers/hand_eye_calibration/config.py b/src/robokit/helpers/hand_eye_calibration/config.py index 313007b..b57048b 100644 --- a/src/robokit/helpers/hand_eye_calibration/config.py +++ b/src/robokit/helpers/hand_eye_calibration/config.py @@ -5,7 +5,7 @@ from robokit.helpers.hand_eye_calibration.mask_alignment_task import MaskAlignmentNormalEqTask from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.task import ResidualTask @@ -37,12 +37,15 @@ def _default_levels() -> List[PyramidLevel]: def _default_solver() -> PopulationSolverConfig: - lm = LMOptimizerConfig(lm_lambda=1e-3, rho_min=1e-3) + lm = LMOptimizerConfig(lm_lambda=1e-3, rho_min=1e-3, early_stopping_interval=2) return PopulationSolverConfig( - num_iters=15 + 10 + 12 + 10 + 30, - select_at=[15, 15 + 10, 15 + 10 + 12, 15 + 10 + 12 + 10], - num_candidates=[32, 3, 2, 1, 1], - optimizer=[replace(lm, early_stopping_interval=interval) for interval in (2, 2, 2, 1, 1)], + stages=[ + Stage(15, 32, lm), + Stage(10, 3), + Stage(12, 2), + Stage(10, 1, replace(lm, early_stopping_interval=1)), + Stage(30), + ] ) @@ -131,10 +134,7 @@ class QposTrajectoryCalibratorConfig: levels: Sequence[PyramidLevel] = field(default_factory=lambda: [PyramidLevel(4, 1.0, 5), PyramidLevel(1, 0.0, 5)]) solver: PopulationSolverConfig = field( default_factory=lambda: PopulationSolverConfig( - num_iters=40, - select_at=[20], - num_candidates=[1, 1], - optimizer=LMOptimizerConfig(lm_lambda=1e-3, rho_min=1e-3, early_stopping_interval=2), + stages=[Stage(20, 1, LMOptimizerConfig(lm_lambda=1e-3, rho_min=1e-3, early_stopping_interval=2)), Stage(20)] ) ) path_weight: float = 0.08 diff --git a/src/robokit/helpers/hand_eye_calibration/presets.py b/src/robokit/helpers/hand_eye_calibration/presets.py index dcec753..fcf2071 100644 --- a/src/robokit/helpers/hand_eye_calibration/presets.py +++ b/src/robokit/helpers/hand_eye_calibration/presets.py @@ -10,7 +10,7 @@ _default_levels, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage # --- camera calibration ----------------------------------------------------- @@ -22,10 +22,11 @@ rgb_single_level = replace( # the full-resolution level alone, with the whole pyramid's iteration budget rgb, levels=[rgb.levels[-1]], - solver=replace(rgb.solver, select_at=[], num_candidates=[1], optimizer=cast(list, rgb.solver.optimizer)[-1]), + solver=replace(rgb.solver, stages=[Stage(rgb.solver.num_iters, 1, cast(list, rgb.solver.optimizer)[-1])]), ) # --- unknown frame qpos ------------------------------------------------------ +_lm = LMOptimizerConfig(lm_lambda=1e-3, rho_min=1e-3, early_stopping_interval=2) # Screen broad seeds once, then refine a smaller beam until image convergence. rgb_qpos = replace( rgb, @@ -34,12 +35,7 @@ PyramidLevel(4, 1.0, 4), PyramidLevel(1, 0.0, 5), ], - solver=PopulationSolverConfig( - num_iters=80, - select_at=[1, 40], - num_candidates=[512, 64, 8], - optimizer=LMOptimizerConfig(lm_lambda=1e-3, rho_min=1e-3, early_stopping_interval=2), - ), + solver=PopulationSolverConfig(stages=[Stage(1, 512, _lm), Stage(39, 64), Stage(40, 8)]), optimize_q=True, optimize_camera=False, candidate_noise_q=None, @@ -52,7 +48,10 @@ rgb_qpos_trajectory = QposTrajectoryCalibratorConfig( frame=replace( rgb_qpos, - solver=replace(rgb_qpos.solver, num_candidates=[1024, 32, 8]), + solver=replace( + rgb_qpos.solver, + stages=[replace(s, num_candidates=n) for s, n in zip(rgb_qpos.solver.stages, (1024, 32, 8))], + ), max_restarts=0, candidate_metric="iou", keypoint_sigma=16.0, @@ -64,12 +63,7 @@ initialization_seconds=18.0, levels=[PyramidLevel(4, 1.0, 5), PyramidLevel(2, 0.6, 5), PyramidLevel(1, 0.0, 5)], solver=PopulationSolverConfig( - num_iters=48, - select_at=[16, 32], - num_candidates=[1, 1, 1], - optimizer=LMOptimizerConfig( - lm_lambda=1e-3, lambda_min=1e-4, rho_min=1e-3, early_stopping_interval=2, linear_solver="torch_cholesky" - ), + stages=[Stage(16, 1, replace(_lm, lambda_min=1e-4, linear_solver="torch_cholesky")), Stage(16), Stage(16)] ), velocity_weight=0.015, acceleration_weight=0.05, diff --git a/src/robokit/helpers/hand_eye_calibration/qpos_trajectory_calibrator.py b/src/robokit/helpers/hand_eye_calibration/qpos_trajectory_calibrator.py index ea28aa8..c90e2de 100644 --- a/src/robokit/helpers/hand_eye_calibration/qpos_trajectory_calibrator.py +++ b/src/robokit/helpers/hand_eye_calibration/qpos_trajectory_calibrator.py @@ -245,9 +245,7 @@ def on_step(self, accept_mask: wp.array, iter_idx: int, costs: wp.array) -> bool class QposTrajectoryCalibrator: - """Fit unknown q[T,J], optionally refining shared static cameras[V,4,4]. - - Cameras are shared over time; temporal penalties apply only to q. + """Fit unknown q[T,J], optionally refining static cameras[V,4,4] shared over time; temporal penalties apply only to q. Example (CUDA, robot meshes and observations required): >>> # xdoctest: +REQUIRES(module:nvdiffrast) @@ -478,14 +476,17 @@ def _initialize_q( ) seed_helper = None if target_keypoints is None: + solver = helper.config.solver # half the schedule, one candidate per level + ends = [max(1, i // 2) for i in solver.select_at] + [solver.num_iters // 2] seed_helper = HandEyeCalibrator( replace( helper.config, solver=replace( - helper.config.solver, - num_iters=helper.config.solver.num_iters // 2, - select_at=[max(1, i // 2) for i in helper.config.solver.select_at], - num_candidates=[1] * len(helper.config.levels), + solver, + stages=[ + replace(stage, iters=end - start, num_candidates=1) + for stage, start, end in zip(solver.stages, [0, *ends], ends) + ], ), max_restarts=0, ), @@ -606,7 +607,7 @@ def solve( target_keypoints: Optional[torch.Tensor] = None, keypoint_weights: Optional[torch.Tensor] = None, ) -> torch.Tensor: - """Fit synchronized silhouettes and optional keypoints to a joint trajectory. + """Fit synchronized silhouettes and optional keypoints to a joint trajectory; an empty mask with positive weight constrains absence. Lifecycle: 1. Validate calibration, timestamps and observations; normalize mask costs by area. @@ -624,8 +625,6 @@ def solve( target_keypoints: Image coordinates `[T,V,P,2]`; NaNs mark missing points. keypoint_weights: Optional confidence weights `[T,V,P]`; zero excludes a point. - An empty mask with positive weight constrains absence. - Returns: Cameras `[V,4,4]` on the input device; fixed unless camera refinement is enabled. diff --git a/src/robokit/helpers/hand_eye_calibration/trajectory_alignment.py b/src/robokit/helpers/hand_eye_calibration/trajectory_alignment.py index fd6e7ca..6401009 100644 --- a/src/robokit/helpers/hand_eye_calibration/trajectory_alignment.py +++ b/src/robokit/helpers/hand_eye_calibration/trajectory_alignment.py @@ -7,10 +7,7 @@ def initialization_frames(visible: np.ndarray, times: np.ndarray, count: int, guided: np.ndarray) -> np.ndarray: - """Search jointly visible interval boundaries, then spread guided frames. - - Visibility `[T,V]` prefers two views; `[T]` retains supplied visibility, while absent or partial masks still constrain refinement. - """ + """Search jointly visible interval boundaries, then spread guided frames; visibility `[T,V]` prefers two views, `[T]` retains supplied visibility, while absent or partial masks still constrain refinement.""" if visible.ndim == 2: counts = visible.sum(-1) visible = counts >= max(1, min(2, int(counts.max()))) @@ -43,9 +40,7 @@ def trajectory_normal_equations( acceleration_weight: float = 0.02, free_cameras: bool = False, ) -> tuple: - """Assemble one coupled system from [views, frames, 6+joints] image blocks. - - Joint smoothness uses source timestamps; no recorded states or task-specific priors are used. + """Assemble one coupled system from [views, frames, 6+joints] image blocks; joint smoothness uses source timestamps, no recorded states or task-specific priors. >>> # xdoctest: +REQUIRES(module:nvdiffrast) >>> q = torch.zeros((3, 1)) diff --git a/src/robokit/helpers/hand_retargeting/config.py b/src/robokit/helpers/hand_retargeting/config.py index 0f29b30..5fc8e8b 100644 --- a/src/robokit/helpers/hand_retargeting/config.py +++ b/src/robokit/helpers/hand_retargeting/config.py @@ -7,7 +7,7 @@ import numpy as np from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_vector_task import FrameVectorTask @@ -28,16 +28,12 @@ _Correspondence = Tuple[str, str, str, str] # origin link, task link, origin target, task target -def _online_solver() -> PopulationSolverConfig: +def _online_solver( + iters: Tuple[int, int, int] = (6, 10, 0), widths: Tuple[int, int, int] = (16, 4, 1) +) -> PopulationSolverConfig: + damping = (1e-1, 1e-2, 1e-2) return PopulationSolverConfig( - num_iters=6 + 10, - select_at=[6, 6 + 10], - num_candidates=[16, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=1e-1), - LMOptimizerConfig(lm_lambda=1e-2), - LMOptimizerConfig(lm_lambda=1e-2), - ], + stages=[Stage(n, w, LMOptimizerConfig(lm_lambda=d)) for n, w, d in zip(iters, widths, damping)], cuda_graph_mode="full", ) diff --git a/src/robokit/helpers/hand_retargeting/dexycb_utils.py b/src/robokit/helpers/hand_retargeting/dexycb_utils.py index 6769fcf..a629b55 100644 --- a/src/robokit/helpers/hand_retargeting/dexycb_utils.py +++ b/src/robokit/helpers/hand_retargeting/dexycb_utils.py @@ -141,8 +141,7 @@ def compute_dexycb_contacts( contact_threshold: Maximum fingertip-to-surface contact distance. Returns: - Arrays keyed by `_points` and `_mask`, with shapes - `[F_raw, 5, 3]` and `[F_raw, 5]` respectively. + Arrays keyed by `_points` and `_mask`, with shapes `[F_raw, 5, 3]` and `[F_raw, 5]` respectively. """ tip_indices = np.flatnonzero(np.asarray(MANOPTH_KEYPOINT_PERMUTATION) >= MANO_NUM_JOINTS) queries: Dict[Path, trimesh.proximity.ProximityQuery] = {} diff --git a/src/robokit/helpers/hand_retargeting/offline.py b/src/robokit/helpers/hand_retargeting/offline.py index 6cf648c..c89f05d 100644 --- a/src/robokit/helpers/hand_retargeting/offline.py +++ b/src/robokit/helpers/hand_retargeting/offline.py @@ -268,8 +268,7 @@ def solve( """Retarget one Warp trajectory batch. Args: - target_points: Float points shaped (batch, frames, targets, 3) in - spec.target_names order. + target_points: Float points shaped (batch, frames, targets, 3) in spec.target_names order. root_quat_wxyz: Optional root rotations shaped (batch, frames, 4). init_state: Optional joint and base warm start. out: Optional packed output shaped (batch, frames, 7 + dofs). @@ -333,8 +332,7 @@ def solve_with_contact( init_state: Optional state that anchors the solution around that trajectory. local_contact_points: Optional contacts in each link frame. out: Optional caller-owned packed output. - surface_contact_mask: Optional mask for sphere-surface contacts. Uses - `contact_mask` when omitted. + surface_contact_mask: Optional mask for sphere-surface contacts; uses `contact_mask` when omitted. Returns: Packed base transforms and joint positions. diff --git a/src/robokit/helpers/hand_retargeting/online.py b/src/robokit/helpers/hand_retargeting/online.py index 81bf2a3..5974360 100644 --- a/src/robokit/helpers/hand_retargeting/online.py +++ b/src/robokit/helpers/hand_retargeting/online.py @@ -37,8 +37,7 @@ class HandRetargeterOnline: - Later frames: smooth against the previous solution, independently of the initial guess. Args: - robot: Loaded robot model. Self-collision skip pairs come from its spec - (`Robot.load(self_collision_ignore_path=...)`). + robot: Loaded robot model; self-collision skip pairs come from its spec (`Robot.load(self_collision_ignore_path=...)`). spec: Ordered semantic point topology. config: Online solver, objective, filtering, and sampling settings. device: Warp device. The first CUDA device is used when available. @@ -46,7 +45,7 @@ class HandRetargeterOnline: Example: >>> from robokit.robo.robot_spec import RobotSpec >>> from robokit.utils.ee_coord_utils import MANOPTH_HAND_COORD_SPEC as coords - >>> from robokit.opt.population_solver import PopulationSolverConfig + >>> from robokit.opt.population_solver import PopulationSolverConfig, Stage >>> from robokit.opt.lm_optimizer import LMOptimizerConfig >>> from robokit.utils.warp_utils import wp_vec7 >>> urdf = ''' @@ -57,8 +56,8 @@ class HandRetargeterOnline: >>> spec = HandSpec(True, ("tip", "wrist"), {"tip": "tip", "wrist": "palm"}, ... (("tip",),), "wrist", ("tip",), coords) >>> config = HandRetargeterOnlineConfig(reference_origin="wrist", - ... solver=PopulationSolverConfig(num_iters=2, num_candidates=[1], - ... optimizer=LMOptimizerConfig(), cuda_graph_mode="none")) + ... solver=PopulationSolverConfig(stages=[Stage(2, optimizer=LMOptimizerConfig())], + ... cuda_graph_mode="none")) >>> config.task("positions").weight = {"tip": 24.0, "wrist": 0.1} >>> solver = HandRetargeterOnline(config, robot, spec, device="cpu") >>> solver.warmup(1) @@ -272,14 +271,12 @@ def solve( """Retarget one batched frame. Args: - target_points: Point targets with shape `(batch, targets, 3)` in - `spec.target_names` order. + target_points: Point targets with shape `(batch, targets, 3)` in `spec.target_names` order. init_state: Optional state overriding the streaming warm start. out: Optional packed output buffer with shape `(batch, 7 + dofs)`. Returns: - Packed base transform and joint positions. A helper-owned buffer is - reused when `out` is omitted. + Packed base transform and joint positions; a helper-owned buffer is reused when `out` is omitted. """ if self._batch_size is None: raise RuntimeError("call warmup(batch_size) before solve().") diff --git a/src/robokit/helpers/hand_retargeting/presets/_common.py b/src/robokit/helpers/hand_retargeting/presets/_common.py index 139977a..3e6bdb2 100644 --- a/src/robokit/helpers/hand_retargeting/presets/_common.py +++ b/src/robokit/helpers/hand_retargeting/presets/_common.py @@ -149,5 +149,5 @@ def wrist_config( output_ema_alpha=1.0, base_init_sample_range=(0.0, 0.0, 0.0), sampler=RobertsSamplerConfig(scale=0.05, keep_first=True), - solver=replace(_online_solver(), num_candidates=[64, 8, 1], num_iters=64, select_at=[24, 64]), + solver=_online_solver((24, 40, 0), (64, 8, 1)), ) diff --git a/src/robokit/helpers/hand_retargeting/presets/ability.py b/src/robokit/helpers/hand_retargeting/presets/ability.py index 6cf3e0f..839ebeb 100644 --- a/src/robokit/helpers/hand_retargeting/presets/ability.py +++ b/src/robokit/helpers/hand_retargeting/presets/ability.py @@ -19,6 +19,7 @@ wrist_config, ) from robokit.opt.lm_optimizer import LMOptimizerConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_vector_task import FrameVectorTask from robokit.terms.dense.position_limit import PositionLimit @@ -95,10 +96,9 @@ ], target_scale=0.998100757598877, output_ema_alpha=0.7, - solver=replace( - HandRetargeterOnlineConfig().solver, - num_iters=300, - optimizer=[LMOptimizerConfig(lm_lambda=0.001, lambda_min=1e-07) for _ in range(3)], + solver=PopulationSolverConfig( + stages=[Stage(6, 16, LMOptimizerConfig(lm_lambda=0.001, lambda_min=1e-07)), Stage(10, 4), Stage(284, 1)], + cuda_graph_mode="full", ), base_init_sample_range=(0.0, 0.0, 0.0), ) diff --git a/src/robokit/helpers/hand_retargeting/presets/allegro.py b/src/robokit/helpers/hand_retargeting/presets/allegro.py index 9f6e977..edc8479 100644 --- a/src/robokit/helpers/hand_retargeting/presets/allegro.py +++ b/src/robokit/helpers/hand_retargeting/presets/allegro.py @@ -20,7 +20,7 @@ wrist_config, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_vector_task import FrameVectorTask @@ -114,7 +114,7 @@ target_scale=1.36, output_ema_alpha=0.4, solver=PopulationSolverConfig( - num_iters=10, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=0.01), cuda_graph_mode="full" + stages=[Stage(10, optimizer=LMOptimizerConfig(lm_lambda=0.01))], cuda_graph_mode="full" ), sampler=RobertsSamplerConfig(keep_first=True, scale=0.0), ) diff --git a/src/robokit/helpers/hand_retargeting/presets/inspire.py b/src/robokit/helpers/hand_retargeting/presets/inspire.py index 262b601..426c966 100644 --- a/src/robokit/helpers/hand_retargeting/presets/inspire.py +++ b/src/robokit/helpers/hand_retargeting/presets/inspire.py @@ -19,7 +19,7 @@ wrist_config, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_vector_task import FrameVectorTask from robokit.terms.dense.position_limit import PositionLimit @@ -96,7 +96,7 @@ target_scale=1.2075, output_ema_alpha=0.4, solver=PopulationSolverConfig( - num_iters=30, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=0.01), cuda_graph_mode="full" + stages=[Stage(30, optimizer=LMOptimizerConfig(lm_lambda=0.01))], cuda_graph_mode="full" ), ) offline = HandRetargeterOfflineConfig(target_scale=1.15) diff --git a/src/robokit/helpers/hand_retargeting/presets/leap.py b/src/robokit/helpers/hand_retargeting/presets/leap.py index 814a4e2..89c345b 100644 --- a/src/robokit/helpers/hand_retargeting/presets/leap.py +++ b/src/robokit/helpers/hand_retargeting/presets/leap.py @@ -7,6 +7,7 @@ HandRetargeterOfflineConfig, HandRetargeterOnlineConfig, HandSpec, + _online_solver, ) from robokit.helpers.hand_retargeting.presets._common import ( FOUR_DIRECTION_PAIRS, @@ -89,7 +90,7 @@ PositionLimit(weight=1.0, name="position_limit"), ], target_scale=1.2797727584838867, - solver=replace(HandRetargeterOnlineConfig().solver, num_iters=30), + solver=_online_solver((6, 10, 14)), base_init_sample_range=(0.0, 0.0, 0.0), ) offline = HandRetargeterOfflineConfig(target_scale=1.28) diff --git a/src/robokit/helpers/hand_retargeting/presets/paxini.py b/src/robokit/helpers/hand_retargeting/presets/paxini.py index b0e70e4..fe96f18 100644 --- a/src/robokit/helpers/hand_retargeting/presets/paxini.py +++ b/src/robokit/helpers/hand_retargeting/presets/paxini.py @@ -7,6 +7,7 @@ HandRetargeterOfflineConfig, HandRetargeterOnlineConfig, HandSpec, + _online_solver, ) from robokit.helpers.hand_retargeting.presets._common import ( FOUR_DIRECTION_PAIRS, @@ -88,7 +89,7 @@ ], target_scale=1.306305170059204, output_ema_alpha=0.8, - solver=replace(HandRetargeterOnlineConfig().solver, num_iters=30), + solver=_online_solver((6, 10, 14)), base_init_sample_range=(0.0, 0.0, 0.0), ) offline = HandRetargeterOfflineConfig(target_scale=1.36) diff --git a/src/robokit/helpers/hand_retargeting/presets/shadow.py b/src/robokit/helpers/hand_retargeting/presets/shadow.py index bf01ef8..10da157 100644 --- a/src/robokit/helpers/hand_retargeting/presets/shadow.py +++ b/src/robokit/helpers/hand_retargeting/presets/shadow.py @@ -19,7 +19,7 @@ wrist_config, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_vector_task import FrameVectorTask from robokit.terms.dense.position_limit import PositionLimit @@ -118,7 +118,7 @@ target_scale=1.1115, output_ema_alpha=0.4, solver=PopulationSolverConfig( - num_iters=10, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=0.01), cuda_graph_mode="full" + stages=[Stage(10, optimizer=LMOptimizerConfig(lm_lambda=0.01))], cuda_graph_mode="full" ), ) offline = HandRetargeterOfflineConfig(target_scale=1.17) diff --git a/src/robokit/helpers/hand_retargeting/presets/sharpa.py b/src/robokit/helpers/hand_retargeting/presets/sharpa.py index 8964b2e..2514210 100644 --- a/src/robokit/helpers/hand_retargeting/presets/sharpa.py +++ b/src/robokit/helpers/hand_retargeting/presets/sharpa.py @@ -1,12 +1,11 @@ """Sharpa Wave Hand retargeting presets.""" -from dataclasses import replace - from robokit.helpers.hand_retargeting.config import ( HandContext, HandRetargeterOfflineConfig, HandRetargeterOnlineConfig, HandSpec, + _online_solver, ) from robokit.helpers.hand_retargeting.presets._common import ( FIVE_FINGERTIPS, @@ -96,7 +95,7 @@ SelfCollisionTask(weight=10.0, margin=0.002, max_active_pairs=32, name="self_collision"), ], target_scale=1.1541533470153809, - solver=replace(HandRetargeterOnlineConfig().solver, num_iters=30), + solver=_online_solver((6, 10, 14)), base_init_sample_range=(0.0, 0.0, 0.0), ) offline = HandRetargeterOfflineConfig(target_scale=1.2) diff --git a/src/robokit/helpers/hand_retargeting/presets/svh.py b/src/robokit/helpers/hand_retargeting/presets/svh.py index 69a8a91..c56174e 100644 --- a/src/robokit/helpers/hand_retargeting/presets/svh.py +++ b/src/robokit/helpers/hand_retargeting/presets/svh.py @@ -7,6 +7,7 @@ HandRetargeterOfflineConfig, HandRetargeterOnlineConfig, HandSpec, + _online_solver, ) from robokit.helpers.hand_retargeting.presets._common import ( FIVE_FINGERTIPS, @@ -96,7 +97,7 @@ ], target_scale=1.123853325843811, output_ema_alpha=0.8, - solver=replace(HandRetargeterOnlineConfig().solver, num_iters=30), + solver=_online_solver((6, 10, 14)), base_init_sample_range=(0.0, 0.0, 0.0), ) offline = HandRetargeterOfflineConfig(target_scale=1.2) diff --git a/src/robokit/helpers/hand_retargeting/presets/xhand.py b/src/robokit/helpers/hand_retargeting/presets/xhand.py index 89a74ce..5935b7b 100644 --- a/src/robokit/helpers/hand_retargeting/presets/xhand.py +++ b/src/robokit/helpers/hand_retargeting/presets/xhand.py @@ -7,6 +7,7 @@ HandRetargeterOfflineConfig, HandRetargeterOnlineConfig, HandSpec, + _online_solver, ) from robokit.helpers.hand_retargeting.presets._common import ( FIVE_FINGERTIPS, @@ -107,7 +108,7 @@ ], target_scale=1.1761616468429565, output_ema_alpha=0.4, - solver=replace(HandRetargeterOnlineConfig().solver, num_iters=30), + solver=_online_solver((6, 10, 14)), base_init_sample_range=(0.0, 0.0, 0.0), ) offline = HandRetargeterOfflineConfig(target_scale=1.12) diff --git a/src/robokit/helpers/humanoid_retargeting/alignment.py b/src/robokit/helpers/humanoid_retargeting/alignment.py index 741ce93..13ddc28 100644 --- a/src/robokit/helpers/humanoid_retargeting/alignment.py +++ b/src/robokit/helpers/humanoid_retargeting/alignment.py @@ -410,7 +410,7 @@ def ik_seed_pairs( """Seed each pair's joints from a single-frame IK of its SMPL-X pose, using a static preset tracking all links.""" from robokit.helpers.humanoid_retargeting.online import HumanoidRetargeterOnline from robokit.opt.lm_optimizer import LMOptimizerConfig - from robokit.opt.population_solver import PopulationSolverConfig + from robokit.opt.population_solver import PopulationSolverConfig, Stage position_weights, _ = config.task("target").weights_for(list(config.link_mapping)) tracking_weights = {rl: max(weight, 20.0) for rl, weight in zip(config.link_mapping, position_weights)} @@ -418,13 +418,10 @@ def ik_seed_pairs( config, velocity_clamp_scale=0.0, solver=PopulationSolverConfig( - num_iters=10 + 20 + 40, - select_at=[10, 10 + 20], - num_candidates=[64, 8, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=0.3), + stages=[ + Stage(10, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(20, 8, LMOptimizerConfig(lm_lambda=1.0)), + Stage(40, 1, LMOptimizerConfig(lm_lambda=0.3)), ], ), terms=deepcopy(config.terms), diff --git a/src/robokit/helpers/humanoid_retargeting/config.py b/src/robokit/helpers/humanoid_retargeting/config.py index c9ee5d4..7657c90 100644 --- a/src/robokit/helpers/humanoid_retargeting/config.py +++ b/src/robokit/helpers/humanoid_retargeting/config.py @@ -13,7 +13,7 @@ from robokit.opt.gd_optimizer import GDOptimizerConfig from robokit.opt.lbfgs_optimizer import LBFGSOptimizerConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import GaussianSamplerConfig, RobertsSamplerConfig from robokit.opt.var_values import VarKey from robokit.terms.dense.configuration_task import ConfigurationTask @@ -241,15 +241,12 @@ class TargetArrays: def _default_retargeting_solver() -> PopulationSolverConfig: return PopulationSolverConfig( - num_iters=10, - cuda_graph_mode="full", - select_at=[4, 10], - num_candidates=[16, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(4, 16, LMOptimizerConfig(lm_lambda=10.0)), + Stage(6, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], + cuda_graph_mode="full", ) @@ -471,14 +468,16 @@ def from_yaml(cls, yaml_path: Union[str, Path]) -> "HumanoidRetargeterOnlineConf ] if "solver" in data: settings = dict(data["solver"]) - # Existing asset YAML used one LM damping value per segment. - if "lm_lambda" in settings: - settings["optimizer"] = [ - {"type": "LMOptimizerConfig", "lm_lambda": float(value)} for value in settings.pop("lm_lambda") - ] - elif "optimizer" not in settings: - settings["optimizer"] = [ - {"type": "LMOptimizerConfig", "lm_lambda": 10.0} for _ in settings["num_candidates"] + if "stages" not in settings: # legacy YAML: segment ends, widths and one LM damping value per segment + ends = [*settings.pop("select_at", []), settings.pop("num_iters", 10)] + damping = settings.pop("lm_lambda", [10.0] * len(ends)) + settings["stages"] = [ + { + "iters": end - start, + "num_candidates": width, + "optimizer": {"type": "LMOptimizerConfig", "lm_lambda": float(value)}, + } + for start, end, width, value in zip([0, *ends], ends, settings.pop("num_candidates", [1]), damping) ] settings.setdefault("cuda_graph_mode", data.get("cuda_graph_mode", "full")) config_types = { @@ -491,24 +490,21 @@ def from_yaml(cls, yaml_path: Union[str, Path]) -> "HumanoidRetargeterOnlineConf GaussianSamplerConfig, ) } - for key in ("optimizer", "samplers"): - if key not in settings: + stages = settings["stages"] + restored = [] + for entry in [stage.get("optimizer") for stage in stages] + list(settings.get("samplers", [])): + if entry is None: + restored.append(None) continue - entries = settings[key] - many = isinstance(entries, (list, tuple)) - restored = [] - for entry in entries if many else (entries,): - if entry is None: - restored.append(None) - continue - options = dict(entry) - name = options.pop("type") - if name not in config_types: - raise ValueError(f"Unsupported online config type: {name}") - if name == "LBFGSOptimizerConfig" and "line_search_alphas" in options: - options["line_search_alphas"] = tuple(options["line_search_alphas"]) - restored.append(config_types[name](**{key: _yaml_enum(value) for key, value in options.items()})) - settings[key] = restored if many else restored[0] + options = dict(entry) + name = options.pop("type") + if name not in config_types: + raise ValueError(f"Unsupported online config type: {name}") + if name == "LBFGSOptimizerConfig" and "line_search_alphas" in options: + options["line_search_alphas"] = tuple(options["line_search_alphas"]) + restored.append(config_types[name](**{key: _yaml_enum(value) for key, value in options.items()})) + settings["stages"] = [Stage(**{**stage, "optimizer": c}) for stage, c in zip(stages, restored)] + settings["samplers"] = restored[len(stages) :] config.solver = PopulationSolverConfig(**settings) elif "cuda_graph_mode" in data: config.solver = replace(config.solver, cuda_graph_mode=data["cuda_graph_mode"]) @@ -524,28 +520,26 @@ def _weight_to_yaml(self, val: Union[float, int, Sequence[float], np.ndarray]) - def to_dict(self) -> dict: solver = asdict(self.solver) - for key, configs in (("optimizer", self.solver.optimizer), ("samplers", self.solver.samplers)): - many = isinstance(configs, (list, tuple)) - encoded = [] - for config in configs if many else (configs,): - if config is None: - encoded.append(None) - continue - if not is_dataclass(config) or type(config) not in ( - LMOptimizerConfig, - GDOptimizerConfig, - LBFGSOptimizerConfig, - RobertsSamplerConfig, - GaussianSamplerConfig, - ): - raise ValueError(f"Unsupported online config type: {type(config).__name__}") - options = {key: _yaml_enum(value) for key, value in asdict(config).items()} - if any(callable(value) for value in options.values()): - raise ValueError("Callable optimizer schedules cannot be serialized.") - encoded.append({"type": type(config).__name__, **options}) - solver[key] = encoded if many else encoded[0] - for key in ("sample_at", "select_at", "num_candidates"): - solver[key] = list(solver[key]) + stages = self.solver.stages + encoded = [] + for config in [stage.optimizer for stage in stages] + list(self.solver.samplers): + if config is None: + encoded.append(None) + continue + if not is_dataclass(config) or type(config) not in ( + LMOptimizerConfig, + GDOptimizerConfig, + LBFGSOptimizerConfig, + RobertsSamplerConfig, + GaussianSamplerConfig, + ): + raise ValueError(f"Unsupported online config type: {type(config).__name__}") + options = {key: _yaml_enum(value) for key, value in asdict(config).items()} + if any(callable(value) for value in options.values()): + raise ValueError("Callable optimizer schedules cannot be serialized.") + encoded.append({"type": type(config).__name__, **options}) + solver["stages"] = [{**stage, "optimizer": c} for stage, c in zip(solver["stages"], encoded)] + solver["samplers"] = encoded[len(stages) :] data: dict = {} if self.urdf_path is not None: data["urdf_path"] = self.urdf_path @@ -619,9 +613,7 @@ class HumanoidRetargeterOfflineConfig: default_factory=lambda: ( IKSolverConfig( enable_T_world_base=True, - solver=PopulationSolverConfig( - num_iters=6 + 3, select_at=[6], num_candidates=[4, 1], optimizer=LMOptimizerConfig(lm_lambda=1.5) - ), + solver=PopulationSolverConfig(stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)]), ) .add(PositionTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, weight=10.0)) .add(RotationTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, weight=5.0)) diff --git a/src/robokit/helpers/humanoid_retargeting/offline.py b/src/robokit/helpers/humanoid_retargeting/offline.py index f62b4fa..d4c352e 100644 --- a/src/robokit/helpers/humanoid_retargeting/offline.py +++ b/src/robokit/helpers/humanoid_retargeting/offline.py @@ -223,9 +223,7 @@ def solve( valid_lengths: Optional valid frame count for each padded batch element. human_heights: Optional human height in meters for each batch element. out: Optional caller-owned output with shape `(batch, frames, 7 + dofs)`. - target_overrides: Optional `(batch, frames, 7)` target tracks keyed by robot link. They move the - IK warm start and `TARGET_POSITIONS`; orientation templates read `TARGETS` (the mapped poses) - unless they read `OVERRIDDEN_TARGETS`. + target_overrides: Optional `(batch, frames, 7)` target tracks keyed by robot link; they move the IK warm start and `TARGET_POSITIONS`, while orientation templates read `TARGETS` (the mapped poses) unless they read `OVERRIDDEN_TARGETS`. Returns: `out` when provided; otherwise a reusable helper-owned buffer overwritten by the next call. diff --git a/src/robokit/helpers/humanoid_retargeting/presets/_interaction.py b/src/robokit/helpers/humanoid_retargeting/presets/_interaction.py index 4c9b93c..afeb96d 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/_interaction.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/_interaction.py @@ -6,7 +6,7 @@ from robokit.helpers.humanoid_retargeting.config import HumanoidContext, HumanoidRetargeterOnlineConfig, LinkMapping from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.interaction_mesh_task import InteractionMeshTask from robokit.terms.dense.position_limit import PositionLimit @@ -35,7 +35,7 @@ def _interaction_preset( ], velocity_clamp_scale=0.0, solver=PopulationSolverConfig( - num_iters=30, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=1.0), cuda_graph_mode="none" + stages=[Stage(30, optimizer=LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="none" ), terms=[ PositionLimit(weight=30.0, residual_mode="abs", frame=HumanoidContext.FRAME, name="position_limit"), diff --git a/src/robokit/helpers/humanoid_retargeting/presets/adam_lite.py b/src/robokit/helpers/humanoid_retargeting/presets/adam_lite.py index 8ca5eee..0e6aa69 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/adam_lite.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/adam_lite.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/bhl.py b/src/robokit/helpers/humanoid_retargeting/presets/bhl.py index a37b9e9..32279c7 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/bhl.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/bhl.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -50,10 +50,7 @@ 8.0, ], solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/g1.py b/src/robokit/helpers/humanoid_retargeting/presets/g1.py index 721c0a9..6608a8c 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/g1.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/g1.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -58,10 +58,7 @@ 12.0, ], solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/gr3.py b/src/robokit/helpers/humanoid_retargeting/presets/gr3.py index fe71e21..294e685 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/gr3.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/gr3.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -59,10 +59,7 @@ 8.0, ], solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/h1.py b/src/robokit/helpers/humanoid_retargeting/presets/h1.py index 4255221..4427024 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/h1.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/h1.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/h1_2.py b/src/robokit/helpers/humanoid_retargeting/presets/h1_2.py index 253e6c7..6d39c37 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/h1_2.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/h1_2.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -55,10 +55,7 @@ 12.0, ], solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/k1.py b/src/robokit/helpers/humanoid_retargeting/presets/k1.py index 44b3a00..5d83450 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/k1.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/k1.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/pm01.py b/src/robokit/helpers/humanoid_retargeting/presets/pm01.py index 12011f5..47d824c 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/pm01.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/pm01.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/t1.py b/src/robokit/helpers/humanoid_retargeting/presets/t1.py index 082e2d5..b0aedf9 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/t1.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/t1.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/talos.py b/src/robokit/helpers/humanoid_retargeting/presets/talos.py index f9c387a..ed10e92 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/talos.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/talos.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/tienkung.py b/src/robokit/helpers/humanoid_retargeting/presets/tienkung.py index dbeabae..0834da9 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/tienkung.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/tienkung.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/humanoid_retargeting/presets/toddy.py b/src/robokit/helpers/humanoid_retargeting/presets/toddy.py index 4bc3feb..095741e 100644 --- a/src/robokit/helpers/humanoid_retargeting/presets/toddy.py +++ b/src/robokit/helpers/humanoid_retargeting/presets/toddy.py @@ -9,7 +9,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit @@ -26,10 +26,7 @@ velocity_limit_dt=0.03333333, velocity_clamp_scale=0.8, solver=PopulationSolverConfig( - num_iters=6 + 3, - select_at=[6], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.5), + stages=[Stage(6, 4, LMOptimizerConfig(lm_lambda=1.5)), Stage(3, 1)], cuda_graph_mode="full", ), scale_table={ diff --git a/src/robokit/helpers/ik/config.py b/src/robokit/helpers/ik/config.py index 8f39b63..14928be 100644 --- a/src/robokit/helpers/ik/config.py +++ b/src/robokit/helpers/ik/config.py @@ -4,7 +4,7 @@ from typing import List, Optional, Sequence, Tuple from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.terms.task import Context, ResidualTask @@ -36,13 +36,10 @@ class IKContext(Context): def _default_ik_solver_config() -> PopulationSolverConfig: return PopulationSolverConfig( - num_iters=6 + 10, - select_at=[6, 6 + 10], - num_candidates=[64, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(6, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(10, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="full", ) @@ -68,8 +65,6 @@ class IKSolverConfig: """Active (1.0) or locked (0.0) base DOFs `[x, y, z, roll, pitch, yaw]`; locking needs `enable_T_world_base`.""" def __post_init__(self): - if not self.solver.num_candidates: - raise ValueError("solver.num_candidates must not be empty") if len(self.base_active_mask) != 6: raise ValueError(f"base_active_mask length {len(self.base_active_mask)} != 6") if any(m != 1.0 for m in self.base_active_mask) and not self.enable_T_world_base: diff --git a/src/robokit/helpers/ik/ik.py b/src/robokit/helpers/ik/ik.py index 7bcbc0f..d19863a 100644 --- a/src/robokit/helpers/ik/ik.py +++ b/src/robokit/helpers/ik/ik.py @@ -231,11 +231,7 @@ def solve( base_init_sample_range: Optional[Sequence[float]] = None, scene_indices: Optional[wp.array] = None, ) -> RobotState: - """Solve IK and return instance-major final-stage solutions shaped `(batch * num_solutions, dofs)`. - - Ranking options: - - `solver.rank_final=True`: sort solutions best first within each instance. - """ + """Solve IK and return instance-major final-stage solutions shaped `(batch * num_solutions, dofs)`; `solver.rank_final=True` sorts them best first within each instance.""" batch_size = self._validate_target(T_world_target) if not self._initialized: diff --git a/src/robokit/helpers/ik/presets.py b/src/robokit/helpers/ik/presets.py index 918c020..4e8d34a 100644 --- a/src/robokit/helpers/ik/presets.py +++ b/src/robokit/helpers/ik/presets.py @@ -2,7 +2,7 @@ from robokit.helpers.ik.config import IKContext, IKSolverConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.terms.dense.position_limit import PositionLimit from robokit.terms.dense.position_task import PositionTask @@ -27,12 +27,7 @@ single_candidate = ( IKSolverConfig( - solver=PopulationSolverConfig( - num_iters=30, - num_candidates=[1], - optimizer=LMOptimizerConfig(lm_lambda=1.0), - cuda_graph_mode="full", - ), + solver=PopulationSolverConfig(stages=[Stage(30, 1, LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="full"), ) .add(PositionTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, weight=20.0)) .add(RotationTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, weight=10.0)) diff --git a/src/robokit/helpers/motion_plan/__init__.py b/src/robokit/helpers/motion_plan/__init__.py index 3e4a9bf..1c2a4ec 100644 --- a/src/robokit/helpers/motion_plan/__init__.py +++ b/src/robokit/helpers/motion_plan/__init__.py @@ -5,6 +5,8 @@ MotionPlanContext, ) from robokit.helpers.motion_plan.motion_planner import ( + AttachedObject, + FixedRelativePose, MotionPlanner, MotionPlannerConfig, MotionPlanResult, @@ -18,6 +20,8 @@ __all__ = [ + "AttachedObject", + "FixedRelativePose", "RetimeConfig", "MotionPlanResult", "MotionPlanEvaluator", diff --git a/src/robokit/helpers/motion_plan/gradient_trajectory_optimizer.py b/src/robokit/helpers/motion_plan/gradient_trajectory_optimizer.py index ae07588..43418af 100644 --- a/src/robokit/helpers/motion_plan/gradient_trajectory_optimizer.py +++ b/src/robokit/helpers/motion_plan/gradient_trajectory_optimizer.py @@ -12,8 +12,8 @@ from robokit.helpers.motion_plan.plan_goal import MotionPlanContext, PlanGoal from robokit.helpers.motion_plan.trajectory_retimer import RetimeConfig, TimingVar from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig -from robokit.opt.var_values import VarKey, VarValues +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage +from robokit.opt.var_values import VarKey, VarValues, VectorVar from robokit.robo.robot import Robot from robokit.robo.robot_state import RobotState from robokit.terms.composite_task import CompositeTask @@ -53,11 +53,31 @@ def _active_dof_mask_kernel( dof_mask: wp.array1d(dtype=wp.float32), locked: wp.array1d(dtype=wp.int32), config_locked: wp.array1d(dtype=wp.int32), + dof_links: wp.array1d(dtype=wp.int32), # each dof's target links as bits, which `locked` holds by bit + segment_free: wp.array1d(dtype=wp.int32), # each segment: 1 optimizes its step, whose column follows the frames' + segments: int, out: wp.array1d(dtype=wp.float32), ): frame, dof = wp.tid() # pyright: ignore[reportAssignmentType] - held = locked[frame] != 0 or config_locked[frame] != 0 + held = (locked[frame] & dof_links[dof]) != 0 or config_locked[frame] != 0 out[frame * dof_mask.shape[0] + dof] = wp.where(held, 0.0, dof_mask[dof]) + if dof == 0 and frame < segments: + out[locked.shape[0] * dof_mask.shape[0] + frame] = float(segment_free[frame]) + + +@wp.kernel +def _log_step_kernel(dt: wp.array1d(dtype=wp.float32), log_step: wp.array2d(dtype=wp.float32)): + row, segment = wp.tid() # pyright: ignore[reportAssignmentType] + log_step[row, segment] = wp.log(dt[row // (log_step.shape[0] // dt.shape[0])]) + + +def _dof_links(robot: Robot, target_link_indices: Sequence[int], base_dofs: int, device: str) -> wp.array: + """Each tangent dof's target links as bits: those its joint moves; all for the base and joints moving none.""" + spec = robot.spec + moves = spec.link_ancestor_joints_mask[target_link_indices] @ (spec.joints_to_actuated_mapping != 0) # bool + bits = (moves.astype(np.int64) << np.arange(len(target_link_indices))[:, None]).sum(0) + links = np.r_[np.full(base_dofs, -1), np.where(bits > 0, bits, -1)].astype(np.int32) + return wp.array(links, dtype=wp.int32, device=device) # --- task construction ----------------------------------------------------- @@ -166,18 +186,19 @@ class GradientTrajectoryOptimizerConfig: """Rank the candidates when there are several; several tasks combine.""" solver: PopulationSolverConfig = field( default_factory=lambda: PopulationSolverConfig( - num_iters=50, optimizer=LMOptimizerConfig(lm_lambda=0.5, lambda_min=1e-6, lambda_max=1e6, rho_min=1e-4) + stages=[ + Stage(50, optimizer=LMOptimizerConfig(lm_lambda=0.5, lambda_min=1e-6, lambda_max=1e6, rho_min=1e-4)) + ] ) ) - """Iterations, candidate widths, beam selections and the update rule; the planner sets graph capture.""" + """The stages: iterations, candidate widths and update rules; the planner sets graph capture.""" method: Literal["gradient"] = "gradient" """The stage's method, which the planner dispatches on.""" clamp_to_limits: bool = False """Clamp every line-search trial to the joint position limits.""" lock_frames: Tuple[int, ...] = () - """Frames held where they start, e.g. `(0,)` the start or `(0, -1)` both ends; a locked last frame pursues no - pose goal. Smoothness still spans them.""" + """Frames held where they start, e.g. `(0,)` the start or `(0, -1)` both ends; a locked last frame pursues no pose goal. Smoothness still spans them.""" def add(self, term: ResidualTask, *, name: Optional[str] = None) -> "GradientTrajectoryOptimizerConfig": """Append a task, optionally assigning its input role. @@ -224,8 +245,7 @@ class GradientTrajectoryOptimizer: Lifecycle: 1. `__init__` stores configuration and creates the active-DOF mask. - 2. `warmup(var)` ties the stage to the population `var` (its `robot` trajectories and their `timing`) - and builds the tasks and the solver once. The first `solve` calls it when needed. + 2. `warmup(var)` ties the stage to the population `var` (its `robot` trajectories and their `timing`) and builds the tasks and the solver once; the first `solve` calls it when needed. 3. `solve(var, goal)` optimizes the population in place and returns each query's best trajectory. """ @@ -242,7 +262,10 @@ def __init__( use_cuda_graph: bool = True, acceleration_limit: float = 15.0, jerk_limit: float = 500.0, + sphere_mask: Optional[wp.array] = None, retime: Optional[RetimeConfig] = None, + segments: int = 0, + duration_weight: float = 0.0, device: Optional[wp_device_type] = None, ): device = str(resolve_device(device)) @@ -252,6 +275,7 @@ def __init__( self._base_dofs = 6 if enable_T_world_base else 0 self.num_frames = num_frames self._scene = scene + self._sphere_mask = sphere_mask # each frame's checked spheres, for the score self.device = device self.num_dofs = robot.num_actuated_joints self.num_candidates = config.solver.num_candidates[0] @@ -269,15 +293,19 @@ def __init__( locked = sorted({frame % num_frames for frame in config.lock_frames}) # a locked end frame never moves: a pose cost there is a constant with a masked gradient self._goal_frames = [] if num_frames - 1 in locked else [-1] - self._active_dof_mask_wp = wp.empty(num_frames * width, dtype=wp.float32, device=device) + self.segments, self._duration_weight = segments, duration_weight # VarKey.SEGMENT_STEP columns; >0 optimizes + self.frame_segment = wp.zeros(num_frames, dtype=wp.int32, device=device) # each frame interval's segment + self.segment_free = wp.zeros(num_frames, dtype=wp.int32, device=device) # each segment: 1 optimizes it + self._active_dof_mask_wp = wp.empty(num_frames * width + segments, dtype=wp.float32, device=device) self._joint_mask = np.ones(self.num_dofs, dtype=np.float32) # the goal's, last applied to the mask above self._dof_mask_wp = wp.ones(width, dtype=wp.float32, device=device) # the base, then the joints config_locked = np.zeros(num_frames, np.int32) config_locked[locked] = 1 self._config_locked_wp = wp.array(config_locked, dtype=wp.int32, device=device) + self._dof_links = _dof_links(robot, self.target_link_indices, self._base_dofs, device) self.locked_frames = wp.zeros( num_frames, dtype=wp.int32, device=device - ) # 1 holds a frame; may change on device + ) # each frame's held target links as bits, -1 all; may change on device self.set_lock_frames(()) self._solver: Optional[PopulationSolver] = None self._var: Optional[VarValues] = None @@ -285,7 +313,7 @@ def __init__( def set_lock_frames(self, lock_frames: Sequence[int]): """Hold these frames, besides `config.lock_frames`, where they start; never while capturing.""" locked = np.zeros(self.num_frames, np.int32) - locked[[f % self.num_frames for f in lock_frames]] = 1 + locked[[f % self.num_frames for f in lock_frames]] = -1 self.locked_frames.assign(locked) self._apply_active_dof_mask() @@ -293,7 +321,8 @@ def _apply_active_dof_mask(self): wp.launch( _active_dof_mask_kernel, dim=(self.num_frames, self._dof_mask_wp.shape[0]), - inputs=[self._dof_mask_wp, self.locked_frames, self._config_locked_wp], + inputs=[self._dof_mask_wp, self.locked_frames, self._config_locked_wp, self._dof_links] + + [self.segment_free, self.segments], outputs=[self._active_dof_mask_wp], device=self.device, ) @@ -318,6 +347,11 @@ def best(self) -> Tuple[RobotState, wp.array]: solver = cast(PopulationSolver, self._solver) return cast(RobotState, solver._best_var.get(VarKey.ROBOT)), solver.best_costs + @property + def best_steps(self) -> wp.array: + """Each query's best segment log steps after the last solve.""" + return cast(VectorVar, cast(PopulationSolver, self._solver)._best_var.get(VarKey.SEGMENT_STEP)).x + def _build_problem(self, var: VarValues): """Build batch-shaped tasks on the population `var`.""" config = self.config @@ -364,9 +398,13 @@ def _build_problem(self, var: VarValues): cast(PopulationSolver, self_ref()._solver).candidate_scores ), ctx.RETIME: self._retime, + ctx.SPHERE_MASK: self._sphere_mask, } self._reads_goal_distance = ctx.GOAL_DISTANCE in set().union(*(t.needs() for t in config.terms if t.active)) self._tasks = _build_terms(config.terms, var, context) + timed = [t for t in self._tasks if isinstance(t, TrajectoryLimitTask) and t.dt is timing.dt] + for index, task in enumerate(timed if self._duration_weight > 0.0 else ()): # bounds at the optimized steps + task.timing = (self.frame_segment, self.segments, self._duration_weight if index == 0 else 0.0) # every task that reports penetration makes a candidate infeasible through the score self._collision_tasks = [task for task in self._tasks if isinstance(task, TrajectoryCollisionTask)] context[ctx.COLLISION_TASKS] = self._collision_tasks @@ -455,5 +493,8 @@ def solve(self, var: VarValues, goal: PlanGoal) -> Tuple[RobotState, wp.array]: """ self.warmup(var) self._set_inputs(goal) + if self._duration_weight > 0.0: # every segment starts at its query's step + dt, steps = cast(TimingVar, var.get(VarKey.TIMING)).dt, cast(VectorVar, var.get(VarKey.SEGMENT_STEP)).x + wp.launch(_log_step_kernel, steps.shape, [dt], [steps], device=self.device) cast(PopulationSolver, self._solver).solve(var) return self.best diff --git a/src/robokit/helpers/motion_plan/motion_plan_score_task.py b/src/robokit/helpers/motion_plan/motion_plan_score_task.py index d3fc89c..7e5a4aa 100644 --- a/src/robokit/helpers/motion_plan/motion_plan_score_task.py +++ b/src/robokit/helpers/motion_plan/motion_plan_score_task.py @@ -21,6 +21,24 @@ # --- kernel ---------------------------------------------------------------- +@wp.kernel +def _path_sphere_mask_kernel( + frame_mask: wp.array2d(dtype=wp.int32), # each plan frame's checked spheres + steps: int, # path samples per frame interval + scene_spheres: wp.array1d(dtype=wp.int32), + path_mask: wp.array2d(dtype=wp.int32), + scene_mask: wp.array3d(dtype=wp.bool), +): + """Each path sample's checked spheres: those both plan frames about it check (the scene's: but at the start).""" + p, k = wp.tid() # pyright: ignore[reportAssignmentType] + a = p // steps + b = wp.min(a + wp.where(p % steps == 0, 0, 1), frame_mask.shape[0] - 1) + path_mask[p, k] = frame_mask[a, k] * frame_mask[b, k] + if k < scene_mask.shape[2]: + sphere = scene_spheres[k] + scene_mask[0, p, k] = p > 0 and frame_mask[a, sphere] * frame_mask[b, sphere] != 0 + + @wp.kernel def _accumulate_row_max_kernel(values: wp.array2d(dtype=wp.float32), out: wp.array1d(dtype=wp.float32)): row, col = wp.tid() # pyright: ignore[reportAssignmentType] @@ -180,6 +198,14 @@ def resolve(self, var_values: VarValues, context: Mapping[Context, Any]): movable = np.flatnonzero(robot.spec.collision_spheres_link_indices > 0) # base spheres never move after_start = np.ones((path_frames, len(movable)), dtype=bool) after_start[0] = False # as the frame check: the given start is not the plan's to fix + # the stages' per-frame checked spheres, if any, and each path sample's: `_path_sphere_mask_kernel`'s inputs + frame_mask, self._sphere_masks = context.get(ctx.SPHERE_MASK), None + if frame_mask is not None: + path_mask = wp.ones((path_frames, len(robot.spec.collision_sphere_radii)), wp.int32, device) + after_start = wp.array(after_start[None], wp.bool, device=device) + steps = (path_frames - 1) // (num_frames - 1) + spheres = wp.array(movable, wp.int32, device=device) + self._sphere_masks = (frame_mask, steps, spheres, path_mask, after_start) self.interpolated_collision_tasks = tuple( [ TrajectoryCollisionTask( @@ -206,6 +232,8 @@ def resolve(self, var_values: VarValues, context: Mapping[Context, Any]): if self.self_collision else None ) + if self.self_collision_task is not None and self._sphere_masks is not None: + self.self_collision_task.sphere_mask = self._sphere_masks[3] retime = context.get(ctx.RETIME) # (velocity limits, step, acceleration and jerk limits, hold frames): rank by the retimed plan self.retimed_timing = ( @@ -259,6 +287,9 @@ def compute_weighted_residual( out_residual = wp.empty((state.q.shape[0], 1), dtype=wp.float32, device=state.q.device) row_offset = 0 self._penetrations.zero_() + if self._sphere_masks is not None: + dim = self._sphere_masks[3].shape + wp.launch(_path_sphere_mask_kernel, dim=dim, inputs=self._sphere_masks, device=state.q.device) for task in self.collision_tasks: task._query_collision_distances(var_values) task.accumulate_max_penetration(self._penetrations) diff --git a/src/robokit/helpers/motion_plan/motion_planner.py b/src/robokit/helpers/motion_plan/motion_planner.py index f299fec..56c9614 100644 --- a/src/robokit/helpers/motion_plan/motion_planner.py +++ b/src/robokit/helpers/motion_plan/motion_planner.py @@ -24,6 +24,7 @@ import warp as wp from robokit.geom import WarpScene +from robokit.geom.covering_spheres import _compute_covering_spheres from robokit.helpers.ik import IKContext, IKSolver, IKSolverConfig from robokit.helpers.motion_plan.evaluator import MotionPlanEvaluator, MotionPlanMetrics from robokit.helpers.motion_plan.gradient_trajectory_optimizer import ( @@ -38,6 +39,7 @@ _expand_ik_goal_candidates_kernel, _frame_flags_kernel, _frame_need_kernel, + _held_radii_kernel, _hold_kernel, _min_distance_kernel, _motion_time_kernel, @@ -66,22 +68,26 @@ ) from robokit.lie.se3 import se3_from_matrix, se3_to_matrix from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig -from robokit.opt.var_values import VarKey, VarValues +from robokit.opt.population_solver import PopulationSolverConfig, Stage +from robokit.opt.var_values import VarKey, VarValues, VectorVar from robokit.robo.robot import Robot +from robokit.robo.robot_spec import JointType from robokit.robo.robot_state import RobotState from robokit.terms.composite_task import CompositeTask from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask from robokit.terms.dense.position_limit import PositionLimit from robokit.terms.dense.position_task import PositionTask +from robokit.terms.dense.relative_frame_task import RelativeFrameTask from robokit.terms.dense.rotation_task import RotationTask from robokit.terms.dense.scene_collision_task import SceneCollisionTask from robokit.terms.sparse.trajectory_collision_task import TrajectoryCollisionTask +from robokit.terms.sparse.trajectory_self_collision_task import TrajectorySelfCollisionTask +from robokit.terms.trajectory_task import TrajectoryTask from robokit.utils import warp_utils from robokit.utils.warp_utils import resolve_device, wp_device_type, wp_vec7 from robokit.xform.numpy.rotation_conversions import normalize_quaternion -from robokit.xform.numpy.transforms import tf_mat_to_pose7 +from robokit.xform.numpy.transforms import pose7_to_tf_mat, tf_mat_to_pose7 if TYPE_CHECKING: @@ -107,7 +113,11 @@ class OnlineState: @dataclass class MotionPlanResult(Generic[ArrayT]): - """Planner output with offline timing or online state; waypoint_indices locates fixed anchors when supplied.""" + """Planner output with offline timing or online state. + + Offline: `q_traj` `(batch, frames, dofs)` with `frames = num_timesteps + 1`, `motion_time` `(batch,)` (s) and + `waypoint_indices` each waypoint's frame in `q_traj` (one per waypoint, 0 first, the same for every row). + """ q_traj: ArrayT T_world_base_traj: Optional[ArrayT] = None @@ -117,13 +127,14 @@ class MotionPlanResult(Generic[ArrayT]): segment_fixed_duration: Optional[Tuple[Optional[float], ...]] = ( None # seconds of fixed segments, None where retimed ) + segment_duration: Optional[ArrayT] = None # each plan's segment seconds `(batch, segments)`, when optimized def interpolate(self, dt: float, speed_scale: float = 1.0) -> ArrayT: """Joint trajectories sampled every `dt` (s) or slightly less across `motion_time`. Each segment between waypoints spreads `ceil(its time / dt)` steps evenly over its frames, so every waypoint is a sample; a plan then holds its last frame, so a batch shares one length. A segment with a - fixed `segment_fixed_duration` takes that time; the others run at the plan's retimed step. + fixed `segment_fixed_duration` takes that time; the others run at the plan's retimed step or `segment_duration`. Args: dt: Control step (s). @@ -155,28 +166,31 @@ def interpolate(self, dt: float, speed_scale: float = 1.0) -> ArrayT: frame_step = (cast(Any, self.motion_time) - float(durations[fixed].sum())) / speed_scale / moving_frames q, step = convert(q_traj), convert(frame_step) step_max = float(frame_step.max()) # the longest plan takes the most samples - samples = int(np.ceil(np.where(fixed, durations / dt, np.diff(anchors) * (step_max / dt))).sum()) + 1 + plans = np.tile(durations, (q.shape[0], 1)) # each plan's; optimized ones one plan at a time + if self.segment_duration is not None: + plans = np.where(fixed, durations, np.asarray(cast(Any, self.segment_duration).tolist()) / speed_scale) + samples = int(np.ceil(np.where(plans > 0, plans / dt, np.diff(anchors) * (step_max / dt))).sum(1).max()) + 1 out = wp.empty((q.shape[0], samples, q.shape[2]), dtype=wp.float32, device=q.device) - wp.launch( - _interpolate_trajectory_kernel, - dim=out.shape, - inputs=[ - q, - step, - dt, - wp.array(anchors, dtype=wp.int32, device=q.device), - wp.array(durations, dtype=wp.float32, device=q.device), - ], - outputs=[out], - device=q.device, - ) + for rows in [slice(None)] if self.segment_duration is None else [slice(b, b + 1) for b in range(q.shape[0])]: + wp.launch( + _interpolate_trajectory_kernel, + dim=out[rows].shape, + inputs=[ + q[rows], + step[rows], + dt, + wp.array(anchors, dtype=wp.int32, device=q.device), + wp.array(plans[rows][0], dtype=wp.float32, device=q.device), + ], + outputs=[out[rows]], + device=q.device, + ) return cast(ArrayT, out.numpy() if is_numpy else wp.to_torch(out)) # --- configuration --------------------------------------------------------- def build_goal_score(goal_tolerance: Tuple[float, float] = (0.005, 0.05)) -> CompositeTask: - """Goal IK's score, ranking goals within `goal_tolerance` (m, rad) of the target, the joint limits - and collision-free first, then the nearest the rest configuration; the planner keeps it for several goals.""" + """Goal IK's score, ranking goals within `goal_tolerance` (m, rad) of the target, the joint limits and collision-free first, then the nearest the rest configuration; the planner keeps it for several goals.""" return CompositeTask( [ FrameTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, residual_mode="distance"), @@ -202,13 +216,10 @@ def build_default_motion_plan_ik_config() -> IKSolverConfig: return ( IKSolverConfig( solver=PopulationSolverConfig( - num_iters=6 + 10, - select_at=[6, 6 + 10], - num_candidates=[64, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(6, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(10, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1, LMOptimizerConfig(lm_lambda=1.0)), ], cuda_graph_mode="full", ) @@ -229,6 +240,34 @@ def build_default_motion_plan_ik_config() -> IKSolverConfig: ) +@dataclass +class AttachedObject: + """A box (half extents `size`) or z-axis cylinder (radius, half height) that `link` carries, posed in its frame by + 4x4 `T_link_object`: checked against the world and the robot, but `link`'s body, the bodies one joint from it (the + wrist, the fingers) and `collision_ignored_links`, over `segments` (indices; None: all). `link` must be rigid with + a target link. + """ + + link: str + shape: Literal["box", "cylinder"] + size: Tuple[float, ...] + T_link_object: Optional[np.ndarray] = None + collision_ignored_links: Tuple[str, ...] = () + segments: Optional[Tuple[int, ...]] = None + + +@dataclass +class FixedRelativePose: + """`link_b`'s pose in `link_a`'s frame, held over `segments` (indices; None: all) by the gradient stages at its + value at waypoint `at_waypoint`, else at each segment's first waypoint (e.g. two hands carrying one object). + """ + + link_a: str + link_b: str + at_waypoint: Optional[int] = None + segments: Optional[Tuple[int, ...]] = None + + @dataclass class MotionPlannerConfig: """Configuration for offline or online motion planning.""" @@ -238,10 +277,19 @@ class MotionPlannerConfig: """Steps per plan; a plan has one more frame.""" dt: float = 0.25 """Planning step (s).""" + max_attached_spheres: int = 0 + """Collision spheres reserved on each target link for `attached_objects`, which every solve places there.""" + max_fixed_relative_poses: int = 0 + """Link pairs reserved for `fixed_relative_poses`, which every solve sets.""" + fixed_relative_pose_weight: Tuple[float, float] = (3000.0, 1000.0) + """Position and rotation weights of `fixed_relative_poses`, per m and per rad of drift.""" acceleration_limit: float = 15.0 """Joint acceleration limit (rad/s²): the stages' bounds and ranking, MPPI rollouts, retimes and resplits.""" jerk_limit: float = 500.0 """Joint jerk limit (rad/s³): the stages' bounds and ranking, retimes and resplits.""" + duration_weight: float = 0.0 + """>0: the last stage also optimizes each free segment's duration, from the query's step, at this cost per second + of plan time; its derivative bounds use the optimized durations, which the returned retime only lengthens.""" # --- goal --- goal_ik: IKSolverConfig = field(default_factory=build_default_motion_plan_ik_config) @@ -277,11 +325,10 @@ class MotionPlannerConfig: retime: Optional[RetimeConfig] = None """Retime of the returned plan; None keeps the planning step.""" resplit_waypoints: bool = True - """Resplit a waypoint plan's frames by the time each part needs, so a short segment takes fewer: its straight lines' - before the solve, and its paths' after the first stage, which the later gradient stages smooth; False keeps the - even split.""" + """Resplit a waypoint plan's frames by the time each part needs, so a short segment takes fewer: its straight lines' before the solve, and its paths' after the first stage, which the later gradient stages smooth; False keeps the even split.""" cuda_graph: Literal["none", "stages", "solve"] = "stages" - """CUDA graphs: none, each stage's and goal IK's solve, or the whole NumPy solve with its device-side retries.""" + """CUDA graphs: none, each stage's and goal IK's solve, or the whole NumPy solve with its device-side retries; a + capture makes a planner's first solve take seconds longer.""" class WaypointLayout(NamedTuple): @@ -295,6 +342,8 @@ class WaypointLayout(NamedTuple): check_collision: Optional[wp.array] # each segment: 1 checks world collision lock_goal: int # 1 holds the goal frame: a joint goal's, or a locked last segment's resplit: Optional[Tuple[wp.array, wp.array]] # with a resplit: the fixed segments, and the new frames + # each segment's checked spheres and relative poses' reference waypoints, and each waypoint's named links as bits + segment_items: Optional[Tuple[wp.array, wp.array, wp.array]] = None # None: start and goal only, never split # --- planner --------------------------------------------------------------- @@ -302,14 +351,10 @@ class MotionPlanner: """Batched motion planning with goal IK, trajectory optimization stages, and retry. Lifecycle: - 1. `__init__` copies configuration and constructs goal IK, the optimizer stages, and their - retiming. + 1. `__init__` copies configuration and constructs goal IK, the optimizer stages, and their retiming. 2. `warmup(batch_size)` fixes the batch size and allocates all batch-shaped state. - 3. `solve_offline(...)`, which `solve_offline_numpy` and `solve_offline_torch` wrap, places the - waypoints, builds candidates, solves and retries trajectories, then retimes them with the last stage's - `retime` and computes `motion_time`. - 4. `solve_online(...)` runs a fresh gradient solve with executed-history smoothing, or - updates the retained MPPI action distribution. + 3. `solve_offline(...)`, which `solve_offline_numpy` and `solve_offline_torch` wrap, places the waypoints, builds candidates, solves and retries trajectories, then retimes them with the last stage's `retime` and computes `motion_time`. + 4. `solve_online(...)` runs a fresh gradient solve with executed-history smoothing, or updates the retained MPPI action distribution. Args: config: Planner configuration. @@ -329,13 +374,49 @@ def __init__( scene: Optional[WarpScene] = None, device: Optional[wp_device_type] = None, ): - self.robot = robot # copies the planner mutates; completed preset terms hold device arrays, so they are shared, not deep-copied self.config = copy.copy(config) self.config.stages = tuple(dataclasses.replace(c, terms=list(c.terms)) for c in config.stages) self.device = resolve_device(device) links = [target_links] if isinstance(target_links, (str, int)) else list(target_links) self.target_link_indices = [robot.link_names.index(x) if isinstance(x, str) else int(x) for x in links] + # the robot with `max_attached_spheres` spheres on a link welded to each target link, after its own links and + # spheres; off (radius -1e9) but where a solve places an attached object + slots, spec, targets = config.max_attached_spheres, robot.spec, self.target_link_indices + self._num_robot_links, self._num_robot_spheres = spec.num_links, len(spec.collision_sphere_radii) + if slots: + count = len(targets) + spec = dataclasses.replace( + spec, + link_names=[*robot.link_names, *(f"{robot.link_names[t]} attached" for t in targets)], + link_parent_joint_indices=np.r_[ + spec.link_parent_joint_indices, spec.link_parent_joint_indices[targets] + ], + link_masses=np.r_[spec.link_masses, np.zeros(count)], + link_local_com_positions=np.r_[spec.link_local_com_positions, np.zeros((count, 3))], + local_collision_sphere_centers=np.r_[spec.local_collision_sphere_centers, np.zeros((count * slots, 3))], + collision_sphere_radii=np.r_[spec.collision_sphere_radii, np.full(count * slots, -1.0e9)], + collision_spheres_link_indices=np.r_[ + spec.collision_spheres_link_indices, np.repeat(spec.num_links + np.arange(count), slots) + ].astype(np.int32), + ) + robot = Robot(spec) + self.robot = robot + # the gradient stages hold `max_fixed_relative_poses` link pairs' relative poses at each frame's reference + poses = config.max_fixed_relative_poses + self._reference_frames = wp.full((config.num_timesteps + 1, max(1, poses)), -1, wp.int32, self.device) + self._relative: Optional[RelativeFrameTask] = None + if poses: + weights = config.fixed_relative_pose_weight + relative = RelativeFrameTask(robot, [(0, 0)] * poses, self._reference_frames, *weights) + self._relative, term = relative, TrajectoryTask(relative, config.num_timesteps + 1, name="relative") + term.init_buffers(self.device) + self.config.stages = tuple( + c if c.method == "mppi" else dataclasses.replace(c, terms=[*c.terms, term]) for c in self.config.stages + ) + # each frame's checked spheres: all but attached objects outside their segments; the score's path checks too + num_spheres = max(1, len(robot.spec.collision_sphere_radii)) + self._sphere_active = wp.ones((config.num_timesteps + 1, num_spheres), wp.int32, self.device) # a floating base plans its pose along with the joints, from goal IK that places it self._floating = self.config.goal_ik.enable_T_world_base @@ -368,29 +449,45 @@ def __init__( or any(c.method == "mppi" for c in self.config.stages[1:]) ): raise ValueError("stage_retries needs stage_dt_scale > 0, stage_retry_iters >= 1 and gradient stages.") + # each candidate's segment log steps, which the last stage optimizes: a segment spans at least two steps + self._segments = self.config.num_timesteps // 2 if self.config.duration_weight > 0.0 else 0 + if self._segments and any(c.method == "mppi" for c in self.config.stages): + raise ValueError("duration_weight needs gradient stages.") def build( config: Union[GradientTrajectoryOptimizerConfig, MppiTrajectoryOptimizerConfig], index: int ) -> Union[GradientTrajectoryOptimizer, MppiTrajectoryOptimizer]: args = (config, robot, self.target_link_indices, self._num_frames, self.config.dt) + timing = dict(segments=self._segments, duration_weight=self.config.duration_weight) if index == last else {} options = dict( enable_T_world_base=self._floating, scene=self._scene, use_cuda_graph=self.config.cuda_graph != "none", acceleration_limit=self.config.acceleration_limit, + sphere_mask=self._sphere_active if slots else None, device=self.device, ) if config.method == "mppi": return MppiTrajectoryOptimizer(*args, **options) return GradientTrajectoryOptimizer( - *args, **options, jerk_limit=self.config.jerk_limit, retime=stage_retimes[index] + *args, **options, jerk_limit=self.config.jerk_limit, retime=stage_retimes[index], **timing ) self._optimizers = [build(config, index) for index, config in enumerate(self.config.stages)] self._retry_optimizers = { # the last stage's retry: no later stage reads the population it rewrites last: build( dataclasses.replace( - config, solver=dataclasses.replace(config.solver, num_iters=self.config.stage_retry_iters) + config, + solver=dataclasses.replace( # the last solver stage runs what the earlier ones leave of the retry + config.solver, + stages=[ + *config.solver.stages[:-1], + dataclasses.replace( + config.solver.stages[-1], + iters=self.config.stage_retry_iters - sum(s.iters for s in config.solver.stages[:-1]), + ), + ], + ), ), last, ) @@ -419,12 +516,20 @@ def build( ik_config = dataclasses.replace( goal_ik, score_terms=[self._goal_score] if total > 1 else [], - solver=dataclasses.replace(goal_ik.solver, num_candidates=candidates, rank_final=total > 1), + solver=dataclasses.replace( + goal_ik.solver, + stages=[dataclasses.replace(s, num_candidates=c) for s, c in zip(goal_ik.solver.stages, candidates)], + rank_final=total > 1, + ), ) # the goal IK, public for IK alone: the planner's scene, and with several answers per query, best first self.ik = IKSolver( ik_config, robot=robot, target_links=self.target_link_indices, device=self.device, scene=self._scene ) + # the robot's sphere radii and a copy: each IK solve of a plan sets the attached objects its waypoint does not + # hold not to collide (radius -1e9) while it runs + radii = robot.spec.get_tensors(str(self.device)).collision_sphere_radii + self._radii = (radii, wp.clone(radii)) if slots else None self._ik_goal_q: Optional[wp.array] = None self._ik_goal_state: Optional[RobotState] = None self._evaluator: Optional[MotionPlanEvaluator] = None @@ -488,10 +593,16 @@ def trajectories(rows: int) -> RobotState: # joints, and base poses when the ba optimizers = [self._trajectory_optimizer] else: self._timing = TimingVar.full(batch_size, self.config.dt, self.device) - self._population = VarValues({VarKey.ROBOT: trajectories(n_total), VarKey.TIMING: self._timing}) + population = {VarKey.ROBOT: trajectories(n_total), VarKey.TIMING: self._timing} + self._population = self._last_population = VarValues(population) + if self._segments: # the last stage's: each candidate's segment log steps + steps = wp.zeros((n_total, self._segments), dtype=wp.float32, device=self.device) + steps = VectorVar(steps, unit=3.0, max_step=0.05) # moves 3x a joint's unit, at most 5% of a step + self._last_population = VarValues({**population, VarKey.SEGMENT_STEP: steps}) + self._final_log_step = wp.zeros((batch_size, self._segments), dtype=wp.float32, device=self.device) optimizers = [*self._optimizers, *self._retry_optimizers.values()] for optimizer in optimizers: - optimizer.warmup(self._population) + optimizer.warmup(self._last_population if optimizer.segments else self._population) self._fastest_step = wp.empty(batch_size, dtype=wp.float32, device=self.device) self._stage_condition = wp.zeros(1, dtype=wp.int32, device=self.device) self._retry_condition_stage = wp.zeros(1, dtype=wp.int32, device=self.device) @@ -516,6 +627,17 @@ def trajectories(rows: int) -> RobotState: # joints, and base poses when the ba spec = self.robot.spec self._world_collision = bool(self._scene.geoms) and spec.has_collision_spheres num_spheres = len(spec.collision_sphere_radii) + # the self-collision checks of the stages and their scores, which a solve tells the attached objects' radii and + # ignored pairs; the stages' also which spheres each frame checks + stage_tasks = [t for o in optimizers for t in o._tasks if isinstance(t, TrajectorySelfCollisionTask)] + scores = [s for o in optimizers for s in o._solver.score_terms if s is not None] + scores = [getattr(t, "self_collision_task", None) for s in scores for t in getattr(s, "tasks", [s])] + tasks = list(dict.fromkeys([*stage_tasks, *(t for t in scores if t is not None)])) + self._self_collision_tasks = tasks if self.config.max_attached_spheres else [] + self._pair_active = wp.ones(max([1, *(t.num_pairs for t in tasks)]), wp.int32, self.device) + for task in self._self_collision_tasks: + task.pair_mask = self._pair_active + task.sphere_mask = self._sphere_active if task in stage_tasks else task.sphere_mask self._eff_radii = wp.from_numpy( np.where(spec.collision_spheres_link_indices > 0, spec.collision_sphere_radii, -1.0e9).astype(np.float32), dtype=wp.float32, @@ -550,10 +672,7 @@ def distance_bufs(num_configs: int) -> Tuple[RobotState, wp.array, wp.array]: # self._batch_size = batch_size def set_active_joint_mask(self, joint_mask: Sequence[float]): - """Set which actuated joints IK and trajectory optimization may change. - - Before the first solve it also limits the trajectory collision Jacobians to the active joints, which later masks - must stay within. + """Set which actuated joints IK and trajectory optimization may change; before the first solve it also limits the trajectory collision Jacobians to the active joints, which later masks must stay within. Args: joint_mask: One value per actuated joint; zero pins the joint. @@ -583,12 +702,14 @@ def _solve_waypoint_ik( seed_q: Optional[wp.array], start_T_world_base: Optional[wp.array], scene_indices: wp.array, + named: Sequence[int], + spheres: Optional[np.ndarray] = None, ) -> Tuple[wp.array, list]: - """Each waypoint's joints: a pose's best goal IK, started and resting at its neighbors' blend, else `seed_q`. + """Each waypoint's joints: a pose's best goal IK, started and resting at its neighbors' blend, else `seed_q`; + the target links a pose leaves out (`named`: its links as bits, -1 all) keep their poses at that blend. Returns: - The `(batch, waypoints, dofs)` joints, and each later pose's index, next joint waypoint, IK answers and - valid count, from which every guess picks its own. + The `(batch, waypoints, dofs)` joints, and each later pose's index, next joint waypoint, IK answers and valid count, from which every guess picks its own. """ batch = waypoints[0].shape[0] joints: List[Optional[wp.array]] = [None if w.dtype == wp_vec7 else w for w in waypoints] @@ -615,8 +736,18 @@ def _solve_waypoint_ik( rest = ( None if reference is None else self.robot.state(q=wp.clone(reference), T_world_base=start_T_world_base) ) + target = waypoint.reshape((batch, len(self.target_link_indices))) + if named[index] != -1 and rest is None: # nothing to keep the links it leaves out at + raise ValueError("A start pose naming some target links needs seed_q or a later joint waypoint.") + if named[index] != -1: + kept = (named[index] >> np.arange(len(self.target_link_indices)) & 1)[None, :, None] == 0 + T_world_link = self.robot.forward_kinematics(rest).T_world_link.numpy()[:, self.target_link_indices] + target = wp.array(np.where(kept, T_world_link, target.numpy()), dtype=wp_vec7, device=self.device) + if self._radii is not None and spheres is not None: # the spheres both segments at the waypoint check + held = spheres[index - 1] * spheres[min(index, len(spheres) - 1)] + self._radii[0].assign(np.where(held != 0, self.robot.spec.collision_sphere_radii, -1.0e9)) state = self.ik.solve( - T_world_target=waypoint.reshape((batch, len(self.target_link_indices))), + T_world_target=target, init_state=rest, rest_state=rest, scene_indices=scene_indices, @@ -634,6 +765,8 @@ def _solve_waypoint_ik( anchors = wp.empty((batch, len(joints), self.robot.num_actuated_joints), dtype=wp.float32, device=self.device) for index, q in enumerate(joints): wp.copy(anchors[:, index], q) + if self._radii is not None: + wp.copy(*self._radii) return anchors, picks def _build_target_q_per_candidate( @@ -842,11 +975,7 @@ def _optimize( waypoint_layout: Optional[WaypointLayout] = None, round_index: int = 0, ) -> Tuple[RobotState, wp.array]: - """Run the optimizer stages in order on the candidate population; each query's best plan and score. - - A waypoint layout holds its waypoints and checks collision on its first split; with a resplit, the stages - after the first plan on frames spread by the time each part of the first stage's paths needs. - """ + """Run the optimizer stages in order on the candidate population, giving each query's best plan and score; a waypoint layout holds its waypoints and checks collision on its first split; with a resplit, the stages after the first plan on frames spread by the time each part of the first stage's paths needs.""" if waypoint_layout is not None: # every round starts on the first split self._apply_split(self._frame_masks, waypoint_layout.frames, waypoint_layout) if self.config.stages[0].method == "mppi": @@ -866,11 +995,10 @@ def _optimize( wp.copy(population.T_world_base, traj_init.T_world_base) population.invalidate() self._timing.fill(dt) # every round starts at its step - state, scores = self._optimizers[0].solve(var, goal) + state, scores = self._optimizers[0].solve(self._last_population if self._optimizers[0].segments else var, goal) for index in range(1, len(self._optimizers)): previous, stage = self._optimizers[index - 1], self._optimizers[index] - # resplit by the time the first stage's best paths need, and resample every candidate onto the new frames; - # retry rounds reuse the first round's split, so every plan shares one + # resplit by the time the first stage's best paths need, and resample every candidate onto the new frames; retry rounds reuse the first round's split, so every plan shares one resplit = waypoint_layout.resplit if waypoint_layout is not None else None if index == 1 and resplit is not None and self.config.stages[1].method != "mppi": (fixed, new_frames), (resampled_q, _, _, at, resampled_base) = resplit, self._resplit_bufs @@ -907,9 +1035,9 @@ def _optimize( minimum_dt = self.config.stage_retime.minimum_dt self._timing.scale(self._fastest_step, self.config.stage_dt_scale, minimum_dt) previous_scores = previous.best[1] - state, scores = stage.solve(var, goal) + state, scores = stage.solve(self._last_population if stage.segments else var, goal) if index in self._retry_optimizers: # retries only follow a stage that planned some query - self._retry_optimizers[index].prepare(var, goal) # a conditional branch cannot set a solver up + self._retry_optimizers[index].prepare(self._last_population, goal) # a branch cannot set a solver up self._stage_condition.zero_() wp.launch( _score_condition_kernel, @@ -940,19 +1068,20 @@ def _resplit_frames(self, path: wp.array, frames: wp.array, fixed: wp.array, new def _apply_split(self, optimizers: Iterable, frames: wp.array, waypoint_layout: WaypointLayout): """Hold a split's waypoints on `frames`, and check collision where its segments ask, in each optimizer.""" locked, check, lock_goal = waypoint_layout.locked, waypoint_layout.check_collision, waypoint_layout.lock_goal - for optimizer in optimizers: + for optimizer in optimizers: # attached objects and relative poses follow their segments too wp.launch( _frame_flags_kernel, dim=self._num_frames, - inputs=[frames, locked, check, lock_goal], - outputs=[optimizer.locked_frames, self._checked_frames], + inputs=[frames, locked, check, lock_goal, *cast(tuple, waypoint_layout.segment_items)], + outputs=[optimizer.locked_frames, self._checked_frames, self._sphere_active, self._reference_frames] + + [getattr(optimizer, "frame_segment", None)], # a gradient stage's device=self.device, ) for task, base in self._frame_masks[optimizer]: wp.launch( _collision_mask_kernel, dim=base.shape, - inputs=[base, self._checked_frames], + inputs=[base, self._checked_frames, self._sphere_active, task._sphere_indices_wp], outputs=[task.frame_sphere_mask], device=self.device, ) @@ -963,7 +1092,7 @@ def _retry_stage(self, index: int, goal: PlanGoal, attempt: int = 0): if attempt > 0: scale = self.config.stage_dt_scale * self.config.stage_retry_dt_growth**attempt self._timing.scale(self._fastest_step, scale, self.config.stage_retime.minimum_dt) - retry.solve(self._population, goal) + retry.solve(self._last_population, goal) (state, scores), (retry_state, retry_scores) = stage.best, retry.best self._retry_condition_stage.zero_() wp.launch( # each query keeps its better plan; the condition flags any still infeasible @@ -976,8 +1105,9 @@ def _retry_stage(self, index: int, goal: PlanGoal, attempt: int = 0): self._start_distance, scores, self._retry_condition_stage, + retry.best_steps if self._segments else None, ], - outputs=[state.q, state.T_world_base], + outputs=[state.q, state.T_world_base, stage.best_steps if self._segments else None], device=self.device, ) else: @@ -1082,6 +1212,8 @@ def _solve_offline_attempt( ) state, scores = self._optimize(goal, self._traj_init, self.config.dt, waypoint_layout, round_index) if retries == 0: + if self._segments: + wp.copy(self._final_log_step, self._optimizers[-1].best_steps) wp.copy(self._final_state.q, state.q) if self._floating: wp.copy(self._final_state.T_world_base, state.T_world_base) @@ -1097,8 +1229,10 @@ def _solve_offline_attempt( self._start_distance, self._retry_best_score, self._retry_condition, + self._optimizers[-1].best_steps if self._segments else None, self._final_state.q, self._final_state.T_world_base, + self._final_log_step if self._segments else None, ], device=self.device, ) @@ -1118,7 +1252,7 @@ def _solve_offline_attempt( def solve_offline( self, - waypoints: Sequence[wp.array], + waypoints: Sequence[Union[wp.array, Dict[str, wp.array]]], *, start_T_world_base: Optional[wp.array] = None, seed_q: Optional[wp.array] = None, @@ -1126,42 +1260,74 @@ def solve_offline( segment_check_collision: Optional[Sequence[bool]] = None, segment_fixed_duration: Optional[Sequence[Optional[float]]] = None, segment_locked: Optional[Sequence[bool]] = None, + attached_objects: Optional[Sequence[AttachedObject]] = None, + fixed_relative_poses: Optional[Sequence[FixedRelativePose]] = None, ) -> MotionPlanResult[wp.array]: """Plan batched Warp trajectories through waypoints, start first and goal last; the NumPy and Torch APIs wrap it. Lifecycle: 1. Parse segments: each segment's world collision flag, fixed duration and lock. - 2. Solve waypoint IK: each pose but a final goal by goal IK, resting at its neighbors' blend. + 2. Solve waypoint IK: each pose but a final goal by goal IK (scene collision, no self collision), + resting at its neighbors' blend. 3. Create split: each segment's frames by its duration, else evenly, then the locked frames and collision. - 4. Solve: `_solve_offline_attempt` with retries, one CUDA graph under `cuda_graph="solve"` but for - durations. It builds each guess's goal by goal IK, its later poses' answers nearest its neighbors' - blend, and straight lines through its waypoints, on frames resplit by the time each line needs; after - the first stage, several segments resplit their frames again. + 4. Solve: `_solve_offline_attempt` with retries, one CUDA graph under `cuda_graph="solve"` but for durations; it builds each guess's goal by goal IK, its later poses' answers nearest its neighbors' blend, and straight lines through its waypoints, on frames resplit by the time each line needs; after the first stage, several segments resplit their frames again. 5. Retime: every plan under the last stage's retime, its fixed segments held still, and its motion time. Args: waypoints: Ordered list of at least two: joint arrays `(batch, dofs)` in `robot.spec.actuated_joint_names` - order, or `wp_vec7` arrays `(batch,)` or `(batch, target links)` posing the target links. + order, `wp_vec7` arrays `(batch,)` or `(batch, target links)` posing the target links, or dicts of + target link names to `wp_vec7` `(batch,)` posing some of them (other keys are ignored). A link + a dict leaves out is free at its frame, so each link reaches its own waypoints in turn: the first + guess keeps it at its pose of the waypoint before (blended toward any later joint waypoint; a start + pose's at `seed_q` or the next joint waypoint, one needed), and the stages move it from there only as + their costs pull. Every link passes each waypoint at the same instant, and the goal names all. An + inner waypoint holds the links it names at its joints or IK answer, contact included. start_T_world_base: A floating base's start poses, `wp_vec7` `(batch,)`; such plans take a start and a goal. seed_q: Optional IK seed: the goal IK's initialization, or the rest of a pose waypoint before any joint one. scene_indices: Optional scene index per batch row; defaults to zero. - segment_check_collision: One flag per segment (waypoint `i` to `i + 1`); False drops world collision there, - and from the checks of anchors only such segments touch, e.g. a grasp. Defaults to all True. + segment_check_collision: One flag per segment (waypoint `i` to `i + 1`); False drops world collision there + (self collision stays), and from the checks of anchors only such segments touch, e.g. a contact. + Defaults to all True. Every `segment_*` and `waypoint_*` list applies to all batch rows alike. segment_fixed_duration: Seconds per segment, or None to let the planner time it. A duration gives the segment `round(duration / dt)` frames (at least two) in the solve, keeps them through the resplit and is its time in `interpolate`; None segments share the rest of `num_timesteps`, which the durations must fit. - segment_locked: One flag per segment; True keeps its frames on the straight line between its waypoints. + segment_locked: One flag per segment; True keeps its frames on the straight joint-space line between its + waypoints (the tool's path between them is not straight), whatever it passes through, and holds the + links both its waypoints name. + attached_objects: Objects the robot carries, on the spheres `max_attached_spheres` reserves on the target + link each one's `link` is rigid with: checked by world and self collision over their segments (an + inner waypoint: those both its segments carry), in the stages, their scores and waypoint and goal IK. + fixed_relative_poses: Link pairs whose relative pose the gradient stages hold over their segments, at most + `max_fixed_relative_poses`. Returns: `q_traj` `(batch, frames, dofs)`, `motion_time` `(batch,)` and a floating base's `T_world_base_traj`, borrowed buffers the next solve overwrites; `motion_time` counts fixed segments at their duration. - `waypoint_indices` locates every fixed anchor, and `segment_fixed_duration` repeats the fixed durations. - Fewer queries than the warmed batch are padded with the last, and only their rows return. + `waypoint_indices` locates every fixed anchor, `segment_fixed_duration` repeats the fixed durations, and + `segment_duration` holds each plan's segment times when optimized. + The first solve (or `warmup`) fixes the batch, goal IK's included: fewer queries are padded with the + last and only their rows return; more raise `ValueError("Batch size mismatch")`. """ if len(waypoints) < 2: raise ValueError("solve_offline needs a start and a goal; use `planner.ik` for IK alone.") + num_segments, waypoints = len(waypoints) - 1, list(waypoints) robot, device, dofs = self.robot, self.device, self.robot.num_actuated_joints + names = [robot.link_names[i] for i in self.target_link_indices] + named = [] # each waypoint's target links as bits, -1 all; a dict's poses become one per target link + for index, w in enumerate(waypoints): + keys = [k for k in w if k in names] if isinstance(w, dict) else names + if not keys: + raise ValueError(f"A waypoint dict must name target links among {names}.") + named.append(-1 if len(keys) == len(names) else sum(1 << names.index(k) for k in keys)) + if isinstance(w, dict) and len(names) > 1: # a link it leaves out takes a filler pose + waypoints[index] = wp.empty((w[keys[0]].shape[0], len(names)), dtype=wp_vec7, device=device) + for k, name in enumerate(names): + wp.copy(waypoints[index][:, k], w.get(name, w[keys[0]])) + elif isinstance(w, dict): + waypoints[index] = w[names[0]] + if named[-1] != -1: + raise ValueError("The goal must name every target link.") queries = waypoints[0].shape[0] batch = max(queries, self._batch_size or 0) if batch > queries: @@ -1174,17 +1340,105 @@ def solve_offline( self.warmup(batch) # --- parse segments --- - num_segments = len(waypoints) - 1 check_collision = [True] * num_segments if segment_check_collision is None else list(segment_check_collision) durations = [None] * num_segments if segment_fixed_duration is None else list(segment_fixed_duration) locked = [False] * num_segments if segment_locked is None else list(segment_locked) fixed = np.array([d is not None for d in durations], dtype=bool) goal_pose = waypoints[-1].dtype == wp_vec7 # its IK runs per guess, in the solve + # --- place attached objects and relative poses --- + # each segment's checked spheres: the robot's, and the reserved ones that an object it carries takes, on the + # target link its `link` is rigid with, in that link's frame + objects, poses, spec = list(attached_objects or ()), list(fixed_relative_poses or ()), robot.spec + slots, first, tools = self.config.max_attached_spheres, self._num_robot_spheres, self.target_link_indices + if objects and not slots or len(poses) > self.config.max_fixed_relative_poses: + raise ValueError( + "attached_objects need max_attached_spheres; fixed_relative_poses max_fixed_relative_poses." + ) + + def segments_of(x: Union[AttachedObject, FixedRelativePose]) -> List[int]: + return list(range(num_segments)) if x.segments is None else [k % num_segments for k in x.segments] + + def body_of(link: int) -> int: # the joint that moves it + joint = int(spec.link_parent_joint_indices[link]) + while joint >= 0 and spec.joint_types[joint] == JointType.FIXED: + joint = int(spec.parent_joint_indices[joint]) + return joint + + spheres = np.ones((num_segments, len(spec.collision_sphere_radii)), np.int32) + if slots: + spheres[:, first:] = 0 + spec.local_collision_sphere_centers[first:], spec.collision_sphere_radii[first:] = 0.0, -1.0e9 # off + ignored = np.zeros((spheres.shape[1], spec.num_links), bool) # each sphere's ignored links + T_world_link = pose7_to_tf_mat( + robot.forward_kinematics_numpy(np.zeros((1, dofs), np.float32), device=str(device))[0] + ) + used = [0] * len(tools) + for obj in objects: + holder = robot.link_names.index(obj.link) + k = next((k for k, t in enumerate(tools) if body_of(t) == body_of(holder)), None) + if k is None: + raise ValueError(f"An attached object's link {obj.link} must be rigid with a target link.") + T_link_object = np.eye(4) if obj.T_link_object is None else np.asarray(obj.T_link_object) + T_target_object = np.linalg.inv(T_world_link[tools[k]]) @ T_world_link[holder] @ T_link_object + cover = _compute_covering_spheres(obj.shape, obj.size, T_target_object) + rows = first + k * slots + used[k] + np.arange(len(cover)) + used[k] += len(cover) + if used[k] > slots: + raise ValueError(f"{names[k]} carries {used[k]} spheres, over max_attached_spheres={slots}.") + spec.local_collision_sphere_centers[rows], spec.collision_sphere_radii[rows] = cover[:, :3], cover[:, 3] + spheres[np.ix_(segments_of(obj), rows)] = 1 + skip = [robot.link_names.index(x) for x in obj.collision_ignored_links] + skip += [self._num_robot_links + tools.index(x) for x in skip if x in tools] # and its spheres + ignored[np.ix_(rows, skip)] = True + # every copy of the spheres: the device's, goal IK's, the seeds' and the self-collision checks', and each + # reserved link's bounding sphere + tensors, radii = spec.get_tensors(str(device)), spec.collision_sphere_radii.astype(np.float32) + tensors.local_collision_sphere_centers.assign(spec.local_collision_sphere_centers.astype(np.float32)) + for array in (tensors.collision_sphere_radii, cast(tuple, self._radii)[1]): # and goal IK's copy + array.assign(radii) + self._eff_radii[first:].assign(radii[first:]) + centers, r = ( + spec.local_collision_sphere_centers[first:].reshape(-1, slots, 3), + radii[first:].reshape(-1, slots), + ) + on = r > -1.0e8 + mean = (centers * on[..., None]).sum(1) / np.maximum(on.sum(1), 1)[:, None] + bound = np.where(on, np.linalg.norm(centers - mean[:, None], axis=-1) + r, -1.0e9).max(1) + tensors.local_link_bounding_sphere_centers[self._num_robot_links :].assign(mean.astype(np.float32)) + tensors.link_bounding_sphere_radii[self._num_robot_links :].assign(bound.astype(np.float32)) + for task in self._self_collision_tasks: + task._radii_np[first:] = radii[first:] + if getattr(task, "_radii_wp", None) is not None: + task._radii_wp.assign(task._radii_np) + link = spec.collision_spheres_link_indices + for task in self._self_collision_tasks[:1]: # all check the same pairs + i, j = task._active_pairs_np.T + self._pair_active[: len(i)].assign((~(ignored[i, link[j]] | ignored[j, link[i]])).astype(np.int32)) + self._evaluator = None # built again with these spheres + if self._relative is not None: + indices = [(robot.link_names.index(p.link_a), robot.link_names.index(p.link_b)) for p in poses] + indices += [(0, 0)] * (self._reference_frames.shape[1] - len(poses)) + self._relative.link_pairs.assign(np.array(indices, np.int32)) + references = [ # each segment's relative poses' reference waypoint + 1, 0 off + [ + (k if p.at_waypoint is None else p.at_waypoint % len(waypoints)) + 1 if k in segments_of(p) else 0 + for p in poses + ] + + [0] * (self._reference_frames.shape[1] - len(poses)) + for k in range(num_segments) + ] + segment_items = (spheres, references, named) + # --- solve waypoint IK --- # a pose goal is left to the solver's goal IK, one answer per guess waypoint_q, picks = self._solve_waypoint_ik( - waypoints[: num_segments if goal_pose else num_segments + 1], seed_q, start_T_world_base, scene_indices + waypoints[: num_segments + 1 - goal_pose], + seed_q, + start_T_world_base, + scene_indices, + named, + spheres, ) # --- create split --- @@ -1208,13 +1462,22 @@ def solve_offline( known = [1, *(w.dtype == wp_vec7 for w in waypoints[1:-1]), 1] # waypoints with a base pose # frames resplit by the time each part needs: the straight lines', then the first stage's paths' resplit = num_segments > 1 and self.config.resplit_waypoints and not fixed.all() + free = np.r_[~fixed, np.zeros(self._num_frames - num_segments, bool)].astype(np.int32) # the last stage's steps + for optimizer in [self._optimizers[-1], *self._retry_optimizers.values()] if self._segments else (): + optimizer.segment_free.assign(free) def solve(start_q, base, T_world_target, target_q, seed_q, scene_indices, waypoint_q, rest_q, *layout_inputs): start_state = robot.state(q=start_q, T_world_base=base) + new_frames, frames_wp, locked_wp, known_wp, fixed_wp, check_wp, *items_wp = layout_inputs[:9] + if self._radii is not None: # goal IK checks the spheres the last segment checks + held_radii = (self._radii[1], items_wp[0], num_segments - 1) + wp.launch(_held_radii_kernel, self._radii[0].shape, held_radii, [self._radii[0]], device=self.device) targets = self._build_target_q_per_candidate( T_world_target, target_q, scene_indices, start_state, seed_q=seed_q, rest_q=rest_q ) - new_frames, frames_wp, locked_wp, known_wp, fixed_wp, check_wp, *answers = layout_inputs + if self._radii is not None: + wp.copy(*self._radii) + answers = layout_inputs[9:] waypoint_layout = WaypointLayout( q=waypoint_q, frames=frames_wp, @@ -1224,6 +1487,7 @@ def solve(start_q, base, T_world_target, target_q, seed_q, scene_indices, waypoi check_collision=check_wp, lock_goal=int(not goal_pose or locked[-1]), resplit=(fixed_wp, new_frames) if resplit else None, + segment_items=tuple(items_wp), ) # retries draw new detours, and pose goals new goal IK candidates, over the full batch retries = self.config.max_retries if self._retry_enabled else 0 @@ -1249,10 +1513,11 @@ def solve(start_q, base, T_world_target, target_q, seed_q, scene_indices, waypoi scene_indices, waypoint_q, wp.clone(waypoint_q[:, num_segments - 1]), # the goal IK's rest - # the final frames (input 8), then the first split, its locks, base poses, durations and collision checks + # the final frames (input 8), then the first split, its locks, base poses, durations, collision checks, + # checked spheres, relative pairs and named links *( wp.array(x, dtype=wp.int32, device=device) - for x in (frames, frames, locked, known, fixed, check_collision) + for x in (frames, frames, locked, known, fixed, check_collision, *segment_items) ), *(answer for p in picks for answer in p[2:]), ) @@ -1304,6 +1569,20 @@ def solve(start_q, base, T_world_target, target_q, seed_q, scene_indices, waypoi outputs=[self._motion_time], device=device, ) + segment_duration = None + if self._segments: # each free segment's optimized time, stretched to the retime of it alone, the rest held + free_segments, held_q = np.flatnonzero(~fixed), wp.empty_like(q) + times = np.exp(self._final_log_step.numpy()[:, :num_segments]) * np.diff(frames) + for segment in free_segments if self._retimers[-1].config is not None else (): # one: the retime above + if len(free_segments) > 1: + held = wp.array(np.arange(num_segments) != segment, dtype=wp.int32, device=device) + wp.launch(_hold_kernel, q.shape, [self._final_state.q, new_frames, held], [held_q], device=device) + self._retimers[-1].retime(held_q, self._final_timing) + needed = self._final_timing.dt.numpy() * (frames[segment + 1] - frames[segment]) + times[:, segment] = np.maximum(times[:, segment], needed) + times = np.where(fixed, [d or 0.0 for d in durations], times).astype(np.float32) + segment_duration = wp.array(times, dtype=wp.float32, device=device) + wp.copy(self._motion_time, wp.array(times.sum(1), dtype=wp.float32, device=device)) return MotionPlanResult( # pyright: ignore[reportReturnType] # slices are arrays, not indexed arrays q_traj=self._final_state.q[:queries], @@ -1311,6 +1590,7 @@ def solve(start_q, base, T_world_target, target_q, seed_q, scene_indices, waypoi motion_time=self._motion_time[:queries], waypoint_indices=frames, segment_fixed_duration=tuple(durations) if fixed.any() else None, + segment_duration=None if segment_duration is None else segment_duration[:queries], ) def solve_offline_numpy( @@ -1323,12 +1603,14 @@ def solve_offline_numpy( segment_check_collision: Optional[Sequence[bool]] = None, segment_fixed_duration: Optional[Sequence[Optional[float]]] = None, segment_locked: Optional[Sequence[bool]] = None, + attached_objects: Optional[Sequence[AttachedObject]] = None, + fixed_relative_poses: Optional[Sequence[FixedRelativePose]] = None, ) -> MotionPlanResult[np.ndarray]: """NumPy wrapper for `solve_offline`: a pose waypoint is a dict of target links to 4x4 or - `[x, y, z, qw, qx, qy, qz]` poses, unbatched values broadcast across queries, and the result holds owned copies. + `[x, y, z, qw, qx, qy, qz]` poses, unbatched values broadcast across queries, and the result holds owned + copies. """ device = self.device - names = [self.robot.link_names[i] for i in self.target_link_indices] def joints(q: np.ndarray) -> np.ndarray: return np.atleast_2d(np.asarray(q, dtype=np.float32)) @@ -1349,20 +1631,16 @@ def pose7(T: np.ndarray) -> np.ndarray: # a 4x4 matrix or a 7-vector, batched o def array(value: np.ndarray, dtype=wp.float32) -> wp.array: # an unbatched value broadcasts across queries return wp.from_numpy(np.broadcast_to(value, (batch, *value.shape[1:])).copy(), dtype=dtype, device=device) - def waypoint(w: Union[np.ndarray, Dict[str, np.ndarray]]) -> wp.array: - if not isinstance(w, dict): - return array(w) - T = w[names[0]] if len(names) == 1 else np.stack([np.broadcast_to(w[k], (batch, 7)) for k in names], 1) - return array(T, wp_vec7) - result = self.solve_offline( - [waypoint(w) for w in values], + [{k: array(v, wp_vec7) for k, v in w.items()} if isinstance(w, dict) else array(w) for w in values], start_T_world_base=None if base is None else array(base, wp_vec7), seed_q=None if seed_q is None else array(seed_q), scene_indices=array(scene_indices.astype(np.int32), wp.int32), segment_check_collision=segment_check_collision, segment_fixed_duration=segment_fixed_duration, segment_locked=segment_locked, + attached_objects=attached_objects, + fixed_relative_poses=fixed_relative_poses, ) return MotionPlanResult( q_traj=cast(wp.array, result.q_traj).numpy().copy(), @@ -1370,6 +1648,7 @@ def waypoint(w: Union[np.ndarray, Dict[str, np.ndarray]]) -> wp.array: motion_time=cast(wp.array, result.motion_time).numpy().copy(), waypoint_indices=result.waypoint_indices, segment_fixed_duration=result.segment_fixed_duration, + segment_duration=None if result.segment_duration is None else result.segment_duration.numpy().copy(), ) def solve_offline_torch( @@ -1382,13 +1661,12 @@ def solve_offline_torch( segment_check_collision: Optional[Sequence[bool]] = None, segment_fixed_duration: Optional[Sequence[Optional[float]]] = None, segment_locked: Optional[Sequence[bool]] = None, + attached_objects: Optional[Sequence[AttachedObject]] = None, + fixed_relative_poses: Optional[Sequence[FixedRelativePose]] = None, ) -> MotionPlanResult["torch.Tensor"]: """Torch wrapper for `solve_offline`, as `solve_offline_numpy` with 4x4 pose matrices; plans without waypoint IK stay on device. """ - import torch - - names = [self.robot.link_names[i] for i in self.target_link_indices] batched = [(w, 2) for w in (*waypoints, seed_q) if w is not None and not isinstance(w, dict)] batched += [(T, 3) for w in waypoints if isinstance(w, dict) for T in w.values()] batched += [(x, ndim) for x, ndim in ((start_T_world_base, 3), (scene_indices, 1)) if x is not None] @@ -1401,20 +1679,19 @@ def array(value: "torch.Tensor", dtype, ndim: int) -> wp.array: return se3_from_matrix(wp.from_torch(value.contiguous(), dtype=wp.mat44)) return wp.from_torch(value.contiguous(), dtype=dtype) - def waypoint(w: Union["torch.Tensor", Dict[str, "torch.Tensor"]]) -> wp.array: - if not isinstance(w, dict): - return array(w, wp.float32, 2) - T = w[names[0]] if len(names) == 1 else torch.stack([w[k] for k in names], -3) - return array(T, wp.mat44, 3 if len(names) == 1 else 4) - result = self.solve_offline( - [waypoint(w) for w in waypoints], + [ + {k: array(T, wp.mat44, 3) for k, T in w.items()} if isinstance(w, dict) else array(w, wp.float32, 2) + for w in waypoints + ], start_T_world_base=None if start_T_world_base is None else array(start_T_world_base, wp.mat44, 3), seed_q=None if seed_q is None else array(seed_q, wp.float32, 2), scene_indices=None if scene_indices is None else array(scene_indices.int(), wp.int32, 1), segment_check_collision=segment_check_collision, segment_fixed_duration=segment_fixed_duration, segment_locked=segment_locked, + attached_objects=attached_objects, + fixed_relative_poses=fixed_relative_poses, ) return MotionPlanResult( q_traj=wp.to_torch(cast(wp.array, result.q_traj)).clone(), @@ -1424,6 +1701,7 @@ def waypoint(w: Union["torch.Tensor", Dict[str, "torch.Tensor"]]) -> wp.array: motion_time=wp.to_torch(cast(wp.array, result.motion_time)).clone(), waypoint_indices=result.waypoint_indices, segment_fixed_duration=result.segment_fixed_duration, + segment_duration=None if result.segment_duration is None else wp.to_torch(result.segment_duration).clone(), ) # --- online planning --- diff --git a/src/robokit/helpers/motion_plan/motion_planner_kernels.py b/src/robokit/helpers/motion_plan/motion_planner_kernels.py index 366054c..5186b1a 100644 --- a/src/robokit/helpers/motion_plan/motion_planner_kernels.py +++ b/src/robokit/helpers/motion_plan/motion_planner_kernels.py @@ -401,33 +401,63 @@ def _frame_flags_kernel( locked: wp.array1d(dtype=wp.int32), # each segment: 1 holds its frames check: wp.array1d(dtype=wp.int32), # each segment: 1 checks world collision lock_goal: int, - held: wp.array1d(dtype=wp.int32), + spheres: wp.array2d(dtype=wp.int32), # each segment: 1 checks each sphere + pairs: wp.array2d(dtype=wp.int32), # each segment: each link pair's reference waypoint + 1, 0 off + named: wp.array1d(dtype=wp.int32), # each waypoint's target links as bits, -1 all + held: wp.array1d(dtype=wp.int32), # each frame's held target links as bits checked: wp.array1d(dtype=wp.int32), + sphere_active: wp.array2d(dtype=wp.int32), + reference_frames: wp.array2d(dtype=wp.int32), + frame_segment: wp.array1d(dtype=wp.int32), # or empty: the segment of each frame's interval to the next ): - """Each frame of a split: held (a waypoint but a free goal, or inside a locked segment), and collision-checked.""" + """Each frame of a split: its held links (a waypoint's named, all at a held goal, inside a locked segment those + both its waypoints name), collision-checked, its checked spheres (at an inner waypoint, those both segments + check) and its pairs' reference frame.""" frame = wp.tid() last = frames.shape[0] - 1 segment = int(0) while segment < last - 1 and frames[segment + 1] < frame: segment += 1 + if frame_segment.shape[0] > 0: + frame_segment[frame] = wp.where(frame < frames[segment + 1] or segment == last - 1, segment, segment + 1) hold = int(0) for k in range(last): if frames[k] == frame: - hold = 1 - if (frame == frames[last] and lock_goal != 0) or ( - locked[segment] != 0 and frame > frames[segment] and frame < frames[segment + 1] - ): - hold = 1 - held[frame] = hold + hold = named[k] + if locked[segment] != 0 and frame > frames[segment] and frame < frames[segment + 1]: + hold = named[segment] & named[segment + 1] + held[frame] = wp.where(frame == frames[last] and lock_goal != 0, -1, hold) checked[frame] = wp.where(frame == 0, 1, check[segment]) + inner = frame == frames[segment + 1] and segment < last - 1 + for k in range(spheres.shape[1]): + sphere_active[frame, k] = spheres[segment, k] * wp.where(inner, spheres[wp.min(segment + 1, last - 1), k], 1) + for k in range(pairs.shape[1]): + reference_frames[frame, k] = wp.where(pairs[segment, k] != 0, frames[wp.max(pairs[segment, k] - 1, 0)], -1) + + +@wp.kernel +def _held_radii_kernel( + radii: wp.array1d(dtype=wp.float32), + spheres: wp.array2d(dtype=wp.int32), # each segment: 1 checks each sphere + segment: int, + out: wp.array1d(dtype=wp.float32), +): + """The radii of the spheres `segment` checks, -1e9 (never colliding) for the others.""" + k = wp.tid() + out[k] = wp.where(spheres[segment, k] != 0, radii[k], -1.0e9) @wp.kernel def _collision_mask_kernel( - base: wp.array3d(dtype=wp.bool), checked: wp.array1d(dtype=wp.int32), out: wp.array3d(dtype=wp.bool) + base: wp.array3d(dtype=wp.bool), + checked: wp.array1d(dtype=wp.int32), + sphere_active: wp.array2d(dtype=wp.int32), + sphere_indices: wp.array1d(dtype=wp.int32), + out: wp.array3d(dtype=wp.bool), ): row, frame, sphere = wp.tid() # pyright: ignore[reportAssignmentType] - out[row, frame, sphere] = base[row, frame, sphere] and checked[frame] != 0 + active = sphere_active[frame, sphere_indices[sphere]] != 0 + out[row, frame, sphere] = base[row, frame, sphere] and checked[frame] != 0 and active # --------------------------------------------------------------------------- @@ -451,8 +481,10 @@ def _set_best_retry_result_kernel( start_distance: wp.array1d(dtype=wp.float32), best_score: wp.array1d(dtype=wp.float32), condition: wp.array1d(dtype=wp.int32), + steps: wp.array2d(dtype=wp.float32), # or None: each query's segment log steps final_q: wp.array3d(dtype=wp.float32), final_base: wp.array2d(dtype=wp_vec7), + final_steps: wp.array2d(dtype=wp.float32), ): batch = wp.tid() if scores[batch] < best_score[batch]: @@ -461,6 +493,8 @@ def _set_best_retry_result_kernel( final_base[batch, frame] = base[batch, frame] for dof in range(q.shape[2]): final_q[batch, frame, dof] = q[batch, frame, dof] + for segment in range(final_steps.shape[1]): + final_steps[batch, segment] = steps[batch, segment] # Retry infeasible plans (score ≥1e6), except a colliding start that retries cannot fix. if best_score[batch] >= 1.0e6 and start_distance[batch] >= 0.0: wp.atomic_max(condition, 0, 1) diff --git a/src/robokit/helpers/motion_plan/mppi_trajectory_optimizer.py b/src/robokit/helpers/motion_plan/mppi_trajectory_optimizer.py index b8a9b2e..d4ba5d4 100644 --- a/src/robokit/helpers/motion_plan/mppi_trajectory_optimizer.py +++ b/src/robokit/helpers/motion_plan/mppi_trajectory_optimizer.py @@ -3,6 +3,11 @@ # pyright: reportGeneralTypeIssues=false # pyright: reportIndexIssue=false # pyright: reportOperatorIssue=false +"""MPPI trajectory optimization. + +MPPI: https://arxiv.org/abs/1509.01149. +""" + import dataclasses import weakref from dataclasses import field @@ -16,11 +21,12 @@ MotionPlanContext, _active_dof_mask_kernel, _build_terms, + _dof_links, ) from robokit.helpers.motion_plan.motion_plan_score_task import MotionPlanScoreTask from robokit.lie.se3 import se3_identity from robokit.lie.se3_kernels import se3_exp_map_func, se3_inverse_func, se3_log_map_func, se3_multiply_func -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.sampler import GaussianSampler, GaussianSamplerConfig from robokit.opt.var_values import Var, VarKey, VarValues, VectorVar from robokit.robo.robot import Robot @@ -322,10 +328,10 @@ def clone(self) -> "AccelerationTrajectory": out._stale = self._stale return out - def view(self, batch_size: int) -> "AccelerationTrajectory": - action = cast(VectorVar, self.get(VarKey.ACTION)).view(batch_size) + def view(self, batch_size: int, offset: int = 0) -> "AccelerationTrajectory": + action = cast(VectorVar, self.get(VarKey.ACTION)).view(batch_size, offset) out = AccelerationTrajectory( - action, cast(RobotState, super().get(VarKey.ROBOT)).view(batch_size), self._rollout + action, cast(RobotState, super().get(VarKey.ROBOT)).view(batch_size, offset), self._rollout ) out._stale = self._stale return out @@ -461,11 +467,9 @@ class MppiTrajectoryOptimizerConfig: score_terms: List[ResidualTask] = field(default_factory=lambda: [MotionPlanScoreTask(keep_candidate_zero=False)]) """Rank the candidates when there are several; several tasks combine.""" solver: PopulationSolverConfig = field( - default_factory=lambda: PopulationSolverConfig(num_iters=50, samplers=[ColoredGaussianSamplerConfig()]) + default_factory=lambda: PopulationSolverConfig(stages=[Stage(50)], samplers=[ColoredGaussianSamplerConfig()]) ) - """Sampling updates (`num_iters`), trajectories per query (`num_candidates`) and one `ColoredGaussianSamplerConfig`: - draws, spread and update rule. Position control draws white noise, as knots and the filter shape actions; the - planner sets graph capture.""" + """One stage of sampling updates (`iters`) and trajectories per query (`num_candidates`), and one `ColoredGaussianSamplerConfig`: draws, spread and update rule. Position control draws white noise, as knots and the filter shape actions; the planner sets graph capture.""" method: Literal["mppi"] = "mppi" """The stage's method, which the planner dispatches on.""" control_space: Literal["position", "acceleration"] = "position" @@ -477,11 +481,9 @@ class MppiTrajectoryOptimizerConfig: q_limit_margin: float = 0.0 """Margin (rad) an acceleration rollout may pass the joint limits by before it clamps.""" dt_max: float = 0.0 - """Above the planning step: an acceleration rollout's step grows linearly to this over the horizon's second - half.""" + """Above the planning step: an acceleration rollout's step grows linearly to this over the horizon's second half.""" settle_radius: float = 0.0 - """>0: an online update narrows the spread toward the sampler's `min_std` as the end effector comes within this - distance (m) of its goal.""" + """>0: an online update narrows the spread toward the sampler's `min_std` as the end effector comes within this distance (m) of its goal.""" fresh_noise: bool = False """Each online update draws new noise instead of replaying one sequence.""" @@ -522,13 +524,11 @@ class MppiTrajectoryOptimizer: 1. `__init__` stores configuration and creates the active-DOF mask. 2. `warmup(batch_size)` builds batch-shaped tasks, buffers, execution graphs, and the variable: a. position control samples the trajectory `RobotState` directly; - b. acceleration control samples an `AccelerationTrajectory`, whose actions roll out to `robot` - with `ColoredGaussianSampler` noise. + b. acceleration control samples an `AccelerationTrajectory`, whose actions roll out to `robot` with `ColoredGaussianSampler` noise. 3. `solve(...)` uses the same path for offline, cold-online, and warm-online optimization: a. `_set_inputs(...)` updates tasks and restores or initializes the optimization state. b. `_solver.solve(...)` runs the `PopulationSolver` schedule. - c. `wp.copy(...)` saves the trajectory, previous configuration, and mean action to - `online_state` when provided. + c. `wp.copy(...)` saves the trajectory, previous configuration, and mean action to `online_state` when provided. """ def __init__( @@ -543,6 +543,7 @@ def __init__( scene: Optional["WarpScene"] = None, use_cuda_graph: bool = True, acceleration_limit: float = 15.0, + sphere_mask: Optional[wp.array] = None, device: Optional[wp_device_type] = None, ): device = str(resolve_device(device)) @@ -555,14 +556,11 @@ def __init__( raise ValueError("A floating base needs acceleration control: it carries its measured twist.") self.num_frames = num_frames self._scene = scene + self._sphere_mask = sphere_mask # each frame's checked spheres, for the score self.device = device self.num_dofs = robot.num_actuated_joints - if ( - len(config.solver.samplers) != 1 - or config.solver.optimizer is not None - or len(config.solver.num_candidates) != 1 - ): - raise ValueError("MPPI samples with one sampler, no optimizer and one candidate width.") + if len(config.solver.samplers) != 1 or config.solver.optimizer is not None or len(config.solver.stages) != 1: + raise ValueError("MPPI samples with one sampler, no optimizer and one stage.") self.num_candidates = config.solver.num_candidates[0] self._use_cuda_graph = use_cuda_graph self._acceleration_limit = acceleration_limit # the plan's, which acceleration rollouts clamp to @@ -580,15 +578,16 @@ def __init__( config_locked = np.zeros(num_frames, np.int32) config_locked[[f % num_frames for f in config.lock_frames]] = 1 self._config_locked_wp = wp.array(config_locked, dtype=wp.int32, device=device) + self._dof_links = _dof_links(robot, self.target_link_indices, 0, device) self.locked_frames = wp.zeros( num_frames, dtype=wp.int32, device=device - ) # 1 holds a frame; may change on device + ) # each frame's held target links as bits, -1 all; may change on device self.set_lock_frames(()) def set_lock_frames(self, lock_frames: Sequence[int]): """Hold these frames, besides `config.lock_frames`, where they start; never while capturing.""" locked = np.zeros(self.num_frames, np.int32) - locked[[f % self.num_frames for f in lock_frames]] = 1 + locked[[f % self.num_frames for f in lock_frames]] = -1 self.locked_frames.assign(locked) self._apply_active_dof_mask() @@ -601,7 +600,7 @@ def _apply_active_dof_mask(self): wp.launch( _active_dof_mask_kernel, dim=(self.num_frames, self.num_dofs), - inputs=[self._dof_mask_wp, self.locked_frames, self._config_locked_wp], + inputs=[self._dof_mask_wp, self.locked_frames, self._config_locked_wp, self._dof_links, None, 0], outputs=[self._active_dof_mask_wp], device=self.device, ) @@ -814,6 +813,7 @@ def warmup(self, batch_size: int): # weak: the solver holds the score, so a strong `self` would keep the scene alive until a GC pass ctx.CANDIDATE_COSTS: lambda self_ref=weakref.ref(self): self_ref()._solver.candidate_scores, ctx.DRAWS: config.solver.num_draws, + ctx.SPHERE_MASK: self._sphere_mask, } var = VarValues({VarKey.ROBOT: self._state}) self._tasks = _build_terms(config.terms, var, context) diff --git a/src/robokit/helpers/motion_plan/plan_goal.py b/src/robokit/helpers/motion_plan/plan_goal.py index 11f88f2..8be6a07 100644 --- a/src/robokit/helpers/motion_plan/plan_goal.py +++ b/src/robokit/helpers/motion_plan/plan_goal.py @@ -67,6 +67,8 @@ class MotionPlanContext(Context): """The planner's `RetimeConfig` for this stage, or None; the score samples plans at the step it gives.""" DRAWS = 20 """Draws each candidate holds in a ranked population; MPPI only.""" + SPHERE_MASK = 21 + """Each frame's checked spheres `(frames, spheres)` int32 (0 drops a sphere there, e.g. an attached object), or None.""" __all__ = ["MotionPlanContext", "PlanGoal"] diff --git a/src/robokit/helpers/motion_plan/presets.py b/src/robokit/helpers/motion_plan/presets.py index b01c57e..c954d58 100644 --- a/src/robokit/helpers/motion_plan/presets.py +++ b/src/robokit/helpers/motion_plan/presets.py @@ -31,7 +31,7 @@ from robokit.opt.gd_optimizer import GDOptimizerConfig from robokit.opt.lbfgs_optimizer import LBFGSOptimizerConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms.dense.com_position_task import ComPositionTask from robokit.terms.dense.configuration_task import ConfigurationTask from robokit.terms.dense.frame_task import FrameTask @@ -76,8 +76,8 @@ def build_offline_ik_config( num_goal_candidates: Number of final joint goals returned per query. Defaults to `num_candidates`. num_samples: Number of IK seeds sampled before the funnel narrows. num_refine_samples: Seeds retained for refinement. Defaults to `num_samples`. - collision_margin: Clearance goal IK keeps from every scene geometry. - collision_weight: Weight of that clearance. + collision_margin: Clearance goal IK keeps from every scene geometry (goal IK has no self-collision term). + collision_weight: Weight of that clearance: a cost, not a constraint, so answers can still end inside. Returns: A `samples -> refine -> goal` IK configuration. @@ -96,17 +96,10 @@ def build_offline_ik_config( return ( IKSolverConfig( solver=PopulationSolverConfig( - num_iters=4 + 12, - select_at=[4, 4 + 12], - num_candidates=[ - max(num_samples, num_candidates * 2), - max(num_refine_samples, num_candidates * 2), - num_goal_candidates, - ], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(4, max(num_samples, num_candidates * 2), LMOptimizerConfig(lm_lambda=10.0)), + Stage(12, max(num_refine_samples, num_candidates * 2), LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, num_goal_candidates, LMOptimizerConfig(lm_lambda=1.0)), ], cuda_graph_mode=cuda_graph_mode, ) @@ -215,15 +208,19 @@ def build_offline_pose_goal_config( TrajectorySelfCollisionTask(weight=5000.0, margin=0.0, penalty="max_linear", name="self_collision"), ], solver=PopulationSolverConfig( - num_iters=max_iter, - num_candidates=[num_candidates], - optimizer=dataclasses.replace( - _lbfgs, - line_search="approx_wolfe", - line_search_alphas=(0.3, 1.0), # two trials cost less per iteration and plan as well as four - h0_scale=0.01, - wolfe_c1=1e-5, - ), + stages=[ + Stage( + max_iter, + num_candidates, + dataclasses.replace( + _lbfgs, + line_search="approx_wolfe", + line_search_alphas=(0.3, 1.0), # two trials cost less per iteration and plan as well as four + h0_scale=0.01, + wolfe_c1=1e-5, + ), + ) + ] ), score_terms=[ MotionPlanScoreTask( @@ -240,7 +237,7 @@ def build_offline_pose_goal_config( ) finetune = dataclasses.replace( trajopt, - solver=dataclasses.replace(trajopt.solver, num_iters=180), + solver=dataclasses.replace(trajopt.solver, stages=[dataclasses.replace(trajopt.solver.stages[0], iters=180)]), lock_frames=(0, -1), # holds the terminal waypoint the trajectory stage reached, besides the start terms=[ # first, so its term streams fork first: the swept cost runs longest and otherwise waits for SMs @@ -318,7 +315,14 @@ def build_offline_pose_goal_config( stages=tuple( dataclasses.replace( stage, - solver=dataclasses.replace(stage.solver, num_iters=50, optimizer=dataclasses.replace(_lm, lm_lambda=0.01)), + solver=dataclasses.replace( + stage.solver, + stages=[ + dataclasses.replace( + stage.solver.stages[0], iters=50, optimizer=dataclasses.replace(_lm, lm_lambda=0.01) + ) + ], + ), terms=deepcopy(stage.terms), ) for stage in offline_pose_lbfgs.stages @@ -381,9 +385,13 @@ def build_offline_pose_goal_config( ], score_terms=[MotionPlanScoreTask(keep_candidate_zero=False)], solver=PopulationSolverConfig( - num_iters=10, - num_candidates=[16], # eight candidates lose success on the full reactive benchmark - optimizer=dataclasses.replace(_lbfgs, normalize_direction=True), # ten iterations: steps are lengths + stages=[ + Stage( + 10, + 16, # eight candidates lose success on the full reactive benchmark + dataclasses.replace(_lbfgs, normalize_direction=True), # ten iterations: steps are lengths + ) + ] ), lock_frames=(0,), ), @@ -400,9 +408,7 @@ def build_offline_pose_goal_config( dataclasses.replace( online_pose_lbfgs.stages[0], solver=PopulationSolverConfig( - num_iters=5, - num_candidates=[8], - optimizer=dataclasses.replace(_lm, lm_lambda=0.01, linear_solver="cg", cg_max_iter=4), + stages=[Stage(5, 8, dataclasses.replace(_lm, lm_lambda=0.01, linear_solver="cg", cg_max_iter=4))] ), terms=deepcopy(online_pose_lbfgs.stages[0].terms), ), @@ -450,7 +456,7 @@ def build_offline_pose_goal_config( ), ], solver=PopulationSolverConfig( - num_iters=5, # MPPI updates per tick + stages=[Stage(5)], # MPPI updates per tick samplers=[ ColoredGaussianSamplerConfig( num_draws=384, temperature=0.2, init_std=1.5, min_std=0.005, knot_ratio=0.7 @@ -478,16 +484,21 @@ def build_offline_pose_goal_config( terms=deepcopy(stage.terms), solver=dataclasses.replace( stage.solver, - optimizer=GDOptimizerConfig( - learning_rate=learning_rate, - # cosine annealing to `low` over the stage's 50 iterations - lr_schedule=lambda it, lr, low=low: ( - low + 0.5 * (lr - low) * (1.0 + math.cos(math.pi * min(it, 50) / 50)) - ), - optimizer_type="adam" if adam else "gd", - weight_decay=weight_decay, - early_stopping_interval=0, - ), + stages=[ + dataclasses.replace( + stage.solver.stages[0], + optimizer=GDOptimizerConfig( + learning_rate=learning_rate, + # cosine annealing to `low` over the stage's 50 iterations + lr_schedule=lambda it, lr, low=low: ( + low + 0.5 * (lr - low) * (1.0 + math.cos(math.pi * min(it, 50) / 50)) + ), + optimizer_type="adam" if adam else "gd", + weight_decay=weight_decay, + early_stopping_interval=0, + ), + ) + ], ), ) for stage in offline_pose_lm.stages @@ -507,13 +518,10 @@ def build_offline_pose_goal_config( def _humanoid_ik_config() -> IKSolverConfig: return IKSolverConfig( solver=PopulationSolverConfig( - num_iters=24, - select_at=[8, 24], - num_candidates=[128, 64, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(8, 128, LMOptimizerConfig(lm_lambda=10.0)), + Stage(16, 64, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1, LMOptimizerConfig(lm_lambda=1.0)), ], cuda_graph_mode="full", ), @@ -551,14 +559,18 @@ def _humanoid_ik_config() -> IKSolverConfig: stages=( GradientTrajectoryOptimizerConfig( solver=PopulationSolverConfig( - num_iters=120, - num_candidates=[4], # the goal IK solution, repeated with different initial noise - optimizer=dataclasses.replace( - _lbfgs, - line_search_alphas=(1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 5e-1, 1.0), - history_len=10, - normalize_direction=True, # the planted-feet weights dwarf the rest: steps are lengths - ), + stages=[ + Stage( + 120, + 4, # the goal IK solution, repeated with different initial noise + dataclasses.replace( + _lbfgs, + line_search_alphas=(1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 5e-1, 1.0), + history_len=10, + normalize_direction=True, # the planted-feet weights dwarf the rest: steps are lengths + ), + ) + ] ), lock_frames=(0, -1), # paths run from the start to the goal IK solution terms=[ @@ -623,11 +635,8 @@ def _humanoid_ik_config() -> IKSolverConfig: stages=( GradientTrajectoryOptimizerConfig( solver=PopulationSolverConfig( - num_iters=60, - select_at=[10], - num_candidates=[4, 1], # the planted-feet weights dwarf the rest: steps are lengths - optimizer=dataclasses.replace(_lbfgs, normalize_direction=True), + stages=[Stage(10, 4, dataclasses.replace(_lbfgs, normalize_direction=True)), Stage(50, 1)], ), score_terms=[MotionPlanScoreTask(keep_candidate_zero=False)], lock_frames=(0,), @@ -695,7 +704,7 @@ def _humanoid_ik_config() -> IKSolverConfig: MppiTrajectoryOptimizerConfig( control_space="acceleration", solver=PopulationSolverConfig( - num_iters=50, + stages=[Stage(50)], samplers=[ ColoredGaussianSamplerConfig( num_draws=64, init_std=0.1, min_std=0.001, temperature=0.05, knot_ratio=0.9 diff --git a/src/robokit/helpers/motion_plan/trajectory_retimer.py b/src/robokit/helpers/motion_plan/trajectory_retimer.py index 47d447d..288f098 100644 --- a/src/robokit/helpers/motion_plan/trajectory_retimer.py +++ b/src/robokit/helpers/motion_plan/trajectory_retimer.py @@ -204,8 +204,7 @@ def _interpolate_trajectory_kernel( """Linearly interpolate the plan, segment by segment between anchors. Sampling steps: - 1. Spread ceil(segment time / interpolation_dt) samples evenly across each segment, its time its fixed - duration or its frames * step. + 1. Spread ceil(segment time / interpolation_dt) samples evenly across each segment, its time its fixed duration or its frames * step. 2. Repeat the final frame. """ batch, sample, dof = wp.tid() # pyright: ignore[reportAssignmentType] @@ -277,7 +276,7 @@ def device(self) -> wp_device_type: def clone(self) -> "TimingVar": return TimingVar(wp.clone(self.dt)) - def view(self, batch_size: int) -> "TimingVar": + def view(self, batch_size: int, offset: int = 0) -> "TimingVar": return self def integrate( diff --git a/src/robokit/helpers/rl/__init__.py b/src/robokit/helpers/rl/__init__.py new file mode 100644 index 0000000..ea6125b --- /dev/null +++ b/src/robokit/helpers/rl/__init__.py @@ -0,0 +1,28 @@ +"""PPO (`ppo`) and FastSAC (`fastsac`) for batched GPU envs that implement `Env`; examples/rl holds such tasks.""" + +from typing import List, Protocol, Tuple + +import torch + + +class Env(Protocol): + """What solvers call: GPU tensors, no host syncs (FastSAC graphs a step), on the current (not default) stream.""" + + n: int # worlds + obs_dims: Tuple[int, int] # the actor's and the critic's observation sizes + bound: torch.Tensor # (number of actions,): FastSAC's tanh spans [-bound, bound] + names: List[str] # the reward terms + + def obs(self) -> Tuple[torch.Tensor, torch.Tensor]: ... # the actor's and the critic's + def reset(self, mask: torch.Tensor): ... # the masked worlds + def curriculum(self, step: int): ... # to `step` env steps; called outside CUDA graphs, which freeze Python ints + def step(self, action: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Act; return the reward, terminated and truncated (n,), and each reward term's mean over worlds.""" + ... + + +from robokit.helpers.rl.fastsac import FastSACConfig # noqa: E402 (after `Env`, which the solvers import) +from robokit.helpers.rl.ppo import PPOConfig # noqa: E402 + + +__all__ = ["Env", "FastSACConfig", "PPOConfig"] diff --git a/src/robokit/helpers/rl/fastsac.py b/src/robokit/helpers/rl/fastsac.py new file mode 100644 index 0000000..8d39bdc --- /dev/null +++ b/src/robokit/helpers/rl/fastsac.py @@ -0,0 +1,211 @@ +# pyright: reportCallIssue=false, reportPrivateImportUsage=false +"""FastSAC (SAC, C51 critics, G1 settings) with a 1024-step replay per world and no symmetry. + +FastSAC: https://arxiv.org/abs/2512.01996. SAC: https://arxiv.org/abs/1801.01290. C51: https://arxiv.org/abs/1707.06887. +""" + +import copy +import math +import time +from dataclasses import dataclass +from typing import Dict, Tuple + +import torch +import warp as wp +from torch import nn +from torch.optim.adamw import AdamW + +from robokit.helpers.rl import Env +from robokit.helpers.rl.ppo import Normalizer + + +@dataclass(frozen=True) +class FastSACConfig: + """FastSAC settings for the G1, with a 1024-step replay per world. + + Example: + >>> # xdoctest: +REQUIRES(module:torch) + >>> FastSACConfig().batch + 8192 + """ + + actor_width: int = 512 + """Width of the actor's first hidden layer; the next two halve it.""" + critic_width: int = 768 + """Width of each critic's first hidden layer; the next two halve it.""" + atoms: int = 101 + """C51 atoms per critic, evenly on [-v_max, v_max].""" + v_max: float = 20.0 + """Largest return the critics represent.""" + batch: int = 8192 + """Samples per update.""" + updates: int = 8 + """Updates per env step.""" + actor_every: int = 4 + """Critic updates per actor update.""" + gamma: float = 0.97 + """Discount.""" + tau: float = 0.125 + """Target critics' step toward the critics per update.""" + lr: float = 3e-4 + """AdamW learning rate of the actor, the critics and the temperature.""" + weight_decay: float = 0.001 + """AdamW weight decay of the actor and the critics.""" + alpha: float = 0.001 + """Initial entropy temperature.""" + log_std_range: Tuple[float, float] = (-5.0, 0.0) + """Range of the actor's log-std.""" + buffer: int = 1024 + """Replay env steps per world.""" + start: int = 10 + """Env steps before learning, which fill the replay.""" + + +def _mlp(dim: int, hidden: int, out: int) -> nn.Sequential: + dims, layers = (dim, hidden, hidden // 2, hidden // 4), [] + for a, b in zip(dims, dims[1:]): + layers += [nn.Linear(a, b), nn.LayerNorm(b), nn.SiLU()] + return nn.Sequential(*layers, nn.Linear(dims[-1], out)) + + +class Actor(nn.Module): + """A tanh-squashed Gaussian actor with its observation normalizer; actions in [-1, 1] times `bound`. + + Example: + >>> # xdoctest: +REQUIRES(module:torch) + >>> [tuple(x.shape) for x in Actor(48, torch.ones(12), FastSACConfig()).sample(torch.zeros(5, 48))] + [(5, 12), (5,)] + """ + + def __init__(self, dim: int, bound: torch.Tensor, config: FastSACConfig): + super().__init__() + self.n, self.obs_normalizer, self.log_std_range = len(bound), Normalizer(dim), config.log_std_range + self.net = _mlp(dim, config.actor_width, 2 * self.n) + nn.init.normal_(self.net[-1].weight, 0.0, 0.0) # pyright: ignore[reportArgumentType] + nn.init.zeros_(self.net[-1].bias) # pyright: ignore[reportArgumentType] + self.register_buffer("bound", bound) + + def forward(self, obs: torch.Tensor) -> torch.Tensor: + """The deterministic action, in the env's units.""" + return self.net(self.obs_normalizer(obs))[..., : self.n].tanh() * self.bound + + def sample(self, obs: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: + """A squashed Gaussian action in [-1, 1] and its log-probability in the env's units.""" + mean, log_std = self.net(self.obs_normalizer(obs)).float().chunk(2, -1) + low, high = self.log_std_range + log_std = low + 0.5 * (high - low) * (log_std.tanh() + 1) + z = torch.randn_like(mean) + u = (mean + log_std.exp() * z).tanh() + logp = -0.5 * z**2 - log_std - 0.5 * math.log(2 * math.pi) - (1 - u**2 + 1e-6).log() - self.bound.log() + return u, logp.sum(-1) + + +def train(env: Env, minutes: float, config: FastSACConfig = FastSACConfig()) -> Actor: + """Train an actor with FastSAC on `env` for `minutes` of wall time; returns it, deterministic in the env's units. + + Example: + >>> # xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS) + >>> from types import SimpleNamespace + >>> o, f = torch.zeros(64, 3, device="cuda"), torch.zeros(64, dtype=torch.bool, device="cuda") + >>> env = SimpleNamespace(n=64, obs_dims=(3, 3), bound=torch.ones(2, device="cuda"), names=["a2"], + ... obs=lambda: (o, o), step=lambda a: (-(a**2).sum(1), f, f, (a**2).mean()[None]), reset=id, curriculum=id) + >>> torch.cuda.set_stream(torch.cuda.Stream()) # envs run on a stream other than the default, as graphs need + >>> tuple(train(env, minutes=0.2)(o).shape) # a bandit: actions near 0 pay + (64, 2) + """ + torch.backends.cuda.matmul.allow_tf32 = torch.backends.cudnn.allow_tf32 = True + n, (da, dc), k, obs = env.n, env.obs_dims, config.batch // env.n, env.obs() + device = env.bound.device + gamma, v_max, atoms = config.gamma, config.v_max, config.atoms + actor, norm_c = Actor(da, env.bound, config).to(device), Normalizer(dc).to(device) + critic = nn.ModuleList(_mlp(dc + actor.n, config.critic_width, atoms) for _ in range(2)).to(device) # two C51s + target, support = copy.deepcopy(critic).requires_grad_(False), torch.linspace(-v_max, v_max, atoms, device=device) + log_alpha = torch.tensor(math.log(config.alpha), device=device, requires_grad=True) + opt_a = AdamW(actor.parameters(), config.lr, weight_decay=config.weight_decay, capturable=True) + opt_c = AdamW(critic.parameters(), config.lr, weight_decay=config.weight_decay, capturable=True) + opt_t = AdamW([log_alpha], config.lr, betas=(0.9, 0.95), capturable=True) + dims = dict(a=da, c=dc, act=actor.n, r=0, a2=da, c2=dc, boot=0) + buf = {key: torch.zeros(config.buffer, n, *([d] if d else []), device=device) for key, d in dims.items()} + filled = torch.zeros((), device=device) # replay size + pos = torch.zeros(1, dtype=torch.long, device=device) # next slot + side, worlds = torch.cuda.Stream(priority=-1), torch.arange(n, device=device) # learning, the longer branch, first + + def q(net: nn.ModuleList, obs: torch.Tensor, act: torch.Tensor) -> torch.Tensor: # both critics' logits + x = torch.cat([obs, act], -1) + return torch.stack([m(x) for m in net]).float() + + @torch.compile + def update(b: Dict[str, torch.Tensor], policy: bool): + """One critic step and the temperature's, every `actor_every`-th an actor step, then the targets.""" + xc, xc2 = norm_c(b["c"]), norm_c(b["c2"]) + with torch.no_grad(), torch.autocast("cuda", torch.bfloat16): + u2, logp2 = actor.sample(b["a2"]) + reward = b["r"] - gamma * b["boot"] * log_alpha.exp() * logp2 + # the distribution of reward + gamma * Z, Z ~ the target critics, projected onto the support + x = (reward[:, None] + gamma * b["boot"][:, None] * support).clamp(-v_max, v_max) + x = (x + v_max) / (2 * v_max / (atoms - 1)) # in atoms + lo, hi = x.floor(), x.ceil() + p = q(target, xc2, u2).softmax(-1) + dist = torch.zeros_like(p).scatter_add_(-1, lo.long().expand_as(p), p * (hi - x + (lo == hi))) # whole atom + dist.scatter_add_(-1, hi.long().expand_as(p), p * (x - lo)) + with torch.autocast("cuda", torch.bfloat16): + loss = -(dist * q(critic, xc, b["act"]).log_softmax(-1)).sum(-1).mean(-1).sum() + opt_c.zero_grad(set_to_none=True) + loss.backward() + opt_c.step() + opt_t.zero_grad(set_to_none=True) + (-log_alpha.exp() * logp2.mean()).backward() # target entropy 0 + opt_t.step() + if policy: + with torch.autocast("cuda", torch.bfloat16): + u, logp = actor.sample(b["a"]) + value = (q(critic, xc, u).softmax(-1) * support).sum(-1) + loss = (log_alpha.exp().detach() * logp - value.mean(0)).mean() + opt_a.zero_grad(set_to_none=True) + loss.backward() + opt_a.step() + torch._foreach_lerp_(list(target.parameters()), list(critic.parameters()), config.tau) + + @torch.compile + def act(obs: torch.Tensor) -> torch.Tensor: + with torch.autocast("cuda", torch.bfloat16): + return actor.sample(obs)[0] + + @torch.no_grad() + def step(learning: bool): + """Act, then physics and resets alongside learning on the replay so far, then the replay write; in place.""" + obs_a, obs_c = obs + actor.obs_normalizer.update(obs_a) + norm_c.update(obs_c) + u = act(obs_a) + side.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(side), torch.enable_grad(): # pyright: ignore[reportArgumentType] + if learning: # sample `updates` batches at once (a batch per world), then update on each in turn + idx = (torch.rand(config.updates * k, n, device=device) * filled).long() + batch = {key: v[idx, worlds].flatten(0, 1) for key, v in buf.items()} + for i in range(config.updates): + minibatch = {key: v[i * k * n : (i + 1) * k * n] for key, v in batch.items()} + update(minibatch, i % config.actor_every == 1) + reward, terminated, timeout, _ = env.step(u * actor.bound) # pyright: ignore[reportOperatorIssue] + final_a, final_c = env.obs() # where a timed-out episode ended, for its bootstrap + env.reset(terminated | timeout) + obs2 = env.obs() + torch.cuda.current_stream().wait_stream(side) + new = dict(a=obs_a, c=obs_c, act=u, r=reward, a2=final_a, c2=final_c, boot=(~terminated).float()) + for key, value in new.items(): + buf[key].index_copy_(0, pos, value[None]) + pos.add_(1).remainder_(config.buffer) + filled.add_(1).clamp_(max=config.buffer) + for o, o2 in zip(obs, obs2): + o.copy_(o2) + + graph, it, start = torch.cuda.CUDAGraph(), 0, time.perf_counter() + while time.perf_counter() - start < minutes * 60: + env.curriculum(it) + if it == config.start + 3: # eager while the replay fills and torch.compile warms up, then one graph per step + with torch.cuda.graph(graph): # on torch's capture stream, which Warp then also records on + with wp.ScopedStream(wp.stream_from_torch(), sync_enter=False, sync_exit=False): + step(True) + step(it >= config.start) if it < config.start + 3 else graph.replay() + it += 1 + return actor diff --git a/src/robokit/helpers/rl/ppo.py b/src/robokit/helpers/rl/ppo.py new file mode 100644 index 0000000..02bc31f --- /dev/null +++ b/src/robokit/helpers/rl/ppo.py @@ -0,0 +1,347 @@ +"""PPO with GAE, a KL-adaptive learning rate and observation normalizers, the whole update as one CUDA graph. + +PPO: https://arxiv.org/abs/1707.06347. GAE: https://arxiv.org/abs/1506.02438. +""" + +import math +import random +import time +from dataclasses import dataclass +from itertools import chain +from typing import Callable, Dict, List, Literal, Optional, Tuple + +import torch +from torch import nn +from torch.nn import functional as F +from torch.optim.adam import Adam +from torch.optim.optimizer import Optimizer + +from robokit.helpers.rl import Env + + +@dataclass(frozen=True) +class PPOConfig: + """PPO hyperparameters for locomotion and manipulation tasks. + + Example: + >>> # xdoctest: +REQUIRES(module:torch) + >>> PPOConfig(entropy=0.005).horizon + 24 + """ + + gamma: float = 0.99 + """Discount.""" + lam: float = 0.95 + """GAE lambda.""" + clip: float = 0.2 + """Clip of the probability ratio and of the value's change.""" + value_coef: float = 1.0 + """Value loss weight.""" + entropy: float = 0.01 + """Entropy bonus weight.""" + lr: float = 1e-3 + """Initial learning rate.""" + lr_range: Tuple[float, float] = (1e-5, 1e-2) + """Bounds of the adaptive learning rate.""" + lr_factor: float = 1.5 + """The rate divides by this when the KL exceeds `2 kl`, multiplies by it when the KL falls under `kl / 2`.""" + kl: float = 0.01 + """Target KL divergence per minibatch.""" + epochs: int = 5 + """Passes over each rollout.""" + minibatches: int = 4 + """Minibatches per pass.""" + reshuffle: bool = False + """A new minibatch split each pass, not one split per update.""" + max_grad: float = 1.0 + """Gradient-norm clip.""" + grad_clip: Literal["network", "joint"] = "network" + """Clip each network's gradient norm (shared parameters count as the actor's), or one norm over both.""" + horizon: int = 24 + """Env steps per world per rollout.""" + hidden: Tuple[int, ...] = (512, 256, 128) + """Hidden widths of the actor's and the critic's ELU MLPs.""" + init_std: float = 1.0 + """Initial action std.""" + std_range: Tuple[float, float] = (1e-6, 1e6) + """Clamp of the action std.""" + std: Literal["global", "state"] = "global" + """`global`: a learned std per action; `state`: a softplus std per sample, actions tanh-squashed.""" + squash_entropy: bool = False + """With `std="state"`, the squashed entropy (tanh log-Jacobian at a sample added): saturation loses entropy.""" + normalize: bool = True + """Empirical normalization of both networks' observations (off for cartpole).""" + + +class Normalizer(nn.Module): + """Empirical normalization: running mean and variance over every sample seen; 0.01 added to the std. + + Example: + >>> # xdoctest: +REQUIRES(module:torch) + >>> (norm := Normalizer(2)).update(torch.tensor([[1.0, 2.0], [3.0, 6.0]])) + >>> norm(torch.tensor([[2.0, 4.0]])).tolist() + [[0.0, 0.0]] + """ + + def __init__(self, dim: int): + super().__init__() + for name, value in (("_mean", 0.0), ("_var", 1.0), ("_std", 1.0)): + self.register_buffer(name, torch.full((1, dim), value)) + self.register_buffer("count", torch.zeros((), dtype=torch.long)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return (x - self._mean) / (self._std + 0.01) # pyright: ignore[reportOperatorIssue] + + @torch.no_grad() + def update(self, x: torch.Tensor): + self.count += x.shape[0] + rate, mean = x.shape[0] / self.count, x.mean(0, keepdim=True) + delta = mean - self._mean + self._mean += rate * delta + self._var += rate * (x.var(0, unbiased=False, keepdim=True) - self._var + delta * (mean - self._mean)) + self._std.copy_(self._var.sqrt()) # pyright: ignore[reportCallIssue] + + +class Model(nn.Module): + """A normalizer, an ELU MLP and a scalar std per action. + + Args: + state_std: the MLP also outputs each std; `forward` is the deterministic action, tanh of the mean. + normalize: an empirical normalizer, else the identity. + + Example: + >>> # xdoctest: +REQUIRES(module:torch) + >>> tuple(Model(48, 12, hidden=(64, 64), std=1.0)(torch.zeros(5, 48)).shape) + (5, 12) + >>> tuple(Model(48, 12, hidden=(64, 64), std=1.0, state_std=True).dist(torch.zeros(5, 48), (0.0, 9.0))[1].shape) + (5, 12) + """ + + def __init__( + self, + obs_dim: int, + out_dim: int, + hidden: Tuple[int, ...], + std: float = 0.0, + state_std: bool = False, + normalize: bool = True, + ): + super().__init__() + dims, self.state_std = (obs_dim, *hidden), state_std + self.obs_normalizer = Normalizer(obs_dim) if normalize else nn.Identity() + layers = [layer for a, b in zip(dims, dims[1:]) for layer in (nn.Linear(a, b), nn.ELU())] + self.mlp = nn.Sequential(*layers, nn.Linear(dims[-1], out_dim * (1 + state_std))) + self.std_shift = math.log(math.expm1(std)) if state_std else 0.0 # softplus(shift) = std initially + if std and not state_std: # the actor's + self.distribution = nn.Module() + self.distribution.std_param = nn.Parameter(torch.full((out_dim,), std)) + + def forward(self, obs: torch.Tensor) -> torch.Tensor: + out = self.mlp(self.obs_normalizer(obs)) + return out.chunk(2, -1)[0].tanh() if self.state_std else out + + def dist(self, obs: torch.Tensor, std_range: Tuple[float, float]) -> Tuple[torch.Tensor, torch.Tensor]: + """The actor's Gaussian (before any tanh): its mean and std, the std per action or per sample and action.""" + out = self.mlp(self.obs_normalizer(obs)) + if self.state_std: + mean, raw = out.chunk(2, -1) + return mean, (F.softplus(raw + self.std_shift) + 1e-3).clamp(*std_range) # a 0.001 floor + return out, self.distribution.std_param.clamp(*std_range) # pyright: ignore[reportCallIssue] + + +def _log_density(z: torch.Tensor, std: torch.Tensor) -> torch.Tensor: + return -0.5 * (z * z).sum(-1) - std.log().sum(-1) - 0.5 * z.shape[-1] * math.log(2 * math.pi) + + +@torch.compile +def _loss(actor: nn.Module, critic: nn.Module, batch: dict, lr: torch.Tensor, config: PPOConfig) -> torch.Tensor: + """The PPO loss (clipped surrogate, clipped value loss, entropy bonus); adapts `lr` in place from the KL.""" + (mean, std), std0 = actor.dist(batch["obs_a"], config.std_range), batch["std"] # pyright: ignore[reportCallIssue] + value = critic(batch["obs_c"]).squeeze(-1) + # Tanh-squashed actions use their pre-tanh samples: the squash's Jacobian cancels in the ratio and the KL. + logp = _log_density((batch["act"] - mean) / std, std) + ratio, adv, clip = (logp - batch["logp"]).exp(), batch["adv"], config.clip + surrogate = torch.max(-adv * ratio, -adv * ratio.clamp(1 - clip, 1 + clip)).mean() + clipped = batch["val"] + (value - batch["val"]).clamp(-clip, clip) + value_loss = torch.max((value - batch["ret"]) ** 2, (clipped - batch["ret"]) ** 2).mean() + entropy = (0.5 + 0.5 * math.log(2 * math.pi) + std.log()).sum(-1).mean() + if config.squash_entropy: # at the rollout's sample, moved with the new mean and std: log(1 - tanh(x) ** 2) + x = mean + std * (batch["act"] - batch["mean"]) / std0 + entropy = entropy + (2 * (math.log(2) - x - F.softplus(-2 * x))).sum(-1).mean() + kl = ((std / std0).log() + (std0**2 + (batch["mean"] - mean) ** 2) / (2 * std**2) - 0.5).sum(-1).mean() + down, up = kl > 2 * config.kl, (kl < config.kl / 2) & (kl > 0) + lower = (lr / config.lr_factor).clamp(min=config.lr_range[0]) + upper = (lr * config.lr_factor).clamp(max=config.lr_range[1]) + lr.copy_(torch.where(down, lower, torch.where(up, upper, lr))) + return surrogate + config.value_coef * value_loss - config.entropy * entropy + + +def _update( + actor: nn.Module, + critic: nn.Module, + opt: Optimizer, + params: List[List[nn.Parameter]], + batch: dict, + last: torch.Tensor, + config: PPOConfig, +): + """GAE, PPO epochs at a KL-adaptive learning rate, then the normalizers' update; `params`: per network.""" + vals, done, adv, carry = batch["val"], batch["done"].float(), torch.zeros_like(batch["val"]), 0.0 + gamma, lam = config.gamma, config.lam + for t in reversed(range(len(vals))): + nxt = last if t == len(vals) - 1 else vals[t + 1] + carry = batch["rew"][t] + (1 - done[t]) * gamma * nxt - vals[t] + (1 - done[t]) * gamma * lam * carry + adv[t] = carry + batch["ret"] = adv + vals + batch["adv"] = (adv - adv.mean()) / (adv.std() + 1e-8) + flat = {k: v.flatten(0, 1) for k, v in batch.items()} + lr, size = opt.param_groups[0]["lr"], len(flat["val"]) // config.minibatches # lr is a GPU tensor + for epoch in range(config.epochs): + if epoch == 0 or config.reshuffle: + perm = torch.randperm(size * config.minibatches, device=last.device) + for i in range(config.minibatches): + idx = perm[i * size : (i + 1) * size] + loss = _loss(actor, critic, {k: v[idx] for k, v in flat.items()}, lr, config) + opt.zero_grad(set_to_none=True) + loss.backward() + for group in [params[0] + params[1]] if config.grad_clip == "joint" else params: + nn.utils.clip_grad_norm_(group, config.max_grad) + opt.step() + if config.normalize: # a normalizer the two share once, with the actor's observations + actor.obs_normalizer.update(flat["obs_a"]) # pyright: ignore[reportCallIssue] + if critic.obs_normalizer is not actor.obs_normalizer: + critic.obs_normalizer.update(flat["obs_c"]) # pyright: ignore[reportCallIssue] + + +class PPO: + """An actor and critic for `obs_dims` (actor's, critic's) observations and `actions` actions, trained by `update`. + + Args: + actor: Replaces the actor `Model`: a graph-safe module with `dist`, `forward` (the mean action) and `state_std`. + critic: Likewise replaces the critic `Model`; with `config.normalize`, both need `obs_normalizer`, maybe shared. + + Example: + >>> # xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS) + >>> from types import SimpleNamespace + >>> o, f = torch.zeros(64, 3, device="cuda"), torch.zeros(64, dtype=torch.bool, device="cuda") + >>> env = SimpleNamespace(n=64, obs_dims=(3, 3), bound=torch.ones(2, device="cuda"), names=["a2"], + ... obs=lambda: (o, o), step=lambda a: (-(a**2).sum(1), f, f, (a**2).mean()[None]), reset=id, curriculum=id) + >>> learner = PPO(env.obs_dims, 2) + >>> for _ in range(10): # a bandit: actions near 0 pay + ... learner.update(env) + >>> tuple(learner.actor(o).shape) + (64, 2) + """ + + def __init__( + self, + obs_dims: Tuple[int, int], + actions: int, + config: PPOConfig = PPOConfig(), + device: str = "cuda", + actor: Optional[nn.Module] = None, + critic: Optional[nn.Module] = None, + ): + torch.backends.cuda.matmul.allow_tf32 = torch.backends.cudnn.allow_tf32 = True # faster matmuls + self.config, self.env, self.it, self.graph = config, None, 0, torch.cuda.CUDAGraph() + state_std, normalize = config.std == "state", config.normalize + if actor is None: + actor = Model(obs_dims[0], actions, config.hidden, config.init_std, state_std, normalize) + if critic is None: + critic = Model(obs_dims[1], 1, config.hidden, normalize=normalize) + self.actor, self.critic = actor.to(device), critic.to(device) + shared = {id(p) for p in self.actor.parameters()} # the critic's own: a shared parameter is the actor's + self.params = [list(self.actor.parameters()), [p for p in self.critic.parameters() if id(p) not in shared]] + lr = torch.tensor(config.lr, device=device) # a tensor rate lets fused Adam adapt it without a host sync + self.opt = Adam(chain(*self.params), lr=lr, fused=True, capturable=True) + + def update(self, env: Env): + """Set `env`'s curriculum to this update's env step, roll out `horizon` steps from where it is, then update. + + Args: + env: The caller's pick for this update (e.g. coarse, then fine physics); the caller also owns the loop. + """ + actor, critic, config = self.actor, self.critic, self.config + if env is not self.env: # a new env: start from its observations + self.env, self.obs = env, env.obs() + env.curriculum(self.it * config.horizon) + (obs_a, obs_c), steps, self.reward = self.obs, [], torch.zeros(()) + with torch.no_grad(): # rollout + for _ in range(config.horizon): + (mean, std), val = actor.dist(obs_a, config.std_range), critic(obs_c).squeeze(-1) # pyright: ignore + z = torch.randn_like(mean) + act = mean + std * z + reward, terminated, timeout, _ = env.step(act.tanh() if actor.state_std else act) + self.reward = self.reward + reward.mean() / config.horizon # its mean reward per step, a GPU scalar + done = terminated | timeout + logp, std = _log_density(z, std), std.expand_as(mean) + steps.append(dict(obs_a=obs_a, obs_c=obs_c, act=act, logp=logp, mean=mean, std=std, val=val)) + steps[-1].update(rew=reward + config.gamma * val * timeout, done=done) # bootstrap: V(s_t) + env.reset(done) + obs_a, obs_c = self.obs = env.obs() + batch, last = {k: torch.stack([s[k] for s in steps]) for k in steps[0]}, critic(obs_c).squeeze(-1) + # eager while torch.compile warms up, then the whole update is one CUDA graph over fixed inputs + if self.it == 3: + self.static = (*batch.values(), last) + with torch.cuda.graph(self.graph): + _update(actor, critic, self.opt, self.params, dict(batch), last, config) # a copy: it adds keys + if self.it < 3: + _update(actor, critic, self.opt, self.params, batch, last, config) + else: + for a, b in zip(self.static, (*batch.values(), last)): + a.copy_(b) + self.graph.replay() + self.it += 1 + + def train(self, env: Env, minutes: float, coarse_env: Optional[Env] = None, coarse: float = 0.0) -> nn.Module: + """Update for `minutes` of wall time, then return the actor. + + Args: + env: What every other update draws. + coarse_env: Over the first `coarse` fraction, an update draws it with a chance falling linearly from 1 to 0. + + Example: + >>> # xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS) + >>> from types import SimpleNamespace + >>> o, f = torch.zeros(64, 3, device="cuda"), torch.zeros(64, dtype=torch.bool, device="cuda") + >>> env = SimpleNamespace(n=64, obs_dims=(3, 3), bound=torch.ones(2, device="cuda"), names=["a2"], + ... obs=lambda: (o, o), step=lambda a: (-(a**2).sum(1), f, f, (a**2).mean()[None]), + ... reset=id, curriculum=id) + >>> actor = PPO(env.obs_dims, 2).train(env, minutes=0.01) # a few updates + >>> tuple(actor(o).shape) + (64, 2) + """ + start, draw, mix = time.perf_counter(), random.Random(0).random, coarse * minutes * 60 # s of mixing + while (elapsed := time.perf_counter() - start) < minutes * 60: + self.update(coarse_env if coarse_env is not None and draw() * mix >= elapsed else env) + return self.actor + + +@torch.no_grad() +def evaluate(env: Env, actor: Callable, metrics: Dict[str, Callable] = {}, steps: int = 1000) -> Dict[str, float]: + """Score a deterministic `actor` over `steps` env steps from a full reset at the first curriculum stage. + + Returns: + Each reward term's and `metrics()`'s mean per step (metrics read after resets), and terminations per world. + + Example: + >>> # xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS) + >>> from types import SimpleNamespace + >>> o, f = torch.zeros(64, 3, device="cuda"), torch.zeros(64, dtype=torch.bool, device="cuda") + >>> env = SimpleNamespace(n=64, obs_dims=(3, 3), bound=torch.ones(2, device="cuda"), names=["a2"], + ... obs=lambda: (o, o), step=lambda a: (-(a**2).sum(1), f, f, (a**2).mean()[None]), reset=id, curriculum=id) + >>> evaluate(env, lambda obs: obs[:, :2], dict(ones=lambda: o[:, 0] + 1), steps=10) + {'a2': 0.0, 'ones': 1.0, 'terminations': 0.0} + """ + torch.manual_seed(0) + env.curriculum(0) + env.reset(torch.ones(env.n, dtype=torch.bool, device=env.bound.device)) + obs, sums, ends = env.obs(), 0.0, 0.0 + for _ in range(steps): + _, terminated, timeout, means = env.step(actor(obs[0])) + ends = ends + terminated.float().mean() + env.reset(terminated | timeout) + obs = env.obs() + sums = sums + torch.cat([means, *(f().mean()[None] for f in metrics.values())]) + score = dict(zip([*env.names, *metrics], (sums / steps).tolist()), terminations=float(ends)) + return {k: round(v, 4) for k, v in score.items()} diff --git a/src/robokit/helpers/sim_mpc/__init__.py b/src/robokit/helpers/sim_mpc/__init__.py index 2f0d9fc..a0e2981 100644 --- a/src/robokit/helpers/sim_mpc/__init__.py +++ b/src/robokit/helpers/sim_mpc/__init__.py @@ -1,7 +1,8 @@ -"""Sampling MPC over batched simulator rollouts; bindings in `sim_mpc.mjwarp` (MuJoCo Warp) and `sim_mpc.newton`.""" +"""Sampling MPC over batched `robokit.sim` rollouts, and `CartesianControl`, a control map for it.""" -from robokit.helpers.sim_mpc.config import SimMPCConfig -from robokit.helpers.sim_mpc.sim_mpc import SimBinding, SimMPC +from robokit.helpers.sim_mpc.cartesian_control import CartesianControl +from robokit.helpers.sim_mpc.config import SimMPCConfig, SimMPCStage +from robokit.helpers.sim_mpc.sim_mpc import SimMPC, sim_context -__all__ = ["SimBinding", "SimMPC", "SimMPCConfig"] +__all__ = ["CartesianControl", "SimMPC", "SimMPCConfig", "SimMPCStage", "sim_context"] diff --git a/src/robokit/helpers/sim_mpc/cartesian_control.py b/src/robokit/helpers/sim_mpc/cartesian_control.py new file mode 100644 index 0000000..5a3cd98 --- /dev/null +++ b/src/robokit/helpers/sim_mpc/cartesian_control.py @@ -0,0 +1,154 @@ +# pyright: reportArgumentType=false +# pyright: reportIndexIssue=false +# pyright: reportAttributeAccessIssue=false +# pyright: reportOperatorIssue=false +# pyright: reportCallIssue=false +"""`CartesianControl`: a `SimMPC` control map from world-frame body twists to joint velocity commands.""" + +from typing import TYPE_CHECKING, Sequence + +import numpy as np +import warp as wp + + +if TYPE_CHECKING: + import mujoco # pyright: ignore[reportMissingImports] + + from robokit.sim import Sim + + +# --- kernels ---------------------------------------------------------------- +@wp.kernel +def _compute_cartesian_ctrl_kernel( + xpos: wp.array2d(dtype=wp.vec3), + xmat: wp.array2d(dtype=wp.mat33), + subtree_com: wp.array2d(dtype=wp.vec3), + cdof: wp.array2d(dtype=wp.spatial_vector), + dofs: wp.array(dtype=int), + ancestors: wp.array(dtype=float), + gear: wp.array(dtype=float), + body: int, + root: int, + target_position: wp.vec3, + target_rotation: wp.mat33, + position_gain: wp.vec3, + rotation_gain: wp.vec3, + damping: float, + ctrl: wp.array2d(dtype=float), +): + """Each world's commands `gear * J^T (J J^T + damping)^-1 twist`, the twist being the commanded one plus the feedback toward the target; `J`'s columns are the actuated dofs' world-frame twists at the body.""" + world = wp.tid() + offset = xpos[world, body] - subtree_com[world, root] + q_xyzw_error = wp.quat_from_matrix(target_rotation * wp.transpose(xmat[world, body])) + if q_xyzw_error[3] < 0.0: + q_xyzw_error = -q_xyzw_error + angular = wp.vec3(q_xyzw_error[0], q_xyzw_error[1], q_xyzw_error[2]) + length = wp.length(angular) + angular *= 2.0 * wp.atan2(length, q_xyzw_error[3]) / wp.max(length, 1.0e-9) + linear = target_position - xpos[world, body] + twist = wp.spatial_vector() + for i in range(3): + twist[i] = position_gain[i] * linear[i] + twist[i + 3] = rotation_gain[i] * angular[i] + for i in range(wp.min(6, ctrl.shape[1])): + twist[i] += ctrl[world, i] + matrix = wp.spatial_matrix() # J J^T + for actuator in range(dofs.shape[0]): + motion = cdof[world, dofs[actuator]] + omega = wp.spatial_top(motion) * ancestors[actuator] + velocity = (wp.spatial_bottom(motion) + wp.cross(omega, offset)) * ancestors[actuator] + column = wp.spatial_vector(velocity[0], velocity[1], velocity[2], omega[0], omega[1], omega[2]) + for i in range(6): + for j in range(6): + matrix[i, j] += column[i] * column[j] + # damped 6x6 Cholesky solve; no fixed robot size or matrix inverse is needed + lower = wp.spatial_matrix() + for j in range(6): + diagonal = matrix[j, j] + damping + for k in range(j): + diagonal -= lower[j, k] * lower[j, k] + lower[j, j] = wp.sqrt(wp.max(diagonal, 1.0e-12)) + for i in range(j + 1, 6): + value = matrix[i, j] + for k in range(j): + value -= lower[i, k] * lower[j, k] + lower[i, j] = value / lower[j, j] + forward = wp.spatial_vector() + solution = wp.spatial_vector() + for i in range(6): + value = twist[i] + for j in range(i): + value -= lower[i, j] * forward[j] + forward[i] = value / lower[i, i] + for reverse in range(6): + i = 5 - reverse + value = forward[i] + for j in range(i + 1, 6): + value -= lower[j, i] * solution[j] + solution[i] = value / lower[i, i] + for actuator in range(dofs.shape[0]): + motion = cdof[world, dofs[actuator]] + omega = wp.spatial_top(motion) * ancestors[actuator] + velocity = (wp.spatial_bottom(motion) + wp.cross(omega, offset)) * ancestors[actuator] + column = wp.spatial_vector(velocity[0], velocity[1], velocity[2], omega[0], omega[1], omega[2]) + ctrl[world, actuator] = wp.dot(column, solution) * gear[actuator] + + +# --- control map ------------------------------------------------------------ +class CartesianControl: + """A `SimMPC` control map: world-frame body twists (the first six commands) to joint velocities by damped least squares, with feedback toward `position_ref` and `q_wxyz_ref`; needs scalar joint actuators. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco) + >>> import mujoco + >>> model = mujoco.MjModel.from_xml_string('' + ... '') + >>> control = CartesianControl(model, "b", position_gain=[0, 0, 1]) + >>> control.dofs.shape + (1,) + """ + + def __init__( + self, + model: "mujoco.MjModel", + body: str, + position_ref: Sequence[float] = (0, 0, 0), + q_wxyz_ref: Sequence[float] = (1, 0, 0, 0), + position_gain: Sequence[float] = (0, 0, 0), + rotation_gain: Sequence[float] = (0, 0, 0), + damping: float = 1e-3, + ): + import mujoco # pyright: ignore[reportMissingImports] + + joints = model.actuator_trnid[:, 0] + q_wxyz = np.asarray(q_wxyz_ref, float) + if damping <= 0 or np.any(model.actuator_trntype != 0) or np.any(model.jnt_type[joints] < 2): + raise ValueError("CartesianControl requires scalar joint actuators and positive damping") + if q_wxyz.shape != (4,) or not np.isfinite(q_wxyz).all() or np.linalg.norm(q_wxyz) == 0: + raise ValueError("q_wxyz_ref must be a finite nonzero quaternion") + self.body = model.body(body).id + self.root = int(model.body_rootid[self.body]) + chain = [self.body] # the body and its ancestors, which the joints that move it sit on + while chain[-1]: + chain.append(int(model.body_parentid[chain[-1]])) + self.ancestors = wp.array(np.isin(model.jnt_bodyid[joints], chain).astype(np.float32), dtype=float) + self.dofs = wp.array(model.jnt_dofadr[joints].astype(np.int32), dtype=int) + self.gear = wp.array(model.actuator_gear[:, 0].astype(np.float32), dtype=float) + rotation = np.zeros(9) + mujoco.mju_quat2Mat(rotation, q_wxyz / np.linalg.norm(q_wxyz)) + self.position = wp.vec3(*position_ref) + self.rotation = wp.mat33(*rotation) + self.position_gain = wp.vec3(*position_gain) + self.rotation_gain = wp.vec3(*rotation_gain) + self.damping = damping + + def __call__(self, sim: "Sim", clock: wp.array): + sim.kinematics() # `xpos` and `xmat` of the current state + sim.com_pos() # and `subtree_com` and `cdof` + data = sim.data + inputs = [data.xpos, data.xmat, data.subtree_com, data.cdof, self.dofs, self.ancestors, self.gear, self.body] + inputs += [self.root, self.position, self.rotation, self.position_gain, self.rotation_gain, self.damping] + wp.launch(_compute_cartesian_ctrl_kernel, dim=sim.nworld, inputs=inputs, outputs=[data.ctrl]) + + +__all__ = ["CartesianControl"] diff --git a/src/robokit/helpers/sim_mpc/config.py b/src/robokit/helpers/sim_mpc/config.py index f10002a..a229f16 100644 --- a/src/robokit/helpers/sim_mpc/config.py +++ b/src/robokit/helpers/sim_mpc/config.py @@ -1,7 +1,27 @@ -"""SimMPC settings; build a planner with `SimMPC(MjWarpSim(model, data), ctrl_ref, ctrl_std, costs, config)`.""" +"""SimMPC settings; build a planner with `SimMPC(config.add(cost), MjWarpSim(model, 1), ctrl_ref)`. -from dataclasses import dataclass -from typing import Literal +Predictive sampling: https://arxiv.org/abs/2212.00541. CEM: https://doi.org/10.1023/A:1010091220143. +""" + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Callable, List, Literal, Optional, Sequence, Tuple, Union + +import numpy as np +import warp as wp + +from robokit.terms.task import Task + + +if TYPE_CHECKING: + from robokit.sim import Sim + + +@dataclass(frozen=True) +class SimMPCStage: + """A run of each plan's iterations whose rollouts step at `dt` seconds (None: the simulator's timestep), or along a schedule of `(fraction of the horizon it runs to, dt)`, e.g. `[(0.25, None), (1.0, 0.04)]`; each dt a whole multiple of the timestep, each step's costs weighted by the timesteps it spans.""" + + iters: int + dt: Union[None, float, Sequence[Tuple[float, Optional[float]]]] = None @dataclass(frozen=True) @@ -12,34 +32,83 @@ class SimMPCConfig: >>> config = SimMPCConfig(num_samples=64, horizon_steps=30) >>> config.num_samples, config.node_steps (64, 50) + >>> SimMPCConfig(stages=[SimMPCStage(3, dt=0.04), SimMPCStage(1)]).max_iterations # 3 coarse iterations, 1 fine + 4 """ + terms: List[Tuple[Task, float, Optional[float]]] = field(default_factory=list) + """The cost terms with their running and terminal scales, added with `add`.""" + ctrl_std: Any = 0.1 + """Node noise per command at the first free node, one value or one per command.""" + ctrl_range: Optional[np.ndarray] = None + """`(nu, 2)` bounds of the commands; None: the actuator ranges MuJoCo clamps to.""" + qpos_std: Any = 0.0 + """Each replica's start noise on `qpos`, one value or one per coordinate.""" + qvel_std: Any = 0.0 + """Each replica's start noise on `qvel`, one value or one per dof.""" + control_map: Optional[Callable[["Sim", wp.array], None]] = None + """`control_map(sim, clock)` turns the commands in `sim.data.ctrl` into actuator controls before every step.""" batch_size: int = 1 - """Instances planned at once; they share the model, the config and `ctrl_std`.""" + """Instances planned at once; they share the model and the config.""" num_samples: int = 512 - """Draws per iteration, one of them reserved to score the moved plan.""" + """Draws per iteration, one of them reserved to score the moved plan. A sim step costs about the same up to some hundreds of worlds (about 512 on an RTX 3090) and grows past them, so fill that many before adding iterations.""" num_replicas: int = 1 - """Worlds per draw, which average their costs (e.g. `MjWarpSim`'s `plan_parameters`).""" + """Worlds per draw, which average their costs (e.g. over `qpos_std` noise).""" horizon_steps: int = 300 + """Steps each rollout simulates and scores.""" node_steps: int = 50 """Steps between nodes, the points the control offsets are interpolated through.""" ctrl_steps: int = 100 """Steps executed per plan; a multiple of `node_steps` keeps shifted nodes exact.""" max_iterations: int = 12 + """Sampling iterations per plan, at most; with `stages`, the sum of their iters.""" init_iterations: int = 0 - """If positive, the first plan's iterations instead of `max_iterations`.""" + """If positive, the first plan's iterations instead of `max_iterations`: the stages' last ones, the first stage run longer or cut.""" + stages: Optional[List[SimMPCStage]] = None + """Coarse to fine: the stages each plan's iterations run in order; the moved plans are scored at the simulator's timestep. None: the first rollouts pick `[SimMPCStage(max_iterations, [(0.25, None), (1.0, k * timestep)])]` for the largest k of 4 and 2 whose draws end within 11% of their spread of the fine ones, else one fine stage.""" min_improvement: float = 0.005 """Stop once the best draw beats the plan by under this, `patience` times running.""" patience: int = 2 + """Iterations under `min_improvement` in a row that stop the plan.""" std_growth: float = 4.0 """Node noise grows from `ctrl_std` at the first free node to this multiple at the last.""" noise_decay: float = 1.0 """Iteration `i` scales the node noise by `noise_decay**i`.""" - interpolation: Literal["linear", "cubic", "zero"] = "linear" - """Node interpolation; "zero" also draws the first node.""" + interpolation: Union[Literal["linear", "cubic", "zero"], np.ndarray] = "linear" + """Node interpolation, or a `(steps, num_nodes)` basis of each step's node weights; "zero" also draws the first node.""" + draw_first_node: bool = False + """Draw the first node for any interpolation, so a plan can change the command it executes now (predictive sampling, CEM).""" + wide_ratio: float = 0.0 + """Share of each plan's first-round draws taken at `wide_scale` times the noise, as predictive sampling explores.""" + wide_scale: float = 6.0 + std_range: Optional[Tuple[float, float]] = None + """If set, a plan of one iteration starts from the last plan's refit noise, as CEM carries its spread: one scale of the configured noise (root mean square over the drawn nodes), clipped to this range.""" min_std: float = 1e-3 + """Floor of the node noise.""" + std_gamma: float = 0.5 + """Share of the draws' weighted spread each iteration moves the node noise toward.""" + elite_ratio: float = 0.2 + """Share of the cheapest draws whose cost spread is the temperature and whose weighted mean is the moved plan.""" + best_draw_margin: float = 4.0 + """Execute the best draw instead of the moved plan when the moved plan costs this many temperatures more.""" settle_steps: int = 0 """Unscored zero-control steps before each rollout.""" terminal_scale: float = 10.0 - """Cost scale at the horizon's last step, unless a term sets its own.""" + """Cost scale at the horizon's last step, unless `add` sets a term's own.""" seed: int = 0 + """Seed of the node draws and the replicas' initial-state noise.""" + cuda_graph_mode: Literal["none", "step"] = "step" + """"step" replays one captured graph per sim step; "none" launches every kernel.""" + planner: Literal["mppi", "ilqr"] = "mppi" + """"ilqr": `ILQROptimizer` refines commands held for `node_steps`, `max_iterations` times a plan, instead of nodes.""" + ilqr: Optional[Any] = None + """"ilqr"'s `ILQROptimizerConfig`, but `max_iter`; None: damped (robot costs seldom penalize controls) and cautious.""" + + def __post_init__(self): + if self.stages is not None: + object.__setattr__(self, "max_iterations", sum(stage.iters for stage in self.stages)) + + def add(self, term: Task, running_scale: float = 1.0, terminal_scale: Optional[float] = None) -> "SimMPCConfig": + """Add a cost term, scaled by `running_scale` per step and by `terminal_scale` (default: the config's) at the horizon's last step; `running_scale=0` makes a terminal-only cost.""" + self.terms.append((term, running_scale, terminal_scale)) + return self diff --git a/src/robokit/helpers/sim_mpc/mjwarp.py b/src/robokit/helpers/sim_mpc/mjwarp.py deleted file mode 100644 index d46762d..0000000 --- a/src/robokit/helpers/sim_mpc/mjwarp.py +++ /dev/null @@ -1,512 +0,0 @@ -# pyright: reportMissingImports=false -# pyright: reportGeneralTypeIssues=false -# pyright: reportArgumentType=false -# pyright: reportIndexIssue=false -# pyright: reportAttributeAccessIssue=false -# pyright: reportCallIssue=false -# pyright: reportOperatorIssue=false -"""MuJoCo Warp binding for `SimMPC`, and `CartesianControl`, a control map for it.""" - -import copy -from pathlib import Path -from typing import Any, Callable, Dict, Optional, Sequence, Tuple, Union - -import mujoco -import mujoco_warp as mjwarp -import numpy as np -import warp as wp - -from robokit.terms.simulation import SimContext - - -# --- kernels ---------------------------------------------------------------- -@wp.kernel -def _set_broadcast_state_kernel( - qpos: wp.array2d(dtype=float), - qvel: wp.array2d(dtype=float), - act: wp.array2d(dtype=float), - warmstart: wp.array2d(dtype=float), - qpos_std: wp.array(dtype=float), - qvel_std: wp.array(dtype=float), - num_replicas: int, - instance_worlds: int, - seed: int, - clock: wp.array(dtype=int), - iteration: wp.array(dtype=int), - out_qpos: wp.array2d(dtype=float), - out_qvel: wp.array2d(dtype=float), - out_act: wp.array2d(dtype=float), - out_warmstart: wp.array2d(dtype=float), -): - w = wp.tid() - b = w // instance_worlds - rng = wp.rand_init(seed + clock[0], w % num_replicas + num_replicas * iteration[0]) - for i in range(qpos.shape[1]): - out_qpos[w, i] = qpos[b, i] + qpos_std[i] * wp.randn(rng) - for i in range(qvel.shape[1]): - out_qvel[w, i] = qvel[b, i] + qvel_std[i] * wp.randn(rng) - out_warmstart[w, i] = warmstart[b, i] - for i in range(act.shape[1]): - out_act[w, i] = act[b, i] - - -@wp.kernel -def _set_clipped_ctrl_kernel(limits: wp.array2d(dtype=float), ctrl: wp.array2d(dtype=float)): - w, u = wp.tid() # pyright: ignore[reportAssignmentType] - ctrl[w, u] = wp.clamp(ctrl[w, u], limits[u, 0], limits[u, 1]) - - -@wp.kernel -def _set_record_kernel( - clock: wp.array(dtype=int), - time: wp.array(dtype=float), - qpos: wp.array2d(dtype=float), - qvel: wp.array2d(dtype=float), - ctrl: wp.array2d(dtype=float), - sensordata: wp.array2d(dtype=float), - stepped: bool, - record: wp.array3d(dtype=float), -): - w = wp.tid() - t, nq, nv, nu = clock[1], qpos.shape[1], qvel.shape[1], ctrl.shape[1] - if stepped: # MuJoCo evaluates sensors on the state before integrating, so they belong to row t too - for i in range(sensordata.shape[1]): - record[w, t, 1 + nq + nv + nu + i] = sensordata[w, i] - return - record[w, t, 0] = time[w] # row t: the executed world's state at sim step t and the ctrl applied during it - for i in range(nq): - record[w, t, 1 + i] = qpos[w, i] - for i in range(nv): - record[w, t, 1 + nq + i] = qvel[w, i] - for i in range(nu): - record[w, t, 1 + nq + nv + i] = ctrl[w, i] - - -@wp.kernel -def _compute_cartesian_ctrl_kernel( - xpos: wp.array2d(dtype=wp.vec3), - xmat: wp.array2d(dtype=wp.mat33), - subtree_com: wp.array2d(dtype=wp.vec3), - cdof: wp.array2d(dtype=wp.spatial_vector), - dofs: wp.array(dtype=int), - ancestors: wp.array(dtype=float), - gear: wp.array(dtype=float), - body: int, - root: int, - target_position: wp.vec3, - target_rotation: wp.mat33, - position_gain: wp.vec3, - rotation_gain: wp.vec3, - damping: float, - ctrl: wp.array2d(dtype=float), -): - w = wp.tid() - offset = xpos[w, body] - subtree_com[w, root] - error_q = wp.quat_from_matrix(target_rotation * wp.transpose(xmat[w, body])) - if error_q[3] < 0.0: - error_q = -error_q - angular = wp.vec3(error_q[0], error_q[1], error_q[2]) - length = wp.length(angular) - angular *= 2.0 * wp.atan2(length, error_q[3]) / wp.max(length, 1.0e-9) - linear = target_position - xpos[w, body] - twist = wp.spatial_vector() - for i in range(3): - twist[i] = position_gain[i] * linear[i] - twist[i + 3] = rotation_gain[i] * angular[i] - for i in range(wp.min(6, ctrl.shape[1])): - twist[i] += ctrl[w, i] - matrix = wp.spatial_matrix() - for u in range(dofs.shape[0]): - motion = cdof[w, dofs[u]] - rot = wp.spatial_top(motion) * ancestors[u] - pos = (wp.spatial_bottom(motion) + wp.cross(rot, offset)) * ancestors[u] - column = wp.spatial_vector(pos[0], pos[1], pos[2], rot[0], rot[1], rot[2]) - for i in range(6): - for j in range(6): - matrix[i, j] += column[i] * column[j] - # Damped 6x6 Cholesky solve; no fixed robot size or matrix inverse is needed. - lower = wp.spatial_matrix() - for j in range(6): - diagonal = matrix[j, j] + damping - for k in range(j): - diagonal -= lower[j, k] * lower[j, k] - lower[j, j] = wp.sqrt(wp.max(diagonal, 1.0e-12)) - for i in range(j + 1, 6): - value = matrix[i, j] - for k in range(j): - value -= lower[i, k] * lower[j, k] - lower[i, j] = value / lower[j, j] - forward, solution = wp.spatial_vector(), wp.spatial_vector() - for i in range(6): - value = twist[i] - for j in range(i): - value -= lower[i, j] * forward[j] - forward[i] = value / lower[i, i] - for rev in range(6): - i = 5 - rev - value = forward[i] - for j in range(i + 1, 6): - value -= lower[j, i] * solution[j] - solution[i] = value / lower[i, i] - for u in range(dofs.shape[0]): - motion = cdof[w, dofs[u]] - rot = wp.spatial_top(motion) * ancestors[u] - pos = (wp.spatial_bottom(motion) + wp.cross(rot, offset)) * ancestors[u] - column = wp.spatial_vector(pos[0], pos[1], pos[2], rot[0], rot[1], rot[2]) - ctrl[w, u] = wp.dot(column, solution) * gear[u] - - -# --- binding ---------------------------------------------------------------- -class MjWarpSim: - """Run `SimMPC`'s worlds on MuJoCo Warp: rollouts and validation step `plan_model`, execution steps `model`. - - Example: - >>> # xdoctest: +REQUIRES(module:mujoco_warp) - >>> model = mujoco.MjModel.from_xml_string( - ... '' - ... '' - ... ) - >>> sim = MjWarpSim(model, mujoco.MjData(model), nconmax=8, njmax=16) - >>> sim.build(batch_size=2, num_samples=4, num_replicas=1, ctrl_steps=1, settle_steps=0, seed=0) - >>> {name: data.nworld for name, data in sim.data.items()} - {'execution': 2, 'rollout': 8, 'validation': 2} - """ - - def __init__( - self, - model: mujoco.MjModel, - data: Union[mujoco.MjData, Sequence[mujoco.MjData]], - plan_model: Optional[mujoco.MjModel] = None, - plan_parameters: Optional[Dict[str, np.ndarray]] = None, - initial_state_std: Optional[Dict[str, np.ndarray]] = None, - control_map: Optional[Callable[[mjwarp.Model, mjwarp.Data, wp.array], None]] = None, - nconmax: int = 120, - njmax: int = 500, - plan_ls_parallel: int = 0, - cpu_execute: bool = False, - instance_parameters: Optional[Dict[str, np.ndarray]] = None, - ): - plan = model if plan_model is None else plan_model - if [getattr(plan, k) for k in ("nq", "nv", "nu", "nsensordata")] != [ - model.nq, - model.nv, - model.nu, - model.nsensordata, - ]: - raise ValueError("plan_model must match model's nq, nv, nu and nsensordata") - if cpu_execute and (control_map is not None or instance_parameters): - raise ValueError("cpu_execute cannot replay a control_map or instance_parameters") - self.mj_model, self.mj_plan = model, plan - self.mj_data = [data] if isinstance(data, mujoco.MjData) else list(data) - self.plan_parameters, self.control_map, self.cpu_execute = plan_parameters or {}, control_map, cpu_execute - self.instance_parameters = instance_parameters or {} - self.nconmax, self.njmax, self.nu, self.device = nconmax, njmax, model.nu, wp.get_device() - self.timestep, self.initial_time = model.opt.timestep, self.mj_data[0].time - limited = model.actuator_ctrllimited.astype(bool) - if model.opt.disableflags & mujoco.mjtDisableBit.mjDSBL_CLAMPCTRL: - limited[:] = False - limits = np.where(limited[:, None], model.actuator_ctrlrange, [-np.inf, np.inf]) - self.ctrl_limits = wp.array(limits.astype(np.float32), dtype=float) - initial_state_std = initial_state_std or {} - self.qpos_std = wp.array(np.broadcast_to(initial_state_std.get("qpos", 0.0), model.nq), dtype=float) - self.qvel_std = wp.array(np.broadcast_to(initial_state_std.get("qvel", 0.0), model.nv), dtype=float) - self.model = mjwarp.put_model(model) - self.plan_model = mjwarp.put_model(plan) - if hasattr(mjwarp, "OverflowType"): # newer MuJoCo Warp warns on every capped solve; scenes cap them on purpose - quiet = ~int(mjwarp.OverflowType.ITERATIONS | mjwarp.OverflowType.LS_ITERATIONS) - self.model.opt.warn_overflow &= quiet - self.plan_model.opt.warn_overflow &= quiet - if plan_ls_parallel > 0: - self.plan_model.opt.ls_parallel, self.plan_model.opt.ls_iterations = True, plan_ls_parallel - self.joints = tuple( - wp.array(np.asarray(x, np.int32), dtype=int) for x in (model.jnt_type, model.jnt_qposadr, model.jnt_dofadr) - ) - self.sensors = [ - (model.sensor(i).name, int(model.sensor_adr[i]), int(model.sensor_dim[i])) for i in range(model.nsensor) - ] - self.sizes = dict(time=1, qpos=model.nq, qvel=model.nv, ctrl=model.nu, sensordata=model.nsensordata) - - def build( - self, - batch_size: int, - num_samples: int, - num_replicas: int, - ctrl_steps: int, - settle_steps: int, - seed: int, - ): - """Allocate the world sets of `SimBinding.build`; each world gets its instance's `instance_parameters` and, - planning, its replica's `plan_parameters` (`(num_replicas, ...)`, or `(batch_size, num_replicas, ...)`).""" - datas = self.mj_data * batch_size if len(self.mj_data) == 1 else self.mj_data - if len(datas) != batch_size: - raise ValueError("data must be one MjData or one per instance") - self.datas = datas - self.instance_worlds = dict(execution=1, rollout=num_samples * num_replicas, validation=num_replicas) - self.models = dict(execution=self.model, rollout=self.plan_model, validation=self.plan_model) - if self.instance_parameters or self.plan_parameters: # each world set's own copy, with every world's values - self.models = {name: copy.copy(model) for name, model in self.models.items()} - for worlds, model in self.models.items(): - n = self.instance_worlds[worlds] - world, plan = np.arange(batch_size * n), self.plan_parameters if worlds != "execution" else {} - for name, values in {**self.instance_parameters, **plan}.items(): - shape = getattr(model, name).numpy().shape[1:] # also MuJoCo's layout, e.g. geom_aabb - if name in self.instance_parameters and name in self.plan_parameters: - raise ValueError(f"{name!r} cannot be both an instance and a plan parameter") - if name in plan and np.shape(values) not in [ - (num_replicas, *shape), - (batch_size, num_replicas, *shape), - ]: - raise ValueError(f"plan_parameters[{name!r}] must have one model value per replica (and instance)") - if name in plan: - values = np.broadcast_to(values, (batch_size, num_replicas, *shape))[ - world // n, world % num_replicas - ] - elif len(values) == batch_size and np.size(values) == batch_size * np.prod(shape): - values = np.reshape(values, (batch_size, *shape))[world // n] - else: - raise ValueError(f"instance_parameters[{name!r}] must have one model value per instance") - setattr(model, name, wp.array(np.ascontiguousarray(values), dtype=getattr(model, name).dtype)) - self.data = {"execution": self._put(self.mj_model, batch_size)} - if len(self.mj_data) > 1: # one initial state per instance - for name in ("qpos", "qvel", "act", "qacc_warmstart"): - getattr(self.data["execution"], name).assign(np.stack([getattr(d, name) for d in datas])) - self.set_active_instances(batch_size) - self.num_replicas, self.settle_steps, self.seed = num_replicas, settle_steps, seed - self.record = wp.zeros((batch_size, ctrl_steps, sum(self.sizes.values())), dtype=float) - self.cpu = [copy.copy(d) for d in datas] if self.cpu_execute else None - - def _put(self, model: mujoco.MjModel, nworld: int) -> mjwarp.Data: - return mjwarp.put_data(model, self.datas[0], nworld=nworld, nconmax=self.nconmax, njmax=self.njmax) - - def set_active_instances(self, num_instances: int): - """Rebuild the rollout and validation worlds for the first `num_instances` instances.""" - for name in ["rollout", "validation"]: - self.data[name] = self._put(self.mj_plan, num_instances * self.instance_worlds[name]) - - def context(self, worlds: str) -> Dict[SimContext, Any]: - """Return the `SimContext` arrays of a world set and the model's layout.""" - d, m = self.data[worlds], self.mj_model - return { - SimContext.QPOS: d.qpos, - SimContext.QVEL: d.qvel, - SimContext.CTRL: d.ctrl, - SimContext.SENSORDATA: d.sensordata, - SimContext.BODY_POSITION: d.xpos, - SimContext.BODY_ROTATION: d.xmat, - SimContext.CONTACTS: (d.nacon, d.contact.worldid, d.contact.geom, d.contact.dist, d.contact.pos), - SimContext.JOINTS: self.joints, - SimContext.SENSORS: self.sensors, - SimContext.BODIES: [m.body(i).name for i in range(m.nbody)], - SimContext.GEOMS: [m.geom(i).name for i in range(m.ngeom)], - } - - def reset(self, worlds: str, clock: wp.array, iteration: wp.array): - """Copy the executed states into a world set with replica noise, then settle it with zero controls.""" - d, e = self.data[worlds], self.data["execution"] - wp.launch( - _set_broadcast_state_kernel, - dim=d.nworld, - inputs=[e.qpos, e.qvel, e.act, e.qacc_warmstart, self.qpos_std, self.qvel_std, self.num_replicas] - + [self.instance_worlds[worlds], self.seed, clock, iteration], - outputs=[d.qpos, d.qvel, d.act, d.qacc_warmstart], - ) - if self.settle_steps: - d.ctrl.zero_() - for _ in range(self.settle_steps): - mjwarp.step(self.models[worlds], d) - - def set_time(self, worlds: str, t0: int): - """Set a world set's time to that of sim step `t0`.""" - self.data[worlds].time.fill_(self.initial_time + t0 * self.timestep) - - def step(self, worlds: str, clock: wp.array): - """Map, clip and apply the commands, then step; the executed worlds record their rows around the step.""" - d = self.data[worlds] - model = self.models[worlds] - if self.control_map is not None: - self.control_map(model, d, clock) - wp.launch(_set_clipped_ctrl_kernel, dim=d.ctrl.shape, inputs=[self.ctrl_limits], outputs=[d.ctrl]) - fields = [clock, d.time, d.qpos, d.qvel, d.ctrl, d.sensordata] - if worlds == "execution": - wp.launch(_set_record_kernel, dim=d.nworld, inputs=[*fields, False], outputs=[self.record]) - mjwarp.step(model, d) - if worlds == "execution": - wp.launch(_set_record_kernel, dim=d.nworld, inputs=[*fields, True], outputs=[self.record]) - - def read_execution(self) -> Dict[str, np.ndarray]: - """Return the executed rows; with `cpu_execute`, replay their controls in MuJoCo and plan from its states.""" - record = self.record.numpy().copy() # on the CPU, numpy() is a view of the reused buffer - if self.cpu is not None: - m, e = self.mj_model, self.data["execution"] - nq, nv, nu = m.nq, m.nv, m.nu - for d, rows in zip(self.cpu, record): - for row in rows: - row[: 1 + nq + nv] = np.concatenate([[d.time], d.qpos, d.qvel]) - d.ctrl[:] = row[1 + nq + nv : 1 + nq + nv + nu] - mujoco.mj_step(m, d) - row[1 + nq + nv + nu :] = d.sensordata # evaluated before integrating, as on the GPU - for name in ("qpos", "qvel", "act", "qacc_warmstart"): - getattr(e, name).assign(np.stack([getattr(d, name) for d in self.cpu])) - e.time.assign(np.array([d.time for d in self.cpu])) - split = np.split(record, np.cumsum(list(self.sizes.values()))[:-1], axis=2) - rows = dict(zip(self.sizes, split)) - rows["time"] = rows["time"][..., 0] - return rows - - -def batch_models(specs: Sequence[mujoco.MjSpec]) -> Tuple[mujoco.MjModel, Dict[str, np.ndarray]]: - """One model for instances whose scenes differ in geoms, meshes, inertias, sites and contact pairs, and each - instance's values of it for `MjWarpSim(instance_parameters=...)`. - - The instance with the most geoms is the template: the others' meshes join it and their geoms match its geoms by - name (unnamed: by place on their body), so geom ids are the template's. A geom or contact pair an instance lacks - never collides there (a margin of -1 km; MuJoCo Warp detects contacts within margin + gap), though rays and - renders still see it. Instances must match in bodies, joints, actuators, sensors and sites, and each geom and - pair its template's in all but the batched values. - - Example: - >>> # xdoctest: +REQUIRES(module:mujoco_warp) - >>> xml = '{}' - >>> one = mujoco.MjSpec.from_string(xml.format("")) - >>> two = mujoco.MjSpec.from_string(xml.format('')) - >>> model, parameters = batch_models([one, two]) - >>> model.ngeom, parameters["geom_margin"].tolist() - (2, [[0.0, -1000.0], [0.0, 0.0]]) - """ - models, off = [s.compile() for s in specs], -1e3 # a margin that keeps a geom or pair out of every collision - sizes = ["nq", "nv", "nu", "na", "nbody", "njnt", "nsite", "nsensordata", "neq", "ntendon"] - if any(getattr(m, k) != getattr(models[0], k) for m in models for k in sizes): - raise ValueError("batched models must match in bodies, joints, actuators, sensors and sites") - t = int(np.argmax([m.ngeom for m in models])) - T, spec = models[t], specs[t].copy() - if any((m.body_geomnum > T.body_geomnum).any() for m in models): - raise ValueError("one instance must have the most geoms on every body") - vert = lambda m, k: m.mesh_vert[m.mesh_vertadr[k] : m.mesh_vertadr[k] + m.mesh_vertnum[k]] - names = lambda m: [m.mesh(k).name for k in range(m.nmesh)] - shared = lambda m, k: m.mesh(k).name in names(T) and np.array_equal(vert(m, k), vert(T, T.mesh(m.mesh(k).name).id)) - for i, (s, m) in enumerate(zip(specs, models)): # the other instances' own meshes join as `__` - for k in [k for k in range(m.nmesh) if i != t and not shared(m, k)]: - mesh, fields = s.mesh(m.mesh(k).name), ["content_type", "scale", "refpos", "refquat", "inertia", - "maxhullvert", "smoothnormal", "uservert", "userface"] # fmt: skip - file = str(Path(s.modelfiledir, s.meshdir, mesh.file).resolve()) if mesh.file else "" - spec.add_mesh(name=f"{mesh.name}__{i}", file=file, **{f: getattr(mesh, f) for f in fields}) - bit = next(1 << b for b in range(31) if not np.bitwise_or.reduce([*T.geom_contype, *T.geom_conaffinity]) & 1 << b) - for mesh in spec.meshes[T.nmesh :]: # a world geom that collides with nothing, so MuJoCo builds its collision data - spec.worldbody.add_geom( - type=mujoco.mjtGeom.mjGEOM_MESH, meshname=mesh.name, contype=bit, conaffinity=0, group=5 - ) - model = spec.compile() - batched = ["geom_dataid", "geom_pos", "geom_quat", "geom_size", "geom_aabb", "geom_rbound", "geom_friction", - "geom_margin", "geom_gap", "geom_solmix", "geom_solref", "geom_solimp", "body_mass", "body_ipos", - "body_iquat", "body_inertia", "body_subtreemass", "body_invweight0", "dof_invweight0", "site_pos", - "pair_solref", "pair_solreffriction", "pair_solimp", "pair_margin", "pair_gap", "pair_friction"] # fmt: skip - statics = lambda m, kind: [f for f in dir(m) if f.startswith(kind) and f not in batched and "sameframe" not in f - and f not in ["geom_rgba", "geom_matid", "pair_geom1", "pair_geom2"]] # fmt: skip - skip = ("_", "geom_", "mesh_", "pair_", "bvh_", "oct_", "name", "cam_", "light_", "body_geom", "body_bvh", - "body_con", "dof_M0", "dof_length") # fmt: skip - values = {f: np.repeat(getattr(model, f)[None], len(models), 0) for f in batched} - pairs = {(g1, g2): p for p, (g1, g2) in enumerate(zip(model.pair_geom1, model.pair_geom2))} - geoms = {model.geom(k).name: k for k in range(model.ngeom)} - is_mesh = model.geom_type == mujoco.mjtGeom.mjGEOM_MESH - for i, m in enumerate(models): - g = model.body_geomadr[m.geom_bodyid] + np.arange(m.ngeom) - m.body_geomadr[m.geom_bodyid] # its geoms there: - g = np.array([geoms.get(m.geom(k).name, -1) if m.geom(k).name else g[k] for k in range(m.ngeom)]) # by name - if len(set(g)) < m.ngeom or -1 in g or (model.geom_bodyid[g] != m.geom_bodyid).any(): - raise ValueError(f"instance {i}'s geoms do not each match a template geom on their body") - p = np.array([pairs.get((g[a], g[b]), -1) for a, b in zip(m.pair_geom1, m.pair_geom2)], int) - bad = [f for f in statics(m, "geom_") if not np.array_equal(getattr(m, f), getattr(model, f)[g])] - bad += ( - ["pairs"] - if -1 in p - else [f for f in statics(m, "pair_") if not np.array_equal(getattr(m, f), getattr(model, f)[p])] - ) - bad += [f for f in dir(m) if not f.startswith(skip) and f not in batched and "sameframe" not in f - and isinstance(x := getattr(m, f), np.ndarray) and x.shape == getattr(model, f).shape - and not np.array_equal(x, getattr(model, f))] # fmt: skip - if bad: - raise ValueError(f"instance {i} differs from the template beyond geoms, inertias, sites and pairs: {bad}") - for f in batched: - index = g if f.startswith("geom_") else p if f.startswith("pair_") else slice(None) - values[f][i][index] = getattr(m, f) - meshes = np.array([model.mesh(n if i == t or shared(m, k) else f"{n}__{i}").id for k, n in enumerate(names(m))]) - values["geom_dataid"][i][g[is_mesh[g]]] = meshes[m.geom_dataid[is_mesh[g]]] - lacks = np.setdiff1d(np.arange(model.ngeom), g) # the geoms and pairs it lacks never collide - values["geom_margin"][i][lacks], values["geom_gap"][i][lacks] = off, 0 - lacks = np.setdiff1d(np.arange(model.npair), p) - values["pair_margin"][i][lacks], values["pair_gap"][i][lacks] = off, 0 - return model, {f: x for f, x in values.items() if not (x == x[:1]).all()} - - -# --- control maps ----------------------------------------------------------- -class CartesianControl: - """Map world-frame body twists (the first six commands) to joint velocities by damped least squares. - - Example: - >>> # xdoctest: +REQUIRES(module:mujoco_warp) - >>> model = mujoco.MjModel.from_xml_string('' - ... '') - >>> control = CartesianControl(model, "b", position_gain=[0, 0, 1]) - >>> control.dofs.shape - (1,) - """ - - def __init__( - self, - model: mujoco.MjModel, - body: str, - position_ref: Sequence[float] = (0, 0, 0), - q_wxyz_ref: Sequence[float] = (1, 0, 0, 0), - position_gain: Sequence[float] = (0, 0, 0), - rotation_gain: Sequence[float] = (0, 0, 0), - damping: float = 1e-3, - ): - joints = model.actuator_trnid[:, 0] - if damping <= 0 or np.any(model.actuator_trntype != 0) or np.any(model.jnt_type[joints] < 2): - raise ValueError("CartesianControl requires scalar joint actuators and positive damping") - self.body = model.body(body).id - self.root = int(model.body_rootid[self.body]) - chain, b = set(), self.body - while b: - chain.add(b) - b = int(model.body_parentid[b]) - self.ancestors = wp.array( - np.array([int(model.jnt_bodyid[j]) in chain for j in joints], np.float32), dtype=float - ) - self.dofs = wp.array(model.jnt_dofadr[joints].astype(np.int32), dtype=int) - self.gear = wp.array(model.actuator_gear[:, 0].astype(np.float32), dtype=float) - rotation = np.zeros(9) - q_wxyz = np.asarray(q_wxyz_ref, float) - if q_wxyz.shape != (4,) or not np.isfinite(q_wxyz).all() or np.linalg.norm(q_wxyz) == 0: - raise ValueError("q_wxyz_ref must be a finite nonzero quaternion") - mujoco.mju_quat2Mat(rotation, q_wxyz / np.linalg.norm(q_wxyz)) - self.position, self.rotation = wp.vec3(*position_ref), wp.mat33(*rotation) - self.position_gain, self.rotation_gain = wp.vec3(*position_gain), wp.vec3(*rotation_gain) - self.damping = damping - - def __call__(self, model: mjwarp.Model, data: mjwarp.Data, clock: wp.array): - mjwarp.kinematics(model, data) - mjwarp.com_pos(model, data) - wp.launch( - _compute_cartesian_ctrl_kernel, - dim=data.nworld, - inputs=[ - data.xpos, - data.xmat, - data.subtree_com, - data.cdof, - self.dofs, - self.ancestors, - self.gear, - self.body, - self.root, - self.position, - self.rotation, - self.position_gain, - self.rotation_gain, - self.damping, - ], - outputs=[data.ctrl], - ) - - -__all__ = ["CartesianControl", "MjWarpSim", "batch_models"] diff --git a/src/robokit/helpers/sim_mpc/newton.py b/src/robokit/helpers/sim_mpc/newton.py deleted file mode 100644 index a8bb77d..0000000 --- a/src/robokit/helpers/sim_mpc/newton.py +++ /dev/null @@ -1,281 +0,0 @@ -# pyright: reportMissingImports=false -# pyright: reportGeneralTypeIssues=false -# pyright: reportArgumentType=false -# pyright: reportIndexIssue=false -# pyright: reportAttributeAccessIssue=false -# pyright: reportCallIssue=false -# pyright: reportOperatorIssue=false -"""Newton binding for `SimMPC`: an MJCF scene on Newton's Featherstone solver, one joint per body, MuJoCo's layout.""" - -import xml.etree.ElementTree as ET -from pathlib import Path -from types import SimpleNamespace -from typing import Any, Dict, Optional, Union - -import mujoco -import newton -import numpy as np -import warp as wp - -from robokit.terms.simulation import SimContext - - -# --- kernels ---------------------------------------------------------------- -@wp.kernel -def _set_broadcast_state_kernel( - qpos: wp.array2d(dtype=float), - qvel: wp.array2d(dtype=float), - instance_worlds: int, - out_qpos: wp.array2d(dtype=float), - out_qvel: wp.array2d(dtype=float), -): - w, i = wp.tid() # pyright: ignore[reportAssignmentType] - out_qpos[w, i] = qpos[w // instance_worlds, i] - out_qvel[w, i] = qvel[w // instance_worlds, i] - - -@wp.kernel -def _compute_sensors_kernel( - body_q: wp.array2d(dtype=wp.transform), - body_qd: wp.array2d(dtype=wp.spatial_vector), - kind: wp.array(dtype=int), - body: wp.array(dtype=int), - adr: wp.array(dtype=int), - subtree_mass: wp.array2d(dtype=float), - sensordata: wp.array2d(dtype=float), -): - w, s = wp.tid() # pyright: ignore[reportAssignmentType] - value = wp.transform_get_translation(body_q[w, body[s]]) # framepos - if kind[s] == 1: # framezaxis - value = wp.quat_rotate(wp.transform_get_rotation(body_q[w, body[s]]), wp.vec3(0.0, 0.0, 1.0)) - if kind[s] == 2: # subtreelinvel: the subtree's mass-weighted centre-of-mass velocity - momentum, mass = wp.vec3(0.0), float(0.0) - for b in range(subtree_mass.shape[1]): - momentum += subtree_mass[s, b] * wp.spatial_top(body_qd[w, b]) - mass += subtree_mass[s, b] - value = momentum / mass - for i in range(3): - sensordata[w, adr[s] + i] = value[i] - - -@wp.kernel -def _set_joint_force_kernel( - limits: wp.array2d(dtype=float), - gain: wp.array(dtype=float), - dof: wp.array(dtype=int), - ctrl: wp.array2d(dtype=float), - joint_f: wp.array2d(dtype=float), -): - w, u = wp.tid() # pyright: ignore[reportAssignmentType] - ctrl[w, u] = wp.clamp(ctrl[w, u], limits[u, 0], limits[u, 1]) - joint_f[w, dof[u]] = gain[u] * ctrl[w, u] - - -@wp.kernel -def _set_record_kernel( - clock: wp.array(dtype=int), - timestep: float, - qpos: wp.array2d(dtype=float), - qvel: wp.array2d(dtype=float), - ctrl: wp.array2d(dtype=float), - sensordata: wp.array2d(dtype=float), - time: wp.array(dtype=float), - record: wp.array3d(dtype=float), -): - w = wp.tid() - t, nq, nv, nu = clock[1], qpos.shape[1], qvel.shape[1], ctrl.shape[1] - record[w, t, 0] = time[w] # row t: the state at sim step t, the ctrl applied during it, its sensors - for i in range(nq): - record[w, t, 1 + i] = qpos[w, i] - for i in range(nv): - record[w, t, 1 + nq + i] = qvel[w, i] - for i in range(nu): - record[w, t, 1 + nq + nv + i] = ctrl[w, i] - for i in range(sensordata.shape[1]): - record[w, t, 1 + nq + nv + nu + i] = sensordata[w, i] - time[w] = time[w] + timestep - - -# --- binding ---------------------------------------------------------------- -def _split_joints(xml: str, mass: float = 1e-6) -> str: - """Give every MJCF body at most one joint: a body's later joints move onto nested links of `mass`.""" - root = ET.fromstring(xml) - for body in list(root.iter("body")): - joints = body.findall("joint") - if len(joints) < 2: - continue - rest = [c for c in body if c not in joints] - for c in joints[1:] + rest: - body.remove(c) - link, name = body, body.get("name", "") - for joint in joints[1:]: - ET.SubElement(link, "inertial", pos="0 0 0", mass=str(mass), diaginertia=f"{mass} {mass} {mass}") - link = ET.SubElement(link, "body", name=f"{name}_{joint.get('name')}") - link.append(joint) - link.extend(rest) - body.set("name", f"{name}_{joints[0].get('name')}") - link.set("name", name) # sensors and terms still name the innermost body - return ET.tostring(root, encoding="unicode") - - -class NewtonSim: - """Run `SimMPC`'s worlds on Newton's `SolverFeatherstone` with penalty contacts and joint limits. - - Example: - >>> # xdoctest: +REQUIRES(module:newton) - >>> import tempfile - >>> path = Path(tempfile.mkdtemp()) / "scene.xml" - >>> _ = path.write_text( - ... '' - ... '' - ... '' - ... ) - >>> sim = NewtonSim(path, np.zeros(2), np.zeros(2)) - >>> sim.build(batch_size=2, num_samples=4, num_replicas=1, ctrl_steps=1, settle_steps=0, seed=0) - >>> {name: worlds.qpos.shape for name, worlds in sim.sets.items()}, sim.sensors - ({'execution': (2, 2), 'rollout': (8, 2), 'validation': (2, 2)}, [('p', 0, 3)]) - """ - - def __init__( - self, - path: Union[str, Path], - qpos: np.ndarray, - qvel: np.ndarray, - contact_ke: float = 2e4, - contact_kd: float = 200.0, - contact_kf: float = 200.0, - limit_ke: float = 2e3, - limit_kd: float = 5.0, - ): - xml = _split_joints(Path(path).read_text()) - m = self.mj = mujoco.MjModel.from_xml_string(xml) - sensor = mujoco.mjtSensor - kinds = {int(sensor.mjSENS_FRAMEPOS): 0, int(sensor.mjSENS_FRAMEZAXIS): 1, int(sensor.mjSENS_SUBTREELINVEL): 2} - frame = m.sensor_type != sensor.mjSENS_SUBTREELINVEL - unsupported = ~np.isin(m.sensor_type, list(kinds)) | frame & (m.sensor_objtype != mujoco.mjtObj.mjOBJ_XBODY) - actuators = np.stack([m.actuator_trntype, m.actuator_dyntype, m.actuator_gaintype, m.actuator_biastype]) - if np.any(m.jnt_type < 2) or np.any(actuators != 0) or np.any(unsupported | (m.sensor_refid >= 0)): - raise ValueError("NewtonSim supports slide/hinge joints, gain-only joint actuators and the listed sensors") - b = self.builder = newton.ModelBuilder() - b.add_mjcf(xml) - b.shape_material_ke[:] = [contact_ke] * len(b.shape_material_ke) - b.shape_material_kd[:] = [contact_kd] * len(b.shape_material_kd) - b.shape_material_kf[:] = [contact_kf] * len(b.shape_material_kf) - b.joint_limit_ke[:] = [limit_ke] * len(b.joint_limit_ke) - b.joint_limit_kd[:] = [limit_kd] * len(b.joint_limit_kd) - self.qpos, self.qvel = np.atleast_2d(qpos), np.atleast_2d(qvel) - self.nu, self.device, self.timestep = m.nu, wp.get_device(), m.opt.timestep - limited = m.actuator_ctrllimited.astype(bool)[:, None] - self.limits = wp.array(np.where(limited, m.actuator_ctrlrange, [-np.inf, np.inf]), dtype=float) - self.gain = wp.array(m.actuator_gear[:, 0] * m.actuator_gainprm[:, 0], dtype=float) - self.dof = wp.array(m.jnt_dofadr[m.actuator_trnid[:, 0]], dtype=int) - self.joints = tuple(wp.array(x, dtype=int) for x in (m.jnt_type, m.jnt_qposadr, m.jnt_dofadr)) - self.sensors = [(m.sensor(i).name, int(m.sensor_adr[i]), int(m.sensor_dim[i])) for i in range(m.nsensor)] - subtree_mass = np.zeros((m.nsensor, m.nbody - 1)) # Newton's body b is MuJoCo's b + 1 (no world body) - for s, root in enumerate(m.sensor_objid): - for c in range(1, m.nbody): - a = c - while a > 0 and a != root: - a = m.body_parentid[a] - subtree_mass[s, c - 1] = m.body_mass[c] * (a == root) - self.kind = wp.array([kinds[int(t)] for t in m.sensor_type], dtype=int) - self.body, self.adr = wp.array(m.sensor_objid - 1, dtype=int), wp.array(m.sensor_adr, dtype=int) - self.subtree_mass = wp.array(subtree_mass, dtype=float) - self.sizes = dict(time=1, qpos=m.nq, qvel=m.nv, ctrl=m.nu, sensordata=m.nsensordata) - - def _worlds(self, n: int) -> SimpleNamespace: - """`n` copies of the scene with their solver, contacts and MuJoCo-layout views.""" - scene = newton.ModelBuilder() - scene.replicate(self.builder, n) - model = scene.finalize() - state, control, pipeline = model.state(), model.control(), newton.CollisionPipeline(model) - w = SimpleNamespace(model=model, state=state, control=control, pipeline=pipeline, contacts=pipeline.contacts()) - w.solver = newton.solvers.SolverFeatherstone(model, angular_damping=0.0) - w.qpos, w.qvel = state.joint_q.reshape((n, -1)), state.joint_qd.reshape((n, -1)) - w.body_q, w.body_qd = state.body_q.reshape((n, -1)), state.body_qd.reshape((n, -1)) - w.joint_f, w.ctrl = control.joint_f.reshape((n, -1)), wp.zeros((n, self.nu), dtype=float) - w.sensordata, w.time = wp.zeros((n, self.mj.nsensordata), dtype=float), wp.zeros(n, dtype=float) - self._advance(w) # allocates the solver's buffers before any graph capture - return w - - def _advance(self, w: SimpleNamespace, clock: Optional[wp.array] = None): - """Clip the commands and apply them as joint forces, record the row if `clock` is given, then step.""" - inputs = [self.limits, self.gain, self.dof] - wp.launch(_set_joint_force_kernel, dim=w.ctrl.shape, inputs=inputs, outputs=[w.ctrl, w.joint_f]) - if clock is not None: - inputs = [clock, self.timestep, w.qpos, w.qvel, w.ctrl, w.sensordata] - wp.launch(_set_record_kernel, dim=w.ctrl.shape[0], inputs=inputs, outputs=[w.time, self.record]) - w.pipeline.collide(w.state, w.contacts) - w.solver.step(w.state, w.state, w.control, w.contacts, self.timestep) - - def build( - self, - batch_size: int, - num_samples: int, - num_replicas: int, - ctrl_steps: int, - settle_steps: int, - seed: int, - ): - """Allocate the world sets of `SimBinding.build`.""" - self.sets = {"execution": self._worlds(batch_size)} - self.instance_worlds = dict(execution=1, rollout=num_samples * num_replicas, validation=num_replicas) - self.set_active_instances(batch_size) - e, shape = self.sets["execution"], (batch_size, self.mj.nq) - e.qpos.assign(np.broadcast_to(self.qpos, shape).astype(np.float32)) - e.qvel.assign(np.broadcast_to(self.qvel, shape).astype(np.float32)) - e.time.zero_() - newton.eval_fk(e.model, e.state.joint_q, e.state.joint_qd, e.state) - self.settle_steps = settle_steps - self.record = wp.zeros((batch_size, ctrl_steps, sum(self.sizes.values())), dtype=float) - - def set_active_instances(self, num_instances: int): - """Rebuild the rollout and validation worlds for the first `num_instances` instances.""" - for name in ["rollout", "validation"]: - self.sets[name] = self._worlds(num_instances * self.instance_worlds[name]) - - def context(self, worlds: str) -> Dict[SimContext, Any]: - """Return the `SimContext` values of a world set: states, controls, sensors and the joint and sensor layout.""" - w = self.sets[worlds] - return { - SimContext.QPOS: w.qpos, - SimContext.QVEL: w.qvel, - SimContext.CTRL: w.ctrl, - SimContext.SENSORDATA: w.sensordata, - SimContext.JOINTS: self.joints, - SimContext.SENSORS: self.sensors, - } - - def reset(self, worlds: str, clock: wp.array, iteration: wp.array): - """Copy the executed states into a world set, then settle it with zero controls.""" - w, e = self.sets[worlds], self.sets["execution"] - inputs = [e.qpos, e.qvel, self.instance_worlds[worlds]] - wp.launch(_set_broadcast_state_kernel, dim=w.qpos.shape, inputs=inputs, outputs=[w.qpos, w.qvel]) - newton.eval_fk(w.model, w.state.joint_q, w.state.joint_qd, w.state) - if self.settle_steps: - w.ctrl.zero_() - for _ in range(self.settle_steps): - self._advance(w) - - def set_time(self, worlds: str, t0: int): - """Set a world set's time to that of sim step `t0`.""" - self.sets[worlds].time.fill_(t0 * self.timestep) - - def step(self, worlds: str, clock: wp.array): - """Read the sensors on the current state, then apply the commands and step; execution records its rows.""" - w = self.sets[worlds] - inputs = [w.body_q, w.body_qd, self.kind, self.body, self.adr, self.subtree_mass] - wp.launch( - _compute_sensors_kernel, dim=(w.ctrl.shape[0], len(self.sensors)), inputs=inputs, outputs=[w.sensordata] - ) - self._advance(w, clock if worlds == "execution" else None) - - def read_execution(self) -> Dict[str, np.ndarray]: - """Return the executed rows, `{name: (batch_size, ctrl_steps, ...)}`.""" - split = np.split(self.record.numpy().copy(), np.cumsum(list(self.sizes.values()))[:-1], axis=2) - rows = dict(zip(self.sizes, split)) - rows["time"] = rows["time"][..., 0] - return rows - - -__all__ = ["NewtonSim"] diff --git a/src/robokit/helpers/sim_mpc/sim_mpc.py b/src/robokit/helpers/sim_mpc/sim_mpc.py index 291bb45..42382f4 100644 --- a/src/robokit/helpers/sim_mpc/sim_mpc.py +++ b/src/robokit/helpers/sim_mpc/sim_mpc.py @@ -6,61 +6,36 @@ # pyright: reportOperatorIssue=false """Receding-horizon MPPI (`PopulationSolver` with a `GaussianSampler`) scored by batched simulator rollouts. -Each control period of `SimMPC.solve`, from every instance's executed state: +Each `SimMPC.plan`, from every instance's given state: 1. `_optimize`: draw node offsets around each plan (draw zero is the plan) and score each by its rollout. 2. Move each plan to the draws' cost-weighted mean and redraw, until the best draws stop beating the plans. -3. Score the moved plans; an instance whose moved plan costs over 4 temperatures more keeps its best draw. -4. `_simulate`: advance each executed world by its plan's first `ctrl_steps`, then shift the plans forward. +3. Score the moved plans; an instance whose moved plan costs over `best_draw_margin` temperatures more keeps its best draw. +4. Return each plan's first `ctrl_steps` commands, then shift the plans forward. + +`robokit.sim.Sim`s resized from the given one hold the worlds: "rollout" (`batch_size * num_samples * num_replicas`) and "validation" (`batch_size * num_replicas`), instance-major. Coarse to fine (`config.stages`): a stage's rollouts step at its `dt`, or along its dt schedule over the horizon, each step's costs weighted by the sim steps it spans. `SimMPC.execute` runs the planner in closed loop on a simulator of its own. """ import copy +import dataclasses from enum import Enum -from typing import Any, Callable, Dict, List, Optional, Protocol, Sequence, Tuple, Union, cast +from functools import partial +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, cast import numpy as np import warp as wp -from robokit.helpers.sim_mpc.config import SimMPCConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.helpers.sim_mpc.config import SimMPCConfig, SimMPCStage +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.sampler import GaussianSampler, GaussianSamplerConfig from robokit.opt.var_values import VarValues, VectorVar from robokit.terms.simulation import SimContext +from robokit.terms.simulation.sim_context import sim_context from robokit.terms.task import Task from robokit.utils.warp_utils import masked_copy -class SimBinding(Protocol): - """What `SimMPC` needs from a simulator; `worlds` names a world set: "rollout", "validation" or "execution".""" - - nu: int - """Commands per world, the width of `SimContext.CTRL`.""" - device: Any - """The Warp device every world set lives on.""" - - def build( - self, batch_size: int, num_samples: int, num_replicas: int, ctrl_steps: int, settle_steps: int, seed: int - ): - """Allocate rollout (`B*S*R`), validation (`B*R`) and executed (`B`) worlds at the initial states.""" - - def set_active_instances(self, num_instances: int): - """Rebuild the rollout and validation worlds for the first `num_instances` instances.""" - - def context(self, worlds: str) -> Dict[SimContext, Any]: - """The world set's `SimContext` values except `CLOCK`, `NUM_INSTANCES` and `WORLDS_PER_INSTANCE`.""" - ... - - def reset(self, worlds: str, clock: wp.array, iteration: wp.array): - """Copy the executed states into a world set with replica noise, then settle it; device work only.""" - - def set_time(self, worlds: str, t0: int): - """Set the world set's time to that of sim step `t0`; called eagerly after `reset`.""" - - def step(self, worlds: str, clock: wp.array): - """Apply the commands in `SimContext.CTRL` and step; "execution" records row `clock[1]`; device work only.""" - - def read_execution(self) -> Dict[str, np.ndarray]: - """The rows "execution" recorded since the last call, `{name: (batch_size, ctrl_steps, ...)}`.""" - ... +if TYPE_CHECKING: + from robokit.sim import Sim class _Key(Enum): @@ -77,17 +52,59 @@ def _compute_ctrl_kernel( row_worlds: int, instance_worlds: int, bounds: wp.array2d(dtype=float), - ctrl: wp.array2d(dtype=float), + ctrl: wp.array3d(dtype=float), ): - """Each world's commands at step `clock[1]`: its reference plus its node row weighted by `interpolation[t]`.""" - w, u = wp.tid() # pyright: ignore[reportAssignmentType] - t, nu = clock[1], ctrl.shape[1] - row = wp.min(w // row_worlds, nodes.shape[0] - 1) + """Each world's commands at steps `clock[1] + k`, into `ctrl[k]`: its reference plus its node row weighted by that step's `interpolation` row.""" + world, k, command = wp.tid() # pyright: ignore[reportAssignmentType] + step = clock[1] + k + nu = ctrl.shape[2] + row = wp.min(world // row_worlds, nodes.shape[0] - 1) offset = float(0.0) - for k in range(interpolation.shape[1]): - offset += interpolation[t, k] * nodes[row, k * nu + u] - reference = ctrl_ref[w // instance_worlds, wp.min(clock[0] + t, ctrl_ref.shape[1] - 1), u] - ctrl[w, u] = wp.clamp(reference + offset, bounds[u, 0], bounds[u, 1]) + for node in range(interpolation.shape[1]): + offset += interpolation[step, node] * nodes[row, node * nu + command] + reference = ctrl_ref[world // instance_worlds, wp.min(clock[0] + step, ctrl_ref.shape[1] - 1), command] + ctrl[k, world, command] = wp.clamp(reference + offset, bounds[command, 0], bounds[command, 1]) + + +@wp.kernel +def _set_clipped_ctrl_kernel(limits: wp.array2d(dtype=float), ctrl: wp.array2d(dtype=float)): + world, command = wp.tid() # pyright: ignore[reportAssignmentType] + ctrl[world, command] = wp.clamp(ctrl[world, command], limits[command, 0], limits[command, 1]) + + +@wp.kernel +def _set_broadcast_state_kernel( + qpos: wp.array2d(dtype=float), + qvel: wp.array2d(dtype=float), + qpos_std: wp.array(dtype=float), + qvel_std: wp.array(dtype=float), + num_replicas: int, + instance_worlds: int, + seed: int, + clock: wp.array(dtype=int), + iteration: wp.array(dtype=int), + out_qpos: wp.array2d(dtype=float), + out_qvel: wp.array2d(dtype=float), +): + """Each world's instance's executed state plus its replica's noise, redrawn per plan start and iteration.""" + world = wp.tid() + instance = world // instance_worlds + rng = wp.rand_init(seed + clock[0], world % num_replicas + num_replicas * iteration[0]) + for i in range(qpos.shape[1]): + out_qpos[world, i] = qpos[instance, i] + qpos_std[i] * wp.randn(rng) + for i in range(qvel.shape[1]): + out_qvel[world, i] = qvel[instance, i] + qvel_std[i] * wp.randn(rng) + + +@wp.kernel +def _set_value_kernel(value: float, out: wp.array(dtype=float)): + out[wp.tid()] = value + + +@wp.kernel +def _set_broadcast_kernel(x: wp.array2d(dtype=float), instance_worlds: int, out: wp.array2d(dtype=float)): + world, i = wp.tid() # pyright: ignore[reportAssignmentType] + out[world, i] = x[world // instance_worlds, i] @wp.kernel @@ -95,14 +112,15 @@ def _compute_step_cost_kernel( term_cost: wp.array2d(dtype=float), scales: wp.array2d(dtype=float), clock: wp.array(dtype=int), + ticks: int, cost: wp.array(dtype=float), ): - """Add every term's step cost at its running scale; thread 0 ticks the clock, which no thread here reads.""" - w = wp.tid() - for i in range(term_cost.shape[0]): - cost[w] += scales[i, 0] * term_cost[i, w] - if w == 0: - clock[1] = clock[1] + 1 + """Add every term's step cost at its running scale times the `ticks` sim steps this step stands for; thread 0 ticks the clock, which no thread here reads.""" + world = wp.tid() + for term in range(term_cost.shape[0]): + cost[world] += float(ticks) * scales[term, 0] * term_cost[term, world] + if world == 0: + clock[1] = clock[1] + ticks @wp.kernel @@ -110,327 +128,443 @@ def _compute_draw_cost_kernel( term_cost: wp.array2d(dtype=float), scales: wp.array2d(dtype=float), horizon: int, + ticks: int, num_rows: int, num_replicas: int, - active: wp.array(dtype=int), iteration: int, rollout_cost: wp.array(dtype=float), cost: wp.array(dtype=float), history: wp.array3d(dtype=float), ): - """Per instance: finish each world's cost, add each row's replica mean unless finished, and record history.""" - b = wp.tid() + """Per instance: finish each world's cost, add each row's replica mean, and record history.""" + instance = wp.tid() best = float(0.0) - for i in range(b * num_rows, (b + 1) * num_rows): + for row in range(instance * num_rows, (instance + 1) * num_rows): total = float(0.0) - for w in range(i * num_replicas, (i + 1) * num_replicas): - value = rollout_cost[w] - for k in range(term_cost.shape[0]): - value += (scales[k, 1] - scales[k, 0]) * term_cost[k, w] + for world in range(row * num_replicas, (row + 1) * num_replicas): + value = rollout_cost[world] + for term in range(term_cost.shape[0]): + value += (scales[term, 1] - float(ticks) * scales[term, 0]) * term_cost[term, world] value = value / float(horizon) value = wp.where(wp.isfinite(value), value, 1.0e6) - rollout_cost[w] = value + rollout_cost[world] = value total += value - if active[b] != 0: - cost[i] += total / float(num_replicas) - best = wp.where(i == b * num_rows, cost[i], wp.min(best, cost[i])) + cost[row] += total / float(num_replicas) + best = wp.where(row == instance * num_rows, cost[row], wp.min(best, cost[row])) if iteration >= 0: - history[iteration, b, 0] = cost[b * num_rows] - history[iteration, b, 1] = best - - -@wp.kernel -def _compute_node_bounds_kernel( - ref: wp.array3d(dtype=float), - clock: wp.array(dtype=int), - node_steps: int, - bounds: wp.array2d(dtype=float), - lower: wp.array2d(dtype=wp.float32), - upper: wp.array2d(dtype=wp.float32), -): - """The command bounds as node offsets from `ctrl_ref`, per instance and node of a plan from `clock[0]`.""" - b, j = wp.tid() # pyright: ignore[reportAssignmentType] - nu = bounds.shape[0] - reference = ref[b, wp.min(clock[0] + (j // nu) * node_steps, ref.shape[1] - 1), j % nu] - lower[b, j] = bounds[j % nu, 0] - reference - upper[b, j] = bounds[j % nu, 1] - reference + history[iteration, instance, 0] = cost[instance * num_rows] + history[iteration, instance, 1] = best @wp.kernel def _compute_shifted_nodes_kernel( nodes: wp.array2d(dtype=wp.float32), shift: wp.array2d(dtype=float), shifted: wp.array2d(dtype=wp.float32) ): - """Each plan's nodes `ctrl_steps` later: per command, `shifted[b, j] = sum_k shift[j, k] * nodes[b, k]`.""" - b, j = wp.tid() # pyright: ignore[reportAssignmentType] + """Each plan's nodes `ctrl_steps` later: per command, node `j` becomes `sum_k shift[j, k] * node_k`.""" + instance, column = wp.tid() # pyright: ignore[reportAssignmentType] nu = nodes.shape[1] // shift.shape[0] + node = column // nu + command = column % nu value = float(0.0) for k in range(shift.shape[1]): - value += shift[j // nu, k] * nodes[b, k * nu + j % nu] - shifted[b, j] = value + value += shift[node, k] * nodes[instance, k * nu + command] + shifted[instance, column] = value # --- planner ---------------------------------------------------------------- class SimMPC(Task): - """Receding-horizon MPPI on `config.batch_size` instances of one scene; `solve` plans and simulates an episode. + """Receding-horizon MPPI over simulated rollouts, for `config.batch_size` instances. + + Lifecycle: + 1. `__init__` resizes `sim` into the rollout and validation worlds and captures their graphs on the first plan. + 2. `plan(data, t0)` refines every instance's plan from its state and returns the next `ctrl_steps` commands. + 3. The caller executes them on its own simulator (or `execute` does on one), then plans again at `t0 + ctrl_steps`. + + Args: + config: The settings, with the cost terms (`config.add`), the node noise (`ctrl_std`) and command bounds. + sim: The planning simulator, e.g. `MjWarpSim(model, 1)`; for scenes that differ, one scene per instance. + ctrl_ref: The reference commands the plans offset, `(T, nu)` or `(batch_size, T, nu)`. Example: >>> # xdoctest: +REQUIRES(module:mujoco_warp) >>> import mujoco >>> from robokit.helpers.sim_mpc import SimMPCConfig - >>> from robokit.helpers.sim_mpc.mjwarp import MjWarpSim + >>> from robokit.sim import MjWarpSim >>> from robokit.terms import SensorTask - >>> model = mujoco.MjModel.from_xml_string( + >>> xml = ( ... '' ... ) + >>> model = mujoco.MjModel.from_xml_string(xml) >>> config = SimMPCConfig(num_samples=32, horizon_steps=20, node_steps=10, ctrl_steps=10, max_iterations=2) - >>> cost = SensorTask(np.full((60, 1), 0.3), {"x": 100.0}) - >>> mpc = SimMPC(MjWarpSim(model, mujoco.MjData(model)), np.zeros((60, 1)), np.full(1, 0.1), [cost], config) - >>> (rollout,), (plans,) = mpc.solve(40) - >>> rollout["qpos"].shape, rollout["ctrl"].shape, len(plans) - ((40, 1), (40, 1), 4) + >>> config = config.add(SensorTask(np.full((60, 1), 0.3), {"x": 100.0})) + >>> mpc = SimMPC(config, MjWarpSim(model, 1), np.zeros((60, 1))) + >>> commands, infos = mpc.plan(mujoco.MjData(model), 0) # execute these, then plan again at step 10 + >>> commands.shape, mpc.sims["rollout"].nworld + ((10, 1, 1), 31) + >>> (rollout,), (plans,) = mpc.execute(MjWarpSim(model, 1), 40) # or run the loop on a simulator + >>> rollout["qpos"].shape, len(plans) + ((40, 1), 4) + >>> # "auto" picked 4x on the CPU (2x on an RTX 3090): every rollout's first quarter steps at 10 ms, the rest at 40 ms + >>> mpc.stages # xdoctest: +IGNORE_WANT + [SimMPCStage(iters=2, dt=[(0.25, None), (1.0, 0.04)])] """ var_key = _Key.NODES - def __init__( - self, - sim: SimBinding, - ctrl_ref: np.ndarray, - ctrl_std: np.ndarray, - costs: Sequence[Task], - config: SimMPCConfig = SimMPCConfig(), - spline_basis: Optional[np.ndarray] = None, - ctrl_range: Optional[np.ndarray] = None, - ): - c, B = config, config.batch_size - self.config, self.sim, self.batch_size = c, sim, B - self.num_samples = S = c.num_samples - 1 # one draw's budget scores the moved plan - if B < 1 or c.num_replicas < 1 or S < 2: + def __init__(self, config: SimMPCConfig, sim: "Sim", ctrl_ref: np.ndarray): + import mujoco # pyright: ignore[reportMissingImports] # here, so that the module imports without MuJoCo + + batch_size = config.batch_size + num_replicas = config.num_replicas + self.config = config + self.batch_size = batch_size + self.device = wp.get_device() + self.num_samples = config.num_samples - 1 # one draw's budget scores the moved plan + if batch_size < 1 or num_replicas < 1 or self.num_samples < 2: raise ValueError("batch_size and num_replicas must be positive; num_samples needs three draws") - self.nu = nu = sim.nu - ctrl_ref = np.asarray(ctrl_ref, np.float32) - if ctrl_ref.shape[-1] != nu or ctrl_ref.ndim not in (2, 3) or ctrl_ref.ndim == 3 and len(ctrl_ref) != B: + self.instance_worlds = dict(rollout=self.num_samples * num_replicas, validation=num_replicas) + mppi = config.planner == "mppi" + with wp.ScopedDevice(self.device): # each instance's worlds consecutive + self.sims = {name: sim.resized(batch_size * n) for name, n in self.instance_worlds.items() if mppi} + self.dt = sim.mjm.opt.timestep + self.stages, self.check = config.stages or [SimMPCStage(config.max_iterations)], False # auto: fine at first + dts = [dt for stage in self.stages for _, dt in self._schedule(stage.dt)] + ratios = np.array([(dt or self.dt) / self.dt for dt in dts]) + if np.any(ratios < 1) or not np.allclose(ratios, np.round(ratios)): + raise ValueError("a stage's dt must be a whole multiple of the simulator's timestep") + model = self.model = (self.sims["rollout"] if mppi else sim).mjm # its layout: for several scenes, their merge + nu = model.nu + self.nu = nu + ctrl_ref = np.asarray(ctrl_ref) + if ctrl_ref.ndim == 2: # one reference for every instance + ctrl_ref = np.broadcast_to(ctrl_ref, (batch_size, *ctrl_ref.shape)) + if ctrl_ref.shape[-1] != nu or ctrl_ref.ndim != 3 or len(ctrl_ref) != batch_size: raise ValueError("ctrl_ref must be (T, nu) or (batch_size, T, nu)") - ctrl_ref = np.broadcast_to(ctrl_ref if ctrl_ref.ndim == 3 else ctrl_ref[None], (B, *ctrl_ref.shape[-2:])) - self.ctrl_ref = wp.array(np.ascontiguousarray(ctrl_ref), dtype=float) + self.ctrl_ref = wp.array(ctrl_ref, dtype=float) # --- interpolation: every mode is linear in the nodes, so one row of node weights per sim step --- - K = self.num_nodes = -(-c.horizon_steps // c.node_steps) + 1 - t = np.arange(c.ctrl_steps + (K - 1) * c.node_steps + 1) # through the last node after a shift - if spline_basis is None: - k = np.minimum(t // c.node_steps, K - 1) - a = np.minimum(t / c.node_steps - k, 1.0) - powers = dict( # nodes k - 1 .. k + 2 per power of a, clamped to the ends + num_nodes = -(-config.horizon_steps // config.node_steps) + 1 + self.num_nodes = num_nodes + steps = np.arange(config.ctrl_steps + (num_nodes - 1) * config.node_steps + 1) # past the last shifted node + basis = config.interpolation + if isinstance(basis, str): + node = np.minimum(steps // config.node_steps, num_nodes - 1) # each step's segment start + phase = np.minimum(steps / config.node_steps - node, 1.0) # and how far into the segment it is + powers = dict( # weights of nodes `node - 1 .. node + 2` per power of `phase`, clamped to the ends linear=[[0, 1, 0, 0], [0, -1, 1, 0]], cubic=[[0, 1, 0, 0], [-0.5, 0, 0.5, 0], [1, -2.5, 2, -0.5], [-0.5, 1.5, -1.5, 0.5]], zero=[[0, 1, 0, 0]], - )[c.interpolation] - weights, interpolation = a[:, None] ** np.arange(len(powers)) @ np.array(powers), np.zeros((len(t), K)) - for d in range(4): - np.add.at(interpolation, (t, np.clip(k + d - 1, 0, K - 1)), weights[:, d]) + )[basis] + weights = phase[:, None] ** np.arange(len(powers)) @ np.array(powers) + interpolation = np.zeros((len(steps), num_nodes)) + for neighbor in range(4): + np.add.at(interpolation, (steps, np.clip(node + neighbor - 1, 0, num_nodes - 1)), weights[:, neighbor]) else: - if np.ndim(spline_basis) != 2 or np.shape(spline_basis)[1] != K: - raise ValueError("spline_basis needs one column per node") - interpolation = np.asarray(spline_basis)[np.minimum(t, len(spline_basis) - 1)] - self.interpolation = wp.array(interpolation.astype(np.float32), dtype=float) + if np.ndim(basis) != 2 or np.shape(basis)[1] != num_nodes: + raise ValueError("an interpolation basis needs one column per node") + interpolation = np.asarray(basis)[np.minimum(steps, len(basis) - 1)] + self.interpolation = wp.array(interpolation, dtype=float) # a shift moves node j to the plan's time ctrl_steps later, fading to zero past the horizon - tail = np.clip(1 - (t[c.ctrl_steps :: c.node_steps] - c.horizon_steps) / c.ctrl_steps, 0, 1) - self.shift = wp.array((tail[:, None] * interpolation[c.ctrl_steps :: c.node_steps]).astype(np.float32)) - bounds = np.tile([-np.inf, np.inf], (nu, 1)) if ctrl_range is None else np.asarray(ctrl_range) + shifted_steps = steps[config.ctrl_steps :: config.node_steps] + tail = np.clip(1 - (shifted_steps - config.horizon_steps) / config.ctrl_steps, 0, 1) + shift = tail[:, None] * interpolation[config.ctrl_steps :: config.node_steps] + self.shift = wp.array(shift, dtype=float) + clamp = not model.opt.disableflags & mujoco.mjtDisableBit.mjDSBL_CLAMPCTRL # MuJoCo clamps ctrl to ctrlrange + limits = np.where(model.actuator_ctrllimited[:, None] * clamp, model.actuator_ctrlrange, [-np.inf, np.inf]) + self.ctrl_limits = wp.array(limits, dtype=float) + bounds = limits if config.ctrl_range is None else np.asarray(config.ctrl_range) if bounds.shape != (nu, 2) or np.any(bounds[:, 0] > bounds[:, 1]): raise ValueError("ctrl_range must contain ordered bounds for every command") - self.command_bounds = wp.array(bounds.astype(np.float32), dtype=float) - sim.build(B, S, c.num_replicas, c.ctrl_steps, c.settle_steps, c.seed) + self.command_bounds = wp.array(bounds, dtype=float) + self._host = dict(ctrl_ref=ctrl_ref, bounds=bounds) # for the sampler's per-plan bounds + self.qpos_std = wp.array(np.broadcast_to(config.qpos_std, model.nq), dtype=float) + self.qvel_std = wp.array(np.broadcast_to(config.qvel_std, model.nv), dtype=float) # --- buffers --- - self.clock = wp.array([0, 0, c.horizon_steps], dtype=int) # [t0, t, horizon] - self.rollout_cost = wp.zeros(B * S * c.num_replicas, dtype=float) + self.state = dict( # each instance's state, which `plan` copies in and every rollout starts from + time=wp.zeros((batch_size, 1), dtype=float), + qpos=wp.array(np.tile(model.qpos0, (batch_size, 1)), dtype=float), + qvel=wp.zeros((batch_size, model.nv), dtype=float), + act=wp.zeros((batch_size, model.na), dtype=float), + qacc_warmstart=wp.zeros((batch_size, model.nv), dtype=float), + ) + self.commands = wp.zeros((config.ctrl_steps, batch_size, nu), dtype=float) + self.clock = wp.array([0, 0, config.horizon_steps], dtype=int) # [t0, t, horizon] + self.rollout_cost = wp.zeros(batch_size * self.instance_worlds["rollout"], dtype=float) self.counter = wp.zeros(1, dtype=int) # the iteration, which seeds replica noise - self.history = wp.zeros((max(c.max_iterations, c.init_iterations, 1), B, 2), dtype=float) - self.use_best = wp.zeros(B, dtype=wp.int32) # instances whose moved plan scored worse than their best draw - self.running = wp.ones(B, dtype=int) # instances still running; finished ones count as stalled - self.plan = VarValues({_Key.NODES: VectorVar(wp.zeros((B, K * nu), dtype=wp.float32))}) - self.execution = self.plan.get(_Key.NODES).x + self.history = wp.zeros((max(config.max_iterations, config.init_iterations, 1), batch_size, 2), dtype=float) + self.plan_values = VarValues({_Key.NODES: VectorVar(wp.zeros((batch_size, num_nodes * nu), dtype=wp.float32))}) + self.execution = self.plan_values.get(_Key.NODES).x self.shifted = wp.zeros_like(self.execution) - self.costs, self.graphs, self.contexts, self.terms = costs, {}, {}, {} - self.lengths, self.num_active, self.t0, self.iteration = np.full(B, np.inf), B, 0, 0 + self.best_draw_mask = wp.zeros(batch_size, dtype=wp.int32) + self.graphs = {} + self.terms = {} + self.t0 = 0 + self.iteration = 0 + self.scales = np.reshape([[r, config.terminal_scale if t is None else t] for _, r, t in config.terms], (-1, 2)) + if not mppi: # iLQR on commands held for `node_steps`, first the reference's, from the instances' states + from robokit.opt.ilqr_optimizer import ILQROptimizer, ILQROptimizerConfig + from robokit.sim.dynamics import SimDynamics + + if config.control_map is not None: + raise ValueError("planner 'ilqr' takes commands as controls: no control_map") + dynamics = SimDynamics(sim, config.node_steps) + dynamics.ctrl_range = bounds + ilqr_config = config.ilqr or ILQROptimizerConfig(improve=True, feedback_cap=0.1, min_regularization=30.0) + ilqr_config = dataclasses.replace(ilqr_config, max_iter=config.max_iterations) + self.ilqr = ILQROptimizer(dynamics, [term for term, _, _ in config.terms], ilqr_config, scales=self.scales) + self.ilqr_start = dynamics.build_state(self.state["qpos"], self.state["qvel"], self.state["act"]) + ref = ctrl_ref[:, np.minimum(np.arange(0, config.horizon_steps, config.node_steps), ctrl_ref.shape[1] - 1)] + self.ilqr_plan = VectorVar(wp.array(np.clip(ref, *bounds.T).reshape(batch_size, -1), dtype=float)) + return # --- MPPI: node noise grows from ctrl_std at the first free node to std_growth times it at the last --- - ramp = np.minimum(np.arange(K - 1) / max(c.horizon_steps // c.node_steps - 1, 1), 1.0) - growth = c.std_growth ** ramp[:, None] - std = np.vstack([np.zeros((1, nu)), growth * np.asarray(ctrl_std)[None]]).astype(np.float32) - if c.interpolation == "zero": # a held first node would hold the last plan's command - std[0] = ctrl_std - mask = wp.array((std.reshape(-1) > 0).astype(np.float32), dtype=wp.float32) - sampler = GaussianSamplerConfig( - var_key=_Key.NODES, num_draws=S, init_std=0.0, min_std=c.min_std, gamma=0.5, seed=c.seed, - elite_ratio=0.2, mean_elites=True, noise_decay=c.noise_decay, + ctrl_std = np.broadcast_to(config.ctrl_std, nu) + ramp = np.minimum(np.arange(num_nodes - 1) / max(config.horizon_steps // config.node_steps - 1, 1), 1.0) + node_std = np.vstack([np.zeros(nu), config.std_growth ** ramp[:, None] * ctrl_std]) + if isinstance(basis, str) and basis == "zero" or config.draw_first_node: # else it holds the last command + node_std[0] = ctrl_std + mask = wp.array(node_std.reshape(-1) > 0, dtype=wp.float32) + sampler_config = GaussianSamplerConfig( + var_key=_Key.NODES, num_draws=self.num_samples, init_std=0.0, min_std=config.min_std, + gamma=config.std_gamma, seed=config.seed, elite_ratio=config.elite_ratio, mean_elites=True, + noise_decay=config.noise_decay, wide_ratio=config.wide_ratio, wide_scale=config.wide_scale, ) # fmt: skip - solver = PopulationSolverConfig( - num_iters=c.max_iterations, samplers=[sampler], cuda_graph_mode="none", - min_improvement=c.min_improvement, patience=c.patience, + solver_config = PopulationSolverConfig( # SimMPC captures its own step graphs, per `config.cuda_graph_mode` + stages=[Stage(config.max_iterations)], samplers=[sampler_config], cuda_graph_mode="none", + min_improvement=config.min_improvement, patience=config.patience, ) # fmt: skip - self.solver = PopulationSolver([self], solver, sim.device, active_dof_mask=mask) - self.solver.setup(self.plan) # scores the plans once, which captures the rollout graphs + self.solver = PopulationSolver([self], solver_config, self.device, active_dof_mask=mask) + self.solver.setup(self.plan_values) # scores the plans once, which captures the rollout graphs + self.check = config.stages is None # on the first plan's rollouts, from a given state self.sampler = cast(GaussianSampler, self.solver.samplers[0]) - self.sampler.std_reset.assign(np.tile(std.reshape(1, -1), (B, 1))) + self.node_std = np.tile(node_std.reshape(1, -1), (batch_size, 1)) # the configured noise + self.sampler.std_reset.assign(self.node_std) self.sampler.reset() - if ctrl_range is not None: # the sampler clamps the draws to the bounds the commands get - self.sampler.lower, self.sampler.upper = wp.zeros_like(self.execution), wp.zeros_like(self.execution) - - def _set_active_instances(self, k: int): - """Plan the first `k` instances only; their worlds, terms and graphs are rebuilt on the next score.""" - if k != self.num_active: - self.sim.set_active_instances(k) - self.num_active = k - for name in ["rollout", "rollout_reset", "validation", "validation_reset"]: - self.graphs.pop(name, None) - - def _build(self, worlds: str, nodes: wp.array): - """Resolve the costs on a world set and capture its reset and one-step graphs (run once first).""" - c, R, S = self.config, self.config.num_replicas, self.num_samples - instance_worlds = dict(rollout=S * R, validation=R, execution=1)[worlds] - context = {**self.sim.context(worlds), SimContext.CLOCK: self.clock, SimContext.NUM_INSTANCES: self.batch_size} + self.sampler.lower = wp.zeros_like(self.execution) # the sampler clamps the draws to the command bounds + self.sampler.upper = wp.zeros_like(self.execution) + + def _build(self, worlds: str, nodes: wp.array, spans: set): + """Resolve the costs on a world set and capture its reset and one-step graphs, each run once first: the reset copies the instances' states in with replica noise and settles them with zero controls; the step writes, maps and clips the commands, steps and adds the costs.""" + config = self.config + sim = self.sims[worlds] + data = sim.data + instance_worlds = self.instance_worlds[worlds] + context = sim_context(sim) + context[SimContext.CLOCK] = self.clock context[SimContext.WORLDS_PER_INSTANCE] = instance_worlds - terms = [] if worlds == "execution" else [copy.copy(term) for term in self.costs] + context[SimContext.NUM_INSTANCES] = self.batch_size + terms = [copy.copy(term) for term, _, _ in config.terms] for term in terms: term.resolve(None, context) - scales = [[getattr(t, "running_scale", 1.0), getattr(t, "terminal_scale", None)] for t in terms] - scales = [[running, c.terminal_scale if terminal is None else terminal] for running, terminal in scales] - term_cost = wp.zeros((len(terms), context[SimContext.CTRL].shape[0]), dtype=float) - self.contexts[worlds] = context - self.terms[worlds] = terms, term_cost, wp.array(np.reshape(scales, (-1, 2)).astype(np.float32), dtype=float) - row_worlds = 1 if worlds == "execution" else R - bodies = [] if worlds == "execution" else [(worlds + "_reset", lambda: self._reset(worlds))] - bodies.append((worlds, lambda: self._step(worlds, nodes, row_worlds, instance_worlds))) - for name, body in bodies: - if worlds != "execution": - body() - if not self.sim.device.is_cuda: + scales = wp.array(self.scales, dtype=float) # each term's running and terminal scales + term_cost = wp.zeros((len(terms), sim.nworld), dtype=float) + self.terms[worlds] = terms, term_cost, scales # kept alive for the graphs + state = self.state + + def reset(): + self.clock[1:2].zero_() + self.rollout_cost.zero_() + inputs = [state["qpos"], state["qvel"], self.qpos_std, self.qvel_std, config.num_replicas, instance_worlds] + inputs += [config.seed, self.clock, self.counter] + wp.launch(_set_broadcast_state_kernel, dim=sim.nworld, inputs=inputs, outputs=[data.qpos, data.qvel]) + data.ctrl.zero_() + wp.launch(_set_value_kernel, dim=sim.opt.timestep.shape, inputs=[self.dt], outputs=[sim.opt.timestep]) + for name, out in (("act", data.act), ("qacc_warmstart", data.qacc_warmstart), ("time", data.time)): + if name == "time": # after settling: the rollouts start at the state's time + for _ in range(config.settle_steps): + sim.step() + out = out.reshape((sim.nworld, -1)) + wp.launch(_set_broadcast_kernel, dim=out.shape, inputs=[state[name], instance_worlds], outputs=[out]) + + def step(ticks: int): + timestep = sim.opt.timestep + wp.launch(_set_value_kernel, dim=timestep.shape, inputs=[ticks * self.dt], outputs=[timestep]) + inputs = [nodes, self.interpolation, self.ctrl_ref, self.clock] + inputs += [config.num_replicas, instance_worlds, self.command_bounds] + ctrl = data.ctrl.reshape((1, *data.ctrl.shape)) + wp.launch(_compute_ctrl_kernel, dim=(sim.nworld, 1, self.nu), inputs=inputs, outputs=[ctrl]) + if config.control_map is not None: + config.control_map(sim, self.clock) + wp.launch(_set_clipped_ctrl_kernel, dim=data.ctrl.shape, inputs=[self.ctrl_limits], outputs=[data.ctrl]) + sim.step() + term_cost.zero_() + for i, term in enumerate(terms): + term.compute_weighted_cost(None, out_cost=term_cost[i]) + inputs = [term_cost, scales, self.clock, ticks] + wp.launch(_compute_step_cost_kernel, dim=sim.nworld, inputs=inputs, outputs=[self.rollout_cost]) + + bodies = {worlds + "_reset": reset, **{f"{worlds}_{t}": partial(step, t) for t in spans}} + for name, body in bodies.items(): + body() + if self.device.is_cuda and self.config.cuda_graph_mode == "step": + with wp.ScopedCapture() as capture: + body() + self.graphs[name] = partial(wp.capture_launch, capture.graph) + else: self.graphs[name] = body - continue - with wp.ScopedCapture() as capture: - body() - self.graphs[name] = lambda graph=capture.graph: wp.capture_launch(graph) - - def _reset(self, worlds: str): - self.clock[1:2].zero_() - self.rollout_cost.zero_() - self.sim.reset(worlds, self.clock, self.counter) - - def _step(self, worlds: str, nodes: wp.array, row_worlds: int, instance_worlds: int): - ctrl, (terms, term_cost, scales) = self.contexts[worlds][SimContext.CTRL], self.terms[worlds] - inputs = [ - nodes, - self.interpolation, - self.ctrl_ref, - self.clock, - row_worlds, - instance_worlds, - self.command_bounds, - ] - wp.launch(_compute_ctrl_kernel, dim=ctrl.shape, inputs=inputs, outputs=[ctrl]) - self.sim.step(worlds, self.clock) - term_cost.zero_() - for i, term in enumerate(terms): - term.compute_weighted_cost(None, out_cost=term_cost[i]) - inputs = [term_cost, scales, self.clock] - wp.launch(_compute_step_cost_kernel, dim=ctrl.shape[0], inputs=inputs, outputs=[self.rollout_cost]) + + @staticmethod + def _schedule(dt: Any) -> List[Tuple[float, Optional[float]]]: + """A stage's dt as `(fraction of the horizon it runs to, dt)` pairs.""" + return list(dt) if isinstance(dt, (list, tuple)) else [(1.0, dt)] + + def _segments(self, dt: Any) -> List[Tuple[int, int]]: + """Runs of (sim steps per physics step, physics steps) along the horizon for a stage's dt; each part's remainder first, at the timestep.""" + horizon, start, runs = self.config.horizon_steps, 0, [] + for until, part_dt in self._schedule(dt): + k, end = round((part_dt or self.dt) / self.dt), round(until * horizon) + runs += [(1, (end - start) % k), (k, (end - start) // k)] + start = end + return [(t, n) for t, n in runs if n] def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): """Add each node row's rollout cost: draws in the rollout worlds, moved plans in the validation worlds.""" nodes = cast(VectorVar, cast(VarValues, var_values).get(_Key.NODES)).x - worlds = "rollout" if nodes.shape[0] > self.batch_size else "validation" - if worlds not in self.graphs: - self._build(worlds, nodes) - self.iteration += worlds == "rollout" + is_rollout = nodes.shape[0] > self.batch_size + worlds = "rollout" if is_rollout else "validation" + plans = [self._segments(stage.dt) for stage in self.stages for _ in range(stage.iters)] + if worlds + "_reset" not in self.graphs: + self._build(worlds, nodes, {1, 2, 4, *(t for plan in plans for t, _ in plan)}) + if is_rollout: + self.iteration += 1 self.counter.fill_(self.iteration - 1) - self.graphs[worlds + "_reset"]() - self.sim.set_time(worlds, self.t0) - for _ in range(self.config.horizon_steps): - self.graphs[worlds]() - c, (_, term_cost, scales) = self.config, self.terms[worlds] - rows, iteration = (self.num_samples, self.iteration - 1) if worlds == "rollout" else (1, -1) - inputs = [term_cost, scales, c.horizon_steps, rows, c.num_replicas, self.running, iteration] + # this iteration's stage: a plan of other than `max_iterations` runs the stages' last iterations, the first stage longer or cut; the moved plans step at the timestep + index = max(self.iteration - 1 + len(plans) - self.solver.config.num_iters, 0) + ends, horizon, check = {}, self.config.horizon_steps, self.check and is_rollout + split = {k: [(0.25, None), (1.0, k * self.dt)] for k in (4, 2)} # auto's: the first quarter at the timestep + for k in (4, 2, 1) if check else (None,): # auto, once: the same draws at each k + plan = self._segments(split.get(k)) if check else plans[index] if is_rollout else [(1, horizon)] + self.graphs[worlds + "_reset"]() + for t, steps in plan: + for _ in range(steps): + self.graphs[f"{worlds}_{t}"]() + if check: + ends[k] = self.sims[worlds].data.qpos.numpy().reshape(self.batch_size, -1, self.model.nq) + if check: # the coarsest whose draws end within 11% of their spread of the fine ones + spread = np.linalg.norm(ends[1] - ends[1].mean(1, keepdims=True), axis=-1).mean(1) + error = {k: np.median(np.linalg.norm(ends[k] - ends[1], axis=-1), axis=1) / spread for k in (4, 2)} + coarse = next((k for k in (4, 2) if np.all(error[k] <= 0.11)), 1) + self.stages, self.check = [SimMPCStage(self.config.max_iterations, split.get(coarse))], False + last = plan[-1][0] # the last step's sim steps, whose running cost the terminal one replaces + _, term_cost, scales = self.terms[worlds] + num_rows = self.num_samples if is_rollout else 1 + iteration = self.iteration - 1 if is_rollout else -1 # validation records no history + inputs = [term_cost, scales, horizon, last, num_rows] + inputs += [self.config.num_replicas, iteration] outputs = [self.rollout_cost, out_cost, self.history] - wp.launch(_compute_draw_cost_kernel, dim=self.num_active, inputs=inputs, outputs=outputs) + wp.launch(_compute_draw_cost_kernel, dim=self.batch_size, inputs=inputs, outputs=outputs) def _optimize(self, t0: int) -> List[dict]: """Refine every instance's plan from sim step `t0`; return each instance's iterations and costs.""" - c, B, n = self.config, self.num_active, self.num_samples - limit = c.init_iterations if t0 == 0 and c.init_iterations > 0 else c.max_iterations - self.clock.assign(np.array([t0, 0, c.horizon_steps], np.int32)) - self.running.assign((self.lengths > t0).astype(np.int32)) - self.solver.config.num_iters, self.t0, self.iteration = limit, t0, 0 - self.sampler.epoch.fill_(t0 // c.ctrl_steps) - if self.sampler.lower is not None: - inputs = [self.ctrl_ref, self.clock, c.node_steps, self.command_bounds] - outputs = [self.sampler.lower, self.sampler.upper] - wp.launch(_compute_node_bounds_kernel, dim=self.shifted.shape, inputs=inputs, outputs=outputs) - self.solver.solve(self.plan) - done = self.iteration - history = self.history.numpy()[:done, :B] - infos = [ - dict( - t0=t0, - iterations=done, - plan_cost=float(h[-1, 0]), - best_cost=float(h[-1, 1]), - history=[(float(a), float(b)) for a, b in h], - ) - for h in history.transpose(1, 0, 2) - ] - # the solver scored the moved plans last; execute one unless it costs 4 temperatures more than the best draw - mean_cost = self.rollout_cost.numpy()[: B * c.num_replicas].reshape(B, c.num_replicas).mean(axis=1) - temperature = self.sampler.temperatures.numpy()[:B] - best = history[-1, :, 1].astype(np.float64) - mean = mean_cost.astype(np.float64) <= best + 4.0 * temperature.astype(np.float64) - self.use_best[:B].assign((~mean).astype(np.int32)) - for info, m, t, e in zip(infos, mean_cost, temperature, mean): - info.update( - mean_cost=float(m), executed_mean=bool(e), rollout_evaluations=done * n + 1, temperature=float(t) - ) - best = cast(VectorVar, cast(VarValues, self.sampler.best_draws).get(_Key.NODES)).x - masked_copy(self.use_best[:B], best[:B], self.execution[:B]) - return infos - - def _simulate(self, t0: int) -> Dict[str, np.ndarray]: - """Advance the executed worlds by their plans' first `ctrl_steps`, shift the plans, return the rows.""" - if "execution" not in self.graphs: - self._build("execution", self.execution) - self.clock.assign(np.array([t0, 0, 0], np.int32)) - for _ in range(self.config.ctrl_steps): - self.graphs["execution"]() - record = self.sim.read_execution() - wp.launch( - _compute_shifted_nodes_kernel, - dim=self.shifted.shape, - inputs=[self.execution, self.shift], - outputs=[self.shifted], - ) + config = self.config + num_replicas = config.num_replicas + self.clock.assign([t0, 0, config.horizon_steps]) + first_plan = t0 == 0 and config.init_iterations > 0 + self.solver.config.stages = [Stage(config.init_iterations if first_plan else config.max_iterations)] + self.t0 = t0 + self.iteration = 0 + self.sampler.epoch.fill_(t0 // config.ctrl_steps) + if t0 == 0: # an earlier episode's carried noise + self.sampler.std_reset.assign(self.node_std) + ctrl_ref, bounds = self._host["ctrl_ref"], self._host["bounds"] # the bounds as offsets from each node's ref + node_ref = ctrl_ref[:, np.minimum(t0 + np.arange(self.num_nodes) * config.node_steps, ctrl_ref.shape[1] - 1)] + self.sampler.lower.assign((bounds[:, 0] - node_ref).reshape(self.batch_size, -1)) + self.sampler.upper.assign((bounds[:, 1] - node_ref).reshape(self.batch_size, -1)) + self.solver.solve(self.plan_values) + history = self.history.numpy()[: self.iteration].transpose(1, 0, 2) + # the solver scored the moved plans last; execute one unless it costs `best_draw_margin` temperatures more + validation_cost = self.rollout_cost.numpy()[: self.batch_size * num_replicas] + mean_costs = validation_cost.reshape(self.batch_size, num_replicas).mean(axis=1) + temperatures = self.sampler.temperatures.numpy().astype(np.float64) + best_costs = history[:, -1, 1].astype(np.float64) + executed_means = mean_costs.astype(np.float64) <= best_costs + config.best_draw_margin * temperatures + best_draws = cast(VectorVar, cast(VarValues, self.sampler.best_draws).get(_Key.NODES)).x + self.best_draw_mask.assign(~executed_means) + masked_copy(self.best_draw_mask, best_draws, self.execution) + scales = np.ones(self.batch_size) + if config.std_range is not None and self.solver.config.num_iters == 1: # carry the refit spread, one scale + drawn = self.node_std[0] > 0 + ratios = self.sampler.std.numpy()[:, drawn] / self.node_std[:, drawn] + scales = np.clip(np.sqrt(np.mean(ratios**2, axis=1)), *config.std_range) + self.sampler.std_reset.assign(scales[:, None] * self.node_std) + return [ + dict(t0=t0, iterations=self.iteration, plan_cost=float(costs[-1, 0]), best_cost=float(costs[-1, 1]), + history=[(float(plan), float(best)) for plan, best in costs], mean_cost=float(mean_cost), + executed_mean=bool(executed_mean), rollout_evaluations=self.iteration * self.num_samples + 1, + temperature=float(temperature), std_scale=float(scale)) + for costs, mean_cost, executed_mean, temperature, scale in zip(history, mean_costs, executed_means, + temperatures, scales) + ] # fmt: skip + + def plan(self, data: Any, t0: int) -> Tuple[wp.array, List[dict]]: + """Refine every instance's plan from its state at sim step `t0`; return its next `ctrl_steps` commands. + + Args: + data: Each instance's `time`, `qpos`, `qvel`, `act` and `qacc_warmstart`, `(batch_size, ...)` arrays: e.g. the executing simulator's `data`, or a `mujoco.MjData` for one instance. + t0: The state's sim step, which indexes `ctrl_ref` and the costs' references. + + Returns: + The commands, `(ctrl_steps, batch_size, nu)` before any `control_map`, in a buffer the next call reuses, and each instance's plan info (`t0`, `iterations`, `plan_cost`, `best_cost`, ...). + """ + for out, value in zip(self.state.values(), (data.time, data.qpos, data.qvel, data.act, data.qacc_warmstart)): + if isinstance(value, wp.array): + wp.copy(out, value.reshape(out.shape)) + else: + out.assign(np.reshape(value, out.shape)) + if self.config.planner == "ilqr": # from the last plan shifted to `t0` (after the first); then its first knots + steps, ref, bounds = self.config.node_steps, self._host["ctrl_ref"], self._host["bounds"] + shift = (t0 - self.t0) / steps if self.t0 < t0 else None + if shift and self.config.ctrl_steps > steps: # several knots a plan, as mjbatch: open loop, reference after + plan, new = self.ilqr_plan.x.numpy().reshape(self.batch_size, -1, self.nu), int(shift) + times = np.minimum(t0 + (plan.shape[1] - new + np.arange(new)) * steps, ref.shape[1] - 1) + plan, shift = np.concatenate([plan[:, new:], np.clip(ref[:, times], *bounds.T)], axis=1), None + self.ilqr_plan.x.assign(plan.reshape(self.batch_size, -1)) + self.ilqr.set_start(self.ilqr_start, t0) + _, costs = self.ilqr.solve(self.ilqr_plan, shift=shift) + self.t0 = t0 + plan = self.ilqr_plan.x.numpy().reshape(self.batch_size, -1, self.nu) + self.commands.assign(plan[:, np.arange(self.config.ctrl_steps) // steps].transpose(1, 0, 2)) + return self.commands, [dict(t0=t0, plan_cost=float(c) / self.config.horizon_steps) for c in costs.numpy()] + infos = self._optimize(t0) + self.clock.assign([t0, 0, 0]) + inputs = [self.execution, self.interpolation, self.ctrl_ref, self.clock, 1, 1, self.command_bounds] + dim = (self.batch_size, self.config.ctrl_steps, self.nu) + wp.launch(_compute_ctrl_kernel, dim=dim, inputs=inputs, outputs=[self.commands]) + inputs = [self.execution, self.shift] # the plans from `t0 + ctrl_steps` on + wp.launch(_compute_shifted_nodes_kernel, dim=self.shifted.shape, inputs=inputs, outputs=[self.shifted]) wp.copy(self.execution, self.shifted) - return record + return self.commands, infos - def solve( - self, num_steps: Union[int, Sequence[int]], callback: Optional[Callable[[List[dict]], None]] = None + def execute( + self, sim: "Sim", num_steps: int, callback: Optional[Callable[[List[dict]], None]] = None ) -> Tuple[List[Dict[str, np.ndarray]], List[List[dict]]]: - """Plan and simulate `num_steps` (or one length per instance); return each instance's rows and plan infos.""" - B, steps = self.batch_size, self.config.ctrl_steps - self.lengths = np.broadcast_to(np.asarray(num_steps), B) - if self.num_active < B: # a compacted earlier run - self._set_active_instances(B) - rows, infos = [], [[] for _ in range(B)] - for t0 in range(0, int(self.lengths.max()), steps): - active = np.flatnonzero(self.lengths > t0) - if active[-1] + 1 < self.num_active: - self._set_active_instances(int(active[-1]) + 1) - plan = self._optimize(t0) - rows.append(self._simulate(t0)) - for b in active: - infos[b].append(plan[b]) + """Run the planner in closed loop on `sim`, one world per instance, for `num_steps` sim steps: each control period plans from `sim`'s state, then steps `sim` through the commands, mapped by the config's `control_map` and clipped to the controls MuJoCo applies, and calls `callback` with every instance's plan info. + + Returns: + Each instance's rows, `time`, `qpos`, `qvel`, `ctrl` and `sensordata` (after the step), each `(num_steps, ...)`, and its plan info per control period. + """ + data, control_map = sim.data, self.config.control_map + clock = wp.zeros(3, dtype=int) # [t0, k, 0] for `control_map` + names, plans = ("time", "qpos", "qvel", "ctrl", "sensordata"), [] + rows = {name: wp.empty((num_steps, *getattr(data, name).shape), dtype=float) for name in names} # no syncs + for t0 in range(0, num_steps, self.config.ctrl_steps): + commands, infos = self.plan(data, t0) + for k in range(min(self.config.ctrl_steps, num_steps - t0)): + wp.copy(data.ctrl, commands[k]) + if control_map is not None: + clock.assign([t0, k, 0]) + control_map(sim, clock) + wp.launch(_set_clipped_ctrl_kernel, dim=data.ctrl.shape, inputs=[self.ctrl_limits], outputs=[data.ctrl]) + for name in names: + if name == "sensordata": # after the step + sim.step() + if rows[name].size: # no sensors: no sensordata + wp.copy(rows[name][t0 + k], getattr(data, name)) + plans.append(infos) if callback is not None: - callback(plan) - rollout = {k: np.concatenate([r[k] for r in rows], axis=1) for k in rows[0]} - return [{k: v[b, : len(infos[b]) * steps] for k, v in rollout.items()} for b in range(B)], infos + callback(infos) + rows = {name: np.moveaxis(x.numpy(), 0, 1) for name, x in rows.items()} # (nworld, num_steps, ...) + return [{name: x[i] for name, x in rows.items()} for i in range(sim.nworld)], [list(p) for p in zip(*plans)] -__all__ = ["SimBinding", "SimMPC"] +__all__ = ["SimMPC", "sim_context"] diff --git a/src/robokit/lie/se3.py b/src/robokit/lie/se3.py index 18a334a..276cae7 100644 --- a/src/robokit/lie/se3.py +++ b/src/robokit/lie/se3.py @@ -326,8 +326,8 @@ def device(self) -> wp_device_type: def clone(self) -> "SE3Var": return SE3Var(wp.clone(self._xyz_wxyz)) - def view(self, batch_size: int) -> "SE3Var": - return SE3Var(self._xyz_wxyz[:batch_size]) + def view(self, batch_size: int, offset: int = 0) -> "SE3Var": + return SE3Var(self._xyz_wxyz[offset : offset + batch_size]) def integrate( self, diff --git a/src/robokit/opt/__init__.py b/src/robokit/opt/__init__.py index c6fc189..96b22e7 100644 --- a/src/robokit/opt/__init__.py +++ b/src/robokit/opt/__init__.py @@ -4,7 +4,7 @@ if TYPE_CHECKING: - from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig + from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage def __getattr__(name: str): @@ -12,16 +12,17 @@ def __getattr__(name: str): from robokit.opt.population_solver import PopulationSolver return PopulationSolver - if name == "PopulationSolverConfig": - from robokit.opt.population_solver import PopulationSolverConfig + if name in ("PopulationSolverConfig", "Stage"): + from robokit.opt import population_solver - return PopulationSolverConfig + return getattr(population_solver, name) raise AttributeError(f"module 'robokit.opt' has no attribute {name!r}") __all__ = [ "PopulationSolver", "PopulationSolverConfig", + "Stage", "Var", "VarKey", "VarValues", diff --git a/src/robokit/opt/ilqr_optimizer.py b/src/robokit/opt/ilqr_optimizer.py new file mode 100644 index 0000000..c9419af --- /dev/null +++ b/src/robokit/opt/ilqr_optimizer.py @@ -0,0 +1,1065 @@ +# pyright: reportCallIssue=false +# pyright: reportArgumentType=false +"""Batched iLQR: iLQG on any batched dynamics, every step of it on the device. + +iLQG: https://homes.cs.washington.edu/~todorov/papers/TassaIROS12.pdf. MJPC: https://arxiv.org/abs/2212.00541. + +Each solve: +1. Nominal rollout: the initial guess, at the feedback scales. +2. Linearization: forward differences of `Dynamics.step` and the terms' residuals. +3. Backward pass: Gauss-Newton costs, control regularization, and a box QP on bounded controls. +4. Line search: one rollout per step size, every instance at once. +""" + +import copy +from dataclasses import dataclass +from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union, cast + +import numpy as np +import warp as wp + +from robokit.opt.optimizer import OptimizerConfig +from robokit.opt.var_values import Var, VarKey, VarValues, VectorVar +from robokit.terms.simulation.sim_context import SimContext +from robokit.terms.task import Context, ResidualTask +from robokit.utils.warp_utils import wp_device_type + + +f64 = wp.float64 # Warp 1.10 (the last for Python 3.8) types f64(x) as int-only: hence the ignores +_STEP_SIZES = np.r_[np.logspace(0, -3, 9), 0.0] # line-search step sizes +_FD_ROWS = 2**15 # most finite-difference rows stepped at once +_UNBOUNDED = 1e30 # stands in for an infinite control bound +_BOX_QP_MAX_ITER = wp.constant(100) +_ARMIJO_DECREASE = wp.constant(0.1) # the box QP line search's sufficient decrease +_ARMIJO_SHRINK = wp.constant(0.6) + + +# --- derivative kernels ----------------------------------------------------- +@wp.kernel +def _set_fd_rows_kernel( + knot0: int, + rows_per_knot: int, + total_knots: int, + ctrls: wp.array3d(dtype=float), # (N, T, nu) + fd_eps: wp.array(dtype=f64), # (ndx + nu,) + ctrl_upper: wp.array(dtype=float), + state_steps: wp.array2d(dtype=float), # (rows, ndx) + row_ctrls: wp.array2d(dtype=float), # (rows, nu) + step_sizes: wp.array(dtype=f64), # (rows,) +): + """Set each row's state step, controls and step size; a knot's first row steps nothing.""" + row = wp.tid() + knot = wp.min(knot0 + row // rows_per_knot, total_knots - 1) # pyright: ignore[reportOperatorIssue] + column = row % rows_per_knot - 1 # pyright: ignore[reportOperatorIssue] + horizon, state_dim, ctrl_dim = ctrls.shape[1], state_steps.shape[1], row_ctrls.shape[1] + instance = knot // (horizon + 1) + t = knot % (horizon + 1) + size = f64(0.0) # pyright: ignore[reportArgumentType] + if column >= 0: + size = fd_eps[column] + for j in range(state_dim): + state_steps[row, j] = 0.0 + if column >= 0 and column < state_dim: + state_steps[row, column] = float(size) + for j in range(ctrl_dim): + row_ctrls[row, j] = 0.0 + if t < horizon: + row_ctrls[row, j] = ctrls[instance, t, j] + if column >= state_dim: + j = column - state_dim + if row_ctrls[row, j] + float(size) > ctrl_upper[j]: # step down at an upper bound + size = -size + row_ctrls[row, j] += float(size) + step_sizes[row] = size + + +@wp.kernel +def _compute_fd_jacobians_kernel( + knot0: int, + rows_per_knot: int, + next_state_diffs: wp.array2d(dtype=float), # (rows, ndx) each row's next state less its knot's unstepped one + residuals: wp.array2d(dtype=float), # (rows, nr) + step_sizes: wp.array(dtype=f64), + dynamics_jacobians: wp.array4d(dtype=f64), # (N, T, ndx, ndx + nu) + residual_jacobians: wp.array4d(dtype=f64), # (N, T + 1, ndx + nu, nr) +): + """Compute one column of a knot's dynamics and residual Jacobians by forward differences.""" + chunk_knot, column = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + horizon = dynamics_jacobians.shape[1] + knot = knot0 + chunk_knot + base = chunk_knot * rows_per_knot + row = base + column + 1 + instance = knot // (horizon + 1) + t = knot % (horizon + 1) + size = step_sizes[row] + for m in range(residuals.shape[1]): + residual_jacobians[instance, t, column, m] = (f64(residuals[row, m]) - f64(residuals[base, m])) / size + if t < horizon: + for i in range(next_state_diffs.shape[1]): + dynamics_jacobians[instance, t, i, column] = f64(next_state_diffs[row, i]) / size + + +@wp.kernel +def _compute_gauss_newton_kernel( + knot0: int, + rows_per_knot: int, + residuals: wp.array2d(dtype=float), # (rows, nr), read at each knot's unstepped row + residual_jacobians: wp.array4d(dtype=f64), + cost_grad: wp.array3d(dtype=f64), # (N, T + 1, ndx + nu) + cost_hess: wp.array4d(dtype=f64), # (N, T + 1, ndx + nu, ndx + nu) +): + """Compute row i of a knot's Gauss-Newton cost gradient `J'r` and Hessian `J'J`.""" + chunk_knot, i = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + num_knots, knot_dim, residual_dim = residual_jacobians.shape[1], residual_jacobians.shape[2], residuals.shape[1] + instance = (knot0 + chunk_knot) // num_knots + t = (knot0 + chunk_knot) % num_knots + base = chunk_knot * rows_per_knot + s = f64(0.0) # pyright: ignore[reportArgumentType] + for m in range(residual_dim): + s += residual_jacobians[instance, t, i, m] * f64(residuals[base, m]) + cost_grad[instance, t, i] = s + for j in range(knot_dim): + s = f64(0.0) # pyright: ignore[reportArgumentType] + for m in range(residual_dim): + s += residual_jacobians[instance, t, i, m] * residual_jacobians[instance, t, j, m] + cost_hess[instance, t, i, j] = s + + +# --- backward pass kernels -------------------------------------------------- +@wp.func +def _compute_cholesky_func( + matrix: wp.array2d(dtype=f64), mu: f64, free: wp.array(dtype=int), factor: wp.array2d(dtype=f64) +) -> int: + """Factor `matrix + mu I` on the free rows and columns, identity elsewhere; return 0 unless positive definite.""" + for i in range(matrix.shape[0]): + for j in range(i + 1): + if free[i] == 0 or free[j] == 0: + factor[i, j] = f64(0.0) # pyright: ignore[reportArgumentType] + if i == j: + factor[i, j] = f64(1.0) # pyright: ignore[reportArgumentType] + else: + s = matrix[i, j] + if i == j: + s += mu + for m in range(j): + s -= factor[i, m] * factor[j, m] + if i == j: + if not (s > f64(0.0)): # pyright: ignore[reportArgumentType] + return 0 + factor[i, i] = wp.sqrt(s) + else: + factor[i, j] = s / factor[j, j] + return 1 + + +@wp.func +def _compute_cho_solve_func(factor: wp.array2d(dtype=f64), b: wp.array(dtype=f64)): + """Overwrite `b` with `(L L')^-1 b` for the Cholesky factor `L`.""" + n = factor.shape[0] + for i in range(n): + s = b[i] + for j in range(i): + s -= factor[i, j] * b[j] + b[i] = s / factor[i, i] + for ii in range(n): + i = n - 1 - ii + s = b[i] + for j in range(i + 1, n): + s -= factor[j, i] * b[j] + b[i] = s / factor[i, i] + + +@wp.func +def _compute_box_qp_cost_func( + quu: wp.array2d(dtype=f64), qu: wp.array(dtype=f64), mu: f64, du: wp.array(dtype=f64) +) -> f64: + """Return the box QP's cost of the step `du`, `du'(qu + (Quu + mu I) du / 2)`.""" + value = f64(0.0) # pyright: ignore[reportArgumentType] + for i in range(quu.shape[0]): + s = mu * du[i] + for j in range(quu.shape[0]): + s += quu[i, j] * du[j] + value += du[i] * (f64(0.5) * s + qu[i]) # pyright: ignore[reportArgumentType] + return value + + +@wp.kernel +def _compute_value_hess_ab_kernel( + t: int, + dynamics_jacobians: wp.array4d(dtype=f64), + value_hess: wp.array3d(dtype=f64), + value_hess_ab: wp.array3d(dtype=f64), # (N, ndx, ndx + nu) +): + """Compute entry (i, j) of `Vxx [A B]` at knot t.""" + instance, i, j = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + s = f64(0.0) # pyright: ignore[reportArgumentType] + for m in range(value_hess.shape[1]): + s += value_hess[instance, i, m] * dynamics_jacobians[instance, t, m, j] + value_hess_ab[instance, i, j] = s + + +@wp.kernel +def _compute_q_function_kernel( + t: int, + dynamics_jacobians: wp.array4d(dtype=f64), + cost_grad: wp.array3d(dtype=f64), + cost_hess: wp.array4d(dtype=f64), + value_grad: wp.array2d(dtype=f64), + value_hess_ab: wp.array3d(dtype=f64), + q_grad: wp.array2d(dtype=f64), # (N, ndx + nu): qx, qu + q_hess: wp.array3d(dtype=f64), # (N, ndx + nu, ndx + nu): H + [A B]' Vxx [A B] +): + """Compute entry (i, j) of knot t's Q-function Hessian, and its gradient entry i when j is 0.""" + instance, i, j = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + state_dim = value_grad.shape[1] + if j == 0: + s = cost_grad[instance, t, i] + for m in range(state_dim): + s += dynamics_jacobians[instance, t, m, i] * value_grad[instance, m] + q_grad[instance, i] = s + if i < state_dim and j >= state_dim: + return + s = cost_hess[instance, t, i, j] + for m in range(state_dim): + s += dynamics_jacobians[instance, t, m, i] * value_hess_ab[instance, m, j] + q_hess[instance, i, j] = s + + +@wp.kernel +def _solve_box_qp_kernel( + t: int, + q_grad: wp.array2d(dtype=f64), + q_hess: wp.array3d(dtype=f64), + ctrls: wp.array3d(dtype=float), + ctrl_lower: wp.array(dtype=f64), + ctrl_upper: wp.array(dtype=f64), + regularization: wp.array(dtype=f64), + ok: wp.array(dtype=int), + factors: wp.array3d(dtype=f64), # (N, nu, nu) Cholesky factor of the free controls' Quu + free: wp.array2d(dtype=int), # (N, nu) 1 where a control's bounds don't bind + steps: wp.array2d(dtype=f64), # (N, nu) + directions: wp.array2d(dtype=f64), + trials: wp.array2d(dtype=f64), + grads: wp.array2d(dtype=f64), + quus: wp.array3d(dtype=f64), + qus: wp.array2d(dtype=f64), + feedforward: wp.array3d(dtype=float), # (N, T + 1, nu), zero at the final knot +): + """Solve knot t's box QP for its feedforward step, keeping the free controls' factor.""" + instance = wp.tid() + if ok[instance] == 0: + return + factor, free_ctrls, du, direction = factors[instance], free[instance], steps[instance], directions[instance] + trial, grad, quu, qu = trials[instance], grads[instance], quus[instance], qus[instance] + ctrl_dim = qu.shape[0] + state_dim = q_hess.shape[1] - ctrl_dim + mu = regularization[instance] + for i in range(ctrl_dim): + qu[i] = q_grad[instance, state_dim + i] + free_ctrls[i] = 1 + for j in range(ctrl_dim): + quu[i, j] = q_hess[instance, state_dim + i, state_dim + j] + if _compute_cholesky_func(quu, mu, free_ctrls, factor) == 0: + ok[instance] = 0 + return + for i in range(ctrl_dim): + du[i] = -qu[i] + _compute_cho_solve_func(factor, du) # the unconstrained step + out = int(0) + for i in range(ctrl_dim): + if du[i] < ctrl_lower[i] - f64(ctrls[instance, t, i]) or du[i] > ctrl_upper[i] - f64(ctrls[instance, t, i]): + out = 1 + if out == 1: # projected Newton (Tassa 2014) from the next knot's step + value = f64(1e300) # pyright: ignore[reportArgumentType] + for i in range(ctrl_dim): + lower, upper = ctrl_lower[i] - f64(ctrls[instance, t, i]), ctrl_upper[i] - f64(ctrls[instance, t, i]) + du[i] = wp.clamp(f64(feedforward[instance, t + 1, i]), lower, upper) + for _ in range(_BOX_QP_MAX_ITER): + grad_norm, num_free = f64(0.0), int(0) # pyright: ignore[reportArgumentType] + for i in range(ctrl_dim): + s = qu[i] + mu * du[i] + for j in range(ctrl_dim): + s += quu[i, j] * du[j] + grad[i] = s + lower, upper = ctrl_lower[i] - f64(ctrls[instance, t, i]), ctrl_upper[i] - f64(ctrls[instance, t, i]) + free_ctrls[i] = 1 + if (du[i] <= lower and s > f64(0.0)) or (du[i] >= upper and s < f64(0.0)): # pyright: ignore[reportArgumentType] + free_ctrls[i] = 0 + else: + grad_norm += s * s + num_free += 1 + new_value = _compute_box_qp_cost_func(quu, qu, mu, du) + small = value - new_value < f64(1e-12) * (f64(1.0) + wp.abs(new_value)) # pyright: ignore[reportArgumentType, reportOperatorIssue] + if num_free == 0 or wp.sqrt(grad_norm) < f64(1e-8) or small: # pyright: ignore[reportArgumentType, reportOperatorIssue] + break + value = new_value + _compute_cholesky_func(quu, mu, free_ctrls, factor) + for i in range(ctrl_dim): + direction[i] = -grad[i] * f64(free_ctrls[i]) + _compute_cho_solve_func(factor, direction) + slope = f64(0.0) # pyright: ignore[reportArgumentType] + for i in range(ctrl_dim): + slope += grad[i] * direction[i] + a = f64(1.0) # pyright: ignore[reportArgumentType] + while a > f64(1e-12): # pyright: ignore[reportArgumentType, reportOperatorIssue] # projected Armijo + for i in range(ctrl_dim): + lower, upper = ( + ctrl_lower[i] - f64(ctrls[instance, t, i]), + ctrl_upper[i] - f64(ctrls[instance, t, i]), + ) + trial[i] = wp.clamp(du[i] + a * direction[i], lower, upper) + if _compute_box_qp_cost_func(quu, qu, mu, trial) - value <= f64(_ARMIJO_DECREASE) * a * slope: # pyright: ignore[reportOperatorIssue] + break + a *= f64(_ARMIJO_SHRINK) + if a <= f64(1e-12): # pyright: ignore[reportArgumentType, reportOperatorIssue] + break + for i in range(ctrl_dim): + du[i] = trial[i] + _compute_cholesky_func(quu, mu, free_ctrls, factor) # gains on the free controls only + for j in range(ctrl_dim): + feedforward[instance, t, j] = float(du[j]) + + +@wp.kernel +def _compute_gains_kernel( + t: int, + q_hess: wp.array3d(dtype=f64), + ok: wp.array(dtype=int), + factors: wp.array3d(dtype=f64), + free: wp.array2d(dtype=int), + columns: wp.array3d(dtype=f64), # (N, ndx, nu) scratch + feedback: wp.array4d(dtype=float), # (N, T, nu, ndx) +): + """Compute one column of knot t's gains, `-Quu^-1 Qux` on the free controls and zero on clamped ones.""" + instance, column = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + if ok[instance] == 0: + return + ctrl_dim = factors.shape[1] + state_dim = q_hess.shape[1] - ctrl_dim + gains = columns[instance, column] + for i in range(ctrl_dim): + gains[i] = -q_hess[instance, state_dim + i, column] * f64(free[instance, i]) + _compute_cho_solve_func(factors[instance], gains) + for i in range(ctrl_dim): + feedback[instance, t, i, column] = float(gains[i] * f64(free[instance, i])) + + +@wp.kernel +def _compute_q_gain_kernel( + t: int, q_hess: wp.array3d(dtype=f64), feedback: wp.array4d(dtype=float), q_gain: wp.array3d(dtype=f64) +): + """Compute entry (j, m) of `Qux + Quu K` at knot t.""" + instance, j, m = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + ctrl_dim = feedback.shape[2] + state_dim = q_hess.shape[1] - ctrl_dim + s = q_hess[instance, state_dim + j, m] + for p in range(ctrl_dim): + s += q_hess[instance, state_dim + j, state_dim + p] * f64(feedback[instance, t, p, m]) + q_gain[instance, j, m] = s + + +@wp.kernel +def _compute_value_function_kernel( + t: int, + q_grad: wp.array2d(dtype=f64), + q_hess: wp.array3d(dtype=f64), + q_gain: wp.array3d(dtype=f64), + feedforward: wp.array3d(dtype=float), + feedback: wp.array4d(dtype=float), + value_grad: wp.array2d(dtype=f64), + value_hess: wp.array3d(dtype=f64), +): + """Compute knot t's value Hessian entries (i, m) and (m, i), and on the diagonal its gradient entry i.""" + instance, i, m = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + state_dim, ctrl_dim = value_grad.shape[1], feedforward.shape[2] + if m < i: + return + a, b = f64(q_hess[instance, i, m]), f64(q_hess[instance, m, i]) # qxx is full: H's xx block plus A' Vxx A + for j in range(ctrl_dim): + a += f64(feedback[instance, t, j, i]) * q_gain[instance, j, m] + q_hess[instance, state_dim + j, i] * f64( + feedback[instance, t, j, m] + ) + b += f64(feedback[instance, t, j, m]) * q_gain[instance, j, i] + q_hess[instance, state_dim + j, m] * f64( + feedback[instance, t, j, i] + ) + value_hess[instance, i, m] = f64(0.5) * (a + b) # pyright: ignore[reportArgumentType] + value_hess[instance, m, i] = f64(0.5) * (a + b) # pyright: ignore[reportArgumentType] + if m == i: + s = f64(q_grad[instance, i]) + for j in range(ctrl_dim): + qk = f64(q_grad[instance, state_dim + j]) + for p in range(ctrl_dim): + qk += q_hess[instance, state_dim + j, state_dim + p] * f64(feedforward[instance, t, p]) + s += f64(feedback[instance, t, j, i]) * qk + q_hess[instance, state_dim + j, i] * f64( + feedforward[instance, t, j] + ) + value_grad[instance, i] = s + + +# --- rollout kernels -------------------------------------------------------- +@wp.kernel +def _compute_rollout_ctrls_kernel( + t: int, + final: int, + num_step_sizes: int, + scale_feedback: int, # 1: the step size scales the feedback instead of the feedforward (nominal rollouts) + feedback_cap: float, # > 0: clip the feedback to this times half the control range + ctrls: wp.array3d(dtype=float), # (N, T, nu) + feedforward: wp.array3d(dtype=float), # (N, T + 1, nu) + feedback: wp.array4d(dtype=float), # (N, T, nu, ndx) + step_sizes: wp.array(dtype=float), + ctrl_lower: wp.array(dtype=float), + ctrl_upper: wp.array(dtype=float), + state_diffs: wp.array2d(dtype=float), # (W, ndx) each world's state less its reference + rollout_ctrls: wp.array2d(dtype=float), # (W, nu) + ctrl_history: wp.array3d(dtype=float), # (T + 1, W, nu) +): + """Compute each world's clipped knot-t control `u + alpha k + K dx` (zero at the final knot) and record it.""" + world = wp.tid() + instance = world // num_step_sizes # pyright: ignore[reportOperatorIssue] + step_size = world % num_step_sizes # pyright: ignore[reportOperatorIssue] + for j in range(rollout_ctrls.shape[1]): + u = float(0.0) + if final == 0: + alpha, fb = float(step_sizes[step_size]), float(0.0) + for m in range(state_diffs.shape[1]): + fb += feedback[instance, t, j, m] * state_diffs[world, m] + if feedback_cap > 0.0: + cap = feedback_cap * 0.5 * (ctrl_upper[j] - ctrl_lower[j]) + fb = wp.clamp(fb, -cap, cap) + if scale_feedback == 1: + u = ctrls[instance, t, j] + alpha * fb + else: + u = ctrls[instance, t, j] + alpha * feedforward[instance, t, j] + fb + u = wp.clamp(u, ctrl_lower[j], ctrl_upper[j]) + rollout_ctrls[world, j] = u + ctrl_history[t, world, j] = u + + +@wp.kernel +def _compute_rollout_costs_kernel(num_knots: int, residuals: wp.array2d(dtype=float), costs: wp.array(dtype=f64)): + """Compute each world's rollout cost, `0.5 |r|^2` over its knots' residuals (knot-major rows).""" + world = wp.tid() + s = f64(0.0) # pyright: ignore[reportArgumentType] + for t in range(num_knots): + for m in range(residuals.shape[1]): + v = f64(residuals[t * costs.shape[0] + world, m]) + s += f64(0.5) * v * v # pyright: ignore[reportArgumentType] + costs[world] = s + + +@wp.kernel +def _accept_best_rollout_kernel( + num_step_sizes: int, + nominal: int, + improve: int, + min_regularization: f64, + rollout_costs: wp.array(dtype=f64), # (W,) + ok: wp.array(dtype=int), + costs_before: wp.array(dtype=f64), + ctrl_history: wp.array3d(dtype=float), # (T + 1, W, nu) + feedback: wp.array4d(dtype=float), + init_ctrls: wp.array3d(dtype=float), + costs: wp.array(dtype=f64), + regularization: wp.array(dtype=f64), + ctrls: wp.array3d(dtype=float), + gains: wp.array4d(dtype=float), + taken_rows: wp.array(dtype=int), # (T + 1) * N: the rollout state each knot takes, knot-major + taken: wp.array(dtype=int), # 1 where it takes one +): + """Accept knot t of each instance's cheapest rollout: of the step sizes, or nominal, of the feedback scales.""" + instance, t = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + batch_size, horizon, num_worlds = costs.shape[0], ctrls.shape[1], rollout_costs.shape[0] + best, value = int(-1), f64(1e300) # pyright: ignore[reportArgumentType] + for a in range(num_step_sizes): + v = rollout_costs[instance * num_step_sizes + a] + if wp.isfinite(v) and v < value: + best, value = a, v + source, take = int(0), int(0) + improved = ok[instance] == 1 and best >= 0 and (improve == 0 or value < costs_before[instance]) + if nominal == 1 and best < 0: # every nominal rollout failed: hold the initial guess, at x0, with no gains + source, take = instance * num_step_sizes, 1 # the rollouts' first knot: x0 + if t < horizon: + for j in range(ctrls.shape[2]): + ctrls[instance, t, j] = init_ctrls[instance, t, j] + if t == 0: + costs[instance] = value + elif nominal == 1 or improved: # take any best step + world = instance * num_step_sizes + wp.max(best, 0) + source, take = t * num_worlds + world, 1 + if t < horizon: + for j in range(ctrls.shape[2]): + ctrls[instance, t, j] = ctrl_history[t, world, j] + if nominal == 0: + for i in range(gains.shape[2]): + for j in range(gains.shape[3]): + gains[instance, t, i, j] = feedback[instance, t, i, j] + if t == 0: + costs[instance] = value + if nominal == 0: + regularization[instance] = wp.max(regularization[instance] / f64(10.0), min_regularization) # pyright: ignore[reportArgumentType] + elif t == 0: + regularization[instance] = regularization[instance] * f64(10.0) # pyright: ignore[reportArgumentType] + taken_rows[t * batch_size + instance] = source + taken[t * batch_size + instance] = take + + +@wp.kernel +def _set_shifted_init_kernel( + shift: float, + ctrls: wp.array3d(dtype=float), + gains: wp.array4d(dtype=float), + init_ctrls: wp.array3d(dtype=float), + init_gains: wp.array4d(dtype=float), + lo_rows: wp.array(dtype=int), + hi_rows: wp.array(dtype=int), + fractions: wp.array(dtype=float), +): + """Set the initial guess to the last solution `shift` knots on, linear between knots and held at the end.""" + instance, t = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + batch_size, horizon = ctrls.shape[0], ctrls.shape[1] + at = wp.min(float(t) + shift, float(horizon)) + lo = wp.min(int(at), horizon - 1) + lo_rows[t * batch_size + instance] = lo * batch_size + instance + hi_rows[t * batch_size + instance] = (lo + 1) * batch_size + instance + fractions[t * batch_size + instance] = at - float(lo) + if t == horizon: + return + at = wp.min(float(t) + shift, float(horizon - 1)) + lo = wp.min(int(at), horizon - 2) + f = at - float(lo) + for j in range(ctrls.shape[2]): + init_ctrls[instance, t, j] = (1.0 - f) * ctrls[instance, lo, j] + f * ctrls[instance, lo + 1, j] + for i in range(gains.shape[3]): + init_gains[instance, t, j, i] = (1.0 - f) * gains[instance, lo, j, i] + f * gains[instance, lo + 1, j, i] + + +@wp.kernel +def _set_scaled_residuals_kernel( + knot: int, # the rows' clock step, or -1: each row's, from `world_steps` + final_knot: int, # the final knot's clock step + world_steps: wp.array(dtype=wp.vec2i), + column_scales: wp.array2d(dtype=float), # (nr, 2) square roots of each column's running and terminal scales + residuals: wp.array2d(dtype=float), +): + """Scale each residual by the square root of its term's running scale, or at the final knot its terminal one.""" + row, column = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + t = knot + if knot < 0: + t = world_steps[row][1] + residuals[row, column] = residuals[row, column] * column_scales[column, wp.where(t == final_knot, 1, 0)] + + +@wp.kernel +def _set_scaled_rows_kernel(scale: wp.array(dtype=float), x: wp.array2d(dtype=float)): + """Scale row i of `x` by `scale[i]`.""" + i, j = wp.tid() # pyright: ignore[reportAssignmentType, reportGeneralTypeIssues] + x[i, j] = scale[i] * x[i, j] + + +# --- optimizer -------------------------------------------------------------- +class Dynamics: + """Batched discrete dynamics `x_next = step(x, u)` on `Var` states; subclasses implement `step`. + + Args: + nu: Controls per step. + ctrl_range: `(nu, 2)` control bounds, infinite where unbounded; None leaves every control unbounded. + steps_per_knot: Steps of the terms' clock (`SimContext.CLOCK`) one `step` spans. + """ + + def __init__(self, nu: int, ctrl_range: Optional[np.ndarray] = None, steps_per_knot: int = 1): + self.nu = nu + self.ctrl_range = ctrl_range + self.steps_per_knot = steps_per_knot + + def step(self, x: Var, u: wp.array, x_next: Var, finite_differences: bool = False): + """Write the states one step after `x` under controls `u` into `x_next`. + + Args: + x: States, a Var of `batch_size`. + u: `(batch_size, nu)` float32 controls. + x_next: The next states, a Var like `x`. + finite_differences: The rows are finite-difference steps: step them alike (a simulator: one contact order). + """ + raise NotImplementedError + + def get_context(self, batch_size: int, finite_differences: bool = False) -> Dict[Context, Any]: + """Return what the terms read of the worlds `step` steps, as they stand after each step. + + Args: + batch_size: States per step. + finite_differences: As in `step`. + + Returns: + The terms' context (`SimContext` for a simulator); empty by default. + """ + return {} + + +@dataclass(frozen=True) +class ILQROptimizerConfig(OptimizerConfig): + """`ILQROptimizer`'s settings; a solve is one CUDA graph, so it never stops early. + + Example: + >>> ILQROptimizerConfig().max_iter + 1 + """ + + max_iter: int = 1 + """Iterations per solve, after the nominal rollout: linearize, backward pass, line search.""" + cuda_graph_mode: Literal["none", "iter", "full"] = "full" + """"none" launches eagerly; else a CUDA device replays the whole solve as one graph.""" + state_eps: Union[float, Tuple[float, ...]] = 1e-4 + """Finite-difference step of the states: one for every tangent dimension, or one each.""" + ctrl_eps: float = 1e-3 + """Finite-difference step of the controls.""" + feedback_search: bool = True + """Run the nominal rollout at the best of the step sizes as feedback scale; else at full feedback.""" + improve: bool = False + """Take a line-search step only if it lowers the cost; else the best step, even 0.""" + feedback_cap: float = 0.0 + """If positive, clip each control's feedback `K dx` to this times half its range.""" + min_regularization: float = 1e-6 + """Control regularization (`Quu + mu I`) every solve starts from and keeps. Larger damps steps.""" + + +class ILQROptimizer: + """iLQG on a batch of plans at once, every step of it on the device. + + Solve sequence: + 1. `set_start(x0)`: the start states, a Var of `batch_size` instances. + 2. `solve(plan)`: refine `plan` in place: a nominal rollout, then `max_iter` iterations. + 3. Read `states` (knot-major: row `t * batch_size + instance`), `gains` and `costs`. + + Args: + dynamics: Batched dynamics. + terms: Residual terms of `VarKey.STATE` and `VarKey.ACTION`; the cost is `0.5 |r|^2` after every step. + config: Solver settings. + device: Warp device. + scales: `(num_terms, 2)` scales of each term's cost: at every knot but the final one, and at the final one. + """ + + # --- setup --- + def __init__( + self, + dynamics: Dynamics, + terms: Sequence[ResidualTask], + config: Optional[ILQROptimizerConfig] = None, + device: Optional[wp_device_type] = None, + scales: Optional[np.ndarray] = None, + ): + self.dynamics = dynamics + self.terms = list(terms) + self.scales = np.ones((len(self.terms), 2)) if scales is None else np.asarray(scales, dtype=float) + self.config = config if config is not None else ILQROptimizerConfig() + self.device = wp.get_device(device) + self._x0: Optional[Var] = None + self._built = False + self._graph: Optional[wp.Graph] = None + + def set_start(self, x0: Var, step: int = 0): + """Start the next solves from `x0`, at sim step `step` of the terms' references. + + Args: + x0: Start states, a Var of `batch_size` instances. + step: Sim step of the terms' references at the start. + """ + if self._x0 is None: + self._x0 = x0.clone() + self._x0_rows = wp.array(np.arange(x0.batch_size), dtype=int, device=self.device) + self._clock = wp.array([step, 0, 0], dtype=int, device=self.device) # `SimContext.CLOCK` + else: + x0.gather(self._x0_rows, out=self._x0) + self._clock[0:1].fill_(step) + + # --- solve --- + def solve(self, plan: VectorVar, shift: Optional[float] = None) -> Tuple[VectorVar, wp.array]: + """Refine the controls `plan` from the start states. + + Args: + plan: `(batch_size, horizon * nu)` controls, refined in place; the initial guess when `shift` is None. + shift: Knots to shift the last solution by for the initial guess, as a receding horizon. + + Returns: + `plan` and each instance's float64 cost. + """ + if self._x0 is None: + raise ValueError("set_start before solve") + with wp.ScopedDevice(self.device): + if not self._built: + self._build(plan) + batch_size, horizon, nu = self._ctrls.shape + ctrls = plan.x.reshape((batch_size, horizon, nu)) + if shift is None: # open loop from the start + wp.copy(self._init_ctrls, ctrls) + self._init_gains.zero_() + self._x0.gather(self._start_rows, out=self._init_states) + else: # the states between knots: lo + fraction (hi - lo), on their manifold + wp.launch( + _set_shifted_init_kernel, + (batch_size, horizon + 1), + inputs=[float(shift), self._ctrls, self.gains], + outputs=[self._init_ctrls, self._init_gains, self._lo_rows, self._hi_rows, self._fractions], + ) + lo_states = self.states.gather(self._lo_rows, out=self._lo_states) + hi_states = self.states.gather(self._hi_rows, out=self._hi_states) + diffs = lo_states.difference(hi_states, out=self._shift_diffs) + wp.launch(_set_scaled_rows_kernel, diffs.shape, inputs=[self._fractions], outputs=[diffs]) + lo_states.integrate(diffs, out=self._init_states) + capturing = self.device.is_cuda and wp.get_stream().is_capturing + if self._graph is None and self.config.cuda_graph_mode != "none" and self.device.is_cuda and not capturing: + self._solve_body() # compile, and let the dynamics allocate, before capturing + with wp.ScopedCapture() as capture: + self._solve_body() + self._graph = capture.graph + if self._graph is not None and not capturing: + wp.capture_launch(self._graph) + else: + self._solve_body() + wp.copy(ctrls, self._ctrls) + return plan, self.costs + + def _solve_body(self): + """Run the nominal rollout, then per iteration the linearization, backward pass and line search.""" + self._regularization.fill_(self.config.min_regularization) + wp.copy(self.gains, self._init_gains) # the last gains stand if a backward pass fails + init = (self._init_states, self._init_ctrls, self._zero_feedforward, self._init_gains, self._feedback_scales) + self._compute_rollouts(*init, nominal=True) + for _ in range(self.config.max_iter): + self._compute_derivatives() + self._compute_backward_pass() + line_search = (self.states, self._ctrls, self._feedforward, self._feedback, self._step_sizes) + self._compute_rollouts(*line_search, nominal=False) + + # --- build --- + def _build(self, plan: VectorVar): + """Allocate every buffer at the first plan's size and resolve the terms on the worlds they read.""" + config, dynamics, x0 = self.config, self.dynamics, self._x0 + assert x0 is not None + batch_size = x0.batch_size + state_dim = x0.tangent_dim + nu = dynamics.nu + horizon = plan.tangent_dim // nu + num_knots = horizon + 1 # the last knot has only the terminal cost + knot_dim = state_dim + nu # a knot's tangent columns: states, then controls + num_step_sizes = len(_STEP_SIZES) + num_worlds = batch_size * num_step_sizes # every step size of every instance, instance-major + self._rows_per_knot = knot_dim + 1 # the unstepped knot, then one row per tangent column + self._knots_per_chunk = min(max(1, _FD_ROWS // self._rows_per_knot), batch_size * num_knots) + num_rows = self._knots_per_chunk * self._rows_per_knot + f32, i32 = wp.float32, wp.int32 + + def zeros(*shape: int, dtype: Any = f64) -> wp.array: + return wp.zeros(shape, dtype=dtype) + + def index(rows: Any) -> wp.array: + return wp.array(np.asarray(rows).ravel(), dtype=i32) + + def states(n: int) -> Var: + return x0.gather(wp.zeros(n, dtype=i32)) + + # settings + ctrl_range = np.full((nu, 2), [-np.inf, np.inf]) if dynamics.ctrl_range is None else dynamics.ctrl_range + lower, upper = np.clip(ctrl_range, -_UNBOUNDED, _UNBOUNDED).T + self._ctrl_lower, self._ctrl_upper = wp.array(lower, dtype=f32), wp.array(upper, dtype=f32) + self._ctrl_lower64, self._ctrl_upper64 = wp.array(lower, dtype=f64), wp.array(upper, dtype=f64) + fd_eps = np.r_[np.broadcast_to(config.state_eps, (state_dim,)), np.full(nu, config.ctrl_eps)] + self._fd_eps = wp.array(fd_eps, dtype=f64) + self._step_sizes = wp.array(_STEP_SIZES, dtype=f32) + self._feedback_scales = wp.array(_STEP_SIZES if config.feedback_search else np.ones(num_step_sizes), dtype=f32) + + # the solution, with states knot-major (row t * batch_size + instance) + self._ctrls = zeros(batch_size, horizon, nu, dtype=f32) + self.gains = zeros(batch_size, horizon, nu, state_dim, dtype=f32) + self.costs = zeros(batch_size) + self.states = states(num_knots * batch_size) + + # the initial guess, and the shift's scratch + self._init_ctrls = zeros(batch_size, horizon, nu, dtype=f32) + self._init_gains = zeros(batch_size, horizon, nu, state_dim, dtype=f32) + self._init_states = states(num_knots * batch_size) + self._zero_feedforward = zeros(batch_size, num_knots, nu, dtype=f32) + self._start_rows = index(np.tile(np.arange(batch_size), num_knots)) + self._lo_rows = zeros(num_knots * batch_size, dtype=i32) + self._hi_rows = zeros(num_knots * batch_size, dtype=i32) + self._fractions = zeros(num_knots * batch_size, dtype=f32) + self._lo_states = states(num_knots * batch_size) + self._hi_states = states(num_knots * batch_size) + self._shift_diffs = zeros(num_knots * batch_size, state_dim, dtype=f32) + + # rollouts, knot-major (row t * num_worlds + world) + self._rollout_states = states((horizon + 2) * num_worlds) + self._rollout_knots = [self._rollout_states.view(num_worlds, t * num_worlds) for t in range(horizon + 2)] + self._rollout_refs = states(num_knots * num_worlds) + self._rollout_ref_knots = [self._rollout_refs.view(num_worlds, t * num_worlds) for t in range(num_knots)] + worlds = np.arange(num_worlds) + self._rollout_ref_rows = index([t * batch_size + worlds // num_step_sizes for t in range(num_knots)]) + self._rollout_start_rows = index(worlds // num_step_sizes) + self._rollout_diffs = zeros(num_worlds, state_dim, dtype=f32) + self._rollout_ctrls = zeros(num_worlds, nu, dtype=f32) + self._rollout_ctrl_history = zeros(num_knots, num_worlds, nu, dtype=f32) + self._rollout_costs = zeros(num_worlds) + self._costs_before = zeros(batch_size) + self._taken_rows = zeros(num_knots * batch_size, dtype=i32) + self._taken = zeros(num_knots * batch_size, dtype=i32) + self._taken_states = states(num_knots * batch_size) + + # finite differences, a chunk of knots at a time: row r steps column r % rows_per_knot - 1 of its knot + rows = np.arange(num_rows) + self._fd_state_rows, self._fd_chunk_steps = [], [] # each row's knot state, and its (instance, step) + for knot0 in range(0, batch_size * num_knots, self._knots_per_chunk): + knots = np.minimum(knot0 + rows // self._rows_per_knot, batch_size * num_knots - 1) # spare rows: the last + self._fd_state_rows.append(index(knots % num_knots * batch_size + knots // num_knots)) + steps = np.c_[knots // num_knots, knots % num_knots * dynamics.steps_per_knot].astype(np.int32) + self._fd_chunk_steps.append(wp.array(steps, dtype=wp.vec2i)) + self._fd_unstepped_rows = index(rows // self._rows_per_knot * self._rows_per_knot) + self._fd_states = states(num_rows) + self._fd_next_states = states(num_rows) + self._fd_unstepped_states = states(num_rows) + self._fd_state_steps = zeros(num_rows, state_dim, dtype=f32) + self._fd_ctrls = zeros(num_rows, nu, dtype=f32) + self._fd_next_diffs = zeros(num_rows, state_dim, dtype=f32) + self._fd_step_sizes = zeros(num_rows) + self._fd_world_steps = zeros(num_rows, dtype=wp.vec2i) + + # the terms, resolved on the rollouts' worlds and on the finite-difference rows + self._rollout_vars = [ + VarValues({VarKey.STATE: x, VarKey.ACTION: VectorVar(self._rollout_ctrls)}) + for x in self._rollout_knots[:num_knots] + ] + self._fd_vars = VarValues({VarKey.STATE: self._fd_states, VarKey.ACTION: VectorVar(self._fd_ctrls)}) + shared = {SimContext.CLOCK: self._clock, SimContext.NUM_INSTANCES: batch_size} + rollout_context = {**dynamics.get_context(num_worlds), **shared, SimContext.WORLDS_PER_INSTANCE: num_step_sizes} + fd_context = {**dynamics.get_context(num_rows, True), **shared, SimContext.WORLDS_PER_INSTANCE: 1} + fd_context[SimContext.WORLD_STEPS] = self._fd_world_steps + self._rollout_terms = [copy.copy(term) for term in self.terms] + self._fd_terms = [copy.copy(term) for term in self.terms] + for term in self._rollout_terms: + term.resolve(self._rollout_vars[0], rollout_context) + for term in self._fd_terms: + term.resolve(self._fd_vars, fd_context) + residual_dims = [term.residual_dim for term in self._rollout_terms] + residual_dim = sum(residual_dims) + self._column_scales = wp.array(np.repeat(np.sqrt(self.scales), residual_dims, axis=0), dtype=f32) + self._rollout_residuals = zeros(num_knots * num_worlds, residual_dim, dtype=f32) + knot_residuals = [self._rollout_residuals[t * num_worlds : (t + 1) * num_worlds] for t in range(num_knots)] + self._rollout_knot_residuals = cast(List[wp.array], knot_residuals) + self._fd_residuals = zeros(num_rows, residual_dim, dtype=f32) + + # derivatives at every knot + self.dynamics_jacobians = zeros(batch_size, horizon, state_dim, knot_dim) + self._residual_jacobians = zeros(batch_size, num_knots, knot_dim, residual_dim) + self._cost_grad = zeros(batch_size, num_knots, knot_dim) + self._cost_hess = zeros(batch_size, num_knots, knot_dim, knot_dim) + + # backward pass, with the box QP's scratch, and the feedforward steps and feedback gains it finds + self._regularization = zeros(batch_size) + self._backward_ok = zeros(batch_size, dtype=int) + self._value_grad = zeros(batch_size, state_dim) + self._value_hess = zeros(batch_size, state_dim, state_dim) + self._q_grad = zeros(batch_size, knot_dim) + self._q_hess = zeros(batch_size, knot_dim, knot_dim) + self._value_hess_ab = zeros(batch_size, state_dim, knot_dim) + self._q_gain = zeros(batch_size, nu, state_dim) + self._gain_columns = zeros(batch_size, state_dim, nu) + self._qp_factors = zeros(batch_size, nu, nu) + self._qp_free = zeros(batch_size, nu, dtype=int) + self._qp_steps = zeros(batch_size, nu) + self._qp_directions = zeros(batch_size, nu) + self._qp_trials = zeros(batch_size, nu) + self._qp_grads = zeros(batch_size, nu) + self._qp_quus = zeros(batch_size, nu, nu) + self._qp_qus = zeros(batch_size, nu) + self._feedforward = zeros(batch_size, num_knots, nu, dtype=f32) + self._feedback = zeros(batch_size, horizon, nu, state_dim, dtype=f32) + self._built = True + + # --- rollouts --- + def _compute_rollouts( + self, + ref_states: Var, + ctrls: wp.array, + feedforward: wp.array, + feedback: wp.array, + scales: wp.array, + nominal: bool, + ): + """Roll out each instance at every scale of its feedforward (nominal: feedback) and keep the cheapest.""" + x0, config = self._x0, self.config + assert x0 is not None + batch_size, horizon, _ = self._ctrls.shape + num_worlds, num_step_sizes = self._rollout_ctrls.shape[0], self._step_sizes.shape[0] + x0.gather(self._rollout_start_rows, out=self._rollout_knots[0]) + ref_states.gather(self._rollout_ref_rows, out=self._rollout_refs) # each world's reference, every knot + for t in range(horizon + 1): + self._rollout_ref_knots[t].difference(self._rollout_knots[t], out=self._rollout_diffs) + wp.launch( + _compute_rollout_ctrls_kernel, + num_worlds, + inputs=[ + t, + int(t == horizon), + num_step_sizes, + int(nominal), + config.feedback_cap, + ctrls, + feedforward, + feedback, + scales, + self._ctrl_lower, + self._ctrl_upper, + self._rollout_diffs, + ], + outputs=[self._rollout_ctrls, self._rollout_ctrl_history], + ) + self.dynamics.step(self._rollout_knots[t], self._rollout_ctrls, self._rollout_knots[t + 1]) + step = t * self.dynamics.steps_per_knot # the terms' clock + self._clock[1:2].fill_(step) + self._compute_residuals(self._rollout_terms, self._rollout_vars[t], self._rollout_knot_residuals[t], step) + wp.launch( + _compute_rollout_costs_kernel, + num_worlds, + inputs=[horizon + 1, self._rollout_residuals], + outputs=[self._rollout_costs], + ) + wp.copy(self._costs_before, self.costs) # every knot compares against the cost before this acceptance + wp.launch( + _accept_best_rollout_kernel, + (batch_size, horizon + 1), + inputs=[ + num_step_sizes, + int(nominal), + int(config.improve), + config.min_regularization, + self._rollout_costs, + self._backward_ok, + self._costs_before, + self._rollout_ctrl_history, + self._feedback, + self._init_ctrls, + ], + outputs=[self.costs, self._regularization, self._ctrls, self.gains, self._taken_rows, self._taken], + ) + self._rollout_states.gather(self._taken_rows, out=self._taken_states) + self.states.accept(self._taken, self._taken_states) + + # --- derivatives --- + def _compute_derivatives(self): + """Compute every knot's dynamics and residual Jacobians by forward differences, and its Gauss-Newton costs.""" + batch_size, horizon, _ = self._ctrls.shape + total_knots = batch_size * (horizon + 1) + knot_dim, num_rows = self._cost_grad.shape[2], self._fd_step_sizes.shape[0] + for chunk, (state_rows, chunk_steps) in enumerate(zip(self._fd_state_rows, self._fd_chunk_steps)): + knot0 = chunk * self._knots_per_chunk + chunk_knots = min(self._knots_per_chunk, total_knots - knot0) + wp.launch( + _set_fd_rows_kernel, + num_rows, + inputs=[knot0, self._rows_per_knot, total_knots, self._ctrls, self._fd_eps, self._ctrl_upper], + outputs=[self._fd_state_steps, self._fd_ctrls, self._fd_step_sizes], + ) + self.states.gather(state_rows, out=self._fd_states) + self._fd_states.integrate(self._fd_state_steps, out=self._fd_states) + self.dynamics.step(self._fd_states, self._fd_ctrls, self._fd_next_states, finite_differences=True) + wp.copy(self._fd_world_steps, chunk_steps) + self._compute_residuals(self._fd_terms, self._fd_vars, self._fd_residuals, -1) + self._fd_next_states.gather(self._fd_unstepped_rows, out=self._fd_unstepped_states) + self._fd_unstepped_states.difference(self._fd_next_states, out=self._fd_next_diffs) + wp.launch( + _compute_fd_jacobians_kernel, + (chunk_knots, knot_dim), + inputs=[knot0, self._rows_per_knot, self._fd_next_diffs, self._fd_residuals, self._fd_step_sizes], + outputs=[self.dynamics_jacobians, self._residual_jacobians], + ) + wp.launch( + _compute_gauss_newton_kernel, + (chunk_knots, knot_dim), + inputs=[knot0, self._rows_per_knot, self._fd_residuals, self._residual_jacobians], + outputs=[self._cost_grad, self._cost_hess], + ) + + def _compute_residuals(self, terms: List[ResidualTask], var: VarValues, out: wp.array, knot: int): + """Compute every term's scaled residuals of `var` at clock step `knot` (-1: each row's), side by side in `out`.""" + offset = 0 + for term in terms: + term.precompute(var) + term.compute_weighted_residual(var, out_residual=out, row_offset=offset) + offset += term.residual_dim + inputs = [knot, self._ctrls.shape[1] * self.dynamics.steps_per_knot, self._fd_world_steps, self._column_scales] + wp.launch(_set_scaled_residuals_kernel, out.shape, inputs=inputs, outputs=[out]) + + # --- backward pass --- + def _compute_backward_pass(self): + """Compute every knot's feedforward step and feedback gains, from the last knot back.""" + batch_size, horizon, nu = self._ctrls.shape + state_dim, knot_dim = self._value_grad.shape[1], self._q_grad.shape[1] + # the final knot's value is its cost + final_grad = self._cost_grad[:, horizon, :state_dim] + final_hess = self._cost_hess[:, horizon, :state_dim, :state_dim] + wp.copy(self._value_grad, final_grad) # pyright: ignore[reportArgumentType] + wp.copy(self._value_hess, final_hess) # pyright: ignore[reportArgumentType] + self._feedforward[:, horizon].zero_() + self._backward_ok.fill_(1) + for t in reversed(range(horizon)): + wp.launch( + _compute_value_hess_ab_kernel, + (batch_size, state_dim, knot_dim), + inputs=[t, self.dynamics_jacobians, self._value_hess], + outputs=[self._value_hess_ab], + ) + wp.launch( + _compute_q_function_kernel, + (batch_size, knot_dim, knot_dim), + inputs=[ + t, + self.dynamics_jacobians, + self._cost_grad, + self._cost_hess, + self._value_grad, + self._value_hess_ab, + ], + outputs=[self._q_grad, self._q_hess], + ) + wp.launch( + _solve_box_qp_kernel, + batch_size, + inputs=[ + t, + self._q_grad, + self._q_hess, + self._ctrls, + self._ctrl_lower64, + self._ctrl_upper64, + self._regularization, + ], + outputs=[ + self._backward_ok, + self._qp_factors, + self._qp_free, + self._qp_steps, + self._qp_directions, + self._qp_trials, + self._qp_grads, + self._qp_quus, + self._qp_qus, + self._feedforward, + ], + ) + wp.launch( + _compute_gains_kernel, + (batch_size, state_dim), + inputs=[t, self._q_hess, self._backward_ok, self._qp_factors, self._qp_free], + outputs=[self._gain_columns, self._feedback], + ) + wp.launch( + _compute_q_gain_kernel, + (batch_size, nu, state_dim), + inputs=[t, self._q_hess, self._feedback], + outputs=[self._q_gain], + ) + wp.launch( + _compute_value_function_kernel, + (batch_size, state_dim, state_dim), + inputs=[t, self._q_grad, self._q_hess, self._q_gain, self._feedforward, self._feedback], + outputs=[self._value_grad, self._value_hess], + ) diff --git a/src/robokit/opt/lbfgs_optimizer.py b/src/robokit/opt/lbfgs_optimizer.py index 7069f58..c507577 100644 --- a/src/robokit/opt/lbfgs_optimizer.py +++ b/src/robokit/opt/lbfgs_optimizer.py @@ -35,8 +35,7 @@ class LBFGSOptimizerConfig(OptimizerConfig): wolfe_c2: float = 0.9 """Curvature constant (approx_wolfe).""" line_search: Literal["armijo", "approx_wolfe"] = "armijo" - """armijo: largest passing trial, else no step; approx_wolfe: largest Armijo/curvature trial, else smallest, - and needs folded gradients.""" + """armijo: largest passing trial, else no step; approx_wolfe: largest Armijo/curvature trial, else smallest, and needs folded gradients.""" normalize_direction: bool = False """Normalize directions so trial steps are lengths; H0 then uses `h0_scale` instead of Barzilai-Borwein.""" gradient_mode: Literal["analytic_jacobian", "autodiff", "analytic_gradient"] = "analytic_jacobian" @@ -344,8 +343,7 @@ def _compute_search_direction( bb = normalize == 0 and count > 0 and y_y > 1.0e-12 gamma = wp.where(bb, warp_shuffle(total, pairs + 1) / y_y, h0_scale) - # second loop, oldest to newest: beta_i = rho_i y_i . (gamma q + sum over older j of - # (alpha_j - beta_j) s_j) + # second loop, oldest to newest: beta_i = rho_i y_i . (gamma q + sum over older j of (alpha_j - beta_j) s_j) coefficient = history_vector() # alpha_i - beta_i s_r = float(0.0) for j in range(pairs): diff --git a/src/robokit/opt/population_solver.py b/src/robokit/opt/population_solver.py index 8cc0cb7..8573822 100644 --- a/src/robokit/opt/population_solver.py +++ b/src/robokit/opt/population_solver.py @@ -46,38 +46,41 @@ def _select_best_k_kernel(costs: wp.array1d(dtype=wp.float32), width: int, best_ prev_j = best_j +# Warp 1.15+ also records CPU launches and replays them in a native loop, saving each launch's Python cost. +_CPU_CAPTURE = tuple(int(x) for x in wp.__version__.split(".")[:2]) >= (1, 15) + # Tile sort is faster on wide populations, but warp 1.8's CPU tile sort segfaults; 1.8 uses the plain loop above. _TILE_SELECT = not wp.__version__.startswith("1.8.") @dataclass -class PopulationSolverConfig: - """What a round does, and when. Iterations are global; every operation is a schedule over them.""" +class Stage: + """A run of `iters` iterations at one population width. Entering a stage keeps each instance's best `num_candidates` (the first stage's is the input width); unset fields keep the previous stage's.""" - num_iters: int = 10 - """Iterations of the whole schedule.""" - optimizer: Union[None, OptimizerConfig, Sequence[OptimizerConfig]] = None - """Choose a gradient update per iteration or segment (e.g. damping decreases as the beam narrows). + iters: int = 0 + """Iterations of this stage.""" + num_candidates: Optional[int] = None + """Population width per instance; None: the previous stage's, or 1.""" + optimizer: Optional[OptimizerConfig] = None + """Gradient update; None: the previous stage's. With none in any stage: drawing samplers (MPPI/ES) update by sampling, other solvers by dense LM.""" + sample_every: int = 0 + """Draw with the samplers every this many iterations from the stage's start; 0 in every stage: a drawing sampler draws before every score and once after the last, others at each select.""" - None defaults: - - Drawing samplers (MPPI/ES): no gradient update. - - Other solvers: dense LM. - """ + +@dataclass +class PopulationSolverConfig: + """What a round does, and when: `stages` run in order, iterations counted across them.""" + + stages: List[Stage] = field(default_factory=lambda: [Stage(iters=10)]) + """The schedule, e.g. `[Stage(6, 64, LMOptimizerConfig(lm_lambda=10.0)), Stage(10, 4), Stage(0, 1)]`: 64 candidates for 6 iterations, the best 4 for 10 more, then the best one.""" samplers: Sequence[SamplerConfig] = field(default_factory=tuple) - """Built during setup, then applied in order at `sample_at`.""" - sample_at: Sequence[int] = () - """Zero-based sampling iterations. + """Built during setup, then applied in order where the stages sample. - At each scheduled iteration: + At each sampling iteration: 1. Sample the population before optimizing. 2. Restart the optimizer on that population. - 3. If scheduled at `num_iters`, sample after the final score and end on the moved candidates. + 3. At the last iteration, sample after the final score and end on the moved candidates. """ - select_at: Sequence[int] = () - """Iterations (1-based, after the update) at which the best `num_candidates[k + 1]` per instance are kept.""" - num_candidates: List[int] = field(default_factory=lambda: [1]) - """Population width per instance in each segment: the input's, then one per select.""" - cuda_graph_mode: Literal["none", "full", "iter"] = "iter" """"iter" replays one optimizer step per width; "full" the whole solve (no callbacks or early stopping).""" use_early_stopping: bool = True @@ -85,9 +88,7 @@ class PopulationSolverConfig: rank_final: bool = False """Score only the final population and return it best first; earlier selects keep the optimization cost.""" min_improvement: float = 0.0 - """If positive, a drawing sampler's solve ends once each instance's cheapest draw beats its first one (the center) - by less than this, `patience` scores in a row; the last sample still moves the candidates. Reads scores on the - host.""" + """If positive, a drawing sampler's solve ends once each instance's cheapest draw beats its first one (the center) by less than this, `patience` scores in a row; the last sample still moves the candidates. Reads scores on the host.""" patience: int = 2 @property @@ -95,18 +96,51 @@ def num_draws(self) -> int: """The widest the population gets per candidate: the drawing sampler's draw count, or 1.""" return max((s.num_draws for s in self.samplers), default=1) + @property + def num_iters(self) -> int: + """Iterations of the whole schedule.""" + return sum(stage.iters for stage in self.stages) + + @property + def select_at(self) -> List[int]: + """Iterations (1-based, after the update) where a stage ends and the next one's width is kept.""" + return [int(i) for i in np.cumsum([stage.iters for stage in self.stages])[:-1]] + + @property + def num_candidates(self) -> List[int]: + """Population width per instance in each stage.""" + widths = [1] + for stage in self.stages: + widths.append(widths[-1] if stage.num_candidates is None else stage.num_candidates) + return widths[1:] + + @property + def optimizer(self) -> Optional[List[Optional[OptimizerConfig]]]: + """Each stage's gradient update, or None if no stage sets one.""" + configs: List[Optional[OptimizerConfig]] = [None] + for stage in self.stages: + configs.append(stage.optimizer or configs[-1]) + return configs[1:] if any(configs) else None + + @property + def sample_at(self) -> List[int]: + """Zero-based sampling iterations; empty: the default (see `Stage.sample_every`).""" + starts = [0, *np.cumsum([stage.iters for stage in self.stages])] + return [ + i + for k, s in enumerate(self.stages) + if s.sample_every + for i in range(starts[k], starts[k + 1], s.sample_every) + ] + def __post_init__(self): - self.num_candidates = list(self.num_candidates) + self.stages = list(self.stages) + if not self.stages or any(stage.iters < 0 for stage in self.stages): + raise ValueError("stages must be a non-empty list with non-negative iters") if any(not isinstance(s, SamplerConfig) for s in self.samplers): raise TypeError("samplers must contain SamplerConfig objects, not runtime samplers") if sum(s.num_draws > 1 for s in self.samplers) > 1: # a second one would draw around the first one's draws raise ValueError("at most one sampler may draw more than one candidate") - if isinstance(self.optimizer, (list, tuple)) and len(self.optimizer) != len(self.num_candidates): - raise ValueError(f"one optimizer config per segment: {len(self.num_candidates)}, got {len(self.optimizer)}") - if len(self.num_candidates) != len(self.select_at) + 1: - raise ValueError( - f"num_candidates needs one width per segment: {len(self.select_at) + 1}, got {len(self.num_candidates)}" - ) if self.min_improvement > 0 and max(self.num_candidates) > 1: # it compares each instance's one center raise ValueError("min_improvement needs one candidate per instance") @@ -150,8 +184,8 @@ def __init__( self.score_terms = [score_terms] * num_segments if config.rank_final: self.score_terms = [None] * (num_segments - 1) + self.score_terms[-1:] - self._supports_cuda_graph = ( - self.device.is_cuda + self._can_capture = ( + (self.device.is_cuda or _CPU_CAPTURE) and all(t.SUPPORTS_CUDA_GRAPH for seg in self.terms for t in seg) and all(s is None or s.SUPPORTS_CUDA_GRAPH for s in self.score_terms) ) @@ -228,10 +262,10 @@ def setup(self, var: VarValues): widths = [max(sum(t.residual_dim for t in ts if isinstance(t, ResidualTask)), 1) for ts in self.terms] self._residuals = [wp.zeros((max_width, w), dtype=wp.float32, device=self.device) for w in widths] self.candidate_scores: Optional[wp.array] = None # live scores of the current population - if cfg.num_draws > 1: # terms size their buffers to the first population they see: make it the widest - self._score(self._draws(var), 0, None, rank=False) + # terms size their buffers to the first population they see: make it the widest + self._score(self._draws(var), 0, None, rank=False) self._full_graph = None - if mode == "full" and self._supports_cuda_graph: + if mode == "full" and self._can_capture: self._warmup_and_capture() self._initialized = True @@ -265,7 +299,7 @@ def _run_solve_body(self, sync_each_stage: bool = False): - `sync_each_stage`: eager warmup for "full" capture; drain each select and cap segments at two iterations. """ cfg = self.config - capturing = self.device.is_cuda and wp.get_stream(self.device).is_capturing + capturing = self.device.is_capturing selects = list(cfg.select_at) num_iters = cfg.num_iters if sync_each_stage: # warmup schedule: same selects, at most two iterations per segment @@ -299,7 +333,7 @@ def _run_solve_body(self, sync_each_stage: bool = False): optimizer.reset(cur, steps()) reset_on = cur scores = self._score(cur, segment, optimizer, rank=False) - ranked, stall = False, np.zeros(self.batch_size, int) + ranked, recent = False, [] # with `min_improvement`, each score of this solve while it < num_iters: if it in samples: # a sampled population is a fresh start for the optimizer (damping, history) cur, reset_on = self._sample(cur, scores), None @@ -313,9 +347,10 @@ def _run_solve_body(self, sync_each_stage: bool = False): ranked = selecting or it == num_iters scores = self._score(cur, segment, optimizer, rank=ranked) if cfg.min_improvement > 0 and cfg.num_draws > 1 and not capturing: # a plateau: skip to the last sample - costs = scores.numpy().reshape(self.batch_size, -1) - stall = np.where(costs[:, 0] - costs.min(1) < cfg.min_improvement, stall + 1, 0) - it = num_iters if np.all(stall >= cfg.patience) else it + recent.append(wp.clone(scores)) + if cfg.patience <= it < num_iters: # only the last `patience` scores decide; other checks cannot stop + costs = np.stack([x.numpy().reshape(self.batch_size, -1) for x in recent[-cfg.patience :]]) + it = num_iters if np.all(costs[..., 0] - costs.min(-1) < cfg.min_improvement) else it if self._use_early_stopping and optimizer is not None and not capturing: # converged, or a term asked to stop: skip to this segment's select, as a per-stage solve would interval = optimizer.config.early_stopping_interval @@ -496,7 +531,7 @@ def solve( self, var: VarValues, iteration_callback: Optional[IterationCallback] = None ) -> Tuple[VarValues, wp.array]: """Run the schedule on widest `var`; return each instance's best candidate and cost.""" - if iteration_callback is not None and self.config.cuda_graph_mode == "full" and self._supports_cuda_graph: + if iteration_callback is not None and self.config.cuda_graph_mode == "full" and self._can_capture: raise ValueError("iteration_callback is incompatible with full-solve CUDA graph capture") if not self._initialized: self.setup(var) @@ -506,7 +541,7 @@ def solve( raise ValueError(f"the recorded solve takes {self._pop.batch_size} candidates, got {var.batch_size}") if var is not self._pop: self._pop.accept(self._restore_mask, var) - if wp.get_stream(self.device).is_capturing: + if self.device.is_capturing: self._run_solve_body() # CUDA cannot launch a graph while capturing; record its kernels instead else: wp.capture_launch(self._full_graph) diff --git a/src/robokit/opt/sampler.py b/src/robokit/opt/sampler.py index c5b04a8..029779f 100644 --- a/src/robokit/opt/sampler.py +++ b/src/robokit/opt/sampler.py @@ -48,6 +48,8 @@ def _gaussian_sample_kernel( tangent_dim: int, active_dof_mask: wp.array1d(dtype=wp.float32), std: wp.array2d(dtype=wp.float32), + num_wide: int, + wide_scale: float, noise: wp.array2d(dtype=wp.float32), ): batch_idx, dof_idx = wp.tid() # pyright: ignore[reportAssignmentType] @@ -55,13 +57,15 @@ def _gaussian_sample_kernel( noise[batch_idx, dof_idx] = 0.0 else: state = wp.rand_init(seed + epoch[0] * 7919, (salt * 1000003 + batch_idx) * tangent_dim + dof_idx) - noise[batch_idx, dof_idx] = std[batch_idx / num_draws, dof_idx] * wp.randn(state) + wide = salt == 0 and batch_idx % num_draws >= num_draws - num_wide # a solve's first round: the last draws + noise[batch_idx, dof_idx] = ( + std[batch_idx / num_draws, dof_idx] * wp.randn(state) * wp.where(wide, wide_scale, 1.0) + ) @lru_cache(maxsize=None) # one kernel per config; on warp 1.8, freeing one sampler's copy crashed the others def _build_weights_kernel(num_draws: int, weighting: Weighting): - """Per center: cost weights over its draws. Each thread of the block strides over the draws, so shared - memory stays one value per thread at any `num_draws`.""" + """Per center: cost weights over its draws. Each thread of the block strides over the draws, so shared memory stays one value per thread at any `num_draws`.""" draws = wp.constant(num_draws) softmax = weighting == "softmax" @@ -417,12 +421,14 @@ class GaussianSamplerConfig(SamplerConfig): sample_mode: Literal["mean", "best"] = "mean" """Move each center to its draws' weighted mean, or onto its cheapest draw.""" elite_ratio: float = 0.0 - """If positive, the softmax temperature is each center's cost spread over this best share of its draws (at least - two) instead of `temperature`, and `best_draws` keeps its cheapest draw.""" + """If positive, the softmax temperature is each center's cost spread over this best share of its draws (at least two) instead of `temperature`, and `best_draws` keeps its cheapest draw.""" mean_elites: bool = False """With `elite_ratio`, move each center to the weighted mean of that share alone.""" noise_decay: float = 1.0 """Each scored round scales `std` by this before the refit, never below `min_std`.""" + wide_ratio: float = 0.0 + """Share of a solve's first-round draws (its last ones) drawn at `wide_scale` times `std`, to explore.""" + wide_scale: float = 1.0 def build(self, var: VarValues, num_candidates: int, active_dof_mask: Optional[wp.array] = None) -> Sampler: width = var.get(self.var_key).tangent_dim @@ -454,8 +460,7 @@ class GaussianSampler: Capacity/reset controls: - `instances`: maximum center population; narrower solves use prefixes. - `std_reset` and `temperatures`: caller-adjustable per-instance settings; `reset` restores std from `std_reset`. - - `lower` and `upper`: optional `(instances, tangent_dim)` bounds on a vector variable's drawn values; each draw is - clamped to its center's and its noise follows. + - `lower` and `upper`: optional `(instances, tangent_dim)` bounds on a vector variable's drawn values; each draw is clamped to its center's and its noise follows. """ def __init__( @@ -475,6 +480,8 @@ def __init__( elite_ratio: float = 0.0, mean_elites: bool = False, noise_decay: float = 1.0, + wide_ratio: float = 0.0, + wide_scale: float = 1.0, active_dof_mask: Optional[wp.array] = None, device: wp_device_type = "cpu", var_key: Enum = VarKey.ROBOT, @@ -486,6 +493,7 @@ def __init__( self.learning_rate, self.epsilon = learning_rate, epsilon self.seed, self.sample_mode = seed, sample_mode self.elite_ratio, self.mean_elites, self.noise_decay = elite_ratio, mean_elites, noise_decay + self.num_wide, self.wide_scale = int(wide_ratio * (num_draws - 1)), wide_scale self._device = device self.active_dof_mask = ( active_dof_mask if active_dof_mask is not None else wp.ones(tangent_dim, dtype=wp.float32, device=device) @@ -574,6 +582,8 @@ def fill(self, out_tangent: wp.array, iteration: int = 0) -> None: self.tangent_dim, self.active_dof_mask, self.std, + self.num_wide, + self.wide_scale, out_tangent, ], device=self._device, diff --git a/src/robokit/opt/var_values.py b/src/robokit/opt/var_values.py index d750b07..5492d50 100644 --- a/src/robokit/opt/var_values.py +++ b/src/robokit/opt/var_values.py @@ -1,6 +1,7 @@ # pyright: reportOperatorIssue=false # pyright: reportGeneralTypeIssues=false # pyright: reportArgumentType=false +# pyright: reportCallIssue=false """Optimization variables: `Var` defines the protocol and `VarValues` combines leaves keyed by an Enum such as `VarKey`. Leaf types: @@ -29,8 +30,8 @@ def tangent_dim(self) -> int: ... def clone(self) -> Self: ... @abc.abstractmethod - def view(self, batch_size: int) -> Self: - """The first `batch_size` elements, sharing storage.""" + def view(self, batch_size: int, offset: int = 0) -> Self: + """Elements `offset` to `offset + batch_size`, sharing storage.""" ... @abc.abstractmethod @@ -45,6 +46,10 @@ def integrate( """Move by velocity; only shortened steps write `out_velocity`, which may alias the input velocity.""" ... + def difference(self, other: Self, out: Optional[ArrayLike] = None) -> ArrayLike: + """`(batch, tangent_dim)` velocities that `integrate` moves each element by to reach `other`'s.""" + raise NotImplementedError(f"{type(self).__name__} has no difference") + def invalidate(self): pass @@ -73,13 +78,17 @@ class VarKey(Enum): TIMING = 1 """Shared trajectory timestep of a motion-planning population.""" ACTION = 2 - """Control actions that MPPI samples.""" + """Control actions that MPPI samples, or that a dynamics model steps under (iLQR).""" CONTACTS = 3 """Discrete contact choices of grasp optimization.""" QPOS_OFFSET = 4 """Joint-encoder offsets that hand-eye calibration estimates.""" MOUNT_OFFSET = 5 """Mount-pose offset that hand-eye calibration estimates.""" + STATE = 6 + """States a dynamics model steps from (`ILQROptimizer`'s residual terms read them beside `ACTION`).""" + SEGMENT_STEP = 7 + """Log frame step (s) of each waypoint segment of a motion-planning candidate whose durations are optimized.""" class VarValues(Var): @@ -133,8 +142,8 @@ def clone(self) -> "VarValues": cloned_vars = {name: var.clone() for name, var in self._vars.items()} return type(self)(cloned_vars) - def view(self, batch_size: int) -> "VarValues": - return type(self)({name: var.view(batch_size) for name, var in self._vars.items()}) + def view(self, batch_size: int, offset: int = 0) -> "VarValues": + return type(self)({name: var.view(batch_size, offset) for name, var in self._vars.items()}) def _get_velocity(self, name: Enum, velocity: ArrayLike): offset = self._offsets[name] @@ -182,6 +191,14 @@ def integrate( ) return type(self)(integrated_vars) + def difference(self, other: "VarValues", out: Optional[ArrayLike] = None) -> ArrayLike: + if out is None: + out = wp.empty((self.batch_size, self.tangent_dim), dtype=wp.float32, device=self.device) + for name, var in self._vars.items(): + if var.tangent_dim: + var.difference(other.get(name), out=self._get_velocity(name, out)) + return out + def gather(self, indices: ArrayLike, out: Optional["VarValues"] = None) -> "VarValues": if out is None: return type(self)({name: var.gather(indices) for name, var in self._vars.items()}) @@ -207,6 +224,8 @@ def _integrate_vector_kernel( has_tangent_mask: wp.bool, weight_decay: float, write_applied: wp.bool, + unit: float, + max_step: float, out: wp.array2d(dtype=wp.float32), out_velocity: wp.array2d(dtype=wp.float32), ): @@ -215,11 +234,20 @@ def _integrate_vector_kernel( if has_tangent_mask: mask = tangent_mask[dim_idx] move = mask * (velocity[batch_idx, dim_idx] - weight_decay * x[batch_idx, dim_idx]) + move = wp.where(max_step > 0.0, wp.clamp(unit * move, -max_step, max_step), unit * move) if write_applied: - out_velocity[batch_idx, dim_idx] = move + out_velocity[batch_idx, dim_idx] = move / unit out[batch_idx, dim_idx] = x[batch_idx, dim_idx] + move +@wp.kernel +def _difference_vector_kernel( + x: wp.array2d(dtype=wp.float32), y: wp.array2d(dtype=wp.float32), out: wp.array2d(dtype=wp.float32) +): + batch_idx, dim_idx = wp.tid() # pyright: ignore[reportAssignmentType] + out[batch_idx, dim_idx] = y[batch_idx, dim_idx] - x[batch_idx, dim_idx] + + class VectorVar(Var): """A batched vector optimization variable on Euclidean space. @@ -233,12 +261,17 @@ class VectorVar(Var): >>> result = values.integrate(wp.array([[0.5, -1.0]], dtype=wp.float32)) >>> result.get(Key.X).x.numpy().tolist() [[1.5, 1.0]] + >>> capped = VectorVar(wp.zeros((1, 2), dtype=wp.float32), unit=10.0, max_step=1.0) # moves 10x, 1 at most + >>> capped.integrate(wp.array([[0.0625, 1.0]], dtype=wp.float32)).x.numpy().tolist() + [[0.625, 1.0]] """ - def __init__(self, x: wp.array): + def __init__(self, x: wp.array, unit: float = 1.0, max_step: float = 0.0): if x.ndim != 2 or x.dtype != wp.float32: raise ValueError("VectorVar requires a 2D float32 Warp array") self._x = x.contiguous() + # a move is `unit` times the velocity (tasks scale their Jacobians by it), at most `max_step` when > 0 + self.unit, self.max_step = unit, max_step @property def x(self) -> wp.array: @@ -263,10 +296,10 @@ def device(self) -> wp_device_type: return self._x.device def clone(self) -> "VectorVar": - return VectorVar(wp.clone(self._x)) + return VectorVar(wp.clone(self._x), self.unit, self.max_step) - def view(self, batch_size: int) -> "VectorVar": - return VectorVar(self._x[:batch_size]) + def view(self, batch_size: int, offset: int = 0) -> "VectorVar": + return VectorVar(self._x[offset : offset + batch_size], self.unit, self.max_step) def integrate( self, @@ -282,17 +315,27 @@ def integrate( raise ValueError(f"Expected tangent_mask shape {(self.tangent_dim,)}, but got {tangent_mask.shape}") if out is None: out = VectorVar(wp.empty_like(self._x, requires_grad=velocity.requires_grad or self._x.requires_grad)) + out.unit, out.max_step = self.unit, self.max_step wp.launch( _integrate_vector_kernel, dim=self._x.shape, - inputs=[self._x, velocity, tangent_mask, tangent_mask is not None, weight_decay, out_velocity is not None], + inputs=[self._x, velocity, tangent_mask, tangent_mask is not None, weight_decay, out_velocity is not None] + + [self.unit, self.max_step], outputs=[out._x, out_velocity], device=self.device, ) return out + def difference(self, other: "VectorVar", out: Optional[ArrayLike] = None) -> ArrayLike: + if out is None: + out = wp.empty_like(self._x) + wp.launch( + _difference_vector_kernel, dim=self._x.shape, inputs=[self._x, other._x], outputs=[out], device=self.device + ) + return out + def gather(self, indices: ArrayLike, out: Optional["VectorVar"] = None) -> "VectorVar": - return VectorVar(gather(self._x, indices, out._x if out is not None else None)) + return VectorVar(gather(self._x, indices, out._x if out is not None else None), self.unit, self.max_step) def accept(self, accept_mask: ArrayLike, proposed: "VectorVar") -> "VectorVar": masked_copy(accept_mask, proposed._x, self._x) diff --git a/src/robokit/robo/robot_spec.py b/src/robokit/robo/robot_spec.py index 545e95f..5cd61c3 100644 --- a/src/robokit/robo/robot_spec.py +++ b/src/robokit/robo/robot_spec.py @@ -628,10 +628,7 @@ def parse_mjcf( ee_link_names: Optional[Union[Sequence[str], str]] = None, keep_world_link: bool = False, ) -> "RobotSpec": - """Parse an MJCF robot: hinge/slide joints, equality mimics; the world body stays if kept or a root has joints. - - A hinge with an anchor (`jnt_pos`) turns at a synthetic `_anchor` link, then a fixed joint shifts back. - """ + """Parse an MJCF robot: hinge/slide joints, equality mimics; the world body stays if kept or a root has joints. A hinge with an anchor (`jnt_pos`) turns at a synthetic `_anchor` link, then a fixed joint shifts back.""" import mujoco # type: ignore # no wheels/stubs for py<3.10; lazily imported only when parsing MJCF def _mjcf_geom_to_trimesh(model: Any, geom_idx: int) -> Optional[trimesh.Trimesh]: diff --git a/src/robokit/robo/robot_state.py b/src/robokit/robo/robot_state.py index f4ae40c..0fd40e7 100644 --- a/src/robokit/robo/robot_state.py +++ b/src/robokit/robo/robot_state.py @@ -353,17 +353,18 @@ def clone(self) -> "RobotState": state.spec_tensors = self.spec_tensors return state - def view(self, batch_size: int) -> "RobotState": - """The first `batch_size` elements of every buffer, sharing storage.""" + def view(self, batch_size: int, offset: int = 0) -> "RobotState": + """Elements `offset` to `offset + batch_size` of every buffer, sharing storage.""" state = object.__new__(type(self)) state.spec = self.spec - state.q = self.q[:batch_size] - state.T_world_base = self.T_world_base[:batch_size] + state.q = self.q[offset : offset + batch_size] + state.T_world_base = self.T_world_base[offset : offset + batch_size] state._view_source = self for name in _CLONE_BUFFERS: if name in self.__dict__: buf = self.__dict__[name] # com_world is already flat; everything else leads with the batch - setattr(state, name, buf[: batch_size * (buf.shape[0] // self.batch_size)]) + k = buf.shape[0] // self.batch_size + setattr(state, name, buf[offset * k : (offset + batch_size) * k]) state.has_floating_base = self.has_floating_base state.is_fk_computed = self.is_fk_computed state.is_motion_subspace_computed = self.is_motion_subspace_computed diff --git a/src/robokit/sim/__init__.py b/src/robokit/sim/__init__.py new file mode 100644 index 0000000..0541f6f --- /dev/null +++ b/src/robokit/sim/__init__.py @@ -0,0 +1,51 @@ +"""Batched simulation: `nworld` worlds of one model or of several scenes stepped together, fields as Warp arrays.""" + +from typing import TYPE_CHECKING, Any, Optional, Protocol + +import warp as wp + +from robokit.sim.dynamics import QposVar, SimDynamics, SimKey + + +if TYPE_CHECKING: + from robokit.sim.mjwarp import CoarseConfig, MjWarpSim + + +def __getattr__(name: str): + if name in ("CoarseConfig", "MjWarpSim"): # imported on first use: MuJoCo Warp needs Python >= 3.10 + from robokit.sim import mjwarp + + return getattr(mjwarp, name) + raise AttributeError(f"module 'robokit.sim' has no attribute {name!r}") + + +class Sim(Protocol): + """What `MjWarpSim` and `newton.NewtonSim` offer: device work only, also in a capture on Warp's current stream.""" + + mjm: Any + """The `mujoco.MjModel` whose layout `data` follows: bodies, joints, sensors (for several scenes, their merge).""" + nworld: int + substeps: int + stream: Optional[wp.Stream] + """The CUDA stream it launches on (None on the CPU); other GPU work on it stays ordered without host syncs.""" + # at least time, qpos, qvel, act, qacc_warmstart, ctrl, sensordata, xpos, xmat, nacon, contact.worldid/geom/dist/pos + data: Any + """Warp arrays named and laid out as in `mujoco.MjData`, with a leading world axis `(nworld, ...)`.""" + model: Any # a per-world array assigned to a field stays + """`mujoco.MjModel`'s fields (`NewtonSim`: none), a row per world copied from the shared row on first access.""" + + def step(self): + """Advance `substeps` physics steps; `data.substep_sensordata[k]`: `sensordata` after substep `k`.""" + + def forward(self): + """Recompute the derived quantities (`xpos`, `sensordata`, ...) from the current state.""" + + def reset(self, mask: wp.array): + """Return the worlds where `mask` is set to the initial state.""" + + def resized(self, nworld: int) -> "Sim": + """A new simulator of the same scenes and settings with `nworld` worlds.""" + ... + + +__all__ = ["CoarseConfig", "MjWarpSim", "QposVar", "Sim", "SimDynamics", "SimKey"] diff --git a/src/robokit/sim/_mjwarp_sort.py b/src/robokit/sim/_mjwarp_sort.py new file mode 100644 index 0000000..032906a --- /dev/null +++ b/src/robokit/sim/_mjwarp_sort.py @@ -0,0 +1,625 @@ +# pyright: reportArgumentType=false, reportAssignmentType=false, reportCallIssue=false +# pyright: reportGeneralTypeIssues=false, reportIndexIssue=false, reportOperatorIssue=false +# Copyright 2026 The Newton Developers +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== + +"""MuJoCo Warp's contact and constraint sorts, which mujoco-warp 3.17.0 leaves as empty stubs.""" + +# Vendored from google-deepmind/mujoco_warp#1422 (`mujoco_warp/_src/sort.py` at 831a476); delete once a release has it. + +import importlib.metadata +import inspect +from typing import Any, Callable, Optional + +import warp as wp +from mujoco_warp._src import types # pyright: ignore[reportMissingImports] +from mujoco_warp._src.warp_util import cache_kernel # pyright: ignore[reportMissingImports] + + +wp.set_module_options({"default_grid_stride": False}) + + +@wp.struct +class _ConstraintKeys: + primary: wp.array2d[wp.vec4i] + J: wp.array3d[wp.uint32] + J_rownnz: wp.array2d[int] + J_rowadr: wp.array2d[int] + J_colind: wp.array3d[int] + pos: wp.array2d[wp.uint32] + margin: wp.array2d[wp.uint32] + D: wp.array2d[wp.uint32] + vel: wp.array2d[wp.uint32] + aref: wp.array2d[wp.uint32] + frictionloss: wp.array2d[wp.uint32] + contact: wp.array3d[wp.uint32] # contact_keys: contact rows compare their contacts, as a contact sort would + nv: int + + +@wp.func +def _float_key(bits: wp.uint32) -> wp.uint32: + """Total ordering of float bits, including signed zero and NaNs.""" + return wp.where((bits & wp.uint32(0x80000000)) != wp.uint32(0), ~bits, bits ^ wp.uint32(0x80000000)) + + +@wp.func +def _contact_less(keys: wp.array3d[wp.uint32], worldid: int, a: int, b: int) -> bool: + for j in range(keys.shape[2]): + ka = keys[worldid, a, j] + kb = keys[worldid, b, j] + if ka != kb: + return ka < kb + return False + + +@wp.func +def _constraint_less(keys: _ConstraintKeys, worldid: int, a: int, b: int) -> bool: + ka = keys.primary[worldid, a] + kb = keys.primary[worldid, b] + for i in range(4): # (type, subtype, id, component): connect/weld and contact components differ here + if ka[i] != kb[i]: + if i != 2 or ka[0] < int(types.ConstraintType.CONTACT_FRICTIONLESS): + return ka[i] < kb[i] + for j in range(keys.contact.shape[2]): # two contacts: by their keys, as `_contact_less` + ua = keys.contact[0, ka[2], j] + ub = keys.contact[0, kb[2], j] + if ua != ub: + return ua < ub + + # Equal type/id is not sufficient for flex edges: compare Jacobian rows, not their atomic allocation addresses. + if keys.J_rownnz.shape[1] > 0: + na = keys.J_rownnz[worldid, a] + nb = keys.J_rownnz[worldid, b] + aa = keys.J_rowadr[worldid, a] + ab = keys.J_rowadr[worldid, b] + for i in range(wp.min(na, nb)): + ca = keys.J_colind[worldid, 0, aa + i] + cb = keys.J_colind[worldid, 0, ab + i] + if ca != cb: + return ca < cb + va = _float_key(keys.J[worldid, 0, aa + i]) + vb = _float_key(keys.J[worldid, 0, ab + i]) + if va != vb: + return va < vb + if na != nb: + return na < nb + else: + for i in range(keys.nv): + va = _float_key(keys.J[worldid, a, i]) + vb = _float_key(keys.J[worldid, b, i]) + if va != vb: + return va < vb + + va = _float_key(keys.pos[worldid, a]) + vb = _float_key(keys.pos[worldid, b]) + if va != vb: + return va < vb + va = _float_key(keys.margin[worldid, a]) + vb = _float_key(keys.margin[worldid, b]) + if va != vb: + return va < vb + va = _float_key(keys.D[worldid, a]) + vb = _float_key(keys.D[worldid, b]) + if va != vb: + return va < vb + va = _float_key(keys.vel[worldid, a]) + vb = _float_key(keys.vel[worldid, b]) + if va != vb: + return va < vb + va = _float_key(keys.aref[worldid, a]) + vb = _float_key(keys.aref[worldid, b]) + if va != vb: + return va < vb + va = _float_key(keys.frictionloss[worldid, a]) + vb = _float_key(keys.frictionloss[worldid, b]) + if va != vb: + return va < vb + return False + + +@wp.func +def _block_less(keys: wp.array2d[int], worldid: int, a: int, b: int) -> bool: + return keys[worldid, a] < keys[worldid, b] + + +@wp.kernel +def _identity(order_out: wp.array2d[int]): + worldid, i = wp.tid() + order_out[worldid, i] = i + + +@cache_kernel +def _merge(compare: Callable): + @wp.kernel(module="unique", enable_backward=False, grid_stride=False) + def kernel( + # In: + count_in: wp.array[int], + keys_in: Any, + order_in: wp.array2d[int], + width: int, + # Out: + order_out: wp.array2d[int], + ): + worldid, i = wp.tid() + count = wp.min(count_in[worldid], order_in.shape[1]) + if i >= count: + order_out[worldid, i] = i + return + start = (i // (2 * width)) * (2 * width) + middle = wp.min(start + width, count) + end = wp.min(start + 2 * width, count) + left = i < middle + lo = wp.where(left, middle, start) + hi = wp.where(left, end, middle) + other_start = lo + source = order_in[worldid, i] + while lo < hi: + mid = (lo + hi) // 2 + other = order_in[worldid, mid] + before = compare(keys_in, worldid, other, source) + # Stable merge of *identical* keys, not a key based on emission order. + if not left: + before = not compare(keys_in, worldid, source, other) + if before: + lo = mid + 1 + else: + hi = mid + dest = start + (i - wp.where(left, start, middle)) + lo - other_start + order_out[worldid, dest] = source + + return kernel + + +@wp.kernel +def _gather( + # In: + count_in: wp.array[int], + order_in: wp.array2d[int], + value_in: wp.array3d[Any], + # Out: + value_out: wp.array3d[Any], +): + worldid, row = wp.tid() + if row < count_in[worldid]: + source = row # no order: copy + if order_in.shape[1] > 0: + source = order_in[worldid, row] + for col in range(value_out.shape[2]): + value_out[worldid, row, col] = value_in[worldid, source, col] + + +@cache_kernel +def _contact_key_field(is_float: bool, feature: bool): + @wp.kernel(module="unique", enable_backward=False, grid_stride=False) + def kernel( + # Data in: + nacon_in: wp.array[int], + # In: + geom_in: wp.array[wp.vec2i], + value_in: wp.array3d[wp.uint32], + offset: int, + # Out: + keys_out: wp.array3d[wp.uint32], + ): + i, j = wp.tid() + if i >= wp.min(nacon_in[0], keys_out.shape[1]): + return + bits = value_in[0, i, j] + if wp.static(feature): + # Rigid writers do not initialize flex feature fields; ignore those slots. + if geom_in[i][j] >= 0: + bits = wp.uint32(0xFFFFFFFF) + if wp.static(is_float): + key = _float_key(bits) + else: + key = bits ^ wp.uint32(0x80000000) + keys_out[0, i, offset + j] = key + + return kernel + + +@wp.kernel +def _constraint_counts( + # Data in: + nefc_in: wp.array[int], + njmax_in: int, + njmax_nnz_in: int, + # In: + nnz_in: wp.array[int], + # Out: + count_out: wp.array[int], +): + worldid = wp.tid() + count = nefc_in[worldid] + # Overflow may leave partial groups/rows: leave them and the counters alone; the overflow checks report it. + if count > njmax_in: # canonical ordering requires sufficient buffers + count = 0 + if nnz_in.shape[0] > 0: + if nnz_in[worldid] > njmax_nnz_in: + count = 0 + count_out[worldid] = count + + +@wp.kernel +def _constraint_primary( + # Model: + eq_type: wp.array[int], + # In: + count_in: wp.array[int], + type_in: wp.array2d[int], + id_in: wp.array2d[int], + # Out: + keys_out: wp.array2d[wp.vec4i], +): + worldid, row = wp.tid() + if row < count_in[worldid]: + row_type = type_in[worldid, row] + id = id_in[worldid, row] + subtype = int(0) + component = int(0) + if row_type == int(types.ConstraintType.EQUALITY): + subtype = eq_type[id] + if subtype == int(types.EqType.CONNECT) or subtype == int(types.EqType.WELD): + # Assembly emits each group contiguously, XYZ force then XYZ torque. + nrow = 3 if subtype == int(types.EqType.CONNECT) else 6 + while component + 1 < nrow and row > component: + previous = row - component - 1 + if type_in[worldid, previous] != row_type or id_in[worldid, previous] != id: + break + component += 1 # the offset within that group, not its nondeterministic allocation address + # Force reconstruction requires all connects before welds, regardless of XML equality IDs. + keys_out[worldid, row] = wp.vec4i(row_type, subtype, id, component) + + +@wp.kernel +def _contact_constraint_primary( + # Data in: + nacon_in: wp.array[int], + # In: + count_in: wp.array[int], + worldid_in: wp.array[int], + efc_address_in: wp.array2d[int], + type_in: wp.array2d[int], + id_in: wp.array2d[int], + dim_in: wp.array[int], + is_pyramidal: bool, + # Out: + keys_out: wp.array2d[wp.vec4i], +): + conid, component = wp.tid() + if conid >= wp.min(nacon_in[0], efc_address_in.shape[0]): + return + dim = dim_in[conid] + nrow = wp.max(1, 2 * (dim - 1)) if is_pyramidal else dim + if component >= nrow: + return + worldid = worldid_in[conid] + row = efc_address_in[conid, component] + if row >= 0 and row < count_in[worldid]: + if type_in[worldid, row] >= int(types.ConstraintType.CONTACT_FRICTIONLESS) and id_in[worldid, row] == conid: + keys_out[worldid, row] = wp.vec4i(type_in[worldid, row], 0, conid, component) + + +@wp.kernel +def _inverse(order_in: wp.array2d[int], inverse_out: wp.array2d[int]): + worldid, row = wp.tid() + inverse_out[worldid, order_in[worldid, row]] = row + + +@wp.kernel +def _remap_contacts( + # Data in: + nacon_in: wp.array[int], + # In: + count_in: wp.array[int], + worldid_in: wp.array[int], + inverse_in: wp.array2d[int], + address_in: wp.array2d[int], + # Out: + address_out: wp.array2d[int], +): + conid, component = wp.tid() + if conid < wp.min(nacon_in[0], address_in.shape[0]): + row = address_in[conid, component] + worldid = worldid_in[conid] + if row >= 0 and row < count_in[worldid]: + address_out[conid, component] = inverse_in[worldid, row] + + +@wp.kernel +def _sparse_offsets( + # In: + count_in: wp.array[int], + order_in: wp.array2d[int], + rownnz_in: wp.array2d[int], + # Out: + offsets_out: wp.array2d[int], +): + worldid = wp.tid() + offset = int(0) + # Scan assembled rows within each world, not the (possibly interleaved) contact buffer. + for row in range(count_in[worldid]): + offsets_out[worldid, row] = offset + offset += rownnz_in[worldid, order_in[worldid, row]] + + +@wp.kernel +def _pack_sparse( + # In: + count_in: wp.array[int], + order_in: wp.array2d[int], + offsets_in: wp.array2d[int], + rownnz_in: wp.array2d[int], + rowadr_in: wp.array2d[int], + colind_in: wp.array3d[int], + J_in: wp.array3d[float], + # Out: + rownnz_out: wp.array2d[int], + rowadr_out: wp.array2d[int], + colind_out: wp.array3d[int], + J_out: wp.array3d[float], +): + worldid, row = wp.tid() + if row >= count_in[worldid]: + return + old = order_in[worldid, row] + nnz = rownnz_in[worldid, old] + start = rowadr_in[worldid, old] + adr = offsets_in[worldid, row] + rownnz_out[worldid, row] = nnz + rowadr_out[worldid, row] = adr + for i in range(nnz): + colind_out[worldid, 0, adr + i] = colind_in[worldid, 0, start + i] + J_out[worldid, 0, adr + i] = J_in[worldid, 0, start + i] + + +@wp.kernel +def _remap_blocks( + # In: + count_in: wp.array[int], + nblock_in: wp.array[int], + inverse_in: wp.array2d[int], + adr_in: wp.array2d[int], + nrow_in: wp.array2d[int], + # Out: + adr_out: wp.array2d[int], + nblock_out: wp.array[int], +): + worldid, block = wp.tid() + if block == 0: + nblock_out[worldid] = wp.where(count_in[worldid] > 0, nblock_in[worldid], 0) + if count_in[worldid] == 0 or block >= nblock_in[worldid]: + return + start = adr_in[worldid, block] + first = inverse_in[worldid, start] + for i in range(1, nrow_in[worldid, block]): + first = wp.min(first, inverse_in[worldid, start + i]) + adr_out[worldid, block] = first + + +def permutation(count: wp.array, capacity: int, keys: wp.array | _ConstraintKeys.cls, compare: Callable) -> wp.array: + """Stable parallel mergesort, bounded by capacity and compatible with CUDA capture.""" + order = wp.empty((count.size, capacity), dtype=int) + scratch = wp.empty_like(order) + wp.launch(_identity, dim=order.shape, outputs=[order]) + width = 1 + while width < capacity: + wp.launch(_merge(compare), dim=order.shape, inputs=[count, keys, order, width], outputs=[scratch]) + order, scratch = scratch, order + width *= 2 + return order + + +def row_view(value: wp.array, nworld: int, capacity: int, dtype=None) -> wp.array: + """View a contiguous array as scalar rows without moving its storage.""" + scalar = ( + value.dtype._wp_scalar_type_ + if wp.types.type_is_vector(value.dtype) or wp.types.type_is_matrix(value.dtype) + else value.dtype + ) + view = value.view(dtype or scalar) + width = view.size // max(nworld * capacity, 1) + # Keep the backing allocation alive when a captured gather retains the view. + return view.reshape((nworld, capacity, width)) + + +def gather(count: wp.array, order: wp.array, value: wp.array, capacity: int): + """Permute active rows in place (copying only those, for less GPU time), keeping array references and padding.""" + dest_view = row_view(value, count.size, capacity) + source_view, copy = wp.empty_like(dest_view), wp.empty((0, 0), dtype=int) # copy: the active rows, not padding + wp.launch(_gather, dim=dest_view.shape[:2], inputs=[count, copy, dest_view], outputs=[source_view]) + wp.launch(_gather, dim=dest_view.shape[:2], inputs=[count, order, source_view], outputs=[dest_view]) + + +def contact_keys(d: types.Data) -> wp.array: + """Keys that order contacts by world, features, geometry, then material; never by an allocated contact index. + + Returns: + `(1, naconmax, fields)` uint32 keys; equal keys describe interchangeable contacts. + """ + fields = [] + offset = 0 + for value, is_float, feature in ( + (d.contact.worldid, False, False), + (d.contact.geom, False, False), + (d.contact.flex, False, True), + (d.contact.elem, False, True), + (d.contact.vert, False, True), + (d.contact.pos, True, False), + (d.contact.frame, True, False), + (d.contact.dist, True, False), + (d.contact.dim, False, False), + (d.contact.type, False, False), + (d.contact.includemargin, True, False), + (d.contact.friction, True, False), + (d.contact.solref, True, False), + (d.contact.solreffriction, True, False), + (d.contact.solimp, True, False), + (d.contact.adhesion, True, False), + (d.contact.geomcollisionid, False, False), + ): + if not value.size: + continue + view = row_view(value, 1, d.naconmax, wp.uint32) + fields.append((view, offset, is_float, feature)) + offset += view.shape[2] + keys = wp.empty((1, d.naconmax, offset), dtype=wp.uint32) + for view, offset, is_float, feature in fields: + wp.launch( + _contact_key_field(is_float, feature), + dim=(d.naconmax, view.shape[2]), + inputs=[d.nacon, d.contact.geom, view, offset], + outputs=[keys], + ) + return keys + + +def constraints(m: types.Model, d: types.Data, nnz: wp.array | None = None): + """Sort assembled rows and repair their contact, sparse-J, and JTDAJ references.""" + count = wp.empty_like(d.nefc) + wp.launch( + _constraint_counts, + dim=d.nworld, + inputs=[d.nefc, d.njmax, d.njmax_nnz, nnz if m.is_sparse and nnz is not None else wp.empty(0, dtype=int)], + outputs=[count], + ) + keys = _ConstraintKeys() + keys.primary = wp.empty((d.nworld, d.njmax), dtype=wp.vec4i) + keys.J = d.efc.J.view(wp.uint32) + keys.J_rownnz = d.efc.J_rownnz + keys.J_rowadr = d.efc.J_rowadr + keys.J_colind = d.efc.J_colind + keys.pos = d.efc.pos.view(wp.uint32) + keys.margin = d.efc.margin.view(wp.uint32) + keys.D = d.efc.D.view(wp.uint32) + keys.vel = d.efc.vel.view(wp.uint32) + keys.aref = d.efc.aref.view(wp.uint32) + keys.frictionloss = d.efc.frictionloss.view(wp.uint32) + keys.contact = contact_keys(d) + keys.nv = m.nv + wp.launch( + _constraint_primary, + dim=keys.primary.shape, + inputs=[m.eq_type, count, d.efc.type, d.efc.id], + outputs=[keys.primary], + ) + # Contact rows compare their contacts' keys, not #1422's contact ranks: its order with or without CONTACTS, faster. + wp.launch( + _contact_constraint_primary, + dim=d.contact.efc_address.shape, + inputs=[ + d.nacon, + count, + d.contact.worldid, + d.contact.efc_address, + d.efc.type, + d.efc.id, + d.contact.dim, + m.opt.cone == types.ConeType.PYRAMIDAL, + ], + outputs=[keys.primary], + ) + order = permutation(count, d.njmax, keys, _constraint_less) + inverse = wp.empty_like(order) + wp.launch(_inverse, dim=order.shape, inputs=[order], outputs=[inverse]) + wp.launch( + _remap_contacts, + dim=d.contact.efc_address.shape, + inputs=[d.nacon, count, d.contact.worldid, inverse, d.contact.efc_address], + outputs=[d.contact.efc_address], + ) + if m.is_sparse: + offsets = wp.empty_like(order) + wp.launch(_sparse_offsets, dim=d.nworld, inputs=[count, order, d.efc.J_rownnz], outputs=[offsets]) + wp.launch( + _pack_sparse, + dim=order.shape, + inputs=[ + count, + order, + offsets, + wp.clone(d.efc.J_rownnz), + wp.clone(d.efc.J_rowadr), + wp.clone(d.efc.J_colind), + wp.clone(d.efc.J), + ], + outputs=[d.efc.J_rownnz, d.efc.J_rowadr, d.efc.J_colind, d.efc.J], + ) + if m.opt.solver == types.SolverType.NEWTON: + nblock = wp.zeros_like(d.efc.jtdaj_nblock) + wp.launch( + _remap_blocks, + dim=order.shape, + inputs=[count, d.efc.jtdaj_nblock, inverse, d.efc.jtdaj_adr, d.efc.jtdaj_nrow], + outputs=[d.efc.jtdaj_adr, nblock], + ) + blocks = permutation(nblock, d.njmax, d.efc.jtdaj_adr, _block_less) + gather(nblock, blocks, d.efc.jtdaj_adr, d.njmax) + gather(nblock, blocks, d.efc.jtdaj_nrow, d.njmax) + else: + gather(count, order, d.efc.J, d.efc.J.shape[1]) + for value in ( + d.efc.type, + d.efc.id, + d.efc.pos, + d.efc.margin, + d.efc.D, + d.efc.vel, + d.efc.aref, + d.efc.frictionloss, + d.efc.force, + d.efc.state, + d.efc.island, + d.efc.Jqvel, + ): + if value.size: + gather(count, order, value, value.shape[1]) + + +def patch() -> None: + """Fill 3.17.0's stub sorts, so `DeterminismType.CONSTRAINT` gives each world one canonical constraint row order. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> patch() + >>> from mujoco_warp._src import constraint + >>> constraint._sort_constraints is _sort_constraints or importlib.metadata.version("mujoco-warp") != "3.17.0" + True + """ + from mujoco_warp._src import collision_driver, constraint # pyright: ignore[reportMissingImports] + + stubs = collision_driver._sort_contacts, constraint._sort_constraints + if importlib.metadata.version("mujoco-warp") != "3.17.0" or not all("TODO" in inspect.getsource(f) for f in stubs): + return # a no-op on any other version + collision_driver._sort_contacts, constraint._sort_constraints = _sort_contacts, _sort_constraints + + +def _sort_contacts(m: types.Model, d: types.Data): + """Sort contacts canonically under `DeterminismType.CONTACTS` (#1422's `collision_driver._sort_contacts`).""" + d.contact.efc_address.fill_(-1) # #1422 resets reused slots in make_constraint; it runs right after this + order = permutation(d.nacon, d.naconmax, contact_keys(d), _contact_less) # on overflow, the retained contacts only + for value in ( + d.contact.dist, d.contact.pos, d.contact.frame, d.contact.includemargin, d.contact.friction, d.contact.solref, + d.contact.solreffriction, d.contact.solimp, d.contact.dim, d.contact.geom, d.contact.flex, d.contact.elem, + d.contact.vert, d.contact.efc_address, d.contact.worldid, d.contact.type, d.contact.geomcollisionid, + d.contact.adhesion, + ): # fmt: skip + if value.size: + gather(d.nacon, order, value, d.naconmax) + + +def _sort_constraints(m: types.Model, d: types.Data, nnz: Optional[wp.array] = None): + """Sort constraint rows canonically (#1422's `constraint._sort_constraints`).""" + constraints(m, d, nnz) diff --git a/src/robokit/sim/dynamics.py b/src/robokit/sim/dynamics.py new file mode 100644 index 0000000..40e7c04 --- /dev/null +++ b/src/robokit/sim/dynamics.py @@ -0,0 +1,264 @@ +# pyright: reportArgumentType=false +# pyright: reportCallIssue=false +# pyright: reportIndexIssue=false +# pyright: reportOperatorIssue=false +"""`SimDynamics`: one step of a `robokit.sim.Sim` as `Dynamics`, on MuJoCo states made of `QposVar` joint positions.""" + +import copy +from enum import Enum +from typing import Any, Dict, Optional, Tuple, cast + +import mujoco # pyright: ignore[reportMissingImports] +import numpy as np +import warp as wp + +from robokit.opt.ilqr_optimizer import Dynamics +from robokit.opt.var_values import Var, VarValues, VectorVar +from robokit.terms.simulation.sim_context import sim_context +from robokit.terms.task import Context +from robokit.types import ArrayLike +from robokit.utils.warp_utils import gather, masked_copy, wp_device_type +from robokit.xform.warp.rotation_conversions import ( + axis_angle_to_quaternion_func, + quaternion_invert_func, + quaternion_multiply_func, + quaternion_to_axis_angle_func, +) + + +f64 = wp.float64 + + +class SimKey(Enum): + """`SimDynamics` states' parts.""" + + QPOS = 0 + QVEL = 1 + ACT = 2 + + +# --- kernels ---------------------------------------------------------------- +@wp.kernel +def _integrate_qpos_kernel( + q: wp.array2d(dtype=float), + v: wp.array2d(dtype=float), + lin_q: wp.array(dtype=int), # linear coordinates' qpos indices + lin_v: wp.array(dtype=int), # ... and dof indices + quat_q: wp.array(dtype=int), # quaternions' qpos addresses + quat_v: wp.array(dtype=int), # ... and their rotations' dof addresses + mask: wp.array(dtype=float), + has_mask: bool, + out: wp.array2d(dtype=float), +): + """Row b moved by `v`: linear coordinates add, quaternions turn by the rotation vector in their own frame.""" + b = wp.tid() + for i in range(lin_q.shape[0]): + m = float(1.0) + if has_mask: + m = mask[lin_v[i]] + out[b, lin_q[i]] = q[b, lin_q[i]] + m * v[b, lin_v[i]] + for i in range(quat_q.shape[0]): + a, d = quat_q[i], quat_v[i] + w = wp.vec3(v[b, d], v[b, d + 1], v[b, d + 2]) + if has_mask: + w = wp.cw_mul(w, wp.vec3(mask[d], mask[d + 1], mask[d + 2])) + quat = wp.vec4(q[b, a], q[b, a + 1], q[b, a + 2], q[b, a + 3]) + p = wp.normalize(quaternion_multiply_func(quat, axis_angle_to_quaternion_func(w))) + for j in range(4): + out[b, a + j] = p[j] + + +@wp.kernel +def _difference_qpos_kernel( + q: wp.array2d(dtype=float), + p: wp.array2d(dtype=float), + lin_q: wp.array(dtype=int), + lin_v: wp.array(dtype=int), + quat_q: wp.array(dtype=int), + quat_v: wp.array(dtype=int), + out: wp.array2d(dtype=float), +): + """Row b's velocity from `q` to `p`; quaternions' rotation vector of conj(q) p, the shorter way, in float64.""" + b = wp.tid() + for i in range(lin_q.shape[0]): + out[b, lin_v[i]] = p[b, lin_q[i]] - q[b, lin_q[i]] + for i in range(quat_q.shape[0]): + a, d = quat_q[i], quat_v[i] + qa = wp.vec4d(f64(q[b, a]), f64(q[b, a + 1]), f64(q[b, a + 2]), f64(q[b, a + 3])) + pa = wp.vec4d(f64(p[b, a]), f64(p[b, a + 1]), f64(p[b, a + 2]), f64(p[b, a + 3])) + turn = quaternion_to_axis_angle_func(quaternion_multiply_func(quaternion_invert_func(qa), pa)) + for j in range(3): + out[b, d + j] = float(turn[j]) + + +# --- states ----------------------------------------------------------------- +class QposVar(Var): + """MuJoCo joint positions `(B, nq)`, float32, with `qvel`'s tangent space (nv). + + Example: + >>> import mujoco + >>> model = mujoco.MjModel.from_xml_string("" + ... "") + >>> q = QposVar(wp.array([[0, 0, 0, 1, 0, 0, 0]], dtype=float), model) + >>> v = wp.array([[1, 0, 0, 0, 0, np.pi / 2]], dtype=float) # 1 m along x, a quarter turn about z + >>> p = q.integrate(v) + >>> p.qpos.numpy().astype(float).round(4).tolist() + [[1.0, 0.0, 0.0, 0.7071, 0.0, 0.0, 0.7071]] + >>> q.difference(p).numpy().astype(float).round(4).tolist() + [[1.0, 0.0, 0.0, 0.0, 0.0, 1.5708]] + """ + + def __init__(self, qpos: wp.array, model: mujoco.MjModel): + lin, quat = [], [] # (qpos index, dof index) of each linear coordinate, each quaternion's first + for j in range(model.njnt): + a, d, kind = model.jnt_qposadr[j], model.jnt_dofadr[j], model.jnt_type[j] + if kind == mujoco.mjtJoint.mjJNT_FREE: + lin, quat = lin + [(a + i, d + i) for i in range(3)], quat + [(a + 3, d + 3)] + elif kind == mujoco.mjtJoint.mjJNT_BALL: + quat.append((a, d)) + else: + lin.append((a, d)) + self.qpos, self.nv = qpos, model.nv + self._joints = [wp.array(np.array(p, np.int32).reshape(-1, 2)[:, i].copy(), dtype=int, device=qpos.device) + for p in (lin, quat) for i in range(2)] # fmt: skip + + def _like(self, qpos: wp.array) -> "QposVar": + var = copy.copy(self) + var.qpos = qpos + return var + + @property + def tangent_dim(self) -> int: + return self.nv + + @property + def batch_size(self) -> int: + return int(self.qpos.shape[0]) + + @property + def device(self) -> wp_device_type: + return self.qpos.device + + def clone(self) -> "QposVar": + return self._like(wp.clone(self.qpos)) + + def view(self, batch_size: int, offset: int = 0) -> "QposVar": + return self._like(self.qpos[offset : offset + batch_size]) + + def integrate( + self, + velocity: ArrayLike, + out: Optional["QposVar"] = None, + tangent_mask: Optional[wp.array] = None, + weight_decay: float = 0.0, + out_velocity: Optional[ArrayLike] = None, + ) -> "QposVar": + """As `mj_integratePos`: free and ball joints' quaternions turn by `velocity` in their own frame, others add.""" + if weight_decay != 0.0: + raise ValueError("QposVar does not support weight_decay") + out = out if out is not None else self._like(wp.empty_like(self.qpos)) + ins = [self.qpos, velocity, *self._joints, tangent_mask, tangent_mask is not None] + wp.launch(_integrate_qpos_kernel, self.batch_size, inputs=ins, outputs=[out.qpos], device=self.device) + return out + + def difference(self, other: "QposVar", out: Optional[ArrayLike] = None) -> ArrayLike: + """The velocity from these positions to `other`'s, as `mj_differentiatePos`.""" + out = out if out is not None else wp.empty((self.batch_size, self.nv), dtype=float, device=self.device) + ins = [self.qpos, other.qpos, *self._joints] + wp.launch(_difference_qpos_kernel, self.batch_size, inputs=ins, outputs=[out], device=self.device) + return out + + def gather(self, indices: ArrayLike, out: Optional["QposVar"] = None) -> "QposVar": + return self._like(gather(self.qpos, indices, out.qpos if out is not None else None)) + + def accept(self, accept_mask: ArrayLike, proposed: "QposVar") -> "QposVar": + masked_copy(accept_mask, proposed.qpos, self.qpos) + return self + + +# --- dynamics --------------------------------------------------------------- +class SimDynamics(Dynamics): + """`Dynamics` for `robokit.opt.ilqr_optimizer.ILQROptimizer`: one physics step of `(qpos, qvel, act)` on a `Sim`. + + Args: + sim: A `Sim`; `resized` gives one per batch size stepped and finite-difference setting, as `SimMPC` does. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco, numpy as np + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> model = mujoco.MjModel.from_xml_string(xml + '') + >>> dynamics = SimDynamics(MjWarpSim(model, 1)) + >>> x = dynamics.build_state(np.zeros((2, 1)), np.array([[0.0], [1.0]])) + >>> x_next = x.clone() + >>> dynamics.step(x, wp.zeros((2, 1), dtype=float), x_next) + >>> x_next.get(SimKey.QPOS).qpos.numpy()[:, 0].astype(float).round(4).tolist() # 1 m/s for one 2 ms step + [0.0, 0.002] + """ + + def __init__(self, sim: Any, steps_per_knot: int = 1): + from robokit.sim import _mjwarp_sort # here, so that the module imports without MuJoCo Warp + + model = sim.mjm + limited = model.actuator_ctrllimited.astype(bool)[:, None] + super().__init__(model.nu, np.where(limited, model.actuator_ctrlrange, [-np.inf, np.inf]), steps_per_knot) + self.model, self._base = model, sim + self._sims: Dict[Tuple[int, bool], Any] = {} + self._sim: Any = None # the last stepped + self._last: Optional[Var] = None # the states it stepped to + _mjwarp_sort.patch() + + def _get_sim(self, batch_size: int, finite_differences: bool) -> Any: + """The simulator that steps `batch_size` states, made on first use.""" + key = (batch_size, finite_differences) + if key not in self._sims: + sim = self._sims[key] = self._base.resized(batch_size) + if finite_differences and hasattr(sim, "opt"): # MuJoCo Warp: sorted rows (costly, so not elsewhere) + import mujoco_warp as mjw # pyright: ignore[reportMissingImports] + + sim.opt.deterministic = int(mjw.DeterminismType.CONSTRAINT) # so neighboring states' differences agree + sim.data.contact.geomcollisionid.zero_() + return self._sims[key] + + def get_context(self, batch_size: int, finite_differences: bool = False) -> Dict[Context, Any]: + """The simulation terms' context (`sim_context`) of the worlds that step `batch_size` states.""" + return sim_context(self._get_sim(batch_size, finite_differences)) + + def build_state(self, qpos: ArrayLike, qvel: ArrayLike, act: Optional[ArrayLike] = None) -> VarValues: + """A `VarValues` state keyed by `SimKey`. + + Args: + qpos: `(B, nq)` joint positions. + qvel: `(B, nv)` velocities. + act: `(B, na)` activations, if the model has any. + """ + array = lambda a: a if isinstance(a, wp.array) else wp.array(np.asarray(a, np.float32), dtype=float) + parts: Dict[Enum, Var] = {SimKey.QPOS: QposVar(array(qpos), self.model), SimKey.QVEL: VectorVar(array(qvel))} + if self.model.na: + parts[SimKey.ACT] = VectorVar(array(act)) + return VarValues(parts) + + def step(self, x: Var, u: wp.array, x_next: Var, finite_differences: bool = False): + """`Dynamics.step`; then the worlds' `sensordata` is that of `x`, the rest that of `x_next`.""" + assert isinstance(x, VarValues) and isinstance(x_next, VarValues) + sim = self._get_sim(x.batch_size, finite_differences) + fresh = x is not self._last or sim is not self._sim # a step that continues the last keeps its warm start + for key in [k for k in SimKey if k in x] if fresh else (): # a fresh start: its states, a cold solver + wp.copy(getattr(sim.data, key.name.lower()), _get_array(x.get(key))) + if fresh: + sim.data.qacc_warmstart.zero_() + wp.copy(sim.data.ctrl, u) + for _ in range(self.steps_per_knot): # under the same controls + sim.step() + for key in [k for k in SimKey if k in x_next]: + wp.copy(_get_array(x_next.get(key)), getattr(sim.data, key.name.lower())) + self._sim, self._last = sim, x_next + + +def _get_array(var: Var) -> wp.array: + return var.qpos if isinstance(var, QposVar) else cast(VectorVar, var).x + + +__all__ = ["QposVar", "SimDynamics", "SimKey"] diff --git a/src/robokit/sim/mjentity.py b/src/robokit/sim/mjentity.py new file mode 100644 index 0000000..95c7886 --- /dev/null +++ b/src/robokit/sim/mjentity.py @@ -0,0 +1,309 @@ +"""`Entity`: a robot in a `MjWarpSim`, its state as torch tensors and its writes.""" + +import re +from typing import Any, List, Optional, Sequence + +import mujoco # pyright: ignore[reportMissingImports] +import numpy as np +import torch + + +def _find(names: Sequence[str], keys: Sequence[str]) -> List[int]: + """The indices of `names` that fully match each regex of `keys`, in the keys' order.""" + return [i for key in keys for i, name in enumerate(names) if re.fullmatch(key, name)] + + +class EntityData: + """An entity's state as torch tensors read from `sim.data.torch`, so `torch.compile` works. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> data = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).build_entity("r/").data + >>> data.root_link_pos_w[:, 2].tolist(), data.projected_gravity_b[:, 2].tolist() + ([0.5, 0.5], [-1.0, -1.0]) + """ + + def __init__(self, sim: Any, entity: "Entity", default_qpos: np.ndarray, soft_joint_pos_limit_factor: float): + mjm = sim.mjm + self._views = sim.data.torch + device = entity.device + joints = entity.joint_ids + self._root_body = entity.root_body + self.root_q_adr = int(mjm.jnt_qposadr[entity.root_joint]) if entity.root_joint >= 0 else 0 + self.root_v_adr = int(mjm.jnt_dofadr[entity.root_joint]) if entity.root_joint >= 0 else 0 + self.joint_q_adr = torch.tensor(mjm.jnt_qposadr[joints], device=device) + self.joint_v_adr = torch.tensor(mjm.jnt_dofadr[joints], device=device) + self._body_ids = torch.tensor(entity.body_ids, device=device) + self._site_ids = torch.tensor(entity.site_ids, device=device) + self._ctrl_ids = torch.tensor(entity.actuator_ids, device=device) + self._site_bodies = torch.tensor(mjm.site_bodyid[entity.site_ids], device=device) + self._site_roots = torch.tensor(mjm.body_rootid[mjm.site_bodyid[entity.site_ids]], device=device) + self._body_roots = torch.tensor(mjm.body_rootid[entity.body_ids], device=device) + root_pose = default_qpos[self.root_q_adr : self.root_q_adr + 7] if entity.root_joint >= 0 else np.zeros(7) + self.default_root_state = torch.zeros(13, device=device) # position, wxyz quaternion, linear, angular velocity + self.default_root_state[:7] = torch.tensor(root_pose, device=device) + self.default_joint_pos = torch.tensor(default_qpos[mjm.jnt_qposadr[joints]], device=device, dtype=torch.float32) + lo, hi = mjm.jnt_range[joints].T + mid = (lo + hi) / 2 + half = soft_joint_pos_limit_factor / 2 * (hi - lo) + limits = np.stack([mid - half, mid + half], 1) + self.soft_joint_pos_limits = torch.tensor(limits, device=device, dtype=torch.float32) # (joints, 2) + self.encoder_bias = torch.zeros(sim.nworld, len(joints), device=device) # rad, in `joint_pos_biased` + + @property + def projected_gravity_b(self) -> torch.Tensor: + """(nworld, 3): gravity's direction in the root's frame.""" + return -self._views.xmat[:, self._root_body, 2] + + @property + def heading_w(self) -> torch.Tensor: + """(nworld,): the yaw of the root's x axis, rad.""" + R_world_root = self._views.xmat[:, self._root_body] + return torch.atan2(R_world_root[:, 1, 0], R_world_root[:, 0, 0]) + + @property + def root_link_vel_w(self) -> torch.Tensor: + """(nworld, 6): the root's linear and angular velocity in the world frame, from the free joint's.""" + R_world_root = self._views.xmat[:, self._root_body] + ang_vel_w = torch.einsum("nij,nj->ni", R_world_root, self.root_link_ang_vel_b) + return torch.cat([self._views.qvel[:, self.root_v_adr : self.root_v_adr + 3], ang_vel_w], 1) + + @property + def root_link_lin_vel_b(self) -> torch.Tensor: + """(nworld, 3): the root's linear velocity in its frame, from the free joint's.""" + R_world_root = self._views.xmat[:, self._root_body] + return torch.einsum("nji,nj->ni", R_world_root, self._views.qvel[:, self.root_v_adr : self.root_v_adr + 3]) + + @property + def root_link_ang_vel_b(self) -> torch.Tensor: + """(nworld, 3): the root's angular velocity in its frame, the free joint's.""" + return self._views.qvel[:, self.root_v_adr + 3 : self.root_v_adr + 6] + + @property + def root_link_pos_w(self) -> torch.Tensor: + """(nworld, 3): the root's position.""" + return self._views.xpos[:, self._root_body] + + @property + def body_link_pos_w(self) -> torch.Tensor: + """(nworld, bodies, 3): each body's position.""" + return self._views.xpos[:, self._body_ids] + + @property + def body_link_mat_w(self) -> torch.Tensor: + """(nworld, bodies, 3, 3): each body's orientation.""" + return self._views.xmat[:, self._body_ids] + + @property + def body_link_lin_vel_w(self) -> torch.Tensor: + """(nworld, bodies, 3): each body origin's linear velocity, from its `cvel` about its tree's center of mass.""" + cvel = self._views.cvel[:, self._body_ids] + arm = self.body_link_pos_w - self._views.subtree_com[:, self._body_roots] + return cvel[..., 3:] + torch.cross(cvel[..., :3], arm, dim=-1) + + @property + def body_link_ang_vel_w(self) -> torch.Tensor: + """(nworld, bodies, 3): each body's angular velocity in the world frame.""" + return self._views.cvel[:, self._body_ids, :3] + + @property + def site_pos_w(self) -> torch.Tensor: + """(nworld, sites, 3).""" + return self._views.site_xpos[:, self._site_ids] + + @property + def site_mat_w(self) -> torch.Tensor: + """(nworld, sites, 3, 3): each site's orientation.""" + return self._views.site_xmat[:, self._site_ids] + + @property + def site_lin_vel_w(self) -> torch.Tensor: + """(nworld, sites, 3): each site's linear velocity, from its body's `cvel` about its tree's center of mass.""" + cvel = self._views.cvel[:, self._site_bodies] + arm = self.site_pos_w - self._views.subtree_com[:, self._site_roots] + return cvel[..., 3:] + torch.cross(cvel[..., :3], arm, dim=-1) + + @property + def joint_pos_target(self) -> torch.Tensor: + """(nworld, actuated joints): the position targets in `ctrl`, in joint order.""" + return self._views.ctrl[:, self._ctrl_ids] + + @property + def joint_pos(self) -> torch.Tensor: + """(nworld, joints).""" + return self._views.qpos[:, self.joint_q_adr] + + @property + def joint_pos_biased(self) -> torch.Tensor: + """(nworld, joints): as the encoders read them, with `encoder_bias`.""" + return self.joint_pos + self.encoder_bias + + @property + def joint_vel(self) -> torch.Tensor: + """(nworld, joints).""" + return self._views.qvel[:, self.joint_v_adr] + + @property + def qfrc_actuator(self) -> torch.Tensor: + """(nworld, joints): the actuators' generalized forces at the joints.""" + return self._views.qfrc_actuator[:, self.joint_v_adr] + + +class Entity: + """A robot in a `MjWarpSim`: the bodies, sites, joints named `prefix*`, actuators and `data`. + + Args: + prefix: The prefix of its names, which `joint_names`, `body_names` and `site_names` drop. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> xml += '' + >>> robot = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).build_entity( + ... "r/", soft_joint_pos_limit_factor=0.5) + >>> robot.joint_names, robot.find_sites(["tip"]), robot.data.soft_joint_pos_limits.tolist() + (['a'], [0], [[-0.5, 0.5]]) + >>> mask = torch.tensor([True, False], device=robot.device) + >>> robot.write_root_link_velocity_to_sim(torch.ones(2, 6, device=robot.device), mask) + >>> robot.data.root_link_vel_w[:, 0].tolist() + [1.0, 0.0] + """ + + def __init__(self, sim: Any, prefix: str, default_qpos: np.ndarray, soft_joint_pos_limit_factor: float = 1.0): + mjm = sim.mjm + self.device = sim.data.torch.qpos.device + free = mujoco.mjtJoint.mjJNT_FREE + ours = [j for j in range(mjm.njnt) if mjm.joint(j).name.startswith(prefix)] + self.joint_ids = [j for j in ours if mjm.jnt_type[j] != free] # hinges and slides, in model order + roots = [j for j in ours if mjm.jnt_type[j] == free] + self.root_joint = roots[0] if roots else -1 # its free joint, if any, is the root + self.body_ids = [b for b in range(mjm.nbody) if mjm.body(b).name.startswith(prefix)] + self.root_body = int(mjm.jnt_bodyid[self.root_joint]) if roots else self.body_ids[0] + self.site_ids = [s for s in range(mjm.nsite) if mjm.site(s).name.startswith(prefix)] + self.joint_names = [mjm.joint(j).name.removeprefix(prefix) for j in self.joint_ids] + self.body_names = [mjm.body(b).name.removeprefix(prefix) for b in self.body_ids] + self.site_names = [mjm.site(s).name.removeprefix(prefix) for s in self.site_ids] + acting = {} # joint: its actuator + for a in range(mjm.nu): + if mjm.actuator_trntype[a] == mujoco.mjtTrn.mjTRN_JOINT and mjm.actuator_trnid[a, 0] in self.joint_ids: + acting[int(mjm.actuator_trnid[a, 0])] = a + actuated = [i for i, j in enumerate(self.joint_ids) if j in acting] # joints with an actuator, in joint order + self.actuator_ids = [acting[self.joint_ids[i]] for i in actuated] # their actuators, in that order + self.actuated_ids = torch.tensor(actuated, device=self.device) + self._views = sim.data.torch # writes to them are masked, with no host syncs + self._ctrl_ids = torch.tensor(self.actuator_ids, device=self.device) + self.data = EntityData(sim, self, default_qpos, soft_joint_pos_limit_factor) + + def find_bodies(self, keys: Sequence[str]) -> List[int]: + """Indices into `body_names` (and `data`'s body axes) of the bodies matching each regex of `keys`, in order. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=1).build_entity("r/").find_bodies(["foot", "b.*"]) + [1, 0] + """ + return _find(self.body_names, keys) + + def find_sites(self, keys: Sequence[str]) -> List[int]: + """Indices into `site_names` (and `data`'s site axes) of the sites matching each regex of `keys`, in order. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=1).build_entity("r/").find_sites(["toe", "h.*"]) + [1, 0] + """ + return _find(self.site_names, keys) + + def set_joint_position_target(self, target: torch.Tensor): + """Write `target` (nworld, actuated joints), in joint order, to their actuators' `ctrl`. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> robot = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).build_entity("r/") + >>> robot.set_joint_position_target(torch.tensor([[0.5], [-0.5]], device=robot.device)) # c only + >>> robot.data.joint_pos_target.tolist() + [[0.5], [-0.5]] + """ + self._views.ctrl[:, self._ctrl_ids] = target + + def write_root_link_pose_to_sim(self, pose: torch.Tensor, mask: Optional[torch.Tensor] = None): + """Set the root's pose (nworld, 7: position, wxyz quaternion) where `mask` (nworld,) is set, else all. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> robot = (sim := MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2)).build_entity("r/") + >>> T_world_root = torch.tensor([[0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0]], device=robot.device).repeat(2, 1) + >>> robot.write_root_link_pose_to_sim(T_world_root, torch.tensor([True, False], device=robot.device)) + >>> sim.kinematics() # xpos from the new qpos + >>> robot.data.root_link_pos_w[:, 2].tolist() + [1.0, 0.0] + """ + q = self.data.root_q_adr + old = self._views.qpos[:, q : q + 7] + self._views.qpos[:, q : q + 7] = pose if mask is None else torch.where(mask[:, None], pose, old) + + def write_root_link_velocity_to_sim(self, velocity: torch.Tensor, mask: Optional[torch.Tensor] = None): + """Set the root's world-frame velocity (nworld, 6: linear, angular) where `mask` (nworld,) is set, else all. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' # yawed 90 deg + >>> robot = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).build_entity("r/") + >>> robot.write_root_link_velocity_to_sim(torch.tensor([[0.0, 0, 0, 1, 0, 0]] * 2, device=robot.device)) + >>> expected = torch.tensor([0.0, -1, 0], device=robot.device) # about world x is about the root's -y + >>> torch.allclose(robot.data.root_link_ang_vel_b, expected, atol=1e-6) + True + """ + q = self.data.root_q_adr + v = self.data.root_v_adr + q_wxyz_world_root = self._views.qpos[:, q + 3 : q + 7] # current, unlike `xmat` right after a pose write + twice_cross = 2 * torch.cross(q_wxyz_world_root[:, 1:], velocity[:, 3:], dim=-1) + rotated = q_wxyz_world_root[:, :1] * twice_cross + ang_vel_b = velocity[:, 3:] - rotated + torch.cross(q_wxyz_world_root[:, 1:], twice_cross, dim=-1) # body frame + qvel = torch.cat([velocity[:, :3], ang_vel_b], 1) + old = self._views.qvel[:, v : v + 6] + self._views.qvel[:, v : v + 6] = qvel if mask is None else torch.where(mask[:, None], qvel, old) + + def write_joint_state_to_sim( + self, position: torch.Tensor, velocity: torch.Tensor, mask: Optional[torch.Tensor] = None + ): + """Set the joints' positions and velocities (nworld, joints) where `mask` (nworld,) is set, else all. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> robot = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).build_entity("r/") + >>> one = torch.ones(1, device=robot.device) # broadcast to every world + >>> robot.write_joint_state_to_sim(0.5 * one, 0 * one, torch.tensor([False, True], device=robot.device)) + >>> robot.data.joint_pos.tolist() + [[0.0], [0.5]] + """ + position = position.expand_as(self.data.joint_pos) + velocity = velocity.expand_as(self.data.joint_vel) + if mask is not None: + position = torch.where(mask[:, None], position, self.data.joint_pos) + velocity = torch.where(mask[:, None], velocity, self.data.joint_vel) + self._views.qpos[:, self.data.joint_q_adr] = position + self._views.qvel[:, self.data.joint_v_adr] = velocity diff --git a/src/robokit/sim/mjscene.py b/src/robokit/sim/mjscene.py new file mode 100644 index 0000000..b24356c --- /dev/null +++ b/src/robokit/sim/mjscene.py @@ -0,0 +1,214 @@ +"""MuJoCo scenes from robokit robot files: robots at given transforms, a light, a floor or a curriculum terrain.""" + +from pathlib import Path +from typing import Sequence, Tuple, Union + +import mujoco # pyright: ignore[reportMissingImports] +import numpy as np + + +def build_robot_spec(path: Union[str, Path], prefix: str = "", body: str = "") -> mujoco.MjSpec: + """Load an MJCF or URDF robot into a spec with prefixed names; `body` keeps only that subtree, e.g. one ALOHA arm. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import tempfile + >>> path = Path(tempfile.mkdtemp()) / "arm.xml" + >>> _ = path.write_text('') + >>> build_robot_spec(path, prefix="left/").compile().joint(0).name + 'left/joint1' + """ + source = mujoco.MjSpec.from_file(str(path)) + robot = mujoco.MjSpec() + source.option = robot.option + root = source.body(body) if body else source.worldbody.first_body() + robot.worldbody.add_frame().attach_body(root, prefix, "") + return robot + + +def build_scene_spec( + robots: Sequence[Tuple[mujoco.MjSpec, Sequence[float]]] = (), floor: bool = True, timestep: float = 0.005 +) -> mujoco.MjSpec: + """Build a scene spec: implicitfast, a light, a floor if `floor`, each `(robot, T_world_base)` at its 7D transform. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import tempfile + >>> path = Path(tempfile.mkdtemp()) / "arm.xml" + >>> _ = path.write_text('') + >>> model = build_scene_spec([(build_robot_spec(path), (0, 0, 0, 1, 0, 0, 0))]).compile() + >>> model.joint(0).name, model.geom("floor").type[0] == mujoco.mjtGeom.mjGEOM_PLANE + ('joint1', True) + """ + spec = mujoco.MjSpec() + spec.option.timestep = timestep + spec.option.integrator = mujoco.mjtIntegrator.mjINT_IMPLICITFAST + spec.worldbody.add_light(pos=[0, 0, 3], dir=[0, 0, -1], type=mujoco.mjtLightType.mjLIGHT_DIRECTIONAL) + if floor: + spec.worldbody.add_geom(name="floor", type=mujoco.mjtGeom.mjGEOM_PLANE, size=[0, 0, 0.05]) + for robot, T_world_base in robots: + robot.option = spec.option + frame = spec.worldbody.add_frame(pos=T_world_base[:3], quat=T_world_base[3:]) + frame.attach_body(robot.worldbody.first_body(), "", "") + return spec + + +CONTACT_DATA = dict(found=1, force=2, torque=4, dist=8, pos=16, normal=32, tangent=64) # contact sensor fields +CONTACT_REDUCE = dict(none=0, mindist=1, maxforce=2, netforce=3) # how a contact sensor combines its matches + + +def build_contact_sensor( + spec: mujoco.MjSpec, + name: str, + obj: Tuple[int, str], + ref: Tuple[int, str] = (mujoco.mjtObj.mjOBJ_UNKNOWN, ""), + data: Sequence[str] = ("found",), + reduce: str = "none", + num: int = 1, +) -> mujoco.MjsSensor: + """Add a contact sensor `name` on `obj` against `ref`, reporting `data` for `num` contacts combined by `reduce`. + + Args: + obj: `(mujoco.mjtObj, name)`. + ref: `(mujoco.mjtObj, name)`; without it, contacts with anything count. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> spec = build_scene_spec() + >>> ball = spec.worldbody.add_body(name="ball", pos=[0, 0, 0.1]) + >>> _ = ball.add_geom(name="ball", size=[0.1, 0, 0]) + >>> _ = build_contact_sensor(spec, "touch", (mujoco.mjtObj.mjOBJ_GEOM, "ball"), data=("found", "force")) + >>> int(spec.compile().sensor_dim[0]) + 4 + """ + return spec.add_sensor( + name=name, + type=mujoco.mjtSensor.mjSENS_CONTACT, + objtype=obj[0], + objname=obj[1], + reftype=ref[0], + refname=ref[1], + intprm=[sum(CONTACT_DATA[field] for field in data), CONTACT_REDUCE[reduce], num], + ) + + +def _box(body: mujoco.MjsBody, pos: Sequence[float], dims: Sequence[float]): + """Add a box geom at `pos` with side lengths `dims`, each at least 2e-6 m.""" + body.add_geom(type=mujoco.mjtGeom.mjGEOM_BOX, pos=pos, size=np.maximum(1e-6, np.array(dims) / 2)) + + +def _ring(body: mujoco.MjsBody, center: Sequence[float], size: Sequence[float], hole: Sequence[float], height: float): + """Add four boxes `height` high framing a `hole` (x, y) at `center` within a `size` (x, y) square.""" + x, y, z = center + tx = (size[0] - hole[0]) / 2 + ty = (size[1] - hole[1]) / 2 + _box(body, (x, y + (hole[1] + ty) / 2, z), (size[0], ty, height)) + _box(body, (x, y - (hole[1] + ty) / 2, z), (size[0], ty, height)) + _box(body, (x - (hole[0] + tx) / 2, y, z), (tx, hole[1], height)) + _box(body, (x + (hole[0] + tx) / 2, y, z), (tx, hole[1], height)) + + +def build_terrain( + spec: mujoco.MjSpec, + kinds: Sequence[str] = ("flat", "stairs", "stairs_inv", "slope", "slope_inv", "random_rough", "wave"), + rows: int = 10, + tile: float = 8.0, + border: float = 20.0, + seed: int = 0, +) -> np.ndarray: + """Add a body "terrain" of `tile` m square tiles; return the tiles' spawn origins (rows, len(kinds), 3). + + Args: + kinds: A column of tiles per kind. + rows: Rows of tiles, of difficulty 0 to 1. + border: Width of the flat ring around the tiles, m. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> spec = build_scene_spec(floor=False) + >>> origins = build_terrain(spec, kinds=("flat", "stairs", "wave"), rows=2) + >>> origins.shape, spec.compile().nhfield + ((2, 3, 3), 2) + """ + body = spec.worldbody.add_body(name="terrain") + rng = np.random.default_rng(seed) # random_rough heights + origins = np.zeros((rows, len(kinds), 3)) + for col, kind in enumerate(kinds): + for row in range(rows): + difficulty = row / max(rows - 1, 1) + cx = -rows * tile / 2 + row * tile + tile / 2 + cy = -len(kinds) * tile / 2 + col * tile + tile / 2 + if kind == "flat": + _box(body, (cx, cy, -0.5), (tile, tile, 1.0)) + spawn_z = 0.0 + elif kind.startswith("stairs"): # steps 0 to 0.1 m high, 0.3 m deep, to a 3 m platform; a 1 m flat edge + rise = 0.1 * difficulty + run = 0.3 + inner = tile - 2 * 1.0 + steps = max(0, int((inner - 3.0) / (2 * run))) + top = (steps + 1) * rise + edge_height = max(rise, 0.05) + _ring(body, (cx, cy, -edge_height / 2), (tile, tile), (inner, inner), edge_height) + for k in range(steps): # step k: a square ring, its top at (k + 1) * rise up or down + if kind == "stairs_inv": + step_z = -top / 2 - (k + 1) * rise / 2 + height = top - (k + 1) * rise + else: + step_z = k * rise / 2 + height = (k + 2) * rise + size = inner - 2 * k * run + offset = inner / 2 - (k + 0.5) * run + _box(body, (cx, cy + offset, step_z), (size, run, height)) + _box(body, (cx, cy - offset, step_z), (size, run, height)) + _box(body, (cx + offset, cy, step_z), (run, size - 2 * run, height)) + _box(body, (cx - offset, cy, step_z), (run, size - 2 * run, height)) + rest = inner - 2 * steps * run + if kind == "stairs_inv": + _box(body, (cx, cy, -top - rise / 2), (rest, rest, rise)) + spawn_z = -top + else: + _box(body, (cx, cy, steps * rise / 2), (rest, rest, top + rise)) + spawn_z = top + else: # a heightfield: 0.1 m cells, 0.005 m height units, its outer 2 cells flat + cells = int(tile / 0.1) + n = cells - 4 # the cells inside the flat edge + width = n * 0.1 + unit = 0.005 + i = np.arange(n) + if kind.startswith("slope"): # a pyramid of slope 0 to 1, up or down to a 2 m platform + slope = -difficulty if kind == "slope_inv" else difficulty + peak = int(slope * width / 2 / unit) + center = n // 2 + ramp = (center - np.abs(center - i)) / center + raw = peak * ramp[:, None] * ramp[None, :] + plateau = raw[center - 10, center - 10] # the platform's edge, 1 m from the center + raw = np.clip(raw, min(0, plateau), max(0, plateau)) + elif kind == "random_rough": # 0.02 to 0.1 m in 0.02 m steps, a random height per cell + raw = rng.choice(np.arange(4, 21, 4), (n, n)) + else: # wave: 4 waves along x plus 4 along y, 0 to 0.2 m high + wavenumber = 2 * np.pi / (n / 4) + amplitude = int(0.1 * difficulty / unit) + raw = amplitude * (np.cos(i[None, :] * wavenumber) + np.sin(i[:, None] * wavenumber)) + heights = np.zeros((cells, cells), dtype=np.int16) + heights[2:-2, 2:-2] = np.rint(raw) + heights = heights.T + lo = heights.min() + span = max(heights.max() - lo, 1) + top = span * unit + base = top / 4 if kind == "wave" else top # the depth below the lowest cell + field = spec.add_hfield( + name=f"hfield_{row}_{col}", + size=[tile / 2, tile / 2, top, base], + nrow=cells, + ncol=cells, + userdata=((heights - lo) / span).flatten().astype(np.float32).tolist(), + ) + geom_z = {"slope_inv": -top, "wave": -top / 2}.get(kind, 0.0) # the flat edge at about z 0 + body.add_geom(type=mujoco.mjtGeom.mjGEOM_HFIELD, hfieldname=field.name, pos=(cx, cy, geom_z)) + spawn_z = {"slope": top, "slope_inv": -top, "random_rough": 0.06, "wave": 0.0}[kind] + origins[row, col] = cx, cy, spawn_z + grid = (rows * tile, len(kinds) * tile) + _ring(body, (0.0, 0.0, -0.5), (grid[0] + 2 * border, grid[1] + 2 * border), grid, 1.0) + for index, geom in enumerate(body.geoms): + geom.name = f"terrain_{index}" + return origins diff --git a/src/robokit/sim/mjsensor.py b/src/robokit/sim/mjsensor.py new file mode 100644 index 0000000..4845526 --- /dev/null +++ b/src/robokit/sim/mjsensor.py @@ -0,0 +1,173 @@ +"""`ContactSensor`: MuJoCo contact sensors in a `MjWarpSim` read together, as torch tensors.""" + +import re +from typing import Any, Optional + +import torch + + +class ContactSensorData: + """Contact readings as torch tensors read from `sim.data.torch`, so `torch.compile` works. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> xml += '' + >>> sim = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2, substeps=2) + >>> sim.step() + >>> data = sim.build_contact_sensor("touch").data + >>> data.found.tolist(), tuple(data.found_history.shape) # (substeps, nworld, primaries) + ([[1.0], [1.0]], (2, 2, 1)) + """ + + def __init__(self, sim: Any, found: list, force: list, track_air_time: bool): + self._views = sim.data.torch + device = self._views.sensordata.device + self._found = torch.tensor(found, dtype=torch.long, device=device) # (primaries,) + self._force = torch.tensor(force, dtype=torch.long, device=device).reshape(-1, 3) # (primaries, 3) + primaries = max(len(found), len(force)) + self.current_air_time: Optional[torch.Tensor] = None # (nworld, primaries), s, with `track_air_time` + self.current_contact_time: Optional[torch.Tensor] = None + if track_air_time: + self.current_air_time = torch.zeros(sim.nworld, primaries, device=device) + self.current_contact_time = torch.zeros(sim.nworld, primaries, device=device) + + @property + def found(self) -> torch.Tensor: + """(nworld, primaries): the contacts each found after the last substep.""" + return self._views.sensordata[:, self._found] + + @property + def force(self) -> torch.Tensor: + """(nworld, primaries, 3): each one's contact force after the last substep.""" + return self._views.sensordata[:, self._force] + + @property + def found_history(self) -> torch.Tensor: + """(substeps, nworld, primaries): `found` after each substep of the last step.""" + return self._views.substep_sensordata[:, :, self._found] + + @property + def force_history(self) -> torch.Tensor: + """(substeps, nworld, primaries, 3): `force` after each substep of the last step.""" + return self._views.substep_sensordata[:, :, self._force] + + +class ContactSensor: + """The MuJoCo contact sensors `{name}_{primary}_{found or force}`, one per primary. + + Args: + track_air_time: Let `update()` count each primary's air and contact time per substep. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco + >>> from robokit.sim import MjWarpSim, mjscene + >>> spec = mjscene.build_scene_spec() + >>> ball = spec.worldbody.add_body(name="ball", pos=[0, 0, 0.1]) + >>> _ = ball.add_freejoint() + >>> _ = ball.add_geom(name="ball", size=[0.1, 0, 0]) + >>> for field in ("found", "force"): + ... _ = mjscene.build_contact_sensor( + ... spec, f"touch_ball_{field}", (mujoco.mjtObj.mjOBJ_GEOM, "ball"), data=(field,)) + >>> sim = MjWarpSim(spec.compile(), nworld=2, substeps=2) + >>> touch = sim.build_contact_sensor("touch", track_air_time=True) + >>> sim.step() + >>> touch.update() + >>> touch.primary_names, tuple(touch.data.force.shape), (touch.data.current_contact_time > 0).tolist() + (['ball'], (2, 1, 3), [[True], [True]]) + """ + + def __init__(self, sim: Any, name: str, track_air_time: bool = False): + mjm = sim.mjm + pattern = re.compile(re.escape(name) + r"_(.+)_(found|force)") + self.primary_names = [] + found = {} + force = {} + for i in range(mjm.nsensor): + match = pattern.fullmatch(mjm.sensor(i).name) + if match is None: + continue + primary, field = match.groups() + if primary not in self.primary_names: + self.primary_names.append(primary) + adr = int(mjm.sensor_adr[i]) + if field == "found": + found[primary] = adr + else: + force[primary] = [adr, adr + 1, adr + 2] + self.substep_dt = mjm.opt.timestep + found_adr = [found[p] for p in self.primary_names if p in found] + force_adr = [force[p] for p in self.primary_names if p in force] + self.data = ContactSensorData(sim, found_adr, force_adr, track_air_time) + + def update(self): + """Count each primary's air and contact time over the last step's substeps, from `found`. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> xml += '' + >>> sim = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2, substeps=2) + >>> touch = sim.build_contact_sensor("touch", track_air_time=True) + >>> sim.step() + >>> touch.update() + >>> (touch.data.current_air_time > 0).tolist(), (touch.data.current_contact_time > 0).tolist() + ([[True], [True]], [[False], [False]]) + """ + air = self.data.current_air_time + contact = self.data.current_contact_time + assert air is not None and contact is not None, "needs track_air_time" + for found in self.data.found_history: + touching = found > 0 + air.copy_(torch.where(touching, 0.0, air + self.substep_dt)) + contact.copy_(torch.where(touching, contact + self.substep_dt, 0.0)) + + def compute_first_contact(self, dt: float, abs_tol: float = 1e-6) -> torch.Tensor: + """(nworld, primaries): the primaries that touched down within the last `dt` s. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> xml += '' + >>> sim = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2, substeps=2) + >>> touch = sim.build_contact_sensor("touch", track_air_time=True) + >>> sim.step() + >>> touch.update() + >>> touch.compute_first_contact(dt=sim.substeps * sim.mjm.opt.timestep).tolist() + [[True], [True]] + """ + contact = self.data.current_contact_time + assert contact is not None, "needs track_air_time" + return (contact > 0) & (contact < dt + abs_tol) + + def reset(self, mask: torch.Tensor): + """Zero the air and contact times in the worlds where `mask` (nworld,) is set. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> xml += '' + >>> sim = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2, substeps=2) + >>> touch = sim.build_contact_sensor("touch", track_air_time=True) + >>> sim.step() + >>> touch.update() + >>> touch.reset(torch.tensor([True, False], device=touch.data.found.device)) + >>> (touch.data.current_air_time > 0).tolist() + [[False], [True]] + """ + for time in (self.data.current_air_time, self.data.current_contact_time): + if time is not None: + time.copy_(torch.where(mask[:, None], 0.0, time)) diff --git a/src/robokit/sim/mjwarp.py b/src/robokit/sim/mjwarp.py new file mode 100644 index 0000000..135fbd8 --- /dev/null +++ b/src/robokit/sim/mjwarp.py @@ -0,0 +1,616 @@ +# pyright: reportArgumentType=false +# pyright: reportGeneralTypeIssues=false +# pyright: reportMissingImports=false +# pyright: reportAttributeAccessIssue=false +# pyright: reportCallIssue=false +"""`MjWarpSim`: MuJoCo Warp worlds of one model or several scenes stepped together, their fields as Warp arrays.""" + +import dataclasses +import gc +import re +import types +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import mujoco +import mujoco_warp as mjw +import numpy as np +import warp as wp +from mujoco_warp._src import math as mjmath # wxyz quaternions, as MuJoCo Warp's + + +if TYPE_CHECKING: + from robokit.sim.mjentity import Entity + from robokit.sim.mjsensor import ContactSensor + + +# --- fields ---------------------------------------------------------------- +# The data fields `reset` restores. +_STATE = ("qpos", "qvel", "act", "ctrl", "qacc_warmstart", "time") +# The model fields `mjw.set_const` derives from masses and inertias; randomized masses need them per world too. +_DERIVED = ( + "body_subtreemass", + "dof_invweight0", + "body_invweight0", + "tendon_length0", + "tendon_invweight0", + "actuator_acc0", +) +# The model fields with a world axis; the others are shared by every world. +_BATCHED = {f.name for f in dataclasses.fields(mjw.Model) if getattr(f.type, "shape", ())[:1] == ("*",)} + + +class _Fields: + """Cached Warp arrays of the fields of a `mjw.Data`, `mjw.Model` or `mjw.Option`.""" + + def __init__(self, struct: Any, sim: "MjWarpSim"): + self.__dict__.update(_struct=struct, _sim=sim) + + def __getattr__(self, field: str) -> Any: + """The field; a model field with a world axis gets a row per world on first access.""" + value, nworld = getattr(self._struct, field), self._sim.nworld + if field in _BATCHED and value.shape[0] < nworld: # copy the shared row(s) out to every world + value = wp.array(value.numpy()[np.arange(nworld) % value.shape[0]], dtype=value.dtype, device=value.device) + setattr(self, field, value) + self.__dict__[field] = value + return value + + def __setattr__(self, field: str, value: Any): + """Replace the field and drop `sim`'s graphs, which hold the old array.""" + setattr(self._struct, field, value) + self.__dict__[field] = value + self.__dict__.pop("_torch", None) # its torch views hold the old + self._sim._graphs.clear() + + +class _DataFields(_Fields): + """`_Fields` of a `mjw.Data` plus `substep_sensordata`; `torch`: zero-copy torch views, made on first access.""" + + @property + def torch(self) -> types.SimpleNamespace: + if "_torch" not in self.__dict__: + views = {} + for field in dataclasses.fields(self._struct): + value = getattr(self._struct, field.name) + if isinstance(value, wp.array): + views[field.name] = wp.to_torch(value) + views["substep_sensordata"] = wp.to_torch(self.substep_sensordata) + self.__dict__["_torch"] = types.SimpleNamespace(**views) + return self.__dict__["_torch"] + + +# m: a geom's or pair's margin in the worlds whose scene lacks it: it never collides there, but rays and renders see it. +_NO_CONTACT_MARGIN = -1e3 + + +# --- simulator ------------------------------------------------------------- +@wp.kernel +def _mask_kernel(mask: wp.array(dtype=Any), out: wp.array(dtype=int)): + w = wp.tid() + out[w] = 0 + if mask[w]: + out[w] = 1 + + +@wp.kernel +def _reset_kernel(mask: wp.array(dtype=int), value: wp.array2d(dtype=float), out: wp.array2d(dtype=float)): + w, i = wp.tid() # pyright: ignore[reportAssignmentType] + if mask[w]: + out[w, i] = value[w, i] + + +@wp.kernel +def _scene_kernel( + mask: wp.array(dtype=int), scene: wp.array(dtype=int), rows: wp.array2d(dtype=Any), out: wp.array2d(dtype=Any) +): + w, i = wp.tid() # pyright: ignore[reportAssignmentType] + if mask[w]: + out[w, i] = rows[scene[w], i] + + +@wp.kernel +def _static_kernel( + mask: wp.array(dtype=int), + geoms: wp.array(dtype=int), + geom_bodyid: wp.array(dtype=int), + geom_pos: wp.array2d(dtype=wp.vec3), + geom_quat: wp.array2d(dtype=wp.quat), + xpos: wp.array2d(dtype=wp.vec3), + xquat: wp.array2d(dtype=wp.quat), + geom_xpos: wp.array2d(dtype=wp.vec3), + geom_xmat: wp.array2d(dtype=wp.mat33), +): + # MuJoCo Warp places the geoms of static bodies once, in `put_data`; kinematics still computes the bodies' frames + w, i = wp.tid() # pyright: ignore[reportAssignmentType] + g = geoms[i] + b = geom_bodyid[g] + if mask[w]: + geom_xpos[w, g] = xpos[w, b] + mjmath.rot_vec_quat(geom_pos[w % geom_pos.shape[0], g], xquat[w, b]) + geom_xmat[w, g] = mjmath.quat_to_mat(mjmath.mul_quat(xquat[w, b], geom_quat[w % geom_quat.shape[0], g])) + + +@dataclasses.dataclass(frozen=True) +class CoarseConfig: + """`MjWarpSim.build_coarse_spec`'s cheaper geometry and physics; a field at its default changes nothing. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> spec = mujoco.MjSpec.from_string('') + >>> MjWarpSim.build_coarse_spec(spec, CoarseConfig()).to_xml() == spec.to_xml() + True + >>> MjWarpSim.build_coarse_spec(spec, CoarseConfig(timestep=0.01)).option.timestep + 0.01 + """ + + max_hull_vertices: int = -1 # each mesh's convex hull's most vertices + qpos_ref: Optional[np.ndarray] = None # (T, nq): only the ``s that come within `reach` m along it remain + reach: float = 0.02 # m + collide: str = "" # only the geoms whose name (else their body's) fully matches this regex collide + condim: int = 0 # contacts of at most this many dimensions + condim_geoms: str = "" # `condim` only for the geoms whose name (else their body's) fully matches this regex + timestep: float = 0.0 # s + min_timeconst: float = 0.0 # contacts' and equalities' solref time constants at least this, s + min_impedance_width: float = 0.0 # contacts' and equalities' solimp widths at least this, m + pyramidal: bool = False # pyramidal friction cones with impratio 1, as mjbatch's + iterations: int = 0 # the most solver iterations + ls_iterations: int = 0 # the most line search iterations, else `iterations` + integrator: str = "" # e.g. "implicitfast", stable at larger steps with joint damping + + +class MjWarpSim: + """Step `nworld` worlds of `model`, or `nworld[i]` of each scene `model[i]`, `substeps` physics steps per `step()`. + + Args: + model: A `mujoco.MjModel`, or `mujoco.MjSpec` scenes that may differ in geoms, meshes, inertias, sites, pairs. + nworld: The worlds, or each scene's; each world gets its scene's values. + data: The state `reset()` restores, else keyframe `key`'s, else the defaults; several scenes: their defaults. + device: The Warp device; on a GPU each call runs as one cached CUDA graph. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> import mujoco, numpy as np, warp as wp + >>> from robokit.sim import MjWarpSim + >>> xml = '' + >>> xml += '' + >>> sim = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=8, substeps=4) + >>> sim.model.geom_friction.shape # one row per world, ready to randomize + (8, 2) + >>> sim.opt.iterations = 5 # from the next step on + >>> sim.step() + >>> bool((sim.data.qpos.numpy()[:, 2] < 0.5).all()), sim.data.substep_sensordata.shape + (True, (4, 8, 0)) + >>> sim.reset(wp.array(np.arange(8) < 4)) # the first four worlds back to the start + >>> z = sim.data.qpos.numpy()[:, 2] + >>> float(z[0]), bool(z[7] < 0.5) + (0.5, True) + >>> big = mujoco.MjSpec.from_string(xml.replace('size=".1"', 'size=".2"')) + >>> mixed = MjWarpSim([mujoco.MjSpec.from_string(xml), big], nworld=[3, 5]) # worlds 3 to 7: the big ball + >>> (mixed.model.geom_size.numpy()[:, 1, 0] > 0.15).tolist() + [False, False, False, True, True, True, True, True] + >>> pos = mixed.model.geom_pos.numpy() + >>> pos[0, 0, 2] = -1.0 # world 0's floor, a static geom, a meter lower ... + >>> mixed.model.geom_pos.assign(pos) + >>> mixed.reset(wp.array(np.arange(8) == 0)) # ... from its next reset + >>> mixed.data.geom_xpos.numpy()[:2, 0, 2].tolist() + [-1.0, 0.0] + """ + + def __init__( + self, + model: Union[mujoco.MjModel, Sequence[mujoco.MjSpec]], + nworld: Union[int, Sequence[int]], + data: Optional[mujoco.MjData] = None, + substeps: int = 1, + njmax: Optional[int] = None, + nconmax: Optional[int] = None, + key: Optional[str] = None, + device=None, + ): + self._args = {k: v for k, v in locals().items() if k not in ("self", "nworld")} # for `resized` + mixed = not isinstance(model, mujoco.MjModel) + if mixed: + model, scenes, values = self._merge_scenes(model) + else: + scenes, values = [model], {} + scene = np.repeat(np.arange(len(scenes)), nworld) # each world's scene + if data is None: + data = mujoco.MjData(model) + if key is not None: + mujoco.mj_resetDataKeyframe(model, data, model.key(key).id) + mujoco.mj_forward(model, data) + initial = [mujoco.MjData(m) for m in scenes] if mixed else [data] # each scene's initial state + self.mjm, self.nworld, self.substeps, self.device = model, len(scene), substeps, wp.get_device(device) + self.stream = wp.get_stream(self.device) if self.device.is_cuda else None + self._graphs: Dict[str, wp.Graph] = {} + with wp.ScopedDevice(self.device): + self._m = mjw.put_model(model) + if hasattr(mjw, "OverflowType"): # newer MuJoCo Warp warns on each capped solve; scenes cap on purpose + self._m.opt.warn_overflow &= ~int(mjw.OverflowType.ITERATIONS | mjw.OverflowType.LS_ITERATIONS) + self._d = mjw.put_data(model, data, nworld=self.nworld, nconmax=nconmax, njmax=njmax) + self.data, self.model, self.opt = ( + _DataFields(self._d, self), + _Fields(self._m, self), + _Fields(self._m.opt, self), # a change takes effect from the next call + ) + sensordata = wp.zeros((substeps, self.nworld, model.nsensordata), dtype=float) + self.data.__dict__["substep_sensordata"] = sensordata # not a `mjw.Data` field + self._mask = wp.zeros(self.nworld, dtype=int) # `reset`'s, at a fixed address its cached graph reads + self._static = wp.array(np.flatnonzero(model.body_weldid[model.geom_bodyid] == 0), dtype=int) + self._scene_rows: List[Tuple[wp.array, wp.array]] = [] # for `set_scene`: each world's field, every scene's + for f, x in values.items(): # each world its scene's values where the scenes differ + if not (x == x[:1]).all(): + field = getattr(self.model, f) + shape = field.numpy().shape + field.assign(x[scene].reshape(shape)) + rows = wp.array(x.reshape((len(scenes),) + shape[1:]), dtype=field.dtype) + self._scene_rows.append((field.reshape((self.nworld, -1)), rows.reshape((len(scenes), -1)))) + self._initial: List[Tuple[wp.array, wp.array]] = [] # for `reset`: each `_STATE` field, its initial rows + for f in _STATE: + value = np.stack([np.atleast_1d(getattr(d, f)) for d in initial])[scene] # its starting scene's + self._initial.append((getattr(self._d, f).reshape((self.nworld, -1)), wp.array(value, dtype=float))) + if mixed: # each world from its scene's initial state, its static geoms where its scene has them + self.reset(wp.ones(self.nworld, dtype=int)) + mjw.forward(self._m, self._d) + + def resized(self, nworld: int) -> "MjWarpSim": + """A new simulator of this one's scenes and settings with `nworld` worlds, split evenly over several scenes.""" + scenes = self._args["model"] + one = isinstance(scenes, mujoco.MjModel) + return MjWarpSim(nworld=nworld if one else [nworld // len(scenes)] * len(scenes), **self._args) + + @staticmethod + def build_coarse_spec(spec: mujoco.MjSpec, config: CoarseConfig) -> mujoco.MjSpec: + """A copy of `spec` with `config`'s cheaper geometry and physics, e.g. for planning or early RL training. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> spec = mujoco.MjSpec.from_string( + ... '' + ... '' + ... '' + ... ) + >>> coarse = MjWarpSim.build_coarse_spec(spec, CoarseConfig(qpos_ref=np.array([[0, 0, 0, 1, 0, 0, 0]]))) + >>> coarse.compile().npair # only a-c comes near + 1 + >>> config = CoarseConfig(collide="a|c|d", condim=1, condim_geoms="d", timestep=0.01, pyramidal=True) + >>> model = MjWarpSim.build_coarse_spec(spec, config).compile() + >>> model.geom_contype.tolist(), model.geom_condim.tolist() # b, c, a, d's unnamed: b no longer collides + ([0, 1, 1, 1], [3, 3, 3, 1]) + >>> model.opt.timestep, model.opt.cone + (0.01, 0) + >>> config = CoarseConfig(min_timeconst=0.01, min_impedance_width=0.002) + >>> model = MjWarpSim.build_coarse_spec(spec, config).compile() + >>> model.geom_solref[:, 0].tolist(), model.geom_solimp[:, 2].tolist() # from 0.02 and 0.001 by default + ([0.02, 0.02, 0.02, 0.02], [0.002, 0.002, 0.002, 0.002]) + >>> config = CoarseConfig(iterations=2, ls_iterations=4, integrator="implicitfast") + >>> opt = MjWarpSim.build_coarse_spec(spec, config).option + >>> opt.iterations, opt.ls_iterations, opt.integrator == mujoco.mjtIntegrator.mjINT_IMPLICITFAST + (2, 4, True) + """ + coarse = spec.copy() + for mesh in coarse.meshes if config.max_hull_vertices > 0 else []: + mesh.maxhullvert = config.max_hull_vertices + if config.qpos_ref is not None: + wide = coarse.copy() + for pair in wide.pairs: + pair.margin = config.reach + model, near = wide.compile(), set() + data = mujoco.MjData(model) + for q in config.qpos_ref: + data.qpos[:] = q + mujoco.mj_kinematics(model, data) + mujoco.mj_collision(model, data) + near |= {tuple(sorted(map(int, c.geom))) for c in data.contact[: data.ncon]} + for pair in list(coarse.pairs): + if tuple(sorted((model.geom(pair.geomname1).id, model.geom(pair.geomname2).id))) not in near: + coarse.delete(pair) + for geom in coarse.geoms: + name = geom.name or geom.parent.name + if config.collide and not re.fullmatch(config.collide, name): + geom.contype = geom.conaffinity = 0 + elif config.condim and re.fullmatch(config.condim_geoms or ".*", name): + geom.condim = min(geom.condim, config.condim) + for pair in coarse.pairs if config.condim and not config.condim_geoms else []: + pair.condim = min(pair.condim, config.condim) + for element in [*coarse.geoms, *coarse.pairs, *coarse.equalities]: + if element.solref[0] > 0: # time constants, not direct stiffness and damping + element.solref[0] = max(element.solref[0], config.min_timeconst) + element.solimp[2] = max(element.solimp[2], config.min_impedance_width) + coarse.option.timestep = config.timestep or coarse.option.timestep + if config.pyramidal: + coarse.option.cone, coarse.option.impratio = mujoco.mjtCone.mjCONE_PYRAMIDAL, 1.0 + iterations = config.iterations or coarse.option.iterations + coarse.option.iterations = min(iterations, coarse.option.iterations) + ls_iterations = config.ls_iterations or config.iterations or coarse.option.ls_iterations + coarse.option.ls_iterations = min(ls_iterations, coarse.option.ls_iterations) + if config.integrator: + coarse.option.integrator = getattr(mujoco.mjtIntegrator, f"mjINT_{config.integrator.upper()}") + return coarse + + def set_const(self): + """Recompute constants derived from masses and inertias, per world, after randomizing them or `body_ipos`.""" + for field in _DERIVED: + getattr(self.model, field) + with wp.ScopedDevice(self.device): + mjw.set_const(self._m, self._d) + + def build_entity(self, prefix: str, soft_joint_pos_limit_factor: float = 1.0) -> "Entity": + """The `robokit.sim.mjentity.Entity` named `prefix*`, its default pose the initial `qpos`. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> xml = '' + >>> xml += '' + >>> robot = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).build_entity("r/") + >>> robot.joint_names, robot.data.default_root_state[:3].tolist() + (['a'], [0.0, 0.0, 0.5]) + """ + from robokit.sim.mjentity import Entity + + default_qpos = self._initial[0][1].numpy()[0] # `qpos`, world 0's + return Entity(self, prefix, default_qpos, soft_joint_pos_limit_factor) + + def build_contact_sensor(self, name: str, track_air_time: bool = False) -> "ContactSensor": + """A `robokit.sim.mjsensor.ContactSensor` of the contact sensors named `{name}_{primary}_{found or force}`. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> xml = '' + >>> xml += '' + >>> MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).build_contact_sensor("touch").primary_names + ['ball'] + """ + from robokit.sim.mjsensor import ContactSensor + + return ContactSensor(self, name, track_air_time) + + def get_sensor(self, name: str) -> Any: + """(nworld, dim): sensor `name`'s readings, a zero-copy torch view of `data.sensordata`. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> xml = '' + >>> xml += '' + >>> MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2).get_sensor("p").tolist() + [[0.0, 0.0, 0.5], [0.0, 0.0, 0.5]] + """ + sensor = self.mjm.sensor(name) + adr = int(self.mjm.sensor_adr[sensor.id]) + return self.data.torch.sensordata[:, adr : adr + int(self.mjm.sensor_dim[sensor.id])] + + def compute_rays(self, render_context: Any, **rays: Any): + """Refit `render_context`'s BVH to the current poses, then cast `rays` (`mjw.rays` arguments) in every world. + + Example: + >>> # xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS) + >>> mjm = mujoco.MjModel.from_xml_string('' + ... '') + >>> rc = mjw.create_render_context(mjm, 2, cam_res=[], render_rgb=[], render_depth=[], render_seg=[]) + >>> dist, down = wp.zeros((2, 1), dtype=float), wp.array([[[0, 0, -1]]] * 2, dtype=wp.vec3) # from z = 1 m + >>> MjWarpSim(mjm, nworld=2).compute_rays(rc, pnt=wp.array([[[0, 0, 1]]] * 2, dtype=wp.vec3), vec=down, + ... geomgroup=wp.types.vector(6, wp.float32)(-1, -1, -1, -1, -1, -1), flg_static=True, + ... bodyexclude=wp.array([-1], dtype=int), dist=dist, geomid=wp.zeros((2, 1), dtype=int), + ... normal=wp.zeros((2, 1), dtype=wp.vec3)) + >>> dist.numpy().tolist() + [[1.0], [1.0]] + """ + with wp.ScopedDevice(self.device): + mjw.refit_bvh(self._m, self._d, render_context) + mjw.rays(self._m, self._d, rc=render_context, **rays) + + def set_torch_stream(self): + """Run torch on Warp's `stream`, so torch and the simulator stay ordered without host syncs. + + Example: + >>> # xdoctest: +REQUIRES(env:ROBOKIT_CUDA_DOCS) + >>> import torch + >>> xml = '' + >>> (sim := MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=2)).set_torch_stream() + >>> torch.cuda.current_stream().cuda_stream == sim.stream.cuda_stream + True + """ + import torch + + torch.cuda.set_stream(wp.stream_to_torch(self.stream)) + + def set_random( + self, + field: str, + index: Tuple[Any, ...], + low: Union[float, Sequence[float]], + high: Union[float, Sequence[float]], + log: bool = False, + add: bool = False, + rng: Optional[np.random.Generator] = None, + ): + """Set (`add`: offset) `model.[:, *index]` to one uniform draw per world from `low` to `high`. + + Args: + field: After `body_mass`, `body_inertia`, `body_ipos` or `body_iquat`, it runs `set_const()`. + low: Lower bound, broadcast to the trailing axes. + high: Upper bound, broadcast to the trailing axes. + log: Draw log-uniformly. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> xml = '' + >>> sim = MjWarpSim(mujoco.MjModel.from_xml_string(xml), nworld=8) + >>> sim.set_random("geom_friction", (0, 0), 0.5, 1.0) # sliding friction + >>> friction = sim.model.geom_friction.numpy()[:, 0, 0] + >>> bool(((friction >= 0.5) & (friction <= 1.0)).all()), len(set(friction.tolist())) + (True, 8) + >>> sim.set_random("body_ipos", (1,), (-0.01, -0.01, 0.0), (0.01, 0.01, 0.0), add=True) # center of mass + >>> float(abs(sim.model.body_ipos.numpy()[:, 1, 2]).max()) + 0.0 + """ + rng = rng if rng is not None else np.random.default_rng() + array = getattr(self.model, field) + values = array.numpy() + lo = np.asarray(low, dtype=float) + hi = np.asarray(high, dtype=float) + target = values[(slice(None), *index)] + shape = (self.nworld,) + (1,) * (target.ndim - 1 - lo.ndim) + lo.shape + u = rng.random(shape) + draw = lo * (hi / lo) ** u if log else lo + (hi - lo) * u + values[(slice(None), *index)] = target + draw if add else draw + array.assign(values) + if field in ("body_mass", "body_inertia", "body_ipos", "body_iquat"): + self.set_const() + + def step(self): + """Advance `substeps` physics steps into `substep_sensordata`; derived fields then lag `qpos` by a substep.""" + + def body(): + for k in range(self.substeps): + mjw.step(self._m, self._d) + wp.copy(self.data.substep_sensordata, self._d.sensordata, dest_offset=k * self._d.sensordata.size) + + self._launch("step", body) + + def kinematics(self): + """Recompute `xpos`, `xmat`, `site_xpos`, ... from `qpos`, e.g. after writing it, as `mj_kinematics`.""" + self._launch("kinematics", lambda: mjw.kinematics(self._m, self._d)) + + def com_pos(self): + """Recompute `subtree_com` (subtree centers of mass), `cinert` and `cdof` from the positions, as `mj_comPos`.""" + self._launch("com_pos", lambda: mjw.com_pos(self._m, self._d)) + + def forward(self): + """Recompute every derived quantity, accelerations and `sensordata` included, as `mj_forward`.""" + self._launch("forward", lambda: mjw.forward(self._m, self._d)) + + def reset(self, mask: wp.array): + """Return the worlds where `mask` is set to their initial state, static geoms to their current rows. + + Args: + mask: (nworld,), bool or int; read on the device, with no host syncs. + """ + + def body(): + m, d = self._m, self._d + for out, value in self._initial: + wp.launch(_reset_kernel, dim=out.shape, inputs=[self._mask, value], outputs=[out]) + mjw.kinematics(m, d) + # static geoms from the current `body_pos`, `body_quat`, `geom_pos`, `geom_quat` + inputs = [self._mask, self._static, m.geom_bodyid, m.geom_pos, m.geom_quat, d.xpos, d.xquat] + wp.launch(_static_kernel, (self.nworld, len(self._static)), inputs, [d.geom_xpos, d.geom_xmat]) + + wp.launch(_mask_kernel, dim=self.nworld, inputs=[mask], outputs=[self._mask], device=self.device) + self._launch("reset", body) + + def set_scene(self, mask: wp.array, scene: wp.array): + """Give the worlds where `mask` is set scene `scene[w]`'s model rows; their static geoms move at `reset()`. + + Args: + mask: (nworld,), read on the device, with no host syncs. + scene: (nworld,), int. + + Example: + >>> # xdoctest: +REQUIRES(module:mujoco_warp) + >>> xml = '' + >>> scenes = [mujoco.MjSpec.from_string(xml), mujoco.MjSpec.from_string(xml.replace(".1", ".2"))] + >>> sim = MjWarpSim(scenes, nworld=[2, 2]) + >>> sim.set_scene(wp.array([True, False, False, False]), wp.array([1, 0, 0, 0], dtype=int)) + >>> (sim.model.geom_size.numpy()[:, 0, 0] > 0.15).tolist() # world 0: the big ball + [True, False, True, True] + """ + wp.launch(_mask_kernel, dim=self.nworld, inputs=[mask], outputs=[self._mask], device=self.device) + for out, rows in self._scene_rows: + wp.launch(_scene_kernel, dim=out.shape, inputs=[self._mask, scene, rows], outputs=[out], device=self.device) + + def _launch(self, name: Optional[str], body: Callable[[], None]): + """Run `body` into an enclosing capture, directly on the CPU or without a `name`, else as a cached graph.""" + with wp.ScopedDevice(self.device): + stream = wp.get_stream() if self.device.is_cuda else None + if stream is not None and stream.is_capturing: # inside an enclosing capture: record the kernels into it + external = stream not in self.device.captures # not started by Warp, e.g. torch's + conditional = self._m.opt.graph_conditional + # In a capture Warp did not start, the solver runs all iterations: an early stop would pause it. + self._m.opt.graph_conditional = conditional and not external + if external: # tell Warp about it, as its own launches and allocations need + wp.capture_begin(stream=stream, external=True, capture_mode=wp.CaptureMode.GLOBAL) + body() + if external: + wp.capture_end(stream=stream) + self._m.opt.graph_conditional = conditional + elif stream is None or name is None: + body() + else: + if name not in self._graphs: + wp.synchronize_device() + gc.collect() # as torch.cuda.graph: a collection during the capture may free CUDA modules + gc.disable() + try: + with wp.ScopedCapture() as capture: + body() + finally: + gc.enable() + self._graphs[name] = capture.graph + wp.capture_launch(self._graphs[name]) + + # --- mixed scenes --------------------------------------------------------- + @staticmethod + def _merge_scenes( + specs: Sequence[mujoco.MjSpec], + ) -> Tuple[mujoco.MjModel, List[mujoco.MjModel], Dict[str, np.ndarray]]: + """Merge `specs` into the one with the most geoms; others' geoms match its own by name (unnamed: by place). + + Returns: + One model of every scene's geoms, meshes, pairs; the compiled scenes; each scene's values `(nscene, ...)`. + """ + scenes = [s.compile() for s in specs] + t = int(np.argmax([m.ngeom for m in scenes])) # the template + T = scenes[t] + sizes = ("nq", "nv", "nu", "na", "nbody", "njnt", "nsite", "nsensordata") + for m in scenes: + if [getattr(m, k) for k in sizes] != [getattr(T, k) for k in sizes] or ( + m.body_geomnum > T.body_geomnum + ).any(): + raise ValueError(f"scenes must match in {', '.join(sizes)}, and one have the most geoms on every body") + + # A scene's mesh the template lacks joins its spec as `__`, with a geom so MuJoCo builds the hull. + spec = specs[t].copy() + used = np.bitwise_or.reduce(np.r_[T.geom_contype, T.geom_conaffinity]) + unused = int(~used & (used + 1)) # a collision bit no geom uses: those geoms collide with nothing + # MjSpec copies no element across specs, so these attributes carry a mesh over (its material may not exist). + copied = "content_type scale refpos refquat inertia maxhullvert smoothnormal uservert userface".split() + meshes = [[m.mesh(k).name for k in range(m.nmesh)] for m in scenes] # each scene's meshes' names in the model + verts = [[m.mesh_vert[a : a + n] for a, n in zip(m.mesh_vertadr, m.mesh_vertnum)] for m in scenes] + for i, s in enumerate(specs): + for k, name in enumerate(meshes[i]): + if i == t or name in meshes[t] and np.array_equal(verts[i][k], verts[t][meshes[t].index(name)]): + continue + mesh = s.mesh(name) + meshes[i][k] = f"{name}__{i}" + file = str(Path(s.modelfiledir, s.meshdir, mesh.file).resolve()) if mesh.file else "" + spec.add_mesh(name=meshes[i][k], file=file, **{f: getattr(mesh, f) for f in copied}) + spec.worldbody.add_geom( + type=mujoco.mjtGeom.mjGEOM_MESH, meshname=meshes[i][k], contype=unused, conaffinity=0, group=5 + ) + model = spec.compile() + + # Each scene's values: the per-world geom, pair, body, site fields but `geom_matid` (materials do not join). + fields = [ + f for f in sorted(_BATCHED) if f.split("_")[0] in ("geom", "pair", "body", "site") and f != "geom_matid" + ] + values = {f: np.repeat(getattr(model, f)[None], len(scenes), 0) for f in fields + ["dof_invweight0", "qpos0"]} + geoms = {model.geom(k).name: k for k in range(model.ngeom)} + pairs = {(g1, g2): p for p, (g1, g2) in enumerate(zip(model.pair_geom1, model.pair_geom2))} + for i, m in enumerate( + scenes + ): # `geom_` and `pair_` values at its geoms' (by name, else place) and pairs' places + place = model.body_geomadr[m.geom_bodyid] + np.arange(m.ngeom) - m.body_geomadr[m.geom_bodyid] + g = np.array([geoms[m.geom(k).name] if m.geom(k).name else place[k] for k in range(m.ngeom)], int) + p = np.array([pairs[g[a], g[b]] for a, b in zip(m.pair_geom1, m.pair_geom2)], int) + for f in values: + index = g if f.startswith("geom_") else p if f.startswith("pair_") else slice(None) + values[f][i][index] = getattr(m, f) + mesh = m.geom_type == mujoco.mjtGeom.mjGEOM_MESH + values["geom_dataid"][i][g[mesh]] = [model.mesh(meshes[i][k]).id for k in m.geom_dataid[mesh]] + lacks = np.setdiff1d(np.arange(model.ngeom), g) + values["geom_margin"][i][lacks] = _NO_CONTACT_MARGIN + values["geom_gap"][i][lacks] = 0 + lacks = np.setdiff1d(np.arange(model.npair), p) + values["pair_margin"][i][lacks] = _NO_CONTACT_MARGIN + values["pair_gap"][i][lacks] = 0 + return model, scenes, values diff --git a/src/robokit/sim/newton.py b/src/robokit/sim/newton.py new file mode 100644 index 0000000..9258030 --- /dev/null +++ b/src/robokit/sim/newton.py @@ -0,0 +1,253 @@ +# pyright: reportArgumentType=false +# pyright: reportGeneralTypeIssues=false +# pyright: reportIndexIssue=false +# pyright: reportMissingImports=false +# pyright: reportAttributeAccessIssue=false +"""`NewtonSim`: a MuJoCo model's worlds on Newton's Featherstone solver, read and written as MuJoCo's data fields.""" + +import xml.etree.ElementTree as ET +from types import SimpleNamespace +from typing import Optional + +import mujoco +import newton +import numpy as np +import warp as wp + +from robokit.sim.mjwarp import _reset_kernel + + +# --- kernels --------------------------------------------------------------- +@wp.kernel +def _compute_derived_kernel( + body_q: wp.array2d(dtype=wp.transform), + body_qd: wp.array2d(dtype=wp.spatial_vector), + link: wp.array(dtype=int), + kind: wp.array(dtype=int), + body: wp.array(dtype=int), + adr: wp.array(dtype=int), + subtree_mass: wp.array2d(dtype=float), + limits: wp.array2d(dtype=float), + gain: wp.array(dtype=float), + dof: wp.array(dtype=int), + ctrl: wp.array2d(dtype=float), + dt: float, + xpos: wp.array2d(dtype=wp.vec3), + xmat: wp.array2d(dtype=wp.mat33), + sensordata: wp.array2d(dtype=float), + joint_f: wp.array2d(dtype=float), + time: wp.array(dtype=float), +): + """Per world: body poses (body `i` is Newton's `link[i]`), sensors, joint forces from `ctrl`, and `time` += `dt`.""" + w, i = wp.tid() # pyright: ignore[reportAssignmentType] + if i == 0: + time[w] = time[w] + dt + if i > 0 and i < xpos.shape[1]: + T_world_body = body_q[w, link[i]] + xpos[w, i] = wp.transform_get_translation(T_world_body) + xmat[w, i] = wp.quat_to_matrix(wp.transform_get_rotation(T_world_body)) + if i < ctrl.shape[1]: + joint_f[w, dof[i]] = gain[i] * wp.clamp(ctrl[w, i], limits[i, 0], limits[i, 1]) + if i < kind.shape[0]: + T_world_body = body_q[w, link[body[i]]] + value = wp.transform_get_translation(T_world_body) # framepos + if kind[i] == 1: # framezaxis + value = wp.quat_rotate(wp.transform_get_rotation(T_world_body), wp.vec3(0.0, 0.0, 1.0)) + if kind[i] == 2: # subtreelinvel: the subtree's mass-weighted centre-of-mass velocity + momentum, mass = wp.vec3(0.0), float(0.0) # pyright: ignore[reportCallIssue] + for b in range(1, subtree_mass.shape[1]): + momentum += subtree_mass[i, b] * wp.spatial_top(body_qd[w, link[b]]) + mass += subtree_mass[i, b] + value = momentum / mass # pyright: ignore[reportOperatorIssue] + for k in range(3): + sensordata[w, adr[i] + k] = value[k] + + +# --- simulator ------------------------------------------------------------- +_LINK_MASS = 1e-6 # kg: each nested link that carries a body's joint after its first + + +class NewtonSim: + """Step `nworld` copies of `model` on Newton's `SolverFeatherstone`, `substeps` steps per `step()`, as MuJoCo data. + + Args: + data: The state `reset()` restores (`qpos`, `qvel`, `ctrl`, `time`), else keyframe `key`'s, else the defaults. + contact_ke: Penalty contacts' stiffness. + contact_kd: Penalty contacts' damping. + contact_kf: Penalty contacts' friction stiffness. + limit_ke: Penalty joint limits' stiffness. + limit_kd: Penalty joint limits' damping. + + Example: + >>> # xdoctest: +REQUIRES(module:newton) + >>> model = mujoco.MjModel.from_xml_string( + ... '' + ... '' + ... '' + ... ) + >>> sim = NewtonSim(model, nworld=4, substeps=2) + >>> sim.step() # every world falls + >>> sim.data.qpos.shape, sim.data.xpos.shape, sim.data.substep_sensordata.shape + ((4, 2), (4, 2), (2, 4, 3)) + >>> sim.reset(wp.array(np.arange(4) < 2)) # the first two worlds back to the start + >>> (sim.data.qpos.numpy()[:, 0] < 0).tolist() + [False, False, True, True] + """ + + def __init__( + self, + model: mujoco.MjModel, + nworld: int, + data: Optional[mujoco.MjData] = None, + substeps: int = 1, + key: Optional[str] = None, + device=None, + contact_ke: float = 2e4, + contact_kd: float = 200.0, + contact_kf: float = 200.0, + limit_ke: float = 2e3, + limit_kd: float = 5.0, + ): + self._args = {k: v for k, v in locals().items() if k not in ("self", "nworld")} # for `resized` + m, sensor = model, mujoco.mjtSensor + kinds = {int(sensor.mjSENS_FRAMEPOS): 0, int(sensor.mjSENS_FRAMEZAXIS): 1, int(sensor.mjSENS_SUBTREELINVEL): 2} + frame = m.sensor_type != sensor.mjSENS_SUBTREELINVEL + unsupported = ~np.isin(m.sensor_type, list(kinds)) | frame & (m.sensor_objtype != mujoco.mjtObj.mjOBJ_XBODY) + actuators = np.stack([m.actuator_trntype, m.actuator_dyntype, m.actuator_gaintype, m.actuator_biastype]) + if np.any(m.jnt_type < 2) or np.any(actuators != 0) or np.any(unsupported | (m.sensor_refid >= 0)): + raise ValueError("NewtonSim supports slide/hinge joints, gain-only joint actuators and the listed sensors") + + # `model` as MJCF for Newton: each body's joints after its first on nested links. + s = lambda x: " ".join(map(str, np.ravel(x))) + root = ET.Element("mujoco") + ET.SubElement(root, "compiler", angle="radian") + asset, links = ET.SubElement(root, "asset"), [ET.SubElement(root, "worldbody")] # each body's innermost link + for k in range(m.nmesh): + vert = m.mesh_vert[m.mesh_vertadr[k] : m.mesh_vertadr[k] + m.mesh_vertnum[k]] + face = m.mesh_face[m.mesh_faceadr[k] : m.mesh_faceadr[k] + m.mesh_facenum[k]] + ET.SubElement(asset, "mesh", name=str(k), vertex=s(vert), face=s(face)) + for b in range(1, m.nbody): + link = ET.SubElement(links[m.body_parentid[b]], "body", pos=s(m.body_pos[b]), quat=s(m.body_quat[b])) + for j in range(m.body_jntadr[b], m.body_jntadr[b] + m.body_jntnum[b]): + if j > m.body_jntadr[b]: # a later joint: on a nested link + ET.SubElement(link, "inertial", pos="0 0 0", mass=str(_LINK_MASS), diaginertia=s([_LINK_MASS] * 3)) + link = ET.SubElement(link, "body") + dof, limit = m.jnt_dofadr[j], dict(range=s(m.jnt_range[j])) if m.jnt_limited[j] else {} + ET.SubElement( + link, "joint", type=("slide", "hinge")[m.jnt_type[j] - 2], pos=s(m.jnt_pos[j]), + axis=s(m.jnt_axis[j]), damping=str(m.dof_damping[dof]), armature=str(m.dof_armature[dof]), **limit, + ) # fmt: skip + ET.SubElement( + link, "inertial", pos=s(m.body_ipos[b]), quat=s(m.body_iquat[b]), mass=str(m.body_mass[b]), + diaginertia=s(m.body_inertia[b]), + ) # fmt: skip + links.append(link) + for g in range(m.ngeom): + mesh = dict(mesh=str(m.geom_dataid[g])) if m.geom_type[g] == mujoco.mjtGeom.mjGEOM_MESH else {} + ET.SubElement( + links[m.geom_bodyid[g]], "geom", type=mujoco.mjtGeom(m.geom_type[g]).name[7:].lower(), + size=s(m.geom_size[g]), pos=s(m.geom_pos[g]), quat=s(m.geom_quat[g]), friction=s(m.geom_friction[g]), + contype=str(m.geom_contype[g]), conaffinity=str(m.geom_conaffinity[g]), **mesh, + ) # fmt: skip + + # Newton's model of `nworld` copies, its collisions and its solver. + b = newton.ModelBuilder() + b.add_mjcf(ET.tostring(root, encoding="unicode")) + b.shape_material_ke[:] = [contact_ke] * len(b.shape_material_ke) + b.shape_material_kd[:] = [contact_kd] * len(b.shape_material_kd) + b.shape_material_kf[:] = [contact_kf] * len(b.shape_material_kf) + b.joint_limit_ke[:] = [limit_ke] * len(b.joint_limit_ke) + b.joint_limit_kd[:] = [limit_kd] * len(b.joint_limit_kd) + scene = newton.ModelBuilder() + scene.replicate(b, nworld) + self.mjm, self.nworld, self.substeps, self.device = m, nworld, substeps, wp.get_device(device) + self.stream = wp.get_stream(self.device) if self.device.is_cuda else None + newton_model = self.newton_model = scene.finalize(device=self.device) # `model`'s bodies, joints and geoms + state, control = self._state, self._control = newton_model.state(), newton_model.control() + self._pipeline = newton.CollisionPipeline(newton_model) + self._contacts = self._pipeline.contacts() + self._solver = newton.solvers.SolverFeatherstone(newton_model, angular_damping=0.0) + + # MuJoCo's data fields over Newton's state, `_compute_derived_kernel`'s arguments and `reset`'s initial rows. + ancestor = np.eye(m.nbody, dtype=bool) # ancestor[c, a]: body a is c or holds it + for c in range(1, m.nbody): + ancestor[c] |= ancestor[m.body_parentid[c]] + if data is None: + data = mujoco.MjData(m) + if key is not None: + mujoco.mj_resetDataKeyframe(m, data, m.key(key).id) + with wp.ScopedDevice(self.device): + limited = m.actuator_ctrllimited.astype(bool)[:, None] + d = self.data = SimpleNamespace( # as `mujoco.MjData`'s; `qpos`, `qvel`: Newton's joint state + time=wp.zeros(nworld, dtype=float), + qpos=state.joint_q.reshape((nworld, -1)), + qvel=state.joint_qd.reshape((nworld, -1)), + act=wp.zeros((nworld, 0), dtype=float), + qacc_warmstart=wp.zeros((nworld, m.nv), dtype=float), + ctrl=wp.zeros((nworld, m.nu), dtype=float), # clamped to `ctrlrange`, times gear and gain: joint forces + sensordata=wp.zeros((nworld, m.nsensordata), dtype=float), + xpos=wp.zeros((nworld, m.nbody), dtype=wp.vec3), + xmat=wp.array(np.tile(np.eye(3), (nworld, m.nbody, 1, 1)), dtype=wp.mat33), + nacon=wp.zeros(1, dtype=int), + contact=SimpleNamespace( + worldid=wp.zeros(0, dtype=int), + geom=wp.zeros(0, dtype=wp.vec2i), + dist=wp.zeros(0, dtype=float), + pos=wp.zeros(0, dtype=wp.vec3), + ), + ) + self.model = SimpleNamespace() # no MuJoCo fields + self.data.substep_sensordata = wp.zeros((substeps, nworld, m.nsensordata), dtype=float) + self._inputs = [ # of `_compute_derived_kernel`, before `dt` + state.body_q.reshape((nworld, -1)), + state.body_qd.reshape((nworld, -1)), + wp.array(np.arange(m.nbody) - 1 + np.cumsum(np.maximum(m.body_jntnum - 1, 0)), dtype=int), + wp.array([kinds[int(t)] for t in m.sensor_type], dtype=int), + wp.array(m.sensor_objid, dtype=int), + wp.array(m.sensor_adr, dtype=int), + wp.array(ancestor[:, m.sensor_objid].T * m.body_mass, dtype=float), + wp.array(np.where(limited, m.actuator_ctrlrange, [-np.inf, np.inf]), dtype=float), + wp.array(m.actuator_gear[:, 0] * m.actuator_gainprm[:, 0], dtype=float), + wp.array(m.jnt_dofadr[m.actuator_trnid[:, 0]], dtype=int), + d.ctrl, + ] + self._outputs = [d.xpos, d.xmat, d.sensordata, control.joint_f.reshape((nworld, -1)), d.time] + self._initial = [ # (world-major data array, each world's initial row) pairs for `reset` + (getattr(d, f).reshape((nworld, -1)), wp.array(np.tile(getattr(data, f), (nworld, 1)), dtype=float)) + for f in ("qpos", "qvel", "ctrl", "time") + ] + self._dim = (nworld, max(m.nbody, m.nsensor, m.nu)) + self.step() # allocates the solver's buffers before any graph capture + self.reset(wp.full(nworld, 1, dtype=int, device=self.device)) + + def resized(self, nworld: int) -> "NewtonSim": + """A new simulator of this one's model and settings with `nworld` worlds.""" + return NewtonSim(nworld=nworld, **self._args) + + def step(self): + """Advance `substeps` steps from `qpos`, `qvel` as they are; derived fields lag a substep, as MuJoCo's.""" + dt, s = self.mjm.opt.timestep, self._state + with wp.ScopedDevice(self.device): + newton.eval_fk(self.newton_model, s.joint_q, s.joint_qd, s) # the body poses of `qpos`, also if written + for k in range(self.substeps): # `substep_sensordata[k]`: substep `k`'s start + wp.launch(_compute_derived_kernel, dim=self._dim, inputs=[*self._inputs, dt], outputs=self._outputs) + wp.copy(self.data.substep_sensordata, self.data.sensordata, dest_offset=k * self.data.sensordata.size) + self._pipeline.collide(s, self._contacts) + self._solver.step(s, s, self._control, self._contacts, dt) + + def forward(self): + """Recompute `xpos`, `xmat`, `sensordata` (body framepos, framezaxis; subtreelinvel) from `qpos` and `qvel`.""" + s = self._state + with wp.ScopedDevice(self.device): + newton.eval_fk(self.newton_model, s.joint_q, s.joint_qd, s) + wp.launch(_compute_derived_kernel, dim=self._dim, inputs=[*self._inputs, 0.0], outputs=self._outputs) + + def reset(self, mask: wp.array): + """Reset the worlds where `mask` (nworld,), bool or int, is set, then run `forward()`; no host syncs.""" + with wp.ScopedDevice(self.device): + for out, value in self._initial: + wp.launch(_reset_kernel, dim=out.shape, inputs=[mask, value], outputs=[out]) + self.forward() + + +__all__ = ["NewtonSim"] diff --git a/src/robokit/terms/__init__.py b/src/robokit/terms/__init__.py index 7a87111..d9336a1 100644 --- a/src/robokit/terms/__init__.py +++ b/src/robokit/terms/__init__.py @@ -21,9 +21,11 @@ ContactTask, ControlTask, GraspTask, + PinchTask, SensorTask, SimContext, StateTask, + SupportTask, ) from robokit.terms.sparse.trajectory_collision_task import TrajectoryCollisionTask from robokit.terms.sparse.trajectory_limit_task import TrajectoryLimitTask @@ -77,6 +79,8 @@ "ContactTask", "ControlTask", "GraspTask", + "PinchTask", "SensorTask", "StateTask", + "SupportTask", ] diff --git a/src/robokit/terms/dense/__init__.py b/src/robokit/terms/dense/__init__.py index c4677f1..83add52 100644 --- a/src/robokit/terms/dense/__init__.py +++ b/src/robokit/terms/dense/__init__.py @@ -6,6 +6,7 @@ from robokit.terms.dense.pixel_task import PixelTask from robokit.terms.dense.position_limit import PositionLimit from robokit.terms.dense.position_task import PositionTask +from robokit.terms.dense.relative_frame_task import RelativeFrameTask from robokit.terms.dense.rotation_task import AxisLimitTask, RotationTask from robokit.terms.dense.scene_collision_task import SceneCollisionTask from robokit.terms.dense.scene_distance_task import SceneDistanceTask @@ -24,6 +25,7 @@ "PositionLimit", "PixelTask", "PositionTask", + "RelativeFrameTask", "ConfigurationTask", "RotationTask", "SceneCollisionTask", diff --git a/src/robokit/terms/dense/frame_vector_task.py b/src/robokit/terms/dense/frame_vector_task.py index 8f938a0..995180e 100644 --- a/src/robokit/terms/dense/frame_vector_task.py +++ b/src/robokit/terms/dense/frame_vector_task.py @@ -67,10 +67,8 @@ class FrameVectorTask(RobotTask, ResidualTask): - ``direction_only=True`` with ``direction_metric="cosine"``: ``1 - dot(normalized_robot, normalized_target)``. Named weights pick their rows when the task is built: - - A target name tracks that target's row of `targets`, ordered by `target_names`, from the world origin to - its link in `target_links`. - - `(origin link, task link, origin target, task target)` reads the pair row `origin * len(target_names) + task` - of a pair buffer. + - A target name tracks that target's row of `targets`, ordered by `target_names`, from the world origin to its link in `target_links`. + - `(origin link, task link, origin target, task target)` reads the pair row `origin * len(target_names) + task` of a pair buffer. """ num_pairs = 1 # a template counts as active until `resolve` sizes it diff --git a/src/robokit/terms/dense/pixel_task.py b/src/robokit/terms/dense/pixel_task.py index 0c02695..fe0c64e 100644 --- a/src/robokit/terms/dense/pixel_task.py +++ b/src/robokit/terms/dense/pixel_task.py @@ -16,12 +16,7 @@ class PixelTask(RobotTask, ResidualTask): - """Match the image pixels of link origins seen by a fixed pinhole camera (`intrinsic`, `T_camera_world`). - - The residual is `weight * (uv - project_points(transform_points(p_world_link, T_camera_world), intrinsic))` - in pixels (OpenCV camera axes; identity `T_camera_world` by default); a point at or behind the camera is - projected at depth 1e-3 m. `uv` is `(batch, frames, 2)` and is shared by the candidates; `set_target` refills - it in place, so a built solver sees new pixels. `frame_index` may be `IKContext.TARGET_LINKS`. + """Match the image pixels of link origins seen by a fixed pinhole camera (`intrinsic`, `T_camera_world`); the residual is `weight * (uv - project_points(transform_points(p_world_link, T_camera_world), intrinsic))` in pixels (OpenCV camera axes; identity `T_camera_world` by default); a point at or behind the camera is projected at depth 1e-3 m; `uv` is `(batch, frames, 2)` and is shared by the candidates; `set_target` refills it in place, so a built solver sees new pixels; `frame_index` may be `IKContext.TARGET_LINKS`. Example: >>> from robot_descriptions.loaders.yourdfpy import load_robot_description diff --git a/src/robokit/terms/dense/relative_frame_task.py b/src/robokit/terms/dense/relative_frame_task.py new file mode 100644 index 0000000..fec5354 --- /dev/null +++ b/src/robokit/terms/dense/relative_frame_task.py @@ -0,0 +1,103 @@ +# pyright: reportArgumentType=false, reportIndexIssue=false, reportGeneralTypeIssues=false, reportOperatorIssue=false +from typing import Optional, Sequence, Tuple + +import warp as wp + +from robokit.lie.se3_kernels import se3_adjoint_func, se3_jlog_func, se3_log_map_func +from robokit.lie.se3_kernels import se3_inverse_func as inv +from robokit.lie.se3_kernels import se3_multiply_func as mul +from robokit.opt.var_values import VarValues +from robokit.robo.robot import Robot +from robokit.terms.robot_task import RobotTask +from robokit.terms.task import ResidualTask +from robokit.utils.warp_utils import wp_vec6, wp_vec7 + + +@wp.kernel +def _relative_frame_kernel( + S_world: wp.array3d(dtype=wp.float32), # (poses, 6, joints), read with the Jacobian + T_world_link: wp.array2d(dtype=wp_vec7), # (poses, links), `reference_frames.shape[0]` poses per trajectory + link_pairs: wp.array2d(dtype=wp.int32), + reference_frames: wp.array2d(dtype=wp.int32), # (frames, pairs): each pair's reference frame, -1 off + ancestor_mask: wp.array2d(dtype=wp.bool), + joints_to_actuated: wp.array2d(dtype=wp.float32), + weight: wp.vec2, + offsets: wp.vec3i, # Jacobian (1) or residual (0), row offset, column offset + out: wp.array3d(dtype=wp.float32), # (poses, rows, columns), one column for residuals +): + pose, pair, col = wp.tid() # pyright: ignore[reportAssignmentType] + frames, a, b = reference_frames.shape[0], link_pairs[pair, 0], link_pairs[pair, 1] + reference = reference_frames[pose % frames, pair] + start = wp.where(reference < 0, pose, pose - pose % frames + reference) # off: its own pose, a zero residual + T_a_bref = mul(inv(T_world_link[start, a]), T_world_link[start, b]) # b at the reference frame, in a's frame + error = mul(inv(T_a_bref), mul(inv(T_world_link[pose, a]), T_world_link[pose, b])) # T_bref_b + value = se3_log_map_func(error, wp.float32(1e-4)) + if offsets[0] != 0: # b's spatial velocity relative to a's, in b's frame: d log(error) = jlog Ad(T_b_world) dS + spatial = wp_vec6(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + for joint in range(S_world.shape[2]): + sign = wp.where(ancestor_mask[b, joint], 1.0, 0.0) - wp.where(ancestor_mask[a, joint], 1.0, 0.0) + for row in range(6): + spatial[row] += sign * joints_to_actuated[joint, col] * S_world[pose, row, joint] + value = se3_jlog_func(error, wp.float32(1e-4)) * (se3_adjoint_func(inv(T_world_link[pose, b])) * spatial) + for row in range(6): + on = wp.where(reference < 0, 0.0, weight[row // 3]) + out[pose, offsets[1] + 6 * pair + row, wp.where(offsets[0] != 0, offsets[2] + col, 0)] = on * value[row] + + +class RelativeFrameTask(RobotTask, ResidualTask): + """Hold each link pair's relative pose `T_a_b` at its value on a reference frame of the same trajectory: wrapped + in `TrajectoryTask`, frame `t` reads pair `p`'s reference frame `reference_frames[t, p]`; -1 leaves its rows zero, + else the residual is `log(T_a_b(reference)^-1 T_a_b(t))`, with the reference held fixed. + + Example: + >>> import numpy as np + >>> from robot_descriptions.loaders.yourdfpy import load_robot_description + >>> from robokit.terms.trajectory_task import TrajectoryTask + >>> robot = Robot.load(load_robot_description("panda_description")) + >>> reference = wp.array([[0], [0]], dtype=wp.int32, device="cpu") # both frames hold frame 0's pose + >>> task = TrajectoryTask(RelativeFrameTask(robot, [(0, robot.link_names.index("panda_hand"))], reference), 2) + >>> q = wp.array(np.stack([robot.spec.zero_q, robot.spec.zero_q + 0.1])[None], dtype=wp.float32, device="cpu") + >>> residual = task.compute_weighted_residual(VarValues({task.var_key: robot.state(q=q)})).numpy() + >>> bool(np.allclose(residual[0, :6], 0.0)), bool(np.linalg.norm(residual[0, 6:]) > 0.1) + (True, True) + """ + + def __init__( + self, + robot: Robot, + link_pairs: Sequence[Tuple[int, int]], + reference_frames: wp.array, # (frames, pairs) int32, which the caller rewrites + position_weight: float = 1.0, + orientation_weight: float = 1.0, + ): + self.robot, self.reference_frames, self.device = robot, reference_frames, reference_frames.device + self.weight = (position_weight, orientation_weight) + self.link_pairs = wp.array(link_pairs, dtype=wp.int32, device=self.device) # which the caller may rewrite + + @property + def residual_dim(self) -> int: + return 6 * self.link_pairs.shape[0] + + def compute_weighted_residual( + self, var_values: VarValues, out_residual: Optional[wp.array] = None, row_offset: int = 0 + ) -> wp.array: + return self.compute_weighted_jacobian_analytic(var_values, out_residual, row_offset, jacobian=False) + + def compute_weighted_jacobian_analytic( + self, var_values: VarValues, out_jacobian: Optional[wp.array] = None, row_offset: int = 0, jacobian: bool = True + ) -> wp.array: + var, rows, out = var_values.get(self.var_key), self.residual_dim, out_jacobian + self.precompute(var_values, need_gradient=jacobian) + if out is None: + shape = (var.batch_size, rows, var.tangent_dim) if jacobian else (var.batch_size, rows) + out, row_offset = wp.zeros(shape, dtype=wp.float32, device=self.device), 0 + spec, base = var.spec_tensors, var_values.tangent_offset(self.var_key) + (6 if var.has_floating_base else 0) + wp.launch( + _relative_frame_kernel, + dim=(var.batch_size, self.link_pairs.shape[0], spec.joints_to_actuated_mapping.shape[1] if jacobian else 1), + inputs=[var.S_world if jacobian else None, var.T_world_link, self.link_pairs, self.reference_frames] + + [spec.link_ancestor_joints_mask, spec.joints_to_actuated_mapping, wp.vec2(*self.weight)] + + [wp.vec3i(int(jacobian), row_offset, base), out if jacobian else out.reshape((*out.shape, 1))], + device=self.device, + ) + return out diff --git a/src/robokit/terms/dense/self_collision_task.py b/src/robokit/terms/dense/self_collision_task.py index eaf11d6..e35beca 100644 --- a/src/robokit/terms/dense/self_collision_task.py +++ b/src/robokit/terms/dense/self_collision_task.py @@ -36,8 +36,7 @@ def compute_active_collision_pairs( Args: spec: Robot specification. ignored_link_pairs: Explicit link pairs to skip instead of adjacency filtering. - geom_link_indices: Link index of each geometry. Defaults to the collision - spheres' link indices; pass `arange(num_links)` for one-capsule-per-link. + geom_link_indices: Link index of each geometry. Defaults to the collision spheres' link indices; pass `arange(num_links)` for one-capsule-per-link. Returns: Geometry index pairs, shape `[num_pairs, 2]`. diff --git a/src/robokit/terms/simulation/__init__.py b/src/robokit/terms/simulation/__init__.py index 8ba05b7..ea4d3a2 100644 --- a/src/robokit/terms/simulation/__init__.py +++ b/src/robokit/terms/simulation/__init__.py @@ -4,9 +4,11 @@ from robokit.terms.simulation.contact_task import ContactTask from robokit.terms.simulation.control_task import ControlTask from robokit.terms.simulation.grasp_task import GraspTask +from robokit.terms.simulation.pinch_task import PinchTask from robokit.terms.simulation.sensor_task import SensorTask from robokit.terms.simulation.sim_context import SimContext from robokit.terms.simulation.state_task import StateTask +from robokit.terms.simulation.support_task import SupportTask __all__ = [ @@ -14,7 +16,9 @@ "ContactTask", "ControlTask", "GraspTask", + "PinchTask", "SensorTask", "SimContext", "StateTask", + "SupportTask", ] diff --git a/src/robokit/terms/simulation/align_task.py b/src/robokit/terms/simulation/align_task.py index 9113379..fdf0cb9 100644 --- a/src/robokit/terms/simulation/align_task.py +++ b/src/robokit/terms/simulation/align_task.py @@ -12,12 +12,12 @@ import warp as wp from robokit.opt.var_values import VarValues -from robokit.terms.simulation.sim_context import SimContext, _instanced -from robokit.terms.task import Context, Task +from robokit.terms.simulation.sim_context import SimContext, SimResidualTask, _get_instance_step_func, _instanced +from robokit.terms.task import Context @wp.kernel -def _compute_align_cost_kernel( +def _compute_align_kernel( sensordata: wp.array2d(dtype=float), target_ref: wp.array3d(dtype=float), origin: int, @@ -27,11 +27,15 @@ def _compute_align_cost_kernel( freeze_reference: bool, clock: wp.array(dtype=int), worlds: int, - out: wp.array(dtype=float), + world_steps: wp.array(dtype=wp.vec2i), + row_offset: int, + out: wp.array2d(dtype=float), + out_cost: wp.array(dtype=float), ): w = wp.tid() - b = w // worlds - r = wp.min(clock[0] + wp.where(freeze_reference, 0, clock[1]), target_ref.shape[1] - 1) + bt = _get_instance_step_func(w, worlds, clock, world_steps) + b = bt[0] + r = wp.min(clock[0] + wp.where(freeze_reference, 0, bt[1]), target_ref.shape[1] - 1) uv, uu, vv = float(0.0), float(0.0), float(0.0) for j in range(components.shape[0]): i = components[j] @@ -40,11 +44,16 @@ def _compute_align_cost_kernel( uv += u * v uu += u * u vv += v * v + cost = float(0.0) if uu >= 1.0e-12 and vv >= 1.0e-12: - out[w] += weight * (1.0 + uv / wp.sqrt(uu * vv)) + cost = weight * (1.0 + uv / wp.sqrt(uu * vv)) + if out_cost.shape[0] > 0: + out_cost[w] += cost + else: + out[w, row_offset] = wp.sqrt(2.0 * wp.max(cost, 0.0)) -class AlignTask(Task): +class AlignTask(SimResidualTask): """Per step, `weight * (1 + u.v / (|u||v|))` with `u = sensor - origin` and `v = target_ref[k] - origin`. Example: @@ -68,11 +77,10 @@ def __init__( target_ref: np.ndarray, weight: float, components: Sequence[int] = (0, 1), - terminal_scale: Optional[float] = None, freeze_reference: bool = False, ): self.origin, self.sensor, self.target_ref, self.weight = origin, sensor, target_ref, weight - self.components, self.terminal_scale, self.freeze_reference = components, terminal_scale, freeze_reference + self.components, self.freeze_reference = components, freeze_reference self.sensordata, self.sensors, self.clock = SimContext.SENSORDATA, SimContext.SENSORS, SimContext.CLOCK self.instances, self.worlds = SimContext.NUM_INSTANCES, SimContext.WORLDS_PER_INSTANCE @@ -83,22 +91,16 @@ def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any self.origin, self.sensor = int(table[self.origin]), int(table[self.sensor]) self.target_ref = _instanced(self.target_ref, 2, self.instances, device) self.components = wp.array(np.asarray(self.components, np.int32), dtype=int, device=device) + self._residual_dim = 1 # sqrt(2 cost) + self._resolve_world_steps(context, device) - def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): + def _launch(self, out_residual: wp.array, row_offset: int, out_cost: wp.array): + inputs = [self.sensordata, self.target_ref, self.origin, self.sensor, self.components, self.weight] + inputs += [self.freeze_reference, self.clock, self.worlds, self.world_steps, row_offset] wp.launch( - _compute_align_cost_kernel, + _compute_align_kernel, dim=self.sensordata.shape[0], - inputs=[ - self.sensordata, - self.target_ref, - self.origin, - self.sensor, - self.components, - self.weight, - self.freeze_reference, - self.clock, - self.worlds, - ], - outputs=[out_cost], - device=out_cost.device, + inputs=inputs, + outputs=[out_residual, out_cost], + device=self.sensordata.device, ) diff --git a/src/robokit/terms/simulation/contact_task.py b/src/robokit/terms/simulation/contact_task.py index a614708..82f3f0e 100644 --- a/src/robokit/terms/simulation/contact_task.py +++ b/src/robokit/terms/simulation/contact_task.py @@ -32,18 +32,23 @@ def _compute_contact_cost_kernel( weight: float, penalty: float, margin: float, + box: wp.vec2, + height: wp.vec2, out: wp.array(dtype=float), ): c = wp.tid() if c >= count[0]: return p, d, k, b = pos[c], dist[c], clock[0] + clock[1], world[c] // worlds - r, ra = wp.min(k, radius.shape[1] - 1), wp.min(k, allowed.shape[1] - 1) + r, rt, ra = wp.min(k, radius.shape[1] - 1), wp.min(k, target.shape[1] - 1), wp.min(k, allowed.shape[1] - 1) for side in range(2): i = slot[wp.max(geom[c][side], 0)] if geom[c][side] >= 0 and i >= 0: - dx, dy = p[0] - target[b, r, i, 0], p[1] - target[b, r, i, 1] + dx, dy = p[0] - target[b, rt, i, 0], p[1] - target[b, rt, i, 1] inside = dx * dx + dy * dy <= radius[b, r, i] * radius[b, r, i] + if box[0] > 0.0: + inside = wp.abs(dx) <= box[0] and wp.abs(dy) <= box[1] + inside = inside and p[2] >= height[0] and p[2] <= height[1] total = wp.where(inside, -weight * wp.clamp(1.0 - d, 0.0, 1.0), 0.0) free = bool(False) for s in range(allowed.shape[3]): @@ -58,9 +63,12 @@ def _compute_contact_cost_kernel( class ContactTask(Task): """Reward `geoms`' contacts inside their target discs; penalize touches outside every `allowed` disc. + `box`, half widths (x, y), replaces each target disc with that axis-aligned box around the target; `height`, + (low, high), rewards only contacts at those heights. + Example: - >>> context = { # one contact of geom 1 at (0, 0), 0.25 apart - ... SimContext.CLOCK: wp.array([0, 0, 1], dtype=int, device="cpu"), + >>> context = { # one contact of geom 1 at (0, 0), 0.25 apart, at sim step 1 + ... SimContext.CLOCK: wp.array([1, 0, 1], dtype=int, device="cpu"), ... SimContext.NUM_INSTANCES: 1, ... SimContext.WORLDS_PER_INSTANCE: 1, ... SimContext.GEOMS: ["floor", "foot"], @@ -71,15 +79,17 @@ class ContactTask(Task): ... } >>> far, allowed = np.ones((1, 1, 2)), np.array([[[[0.0, 0.0, 0.1]]]]) # a disc (x, y, r) around the foot >>> terms = [ - ... ContactTask(["foot"], np.zeros((1, 1, 2)), np.full((1, 1), 0.1), weight=2.0), + ... ContactTask(["foot"], np.zeros((1, 1, 2)), np.full((1, 2, 1), 0.1), weight=2.0), # radius over time ... ContactTask(["foot"], far, np.zeros((1, 1)), penalty=0.5, margin=0.3), ... ContactTask(["foot"], far, np.zeros((1, 1)), allowed, penalty=0.5, margin=0.3), + ... ContactTask(["foot"], far, np.zeros((1, 1)), weight=2.0, box=(1.0, 1.0)), # (0, 0) is in the box + ... ContactTask(["foot"], far, np.zeros((1, 1)), weight=2.0, box=(1.0, 1.0), height=(0.1, 1.0)), # too low ... ] - >>> out = wp.zeros(3, dtype=float, device="cpu") + >>> out = wp.zeros(5, dtype=float, device="cpu") >>> for i, term in enumerate(terms): ... term.resolve(None, context) ... term.compute_weighted_cost(None, out_cost=out[i : i + 1]) - >>> assert np.allclose(out.numpy(), [-2.0 * 0.75, 0.5, 0.0]) + >>> assert np.allclose(out.numpy(), [-2.0 * 0.75, 0.5, 0.0, -2.0 * 0.75, 0.0]) """ def __init__( @@ -91,10 +101,12 @@ def __init__( weight: float = 1.0, penalty: float = 0.0, margin: float = 0.0, - terminal_scale: Optional[float] = None, + box: Optional[Sequence[float]] = None, + height: Optional[Sequence[float]] = None, ): self.geom_names, self.target, self.radius, self.allowed = list(geoms), target, radius, allowed - self.weight, self.penalty, self.margin, self.terminal_scale = weight, penalty, margin, terminal_scale + self.box, self.height = wp.vec2(*(box or (0.0, 0.0))), wp.vec2(*(height or (-1e9, 1e9))) + self.weight, self.penalty, self.margin = weight, penalty, margin self.contact_data, self.geoms, self.clock = SimContext.CONTACTS, SimContext.GEOMS, SimContext.CLOCK self.instances, self.worlds = SimContext.NUM_INSTANCES, SimContext.WORLDS_PER_INSTANCE @@ -111,12 +123,12 @@ def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any self.allowed = _instanced(allowed, 4, n, device, wp.vec3) def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): - count, world, geom, dist, pos = self.contact_data + count, world, geom, dist, pos = self.contact_data[:5] wp.launch( _compute_contact_cost_kernel, dim=world.shape[0], inputs=[count, world, geom, dist, pos, self.clock, self.worlds, self.slot, self.target, self.radius] - + [self.allowed, self.weight, self.penalty, self.margin], + + [self.allowed, self.weight, self.penalty, self.margin, self.box, self.height], outputs=[out_cost], device=out_cost.device, ) diff --git a/src/robokit/terms/simulation/control_task.py b/src/robokit/terms/simulation/control_task.py index b1dcc45..d8c10c9 100644 --- a/src/robokit/terms/simulation/control_task.py +++ b/src/robokit/terms/simulation/control_task.py @@ -12,30 +12,42 @@ import warp as wp from robokit.opt.var_values import VarValues -from robokit.terms.simulation.sim_context import SimContext, _instanced -from robokit.terms.task import Context, Task +from robokit.terms.simulation.sim_context import SimContext, SimResidualTask, _get_instance_step_func, _instanced +from robokit.terms.task import Context @wp.kernel -def _compute_control_cost_kernel( +def _compute_control_kernel( ctrl: wp.array2d(dtype=float), ctrl_ref: wp.array3d(dtype=float), weight: wp.array(dtype=float), norm: bool, clock: wp.array(dtype=int), worlds: int, - out: wp.array(dtype=float), + world_steps: wp.array(dtype=wp.vec2i), + row_offset: int, + out: wp.array2d(dtype=float), + out_cost: wp.array(dtype=float), ): + """`sqrt(2 weight) (ctrl - ctrl_ref[k])` per control, or with `norm` one `sqrt(2 cost)`; or the cost, if wanted.""" w = wp.tid() - r = wp.min(clock[0] + clock[1], ctrl_ref.shape[1] - 1) + bt = _get_instance_step_func(w, worlds, clock, world_steps) + r = wp.min(clock[0] + bt[1], ctrl_ref.shape[1] - 1) + cost_only = out_cost.shape[0] > 0 total = float(0.0) for u in range(ctrl.shape[1]): - e = ctrl[w, u] - ctrl_ref[w // worlds, r, u] + e = ctrl[w, u] - ctrl_ref[bt[0], r, u] total += wp.where(norm, weight[u] * weight[u], weight[u]) * e * e - out[w] += wp.where(norm, wp.sqrt(total), total) + if not norm and not cost_only: + out[w, row_offset + u] = wp.sqrt(2.0 * weight[u]) * e + value = wp.where(norm, wp.sqrt(total), total) + if cost_only: + out_cost[w] += value + elif norm: + out[w, row_offset] = wp.sqrt(2.0 * value) -class ControlTask(Task): +class ControlTask(SimResidualTask): """Per step, `sum(weight * (ctrl - ctrl_ref[k])**2)`, or with `norm` its unsquared norm; `ctrl_ref` defaults to 0. Example: @@ -58,11 +70,8 @@ def __init__( weight: Union[float, Sequence[float]], ctrl_ref: Optional[np.ndarray] = None, norm: bool = False, - terminal_scale: Optional[float] = None, - running_scale: float = 1.0, ): self.weight, self.ctrl_ref, self.norm = weight, ctrl_ref, norm - self.terminal_scale, self.running_scale = terminal_scale, running_scale self.ctrl, self.clock = SimContext.CTRL, SimContext.CLOCK self.instances, self.worlds = SimContext.NUM_INSTANCES, SimContext.WORLDS_PER_INSTANCE @@ -73,13 +82,15 @@ def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any self.weight = wp.array(np.broadcast_to(self.weight, nu).astype(np.float32), dtype=float, device=device) ctrl_ref = np.zeros((1, nu)) if self.ctrl_ref is None else self.ctrl_ref self.ctrl_ref = _instanced(ctrl_ref, 2, self.instances, device) + self._residual_dim = 1 if self.norm else nu + self._resolve_world_steps(context, device) - def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): - inputs = [self.ctrl, self.ctrl_ref, self.weight, self.norm, self.clock, self.worlds] + def _launch(self, out_residual: wp.array, row_offset: int, out_cost: wp.array): + inputs = [self.ctrl, self.ctrl_ref, self.weight, self.norm, self.clock, self.worlds, self.world_steps] wp.launch( - _compute_control_cost_kernel, + _compute_control_kernel, dim=self.ctrl.shape[0], - inputs=inputs, - outputs=[out_cost], - device=out_cost.device, + inputs=[*inputs, row_offset], + outputs=[out_residual, out_cost], + device=self.ctrl.device, ) diff --git a/src/robokit/terms/simulation/grasp_task.py b/src/robokit/terms/simulation/grasp_task.py index 5bb145c..c6d77f8 100644 --- a/src/robokit/terms/simulation/grasp_task.py +++ b/src/robokit/terms/simulation/grasp_task.py @@ -12,35 +12,43 @@ import warp as wp from robokit.opt.var_values import VarValues -from robokit.terms.simulation.sim_context import SimContext, _instanced -from robokit.terms.task import Context, Task +from robokit.terms.simulation.sim_context import SimContext, SimResidualTask, _get_instance_step_func, _instanced +from robokit.terms.task import Context @wp.kernel -def _compute_grasp_cost_kernel( +def _compute_grasp_kernel( body_position: wp.array2d(dtype=wp.vec3), body_rotation: wp.array2d(dtype=wp.mat33), clock: wp.array(dtype=int), worlds: int, + world_steps: wp.array(dtype=wp.vec2i), gripper: int, obj: int, offset: wp.array2d(dtype=wp.vec3), weight: wp.array2d(dtype=float), tolerance: wp.array2d(dtype=float), object_frame: bool, - out: wp.array(dtype=float), + row_offset: int, + out: wp.array2d(dtype=float), + out_cost: wp.array(dtype=float), ): w = wp.tid() - b = w // worlds - r = wp.min(clock[0] + clock[1] + 1, weight.shape[1] - 1) + bt = _get_instance_step_func(w, worlds, clock, world_steps) + b = bt[0] + r = wp.min(clock[0] + bt[1] + 1, weight.shape[1] - 1) relative = offset[b, r] if object_frame: relative = body_rotation[w, obj] @ relative distance = wp.length(body_position[w, gripper] - (body_position[w, obj] + relative)) - out[w] += weight[b, r] * (distance - wp.min(distance, tolerance[b, r])) + cost = weight[b, r] * (distance - wp.min(distance, tolerance[b, r])) + if out_cost.shape[0] > 0: + out_cost[w] += cost + else: + out[w, row_offset] = wp.sqrt(2.0 * wp.max(cost, 0.0)) -class GraspTask(Task): +class GraspTask(SimResidualTask): """Per step, `weight[k]` times the gripper's distance to body `obj` plus `offset[k]`, less `tolerance`, at least 0. Example: @@ -89,23 +97,16 @@ def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any tolerance = np.broadcast_to(self.tolerance, np.shape(self.weight)) self.offset = _instanced(self.offset, 2, n, device, wp.vec3) self.weight, self.tolerance = _instanced(self.weight, 1, n, device), _instanced(tolerance, 1, n, device) + self._residual_dim = 1 # sqrt(2 cost) + self._resolve_world_steps(context, device) - def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): + def _launch(self, out_residual: wp.array, row_offset: int, out_cost: wp.array): + inputs = [self.body_position, self.body_rotation, self.clock, self.worlds, self.world_steps, self.gripper] + inputs += [self.obj, self.offset, self.weight, self.tolerance, self.object_frame, row_offset] wp.launch( - _compute_grasp_cost_kernel, + _compute_grasp_kernel, dim=self.body_position.shape[0], - inputs=[ - self.body_position, - self.body_rotation, - self.clock, - self.worlds, - self.gripper, - self.obj, - self.offset, - self.weight, - self.tolerance, - self.object_frame, - ], - outputs=[out_cost], - device=out_cost.device, + inputs=inputs, + outputs=[out_residual, out_cost], + device=self.body_position.device, ) diff --git a/src/robokit/terms/simulation/pinch_task.py b/src/robokit/terms/simulation/pinch_task.py new file mode 100644 index 0000000..264c2c8 --- /dev/null +++ b/src/robokit/terms/simulation/pinch_task.py @@ -0,0 +1,130 @@ +# pyright: reportGeneralTypeIssues=false +# pyright: reportArgumentType=false +# pyright: reportIndexIssue=false +# pyright: reportAttributeAccessIssue=false +# pyright: reportCallIssue=false +# pyright: reportOperatorIssue=false +"""Score two-finger pinches: opposed contact normals and an aligned gripper, as MJPC's bimanual grasp score. + +MJPC: https://arxiv.org/abs/2212.00541. +""" + +from typing import Any, Mapping, Optional, Sequence, Tuple + +import numpy as np +import warp as wp + +from robokit.opt.var_values import VarValues +from robokit.terms.simulation.sim_context import SimContext +from robokit.terms.task import Context, Task + + +@wp.kernel +def _compute_pinch_normals_kernel( + count: wp.array(dtype=int), + world: wp.array(dtype=int), + geom: wp.array(dtype=wp.vec2i), + dist: wp.array(dtype=float), + frame: wp.array(dtype=wp.mat33), + role: wp.array(dtype=int), + depth: float, + normal: wp.array3d(dtype=wp.vec3), + touches: wp.array3d(dtype=int), +): + c = wp.tid() + if c >= count[0] or geom[c][0] < 0 or geom[c][1] < 0: + return + r0, r1 = role[geom[c][0]], role[geom[c][1]] + if r0 < 0 or r1 < 0 or r0 // 3 != r1 // 3 or (r0 % 3 == 2) == (r1 % 3 == 2): + return + finger, sign = wp.where(r0 % 3 == 2, r1, r0), wp.where(r0 % 3 == 2, -1.0, 1.0) # normal: finger to object + scale = wp.where(dist[c] < depth, 10.0, 1.0) # touching counts 10 times a contact within the margin + wp.atomic_add(normal, world[c], finger // 3, finger % 3, sign * scale * frame[c][0]) + wp.atomic_add(touches, world[c], finger // 3, finger % 3, 1) + + +@wp.kernel +def _compute_pinch_cost_kernel( + sensordata: wp.array2d(dtype=float), + axes: wp.array2d(dtype=int), + weight: float, + normal: wp.array3d(dtype=wp.vec3), + touches: wp.array3d(dtype=int), + out: wp.array(dtype=float), +): + w = wp.tid() + total = float(0.0) + for p in range(axes.shape[0]): + score = float(1.0) # a finger without contact + if touches[w, p, 0] > 0 and touches[w, p, 1] > 0: + g, o = axes[p, 0], axes[p, 1] + gripper = wp.vec3(sensordata[w, g], sensordata[w, g + 1], sensordata[w, g + 2]) + obj = wp.vec3(sensordata[w, o], sensordata[w, o + 1], sensordata[w, o + 2]) + fingers = wp.dot(wp.normalize(normal[w, p, 0]), wp.normalize(normal[w, p, 1])) + score = (fingers + 2.0 * wp.dot(gripper, obj) + 3.0) / 6.0 + total += weight * score + for f in range(2): + normal[w, p, f] = wp.vec3(0.0) + touches[w, p, f] = 0 + out[w] += total + + +class PinchTask(Task): + """Per step and pinch, `weight` times the bimanual grasp score: 1 while a finger touches nothing of the object, else `(n_0 . n_1 + 2 x_g . x_o + 3) / 6`, 0 for opposed fingers and opposed gripper and object axes; each pinch is `(finger_0, finger_1, object, gripper_axis, object_axis)`: three geoms and two 3-axis sensors; `n_f` sums finger f's contact normals toward the object, one with dist below `depth` (touching) counting 10 times one within the margin. + + Example: + >>> contacts = [([0, 2], [0.0, 0, 1]), ([2, 1], [0.0, 0, 1])] # both fingers on the box, from either side + >>> context = { + ... SimContext.CLOCK: wp.array([0, 0, 1], dtype=int, device="cpu"), + ... SimContext.GEOMS: ["finger_0", "finger_1", "box"], + ... SimContext.SENSORS: [("gripper_x", 0, 3), ("box_x", 3, 3)], + ... SimContext.SENSORDATA: wp.array([[1.0, 0, 0, -1, 0, 0]], dtype=float, device="cpu"), + ... SimContext.CONTACTS: ( + ... wp.array([2], dtype=int, device="cpu"), + ... wp.zeros(2, dtype=int, device="cpu"), + ... wp.array([g for g, _ in contacts], dtype=wp.vec2i, device="cpu"), + ... wp.zeros(2, dtype=float, device="cpu"), + ... wp.zeros(2, dtype=wp.vec3, device="cpu"), + ... wp.array([[n, [1.0, 0, 0], [0, 1.0, 0]] for _, n in contacts], dtype=wp.mat33, device="cpu"), # normal 1st + ... ), + ... } + >>> out = wp.zeros(1, dtype=float, device="cpu") + >>> term = PinchTask([("finger_0", "finger_1", "box", "gripper_x", "box_x")]) + >>> term.resolve(None, context) + >>> term.compute_weighted_cost(None, out_cost=out) + >>> assert np.allclose(out.numpy(), [0.0]) + """ + + def __init__(self, pinches: Sequence[Tuple[str, str, str, str, str]], weight: float = 1.0, depth: float = 0.0): + self.pinches, self.weight, self.depth = [tuple(p) for p in pinches], weight, depth + self.contact_data, self.geoms, self.sensors = SimContext.CONTACTS, SimContext.GEOMS, SimContext.SENSORS + self.sensordata, self.clock = SimContext.SENSORDATA, SimContext.CLOCK + + def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any]): + """Look up the pinches' geoms and axis sensors and build the per-world accumulators.""" + super().resolve(var_values, context) + device, adr = self.clock.device, {name: a for name, a, _ in self.sensors} + role = np.full(len(self.geoms), -1, np.int32) # pinch * 3 + (0, 1: a finger; 2: the object) + for p, pinch in enumerate(self.pinches): + role[[self.geoms.index(g) for g in pinch[:3]]] = 3 * p + np.arange(3) + self.role = wp.array(role, dtype=int, device=device) + self.axes = wp.array([[adr[p[3]], adr[p[4]]] for p in self.pinches], dtype=int, device=device) + shape = (self.sensordata.shape[0], len(self.pinches), 2) + self.normal, self.touches = wp.zeros(shape, wp.vec3, device), wp.zeros(shape, int, device) + + def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): + count, world, geom, dist, _, frame = self.contact_data + wp.launch( + _compute_pinch_normals_kernel, + dim=world.shape[0], + inputs=[count, world, geom, dist, frame, self.role, self.depth], + outputs=[self.normal, self.touches], + device=out_cost.device, + ) + wp.launch( + _compute_pinch_cost_kernel, + dim=self.sensordata.shape[0], + inputs=[self.sensordata, self.axes, self.weight], + outputs=[self.normal, self.touches, out_cost], + device=out_cost.device, + ) diff --git a/src/robokit/terms/simulation/sensor_task.py b/src/robokit/terms/simulation/sensor_task.py index 89ce463..c47fe44 100644 --- a/src/robokit/terms/simulation/sensor_task.py +++ b/src/robokit/terms/simulation/sensor_task.py @@ -12,71 +12,95 @@ import warp as wp from robokit.opt.var_values import VarValues -from robokit.terms.simulation.sim_context import SimContext, _instanced +from robokit.terms.simulation.sim_context import SimContext, SimResidualTask, _get_instance_step_func, _instanced from robokit.terms.simulation.state_task import _compute_rotation_error_func -from robokit.terms.task import Context, Task +from robokit.terms.task import Context @wp.kernel -def _compute_sensor_cost_kernel( +def _compute_sensor_kernel( sensordata: wp.array2d(dtype=float), sensor_ref: wp.array3d(dtype=float), weight: wp.array2d(dtype=float), adr: wp.array(dtype=int), dim: wp.array(dtype=int), + out_adr: wp.array(dtype=int), norm: bool, residual: int, hinge: float, + relative: int, freeze_reference: bool, clock: wp.array(dtype=int), worlds: int, - out: wp.array(dtype=float), + world_steps: wp.array(dtype=wp.vec2i), + row_offset: int, + out: wp.array2d(dtype=float), + out_cost: wp.array(dtype=float), ): + """Per sensor, `sqrt(2 w) e` per error component; with `norm` or `hinge`, one `sqrt(2 cost)` per sensor; or the cost, if wanted.""" w = wp.tid() - b = w // worlds - r = wp.min(clock[0] + wp.where(freeze_reference, 0, clock[1]), sensor_ref.shape[1] - 1) - rw = wp.min(clock[0] + clock[1], weight.shape[0] - 1) + bt = _get_instance_step_func(w, worlds, clock, world_steps) + b = bt[0] + r = wp.min(clock[0] + wp.where(freeze_reference, 0, bt[1]), sensor_ref.shape[1] - 1) + rw = wp.min(clock[0] + bt[1], weight.shape[0] - 1) + cost_only = out_cost.shape[0] > 0 + split = not norm and hinge < 0.0 and not cost_only total = float(0.0) for j in range(adr.shape[0]): s = float(0.0) - a = adr[j] + a, o = adr[j], row_offset + out_adr[j] + ws = wp.where(norm, weight[rw, a] * weight[rw, a], weight[rw, a]) if residual == 2: rotation = _compute_rotation_error_func(sensordata, w, sensor_ref, b, r, a) - s = wp.where(norm, weight[rw, a] * weight[rw, a], weight[rw, a]) * wp.dot(rotation, rotation) - elif residual == 5: - e = wp.atan2(sensordata[w, a + 1], sensordata[w, a]) - e -= wp.atan2(sensor_ref[b, r, a + 1], sensor_ref[b, r, a]) - e = wp.atan2(wp.sin(e), wp.cos(e)) - s = wp.where(norm, weight[rw, a] * weight[rw, a], weight[rw, a]) * e * e - elif residual >= 3: # intrinsic XYZ Euler yaw, atan2(-R[0,1], R[0,0]) - qw, qx, qy, qz = sensordata[w, a], sensordata[w, a + 1], sensordata[w, a + 2], sensordata[w, a + 3] - tw, tx, ty, tz = ( - sensor_ref[b, r, a], - sensor_ref[b, r, a + 1], - sensor_ref[b, r, a + 2], - sensor_ref[b, r, a + 3], - ) - e = wp.atan2(2.0 * (qw * qz - qx * qy), qw * qw + qx * qx - qy * qy - qz * qz) - e -= wp.atan2(2.0 * (tw * tz - tx * ty), tw * tw + tx * tx - ty * ty - tz * tz) - if residual == 3: + s = ws * wp.dot(rotation, rotation) + if split: + for k in range(3): + out[w, o + k] = wp.sqrt(2.0 * weight[rw, a]) * rotation[k] + elif residual >= 3: + e = float(0.0) + if residual == 5: + e = wp.atan2(sensordata[w, a + 1], sensordata[w, a]) + e -= wp.atan2(sensor_ref[b, r, a + 1], sensor_ref[b, r, a]) e = wp.atan2(wp.sin(e), wp.cos(e)) - s = wp.where(norm, weight[rw, a] * weight[rw, a], weight[rw, a]) * e * e + else: # intrinsic XYZ Euler yaw, atan2(-R[0,1], R[0,0]) + qw, qx, qy, qz = sensordata[w, a], sensordata[w, a + 1], sensordata[w, a + 2], sensordata[w, a + 3] + tw, tx, ty, tz = ( + sensor_ref[b, r, a], + sensor_ref[b, r, a + 1], + sensor_ref[b, r, a + 2], + sensor_ref[b, r, a + 3], + ) + e = wp.atan2(2.0 * (qw * qz - qx * qy), qw * qw + qx * qx - qy * qy - qz * qz) + e -= wp.atan2(2.0 * (tw * tz - tx * ty), tw * tw + tx * tx - ty * ty - tz * tz) + if residual == 3: + e = wp.atan2(wp.sin(e), wp.cos(e)) + s = ws * e * e + if split: + out[w, o] = wp.sqrt(2.0 * weight[rw, a]) * e else: for i in range(a, a + dim[j]): e = sensordata[w, i] - sensor_ref[b, r, i] + if relative >= 0: # less the relative sensor's error + e -= sensordata[w, relative + i - a] - sensor_ref[b, r, relative + i - a] if residual == 1: e = wp.atan2(wp.sin(e), wp.cos(e)) s += wp.where(norm, weight[rw, i] * weight[rw, i], weight[rw, i]) * e * e + if split: + out[w, o + i - a] = wp.sqrt(2.0 * weight[rw, i]) * e value = wp.where(norm, wp.sqrt(s), s) - total += wp.where(hinge >= 0.0, wp.max(value - hinge, 0.0), value) - out[w] += total + cost = wp.where(hinge >= 0.0, wp.max(value - hinge, 0.0), value) + total += cost + if not split and not cost_only: + out[w, o] = wp.sqrt(2.0 * cost) + if cost_only: + out_cost[w] += total -class SensorTask(Task): +class SensorTask(SimResidualTask): """Per step, `sum_s w_s * ||sensordata_s - sensor_ref[k]_s||^2` over the sensors in `weight` (`norm`: unsquared). Example: - >>> context = { # what a binding gives one world at sim step 0 + >>> context = { # what SimMPC gives one world at sim step 0 ... SimContext.CLOCK: wp.array([0, 0, 1], dtype=int, device="cpu"), ... SimContext.NUM_INSTANCES: 1, ... SimContext.WORLDS_PER_INSTANCE: 1, @@ -97,18 +121,17 @@ def __init__( sensor_ref: np.ndarray, weight: Union[Dict[str, Union[float, Sequence[float]]], np.ndarray], norm: bool = False, - terminal_scale: Optional[float] = None, residual: Literal["linear", "angle", "quaternion", "yaw", "yaw_unwrapped", "heading"] = "linear", hinge: Optional[float] = None, freeze_reference: bool = False, - running_scale: float = 1.0, + relative: Optional[str] = None, # a sensor whose error every linear error is less, e.g. the pelvis position ): if hinge is not None and hinge < 0: raise ValueError("hinge must be nonnegative") modes = {"linear": 0, "angle": 1, "quaternion": 2, "yaw": 3, "yaw_unwrapped": 4, "heading": 5} - self.sensor_ref, self.weight, self.norm, self.terminal_scale = sensor_ref, weight, norm, terminal_scale + self.sensor_ref, self.weight, self.norm = sensor_ref, weight, norm self.residual, self.hinge = modes[residual], -1.0 if hinge is None else hinge - self.freeze_reference, self.running_scale = freeze_reference, running_scale + self.freeze_reference, self.relative = freeze_reference, relative self.sensordata, self.sensors, self.clock = SimContext.SENSORDATA, SimContext.SENSORS, SimContext.CLOCK self.instances, self.worlds = SimContext.NUM_INSTANCES, SimContext.WORLDS_PER_INSTANCE @@ -129,28 +152,25 @@ def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any for a, n in sensors: if n != (3 if self.residual == 5 else 4) or not np.allclose(w[:, a : a + n], w[:, a : a + 1]): raise ValueError("quaternion/yaw residuals require quaternion sensors with scalar weights") + self.relative_adr = -1 if self.relative is None else {n: int(a) for n, a, _ in self.sensors}[self.relative] self.weight = wp.array(w, dtype=float, device=device) self.adr = wp.array([int(a) for a, _ in sensors], dtype=int, device=device) self.dim = wp.array([int(n) for _, n in sensors], dtype=int, device=device) self.sensor_ref = _instanced(self.sensor_ref, 2, self.instances, device) + split = not self.norm and self.hinge < 0 # residuals per error component, else one per sensor + counts = [(n if self.residual < 2 else 3 if self.residual == 2 else 1) if split else 1 for _, n in sensors] + self.out_adr = wp.array(np.r_[0, np.cumsum(counts)[:-1]].astype(np.int32), dtype=int, device=device) + self._residual_dim = int(sum(counts)) + self._resolve_world_steps(context, device) - def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): + def _launch(self, out_residual: wp.array, row_offset: int, out_cost: wp.array): + inputs = [self.sensordata, self.sensor_ref, self.weight, self.adr, self.dim, self.out_adr, self.norm] + inputs += [self.residual, self.hinge, self.relative_adr, self.freeze_reference, self.clock, self.worlds] + inputs += [self.world_steps] wp.launch( - _compute_sensor_cost_kernel, + _compute_sensor_kernel, dim=self.sensordata.shape[0], - inputs=[ - self.sensordata, - self.sensor_ref, - self.weight, - self.adr, - self.dim, - self.norm, - self.residual, - self.hinge, - self.freeze_reference, - self.clock, - self.worlds, - ], - outputs=[out_cost], - device=out_cost.device, + inputs=[*inputs, row_offset], + outputs=[out_residual, out_cost], + device=self.sensordata.device, ) diff --git a/src/robokit/terms/simulation/sim_context.py b/src/robokit/terms/simulation/sim_context.py index faaa610..c5a059f 100644 --- a/src/robokit/terms/simulation/sim_context.py +++ b/src/robokit/terms/simulation/sim_context.py @@ -4,18 +4,23 @@ # pyright: reportAttributeAccessIssue=false # pyright: reportCallIssue=false # pyright: reportOperatorIssue=false -"""The values a simulator binding gives simulation terms, and their reference-array helper.""" +"""The values `SimMPC` and `ILQROptimizer` give simulation terms, and the terms' shared parts.""" -from typing import Any +from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional import numpy as np import warp as wp -from robokit.terms.task import Context +from robokit.opt.var_values import VarValues +from robokit.terms.task import Context, ResidualTask + + +if TYPE_CHECKING: + from robokit.sim import Sim class SimContext(Context): - """Values a simulator binding gives its terms for one world set; arrays are refilled every step.""" + """Values a planner gives its terms for one world set (`sim_context`); arrays are refilled every step.""" CLOCK = 0 """Device ints `[t0, t, horizon]`: the rollout started at sim step `t0` and has just taken step `t`.""" @@ -36,7 +41,7 @@ class SimContext(Context): BODY_ROTATION = 8 """`(nworld, nbody)` mat33 body rotations, world from body.""" CONTACTS = 9 - """Device arrays `(count, world, geom, dist, position)` of the contact slots; a negative geom pair is empty.""" + """Device arrays `(count, world, geom, dist, position, frame)` of the contact slots (frame: normal first); a negative geom pair is empty.""" JOINTS = 10 """Device ints `(type, qpos_address, dof_address)` per joint; MuJoCo's types: 0 free, 1 ball, 2 slide, 3 hinge.""" SENSORS = 11 @@ -45,13 +50,79 @@ class SimContext(Context): """Body names by id.""" GEOMS = 13 """Geom names by id.""" + WORLD_STEPS = 14 + """Optional device vec2i `(instance, step)` per world, for worlds of different instances and steps (iLQR's finite differences); without it, world `w` is instance `w // WORLDS_PER_INSTANCE` at step `CLOCK[1]`.""" -def _instanced(x: Any, ndim: int, instances: int, device: Any, dtype: Any = float) -> wp.array: - """`x` with a leading instance axis on `device`; an array of `ndim` axes is shared by every instance. +@wp.func +def _get_instance_step_func( + w: int, worlds: int, clock: wp.array(dtype=int), world_steps: wp.array(dtype=wp.vec2i) +) -> wp.vec2i: + """World `w`'s instance and step since the rollout's start (`SimContext.WORLD_STEPS`).""" + if world_steps.shape[0] > 0: + return world_steps[w] + return wp.vec2i(w // worlds, clock[1]) + + +def sim_context(sim: "Sim") -> Dict[Context, Any]: + """The `SimContext` values of a simulator's worlds, with its `mjm`'s layout, except `CLOCK`, `NUM_INSTANCES` and `WORLDS_PER_INSTANCE`.""" + data = sim.data + model = sim.mjm + device = data.qpos.device + return { + SimContext.QPOS: data.qpos, + SimContext.QVEL: data.qvel, + SimContext.CTRL: data.ctrl, + SimContext.SENSORDATA: data.sensordata, + SimContext.BODY_POSITION: data.xpos, + SimContext.BODY_ROTATION: data.xmat, + SimContext.JOINTS: tuple( + wp.array(np.asarray(x, np.int32), dtype=int, device=device) + for x in (model.jnt_type, model.jnt_qposadr, model.jnt_dofadr) + ), + SimContext.SENSORS: [ + (model.sensor(i).name, int(model.sensor_adr[i]), int(model.sensor_dim[i])) for i in range(model.nsensor) + ], + SimContext.BODIES: [model.body(i).name for i in range(model.nbody)], + SimContext.GEOMS: [model.geom(i).name for i in range(model.ngeom)], + SimContext.CONTACTS: ( + data.nacon, + *(getattr(data.contact, k) for k in ["worldid", "geom", "dist", "pos", "frame"]), + ), + } + + +class SimResidualTask(ResidualTask): + """A simulation term with weighted residuals: `ILQROptimizer` reads them, `SimMPC` their cost `0.5 |r|^2`, which the term's kernel adds up directly; subclasses set `_residual_dim` and call `_resolve_world_steps` in `resolve`, then implement `_launch`: one kernel over the context's worlds that writes the residuals, or with a nonempty `out_cost`, adds each world's cost.""" + + _residual_dim: int = 0 - A Warp array that already has the instance axis is used in place, so its owner can rewrite it between plans. - """ + @property + def residual_dim(self) -> int: + return self._residual_dim + + def _resolve_world_steps(self, context: Mapping[Context, Any], device: Any): + """Each world's instance and step (`SimContext.WORLD_STEPS`, else none), and the kernel's unused outputs.""" + steps = context.get(SimContext.WORLD_STEPS) + self.world_steps = steps if steps is not None else wp.zeros(0, dtype=wp.vec2i, device=device) + self._no_cost, self._no_residual = wp.zeros(0, device=device), wp.zeros((0, 0), device=device) + + def _launch(self, out_residual: wp.array, row_offset: int, out_cost: wp.array): + raise NotImplementedError + + def compute_weighted_residual( + self, var_values: Optional[VarValues], *, out_residual: wp.array, row_offset: int = 0 + ) -> wp.array: + self._launch(out_residual, row_offset, self._no_cost) + return out_residual + + def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): + """Add each world's `0.5 |r|^2`.""" + self._launch(self._no_residual, 0, out_cost) + + +def _instanced(x: Any, ndim: int, instances: int, device: Any, dtype: Any = float) -> wp.array: + """`x` with a leading instance axis on `device`; an array of `ndim` axes is shared by every instance; a Warp array that already has the instance axis is used in place, so its owner can rewrite it between plans.""" if isinstance(x, wp.array) and x.ndim == ndim + 1 and x.shape[0] == instances: return x x = np.asarray(x, np.float32) diff --git a/src/robokit/terms/simulation/state_task.py b/src/robokit/terms/simulation/state_task.py index 68f6781..a106989 100644 --- a/src/robokit/terms/simulation/state_task.py +++ b/src/robokit/terms/simulation/state_task.py @@ -12,8 +12,8 @@ import warp as wp from robokit.opt.var_values import VarValues -from robokit.terms.simulation.sim_context import SimContext, _instanced -from robokit.terms.task import Context, Task +from robokit.terms.simulation.sim_context import SimContext, SimResidualTask, _get_instance_step_func, _instanced +from robokit.terms.task import Context @wp.kernel @@ -63,13 +63,14 @@ def _compute_rotation_error_func( @wp.kernel -def _compute_tracking_cost_kernel( +def _compute_tracking_kernel( qpos: wp.array2d(dtype=float), qvel: wp.array2d(dtype=float), qpos_ref: wp.array3d(dtype=float), qvel_ref: wp.array3d(dtype=float), clock: wp.array(dtype=int), worlds: int, + world_steps: wp.array(dtype=wp.vec2i), jnt_type: wp.array(dtype=int), jnt_qposadr: wp.array(dtype=int), jnt_dofadr: wp.array(dtype=int), @@ -83,62 +84,67 @@ def _compute_tracking_cost_kernel( touch: wp.array2d(dtype=int), squared: bool, freeze_reference: bool, - out: wp.array(dtype=float), + row_offset: int, + out: wp.array2d(dtype=float), + out_cost: wp.array(dtype=float), ): + """`sqrt(2)` times each weighted dof error (`squared`), else one `sqrt(2 |error|)`, then `sqrt(2 vel_weight |qvel error|)`; or if wanted, the cost, contact terms included, which clears the step's contact flags.""" w = wp.tid() - b = w // worlds - r = wp.min(clock[0] + wp.where(freeze_reference, 0, clock[1] + 1), qpos_ref.shape[1] - 1) + bt = _get_instance_step_func(w, worlds, clock, world_steps) + b = bt[0] + r = wp.min(clock[0] + wp.where(freeze_reference, 0, bt[1] + 1), qpos_ref.shape[1] - 1) rw = wp.min(r, dof_weight.shape[1] - 1) + cost_only = out_cost.shape[0] > 0 s = float(0.0) for j in range(jnt_type.shape[0]): qa, da = jnt_qposadr[j], jnt_dofadr[j] - if jnt_type[j] == 0: # free: position, then rotation - for i in range(3): + n = wp.where(jnt_type[j] == 0, 6, wp.where(jnt_type[j] == 1, 3, 1)) # free: position, then rotation + v = wp.vec3(0.0) + if jnt_type[j] <= 1: + v = _compute_rotation_error_func(qpos, w, qpos_ref, b, r, qa + wp.where(jnt_type[j] == 0, 3, 0)) + for i in range(n): + e = float(0.0) + if n - i <= 3 and jnt_type[j] <= 1: + e = v[i - (n - 3)] * dof_weight[b, rw, da + i] + else: e = (qpos[w, qa + i] - qpos_ref[b, r, qa + i]) * dof_weight[b, rw, da + i] + if jnt_type[j] <= 1: e = wp.where(pose_tolerance > 0.0, wp.abs(e) - wp.min(wp.abs(e), pose_tolerance), e) - s += e * e - v = _compute_rotation_error_func(qpos, w, qpos_ref, b, r, qa + 3) - for i in range(3): - e = v[i] * dof_weight[b, rw, da + 3 + i] - e = wp.where(pose_tolerance > 0.0, wp.abs(e) - wp.min(wp.abs(e), pose_tolerance), e) - s += e * e - elif jnt_type[j] == 1: # ball - v = _compute_rotation_error_func(qpos, w, qpos_ref, b, r, qa) - for i in range(3): - e = v[i] * dof_weight[b, rw, da + i] - e = wp.where(pose_tolerance > 0.0, wp.abs(e) - wp.min(wp.abs(e), pose_tolerance), e) - s += e * e - else: - e = (qpos[w, qa] - qpos_ref[b, r, qa]) * dof_weight[b, rw, da] s += e * e + if squared and not cost_only: + out[w, row_offset + da + i] = wp.sqrt(2.0) * e sv = float(0.0) for i in range(qvel.shape[1]): e = qvel[w, i] - qvel_ref[b, r, i] sv += e * e + if not cost_only: + if not squared: + out[w, row_offset] = wp.sqrt(2.0 * wp.sqrt(s)) + out[w, row_offset + wp.where(squared, qvel.shape[1], 1)] = wp.sqrt(2.0 * vel_weight * wp.sqrt(sv)) + return p = penetration[w] total = wp.where(squared, s, wp.sqrt(s)) + vel_weight * wp.sqrt(sv) + penetration_scale * p * p for k in range(contact_scale.shape[0]): # contacts the reference wants but the rollout lacks total += contact_scale[k] * contact_ref[b, r, k] * float(1 - touch[w, k + 1]) touch[w, k + 1] = 0 penetration[w] = 0.0 - out[w] += total + out_cost[w] += total -class StateTask(Task): - """Per step, the weighted qpos error norm plus `vel_weight` times the qvel error norm, and optional contact terms. +class StateTask(SimResidualTask): + """Per step, the weighted qpos error norm plus `vel_weight` times the qvel error norm, and optional contact terms; its residuals cover the errors, while the contact terms (penetration, missing contacts) are cost-only, so `SimMPC` sees them and `ILQROptimizer` does not. Example: >>> # xdoctest: +REQUIRES(module:mujoco_warp) >>> import copy, mujoco - >>> from robokit.helpers.sim_mpc.mjwarp import MjWarpSim + >>> from robokit.helpers.sim_mpc import sim_context + >>> from robokit.sim import MjWarpSim >>> model = mujoco.MjModel.from_xml_string( ... '' ... ) >>> data = mujoco.MjData(model) >>> data.qpos[0] = 0.05 # 5 cm off the reference in x - >>> sim = MjWarpSim(model, data) - >>> sim.build(1, 2, 1, 1, 0, 0) - >>> context = sim.context("execution") | { + >>> context = sim_context(MjWarpSim(model, 1, data)) | { ... SimContext.CLOCK: wp.array([0, 0, 1], dtype=int), ... SimContext.NUM_INSTANCES: 1, ... SimContext.WORLDS_PER_INSTANCE: 1, @@ -161,16 +167,14 @@ def __init__( penetration_scale: float = 0.0, margin: float = 0.0, contacts: Sequence[Tuple[np.ndarray, np.ndarray, np.ndarray, float]] = (), - terminal_scale: Optional[float] = None, squared: bool = False, freeze_reference: bool = False, - running_scale: float = 1.0, pose_tolerance: float = 0.0, ): self.qpos_ref, self.qvel_ref, self.dof_weight, self.vel_weight = qpos_ref, qvel_ref, dof_weight, vel_weight self.penetration_groups, self.penetration_scale, self.margin = penetration_groups, penetration_scale, margin - self.contacts, self.terminal_scale, self.squared = list(contacts), terminal_scale, squared - self.freeze_reference, self.running_scale, self.pose_tolerance = freeze_reference, running_scale, pose_tolerance + self.contacts, self.squared = list(contacts), squared + self.freeze_reference, self.pose_tolerance = freeze_reference, pose_tolerance self.qpos, self.qvel, self.contact_data, self.joints = ( SimContext.QPOS, SimContext.QVEL, @@ -204,9 +208,23 @@ def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any self.qpos_ref, self.qvel_ref = _instanced(self.qpos_ref, 2, n, device), _instanced(self.qvel_ref, 2, n, device) self.penetration = wp.zeros(self.qpos.shape[0], dtype=float, device=device) self.touch = wp.zeros((self.qpos.shape[0], self.pair_a.shape[0]), dtype=int, device=device) + self._residual_dim = (self.qvel.shape[1] if self.squared else 1) + 1 + self._resolve_world_steps(context, device) + + def _launch(self, out_residual: wp.array, row_offset: int, out_cost: wp.array): + inputs = [self.qpos, self.qvel, self.qpos_ref, self.qvel_ref, self.clock, self.worlds, self.world_steps] + inputs += [*self.joints, self.dof_weight, self.pose_tolerance, self.vel_weight, self.penetration_scale] + inputs += [self.contact_ref, self.contact_scale, self.penetration, self.touch, self.squared] + wp.launch( + _compute_tracking_kernel, + dim=self.qpos.shape[0], + inputs=[*inputs, self.freeze_reference, row_offset], + outputs=[out_residual, out_cost], + device=self.qpos.device, + ) def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): - count, world, geom, dist, _ = self.contact_data + count, world, geom, dist = self.contact_data[:4] wp.launch( _compute_contact_flags_kernel, dim=world.shape[0], @@ -214,28 +232,4 @@ def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp outputs=[self.penetration, self.touch], device=out_cost.device, ) - wp.launch( - _compute_tracking_cost_kernel, - dim=self.qpos.shape[0], - inputs=[ - self.qpos, - self.qvel, - self.qpos_ref, - self.qvel_ref, - self.clock, - self.worlds, - *self.joints, - self.dof_weight, - self.pose_tolerance, - self.vel_weight, - self.penetration_scale, - self.contact_ref, - self.contact_scale, - self.penetration, - self.touch, - self.squared, - self.freeze_reference, - ], - outputs=[out_cost], - device=out_cost.device, - ) + super().compute_weighted_cost(var_values, out_cost=out_cost) diff --git a/src/robokit/terms/simulation/support_task.py b/src/robokit/terms/simulation/support_task.py new file mode 100644 index 0000000..f5ad9b1 --- /dev/null +++ b/src/robokit/terms/simulation/support_task.py @@ -0,0 +1,101 @@ +# pyright: reportGeneralTypeIssues=false +# pyright: reportArgumentType=false +# pyright: reportIndexIssue=false +# pyright: reportAttributeAccessIssue=false +# pyright: reportCallIssue=false +# pyright: reportOperatorIssue=false +"""Penalize steps where too few finger groups touch an object.""" + +from typing import Any, Mapping, Optional, Sequence + +import warp as wp + +from robokit.opt.var_values import VarValues +from robokit.terms.simulation.sim_context import SimContext +from robokit.terms.task import Context, Task + + +@wp.kernel +def _compute_touch_kernel( + count: wp.array(dtype=int), + world: wp.array(dtype=int), + geom: wp.array(dtype=wp.vec2i), + dist: wp.array(dtype=float), + obj: int, + group: wp.array(dtype=int), + margin: float, + touch: wp.array2d(dtype=int), +): + c = wp.tid() + if c >= count[0] or dist[c] > margin: + return + a, b = geom[c][0], geom[c][1] + other = wp.where(a == obj, b, wp.where(b == obj, a, -1)) + if other >= 0 and group[other] >= 0: + wp.atomic_max(touch, world[c], group[other], 1) + + +@wp.kernel +def _compute_support_cost_kernel( + touch: wp.array2d(dtype=int), need: int, weight: float, free: int, out: wp.array(dtype=float) +): + w, last = wp.tid(), touch.shape[1] - 1 + n = int(0) + for g in range(touch.shape[1] - free): + n += touch[w, g] + if free == 0 or touch[w, last] == 0: + out[w] += weight * float(wp.max(need - n, 0)) + for g in range(touch.shape[1]): + touch[w, g] = 0 + + +class SupportTask(Task): + """Per step, `weight` times how many groups short of `need` touch geom `obj`, at least 0; a group is every geom whose name contains one of `groups`, and it touches when any of its contacts with `obj` is within `margin`; with `free`, the last group (say a thumb) is not counted and the cost applies only while it is off `obj`. + + Example: + >>> contacts = [([4], int), ([0, 0, 1, 1], int), ([[0, 1], [2, 0], [1, 0], [0, 3]], wp.vec2i)] + >>> contacts += [([0.0, 0.001, 0.0, 0.0], float), ([[0, 0, 0]] * 4, wp.vec3)] + >>> context = { # world 0: index and middle on the pen; world 1: index and thumb + ... SimContext.GEOMS: ["pen", "index", "middle", "thumb"], + ... SimContext.CTRL: wp.zeros((2, 1), dtype=float, device="cpu"), + ... SimContext.CONTACTS: tuple(wp.array(x, dtype=t, device="cpu") for x, t in contacts), + ... } + >>> costs = [] + >>> for term in [SupportTask("pen", ["index", "middle"], 2, 3.0, 0.002), + ... SupportTask("pen", ["index", "middle", "thumb"], 2, 3.0, 0.002, free=True)]: # fmt: skip + ... term.resolve(None, context) + ... out = wp.zeros(2, dtype=float, device="cpu") + ... term.compute_weighted_cost(None, out_cost=out) + ... costs.append(out.numpy().tolist()) + >>> costs # world 1 is one finger short, which `free` forgives while the thumb is on the pen + [[0.0, 3.0], [0.0, 0.0]] + """ + + def __init__( + self, obj: str, groups: Sequence[str], need: int, weight: float, margin: float = 0.0, free: bool = False + ): + self.obj, self.groups, self.need, self.weight = obj, list(groups), need, weight + self.margin, self.free = margin, free + self.contact_data, self.geoms, self.ctrl = SimContext.CONTACTS, SimContext.GEOMS, SimContext.CTRL + + def resolve(self, var_values: Optional[VarValues], context: Mapping[Context, Any]): + """Map every geom to its group, look up the object and make each world's touch flags.""" + super().resolve(var_values, context) + group = [next((i for i, g in enumerate(self.groups) if g in (name or "")), -1) for name in self.geoms] + self.group, self.obj = wp.array(group, dtype=int, device=self.ctrl.device), self.geoms.index(self.obj) + self.touch = wp.zeros((self.ctrl.shape[0], len(self.groups)), dtype=int, device=self.ctrl.device) + + def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): + count, world, geom, dist = self.contact_data[:4] + inputs = [count, world, geom, dist, self.obj, self.group, self.margin] + wp.launch( + _compute_touch_kernel, dim=world.shape[0], inputs=inputs, outputs=[self.touch], device=out_cost.device + ) + inputs = [self.touch, self.need, self.weight, int(self.free)] + wp.launch( + _compute_support_cost_kernel, + dim=out_cost.shape[0], + inputs=inputs, + outputs=[out_cost], + device=out_cost.device, + ) diff --git a/src/robokit/terms/sparse/trajectory_collision_task.py b/src/robokit/terms/sparse/trajectory_collision_task.py index 61d78b2..358c342 100644 --- a/src/robokit/terms/sparse/trajectory_collision_task.py +++ b/src/robokit/terms/sparse/trajectory_collision_task.py @@ -540,7 +540,7 @@ def compute_traj_collision_jacobian_cached_kernel( _SWEPT_THREADS = 128 # CUDA threads per frame: sphere slots of _SWEPT_LANES lanes _SWEPT_LANES = 2 # threads per sphere, each taking every other box -_MAX_JACOBIAN_COLS = 16 +_MAX_JACOBIAN_COLS = 31 # the frame cost and every column share one 32-wide row sum _frame_sums = wp.types.vector(length=32, dtype=wp.float32) @@ -837,7 +837,8 @@ def max_penetration_kernel( frame_idx = interior_idx + 1 radius = collision_sphere_radii[sphere_indices[sphere_local_idx]] cache_idx = (batch_idx * num_frames + frame_idx) * num_spheres + sphere_local_idx - mask = _frame_sphere_weight_func(frame_sphere_mask, batch_idx, frame_idx, sphere_local_idx, out.shape[0]) + batch_size = cache_sdf_normal.shape[0] // (num_frames * num_spheres) # the cache's, not `out`'s + mask = _frame_sphere_weight_func(frame_sphere_mask, batch_idx, frame_idx, sphere_local_idx, batch_size) pen = mask * sphere_mask[sphere_local_idx] * (radius - cache_sdf_normal[cache_idx][0]) if pen > 0.0: wp.atomic_max(out, batch_idx, pen) @@ -1084,13 +1085,16 @@ def init_buffers(self, device: wp_device_type): ) def accumulate_max_penetration(self, out: wp.array): - """Max-accumulate penetration from the most recent Jacobian query cache, over every geometry.""" + """Max-accumulate penetration from the most recent Jacobian query cache, over every geometry. + + Runs over the batch the cache holds: `out` may be longer (a score task sized for every draw). + """ n = self._cache_size for k in range(len(self._kinds)): wp.launch( kernel=max_penetration_kernel, dim=( - out.shape[0], + n // (self.num_frames * self.num_spheres), self.num_frames - 2 if self.free_goal_frame and self.sweep_steps == 0 else self.num_frames - 1, self.num_spheres, ), diff --git a/src/robokit/terms/sparse/trajectory_limit_task.py b/src/robokit/terms/sparse/trajectory_limit_task.py index c5a2e1c..6546f22 100644 --- a/src/robokit/terms/sparse/trajectory_limit_task.py +++ b/src/robokit/terms/sparse/trajectory_limit_task.py @@ -2,6 +2,7 @@ # pyright: reportIndexIssue=false # pyright: reportGeneralTypeIssues=false # pyright: reportOperatorIssue=false +# pyright: reportCallIssue=false """Sparse joint position and derivative bounds along a trajectory.""" from math import comb @@ -46,6 +47,8 @@ class TrajectoryLimitTask(SparseTask, GradientTask): Time scaling: - Default: divide each derivative by dt raised to its order. - Explicit ``dt_power``: override the exponent per order. + - ``timing = (frame_segment, segments, time_weight)``: a bound row's step is its plan's ``exp(VarKey.SEGMENT_STEP)`` + for its frame's segment, a Jacobian column (zero-width bounds keep ``dt``); ``time_weight`` > 0 costs each second. Unbuilt templates (`resolve`): - ``upper`` may hold one entry per order; unset bounds default to the robot's position and velocity limits. @@ -87,6 +90,7 @@ def __init__( self.normalize = normalize self.dt = dt self.device: Optional[wp_device_type] = None + self.timing: Optional[Tuple[wp.array, int, float]] = None if robot is None or num_frames is None: return # runtime bounds, horizon and robot come from the helper orders = [int(o) for o in np.atleast_1d(order)] @@ -247,9 +251,16 @@ def set_dt(self, dt: Union[float, wp.array]): wp.full(1, float(dt), dtype=wp.float32, device=self.device) if self.device is not None else float(dt) ) + def _segment_steps(self, var_values: "VarValues") -> Tuple[Optional[wp.array], Optional[wp.array], float, float]: + """Each plan's segment log steps, each frame interval's segment, their tangent unit and time cost weight.""" + frame_segment, _, time_weight = self.timing or (None, 0, 0.0) + steps = None if frame_segment is None else var_values.get(VarKey.SEGMENT_STEP) + return (None, None, 1.0, 0.0) if steps is None else (steps.x, frame_segment, steps.unit, time_weight) + @property def residual_dim(self) -> int: - return len(self.orders) * self._num_rows * self.robot.spec.num_actuated_joints + cost_rows = self.timing[1] if self.timing is not None and self.timing[2] > 0.0 else 0 + return len(self.orders) * self._num_rows * self.robot.spec.num_actuated_joints + cost_rows def compute_weighted_residual( self, @@ -281,6 +292,7 @@ def compute_weighted_residual( self._offset, self.use_mask, self._get_frame_mask(), + *self._segment_steps(var_values), row_offset, 0, 0, @@ -323,6 +335,7 @@ def fill_residual_and_jacobian( self._offset, self.use_mask, self._get_frame_mask(), + *self._segment_steps(var_values), row_offset, nnz_offset, 2, @@ -346,7 +359,9 @@ def compute_sparse_jacobian_pattern( self.init_buffers(state.q.device) num_dofs = self.robot.spec.num_actuated_joints base_dim = 6 if bool(state.has_floating_base) else 0 - nnz = self.residual_dim * self._coefficients_np.shape[1] + segments = 0 if self.timing is None else self.timing[1] + width, limit_rows = self._coefficients_np.shape[1] + segments, len(self.orders) * self._num_rows * num_dofs + nnz = self.residual_dim * width rows = wp.empty(nnz, dtype=wp.int32, device=state.q.device) if out_row_indices is None else out_row_indices cols = wp.empty(nnz, dtype=wp.int32, device=state.q.device) if out_col_indices is None else out_col_indices wp.launch( @@ -360,6 +375,10 @@ def compute_sparse_jacobian_pattern( base_dim, self._coefficients_np.shape[1], self._offset, + segments, + var_values.tangent_offset(VarKey.SEGMENT_STEP) if segments else 0, # the step columns + limit_rows, + self.residual_dim - limit_rows, offset, nnz_offset, ], @@ -386,9 +405,8 @@ def compute_weighted_sparse_jacobian_values( if q.shape[0] % self.dt.shape[0]: raise ValueError("the plan batch must be a multiple of the dt batch") if out_jacobian_values is None: - out_jacobian_values = wp.empty( - (q.shape[0], self.residual_dim * self._coefficients_np.shape[1]), dtype=wp.float32, device=q.device - ) + width = self._coefficients_np.shape[1] + (0 if self.timing is None else self.timing[1]) + out_jacobian_values = wp.empty((q.shape[0], self.residual_dim * width), dtype=wp.float32, device=q.device) wp.launch( _limit_kernel, dim=(q.shape[0], len(self.orders) * self._num_rows, q.shape[2]), @@ -403,6 +421,7 @@ def compute_weighted_sparse_jacobian_values( self._offset, self.use_mask, self._get_frame_mask(), + *self._segment_steps(var_values), 0, nnz_offset, 1, @@ -426,6 +445,10 @@ def _limit_kernel( frame_offset: int, use_mask: wp.bool, frame_mask: wp.array2d(dtype=wp.uint8), + log_step: wp.array2d(dtype=wp.float32), # (plans, segments) log steps, or empty at `dt` + frame_segment: wp.array1d(dtype=wp.int32), # each frame interval's segment + unit: float, # the log steps' tangent unit + time_weight: float, # >0: the segments' time cost per second row_offset: int, nnz_offset: int, jacobian: int, # 0: the residual, 1: the Jacobian values, 2: both @@ -436,6 +459,21 @@ def _limit_kernel( t, f = r // num_rows, r % num_rows n = q.shape[1] scale = 1.0 / wp.pow(dt[b // (q.shape[0] // dt.shape[0])], dt_power[t]) + stencil, segments = coefficients.shape[1], log_step.shape[1] + if time_weight > 0.0 and d == 0 and r < segments: # segment r's cost row: half the square of sqrt(2 weight time) + time = float(0.0) + for interval in range(n - 1): + time += wp.where(frame_segment[interval] == r, wp.exp(log_step[b, r]), 0.0) + cost_row = coefficients.shape[0] * num_rows * q.shape[2] + r + if jacobian != 1: + out_residual[b, row_offset + cost_row] = wp.sqrt(2.0 * time_weight * time) + for k in range(wp.where(jacobian != 0, stencil + segments, 0)): + entry = wp.where(k == stencil + r, wp.sqrt(0.5 * time_weight * time) * unit, 0.0) + out_jacobian[b, nnz_offset + cost_row * (stencil + segments) + k] = entry + segment = int(-1) # a bound's segment; zero-width bounds (penalties) stay at `dt` + if segments > 0 and bounds[t, d, 0] < bounds[t, d, 1]: + segment = frame_segment[wp.min(f, n - 2)] + scale = wp.exp(-dt_power[t] * log_step[b, segment]) value = float(0.0) mask = float(1.0) for k in range(coefficients.shape[1]): @@ -451,11 +489,13 @@ def _limit_kernel( if jacobian == 0: return sign = float(1.0) if above > 0.0 else float(-1.0) - for k in range(coefficients.shape[1]): + for k in range(stencil + segments): entry = float(0.0) - if below > 0.0 or above > 0.0: + if (below > 0.0 or above > 0.0) and k < stencil: entry = weight[t, d] * sign * coefficients[t, k] * scale * mask - out_jacobian[b, nnz_offset + row * coefficients.shape[1] + k] = entry + if (below > 0.0 or above > 0.0) and segment >= 0 and k == stencil + segment: # d value / d log step + entry = -weight[t, d] * sign * dt_power[t] * value * mask * unit + out_jacobian[b, nnz_offset + row * (stencil + segments) + k] = entry @wp.kernel @@ -467,6 +507,10 @@ def _limit_pattern_kernel( base_dim: int, stencil_size: int, frame_offset: int, + segments: int, # segment step columns, from `step_column` on + step_column: int, + limit_rows: int, # rows before the segments' time cost rows + cost_rows: int, row_offset: int, nnz_offset: int, row_indices: wp.array1d(dtype=wp.int32), @@ -475,11 +519,17 @@ def _limit_pattern_kernel( r, d = wp.tid() # pyright: ignore[reportAssignmentType] f = r % num_rows row = r * num_dofs + d - for k in range(stencil_size): - row_indices[nnz_offset + row * stencil_size + k] = row_offset + row - col_indices[nnz_offset + row * stencil_size + k] = ( + width = stencil_size + segments + for k in range(width): + row_indices[nnz_offset + row * width + k] = row_offset + row + col_indices[nnz_offset + row * width + k] = ( wp.clamp(f + k + frame_offset, 0, num_frames - 1) * single_tangent_dim + base_dim + d ) + if k >= stencil_size: + col_indices[nnz_offset + row * width + k] = step_column + k - stencil_size + if d == 0 and r < cost_rows: # segment r's time, in its step's column + row_indices[nnz_offset + (limit_rows + r) * width + k] = row_offset + limit_rows + r + col_indices[nnz_offset + (limit_rows + r) * width + k] = step_column + r if TYPE_CHECKING: diff --git a/src/robokit/terms/sparse/trajectory_position_task.py b/src/robokit/terms/sparse/trajectory_position_task.py index 79a66f9..4bae919 100644 --- a/src/robokit/terms/sparse/trajectory_position_task.py +++ b/src/robokit/terms/sparse/trajectory_position_task.py @@ -3,6 +3,7 @@ # pyright: reportGeneralTypeIssues=false # pyright: reportOperatorIssue=false # pyright: reportUndefinedVariable=false +# pyright: reportCallIssue=false """Sparse trajectory position and contact residuals.""" from typing import TYPE_CHECKING, Any, Mapping, Optional, Sequence, Union @@ -471,10 +472,22 @@ def compute_trajectory_position_jacobian_sparse_values_kernel( # --- contact kernels -------------------------------------------------------- +@wp.func +def _segment_target_func(contact_pt: wp.vec3, axis: wp.vec3, point: wp.vec3) -> wp.vec4: + """The point of the segment `contact_pt + t axis`, `t` in [0, 1], nearest `point`, and `t`.""" + length_sq = wp.dot(axis, axis) + t = wp.float32(0.0) + if length_sq > wp.float32(0.0): + t = wp.clamp(wp.dot(point - contact_pt, axis) / length_sq, wp.float32(0.0), wp.float32(1.0)) + target = contact_pt + t * axis + return wp.vec4(target[0], target[1], target[2], t) + + @wp.kernel def _compute_trajectory_contact_residual_kernel( T_world_link: wp.array3d(dtype=wp_vec7), # [batch, frames, num_links] contact_points: wp.array4d(dtype=wp.float32), # [batch, frames, max_contacts, 3] + contact_axes: wp.array4d(dtype=wp.float32), # [batch, frames, max_contacts, 3] local_contact_points: wp.array4d(dtype=wp.float32), # [batch, frames, max_contacts, 3] contact_link_indices: wp.array2d(dtype=wp.int32), # [frames, max_contacts] contact_mask: wp.array3d(dtype=wp.bool), # [batch, frames, max_contacts] @@ -512,8 +525,14 @@ def _compute_trajectory_contact_residual_kernel( contact_points[tgt_idx, frame_idx, contact_idx, 1], contact_points[tgt_idx, frame_idx, contact_idx, 2], ) + axis = wp.vec3( + contact_axes[tgt_idx, frame_idx, contact_idx, 0], + contact_axes[tgt_idx, frame_idx, contact_idx, 1], + contact_axes[tgt_idx, frame_idx, contact_idx, 2], + ) + target = _segment_target_func(contact_pt, axis, link_point) - raw_diff = contact_pt - link_point + raw_diff = wp.vec3(target[0], target[1], target[2]) - link_point margin = wp.float32(contact_margin) p0 = wp.max(wp.abs(raw_diff[0]) - margin, wp.float32(0.0)) @@ -571,6 +590,7 @@ def _compute_trajectory_contact_jacobian_sparse_values_kernel( T_world_link: wp.array3d(dtype=wp_vec7), # [batch, frames, num_links] T_world_base: wp.array2d(dtype=wp_vec7), # [batch, frames] contact_points: wp.array4d(dtype=wp.float32), # [batch, frames, max_contacts, 3] + contact_axes: wp.array4d(dtype=wp.float32), # [batch, frames, max_contacts, 3] local_contact_points: wp.array4d(dtype=wp.float32), # [batch, frames, max_contacts, 3] contact_link_indices: wp.array2d(dtype=wp.int32), # [frames, max_contacts] contact_mask: wp.array3d(dtype=wp.bool), # [batch, frames, max_contacts] @@ -614,8 +634,18 @@ def _compute_trajectory_contact_jacobian_sparse_values_kernel( contact_points[tgt_idx, frame_idx, contact_idx, 1], contact_points[tgt_idx, frame_idx, contact_idx, 2], ) - raw_diff = contact_pt - p_contact + axis = wp.vec3( + contact_axes[tgt_idx, frame_idx, contact_idx, 0], + contact_axes[tgt_idx, frame_idx, contact_idx, 1], + contact_axes[tgt_idx, frame_idx, contact_idx, 2], + ) + target = _segment_target_func(contact_pt, axis, p_contact) + raw_diff = wp.vec3(target[0], target[1], target[2]) - p_contact margin = wp.float32(contact_margin) + # inside the segment the target slides with the point: only motion across the axis counts + slide = wp.vec3(0.0, 0.0, 0.0) + if target[3] > wp.float32(0.0) and target[3] < wp.float32(1.0): + slide = wp.normalize(axis) # activate components outside the deadband act_x = wp.float32(0.0) @@ -659,6 +689,7 @@ def _compute_trajectory_contact_jacobian_sparse_values_kernel( S_world[batch_idx, frame_idx, 5, joint_idx], ) dp_dq = dp_dq + w_jt * (v + wp.cross(om, p_contact)) + dp_dq = dp_dq - wp.dot(dp_dq, slide) * slide # differentiate the active residual components val_x = -act_x * w * dp_dq[0] @@ -677,6 +708,7 @@ def _compute_trajectory_contact_jacobian_sparse_values_kernel( v = wp.vec3(base_twist[0], base_twist[1], base_twist[2]) om = wp.vec3(base_twist[3], base_twist[4], base_twist[5]) dp_dq = v + wp.cross(om, p_contact) + dp_dq = dp_dq - wp.dot(dp_dq, slide) * slide idx = max_ancestor_dofs + b values[batch_idx, base_nnz + 0 * cols_per_residual + idx] = -act_x * w * dp_dq[0] @@ -686,7 +718,7 @@ def _compute_trajectory_contact_jacobian_sparse_values_kernel( # --- contact task ----------------------------------------------------------- class TrajectoryContactTask(RobotTask, SparseTask): - """Keep selected link points within a deadband of trajectory contacts. + """Keep selected link points within a deadband of trajectory contacts: points, or segments along `contact_axes`. Args: robot: Robot with FK support. @@ -766,6 +798,7 @@ def __init__( self.device: Optional[wp_device_type] = None self.contact_points_wp: Optional[wp.array] = None self.local_contact_points_wp: Optional[wp.array] = None + self.contact_axes_wp: Optional[wp.array] = None self.contact_link_indices_wp: Optional[wp.array] = None self.contact_mask_wp: Optional[wp.array] = None self.link_ancestor_dofs_wp: Optional[wp.array] = None @@ -799,6 +832,7 @@ def _init_buffers(self, device: wp_device_type): self.device = device self.contact_points_wp = wp.from_numpy(self.contact_points_input, dtype=wp.float32, device=device) self.local_contact_points_wp = wp.from_numpy(self.local_contact_points_input, dtype=wp.float32, device=device) + self.contact_axes_wp = wp.zeros(self.contact_points_input.shape, dtype=wp.float32, device=device) self.contact_link_indices_wp = wp.from_numpy(self.contact_link_indices_input, dtype=wp.int32, device=device) self.contact_mask_wp = wp.from_numpy(self.contact_mask_input, dtype=wp.bool, device=device) @@ -828,8 +862,11 @@ def set_contacts( contact_points: wp.array, contact_mask: wp.array, local_contact_points: Optional[wp.array] = None, + contact_axes: Optional[wp.array] = None, ): - """Copy batched runtime contact data into graph-stable device buffers.""" + """Copy batched runtime contact data into graph-stable device buffers; omitted points and axes are zero. A + nonzero axis makes its contact the segment from the point along it: the link point may sit anywhere on it, e.g. + a straight move at its own pace.""" if self.device is None: self._init_buffers(contact_points.device) if contact_points.ndim == 3: @@ -842,6 +879,7 @@ def set_contacts( expected = (contact_batch, self.num_frames, self.max_contacts, 3) self.contact_points_wp = wp.zeros(expected, dtype=wp.float32, device=self.device) self.local_contact_points_wp = wp.zeros(expected, dtype=wp.float32, device=self.device) + self.contact_axes_wp = wp.zeros(expected, dtype=wp.float32, device=self.device) self.contact_mask_wp = wp.zeros(expected[:-1], dtype=wp.bool, device=self.device) expected_points_shape = (contact_batch, self.num_frames, self.max_contacts, 3) expected_mask_shape = expected_points_shape[:-1] @@ -851,19 +889,23 @@ def set_contacts( raise ValueError(f"contact_mask must have shape {expected_mask_shape}.") if contact_points.dtype != wp.float32 or contact_mask.dtype != wp.bool: raise TypeError("contact_points must be wp.float32 and contact_mask must be wp.bool.") - if local_contact_points is not None: - if local_contact_points.ndim == 3: - local_contact_points = local_contact_points.reshape((1,) + local_contact_points.shape) - if local_contact_points.shape != expected_points_shape or local_contact_points.dtype != wp.float32: - raise ValueError(f"local_contact_points must be wp.float32 with shape {expected_points_shape}.") - if any(a is not None and a.device != self.device for a in (contact_points, contact_mask, local_contact_points)): + optional = [ + a.reshape((1,) + a.shape) if a is not None and a.ndim == 3 else a + for a in (local_contact_points, contact_axes) + ] + if any(a is not None and (a.shape != expected_points_shape or a.dtype != wp.float32) for a in optional): + raise ValueError( + f"local_contact_points and contact_axes must be wp.float32 of shape {expected_points_shape}." + ) + if any(a is not None and a.device != self.device for a in (contact_points, contact_mask, *optional)): raise ValueError(f"contact inputs must be on {self.device}.") wp.copy(self.contact_points_wp, contact_points) wp.copy(self.contact_mask_wp, contact_mask) - if local_contact_points is None: - self.local_contact_points_wp.zero_() - else: - wp.copy(self.local_contact_points_wp, local_contact_points) + for buffer, value in zip((self.local_contact_points_wp, self.contact_axes_wp), optional): + if value is None: + buffer.zero_() + else: + wp.copy(buffer, value) @property def residual_dim(self) -> int: @@ -896,6 +938,7 @@ def compute_weighted_residual( inputs=[ robot_state.T_world_link, self.contact_points_wp, + self.contact_axes_wp, self.local_contact_points_wp, self.contact_link_indices_wp, self.contact_mask_wp, @@ -999,6 +1042,7 @@ def compute_weighted_sparse_jacobian_values( robot_state.T_world_link, robot_state.T_world_base, self.contact_points_wp, + self.contact_axes_wp, self.local_contact_points_wp, self.contact_link_indices_wp, self.contact_mask_wp, diff --git a/src/robokit/terms/sparse/trajectory_self_collision_task.py b/src/robokit/terms/sparse/trajectory_self_collision_task.py index 08dc2c7..994fa8c 100644 --- a/src/robokit/terms/sparse/trajectory_self_collision_task.py +++ b/src/robokit/terms/sparse/trajectory_self_collision_task.py @@ -68,6 +68,8 @@ def __init__( self.device: Optional[wp_device_type] = None self._active_pairs_wp: Optional[wp.array] = None + self.sphere_mask: Optional[wp.array] = None # (frames, spheres): 0 drops a sphere's pairs at a frame + self.pair_mask: Optional[wp.array] = None # (pairs,): 0 drops a pair def resolve(self, var_values: VarValues, context: Mapping[Context, Any]): """Build from the robot and horizon of the trajectory `var_values` holds.""" @@ -87,6 +89,10 @@ def init_buffers(self, device: wp_device_type): self.device = device self._radii_wp = wp.from_numpy(self._radii_np, dtype=wp.float32, device=device) self._no_argmax = wp.full((1, 1), -1, dtype=wp.int32, device=device) + if self.sphere_mask is None: + self.sphere_mask = wp.ones((self.num_frames, len(self._radii_np)), dtype=wp.int32, device=device) + if self.pair_mask is None: + self.pair_mask = wp.ones(max(1, self.num_pairs), dtype=wp.int32, device=device) if self.num_pairs > 0: self._active_pairs_wp = wp.from_numpy(self._active_pairs_np, dtype=wp.int32, device=device) else: @@ -119,6 +125,8 @@ def _accumulate_max_residual(self, var_values: "VarValues", out: wp.array): # n self.weight, self.use_mask, self._get_frame_mask(), + self.sphere_mask, + self.pair_mask, self.penalty == "max_linear", ], outputs=[out], @@ -170,6 +178,8 @@ def compute_weighted_residual( row_offset, self.use_mask, self._get_frame_mask(), + self.sphere_mask, + self.pair_mask, ], outputs=[out_residual, self._argmax], block_dim=_PAIR_THREADS, @@ -193,6 +203,8 @@ def compute_weighted_residual( self.num_pairs, self.use_mask, self._get_frame_mask(), + self.sphere_mask, + self.pair_mask, ], outputs=[out_residual], device=kernel_device, @@ -301,6 +313,8 @@ def compute_weighted_sparse_jacobian_values( nnz_offset, self.use_mask, self._get_frame_mask(), + self.sphere_mask, + self.pair_mask, self._argmax if self._argmax is not None else self._no_argmax, self.penalty == "max_linear", ], @@ -323,6 +337,8 @@ def compute_self_collision_residual_kernel( num_pairs: int, use_mask: wp.bool, frame_mask: wp.array2d(dtype=wp.uint8), + sphere_mask: wp.array2d(dtype=wp.int32), + pair_mask: wp.array1d(dtype=wp.int32), out_residual: wp.array2d(dtype=wp.float32), ): batch_idx, frame_idx, pair_idx = wp.tid() # pyright: ignore[reportAssignmentType] @@ -333,9 +349,9 @@ def compute_self_collision_residual_kernel( diff = sphere_centers[batch_idx, frame_idx, sphere_i] - sphere_centers[batch_idx, frame_idx, sphere_j] surface_dist = wp.length(diff) - collision_sphere_radii[sphere_i] - collision_sphere_radii[sphere_j] penetration = wp.max(0.0, margin - surface_dist) - mask = wp.float32(1.0) + mask = wp.float32(sphere_mask[frame_idx, sphere_i] * sphere_mask[frame_idx, sphere_j] * pair_mask[pair_idx]) if use_mask: - mask = wp.float32(frame_mask[batch_idx, frame_idx]) + mask *= wp.float32(frame_mask[batch_idx, frame_idx]) residual_idx = frame_idx * num_pairs + pair_idx out_residual[batch_idx, row_offset + residual_idx] = weight * penetration * mask @@ -355,6 +371,8 @@ def _deepest_pair_kernel( row_offset: int, use_mask: wp.bool, frame_mask: wp.array2d(dtype=wp.uint8), + sphere_mask: wp.array2d(dtype=wp.int32), + pair_mask: wp.array1d(dtype=wp.int32), out_residual: wp.array2d(dtype=wp.float32), argmax: wp.array2d(dtype=wp.int32), ): @@ -369,7 +387,8 @@ def _deepest_pair_kernel( sphere_j = active_pairs[pair, 1] diff = sphere_centers[batch_idx, frame_idx, sphere_i] - sphere_centers[batch_idx, frame_idx, sphere_j] penetration = margin - (wp.length(diff) - collision_sphere_radii[sphere_i] - collision_sphere_radii[sphere_j]) - if penetration > deepest: + on = sphere_mask[frame_idx, sphere_i] * sphere_mask[frame_idx, sphere_j] * pair_mask[pair] + if penetration > deepest and on != 0: deepest = penetration best = pair lane_deepest = wp.tile(deepest) @@ -397,6 +416,8 @@ def _max_residual_kernel( weight: float, use_mask: wp.bool, frame_mask: wp.array2d(dtype=wp.uint8), + sphere_mask: wp.array2d(dtype=wp.int32), + pair_mask: wp.array1d(dtype=wp.int32), max_linear: wp.bool, out: wp.array1d(dtype=wp.float32), ): @@ -412,7 +433,8 @@ def _max_residual_kernel( i, j = active_pairs[pair, 0], active_pairs[pair, 1] diff = sphere_centers[batch, frame, i] - sphere_centers[batch, frame, j] penetration = margin - (wp.length(diff) - radii[i] - radii[j]) - deepest = wp.where(penetration > deepest, penetration, deepest) + if sphere_mask[frame, i] * sphere_mask[frame, j] * pair_mask[pair] != 0: + deepest = wp.where(penetration > deepest, penetration, deepest) deepest = wp.max(0.0, wp.tile_extract(wp.tile_max(wp.tile(deepest)), 0)) if lane == 0: value = weight * deepest * mask @@ -575,6 +597,8 @@ def compute_self_collision_jacobian_values_kernel( nnz_offset: int, use_mask: wp.bool, frame_mask: wp.array2d(dtype=wp.uint8), + sphere_mask: wp.array2d(dtype=wp.int32), + pair_mask: wp.array1d(dtype=wp.int32), argmax: wp.array2d(dtype=wp.int32), max_linear: wp.bool, values: wp.array2d(dtype=wp.float32), @@ -592,9 +616,9 @@ def compute_self_collision_jacobian_values_kernel( sphere_i = active_pairs[pair, 0] sphere_j = active_pairs[pair, 1] - mask = wp.float32(1.0) + mask = wp.float32(sphere_mask[frame_idx, sphere_i] * sphere_mask[frame_idx, sphere_j] * pair_mask[pair]) if use_mask: - mask = wp.float32(frame_mask[batch_idx, frame_idx]) + mask *= wp.float32(frame_mask[batch_idx, frame_idx]) values[batch_idx, nnz_idx] = mask * _pair_jacobian_value_func( S_world, sphere_centers, diff --git a/src/robokit/terms/sparse/trajectory_smoothness_task.py b/src/robokit/terms/sparse/trajectory_smoothness_task.py index ee8a2f6..134ebe9 100644 --- a/src/robokit/terms/sparse/trajectory_smoothness_task.py +++ b/src/robokit/terms/sparse/trajectory_smoothness_task.py @@ -128,11 +128,7 @@ def compute_paths( weight: float = 0.08, count: int = 1, ) -> np.ndarray: - """Return [K,T,J] paths, preserving alternative initial pose hypotheses. - - Each initial hypothesis retains a distinct branch; the output contains at most `count` paths. - Periodic joints use angular distances and return continuous equivalent angles within supplied limits. - If no continuous lift fits the limits, the original bounded path is retained. + """Return [K,T,J] paths, preserving alternative initial pose hypotheses; each initial hypothesis retains a distinct branch, and the output contains at most `count` paths; periodic joints use angular distances and return continuous equivalent angles within supplied limits; if no continuous lift fits the limits, the original bounded path is retained. >>> q = np.array([[[0.], [3.]], [[3.], [0.1]], [[0.2], [3.]]]) >>> TrajectorySmoothnessTask().compute_paths(q, np.array([[0., .1], [.1, 0.], [0., .1]]), np.arange(3.)).ravel().tolist() @@ -186,10 +182,7 @@ def compute_paths( return np.stack(paths) def compute_offset_candidates(self, q: np.ndarray, samples: int = 16) -> np.ndarray: - """Sample constant joint shifts that preserve every frame's joint limits. - - Full-turn joints need at most one revolution; extra cubic samples retain small shifts. - """ + """Sample constant joint shifts that preserve every frame's joint limits; full-turn joints need at most one revolution, and extra cubic samples retain small shifts.""" if self.robot is None: raise ValueError("joint offset candidates require a robot") periodic = cast(np.ndarray, self._periodic_joints) diff --git a/src/robokit/terms/task.py b/src/robokit/terms/task.py index 36752dc..2aedc26 100644 --- a/src/robokit/terms/task.py +++ b/src/robokit/terms/task.py @@ -102,8 +102,7 @@ def precompute(self, var_values: VarValues, need_gradient: bool = False): pass def compute_weighted_cost(self, var_values: Optional[VarValues], *, out_cost: wp.array): - """Add each row's weighted cost into `out_cost`, for a term without residuals (a simulated rollout, or one of - its per-step costs); `PopulationSolver` calls it on every term that is not a `ResidualTask`.""" + """Add each row's weighted cost into `out_cost`, for a term without residuals (a simulated rollout, or one of its per-step costs); `PopulationSolver` calls it on every term that is not a `ResidualTask`.""" raise NotImplementedError(f"{type(self).__name__} has no cost-only evaluation") diff --git a/src/robokit/utils/warp_utils.py b/src/robokit/utils/warp_utils.py index 513e5a8..363282a 100644 --- a/src/robokit/utils/warp_utils.py +++ b/src/robokit/utils/warp_utils.py @@ -167,6 +167,17 @@ def _gather_2d_kernel( out[tid, j] = source[indices[tid], j] +# Warp 1.18's CPU replay finds a kernel by name, so one capture mixing a generic kernel's dtypes runs the wrong one. +@wp.kernel +def _gather_2d_vec7_kernel( + source: wp.array2d(dtype=wp_vec7f), + indices: wp.array1d(dtype=wp.int32), + out: wp.array2d(dtype=wp_vec7f), +): + tid, j = wp.tid() # pyright: ignore[reportAssignmentType] + out[tid, j] = source[indices[tid], j] + + @wp.kernel def _gather_3d_kernel( source: wp.array3d(dtype=Any), @@ -380,8 +391,7 @@ def _masked_copy_kernel( out[tid, i, j, k] = source[tid, i, j, k] -# Overload the generic kernels for every dtype robokit uses up front: a later overload rehashes the module, -# making its Warp kernel-cache key depend on which dtypes a process happened to launch first. +# Overload the generic kernels for every dtype robokit uses up front: a later overload rehashes the module, making its Warp kernel-cache key depend on which dtypes a process happened to launch first. for _kernel in [k for k in list(globals().values()) if isinstance(k, wp.Kernel) and k.is_generic]: _generic_args = [a for a in _kernel.adj.args if getattr(a.type, "dtype", None) is Any] for _dtype in (wp.float32, wp.int32, wp.uint32, wp.vec3f, wp_vec7f): @@ -458,7 +468,8 @@ def gather(source: wp.array, indices: wp.array, out: Optional[wp.array] = None) if source.ndim == 1: source_2d = source.reshape((source.shape[0], 1)) dest_2d = out.reshape((num_gather, 1)) - wp.launch(_gather_2d_kernel, dim=(num_gather, 1), inputs=[source_2d, indices, dest_2d], device=device) + kernel = _gather_2d_vec7_kernel if source.dtype == wp_vec7f else _gather_2d_kernel + wp.launch(kernel, dim=(num_gather, 1), inputs=[source_2d, indices, dest_2d], device=device) elif source.ndim == 2: wp.launch(_gather_2d_kernel, dim=(num_gather, source.shape[1]), inputs=[source, indices, out], device=device) elif source.ndim == 3: diff --git a/src/robokit/xform/numpy/rotation_conversions.py b/src/robokit/xform/numpy/rotation_conversions.py index c5048d8..a1d9575 100644 --- a/src/robokit/xform/numpy/rotation_conversions.py +++ b/src/robokit/xform/numpy/rotation_conversions.py @@ -58,8 +58,7 @@ def normalize_quaternion(q_wxyz: Float[np.ndarray, "... 4"]) -> Float[np.ndarray Normalize quaternions to unit length. Args: - q_wxyz: a numpy array of shape (..., 4), where the last dimension - represents the quaternion components [w, x, y, z]. + q_wxyz: a numpy array of shape (..., 4), where the last dimension represents the quaternion components [w, x, y, z]. Returns: A numpy array of shape (..., 4) with unit-norm quaternions. @@ -80,12 +79,10 @@ def standardize_quaternion(q_wxyz: Float[np.ndarray, "... 4"]) -> Float[np.ndarr Convert a unit quaternion to a standard form: one in which the real part is non-negative. Args: - q_wxyz: a numpy array of shape (..., 4), where the last dimension - represents the quaternion components [w, x, y, z]. + q_wxyz: a numpy array of shape (..., 4), where the last dimension represents the quaternion components [w, x, y, z]. Returns: - A numpy array with shape of (..., 4) representing the quaternion components - [w, x, y, z]. + A numpy array with shape of (..., 4) representing the quaternion components [w, x, y, z]. Example: >>> q_wxyz = np.array([[0.0, -0.7071, 0.0, 0.7071], [-0.7071, 0.0, 0.7071, 0.0]]) @@ -104,8 +101,7 @@ def matrix_to_axis_angle(rot_mat: Float[np.ndarray, "... 3 3"]) -> Float[np.ndar rot_mat: Rotation matrices with shape (..., 3, 3). Returns: - Axis-angle representation with shape (..., 3) where the magnitude - represents the rotation angle and the direction represents the rotation axis. + Axis-angle representation with shape (..., 3) where the magnitude represents the rotation angle and the direction represents the rotation axis. Example: >>> rot_mat = np.array([[1., 0., 0.], [0., 0., -1.], [0., 1., 0.]]) @@ -173,13 +169,10 @@ def axis_angle_to_matrix(axis_angle: Float[np.ndarray, "... 3"]) -> Float[np.nda Convert an axis-angle representation to a 3x3 rotation matrix. Args: - axis_angle: A numpy array of shape (..., 3) representing a vector in - axis-angle format where the direction indicates the axis of rotation - and the magnitude represents the rotation angle in radians. + axis_angle: A numpy array of shape (..., 3) representing a vector in axis-angle format where the direction indicates the axis of rotation and the magnitude represents the rotation angle in radians. Returns: - A numpy array of shape (..., 3, 3) representing the rotation matrices - corresponding to each axis-angle input. + A numpy array of shape (..., 3, 3) representing the rotation matrices corresponding to each axis-angle input. Example: >>> axis_angle = np.array([np.pi/2, 0., 0.]) @@ -198,8 +191,7 @@ def euler_angles_to_matrix( Args: euler_angles: angles in radians, in shape of (..., 3). - axes: "s" (static/extrinsic) or "r" (rotating/intrinsic) plus an axis sequence, e.g. "sxyz" or "rxyz"; - three-character forms get a leading "s". + axes: "s" (static/extrinsic) or "r" (rotating/intrinsic) plus an axis sequence, e.g. "sxyz" or "rxyz"; three-character forms get a leading "s". Returns: rotation matrices, in shape of (..., 3, 3). @@ -232,13 +224,10 @@ def matrix_to_euler_angles(rot_mat: Float[np.ndarray, "... 3 3"], axes: str = "s Args: rot_mat: rotation matrices, in shape of (..., 3, 3). - axes: "s" (static/extrinsic) or "r" (rotating/intrinsic) plus an axis sequence, e.g. "sxyz" or "rxyz"; - three-character forms get a leading "s". + axes: "s" (static/extrinsic) or "r" (rotating/intrinsic) plus an axis sequence, e.g. "sxyz" or "rxyz"; three-character forms get a leading "s". Returns: - angles in radians, in shape of (..., 3). As in scipy, the middle angle lies in [-pi/2, pi/2] for - Tait-Bryan axes (e.g. "sxyz") and in [0, pi] for proper Euler axes (e.g. "szxz"), the others in - [-pi, pi], and the third angle is zero at gimbal lock. + angles in radians, in shape of (..., 3). As in scipy, the middle angle lies in [-pi/2, pi/2] for Tait-Bryan axes (e.g. "sxyz") and in [0, pi] for proper Euler axes (e.g. "szxz"), the others in [-pi, pi], and the third angle is zero at gimbal lock. Example: >>> angles = np.array([1.0, 0.5, 2.0]) @@ -380,14 +369,11 @@ def quaternion_multiply( Multiply two quaternions (Hamilton product) and standardize the result. Args: - q_wxyz_1: a numpy array of shape (..., 4), where the last dimension - represents the quaternion components [w, x, y, z]. - q_wxyz_2: a numpy array of shape (..., 4), where the last dimension - represents the quaternion components [w, x, y, z]. + q_wxyz_1: a numpy array of shape (..., 4), where the last dimension represents the quaternion components [w, x, y, z]. + q_wxyz_2: a numpy array of shape (..., 4), where the last dimension represents the quaternion components [w, x, y, z]. Returns: - A numpy array with shape of (..., 4) representing the quaternion components - [w, x, y, z]. + A numpy array with shape of (..., 4) representing the quaternion components [w, x, y, z]. Example: >>> a = np.array([0.9238795, 0.0, 0.0, 0.3826834]) diff --git a/src/robokit/xform/numpy/transforms.py b/src/robokit/xform/numpy/transforms.py index d30331c..57a8088 100644 --- a/src/robokit/xform/numpy/transforms.py +++ b/src/robokit/xform/numpy/transforms.py @@ -184,11 +184,7 @@ def rotate_points( def project_points( pts: Float[np.ndarray, "... n 3"], intrinsic: Float[np.ndarray, "... 3 3"] ) -> Float[np.ndarray, "... n 2"]: - """Project camera-frame 3D points to pixels with pinhole intrinsics (OpenCV axes: x right, y down, z forward). - - Depth is clamped at 1e-3 m (`u = fx x / max(z, 1e-3) + cx`), so points at or behind the camera stay finite. - World points project as - `project_points(transform_points(pts, T_camera_world), intrinsic)`. + """Project camera-frame 3D points to pixels with pinhole intrinsics (OpenCV axes: x right, y down, z forward). Depth is clamped at 1e-3 m (`u = fx x / max(z, 1e-3) + cx`), so points at or behind the camera stay finite. World points project as `project_points(transform_points(pts, T_camera_world), intrinsic)`. Args: pts (np.ndarray): Camera-frame 3D points in shape [... n 3]. diff --git a/src/robokit/xform/warp/rotation_conversions.py b/src/robokit/xform/warp/rotation_conversions.py index 9d7cc4c..60a090d 100644 --- a/src/robokit/xform/warp/rotation_conversions.py +++ b/src/robokit/xform/warp/rotation_conversions.py @@ -2,37 +2,40 @@ # pyright: reportArgumentType=false # pyright: reportIndexIssue=false # pyright: reportCallIssue=false +from typing import Any + import warp as wp -@wp.kernel -def axis_angle_to_quaternion_kernel(axis_angle: wp.array(dtype=wp.vec3), quat_wxyz: wp.array(dtype=wp.vec4)): - """Warp kernel to convert axis-angle to quaternion.""" - tid = wp.tid() - - axis_angle_vec = axis_angle[tid] +@wp.func +def axis_angle_to_quaternion_func(axis_angle_vec: wp.vec3) -> wp.vec4: + """Convert an axis-angle vector to a quaternion (wxyz).""" angle = wp.length(axis_angle_vec) eps = 1e-6 if angle < eps: - # small angle approximation: q ≈ [1, axis_angle/2] - # use Taylor series: sin(x/2) ≈ x/2 - x³/48 for small x + # small angle approximation q ≈ [1, axis_angle/2], via the Taylor series sin(x/2) ≈ x/2 - x³/48 for small x angle_sq = angle * angle scale = 0.5 - angle_sq / 48.0 - quat_wxyz[tid] = wp.vec4( + return wp.vec4( 1.0 - angle_sq / 8.0, # cos(angle/2) ≈ 1 - x²/8 axis_angle_vec[0] * scale, axis_angle_vec[1] * scale, axis_angle_vec[2] * scale, ) - else: - # standard conversion - axis = axis_angle_vec / angle - half_angle = angle * 0.5 - sin_half = wp.sin(half_angle) - cos_half = wp.cos(half_angle) + # standard conversion + axis = axis_angle_vec / angle + half_angle = angle * 0.5 + sin_half = wp.sin(half_angle) + cos_half = wp.cos(half_angle) + return wp.vec4(cos_half, axis[0] * sin_half, axis[1] * sin_half, axis[2] * sin_half) - quat_wxyz[tid] = wp.vec4(cos_half, axis[0] * sin_half, axis[1] * sin_half, axis[2] * sin_half) + +@wp.kernel +def axis_angle_to_quaternion_kernel(axis_angle: wp.array(dtype=wp.vec3), quat_wxyz: wp.array(dtype=wp.vec4)): + """Warp kernel to convert axis-angle to quaternion.""" + tid = wp.tid() + quat_wxyz[tid] = axis_angle_to_quaternion_func(axis_angle[tid]) @wp.func @@ -208,8 +211,9 @@ def quaternion_apply_kernel( @wp.func -def quaternion_invert_func(quat_wxyz: wp.vec4) -> wp.vec4: - return wp.vec4(quat_wxyz[0], -quat_wxyz[1], -quat_wxyz[2], -quat_wxyz[3]) +def quaternion_invert_func(quat_wxyz: Any): + """Conjugate a unit quaternion (wxyz), float32 or float64.""" + return wp.vector(quat_wxyz[0], -quat_wxyz[1], -quat_wxyz[2], -quat_wxyz[3]) @wp.kernel @@ -222,19 +226,20 @@ def quaternion_invert_kernel( @wp.func -def quaternion_to_axis_angle_func(quat_wxyz: wp.vec4) -> wp.vec3: +def quaternion_to_axis_angle_func(quat_wxyz: Any): + """Convert a quaternion (wxyz), float32 or float64, to an axis-angle vector.""" w = quat_wxyz[0] - xyz = wp.vec3(quat_wxyz[1], quat_wxyz[2], quat_wxyz[3]) + xyz = wp.vector(quat_wxyz[1], quat_wxyz[2], quat_wxyz[3]) norm = wp.length(xyz) half_angle = wp.atan2(norm, w) - angle = 2.0 * half_angle - eps = 1e-6 + angle = type(w)(2.0) * half_angle + eps = type(w)(1e-6) small_angle = wp.abs(angle) < eps if small_angle: # for small angles, sin(half_angle) ≈ half_angle - half_angle^3/6, so sin(half_angle)/angle ≈ 0.5 - angle^2/48 - sin_half_angle_over_angle = 0.5 - (angle * angle) / 48.0 + sin_half_angle_over_angle = type(w)(0.5) - (angle * angle) / type(w)(48.0) else: sin_half_angle = wp.sin(half_angle) sin_half_angle_over_angle = sin_half_angle / angle @@ -252,17 +257,17 @@ def quaternion_to_axis_angle_kernel( @wp.func -def standardize_quaternion_func(quat_wxyz: wp.vec4) -> wp.vec4: +def standardize_quaternion_func(quat_wxyz: Any): """Standardize quaternion to have non-negative real part.""" # assumes wxyz format - if quat_wxyz[0] < 0.0: + if quat_wxyz[0] < type(quat_wxyz[0])(0.0): return -quat_wxyz return quat_wxyz @wp.func -def quaternion_multiply_func(quat_wxyz1: wp.vec4, quat_wxyz2: wp.vec4) -> wp.vec4: - """Multiply two quaternions (assumes wxyz format).""" +def quaternion_multiply_func(quat_wxyz1: Any, quat_wxyz2: Any): + """Multiply two quaternions (wxyz), float32 or float64, and standardize the result.""" w1, x1, y1, z1 = quat_wxyz1[0], quat_wxyz1[1], quat_wxyz1[2], quat_wxyz1[3] w2, x2, y2, z2 = quat_wxyz2[0], quat_wxyz2[1], quat_wxyz2[2], quat_wxyz2[3] @@ -271,7 +276,7 @@ def quaternion_multiply_func(quat_wxyz1: wp.vec4, quat_wxyz2: wp.vec4) -> wp.vec y = w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2 z = w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2 - return standardize_quaternion_func(wp.vec4(w, x, y, z)) + return standardize_quaternion_func(wp.vector(w, x, y, z)) @wp.kernel diff --git a/src/robokit/xform/warp/torch_wrappers.py b/src/robokit/xform/warp/torch_wrappers.py index 11b36c7..8702707 100644 --- a/src/robokit/xform/warp/torch_wrappers.py +++ b/src/robokit/xform/warp/torch_wrappers.py @@ -29,8 +29,7 @@ def axis_angle_to_matrix(axis_angle: Float[torch.Tensor, "... 3"]) -> Float[torc Convert rotations given as axis/angle to rotation matrices. Args: - axis_angle (torch.Tensor): Rotation vectors with shape [..., 3], whose magnitude is the angle in radians - turned anticlockwise around their direction. + axis_angle (torch.Tensor): Rotation vectors with shape [..., 3], whose magnitude is the angle in radians turned anticlockwise around their direction. Returns: torch.Tensor: Rotation matrices [..., 3, 3]. @@ -108,10 +107,7 @@ def axis_angle_to_quaternion(axis_angle: Float[torch.Tensor, "... 3"]) -> Float[ Convert rotations given as axis/angle to quaternions using Warp. Args: - axis_angle: Rotations given as a vector in axis angle form, - as a tensor of shape (..., 3), where the magnitude is - the angle turned anticlockwise in radians around the - vector's direction. + axis_angle: Rotations given as a vector in axis angle form, as a tensor of shape (..., 3), where the magnitude is the angle turned anticlockwise in radians around the vector's direction. Returns: quaternions with real part first, as tensor of shape (..., 4). @@ -287,9 +283,7 @@ def matrix_to_euler_angles( axes (str): One of 24 axis sequences, e.g. "sxyz"; three-character forms get a leading "s". Returns: - torch.Tensor: Euler angles with shape [..., 3]. As in scipy, the middle angle lies in [-pi/2, pi/2] for - Tait-Bryan axes and in [0, pi] for proper Euler axes, the others in [-pi, pi], and the third angle is - zero at gimbal lock, where the gradient is undefined. + torch.Tensor: Euler angles with shape [..., 3]. As in scipy, the middle angle lies in [-pi/2, pi/2] for Tait-Bryan axes and in [0, pi] for proper Euler axes, the others in [-pi, pi], and the third angle is zero at gimbal lock, where the gradient is undefined. Example: >>> euler_angles = torch.tensor([1.0, 0.5, 2.0]) @@ -395,9 +389,7 @@ def matrix_to_quaternion(rot_mat: Float[torch.Tensor, "... 3 3"]) -> Float[torch tensor([0.4671, 0.3940, 0.1503, 0.7772]) Note: - The gradient of this function differs from the pytorch3d implementation, but it - should be okay for most use cases. See - https://github.com/facebookresearch/pytorch3d/issues/503#issuecomment-755493515. + The gradient of this function differs from the pytorch3d implementation, but it should be okay for most use cases. See https://github.com/facebookresearch/pytorch3d/issues/503#issuecomment-755493515. """ return MatrixToQuaternion.apply(rot_mat) # type: ignore @@ -710,10 +702,7 @@ def quaternion_to_axis_angle(q_wxyz: Float[torch.Tensor, "... 4"]) -> Float[torc q_wxyz: quaternions with shape (..., 4) in wxyz format. Returns: - Rotations given as a vector in axis angle form, as a tensor - of shape (..., 3), where the magnitude is the angle - turned anticlockwise in radians around the vector's - direction. + Rotations given as a vector in axis angle form, as a tensor of shape (..., 3), where the magnitude is the angle turned anticlockwise in radians around the vector's direction. Example: >>> q_wxyz = torch.tensor([0.7071, 0.7071, 0.0, 0.0]) @@ -841,8 +830,7 @@ def rotation_between_vectors( dst (torch.Tensor): Destination vectors with shape [..., 3]; only their direction is used. Returns: - torch.Tensor: Rotation matrices [..., 3, 3] with `rot_mat @ src` parallel to `dst`; a half turn for - opposite vectors. + torch.Tensor: Rotation matrices [..., 3, 3] with `rot_mat @ src` parallel to `dst`; a half turn for opposite vectors. Example: >>> rot_mat = rotation_between_vectors(torch.tensor([0.0, 0.0, 1.0]), torch.tensor([1.0, 0.0, 0.0])) @@ -956,11 +944,7 @@ def transform_points( [6., 8., 7.]]) Note: - The dimension number of `pts` and `tf_mat` should be the same. The batch dimensions (...) are broadcast - (https://pytorch.org/docs/stable/notes/broadcasting.html; thus must be broadcastable). We don't adopt the - shapes [... 3] and [... 4 4] because there is no real broadcasted vector-matrix multiplication in pytorch. - [... 3] and [... 4 4] will be converted to [... 1 3] and [... 4 4] and apply a broadcasted matrix-matrix - multiplication. + The dimension number of `pts` and `tf_mat` should be the same. The batch dimensions (...) are broadcast (https://pytorch.org/docs/stable/notes/broadcasting.html; thus must be broadcastable). We don't adopt the shapes [... 3] and [... 4 4] because there is no real broadcasted vector-matrix multiplication in pytorch. [... 3] and [... 4 4] will be converted to [... 1 3] and [... 4 4] and apply a broadcasted matrix-matrix multiplication. """ if pts.device != tf_mat.device: raise ValueError(f"pts and tf_mat must be on the same device, got {pts.device} and {tf_mat.device}") diff --git a/tests/conftest.py b/tests/conftest.py index 86e1086..d12c88b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,5 +1,7 @@ """Session-scoped robot fixtures shared across the entire test suite.""" +import sys +import types from pathlib import Path from typing import Sequence @@ -102,6 +104,20 @@ def allegro_hand_robot(): return Robot.load(load_robot_description("allegro_hand_description")) +@pytest.fixture +def franka_assets(monkeypatch: pytest.MonkeyPatch): + """robokit's Franka asset module, pointed at local fixtures so no test fetches it from the Hub.""" + from robokit.assets.robots import arms + + module = types.ModuleType("robokit.assets.robots.arms.franka_panda") + module.URDF_PATH = _FIXTURES / "franka_panda_v2.urdf" # mesh files absent: the demos load it without meshes + module.COLLISION_SPHERE_PATH = _FIXTURES / "franka_panda_collision_spheres.yaml" + module.SPHERE_SELF_COLLISION_IGNORE_PATH = _FIXTURES / "franka_self_collision_ignore.yml" + monkeypatch.setitem(sys.modules, module.__name__, module) + monkeypatch.setattr(arms, "franka_panda", module, raising=False) + return module + + @pytest.fixture(scope="session") def robot(request: pytest.FixtureRequest) -> Robot: """Robot chosen by indirect parametrization, e.g. `parametrize("robot", ["panda_description"], indirect=True)`.""" diff --git a/tests/fixtures/franka_panda_collision_spheres.yaml b/tests/fixtures/franka_panda_collision_spheres.yaml new file mode 100644 index 0000000..2df9cee --- /dev/null +++ b/tests/fixtures/franka_panda_collision_spheres.yaml @@ -0,0 +1,164 @@ +## +## Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +## +## NVIDIA CORPORATION, its affiliates and licensors retain all intellectual +## property and proprietary rights in and to this material, related +## documentation and any modifications thereto. Any use, reproduction, +## disclosure or distribution of this material and related documentation +## without an express license agreement from NVIDIA CORPORATION or +## its affiliates is strictly prohibited. +## +robot: 'Franka Panda' +urdf_path: "urdf/franka_description/franka_panda_dyn.urdf" +collision_spheres: + panda_link0: + - "center": [-0.08, 0.0, 0.05] + "radius": 0.06 + - "center": [-0.0, 0.0, 0.05] + "radius": 0.08 + panda_link1: + - "center": [0.0, -0.08, 0.0] + "radius": 0.06 + - "center": [0.0, -0.03, 0.0] + "radius": 0.06 + - "center": [0.0, 0.0, -0.12] + "radius": 0.06 + - "center": [0.0, 0.0, -0.17] + "radius": 0.06 + panda_link2: + - "center": [0.0, 0.0, 0.03] + "radius": 0.06 + - "center": [0.0, 0.0, 0.08] + "radius": 0.06 + - "center": [0.0, -0.12, 0.0] + "radius": 0.06 + - "center": [0.0, -0.17, 0.0] + "radius": 0.06 + panda_link3: + - "center": [0.0, 0.0, -0.06] + "radius": 0.05 + - "center": [0.0, 0.0, -0.1] + "radius": 0.06 + - "center": [0.08, 0.06, 0.0] + "radius": 0.055 + - "center": [0.08, 0.02, 0.0] + "radius": 0.055 + panda_link4: + - "center": [0.0, 0.0, 0.02] + "radius": 0.055 + - "center": [0.0, 0.0, 0.06] + "radius": 0.055 + - "center": [-0.08, 0.095, 0.0] + "radius": 0.06 + - "center": [-0.08, 0.06, 0.0] + "radius": 0.055 + panda_link5: + - "center": [0.0, 0.055, 0.0] + "radius": 0.05 + - "center": [0.0, 0.085, 0.0] + "radius": 0.055 + - "center": [0.0, 0.000, -0.22] + "radius": 0.05 + - "center": [0.0, 0.05, -0.18] + "radius": 0.045 + - "center": [0.015, 0.08, -0.14] + "radius": 0.03 + - "center": [0.015, 0.085, -0.11] + "radius": 0.03 + - "center": [0.015, 0.09, -0.08] + "radius": 0.03 + - "center": [0.015, 0.095, -0.05] + "radius": 0.03 + - "center": [-0.015, 0.08, -0.14] + "radius": 0.03 + - "center": [-0.015, 0.085, -0.11] + "radius": 0.03 + - "center": [-0.015, 0.09, -0.08] + "radius": 0.03 + - "center": [-0.015, 0.095, -0.05] + "radius": 0.03 + panda_link6: + - "center": [0.0, 0.0, 0.0] + "radius": 0.05 + - "center": [0.08, 0.035, 0.0] + "radius": 0.05 + - "center": [0.08, -0.01, 0.0] + "radius": 0.05 + panda_link7: + - "center": [0.0, 0.0, 0.07] + "radius": 0.05 + - "center": [0.02, 0.04, 0.08] + "radius": 0.025 + - "center": [0.04, 0.02, 0.08] + "radius": 0.025 + - "center": [0.04, 0.06, 0.085] + "radius": 0.02 + - "center": [0.06, 0.04, 0.085] + "radius": 0.02 + panda_hand: + - "center": [0.0, -0.075, 0.01] + "radius": 0.03 + - "center": [0.0, -0.045, 0.01] + "radius": 0.03 + - "center": [0.0, -0.015, 0.01] + "radius": 0.03 + - "center": [0.0, 0.015, 0.01] + "radius": 0.03 + - "center": [0.0, 0.045, 0.01] + "radius": 0.03 + - "center": [0.0, 0.075, 0.01] + "radius": 0.03 + - "center": [0.0, 0.065, -0.02] + "radius": 0.03 + - "center": [0.0, -0.075, 0.03] + "radius": 0.03 + - "center": [0.0, -0.045, 0.03] + "radius": 0.03 + - "center": [0.0, -0.015, 0.03] + "radius": 0.03 + - "center": [0.0, 0.015, 0.03] + "radius": 0.03 + - "center": [0.0, 0.045, 0.03] + "radius": 0.03 + - "center": [0.0, 0.075, 0.03] + "radius": 0.03 + - "center": [0.0, -0.075, 0.05] + "radius": 0.02 + - "center": [0.0, -0.045, 0.05] + "radius": 0.02 + - "center": [0.0, -0.015, 0.05] + "radius": 0.02 + - "center": [0.0, 0.015, 0.05] + "radius": 0.02 + - "center": [0.0, 0.045, 0.05] + "radius": 0.02 + - "center": [0.0, 0.075, 0.05] + "radius": 0.02 + panda_leftfinger: + # - "center": [0.0, 0.01, 0.04] + # "radius": 0.01 + # - "center": [0.0, 0.01, 0.014] + # "radius": 0.01 + - "center": [0.0, 0.007, 0.045] + "radius": 0.01 + - "center": [0.0, 0.02, 0.014] + "radius": 0.01 + panda_rightfinger: + # - "center": [0.0, -0.01, 0.04] + # "radius": 0.01 + # - "center": [0.0, -0.01, 0.014] + # "radius": 0.01 + - "center": [0.0, -0.007, 0.045] + "radius": 0.01 + - "center": [0.0, -0.02, 0.014] + "radius": 0.01 + attached_object: + - "center": [0.0, 0.0, 0.0] + "radius": -10.0 + - "center": [0.0, 0.0, 0.0] + "radius": -10.0 + - "center": [0.0, 0.0, 0.0] + "radius": -10.0 + - "center": [0.0, 0.0, 0.0] + "radius": -10.0 + \ No newline at end of file diff --git a/tests/fixtures/franka_panda_v2.urdf b/tests/fixtures/franka_panda_v2.urdf new file mode 100644 index 0000000..4196ed6 --- /dev/null +++ b/tests/fixtures/franka_panda_v2.urdf @@ -0,0 +1,351 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/fixtures/franka_self_collision_ignore.yml b/tests/fixtures/franka_self_collision_ignore.yml new file mode 100644 index 0000000..740de37 --- /dev/null +++ b/tests/fixtures/franka_self_collision_ignore.yml @@ -0,0 +1,47 @@ +# self-collision ignore set: skip these link pairs during self-collision checking. +# backend: sphere | samples: 10000 | always_frac: 1.0 | joint_padding: 0.1 +self_collision_ignore: + panda_hand: + - panda_leftfinger # Adjacent + - panda_rightfinger # Adjacent + panda_leftfinger: + - panda_rightfinger # Default + panda_link0: + - panda_link1 # Adjacent + - panda_link2 # Never + - panda_link3 # Never + - panda_link4 # Never + panda_link1: + - panda_link2 # Adjacent + - panda_link3 # Never + - panda_link4 # Never + panda_link2: + - panda_link3 # Adjacent + - panda_link4 # Never + panda_link3: + - panda_hand # Never + - panda_leftfinger # Never + - panda_link4 # Adjacent + - panda_link5 # Never + - panda_link6 # Never + - panda_link7 # Never + - panda_rightfinger # Never + panda_link4: + - panda_hand # Never + - panda_leftfinger # Never + - panda_link5 # Adjacent + - panda_link6 # Never + - panda_link7 # Never + - panda_rightfinger # Never + panda_link5: + - panda_hand # Default + - panda_link6 # Adjacent + panda_link6: + - panda_hand # Adjacent + - panda_leftfinger # Never + - panda_link7 # Adjacent + - panda_rightfinger # Never + panda_link7: + - panda_hand # Adjacent + - panda_leftfinger # Adjacent + - panda_rightfinger # Adjacent diff --git a/tests/geom/test_scene.py b/tests/geom/test_scene.py index 0d72dd8..deed132 100644 --- a/tests/geom/test_scene.py +++ b/tests/geom/test_scene.py @@ -308,8 +308,7 @@ def test_query_sdf_on_multi_geometry_scene_works(self): scene_offsets = wp.from_numpy(np.array([0, 3], dtype=np.int32), dtype=wp.int32, device="cpu") signed_dists, _, _ = scene.query_sdf(qp_wp, scene_offsets) signed_dists_np = signed_dists.numpy() - # [1,0,0]: sphere sdf = 0.5 (inside sphere is negative, dist from origin=1, r=0.5 → 0.5 outside) - # → min with box (dist=0.9) → 0.5. + # [1,0,0]: sphere sdf = 0.5 (inside sphere is negative, dist from origin=1, r=0.5 → 0.5 outside) → min with box (dist=0.9) → 0.5. # [0,0,0]: inside both; sphere=-0.5, box=-0.1; min = -0.5. # [0.3,0,0]: sphere=-0.2, box=0.1; min = -0.2. np.testing.assert_allclose(signed_dists_np, np.array([0.5, -0.5, -0.2]), atol=1e-5) diff --git a/tests/helpers/hand_eye_calibration/test_hec.py b/tests/helpers/hand_eye_calibration/test_hec.py index 2bec73c..0ae2909 100644 --- a/tests/helpers/hand_eye_calibration/test_hec.py +++ b/tests/helpers/hand_eye_calibration/test_hec.py @@ -10,7 +10,7 @@ from scipy.spatial.transform import Rotation from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.robo import Robot @@ -29,8 +29,8 @@ _H = _W = 128 _N_OBS = 4 _LM = LMOptimizerConfig(lm_lambda=1e-3, rho_min=1e-3) -_ONE_ITER = PopulationSolverConfig(num_iters=1, optimizer=_LM) -_TWO_LEVELS = PopulationSolverConfig(num_iters=20 + 40, select_at=[20], num_candidates=[4, 1], optimizer=_LM) +_ONE_ITER = PopulationSolverConfig(stages=[Stage(1, optimizer=_LM)]) +_TWO_LEVELS = PopulationSolverConfig(stages=[Stage(20, 4, _LM), Stage(40, 1)]) _URDF = """ @@ -349,7 +349,9 @@ def test_requires_some_target(self, toy_scene): def test_use_depth_without_depths_raises(self, toy_scene): levels = [hec_config.PyramidLevel(downscale=1, blur_sigma=0.0, patience=2, use_depth=True)] with pytest.raises(ValueError): - _solve(toy_scene, toy_scene["masks"], None, levels, PopulationSolverConfig(num_iters=5, optimizer=_LM)) + _solve( + toy_scene, toy_scene["masks"], None, levels, PopulationSolverConfig(stages=[Stage(5, optimizer=_LM)]) + ) @_REQUIRES_CUDA @@ -593,7 +595,7 @@ def test_pyramid_cost_preserves_observation_weight(self, toy_scene: dict, weight """A constant image error must keep its weight relative to non-image terms at every level.""" config = hec_config.HandEyeCalibratorConfig( levels=[hec_config.PyramidLevel(4, 0, 5), hec_config.PyramidLevel(1, 0, 5)], - solver=PopulationSolverConfig(num_iters=1, select_at=[0], num_candidates=[1, 1], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(0, 1, _LM), Stage(1)]), ) helper = hec_module.HandEyeCalibrator(config, toy_scene["robot"], toy_scene["intrinsic"], _H, _W) masks = torch.zeros_like(toy_scene["masks"]) @@ -615,7 +617,7 @@ def test_accepted_render_reuse_with_mixed_q_steps(self, offset_scene: dict): config = replace( hec_module.presets.rgb_qpos, levels=[hec_config.PyramidLevel(1, 0.0, 5)], - solver=PopulationSolverConfig(num_iters=1, num_candidates=[2], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(1, 2, _LM)]), max_restarts=0, ) helper = hec_module.HandEyeCalibrator(config, scene["robot"], scene["intrinsic"], _H, _W) @@ -654,13 +656,10 @@ def test_iou_scores_match_terminal_population(self, offset_scene, terminal_sampl config = replace( hec_module.presets.rgb_qpos, candidate_metric="iou", - levels=[hec_config.PyramidLevel(1, 0.0, 3)], - solver=PopulationSolverConfig( - num_iters=4, - num_candidates=[4], - optimizer=_LM, + levels=[hec_config.PyramidLevel(1, 0.0, 3)] * (1 + terminal_sample), + solver=PopulationSolverConfig( # Roberts samples at selects: a trailing stage samples the final population + stages=[Stage(4, 4, _LM), Stage(0)][: 1 + terminal_sample], samplers=[RobertsSamplerConfig(var_key=VarKey.QPOS_OFFSET, scale=0.2)] if terminal_sample else [], - sample_at=[4] if terminal_sample else [], ), candidate_noise_q=0.5, max_restarts=0, @@ -690,7 +689,13 @@ def test_recovery_without_initial_q(self, offset_scene, candidate_metric: str): recipe, candidate_metric=candidate_metric, max_restarts=0, - solver=replace(recipe.solver, num_candidates=[min(width, 16) for width in recipe.solver.num_candidates]), + solver=replace( + recipe.solver, + stages=[ + replace(stage, num_candidates=min(width, 16)) + for stage, width in zip(recipe.solver.stages, recipe.solver.num_candidates) + ], + ), ) helper = hec_module.HandEyeCalibrator(config, robot, offset_scene["intrinsic"], _H, _W) fitted_camera = helper.solve(camera, target_masks=masks, T_mount_base=views) @@ -757,7 +762,7 @@ def test_full_range_sampling_and_joint_limits(self, offset_scene): robot = offset_scene["robot"] config = hec_config.HandEyeCalibratorConfig( levels=[hec_config.PyramidLevel(4, 1.2, 1), hec_config.PyramidLevel(1, 0.0, 1)], - solver=replace(_TWO_LEVELS, num_iters=2, select_at=[1], num_candidates=[8, 1]), + solver=replace(_TWO_LEVELS, stages=[Stage(1, 8, _LM), Stage(1, 1)]), optimize_q=True, optimize_camera=False, max_restarts=0, @@ -858,7 +863,7 @@ def test_active_joint_limits_preserve_camera_updates(self, toy_scene: dict, uppe )[:, None] config = hec_config.QposTrajectoryCalibratorConfig( levels=[hec_config.PyramidLevel(1, 0, 5)], - solver=PopulationSolverConfig(num_iters=1, num_candidates=[1], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(1, 1, _LM)]), optimize_camera=True, ) helper = hec_module.QposTrajectoryCalibrator(config, scene["robot"], scene["intrinsic"], _H, _W) @@ -911,7 +916,7 @@ def test_offset_search_cannot_raise_native_cost(self, toy_scene: dict, monkeypat ] config = hec_config.QposTrajectoryCalibratorConfig( levels=[hec_config.PyramidLevel(1, 0, 5)], - solver=PopulationSolverConfig(num_iters=1, num_candidates=[1], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(1, 1, _LM)]), velocity_weight=0, acceleration_weight=0, ) @@ -943,7 +948,7 @@ def test_global_offset_search_uses_images(self, toy_scene: dict, monkeypatch): )[:, None] config = hec_config.QposTrajectoryCalibratorConfig( levels=[hec_config.PyramidLevel(1, 0, 5)], - solver=PopulationSolverConfig(num_iters=1, num_candidates=[1], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(1, 1, _LM)]), velocity_weight=0, acceleration_weight=0, ) @@ -974,7 +979,7 @@ def test_unobserved_joint_keeps_initial_state(self, toy_scene: dict): scene = toy_scene config = hec_config.QposTrajectoryCalibratorConfig( levels=[hec_config.PyramidLevel(1, 0, 5)], - solver=PopulationSolverConfig(num_iters=20, num_candidates=[1], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(20, 1, _LM)]), velocity_weight=0, acceleration_weight=0, ) @@ -1050,9 +1055,7 @@ def test_long_sequence_with_shared_camera_priors(self, offset_scene: dict, linea config = replace( hec_module.presets.rgb_qpos_trajectory_camera, levels=[hec_config.PyramidLevel(1, 0, 5)], - solver=PopulationSolverConfig( - num_iters=4, num_candidates=[1], optimizer=replace(_LM, linear_solver=linear_solver) - ), + solver=PopulationSolverConfig(stages=[Stage(4, 1, replace(_LM, linear_solver=linear_solver))]), ) helper = hec_module.QposTrajectoryCalibrator(config, robot, k, _H, _W) refined = helper.solve(cameras, masks, times, q=truth.clone() + 0.03) @@ -1123,7 +1126,7 @@ def test_recovers_sequence( optimize_q=True, optimize_camera=False, levels=[hec_config.PyramidLevel(4, 1.0, 5), hec_config.PyramidLevel(1, 0.0, 5)], - solver=PopulationSolverConfig(num_iters=40, select_at=[15], num_candidates=[32, 4], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(15, 32, _LM), Stage(25, 4)]), max_restarts=0, ) config = hec_config.QposTrajectoryCalibratorConfig( @@ -1136,7 +1139,7 @@ def test_recovers_sequence( acceleration_weight=0.001, optimize_camera=free_cameras, camera_prior_weight=camera_prior_weight, - solver=PopulationSolverConfig(num_iters=40, select_at=[20], num_candidates=[1, 1], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(20, 1, _LM), Stage(20)]), ) helper = hec_module.QposTrajectoryCalibrator(config, robot, intrinsics, _H, _W) # Missing view differs from an observed, explicitly empty silhouette. @@ -1296,7 +1299,7 @@ def test_unknown_sequence_with_missing_masks(self, toy_scene: dict): optimize_q=True, optimize_camera=False, levels=[hec_config.PyramidLevel(4, 1.0, 5), hec_config.PyramidLevel(1, 0.0, 5)], - solver=PopulationSolverConfig(num_iters=30, select_at=[10], num_candidates=[32, 4], optimizer=_LM), + solver=PopulationSolverConfig(stages=[Stage(10, 32, _LM), Stage(20, 4)]), max_restarts=0, keypoint_warmup_iters=8, candidate_metric="iou", diff --git a/tests/helpers/hand_eye_calibration/test_observation_reuse.py b/tests/helpers/hand_eye_calibration/test_observation_reuse.py index 1a8743b..f85e89b 100644 --- a/tests/helpers/hand_eye_calibration/test_observation_reuse.py +++ b/tests/helpers/hand_eye_calibration/test_observation_reuse.py @@ -6,7 +6,7 @@ import warp as wp from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from tests.helpers.hand_eye_calibration.test_hec import ( _H, _REQUIRES_CUDA, @@ -63,10 +63,7 @@ def test_rebuilt_and_fresh_solvers_match(self, toy_scene, mode, external_stream) hec_config.PyramidLevel(1, 0.0, 20, use_depth=mode == "rgbd"), ], solver=PopulationSolverConfig( - num_iters=6, - select_at=[3], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(early_stopping_interval=0), + stages=[Stage(3, 4, LMOptimizerConfig(early_stopping_interval=0)), Stage(3, 1)] ), optimize_q=unknown, optimize_camera=not unknown, @@ -143,7 +140,7 @@ def test_rebuilds_after_observation_or_config_change(self, toy_scene): scene = toy_scene config = hec_config.HandEyeCalibratorConfig( levels=[hec_config.PyramidLevel(1, 0.0, 10)], - solver=PopulationSolverConfig(num_iters=1, num_candidates=[1]), + solver=PopulationSolverConfig(stages=[Stage(1)]), max_restarts=0, ) helper = hec_module.HandEyeCalibrator(config, scene["robot"], scene["intrinsic"], _H, _W) diff --git a/tests/helpers/hand_retargeting/test_device_parity.py b/tests/helpers/hand_retargeting/test_device_parity.py index d78fe73..3e70259 100644 --- a/tests/helpers/hand_retargeting/test_device_parity.py +++ b/tests/helpers/hand_retargeting/test_device_parity.py @@ -14,7 +14,7 @@ HandSpec, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.robo import Robot from robokit.robo.robot_spec import RobotSpec @@ -56,7 +56,7 @@ def test_online_irregular_points(self) -> None: config = HandRetargeterOnlineConfig( base_init_sample_range=(0.0, 0.0, 0.0), solver=PopulationSolverConfig( - num_iters=1, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=0.2), cuda_graph_mode="none" + stages=[Stage(1, optimizer=LMOptimizerConfig(lm_lambda=0.2))], cuda_graph_mode="none" ), sampler=RobertsSamplerConfig(keep_first=True, scale=0.0), ) diff --git a/tests/helpers/hand_retargeting/test_hand_retargeting.py b/tests/helpers/hand_retargeting/test_hand_retargeting.py index 1db0157..427f218 100644 --- a/tests/helpers/hand_retargeting/test_hand_retargeting.py +++ b/tests/helpers/hand_retargeting/test_hand_retargeting.py @@ -6,6 +6,7 @@ import warp as wp from robokit.helpers.hand_retargeting import HandRetargeterOffline, HandRetargeterOnline, config, presets +from robokit.opt.population_solver import Stage from robokit.robo import Robot @@ -67,12 +68,7 @@ def test_fixture_topology_resolves_and_solves(self, shadow_hand_robot: Robot) -> online = presets.shadow.online damping = online.solver.optimizer # the final segment's, when it varies per segment online_solver = replace( - online.solver, - num_iters=0, - select_at=[], - num_candidates=[1], - optimizer=damping[-1] if isinstance(damping, (list, tuple)) else damping, - cuda_graph_mode="none", + online.solver, stages=[Stage(optimizer=damping[-1] if damping else None)], cuda_graph_mode="none" ) online_helper = HandRetargeterOnline(replace(online, solver=online_solver), robot, spec, device="cpu") online_helper.warmup(1) diff --git a/tests/helpers/hand_retargeting/test_online.py b/tests/helpers/hand_retargeting/test_online.py index e20f56d..55f5c3f 100644 --- a/tests/helpers/hand_retargeting/test_online.py +++ b/tests/helpers/hand_retargeting/test_online.py @@ -15,7 +15,7 @@ from robokit.helpers.hand_retargeting.online import HandRetargeterOnline from robokit.lie.se3 import se3_identity from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.opt.var_values import VarKey, VarValues from robokit.robo import Robot @@ -63,7 +63,7 @@ base_init_sample_range=(0.02, 0.02, 0.0), pinch_threshold=0.02, solver=PopulationSolverConfig( - num_iters=2, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=0.2), cuda_graph_mode="none" + stages=[Stage(2, optimizer=LMOptimizerConfig(lm_lambda=0.2))], cuda_graph_mode="none" ), sampler=RobertsSamplerConfig(keep_first=True, seed=17, scale=0.04), ) @@ -173,7 +173,7 @@ def test_batch_and_caller_output(self) -> None: **_CONFIG.__dict__, "output_ema_alpha": 1.0, "solver": PopulationSolverConfig( - num_iters=0, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=0.2), cuda_graph_mode="none" + stages=[Stage(0, optimizer=LMOptimizerConfig(lm_lambda=0.2))], cuda_graph_mode="none" ), } ) @@ -205,7 +205,7 @@ def test_direction_only_and_numpy_output(self) -> None: robot = Robot(RobotSpec.parse(_URDF, load_meshes=False, mesh_dir=None)) config = HandRetargeterOnlineConfig( solver=PopulationSolverConfig( - num_iters=0, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=0.2), cuda_graph_mode="none" + stages=[Stage(0, optimizer=LMOptimizerConfig(lm_lambda=0.2))], cuda_graph_mode="none" ) ) config.task("directions").weight = {("ffproximal", "ffmiddle", "index_base", "index_middle"): 1.0} diff --git a/tests/helpers/hand_retargeting/test_reference_origin.py b/tests/helpers/hand_retargeting/test_reference_origin.py index 0ee0fb0..fae963f 100644 --- a/tests/helpers/hand_retargeting/test_reference_origin.py +++ b/tests/helpers/hand_retargeting/test_reference_origin.py @@ -15,7 +15,7 @@ ) from robokit.helpers.hand_retargeting.presets._common import wrist_config from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.var_values import VarKey, VarValues from robokit.robo import Robot from robokit.robo.robot_spec import RobotSpec @@ -48,7 +48,7 @@ def test_tracking_without_directions_or_regularizers(self): ) config = wrist_config(spec, HandRetargeterOnlineConfig()) config.terms = [config.task("positions")] - config.solver = PopulationSolverConfig(num_iters=0, num_candidates=[1], cuda_graph_mode="none") + config.solver = PopulationSolverConfig(stages=[Stage(0)], cuda_graph_mode="none") solver = HandRetargeterOnline(config, robot, spec, device="cpu") solver.warmup(1) result = solver.solve_numpy(np.zeros((1, 2, 3), dtype=np.float32)) @@ -130,9 +130,7 @@ def test_stream_matches_manual_coordinates( config = replace( wrist_config(spec, online), reference_origin=reference_origin, - solver=PopulationSolverConfig( - num_iters=3, num_candidates=[1], optimizer=LMOptimizerConfig(), cuda_graph_mode="none" - ), + solver=PopulationSolverConfig(stages=[Stage(3, optimizer=LMOptimizerConfig())], cuda_graph_mode="none"), ) config.task("smoothness").weight = q_smoothness_weight config.task("smoothness").base_weight = 0.2 diff --git a/tests/helpers/humanoid_retargeting/test_batched_retargeting.py b/tests/helpers/humanoid_retargeting/test_batched_retargeting.py index 592a863..08a9a58 100644 --- a/tests/helpers/humanoid_retargeting/test_batched_retargeting.py +++ b/tests/helpers/humanoid_retargeting/test_batched_retargeting.py @@ -19,7 +19,7 @@ ) from robokit.lie.se3 import se3_identity from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.robo import Robot from robokit.utils.warp_utils import wp_vec7 @@ -109,7 +109,7 @@ def test_targets_match_online(self, g1_robot: Robot, device: str): wp.from_numpy(np.array([1.6], dtype=np.float32), dtype=wp.float32, device=device), ) - offline.retargeting_config.solver = PopulationSolverConfig(num_iters=0, num_candidates=[1]) + offline.retargeting_config.solver = PopulationSolverConfig(stages=[Stage(0)]) offline.retargeting_config.solver.cuda_graph_mode = "none" online = HumanoidRetargeterOnline(offline.retargeting_config, robot=g1_robot, device=device) online.warmup(len(motion)) @@ -212,14 +212,10 @@ def test_online_yaml_preserves_nested_settings(self, tmp_path): ): config = HumanoidRetargeterOnlineConfig( solver=PopulationSolverConfig( - num_iters=7, - num_candidates=[2, 1], - select_at=[4], - optimizer=[optimizer, optimizer], + stages=[Stage(4, 2, optimizer, sample_every=4), Stage(3, 1, optimizer)], cuda_graph_mode="none", use_early_stopping=False, samplers=[RobertsSamplerConfig(scale=(0.1, 0.3), seed=17)], - sample_at=[0], ), ) config.to_yaml(path) @@ -227,6 +223,7 @@ def test_online_yaml_preserves_nested_settings(self, tmp_path): restored.to_yaml(tmp_path / "restored.yaml") assert path.read_text() == (tmp_path / "restored.yaml").read_text() assert restored.solver.cuda_graph_mode == "none" + assert restored.solver.stages == config.solver.stages assert type(restored.solver.optimizer[0]) is type(optimizer) assert restored.solver.optimizer[0] == optimizer @@ -256,7 +253,7 @@ def test_callable_schedule_cannot_be_silently_dropped(self, tmp_path): config = HumanoidRetargeterOnlineConfig( solver=PopulationSolverConfig( - optimizer=GDOptimizerConfig(lr_schedule=lambda step, rate: rate / (step + 1)), + stages=[Stage(10, optimizer=GDOptimizerConfig(lr_schedule=lambda step, rate: rate / (step + 1)))] ) ) path = tmp_path / "online.yaml" diff --git a/tests/helpers/humanoid_retargeting/test_humanoid_correspondence.py b/tests/helpers/humanoid_retargeting/test_humanoid_correspondence.py index cd2e8e7..6d0e6f0 100644 --- a/tests/helpers/humanoid_retargeting/test_humanoid_correspondence.py +++ b/tests/helpers/humanoid_retargeting/test_humanoid_correspondence.py @@ -10,7 +10,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.terms import FrameVectorTask @@ -30,7 +30,7 @@ def _config(edges): link_mapping=mapping, correspondence_edges=edges, solver=PopulationSolverConfig( - num_iters=3, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=1.0), cuda_graph_mode="none" + stages=[Stage(3, optimizer=LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="none" ), ) config.task("smoothness").weight = 0.0 diff --git a/tests/helpers/humanoid_retargeting/test_humanoid_scene_collision.py b/tests/helpers/humanoid_retargeting/test_humanoid_scene_collision.py index 567add7..fde6822 100644 --- a/tests/helpers/humanoid_retargeting/test_humanoid_scene_collision.py +++ b/tests/helpers/humanoid_retargeting/test_humanoid_scene_collision.py @@ -11,7 +11,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.var_values import VarKey, VarValues from robokit.terms.dense.scene_collision_task import SceneCollisionTask from robokit.utils.warp_utils import wp_vec7 @@ -32,7 +32,7 @@ def _config(weight: float) -> HumanoidRetargeterOnlineConfig: link_mapping={"panda_link0": LinkMapping("root", _ZERO3, _IDENTITY)}, velocity_clamp_scale=0.0, solver=PopulationSolverConfig( - num_iters=1, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=1.0), cuda_graph_mode="none" + stages=[Stage(1, optimizer=LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="none" ), ) config.task("collision").weight = weight diff --git a/tests/helpers/humanoid_retargeting/test_instance_batched_retargeting.py b/tests/helpers/humanoid_retargeting/test_instance_batched_retargeting.py index ddeb9d4..f3332f2 100644 --- a/tests/helpers/humanoid_retargeting/test_instance_batched_retargeting.py +++ b/tests/helpers/humanoid_retargeting/test_instance_batched_retargeting.py @@ -16,7 +16,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.utils.warp_utils import wp_vec7 @@ -35,7 +35,7 @@ def _config(smoothness): link_mapping=mapping, velocity_clamp_scale=0.0, solver=PopulationSolverConfig( - num_iters=4, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=1.0), cuda_graph_mode="none" + stages=[Stage(4, optimizer=LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="none" ), ) config.task("position_limit").warmup_frames = 0 diff --git a/tests/helpers/humanoid_retargeting/test_retargeting_self_collision.py b/tests/helpers/humanoid_retargeting/test_retargeting_self_collision.py index 13630b9..3ecd809 100644 --- a/tests/helpers/humanoid_retargeting/test_retargeting_self_collision.py +++ b/tests/helpers/humanoid_retargeting/test_retargeting_self_collision.py @@ -11,7 +11,7 @@ LinkMapping, ) from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.robo import Robot from robokit.utils.warp_utils import wp_vec7 @@ -31,10 +31,7 @@ def _config(weight: float) -> HumanoidRetargeterOnlineConfig: link_mapping=mapping, velocity_clamp_scale=0.0, solver=PopulationSolverConfig( - num_iters=10 + 5, - select_at=[10], - num_candidates=[4, 1], - optimizer=LMOptimizerConfig(lm_lambda=1.0), + stages=[Stage(10, 4, LMOptimizerConfig(lm_lambda=1.0)), Stage(5, 1)], cuda_graph_mode="none", ), ) diff --git a/tests/helpers/ik/test_ik.py b/tests/helpers/ik/test_ik.py index 5fb483c..ec5ad7a 100644 --- a/tests/helpers/ik/test_ik.py +++ b/tests/helpers/ik/test_ik.py @@ -1,5 +1,6 @@ """Tests for the IK API (helpers/ik).""" +import dataclasses from typing import List, Optional import numpy as np @@ -8,11 +9,11 @@ import warp as wp from robot_descriptions.loaders.yourdfpy import load_robot_description -from robokit.geom import WarpScene +from robokit.geom import SphereGeom, WarpScene from robokit.helpers.ik import IKContext, IKSolver, IKSolverConfig, presets from robokit.lie.se3 import se3_identity from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.opt.var_values import VarKey, VarValues from robokit.robo import Robot @@ -303,13 +304,10 @@ def test_ik_score_task(self): IKSolverConfig( enable_T_world_base=True, solver=PopulationSolverConfig( - num_iters=4 + 6, - select_at=[4, 4 + 6], - num_candidates=[8, 2, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(4, 8, LMOptimizerConfig(lm_lambda=10.0)), + Stage(6, 2, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="none", ), @@ -416,10 +414,10 @@ def test_ik_returns_multiple_final_solutions(self): config = ( IKSolverConfig( solver=PopulationSolverConfig( - num_iters=2, - select_at=[2], - num_candidates=[8, 2], - optimizer=[LMOptimizerConfig(lm_lambda=10.0), LMOptimizerConfig(lm_lambda=1.0)], + stages=[ + Stage(2, 8, LMOptimizerConfig(lm_lambda=10.0)), + Stage(0, 2, LMOptimizerConfig(lm_lambda=1.0)), + ], cuda_graph_mode="none", ) ) @@ -608,13 +606,10 @@ def test_frozen_joints_g1_right_hand_only(self): config = ( IKSolverConfig( solver=PopulationSolverConfig( - num_iters=10 + 15, - select_at=[10, 10 + 15], - num_candidates=[64, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(10, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(15, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="none", ), @@ -662,13 +657,10 @@ def test_explicit_mask_applied(self): config = ( IKSolverConfig( solver=PopulationSolverConfig( - num_iters=10 + 15, - select_at=[10, 10 + 15], - num_candidates=[64, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(10, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(15, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="none", ), @@ -710,13 +702,10 @@ def _solve(set_mask): enable_T_world_base=True, base_init_sample_range=(0.0, 0.0, 0.0), solver=PopulationSolverConfig( - num_iters=16 + 16, - select_at=[16, 16 + 16], - num_candidates=[64, 4, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(16, 64, LMOptimizerConfig(lm_lambda=10.0)), + Stage(16, 4, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="none", ), @@ -867,9 +856,7 @@ def test_matches_single_scene(self): device = "cuda:0" if wp.is_cuda_available() else "cpu" robot = _collision_robot() start_q, target_pos, target_wxyz = sample_targets(robot, device) - solver = PopulationSolverConfig( - num_iters=40, num_candidates=[1], optimizer=LMOptimizerConfig(lm_lambda=1.0), cuda_graph_mode="none" - ) + solver = PopulationSolverConfig(stages=[Stage(40, 1, LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="none") multi = build_multi_scene(device) scene_indices = wp.from_numpy(np.asarray(SCENE_IDS, np.int32), dtype=wp.int32, device=device) @@ -966,3 +953,34 @@ def test_collision_free_per_scene(self): ) pos_err = np.linalg.norm(ee_pos[i] - target_pos[i]) assert pos_err < 0.02, f"query {i} missed target: pos_err={pos_err * 1000:.1f}mm" + + +class TestIKPreviousStateWithSceneCollision: + @pytest.mark.parametrize("mode", ["none", "iter", "full"]) + def test_prev_state_does_not_shrink_the_candidate_collision_term(self, mode): + """Scoring prev_state, one row per target, runs before the multi-candidate solve and must not size its terms.""" + device = "cuda:0" if wp.is_cuda_available() else "cpu" + robot = _collision_robot() + far = np.eye(4, dtype=np.float32)[None] + far[0, :3, 3] = 2.0 + scene = WarpScene(1, device).add( + SphereGeom( + np.array([0.05]), np.array([0, 1], np.int32), poses=wp.from_numpy(far, dtype=wp.mat44, device=device) + ) + ) + solver = dataclasses.replace(IKSolverConfig().solver, cuda_graph_mode=mode) + config = ( + IKSolverConfig(solver=solver) + .add(PositionTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, weight=20.0)) + .add(_RotationTask(frame_index=IKContext.TARGET_LINKS, T_world_target=IKContext.TARGET, weight=10.0)) + .add(SceneCollisionTask(scene=IKContext.SCENE, scene_indices=IKContext.SCENE_INDICES, weight=100.0)) + ) + ik = IKSolver(config, robot, EE_LINK, device=device, scene=scene) + q = wp.from_numpy(robot.spec.midrange_q.astype(np.float32)[None], dtype=wp.float32, device=device) + state = robot.forward_kinematics(robot.state(q=q)) + pose = state.T_world_link.numpy()[:, robot.link_names.index(EE_LINK)] + target = wp.from_numpy(pose[:, None], dtype=wp_vec7, device=device) + + solved = ik.solve(target, prev_state=state, init_state=state).q.numpy() + + np.testing.assert_allclose(solved, q.numpy(), atol=1e-4) # prev_state already reaches the target diff --git a/tests/helpers/motion_plan/test_attached_objects.py b/tests/helpers/motion_plan/test_attached_objects.py new file mode 100644 index 0000000..21b8b86 --- /dev/null +++ b/tests/helpers/motion_plan/test_attached_objects.py @@ -0,0 +1,203 @@ +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pytest +import torch +import warp as wp +from robot_descriptions import panda_description +from test_waypoints import build_planner # pytest puts this directory on the path + +from robokit.geom import BoxGeom, WarpScene +from robokit.geom.covering_spheres import _compute_covering_spheres +from robokit.helpers.motion_plan import AttachedObject, FixedRelativePose, MotionPlanner, presets +from robokit.robo import Robot +from robokit.terms.dense.self_collision_task import SelfCollisionTask +from robokit.terms.sparse.trajectory_self_collision_task import TrajectorySelfCollisionTask +from robokit.utils.assembly_utils import assemble_urdf, merge_collision_spheres +from robokit.xform.numpy.transforms import pose7_to_tf_mat + + +PANDA_IGNORE = Path(__file__).parents[2] / "fixtures/franka_self_collision_ignore.yml" + + +pytestmark = pytest.mark.torch +DEVICE = "cuda:0" if wp.is_cuda_available() else "cpu" + + +def _translation(x: float, y: float, z: float) -> np.ndarray: + T = np.eye(4) + T[:3, 3] = (x, y, z) + return T + + +def _box_clearance(q_traj: np.ndarray, spheres: np.ndarray, center: np.ndarray, half: np.ndarray) -> float: + """Least clearance of the held spheres to an axis-aligned box along the plan, 20 samples a step.""" + weights = np.linspace(0, 1, 20, endpoint=False)[:, None] + q = np.concatenate([(1 - weights) * a + weights * b for a, b in zip(q_traj[:-1], q_traj[1:])] + [q_traj[-1:]]) + points = np.c_[q, np.zeros(len(q))][:, None] + spheres[None, :, :3] - center + outside = np.linalg.norm(np.maximum(np.abs(points) - half, 0), axis=-1) + inside = np.minimum(np.max(np.abs(points) - half, axis=-1), 0) + return float((outside + inside - spheres[None, :, 3]).min()) + + +class TestAttachedObjects: + def _planner(self, tmp_path: Path) -> MotionPlanner: + spheres = tmp_path / "spheres.yaml" + spheres.write_text("collision_spheres:\n tool:\n - center: [0, 0, 0]\n radius: 0.05\n") + poses = wp.array([_translation(0.0, 0.4, 0.0)], dtype=wp.mat44, device="cpu") + scene = WarpScene(1, "cpu").add(BoxGeom(np.full((1, 3), 0.2), np.array([0, 1], np.int32), poses=poses)) + return build_planner(spheres=spheres, scene=scene, collision=1000.0, attached_spheres=32) + + box = AttachedObject("tool", "box", (0.05, 0.15, 0.05), _translation(0.0, 0.15, 0.0)) + + def test_held_box_avoids_obstacle(self, tmp_path: Path): + """The tool clears the obstacle on a straight line; the box it holds would not, so the held plan detours.""" + planner = self._planner(tmp_path) + anchors = [np.array([-1.0, 0.0], np.float32), np.array([1.0, 0.0], np.float32)] + free = planner.solve_offline_numpy(anchors).q_traj[0] + carried = planner.solve_offline_numpy(anchors, attached_objects=[self.box]).q_traj[0] + spheres = _compute_covering_spheres("box", self.box.size, self.box.T_link_object) + center, half = np.array([0.0, 0.4, 0.0]), np.full(3, 0.2) + free_clearance, carried_clearance = (_box_clearance(q, spheres, center, half) for q in (free, carried)) + print(f"held box clearance: {free_clearance:.4f} m ignored, {carried_clearance:.4f} m attached") + assert free_clearance < -0.05 < 0.0 < carried_clearance + assert _box_clearance(free, np.array([[0, 0, 0, 0.05]]), center, half) > 0.1 # the tool alone is clear + + def test_inactive_attachment_and_empty_lists_keep_the_plan(self, tmp_path: Path): + planner = self._planner(tmp_path) + anchors = [ + np.array([-1.0, 0.0], np.float32), + np.array([0.0, -0.5], np.float32), + np.array([1.0, 0.0], np.float32), + ] + base = planner.solve_offline_numpy(anchors).q_traj + empty = planner.solve_offline_numpy(anchors, attached_objects=[], fixed_relative_poses=[]).q_traj + torch.testing.assert_close(torch.from_numpy(empty), torch.from_numpy(base), rtol=0, atol=0) + # held on the second segment only, which never nears the obstacle: the first segment plans as before + late = planner.solve_offline_numpy(anchors, attached_objects=[replace(self.box, segments=(1,))]) + torch.testing.assert_close(torch.from_numpy(late.q_traj), torch.from_numpy(base), rtol=0, atol=2e-3) + again = planner.solve_offline_numpy(anchors) # its reserved spheres off again: the plan as first + torch.testing.assert_close(torch.from_numpy(again.q_traj), torch.from_numpy(base), rtol=0, atol=0) + + def test_goal_ik_and_score_skip_an_attachment_outside_its_segments(self, tmp_path: Path): + """The box is held on the first segment only: at the pose goal, where it would overlap the obstacle, neither goal + IK nor the score counts it, so the tool reaches the goal and the plan ranks feasible.""" + planner = self._planner(tmp_path) + goal = {"tool": np.array([0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], np.float32)} + anchors = [np.array([-1.0, -0.5], np.float32), np.array([1.0, -0.5], np.float32), goal] + result = planner.solve_offline_numpy(anchors, attached_objects=[replace(self.box, segments=(0,))]) + assert np.abs(result.q_traj[0, -1]).max() < 1e-3 + held_late = planner.solve_offline_numpy(anchors, attached_objects=[replace(self.box, segments=(1,))]) # moved + assert np.abs(held_late.q_traj[0, -1]).max() > 0.01 + + +class TestRelativeFrames: + def test_two_arms_hold_their_relative_pose(self, tmp_path: Path): + """Two Pandas facing each other carry a shared pose: their hands' relative pose holds while both move.""" + T_mount_b = np.diag([-1.0, -1.0, 1.0, 1.0]) + T_mount_b[0, 3] = 1.1 + urdf = assemble_urdf( + tmp_path / "two_pandas.urdf", + Path(panda_description.URDF_PATH), + Path(panda_description.URDF_PATH), + "panda_link0", + "panda_link0", + T_mount_b, + "b_", + ) + franka = Path(__file__).parents[2] / "fixtures/franka_collision_spheres.yaml" + spheres = merge_collision_spheres(tmp_path / "two_pandas.yaml", [(franka, ""), (franka, "b_")]) + robot = Robot.load(str(urdf), load_collision_spheres=True, collision_spheres_path=spheres) + # the preset's iterations on every device: the relative pose is a soft cost, still ~3 mm off after 60 on CPU + config = presets.build_offline_pose_goal_config(max_retries=2, use_cuda_graph=DEVICE != "cpu") + planner = MotionPlanner( + replace(config, max_fixed_relative_poses=1), robot, ["panda_hand", "b_panda_hand"], device=DEVICE + ) + start = np.zeros(robot.num_actuated_joints, np.float32) + for prefix in ("", "b_"): # both arms at the ready pose, hands 0.49 m apart + for k, value in enumerate((0.0, -0.785, 0.0, -2.356, 0.0, 1.571, 0.785)): + start[robot.spec.actuated_joint_names.index(f"{prefix}panda_joint{k + 1}")] = value + hands = [robot.link_names.index(name) for name in ("panda_hand", "b_panda_hand")] + T_world_start = pose7_to_tf_mat(robot.forward_kinematics_numpy(start[None]))[0] + goal = {} + for name, link in zip(("panda_hand", "b_panda_hand"), hands): # both hands shift alike: T_a_b can hold + goal[name] = T_world_start[link].copy() + goal[name][:3, 3] += (0.0, 0.25, 0.15) + errors = [] + tray = FixedRelativePose("panda_hand", "b_panda_hand") + for relative in (None, [tray], [replace(tray, at_waypoint=1)]): # 1: the goal's + q_traj = planner.solve_offline_numpy([start, goal], fixed_relative_poses=relative).q_traj[0] + T_world_link = pose7_to_tf_mat(robot.forward_kinematics_numpy(q_traj)) + T_a_b = np.linalg.inv(T_world_link[:, hands[0]]) @ T_world_link[:, hands[1]] + error = np.linalg.inv(T_a_b[-1 if relative and relative[0].at_waypoint else 0]) @ T_a_b[1:] # vs reference + angle = np.arccos(np.clip((np.trace(error[:, :3, :3], axis1=1, axis2=2) - 1) / 2, -1, 1)) + errors.append((float(np.linalg.norm(error[:, :3, 3], axis=1).max()), float(angle.max()))) + final = T_world_link[-1, hands[0], :3, 3] + print(f"relative pose error: {errors[0]} free, {errors[1]} held, {errors[2]} held from the goal (m, rad)") + assert errors[1][0] < 0.002 and errors[1][1] < 0.02 + assert errors[2][0] < 0.3 * errors[0][0] and errors[2][1] < 0.5 * errors[0][1] # held from the (free) goal + assert errors[0][0] > 2 * errors[1][0] + assert np.linalg.norm(final - goal["panda_hand"][:3, 3]) < 0.005 + + +class TestHeldSelfCollision: + bar = AttachedObject( + "panda_hand", "box", (0.25, 0.015, 0.015), _translation(0.0, 0.0, 0.1) + ) # 0.5 m, at the fingers + + def _panda(self) -> Robot: + franka = Path(__file__).parents[2] / "fixtures/franka_collision_spheres.yaml" + return Robot.load( + panda_description.URDF_PATH, + load_collision_spheres=True, + collision_spheres_path=franka, + self_collision_ignore_path=PANDA_IGNORE, + ) + + def _planner(self, robot: Robot, device: str = DEVICE, **config) -> MotionPlanner: + config = presets.build_offline_pose_goal_config(use_cuda_graph=device != "cpu", **config) + return MotionPlanner(replace(config, max_attached_spheres=8), robot, "panda_hand", device=device) + + def test_held_spheres_meet_the_holders_arm_but_its_hand(self): + """A held bar meets every link but the hand's body, those one joint from it and the bar's ignored links, though + the hand's own spheres skip links 3-7.""" + planner = self._planner(self._panda(), "cpu", max_iter=1, max_retries=0, num_ik_samples=8) + robot, own = planner.robot, len(self._panda().spec.collision_sphere_radii) + link, start = robot.spec.collision_spheres_link_indices, np.zeros(robot.num_actuated_joints, np.float32) + for pairs in ( + TrajectorySelfCollisionTask(robot, 2)._active_pairs_np, + SelfCollisionTask(robot)._pair_indices_np, + ): + met = {robot.link_names[link[i]] for i, j in pairs if i < own <= j} + assert sorted(met) == [f"panda_link{k}" for k in "012345"] + for ignored, expected in [((), "012345"), (("panda_link4",), "01235")]: + planner.solve_offline_numpy( + [start, start], attached_objects=[replace(self.bar, collision_ignored_links=ignored)] + ) + task = planner._self_collision_tasks[0] + on = planner._pair_active.numpy()[: task.num_pairs] != 0 + met = {robot.link_names[link[i]] for (i, j), m in zip(task._active_pairs_np, on) if m and i < own <= j} + assert sorted(met) == [f"panda_link{k}" for k in expected] + + def test_held_bar_clears_its_own_forearm(self): + """Joint 7 sweeps a held bar through the holder's forearm (link 5): holding it, the plan goes around.""" + planner = self._planner(self._panda(), max_retries=4) + start = np.array([0.0, -0.785, 0.0, -2.356, 0.0, 0.88, -0.8, 0.04], np.float32) + goal = start.copy() + goal[6] = 2.4 + plans = [planner.solve_offline_numpy([start, goal], attached_objects=x).q_traj[0] for x in (None, [self.bar])] + robot = planner.robot # holding the bar, as the last solve left it + link, radii = robot.spec.collision_spheres_link_indices, robot.spec.collision_sphere_radii + bar_spheres = np.flatnonzero((link == len(robot.link_names) - 1) & (radii > 0)) + arm_spheres = np.flatnonzero(link == robot.link_names.index("panda_link5")) + weights, gaps = np.linspace(0, 1, 20, endpoint=False)[:, None], [] + for q_traj in plans: # the least gap of the bar to link 5 along the plan, 20 samples a step + q = np.concatenate([(1 - weights) * a + weights * b for a, b in zip(q_traj[:-1], q_traj[1:])]) + T_world_sphere = pose7_to_tf_mat(robot.forward_kinematics_numpy(q))[:, link] + centers = np.einsum("nsij,sj->nsi", T_world_sphere[..., :3, :3], robot.spec.local_collision_sphere_centers) + centers += T_world_sphere[..., :3, 3] + gap = np.linalg.norm(centers[:, bar_spheres, None] - centers[:, None, arm_spheres], axis=-1) + gaps.append(float((gap - radii[bar_spheres, None] - radii[arm_spheres]).min())) + print(f"held bar to link 5: {gaps[0]:.4f} m free, {gaps[1]:.4f} m held") + assert gaps[0] < -0.005 < 0.0 < gaps[1] diff --git a/tests/helpers/motion_plan/test_motion_plan.py b/tests/helpers/motion_plan/test_motion_plan.py index 43b5907..a1ff2ca 100644 --- a/tests/helpers/motion_plan/test_motion_plan.py +++ b/tests/helpers/motion_plan/test_motion_plan.py @@ -42,7 +42,7 @@ from robokit.helpers.motion_plan.plan_goal import PlanGoal from robokit.helpers.motion_plan.trajectory_retimer import RetimeConfig from robokit.opt.lbfgs_optimizer import LBFGSOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.var_values import VarKey, VarValues from robokit.robo import Robot, RobotState from robokit.terms.autodiff import autodiff_weighted_jacobian @@ -74,8 +74,8 @@ wp.init() # every weighted term off: the test's explicit terms carry the whole objective -_LM = GradientTrajectoryOptimizerConfig().solver.optimizer # a stage's default update -_LBFGS = presets.offline_pose_lbfgs.stages[0].solver.optimizer +_LM = GradientTrajectoryOptimizerConfig().solver.stages[0].optimizer # a stage's default update +_LBFGS = presets.offline_pose_lbfgs.stages[0].solver.stages[0].optimizer def _make_config(lock_goal: bool = False) -> MotionPlannerConfig: @@ -90,7 +90,7 @@ def _make_config(lock_goal: bool = False) -> MotionPlannerConfig: cuda_graph="none", goal_ik=ik_config, ) - config.stages[0].solver.num_iters = 50 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=50) if lock_goal: # mirrors presets._q_goal_traj: the locked endpoint carries the goal, not the pose tasks config.stages[0].lock_frames = (0, -1) config.stages[0].task("target").dense_task.position_weight = 0.0 @@ -192,7 +192,7 @@ def select(scores: List[float], q_value: float): wp.launch( _set_best_retry_result_kernel, dim=batch_size, - inputs=[scores_wp, q, base, start_distance, best_score, condition, final_q, final_base], + inputs=[scores_wp, q, base, start_distance, best_score, condition, None, final_q, final_base, None], device="cpu", ) @@ -288,8 +288,7 @@ def test_plan_and_update_fix_batch_size_lazily(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) plan_planner = _load_panda_motion_plan(config, device="cpu") q = plan_planner.robot.spec.zero_q.astype(np.float32) @@ -366,9 +365,9 @@ def test_offline_graph_replays_changed_inputs(self, derivative_limit_weight: flo config.max_retries = 0 config.jerk_limit = 120.0 config.retime = RetimeConfig(virtual_hold_frames=2) - config.stages[0].solver.num_iters = 5 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=5) if temporal_damping: - config.stages[0].solver.optimizer = _LBFGS + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], optimizer=_LBFGS) planner = _load_panda_motion_plan(config, device="cuda:0") start = planner.robot.spec.midrange_q.astype(np.float32) for distance, with_scene in ((0.1, False), (-0.1, False), (0.05, True), (-0.05, True)): @@ -385,12 +384,12 @@ def test_offline_graph_replays_changed_inputs(self, derivative_limit_weight: flo def test_pose_goal_candidates_repeat_across_trajectory_candidates(self): config = _make_config() config.max_retries = 0 - config.stages[0].solver.num_candidates = [4] - config.goal_ik.solver.num_candidates[-1] = 3 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], num_candidates=4) + config.goal_ik.solver.stages[-1] = replace(config.goal_ik.solver.stages[-1], num_candidates=3) with pytest.raises(ValueError, match="divisible"): _load_panda_motion_plan(config, device="cpu") - config.goal_ik.solver.num_candidates[-1] = 2 + config.goal_ik.solver.stages[-1] = replace(config.goal_ik.solver.stages[-1], num_candidates=2) planner = _load_panda_motion_plan(config, device="cpu") start_q = planner.robot.spec.zero_q.astype(np.float32) t_world_goal, q_wxyz_world_goal = _goal_from_q(planner, start_q) @@ -695,8 +694,7 @@ def test_reuses_single_query_optimizer(self): def test_scene_given_at_construction_is_reused(self): config = _make_config(lock_goal=True) config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) scene = WarpScene(2, "cpu") planner = _load_panda_motion_plan(config, device="cpu", scene=scene) q = planner.robot.spec.zero_q.astype(np.float32) @@ -718,8 +716,7 @@ def test_fixed_solver_config_builds_and_reuses_one_optimizer(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [2] - config.stages[0].solver.num_iters = 2 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=2, num_candidates=2) planner = _load_panda_motion_plan(config, device="cpu") start_q = planner.robot.spec.zero_q.astype(np.float32) target_q = start_q.copy() @@ -738,12 +735,11 @@ def test_fixed_solver_config_builds_and_reuses_one_optimizer(self): def test_plan_retries_but_update_runs_once(self, monkeypatch: pytest.MonkeyPatch): config = _make_config() - config.stages[0].solver.optimizer = _LBFGS + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], optimizer=_LBFGS) config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [2] - config.goal_ik.solver.num_candidates[-1] = 2 - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=2) + config.goal_ik.solver.stages[-1] = replace(config.goal_ik.solver.stages[-1], num_candidates=2) planner = _load_panda_motion_plan(config, device="cpu") start_q = planner.robot.spec.zero_q.astype(np.float32) target = _target(np.float32([10.0, 10.0, 10.0]), np.float32([1.0, 0.0, 0.0, 0.0])) # unreachable: it retries @@ -771,12 +767,11 @@ def solve( def test_cuda_retry_replays_without_error(self): config = _make_config() config.cuda_graph = "stages" - config.stages[0].solver.optimizer = _LBFGS + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], optimizer=_LBFGS) config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [2] - config.goal_ik.solver.num_candidates[-1] = 2 - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=2) + config.goal_ik.solver.stages[-1] = replace(config.goal_ik.solver.stages[-1], num_candidates=2) planner = _load_panda_motion_plan(config, device="cuda:0") start_q = planner.robot.spec.zero_q.astype(np.float32) target = _target(np.float32([10.0, 10.0, 10.0]), np.float32([1.0, 0.0, 0.0, 0.0])) # unreachable: it retries @@ -791,8 +786,7 @@ def test_plan_result_does_not_compute_metrics(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) planner = _load_panda_motion_plan(config, device="cpu") start_q = planner.robot.spec.zero_q.astype(np.float32) goal_q = start_q.copy() @@ -850,13 +844,13 @@ def test_compute_metrics_fails_success_on_penetration(self): # the given start and goal frames are reported but never gate success assert blocked_metrics.penetration_mm.shape == (1, blocked._num_frames) - def test_score_samples_the_path_where_curobo_checks_it(self): + def test_score_samples_the_path_at_its_check_points(self): q = wp.from_numpy(np.arange(4, dtype=np.float32).reshape(1, 4, 1), dtype=wp.float32, device="cpu") step = wp.from_numpy(np.array([0.04], dtype=np.float32), dtype=wp.float32, device="cpu") out = wp.empty((1, 10, 1), dtype=wp.float32, device="cpu") ends = wp.array([0, 3], dtype=wp.int32, device="cpu") # one segment timed = wp.array([0.0], dtype=wp.float32, device="cpu") # by its step - # cuRobo: ceil(3 * 0.04 / 0.025) = 5 samples 3 / 5 frames apart, then the last frame + # ceil(3 * 0.04 / 0.025) = 5 samples 3 / 5 frames apart, then the last frame wp.launch( _interpolate_trajectory_kernel, dim=out.shape, @@ -880,8 +874,7 @@ def test_plan_always_returns_owned_numpy_arrays(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) planner = _load_panda_motion_plan(config, device="cpu") start_q = planner.robot.spec.zero_q.astype(np.float32) @@ -901,8 +894,7 @@ def test_plan_returns_robot_state(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) planner = _load_panda_motion_plan(config, device="cpu") start_q = wp.from_numpy(planner.robot.spec.zero_q.astype(np.float32)[None], dtype=wp.float32, device="cpu") @@ -920,8 +912,7 @@ def make_planner(lock_goal: bool) -> MotionPlanner: config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) return _load_panda_motion_plan(config, device="cpu") planner = make_planner(lock_goal=True) @@ -952,8 +943,7 @@ def test_update_returns_device_trajectory_without_metrics(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) planner = _load_panda_motion_plan(config, device="cpu") start_q = wp.from_numpy(planner.robot.spec.zero_q.astype(np.float32)[None], dtype=wp.float32, device="cpu") @@ -969,8 +959,7 @@ def test_solve_online_numpy_returns_owned_trajectory(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1, num_candidates=1) planner = _load_panda_motion_plan(config, device="cpu") start_q = planner.robot.spec.zero_q.astype(np.float32) target_q = start_q.copy() @@ -988,8 +977,7 @@ def test_gradient_online_state_keeps_history_without_trajectory(self): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [3] - config.stages[0].solver.num_iters = 0 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=0, num_candidates=3) config.stages[0].task("jerk_smoothness").dense_task.weight = 1.0 planner = _load_panda_motion_plan(config, device="cpu") start_q = planner.robot.spec.zero_q.astype(np.float32) @@ -1028,7 +1016,7 @@ def test_update_q_goal_reaches_target(self): config.stages[0].task("position_limit").dense_task.weight = 0.0 config.stages[0].task("rest").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_candidates = [1] + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], num_candidates=1) planner = _load_panda_motion_plan(config, device="cpu") start_q_np = planner.robot.spec.zero_q.astype(np.float32) target_q_np = start_q_np.copy() @@ -1315,7 +1303,7 @@ def test_static_mixed_scene_expands_collision_tasks(self): ) config = GradientTrajectoryOptimizerConfig( - solver=PopulationSolverConfig(num_iters=80, optimizer=replace(_LM, lm_lambda=1.0)) + solver=PopulationSolverConfig(stages=[Stage(80, optimizer=replace(_LM, lm_lambda=1.0))]) ) config.task("target").dense_task.position_weight = 0.0 config.task("target").dense_task.orientation_weight = 0.0 @@ -1453,7 +1441,7 @@ def test_lbfgs_solver_skips_dense_jacobian_and_reduces_collision(self): ) cfg = GradientTrajectoryOptimizerConfig( solver=PopulationSolverConfig( - num_iters=60, optimizer=replace(_LBFGS, h0_scale=0.0001, line_search_alphas=(0.1, 0.3, 0.5, 1.0)) + stages=[Stage(60, optimizer=replace(_LBFGS, h0_scale=0.0001, line_search_alphas=(0.1, 0.3, 0.5, 1.0)))] ), ) for name in ("smoothness", "jerk_smoothness", "acceleration_smoothness"): @@ -1521,7 +1509,7 @@ def test_smooth_boundary_penalizes_first_and_last_transitions(self): def smoothness_weight(smooth_boundary: bool) -> np.ndarray: cfg = GradientTrajectoryOptimizerConfig( - solver=PopulationSolverConfig(num_iters=50, optimizer=replace(_LM, lm_lambda=1.0)) + solver=PopulationSolverConfig(stages=[Stage(50, optimizer=replace(_LM, lm_lambda=1.0))]) ) for name in ("smoothness", "jerk_smoothness", "acceleration_smoothness"): cfg.task(name).dense_task.virtual_hold_frames = 2 @@ -1566,7 +1554,7 @@ def test_reactive_position_online_state_only_uses_trajectory(self): config = _make_config() config.max_retries = 0 stage = MppiTrajectoryOptimizerConfig( - solver=PopulationSolverConfig(num_iters=2, samplers=[ColoredGaussianSamplerConfig(num_draws=16)]), + solver=PopulationSolverConfig(stages=[Stage(2)], samplers=[ColoredGaussianSamplerConfig(num_draws=16)]), control_space="position", lock_frames=(0,), ) @@ -1930,10 +1918,14 @@ def test_presets_build_independent_tasks_and_dimensions(self, name: str): config = deepcopy(getattr(presets, name)) stage = config.stages[0] options = ( - {"solver": replace(stage.solver, num_iters=1)} + {"solver": replace(stage.solver, stages=[replace(stage.solver.stages[0], iters=1)])} if isinstance(stage, GradientTrajectoryOptimizerConfig) else { - "solver": replace(stage.solver, num_iters=1, samplers=[replace(stage.solver.samplers[0], num_draws=8)]) + "solver": replace( + stage.solver, + stages=[replace(stage.solver.stages[0], iters=1)], + samplers=[replace(stage.solver.samplers[0], num_draws=8)], + ) } ) config.stages = (replace(stage, **options),) @@ -1988,11 +1980,14 @@ def test_floating_base_planning_preserves_configured_ik_rest(self, device: str, config = deepcopy(presets.online_pose_lbfgs) config.num_timesteps = 4 config.goal_ik.enable_T_world_base = True - config.goal_ik.solver.num_iters = 2 - config.goal_ik.solver.select_at = [1, 2] - config.goal_ik.solver.num_candidates = [4, 2, 1] + config.goal_ik.solver.stages = [ + replace(s, iters=i, num_candidates=c) for s, i, c in zip(config.goal_ik.solver.stages, (1, 1, 0), (4, 2, 1)) + ] + solver = config.stages[0].solver config.stages = ( - replace(config.stages[0], solver=replace(config.stages[0].solver, num_iters=1, num_candidates=[1])), + replace( + config.stages[0], solver=replace(solver, stages=[replace(solver.stages[0], iters=1, num_candidates=1)]) + ), ) robot = _load_panda_motion_plan(_make_config(), device=device).robot home_q = robot.spec.midrange_q.astype(np.float32)[None] @@ -2056,9 +2051,12 @@ def test_trajectory_initialization_preserves_ik_base(self, device: str, ik_candi config = deepcopy(presets.online_pose_lbfgs) config.num_timesteps = 4 config.goal_ik.enable_T_world_base = True - config.goal_ik.solver.num_candidates[-1] = ik_candidates + config.goal_ik.solver.stages[-1] = replace(config.goal_ik.solver.stages[-1], num_candidates=ik_candidates) config.init_sample_range = 0.0 - config.stages = (replace(config.stages[0], solver=replace(config.stages[0].solver, num_candidates=[4])),) + solver = config.stages[0].solver + config.stages = ( + replace(config.stages[0], solver=replace(solver, stages=[replace(solver.stages[0], num_candidates=4)])), + ) planner = _load_panda_motion_plan(config, device=device) robot = planner.robot batch, candidates, frames = 2, 4, 5 @@ -2116,11 +2114,14 @@ def test_floating_base_plans_pose_waypoints_with_retries(self): config = deepcopy(presets.offline_pose_lbfgs) config.num_timesteps = 6 config.goal_ik.enable_T_world_base = True - config.goal_ik.solver.num_iters = 2 - config.goal_ik.solver.select_at = [1, 2] - config.goal_ik.solver.num_candidates = [4, 2, 2] + config.goal_ik.solver.stages = [ + replace(s, iters=i, num_candidates=c) for s, i, c in zip(config.goal_ik.solver.stages, (1, 1, 0), (4, 2, 2)) + ] + solver = config.stages[0].solver config.stages = ( - replace(config.stages[0], solver=replace(config.stages[0].solver, num_iters=2, num_candidates=[2])), + replace( + config.stages[0], solver=replace(solver, stages=[replace(solver.stages[0], iters=2, num_candidates=2)]) + ), ) robot = _load_panda_motion_plan(_make_config(), device="cpu").robot planner = MotionPlanner(config, robot, "panda_hand", device="cpu") @@ -2226,8 +2227,11 @@ def test_collision_evaluation_paths( solver = PopulationSolver( terms=[TrajectoryTask(ConfigurationTask(robot, rest_q=robot.spec.midrange_q, weight=1e-4), 3), task], config=PopulationSolverConfig( - num_iters=8, - optimizer=LBFGSOptimizerConfig(gradient_mode=gradient_mode, fold_line_search_gradient=fold), + stages=[ + Stage( + 8, optimizer=LBFGSOptimizerConfig(gradient_mode=gradient_mode, fold_line_search_gradient=fold) + ) + ], cuda_graph_mode="full" if str(device).startswith("cuda") else "none", ), device=device, @@ -2271,13 +2275,13 @@ def test_explicit_tasks_keep_targets_and_update_in_place(self, backend: str): # the explicit terms carry the objective: the goal is the start, so only they move the middle frame stage = ( GradientTrajectoryOptimizerConfig( - terms=terms, solver=PopulationSolverConfig(num_iters=15, optimizer=_LBFGS), lock_frames=(0,) + terms=terms, solver=PopulationSolverConfig(stages=[Stage(15, optimizer=_LBFGS)]), lock_frames=(0,) ) if backend == "lbfgs" else MppiTrajectoryOptimizerConfig( terms=terms, solver=PopulationSolverConfig( - num_iters=15, samplers=[ColoredGaussianSamplerConfig(init_std=0.03, min_std=0.001)] + stages=[Stage(15)], samplers=[ColoredGaussianSamplerConfig(init_std=0.03, min_std=0.001)] ), lock_frames=(0,), ) @@ -2303,11 +2307,12 @@ def test_caller_built_stubs_keep_frames_targets_and_name(self, backend: str): T_world_link = robot.forward_kinematics_numpy(q[None])[0, [link]] stage = ( GradientTrajectoryOptimizerConfig( - solver=PopulationSolverConfig(num_iters=2, optimizer=_LM), lock_frames=(0, -1) + solver=PopulationSolverConfig(stages=[Stage(2, optimizer=_LM)]), lock_frames=(0, -1) ) if backend == "lbfgs" else MppiTrajectoryOptimizerConfig( - solver=PopulationSolverConfig(num_iters=2, samplers=[ColoredGaussianSamplerConfig()]), lock_frames=(0,) + solver=PopulationSolverConfig(stages=[Stage(2)], samplers=[ColoredGaussianSamplerConfig()]), + lock_frames=(0,), ) ) stage.add(TrajectoryTask(PositionTask(weight=5.0, fixed_target=True)), name="feet_position") @@ -2342,7 +2347,7 @@ def test_native_base_survives_offline_online_and_history(self, backend: str): stage = ( GradientTrajectoryOptimizerConfig( terms=terms, - solver=PopulationSolverConfig(num_iters=2, optimizer=_LBFGS if backend == "lbfgs" else _LM), + solver=PopulationSolverConfig(stages=[Stage(2, optimizer=_LBFGS if backend == "lbfgs" else _LM)]), lock_frames=(0,), ) if backend != "mppi" @@ -2350,7 +2355,7 @@ def test_native_base_survives_offline_online_and_history(self, backend: str): terms=terms, control_space="acceleration", solver=PopulationSolverConfig( - num_iters=2, samplers=[ColoredGaussianSamplerConfig(init_std=1e-4, min_std=1e-5)] + stages=[Stage(2)], samplers=[ColoredGaussianSamplerConfig(init_std=1e-4, min_std=1e-5)] ), ) ) @@ -2412,7 +2417,7 @@ def test_multiple_pose_goals(self, floating: bool): config.max_retries = 0 config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1) robot = _load_panda_motion_plan(config, device="cpu").robot links = [robot.link_names.index("panda_hand"), robot.link_names.index("panda_link3")] q0 = robot.spec.midrange_q.astype(np.float32) # within the joint limits, so the targets are reachable @@ -2528,7 +2533,7 @@ def test_goal_placeholder_takes_each_candidates_goal(self, backend: str, candida if backend == "gradient": optimizer = GradientTrajectoryOptimizer( GradientTrajectoryOptimizerConfig( - terms=[role], solver=PopulationSolverConfig(num_iters=0, num_candidates=[candidates], optimizer=_LM) + terms=[role], solver=PopulationSolverConfig(stages=[Stage(0, candidates, _LM)]) ), robot, "panda_hand", @@ -2543,7 +2548,7 @@ def test_goal_placeholder_takes_each_candidates_goal(self, backend: str, candida MppiTrajectoryOptimizerConfig( terms=[role], solver=PopulationSolverConfig( - num_iters=0, num_candidates=[candidates], samplers=[ColoredGaussianSamplerConfig(num_draws=4)] + stages=[Stage(0, candidates)], samplers=[ColoredGaussianSamplerConfig(num_draws=4)] ), lock_frames=(0,), ), @@ -2619,7 +2624,7 @@ def test_mppi_settling_uses_measured_base(self): settle_radius=0.2, control_space="acceleration", solver=PopulationSolverConfig( - num_iters=0, samplers=[ColoredGaussianSamplerConfig(num_draws=4, init_std=0.1, min_std=0.01)] + stages=[Stage(0)], samplers=[ColoredGaussianSamplerConfig(num_draws=4, init_std=0.1, min_std=0.01)] ), terms=[TrajectoryTask(PositionLimit(weight=1.0))], ) @@ -2657,7 +2662,7 @@ def test_goal_inputs_keep_existing_meanings(self): config = _make_config() config.stages[0].task("collision").dense_task.weight = 0.0 config.stages[0].task("self_collision").dense_task.weight = 0.0 - config.stages[0].solver.num_iters = 1 + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], iters=1) planner = _load_panda_motion_plan(config, device="cpu") q = planner.robot.spec.midrange_q.astype(np.float32) t_world_goal, q_wxyz_world_goal = _goal_from_q(planner, q) @@ -2677,8 +2682,7 @@ def test_acceleration_candidate_selection_preserves_query_starts(self, weighting config = MppiTrajectoryOptimizerConfig( control_space="acceleration", solver=PopulationSolverConfig( - num_iters=2, - num_candidates=[candidates], + stages=[Stage(2, candidates)], samplers=[ColoredGaussianSamplerConfig(num_draws=8, sample_mode=sample_mode, weighting=weighting)], ), terms=[ @@ -2717,7 +2721,11 @@ def test_fewer_trajectory_candidates_take_fewer_goals(self): presets.offline_pose_lbfgs, max_retries=0, cuda_graph="none", - stages=(replace(stage, solver=replace(stage.solver, num_candidates=[1])),), + stages=( + replace( + stage, solver=replace(stage.solver, stages=[replace(stage.solver.stages[0], num_candidates=1)]) + ), + ), ) planner = _load_panda_motion_plan(config, "cpu") assert presets.offline_pose_lbfgs.goal_ik.solver.num_candidates[-1] > 1 @@ -2784,9 +2792,11 @@ def _planner( config = _make_config() config.max_retries = retries # each retry reserves 4 more goals, so 12 retries rank a 52-goal pool if retries: - config.stages[0].solver.optimizer = _LBFGS - config.stages[0].solver.num_candidates = [4] - config.goal_ik.solver.num_candidates = [64, 4, 4] + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], optimizer=_LBFGS) + config.stages[0].solver.stages[0] = replace(config.stages[0].solver.stages[0], num_candidates=4) + config.goal_ik.solver.stages = [ + replace(s, num_candidates=c) for s, c in zip(config.goal_ik.solver.stages, (64, 4, 4)) + ] config.goal_ik.solver = replace(config.goal_ik.solver, cuda_graph_mode="full" if cuda_graph else "none") config.cuda_graph = "solve" if cuda_graph else "none" planner = _load_panda_motion_plan(config, device=device, scene=scene) diff --git a/tests/helpers/motion_plan/test_per_link_waypoints.py b/tests/helpers/motion_plan/test_per_link_waypoints.py new file mode 100644 index 0000000..1940a7a --- /dev/null +++ b/tests/helpers/motion_plan/test_per_link_waypoints.py @@ -0,0 +1,128 @@ +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pytest +import torch +import warp as wp +from robot_descriptions import panda_description + +from robokit.helpers.motion_plan import MotionPlanner, presets +from robokit.robo import Robot +from robokit.utils.assembly_utils import assemble_urdf, merge_collision_spheres +from robokit.utils.warp_utils import wp_vec7 +from robokit.xform.numpy.rotation_conversions import normalize_quaternion +from robokit.xform.numpy.transforms import pose7_to_tf_mat, tf_mat_to_pose7 + + +pytestmark = pytest.mark.torch +DEVICE = "cuda:0" if wp.is_cuda_available() else "cpu" +HANDS = ("panda_hand", "b_panda_hand") + + +class TestPerLinkWaypoints: + def _two_pandas(self, tmp_path: Path, device: str = DEVICE, **config) -> tuple: + """Two Pandas facing each other 1.1 m apart, both at the ready pose; their planner and start.""" + T_mount_b = np.diag([-1.0, -1.0, 1.0, 1.0]) + T_mount_b[0, 3] = 1.1 + panda = Path(panda_description.URDF_PATH) + urdf = assemble_urdf(tmp_path / "two.urdf", panda, panda, "panda_link0", "panda_link0", T_mount_b, "b_") + franka = Path(__file__).parents[2] / "fixtures/franka_collision_spheres.yaml" + spheres = merge_collision_spheres(tmp_path / "two.yaml", [(franka, ""), (franka, "b_")]) + robot = Robot.load(str(urdf), load_collision_spheres=True, collision_spheres_path=spheres) + planner_config = presets.build_offline_pose_goal_config(max_retries=2, use_cuda_graph=device != "cpu") + if device == "cpu": + stages = tuple( + replace(s, solver=replace(s.solver, stages=[replace(st, iters=60) for st in s.solver.stages])) + for s in planner_config.stages + ) + planner_config = replace(planner_config, stages=stages) + planner = MotionPlanner(replace(planner_config, **config), robot, list(HANDS), device=device) + start = np.zeros(robot.num_actuated_joints, np.float32) + for prefix in ("", "b_"): + for k, value in enumerate((0.0, -0.785, 0.0, -2.356, 0.0, 1.571, 0.785)): + start[robot.spec.actuated_joint_names.index(f"{prefix}panda_joint{k + 1}")] = value + return planner, start + + def _hands(self, planner: MotionPlanner, q: np.ndarray) -> np.ndarray: + """Each hand's pose `[x, y, z, qw, qx, qy, qz]` at each configuration, `(configs, 2, 7)`.""" + links = [planner.robot.link_names.index(name) for name in HANDS] + return planner.robot.forward_kinematics_numpy(np.atleast_2d(q).astype(np.float32))[:, links] + + def test_each_arm_reaches_its_own_keyframe(self, tmp_path: Path): + """Arm a reaches its keyframe while arm b is free and still on its way; b reaches its own one waypoint later.""" + planner, start = self._two_pandas(tmp_path) + key = pose7_to_tf_mat(self._hands(planner, start)[0]) + key[0, :3, 3] += (0.0, 0.25, -0.1) # a's hand to its side and down, b's to the other side + key[1, :3, 3] += (0.0, -0.25, -0.1) + waypoints = [start, {HANDS[0]: key[0]}, {HANDS[1]: key[1]}, dict(zip(HANDS, key))] + result = planner.solve_offline_numpy(waypoints) + reached = self._hands(planner, result.q_traj[0][list(result.waypoint_indices)])[..., :3] + miss = np.linalg.norm(reached - key[:, :3, 3], axis=-1) # (waypoints, hands) + print(f"frames {result.waypoint_indices}, each waypoint's miss per hand (m): {np.round(miss, 4).tolist()}") + assert miss[1, 0] < 0.005 and miss[2, 1] < 0.005 and miss[3].max() < 0.005 # a, then b, then both + b_start = self._hands(planner, start)[0, 1, :3] + assert miss[1, 1] > 0.03 and np.linalg.norm(reached[1, 1] - b_start) > 0.03 # b, free there, on its way + + def test_locked_segment_holds_the_links_both_waypoints_name(self, tmp_path: Path): + """A locked segment keeps arm a, named at both its waypoints, on the straight line; arm b, named at its end + alone, moves freely there.""" + planner, start = self._two_pandas(tmp_path) + key = pose7_to_tf_mat(self._hands(planner, start)[0]) + lower, side = key.copy(), key.copy() + lower[:, 2, 3] -= 0.1 + side[:, 1, 3] += (0.2, -0.2) + waypoints = [start, {HANDS[0]: lower[0]}, dict(zip(HANDS, side)), dict(zip(HANDS, side))] + result = planner.solve_offline_numpy(waypoints, segment_locked=[False, True, False]) + q, (_, left, right, _) = result.q_traj[0], result.waypoint_indices + joints = [ + [planner.robot.spec.actuated_joint_names.index(f"{p}panda_joint{k}") for k in range(1, 8)] + for p in ("", "b_") + ] + for arm, (index, held) in enumerate(zip(joints, (True, False))): # each frame's distance from the line + moved, chord = q[left : right + 1, index] - q[left, index], q[right, index] - q[left, index] + off = np.linalg.norm(moved - np.outer(moved @ chord, chord) / (chord @ chord), axis=1).max() + print(f"arm {arm}: {off:.2e} rad off the straight line") + assert off < 1e-5 if held else off > 1e-4 + + def test_naming_every_link_keeps_the_plan(self, tmp_path: Path): + """Pose dicts naming every target link plan bitwise as Warp pose arrays do (on the CPU, where solves repeat + bitwise).""" + planner, start = self._two_pandas(tmp_path, "cpu", duration_weight=1e4, max_retries=0) + T_world_hand = self._hands(planner, start)[0] + middle, goal = ((T_world_hand + [0, 0.1, z, 0, 0, 0, 0]).astype(np.float32) for z in (0.0, 0.1)) + segments = dict(segment_locked=[False, True]) + named = planner.solve_offline_numpy([start, dict(zip(HANDS, middle)), dict(zip(HANDS, goal))], **segments) + poses = [ + wp.array(np.c_[T[:, :3], normalize_quaternion(T[:, 3:])][None], dtype=wp_vec7, device="cpu") + for T in (middle, goal) + ] + plain = planner.solve_offline([wp.array(start[None], device="cpu"), *poses], **segments) + for x, y in ((named.q_traj, plain.q_traj), (named.segment_duration, plain.segment_duration)): + torch.testing.assert_close(torch.from_numpy(x), torch.from_numpy(y.numpy()), rtol=0, atol=0) + + def test_dict_keys_and_wrappers(self, tmp_path: Path): + """Unrelated dict keys are ignored; a dict naming no target link, or a start pose leaving one out with no + joints to keep it at, raises; the Warp and Torch APIs plan partial dicts as the NumPy one.""" + planner, start = self._two_pandas(tmp_path, "cpu", max_retries=0) + key = pose7_to_tf_mat(self._hands(planner, start)[0]) + key[0, :3, 3] += (0.0, 0.1, -0.1) + plain = planner.solve_offline_numpy([start, {HANDS[0]: key[0]}, dict(zip(HANDS, key))]).q_traj + extra = planner.solve_offline_numpy( + [start, {HANDS[0]: key[0], "other": key[1]}, dict(zip(HANDS, key), x=key[0])] + ) + torch.testing.assert_close(torch.from_numpy(extra.q_traj), torch.from_numpy(plain), rtol=0, atol=0) + with pytest.raises(ValueError, match="name target links"): + planner.solve_offline_numpy([start, {"other": key[0]}, dict(zip(HANDS, key))]) + with pytest.raises(ValueError, match="needs seed_q"): + planner.solve_offline_numpy([{HANDS[0]: key[0]}, dict(zip(HANDS, key))]) + T7 = tf_mat_to_pose7(key.astype(np.float32)) # as the NumPy wrapper reads the matrices + T7 = np.c_[T7[:, :3], normalize_quaternion(T7[:, 3:])] + pose = [wp.array(T[None], dtype=wp_vec7, device="cpu") for T in T7] + warp_plan = planner.solve_offline( + [wp.array(start[None], device="cpu"), {HANDS[0]: pose[0]}, dict(zip(HANDS, pose))] + ) + torch.testing.assert_close(torch.from_numpy(warp_plan.q_traj.numpy()), torch.from_numpy(plain), rtol=0, atol=0) + T = torch.from_numpy(key.astype(np.float32)) + torch_plan = planner.solve_offline_torch([torch.from_numpy(start), {HANDS[0]: T[0]}, dict(zip(HANDS, T))]) + torch.testing.assert_close(torch_plan.q_traj, torch.from_numpy(plain), rtol=0, atol=1e-3) diff --git a/tests/helpers/motion_plan/test_segment_durations.py b/tests/helpers/motion_plan/test_segment_durations.py new file mode 100644 index 0000000..9813969 --- /dev/null +++ b/tests/helpers/motion_plan/test_segment_durations.py @@ -0,0 +1,97 @@ +from dataclasses import replace +from io import StringIO + +import numpy as np +import pytest +import yourdfpy + +from robokit.helpers.motion_plan import GradientTrajectoryOptimizerConfig, MotionPlanner, MotionPlannerConfig +from robokit.helpers.motion_plan.plan_goal import MotionPlanContext as ctx +from robokit.helpers.motion_plan.trajectory_retimer import RetimeConfig +from robokit.opt.lbfgs_optimizer import LBFGSOptimizerConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage +from robokit.robo import Robot +from robokit.terms.dense.position_limit import PositionLimit +from robokit.terms.sparse.trajectory_limit_task import TrajectoryLimitTask +from robokit.terms.trajectory_task import TrajectoryTask + + +LIMITS = (2.0, 15.0, 150.0) # rad/s (the URDF's), rad/s², rad/s³ + + +def _plan(duration_weight: float, waypoints: list, fixed: tuple = ()) -> tuple: + xml = """ + + + + """ + robot = Robot.load(yourdfpy.URDF.load(StringIO(xml))) + stage = GradientTrajectoryOptimizerConfig( + terms=[ # the derivative bounds at the query step, which read the optimized steps + TrajectoryTask(PositionLimit(weight=100.0), name="position_limit"), + TrajectoryLimitTask( + order=(1, 2, 3), + upper=(ctx.VELOCITY_LIMITS, ctx.ACCELERATION_LIMIT, ctx.JERK_LIMIT), + weight=(300.0, 100.0, 10.0), + dt=ctx.QUERY_STEP, + name="derivative_bounds", + ), + ], + lock_frames=(0, -1), + solver=PopulationSolverConfig( + stages=[Stage(200, 1, LBFGSOptimizerConfig(history_len=15, fold_line_search_gradient=True))] + ), + ) + config = MotionPlannerConfig( + num_timesteps=20, + acceleration_limit=LIMITS[1], + jerk_limit=LIMITS[2], + stages=(stage,), + retime=RetimeConfig(speed_scale=1.0, max_dt=1.0, virtual_hold_frames=2), + cuda_graph="none", + duration_weight=duration_weight, + ) + planner = MotionPlanner(replace(config), robot, "tool", device="cpu") + durations = [None] * (len(waypoints) - 1) + for segment, seconds in fixed: + durations[segment] = seconds + result = planner.solve_offline_numpy( + [np.asarray(w, np.float32) for w in waypoints], segment_fixed_duration=durations + ) + return result, planner + + +def _peak_ratio(q: np.ndarray, steps: np.ndarray) -> float: + """The worst ratio of a plan's velocity, acceleration and jerk to the limits, each frame at its interval's step, + by the retime's five-point derivatives with held ends.""" + padded = np.concatenate([q[:1], q[:1], q, q[-1:], q[-1:]]) + window = np.stack([padded[k : k + len(q)] for k in range(5)]) # frames f - 2 .. f + 2 + step = np.r_[steps, steps[-1:]][:, None] + velocity = np.abs(window[0] - 8 * window[1] + 8 * window[3] - window[4]) / 12 / step + acceleration = np.abs(-window[0] + 16 * window[1] - 30 * window[2] + 16 * window[3] - window[4]) / 12 / step**2 + jerk = np.abs(-0.5 * window[0] + window[1] - window[3] + 0.5 * window[4]) / step**3 + return max(velocity.max() / LIMITS[0], acceleration.max() / LIMITS[1], jerk.max() / LIMITS[2]) + + +class TestSegmentDurations: + def test_shorter_than_the_uniform_step_within_limits(self): + start, goal = [0.0, 0.0], [1.0, 0.5] + uniform, _ = _plan(0.0, [start, goal]) + timed, _ = _plan(1.0e4, [start, goal]) + assert timed.segment_duration is not None and uniform.segment_duration is None + np.testing.assert_allclose(timed.motion_time, timed.segment_duration.sum(1), rtol=1e-6) + assert timed.motion_time[0] < 0.9 * uniform.motion_time[0] + steps = np.full(20, timed.motion_time[0] / 20) + assert _peak_ratio(timed.q_traj[0], steps) <= 1.0 + 1e-3 + np.testing.assert_allclose(timed.q_traj[0, [0, -1]], [start, goal], atol=1e-5) + + def test_fixed_segments_keep_their_durations(self): + waypoints = [[0.0, 0.0], [0.5, 0.0], [0.5, 0.5]] + result, _ = _plan(1.0e4, waypoints, fixed=((1, 1.0),)) + frames = np.diff(result.waypoint_indices) + assert result.segment_duration[0, 1] == pytest.approx(1.0) + np.testing.assert_allclose(result.motion_time, result.segment_duration.sum(1), rtol=1e-6) + free = result.segment_duration[0, 0] / frames[0] # the free segment's step, within the limits + assert _peak_ratio(result.q_traj[0, : result.waypoint_indices[1] + 1], np.full(frames[0], free)) <= 1.0 + 1e-3 + samples = result.interpolate(0.01)[0] # the plan plays each segment over its own time + assert len(samples) == int(np.ceil(result.segment_duration[0] / 0.01).sum()) + 1 diff --git a/tests/helpers/motion_plan/test_task_config.py b/tests/helpers/motion_plan/test_task_config.py index 490ce02..7e61946 100644 --- a/tests/helpers/motion_plan/test_task_config.py +++ b/tests/helpers/motion_plan/test_task_config.py @@ -1,4 +1,5 @@ from copy import deepcopy +from dataclasses import replace from io import StringIO import numpy as np @@ -37,7 +38,7 @@ def test_pose_task_keeps_its_residual_mode(self) -> None: name="target", ) config = GradientTrajectoryOptimizerConfig(terms=[source]) - config.solver.num_iters = 0 + config.solver.stages[0] = replace(config.solver.stages[0], iters=0) stage = GradientTrajectoryOptimizer(config, robot, "tip", 3, 0.25, use_cuda_graph=False, device="cpu") var = stage.make_var( wp.from_numpy(np.array([[[0.0], [1.0], [2.0]]], np.float32), dtype=wp.float32, device="cpu") @@ -56,7 +57,7 @@ def test_explicit_task_target_without_implicit_costs(self, built: bool) -> None: name="rest", ) config = GradientTrajectoryOptimizerConfig(terms=[source]) - config.solver.num_iters = 0 + config.solver.stages[0] = replace(config.solver.stages[0], iters=0) stage = GradientTrajectoryOptimizer(config, robot, "tip", 3, 0.25, use_cuda_graph=False, device="cpu") var = stage.make_var( wp.from_numpy(np.array([[[0.0], [1.0], [2.0]]], np.float32), dtype=wp.float32, device="cpu") diff --git a/tests/helpers/motion_plan/test_waypoints.py b/tests/helpers/motion_plan/test_waypoints.py index cada988..a0b6827 100644 --- a/tests/helpers/motion_plan/test_waypoints.py +++ b/tests/helpers/motion_plan/test_waypoints.py @@ -21,7 +21,7 @@ ) from robokit.helpers.motion_plan.trajectory_retimer import RetimeConfig from robokit.opt.lbfgs_optimizer import LBFGSOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.robo import Robot from robokit.terms.dense.configuration_task import ConfigurationTask @@ -36,6 +36,7 @@ def build_planner( scene: Optional[WarpScene] = None, beam: bool = False, collision: float = 0.0, + attached_spheres: int = 0, ) -> MotionPlanner: xml = """ @@ -51,10 +52,9 @@ def build_planner( stage = GradientTrajectoryOptimizerConfig( lock_frames=(0, -1), solver=PopulationSolverConfig( - num_iters=30, - select_at=[10] if beam else [], - num_candidates=[candidates, 1] if beam else [candidates], - optimizer=GradientTrajectoryOptimizerConfig().solver.optimizer if beam else lbfgs, + stages=[Stage(10, candidates, GradientTrajectoryOptimizerConfig().solver.stages[0].optimizer), Stage(20, 1)] + if beam + else [Stage(30, candidates, lbfgs)] ), ) stage.task("target").dense_task.position_weight = 0 @@ -74,6 +74,7 @@ def build_planner( acceleration_limit=2, jerk_limit=10, retime=RetimeConfig(), + max_attached_spheres=attached_spheres, ) config.goal_ik.solver = replace(config.goal_ik.solver, cuda_graph_mode="none" if device == "cpu" else "full") config.goal_ik.add(ConfigurationTask(rest_q=IKContext.REST_Q, weight=0.1)) @@ -226,7 +227,8 @@ def test_pose_ik_in_a_scene(self, tmp_path: Path): clear = np.array([-1, 0]) # multi-solution IK picks a clear solution multi = build_planner(spheres=spheres, scene=scene) - multi.config.goal_ik.solver.num_candidates = [64, 4, 2] + solver = multi.config.goal_ik.solver + solver.stages = [replace(s, num_candidates=c) for s, c in zip(solver.stages, (64, 4, 2))] pose = {"tool": np.array([-1, 0.5, 0, 1, 0, 0, 0])} result = multi.solve_offline_numpy([clear, pose]) torch.testing.assert_close( diff --git a/tests/helpers/rl/test_ppo.py b/tests/helpers/rl/test_ppo.py new file mode 100644 index 0000000..6509181 --- /dev/null +++ b/tests/helpers/rl/test_ppo.py @@ -0,0 +1,64 @@ +"""PPO with its own networks: a trunk the actor and the critic share trains, eagerly and as one CUDA graph.""" + +import math +from types import SimpleNamespace +from typing import Literal, Tuple + +import pytest +import torch +from torch import nn + +from robokit.helpers.rl.ppo import PPO, Normalizer, PPOConfig + + +pytestmark = pytest.mark.torch + + +class _Critic(nn.Module): + def __init__(self, trunk: nn.Module, norm: nn.Module, out: int = 1): + super().__init__() + self.trunk, self.obs_normalizer, self.head = trunk, norm, nn.Linear(32, out) + + def forward(self, obs: torch.Tensor) -> torch.Tensor: + return self.head(self.trunk(self.obs_normalizer(obs))) + + +class _Actor(_Critic): + """NIST's std: a log-std parameter, clamped to the bounds.""" + + state_std = False + + def __init__(self, trunk: nn.Module, norm: nn.Module, actions: int): + super().__init__(trunk, norm, actions) + self.log_std = nn.Parameter(torch.zeros(actions)) + + def dist(self, obs: torch.Tensor, std_range: Tuple[float, float]) -> Tuple[torch.Tensor, torch.Tensor]: + return self(obs), self.log_std.clamp(math.log(std_range[0]), math.log(std_range[1])).exp() + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="PPO's update is a CUDA graph") +class TestCustomNetworks: + @pytest.mark.parametrize("grad_clip, reshuffle", [("network", False), ("joint", True)]) # default, NIST's + def test_shared_trunk(self, grad_clip: Literal["network", "joint"], reshuffle: bool): + """A bandit paying actions near the first two observations: rewards rise over eager updates (0 to 2) and graph + replays (3 on); Adam steps each shared parameter once per minibatch, and the shared normalizer sees each + rollout once.""" + torch.manual_seed(0) + n, obs, f = 256, torch.randn(256, 3, device="cuda"), torch.zeros(256, dtype=torch.bool, device="cuda") + env = SimpleNamespace(n=n, obs_dims=(3, 3), bound=torch.ones(2, device="cuda"), names=["err"], reset=id, + obs=lambda: (obs, obs), step=lambda a: (-((a - obs[:, :2]) ** 2).sum(1), f, f, f[:1]), curriculum=id) # fmt: skip + trunk, norm = nn.Sequential(nn.Linear(3, 32), nn.ELU()), Normalizer(3) + actor, critic = _Actor(trunk, norm, 2), _Critic(trunk, norm) + config = PPOConfig(std_range=(1e-3, 2.0), grad_clip=grad_clip, reshuffle=reshuffle) + learner = PPO(env.obs_dims, 2, config, actor=actor, critic=critic) + rewards, weights = [], [next(trunk.parameters()).detach().clone()] + params = learner.opt.param_groups[0]["params"] + assert len(params) == 7 # the trunk's 2, the heads' 4, the log-std + for _ in range(30): + learner.update(env) + rewards.append(learner.reward.item()) + weights.append(next(trunk.parameters()).detach().clone()) + assert all(learner.opt.state[p]["step"].item() == 30 * config.epochs * config.minibatches for p in params) + assert norm.count.item() == 30 * config.horizon * n + assert not torch.equal(weights[0], weights[3]) and not torch.equal(weights[4], weights[-1]) # eager, graph + assert rewards[-1] - 1.0 > rewards[3] > rewards[0] + 0.5, rewards diff --git a/tests/helpers/sim_mpc/test_sim_mpc.py b/tests/helpers/sim_mpc/test_sim_mpc.py index 69c6e86..9afdc24 100644 --- a/tests/helpers/sim_mpc/test_sim_mpc.py +++ b/tests/helpers/sim_mpc/test_sim_mpc.py @@ -1,28 +1,22 @@ -"""SimMPC, its MuJoCo Warp binding and the simulation terms; needs MuJoCo Warp.""" +"""SimMPC on MuJoCo Warp worlds and the simulation terms; needs MuJoCo Warp.""" import copy +from functools import partial from typing import Optional import numpy as np import pytest import warp as wp -from robokit.helpers.sim_mpc import SimMPC, SimMPCConfig +from robokit.helpers.sim_mpc import CartesianControl, SimMPC, SimMPCConfig, SimMPCStage, sim_context from robokit.helpers.sim_mpc.sim_mpc import _Key from robokit.opt.var_values import VarValues -from robokit.terms import ( - ContactTask, - ControlTask, - GraspTask, - SensorTask, - SimContext, - StateTask, - Task, -) +from robokit.terms import ContactTask, ControlTask, GraspTask, SensorTask, SimContext, StateTask, Task mujoco = pytest.importorskip("mujoco") -mjwarp = pytest.importorskip("robokit.helpers.sim_mpc.mjwarp") +MjWarpSim = pytest.importorskip("robokit.sim.mjwarp").MjWarpSim # needs MuJoCo Warp +SIM = partial(MjWarpSim, nconmax=120, njmax=500) # the sizes the examples default to XML = """ @@ -39,20 +33,12 @@ """ -def _planner(model, ctrl_ref, ctrl_std, costs, config, data=None, binding: Optional[dict] = None, **kwargs) -> SimMPC: - sim = mjwarp.MjWarpSim(model, mujoco.MjData(model) if data is None else data, **(binding or {})) - return SimMPC(sim, np.asarray(ctrl_ref), np.asarray(ctrl_std), costs, config, **kwargs) - - def _evaluate(model, data, term: Task, clock=(0, 0, 1), forward: bool = False) -> float: """One term's cost on `data` as the executed world of a single instance.""" - import mujoco_warp - - sim = mjwarp.MjWarpSim(model, data) - sim.build(1, 2, 1, 1, 0, 0) + sim = SIM(model, 1, data) if forward: - mujoco_warp.forward(sim.model, sim.data["execution"]) - context = sim.context("execution") | { + sim.forward() + context = sim_context(sim) | { SimContext.CLOCK: wp.array(clock, dtype=int), SimContext.NUM_INSTANCES: 1, SimContext.WORLDS_PER_INSTANCE: 1, @@ -86,9 +72,6 @@ def _one_kernel(out: wp.array(dtype=float)): class _OneTask(Task): - def __init__(self, terminal_scale: Optional[float] = None, running_scale: float = 1.0): - self.terminal_scale, self.running_scale = terminal_scale, running_scale - def compute_weighted_cost(self, var_values, *, out_cost: wp.array): wp.launch(_one_kernel, dim=out_cost.shape[0], outputs=[out_cost]) @@ -102,85 +85,72 @@ def test_cost_choice_and_budget(self, case: str, replicas: int): '' ) cfg = SimMPCConfig( - num_samples=4, - num_replicas=replicas, - horizon_steps=1, - node_steps=1, - ctrl_steps=1, - max_iterations=1, - min_improvement=-1, - interpolation="zero", - terminal_scale=1, - ) - solver = _planner(model, np.zeros((2, 1)), np.ones(1), [_MeanTask(case != "convex")], cfg) + ctrl_std=1.0, num_samples=4, num_replicas=replicas, horizon_steps=1, node_steps=1, ctrl_steps=1, + max_iterations=1, min_improvement=-1, interpolation="zero", terminal_scale=1, + ).add(_MeanTask(case != "convex")) # fmt: skip + solver = SimMPC(cfg, SIM(model, 1), np.zeros((2, 1))) values = dict(convex=[0, 0.5, 1], opposite=[0, 1, -1], nearby=[1, -0.5, 0.25])[case] def fixed(out: wp.array, iteration: int = 0): out.assign(np.repeat(np.asarray(values, np.float32)[:, None], out.shape[1], axis=1)) solver.sampler.fill = fixed - (info,) = solver._optimize(0) - applied = solver._simulate(0)["ctrl"][0, 0, 0] + commands, (info,) = solver.plan(mujoco.MjData(model), 0) mean = case != "opposite" expected = 0.25 if case == "convex" else 1.0 - 1.5 / (1 + np.exp(2)) if mean else 1.0 assert info["executed_mean"] is mean assert info["rollout_evaluations"] == cfg.num_samples - assert solver.sim.data["rollout"].nworld + solver.sim.data["validation"].nworld == cfg.num_samples * replicas - assert applied == pytest.approx(expected, abs=1e-6) + assert solver.sims["rollout"].nworld + solver.sims["validation"].nworld == cfg.num_samples * replicas + assert commands.numpy()[0, 0, 0] == pytest.approx(expected, abs=1e-6) if mean: assert info["mean_cost"] <= info["best_cost"] + 4 * info["temperature"] class TestSimMPCExecution: def test_complete_state_timing(self): - """Row k is the state at sim step k; the executed world ends one step past the last row.""" + """Row k is the state at sim step k; the executing sim ends one step past the last row.""" model = mujoco.MjModel.from_xml_string( '" ) - config = SimMPCConfig(num_samples=4, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1) - mpc = _planner(model, np.ones((8, 1)), np.zeros(1), [], config) - (rollout,), _ = mpc.solve(4) + config = SimMPCConfig(ctrl_std=0, num_samples=4, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1) + sim = SIM(model, 1) + (rollout,), _ = SimMPC(config, SIM(model, 1), np.ones((8, 1))).execute(sim, 4) np.testing.assert_allclose(rollout["qpos"][:, 0], [0, 0.0001, 0.0003, 0.0006], atol=1e-8) np.testing.assert_allclose(rollout["time"], [0, 0.01, 0.02, 0.03], atol=1e-8) - executed = mpc.sim.data["execution"] - assert executed.qpos.numpy()[0, 0] == pytest.approx(0.001, abs=1e-8) - assert executed.time.numpy()[0] == pytest.approx(0.04, abs=1e-8) + assert sim.data.qpos.numpy()[0, 0] == pytest.approx(0.001, abs=1e-8) + assert sim.data.time.numpy()[0] == pytest.approx(0.04, abs=1e-8) @pytest.mark.parametrize("interpolation", ["linear", "cubic", "zero"]) def test_automatic_boundary_matches_interpolant(self, interpolation: str): model = mujoco.MjModel.from_xml_string(XML) - config = SimMPCConfig(num_samples=8, horizon_steps=4, node_steps=2, ctrl_steps=1, interpolation=interpolation) - solver = _planner(model, np.zeros((10, 1)), np.ones(1), [ControlTask(1)], config) + config = SimMPCConfig( + ctrl_std=1.0, num_samples=8, horizon_steps=4, node_steps=2, ctrl_steps=1, interpolation=interpolation + ) + solver = SimMPC(config, SIM(model, 1), np.zeros((10, 1))) assert (solver.sampler.std.numpy()[0, 0] > 0) == (interpolation == "zero") @pytest.mark.parametrize("custom", [False, True]) def test_native_spline_and_command_bounds(self, custom: bool): model = mujoco.MjModel.from_xml_string(XML) - config = SimMPCConfig(num_samples=8, horizon_steps=4, node_steps=4, ctrl_steps=4) spline = np.column_stack([1 - np.arange(5) / 4, np.arange(5) / 4]) - solver = _planner( - model, - np.zeros((10, 1)), - np.ones(1), - [ControlTask(1)], - config, - spline_basis=spline if custom else None, - ctrl_range=np.array([[-1, 1]]), - ) - solver.plan.get(_Key.NODES).x.assign(np.array([[1, -1]], np.float32)) - np.testing.assert_allclose(solver._simulate(0)["ctrl"][0, :, 0], [1, 0.5, 0, -0.5], atol=1e-7) + config = SimMPCConfig( + ctrl_std=0.0, num_samples=8, horizon_steps=4, node_steps=4, ctrl_steps=4, ctrl_range=np.array([[-1, 1]]), + interpolation=spline if custom else "linear", + ) # fmt: skip + solver = SimMPC(config, SIM(model, 1), np.zeros((10, 1))) + solver.execution.assign(np.array([[1, -1]], np.float32)) + commands, _ = solver.plan(mujoco.MjData(model), 0) # no node noise: the assigned plan's commands + np.testing.assert_allclose(commands.numpy()[:, 0, 0], [1, 0.5, 0, -0.5], atol=1e-7) def test_bounded_mean_uses_projected_samples(self): model = mujoco.MjModel.from_xml_string(XML) config = SimMPCConfig( - num_samples=4, horizon_steps=1, node_steps=1, ctrl_steps=1, max_iterations=1, interpolation="zero", - terminal_scale=1, - ) # fmt: skip - solver = _planner( - model, np.ones((10, 1)), np.ones(1), [ControlTask(1)], config, ctrl_range=np.array([[-0.1, 0.1]]) - ) + ctrl_std=1.0, num_samples=4, horizon_steps=1, node_steps=1, ctrl_steps=1, max_iterations=1, + interpolation="zero", terminal_scale=1, ctrl_range=np.array([[-0.1, 0.1]]), + ).add(ControlTask(1)) # fmt: skip + solver = SimMPC(config, SIM(model, 1), np.ones((10, 1))) fill = solver.sampler.fill def fixed_noise(out: wp.array, iteration: int = 0): @@ -188,21 +158,22 @@ def fixed_noise(out: wp.array, iteration: int = 0): out.assign(np.array([[0, 0], [-3, -3], [3, 3]], np.float32)) solver.sampler.fill = fixed_noise - solver._optimize(0) + commands, _ = solver.plan(mujoco.MjData(model), 0) # Equal costs: the mean of the two elite (first) draws as bounded, mean([.1, -.1]), not unbounded (-0.1). - np.testing.assert_allclose(solver._simulate(0)["ctrl"][0, :, 0], [0.0], atol=2e-6) + np.testing.assert_allclose(commands.numpy()[0, :, 0], [0.0], atol=2e-6) def test_actuator_limits_clip_controls(self): model = mujoco.MjModel.from_xml_string(XML.replace('kp="50"', 'kp="50" ctrlrange="-0.05 0.05"')) config = SimMPCConfig( - num_samples=8, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1, terminal_scale=1 - ) - (rollout,), (plans,) = _planner(model, np.ones((10, 1)), np.zeros(1), [ControlTask(1.0)], config).solve(2) + ctrl_std=0.0, num_samples=8, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1, terminal_scale=1 + ).add(ControlTask(1.0)) + (rollout,), (plans,) = SimMPC(config, SIM(model, 1), np.ones((10, 1))).execute(SIM(model, 1), 2) assert rollout["ctrl"] == pytest.approx(np.full((2, 1), 0.05), abs=1e-7) assert plans[0]["plan_cost"] == pytest.approx(0.05**2) - def test_sensor_tracking(self): - """With a zero control reference, only SensorTask moves the cart from 0.1 m onto a ramp to 0.3 m.""" + @pytest.mark.parametrize("planner", ["mppi", "ilqr"]) + def test_sensor_tracking(self, planner: str): + """With a zero control reference, only SensorTask moves the cart from 0.1 m onto a ramp to 0.3 m, by either planner.""" model = mujoco.MjModel.from_xml_string(XML) data = mujoco.MjData(model) data.qpos[0] = 0.1 @@ -210,9 +181,11 @@ def test_sensor_tracking(self): target = np.interp(np.arange(200), [0, 50], [0.1, 0.3]) sensor = np.zeros((200, 4)) sensor[:, 0] = sensor[:, 1] = target - config = SimMPCConfig(num_samples=64, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=4, seed=3) - cost = SensorTask(sensor, {"x": 100.0, "p": [100.0, 0.0, 0.0]}) - (rollout,), (plans,) = _planner(model, np.zeros((200, 1)), np.full(1, 0.1), [cost], config, data).solve(100) + config = SimMPCConfig( + num_samples=64, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=4, seed=3, planner=planner + ) + config.add(SensorTask(sensor, {"x": 100.0, "p": [100.0, 0.0, 0.0]})) + (rollout,), (plans,) = SimMPC(config, SIM(model, 1), np.zeros((200, 1))).execute(SIM(model, 1, data), 100) assert {k: v.shape for k, v in rollout.items()} == { "time": (100,), "qpos": (100, 1), @@ -225,23 +198,35 @@ def test_sensor_tracking(self): np.testing.assert_allclose(rollout["sensordata"][:, 0], rollout["qpos"][:, 0], atol=1e-6) assert abs(rollout["qpos"][-1, 0] - 0.3) < 0.03 and len(plans) == 10 + def test_plan_from_mujoco_data(self): + """`plan` takes a `mujoco.MjData` as it takes the sim's data; MuJoCo stepping its commands reaches the target.""" + model = mujoco.MjModel.from_xml_string(XML) + data = mujoco.MjData(model) + data.qpos[0] = 0.1 + config = SimMPCConfig(num_samples=16, horizon_steps=20, node_steps=10, ctrl_steps=10, max_iterations=2) + config.add(SensorTask(np.full((60, 4), 0.3), {"x": 100.0})) + (rollout,), _ = SimMPC(config, SIM(model, 1), np.zeros((60, 1))).execute(SIM(model, 1, data), 10) + mpc = SimMPC(config, SIM(model, 1), np.zeros((60, 1))) + for t0 in range(0, 30, 10): + commands, (info,) = mpc.plan(data, t0) + assert commands.shape == (10, 1, 1) and info["t0"] == t0 + if t0 == 0: + np.testing.assert_array_equal(commands.numpy()[:, 0], rollout["ctrl"]) + for ctrl in commands.numpy()[:, 0]: + data.ctrl[:] = ctrl + mujoco.mj_step(model, data) + assert abs(data.qpos[0] - 0.3) < 0.1 + class TestSimMPCAnnealing: def test_noise_schedule(self): """Iteration i draws free node j with `ctrl_std * std_growth**(j / (H - 1)) * noise_decay**i`.""" model = mujoco.MjModel.from_xml_string(XML) config = SimMPCConfig( - num_samples=16, - horizon_steps=30, - node_steps=10, - ctrl_steps=10, - max_iterations=2, - init_iterations=4, - min_improvement=-np.inf, - noise_decay=0.5, - min_std=1e-6, - ) - mpc = _planner(model, np.zeros((100, 1)), np.array([0.1]), [], config) + num_samples=16, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=2, init_iterations=4, + min_improvement=-np.inf, noise_decay=0.5, min_std=1e-6, + ) # fmt: skip + mpc = SimMPC(config, SIM(model, 1), np.zeros((100, 1))) mpc.sampler.gamma = 0.0 # no std adaptation, so the schedule is exact stds, fill = [], mpc.sampler.fill mpc.sampler.fill = lambda *args: (stds.append(mpc.sampler.std.numpy()[0, 1:].copy()), fill(*args))[1] @@ -249,44 +234,80 @@ def test_noise_schedule(self): expected = [np.array([0.1, 0.2, 0.4]) * 0.5**i for i in [0, 1, 2, 3, 4, 0, 1, 2]] np.testing.assert_allclose(stds, expected, rtol=1e-5) # each plan also redraws after its last iteration + def test_carried_noise_and_first_node(self): + """One-round plans with `std_range` start from the last refit spread, one clipped scale of the configured noise; `draw_first_node` draws node 0 too, and a new episode (t0 = 0) restarts from the configured noise.""" + model = mujoco.MjModel.from_xml_string(XML) + config = SimMPCConfig( + num_samples=32, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=1, draw_first_node=True, + wide_ratio=0.2, std_range=(0.35, 2.0), elite_ratio=0.1, + ) # fmt: skip + config.add(SensorTask(np.full((100, 1), 0.3), {"x": 100.0})) + mpc = SimMPC(config, SIM(model, 1), np.zeros((100, 1))) + node_std = mpc.node_std.copy() + assert node_std[0, 0] == pytest.approx(0.1) + (info,) = mpc._optimize(0) + assert 0.35 <= info["std_scale"] <= 2.0 + np.testing.assert_allclose(mpc.sampler.std_reset.numpy(), info["std_scale"] * node_std, rtol=1e-6) + mpc._optimize(0) + stds, fill = [], mpc.sampler.fill + mpc.sampler.fill = lambda *args: (stds.append(mpc.sampler.std.numpy().copy()), fill(*args))[1] + mpc._optimize(0) + np.testing.assert_allclose(stds[0], node_std, rtol=1e-6) + class TestSimMPCTerminalScale: def test_terminal_only(self): model = mujoco.MjModel.from_xml_string(XML) - config = SimMPCConfig(num_samples=8, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=1) - mpc = _planner(model, np.zeros((100, 1)), np.zeros(1), [_OneTask(6.0, running_scale=0.0)], config) - assert mpc._optimize(0)[0]["plan_cost"] == pytest.approx(6 / 30) + config = SimMPCConfig( + ctrl_std=0.0, num_samples=8, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=1 + ).add(_OneTask(), running_scale=0.0, terminal_scale=6.0) + assert SimMPC(config, SIM(model, 1), np.zeros((100, 1)))._optimize(0)[0]["plan_cost"] == pytest.approx(6 / 30) def test_cost_overrides_config(self): - """A unit cost per step over a 30-step horizon, normalized: (29 + 10) / 30 with the config's terminal - scale 10, plus 29 / 30 for the cost whose own terminal_scale 0 drops its last step.""" + """A unit cost per step over a 30-step horizon, normalized: (29 + 10) / 30 with the config's terminal scale 10, plus 29 / 30 for the cost whose own terminal_scale 0 drops its last step.""" model = mujoco.MjModel.from_xml_string(XML) - config = SimMPCConfig(num_samples=8, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=1) - mpc = _planner(model, np.zeros((100, 1)), np.array([0.1]), [_OneTask(), _OneTask(0.0)], config) + config = ( + SimMPCConfig(num_samples=8, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=1) + .add(_OneTask()) + .add(_OneTask(), terminal_scale=0.0) + ) + mpc = SimMPC(config, SIM(model, 1), np.zeros((100, 1))) assert np.isclose(mpc._optimize(0)[0]["plan_cost"], (39 + 29) / 30) -class TestSimMPCPlanModel: - def test_common_randomizations_leave_execution_unchanged(self): +class TestSimMPCStages: + def test_coarse_stage_costs_and_first_plan(self): + """A unit cost over 30 steps at 40 ms: 2 steps of 10 ms, then 7 of 40 ms weighted 4, the last one's 4 replaced by the terminal 10: (30 - 4 + 10) / 30; at 10 ms (29 + 10) / 30. A first plan of 3 iterations runs the coarse stage longer; a dt off the timestep's multiples fails.""" model = mujoco.MjModel.from_xml_string(XML) - friction = np.tile(model.geom_friction, (2, 1, 1)) - friction[1, :, 0] *= 2 config = SimMPCConfig( - num_samples=9, num_replicas=2, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1 - ) - binding = dict(plan_parameters={"geom_friction": friction}, initial_state_std={"qpos": np.array([0.1])}) - mpc = _planner(model, np.zeros((10, 1)), np.ones(1), [], config, binding=binding) - sim = mpc.sim + num_samples=8, horizon_steps=30, node_steps=10, ctrl_steps=10, init_iterations=3, min_improvement=0, + stages=[SimMPCStage(1, dt=0.04), SimMPCStage(1)], + ).add(_OneTask()) # fmt: skip + mpc = SimMPC(config, SIM(model, 1), np.zeros((100, 1))) + assert config.max_iterations == 2 + for t0, expected in ((0, [36, 36, 39]), (10, [36, 39])): + np.testing.assert_allclose([c for c, _ in mpc._optimize(t0)[0]["history"]], np.divide(expected, 30)) + with pytest.raises(ValueError, match="whole multiple"): + SimMPC(SimMPCConfig(num_samples=8, stages=[SimMPCStage(1, dt=0.015)]), SIM(model, 1), np.zeros((9, 1))) + + +class TestSimMPCRollouts: + def test_start_noise(self): + """Each replica gets its start noise, which is redrawn per plan start.""" + model = mujoco.MjModel.from_xml_string(XML) + config = SimMPCConfig( + ctrl_std=1.0, num_samples=9, num_replicas=2, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1, + qpos_std=0.1, + ) # fmt: skip + mpc = SimMPC(config, SIM(model, 1), np.zeros((10, 1))) + rollout = mpc.sims["rollout"] mpc.graphs["rollout_reset"]() - actual = sim.data["rollout"].qpos.numpy().reshape(8, 2).copy() # a CPU array's numpy() is a view + actual = rollout.data.qpos.numpy().reshape(8, 2).copy() # a CPU array's numpy() is a view assert actual == pytest.approx(np.tile(actual[:1], (8, 1))) assert actual[0, 0] != actual[0, 1] - assert sim.data["execution"].qpos.numpy()[0, 0] == 0 - assert sim.models["rollout"].geom_friction.numpy() == pytest.approx(np.tile(friction, (8, 1, 1))) - assert sim.model.geom_friction.numpy()[0] == pytest.approx(model.geom_friction) mpc.clock.assign(np.array([1, 0, 2], np.int32)) mpc.graphs["rollout_reset"]() - assert not np.allclose(actual, sim.data["rollout"].qpos.numpy().reshape(8, 2)) + assert not np.allclose(actual, rollout.data.qpos.numpy().reshape(8, 2)) def test_unscored_settle_and_reset_time(self): model = mujoco.MjModel.from_xml_string(XML) @@ -294,68 +315,36 @@ def test_unscored_settle_and_reset_time(self): data.qpos[0], data.qvel[0] = 0.2, 1.0 mujoco.mj_forward(model, data) config = SimMPCConfig( - num_samples=8, - horizon_steps=1, - node_steps=1, - ctrl_steps=1, - max_iterations=1, - terminal_scale=1, + ctrl_std=0.0, num_samples=8, horizon_steps=1, node_steps=1, ctrl_steps=1, max_iterations=1, terminal_scale=1, settle_steps=2, - ) - mpc = _planner(model, np.zeros((10, 1)), np.zeros(1), [_OneTask()], config, data) - assert mpc._optimize(0)[0]["plan_cost"] == pytest.approx(1.0) + ).add(_OneTask()) # fmt: skip + mpc = SimMPC(config, SIM(model, 1), np.zeros((10, 1))) + assert mpc.plan(data, 0)[1][0]["plan_cost"] == pytest.approx(1.0) for _ in range(3): mujoco.mj_step(model, data) - assert mpc.sim.data["rollout"].qpos.numpy()[0] == pytest.approx(data.qpos, abs=1e-6) - assert mpc.sim.data["rollout"].time.numpy()[0] == pytest.approx(model.opt.timestep) - assert mpc.sim.data["execution"].qpos.numpy()[0, 0] == pytest.approx(0.2) + assert mpc.sims["rollout"].data.qpos.numpy()[0] == pytest.approx(data.qpos, abs=1e-6) + assert mpc.sims["rollout"].data.time.numpy()[0] == pytest.approx(model.opt.timestep) def test_partial_node_interval(self): """The last simulated step interpolates inside the allocated nodes for uneven horizons.""" model = mujoco.MjModel.from_xml_string(XML) - config = SimMPCConfig(num_samples=8, horizon_steps=25, node_steps=10, ctrl_steps=10, max_iterations=1) - mpc = _planner(model, np.zeros((100, 1)), np.array([0.1]), [_OneTask()], config) + config = SimMPCConfig(num_samples=8, horizon_steps=25, node_steps=10, ctrl_steps=10, max_iterations=1).add( + _OneTask() + ) + mpc = SimMPC(config, SIM(model, 1), np.zeros((100, 1))) assert mpc.num_nodes == 4 assert np.isclose(mpc._optimize(0)[0]["plan_cost"], (24 + config.terminal_scale) / 25) - def test_rollouts_step_the_plan_model(self): - model, plan = mujoco.MjModel.from_xml_string(XML), mujoco.MjModel.from_xml_string(XML.replace("0.01", "0.02")) - config = SimMPCConfig(num_samples=8, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=1) - sim = _planner(model, np.zeros((100, 1)), np.array([0.1]), [], config, binding=dict(plan_model=plan)).sim - assert sim.plan_model.opt.timestep.numpy()[0] == np.float32(0.02) - assert sim.model.opt.timestep.numpy()[0] == np.float32(0.01) - with pytest.raises(ValueError, match="plan_model"): - mjwarp.MjWarpSim(model, mujoco.MjData(model), plan_model=mujoco.MjModel.from_xml_string("")) - - def test_parallel_line_search_only_in_rollouts(self): - model = mujoco.MjModel.from_xml_string( - '' - '' - ) - config = SimMPCConfig(num_samples=8, horizon_steps=4, node_steps=2, ctrl_steps=2, max_iterations=2) - try: - mpc = _planner(model, np.zeros((10, 1)), np.ones(1), [], config, binding=dict(plan_ls_parallel=8)) - except AttributeError as error: - if "ls_parallel was removed" not in str(error): - raise - pytest.skip(str(error)) - assert mpc.sim.plan_model.opt.ls_parallel and mpc.sim.plan_model.opt.ls_iterations == 8 - assert not mpc.sim.model.opt.ls_parallel and mpc.sim.model.opt.ls_iterations == model.opt.ls_iterations - (rollout,), (plans,) = mpc.solve(4) - assert np.isfinite(rollout["qpos"]).all() and np.isfinite(plans[-1]["plan_cost"]) - class TestSimMPCRanking: def test_device_ranking_matches_numpy(self): - """The device ranking sorts stably, reports the plan's and the best cost and sets the elite-spread - temperature.""" + """The device ranking sorts stably, reports the plan's and the best cost and sets the elite-spread temperature.""" model = mujoco.MjModel.from_xml_string(XML) config = SimMPCConfig( - num_samples=81, num_replicas=2, horizon_steps=30, node_steps=10, ctrl_steps=10, max_iterations=1 - ) # fmt: skip - cost_fn = SensorTask(np.tile([0.3, 0.3, 0.0, 0.0], (100, 1)), {"x": 100.0}) - mpc = _planner(model, np.zeros((100, 1)), np.array([0.5]), [cost_fn], config) + ctrl_std=0.5, num_samples=81, num_replicas=2, horizon_steps=30, node_steps=10, ctrl_steps=10, + max_iterations=1, + ).add(SensorTask(np.tile([0.3, 0.3, 0.0, 0.0], (100, 1)), {"x": 100.0})) # fmt: skip + mpc = SimMPC(config, SIM(model, 1), np.zeros((100, 1))) scored, sample = [], mpc.sampler.sample def capture(var: VarValues, scores: Optional[wp.array]) -> VarValues: @@ -373,8 +362,10 @@ def capture(var: VarValues, scores: Optional[wp.array]) -> VarValues: def test_mean_of_elites(self): """The plan moves to the softmax-weighted mean of the best 20% of draws, at their spread's temperature.""" model = mujoco.MjModel.from_xml_string(XML) - config = SimMPCConfig(num_samples=81, horizon_steps=4, node_steps=1, ctrl_steps=1, max_iterations=1) - mpc = _planner(model, np.ones((10, 1)), np.array([0.3]), [ControlTask(1)], config) + config = SimMPCConfig( + ctrl_std=0.3, num_samples=81, horizon_steps=4, node_steps=1, ctrl_steps=1, max_iterations=1 + ).add(ControlTask(1)) + mpc = SimMPC(config, SIM(model, 1), np.ones((10, 1))) draws, sample = [], mpc.sampler.sample def capture(var: VarValues, scores: Optional[wp.array]) -> VarValues: @@ -389,28 +380,23 @@ def capture(var: VarValues, scores: Optional[wp.array]) -> VarValues: costs[np.argsort(costs, kind="stable")[16:]] = np.inf # the other 80% get no weight weights = np.exp((costs.min() - costs) / temperature) expected = weights @ draws / weights.sum() - assert mpc.execution.numpy()[0] == pytest.approx(expected, abs=1e-6) - assert mpc.plan.get(_Key.NODES).x.numpy()[0] == pytest.approx(expected, abs=1e-6) - assert mpc.sim.data["rollout"].nworld == 80 + assert mpc.plan_values.get(_Key.NODES).x.numpy()[0] == pytest.approx(expected, abs=1e-6) + assert mpc.sims["rollout"].nworld == 80 @pytest.mark.parametrize("early_stop", [False, True]) def test_repeated_mean_refinement(self, early_stop: bool): model = mujoco.MjModel.from_xml_string(XML) config = SimMPCConfig( - num_samples=81, - horizon_steps=4, - node_steps=1, - ctrl_steps=1, - max_iterations=4 if early_stop else 2, - min_improvement=1e6 if early_stop else 0, - ) - mpc = _planner(model, np.ones((10, 1)), np.array([0.3]), [ControlTask(1)], config) + ctrl_std=0.3, num_samples=81, horizon_steps=4, node_steps=1, ctrl_steps=1, + max_iterations=4 if early_stop else 2, min_improvement=1e6 if early_stop else 0, + ).add(ControlTask(1)) # fmt: skip + mpc = SimMPC(config, SIM(model, 1), np.ones((10, 1))) updates, sample = [], mpc.sampler.sample def capture(var: VarValues, scores: Optional[wp.array]) -> VarValues: if scores is None: return sample(var, scores) - plan, draws = (x.get(_Key.NODES).x.numpy().copy() for x in (mpc.plan, mpc.sampler.draws)) + plan, draws = (x.get(_Key.NODES).x.numpy().copy() for x in (mpc.plan_values, mpc.sampler.draws)) costs, out = scores.numpy().copy(), sample(var, scores) # the sampler sets the temperature from them updates.append((plan[0], draws, costs, mpc.sampler.temperatures.numpy()[0])) return out @@ -429,13 +415,17 @@ def capture(var: VarValues, scores: Optional[wp.array]) -> VarValues: class TestSimMPCInterpolation: @pytest.mark.parametrize("mode", ["linear", "cubic", "zero"]) def test_interpolation_and_shift(self, mode: str): - config = SimMPCConfig(num_samples=4, horizon_steps=30, node_steps=10, ctrl_steps=5, interpolation=mode) - mpc = _planner(mujoco.MjModel.from_xml_string(XML), np.zeros((40, 1)), np.ones(1), [], config) + model = mujoco.MjModel.from_xml_string(XML) + config = SimMPCConfig( + ctrl_std=0, num_samples=4, horizon_steps=30, node_steps=10, ctrl_steps=5, interpolation=mode + ) + mpc = SimMPC(config, SIM(model, 1), np.zeros((40, 1))) values = np.array([0, 1, 0, 2], np.float32) expected = [0.5, 0.5625, 0][["linear", "cubic", "zero"].index(mode)] assert mpc.interpolation.numpy()[5] @ values == pytest.approx(expected) mpc.execution.assign(values[None]) - mpc._simulate(0) + commands, _ = mpc.plan(mujoco.MjData(model), 0) # no node noise: the assigned plan, then shifted + np.testing.assert_allclose(commands.numpy()[:, 0, 0], mpc.interpolation.numpy()[:5] @ values, atol=1e-6) assert mpc.execution.numpy()[0, 0] == pytest.approx(expected) assert mpc.execution.numpy()[0, -1] == 0 @@ -468,6 +458,31 @@ def test_orientation_residual(self, residual: str): cost = _evaluate(model, data, SensorTask(ref, {"q": 2.0}, residual=residual)) assert cost == pytest.approx(expected, rel=2e-5, abs=1e-7) + def test_world_steps_index_each_world(self): + """With `WORLD_STEPS`, each world reads its own instance and step, as the clock would at that step, and its residuals' `0.5 |r|^2` is its cost.""" + model = mujoco.MjModel.from_xml_string(XML) + base = sim_context(SIM(model, 2, mujoco.MjData(model))) | { + SimContext.NUM_INSTANCES: 1, + SimContext.WORLDS_PER_INSTANCE: 2, + } + ref = np.arange(8.0)[:, None] * np.ones((1, model.nu)) + + def evaluate(clock: tuple, steps: Optional[list] = None) -> tuple: + term, cost = copy.copy(ControlTask(1.0, ref)), wp.zeros(2, dtype=float) + extra = {} if steps is None else {SimContext.WORLD_STEPS: wp.array(steps, dtype=wp.vec2i)} + term.resolve(None, base | {SimContext.CLOCK: wp.array(clock, dtype=int)} | extra) + term.compute_weighted_cost(None, out_cost=cost) + residual = term.compute_weighted_residual(None, out_residual=wp.zeros((2, term.residual_dim))) + return cost.numpy(), 0.5 * (residual.numpy() ** 2).sum(1) + + (mixed, half_squared), at_1, at_3 = ( + evaluate((2, 0, 8), [(0, 1), (0, 3)]), + evaluate((2, 1, 8)), + evaluate((2, 3, 8)), + ) + np.testing.assert_allclose(mixed, [at_1[0][0], at_3[0][1]]) + np.testing.assert_allclose(half_squared, mixed, rtol=1e-6) + def test_hinge_control_and_squared_tracking(self): model = mujoco.MjModel.from_xml_string(XML) data = mujoco.MjData(model) @@ -530,9 +545,8 @@ def test_contact_targets_and_tracking_schedule(self): def test_instance_references(self): """Each instance's worlds read its own row of a reference with a leading instance axis; a Warp one in place.""" model = mujoco.MjModel.from_xml_string(XML) - sim = mjwarp.MjWarpSim(model, mujoco.MjData(model)) - sim.build(2, 2, 1, 1, 0, 0) - context = sim.context("rollout") | { + sim = SIM(model, 4, mujoco.MjData(model)) + context = sim_context(sim) | { SimContext.CLOCK: wp.array([0, 0, 1], dtype=int), SimContext.NUM_INSTANCES: 2, SimContext.WORLDS_PER_INSTANCE: 2, @@ -554,42 +568,33 @@ def test_instance_references(self): class TestSimMPCBatch: @staticmethod def _instance(start: float, target: float, offset: float) -> tuple: - model = mujoco.MjModel.from_xml_string(XML) - data = mujoco.MjData(model) - data.qpos[0] = start - mujoco.mj_forward(model, data) sensor = np.zeros((80, 4)) sensor[:, :2] = target - return data, sensor, np.full((80, 1), offset) - - def _run(self, *instances: tuple, lengths=40, worlds: Optional[dict] = None, xml: str = XML, **binding) -> tuple: - model = mujoco.MjModel.from_xml_string(xml) + return start, sensor, np.full((80, 1), offset) + + def _run( + self, *instances: tuple, steps: int = 40, model=None, device: str = "cpu", mode: str = "step", callback=None + ) -> tuple: + """`SimMPC.execute` on worlds of `model`, or one world per instance of its scenes; keeps the planner's sims.""" + model = mujoco.MjModel.from_xml_string(XML) if model is None else model + starts, sensor, ctrl_ref = zip(*instances) config = SimMPCConfig( - batch_size=len(instances), - num_samples=16, - num_replicas=2, - horizon_steps=20, - node_steps=10, - ctrl_steps=10, - max_iterations=3, - min_improvement=0, - ) - data, sensor, ctrl_ref = (list(x) for x in zip(*instances)) - costs = [SensorTask(np.stack(sensor), {"x": 100.0}), ControlTask(0.01)] - binding = dict(initial_state_std={"qpos": np.array([0.01])}, **binding) - with wp.ScopedDevice("cpu"): # also runs natively on the CPU device - mpc = _planner(model, np.stack(ctrl_ref), np.full(1, 0.1), costs, config, data, binding) - assert {name: d.nworld for name, d in mpc.sim.data.items()} == dict( - execution=len(instances), rollout=len(instances) * 15 * 2, validation=len(instances) * 2 + cuda_graph_mode=mode, batch_size=len(instances), num_samples=16, num_replicas=2, horizon_steps=20, + node_steps=10, ctrl_steps=10, max_iterations=3, min_improvement=0, qpos_std=0.01, + ).add(SensorTask(np.stack(sensor), {"x": 100.0})).add(ControlTask(0.01)) # fmt: skip + nworld = len(instances) if isinstance(model, mujoco.MjModel) else [1] * len(model) + with wp.ScopedDevice(device): # also runs natively on the CPU device + mpc = SimMPC(config, SIM(model, nworld), np.stack(ctrl_ref)) + self.sims = mpc.sims + assert {name: sim.nworld for name, sim in mpc.sims.items()} == dict( + rollout=len(instances) * 15 * 2, validation=len(instances) * 2 ) - result = mpc.solve(lengths) - assert worlds is None or {name: d.nworld for name, d in mpc.sim.data.items()} == worlds - self.models = mpc.sim.models - return result + sim = SIM(model, nworld) + sim.data.qpos.assign(np.array(starts, np.float32)[:, None]) + return mpc.execute(sim, steps, callback) def test_first_instance_matches_a_single_run(self): - """The first instance of a batch draws the noise of a single run, so it is bit-identical to one; the - second, with its own noise stream, still follows its own start, reference and `ctrl_ref`.""" + """The first instance of a batch draws the noise of a single run, so it is bit-identical to one; the second, with its own noise stream, still follows its own start, reference and `ctrl_ref`.""" a, b = self._instance(0.1, 0.3, 0.0), self._instance(-0.1, -0.2, 0.05) (single_a,), (plans_a,) = self._run(a) (single_b,), (plans_b,) = self._run(b) @@ -600,87 +605,34 @@ def test_first_instance_matches_a_single_run(self): assert plans[0] == plans_a and swapped_plans[0] == plans_b assert batch[1]["qpos"][0, 0] == np.float32(-0.1) and abs(batch[1]["qpos"][-1, 0] + 0.2) < 0.05 - def test_finished_instances_leave_the_batch(self): - """With per-instance lengths, the second instance stops after its two plans and its worlds are dropped; the - first still matches a single run, and the second's plans match those of the full batch.""" + def test_partial_last_period(self): + """A length that is not a whole number of control periods stops mid-period, as the start of a longer run.""" a, b = self._instance(0.1, 0.3, 0.0), self._instance(-0.1, -0.2, 0.05) - (single,), (single_plans,) = self._run(a) full, full_plans = self._run(a, b) - worlds = dict(execution=2, rollout=15 * 2, validation=2) - compact, plans = self._run(a, b, lengths=[40, 15], worlds=worlds) - assert all(np.array_equal(compact[0][k], single[k]) for k in single) and plans[0] == single_plans - assert len(compact[1]["qpos"]) == 20 and plans[1] == full_plans[1][:2] - assert all(np.array_equal(compact[1][k], full[1][k][:20]) for k in single) - - def test_instance_parameters(self): - """Per-instance model values reach every world of their instance in instance-major order, and the first - instance (as the single run's noise) matches a single run on its own model, also as instances finish.""" + rows, plans = self._run(a, b, steps=15) + assert len(rows[1]["qpos"]) == 15 and plans == [p[:2] for p in full_plans] + assert all(np.array_equal(r[k], f[k][:15]) for r, f in zip(rows, full) for k in f) + + @pytest.mark.skipif(not wp.is_cuda_available(), reason="CUDA graphs") + def test_step_graphs_match_eager_kernels(self): + """Step graphs plan and execute exactly what eager launches do, and the callback gets each period's infos as `execute` returns them.""" a, b = self._instance(0.1, 0.3, 0.0), self._instance(-0.1, -0.2, 0.05) - damped = XML.replace('damping="5"', 'damping="20"') - (single,), (single_plans,) = self._run(b, xml=damped) - batch, plans = self._run(b, a, lengths=[40, 15], instance_parameters={"dof_damping": np.array([[20.0], [5.0]])}) + eager, eager_plans = self._run(a, b, device="cuda:0", mode="none") + seen = [] + step, step_plans = self._run(a, b, device="cuda:0", callback=seen.append) + assert step_plans == eager_plans and [p[0] for p in seen] == step_plans[0] + assert all(np.array_equal(s[k], e[k]) for s, e in zip(step, eager) for k in e) + + def test_scenes_that_differ(self): + """Each instance's scene reaches all its worlds, instance-major, and the first instance (as the single run's noise) matches a single run on its own scene, though the second's is the template.""" + a, b = self._instance(0.1, 0.3, 0.0), self._instance(-0.1, -0.2, 0.05) + heavy = XML.replace('mass="1"', 'mass="4"') + extra = XML.replace("", '') # the most geoms: the template + (single,), (single_plans,) = self._run(b, model=mujoco.MjModel.from_xml_string(heavy)) + batch, plans = self._run(b, a, model=[mujoco.MjSpec.from_string(x) for x in (heavy, extra)]) assert all(np.array_equal(batch[0][k], single[k]) for k in single) and plans[0] == single_plans - for worlds, n in dict(execution=1, rollout=30, validation=2).items(): - assert np.array_equal(self.models[worlds].dof_damping.numpy()[:, 0], np.repeat([20.0, 5.0], n)) - - def test_plan_parameters_per_instance(self): - """`plan_parameters` with an instance axis give each planning world its instance's value of its replica.""" - damping = np.array([[[20.0], [10.0]], [[5.0], [1.0]]]) # (instance, replica, dof) - self._run( - self._instance(0.1, 0.3, 0.0), self._instance(-0.1, -0.2, 0.05), plan_parameters={"dof_damping": damping} - ) for worlds, n in dict(rollout=30, validation=2).items(): - w = np.arange(2 * n) - assert np.array_equal(self.models[worlds].dof_damping.numpy()[:, 0], damping[w // n, w % 2, 0]) - assert (self.models["execution"].dof_damping.numpy() == 5.0).all() - - def test_batch_models_step_like_their_own_models(self): - """Scenes with different geoms run as one batch: each instance steps as on its own model, and the geom an - instance lacks (here under the floor) never pushes.""" - xml = """ - {}""" - scenes = [xml.format(""), xml.format('')] - model, parameters = mjwarp.batch_models([mujoco.MjSpec.from_string(x) for x in scenes]) - with wp.ScopedDevice("cpu"): - m, d = mjwarp.mjwarp.put_model(model), mjwarp.mjwarp.put_data(model, mujoco.MjData(model), nworld=2) - for name, values in parameters.items(): - shape = getattr(m, name).numpy().shape[1:] - setattr(m, name, wp.array(np.reshape(values, (2, *shape)), dtype=getattr(m, name).dtype)) - for _ in range(50): - mjwarp.mjwarp.step(m, d) - for i, x in enumerate(scenes): - own = mujoco.MjModel.from_xml_string(x) - om, od = mjwarp.mjwarp.put_model(own), mjwarp.mjwarp.put_data(own, mujoco.MjData(own)) - for _ in range(50): - mjwarp.mjwarp.step(om, od) - np.testing.assert_allclose(d.qpos.numpy()[i], od.qpos.numpy()[0], atol=1e-6) - z = d.qpos.numpy()[:, 2] # from 0.12: the lone sphere falls; the box holds the other up - assert z[0] < 0.11 and z[1] > 0.12 - - -class TestSimMPCCPUExecute: - def test_replays_controls_in_mujoco(self): - """Executed rows are MuJoCo's own states under the recorded controls; planning restarts from them.""" - model = mujoco.MjModel.from_xml_string(XML) - data = mujoco.MjData(model) - data.qpos[0] = 0.1 - mujoco.mj_forward(model, data) - config = SimMPCConfig(num_samples=16, horizon_steps=20, node_steps=10, ctrl_steps=10, max_iterations=2) - cost = SensorTask(np.full((60, 4), 0.3), {"x": 100.0}) - mpc = _planner(model, np.zeros((60, 1)), np.array([0.1]), [cost], config, data, dict(cpu_execute=True)) - (rollout,), _ = mpc.solve(30) - replay = mujoco.MjData(model) - replay.qpos[0] = 0.1 - for k, ctrl in enumerate(rollout["ctrl"]): - assert rollout["time"][k] == pytest.approx(replay.time) and rollout["qpos"][k] == pytest.approx(replay.qpos) - replay.ctrl[:] = ctrl - mujoco.mj_step(model, replay) - assert rollout["sensordata"][k] == pytest.approx(replay.sensordata) - assert mpc.sim.data["execution"].qpos.numpy()[0] == pytest.approx(replay.qpos) - assert mpc.sim.data["execution"].time.numpy()[0] == pytest.approx(replay.time) - assert data.qpos[0] == 0.1 and abs(replay.qpos[0] - 0.3) < 0.1 - with pytest.raises(ValueError, match="cpu_execute"): - mjwarp.MjWarpSim(model, data, control_map=lambda *args: None, cpu_execute=True) + assert np.array_equal(self.sims[worlds].model.body_mass.numpy()[:, 1], np.repeat([4.0, 1.0], n)) class TestSimMPCControlOffset: @@ -691,19 +643,17 @@ def test_norm_of_offsets_from_reference(self, weight: float): '' '' ) - config = SimMPCConfig( - num_samples=8, horizon_steps=4, node_steps=2, ctrl_steps=2, max_iterations=1, terminal_scale=1 - ) # fmt: skip ctrl_ref = np.arange(10)[:, None] * np.array([[0.1, -0.1]]) - mpc = _planner(model, ctrl_ref, np.zeros(2), [ControlTask(weight, ctrl_ref, norm=True)], config) - mpc.plan.get(_Key.NODES).x.assign(np.tile(np.float32([0.3, 0.4]), (1, mpc.num_nodes))) + config = SimMPCConfig( + ctrl_std=0.0, num_samples=8, horizon_steps=4, node_steps=2, ctrl_steps=2, max_iterations=1, terminal_scale=1 + ).add(ControlTask(weight, ctrl_ref, norm=True)) + mpc = SimMPC(config, SIM(model, 1), ctrl_ref) + mpc.execution.assign(np.tile(np.float32([0.3, 0.4]), (1, mpc.num_nodes))) assert mpc._optimize(2)[0]["plan_cost"] == pytest.approx(weight * 0.5, rel=1e-5, abs=1e-7) class TestSimMPCCartesianControl: def test_matches_mujoco_jacobian_after_state_changes(self): - import mujoco_warp - model = mujoco.MjModel.from_xml_string( '' '' @@ -711,9 +661,9 @@ def test_matches_mujoco_jacobian_after_state_changes(self): ) data = mujoco.MjData(model) mujoco.mj_forward(model, data) - device_model, device_data = mujoco_warp.put_model(model), mujoco_warp.put_data(model, data) + sim = MjWarpSim(model, 1, data) target = np.array([0.3, 0.1, 0.2]) - control = mjwarp.CartesianControl( + control = CartesianControl( model, "b", position_ref=target, position_gain=[1, 0.5, 0.2], rotation_gain=[0.1, 0.1, 0.1] ) for q in ([0.2, -0.1], [-0.5, 0.4]): @@ -728,16 +678,16 @@ def test_matches_mujoco_jacobian_after_state_changes(self): twist = np.r_[(target - data.body("b").xpos) * [1, 0.5, 0.2], 0.1 * angular] twist[:2] += [0.1, -0.2] expected = jac.T @ np.linalg.solve(jac @ jac.T + 1e-3 * np.eye(6), twist) - device_data.qpos.assign(np.array([q], np.float32)) - device_data.ctrl.assign(np.array([[0.1, -0.2]], np.float32)) - control(device_model, device_data, wp.array([0, 0, 1], dtype=int)) - assert device_data.ctrl.numpy()[0] == pytest.approx(expected, rel=1e-4, abs=1e-6) + sim.data.qpos.assign(np.array([q], np.float32)) + sim.data.ctrl.assign(np.array([[0.1, -0.2]], np.float32)) + control(sim, wp.array([0, 0, 1], dtype=int)) + assert sim.data.ctrl.numpy()[0] == pytest.approx(expected, rel=1e-4, abs=1e-6) class TestNewtonSim: - def test_matches_mujoco(self, tmp_path): + def test_matches_mujoco(self): """A pendulum on a cart, one body (slide then hinge, split for Featherstone), executes and senses like MuJoCo.""" - newton = pytest.importorskip("robokit.helpers.sim_mpc.newton") + newton = pytest.importorskip("robokit.sim.newton") xml = ( '' ) - (tmp_path / "scene.xml").write_text(xml) model, ctrl = mujoco.MjModel.from_xml_string(xml), np.array([0.5, 0.3]) - config = SimMPCConfig(num_samples=4, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1) - sim = newton.NewtonSim(tmp_path / "scene.xml", [0.0, 0.2], np.zeros(2)) - (rollout,), _ = SimMPC(sim, np.tile(ctrl, (60, 1)), np.zeros(2), [], config).solve(50) + config = SimMPCConfig(ctrl_std=0, num_samples=4, horizon_steps=2, node_steps=1, ctrl_steps=1, max_iterations=1) + data = mujoco.MjData(model) + data.qpos[1] = 0.2 + mpc = SimMPC(config, newton.NewtonSim(model, 1), np.tile(ctrl, (60, 1))) + (rollout,), _ = mpc.execute(newton.NewtonSim(model, 1, data), 50) data = mujoco.MjData(model) data.qpos[1] = 0.2 for row in range(50): diff --git a/tests/opt/test_graph_capture_allocation.py b/tests/opt/test_graph_capture_allocation.py index 4aec58e..d92eb3b 100644 --- a/tests/opt/test_graph_capture_allocation.py +++ b/tests/opt/test_graph_capture_allocation.py @@ -19,7 +19,7 @@ from robokit.geom import BoxGeom, MeshGeom, WarpScene from robokit.helpers.motion_plan import MotionPlanner, presets from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.utils.warp_utils import wp_vec7 @@ -90,7 +90,7 @@ def test_reused_scene_releases_discarded_planners( config.num_timesteps = 3 config.max_retries = 0 config.goal_ik.solver = PopulationSolverConfig( - num_iters=1, num_candidates=[1], optimizer=LMOptimizerConfig(), cuda_graph_mode="full" + stages=[Stage(1, 1, LMOptimizerConfig())], cuda_graph_mode="full" ) stage = config.stages[0] mppi = stage.method == "mppi" @@ -98,13 +98,12 @@ def test_reused_scene_releases_discarded_planners( { "solver": replace( stage.solver, - num_iters=1, - num_candidates=[1], + stages=[replace(stage.solver.stages[0], iters=1, num_candidates=1)], samplers=[replace(stage.solver.samplers[0], num_draws=4)], ) } if mppi - else {"solver": replace(stage.solver, num_iters=1, num_candidates=[3])} + else {"solver": replace(stage.solver, stages=[replace(stage.solver.stages[0], iters=1, num_candidates=3)])} ) config.stages = (replace(stage, **options),) scene = WarpScene(1, device) diff --git a/tests/opt/test_ilqr_optimizer.py b/tests/opt/test_ilqr_optimizer.py new file mode 100644 index 0000000..00a3d01 --- /dev/null +++ b/tests/opt/test_ilqr_optimizer.py @@ -0,0 +1,128 @@ +# pyright: reportArgumentType=false +"""`ILQROptimizer` on the pendulum example (any device) and on MuJoCo Warp worlds against MuJoCo's derivatives.""" + +from enum import Enum +from importlib import import_module + +import numpy as np +import pytest +import warp as wp + +from robokit.opt import VarValues, VectorVar +from robokit.opt.ilqr_optimizer import ILQROptimizer, ILQROptimizerConfig +from robokit.terms.simulation import ControlTask, SensorTask + + +pendulum = import_module("robokit.examples.opt.07_ilqr_pendulum") +DEVICE = "cuda" if wp.is_cuda_available() else "cpu" + +SLIDE = """""" + +FREE = """""" + + +def _make_pendulum(batch: int, horizon: int, **config) -> tuple: + optimizer = ILQROptimizer( + pendulum.Pendulum(), [pendulum.SwingUpCost()], ILQROptimizerConfig(**config), device=DEVICE + ) + starts = np.c_[np.linspace(2.5, 3.5, batch), np.zeros(batch)].astype(np.float32) + optimizer.set_start(VectorVar(wp.array(starts, dtype=float, device=DEVICE))) + return optimizer, VectorVar(wp.full((batch, horizon), 0.5, device=DEVICE)) + + +class TestILQROptimizer: + def test_solves_lower_the_cost(self): + """Taking only improving steps, every solve from the last plan lowers the pendulums' cost or keeps it, below the first plan's, with the torques in their bounds.""" + optimizer, plan = _make_pendulum(3, 30, improve=True) + costs = [optimizer.solve(plan)[1].numpy().copy() for _ in range(5)] + initial, initial_plan = _make_pendulum(3, 30, max_iter=0) + first = initial.solve(initial_plan)[1].numpy() + assert (costs[0] < first).all() and (np.diff(costs, axis=0) <= 0).all() + assert np.abs(plan.x.numpy()).max() <= pendulum.LIMIT + + def test_shifted_warm_start_replays_the_solution(self): + """From the solution's second state, `solve(shift=1)` without iterations replays it one knot on: the nominal rollout follows the shifted policy, where the feedback sees no error.""" + optimizer, plan = _make_pendulum(2, 20) + optimizer.solve(plan) + states, us = optimizer.states.x.numpy().reshape(21, 2, 2), plan.x.numpy().copy() + replay = ILQROptimizer( + pendulum.Pendulum(), [pendulum.SwingUpCost()], ILQROptimizerConfig(max_iter=0), device=DEVICE + ) + replay.set_start(VectorVar(wp.array(states[0], dtype=float, device=DEVICE))) + replay.solve(VectorVar(wp.array(us, dtype=float, device=DEVICE))) # the same solution... + wp.copy(replay.gains, optimizer.gains) # ... with its gains + replay.set_start(VectorVar(wp.array(states[1], dtype=float, device=DEVICE))) + out, _ = replay.solve(VectorVar(wp.zeros((2, 20), device=DEVICE)), shift=1.0) + np.testing.assert_allclose(replay.states.x.numpy().reshape(21, 2, 2)[:19], states[1:20], atol=1e-5) + np.testing.assert_allclose(out.x.numpy()[:, :18], us[:, 1:19], atol=1e-6) + + def test_states_difference_inverts_integrate(self): + """For vectors, joint positions with free, ball and hinge joints, and both together in a `VarValues`: `x.integrate(x.difference(y))` is `y`, also on views at an offset.""" + mujoco = pytest.importorskip("mujoco") + QposVar = pytest.importorskip("robokit.sim").QposVar + model = mujoco.MjModel.from_xml_string(""" + + """) + rng = np.random.default_rng(0) + + def qpos(b: int) -> wp.array: + q = rng.normal(size=(b, model.nq)) + q[:, 3:7] /= np.linalg.norm(q[:, 3:7], axis=1, keepdims=True) + q[:, 7:11] /= np.linalg.norm(q[:, 7:11], axis=1, keepdims=True) + return wp.array(q, dtype=float) + + class Key(Enum): + Q, V = 0, 1 + + def var(b: int) -> VarValues: + return VarValues( + {Key.Q: QposVar(qpos(b), model), Key.V: VectorVar(wp.array(rng.normal(size=(b, 2)), dtype=float))} + ) + + x, y = var(6).view(4, offset=2), var(4) + z = x.integrate(x.difference(y)) # quaternions up to sign: the same turn + np.testing.assert_allclose(z.difference(y).numpy(), 0.0, atol=1e-5) + np.testing.assert_allclose(z.get(Key.V).x.numpy(), y.get(Key.V).x.numpy(), atol=1e-6) + + @pytest.mark.parametrize("free", [False, True]) + def test_jacobians_match_mujoco(self, free: bool): + """A ball on a frictionless floor (free: on a free joint, tilted): every knot's float32 forward differences match MuJoCo's float64 central ones (`mjd_transitionFD`) along the zero-control rollout, after the contact's first knot (where central differences straddle its onset).""" + mujoco = pytest.importorskip("mujoco") + pytest.importorskip("mujoco_warp") + sim = pytest.importorskip("robokit.sim") + model, N, T = mujoco.MjModel.from_xml_string(FREE if free else SLIDE), 2, 10 + nq, nv, nu = model.nq, model.nv, model.nu + x0 = np.zeros((N, nq + nv)) + x0[:, 0], x0[:, nq] = [0.0, 0.2], [0.5, -0.3] + if free: # z, a tilted quaternion + x0[:, 2:7] = [0.1, np.cos(0.2), 0.0, 0.6 * np.sin(0.2), 0.8 * np.sin(0.2)] + dynamics = sim.SimDynamics(sim.MjWarpSim(model, 1)) + + weight, ref = np.zeros(model.nsensordata), np.zeros((1, model.nsensordata)) + weight[0], weight[3 if free else 1], ref[0, 0] = 0.5, 0.045, 0.5 # x to 0.5, slowly (its velocity sensor) + terms = [SensorTask(ref, weight), ControlTask(0.005)] # with little force + with wp.ScopedDevice(DEVICE): + optimizer = ILQROptimizer(dynamics, terms, ILQROptimizerConfig(state_eps=1e-4), device=DEVICE) + optimizer.set_start(dynamics.build_state(x0[:, :nq], x0[:, nq:])) + optimizer.solve(VectorVar(wp.zeros((N, T * nu)))) + data, A, B = mujoco.MjData(model), np.zeros((2 * nv, 2 * nv)), np.zeros((2 * nv, nu)) + for i, x in enumerate(x0): + data.qpos, data.qvel = x[:nq], x[nq:] + for t in range(T): + data.qacc_warmstart[:] = 0 # as each finite difference starts + mujoco.mjd_transitionFD(model, data, 1e-6, True, A, B, None, None) + if t > 0: + want = np.c_[A, B] + np.testing.assert_allclose( + optimizer.dynamics_jacobians.numpy()[i, t], want, atol=1e-2 * np.abs(want).max() + ) + mujoco.mj_step(model, data) diff --git a/tests/opt/test_iteration_callback.py b/tests/opt/test_iteration_callback.py index 45ba9eb..76b0866 100644 --- a/tests/opt/test_iteration_callback.py +++ b/tests/opt/test_iteration_callback.py @@ -7,7 +7,7 @@ import pytest import warp as wp -from robokit.opt import PopulationSolver, PopulationSolverConfig, VarValues, VectorVar +from robokit.opt import PopulationSolver, PopulationSolverConfig, Stage, VarValues, VectorVar from robokit.opt.gd_optimizer import GDOptimizer, GDOptimizerConfig from robokit.opt.lbfgs_optimizer import LBFGSOptimizer, LBFGSOptimizerConfig from robokit.opt.lm_optimizer import LMOptimizer, LMOptimizerConfig @@ -158,29 +158,22 @@ def test_population_solvers(self): task = QuadraticTask() for weighting in ("softmax", "fitness_shaping"): sampler = GaussianSamplerConfig(var_key=Key.X, num_draws=32, weighting=weighting) - config = PopulationSolverConfig(num_iters=2, num_candidates=[1], cuda_graph_mode="none", samplers=[sampler]) + config = PopulationSolverConfig(stages=[Stage(2)], cuda_graph_mode="none", samplers=[sampler]) self._run(PopulationSolver([[task]], config, "cpu")) for device in ("cpu", "cuda:0") if wp.is_cuda_available() else ("cpu",): for linear_solver in ("cg", "cholesky"): for mode in ("none", "iter"): config = PopulationSolverConfig( - num_iters=2, - num_candidates=[1], + stages=[Stage(2, 1, LMOptimizerConfig(linear_solver=linear_solver))], cuda_graph_mode=mode, use_early_stopping=False, - optimizer=LMOptimizerConfig(linear_solver=linear_solver), ) self._run(PopulationSolver([[SparseQuadraticTask()]], config, device), device=device) def test_multi_seed_forwards_callback(self): solver = PopulationSolver( [[QuadraticTask()], [QuadraticTask()]], - PopulationSolverConfig( - num_iters=1 + 1, - select_at=[1], - num_candidates=[1, 1], - cuda_graph_mode="none", - ), + PopulationSolverConfig(stages=[Stage(1), Stage(1)], cuda_graph_mode="none"), "cpu", ) self._run(solver) @@ -210,7 +203,7 @@ def test_full_cuda_graph_rejects_callback(self): population = PopulationSolver( [[QuadraticTask()]], - PopulationSolverConfig(num_iters=1, num_candidates=[1], cuda_graph_mode="full"), + PopulationSolverConfig(stages=[Stage(1)], cuda_graph_mode="full"), wp.get_device("cuda:0"), ) with pytest.raises(ValueError, match="full-solve CUDA graph"): @@ -303,8 +296,7 @@ def test_cuda_graph_matches_eager_and_preserves_input(self): graph_solver = PopulationSolver( [[QuadraticTask()]], PopulationSolverConfig( - num_iters=2, - num_candidates=[1], + stages=[Stage(2)], cuda_graph_mode="full", samplers=[GaussianSamplerConfig(var_key=Key.X, num_draws=32, seed=7)], ), @@ -316,8 +308,7 @@ def test_cuda_graph_matches_eager_and_preserves_input(self): eager_result, _ = PopulationSolver( [[QuadraticTask()]], PopulationSolverConfig( - num_iters=2, - num_candidates=[1], + stages=[Stage(2)], cuda_graph_mode="none", samplers=[GaussianSamplerConfig(var_key=Key.X, num_draws=32, seed=7)], ), @@ -343,7 +334,7 @@ def record(iteration: int, values: VarValues, costs: wp.array): solver = PopulationSolver( [[QuadraticTask(), QuadraticTask()], [QuadraticTask()]], - PopulationSolverConfig(num_iters=2, select_at=[1], num_candidates=[2, 1], cuda_graph_mode="none"), + PopulationSolverConfig(stages=[Stage(1, 2), Stage(1, 1)], cuda_graph_mode="none"), "cpu", ) candidates = VarValues.from_var( diff --git a/tests/opt/test_population_solver.py b/tests/opt/test_population_solver.py index 3cdd150..622d087 100644 --- a/tests/opt/test_population_solver.py +++ b/tests/opt/test_population_solver.py @@ -13,7 +13,7 @@ from robokit.opt.gd_optimizer import GDOptimizer, GDOptimizerConfig from robokit.opt.lbfgs_optimizer import LBFGSOptimizer, LBFGSOptimizerConfig from robokit.opt.lm_optimizer import LMOptimizer, LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import _CPU_CAPTURE, PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.sampler import GaussianSamplerConfig, RobertsSamplerConfig from robokit.opt.var_values import VarKey, VarValues, VectorVar from robokit.robo.robot import Robot @@ -26,7 +26,7 @@ def _solver(self, **config_kwargs) -> PopulationSolver: q = wp.from_numpy(np.zeros((4, robot.num_actuated_joints), dtype=np.float32), dtype=wp.float32, device="cpu") solver = PopulationSolver( terms=[[ConfigurationTask(robot, weight=1.0)]], - config=PopulationSolverConfig(num_iters=1, num_candidates=[2], **config_kwargs), + config=PopulationSolverConfig(stages=[Stage(1, 2, **config_kwargs)]), device="cpu", ) solver.setup(VarValues({VarKey.ROBOT: robot.state(q=q)})) @@ -57,7 +57,7 @@ def test_solved_optimizer_frees_without_gc(self, optimizer): def solve() -> weakref.ref: solver = PopulationSolver( [[ConfigurationTask(robot, weight=1.0)]], - PopulationSolverConfig(num_iters=2, optimizer=optimizer), + PopulationSolverConfig(stages=[Stage(2, optimizer=optimizer)]), device="cpu", ) solver.solve(VarValues({VarKey.ROBOT: robot.state(q=q)})) @@ -81,11 +81,9 @@ def test_outer_capture_replays_updates(self, mode: str): solver = PopulationSolver( [QuadraticTask()], PopulationSolverConfig( - num_iters=1, - num_candidates=[1], + stages=[Stage(1, 1, GDOptimizerConfig(learning_rate=0.5, early_stopping_interval=1))], cuda_graph_mode=mode, use_early_stopping=True, - optimizer=GDOptimizerConfig(learning_rate=0.5, early_stopping_interval=1), ), "cuda:0", ) @@ -155,17 +153,15 @@ def _solve(self, var: VarValues, terms=None, score_terms=None, **config) -> tupl def test_final_sample_returns_the_cost_of_the_moved_population(self): result, costs = self._solve( self._x(), - num_iters=1, - optimizer=GDOptimizerConfig(learning_rate=0.0), + stages=[Stage(1, optimizer=GDOptimizerConfig(learning_rate=0.0)), Stage(0)], # sample at the last select samplers=[RobertsSamplerConfig(var_key=Key.X, scale=[2.0, 0.0])], - sample_at=[1], ) np.testing.assert_allclose(costs.numpy(), 0.5 * np.sum(result.get(Key.X).x.numpy() ** 2, axis=1)) def test_best_mode_lands_on_the_optimized_draw(self): sampler = GaussianSamplerConfig(sample_mode="best", var_key=Key.X, num_draws=8) result, costs = self._solve( - self._x(), num_iters=1, optimizer=GDOptimizerConfig(learning_rate=1.0), samplers=[sampler] + self._x(), stages=[Stage(1, optimizer=GDOptimizerConfig(learning_rate=1.0))], samplers=[sampler] ) np.testing.assert_allclose(result.get(Key.X).x.numpy(), 0.0, atol=1e-6) # one GD step solves the quadratic np.testing.assert_allclose(costs.numpy(), 0.0, atol=1e-6) @@ -179,23 +175,21 @@ def compute_weighted_residual(self, var_values, out_residual=None, row_offset=0) self._solve( self._x(), score_terms=CheckedQuadraticTask(), - num_iters=1, + stages=[Stage(1)], samplers=[GaussianSamplerConfig(var_key=Key.X, num_draws=8)], ) def test_sampling_with_zero_iterations_still_samples(self): result, _ = self._solve( - self._x(), num_iters=0, samplers=[RobertsSamplerConfig(var_key=Key.X, scale=[2.0, 0.0])], sample_at=[0] + self._x(), stages=[Stage(0), Stage(0)], samplers=[RobertsSamplerConfig(var_key=Key.X, scale=[2.0, 0.0])] ) np.testing.assert_allclose(result.get(Key.X).x.numpy(), [[1.0, 0.0]]) def test_a_sample_restarts_the_optimizer(self): result, _ = self._solve( self._x(), - num_iters=2, - optimizer=GDOptimizerConfig(learning_rate=1.0), + stages=[Stage(1, optimizer=GDOptimizerConfig(learning_rate=1.0)), Stage(1, sample_every=1)], samplers=[RobertsSamplerConfig(var_key=Key.X, scale=[2.0, 0.0])], - sample_at=[1], ) np.testing.assert_allclose(result.get(Key.X).x.numpy(), 0.0, atol=1e-6) @@ -218,7 +212,7 @@ def test_shared_config_has_independent_samplers_and_releases_buffers(self, devic if device.startswith("cuda") and not wp.is_cuda_available(): pytest.skip("CUDA required") config = PopulationSolverConfig( - num_iters=3, + stages=[Stage(3)], cuda_graph_mode="full", use_early_stopping=False, samplers=[GaussianSamplerConfig(var_key=Key.X, num_draws=8, seed=7)], @@ -251,19 +245,44 @@ def test_rejects_runtime_samplers_and_nested_annealing(self): with pytest.raises(TypeError, match="SamplerConfig"): PopulationSolverConfig(samplers=[RobertsSampler(1, [0.1])]) var = VarValues({Key.X: VectorVar(wp.array([[2.0, 0.0]], dtype=wp.float32, device="cpu"))}) - for optimizer in (AnnealedGDConfig(), [AnnealedGDConfig()]): - solver = PopulationSolver([QuadraticTask()], PopulationSolverConfig(optimizer=optimizer), "cpu") - with pytest.raises(ValueError, match="AnnealedGDConfig"): - solver.setup(var) + solver = PopulationSolver( + [QuadraticTask()], PopulationSolverConfig(stages=[Stage(10, optimizer=AnnealedGDConfig())]), "cpu" + ) + with pytest.raises(ValueError, match="AnnealedGDConfig"): + solver.setup(var) def test_implicit_sampling_schedule_tracks_changed_iterations(self): from dataclasses import replace config = PopulationSolverConfig( - num_iters=1, cuda_graph_mode="none", samplers=[GaussianSamplerConfig(var_key=Key.X, num_draws=8)] + stages=[Stage(1)], cuda_graph_mode="none", samplers=[GaussianSamplerConfig(var_key=Key.X, num_draws=8)] ) - longer = replace(config, num_iters=4) + longer = replace(config, stages=[Stage(4)]) solver = PopulationSolver([QuadraticTask()], longer, "cpu") solver.solve(VarValues({Key.X: VectorVar(wp.array([[2.0, 1.0]], dtype=wp.float32, device="cpu"))})) assert solver.samplers[0]._round == 5 - assert config.sample_at == () + assert config.sample_at == [] + + +_HALVING = GDOptimizerConfig(learning_rate=0.5) # halves x every iteration + + +class TestCpuReplay: + """On Warp 1.15+, a "full" CPU solve is recorded once and replayed natively.""" + + @pytest.mark.skipif(not _CPU_CAPTURE, reason="CPU replay needs Warp 1.15+") + @pytest.mark.parametrize( + ("stages", "expected"), + [ + ([Stage(2, 1, _HALVING)], [[[2.0, 0.0], [0.5, 0.0]], [[1.5, 0.0], [5.0, 0.0]]]), + ([Stage(1, 2, _HALVING), Stage(1, 1)], [[[0.5, 0.0]], [[1.5, 0.0]]]), + ], + ) + def test_replay_solves_each_new_population(self, stages, expected): + config = PopulationSolverConfig(stages=stages, cuda_graph_mode="full") + solver = PopulationSolver([QuadraticTask()], config, "cpu") + for values, want in zip(((8.0, 2.0), (6.0, 20.0)), expected): + x = wp.array(np.array([[v, 0.0] for v in values], dtype=np.float32), dtype=wp.float32, device="cpu") + result, _ = solver.solve(VarValues({Key.X: VectorVar(x)})) + np.testing.assert_allclose(result.get(Key.X).x.numpy(), want) + assert solver._full_graph is not None diff --git a/tests/opt/test_population_updaters.py b/tests/opt/test_population_updaters.py index 51e19d6..8843b29 100644 --- a/tests/opt/test_population_updaters.py +++ b/tests/opt/test_population_updaters.py @@ -14,7 +14,7 @@ from robokit.lie.se3 import se3_identity from robokit.opt.lbfgs_optimizer import LBFGSOptimizer, LBFGSOptimizerConfig from robokit.opt.lm_optimizer import LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.sampler import RobertsSamplerConfig from robokit.opt.var_values import VarKey, VarValues from robokit.robo.robot import Robot @@ -55,10 +55,7 @@ def test_full_cuda_graph_mode_caps_lbfgs_eager_warmup_iters(self): configured_max_iter = 20 solver_config = PopulationSolverConfig( - num_iters=configured_max_iter, - num_candidates=[1], - cuda_graph_mode="full", - optimizer=LBFGSOptimizerConfig(), + stages=[Stage(configured_max_iter, 1, LBFGSOptimizerConfig())], cuda_graph_mode="full" ) solver = PopulationSolver( terms=[[FrameTask(robot, target_link_index, target_pose, 10.0, 5.0)]], @@ -145,13 +142,10 @@ def test_solver_multistage(self): base_state = robot.state(q=q_base) solver_config = PopulationSolverConfig( - num_iters=init_iters + mid_iters + final_iters, - select_at=[init_iters, init_iters + mid_iters], - num_candidates=[num_candidates, num_candidates_mid, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=5.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(init_iters, num_candidates, LMOptimizerConfig(lm_lambda=10.0)), + Stage(mid_iters, num_candidates_mid, LMOptimizerConfig(lm_lambda=5.0)), + Stage(final_iters, 1, LMOptimizerConfig(lm_lambda=1.0)), ], cuda_graph_mode="none", ) @@ -194,7 +188,7 @@ def test_solver_selects_terminal_seed_with_score_terms(self): solver = PopulationSolver( terms=[[ConfigurationTask(robot=robot, rest_q=q0)]], score_terms=[ConfigurationTask(robot=robot, rest_q=q1)], - config=PopulationSolverConfig(num_iters=0, num_candidates=[2], cuda_graph_mode="none"), + config=PopulationSolverConfig(stages=[Stage(0, 2)], cuda_graph_mode="none"), device=device, ) @@ -214,13 +208,10 @@ def test_solver_stage_handoff_cost_consistency_with_mobile_smoothness(self): IKSolverConfig( enable_T_world_base=True, solver=PopulationSolverConfig( - num_iters=4 + 6, - select_at=[4, 4 + 6], - num_candidates=[8, 2, 1], - optimizer=[ - LMOptimizerConfig(lm_lambda=10.0), - LMOptimizerConfig(lm_lambda=1.0), - LMOptimizerConfig(lm_lambda=1.0), + stages=[ + Stage(4, 8, LMOptimizerConfig(lm_lambda=10.0)), + Stage(6, 2, LMOptimizerConfig(lm_lambda=1.0)), + Stage(0, 1), ], cuda_graph_mode="none", ), diff --git a/tests/opt/test_sampler.py b/tests/opt/test_sampler.py index 1ca16e3..e7926fd 100644 --- a/tests/opt/test_sampler.py +++ b/tests/opt/test_sampler.py @@ -2,7 +2,7 @@ import pytest import warp as wp -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.sampler import ( GaussianSampler, GaussianSamplerConfig, @@ -77,9 +77,7 @@ def _solve(self, samplers, mode, device): num_dofs = robot.num_actuated_joints q = wp.from_numpy(np.zeros((4 * 3, num_dofs), dtype=np.float32), dtype=wp.float32, device=device) config = PopulationSolverConfig( - num_iters=0, - select_at=[0], - num_candidates=[3, 2], + stages=[Stage(0, 3), Stage(0, 2)], cuda_graph_mode=mode, samplers=samplers, ) @@ -170,7 +168,7 @@ def test_elite_rule_decay_and_bounds(self, device): def test_cost_only_task_and_plateau_stop(self, min_improvement): """PopulationSolver's MPPI scores with a cost-only task; a plateau ends the solve after `patience` scores.""" sampler = GaussianSamplerConfig(num_draws=64, init_std=0.2, seed=1) - config = PopulationSolverConfig(num_iters=20, samplers=[sampler], cuda_graph_mode="none", patience=3) + config = PopulationSolverConfig(stages=[Stage(20)], samplers=[sampler], cuda_graph_mode="none", patience=3) config.min_improvement = min_improvement solver, scores = PopulationSolver([_DistanceTask()], config, "cpu"), [] solver.setup(VarValues({VarKey.ROBOT: VectorVar(wp.zeros((2, 3), device="cpu"))})) diff --git a/tests/opt/test_sampling_updates.py b/tests/opt/test_sampling_updates.py index 7c1f695..828bdef 100644 --- a/tests/opt/test_sampling_updates.py +++ b/tests/opt/test_sampling_updates.py @@ -20,7 +20,7 @@ MppiTrajectoryOptimizer, MppiTrajectoryOptimizerConfig, ) -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.sampler import GaussianSamplerConfig from robokit.opt.var_values import VarKey, VarValues from robokit.robo import Robot @@ -45,7 +45,7 @@ def _init_cost(task, state): def _mppi_config(*, num_iters: int, sampler: ColoredGaussianSamplerConfig, **kwargs) -> MppiTrajectoryOptimizerConfig: """Every weighted term off, as the tests pass their own.""" return MppiTrajectoryOptimizerConfig( - terms=[], solver=PopulationSolverConfig(num_iters=num_iters, samplers=[sampler]), **kwargs + terms=[], solver=PopulationSolverConfig(stages=[Stage(num_iters)], samplers=[sampler]), **kwargs ) @@ -236,7 +236,7 @@ def test_selects_terminal_seed_with_score_terms(self, panda_robot): solver = PopulationSolver( terms=[[ConfigurationTask(robot=robot, rest_q=q0)]], score_terms=[ConfigurationTask(robot=robot, rest_q=q1)], - config=PopulationSolverConfig(num_iters=0, num_candidates=[2], cuda_graph_mode="none"), + config=PopulationSolverConfig(stages=[Stage(0, 2)], cuda_graph_mode="none"), device=device, ) @@ -256,7 +256,7 @@ def test_mppi_minimizes_rest_cost(self, panda_robot): init = _init_cost(task, robot.state(q=wp.from_numpy(start_q, dtype=wp.float32, device=device))) sampler = GaussianSamplerConfig(init_std=0.25, temperature=0.05, var_key=VarKey.ROBOT, num_draws=256) - config = PopulationSolverConfig(num_iters=60, num_candidates=[1], cuda_graph_mode="none", samplers=[sampler]) + config = PopulationSolverConfig(stages=[Stage(60)], cuda_graph_mode="none", samplers=[sampler]) solver = PopulationSolver(terms=[[task]], config=config, device=device) var = VarValues({VarKey.ROBOT: robot.state(q=wp.from_numpy(start_q, dtype=wp.float32, device=device))}) best_var, best_costs = solver.solve(var) @@ -276,8 +276,7 @@ def test_mppi_respects_active_dof_mask(self, panda_robot): solver = PopulationSolver( terms=[[ConfigurationTask(robot=robot, rest_q=rest_q)]], config=PopulationSolverConfig( - num_iters=40, - num_candidates=[1], + stages=[Stage(40)], cuda_graph_mode="none", samplers=[GaussianSamplerConfig(num_draws=256, var_key=VarKey.ROBOT, init_std=0.25)], ), @@ -315,7 +314,7 @@ def test_mppi_is_deterministic(self, panda_robot): task = ConfigurationTask(robot=robot, rest_q=rest_q, weight=1.0) sampler = GaussianSamplerConfig(seed=7, var_key=VarKey.ROBOT, num_draws=128) - config = PopulationSolverConfig(num_iters=20, num_candidates=[1], cuda_graph_mode="none", samplers=[sampler]) + config = PopulationSolverConfig(stages=[Stage(20)], cuda_graph_mode="none", samplers=[sampler]) costs = [] for _ in range(2): @@ -333,7 +332,7 @@ def test_mppi_solve_is_reusable(self, panda_robot): rest_q = robot.spec.midrange_q.astype(np.float32) task = ConfigurationTask(robot=robot, rest_q=rest_q, weight=1.0) sampler = GaussianSamplerConfig(init_std=0.25, var_key=VarKey.ROBOT, num_draws=256) - config = PopulationSolverConfig(num_iters=40, num_candidates=[1], cuda_graph_mode="none", samplers=[sampler]) + config = PopulationSolverConfig(stages=[Stage(40)], cuda_graph_mode="none", samplers=[sampler]) solver = PopulationSolver(terms=[[task]], config=config, device=device) first = VarValues( diff --git a/tests/opt/test_sampling_weighting.py b/tests/opt/test_sampling_weighting.py index 517fa18..e0661b1 100644 --- a/tests/opt/test_sampling_weighting.py +++ b/tests/opt/test_sampling_weighting.py @@ -6,7 +6,7 @@ import pytest import warp as wp -from robokit.opt import PopulationSolver, PopulationSolverConfig, VarValues, VectorVar +from robokit.opt import PopulationSolver, PopulationSolverConfig, Stage, VarValues, VectorVar from robokit.opt.sampler import GaussianSamplerConfig from robokit.terms.task import ResidualTask @@ -57,7 +57,7 @@ class TestSamplingSolver: def _solve(self) -> np.ndarray: task = QuadraticTask(2) sampler = _gaussian(num_draws=256, weighting="fitness_shaping", init_std=1.0, min_std=1.0, learning_rate=0.1) - config = PopulationSolverConfig(num_iters=60, num_candidates=[1], cuda_graph_mode="none", samplers=[sampler]) + config = PopulationSolverConfig(stages=[Stage(60)], cuda_graph_mode="none", samplers=[sampler]) solver = PopulationSolver(terms=[[task]], config=config, device="cpu") var = VarValues.from_var(VectorVar(wp.array([[2.0, -1.5]], dtype=wp.float32, device="cpu")), Key.X) result, _ = solver.solve(var) @@ -77,7 +77,7 @@ def test_best_sample_mode_recandidates_each_iteration(self): outputs = {} for sample_mode in ("mean", "best"): sampler = _gaussian(num_draws=64, init_std=0.5, sample_mode=sample_mode) - config = PopulationSolverConfig(num_iters=4, cuda_graph_mode="none", samplers=[sampler]) + config = PopulationSolverConfig(stages=[Stage(4)], cuda_graph_mode="none", samplers=[sampler]) solver = PopulationSolver(terms=[[task]], config=config, device="cpu") values = VarValues.from_var(VectorVar(wp.array(start, dtype=wp.float32, device="cpu")), Key.X) history = [] @@ -102,7 +102,7 @@ def test_best_sample_mode_preserves_instance_major_layout(self): sampler = _gaussian(num_draws=32, init_std=0.5, sample_mode="best") solver = PopulationSolver( terms=[[task]], - config=PopulationSolverConfig(num_iters=2, num_candidates=[2], cuda_graph_mode="none", samplers=[sampler]), + config=PopulationSolverConfig(stages=[Stage(2, 2)], cuda_graph_mode="none", samplers=[sampler]), device="cpu", ) result, costs = solver.solve( @@ -124,9 +124,7 @@ def test_best_sample_mode_cuda_graph_matches_eager(self): ) solver = PopulationSolver( terms=[[task]], - config=PopulationSolverConfig( - num_iters=4, num_candidates=[1], cuda_graph_mode=cuda_graph_mode, samplers=[sampler] - ), + config=PopulationSolverConfig(stages=[Stage(4)], cuda_graph_mode=cuda_graph_mode, samplers=[sampler]), device="cuda:0", ) result, costs = solver.solve( diff --git a/tests/opt/test_var_values.py b/tests/opt/test_var_values.py index d9ad46e..a2713c1 100644 --- a/tests/opt/test_var_values.py +++ b/tests/opt/test_var_values.py @@ -6,7 +6,7 @@ from robokit.lie.se3 import SE3Var, se3_compose, se3_identity, se3_inverse, se3_log from robokit.opt.lm_optimizer import LMOptimizer, LMOptimizerConfig -from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolver, PopulationSolverConfig, Stage from robokit.opt.var_values import VarKey, VarValues from robokit.terms import FrameTask, PositionLimit from robokit.terms.autodiff import autodiff_weighted_jacobian @@ -197,9 +197,7 @@ def test_multi_seed_solver_converges(self): solver = PopulationSolver( terms=[[SE3TargetTask(target=target, var_key=Key.POSE)]], config=PopulationSolverConfig( - num_iters=50, - num_candidates=[num_candidates], - optimizer=LMOptimizerConfig(lm_lambda=1.0), + stages=[Stage(50, num_candidates, LMOptimizerConfig(lm_lambda=1.0))], cuda_graph_mode="none", ), device=device, diff --git a/tests/sim/test_mjscene.py b/tests/sim/test_mjscene.py new file mode 100644 index 0000000..fae203e --- /dev/null +++ b/tests/sim/test_mjscene.py @@ -0,0 +1,47 @@ +from pathlib import Path + +import numpy as np +import pytest + + +pytest.importorskip("mujoco_warp") # robokit.sim targets the MuJoCo that MuJoCo Warp brings; older MjSpec differs +mujoco = pytest.importorskip("mujoco") +mjscene = pytest.importorskip("robokit.sim.mjscene") + +ARM_XML = """ + +""" +DOG_XML = """ +""" + + +class TestMjScene: + def test_scene(self, tmp_path: Path): + (tmp_path / "arm.xml").write_text(ARM_XML) + (tmp_path / "dog.xml").write_text(DOG_XML) + arm = mjscene.build_robot_spec(tmp_path / "arm.xml", prefix="arm/") + dog = mjscene.build_robot_spec(tmp_path / "dog.xml", prefix="dog/", body="trunk") + spec = mjscene.build_scene_spec( + [(arm, (0.0, 0.0, 0.4, 1.0, 0.0, 0.0, 0.0)), (dog, (-1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0))], timestep=0.004 + ) + model = spec.compile() + data = mujoco.MjData(model) + mujoco.mj_forward(model, data) + assert model.opt.timestep == 0.004 + assert (model.nu, model.nbody, model.nlight) == (1, 4, 1) # world, arm base and link, dog trunk: no leg + assert model.actuator(0).name == "arm/joint" + np.testing.assert_allclose(data.body("arm/link").xpos, (0.0, 0.0, 0.5), atol=1e-9) + np.testing.assert_allclose(data.body("dog/trunk").xpos, (-1.0, 0.0, 0.3), atol=1e-9) + for _ in range(100): + mujoco.mj_step(model, data) + assert data.body("dog/trunk").xpos[2] == pytest.approx(0.1, abs=2e-3) # fell onto the floor + + def test_terrain(self): + spec = mjscene.build_scene_spec(floor=False) + origins = mjscene.build_terrain(spec) + model = spec.compile() + assert origins.shape == (10, 7, 3) + assert model.nhfield == 40 # slope, slope_inv, random_rough and wave columns + assert model.geom(0).name == "terrain_0" and model.hfield(0).name == "hfield_0_3" + np.testing.assert_array_equal(origins[0, 0], (-36.0, -24.0, 0.0)) # the first flat tile + np.testing.assert_array_equal(origins[:, 0, 2], 0.0) diff --git a/tests/sim/test_sim.py b/tests/sim/test_sim.py new file mode 100644 index 0000000..5a3b61e --- /dev/null +++ b/tests/sim/test_sim.py @@ -0,0 +1,209 @@ +# pyright: reportArgumentType=false +"""`MjWarpSim` on the CPU against MuJoCo: steps, substep sensordata, resets, per-world model fields and enclosing captures.""" + +import numpy as np +import pytest +import warp as wp + + +mujoco = pytest.importorskip("mujoco") +MjWarpSim = pytest.importorskip("robokit.sim.mjwarp").MjWarpSim + +XML = """ + + +""" +STATE = ("qpos", "qvel", "act", "ctrl", "qacc_warmstart", "time") + + +class TestSim: + def test_step_matches_mujoco(self): + """Two substeps per step: the state follows `mj_step` and `data.substep_sensordata[k]` is `sensordata` after substep `k`.""" + model = mujoco.MjModel.from_xml_string(XML) + data = mujoco.MjData(model) + data.qpos[:], data.ctrl[:] = [0.1, 0.3], [0.5, 0.2] + sim = MjWarpSim(model, nworld=3, data=data, substeps=2, device="cpu") + assert sim.stream is None and sim.data.substep_sensordata.shape == (2, 3, model.nsensordata) + for _ in range(3): + sim.step() + for k in range(2): + mujoco.mj_step(model, data) + np.testing.assert_allclose( + sim.data.substep_sensordata.numpy()[k], np.tile(data.sensordata, (3, 1)), atol=1e-5 + ) + for field in STATE: + np.testing.assert_allclose(getattr(sim.data, field).numpy()[1], getattr(data, field), atol=1e-5) + assert sim._graphs == {} # the CPU launches directly + sim.data.qpos.fill_(0.0) + sim.forward() + mujoco.mj_resetData(model, data) + mujoco.mj_forward(model, data) + np.testing.assert_allclose(sim.data.xpos.numpy()[2], data.xpos, atol=1e-6) + sim.data.qpos.fill_(0.3) + sim.kinematics() + sim.com_pos() + data.qpos[:] = 0.3 + mujoco.mj_kinematics(model, data) + mujoco.mj_comPos(model, data) + np.testing.assert_allclose(sim.data.subtree_com.numpy()[2], data.subtree_com, atol=1e-6) + + def test_reset(self): + """`reset` restores the masked worlds to `data`, else keyframe `key`, else the defaults, then their kinematics.""" + model = mujoco.MjModel.from_xml_string(XML) + data, key, defaults = mujoco.MjData(model), mujoco.MjData(model), mujoco.MjData(model) + data.qpos[:], data.qvel[:], data.act[:], data.ctrl[:], data.time = [0.4, -0.3], [1, 2], [0.7], [2, 0], 1.0 + data.qacc_warmstart[:] = [0.1, 0.2] + mujoco.mj_resetDataKeyframe(model, key, 0) + for initial, kwargs in ((defaults, {}), (key, dict(key="k")), (data, dict(data=data))): + sim = MjWarpSim(model, nworld=4, device="cpu", **kwargs) + sim.data.ctrl.fill_(1.0) + sim.step() + before = {field: getattr(sim.data, field).numpy().copy() for field in STATE} + for mask in ( + wp.array([1, 0, 1, 0], dtype=int, device="cpu"), + wp.array([1, 0, 1, 0], dtype=bool, device="cpu"), + ): + sim.reset(mask) + for field in STATE: + x = getattr(sim.data, field).numpy() + np.testing.assert_allclose(x[[0, 2]], np.broadcast_to(getattr(initial, field), x[[0, 2]].shape)) + np.testing.assert_array_equal(x[[1, 3]], before[field][[1, 3]]) + mujoco.mj_kinematics(model, initial) + np.testing.assert_allclose(sim.data.xpos.numpy()[0], initial.xpos, atol=1e-6) + + def test_model_fields(self): + """Model fields get a row per world once, accept per-world arrays, and change those worlds' physics.""" + model = mujoco.MjModel.from_xml_string(XML) + sim = MjWarpSim(model, nworld=3, device="cpu") + assert sim.model.body_parentid.shape == (model.nbody,) # shared by every world + mass = sim.model.body_mass + assert mass.shape == (3, model.nbody) and sim.model.body_mass is mass and sim._m.body_mass is mass + friction = wp.zeros((5, model.ngeom), dtype=wp.vec3, device="cpu") # more rows than worlds: kept + sim._graphs["step"] = None # a graph holding the old arrays + sim.model.geom_friction = friction + assert sim.model.geom_friction is friction and sim._m.geom_friction is friction and sim._graphs == {} + sim._graphs["step"] = None + sim.opt.iterations = 50 # options too drop the graphs, which hold the old ones + assert sim._m.opt.iterations == 50 and sim._graphs == {} + scale = np.array([1.0, 2.0, 4.0]) # every mass and inertia, so the mass matrix scales too + sim.model.body_mass = wp.array(np.outer(scale, model.body_mass), dtype=float, device="cpu") + sim.model.body_inertia = wp.array(scale[:, None, None] * model.body_inertia, dtype=wp.vec3, device="cpu") + sim.set_const() + sim.data.ctrl.fill_(1.0) + sim.step() + qvel = sim.data.qvel.numpy()[:, 0] + np.testing.assert_allclose(qvel[0] / qvel, scale, rtol=1e-4) # the acceleration is 1 / mass + assert sim.data.nacon.shape == (1,) and not isinstance(sim.data.contact, wp.array) # passed through + + def test_mixed_scenes(self): + """Worlds of scenes that differ in meshes, geoms and start step each as its own scene's sim, a geom its scene lacks (the box under the big cube) never pushes, and `reset` restores each scene's start.""" + xml = """""" + cube = lambda h: " ".join(f"{x} {y} {z}" for x in (-h, h) for y in (-h, h) for z in (-h, h)) + scenes = [ + xml.format(cube(0.05), 0.12, ""), + xml.format(cube(0.08), 0.3, ''), + ] + sim = MjWarpSim([mujoco.MjSpec.from_string(x) for x in scenes], nworld=[1, 2], device="cpu") + own = [MjWarpSim(mujoco.MjModel.from_xml_string(x), 1, device="cpu") for x in scenes] + assert sim.nworld == 3 and sim.data.qpos.numpy()[:, 2].tolist() == pytest.approx([0.12, 0.3, 0.3]) + for _ in range(50): + for s in (sim, *own): + s.step() + for w, i in enumerate([0, 1, 1]): + np.testing.assert_allclose(sim.data.qpos.numpy()[w], own[i].data.qpos.numpy()[0], atol=1e-6) + z = sim.data.qpos.numpy()[:, 2] # the small cube rests on the floor, the big one on its box + assert z == pytest.approx([0.05, 0.25, 0.25], abs=0.01) + sim.reset(wp.array([1, 1, 1], dtype=int, device="cpu")) + assert sim.data.qpos.numpy()[:, 2].tolist() == pytest.approx([0.12, 0.3, 0.3]) + + def test_static_rows(self): + """A world's new rows of static bodies place its static geoms, as MuJoCo does that scene's, at its next `reset` (and at the start), and a falling ball meets the box there: a fixture, two static bodies rotated and offset, under the ball in scene 1 only.""" + xml = """""" + scenes = [xml.format(x) for x in (-0.5, 0.5)] + cpu = [] # each scene's static geoms' places, by MuJoCo + for x in scenes: + model = mujoco.MjModel.from_xml_string(x) + data = mujoco.MjData(model) + mujoco.mj_kinematics(model, data) + cpu.append((data.geom_xpos.copy(), data.geom_xmat.reshape(-1, 3, 3).copy())) + sim = MjWarpSim([mujoco.MjSpec.from_string(x) for x in scenes], nworld=[1, 1], device="cpu") + + def check(scene: list): + for w, i in enumerate(scene): + np.testing.assert_allclose(sim.data.geom_xpos.numpy()[w], cpu[i][0], atol=1e-6) + np.testing.assert_allclose(sim.data.geom_xmat.numpy()[w], cpu[i][1], atol=1e-6) + + check([0, 1]) + for f in ("body_pos", "body_quat", "geom_pos", "geom_quat"): # the worlds swap scenes' rows + getattr(sim.model, f).assign(getattr(sim.model, f).numpy()[[1, 0]]) + sim.reset(wp.array([1, 0], dtype=int, device="cpu")) + check([1, 1]) # world 1's new rows wait for its reset + sim.reset(wp.array([0, 1], dtype=int, device="cpu")) + check([1, 0]) + for _ in range(100): + sim.step() + z = sim.data.qpos.numpy()[:, 2] # world 0's ball rests on the box (top at 0.2), world 1's on the floor + assert z == pytest.approx([0.25, 0.05], abs=0.01) + + def test_resized(self): + """`resized` keeps the start, substeps, sizes and device, and splits the worlds evenly over several scenes.""" + model = mujoco.MjModel.from_xml_string(XML) + sim = MjWarpSim(model, 1, substeps=2, njmax=50, key="k", device="cpu").resized(4) + assert (sim.nworld, sim.substeps, sim._d.njmax, sim.device.is_cpu) == (4, 2, 50, True) + np.testing.assert_allclose(sim.data.qpos.numpy(), np.tile([0.1, 0.2], (4, 1)), atol=1e-7) + heavy = mujoco.MjSpec.from_string(XML.replace('mass="1"', 'mass="4"')) + mixed = MjWarpSim([mujoco.MjSpec.from_string(XML), heavy], [1, 1], device="cpu").resized(4) + assert mixed.model.body_mass.numpy()[:, 1].tolist() == [1, 1, 4, 4] + + def test_enclosing_capture(self): + """Inside an enclosing capture, here Warp's on the CPU, a step records its kernels instead of running them.""" + sim = MjWarpSim(mujoco.MjModel.from_xml_string(XML), nworld=2, device="cpu") + sim.data.ctrl.fill_(1.0) + with wp.ScopedCapture(device="cpu") as capture: + sim.step() + assert sim.data.time.numpy().tolist() == [0.0, 0.0] + wp.capture_launch(capture.graph) + wp.capture_launch(capture.graph) + np.testing.assert_allclose(sim.data.time.numpy(), [0.02, 0.02], atol=1e-7) + + +class TestNewtonSim: + def test_matches_mujoco(self): + """A pendulum on a cart, one body (slide then hinge, split for Featherstone), steps from a written `qpos` and senses like MuJoCo.""" + newton = pytest.importorskip("robokit.sim.newton") + model = mujoco.MjModel.from_xml_string( + '' + ) + sim, data = newton.NewtonSim(model, 2, substeps=2, device="cpu"), mujoco.MjData(model) + data.qpos[1], data.ctrl[:] = 0.2, [0.5, 0.3] + sim.data.qpos.assign(np.tile(data.qpos, (2, 1))) # no `forward()`: `step()` starts from it as written + sim.data.ctrl.assign(np.tile(data.ctrl, (2, 1))) + for _ in range(25): + sim.step() + for k in range(2): + mujoco.mj_step(model, data) # sensors of the state before the step, as recorded + np.testing.assert_allclose(sim.data.substep_sensordata.numpy()[k, 1], data.sensordata, atol=1e-4) + np.testing.assert_allclose(sim.data.qpos.numpy()[1], data.qpos, atol=1e-4) + np.testing.assert_allclose(sim.data.xpos.numpy()[1], data.xpos, atol=1e-4) diff --git a/tests/terms/test_trajectory_collision_task.py b/tests/terms/test_trajectory_collision_task.py index ac80135..8ad8fdf 100644 --- a/tests/terms/test_trajectory_collision_task.py +++ b/tests/terms/test_trajectory_collision_task.py @@ -1,6 +1,9 @@ +from pathlib import Path + import numpy as np import pytest import warp as wp +from robot_descriptions import panda_description from robokit.geom import BoxGeom, WarpScene from robokit.opt import VarValues @@ -8,6 +11,7 @@ from robokit.robo import Robot from robokit.terms.sparse.trajectory_collision_task import TrajectoryCollisionTask from robokit.terms.task import sparse_cost_and_gradient +from robokit.utils.assembly_utils import assemble_urdf, merge_collision_spheres from robokit.utils.warp_utils import wp_vec7 @@ -193,6 +197,43 @@ def test_subset_columns_and_geometry_updates(self, panda_robot_with_collision: R tasks[1].fill_residual_and_jacobian(values, residuals[1], 0, out_jacobian=jacobians[1]) graph = capture.graph + def test_three_arms_past_sixteen_columns(self, device: str, tmp_path: Path): + """Three Pandas' 24 speed-metric columns match each arm's columns computed alone.""" + torch = pytest.importorskip("torch") + urdf, panda = Path(panda_description.URDF_PATH), Path(panda_description.URDF_PATH) + for k in (1, 2): # arms 0.9 m apart along x + T_mount_arm = np.eye(4) + T_mount_arm[0, 3] = 0.9 * k + urdf = assemble_urdf( + tmp_path / f"{k}.urdf", urdf, panda, "panda_link0", "panda_link0", T_mount_arm, f"{k}_" + ) + franka = Path(__file__).parents[1] / "fixtures/franka_collision_spheres.yaml" + spheres = merge_collision_spheres(tmp_path / "arms.yaml", [(franka, p) for p in ("", "1_", "2_")]) + robot = Robot.load(str(urdf), load_collision_spheres=True, collision_spheres_path=spheres) + frames, dofs = 3, robot.num_actuated_joints + q = robot.spec.midrange_q + np.linspace(-0.3, 0.3, frames, dtype=np.float32)[:, None] + values = VarValues({VarKey.ROBOT: robot.state(q=wp.array(q[None], dtype=wp.float32, device=device))}) + T_world_box = np.eye(4, dtype=np.float32) + T_world_box[:3, 3] = (0.9, 0.0, 0.4) + poses = wp.array(T_world_box[None], dtype=wp.mat44, device=device) + scene = WarpScene(1, device).add( + BoxGeom(np.array([[0.7, 0.25, 0.25]], np.float32), np.array([0, 1]), poses=poses) + ) + arms = [None] + [np.arange(dofs // 3, dtype=np.int32) + k * dofs // 3 for k in range(3)] + speed_dt = wp.array(np.full(1, 0.1, np.float32), device=device) + tasks = [ + TrajectoryCollisionTask( + robot, scene, frames, margin=0.3, active_actuated_indices=columns, sweep_steps=4, speed_dt=speed_dt + ) + for columns in arms + ] + residuals = [task.compute_weighted_residual(values).numpy() for task in tasks] + jacobians = [task.compute_weighted_sparse_jacobian_values(values).numpy().reshape(-1, dofs) for task in tasks] + assert np.abs(jacobians[0]).max() > 0.0 + for k, columns in enumerate(arms[1:], 1): + torch.testing.assert_close(residuals[k], residuals[0], rtol=1e-5, atol=1e-6) + torch.testing.assert_close(jacobians[k][:, columns], jacobians[0][:, columns], rtol=1e-4, atol=1e-5) + @pytest.mark.parametrize("num_spheres", [3, 65]) def test_masks_and_zero_weights(self, panda_robot_with_collision: Robot, device: str, num_spheres: int): """Masked and zero-weight spheres match removing them, including a partial CUDA sphere group.""" diff --git a/tests/terms/test_trajectory_self_collision_task.py b/tests/terms/test_trajectory_self_collision_task.py index a290d34..a0b5c28 100644 --- a/tests/terms/test_trajectory_self_collision_task.py +++ b/tests/terms/test_trajectory_self_collision_task.py @@ -36,6 +36,8 @@ def test_streamed_max_ignores_trailing_nan(self, device: str, max_linear: bool): 3.0, False, wp.zeros((1, 1), dtype=wp.uint8, device=device), + wp.ones((1, 4), dtype=wp.int32, device=device), + wp.ones(len(pairs), dtype=wp.int32, device=device), max_linear, ], outputs=[maximum], @@ -138,6 +140,8 @@ def test_deepest_pair_ties_masks_and_nan(self, device: str, use_mask: bool): wp.array(np.array([[1, 1, 0, 1]], dtype=np.uint8), dtype=wp.uint8, device=device) if use_mask else None, # an unused mask must never be read + wp.ones((4, 3), dtype=wp.int32, device=device), + wp.ones(len(pairs), dtype=wp.int32, device=device), ], outputs=[residual, argmax], block_dim=_PAIR_THREADS, diff --git a/tests/test_frees_without_gc.py b/tests/test_frees_without_gc.py index a2b504d..8ed9780 100644 --- a/tests/test_frees_without_gc.py +++ b/tests/test_frees_without_gc.py @@ -13,7 +13,7 @@ MppiTrajectoryOptimizer, MppiTrajectoryOptimizerConfig, ) -from robokit.opt.population_solver import PopulationSolverConfig +from robokit.opt.population_solver import PopulationSolverConfig, Stage from robokit.robo import Robot from robokit.robo.robot_torch_wrappers import WarpForwardKinematicsMatrix @@ -38,7 +38,7 @@ def build() -> MppiTrajectoryOptimizer: config = MppiTrajectoryOptimizerConfig( control_space=control_space, solver=PopulationSolverConfig( - num_iters=1, samplers=[ColoredGaussianSamplerConfig(num_draws=4, init_std=0.1)] + stages=[Stage(1)], samplers=[ColoredGaussianSamplerConfig(num_draws=4, init_std=0.1)] ), ) config.task("target").dense_task.position_weight = 1.0
- IK
+ IK
IK Multi-link targets, fixed or floating base.
- Motion Planning
+ Motion Planning
Motion Planning Collision-free trajectories, offline or online.
- Hand-Eye Calibration
+ Hand-Eye Calibration
Hand-Eye Calibration Camera pose from rendered robot masks.
- Humanoid Retargeting
+ Humanoid Retargeting
Humanoid Retargeting Human motion capture to a humanoid.
- Hand Retargeting
+ Hand Retargeting
Hand Retargeting Human hand motion to a robot hand.
- Grasp Optimization
+ Grasp Optimization
Grasp Optimization Force-closure grasps for any hand or body.
umi_gripperMJCFMenagerieMIT——
xhandURDFRobotEra—YAML (right)✓ (right)
MJCF (right)RobotEra——✓
wuji_hand (Hand 1)URDFWuji TechnologyMITYAML✓
MJCFWuji TechnologyMIT——
wuji_hand_2_2 (Hand 2.2)URDFWuji TechnologyMITYAML✓
MJCFWuji TechnologyMIT——
yam_gripperURDFI2RTMITYAML✓
MJCFI2RTMIT—✓
dexmachinaNPZDexMachina / ARCTICARCTIC
dexycbNPZ, JSON, OBJDexYCBCC-BY-NC-4.0
gigahandsNPZGigaHandsCC-BY-NC-4.0
nist_assemblyXML, NPZAssembleNIST / UW LabMIT
oakink2NPZOakInk-v2CC-BY-SA-4.0
omomoPT, PKL, OBJOMOMO / InterMimic—
parahomePKL, JSON, OBJParaHomeCC-BY-NC-SA-4.0