Cheat sheets

Swarm Optimization and MARL for Agents

PSO and ACO for prompts and routing, queue swarms, and MADDPG, QMIX, MAPPO and self-play set side by side.

  • Concepts and terms
  • Tasks and commands
  • Annotated code
  • Diagrams
  • Comparisons
  • Defaults and numbers
  • Troubleshooting
  • Questions and tips

Source

PSO vs ACO#

FactorPSOACO
ProblemContinuous search spaceRouting or path selection
Memoryp_best and g_bestPheromone per task-type × agent
Agent useLMPSO, Model SwarmsAMRO-S routing
Reported gain13.3% over 12 baselines4.7x speedup
Population10-30 particles3 agents, 4 task types in the demo
Update ruleInertia + cognitive + socialDecay, then gated deposit
Demo functionrun_lmpso()run_amro_s()

From Lesson 16.19, 16.19 code/main.py

MARL algorithms#

FactorMADDPGQMIXMAPPO
Year, venueNeurIPS 2017ICML 2018NeurIPS 2022
SettingCoop, competitive, mixedCooperative onlyCooperative
Training signalPer-agent critic sees all actionsMonotone mixer of per-agent QsCentralized value function
Policy typeOff-policyOff-policyOn-policy PPO
TestbedParticle WorldSMACFootball, Hanabi, MPE
LimitPast ~10 agents critics growReward must be monotoneDefault baseline to beat
Demorun_maddpg_stylerun_qmix_stylerun_mappo_style

From Lesson 16.20, 16.20 code/main.py

MARL regimes#

FactorIQL / IPPOCTDESelf-playLeague play
IdeaOthers are environmentCentral critic, local policyCopy of past selfPopulation of past policies
FitsLoosely-coupled tasksCooperative navigationZero-sum gamesStrategy cycles
ExamplesIndependent QMADDPG, COMA, MAPPO, QMIXAlphaZeroAlphaStar
NoteTheoretical convergence: noneMost common modern paradigmCan stick in a dominance cycleAdds exploiters and main exploiters

From Lesson 09.10

Queue swarm vs fixed assignment#

FactorSequentialFixed assignmentSwarm
Who picks workOne workerPre-assigned worker idWorkers pull from a shared queue
Functionrun_sequentialrun_fixed_assignmentrun_swarm
Load balanceNoneFast workers sit idleAutomatic
FitsBaseline onlyDurations known aheadMany independent tasks
Weak pointWall-clock timeWorker 0 gets all slow tasksOrdering and debugging

From Lesson 16.09, 16.09 code/main.py

PSO update#

w, c1, c2 = 0.6, 1.2, 1.2inertia, cognitive, social
r1, r2 = rng.random(), rng.random()
cognitive = c1 * r1 * (p.p_best[d] - p.x[d])
social = c2 * r2 * (g_best_x[d] - p.x[d])
p.v[d] = w * p.v[d] + cognitive + social
p.x[d] += p.v[d]
p.x[d] = max(bounds[d][0], min(bounds[d][1], p.x[d]))clamp to bounds
f = fitness(p.x)only an evaluator, no gradient
if f > p.p_best_fit:then check g_best_fit

From 16.19 code/main.py

ACO router#

router = PheromoneRouter(task_types, agents)every trail starts at 1.0
aco_agent = router.choose(tt, rng)sample by pheromone weight
aq = simulate_task(aco_agent, tt, rng)
router.deposit(tt, aco_agent, aq)
self.pheromones[task_type][a] *= (1.0 - self.decay)all agents decay
if quality >= self.quality_threshold:quality gate
self.pheromones[task_type][agent] += self.reinforce * quality

From 16.19 code/main.py

Use each method when#

PSO
continuous parameters, cheap automatic fitness, population 10-30.
ACO
routing that repeats over time and needs interpretable evidence.
Neither
fitness needs human review, or latency must be strict.
Genetic algorithm
discrete combinatorial space that PSO does not cover.
Swarm
many independent tasks with variable duration.
Supervisor
the task needs one coherent global plan.
MAPPO
start here for cooperative MARL.
Self-play
zero-sum games. League play when strategies cycle.

From Lesson 16.19, Lesson 16.20, Lesson 16.09, Lesson 09.10

Run the patterns#

TaskCode
Run any lesson demopython3 code/main.py
PSO over 2 prompt parametershistory = run_lmpso()
ACO routing vs randomrun_amro_s(n_tasks=200, seed=0)
Print the trailprint_pheromone_table(router)
Steps-to-goal per MARL stylebench(label, runner) over 500 trials
Pull from a shared queuerun_swarm(tasks, n_workers)
Independent Q on the gridindependent_q(episodes=1500)
Joint Q over 16 actionsjoint_q_learning(episodes=1500)

From 16.19 code/main.py, 16.20 code/main.py, 16.09 code/main.py, 09.10 code/main.py, Lesson 16.19

CTDE pattern#

traingradientdeploydeploygradientstoreGlobal stateall obs + jointactionmodelCentralizedcritictraining time onlyAgent 1 obso_iprocessActor 1mu_i(o_i)Agent 2 obso_iprocessActor 2mu_i(o_i)traingradientdeploydeploygradientstoreGlobal stateall obs + jointactionmodelCentralizedcritictraining time onlyAgent 1 obso_iprocessActor 1mu_i(o_i)Agent 2 obso_iprocessActor 2mu_i(o_i)

From Lesson 16.20, Lesson 09.10

Defaults in the lesson code#

SettingDefaultNote
n_particles20run_lmpso population
iterations30PSO iterations
decay0.05Pheromone decay per deposit
reinforce0.2Deposit is reinforce times quality
quality_threshold0.6No deposit below it
n_tasks200Routed tasks in run_amro_s
epsilon0.15Exploration in independent_q
gamma0.95Discount, with alpha 0.1

From 16.19 code/main.py, 09.10 code/main.py

Failure modes#

SymptomCauseFix
Router locks on a bad agentFast-but-wrong agent got pheromoneQuality-gate the deposits
Best fitness divergesCatastrophic drift after data shiftReset or double the decay rate
Swarm forgets good solutionsDecay too fastSlower decay, monitor best fitness
Long tasks never runQueue starvationPriority queue with aging
Task output appears twiceWorker crashed mid-runIdempotent workers, durable queue
Agents chase each otherPolicy drift, non-stationarityCentralized critic, slow learning rates
Old replay hurts learningTransitions from obsolete opponentsRelabel or weight by recency
Auction agents bid zeroReward hacking via coordinationCareful reward design, constraints

From Lesson 16.19, Lesson 16.09, Lesson 09.10, Lesson 16.20

Questions#

Why gradient-free for prompts?
A prompt is a discrete string. PSO and ACO need only an evaluator.
What does a 20-particle, 50-iteration PSO cost?
About $20 at ~$0.02 per call.
Why does QMIX decentralize?
Monotone mixing lets each agent take its own argmax.
Why not train MARL for LLM agents?
Most systems prompt policies. Train only with data, reward and infrastructure.
Why is the joint-Q demo slow to scale?
Its action space is |A|² = 16 for two agents.

From Lesson 16.19, Lesson 16.20, Lesson 09.10

Ship checklist#

  • Start with 10-20 particles and 20-50 iterations.
  • Log pheromones or g_best per iteration.
  • Emit a cost-per-iteration metric.
  • Give every swarm task a trace ID. Apply back-pressure when the queue grows.
  • Let the execution path see only o_i.
  • Log every agent's observation and action stream.

From Lesson 16.19, Lesson 16.20, Lesson 16.09