AI Engineering and Architecture

Choosing What to Keep: Submodular Optimization for AI Context Selection

A model can only hold so many tokens. Submodular optimization turns that brutal budget into a problem with a mathematical guarantee β€” and it is the memory side of the same machine we have been building all along.

Guillermo Perry 13 min read
submodular optimization KV cache context window H2O BumbleBee SnapKV greedy algorithm LLM inference agent memory context selection diminishing returns
🧠

Listen to the episode: Submodular Optimization: Choosing What to Keep

Every long conversation you have ever had with a model runs into the same wall: the context window is finite, and something has to be thrown away. The usual answer is embarrassingly crude β€” keep the newest tokens, drop the oldest, and hope the fact you needed was not in the part you just discarded. Submodular optimization is the formal name for doing this better, and it comes with a guarantee most engineering tricks never earn.

🧩Recency is topic-blind

A fact established early in a session gets discarded simply because it is old, even when the current question is about exactly that fact. That is the failure mode of pure recency-based truncation: it is blind to topic. The real problem was never memory capacity. It is choice β€” you have a budget of, say, a thousand tokens, a hundred thousand candidates, and you must pick the thousand that matter most.

That is a selection problem, and selection has a theory. It comes from a field older than neural networks, and its central property is easy to feel before you define it.

πŸ“‰Diminishing returns, written as math

A function is submodular when it has diminishing returns. The first copy of a fact adds a lot. A second copy of the same fact, once the first is already in your set, adds almost nothing. Formally, adding an item to a small set helps at least as much as adding it to a bigger set that already contains the small one:

f(A βˆͺ {x}) βˆ’ f(A) β‰₯ f(B βˆͺ {x}) βˆ’ f(B) for any A βŠ† B, x βˆ‰ B

Picture a coding session. The agent has read the same file three times, run the same command twice, seen the same error log again and again. The first read is worth a lot. The second tells you nearly nothing new. The third tells you nothing at all. A good selection rule notices that and keeps one representative copy instead of three.

A rule that scores each token on its own β€” without looking at what is already kept β€” will happily keep all three copies, because each looks important in isolation. Submodularity is the property that lets a selection algorithm see the overlap.

+100% +36% +16% +7% read 1 read 2 read 3 read 4 Marginal value of each copy of the same file
The first read of a file earns its place; the fourth barely moves the needle. Submodular scoring captures exactly this curve.

πŸ€–The greedy algorithm β€” and its 63% guarantee

The classic algorithm is almost insultingly simple. Start with an empty set. At each step, add the token that gives the biggest extra value on top of what you already have. Repeat until the budget is full. That is greedy selection.

In 1978, Nemhauser, Wolsey, and Fisher proved something remarkable about it. If the function is monotone (adding more never hurts) and submodular (diminishing returns), then greedy is guaranteed to reach at least 1 βˆ’ 1/e of the best possible selection β€” about 63% β€” using a rule a child could follow Nemhauser, Wolsey & Fisher, 1978.

The floor

63% is a floor, not a ceiling. In practice greedy usually does much better. And in 1998, Feige showed that for maximum coverage, a special case of this problem, no polynomial-time algorithm can beat 1 βˆ’ 1/e unless P = NP. So greedy is not just simple β€” it is essentially the best any fast method can promise in the worst case Feige, 1998.

⚠️The most important caveat in the whole episode

The guarantee is about the value function you wrote down, not about whether the model actually answers well. Greedy is provably near-optimal at maximizing whatever score you defined. If your score is a bad proxy for what the model needs, greedy will faithfully maximize a bad proxy. The mathematics is honest; the modeling choice is where things go wrong.

Remember this

The guarantee says greedy is near-optimal at maximizing your score. It says nothing about whether your score is the right thing to maximize. The score is the real engineering.

πŸ”₯H2O: heavy hitters, scored per token

The most influential answer for a KV cache is H2O β€” the Heavy-Hitter Oracle (Zhang et al., 2023) arXiv:2306.14048. The observation: a small portion of tokens receives most of the attention. A few tokens get looked at over and over by nearly every later token. Remove them and performance falls off a cliff; keep them and you can throw away most of the rest.

H2O keeps the heavy hitters plus a rolling window of recent tokens β€” roughly 20% heavy hitters plus the recent context β€” and drops the middle. The authors did something earlier heuristics had not: they formulated eviction as a dynamic submodular problem and proved a guarantee for their eviction rule under mild assumptions. The payoff was large β€” throughput on OPT-6.7B and OPT-30B rose by up to 29Γ— over DeepSpeed Zero-Inference and Hugging Face Accelerate (and 3Γ— over FlexGen), because a smaller cache means more sequences fit on one card. The bottleneck was memory, not arithmetic.

But H2O scores each token on its own, by how much attention it has received so far. That is exactly the blind spot described earlier: five copies of the same file read would each have high attention, so all five would survive.

🐝BumbleBee: adding coverage so copies stop surviving

The classic fix is a coverage score, sometimes called facility location. You give every token in the full context a weight, and you score a kept set by how well it covers the important tokens. A kept token covers itself and anything similar to it. The first copy of a file covers the whole file; the second covers almost nothing new, so greedy will not pick it β€” it will pick something uncovered instead. That is diminishing returns, written directly into the score.

A 2024 paper, BumbleBee (COLM 2024) Kumari et al., 2024, mixes two submodular scores: one rewards diversity in the key-embedding space (so kept tokens spread out instead of clustering), the other rewards importance (accumulated attention). Across 13 datasets on LLaMA 7B and 13B, it beat leading techniques at comparable context-reduction ratios β€” not by a landslide, but consistently, and with a reason attached to the win. It was not a better heuristic; it was a better objective.

🎯SnapKV: choosing before generation even starts

H2O chooses during generation. What about the prompt itself, before generation starts? SnapKV (Li et al., NeurIPS 2024) arXiv:2404.14469 noticed that each attention head settles into a stable pattern during generation, and that pattern is already visible in a short window at the end of the prompt. The last few tokens vote, in effect, on which earlier prompt tokens will matter. SnapKV takes those votes, clusters the winners per head, and compresses the prompt cache before generation starts.

With that, the authors processed up to 380,000 tokens of context on a single 80 GB card with only a negligible drop on a needle-in-a-haystack retrieval test. H2O chooses during generation; SnapKV chooses before it.

MethodWhen it choosesWhat it scoresCore idea
H2ODuring generationAccumulated attention, per tokenKeep heavy hitters + a recent window
SnapKVBefore generationObservation-window votes, per headCompress the prompt cache once, up front
BumbleBeePrefill + streamingCoverage (diversity) + attention (importance)Mixture objective; greedy stays near-optimal

πŸ•ΈοΈWhere the agent world fits in

Agents do not have just one prompt. They have turns, memory, and tool outputs. A June 2026 paper, PACMS (arXiv:2606.20047), treats agent context as one candidate pool: user turns, assistant turns, entries from a memory store, and the verbatim outputs of tool calls β€” file reads, search results, command output β€” all go into the same pool, and the framework selects from it by relevance at the moment the prompt is assembled. Recency truncation fails exactly where agents need memory most, because a fact from early in a session is often the one the current question is about, and it is the first thing recency throws away.

βš™οΈThe weak links nobody should skip

Greedy is cheap to describe and expensive to run. At every step it has to rescore every candidate against the set it has so far. Do that per decode step on a cache of 100,000 tokens and the selection itself becomes the bottleneck. The field has two answers.

First, greedy can be made lazy. A 1978 result from Minoux keeps an upper bound on each candidate's gain and only rescores the one at the top of the list; diminishing returns guarantees the bound stays valid, so most candidates never get rescored. Second, sample. Stochastic greedy Mirzasoleiman et al., 2015 looks at a random sample of candidates at each step instead of all of them, and still keeps nearly the same guarantee in expectation, in time that grows linearly with the data.

Even so, there is a difference between a fast greedy and a free one. H2O is basically a sort, which is nearly free. A coverage score has to compare tokens to each other, which is not free. And the evidence agrees. The episode cites one independent experimenter (we could not locate a published write-up, so treat these numbers as anecdotal) who added a redundancy-aware term (H2O plus coverage) to a small inference engine and tested it on real coding-agent sessions found the coverage term helped β€” but only on the most repetitive text, and only by a little. On ordinary prose it did nothing. At a 12.5% cache budget, choosing what to evict took 71% of decode time, and throughput fell below doing no eviction at all. A better objective you cannot afford is worse than a simpler one you can.

The streaming problem

Greedy, as Nemhauser proved it, sees the whole set before it chooses. A KV cache does not. Tokens arrive one at a time, eviction is irreversible, and the question that will need a token has not been asked yet. The guarantee is offline; the cache is online. H2O handles that by re-deciding as attention accumulates and by keeping guardrails (attention sinks and the recent window) no matter what the scores say. SnapKV handles it by deciding once, from the observation window, before generation. Neither gets the full offline guarantee for free.

πŸ”§The hardware angle: selection is the memory side

The first episodes of this series built a machine out of exact arithmetic, cheap add-and-compare operations, and sparse wiring. Selection fits as the memory side of the same machine. Arithmetic decides what a token costs to compute. Wiring decides what it costs to move. Selection decides what is worth keeping close at hand at all.

A cache that keeps the right fifth of its tokens is, for serving, the same as a cache five times larger β€” and the rule that picks that fifth can be written down, analyzed, and guaranteed, instead of guessed. The cheapest token to serve is the one you never had to keep.

πŸ’‘What this means for building agents

If you deploy agents that read files, call tools, and hold multi-turn conversations, context selection is not an academic footnote β€” it is a line item on your latency and GPU bill. Three takeaways, drawn straight from the theory:

  • Score > algorithm Greedy is near-optimal for any reasonable monotone submodular score. Spend your effort on the score, not on a cleverer selector.
  • Coverage beats redundancy Attention-only scores (H2O) keep five copies of the same file. A coverage term (BumbleBee) stops that β€” but only pay for it where repetition is real.
  • Cost is part of the choice A cache policy that eats the time it was meant to save has failed, however elegant its objective looks on paper.

❓Frequently asked questions

What is submodular optimization in plain terms?

It is the math of diminishing returns applied to picking a set. Adding an item to a small set helps at least as much as adding it to a bigger set that already contains the small one. That single property is what lets a simple greedy rule come with a performance guarantee.

Why is the 63% (1 βˆ’ 1/e) guarantee useful if it is only a floor?

Because it bounds the worst case for a fast method, and Feige showed that, unless P = NP, no polynomial-time method can beat it on the general problem. In practice greedy does better, but the floor tells you the algorithm is not the weak link β€” your scoring function is.

Is H2O a submodular method if it scores each token on its own?

H2O frames eviction as a (dynamic) submodular problem and proves a guarantee under that assumption, but its per-token attention score is topic-blind to redundancy. Five identical file reads each score high and all survive. That is the gap BumbleBee's coverage term is built to close.

What is the difference between H2O and SnapKV?

H2O decides what to keep during generation, re-scoring as attention accumulates. SnapKV decides once, before generation, by reading the stable attention pattern in a short observation window at the end of the prompt. Both are submodular-flavored, but they choose at different moments.

Can greedy context selection run fast enough to be worth it?

Lazy greedy (Minoux, 1978) avoids resscoring most candidates, and stochastic greedy (Mirzasoleiman et al., 2015) samples instead of scanning everything. But a coverage score still costs comparisons between tokens. Real measurements show that on ordinary text a redundancy-aware objective can cost more in decode time than it saves β€” so the cost of choosing has to be counted as part of the choice.

πŸ“šReferences

  • Zhang, Z. et al. (2023). H2O: Heavy-Hitter Oracle for Efficient Generative Inference of Large Language Models. arXiv:2306.14048
  • Li, Y. et al. (2024). SnapKV: LLM Knows What You are Looking for Before Generation. NeurIPS 2024. arXiv:2404.14469
  • Kumari, L. et al. (2024). BumbleBee: Dynamic KV-Cache Streaming Submodular Summarization for Infinite-Context Transformers. COLM 2024. COLM Proceedings
  • Nemhauser, G. L., Wolsey, L. A., & Fisher, M. L. (1978). An analysis of approximations for maximizing submodular set functionsβ€”I. Mathematical Programming. doi:10.1007/BF01588971
  • Mirzasoleiman, B. et al. (2015). Lazier Than Lazy Greedy. AAAI 2015. arXiv:1409.7938
  • Feige, U. (1998). A threshold of ln n for approximating set cover. Journal of the ACM. doi:10.1145/285055.285059
  • Ghulyani, M. et al. (2026). PACMS: Submodular Context Selection as a Pluggable Engine for LLM Agents. arXiv:2606.20047