模块更新于 2026-11-21· 浏览 1· 下载 1
SSM 分层草稿缓存
把目标模型预测写入后缀局部、词元局部和词元全局三层表,从具体到通用逐层回退。预填充先引导局部记忆,请求结束仅提交收到验证写回的词元条目,区分不同证据的生命周期。
结构图

把目标模型预测写入后缀局部、词元局部和词元全局三层表,从具体到通用逐层回退。预填充先引导局部记忆,请求结束仅提交收到验证写回的词元条目,区分不同证据的生命周期。
论文信息
- 论文:SuffixSpec: Hierarchical Context-Aware Memory for Training-Free Speculative Decoding
核心痛点
只按当前词元查草稿,容易混淆不同上下文;只按较长后缀查,又容易缺失。预填充阶段已经算出的预测也常被闲置。
模块亮点
- 把目标模型预测写入后缀局部、词元局部和词元全局三层表,从具体到通用逐层回退。预填充先引导局部记忆,请求结束仅提交收到验证写回的词元条目,区分不同证据的生命周期。
适用场景
已有目标模型验证器的树式投机解码系统,尤其适合研究免训练草稿检索。上下文长度、并发与验证成本会改变实际收益,其他任务需单独验证。
插入位置建议
- 接在草稿树节点展开处,并把预填充与验证预测接入写回。调用方需传真实后缀历史、管理批量槽位和请求重置;敏感业务隔离全局记忆,候选始终交给目标模型验证。
适用任务
- 已有目标模型验证器的树式投机解码系统
- 尤其适合研究免训练草稿检索。上下文长度
- 并发与验证成本会改变实际收益
完整代码
ssm.py
"""SuffixSpec 分层草稿记忆(模块名 SuffixSpecMemory)。
论文:SuffixSpec: Hierarchical Context-Aware Memory for Training-Free Speculative Decoding。
免训练投机解码没有草稿模型,只能用目标模型在 prefill 与每次验证时已经算出的 top-K 预测:
只按单个 token 索引则命中多但不精确,按长后缀索引则精确却常常缺失。本模块把这些预测写入
三层记忆——末 m 个 token 哈希键的后缀表、按当前 token 键的请求内局部表、跨请求常驻的 token
全局表——查询按“后缀→token 局部→token 全局→固定默认”逐级回退;写出区分验证写回与 prefill
引导,只在请求结束时把验证过的 token 条目提交到全局表。输入批量 token 与其 top-K 预测,
输出每个位置的候选草稿及命中的记忆层级。
"""
import sys
import torch
import torch.nn as nn
class SuffixSpecMemory(nn.Module):
"""分层上下文感知草稿记忆:三层查找 + 双时间尺度提交。"""
def __init__(
self,
vocab_size: int = 32000,
top_k: int = 8,
suffix_len: int = 3,
num_buckets: int = 16384,
max_batch: int = 4,
default_token: int = 0,
) -> None:
super().__init__()
assert top_k >= 1 and suffix_len >= 1 and max_batch >= 1
self.vocab_size = int(vocab_size)
self.top_k = int(top_k)
self.suffix_len = int(suffix_len)
self.num_buckets = int(num_buckets)
self.max_batch = int(max_batch)
self.default_token = int(default_token)
# 记忆是推理缓存而非参数:不进入 state_dict。候选恒为 top-K 个 token id。
self.register_buffer("suf_tab", torch.zeros(max_batch, num_buckets, top_k, dtype=torch.long), persistent=False)
self.register_buffer("suf_ok", torch.zeros(max_batch, num_buckets, dtype=torch.bool), persistent=False)
self.register_buffer("tok_tab", torch.zeros(max_batch, vocab_size, top_k, dtype=torch.long), persistent=False)
self.register_buffer("tok_ok", torch.zeros(max_batch, vocab_size, dtype=torch.bool), persistent=False)
self.register_buffer("glo_tab", torch.zeros(vocab_size, top_k, dtype=torch.long), persistent=False)
self.register_buffer("glo_ok", torch.zeros(vocab_size, dtype=torch.bool), persistent=False)
self.register_buffer("pending", torch.zeros(max_batch, vocab_size, dtype=torch.bool), persistent=False)
def forward(
self,
tokens: torch.Tensor, # (B, T) long,请求内上下文 token
topk_ids: torch.Tensor | None = None, # (B, T, K) long,目标模型在各位置的 top-K 预测
write_mask: torch.Tensor | None = None, # (B, T) bool,True=验证写回,False=prefill 引导
new_request: bool = False, # True:先清空请求内局部表与 pending 集
commit: bool = False, # True:请求结束,把 pending 的 token 条目提交到全局表
) -> tuple[torch.Tensor, torch.Tensor]:
if tokens.dim() != 2:
raise ValueError(f"tokens 需为 (B, T),收到 {tuple(tokens.shape)}")
B, T = tokens.shape
if T == 0:
raise ValueError("tokens 每个样本至少需要 1 个位置")
if B > self.max_batch:
raise ValueError(f"batch {B} 超过 max_batch={self.max_batch}")
if new_request:
self.suf_ok[:B].zero_()
self.tok_ok[:B].zero_()
self.pending[:B].zero_()
tokens = tokens.long()
if tokens.numel() and int(tokens.max()) >= self.vocab_size:
raise ValueError("tokens 中存在越界 token id")
# 每个位置的后缀状态 s_t:末 m 个 token,按多项式滚动哈希映射到桶
head = tokens[:, :1].expand(B, self.suffix_len - 1)
windows = torch.cat([head, tokens], dim=1).unfold(1, self.suffix_len, 1) # (B, T, m)
h = torch.zeros_like(tokens)
for j in range(self.suffix_len):
h = (h * 1000003 + windows[..., j]) % self.num_buckets
# 分层查找:后缀 → token 局部 → token 全局 → 固定默认条目
K = self.top_k
suf_cand = torch.gather(self.suf_tab[:B], 1, h.unsqueeze(-1).expand(-1, -1, K))
suf_hit = torch.gather(self.suf_ok[:B], 1, h)
tok_cand = torch.gather(self.tok_tab[:B], 1, tokens.unsqueeze(-1).expand(-1, -1, K))
tok_hit = torch.gather(self.tok_ok[:B], 1, tokens)
flat = tokens.reshape(-1)
glo_cand = self.glo_tab.index_select(0, flat).view(B, T, K)
glo_hit = self.glo_ok.index_select(0, flat).view(B, T)
drafts = suf_cand.clone() # (B, T, K)
layer = torch.full_like(tokens, 3) # 0 后缀 / 1 token 局部 / 2 全局 / 3 默认
layer[suf_hit] = 0
use_tok = tok_hit & ~suf_hit
drafts[use_tok] = tok_cand[use_tok]
layer[use_tok] = 1
use_glo = glo_hit & ~suf_hit & ~tok_hit
drafts[use_glo] = glo_cand[use_glo]
layer[use_glo] = 2
miss = ~suf_hit & ~tok_hit & ~glo_hit
drafts[miss] = self.default_token
# 写出:后缀键与 token 键各自覆盖旧条目;只有验证写回的行进入 pending 集
if topk_ids is not None:
if topk_ids.shape[:2] != tokens.shape or topk_ids.shape[-1] != K:
raise ValueError(f"topk_ids 需为 {(B, T, K)},收到 {tuple(topk_ids.shape)}")
if write_mask is None:
write_mask = torch.ones_like(tokens, dtype=torch.bool)
if write_mask.shape != tokens.shape:
raise ValueError(f"write_mask 需为 {tokens.shape},收到 {tuple(write_mask.shape)}")
self._write(h, tokens, topk_ids.long(), write_mask.bool())
if commit:
for b in range(B):
idx = self.pending[b].nonzero().squeeze(1)
if idx.numel():
self.glo_tab[idx] = self.tok_tab[b, idx]
self.glo_ok[idx] = True
self.pending.zero_()
return drafts, layer
def _write(self, h, tokens, topk, mask):
"""所有行都写入局部表;只有 mask 为 True 的验证行进入 pending 集。"""
B = tokens.shape[0]
K = self.top_k
batch = torch.arange(B, device=h.device).unsqueeze(1)
keys = (
((h + batch * self.num_buckets).reshape(-1), self.suf_tab, self.suf_ok, False),
((tokens + batch * self.vocab_size).reshape(-1), self.tok_tab, self.tok_ok, True),
)
values = topk.reshape(-1, K)
for key, tab, ok, to_pending in keys:
order = torch.argsort(key, stable=True) # 等键内保持位置升序
k, v = key[order], values[order]
last = torch.ones_like(k, dtype=torch.bool)
last[:-1] = k[1:] != k[:-1]
tab.view(-1, K)[k[last]] = v[last] # 同键后写覆盖先写
ok.view(-1)[k[last]] = True
if to_pending:
self.pending.view(-1)[key[mask.reshape(-1)]] = True
if __name__ == "__main__":
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
torch.manual_seed(0)
V, K, B, T = 512, 4, 2, 16
mem = SuffixSpecMemory(vocab_size=V, top_k=K, suffix_len=3, num_buckets=4096, max_batch=B)
prompt = torch.randint(1, V, (B, T))
prefill_topk = torch.randn(B, T, V).topk(K, dim=-1).indices
bootstrap_mask = torch.zeros(B, T, dtype=torch.bool) # prefill 引导:不进 pending 集
drafts, layer = mem(prompt, prefill_topk, bootstrap_mask, new_request=True)
print("bootstrap input :", tuple(prompt.shape), tuple(prefill_topk.shape))
print("bootstrap output:", tuple(drafts.shape), tuple(layer.shape),
"layer hist", torch.bincount(layer.reshape(-1), minlength=4).tolist())
drafts, layer = mem(prompt) # prefill 引导后立刻查询:后缀键命中
print("suffix lookup :", tuple(drafts.shape), "layer hist",
torch.bincount(layer.reshape(-1), minlength=4).tolist())
cur = prompt[:, -1:]
verify_topk = torch.randn(B, 1, V).topk(K, dim=-1).indices # 验证写回:进入 pending 集
drafts, layer = mem(cur, verify_topk)
print("decode step :", (tuple(cur.shape), tuple(verify_topk.shape)), "->",
tuple(drafts.shape), "layer hist", torch.bincount(layer.reshape(-1), minlength=4).tolist())
mem(cur, commit=True) # 请求结束:验证过的 token 条目提交到全局表
drafts, layer = mem(cur, new_request=True) # 新请求:局部表清空,同 token 由全局表接住
print("new request :", tuple(drafts.shape), "layer hist",
torch.bincount(layer.reshape(-1), minlength=4).tolist(),
"| global entries", int(mem.glo_ok.sum()), "/", V)
环境与依赖
Python 3.9+
继续浏览
下一篇TAR 令牌感知细化拆成三个部件协同处理。TRM 用 Token 范数统计估计可靠性,做重加权和筛选;CATS 结合全局表示计算条件权重,并加一致性正则;GRM 再把聚合后的局部信息门控注入全局特征。相关资源
模块2026-11-21
CARE-Q 误差补偿量化
用双路校准激活形成共享补偿表示,对角信号指导候选舍入,非对角信息执行双路传播。它属于离线逐列重建,不是推理时额外运行的修正模块。
大语言模型模型量化训练后量化
深度学习MIT
模块2026-11-21
PiCoKV 二值码KV注意力
将解码矩阵折入查询侧和词元归约之后,让键打分与值聚合都在二值码上进行位运算。密集和全局分支共享归一化;所附源码是算子示范,并非专用高速内核。
大语言模型KV缓存模型量化
深度学习MIT
模块2026-11-21
RCG 跨会话记忆门
共享门逐坐标决定旧状态保留多少、新会话写入多少,首段直接初始化,后续递归融合到固定形状状态。该门是整体参数记忆架构中的整合环节,不包含文本编译或LoRA生成。
大语言模型智能体记忆循环门控
深度学习MIT