# Learn to Balance

The simple agents chose actions using fixed rules. Now you’ll train a policy
that uses observations to keep Microduck upright and in place. The robot’s
base can move freely, but the velocity command asks it to stand still. Each
episode lasts up to 20 seconds. You’ll train with
[Proximal Policy Optimization (PPO)](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/robot-learning-fundamentals/05-proximal-policy-optimization.md).

## Think of the Reward as Feedback

Imagine a bubble level on the trunk (the duck’s body). The upright term gives a
larger signal when the bubble is centered. Rewards for zero horizontal speed and
zero turn rate encourage the robot to remain still. Penalties for abrupt actions
and joint-limit violations help shape how it holds that pose.

| Term           | Mental model                       | What the implementation measures                                    |
|----------------|------------------------------------|---------------------------------------------------------------------|
| `upright`      | Center a bubble level              | An exponential of squared horizontal projected gravity on the trunk |
| `still_xy`     | Keep a speedometer near zero       | Horizontal velocity error relative to the zero command              |
| `still_yaw`    | Keep a turn-rate gauge near zero   | World-frame yaw-rate error relative to zero                         |
| `action_rate`  | Pay for sudden changes in requests | Squared differences between consecutive actions                     |
| `joint_limits` | Keep away from the stops           | Joint-position violations of soft limits                            |

When Microduck is pushed, the velocity rewards encourage it to come to a
stop where it lands. To bring it back to its starting spot or have it face
the original direction, you’d need a position or heading target.

The upright term uses `exp(-error² / std²)`. Its maximum is 1 before weighting.
A smaller tolerance makes the same error more costly. A weight changes how
strongly the term competes with other terms. The reward manager multiplies
weighted terms by the control timestep; PPO learns from accumulated rewards.

[Reward Design and Task Success](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/robot-learning-fundamentals/06-reward-design-and-policy-evaluation.md#reward-design-and-task-success)
explains how to turn an intended behavior into training feedback and evaluation
criteria. Here, the reward encourages a steady pose. We evaluate the result by
measuring how long the duck stays upright and how much it moves.

## Configure the Balance Task

Append the five balance terms and the environment that uses them. Keep the
scene and base environment you built earlier.

Use Isaac Lab’s action-rate penalty to discourage sudden changes in joint
targets. The other reward functions come from the velocity task’s
`mdp/rewards.py`.

**Add to the imports in `env_cfg.py`:**

```python
import math

from isaaclab.envs.mdp import action_rate_l2
from isaaclab.managers import RewardTermCfg as Reward
from isaaclab.managers import SceneEntityCfg

from isaaclab_tutorial.tasks.velocity.mdp import rewards
```

**Append to `env_cfg.py`:**

```python
@configclass
class BalanceRewardsCfg:
    # A spirit level: a vertical trunk earns more than a tilted trunk.
    upright = Reward(
        func=rewards.upright,
        weight=2.0,
        params={"std": math.sqrt(0.05), "asset_cfg": SceneEntityCfg("robot", body_names=["trunk_base"])},
    )
    # A speedometer near zero: discourage horizontal motion at the current location.
    still_xy = Reward(
        func=rewards.track_linear_velocity_heading, weight=1.0, params={"command_name": "base_velocity", "std": 0.15}
    )
    still_yaw = Reward(
        func=rewards.track_angular_velocity_world, weight=1.0, params={"command_name": "base_velocity", "std": 0.35}
    )
    # A movement budget: discourage abrupt target changes, not all movement.
    action_rate = Reward(func=action_rate_l2, weight=-0.1)
    joint_limits = Reward(func=rewards.joint_pos_limits_finite, weight=-1.0)


@configclass
class BalanceEnvCfg(BaseEnvCfg):
    """Learn balance with a free base; zero commands do not constrain physics."""

    rewards = BalanceRewardsCfg()
```

Register the new task alongside the inspection and passive tasks from lesson 3:

**Append to `microduck/__init__.py`:**

```python
register_task("Balance", "BalanceEnvCfg", "BalancePPORunnerCfg")
```

What could happen if we kept the upright term and removed the
stationary-velocity terms? Predict a change in motion, then choose a
measurement that would test your prediction.

## Train a Policy

Your balance task is ready to train. Run a short test to see the initial
behavior, train the full policy, or use the supplied checkpoint to focus on
evaluation.

Commands below use `checkpoints/microduck/balance.pt` for the supplied policy.
If you train your own, substitute the exact checkpoint path printed by training.

### Do a Quick Test

This quick test should take less than a minute to run.

After a short run, will the duck stand for 20 seconds, drift,
or fall? Keep your prediction beside the result.

```bash
uv run isaaclab train --task Course-Microduck-Balance-v0 \
    --rl_library rsl_rl --num_envs 128 --max_iterations 50 --seed 42 \
    --run_name first_balance
```

After training finishes, play the saved policy:

```bash
uv run --extra viser isaaclab play --task Course-Microduck-Balance-v0 \
    --rl_library rsl_rl --num_envs 1 --checkpoint latest --viz viser --real-time
```

Open Viser using the
[viewer instructions](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/train-a-microduck/04-simple-agents.md#open-the-live-viser-viewer).
In its **Isaac Lab** panel, select **Reset Episode** and watch until the next fall or timeout. Record how
long it stays upright, whether the feet drift, and where it holds its head.
Press **Ctrl+C** when you finish.

This run collects **128 robots × 24 steps × 50 iterations = 153,600 transitions**.
Compare this result with your prediction, then use this run in **Evaluate Standing**.

### Train the Full Policy

This full run should take less than 30 minutes to run.

Train with the same budget as the reference balance policy:

```bash
uv run isaaclab train --task Course-Microduck-Balance-v0 \
    --rl_library rsl_rl --num_envs 4096 --max_iterations 2000 --seed 42
```

After training finishes, play the saved policy:

```bash
uv run --extra viser isaaclab play --task Course-Microduck-Balance-v0 \
    --rl_library rsl_rl --num_envs 1 --checkpoint latest --viz viser --real-time
```

Open Viser using the
[viewer instructions](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/train-a-microduck/04-simple-agents.md#open-the-live-viser-viewer) to watch the trained policy.
Press **Ctrl+C** when you finish, then continue to **Evaluate Standing**,
replacing the supplied `balance.pt` path with your saved checkpoint’s path
in the evaluation command.

### Use a Pretrained Checkpoint

Play the supplied `checkpoints/microduck/balance.pt` policy in the environment you built.

```bash
uv run --extra viser isaaclab play --task Course-Microduck-Balance-v0 \
    --rl_library rsl_rl --num_envs 16 \
    --checkpoint checkpoints/microduck/balance.pt --viz viser --real-time
```

Press **Ctrl+C** when you finish inspecting playback, then continue to
**Evaluate Standing**.

### What Do the First-Run Flags Do?

`--run_name first_balance` labels the run under
`logs/rsl_rl/course_microduck_balance/`. `--checkpoint latest` plays the newest
compatible balance checkpoint there. Save the printed path to replay this
specific attempt later. Installation, asset downloads, and GPU compilation add
startup time beyond the training loop.

If you ran the quick test, compare its motion with the supplied balance policy
in **Inspect the Reference Result**. The quick test uses 50 training iterations;
the supplied policy uses 2,000.

## Evaluate Standing

Use the provided `scripts/evaluate.py` to compare the policy with a zero-action
baseline, which always outputs zero action offsets. It records motion before an
automatic reset and saves completion, tracking, head-tilt, and foot-order
measurements as JSON.

Run the following commands from the IsaacLabTutorial repository root.

### How Does the Standing Evaluation Work?

**Set the conditions.** For `--case stand`, the requested forward speed, sideways
speed, and yaw rate are zero. The script creates one environment per trial,
sets the seed, and disables scheduled pushes.

**Choose the action.** The zero agent sends 14 zero offsets per robot. For a
checkpoint, the script loads the PPO runner, gets the inference policy, and
feeds the latest observations to it at each control step:

```python
actions = policy(obs)
```

**Record the first episode.** The recorder captures the terminal transition
before an automatic reset. Once a robot falls or reaches the time limit, its
trial is finished. In the JSON report, `results` summarizes the trials and
`per_trial` lets you inspect individual outcomes.

Measure the zero-action baseline with the same standing conditions:

```bash
uv run python scripts/evaluate.py \
    --task Course-Microduck-Balance-v0 --agent zero --case stand --trials 16 \
    --output results/balance-zero.json
```

Then evaluate the learned policy:

### Use Your Trained Policy

Run from the IsaacLabTutorial repository root. List the balance policies
saved by your training runs:

```bash
find logs/rsl_rl/course_microduck_balance -type f -name 'model_*.pt' | sort
```

Each timestamped directory is a separate run. Choose the run you want to
measure, then its highest numbered `model_*.pt` file. Compare the numbers
numerically: the alphabetical listing does not put the highest number last.
For the 2,000-iteration run, select `model_1999.pt`; the 50-iteration first run
ends at `model_49.pt`.

Replace `<run-directory>` below with the directory from your listing. If you
selected a different checkpoint, change the filename too.

```bash
RUN_DIR='<run-directory>'
```

```bash
MODEL_FILE='model_1999.pt'
BALANCE_CHECKPOINT="$RUN_DIR/$MODEL_FILE"

uv run python scripts/evaluate.py \
    --task Course-Microduck-Balance-v0 --case stand --trials 16 \
    --checkpoint "$BALANCE_CHECKPOINT" \
    --output results/balance.json
```

### Use a Pretrained Checkpoint

Use the checkpoint saved in `checkpoints/microduck/balance.pt`. If you saved it
elsewhere, update `BALANCE_CHECKPOINT` to match.

```bash
BALANCE_CHECKPOINT='checkpoints/microduck/balance.pt'

uv run python scripts/evaluate.py \
    --task Course-Microduck-Balance-v0 --case stand --trials 16 \
    --checkpoint "$BALANCE_CHECKPOINT" \
    --output results/balance.json
```

The evaluator records the first episode of each trial through the last physics
step before a reset. Compare how long the two agents stay upright and how often
they fall. Then watch how they move. A duck can stay nearly still for a moment
and fall soon after, so read the velocity error alongside the survival time.

## Inspect the Reference Result

The supplied balance policy trained for 2,000 iterations with 4,096 environments
and seed 42. Evaluation on Isaac Lab 3 used seed 123 and the first episode
of each of 16 standing trials:

| Agent           | Completed 20 seconds   | Mean survival   | Mean horizontal velocity error   |
|-----------------|------------------------|-----------------|----------------------------------|
| Zero action     | 0/16                   | 1.21 s          | 0.0980 m/s                       |
| Learned balance | 16/16                  | 20.00 s         | 0.0007 m/s                       |
![Learned balance policy standing for 20 seconds; the caption describes the recorded behavior.](_static/media/microduck/balance.png)

These five reward terms never ask the head to face forward. A *good* policy
can choose an unexpected head pose. In **Hold the Head Level Too**, you’ll add
a reward for a neutral head pose and check whether the duck still balances.

**Check Your Progress:** Explain why “the episode lasted 20 seconds” and
“the upright reward increased” are different observations. Identify a term you
would change for a duck that remains vertical but slides.

## Hold the Head Level Too

Finish the balance task by asking for a neutral head pose while the duck stays
upright. Keep the five existing rewards and add one term for `neck_pitch`,
`head_pitch`, `head_yaw`, and `head_roll`.

Think of four centering springs, one for each neck or head joint. Each joint
earns more reward as it approaches its target. The term averages the four
exponential scores, then applies weight 2.0, with a tolerance of 0.5 rad. The
five existing balance terms still apply.

Our standing task already holds `head_pose` commands at zero. Those are
offsets from the nominal pose: `neck_pitch` and `head_pitch` are each
0.3491 rad (about 20°), while `head_yaw` and `head_roll` are zero. In this asset,
that neck/head arrangement puts the head level when the trunk is upright.

How will adding the head-pose reward affect head tilt and standing?
Write down an expected change and a possible tradeoff. We’ll check both, following
[Reward Design and Task Success](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/robot-learning-fundamentals/06-reward-design-and-policy-evaluation.md#reward-design-and-task-success).

### Add the Head-Pose Reward

Append the new classes to your existing file. The task inherits the balance
scene, zero commands, and free root, and adds only the head-pose reward.

**Append to `env_cfg.py`:**

```python
@configclass
class BalanceHeadRewardsCfg(BalanceRewardsCfg):
    # Four centering springs: return each neck/head joint to its neutral target.
    head_pose = Reward(
        func=rewards.head_pose_tracking,
        weight=2.0,
        params={
            "command_name": "head_pose",
            "std": 0.5,
            "asset_cfg": SceneEntityCfg(
                "robot", joint_names=["neck_pitch", "head_pitch", "head_yaw", "head_roll"], preserve_order=True
            ),
        },
    )


@configclass
class BalanceHeadEnvCfg(BalanceEnvCfg):
    """Keep the balance objective and add a neutral neck/head pose."""

    rewards = BalanceHeadRewardsCfg()
```

Give the continuation its own training log directory:

**Append to `agents/rsl_rl_ppo_cfg.py`:**

```python
@configclass
class BalanceHeadPPORunnerCfg(BalancePPORunnerCfg):
    experiment_name = "course_microduck_balance_head"
    max_iterations = 1000
```

Register the new task alongside the original balance task:

**Append to `microduck/__init__.py`:**

```python
register_task("BalanceHead", "BalanceHeadEnvCfg", "BalanceHeadPPORunnerCfg")
```

### Continue From the Balance Policy

Use the `BALANCE_CHECKPOINT` you selected in **Evaluate Standing** as the starting policy.
Choose a route below, then evaluate whether the added head objective improves
head tilt while preserving balance.

### Do a Quick Test

This short test should take less than a minute to run.

Run two iterations to check that the continuation starts and saves a checkpoint:

```bash
uv run isaaclab train --task Course-Microduck-BalanceHead-v0 \
    --rl_library rsl_rl --num_envs 64 --max_iterations 2 --seed 43 \
    --checkpoint "$BALANCE_CHECKPOINT" \
    --no-resume_optimizer_state agent.algorithm.learning_rate=0.0003
```

Once the check finishes, load the saved policy and watch how the duck moves.

```bash
uv run --extra viser isaaclab play --task Course-Microduck-BalanceHead-v0 \
    --rl_library rsl_rl --num_envs 1 --checkpoint latest --viz viser --real-time
```

Open Viser using the
[viewer instructions](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/train-a-microduck/04-simple-agents.md#open-the-live-viser-viewer).
Press **Ctrl+C** when you finish.

Use this run to practice evaluation. The recorded comparison below uses a longer training run.

### Train the Full Policy

This continuation should take less than 15 minutes to run.

Start again from your selected `BALANCE_CHECKPOINT` with a fresh optimizer:

```bash
uv run isaaclab train --task Course-Microduck-BalanceHead-v0 \
    --rl_library rsl_rl --num_envs 4096 --max_iterations 1000 --seed 43 \
    --checkpoint "$BALANCE_CHECKPOINT" \
    --no-resume_optimizer_state --run_name head_level \
    agent.algorithm.learning_rate=0.0003
```

After training finishes, play the saved policy:

```bash
uv run --extra viser isaaclab play --task Course-Microduck-BalanceHead-v0 \
    --rl_library rsl_rl --num_envs 1 --checkpoint latest --viz viser --real-time
```

Open Viser using the
[viewer instructions](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/train-a-microduck/04-simple-agents.md#open-the-live-viser-viewer).
Press **Ctrl+C** when you finish.

### Use a Pretrained Checkpoint

Play the supplied `checkpoints/microduck/balance-head.pt` policy.

```bash
uv run --extra viser isaaclab play --task Course-Microduck-BalanceHead-v0 \
    --rl_library rsl_rl --num_envs 16 \
    --checkpoint checkpoints/microduck/balance-head.pt --viz viser --real-time
```

Press **Ctrl+C** when you finish inspecting it. Watch whether the bill stays
level while the feet and body make small balance corrections.

### Inspect the Continuation Flags

`--checkpoint` loads the standing policy. `--no-resume_optimizer_state` starts
a fresh optimizer. `BalanceHeadPPORunnerCfg` inherits an initial learning rate
of 0.001 and `schedule="adaptive"` from `BalancePPORunnerCfg`. The commands
above override the initial rate to 0.0003; the schedule remains adaptive.
`--max_iterations` sets the additional training budget. Evaluate the exact
checkpoint produced by your run when judging your own continuation.

### Check Head Tilt and Standing Together

Run both policies through the same 16 standing trials.

### Use Your Trained Policies

First locate their saved checkpoints from the IsaacLabTutorial repository root:

```bash
find logs/rsl_rl/course_microduck_balance logs/rsl_rl/course_microduck_balance_head \
    -type f -name 'model_*.pt' | sort
```

Choose the full balance run and the head-level continuation run, then select
the highest numbered checkpoint within each. The full balance run ends at
`model_1999.pt`. The course’s 1,000-additional-iteration head-level command ends
at `model_2998.pt`; its setup check’s `model_2000.pt` is not that full run’s final
checkpoint.

For a before/after comparison, check the head-level run’s training log to
confirm which policy started it. If it did not start from your selected balance
policy, these measurements compare two policies but do not isolate the effect
of the head-level continuation.

Replace `<balance-run-directory>` and `<head-run-directory>` with the full
respective directory paths from your listing, including `logs/rsl_rl/`, the
experiment directory, and the run’s timestamp. Change the checkpoint filenames
if needed, then compare your measurements with the supplied reference results below:

```bash
BALANCE_RUN_DIR='<balance-run-directory>'
HEAD_RUN_DIR='<head-run-directory>'
```

```bash
BALANCE_MODEL_FILE='model_1999.pt'
HEAD_MODEL_FILE='model_2998.pt'

BALANCE_CHECKPOINT="$BALANCE_RUN_DIR/$BALANCE_MODEL_FILE"
HEAD_CHECKPOINT="$HEAD_RUN_DIR/$HEAD_MODEL_FILE"

uv run python scripts/evaluate.py \
    --task Course-Microduck-Balance-v0 --case stand --trials 16 --seed 123 \
    --checkpoint "$BALANCE_CHECKPOINT" \
    --output results/balance-head-baseline.json

uv run python scripts/evaluate.py \
    --task Course-Microduck-BalanceHead-v0 --case stand --trials 16 --seed 123 \
    --checkpoint "$HEAD_CHECKPOINT" \
    --output results/balance-head.json
```

### Use Pretrained Checkpoints

Use the supplied `balance.pt` and `balance-head.pt` files from `checkpoints/microduck/`.

```bash
BALANCE_CHECKPOINT='checkpoints/microduck/balance.pt'
HEAD_CHECKPOINT='checkpoints/microduck/balance-head.pt'

uv run python scripts/evaluate.py \
    --task Course-Microduck-Balance-v0 --case stand --trials 16 --seed 123 \
    --checkpoint "$BALANCE_CHECKPOINT" \
    --output results/balance-head-baseline.json

uv run python scripts/evaluate.py \
    --task Course-Microduck-BalanceHead-v0 --case stand --trials 16 --seed 123 \
    --checkpoint "$HEAD_CHECKPOINT" \
    --output results/balance-head.json
```

`mean_head_tilt_deg` measures the angle between the head frame’s upward axis
(`yaw_roll_motion`) and world up: 0° is level. `p95_head_tilt_deg` shows the tilt
below which 95% of recorded samples fall. Check these alongside completion and
horizontal velocity error. A better head pose matters only if the duck still
stands.

The supplied continuation trained for 1,000 additional iterations from
`balance.pt`, using 4,096 environments and seed 43. Evaluation on Isaac Lab 3
with seed 123 produced these results:

| Policy              | Completed 20 seconds   | Mean head tilt   | 95th-percentile head tilt   | Horizontal velocity error   |
|---------------------|------------------------|------------------|-----------------------------|-----------------------------|
| Original balance    | 16/16                  | 83.7°            | 94.6°                       | 0.0007 m/s                  |
| Balance + head pose | 16/16                  | 3.2°             | 4.8°                        | 0.0016 m/s                  |
![The original balance policy holds its head down; the policy with the added head-pose objective stands with its head level.](_static/media/microduck/balance-head-comparison.png)

### Optional: Recover From a Push

Give the saved policy a sideways kick and watch its response. We use
Isaac Lab’s [push event](https://isaac-sim.github.io/IsaacLab/v3.0.0/source/api/lab/isaaclab.envs.mdp.html#isaaclab.envs.mdp.events.push_by_setting_velocity).
In the pinned implementation, the kick changes the robot’s body velocity by a
specified amount in a world-frame direction at 3 seconds. The root stays free,
and the policy continues choosing motor targets.

Think back to the bubble level: after a disturbance tilts the trunk, the policy
can change `left_ankle`, `right_ankle`, `left_knee`, and `right_knee` targets to
bring it upright. The checkpoint and reward are unchanged for this test.

![The head-level policy responds to a sideways 0.2 m/s velocity kick while standing.](_static/media/microduck/balance-push-recovery.png)

The clip above runs at original speed. The replay below runs at 0.25× speed:
the 0.2 m/s kick is followed by recovery, and the 0.4 m/s kick leads to a fall.
Both use seed 123 and the same fixed starting heading. The final fall frame is
held after the episode ends, as labeled.

![Side-by-side push trials: the smaller kick is followed by recovery, while the larger kick causes a fall.](_static/media/microduck/balance-push-limits.png)

Repeat the test across four world directions (`+x`, `-x`, `+y`, `-y`), with
16 randomized trials per direction. A trial counts as recovered when horizontal
speed stays below 0.03 m/s and trunk tilt stays below 10° for one continuous
second, and the duck then completes the 10-second episode.

Run `scripts/evaluate_pushes.py` from the repository root.

### How Does the Push Evaluation Work?

**Apply the kick.** The script groups trials by speed and direction. At the
scheduled step it adds the requested velocity to each active robot and checks
that the measured change matches the kick.

```python
push_by_setting_velocity(simulation, ids, kick)
delta = robot.data.root_vel_w.torch[ids] - before
```

**Measure recovery.** The recorder counts consecutive steps below both the
speed and tilt thresholds. A trial must sustain that condition for one second
and reach the episode time limit to count as recovered.

**Read the result.** In `results.json`, find `recovered_and_completed` for
each speed and direction. With `--hold-targets`, the script keeps the last
pre-kick targets, so you can compare recovery with and without policy updates.

```bash
uv run python scripts/evaluate_pushes.py \
    --checkpoint "$HEAD_CHECKPOINT" \
    --speeds 0.1 0.2 0.4 --output results/balance-pushes
```

Evaluation on Isaac Lab 3 with seed 123 produced these results:

| Push speed   | Policy keeps updating   | Hold the last motor targets   |
|--------------|-------------------------|-------------------------------|
| 0.1 m/s      | 64/64 recovered         | 60/64 recovered               |
| 0.2 m/s      | 48/64 recovered         | 22/64 recovered               |
| 0.4 m/s      | 4/64 recovered          | 6/64 recovered                |

The second column uses feedback throughout. For the last column, add
`--hold-targets` and choose a new output directory: joint servos keep running,
while the policy’s targets stay fixed after the kick. In these trials, the
policy’s continuing corrections improve recovery from moderate kicks. Large
kicks frequently topple the robot.

Change the direction or strength, predict the outcome, and measure
recovery. Use `--video --trials 1 --direction +y --speeds 0.2` to save one native
simulation video alongside the measurements.
