File size: 6,222 Bytes
ebad435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import unittest
from unittest.mock import patch

import torch
import torch.nn.functional as F
from torch import nn

from predictor_training.atc_fusion import ATCFusion, MultiInputMLP, StateTransport
from predictor_training.single_block import SingleBlockPredictor
from wan.modules.model import rope_params


def small_freqs(head_dim: int = 8) -> torch.Tensor:
    return torch.cat(
        [
            rope_params(32, head_dim - 4 * (head_dim // 6)),
            rope_params(32, 2 * (head_dim // 6)),
            rope_params(32, 2 * (head_dim // 6)),
        ],
        dim=1,
    )


def reference_attention(
    q: torch.Tensor, k: torch.Tensor, v: torch.Tensor
) -> torch.Tensor:
    scores = torch.einsum("blhd,bshd->bhls", q, k) / q.shape[-1] ** 0.5
    probability = scores.float().softmax(dim=-1).to(v.dtype)
    return torch.einsum("bhls,bshd->blhd", probability, v)


class DummyBlock(nn.Module):
    num_heads = 1

    def forward(self, value: torch.Tensor, **_kwargs) -> torch.Tensor:
        return value


class ATCFusionTest(unittest.TestCase):
    def setUp(self) -> None:
        torch.manual_seed(0)
        self.grid = torch.tensor([[2, 2, 2]], dtype=torch.long)
        self.freqs = small_freqs()
        self.current = torch.randn(1, 8, 8)
        self.previous = torch.randn(1, 8, 8)

    def test_multi_input_mlp_matches_explicit_concat(self) -> None:
        module = MultiInputMLP(3, dim=8, hidden_dim=12)
        values = [torch.randn(2, 5, 8) for _ in range(3)]
        combined_weight = torch.cat(
            [layer.weight for layer in module.inputs], dim=1
        )
        combined_bias = sum(layer.bias for layer in module.inputs)
        reference_hidden = F.linear(
            torch.cat(values, dim=-1), combined_weight, combined_bias
        )
        reference = module.out(module.activation(reference_hidden))
        torch.testing.assert_close(module(*values), reference)

    @patch(
        "predictor_training.atc_fusion.attention",
        side_effect=reference_attention,
    )
    def test_last_frame_scope_cannot_read_earlier_frames(self, _mock) -> None:
        transport = StateTransport(
            dim=8,
            num_heads=1,
            previous_scope="last_frame",
            gradient_checkpointing=False,
            diagnostic_queries=4,
        ).eval()
        first, _ = transport(
            self.current, self.previous, self.grid, self.freqs, current_start=8
        )
        perturbed_early = self.previous.clone()
        perturbed_early[:, :4] += torch.randn_like(perturbed_early[:, :4])
        second, _ = transport(
            self.current,
            perturbed_early,
            self.grid,
            self.freqs,
            current_start=8,
        )
        torch.testing.assert_close(first, second, rtol=0, atol=0)

        perturbed_last = self.previous.clone()
        perturbed_last[:, 4:] += torch.randn_like(perturbed_last[:, 4:])
        third, _ = transport(
            self.current,
            perturbed_last,
            self.grid,
            self.freqs,
            current_start=8,
        )
        self.assertFalse(torch.equal(first, third))

    @patch(
        "predictor_training.atc_fusion.attention",
        side_effect=reference_attention,
    )
    def test_zero_initialized_correction_bypass(self, _mock) -> None:
        fusion = ATCFusion(
            dim=8,
            num_heads=1,
            freq_dim=8,
            mlp_hidden_dim=16,
            gate_hidden_dim=4,
            previous_scope="chunk",
            gradient_checkpointing=False,
        ).eval()
        condition = torch.randn_like(self.current)
        backbone, gated_correction = fusion(
            self.current,
            torch.randn_like(self.current),
            self.previous,
            condition,
            torch.tensor([62.5]),
            self.grid,
            self.freqs,
            current_start=8,
        )
        self.assertEqual(backbone.shape, self.current.shape)
        torch.testing.assert_close(
            gated_correction,
            torch.zeros_like(gated_correction),
            rtol=0,
            atol=0,
        )
        self.assertAlmostEqual(float(fusion.last_gate.mean()), 0.3, delta=0.01)

    def test_atc_token_gate_is_a_stage1_parameter(self) -> None:
        predictor = SingleBlockPredictor(
            DummyBlock(),
            dim=8,
            gradient_checkpointing=False,
            input_variant="atc",
            atc_freq_dim=8,
            atc_mlp_hidden_dim=16,
            atc_gate_hidden_dim=4,
        )
        token_gate_ids = {
            id(parameter)
            for parameter in predictor.fusion.token_gate.parameters()
        }
        stage1_ids = {
            id(parameter) for parameter in predictor.stage1_input_parameters()
        }
        self.assertTrue(token_gate_ids)
        self.assertTrue(token_gate_ids.issubset(stage1_ids))
        self.assertEqual(predictor.gate_parameters(), [])

    @patch(
        "predictor_training.atc_fusion.attention",
        side_effect=reference_attention,
    )
    def test_zero_initialized_predictor_returns_anchor(self, _mock) -> None:
        predictor = SingleBlockPredictor(
            DummyBlock(),
            dim=8,
            gradient_checkpointing=False,
            input_variant="atc",
            atc_freq_dim=8,
            atc_mlp_hidden_dim=16,
            atc_gate_hidden_dim=4,
        ).eval()
        anchor = torch.randn_like(self.current)
        empty_history = torch.empty(1, 0, 1, 8)
        prediction = predictor(
            current_tokens=self.current,
            anchor_hidden=anchor,
            previous_hidden=self.previous,
            timestep_modulation=torch.randn(1, 2, 6, 8),
            grid_sizes=self.grid,
            freqs=self.freqs,
            history_k=empty_history,
            history_v=empty_history,
            cross_k=torch.empty(1, 0, 1, 8),
            cross_v=torch.empty(1, 0, 1, 8),
            current_start=8,
            condition_tokens=torch.randn_like(self.current),
            anchor_distance=torch.tensor([62.5]),
        )
        torch.testing.assert_close(prediction, anchor, rtol=0, atol=0)


if __name__ == "__main__":
    unittest.main()