jmonas commited on
Commit
21c4cac
1 Parent(s): 469f320

Upload cosmos_video_decoder.py

Browse files
Files changed (1) hide show
  1. cosmos_video_decoder.py +93 -0
cosmos_video_decoder.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NOTE: Download the Cosmos-Tokenizer repository and pre-trained model weights before running this script.
3
+ For full installation and setup instructions, please refer to:
4
+ https://github.com/NVIDIA/Cosmos-Tokenizer#readme
5
+ """
6
+
7
+ import math
8
+ from pathlib import Path
9
+
10
+ import av
11
+ import numpy as np
12
+ import torch
13
+
14
+ from cosmos_tokenizer.utils import tensor2numpy
15
+ from cosmos_tokenizer.video_lib import CausalVideoTokenizer
16
+
17
+ input_dir = Path("../worldmodel/val_v2.0")
18
+ output_dir = Path("/tmp/reconst_1xgpt/")
19
+ model_name = "Cosmos-Tokenizer-DV8x8x8"
20
+ decoder_path = Path("pretrained_ckpts") / model_name / "decoder.jit"
21
+
22
+ print(f"Output directory exists: {input_dir.exists()}")
23
+ print(f"Decoder path exists: {decoder_path.exists()}")
24
+
25
+ rank = 0
26
+ metadata_path = input_dir / f"metadata_{rank}.json"
27
+ if not metadata_path.exists():
28
+ raise FileNotFoundError(f"Metadata file not found at {metadata_path}")
29
+
30
+ with open(metadata_path, "r") as f:
31
+ metadata_shard = json.load(f)
32
+
33
+ total_frames = metadata_shard["shard_num_frames"]
34
+ print(f"Total frames: {total_frames}")
35
+
36
+ encoded_video_dataset = np.memmap(input_dir / f"video_{rank}.bin", dtype=np.int32, mode="r", shape=(math.ceil(total_frames / 17), 3, 32, 32))
37
+
38
+ print(f"Encoded video dataset shape: {encoded_video_dataset.shape}")
39
+
40
+ indices = torch.tensor(encoded_video_dataset, device="cuda") if not isinstance(encoded_video_dataset, torch.Tensor) else encoded_video_dataset
41
+
42
+ try:
43
+ decoder = CausalVideoTokenizer(checkpoint_dec=str(decoder_path))
44
+ if decoder._dec_model is None:
45
+ raise RuntimeError(f"Failed to load decoder model from {decoder_path}")
46
+ print("Decoder initialized successfully.")
47
+ except Exception as e:
48
+ raise RuntimeError(f"Error loading decoder: {str(e)}") from e
49
+
50
+ batch_size = 1
51
+ fps = 30
52
+ output_file = output_dir / "reconstructed_video.mp4"
53
+
54
+ first_batch = torch.from_numpy(encoded_video_dataset[0:1]).cuda()
55
+ with torch.no_grad():
56
+ first_output = decoder.decode(first_batch).float()
57
+ _, _, height, width = first_output.shape[-4:]
58
+
59
+ print(f"Output video dimensions: {width}x{height}")
60
+
61
+
62
+ ec = av.open(str(output_file), mode="w")
63
+ es = ec.add_stream("hevc_nvenc", rate=30)
64
+ es.width = 256
65
+ es.height = 256
66
+
67
+
68
+ num_batches = math.ceil(len(encoded_video_dataset) / batch_size)
69
+ for i in range(num_batches):
70
+ start_idx = i * batch_size
71
+ end_idx = min((i + 1) * batch_size, len(encoded_video_dataset))
72
+
73
+ batch = torch.from_numpy(encoded_video_dataset[start_idx:end_idx]).cuda()
74
+ with torch.no_grad():
75
+ # [B, 3, 17, 256, 256]
76
+ reconstructed_batch = decoder.decode(batch)
77
+
78
+ # (B, 17, 256, 256, 3)
79
+ reconstructed_batch = tensor2numpy(reconstructed_batch)
80
+
81
+ # frame: 17, 256, 256, 3
82
+ for this_batch in reconstructed_batch:
83
+ for single_frame in this_batch: # Temporal dimension
84
+ # 256, 256, 3
85
+ for ep in es.encode(av.VideoFrame.from_ndarray(single_frame, format="rgb24")):
86
+ ec.mux(ep)
87
+
88
+ print(f"Processed batch {i + 1}/{num_batches}", flush=True)
89
+ if i == 100:
90
+ break
91
+
92
+ ec.close()
93
+ print(f"Video saved to: {output_file}")