Repository navigation
Expand file tree
/
Copy pathinference.py
More file actions
170 lines (137 loc) · 7.26 KB
/
Copy pathinference.py
File metadata and controls
170 lines (137 loc) · 7.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import os
import argparse
import torch
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import cv2
from utils import VideoDataset
from vqvae import VQVAE
def save_video_frames(frames, output_path, fps=30):
"""Save frames as an MP4 video file."""
os.makedirs(os.path.dirname(output_path), exist_ok=True)
# Convert to numpy and scale to [0, 255]
frames = frames.detach().cpu().numpy() # (C, T, H, W)
frames = np.transpose(frames, (1, 2, 3, 0)) # (T, H, W, C)
frames = ((frames + 1.0) / 2.0 * 255).astype(np.uint8)
# Define video codec and create VideoWriter
h, w = frames.shape[1:3]
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video_writer = cv2.VideoWriter(output_path, fourcc, fps, (w, h))
# Write frames to video file
for frame in frames:
frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
video_writer.write(frame_bgr)
video_writer.release()
print(f"Video saved to {output_path}")
def reconstruct_videos(model, data_loader, device, output_dir, num_samples=5):
"""Reconstruct videos from the test set and save them."""
os.makedirs(output_dir, exist_ok=True)
model.eval()
with torch.no_grad():
for i, data in enumerate(tqdm(data_loader, desc="Reconstructing videos")):
if i >= num_samples:
break
data = data.to(device)
reconstructed, _, _, _, _, _ = model(data)
# Save original and reconstructed videos for each sample in the batch
for j in range(data.shape[0]):
# Save original video
original_path = os.path.join(output_dir, f"sample_{i}_{j}_original.mp4")
save_video_frames(data[j], original_path)
# Save reconstructed video
recon_path = os.path.join(output_dir, f"sample_{i}_{j}_reconstructed.mp4")
save_video_frames(reconstructed[j], recon_path)
def encode_decode_videos(model, data_loader, device, output_dir, num_samples=5):
"""Encode videos to latent indices and decode them back to demonstrate compression."""
os.makedirs(output_dir, exist_ok=True)
model.eval()
with torch.no_grad():
for i, data in enumerate(tqdm(data_loader, desc="Encoding and decoding videos")):
if i >= num_samples:
break
data = data.to(device)
# Encode video to latent space
encoded_indices = model.encode(data)
# Decode back to video
# Note: we need to reshape indices to the expected format for decode
# The exact shape depends on your model's design
decoded = model.decoder(model.vector_quantizer.embeddings[encoded_indices].to(device))
# Save original and decoded videos for each sample in the batch
for j in range(data.shape[0]):
# Save original video
original_path = os.path.join(output_dir, f"sample_{i}_{j}_encode_original.mp4")
save_video_frames(data[j], original_path)
# Save decoded video
decoded_path = os.path.join(output_dir, f"sample_{i}_{j}_encode_decoded.mp4")
save_video_frames(decoded[j], decoded_path)
# Optionally, visualize the latent space
if i == 0 and j == 0:
# Create a visualization of the latent space indices
latent_viz_path = os.path.join(output_dir, f"latent_visualization.png")
plt.figure(figsize=(10, 8))
plt.imshow(encoded_indices[j, 0].cpu().numpy(), cmap='viridis')
plt.colorbar(label='Codebook Index')
plt.title('Latent Space Representation (First Frame)')
plt.savefig(latent_viz_path)
plt.close()
def main():
parser = argparse.ArgumentParser(description='Inference with trained VQ-VAE model')
parser.add_argument('--model_path', type=str, default='models/best_model.pth', help='Path to trained model')
parser.add_argument('--data_dir', type=str, default='data/ApplyLipstick', help='Directory with video data')
parser.add_argument('--output_dir', type=str, default='outputs/inference', help='Directory to save outputs')
parser.add_argument('--batch_size', type=int, default=1, help='Batch size for inference')
parser.add_argument('--sequence_length', type=int, default=16, help='Number of frames per video sequence')
parser.add_argument('--resolution', type=int, default=128, help='Resolution of frames')
parser.add_argument('--hidden_dim', type=int, default=128, help='Hidden dimension of model')
parser.add_argument('--latent_dim', type=int, default=256, help='Latent dimension of model (embedding dimension)')
parser.add_argument('--num_embeddings', type=int, default=1024, help='Number of vectors in the codebook')
parser.add_argument('--num_workers', type=int, default=0, help='Number of workers for data loading')
parser.add_argument('--num_samples', type=int, default=3, help='Number of samples to process')
args = parser.parse_args()
# Create output directory if it doesn't exist
os.makedirs(args.output_dir, exist_ok=True)
# Set device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# Create dataset and data loader
test_dataset = VideoDataset(
args.data_dir,
sequence_length=args.sequence_length,
resolution=args.resolution,
train=False
)
test_loader = torch.utils.data.DataLoader(
test_dataset,
batch_size=args.batch_size,
shuffle=False,
num_workers=args.num_workers
)
# Load model
model = VQVAE(
in_channels=3,
hidden_dim=args.hidden_dim,
latent_dim=args.latent_dim,
num_embeddings=args.num_embeddings
).to(device)
model.load_state_dict(torch.load(args.model_path, map_location=device))
print(f"Loaded model from {args.model_path}")
# Run inference
reconstruct_videos(model, test_loader, device, args.output_dir, args.num_samples)
# Calculate and print statistics
codebook_usage = model.get_codebook_usage()
print(f"Codebook usage: {codebook_usage:.2f}%")
# Calculate compression ratio
original_dims = args.sequence_length * args.resolution * args.resolution * 3 # T×H×W×C
compressed_dims = (args.sequence_length // 4) * (args.resolution // 4) * (args.resolution // 4) # Latent dimensions
compression_ratio = original_dims / compressed_dims
print(f"Compression ratio: {compression_ratio:.2f}x")
# Additional statistics
print(f"Number of codebook vectors: {args.num_embeddings}")
print(f"Original video dimensions: {args.sequence_length} frames, {args.resolution}x{args.resolution} resolution, 3 channels")
print(f"Latent space dimensions: {args.sequence_length // 4} x {args.resolution // 4} x {args.resolution // 4}")
# Print other model info
num_params = sum(p.numel() for p in model.parameters())
print(f"Number of model parameters: {num_params:,}")
if __name__ == "__main__":
main()