| import os |
| from typing import Any |
|
|
| import torch |
| import torch.nn.functional as F |
|
|
|
|
| def compute_token_change_rate(token_t: torch.Tensor, token_t_minus_1: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: |
| """Per-token relative change using L2 norms: (||token_t|| - ||token_{t-1}||) / ||token_t||.""" |
| norm_t = torch.linalg.vector_norm(token_t.float(), dim=-1) |
| norm_t_minus_1 = torch.linalg.vector_norm(token_t_minus_1.float(), dim=-1) |
| return (norm_t - norm_t_minus_1) / norm_t.clamp(min=eps) |
|
|
|
|
| def cosine_match_tokens(history_tokens: torch.Tensor, noise_tokens: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: |
| """For each noise token, find the history token with highest cosine similarity.""" |
| history = F.normalize(history_tokens.float(), dim=-1) |
| noise = F.normalize(noise_tokens.float(), dim=-1) |
| similarity = noise @ history.T |
| match_indices = similarity.argmax(dim=-1) |
| match_scores = similarity.gather(1, match_indices.unsqueeze(1)).squeeze(1) |
| return match_indices, match_scores |
|
|
|
|
| def extract_frame_tokens( |
| token_sequence: torch.Tensor, |
| history_context_length: int, |
| original_context_length: int, |
| grid_tokens: int, |
| history_frame_index: int, |
| noise_frame_index: int, |
| ) -> tuple[torch.Tensor, torch.Tensor]: |
| """Extract one spatial frame from short-history and current-noise token sequences.""" |
| short_history_frames = 2 |
| short_len = short_history_frames * grid_tokens |
| history_seq_len = history_context_length |
|
|
| short_start = history_seq_len - short_len |
| history_start = short_start + history_frame_index * grid_tokens |
| noise_start = history_seq_len + noise_frame_index * grid_tokens |
|
|
| history_tokens = token_sequence[history_start : history_start + grid_tokens] |
| noise_tokens = token_sequence[noise_start : noise_start + grid_tokens] |
| return history_tokens, noise_tokens |
|
|
|
|
| def extract_noise_frame_tokens( |
| token_sequence: torch.Tensor, |
| history_context_length: int, |
| grid_tokens: int, |
| noise_frame_index: int, |
| ) -> torch.Tensor: |
| noise_start = history_context_length + noise_frame_index * grid_tokens |
| return token_sequence[noise_start : noise_start + grid_tokens] |
|
|
|
|
| def resolve_short_history_frame_index(history_frame: int, short_history_frames: int = 2) -> int: |
| if history_frame < 0: |
| history_frame += short_history_frames |
| return history_frame |
|
|
|
|
| def resolve_history_source_frame( |
| chunk_index: int, |
| history_frame: int, |
| *, |
| keep_first_frame: bool, |
| num_latent_frames_per_chunk: int, |
| short_history_frames: int = 2, |
| ) -> tuple[int, int]: |
| """Map configured short-history frame to the chunk/latent-frame where it was denoised.""" |
| short_index = resolve_short_history_frame_index(history_frame, short_history_frames) |
| if keep_first_frame: |
| if short_index == 0: |
| return 0, 0 |
| return max(0, chunk_index - 1), num_latent_frames_per_chunk - 1 |
| return max(0, chunk_index - 1), num_latent_frames_per_chunk - 1 |
|
|
|
|
| def token_yx_from_index(index: int, grid_w: int) -> tuple[int, int]: |
| return int(index) // grid_w, int(index) % grid_w |
|
|
|
|
| def token_rect_on_image( |
| token_y: int, |
| token_x: int, |
| image_height: int, |
| image_width: int, |
| grid_h: int, |
| grid_w: int, |
| patch_h: int = 2, |
| patch_w: int = 2, |
| ) -> tuple[float, float, float, float]: |
| """Map token grid cell to pixel rectangle on decoded frame.""" |
| latent_h = grid_h * patch_h |
| latent_w = grid_w * patch_w |
| ly0 = token_y * patch_h |
| lx0 = token_x * patch_w |
| ly1 = ly0 + patch_h |
| lx1 = lx0 + patch_w |
| py0 = ly0 / latent_h * image_height |
| px0 = lx0 / latent_w * image_width |
| py1 = ly1 / latent_h * image_height |
| px1 = lx1 / latent_w * image_width |
| return px0, py0, px1 - px0, py1 - py0 |
|
|
|
|
| class TokenDynamicsDebugTracker: |
| def __init__(self, config: dict[str, Any] | None): |
| self.config = config |
| self.state: dict[str, Any] = {} |
| self._frame_rates: dict[tuple[int, int], dict[str, list]] = {} |
| self.reset_chunk_records() |
|
|
| @property |
| def enabled(self) -> bool: |
| return self.config is not None and self.config.get("enabled", True) |
|
|
| def reset_chunk_records(self): |
| self.match_indices = None |
| self.match_scores = None |
| self.step_indices: list[int] = [] |
| self.timesteps: list[float] = [] |
| self._prev_noise_frame_tokens: dict[int, torch.Tensor] = {} |
| self._matching_done = False |
| self.noise_latent_frame = None |
| self.history_latent_frame = None |
| self.capture_pass_name = None |
|
|
| def set_state(self, **state): |
| prev_chunk = self.state.get("chunk_index") |
| next_chunk = state.get("chunk_index", prev_chunk) |
| if prev_chunk is not None and next_chunk is not None and prev_chunk != next_chunk: |
| self.reset_chunk_records() |
| self.state.update(state) |
|
|
| def should_record(self) -> bool: |
| if not self.enabled: |
| return False |
| pass_names = self.config.get("pass_names", ["cond"]) |
| if self.state.get("pass_name", "cond") not in pass_names: |
| return False |
| return True |
|
|
| def should_capture(self) -> bool: |
| if not self.should_record(): |
| return False |
| return self.is_analysis_chunk() |
|
|
| def is_analysis_chunk(self) -> bool: |
| chunks = self.config.get("chunks") |
| if chunks is not None and self.state.get("chunk_index", 0) not in chunks: |
| return False |
| return True |
|
|
| def get_recording_targets(self) -> set[tuple[int, int]]: |
| """(chunk, latent_frame) pairs to record: history source frame + noise frame only.""" |
| targets: set[tuple[int, int]] = set() |
| analysis_chunks = self.config.get("chunks") |
| if not analysis_chunks: |
| return targets |
|
|
| noise_frame = int(self.config.get("noise_frame", 0)) |
| for chunk_index in analysis_chunks: |
| targets.add((int(chunk_index), noise_frame)) |
| hist_chunk, hist_frame = resolve_history_source_frame( |
| int(chunk_index), |
| int(self.config.get("history_frame", -1)), |
| keep_first_frame=bool(self.config.get("keep_first_frame", True)), |
| num_latent_frames_per_chunk=int(self.config.get("num_latent_frames_per_chunk", 9)), |
| ) |
| targets.add((hist_chunk, hist_frame)) |
| return targets |
|
|
| def _record_frame_rates(self, chunk_index: int, frame_index: int, rate: torch.Tensor): |
| key = (chunk_index, frame_index) |
| bucket = self._frame_rates.setdefault(key, {"rates": [], "step_indices": [], "timesteps": []}) |
| bucket["rates"].append(rate.detach().cpu()) |
| bucket["step_indices"].append(int(self.state.get("step_index", 0))) |
| bucket["timesteps"].append(float(self.state.get("timestep", self.state.get("step_index", 0)))) |
|
|
| def observe( |
| self, |
| latent_tokens: torch.Tensor, |
| history_context_length: int, |
| original_context_length: int, |
| ): |
| if not self.should_record(): |
| return |
|
|
| if self.capture_pass_name is None: |
| self.capture_pass_name = self.state.get("pass_name", "cond") |
|
|
| grid_h, grid_w = self.config.get("grid", (24, 40)) |
| grid_tokens = int(grid_h) * int(grid_w) |
| history_frame = int(self.config.get("history_frame", -1)) |
| noise_frame = int(self.config.get("noise_frame", 0)) |
| short_history_frame = resolve_short_history_frame_index(history_frame) |
|
|
| chunk_index = int(self.state.get("chunk_index", 0)) |
| recording_targets = self.get_recording_targets() |
| frames_to_record = sorted(frame_index for c, frame_index in recording_targets if c == chunk_index) |
|
|
| for frame_index in frames_to_record: |
| frame_tokens = extract_noise_frame_tokens( |
| latent_tokens[0], |
| history_context_length, |
| grid_tokens, |
| frame_index, |
| ) |
| prev_tokens = self._prev_noise_frame_tokens.get(frame_index) |
| if prev_tokens is not None: |
| self._record_frame_rates( |
| chunk_index, |
| frame_index, |
| compute_token_change_rate(frame_tokens, prev_tokens), |
| ) |
| self._prev_noise_frame_tokens[frame_index] = frame_tokens.detach() |
|
|
| step_index = int(self.state.get("step_index", 0)) |
| total_steps = int(self.state.get("total_steps", 1)) |
| is_last_step = step_index == total_steps - 1 |
|
|
| if self.should_capture() and is_last_step and not self._matching_done: |
| latent_history, latent_noise = extract_frame_tokens( |
| latent_tokens[0], |
| history_context_length, |
| original_context_length, |
| grid_tokens, |
| short_history_frame, |
| noise_frame, |
| ) |
| self.match_indices, self.match_scores = cosine_match_tokens(latent_history, latent_noise) |
| self._matching_done = True |
|
|
| def _get_frame_rate_series(self, chunk_index: int, frame_index: int) -> dict[str, Any]: |
| key = (chunk_index, frame_index) |
| if key not in self._frame_rates or not self._frame_rates[key]["rates"]: |
| raise KeyError(f"No patch-latent change rates recorded for chunk={chunk_index}, frame={frame_index}") |
| bucket = self._frame_rates[key] |
| return { |
| "rates": torch.stack(bucket["rates"], dim=0), |
| "step_indices": bucket["step_indices"].copy(), |
| "timesteps": bucket["timesteps"].copy(), |
| } |
|
|
| def set_visualization_latent_frames( |
| self, |
| denoised_latents: torch.Tensor, |
| history_short_latents: torch.Tensor, |
| ): |
| """Store fully denoised latent frames for VAE visualization (after chunk sampling).""" |
| if not self.enabled or not self._matching_done or not self.is_analysis_chunk(): |
| return |
|
|
| history_frame = int(self.config.get("history_frame", -1)) |
| noise_frame = int(self.config.get("noise_frame", 0)) |
| short_frames = history_short_latents.shape[2] |
| short_index = resolve_short_history_frame_index(history_frame, short_frames) |
|
|
| self.history_latent_frame = history_short_latents[0, :, short_index].detach().float().cpu() |
| self.noise_latent_frame = denoised_latents[0, :, noise_frame].detach().float().cpu() |
|
|
| def save(self): |
| if not self.enabled or self.match_indices is None: |
| return None |
|
|
| chunk_index = int(self.state.get("chunk_index", 0)) |
| noise_frame = int(self.config.get("noise_frame", 0)) |
| history_source_chunk, history_source_frame = resolve_history_source_frame( |
| chunk_index, |
| int(self.config.get("history_frame", -1)), |
| keep_first_frame=bool(self.config.get("keep_first_frame", True)), |
| num_latent_frames_per_chunk=int(self.config.get("num_latent_frames_per_chunk", 9)), |
| ) |
|
|
| history_series = self._get_frame_rate_series(history_source_chunk, history_source_frame) |
| noise_series = self._get_frame_rate_series(chunk_index, noise_frame) |
| self.step_indices = noise_series["step_indices"] |
| self.timesteps = noise_series["timesteps"] |
|
|
| output_dir = self.config.get("output_dir", "token_dynamics_debug") |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| filename = ( |
| f"token_dynamics_chunk{chunk_index}_" |
| f"hist{self.config.get('history_frame', -1)}_" |
| f"noise{self.config.get('noise_frame', 0)}_" |
| f"{self.capture_pass_name or self.state.get('pass_name', 'cond')}.pt" |
| ) |
| path = os.path.join(output_dir, filename) |
|
|
| artifact = { |
| "chunk_index": chunk_index, |
| "history_frame": int(self.config.get("history_frame", -1)), |
| "noise_frame": noise_frame, |
| "history_source_chunk": history_source_chunk, |
| "history_source_frame": history_source_frame, |
| "grid": tuple(self.config.get("grid", (24, 40))), |
| "match_indices": self.match_indices.cpu(), |
| "match_scores": self.match_scores.cpu(), |
| "history_change_rates": history_series["rates"], |
| "noise_change_rates": noise_series["rates"], |
| "step_indices": self.step_indices.copy(), |
| "timesteps": self.timesteps.copy(), |
| "total_steps": int(self.state.get("total_steps", 0)), |
| "noise_latent_frame": self.noise_latent_frame, |
| "history_latent_frame": self.history_latent_frame, |
| } |
| torch.save(artifact, path) |
| return path |
|
|