zxiao commited on
Commit ·
913e058
1
Parent(s): 16fc17c
update evaluation and fix psnr
Browse files- README.md +53 -3
- algorithms/worldmem/df_base.py +1 -1
- algorithms/worldmem/df_video.py +18 -21
- app.py +1 -45
- compute_video_psnr.py +195 -0
- configurations/algorithm/df_video_worldmemminecraft.yaml +0 -5
- configurations/huggingface.yaml +3 -3
- data_generator.py +330 -0
- datasets/video/minecraft_video_dataset.py +9 -11
- evaluate.sh +22 -0
- experiments/exp_base.py +33 -23
- infer.sh +5 -5
- utils/logging_utils.py +166 -44
README.md
CHANGED
|
@@ -49,7 +49,7 @@ conda install -c conda-forge ffmpeg=4.3.2
|
|
| 49 |
python app.py
|
| 50 |
```
|
| 51 |
|
| 52 |
-
##
|
| 53 |
|
| 54 |
To enable cloud logging with [Weights & Biases (wandb)](https://wandb.ai/site), follow these steps:
|
| 55 |
|
|
@@ -92,8 +92,8 @@ sh infer.sh
|
|
| 92 |
You can either **load the diffusion model and VAE separately**:
|
| 93 |
|
| 94 |
```bash
|
| 95 |
-
+diffusion_model_path=
|
| 96 |
-
+vae_path=
|
| 97 |
+customized_load=true \
|
| 98 |
+seperate_load=true \
|
| 99 |
```
|
|
@@ -106,6 +106,41 @@ Or **load a combined checkpoint**:
|
|
| 106 |
+seperate_load=false \
|
| 107 |
```
|
| 108 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
---
|
| 110 |
|
| 111 |
## Dataset
|
|
@@ -119,14 +154,29 @@ data/
|
|
| 119 |
└── minecraft/
|
| 120 |
├── training/
|
| 121 |
└── validation/
|
|
|
|
| 122 |
```
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
## TODO
|
| 126 |
|
| 127 |
- [x] Release inference models and weights;
|
| 128 |
- [x] Release training pipeline on Minecraft;
|
| 129 |
- [x] Release training data on Minecraft;
|
|
|
|
| 130 |
|
| 131 |
|
| 132 |
|
|
|
|
| 49 |
python app.py
|
| 50 |
```
|
| 51 |
|
| 52 |
+
## Run
|
| 53 |
|
| 54 |
To enable cloud logging with [Weights & Biases (wandb)](https://wandb.ai/site), follow these steps:
|
| 55 |
|
|
|
|
| 92 |
You can either **load the diffusion model and VAE separately**:
|
| 93 |
|
| 94 |
```bash
|
| 95 |
+
+diffusion_model_path=zeqixiao/worldmem_checkpoints/diffusion_only.ckpt \
|
| 96 |
+
+vae_path=zeqixiao/worldmem_checkpoints/vae_only.ckpt \
|
| 97 |
+customized_load=true \
|
| 98 |
+seperate_load=true \
|
| 99 |
```
|
|
|
|
| 106 |
+seperate_load=false \
|
| 107 |
```
|
| 108 |
|
| 109 |
+
### Evaluation
|
| 110 |
+
|
| 111 |
+
To run evaluation:
|
| 112 |
+
|
| 113 |
+
```bash
|
| 114 |
+
sh evaluate.sh
|
| 115 |
+
```
|
| 116 |
+
|
| 117 |
+
This script reproduces the results in Table 1 (beyond context window). Evaluating 1 case on 1 A100 GPU takes approximately 6 minutes. You can adjust `experiment.test.limit_batch` to specify the number of cases to evaluate.
|
| 118 |
+
|
| 119 |
+
Visual results will be saved by default to a timestamped directory (e.g., `outputs/2025-11-30/00-02-42`).
|
| 120 |
+
|
| 121 |
+
To calculate the FID score, run:
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
python calculate_fid.py --videos_dir <path_to_videos>
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
For example:
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
python calculate_fid.py --videos_dir outputs/2025-11-30/00-02-42/videos/test_vis
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
**Expected Results:**
|
| 134 |
+
|
| 135 |
+
| Metric | Value |
|
| 136 |
+
|--------|--------|
|
| 137 |
+
| PSNR | 19.34 |
|
| 138 |
+
| LPIPS | 0.1667 |
|
| 139 |
+
| FID | 15.13 |
|
| 140 |
+
|
| 141 |
+
*Note: FID is computed over 5000 frames.*
|
| 142 |
+
*Note: Previous versions incorrectly used `data_range=2.0` for PSNR calculation, but the decoded video data is in the range [0, 1], so `data_range=1.0` should be used. This bug inflated PSNR values by approximately 6 dB. We have now corrected this in the latest version by clipping predictions to [0, 1] before metric computation. The relative performance comparisons and conclusions remain unchanged.*
|
| 143 |
+
|
| 144 |
---
|
| 145 |
|
| 146 |
## Dataset
|
|
|
|
| 154 |
└── minecraft/
|
| 155 |
├── training/
|
| 156 |
└── validation/
|
| 157 |
+
└── test/
|
| 158 |
```
|
| 159 |
|
| 160 |
+
## Data Generation
|
| 161 |
+
|
| 162 |
+
After setting up the environment as described in [MineDojo's GitHub repository](https://github.com/MineDojo/MineDojo), you can generate data using the following command:
|
| 163 |
+
|
| 164 |
+
```bash
|
| 165 |
+
xvfb-run -a python data_generator.py -o data/test -z 4 --env_type plains
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
**Parameters:**
|
| 169 |
+
- `-o`: Output directory for generated data
|
| 170 |
+
- `-z`: Number of parallel workers
|
| 171 |
+
- `--env_type`: Environment type (e.g., `plains`, `forest`, `desert`)
|
| 172 |
+
|
| 173 |
|
| 174 |
## TODO
|
| 175 |
|
| 176 |
- [x] Release inference models and weights;
|
| 177 |
- [x] Release training pipeline on Minecraft;
|
| 178 |
- [x] Release training data on Minecraft;
|
| 179 |
+
- [x] Release evaluation scripts and data generator.
|
| 180 |
|
| 181 |
|
| 182 |
|
algorithms/worldmem/df_base.py
CHANGED
|
@@ -194,7 +194,7 @@ class DiffusionForcingBase(BasePytorchAlgo):
|
|
| 194 |
def test_step(self, *args: Any, **kwargs: Any) -> STEP_OUTPUT:
|
| 195 |
return self.validation_step(*args, **kwargs, namespace="test")
|
| 196 |
|
| 197 |
-
def
|
| 198 |
self.on_validation_epoch_end(namespace="test")
|
| 199 |
|
| 200 |
def _generate_noise_levels(self, xs: torch.Tensor, masks: Optional[torch.Tensor] = None) -> torch.Tensor:
|
|
|
|
| 194 |
def test_step(self, *args: Any, **kwargs: Any) -> STEP_OUTPUT:
|
| 195 |
return self.validation_step(*args, **kwargs, namespace="test")
|
| 196 |
|
| 197 |
+
def on_test_epoch_end(self) -> None:
|
| 198 |
self.on_validation_epoch_end(namespace="test")
|
| 199 |
|
| 200 |
def _generate_noise_levels(self, xs: torch.Tensor, masks: Optional[torch.Tensor] = None) -> torch.Tensor:
|
algorithms/worldmem/df_video.py
CHANGED
|
@@ -341,16 +341,18 @@ class WorldMemMinecraft(DiffusionForcingBase):
|
|
| 341 |
self.memory_condition_length = cfg.memory_condition_length
|
| 342 |
self.pose_cond_dim = getattr(cfg, "pose_cond_dim", 5)
|
| 343 |
|
| 344 |
-
self.use_plucker = cfg
|
| 345 |
-
self.relative_embedding = cfg
|
| 346 |
self.state_embed_only_on_qk = getattr(cfg, "state_embed_only_on_qk", True)
|
| 347 |
self.use_memory_attention = getattr(cfg, "use_memory_attention", True)
|
| 348 |
-
self.add_timestamp_embedding = cfg
|
| 349 |
self.ref_mode = getattr(cfg, "ref_mode", 'sequential')
|
| 350 |
self.log_curve = getattr(cfg, "log_curve", False)
|
| 351 |
self.focal_length = getattr(cfg, "focal_length", 0.35)
|
| 352 |
self.log_video = cfg.log_video
|
| 353 |
-
self.
|
|
|
|
|
|
|
| 354 |
self.next_frame_length = getattr(cfg, "next_frame_length", 1)
|
| 355 |
self.require_pose_prediction = getattr(cfg, "require_pose_prediction", False)
|
| 356 |
|
|
@@ -497,12 +499,20 @@ class WorldMemMinecraft(DiffusionForcingBase):
|
|
| 497 |
namespace=namespace + "_vis",
|
| 498 |
context_frames=self.context_frames,
|
| 499 |
logger=self.logger.experiment,
|
|
|
|
|
|
|
| 500 |
)
|
| 501 |
|
| 502 |
if xs is not None:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
metric_dict = get_validation_metrics_for_videos(
|
| 504 |
-
|
| 505 |
-
lpips_model=self.validation_lpips_model
|
|
|
|
| 506 |
|
| 507 |
self.log_dict(
|
| 508 |
{"mse": metric_dict['mse'],
|
|
@@ -524,19 +534,6 @@ class WorldMemMinecraft(DiffusionForcingBase):
|
|
| 524 |
|
| 525 |
self.logger.experiment.log({"frame_wise_psnr_plot": line_plot})
|
| 526 |
|
| 527 |
-
elif self.self_consistency_eval:
|
| 528 |
-
metric_dict = get_validation_metrics_for_videos(
|
| 529 |
-
xs_pred[:1],
|
| 530 |
-
xs_pred[-1:],
|
| 531 |
-
lpips_model=self.validation_lpips_model,
|
| 532 |
-
)
|
| 533 |
-
self.log_dict(
|
| 534 |
-
{"lpips": metric_dict['lpips'],
|
| 535 |
-
"mse": metric_dict['mse'],
|
| 536 |
-
"psnr": metric_dict['psnr']},
|
| 537 |
-
sync_dist=True
|
| 538 |
-
)
|
| 539 |
-
|
| 540 |
self.validation_step_outputs.clear()
|
| 541 |
|
| 542 |
def _preprocess_batch(self, batch):
|
|
@@ -786,8 +783,8 @@ class WorldMemMinecraft(DiffusionForcingBase):
|
|
| 786 |
xs_pred = self.decode(xs_pred[n_context_frames:].to(conditions.device))
|
| 787 |
xs_decode = self.decode(xs[n_context_frames:].to(conditions.device))
|
| 788 |
|
| 789 |
-
# Store results for evaluation
|
| 790 |
-
self.validation_step_outputs.append((xs_pred, xs_decode))
|
| 791 |
return
|
| 792 |
|
| 793 |
@torch.no_grad()
|
|
|
|
| 341 |
self.memory_condition_length = cfg.memory_condition_length
|
| 342 |
self.pose_cond_dim = getattr(cfg, "pose_cond_dim", 5)
|
| 343 |
|
| 344 |
+
self.use_plucker = getattr(cfg, "use_plucker", True)
|
| 345 |
+
self.relative_embedding = getattr(cfg, "relative_embedding", True)
|
| 346 |
self.state_embed_only_on_qk = getattr(cfg, "state_embed_only_on_qk", True)
|
| 347 |
self.use_memory_attention = getattr(cfg, "use_memory_attention", True)
|
| 348 |
+
self.add_timestamp_embedding = getattr(cfg, "add_timestamp_embedding", True)
|
| 349 |
self.ref_mode = getattr(cfg, "ref_mode", 'sequential')
|
| 350 |
self.log_curve = getattr(cfg, "log_curve", False)
|
| 351 |
self.focal_length = getattr(cfg, "focal_length", 0.35)
|
| 352 |
self.log_video = cfg.log_video
|
| 353 |
+
self.save_local = getattr(cfg, "save_local", True)
|
| 354 |
+
self.local_save_dir = getattr(cfg, "local_save_dir", None)
|
| 355 |
+
self.lpips_batch_size = getattr(cfg, "lpips_batch_size", 16)
|
| 356 |
self.next_frame_length = getattr(cfg, "next_frame_length", 1)
|
| 357 |
self.require_pose_prediction = getattr(cfg, "require_pose_prediction", False)
|
| 358 |
|
|
|
|
| 499 |
namespace=namespace + "_vis",
|
| 500 |
context_frames=self.context_frames,
|
| 501 |
logger=self.logger.experiment,
|
| 502 |
+
save_local=self.save_local,
|
| 503 |
+
local_save_dir=self.local_save_dir,
|
| 504 |
)
|
| 505 |
|
| 506 |
if xs is not None:
|
| 507 |
+
# Move data to the same device as LPIPS model for metric calculation
|
| 508 |
+
device = next(self.validation_lpips_model.parameters()).device
|
| 509 |
+
xs_pred_device = xs_pred.to(device)
|
| 510 |
+
xs_device = xs.to(device)
|
| 511 |
+
|
| 512 |
metric_dict = get_validation_metrics_for_videos(
|
| 513 |
+
xs_pred_device, xs_device,
|
| 514 |
+
lpips_model=self.validation_lpips_model,
|
| 515 |
+
lpips_batch_size=self.lpips_batch_size)
|
| 516 |
|
| 517 |
self.log_dict(
|
| 518 |
{"mse": metric_dict['mse'],
|
|
|
|
| 534 |
|
| 535 |
self.logger.experiment.log({"frame_wise_psnr_plot": line_plot})
|
| 536 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
self.validation_step_outputs.clear()
|
| 538 |
|
| 539 |
def _preprocess_batch(self, batch):
|
|
|
|
| 783 |
xs_pred = self.decode(xs_pred[n_context_frames:].to(conditions.device))
|
| 784 |
xs_decode = self.decode(xs[n_context_frames:].to(conditions.device))
|
| 785 |
|
| 786 |
+
# Store results for evaluation (move to CPU to save GPU memory)
|
| 787 |
+
self.validation_step_outputs.append((xs_pred.detach().cpu(), xs_decode.detach().cpu()))
|
| 788 |
return
|
| 789 |
|
| 790 |
@torch.no_grad()
|
app.py
CHANGED
|
@@ -25,54 +25,10 @@ import os
|
|
| 25 |
import requests
|
| 26 |
from huggingface_hub import model_info
|
| 27 |
|
| 28 |
-
|
| 29 |
-
def is_huggingface_model(path: str) -> bool:
|
| 30 |
-
hf_ckpt = str(path).split('/')
|
| 31 |
-
repo_id = '/'.join(hf_ckpt[:2])
|
| 32 |
-
try:
|
| 33 |
-
model_info(repo_id)
|
| 34 |
-
return True
|
| 35 |
-
except:
|
| 36 |
-
return False
|
| 37 |
-
|
| 38 |
|
| 39 |
torch.set_float32_matmul_precision("high")
|
| 40 |
|
| 41 |
-
def load_custom_checkpoint(algo, checkpoint_path):
|
| 42 |
-
if is_huggingface_model(str(checkpoint_path)):
|
| 43 |
-
hf_ckpt = str(checkpoint_path).split('/')
|
| 44 |
-
repo_id = '/'.join(hf_ckpt[:2])
|
| 45 |
-
file_name = '/'.join(hf_ckpt[2:])
|
| 46 |
-
model_path = hf_hub_download(repo_id=repo_id,
|
| 47 |
-
filename=file_name)
|
| 48 |
-
ckpt = torch.load(model_path, map_location=torch.device('cpu'))
|
| 49 |
-
|
| 50 |
-
filtered_state_dict = {}
|
| 51 |
-
for k, v in ckpt['state_dict'].items():
|
| 52 |
-
if "frame_timestep_embedder" in k:
|
| 53 |
-
new_k = k.replace("frame_timestep_embedder", "timestamp_embedding")
|
| 54 |
-
filtered_state_dict[new_k] = v
|
| 55 |
-
else:
|
| 56 |
-
filtered_state_dict[k] = v
|
| 57 |
-
|
| 58 |
-
algo.load_state_dict(filtered_state_dict, strict=True)
|
| 59 |
-
print("Load: ", model_path)
|
| 60 |
-
else:
|
| 61 |
-
ckpt = torch.load(checkpoint_path, map_location=torch.device('cpu'))
|
| 62 |
-
|
| 63 |
-
filtered_state_dict = {}
|
| 64 |
-
for k, v in ckpt['state_dict'].items():
|
| 65 |
-
if "frame_timestep_embedder" in k:
|
| 66 |
-
new_k = k.replace("frame_timestep_embedder", "timestamp_embedding")
|
| 67 |
-
filtered_state_dict[new_k] = v
|
| 68 |
-
else:
|
| 69 |
-
filtered_state_dict[k] = v
|
| 70 |
-
|
| 71 |
-
algo.load_state_dict(filtered_state_dict, strict=True)
|
| 72 |
-
|
| 73 |
-
# algo.load_state_dict(ckpt['state_dict'], strict=True)
|
| 74 |
-
print("Load: ", checkpoint_path)
|
| 75 |
-
|
| 76 |
def download_assets_if_needed():
|
| 77 |
ASSETS_URL_BASE = "https://huggingface.co/spaces/yslan/worldmem/resolve/main/assets/examples"
|
| 78 |
ASSETS_DIR = "assets/examples"
|
|
|
|
| 25 |
import requests
|
| 26 |
from huggingface_hub import model_info
|
| 27 |
|
| 28 |
+
from experiments.exp_base import load_custom_checkpoint
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
torch.set_float32_matmul_precision("high")
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def download_assets_if_needed():
|
| 33 |
ASSETS_URL_BASE = "https://huggingface.co/spaces/yslan/worldmem/resolve/main/assets/examples"
|
| 34 |
ASSETS_DIR = "assets/examples"
|
compute_video_psnr.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Compute PSNR for each video pair in gt and pred directories.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import numpy as np
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import imageio
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_video(video_path):
|
| 14 |
+
"""
|
| 15 |
+
Load a video file and return frames as a numpy array.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
video_path: Path to the video file
|
| 19 |
+
|
| 20 |
+
Returns:
|
| 21 |
+
np.ndarray: Video frames of shape (T, C, H, W) normalized to [0, 1]
|
| 22 |
+
"""
|
| 23 |
+
reader = imageio.get_reader(str(video_path))
|
| 24 |
+
frames = []
|
| 25 |
+
for frame in reader:
|
| 26 |
+
# frame is already RGB
|
| 27 |
+
frame = frame.astype(np.float32) / 255.0
|
| 28 |
+
frames.append(frame)
|
| 29 |
+
reader.close()
|
| 30 |
+
|
| 31 |
+
if len(frames) == 0:
|
| 32 |
+
raise ValueError(f"No frames loaded from {video_path}")
|
| 33 |
+
|
| 34 |
+
# Convert to numpy array: (T, H, W, C) -> (T, C, H, W)
|
| 35 |
+
frames = np.stack(frames, axis=0)
|
| 36 |
+
frames = np.transpose(frames, (0, 3, 1, 2))
|
| 37 |
+
|
| 38 |
+
return frames
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def calculate_psnr(pred, gt, data_range=1.0):
|
| 42 |
+
"""
|
| 43 |
+
Calculate PSNR between two images/videos.
|
| 44 |
+
|
| 45 |
+
Args:
|
| 46 |
+
pred: Predicted frames
|
| 47 |
+
gt: Ground truth frames
|
| 48 |
+
data_range: Data range (default: 1.0)
|
| 49 |
+
|
| 50 |
+
Returns:
|
| 51 |
+
float: PSNR value in dB
|
| 52 |
+
"""
|
| 53 |
+
mse = np.mean((pred - gt) ** 2)
|
| 54 |
+
if mse == 0:
|
| 55 |
+
return float('inf')
|
| 56 |
+
return 10 * np.log10((data_range ** 2) / mse)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def compute_psnr(pred_frames, gt_frames, data_range=1.0):
|
| 60 |
+
"""
|
| 61 |
+
Compute PSNR between predicted and ground truth frames.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
pred_frames: Predicted frames array (T, C, H, W)
|
| 65 |
+
gt_frames: Ground truth frames array (T, C, H, W)
|
| 66 |
+
data_range: Data range of the frames (default: 1.0 for [0, 1] range)
|
| 67 |
+
|
| 68 |
+
Returns:
|
| 69 |
+
dict: Dictionary containing overall PSNR and frame-wise PSNR
|
| 70 |
+
"""
|
| 71 |
+
# Ensure same shape
|
| 72 |
+
assert pred_frames.shape == gt_frames.shape, \
|
| 73 |
+
f"Shape mismatch: pred {pred_frames.shape} vs gt {gt_frames.shape}"
|
| 74 |
+
|
| 75 |
+
T, C, H, W = pred_frames.shape
|
| 76 |
+
|
| 77 |
+
# Compute frame-wise PSNR
|
| 78 |
+
frame_wise_psnr = []
|
| 79 |
+
for t in range(T):
|
| 80 |
+
psnr = calculate_psnr(pred_frames[t], gt_frames[t], data_range=data_range)
|
| 81 |
+
frame_wise_psnr.append(psnr)
|
| 82 |
+
|
| 83 |
+
# Compute overall PSNR
|
| 84 |
+
overall_psnr = calculate_psnr(pred_frames, gt_frames, data_range=data_range)
|
| 85 |
+
|
| 86 |
+
return {
|
| 87 |
+
'overall_psnr': overall_psnr,
|
| 88 |
+
'frame_wise_psnr': frame_wise_psnr,
|
| 89 |
+
'mean_frame_psnr': np.mean(frame_wise_psnr),
|
| 90 |
+
'std_frame_psnr': np.std(frame_wise_psnr),
|
| 91 |
+
'num_frames': T
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def main():
|
| 96 |
+
# Directories
|
| 97 |
+
gt_dir = Path("/mnt/WorldMem/outputs/2025-12-01/23-39-44/videos/test_vis/gt")
|
| 98 |
+
pred_dir = Path("/mnt/WorldMem/outputs/2025-12-01/23-39-44/videos/test_vis/pred")
|
| 99 |
+
|
| 100 |
+
# Get all video files in gt directory
|
| 101 |
+
gt_videos = sorted(gt_dir.glob("*.mp4"))
|
| 102 |
+
|
| 103 |
+
print(f"Found {len(gt_videos)} videos to process")
|
| 104 |
+
print("=" * 80)
|
| 105 |
+
|
| 106 |
+
results = []
|
| 107 |
+
|
| 108 |
+
for gt_path in tqdm(gt_videos, desc="Computing PSNR"):
|
| 109 |
+
video_name = gt_path.name
|
| 110 |
+
pred_path = pred_dir / video_name
|
| 111 |
+
|
| 112 |
+
if not pred_path.exists():
|
| 113 |
+
print(f"Warning: Prediction video not found for {video_name}")
|
| 114 |
+
continue
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
# Load videos
|
| 118 |
+
gt_frames = load_video(gt_path)
|
| 119 |
+
pred_frames = load_video(pred_path)
|
| 120 |
+
|
| 121 |
+
# Compute PSNR
|
| 122 |
+
psnr_results = compute_psnr(pred_frames, gt_frames, data_range=1.0)
|
| 123 |
+
|
| 124 |
+
# Store results
|
| 125 |
+
result = {
|
| 126 |
+
'video_name': video_name,
|
| 127 |
+
'overall_psnr': psnr_results['overall_psnr'],
|
| 128 |
+
'mean_frame_psnr': psnr_results['mean_frame_psnr'],
|
| 129 |
+
'std_frame_psnr': psnr_results['std_frame_psnr'],
|
| 130 |
+
'num_frames': psnr_results['num_frames']
|
| 131 |
+
}
|
| 132 |
+
results.append(result)
|
| 133 |
+
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Error processing {video_name}: {str(e)}")
|
| 136 |
+
continue
|
| 137 |
+
|
| 138 |
+
# Create DataFrame for better visualization
|
| 139 |
+
df = pd.DataFrame(results)
|
| 140 |
+
|
| 141 |
+
# Print results
|
| 142 |
+
print("\n" + "=" * 80)
|
| 143 |
+
print("PSNR Results for Each Video:")
|
| 144 |
+
print("=" * 80)
|
| 145 |
+
print(df.to_string(index=False))
|
| 146 |
+
|
| 147 |
+
# Print summary statistics
|
| 148 |
+
print("\n" + "=" * 80)
|
| 149 |
+
print("Summary Statistics:")
|
| 150 |
+
print("=" * 80)
|
| 151 |
+
print(f"Average PSNR across all videos: {df['overall_psnr'].mean():.4f} ± {df['overall_psnr'].std():.4f}")
|
| 152 |
+
print(f"Min PSNR: {df['overall_psnr'].min():.4f} ({df.loc[df['overall_psnr'].idxmin(), 'video_name']})")
|
| 153 |
+
print(f"Max PSNR: {df['overall_psnr'].max():.4f} ({df.loc[df['overall_psnr'].idxmax(), 'video_name']})")
|
| 154 |
+
print(f"Median PSNR: {df['overall_psnr'].median():.4f}")
|
| 155 |
+
|
| 156 |
+
# Group by video ID (video_0, video_1, etc.) and rank
|
| 157 |
+
df['video_id'] = df['video_name'].str.extract(r'(video_\d+)')[0]
|
| 158 |
+
df['rank'] = df['video_name'].str.extract(r'rank(\d+)')[0].astype(int)
|
| 159 |
+
|
| 160 |
+
print("\n" + "=" * 80)
|
| 161 |
+
print("Average PSNR by Video ID:")
|
| 162 |
+
print("=" * 80)
|
| 163 |
+
video_group = df.groupby('video_id')['overall_psnr'].agg(['mean', 'std', 'count'])
|
| 164 |
+
print(video_group.to_string())
|
| 165 |
+
|
| 166 |
+
print("\n" + "=" * 80)
|
| 167 |
+
print("Average PSNR by Rank:")
|
| 168 |
+
print("=" * 80)
|
| 169 |
+
rank_group = df.groupby('rank')['overall_psnr'].agg(['mean', 'std', 'count'])
|
| 170 |
+
print(rank_group.to_string())
|
| 171 |
+
|
| 172 |
+
# Save results to CSV
|
| 173 |
+
output_csv = gt_dir.parent / "psnr_results.csv"
|
| 174 |
+
df.to_csv(output_csv, index=False)
|
| 175 |
+
print(f"\nResults saved to: {output_csv}")
|
| 176 |
+
|
| 177 |
+
# Save summary to text file
|
| 178 |
+
output_txt = gt_dir.parent / "psnr_summary.txt"
|
| 179 |
+
with open(output_txt, 'w') as f:
|
| 180 |
+
f.write("PSNR Results Summary\n")
|
| 181 |
+
f.write("=" * 80 + "\n\n")
|
| 182 |
+
f.write(f"Average PSNR: {df['overall_psnr'].mean():.4f} ± {df['overall_psnr'].std():.4f}\n")
|
| 183 |
+
f.write(f"Min PSNR: {df['overall_psnr'].min():.4f}\n")
|
| 184 |
+
f.write(f"Max PSNR: {df['overall_psnr'].max():.4f}\n")
|
| 185 |
+
f.write(f"Median PSNR: {df['overall_psnr'].median():.4f}\n")
|
| 186 |
+
f.write("\n" + "=" * 80 + "\n")
|
| 187 |
+
f.write("Full Results:\n")
|
| 188 |
+
f.write("=" * 80 + "\n")
|
| 189 |
+
f.write(df.to_string(index=False))
|
| 190 |
+
print(f"Summary saved to: {output_txt}")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
if __name__ == "__main__":
|
| 194 |
+
main()
|
| 195 |
+
|
configurations/algorithm/df_video_worldmemminecraft.yaml
CHANGED
|
@@ -35,9 +35,4 @@ diffusion:
|
|
| 35 |
use_linear_attn: True
|
| 36 |
time_emb_type: rotary
|
| 37 |
|
| 38 |
-
metrics:
|
| 39 |
-
# - fvd
|
| 40 |
-
# - fid
|
| 41 |
-
# - lpips
|
| 42 |
-
|
| 43 |
_name: df_video_worldmemminecraft
|
|
|
|
| 35 |
use_linear_attn: True
|
| 36 |
time_emb_type: rotary
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
_name: df_video_worldmemminecraft
|
configurations/huggingface.yaml
CHANGED
|
@@ -54,7 +54,7 @@ noise_level: random_all
|
|
| 54 |
causal: True
|
| 55 |
x_shape: [3, 360, 640]
|
| 56 |
context_frames: 1
|
| 57 |
-
diffusion_path:
|
| 58 |
-
vae_path:
|
| 59 |
-
pose_predictor_path:
|
| 60 |
next_frame_length: 1
|
|
|
|
| 54 |
causal: True
|
| 55 |
x_shape: [3, 360, 640]
|
| 56 |
context_frames: 1
|
| 57 |
+
diffusion_path: zeqixiao/worldmem_checkpoints/diffusion_only.ckpt
|
| 58 |
+
vae_path: zeqixiao/worldmem_checkpoints/vae_only.ckpt
|
| 59 |
+
pose_predictor_path: zeqixiao/worldmem_checkpoints/pose_prediction_model_only.ckpt
|
| 60 |
next_frame_length: 1
|
data_generator.py
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MineDojo Episode Collection Script
|
| 3 |
+
|
| 4 |
+
This script generates trajectory data from MineDojo environment using a simple agent
|
| 5 |
+
that randomly explores the environment. It supports parallel data collection and
|
| 6 |
+
saves video and action/pose data.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import math
|
| 11 |
+
import multiprocessing as mp
|
| 12 |
+
import os
|
| 13 |
+
import os.path as osp
|
| 14 |
+
import random
|
| 15 |
+
from typing import Dict, Optional, Tuple
|
| 16 |
+
|
| 17 |
+
import cv2
|
| 18 |
+
import minedojo
|
| 19 |
+
import numpy as np
|
| 20 |
+
from tqdm import tqdm
|
| 21 |
+
|
| 22 |
+
# Action mappings for the agent
|
| 23 |
+
# Format: [forward/back, ?, ?, pitch, yaw, ?, ?, ?]
|
| 24 |
+
ACTIONS: Dict[str, np.ndarray] = {
|
| 25 |
+
'forward': np.array([1, 0, 0, 12, 12, 0, 0, 0]),
|
| 26 |
+
'back': np.array([2, 0, 0, 12, 12, 0, 0, 0]),
|
| 27 |
+
'left': np.array([0, 0, 0, 12, 11, 0, 0, 0]),
|
| 28 |
+
'right': np.array([0, 0, 0, 12, 13, 0, 0, 0]),
|
| 29 |
+
'up': np.array([0, 0, 0, 11, 12, 0, 0, 0]),
|
| 30 |
+
'down': np.array([0, 0, 0, 13, 12, 0, 0, 0]),
|
| 31 |
+
'noop': np.array([0, 0, 0, 12, 12, 0, 0, 0])
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def sample_action(prob_forward: float) -> str:
|
| 36 |
+
"""
|
| 37 |
+
Sample an action based on forward probability.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
prob_forward: Probability of moving forward or backward
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
Action name string
|
| 44 |
+
"""
|
| 45 |
+
prob_turn = (1 - prob_forward) / 2
|
| 46 |
+
action = np.random.choice(
|
| 47 |
+
['forward', 'back', 'left', 'right', 'up', 'down'],
|
| 48 |
+
p=[prob_forward / 2 - 0.1, prob_forward / 2 - 0.1, prob_turn, prob_turn, 0.1, 0.1]
|
| 49 |
+
)
|
| 50 |
+
return action
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class SimpleAgent:
|
| 54 |
+
"""
|
| 55 |
+
Simple agent that explores the environment with random actions.
|
| 56 |
+
|
| 57 |
+
Attributes:
|
| 58 |
+
action_repeat: Number of times to repeat the same action
|
| 59 |
+
prob_forward: Probability of moving forward/backward
|
| 60 |
+
max_consec_fwd: Maximum consecutive forward actions (currently unused)
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, prob_forward: float, action_repeat: int, max_consec_fwd: int):
|
| 64 |
+
"""
|
| 65 |
+
Initialize the SimpleAgent.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
prob_forward: Probability of moving forward or backward
|
| 69 |
+
action_repeat: How many steps to repeat each sampled action
|
| 70 |
+
max_consec_fwd: Maximum consecutive forward movements
|
| 71 |
+
"""
|
| 72 |
+
self.action_repeat = action_repeat
|
| 73 |
+
self.prob_forward = prob_forward
|
| 74 |
+
self.max_consec_fwd = max_consec_fwd
|
| 75 |
+
self.reset()
|
| 76 |
+
|
| 77 |
+
def reset(self) -> None:
|
| 78 |
+
"""Reset the agent's internal state."""
|
| 79 |
+
self.n_fwd = 0
|
| 80 |
+
self.counter = 0
|
| 81 |
+
self.action = None
|
| 82 |
+
|
| 83 |
+
def sample(self, pos: np.ndarray) -> np.ndarray:
|
| 84 |
+
"""
|
| 85 |
+
Sample an action given the current position.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
pos: Current position array containing [x, y, z, pitch, yaw]
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
Action array
|
| 92 |
+
"""
|
| 93 |
+
prob_forward = self.prob_forward
|
| 94 |
+
|
| 95 |
+
# Sample new action if needed (or if previous was up/down)
|
| 96 |
+
if (self.action is None or
|
| 97 |
+
self.counter % self.action_repeat == 0 or
|
| 98 |
+
self.action in ['up', 'down']):
|
| 99 |
+
self.action = sample_action(prob_forward)
|
| 100 |
+
|
| 101 |
+
self.counter += 1
|
| 102 |
+
return ACTIONS[self.action]
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def collect_episode(env, agent: SimpleAgent, traj_length: int) -> Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]:
|
| 106 |
+
"""
|
| 107 |
+
Collect a single episode of trajectory data.
|
| 108 |
+
|
| 109 |
+
Args:
|
| 110 |
+
env: MineDojo environment
|
| 111 |
+
agent: Agent to collect data with
|
| 112 |
+
traj_length: Length of trajectory to collect
|
| 113 |
+
|
| 114 |
+
Returns:
|
| 115 |
+
Tuple of (rgb observations, actions, poses) or None if collection fails
|
| 116 |
+
"""
|
| 117 |
+
agent.reset()
|
| 118 |
+
|
| 119 |
+
# Retry environment reset until successful
|
| 120 |
+
success = False
|
| 121 |
+
max_retries = 10
|
| 122 |
+
retries = 0
|
| 123 |
+
while not success and retries < max_retries:
|
| 124 |
+
try:
|
| 125 |
+
obs = env.reset()
|
| 126 |
+
success = True
|
| 127 |
+
except Exception as e:
|
| 128 |
+
retries += 1
|
| 129 |
+
if retries >= max_retries:
|
| 130 |
+
print(f"Failed to reset environment after {max_retries} retries")
|
| 131 |
+
return None
|
| 132 |
+
|
| 133 |
+
observations = [obs['rgb']]
|
| 134 |
+
actions = [env.action_space.no_op()]
|
| 135 |
+
pose = [np.concatenate([
|
| 136 |
+
obs['location_stats']['pos'],
|
| 137 |
+
obs['location_stats']['pitch'],
|
| 138 |
+
obs['location_stats']['yaw']
|
| 139 |
+
])]
|
| 140 |
+
|
| 141 |
+
for ei in range(traj_length):
|
| 142 |
+
curr_actions = agent.sample(pose[ei])
|
| 143 |
+
obs, reward, done, info = env.step(curr_actions)
|
| 144 |
+
|
| 145 |
+
actions.append(curr_actions)
|
| 146 |
+
observations.append(obs['rgb'])
|
| 147 |
+
pose.append(np.concatenate([
|
| 148 |
+
obs['location_stats']['pos'],
|
| 149 |
+
obs['location_stats']['pitch'],
|
| 150 |
+
obs['location_stats']['yaw']
|
| 151 |
+
]))
|
| 152 |
+
|
| 153 |
+
rgb = np.stack(observations, axis=0)
|
| 154 |
+
actions = np.array(actions, dtype=np.int32)
|
| 155 |
+
pose = np.array(pose)
|
| 156 |
+
|
| 157 |
+
return rgb, actions, pose
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def worker(worker_id: int, args: argparse.Namespace) -> None:
|
| 161 |
+
"""
|
| 162 |
+
Worker process for parallel data collection.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
worker_id: Unique ID for this worker process
|
| 166 |
+
args: Command-line arguments
|
| 167 |
+
"""
|
| 168 |
+
# Create worker-specific output directory
|
| 169 |
+
worker_output_dir = osp.join(args.output_dir, f'{worker_id}')
|
| 170 |
+
os.makedirs(worker_output_dir, exist_ok=True)
|
| 171 |
+
|
| 172 |
+
# Set worker-specific random seeds for reproducibility
|
| 173 |
+
# Use a large offset between workers to ensure independent random streams
|
| 174 |
+
worker_seed = args.base_seed + worker_id * 10000
|
| 175 |
+
np.random.seed(worker_seed)
|
| 176 |
+
random.seed(worker_seed)
|
| 177 |
+
|
| 178 |
+
agent = SimpleAgent(args.prob_forward, args.action_repeat, args.max_consec_fwd)
|
| 179 |
+
|
| 180 |
+
# Calculate number of episodes for this worker
|
| 181 |
+
num_episodes = args.num_episodes // args.n_parallel
|
| 182 |
+
if worker_id < (args.num_episodes % args.n_parallel):
|
| 183 |
+
num_episodes += 1
|
| 184 |
+
|
| 185 |
+
pbar = tqdm(total=num_episodes, position=worker_id, desc=f"Worker {worker_id}")
|
| 186 |
+
episode_count = 0
|
| 187 |
+
|
| 188 |
+
while episode_count < num_episodes:
|
| 189 |
+
# Create environment with unique seeds for each worker and episode
|
| 190 |
+
# Ensure world_seed and seed are different for each worker and episode
|
| 191 |
+
episode_seed_base = worker_seed + episode_count * 100
|
| 192 |
+
world_seed = episode_seed_base
|
| 193 |
+
env_seed = episode_seed_base + 1
|
| 194 |
+
|
| 195 |
+
env = minedojo.make(
|
| 196 |
+
task_id="open-ended",
|
| 197 |
+
image_size=(360, 640),
|
| 198 |
+
world_seed=world_seed,
|
| 199 |
+
seed=env_seed,
|
| 200 |
+
generate_world_type='specified_biome',
|
| 201 |
+
specified_biome=args.env_type,
|
| 202 |
+
initial_weather='rain'
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
# Collect episode data
|
| 206 |
+
out = collect_episode(env, agent, args.traj_length)
|
| 207 |
+
if out is None:
|
| 208 |
+
env.close()
|
| 209 |
+
continue
|
| 210 |
+
|
| 211 |
+
rgb, actions, poses = out
|
| 212 |
+
|
| 213 |
+
# Save video
|
| 214 |
+
video_fname = osp.join(worker_output_dir, f'{episode_count:06d}.mp4')
|
| 215 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 216 |
+
writer = cv2.VideoWriter(video_fname, fourcc, 10.0, (rgb.shape[3], rgb.shape[2]))
|
| 217 |
+
|
| 218 |
+
for t in range(rgb.shape[0]):
|
| 219 |
+
frame = rgb[t].transpose(1, 2, 0)
|
| 220 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
| 221 |
+
writer.write(frame)
|
| 222 |
+
writer.release()
|
| 223 |
+
|
| 224 |
+
# Save actions and poses
|
| 225 |
+
action_fname = osp.join(worker_output_dir, f'{episode_count:06d}.npz')
|
| 226 |
+
np.savez_compressed(action_fname, actions=actions, poses=poses)
|
| 227 |
+
|
| 228 |
+
episode_count += 1
|
| 229 |
+
env.close()
|
| 230 |
+
pbar.update(1)
|
| 231 |
+
|
| 232 |
+
pbar.close()
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def main(args: argparse.Namespace) -> None:
|
| 236 |
+
"""
|
| 237 |
+
Main function to orchestrate parallel data collection.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
args: Command-line arguments
|
| 241 |
+
"""
|
| 242 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 243 |
+
|
| 244 |
+
# Create and start worker processes
|
| 245 |
+
procs = [mp.Process(target=worker, args=(i, args)) for i in range(args.n_parallel)]
|
| 246 |
+
for p in procs:
|
| 247 |
+
p.start()
|
| 248 |
+
for p in procs:
|
| 249 |
+
p.join()
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == '__main__':
|
| 253 |
+
parser = argparse.ArgumentParser(
|
| 254 |
+
description='Generate MineDojo trajectory data with parallel collection'
|
| 255 |
+
)
|
| 256 |
+
parser.add_argument(
|
| 257 |
+
'-o', '--output_dir',
|
| 258 |
+
type=str,
|
| 259 |
+
default='test',
|
| 260 |
+
help='Output directory for generated data'
|
| 261 |
+
)
|
| 262 |
+
parser.add_argument(
|
| 263 |
+
'--env_type',
|
| 264 |
+
type=str,
|
| 265 |
+
default='test',
|
| 266 |
+
help='Biome type for environment generation'
|
| 267 |
+
)
|
| 268 |
+
parser.add_argument(
|
| 269 |
+
'-z', '--n_parallel',
|
| 270 |
+
type=int,
|
| 271 |
+
default=1,
|
| 272 |
+
help='Number of parallel workers (default: 1)'
|
| 273 |
+
)
|
| 274 |
+
parser.add_argument(
|
| 275 |
+
'-a', '--action_repeat',
|
| 276 |
+
type=int,
|
| 277 |
+
default=5,
|
| 278 |
+
help='Number of times to repeat each action (default: 5)'
|
| 279 |
+
)
|
| 280 |
+
parser.add_argument(
|
| 281 |
+
'-p', '--prob_forward',
|
| 282 |
+
type=float,
|
| 283 |
+
default=0.7,
|
| 284 |
+
help='Probability of forward/backward actions (default: 0.7)'
|
| 285 |
+
)
|
| 286 |
+
parser.add_argument(
|
| 287 |
+
'-m', '--max_consec_fwd',
|
| 288 |
+
type=int,
|
| 289 |
+
default=50,
|
| 290 |
+
help='Maximum consecutive forward movements (default: 50)'
|
| 291 |
+
)
|
| 292 |
+
parser.add_argument(
|
| 293 |
+
'-t', '--traj_length',
|
| 294 |
+
type=int,
|
| 295 |
+
default=1500,
|
| 296 |
+
help='Length of each trajectory (default: 1500)'
|
| 297 |
+
)
|
| 298 |
+
parser.add_argument(
|
| 299 |
+
'-n', '--num_episodes',
|
| 300 |
+
type=int,
|
| 301 |
+
default=100000,
|
| 302 |
+
help='Total number of episodes to generate (default: 100000)'
|
| 303 |
+
)
|
| 304 |
+
parser.add_argument(
|
| 305 |
+
'-r', '--resolution',
|
| 306 |
+
type=int,
|
| 307 |
+
default=128,
|
| 308 |
+
help='Resolution (currently unused, default: 128)'
|
| 309 |
+
)
|
| 310 |
+
parser.add_argument(
|
| 311 |
+
'-rh', '--resolution_h',
|
| 312 |
+
type=int,
|
| 313 |
+
default=360,
|
| 314 |
+
help='Height resolution (currently unused, default: 360)'
|
| 315 |
+
)
|
| 316 |
+
parser.add_argument(
|
| 317 |
+
'-rw', '--resolution_w',
|
| 318 |
+
type=int,
|
| 319 |
+
default=640,
|
| 320 |
+
help='Width resolution (currently unused, default: 640)'
|
| 321 |
+
)
|
| 322 |
+
parser.add_argument(
|
| 323 |
+
'--base_seed',
|
| 324 |
+
type=int,
|
| 325 |
+
default=42,
|
| 326 |
+
help='Base RNG seed; worker i uses base_seed+i (default: 42)'
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
args = parser.parse_args()
|
| 330 |
+
main(args)
|
datasets/video/minecraft_video_dataset.py
CHANGED
|
@@ -66,22 +66,19 @@ class MinecraftVideoDataset(BaseVideoDataset):
|
|
| 66 |
split (str): Dataset split ("training" or "validation").
|
| 67 |
"""
|
| 68 |
def __init__(self, cfg: DictConfig, split: str = "training"):
|
| 69 |
-
if split == "test":
|
| 70 |
-
split = "validation"
|
| 71 |
self.wo_updown = getattr(cfg, "wo_updown", False)
|
| 72 |
super().__init__(cfg, split)
|
| 73 |
-
self.n_frames = cfg.n_frames_valid if split == "validation" and hasattr(cfg, "n_frames_valid") else cfg.n_frames
|
| 74 |
-
self.memory_condition_length = cfg
|
| 75 |
self.customized_validation = cfg.customized_validation
|
| 76 |
if split == "training":
|
| 77 |
self.angle_range = cfg.angle_range
|
| 78 |
self.pos_range = cfg.pos_range
|
| 79 |
-
self.add_timestamp_embedding = cfg
|
| 80 |
self.training_dropout = 0.1
|
| 81 |
-
self.memory_condition_length = getattr(cfg, "memory_condition_length", False)
|
| 82 |
self.sample_more_event = getattr(cfg, "sample_more_event", False)
|
| 83 |
self.causal_frame = getattr(cfg, "causal_frame", False)
|
| 84 |
-
|
| 85 |
def get_data_paths(self, split: str):
|
| 86 |
"""
|
| 87 |
Retrieve all video file paths for the given split.
|
|
@@ -99,9 +96,9 @@ class MinecraftVideoDataset(BaseVideoDataset):
|
|
| 99 |
# Filter out paths containing "w_updown"
|
| 100 |
paths = [p for p in paths if "w_updown" not in str(p)]
|
| 101 |
|
| 102 |
-
if split == "validation" and self.wo_updown:
|
| 103 |
paths = [p for p in paths if "w_updown" not in str(p)]
|
| 104 |
-
elif split == "validation":
|
| 105 |
paths = [p for p in paths if "w_updown" in str(p)]
|
| 106 |
|
| 107 |
if not paths:
|
|
@@ -129,7 +126,7 @@ class MinecraftVideoDataset(BaseVideoDataset):
|
|
| 129 |
try:
|
| 130 |
return self.load_data(idx)
|
| 131 |
except Exception as e:
|
| 132 |
-
print(f"Retrying due to error: {e}")
|
| 133 |
idx = (idx + 1) % len(self)
|
| 134 |
|
| 135 |
def load_data(self, idx):
|
|
@@ -147,7 +144,8 @@ class MinecraftVideoDataset(BaseVideoDataset):
|
|
| 147 |
|
| 148 |
# Fix corrupted height (maybe) in the first frame
|
| 149 |
poses_pool[0, 1] = poses_pool[1, 1]
|
| 150 |
-
assert poses_pool[:, 1].ptp() < 2, f"Height variation too large: {poses_pool[:, 1].ptp()} - {video_path}"
|
|
|
|
| 151 |
|
| 152 |
# Pad poses if shorter than actions
|
| 153 |
if len(poses_pool) < len(actions_pool):
|
|
|
|
| 66 |
split (str): Dataset split ("training" or "validation").
|
| 67 |
"""
|
| 68 |
def __init__(self, cfg: DictConfig, split: str = "training"):
|
|
|
|
|
|
|
| 69 |
self.wo_updown = getattr(cfg, "wo_updown", False)
|
| 70 |
super().__init__(cfg, split)
|
| 71 |
+
self.n_frames = cfg.n_frames_valid if split == "validation" or split == "test" and hasattr(cfg, "n_frames_valid") else cfg.n_frames
|
| 72 |
+
self.memory_condition_length = getattr(cfg, "memory_condition_length", 8)
|
| 73 |
self.customized_validation = cfg.customized_validation
|
| 74 |
if split == "training":
|
| 75 |
self.angle_range = cfg.angle_range
|
| 76 |
self.pos_range = cfg.pos_range
|
| 77 |
+
self.add_timestamp_embedding = getattr(cfg, "add_timestamp_embedding", True)
|
| 78 |
self.training_dropout = 0.1
|
|
|
|
| 79 |
self.sample_more_event = getattr(cfg, "sample_more_event", False)
|
| 80 |
self.causal_frame = getattr(cfg, "causal_frame", False)
|
| 81 |
+
|
| 82 |
def get_data_paths(self, split: str):
|
| 83 |
"""
|
| 84 |
Retrieve all video file paths for the given split.
|
|
|
|
| 96 |
# Filter out paths containing "w_updown"
|
| 97 |
paths = [p for p in paths if "w_updown" not in str(p)]
|
| 98 |
|
| 99 |
+
if (split == "validation" or split == "test") and self.wo_updown:
|
| 100 |
paths = [p for p in paths if "w_updown" not in str(p)]
|
| 101 |
+
elif split == "validation" or split == "test":
|
| 102 |
paths = [p for p in paths if "w_updown" in str(p)]
|
| 103 |
|
| 104 |
if not paths:
|
|
|
|
| 126 |
try:
|
| 127 |
return self.load_data(idx)
|
| 128 |
except Exception as e:
|
| 129 |
+
# print(f"Retrying due to error: {e}")
|
| 130 |
idx = (idx + 1) % len(self)
|
| 131 |
|
| 132 |
def load_data(self, idx):
|
|
|
|
| 144 |
|
| 145 |
# Fix corrupted height (maybe) in the first frame
|
| 146 |
poses_pool[0, 1] = poses_pool[1, 1]
|
| 147 |
+
# assert poses_pool[:, 1].ptp() < 2, f"Height variation too large: {poses_pool[:, 1].ptp()} - {video_path}"
|
| 148 |
+
assert poses_pool[:, 1].ptp() < 2
|
| 149 |
|
| 150 |
# Pad poses if shorter than actions
|
| 151 |
if len(poses_pool) < len(actions_pool):
|
evaluate.sh
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export PYTHONWARNINGS="ignore"
|
| 2 |
+
wandb offline
|
| 3 |
+
python -m main +name=infer \
|
| 4 |
+
experiment.tasks=[test] \
|
| 5 |
+
dataset.validation_multiplier=1 \
|
| 6 |
+
+diffusion_model_path=zeqixiao/worldmem_checkpoints/diffusion_only.ckpt \
|
| 7 |
+
+vae_path=zeqixiao/worldmem_checkpoints/vae_only.ckpt \
|
| 8 |
+
+customized_load=true \
|
| 9 |
+
+seperate_load=true \
|
| 10 |
+
dataset.n_frames=8 \
|
| 11 |
+
dataset.save_dir=data/minecraft \
|
| 12 |
+
+dataset.n_frames_valid=700 \
|
| 13 |
+
algorithm.diffusion.sampling_timesteps=20 \
|
| 14 |
+
+algorithm.memory_condition_length=8 \
|
| 15 |
+
+algorithm.lpips_batch_size=16 \
|
| 16 |
+
+algorithm.log_video=true \
|
| 17 |
+
+algorithm.save_local=true \
|
| 18 |
+
+dataset.customized_validation=true \
|
| 19 |
+
+algorithm.n_tokens=8 \
|
| 20 |
+
algorithm.context_frames=600 \
|
| 21 |
+
experiment.test.batch_size=1 \
|
| 22 |
+
experiment.test.limit_batch=10 \
|
experiments/exp_base.py
CHANGED
|
@@ -49,23 +49,14 @@ def load_custom_checkpoint(algo, checkpoint_path):
|
|
| 49 |
checkpoint_path = Path(checkpoint_path)
|
| 50 |
|
| 51 |
if is_huggingface_model(str(checkpoint_path)):
|
| 52 |
-
# Load from Hugging Face Hub if the path contains '
|
| 53 |
hf_ckpt = str(checkpoint_path).split('/')
|
| 54 |
repo_id = '/'.join(hf_ckpt[:2])
|
| 55 |
file_name = '/'.join(hf_ckpt[2:])
|
| 56 |
model_path = hf_hub_download(repo_id=repo_id, filename=file_name)
|
| 57 |
ckpt = torch.load(model_path, map_location=torch.device('cpu'))
|
| 58 |
|
| 59 |
-
|
| 60 |
-
filtered_state_dict = {}
|
| 61 |
-
for k, v in ckpt['state_dict'].items():
|
| 62 |
-
if "frame_timestep_embedder" in k:
|
| 63 |
-
new_k = k.replace("frame_timestep_embedder", "timestamp_embedding")
|
| 64 |
-
filtered_state_dict[new_k] = v
|
| 65 |
-
else:
|
| 66 |
-
filtered_state_dict[k] = v
|
| 67 |
-
|
| 68 |
-
algo.load_state_dict(filtered_state_dict, strict=False)
|
| 69 |
|
| 70 |
elif checkpoint_path.suffix == ".pt":
|
| 71 |
# Load from a .pt file
|
|
@@ -106,11 +97,6 @@ def load_custom_checkpoint(algo, checkpoint_path):
|
|
| 106 |
if not k in ["data_mean", "data_std"]
|
| 107 |
}
|
| 108 |
|
| 109 |
-
# for k, v in filtered_state_dict.items():
|
| 110 |
-
# if "frame_timestep_embedder" in k:
|
| 111 |
-
# new_k = k.replace("frame_timestep_embedder", "timestamp_embedding")
|
| 112 |
-
# filtered_state_dict[new_k] = v
|
| 113 |
-
|
| 114 |
algo.load_state_dict(filtered_state_dict, strict=False)
|
| 115 |
|
| 116 |
else:
|
|
@@ -436,13 +422,37 @@ class BaseLightningExperiment(BaseExperiment):
|
|
| 436 |
detect_anomaly=False, # self.cfg.debug,
|
| 437 |
)
|
| 438 |
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
if not self.algo:
|
| 447 |
self.algo = self._build_algo()
|
| 448 |
if self.cfg.validation.compile:
|
|
|
|
| 49 |
checkpoint_path = Path(checkpoint_path)
|
| 50 |
|
| 51 |
if is_huggingface_model(str(checkpoint_path)):
|
| 52 |
+
# Load from Hugging Face Hub if the path contains 'zeqixiao'
|
| 53 |
hf_ckpt = str(checkpoint_path).split('/')
|
| 54 |
repo_id = '/'.join(hf_ckpt[:2])
|
| 55 |
file_name = '/'.join(hf_ckpt[2:])
|
| 56 |
model_path = hf_hub_download(repo_id=repo_id, filename=file_name)
|
| 57 |
ckpt = torch.load(model_path, map_location=torch.device('cpu'))
|
| 58 |
|
| 59 |
+
algo.load_state_dict(ckpt['state_dict'], strict=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
elif checkpoint_path.suffix == ".pt":
|
| 62 |
# Load from a .pt file
|
|
|
|
| 97 |
if not k in ["data_mean", "data_std"]
|
| 98 |
}
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
algo.load_state_dict(filtered_state_dict, strict=False)
|
| 101 |
|
| 102 |
else:
|
|
|
|
| 422 |
detect_anomaly=False, # self.cfg.debug,
|
| 423 |
)
|
| 424 |
|
| 425 |
+
if self.customized_load:
|
| 426 |
+
if self.seperate_load:
|
| 427 |
+
if 'oasis500m' in self.diffusion_model_path:
|
| 428 |
+
load_custom_checkpoint(algo=self.algo.diffusion_model.model,checkpoint_path=self.diffusion_model_path)
|
| 429 |
+
else:
|
| 430 |
+
load_custom_checkpoint(algo=self.algo.diffusion_model,checkpoint_path=self.diffusion_model_path)
|
| 431 |
+
load_custom_checkpoint(algo=self.algo.vae,checkpoint_path=self.vae_path)
|
| 432 |
+
else:
|
| 433 |
+
load_custom_checkpoint(algo=self.algo,checkpoint_path=self.ckpt_path)
|
| 434 |
+
|
| 435 |
+
if self.zero_init_gate:
|
| 436 |
+
for name, para in self.algo.diffusion_model.named_parameters():
|
| 437 |
+
if 'r_adaLN_modulation' in name:
|
| 438 |
+
para.requires_grad_(False)
|
| 439 |
+
para[2*1024:3*1024] = 0
|
| 440 |
+
para[5*1024:6*1024] = 0
|
| 441 |
+
para.requires_grad_(True)
|
| 442 |
+
|
| 443 |
+
trainer.test(
|
| 444 |
+
self.algo,
|
| 445 |
+
dataloaders=self._build_test_loader(),
|
| 446 |
+
ckpt_path=None,
|
| 447 |
+
)
|
| 448 |
+
else:
|
| 449 |
+
trainer.test(
|
| 450 |
+
self.algo,
|
| 451 |
+
dataloaders=self._build_test_loader(),
|
| 452 |
+
ckpt_path=self.ckpt_path,
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
if not self.algo:
|
| 457 |
self.algo = self._build_algo()
|
| 458 |
if self.cfg.validation.compile:
|
infer.sh
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
python -m main +name=infer \
|
| 3 |
experiment.tasks=[validation] \
|
| 4 |
dataset.validation_multiplier=1 \
|
| 5 |
-
+diffusion_model_path=
|
| 6 |
-
+vae_path=
|
| 7 |
+customized_load=true \
|
| 8 |
+seperate_load=true \
|
| 9 |
dataset.n_frames=8 \
|
|
@@ -17,5 +18,4 @@ python -m main +name=infer \
|
|
| 17 |
algorithm.context_frames=600 \
|
| 18 |
+algorithm.relative_embedding=true \
|
| 19 |
+algorithm.log_video=true \
|
| 20 |
-
+algorithm.add_timestamp_embedding=true
|
| 21 |
-
algorithm.metrics=[lpips,psnr] \
|
|
|
|
| 1 |
+
export PYTHONWARNINGS="ignore"
|
| 2 |
+
wandb offline
|
| 3 |
python -m main +name=infer \
|
| 4 |
experiment.tasks=[validation] \
|
| 5 |
dataset.validation_multiplier=1 \
|
| 6 |
+
+diffusion_model_path=zeqixiao/worldmem_checkpoints/diffusion_only.ckpt \
|
| 7 |
+
+vae_path=zeqixiao/worldmem_checkpoints/vae_only.ckpt \
|
| 8 |
+customized_load=true \
|
| 9 |
+seperate_load=true \
|
| 10 |
dataset.n_frames=8 \
|
|
|
|
| 18 |
algorithm.context_frames=600 \
|
| 19 |
+algorithm.relative_embedding=true \
|
| 20 |
+algorithm.log_video=true \
|
| 21 |
+
+algorithm.add_timestamp_embedding=true
|
|
|
utils/logging_utils.py
CHANGED
|
@@ -2,6 +2,7 @@ from typing import Optional
|
|
| 2 |
import wandb
|
| 3 |
import numpy as np
|
| 4 |
import torch
|
|
|
|
| 5 |
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import cv2
|
|
@@ -9,7 +10,8 @@ import matplotlib.pyplot as plt
|
|
| 9 |
from tqdm import trange, tqdm
|
| 10 |
import matplotlib.animation as animation
|
| 11 |
from pathlib import Path
|
| 12 |
-
|
|
|
|
| 13 |
plt.set_loglevel("warning")
|
| 14 |
|
| 15 |
from torchmetrics.functional import mean_squared_error, peak_signal_noise_ratio
|
|
@@ -34,6 +36,10 @@ def log_video(
|
|
| 34 |
context_frames=0,
|
| 35 |
color=(255, 0, 0),
|
| 36 |
logger=None,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
):
|
| 38 |
"""
|
| 39 |
take in video tensors in range [-1, 1] and log into wandb
|
|
@@ -46,37 +52,139 @@ def log_video(
|
|
| 46 |
:param context_frames: an int indicating how many frames in observation_hat are ground truth given as context
|
| 47 |
:param color: a tuple of 3 numbers specifying the color of the border for ground truth frames
|
| 48 |
:param logger: optional logger to use. use global wandb if not specified
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
if not logger:
|
| 51 |
logger = wandb
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
# Add red border of 1 pixel width to the context frames
|
| 56 |
-
# for i, c in enumerate(color):
|
| 57 |
-
# c = c / 255.0
|
| 58 |
-
# observation_hat[:context_frames, :, i, [0, -1], :] = c
|
| 59 |
-
# observation_hat[:context_frames, :, i, :, [0, -1]] = c
|
| 60 |
-
|
| 61 |
-
# if observation_gt is not None:
|
| 62 |
-
# observation_gt[:context_frames, :, i, [0, -1], :] = c
|
| 63 |
-
# observation_gt[:context_frames, :, i, :, [0, -1]] = c
|
| 64 |
-
|
| 65 |
if observation_gt is not None:
|
| 66 |
-
|
| 67 |
else:
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
for i in range(n_samples):
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
|
| 82 |
def get_validation_metrics_for_videos(
|
|
@@ -85,6 +193,7 @@ def get_validation_metrics_for_videos(
|
|
| 85 |
lpips_model: Optional[LearnedPerceptualImagePatchSimilarity] = None,
|
| 86 |
fid_model: Optional[FrechetInceptionDistance] = None,
|
| 87 |
fvd_model: Optional[FrechetVideoDistance] = None,
|
|
|
|
| 88 |
):
|
| 89 |
"""
|
| 90 |
:param observation_hat: predicted observation tensor of shape (frame, batch, channel, height, width)
|
|
@@ -92,6 +201,7 @@ def get_validation_metrics_for_videos(
|
|
| 92 |
:param lpips_model: a LearnedPerceptualImagePatchSimilarity object from algorithm.common.metrics
|
| 93 |
:param fid_model: a FrechetInceptionDistance object from algorithm.common.metrics
|
| 94 |
:param fvd_model: a FrechetVideoDistance object from algorithm.common.metrics
|
|
|
|
| 95 |
:return: a tuple of metrics
|
| 96 |
"""
|
| 97 |
frame, batch, channel, height, width = observation_hat.shape
|
|
@@ -104,39 +214,51 @@ def get_validation_metrics_for_videos(
|
|
| 104 |
observation_hat = observation_hat.float()
|
| 105 |
observation_gt = observation_gt.float()
|
| 106 |
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
# output_dict["fvd"] = fvd_model.compute(torch.clamp(observation_hat, -1.0, 1.0), torch.clamp(observation_gt, -1.0, 1.0))
|
| 111 |
|
|
|
|
| 112 |
frame_wise_psnr = []
|
| 113 |
-
for f in range(
|
| 114 |
-
frame_wise_psnr.append(peak_signal_noise_ratio(
|
| 115 |
frame_wise_psnr = torch.stack(frame_wise_psnr)
|
| 116 |
|
| 117 |
output_dict["frame_wise_psnr"] = frame_wise_psnr
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
output_dict["mse"] = mean_squared_error(observation_hat, observation_gt)
|
| 122 |
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
#
|
| 127 |
-
|
| 128 |
-
observation_gt = torch.clamp(observation_gt, -1.0, 1.0)
|
| 129 |
|
|
|
|
| 130 |
if lpips_model is not None:
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
lpips = lpips_model.compute().item()
|
| 133 |
# Reset the states of non-functional metrics
|
| 134 |
output_dict["lpips"] = lpips
|
| 135 |
lpips_model.reset()
|
| 136 |
|
|
|
|
| 137 |
if fid_model is not None:
|
| 138 |
-
observation_hat_uint8 = (
|
| 139 |
-
observation_gt_uint8 = (
|
| 140 |
fid_model.update(observation_gt_uint8, real=True)
|
| 141 |
fid_model.update(observation_hat_uint8, real=False)
|
| 142 |
fid = fid_model.compute()
|
|
|
|
| 2 |
import wandb
|
| 3 |
import numpy as np
|
| 4 |
import torch
|
| 5 |
+
import os
|
| 6 |
|
| 7 |
import matplotlib.pyplot as plt
|
| 8 |
import cv2
|
|
|
|
| 10 |
from tqdm import trange, tqdm
|
| 11 |
import matplotlib.animation as animation
|
| 12 |
from pathlib import Path
|
| 13 |
+
import imageio
|
| 14 |
+
|
| 15 |
plt.set_loglevel("warning")
|
| 16 |
|
| 17 |
from torchmetrics.functional import mean_squared_error, peak_signal_noise_ratio
|
|
|
|
| 36 |
context_frames=0,
|
| 37 |
color=(255, 0, 0),
|
| 38 |
logger=None,
|
| 39 |
+
fps=15,
|
| 40 |
+
format="mp4",
|
| 41 |
+
save_local=True,
|
| 42 |
+
local_save_dir=None,
|
| 43 |
):
|
| 44 |
"""
|
| 45 |
take in video tensors in range [-1, 1] and log into wandb
|
|
|
|
| 52 |
:param context_frames: an int indicating how many frames in observation_hat are ground truth given as context
|
| 53 |
:param color: a tuple of 3 numbers specifying the color of the border for ground truth frames
|
| 54 |
:param logger: optional logger to use. use global wandb if not specified
|
| 55 |
+
:param fps: frames per second for the video (default: 15)
|
| 56 |
+
:param format: video format, either "mp4" or "gif" (default: "mp4")
|
| 57 |
+
:param save_local: whether to save videos to local disk (default: True)
|
| 58 |
+
:param local_save_dir: directory to save local videos. If None, uses hydra output dir
|
| 59 |
"""
|
| 60 |
+
import cv2
|
| 61 |
+
import hydra
|
| 62 |
+
from pathlib import Path
|
| 63 |
+
|
| 64 |
+
# Get local rank for distributed training
|
| 65 |
+
local_rank = int(os.environ.get("LOCAL_RANK", 0))
|
| 66 |
+
|
| 67 |
if not logger:
|
| 68 |
logger = wandb
|
| 69 |
|
| 70 |
+
# Prepare video tensors
|
| 71 |
+
observation_hat_np = observation_hat.detach().cpu().numpy()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
if observation_gt is not None:
|
| 73 |
+
observation_gt_np = observation_gt.detach().cpu().numpy()
|
| 74 |
else:
|
| 75 |
+
observation_gt_np = None
|
| 76 |
+
|
| 77 |
+
# Normalize to 0-255
|
| 78 |
+
observation_hat_np = np.transpose(np.clip(observation_hat_np, a_min=0.0, a_max=1.0) * 255, (1, 0, 2, 3, 4)).astype(np.uint8)
|
| 79 |
+
if observation_gt_np is not None:
|
| 80 |
+
observation_gt_np = np.transpose(np.clip(observation_gt_np, a_min=0.0, a_max=1.0) * 255, (1, 0, 2, 3, 4)).astype(np.uint8)
|
| 81 |
+
|
| 82 |
+
n_samples = len(observation_hat_np)
|
| 83 |
+
|
| 84 |
+
# Setup local save directory
|
| 85 |
+
if save_local:
|
| 86 |
+
if local_save_dir is None:
|
| 87 |
+
try:
|
| 88 |
+
hydra_cfg = hydra.core.hydra_config.HydraConfig.get()
|
| 89 |
+
output_dir = Path(hydra_cfg.runtime.output_dir)
|
| 90 |
+
except:
|
| 91 |
+
output_dir = Path.cwd() / "outputs"
|
| 92 |
+
local_save_dir = output_dir / "videos" / namespace
|
| 93 |
+
else:
|
| 94 |
+
local_save_dir = Path(local_save_dir)
|
| 95 |
+
|
| 96 |
+
local_save_dir.mkdir(parents=True, exist_ok=True)
|
| 97 |
+
|
| 98 |
+
# Save pred videos locally
|
| 99 |
+
pred_dir = local_save_dir / "pred"
|
| 100 |
+
pred_dir.mkdir(parents=True, exist_ok=True)
|
| 101 |
+
|
| 102 |
+
# Save gt videos locally if available
|
| 103 |
+
if observation_gt_np is not None:
|
| 104 |
+
gt_dir = local_save_dir / "gt"
|
| 105 |
+
gt_dir.mkdir(parents=True, exist_ok=True)
|
| 106 |
+
|
| 107 |
+
# Save videos
|
| 108 |
for i in range(n_samples):
|
| 109 |
+
video_pred = observation_hat_np[i] # (T, C, H, W)
|
| 110 |
+
|
| 111 |
+
if save_local:
|
| 112 |
+
# Save prediction video
|
| 113 |
+
if step is not None:
|
| 114 |
+
video_filename_pred = f"{prefix}_{i}_rank{local_rank}_step{step}.{format}"
|
| 115 |
+
else:
|
| 116 |
+
video_filename_pred = f"{prefix}_{i}_rank{local_rank}.{format}"
|
| 117 |
+
|
| 118 |
+
video_path_pred = pred_dir / video_filename_pred
|
| 119 |
+
_save_video_to_file(video_pred, str(video_path_pred), fps)
|
| 120 |
+
|
| 121 |
+
# Save ground truth video if available
|
| 122 |
+
if observation_gt_np is not None:
|
| 123 |
+
video_gt = observation_gt_np[i]
|
| 124 |
+
if step is not None:
|
| 125 |
+
video_filename_gt = f"{prefix}_{i}_rank{local_rank}_step{step}.{format}"
|
| 126 |
+
else:
|
| 127 |
+
video_filename_gt = f"{prefix}_{i}_rank{local_rank}.{format}"
|
| 128 |
+
|
| 129 |
+
video_path_gt = gt_dir / video_filename_gt
|
| 130 |
+
_save_video_to_file(video_gt, str(video_path_gt), fps)
|
| 131 |
+
|
| 132 |
+
# Log to wandb (only rank 0 to avoid duplicate logging)
|
| 133 |
+
if local_rank == 0 and logger:
|
| 134 |
+
# Concatenate pred and gt side by side for visualization
|
| 135 |
+
if observation_gt_np is not None:
|
| 136 |
+
video_combined = torch.cat([
|
| 137 |
+
torch.from_numpy(observation_hat_np),
|
| 138 |
+
torch.from_numpy(observation_gt_np)
|
| 139 |
+
], -2).numpy() # Concatenate along width
|
| 140 |
+
logger.log(
|
| 141 |
+
{
|
| 142 |
+
f"{namespace}/{prefix}_{i}": wandb.Video(video_combined[i], fps=fps, format=format),
|
| 143 |
+
f"trainer/global_step": step,
|
| 144 |
+
}
|
| 145 |
+
)
|
| 146 |
+
else:
|
| 147 |
+
logger.log(
|
| 148 |
+
{
|
| 149 |
+
f"{namespace}/{prefix}_{i}": wandb.Video(video_pred, fps=fps, format=format),
|
| 150 |
+
f"trainer/global_step": step,
|
| 151 |
+
}
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _save_video_to_file(video_tensor, output_path, fps=15):
|
| 156 |
+
"""
|
| 157 |
+
Save a video tensor to file using imageio (better compatibility than cv2).
|
| 158 |
+
|
| 159 |
+
:param video_tensor: numpy array of shape (T, C, H, W) with values in [0, 255]
|
| 160 |
+
:param output_path: path to save the video
|
| 161 |
+
:param fps: frames per second
|
| 162 |
+
"""
|
| 163 |
+
|
| 164 |
+
T, C, H, W = video_tensor.shape
|
| 165 |
+
|
| 166 |
+
# Convert from (T, C, H, W) to (T, H, W, C)
|
| 167 |
+
video_tensor = np.transpose(video_tensor, (0, 2, 3, 1))
|
| 168 |
+
|
| 169 |
+
# Ensure uint8
|
| 170 |
+
video_tensor = video_tensor.astype(np.uint8)
|
| 171 |
+
|
| 172 |
+
# Save using imageio with H.264 codec (best compatibility)
|
| 173 |
+
writer = imageio.get_writer(
|
| 174 |
+
output_path,
|
| 175 |
+
fps=fps,
|
| 176 |
+
codec='libx264', # H.264 codec - widely supported
|
| 177 |
+
quality=8, # Good quality (scale 0-10, 10 is best)
|
| 178 |
+
pixelformat='yuv420p', # Standard pixel format for compatibility
|
| 179 |
+
macro_block_size=1 # Better quality
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
for frame in video_tensor:
|
| 183 |
+
writer.append_data(frame)
|
| 184 |
+
|
| 185 |
+
writer.close()
|
| 186 |
+
|
| 187 |
+
|
| 188 |
|
| 189 |
|
| 190 |
def get_validation_metrics_for_videos(
|
|
|
|
| 193 |
lpips_model: Optional[LearnedPerceptualImagePatchSimilarity] = None,
|
| 194 |
fid_model: Optional[FrechetInceptionDistance] = None,
|
| 195 |
fvd_model: Optional[FrechetVideoDistance] = None,
|
| 196 |
+
lpips_batch_size: int = 100,
|
| 197 |
):
|
| 198 |
"""
|
| 199 |
:param observation_hat: predicted observation tensor of shape (frame, batch, channel, height, width)
|
|
|
|
| 201 |
:param lpips_model: a LearnedPerceptualImagePatchSimilarity object from algorithm.common.metrics
|
| 202 |
:param fid_model: a FrechetInceptionDistance object from algorithm.common.metrics
|
| 203 |
:param fvd_model: a FrechetVideoDistance object from algorithm.common.metrics
|
| 204 |
+
:param lpips_batch_size: batch size for LPIPS calculation to avoid OOM (default: 100)
|
| 205 |
:return: a tuple of metrics
|
| 206 |
"""
|
| 207 |
frame, batch, channel, height, width = observation_hat.shape
|
|
|
|
| 214 |
observation_hat = observation_hat.float()
|
| 215 |
observation_gt = observation_gt.float()
|
| 216 |
|
| 217 |
+
# Clip to [0, 1] range before computing metrics (matching video saving behavior)
|
| 218 |
+
observation_hat_clipped = torch.clamp(observation_hat, 0.0, 1.0)
|
| 219 |
+
observation_gt_clipped = torch.clamp(observation_gt, 0.0, 1.0)
|
|
|
|
| 220 |
|
| 221 |
+
# Compute frame-wise PSNR
|
| 222 |
frame_wise_psnr = []
|
| 223 |
+
for f in range(observation_hat_clipped.shape[0]):
|
| 224 |
+
frame_wise_psnr.append(peak_signal_noise_ratio(observation_hat_clipped[f], observation_gt_clipped[f], data_range=1.0))
|
| 225 |
frame_wise_psnr = torch.stack(frame_wise_psnr)
|
| 226 |
|
| 227 |
output_dict["frame_wise_psnr"] = frame_wise_psnr
|
| 228 |
+
observation_hat_clipped = observation_hat_clipped.view(-1, channel, height, width)
|
| 229 |
+
observation_gt_clipped = observation_gt_clipped.view(-1, channel, height, width)
|
|
|
|
|
|
|
| 230 |
|
| 231 |
+
# Compute MSE and PSNR on clipped data
|
| 232 |
+
output_dict["mse"] = mean_squared_error(observation_hat_clipped, observation_gt_clipped)
|
| 233 |
+
output_dict["psnr"] = peak_signal_noise_ratio(observation_hat_clipped, observation_gt_clipped, data_range=1.0)
|
| 234 |
+
# output_dict["ssim"] = structural_similarity_index_measure(observation_hat_clipped, observation_gt_clipped, data_range=1.0)
|
| 235 |
+
# output_dict["uiqi"] = universal_image_quality_index(observation_hat_clipped, observation_gt_clipped)
|
|
|
|
| 236 |
|
| 237 |
+
# LPIPS computation
|
| 238 |
if lpips_model is not None:
|
| 239 |
+
# Process LPIPS in batches to avoid OOM
|
| 240 |
+
num_frames = observation_hat_clipped.shape[0]
|
| 241 |
+
|
| 242 |
+
for i in range(0, num_frames, lpips_batch_size):
|
| 243 |
+
batch_end = min(i + lpips_batch_size, num_frames)
|
| 244 |
+
observation_hat_batch = observation_hat_clipped[i:batch_end]
|
| 245 |
+
observation_gt_batch = observation_gt_clipped[i:batch_end]
|
| 246 |
+
|
| 247 |
+
lpips_model.update(observation_hat_batch, observation_gt_batch)
|
| 248 |
+
|
| 249 |
+
# Free GPU memory after each batch
|
| 250 |
+
del observation_hat_batch, observation_gt_batch
|
| 251 |
+
torch.cuda.empty_cache()
|
| 252 |
+
|
| 253 |
lpips = lpips_model.compute().item()
|
| 254 |
# Reset the states of non-functional metrics
|
| 255 |
output_dict["lpips"] = lpips
|
| 256 |
lpips_model.reset()
|
| 257 |
|
| 258 |
+
# FID computation
|
| 259 |
if fid_model is not None:
|
| 260 |
+
observation_hat_uint8 = (observation_hat_clipped * 255).type(torch.uint8)
|
| 261 |
+
observation_gt_uint8 = (observation_gt_clipped * 255).type(torch.uint8)
|
| 262 |
fid_model.update(observation_gt_uint8, real=True)
|
| 263 |
fid_model.update(observation_hat_uint8, real=False)
|
| 264 |
fid = fid_model.compute()
|