Cccccz's picture
Add files using upload-large-folder tool
34c65dc verified
Raw
History Blame Contribute Delete
15.6 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.
"""
HistoryAwareCache (dev5): MotionDetailCache + AR historical chunk signals.
Idea 1: cross-chunk spatial accumulator with decay
Idea 2: clean latent anchor distance weights
Idea 3: active streak propagation across denoise steps
"""
from typing import Dict, List, Optional, Tuple
import torch
from .motiondetailcache import MotionDetailCache
class HistoryAwareCache(MotionDetailCache):
"""Motion + detail + AR history aware token cache."""
def __init__(
self,
use_history_cache: bool = True,
history_decay: float = 0.7,
history_anchor_horizon: int = 3,
history_streak_len: int = 5,
history_anchor_lambda: float = 0.3,
history_streak_gamma: float = 0.2,
history_anchor_alpha: float = 0.5,
**kwargs,
):
super().__init__(**kwargs)
self.use_history_cache = use_history_cache
self.history_decay = history_decay
self.history_anchor_horizon = history_anchor_horizon
self.history_streak_len = max(1, history_streak_len)
self.history_anchor_lambda = history_anchor_lambda
self.history_streak_gamma = history_streak_gamma
self.history_anchor_alpha = history_anchor_alpha
self.cross_chunk_accumulator: Dict[int, torch.Tensor] = {}
self.clean_latent_history: Dict[int, torch.Tensor] = {}
self._clean_chunk_order: List[int] = []
self.active_streak: Dict[int, torch.Tensor] = {}
self.token_anchor_weights: Dict[int, torch.Tensor] = {}
self.token_history_weights: Dict[int, torch.Tensor] = {}
def reset(self):
super().reset()
self.cross_chunk_accumulator.clear()
self.clean_latent_history.clear()
self._clean_chunk_order.clear()
self.active_streak.clear()
self.token_anchor_weights.clear()
self.token_history_weights.clear()
def _shape_mask(self, x_chunk: torch.Tensor) -> Tuple[int, ...]:
return (x_chunk.size(0), x_chunk.size(2), x_chunk.size(3), x_chunk.size(4))
def _init_cross_chunk_state(
self,
chunk_id: int,
x_chunk: torch.Tensor,
chunk_offset: int,
) -> torch.Tensor:
shape = self._shape_mask(x_chunk)
device, dtype = x_chunk.device, x_chunk.dtype
if chunk_id in self.cross_chunk_accumulator:
return self.cross_chunk_accumulator[chunk_id]
carried = torch.zeros(shape, device=device, dtype=dtype)
if chunk_id > chunk_offset and (chunk_id - 1) in self.cross_chunk_accumulator:
prev = self.cross_chunk_accumulator[chunk_id - 1]
if prev.shape == shape:
carried = self.history_decay * prev
else:
prev_last = prev[:, -1:, :, :]
carried = self.history_decay * prev_last.expand(shape[0], shape[1], shape[2], shape[3])
self.cross_chunk_accumulator[chunk_id] = carried
return carried
def _init_active_streak(self, chunk_id: int, x_chunk: torch.Tensor, chunk_offset: int) -> torch.Tensor:
shape = self._shape_mask(x_chunk)
device, dtype = x_chunk.device, x_chunk.dtype
if chunk_id in self.active_streak:
return self.active_streak[chunk_id]
streak = torch.zeros(shape, device=device, dtype=dtype)
if chunk_id > chunk_offset and (chunk_id - 1) in self.active_streak:
prev = self.active_streak[chunk_id - 1]
if prev.shape == shape:
streak = torch.clamp(prev * self.history_decay, max=float(self.history_streak_len))
else:
prev_last = prev[:, -1:, :, :]
streak = torch.clamp(
prev_last.expand(shape[0], shape[1], shape[2], shape[3]) * self.history_decay,
max=float(self.history_streak_len),
)
self.active_streak[chunk_id] = streak
return streak
def register_clean_chunk(self, chunk_id: int, x_clean: torch.Tensor):
"""Store clean latent for anchor reference (Idea 2)."""
if not self.use_history_cache:
return
# Keep conditional branch only when CFG duplicates batch.
if x_clean.size(0) > 1:
x_clean = x_clean[:1].clone()
else:
x_clean = x_clean.detach().clone()
self.clean_latent_history[chunk_id] = x_clean
if chunk_id in self._clean_chunk_order:
self._clean_chunk_order.remove(chunk_id)
self._clean_chunk_order.append(chunk_id)
while len(self._clean_chunk_order) > self.history_anchor_horizon:
old_id = self._clean_chunk_order.pop(0)
self.clean_latent_history.pop(old_id, None)
def _get_recent_clean_refs(self, chunk_id: int) -> List[torch.Tensor]:
refs = []
for cid in reversed(self._clean_chunk_order):
if cid < chunk_id and cid in self.clean_latent_history:
refs.append(self.clean_latent_history[cid])
if len(refs) >= self.history_anchor_horizon:
break
return refs
def compute_anchor_weights(
self,
x_chunk: torch.Tensor,
chunk_id: int,
chunk_offset: int,
) -> torch.Tensor:
"""Idea 2: rel-L1 distance to recent clean latent history."""
n, t, h, w = self._shape_mask(x_chunk)
device, dtype = x_chunk.device, x_chunk.dtype
refs = self._get_recent_clean_refs(chunk_id)
importance = torch.zeros(n, t, h, w, device=device, dtype=dtype)
cur_mag = x_chunk.float().abs().mean(dim=1)[:n]
if refs:
for ref in refs:
ref_mag = ref.float().abs().mean(dim=1)[:n]
rt = ref_mag.size(1)
for frame_idx in range(t):
ref_frame = ref_mag[:, min(frame_idx, rt - 1)]
diff = (cur_mag[:, frame_idx] - ref_frame).abs()
denom = ref_frame.abs().mean(dim=(1, 2), keepdim=True) + self.eps
rel = diff / denom
importance[:, frame_idx] = torch.maximum(importance[:, frame_idx], rel)
elif chunk_id > chunk_offset and (chunk_id - 1) in self.prev_latent_chunks:
prev = self.prev_latent_chunks[chunk_id - 1].float().abs().mean(dim=1)[:n]
prev_last = prev[:, -1]
diff = (cur_mag[:, 0] - prev_last).abs()
denom = prev_last.abs().mean(dim=(1, 2), keepdim=True) + self.eps
importance[:, 0] = diff / denom
if t > 1:
importance[:, 1] = importance[:, 0]
weights = torch.zeros_like(importance)
for frame_idx in range(t):
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.history_anchor_alpha + (1.0 - self.history_anchor_alpha) * normalized
return weights.to(dtype=dtype)
def compute_streak_boost(self, chunk_id: int) -> Optional[torch.Tensor]:
"""Idea 3: boost weight for tokens with sustained activity."""
streak = self.active_streak.get(chunk_id)
if streak is None:
return None
return self.history_streak_gamma * torch.clamp(
streak / float(self.history_streak_len), max=1.0
)
def fuse_history_weights(
self,
base_weights: torch.Tensor,
anchor_weights: torch.Tensor,
streak_boost: Optional[torch.Tensor],
) -> torch.Tensor:
lam = self.history_anchor_lambda
fused = (1.0 - lam) * base_weights + lam * torch.maximum(base_weights, anchor_weights)
if streak_boost is not None:
fused = fused * (1.0 + streak_boost)
return fused
def update_active_streak(self, chunk_id: int, token_mask: torch.Tensor):
if chunk_id not in self.active_streak:
return
streak = self.active_streak[chunk_id]
active = token_mask.to(dtype=streak.dtype)
streak.copy_(torch.where(active > 0, streak + 1, torch.clamp(streak - 1, min=0)))
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 not self.use_history_cache:
return super().update_token_policy(
chunk_id, x_chunk, current_features, chunk_offset, chunk_denoise_count
)
if (
chunk_denoise_count is not None
and chunk_denoise_count.get(chunk_id, 0) == self.phase1_steps
):
mask = torch.ones(self._shape_mask(x_chunk), device=x_chunk.device, dtype=torch.bool)
self.token_active_mask[chunk_id] = mask
self.token_accumulator[chunk_id] = torch.zeros(
self._shape_mask(x_chunk), device=x_chunk.device, dtype=x_chunk.dtype
)
self._init_cross_chunk_state(chunk_id, x_chunk, chunk_offset)
self._init_active_streak(chunk_id, x_chunk, chunk_offset)
return mask
prev_features = self.prev_metric_chunks.get(chunk_id)
if prev_features is None:
mask = torch.ones(self._shape_mask(x_chunk), 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)
base_weights = self.combine_motion_detail_weights(motion_weights, detail_weights)
anchor_weights = self.compute_anchor_weights(x_chunk, chunk_id, chunk_offset)
self._init_active_streak(chunk_id, x_chunk, chunk_offset)
streak_boost = self.compute_streak_boost(chunk_id)
final_weights = self.fuse_history_weights(base_weights, anchor_weights, streak_boost)
self.token_motion_weights[chunk_id] = motion_weights
self.token_detail_weights[chunk_id] = detail_weights
self.token_combined_weights[chunk_id] = base_weights
self.token_anchor_weights[chunk_id] = anchor_weights
self.token_history_weights[chunk_id] = final_weights
if chunk_id not in self.token_accumulator:
self.token_accumulator[chunk_id] = torch.zeros_like(final_weights)
cross_acc = self._init_cross_chunk_state(chunk_id, x_chunk, chunk_offset)
step_mass = final_weights * delta_chunk
self.token_accumulator[chunk_id] = self.token_accumulator[chunk_id] + step_mass
self.cross_chunk_accumulator[chunk_id] = cross_acc + step_mass
local_active = self.token_accumulator[chunk_id] > self.rel_l1_thresh
cross_active = self.cross_chunk_accumulator[chunk_id] > self.rel_l1_thresh
mask = local_active | cross_active
self.token_active_mask[chunk_id] = mask
return mask
def reset_token_accumulator(self, chunk_id: int, mask: torch.Tensor):
super().reset_token_accumulator(chunk_id, mask)
if not self.use_history_cache:
return
if chunk_id in self.cross_chunk_accumulator:
self.cross_chunk_accumulator[chunk_id] = torch.where(
mask,
torch.zeros_like(self.cross_chunk_accumulator[chunk_id]),
self.cross_chunk_accumulator[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
anchor_ratio = None
anchor_w = self.token_anchor_weights.get(chunk_id)
if anchor_w is not None:
anchor_ratio = float((anchor_w > self.history_anchor_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_anchor_token_ratio": anchor_ratio,
"use_history_cache": self.use_history_cache,
"history_decay": self.history_decay,
"history_anchor_lambda": self.history_anchor_lambda,
"history_streak_gamma": self.history_streak_gamma,
"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": "HistoryAwareCache: motion + detail + AR history (cross-chunk acc, anchor, streak).",
"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,
"use_history_cache": self.use_history_cache,
"history_decay": self.history_decay,
"history_anchor_horizon": self.history_anchor_horizon,
"history_streak_len": self.history_streak_len,
"history_anchor_lambda": self.history_anchor_lambda,
"history_streak_gamma": self.history_streak_gamma,
"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 HistoryAwareCache metric stats to {self.metric_stats_path}")