知识卡片
缓存状态属于一次生成
本章每次生成初始化 KVCache 并重置模型相关位置状态,再预填充输入。新请求若误用旧请求的缓存,历史内容和位置可能混入结果。缓存生命周期、位置编号和输入前缀一致性,是推理正确性的一部分。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- · 查看原书依据
token_ids, max_new_tokens, eos_token_id=None ): input_length = token_ids.shape[1] model.eval() cache = KVCache(n_layers=model.cfg["n_layers"]) #A model.reset_kv_cache() out = model(token_ids, cache=cache)[:, -1] #B for _ in range(max_new_tokens): next_token = torch.argmax(out, dim=-1, keepdim=True) if (eos_token_id is not None and next_token.item() == eos_token_id): break token_ids = torch.cat([token_ids, next_token], dim=1) out = model(next_token, cache=cache)[:, -1] #C return token_ids[:, input_length:] #A Initialize the KV cache #B In the first round, the whole input
参考来源
- 位置:《Build a Reasoning Model (From Scratch)》第02章《使用预训练模型生成文本》(来源项目:a19c7933-4eda-4176-aebd-30fe7e1ad292;源文件:extracted/Build a Reasoning Model (From Scratch)/_epub-src/OEBPS/Text/chapter-2.html)
- 结论依据:摘录中关于缓存状态属于一次生成的定义、比较或条件支撑卡片;原书表述不严谨的范围已在覆盖记录逐项限定,不把案例结果外推为普遍结论。
- 原始内容:token_ids, max_new_tokens, eos_token_id=None ): input_length = token_ids.shape[1] model.eval() cache = KVCache(n_layers=model.cfg["n_layers"]) #A model.reset_kv_cache() out = model(token_ids, cache=cache)[:, -1] #B for _ in range(max_new_tokens): next_token = torch.argmax(out, dim=-1, keepdim=True) if (eos_token_id is not None and next_token.item() == eos_token_id): break token_ids = torch.cat([token_ids, next_token], dim=1) out = model(next_token, cache=cache)[:, -1] #C return token_ids[:, input_length:] #A Initialize the KV cache #B In the first round, the whole input