Download indexer.py from M-Ma/SparseGUI-Indexer: direct link, hf CLI and curl.
- Browser
- Download file 5.86 kB
-
https://huggingface.co/M-Ma/SparseGUI-Indexer/resolve/main/indexer.py
- Command line
-
hf download hf://M-Ma/SparseGUI-Indexer/indexer.py
-
curl -L -o indexer.py https://huggingface.co/M-Ma/SparseGUI-Indexer/resolve/main/indexer.py
5.86 kB
| """Reference implementation of the SparseGUI Indexer (DSA-style, no source embedding). | |
| The Indexer picks, for every decoder layer and every decode query, which prompt tokens the | |
| query attends to. One pair of projections is shared by all layers: | |
| q~ = W_q q q: post-RoPE query of the decode token, all query heads, flattened | |
| k~ = W_k k k: post-RoPE key of a prompt token, all KV heads, flattened | |
| r = q~ . k~ / sqrt(index_dim) | |
| Per layer, the kept set of a decode query is | |
| top-B routed prompt tokens by r U always-on tokens U tokens generated in this turn | |
| where the always-on tokens are ``always_on.head_positions`` plus the last | |
| ``always_on.tail_window`` prompt positions, and every other prompt position is routed. | |
| All heads of a layer use the same kept set (GQA). Prefill stays dense; only the last prompt | |
| position and the generated tokens are sparsified. If the number of routed tokens is at most B, | |
| nothing is dropped. | |
| Every backbone has its own checkpoint folder (config.json + model.safetensors); this file reads | |
| all dimensions from config.json and works for each of them. | |
| This file needs only torch and safetensors (plus huggingface_hub to download). It reproduces | |
| the scores and selections of the training / inference code (``sparsegui.sparse.gather``); | |
| the fused prefix-cache and CUDA-graph runtime used for the paper's timings lives in the | |
| SparseGUI code repository: | |
| https://github.com/MichelleMa8/SparseGUI | |
| from indexer import Indexer | |
| idx = Indexer.from_pretrained("M-Ma/SparseGUI-Indexer", subfolder="evocua-8b-20260105") | |
| kt = idx.keys(k_post) # k_post [L, n_kv_heads, head_dim] -> [L, d] (cache this) | |
| kept = idx.select(q_post, kt, prompt_len) # q_post [n_q_heads, head_dim] -> sorted kept positions | |
| ``from_pretrained`` also takes a local copy of the repository (with ``subfolder``) or a local | |
| checkpoint folder (without it). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| from pathlib import Path | |
| import torch | |
| from safetensors.torch import load_file | |
| class Indexer(torch.nn.Module): | |
| def __init__(self, config: dict): | |
| super().__init__() | |
| self.config = config | |
| q_dim = config["n_q_heads"] * config["head_dim"] | |
| k_dim = config["n_kv_heads"] * config["head_dim"] | |
| d = config["index_dim"] | |
| self.w_q = torch.nn.Linear(q_dim, d, bias=False) | |
| self.w_k = torch.nn.Linear(k_dim, d, bias=False) | |
| self.scale = 1.0 / math.sqrt(d) | |
| def from_pretrained(cls, path_or_repo: str | Path, subfolder: str | None = None, | |
| revision: str | None = None, device="cpu") -> "Indexer": | |
| """Load one checkpoint folder from a local path or a Hub repository. | |
| ``subfolder`` names the backbone checkpoint inside the repository (for example | |
| ``"evocua-8b-20260105"``). From the Hub only that folder is downloaded. | |
| """ | |
| path = Path(path_or_repo) | |
| if not path.exists(): | |
| from huggingface_hub import snapshot_download | |
| patterns = [f"{subfolder.strip('/')}/*"] if subfolder else None | |
| path = Path(snapshot_download(str(path_or_repo), revision=revision, | |
| allow_patterns=patterns)) | |
| if subfolder: | |
| path = path / subfolder | |
| if not (path / "config.json").is_file(): | |
| found = sorted(p.parent.name for p in path.glob("*/config.json")) | |
| raise FileNotFoundError( | |
| f"no config.json in {path}; pass subfolder=" + (" or ".join(map(repr, found)) | |
| if found else "<checkpoint folder>")) | |
| config = json.loads((path / "config.json").read_text()) | |
| model = cls(config) | |
| model.load_state_dict(load_file(str(path / "model.safetensors")), strict=True) | |
| return model.to(device).eval() | |
| def keys(self, k_post: torch.Tensor) -> torch.Tensor: | |
| """Indexer keys k~ [L, index_dim] for post-RoPE keys [L, n_kv_heads, head_dim].""" | |
| return self.w_k(k_post.reshape(k_post.shape[0], -1).float()) | |
| def scores(self, q_post: torch.Tensor, keys: torch.Tensor) -> torch.Tensor: | |
| """Scores r [L] of one decode query (post-RoPE, [n_q_heads, head_dim]) over k~ [L, d].""" | |
| q = self.w_q(q_post.reshape(1, -1).float()) | |
| return (q @ keys.T)[0] * self.scale | |
| def always_on_mask(self, prompt_len: int) -> torch.Tensor: | |
| ao = self.config["always_on"] | |
| m = torch.zeros(prompt_len, dtype=torch.bool) | |
| for p in ao["head_positions"]: | |
| if 0 <= p < prompt_len: | |
| m[p] = True | |
| if ao["tail_window"] > 0: | |
| m[max(0, prompt_len - ao["tail_window"]):] = True | |
| return m | |
| def select(self, q_post: torch.Tensor, keys: torch.Tensor, prompt_len: int, | |
| total_len: int | None = None, budget: int | None = None) -> torch.Tensor: | |
| """Sorted positions one layer keeps for one decode query. | |
| ``keys`` holds k~ of the prompt positions [0, prompt_len); positions in | |
| [prompt_len, total_len) are this turn's generated tokens and are always kept. | |
| """ | |
| budget = self.config["budget"] if budget is None else budget | |
| total_len = prompt_len if total_len is None else total_len | |
| ao = self.always_on_mask(prompt_len).to(keys.device) | |
| routed = (~ao).nonzero().squeeze(1) | |
| if budget >= routed.numel(): | |
| chosen = routed | |
| else: | |
| r = self.scores(q_post, keys[:prompt_len])[routed] | |
| chosen = routed[torch.topk(r, budget).indices] | |
| turn = torch.arange(prompt_len, total_len, device=keys.device) | |
| return torch.sort(torch.cat([ao.nonzero().squeeze(1), chosen, turn])).values | |