|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +"""Compare cached and freshly built DeepSeek V4 SWA/HCA attention masks.""" |
| 8 | + |
| 9 | +import unittest |
| 10 | +from unittest import mock |
| 11 | + |
| 12 | +import torch |
| 13 | + |
| 14 | +from torchtitan.models.deepseek_v4 import model_registry |
| 15 | +from torchtitan.models.deepseek_v4.attention import ( |
| 16 | + dsv4_mask_key, |
| 17 | + DSV4FlexInnerAttention, |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +@unittest.skipUnless(torch.cuda.is_available(), "CUDA is unavailable") |
| 22 | +class TestDeepSeekV4AttentionCache(unittest.TestCase): |
| 23 | + def _make_model(self): |
| 24 | + # Only mask construction and parameter-free inner attention are used. |
| 25 | + with torch.device("meta"): |
| 26 | + model = model_registry("debugmodel", seq_len=512).model.build() |
| 27 | + return model |
| 28 | + |
| 29 | + def _assert_outputs_and_grads_match(self, inner, cached_mask, seqlen): |
| 30 | + device = torch.device("cuda") |
| 31 | + num_heads, head_dim = 2, 64 |
| 32 | + inputs = [ |
| 33 | + torch.randn(seqlen, num_heads, head_dim, device=device, requires_grad=True), |
| 34 | + torch.randn(seqlen, head_dim, device=device, requires_grad=True), |
| 35 | + ] |
| 36 | + if inner.compress_ratio > 1: |
| 37 | + inputs.append( |
| 38 | + torch.randn( |
| 39 | + seqlen // inner.compress_ratio, |
| 40 | + head_dim, |
| 41 | + device=device, |
| 42 | + requires_grad=True, |
| 43 | + ) |
| 44 | + ) |
| 45 | + inputs.append(torch.randn(num_heads, device=device, requires_grad=True)) |
| 46 | + reference_inputs = [x.detach().clone().requires_grad_(True) for x in inputs] |
| 47 | + |
| 48 | + fresh_mask = DSV4FlexInnerAttention.build_block_mask( |
| 49 | + inner, seqlen=seqlen, device=device |
| 50 | + ) |
| 51 | + self.assertIsNot(cached_mask, fresh_mask) |
| 52 | + cached_output = inner(*inputs, attention_masks=cached_mask) |
| 53 | + reference_output = inner(*reference_inputs, attention_masks=fresh_mask) |
| 54 | + grad_output = torch.randn_like(cached_output) |
| 55 | + cached_grads = torch.autograd.grad(cached_output, inputs, grad_output) |
| 56 | + reference_grads = torch.autograd.grad( |
| 57 | + reference_output, reference_inputs, grad_output |
| 58 | + ) |
| 59 | + |
| 60 | + torch.testing.assert_close( |
| 61 | + cached_output, reference_output, atol=1e-5, rtol=1e-5 |
| 62 | + ) |
| 63 | + names = ["q", "swa_k"] |
| 64 | + if inner.compress_ratio > 1: |
| 65 | + names.append("cmp_k") |
| 66 | + names.append("attn_sink") |
| 67 | + for name, actual, expected in zip( |
| 68 | + names, cached_grads, reference_grads, strict=True |
| 69 | + ): |
| 70 | + torch.testing.assert_close( |
| 71 | + actual, expected, atol=1e-5, rtol=1e-5, msg=f"grad[{name}] mismatch" |
| 72 | + ) |
| 73 | + |
| 74 | + def test_cached_masks_reused_across_sequence_lengths(self): |
| 75 | + model = self._make_model() |
| 76 | + masks_by_length = {} |
| 77 | + build_mask = DSV4FlexInnerAttention.build_block_mask |
| 78 | + |
| 79 | + for seqlen, expected_builds in [(256, 2), (256, 0), (512, 2), (256, 0)]: |
| 80 | + with self.subTest(seqlen=seqlen, expected_builds=expected_builds): |
| 81 | + positions = torch.arange(seqlen, device="cuda") |
| 82 | + with mock.patch.object( |
| 83 | + DSV4FlexInnerAttention, |
| 84 | + "build_block_mask", |
| 85 | + autospec=True, |
| 86 | + side_effect=build_mask, |
| 87 | + ) as builder: |
| 88 | + masks = model.get_attention_masks(positions) |
| 89 | + self.assertEqual(builder.call_count, expected_builds) |
| 90 | + self.assertEqual(set(masks), {"swa", "hca_128"}) |
| 91 | + |
| 92 | + if seqlen in masks_by_length: |
| 93 | + for key, mask in masks.items(): |
| 94 | + self.assertIs(mask, masks_by_length[seqlen][key]) |
| 95 | + else: |
| 96 | + for other_masks in masks_by_length.values(): |
| 97 | + for key, mask in masks.items(): |
| 98 | + self.assertIsNot(mask, other_masks[key]) |
| 99 | + masks_by_length[seqlen] = masks |
| 100 | + self.assertEqual(len(model.mask_cache), 2 * len(masks_by_length)) |
| 101 | + |
| 102 | + def test_cached_masks_match_fresh_outputs_and_grads(self): |
| 103 | + torch.manual_seed(0) |
| 104 | + model = self._make_model() |
| 105 | + seqlen = 128 |
| 106 | + masks = model.get_attention_masks(torch.arange(seqlen, device="cuda")) |
| 107 | + checked = set() |
| 108 | + for layer in model.layers.values(): |
| 109 | + inner = layer.attention.inner_attention |
| 110 | + key = dsv4_mask_key(inner.compress_ratio) |
| 111 | + if key is not None and key not in checked: |
| 112 | + with self.subTest(mask=key): |
| 113 | + self._assert_outputs_and_grads_match(inner, masks[key], seqlen) |
| 114 | + checked.add(key) |
| 115 | + self.assertEqual(checked, {"swa", "hca_128"}) |
| 116 | + |
| 117 | + def test_rejects_incompatible_layers_before_deduplication(self): |
| 118 | + for field, value in [("window_size", 32), ("block_size", 64)]: |
| 119 | + for populate_cache in (False, True): |
| 120 | + with self.subTest(field=field, populate_cache=populate_cache): |
| 121 | + model = self._make_model() |
| 122 | + positions = torch.arange(256, device="cuda") |
| 123 | + if populate_cache: |
| 124 | + model.get_attention_masks(positions) |
| 125 | + inner = model.layers["1"].attention.inner_attention |
| 126 | + self.assertNotEqual(getattr(inner, field), value) |
| 127 | + setattr(inner, field, value) |
| 128 | + with self.assertRaises(AssertionError): |
| 129 | + model.get_attention_masks(positions) |
| 130 | + |
| 131 | + |
| 132 | +if __name__ == "__main__": |
| 133 | + unittest.main() |
0 commit comments