# 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. """ AdaptiveDetailCache: MotionDetailCache + chunk-level AR difficulty → dynamic tau. Uses historical chunk statistics (motion, detail, reuse, active ratio) and the current chunk proxy to estimate difficulty d in [0, 1], then: tau_eff = clamp(tau_base * exp(-beta * (d - 0.5)), tau_min, tau_max) Higher difficulty → lower tau → more token computation. """ import math from typing import Dict, Optional import torch from .motiondetailcache import MotionDetailCache class AdaptiveDetailCache(MotionDetailCache): """Per-chunk dynamic threshold on top of motion + detail metrics.""" def __init__( self, use_adaptive_tau: bool = True, adaptive_tau_beta: float = 0.8, adaptive_tau_min: float = 0.008, adaptive_tau_max: float = 0.020, difficulty_w_motion: float = 0.30, difficulty_w_detail: float = 0.20, difficulty_w_delta: float = 0.20, difficulty_w_active: float = 0.15, difficulty_w_reuse: float = 0.15, **kwargs, ): super().__init__(**kwargs) self.use_adaptive_tau = use_adaptive_tau self.adaptive_tau_beta = adaptive_tau_beta self.adaptive_tau_min = adaptive_tau_min self.adaptive_tau_max = adaptive_tau_max self.difficulty_w_motion = difficulty_w_motion self.difficulty_w_detail = difficulty_w_detail self.difficulty_w_delta = difficulty_w_delta self.difficulty_w_active = difficulty_w_active self.difficulty_w_reuse = difficulty_w_reuse self.chunk_tau_eff: Dict[int, float] = {} self.chunk_difficulty: Dict[int, float] = {} self.chunk_step_stats: Dict[int, Dict[str, float]] = {} self._chunk_reuse_steps: Dict[int, int] = {} self._chunk_total_steps: Dict[int, int] = {} self._chunk_last_delta: Dict[int, float] = {} def reset(self): super().reset() self.chunk_tau_eff.clear() self.chunk_difficulty.clear() self.chunk_step_stats.clear() self._chunk_reuse_steps.clear() self._chunk_total_steps.clear() self._chunk_last_delta.clear() def get_effective_tau(self, chunk_id: int) -> float: if not self.use_adaptive_tau: return self.rel_l1_thresh return self.chunk_tau_eff.get(chunk_id, self.rel_l1_thresh) @staticmethod def _norm_weight(mean_val: float, floor: float) -> float: return float(max(0.0, min(1.0, (mean_val - floor) / (1.0 - floor + 1e-8)))) def _history_stats(self, chunk_id: int, chunk_offset: int) -> Dict[str, float]: prev_ids = [cid for cid in sorted(self.chunk_step_stats) if chunk_offset <= cid < chunk_id] if not prev_ids: return {"motion": 0.5, "detail": 0.5, "delta": 0.5, "active": 0.5, "reuse": 0.5} motion = sum(self.chunk_step_stats[c]["motion"] for c in prev_ids) / len(prev_ids) detail = sum(self.chunk_step_stats[c]["detail"] for c in prev_ids) / len(prev_ids) delta = sum(self.chunk_step_stats[c]["delta"] for c in prev_ids) / len(prev_ids) active = sum(self.chunk_step_stats[c]["active"] for c in prev_ids) / len(prev_ids) reuse_vals = [] for c in prev_ids: total = max(1, self._chunk_total_steps.get(c, 1)) reuse_vals.append(self._chunk_reuse_steps.get(c, 0) / total) reuse = 1.0 - (sum(reuse_vals) / len(reuse_vals)) return {"motion": motion, "detail": detail, "delta": delta, "active": active, "reuse": reuse} def predict_chunk_difficulty( self, chunk_id: int, chunk_offset: int, motion_weights: torch.Tensor, detail_weights: torch.Tensor, delta_chunk: float, ) -> float: cur_motion = self._norm_weight(float(motion_weights.mean().item()), self.alpha) cur_detail = self._norm_weight(float(detail_weights.mean().item()), self.detail_alpha) cur_delta = float(max(0.0, min(1.0, delta_chunk / 0.05))) hist = self._history_stats(chunk_id, chunk_offset) gen_idx = max(0, chunk_id - chunk_offset) hist_blend = min(0.7, 0.15 * gen_idx) motion = (1 - hist_blend) * cur_motion + hist_blend * hist["motion"] detail = (1 - hist_blend) * cur_detail + hist_blend * hist["detail"] delta = (1 - hist_blend) * cur_delta + hist_blend * hist["delta"] active = hist["active"] reuse = hist["reuse"] w_sum = ( self.difficulty_w_motion + self.difficulty_w_detail + self.difficulty_w_delta + self.difficulty_w_active + self.difficulty_w_reuse ) difficulty = ( self.difficulty_w_motion * motion + self.difficulty_w_detail * detail + self.difficulty_w_delta * delta + self.difficulty_w_active * active + self.difficulty_w_reuse * reuse ) / max(w_sum, 1e-8) return float(max(0.0, min(1.0, difficulty))) def tau_from_difficulty(self, difficulty: float) -> float: tau = self.rel_l1_thresh * math.exp(-self.adaptive_tau_beta * (difficulty - 0.5)) return float(max(self.adaptive_tau_min, min(self.adaptive_tau_max, tau))) def prepare_chunk_tau( self, chunk_id, x_chunk, current_features, chunk_offset, motion_weights, detail_weights, delta_chunk, chunk_denoise_count, ): if not self.use_adaptive_tau: return if chunk_denoise_count is not None and self.in_phase1(chunk_id, chunk_denoise_count): return if chunk_id in self.chunk_tau_eff: return difficulty = self.predict_chunk_difficulty( chunk_id, chunk_offset, motion_weights, detail_weights, delta_chunk ) self.chunk_difficulty[chunk_id] = difficulty self.chunk_tau_eff[chunk_id] = self.tau_from_difficulty(difficulty) self._chunk_last_delta[chunk_id] = float(delta_chunk) if self.log: print( f"AdaptiveDetailCache chunk {chunk_id}: difficulty={difficulty:.3f}, " f"tau_eff={self.chunk_tau_eff[chunk_id]:.4f} (base={self.rel_l1_thresh:.4f})" ) def record_motion_decision(self, chunk_id: int, reused: bool, active_ratio: Optional[float] = None, **kwargs): chunk_denoise_count = kwargs.get("chunk_denoise_count", {}) if not self.in_phase1(chunk_id, chunk_denoise_count): self._chunk_total_steps[chunk_id] = self._chunk_total_steps.get(chunk_id, 0) + 1 if reused: self._chunk_reuse_steps[chunk_id] = self._chunk_reuse_steps.get(chunk_id, 0) + 1 motion_w = self.token_motion_weights.get(chunk_id) detail_w = self.token_detail_weights.get(chunk_id) if motion_w is not None and detail_w is not None: m = self._norm_weight(float(motion_w.mean().item()), self.alpha) d = self._norm_weight(float(detail_w.mean().item()), self.detail_alpha) a = float(active_ratio if active_ratio is not None else 0.0) delta = float(max(0.0, min(1.0, self._chunk_last_delta.get(chunk_id, 0.0) / 0.05))) if chunk_id not in self.chunk_step_stats: self.chunk_step_stats[chunk_id] = { "motion": m, "detail": d, "delta": delta, "active": a, } else: st = self.chunk_step_stats[chunk_id] n = self._chunk_total_steps[chunk_id] st["motion"] = st["motion"] + (m - st["motion"]) / n st["detail"] = st["detail"] + (d - st["detail"]) / n st["delta"] = st["delta"] + (delta - st["delta"]) / n st["active"] = st["active"] + (a - st["active"]) / n super().record_motion_decision(chunk_id, reused, active_ratio, **kwargs) if self.metric_stats_path and self.execution_records: self.execution_records[-1]["chunk_difficulty"] = self.chunk_difficulty.get(chunk_id) self.execution_records[-1]["tau_effective"] = self.get_effective_tau(chunk_id) 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": ( "AdaptiveDetailCache: motion + detail with chunk-level AR difficulty " "and dynamic tau." ), "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_adaptive_tau": self.use_adaptive_tau, "adaptive_tau_beta": self.adaptive_tau_beta, "adaptive_tau_min": self.adaptive_tau_min, "adaptive_tau_max": self.adaptive_tau_max, "rel_l1_thresh": self.rel_l1_thresh, "phase1_steps": self.phase1_steps, "warmup_steps": self.warmup_steps, }, "chunk_tau_effective": {str(k): v for k, v in self.chunk_tau_eff.items()}, "chunk_difficulty": {str(k): v for k, v in self.chunk_difficulty.items()}, "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 AdaptiveDetailCache metric stats to {self.metric_stats_path}")