Built as part of the Neuromatch Academy training program.
This repository implements MADDPG (Multi-Agent Deep Deterministic Policy Gradient) in PyTorch for OpenAI Multi-Agent Particle Environments (MPE), supporting training and evaluation across cooperative and competitive scenarios, with saved checkpoints/results and optional GIF export (recommended via Linux/Colab).
Multi-Agent Deep Deterministic Policy Gradient (MADDPG) implementation for Multi-Agent Particle Environments (MPE). This project implements the MADDPG algorithm for training multiple agents in cooperative and competitive multi-agent scenarios.
- Installation
- Quick Start
- Training Models
- Evaluating Models
- Available Environments
- Command Line Arguments
- Understanding Outputs
- Advanced Usage
- Project Structure
- Troubleshooting
- Platform Compatibility
- Python 3.7 or higher
- pip or conda package manager
- Git (for cloning the multiagent-particle-envs repository)
-
Clone or navigate to the project directory:
cd neuromatch_project -
Create a virtual environment (recommended):
python -m venv venv source venv/bin/activate # On macOS/Linux # or venv\Scripts\activate # On Windows
-
Install dependencies:
pip install -r requirements.txt
-
Fix gym version (if needed):
pip uninstall gym pip install gym==0.10.5
-
Install the multiagent package:
pip install -e .
-
Create a conda environment:
conda create -n neuromatch python=3.8 conda activate neuromatch
-
Install dependencies:
conda install --file conda-requirements.txt
-
Install the multiagent package:
pip install -e .
Test that everything is installed correctly:
python -c "import torch; import numpy; from multiagent import scenarios; print('Installation successful!')"Run a short training session to verify everything works:
python main.py --env simple_tag --episode-num 100 --episode-length 25This will:
- Train agents for 100 episodes
- Save results to
results/simple_tag/{N}/where{N}is the next available folder number (1, 2, 3, etc.)- If this is your first run, results will be in
results/simple_tag/1/ - If folders 1-7 already exist, results will be in
results/simple_tag/8/
- If this is your first run, results will be in
- Generate training plots and save the model
After training, evaluate the model. First, check which folder number was created:
ls results/simple_tag/Then evaluate (replace {N} with the actual folder number):
python evaluate.py --env simple_tag --folder {N} --episode-num 10 --episode-length 25For example, if results are in folder 7:
python evaluate.py --env simple_tag --folder 7 --episode-num 10 --episode-length 25This will:
- Load the trained model from
results/simple_tag/{N}/ - Run 10 evaluation episodes with rendering
- Generate evaluation plots
Train a model with default parameters:
python main.py --env simple_tagThis uses default settings:
- 30,000 episodes
- 25 steps per episode
- Learning starts after 50,000 steps
- Model saves every 100 episodes
Train with custom hyperparameters:
python main.py \
--env simple_tag \
--episode-num 10000 \
--episode-length 50 \
--actor-lr 0.001 \
--critic-lr 0.001 \
--batch-size 512 \
--gamma 0.99 \
--tau 0.01Train on different multi-agent scenarios:
# Cooperative spread task
python main.py --env simple_spread
# Adversarial scenario
python main.py --env simple_adversary
# Communication task
python main.py --env simple_speaker_listenerDuring training, you'll see:
- Episode number and cumulative rewards for each agent
- Total reward sum
- Progress updates
Example output:
episode 1: cumulative reward: [-2.5 1.3 -1.2], sum reward: -2.4
episode 2: cumulative reward: [-1.8 2.1 -0.9], sum reward: -0.6
...
After training completes, results are saved in:
results/{env_name}/{run_number}/
├── model.pt # Final trained model
├── model/model_{episode}.pt # Checkpoints (every save_interval episodes)
├── rewards.npy # Reward history (numpy array)
├── maddpg.log # Training log file
└── training result of maddpg solve {env_name}.png # Training plot
Note: The {run_number} is automatically incremented. Each new training run creates a new numbered folder (1, 2, 3, etc.) in the environment's results directory, so your previous runs are preserved.
Evaluate a trained model with visual rendering:
python evaluate.py --env simple_tag --folder 1Parameters:
--env: Environment name (must match training environment)--folder: Folder number in results directory (usually1for first run)--episode-num: Number of evaluation episodes (default: 30)--episode-length: Steps per episode (default: 50)
python evaluate.py \
--env simple_tag \
--folder 1 \
--episode-num 50 \
--episode-length 100The evaluation script:
- Loads the trained model
- Runs episodes with rendering (visual display)
- Saves evaluation plots to the model directory
- Prints cumulative rewards for each episode
Results saved in:
results/{env_name}/{folder}/
└── evaluating result of maddpg solve {env_name}.png
If your goal is a GIF (not realtime visualization), the most reliable workflow is to export frames on Linux (Google Colab or a Linux VM) and generate a GIF there.
The renderer in this repo uses legacy OpenGL calls (glPushMatrix, glBegin, etc.).
On macOS, the OpenGL context is often Core Profile, where these calls are invalid, which can cause rendering to crash.
So for GIF export, prefer Linux.
To prevent rendering in local, the line "env.render()" has been commented in the evaluate.py.
See: docs/GIF_EXPORT_COLAB.md
For generating animated GIFs of agent behavior, use the z_experiments.py module:
from z_experiments import evaluate_model, get_args
# Evaluate and create GIF
args = get_args({'env': 'simple_tag', 'episode_num': 5, 'episode_length': 100})
evaluate_model(args, save_video=True, folder_name='simple_tag')This creates:
- Individual frame images in
frames/directory - Animated GIF in
animation.gif - Copy in
animations/directory
| Environment | Description | Agents | Type |
|---|---|---|---|
simple_tag |
Tag game (chase and evade) | 3 good, 1 adversary | Competitive |
simple_adversary |
Adversarial scenario | 2 good, 1 adversary | Competitive |
simple_spread |
Cooperative spread task | 3 agents | Cooperative |
simple_push |
Cooperative push task | 2 agents | Cooperative |
simple_crypto |
Cryptography task | 2 agents | Competitive |
simple_reference |
Reference scenario | 2 agents | Mixed |
simple_speaker_listener |
Communication task | 2 agents | Cooperative |
simple_world_comm |
World communication | 3 agents | Cooperative |
| Environment | Description |
|---|---|
simple_tag_4_4 |
Tag with 4 agents |
simple_tag_no_adv_sharing |
Tag without adversary sharing |
simple_tag_big_bounds |
Tag with larger boundaries |
simple_tag_colab |
Collaborative tag variant |
simple_tag_goty_edition |
Configurable tag with many parameters |
Each environment has different:
- Number of agents
- Observation spaces
- Action spaces
- Reward structures
- Episode lengths
Check multiagent/scenarios/ for environment-specific details.
| Argument | Type | Default | Description |
|---|---|---|---|
--env |
str | simple_tag_no_adv_sharing |
Environment name |
--episode-length |
int | 25 | Steps per episode |
--episode-num |
int | 30000 | Total training episodes |
--gamma |
float | 0.95 | Discount factor (0-1) |
--buffer-capacity |
int | 1000000 | Replay buffer size |
--batch-size |
int | 1024 | Training batch size |
--actor-lr |
float | 0.01 | Actor learning rate |
--critic-lr |
float | 0.01 | Critic learning rate |
--steps-before-learn |
int | 50000 | Steps before learning starts |
--learn-interval |
int | 100 | Learning frequency (every N steps) |
--save-interval |
int | 100 | Model save frequency (every N episodes) |
--tau |
float | 0.02 | Soft update parameter (0-1) |
| Argument | Type | Default | Description |
|---|---|---|---|
--env |
str | simple_tag_big_bounds |
Environment name |
--folder |
str | 3 |
Results folder number |
--episode-length |
int | 50 | Steps per episode |
--episode-num |
int | 30 | Number of evaluation episodes |
The training script generates a plot showing:
- Individual agent rewards: Each agent's cumulative reward per episode
- Running average: Smoothed reward curve (100-episode window)
File: results/{env}/1/training result of maddpg solve {env}.png
rewards.npy: NumPy array of shape(episodes, num_agents)- Load with:
np.load('rewards.npy') - Contains cumulative rewards for each agent per episode
- Load with:
model.pt: Final trained model (PyTorch state dicts)model/model_{N}.pt: Checkpoints saved during training
maddpg.log: Training log with detailed information- Training progress
- Loss values (if enabled)
- Error messages
Evaluation script generates:
- Reward plots for each agent during evaluation
- File:
results/{env}/{folder}/evaluating result of maddpg solve {env}.png
Use z_batch_train.py for running multiple experiments:
from z_batch_train import run_experiment, get_args
# Run with default args
args = get_args({'env': 'simple_tag'})
run_experiment(args)
# Run with custom world parameters (for goty_edition)
world_args = {
'num_good_agents': 4,
'num_adversaries': 2,
'out_of_bound_punishment': 10,
'hard_boundary': False
}
args = get_args({'env': 'simple_tag_goty_edition'})
run_experiment(args, world_args=world_args)For simple_tag_goty_edition, you can customize:
world_args = {
'num_good_agents': 4, # Number of good agents
'num_adversaries': 2, # Number of adversaries
'num_landmarks': 2, # Number of landmarks
'out_of_bound_punishment': 10, # Penalty for going out of bounds
'hard_boundary': False, # Use soft or hard boundaries
'good_collaborative': True, # Good agents share rewards
'bad_collaborative': False, # Bad agents share rewards
'remove_old_adv_sharing': True # Remove old adversary sharing
}- Create a new file in
multiagent/scenarios/ - Inherit from
BaseScenario - Implement required methods:
make_world(): Create the world and agentsreset_world(): Reset world statereward(): Calculate rewardsobservation(): Generate observations
See existing scenarios for examples.
Key hyperparameters to tune:
- Learning rates (
--actor-lr,--critic-lr): Start with 0.01, try 0.001 or 0.0001 - Batch size (
--batch-size): Larger = more stable, but slower. Try 256, 512, 1024 - Gamma (
--gamma): Discount factor. Higher = long-term thinking. Try 0.9, 0.95, 0.99 - Tau (
--tau): Soft update rate. Lower = slower target network updates. Try 0.01, 0.02, 0.05 - Steps before learn (
--steps-before-learn): More = better initial data. Try 25k, 50k, 100k
neuromatch_project/
├── main.py # Main training script
├── evaluate.py # Model evaluation script
├── MADDPG.py # MADDPG algorithm implementation
├── Agent.py # Individual agent (actor-critic)
├── Buffer.py # Experience replay buffer
├── make_env.py # Environment creation utility
├── z_batch_train.py # Batch training utilities
├── z_experiments.py # Experiment utilities (GIF generation)
├── requirements.txt # pip dependencies
├── conda-requirements.txt # conda dependencies
├── setup.py # Package setup
│
├── multiagent/ # Multi-agent environment package
│ ├── __init__.py
│ ├── core.py # Core classes (World, Agent, Entity)
│ ├── environment.py # MultiAgentEnv class
│ ├── scenario.py # Base scenario class
│ ├── rendering.py # Visualization
│ └── scenarios/ # Environment scenarios
│ ├── simple_tag.py
│ ├── simple_spread.py
│ └── ...
│
├── results/ # Training results
│ └── {env_name}/
│ └── {run_number}/
│ ├── model.pt
│ ├── rewards.npy
│ └── ...
│
└── animations/ # Generated GIFs
Problem: ModuleNotFoundError: No module named 'multiagent'
Solution:
pip install -e .Problem: AttributeError or version-related errors
Solution:
pip uninstall gym gymnasium
pip install gym==0.10.5Problem: Window doesn't open or display errors
Solution:
- For headless evaluation, use
save_video=Trueinz_experiments.py - Install XQuartz if needed:
brew install --cask xquartz
Problem: CUDA errors or GPU not detected
Solution:
- The code automatically uses CPU if CUDA is unavailable
- To force CPU: Modify
MADDPG.pyto setdevice=torch.device('cpu')
Problem: RuntimeError: CUDA out of memory
Solution:
- Reduce
--batch-size(try 256 or 512) - Reduce
--buffer-capacity(try 100000) - Use CPU instead of GPU
Problem: FileNotFoundError when evaluating
Solution:
- Check that the folder number exists:
ls results/{env}/ - Ensure
model.ptexists in the folder - Verify environment name matches training environment
Problem: Training is very slow
Solution:
- Reduce
--episode-numfor testing - Reduce
--episode-length - Disable rendering during training (already disabled by default)
- Use GPU if available
- Check the log file:
results/{env}/{folder}/maddpg.log - Verify all dependencies are installed:
pip list - Test with minimal parameters first
- Check that environment name is correct
- Fully supported
- All dependencies available
- Rendering works with XQuartz (if needed)
- Fully supported
- All dependencies available
- Rendering works natively
- Should work with most features
pywin32removed from requirements (not needed for core functionality)- Rendering may require additional setup
- ✅ Fixed security vulnerabilities (fonttools, idna, requests)
- ✅ Removed platform-specific dependencies (pywin32)
- ✅ Cleaned conda-requirements.txt of conda-specific file paths
- ✅ Refactored main.py for better code structure
- ✅ Added proper error handling
- ✅ Improved cross-platform compatibility
- MADDPG: Multi-Agent Deep Deterministic Policy Gradient
- Actor-Critic: Each agent has an actor (policy) and critic (value function)
- Centralized Training, Decentralized Execution: Training uses global info, execution is local
- MADDPG: Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments
- Multi-Agent Particle Environments: OpenAI Multi-Agent Particle Environments
See LICENSE.txt for details.
When contributing:
- Follow existing code style
- Test on multiple environments
- Update documentation
- Ensure cross-platform compatibility
If you use this code in your research, please cite:
@article{lowe2017multi,
title={Multi-Agent Actor-Critic for Mixed Cooperative-Competitive Environments},
author={Lowe, Ryan and Wu, Yi and Tamar, Aviv and Harb, Jean and Abbeel, Pieter and Mordatch, Igor},
journal={Advances in neural information processing systems},
year={2017}
}Happy Training! 🚀