知识卡片
缓存重置包含两处状态
本章模型保存current_pos,KVCache对象保存各层键值,二者有各自reset。开始新请求时只重置其中一处可能使位置与历史张量失配;应把它们当作一个生成会话的联合状态,并避免在同一模型实例上无隔离交错请求。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- · 查看原书依据
self.current_pos = 0 # Track current position in KV cache def forward(self, in_idx, cache=None): tok_embeds = self.tok_emb(in_idx) x = tok_embeds num_tokens = x.shape[1] if cache is not None: pos_start = self.current_pos pos_end = pos_start + num_tokens self.current_pos = pos_end mask = torch.triu( torch.ones( pos_end, pos_end, device=x.device, dtype=torch.bool ), diagonal=1 )[pos_start:pos_end, :pos_end] else:
参考来源
- 位置:《Build a Reasoning Model (From Scratch)》第09章《附录C Qwen3模型源码》(来源项目:a19c7933-4eda-4176-aebd-30fe7e1ad292;源文件:extracted/Build a Reasoning Model (From Scratch)/_epub-src/OEBPS/Text/appendix-c.html)
- 结论依据:摘录中关于缓存重置包含两处状态的定义、比较或条件支撑卡片;原书表述不严谨的范围已在覆盖记录逐项限定,不把案例结果外推为普遍结论。
- 原始内容:self.current_pos = 0 # Track current position in KV cache def forward(self, in_idx, cache=None): tok_embeds = self.tok_emb(in_idx) x = tok_embeds num_tokens = x.shape[1] if cache is not None: pos_start = self.current_pos pos_end = pos_start + num_tokens self.current_pos = pos_end mask = torch.triu( torch.ones( pos_end, pos_end, device=x.device, dtype=torch.bool ), diagonal=1 )[pos_start:pos_end, :pos_end] else: