Cccccz's picture
Add files using upload-large-folder tool
d2b26ce verified
Raw
History Blame Contribute Delete
11.1 kB
# 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.
"""
MotionDetailCache: MotionCache + spatial detail-aware token activation.
Extends motion-weighted accumulation with local latent variance to preserve
edges, textures, and semantic fine structure even when temporal motion is low.
"""
from typing import Dict, Optional
import torch
import torch.nn.functional as F
from .motioncache import MotionWiseCache
class MotionDetailCache(MotionWiseCache):
"""
Motion + detail dual-metric token cache.
Detail proxy: local spatial variance of channel-aggregated latent magnitude
within a k×k window. High variance indicates heterogeneous neighborhoods
(edges, textures, object boundaries).
Combined weight modes (``weight_combine_mode``):
- ``max``: max(motion_w, detail_w) — either signal can drive activation
- ``product``: motion_w * detail_w — both must be informative
- ``blend``: (1-λ)*motion_w + λ*detail_w — linear trade-off
"""
def __init__(
self,
rel_l1_thresh: float = 0.015,
warmup_steps: int = 5,
phase1_steps: int = 9,
alpha: float = 0.5,
detail_alpha: float = 0.5,
detail_window_size: int = 3,
detail_lambda: float = 0.5,
weight_combine_mode: str = "max",
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,
phase1_steps=phase1_steps,
alpha=alpha,
discard_nearly_clean_chunk=discard_nearly_clean_chunk,
log=log,
metric_stats_path=metric_stats_path,
eps=eps,
)
self.detail_alpha = detail_alpha
self.detail_window_size = detail_window_size
self.detail_lambda = detail_lambda
self.weight_combine_mode = weight_combine_mode
self.token_detail_weights: Dict[int, torch.Tensor] = {}
self.token_combined_weights: Dict[int, torch.Tensor] = {}
def reset(self):
super().reset()
self.token_detail_weights.clear()
self.token_combined_weights.clear()
def compute_detail_weights(self, x_chunk: torch.Tensor) -> torch.Tensor:
"""
Local spatial variance importance per latent pixel.
Args:
x_chunk: [N, C, T, H, W]
Returns:
Weights [N, T, H, W] in [detail_alpha, 1]
"""
n, _, num_frames, h, w = x_chunk.shape
window = self.detail_window_size
if window % 2 == 0:
window += 1
pad = window // 2
mag = x_chunk.float().abs().mean(dim=1)
mag_2d = mag.reshape(n * num_frames, 1, h, w)
kernel = torch.ones(1, 1, window, window, device=mag.device, dtype=torch.float32)
kernel = kernel / kernel.sum()
padded = F.pad(mag_2d, (pad, pad, pad, pad), mode="reflect")
local_mean = F.conv2d(padded, kernel)
local_mean_sq = F.conv2d(padded ** 2, kernel)
local_var = (local_mean_sq - local_mean ** 2).clamp_min(0.0)
importance = local_var.reshape(n, num_frames, h, w)
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.detail_alpha + (1.0 - self.detail_alpha) * normalized
return weights.to(dtype=x_chunk.dtype)
def combine_motion_detail_weights(
self,
motion_weights: torch.Tensor,
detail_weights: torch.Tensor,
) -> torch.Tensor:
mode = self.weight_combine_mode
if mode == "max":
return torch.maximum(motion_weights, detail_weights)
if mode == "product":
return motion_weights * detail_weights
if mode == "blend":
lam = self.detail_lambda
return (1.0 - lam) * motion_weights + lam * detail_weights
raise ValueError(f"Unknown weight_combine_mode: {mode}")
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:
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)
motion_weights = self.compute_motion_weights(x_chunk, chunk_id, chunk_offset)
detail_weights = self.compute_detail_weights(x_chunk)
combined_weights = self.combine_motion_detail_weights(motion_weights, detail_weights)
self.token_motion_weights[chunk_id] = motion_weights
self.token_detail_weights[chunk_id] = detail_weights
self.token_combined_weights[chunk_id] = combined_weights
if chunk_id not in self.token_accumulator:
self.token_accumulator[chunk_id] = torch.zeros_like(combined_weights)
self.token_accumulator[chunk_id] = (
self.token_accumulator[chunk_id] + combined_weights * delta_chunk
)
self.prepare_chunk_tau(
chunk_id=chunk_id,
x_chunk=x_chunk,
current_features=current_features,
chunk_offset=chunk_offset,
motion_weights=motion_weights,
detail_weights=detail_weights,
delta_chunk=delta_chunk,
chunk_denoise_count=chunk_denoise_count,
)
tau_eff = self.get_effective_tau(chunk_id)
mask = self.token_accumulator[chunk_id] > tau_eff
self.token_active_mask[chunk_id] = mask
return mask
def get_effective_tau(self, chunk_id: int) -> float:
"""Return active-token threshold for chunk (override for adaptive tau)."""
return self.rel_l1_thresh
def prepare_chunk_tau(
self,
chunk_id,
x_chunk,
current_features,
chunk_offset,
motion_weights,
detail_weights,
delta_chunk,
chunk_denoise_count,
):
"""Hook before mask decision; adaptive caches set per-chunk tau here."""
return
def record_motion_decision(
self,
chunk_id: int,
reused: bool,
active_ratio: Optional[float] = None,
**kwargs,
):
if not self.metric_stats_path:
return
detail_ratio = None
detail_w = self.token_detail_weights.get(chunk_id)
if detail_w is not None:
detail_ratio = float((detail_w > self.detail_alpha + 1e-6).float().mean().item())
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,
"high_detail_token_ratio": detail_ratio,
"phase1_steps": self.phase1_steps,
"alpha": self.alpha,
"detail_alpha": self.detail_alpha,
"detail_window_size": self.detail_window_size,
"weight_combine_mode": self.weight_combine_mode,
"detail_lambda": self.detail_lambda,
"rel_l1_thresh": self.rel_l1_thresh,
}
self.execution_records.append(record)
def save_metric_stats(self):
if not self.metric_stats_path:
return
import json
import os
save_dir = os.path.dirname(self.metric_stats_path)
if save_dir:
os.makedirs(save_dir, exist_ok=True)
payload = {
"description": (
"MotionDetailCache stats. Phase 1 chunk-wise FlowCache; Phase 2 uses "
"motion + local spatial variance detail weights for token accumulation."
),
"hyperparameters": {
"alpha": self.alpha,
"detail_alpha": self.detail_alpha,
"detail_window_size": self.detail_window_size,
"detail_lambda": self.detail_lambda,
"weight_combine_mode": self.weight_combine_mode,
"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 MotionDetailCache metric stats to {self.metric_stats_path}")