File size: 7,809 Bytes
d4bcd5c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | """
SPLIT: Salience-guided Partitioning towards Local coverage for Importance-aware
Token dropping. Faithful, training-free reimplementation of Algorithm 1 from
SPLIT-VLM (ICML 2026, OpenReview Elm4TdaXi0).
Given the per-layer ViT hidden states of the vision patch tokens and the final
patch-token embeddings, SPLIT selects a subset of `budget` tokens by:
1. temporal-shift importance I(x) = mean_l ||h_l - h_{l-1}|| / ||h_l|| (Eq.5-6)
2. adaptive region budget B_k = B/K + B * I(X_k)/sum_j I(X_j) (Eq.7)
3. diversity-score selection D(i) = lambda*std_j(S_ij) - mean_j(S_ij) (Eq.8-10)
select top-B_k tokens by D within each region.
All operations are batch-size-1 (one image) and vectorised in torch.
"""
from __future__ import annotations
import math
import torch
def temporal_shift_importance(hidden_states, layers=None):
"""
hidden_states: list/tuple of length L+1, each [N, d] (patch tokens only,
CLS already removed), h[0] = embeddings, h[l] = after layer l.
layers: iterable of layer indices l>=1 to use (default: all).
returns I: [N] importance per token (Eq. 6).
"""
L = len(hidden_states) - 1
if layers is None:
layers = range(1, L + 1)
layers = [l for l in layers if 1 <= l <= L]
acc = None
for l in layers:
h = hidden_states[l]
hprev = hidden_states[l - 1]
num = torch.linalg.vector_norm(h - hprev, dim=-1) # ||h_l - h_{l-1}||
den = torch.linalg.vector_norm(h, dim=-1).clamp_min(1e-6) # ||h_l||
delta = num / den
acc = delta if acc is None else acc + delta
return acc / len(layers)
def region_ids_grid(num_tokens, grid_hw, region_grid):
"""
Map each patch token to a region id for a square grid of patches.
grid_hw = (H, W) patch grid (e.g. 24,24); region_grid = (rh, rw) e.g. (4,4)=16 regions.
returns LongTensor [N] with region id in [0, rh*rw).
"""
H, W = grid_hw
rh, rw = region_grid
assert H * W == num_tokens, f"{H}*{W} != {num_tokens}"
idx = torch.arange(num_tokens)
row = idx // W
col = idx % W
# region row/col via proportional binning (handles non-divisible grids)
r_row = (row * rh // H).clamp(max=rh - 1)
r_col = (col * rw // W).clamp(max=rw - 1)
return (r_row * rw + r_col).long()
def allocate_region_budgets(importance, region_ids, K, budget):
"""
Eq. 7 hybrid allocation, then integer rounding that sums exactly to `budget`
and never exceeds region population.
importance: [N]; region_ids: [N]; K regions; budget total tokens to keep.
returns dict region_id -> int budget.
"""
device = importance.device
reg_imp = torch.zeros(K, device=device)
reg_cnt = torch.zeros(K, device=device)
reg_imp.scatter_add_(0, region_ids, importance)
reg_cnt.scatter_add_(0, region_ids, torch.ones_like(importance))
# region-level importance = mean token importance within region
mean_imp = torch.where(reg_cnt > 0, reg_imp / reg_cnt.clamp_min(1), torch.zeros_like(reg_imp))
total_imp = mean_imp.sum().clamp_min(1e-9)
# B_k = B/K + B * I(X_k)/sum_j I(X_j) (Eq. 7). As written this sums to 2*B
# (both terms individually sum to B), so we renormalise the hybrid allocation
# to distribute exactly the total budget B (i.e. a 50/50 uniform+importance mix).
b_float = budget / K + budget * (mean_imp / total_imp)
# zero out empty regions
b_float = torch.where(reg_cnt > 0, b_float, torch.zeros_like(b_float))
b_float = b_float * (budget / b_float.sum().clamp_min(1e-9))
# cap by population (redistribute happens via largest-remainder below)
b_float = torch.minimum(b_float, reg_cnt)
# round preserving the exact total via largest-remainder
floor = torch.floor(b_float)
rem = b_float - floor
alloc = floor.clone()
deficit = int(round(budget - float(alloc.sum().item())))
if deficit > 0:
# give +1 to regions with largest remainder that still have capacity
cap = (reg_cnt - alloc)
order = torch.argsort(rem * (cap > 0), descending=True)
i = 0
while deficit > 0 and i < len(order):
k = order[i].item()
if cap[k] > 0:
alloc[k] += 1
cap[k] -= 1
deficit -= 1
i += 1
if i >= len(order) and deficit > 0:
# loop again over any region with capacity
cap = (reg_cnt - alloc)
order = torch.argsort(cap, descending=True)
i = 0
if float(cap.max()) <= 0:
break
elif deficit < 0:
order = torch.argsort(rem) # smallest remainder first -> remove
i = 0
while deficit < 0 and i < len(order):
k = order[i].item()
if alloc[k] > 0:
alloc[k] -= 1
deficit += 1
i += 1
return {k: int(alloc[k].item()) for k in range(K)}
def diversity_scores(token_embeds, lam=0.5, chunk=None):
"""
Eq. 8-10. token_embeds: [N, d]. D(i) = lam*sigma_i - mu_i, where S is the
cosine self-similarity matrix. Returns D: [N].
"""
x = torch.nn.functional.normalize(token_embeds.float(), dim=-1)
N = x.shape[0]
# S = x x^T (N x N); compute mu, sigma row-wise (optionally chunked for memory)
if chunk is None or N <= chunk:
S = x @ x.t()
mu = S.mean(dim=1)
sigma = S.std(dim=1, unbiased=False)
else:
mu = torch.empty(N, device=x.device)
sigma = torch.empty(N, device=x.device)
for s in range(0, N, chunk):
e = min(s + chunk, N)
Sc = x[s:e] @ x.t()
mu[s:e] = Sc.mean(dim=1)
sigma[s:e] = Sc.std(dim=1, unbiased=False)
return lam * sigma - mu
def split_select(hidden_states, token_embeds, budget,
grid_hw=(24, 24), region_grid=(4, 4), layers=None, lam=0.5):
"""
Full SPLIT selection. Returns sorted LongTensor of kept token indices (len=budget).
hidden_states: per-layer ViT hidden states for the N patch tokens (CLS removed).
token_embeds: [N, d] final patch embeddings used for diversity.
"""
N = token_embeds.shape[0]
if budget >= N:
return torch.arange(N, device=token_embeds.device)
K = region_grid[0] * region_grid[1]
device = token_embeds.device
imp = temporal_shift_importance(hidden_states, layers).to(device) # [N]
rid = region_ids_grid(N, grid_hw, region_grid).to(device) # [N]
budgets = allocate_region_budgets(imp, rid, K, budget)
D = diversity_scores(token_embeds, lam=lam) # [N]
keep = []
for k in range(K):
bk = budgets[k]
if bk <= 0:
continue
mask = (rid == k).nonzero(as_tuple=True)[0]
if mask.numel() == 0:
continue
dk = D[mask]
topk = torch.topk(dk, min(bk, mask.numel())).indices
keep.append(mask[topk])
keep = torch.cat(keep) if keep else torch.arange(min(budget, N), device=device)
return torch.sort(keep).values
# ---- baselines for comparison (Claim 3 control) ----
def random_select(N, budget, generator=None, device="cpu"):
if budget >= N:
return torch.arange(N, device=device)
perm = torch.randperm(N, generator=generator)[:budget]
return torch.sort(perm).values.to(device)
def attention_select(cls_attn, budget):
"""FastV/HiRED-style: keep top-`budget` tokens by CLS->patch attention.
cls_attn: [N] attention from CLS to each patch (already averaged over heads)."""
N = cls_attn.shape[0]
if budget >= N:
return torch.arange(N, device=cls_attn.device)
idx = torch.topk(cls_attn, budget).indices
return torch.sort(idx).values
|