Merge similar tokens with bipartite matching

Why it matters ToMe gives ViTs and Stable Diffusion U-Nets about 2x speedups with small accuracy loss.

Token Merging (ToMe) speeds up ViTs by averaging the most similar token pairs.

Write tome_merge(x, r). x is (T, d). Split into set A (even indices) and B (odd indices). For each a in A find its most similar b in B by cosine similarity (ties to the smaller b). Pick the r tokens of A with the highest best-similarity (stable). Merge each picked a into its b by averaging with sizes: every token starts with size 1, b_new = (b * size_b + a * size_a) / (size_b + size_a), sizes add (several a can merge into one b). Return the output tokens: the unmerged A tokens in original order followed by all B tokens in original order, as a (T - r, d) array.

Signaturedef tome_merge(x, r)

Example

x = [[1, 0], [1, 0], [0, 1], [0, 1]] with r 1 merges token 0 into token 1, giving [[0, 1], [1, 0], [0, 1]].

Understand the idea

Token Merging speeds up vision transformers by averaging away near-duplicate tokens, such as patches of plain sky. Tokens are split into two sets, A (even positions) and B (odd positions). Each A token finds its most similar B token by cosine similarity, and the r A tokens with the strongest matches are merged into their partners. Worked example: x0 = [1, 0], x1 = [0, 1], x2 = [0, 1], x3 = [1, 0], r = 1. A = {0, 2}, B = {1, 3}. Token 0 best matches token 3 (cosine 1). Token 2 best matches token 1 (cosine 1). It is a tie, so the stable order picks token 0. Merge: x3 becomes ([1, 0] * 1 + [1, 0] * 1) / 2 = [1, 0], size 2. Output: unmerged A [x2], then B [x1, x3] = [[0, 1], [0, 1], [1, 0]]. Rule: merged b = (b * size_b + a * size_a) / (size_b + size_a), and sizes add, so a token that absorbs several others stays their true mean. For example 0, then 3, then 6 merged into one gives 3. Used in: faster ViT and Stable Diffusion inference without retraining.

Shapes and data flow

x (T, d) -> A (T/2, d), B (T/2, d)
cos S (|A|, |B|) -> best b per a, top r a
merge into B -> output (T - r, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampletome_merge([[1, 0], [1, 0], [0, 1], [0, 1]], 1)
  • Sample 2: random r 2tome_merge(_x, 2)