Prisoner's Dilemma: Noise, Tit-for-Tat, and Forgiveness
One accidental defection turns unforgiving tit-for-tat into a prisoner's dilemma revenge spiral. Forgive some of those slips and cooperation holds.
Level: Advanced
Feedback Loops
Understand the balancing and reinforcing feedback loops that drive system behavior and create complex dynamics in systems thinking.
Take the QuizSystem Archetypes
Learn recurring structural patterns like Limits to Growth, Fixes That Fail, and Tragedy of the Commons, plus high-leverage interventions.
Take the QuizPrisoner's dilemma: noise, tit-for-tat, and forgiveness
Two players choose to cooperate or defect every round. In one meeting defection is dominant, so the Nash equilibrium pays both less than mutual cooperation. Tit-for-tat copies the last move it saw, and a noisy channel sometimes flips that move. Forgiveness is the only knob between the two main runs: zero lets one accident echo into a feud, and a modest chance of letting it go absorbs the same flips.
from tys import probe, progress
Moves are integers so a noisy trembling hand is a bit-flip: 1 - move.
COOPERATE, DEFECT = 1, 0
Each classic strategy plays a tit-for-tat partner under the same shocks. A full round-robin is a later, larger model; this lineup is the comparison.
LINEUP = (
("tft", "tft_payoff"),
("generous-tft", "generous_tft_payoff"),
("always-defect", "always_defect_payoff"),
("grudger", "grudger_payoff"),
)
class Player:One strategy, one round of memory. kind picks the rule.
generous-tft is tit-for-tat softened by forgiveness: after a seen
defection it still cooperates with that probability. grudger cooperates
until the first seen defection, then defects forever. always-defect
never considers the partner. Memory stores the move that arrived, after
noise, not the move the partner meant to send.
def __init__(self, name: str, kind: str, forgiveness: float):
self.name = name
self.kind = kind
self.forgiveness = forgiveness
self.last_seen = COOPERATE # round 1 gives the partner the benefit of the doubt
self.grudge = False
def decide(self, rng) -> int:
if self.kind == "always-defect":
return DEFECT
if self.kind == "grudger":
return DEFECT if self.grudge else COOPERATETit-for-tat, generous or not: copy cooperation, retaliate against a slip.
if self.last_seen == COOPERATE:
return COOPERATEGenerous tit-for-tat draws only here, and only from the policy RNG.
if self.kind == "generous-tft" and rng.random() < self.forgiveness:
return COOPERATE
return DEFECT
def observe(self, partner_move: int) -> None:
self.last_seen = partner_move
if partner_move == DEFECT:
self.grudge = True
def simulate(cfg: dict):
"""Play a noisy repeated prisoner's dilemma, or a short strategy lineup."""
import random
import simpy
env = simpy.Environment()
seed = int(cfg.get("seed", 0))
The payoff matrix. A real dilemma needs T > R > P > S (defecting always tempts) and 2R > T + S (taking turns exploiting each other cannot beat honest mutual cooperation). The classic numbers do both. Read them per player, per round:
R = cfg["reward"] # both cooperate — the prize each side earns
S = cfg["sucker"] # you cooperate, they defect — the sucker's payoff
T = cfg["temptation"] # you defect, they cooperate — the temptation
P = cfg["punishment"] # both defect — mutual punishment
noise = float(cfg["noise"]) # chance a chosen move is flipped in transit
rounds = int(cfg["rounds"]) # length of the repeated game, the shadow of the future
forgiveness = float(cfg["forgiveness"]) # the knob: 0 is a pure grudge
compare = bool(cfg.get("compare_strategies", False))
def payoff(mine: int, theirs: int) -> int:T > R and P > S, so defecting beats cooperating against either reply.
if mine == COOPERATE:
return R if theirs == COOPERATE else S
return T if theirs == COOPERATE else P
def fresh_rngs():Two streams from one seed. Noise is drawn once per player per round, in player order, and never shares a stream with forgiveness. Changing forgiveness — or which strategy is sitting in the seat — cannot move the accidents.
return random.Random(seed), random.Random(seed + 1)
done = env.event()
def one_round(players, noise_rng, policy_rng):Simultaneous choice. Both players wake on one event and commit from their own memory. Neither can peek at the other's move this round.
decision = env.event()
committed: dict[str, int] = {}
slips = 0
def act(player: Player):
nonlocal slips
yield decision
intended = player.decide(policy_rng)
if noise_rng.random() < noise:
slips += 1
committed[player.name] = 1 - intended
else:
committed[player.name] = intended
movers = [env.process(act(p)) for p in players]
decision.succeed()
yield env.all_of(movers)
moves = [committed[p.name] for p in players]
for i, player in enumerate(players):
player.observe(moves[1 - i])
scores = [payoff(moves[i], moves[1 - i]) for i in range(2)]
return moves, scores, slips
def duo():Both seats run generous tit-for-tat. Forgiveness 0 is pure tit-for-tat.
players = [
Player("A", "generous-tft", forgiveness),
Player("B", "generous-tft", forgiveness),
]
noise_rng, policy_rng = fresh_rngs()
coop_moves = 0
total_moves = 0
cumulative = 0.0
first_defection = None
accidental_flips = 0
for r in range(rounds):
step = env.process(one_round(players, noise_rng, policy_rng))
yield step
moves, scores, slips = step.value
accidental_flips += slips
joint = scores[0] + scores[1]
cumulative += joint
coop_moves += moves[0] + moves[1]
total_moves += 2
if first_defection is None and DEFECT in moves:
first_defection = r
Three probes. cooperation_rate is the fork: one run craters,
the other holds. round_payoff is the joint score this round
(6 mutual cooperation, 2 the Nash trap, 5 one side
exploited). cumulative_payoff turns that gap into lost welfare.
probe("cooperation_rate", r, coop_moves / total_moves)
probe("round_payoff", r, joint)
probe("cumulative_payoff", r, cumulative)
pct = int(100 * (r + 1) / rounds)
if first_defection == r:
progress(pct, "an accidental defection just landed")
elif r + 1 == rounds:
progress(100, "the repeated game is over")
else:
progress(pct)
yield env.timeout(1)
final_rate = coop_moves / total_movescooperation_survived is the regime the tests lock: above 0.75 the
pair is still mostly cooperating; below it, the echo has won.
return {
"first_defection_round": first_defection,
"accidental_flips": accidental_flips,
"final_cooperation_rate": final_rate,
"final_avg_payoff": cumulative / (2 * rounds),
"cooperation_survived": final_rate > 0.75,
}
def lineup():Same shocks every match: each strategy faces a fresh tit-for-tat partner, and both RNGs are reseeded so the flips line up.
totals = {name: 0.0 for _, name in LINEUP}
total_steps = rounds * len(LINEUP)
step_i = 0
for kind, probe_name in LINEUP:
players = [
Player("A", kind, forgiveness),
Player("B", "tft", 0.0),
]
noise_rng, policy_rng = fresh_rngs()
running = 0.0
for r in range(rounds):
step = env.process(one_round(players, noise_rng, policy_rng))
yield step
_moves, scores, _slips = step.value
running += scores[0]
totals[probe_name] = runningRunning mean payoff for the strategy under test, not the partner.
probe(probe_name, r, running / (r + 1))
step_i += 1
pct = int(100 * step_i / total_steps)
if step_i == total_steps:
progress(100, "four strategies, one noisy partner")
else:
progress(pct)
yield env.timeout(1)
means = {name: totals[name] / rounds for _, name in LINEUP}
generous = means["generous_tft_payoff"]
return {
"tft_mean": means["tft_payoff"],
"generous_tft_mean": generous,
"always_defect_mean": means["always_defect_payoff"],
"grudger_mean": means["grudger_payoff"],
"generous_leads": generous > max(
means["tft_payoff"],
means["always_defect_payoff"],
means["grudger_payoff"],
),
}
def referee():
if compare:
summary = yield from lineup()
else:
summary = yield from duo()
done.succeed(summary)
env.process(referee())
env.run(until=done)
return done.value
def requirements():
return {"external": ["simpy==4.1.1"]}
# grudge.yaml — the default, just on the failing side of the repeated game.
# Pure tit-for-tat: forgiveness is 0. Both players cooperate until the noisy
# channel flips a move at round 40. With nothing to absorb that slip, the
# retaliation echo drags cooperation down to about one half.
reward: 3
sucker: 0
temptation: 5
punishment: 1
noise: 0.04
rounds: 300
forgiveness: 0.0
seed: 4
Share of moves so far that were cooperation. Both runs stay at 1 until the shared slip at round 40; the grudge then drifts toward one half while forgiveness 0.22 climbs back near 0.85.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 0.51, mean 0.67, median 0.58, max 1.00, σ 0.17 |
Joint score this round. 6 is mutual cooperation, the social optimum. 2 is mutual defection, the Nash trap. 5 means one player exploited the other.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 2.00, mean 4.40, median 5.00, max 6.00, σ 1.66 |
| Metric | Value |
|---|---|
| first_defection_round | 40.00 |
| accidental_flips | 29.00 |
| final_cooperation_rate | 0.51 |
| final_avg_payoff | 2.20 |
| cooperation_survived | false |
# forgiving.yaml — the contrast. Identical to grudge.yaml except forgiveness
# (0.0 -> 0.22). That is the narrowest step that still keeps cooperation
# above the survival line on every seed checked. The same accidental flips
# are absorbed instead of echoed.
reward: 3
sucker: 0
temptation: 5
punishment: 1
noise: 0.04
rounds: 300
forgiveness: 0.22
seed: 4
Share of moves so far that were cooperation. Both runs stay at 1 until the shared slip at round 40; the grudge then drifts toward one half while forgiveness 0.22 climbs back near 0.85.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 0.84, mean 0.89, median 0.87, max 1.00, σ 0.05 |
Joint score this round. 6 is mutual cooperation, the social optimum. 2 is mutual defection, the Nash trap. 5 means one player exploited the other.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 2.00, mean 5.63, median 6.00, max 6.00, σ 0.77 |
| Metric | Value |
|---|---|
| first_defection_round | 40.00 |
| accidental_flips | 29.00 |
| final_cooperation_rate | 0.84 |
| final_avg_payoff | 2.81 |
| cooperation_survived | true |
# lineup.yaml — a side comparison, not the regime contrast. Same payoffs,
# noise, and seed as the two-player runs. Four strategies each play a
# tit-for-tat partner, and every match reseeds the same noise stream.
# Generous tit-for-tat finishes ahead; the grudger and always-defect do not.
# A full round-robin is a later experiment.
compare_strategies: true
reward: 3
sucker: 0
temptation: 5
punishment: 1
noise: 0.04
rounds: 300
forgiveness: 0.22
seed: 4
Running average payoff of pure tit-for-tat against a tit-for-tat partner. The same noise that starts the grudge spiral keeps this score well below the cooperative prize of 3.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 2.18, mean 2.47, median 2.29, max 3.05, σ 0.31 |
Running average payoff of generous tit-for-tat against a tit-for-tat partner, using the same forgiveness as the Forgiving run. Absorbing accidents holds the score nearest 3.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 2.63, mean 2.77, median 2.70, max 3.05, σ 0.13 |
Running average payoff of always-defect against tit-for-tat. The opening exploitation pays once, then retaliation leaves the score near mutual punishment of 1.
| Samples | 300 @ 0.00–299.00 |
|---|---|
| Values | min 1.07, mean 1.30, median 1.29, max 5.00, σ 0.26 |
| Metric | Value |
|---|---|
| tft_mean | 2.21 |
| generous_tft_mean | 2.70 |
| always_defect_mean | 1.35 |
| grudger_mean | 1.61 |
| generous_leads | true |
- What sets the tipping point?
- Two boundaries. In a single round T > R > P > S makes defection dominant, so the Nash equilibrium is mutual defection even though mutual cooperation pays more, and 2R > T + S so taking turns exploiting each other cannot beat honest cooperation. Once the game repeats under 4% noise, forgiveness is the boundary that moves. At 0, cooperation ends between about 0.33 and 0.68 on every seed checked. At 0.22 it stays above 0.75 on all 60 seeds checked, with a floor near 0.77. That is narrower than the textbook generosity of 1/3, which is 1 - (T - R) / (R - S) and also holds, with a higher floor near 0.85. A few percent of forgiveness can recover on one seed and collapse on the next.
- Why does only forgiveness differ between the two main runs?
- Payoffs, noise, rounds, and seed are frozen, and accidental flips are drawn from their own random stream so forgiveness cannot move them. Both runs flip the same 29 moves, and the first defection lands at round 40. Forgiveness 0 then ends near a 0.51 cooperation rate. Forgiveness 0.22 ends near 0.85. The retaliation echo is a reinforcing loop, the escalation archetype in miniature: each answer becomes the next grievance. Forgiveness is the balancing reply that breaks it on purpose instead of waiting for a lucky second accident.
- Why doesn't pure tit-for-tat survive the noise?
- Tit-for-tat only remembers the last move it saw. After an accidental defection it retaliates, the partner retaliates back, and the two echo each other. Later noise sometimes interrupts the echo and sometimes deepens it, which is why the unforgiving score wanders from seed to seed but never climbs back to the cooperative prize.
- What is the strategy lineup showing?
- It is a side comparison, not the regime contrast. Tit-for-tat, generous tit-for-tat, always-defect, and the grudger each play a tit-for-tat partner, and every match sees the same accidental flips. On the shipped seed, generous tit-for-tat averages about 2.7 per round, pure tit-for-tat about 2.2, the grudger about 1.6, and always-defect about 1.3. Mutual cooperation would pay 3 and mutual punishment pays 1. Generosity leads on every seed checked. A full round-robin of a larger field is a different experiment.
- Where does this show up outside the lab?
- Anywhere a repeated rivalry runs on noisy signals: arms-control inspections, trade disputes, neighbor feuds, and online arguments. One misread message is enough to start a retaliation spiral if neither side will let a slight go. Axelrod's tournaments found the strategies that do well are nice, retaliating, and forgiving. Strict reciprocity without forgiveness is fragile.