TAI BUI
Back to curriculum
BuildPython

Swarm Optimization for LLMs (PSO, ACO)

Bio-inspired optimization is making an LLM comeback. **LMPSO** (arXiv:2504.09247) runs PSO where each particle's velocity is a prompt and the LLM generates the next candidate, which suits structured outputs like math expressions and programs. **Model Swarms** (arXiv:2410.11163) treats each LLM expert as a PSO particle on a model-weight manifold and reports a **13.3% average gain** over 12 baselines on 9 datasets with just 200 instances. **SwarmPrompt** (ICAART 2025) hybridizes PSO with Grey Wolf for prompt optimization. **AMRO-S** (arXiv:2603.12933) uses ACO-style pheromone specialists for multi-agent LLM routing, with a reported **4.7x speedup**, interpretable routing evidence, and a quality-gated asynchronous update that decouples inference from learning. This lesson implements PSO on a prompt-parameter space and ACO on agent routing, then looks at why these classical algorithms fit the LLM era and where they stop fitting.

TIME: ~75 minutesPREREQUISITES: Phase 16 · 09 (Parallel Swarm Networks), Phase 16 · 14 (Consensus and BFT)

Learning Objectives

  • Explain why PSO and ACO fit LLM prompt and routing problems where gradients do not exist, and what they need instead (an evaluator).
  • Describe how LMPSO, Model Swarms, and AMRO-S each adapt a classical swarm algorithm to LLM outputs, model weights, or agent routing.
  • Run the stdlib PSO and ACO simulations and read a convergence curve and a pheromone table.
  • Decide when to use PSO, ACO, or neither, given evaluation cost, search space, and latency limits.

Problem

You have a prompt that scores 62% on your task eval and you want it higher. Manual tweaking scales badly. Reinforcement learning needs a reward signal and enough rollouts to train on. Backprop through a prompt isn't really possible, because the prompt is a discrete string and not a differentiable parameter.

Classical bio-inspired optimizers were built for exactly this regime: PSO for continuous search spaces, ACO for path selection. Both are gradient-free, population-based, and cheap per evaluation. Put an LLM inside the search step and you get a practical optimizer.

The same patterns work for routing in multi-agent systems. An ACO-style pheromone trail records which agent did best on which task type. The router exploits the trail, and decay lets it rediscover routes when things change.

Warm-up0/3
1. In a swarm architecture with no central orchestrator, how does a worker find its next piece of work?Warm-up
A pending-tasks pile with five queued items on the left and three idle workers on the right, not connected by any arrow, with a question mark between them.
No central orchestrator is drawn.
2. Three agents built on the same base model all return the same wrong answer. Why can't classical BFT voting rescue this?Warm-up
Three agent boxes, each noted as the same base model and each outputting 42, above a vote tally of 3 of 3 agreeing, with a question about whether agreement guarantees correctness.
3. A function can only be evaluated by running it, and there is no formula you can differentiate. Which optimizer cannot be applied to it directly?Warm-up
A black-box function f(x) drawn as input x going in and a score coming out, with no visible formula, and a crossed derivative d/dx f(x) marked with a question mark.
Check: Problem0/1
1. Why can't you improve a prompt by backpropagating through it?Explain
A hill-shaped curve over a continuous number with a tangent line marked as having a slope, next to a box holding a prompt string with a derivative symbol marked with a question mark.

Concept

PSO refresher (Kennedy & Eberhart 1995)

Particle Swarm Optimization keeps a population of particles in a continuous search space. Each particle has a position x_i and a velocity v_i. Each iteration:

v_i <- w * v_i + c1 * r1 * (p_best_i - x_i) + c2 * r2 * (g_best - x_i)
x_i <- x_i + v_i
evaluate fitness(x_i)
update p_best_i if improved
update g_best if global best

p_best is the particle's own best and g_best is the swarm's best. w, c1, and c2 are the inertia, cognitive, and social weights, and r1, r2 are random factors.

PSO on LLM outputs: LMPSO

arXiv:2504.09247 adapts PSO to LLM-generated structured outputs (math expressions, programs). Each particle is a candidate output. Velocity is a prompt describing how to modify the current output toward the personal or global best, and the LLM generates the new output from it. Inertia becomes a prompt like "make small incremental changes."

This works well when:

  • The output is structured (parseable, evaluable).
  • Fitness is automatic (test runs, arithmetic evaluation).
  • The population is small (~10-30 particles), so total LLM calls stay manageable.

It breaks down when fitness needs human review, because the per-iteration cost gets prohibitive.

Model Swarms

arXiv:2410.11163 moves PSO off the output layer and into the model layer. Each particle is an expert LLM (its parameters), and the swarm moves toward the collective best with a gradient-free update. The paper reports a 13.3% average gain over 12 baselines on 9 datasets, with just 200 instances per iteration.

The key insight is that LLM experts sit close together in a shared parameter manifold (adapter weights, LoRA deltas). PSO on that low-dimensional subspace is cheap and effective.

ACO refresher (Dorigo 1992)

Ant Colony Optimization sends ants across a graph where each path carries a pheromone trail. Move probabilities weight by pheromone strength. Ants that finish the task deposit pheromone in proportion to solution quality, and pheromone decays over time.

AMRO-S: ACO for agent routing

arXiv:2603.12933 applies ACO to multi-agent routing. Each task type is a destination and each agent is a possible route. Pheromone strengthens the routes that produce good outputs. The paper's main contributions:

  • Interpretable routing evidence. Pheromone strength is a human-readable signal.
  • Quality-gated asynchronous update. Pheromone updates only after quality checks pass, which decouples inference from learning.
  • 4.7x speedup on the multi-agent routing benchmark.

The quality gate matters. Without it, fast-but-wrong agents accrue pheromone and the system locks in on bad routes.

When to use PSO / ACO for LLMs

Use PSO when:

  • The search space is continuous or maps to continuous parameters (prompt embeddings, LoRA weights, numeric generation parameters).
  • Fitness is cheap and automatic.
  • The population can be small (10-30).

Use ACO when:

  • You have a routing or path-selection problem.
  • Decisions reinforce over time because the same task types keep coming back.
  • You need interpretable evidence for routing decisions.

Skip both when:

  • Fitness requires human review (too expensive per iteration).
  • The search space is discrete and combinatorial in a way PSO doesn't cover. Use genetic algorithms instead.
  • Real-time decisions have strict latency limits. PSO and ACO converge slowly compared to single-pass heuristics.

Why bio-inspired still wins

Gradient-based methods need differentiable signals, and LLM outputs and routing decisions aren't trivially differentiable. Pseudo-gradient methods (reinforcement-learned routers, DPO-style prompt tuners) work but need expensive training.

PSO and ACO need only an evaluator function. If you can score a candidate output or a routing decision, you can optimize over the space. That lowers the bar for applicability a lot.

Practical limits

  • Population budget. N particles × T iterations × per-eval cost. At ~$0.02 per LLM call, a 20-particle PSO running 50 iterations costs ~$20. Plan for it.
  • Exploration vs exploitation. Pheromone decay rate and PSO inertia trade these off. Decay that is too fast forgets good solutions, and decay that is too slow sticks on early local optima.
  • Catastrophic drift. Both algorithms can converge and later diverge if the fitness landscape shifts (a new data distribution). Monitor best-fitness stability.
Check: Concept0/23
1. What is Particle Swarm Optimization (PSO)?Define
Six particles plotted as dots on a two-parameter grid from 0 to 1 on each axis, each with a short arrow showing its current velocity, no other labels.
Positions and velocities from the lesson's run_lmpso, iteration 0, seed 0.
2. What is Ant Colony Optimization (ACO)?Define
A start node and an end node joined by three alternative routes, each drawn with a different line thickness between start and end.
Illustrative pheromone thickness.
3. In LMPSO (arXiv:2504.09247), what role does the 'velocity' play?Define
A two-column mapping from classical PSO terms to LMPSO terms: position maps to candidate output, fitness maps to an automatic score, and velocity maps to a blanked question mark.
4. What is Model Swarms (arXiv:2410.11163)?Define
Three dots labeled expert A, B and C scattered inside a large box labeled as a model-parameter space.
Illustrative positions.
5. What is AMRO-S (arXiv:2603.12933)?Define
Three bars of illustrative pheromone strength for one task type, one bar per agent: coder, mathematician and writer, with a note that the same structure repeats for other task types.
Illustrative values, not the lesson's real run.
6. In the classical PSO update rule, what does `g_best` represent?Define
Three particles labeled P0, P1 and P2 at their own best positions, and a fourth, more prominent position marked with a triangle and a question mark, on the same two-parameter grid.
Positions from the lesson's run_lmpso, iteration 0, seed 0.
7. In ACO-style routing, what is pheromone?Define
Two small bar charts for the same route at two points in time: a low pheromone bar at T=10 and a taller one at T=40.
Illustrative values.
8. What is catastrophic drift?Define
A bowl-shaped fitness curve with a peak and a small cluster of particle dots near it, labeled before, above a second, mostly empty panel labeled after with a note that the evaluation data changed.
Illustrative landscape.
9. What do PSO and ACO need in order to optimize an LLM prompt or a routing decision?Explain
A candidate box feeding into a highlighted blank box, feeding into a score box, with a question about what fills the blank.
10. In LMPSO, how is the classical inertia term expressed?Explain
The classical PSO update line with the w times v term marked as inertia, above a card asking what the LMPSO analog of inertia is.
11. Why is PSO cheap enough to run in Model Swarms?Explain
A large outer box labeled the full weight space, with a small highlighted region inside it holding three expert dots labeled adapter or LoRA deltas.
12. What is the purpose of the quality gate in AMRO-S's pheromone update?Explain
Two agents on the same task type: a fast agent with quality 0.30 blocked from depositing, and a slower agent with quality 0.80 allowed to deposit.
13. What does the quality-gated asynchronous update in AMRO-S decouple?Explain
Two lanes: respond to the user on a fast path returning immediately, and update pheromone running later and asynchronously, with a question about what this separates.
14. In an ACO router, pheromone decay is set too slow. What is the likely effect?Explain
A line chart of pheromone strength over 50 routed tasks for two decay rates, one line staying high and flat, the other dropping quickly to a lower level.
Illustrative decay curves.
15. At roughly $0.02 per LLM call, what does a 20-particle PSO run for 50 iterations cost?Apply
A formula card: particles times iterations times cost per evaluation, with the numbers 20 particles, 50 iterations and $0.02 per call, and a blank total.
16. A team has a $10 budget at $0.02 per LLM call and runs 20 particles. How many iterations can it afford?Apply
A card with a $10 budget, a cost of $0.02 per call and a population of 20 particles, with a question about how many iterations the budget affords.
17. A particle has x = 2 and v = 1. With w = 0.5, c1 = c2 = 1, r1 = r2 = 1, p_best = 3 and g_best = 5, what is its new position?Apply
A number line marking a particle's position at 2, its personal best at 3 and the swarm's best at 5, with the parameters w, c1, c2, r1 and r2 given, and a question asking for the new position.
18. A router keeps sending math tasks to a fast agent that often scores poorly, and its pheromone keeps rising. Which ingredient is missing or too weak?Analyze
Two bar charts side by side: agent Z's quality score staying low across five math tasks, and agent Z's pheromone climbing across the same five tasks, with a question about what is missing.
Illustrative scores.
19. A PSO run converged, then its best fitness quietly worsened after the eval distribution changed. What would have caught this early?Analyze
A line chart of best fitness rising then, after a marked point where the distribution changes, slowly declining, captioned as an illustrative monitoring curve.
Illustrative, not produced by main.py.
20. You want to tune a prompt, but every candidate needs a person to read and rate the output. Should you use PSO or ACO?Design
Three cards for iteration 1, 10 and 50, each showing the cumulative number of human reviews needed so far: 20, 200 and 1,000.
20-particle population, illustrative scaling.
21. Tickets of five recurring types go to five specialist agents, and managers want to see why each route was chosen. Which design fits best?Design
Five ticket types each with an arrow to one of five agents, above a box marked with a question mark and a note that managers want to see why each route was chosen.
22. Your search space is discrete and combinatorial in a way PSO does not cover, and fitness is cheap and automatic. What does the lesson point to?Design
A scatter of points in a continuous two-parameter space on the left, next to a grid of separate discrete option combinations on the right.
23. You plan to run a PSO search live inside each user request, which has a strict latency limit. What is the right call?Design
A short green bar for a 200 millisecond request budget, above a dashed outline bar of unknown length for one PSO run of 20 particles over 30 iterations, with a question mark asking whether it fits.
Illustrative timing, not measured.

Build It

main.py is stdlib-only Python with two parts:

  • run_lmpso is PSO over two numeric prompt parameters (temperature and a top_k weight), with 20 particles and 30 iterations by default. There are no LLM calls. The "generation" step is replaced by a scripted fitness function, so the velocity is a plain number and not a prompt. It records g_best after every iteration.
  • run_amro_s is ACO-style routing with a PheromoneRouter: 3 agents, 4 task types, a pheromone table, and 200 routed tasks. Each deposit decays that task type's row and then reinforces the chosen agent, but only if the quality score clears the threshold (0.6). The same task stream also goes through a random router for comparison, and the script compares average quality.

Run:

python3 main.py

On the default seed:

  • LMPSO: g_best climbs from 0.96 at iteration 0 to just over 1.0 within about 5 iterations, then plateaus.
  • AMRO-S: the pheromone table concentrates on one agent per task type, and ACO routing beats random by about 31% on average quality (0.651 against 0.498). The script does not measure latency or retries.
Check: Build It0/5
1. In the `run_amro_s` simulation with 3 agents and 4 task types, how many pheromone values does the router hold?Apply
An empty grid with four task-type row labels and three agent column labels, one blank cell at each row and column crossing.
2. With the 0.6 threshold, one agent scores 0.55 on a task and 0.72 on another task of the same type. Which run gets reinforced?Apply
Two bars for two runs of the same agent on the same task type, labeled run A at 0.55 and run B at 0.72, against a dashed threshold line at 0.6, with a question about which gets reinforced.
3. In the default run, ACO routing scores 0.651 average quality and random routing scores 0.498. About how much better is ACO, relatively?Apply
Two bars for average quality over 200 tasks: random routing at 0.498 rounding to 0.498, ACO routing at 0.651 rounding to 0.651, with a question about the size of the gap relative to the baseline.
4. After 200 tasks in the Build It run, the code, math, and writing rows each show one dominant agent, but the planning row shows the writer at 0.575 and the other two at 0.077. What does that say?Analyze
A table of the final pheromone values for code, math, writing and planning rows across the coder, mathematician and writer columns, planning row highlighted with writer at 0.575 and the others at 0.077.
From the lesson's run_amro_s, seed 0.
5. The Build It run prints a final `g_best` of 1.0094 while the stated optimum is 1.0000. What explains this?Analyze
The scripted fitness formula with its ripple term highlighted, above a note that the run's final g_best prints as 1.0094 next to a stated optimum of 1.0000.

Use It

outputs/skill-swarm-optimizer.md helps you choose between PSO, ACO, genetic algorithms, and gradient-based optimizers for an LLM or agent optimization problem.

Ship It

  • Start small. 10-20 particles and 20-50 iterations. Scale up only if the convergence curve shows a clear gain.
  • Log pheromones or g_best every iteration. Debugging a swarm optimizer without a trail is painful.
  • Quality-gate updates, especially for ACO routing. Fast-and-wrong agents must not accrue pheromone.
  • Reset decay on distribution shift. When your eval distribution changes, aged pheromones are stale. Reset them, or double the decay rate for a while.
  • Cap the per-iteration cost. Emit a cost-per-iteration metric. A PSO run that costs $500 per iteration and gains 0.5% isn't shippable.
Check: Ship It0/3
1. What does a quality-gated update do in AMRO-S-style routing?Define
A flow from a task run to a quality score to a diamond gate, with two unresolved outcome boxes marked with question marks above and below it.
2. Your eval data distribution changes and the router keeps sending tasks to agents that used to win. Per Ship It, what is the right response?Analyze
Two cards: period 1 with agent M's pheromone on math tasks at 2.50, and period 2 after the eval distribution changes, with the same pheromone value still unchanged, and a question about what to do.
Illustrative pheromone value.
3. A PSO run costs $500 per iteration and gains 0.5% per iteration. What does the lesson's shipping advice say?Design
Two bar charts: a tall bar for a $500 cost per iteration next to a tiny bar for a 0.5% gain per iteration.
Author's Note

I'd run main.py and read the pheromone table before the theory. After 200 tasks, the code, math, and writing rows each have one agent far ahead of the other two, which is the trail forming. The planning row is weaker. The agents' base scores there are close together (0.4, 0.5, 0.6) and the noise on each run is wide enough to blur them, so the writer's trail is the strongest in its row but nowhere near as dominant as in the others.

The quality gate deserves a second look. In the code it is a threshold of 0.6 on the score, so a wrong agent that happens to score above it still gets pheromone. The gate is only as good as the evaluator behind it, which is the same point as "PSO and ACO need only an evaluator," turned around. If I were routing real traffic, I'd spend the effort on the evaluator first.

The LMPSO half is a numeric stand-in, so I'd read it as a convergence curve and not as a result about LLMs. The final g_best prints as 1.0094 next to a stated optimum of 1.0000, because the ripple term in the fitness function can push the score above 1. And with 20 random particles in two dimensions, the best one already starts at 0.96, so the climb is short. Shrinking the population in the first exercise makes the curve easier to see. For budgeting, the 20 particles and 30 iterations here would be 600 evaluations, which is about $12 at the $0.02 per call from the Practical limits.

Exercises

  1. Run main.py. Observe LMPSO convergence. Vary population size 5, 10, 20, 50. At what size does time-to-converge saturate?
  2. Implement a "catastrophic drift" experiment: after iteration 30, change the fitness function. How fast does PSO adapt? Does resetting p_best help?
  3. Raise the AMRO-S quality gate from 0.6 to 0.7, then remove it entirely. How does convergence change in each case?
  4. Read LMPSO (arXiv:2504.09247). Map the paper's "velocity as a prompt" back to your numeric velocity. What is lost in the simulation and what is preserved?
  5. Read AMRO-S (arXiv:2603.12933). Implement the decoupled "inference fast-path" with asynchronous pheromone update. How does this change system latency under sustained load?

Key Terms

TermWhat people sayWhat it actually means
PSO"Particle Swarm Optimization"Kennedy-Eberhart 1995. Population-based gradient-free optimizer.
ACO"Ant Colony Optimization"Dorigo 1992. Path/route optimization via pheromone trails.
LMPSO"PSO with LLM generation"arXiv:2504.09247. Velocity is a prompt; LLM produces candidates.
Model Swarms"PSO on expert weights"arXiv:2410.11163. Gradient-free update on model parameter subspace.
AMRO-S"ACO for agent routing"arXiv:2603.12933. Pheromone matrix over task-type × agent.
p_best / g_best"Personal / global best"Per-particle and swarm-wide best solutions found so far.
Pheromone"Routing memory"Strength on an edge; decays over time; deposits on quality.
Quality-gated update"Only learn from good runs"Pheromone deposit conditioned on quality check.
Catastrophic drift"Distribution shift"Fitness landscape changes; old p_best and pheromones become stale.

Further Reading

Code

Ships With