Deep multi-agent RL: cooperation, competition and leagues
Apply game theory to deep multiagent RL: independent learners and nonstationarity, centralized training with decentralized execution, multiagent credit assignment, VDN, QMIX, MAPPO, and competitive self-play with populations, leagues, and PSRO. Practice locally with PettingZoo.
After this lesson you can
- Formulate cooperation as a Dec-POMDP and competition as a partially observable Markov game.
- Implement IPPO and MAPPO with shared parameters and a centralized critic.
- Implement VDN and QMIX and prove the IGM condition for monotonic mixing.
- Explain counterfactual credit assignment and self-play leagues.
- Evaluate multiagent systems while avoiding common pitfalls.
Before you start
Multiple agents change the problem
Three robots trying to cover three locations cannot be treated as three independent tasks without examining their interactions: one robot’s movement affects the spaces available to the others. An auction combines competition and shared rules; a fleet of vehicles has individual objectives and common constraints; a defender and attacker have different information and capabilities. A single application can contain cooperation within each team and competition between teams.
A cooperative Dec-POMDP specifies global state , local observations , joint actions , transition , and shared reward. Each execution policy depends on local history , not necessarily the full state. A partially observable Markov game allows different rewards per agent and does not assume everyone shares an objective. Information available to a critic during training must be distinguished from information available to the actor when it acts.
The observation protocol must include what can be remembered and communicated. If two robots each see half a room, joining their observations in the actor is equivalent to adding a perfect communication channel. This can be a legitimate centralized baseline, but does not solve the original decentralized task. Training a critic with joint information without providing it to the actor at execution respects that contract. It also matters whether everyone chooses actions simultaneously or one agent sees another’s earlier decision: this changes the information space and thus the possible policies.
For a team with memory, may contain its observations, prior actions, and received messages. If local state is not Markovian, a recurrent network can summarize that history, but its state must reset when a new task begins and persist while the dependency lasts. Training that leaves hidden information in memory between evaluations would use an undeclared advantage. In tasks with agents appearing or disappearing, absent observations and actions need explicit masks.
Independent learners treat other agents’ actions as part of the environment. From agent ’s perspective, the effective transition averages over teammates’ policies. If those policies change during learning, so does that effective transition: the target the table or network tries to fit moves. Old replay can contain data generated by teammates very different from the current ones. Nonstationarity does not mean an independent algorithm always fails, but prevents directly applying stationary-MDP guarantees.
The reward is 4 when both choose the first action, 3 when both choose the second, and 0 when they disagree. Each table updates only the chosen action, at rate , and uses -greedy with random tie-breaking. The curve shows and the counter shows what the other player did. The expected reward of that action is , so it changes as the teammate’s frequency changes. The fixed seed makes the comparison reproducible; it is neither a statistical average nor a convergence guarantee.
The teammate’s frequency is not a fixed hidden parameter that can be estimated once. Their policy itself depends on learned values, which depend on the first agent’s actions. With fast learning, a recent outcome can change both policies at once; with high exploration, a coordinated action periodically receives low rewards when the other explores. If exploration is reduced too early, the team may settle on reward-3 coordination despite a reward-4 alternative. The example is deliberately small: in sequential problems the distributions of visited states also change.
To compare a learned Q table with a target, specify the time window in which opponent frequency was estimated. An average from the start can mix a previous policy with the current one, while a short window has more noise. Curves can chase one another or fluctuate without any single one indicating the cause. Recording teammate policy, joint actions, and reward separately helps distinguish distribution changes from a purely numerical error.
Centralized training, local execution
In centralized training and decentralized execution (CTDE), the critic or mixer can query joint information while fitting policies that later act on local observations. This separation does not turn global information into local knowledge. In MADDPG, for example, a critic can depend on state and joint actions to train decentralized actors; Lowe and colleagues study this approach in cooperative and competitive environments.
Multi-agent credit assignment asks how much an action contributed to the team’s outcome. If everyone receives the same reward, an agent that did nothing may share the prize with the one that solved the problem. COMA compares the value of the observed joint action with a baseline averaging one agent’s alternatives while holding the others’ actions fixed:
The baseline depends on the learned critic and policy; it does not observe the actual outcome of every alternative. Foerster and colleagues explain how to compute it with a centralized critic. A bad critic can produce incorrect attribution; subtraction does not automatically identify a real cause in a system with incomplete information.
The baseline must not depend on the particular action being scored. Averaging alternatives under the policy makes the expectation of multiplied by that baseline zero under usual policy-gradient assumptions. It can therefore reduce variance without changing the ideal gradient. In an approximate implementation, value error, finite samples, and training distribution still matter. Distinguish this baseline from a physical intervention: the world has not been run under each alternative; an estimator has been queried.
Another option is a difference reward: compare global reward with what would have happened in a reference situation without the agent’s contribution. Its interpretation depends on how that situation is constructed. If removing one vehicle also changes everyone else’s route, the contrast no longer isolates one action. The definition of the counterfactual and cost of evaluating it are part of the method, not a visualization detail.
Local values and a joint mixer
Value decomposition in VDN uses . In a sum, choosing for each agent an action maximizing its term also maximizes the sum. VDN trains terms with joint reward; it does not claim each is an individual causal reward.
QMIX replaces the sum with and requires to be nondecreasing in each argument. A hypernetwork receives the state during training and generates nonnegative mixer weights, while each individual utility receives only local history. Let . For any joint action , each component satisfies ; changing components one by one, monotonicity gives
Therefore every combination of local maxima is a global maximum: this is the individual-global consistency property, IGM. If the mixer has flat regions there can be other global maxima that are not maxima of each utility; exact equality of sets should not be claimed without an additional condition. Rashid and colleagues use monotonicity so joint maximization is compatible with local decisions.
The VDN sum and monotonic mix in the figure are mathematical examples, not a fitted network. The third function subtracts the first utility: increasing it worsens joint value and the global maximum moves to , different from . Monotonicity makes choosing actions easier but restricts which tables can be represented. For matrix , changing the first action improves payoff with one action of the second agent and worsens it with the other. No single ordering of the first agent’s utilities can satisfy both strict comparisons through a monotonic mix. This demonstrates a limitation of exact representation, not that no decentralized policy can choose one of the two optimal diagonals.
The hypernetwork need not be monotonic in state: it can produce different mixes for different states. The restriction applies to the output’s dependence on individual utilities when state is fixed. To implement it, weights multiplying utilities are transformed with absolute value or a positive function and combined with nondecreasing activations; biases may have any sign. On differentiation, each product of derivatives along those paths is nonnegative. Adding a negative connection that violates this construction would remove the architectural guarantee.
A local utility value also has no unique scale. A network can compensate for changes in one utility with changes in the mixer while preserving the same joint value. Therefore should not be interpreted as the agent’s exact physical contribution to the reward. The property important for execution is its action ordering, together with the local-information contract. The lab tests separately check reward obtained by greedy actions and the representation that was fitted.
MAPPO and fair comparison
MAPPO adapts PPO to a team with a centralized critic; IPPO uses local information in its critic. Both can share actor parameters and receive an agent identifier to allow different behaviors. Sharing reduces parameter count and exploits experience from multiple agents, but can impose unsuitable symmetry if agents have different capabilities, observations, or incentives. Identity helps break symmetries, though it does not replace information the agent cannot observe.
The PPO objective clips the ratio of new to old probabilities and fits a value function. Normalization quality, number of epochs, inactive-agent masks, and handling of endings affect comparison. Yu and colleagues show PPO variants are strong baselines in several cooperative tasks, not that they win in every configuration. Comparisons should equalize joint environment steps, decisions per agent, seeds, execution information, evaluations, and stopping rules. If an agent dies or is deactivated, its loss mask must exclude nonexistent decisions.
One joint step in a three-agent environment produces three decisions. If one method performs 10,000 joint steps and another 10,000 individual decisions, the former has observed three times as many actions, and comparing them without clarification is misleading. Likewise, one method collecting a centralized trajectory and another using three independent processes may count samples differently. Report both units and compute time, as well as episode count and length.
During evaluation, normalization should use statistics fixed during training, if used; updating it with test data can change the contract. A stochastic policy can be evaluated by sampling or greedily, but state which. An interval over seeds measures training variation under the chosen protocol, while an interval over episodes from one seed measures situation variation for one policy. Mixing the two as if all observations were independent exaggerates the evidence.
Populations and new responses
In population-based self-play, an agent can face historical versions and specialized opponents. This reduces the risk of fitting only the current opponent but does not guarantee robustness against every rival. PSRO maintains an estimated payoff matrix among population policies, calculates a mixture with a meta-solver, and adds approximate responses to that mixture. Its properties depend on matrix and response accuracy; Lanctot and colleagues present the general framework.
In this antisymmetric matrix, self-play against the last action goes from rock to paper, then scissors, then repeats. The historical mixture averages observed actions. PSRO calculates an equilibrium of the restricted population and adds a best response among all three actions. The shown NashConv compares the mixture with all actions in the game, not only those already in the population. In the complete three-action example, zero NashConv certifies equilibrium of that matrix; a large neural-network league usually lacks an exact best response.
A real league payoff matrix is estimated from games, so cells are noisy and can depend on the distribution of maps, starting positions, or versions. A policy beating the latest version may lose against an older one and there need not be a transitive ranking. Saving snapshots and forming a cross-play matrix helps reveal such cycles. It is also useful to separate opponents used to select policies from others reserved for final evaluation.
In PSRO, an approximate response may get stuck in a local optimum or fail to discover a strategy exploiting the whole mixture. Precisely solving the restricted game guarantees something only relative to present policies and estimated payoffs. The figure can calculate true NashConv because it enumerates all three available actions; in a neural-policy space, report bounds or vulnerability against a set of opponents, without calling them exact exploitability unless the best response has actually been solved.
Local lab: values in coordination
The first lab uses two one-step cooperative matrices with three actions per agent. The rewarded corner’s diagonal actions give 8, disagreements involving that action give −12, and other combinations give 0; the second matrix reverses action ordering. Both agents observe which matrix is active. A uniformly generated synthetic buffer contains joint actions and true rewards; since this is a one-step problem, there is no bootstrap or temporal dynamics.
We compare independent networks fitting joint reward to each local value, VDN with a sum, and QMIX with a state-conditioned hypernetwork. Utility parameters are shared and an agent identifier is added. Networks are fitted with 2000 batches of 128 and three seeds. Uniform supervised fitting controls the data distribution and isolates representational capacity; it is not equivalent to comparing full exploration algorithms with replay in sequential tasks.
"""VDN, QMIX e independientes en dos matrices cooperativas de un paso."""
import numpy as np
import torch
from torch import nn
torch.set_num_threads(1)
A=np.array([[8.,-12.,-12.],[-12.,0.,0.],[-12.,0.,0.]],dtype=np.float32)
REWARDS=np.stack((A,A[::-1,::-1].copy()))
class Utility(nn.Module):
def __init__(self):super().__init__();self.net=nn.Sequential(nn.Linear(4,32),nn.ReLU(),nn.Linear(32,3))
def forward(self,state):
ids=torch.eye(2).expand(len(state),-1,-1);s=state[:,None,:].expand(-1,2,-1)
return self.net(torch.cat((s,ids),-1))
class Mixer(nn.Module):
def __init__(self):
super().__init__();self.w1=nn.Linear(2,16);self.b1=nn.Linear(2,8);self.w2=nn.Linear(2,8);self.b2=nn.Sequential(nn.Linear(2,8),nn.ReLU(),nn.Linear(8,1))
def forward(self,q,state):
w1=self.w1(state).abs().reshape(-1,2,8);b1=self.b1(state).reshape(-1,1,8);w2=self.w2(state).abs().reshape(-1,8,1)
h=torch.nn.functional.elu(torch.bmm(q[:,None,:],w1)+b1)
return (torch.bmm(h,w2).squeeze(-1)+self.b2(state)).squeeze(-1)
def fit(method,seed,updates=2000,batch=128):
torch.manual_seed(seed);rng=np.random.default_rng(seed);utility=Utility();mixer=Mixer();params=list(utility.parameters())+(list(mixer.parameters()) if method=='qmix' else []);opt=torch.optim.Adam(params,lr=.001)
for step in range(updates):
state=rng.integers(2,size=batch);actions=rng.integers(3,size=(batch,2));s=torch.nn.functional.one_hot(torch.tensor(state),2).float();a=torch.tensor(actions)
r=torch.tensor(REWARDS[state,actions[:,0],actions[:,1]]);allq=utility(s);chosen=allq.gather(2,a[:,:,None]).squeeze(-1)
if method=='independent':loss=(chosen-r[:,None]).square().mean()
else:
joint=chosen.sum(1) if method=='vdn' else mixer(chosen,s);loss=(joint-r).square().mean()
opt.zero_grad();loss.backward();opt.step()
with torch.no_grad():
s=torch.eye(2);q=utility(s);chosen=q.argmax(-1).numpy();predicted=[]
for state in range(2):
acts=chosen[state];predicted.append({'state':state,'actions':acts.tolist(),'reward':float(REWARDS[state,*acts]),'optimal':float(REWARDS[state].max())})
return {'method':method,'seed':seed,'updates':updates,'results':predicted}npm run lab and open the connection link.results=[fit(method,seed,2000) for method in ("independent","vdn","qmix") for seed in range(3)]
for row in results:print(row)npm run lab and open the connection link.In the described run, independent learners and VDN chose reward-0 actions in all six seed–matrix pairs. QMIX chose the optimal reward-8 action in two of the six cases and reward 0 in the other four. The results show this fit’s sensitivity to initialization and function class; they do not demonstrate general QMIX superiority or that its monotonicity can exactly represent any of these matrices. All three methods receive the same sample distribution and number of updates.
Local lab: IPPO and MAPPO
The second lab uses simple_spread_v4 from MPE2 with PettingZoo’s parallel API. The PettingZoo documentation explains that particle environments moved to MPE2. Here there are three agents, five discrete actions, and shared reward (local_ratio=0); each observation has 18 components and the environment’s centralized state concatenates 54. Each actor receives only its observation and a one-hot identifier. The actor network is shared; IPPO’s local critic receives observation and identifier, whereas MAPPO’s centralized critic receives state and identifier.
Recorded runs use MPE2 1.2.0, PettingZoo 1.27.0, Gymnasium 1.4.0, NumPy 2.5.4, and PyTorch 2.11.0. Preserve versions when repeating the comparison: simple_spread_v4 is not necessarily identical to earlier environment versions.
The 25-step horizon is treated as a finite episode: the advantage is cut at the horizon and no bootstrap is used through reset. Each combination has 12,800 joint steps, 38,400 agent decisions, three seeds, and 20 greedy evaluation episodes on separate seeds. Both methods use the same actor architecture, number of updates, and PPO options. These are small CPU runs, useful to investigate the flow and compare this budget, not a full reproduction of the paper’s benchmarks.
The central state provided by this version contains concatenated observations; it is not permission to send that concatenation to the actor. One-hot identity is added to both local and central inputs so a shared critic can distinguish agents. The policy retains the same local interface in both variants. The environment has three agents throughout the episode, so no dead-agent mask is needed; changing to an environment where agents disappear would require one.
Each evaluation begins with a different seed from those used to create the training environment. A vector of returns per seed is retained to inspect episode dispersion as well as the mean. Per-step reward is the same for the three agents in the chosen configuration; averaging its three copies avoids presenting team return multiplied by three. Treating the 25-step limit as the task horizon is part of the experiment: to estimate a continuous process interrupted by an external limit instead, bootstrap from the final observation rather than use this mask.
"""PPO compartido con crítico local o central en MPE2 Simple Spread."""
import json,random
import numpy as np
import torch
from torch import nn
from torch.distributions import Categorical
from mpe2 import simple_spread_v4
torch.set_num_threads(1)
N=3;H=25
def env():return simple_spread_v4.parallel_env(N=N,local_ratio=0.,max_cycles=H,continuous_actions=False)
def act_input(obs):return np.concatenate((np.stack([obs[f'agent_{i}'] for i in range(N)]),np.eye(N,dtype=np.float32)),axis=1).astype(np.float32)
def crit_input(obs,state,central):
return np.concatenate((np.tile(state,(N,1)),np.eye(N,dtype=np.float32)),axis=1).astype(np.float32) if central else act_input(obs)
def net(d,o):return nn.Sequential(nn.Linear(d,128),nn.Tanh(),nn.Linear(128,128),nn.Tanh(),nn.Linear(128,o))
def evaluate(actor,seed,episodes=20):
e=env();scores=[]
for ep in range(episodes):
obs,_=e.reset(seed=seed+ep);total=0.
while e.agents:
with torch.no_grad():actions=actor(torch.tensor(act_input(obs))).argmax(-1).numpy()
obs,rewards,term,trunc,_=e.step({f'agent_{i}':int(actions[i]) for i in range(N)});total+=sum(rewards.values())/N
scores.append(total)
e.close();return scores
def train(central,seed,steps=51200):
random.seed(seed);np.random.seed(seed);torch.manual_seed(seed);e=env();obs,_=e.reset(seed=seed);state=e.state()
actor=net(21,5);critic=net(57 if central else 21,1);opt=torch.optim.Adam(list(actor.parameters())+list(critic.parameters()),lr=3e-4,eps=1e-5)
horizon=200;updates=steps//horizon;completed=0
for update in range(updates):
ob=[];ci=[];acts=[];logp=[];values=[];rewards=[];ends=[]
for t in range(horizon):
x=torch.tensor(act_input(obs));cx=torch.tensor(crit_input(obs,state,central))
with torch.no_grad():dist=Categorical(logits=actor(x));a=dist.sample();lp=dist.log_prob(a);v=critic(cx).squeeze(-1)
nxt,rew,term,trunc,_=e.step({f'agent_{i}':int(a[i]) for i in range(N)})
done=all(term.values()) or all(trunc.values());r=np.array([rew[f'agent_{i}'] for i in range(N)],dtype=np.float32)
ob.append(x);ci.append(cx);acts.append(a);logp.append(lp);values.append(v);rewards.append(torch.tensor(r));ends.append(float(done))
if done:completed+=1;obs,_=e.reset();state=e.state()
else:obs=nxt;state=e.state()
with torch.no_grad():last_v=critic(torch.tensor(crit_input(obs,state,central))).squeeze(-1)
values=torch.stack(values);rewards=torch.stack(rewards);ends=torch.tensor(ends);adv=torch.zeros_like(rewards);last=torch.zeros(N)
for t in reversed(range(horizon)):
next_v=last_v if t==horizon-1 else values[t+1];mask=1-ends[t]
delta=rewards[t]+.99*mask*next_v-values[t];last=delta+.99*.95*mask*last;adv[t]=last
returns=adv+values;advantages=(adv-adv.mean())/(adv.std(unbiased=False)+1e-8)
ob=torch.stack(ob);ci=torch.stack(ci);acts=torch.stack(acts);logp=torch.stack(logp)
for _ in range(4):
dist=Categorical(logits=actor(ob));ratio=(dist.log_prob(acts)-logp).exp();v=critic(ci).squeeze(-1)
loss=-torch.minimum(ratio*advantages,ratio.clamp(.8,1.2)*advantages).mean()+.5*(v-returns).square().mean()-.01*dist.entropy().mean()
if not torch.isfinite(loss):raise FloatingPointError('pérdida no finita')
opt.zero_grad();loss.backward();nn.utils.clip_grad_norm_(list(actor.parameters())+list(critic.parameters()),.5);opt.step()
e.close();scores=evaluate(actor,10000+100*seed)
return {'method':'mappo' if central else 'ippo','seed':seed,'env_steps':updates*horizon,'agent_steps':updates*horizon*N,'episodes_train':completed,'returns':scores,'mean':float(np.mean(scores))}npm run lab and open the connection link.from pathlib import Path
path=Path("mappo-results.jsonl")
previous=[json.loads(line) for line in path.read_text(encoding="utf8").splitlines() if line.strip()] if path.exists() else []
assert all(x["env_steps"]==12800 for x in previous)
done={(r["method"],r["seed"]) for r in previous}
for central in (False,True):
for seed in range(3):
method="mappo" if central else "ippo"
if (method,seed) in done: continue
row=train(central,seed,12800)
with path.open("a",encoding="utf8") as f:f.write(json.dumps(row)+"\n");f.flush()
print(row,flush=True)npm run lab and open the connection link.In our run, mean IPPO evaluation returns for seeds 0, 1, and 2 were −49.77, −39.20, and −62.63; MAPPO’s were −56.27, −46.24, and −45.72. Means across seeds were −50.53 and −49.41 respectively. With local_ratio=0, reward is the negative of minimum distances to objectives and excludes the local collision penalty; a less negative return is better under that metric. With three seeds and one configuration, one cannot conclude that either variant generally dominates; seed differences show appreciable variation. The 20 evaluations per seed correspond to one trained policy and do not replace 20 independent training runs.
An additional check is to evaluate each policy with different teammates or swapped identities, if the environment permits. Here only three copies of the same shared actor are evaluated, so compatibility with outside agents has not been measured. State coverage, collisions, and distance distributions could also clarify what behavior produces a given reward sum. These indicators cannot be reconstructed from final return and should be recorded during a new campaign if the question requires distinguishing them.
Exercises
Step 1 of 3. What is known about each utility at a local maximum?
mix(q, state, params). q has shape (B,2), state shape (B,2); params contains w1 (2,4), b1 (4,), h1 (2,2), c1 (2,), w2 (2,2), b2 (2,), w3 (2,1), b3 (1,). Compute W₁ = abs(state @ w1 + b1), reshaped as (B,2,2); hidden bias state @ h1 + c1; W₂ = abs(state @ w2 + b2); final bias state @ w3 + b3. The hidden layer is ELU(q @ W₁ + bias) and output is its product with W₂ plus final bias. Return a vector of length B.import numpy as np
def mix(q, state, params):
pass