MCPcopy Create free account
hub / github.com/deepspeedai/DeepSpeed / DeepSpeedStaticLayer

Class DeepSpeedStaticLayer

deepspeed/utils/static_cache.py:34–191  ·  view source on GitHub ↗

A single layer's static KV cache whose write position is externally set. Parameters ---------- max_cache_len : int Maximum number of tokens the cache can hold (last dim size).

Source from the content-addressed store, hash-verified

32
33
34class DeepSpeedStaticLayer:
35 """A single layer's static KV cache whose write position is externally set.
36
37 Parameters
38 ----------
39 max_cache_len : int
40 Maximum number of tokens the cache can hold (last dim size).
41 """
42
43 is_compileable = True
44 is_sliding = False
45
46 def __init__(self, max_cache_len: int):
47 self.max_cache_len = max_cache_len
48 self.keys: torch.Tensor | None = None
49 self.values: torch.Tensor | None = None
50 self.is_initialized = False
51 self._write_position: torch.Tensor | None = None
52
53 def set_write_position(self, pos: torch.Tensor):
54 if not isinstance(pos, torch.Tensor) or pos.dim() not in (0, 1):
55 raise ValueError("write position must be a scalar or a 1-D tensor")
56 if pos.dtype not in (torch.int32, torch.int64):
57 raise ValueError("write position must use an integer dtype")
58 self._write_position = pos
59
60 def lazy_initialization(self,
61 key_states: torch.Tensor,
62 value_states: torch.Tensor,
63 max_batch_size: int | None = None) -> None:
64 self.dtype = key_states.dtype
65 self.device = key_states.device
66 num_heads = key_states.shape[1]
67 if max_batch_size is None:
68 max_batch_size = key_states.shape[0]
69 self.max_batch_size = max_batch_size
70 self.num_heads = num_heads
71 self.k_head_dim = key_states.shape[-1]
72 self.v_head_dim = value_states.shape[-1]
73
74 self.keys = torch.zeros(
75 (max_batch_size, num_heads, self.max_cache_len, self.k_head_dim),
76 dtype=self.dtype,
77 device=self.device,
78 )
79 self.values = torch.zeros(
80 (max_batch_size, num_heads, self.max_cache_len, self.v_head_dim),
81 dtype=self.dtype,
82 device=self.device,
83 )
84 torch._dynamo.mark_static_address(self.keys)
85 torch._dynamo.mark_static_address(self.values)
86 self.is_initialized = True
87
88 def update(
89 self,
90 key_states: torch.Tensor,
91 value_states: torch.Tensor,

Calls

no outgoing calls