禁用键值缓存¶
- torchtune.modules.common_utils.disable_kv_cache(model: Module) Generator[None, None, None][source]¶
此上下文管理器临时禁用给定模型上的KV缓存,该模型必须已经设置了KV缓存。在此上下文管理器中使用该模型的所有前向传递将不会使用KV缓存。
进入上下文管理器时,KV缓存将被禁用,并在退出时重新启用,且不会被修改。
这在我们可能希望在使用KV缓存的模型调用和不使用KV缓存的模型调用之间交替的情况下非常有用,而无需每次删除和设置缓存的额外开销。
示例
>>> from torchtune.models.llama3_2 import llama3_2_1b >>> from torchtune.modules import disable_kv_cache >>> import torch >>> model = llama3_2_1b() >>> # setup caches >>> model.setup_caches(batch_size=1, >>> dtype=torch.float32, >>> decoder_max_seq_len=1024) >>> print(model.caches_are_setup()) True >>> print(model.caches_are_enabled()) True >>> print(model.layers[0].attn.kv_cache) KVCache() >>> # now temporarily disable caches >>> with disable_kv_cache(model): >>> print(model.caches_are_setup()) True >>> print(model.caches_are_enabled()) False >>> print(model.layers[0].attn.kv_cache) KVCache() >>> # caches are now re-enabled, and their state is untouched >>> print(model.caches_are_setup()) True >>> print(model.caches_are_enabled()) True >>> print(model.layers[0].attn.kv_cache) KVCache()
- Parameters:
model (nn.Module) – 禁用KV缓存的模型。
- Yields:
None – 在给定模型上禁用KV缓存的情况下,将控制权返回给调用者。
- Raises:
ValueError – 如果模型没有设置缓存。请先使用
setup_caches()来设置缓存。