| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| """ |
| 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}") |
|
|