# Shape Rewards

What happens if you penalize foot slip more heavily? To test that, you’ll
start two training runs from the same walking checkpoint and give them
different slip weights. First, work through a small example of how a reward
can make a robot favor one behavior over another.

## Give Feedback Before Success

Imagine rewarding Microduck only when it finishes an inspection route. A new
policy might fall long before reaching the destination, receiving no positive
feedback about the movements that helped. This is a **sparse reward**: useful
feedback occurs infrequently.

**Reward shaping** adds intermediate feedback. A proximity bonus could reward
being closer to the destination before the robot completes the route. In the
walking task, the duck earns a reward as it moves at the requested speed.
The air-time reward encourages it to lift its feet for a particular amount
of time. Penalties discourage behaviors such as abrupt action changes.

More frequent feedback can help learning. It also changes the score: an
intermediate behavior may become more rewarding than the outcome you wanted.
Let’s inspect that possibility before choosing another Microduck weight.

## When Does Waiting Beat Finishing?

Calculate the reward for one step, then compare the totals for three **fixed
candidate trajectories** (paths of positions over time) along a one-meter
route: finish, approach and wait, or stay at the start. Each step represents
one second. The score combines a proximity bonus, a movement cost, and a bonus
for finishing.

$$
r_t = b x_t - c |x_t-x_{t-1}| + 4\,\mathbf{1}[x_t=1].
$$

For example, moving from 0.50 m to 0.75 m with b = 1 and c = 0.5 earns
1 × 0.75 − 0.5 × |0.75 − 0.50| + 4 × 0 = 0.625 reward units. Waiting at
0.75 m on the next step earns 0.75 again with no movement cost or completion
bonus. Repeating those payments can make waiting more rewarding than finishing.

Here, position $x_t$ is in meters, $b$ is a proximity-bonus
coefficient in reward units per meter per step, and $c$ is a movement-cost
coefficient in reward units per meter. The indicator is 1 at the destination
and 0 elsewhere. Reaching the destination pays 4 reward units once and ends
the episode immediately; unfinished episodes end after eight steps. The
return is the sum of rewards with no discounting ($\gamma=1$). There
are no rewards after termination.

Start with bonus 1 and movement cost 0.5. Finishing earns 6, approaching and
waiting earns 4.875, and staying earns 0. Increase the bonus to 2. Waiting then
earns 10.125, which exceeds finishing’s 8.5. The route hasn’t changed. Repeated
intermediate payments changed which candidate wins.

Find settings where waiting beats finishing. Then change the bonus or
cost so finishing wins again. Expand **Inspect Step Rewards and Episode Totals**
to compare the full timelines. Which candidate collects more proximity payments?

At bonus 1 and movement cost 0.5, the finishing trajectory earns 2.5 in
proximity bonuses, pays 0.5 in movement costs, and receives 4 for completion:
6 total. The waiting trajectory earns 5.25 in proximity bonuses and pays
0.375 in movement costs: 4.875 total. Doubling the bonus changes those totals
to 8.5 and 10.125. Staying at the start always earns zero in this model.

This example computes scores live. It contains no training, balance, contact
physics, or exploration. Its preferred candidate is the highest-scoring of
three scripted trajectories, not a prediction of what reinforcement learning
will discover. Other trajectories could earn more. Changing the episode
limit, discount, or termination rules could change the comparison.

A bonus for proximity pays repeatedly for occupying a good state. A reward
for **progress** pays for a change between states; once the robot waits,
that progress signal stops. Switching to progress fixes the waiting problem
here, but any new formula still needs its own checks for unintended incentives
and task performance.

Return to Microduck: a policy might follow the requested velocity while sliding
its planted feet. You’ll change the slip penalty and check both foot motion
and tracking. First, read that penalty alongside the other terms that shape
the walking behavior.

## Read the Reward as a Set of Competing Requests

The reference walking recipe combines the terms below. Each term is a request
for one behavior. As discussed in
[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),
the weights set how strongly each request influences learning.
Read the terms together to see where strengthening one request could work
against another.

In your IsaacLabTutorial checkout, open
`microduck/walking.py` and find
`RewardsCfg`. Each term pairs a weight with a function. For the slip penalty,
follow `rewards.foot_slip` into `mdp/rewards.py` to see how ankle
speed and foot contact enter the calculation.

| Term                          | Mental model                           | Signal and possible tradeoff                                                                                         |
|-------------------------------|----------------------------------------|----------------------------------------------------------------------------------------------------------------------|
| **Velocity-Tracking Rewards** |                                        |                                                                                                                      |
| `track_lin_vel`               | Hit a moving bull’s-eye                | Reward matching horizontal velocity; gait terms also shape how the robot moves                                       |
| `track_ang_vel`               | Match a requested turn rate            | Reward matching how fast the body turns about the world vertical axis                                                |
| **Posture Rewards**           |                                        |                                                                                                                      |
| `upright`                     | Center the trunk’s bubble level        | Reward small trunk tilt; velocity terms encourage the requested motion, with zero commands encouraging stillness     |
| `pose`                        | Return to a comfortable standing pose  | Reward nominal leg posture only during standing commands; applying it while walking can resist necessary leg motion  |
| **Head-Pose Rewards**         |                                        |                                                                                                                      |
| `head_pose_tracking`          | Aim the head at its requested pose     | Reward matching head-joint offsets; competes for motion and balance capacity                                         |
| `head_pose_bias`              | Correct an error that keeps persisting | Penalize a moving average of head error; this term is introduced by curriculum                                       |
| **Gait and Foot Rewards**     |                                        |                                                                                                                      |
| `air_time`                    | Lift a foot for a useful interval      | Reward each step with current air time strictly between 0.125 and 0.3 seconds while commanded to move                |
| `foot_clearance`              | Clear the floor without high-stepping  | Penalize speed-weighted foot-height error measured at the ankle frame                                                |
| `foot_swing_height`           | Land after a suitably high swing       | Penalize the error between peak swing height and its target at first contact                                         |
| `foot_slip`                   | Plant a foot like a grip on the floor  | Penalize squared planar ankle-frame speed during contact and moving commands; stronger grip feedback may slow travel |
| **Regularization Penalties**  |                                        |                                                                                                                      |
| `body_ang_vel`                | Avoid wobbling the trunk               | Penalize roll/pitch rate; too much can resist corrections                                                            |
| `angular_momentum`            | Avoid excessive whole-body spin        | Penalize squared total angular momentum; momentum can also help recovery                                             |
| `dof_pos_limits`              | Stay away from joint stops             | Penalize joint positions outside their configured soft limits                                                        |
| `action_rate_l2`              | Pay for abrupt target changes          | Penalize consecutive action differences; excessive smoothing can delay response                                      |
| **Contact Penalties**         |                                        |                                                                                                                      |
| `self_collisions`             | Keep the feet from hitting each other  | Penalize foot-to-foot contact using the enabled sole colliders                                                       |

The slip term uses ankle speed as a proxy for sliding. A foot can pivot
where its sole touches the ground and still move the ankle. Watch the video
alongside the measurements to see which kind of motion you’re picking up. The air-time term counts qualifying
airborne feet on each control step; its reward stops at landing or outside
the window.

For foot clearance, the 0.0425 m target includes the 0.0225 m sole-to-ankle
frame offset. Check the reference frame before interpreting a target height.

## Read the Effective Feedback

To see how much a reward term matters, look at the signal it measures, when
it applies, and how its contribution adds up over time.

- **Magnitude:** a small weight on a large raw signal can produce a substantial contribution.
- **Frequency:** a small payment every step can accumulate beyond a one-time success bonus.
- **Gating:** a term contributes only when its activation conditions hold. Microduck’s slip term is gated by contact and moving commands.
- **Time scaling:** Isaac Lab scales configured reward contributions by the environment’s control interval. Include that interval when reproducing the score.

A curriculum (a schedule that changes training conditions over time) adds
another consideration: weights and command ranges can change while training.
Compare the effective settings at the checkpoint as well as the initial recipe.

The **Score the Same Recorded Motion Twice** example below isolates the effect
of the weight: the score changes while the motion stays fixed. Retraining
also lets the motion change. A stronger slip penalty could lead the policy to
move more slowly, compensate through another joint, or find another way to earn
reward. You’ll need to measure the trained behavior to know whether sliding decreased.

Two terms have the same weight. Must they contribute
equally to return?

### Answer

No. Their raw magnitudes, activation frequency, and gates can differ. Inspect
weighted contributions over trajectories as well as the configured weights.
Even a large contribution does not by itself establish how strongly a term
changes learning; that also depends on how the signal varies with behavior.

## Predict a Single Change

We’ll change only `foot_slip.weight`, from −0.1 to −0.5. For one foot in contact
with the ground, an ankle-frame speed of 0.2 m/s gives an unweighted squared-speed
cost of 0.04. Before timestep scaling, that foot contributes −0.004 or −0.02
respectively. With no detected contact, the term contributes no slip cost;
the reward function also gates it off for standing commands.

Write a hypothesis: **“A stronger slip penalty will reduce ankle speed during
contact, but might worsen velocity tracking or stability.”** Decide how you
will check both the intended effect and the tradeoff before training.

### Score the Same Recorded Motion Twice

At 6.02 seconds in a [recorded command-sequence evaluation](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/_downloads/844236e0b7ea0269a44833bc4e49e2ea/microduck-command-sequence.json),
the 16-trial mean sum of squared contacting-ankle speeds was 0.00097346.
Every active trial had a forward command. Keep this measured motion fixed and
multiply by the two weights and the 0.02-second control interval:

| Weight   |   Mean slip contribution for that step |
|----------|----------------------------------------|
| −0.1     |                              -1.95e-06 |
| −0.5     |                              -9.73e-06 |

The stronger weight makes this same recorded motion cost five times as much.
Training can then change the motion in response. Predict one useful change
and one possible cost before running a continuation.

Append a variant to your existing environment file. It inherits the completed
walking task and changes only the slip penalty.

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

```python
@configclass
class LessSlipEnvCfg(WalkEnvCfg):
    def __post_init__(self):
        super().__post_init__()
        self.rewards.foot_slip.weight = -0.5
```

Give the new task its own experiment names so its checkpoints are easy to
find. Both runners inherit the walking settings from lesson 6. The matched
comparison below uses the symmetry-enabled runner for both policies.

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

```python
@configclass
class LessSlipPPORunnerCfg(WalkPPORunnerCfg):
    experiment_name = "course_microduck_less_slip"


@configclass
class SymmetricLessSlipPPORunnerCfg(SymmetricWalkPPORunnerCfg):
    experiment_name = "course_microduck_less_slip_symmetry"
```

Register both runner choices with the helper from lesson 6.

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

```python
register_task(
    "LessSlip",
    "LessSlipEnvCfg",
    "LessSlipPPORunnerCfg",
    symmetry_agent_cfg="SymmetricLessSlipPPORunnerCfg",
)
```

## Give Both Policies the Same Opportunity

Run from the root of IsaacLabTutorial. Set `WALK_CHECKPOINT` to the walking
policy you evaluated in lesson 6. To reproduce the supplied experiment, use
the pretrained policy from that lesson. Start both continuations from the
same file, use the same seed
and environment count, and give each 250 additional iterations. Disable the
curriculum in both runs so its changing weights don’t obscure the experiment.
Both runs use the configuration’s initial weights and ranges, start new
simulation episodes, and use a fresh optimizer. Both start with the same
network weights from the checkpoint.

```bash
uv run isaaclab train --task Course-Microduck-Walk-v0 \
    --rl_library rsl_rl --agent rsl_rl_with_symmetry_cfg_entry_point \
    --num_envs 4096 --max_iterations 250 --seed 43 \
    --checkpoint "$WALK_CHECKPOINT" \
    --no-resume_optimizer_state --run_name comparison_baseline \
    env.curriculum=null agent.algorithm.learning_rate=0.0001
```

After training finishes, play the saved policy:

```bash
uv run --extra viser isaaclab play --task Course-Microduck-Walk-v0 \
    --rl_library rsl_rl --agent rsl_rl_with_symmetry_cfg_entry_point \
    --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.

```bash
uv run isaaclab train --task Course-Microduck-LessSlip-v0 \
    --rl_library rsl_rl --agent rsl_rl_with_symmetry_cfg_entry_point \
    --num_envs 4096 --max_iterations 250 --seed 43 \
    --checkpoint "$WALK_CHECKPOINT" \
    --no-resume_optimizer_state --run_name comparison_less_slip \
    env.curriculum=null agent.algorithm.learning_rate=0.0001
```

After training finishes, play the saved policy:

```bash
uv run --extra viser isaaclab play --task Course-Microduck-LessSlip-v0 \
    --rl_library rsl_rl --agent rsl_rl_with_symmetry_cfg_entry_point \
    --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.

You can also skip training and evaluate the supplied comparison checkpoints.
In the next lesson, compare tracking and foot-contact measurements to test
your hypothesis.

## Try a New Case

First apply the one-step equation to a different starting position. Keep
`b = 1` and `c = 0.5`, but move from 0.90 m to 0.75 m instead of from 0.50 m
to 0.75 m. Calculate the reward and compare it with the worked example.
Explain why a backward move does not necessarily produce a negative reward.

A reaching robot receives a bonus every step its gripper stays near a
placement target. It often holds the object nearby until the episode ends
and rarely releases it.

Explain one possible incentive problem, propose one reward change, and state
how you would test it. Include a task-success measure and a possible downside
of your change. Also name one alternative explanation you would investigate
before blaming the reward.

### Compare Your Reasoning

Repeated proximity payments could make waiting attractive. One candidate
change is to replace those payments with progress feedback while retaining
a clearly defined completion reward. Measure full placement and release
independently of the reward, and compare success rate and time to completion
under common conditions. A progress signal might encourage fast,
unsafe approaches, so inspect contact forces too. Poor release actions,
missing observations, or insufficient exploration could also explain the
failure; the behavior alone does not prove a reward problem.

### Optional Depth: Potential-Based Shaping

A special shaping form is

$$
F(s_t,s_{t+1})=\gamma\Phi(s_{t+1})-\Phi(s_t),
$$

where $\Phi$ assigns a potential to each state and $\gamma$
is the same discount factor used by the learning objective. In a discounted
Markov decision process with bounded potential, its discounted sum telescopes
(intermediate potential terms cancel), leaving a state-dependent offset when
the terminal boundary term vanishes. That preserves the ordering of policies
from a fixed starting state.

For finite episodes, terminal handling matters: use zero terminal potential
or an equivalent absorbing-state treatment that removes the boundary term.
Time limits and truncations need handling consistent with the chosen
objective. The figure’s undiscounted, finite-episode proximity bonus does not
have this guarantee. Arbitrary gait bonuses and penalties do not either.

See [Ng, Harada, and Russell, *Policy Invariance Under Reward Transformations*](https://people.eecs.berkeley.edu/~russell/papers/icml99-shaping.pdf)
for the policy-invariance result and its assumptions.

## Check Your Progress

Changing the slip weight changes the scoring rule.
Choose shared measurements that let you compare the two policies using the
same criteria.

Continue to [Compare Policies](https://docs.nvidia.com/learning/physical-ai/getting-started-with-isaac-lab/2026-11.3/train-a-microduck/09-compare-policies.md) to evaluate the matched
slip-weight comparison using tracking, completion, and foot-motion measurements.
