local_kv_cache¶
- torchtune.modules.common_utils.local_kv_cache(model: Module, *, batch_size: int, device: device, dtype: dtype, encoder_max_seq_len: Optional[int] = None, decoder_max_seq_len: Optional[int] = None) Generator[None, None, None][source]¶
此上下文管理器临时启用给定模型上的KV缓存,该模型尚未设置KV缓存。在此上下文管理器中使用模型的所有前向传递都将使用KV缓存。
KV缓存将在进入上下文管理器时使用给定的
batch_size、dtype和max_seq_len进行设置,并在退出时删除。示例
>>> from torchtune.models.llama3_2 import llama3_2_1b >>> from torchtune.modules import local_kv_cache >>> import torch >>> model = llama3_2_1b() >>> print(model.caches_are_setup()) False >>> print(model.caches_are_enabled()) False >>> print(model.layers[0].attn.kv_cache) None >>> # entering cacheing mode >>> with local_kv_cache(model, >>> batch_size=1, >>> device=torch.device("cpu"), >>> 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() >>> # exited cacheing mode >>> print(model.caches_are_setup()) False >>> print(model.caches_are_enabled()) False >>> print(model.layers[0].attn.kv_cache) None
- Parameters:
model (nn.Module) – 为模型启用KV缓存。
batch_size (int) – 缓存的批量大小。
device (torch.device) – 用于设置缓存的设备。这应该与模型所在的设备相同。
dtype (torch.dpython:type) – 缓存的dtype。
encoder_max_seq_len (可选[int]) – 编码器缓存的最大序列长度。
decoder_max_seq_len (可选[int]) – 最大解码器缓存序列长度。
- Yields:
None – 返回控制给调用者,并在给定模型上设置并启用KV缓存。
- Raises:
ValueError – 如果模型已经设置了缓存。 您可以使用
delete_kv_caches()来删除现有的缓存。