We are going to design a library for reinforcement learning reward design. The library should include:
- Templates for common reward structures (e.g., sparse, dense, shaped, penalizing, etc.)
- Documentation of common pitfalls (e.g., reward hacking, unintended shortcuts, etc.)
- Validation tests to check for common issues (like reward hacking, local optima, etc.)
We'll design the library in a modular way so that users can compose rewards and run validation tests.
Steps:
- Define a base
Reward class that can be composed and modified.
- Implement common reward templates as subclasses or functions that return a Reward function.
- Implement a set of validation tests that take a reward function and an environment (or a set of trajectories) and run checks.
- Provide a way to run these tests and report results.
However, note that in RL, the reward function is typically part of the environment. So we might assume that we have an environment and we want to design a reward function for it.
Alternatively, we can design a library that helps in:
a) Designing the reward function (by providing building blocks and patterns)
b) Testing the reward function for common issues (by generating trajectories or using known problematic scenarios)
Since we are designing a library, we can have:
reward_designer: a module with templates and composition tools.
reward_validation: a module with tests that can be run on a given reward function and environment.
But note: some validation tests might require the environment dynamics. So we might need to pass the environment or a model of the environment.
Alternatively, we can design the validation tests to work with a set of trajectories (state, action, reward, next_state) and look for anomalies.
Let's break down:
Part 1: Reward Design Templates
We can have:
- Sparse reward: only at terminal state.
- Dense reward: at every step, based on some features.
- Shaped reward: using a potential function to guide the agent (like in reward shaping).
- Penalizing: for certain actions or state transitions.
- Multi-objective: combining multiple rewards.
We can represent a reward function as a function: f(state, action, next_state) -> reward.
But note: in some environments, the reward might depend only on state or next_state. We can be flexible.
We can have:
class Reward:
def call(self, state, action=None, next_state=None, done=False):
pass
Then we can have:
class SparseReward(Reward):
def init(self, terminal_reward=1.0, non_terminal_reward=0.0):
self.terminal_reward = terminal_reward
self.non_terminal_reward = non_terminal_reward
def __call__(self, state, action=None, next_state=None, done=False):
return self.terminal_reward if done else self.non_terminal_reward
class DenseReward(Reward):
def init(self, reward_fn):
self.reward_fn = reward_fn # a function that takes (state, action, next_state)
def __call__(self, state, action=None, next_state=None, done=False):
return self.reward_fn(state, action, next_state)
class ShapedReward(Reward):
def init(self, potential_fn, gamma=0.99):
self.potential_fn = potential_fn
self.gamma = gamma
def __call__(self, state, action=None, next_state=None, done=False):
if done:
# In the terminal state, we might set potential to 0 or the terminal reward?
# Typically, reward shaping: F(s,s') = gamma * phi(s') - phi(s)
# But we need to define the shaped reward as an add-on to the original reward.
# Alternatively, we can have the shaped reward as a separate reward that is added.
# Let's assume we are designing the entire reward. Then we can do:
# reward = original_reward + gamma * phi(s') - phi(s)
# But note: we don't have the original reward here?
# So maybe we should have a base reward and then shape it.
pass
This becomes tricky. Instead, let's think of composing rewards:
class CompositeReward(Reward):
def init(self, rewards):
self.rewards = rewards
def __call__(self, state, action=None, next_state=None, done=False):
total = 0
for r in self.rewards:
total += r(state, action, next_state, done)
return total
Then we can have:
base_reward = SparseReward(terminal_reward=1.0)
shaping = ShapedReward(potential_fn, gamma=0.99)
reward = CompositeReward([base_reward, shaping])
But note: the shaped reward should be defined in terms of the base reward? Actually, reward shaping is a transformation of the reward function.
Alternatively, we can have a RewardShaper that takes a base reward and returns a new reward.
class RewardShaper:
def init(self, potential_fn, gamma=0.99):
self.potential_fn = potential_fn
self.gamma = gamma
def shape(self, base_reward):
# returns a new reward function that is base_reward + gamma*phi(s') - phi(s)
def shaped_reward(state, action=None, next_state=None, done=False):
if done:
# In the terminal state, we don't have next_state? or we do?
# In some definitions, the potential of terminal state is 0.
phi_s_next = 0.0
else:
phi_s_next = self.potential_fn(next_state)
phi_s = self.potential_fn(state)
return base_reward(state, action, next_state, done) + self.gamma * phi_s_next - phi_s
return shaped_reward
But then we lose the class structure. Alternatively, we can have:
class ShapedReward(Reward):
def init(self, base_reward, potential_fn, gamma=0.99):
self.base_reward = base_reward
self.potential_fn = potential_fn
self.gamma = gamma
def __call__(self, state, action=None, next_state=None, done=False):
if done:
phi_s_next = 0.0
else:
phi_s_next = self.potential_fn(next_state)
phi_s = self.potential_fn(state)
return self.base_reward(state, action, next_state, done) + self.gamma * phi_s_next - phi_s
However, note: the base reward might be a function that doesn't take done? We are passing done to it. But the base reward might not use done. That's okay.
But then we have a problem: what if the base reward is already a composite? We can handle it because we are just calling it.
Alternatively, we can have a Reward base class and then have ShapedReward take a Reward instance as base.
Let's redesign:
class Reward:
def call(self, state, action=None, next_state=None, done=False):
raise NotImplementedError
class SparseReward(Reward):
...
class DenseReward(Reward):
...
class ShapedReward(Reward):
def init(self, base_reward, potential_fn, gamma=0.99):
self.base_reward = base_reward
self.potential_fn = potential_fn
self.gamma = gamma
def __call__(self, state, action=None, next_state=None, done=False):
# potential of next_state: if done, then we set to 0?
# But note: in the terminal state, the agent doesn't take an action. So we might not have next_state?
# Actually, in the transition that leads to terminal, we have next_state as the terminal state.
# And then the episode ends. So we can compute phi(s_next) for the terminal state?
# But the agent doesn't act in the terminal state. So we set phi(terminal)=0?
# This is common in reward shaping to avoid shaping in the terminal state.
if done:
phi_s_next = 0.0
else:
phi_s_next = self.potential_fn(next_state)
phi_s = self.potential_fn(state)
base = self.base_reward(state, action, next_state, done)
return base + self.gamma * phi_s_next - phi_s
class CompositeReward(Reward):
def init(self, rewards):
self.rewards = rewards
def __call__(self, state, action=None, next_state=None, done=False):
return sum(r(state, action, next_state, done) for r in self.rewards)
Then we can do:
base = SparseReward(terminal_reward=1.0)
potential_fn = lambda state: -np.linalg.norm(state - goal) # for example
shaped = ShapedReward(base, potential_fn, gamma=0.99)
reward = shaped # or we can add more to composite
But note: the potential function must be bounded? Actually, for the shaping to be valid (i.e., not change the optimal policy) we need the potential to be bounded. But in practice, we often use unbounded potentials and it might still work.
However, for validation, we might want to check if the potential is bounded? That's one of the validation tests.
Part 2: Common Pitfalls
We can document:
- Reward hacking: when the agent finds a way to get high reward without achieving the intended goal.
- Unintended shortcuts: the agent exploits a loophole in the reward function.
- Over-shaping: too much shaping might lead to suboptimal policies or instability.
- Sparse rewards leading to exploration problems.
- Reward scale: if rewards are too small or too large, learning can be unstable.
We can write these as warnings in the documentation and also have validation tests that try to detect some of these.
Part 3: Validation Tests
We can have a set of tests that take:
- environment (or a model of the environment)
- reward function (of type Reward)
- (optionally) a policy (or we can generate random trajectories)
and then check:
-
Reward hacking: try to see if there is a state (or trajectory) that gives high reward but is clearly not the intended goal.
How? We might need a way to specify what the intended goal is. So we can have a GoalChecker that, given a state, says if the goal is achieved.
Test: generate random trajectories and check if there are states with high reward that are not goal states (if we have a goal checker).
-
Unintended shortcuts: for example, in a maze, if the reward is based on distance to goal, the agent might learn to go to a corner that is close to the goal but not the goal? Actually, that's a shaping issue.
-
Check for potential function being bounded? (if using shaping) We can try to compute the potential over a set of states (maybe from random trajectories) and see if it's bounded.
-
Check for reward scale: compute the mean and variance of rewards over random trajectories. If the variance is too low, the agent might not have enough signal. If too high, it might be unstable.
-
Check for local optima: if there is a state that gives high reward but is not the goal, and from there the agent cannot reach the goal, that's a local optimum.
We can try to run a short-horizon planner (or value iteration) on a model of the environment (if available) to see if the reward function leads to the intended goal.
-
Check if the reward is Markovian? Actually, the reward function should be a function of (s, a, s'). But if we are designing a reward that depends on history, that's non-Markovian and might be problematic.
We can test: for two identical (s, a, s') pairs in different trajectories, do we get the same reward? If not, then it's non-Markovian.
However, note: the environment might be non-Markovian? But typically we assume MDP.
Implementation:
We can have a RewardValidator class that runs a set of tests.
Example:
validator = RewardValidator(env, reward_function)
results = validator.run_tests(['reward_hacking', 'potential_bounded', ...])
But note: some tests require a goal checker. We can have:
validator.set_goal_checker(goal_checker_fn)
where goal_checker_fn(state) -> bool
Also, some tests require a model of the environment? We might not have that. So we rely on trajectories.
We can generate random trajectories by:
state = env.reset()
done = False
while not done:
action = env.action_space.sample()
next_state, reward, done, _ = env.step(action)
# record (state, action, next_state, reward)
But note: we are using the environment's step, which uses the environment's reward. We want to test our designed reward function, so we should replace the environment's reward with our reward function.
Alternatively, we can have:
def run_episode(env, policy, reward_function=None):
# if reward_function is provided, we use it instead of env's reward.
But then we need to change the environment? Or we can just compute the reward ourselves.
Let's assume we have an environment that we can step and get (next_state, done, info) and then we compute the reward with our function.
We can do:
state = env.reset()
done = False
trajectory = []
while not done:
action = policy(state) # or random
next_state, _, done, info = env.step(action) # we ignore the env's reward
reward = reward_function(state, action, next_state, done)
trajectory.append((state, action, next_state, reward, done))
state = next_state
Then we can analyze the trajectory.
So the validation tests will run multiple episodes (maybe random policy) and collect data.
Tests:
Test 1: Reward Hacking
For each (state, action, next_state, reward) in the trajectory:
if reward > threshold (e.g., 0.9 * max_possible_reward) and not goal_checker(next_state):
flag as potential reward hacking.
Test 2: Potential Bounded (for shaping)
If the reward function is a ShapedReward, then we can extract the potential function and compute its values over all states in the trajectory.
Check if the potential is bounded (within some range). But note: we might not see the entire state space.
Test 3: Reward Scale
Compute mean and std of rewards. If std < epsilon, then too low. If mean is too high or too low? We can set thresholds.
Test 4: Local Optima
We can try to see if there is a state that yields high reward (above a threshold) but from which the goal is not reachable (according to a planner or by checking if the agent ever reaches the goal from that state in the trajectories?).
But we might not have trajectories from that state. So we might need a model.
Alternatively, we can use the trajectories to build a graph and then check for states that have high reward and are in a component that does not contain the goal.
Steps:
Build a graph: nodes are states (or state clusters) and edges are transitions.
Then for each state that has high reward, check if there is a path from that state to a goal state (in the graph). If not, then it's a local optimum.
But note: the graph might not be fully explored.
Test 5: Non-Markovian
For each unique (state, action, next_state) pair, check if the reward is the same. If not, then the reward is non-Markovian.
However, note that the same (s,a,s') might occur in different contexts (with different done flags). So we should also consider `done`? Actually, the reward function might depend on `done`. So we should consider (s,a,s',done).
But in an MDP, the reward should only depend on (s,a,s'). So if we see two identical (s,a,s') but different `done` and the reward is different, then it's non-Markovian? Actually, no, because `done` is a property of the transition. In MDP, the reward is a function of (s,a,s') and then `done` is determined by s' (if s' is terminal). So if s' is terminal, then done is True. So we don't need to pass done? Actually, in the step function, we get done. But in the MDP, the reward for (s,a,s') is fixed regardless of whether we call it done or not? Actually, the done flag is part of the transition: if s' is terminal, then the transition leads to termination.
So we can ignore `done` and just use (s,a,s'). But note: if s' is terminal, then the next state is not used. So the reward for (s,a,s') when s' is terminal might be different than when s' is non-terminal? Actually, in the MDP, the reward is defined for every (s,a,s') and then the transition probability and the done are separate.
So we should not include `done` in the key? Because the same (s,a,s') should always yield the same reward, regardless of whether s' is terminal or not? Actually, the reward function is defined on the transition (s,a,s'). So if we have two transitions (s,a,s') and s' is the same state, then the reward should be the same. But if s' is terminal, then we might have a special reward? Actually, the reward function is defined on the triplet. So if s' is a terminal state, then the reward for (s,a,s') is defined and then the episode ends.
So we can group by (s,a,s') and check if the reward is the same.
However, note: if the reward function uses `done` in its computation, then it's non-Markovian? Actually, in an MDP, the reward function should not depend on `done` because `done` is determined by s' (if s' is terminal). So if the reward function is defined as f(s,a,s',done) and we have two identical (s,a,s') but one has done=True and the other done=False, then that would be non-Markovian? But in reality, if s' is terminal, then done must be True. So we cannot have two identical (s,a,s') with different done? Unless s' is the same state but sometimes terminal and sometimes not? That would be a non-Markovian environment.
So in a proper MDP, for a given (s,a,s'), the done is fixed (if s' is terminal, then done is always True). So we can ignore done and just use (s,a,s').
But note: our reward function might be designed to use `done` as an input. Then we are allowing non-Markovian rewards? We should warn the user.
So test: for every (s,a,s') that appears in the trajectories, check if the reward is the same regardless of the `done` flag? Actually, if we see the same (s,a,s') with different done, then that's a problem in the environment? Or in the reward function? The reward function might be using `done` to change the reward for the same (s,a,s')? That would be non-Markovian.
So we can check: group by (s,a,s') and then check if the reward is the same for all groups. If not, then the reward function is non-Markovian.
But note: if the environment is non-Markovian (i.e., the same (s,a,s') can lead to different done) then we have a problem in the environment. We are testing the reward function in the context of the environment. So if the environment is non-Markovian, then we cannot expect the reward function to be Markovian? Actually, the reward function should only depend on (s,a,s') and not on the history. So if the environment gives the same (s,a,s') but different done, then the environment is non-Markovian and the reward function is being called with the same (s,a,s') but different done? Then the reward function might give different rewards? That would be the reward function's fault? Or the environment's?
Let's assume we are in an MDP. Then we expect that for a given (s,a,s'), the done is fixed. So we can ignore done.
So test: for each unique (s,a,s'), the reward should be the same.
Implementation:
We'll collect all (s,a,s',reward) and then group by (s,a,s'). If any group has more than one unique reward, then fail.
But note: due to floating point, we might have slight differences. We can use a tolerance.
Alternatively, we can compute the standard deviation for each group and if it's above a threshold, then fail.
Part 4: Putting it together
We'll create:
reward_designer/
__init__.py
templates.py # contains Reward base class and common templates
shaping.py # if we want to separate, but we can keep in templates.
reward_validation/
__init__.py
validator.py # RewardValidator class
tests.py # individual test functions
Example usage:
from reward_designer.templates import SparseReward, ShapedReward, CompositeReward
from reward_validation.validator import RewardValidator
# Design the reward
base = SparseReward(terminal_reward=1.0)
potential_fn = lambda state: -np.linalg.norm(state - goal)
shaped = ShapedReward(base, potential_fn, gamma=0.99)
reward_fn = shaped
# Set up environment (must be an environment that we can step and reset)
env = ...
# Define goal checker (if we have one)
def is_goal(state):
return np.linalg.norm(state - goal) < 0.1
validator = RewardValidator(env, reward_fn)
validator.set_goal_checker(is_goal)
results = validator.run_tests(['reward_hacking', 'non_markovian', 'potential_bounded'])
print(results)
We can also allow the user to run a specific test.
The validator will run random episodes (with random policy) to collect data for tests that require trajectories.
For tests that require a model (like checking for local optima with planning), we might need a model. We can skip if no model.
Alternatively, we can have:
validator.run_tests(test_names, model=None, num_episodes=10)
If a test requires a model and it's not provided, we skip or warn.
Let's design the RewardValidator:
class RewardValidator:
def init(self, env, reward_function):
self.env = env
self.reward_function = reward_function
self.goal_checker = None
self.trajectories = [] # we can store trajectories for multiple tests
def set_goal_checker(self, goal_checker):
self.goal_checker = goal_checker
def collect_trajectories(self, num_episodes, policy=None):
if policy is None:
policy = lambda state: self.env.action_space.sample()
trajectories = []
for _ in range(num_episodes):
state = self.env.reset()
done = False
trajectory = []
while not done:
action = policy(state)
next_state, _, done, info = self.env.step(action) # ignore env reward
reward = self.reward_function(state, action, next_state, done)
trajectory.append((state, action, next_state, reward, done))
state = next_state
trajectories.append(trajectory)
self.trajectories = trajectories
return trajectories
def test_reward_hacking(self, reward_threshold=0.9):
# We need to know the maximum possible reward? Or we can set a threshold.
# Alternatively, we can look for rewards that are high (above a threshold) and the next state is not a goal.
if self.goal_checker is None:
raise ValueError("Goal checker not set for reward hacking test.")
hacking_cases = []
for traj in self.trajectories:
for (s, a, s_next, r, done) in traj:
if r > reward_threshold and not self.goal_checker(s_next):
hacking_cases.append((s, a, s_next, r))
return hacking_cases
def test_non_markovian(self, tolerance=1e-6):
# Group by (s, a, s_next) and check reward consistency.
rewards_by_transition = {}
for traj in self.trajectories:
for (s, a, s_next, r, done) in traj:
key = (tuple(s.tolist()), a, tuple(s_next.tolist())) # assuming states are arrays
if key not in rewards_by_transition:
rewards_by_transition[key] = []
rewards_by_transition[key].append(r)
non_markovian_cases = []
for key, rewards in rewards_by_transition.items():
if len(rewards) > 1:
max_diff = max(rewards) - min(rewards)
if max_diff > tolerance:
non_markovian_cases.append((key, rewards))
return non_markovian_cases
def test_potential_bounded(self):
# Check if the reward function is a ShapedReward and then check the potential function.
if not isinstance(self.reward_function, ShapedReward):
return "Not a shaped reward."
potential_fn = self.reward_function.potential_fn
# Collect all states from trajectories
all_states = []
for traj in self.trajectories:
for (s, a, s_next, r, done) in traj:
all_states.append(s)
all_states.append(s_next)
# Compute potentials
potentials = [potential_fn(s) for s in all_states]
min_p = min(potentials)
max_p = max(potentials)
# Check if bounded? We can set a threshold for the range?
# We can return the range and let the user decide.
return {"min_potential": min_p, "max_potential": max_p, "range": max_p - min_p}
def test_reward_scale(self, low_threshold=-10, high_threshold=10):
# Collect all rewards
all_rewards = []
for traj in self.trajectories:
for (_, _, _, r, _) in traj:
all_rewards.append(r)
mean = np.mean(all_rewards)
std = np.std(all_rewards)
if std < 1e-6:
return "Very low variance in rewards. Consider rescaling."
if mean < low_threshold or mean > high_threshold:
return f"Mean reward {mean} is outside the typical range [{low_threshold}, {high_threshold}]."
return {"mean": mean, "std": std, "message": "OK"}
def run_tests(self, test_names, num_episodes=10, policy=None):
# Collect trajectories if not already collected or if we want new ones.
if not self.trajectories:
self.collect_trajectories(num_episodes, policy)
results = {}
for test_name in test_names:
if test_name == 'reward_hacking':
results['reward_hacking'] = self.test_reward_hacking()
elif test_name == 'non_markovian':
results['non_markovian'] = self.test_non_markovian()
elif test_name == 'potential_bounded':
results['potential_bounded'] = self.test_potential_bounded()
elif test_name == 'reward_scale':
results['reward_scale'] = self.test_reward_scale()
else:
results[test_name] = "Unknown test."
return results
This is a basic structure.
We might want to add more tests and make the validator more flexible.
Note: The test for local optima is more complex and might require a model. We skip for now.
Also, note: the test for potential bounded only works if the reward is a ShapedReward. We can also check if the potential function is bounded in general (even if not shaped, we might want to check the reward function's scale?).
We can also add a test for:
- Dead ends: states from which the agent cannot reach the goal (if we have a goal checker and a model, we can check). Without a model, we can check in the trajectories if there are states that are visited and from which the agent never reaches the goal? But that might be due to policy.
So without a model, it's hard.
We can also check:
- Reward sparsity: if the reward is zero most of the time? We can compute the fraction of non-zero rewards.
Let's add:
def test_reward_sparsity(self, threshold=0.1):
# If less than threshold of steps have non-zero reward, then it's sparse.
total_steps = 0
non_zero_steps = 0
for traj in self.trajectories:
for (_, _, _, r, _) in traj:
total_steps += 1
if abs(r) > 1e-6:
non_zero_steps += 1
fraction = non_zero_steps / total_steps if total_steps > 0 else 0
if fraction < threshold:
return f"Reward is sparse: only {fraction*100:.2f}% of steps have non-zero reward."
else:
return f"Reward is dense: {fraction*100:.2f}% of steps have non-zero reward."
We can also check for:
- Reward clipping: if the reward is always within a small range? That might be intentional.
But we already have reward_scale.
We can also check for:
- Constant reward: if the reward is the same for every step? That would be a bug.
We can do:
def test_constant_reward(self):
all_rewards = []
for traj in self.trajectories:
for (_, _, _, r, _) in traj:
all_rewards.append(r)
if len(set(all_rewards)) == 1:
return f"Constant reward: {all_rewards[0]}"
else:
return "Not constant."
Now, we have a basic library.
However, note: the potential function might be defined in a way that is not bounded? We are just computing the range over the visited states. That's not a guarantee for the entire state space.
We can warn the user that the test is only over the visited states.
Similarly, for non-Markovian, we are only checking the visited transitions.
We can also add a test for:
- Negative rewards: if the reward is always negative, that might be problematic.
But that's domain specific.
Let's keep it as is for now.
We should also document the pitfalls in the docstrings.
Example for ShapedReward:
"""
Shaped reward: r(s,a,s') = r_base(s,a,s') + gamma * phi(s') - phi(s)
Pitfalls:
- The potential function phi should be bounded to ensure that the optimal policy is unchanged.
- If the potential function is not bounded, the shaped reward might lead to a different optimal policy.
- Over-shaping: if the potential function is too strong, the agent might ignore the base reward.
Validation tests:
- potential_bounded: checks if the potential function (over visited states) is bounded.
"""
We can also have a test for the potential function's gradient? Not really.
Now, note: the user might not use our templates. They might write their own reward function. Then the validator should still work as long as the reward function has the signature (state, action, next_state, done). But the tests that are specific to ShapedReward (like potential_bounded) will not work.
So we can make the validator only run tests that are applicable? Or we can have a test that checks the type of the reward function.
Alternatively, we can have a way for the user to specify which tests to run.
We did that by passing test_names.
Now, we can write the library.
Let's create the following structure:
reward_designer/
init.py
templates.py
shaping.py (optional, we can put ShapedReward in templates)
reward_validation/
init.py
validator.py
tests.py (we can put the test functions here and the validator just calls them)
But for simplicity, we can put everything in one file? We are designing a library, so we want modularity.
Alternatively, we can have:
from reward_designer import SparseReward, DenseReward, ShapedReward, CompositeReward
from reward_validation import RewardValidator
And then the validator has the tests.
We'll write:
reward_designer/templates.py:
class Reward:
...
class SparseReward(Reward):
...
class DenseReward(Reward):
...
class ShapedReward(Reward):
...
class CompositeReward(Reward):
...
reward_validation/validator.py:
class RewardValidator:
...
And then in reward_validation/init.py, we expose RewardValidator.
We can also put the tests in separate file, but for now let's keep in validator.
However, note: the test functions are methods of RewardValidator.
Alternatively, we can have standalone test functions and the validator runs them.
But then the validator needs to have the trajectories. So we can have:
def test_reward_hacking(validator, reward_threshold=0.9):
... # uses validator.trajectories and validator.goal_checker
Then the validator can run:
results = {}
for test_name in test_names:
test_func = getattr(module, test_name)
results[test_name] = test_func(self, **kwargs)
But then we have to pass the validator to the test function.
Alternatively, we can have a registry of tests.
Let's do:
# in reward_validation/tests.py
def reward_hacking_test(validator, reward_threshold=0.9):
...
def non_markovian_test(validator, tolerance=1e-6):
...
# and so on.
TEST_REGISTRY = {
'reward_hacking': reward_hacking_test,
'non_markovian': non_markovian_test,
...
}
Then in validator:
from .tests import TEST_REGISTRY
class RewardValidator:
...
def run_tests(self, test_names, num_episodes=10, policy=None, **kwargs):
if not self.trajectories:
self.collect_trajectories(num_episodes, policy)
results = {}
for test_name in test_names:
if test_name in TEST_REGISTRY:
test_func = TEST_REGISTRY[test_name]
results[test_name] = test_func(self, **kwargs.get(test_name, {}))
else:
results[test_name] = "Unknown test."
return results
This way, the user can also register their own tests.
Now, let's code accordingly.
However, note: the test functions might have different parameters. We are passing **kwargs.get(test_name, {}) so that for each test we can have a dictionary of parameters.
Example:
results = validator.run_tests(['reward_hacking'], reward_hacking={'reward_threshold': 0.8})
Then in the run_tests:
for test_name in test_names:
test_kwargs = kwargs.get(test_name, {})
test_func = TEST_REGISTRY[test_name]
results[test_name] = test_func(self, **test_kwargs)
But note: the test function might have default parameters. We are passing all the kwargs for that test.
Now, let's write the code accordingly.
We'll create:
reward_designer/templates.py
reward_validation/tests.py
reward_validation/validator.py
And then init.py files to expose the classes.
However, note: the test functions need to access the trajectories and goal_checker from the validator.
So the test functions will be called with the validator as the first argument.
Example test function:
def reward_hacking_test(validator, reward_threshold=0.9):
if validator.goal_checker is None:
return "Goal checker not set."
hacking_cases = []
for traj in validator.trajectories:
for (s, a, s_next, r, done) in traj:
if r > reward_threshold and not validator.goal_checker(s_next):
hacking_cases.append((s, a, s_next, r))
return hacking_cases
This is a bit ugly because the test function is using the internal state of the validator.
Alternatively, we can have the validator pass the necessary data to the test function.
But then we would have to change the signature of the test functions.
We can have:
def reward_hacking_test(trajectories, goal_checker, reward_threshold=0.9):
...
And then in run_tests:
test_func(self.trajectories, self.goal_checker, **test_kwargs)
Then the test functions are independent of the validator.
Let's do that.
So:
# in tests.py
def reward_hacking_test(trajectories, goal_checker, reward_threshold=0.9):
...
TEST_REGISTRY = {
'reward_hacking': reward_hacking_test,
...
}
Then in validator:
def run_tests(self, test_names, num_episodes=10, policy=None, **kwargs):
if not self.trajectories:
self.collect_trajectories(num_episodes, policy)
results = {}
for test_name in test_names:
if test_name in TEST_REGISTRY:
test_func = TEST_REGISTRY[test_name]
test_kwargs = kwargs.get(test_name, {})
results[test_name] = test_func(self.trajectories, self.goal_checker, **test_kwargs)
else:
results[test_name] = "Unknown test."
return results
But note: some tests might need other things (like the reward function itself? or the environment?).
We are passing trajectories and goal_checker. For non_markovian, we don't need goal_checker. For potential_bounded, we need the reward function to be a ShapedReward and then we need the potential function. So we might need to pass the reward function? Or we can pass the validator? That's circular.
Alternatively, we can pass the validator to the test function? But then the test function can access anything from the validator.
Let's stick to passing the necessary arguments.
For test_potential_bounded, we need the reward function and the trajectories? We can get the potential function from the reward function if it's a ShapedReward.
So:
def potential_bounded_test(trajectories, reward_function):
if not isinstance(reward_function, ShapedReward):
return "Not a shaped reward."
potential_fn = reward_function.potential_fn
... # compute potentials from trajectories
But then we have to pass the reward_function. So in run_tests:
results[test_name] = test_func(self.trajectories, reward_function=self.reward_function, **test_kwargs)
But we don't want to change the signature of every test to include reward_function? Some tests don't need it.
Alternatively, we can pass a context object that has:
trajectories, goal_checker, reward_function, env, etc.
Then the test function can take that context and then use what it needs.
Let's define:
class TestContext:
def __init__(self, trajectories, goal_checker, reward_function, env):
self.trajectories = trajectories
self.goal_checker = goal_checker
self.reward_function = reward_function
self.env = env
Then the test functions take a TestContext and then kwargs.
Example:
def reward_hacking_test(context, reward_threshold=0.9):
if context.goal_checker is None:
return "Goal checker not set."
...
Then in run_tests:
context = TestContext(self.trajectories, self.goal_checker, self.reward_function, self.env)
results[test_name] = test_func(context, **test_kwargs)
This is more extensible.
Let's do that.
Now, we can write the tests accordingly.
We'll create:
reward_validation/context.py:
class TestContext:
def __init__(self, trajectories, goal_checker, reward_function, env):
self.trajectories = trajectories
self.goal_checker = goal_checker
self.reward_function = reward_function
self.env = env
Then in validator:
from .context import TestContext
from .tests import TEST_REGISTRY
class RewardValidator:
...
def run_tests(self, test_names, num_episodes=10, policy=None, **kwargs):
if not self.trajectories:
self.collect_trajectories(num_episodes, policy)
context = TestContext(self.trajectories, self.goal_checker, self.reward_function, self.env)
results = {}
for test_name in test_names:
if test_name in TEST_REGISTRY:
test_func = TEST_REGISTRY[test_name]
test_kwargs = kwargs.get(test_name, {})
results[test_name] = test_func(context, **test_kwargs)
else:
results[test_name] = "Unknown test."
return results
Now, we can write the tests in tests.py.
Let's write:
tests.py:
from reward_designer.templates import ShapedReward
def reward_hacking_test(context, reward_threshold=0.9):
if context.goal_checker is None:
return "Goal checker not set."
hacking_cases = []
for traj in context.trajectories:
for (s, a, s_next, r, done) in traj:
if r > reward_threshold and not context.goal_checker(s_next):
hacking_cases.append((s, a, s_next, r))
return hacking_cases
def non_markovian_test(context, tolerance=1e-6):
rewards_by_transition = {}
for traj in context.trajectories:
for (s, a, s_next, r, done) in traj:
key = (tuple(s.tolist()), a, tuple(s_next.tolist()))
if key not in rewards_by_transition:
rewards_by_transition[key] = []
rewards_by_transition[key].append(r)
non_markovian_cases = []
for key, rewards in rewards_by_transition.items():
if len(rewards) > 1:
max_diff = max(rewards) - min(rewards)
if max_diff > tolerance:
non_markovian_cases.append((key, rewards))
return non_markovian_cases
def potential_bounded_test(context):
if not isinstance(context.reward_function, ShapedReward):
return "Not a shaped reward."
potential_fn = context.reward_function.potential_fn
all_states = []
for traj in context.trajectories:
for (s, a, s_next, r, done) in traj:
all_states.append(s)
all_states.append(s_next)
potentials = [potential_fn(s) for s in all_states]
min_p = min(potentials)
max_p = max(potentials)
return {"min_potential": min_p, "max_potential": max_p, "range": max_p - min_p}
def reward_scale_test(context, low_threshold=-10, high_threshold=10):
all_rewards = []
for traj in context.trajectories:
for (_, _, _, r, _) in traj:
all_rewards.append(r)
mean = np.mean(all_rewards)
std = np.std(all_rewards)
if std < 1e-6:
return "Very low variance in rewards. Consider rescaling."
if mean < low_threshold or mean > high_threshold:
return f"Mean reward {mean} is outside the typical range [{low_threshold}, {high_threshold}]."
return {"mean": mean, "std": std, "message": "OK"}
def reward_sparsity_test(context, threshold=0.1):
total_steps = 0
non_zero_steps = 0
for traj in context.trajectories:
for (_, _, _, r, _) in traj:
total_steps += 1
if abs(r) > 1e-6:
non_zero_steps += 1
fraction = non_zero_steps / total_steps if total_steps > 0 else 0
if fraction < threshold:
return f"Reward is sparse: only {fraction*100:.2f}% of steps have non-zero reward."
else:
return f"Reward is dense: {fraction*100:.2f}% of steps have non-zero reward."
def constant_reward_test(context):
all_rewards = []
for traj in context.trajectories:
for (_, _, _, r, _) in traj:
all_rewards.append(r)
if len(set(all_rewards)) == 1:
return f"Constant reward: {all_rewards[0]}"
else:
return "Not constant."
TEST_REGISTRY = {
'reward_hacking': reward_hacking_test,
'non_markovian': non_markovian_test,
'potential_bounded': potential_bounded_test,
'reward_scale': reward_scale_test,
'reward_sparsity': reward_sparsity_test,
'constant_reward': constant_reward_test,
}
Note: we assume states are arrays and we convert to tuples for hashing. This might not work for all state types (e.g., if state is a dictionary). We can try to convert to a hashable representation.
Alternatively, we can use a hash function? But then we might have collisions.
We can use:
key = (s, a, s_next)
but s and s_next are arrays, which are not hashable.
We can convert to tuple if they are arrays. But if they are dictionaries, we can convert to frozenset of items? Or we can use a function that converts to a hashable representation.
We can do:
def to_hashable(obj):
if isinstance(obj, np.ndarray):
return tuple(obj.tolist())
elif isinstance(obj, dict):
return frozenset(obj.items())
else:
return obj # if it's already hashable
key = (to_hashable(s), a, to_hashable(s_next))
But note: the action might also be non-hashable? We assume action is hashable (like an integer or tuple).
We can write a helper function.
Alternatively, we can use pickle to hash? But that's heavy.
Let's write a helper:
def make_hashable(o):
if isinstance(o, (tuple, list)):
return tuple(make_hashable(e) for e in o)
elif isinstance(o, dict):
return frozenset((k, make_hashable(v)) for k, v in o.items())
elif isinstance(o, np.ndarray):
return tuple(o.tolist())
else:
return o
But note: we might have nested structures. We can do recursion.
We'll do:
def make_hashable(o):
try:
hash(o)
return o
except TypeError:
if isinstance(o, (list, tuple)):
return tuple(make_hashable(e) for e in o)
elif isinstance(o, dict):
return frozenset((k, make_hashable(v)) for k, v in o.items())
elif isinstance(o, np.ndarray):
return tuple(o.tolist())
else:
raise TypeError(f"Unhashable type: {type(o)}")
Then:
key = (make_hashable(s), make_hashable(a), make_hashable(s_next))
But note: we are using a as is, and if a is an array, we need to convert too.
We can apply make_hashable to a as well.
Let's change:
key = (make_hashable(s), make_hashable(a), make_hashable(s_next))
We'll put this helper in a utils module.
However, for simplicity, we assume states and actions are hashable or can be converted to tuples.
We'll adjust the non_markovian_test to use this helper.
Now, we have a basic library.
We should also document the pitfalls in the docstrings of the reward templates and in the validator.
Let's write the docstrings.
For ShapedReward:
"""
Shaped reward: r(s,a,s') = r_base(s,a,s') + gamma * phi(s') - phi(s)
This is a potential-based reward shaping that preserves the optimal policy.
Pitfalls:
- The potential function phi must be bounded for the optimal policy to remain unchanged.
- If the potential function is unbounded, the shaped reward may lead to a different optimal policy.
- Over-shaping: if the potential function is too strong, the agent may ignore the base reward and learn a suboptimal policy for the original task.
Validation tests:
- potential_bounded: checks if the potential function (over visited states) is bounded.
"""
For SparseReward:
"""
Sparse reward: only non-zero at terminal states (or when specified).
Pitfalls:
- Sparse rewards can make exploration difficult.
- The agent may not receive enough signal to learn.
Validation tests:
- reward_sparsity: checks the fraction of non-zero rewards.
"""
For DenseReward:
"""
Dense reward: a reward function that provides feedback at every step.
Pitfalls:
- Dense rewards might lead to reward hacking if not carefully designed.
- The agent may learn to exploit the dense reward without achieving the true goal.
Validation tests:
- reward_hacking: checks for high rewards in non-goal states.
"""
We can also have a pitfall about reward scale in all.
Now, we can write the code.
Let's create the files.
However, note: the user might not use our templates. They might write their own. But we are providing templates and validation.
We are done with the design.
Let's code accordingly.
We'll create:
reward_designer/templates.py
reward_validation/context.py
reward_validation/tests.py
reward_validation/validator.py
Then init.py files.
But note: the user might not want to use the entire library. We can have:
from reward_designer import SparseReward, DenseReward, ShapedReward, CompositeReward
from reward_validation import RewardValidator
And then the validator will use the tests from tests.py.
Let's write the code.
However, note: the tests require numpy? We are using np.mean, etc. We should import numpy in tests.
We'll assume numpy is installed.
Now, let's write the code for each file.
Due to the length, I'll write the code for the main parts.
Note: This is a design for a library. In practice, we might need to adjust.
Let's start with reward_designer/templates.py:
I'll design a comprehensive reinforcement learning reward design library with templates, pitfalls documentation, and validation tests. This library will help RL practitioners design robust reward functions.
"""
rewardsafe - A reinforcement learning reward design library with validation
"""
__version__ = "0.1.0"
__author__ = "RL Safety Team"
from dataclasses import dataclass
from typing import Callable, Dict, List, Optional, Tuple, Any
import numpy as np
from enum import Enum
import warnings
# ==================== CORE TYPES ====================
class RewardType(Enum):
"""Types of reward functions"""
SPARSE = "sparse"
DENSE = "dense"
SHAPED = "shaped"
PENALTY = "penalty"
MULTI_OBJECTIVE = "multi_objective"
HUMAN_FEEDBACK = "human_feedback"
@dataclass
class RewardSpec:
"""Specification for a reward function"""
name: str
reward_type: RewardType
description: str
inputs: List[str] # e.g., ['state', 'action', 'next_state', 'done']
output_range: Tuple[float, float]
constraints: List[str] = None
dependencies: List[str] = None # other rewards it depends on
# ==================== TEMPLATE LIBRARY ====================
class RewardTemplate:
"""Base class for reward templates"""
@staticmethod
def sparse_terminal(goal_condition: Callable,
terminal_reward: float = 1.0,
step_penalty: float = 0.0) -> Callable:
"""
Sparse reward only given at terminal state when goal is achieved.
Args:
goal_condition: Function(state) -> bool indicating goal achievement
terminal_reward: Reward given when goal is achieved
step_penalty: Small penalty per step to encourage efficiency
Returns:
Reward function: (state, action, next_state, done) -> float
"""
def reward_fn(state, action, next_state, done):
if done and goal_condition(next_state):
return terminal_reward
return step_penalty
return reward_fn
@staticmethod
def distance_based(target_position: np.ndarray,
scale: float = 1.0,
normalize: bool = False) -> Callable:
"""
Dense reward based on negative distance to target.
Args:
target_position: Target coordinates
scale: Scaling factor for reward
normalize: Whether to normalize by initial distance
Returns:
Reward function based on distance
"""
def reward_fn(state, action, next_state, done):
current_pos = state[:len(target_position)]
next_pos = next_state[:len(target_position)]
current_dist = np.linalg.norm(current_pos - target_position)
next_dist = np.linalg.norm(next_pos - target_position)
reward = (current_dist - next_dist) * scale
if normalize and next_dist > 0:
reward /= max(current_dist, 1e-8)
return reward
return reward_fn
@staticmethod
def potential_shaped(base_reward: Callable,
potential_fn: Callable,
gamma: float = 0.99) -> Callable:
"""
Potential-based reward shaping (Ng et al., 1999).
Preserves optimal policy while providing shaping.
Args:
base_reward: Original reward function
potential_fn: Potential function φ(s)
gamma: Discount factor
Returns:
Shaped reward function
"""
def reward_fn(state, action, next_state, done):
base = base_reward(state, action, next_state, done)
phi_current = potential_fn(state)
phi_next = potential_fn(next_state) if not done else 0.0
return base + gamma * phi_next - phi_current
return reward_fn
@staticmethod
def multi_objective(components: Dict[str, Tuple[Callable, float]],
aggregation: str = 'weighted_sum') -> Callable:
"""
Multi-objective reward combining multiple objectives.
Args:
components: Dict of {name: (reward_fn, weight)}
aggregation: 'weighted_sum', 'min', or 'prod'
Returns:
Combined reward function
"""
def reward_fn(state, action, next_state, done):
rewards = {}
for name, (fn, weight) in components.items():
rewards[name] = fn(state, action, next_state, done) * weight
if aggregation == 'weighted_sum':
return sum(rewards.values())
elif aggregation == 'min':
return min(rewards.values())
elif aggregation == 'prod':
prod = 1.0
for r in rewards.values():
prod *= (1.0 + r) # Add 1 to handle negative rewards
return prod - 1.0
else:
raise ValueError(f"Unknown aggregation: {aggregation}")
return reward_fn
@staticmethod
def safety_constrained(base_reward: Callable,
safety_constraint: Callable,
penalty_scale: float = 10.0) -> Callable:
"""
Base reward with safety constraint violations penalized.
Args:
base_reward: Original reward function
safety_constraint: Function(state) -> float (negative = violation)
penalty_scale: How much to penalize constraint violations
Returns:
Constrained reward function
"""
def reward_fn(state, action, next_state, done):
base = base_reward(state, action, next_state, done)
constraint_value = safety_constraint(next_state)
penalty = min(0, constraint_value) * penalty_scale # Only penalize violations
return base + penalty
return reward_fn
@staticmethod
def curriculum_progressive(initial_reward: Callable,
final_reward: Callable,
schedule: Callable[[int], float]) -> Callable:
"""
Curriculum learning with gradually transitioning rewards.
Args:
initial_reward: Early training reward
final_reward: Target reward
schedule: Function(timestep) -> mixing coefficient [0, 1]
Returns:
Curriculum reward function
"""
def reward_fn(state, action, next_state, done, timestep=0):
alpha = schedule(timestep)
r_initial = initial_reward(state, action, next_state, done)
r_final = final_reward(state, action, next_state, done)
return (1 - alpha) * r_initial + alpha * r_final
return reward_fn
# ==================== COMMON PITFALLS ====================
class RewardPitfalls:
"""Documentation of common reward design pitfalls"""
PITFALLS = {
'reward_hacking': {
'description': 'Agent finds loopholes to maximize reward without achieving intended goal',
'examples': [
'Game score hacking (e.g., circling in Mario to farm points)',
'Robot moving object to sensor instead of destination',
'Agent clicking random buttons to maximize YouTube watch time'
],
'prevention': [
'Use multiple reward signals',
'Add constraint rewards (safety, efficiency)',
'Validate with out-of-distribution scenarios',
'Use human feedback or demonstrations'
]
},
'side_effects': {
'description': 'Agent causes unintended negative consequences while maximizing reward',
'examples': [
'Cleaning robot pushing vase out of way',
'Agent breaking environment to avoid negative reward',
'Resource depletion for short-term gain'
],
'prevention': [
'Include side-effect penalties',
'Use relative reachability or impact measures',
'Add human-in-the-loop oversight',
'Define safe states explicitly'
]
},
'overlooked_constraints': {
'description': 'Important constraints not captured in reward function',
'examples': [
'Robot damaging furniture while navigating',
'Agent learning unsafe behaviors not explicitly penalized',
'Energy/calorie constraints ignored'
],
'prevention': [
'Systematically list all constraints',
'Use specification languages (e.g., LTL, STL)',
'Conduct pre-deployment safety analysis',
'Include whitelisting/penalties for undesired states'
]
},
'sparse_rewards': {
'description': 'Too few reward signals causing exploration problems',
'examples': [
'Only terminal reward in complex tasks',
'No intermediate feedback for long-horizon tasks'
],
'prevention': [
'Use reward shaping carefully',
'Implement curriculum learning',
'Use demonstrations or imitation learning',
'Add auxiliary rewards (e.g., curiosity)'
]
},
'scale_mismatch': {
'description': 'Inappropriate reward magnitude causing learning issues',
'examples': [
'Rewards too small: gradient vanishes',
'Rewards too large: value explosion',
'Multiple objectives with vastly different scales'
],
'prevention': [
'Normalize rewards to consistent range (e.g., [-1, 1])',
'Use reward clipping',
'Weight objectives appropriately',
'Monitor value function statistics'
]
},
'temporal_credit_assignment': {
'description': 'Difficulty assigning credit for delayed rewards',
'examples': [
'Agent cannot learn which actions led to distant reward',
'Myopic behavior due to discounting'
],
'prevention': [
'Use eligibility traces',
'Reduce discount factor (carefully)',
'Provide intermediate rewards',
'Use hierarchical RL'
]
}
}
@classmethod
def get_pitfall_info(cls, pitfall_name: str) -> Dict:
"""Get detailed information about a specific pitfall"""
return cls.PITFALLS.get(pitfall_name, {"description": "Unknown pitfall"})
@classmethod
def list_pitfalls(cls) -> List[str]:
"""List all documented pitfalls"""
return list(cls.PITFALLS.keys())
# ==================== VALIDATION FRAMEWORK ====================
class RewardValidator:
"""Validate reward functions for common issues"""
def __init__(self,
reward_fn: Callable,
spec: Optional[RewardSpec] = None,
environment_model: Optional[Callable] = None):
"""
Initialize validator.
Args:
reward_fn: Reward function to validate
spec: Optional specification for the reward
environment_model: Optional model(state, action) -> next_state for simulation
"""
self.reward_fn = reward_fn
self.spec = spec
self.env_model = environment_model
self.test_results = {}
def validate_all(self,
test_horizon: int = 100,
num_trajectories: int = 100) -> Dict[str, Any]:
"""Run all validation tests"""
tests = [
('range_check', self._test_reward_range),
('sparsity_check', self._test_reward_sparsity),
('markov_check', self._test_markov_property),
('monotonicity_check', self._test_monotonicity),
('scale_consistency', self._test_scale_consistency),
('policy_sensitivity', self._test_policy_sensitivity),
]
results = {}
for test_name, test_fn in tests:
try:
results[test_name] = test_fn(test_horizon, num_trajectories)
except Exception as e:
results[test_name] = {"status": "error", "message": str(e)}
self.test_results = results
return results
def _test_reward_range(self, horizon: int, num_trajectories: int) -> Dict:
"""Test if rewards stay within expected range"""
if self.spec and self.spec.output_range:
expected_min, expected_max = self.spec.output_range
else:
expected_min, expected_max = -10.0, 10.0 # defaults
# Generate random trajectories
rewards = []
for _ in range(num_trajectories):
state = np.random.randn(10) # Mock state
for t in range(horizon):
action = np.random.randint(0, 3)
next_state = state + np.random.randn(10) * 0.1 if not self.env_model else self.env_model(state, action)
done = (t == horizon - 1)
reward = self.reward_fn(state, action, next_state, done)
rewards.append(reward)
state = next_state
if done:
break
actual_min, actual_max = min(rewards), max(rewards)
violations = []
if actual_min < expected_min:
violations.append(f"Min reward {actual_min:.3f} < {expected_min}")
if actual_max > expected_max:
violations.append(f"Max reward {actual_max:.3f} > {expected_max}")
return {
"status": "pass" if not violations else "fail",
"expected_range": (expected_min, expected_max),
"actual_range": (actual_min, actual_max),
"violations": violations,
"statistics": {
"mean": float(np.mean(rewards)),
"std": float(np.std(rewards)),
"median": float(np.median(rewards))
}
}
def _test_reward_sparsity(self, horizon: int, num_trajectories: int) -> Dict:
"""Check if reward is too sparse"""
non_zero_count = 0
total_steps = 0
for _ in range(num_trajectories):
state = np.random.randn(10)
for t in range(horizon):
action = np.random.randint(0, 3)
next_state = state + np.random.randn(10) * 0.1 if not self.env_model else self.env_model(state, action)
done = (t == horizon - 1)
reward = self.reward_fn(state, action, next_state, done)
if abs(reward) > 1e-6:
non_zero_count += 1
total_steps += 1
state = next_state
if done:
break
sparsity_ratio = 1.0 - (non_zero_count / total_steps) if total_steps > 0 else 1.0
threshold = 0.95 # More than 95% zeros is concerning
return {
"status": "pass" if sparsity_ratio < threshold else "warn",
"sparsity_ratio": float(sparsity_ratio),
"non_zero_steps": non_zero_count,
"total_steps": total_steps,
"message": f"Reward is {sparsity_ratio*100:.1f}% sparse" if sparsity_ratio >= threshold else "Acceptable density"
}
def _test_markov_property(self, horizon: int, num_trajectories: int) -> Dict:
"""Test Markov property: reward depends only on (s,a,s')"""
transitions = {}
for _ in range(num_trajectories):
state = np.random.randn(10)
for t in range(horizon):
action = np.random.randint(0, 3)
next_state = state + np.random.randn(10) * 0.1 if not self.env_model else self.env_model(state, action)
done = (t == horizon - 1)
reward = self.reward_fn(state, action, next_state, done)
# Create hashable key
key = (tuple(np.round(state, 4)), action, tuple(np.round(next_state, 4)), done)
if key not in transitions:
transitions[key] = []
transitions[key].append(reward)
state = next_state
if done:
break
# Check consistency
violations = []
for key, rewards in transitions.items():
if len(rewards) > 1:
if not np.allclose(rewards, rewards[0], atol=1e-5):
violations.append({
"transition": key,
"rewards": rewards,
"std": float(np.std(rewards))
})
return {
"status": "pass" if not violations else "fail",
"tested_transitions": len(transitions),
"violations": violations[:10], # Limit output
"message": f"Found {len(violations)} non-Markovian transitions"
}
def _test_monotonicity(self, horizon: int, num_trajectories: int) -> Dict:
"""Test if reward monotonically improves towards goal (if applicable)"""
# This is domain-specific; here we test a simple case
# For distance-based rewards, we expect reward to increase as distance decreases
if self.spec and 'distance' not in self.spec.name.lower():
return {"status": "skip", "message": "Monotonicity test only applicable for distance-based rewards"}
violations = 0
total = 0
for _ in range(num_trajectories):
state = np.random.randn(10)
for t in range(min(horizon, 20)): # Short horizon for test
action = np.random.randint(0, 3)
next_state = state + np.random.randn(10) * 0.1
done = False
reward = self.reward_fn(state, action, next_state, done)
# Mock distance calculation
dist_before = np.linalg.norm(state)
dist_after = np.linalg.norm(next_state)
# For distance-based rewards, we expect:
# if distance decreases, reward should be positive
# if distance increases, reward should be negative
if dist_after < dist_before and reward < 0:
violations += 1
elif dist_after > dist_before and reward > 0:
violations += 1
total += 1
state = next_state
violation_rate = violations / total if total > 0 else 0
return {
"status": "pass" if violation_rate < 0.1 else "warn",
"violation_rate": float(violation_rate),
"violations": violations,
"total_checks": total
}
def _test_scale_consistency(self, horizon: int, num_trajectories: int) -> Dict:
"""Test if reward scale is consistent across different state magnitudes"""
scales = [0.1, 1.0, 10.0]
reward_stats = {}
for scale in scales:
rewards = []
for _ in range(10): # Fewer trajectories for speed
state = np.random.randn(10) * scale
for t in range(min(horizon, 10)):
action = np.random.randint(0, 3)
next_state = state + np.random.randn(10) * 0.1 * scale
done = (t == 9)
reward = self.reward_fn(state, action, next_state, done)
rewards.append(abs(reward))
state = next_state
if done:
break
reward_stats[scale] = {
"mean": float(np.mean(rewards)),
"std": float(np.std(rewards))
}
# Check if rewards scale approximately linearly with state magnitude
scale_ratios = []
for i in range(len(scales)-1):
ratio = reward_stats[scales[i+1]]["mean"] / max(reward_stats[scales[i]]["mean"], 1e-8)
expected_ratio = scales[i+1] / scales[i]
scale_ratios.append(ratio / expected_ratio)
consistent = all(0.5 < r < 2.0 for r in scale_ratios)
return {
"status": "pass" if consistent else "warn",
"scale_ratios": scale_ratios,
"reward_statistics": reward_stats,
"message": "Reward scale consistent across state magnitudes" if consistent else
"Reward scale varies significantly with state magnitude"
}
def _test_policy_sensitivity(self, horizon: int, num_trajectories: int) -> Dict:
"""Test how sensitive reward is to policy changes"""
# Compare random vs. slightly optimized policy
if not self.env_model:
return {"status": "skip", "message": "Requires environment model"}
random_rewards = []
greedy_rewards = []
for _ in range(num_trajectories):
state = np.random.randn(10)
random_trajectory_reward = 0
greedy_trajectory_reward = 0
for t in range(horizon):
# Random action
action_random = np.random.randint(0, 3)
next_state_random = self.env_model(state, action_random)
done = (t == horizon - 1)
reward_random = self.reward_fn(state, action_random, next_state_random, done)
random_trajectory_reward += reward_random
# Greedy action (if we could compute it)
# For test, use a slightly better random action (biased toward one action)
action_greedy = (action_random + 1) % 3 # Simple "better" action
next_state_greedy = self.env_model(state, action_greedy)
reward_greedy = self.reward_fn(state, action_greedy, next_state_greedy, done)
greedy_trajectory_reward += reward_greedy
state = next_state_random # Continue from random policy's state
if done:
break
random_rewards.append(random_trajectory_reward)
greedy_rewards.append(greedy_trajectory_reward)
mean_random = np.mean(random_rewards)
mean_greedy = np.mean(greedy_rewards)
improvement = (mean_greedy - mean_random) / max(abs(mean_random), 1e-8)
# If improvement is too small, reward might not provide enough signal
if abs(improvement) < 0.1:
status = "warn"
message = "Small difference between policies; reward may not provide sufficient gradient"
else:
status = "pass"
message = f"Clear signal: {improvement:.1%} improvement"
return {
"status": status,
"mean_random": float(mean_random),
"mean_greedy": float(mean_greedy),
"improvement": float(improvement),
"message": message
}
# ==================== SAFETY DECORATORS ====================
class RewardSafeguards:
"""Decorators and wrappers for safe reward computation"""
@staticmethod
def clip_reward(reward_fn: Callable,
min_val: float = -10.0,
max_val: float = 10.0) -> Callable:
"""Clip rewards to prevent extreme values"""
def safe_fn(state, action, next_state, done):
reward = reward_fn(state, action, next_state, done)
return np.clip(reward, min_val, max_val)
return safe_fn
@staticmethod
def anomaly_detector(reward_fn: Callable,
threshold: float = 5.0,
window_size: int = 100) -> Callable:
"""Detect and log anomalous reward values"""
recent_rewards = []
def safe_fn(state, action, next_state, done):
reward = reward_fn(state, action, next_state, done)
recent_rewards.append(reward)
if len(recent_rewards) > window_size:
recent_rewards.pop(0)
if len(recent_rewards) >= window_size // 2:
mean = np.mean(recent_rewards)
std = np.std(recent_rewards)
if std > 0 and abs(reward - mean) > threshold * std:
warnings.warn(f"Anomalous reward detected: {reward:.3f} (mean: {mean:.3f}, std: {std:.3f})")
return reward
return safe_fn
@staticmethod
def rate_limiter(reward_fn: Callable,
max_per_second: float = 100.0,
min_interval: float = 0.01) -> Callable:
"""Limit rate of reward computation (useful for expensive rewards)"""
import time
last_call = 0
def safe_fn(state, action, next_state, done):
nonlocal last_call
current_time = time.time()
elapsed = current_time - last_call
if elapsed < min_interval:
time.sleep(min_interval - elapsed)
reward = reward_fn(state, action, next_state, done)
last_call = time.time()
return reward
return safe_fn
# ==================== UTILITY FUNCTIONS ====================
def compose_rewards(reward_fns: List[Callable],
weights: Optional[List[float]] = None) -> Callable:
"""Compose multiple reward functions with optional weighting"""
if weights is None:
weights = [1.0] * len(reward_fns)
assert len(reward_fns) == len(weights), "Must have same number of rewards and weights"
def composed_fn(state, action, next_state, done):
total = 0.0
for fn, w in zip(reward_fns, weights):
total += w * fn(state, action, next_state, done)
return total
return composed_fn
def validate_specification(spec: RewardSpec) -> List[str]:
"""Validate a reward specification against common issues"""
issues = []
if spec.reward_type == RewardType.SPARSE:
if 'terminal' not in spec.name.lower() and 'sparse' not in spec.name.lower():
issues.append("Sparse reward should indicate terminal or sparse nature in name")
if spec.output_range:
min_val, max_val = spec.output_range
if min_val >= max_val:
issues.append("Invalid output range: min >= max")
if abs(min_val) > 100 or abs(max_val) > 100:
issues.append("Extreme reward values detected; consider normalization")
if not spec.inputs:
issues.append("No inputs specified for reward function")
required_inputs = {'state', 'action', 'next_state', 'done'}
if not all(inp in spec.inputs for inp in required_inputs):
issues.append(f"Missing required inputs: {required_inputs - set(spec.inputs)}")
return issues
# ==================== EXAMPLE USAGE ====================
def example_usage():
"""Demonstrate library usage"""
# 1. Create a reward using template
def goal_condition(state):
return np.linalg.norm(state[:2]) < 0.1
sparse_reward = RewardTemplate.sparse_terminal(
goal_condition=goal_condition,
terminal_reward=10.0,
step_penalty=-0.01
)
# 2. Add shaping
def potential_fn(state):
return -np.linalg.norm(state[:2])
shaped_reward = RewardTemplate.potential_shaped(
base_reward=sparse_reward,
potential_fn=potential_fn,
gamma=0.99
)
# 3. Wrap with safety
safe_reward = RewardSafeguards.clip_reward(shaped_reward, -1.0, 1.0)
monitored_reward = RewardSafeguards.anomaly_detector(safe_reward)
# 4. Create specification
spec = RewardSpec(
name="shaped_navigation",
reward_type=RewardType.SHAPED,
description="Distance-shaped navigation with terminal reward",
inputs=['state', 'action', 'next_state', 'done'],
output_range=(-1.0, 1.0),
constraints=["No negative distances", "Terminal only at goal"]
)
# 5. Validate
validator = RewardValidator(monitored_reward, spec)
results = validator.validate_all(num_trajectories=50)
print("Validation Results:")
for test, result in results.items():
status = result.get('status', 'unknown')
print(f" {test}: {status}")
if 'message' in result:
print(f" {result['message']}")
# 6. Check specification
spec_issues = validate_specification(spec)
if spec_issues:
print("\nSpecification Issues:")
for issue in spec_issues:
print(f" - {issue}")
# 7. Document pitfalls
print("\nCommon Pitfalls to Consider:")
for pitfall in RewardPitfalls.list_pitfalls():
info = RewardPitfalls.get_pitfall_info(pitfall)
print(f"\n{pitfall}: {info['description']}")
print(" Examples:", info['examples'][0])
print(" Prevention:", info['prevention'][0])
if __name__ == "__main__":
example_usage()
Key Features:
1. Reward Templates
- Sparse Terminal: Only rewards at goal achievement
- Distance-Based: Dense shaping based on proximity to target
- Potential Shaping: Policy-preserving shaping (Ng et al.)
- Multi-Objective: Combine multiple objectives with different aggregation strategies
- Safety-Constrained: Base reward + constraint penalties
- Curriculum: Gradually transition between reward functions
2. Pitfalls Documentation
- Reward hacking (specification gaming)
- Side effects and safety violations
- Overlooked constraints
- Sparse reward challenges
- Scale mismatches
- Temporal credit assignment issues
3. Validation Tests
- Range Check: Verify rewards stay within expected bounds
- Sparsity Check: Detect overly sparse rewards
- Markov Property: Ensure rewards depend only on (s,a,s')
- Monotonicity: Check consistent improvement signals
- Scale Consistency: Verify reward scaling across state magnitudes
- Policy Sensitivity: Ensure reward provides learning signal
4. Safety Decorators
- Reward clipping to prevent extremes
- Anomaly detection for unusual values
- Rate limiting for expensive computations
5. Specification System
- Structured
RewardSpec dataclass
- Automatic validation of specifications
- Clear documentation of inputs/outputs/constraints
Usage Patterns:
# Basic usage
reward = RewardTemplate.distance_based(
target_position=np.array([1.0, 0.5]),
scale=1.0,
normalize=True
)
# Composition
combined = compose_rewards(
[navigation_reward, safety_reward],
weights=[0.7, 0.3]
)
# With safeguards
safe_reward = RewardSafeguards.clip_reward(combined, -1.0, 1.0)
safe_reward = RewardSafeguards.anomaly_detector(safe_reward)
# Full validation pipeline
validator = RewardValidator(safe_reward, spec)
results = validator.validate_all()
Best Practices Documented:
- Always validate: Run the test suite before deployment
- Document assumptions: Use
RewardSpec to capture design decisions
- Monitor in production: Use anomaly detector in deployment
- Test edge cases: Include out-of-distribution scenarios in validation
- Iterate: Use validation results to refine reward design
- Consider safety: Add constraint rewards proactively
- Check Markov property: Ensure no history dependence
- Verify scale: Consistent magnitude across different regimes
This library provides both the tools to build reward functions and the safety nets to catch common mistakes. The validation framework helps catch issues early, while the documented pitfalls educate practitioners about subtle failure modes.