We are going to design a synthetic agent simulation for Reinforcement Learning (RL) that handles:
- Curriculum: a sequence of tasks that the agent must learn, typically of increasing difficulty.
- Adversaries: other agents or elements that can change the environment or act against the agent.
- Metrics: ways to measure the agent's performance and progress.
We'll design a modular system that can be configured with different environments, adversaries, and curriculum schedules.
Components:
- Agent: The RL agent that will learn across the curriculum.
- Environment: The world in which the agent operates. It can include adversaries and other agents.
- Curriculum Manager: Decides which task (or environment configuration) the agent should train on next based on performance.
- Adversary Manager: Manages the adversaries in the environment (could be fixed, or adaptive to the agent's performance).
- Metrics Tracker: Collects and reports metrics about the agent's performance.
We'll assume that the environment is a standard RL environment (like OpenAI Gym) but with the ability to include adversaries and to be configured for different tasks.
Steps:
-
Define an abstract base class for the environment that can be configured for different tasks and can include adversaries.
-
Define an adversary interface. Adversaries can be other agents (with their own policy) or environmental changes.
-
Define a curriculum manager that:
- Keeps a list of tasks (each task is a specific configuration of the environment, possibly including a different set of adversaries or parameters).
- Monitors the agent's performance on the current task.
- Switches to the next task when the agent reaches a certain performance threshold (or after a fixed number of episodes).
-
The main training loop will:
- For each task in the curriculum (until completion or max tasks):
- Configure the environment for the current task.
- Train the agent until the curriculum manager decides to move on (or until max steps).
- Track metrics for the current task and overall.
-
Metrics: We want to track:
- Episode return (average, max, min)
- Success rate (if the task has a binary success condition)
- Any task-specific metrics (like time to completion, etc.)
- Adversary-specific metrics (if we have adversaries, how well the agent does against them)
-
Adversaries: We might have a set of adversaries that are introduced in the curriculum. The adversary manager could:
- Introduce more adversaries as the curriculum progresses.
- Change the policy of the adversaries (from random to more sophisticated) as the agent improves.
- Alternatively, the adversaries could be part of the task configuration (task 1 has no adversary, task 2 has a random adversary, task 3 has a learning adversary).
Let's design the classes:
-
Environment (abstract base class):
- init(self, config): config is a dictionary that can include parameters for the environment and adversaries.
- reset(self): resets the environment and returns the initial state.
- step(self, action): takes an action and returns (next_state, reward, done, info). The info dict can include adversary actions, etc.
- render(self, mode='human'): optional.
-
Adversary (abstract base class):
- init(self, config): config might include the adversary's policy or parameters.
- act(self, state): returns an action that the adversary will take (which might affect the environment or the agent).
- update(self, ...): if the adversary is learning, it might update its policy.
-
Curriculum Manager:
- init(self, tasks): a list of tasks, where each task is a configuration dictionary for the environment.
- get_current_task(self): returns the current task configuration.
- should_advance(self, metrics): returns True if the agent has met the criteria to move to the next task.
-
Metrics Tracker:
- init(self, task_name):
- record_episode(self, episode_return, success, ...): records metrics for an episode.
- get_summary(self): returns a dictionary of summary statistics for the current task and overall.
-
Main training loop:
curriculum = CurriculumManager(tasks)
agent = RLAgent()
metrics_tracker = MetricsTracker()
for task in curriculum:
env = Environment(config=task) # The environment for the current task
adversary_manager = AdversaryManager(task.get('adversaries', []))
for episode in range(max_episodes_per_task):
state = env.reset()
done = False
episode_return = 0
while not done:
agent_action = agent.act(state)
# If there are adversaries, get their actions and pass them to the environment step?
# Alternatively, the environment might internally handle adversaries.
# Let's assume the environment step takes the agent's action and internally uses adversaries if present.
next_state, reward, done, info = env.step(agent_action)
agent.learn(state, agent_action, reward, next_state, done)
state = next_state
episode_return += reward
# Record metrics for the episode
metrics_tracker.record_episode(episode_return, success=info.get('success', False), ...)
# Check if we should advance the task
if curriculum.should_advance(metrics_tracker.get_current_summary()):
break
# After finishing a task, we might want to save the agent or do something.
Given the complexity, we'll start by designing the interfaces and then the main loop.
Let's write some pseudocode for the classes:
Note: We are going to use Python and assume we have an existing RL algorithm (like DQN, PPO, etc.) for the agent.
We'll define:
class Environment(ABC):
@abstractmethod
def reset(self):
pass
@abstractmethod
def step(self, action):
pass
class Adversary(ABC):
@abstractmethod
def act(self, state):
pass
# If the adversary learns, it might have an update method.
@abstractmethod
def update(self, ...):
pass
But note: the environment might have multiple adversaries, and they might need to be stepped at each timestep.
Alternatively, we can have an AdversaryManager that holds a list of adversaries and steps them.
class AdversaryManager:
def init(self, adversary_configs):
self.adversaries = [create_adversary(config) for config in adversary_configs]
def get_actions(self, state):
return [adv.act(state) for adv in self.adversaries]
def update_all(self, ...):
for adv in self.adversaries:
adv.update(...)
Then the environment step might look like:
def step(self, agent_action):
# Get adversary actions from the adversary manager (which might be passed in the environment constructor)
adversary_actions = self.adversary_manager.get_actions(self.state) if self.adversary_manager else []
# Then combine agent_action and adversary_actions to affect the environment.
# This is environment specific.
However, the environment might not know about the adversary manager? Alternatively, the environment could be given the adversary manager and then the environment step uses the adversary actions.
Let's change: The environment is built with a list of adversaries (or an adversary manager). Then the environment's step function internally uses the adversaries.
So:
class MyEnvironment(Environment):
def __init__(self, config):
self.adversary_manager = AdversaryManager(config.get('adversaries', []))
def step(self, agent_action):
# Get adversary actions
adversary_actions = self.adversary_manager.get_actions(self.state)
# Now, how to apply them? This is environment-specific.
# Maybe the environment's dynamics are: state' = f(state, agent_action, adversary_actions)
# Then the reward might also depend on adversary_actions.
But note: the adversaries might be part of the state? Or they might be external. We need to define the interface.
Alternatively, we can have the environment step take both agent action and adversary actions? But then the training loop would have to get the adversary actions and pass them. That would break the standard RL loop.
Let's decide: the environment will handle the adversaries internally. The training loop only passes the agent's action.
Then the environment must be designed to include the adversaries in its dynamics.
This is more modular because the training loop doesn't have to change for different adversary setups.
-
We might have adversaries that are not part of the environment but are other agents that are learning alongside? That would be a multi-agent RL setting, which is more complex. For now, let's assume the adversaries are non-learning (or fixed policy) or are part of the environment and their policy is fixed or changes according to the task.
-
If we want the adversaries to learn, then we have to update them. But note that in an adversarial setting, the agent and adversary are both learning. This is a two-player game. We might need to update the adversary at the same time as the agent? Or the adversary might be fixed for a while and then updated? This is getting complex.
Given the scope, let's assume for now that the adversaries are either:
- Static (random or fixed policy)
- Or they are part of the environment and their policy is defined by the task configuration (so they might change from task to task, but don't learn during the task).
If we want learning adversaries, we might need to have the training loop also update the adversary. But then the adversary is another agent? We might need to have two agents? This is beyond the initial scope.
So, for simplicity, we'll assume adversaries are non-learning (or their learning is handled externally, and we just provide them with a policy).
-
Design of the Curriculum Manager:
class CurriculumManager:
def init(self, tasks, threshold=0.9, window_size=100):
self.tasks = tasks # list of task configurations
self.current_task_index = 0
self.threshold = threshold # for example, success rate threshold
self.window_size = window_size # number of recent episodes to consider
def get_current_task(self):
return self.tasks[self.current_task_index]
def should_advance(self, recent_success_rates):
# recent_success_rates is a list of success rates (0 or 1) for the last window_size episodes.
if len(recent_success_rates) < self.window_size:
return False
avg_success = sum(recent_success_rates) / len(recent_success_rates)
return avg_success >= self.threshold
def advance(self):
self.current_task_index += 1
# Reset the metrics for the new task?
# We'll let the metrics tracker handle per-task metrics.
-
Metrics Tracker:
class MetricsTracker:
def init(self):
self.current_task_episodes = [] # list of (return, success) for the current task
self.all_episodes = [] # for overall
def record_episode(self, return, success, task_name):
self.current_task_episodes.append((return, success))
self.all_episodes.append((return, success, task_name))
def get_current_summary(self):
if not self.current_task_episodes:
return {}
returns = [r for r, s in self.current_task_episodes]
successes = [s for r, s in self.current_task_episodes]
return {
'avg_return': sum(returns) / len(returns),
'success_rate': sum(successes) / len(successes),
'last_10_avg_return': sum(returns[-10:]) / min(10, len(returns)),
'last_10_success_rate': sum(successes[-10:]) / min(10, len(successes))
}
def get_overall_summary(self):
# similar but for all_episodes, maybe per task?
pass
-
Main loop with curriculum and adversaries:
tasks = [...] # list of task configurations
curriculum = CurriculumManager(tasks)
agent = SomeRLAgent()
metrics_tracker = MetricsTracker()
for task_index in range(len(tasks)):
task_config = curriculum.get_current_task()
env = Environment(task_config) # This environment will have adversaries as per the task_config.
# Reset the metrics tracker for the new task? Or we keep the current task episodes separate?
# We'll reset the current_task_episodes when we start a new task.
metrics_tracker.current_task_episodes = []
for episode in range(max_episodes_per_task):
state = env.reset()
done = False
episode_return = 0
success = False # depends on the environment
while not done:
action = agent.act(state)
next_state, reward, done, info = env.step(action)
# The environment might set 'success' in info if the task is successful.
agent.learn(state, action, reward, next_state, done)
state = next_state
episode_return += reward
success = info.get('success', False)
metrics_tracker.record_episode(episode_return, success, task_name=task_config.get('name', f'task_{task_index}'))
# Check for curriculum advancement
# We'll use the success rate from the current task episodes.
recent_successes = [s for r, s in metrics_tracker.current_task_episodes]
if curriculum.should_advance(recent_successes):
print(f"Advancing to next task after {episode+1} episodes.")
break
# After finishing the task (either by advancement or max episodes), we might want to save the agent.
Given the time, we'll stick to success rate for advancement.
This is a high-level design. Let's write a simple example with a mock environment and adversary.
Example:
Task 1: A grid world with no adversary.
Task 2: The same grid world but with a random adversary that blocks the agent.
We'll create a simple environment and a random adversary.
Implementation:
We'll create:
class SimpleGridWorld(Environment):
def __init__(self, config):
self.size = config.get('size', 5)
self.adversary_manager = AdversaryManager(config.get('adversaries', []))
# ... other initializations
def reset(self):
# reset the state (agent position, goal position, etc.)
self.agent_pos = [0,0]
self.goal_pos = [self.size-1, self.size-1]
# If there are adversaries, reset them too? They might have their own reset.
if self.adversary_manager:
for adv in self.adversary_manager.adversaries:
if hasattr(adv, 'reset'):
adv.reset()
return self._get_obs()
def step(self, agent_action):
# Apply agent action (e.g., move in a direction)
# Then apply adversary actions if any.
# For example, if the adversary moves and blocks the agent, then the agent might not move.
# First, get adversary actions (they might act before or after the agent? Depends on the game)
adversary_actions = self.adversary_manager.get_actions(self._get_obs()) if self.adversary_manager else []
# Then update the state based on agent action and adversary actions.
# For simplicity, let's say the adversary can block a cell. If the agent tries to move into a cell blocked by an adversary, the move fails.
# ... update state ...
# Compute reward and done
reward = -1 # step penalty
done = False
if self.agent_pos == self.goal_pos:
done = True
reward = 10
success = True
else:
success = False
# If an adversary is on the goal, then maybe the agent cannot reach it? Or we have a different condition.
info = {'success': success, 'adversary_actions': adversary_actions}
return self._get_obs(), reward, done, info
The adversary for the random one:
class RandomAdversary(Adversary):
def __init__(self, config):
self.block_prob = config.get('block_prob', 0.1)
def act(self, state):
# With probability block_prob, return an action that blocks a random adjacent cell?
# But the environment must know how to interpret the adversary action.
# For our simple grid world, let's say the adversary action is a position to block.
# But the adversary doesn't know the agent's position? It might just block a random cell.
# We'll have the adversary choose a random cell to block? But then the environment must have a way to apply it.
# Alternatively, we can have the adversary action be a direction from the adversary's position?
# We need to define the adversary's state.
This is getting very environment-specific. We might need to design the interface for adversaries to be more general.
Given the time, we might leave the adversary implementation to the specific environment.
Alternatively, we can define:
class Adversary(ABC):
def act(self, state, agent_state):
# The adversary gets the full state and the agent's state?
# But then the environment must provide the agent's state to the adversary?
# This is getting messy.
We might instead design the environment to have a fixed set of adversaries that are part of the environment's dynamics and are configured by the task configuration.
So, for each task, the environment might have a different set of adversaries with different behaviors. The curriculum manager just changes the environment configuration.
Therefore, we don't need a separate adversary manager? The environment internally creates and manages the adversaries.
Then the training loop doesn't need to know about adversaries. The environment's step function will incorporate the adversary actions.
So we can remove the AdversaryManager from the training loop and let the environment handle everything.
Revised plan:
class Environment(ABC):
@abstractmethod
def reset(self):
pass
@abstractmethod
def step(self, agent_action):
# The environment uses its internal adversaries (if any) and the agent's action to update the state.
# Returns (state, reward, done, info)
pass
Then the training loop is as before, but the environment is responsible for adversaries.
The task configuration for an environment with an adversary might look like:
task_config = {
'env_id': 'SimpleGridWorld',
'size': 5,
'adversary': {
'type': 'random_blocker',
'block_prob': 0.1
}
}
And the environment's __init__ will create the adversary based on the config.
This is simpler for the training loop.
-
We'll adjust the curriculum manager to use the environment's success rate (from the info dict) to decide advancement.
-
We'll also adjust the metrics tracker to record the success from the info.
-
We'll write a simple example:
tasks = [
{'env_id': 'SimpleGridWorld', 'size': 5, 'adversary': None},
{'env_id': 'SimpleGridWorld', 'size': 5, 'adversary': {'type': 'random_blocker', 'block_prob': 0.1}},
{'env_id': 'SimpleGridWorld', 'size': 5, 'adversary': {'type': 'random_blocker', 'block_prob': 0.2}}
]
Then the curriculum will start with no adversary, then a random blocker with 0.1, then 0.2.
-
We'll need a way to create the environment from the config. We can have an environment registry.
ENV_REGISTRY = {
'SimpleGridWorld': SimpleGridWorld,
...
}
Then in the training loop:
env_class = ENV_REGISTRY[task_config['env_id']]
env = env_class(task_config)
-
We might also want to have the same agent for all tasks? Yes, typically the agent is the same and learns across tasks.
-
We might want to save the agent after each task? Or only at the end.
Given the complexity and the fact that we are designing a simulation, we'll keep the example simple.
Let's code a minimal version:
- We'll create a SimpleGridWorld environment with an optional random blocker adversary.
- We'll create a dummy RL agent that uses a random policy for now (or a simple Q-learning if we want).
- We'll run the curriculum and see the success rates.
But note: the agent must learn. We'll use a simple Q-learning agent for discrete actions and states.
However, the state in the grid world is the agent's position. We can represent it as (x,y). The actions are: up, down, left, right.
The adversary: a random blocker that with probability block_prob, blocks a random adjacent cell (other than the agent's current cell) for one step? Or blocks a cell for the whole episode? We'll do:
The adversary blocks one cell at a time, chosen randomly at each step (with probability block_prob). The blocked cell is not passable for the agent in that step.
But note: the environment's state must include which cells are blocked? Or the blocking is temporary and only for the next step?
We'll do:
At each step, after the agent chooses an action, the adversary (if present) chooses a cell to block (from a set of cells, excluding the agent's current cell and the goal?).
Then, when the agent tries to move, if the target cell is blocked, the move fails (agent stays).
This is a simple example.
Let's code:
class SimpleGridWorld:
def __init__(self, config):
self.size = config['size']
self.adversary_config = config.get('adversary')
self.blocked_cell = None # for the current step, if any
def reset(self):
self.agent_pos = [0,0]
self.goal_pos = [self.size-1, self.size-1]
self.blocked_cell = None
return self._get_obs()
def _get_obs(self):
return tuple(self.agent_pos)
def step(self, agent_action):
# agent_action: 0=up, 1=down, 2=left, 3=right
# First, let the adversary act (if any) and set a blocked cell for this step.
if self.adversary_config and self.adversary_config['type'] == 'random_blocker':
if random.random() < self.adversary_config['block_prob']:
# Choose a random cell that is not the agent's current cell and not the goal?
# We'll choose any cell except the agent's current cell.
candidate_cells = [(x,y) for x in range(self.size) for y in range(self.size) if (x,y) != tuple(self.agent_pos)]
self.blocked_cell = random.choice(candidate_cells)
else:
self.blocked_cell = None
# Now, compute the next agent position based on the action, but if the target is blocked, then stay.
next_pos = self.agent_pos.copy()
if agent_action == 0: # up
next_pos[0] = max(0, self.agent_pos[0]-1)
elif agent_action == 1: # down
next_pos[0] = min(self.size-1, self.agent_pos[0]+1)
elif agent_action == 2: # left
next_pos[1] = max(0, self.agent_pos[1]-1)
elif agent_action == 3: # right
next_pos[1] = min(self.size-1, self.agent_pos[1]+1)
# If the next_pos is the blocked cell, then don't move.
if tuple(next_pos) == self.blocked_cell:
next_pos = self.agent_pos
self.agent_pos = next_pos
# Check if reached goal
done = False
reward = -1
success = False
if self.agent_pos == self.goal_pos:
done = True
reward = 10
success = True
info = {'success': success, 'blocked_cell': self.blocked_cell}
return self._get_obs(), reward, done, info
This is a very simple environment.
-
Now, the agent:
We'll use a simple Q-table for the grid world (since the state is the agent's position and the action is discrete).
But note: the state does not include the blocked cell. So the agent cannot know which cell is blocked until it tries?
Actually, the blocked cell is not part of the observation. So the agent doesn't know if a cell is going to be blocked.
This is a partially observable environment? Actually, the agent doesn't observe the blocked cell at all. So it's a POMDP?
But in our step function, the agent doesn't get to know the blocked cell until after it has taken the action and the move fails?
We are not giving the blocked cell in the observation. So the agent doesn't know.
We might want to change that? Or we can leave it as a challenge.
Alternatively, we can include the blocked cell in the state? But then the state space becomes (agent_pos, blocked_cell) and the blocked_cell can be any cell or None. That's large.
We'll keep it as is: the agent doesn't observe the blocked cell. So it's a POMDP.
But then the agent cannot learn a policy that accounts for the adversary? It will just learn to avoid the goal? Actually, the adversary blocks randomly, so the agent might still learn to go to the goal because the blocking is random and not always on the path.
However, if the blocking probability is high, the agent might have a hard time.
This is just an example.
-
We'll implement a Q-learning agent that doesn't consider the blocked cell (so it's learning in a POMDP).
class QLearningAgent:
def init(self, state_space, action_space, alpha=0.1, gamma=0.99, epsilon=0.1):
self.state_space = state_space # list of all possible states (for grid world, all (x,y))
self.action_space = action_space # 4
self.alpha = alpha
self.gamma = gamma
self.epsilon = epsilon
self.q_table = {}
for state in state_space:
self.q_table[state] = [0.0] * action_space
def act(self, state):
if random.random() < self.epsilon:
return random.randint(0, self.action_space-1)
else:
return np.argmax(self.q_table[state])
def learn(self, state, action, reward, next_state, done):
old_q = self.q_table[state][action]
if done:
target = reward
else:
target = reward + self.gamma * max(self.q_table[next_state])
self.q_table[state][action] = old_q + self.alpha * (target - old_q)
-
We need to define the state space for the grid world:
state_space = [(x,y) for x in range(size) for y in range(size)]
-
Now, the main loop with curriculum:
tasks = [
{'env_id': 'SimpleGridWorld', 'size': 5, 'adversary': None},
{'env_id': 'SimpleGridWorld', 'size': 5, 'adversary': {'type': 'random_blocker', 'block_prob': 0.1}},
{'env_id': 'SimpleGridWorld', 'size': 5, 'adversary': {'type': 'random_blocker', 'block_prob': 0.2}}
]
Given the time, we'll leave it as is.
This design should be flexible enough to plug in different environments and adversaries.
We'll now write the code accordingly.
However, note that the environment we built is specific to the grid world and the random blocker. To make it general, we would need to define an interface for adversaries that can be implemented for different environments.
But since we are designing a simulation, we can have different environment classes and different adversary classes that are specific to that environment.
We'll leave the adversary implementation to the environment.
So, the environment class is responsible for creating and managing the adversaries. The training loop doesn't see the adversaries.
This is acceptable for a simulation where the environment is a black box that may contain adversaries.
Let's code accordingly.
We'll create:
ENV_REGISTRY = {}
def register_env(name):
def decorator(cls):
ENV_REGISTRY[name] = cls
return cls
return decorator
Then, we define SimpleGridWorld and register it.
But for simplicity, we'll just use a dictionary.
Given the above, let's write the code.
We'll break the code into:
- environment.py: contains base Environment class and SimpleGridWorld.
- agent.py: contains QLearningAgent (and maybe other agents).
- curriculum.py: contains CurriculumManager.
- metrics.py: contains MetricsTracker.
- main.py: the training loop.
But since we are in one response, we'll write a single script.
Let's code accordingly.
We'll assume the grid world size is fixed at 5 for the state space of the QLearningAgent.
However, note: the state space for the agent is the agent's position. The grid world size can be variable? Then we need to adjust the state space accordingly.
We'll make the agent accept the state space at construction.
We'll run the example and see if the agent can learn in the first task (no adversary) and then in the second and third.
Given the simplicity, we expect the agent to learn the first task quickly (since it's deterministic and shortest path is 8 steps). Then with 10% blocking, it might take longer, and with 20% blocking, even longer.
We'll adjust the threshold for advancement to 0.8 (80% success rate) and window size 50.
Let's code accordingly.
Note: the success condition is reaching the goal. The agent gets a reward of 10 for reaching the goal and -1 per step.
We'll run the example and print the success rates.
We'll also print the number of episodes per task.
Let's code.
I'll design a comprehensive synthetic agent simulation for RL with curriculum learning, adversarial dynamics, and robust metrics. This will be a modular, extensible framework.
Architecture Overview
├── Core Simulation Engine
├── Curriculum Manager
├── Adversarial Dynamics System
├── Multi-Metric Tracker
├── Agent Repository (Policies)
└── Configuration System
1. Core Components
1.1 Simulation Engine
class SimulationEngine:
"""
Central orchestrator managing environment instances,
time progression, and state transitions.
"""
def __init__(self, config: SimulationConfig):
self.env_registry = EnvironmentRegistry()
self.time = 0
self.global_state = GlobalState()
self.event_bus = EventBus()
def create_episode(self, task_config: TaskConfig) -> Episode:
"""Instantiate environment with specific task parameters"""
env = self.env_registry.get(task_config.env_type)
return Episode(env, task_config)
def step(self, actions: Dict[AgentID, Action]) -> StepResult:
"""Single timestep across all agents"""
observations = {}
rewards = {}
for agent_id, action in actions.items():
obs, reward, done = self.current_episode.env.step(agent_id, action)
observations[agent_id] = obs
rewards[agent_id] = reward
self.time += 1
return StepResult(observations, rewards, self.time)
1.2 Environment Abstraction
class ModularEnvironment(ABC):
"""
Composable environment with pluggable components:
- Dynamics (physics/rules)
- Adversary injectors
- Curriculum hooks
"""
def __init__(self, config: EnvConfig):
self.dynamics = DynamicsSystem(config.dynamics)
self.adversary_layer = AdversaryLayer(config.adversaries)
self.curriculum_hooks = config.curriculum_hooks
self.observable_space = ObservableSpace(config.observation_spec)
def reset(self) -> Observation:
state = self.dynamics.initial_state()
state = self.adversary_layer.inject(state, phase='reset')
return self.observable_space.encode(state)
def step(self, agent_id: str, action: Action) -> Tuple[Observation, Reward, bool]:
state = self.dynamics.current_state()
# Apply adversary perturbations
state = self.adversary_layer.inject(state, phase='pre_step')
# Agent action
next_state = self.dynamics.transition(state, agent_id, action)
# Post-transition adversary effects
next_state = self.adversary_layer.inject(next_state, phase='post_step')
reward = self._compute_reward(state, next_state, agent_id)
done = self.dynamics.is_terminal(next_state)
return self.observable_space.encode(next_state), reward, done
2. Curriculum Management System
2.1 Curriculum Manager
class CurriculumManager:
"""
Manages task progression based on performance metrics
Supports multiple scheduling strategies
"""
def __init__(self, curriculum_spec: CurriculumSpec):
self.tasks = self._build_task_graph(curriculum_spec)
self.current_task_id = self.tasks[0].id
self.performance_history = deque(maxlen=1000)
self.scheduler = self._create_scheduler(curriculum_spec.scheduler_type)
def _build_task_graph(self, spec) -> List[Task]:
"""Create dependency graph of tasks"""
tasks = []
for i, task_spec in enumerate(spec.tasks):
prerequisites = [t.id for t in tasks if t.id in task_spec.requires]
tasks.append(Task(
id=task_spec.id,
difficulty=task_spec.difficulty,
config=task_spec.config,
prerequisites=prerequisites,
success_threshold=task_spec.threshold
))
return tasks
def should_advance(self, metrics: AgentMetrics) -> bool:
"""Determine if agent ready for next task"""
current_task = self.get_current_task()
return self.scheduler.evaluate(
current_task,
metrics,
self.performance_history
)
def get_current_task(self) -> Task:
return next(t for t in self.tasks if t.id == self.current_task_id)
def advance(self) -> Task:
"""Move to next appropriate task"""
next_task = self.scheduler.select_next(
self.current_task_id,
self.tasks
)
self.current_task_id = next_task.id
return next_task
2.2 Scheduler Strategies
class Scheduler(ABC):
@abstractmethod
def evaluate(self, task: Task, metrics: AgentMetrics, history: deque) -> bool:
pass
class PerformanceThresholdScheduler(Scheduler):
def __init__(self, window_size=100, threshold=0.8):
self.window = window_size
self.threshold = threshold
def evaluate(self, task, metrics, history):
recent_metrics = list(history)[-self.window:]
if not recent_metrics:
return False
avg_success = np.mean([m.success_rate for m in recent_metrics])
return avg_success >= task.success_threshold
class TaskSequenceScheduler(Scheduler):
"""Linear progression through predefined tasks"""
def evaluate(self, task, metrics, history):
return metrics.episodes_on_task >= task.min_episodes
class AdaptiveDifficultyScheduler(Scheduler):
"""Dynamically adjust based on learning curve"""
def evaluate(self, task, metrics, history):
# Check if learning has plateaued
if len(history) < 50:
return False
recent = [m.episode_return for m in list(history)[-30:]]
older = [m.episode_return for m in list(history)[-60:-30]]
return np.std(recent) < 0.1 * np.std(older) # Low variance indicates mastery
3. Adversarial Dynamics System
3.1 Adversary Types
class Adversary(ABC):
@abstractmethod
def perturb(self, state: State, agent_policy: Policy) -> Perturbation:
"""Generate adversarial perturbation"""
pass
class StaticAdversary(Adversary):
"""Pre-defined adversarial patterns"""
def __init__(self, pattern: AdversarialPattern):
self.pattern = pattern
def perturb(self, state, policy):
return self.pattern.get_perturbation(state.step)
class LearningAdversary(Adversary):
"""Adversary that learns to counter agent"""
def __init__(self, adversary_policy: Policy):
self.policy = adversary_policy
self.opponent_model = opponent_model # Model of agent's policy
def perturb(self, state, agent_policy):
# Use opponent model to generate worst-case action
worst_action = self._find_max_loss_action(state, agent_policy)
return Perturbation(action=worst_action, strength=0.5)
class CurriculumAdversary(Adversary):
"""Adversary strength scales with curriculum level"""
def __init__(self, base_strength: float, growth_rate: float):
self.strength = base_strength
self.growth = growth_rate
def adapt_to_task(self, task_difficulty: float):
self.strength = self.base_strength * (1 + self.growth * task_difficulty)
3.2 Adversary Layer
class AdversaryLayer:
"""Manages multiple adversary types and their interactions"""
def __init__(self, adversary_specs: List[AdversarySpec]):
self.adversaries = [create_adversary(spec) for spec in adversary_specs]
self.mixing_strategy = adversary_specs[0].mixing # uniform, weighted, etc.
def inject(self, state: State, phase: str) -> State:
"""Apply adversarial perturbations to state"""
perturbations = []
for adv in self.adversaries:
if adv.active_in_phase(phase):
p = adv.perturb(state, self._get_current_policies())
perturbations.append(p)
# Combine perturbations based on mixing strategy
combined = self._combine_perturbations(perturbations)
return state.apply_perturbation(combined)
4. Multi-Metric Tracking
4.1 Metric Definitions
@dataclass
class AgentMetrics:
"""Comprehensive metrics for agent evaluation"""
# Performance
episode_return: float
success_rate: float
episode_length: int
cumulative_reward: float
# Learning progress
improvement_rate: float # Δ performance per 100 episodes
sample_efficiency: float # Performance / episodes
stability: float # Variance of returns
# Curriculum-specific
task_mastery: Dict[str, float] # Per-task performance
transfer_gain: float # Improvement when switching tasks
forget_rate: float # Performance drop on previous tasks
# Adversarial robustness
adversarial_robustness: float # Performance under attack
worst_case_performance: float
perturbation_sensitivity: Dict[str, float]
4.2 Metrics Collector
class MetricsCollector:
"""
Multi-scale metric collection:
- Episode-level
- Task-level
- Curriculum-level
- Population-level (if multi-agent)
"""
def __init__(self, config: MetricsConfig):
self.window_size = config.window_size
self.metrics_history = defaultdict(lambda: deque(maxlen=config.history_size))
self.current_task_metrics = []
self.aggregators = self._build_aggregators(config.aggregators)
def record_episode(self, episode_data: EpisodeData):
"""Record all metrics for single episode"""
metrics = self._compute_episode_metrics(episode_data)
self.current_task_metrics.append(metrics)
self.metrics_history['episode'].append(metrics)
# Update rolling aggregations
for aggregator in self.aggregators:
aggregator.update(metrics)
def get_current_task_summary(self) -> Dict[str, float]:
"""Summary statistics for current task"""
if not self.current_task_metrics:
return {}
return {
'avg_return': np.mean([m.episode_return for m in self.current_task_metrics]),
'success_rate': np.mean([m.success_rate for m in self.current_task_metrics]),
'mastery_score': self._compute_mastery_score()
}
def get_curriculum_report(self) -> CurriculumReport:
"""Cross-task analysis"""
return CurriculumReport(
task_performance=self._group_by_task(),
transfer_matrix=self._compute_transfer_matrix(),
learning_curves=self._plot_learning_curves()
)
5. Complete Training Loop
class CurriculumAdversarialTrainer:
def __init__(self, config: TrainingConfig):
self.engine = SimulationEngine(config.simulation)
self.curriculum = CurriculumManager(config.curriculum)
self.agent = create_agent(config.agent)
self.metrics = MetricsCollector(config.metrics)
self.adversary_scheduler = AdversaryScheduler(config.adversaries)
def train(self):
"""Main training loop with curriculum and adversaries"""
for task in self.curriculum.tasks:
self._setup_task(task)
while not self.curriculum.should_advance(
self.metrics.get_current_task_summary()
):
# Dynamic adversary adjustment
current_adversaries = self.adversary_scheduler.get_adversaries(
task.difficulty,
self.metrics.current_task_metrics
)
self.engine.env.adversary_layer.update_adversaries(current_adversaries)
# Training episode
episode_data = self._run_episode()
self.metrics.record_episode(episode_data)
self.agent.learn(episode_data)
# Periodic evaluation
if self.engine.time % config.eval_interval == 0:
self._evaluate()
self._on_task_complete()
def _run_episode(self) -> EpisodeData:
"""Execute single episode with current adversaries"""
episode = self.engine.create_episode(self.curriculum.get_current_task().config)
state = episode.reset()
done = False
transitions = []
while not done:
action = self.agent.act(state)
next_state, reward, done = self.engine.step({self.agent.id: action})
transitions.append(Transition(state, action, reward, next_state, done))
state = next_state
return EpisodeData(
transitions=transitions,
metrics=self._compute_episode_metrics(transitions)
)
6. Configuration Schema
simulation:
seed: 42
max_steps: 10000
parallelism: 4
curriculum:
scheduler_type: "performance_threshold"
tasks:
- id: "simple_navigation"
difficulty: 0.2
min_episodes: 100
threshold: 0.85
requires: []
config:
env_type: "gridworld"
size: 5
goal_reward: 10.0
- id: "navigation_with_obstacles"
difficulty: 0.5
requires: ["simple_navigation"]
adversaries:
- type: "static_blocker"
frequency: 0.1
- id: "adversarial_navigation"
difficulty: 0.8
requires: ["navigation_with_obstacles"]
adversaries:
- type: "learning_adversary"
policy: "mcta"
strength: 0.3
agent:
type: "ppo"
network:
hidden_layers: [256, 256]
activation: "relu"
hyperparameters:
learning_rate: 3e-4
gamma: 0.99
adversaries:
- type: "static_blocker"
pattern: "random"
activation_threshold: 0.3
metrics:
window_size: 100
track:
- "episode_return"
- "success_rate"
- "adversarial_robustness"
- "forget_rate"
aggregators:
- type: "exponential_moving_average"
alpha: 0.1
7. Key Features
7.1 Dynamic Adversary Injection
- Adversaries scale with task difficulty
- Multiple adversary types can coexist
- Adversary policies can be static, learning, or curriculum-based
7.2 Curriculum Intelligence
- Multiple scheduling strategies
- Performance-based progression
- Prerequisite task requirements
- Automatic difficulty adjustment
7.3 Comprehensive Metrics
- Performance: Returns, success rates, sample efficiency
- Robustness: Performance under adversarial conditions
- Transfer: Learning curve across tasks
- Catastrophic Forgetting: Retention of previous skills
- Sample Efficiency: Episodes to mastery
7.4 Extensibility Points
- Custom Environments: Implement
ModularEnvironment
- New Adversaries: subclass
Adversary
- Custom Metrics: add to
MetricsCollector
- Curriculum Schedulers: implement
Scheduler interface
- Agent Policies: plug in any RL algorithm
8. Usage Example
# Initialize simulation
config = load_config("curriculum_adversarial.yaml")
trainer = CurriculumAdversarialTrainer(config)
# Train with full curriculum
trainer.train()
# Get comprehensive report
report = trainer.metrics.get_curriculum_report()
print(f"Final performance: {report.final_performance}")
print(f"Transfer efficiency: {report.transfer_efficiency}")
print(f"Best adversarial robustness: {report.max_robustness}")
# Save checkpoint with curriculum state
save_checkpoint({
'agent_state': trainer.agent.state_dict(),
'curriculum_state': trainer.curriculum.state_dict(),
'metrics_history': trainer.metrics.history
})
9. Advanced Features (Optional Extensions)
9.1 Multi-Agent Competition
class CompetitiveEnvironment(ModularEnvironment):
def __init__(self, config):
super().__init__(config)
self.competitors = [create_agent(c) for c in config.competitors]
def step(self, agent_id, action):
# Get competitor actions
comp_actions = {c.id: c.act(self.state) for c in self.competitors}
all_actions = {agent_id: action, **comp_actions}
return super().step(all_actions)
9.2 AutomatedCurriculum Design
class AutoCurriculumDesigner:
"""Uses meta-learning to design optimal curriculum"""
def design_curriculum(self, agent_initialization, target_task):
# Use bandit algorithms or RL to sequence tasks
# Optimize for fastest learning to target
pass
9.3 Diagnostic Toolkit
class DiagnosticTools:
def plot_learning_curves(self, metrics):
"""Visualize performance across all tasks"""
def failure_analysis(self, episodes):
"""Analyze failure modes in adversarial settings"""
def transfer_matrix(self):
"""Show how learning on task A affects task B"""
10. Research Applications
This framework enables research in:
- Curriculum Learning: Optimal task sequencing
- Adversarial RL: Robust policy learning
- Multi-task RL: Skill retention and transfer
- Sample Efficiency: Minimizing data requirements
- Benchmarking: Standardized evaluation protocols
Implementation Notes
- Parallelization: Support vectorized environments for faster data collection
- Checkpointing: Save/restore full curriculum state
- Visualization: Real-time dashboards for metrics
- Heterogeneous Tasks: Support different observation/action spaces
- Restartability: Save/restore at any curriculum stage
This architecture provides a production-ready framework for researching curriculum learning with adversarial dynamics while maintaining full observability into agent capabilities through comprehensive metrics. The modular design allows swapping components for different research questions while maintaining consistent evaluation protocols.