Markov Games
Markov games extend MDPs to multi-agent settings, where state transitions and rewards depend simultaneously on the concurrent actions of all participants.
Why Does This Exist?
In classical single-agent reinforcement learning, the environment is formalized as a Markov Decision Process (MDP). An MDP guarantees environmental stationarity: the transition probability and reward depend solely on the current state and the lone agent's action . Under this assumption, the Bellman optimality equation ensures that a stationary optimal policy always exists and can be discovered by greedy value iteration: .
However, as soon as two or more learning agents operate within the same shared environment—such as autonomous vehicles navigating an intersection, robotic swarms coordinating warehouse logistics, or competing financial algorithms—the single-agent MDP foundation shatters:
- Non-Stationarity: From the perspective of any individual agent , the environment appears non-stationary. As co-players and opponents continuously update their respective policies , the observed transition dynamics shift underfoot. An action that led to high rewards yesterday results in catastrophic failure today because other agents altered their behaviors.
- Breakdown of the Greedy Max Operator: An agent cannot unilaterally choose to "maximize" its return. The outcome of any action depends entirely on what concurrent choices other agents make at the exact same timestep.
- Strategic Interdependence: Agents may cooperate (sharing rewards), compete (zero-sum payoffs), or engage in general-sum mixed-motive interactions requiring mutual coordination or negotiated compromise.
Markov games (first formulated as stochastic games by mathematician Lloyd Shapley in 1953, and introduced to reinforcement learning by Michael Littman in 1994) resolve these challenges. By integrating dynamic programming with game theory, Markov games provide the rigorous mathematical framework for Multi-Agent RL. They replace unilateral maximization with game-theoretic solution concepts—such as the Nash equilibrium and Minimax value—enabling agents to learn stable, mutual best-response strategies.
Think of It Like This
Upgrading from a Solo Simulator to a Multiplayer Traffic Grid
Picture practicing your driving skills in a solo closed-track simulator.
In the solo simulator (single-agent MDP), you are the only car on the track. The physics engine is static and passive. If you turn the steering wheel 30 degrees to the right at 40 mph, your car deterministically glides into the right lane. You can run hundreds of trials, find the exact optimal braking point before each corner, and lock in a single deterministic line. The track will never swerve into you or react to your maneuvers.
Now, imagine taking that exact vehicle onto a busy, un-signaled four-way city intersection occupied by three other human drivers (a Markov game).
You approach the intersection at the same moment as the cross-traffic vehicle. You cannot predict your car's next physical state simply by looking at your own accelerator pedal. If you step on the gas while the cross-traffic driver also steps on the gas, the next state is a high-speed T-bone collision. If both of you slam on the brakes out of extreme caution, you idle indefinitely. If you advance while the other yields, you both safely proceed.
Your steering angle alone no longer dictates reality. The state of the intersection evolves according to the joint vector of all four drivers' pedals and wheels. To avoid gridlock or death, you cannot treat the other cars as inert roadside rocks; you must model their intentions and converge toward shared behavioral conventions (game-theoretic equilibria).
Where the analogy stops: Human drivers rely on eye contact, horn taps, and social traffic conventions. In a formal Markov game, agents execute mathematical policies , and equilibria are computed through matrix-payoff game solvers (such as linear programs or support enumeration) over discounted value functions.
How It Actually Works
Formal Mathematical Definition and Joint Spaces
A Markov game (stochastic game) is formally defined as a tuple:
where:
- : The number of participating agents, indexed by .
- : The shared environmental state space.
- : The individual action space for each agent . The Cartesian product defines the joint action space: A joint action vector at timestep is denoted .
- : The joint transition probability function. The probability of transitioning to state depends on the previous state and the full joint action :
- : The individual reward function for agent . Notice that agent 's reward is determined not just by its own action , but by the concurrent joint action of all agents.
- : The temporal discount factor for future rewards.
Joint Value Functions and Nash Equilibria
Each agent chooses actions according to a stochastic policy . Under decentralized execution, the joint policy is the product of individual policies:
The state-value function for agent under joint policy is the expected discounted cumulative return:
The joint action-value function satisfies the multi-agent Bellman equation:
Because all agents' rewards and transitions are coupled, optimal policies cannot be defined unilaterally. Instead, multi-agent reinforcement learning seeks a Markov Perfect Nash Equilibrium.
A joint policy is a Nash equilibrium if for every agent and every state :
where denotes the joint strategy of all agents other than agent . At equilibrium, no agent can unilaterally increase its expected return by deviating to another policy, assuming all other agents hold their strategies fixed.
Game Classes: Zero-Sum vs. General-Sum
The structure and computational tractability of a Markov game depend heavily on the alignment of reward functions:
-
Two-Player Zero-Sum Games ():
- Total conflict: Agent 1's gain is strictly Agent 2's loss.
- Von Neumann's Minimax Theorem guarantees that every state possesses a unique minimax value:
- Solvable in polynomial time via linear programming at each Bellman update (e.g., Littman's Minimax-Q algorithm).
-
Fully Cooperative Games ():
- Agents share a single identical team reward.
- Reduces to a Multi-Agent MDP (M-MDP) or Dec-POMDP, where agents coordinate on Pareto-optimal joint actions without strategic adversarial counter-play.
-
General-Sum Games (Arbitrary Rewards):
- Agents have distinct, non-zero-sum preferences (e.g., traffic merging or negotiations).
- Multiple disparate Nash equilibria often coexist (the equilibrium selection problem).
- Computing a Nash equilibrium in general-sum games is PPAD-complete (Polynomial Parity Arguments on Directed graphs), explaining why scalable deep MARL algorithms rely on function approximation and decentralized execution frameworks (like MADDPG, MAPPO, or QMIX).
Worked numerical example
Let us trace a concrete 2-player stochastic game on a 2-state grid:
- State Space:
- State : Start state (non-terminal).
- State : Terminal goal state ().
- Action Spaces:
- Agent 1: (Up, Down).
- Agent 2: (Left, Right).
- Transitions and Immediate Payoffs:
- (Coordinated Exit): Transitions to with probability . Payoffs: , .
- (Collision): State remains with probability . Payoffs: , .
- (Collision): State remains with probability . Payoffs: , .
- (Safe Alternate Route): Transitions to with probability . Payoffs: , .
- Discount Factor: .
- Current Value Estimates: Suppose current estimates are and .
Step 1: Compute Joint Action-Values
Using the multi-agent Bellman equation:
By symmetry, for all joint actions.
Step 2: Form the Matrix Payoff Game at State
At state , the Q-values form the following symmetric bimatrix game :
| Agent 1 \ Agent 2 | (Left) | (Right) |
|---|---|---|
| (Up) | ||
| (Down) |
Step 3: Evaluate Nash Equilibria
-
Pure Strategy Nash Equilibria:
- Pair : If Agent 2 plays , Agent 1's best response is (). If Agent 1 plays , Agent 2's best response is (). This is a pure Nash equilibrium with payoff (Pareto-dominant).
- Pair : If Agent 2 plays , Agent 1's best response is (). If Agent 1 plays , Agent 2's best response is (). This is also a pure Nash equilibrium with payoff (risk-dominant).
-
Mixed Strategy Nash Equilibrium: Let Agent 1 play with probability and with probability .
Let Agent 2 play with probability and with probability .For Agent 2 to randomize between and , the expected payoffs must be equal:
Equating them:
By symmetry:
Under this mixed equilibrium, both agents achieve an expected return of:
If both agents coordinate on the Pareto-dominant pure equilibrium , the updated state value for state improves from to .
Code
import numpy as np
class MarkovGameSimulator: """Simulates a 2-player stochastic Markov game with joint action transitions,
payoff matrices, and Nash equilibrium evaluation. """
def __init__(self, gamma: float = 0.90) -> None: self.gamma = gamma self.actions_p1 = ["U", "D"] self.actions_p2 = ["L", "R"]
def compute_joint_q_values( self, v_s0: float, v_goal: float = 0.0 ) -> tuple[np.ndarray, np.ndarray]: """Computes Q-matrices for Agent 1 and Agent 2 at non-terminal state s_0.
Joint Actions: (U, L): Coordinated exit -> R=(+4.0, +4.0), s' = s_goal (U, R): Collision -> R=( 0.0, 0.0), s' = s_0 (D, L): Collision -> R=( 0.0, 0.0), s' = s_0 (D, R): Suboptimal exit -> R=(+2.0, +2.0), s' = s_goal """ q1 = np.zeros((2, 2), dtype=np.float64) q2 = np.zeros((2, 2), dtype=np.float64)
# Joint action (U, L) -> Index (0, 0) q1[0, 0] = 4.0 + self.gamma * v_goal q2[0, 0] = 4.0 + self.gamma * v_goal
# Joint action (U, R) -> Index (0, 1) q1[0, 1] = 0.0 + self.gamma * v_s0 q2[0, 1] = 0.0 + self.gamma * v_s0
# Joint action (D, L) -> Index (1, 0) q1[1, 0] = 0.0 + self.gamma * v_s0 q2[1, 0] = 0.0 + self.gamma * v_s0
# Joint action (D, R) -> Index (1, 1) q1[1, 1] = 2.0 + self.gamma * v_goal q2[1, 1] = 2.0 + self.gamma * v_goal
return q1, q2
def find_pure_nash_equilibria( self, q1: np.ndarray, q2: np.ndarray ) -> list[tuple[str, str, float, float]]: """Identifies all pure strategy Nash equilibria in the 2x2 matrix game.""" pure_equilibria: list[tuple[str, str, float, float]] = []
for i, a1 in enumerate(self.actions_p1): for j, a2 in enumerate(self.actions_p2): # Check if a1 is best response to a2: q1[i, j] >= q1[k, j] for all k is_br_p1 = bool(np.all(q1[i, j] >= q1[:, j])) # Check if a2 is best response to a1: q2[i, j] >= q2[i, k] for all k is_br_p2 = bool(np.all(q2[i, j] >= q2[i, :]))
if is_br_p1 and is_br_p2: pure_equilibria.append( (a1, a2, float(q1[i, j]), float(q2[i, j])) )
return pure_equilibria
def compute_mixed_nash_equilibrium( self, q1: np.ndarray, q2: np.ndarray ) -> tuple[float, float, float, float]: """Computes mixed strategy Nash equilibrium (p for U, q for L) and expected payoffs.""" # Condition for Agent 2: E[Q2|L] == E[Q2|R] denom_p = (q2[0, 0] - q2[1, 0]) - (q2[0, 1] - q2[1, 1]) p = float((q2[1, 1] - q2[1, 0]) / denom_p)
# Condition for Agent 1: E[Q1|U] == E[Q1|D] denom_q = (q1[0, 0] - q1[0, 1]) - (q1[1, 0] - q1[1, 1]) q = float((q1[1, 1] - q1[0, 1]) / denom_q)
# Expected equilibrium returns v1_mixed = float( p * q * q1[0, 0] + p * (1 - q) * q1[0, 1] + (1 - p) * q * q1[1, 0] + (1 - p) * (1 - q) * q1[1, 1] ) v2_mixed = float( p * q * q2[0, 0] + p * (1 - q) * q2[0, 1] + (1 - p) * q * q2[1, 0] + (1 - p) * (1 - q) * q2[1, 1] )
return p, q, v1_mixed, v2_mixed
if __name__ == "__main__": np.set_printoptions(precision=4, suppress=True)
sim = MarkovGameSimulator(gamma=0.90)
# Initial state values from the worked numerical example v_s0_initial = 2.00 v_goal = 0.00
# Step 1: Compute joint Q-values q1, q2 = sim.compute_joint_q_values(v_s0=v_s0_initial, v_goal=v_goal)
# Step 2: Solve for pure strategy Nash equilibria pure_eqs = sim.find_pure_nash_equilibria(q1, q2)
# Step 3: Solve for mixed strategy Nash equilibrium p_mix, q_mix, v1_mix, v2_mix = sim.compute_mixed_nash_equilibrium(q1, q2)
print(f"Q1(s_0, (U, L)): {q1[0, 0]:.2f}") # -> Q1(s_0, (U, L)): 4.00
print(f"Q1(s_0, (U, R)): {q1[0, 1]:.2f}") # -> Q1(s_0, (U, R)): 1.80
print(f"Q1(s_0, (D, L)): {q1[1, 0]:.2f}") # -> Q1(s_0, (D, L)): 1.80
print(f"Q1(s_0, (D, R)): {q1[1, 1]:.2f}") # -> Q1(s_0, (D, R)): 2.00
print(f"Pure Nash Equilibria count: {len(pure_eqs)}") # -> Pure Nash Equilibria count: 2
print( f"Pareto-Dominant Equilibrium: ({pure_eqs[0][0]}, {pure_eqs[0][1]}) with payoffs ({pure_eqs[0][2]:.2f}, {pure_eqs[0][3]:.2f})" ) # -> Pareto-Dominant Equilibrium: (U, L) with payoffs (4.00, 4.00)
print( f"Risk-Dominant Equilibrium: ({pure_eqs[1][0]}, {pure_eqs[1][1]}) with payoffs ({pure_eqs[1][2]:.2f}, {pure_eqs[1][3]:.2f})" ) # -> Risk-Dominant Equilibrium: (D, R) with payoffs (2.00, 2.00)
print( f"Mixed Nash Equilibrium: p(U)={p_mix:.4f}, q(L)={q_mix:.4f}, V1={v1_mix:.4f}" ) # -> Mixed Nash Equilibrium: p(U)=0.0833, q(L)=0.0833, V1=1.9833
# Assert correctness against worked example assert np.isclose(q1[0, 0], 4.00, atol=1e-2) assert np.isclose(q1[0, 1], 1.80, atol=1e-2) assert np.isclose(q1[1, 0], 1.80, atol=1e-2) assert np.isclose(q1[1, 1], 2.00, atol=1e-2) assert len(pure_eqs) == 2 assert pure_eqs[0][:2] == ("U", "L") assert pure_eqs[1][:2] == ("D", "R") assert np.isclose(p_mix, 1 / 12, atol=1e-3) assert np.isclose(q_mix, 1 / 12, atol=1e-3) assert np.isclose(v1_mix, 1.9833, atol=1e-3)Watch Out For
Assuming Environment Stationarity by Factoring Transition Dynamics Independently
The most frequent architectural trap in multi-agent reinforcement learning is applying independent single-agent algorithms (like Independent Q-Learning, IQL) directly to a multi-agent environment by treating other agents as static background noise.
Practitioners assume that agent can learn using a local transition model and a scalar Q-function . In reality:
- The true transition probability is strictly coupled to the actions of all other agents.
- As co-players learn and adapt their policies , the marginal transition distribution shifts continuously:
- Because changes at every training epoch , the Markov property is completely violated from the perspective of agent . Experience collected in earlier replay batches no longer reflects the true underlying transition dynamics, causing severe policy oscillations, policy chasing, and failure to converge.
The Fix: Model the multi-agent nature explicitly:
- Centralized Training with Decentralized Execution (CTDE): Use architectures like MADDPG, MAPPO, or QMIX. During training, the critic network evaluates joint action-values using global information, while decentralized actor networks execute individual policies using local observations during deployment.
- Opponent Modeling: Explicitly model the predicted policy distribution of other agents to marginalize transitions accurately.
- Equilibrium-Based Value Backups: When operating in small discrete games, employ Minimax-Q or Nash-Q learning to backup values based on game-theoretic equilibria rather than myopic single-agent greedy max operators.
The Quick Version
- Multi-Agent Generalization of MDPs: Markov games formalize environments with concurrent decision-makers, where state transitions and individual rewards depend on the full joint action vector .
- Inherent Non-Stationarity: Treating co-players as part of the environment violates the Markov property because changing policies continuously alter perceived transition dynamics.
- Nash Equilibrium Replaces Max: Unilateral maximization () is invalid; agents instead seek Markov Perfect Nash Equilibria where no agent can unilaterally improve their return by altering their strategy.
- Game Classes Dictate Complexity: Two-player zero-sum games possess unique minimax values solvable via linear programming, while general-sum games admit multiple equilibria whose computation is PPAD-complete.