huggingface/transformers · #50993

Fix dory static cache

ArthurZucker · merged Nov 23, 20263 files · 140 + / 49 −
src/transformers/models/dory/modeling_dory.py58 + / 23 −
@@ -26,7 +26,15 @@  from ... import initialization as init from ...activations import ACT2FN-from ...cache_utils import Cache, DynamicCache+from ...cache_utils import (+    Cache,+    DummyLayer,+    DynamicCache,+    DynamicLayer,+    DynamicSlidingWindowLayer,+    StaticLayer,+    StaticSlidingWindowLayer,+) from ...generation import GenerationMixin from ...integrations import use_kernel_forward_from_hub, use_kernelized_func from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask@@ -119,6 +127,42 @@ def forward(self, x, position_ids, layer_type):         return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)  +class DoryPastReader(DummyLayer):+    """+    Read-only view of a cache layer, for `last_loop` loops before the last: `update` returns the states `layer.update`+    would, without writing them, so these loops attend over the cached past and their own tokens.+    """++    def __init__(self, layer: DynamicLayer | StaticLayer):+        super().__init__()+        if type(layer) not in (DynamicLayer, DynamicSlidingWindowLayer, StaticLayer, StaticSlidingWindowLayer):+            raise NotImplementedError(f"`last_loop` does not support {type(layer).__name__} cache layers")+        self.layer = layer++    def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs):+        if not self.layer.is_initialized:+            # Allocates the (static) buffers only, so the states keep the shapes the attention mask was built for+            self.layer.lazy_initialization(key_states, value_states)+        return self._read(self.layer.keys, key_states), self._read(self.layer.values, value_states)++    def _read(self, past: torch.Tensor, states: torch.Tensor) -> torch.Tensor:+        layer, num_new = self.layer, states.shape[-2]+        if isinstance(layer, DynamicLayer):+            states = torch.cat([past, states], dim=-2)+            # The cache may hold more than the window if past recording is on+            return states[..., -(layer.sliding_window - 1 + num_new) :, :] if layer.is_sliding else states+        if layer.is_sliding and layer.cumulative_length_int + num_new > layer.max_cache_len:+            # Full or becoming full: the window slides, as in `StaticSlidingWindowLayer.update`+            start = 1 if layer.cumulative_length_int >= layer.max_cache_len else 0+            return torch.cat([past[..., start : layer.cumulative_length_int, :], states], dim=-2)+        # Out-of-place write into the static buffer, keeping its shape+        cache_position = torch.arange(num_new, device=past.device) + layer.cumulative_length+        return past.index_copy(2, cache_position, states)++    def get_seq_length(self) -> int:+        return self.layer.get_seq_length()++ def rotate_half(x):     """Rotates half the hidden dims of the input."""     x1 = x[..., : x.shape[-1] // 2]@@ -236,7 +280,6 @@ def forward(         attention_mask: torch.Tensor | None,         cache: Cache | None = None,         cache_offset: int = 0,-        shared_kv_states: dict[int, tuple[torch.Tensor, torch.Tensor]] | None = None,         **kwargs: Unpack[TransformersKwargs],     ) -> tuple[torch.Tensor, torch.Tensor]:         input_shape = hidden_states.shape[:-1]@@ -256,17 +299,8 @@ def forward(         query_scale = (self.sqk * self.sqk_scale).view(-1, 1, self.head_dim)         query_states = query_states * query_scale.square() -        if shared_kv_states is not None:-            # `last_loop`: earlier loops attend over the last loop's cached past and their own tokens, without writing-            if (past := shared_kv_states.get(self.layer_idx)) is not None:-                key_states = torch.cat([past[0], key_states], dim=-2)-                value_states = torch.cat([past[1], value_states], dim=-2)-                if self.sliding_window is not None:-                    # The cache may hold more than the window if past recording is on-                    num_visible = self.sliding_window - 1 + query_states.shape[-2]-                    key_states, value_states = key_states[..., -num_visible:, :], value_states[..., -num_visible:, :]-        elif cache is not None:-            # `per_loop` loops past the first write to their own copy of this layer's cache, see `DoryModel.forward`+        if cache is not None:+            # Loops write to their own copy of this layer's cache, see `DoryModel.forward`             key_states, value_states = cache.update(key_states, value_states, self.layer_idx + cache_offset)          attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(@@ -482,13 +516,14 @@ def forward(         recurrent_end = recurrent_start + n_recurrent         last_loop_only = self.config.recurrent_kv_cache_mode == "last_loop" -        shared_kv_states = None-        if cache is not None and last_loop_only:-            # Only the last loop writes, the earlier ones read the past-            shared_kv_states = {i: (c.keys, c.values) for i, c in enumerate(cache.layers) if c.is_initialized}-        elif cache is not None and len(cache.layers) == self.config.num_hidden_layers:-            # Loops 1, 2, ... write to copies of the recurrent cache layers, appended at the end-            cache.layers += [copy.deepcopy(c) for c in cache.layers[recurrent_start:recurrent_end] * (n_loops - 1)]+        if cache is not None and len(cache.layers) == self.config.num_hidden_layers:+            # Extra cache layers, appended at the end: `per_loop` loops 1, 2, ... write to copies of the recurrent+            # layers, `last_loop` loops before the last read them without writing+            recurrent_cache = cache.layers[recurrent_start:recurrent_end]+            if last_loop_only:+                cache.layers += [DoryPastReader(c) for c in recurrent_cache]+            else:+                cache.layers += [copy.deepcopy(c) for c in recurrent_cache * (n_loops - 1)]          hidden_states = inputs_embeds         for decoder_layer in self.layers[:recurrent_start]:@@ -500,21 +535,21 @@ def forward(                 **kwargs,             ) -        # Loop i > 0 writes to its copies of the recurrent cache layers, appended after the model's layers+        # Loops reach their extra cache layers through `cache_offset`         offset = len(self.layers) - recurrent_start - n_recurrent         # Each loop restarts from the input section's output         input_hidden_states = self.norm(hidden_states)         for loop_idx in range(n_loops):             hidden_states = self.norm(hidden_states) + input_hidden_states-            cache_offset = 0 if loop_idx == 0 or last_loop_only else offset + loop_idx * n_recurrent+            extra_idx = int(loop_idx < n_loops - 1) if last_loop_only else loop_idx+            cache_offset = offset + extra_idx * n_recurrent if extra_idx else 0             for decoder_layer in self.layers[recurrent_start:recurrent_end]:                 hidden_states = decoder_layer(                     hidden_states,                     attention_mask=causal_mask_mapping[decoder_layer.attention_type],                     position_embeddings=position_embeddings[decoder_layer.attention_type],                     cache=cache,                     cache_offset=cache_offset,-                    shared_kv_states=shared_kv_states if loop_idx < n_loops - 1 else None,                     **kwargs,                 ) 
src/transformers/models/dory/modular_dory.py58 + / 23 −
@@ -20,7 +20,15 @@ from torch import nn  from ... import initialization as init-from ...cache_utils import Cache, DynamicCache+from ...cache_utils import (+    Cache,+    DummyLayer,+    DynamicCache,+    DynamicLayer,+    DynamicSlidingWindowLayer,+    StaticLayer,+    StaticSlidingWindowLayer,+) from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask from ...modeling_outputs import BaseModelOutputWithPast from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS@@ -61,6 +69,42 @@ def compute_default_rope_parameters(         return super().compute_default_rope_parameters(config, layer_type)  +class DoryPastReader(DummyLayer):+    """+    Read-only view of a cache layer, for `last_loop` loops before the last: `update` returns the states `layer.update`+    would, without writing them, so these loops attend over the cached past and their own tokens.+    """++    def __init__(self, layer: DynamicLayer | StaticLayer):+        super().__init__()+        if type(layer) not in (DynamicLayer, DynamicSlidingWindowLayer, StaticLayer, StaticSlidingWindowLayer):+            raise NotImplementedError(f"`last_loop` does not support {type(layer).__name__} cache layers")+        self.layer = layer++    def update(self, key_states: torch.Tensor, value_states: torch.Tensor, *args, **kwargs):+        if not self.layer.is_initialized:+            # Allocates the (static) buffers only, so the states keep the shapes the attention mask was built for+            self.layer.lazy_initialization(key_states, value_states)+        return self._read(self.layer.keys, key_states), self._read(self.layer.values, value_states)++    def _read(self, past: torch.Tensor, states: torch.Tensor) -> torch.Tensor:+        layer, num_new = self.layer, states.shape[-2]+        if isinstance(layer, DynamicLayer):+            states = torch.cat([past, states], dim=-2)+            # The cache may hold more than the window if past recording is on+            return states[..., -(layer.sliding_window - 1 + num_new) :, :] if layer.is_sliding else states+        if layer.is_sliding and layer.cumulative_length_int + num_new > layer.max_cache_len:+            # Full or becoming full: the window slides, as in `StaticSlidingWindowLayer.update`+            start = 1 if layer.cumulative_length_int >= layer.max_cache_len else 0+            return torch.cat([past[..., start : layer.cumulative_length_int, :], states], dim=-2)+        # Out-of-place write into the static buffer, keeping its shape+        cache_position = torch.arange(num_new, device=past.device) + layer.cumulative_length+        return past.index_copy(2, cache_position, states)++    def get_seq_length(self) -> int:+        return self.layer.get_seq_length()++ class DoryAttention(AfmoeAttention):     """     Afmoe attention with nGPT details: unit-norm queries and keys, queries rescaled per channel by `sqk` after rope,@@ -87,7 +131,6 @@ def forward(         attention_mask: torch.Tensor | None,         cache: Cache | None = None,         cache_offset: int = 0,-        shared_kv_states: dict[int, tuple[torch.Tensor, torch.Tensor]] | None = None,         **kwargs: Unpack[TransformersKwargs],     ) -> tuple[torch.Tensor, torch.Tensor]:         input_shape = hidden_states.shape[:-1]@@ -107,17 +150,8 @@ def forward(         query_scale = (self.sqk * self.sqk_scale).view(-1, 1, self.head_dim)         query_states = query_states * query_scale.square() -        if shared_kv_states is not None:-            # `last_loop`: earlier loops attend over the last loop's cached past and their own tokens, without writing-            if (past := shared_kv_states.get(self.layer_idx)) is not None:-                key_states = torch.cat([past[0], key_states], dim=-2)-                value_states = torch.cat([past[1], value_states], dim=-2)-                if self.sliding_window is not None:-                    # The cache may hold more than the window if past recording is on-                    num_visible = self.sliding_window - 1 + query_states.shape[-2]-                    key_states, value_states = key_states[..., -num_visible:, :], value_states[..., -num_visible:, :]-        elif cache is not None:-            # `per_loop` loops past the first write to their own copy of this layer's cache, see `DoryModel.forward`+        if cache is not None:+            # Loops write to their own copy of this layer's cache, see `DoryModel.forward`             key_states, value_states = cache.update(key_states, value_states, self.layer_idx + cache_offset)          attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(@@ -295,13 +329,14 @@ def forward(         recurrent_end = recurrent_start + n_recurrent         last_loop_only = self.config.recurrent_kv_cache_mode == "last_loop" -        shared_kv_states = None-        if cache is not None and last_loop_only:-            # Only the last loop writes, the earlier ones read the past-            shared_kv_states = {i: (c.keys, c.values) for i, c in enumerate(cache.layers) if c.is_initialized}-        elif cache is not None and len(cache.layers) == self.config.num_hidden_layers:-            # Loops 1, 2, ... write to copies of the recurrent cache layers, appended at the end-            cache.layers += [copy.deepcopy(c) for c in cache.layers[recurrent_start:recurrent_end] * (n_loops - 1)]+        if cache is not None and len(cache.layers) == self.config.num_hidden_layers:+            # Extra cache layers, appended at the end: `per_loop` loops 1, 2, ... write to copies of the recurrent+            # layers, `last_loop` loops before the last read them without writing+            recurrent_cache = cache.layers[recurrent_start:recurrent_end]+            if last_loop_only:+                cache.layers += [DoryPastReader(c) for c in recurrent_cache]+            else:+                cache.layers += [copy.deepcopy(c) for c in recurrent_cache * (n_loops - 1)]          hidden_states = inputs_embeds         for decoder_layer in self.layers[:recurrent_start]:@@ -313,21 +348,21 @@ def forward(                 **kwargs,             ) -        # Loop i > 0 writes to its copies of the recurrent cache layers, appended after the model's layers+        # Loops reach their extra cache layers through `cache_offset`         offset = len(self.layers) - recurrent_start - n_recurrent         # Each loop restarts from the input section's output         input_hidden_states = self.norm(hidden_states)         for loop_idx in range(n_loops):             hidden_states = self.norm(hidden_states) + input_hidden_states-            cache_offset = 0 if loop_idx == 0 or last_loop_only else offset + loop_idx * n_recurrent+            extra_idx = int(loop_idx < n_loops - 1) if last_loop_only else loop_idx+            cache_offset = offset + extra_idx * n_recurrent if extra_idx else 0             for decoder_layer in self.layers[recurrent_start:recurrent_end]:                 hidden_states = decoder_layer(                     hidden_states,                     attention_mask=causal_mask_mapping[decoder_layer.attention_type],                     position_embeddings=position_embeddings[decoder_layer.attention_type],                     cache=cache,                     cache_offset=cache_offset,-                    shared_kv_states=shared_kv_states if loop_idx < n_loops - 1 else None,                     **kwargs,                 ) 
tests/models/dory/test_modeling_dory.py24 + / 3 −
@@ -27,7 +27,7 @@ if is_torch_available():     import torch -    from transformers import DoryForCausalLM, DoryModel+    from transformers import DoryForCausalLM, DoryModel, DynamicCache, StaticCache   class DoryModelTester(CausalLMModelTester):@@ -68,6 +68,27 @@ def test_chunked_prefill_and_decode_match_full_forward(self):                 logits.append(outputs.logits)         torch.testing.assert_close(torch.cat(logits, dim=1), full_logits, rtol=1e-4, atol=1e-4) +    def test_static_cache_matches_dynamic_with_loops(self):+        # `last_loop` loops before the last read the cache without writing, which must match across cache types, also+        # past the sliding window+        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()+        config.num_hidden_layers, config.layer_types, config.rope_parameters = 4, None, None+        config.n_input_layers, config.n_recurrent_layers, config.n_output_layers, config.n_recurrent_loops = 1, 2, 1, 3+        config.sliding_window = 4+        input_ids = inputs_dict["input_ids"][:1].repeat(1, 2)[:, :12]+        for mode in ("per_loop", "last_loop"):+            with self.subTest(mode=mode):+                config.recurrent_kv_cache_mode = mode+                config.__post_init__()+                model = DoryForCausalLM(config).to(torch_device).eval()+                dynamic, static = DynamicCache(config=config), StaticCache(config=config, max_cache_len=16)+                with torch.no_grad():+                    for start, end in ((0, 2), (2, 4), (4, 7), (7, 8), (8, 12)):+                        expected = model(input_ids[:, start:end], cache=dynamic).logits+                        actual = model(input_ids[:, start:end], cache=static).logits+                        torch.testing.assert_close(actual, expected, rtol=1e-4, atol=1e-4)+                self.assertTrue(all(layer.get_seq_length() == 12 for layer in static.layers))+     def test_prompt_lookup_past_sliding_window_with_loops(self):         # Assisted decoding rolls the cache back: the later loops' sliding layers must record their past too         config, _ = self.model_tester.prepare_config_and_inputs_for_common()@@ -126,14 +147,14 @@ def test_resize_preserves_learned_logit_scale(self):                 torch.testing.assert_close(restored(input_ids, use_cache=False).logits, expected[..., :retained])      def test_recurrent_cache_layout(self):-        # Plain cache layers: `per_loop` appends one copy of the recurrent layers per extra loop, `last_loop` adds none+        # Plain cache layers: `per_loop` appends one copy of the recurrent layers per extra loop, `last_loop` one read-only view of them         config = self.model_tester_class(             self, num_hidden_layers=4, n_input_layers=1, n_output_layers=1, n_recurrent_loops=3         ).get_config()         input_ids = torch.tensor([[1, 2, 3]])         for mode, expected in [             ("per_loop", ["DynamicSlidingWindowLayer"] * 3 + ["DynamicLayer"] + ["DynamicSlidingWindowLayer"] * 4),-            ("last_loop", ["DynamicSlidingWindowLayer"] * 3 + ["DynamicLayer"]),+            ("last_loop", ["DynamicSlidingWindowLayer"] * 3 + ["DynamicLayer"] + ["DoryPastReader"] * 2),         ]:             config.recurrent_kv_cache_mode = mode             cache = DoryModel(config).eval()(input_ids, use_cache=True).cache