SignX / eval /analyze_video2pose.py
FangSen9000
Initial SignX import (LFS)
cbc5e69
Raw History Blame Contribute Delete
7.91 kB
#!/usr/bin/env python3
"""Analyze pose ViT features from video2text checkpoint outputs."""
import argparse
import json
import os
from pathlib import Path
import cv2
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import torch
from PIL import Image
from torchvision import transforms
from smkd.pretrained.video2text import (
MultimodalPose2TextDiffusion,
MultimodalVideo2TextDiffusion,
)
INPUT_DIMS = {
"dwpose": 384,
"mediapipe_pose": 258,
"primedepth_depth": 576,
"sapiens_segmentation": 576,
"smplerx": 165,
}
def parse_args():
parser = argparse.ArgumentParser(description="Pose-dimensional ablation via video2text checkpoint.")
parser.add_argument("--video", required=True, help="Path to input video (mp4).")
parser.add_argument(
"--checkpoint",
default="smkd/pretrained/video2text_checkpoint_epoch_14.pth",
help="Path to video2text checkpoint.",
)
parser.add_argument(
"--output-dir",
default="pose_vit_feature_analysis",
help="Directory to store extracted features/plots.",
)
parser.add_argument("--num-frames", type=int, default=32, help="Number of frames sampled from video.")
parser.add_argument("--device", default="cuda", choices=["cuda", "cpu"], help="Torch device preference.")
parser.add_argument("--topk", type=int, default=32, help="Top dimensions to visualize.")
return parser.parse_args()
def prepare_device(device_pref: str) -> torch.device:
if device_pref == "cuda" and torch.cuda.is_available():
return torch.device("cuda")
return torch.device("cpu")
def ensure_dir(path: str) -> Path:
path_obj = Path(path)
path_obj.mkdir(parents=True, exist_ok=True)
return path_obj
def load_video_frames(video_path: str, num_frames: int, transform) -> torch.Tensor:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
raise RuntimeError(f"Failed to open video: {video_path}")
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
if total_frames <= 0:
raise RuntimeError(f"No frames found in video: {video_path}")
indices = np.linspace(0, max(total_frames - 1, 0), num=num_frames, dtype=np.int32)
frames = []
for idx in indices:
cap.set(cv2.CAP_PROP_POS_FRAMES, int(idx))
ok, frame = cap.read()
if not ok:
continue
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(transform(Image.fromarray(frame)))
cap.release()
if not frames:
raise RuntimeError(f"No decodable frames in video: {video_path}")
while len(frames) < num_frames:
frames.append(frames[-1].clone())
return torch.stack(frames[:num_frames], dim=0)
def compute_dimension_stats(pose_2048: torch.Tensor):
with torch.no_grad():
scores = pose_2048.abs().mean(dim=(0, 1))
normalized = scores / (scores.max() + 1e-8)
return scores.cpu().numpy(), normalized.cpu().numpy()
def plot_top_dims(scores, top_indices, output_path):
plt.figure(figsize=(max(8, len(top_indices) * 0.35), 4))
plt.bar(range(len(top_indices)), scores[top_indices], color="#1f77b4")
plt.xticks(range(len(top_indices)), [str(i) for i in top_indices], rotation=60)
plt.ylabel("Mean |value|")
plt.xlabel("Dimension")
plt.title("Top pose dimensions")
plt.tight_layout()
plt.savefig(output_path, dpi=240)
plt.close()
def plot_heatmap(norm_scores, output_path):
rows = 32
usable = (norm_scores.shape[0] // rows) * rows
reshaped = norm_scores[:usable].reshape(rows, -1)
plt.figure(figsize=(12, 4))
plt.imshow(reshaped, aspect="auto", cmap="magma")
plt.colorbar(label="Normalized importance")
plt.xlabel("Chunk index")
plt.ylabel("Row")
plt.title("Pose dimension importance heatmap")
plt.tight_layout()
plt.savefig(output_path, dpi=240)
plt.close()
def plot_cumulative(scores, output_path):
sorted_scores = np.sort(scores)[::-1]
cumsum = np.cumsum(sorted_scores)
coverage = cumsum / cumsum[-1]
dims = np.arange(1, len(sorted_scores) + 1)
plt.figure(figsize=(8, 4))
plt.plot(dims, coverage, color="#ff7f0e")
plt.xlabel("Top-k dimensions")
plt.ylabel("Cumulative coverage")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(output_path, dpi=240)
plt.close()
return coverage
def save_csv(scores, norm_scores, output_path):
with open(output_path, "w", encoding="utf-8") as handle:
handle.write("dimension,score,normalized\n")
for idx, (score, norm) in enumerate(zip(scores, norm_scores)):
handle.write(f"{idx},{score:.8f},{norm:.6f}\n")
def write_report(video_path, checkpoint, scores, norm_scores, coverage, top_indices, output_path):
levels = [0.25, 0.5, 0.9]
with open(output_path, "w", encoding="utf-8") as handle:
handle.write("Pose ViT dimensional analysis\n")
handle.write("=" * 60 + "\n\n")
handle.write(f"Video : {video_path}\n")
handle.write(f"Checkpoint : {checkpoint}\n")
handle.write(f"Total dims : {scores.shape[0]}\n\n")
handle.write("Top dimensions:\n")
for rank, dim_idx in enumerate(top_indices, 1):
handle.write(
f"{rank:02d}. dim {dim_idx:04d} | score={scores[dim_idx]:.6f} "
f"| normalized={norm_scores[dim_idx]:.4f}\n"
)
handle.write("\nCoverage milestones:\n")
for level in levels:
required = int(np.argmax(coverage >= level) + 1)
handle.write(f" - Top {required:4d} dims explain {level:.0%} of energy\n")
handle.write("\nScores computed as mean absolute activations on pose_2048.\n")
def main():
args = parse_args()
video_path = os.path.abspath(args.video)
checkpoint_path = os.path.abspath(args.checkpoint)
output_dir = ensure_dir(args.output_dir)
if not os.path.exists(video_path):
raise FileNotFoundError(f"Video not found: {video_path}")
if not os.path.exists(checkpoint_path):
raise FileNotFoundError(f"Checkpoint not found: {checkpoint_path}")
device = prepare_device(args.device)
print(f"[INFO] Using device: {device}")
pose2text = MultimodalPose2TextDiffusion(
input_dims=INPUT_DIMS,
hidden_dim=2048,
device=device,
codebook=None,
)
video2text = MultimodalVideo2TextDiffusion(
pose2text_model=pose2text,
device=device,
)
checkpoint = torch.load(checkpoint_path, map_location=device)
load_result = video2text.load_state_dict(checkpoint["model_state_dict"], strict=False)
if load_result.missing_keys:
print(f"[WARN] Missing keys ({len(load_result.missing_keys)}): {load_result.missing_keys[:5]}...")
if load_result.unexpected_keys:
print(f"[WARN] Unexpected keys ({len(load_result.unexpected_keys)}): {load_result.unexpected_keys[:5]}...")
video2text.eval()
frame_transform = transforms.Compose(
[
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
]
)
frames = load_video_frames(video_path, args.num_frames, frame_transform)
video_tensor = frames.unsqueeze(0).to(device)
with torch.no_grad():
pose_features = video2text.video2pose(video_tensor)
concatenated = pose2text.pose_encoder(pose_features)
B, F, D = concatenated.shape
flattened = concatenated.reshape(B * F, D)
pose_2048 = pose2text.dim_match(flattened).view(B, F, -1)
pose_numpy = pose_2048.cpu().numpy()
np.save(output_dir / "pose_2048.npy", pose_numpy)
scores, norm_scores = compute_dimension_stats(pose_2048)
save_csv(scores, norm_scores, output_dir / "dimension_scores.csv")
topk = min(args.topk, scores.shape)