The user wants a Reinforcement Learning (RL) experimentation harness.
This harness needs to support three main functionalities:
- Simulate environments: It needs to wrap or mock environments (likely compatible with the OpenAI Gym/Farama Gymnasium API, as that's the standard).
- Log rewards: It needs to track and record the rewards obtained during training/evaluation.
- Enforce guardrails: It needs mechanisms to stop or limit training based on certain conditions (e.g., exploding losses, runaway performance, resource limits, safety constraints).
Key Components of the System:
- The Environment Wrapper: A class that wraps a standard gym environment to intercept step/reset calls for logging and safety checks.
- The Logger: A component to store metrics (rewards, episode lengths, timestamps). A simple CSV or JSON logger, or integration with TensorBoard/MLFlow, would be good. For a standalone code example, a structured list or simple file writer is best.
- The Guardrails System:
- Constraints: Max steps, min/max reward thresholds, divergence checks.
- Action: Raise an exception, return a flag, or pause training.
- The Harness/Trainer Loop: The orchestration script that connects the agent, the environment, the logger, and the guardrails.
Design Patterns:
- Strategy Pattern: For the policy/agent (though I'll provide a random agent for demonstration).
- Observer Pattern: For the logger and guardrails observing the environment interaction.
- Decorator Pattern: Wrapping the environment to add logging/guardrail functionality without changing the core environment code.
Drafting the Code Structure (Mental or scratchpad):
- Dependencies:
gymnasium (standard), numpy (always needed).
- Guardrail Class: Needs to check state, reward, and total steps.
- Logger Class: Needs to write to disk or memory.
- Harness Class:
__init__(env, agent, guardrails, logger)
run_episode()
train(n_episodes)
Refining "Guardrails":
What does "enforce guardrails" mean in RL?
- Safety: If the agent enters a "dangerous" state (hard to simulate without a specific env, but I can check for NaN/Inf).
- Performance: If rewards suddenly drop to -infinity (instability).
- Resource: Timeouts.
I will implement a
GuardrailManager that takes a list of callable checks.
Refining "Logger":
I'll implement a simple JSON lines logger that saves episode summaries and step-level data if requested.
The Agent:
Since I can't import a full Stable-Baselines3 or RLlib agent easily in a single script, I will create a BaseAgent interface and a RandomAgent implementation.
Putting it together:
- Environment: Use
CartPole as a concrete example.
- Wrapper:
MonitoredEnv wraps gym.make.
- Harness: The main driver.
Self-Correction/Edge Cases:
- Issue: The environment might crash. The harness needs
try-except blocks.
- Issue: The agent might return invalid actions. The harness should check action space.
- Issue: Guardrails should be able to reset the environment or stop the training loop gracefully.
Plan:
- Define the
Agent interface.
- Define the
Guardrail classes (NaN check, Reward bound check, Step limit).
- Define the
Logger class.
- Define the
ExperimentHarness class.
- Provide a usage example with
CartPole.
Let's write the code. I will aim for clean, Pythonic, object-oriented code with type hinting.
Specific implementation details:
- Use
gymnasium (the maintained fork of gym).
- The guardrail logic should return a status enum (OK, TERMINATE_EPISODE, TERMINATE_TRAINING).
Let's start coding mentally...
class Guardrail(ABC): check(obs, reward, done, info) -> Status
class RewardBoundGuardrail(Guardrail): ...
class ExperimentHarness: train() ...
I will add comments explaining how to swap out the dummy agent for a real one (like PPO/DQN).
Final Polish: ensure the logging captures the "why" if a guardrail is tripped.
Let's construct the response.
This design implements a modular Reinforcement Learning (RL) experimentation harness in Python. It uses the standard gymnasium (formerly OpenAI Gym) API, making it compatible with most RL libraries (Stable-Baselines3, Ray RLLib, etc.).
The system consists of three main components:
- The Environment Wrapper: Injects logging and safety checks into standard environments.
- The Guardrail System: A rule-based engine that enforces constraints (e.g., preventing divergence or unsafe states).
- The Harness Controller: Orchestrates the training loop, handles exceptions, and manages the session lifecycle.
1. Prerequisites
You will need gymnasium and numpy.
pip install gymnasium numpy
2. The Implementation
import gymnasium as gym
import numpy as np
import logging
import json
from abc import ABC, abstractmethod
from typing import List, Dict, Any, Optional, Tuple
from enum import Enum
# ==========================================
# 1. Guardrail System
# ==========================================
class GuardrailAction(Enum):
CONTINUE = 1
TRUNCATE_EPISODE = 2
STOP_TRAINING = 3
class BaseGuardrail(ABC):
"""Abstract base class for custom guardrails."""
@abstractmethod
def check(self, observation: np.ndarray, reward: float, done: bool, info: Dict) -> GuardrailAction:
pass
class RewardAnomalyGuardrail(BaseGuardrail):
"""
Stops training if rewards explode (NaN/Infinity) or
if the moving average drops below a catastrophic threshold.
"""
def __init__(self, min_avg_reward: float = -1000.0, window_size: int = 10):
self.min_avg_reward = min_avg_reward
self.window_size = window_size
self.reward_history = []
def check(self, observation: np.ndarray, reward: float, done: bool, info: Dict) -> GuardrailAction:
# 1. Check for NaN or Infinity
if np.isnan(reward) or np.isinf(reward):
logging.error(f"Guardrail Triggered: Invalid reward detected ({reward}).")
return GuardrailAction.STOP_TRAINING
# 2. Update history
self.reward_history.append(reward)
if len(self.reward_history) > self.window_size:
self.reward_history.pop(0)
# 3. Check moving average
if len(self.reward_history) == self.window_size:
avg = np.mean(self.reward_history)
if avg < self.min_avg_reward:
logging.error(f"Guardrail Triggered: Avg reward {avg} below threshold {self.min_avg_reward}.")
return GuardrailAction.STOP_TRAINING
return GuardrailAction.CONTINUE
class ActionConstraintGuardrail(BaseGuardrail):
"""
Example guardrail for continuous control:
Ensures agent outputs actions within valid bounds (if the model misbehaves).
"""
def __init__(self, action_bounds: Tuple[float, float]):
self.low, self.high = action_bounds
def check(self, observation: np.ndarray, reward: float, done: bool, info: Dict) -> GuardrailAction:
# Note: In a real wrapper, we'd check the *action* before stepping.
# Here we check if the environment state is valid after stepping.
# This is a placeholder for state-based safety checks.
return GuardrailAction.CONTINUE
# ==========================================
# 2. Environment Wrapper (The Harness Core)
# ==========================================
class ExperimentHarnessWrapper(gym.Wrapper):
"""
A Gym wrapper that logs metrics and enforces guardrails every step.
"""
def __init__(self, env: gym.Env, guardrails: List[BaseGuardrail], log_file: str = "experiment_log.jsonl"):
super().__init__(env)
self.guardrails = guardrails
self.log_file = log_file
self.episode_rewards = []
self.current_episode_reward = 0
self.global_step_count = 0
# Initialize logger
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Clear log file
with open(self.log_file, 'w') as f:
pass
def _log_step(self, obs, reward, terminated, truncated, info):
"""Log step data to file (JSON Lines format)."""
log_entry = {
'step': self.global_step_count,
'reward': reward,
'episode_reward_so_far': self.current_episode_reward,
'terminated': terminated
}
with open(self.log_file, 'a') as f:
f.write(json.dumps(log_entry) + '\n')
def step(self, action):
# Execute action in the underlying environment
obs, reward, terminated, truncated, info = self.env.step(action)
self.global_step_count += 1
self.current_episode_reward += reward
# 1. Logging
self._log_step(obs, reward, terminated, truncated, info)
# 2. Guardrail Enforcement
for guardrail in self.guardrails:
action_code = guardrail.check(obs, reward, terminated, info)
if action_code == GuardrailAction.TRUNCATE_EPISODE:
logging.warning("Guardrail requested episode truncation.")
truncated = True
info['guardrail_trigger'] = True
elif action_code == GuardrailAction.STOP_TRAINING:
logging.critical("CRITICAL GUARDRAIL: Stopping training immediately.")
# We raise a custom exception to break the control loop externally
raise TrainingInterruptionError("Guardrail condition met: Stop Training.")
# Handle episode completion
if terminated or truncated:
self.episode_rewards.append(self.current_episode_reward)
logging.info(f"Episode finished. Total Reward: {self.current_episode_reward}")
self.current_episode_reward = 0
return obs, reward, terminated, truncated, info
def reset(self, **kwargs):
self.current_episode_reward = 0
return self.env.reset(**kwargs)
class TrainingInterruptionError(Exception):
"""Custom exception to signal the training loop to stop."""
pass
# ==========================================
# 3. The Experiment Harness (Orchestrator)
# ==========================================
class ExperimentHarness:
"""
Orchestrates the experiment setup, execution, and error handling.
"""
def __init__(self, env_name: str, agent, guardrails: List[BaseGuardrail]):
self.env_name = env_name
self.agent = agent
# Create environment
base_env = gym.make(env_name)
# Wrap environment with logging and guardrails
self.wrapped_env = ExperimentHarnessWrapper(base_env, guardrails)
# Give agent access to the environment
self.agent.set_env(self.wrapped_env)
def run(self, total_steps: int):
logging.info(f"Starting experiment on {self.env_name} for {total_steps} steps.")
try:
self.agent.learn(total_timesteps=total_steps)
logging.info("Training completed successfully.")
except TrainingInterruptionError as e:
logging.error(f"Experiment halted by guardrail: {e}")
# Here you could add logic to save the last valid model state
except Exception as e:
logging.error(f"Experiment crashed: {e}")
raise e
finally:
self._generate_report()
def _generate_report(self):
rewards = self.wrapped_env.episode_rewards
if not rewards:
return
report = {
"environment": self.env_name,
"total_episodes": len(rewards),
"average_reward": np.mean(rewards),
"max_reward": np.max(rewards),
"min_reward": np.min(rewards)
}
logging.info("==== EXPERIMENT REPORT ====")
for k, v in report.items():
logging.info(f"{k}: {v}")
logging.info("===========================")
# ==========================================
# 4. Mock Agent (For Demonstration)
# ==========================================
class MockAgent:
"""
A dummy agent that mimics an RL library (like SB3) interface.
It takes random actions but allows us to test the loop.
"""
def __init__(self):
self.env = None
def set_env(self, env):
self.env = env
def learn(self, total_timesteps: int):
obs, _ = self.env.reset()
for i in range(total_timesteps):
# Random action
action = self.env.action_space.sample()
# Occasionally simulate a dangerous reward to test guardrails
# (Comment this out to see a full successful run)
if i == 500:
# Injecting a bad reward manually for demonstration purposes
# In real RL, this would come from the env logic
obs, reward, term, trunc, info = self.env.step(action)
# Override reward for test (cannot easily do this without hacking the env)
# Instead, we rely on the environment behaving normally
# or the user injecting faults.
pass
try:
obs, reward, terminated, truncated, info = self.env.step(action)
if terminated or truncated:
obs, _ = self.env.reset()
except TrainingInterruptionError:
raise
# ==========================================
# 5. Running the System
# ==========================================
if __name__ == "__main__":
# 1. Define Guardrails
# Stop if average reward over 5 steps drops below -50 (CartPole usually gives +1 per step, so -50 is bad)
safety_guardrails = [
RewardAnomalyGuardrail(min_avg_reward=-20.0, window_size=5)
]
# 2. Initialize Harness with a MockAgent and CartPole
harness = ExperimentHarness(
env_name="CartPole-v1",
agent=MockAgent(),
guardrails=safety_guardrails
)
# 3. Run Experiment
try:
harness.run(total_steps=1000)
except Exception as e:
print(f"Execution finished with error: {e}")
Design Breakdown
1. The Guardrails (BaseGuardrail)
We define guardrails as modular, swappable classes.
RewardAnomalyGuardrail: Monitors the reward stream. If it sees NaN (common in numerical instabilities) or if the moving average plummets (indicating a broken policy), it triggers a STOP_TRAINING signal.
ActionConstraintGuardrail: A placeholder showing how you could enforce physical limits or safety constraints before the environment steps forward.
2. The Wrapper (ExperimentHarnessWrapper)
This is the interception layer. It relies on the Decorator Pattern.
- It sits between the Agent and the actual Environment.
- Logging: It writes step-by-step data to a JSON-lines file. This is better than CSV for nested structures (like arrays of pixels) and allows for streaming writes.
- Enforcement: It iterates through the list of guardrails after every step. If a guardrail fails, it can force an episode to end (
truncated=True) or raise a system-wide exception (TrainingInterruptionError) to kill the process safely.
3. The Orchestrator (ExperimentHarness)
This is the "Harness" proper.
- It handles the messy setup of instantiating the environment and wrapping it.
- It runs the training loop inside a
try-except block.
- Report Generation: Even if the training crashes, the
finally block ensures you get a summary of what happened (mean reward, episodes completed) so the experiment isn't a total loss.
4. Extensibility
- Real Agents: You can replace
MockAgent with an agent from Stable-Baselines3 (SB3). The ExperimentHarnessWrapper is fully compatible with SB3's VecEnv wrappers if adapted slightly.
- Remote Logging: In
_log_step, you could easily swap the file write for a requests.post to send metrics to MLFlow, TensorBoard, or Neptune.ai.