SearchJev-27B / searchjev /shared_prefix.py
byfrfy's picture
SearchJev 27B: adapter, calibration, server
5a81b57 verified
Raw History Blame Contribute Delete
5.82 kB
"""Shared-prefix inference for multi-question Decision Index requests (user 2026-11-05: approved latency work on the
idle GPU 0, inference code only).
Every question of one JEV request repeats the same system prompt + STATE before its own question and options, and
JEVPredictor encodes each full prompt separately, so a 17-question request with a 3,000-token state costs 17 x 3,000
tokens. Here the longest common token prefix of a request's prompts is run once (batch 1, use_cache=True); its cache
(key/value of the full-attention layers, conv + recurrent states of the linear-attention layers) is then copied for
each batch of question suffixes, which run right-padded on top of it. The menu logits are read at each suffix's last
real token, so every question sees exactly the tokens it saw before (only the floating-point evaluation order of the
chunked kernels differs). Right padding matters: pads before a question would shift the conv window and decay the
recurrent state of the linear-attention layers.
from shared_prefix import SharedPrefixPredictor # same arguments as JEVPredictor
"""
from __future__ import annotations
import copy
import sys
sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
import torch # noqa: E402
from training.inference import JEVPredictor # noqa: E402
MIN_PREFIX = 64 # shorter common prefixes are not worth a separate forward pass
def _expand_cache(cache, b: int):
"""Copy of a batch-1 cache with every state repeated to batch ``b`` (fresh tensors: the linear-attention states
are updated in place by the next forward)."""
c = copy.copy(cache)
c.layers = []
for layer in cache.layers:
lay = copy.copy(layer)
for name in ("conv_states", "recurrent_states"):
st = getattr(layer, name, None)
if isinstance(st, dict):
setattr(lay, name, {k: (None if v is None else v.expand(b, *v.shape[1:]).contiguous())
for k, v in st.items()})
for name in ("has_previous_state", "is_conv_states_initialized", "is_recurrent_states_initialized",
"conv_kernel_size"):
if isinstance(getattr(layer, name, None), dict):
setattr(lay, name, dict(getattr(layer, name)))
keys = getattr(layer, "keys", None)
if isinstance(keys, torch.Tensor) and keys.numel() > 0:
lay.keys = keys.expand(b, *keys.shape[1:]).contiguous()
lay.values = layer.values.expand(b, *layer.values.shape[1:]).contiguous()
c.layers.append(lay)
return c
class SharedPrefixPredictor(JEVPredictor):
"""JEVPredictor whose multi-question calls run the common prompt prefix once (``share_prefix = False`` gives the
original behaviour, for comparisons)."""
share_prefix = True
def _backbone(self):
m = self.model
return m.model, m.lm_head
@torch.inference_mode()
def _display_logits(self, examples, perms):
n = len(examples)
if n < 2 or not self.share_prefix:
return super()._display_logits(examples, perms)
if perms is None:
perms = [None] * n
encoded = [self._encode(ex, perm) for ex, perm in zip(examples, perms)]
truncated = [bool(e.get("truncated", False)) for e in encoded]
ids = [e["input_ids"] for e in encoded]
first = ids[0]
p = min(len(x) for x in ids) - 1 # every suffix keeps at least one token
for x in ids[1:]:
k = 0
while k < p and x[k] == first[k]:
k += 1
p = k
if p < MIN_PREFIX:
order = sorted(range(n), key=lambda i: -len(ids[i]))
out = [None] * n
for idx in self._batches(order, [len(x) for x in ids]):
for i, lg in zip(idx, self._forward([encoded[i] for i in idx])):
out[i] = lg
return out, truncated
backbone, lm_head = self._backbone()
dev = self.device
prefix = torch.as_tensor([first[:p]], dtype=torch.long, device=dev)
cache = backbone(input_ids=prefix, use_cache=True).past_key_values
suf = [x[p:] for x in ids]
ks = [int(e["num_options"]) for e in encoded]
order = sorted(range(n), key=lambda i: -len(suf[i]))
out = [None] * n
budget = self.max_batch_tokens or 131072
i0 = 0
while i0 < n:
width = len(suf[order[i0]])
b = max(1, min(self.batch_size, budget // (p + width), n - i0))
idx = order[i0:i0 + b]
i0 += b
input_ids = torch.full((b, width), self.pad_token_id, dtype=torch.long)
mask = torch.zeros((b, p + width), dtype=torch.long)
mask[:, :p] = 1
lens = []
for r, i in enumerate(idx):
s = suf[i]
input_ids[r, :len(s)] = torch.as_tensor(s, dtype=torch.long)
mask[r, p:p + len(s)] = 1
lens.append(len(s))
h = backbone(input_ids=input_ids.to(dev), attention_mask=mask.to(dev),
past_key_values=_expand_cache(cache, b), use_cache=True).last_hidden_state
last = h[torch.arange(b, device=dev), torch.as_tensor(lens, device=dev) - 1]
logits = lm_head(last).float()
k_max = max(ks[i] for i in idx)
label_ids = torch.zeros((b, k_max), dtype=torch.long)
for r, i in enumerate(idx):
label_ids[r, :ks[i]] = torch.as_tensor(self.label_space.ids_for(ks[i]), dtype=torch.long)
menu = logits.gather(1, label_ids.to(dev)).cpu()
for r, i in enumerate(idx):
out[i] = menu[r, :ks[i]].tolist()
return out, truncated