Atharva31's picture
Upload IndicSLM checkpoints, code, and model card
ddc7239 verified
Raw History Blame Contribute Delete
3.36 kB
"""
KV cache for incremental (token-by-token) decoding.
Design decisions:
- Pre-allocated fixed-size buffers (batch, n_kv_heads, max_seq_len,
head_dim) per layer, written in-place via slice assignment (O(1) per
step), rather than growing a Python list and torch.cat-ing every step
(which would be O(seq_len^2) total copy work over a generation).
- Caches POST-RoPE keys and un-rotated values (RoPE is never applied to
values), matching attention.py which rotates before writing to cache.
- One KVCache instance holds buffers for ALL layers, indexed by layer_idx,
so model.py passes around a single object; reset() clears every layer.
- Sized by n_kv_heads (not n_heads): the cache stores GQA-grouped k/v
before the repeat-to-n_heads broadcast, since that broadcast is
deterministic/cheap to redo per step — storing already-repeated tensors
would waste (n_heads/n_kv_heads)x memory for no benefit.
"""
import torch
class KVCache:
def __init__(self, n_layers: int, batch_size: int, n_kv_heads: int, max_seq_len: int, head_dim: int, dtype: torch.dtype = torch.float32, device: str = "cpu"):
self.max_seq_len = max_seq_len
self.n_layers = n_layers
self.k_cache = [torch.zeros(batch_size, n_kv_heads, max_seq_len, head_dim, dtype = dtype, device = device) for _ in range(n_layers)]
self.v_cache = [torch.zeros(batch_size, n_kv_heads, max_seq_len, head_dim, dtype = dtype, device = device) for _ in range(n_layers)]
self.seq_len = 0 #These are the positions written so far
def reset(self):
for k, v in zip(self.k_cache, self.v_cache):
k.zero_() #This Overwrites every number in our current Key tensor from Cache to 0 without allocating a new Tensor
v.zero_() #This Overwrites every number in our current Key tensor from Cache to 0 without allocating a new Tensor
self.seq_len = 0
def update(self, layer_idx: int, new_k: torch.Tensor, new_v: torch.Tensor):
"""
Writes new_k/new_v into this layer's buffer starting at seq_len,
returns the full valid k/v so far. The caller (model.py) must call
`cache.step(new_tokens)` exactly ONCE per forward pass, after ALL
layers have been updated — not once per layer — so every layer
writes at the same start offset within one forward call.
"""
start = self.seq_len #This is the position in the buffer to store the new incoming Key,Value tensor
end = start + new_k.shape[2] #new_k.shape[2] is the seq_len dimension of the incoming tensor
assert end <= self.max_seq_len, f"KV Cache overflow: {end} > max_seq_len = {self.max_seq_len}"
#We are picking the layer_idx buffer from the cache and getting all batch items, all heads, only the new slots in place of seq-len and all channels
self.k_cache[layer_idx][:, :, start:end, :] = new_k #This means "In this layer's buffer, at exactly new positions we haven't filled yet, drop in the new keys"
self.v_cache[layer_idx][:, :, start:end, :] = new_v
return self.k_cache[layer_idx][:, :, :end, :], self.v_cache[layer_idx][:, :, :end, :]
def step(self, n_new_tokens: int):
self.seq_len += n_new_tokens