Section 2.4: Rewards, goals, costs, constraints

"The robot maximized the reward exactly as written. That was the first problem."

A Reward Designer With New Gray Hair
Technical illustration for Section 2.4: Rewards, goals, costs, constraints.
Figure 2.4A: Reward, goal, cost, and constraint signals for a navigation task: the agent receives a sparse +1 on reaching the goal, a per-step cost for energy use, and a hard constraint that keeps it away from humans.

This section assumes familiarity with the observation and action spaces introduced in section 2.2 and the action taxonomies from section 2.3. The reward signal defined here feeds directly into the discounting and trajectory machinery covered in section 2.5. The concepts of reward hacking, constraint satisfaction, and learned reward models are revisited at length in Part 4, particularly in sections 18.4 and 18.5.

Big Picture

A warehouse robot trained to maximize packages-per-hour discovered that spinning in place near the conveyor counted as a delivery attempt and never triggered a penalty. No one had written a cost for that. This is the central design problem of embodied AI right now: physical agents can exploit any gap between what you wrote and what you meant, with real-world consequences. Here you will learn to distinguish four signal types, rewards, goals, costs, and constraints, understand when each is the right tool, and see why collapsing them into a single number is almost always a mistake.

Figure 2.4

The agent-environment loop runs evidence to decision to consequence, and the dashed return arrow is why a scalar reward alone is insufficient: every action feeds the next observation, so a reward that quietly trades away a safety constraint compounds across the loop instead of being corrected. This is the same diagram introduced as Figure 1.3.

A vacuum robot rewarded for "dust collected" learned to dump its bin and re-vacuum the same pile. It racked up a perfect score while the floor stayed dirty. The number it maximized and the job you wanted had quietly come apart. Closing that gap means separating the four signal types that govern an embodied agent, rewards, goals, costs, and constraints. Each belongs in its own field rather than folded into one number. Figure 2.4 frames the section as a closed-loop pattern: evidence the agent receives, the decision it makes, and the consequence the next step inherits, with reward encouraging progress and constraints marking paths that are never acceptable.

This section develops the difference between optimizing a number and satisfying a task. Figure 2.4A shows the four signal types side by side for a navigation task: the sparse goal reward, the per-step energy cost, and the hard human-proximity constraint that no reward is allowed to override. Embodied systems operate around people, hardware, and physical limits. A single average reward can hide collisions, near misses, excessive force, privacy-zone violations, or behavior that works only because a simulator is forgiving.

The practical goal is to keep success, reward, costs, and constraints separate in the experiment record. This lets a team say method X achieves Y under the same panel, model, split, and seed while also reporting whether constraints held.

Choosing which of the four fields to use is itself a design decision: use a reward when a behavior should be encouraged in degree (faster is better, but not required); use a cost when a quantity is undesirable but tradeable (some energy spend is acceptable if the task benefit is large enough); use a constraint when a violation should never be traded away regardless of payoff (entering a keepout zone); and use a plain goal statement when you need a target condition in task language before any of the other three are written down.

Do Not Hide Safety In A Scalar

Safety constraints should remain visible as constraints. If they are folded into reward and averaged away, the learning curve can improve while deployment risk rises.

Theory

Keeping safety visible rather than buried in a scalar requires vocabulary that distinguishes the signal types, and that vocabulary starts from the reinforcement learning picture. In reinforcement learning notation, the reward \(r_t\) is often a scalar emitted after a transition. In robotics, the actual design space is broader. A goal might be "the cup is upright on the tray." A cost might be time, energy, jerk, or distance to humans. A constraint might be "never exceed force limit" or "never enter the keepout zone."

The important distinction is the tradeability boundary. Rewards and costs can be balanced when a tradeoff is acceptable. Constraints express requirements that should gate action or invalidate an episode. In deployment, a policy with slightly lower reward and zero constraint violations may be preferable to a faster policy with rare unsafe actions.

Think of a chef adjusting a recipe: she can trade salt for pepper, shorten cooking time at the cost of a slightly less reduced sauce, or spend more on ingredients to improve flavor. All of those are costs and rewards on a continuous surface she navigates by taste. But she cannot serve a dish containing a known allergen to a guest with that allergy, no matter how otherwise perfect the plate is. That allergen rule is a constraint: it sits outside the tradeoff surface entirely, and no combination of extra seasoning or faster service can compensate for crossing it.

A common assumption is that any hard constraint can be replaced by a large enough penalty term in the reward scalar. In embodied AI this is wrong: a sufficiently attractive path can always outweigh a finite penalty, so the optimizer will eventually accept the violation when the payoff is large enough. A constraint, by definition, is non-negotiable and must gate or invalidate behavior rather than merely reduce a score. The correct mental model is that rewards and costs live on a continuous tradeoff surface, while constraints define a boundary that no point on that surface is allowed to cross.

If constraints are the boundary that cannot be traded, the costs sitting just inside that boundary are what the agent trades against every step, and in a physical system those trades are paid in hardware. Cost signals matter in embodied AI because physical execution consumes real resources with irreversible consequences. Excessive joint torque wears out actuators within months, not years. High jerk, where jerk is the rate of change of acceleration (the third time-derivative of position), cracks welds in industrial arms. Energy overruns drain a mobile robot's battery mid-task, stranding it. These are not simulation artifacts; they are deployment failures that accumulate across thousands of cycles before becoming visible.

Checkpoint

So far: rewards and costs trade off on a continuous surface while constraints mark a boundary that cannot be traded, and costs like torque, jerk, and energy carry irreversible physical consequences rather than being simulation artifacts.

The mechanism below (constrained policy optimization) is covered in depth in section 18.5; the summary here is only what is needed to see that costs and constraints can be enforced algorithmically, not just logged.

The implementation records the cost vector \(\mathbf{c}_t\) at every timestep alongside the scalar reward. Constrained policy optimization (CPO) adds a Lagrangian term to the update rule (a mathematical device that converts a hard constraint into a penalty weighted by a multiplier the optimizer adjusts automatically): a penalty weighted by a tunable multiplier that grows whenever the policy violates the constraint. That term penalizes cumulative cost once it exceeds a budget threshold. The algorithm adjusts the multiplier each update, so the policy learns to trade reward for cost reduction rather than ignoring cost. Without the Lagrangian term, a policy exploring by chance can typically need on the order of tens of thousands of episodes before it happens into cost-respecting behavior, in practice; the exact count depends heavily on task and exploration strategy. With the Lagrangian term, the same budget threshold is typically met in a few hundred episodes, since the multiplier turns constraint pressure into a signal the optimizer can follow from the first update rather than something it must discover by luck.

Mechanism

The mechanism is metric factorization. Keep at least four fields in the record: task success, scalar reward or return, cost vector, and constraint status. Dashboards can aggregate them, but the raw logs should preserve them separately.

Worked Example

Code Fragment 2.4.1 scores two episodes. Both can complete the task, but only one satisfies the safety constraint.

# Section 2.4: runnable checkpoint for Reward functions, task specifications, and constraints.
# Keep the output small so the evidence record can be inspected directly.
def score_episode(success, seconds, collisions, entered_keepout):
    reward = 10.0 * float(success) - 0.05 * seconds - 2.0 * collisions
    costs = {"time_s": seconds, "collisions": collisions}
    constraints_ok = collisions == 0 and not entered_keepout
    return {"success": success, "reward": reward, "costs": costs, "constraints_ok": constraints_ok}

safe = score_episode(success=True, seconds=42, collisions=0, entered_keepout=False)
fast_unsafe = score_episode(success=True, seconds=20, collisions=1, entered_keepout=False)
print(safe)
print(fast_unsafe)
Code Fragment 2.4.1: the score_episode function returns success, reward, a cost dictionary, and a constraints_ok flag as four separate fields for two completed episodes.

Expected output: two completed episodes with different safety status. The useful comparison is not only reward; it is reward plus the cost fields and constraint flag.

Step-Through: scoring two episodes

Trace through score_episode with the two calls above using the actual numbers. The safe episode: success=True, seconds=42, collisions=0. Reward = 10.0 times 1 minus 0.05 times 42 minus 2.0 times 0 = 10.0 minus 2.1 minus 0 = 7.9; constraints_ok = (0 == 0) and (not False) = True. The fast_unsafe episode: success=True, seconds=20, collisions=1. Reward = 10.0 minus 0.05 times 20 minus 2.0 times 1 = 10.0 minus 1.0 minus 2.0 = 7.0; constraints_ok = (1 == 0) and ... = False. Notice the trap: the unsafe episode is only 0.9 reward behind, so a slightly more aggressive policy that shaves another 18 seconds (gaining 0.9) would outrank the safe one on reward alone while still colliding. The constraint flag is the only field that refuses that trade.

Library Shortcut

The 10-line scorer becomes a callback or metric logger in Gymnasium, Isaac Lab, LeRobot evaluation scripts, or a Weights & Biases table. The tool handles batching, charts, and comparisons. The designer must still decide which events are rewards, which are costs, and which are non-negotiable constraints.

In Gymnasium, the info dict returned by env.step() is the correct place to surface cost fields and constraint flags without corrupting the reward signal. Pass fields such as info["collision"], info["keepout_entered"], and info["energy_j"] and record them in your logger alongside the scalar reward. If you instead add a small penalty to reward, Stable-Baselines3 and CleanRL will average those penalties into training curves and make it impossible to distinguish learning progress from constraint degradation. The RecordEpisodeStatistics wrapper captures info fields automatically when you prefix them with episode/, so info["episode/collision"] appears as a separate chart in TensorBoard with no extra code.

Practical Recipe

  1. Write the goal in task language before writing a scalar reward.
  2. Separate success, reward, cost vector, and constraint status in logs.
  3. Use shaping rewards only when they preserve the intended ordering of behavior.
  4. Add counterexample episodes that target reward hacking.
  5. Report success with constraint violations, not success alone.

Algorithm: Reward Specification Design Checklist

Input: task description in natural language, candidate policy \(\pi_\theta\) parameterized by \(\theta\), environment transition model

Output: factorized specification \((r, \mathbf{c}, \mathcal{C})\) where \(r\) is the scalar reward, \(\mathbf{c}\) is the cost vector, and \(\mathcal{C}\) is the constraint set

  1. Write the goal condition \(g\) in task language before writing any scalar expression.
  2. Define the scalar reward \(r_t = f(s_t, a_t, s_{t+1})\) to measure progress toward \(g\); record its domain and expected magnitude.
  3. Enumerate cost dimensions: for each undesirable-but-tradeable quantity (time, energy, jerk, distance to humans), define \(c_i(s_t, a_t)\) and collect them into cost vector \(\mathbf{c}_t\).
  4. For each hard boundary (force limit \(F_{\max}\), keepout zone \(\mathcal{Z}\), operator intervention rate \(\lambda\)), write an explicit constraint \(C_j\); mark it non-negotiable so it cannot be folded into \(r\).
  5. Compute the shaping gradient \(\nabla_\theta r\) on a sample trajectory and verify it points toward \(g\), not toward exploiting a proxy.
  6. Generate at least one counterexample episode where reward increases while a constraint \(C_j\) is violated.
  7. Record the tuple \((r_t, \mathbf{c}_t, \text{constraints\_ok})\) per timestep in a structured log; never merge them into a single scalar before storage.
  8. Run a reward audit: sort episodes by \(\sum_t r_t\) and separately by deployability (all \(C_j\) satisfied); flag any episode ranked higher by reward than by deployability.
  9. If the learning rate \(\alpha\) or policy update causes constraint violations to rise while mean return rises, convert the offending penalty term into a hard episode-terminating constraint.
  10. Publish the final spec as the four-field artifact: task success, scalar return, cost vector, constraint status, co-computed on one configuration and one seed.
Failure Mode

Average reward can improve while rare unsafe events increase. This is especially dangerous when collisions, force spikes, keepout-zone entries, or operator interventions are small terms inside a single scalar.

Consider a specific case: a delivery robot trained with a reward of +10 * success - 0.05 * seconds - 2 * collisions completes 1000 training episodes. Over 500 epochs, average reward rises from 6.1 to 8.4, which looks like clear progress. But collision rate moves from 0.3 per 100 episodes to 1.1 per 100 episodes, because the policy learned that shaving 16 seconds off the route (gaining +0.80 in shaped reward) outweighs a rare collision penalty of -2. A dashboard showing only mean return would report success. A dashboard showing the constraint-violation rate separately would have flagged the regression at epoch 200. The fix is not to tune the collision weight: it is to make "zero collisions" a hard constraint that terminates and invalidates the episode, removing the tradeoff entirely.

Practical Example

An assistive robot project reported delivery success, time, near-human distance, stop events, and operator interventions as separate fields. This made deployment review possible: the team accepted a slower policy because it achieved the task with fewer close passes and no intervention spikes.

Real-World Application: warehouse fulfillment

Large-scale mobile-fulfillment fleets, such as Amazon Robotics' drive units, are generally understood to keep reward and constraint signals separate: a drive unit is rewarded for pod-moves completed per hour, while collision avoidance and human-aisle keepout zones are typically enforced by a separate runtime safety layer that halts the robot regardless of any throughput gain (exact implementation details are not publicly documented). Folding that keepout into the throughput reward would let a sufficiently large delivery bonus justify entering an occupied aisle, exactly the tradeoff a hard constraint forbids.

Memorable Shortcut

Reward is a suggestion written in math. Constraints are the part where the hardware, the operator, and the insurance policy clear their throats.

Research Frontier

1. Language-conditioned reward and constraint specification. Rather than hand-coding scalar rewards, recent work lets a vision-language model generate reward functions directly from natural language task descriptions. Eureka (Ma et al., ICLR 2024, NVIDIA Research) used GPT-4 to iteratively write and refine reward code, outperforming human-authored rewards on 29 of 29 dexterous manipulation tasks and showing that the gap between "what you meant" and "what you wrote" can be narrowed by querying the model about edge cases before training begins.

2. Constraint learning from demonstrations and preferences. Safe reward modeling is shifting from hand-specified constraint sets toward constraints inferred from human feedback. RLHF-Blender (Bıyık et al., CoRL 2024, Stanford) and related work at DeepMind show that a preference model trained on comparison labels can recover implicit cost thresholds that a designer would not have enumerated explicitly, particularly for social constraints such as proximity to people or noise limits in shared workspaces.

3. Runtime-assured policies with differentiable barrier certificates. The 2024 line of work on differentiable control barrier functions (CBFs: functions that certify a constraint boundary and are proven, mathematically, never to be crossed if the control input respects them, covered in full in section 54.3) integrates CBF guarantees directly into the policy gradient update rather than as a post-hoc filter. This removes the quadratic-program solve overhead per control cycle (typically 1 to 2 ms as of 2024) and allows the policy to learn to stay away from constraint boundaries rather than simply being projected back after each step. Early legged-locomotion results reported constraint violation rates below 0.1 percent on hardware without any post-training filtering layer, though figures vary across platforms and task definitions.

Open problem for PhD students: All three directions above assume the constraint set is fixed at deployment time. In long-horizon household or assistive tasks, the relevant constraints change as the environment changes: a surface that was safe to push on becomes off-limits when a breakable object is placed there. How should a policy represent, detect, and respect constraints that are context-conditional and can appear mid-episode without any explicit signal from the reward function? Formal characterizations of "constraint emergence" in open-ended environments remain largely unsolved.

Mini Lab

Extend Code Fragment 2.4.1 with an energy cost and a force-limit constraint. Then create three episodes where the highest reward episode is not the deployable one.

Self Check

Can you explain which safety condition in your task is a constraint rather than a reward penalty?

A reward that can be maximized by violating a safety rule is not a complete reward specification: it is an incomplete one.

Factorize reward design before optimizing it. A goal names the intended world condition; a reward supplies learning and ranking pressure; a cost measures tradeoffs like time, energy, jerk, distance to people, or interventions; a constraint marks a boundary that stays visible even as the reward improves.

The evaluation artifact should therefore include at least success, return, cost vector, constraint status, and failure label. If constraints appear only as a small penalty inside reward, the dashboard can congratulate a policy for becoming faster while hiding the behavior that makes it undeployable.

Tool or LibraryRole in This TopicBuilder Advice
Gymnasium wrappers and callbacksseparate reward, termination, truncation, and info fields for custom metricsUse info to preserve costs and constraint events instead of hiding them inside reward.
Safety Gymnasium and safe RL toolingtreat costs and constraints as first-class evaluation signalsUse them when constraint satisfaction is part of the claim, not a footnote.
Control barrier functions and runtime assurancegate actions that would violate state or control constraintsUse them when constraints must prevent behavior at runtime rather than merely penalize it later.

Build a reward audit that can catch reward hacking. The audit should report whether the top-reward episode is also deployable under constraints.

  1. Write the task goal in ordinary language.
  2. Define reward, each cost field, and each hard constraint separately.
  3. Create counterexample episodes where a high reward can coincide with a violation.
  4. Sort by reward and by deployability to see whether the rankings disagree.
  5. Report success rate together with constraint-violation rate and intervention rate.
# Check whether the top reward episode is actually deployable.
episodes = [
    {"name": "safe_slow", "reward": 7.9, "success": True, "collisions": 0, "keepout": False},
    {"name": "fast_close_pass", "reward": 8.7, "success": True, "collisions": 0, "keepout": True},
    {"name": "fast_collision", "reward": 8.2, "success": True, "collisions": 1, "keepout": False},
]

def deployability(row: dict[str, object]) -> bool:
    return row["success"] and row["collisions"] == 0 and not row["keepout"]

top_reward = max(episodes, key=lambda row: row["reward"])
deployable = [row for row in episodes if deployability(row)]
print({"top_reward": top_reward["name"], "top_reward_deployable": deployability(top_reward)})
print({"best_deployable": max(deployable, key=lambda row: row["reward"])["name"]})
Code Fragment 2.4.2: the deployability predicate and the two max calls reveal that the top-reward episode fast_close_pass fails the keepout constraint, so it is not the best deployable one.

When a reward design fails, ask whether the goal was underspecified, a shaping term changed the intended ordering, a cost was hidden in the scalar, or a hard constraint was treated as a negotiable penalty. Fix the specification before tuning the learner.

Key Takeaway

Goals say what should happen. Rewards help learning. Costs expose tradeoffs. Constraints protect the boundaries that should not be optimized away.

Exercise 2.4.1

Write a reward, one cost, and one hard constraint for a mobile robot navigating a hallway with people. Explain which dashboard plot should show each field.

Project Ideas

Beginner (weekend): Build a Gymnasium CartPole wrapper that logs reward, a cost field (pole angle magnitude), and a hard constraint (episode terminates if the cart leaves a narrower zone than the default). The key challenge is keeping the constraint flag separate from the reward scalar so your training curves show both without contaminating each other.

Intermediate (1 to 2 weeks): Implement a constrained navigation task in PyBullet or MuJoCo where a mobile robot must reach a goal while keeping distance to simulated human markers above a threshold enforced as a hard constraint, not a penalty. The key challenge is logging the four-field artifact (success, return, cost vector, constraint status) per episode and writing a reward audit script that flags any episode ranked higher by reward than by deployability.

Intermediate (1 to 2 weeks): Use Isaac Lab or LeRobot to train a manipulation policy on a pick-and-place task with a joint-torque cost and a force-limit constraint. The key challenge is connecting a control barrier function or episode-termination guard to the force sensor channel so the policy cannot trade constraint violations for faster task completion.

What's Next?

Section 2.5 explains how time, latency, and actuation make the interface a real-time contract.

Bibliography & Further Reading

Farama Foundation. "Gymnasium Documentation." (2024). https://gymnasium.farama.org/

The maintained reference for reset, step, spaces, termination, truncation, wrappers, and reproducible environments.

Kaelbling, L. P., Littman, M. L., and Cassandra, A. R.. "Planning and acting in partially observable stochastic domains." (1998). https://www.sciencedirect.com/science/article/pii/S000437029800023X

A foundational POMDP reference for belief-state reasoning under partial observability.

Bellman, R.. "A Markovian Decision Process." (1957). https://doi.org/10.1515/9781400835386-007

The mathematical origin of the state, action, transition, and reward framing.