Let's change: instead of skip, we can have the guardrail modify the action to a safe one, or if it wants to reset, it can return a special flag.
Alternatively, we can have the guardrail in after_step decide to reset. So we always take the step.
Revised plan:
We always take the step (unless the environment is already done). Then after the step, the guardrail can decide to reset.
So:
action = agent.act(state)
# Pre-action guardrail: can modify the action.
action = guardrail_manager.before_action(state, action) # returns modified action
next_state, reward, done, info = env.step(action)
# Now apply post-step guardrail
next_state, reward, done, reset = guardrail_manager.after_step(state, action, next_state, reward, done, info)
# Log the step (with the possibly modified values)
logger.log_step(...)
state = next_state
episode_reward += reward
steps += 1
if reset or done:
logger.end_episode(...)
state = env.reset()
episode_reward = 0
steps = 0
But note: if reset is True, we want to end the current episode and start a new one, even if done was False.
So the condition to end an episode: reset or done.
However, if reset is True, we might want to log the episode as terminated by guardrail.
We'll adjust:
We'll have two flags: done (from environment) and reset (from guardrail). The episode ends if either is True.
But note: if reset is True, we ignore the done from the environment? Or we combine?
Let's say: if reset is True, then we treat the episode as done and reset, regardless of the environment's done.
So:
if reset:
done = True # for the purpose of ending the episode, but we already have done from environment.
Actually, we can do:
episode_ended = done or reset
Then:
if episode_ended:
logger.end_episode(...)
state = env.reset()
... reset counters
But note: the step that caused the reset might have been the one that made done=True, or the guardrail reset.
We'll log the step and then end the episode.
However, if the guardrail resets, we might want to not use the next_state from that step as the start of the next episode? But we are resetting the environment, so we get a new state.
This seems workable.
But what about the step that caused the reset? We logged it, then we reset. So the next episode starts with a new state.
This is acceptable.
Now, what about the pre-action guardrail? We only modify the action. We don't skip the step.
This design is simpler: we always take a step.
However, what if the pre-action guardrail wants to prevent the agent from taking an action and then reset without stepping? We can simulate that by having the guardrail in after_step of the previous step reset, but that's not immediate.
Alternatively, we can have the pre-action guardrail return a flag that says "reset immediately", but then we haven't taken a step. We can treat that as:
- We reset the environment and start a new episode without logging the current state and action? That would break the sequence.
Let's stick to: we always take a step. The guardrail can modify the action and then after the step, it can decide to reset.
If we need to reset without taking a step, we can have a special action that the agent takes that is then caught by the guardrail? But that's not clean.
Alternatively, we can have the pre-action guardrail modify the action to a "reset" action that the environment understands? But that couples the guardrail with the environment.
So, let's not have a pre-action reset. Only post-step reset.
Then the pre-action guardrail only modifies the action to make it safe.
This seems reasonable.
So the guardrail interface:
class Guardrail:
def before_action(self, state, action):
return action # modified action
def after_step(self, state, action, next_state, reward, done, info):
return next_state, reward, done, reset_flag
And the GuardrailManager will apply all guardrails in order for before_action and after_step.
For before_action:
for guard in guardrails:
if hasattr(guard, 'before_action'):
action = guard.before_action(state, action)
return action
For after_step:
reset = False
for guard in guardrails:
if hasattr(guard, 'after_step'):
next_state, reward, done, reset_flag = guard.after_step(state, action, next_state, reward, done, info)
if reset_flag:
reset = True
# We break? Or let all guardrails run? We might want to let all run so that all guardrails get a chance to modify.
# But if one guardrail resets, we might not care about others? Or we might want to collect all violations.
# Let's not break, but note that reset flag might be set by multiple. We'll take the last one? Or we can accumulate?
# We'll let all guardrails run and then set reset if any guardrail sets reset_flag to True.
return next_state, reward, done, reset
But note: if one guardrail resets, we might still want to let other guardrails modify the state and reward? Possibly.
However, if we reset, we are going to throw away the next_state and start a new episode. But we still want to log the step? Yes, we log the step and then reset.
So we apply all guardrails and then reset if any says so.
Now, let's design the Experiment class:
class Experiment:
def __init__(self, env, agent, logger, guardrails=None):
self.env = env
self.agent = agent
self.logger = logger
self.guardrails = guardrails or []
self.guardrail_manager = GuardrailManager(self.guardrails)
def run(self, num_episodes):
for episode in range(num_episodes):
state = self.env.reset()
episode_reward = 0
steps = 0
self.logger.start_episode(episode)
done = False
while not done:
action = self.agent.act(state)
action = self.guardrail_manager.before_action(state, action)
next_state, reward, done, info = self.env.step(action)
# Apply post-step guardrails
next_state, reward, done, reset = self.guardrail_manager.after_step(state, action, next_state, reward, done, info)
# Log the step
self.logger.log_step(state, action, reward, next_state, done, info)
state = next_state
episode_reward += reward
steps += 1
if reset or done:
# If reset, we treat as done and reset the environment.
self.logger.end_episode(episode, episode_reward, steps, reset=reset)
if reset:
# We reset the environment even if done was False, but if done was True we are resetting anyway.
state = self.env.reset()
else:
# If not reset but done, we break and then reset at the beginning of next episode.
break
# If the loop ended because of done (and not reset) then we have already logged the end_episode inside?
# Wait, we have a break when done and not reset? Actually, we break when done and not reset? No.
# Let's restructure:
# We break when done and not reset? Actually, we break when we set state = env.reset() and then continue to next episode? No.
# We are in a while loop. We break when done and not reset? But then we don't log the end_episode? We log inside the if reset or done.
# Actually, we log the episode when reset or done. Then if reset, we reset the environment and continue the loop (because we are still in the same episode? No, we reset and then we are starting a new episode? But we are in the same episode index?).
# This is confusing.
# We are running for a fixed number of episodes. Each call to run_episode should run one episode.
# So let's change: we run one episode at a time.
# We'll have a method run_episode:
# Then, in the run_episode method:
# state = env.reset()
# done = False
# reset = False
# while not (done or reset):
# ... step ...
# Then, after the loop, we log the end_episode and then return the total_reward, steps, etc.
# But note: if we reset, we break the loop and then we have to reset the environment and start a new episode? But that would be two episodes.
# Actually, if a guardrail resets, we consider that episode as terminated and we start a new one. But we are in the same call to run_episode? We want to run until we get a natural done? Or until we have run a certain number of steps?
# Let's clarify: the experiment runs for a fixed number of episodes. Each episode is from reset to done (or reset by guardrail). So if a guardrail resets, that episode ends and we start a new one (with the same episode index?).
# But then we are running more episodes than the specified number? Because a guardrail reset in the middle of an episode causes that episode to end and a new one to start, but we count that as one episode? Or two?
# We want to count the number of episodes that are started from a reset (either by environment or guardrail). So if a guardrail resets, that episode ends and we start a new one (and that new one is counted as a new episode).
# But then the experiment might run more than num_episodes episodes? Because we might have guardrail resets that cause extra episodes.
# We want to run exactly num_episodes episodes that start from a reset (either by environment or guardrail). So we count an episode when we call env.reset().
# So:
# for episode in range(num_episodes):
# state = env.reset()
# ... run until done or reset ...
# If during an episode we get a reset, we break the loop and then at the top of the for loop we reset again.
# But note: if we reset in the middle, we break the current episode and then the for loop will reset again, starting a new episode.
# So we are running exactly num_episodes episodes.
# However, the episode that was reset in the middle is counted as one episode (the one that ended by reset) and then we start a new one.
# So we need to log the end of the episode when reset or done, and then the for loop will reset and start a new episode.
# But then we are resetting twice? Once in the middle (by guardrail) and then at the beginning of the for loop? That's not right.
# We want: when reset happens, we end the current episode and then we want to start a new episode immediately (without going back to the for loop). But then we are running an extra episode? Because the for loop will also reset.
# Let's think: if we run for 10 episodes, we want 10 episodes that start with env.reset(). If an episode ends by reset (from guardrail), then that episode is over and we start a new one (by resetting the environment). But then we are still in the same for-loop iteration? We don't want to count that as two episodes.
# Actually, we want to count an episode as the sequence from one reset to the next (either by environment or guardrail). So if an episode ends by reset, then we have completed one episode and we start a new one (by resetting the environment). But then we are still in the same for-loop iteration? That would mean we are running more than one episode per for-loop iteration.
# So we need to change the for loop to:
# episode = 0
# while episode < num_episodes:
# state = env.reset()
# ... run until done or reset ...
# episode += 1
# But then if we reset in the middle, we break the current episode and then we reset and run again? That would be two episodes? We want the reset to end the current episode and then we start a new episode (with a new reset). So we do:
# while episode < num_episodes:
# state = env.reset()
# ... run until done or reset ...
# episode += 1 # because we just finished an episode (either by done or reset)
# But note: if we reset in the middle, we break the loop and then we reset again? That would be two resets in a row? We don't want that.
# Actually, when we reset in the middle, we set state = env.reset() and then continue the loop? But then we are in the same episode? We don't want to continue the same episode, we want to start a new one.
# So:
# We run the episode until done or reset. Then we log the end, and then we break out of the inner loop and the outer loop will reset and start a new episode.
# But if we reset in the middle, we break the inner loop and then the outer loop resets and starts a new episode. That means the reset in the middle ends the current episode and the outer loop starts a new one.
# However, note that when we reset in the middle, we set state = env.reset() and then we break? Actually, we break the inner loop and then the outer loop will reset again? We don't want to reset twice.
# Let's restructure:
# We'll have a method run_episode that runs one episode from reset to termination (by done or guardrail reset). Then we call that method in a loop.
# In run_episode:
# state = self.env.reset()
# done = False
# reset = False
# while not (done or reset):
# ... step ...
# # When we exit, either done or reset is True.
# self.logger.end_episode(...)
# return reset # if reset, then we had a guardrail reset.
# Then in run:
# for episode in range(num_episodes):
# reset_occurred = self.run_episode()
# # If reset_occurred, then we don't need to do anything because we already reset the environment in run_episode? Actually, no.
# But in run_episode, if reset occurs, we break and then we don't reset the environment again? We already reset in the middle? Actually, when reset occurs, we set state = self.env.reset() and then break? But then we are in a new state and the next call to run_episode will reset again? That's two resets.
# So we need to be careful.
# Alternatively, we can have run_episode not reset the environment when a guardrail reset occurs, but instead return and let the outer loop reset? But then the state we are in is the state after the reset? We don't have that because we broke the loop.
# Let's change: when a guardrail reset occurs, we break the inner loop and then the outer loop will reset the environment for the next episode. But then we lost the state after the reset? Actually, we don't need it because we are ending the episode.
# So:
# In run_episode:
# state = self.env.reset()
# done = False
# reset = False
# while not (done or reset):
# ... step ...
# if reset:
# break
# # Log the end of the episode.
# self.logger.end_episode(...)
# # If reset, we don't reset the environment here because we are going to reset in the outer loop? But then the environment state is the state after the step that caused reset? We don't want to use that for the next episode.
# Actually, when reset is True, we want to reset the environment immediately so that the next episode starts from a fresh state. But we are about to exit run_episode and then the outer loop will call run_episode again, which will reset the environment. So we don't need to reset in run_episode.
# However, note that the environment is already stepped and we are in a state that might be invalid (because of the reset). But we are going to reset at the beginning of the next run_episode.
# So we don't reset in run_episode when reset occurs. We just break and then the next run_episode will reset.
# But then the state we are in when we break is the state after the step that caused reset? We don't care because we are ending the episode.
# So:
# while not (done or reset):
# ... step ...
# if reset:
# break
# And then we log and return.
# Then the next call to run_episode will reset the environment and start fresh.
# However, what if the environment's done is True and reset is also True? We break on reset? We break on the first condition that becomes true.
# We break if done or reset. So if both are true, we break.
# This is acceptable.
# But note: if reset is True, we break and then we don't process the done? We already have done from the environment. We are breaking because reset is True, but done might be False.
# We are logging the step and then breaking. Then we log the end of the episode.
# So the episode ends because of reset, even if done was False.
# This is what we want.
# Now, what about the step that caused the reset? We logged it. That's correct.
# So the design:
# Experiment.run_episode():
# state = self.env.reset()
# total_reward = 0
# steps = 0
# self.logger.start_episode(episode_id) # we need to pass an episode id? We can have the experiment generate one.
# done = False
# reset = False
# while not (done or reset):
# action = self.agent.act(state)
# action = self.guardrail_manager.before_action(state, action)
# next_state, reward, done, info = self.env.step(action)
# next_state, reward, done, reset = self.guardrail_manager.after_step(state, action, next_state, reward, done, info)
# self.logger.log_step(state, action, reward, next_state, done, info)
# state = next_state
# total_reward += reward
# steps += 1
# self.logger.end_episode(episode_id, total_reward, steps, reset=reset)
# return reset
# Then in Experiment.run(num_episodes):
# for episode in range(num_episodes):
# self.run_episode(episode)
# This way, each call to run_episode runs one episode from reset to termination (by done or guardrail reset).
# But note: if a guardrail reset occurs, we break and then the next episode will reset the environment. So we are not resetting the environment in the middle of the episode? We are breaking and then the next episode resets.
# However, what about the state? We are in some state after the step that caused reset. We don't reset the environment until the next run_episode. That means the environment is left in a state that might be invalid? But we are going to reset at the beginning of the next episode.
# This is acceptable because we are not using that state for anything else.
Let's code accordingly.
However, note: the guardrail after_step might return a reset flag and also modify the next_state, reward, done. We are using the modified values for logging and for the next state.
But if reset is True, we break and then we don't use the next_state for the next step (because we break). So it's okay.
Now, what about the logger? We need to log the step and then the episode.
We'll design the logger to have:
start_episode(episode_id)
log_step(state, action, reward, next_state, done, info)
end_episode(episode_id, total_reward, length, reset)
We can have a simple logger that just prints, or one that writes to a file.
We'll design a base class and then a simple console logger.
Now, let's write the code structure.
We'll create:
class Guardrail:
def before_action(self, state, action):
return action
def after_step(self, state, action, next_state, reward, done, info):
return next_state, reward, done, False # default: no reset
class GuardrailManager:
def __init__(self, guardrails):
self.guardrails = guardrails
def before_action(self, state, action):
for guard in self.guardrails:
if hasattr(guard, 'before_action'):
action = guard.before_action(state, action)
return action
def after_step(self, state, action, next_state, reward, done, info):
reset = False
for guard in self.guardrails:
if hasattr(guard, 'after_step'):
next_state, reward, done, reset_flag = guard.after_step(state, action, next_state, reward, done, info)
if reset_flag:
reset = True
return next_state, reward, done, reset
class Experiment:
def __init__(self, env, agent, logger, guardrails=None):
self.env = env
self.agent = agent
self.logger = logger
self.guardrail_manager = GuardrailManager(guardrails or [])
def run_episode(self, episode_id):
state = self.env.reset()
total_reward = 0
steps = 0
self.logger.start_episode(episode_id)
done = False
reset = False
while not (done or reset):
action = self.agent.act(state)
action = self.guardrail_manager.before_action(state, action)
next_state, reward, done, info = self.env.step(action)
next_state, reward, done, reset = self.guardrail_manager.after_step(state, action, next_state, reward, done, info)
self.logger.log_step(state, action, reward, next_state, done, info)
state = next_state
total_reward += reward
steps += 1
self.logger.end_episode(episode_id, total_reward, steps, reset=reset)
return reset
def run(self, num_episodes):
for episode in range(num_episodes):
self.run_episode(episode)
This is a basic design.
However, note: the guardrail_manager.after_step might change the done flag. So we are using the modified done.
Also, note that the environment step returns done, which we then pass to guardrails. The guardrails can change it.
This is acceptable.
Now, let's consider some example guardrails:
Example 1: Clip action to environment's action space.
Example 2: Penalize negative reward? Or reset if reward is negative? (that might be too strong)
We can have:
class ClipActionGuardrail(Guardrail):
def before_action(self, state, action):
# Assuming the environment has an action_space
return self.env.action_space.clip(action) # but we don't have env in guardrail? We can pass env to guardrail.
But the guardrail doesn't have access to the environment? We can pass the environment to the guardrail in the constructor.
Alternatively, we can have the guardrail be a function that takes (state, action) and returns action, and we pass the environment to that function.
We can design the guardrail to be a class that is initialized with the environment.
But then the guardrail is tied to a specific environment.
Alternatively, we can have the guardrail not depend on the environment, but then we cannot clip without knowing the bounds.
So we can have:
class ClipActionGuardrail(Guardrail):
def __init__(self, action_space):
self.action_space = action_space
def before_action(self, state, action):
return self.action_space.clip(action)
Then when creating the experiment, we can create this guardrail with env.action_space.
But note: the environment might change? We assume fixed.
Another example: reset if the agent goes out of bounds.
class OutOfBoundsGuardrail(Guardrail):
def __init__(self, bounds):
self.bounds = bounds # bounds for state, for example.
def after_step(self, state, action, next_state, reward, done, info):
if any(next_state < self.bounds[0]) or any(next_state > self.bounds[1]):
reset = True
# Maybe also modify reward?
reward = -10 # penalty
return next_state, reward, done, reset
But note: the guardrail after_step can modify the next_state, reward, done, and reset.
Now, what about logging? We can have a simple logger that prints to console.
We'll design:
class Logger:
def start_episode(self, episode_id):
pass
def log_step(self, state, action, reward, next_state, done, info):
pass
def end_episode(self, episode_id, total_reward, steps, reset):
pass
class ConsoleLogger(Logger):
def start_episode(self, episode_id):
print(f"Starting episode {episode_id}")
def log_step(self, state, action, reward, next_state, done, info):
print(f"State: {state}, Action: {action}, Reward: {reward}, Next State: {next_state}, Done: {done}")
def end_episode(self, episode_id, total_reward, steps, reset):
print(f"Episode {episode_id} ended. Total reward: {total_reward}, Steps: {steps}, Reset by guardrail: {reset}")
Now, what about the agent? We can have a simple random agent for testing.
class Agent:
def act(self, state):
# return a random action
pass
But we need to know the action space? We can pass the environment to the agent? Or the agent can be initialized with the action space.
We'll design:
class RandomAgent(Agent):
def __init__(self, action_space):
self.action_space = action_space
def act(self, state):
return self.action_space.sample()
Now, the environment: we need a simple environment for testing.
class DummyEnvironment:
def __init__(self):
self.state = 0
self.action_space = ... # we need to define an action space and observation space.
But we want to be generic, so we can use a mock environment.
Let's create a simple environment that goes from 0 to 9 and then done.
class SimpleEnv:
def __init__(self):
self.state = 0
self.action_space = Discrete(2) # 0: stay, 1: increment
self.observation_space = Discrete(10)
def reset(self):
self.state = 0
return self.state
def step(self, action):
if action == 1:
self.state += 1
if self.state >= 9:
done = True
else:
done = False
reward = 1 if self.state == 9 else 0
return self.state, reward, done, {}
But note: we are using OpenAI Gym's Discrete. We can either depend on gym or define a simple one.
For the harness, we don't want to depend on gym. So we can define a simple action space and observation space that just have a sample method and maybe a clip method.
Alternatively, we can let the environment return the state and let the agent and guardrail handle the action space.
We can define:
class SimpleActionSpace:
def __init__(self, n):
self.n = n
def sample(self):
return random.randint(0, self.n-1)
def clip(self, action):
return max(0, min(self.n-1, action))
But then the environment doesn't have to use this.
Alternatively, we can skip the action space and observation space and just let the environment and agent agree on the format.
Since we are designing a harness, we can be flexible and not require the environment to have action_space and observation_space.
But then the ClipActionGuardrail would need to know the bounds.
We can have the guardrail take a clipping function.
Alternatively, we can have the environment provide a method to clip the action? But that's not standard.
Let's decide: we won't require the environment to have action_space. Instead, we will require the agent to produce actions that are valid for the environment. The guardrails can be tailored to the environment.
So we remove the action_space from the environment and let the user provide the necessary information to the guardrails.
For example, the ClipActionGuardrail can be constructed with a lower and upper bound.
We'll change:
class ClipActionGuardrail(Guardrail):
def __init__(self, low, high):
self.low = low
self.high = high
def before_action(self, state, action):
return np.clip(action, self.low, self.high)
But note: action might be a scalar or vector. We'll assume it's a numpy array? Or we can handle both.
We'll use numpy clip if available, else we can write a simple one.
But we don't want to depend on numpy. We can write:
def clip(value, low, high):
return max(low, min(high, value))
For vectors, we can use:
[max(low, min(high, v)) for v in value]
But we don't know if it's a scalar or list. We'll assume it's a scalar for simplicity.
Alternatively, we can use:
import numpy as np
but we don't want to force numpy.
We'll leave it to the user to implement the clipping as needed.
So the guardrail can be:
class ClipActionGuardrail(Guardrail):
def __init__(self, clip_func):
self.clip_func = clip_func
def before_action(self, state, action):
return self.clip_func(action)
Then the user can pass a function that clips the action.
Similarly, for the OutOfBoundsGuardrail, we can have:
class OutOfBoundsGuardrail(Guardrail):
def __init__(self, lower_bounds, upper_bounds, reset_on_violation=True, penalty=0):
self.lower_bounds = lower_bounds
self.upper_bounds = upper_bounds
self.reset_on_violation = reset_on_violation
self.penalty = penalty
def after_step(self, state, action, next_state, reward, done, info):
reset = False
# Check if next_state is within bounds
for i, (low, high) in enumerate(zip(self.lower_bounds, self.upper_bounds)):
if next_state[i] < low or next_state[i] > high:
reset = self.reset_on_violation
reward += self.penalty # or set to penalty? We add.
break
return next_state, reward, done, reset
But note: the next_state might be a scalar or a vector. We assume it's a vector.
We'll leave it to the user to design guardrails that are appropriate for their environment.
Now, we have a basic harness.
Let's write the code accordingly.
We'll also consider that the environment might return a tuple of (next_state, reward, done, info) or (next_state, reward, terminated, truncated, info) for newer gym.
We'll assume the environment returns (next_state, reward, done, info) and done is a boolean that indicates the episode is terminated (either by success or failure). We don't handle truncated separately.
If the environment returns (next_state, reward, terminated, truncated, info), we can adapt by:
done = terminated or truncated
But we don't want to force the environment to be a specific version.
We can make the experiment harness flexible by allowing the user to specify how to interpret the environment's output.
Alternatively, we can have a wrapper for the environment that standardizes the output.
Let's create an EnvironmentAdapter:
class EnvironmentAdapter:
def __init__(self, env):
self.env = env
def reset(self):
result = self.env.reset()
if isinstance(result, tuple):
# gym new style: (state, info)
state, _ = result
else:
state = result
return state
def step(self, action):
result = self.env.step(action)
if len(result) == 5:
next_state, reward, terminated, truncated, info = result
done = terminated or truncated
else:
next_state, reward, done, info = result
return next_state, reward, done, info
Then in the experiment, we use the adapter.
But we don't want to force the user to use gym. So we can have a base environment that we expect to have reset and step that return (state, reward, done, info). If the environment doesn't follow that, the user can wrap it.
We'll assume the environment follows the old gym interface: reset returns state, step returns (next_state, reward, done, info).
For new gym, we can have the user wrap their environment with the adapter.
Now, let's code without the adapter for simplicity, but note that we are making an assumption.
We'll write the code accordingly.
Let's put it all together.
We'll create the following files:
harness.py: contains Guardrail, GuardrailManager, Experiment, Logger, ConsoleLogger.
And then example usage.
However, note: the experiment run_episode method uses an episode_id. We can generate a unique id if not provided.
We'll leave it to the user to provide an episode_id in run_episode, or we can generate one.
We'll change the run method to:
def run(self, num_episodes, start_episode_id=0):
for episode in range(start_episode_id, start_episode_id+num_episodes):
self.run_episode(episode)
Now, let's code the base classes.
We'll also consider that the agent might need to know the state? We already pass state to act.
We are done with the design.
Let's write the code.
Note: We are not handling vectorized environments. We assume one environment.
We'll write the code accordingly.</think>
"""
Reinforcement Learning Experimentation Harness
A modular framework for safe RL experimentation with environment simulation,
comprehensive logging, and configurable guardrails.
"""
import json
import time
import uuid
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass, asdict
from typing import Any, Dict, List, Optional, Tuple, Callable
from datetime import datetime
from enum import Enum
import numpy as np
from collections import deque
# ==================== Core Interfaces ====================
class Environment(ABC):
"""Abstract environment interface."""
@abstractmethod
def reset(self) -> np.ndarray:
"""Reset environment and return initial observation."""
pass
@abstractmethod
def step(self, action: Any) -> Tuple[np.ndarray, float, bool, Dict]:
"""Take action and return (observation, reward, terminated, truncated, info)."""
pass
@abstractmethod
def render(self) -> Optional[np.ndarray]:
"""Render environment (optional)."""
pass
@property
@abstractmethod
def action_space(self) -> Any:
"""Return action space specification."""
pass
@property
@abstractmethod
def observation_space(self) -> Any:
"""Return observation space specification."""
pass
class Agent(ABC):
"""Abstract agent interface."""
@abstractmethod
def act(self, observation: np.ndarray, deterministic: bool = False) -> Any:
"""Select action given observation."""
pass
@abstractmethod
def update(self, *args, **kwargs):
"""Update agent parameters (optional for on-policy)."""
pass
def reset(self):
"""Reset agent state (for episodic agents)."""
pass
# ==================== Data Structures ====================
class GuardrailViolation(Enum):
"""Types of guardrail violations."""
ACTION_BOUNDS = "action_out_of_bounds"
REWARD_THRESHOLD = "reward_threshold_exceeded"
OBSERVATION = "observation_anomaly"
STEP_LIMIT = "step_limit_exceeded"
CUSTOM = "custom_violation"
@dataclass
class StepResult:
"""Container for single step results."""
timestamp: float
episode_id: str
step: int
observation: np.ndarray
action: Any
reward: float
next_observation: np.ndarray
terminated: bool
truncated: bool
info: Dict[str, Any]
violations: List[GuardrailViolation]
metadata: Dict[str, Any]
@dataclass
class EpisodeSummary:
"""Container for episode summary."""
episode_id: str
start_time: float
end_time: float
total_steps: int
total_reward: float
terminated: bool
truncated: bool
violations: List[GuardrailViolation]
final_observation: np.ndarray
custom_metrics: Dict[str, Any]
@dataclass
class ExperimentConfig:
"""Configuration for experiment."""
experiment_id: str
description: str
agent_config: Dict[str, Any]
env_config: Dict[str, Any]
max_episodes: int
max_steps_per_episode: int
seed: int
log_dir: str
guardrails_config: Dict[str, Any]
# ==================== Guardrail System ====================
class Guardrail(ABC):
"""Base class for safety guardrails."""
def __init__(self, config: Dict[str, Any]):
self.config = config
self.violation_count = 0
@abstractmethod
def check_action(self, action: Any, observation: np.ndarray) -> Optional[GuardrailViolation]:
"""Check if action violates guardrail. Return violation type or None."""
pass
@abstractmethod
def check_observation(self, observation: np.ndarray) -> Optional[GuardrailViolation]:
"""Check if observation violates guardrail."""
pass
@abstractmethod
def check_reward(self, reward: float) -> Optional[GuardrailViolation]:
"""Check if reward violates guardrail."""
pass
def on_violation(self, violation: GuardrailViolation, context: Dict[str, Any]):
"""Called when violation occurs."""
self.violation_count += 1
logging.warning(f"Guardrail violation: {violation.value}. Context: {context}")
class CompositeGuardrail:
"""Composite guardrail that combines multiple guardrails."""
def __init__(self, guardrails: List[Guardrail], violation_policy: str = "terminate"):
"""
Args:
guardrails: List of guardrail instances
violation_policy: "terminate", "reset", "continue", "custom"
"""
self.guardrails = guardrails
self.violation_policy = violation_policy
self.violation_history = []
def check(self,
action: Any = None,
observation: np.ndarray = None,
reward: float = None,
step: int = None,
episode_id: str = None) -> Tuple[bool, List[GuardrailViolation], Dict]:
"""
Check all guardrails. Returns (should_terminate, violations, context).
"""
violations = []
context = {
"step": step,
"episode_id": episode_id,
"timestamp": time.time()
}
# Check observation guardrails
if observation is not None:
for guardrail in self.guardrails:
violation = guardrail.check_observation(observation)
if violation:
violations.append(violation)
guardrail.on_violation(violation, context)
# Check action guardrails
if action is not None and observation is not None:
for guardrail in self.guardrails:
violation = guardrail.check_action(action, observation)
if violation:
violations.append(violation)
guardrail.on_violation(violation, context)
# Check reward guardrails
if reward is not None:
for guardrail in self.guardrails:
violation = guardrail.check_reward(reward)
if violation:
violations.append(violation)
guardrail.on_violation(violation, context)
# Record violations
if violations:
self.violation_history.append({
"timestamp": time.time(),
"episode_id": episode_id,
"step": step,
"violations": [v.value for v in violations]
})
# Determine if we should terminate
should_terminate = False
if violations:
if self.violation_policy == "terminate":
should_terminate = True
elif self.violation_policy == "reset":
should_terminate = True # Will be handled as reset by experiment
# "continue" doesn't terminate
return should_terminate, violations, context
# ==================== Built-in Guardrails ====================
class ActionBoundsGuardrail(Guardrail):
"""Ensures actions are within specified bounds."""
def __init__(self, action_space, config: Dict[str, Any]):
super().__init__(config)
self.action_space = action_space
def check_action(self, action: Any, observation: np.ndarray) -> Optional[GuardrailViolation]:
try:
if not self.action_space.contains(action):
return GuardrailViolation.ACTION_BOUNDS
except:
# If space doesn't have contains method, use naive bounds check
if hasattr(self.action_space, 'low') and hasattr(self.action_space, 'high'):
if np.any(action < self.action_space.low) or np.any(action > self.action_space.high):
return GuardrailViolation.ACTION_BOUNDS
return None
def check_observation(self, observation: np.ndarray) -> Optional[GuardrailViolation]:
return None
def check_reward(self, reward: float) -> Optional[GuardrailViolation]:
return None
class RewardThresholdGuardrail(Guardrail):
"""Checks if reward exceeds thresholds."""
def __init__(self, config: Dict[str, Any]):
"""
Config expects:
min_reward: float (optional)
max_reward: float (optional)
window_size: int (for moving average check)
"""
super().__init__(config)
self.reward_history = deque(maxlen=config.get("window_size", 100))
def check_reward(self, reward: float) -> Optional[GuardrailViolation]:
self.reward_history.append(reward)
min_r = self.config.get("min_reward")
max_r = self.config.get("max_reward")
if min_r is not None and reward < min_r:
return GuardrailViolation.REWARD_THRESHOLD
if max_r is not None and reward > max_r:
return GuardrailViolation.REWARD_THRESHOLD
# Check moving average if window is full
if len(self.reward_history) == self.reward_history.maxlen:
moving_avg = np.mean(self.reward_history)
if min_r is not None and moving_avg < min_r * 1.1: # 10% tolerance
return GuardrailViolation.REWARD_THRESHOLD
if max_r is not None and moving_avg > max_r * 0.9:
return GuardrailViolation.REWARD_THRESHOLD
return None
def check_action(self, action: Any, observation: np.ndarray) -> Optional[GuardrailViolation]:
return None
def check_observation(self, observation: np.ndarray) -> Optional[GuardrailViolation]:
return None
class StepLimitGuardrail(Guardrail):
"""Enforces maximum steps per episode."""
def __init__(self, config: Dict[str, Any]):
super().__init__(config)
self.max_steps = config["max_steps_per_episode"]
def check_step(self, step: int) -> Optional[GuardrailViolation]:
if step >= self.max_steps:
return GuardrailViolation.STEP_LIMIT
return None
# We'll call this directly from experiment, not through check methods
def should_truncate(self, step: int) -> bool:
return step >= self.max_steps
def check_action(self, action: Any, observation: np.ndarray) -> Optional[GuardrailViolation]:
return None
def check_observation(self, observation: np.ndarray) -> Optional[GuardrailViolation]:
return None
def check_reward(self, reward: float) -> Optional[GuardrailViolation]:
return None
class CustomGuardrail(Guardrail):
"""User-defined custom guardrail."""
def __init__(self, check_fn: Callable, config: Dict[str, Any]):
super().__init__(config)
self.check_fn = check_fn
def check_action(self, action: Any, observation: np.ndarray) -> Optional[GuardrailViolation]:
return self.check_fn(action, observation, "action")
def check_observation(self, observation: np.ndarray) -> Optional[GuardrailViolation]:
return self.check_fn(observation, None, "observation")
def check_reward(self, reward: float) -> Optional[GuardrailViolation]:
return self.check_fn(reward, None, "reward")
# ==================== Logging System ====================
class DataLogger(ABC):
"""Abstract logger interface."""
@abstractmethod
def log_step(self, result: StepResult):
"""Log single step."""
pass
@abstractmethod
def log_episode(self, summary: EpisodeSummary):
"""Log episode summary."""
pass
@abstractmethod
def log_experiment_config(self, config: ExperimentConfig):
"""Log experiment configuration."""
pass
@abstractmethod
def get_metrics(self) -> Dict[str, Any]:
"""Get current metrics."""
pass
class JsonLogger(DataLogger):
"""JSON file logger with rotation."""
def __init__(self, log_dir: str, experiment_id: str, max_files: int = 10):
self.log_dir = log_dir
self.experiment_id = experiment_id
self.max_files = max_files
self.step_file = f"{log_dir}/{experiment_id}_steps.jsonl"
self.episode_file = f"{log_dir}/{experiment_id}_episodes.jsonl"
self.config_file = f"{log_dir}/{experiment_id}_config.json"
# Initialize files
with open(self.step_file, 'w') as f:
f.write("")
with open(self.episode_file, 'w') as f:
f.write("")
def log_step(self, result: StepResult):
"""Append step to JSONL file."""
with open(self.step_file, 'a') as f:
# Convert numpy arrays to lists for JSON serialization
result_dict = asdict(result)
result_dict['observation'] = result.observation.tolist()
result_dict['next_observation'] = result.next_observation.tolist()
result_dict['violations'] = [v.value for v in result.violations]
f.write(json.dumps(result_dict) + "\n")
def log_episode(self, summary: EpisodeSummary):
"""Append episode to JSONL file."""
with open(self.episode_file, 'a') as f:
summary_dict = asdict(summary)
summary_dict['final_observation'] = summary.final_observation.tolist()
summary_dict['violations'] = [v.value for v in summary.violations]
f.write(json.dumps(summary_dict) + "\n")
def log_experiment_config(self, config: ExperimentConfig):
"""Write config to JSON file."""
with open(self.config_file, 'w') as f:
json.dump(asdict(config), f, indent=2, default=str)
def get_metrics(self) -> Dict[str, Any]:
"""Calculate aggregated metrics from logs."""
metrics = {
"total_episodes": 0,
"total_steps": 0,
"total_reward": 0.0,
"violations": {},
"termination_causes": {}
}
try:
with open(self.episode_file, 'r') as f:
for line in f:
episode = json.loads(line)
metrics["total_episodes"] += 1
metrics["total_steps"] += episode["total_steps"]
metrics["total_reward"] += episode["total_reward"]
# Count violations
for v in episode["violations"]:
metrics["violations"][v] = metrics["violations"].get(v, 0) + 1
# Count termination causes
if episode["terminated"]:
cause = "environment_termination"
elif episode["truncated"]:
cause = "step_limit"
else:
cause = "unknown"
metrics["termination_causes"][cause] = metrics["termination_causes"].get(cause, 0) + 1
except FileNotFoundError:
pass
return metrics
class TensorboardLogger(DataLogger):
"""TensorBoard logger wrapper."""
def __init__(self, log_dir: str, experiment_id: str):
try:
from torch.utils.tensorboard import SummaryWriter
self.writer = SummaryWriter(f"{log_dir}/tensorboard/{experiment_id}")
self.enabled = True
except ImportError:
logging.warning("TensorBoard not available. TensorboardLogger disabled.")
self.enabled = False
def log_step(self, result: StepResult):
if not self.enabled:
return
# Log step-level metrics
pass
def log_episode(self, summary: EpisodeSummary):
if not self.enabled:
return
self.writer.add_scalar("episode/total_reward", summary.total_reward, summary.episode_id)
self.writer.add_scalar("episode/steps", summary.total_steps, summary.episode_id)
self.writer.add_scalar("episode/violations", len(summary.violations), summary.episode_id)
def log_experiment_config(self, config: ExperimentConfig):
if not self.enabled:
return
# Log hyperparameters
pass
def get_metrics(self) -> Dict[str, Any]:
return {}
# ==================== Main Experiment Harness ====================
class ExperimentHarness:
"""
Main experimentation harness that coordinates all components.
"""
def __init__(self,
config: ExperimentConfig,
agent: Agent,
environment: Environment,
logger: DataLogger,
guardrails: Optional[CompositeGuardrail] = None):
"""
Initialize experiment harness.
Args:
config: Experiment configuration
agent: RL agent
environment: Environment instance
logger: Data logger instance
guardrails: Optional composite guardrail
"""
self.config = config
self.agent = agent
self.env = environment
self.logger = logger
self.guardrails = guardrails or CompositeGuardrail([])
# Statistics
self.global_step = 0
self.episode_count = 0
self.start_time = time.time()
# Set random seeds
np.random.seed(config.seed)
self._set_agent_seed(config.seed)
# Log configuration
self.logger.log_experiment_config(config)
logging.info(f"Initialized experiment {config.experiment_id}")
def _set_agent_seed(self, seed: int):
"""Set agent seed if possible."""
if hasattr(self.agent, 'seed'):
self.agent.seed(seed)
def run_episode(self,
episode_id: Optional[str] = None,
max_steps: Optional[int] = None,
render: bool = False) -> EpisodeSummary:
"""
Run single episode.
Returns:
EpisodeSummary with results
"""
if episode_id is None:
episode_id = str(uuid.uuid4())[:8]
if max_steps is None:
max_steps = self.config.max_steps_per_episode
# Reset environment and agent
observation = self.env.reset()
self.agent.reset()
episode_start_time = time.time()
total_reward = 0.0
step = 0
violations = []
step_results = []
terminated = False
truncated = False
while not (terminated or truncated):
# Get action from agent
action = self.agent.act(observation)
# Check pre-action guardrails
should_terminate, action_violations, guardrail_context = \
self.guardrails.check(action=action,
observation=observation,
step=step,
episode_id=episode_id)
if action_violations:
violations.extend(action_violations)
# Take environment step
try:
step_result = self.env.step(action)
if len(step_result) == 5:
next_observation, reward, terminated, truncated, info = step_result
else:
next_observation, reward, terminated, info = step_result
truncated = False
except Exception as e:
logging.error(f"Environment step failed: {e}")
terminated = True
reward = 0.0
next_observation = observation
info = {"error": str(e)}
# Check post-step guardrails
should_terminate_post, step_violations, _ = \
self.guardrails.check(action=action,
observation=next_observation,
reward=reward,
step=step,
episode_id=episode_id)
if step_violations:
violations.extend(step_violations)
if should_terminate_post:
terminated = True
# Check step limit
step_limit_guardrail = next(
(g for g in self.guardrails.guardrails
if isinstance(g, StepLimitGuardrail)), None
)
if step_limit_guardrail and step_limit_guardrail.should_truncate(step):
truncated = True
# Render if requested
if render:
self.env.render()
# Log step
step_result = StepResult(
timestamp=time.time(),
episode_id=episode_id,
step=step,
observation=observation.copy(),
action=action,
reward=reward,
next_observation=next_observation.copy(),
terminated=terminated,
truncated=truncated,
info=info,
violations=violations.copy(),
metadata={
"global_step": self.global_step,
"should_terminate_guardrail": should_terminate or should_terminate_post
}
)
self.logger.log_step(step_result)
step_results.append(step_result)
# Update counters
total_reward += reward
step += 1
self.global_step += 1
observation = next_observation
# Break if we've exceeded max steps
if step >= max_steps:
truncated = True
# Create episode summary
episode_summary = EpisodeSummary(
episode_id=episode_id,
start_time=episode_start_time,
end_time=time.time(),
total_steps=step,
total_reward=total_reward,
terminated=terminated,
truncated=truncated,
violations=list(set(violations)), # Unique violations
final_observation=observation.copy(),
custom_metrics=self._extract_custom_metrics(step_results)
)
self.logger.log_episode(episode_summary)
self.episode_count += 1
return episode_summary
def _extract_custom_metrics(self, step_results: List[StepResult]) -> Dict[str, Any]:
"""Extract custom metrics from step results."""
metrics = {
"mean_reward": np.mean([r.reward for r in step_results]),
"std_reward": np.std([r.reward for r in step_results]),
"min_reward": min([r.reward for r in step_results]),
"max_reward": max([r.reward for r in step_results]),
"total_violations": len([r for r in step_results if r.violations]),
"unique_violations": len(set([v for r in step_results for v in r.violations]))
}
return metrics
def run(self, num_episodes: int, render: bool = False) -> List[EpisodeSummary]:
"""
Run multiple episodes.
Returns:
List of episode summaries
"""
summaries = []
for i in range(num_episodes):
if i % 10 == 0:
logging.info(f"Starting episode {i+1}/{num_episodes}")
summary = self.run_episode(episode_id=str(i), render=render)
summaries.append(summary)
# Early termination if too many violations
if self._should_early_terminate():
logging.warning("Early termination due to excessive violations")
break
return summaries
def _should_early_terminate(self) -> bool:
"""Check if experiment should terminate early."""
metrics = self.logger.get_metrics()
violation_rate = metrics.get("violations", {}).get(GuardrailViolation.ACTION_BOUNDS.value, 0)
# Terminate if >50% of episodes have violations
if self.episode_count > 10:
if violation_rate / self.episode_count > 0.5:
return True
return False
def get_metrics(self) -> Dict[str, Any]:
"""Get experiment-wide metrics."""
metrics = self.logger.get_metrics()
metrics.update({
"global_steps": self.global_step,
"episodes_completed": self.episode_count,
"experiment_duration": time.time() - self.start_time
})
return metrics
# ==================== Factory Functions ====================
def create_experiment(config: Dict[str, Any],
agent: Agent,
environment: Environment,
logger: Optional[DataLogger] = None,
guardrails: Optional[List[Guardrail]] = None) -> ExperimentHarness:
"""
Factory function to create experiment from configuration.
Example config:
{
"experiment_id": "test_001",
"description": "Test experiment with safety guardrails",
"max_episodes": 100,
"max_steps_per_episode": 1000,
"seed": 42,
"log_dir": "./logs",
"guardrails_config": {
"action_bounds": {"enabled": true},
"reward_threshold": {"min_reward": -10, "max_reward": 10, "window_size": 50},
"step_limit": {"max_steps_per_episode": 1000},
"custom": [{"type": "custom", "module": "my_guardrails", "class": "MyGuardrail"}]
}
}
"""
# Create experiment config object
exp_config = ExperimentConfig(
experiment_id=config["experiment_id"],
description=config.get("description", ""),
agent_config=config.get("agent_config", {}),
env_config=config.get("env_config", {}),
max_episodes=config["max_episodes"],
max_steps_per_episode=config["max_steps_per_episode"],
seed=config.get("seed", 42),
log_dir=config["log_dir"],
guardrails_config=config.get("guardrails_config", {})
)
# Create logger if not provided
if logger is None:
logger = JsonLogger(
log_dir=config["log_dir"],
experiment_id=config["experiment_id"]
)
# Create guardrails from config
guardrail_instances = []
if guardrails:
guardrail_instances.extend(guardrails)
# Add guardrails from config
guardrails_config = config.get("guardrails_config", {})
if guardrails_config.get("action_bounds", {}).get("enabled", False):
guardrail_instances.append(ActionBoundsGuardrail(
environment.action_space,
guardrails_config["action_bounds"]
))
if "reward_threshold" in guardrails_config:
guardrail_instances.append(RewardThresholdGuardrail(
guardrails_config["reward_threshold"]
))
if "step_limit" in guardrails_config:
guardrail_instances.append(StepLimitGuardrail(
guardrails_config["step_limit"]
))
# Add custom guardrails
for custom_config in guardrails_config.get("custom", []):
# Dynamic import (use with caution)
module = __import__(custom_config["module"], fromlist=[custom_config["class"]])
guardrail_class = getattr(module, custom_config["class"])
guardrail_instances.append(guardrail_class(custom_config))
composite_guardrails = CompositeGuardrail(
guardrail_instances,
violation_policy=guardrails_config.get("violation_policy", "terminate")
)
return ExperimentHarness(
config=exp_config,
agent=agent,
environment=environment,
logger=logger,
guardrails=composite_guardrails
)
# ==================== Example Usage ====================
class DummyEnvironment(Environment):
"""Example environment for testing."""
def __init__(self, size=10):
self.size = size
self.state = 0
self.action_space = {"type": "discrete", "n": 3} # 0: left, 1: stay, 2: right
self.observation_space = {"type": "box", "shape": (1,), "low": 0, "high": size-1}
def reset(self) -> np.ndarray:
self.state = np.random.randint(0, self.size)
return np.array([self.state])
def step(self, action: int) -> Tuple[np.ndarray, float, bool, Dict]:
old_state = self.state
# Simple dynamics
if action == 0: # left
self.state = max(0, self.state - 1)
elif action == 2: # right
self.state = min(self.size - 1, self.state + 1)
# Reward: get closer to middle
middle = self.size // 2
reward = -abs(self.state - middle) / self.size
# Terminate if reached middle
terminated = (self.state == middle)
truncated = False
return np.array([self.state]), reward, terminated, truncated, {"old_state": old_state}
def render(self):
print(f"State: {self.state}")
@property
def action_space(self):
return {"type": "discrete", "n": 3}
@property
def observation_space(self):
return {"type": "box", "shape": (1,), "low": 0, "high": self.size-1}
class RandomAgent(Agent):
"""Random agent for testing."""
def __init__(self, action_space):
self.action_space = action_space
def act(self, observation: np.ndarray, deterministic: bool = False) -> int:
if isinstance(self.action_space, dict) and self.action_space["type"] == "discrete":
return np.random.randint(0, self.action_space["n"])
return 0
def reset(self):
pass
# ==================== Example Script ====================
if __name__ == "__main__":
# Setup logging
logging.basicConfig(level=logging.INFO)
# Create components
env = DummyEnvironment(size=5)
agent = RandomAgent(env.action_space)
logger = JsonLogger(log_dir="./logs", experiment_id="example_001")
# Create guardrails
guardrails = CompositeGuardrail([
ActionBoundsGuardrail(env.action_space, {}),
StepLimitGuardrail({"max_steps_per_episode": 20})
], violation_policy="terminate")
# Create experiment config
config = ExperimentConfig(
experiment_id="example_001",
description="Example experiment with guardrails",
agent_config={"type": "random"},
env_config={"size": 5},
max_episodes=5,
max_steps_per_episode=50,
seed=42,
log_dir="./logs",
guardrails_config={"violation_policy": "terminate"}
)
# Create and run experiment
harness = ExperimentHarness(
config=config,
agent=agent,
environment=env,
logger=logger,
guardrails=guardrails
)
# Run experiment
results = harness.run(num_episodes=5, render=False)
# Print metrics
metrics = harness.get_metrics()
print("Experiment Metrics:")
print(json.dumps(metrics, indent=2))