Spaces:
Paused
Paused
Delete LTX-Video/ltx_video/pipelines/spy_late.py
Browse files
LTX-Video/ltx_video/pipelines/spy_late.py
DELETED
|
@@ -1,115 +0,0 @@
|
|
| 1 |
-
# spy_latent.py
|
| 2 |
-
|
| 3 |
-
import torch
|
| 4 |
-
import os
|
| 5 |
-
import traceback
|
| 6 |
-
from einops import rearrange
|
| 7 |
-
from torchvision.utils import save_image
|
| 8 |
-
|
| 9 |
-
# Tenta importar o VAE do pipeline. Se não conseguir, a visualização será desativada.
|
| 10 |
-
try:
|
| 11 |
-
from ltx_video.models.autoencoders.causal_video_autoencoder import CausalVideoAutoencoder
|
| 12 |
-
except ImportError:
|
| 13 |
-
CausalVideoAutoencoder = None
|
| 14 |
-
|
| 15 |
-
class SpyLatent:
|
| 16 |
-
"""
|
| 17 |
-
Uma classe para inspecionar tensores latentes em vários estágios de um pipeline.
|
| 18 |
-
Imprime estatísticas e pode salvar visualizações decodificadas por um VAE.
|
| 19 |
-
"""
|
| 20 |
-
def __init__(self, vae=None, output_dir: str = "/app/output"):
|
| 21 |
-
"""
|
| 22 |
-
Inicializa o espião.
|
| 23 |
-
|
| 24 |
-
Args:
|
| 25 |
-
vae: A instância do modelo VAE para decodificar os latentes. Se for None,
|
| 26 |
-
a visualização será desativada.
|
| 27 |
-
output_dir (str): O diretório padrão para salvar as imagens de visualização.
|
| 28 |
-
"""
|
| 29 |
-
self.vae = vae
|
| 30 |
-
self.output_dir = output_dir
|
| 31 |
-
self.device = vae.device if hasattr(vae, 'device') else torch.device("cpu")
|
| 32 |
-
|
| 33 |
-
if self.vae is None:
|
| 34 |
-
print("[SpyLatent] AVISO: VAE não fornecido. A funcionalidade de visualização de imagem está desativada.")
|
| 35 |
-
|
| 36 |
-
def inspect(
|
| 37 |
-
self,
|
| 38 |
-
tensor: torch.Tensor,
|
| 39 |
-
tag: str,
|
| 40 |
-
reference_shape_5d: tuple = None,
|
| 41 |
-
save_visual: bool = True,
|
| 42 |
-
):
|
| 43 |
-
"""
|
| 44 |
-
Inspeciona um tensor latente.
|
| 45 |
-
|
| 46 |
-
Args:
|
| 47 |
-
tensor (torch.Tensor): O tensor a ser inspecionado.
|
| 48 |
-
tag (str): Um rótulo para identificar o ponto de inspeção nos logs.
|
| 49 |
-
reference_shape_5d (tuple, optional): A forma 5D de referência (B, C, F, H, W)
|
| 50 |
-
necessária se o tensor de entrada for 3D.
|
| 51 |
-
save_visual (bool): Se True, decodifica com o VAE e salva uma imagem.
|
| 52 |
-
"""
|
| 53 |
-
print(f"\n--- [INSPEÇÃO DE LATENTE: {tag}] ---")
|
| 54 |
-
if not isinstance(tensor, torch.Tensor):
|
| 55 |
-
print(f" AVISO: O objeto fornecido para '{tag}' não é um tensor.")
|
| 56 |
-
print("--- [FIM DA INSPEÇÃO] ---\n")
|
| 57 |
-
return
|
| 58 |
-
|
| 59 |
-
try:
|
| 60 |
-
# --- Imprime Estatísticas do Tensor Original ---
|
| 61 |
-
self._print_stats("Tensor Original", tensor)
|
| 62 |
-
|
| 63 |
-
# --- Converte para 5D se necessário ---
|
| 64 |
-
tensor_5d = self._to_5d(tensor, reference_shape_5d)
|
| 65 |
-
if tensor_5d is not None and tensor.ndim == 3:
|
| 66 |
-
self._print_stats("Convertido para 5D", tensor_5d)
|
| 67 |
-
|
| 68 |
-
# --- Visualização com VAE ---
|
| 69 |
-
if save_visual and self.vae is not None and tensor_5d is not None:
|
| 70 |
-
os.makedirs(self.output_dir, exist_ok=True)
|
| 71 |
-
print(f" VISUALIZAÇÃO (VAE): Salvando imagem em {self.output_dir}...")
|
| 72 |
-
|
| 73 |
-
frame_idx_to_viz = min(1, tensor_5d.shape[2] - 1)
|
| 74 |
-
if frame_idx_to_viz < 0:
|
| 75 |
-
print(" VISUALIZAÇÃO (VAE): Tensor não tem frames para visualizar.")
|
| 76 |
-
else:
|
| 77 |
-
print(f" VISUALIZAÇÃO (VAE): Usando frame de índice {frame_idx_to_viz}.")
|
| 78 |
-
latent_slice = tensor_5d[:, :, frame_idx_to_viz:frame_idx_to_viz+1, :, :]
|
| 79 |
-
|
| 80 |
-
with torch.no_grad(), torch.autocast(device_type=self.device.type):
|
| 81 |
-
pixel_slice = self.vae.decode(latent_slice / self.vae.config.scaling_factor).sample
|
| 82 |
-
|
| 83 |
-
save_image((pixel_slice / 2 + 0.5).clamp(0, 1), os.path.join(self.output_dir, f"inspect_{tag.lower()}.png"))
|
| 84 |
-
print(" VISUALIZAÇÃO (VAE): Imagem salva.")
|
| 85 |
-
|
| 86 |
-
except Exception as e:
|
| 87 |
-
print(f" ERRO na inspeção: {e}")
|
| 88 |
-
traceback.print_exc()
|
| 89 |
-
finally:
|
| 90 |
-
print("--- [FIM DA INSPEÇÃO] ---\n")
|
| 91 |
-
|
| 92 |
-
def _to_5d(self, tensor: torch.Tensor, shape_5d: tuple) -> torch.Tensor:
|
| 93 |
-
"""Converte um tensor 3D patchificado de volta para 5D."""
|
| 94 |
-
if tensor.ndim == 5:
|
| 95 |
-
return tensor
|
| 96 |
-
if tensor.ndim == 3 and shape_5d:
|
| 97 |
-
try:
|
| 98 |
-
b, c, f, h, w = shape_5d
|
| 99 |
-
return rearrange(tensor, "b (f h w) c -> b c f h w", c=c, f=f, h=h, w=w)
|
| 100 |
-
except Exception as e:
|
| 101 |
-
print(f" AVISO: Erro ao rearranjar tensor 3D para 5D: {e}. A visualização pode falhar.")
|
| 102 |
-
return None
|
| 103 |
-
return None
|
| 104 |
-
|
| 105 |
-
def _print_stats(self, prefix: str, tensor: torch.Tensor):
|
| 106 |
-
"""Helper para imprimir estatísticas de um tensor."""
|
| 107 |
-
mean = tensor.mean().item()
|
| 108 |
-
std = tensor.std().item()
|
| 109 |
-
min_val = tensor.min().item()
|
| 110 |
-
max_val = tensor.max().item()
|
| 111 |
-
print(f" {prefix}: Shape={list(tensor.shape)}, Mean={mean:.4f}, Std={std:.4f}, Min={min_val:.4f}, Max={max_val:.4f}")
|
| 112 |
-
|
| 113 |
-
# Exemplo de como instanciar globalmente (se desejado)
|
| 114 |
-
# spy = SpyLatent()
|
| 115 |
-
# A melhor prática é instanciar dentro da sua classe principal, passando o VAE.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|