File size: 11,874 Bytes
d2b26ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# Copyright (c) 2025 SandAI. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
MotionCache: motion-aware token-wise cache reuse for autoregressive video generation.

Implements the coarse-to-fine schedule from Xu et al. (2026):
- Phase 1 (first K steps after warmup): chunk-wise binary reuse (FlowCache-style)
- Phase 2: motion-weighted per-token accumulation and selective reuse
"""

import json
import os
from typing import Dict, Optional, Tuple

import torch
from einops import rearrange

from .cachereuse import ChunkWiseCache


class MotionWiseCache(ChunkWiseCache):
    """
    Motion-aware cache extending chunk-wise FlowCache with token-level reuse.

    Hyperparameters (paper Appendix C for MAGI-1):
        alpha: soft-mapping floor for static tokens (default 0.5)
        phase1_steps (K): chunk-wise phase duration before token-wise mode (default 9)
        rel_l1_thresh (tau): accumulator threshold for token activation
        warmup_steps (m): global steps with reuse disabled (default 5)
    """

    def __init__(
        self,
        rel_l1_thresh: float = 0.015,
        warmup_steps: int = 5,
        phase1_steps: int = 9,
        alpha: float = 0.5,
        discard_nearly_clean_chunk: bool = False,
        log: bool = False,
        metric_stats_path: Optional[str] = None,
        eps: float = 1e-8,
    ):
        super().__init__(
            rel_l1_thresh=rel_l1_thresh,
            warmup_steps=warmup_steps,
            discard_nearly_clean_chunk=discard_nearly_clean_chunk,
            log=log,
            metric_stats_path=metric_stats_path,
        )
        self.phase1_steps = phase1_steps
        self.alpha = alpha
        self.eps = eps

        self.token_accumulator: Dict[int, torch.Tensor] = {}
        self.token_active_mask: Dict[int, torch.Tensor] = {}
        self.token_motion_weights: Dict[int, torch.Tensor] = {}
        self.prev_latent_chunks: Dict[int, torch.Tensor] = {}
        self.prev_chunk_last_frame: Dict[int, torch.Tensor] = {}
        self.previous_velocity: Dict[int, torch.Tensor] = {}
        self.chunk_sparse_flags: Dict[int, bool] = {}

    def reset(self):
        super().reset()
        self.token_accumulator.clear()
        self.token_active_mask.clear()
        self.token_motion_weights.clear()
        self.prev_latent_chunks.clear()
        self.prev_chunk_last_frame.clear()
        self.previous_velocity.clear()
        self.chunk_sparse_flags.clear()

    @staticmethod
    def expand_token_mask_to_output(
        token_mask: torch.Tensor,
        output: torch.Tensor,
    ) -> torch.Tensor:
        """Expand [N, T, H, W] latent mask to match velocity/output [N, C, T, H, W]."""
        return token_mask.unsqueeze(1).expand_as(output).to(dtype=output.dtype)

    def in_phase1(self, chunk_id: int, chunk_denoise_count: Dict[int, int]) -> bool:
        """Return True while chunk i is still in coarse chunk-wise phase (denoise step < K)."""
        return chunk_denoise_count.get(chunk_id, 0) < self.phase1_steps

    def compute_motion_weights(
        self,
        x_chunk: torch.Tensor,
        chunk_id: int,
        chunk_offset: int,
    ) -> torch.Tensor:
        """
        Compute motion-aware importance weights W in [alpha, 1] per latent frame.

        Args:
            x_chunk: Latent tensor [N, C, T, H, W] at current denoising step
            chunk_id: Global chunk index
            chunk_offset: Index of first generated chunk

        Returns:
            Weights tensor [N, T, H, W]
        """
        _, _, num_frames, _, _ = x_chunk.shape
        device = x_chunk.device
        dtype = x_chunk.dtype
        importance = torch.zeros(
            x_chunk.size(0), num_frames, x_chunk.size(3), x_chunk.size(4),
            device=device, dtype=dtype,
        )

        for frame_idx in range(num_frames):
            if frame_idx > 0:
                diff = (x_chunk[:, :, frame_idx] - x_chunk[:, :, frame_idx - 1]).abs().sum(dim=1)
            elif chunk_id > chunk_offset:
                prev_frame = self.prev_chunk_last_frame.get(chunk_id - 1)
                if prev_frame is not None:
                    diff = (x_chunk[:, :, 0] - prev_frame).abs().sum(dim=1)
                else:
                    diff = torch.zeros(
                        x_chunk.size(0), x_chunk.size(3), x_chunk.size(4),
                        device=device, dtype=dtype,
                    )
            else:
                continue
            importance[:, frame_idx] = diff

        if chunk_id == chunk_offset and num_frames > 1:
            importance[:, 0] = importance[:, 1]

        weights = torch.zeros_like(importance)
        for frame_idx in range(num_frames):
            frame_importance = importance[:, frame_idx]
            min_val = frame_importance.amin(dim=(1, 2), keepdim=True)
            max_val = frame_importance.amax(dim=(1, 2), keepdim=True)
            normalized = (frame_importance - min_val) / (max_val - min_val + self.eps)
            weights[:, frame_idx] = self.alpha + (1.0 - self.alpha) * normalized

        return weights

    def compute_chunk_delta_l1(
        self,
        current_features: torch.Tensor,
        prev_features: torch.Tensor,
    ) -> float:
        """Relative L1 distance between consecutive embedded features (Eq. 11)."""
        diff = (current_features - prev_features).abs().mean()
        denom = prev_features.abs().mean() + self.eps
        return (diff / denom).item()

    def update_token_policy(
        self,
        chunk_id: int,
        x_chunk: torch.Tensor,
        current_features: torch.Tensor,
        chunk_offset: int,
        chunk_denoise_count: Optional[Dict[int, int]] = None,
    ) -> torch.Tensor:
        """
        Phase-2 token policy: update accumulators and return active mask.

        Returns:
            Boolean mask [N, T, H, W], True = compute, False = reuse cache
        """
        if (
            chunk_denoise_count is not None
            and chunk_denoise_count.get(chunk_id, 0) == self.phase1_steps
        ):
            mask = torch.ones(
                x_chunk.size(0), x_chunk.size(2), x_chunk.size(3), x_chunk.size(4),
                device=x_chunk.device, dtype=torch.bool,
            )
            self.token_active_mask[chunk_id] = mask
            self.token_accumulator[chunk_id] = torch.zeros(
                x_chunk.size(0), x_chunk.size(2), x_chunk.size(3), x_chunk.size(4),
                device=x_chunk.device,
                dtype=x_chunk.dtype,
            )
            return mask

        prev_features = self.prev_metric_chunks.get(chunk_id)
        if prev_features is None:
            mask = torch.ones(
                x_chunk.size(0), x_chunk.size(2), x_chunk.size(3), x_chunk.size(4),
                device=x_chunk.device, dtype=torch.bool,
            )
            self.token_active_mask[chunk_id] = mask
            return mask

        delta_chunk = self.compute_chunk_delta_l1(current_features, prev_features)
        weights = self.compute_motion_weights(x_chunk, chunk_id, chunk_offset)
        self.token_motion_weights[chunk_id] = weights

        if chunk_id not in self.token_accumulator:
            self.token_accumulator[chunk_id] = torch.zeros_like(weights)

        self.token_accumulator[chunk_id] = (
            self.token_accumulator[chunk_id] + weights * delta_chunk
        )
        mask = self.token_accumulator[chunk_id] > self.rel_l1_thresh
        self.token_active_mask[chunk_id] = mask
        return mask

    def reset_token_accumulator(self, chunk_id: int, mask: torch.Tensor):
        """Reset accumulator for tokens selected for computation."""
        if chunk_id in self.token_accumulator:
            self.token_accumulator[chunk_id] = torch.where(
                mask, torch.zeros_like(self.token_accumulator[chunk_id]),
                self.token_accumulator[chunk_id],
            )

    def should_skip_chunk_forward(
        self,
        chunk_id: int,
        chunk_denoise_count: Dict[int, int],
    ) -> bool:
        """Return True if the entire chunk can skip the DiT forward pass."""
        if self.in_phase1(chunk_id, chunk_denoise_count):
            return self.chunk_reuse_flags.get(chunk_id, False)

        mask = self.token_active_mask.get(chunk_id)
        if mask is None:
            return False
        return not mask.any()

    def store_latent_chunk(self, chunk_id: int, x_chunk: torch.Tensor):
        """Store latent for cross-chunk motion reference."""
        self.prev_latent_chunks[chunk_id] = x_chunk.detach().clone()
        self.prev_chunk_last_frame[chunk_id] = x_chunk[:, :, -1].detach().clone()

    def get_token_mask(
        self,
        chunk_id: int,
        chunk_denoise_count: Dict[int, int],
    ) -> Optional[torch.Tensor]:
        if self.in_phase1(chunk_id, chunk_denoise_count):
            return None
        return self.token_active_mask.get(chunk_id)

    def record_motion_decision(
        self,
        chunk_id: int,
        reused: bool,
        active_ratio: Optional[float] = None,
        **kwargs,
    ):
        if not self.metric_stats_path:
            return
        record = {
            "infer_idx": kwargs.get("infer_idx"),
            "cur_denoise_step": kwargs.get("cur_denoise_step"),
            "denoise_stage": kwargs.get("denoise_stage"),
            "denoise_idx": kwargs.get("denoise_idx"),
            "chunk_idx": chunk_id,
            "generated_chunk_idx": chunk_id - kwargs.get("chunk_offset", 0),
            "chunk_denoise_count": kwargs.get("chunk_denoise_count_value"),
            "phase": (
                "phase1_chunk"
                if self.in_phase1(chunk_id, kwargs.get("chunk_denoise_count", {}))
                else "phase2_token"
            ),
            "reused": bool(reused),
            "execution": "reuse" if reused else "compute",
            "active_token_ratio": active_ratio,
            "phase1_steps": self.phase1_steps,
            "alpha": self.alpha,
            "rel_l1_thresh": self.rel_l1_thresh,
        }
        self.execution_records.append(record)

    def save_metric_stats(self):
        if not self.metric_stats_path:
            return
        save_dir = os.path.dirname(self.metric_stats_path)
        if save_dir:
            os.makedirs(save_dir, exist_ok=True)

        payload = {
            "description": (
                "MotionCache metric stats. Phase 1 uses chunk-wise FlowCache policy for "
                f"the first {self.phase1_steps} denoise steps per chunk; Phase 2 uses motion-weighted "
                "token accumulation with alpha floor and rel_l1_thresh."
            ),
            "hyperparameters": {
                "alpha": self.alpha,
                "phase1_steps": self.phase1_steps,
                "warmup_steps": self.warmup_steps,
                "rel_l1_thresh": self.rel_l1_thresh,
            },
            "chunk_execution_summary": self.get_execution_summary(),
            "execution_records": self.execution_records,
            "records": self.metric_records,
        }
        if self.metric_stats_path.endswith((".pt", ".pth")):
            torch.save(payload, self.metric_stats_path)
        else:
            with open(self.metric_stats_path, "w") as f:
                json.dump(payload, f, indent=2)
        print(f"Saved MotionCache metric stats to {self.metric_stats_path}")