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

Method update

deepspeed/utils/static_cache.py:88–131  ·  view source on GitHub ↗
(
        self,
        key_states: torch.Tensor,
        value_states: torch.Tensor,
        *args,
        **kwargs,
    )

Source from the content-addressed store, hash-verified

86 self.is_initialized = True
87
88 def update(
89 self,
90 key_states: torch.Tensor,
91 value_states: torch.Tensor,
92 *args,
93 **kwargs,
94 ) -> tuple[torch.Tensor, torch.Tensor]:
95 if not self.is_initialized:
96 self.lazy_initialization(key_states, value_states)
97 # Under autocast, keys and values can arrive in different dtypes: rotary embeddings
98 # promote bf16 key projections to fp32 while value projections stay bf16.
99 key_states = key_states.to(self.dtype)
100 value_states = value_states.to(self.dtype)
101
102 kv_length = key_states.shape[-2]
103
104 if self._write_position is not None and self._write_position.dim() == 1:
105 if self._write_position.numel() < key_states.shape[0]:
106 raise ValueError("per-row write positions must cover the active batch size")
107 if kv_length != 1:
108 raise ValueError("per-row write positions currently support one decode token at a time")
109 cache_position = self._write_position[:key_states.shape[0]].to(self.device)
110 is_capturing = get_accelerator().is_current_stream_capturing()
111 if not is_capturing and ((cache_position < 0).any() or (cache_position >= self.max_cache_len).any()):
112 raise ValueError("per-row write positions must be within the cache bounds")
113 row_indices = torch.arange(key_states.shape[0], device=self.device)
114 self.keys[row_indices, :, cache_position, :] = key_states[:, :, 0, :]
115 self.values[row_indices, :, cache_position, :] = value_states[:, :, 0, :]
116 active_batch_size = key_states.shape[0]
117 return self.keys[:active_batch_size], self.values[:active_batch_size]
118
119 if self._write_position is not None:
120 cache_position = torch.arange(kv_length, device=self.device) + self._write_position
121 else:
122 cache_position = torch.arange(kv_length, device=self.device)
123
124 try:
125 self.keys.index_copy_(2, cache_position, key_states)
126 self.values.index_copy_(2, cache_position, value_states)
127 except NotImplementedError:
128 self.keys[:, :, cache_position] = key_states
129 self.values[:, :, cache_position] = value_states
130
131 return self.keys, self.values
132
133 def get_mask_sizes(self, query_length: int) -> tuple[int, int]:
134 # Mirror HF StaticLayer exactly: static caches answer with the full

Calls 5

lazy_initializationMethod · 0.95
get_acceleratorFunction · 0.90
toMethod · 0.45
numelMethod · 0.45