""" 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