backup 06_ovow_code 2026-11-08 10:30:30 (part 9)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- OVOW/third_party/Motion324/configs/dyscene.yaml +67 -0
- OVOW/third_party/Motion324/dataset/dataset_utils.py +136 -0
- OVOW/third_party/Motion324/dataset/dyscene.py +383 -0
- OVOW/third_party/Motion324/dataset/long_videos.txt +16 -0
- OVOW/third_party/Motion324/dataset/short_videos.txt +64 -0
- OVOW/third_party/Motion324/dataset/train.lst +0 -0
- OVOW/third_party/Motion324/evaluation/calculate_fvd.py +99 -0
- OVOW/third_party/Motion324/evaluation/calculate_lpips.py +219 -0
- OVOW/third_party/Motion324/evaluation/evaluation.py +274 -0
- OVOW/third_party/Motion324/evaluation/evaluation_pcd.py +940 -0
- OVOW/third_party/Motion324/evaluation/fvd/styleganv/fvd.py +90 -0
- OVOW/third_party/Motion324/evaluation/lpips/__init__.py +126 -0
- OVOW/third_party/Motion324/evaluation/lpips/lpips.py +241 -0
- OVOW/third_party/Motion324/evaluation/lpips/pretrained_networks.py +180 -0
- OVOW/third_party/Motion324/evaluation/lpips/trainer.py +280 -0
- OVOW/third_party/Motion324/experiments/checkpoints/ckpt_0000000000060000.pt +3 -0
- OVOW/third_party/Motion324/model/Pcd_motion.py +598 -0
- OVOW/third_party/Motion324/model/__init__.py +0 -0
- OVOW/third_party/Motion324/model/image_encoder/__init__.py +0 -0
- OVOW/third_party/Motion324/model/image_encoder/dino/__init__.py +0 -0
- OVOW/third_party/Motion324/model/image_encoder/dino/model_dino.py +859 -0
- OVOW/third_party/Motion324/model/image_encoder/dinov2.py +144 -0
- OVOW/third_party/Motion324/model/loss.py +66 -0
- OVOW/third_party/Motion324/model/transformer.py +423 -0
- OVOW/third_party/Motion324/pyrightconfig.json +12 -0
- OVOW/third_party/Motion324/requirements.txt +36 -0
- OVOW/third_party/Motion324/scripts/4D_from_existing.sh +71 -0
- OVOW/third_party/Motion324/scripts/4D_from_video.sh +145 -0
- OVOW/third_party/Motion324/scripts/hunyuan_Gen.py +375 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/__init__.py +13 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/rembg.py +25 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/__init__.py +17 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/pipelines.py +765 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/postprocessors.py +204 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/preprocessors.py +167 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/schedulers.py +480 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/utils.py +126 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/__init__.py +16 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/__init__.py +22 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_glb.py +241 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_obj.py +66 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/render.py +31 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/__init__.py +13 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/grid_neighbor.cpp +574 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.cpp +139 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.h +54 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer_gpu.cu +127 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/setup.py +26 -0
- OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/setup.py.hy3d +26 -0
.gitattributes
CHANGED
|
@@ -3998,3 +3998,4 @@ OVOW/engine/oneposeviagen/fpose/fpose/bundlesdf/mycuda/gridencoder.cpython-311-x
|
|
| 3998 |
OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o filter=lfs diff=lfs merge=lfs -text
|
| 3999 |
OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o filter=lfs diff=lfs merge=lfs -text
|
| 4000 |
OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/mycpp.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 3998 |
OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/Utils.cpp.o filter=lfs diff=lfs merge=lfs -text
|
| 3999 |
OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/CMakeFiles/mycpp.dir/src/app/pybind_api.cpp.o filter=lfs diff=lfs merge=lfs -text
|
| 4000 |
OVOW/engine/oneposeviagen/fpose/fpose/mycpp/build/mycpp.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 4001 |
+
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/differentiable_renderer/mesh_processor.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
OVOW/third_party/Motion324/configs/dyscene.yaml
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
class_name: model.Pcd_motion.Motion_Latent_Model
|
| 3 |
+
feat_dim: 768
|
| 4 |
+
tokens: 64
|
| 5 |
+
pcd_layers: 4
|
| 6 |
+
video_encoder:
|
| 7 |
+
image_tokenizer:
|
| 8 |
+
image_size: 224
|
| 9 |
+
patch_size: 14
|
| 10 |
+
patch_length: 1
|
| 11 |
+
in_channels: 3
|
| 12 |
+
transformer:
|
| 13 |
+
d: 768
|
| 14 |
+
d_head: 64
|
| 15 |
+
n_layer: 16
|
| 16 |
+
special_init: true
|
| 17 |
+
depth_init: true
|
| 18 |
+
use_qk_norm: true
|
| 19 |
+
|
| 20 |
+
training:
|
| 21 |
+
amp_dtype: bf16
|
| 22 |
+
api_key_path: ./configs/api_keys.yaml
|
| 23 |
+
batch_size_per_gpu: 16
|
| 24 |
+
beta1: 0.9
|
| 25 |
+
beta2: 0.95
|
| 26 |
+
allowed_gradnorm_factor: 5
|
| 27 |
+
dataset_name: dataset.dyscene.Dyscene16k_Dataset
|
| 28 |
+
dataset_path: /path/to/your/dataset
|
| 29 |
+
train_lst: dataset/train.lst
|
| 30 |
+
dataset_end: -1
|
| 31 |
+
dataset_begin: 1000
|
| 32 |
+
num_shape_samples: 4096
|
| 33 |
+
num_pcd_samples: 4096
|
| 34 |
+
replica: 1
|
| 35 |
+
frames: 12
|
| 36 |
+
grad_accum_steps: 1
|
| 37 |
+
use_checkpoint: True
|
| 38 |
+
grad_checkpoint_every: 1
|
| 39 |
+
grad_clip_norm: 1.0
|
| 40 |
+
coord_mse_loss_weight: 1.0
|
| 41 |
+
lr: 0.0004
|
| 42 |
+
num_workers: 8
|
| 43 |
+
prefetch_factor: 2
|
| 44 |
+
print_every: 20
|
| 45 |
+
use_amp: true
|
| 46 |
+
use_tf32: true
|
| 47 |
+
checkpoint_every: 10000
|
| 48 |
+
train_steps: 30000
|
| 49 |
+
stop_steps: 30000
|
| 50 |
+
warmup: 1000
|
| 51 |
+
wandb_log_every: 1
|
| 52 |
+
wandb_exp_name: test
|
| 53 |
+
wandb_project: Motion324
|
| 54 |
+
resume_ckpt: ''
|
| 55 |
+
checkpoint_dir: ./experiments/checkpoints/${training.wandb_exp_name}
|
| 56 |
+
weight_decay: 0.05
|
| 57 |
+
|
| 58 |
+
# evaluation:
|
| 59 |
+
# dataset_name: dataset.dyscene.Dyscene16k_Dataset
|
| 60 |
+
# dataset_path: /path/to/your/dataset
|
| 61 |
+
# dataset_begin: 0
|
| 62 |
+
# dataset_end: 1000
|
| 63 |
+
# batch_size_per_gpu: 8
|
| 64 |
+
# frames: 12
|
| 65 |
+
# replica: 1
|
| 66 |
+
# num_shape_samples: 4096
|
| 67 |
+
# num_pcd_samples: 4096
|
OVOW/third_party/Motion324/dataset/dataset_utils.py
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Dict, Tuple
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
import trimesh
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def load_uv_preprocessing_data(save_dir: str) -> Dict[str, np.ndarray]:
|
| 10 |
+
"""Load preprocessed UV data."""
|
| 11 |
+
|
| 12 |
+
data = np.load(save_dir)
|
| 13 |
+
return {
|
| 14 |
+
'face_uvs': data['face_uvs'],
|
| 15 |
+
'texture_array': data['texture_array']
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def sample_texture_color_vectorized(
|
| 20 |
+
uvs: np.ndarray,
|
| 21 |
+
texture_array: np.ndarray
|
| 22 |
+
) -> np.ndarray:
|
| 23 |
+
"""
|
| 24 |
+
Sample colors from texture map in batch based on UV coordinates.
|
| 25 |
+
|
| 26 |
+
Args:
|
| 27 |
+
uvs (np.ndarray): UV coordinate array with shape (N, 2).
|
| 28 |
+
texture_array (np.ndarray): Texture map with shape (H, W, 3).
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
np.ndarray: Sampled RGB color array with shape (N, 3).
|
| 32 |
+
"""
|
| 33 |
+
u, v = uvs[:, 0], uvs[:, 1]
|
| 34 |
+
|
| 35 |
+
x = (u * (texture_array.shape[1] - 1)).astype(int)
|
| 36 |
+
y = ((1 - v) * (texture_array.shape[0] - 1)).astype(int)
|
| 37 |
+
|
| 38 |
+
x = np.clip(x, 0, texture_array.shape[1] - 1)
|
| 39 |
+
y = np.clip(y, 0, texture_array.shape[0] - 1)
|
| 40 |
+
|
| 41 |
+
return texture_array[y, x]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def track_with_normal_rgb(
|
| 45 |
+
init_mesh: trimesh.Trimesh,
|
| 46 |
+
vertex_frames: np.ndarray,
|
| 47 |
+
faces: np.ndarray,
|
| 48 |
+
num_samples: int,
|
| 49 |
+
face_uvs: np.ndarray,
|
| 50 |
+
texture_array: np.ndarray
|
| 51 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, np.ndarray]:
|
| 52 |
+
"""
|
| 53 |
+
Sample points on a deforming mesh sequence and track their positions, normals, and RGB colors.
|
| 54 |
+
|
| 55 |
+
This method first samples points on the first frame (t=0) and computes their barycentric coordinates.
|
| 56 |
+
Then it uses these fixed coordinates to compute the positions of sampled points in all subsequent frames,
|
| 57 |
+
interpolated normals, and RGB colors based on UV mapping.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
init_mesh (trimesh.Trimesh): Trimesh mesh object of the first frame, used for initial sampling.
|
| 61 |
+
vertex_frames (np.ndarray): Mesh vertex sequence with shape (T, N, 3).
|
| 62 |
+
faces (np.ndarray): Mesh faces with shape (F, 3), shared across all frames.
|
| 63 |
+
num_samples (int): Number of points to sample and track.
|
| 64 |
+
face_uvs (np.ndarray): UV coordinates for three vertices of each face, with shape (F, 3, 2).
|
| 65 |
+
texture_array (np.ndarray): Texture map with shape (H, W, 3).
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 69 |
+
- tracked_points (torch.Tensor): Tracked point cloud sequence with shape (T, num_samples, 3).
|
| 70 |
+
- tracked_normals (torch.Tensor): Corresponding normal vector sequence with shape (T, num_samples, 3).
|
| 71 |
+
- tracked_rgbs (torch.Tensor): Corresponding RGB color sequence with shape (T, num_samples, 3).
|
| 72 |
+
Colors are fixed across all frames.
|
| 73 |
+
"""
|
| 74 |
+
num_frames = vertex_frames.shape[0]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
sampled_points_t0, face_indices = trimesh.sample.sample_surface(init_mesh, num_samples)
|
| 78 |
+
|
| 79 |
+
triangles_t0 = init_mesh.vertices[faces[face_indices]]
|
| 80 |
+
|
| 81 |
+
barycentric_coords = trimesh.triangles.points_to_barycentric(
|
| 82 |
+
triangles=triangles_t0, points=sampled_points_t0
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# face_uvs: (F, 3, 2) -> sampled_face_uvs: (num_samples, 3, 2)
|
| 86 |
+
sampled_face_uvs = face_uvs[face_indices]
|
| 87 |
+
|
| 88 |
+
# barycentric_coords: (num_samples, 3), sampled_face_uvs: (num_samples, 3, 2)
|
| 89 |
+
interpolated_uvs = np.einsum(
|
| 90 |
+
'ij,ijk->ik',
|
| 91 |
+
barycentric_coords,
|
| 92 |
+
sampled_face_uvs
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
tracked_rgbs_np = sample_texture_color_vectorized(interpolated_uvs, texture_array)
|
| 96 |
+
tracked_rgbs_np = tracked_rgbs_np / 255.0
|
| 97 |
+
|
| 98 |
+
all_tracked_points = []
|
| 99 |
+
all_tracked_normals = []
|
| 100 |
+
|
| 101 |
+
tracking_mesh = trimesh.Trimesh(faces=faces, process=False)
|
| 102 |
+
|
| 103 |
+
for t in range(num_frames):
|
| 104 |
+
tracking_mesh.vertices = vertex_frames[t]
|
| 105 |
+
|
| 106 |
+
current_triangles = tracking_mesh.vertices[faces[face_indices]]
|
| 107 |
+
current_points = trimesh.triangles.barycentric_to_points(current_triangles, barycentric_coords)
|
| 108 |
+
all_tracked_points.append(current_points)
|
| 109 |
+
|
| 110 |
+
vertex_normals_of_triangles = tracking_mesh.vertex_normals[faces[face_indices]]
|
| 111 |
+
|
| 112 |
+
interpolated_normals = np.einsum(
|
| 113 |
+
'ij,ijk->ik',
|
| 114 |
+
barycentric_coords,
|
| 115 |
+
vertex_normals_of_triangles
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
norms = np.linalg.norm(interpolated_normals, axis=1, keepdims=True)
|
| 119 |
+
non_zero_norms = np.where(norms == 0, 1.0, norms)
|
| 120 |
+
interpolated_normals /= non_zero_norms
|
| 121 |
+
|
| 122 |
+
all_tracked_normals.append(interpolated_normals)
|
| 123 |
+
|
| 124 |
+
tracked_points_np = np.stack(all_tracked_points, axis=0)
|
| 125 |
+
tracked_normals_np = np.stack(all_tracked_normals, axis=0)
|
| 126 |
+
|
| 127 |
+
tracked_rgbs_np_expanded = np.tile(
|
| 128 |
+
tracked_rgbs_np[np.newaxis, :, :],
|
| 129 |
+
(num_frames, 1, 1)
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
tracked_points = torch.from_numpy(tracked_points_np).float()
|
| 133 |
+
tracked_normals = torch.from_numpy(tracked_normals_np).float()
|
| 134 |
+
tracked_rgbs = torch.from_numpy(tracked_rgbs_np_expanded).float()
|
| 135 |
+
|
| 136 |
+
return tracked_points, tracked_normals, tracked_rgbs, face_indices
|
OVOW/third_party/Motion324/dataset/dyscene.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
import re
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
import trimesh
|
| 9 |
+
from torch.utils.data import Dataset
|
| 10 |
+
|
| 11 |
+
from dataset.dataset_utils import load_uv_preprocessing_data, track_with_normal_rgb
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Dyscene16k_Dataset(Dataset):
|
| 15 |
+
def __init__(self, config, pcd_subdir="pcds", transform=None):
|
| 16 |
+
"""
|
| 17 |
+
Args:
|
| 18 |
+
root_dir (string): Directory with all the .glb files, .mp4 files, and the pcd_subdir.
|
| 19 |
+
e.g., /path/to/Dataset/3d_object/dyobjs/Arti-XL/glbs/tracks/
|
| 20 |
+
pcd_subdir (string): Subdirectory under root_dir where object-named folders
|
| 21 |
+
containing .npy point clouds are located. Default is "pcds".
|
| 22 |
+
transform (callable, optional): Optional transform to be applied on a sample.
|
| 23 |
+
"""
|
| 24 |
+
self.root_dir = Path(config.dataset_path)
|
| 25 |
+
self.pcd_base_dir = self.root_dir / pcd_subdir
|
| 26 |
+
self.image_base_dir = self.root_dir / "all_images"
|
| 27 |
+
if hasattr(config, 'train_lst') and config.train_lst:
|
| 28 |
+
train_lst_path = config.train_lst
|
| 29 |
+
else:
|
| 30 |
+
train_lst_path = 'dataset/train.lst'
|
| 31 |
+
self.transform = transform
|
| 32 |
+
self.frames = config.frames
|
| 33 |
+
self.replica = config.replica
|
| 34 |
+
self.num_shape_samples = config.num_shape_samples
|
| 35 |
+
self.num_pcd_samples = config.num_pcd_samples
|
| 36 |
+
|
| 37 |
+
# Find all .glb files and derive object names all_train
|
| 38 |
+
with open(train_lst_path, 'r') as f: #valid all_unique_fliter 2kagain.lst
|
| 39 |
+
self.obj_names = [line.strip() for line in f if line.strip()]
|
| 40 |
+
|
| 41 |
+
self.obj_names = self.obj_names[config.dataset_begin:config.dataset_end]
|
| 42 |
+
|
| 43 |
+
if not self.obj_names:
|
| 44 |
+
raise RuntimeError(f"No .glb files found in {self.root_dir}")
|
| 45 |
+
|
| 46 |
+
print(f"Found {len(self.obj_names)} objects: {self.obj_names[0]}...") # Print first 5 for brevity
|
| 47 |
+
|
| 48 |
+
def __len__(self):
|
| 49 |
+
return len(self.obj_names) * self.replica
|
| 50 |
+
|
| 51 |
+
def _get_sequence_length(self, obj_name):
|
| 52 |
+
"""Get the total number of frames for a given object"""
|
| 53 |
+
# Check point cloud files
|
| 54 |
+
pcd_path = obj_name + '_pointclouds'
|
| 55 |
+
obj_pcd_dir = self.pcd_base_dir / pcd_path
|
| 56 |
+
pcd_files = []
|
| 57 |
+
if obj_pcd_dir.is_dir():
|
| 58 |
+
pcd_files = sorted(
|
| 59 |
+
list(obj_pcd_dir.glob("frame_*.npy")),
|
| 60 |
+
key=self._extract_frame_number
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Check image files
|
| 64 |
+
image_path = obj_name + '_images'
|
| 65 |
+
obj_image_dir = self.image_base_dir / image_path / 'camera_0'
|
| 66 |
+
image_files = []
|
| 67 |
+
if obj_image_dir.is_dir():
|
| 68 |
+
image_files = sorted(
|
| 69 |
+
list(obj_image_dir.glob("frame_*.jpg")) + list(obj_image_dir.glob("frame_*.png")),
|
| 70 |
+
key=self._extract_frame_number
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# Return the minimum length to ensure both modalities have data
|
| 74 |
+
return max(len(pcd_files), len(image_files)) if pcd_files and image_files else 0
|
| 75 |
+
|
| 76 |
+
def _generate_frame_indices(self, T):
|
| 77 |
+
"""Generate frame indices based on sampling strategies"""
|
| 78 |
+
if T < self.frames:
|
| 79 |
+
return None
|
| 80 |
+
|
| 81 |
+
possible_options = []
|
| 82 |
+
if T >= self.frames:
|
| 83 |
+
possible_options.append({
|
| 84 |
+
'name': 'skip1',
|
| 85 |
+
'skip_interval': 1,
|
| 86 |
+
'probability_weight': 0.4,
|
| 87 |
+
'span': self.frames
|
| 88 |
+
})
|
| 89 |
+
required_span_skip2 = (self.frames - 1) * 2 + 1
|
| 90 |
+
if T >= required_span_skip2:
|
| 91 |
+
possible_options.append({
|
| 92 |
+
'name': 'skip2',
|
| 93 |
+
'skip_interval': 2,
|
| 94 |
+
'probability_weight': 0.4,
|
| 95 |
+
'span': required_span_skip2
|
| 96 |
+
})
|
| 97 |
+
required_span_skip4 = (self.frames - 1) * 4 + 1
|
| 98 |
+
if T >= required_span_skip4:
|
| 99 |
+
possible_options.append({
|
| 100 |
+
'name': 'skip4',
|
| 101 |
+
'skip_interval': 4,
|
| 102 |
+
'probability_weight': 0.2,
|
| 103 |
+
'span': required_span_skip4
|
| 104 |
+
})
|
| 105 |
+
|
| 106 |
+
if not possible_options:
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
total_weight = sum(opt['probability_weight'] for opt in possible_options)
|
| 110 |
+
probabilities = [opt['probability_weight'] / total_weight for opt in possible_options]
|
| 111 |
+
|
| 112 |
+
chosen_opt_index = np.random.choice(len(possible_options), p=probabilities)
|
| 113 |
+
chosen_strategy = possible_options[chosen_opt_index]
|
| 114 |
+
|
| 115 |
+
skip = chosen_strategy['skip_interval']
|
| 116 |
+
span_needed = chosen_strategy['span']
|
| 117 |
+
|
| 118 |
+
max_start_idx = T - span_needed
|
| 119 |
+
if max_start_idx <= 0:
|
| 120 |
+
start_idx = np.random.randint(0, T - self.frames + 1)
|
| 121 |
+
return list(range(start_idx, start_idx + self.frames))
|
| 122 |
+
else:
|
| 123 |
+
start_idx = np.random.randint(0, max_start_idx + 1)
|
| 124 |
+
if skip == 1:
|
| 125 |
+
return list(range(start_idx, start_idx + self.frames))
|
| 126 |
+
else:
|
| 127 |
+
return [start_idx + i * skip for i in range(self.frames)]
|
| 128 |
+
|
| 129 |
+
def _load_single_image(self, image_path):
|
| 130 |
+
"""Load a single image file"""
|
| 131 |
+
try:
|
| 132 |
+
from PIL import Image
|
| 133 |
+
image = Image.open(image_path).convert('RGB')
|
| 134 |
+
# Convert to numpy array and normalize to [0, 1]
|
| 135 |
+
image_array = np.array(image).astype(np.float32) / 255.0
|
| 136 |
+
return image_array
|
| 137 |
+
except Exception as e:
|
| 138 |
+
#print(f"Warning: Could not load image {image_path}: {e}")
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
def _load_single_pointcloud(self, pcd_path):
|
| 142 |
+
"""Load a single point cloud file"""
|
| 143 |
+
try:
|
| 144 |
+
point_cloud = np.load(pcd_path)
|
| 145 |
+
return point_cloud
|
| 146 |
+
except Exception as e:
|
| 147 |
+
print(f"Warning: Could not load point cloud {pcd_path}: {e}")
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
def _extract_frame_number(self, filename):
|
| 151 |
+
"""Extracts frame number from filenames like frame_0001.npy"""
|
| 152 |
+
match = re.search(r'frame_(\d+)\.npy', filename.name)
|
| 153 |
+
if not match:
|
| 154 |
+
match = re.search(r'frame_(\d+)\.(jpg|png)', filename.name)
|
| 155 |
+
return int(match.group(1)) if match else -1
|
| 156 |
+
|
| 157 |
+
def __getitem__(self, idx):
|
| 158 |
+
if torch.is_tensor(idx):
|
| 159 |
+
idx = idx.tolist()
|
| 160 |
+
|
| 161 |
+
obj_name = self.obj_names[idx % len(self.obj_names)]
|
| 162 |
+
|
| 163 |
+
# Get total sequence length
|
| 164 |
+
T = self._get_sequence_length(obj_name)
|
| 165 |
+
|
| 166 |
+
if T < self.frames:
|
| 167 |
+
#print(f"Warning: No data found for object {obj_name}. Returning empty sample.")
|
| 168 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 169 |
+
return self[new_idx]
|
| 170 |
+
|
| 171 |
+
# Generate frame indices
|
| 172 |
+
frame_indices = self._generate_frame_indices(T)
|
| 173 |
+
|
| 174 |
+
if frame_indices is None:
|
| 175 |
+
print(f"Warning: Cannot generate valid frame indices for {obj_name} with T={T}")
|
| 176 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 177 |
+
return self[new_idx]
|
| 178 |
+
|
| 179 |
+
if len(frame_indices) != self.frames:
|
| 180 |
+
print(f"Warning: Cannot generate valid frame indices for {obj_name} with T={T}")
|
| 181 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 182 |
+
return self[new_idx]
|
| 183 |
+
|
| 184 |
+
# assert len(frame_indices) == self.frames
|
| 185 |
+
# Load images and point clouds based on frame indices
|
| 186 |
+
image_path = obj_name + '_images'
|
| 187 |
+
camera = random.choice([f'camera_{i}' for i in range(15)])
|
| 188 |
+
obj_image_dir = self.image_base_dir / image_path / camera
|
| 189 |
+
|
| 190 |
+
pcd_path = obj_name + '_pointclouds'
|
| 191 |
+
obj_pcd_dir = self.pcd_base_dir / pcd_path
|
| 192 |
+
|
| 193 |
+
faces_path = obj_pcd_dir / 'faces.npy'
|
| 194 |
+
faces_np = np.load(faces_path)
|
| 195 |
+
faces = torch.from_numpy(faces_np)
|
| 196 |
+
|
| 197 |
+
# Get sorted file lists
|
| 198 |
+
image_files = sorted(
|
| 199 |
+
list(obj_image_dir.glob("frame_*.jpg")) + list(obj_image_dir.glob("frame_*.png")),
|
| 200 |
+
key=self._extract_frame_number
|
| 201 |
+
)
|
| 202 |
+
pcd_files = sorted(
|
| 203 |
+
list(obj_pcd_dir.glob("frame_*.npy")),
|
| 204 |
+
key=self._extract_frame_number
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
# Load selected frames
|
| 208 |
+
rgb_frames = []
|
| 209 |
+
point_clouds_list = []
|
| 210 |
+
|
| 211 |
+
#assert len(frame_indices) == self.frames
|
| 212 |
+
|
| 213 |
+
for frame_idx in frame_indices:
|
| 214 |
+
# Load image
|
| 215 |
+
if frame_idx < len(image_files):
|
| 216 |
+
image_data = self._load_single_image(image_files[frame_idx])
|
| 217 |
+
if image_data is not None:
|
| 218 |
+
rgb_frames.append(image_data)
|
| 219 |
+
else:
|
| 220 |
+
#print(f"Warning: Failed to load image frame {frame_idx} for {obj_name}")
|
| 221 |
+
continue
|
| 222 |
+
else:
|
| 223 |
+
#print(f"Warning: Image frame {frame_idx} not found for {obj_name}")
|
| 224 |
+
continue
|
| 225 |
+
|
| 226 |
+
# Load point cloud
|
| 227 |
+
if frame_idx < len(pcd_files):
|
| 228 |
+
pcd_data = self._load_single_pointcloud(pcd_files[frame_idx])
|
| 229 |
+
if pcd_data is not None:
|
| 230 |
+
point_clouds_list.append(pcd_data)
|
| 231 |
+
else:
|
| 232 |
+
print(f"Warning: Failed to load point cloud frame {frame_idx} for {obj_name}")
|
| 233 |
+
continue
|
| 234 |
+
else:
|
| 235 |
+
print(f"Warning: Point cloud frame {frame_idx} not found for {obj_name}")
|
| 236 |
+
continue
|
| 237 |
+
|
| 238 |
+
if len(point_clouds_list) != self.frames or len(rgb_frames) !=self.frames:
|
| 239 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 240 |
+
return self[new_idx]
|
| 241 |
+
|
| 242 |
+
# Convert to tensors
|
| 243 |
+
video_np = np.stack(rgb_frames, axis=0).astype(np.float32)
|
| 244 |
+
vertex_np = np.stack(point_clouds_list, axis=0)
|
| 245 |
+
|
| 246 |
+
if video_np.shape[0] != vertex_np.shape[0]:
|
| 247 |
+
#print(f"Warning: video_np.shape[0] ({video_np.shape[0]}) != vertex_np.shape[0] ({vertex_np.shape[0]}), resampling for {obj_name}")
|
| 248 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 249 |
+
return self[new_idx]
|
| 250 |
+
|
| 251 |
+
uv_data_dir = obj_pcd_dir
|
| 252 |
+
data_path = os.path.join(uv_data_dir, 'uv_face_texture.npz')
|
| 253 |
+
|
| 254 |
+
if not os.path.exists(data_path):
|
| 255 |
+
print(f"Warning: UV data not found for {obj_name}")
|
| 256 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 257 |
+
return self[new_idx]
|
| 258 |
+
|
| 259 |
+
uv_data = load_uv_preprocessing_data(data_path)
|
| 260 |
+
face_uvs = uv_data['face_uvs']
|
| 261 |
+
texture_array = uv_data['texture_array']
|
| 262 |
+
|
| 263 |
+
try:
|
| 264 |
+
final_rgb_frames = torch.from_numpy(video_np).float()
|
| 265 |
+
|
| 266 |
+
ref_shape_pcd, ref_shape_normals, ref_shape_rgbs, ref_shape_face_indices = track_with_normal_rgb(
|
| 267 |
+
init_mesh=trimesh.Trimesh(vertices=vertex_np[0], faces=faces_np, process=False),
|
| 268 |
+
vertex_frames=vertex_np[0][None, ...],
|
| 269 |
+
faces=faces,
|
| 270 |
+
num_samples=self.num_shape_samples,
|
| 271 |
+
face_uvs=face_uvs,
|
| 272 |
+
texture_array=texture_array
|
| 273 |
+
)
|
| 274 |
+
ref_shape_pcd = ref_shape_pcd[0]
|
| 275 |
+
ref_shape_normals = ref_shape_normals[0]
|
| 276 |
+
ref_shape_rgbs = ref_shape_rgbs[0]
|
| 277 |
+
|
| 278 |
+
if (
|
| 279 |
+
torch.isnan(ref_shape_pcd).any() or torch.isinf(ref_shape_pcd).any() or
|
| 280 |
+
torch.isnan(ref_shape_normals).any() or torch.isinf(ref_shape_normals).any()
|
| 281 |
+
):
|
| 282 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 283 |
+
return self[new_idx]
|
| 284 |
+
|
| 285 |
+
if isinstance(faces, torch.Tensor):
|
| 286 |
+
faces = faces.cpu().numpy()
|
| 287 |
+
else:
|
| 288 |
+
faces = faces
|
| 289 |
+
|
| 290 |
+
initial_vertices = vertex_np[0]
|
| 291 |
+
initial_mesh = trimesh.Trimesh(vertices=initial_vertices, faces=faces_np, process=False)
|
| 292 |
+
|
| 293 |
+
final_point_clouds, final_point_normals, final_point_rgbs, face_indices = track_with_normal_rgb(
|
| 294 |
+
init_mesh=initial_mesh,
|
| 295 |
+
vertex_frames=vertex_np,
|
| 296 |
+
faces=faces,
|
| 297 |
+
num_samples=self.num_pcd_samples,
|
| 298 |
+
face_uvs=face_uvs,
|
| 299 |
+
texture_array=texture_array
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
if (
|
| 304 |
+
torch.isnan(final_point_clouds).any() or torch.isinf(final_point_clouds).any() or
|
| 305 |
+
torch.isnan(final_point_normals).any() or torch.isinf(final_point_normals).any()
|
| 306 |
+
):
|
| 307 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 308 |
+
return self[new_idx]
|
| 309 |
+
|
| 310 |
+
except Exception as e:
|
| 311 |
+
#print(f"Error processing object {obj_name} at index {idx}: {str(e)}. Skipping and trying a new one.")
|
| 312 |
+
new_idx = random.randint(0, len(self) - 1)
|
| 313 |
+
return self[new_idx]
|
| 314 |
+
|
| 315 |
+
sample = {
|
| 316 |
+
'obj_name': obj_name,
|
| 317 |
+
'rgb_video': final_rgb_frames,
|
| 318 |
+
'point_clouds': final_point_clouds,
|
| 319 |
+
'point_rgbs': final_point_rgbs,
|
| 320 |
+
'ref_shape_pcd': ref_shape_pcd,
|
| 321 |
+
'ref_shape_normals': ref_shape_normals,
|
| 322 |
+
'ref_shape_rgbs': ref_shape_rgbs,
|
| 323 |
+
'ref_pcd': final_point_clouds[0],
|
| 324 |
+
'ref_normal': final_point_normals[0],
|
| 325 |
+
'ref_rgb': final_point_rgbs[0],
|
| 326 |
+
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
return sample
|
| 330 |
+
|
| 331 |
+
def collate_fn_with_topology(batch):
|
| 332 |
+
"""
|
| 333 |
+
Batch processing function supporting topology information.
|
| 334 |
+
"""
|
| 335 |
+
collated = {}
|
| 336 |
+
|
| 337 |
+
tensor_keys = [
|
| 338 |
+
'rgb_video',
|
| 339 |
+
'point_clouds',
|
| 340 |
+
'point_rgbs',
|
| 341 |
+
'ref_shape_pcd',
|
| 342 |
+
'ref_shape_normals',
|
| 343 |
+
'ref_shape_rgbs',
|
| 344 |
+
'ref_pcd',
|
| 345 |
+
'ref_normal',
|
| 346 |
+
'ref_rgb',
|
| 347 |
+
]
|
| 348 |
+
|
| 349 |
+
for key in tensor_keys:
|
| 350 |
+
if key in batch[0]:
|
| 351 |
+
try:
|
| 352 |
+
collated[key] = torch.stack([item[key] for item in batch])
|
| 353 |
+
except RuntimeError as e:
|
| 354 |
+
# shapes = [item[key].shape for item in batch]
|
| 355 |
+
for i, item in enumerate(batch):
|
| 356 |
+
if item[key].shape != batch[0][key].shape:
|
| 357 |
+
expected_shape = batch[0][key].shape
|
| 358 |
+
actual_shape = item[key].shape
|
| 359 |
+
raise RuntimeError(
|
| 360 |
+
f"Shape mismatch in tensor '{key}' for object {item['obj_name']}. "
|
| 361 |
+
f"Expected {expected_shape} (from {batch[0]['obj_name']}), "
|
| 362 |
+
f"got {actual_shape}"
|
| 363 |
+
)
|
| 364 |
+
raise RuntimeError(f"Failed to stack tensor '{key}' for batch. Original error: {str(e)}")
|
| 365 |
+
|
| 366 |
+
collated['obj_name'] = [item['obj_name'] for item in batch]
|
| 367 |
+
|
| 368 |
+
edge_indices = []
|
| 369 |
+
num_nodes_offset = 0
|
| 370 |
+
num_nodes_per_sample = batch[0]['point_clouds'].size(1)
|
| 371 |
+
if 'edge_indices' in batch[0]:
|
| 372 |
+
for sample in batch:
|
| 373 |
+
edge_index_offset = sample['edge_indices'] + num_nodes_offset
|
| 374 |
+
edge_indices.append(edge_index_offset)
|
| 375 |
+
|
| 376 |
+
num_nodes_offset += num_nodes_per_sample
|
| 377 |
+
|
| 378 |
+
# final shape: (2, B * E)
|
| 379 |
+
batched_edge_index = torch.cat(edge_indices, dim=1)
|
| 380 |
+
|
| 381 |
+
collated['edge_indices'] = batched_edge_index
|
| 382 |
+
|
| 383 |
+
return collated
|
OVOW/third_party/Motion324/dataset/long_videos.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
bca5350dd54847eea333362dd7997c43-0-mixamo.com-_rootJoint
|
| 2 |
+
b1a2f41008644ce18fdd479437490045-0-Armature.002|Armature.002|mixamo.com|Layer0-_rootJoint
|
| 3 |
+
6569cdd64e104494a9afc76f769a23b8-0-mixamo.com-_rootJoint
|
| 4 |
+
01051d98271941bd971018f50e31fc2f-0-mixamo.com-_rootJoint
|
| 5 |
+
02721a2abe0e4df9851833b4c7dcd6e2-0-mixamo.com-_rootJoint
|
| 6 |
+
064d35c29ddc4e33a9c9028ef9b9bfc9-0-mixamo.com-_rootJoint
|
| 7 |
+
0b649b76d8714363b128c28f31d74153-0-mixamo.com-_rootJoint
|
| 8 |
+
0b7ec4c4e35b49f0bfb278e5424c294c-0-Main-_rootJoint
|
| 9 |
+
0e28b645254b4ff0973791a70268e4ee-0-mixamo.com-_rootJoint
|
| 10 |
+
2011f20f7a7e4442bd44630f9e7ca9a9-0-mixamo.com-_rootJoint
|
| 11 |
+
238eaf4c3a2b425ab9e848d7554d8b06-0-mixamo.com-_rootJoint
|
| 12 |
+
256e92c5fa134f128b737b6f01dc80d3-0-mixamo.com-_rootJoint
|
| 13 |
+
2691fa718007408d87e28ec916c7a400-0-mixamo.com-_rootJoint
|
| 14 |
+
329b630700cf44ff8632498a51512905-0-mixamo.com-_rootJoint
|
| 15 |
+
33bd85b5b24b4ba3b28fc455c021ff8c-0-Take 001-_rootJoint
|
| 16 |
+
36a33548949a47a896acdb4b89b01c81-0-mixamo.com-_rootJoint
|
OVOW/third_party/Motion324/dataset/short_videos.txt
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fa9f51beb7634443be3fce568b66af73-0-Roar-_rootJoint
|
| 2 |
+
d3b7ce8de999486da4651c0cb9147953-0-drunk-_rootJoint
|
| 3 |
+
604e591e0d61402095ad71302d73ff59-0-Take 001-_rootJoint
|
| 4 |
+
5f144ff373404241a4638acb61704fdc-0-Take 001-_rootJoint
|
| 5 |
+
66b977817f6a495f889cdb87e79335cf-0-CINEMA_4D_Principal-GLTF_created_0_rootJoint
|
| 6 |
+
47e7184b167144b3b14c47f20c7f7892-0-mixamo.com-_rootJoint
|
| 7 |
+
b3139fdc5465449589b023d19d39dd5e-0-Take 001-_rootJoint
|
| 8 |
+
bff251cf00374a24839c9b5ea0697c95-0-mixamo.com-_rootJoint
|
| 9 |
+
b2a9701db8b84d3a82f99d1f719af0d4-0-mixamo.com-_rootJoint
|
| 10 |
+
828017e697e64547b552aa868f045714-0-idle-_rootJoint
|
| 11 |
+
1b15161e662d49ab9ead9991500f7342-0-mixamo.com-_rootJoint
|
| 12 |
+
5ff228693ab04cdbad53d42311342b4e-0-mixamo.com-_rootJoint
|
| 13 |
+
f819d72955004cc3bfab5afedee8250a-0-Armature|ArmatureAction.001-_rootJoint
|
| 14 |
+
d0d43e2a29434a1cae0c619667c87815-0-Animation-Skeleton
|
| 15 |
+
d65a6d1e87bf444088a0e8168e34e9e0-0-Armature|ArmatureAction-Armature
|
| 16 |
+
9cda2dc67b5c4a9a88fe1550d1ee40fe-0-Armature|Walk-_rootJoint
|
| 17 |
+
00b9f134359645148c3a5113b8449d1d-0-metarig.001|metarig.001|mixamo.com|Layer0-metarig.001
|
| 18 |
+
00e7a6daedd24e429858182a334f3f88-0-mixamo.com-_rootJoint
|
| 19 |
+
01bd7226a80148e0b1dae42a298580b0-0-Take 001-_rootJoint
|
| 20 |
+
01fa8487749d4aca8ae56e673191c019-0-Take 001-walker_lfLegIkCtrl_space_switch_grp
|
| 21 |
+
045b22e7c1c249a4acd58f14d63977f3-0-mixamo.com-_rootJoint
|
| 22 |
+
075da77f55894dec9dcc38c74bf5465a-0-Armature|ArmatureAction-_rootJoint
|
| 23 |
+
088687e4034a49658f030e30d99f5601-0-dance dance-_rootJoint
|
| 24 |
+
09148d8bdff447ab84b1c10b384efe09-0-Armature|ArmatureAction-_rootJoint
|
| 25 |
+
0a4604dad8da45e18a65179a686cb98e-0-Animation-_rootJoint
|
| 26 |
+
0a7369afec3e461d8f668498e36b7707-0-Take 001-_rootJoint
|
| 27 |
+
0b871ded46ec48f295daae79cee8f0b4-0-Take 001-Plane003
|
| 28 |
+
0b9df8b7d0db4093b7a94746b55a4d88-0-mixamo.com-_rootJoint
|
| 29 |
+
0c5d13b5a1ba4b3aa0f79c3929a2f3a5-0-Win-_rootJoint
|
| 30 |
+
0c7abbb8b0e34a34bf1fb783da518664-0-mixamo.com-_rootJoint
|
| 31 |
+
0f142eaa4ab94740ba9e5d074f306a15-0-Take 001-_rootJoint
|
| 32 |
+
117fe1c12ffe44f698fe5d68f94a61ad-0-mixamo.com-_rootJoint
|
| 33 |
+
1197e9da0aca440c8d371c6a7fe2b8bb-0-jumpin-_rootJoint
|
| 34 |
+
12ad1547bf74421781481cec3dbf18ab-0-Walk-_rootJoint
|
| 35 |
+
1322ec88c4214129a37cb0a870325d2f-0-Walk_blocking-GLTF_created_0_rootJoint
|
| 36 |
+
1398503ac9c54bd89d8ec214be3f898c-0-mixamo.com-_rootJoint
|
| 37 |
+
147255b123c4419cb745c9a688f5a460-0-mixamo.com-_rootJoint
|
| 38 |
+
1646ade065cc4674891c596dd48e1b39-0-mixamo.com-_rootJoint
|
| 39 |
+
1651f10085fb4fe881c9327339c05a49-0-Take 001-_rootJoint
|
| 40 |
+
1697d86e7a2f417185a752c5303fa678-0-mixamo.com-_rootJoint
|
| 41 |
+
16f1c72703974d35957eeeabb4ff3d32-0-mixamo.com-_rootJoint
|
| 42 |
+
1711a1d0703a46baa21ede68b0743930-0-CINEMA_4D_Main-_rootJoint
|
| 43 |
+
17c607eafc3e406785013094598f8226-0-mixamo.com-_rootJoint
|
| 44 |
+
1aa28900f0474e85824085d15340ce15-0-walk-GLTF_created_0_rootJoint
|
| 45 |
+
1c092117ed114d1cad4b43f59e13fe71-0-Take 001-_rootJoint
|
| 46 |
+
1cd64f4208314981ae300cb014c19be4-0-Take 001-_rootJoint
|
| 47 |
+
1f098a7cc2744736ba13ab5bda7c74a8-0-Armature.001|Walk-_rootJoint
|
| 48 |
+
2066afa87c7240d3b74b2ee6116fe0d7-0-mixamo.com-_rootJoint
|
| 49 |
+
21154183a9b44152857bedf21b69e1e5-0-Take 001-_rootJoint
|
| 50 |
+
21507e49b8f3404ea5ac5ffb000bb176-0-ArmatureAction-Armature_rootJoint
|
| 51 |
+
21c898fa071b4414a8c1fd2ea4773b43-0-walk-_rootJoint
|
| 52 |
+
25015f5f3ac64d2dac358f8c17af5128-0-walk-GLTF_created_0_rootJoint
|
| 53 |
+
2611cb5fc0e048bdbb421b142d4ca7f5-0-mixamo.com-_rootJoint
|
| 54 |
+
2932fca2b6bf428ab38944efb12209a1-0-angry talk-_rootJoint
|
| 55 |
+
2b75f50d68084580b16d5986139c407a-0-mixamo.com-_rootJoint
|
| 56 |
+
2d0701a199924a9ca36e76759ceaeea6-0-Take 01-galinha_esqueleto
|
| 57 |
+
2ed510f819b7483198db65f5fcd156cd-0-Attack-_rootJoint
|
| 58 |
+
2efd5252155048499a1fe725462dc77f-0-mixamo.com-Armature
|
| 59 |
+
2f98af6aeee24e1f8225883e52e78425-0-CINEMA_4D_Main-Root_Anim_Hat
|
| 60 |
+
3279369cb5a04838a859bd69823d545c-0-Walking-GLTF_created_0_rootJoint
|
| 61 |
+
32f1d70cbdfa4b0e8cf81e91618df201-0-������Action-GLTF_created_0_rootJoint
|
| 62 |
+
330015cf2cca49f3a84276975eb2687d-0-Take 001-_rootJoint
|
| 63 |
+
34fe9318855d4f9ea80d121dd28cc890-0-Runway_Walk-_rootJoint
|
| 64 |
+
35689c8c52d54f9bbf4a0a789f407469-0-Idle-_rootJoint
|
OVOW/third_party/Motion324/dataset/train.lst
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
OVOW/third_party/Motion324/evaluation/calculate_fvd.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
|
| 5 |
+
def trans(x):
|
| 6 |
+
# if greyscale images add channel
|
| 7 |
+
if x.shape[-3] == 1:
|
| 8 |
+
x = x.repeat(1, 1, 3, 1, 1)
|
| 9 |
+
|
| 10 |
+
# permute BTCHW -> BCTHW
|
| 11 |
+
x = x.permute(0, 2, 1, 3, 4)
|
| 12 |
+
|
| 13 |
+
return x
|
| 14 |
+
|
| 15 |
+
def calculate_fvd(videos1, videos2, device, method='styleganv', only_final=False, i3d_model=None):
|
| 16 |
+
|
| 17 |
+
from fvd.styleganv.fvd import get_fvd_feats, frechet_distance, load_i3d_pretrained
|
| 18 |
+
|
| 19 |
+
print("calculate_fvd...")
|
| 20 |
+
|
| 21 |
+
# videos [batch_size, timestamps, channel, h, w]
|
| 22 |
+
|
| 23 |
+
assert videos1.shape == videos2.shape
|
| 24 |
+
|
| 25 |
+
# Only load model if not provided
|
| 26 |
+
if i3d_model is None:
|
| 27 |
+
i3d = load_i3d_pretrained(device=device)
|
| 28 |
+
else:
|
| 29 |
+
i3d = i3d_model
|
| 30 |
+
|
| 31 |
+
fvd_results = []
|
| 32 |
+
|
| 33 |
+
# support grayscale input, if grayscale -> channel*3
|
| 34 |
+
# BTCHW -> BCTHW
|
| 35 |
+
# videos -> [batch_size, channel, timestamps, h, w]
|
| 36 |
+
|
| 37 |
+
videos1 = trans(videos1)
|
| 38 |
+
videos2 = trans(videos2)
|
| 39 |
+
|
| 40 |
+
fvd_results = []
|
| 41 |
+
|
| 42 |
+
if only_final:
|
| 43 |
+
|
| 44 |
+
assert videos1.shape[2] >= 10, "for calculate FVD, each clip_timestamp must >= 10"
|
| 45 |
+
|
| 46 |
+
# videos_clip [batch_size, channel, timestamps, h, w]
|
| 47 |
+
videos_clip1 = videos1
|
| 48 |
+
videos_clip2 = videos2
|
| 49 |
+
|
| 50 |
+
# get FVD features
|
| 51 |
+
feats1 = get_fvd_feats(videos_clip1, i3d=i3d, device=device)
|
| 52 |
+
feats2 = get_fvd_feats(videos_clip2, i3d=i3d, device=device)
|
| 53 |
+
|
| 54 |
+
# calculate FVD
|
| 55 |
+
fvd_results.append(frechet_distance(feats1, feats2))
|
| 56 |
+
|
| 57 |
+
else:
|
| 58 |
+
|
| 59 |
+
# for calculate FVD, each clip_timestamp must >= 10
|
| 60 |
+
for clip_timestamp in tqdm(range(10, videos1.shape[-3]+1)):
|
| 61 |
+
|
| 62 |
+
# get a video clip
|
| 63 |
+
# videos_clip [batch_size, channel, timestamps[:clip], h, w]
|
| 64 |
+
videos_clip1 = videos1[:, :, : clip_timestamp]
|
| 65 |
+
videos_clip2 = videos2[:, :, : clip_timestamp]
|
| 66 |
+
|
| 67 |
+
# get FVD features
|
| 68 |
+
feats1 = get_fvd_feats(videos_clip1, i3d=i3d, device=device)
|
| 69 |
+
feats2 = get_fvd_feats(videos_clip2, i3d=i3d, device=device)
|
| 70 |
+
|
| 71 |
+
# calculate FVD when timestamps[:clip]
|
| 72 |
+
fvd_results.append(frechet_distance(feats1, feats2))
|
| 73 |
+
|
| 74 |
+
result = {
|
| 75 |
+
"value": fvd_results,
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
return result
|
| 79 |
+
|
| 80 |
+
# test code / using example
|
| 81 |
+
|
| 82 |
+
def main():
|
| 83 |
+
NUMBER_OF_VIDEOS = 8
|
| 84 |
+
VIDEO_LENGTH = 30
|
| 85 |
+
CHANNEL = 3
|
| 86 |
+
SIZE = 64
|
| 87 |
+
videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
|
| 88 |
+
videos2 = torch.ones(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
|
| 89 |
+
device = torch.device("cuda")
|
| 90 |
+
# device = torch.device("cpu")
|
| 91 |
+
|
| 92 |
+
result = calculate_fvd(videos1, videos2, device, method='videogpt', only_final=False)
|
| 93 |
+
print("[fvd-videogpt ]", result["value"])
|
| 94 |
+
|
| 95 |
+
result = calculate_fvd(videos1, videos2, device, method='styleganv', only_final=False)
|
| 96 |
+
print("[fvd-styleganv]", result["value"])
|
| 97 |
+
|
| 98 |
+
if __name__ == "__main__":
|
| 99 |
+
main()
|
OVOW/third_party/Motion324/evaluation/calculate_lpips.py
ADDED
|
@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
from tqdm import tqdm
|
| 4 |
+
import math
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import lpips
|
| 8 |
+
|
| 9 |
+
# ignore torchvision UserWarning of 'weights'
|
| 10 |
+
import warnings
|
| 11 |
+
warnings.filterwarnings("ignore")
|
| 12 |
+
|
| 13 |
+
spatial = True # Return a spatial map of perceptual distance.
|
| 14 |
+
|
| 15 |
+
# Linearly calibrated models (LPIPS)
|
| 16 |
+
loss_fn = lpips.LPIPS(net='vgg', spatial=spatial) # Can also set net = 'squeeze' or 'vgg'
|
| 17 |
+
# loss_fn = lpips.LPIPS(net='alex', spatial=spatial, lpips=False) # Can also set net = 'squeeze' or 'vgg'
|
| 18 |
+
|
| 19 |
+
def trans(x):
|
| 20 |
+
# if greyscale images add channel
|
| 21 |
+
if x.shape[-3] == 1:
|
| 22 |
+
x = x.repeat(1, 1, 3, 1, 1)
|
| 23 |
+
|
| 24 |
+
# value range [0, 1] -> [-1, 1]
|
| 25 |
+
x = x * 2 - 1
|
| 26 |
+
|
| 27 |
+
return x
|
| 28 |
+
|
| 29 |
+
import open_clip
|
| 30 |
+
|
| 31 |
+
from dreamsim import dreamsim
|
| 32 |
+
from torchvision import transforms
|
| 33 |
+
|
| 34 |
+
def calculate_dreamsim_loss(videos1, videos2, device, only_final=False, dreamsim_model=None):
|
| 35 |
+
print("calculate_dreamsim_loss...")
|
| 36 |
+
|
| 37 |
+
assert videos1.shape == videos2.shape
|
| 38 |
+
|
| 39 |
+
# Only load model if not provided
|
| 40 |
+
if dreamsim_model is None:
|
| 41 |
+
dreamsim_model, _ = dreamsim(pretrained=True, device=device)
|
| 42 |
+
|
| 43 |
+
transform = transforms.Compose([
|
| 44 |
+
transforms.Resize((224, 224)),
|
| 45 |
+
transforms.ToTensor()
|
| 46 |
+
])
|
| 47 |
+
|
| 48 |
+
dreamsim_loss_results = []
|
| 49 |
+
|
| 50 |
+
for video_num in tqdm(range(videos1.shape[0])):
|
| 51 |
+
video1 = videos1[video_num]
|
| 52 |
+
video2 = videos2[video_num]
|
| 53 |
+
|
| 54 |
+
dreamsim_loss_results_of_a_video = []
|
| 55 |
+
for clip_timestamp in range(len(video1)):
|
| 56 |
+
img1 = transforms.Resize((224, 224))(video1[clip_timestamp])
|
| 57 |
+
img2 = transforms.Resize((224, 224))(video2[clip_timestamp])
|
| 58 |
+
|
| 59 |
+
img1_tensor = img1.unsqueeze(0).to(device)
|
| 60 |
+
img2_tensor = img2.unsqueeze(0).to(device)
|
| 61 |
+
|
| 62 |
+
loss = dreamsim_model(img1_tensor, img2_tensor).item()
|
| 63 |
+
|
| 64 |
+
dreamsim_loss_results_of_a_video.append(loss)
|
| 65 |
+
|
| 66 |
+
dreamsim_loss_results.append(dreamsim_loss_results_of_a_video)
|
| 67 |
+
|
| 68 |
+
dreamsim_loss_results = np.array(dreamsim_loss_results)
|
| 69 |
+
|
| 70 |
+
dreamsim_loss = []
|
| 71 |
+
dreamsim_loss_std = []
|
| 72 |
+
|
| 73 |
+
if only_final:
|
| 74 |
+
dreamsim_loss.append(np.mean(dreamsim_loss_results))
|
| 75 |
+
dreamsim_loss_std.append(np.std(dreamsim_loss_results))
|
| 76 |
+
else:
|
| 77 |
+
for clip_timestamp in range(len(video1)):
|
| 78 |
+
dreamsim_loss.append(np.mean(dreamsim_loss_results[:, clip_timestamp]))
|
| 79 |
+
dreamsim_loss_std.append(np.std(dreamsim_loss_results[:, clip_timestamp]))
|
| 80 |
+
|
| 81 |
+
result = {
|
| 82 |
+
"value": dreamsim_loss,
|
| 83 |
+
"value_std": dreamsim_loss_std,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
# return mean for each video
|
| 87 |
+
return result, dreamsim_loss_results.mean(axis=1)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def calculate_clip_loss(videos1, videos2, device, only_final=False, clip_model=None, clip_preprocess=None):
|
| 91 |
+
print("Calculating CLIP loss with OpenCLIP's best model...")
|
| 92 |
+
|
| 93 |
+
assert videos1.shape == videos2.shape, "Input videos must have the same shape."
|
| 94 |
+
|
| 95 |
+
# Only load model if not provided
|
| 96 |
+
if clip_model is None or clip_preprocess is None:
|
| 97 |
+
model, _, preprocess = open_clip.create_model_and_transforms("ViT-bigG-14", pretrained="laion2B_s39B_b160k")
|
| 98 |
+
model = model.to(device).eval()
|
| 99 |
+
else:
|
| 100 |
+
model = clip_model
|
| 101 |
+
preprocess = clip_preprocess
|
| 102 |
+
|
| 103 |
+
clip_loss_results = []
|
| 104 |
+
|
| 105 |
+
for video_num in tqdm(range(videos1.shape[0])):
|
| 106 |
+
video1 = videos1[video_num]
|
| 107 |
+
video2 = videos2[video_num]
|
| 108 |
+
|
| 109 |
+
clip_loss_results_of_a_video = []
|
| 110 |
+
for clip_timestamp in range(len(video1)):
|
| 111 |
+
img1 = video1[clip_timestamp].cpu()
|
| 112 |
+
img2 = video2[clip_timestamp].cpu()
|
| 113 |
+
|
| 114 |
+
# Convert numpy images to PIL images for preprocessing
|
| 115 |
+
img1 = preprocess(transforms.ToPILImage()(torch.tensor(img1)))
|
| 116 |
+
img2 = preprocess(transforms.ToPILImage()(torch.tensor(img2)))
|
| 117 |
+
|
| 118 |
+
# Stack and move to device
|
| 119 |
+
images = torch.stack([img1, img2]).to(device)
|
| 120 |
+
|
| 121 |
+
# Compute image features
|
| 122 |
+
with torch.no_grad():
|
| 123 |
+
image_features = model.encode_image(images)
|
| 124 |
+
image_features = torch.nn.functional.normalize(image_features, dim=-1)
|
| 125 |
+
|
| 126 |
+
# Compute cosine similarity
|
| 127 |
+
similarity = torch.cosine_similarity(image_features[0], image_features[1], dim=0)
|
| 128 |
+
clip_loss_results_of_a_video.append(similarity.cpu().item())
|
| 129 |
+
|
| 130 |
+
clip_loss_results.append(clip_loss_results_of_a_video)
|
| 131 |
+
|
| 132 |
+
clip_loss_results = np.array(clip_loss_results)
|
| 133 |
+
clip_loss = np.mean(clip_loss_results, axis=0) if not only_final else [np.mean(clip_loss_results)]
|
| 134 |
+
clip_loss_std = np.std(clip_loss_results, axis=0) if not only_final else [np.std(clip_loss_results)]
|
| 135 |
+
|
| 136 |
+
return {"value": clip_loss, "value_std": clip_loss_std}, clip_loss_results.mean(axis=1)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def calculate_lpips(videos1, videos2, device, only_final=False, lpips_model=None):
|
| 140 |
+
# image should be RGB, IMPORTANT: normalized to [-1,1]
|
| 141 |
+
print("calculate_lpips...")
|
| 142 |
+
|
| 143 |
+
assert videos1.shape == videos2.shape
|
| 144 |
+
|
| 145 |
+
# videos [batch_size, timestamps, channel, h, w]
|
| 146 |
+
|
| 147 |
+
# support grayscale input, if grayscale -> channel*3
|
| 148 |
+
# value range [0, 1] -> [-1, 1]
|
| 149 |
+
videos1 = trans(videos1)
|
| 150 |
+
videos2 = trans(videos2)
|
| 151 |
+
|
| 152 |
+
lpips_results = []
|
| 153 |
+
|
| 154 |
+
# Use provided model or global loss_fn
|
| 155 |
+
if lpips_model is None:
|
| 156 |
+
lpips_model = loss_fn
|
| 157 |
+
|
| 158 |
+
lpips_model.to(device)
|
| 159 |
+
|
| 160 |
+
for video_num in tqdm(range(videos1.shape[0])):
|
| 161 |
+
# get a video
|
| 162 |
+
# video [timestamps, channel, h, w]
|
| 163 |
+
video1 = videos1[video_num]
|
| 164 |
+
video2 = videos2[video_num]
|
| 165 |
+
|
| 166 |
+
lpips_results_of_a_video = []
|
| 167 |
+
for clip_timestamp in range(len(video1)):
|
| 168 |
+
# get a img
|
| 169 |
+
# img [timestamps[x], channel, h, w]
|
| 170 |
+
# img [channel, h, w] tensor
|
| 171 |
+
|
| 172 |
+
img1 = video1[clip_timestamp].unsqueeze(0).to(device)
|
| 173 |
+
img2 = video2[clip_timestamp].unsqueeze(0).to(device)
|
| 174 |
+
|
| 175 |
+
# calculate lpips of a video
|
| 176 |
+
lpips_results_of_a_video.append(lpips_model.forward(img1, img2).mean().detach().cpu().tolist())
|
| 177 |
+
lpips_results.append(lpips_results_of_a_video)
|
| 178 |
+
|
| 179 |
+
lpips_results = np.array(lpips_results)
|
| 180 |
+
|
| 181 |
+
lpips = []
|
| 182 |
+
lpips_std = []
|
| 183 |
+
|
| 184 |
+
if only_final:
|
| 185 |
+
|
| 186 |
+
lpips.append(np.mean(lpips_results))
|
| 187 |
+
lpips_std.append(np.std(lpips_results))
|
| 188 |
+
|
| 189 |
+
else:
|
| 190 |
+
|
| 191 |
+
for clip_timestamp in range(len(video1)):
|
| 192 |
+
lpips.append(np.mean(lpips_results[:,clip_timestamp]))
|
| 193 |
+
lpips_std.append(np.std(lpips_results[:,clip_timestamp]))
|
| 194 |
+
|
| 195 |
+
result = {
|
| 196 |
+
"value": lpips,
|
| 197 |
+
"value_std": lpips_std,
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
return result, lpips_results.mean(axis=1)
|
| 201 |
+
|
| 202 |
+
# test code / using example
|
| 203 |
+
|
| 204 |
+
def main():
|
| 205 |
+
NUMBER_OF_VIDEOS = 8
|
| 206 |
+
VIDEO_LENGTH = 30
|
| 207 |
+
CHANNEL = 3
|
| 208 |
+
SIZE = 64
|
| 209 |
+
videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
|
| 210 |
+
videos2 = torch.ones(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
|
| 211 |
+
device = torch.device("cuda")
|
| 212 |
+
# device = torch.device("cpu")
|
| 213 |
+
|
| 214 |
+
result = calculate_lpips(videos1, videos2, device)
|
| 215 |
+
print("[lpips avg]", result["value"])
|
| 216 |
+
print("[lpips std]", result["value_std"])
|
| 217 |
+
|
| 218 |
+
if __name__ == "__main__":
|
| 219 |
+
main()
|
OVOW/third_party/Motion324/evaluation/evaluation.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 8 |
+
from calculate_lpips import calculate_lpips, calculate_dreamsim_loss, calculate_clip_loss
|
| 9 |
+
import argparse
|
| 10 |
+
from glob import glob
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import lpips
|
| 13 |
+
import open_clip
|
| 14 |
+
from dreamsim import dreamsim
|
| 15 |
+
|
| 16 |
+
# Constants
|
| 17 |
+
FRAME_SIZE = 512 # Resize all frames to 512x512
|
| 18 |
+
TIMESTAMP_LIMIT = 32 # Split videos into 32-frame subvideos
|
| 19 |
+
|
| 20 |
+
# Define transformation
|
| 21 |
+
transform = transforms.Compose([
|
| 22 |
+
transforms.ToPILImage(),
|
| 23 |
+
transforms.Resize((FRAME_SIZE, FRAME_SIZE)),
|
| 24 |
+
transforms.ToTensor() # Converts to [0,1] range
|
| 25 |
+
])
|
| 26 |
+
|
| 27 |
+
def load_video_as_tensor(video_path):
|
| 28 |
+
"""Load a video and convert it into a tensor [timestamp, channel, width, height]."""
|
| 29 |
+
cap = cv2.VideoCapture(video_path)
|
| 30 |
+
frames = []
|
| 31 |
+
|
| 32 |
+
while cap.isOpened():
|
| 33 |
+
ret, frame = cap.read()
|
| 34 |
+
if not ret:
|
| 35 |
+
break
|
| 36 |
+
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
|
| 37 |
+
frame = transform(frame) # Resize & normalize
|
| 38 |
+
frames.append(frame)
|
| 39 |
+
|
| 40 |
+
cap.release()
|
| 41 |
+
|
| 42 |
+
#if len(frames) < TIMESTAMP_LIMIT:
|
| 43 |
+
# return None # Ignore videos with fewer than 32 frames
|
| 44 |
+
|
| 45 |
+
video_tensor = torch.stack(frames) # Shape: [timestamp, channel, width, height]
|
| 46 |
+
return video_tensor
|
| 47 |
+
|
| 48 |
+
def load_images_as_tensor(image_dir):
|
| 49 |
+
"""Load images from a directory and convert them into a tensor [timestamp, channel, width, height]."""
|
| 50 |
+
# Find all image files (png, jpg, jpeg)
|
| 51 |
+
image_files = sorted(glob(os.path.join(image_dir, "*.png")) +
|
| 52 |
+
glob(os.path.join(image_dir, "*.jpg")) +
|
| 53 |
+
glob(os.path.join(image_dir, "*.jpeg")))
|
| 54 |
+
|
| 55 |
+
#if len(image_files) < TIMESTAMP_LIMIT:
|
| 56 |
+
# return None # Ignore if fewer than required frames
|
| 57 |
+
|
| 58 |
+
frames = []
|
| 59 |
+
for img_path in image_files:
|
| 60 |
+
img = Image.open(img_path).convert('RGB')
|
| 61 |
+
img_array = np.array(img)
|
| 62 |
+
frame = transform(img_array) # Resize & normalize
|
| 63 |
+
frames.append(frame)
|
| 64 |
+
|
| 65 |
+
video_tensor = torch.stack(frames) # Shape: [timestamp, channel, width, height]
|
| 66 |
+
return video_tensor
|
| 67 |
+
|
| 68 |
+
def is_video_file(path):
|
| 69 |
+
"""Check if path is a video file"""
|
| 70 |
+
video_extensions = ['.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm']
|
| 71 |
+
return os.path.isfile(path) and any(path.lower().endswith(ext) for ext in video_extensions)
|
| 72 |
+
|
| 73 |
+
def load_input(path):
|
| 74 |
+
"""Load input from video file or image directory"""
|
| 75 |
+
if is_video_file(path):
|
| 76 |
+
return load_video_as_tensor(path)
|
| 77 |
+
elif os.path.isdir(path):
|
| 78 |
+
return load_images_as_tensor(path)
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f"Path {path} is neither a video file nor a directory")
|
| 81 |
+
|
| 82 |
+
def get_frame_count(path):
|
| 83 |
+
"""Get frame count from video file or image directory"""
|
| 84 |
+
if is_video_file(path):
|
| 85 |
+
cap = cv2.VideoCapture(path)
|
| 86 |
+
count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 87 |
+
cap.release()
|
| 88 |
+
return count
|
| 89 |
+
elif os.path.isdir(path):
|
| 90 |
+
image_files = sorted(glob(os.path.join(path, "*.png")) +
|
| 91 |
+
glob(os.path.join(path, "*.jpg")) +
|
| 92 |
+
glob(os.path.join(path, "*.jpeg")))
|
| 93 |
+
return len(image_files)
|
| 94 |
+
else:
|
| 95 |
+
return 0
|
| 96 |
+
|
| 97 |
+
def process_single_video(video_path_or_dir):
|
| 98 |
+
"""Load a single video/image directory and convert it into a tensor [timestamp, channel, width, height]."""
|
| 99 |
+
tensor = load_input(video_path_or_dir)
|
| 100 |
+
if tensor.shape[0] == 0:
|
| 101 |
+
raise ValueError(f"Input {video_path_or_dir} has no frames")
|
| 102 |
+
# If video has fewer frames than TIMESTAMP_LIMIT, pad by repeating the last frame
|
| 103 |
+
if tensor.shape[0] < TIMESTAMP_LIMIT:
|
| 104 |
+
num_frames_needed = TIMESTAMP_LIMIT - tensor.shape[0]
|
| 105 |
+
# Take the last num_frames_needed frames and reverse them for padding
|
| 106 |
+
padding = tensor[-num_frames_needed:].flip(0) # Reverse the last num_frames_needed frames
|
| 107 |
+
tensor = torch.cat([tensor, padding], dim=0) # Concatenate along timestamp dimension
|
| 108 |
+
print(f"Input {video_path_or_dir} padded from {tensor.shape[0] - num_frames_needed} to {tensor.shape[0]} frames")
|
| 109 |
+
# Split into 32-frame subvideos
|
| 110 |
+
subvideos = [tensor[i:i+TIMESTAMP_LIMIT] for i in range(0, tensor.shape[0] - TIMESTAMP_LIMIT + 1, TIMESTAMP_LIMIT)]
|
| 111 |
+
print(f"Loaded {len(subvideos)} subvideos from {video_path_or_dir}")
|
| 112 |
+
|
| 113 |
+
# Stack into batch: [batch, timestamp, channel, width, height]
|
| 114 |
+
return torch.stack(subvideos)
|
| 115 |
+
|
| 116 |
+
parser = argparse.ArgumentParser(description="Evaluate video metrics between videos/images.")
|
| 117 |
+
parser.add_argument('--gt_paths', type=str, required=True, nargs='+', help='Path(s) to ground truth video(s) or image directory(ies)')
|
| 118 |
+
parser.add_argument('--result_paths', type=str, required=True, nargs='+', help='Path(s) to generated/result video(s) or image directory(ies)')
|
| 119 |
+
parser.add_argument('--output_dir', type=str, default=None, help='Directory to save results (optional)')
|
| 120 |
+
args = parser.parse_args()
|
| 121 |
+
|
| 122 |
+
gt_paths = args.gt_paths
|
| 123 |
+
result_paths = args.result_paths
|
| 124 |
+
output_dir = args.output_dir
|
| 125 |
+
|
| 126 |
+
# Ensure same number of paths
|
| 127 |
+
if len(gt_paths) != len(result_paths):
|
| 128 |
+
raise ValueError(f"Number of GT paths ({len(gt_paths)}) must match number of result paths ({len(result_paths)})")
|
| 129 |
+
|
| 130 |
+
# Move tensors to device
|
| 131 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 132 |
+
|
| 133 |
+
# Load all models once before the loop
|
| 134 |
+
print("Loading all models...")
|
| 135 |
+
print(" - Loading LPIPS model...")
|
| 136 |
+
lpips_model = lpips.LPIPS(net='vgg', spatial=True)
|
| 137 |
+
lpips_model = lpips_model.to(device)
|
| 138 |
+
|
| 139 |
+
print(" - Loading I3D model for FVD...")
|
| 140 |
+
from fvd.styleganv.fvd import load_i3d_pretrained
|
| 141 |
+
i3d_model = load_i3d_pretrained(device=device)
|
| 142 |
+
|
| 143 |
+
print(" - Loading DreamSim model...")
|
| 144 |
+
dreamsim_model, _ = dreamsim(pretrained=True, device=device)
|
| 145 |
+
|
| 146 |
+
print(" - Loading OpenCLIP model...")
|
| 147 |
+
clip_model, _, clip_preprocess = open_clip.create_model_and_transforms("ViT-bigG-14", pretrained="laion2B_s39B_b160k")
|
| 148 |
+
clip_model = clip_model.to(device).eval()
|
| 149 |
+
|
| 150 |
+
print("All models loaded successfully!\n")
|
| 151 |
+
|
| 152 |
+
# Create output directory if specified
|
| 153 |
+
if output_dir:
|
| 154 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 155 |
+
|
| 156 |
+
# Process each pair of paths
|
| 157 |
+
all_results = []
|
| 158 |
+
for idx, (gt_path, result_path) in enumerate(zip(gt_paths, result_paths)):
|
| 159 |
+
print(f"\n{'='*60}")
|
| 160 |
+
print(f"Processing pair {idx+1}/{len(gt_paths)}")
|
| 161 |
+
print(f"{'='*60}")
|
| 162 |
+
|
| 163 |
+
# Check if paths exist
|
| 164 |
+
if not os.path.exists(gt_path):
|
| 165 |
+
print(f"Warning: GT path not found at {gt_path}, skipping...")
|
| 166 |
+
continue
|
| 167 |
+
if not os.path.exists(result_path):
|
| 168 |
+
print(f"Warning: Result path not found at {result_path}, skipping...")
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
print(f"GT: {gt_path}")
|
| 172 |
+
print(f"Result: {result_path}")
|
| 173 |
+
|
| 174 |
+
try:
|
| 175 |
+
# Get frame counts
|
| 176 |
+
gt_frame_count = get_frame_count(gt_path)
|
| 177 |
+
result_frame_count = get_frame_count(result_path)
|
| 178 |
+
|
| 179 |
+
if gt_frame_count == 0:
|
| 180 |
+
print(f"Warning: GT path {gt_path} has no frames, skipping...")
|
| 181 |
+
continue
|
| 182 |
+
if result_frame_count == 0:
|
| 183 |
+
print(f"Warning: Result path {result_path} has no frames, skipping...")
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
if gt_frame_count != result_frame_count:
|
| 187 |
+
print(f"Warning: Frame count mismatch: GT has {gt_frame_count} frames, but result has {result_frame_count} frames.")
|
| 188 |
+
|
| 189 |
+
print(f"GT has {gt_frame_count} frames")
|
| 190 |
+
print(f"Result has {result_frame_count} frames")
|
| 191 |
+
print(f"Processing...")
|
| 192 |
+
|
| 193 |
+
videos1 = process_single_video(gt_path)
|
| 194 |
+
videos2 = process_single_video(result_path)
|
| 195 |
+
|
| 196 |
+
# Compute metrics
|
| 197 |
+
only_final = True
|
| 198 |
+
|
| 199 |
+
print("Computing metrics...")
|
| 200 |
+
lpips_result, lpips_eachvideo = calculate_lpips(videos1, videos2, device, only_final=only_final, lpips_model=lpips_model)
|
| 201 |
+
fvd_result = calculate_fvd(videos1, videos2, device, method='styleganv', only_final=only_final, i3d_model=i3d_model)
|
| 202 |
+
dreamsim_result, dreamsim_eachvideo = calculate_dreamsim_loss(videos1, videos2, device, only_final=only_final, dreamsim_model=dreamsim_model)
|
| 203 |
+
clip_loss_result, clip_loss_eachvideo = calculate_clip_loss(videos1, videos2, device, only_final=only_final, clip_model=clip_model, clip_preprocess=clip_preprocess)
|
| 204 |
+
|
| 205 |
+
# Extract scalar values from result dictionaries
|
| 206 |
+
# When only_final=True, value is a list with single element
|
| 207 |
+
fvd_value = fvd_result['value'][0] if isinstance(fvd_result['value'], list) else fvd_result['value']
|
| 208 |
+
lpips_value = lpips_result['value'][0] if isinstance(lpips_result['value'], list) else lpips_result['value']
|
| 209 |
+
dreamsim_value = dreamsim_result['value'][0] if isinstance(dreamsim_result['value'], list) else dreamsim_result['value']
|
| 210 |
+
clip_loss_value = clip_loss_result['value'] if isinstance(clip_loss_result['value'], (int, float)) else clip_loss_result['value'][0]
|
| 211 |
+
|
| 212 |
+
result = {
|
| 213 |
+
'gt_path': gt_path,
|
| 214 |
+
'result_path': result_path,
|
| 215 |
+
'fvd': fvd_value,
|
| 216 |
+
'lpips': lpips_value,
|
| 217 |
+
'dreamsim': dreamsim_value,
|
| 218 |
+
'clip_loss': clip_loss_value,
|
| 219 |
+
}
|
| 220 |
+
all_results.append(result)
|
| 221 |
+
|
| 222 |
+
# Print results
|
| 223 |
+
print(f"\nResults:")
|
| 224 |
+
print(json.dumps({k: v for k, v in result.items() if k not in ['gt_path', 'result_path']}, indent=4))
|
| 225 |
+
|
| 226 |
+
# Save results to file
|
| 227 |
+
# Default: save to result_path's dirname with basename.txt
|
| 228 |
+
result_basename = os.path.basename(result_path.rstrip('/'))
|
| 229 |
+
# Remove extension if it's a file
|
| 230 |
+
if os.path.isfile(result_path):
|
| 231 |
+
result_basename = os.path.splitext(result_basename)[0]
|
| 232 |
+
|
| 233 |
+
if output_dir:
|
| 234 |
+
# If output_dir is specified, save there
|
| 235 |
+
output_file = os.path.join(output_dir, f'{result_basename}.txt')
|
| 236 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 237 |
+
else:
|
| 238 |
+
# Otherwise, save to result_path's directory
|
| 239 |
+
result_dir = os.path.dirname(result_path)
|
| 240 |
+
if result_dir:
|
| 241 |
+
output_file = os.path.join(result_dir, f'{result_basename}.txt')
|
| 242 |
+
os.makedirs(result_dir, exist_ok=True)
|
| 243 |
+
else:
|
| 244 |
+
# If result_path has no dirname (current directory), save to current directory
|
| 245 |
+
output_file = f'{result_basename}.txt'
|
| 246 |
+
with open(output_file, 'w') as f:
|
| 247 |
+
f.write(f"GT Source: {gt_path}\n")
|
| 248 |
+
f.write(f"Result Source: {result_path}\n")
|
| 249 |
+
f.write(f"FVD: {fvd_value}\n")
|
| 250 |
+
f.write(f"LPIPS: {lpips_value}\n")
|
| 251 |
+
f.write(f"DreamSim: {dreamsim_value}\n")
|
| 252 |
+
f.write(f"CLIP Loss: {clip_loss_value}\n")
|
| 253 |
+
f.write("-" * 50 + "\n")
|
| 254 |
+
print(f"Results saved to {output_file}")
|
| 255 |
+
|
| 256 |
+
except Exception as e:
|
| 257 |
+
print(f"Error processing pair {idx+1}: {str(e)}")
|
| 258 |
+
import traceback
|
| 259 |
+
traceback.print_exc()
|
| 260 |
+
continue
|
| 261 |
+
|
| 262 |
+
# Print summary
|
| 263 |
+
print(f"\n{'='*60}")
|
| 264 |
+
print(f"Summary: Processed {len(all_results)}/{len(gt_paths)} pairs")
|
| 265 |
+
if len(all_results) > 0:
|
| 266 |
+
avg_fvd = np.mean([r['fvd'] for r in all_results])
|
| 267 |
+
avg_lpips = np.mean([r['lpips'] for r in all_results])
|
| 268 |
+
avg_dreamsim = np.mean([r['dreamsim'] for r in all_results])
|
| 269 |
+
avg_clip = np.mean([r['clip_loss'] for r in all_results])
|
| 270 |
+
print(f"Average FVD: {avg_fvd:.6f}")
|
| 271 |
+
print(f"Average LPIPS: {avg_lpips:.6f}")
|
| 272 |
+
print(f"Average DreamSim: {avg_dreamsim:.6f}")
|
| 273 |
+
print(f"Average CLIP Loss: {avg_clip:.6f}")
|
| 274 |
+
print(f"{'='*60}")
|
OVOW/third_party/Motion324/evaluation/evaluation_pcd.py
ADDED
|
@@ -0,0 +1,940 @@
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import numpy as np
|
| 3 |
+
import trimesh
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
from mpl_toolkits.mplot3d import Axes3D
|
| 7 |
+
from scipy.spatial import cKDTree
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
# Try to import bpy for GLB/FBX loading
|
| 11 |
+
try:
|
| 12 |
+
import bpy
|
| 13 |
+
BLENDER_AVAILABLE = True
|
| 14 |
+
except ImportError:
|
| 15 |
+
BLENDER_AVAILABLE = False
|
| 16 |
+
print("Warning: bpy not available. GLB/FBX loading will not work.")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def load_pred_mesh_from_file(pred_file_path, frame_idx, pred_mesh_cache=None):
|
| 20 |
+
"""
|
| 21 |
+
Load predicted mesh from GLB/FBX file using Blender.
|
| 22 |
+
pred_mesh_cache should be a dict containing 'obj', 'depsgraph', 'scene', 'file_ext', 'frames'
|
| 23 |
+
"""
|
| 24 |
+
if not BLENDER_AVAILABLE:
|
| 25 |
+
raise RuntimeError("bpy is not available. Cannot load GLB/FBX files.")
|
| 26 |
+
|
| 27 |
+
if pred_mesh_cache is None:
|
| 28 |
+
raise ValueError("pred_mesh_cache must be provided for file loading")
|
| 29 |
+
|
| 30 |
+
obj = pred_mesh_cache['obj']
|
| 31 |
+
depsgraph = pred_mesh_cache['depsgraph']
|
| 32 |
+
scene = pred_mesh_cache['scene']
|
| 33 |
+
file_ext = pred_mesh_cache['file_ext']
|
| 34 |
+
frames = pred_mesh_cache['frames']
|
| 35 |
+
|
| 36 |
+
# Get the actual frame number (handle FBX frame offset)
|
| 37 |
+
if frame_idx < len(frames):
|
| 38 |
+
actual_frame = frames[frame_idx]
|
| 39 |
+
else:
|
| 40 |
+
# If frame_idx exceeds available frames, use last frame
|
| 41 |
+
actual_frame = frames[-1]
|
| 42 |
+
|
| 43 |
+
# Set scene to the target frame
|
| 44 |
+
scene.frame_set(actual_frame)
|
| 45 |
+
obj_eval = obj.evaluated_get(depsgraph)
|
| 46 |
+
me = bpy.data.meshes.new_from_object(
|
| 47 |
+
obj_eval,
|
| 48 |
+
preserve_all_data_layers=True,
|
| 49 |
+
depsgraph=depsgraph,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Extract vertices
|
| 53 |
+
vertices = np.zeros((len(me.vertices), 3), dtype=np.float32)
|
| 54 |
+
for i, v in enumerate(me.vertices):
|
| 55 |
+
vertices[i] = v.co
|
| 56 |
+
|
| 57 |
+
# Extract faces
|
| 58 |
+
faces = []
|
| 59 |
+
for poly in me.polygons:
|
| 60 |
+
faces.append(list(poly.vertices))
|
| 61 |
+
faces = np.array(faces, dtype=np.int32)
|
| 62 |
+
|
| 63 |
+
# Clean up temporary mesh
|
| 64 |
+
bpy.data.meshes.remove(me)
|
| 65 |
+
|
| 66 |
+
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
|
| 67 |
+
return mesh
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def load_pred_mesh_from_dir(pred_path, frame_idx):
|
| 71 |
+
"""Load predicted mesh from faces.npy and frame_{frame_idx:04d}.npy"""
|
| 72 |
+
faces = np.load(Path(pred_path) / "faces.npy")
|
| 73 |
+
vertices = np.load(Path(pred_path) / f"frame_{frame_idx:04d}.npy")
|
| 74 |
+
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
|
| 75 |
+
return mesh
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def load_pred_mesh(pred_path, frame_idx, pred_mesh_cache=None):
|
| 79 |
+
"""
|
| 80 |
+
Load predicted mesh. Supports both:
|
| 81 |
+
1. Directory with faces.npy and frame_*.npy files
|
| 82 |
+
2. GLB/FBX file (requires Blender)
|
| 83 |
+
"""
|
| 84 |
+
pred_path_obj = Path(pred_path)
|
| 85 |
+
|
| 86 |
+
# Check if it's a file (GLB/FBX) or directory (npy files)
|
| 87 |
+
if pred_path_obj.is_file():
|
| 88 |
+
# It's a file, use Blender to load
|
| 89 |
+
if pred_mesh_cache is None:
|
| 90 |
+
raise ValueError("pred_mesh_cache must be provided when loading from GLB/FBX file")
|
| 91 |
+
return load_pred_mesh_from_file(pred_path, frame_idx, pred_mesh_cache)
|
| 92 |
+
else:
|
| 93 |
+
# It's a directory, load from npy files
|
| 94 |
+
return load_pred_mesh_from_dir(pred_path, frame_idx)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def initialize_pred_mesh_cache(pred_path):
|
| 98 |
+
"""
|
| 99 |
+
Initialize Blender scene and load predicted mesh file.
|
| 100 |
+
Returns a cache dict containing necessary Blender objects and frame information.
|
| 101 |
+
Returns None if pred_path is not a file or Blender is not available.
|
| 102 |
+
"""
|
| 103 |
+
pred_path_obj = Path(pred_path)
|
| 104 |
+
|
| 105 |
+
# If it's not a file, return None (will use directory loading)
|
| 106 |
+
if not pred_path_obj.is_file():
|
| 107 |
+
return None
|
| 108 |
+
|
| 109 |
+
if not BLENDER_AVAILABLE:
|
| 110 |
+
raise RuntimeError("bpy is not available. Cannot load GLB/FBX files.")
|
| 111 |
+
|
| 112 |
+
file_ext = pred_path_obj.suffix.lower()
|
| 113 |
+
if file_ext not in ['.glb', '.gltf', '.fbx']:
|
| 114 |
+
return None # Not a supported file format, will use directory loading
|
| 115 |
+
|
| 116 |
+
print(f"Loading predicted mesh from {pred_path_obj}...")
|
| 117 |
+
|
| 118 |
+
# Clear scene and import file
|
| 119 |
+
bpy.ops.object.select_all(action='SELECT')
|
| 120 |
+
bpy.ops.object.delete()
|
| 121 |
+
|
| 122 |
+
if file_ext == '.glb' or file_ext == '.gltf':
|
| 123 |
+
bpy.ops.import_scene.gltf(filepath=str(pred_path_obj))
|
| 124 |
+
elif file_ext == '.fbx':
|
| 125 |
+
bpy.ops.import_scene.fbx(filepath=str(pred_path_obj))
|
| 126 |
+
|
| 127 |
+
# Get the mesh object
|
| 128 |
+
obj = None
|
| 129 |
+
for o in bpy.context.scene.objects:
|
| 130 |
+
if o.type == 'MESH':
|
| 131 |
+
obj = o
|
| 132 |
+
break
|
| 133 |
+
|
| 134 |
+
if obj is None:
|
| 135 |
+
raise ValueError("No mesh object found in the imported file")
|
| 136 |
+
|
| 137 |
+
# Gather keyframes
|
| 138 |
+
def gather_keyframes(o):
|
| 139 |
+
frames = set()
|
| 140 |
+
ad = o.animation_data
|
| 141 |
+
if ad and ad.action:
|
| 142 |
+
for fc in ad.action.fcurves:
|
| 143 |
+
for kp in fc.keyframe_points:
|
| 144 |
+
frames.add(int(round(kp.co.x)))
|
| 145 |
+
sk = getattr(o.data, "shape_keys", None)
|
| 146 |
+
if sk and sk.animation_data and sk.animation_data.action:
|
| 147 |
+
for fc in sk.animation_data.action.fcurves:
|
| 148 |
+
for kp in fc.keyframe_points:
|
| 149 |
+
frames.add(int(round(kp.co.x)))
|
| 150 |
+
return sorted(frames)
|
| 151 |
+
|
| 152 |
+
frames = gather_keyframes(obj)
|
| 153 |
+
|
| 154 |
+
# If no keyframes, use scene frame range
|
| 155 |
+
if not frames:
|
| 156 |
+
frames = list(range(bpy.context.scene.frame_start, bpy.context.scene.frame_end + 1))
|
| 157 |
+
|
| 158 |
+
print(f"Found {len(frames)} frames in predicted mesh file: {frames[:10]}..." if len(frames) > 10 else f"Found {len(frames)} frames in predicted mesh file: {frames}")
|
| 159 |
+
|
| 160 |
+
scene = bpy.context.scene
|
| 161 |
+
depsgraph = bpy.context.evaluated_depsgraph_get()
|
| 162 |
+
|
| 163 |
+
return {
|
| 164 |
+
'obj': obj,
|
| 165 |
+
'depsgraph': depsgraph,
|
| 166 |
+
'scene': scene,
|
| 167 |
+
'file_ext': file_ext,
|
| 168 |
+
'frames': frames
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
def normalize_mesh(mesh):
|
| 172 |
+
"""
|
| 173 |
+
Normalize mesh similar to bpyrenderer's normalize_scene method.
|
| 174 |
+
Uses CUBE range type normalization.
|
| 175 |
+
"""
|
| 176 |
+
vertices = mesh.vertices
|
| 177 |
+
|
| 178 |
+
# Calculate bounding box
|
| 179 |
+
bbox_min = vertices.min(axis=0)
|
| 180 |
+
bbox_max = vertices.max(axis=0)
|
| 181 |
+
|
| 182 |
+
# Calculate offset to center (similar to normalize_scene)
|
| 183 |
+
offset = -(bbox_min + bbox_max) / 2
|
| 184 |
+
center = -offset # Store original center for later use
|
| 185 |
+
|
| 186 |
+
# Calculate scale (CUBE range type: normalize_range / max(bbox_max - bbox_min))
|
| 187 |
+
normalize_range = 2.0
|
| 188 |
+
scale = normalize_range / np.max(bbox_max - bbox_min)
|
| 189 |
+
|
| 190 |
+
# Apply normalization: first translate to center, then scale
|
| 191 |
+
vertices_centered = vertices + offset
|
| 192 |
+
vertices_normalized = vertices_centered * scale
|
| 193 |
+
|
| 194 |
+
return vertices_normalized, center, 1.0 / scale
|
| 195 |
+
|
| 196 |
+
def apply_normalization(vertices, center, scale):
|
| 197 |
+
"""Apply pre-computed normalization parameters"""
|
| 198 |
+
return (vertices - center) / scale
|
| 199 |
+
|
| 200 |
+
def apply_icp_alignment(vertices_norm, R, t, s):
|
| 201 |
+
"""Apply ICP alignment transformation: s * (vertices_norm @ R.T) + t"""
|
| 202 |
+
return s * (vertices_norm @ R.T) + t
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def icp_alignment(source_points, target_points, max_iterations=1000, tolerance=1e-7, output_dir=None, optimize_scale=False, visualize=False):
|
| 206 |
+
"""
|
| 207 |
+
Use standard Point-to-Point ICP algorithm to align source to target.
|
| 208 |
+
Returns: rotation matrix R, translation vector t, scale factor s
|
| 209 |
+
such that: aligned = s * (source @ R.T) + t
|
| 210 |
+
|
| 211 |
+
Args:
|
| 212 |
+
source_points: source point cloud
|
| 213 |
+
target_points: target point cloud
|
| 214 |
+
max_iterations: maximum number of iterations
|
| 215 |
+
tolerance: convergence threshold
|
| 216 |
+
output_dir: output directory (for saving visualizations)
|
| 217 |
+
optimize_scale: whether to optimize scale factor (default False, scale limited to 0.95-1.05 range)
|
| 218 |
+
visualize: whether to generate visualizations
|
| 219 |
+
"""
|
| 220 |
+
# Initialize
|
| 221 |
+
source = source_points.copy()
|
| 222 |
+
target = target_points.copy()
|
| 223 |
+
|
| 224 |
+
# Calculate initial scale (based on bbox max range)
|
| 225 |
+
source_bbox_min = np.min(source, axis=0)
|
| 226 |
+
source_bbox_max = np.max(source, axis=0)
|
| 227 |
+
source_max_range = np.max((source_bbox_max - source_bbox_min)[:2]) # Only consider x and y axes
|
| 228 |
+
|
| 229 |
+
target_bbox_min = np.min(target, axis=0)
|
| 230 |
+
target_bbox_max = np.max(target, axis=0)
|
| 231 |
+
target_max_range = np.max((target_bbox_max - target_bbox_min)[:2]) # Only consider x and y axes
|
| 232 |
+
|
| 233 |
+
print(f"Source max range: {source_max_range}, Target max range: {target_max_range}")
|
| 234 |
+
# Calculate scale factor based on bbox max range
|
| 235 |
+
if source_max_range > 1e-10:
|
| 236 |
+
scale = target_max_range / source_max_range
|
| 237 |
+
# Limit initial scale to 0.95-1.05 range
|
| 238 |
+
scale = np.clip(scale, 0.95, 1.05)
|
| 239 |
+
else:
|
| 240 |
+
print(f"Warning: source_max_range is too small: {source_max_range}")
|
| 241 |
+
scale = 1.0
|
| 242 |
+
|
| 243 |
+
# ICP iteration
|
| 244 |
+
R = np.eye(3)
|
| 245 |
+
t = np.zeros(3)
|
| 246 |
+
prev_error = float('inf')
|
| 247 |
+
|
| 248 |
+
# List to save intermediate results
|
| 249 |
+
iteration_data = []
|
| 250 |
+
|
| 251 |
+
# Create output directory (only when visualizing)
|
| 252 |
+
if visualize and output_dir is not None:
|
| 253 |
+
output_dir = Path(output_dir)
|
| 254 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 255 |
+
temp_dir = output_dir / "icp_iterations"
|
| 256 |
+
temp_dir.mkdir(exist_ok=True)
|
| 257 |
+
|
| 258 |
+
for iteration in range(max_iterations):
|
| 259 |
+
# Apply current transformation: scale * (source @ R.T) + t
|
| 260 |
+
source_transformed = scale * (source @ R.T) + t
|
| 261 |
+
|
| 262 |
+
# Find nearest neighbors
|
| 263 |
+
tree = cKDTree(target)
|
| 264 |
+
distances, indices = tree.query(source_transformed)
|
| 265 |
+
|
| 266 |
+
# Get corresponding target points
|
| 267 |
+
matched_target = target[indices]
|
| 268 |
+
|
| 269 |
+
# Calculate point-to-point distance
|
| 270 |
+
error = np.mean(distances)
|
| 271 |
+
|
| 272 |
+
if visualize:
|
| 273 |
+
print(f"ICP Iteration {iteration+1}: Mean Distance = {error:.6f}, Scale = {scale:.6f}")
|
| 274 |
+
|
| 275 |
+
# Save iteration data (only when visualizing)
|
| 276 |
+
if visualize:
|
| 277 |
+
iteration_data.append({
|
| 278 |
+
'iteration': iteration,
|
| 279 |
+
'error': error,
|
| 280 |
+
'R': R.copy(),
|
| 281 |
+
't': t.copy(),
|
| 282 |
+
'scale': scale,
|
| 283 |
+
'source_transformed': source_transformed.copy()
|
| 284 |
+
})
|
| 285 |
+
|
| 286 |
+
# Visualize current iteration state (only when visualizing)
|
| 287 |
+
if visualize and output_dir is not None and (iteration % 5 == 0 or iteration == 0 or iteration == max_iterations - 1):
|
| 288 |
+
fig = plt.figure(figsize=(15, 5))
|
| 289 |
+
|
| 290 |
+
# Downsample for visualization
|
| 291 |
+
sample_rate = max(1, len(source_transformed) // 5000)
|
| 292 |
+
source_sample = source_transformed[::sample_rate]
|
| 293 |
+
target_sample = target[::sample_rate]
|
| 294 |
+
|
| 295 |
+
# 3D view - front
|
| 296 |
+
ax1 = fig.add_subplot(131, projection='3d')
|
| 297 |
+
ax1.scatter(source_sample[:, 0], source_sample[:, 1], source_sample[:, 2],
|
| 298 |
+
c='red', s=1, alpha=0.5, label='Source')
|
| 299 |
+
ax1.scatter(target_sample[:, 0], target_sample[:, 1], target_sample[:, 2],
|
| 300 |
+
c='blue', s=1, alpha=0.5, label='Target')
|
| 301 |
+
ax1.set_xlabel('X')
|
| 302 |
+
ax1.set_ylabel('Y')
|
| 303 |
+
ax1.set_zlabel('Z')
|
| 304 |
+
ax1.set_title(f'3D View - Iter {iteration+1}')
|
| 305 |
+
ax1.legend()
|
| 306 |
+
ax1.view_init(elev=20, azim=45)
|
| 307 |
+
|
| 308 |
+
# Set same axis range
|
| 309 |
+
all_points = np.vstack([source_transformed, target])
|
| 310 |
+
max_range = np.array([all_points[:, 0].max()-all_points[:, 0].min(),
|
| 311 |
+
all_points[:, 1].max()-all_points[:, 1].min(),
|
| 312 |
+
all_points[:, 2].max()-all_points[:, 2].min()]).max() / 2.0
|
| 313 |
+
mid_x = (all_points[:, 0].max()+all_points[:, 0].min()) * 0.5
|
| 314 |
+
mid_y = (all_points[:, 1].max()+all_points[:, 1].min()) * 0.5
|
| 315 |
+
mid_z = (all_points[:, 2].max()+all_points[:, 2].min()) * 0.5
|
| 316 |
+
ax1.set_xlim(mid_x - max_range, mid_x + max_range)
|
| 317 |
+
ax1.set_ylim(mid_y - max_range, mid_y + max_range)
|
| 318 |
+
ax1.set_zlim(mid_z - max_range, mid_z + max_range)
|
| 319 |
+
|
| 320 |
+
# 3D view - side
|
| 321 |
+
ax2 = fig.add_subplot(132, projection='3d')
|
| 322 |
+
ax2.scatter(source_sample[:, 0], source_sample[:, 1], source_sample[:, 2],
|
| 323 |
+
c='red', s=1, alpha=0.5, label='Source')
|
| 324 |
+
ax2.scatter(target_sample[:, 0], target_sample[:, 1], target_sample[:, 2],
|
| 325 |
+
c='blue', s=1, alpha=0.5, label='Target')
|
| 326 |
+
ax2.set_xlabel('X')
|
| 327 |
+
ax2.set_ylabel('Y')
|
| 328 |
+
ax2.set_zlabel('Z')
|
| 329 |
+
ax2.set_title(f'Side View - Iter {iteration+1}')
|
| 330 |
+
ax2.legend()
|
| 331 |
+
ax2.view_init(elev=0, azim=0)
|
| 332 |
+
ax2.set_xlim(mid_x - max_range, mid_x + max_range)
|
| 333 |
+
ax2.set_ylim(mid_y - max_range, mid_y + max_range)
|
| 334 |
+
ax2.set_zlim(mid_z - max_range, mid_z + max_range)
|
| 335 |
+
|
| 336 |
+
# Error curve
|
| 337 |
+
ax3 = fig.add_subplot(133)
|
| 338 |
+
errors = [d['error'] for d in iteration_data]
|
| 339 |
+
ax3.plot(range(len(errors)), errors, 'b-', linewidth=2)
|
| 340 |
+
ax3.scatter(len(errors)-1, errors[-1], c='red', s=50, zorder=5)
|
| 341 |
+
ax3.set_xlabel('Iteration')
|
| 342 |
+
ax3.set_ylabel('Mean Distance Error')
|
| 343 |
+
ax3.set_title(f'Convergence Curve\nCurrent Error: {error:.6f}')
|
| 344 |
+
ax3.grid(True, alpha=0.3)
|
| 345 |
+
|
| 346 |
+
plt.tight_layout()
|
| 347 |
+
|
| 348 |
+
# Save image
|
| 349 |
+
img_path = temp_dir / f"iteration_{iteration:04d}.png"
|
| 350 |
+
plt.savefig(img_path, dpi=100, bbox_inches='tight')
|
| 351 |
+
plt.close()
|
| 352 |
+
print(f" Saved visualization to {img_path}")
|
| 353 |
+
|
| 354 |
+
# Check convergence
|
| 355 |
+
if abs(prev_error - error) < tolerance:
|
| 356 |
+
if visualize:
|
| 357 |
+
print(f"ICP converged at iteration {iteration+1}")
|
| 358 |
+
break
|
| 359 |
+
prev_error = error
|
| 360 |
+
|
| 361 |
+
# Calculate centroids
|
| 362 |
+
source_centroid = np.mean(source_transformed, axis=0)
|
| 363 |
+
target_centroid = np.mean(matched_target, axis=0)
|
| 364 |
+
|
| 365 |
+
# Center
|
| 366 |
+
source_centered_iter = source_transformed - source_centroid
|
| 367 |
+
target_centered_iter = matched_target - target_centroid
|
| 368 |
+
|
| 369 |
+
# Calculate covariance matrix
|
| 370 |
+
H = source_centered_iter.T @ target_centered_iter
|
| 371 |
+
|
| 372 |
+
# SVD decomposition
|
| 373 |
+
U, S, Vt = np.linalg.svd(H)
|
| 374 |
+
|
| 375 |
+
# Calculate rotation matrix
|
| 376 |
+
R_delta = Vt.T @ U.T
|
| 377 |
+
|
| 378 |
+
# Ensure right-handed coordinate system (determinant = 1)
|
| 379 |
+
if np.linalg.det(R_delta) < 0:
|
| 380 |
+
Vt[-1, :] *= -1
|
| 381 |
+
R_delta = Vt.T @ U.T
|
| 382 |
+
|
| 383 |
+
# Calculate translation increment
|
| 384 |
+
t_delta = target_centroid - source_centroid @ R_delta.T
|
| 385 |
+
|
| 386 |
+
# Update rotation and translation
|
| 387 |
+
R = R @ R_delta
|
| 388 |
+
t = t @ R_delta.T + t_delta
|
| 389 |
+
|
| 390 |
+
# Orthogonalize rotation matrix (ensure numerical stability)
|
| 391 |
+
U, _, Vt = np.linalg.svd(R)
|
| 392 |
+
R = U @ Vt
|
| 393 |
+
|
| 394 |
+
# Optimize scale factor (if enabled)
|
| 395 |
+
if optimize_scale:
|
| 396 |
+
# After applying current R and t, optimize scale
|
| 397 |
+
source_rotated_translated = source @ R.T + t
|
| 398 |
+
# Optimal scale = sum(target * source) / sum(source * source)
|
| 399 |
+
numerator = np.sum(target[indices] * source_rotated_translated)
|
| 400 |
+
denominator = np.sum(source_rotated_translated * source_rotated_translated)
|
| 401 |
+
if denominator > 1e-10:
|
| 402 |
+
scale_new = numerator / denominator
|
| 403 |
+
# Limit scale to 0.95-1.05 range
|
| 404 |
+
scale_new = np.clip(scale_new, 0.95, 1.05)
|
| 405 |
+
# Smooth scale update to avoid oscillation
|
| 406 |
+
scale = 0.8 * scale + 0.2 * scale_new
|
| 407 |
+
# Ensure scale is in range again
|
| 408 |
+
scale = np.clip(scale, 0.95, 1.05)
|
| 409 |
+
|
| 410 |
+
# Print final error
|
| 411 |
+
print(f"Final Mean Distance: {error:.6f}")
|
| 412 |
+
|
| 413 |
+
# Create final comparison plot (only when visualizing)
|
| 414 |
+
if visualize and output_dir is not None:
|
| 415 |
+
print("\nCreating final comparison visualization...")
|
| 416 |
+
|
| 417 |
+
# Select key frames for display
|
| 418 |
+
key_iterations = [0]
|
| 419 |
+
step = max(1, len(iteration_data) // 8)
|
| 420 |
+
for i in range(step, len(iteration_data), step):
|
| 421 |
+
key_iterations.append(i)
|
| 422 |
+
if len(iteration_data) - 1 not in key_iterations:
|
| 423 |
+
key_iterations.append(len(iteration_data) - 1)
|
| 424 |
+
|
| 425 |
+
n_images = len(key_iterations)
|
| 426 |
+
n_cols = min(4, n_images)
|
| 427 |
+
n_rows = (n_images + n_cols - 1) // n_cols
|
| 428 |
+
|
| 429 |
+
fig = plt.figure(figsize=(5*n_cols, 5*n_rows))
|
| 430 |
+
|
| 431 |
+
for idx, iter_idx in enumerate(key_iterations):
|
| 432 |
+
ax = fig.add_subplot(n_rows, n_cols, idx+1, projection='3d')
|
| 433 |
+
|
| 434 |
+
data = iteration_data[iter_idx]
|
| 435 |
+
source_transformed = data['source_transformed']
|
| 436 |
+
|
| 437 |
+
sample_rate = max(1, len(source_transformed) // 3000)
|
| 438 |
+
source_sample = source_transformed[::sample_rate]
|
| 439 |
+
target_sample = target[::sample_rate]
|
| 440 |
+
|
| 441 |
+
ax.scatter(source_sample[:, 0], source_sample[:, 1], source_sample[:, 2],
|
| 442 |
+
c='red', s=1, alpha=0.5, label='Source')
|
| 443 |
+
ax.scatter(target_sample[:, 0], target_sample[:, 1], target_sample[:, 2],
|
| 444 |
+
c='blue', s=1, alpha=0.5, label='Target')
|
| 445 |
+
|
| 446 |
+
ax.set_xlabel('X')
|
| 447 |
+
ax.set_ylabel('Y')
|
| 448 |
+
ax.set_zlabel('Z')
|
| 449 |
+
ax.set_title(f"Iter {data['iteration']+1}\nError: {data['error']:.6f}, Scale: {data['scale']:.6f}")
|
| 450 |
+
ax.legend()
|
| 451 |
+
ax.view_init(elev=20, azim=45)
|
| 452 |
+
|
| 453 |
+
# Set same axis range
|
| 454 |
+
all_points = np.vstack([source_transformed, target])
|
| 455 |
+
max_range = np.array([all_points[:, 0].max()-all_points[:, 0].min(),
|
| 456 |
+
all_points[:, 1].max()-all_points[:, 1].min(),
|
| 457 |
+
all_points[:, 2].max()-all_points[:, 2].min()]).max() / 2.0
|
| 458 |
+
mid_x = (all_points[:, 0].max()+all_points[:, 0].min()) * 0.5
|
| 459 |
+
mid_y = (all_points[:, 1].max()+all_points[:, 1].min()) * 0.5
|
| 460 |
+
mid_z = (all_points[:, 2].max()+all_points[:, 2].min()) * 0.5
|
| 461 |
+
ax.set_xlim(mid_x - max_range, mid_x + max_range)
|
| 462 |
+
ax.set_ylim(mid_y - max_range, mid_y + max_range)
|
| 463 |
+
ax.set_zlim(mid_z - max_range, mid_z + max_range)
|
| 464 |
+
|
| 465 |
+
plt.tight_layout()
|
| 466 |
+
final_grid_path = output_dir / "icp_iterations_grid.png"
|
| 467 |
+
plt.savefig(final_grid_path, dpi=150, bbox_inches='tight')
|
| 468 |
+
plt.close()
|
| 469 |
+
print(f"Final grid saved to {final_grid_path}")
|
| 470 |
+
|
| 471 |
+
# Save error curve and scale curve
|
| 472 |
+
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 10))
|
| 473 |
+
|
| 474 |
+
errors = [d['error'] for d in iteration_data]
|
| 475 |
+
ax1.plot(range(len(errors)), errors, 'b-', linewidth=2, label='Error')
|
| 476 |
+
ax1.scatter(range(len(errors)), errors, c='blue', s=20, alpha=0.5)
|
| 477 |
+
ax1.set_xlabel('Iteration', fontsize=12)
|
| 478 |
+
ax1.set_ylabel('Mean Distance Error', fontsize=12)
|
| 479 |
+
ax1.set_title('ICP Convergence Curve', fontsize=14)
|
| 480 |
+
ax1.grid(True, alpha=0.3)
|
| 481 |
+
ax1.legend()
|
| 482 |
+
|
| 483 |
+
if optimize_scale:
|
| 484 |
+
scales = [d['scale'] for d in iteration_data]
|
| 485 |
+
ax2.plot(range(len(scales)), scales, 'r-', linewidth=2, label='Scale')
|
| 486 |
+
ax2.scatter(range(len(scales)), scales, c='red', s=20, alpha=0.5)
|
| 487 |
+
ax2.axhline(y=0.95, color='g', linestyle='--', alpha=0.5, label='Scale limits')
|
| 488 |
+
ax2.axhline(y=1.05, color='g', linestyle='--', alpha=0.5)
|
| 489 |
+
ax2.set_xlabel('Iteration', fontsize=12)
|
| 490 |
+
ax2.set_ylabel('Scale Factor', fontsize=12)
|
| 491 |
+
ax2.set_title('Scale Optimization (limited to 0.95-1.05)', fontsize=14)
|
| 492 |
+
ax2.grid(True, alpha=0.3)
|
| 493 |
+
ax2.legend()
|
| 494 |
+
|
| 495 |
+
plt.tight_layout()
|
| 496 |
+
error_curve_path = output_dir / "icp_error_curve.png"
|
| 497 |
+
plt.savefig(error_curve_path, dpi=150, bbox_inches='tight')
|
| 498 |
+
plt.close()
|
| 499 |
+
print(f"Error curve saved to {error_curve_path}")
|
| 500 |
+
|
| 501 |
+
return R, t, scale
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def compute_alignment_from_first_frame(gt_path, pred_path, pred_mesh_cache=None, visualize=False):
|
| 505 |
+
"""
|
| 506 |
+
Compute ICP alignment parameters from the first frame.
|
| 507 |
+
Returns: rotation matrix R, translation vector t, scale factor s, and normalization parameters.
|
| 508 |
+
|
| 509 |
+
Args:
|
| 510 |
+
gt_path: path to GT data directory (contains faces.npy and frame_*.npy)
|
| 511 |
+
pred_path: path to predicted data (can be directory with frame_*.npy or GLB/FBX file)
|
| 512 |
+
pred_mesh_cache: cache for predicted mesh (if loading from file)
|
| 513 |
+
visualize: whether to generate visualizations
|
| 514 |
+
"""
|
| 515 |
+
gt_path = Path(gt_path)
|
| 516 |
+
pred_path = Path(pred_path)
|
| 517 |
+
|
| 518 |
+
# Load GT first frame
|
| 519 |
+
print(f"Loading GT frame 0 from {gt_path}...")
|
| 520 |
+
gt_faces_path = gt_path / "faces.npy"
|
| 521 |
+
if gt_faces_path.exists():
|
| 522 |
+
gt_faces = np.load(gt_faces_path)
|
| 523 |
+
else:
|
| 524 |
+
gt_faces = None
|
| 525 |
+
|
| 526 |
+
gt_frame_0 = np.load(gt_path / "frame_0000.npy")
|
| 527 |
+
if gt_faces is not None:
|
| 528 |
+
gt_mesh_0 = trimesh.Trimesh(vertices=gt_frame_0, faces=gt_faces, process=False)
|
| 529 |
+
else:
|
| 530 |
+
gt_mesh_0 = trimesh.Trimesh(vertices=gt_frame_0, process=False)
|
| 531 |
+
|
| 532 |
+
# Normalize GT
|
| 533 |
+
gt_vertices_0_norm, gt_center, gt_scale = normalize_mesh(gt_mesh_0)
|
| 534 |
+
print(f"GT Normalization - Center: {gt_center}, Scale: {gt_scale}")
|
| 535 |
+
|
| 536 |
+
# Sample 10000 points from GT mesh surface for ICP
|
| 537 |
+
print("Sampling 10000 points from GT mesh surface...")
|
| 538 |
+
gt_sampled_points, _ = trimesh.sample.sample_surface(gt_mesh_0, 10000)
|
| 539 |
+
# Apply same normalization to sampled points
|
| 540 |
+
gt_sampled_points_norm = (gt_sampled_points - gt_center) / gt_scale
|
| 541 |
+
|
| 542 |
+
# Load predicted first frame
|
| 543 |
+
print(f"Loading predicted frame 0 from {pred_path}...")
|
| 544 |
+
pred_mesh_0 = load_pred_mesh(pred_path, 0, pred_mesh_cache)
|
| 545 |
+
|
| 546 |
+
# Normalize prediction
|
| 547 |
+
pred_vertices_0_norm, pred_center, pred_scale = normalize_mesh(pred_mesh_0)
|
| 548 |
+
print(f"Pred Normalization - Center: {pred_center}, Scale: {pred_scale}")
|
| 549 |
+
|
| 550 |
+
# Use standard Point-to-Point ICP alignment (using GT sampled points)
|
| 551 |
+
print("\nRunning Point-to-Point ICP alignment...")
|
| 552 |
+
output_dir = gt_path / "icp_visualization" if visualize else None
|
| 553 |
+
R, t, s = icp_alignment(pred_vertices_0_norm, gt_sampled_points_norm,
|
| 554 |
+
output_dir=output_dir, visualize=visualize)
|
| 555 |
+
print(f"\nICP Alignment Results:")
|
| 556 |
+
print(f"Rotation Matrix R:\n{R}")
|
| 557 |
+
print(f"Translation t: {t}")
|
| 558 |
+
print(f"Scale s: {s}")
|
| 559 |
+
|
| 560 |
+
# Save alignment parameters
|
| 561 |
+
# Save to GT path (as npz format for easy loading)
|
| 562 |
+
np.savez(gt_path / 'icp_alignment_params.npz',
|
| 563 |
+
R=R, t=t, s=s)
|
| 564 |
+
print(f"Alignment parameters saved to: {gt_path / 'icp_alignment_params.npz'}")
|
| 565 |
+
|
| 566 |
+
return R, t, s
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def sample_points_from_mesh(mesh, num_points=50000):
|
| 570 |
+
"""Sample points uniformly from mesh surface"""
|
| 571 |
+
points, _ = trimesh.sample.sample_surface(mesh, num_points)
|
| 572 |
+
return points
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def compute_chamfer_distance(points1, points2):
|
| 576 |
+
"""Compute bidirectional Chamfer distance"""
|
| 577 |
+
# Build KD-trees
|
| 578 |
+
tree1 = cKDTree(points1)
|
| 579 |
+
tree2 = cKDTree(points2)
|
| 580 |
+
|
| 581 |
+
# Compute distances from points1 to points2
|
| 582 |
+
dist1, _ = tree1.query(points2, k=1)
|
| 583 |
+
# Compute distances from points2 to points1
|
| 584 |
+
dist2, _ = tree2.query(points1, k=1)
|
| 585 |
+
|
| 586 |
+
# Chamfer distance is the mean of both directions
|
| 587 |
+
chamfer_dist = (np.mean(dist1) + np.mean(dist2))
|
| 588 |
+
return chamfer_dist
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def compute_fscore(points1, points2, threshold=0.02):
|
| 592 |
+
"""Compute F-score at given threshold"""
|
| 593 |
+
# Build KD-trees
|
| 594 |
+
tree1 = cKDTree(points1)
|
| 595 |
+
tree2 = cKDTree(points2)
|
| 596 |
+
|
| 597 |
+
# Compute distances
|
| 598 |
+
dist1, _ = tree1.query(points2, k=1)
|
| 599 |
+
dist2, _ = tree2.query(points1, k=1)
|
| 600 |
+
|
| 601 |
+
# Compute precision and recall
|
| 602 |
+
precision = np.mean(dist1 < threshold)
|
| 603 |
+
recall = np.mean(dist2 < threshold)
|
| 604 |
+
|
| 605 |
+
# Compute F-score
|
| 606 |
+
if precision + recall == 0:
|
| 607 |
+
return 0.0
|
| 608 |
+
fscore = 2 * precision * recall / (precision + recall)
|
| 609 |
+
return fscore
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def compute_iou_voxel(mesh1, mesh2, resolution=128):
|
| 613 |
+
"""Compute IoU on voxel grids"""
|
| 614 |
+
# Voxelize both meshes
|
| 615 |
+
voxel1 = mesh1.voxelized(pitch=1.0/resolution)
|
| 616 |
+
voxel2 = mesh2.voxelized(pitch=1.0/resolution)
|
| 617 |
+
|
| 618 |
+
# Get filled voxel grids
|
| 619 |
+
grid1 = voxel1.matrix
|
| 620 |
+
grid2 = voxel2.matrix
|
| 621 |
+
|
| 622 |
+
# Ensure same shape
|
| 623 |
+
max_shape = np.maximum(grid1.shape, grid2.shape)
|
| 624 |
+
padded_grid1 = np.zeros(max_shape, dtype=bool)
|
| 625 |
+
padded_grid2 = np.zeros(max_shape, dtype=bool)
|
| 626 |
+
|
| 627 |
+
padded_grid1[:grid1.shape[0], :grid1.shape[1], :grid1.shape[2]] = grid1
|
| 628 |
+
padded_grid2[:grid2.shape[0], :grid2.shape[1], :grid2.shape[2]] = grid2
|
| 629 |
+
|
| 630 |
+
# Compute IoU
|
| 631 |
+
intersection = np.logical_and(padded_grid1, padded_grid2).sum()
|
| 632 |
+
union = np.logical_or(padded_grid1, padded_grid2).sum()
|
| 633 |
+
|
| 634 |
+
if union == 0:
|
| 635 |
+
return 0.0
|
| 636 |
+
iou = intersection / union
|
| 637 |
+
return iou
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def visualize_mesh_comparison(gt_mesh, pred_mesh, frame_idx, viz_dir):
|
| 641 |
+
"""Visualize ground truth and predicted meshes"""
|
| 642 |
+
fig = plt.figure(figsize=(15, 5))
|
| 643 |
+
|
| 644 |
+
# Plot GT mesh
|
| 645 |
+
ax1 = fig.add_subplot(131, projection='3d')
|
| 646 |
+
ax1.plot_trisurf(gt_mesh.vertices[:, 0], gt_mesh.vertices[:, 1], gt_mesh.vertices[:, 2],
|
| 647 |
+
triangles=gt_mesh.faces, alpha=0.7, color='blue', edgecolor='none')
|
| 648 |
+
ax1.set_title(f'GT Mesh (Frame {frame_idx})')
|
| 649 |
+
ax1.set_xlabel('X')
|
| 650 |
+
ax1.set_ylabel('Y')
|
| 651 |
+
ax1.set_zlabel('Z')
|
| 652 |
+
ax1.set_xlim(-1, 1)
|
| 653 |
+
ax1.set_ylim(-1, 1)
|
| 654 |
+
ax1.set_zlim(-1, 1)
|
| 655 |
+
|
| 656 |
+
# Plot predicted mesh
|
| 657 |
+
ax2 = fig.add_subplot(132, projection='3d')
|
| 658 |
+
ax2.plot_trisurf(pred_mesh.vertices[:, 0], pred_mesh.vertices[:, 1], pred_mesh.vertices[:, 2],
|
| 659 |
+
triangles=pred_mesh.faces, alpha=0.7, color='red', edgecolor='none')
|
| 660 |
+
ax2.set_title(f'Predicted Mesh (Frame {frame_idx})')
|
| 661 |
+
ax2.set_xlabel('X')
|
| 662 |
+
ax2.set_ylabel('Y')
|
| 663 |
+
ax2.set_zlabel('Z')
|
| 664 |
+
ax2.set_xlim(-1, 1)
|
| 665 |
+
ax2.set_ylim(-1, 1)
|
| 666 |
+
ax2.set_zlim(-1, 1)
|
| 667 |
+
|
| 668 |
+
# Plot both together (wireframe for better visibility)
|
| 669 |
+
ax3 = fig.add_subplot(133, projection='3d')
|
| 670 |
+
ax3.plot_trisurf(gt_mesh.vertices[:, 0], gt_mesh.vertices[:, 1], gt_mesh.vertices[:, 2],
|
| 671 |
+
triangles=gt_mesh.faces, alpha=0.3, color='blue', edgecolor='none')
|
| 672 |
+
ax3.plot_trisurf(pred_mesh.vertices[:, 0], pred_mesh.vertices[:, 1], pred_mesh.vertices[:, 2],
|
| 673 |
+
triangles=pred_mesh.faces, alpha=0.3, color='red', edgecolor='none')
|
| 674 |
+
ax3.set_title(f'Mesh Overlay (Frame {frame_idx})')
|
| 675 |
+
ax3.set_xlabel('X')
|
| 676 |
+
ax3.set_ylabel('Y')
|
| 677 |
+
ax3.set_zlabel('Z')
|
| 678 |
+
ax3.set_xlim(-1, 1)
|
| 679 |
+
ax3.set_ylim(-1, 1)
|
| 680 |
+
ax3.set_zlim(-1, 1)
|
| 681 |
+
# Set viewing angle to 45 degrees
|
| 682 |
+
for ax in [ax1, ax2, ax3]:
|
| 683 |
+
ax.view_init(elev=30, azim=45)
|
| 684 |
+
plt.tight_layout()
|
| 685 |
+
save_path = os.path.join(viz_dir, f'mesh_comparison_frame_{frame_idx:04d}.png')
|
| 686 |
+
plt.savefig(save_path, dpi=150, bbox_inches='tight')
|
| 687 |
+
plt.close()
|
| 688 |
+
print(f"Saved mesh comparison to {save_path}")
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def visualize_pointcloud_comparison(gt_points, pred_points, frame_idx, viz_dir):
|
| 692 |
+
"""Visualize ground truth and predicted point clouds"""
|
| 693 |
+
fig = plt.figure(figsize=(15, 5))
|
| 694 |
+
|
| 695 |
+
# Plot GT points
|
| 696 |
+
ax1 = fig.add_subplot(131, projection='3d')
|
| 697 |
+
ax1.scatter(gt_points[:, 0], gt_points[:, 1], gt_points[:, 2],
|
| 698 |
+
c='blue', s=1, alpha=0.5, label='GT Points')
|
| 699 |
+
ax1.set_title(f'GT Point Cloud (Frame {frame_idx})')
|
| 700 |
+
ax1.set_xlabel('X')
|
| 701 |
+
ax1.set_ylabel('Y')
|
| 702 |
+
ax1.set_zlabel('Z')
|
| 703 |
+
ax1.set_xlim(-1, 1)
|
| 704 |
+
ax1.set_ylim(-1, 1)
|
| 705 |
+
ax1.set_zlim(-1, 1)
|
| 706 |
+
ax1.legend()
|
| 707 |
+
|
| 708 |
+
# Plot predicted points
|
| 709 |
+
ax2 = fig.add_subplot(132, projection='3d')
|
| 710 |
+
ax2.scatter(pred_points[:, 0], pred_points[:, 1], pred_points[:, 2],
|
| 711 |
+
c='red', s=1, alpha=0.5, label='Pred Points')
|
| 712 |
+
ax2.set_title(f'Predicted Point Cloud (Frame {frame_idx})')
|
| 713 |
+
ax2.set_xlabel('X')
|
| 714 |
+
ax2.set_ylabel('Y')
|
| 715 |
+
ax2.set_zlabel('Z')
|
| 716 |
+
ax2.set_xlim(-1, 1)
|
| 717 |
+
ax2.set_ylim(-1, 1)
|
| 718 |
+
ax2.set_zlim(-1, 1)
|
| 719 |
+
ax2.legend()
|
| 720 |
+
|
| 721 |
+
# Plot both together
|
| 722 |
+
ax3 = fig.add_subplot(133, projection='3d')
|
| 723 |
+
ax3.scatter(gt_points[:, 0], gt_points[:, 1], gt_points[:, 2],
|
| 724 |
+
c='blue', s=1, alpha=0.3, label='GT')
|
| 725 |
+
ax3.scatter(pred_points[:, 0], pred_points[:, 1], pred_points[:, 2],
|
| 726 |
+
c='red', s=1, alpha=0.3, label='Pred')
|
| 727 |
+
ax3.set_title(f'Point Cloud Overlay (Frame {frame_idx})')
|
| 728 |
+
ax3.set_xlabel('X')
|
| 729 |
+
ax3.set_ylabel('Y')
|
| 730 |
+
ax3.set_zlabel('Z')
|
| 731 |
+
ax3.set_xlim(-1, 1)
|
| 732 |
+
ax3.set_ylim(-1, 1)
|
| 733 |
+
ax3.set_zlim(-1, 1)
|
| 734 |
+
ax3.legend()
|
| 735 |
+
|
| 736 |
+
for ax in [ax1, ax2, ax3]:
|
| 737 |
+
ax.view_init(elev=30, azim=45)
|
| 738 |
+
|
| 739 |
+
plt.tight_layout()
|
| 740 |
+
save_path = os.path.join(viz_dir, f'pointcloud_comparison_frame_{frame_idx:04d}.png')
|
| 741 |
+
plt.savefig(save_path, dpi=150, bbox_inches='tight')
|
| 742 |
+
plt.close()
|
| 743 |
+
print(f"Saved point cloud comparison to {save_path}")
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def evaluate_sequence(gt_path, pred_path, num_samples=2048, viz=False, icp_viz=False):
|
| 747 |
+
"""Evaluate entire sequence"""
|
| 748 |
+
pred_path = Path(pred_path)
|
| 749 |
+
gt_path = Path(gt_path)
|
| 750 |
+
|
| 751 |
+
# Create visualization directory
|
| 752 |
+
viz_dir = Path(pred_path).parent.parent / 'viz'
|
| 753 |
+
viz_dir.mkdir(exist_ok=True)
|
| 754 |
+
print(f"Visualization directory: {viz_dir}")
|
| 755 |
+
|
| 756 |
+
# Initialize predicted mesh cache if loading from file
|
| 757 |
+
pred_mesh_cache = initialize_pred_mesh_cache(pred_path)
|
| 758 |
+
is_pred_file = pred_mesh_cache is not None
|
| 759 |
+
|
| 760 |
+
# Load GT frames from point cloud directory
|
| 761 |
+
print(f"Loading GT frames from {gt_path}...")
|
| 762 |
+
gt_frame_files = sorted(gt_path.glob("frame_*.npy"))
|
| 763 |
+
gt_frames = [np.load(f) for f in gt_frame_files]
|
| 764 |
+
print(f"Loaded {len(gt_frames)} frames from GT point clouds")
|
| 765 |
+
|
| 766 |
+
# Load GT faces
|
| 767 |
+
gt_faces_path = gt_path / "faces.npy"
|
| 768 |
+
if gt_faces_path.exists():
|
| 769 |
+
gt_faces = np.load(gt_faces_path)
|
| 770 |
+
print(f"Loaded GT faces from {gt_faces_path}")
|
| 771 |
+
else:
|
| 772 |
+
print(f"Warning: No faces.npy found in {gt_path}")
|
| 773 |
+
gt_faces = None
|
| 774 |
+
|
| 775 |
+
# Get number of frames from predicted mesh
|
| 776 |
+
if is_pred_file:
|
| 777 |
+
# Get frame count from Blender cache
|
| 778 |
+
num_frames = len(pred_mesh_cache['frames'])
|
| 779 |
+
print(f"Found {num_frames} frames in predicted mesh file")
|
| 780 |
+
# Extract predicted faces from first frame (they should be consistent)
|
| 781 |
+
pred_mesh_first = load_pred_mesh_from_file(pred_path, 0, pred_mesh_cache)
|
| 782 |
+
pred_faces = pred_mesh_first.faces
|
| 783 |
+
print(f"Loaded predicted faces from first frame: {len(pred_faces)} faces")
|
| 784 |
+
else:
|
| 785 |
+
# Get frame count from directory
|
| 786 |
+
frame_files = sorted(pred_path.glob("frame_*.npy"))
|
| 787 |
+
num_frames = len(frame_files)
|
| 788 |
+
print(f"Found {num_frames} frames in predicted data directory")
|
| 789 |
+
|
| 790 |
+
# Load predicted faces
|
| 791 |
+
pred_faces_path = pred_path / "faces.npy"
|
| 792 |
+
if pred_faces_path.exists():
|
| 793 |
+
pred_faces = np.load(pred_faces_path)
|
| 794 |
+
print(f"Loaded predicted faces from {pred_faces_path}")
|
| 795 |
+
else:
|
| 796 |
+
print(f"Warning: No faces.npy found in {pred_path}")
|
| 797 |
+
pred_faces = None
|
| 798 |
+
|
| 799 |
+
# Ensure we have enough GT frames
|
| 800 |
+
if len(gt_frames) < num_frames:
|
| 801 |
+
print(f"Warning: GT data has {len(gt_frames)} frames but prediction has {num_frames} frames")
|
| 802 |
+
print(f"Will repeat last frame to match predicted length")
|
| 803 |
+
while len(gt_frames) < num_frames:
|
| 804 |
+
gt_frames.append(gt_frames[-1].copy())
|
| 805 |
+
|
| 806 |
+
# Load first predicted frame for normalization
|
| 807 |
+
pred_mesh_0 = load_pred_mesh(pred_path, 0, pred_mesh_cache)
|
| 808 |
+
_, pred_center, pred_scale = normalize_mesh(pred_mesh_0)
|
| 809 |
+
|
| 810 |
+
print(f"Pred Normalization params - Center: {pred_center}, Scale: {pred_scale}")
|
| 811 |
+
|
| 812 |
+
# Normalize predicted frame 0
|
| 813 |
+
pred_vertices_0_norm = apply_normalization(pred_mesh_0.vertices, pred_center, pred_scale)
|
| 814 |
+
|
| 815 |
+
# Normalize GT frame 0
|
| 816 |
+
if gt_faces is not None:
|
| 817 |
+
gt_mesh_0 = trimesh.Trimesh(vertices=gt_frames[0], faces=gt_faces, process=False)
|
| 818 |
+
else:
|
| 819 |
+
gt_mesh_0 = trimesh.Trimesh(vertices=gt_frames[0], process=False)
|
| 820 |
+
_, gt_center, gt_scale = normalize_mesh(gt_mesh_0)
|
| 821 |
+
|
| 822 |
+
gt_vertices_0_norm = apply_normalization(gt_frames[0], gt_center, gt_scale)
|
| 823 |
+
print(f"GT Normalization params - Center: {gt_center}, Scale: {gt_scale}")
|
| 824 |
+
print(f"GT Normalization params - Min: {min(gt_vertices_0_norm[:, 0])}, Max: {max(gt_vertices_0_norm[:, 0])}")
|
| 825 |
+
print(f"GT Normalization params - Min: {min(gt_vertices_0_norm[:, 1])}, Max: {max(gt_vertices_0_norm[:, 1])}")
|
| 826 |
+
print(f"GT Normalization params - Min: {min(gt_vertices_0_norm[:, 2])}, Max: {max(gt_vertices_0_norm[:, 2])}")
|
| 827 |
+
# Load ICP alignment parameters
|
| 828 |
+
icp_params_path = viz_dir / 'icp_alignment_params.npz'
|
| 829 |
+
if icp_params_path.exists():
|
| 830 |
+
icp_params = np.load(icp_params_path)
|
| 831 |
+
R = icp_params['R']
|
| 832 |
+
t = icp_params['t']
|
| 833 |
+
s = icp_params['s']
|
| 834 |
+
print(f"Loaded ICP alignment parameters from {icp_params_path}")
|
| 835 |
+
print(f"R shape: {R.shape}, t shape: {t.shape}, s: {s}")
|
| 836 |
+
else:
|
| 837 |
+
print(f"No icp_alignment_params.npz found in {gt_path}")
|
| 838 |
+
print("Computing ICP alignment from first frame...")
|
| 839 |
+
# Make visualize for compute_alignment_from_first_frame configurable via arg
|
| 840 |
+
R, t, s = compute_alignment_from_first_frame(gt_path, pred_path, pred_mesh_cache, visualize=icp_viz)
|
| 841 |
+
print(f"ICP alignment computed - R shape: {R.shape}, t shape: {t.shape}, s: {s}")
|
| 842 |
+
|
| 843 |
+
# Store metrics for all frames
|
| 844 |
+
chamfer_distances = []
|
| 845 |
+
fscores = []
|
| 846 |
+
ious = []
|
| 847 |
+
if viz:
|
| 848 |
+
print(f"Visualization directory: {viz_dir}")
|
| 849 |
+
os.makedirs(viz_dir, exist_ok=True)
|
| 850 |
+
|
| 851 |
+
for frame_idx in range(num_frames):
|
| 852 |
+
print(f"\nProcessing frame {frame_idx}/{num_frames-1}...")
|
| 853 |
+
|
| 854 |
+
# Load predicted mesh and apply prediction normalization
|
| 855 |
+
pred_mesh = load_pred_mesh(pred_path, frame_idx, pred_mesh_cache)
|
| 856 |
+
pred_vertices_norm = apply_normalization(pred_mesh.vertices, pred_center, pred_scale)
|
| 857 |
+
# Use predicted faces from cache or from mesh
|
| 858 |
+
pred_faces_to_use = pred_faces if pred_faces is not None else pred_mesh.faces
|
| 859 |
+
pred_mesh_norm = trimesh.Trimesh(vertices=pred_vertices_norm, faces=pred_faces_to_use, process=False)
|
| 860 |
+
|
| 861 |
+
# Get GT frame, apply GT normalization, then apply ICP alignment
|
| 862 |
+
gt_vertices = gt_frames[frame_idx]
|
| 863 |
+
gt_vertices_norm = apply_normalization(gt_vertices, gt_center, gt_scale)
|
| 864 |
+
gt_vertices_aligned = apply_icp_alignment(gt_vertices_norm, R, t, s)
|
| 865 |
+
if gt_faces is not None:
|
| 866 |
+
gt_mesh_aligned = trimesh.Trimesh(vertices=gt_vertices_aligned, faces=gt_faces, process=False)
|
| 867 |
+
else:
|
| 868 |
+
gt_mesh_aligned = trimesh.Trimesh(vertices=gt_vertices_aligned, process=False)
|
| 869 |
+
|
| 870 |
+
# Visualize mesh comparison for every frame
|
| 871 |
+
#print(f"Visualizing mesh comparison for frame {frame_idx}...")
|
| 872 |
+
if viz:
|
| 873 |
+
visualize_mesh_comparison(gt_mesh_aligned, pred_mesh_norm, frame_idx, viz_dir)
|
| 874 |
+
|
| 875 |
+
# Sample points
|
| 876 |
+
gt_points = sample_points_from_mesh(gt_mesh_aligned, num_samples)
|
| 877 |
+
pred_points = sample_points_from_mesh(pred_mesh_norm, num_samples)
|
| 878 |
+
|
| 879 |
+
# Visualize point cloud comparison for every frame
|
| 880 |
+
#print(f"Visualizing point cloud comparison for frame {frame_idx}...")
|
| 881 |
+
|
| 882 |
+
#visualize_pointcloud_comparison(gt_points, pred_points, frame_idx, viz_dir)
|
| 883 |
+
# Compute metrics
|
| 884 |
+
chamfer = compute_chamfer_distance(gt_points, pred_points)
|
| 885 |
+
fscore = compute_fscore(gt_points, pred_points, threshold=0.02)
|
| 886 |
+
# iou = compute_iou_voxel(gt_mesh_aligned, pred_mesh_norm, resolution=128)
|
| 887 |
+
|
| 888 |
+
chamfer_distances.append(chamfer)
|
| 889 |
+
fscores.append(fscore)
|
| 890 |
+
# ious.append(iou)
|
| 891 |
+
|
| 892 |
+
print(f"Frame {frame_idx} - Chamfer: {chamfer:.6f}, F-score: {fscore:.4f}")
|
| 893 |
+
|
| 894 |
+
# Print summary statistics
|
| 895 |
+
print("\n" + "="*50)
|
| 896 |
+
print("Summary Statistics:")
|
| 897 |
+
print("="*50)
|
| 898 |
+
print(f"Chamfer Distance - Mean: {np.mean(chamfer_distances):.6f}, Std: {np.std(chamfer_distances):.6f}")
|
| 899 |
+
print(f"F-score - Mean: {np.mean(fscores):.4f}, Std: {np.std(fscores):.4f}")
|
| 900 |
+
# print(f"IoU - Mean: {np.mean(ious):.4f}, Std: {np.std(ious):.4f}")
|
| 901 |
+
|
| 902 |
+
# Save results to txt file in gt_path
|
| 903 |
+
gt_path_obj = Path(gt_path)
|
| 904 |
+
os.makedirs(gt_path_obj, exist_ok=True)
|
| 905 |
+
results_txt_path = gt_path_obj / 'evaluation_results.txt'
|
| 906 |
+
with open(results_txt_path, 'w') as f:
|
| 907 |
+
f.write(f"{gt_path_obj.name}\n")
|
| 908 |
+
f.write(f"cd_mean_{np.mean(chamfer_distances):.6f}\n")
|
| 909 |
+
f.write(f"fs_mean_{np.mean(fscores):.6f}\n")
|
| 910 |
+
print(f"\nResults saved to {results_txt_path}")
|
| 911 |
+
|
| 912 |
+
return {
|
| 913 |
+
'chamfer_distances': chamfer_distances,
|
| 914 |
+
'fscores': fscores,
|
| 915 |
+
# 'ious': ious
|
| 916 |
+
}
|
| 917 |
+
|
| 918 |
+
|
| 919 |
+
def main():
|
| 920 |
+
parser = argparse.ArgumentParser(description='Evaluate mesh reconstruction quality')
|
| 921 |
+
parser.add_argument('--gt_path', type=str, required=True,
|
| 922 |
+
help='Path to ground-truth point cloud directory (contains faces.npy and frame_*.npy)')
|
| 923 |
+
parser.add_argument('--pred_path', type=str, required=True,
|
| 924 |
+
help='Path to predicted data (contains faces.npy and frame_*.npy)')
|
| 925 |
+
parser.add_argument('--num_samples', type=int, default=50000,
|
| 926 |
+
help='Number of points to sample from each mesh')
|
| 927 |
+
parser.add_argument('--viz', action='store_true',
|
| 928 |
+
help='Visualize point clouds and meshes')
|
| 929 |
+
parser.add_argument('--icp_viz', action='store_true',
|
| 930 |
+
help='Visualize ICP alignment procedure for first frame')
|
| 931 |
+
|
| 932 |
+
args = parser.parse_args()
|
| 933 |
+
|
| 934 |
+
results = evaluate_sequence(args.gt_path, args.pred_path, args.num_samples, args.viz, icp_viz=args.icp_viz)
|
| 935 |
+
|
| 936 |
+
print(f"\nResults saved to {args.pred_path}")
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
if __name__ == '__main__':
|
| 940 |
+
main()
|
OVOW/third_party/Motion324/evaluation/fvd/styleganv/fvd.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import os
|
| 3 |
+
import math
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
|
| 6 |
+
# https://github.com/universome/fvd-comparison
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def load_i3d_pretrained(device=torch.device('cpu')):
|
| 10 |
+
i3D_WEIGHTS_URL = "https://www.dropbox.com/s/ge9e5ujwgetktms/i3d_torchscript.pt"
|
| 11 |
+
filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'i3d_torchscript.pt')
|
| 12 |
+
print('Loading model from: %s'%filepath)
|
| 13 |
+
if not os.path.exists(filepath):
|
| 14 |
+
print(f"preparing for download {i3D_WEIGHTS_URL}, you can download it by yourself.")
|
| 15 |
+
os.system(f"wget {i3D_WEIGHTS_URL} -O {filepath}")
|
| 16 |
+
i3d = torch.jit.load(filepath).eval().to(device)
|
| 17 |
+
i3d = torch.nn.DataParallel(i3d)
|
| 18 |
+
return i3d
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_feats(videos, detector, device, bs=10):
|
| 22 |
+
# videos : torch.tensor BCTHW [0, 1]
|
| 23 |
+
detector_kwargs = dict(rescale=False, resize=False, return_features=True) # Return raw features before the softmax layer.
|
| 24 |
+
feats = np.empty((0, 400))
|
| 25 |
+
with torch.no_grad():
|
| 26 |
+
for i in range((len(videos)-1)//bs + 1):
|
| 27 |
+
feats = np.vstack([feats, detector(x=torch.stack([preprocess_single(video) for video in videos[i*bs:(i+1)*bs]]).to(device), **detector_kwargs).detach().cpu().numpy()])
|
| 28 |
+
return feats
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_fvd_feats(videos, i3d, device, bs=10):
|
| 32 |
+
# videos in [0, 1] as torch tensor BCTHW
|
| 33 |
+
# videos = [preprocess_single(video) for video in videos]
|
| 34 |
+
embeddings = get_feats(videos, i3d, device, bs)
|
| 35 |
+
return embeddings
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def preprocess_single(video, resolution=224, sequence_length=None):
|
| 39 |
+
# video: CTHW, [0, 1]
|
| 40 |
+
c, t, h, w = video.shape
|
| 41 |
+
|
| 42 |
+
# temporal crop
|
| 43 |
+
if sequence_length is not None:
|
| 44 |
+
assert sequence_length <= t
|
| 45 |
+
video = video[:, :sequence_length]
|
| 46 |
+
|
| 47 |
+
# scale shorter side to resolution
|
| 48 |
+
scale = resolution / min(h, w)
|
| 49 |
+
if h < w:
|
| 50 |
+
target_size = (resolution, math.ceil(w * scale))
|
| 51 |
+
else:
|
| 52 |
+
target_size = (math.ceil(h * scale), resolution)
|
| 53 |
+
video = F.interpolate(video, size=target_size, mode='bilinear', align_corners=False)
|
| 54 |
+
|
| 55 |
+
# center crop
|
| 56 |
+
c, t, h, w = video.shape
|
| 57 |
+
w_start = (w - resolution) // 2
|
| 58 |
+
h_start = (h - resolution) // 2
|
| 59 |
+
video = video[:, :, h_start:h_start + resolution, w_start:w_start + resolution]
|
| 60 |
+
|
| 61 |
+
# [0, 1] -> [-1, 1]
|
| 62 |
+
video = (video - 0.5) * 2
|
| 63 |
+
|
| 64 |
+
return video.contiguous()
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
Copy-pasted from https://github.com/cvpr2022-stylegan-v/stylegan-v/blob/main/src/metrics/frechet_video_distance.py
|
| 69 |
+
"""
|
| 70 |
+
from typing import Tuple
|
| 71 |
+
from scipy.linalg import sqrtm
|
| 72 |
+
import numpy as np
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def compute_stats(feats: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
|
| 76 |
+
mu = feats.mean(axis=0) # [d]
|
| 77 |
+
sigma = np.cov(feats, rowvar=False) # [d, d]
|
| 78 |
+
return mu, sigma
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def frechet_distance(feats_fake: np.ndarray, feats_real: np.ndarray) -> float:
|
| 82 |
+
mu_gen, sigma_gen = compute_stats(feats_fake)
|
| 83 |
+
mu_real, sigma_real = compute_stats(feats_real)
|
| 84 |
+
m = np.square(mu_gen - mu_real).sum()
|
| 85 |
+
if feats_fake.shape[0]>1:
|
| 86 |
+
s, _ = sqrtm(np.dot(sigma_gen, sigma_real), disp=False) # pylint: disable=no-member
|
| 87 |
+
fid = np.real(m + np.trace(sigma_gen + sigma_real - s * 2))
|
| 88 |
+
else:
|
| 89 |
+
fid = np.real(m)
|
| 90 |
+
return float(fid)
|
OVOW/third_party/Motion324/evaluation/lpips/__init__.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from __future__ import absolute_import
|
| 3 |
+
from __future__ import division
|
| 4 |
+
from __future__ import print_function
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
# from torch.autograd import Variable
|
| 9 |
+
|
| 10 |
+
from lpips.trainer import *
|
| 11 |
+
from lpips.lpips import *
|
| 12 |
+
|
| 13 |
+
def normalize_tensor(in_feat,eps=1e-10):
|
| 14 |
+
norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1,keepdim=True))
|
| 15 |
+
return in_feat/(norm_factor+eps)
|
| 16 |
+
|
| 17 |
+
def l2(p0, p1, range=255.):
|
| 18 |
+
return .5*np.mean((p0 / range - p1 / range)**2)
|
| 19 |
+
|
| 20 |
+
def psnr(p0, p1, peak=255.):
|
| 21 |
+
return 10*np.log10(peak**2/np.mean((1.*p0-1.*p1)**2))
|
| 22 |
+
|
| 23 |
+
def dssim(p0, p1, range=255.):
|
| 24 |
+
from skimage.measure import compare_ssim
|
| 25 |
+
return (1 - compare_ssim(p0, p1, data_range=range, multichannel=True)) / 2.
|
| 26 |
+
|
| 27 |
+
def tensor2np(tensor_obj):
|
| 28 |
+
# change dimension of a tensor object into a numpy array
|
| 29 |
+
return tensor_obj[0].cpu().float().numpy().transpose((1,2,0))
|
| 30 |
+
|
| 31 |
+
def np2tensor(np_obj):
|
| 32 |
+
# change dimenion of np array into tensor array
|
| 33 |
+
return torch.Tensor(np_obj[:, :, :, np.newaxis].transpose((3, 2, 0, 1)))
|
| 34 |
+
|
| 35 |
+
def tensor2tensorlab(image_tensor,to_norm=True,mc_only=False):
|
| 36 |
+
# image tensor to lab tensor
|
| 37 |
+
from skimage import color
|
| 38 |
+
|
| 39 |
+
img = tensor2im(image_tensor)
|
| 40 |
+
img_lab = color.rgb2lab(img)
|
| 41 |
+
if(mc_only):
|
| 42 |
+
img_lab[:,:,0] = img_lab[:,:,0]-50
|
| 43 |
+
if(to_norm and not mc_only):
|
| 44 |
+
img_lab[:,:,0] = img_lab[:,:,0]-50
|
| 45 |
+
img_lab = img_lab/100.
|
| 46 |
+
|
| 47 |
+
return np2tensor(img_lab)
|
| 48 |
+
|
| 49 |
+
def tensorlab2tensor(lab_tensor,return_inbnd=False):
|
| 50 |
+
from skimage import color
|
| 51 |
+
import warnings
|
| 52 |
+
warnings.filterwarnings("ignore")
|
| 53 |
+
|
| 54 |
+
lab = tensor2np(lab_tensor)*100.
|
| 55 |
+
lab[:,:,0] = lab[:,:,0]+50
|
| 56 |
+
|
| 57 |
+
rgb_back = 255.*np.clip(color.lab2rgb(lab.astype('float')),0,1)
|
| 58 |
+
if(return_inbnd):
|
| 59 |
+
# convert back to lab, see if we match
|
| 60 |
+
lab_back = color.rgb2lab(rgb_back.astype('uint8'))
|
| 61 |
+
mask = 1.*np.isclose(lab_back,lab,atol=2.)
|
| 62 |
+
mask = np2tensor(np.prod(mask,axis=2)[:,:,np.newaxis])
|
| 63 |
+
return (im2tensor(rgb_back),mask)
|
| 64 |
+
else:
|
| 65 |
+
return im2tensor(rgb_back)
|
| 66 |
+
|
| 67 |
+
def load_image(path):
|
| 68 |
+
if(path[-3:] == 'dng'):
|
| 69 |
+
import rawpy
|
| 70 |
+
with rawpy.imread(path) as raw:
|
| 71 |
+
img = raw.postprocess()
|
| 72 |
+
elif(path[-3:]=='bmp' or path[-3:]=='jpg' or path[-3:]=='png' or path[-4:]=='jpeg'):
|
| 73 |
+
import cv2
|
| 74 |
+
return cv2.imread(path)[:,:,::-1]
|
| 75 |
+
else:
|
| 76 |
+
import matplotlib.pyplot as plt
|
| 77 |
+
img = (255*plt.imread(path)[:,:,:3]).astype('uint8')
|
| 78 |
+
|
| 79 |
+
return img
|
| 80 |
+
|
| 81 |
+
def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=255./2.):
|
| 82 |
+
image_numpy = image_tensor[0].cpu().float().numpy()
|
| 83 |
+
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + cent) * factor
|
| 84 |
+
return image_numpy.astype(imtype)
|
| 85 |
+
|
| 86 |
+
def im2tensor(image, imtype=np.uint8, cent=1., factor=255./2.):
|
| 87 |
+
return torch.Tensor((image / factor - cent)
|
| 88 |
+
[:, :, :, np.newaxis].transpose((3, 2, 0, 1)))
|
| 89 |
+
|
| 90 |
+
def tensor2vec(vector_tensor):
|
| 91 |
+
return vector_tensor.data.cpu().numpy()[:, :, 0, 0]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def voc_ap(rec, prec, use_07_metric=False):
|
| 95 |
+
""" ap = voc_ap(rec, prec, [use_07_metric])
|
| 96 |
+
Compute VOC AP given precision and recall.
|
| 97 |
+
If use_07_metric is true, uses the
|
| 98 |
+
VOC 07 11 point method (default:False).
|
| 99 |
+
"""
|
| 100 |
+
if use_07_metric:
|
| 101 |
+
# 11 point metric
|
| 102 |
+
ap = 0.
|
| 103 |
+
for t in np.arange(0., 1.1, 0.1):
|
| 104 |
+
if np.sum(rec >= t) == 0:
|
| 105 |
+
p = 0
|
| 106 |
+
else:
|
| 107 |
+
p = np.max(prec[rec >= t])
|
| 108 |
+
ap = ap + p / 11.
|
| 109 |
+
else:
|
| 110 |
+
# correct AP calculation
|
| 111 |
+
# first append sentinel values at the end
|
| 112 |
+
mrec = np.concatenate(([0.], rec, [1.]))
|
| 113 |
+
mpre = np.concatenate(([0.], prec, [0.]))
|
| 114 |
+
|
| 115 |
+
# compute the precision envelope
|
| 116 |
+
for i in range(mpre.size - 1, 0, -1):
|
| 117 |
+
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
|
| 118 |
+
|
| 119 |
+
# to calculate area under PR curve, look for points
|
| 120 |
+
# where X axis (recall) changes value
|
| 121 |
+
i = np.where(mrec[1:] != mrec[:-1])[0]
|
| 122 |
+
|
| 123 |
+
# and sum (\Delta recall) * prec
|
| 124 |
+
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
|
| 125 |
+
return ap
|
| 126 |
+
|
OVOW/third_party/Motion324/evaluation/lpips/lpips.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from __future__ import absolute_import
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.init as init
|
| 7 |
+
from torch.autograd import Variable
|
| 8 |
+
import numpy as np
|
| 9 |
+
from . import pretrained_networks as pn
|
| 10 |
+
import torch.nn
|
| 11 |
+
|
| 12 |
+
import lpips
|
| 13 |
+
|
| 14 |
+
def spatial_average(in_tens, keepdim=True):
|
| 15 |
+
return in_tens.mean([2,3],keepdim=keepdim)
|
| 16 |
+
|
| 17 |
+
def upsample(in_tens, out_HW=(64,64)): # assumes scale factor is same for H and W
|
| 18 |
+
in_H, in_W = in_tens.shape[2], in_tens.shape[3]
|
| 19 |
+
return nn.Upsample(size=out_HW, mode='bilinear', align_corners=False)(in_tens)
|
| 20 |
+
|
| 21 |
+
# Learned perceptual metric
|
| 22 |
+
class LPIPS(nn.Module):
|
| 23 |
+
def __init__(self, pretrained=True, net='alex', version='0.1', lpips=True, spatial=False,
|
| 24 |
+
pnet_rand=False, pnet_tune=False, use_dropout=True, model_path=None, eval_mode=True, verbose=True):
|
| 25 |
+
""" Initializes a perceptual loss torch.nn.Module
|
| 26 |
+
|
| 27 |
+
Parameters (default listed first)
|
| 28 |
+
---------------------------------
|
| 29 |
+
lpips : bool
|
| 30 |
+
[True] use linear layers on top of base/trunk network
|
| 31 |
+
[False] means no linear layers; each layer is averaged together
|
| 32 |
+
pretrained : bool
|
| 33 |
+
This flag controls the linear layers, which are only in effect when lpips=True above
|
| 34 |
+
[True] means linear layers are calibrated with human perceptual judgments
|
| 35 |
+
[False] means linear layers are randomly initialized
|
| 36 |
+
pnet_rand : bool
|
| 37 |
+
[False] means trunk loaded with ImageNet classification weights
|
| 38 |
+
[True] means randomly initialized trunk
|
| 39 |
+
net : str
|
| 40 |
+
['alex','vgg','squeeze'] are the base/trunk networks available
|
| 41 |
+
version : str
|
| 42 |
+
['v0.1'] is the default and latest
|
| 43 |
+
['v0.0'] contained a normalization bug; corresponds to old arxiv v1 (https://arxiv.org/abs/1801.03924v1)
|
| 44 |
+
model_path : 'str'
|
| 45 |
+
[None] is default and loads the pretrained weights from paper https://arxiv.org/abs/1801.03924v1
|
| 46 |
+
|
| 47 |
+
The following parameters should only be changed if training the network
|
| 48 |
+
|
| 49 |
+
eval_mode : bool
|
| 50 |
+
[True] is for test mode (default)
|
| 51 |
+
[False] is for training mode
|
| 52 |
+
pnet_tune
|
| 53 |
+
[False] keep base/trunk frozen
|
| 54 |
+
[True] tune the base/trunk network
|
| 55 |
+
use_dropout : bool
|
| 56 |
+
[True] to use dropout when training linear layers
|
| 57 |
+
[False] for no dropout when training linear layers
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
super(LPIPS, self).__init__()
|
| 61 |
+
if(verbose):
|
| 62 |
+
print('Setting up [%s] perceptual loss: trunk [%s], v[%s], spatial [%s]'%
|
| 63 |
+
('LPIPS' if lpips else 'baseline', net, version, 'on' if spatial else 'off'))
|
| 64 |
+
|
| 65 |
+
self.pnet_type = net
|
| 66 |
+
self.pnet_tune = pnet_tune
|
| 67 |
+
self.pnet_rand = pnet_rand
|
| 68 |
+
self.spatial = spatial
|
| 69 |
+
self.lpips = lpips # false means baseline of just averaging all layers
|
| 70 |
+
self.version = version
|
| 71 |
+
self.scaling_layer = ScalingLayer()
|
| 72 |
+
|
| 73 |
+
if(self.pnet_type in ['vgg','vgg16']):
|
| 74 |
+
net_type = pn.vgg16
|
| 75 |
+
self.chns = [64,128,256,512,512]
|
| 76 |
+
elif(self.pnet_type=='alex'):
|
| 77 |
+
net_type = pn.alexnet
|
| 78 |
+
self.chns = [64,192,384,256,256]
|
| 79 |
+
elif(self.pnet_type=='squeeze'):
|
| 80 |
+
net_type = pn.squeezenet
|
| 81 |
+
self.chns = [64,128,256,384,384,512,512]
|
| 82 |
+
self.L = len(self.chns)
|
| 83 |
+
|
| 84 |
+
self.net = net_type(pretrained=not self.pnet_rand, requires_grad=self.pnet_tune)
|
| 85 |
+
|
| 86 |
+
if(lpips):
|
| 87 |
+
self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
|
| 88 |
+
self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
|
| 89 |
+
self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
|
| 90 |
+
self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
|
| 91 |
+
self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
|
| 92 |
+
self.lins = [self.lin0,self.lin1,self.lin2,self.lin3,self.lin4]
|
| 93 |
+
if(self.pnet_type=='squeeze'): # 7 layers for squeezenet
|
| 94 |
+
self.lin5 = NetLinLayer(self.chns[5], use_dropout=use_dropout)
|
| 95 |
+
self.lin6 = NetLinLayer(self.chns[6], use_dropout=use_dropout)
|
| 96 |
+
self.lins+=[self.lin5,self.lin6]
|
| 97 |
+
self.lins = nn.ModuleList(self.lins)
|
| 98 |
+
|
| 99 |
+
if(pretrained):
|
| 100 |
+
if(model_path is None):
|
| 101 |
+
import inspect
|
| 102 |
+
import os
|
| 103 |
+
model_path = os.path.abspath(os.path.join(inspect.getfile(self.__init__), '..', 'weights/v%s/%s.pth'%(version,net)))
|
| 104 |
+
|
| 105 |
+
if(verbose):
|
| 106 |
+
print('Loading model from: %s'%model_path)
|
| 107 |
+
self.load_state_dict(torch.load(model_path, map_location='cpu'), strict=False)
|
| 108 |
+
|
| 109 |
+
if(eval_mode):
|
| 110 |
+
self.eval()
|
| 111 |
+
|
| 112 |
+
def forward(self, in0, in1, retPerLayer=False, normalize=False):
|
| 113 |
+
if normalize: # turn on this flag if input is [0,1] so it can be adjusted to [-1, +1]
|
| 114 |
+
in0 = 2 * in0 - 1
|
| 115 |
+
in1 = 2 * in1 - 1
|
| 116 |
+
|
| 117 |
+
# v0.0 - original release had a bug, where input was not scaled
|
| 118 |
+
in0_input, in1_input = (self.scaling_layer(in0), self.scaling_layer(in1)) if self.version=='0.1' else (in0, in1)
|
| 119 |
+
outs0, outs1 = self.net.forward(in0_input), self.net.forward(in1_input)
|
| 120 |
+
feats0, feats1, diffs = {}, {}, {}
|
| 121 |
+
|
| 122 |
+
for kk in range(self.L):
|
| 123 |
+
feats0[kk], feats1[kk] = lpips.normalize_tensor(outs0[kk]), lpips.normalize_tensor(outs1[kk])
|
| 124 |
+
diffs[kk] = (feats0[kk]-feats1[kk])**2
|
| 125 |
+
|
| 126 |
+
if(self.lpips):
|
| 127 |
+
if(self.spatial):
|
| 128 |
+
res = [upsample(self.lins[kk](diffs[kk]), out_HW=in0.shape[2:]) for kk in range(self.L)]
|
| 129 |
+
else:
|
| 130 |
+
res = [spatial_average(self.lins[kk](diffs[kk]), keepdim=True) for kk in range(self.L)]
|
| 131 |
+
else:
|
| 132 |
+
if(self.spatial):
|
| 133 |
+
res = [upsample(diffs[kk].sum(dim=1,keepdim=True), out_HW=in0.shape[2:]) for kk in range(self.L)]
|
| 134 |
+
else:
|
| 135 |
+
res = [spatial_average(diffs[kk].sum(dim=1,keepdim=True), keepdim=True) for kk in range(self.L)]
|
| 136 |
+
|
| 137 |
+
val = 0
|
| 138 |
+
for l in range(self.L):
|
| 139 |
+
val += res[l]
|
| 140 |
+
|
| 141 |
+
if(retPerLayer):
|
| 142 |
+
return (val, res)
|
| 143 |
+
else:
|
| 144 |
+
return val
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class ScalingLayer(nn.Module):
|
| 148 |
+
def __init__(self):
|
| 149 |
+
super(ScalingLayer, self).__init__()
|
| 150 |
+
self.register_buffer('shift', torch.Tensor([-.030,-.088,-.188])[None,:,None,None])
|
| 151 |
+
self.register_buffer('scale', torch.Tensor([.458,.448,.450])[None,:,None,None])
|
| 152 |
+
|
| 153 |
+
def forward(self, inp):
|
| 154 |
+
return (inp - self.shift) / self.scale
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class NetLinLayer(nn.Module):
|
| 158 |
+
''' A single linear layer which does a 1x1 conv '''
|
| 159 |
+
def __init__(self, chn_in, chn_out=1, use_dropout=False):
|
| 160 |
+
super(NetLinLayer, self).__init__()
|
| 161 |
+
|
| 162 |
+
layers = [nn.Dropout(),] if(use_dropout) else []
|
| 163 |
+
layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False),]
|
| 164 |
+
self.model = nn.Sequential(*layers)
|
| 165 |
+
|
| 166 |
+
def forward(self, x):
|
| 167 |
+
return self.model(x)
|
| 168 |
+
|
| 169 |
+
class Dist2LogitLayer(nn.Module):
|
| 170 |
+
''' takes 2 distances, puts through fc layers, spits out value between [0,1] (if use_sigmoid is True) '''
|
| 171 |
+
def __init__(self, chn_mid=32, use_sigmoid=True):
|
| 172 |
+
super(Dist2LogitLayer, self).__init__()
|
| 173 |
+
|
| 174 |
+
layers = [nn.Conv2d(5, chn_mid, 1, stride=1, padding=0, bias=True),]
|
| 175 |
+
layers += [nn.LeakyReLU(0.2,True),]
|
| 176 |
+
layers += [nn.Conv2d(chn_mid, chn_mid, 1, stride=1, padding=0, bias=True),]
|
| 177 |
+
layers += [nn.LeakyReLU(0.2,True),]
|
| 178 |
+
layers += [nn.Conv2d(chn_mid, 1, 1, stride=1, padding=0, bias=True),]
|
| 179 |
+
if(use_sigmoid):
|
| 180 |
+
layers += [nn.Sigmoid(),]
|
| 181 |
+
self.model = nn.Sequential(*layers)
|
| 182 |
+
|
| 183 |
+
def forward(self,d0,d1,eps=0.1):
|
| 184 |
+
return self.model.forward(torch.cat((d0,d1,d0-d1,d0/(d1+eps),d1/(d0+eps)),dim=1))
|
| 185 |
+
|
| 186 |
+
class BCERankingLoss(nn.Module):
|
| 187 |
+
def __init__(self, chn_mid=32):
|
| 188 |
+
super(BCERankingLoss, self).__init__()
|
| 189 |
+
self.net = Dist2LogitLayer(chn_mid=chn_mid)
|
| 190 |
+
# self.parameters = list(self.net.parameters())
|
| 191 |
+
self.loss = torch.nn.BCELoss()
|
| 192 |
+
|
| 193 |
+
def forward(self, d0, d1, judge):
|
| 194 |
+
per = (judge+1.)/2.
|
| 195 |
+
self.logit = self.net.forward(d0,d1)
|
| 196 |
+
return self.loss(self.logit, per)
|
| 197 |
+
|
| 198 |
+
# L2, DSSIM metrics
|
| 199 |
+
class FakeNet(nn.Module):
|
| 200 |
+
def __init__(self, use_gpu=True, colorspace='Lab'):
|
| 201 |
+
super(FakeNet, self).__init__()
|
| 202 |
+
self.use_gpu = use_gpu
|
| 203 |
+
self.colorspace = colorspace
|
| 204 |
+
|
| 205 |
+
class L2(FakeNet):
|
| 206 |
+
def forward(self, in0, in1, retPerLayer=None):
|
| 207 |
+
assert(in0.size()[0]==1) # currently only supports batchSize 1
|
| 208 |
+
|
| 209 |
+
if(self.colorspace=='RGB'):
|
| 210 |
+
(N,C,X,Y) = in0.size()
|
| 211 |
+
value = torch.mean(torch.mean(torch.mean((in0-in1)**2,dim=1).view(N,1,X,Y),dim=2).view(N,1,1,Y),dim=3).view(N)
|
| 212 |
+
return value
|
| 213 |
+
elif(self.colorspace=='Lab'):
|
| 214 |
+
value = lpips.l2(lpips.tensor2np(lpips.tensor2tensorlab(in0.data,to_norm=False)),
|
| 215 |
+
lpips.tensor2np(lpips.tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float')
|
| 216 |
+
ret_var = Variable( torch.Tensor((value,) ) )
|
| 217 |
+
if(self.use_gpu):
|
| 218 |
+
ret_var = ret_var.cuda()
|
| 219 |
+
return ret_var
|
| 220 |
+
|
| 221 |
+
class DSSIM(FakeNet):
|
| 222 |
+
|
| 223 |
+
def forward(self, in0, in1, retPerLayer=None):
|
| 224 |
+
assert(in0.size()[0]==1) # currently only supports batchSize 1
|
| 225 |
+
|
| 226 |
+
if(self.colorspace=='RGB'):
|
| 227 |
+
value = lpips.dssim(1.*lpips.tensor2im(in0.data), 1.*lpips.tensor2im(in1.data), range=255.).astype('float')
|
| 228 |
+
elif(self.colorspace=='Lab'):
|
| 229 |
+
value = lpips.dssim(lpips.tensor2np(lpips.tensor2tensorlab(in0.data,to_norm=False)),
|
| 230 |
+
lpips.tensor2np(lpips.tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float')
|
| 231 |
+
ret_var = Variable( torch.Tensor((value,) ) )
|
| 232 |
+
if(self.use_gpu):
|
| 233 |
+
ret_var = ret_var.cuda()
|
| 234 |
+
return ret_var
|
| 235 |
+
|
| 236 |
+
def print_network(net):
|
| 237 |
+
num_params = 0
|
| 238 |
+
for param in net.parameters():
|
| 239 |
+
num_params += param.numel()
|
| 240 |
+
print('Network',net)
|
| 241 |
+
print('Total number of parameters: %d' % num_params)
|
OVOW/third_party/Motion324/evaluation/lpips/pretrained_networks.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
import torch
|
| 3 |
+
from torchvision import models as tv
|
| 4 |
+
|
| 5 |
+
class squeezenet(torch.nn.Module):
|
| 6 |
+
def __init__(self, requires_grad=False, pretrained=True):
|
| 7 |
+
super(squeezenet, self).__init__()
|
| 8 |
+
pretrained_features = tv.squeezenet1_1(pretrained=pretrained).features
|
| 9 |
+
self.slice1 = torch.nn.Sequential()
|
| 10 |
+
self.slice2 = torch.nn.Sequential()
|
| 11 |
+
self.slice3 = torch.nn.Sequential()
|
| 12 |
+
self.slice4 = torch.nn.Sequential()
|
| 13 |
+
self.slice5 = torch.nn.Sequential()
|
| 14 |
+
self.slice6 = torch.nn.Sequential()
|
| 15 |
+
self.slice7 = torch.nn.Sequential()
|
| 16 |
+
self.N_slices = 7
|
| 17 |
+
for x in range(2):
|
| 18 |
+
self.slice1.add_module(str(x), pretrained_features[x])
|
| 19 |
+
for x in range(2,5):
|
| 20 |
+
self.slice2.add_module(str(x), pretrained_features[x])
|
| 21 |
+
for x in range(5, 8):
|
| 22 |
+
self.slice3.add_module(str(x), pretrained_features[x])
|
| 23 |
+
for x in range(8, 10):
|
| 24 |
+
self.slice4.add_module(str(x), pretrained_features[x])
|
| 25 |
+
for x in range(10, 11):
|
| 26 |
+
self.slice5.add_module(str(x), pretrained_features[x])
|
| 27 |
+
for x in range(11, 12):
|
| 28 |
+
self.slice6.add_module(str(x), pretrained_features[x])
|
| 29 |
+
for x in range(12, 13):
|
| 30 |
+
self.slice7.add_module(str(x), pretrained_features[x])
|
| 31 |
+
if not requires_grad:
|
| 32 |
+
for param in self.parameters():
|
| 33 |
+
param.requires_grad = False
|
| 34 |
+
|
| 35 |
+
def forward(self, X):
|
| 36 |
+
h = self.slice1(X)
|
| 37 |
+
h_relu1 = h
|
| 38 |
+
h = self.slice2(h)
|
| 39 |
+
h_relu2 = h
|
| 40 |
+
h = self.slice3(h)
|
| 41 |
+
h_relu3 = h
|
| 42 |
+
h = self.slice4(h)
|
| 43 |
+
h_relu4 = h
|
| 44 |
+
h = self.slice5(h)
|
| 45 |
+
h_relu5 = h
|
| 46 |
+
h = self.slice6(h)
|
| 47 |
+
h_relu6 = h
|
| 48 |
+
h = self.slice7(h)
|
| 49 |
+
h_relu7 = h
|
| 50 |
+
vgg_outputs = namedtuple("SqueezeOutputs", ['relu1','relu2','relu3','relu4','relu5','relu6','relu7'])
|
| 51 |
+
out = vgg_outputs(h_relu1,h_relu2,h_relu3,h_relu4,h_relu5,h_relu6,h_relu7)
|
| 52 |
+
|
| 53 |
+
return out
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class alexnet(torch.nn.Module):
|
| 57 |
+
def __init__(self, requires_grad=False, pretrained=True):
|
| 58 |
+
super(alexnet, self).__init__()
|
| 59 |
+
alexnet_pretrained_features = tv.alexnet(pretrained=pretrained).features
|
| 60 |
+
self.slice1 = torch.nn.Sequential()
|
| 61 |
+
self.slice2 = torch.nn.Sequential()
|
| 62 |
+
self.slice3 = torch.nn.Sequential()
|
| 63 |
+
self.slice4 = torch.nn.Sequential()
|
| 64 |
+
self.slice5 = torch.nn.Sequential()
|
| 65 |
+
self.N_slices = 5
|
| 66 |
+
for x in range(2):
|
| 67 |
+
self.slice1.add_module(str(x), alexnet_pretrained_features[x])
|
| 68 |
+
for x in range(2, 5):
|
| 69 |
+
self.slice2.add_module(str(x), alexnet_pretrained_features[x])
|
| 70 |
+
for x in range(5, 8):
|
| 71 |
+
self.slice3.add_module(str(x), alexnet_pretrained_features[x])
|
| 72 |
+
for x in range(8, 10):
|
| 73 |
+
self.slice4.add_module(str(x), alexnet_pretrained_features[x])
|
| 74 |
+
for x in range(10, 12):
|
| 75 |
+
self.slice5.add_module(str(x), alexnet_pretrained_features[x])
|
| 76 |
+
if not requires_grad:
|
| 77 |
+
for param in self.parameters():
|
| 78 |
+
param.requires_grad = False
|
| 79 |
+
|
| 80 |
+
def forward(self, X):
|
| 81 |
+
h = self.slice1(X)
|
| 82 |
+
h_relu1 = h
|
| 83 |
+
h = self.slice2(h)
|
| 84 |
+
h_relu2 = h
|
| 85 |
+
h = self.slice3(h)
|
| 86 |
+
h_relu3 = h
|
| 87 |
+
h = self.slice4(h)
|
| 88 |
+
h_relu4 = h
|
| 89 |
+
h = self.slice5(h)
|
| 90 |
+
h_relu5 = h
|
| 91 |
+
alexnet_outputs = namedtuple("AlexnetOutputs", ['relu1', 'relu2', 'relu3', 'relu4', 'relu5'])
|
| 92 |
+
out = alexnet_outputs(h_relu1, h_relu2, h_relu3, h_relu4, h_relu5)
|
| 93 |
+
|
| 94 |
+
return out
|
| 95 |
+
|
| 96 |
+
class vgg16(torch.nn.Module):
|
| 97 |
+
def __init__(self, requires_grad=False, pretrained=True):
|
| 98 |
+
super(vgg16, self).__init__()
|
| 99 |
+
vgg_pretrained_features = tv.vgg16(pretrained=pretrained).features
|
| 100 |
+
self.slice1 = torch.nn.Sequential()
|
| 101 |
+
self.slice2 = torch.nn.Sequential()
|
| 102 |
+
self.slice3 = torch.nn.Sequential()
|
| 103 |
+
self.slice4 = torch.nn.Sequential()
|
| 104 |
+
self.slice5 = torch.nn.Sequential()
|
| 105 |
+
self.N_slices = 5
|
| 106 |
+
for x in range(4):
|
| 107 |
+
self.slice1.add_module(str(x), vgg_pretrained_features[x])
|
| 108 |
+
for x in range(4, 9):
|
| 109 |
+
self.slice2.add_module(str(x), vgg_pretrained_features[x])
|
| 110 |
+
for x in range(9, 16):
|
| 111 |
+
self.slice3.add_module(str(x), vgg_pretrained_features[x])
|
| 112 |
+
for x in range(16, 23):
|
| 113 |
+
self.slice4.add_module(str(x), vgg_pretrained_features[x])
|
| 114 |
+
for x in range(23, 30):
|
| 115 |
+
self.slice5.add_module(str(x), vgg_pretrained_features[x])
|
| 116 |
+
if not requires_grad:
|
| 117 |
+
for param in self.parameters():
|
| 118 |
+
param.requires_grad = False
|
| 119 |
+
|
| 120 |
+
def forward(self, X):
|
| 121 |
+
h = self.slice1(X)
|
| 122 |
+
h_relu1_2 = h
|
| 123 |
+
h = self.slice2(h)
|
| 124 |
+
h_relu2_2 = h
|
| 125 |
+
h = self.slice3(h)
|
| 126 |
+
h_relu3_3 = h
|
| 127 |
+
h = self.slice4(h)
|
| 128 |
+
h_relu4_3 = h
|
| 129 |
+
h = self.slice5(h)
|
| 130 |
+
h_relu5_3 = h
|
| 131 |
+
vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
|
| 132 |
+
out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
|
| 133 |
+
|
| 134 |
+
return out
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class resnet(torch.nn.Module):
|
| 139 |
+
def __init__(self, requires_grad=False, pretrained=True, num=18):
|
| 140 |
+
super(resnet, self).__init__()
|
| 141 |
+
if(num==18):
|
| 142 |
+
self.net = tv.resnet18(pretrained=pretrained)
|
| 143 |
+
elif(num==34):
|
| 144 |
+
self.net = tv.resnet34(pretrained=pretrained)
|
| 145 |
+
elif(num==50):
|
| 146 |
+
self.net = tv.resnet50(pretrained=pretrained)
|
| 147 |
+
elif(num==101):
|
| 148 |
+
self.net = tv.resnet101(pretrained=pretrained)
|
| 149 |
+
elif(num==152):
|
| 150 |
+
self.net = tv.resnet152(pretrained=pretrained)
|
| 151 |
+
self.N_slices = 5
|
| 152 |
+
|
| 153 |
+
self.conv1 = self.net.conv1
|
| 154 |
+
self.bn1 = self.net.bn1
|
| 155 |
+
self.relu = self.net.relu
|
| 156 |
+
self.maxpool = self.net.maxpool
|
| 157 |
+
self.layer1 = self.net.layer1
|
| 158 |
+
self.layer2 = self.net.layer2
|
| 159 |
+
self.layer3 = self.net.layer3
|
| 160 |
+
self.layer4 = self.net.layer4
|
| 161 |
+
|
| 162 |
+
def forward(self, X):
|
| 163 |
+
h = self.conv1(X)
|
| 164 |
+
h = self.bn1(h)
|
| 165 |
+
h = self.relu(h)
|
| 166 |
+
h_relu1 = h
|
| 167 |
+
h = self.maxpool(h)
|
| 168 |
+
h = self.layer1(h)
|
| 169 |
+
h_conv2 = h
|
| 170 |
+
h = self.layer2(h)
|
| 171 |
+
h_conv3 = h
|
| 172 |
+
h = self.layer3(h)
|
| 173 |
+
h_conv4 = h
|
| 174 |
+
h = self.layer4(h)
|
| 175 |
+
h_conv5 = h
|
| 176 |
+
|
| 177 |
+
outputs = namedtuple("Outputs", ['relu1','conv2','conv3','conv4','conv5'])
|
| 178 |
+
out = outputs(h_relu1, h_conv2, h_conv3, h_conv4, h_conv5)
|
| 179 |
+
|
| 180 |
+
return out
|
OVOW/third_party/Motion324/evaluation/lpips/trainer.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from __future__ import absolute_import
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch import nn
|
| 7 |
+
from collections import OrderedDict
|
| 8 |
+
from torch.autograd import Variable
|
| 9 |
+
from scipy.ndimage import zoom
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
import lpips
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Trainer():
|
| 16 |
+
def name(self):
|
| 17 |
+
return self.model_name
|
| 18 |
+
|
| 19 |
+
def initialize(self, model='lpips', net='alex', colorspace='Lab', pnet_rand=False, pnet_tune=False, model_path=None,
|
| 20 |
+
use_gpu=True, printNet=False, spatial=False,
|
| 21 |
+
is_train=False, lr=.0001, beta1=0.5, version='0.1', gpu_ids=[0]):
|
| 22 |
+
'''
|
| 23 |
+
INPUTS
|
| 24 |
+
model - ['lpips'] for linearly calibrated network
|
| 25 |
+
['baseline'] for off-the-shelf network
|
| 26 |
+
['L2'] for L2 distance in Lab colorspace
|
| 27 |
+
['SSIM'] for ssim in RGB colorspace
|
| 28 |
+
net - ['squeeze','alex','vgg']
|
| 29 |
+
model_path - if None, will look in weights/[NET_NAME].pth
|
| 30 |
+
colorspace - ['Lab','RGB'] colorspace to use for L2 and SSIM
|
| 31 |
+
use_gpu - bool - whether or not to use a GPU
|
| 32 |
+
printNet - bool - whether or not to print network architecture out
|
| 33 |
+
spatial - bool - whether to output an array containing varying distances across spatial dimensions
|
| 34 |
+
is_train - bool - [True] for training mode
|
| 35 |
+
lr - float - initial learning rate
|
| 36 |
+
beta1 - float - initial momentum term for adam
|
| 37 |
+
version - 0.1 for latest, 0.0 was original (with a bug)
|
| 38 |
+
gpu_ids - int array - [0] by default, gpus to use
|
| 39 |
+
'''
|
| 40 |
+
self.use_gpu = use_gpu
|
| 41 |
+
self.gpu_ids = gpu_ids
|
| 42 |
+
self.model = model
|
| 43 |
+
self.net = net
|
| 44 |
+
self.is_train = is_train
|
| 45 |
+
self.spatial = spatial
|
| 46 |
+
self.model_name = '%s [%s]'%(model,net)
|
| 47 |
+
|
| 48 |
+
if(self.model == 'lpips'): # pretrained net + linear layer
|
| 49 |
+
self.net = lpips.LPIPS(pretrained=not is_train, net=net, version=version, lpips=True, spatial=spatial,
|
| 50 |
+
pnet_rand=pnet_rand, pnet_tune=pnet_tune,
|
| 51 |
+
use_dropout=True, model_path=model_path, eval_mode=False)
|
| 52 |
+
elif(self.model=='baseline'): # pretrained network
|
| 53 |
+
self.net = lpips.LPIPS(pnet_rand=pnet_rand, net=net, lpips=False)
|
| 54 |
+
elif(self.model in ['L2','l2']):
|
| 55 |
+
self.net = lpips.L2(use_gpu=use_gpu,colorspace=colorspace) # not really a network, only for testing
|
| 56 |
+
self.model_name = 'L2'
|
| 57 |
+
elif(self.model in ['DSSIM','dssim','SSIM','ssim']):
|
| 58 |
+
self.net = lpips.DSSIM(use_gpu=use_gpu,colorspace=colorspace)
|
| 59 |
+
self.model_name = 'SSIM'
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError("Model [%s] not recognized." % self.model)
|
| 62 |
+
|
| 63 |
+
self.parameters = list(self.net.parameters())
|
| 64 |
+
|
| 65 |
+
if self.is_train: # training mode
|
| 66 |
+
# extra network on top to go from distances (d0,d1) => predicted human judgment (h*)
|
| 67 |
+
self.rankLoss = lpips.BCERankingLoss()
|
| 68 |
+
self.parameters += list(self.rankLoss.net.parameters())
|
| 69 |
+
self.lr = lr
|
| 70 |
+
self.old_lr = lr
|
| 71 |
+
self.optimizer_net = torch.optim.Adam(self.parameters, lr=lr, betas=(beta1, 0.999))
|
| 72 |
+
else: # test mode
|
| 73 |
+
self.net.eval()
|
| 74 |
+
|
| 75 |
+
if(use_gpu):
|
| 76 |
+
self.net.to(gpu_ids[0])
|
| 77 |
+
self.net = torch.nn.DataParallel(self.net, device_ids=gpu_ids)
|
| 78 |
+
if(self.is_train):
|
| 79 |
+
self.rankLoss = self.rankLoss.to(device=gpu_ids[0]) # just put this on GPU0
|
| 80 |
+
|
| 81 |
+
if(printNet):
|
| 82 |
+
print('---------- Networks initialized -------------')
|
| 83 |
+
networks.print_network(self.net)
|
| 84 |
+
print('-----------------------------------------------')
|
| 85 |
+
|
| 86 |
+
def forward(self, in0, in1, retPerLayer=False):
|
| 87 |
+
''' Function computes the distance between image patches in0 and in1
|
| 88 |
+
INPUTS
|
| 89 |
+
in0, in1 - torch.Tensor object of shape Nx3xXxY - image patch scaled to [-1,1]
|
| 90 |
+
OUTPUT
|
| 91 |
+
computed distances between in0 and in1
|
| 92 |
+
'''
|
| 93 |
+
|
| 94 |
+
return self.net.forward(in0, in1, retPerLayer=retPerLayer)
|
| 95 |
+
|
| 96 |
+
# ***** TRAINING FUNCTIONS *****
|
| 97 |
+
def optimize_parameters(self):
|
| 98 |
+
self.forward_train()
|
| 99 |
+
self.optimizer_net.zero_grad()
|
| 100 |
+
self.backward_train()
|
| 101 |
+
self.optimizer_net.step()
|
| 102 |
+
self.clamp_weights()
|
| 103 |
+
|
| 104 |
+
def clamp_weights(self):
|
| 105 |
+
for module in self.net.modules():
|
| 106 |
+
if(hasattr(module, 'weight') and module.kernel_size==(1,1)):
|
| 107 |
+
module.weight.data = torch.clamp(module.weight.data,min=0)
|
| 108 |
+
|
| 109 |
+
def set_input(self, data):
|
| 110 |
+
self.input_ref = data['ref']
|
| 111 |
+
self.input_p0 = data['p0']
|
| 112 |
+
self.input_p1 = data['p1']
|
| 113 |
+
self.input_judge = data['judge']
|
| 114 |
+
|
| 115 |
+
if(self.use_gpu):
|
| 116 |
+
self.input_ref = self.input_ref.to(device=self.gpu_ids[0])
|
| 117 |
+
self.input_p0 = self.input_p0.to(device=self.gpu_ids[0])
|
| 118 |
+
self.input_p1 = self.input_p1.to(device=self.gpu_ids[0])
|
| 119 |
+
self.input_judge = self.input_judge.to(device=self.gpu_ids[0])
|
| 120 |
+
|
| 121 |
+
self.var_ref = Variable(self.input_ref,requires_grad=True)
|
| 122 |
+
self.var_p0 = Variable(self.input_p0,requires_grad=True)
|
| 123 |
+
self.var_p1 = Variable(self.input_p1,requires_grad=True)
|
| 124 |
+
|
| 125 |
+
def forward_train(self): # run forward pass
|
| 126 |
+
self.d0 = self.forward(self.var_ref, self.var_p0)
|
| 127 |
+
self.d1 = self.forward(self.var_ref, self.var_p1)
|
| 128 |
+
self.acc_r = self.compute_accuracy(self.d0,self.d1,self.input_judge)
|
| 129 |
+
|
| 130 |
+
self.var_judge = Variable(1.*self.input_judge).view(self.d0.size())
|
| 131 |
+
|
| 132 |
+
self.loss_total = self.rankLoss.forward(self.d0, self.d1, self.var_judge*2.-1.)
|
| 133 |
+
|
| 134 |
+
return self.loss_total
|
| 135 |
+
|
| 136 |
+
def backward_train(self):
|
| 137 |
+
torch.mean(self.loss_total).backward()
|
| 138 |
+
|
| 139 |
+
def compute_accuracy(self,d0,d1,judge):
|
| 140 |
+
''' d0, d1 are Variables, judge is a Tensor '''
|
| 141 |
+
d1_lt_d0 = (d1<d0).cpu().data.numpy().flatten()
|
| 142 |
+
judge_per = judge.cpu().numpy().flatten()
|
| 143 |
+
return d1_lt_d0*judge_per + (1-d1_lt_d0)*(1-judge_per)
|
| 144 |
+
|
| 145 |
+
def get_current_errors(self):
|
| 146 |
+
retDict = OrderedDict([('loss_total', self.loss_total.data.cpu().numpy()),
|
| 147 |
+
('acc_r', self.acc_r)])
|
| 148 |
+
|
| 149 |
+
for key in retDict.keys():
|
| 150 |
+
retDict[key] = np.mean(retDict[key])
|
| 151 |
+
|
| 152 |
+
return retDict
|
| 153 |
+
|
| 154 |
+
def get_current_visuals(self):
|
| 155 |
+
zoom_factor = 256/self.var_ref.data.size()[2]
|
| 156 |
+
|
| 157 |
+
ref_img = lpips.tensor2im(self.var_ref.data)
|
| 158 |
+
p0_img = lpips.tensor2im(self.var_p0.data)
|
| 159 |
+
p1_img = lpips.tensor2im(self.var_p1.data)
|
| 160 |
+
|
| 161 |
+
ref_img_vis = zoom(ref_img,[zoom_factor, zoom_factor, 1],order=0)
|
| 162 |
+
p0_img_vis = zoom(p0_img,[zoom_factor, zoom_factor, 1],order=0)
|
| 163 |
+
p1_img_vis = zoom(p1_img,[zoom_factor, zoom_factor, 1],order=0)
|
| 164 |
+
|
| 165 |
+
return OrderedDict([('ref', ref_img_vis),
|
| 166 |
+
('p0', p0_img_vis),
|
| 167 |
+
('p1', p1_img_vis)])
|
| 168 |
+
|
| 169 |
+
def save(self, path, label):
|
| 170 |
+
if(self.use_gpu):
|
| 171 |
+
self.save_network(self.net.module, path, '', label)
|
| 172 |
+
else:
|
| 173 |
+
self.save_network(self.net, path, '', label)
|
| 174 |
+
self.save_network(self.rankLoss.net, path, 'rank', label)
|
| 175 |
+
|
| 176 |
+
# helper saving function that can be used by subclasses
|
| 177 |
+
def save_network(self, network, path, network_label, epoch_label):
|
| 178 |
+
save_filename = '%s_net_%s.pth' % (epoch_label, network_label)
|
| 179 |
+
save_path = os.path.join(path, save_filename)
|
| 180 |
+
torch.save(network.state_dict(), save_path)
|
| 181 |
+
|
| 182 |
+
# helper loading function that can be used by subclasses
|
| 183 |
+
def load_network(self, network, network_label, epoch_label):
|
| 184 |
+
save_filename = '%s_net_%s.pth' % (epoch_label, network_label)
|
| 185 |
+
save_path = os.path.join(self.save_dir, save_filename)
|
| 186 |
+
print('Loading network from %s'%save_path)
|
| 187 |
+
network.load_state_dict(torch.load(save_path))
|
| 188 |
+
|
| 189 |
+
def update_learning_rate(self,nepoch_decay):
|
| 190 |
+
lrd = self.lr / nepoch_decay
|
| 191 |
+
lr = self.old_lr - lrd
|
| 192 |
+
|
| 193 |
+
for param_group in self.optimizer_net.param_groups:
|
| 194 |
+
param_group['lr'] = lr
|
| 195 |
+
|
| 196 |
+
print('update lr [%s] decay: %f -> %f' % (type,self.old_lr, lr))
|
| 197 |
+
self.old_lr = lr
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def get_image_paths(self):
|
| 201 |
+
return self.image_paths
|
| 202 |
+
|
| 203 |
+
def save_done(self, flag=False):
|
| 204 |
+
np.save(os.path.join(self.save_dir, 'done_flag'),flag)
|
| 205 |
+
np.savetxt(os.path.join(self.save_dir, 'done_flag'),[flag,],fmt='%i')
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def score_2afc_dataset(data_loader, func, name=''):
|
| 209 |
+
''' Function computes Two Alternative Forced Choice (2AFC) score using
|
| 210 |
+
distance function 'func' in dataset 'data_loader'
|
| 211 |
+
INPUTS
|
| 212 |
+
data_loader - CustomDatasetDataLoader object - contains a TwoAFCDataset inside
|
| 213 |
+
func - callable distance function - calling d=func(in0,in1) should take 2
|
| 214 |
+
pytorch tensors with shape Nx3xXxY, and return numpy array of length N
|
| 215 |
+
OUTPUTS
|
| 216 |
+
[0] - 2AFC score in [0,1], fraction of time func agrees with human evaluators
|
| 217 |
+
[1] - dictionary with following elements
|
| 218 |
+
d0s,d1s - N arrays containing distances between reference patch to perturbed patches
|
| 219 |
+
gts - N array in [0,1], preferred patch selected by human evaluators
|
| 220 |
+
(closer to "0" for left patch p0, "1" for right patch p1,
|
| 221 |
+
"0.6" means 60pct people preferred right patch, 40pct preferred left)
|
| 222 |
+
scores - N array in [0,1], corresponding to what percentage function agreed with humans
|
| 223 |
+
CONSTS
|
| 224 |
+
N - number of test triplets in data_loader
|
| 225 |
+
'''
|
| 226 |
+
|
| 227 |
+
d0s = []
|
| 228 |
+
d1s = []
|
| 229 |
+
gts = []
|
| 230 |
+
|
| 231 |
+
for data in tqdm(data_loader.load_data(), desc=name):
|
| 232 |
+
d0s+=func(data['ref'],data['p0']).data.cpu().numpy().flatten().tolist()
|
| 233 |
+
d1s+=func(data['ref'],data['p1']).data.cpu().numpy().flatten().tolist()
|
| 234 |
+
gts+=data['judge'].cpu().numpy().flatten().tolist()
|
| 235 |
+
|
| 236 |
+
d0s = np.array(d0s)
|
| 237 |
+
d1s = np.array(d1s)
|
| 238 |
+
gts = np.array(gts)
|
| 239 |
+
scores = (d0s<d1s)*(1.-gts) + (d1s<d0s)*gts + (d1s==d0s)*.5
|
| 240 |
+
|
| 241 |
+
return(np.mean(scores), dict(d0s=d0s,d1s=d1s,gts=gts,scores=scores))
|
| 242 |
+
|
| 243 |
+
def score_jnd_dataset(data_loader, func, name=''):
|
| 244 |
+
''' Function computes JND score using distance function 'func' in dataset 'data_loader'
|
| 245 |
+
INPUTS
|
| 246 |
+
data_loader - CustomDatasetDataLoader object - contains a JNDDataset inside
|
| 247 |
+
func - callable distance function - calling d=func(in0,in1) should take 2
|
| 248 |
+
pytorch tensors with shape Nx3xXxY, and return pytorch array of length N
|
| 249 |
+
OUTPUTS
|
| 250 |
+
[0] - JND score in [0,1], mAP score (area under precision-recall curve)
|
| 251 |
+
[1] - dictionary with following elements
|
| 252 |
+
ds - N array containing distances between two patches shown to human evaluator
|
| 253 |
+
sames - N array containing fraction of people who thought the two patches were identical
|
| 254 |
+
CONSTS
|
| 255 |
+
N - number of test triplets in data_loader
|
| 256 |
+
'''
|
| 257 |
+
|
| 258 |
+
ds = []
|
| 259 |
+
gts = []
|
| 260 |
+
|
| 261 |
+
for data in tqdm(data_loader.load_data(), desc=name):
|
| 262 |
+
ds+=func(data['p0'],data['p1']).data.cpu().numpy().tolist()
|
| 263 |
+
gts+=data['same'].cpu().numpy().flatten().tolist()
|
| 264 |
+
|
| 265 |
+
sames = np.array(gts)
|
| 266 |
+
ds = np.array(ds)
|
| 267 |
+
|
| 268 |
+
sorted_inds = np.argsort(ds)
|
| 269 |
+
ds_sorted = ds[sorted_inds]
|
| 270 |
+
sames_sorted = sames[sorted_inds]
|
| 271 |
+
|
| 272 |
+
TPs = np.cumsum(sames_sorted)
|
| 273 |
+
FPs = np.cumsum(1-sames_sorted)
|
| 274 |
+
FNs = np.sum(sames_sorted)-TPs
|
| 275 |
+
|
| 276 |
+
precs = TPs/(TPs+FPs)
|
| 277 |
+
recs = TPs/(TPs+FNs)
|
| 278 |
+
score = lpips.voc_ap(recs,precs)
|
| 279 |
+
|
| 280 |
+
return(score, dict(ds=ds,sames=sames))
|
OVOW/third_party/Motion324/experiments/checkpoints/ckpt_0000000000060000.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:010696cea050b6be9f4ff540ccbfd9b5e17d0f97080f73009ff0b539c5dd8d15
|
| 3 |
+
size 2240544438
|
OVOW/third_party/Motion324/model/Pcd_motion.py
ADDED
|
@@ -0,0 +1,598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ceback
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import numpy as np
|
| 10 |
+
from easydict import EasyDict as edict
|
| 11 |
+
from .transformer import (QK_Norm_TransformerBlock, init_weights,
|
| 12 |
+
QK_Norm_CrossAttentionBlock)
|
| 13 |
+
from .loss import MSELossComputer
|
| 14 |
+
from .image_encoder.dinov2 import DinoEncoder
|
| 15 |
+
|
| 16 |
+
class FrequencyPositionalEmbedding(nn.Module):
|
| 17 |
+
"""The sin/cosine positional embedding. Given an input tensor `x` of shape [n_batch, ..., c_dim], it converts
|
| 18 |
+
each feature dimension of `x[..., i]` into:
|
| 19 |
+
[
|
| 20 |
+
sin(x[..., i]),
|
| 21 |
+
sin(f_1*x[..., i]),
|
| 22 |
+
sin(f_2*x[..., i]),
|
| 23 |
+
...
|
| 24 |
+
sin(f_N * x[..., i]),
|
| 25 |
+
cos(x[..., i]),
|
| 26 |
+
cos(f_1*x[..., i]),
|
| 27 |
+
cos(f_2*x[..., i]),
|
| 28 |
+
...
|
| 29 |
+
cos(f_N * x[..., i]),
|
| 30 |
+
x[..., i] # only present if include_input is True.
|
| 31 |
+
], here f_i is the frequency.
|
| 32 |
+
|
| 33 |
+
Denote the space is [0 / num_freqs, 1 / num_freqs, 2 / num_freqs, 3 / num_freqs, ..., (num_freqs - 1) / num_freqs].
|
| 34 |
+
If logspace is True, then the frequency f_i is [2^(0 / num_freqs), ..., 2^(i / num_freqs), ...];
|
| 35 |
+
Otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)].
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
num_freqs (int): the number of frequencies, default is 6;
|
| 39 |
+
logspace (bool): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
|
| 40 |
+
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1)];
|
| 41 |
+
input_dim (int): the input dimension, default is 3;
|
| 42 |
+
include_input (bool): include the input tensor or not, default is True.
|
| 43 |
+
|
| 44 |
+
Attributes:
|
| 45 |
+
frequencies (torch.Tensor): If logspace is True, then the frequency f_i is [..., 2^(i / num_freqs), ...],
|
| 46 |
+
otherwise, the frequencies are linearly spaced between [1.0, 2^(num_freqs - 1);
|
| 47 |
+
|
| 48 |
+
out_dim (int): the embedding size, if include_input is True, it is input_dim * (num_freqs * 2 + 1),
|
| 49 |
+
otherwise, it is input_dim * num_freqs * 2.
|
| 50 |
+
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
num_freqs: int = 6,
|
| 56 |
+
logspace: bool = True,
|
| 57 |
+
input_dim: int = 3,
|
| 58 |
+
include_input: bool = True,
|
| 59 |
+
include_pi: bool = True,
|
| 60 |
+
) -> None:
|
| 61 |
+
"""The initialization"""
|
| 62 |
+
|
| 63 |
+
super().__init__()
|
| 64 |
+
|
| 65 |
+
if logspace:
|
| 66 |
+
frequencies = 2.0 ** torch.arange(num_freqs, dtype=torch.float32)
|
| 67 |
+
else:
|
| 68 |
+
frequencies = torch.linspace(
|
| 69 |
+
1.0, 2.0 ** (num_freqs - 1), num_freqs, dtype=torch.float32
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
if include_pi:
|
| 73 |
+
frequencies *= torch.pi
|
| 74 |
+
|
| 75 |
+
self.register_buffer("frequencies", frequencies, persistent=False)
|
| 76 |
+
self.include_input = include_input
|
| 77 |
+
self.num_freqs = num_freqs
|
| 78 |
+
|
| 79 |
+
self.out_dim = self._get_dims(input_dim)
|
| 80 |
+
|
| 81 |
+
def _get_dims(self, input_dim):
|
| 82 |
+
temp = 1 if self.include_input or self.num_freqs == 0 else 0
|
| 83 |
+
out_dim = input_dim * (self.num_freqs * 2 + temp)
|
| 84 |
+
|
| 85 |
+
return out_dim
|
| 86 |
+
|
| 87 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 88 |
+
"""Forward process.
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
x: tensor of shape [..., dim]
|
| 92 |
+
|
| 93 |
+
Returns:
|
| 94 |
+
embedding: an embedding of `x` of shape [..., dim * (num_freqs * 2 + temp)]
|
| 95 |
+
where temp is 1 if include_input is True and 0 otherwise.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
if self.num_freqs > 0:
|
| 99 |
+
embed = (x[..., None].contiguous() * self.frequencies.to(device=x.device)).view(
|
| 100 |
+
*x.shape[:-1], -1
|
| 101 |
+
)
|
| 102 |
+
if self.include_input:
|
| 103 |
+
return torch.cat((x, embed.sin(), embed.cos()), dim=-1)
|
| 104 |
+
else:
|
| 105 |
+
return torch.cat((embed.sin(), embed.cos()), dim=-1)
|
| 106 |
+
else:
|
| 107 |
+
return x
|
| 108 |
+
|
| 109 |
+
def get_sinusoidal_time_embed(num_frames, embed_dim, device):
|
| 110 |
+
"""
|
| 111 |
+
Generate time embedding with shape=[num_frames, embed_dim].
|
| 112 |
+
"""
|
| 113 |
+
position = torch.arange(num_frames, dtype=torch.float32, device=device).unsqueeze(1)
|
| 114 |
+
div_term = torch.exp(torch.arange(0, embed_dim, 2, device=device).float() * (-math.log(10000.0) / embed_dim))
|
| 115 |
+
pe = torch.zeros(num_frames, embed_dim, device=device)
|
| 116 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
| 117 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
| 118 |
+
return pe # [T, C]
|
| 119 |
+
|
| 120 |
+
class SinusoidalPositionalEncoding(nn.Module):
|
| 121 |
+
"""
|
| 122 |
+
Sinusoidal positional encoding module.
|
| 123 |
+
"""
|
| 124 |
+
def __init__(self, d_model: int, max_len: int = 4096, dropout: float = 0.0):
|
| 125 |
+
"""
|
| 126 |
+
Args:
|
| 127 |
+
d_model (int): Model dimension (embedding dimension).
|
| 128 |
+
max_len (int): Maximum sequence length supported.
|
| 129 |
+
dropout (float): Dropout rate.
|
| 130 |
+
"""
|
| 131 |
+
super().__init__()
|
| 132 |
+
self.dropout = nn.Dropout(p=dropout)
|
| 133 |
+
|
| 134 |
+
if d_model % 2 != 0:
|
| 135 |
+
raise ValueError(f"d_model ({d_model}) must be even to use paired sin/cos for sinusoidal positional encoding.")
|
| 136 |
+
|
| 137 |
+
position = torch.arange(max_len).unsqueeze(1) # Shape: [max_len, 1]
|
| 138 |
+
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) # Shape: [d_model / 2]
|
| 139 |
+
|
| 140 |
+
pe = torch.zeros(1, max_len, d_model)
|
| 141 |
+
pe[0, :, 0::2] = torch.sin(position * div_term)
|
| 142 |
+
pe[0, :, 1::2] = torch.cos(position * div_term)
|
| 143 |
+
|
| 144 |
+
self.register_buffer('pe', pe)
|
| 145 |
+
|
| 146 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 147 |
+
"""
|
| 148 |
+
Forward propagation.
|
| 149 |
+
Args:
|
| 150 |
+
x: Input tensor with shape [batch_size, seq_len, embedding_dim]
|
| 151 |
+
Returns:
|
| 152 |
+
torch.Tensor: Output tensor with positional encoding added, same shape as input.
|
| 153 |
+
"""
|
| 154 |
+
x = x + self.pe[:, :x.size(1), :]
|
| 155 |
+
return self.dropout(x)
|
| 156 |
+
|
| 157 |
+
class PointEmbed(nn.Module):
|
| 158 |
+
def __init__(self, hidden_dim=48, dim=768):
|
| 159 |
+
super().__init__()
|
| 160 |
+
|
| 161 |
+
assert hidden_dim % 6 == 0
|
| 162 |
+
|
| 163 |
+
self.embedding_dim = hidden_dim
|
| 164 |
+
e = torch.pow(2, torch.arange(self.embedding_dim // 6)).float() * np.pi
|
| 165 |
+
e = torch.stack([
|
| 166 |
+
torch.cat([e, torch.zeros(self.embedding_dim // 6),
|
| 167 |
+
torch.zeros(self.embedding_dim // 6)]),
|
| 168 |
+
torch.cat([torch.zeros(self.embedding_dim // 6), e,
|
| 169 |
+
torch.zeros(self.embedding_dim // 6)]),
|
| 170 |
+
torch.cat([torch.zeros(self.embedding_dim // 6),
|
| 171 |
+
torch.zeros(self.embedding_dim // 6), e]),
|
| 172 |
+
])
|
| 173 |
+
self.register_buffer('basis', e) # 3 x 16
|
| 174 |
+
|
| 175 |
+
self.mlp = nn.Linear(self.embedding_dim+3, dim)
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def embed(input, basis):
|
| 179 |
+
projections = torch.einsum(
|
| 180 |
+
'bnd,de->bne', input, basis)
|
| 181 |
+
embeddings = torch.cat([projections.sin(), projections.cos()], dim=2)
|
| 182 |
+
return embeddings
|
| 183 |
+
|
| 184 |
+
def forward(self, input):
|
| 185 |
+
# input: B x N x 3
|
| 186 |
+
embed = self.mlp(torch.cat([self.embed(input, self.basis), input], dim=2)) # B x N x C
|
| 187 |
+
return embed
|
| 188 |
+
|
| 189 |
+
class PatchEmbed(nn.Module):#4 patch_length normal
|
| 190 |
+
"""Video patch embedding layer."""
|
| 191 |
+
def __init__(self, video_size=224, video_length=16, patch_size=16, patch_length=4,
|
| 192 |
+
in_chans=3, embed_dim=768):
|
| 193 |
+
super().__init__()
|
| 194 |
+
self.video_size = video_size
|
| 195 |
+
self.video_length = video_length
|
| 196 |
+
self.patch_size = patch_size
|
| 197 |
+
self.patch_length = patch_length
|
| 198 |
+
self.in_chans = in_chans
|
| 199 |
+
self.embed_dim = embed_dim
|
| 200 |
+
|
| 201 |
+
# Calculate number of patches
|
| 202 |
+
self.num_patches_h = video_size // patch_size
|
| 203 |
+
self.num_patches_w = video_size // patch_size
|
| 204 |
+
self.num_patches_t = video_length // patch_length
|
| 205 |
+
self.num_patches = self.num_patches_t * self.num_patches_h * self.num_patches_w
|
| 206 |
+
|
| 207 |
+
# Patch embedding layer
|
| 208 |
+
self.proj = nn.Conv3d(in_chans, embed_dim,
|
| 209 |
+
kernel_size=(patch_length, patch_size, patch_size),
|
| 210 |
+
stride=(patch_length, patch_size, patch_size))
|
| 211 |
+
|
| 212 |
+
def forward(self, x):
|
| 213 |
+
# Input: B, C, T, H, W
|
| 214 |
+
B, C, T, H, W = x.shape
|
| 215 |
+
assert T == self.video_length and H == self.video_size and W == self.video_size, \
|
| 216 |
+
f"Input size mismatch: got {T}x{H}x{W}, expected {self.video_length}x{self.video_size}x{self.video_size}"
|
| 217 |
+
|
| 218 |
+
x = self.proj(x) # B, embed_dim, T/pT, H/pH, W/pW
|
| 219 |
+
return x
|
| 220 |
+
|
| 221 |
+
def resize_pos_embed(posemb, src_shape, target_shape):
|
| 222 |
+
"""Resize position embedding to match target shape."""
|
| 223 |
+
posemb = posemb.reshape(1, src_shape[0], src_shape[1], src_shape[2], -1)
|
| 224 |
+
posemb = posemb.permute(0, 4, 1, 2, 3)
|
| 225 |
+
posemb = nn.functional.interpolate(posemb, size=target_shape, mode='trilinear', align_corners=False)
|
| 226 |
+
posemb = posemb.permute(0, 2, 3, 4, 1)
|
| 227 |
+
posemb = posemb.reshape(1, target_shape[0] * target_shape[1] * target_shape[2], -1)
|
| 228 |
+
return posemb
|
| 229 |
+
|
| 230 |
+
def generate_pos_embed(T, H, W, embed_dim):
|
| 231 |
+
"""Generate 3D position embedding."""
|
| 232 |
+
latent_t = torch.arange(T, dtype=torch.float32)
|
| 233 |
+
latent_h = torch.arange(H, dtype=torch.float32)
|
| 234 |
+
latent_w = torch.arange(W, dtype=torch.float32)
|
| 235 |
+
|
| 236 |
+
if T > 1:
|
| 237 |
+
latent_t = 2 * (latent_t / (T - 1)) - 1
|
| 238 |
+
else:
|
| 239 |
+
latent_t = torch.tensor([0.0], dtype=torch.float32)
|
| 240 |
+
|
| 241 |
+
if H > 1:
|
| 242 |
+
latent_h = 2 * (latent_h / (H - 1)) - 1
|
| 243 |
+
else:
|
| 244 |
+
latent_h = torch.tensor([0.0], dtype=torch.float32)
|
| 245 |
+
|
| 246 |
+
if W > 1:
|
| 247 |
+
latent_w = 2 * (latent_w / (W - 1)) - 1
|
| 248 |
+
else:
|
| 249 |
+
latent_w = torch.tensor([0.0], dtype=torch.float32)
|
| 250 |
+
|
| 251 |
+
t, h, w = torch.meshgrid(latent_t, latent_h, latent_w, indexing='ij')
|
| 252 |
+
|
| 253 |
+
pos = torch.stack([t, h, w], dim=-1)
|
| 254 |
+
|
| 255 |
+
# Apply Fourier feature mapping
|
| 256 |
+
freq_bands = 2.0 ** torch.linspace(0.0, 7.0, embed_dim // 6)
|
| 257 |
+
freq_bands = freq_bands.view(1, 1, 1, 1, -1)
|
| 258 |
+
|
| 259 |
+
# Project to higher dimensions using sin and cos
|
| 260 |
+
pos = pos.unsqueeze(-1) * freq_bands
|
| 261 |
+
pos = torch.cat([torch.sin(pos), torch.cos(pos)], dim=-1)
|
| 262 |
+
|
| 263 |
+
# Reshape to 1D sequence
|
| 264 |
+
pos = pos.reshape(1, -1, embed_dim)
|
| 265 |
+
|
| 266 |
+
return pos
|
| 267 |
+
|
| 268 |
+
class Motion_Latent_Model(nn.Module):
|
| 269 |
+
def __init__(self, config):
|
| 270 |
+
super().__init__()
|
| 271 |
+
self.config = config
|
| 272 |
+
self.feat_dim = self.config.model.feat_dim
|
| 273 |
+
|
| 274 |
+
self._init_video_patchify()
|
| 275 |
+
|
| 276 |
+
transformer_config = self.config.model.video_encoder.transformer
|
| 277 |
+
use_qk_norm = transformer_config.get("use_qk_norm", True)
|
| 278 |
+
d_model = transformer_config.d
|
| 279 |
+
d_head = transformer_config.d_head
|
| 280 |
+
|
| 281 |
+
use_qk_norm = transformer_config.get("use_qk_norm", True)
|
| 282 |
+
|
| 283 |
+
self.point_embed = PointEmbed(dim=transformer_config.d)
|
| 284 |
+
self.point_normal_rgb_proj = nn.Linear(transformer_config.d + 3 + 3, transformer_config.d)
|
| 285 |
+
self.point_normal_rgb_proj.apply(init_weights)
|
| 286 |
+
|
| 287 |
+
self.num_learnable_tokens = config.model.tokens
|
| 288 |
+
self.learnable_tokens = nn.Parameter(torch.randn(1, self.num_learnable_tokens, d_model))
|
| 289 |
+
|
| 290 |
+
# Special tokens for t=0 and t>0. Each is (1, 4, d_model).
|
| 291 |
+
self.special_token_0 = nn.Parameter(torch.randn(1, 4, d_model))
|
| 292 |
+
self.special_token_rest = nn.Parameter(torch.randn(1, 4, d_model))
|
| 293 |
+
|
| 294 |
+
self.encoder_cross_attn = QK_Norm_CrossAttentionBlock(
|
| 295 |
+
dim=d_model,
|
| 296 |
+
head_dim=d_head,
|
| 297 |
+
kv_dim=d_model,
|
| 298 |
+
use_qk_norm=use_qk_norm
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
self.points_transformer_blocks = nn.ModuleList([
|
| 302 |
+
QK_Norm_TransformerBlock(
|
| 303 |
+
transformer_config.d, transformer_config.d_head, use_qk_norm=use_qk_norm
|
| 304 |
+
) for _ in range(config.model.pcd_layers)
|
| 305 |
+
])
|
| 306 |
+
self.points_transformer_blocks.apply(init_weights)
|
| 307 |
+
|
| 308 |
+
self.image_encoder = DinoEncoder(patch_size=14)
|
| 309 |
+
self.alternating_layers = transformer_config.get("n_layer", 12)
|
| 310 |
+
assert self.alternating_layers % 2 == 0, "Alternating layers should be even."
|
| 311 |
+
|
| 312 |
+
self.global_transformer_blocks = nn.ModuleList([
|
| 313 |
+
QK_Norm_TransformerBlock(
|
| 314 |
+
transformer_config.d, transformer_config.d_head, use_qk_norm=use_qk_norm
|
| 315 |
+
) for _ in range(self.alternating_layers // 2)
|
| 316 |
+
])
|
| 317 |
+
self.global_transformer_blocks.apply(init_weights)
|
| 318 |
+
|
| 319 |
+
self.local_transformer_blocks = nn.ModuleList([
|
| 320 |
+
QK_Norm_TransformerBlock(
|
| 321 |
+
transformer_config.d, transformer_config.d_head, use_qk_norm=use_qk_norm
|
| 322 |
+
) for _ in range(self.alternating_layers // 2)
|
| 323 |
+
])
|
| 324 |
+
self.local_transformer_blocks.apply(init_weights)
|
| 325 |
+
|
| 326 |
+
self.transformer_input_layernorm = nn.LayerNorm(transformer_config.d, bias=False)
|
| 327 |
+
self.transformer_input_layernorm.apply(init_weights)
|
| 328 |
+
|
| 329 |
+
self.decoder_cross_attn = QK_Norm_CrossAttentionBlock(
|
| 330 |
+
dim=d_model,
|
| 331 |
+
head_dim=d_head,
|
| 332 |
+
kv_dim=d_model,
|
| 333 |
+
use_qk_norm=use_qk_norm
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
self.shared_mlp_output = nn.Sequential(
|
| 337 |
+
nn.LayerNorm(self.feat_dim),
|
| 338 |
+
nn.Linear(self.feat_dim, self.feat_dim),
|
| 339 |
+
nn.GELU(),
|
| 340 |
+
nn.Linear(self.feat_dim, 3),
|
| 341 |
+
)
|
| 342 |
+
self.shared_mlp_output.apply(init_weights)
|
| 343 |
+
|
| 344 |
+
self.loss_computer = MSELossComputer(self.config)
|
| 345 |
+
|
| 346 |
+
def _init_video_patchify(self):
|
| 347 |
+
video_config = self.config.model.video_encoder
|
| 348 |
+
transformer_config = video_config.transformer
|
| 349 |
+
token_config = video_config.image_tokenizer
|
| 350 |
+
|
| 351 |
+
self.image_size = token_config.get("image_size", 224)
|
| 352 |
+
self.video_length = self.config.training.frames
|
| 353 |
+
self.patch_size = token_config.get("patch_size", 14)
|
| 354 |
+
self.patch_length = token_config.get("patch_length", 1)
|
| 355 |
+
self.embed_dim = transformer_config.d
|
| 356 |
+
|
| 357 |
+
self.num_patches_h = self.image_size // self.patch_size
|
| 358 |
+
self.num_patches_w = self.image_size // self.patch_size
|
| 359 |
+
self.num_patches_t = self.video_length // self.patch_length
|
| 360 |
+
|
| 361 |
+
self.latent_length = self.num_patches_t
|
| 362 |
+
self.latent_size = self.num_patches_h # Assuming square patches
|
| 363 |
+
|
| 364 |
+
pos_embed = generate_pos_embed(
|
| 365 |
+
self.latent_length, self.latent_size, self.latent_size, self.embed_dim
|
| 366 |
+
)
|
| 367 |
+
self.register_buffer('pos_embed', pos_embed)
|
| 368 |
+
|
| 369 |
+
drop_rate = transformer_config.get("drop_rate", 0.1)
|
| 370 |
+
self.pos_drop = nn.Dropout(p=drop_rate)
|
| 371 |
+
|
| 372 |
+
def train(self, mode=True):
|
| 373 |
+
super().train(mode)
|
| 374 |
+
|
| 375 |
+
def pass_transformer_layers(self, blocks, input_tokens, gradient_checkpoint=False, checkpoint_every=1):
|
| 376 |
+
num_layers = len(blocks)
|
| 377 |
+
if not gradient_checkpoint:
|
| 378 |
+
for layer in blocks:
|
| 379 |
+
input_tokens = layer(input_tokens)
|
| 380 |
+
return input_tokens
|
| 381 |
+
|
| 382 |
+
def _process_layer_group(tokens, start_idx, end_idx):
|
| 383 |
+
for idx in range(start_idx, end_idx):
|
| 384 |
+
tokens = blocks[idx](tokens)
|
| 385 |
+
return tokens
|
| 386 |
+
|
| 387 |
+
for start_idx in range(0, num_layers, checkpoint_every):
|
| 388 |
+
end_idx = min(start_idx + checkpoint_every, num_layers)
|
| 389 |
+
input_tokens = torch.utils.checkpoint.checkpoint(
|
| 390 |
+
_process_layer_group, input_tokens, start_idx, end_idx, use_reentrant=False
|
| 391 |
+
)
|
| 392 |
+
return input_tokens
|
| 393 |
+
|
| 394 |
+
def pass_alternating_attention(self, input_tokens, gradient_checkpoint=False, checkpoint_every=1):
|
| 395 |
+
B, T, L, C = input_tokens.shape
|
| 396 |
+
num_loops = len(self.global_transformer_blocks)
|
| 397 |
+
|
| 398 |
+
if not gradient_checkpoint:
|
| 399 |
+
processed_tokens = input_tokens
|
| 400 |
+
for i in range(num_loops):
|
| 401 |
+
processed_tokens = processed_tokens.view(B, T * L, C)
|
| 402 |
+
processed_tokens = self.global_transformer_blocks[i](
|
| 403 |
+
processed_tokens
|
| 404 |
+
)
|
| 405 |
+
processed_tokens = processed_tokens.view(B, T, L, C)
|
| 406 |
+
processed_tokens_reshaped = processed_tokens.view(B * T, L, C)
|
| 407 |
+
processed_tokens_local = self.local_transformer_blocks[i](processed_tokens_reshaped)
|
| 408 |
+
processed_tokens = processed_tokens_local.view(B, T, L, C)
|
| 409 |
+
return processed_tokens
|
| 410 |
+
|
| 411 |
+
def _process_alternating_group(tokens, start_idx, end_idx):
|
| 412 |
+
for i in range(start_idx, end_idx):
|
| 413 |
+
tokens = tokens.view(B, T * L, C)
|
| 414 |
+
tokens = self.global_transformer_blocks[i](
|
| 415 |
+
tokens
|
| 416 |
+
)
|
| 417 |
+
tokens = tokens.view(B, T, L, C)
|
| 418 |
+
tokens_reshaped = tokens.view(B * T, L, C)
|
| 419 |
+
tokens_processed = self.local_transformer_blocks[i](tokens_reshaped)
|
| 420 |
+
tokens = tokens_processed.view(B, T, L, C)
|
| 421 |
+
return tokens
|
| 422 |
+
|
| 423 |
+
processed_tokens = input_tokens
|
| 424 |
+
for start_idx in range(0, num_loops, checkpoint_every):
|
| 425 |
+
end_idx = min(start_idx + checkpoint_every, num_loops)
|
| 426 |
+
processed_tokens = torch.utils.checkpoint.checkpoint(
|
| 427 |
+
_process_alternating_group, processed_tokens, start_idx, end_idx, use_reentrant=False
|
| 428 |
+
)
|
| 429 |
+
return processed_tokens
|
| 430 |
+
|
| 431 |
+
def pass_pcd_layers(self, input_tokens, gradient_checkpoint=False, checkpoint_every=1):
|
| 432 |
+
num_layers = len(self.points_transformer_blocks)
|
| 433 |
+
if not gradient_checkpoint:
|
| 434 |
+
for layer in self.points_transformer_blocks:
|
| 435 |
+
input_tokens = layer(input_tokens)
|
| 436 |
+
return input_tokens
|
| 437 |
+
|
| 438 |
+
def _process_layer_group(tokens, start_idx, end_idx):
|
| 439 |
+
for idx in range(start_idx, end_idx):
|
| 440 |
+
tokens = self.points_transformer_blocks[idx](tokens)
|
| 441 |
+
return tokens
|
| 442 |
+
|
| 443 |
+
for start_idx in range(0, num_layers, checkpoint_every):
|
| 444 |
+
end_idx = min(start_idx + checkpoint_every, num_layers)
|
| 445 |
+
input_tokens = torch.utils.checkpoint.checkpoint(
|
| 446 |
+
_process_layer_group, input_tokens, start_idx, end_idx, use_reentrant=False
|
| 447 |
+
)
|
| 448 |
+
return input_tokens
|
| 449 |
+
|
| 450 |
+
def forward(self, sample):
|
| 451 |
+
B = sample['ref_pcd'].shape[0]
|
| 452 |
+
N_points = sample['ref_pcd'].shape[1]
|
| 453 |
+
device = sample['ref_pcd'].device
|
| 454 |
+
tokens = self.learnable_tokens.shape[1]
|
| 455 |
+
|
| 456 |
+
point_embedding = self.point_embed(sample['ref_shape_pcd'])
|
| 457 |
+
checkpoint_every = self.config.training.grad_checkpoint_every
|
| 458 |
+
|
| 459 |
+
point_normal_rgb_embedding = self.point_normal_rgb_proj(torch.cat([point_embedding, sample['ref_shape_normals'], sample['ref_shape_rgbs']], dim=-1))
|
| 460 |
+
|
| 461 |
+
query_tokens = self.learnable_tokens.expand(B, -1, -1).to(device)
|
| 462 |
+
mesh_point_feat = self.encoder_cross_attn(query_tokens, point_normal_rgb_embedding, point_normal_rgb_embedding)
|
| 463 |
+
use_checkpoint = self.config.training.get('use_checkpoint', True)
|
| 464 |
+
mesh_feat = self.pass_pcd_layers(mesh_point_feat, gradient_checkpoint=use_checkpoint, checkpoint_every=checkpoint_every)
|
| 465 |
+
|
| 466 |
+
rgb_video = sample['rgb_video'] # B, T, H, W, C
|
| 467 |
+
B_vid, T_in, H_in, W_in, C_rgb = rgb_video.shape
|
| 468 |
+
#assert self.config.training.frames == T_in, "Mismatch between configured frames and input video frames."
|
| 469 |
+
|
| 470 |
+
tokenizer_input = rgb_video.permute(0, 1, 4, 2, 3)
|
| 471 |
+
tokenizer_input = tokenizer_input.reshape(B_vid * T_in, tokenizer_input.shape[-3], tokenizer_input.shape[-2], tokenizer_input.shape[-1])
|
| 472 |
+
tokenizer_input = F.interpolate(tokenizer_input, (self.image_size, self.image_size), mode="bilinear", align_corners=False)
|
| 473 |
+
|
| 474 |
+
with torch.no_grad():
|
| 475 |
+
image_tokens_raw = self.image_encoder(tokenizer_input)
|
| 476 |
+
|
| 477 |
+
x = image_tokens_raw.view(B_vid, T_in, self.num_patches_h, self.num_patches_w, image_tokens_raw.shape[-1])
|
| 478 |
+
x = x.permute(0, 4, 1, 2, 3)
|
| 479 |
+
latentT, latentH, latentW = x.shape[2], x.shape[3], x.shape[4]
|
| 480 |
+
x = x.flatten(2).transpose(1, 2)
|
| 481 |
+
if latentT != self.latent_length or latentH != self.latent_size or latentW != self.latent_size:
|
| 482 |
+
pos_embed = resize_pos_embed(
|
| 483 |
+
self.pos_embed,
|
| 484 |
+
src_shape=(self.latent_length, self.latent_size, self.latent_size),
|
| 485 |
+
target_shape=(latentT, latentH, latentW),
|
| 486 |
+
)
|
| 487 |
+
else:
|
| 488 |
+
pos_embed = self.pos_embed
|
| 489 |
+
x = x + pos_embed
|
| 490 |
+
x = self.pos_drop(x)
|
| 491 |
+
video_tokens_projected = x
|
| 492 |
+
num_video_patches_per_frame = video_tokens_projected.shape[1] // T_in
|
| 493 |
+
video_tokens_per_frame = video_tokens_projected.view(B, T_in, num_video_patches_per_frame, -1) # [B,T,L_img,C]
|
| 494 |
+
|
| 495 |
+
special_token_0 = self.special_token_0.expand(B, 4, -1) # [B, 4, C]
|
| 496 |
+
special_token_rest = self.special_token_rest.expand(B, 4, -1) # [B, 4, C]
|
| 497 |
+
|
| 498 |
+
all_special_tokens = torch.stack([special_token_0] + [special_token_rest]*(T_in-1), dim=1) # [B, T_in, 4, C]
|
| 499 |
+
|
| 500 |
+
# mesh_feat: [B, tokens, C] -> [B, T_in, tokens, C]
|
| 501 |
+
pcd_tokens_repeated = mesh_feat.unsqueeze(1).expand(B, T_in, tokens, mesh_feat.shape[-1]) # [B, T_in, tokens, C]
|
| 502 |
+
# [B, T_in, tokens+4+L_img, C]
|
| 503 |
+
concatenated_tokens = torch.cat([
|
| 504 |
+
all_special_tokens,
|
| 505 |
+
pcd_tokens_repeated, # [B, T_in, tokens, C]
|
| 506 |
+
video_tokens_per_frame # [B,T_in,L_img,C]
|
| 507 |
+
], dim=2)
|
| 508 |
+
|
| 509 |
+
concatenated_tokens = self.transformer_input_layernorm(concatenated_tokens)
|
| 510 |
+
B, T, L, C = concatenated_tokens.shape
|
| 511 |
+
|
| 512 |
+
use_checkpoint = self.config.training.get('use_checkpoint', True)
|
| 513 |
+
checkpoint_every = self.config.training.get('grad_checkpoint_every', 1)
|
| 514 |
+
|
| 515 |
+
processed_tokens_BTLC = self.pass_alternating_attention(
|
| 516 |
+
input_tokens=concatenated_tokens,
|
| 517 |
+
gradient_checkpoint=use_checkpoint,
|
| 518 |
+
checkpoint_every=checkpoint_every
|
| 519 |
+
)
|
| 520 |
+
pcd_tokens_final = processed_tokens_BTLC[:, :, 4:4+tokens, :]
|
| 521 |
+
|
| 522 |
+
output_pcds = sample['ref_pcd']
|
| 523 |
+
output_normals = sample['ref_normal']
|
| 524 |
+
output_rgbs = sample['ref_rgb']
|
| 525 |
+
|
| 526 |
+
B, N, _ = output_pcds.shape
|
| 527 |
+
chunk_size = 4096
|
| 528 |
+
|
| 529 |
+
def decode_chunk(pcd_chunk, normal_chunk, rgb_chunk, pcd_tokens_for_decode):
|
| 530 |
+
B = pcd_chunk.shape[0]
|
| 531 |
+
N = pcd_chunk.shape[1]
|
| 532 |
+
T = T_in
|
| 533 |
+
# Repeat to [B, T_in, N, C]
|
| 534 |
+
pcd_chunk_proj = pcd_chunk[:, None, :, :].expand(-1, T, -1, -1)
|
| 535 |
+
normal_chunk_proj = normal_chunk[:, None, :, :].expand(-1, T, -1, -1)
|
| 536 |
+
rgb_chunk_proj = rgb_chunk[:, None, :, :].expand(-1, T, -1, -1)
|
| 537 |
+
|
| 538 |
+
outputs = []
|
| 539 |
+
for t in range(T):
|
| 540 |
+
# For each time step, get corresponding token slice
|
| 541 |
+
# pcd_tokens_for_decode: [B, T_in, tokens, C]
|
| 542 |
+
pcd_tokens_t = pcd_tokens_for_decode[:, t, :, :] # [B, tokens, C]
|
| 543 |
+
|
| 544 |
+
# The inputs for this time step
|
| 545 |
+
pcd_input = pcd_chunk_proj[:, t, :, :] # [B, N, C]
|
| 546 |
+
normal_input = normal_chunk_proj[:, t, :, :]
|
| 547 |
+
rgb_input = rgb_chunk_proj[:, t, :, :]
|
| 548 |
+
|
| 549 |
+
# Project and concat features
|
| 550 |
+
out_ref_emb = self.point_embed(pcd_input)
|
| 551 |
+
point_feat = self.point_normal_rgb_proj(torch.cat([
|
| 552 |
+
out_ref_emb, normal_input, rgb_input
|
| 553 |
+
], dim=-1))
|
| 554 |
+
|
| 555 |
+
# query: [B, chunk_size, C], key/value: [B, num_pcd_tokens, C]
|
| 556 |
+
decoded_out_t = self.decoder_cross_attn(
|
| 557 |
+
query=point_feat,
|
| 558 |
+
key=pcd_tokens_t,
|
| 559 |
+
value=pcd_tokens_t
|
| 560 |
+
)
|
| 561 |
+
output_t = self.shared_mlp_output(decoded_out_t) # [B, N, 3]
|
| 562 |
+
outputs.append(output_t)
|
| 563 |
+
decoded_chunk = torch.stack(outputs, dim=1).contiguous().view(-1, outputs[0].shape[1], outputs[0].shape[2])
|
| 564 |
+
return decoded_chunk
|
| 565 |
+
|
| 566 |
+
if not self.training and N > chunk_size:
|
| 567 |
+
pcds_chunks = []
|
| 568 |
+
for i in range(0, N, chunk_size):
|
| 569 |
+
pcd_chunk_slice = output_pcds[:, i:i + chunk_size, :]
|
| 570 |
+
normal_chunk_slice = output_normals[:, i:i + chunk_size, :]
|
| 571 |
+
rgb_chunk_slice = output_rgbs[:, i:i + chunk_size, :]
|
| 572 |
+
|
| 573 |
+
decoded_chunk = decode_chunk(pcd_chunk_slice, normal_chunk_slice, rgb_chunk_slice, pcd_tokens_final)
|
| 574 |
+
pcds_chunks.append(decoded_chunk)
|
| 575 |
+
pcds = torch.cat(pcds_chunks, dim=1) # [B*T, N, C]
|
| 576 |
+
else:
|
| 577 |
+
pcds = decode_chunk(output_pcds, output_normals, output_rgbs, pcd_tokens_final) # [B*T, N, C]
|
| 578 |
+
|
| 579 |
+
output = pcds.view(B, T_in, N_points, 3)
|
| 580 |
+
|
| 581 |
+
# Check if ground truth is available for loss computation
|
| 582 |
+
if 'point_clouds' in sample:
|
| 583 |
+
xyz_loss_metrics = self.loss_computer(output[..., :3], sample['point_clouds'])
|
| 584 |
+
loss_metrics = edict()
|
| 585 |
+
loss_metrics.loss = xyz_loss_metrics.loss
|
| 586 |
+
loss_metrics.xyz_loss = xyz_loss_metrics.coord_mse_loss
|
| 587 |
+
|
| 588 |
+
result = edict(
|
| 589 |
+
input_data=sample,
|
| 590 |
+
pcd_moved=output[..., :3],
|
| 591 |
+
loss_metrics=loss_metrics
|
| 592 |
+
)
|
| 593 |
+
else:
|
| 594 |
+
result = edict(
|
| 595 |
+
input_data=sample,
|
| 596 |
+
pcd_moved=output[..., :3]
|
| 597 |
+
)
|
| 598 |
+
return result
|
OVOW/third_party/Motion324/model/__init__.py
ADDED
|
File without changes
|
OVOW/third_party/Motion324/model/image_encoder/__init__.py
ADDED
|
File without changes
|
OVOW/third_party/Motion324/model/image_encoder/dino/__init__.py
ADDED
|
File without changes
|
OVOW/third_party/Motion324/model/image_encoder/dino/model_dino.py
ADDED
|
@@ -0,0 +1,859 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 Meta AI and The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
""" PyTorch DINOv2 model."""
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
import collections.abc
|
| 19 |
+
import math
|
| 20 |
+
from typing import Dict, List, Optional, Set, Tuple, Union
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.utils.checkpoint
|
| 24 |
+
from torch import nn
|
| 25 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
| 26 |
+
|
| 27 |
+
from transformers.activations import ACT2FN
|
| 28 |
+
from transformers.modeling_outputs import (
|
| 29 |
+
BackboneOutput,
|
| 30 |
+
BaseModelOutput,
|
| 31 |
+
BaseModelOutputWithPooling,
|
| 32 |
+
ImageClassifierOutput,
|
| 33 |
+
)
|
| 34 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 35 |
+
from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
| 36 |
+
from transformers.utils import (
|
| 37 |
+
add_code_sample_docstrings,
|
| 38 |
+
add_start_docstrings,
|
| 39 |
+
add_start_docstrings_to_model_forward,
|
| 40 |
+
logging,
|
| 41 |
+
replace_return_docstrings,
|
| 42 |
+
)
|
| 43 |
+
from transformers.utils.backbone_utils import BackboneMixin
|
| 44 |
+
from transformers.models.dinov2.configuration_dinov2 import Dinov2Config
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
logger = logging.get_logger(__name__)
|
| 48 |
+
|
| 49 |
+
# General docstring
|
| 50 |
+
_CONFIG_FOR_DOC = "Dinov2Config"
|
| 51 |
+
|
| 52 |
+
# Base docstring
|
| 53 |
+
_CHECKPOINT_FOR_DOC = "facebook/dinov2-base"
|
| 54 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 257, 768]
|
| 55 |
+
|
| 56 |
+
# Image classification docstring
|
| 57 |
+
_IMAGE_CLASS_CHECKPOINT = "facebook/dinov2-small-imagenet1k-1-layer"
|
| 58 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
DINOV2_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
| 62 |
+
"facebook/dinov2-base",
|
| 63 |
+
# See all DINOv2 models at https://huggingface.co/models?filter=dinov2
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class Dinov2Embeddings(nn.Module):
|
| 68 |
+
"""
|
| 69 |
+
Construct the CLS token, mask token, position and patch embeddings.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, config: Dinov2Config) -> None:
|
| 73 |
+
super().__init__()
|
| 74 |
+
|
| 75 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
| 76 |
+
self.mask_token = nn.Parameter(torch.zeros(1, config.hidden_size))
|
| 77 |
+
self.patch_embeddings = Dinov2PatchEmbeddings(config)
|
| 78 |
+
num_patches = self.patch_embeddings.num_patches
|
| 79 |
+
self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
|
| 80 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 81 |
+
self.config = config
|
| 82 |
+
|
| 83 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
| 84 |
+
"""
|
| 85 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
| 86 |
+
resolution images.
|
| 87 |
+
|
| 88 |
+
Source:
|
| 89 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
num_patches = embeddings.shape[1] - 1
|
| 93 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
| 94 |
+
if num_patches == num_positions and height == width:
|
| 95 |
+
return self.position_embeddings
|
| 96 |
+
class_pos_embed = self.position_embeddings[:, 0]
|
| 97 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
| 98 |
+
dim = embeddings.shape[-1]
|
| 99 |
+
height = height // self.config.patch_size
|
| 100 |
+
width = width // self.config.patch_size
|
| 101 |
+
# we add a small number to avoid floating point error in the interpolation
|
| 102 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
| 103 |
+
height, width = height + 0.1, width + 0.1
|
| 104 |
+
patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
|
| 105 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
| 106 |
+
target_dtype = patch_pos_embed.dtype
|
| 107 |
+
patch_pos_embed = nn.functional.interpolate(
|
| 108 |
+
patch_pos_embed.to(dtype=torch.float32),
|
| 109 |
+
scale_factor=(float(height / math.sqrt(num_positions)), float(width / math.sqrt(num_positions))),
|
| 110 |
+
mode="bicubic",
|
| 111 |
+
align_corners=False,
|
| 112 |
+
).to(dtype=target_dtype)
|
| 113 |
+
if int(height) != patch_pos_embed.shape[-2] or int(width) != patch_pos_embed.shape[-1]:
|
| 114 |
+
raise ValueError("Width or height does not match with the interpolated position embeddings")
|
| 115 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
| 116 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
| 117 |
+
|
| 118 |
+
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
|
| 119 |
+
batch_size, _, height, width = pixel_values.shape
|
| 120 |
+
target_dtype = self.patch_embeddings.projection.weight.dtype
|
| 121 |
+
embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
|
| 122 |
+
|
| 123 |
+
if bool_masked_pos is not None:
|
| 124 |
+
embeddings = torch.where(
|
| 125 |
+
bool_masked_pos.unsqueeze(-1), self.mask_token.to(embeddings.dtype).unsqueeze(0), embeddings
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
# add the [CLS] token to the embedded patch tokens
|
| 129 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
| 130 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
| 131 |
+
|
| 132 |
+
# add positional encoding to each token
|
| 133 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
| 134 |
+
|
| 135 |
+
embeddings = self.dropout(embeddings)
|
| 136 |
+
|
| 137 |
+
return embeddings
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class Dinov2PatchEmbeddings(nn.Module):
|
| 141 |
+
"""
|
| 142 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
| 143 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
| 144 |
+
Transformer.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
def __init__(self, config):
|
| 148 |
+
super().__init__()
|
| 149 |
+
image_size, patch_size = config.image_size, config.patch_size
|
| 150 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
| 151 |
+
|
| 152 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
| 153 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
| 154 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 155 |
+
self.image_size = image_size
|
| 156 |
+
self.patch_size = patch_size
|
| 157 |
+
self.num_channels = num_channels
|
| 158 |
+
self.num_patches = num_patches
|
| 159 |
+
|
| 160 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
| 161 |
+
|
| 162 |
+
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
|
| 163 |
+
num_channels = pixel_values.shape[1]
|
| 164 |
+
if num_channels != self.num_channels:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
| 167 |
+
f" Expected {self.num_channels} but got {num_channels}."
|
| 168 |
+
)
|
| 169 |
+
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
| 170 |
+
return embeddings
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention with ViT->Dinov2
|
| 174 |
+
class Dinov2SelfAttention(nn.Module):
|
| 175 |
+
def __init__(self, config: Dinov2Config) -> None:
|
| 176 |
+
super().__init__()
|
| 177 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
| 178 |
+
raise ValueError(
|
| 179 |
+
f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
|
| 180 |
+
f"heads {config.num_attention_heads}."
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
self.num_attention_heads = config.num_attention_heads
|
| 184 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 185 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 186 |
+
|
| 187 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 188 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 189 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
| 190 |
+
|
| 191 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 192 |
+
|
| 193 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
| 194 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
| 195 |
+
x = x.view(new_x_shape)
|
| 196 |
+
return x.permute(0, 2, 1, 3)
|
| 197 |
+
|
| 198 |
+
def forward(
|
| 199 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
| 200 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 201 |
+
mixed_query_layer = self.query(hidden_states)
|
| 202 |
+
|
| 203 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 204 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 205 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
| 206 |
+
|
| 207 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 208 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
| 209 |
+
|
| 210 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
| 211 |
+
|
| 212 |
+
# Normalize the attention scores to probabilities.
|
| 213 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
| 214 |
+
|
| 215 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 216 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 217 |
+
attention_probs = self.dropout(attention_probs)
|
| 218 |
+
|
| 219 |
+
# Mask heads if we want to
|
| 220 |
+
if head_mask is not None:
|
| 221 |
+
attention_probs = attention_probs * head_mask
|
| 222 |
+
|
| 223 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
| 224 |
+
|
| 225 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 226 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 227 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
| 228 |
+
|
| 229 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
| 230 |
+
|
| 231 |
+
return outputs
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->Dinov2
|
| 235 |
+
class Dinov2SelfOutput(nn.Module):
|
| 236 |
+
"""
|
| 237 |
+
The residual connection is defined in Dinov2Layer instead of here (as is the case with other models), due to the
|
| 238 |
+
layernorm applied before each block.
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
def __init__(self, config: Dinov2Config) -> None:
|
| 242 |
+
super().__init__()
|
| 243 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 244 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 245 |
+
|
| 246 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
| 247 |
+
hidden_states = self.dense(hidden_states)
|
| 248 |
+
hidden_states = self.dropout(hidden_states)
|
| 249 |
+
|
| 250 |
+
return hidden_states
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Dinov2
|
| 254 |
+
class Dinov2Attention(nn.Module):
|
| 255 |
+
def __init__(self, config: Dinov2Config) -> None:
|
| 256 |
+
super().__init__()
|
| 257 |
+
self.attention = Dinov2SelfAttention(config)
|
| 258 |
+
self.output = Dinov2SelfOutput(config)
|
| 259 |
+
self.pruned_heads = set()
|
| 260 |
+
|
| 261 |
+
def prune_heads(self, heads: Set[int]) -> None:
|
| 262 |
+
if len(heads) == 0:
|
| 263 |
+
return
|
| 264 |
+
heads, index = find_pruneable_heads_and_indices(
|
| 265 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# Prune linear layers
|
| 269 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
| 270 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
| 271 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
| 272 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
| 273 |
+
|
| 274 |
+
# Update hyper params and store pruned heads
|
| 275 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
| 276 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
| 277 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
| 278 |
+
|
| 279 |
+
def forward(
|
| 280 |
+
self,
|
| 281 |
+
hidden_states: torch.Tensor,
|
| 282 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 283 |
+
output_attentions: bool = False,
|
| 284 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 285 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
| 286 |
+
|
| 287 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
| 288 |
+
|
| 289 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
| 290 |
+
return outputs
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class Dinov2LayerScale(nn.Module):
|
| 294 |
+
def __init__(self, config) -> None:
|
| 295 |
+
super().__init__()
|
| 296 |
+
self.lambda1 = nn.Parameter(config.layerscale_value * torch.ones(config.hidden_size))
|
| 297 |
+
|
| 298 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 299 |
+
return hidden_state * self.lambda1
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
# Copied from transformers.models.beit.modeling_beit.drop_path
|
| 303 |
+
def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
|
| 304 |
+
"""
|
| 305 |
+
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
|
| 306 |
+
|
| 307 |
+
Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
|
| 308 |
+
however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
|
| 309 |
+
See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
|
| 310 |
+
layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
|
| 311 |
+
argument.
|
| 312 |
+
"""
|
| 313 |
+
if drop_prob == 0.0 or not training:
|
| 314 |
+
return input
|
| 315 |
+
keep_prob = 1 - drop_prob
|
| 316 |
+
shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
| 317 |
+
random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
|
| 318 |
+
random_tensor.floor_() # binarize
|
| 319 |
+
output = input.div(keep_prob) * random_tensor
|
| 320 |
+
return output
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
# Copied from transformers.models.beit.modeling_beit.BeitDropPath
|
| 324 |
+
class Dinov2DropPath(nn.Module):
|
| 325 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
| 326 |
+
|
| 327 |
+
def __init__(self, drop_prob: Optional[float] = None) -> None:
|
| 328 |
+
super().__init__()
|
| 329 |
+
self.drop_prob = drop_prob
|
| 330 |
+
|
| 331 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 332 |
+
return drop_path(hidden_states, self.drop_prob, self.training)
|
| 333 |
+
|
| 334 |
+
def extra_repr(self) -> str:
|
| 335 |
+
return "p={}".format(self.drop_prob)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class Dinov2MLP(nn.Module):
|
| 339 |
+
def __init__(self, config) -> None:
|
| 340 |
+
super().__init__()
|
| 341 |
+
in_features = out_features = config.hidden_size
|
| 342 |
+
hidden_features = int(config.hidden_size * config.mlp_ratio)
|
| 343 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=True)
|
| 344 |
+
if isinstance(config.hidden_act, str):
|
| 345 |
+
self.activation = ACT2FN[config.hidden_act]
|
| 346 |
+
else:
|
| 347 |
+
self.activation = config.hidden_act
|
| 348 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=True)
|
| 349 |
+
|
| 350 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 351 |
+
hidden_state = self.fc1(hidden_state)
|
| 352 |
+
hidden_state = self.activation(hidden_state)
|
| 353 |
+
hidden_state = self.fc2(hidden_state)
|
| 354 |
+
return hidden_state
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class Dinov2SwiGLUFFN(nn.Module):
|
| 358 |
+
def __init__(self, config) -> None:
|
| 359 |
+
super().__init__()
|
| 360 |
+
in_features = out_features = config.hidden_size
|
| 361 |
+
hidden_features = int(config.hidden_size * config.mlp_ratio)
|
| 362 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
| 363 |
+
|
| 364 |
+
self.weights_in = nn.Linear(in_features, 2 * hidden_features, bias=True)
|
| 365 |
+
self.weights_out = nn.Linear(hidden_features, out_features, bias=True)
|
| 366 |
+
|
| 367 |
+
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
|
| 368 |
+
hidden_state = self.weights_in(hidden_state)
|
| 369 |
+
x1, x2 = hidden_state.chunk(2, dim=-1)
|
| 370 |
+
hidden = nn.functional.silu(x1) * x2
|
| 371 |
+
return self.weights_out(hidden)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class Dinov2Layer(nn.Module):
|
| 375 |
+
"""This corresponds to the Block class in the original implementation."""
|
| 376 |
+
|
| 377 |
+
def __init__(self, config: Dinov2Config) -> None:
|
| 378 |
+
super().__init__()
|
| 379 |
+
|
| 380 |
+
self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 381 |
+
self.attention = Dinov2Attention(config)
|
| 382 |
+
self.layer_scale1 = Dinov2LayerScale(config)
|
| 383 |
+
self.drop_path = Dinov2DropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
|
| 384 |
+
|
| 385 |
+
self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 386 |
+
|
| 387 |
+
if config.use_swiglu_ffn:
|
| 388 |
+
self.mlp = Dinov2SwiGLUFFN(config)
|
| 389 |
+
else:
|
| 390 |
+
self.mlp = Dinov2MLP(config)
|
| 391 |
+
self.layer_scale2 = Dinov2LayerScale(config)
|
| 392 |
+
|
| 393 |
+
def forward(
|
| 394 |
+
self,
|
| 395 |
+
hidden_states: torch.Tensor,
|
| 396 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 397 |
+
output_attentions: bool = False,
|
| 398 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
| 399 |
+
self_attention_outputs = self.attention(
|
| 400 |
+
self.norm1(hidden_states), # in Dinov2, layernorm is applied before self-attention
|
| 401 |
+
head_mask,
|
| 402 |
+
output_attentions=output_attentions,
|
| 403 |
+
)
|
| 404 |
+
attention_output = self_attention_outputs[0]
|
| 405 |
+
|
| 406 |
+
attention_output = self.layer_scale1(attention_output)
|
| 407 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
| 408 |
+
|
| 409 |
+
# first residual connection
|
| 410 |
+
hidden_states = self.drop_path(attention_output) + hidden_states
|
| 411 |
+
|
| 412 |
+
# in Dinov2, layernorm is also applied after self-attention
|
| 413 |
+
layer_output = self.norm2(hidden_states)
|
| 414 |
+
layer_output = self.mlp(layer_output)
|
| 415 |
+
layer_output = self.layer_scale2(layer_output)
|
| 416 |
+
|
| 417 |
+
# second residual connection
|
| 418 |
+
layer_output = self.drop_path(layer_output) + hidden_states
|
| 419 |
+
|
| 420 |
+
outputs = (layer_output,) + outputs
|
| 421 |
+
|
| 422 |
+
return outputs
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
# Copied from transformers.models.vit.modeling_vit.ViTEncoder with ViT->Dinov2
|
| 426 |
+
class Dinov2Encoder(nn.Module):
|
| 427 |
+
def __init__(self, config: Dinov2Config) -> None:
|
| 428 |
+
super().__init__()
|
| 429 |
+
self.config = config
|
| 430 |
+
self.layer = nn.ModuleList([Dinov2Layer(config) for _ in range(config.num_hidden_layers)])
|
| 431 |
+
self.gradient_checkpointing = False
|
| 432 |
+
|
| 433 |
+
def forward(
|
| 434 |
+
self,
|
| 435 |
+
hidden_states: torch.Tensor,
|
| 436 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 437 |
+
output_attentions: bool = False,
|
| 438 |
+
output_hidden_states: bool = False,
|
| 439 |
+
return_dict: bool = True,
|
| 440 |
+
) -> Union[tuple, BaseModelOutput]:
|
| 441 |
+
all_hidden_states = () if output_hidden_states else None
|
| 442 |
+
all_self_attentions = () if output_attentions else None
|
| 443 |
+
|
| 444 |
+
for i, layer_module in enumerate(self.layer):
|
| 445 |
+
if output_hidden_states:
|
| 446 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 447 |
+
|
| 448 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
| 449 |
+
|
| 450 |
+
if self.gradient_checkpointing and self.training:
|
| 451 |
+
layer_outputs = self._gradient_checkpointing_func(
|
| 452 |
+
layer_module.__call__,
|
| 453 |
+
hidden_states,
|
| 454 |
+
layer_head_mask,
|
| 455 |
+
output_attentions,
|
| 456 |
+
)
|
| 457 |
+
else:
|
| 458 |
+
layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
|
| 459 |
+
|
| 460 |
+
hidden_states = layer_outputs[0]
|
| 461 |
+
|
| 462 |
+
if output_attentions:
|
| 463 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
| 464 |
+
|
| 465 |
+
if output_hidden_states:
|
| 466 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 467 |
+
|
| 468 |
+
if not return_dict:
|
| 469 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
| 470 |
+
return BaseModelOutput(
|
| 471 |
+
last_hidden_state=hidden_states,
|
| 472 |
+
hidden_states=all_hidden_states,
|
| 473 |
+
attentions=all_self_attentions,
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
class Dinov2PreTrainedModel(PreTrainedModel):
|
| 478 |
+
"""
|
| 479 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 480 |
+
models.
|
| 481 |
+
"""
|
| 482 |
+
|
| 483 |
+
config_class = Dinov2Config
|
| 484 |
+
base_model_prefix = "dinov2"
|
| 485 |
+
main_input_name = "pixel_values"
|
| 486 |
+
supports_gradient_checkpointing = True
|
| 487 |
+
|
| 488 |
+
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
|
| 489 |
+
"""Initialize the weights"""
|
| 490 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
| 491 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
| 492 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
| 493 |
+
module.weight.data = nn.init.trunc_normal_(
|
| 494 |
+
module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
|
| 495 |
+
).to(module.weight.dtype)
|
| 496 |
+
if module.bias is not None:
|
| 497 |
+
module.bias.data.zero_()
|
| 498 |
+
elif isinstance(module, nn.LayerNorm):
|
| 499 |
+
module.bias.data.zero_()
|
| 500 |
+
module.weight.data.fill_(1.0)
|
| 501 |
+
elif isinstance(module, Dinov2Embeddings):
|
| 502 |
+
module.position_embeddings.data = nn.init.trunc_normal_(
|
| 503 |
+
module.position_embeddings.data.to(torch.float32),
|
| 504 |
+
mean=0.0,
|
| 505 |
+
std=self.config.initializer_range,
|
| 506 |
+
).to(module.position_embeddings.dtype)
|
| 507 |
+
|
| 508 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
| 509 |
+
module.cls_token.data.to(torch.float32),
|
| 510 |
+
mean=0.0,
|
| 511 |
+
std=self.config.initializer_range,
|
| 512 |
+
).to(module.cls_token.dtype)
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
DINOV2_START_DOCSTRING = r"""
|
| 516 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
| 517 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
| 518 |
+
behavior.
|
| 519 |
+
|
| 520 |
+
Parameters:
|
| 521 |
+
config ([`Dinov2Config`]): Model configuration class with all the parameters of the model.
|
| 522 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 523 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 524 |
+
"""
|
| 525 |
+
|
| 526 |
+
DINOV2_BASE_INPUTS_DOCSTRING = r"""
|
| 527 |
+
Args:
|
| 528 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 529 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 530 |
+
[`BitImageProcessor.preprocess`] for details.
|
| 531 |
+
|
| 532 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, sequence_length)`):
|
| 533 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0). Only relevant for
|
| 534 |
+
pre-training.
|
| 535 |
+
|
| 536 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 537 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 538 |
+
|
| 539 |
+
- 1 indicates the head is **not masked**,
|
| 540 |
+
- 0 indicates the head is **masked**.
|
| 541 |
+
|
| 542 |
+
output_attentions (`bool`, *optional*):
|
| 543 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 544 |
+
tensors for more detail.
|
| 545 |
+
output_hidden_states (`bool`, *optional*):
|
| 546 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 547 |
+
more detail.
|
| 548 |
+
return_dict (`bool`, *optional*):
|
| 549 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
DINOV2_INPUTS_DOCSTRING = r"""
|
| 553 |
+
Args:
|
| 554 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
| 555 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
|
| 556 |
+
[`BitImageProcessor.preprocess`] for details.
|
| 557 |
+
|
| 558 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
| 559 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
| 560 |
+
|
| 561 |
+
- 1 indicates the head is **not masked**,
|
| 562 |
+
- 0 indicates the head is **masked**.
|
| 563 |
+
|
| 564 |
+
output_attentions (`bool`, *optional*):
|
| 565 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
| 566 |
+
tensors for more detail.
|
| 567 |
+
output_hidden_states (`bool`, *optional*):
|
| 568 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 569 |
+
more detail.
|
| 570 |
+
return_dict (`bool`, *optional*):
|
| 571 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 572 |
+
"""
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
@add_start_docstrings(
|
| 576 |
+
"The bare DINOv2 Model transformer outputting raw hidden-states without any specific head on top.",
|
| 577 |
+
DINOV2_START_DOCSTRING,
|
| 578 |
+
)
|
| 579 |
+
class Dinov2Model(Dinov2PreTrainedModel):
|
| 580 |
+
def __init__(self, config: Dinov2Config):
|
| 581 |
+
super().__init__(config)
|
| 582 |
+
self.config = config
|
| 583 |
+
|
| 584 |
+
self.embeddings = Dinov2Embeddings(config)
|
| 585 |
+
self.encoder = Dinov2Encoder(config)
|
| 586 |
+
|
| 587 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 588 |
+
|
| 589 |
+
# Initialize weights and apply final processing
|
| 590 |
+
self.post_init()
|
| 591 |
+
|
| 592 |
+
def get_input_embeddings(self) -> Dinov2PatchEmbeddings:
|
| 593 |
+
return self.embeddings.patch_embeddings
|
| 594 |
+
|
| 595 |
+
def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
|
| 596 |
+
"""
|
| 597 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
| 598 |
+
class PreTrainedModel
|
| 599 |
+
"""
|
| 600 |
+
for layer, heads in heads_to_prune.items():
|
| 601 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
| 602 |
+
|
| 603 |
+
@add_start_docstrings_to_model_forward(DINOV2_BASE_INPUTS_DOCSTRING)
|
| 604 |
+
@add_code_sample_docstrings(
|
| 605 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 606 |
+
output_type=BaseModelOutputWithPooling,
|
| 607 |
+
config_class=_CONFIG_FOR_DOC,
|
| 608 |
+
modality="vision",
|
| 609 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
| 610 |
+
)
|
| 611 |
+
def forward(
|
| 612 |
+
self,
|
| 613 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 614 |
+
bool_masked_pos: Optional[torch.Tensor] = None,
|
| 615 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 616 |
+
output_attentions: Optional[bool] = None,
|
| 617 |
+
output_hidden_states: Optional[bool] = None,
|
| 618 |
+
return_dict: Optional[bool] = None,
|
| 619 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
| 620 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 621 |
+
output_hidden_states = (
|
| 622 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 623 |
+
)
|
| 624 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 625 |
+
|
| 626 |
+
if pixel_values is None:
|
| 627 |
+
raise ValueError("You have to specify pixel_values")
|
| 628 |
+
|
| 629 |
+
# Prepare head mask if needed
|
| 630 |
+
# 1.0 in head_mask indicate we keep the head
|
| 631 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 632 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 633 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 634 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
| 635 |
+
|
| 636 |
+
embedding_output = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
|
| 637 |
+
|
| 638 |
+
encoder_outputs = self.encoder(
|
| 639 |
+
embedding_output,
|
| 640 |
+
head_mask=head_mask,
|
| 641 |
+
output_attentions=output_attentions,
|
| 642 |
+
output_hidden_states=output_hidden_states,
|
| 643 |
+
return_dict=return_dict,
|
| 644 |
+
)
|
| 645 |
+
sequence_output = encoder_outputs[0]
|
| 646 |
+
sequence_output = self.layernorm(sequence_output)
|
| 647 |
+
pooled_output = sequence_output[:, 0, :]
|
| 648 |
+
|
| 649 |
+
if not return_dict:
|
| 650 |
+
head_outputs = (sequence_output, pooled_output)
|
| 651 |
+
return head_outputs + encoder_outputs[1:]
|
| 652 |
+
|
| 653 |
+
return BaseModelOutputWithPooling(
|
| 654 |
+
last_hidden_state=sequence_output,
|
| 655 |
+
pooler_output=pooled_output,
|
| 656 |
+
hidden_states=encoder_outputs.hidden_states,
|
| 657 |
+
attentions=encoder_outputs.attentions,
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
@add_start_docstrings(
|
| 662 |
+
"""
|
| 663 |
+
Dinov2 Model transformer with an image classification head on top (a linear layer on top of the final hidden state
|
| 664 |
+
of the [CLS] token) e.g. for ImageNet.
|
| 665 |
+
""",
|
| 666 |
+
DINOV2_START_DOCSTRING,
|
| 667 |
+
)
|
| 668 |
+
class Dinov2ForImageClassification(Dinov2PreTrainedModel):
|
| 669 |
+
def __init__(self, config: Dinov2Config) -> None:
|
| 670 |
+
super().__init__(config)
|
| 671 |
+
|
| 672 |
+
self.num_labels = config.num_labels
|
| 673 |
+
self.dinov2 = Dinov2Model(config)
|
| 674 |
+
|
| 675 |
+
# Classifier head
|
| 676 |
+
self.classifier = (
|
| 677 |
+
nn.Linear(config.hidden_size * 2, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
# Initialize weights and apply final processing
|
| 681 |
+
self.post_init()
|
| 682 |
+
|
| 683 |
+
@add_start_docstrings_to_model_forward(DINOV2_INPUTS_DOCSTRING)
|
| 684 |
+
@add_code_sample_docstrings(
|
| 685 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
| 686 |
+
output_type=ImageClassifierOutput,
|
| 687 |
+
config_class=_CONFIG_FOR_DOC,
|
| 688 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
| 689 |
+
)
|
| 690 |
+
def forward(
|
| 691 |
+
self,
|
| 692 |
+
pixel_values: Optional[torch.Tensor] = None,
|
| 693 |
+
head_mask: Optional[torch.Tensor] = None,
|
| 694 |
+
labels: Optional[torch.Tensor] = None,
|
| 695 |
+
output_attentions: Optional[bool] = None,
|
| 696 |
+
output_hidden_states: Optional[bool] = None,
|
| 697 |
+
return_dict: Optional[bool] = None,
|
| 698 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
| 699 |
+
r"""
|
| 700 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 701 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
| 702 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
| 703 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 704 |
+
"""
|
| 705 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 706 |
+
|
| 707 |
+
outputs = self.dinov2(
|
| 708 |
+
pixel_values,
|
| 709 |
+
head_mask=head_mask,
|
| 710 |
+
output_attentions=output_attentions,
|
| 711 |
+
output_hidden_states=output_hidden_states,
|
| 712 |
+
return_dict=return_dict,
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
sequence_output = outputs[0] # batch_size, sequence_length, hidden_size
|
| 716 |
+
|
| 717 |
+
cls_token = sequence_output[:, 0]
|
| 718 |
+
patch_tokens = sequence_output[:, 1:]
|
| 719 |
+
|
| 720 |
+
linear_input = torch.cat([cls_token, patch_tokens.mean(dim=1)], dim=1)
|
| 721 |
+
|
| 722 |
+
logits = self.classifier(linear_input)
|
| 723 |
+
|
| 724 |
+
loss = None
|
| 725 |
+
if labels is not None:
|
| 726 |
+
# move labels to correct device to enable model parallelism
|
| 727 |
+
labels = labels.to(logits.device)
|
| 728 |
+
if self.config.problem_type is None:
|
| 729 |
+
if self.num_labels == 1:
|
| 730 |
+
self.config.problem_type = "regression"
|
| 731 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 732 |
+
self.config.problem_type = "single_label_classification"
|
| 733 |
+
else:
|
| 734 |
+
self.config.problem_type = "multi_label_classification"
|
| 735 |
+
|
| 736 |
+
if self.config.problem_type == "regression":
|
| 737 |
+
loss_fct = MSELoss()
|
| 738 |
+
if self.num_labels == 1:
|
| 739 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 740 |
+
else:
|
| 741 |
+
loss = loss_fct(logits, labels)
|
| 742 |
+
elif self.config.problem_type == "single_label_classification":
|
| 743 |
+
loss_fct = CrossEntropyLoss()
|
| 744 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 745 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 746 |
+
loss_fct = BCEWithLogitsLoss()
|
| 747 |
+
loss = loss_fct(logits, labels)
|
| 748 |
+
|
| 749 |
+
if not return_dict:
|
| 750 |
+
output = (logits,) + outputs[2:]
|
| 751 |
+
return ((loss,) + output) if loss is not None else output
|
| 752 |
+
|
| 753 |
+
return ImageClassifierOutput(
|
| 754 |
+
loss=loss,
|
| 755 |
+
logits=logits,
|
| 756 |
+
hidden_states=outputs.hidden_states,
|
| 757 |
+
attentions=outputs.attentions,
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
|
| 761 |
+
@add_start_docstrings(
|
| 762 |
+
"""
|
| 763 |
+
Dinov2 backbone, to be used with frameworks like DETR and MaskFormer.
|
| 764 |
+
""",
|
| 765 |
+
DINOV2_START_DOCSTRING,
|
| 766 |
+
)
|
| 767 |
+
class Dinov2Backbone(Dinov2PreTrainedModel, BackboneMixin):
|
| 768 |
+
def __init__(self, config):
|
| 769 |
+
super().__init__(config)
|
| 770 |
+
super()._init_backbone(config)
|
| 771 |
+
|
| 772 |
+
self.num_features = [config.hidden_size for _ in range(config.num_hidden_layers + 1)]
|
| 773 |
+
self.embeddings = Dinov2Embeddings(config)
|
| 774 |
+
self.encoder = Dinov2Encoder(config)
|
| 775 |
+
|
| 776 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 777 |
+
|
| 778 |
+
# Initialize weights and apply final processing
|
| 779 |
+
self.post_init()
|
| 780 |
+
|
| 781 |
+
def get_input_embeddings(self) -> Dinov2PatchEmbeddings:
|
| 782 |
+
return self.embeddings.patch_embeddings
|
| 783 |
+
|
| 784 |
+
@add_start_docstrings_to_model_forward(DINOV2_INPUTS_DOCSTRING)
|
| 785 |
+
@replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
|
| 786 |
+
def forward(
|
| 787 |
+
self,
|
| 788 |
+
pixel_values: torch.Tensor,
|
| 789 |
+
output_hidden_states: Optional[bool] = None,
|
| 790 |
+
output_attentions: Optional[bool] = None,
|
| 791 |
+
return_dict: Optional[bool] = None,
|
| 792 |
+
) -> BackboneOutput:
|
| 793 |
+
"""
|
| 794 |
+
Returns:
|
| 795 |
+
|
| 796 |
+
Examples:
|
| 797 |
+
|
| 798 |
+
```python
|
| 799 |
+
>>> from transformers import AutoImageProcessor, AutoBackbone
|
| 800 |
+
>>> import torch
|
| 801 |
+
>>> from PIL import Image
|
| 802 |
+
>>> import requests
|
| 803 |
+
|
| 804 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 805 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
| 806 |
+
|
| 807 |
+
>>> processor = AutoImageProcessor.from_pretrained("facebook/dinov2-base")
|
| 808 |
+
>>> model = AutoBackbone.from_pretrained(
|
| 809 |
+
... "facebook/dinov2-base", out_features=["stage2", "stage5", "stage8", "stage11"]
|
| 810 |
+
... )
|
| 811 |
+
|
| 812 |
+
>>> inputs = processor(image, return_tensors="pt")
|
| 813 |
+
|
| 814 |
+
>>> outputs = model(**inputs)
|
| 815 |
+
>>> feature_maps = outputs.feature_maps
|
| 816 |
+
>>> list(feature_maps[-1].shape)
|
| 817 |
+
[1, 768, 16, 16]
|
| 818 |
+
```"""
|
| 819 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 820 |
+
output_hidden_states = (
|
| 821 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 822 |
+
)
|
| 823 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 824 |
+
|
| 825 |
+
embedding_output = self.embeddings(pixel_values)
|
| 826 |
+
|
| 827 |
+
outputs = self.encoder(
|
| 828 |
+
embedding_output, output_hidden_states=True, output_attentions=output_attentions, return_dict=return_dict
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
hidden_states = outputs.hidden_states if return_dict else outputs[1]
|
| 832 |
+
|
| 833 |
+
feature_maps = ()
|
| 834 |
+
for stage, hidden_state in zip(self.stage_names, hidden_states):
|
| 835 |
+
if stage in self.out_features:
|
| 836 |
+
if self.config.apply_layernorm:
|
| 837 |
+
hidden_state = self.layernorm(hidden_state)
|
| 838 |
+
if self.config.reshape_hidden_states:
|
| 839 |
+
hidden_state = hidden_state[:, 1:]
|
| 840 |
+
# this was actually a bug in the original implementation that we copied here,
|
| 841 |
+
# cause normally the order is height, width
|
| 842 |
+
batch_size, _, height, width = pixel_values.shape
|
| 843 |
+
patch_size = self.config.patch_size
|
| 844 |
+
hidden_state = hidden_state.reshape(batch_size, height // patch_size, width // patch_size, -1)
|
| 845 |
+
hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
|
| 846 |
+
feature_maps += (hidden_state,)
|
| 847 |
+
|
| 848 |
+
if not return_dict:
|
| 849 |
+
if output_hidden_states:
|
| 850 |
+
output = (feature_maps,) + outputs[1:]
|
| 851 |
+
else:
|
| 852 |
+
output = (feature_maps,) + outputs[2:]
|
| 853 |
+
return output
|
| 854 |
+
|
| 855 |
+
return BackboneOutput(
|
| 856 |
+
feature_maps=feature_maps,
|
| 857 |
+
hidden_states=outputs.hidden_states if output_hidden_states else None,
|
| 858 |
+
attentions=outputs.attentions if output_attentions else None,
|
| 859 |
+
)
|
OVOW/third_party/Motion324/model/image_encoder/dinov2.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EAN = [0.485, 0.456, 0.406]
|
| 9 |
+
_RESNET_STD = [0.229, 0.224, 0.225]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PositionGetter:
|
| 13 |
+
"""Generates and caches 2D spatial positions for patches in a grid."""
|
| 14 |
+
|
| 15 |
+
def __init__(self):
|
| 16 |
+
self.position_cache: Dict[Tuple[int, int], torch.Tensor] = {}
|
| 17 |
+
|
| 18 |
+
def __call__(self, batch_size: int, height: int, width: int, device: torch.device) -> torch.Tensor:
|
| 19 |
+
"""
|
| 20 |
+
Generate spatial positions for a batch of patches.
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
batch_size: Number of samples in the batch
|
| 24 |
+
height: Height of the grid in patches
|
| 25 |
+
width: Width of the grid in patches
|
| 26 |
+
device: Target device for the position tensor
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
Tensor of shape (batch_size, height*width, 2) containing y,x coordinates
|
| 30 |
+
"""
|
| 31 |
+
if (height, width) not in self.position_cache:
|
| 32 |
+
y_coords = torch.arange(height, device=device)
|
| 33 |
+
x_coords = torch.arange(width, device=device)
|
| 34 |
+
positions = torch.cartesian_prod(y_coords, x_coords)
|
| 35 |
+
self.position_cache[height, width] = positions
|
| 36 |
+
|
| 37 |
+
cached_positions = self.position_cache[height, width]
|
| 38 |
+
return cached_positions.view(1, height * width, 2).expand(batch_size, -1, -1).clone()
|
| 39 |
+
|
| 40 |
+
class DinoEncoder(nn.Module):
|
| 41 |
+
"""DINOv2 vision transformer encoder for extracting image features."""
|
| 42 |
+
|
| 43 |
+
def __init__(self, patch_size=14, model_name='dinov2_vitb14'):
|
| 44 |
+
super(DinoEncoder, self).__init__()
|
| 45 |
+
repo_override = os.environ.get("DINOv2_REPO")
|
| 46 |
+
local_repo_candidates = [
|
| 47 |
+
repo_override,
|
| 48 |
+
os.path.join(torch.hub.get_dir(), "facebookresearch_dinov2_main"),
|
| 49 |
+
"~/.cache/torch/hub/facebookresearch_dinov2_main",
|
| 50 |
+
]
|
| 51 |
+
local_repo = next((p for p in local_repo_candidates if p and os.path.isdir(p)), None)
|
| 52 |
+
# pretrained=False: the backbone weights are restored from the Motion324
|
| 53 |
+
# checkpoint (image_encoder.model.*), so skip the network download that
|
| 54 |
+
# fails offline (SSL/CA) and would be overwritten anyway.
|
| 55 |
+
if local_repo:
|
| 56 |
+
self.model = torch.hub.load(local_repo, model_name, source="local", pretrained=False)
|
| 57 |
+
else:
|
| 58 |
+
self.model = torch.hub.load("facebookresearch/dinov2", model_name, pretrained=False)
|
| 59 |
+
if hasattr(self.model, 'patch_size'):
|
| 60 |
+
assert self.model.patch_size == patch_size, \
|
| 61 |
+
f"DINOv2 model's patch size ({self.model.patch_size}) must match provided patch_size ({patch_size})"
|
| 62 |
+
else:
|
| 63 |
+
print(f"Warning: DINOv2 model does not expose patch_size. Assuming it is {patch_size}.")
|
| 64 |
+
|
| 65 |
+
self.patch_size = patch_size
|
| 66 |
+
self.position_getter = PositionGetter()
|
| 67 |
+
|
| 68 |
+
# For fixed 224x224 input with patch_size=14
|
| 69 |
+
self.image_size = 224
|
| 70 |
+
self.num_patches_per_dim = self.image_size // self.patch_size # 16
|
| 71 |
+
self.num_patches_total = self.num_patches_per_dim * self.num_patches_per_dim # 256
|
| 72 |
+
|
| 73 |
+
for param in self.model.parameters():
|
| 74 |
+
param.requires_grad = False
|
| 75 |
+
|
| 76 |
+
self.model.eval()
|
| 77 |
+
|
| 78 |
+
def forward(self, image):
|
| 79 |
+
"""
|
| 80 |
+
Forward pass through DINOv2 encoder.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
image: Input images of shape (B, C, H, W), e.g., (B, 3, 224, 224)
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
encoded_feats: Patch features of shape (B, N_patches, D_embed)
|
| 87 |
+
"""
|
| 88 |
+
B, C, H, W = image.shape
|
| 89 |
+
device = image.device
|
| 90 |
+
|
| 91 |
+
resnet_mean = torch.tensor(_RESNET_MEAN, device=device).view(1, 3, 1, 1)
|
| 92 |
+
resnet_std = torch.tensor(_RESNET_STD, device=device).view(1, 3, 1, 1)
|
| 93 |
+
images_resnet_norm = (image - resnet_mean) / resnet_std
|
| 94 |
+
|
| 95 |
+
assert H == self.image_size and W == self.image_size, \
|
| 96 |
+
f"Input image size must be {self.image_size}x{self.image_size}, but got {H}x{W}"
|
| 97 |
+
|
| 98 |
+
encoded_feats = self._process_images(images_resnet_norm)
|
| 99 |
+
return encoded_feats
|
| 100 |
+
|
| 101 |
+
def _process_images(self, images):
|
| 102 |
+
"""
|
| 103 |
+
Process a batch of images through DINO encoder.
|
| 104 |
+
|
| 105 |
+
Args:
|
| 106 |
+
images: Input images of shape (B, C, H, W), e.g., (B, 3, 224, 224)
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
encoded_features: Patch features
|
| 110 |
+
"""
|
| 111 |
+
B, C, H, W = images.shape
|
| 112 |
+
features_dict = self.model.forward_features(images)
|
| 113 |
+
|
| 114 |
+
# Get patch tokens
|
| 115 |
+
if 'x_norm_patchtokens' in features_dict:
|
| 116 |
+
encoded_features = features_dict['x_norm_patchtokens']
|
| 117 |
+
elif 'x_patchtokens' in features_dict:
|
| 118 |
+
encoded_features = features_dict['x_patchtokens']
|
| 119 |
+
else:
|
| 120 |
+
if isinstance(features_dict, torch.Tensor) and features_dict.ndim == 3 and features_dict.shape[0] == B:
|
| 121 |
+
num_expected_patches = (H // self.patch_size) * (W // self.patch_size)
|
| 122 |
+
if features_dict.shape[1] == num_expected_patches:
|
| 123 |
+
encoded_features = features_dict
|
| 124 |
+
else:
|
| 125 |
+
raise KeyError(f"DINOv2 output shape {features_dict.shape} does not match expected patch tokens")
|
| 126 |
+
else:
|
| 127 |
+
available_keys = list(features_dict.keys()) if isinstance(features_dict, dict) else 'N/A'
|
| 128 |
+
raise KeyError(f"Could not find patch tokens in DINOv2 output. Available keys: {available_keys}")
|
| 129 |
+
|
| 130 |
+
if hasattr(self.model, 'embed_dim'):
|
| 131 |
+
assert encoded_features.shape[-1] == self.model.embed_dim, \
|
| 132 |
+
f"Feature dimension {encoded_features.shape[-1]} does not match model embed_dim {self.model.embed_dim}"
|
| 133 |
+
|
| 134 |
+
assert encoded_features.shape[1] == self.num_patches_total, \
|
| 135 |
+
f"Number of patches {encoded_features.shape[1]} does not match expected {self.num_patches_total}"
|
| 136 |
+
|
| 137 |
+
return encoded_features
|
| 138 |
+
|
| 139 |
+
def train(self, mode: bool = False):
|
| 140 |
+
"""Override train method to keep DINO model in eval mode."""
|
| 141 |
+
super(DinoEncoder, self).train(mode)
|
| 142 |
+
if self.model is not None:
|
| 143 |
+
self.model.eval()
|
| 144 |
+
return self
|
OVOW/third_party/Motion324/model/loss.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from easydict import EasyDict as edict
|
| 5 |
+
|
| 6 |
+
class MSELossComputer(nn.Module):
|
| 7 |
+
def __init__(self, config):
|
| 8 |
+
"""
|
| 9 |
+
Initializes the LossComputer.
|
| 10 |
+
|
| 11 |
+
Args:
|
| 12 |
+
config: Configuration object. Expected to have config.training.coord_mse_loss_weight.
|
| 13 |
+
"""
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.config = config
|
| 16 |
+
|
| 17 |
+
# Ensure the config has 'coord_mse_loss_weight' defined.
|
| 18 |
+
if not hasattr(self.config, 'training') or \
|
| 19 |
+
not hasattr(self.config.training, 'coord_mse_loss_weight'):
|
| 20 |
+
raise ValueError(
|
| 21 |
+
"Configuration must have 'config.training.coord_mse_loss_weight' defined."
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
def forward(
|
| 25 |
+
self,
|
| 26 |
+
coords_pred: torch.Tensor,
|
| 27 |
+
coords_target: torch.Tensor,
|
| 28 |
+
):
|
| 29 |
+
"""
|
| 30 |
+
Calculate Mean Squared Error (MSE) loss for coordinates.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
coords_pred (torch.Tensor): Predicted coordinates. Shape [B, T, N, C].
|
| 34 |
+
coords_target (torch.Tensor): Ground truth coordinates. Shape [B, T, N, C].
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
edict: Dictionary of loss metrics, containing 'loss' and 'coord_mse_loss'.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
# Determine device from input tensor
|
| 41 |
+
current_device = coords_pred.device
|
| 42 |
+
|
| 43 |
+
total_loss = torch.tensor(0.0, device=current_device)
|
| 44 |
+
loss_metrics = edict()
|
| 45 |
+
|
| 46 |
+
# --- Coordinate MSE Loss ---
|
| 47 |
+
coord_mse_loss_value = torch.tensor(0.0, device=current_device)
|
| 48 |
+
|
| 49 |
+
# Validate shapes
|
| 50 |
+
if not (coords_pred.ndim == 4 and \
|
| 51 |
+
coords_target.ndim == 4 and \
|
| 52 |
+
coords_pred.shape == coords_target.shape):
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"Shape mismatch or invalid shape for coordinate MSE. "
|
| 55 |
+
f"Expected both tensors of shape (B, T, N, C). "
|
| 56 |
+
f"Got pred: {coords_pred.shape}, target: {coords_target.shape}"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
if self.config.training.coord_mse_loss_weight > 0.0:
|
| 60 |
+
coord_mse_loss_value = F.mse_loss(coords_pred, coords_target)
|
| 61 |
+
total_loss += self.config.training.coord_mse_loss_weight * coord_mse_loss_value
|
| 62 |
+
|
| 63 |
+
loss_metrics.coord_mse_loss = coord_mse_loss_value
|
| 64 |
+
loss_metrics.loss = total_loss # The final combined loss (which is just coord_mse_loss weighted)
|
| 65 |
+
|
| 66 |
+
return loss_metrics
|
OVOW/third_party/Motion324/model/transformer.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025 Haian Jin. Created for the LVSM project (ICLR 2025).
|
| 2 |
+
# Modifications Copyright (c) 2025 Hongyuan Chen.
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
import xformers.ops as xops
|
| 10 |
+
except ImportError:
|
| 11 |
+
raise ImportError("Please use flashatt v2")
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def init_weights(module, std=0.02):
|
| 16 |
+
"""Initialize weights for linear and embedding layers.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
module: Module to initialize
|
| 20 |
+
std: Standard deviation for normal initialization
|
| 21 |
+
"""
|
| 22 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
| 23 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
| 24 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
| 25 |
+
torch.nn.init.zeros_(module.bias)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# src: https://github.com/pytorch/benchmark/blob/main/torchbenchmark/models/llama/model.py#L28
|
| 30 |
+
class RMSNorm(nn.Module):
|
| 31 |
+
def __init__(self, dim: int, eps: float = 1e-5):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.eps = eps
|
| 34 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 35 |
+
|
| 36 |
+
def _norm(self, x):
|
| 37 |
+
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
output = self._norm(x.float()).type_as(x)
|
| 41 |
+
|
| 42 |
+
return output * self.weight.type_as(x)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class MLP(nn.Module):
|
| 47 |
+
"""
|
| 48 |
+
Multi-Layer Perceptron block.
|
| 49 |
+
Reference: https://github.com/facebookresearch/dino/blob/7c446df5b9f45747937fb0d72314eb9f7b66930a/vision_transformer.py#L49-L65
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
dim,
|
| 55 |
+
mlp_ratio=4,
|
| 56 |
+
bias=False,
|
| 57 |
+
dropout=0.0,
|
| 58 |
+
activation=nn.GELU,
|
| 59 |
+
mlp_dim=None,
|
| 60 |
+
):
|
| 61 |
+
"""
|
| 62 |
+
Args:
|
| 63 |
+
dim: Input dimension
|
| 64 |
+
mlp_ratio: Multiplier for hidden dimension
|
| 65 |
+
bias: Whether to use bias in linear layers
|
| 66 |
+
dropout: Dropout probability
|
| 67 |
+
activation: Activation function
|
| 68 |
+
mlp_dim: Optional explicit hidden dimension (overrides mlp_ratio)
|
| 69 |
+
"""
|
| 70 |
+
super().__init__()
|
| 71 |
+
hidden_dim = mlp_dim if mlp_dim is not None else int(dim * mlp_ratio)
|
| 72 |
+
|
| 73 |
+
self.mlp = nn.Sequential(
|
| 74 |
+
nn.Linear(dim, hidden_dim, bias=bias),
|
| 75 |
+
activation(),
|
| 76 |
+
nn.Linear(hidden_dim, dim, bias=bias),
|
| 77 |
+
nn.Dropout(dropout),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
def forward(self, x):
|
| 81 |
+
return self.mlp(x)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class QK_Norm_CrossAttention(nn.Module):
|
| 85 |
+
"""
|
| 86 |
+
Cross-attention module with optional Q-K normalization.
|
| 87 |
+
Takes separate query, key, and value inputs.
|
| 88 |
+
"""
|
| 89 |
+
def __init__(
|
| 90 |
+
self,
|
| 91 |
+
dim,
|
| 92 |
+
head_dim,
|
| 93 |
+
kv_dim=None,
|
| 94 |
+
qkv_bias=False,
|
| 95 |
+
fc_bias=True,
|
| 96 |
+
attn_dropout=0.0,
|
| 97 |
+
fc_dropout=0.0,
|
| 98 |
+
use_qk_norm=True,
|
| 99 |
+
):
|
| 100 |
+
super().__init__()
|
| 101 |
+
assert dim % head_dim == 0, f"Token dimension {dim} should be divisible by head dimension {head_dim}"
|
| 102 |
+
if kv_dim is None:
|
| 103 |
+
kv_dim = dim
|
| 104 |
+
|
| 105 |
+
self.dim = dim
|
| 106 |
+
self.kv_dim = kv_dim
|
| 107 |
+
self.head_dim = head_dim
|
| 108 |
+
self.num_heads = dim // head_dim
|
| 109 |
+
self.attn_dropout = attn_dropout
|
| 110 |
+
self.use_qk_norm = use_qk_norm
|
| 111 |
+
|
| 112 |
+
self.to_q = nn.Linear(dim, dim, bias=qkv_bias)
|
| 113 |
+
self.to_k = nn.Linear(kv_dim, dim, bias=qkv_bias)
|
| 114 |
+
self.to_v = nn.Linear(kv_dim, dim, bias=qkv_bias)
|
| 115 |
+
|
| 116 |
+
self.fc = nn.Linear(dim, dim, bias=fc_bias)
|
| 117 |
+
self.attn_fc_dropout = nn.Dropout(fc_dropout)
|
| 118 |
+
|
| 119 |
+
if self.use_qk_norm:
|
| 120 |
+
self.q_norm = RMSNorm(head_dim)
|
| 121 |
+
self.k_norm = RMSNorm(head_dim)
|
| 122 |
+
|
| 123 |
+
def forward(self, query, key, value, attn_bias=None):
|
| 124 |
+
q = self.to_q(query)
|
| 125 |
+
k = self.to_k(key)
|
| 126 |
+
v = self.to_v(value)
|
| 127 |
+
|
| 128 |
+
q, k, v = (rearrange(t, "b l (nh dh) -> b l nh dh", dh=self.head_dim) for t in (q, k, v))
|
| 129 |
+
|
| 130 |
+
if self.use_qk_norm:
|
| 131 |
+
q = self.q_norm(q)
|
| 132 |
+
k = self.k_norm(k)
|
| 133 |
+
|
| 134 |
+
x = xops.memory_efficient_attention(
|
| 135 |
+
q, k, v,
|
| 136 |
+
attn_bias=attn_bias,
|
| 137 |
+
p=self.attn_dropout if self.training else 0.0,
|
| 138 |
+
op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
x = rearrange(x, "b l nh dh -> b l (nh dh)")
|
| 142 |
+
x = self.attn_fc_dropout(self.fc(x))
|
| 143 |
+
|
| 144 |
+
return x
|
| 145 |
+
|
| 146 |
+
class QK_Norm_SelfAttention(nn.Module):
|
| 147 |
+
"""
|
| 148 |
+
Self-attention with optional Q-K normalization.
|
| 149 |
+
Reference: https://github.com/facebookresearch/dino/blob/7c446df5b9f45747937fb0d72314eb9f7b66930a/vision_transformer.py#L68-L92
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
dim,
|
| 155 |
+
head_dim,
|
| 156 |
+
qkv_bias=False,
|
| 157 |
+
fc_bias=True,
|
| 158 |
+
attn_dropout=0.0,
|
| 159 |
+
fc_dropout=0.0,
|
| 160 |
+
use_qk_norm=True,
|
| 161 |
+
):
|
| 162 |
+
"""
|
| 163 |
+
Args:
|
| 164 |
+
dim: Input dimension
|
| 165 |
+
head_dim: Dimension of each attention head
|
| 166 |
+
qkv_bias: Whether to use bias in QKV projection
|
| 167 |
+
fc_bias: Whether to use bias in output projection
|
| 168 |
+
attn_dropout: Dropout probability for attention weights
|
| 169 |
+
fc_dropout: Dropout probability for output projection
|
| 170 |
+
use_qk_norm: Whether to use Q-K normalization
|
| 171 |
+
We use flash attention V2 for efficiency.
|
| 172 |
+
"""
|
| 173 |
+
super().__init__()
|
| 174 |
+
assert dim % head_dim == 0, f"Token dimension {dim} should be divisible by head dimension {head_dim}"
|
| 175 |
+
|
| 176 |
+
self.dim = dim
|
| 177 |
+
self.head_dim = head_dim
|
| 178 |
+
self.num_heads = dim // head_dim
|
| 179 |
+
self.attn_dropout = attn_dropout
|
| 180 |
+
self.use_qk_norm = use_qk_norm
|
| 181 |
+
|
| 182 |
+
self.to_qkv = nn.Linear(dim, 3 * dim, bias=qkv_bias)
|
| 183 |
+
self.fc = nn.Linear(dim, dim, bias=fc_bias)
|
| 184 |
+
self.attn_fc_dropout = nn.Dropout(fc_dropout)
|
| 185 |
+
|
| 186 |
+
# Optional Q-K normalization
|
| 187 |
+
if self.use_qk_norm:
|
| 188 |
+
self.q_norm = RMSNorm(head_dim)
|
| 189 |
+
self.k_norm = RMSNorm(head_dim)
|
| 190 |
+
|
| 191 |
+
def forward(self, x, attn_bias=None):
|
| 192 |
+
"""
|
| 193 |
+
Args:
|
| 194 |
+
x: Input tensor of shape (batch, seq_len, dim)
|
| 195 |
+
attn_bias: Optional attention bias mask
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
Output tensor of shape (batch, seq_len, dim)
|
| 199 |
+
"""
|
| 200 |
+
q, k, v = self.to_qkv(x).chunk(3, dim=-1)
|
| 201 |
+
|
| 202 |
+
q, k, v = (rearrange(t, "b l (nh dh) -> b l nh dh", dh=self.head_dim) for t in (q, k, v))
|
| 203 |
+
|
| 204 |
+
# Apply qk normalization if enabled
|
| 205 |
+
if self.use_qk_norm:
|
| 206 |
+
q = self.q_norm(q)
|
| 207 |
+
k = self.k_norm(k)
|
| 208 |
+
|
| 209 |
+
x = xops.memory_efficient_attention(
|
| 210 |
+
q, k, v,
|
| 211 |
+
attn_bias=attn_bias,
|
| 212 |
+
p=self.attn_dropout if self.training else 0.0,
|
| 213 |
+
op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp),
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
x = rearrange(x, "b l nh dh -> b l (nh dh)")
|
| 217 |
+
x = self.attn_fc_dropout(self.fc(x))
|
| 218 |
+
|
| 219 |
+
return x
|
| 220 |
+
|
| 221 |
+
class SubsetAttention(nn.Module):
|
| 222 |
+
"""Attention that can attend to subsets of queries or keys/values."""
|
| 223 |
+
|
| 224 |
+
def __init__(
|
| 225 |
+
self,
|
| 226 |
+
dim,
|
| 227 |
+
head_dim,
|
| 228 |
+
qkv_bias=False,
|
| 229 |
+
attn_dropout=0.0,
|
| 230 |
+
fc_bias=False,
|
| 231 |
+
fc_dropout=0.0,
|
| 232 |
+
use_qk_norm=False
|
| 233 |
+
):
|
| 234 |
+
"""
|
| 235 |
+
Args:
|
| 236 |
+
dim: Input dimension
|
| 237 |
+
head_dim: Dimension of each attention head
|
| 238 |
+
qkv_bias: Whether to use bias in QKV projection
|
| 239 |
+
attn_dropout: Dropout probability for attention weights
|
| 240 |
+
fc_bias: Whether to use bias in output projection
|
| 241 |
+
fc_dropout: Dropout probability for output projection
|
| 242 |
+
use_qk_norm: Whether to use Q-K normalization
|
| 243 |
+
We use flash attention V2 for efficiency.
|
| 244 |
+
"""
|
| 245 |
+
super().__init__()
|
| 246 |
+
assert dim % head_dim == 0, f"Token dimension {dim} should be divisible by head dimension {head_dim}"
|
| 247 |
+
|
| 248 |
+
self.dim = dim
|
| 249 |
+
self.head_dim = head_dim
|
| 250 |
+
self.num_heads = dim // head_dim
|
| 251 |
+
self.attn_dropout = attn_dropout
|
| 252 |
+
self.use_qk_norm = use_qk_norm
|
| 253 |
+
|
| 254 |
+
# Projections
|
| 255 |
+
self.to_qkv = nn.Linear(dim, 3 * dim, bias=qkv_bias)
|
| 256 |
+
self.fc = nn.Linear(dim, dim, bias=fc_bias)
|
| 257 |
+
self.attn_fc_dropout = nn.Dropout(fc_dropout)
|
| 258 |
+
|
| 259 |
+
# Optional Q-K normalization
|
| 260 |
+
if self.use_qk_norm:
|
| 261 |
+
self.q_norm = RMSNorm(head_dim)
|
| 262 |
+
self.k_norm = RMSNorm(head_dim)
|
| 263 |
+
|
| 264 |
+
def forward(self, x, subset_kv_size=None, subset_q_size=None):
|
| 265 |
+
"""
|
| 266 |
+
Args:
|
| 267 |
+
x: Input tensor of shape (batch, seq_len, dim)
|
| 268 |
+
subset_kv_size: If provided, only attend to tokens after this index in KV
|
| 269 |
+
subset_q_size: If provided, only compute attention for queries up to this index
|
| 270 |
+
|
| 271 |
+
Returns:
|
| 272 |
+
Output tensor of shape (batch, seq_len, dim)
|
| 273 |
+
"""
|
| 274 |
+
# Only one subset parameter can be provided
|
| 275 |
+
assert not (subset_kv_size is not None and subset_q_size is not None), \
|
| 276 |
+
"Only one of subset_kv_size or subset_q_size can be provided"
|
| 277 |
+
|
| 278 |
+
q, k, v = self.to_qkv(x).chunk(3, dim=-1)
|
| 279 |
+
|
| 280 |
+
q, k, v = (rearrange(t, "b l (nh dh) -> b l nh dh", dh=self.head_dim) for t in (q, k, v))
|
| 281 |
+
|
| 282 |
+
if self.use_qk_norm:
|
| 283 |
+
q = self.q_norm(q)
|
| 284 |
+
k = self.k_norm(k)
|
| 285 |
+
|
| 286 |
+
# Handle subset attention cases
|
| 287 |
+
if subset_kv_size is not None and subset_kv_size < k.shape[1]:
|
| 288 |
+
# Attend to subset of key/value tokens
|
| 289 |
+
k_subset = k[:, subset_kv_size:, :, :].contiguous()
|
| 290 |
+
v_subset = v[:, subset_kv_size:, :, :].contiguous()
|
| 291 |
+
|
| 292 |
+
x = xops.memory_efficient_attention(
|
| 293 |
+
q, k_subset, v_subset,
|
| 294 |
+
attn_bias=None,
|
| 295 |
+
p=self.attn_dropout if self.training else 0.0,
|
| 296 |
+
op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp),
|
| 297 |
+
)
|
| 298 |
+
elif subset_q_size is not None and subset_q_size < q.shape[1]:
|
| 299 |
+
# Only compute attention for subset of query tokens
|
| 300 |
+
q_subset = q[:, :subset_q_size, :, :].contiguous()
|
| 301 |
+
|
| 302 |
+
x = xops.memory_efficient_attention(
|
| 303 |
+
q_subset, k, v,
|
| 304 |
+
attn_bias=None,
|
| 305 |
+
p=self.attn_dropout if self.training else 0.0,
|
| 306 |
+
op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp),
|
| 307 |
+
)
|
| 308 |
+
else:
|
| 309 |
+
# Regular attention for all tokens
|
| 310 |
+
x = xops.memory_efficient_attention(
|
| 311 |
+
q, k, v,
|
| 312 |
+
attn_bias=None,
|
| 313 |
+
p=self.attn_dropout if self.training else 0.0,
|
| 314 |
+
op=(xops.fmha.flash.FwOp, xops.fmha.flash.BwOp),
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
x = rearrange(x, "b l nh dh -> b l (nh dh)")
|
| 318 |
+
|
| 319 |
+
# Final projection
|
| 320 |
+
x = self.attn_fc_dropout(self.fc(x))
|
| 321 |
+
|
| 322 |
+
return x
|
| 323 |
+
|
| 324 |
+
class QK_Norm_CrossAttentionBlock(nn.Module):
|
| 325 |
+
"""
|
| 326 |
+
Transformer block using cross-attention.
|
| 327 |
+
Query is processed, then interacts with Key/Value.
|
| 328 |
+
"""
|
| 329 |
+
def __init__(
|
| 330 |
+
self,
|
| 331 |
+
dim,
|
| 332 |
+
head_dim,
|
| 333 |
+
kv_dim=None,
|
| 334 |
+
ln_bias=False,
|
| 335 |
+
attn_qkv_bias=False,
|
| 336 |
+
attn_dropout=0.0,
|
| 337 |
+
attn_fc_bias=False,
|
| 338 |
+
attn_fc_dropout=0.0,
|
| 339 |
+
mlp_ratio=4,
|
| 340 |
+
mlp_bias=False,
|
| 341 |
+
mlp_dropout=0.0,
|
| 342 |
+
use_qk_norm=True,
|
| 343 |
+
):
|
| 344 |
+
super().__init__()
|
| 345 |
+
self.norm_q = nn.LayerNorm(dim, bias=ln_bias)
|
| 346 |
+
self.norm_kv = nn.LayerNorm(kv_dim if kv_dim is not None else dim, bias=ln_bias)
|
| 347 |
+
self.attn = QK_Norm_CrossAttention(
|
| 348 |
+
dim=dim,
|
| 349 |
+
head_dim=head_dim,
|
| 350 |
+
kv_dim=kv_dim,
|
| 351 |
+
qkv_bias=attn_qkv_bias,
|
| 352 |
+
fc_bias=attn_fc_bias,
|
| 353 |
+
attn_dropout=attn_dropout,
|
| 354 |
+
fc_dropout=attn_fc_dropout,
|
| 355 |
+
use_qk_norm=use_qk_norm,
|
| 356 |
+
)
|
| 357 |
+
self.norm2 = nn.LayerNorm(dim, bias=ln_bias)
|
| 358 |
+
self.mlp = MLP(
|
| 359 |
+
dim=dim,
|
| 360 |
+
mlp_ratio=mlp_ratio,
|
| 361 |
+
bias=mlp_bias,
|
| 362 |
+
dropout=mlp_dropout,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
def forward(self, query, key, value):
|
| 366 |
+
# Pre-normalization
|
| 367 |
+
q_norm = self.norm_q(query)
|
| 368 |
+
k_norm = self.norm_kv(key)
|
| 369 |
+
v_norm = self.norm_kv(value)
|
| 370 |
+
|
| 371 |
+
# Cross-attention
|
| 372 |
+
attn_out = self.attn(q_norm, k_norm, v_norm)
|
| 373 |
+
|
| 374 |
+
# Residual connection and MLP
|
| 375 |
+
x = query + attn_out
|
| 376 |
+
x = x + self.mlp(self.norm2(x))
|
| 377 |
+
return x
|
| 378 |
+
|
| 379 |
+
class QK_Norm_TransformerBlock(nn.Module):
|
| 380 |
+
"""
|
| 381 |
+
Standard transformer block with pre-normalization architecture.
|
| 382 |
+
Reference: https://github.com/facebookresearch/dino/blob/7c446df5b9f45747937fb0d72314eb9f7b66930a/vision_transformer.py#L95-L113
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
def __init__(
|
| 386 |
+
self,
|
| 387 |
+
dim,
|
| 388 |
+
head_dim,
|
| 389 |
+
ln_bias=False,
|
| 390 |
+
attn_qkv_bias=False,
|
| 391 |
+
attn_dropout=0.0,
|
| 392 |
+
attn_fc_bias=False,
|
| 393 |
+
attn_fc_dropout=0.0,
|
| 394 |
+
mlp_ratio=4,
|
| 395 |
+
mlp_bias=False,
|
| 396 |
+
mlp_dropout=0.0,
|
| 397 |
+
use_qk_norm=True,
|
| 398 |
+
):
|
| 399 |
+
super().__init__()
|
| 400 |
+
self.norm1 = nn.LayerNorm(dim, bias=ln_bias)
|
| 401 |
+
self.attn = QK_Norm_SelfAttention(
|
| 402 |
+
dim=dim,
|
| 403 |
+
head_dim=head_dim,
|
| 404 |
+
qkv_bias=attn_qkv_bias,
|
| 405 |
+
fc_bias=attn_fc_bias,
|
| 406 |
+
attn_dropout=attn_dropout,
|
| 407 |
+
fc_dropout=attn_fc_dropout,
|
| 408 |
+
use_qk_norm=use_qk_norm,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
self.norm2 = nn.LayerNorm(dim, bias=ln_bias)
|
| 412 |
+
self.mlp = MLP(
|
| 413 |
+
dim=dim,
|
| 414 |
+
mlp_ratio=mlp_ratio,
|
| 415 |
+
bias=mlp_bias,
|
| 416 |
+
dropout=mlp_dropout,
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def forward(self, x):
|
| 421 |
+
x = x + self.attn(self.norm1(x))
|
| 422 |
+
x = x + self.mlp(self.norm2(x))
|
| 423 |
+
return x
|
OVOW/third_party/Motion324/pyrightconfig.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"exclude": [
|
| 3 |
+
"experiments/**",
|
| 4 |
+
"log/**",
|
| 5 |
+
"metric_checkpoint/**",
|
| 6 |
+
"preprocessed_data/**" ],
|
| 7 |
+
"typeCheckingMode": "off"
|
| 8 |
+
// "reportMissingImports": false,
|
| 9 |
+
// "reportUnknownMemberType": false,
|
| 10 |
+
// "reportAttributeAccessIssue": false,
|
| 11 |
+
// "reportUnknownVariableType": false
|
| 12 |
+
}
|
OVOW/third_party/Motion324/requirements.txt
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --extra-index-url https://download.pytorch.org/whl/cu124
|
| 2 |
+
torch==2.4.1
|
| 3 |
+
torchvision==0.19.1+cu124
|
| 4 |
+
xformers==0.0.28
|
| 5 |
+
imageio==2.33.0
|
| 6 |
+
Pillow==10.0.1
|
| 7 |
+
imageio-ffmpeg==0.5.0
|
| 8 |
+
omegaconf==2.1.1
|
| 9 |
+
einops>= 0.4.1
|
| 10 |
+
transformers==4.56.1
|
| 11 |
+
peft==0.17.0
|
| 12 |
+
torchmetrics>= 0.11.0
|
| 13 |
+
datasets==2.14.5
|
| 14 |
+
rich>=13.3.2
|
| 15 |
+
wandb==0.21.1
|
| 16 |
+
ipdb
|
| 17 |
+
tqdm
|
| 18 |
+
easydict==1.13
|
| 19 |
+
lpips==0.1.4
|
| 20 |
+
dreamsim==0.2.1
|
| 21 |
+
open-clip-torch==3.1.0
|
| 22 |
+
jaxtyping==0.3.1
|
| 23 |
+
scikit-image==0.23.2
|
| 24 |
+
rembg==2.0.68
|
| 25 |
+
onnxruntime
|
| 26 |
+
trimesh==4.6.9
|
| 27 |
+
bpy==4.4.0
|
| 28 |
+
natsort
|
| 29 |
+
scikit-learn
|
| 30 |
+
numpy==1.26.4
|
| 31 |
+
matplotlib
|
| 32 |
+
pybind11==2.13.6
|
| 33 |
+
diffusers==0.35.2
|
| 34 |
+
xatlas==0.0.11
|
| 35 |
+
pymeshlab
|
| 36 |
+
pygltflib
|
OVOW/third_party/Motion324/scripts/4D_from_existing.sh
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Script to generate 4D animation from existing mesh and video
|
| 4 |
+
# Usage: ./scripts/4D_from_existing.sh <data_dir> <video_path> <output_dir>
|
| 5 |
+
# Example: ./scripts/4D_from_existing.sh ./examples/mesh.glb ./examples/video.mp4 ./examples/output
|
| 6 |
+
set -e
|
| 7 |
+
|
| 8 |
+
# Check arguments
|
| 9 |
+
if [ $# -lt 3 ]; then
|
| 10 |
+
echo "Usage: $0 <data_dir> <video_path> <output_dir>"
|
| 11 |
+
echo " data_dir: Path to .glb or .fbx mesh file (FBX will be automatically converted to GLB)"
|
| 12 |
+
echo " video_path: Path to video file (.mp4/.avi/.mov) or directory containing images"
|
| 13 |
+
echo " output_dir: Output directory for animation results"
|
| 14 |
+
echo ""
|
| 15 |
+
echo "Example: $0 ./examples/chili.glb ./examples/chili.mp4 ./examples/output"
|
| 16 |
+
exit 1
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
DATA_DIR="$1"
|
| 20 |
+
VIDEO_PATH="$2"
|
| 21 |
+
OUTPUT_DIR="$3"
|
| 22 |
+
|
| 23 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 24 |
+
PROJECT_ROOT="${SCRIPT_DIR}/.."
|
| 25 |
+
|
| 26 |
+
# Validate data_dir
|
| 27 |
+
if [ ! -f "$DATA_DIR" ]; then
|
| 28 |
+
echo "Error: Mesh file not found: $DATA_DIR"
|
| 29 |
+
echo "Supported formats: .glb, .fbx"
|
| 30 |
+
exit 1
|
| 31 |
+
fi
|
| 32 |
+
|
| 33 |
+
# Validate video_path
|
| 34 |
+
if [ ! -f "$VIDEO_PATH" ] && [ ! -d "$VIDEO_PATH" ]; then
|
| 35 |
+
echo "Error: Video file or directory not found: $VIDEO_PATH"
|
| 36 |
+
echo "Supported: .mp4/.avi/.mov video files or directory containing images"
|
| 37 |
+
exit 1
|
| 38 |
+
fi
|
| 39 |
+
|
| 40 |
+
# Create output directory
|
| 41 |
+
mkdir -p "$OUTPUT_DIR"
|
| 42 |
+
|
| 43 |
+
echo "=========================================="
|
| 44 |
+
echo "Generating 4D animation from existing mesh and video"
|
| 45 |
+
echo "Mesh file: $DATA_DIR"
|
| 46 |
+
echo "Video path: $VIDEO_PATH"
|
| 47 |
+
echo "Output directory: $OUTPUT_DIR"
|
| 48 |
+
echo "=========================================="
|
| 49 |
+
|
| 50 |
+
# Change to project root directory
|
| 51 |
+
cd "$PROJECT_ROOT"
|
| 52 |
+
|
| 53 |
+
# Run inference
|
| 54 |
+
python scripts/inference_with_video_mesh.py \
|
| 55 |
+
--config=configs/dyscene.yaml \
|
| 56 |
+
training.resume_ckpt="$PROJECT_ROOT/experiments/checkpoints/ckpt_0000000000060000.pt" \
|
| 57 |
+
model.class_name=model.Pcd_motion.Motion_Latent_Model \
|
| 58 |
+
training.num_shape_samples=16384 \
|
| 59 |
+
training.frames=256 \
|
| 60 |
+
start_frame=0 \
|
| 61 |
+
use_segmentation=True \
|
| 62 |
+
data_dir="$DATA_DIR" \
|
| 63 |
+
video_path="$VIDEO_PATH" \
|
| 64 |
+
output_dir="$OUTPUT_DIR"
|
| 65 |
+
|
| 66 |
+
echo ""
|
| 67 |
+
echo "=========================================="
|
| 68 |
+
echo "Processing complete!"
|
| 69 |
+
echo "Animation output: $OUTPUT_DIR"
|
| 70 |
+
echo "=========================================="
|
| 71 |
+
|
OVOW/third_party/Motion324/scripts/4D_from_video.sh
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
# Script to convert video input to 4D animation
|
| 4 |
+
# Usage: ./scripts/4D_from_video.sh <input_video_path> [--split_only] [--backend hunyuan|trellis2]
|
| 5 |
+
# ./scripts/4D_from_video.sh ./examples/tiger.mp4
|
| 6 |
+
# ./scripts/4D_from_video.sh ./examples/tiger.mp4 --split_only
|
| 7 |
+
# ./scripts/4D_from_video.sh ./examples/tiger.mp4 --backend trellis2
|
| 8 |
+
set -e
|
| 9 |
+
|
| 10 |
+
# Check arguments
|
| 11 |
+
if [ $# -lt 1 ]; then
|
| 12 |
+
echo "Usage: $0 <input_video_path> [--split_only] [--backend hunyuan|trellis2]"
|
| 13 |
+
echo "Example: $0 ./examples/tiger.mp4"
|
| 14 |
+
echo " $0 ./examples/tiger.mp4 --split_only"
|
| 15 |
+
echo " $0 ./examples/tiger.mp4 --backend trellis2"
|
| 16 |
+
exit 1
|
| 17 |
+
fi
|
| 18 |
+
|
| 19 |
+
INPUT_VIDEO="$1"
|
| 20 |
+
shift
|
| 21 |
+
|
| 22 |
+
# Defaults
|
| 23 |
+
SPLIT_ONLY="false"
|
| 24 |
+
BACKEND="hunyuan"
|
| 25 |
+
|
| 26 |
+
while [ $# -gt 0 ]; do
|
| 27 |
+
case "$1" in
|
| 28 |
+
--split_only)
|
| 29 |
+
SPLIT_ONLY="true"
|
| 30 |
+
shift
|
| 31 |
+
;;
|
| 32 |
+
--backend)
|
| 33 |
+
if [ -z "$2" ]; then
|
| 34 |
+
echo "Error: --backend requires a value (hunyuan|trellis2)"
|
| 35 |
+
exit 1
|
| 36 |
+
fi
|
| 37 |
+
BACKEND="$2"
|
| 38 |
+
shift 2
|
| 39 |
+
;;
|
| 40 |
+
--trellis2)
|
| 41 |
+
BACKEND="trellis2"
|
| 42 |
+
shift
|
| 43 |
+
;;
|
| 44 |
+
*)
|
| 45 |
+
echo "Error: Unknown option '$1'"
|
| 46 |
+
exit 1
|
| 47 |
+
;;
|
| 48 |
+
esac
|
| 49 |
+
done
|
| 50 |
+
|
| 51 |
+
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
| 52 |
+
PROJECT_ROOT="${SCRIPT_DIR}/.."
|
| 53 |
+
OUTPUT_BASE_DIR="$(dirname "$INPUT_VIDEO")"
|
| 54 |
+
|
| 55 |
+
# Keep Hunyuan weights under /data to avoid repeated downloads into /mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/.cache.
|
| 56 |
+
CKPT_ROOT="${MOTION324_CKPT_ROOT:-/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/ckpts}"
|
| 57 |
+
export HY3DGEN_MODELS="${HY3DGEN_MODELS:-${CKPT_ROOT}/hy3dgen}"
|
| 58 |
+
mkdir -p "$HY3DGEN_MODELS"
|
| 59 |
+
|
| 60 |
+
# Validate input video
|
| 61 |
+
if [ ! -f "$INPUT_VIDEO" ]; then
|
| 62 |
+
echo "Error: Input video not found: $INPUT_VIDEO"
|
| 63 |
+
exit 1
|
| 64 |
+
fi
|
| 65 |
+
|
| 66 |
+
# Set up paths
|
| 67 |
+
VIDEO_NAME=$(basename "$INPUT_VIDEO" | sed 's/\.[^.]*$//')
|
| 68 |
+
PROCESSED_DIR="$OUTPUT_BASE_DIR/${VIDEO_NAME}_processed"
|
| 69 |
+
MASKED_RGB_DIR="$PROCESSED_DIR/masked_rgb"
|
| 70 |
+
ANIMATION_OUTPUT_DIR="$PROCESSED_DIR/animation"
|
| 71 |
+
|
| 72 |
+
echo "=========================================="
|
| 73 |
+
echo "Processing video: $INPUT_VIDEO"
|
| 74 |
+
echo "Base directory: $OUTPUT_BASE_DIR"
|
| 75 |
+
echo "Processed directory: $PROCESSED_DIR"
|
| 76 |
+
echo "Split only: $SPLIT_ONLY"
|
| 77 |
+
echo "Backend: $BACKEND"
|
| 78 |
+
echo "HY3DGEN_MODELS: $HY3DGEN_MODELS"
|
| 79 |
+
echo "=========================================="
|
| 80 |
+
|
| 81 |
+
# Step 1: Remove background and extract frames or only split frames
|
| 82 |
+
echo ""
|
| 83 |
+
if [ "$SPLIT_ONLY" = "true" ]; then
|
| 84 |
+
echo "Step 1: Extracting frames only (split_only mode)..."
|
| 85 |
+
python "$PROJECT_ROOT/utils/rmbg_for_black_bg.py" --input "$INPUT_VIDEO" --split_only
|
| 86 |
+
echo "Split only mode done. Exiting pipeline after video frame extraction."
|
| 87 |
+
else
|
| 88 |
+
echo "Step 1: Removing background and extracting frames..."
|
| 89 |
+
python "$PROJECT_ROOT/utils/rmbg_for_black_bg.py" --input "$INPUT_VIDEO"
|
| 90 |
+
fi
|
| 91 |
+
|
| 92 |
+
HUNYUAN_INPUT_DIR="$OUTPUT_BASE_DIR/${VIDEO_NAME}_processed/Hunyuan_Gen_Input"
|
| 93 |
+
# Step 2: Generate Hunyuan mesh
|
| 94 |
+
echo ""
|
| 95 |
+
echo "Step 2: Generating mesh ($BACKEND)..."
|
| 96 |
+
FBX_HUNYUAN_O="$(find "$HUNYUAN_INPUT_DIR" -name "*_hunyuan_original_wo_remap_converted.fbx" | head -1)"
|
| 97 |
+
if [ -f "$FBX_HUNYUAN_O" ]; then
|
| 98 |
+
echo "Hunyuan mesh already exists at $FBX_HUNYUAN_O, skipping generation."
|
| 99 |
+
else
|
| 100 |
+
if [ "$BACKEND" = "trellis2" ]; then
|
| 101 |
+
export HF_ENDPOINT=https://huggingface.co
|
| 102 |
+
else
|
| 103 |
+
export HF_ENDPOINT=https://hf-mirror.com
|
| 104 |
+
fi
|
| 105 |
+
python "$PROJECT_ROOT/scripts/hunyuan_Gen.py" \
|
| 106 |
+
--root "$OUTPUT_BASE_DIR" \
|
| 107 |
+
--output "$OUTPUT_BASE_DIR" \
|
| 108 |
+
--N 1 \
|
| 109 |
+
--n 0 \
|
| 110 |
+
--skip 256 \
|
| 111 |
+
--seed 42 \
|
| 112 |
+
--backend "$BACKEND"
|
| 113 |
+
fi
|
| 114 |
+
|
| 115 |
+
if [ "$BACKEND" != "trellis2" ]; then
|
| 116 |
+
python "$PROJECT_ROOT/utils/convert_fbx.py" "$HUNYUAN_INPUT_DIR"
|
| 117 |
+
fi
|
| 118 |
+
# Step 3: Find the generated FBX file
|
| 119 |
+
FBX_FILE=$(find "$HUNYUAN_INPUT_DIR" -name "*_hunyuan_original_wo_remap_converted.fbx" | head -1)
|
| 120 |
+
if [ -z "$FBX_FILE" ]; then
|
| 121 |
+
echo "Error: FBX file not found in $HUNYUAN_INPUT_DIR"
|
| 122 |
+
exit 1
|
| 123 |
+
fi
|
| 124 |
+
|
| 125 |
+
# Step 4: Generate animation
|
| 126 |
+
echo ""
|
| 127 |
+
echo "Step 3: Generating animation..."
|
| 128 |
+
python "$PROJECT_ROOT/scripts/inference_with_video_only.py" \
|
| 129 |
+
--config="$PROJECT_ROOT/configs/dyscene.yaml" \
|
| 130 |
+
training.resume_ckpt="$PROJECT_ROOT/experiments/checkpoints/ckpt_0000000000060000.pt" \
|
| 131 |
+
model.class_name=model.Pcd_motion.Motion_Latent_Model \
|
| 132 |
+
data_dir="$FBX_FILE" \
|
| 133 |
+
image_path="$MASKED_RGB_DIR" \
|
| 134 |
+
training.num_shape_samples=16384 \
|
| 135 |
+
training.num_pcd_samples=4096 \
|
| 136 |
+
training.frames=256 \
|
| 137 |
+
start_frame=0 \
|
| 138 |
+
training.use_fbx=True \
|
| 139 |
+
output_dir="$ANIMATION_OUTPUT_DIR"
|
| 140 |
+
|
| 141 |
+
echo ""
|
| 142 |
+
echo "=========================================="
|
| 143 |
+
echo "Processing complete!"
|
| 144 |
+
echo "Animation output: $ANIMATION_OUTPUT_DIR"
|
| 145 |
+
echo "=========================================="
|
OVOW/third_party/Motion324/scripts/hunyuan_Gen.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Modified from V2M4
|
| 2 |
+
import os
|
| 3 |
+
# os.environ['ATTN_BACKEND'] = 'xformers' # Can be 'flash-attn' or 'xformers', default is 'flash-attn'
|
| 4 |
+
os.environ['SPCONV_ALGO'] = 'native' # Can be 'native' or 'auto', default is 'auto'.
|
| 5 |
+
# 'auto' is faster but will do benchmarking at the beginning.
|
| 6 |
+
# Recommended to set to 'native' if run only once.
|
| 7 |
+
import imageio
|
| 8 |
+
import torch
|
| 9 |
+
import random
|
| 10 |
+
import numpy as np
|
| 11 |
+
import rembg
|
| 12 |
+
from PIL import Image
|
| 13 |
+
from natsort import ns, natsorted
|
| 14 |
+
import argparse
|
| 15 |
+
import trimesh
|
| 16 |
+
import shutil
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
# Work around transformers torch.load safety gate (CVE-2025-32434) for local trusted checkpoints.
|
| 21 |
+
if os.environ.get("MOTION324_DISABLE_TORCH_LOAD_CHECK", "1") == "1":
|
| 22 |
+
try:
|
| 23 |
+
import transformers.modeling_utils as _tf_mu
|
| 24 |
+
_tf_mu.check_torch_load_is_safe = lambda: None
|
| 25 |
+
except Exception:
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
def preprocess_image(input: Image.Image, return_rgba=False, return_all_rbga=False) -> Image.Image:
|
| 29 |
+
"""
|
| 30 |
+
Preprocess the input image.
|
| 31 |
+
"""
|
| 32 |
+
# If the input has an alpha channel, use it directly; otherwise, remove background
|
| 33 |
+
has_alpha = False
|
| 34 |
+
if input.mode == 'RGBA':
|
| 35 |
+
alpha = np.array(input)[:, :, 3]
|
| 36 |
+
if not np.all(alpha == 255):
|
| 37 |
+
has_alpha = True
|
| 38 |
+
if has_alpha:
|
| 39 |
+
output = input
|
| 40 |
+
else:
|
| 41 |
+
input = input.convert('RGB')
|
| 42 |
+
max_size = max(input.size)
|
| 43 |
+
scale = min(1, 1024 / max_size)
|
| 44 |
+
if scale < 1:
|
| 45 |
+
input = input.resize((int(input.width * scale), int(input.height * scale)), Image.Resampling.LANCZOS)
|
| 46 |
+
# Use birefnet-massive instead of u2net for better performance
|
| 47 |
+
rembg_session = rembg.new_session('birefnet-massive')
|
| 48 |
+
output = rembg.remove(input, session=rembg_session)
|
| 49 |
+
output_np = np.array(output)
|
| 50 |
+
alpha = output_np[:, :, 3]
|
| 51 |
+
bbox = np.argwhere(alpha > 0.8 * 255)
|
| 52 |
+
bbox = np.min(bbox[:, 1]), np.min(bbox[:, 0]), np.max(bbox[:, 1]), np.max(bbox[:, 0])
|
| 53 |
+
center = (bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2
|
| 54 |
+
size = max(bbox[2] - bbox[0], bbox[3] - bbox[1])
|
| 55 |
+
size = int(size * 1.2)
|
| 56 |
+
bbox = center[0] - size // 2, center[1] - size // 2, center[0] + size // 2, center[1] + size // 2
|
| 57 |
+
|
| 58 |
+
# Uncropped image
|
| 59 |
+
before_crop = output.resize((518, 518), Image.Resampling.LANCZOS)
|
| 60 |
+
before_crop = np.array(before_crop).astype(np.float32) / 255
|
| 61 |
+
|
| 62 |
+
# If the crop region is out of the image, it will be automatically padded with black.
|
| 63 |
+
output = output.crop(bbox) # type: ignore
|
| 64 |
+
output = output.resize((518, 518), Image.Resampling.LANCZOS)
|
| 65 |
+
output = np.array(output).astype(np.float32) / 255
|
| 66 |
+
|
| 67 |
+
if return_all_rbga:
|
| 68 |
+
before_crop_rgba = Image.fromarray((before_crop * 255).astype(np.uint8), mode='RGBA')
|
| 69 |
+
|
| 70 |
+
before_crop = before_crop[:, :, :3] * before_crop[:, :, 3:4]
|
| 71 |
+
before_crop = Image.fromarray((before_crop * 255).astype(np.uint8))
|
| 72 |
+
|
| 73 |
+
output = Image.fromarray((output * 255).astype(np.uint8), mode='RGBA')
|
| 74 |
+
return output, before_crop_rgba, before_crop
|
| 75 |
+
|
| 76 |
+
before_crop = before_crop[:, :, :3] * before_crop[:, :, 3:4]
|
| 77 |
+
before_crop = Image.fromarray((before_crop * 255).astype(np.uint8))
|
| 78 |
+
|
| 79 |
+
if return_rgba:
|
| 80 |
+
output = Image.fromarray((output * 255).astype(np.uint8), mode='RGBA')
|
| 81 |
+
return output, before_crop
|
| 82 |
+
|
| 83 |
+
output = output[:, :, :3] * output[:, :, 3:4]
|
| 84 |
+
output = Image.fromarray((output * 255).astype(np.uint8))
|
| 85 |
+
return output, before_crop
|
| 86 |
+
|
| 87 |
+
def seed_torch(seed=0):
|
| 88 |
+
print("Seed Fixed!")
|
| 89 |
+
random.seed(seed)
|
| 90 |
+
os.environ['PYTHONHASHSEED'] = str(seed)
|
| 91 |
+
np.random.seed(seed)
|
| 92 |
+
torch.manual_seed(seed)
|
| 93 |
+
torch.cuda.manual_seed(seed)
|
| 94 |
+
torch.cuda.manual_seed_all(seed)
|
| 95 |
+
torch.backends.cudnn.benchmark = False
|
| 96 |
+
torch.backends.cudnn.deterministic = True
|
| 97 |
+
|
| 98 |
+
def parse_args():
|
| 99 |
+
parser = argparse.ArgumentParser(description='HunyuanGen Pipeline')
|
| 100 |
+
parser.add_argument('--root', type=str, default='', help='Root directory of the dataset')
|
| 101 |
+
parser.add_argument('--output', type=str, default='', help='Output directory of the results')
|
| 102 |
+
parser.add_argument('--N', type=int, default=1, help='Total number of parallel processes')
|
| 103 |
+
parser.add_argument('--n', type=int, default=0, help='Index of the current process')
|
| 104 |
+
parser.add_argument('--model', type=str, default='Hunyuan', help='Base model', choices=['Hunyuan'])
|
| 105 |
+
parser.add_argument('--seed', type=int, default=42, help='Random seed for reproducibility')
|
| 106 |
+
parser.add_argument('--skip', type=int, default=256, help='Skip every N frames for large movement of the object (default: 5)')
|
| 107 |
+
parser.add_argument('--max_faces', type=int, default=10000, help='Maximum number of faces for the generated mesh (default: 10000)')
|
| 108 |
+
parser.add_argument('--backend', type=str, default='hunyuan', choices=['hunyuan', 'trellis2'], help='Mesh generation backend')
|
| 109 |
+
parser.add_argument('--trellis2_env', type=str, default=os.environ.get('TRELLIS2_ENV', 'opg'), help='Conda env for Trellis2')
|
| 110 |
+
parser.add_argument('--trellis2_ckpt', type=str, default=os.environ.get('TRELLIS2_CKPT', '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/engine/checkpoints/TRELLIS.2-4B'), help='Trellis2 checkpoint path')
|
| 111 |
+
parser.add_argument('--trellis2_pipeline_type', type=str, default=os.environ.get('TRELLIS2_PIPELINE_TYPE', '1024'), help='Trellis2 pipeline type')
|
| 112 |
+
parser.add_argument('--trellis2_max_num_tokens', type=int, default=int(os.environ.get('TRELLIS2_MAX_NUM_TOKENS', '49152')), help='Trellis2 max tokens')
|
| 113 |
+
parser.add_argument('--trellis2_texture_size', type=int, default=int(os.environ.get('TRELLIS2_TEXTURE_SIZE', '1024')), help='Trellis2 texture size')
|
| 114 |
+
parser.add_argument('--blender_bin', type=str, default=os.environ.get('BLENDER_BIN', '/mnt/einsia/aws01-nvme/einsia-shared/homes/gaomingju/jiayin/OVOW/blender-5.0.0-linux-x64/blender'), help='Blender binary for FBX export')
|
| 115 |
+
return parser.parse_args()
|
| 116 |
+
|
| 117 |
+
def get_folder_size(folder):
|
| 118 |
+
return len([f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))])
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _init_hunyuan_pipelines():
|
| 122 |
+
from hy3dgen.texgen import Hunyuan3DPaintPipeline
|
| 123 |
+
from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline
|
| 124 |
+
from hy3dgen.shapegen import FaceReducer, FloaterRemover, DegenerateFaceRemover
|
| 125 |
+
|
| 126 |
+
pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained('tencent/Hunyuan3D-2')
|
| 127 |
+
pipeline_paint = Hunyuan3DPaintPipeline.from_pretrained('tencent/Hunyuan3D-2')
|
| 128 |
+
|
| 129 |
+
pipeline.model.requires_grad = False
|
| 130 |
+
pipeline.vae.requires_grad = False
|
| 131 |
+
pipeline.conditioner.requires_grad = False
|
| 132 |
+
pipeline_paint.models['delight_model'].pipeline.feature_extractor.requires_grad = False
|
| 133 |
+
pipeline_paint.models['delight_model'].pipeline.text_encoder.requires_grad = False
|
| 134 |
+
pipeline_paint.models['delight_model'].pipeline.unet.requires_grad = False
|
| 135 |
+
pipeline_paint.models['delight_model'].pipeline.vae.requires_grad = False
|
| 136 |
+
pipeline_paint.models['multiview_model'].pipeline.unet.requires_grad = False
|
| 137 |
+
pipeline_paint.models['multiview_model'].pipeline.vae.requires_grad = False
|
| 138 |
+
pipeline_paint.models['multiview_model'].pipeline.text_encoder.requires_grad = False
|
| 139 |
+
pipeline_paint.models['multiview_model'].pipeline.feature_extractor.requires_grad = False
|
| 140 |
+
|
| 141 |
+
return pipeline, pipeline_paint, (FaceReducer, FloaterRemover, DegenerateFaceRemover)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _resolve_conda_exe():
|
| 145 |
+
conda_exe = os.environ.get("CONDA_EXE")
|
| 146 |
+
if conda_exe and os.path.exists(conda_exe):
|
| 147 |
+
return conda_exe
|
| 148 |
+
for candidate in ["conda", "/root/miniconda3/bin/conda", "conda"]:
|
| 149 |
+
if os.path.isabs(candidate):
|
| 150 |
+
if os.path.exists(candidate):
|
| 151 |
+
return candidate
|
| 152 |
+
else:
|
| 153 |
+
return candidate
|
| 154 |
+
return "conda"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _run_trellis2(
|
| 158 |
+
trellis2_script,
|
| 159 |
+
image_path,
|
| 160 |
+
output_glb,
|
| 161 |
+
ckpt_path,
|
| 162 |
+
env_name,
|
| 163 |
+
pipeline_type,
|
| 164 |
+
max_num_tokens,
|
| 165 |
+
simplify_target,
|
| 166 |
+
texture_size,
|
| 167 |
+
seed,
|
| 168 |
+
log_path=None,
|
| 169 |
+
):
|
| 170 |
+
conda_exe = _resolve_conda_exe()
|
| 171 |
+
cmd = [
|
| 172 |
+
conda_exe,
|
| 173 |
+
"run",
|
| 174 |
+
"-n",
|
| 175 |
+
env_name,
|
| 176 |
+
"python",
|
| 177 |
+
"-u",
|
| 178 |
+
trellis2_script,
|
| 179 |
+
"--input",
|
| 180 |
+
image_path,
|
| 181 |
+
"--output_glb",
|
| 182 |
+
output_glb,
|
| 183 |
+
"--ckpt",
|
| 184 |
+
ckpt_path,
|
| 185 |
+
"--seed",
|
| 186 |
+
str(seed),
|
| 187 |
+
"--pipeline_type",
|
| 188 |
+
str(pipeline_type),
|
| 189 |
+
"--max_num_tokens",
|
| 190 |
+
str(max_num_tokens),
|
| 191 |
+
"--simplify_target",
|
| 192 |
+
str(simplify_target),
|
| 193 |
+
"--texture_size",
|
| 194 |
+
str(texture_size),
|
| 195 |
+
"--disable_rembg",
|
| 196 |
+
]
|
| 197 |
+
print("Running Trellis2:", " ".join(cmd))
|
| 198 |
+
env = os.environ.copy()
|
| 199 |
+
env["PYTHONUNBUFFERED"] = "1"
|
| 200 |
+
# Prefer spconv backend to avoid flex_gemm/triton incompatibilities.
|
| 201 |
+
env.setdefault("SPARSE_CONV_BACKEND", "spconv")
|
| 202 |
+
env.setdefault("SPCONV_ALGO", "native")
|
| 203 |
+
if log_path:
|
| 204 |
+
os.makedirs(os.path.dirname(log_path) or ".", exist_ok=True)
|
| 205 |
+
with open(log_path, "a", encoding="utf-8") as log_f:
|
| 206 |
+
log_f.write("CMD: " + " ".join(cmd) + "\n")
|
| 207 |
+
log_f.flush()
|
| 208 |
+
proc = subprocess.Popen(
|
| 209 |
+
cmd,
|
| 210 |
+
stdout=subprocess.PIPE,
|
| 211 |
+
stderr=subprocess.STDOUT,
|
| 212 |
+
text=True,
|
| 213 |
+
bufsize=1,
|
| 214 |
+
env=env,
|
| 215 |
+
)
|
| 216 |
+
assert proc.stdout is not None
|
| 217 |
+
for line in proc.stdout:
|
| 218 |
+
sys.stdout.write(line)
|
| 219 |
+
sys.stdout.flush()
|
| 220 |
+
log_f.write(line)
|
| 221 |
+
log_f.flush()
|
| 222 |
+
ret = proc.wait()
|
| 223 |
+
if ret != 0:
|
| 224 |
+
raise subprocess.CalledProcessError(ret, cmd)
|
| 225 |
+
else:
|
| 226 |
+
subprocess.run(cmd, check=True, env=env)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def _convert_glb_to_fbx(convert_script, glb_path, fbx_path, blender_bin):
|
| 230 |
+
cmd = [
|
| 231 |
+
sys.executable,
|
| 232 |
+
convert_script,
|
| 233 |
+
"--input",
|
| 234 |
+
glb_path,
|
| 235 |
+
"--output",
|
| 236 |
+
fbx_path,
|
| 237 |
+
"--blender_bin",
|
| 238 |
+
blender_bin,
|
| 239 |
+
]
|
| 240 |
+
print("Converting GLB to FBX:", " ".join(cmd))
|
| 241 |
+
subprocess.run(cmd, check=True)
|
| 242 |
+
|
| 243 |
+
if __name__ == "__main__":
|
| 244 |
+
args = parse_args()
|
| 245 |
+
backend = args.backend.lower()
|
| 246 |
+
root = "/path/to/obj_motion/Eval/1/viz" if args.root == "" else args.root
|
| 247 |
+
default_output_root = "results_examples"
|
| 248 |
+
print(f"Root viz dir: {root}")
|
| 249 |
+
|
| 250 |
+
output_root = args.output if args.output != "" else default_output_root
|
| 251 |
+
|
| 252 |
+
processed_dirs = []
|
| 253 |
+
for name in os.listdir(root):
|
| 254 |
+
sub_path = os.path.join(root, name)
|
| 255 |
+
if not os.path.isdir(sub_path):
|
| 256 |
+
continue
|
| 257 |
+
processed_path = os.path.join(sub_path, "masked_rgb")
|
| 258 |
+
animation_path = os.path.join(sub_path, "animation")
|
| 259 |
+
if os.path.isdir(processed_path) and not os.path.isdir(animation_path):
|
| 260 |
+
processed_dirs.append(processed_path)
|
| 261 |
+
print("Found processed masked_rgb folders:")
|
| 262 |
+
print(processed_dirs)
|
| 263 |
+
animations = natsorted(processed_dirs, alg=ns.PATH)
|
| 264 |
+
|
| 265 |
+
folder_sizes = [(anim, get_folder_size(anim)) for anim in animations]
|
| 266 |
+
folder_sizes.sort(key=lambda x: x[1], reverse=True)
|
| 267 |
+
|
| 268 |
+
assignments = [[] for _ in range(args.N)]
|
| 269 |
+
workload = [0] * args.N
|
| 270 |
+
|
| 271 |
+
for folder, size in folder_sizes:
|
| 272 |
+
min_index = workload.index(min(workload))
|
| 273 |
+
assignments[min_index].append(folder)
|
| 274 |
+
workload[min_index] += size
|
| 275 |
+
|
| 276 |
+
assigned_animations = assignments[args.n]
|
| 277 |
+
|
| 278 |
+
total_imgs = sum(get_folder_size(f) for f in assigned_animations)
|
| 279 |
+
print(f"Process {args.n} assigned {len(assigned_animations)} folders with total images: {total_imgs}")
|
| 280 |
+
|
| 281 |
+
if backend == "hunyuan":
|
| 282 |
+
pipeline, pipeline_paint, cleaners = _init_hunyuan_pipelines()
|
| 283 |
+
|
| 284 |
+
for animation in assigned_animations:
|
| 285 |
+
source_path = animation
|
| 286 |
+
output_path = source_path if args.output == "" else os.path.join(args.output, source_path.split("/")[-2], 'Hunyuan_Gen_Input')
|
| 287 |
+
|
| 288 |
+
print("/n/n ============= Start processing: ", animation, " =============/n")
|
| 289 |
+
os.makedirs(output_path, exist_ok=True)
|
| 290 |
+
|
| 291 |
+
seed = args.seed
|
| 292 |
+
seed_torch(seed)
|
| 293 |
+
|
| 294 |
+
imgs_list = os.listdir(source_path)
|
| 295 |
+
imgs_list = [img for img in imgs_list if not os.path.isdir(source_path + "/" + img)]
|
| 296 |
+
imgs_list = natsorted(imgs_list, alg=ns.PATH)
|
| 297 |
+
|
| 298 |
+
outputs_list = []
|
| 299 |
+
base_name_list = []
|
| 300 |
+
extrinsics_list = []
|
| 301 |
+
visual_list = []
|
| 302 |
+
params = None
|
| 303 |
+
|
| 304 |
+
for ind, img in enumerate(imgs_list):
|
| 305 |
+
if ind % args.skip != 0:
|
| 306 |
+
continue
|
| 307 |
+
|
| 308 |
+
image = Image.open(source_path + "/" + img)
|
| 309 |
+
base_name = image.filename.split("/")[-1].split(".")[0]
|
| 310 |
+
|
| 311 |
+
save_path = output_path + "/" + base_name + "_rmbg.png"
|
| 312 |
+
cropped_image, rmbg_image = preprocess_image(image, return_rgba=True)
|
| 313 |
+
rmbg_image.save(save_path)
|
| 314 |
+
cropped_image.save(save_path.replace(".png", "_cropped.png"))
|
| 315 |
+
if backend == "trellis2":
|
| 316 |
+
trellis2_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "trellis2_gen.py")
|
| 317 |
+
trellis2_input = save_path.replace(".png", "_cropped.png")
|
| 318 |
+
glb_path = output_path + "/" + base_name + "_hunyuan_original_wo_remap.glb"
|
| 319 |
+
fbx_path = output_path + "/" + base_name + "_hunyuan_original_wo_remap_converted.fbx"
|
| 320 |
+
if os.path.exists(fbx_path):
|
| 321 |
+
print(f"FBX already exists, skipping: {fbx_path}")
|
| 322 |
+
continue
|
| 323 |
+
_run_trellis2(
|
| 324 |
+
trellis2_script,
|
| 325 |
+
trellis2_input,
|
| 326 |
+
glb_path,
|
| 327 |
+
args.trellis2_ckpt,
|
| 328 |
+
args.trellis2_env,
|
| 329 |
+
args.trellis2_pipeline_type,
|
| 330 |
+
args.trellis2_max_num_tokens,
|
| 331 |
+
args.max_faces,
|
| 332 |
+
args.trellis2_texture_size,
|
| 333 |
+
args.seed,
|
| 334 |
+
log_path=os.path.join(output_path, f"{base_name}_trellis2.log"),
|
| 335 |
+
)
|
| 336 |
+
watertight_path = output_path + "/" + base_name + "_hunyuan_original_watertight.glb"
|
| 337 |
+
if not os.path.exists(watertight_path):
|
| 338 |
+
shutil.copy(glb_path, watertight_path)
|
| 339 |
+
convert_script = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "utils", "convert_glb_to_fbx.py")
|
| 340 |
+
_convert_glb_to_fbx(convert_script, glb_path, fbx_path, args.blender_bin)
|
| 341 |
+
print(f"Trellis2 GLB exported: {glb_path}")
|
| 342 |
+
print(f"Trellis2 FBX exported: {fbx_path}")
|
| 343 |
+
continue
|
| 344 |
+
import time
|
| 345 |
+
start_time = time.time()
|
| 346 |
+
|
| 347 |
+
torch.manual_seed(seed)
|
| 348 |
+
mesh = pipeline(image=cropped_image)[0]
|
| 349 |
+
|
| 350 |
+
for cleaner in [cleaners[1](), cleaners[2]()]:
|
| 351 |
+
mesh = cleaner(mesh)
|
| 352 |
+
|
| 353 |
+
mesh = cleaners[0]()(mesh, max_facenum=args.max_faces)
|
| 354 |
+
|
| 355 |
+
vertices_watertight = mesh.vertices @ np.array([[1, 0, 0], [0, 0, 1], [0, -1, 0]])
|
| 356 |
+
faces_watertight = mesh.faces
|
| 357 |
+
mean_point = mesh.vertices.mean(axis=0)
|
| 358 |
+
vertices_watertight = (vertices_watertight - mean_point) * 0.5 + mean_point
|
| 359 |
+
mesh_watertight = trimesh.Trimesh(vertices_watertight, faces_watertight, process=False)
|
| 360 |
+
mesh_watertight.export(output_path + "/" + base_name + "_hunyuan_original_watertight.glb")
|
| 361 |
+
print("mesh_watertight exported:", output_path + "/" + base_name + "_hunyuan_original_watertight.glb")
|
| 362 |
+
|
| 363 |
+
mesh, vmapping = pipeline_paint(mesh, image=cropped_image)
|
| 364 |
+
# Save vmapping for later use
|
| 365 |
+
vmapping_path = output_path + "/" + base_name + "_vmapping.npy"
|
| 366 |
+
np.save(vmapping_path, vmapping)
|
| 367 |
+
print(f"vmapping saved to: {vmapping_path}")
|
| 368 |
+
|
| 369 |
+
end_time = time.time()
|
| 370 |
+
generation_time = end_time - start_time
|
| 371 |
+
print(f"Hunyuan generation time: {generation_time:.4f} seconds")
|
| 372 |
+
# Save the original Hunyuan mesh before further processing
|
| 373 |
+
mesh_original = mesh.copy()
|
| 374 |
+
mesh_original.export(output_path + "/" + base_name + "_hunyuan_original_wo_remap.glb")
|
| 375 |
+
print("mesh_original exported:", output_path + "/" + base_name + "_hunyuan_original_wo_remap.glb")
|
OVOW/third_party/Motion324/scripts/hy3dgen/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
OVOW/third_party/Motion324/scripts/hy3dgen/rembg.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
from PIL import Image
|
| 16 |
+
from rembg import remove, new_session
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class BackgroundRemover():
|
| 20 |
+
def __init__(self):
|
| 21 |
+
self.session = new_session()
|
| 22 |
+
|
| 23 |
+
def __call__(self, image: Image.Image):
|
| 24 |
+
output = remove(image, session=self.session, bgcolor=[255, 255, 255, 0])
|
| 25 |
+
return output
|
OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
from .pipelines import Hunyuan3DDiTPipeline, Hunyuan3DDiTFlowMatchingPipeline
|
| 16 |
+
from .postprocessors import FaceReducer, FloaterRemover, DegenerateFaceRemover, MeshSimplifier
|
| 17 |
+
from .preprocessors import ImageProcessorV2, IMAGE_PROCESSORS, DEFAULT_IMAGEPROCESSOR
|
OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/pipelines.py
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
import copy
|
| 16 |
+
import importlib
|
| 17 |
+
import inspect
|
| 18 |
+
import os
|
| 19 |
+
from typing import List, Optional, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
import trimesh
|
| 24 |
+
import yaml
|
| 25 |
+
from PIL import Image
|
| 26 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 27 |
+
from diffusers.utils.import_utils import is_accelerate_version, is_accelerate_available
|
| 28 |
+
from tqdm import tqdm
|
| 29 |
+
|
| 30 |
+
from .models.autoencoders import ShapeVAE
|
| 31 |
+
from .models.autoencoders import SurfaceExtractors
|
| 32 |
+
from .utils import logger, synchronize_timer, smart_load_model
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def retrieve_timesteps(
|
| 36 |
+
scheduler,
|
| 37 |
+
num_inference_steps: Optional[int] = None,
|
| 38 |
+
device: Optional[Union[str, torch.device]] = None,
|
| 39 |
+
timesteps: Optional[List[int]] = None,
|
| 40 |
+
sigmas: Optional[List[float]] = None,
|
| 41 |
+
**kwargs,
|
| 42 |
+
):
|
| 43 |
+
"""
|
| 44 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
| 45 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
scheduler (`SchedulerMixin`):
|
| 49 |
+
The scheduler to get timesteps from.
|
| 50 |
+
num_inference_steps (`int`):
|
| 51 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
| 52 |
+
must be `None`.
|
| 53 |
+
device (`str` or `torch.device`, *optional*):
|
| 54 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 55 |
+
timesteps (`List[int]`, *optional*):
|
| 56 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
| 57 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
| 58 |
+
sigmas (`List[float]`, *optional*):
|
| 59 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
| 60 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
| 64 |
+
second element is the number of inference steps.
|
| 65 |
+
"""
|
| 66 |
+
if timesteps is not None and sigmas is not None:
|
| 67 |
+
raise ValueError("Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values")
|
| 68 |
+
if timesteps is not None:
|
| 69 |
+
accepts_timesteps = "timesteps" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
| 70 |
+
if not accepts_timesteps:
|
| 71 |
+
raise ValueError(
|
| 72 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 73 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
| 74 |
+
)
|
| 75 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
| 76 |
+
timesteps = scheduler.timesteps
|
| 77 |
+
num_inference_steps = len(timesteps)
|
| 78 |
+
elif sigmas is not None:
|
| 79 |
+
accept_sigmas = "sigmas" in set(inspect.signature(scheduler.set_timesteps).parameters.keys())
|
| 80 |
+
if not accept_sigmas:
|
| 81 |
+
raise ValueError(
|
| 82 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
| 83 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
| 84 |
+
)
|
| 85 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
| 86 |
+
timesteps = scheduler.timesteps
|
| 87 |
+
num_inference_steps = len(timesteps)
|
| 88 |
+
else:
|
| 89 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
| 90 |
+
timesteps = scheduler.timesteps
|
| 91 |
+
return timesteps, num_inference_steps
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@synchronize_timer('Export to trimesh')
|
| 95 |
+
def export_to_trimesh(mesh_output):
|
| 96 |
+
if isinstance(mesh_output, list):
|
| 97 |
+
outputs = []
|
| 98 |
+
for mesh in mesh_output:
|
| 99 |
+
if mesh is None:
|
| 100 |
+
outputs.append(None)
|
| 101 |
+
else:
|
| 102 |
+
mesh.mesh_f = mesh.mesh_f[:, ::-1]
|
| 103 |
+
mesh_output = trimesh.Trimesh(mesh.mesh_v, mesh.mesh_f)
|
| 104 |
+
outputs.append(mesh_output)
|
| 105 |
+
return outputs
|
| 106 |
+
else:
|
| 107 |
+
mesh_output.mesh_f = mesh_output.mesh_f[:, ::-1]
|
| 108 |
+
mesh_output = trimesh.Trimesh(mesh_output.mesh_v, mesh_output.mesh_f)
|
| 109 |
+
return mesh_output
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_obj_from_str(string, reload=False):
|
| 113 |
+
module, cls = string.rsplit(".", 1)
|
| 114 |
+
if reload:
|
| 115 |
+
module_imp = importlib.import_module(module)
|
| 116 |
+
importlib.reload(module_imp)
|
| 117 |
+
return getattr(importlib.import_module(module, package=None), cls)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def instantiate_from_config(config, **kwargs):
|
| 121 |
+
if "target" not in config:
|
| 122 |
+
raise KeyError("Expected key `target` to instantiate.")
|
| 123 |
+
cls = get_obj_from_str(config["target"])
|
| 124 |
+
params = config.get("params", dict())
|
| 125 |
+
kwargs.update(params)
|
| 126 |
+
instance = cls(**kwargs)
|
| 127 |
+
return instance
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class Hunyuan3DDiTPipeline:
|
| 131 |
+
model_cpu_offload_seq = "conditioner->model->vae"
|
| 132 |
+
_exclude_from_cpu_offload = []
|
| 133 |
+
|
| 134 |
+
@classmethod
|
| 135 |
+
@synchronize_timer('Hunyuan3DDiTPipeline Model Loading')
|
| 136 |
+
def from_single_file(
|
| 137 |
+
cls,
|
| 138 |
+
ckpt_path,
|
| 139 |
+
config_path,
|
| 140 |
+
device='cuda',
|
| 141 |
+
dtype=torch.float16,
|
| 142 |
+
use_safetensors=None,
|
| 143 |
+
**kwargs,
|
| 144 |
+
):
|
| 145 |
+
# load config
|
| 146 |
+
with open(config_path, 'r') as f:
|
| 147 |
+
config = yaml.safe_load(f)
|
| 148 |
+
|
| 149 |
+
# load ckpt
|
| 150 |
+
if use_safetensors:
|
| 151 |
+
ckpt_path = ckpt_path.replace('.ckpt', '.safetensors')
|
| 152 |
+
if not os.path.exists(ckpt_path):
|
| 153 |
+
raise FileNotFoundError(f"Model file {ckpt_path} not found")
|
| 154 |
+
logger.info(f"Loading model from {ckpt_path}")
|
| 155 |
+
|
| 156 |
+
if use_safetensors:
|
| 157 |
+
# parse safetensors
|
| 158 |
+
import safetensors.torch
|
| 159 |
+
safetensors_ckpt = safetensors.torch.load_file(ckpt_path, device='cpu')
|
| 160 |
+
ckpt = {}
|
| 161 |
+
for key, value in safetensors_ckpt.items():
|
| 162 |
+
model_name = key.split('.')[0]
|
| 163 |
+
new_key = key[len(model_name) + 1:]
|
| 164 |
+
if model_name not in ckpt:
|
| 165 |
+
ckpt[model_name] = {}
|
| 166 |
+
ckpt[model_name][new_key] = value
|
| 167 |
+
else:
|
| 168 |
+
ckpt = torch.load(ckpt_path, map_location='cpu', weights_only=True)
|
| 169 |
+
# load model
|
| 170 |
+
model = instantiate_from_config(config['model'])
|
| 171 |
+
model.load_state_dict(ckpt['model'])
|
| 172 |
+
vae = instantiate_from_config(config['vae'])
|
| 173 |
+
vae.load_state_dict(ckpt['vae'], strict=False)
|
| 174 |
+
conditioner = instantiate_from_config(config['conditioner'])
|
| 175 |
+
if 'conditioner' in ckpt:
|
| 176 |
+
conditioner.load_state_dict(ckpt['conditioner'])
|
| 177 |
+
image_processor = instantiate_from_config(config['image_processor'])
|
| 178 |
+
scheduler = instantiate_from_config(config['scheduler'])
|
| 179 |
+
|
| 180 |
+
model_kwargs = dict(
|
| 181 |
+
vae=vae,
|
| 182 |
+
model=model,
|
| 183 |
+
scheduler=scheduler,
|
| 184 |
+
conditioner=conditioner,
|
| 185 |
+
image_processor=image_processor,
|
| 186 |
+
device=device,
|
| 187 |
+
dtype=dtype,
|
| 188 |
+
)
|
| 189 |
+
model_kwargs.update(kwargs)
|
| 190 |
+
|
| 191 |
+
return cls(
|
| 192 |
+
**model_kwargs
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
@classmethod
|
| 196 |
+
def from_pretrained(
|
| 197 |
+
cls,
|
| 198 |
+
model_path,
|
| 199 |
+
device='cuda',
|
| 200 |
+
dtype=torch.float16,
|
| 201 |
+
use_safetensors=True,
|
| 202 |
+
variant='fp16',
|
| 203 |
+
subfolder='hunyuan3d-dit-v2-0',
|
| 204 |
+
**kwargs,
|
| 205 |
+
):
|
| 206 |
+
kwargs['from_pretrained_kwargs'] = dict(
|
| 207 |
+
model_path=model_path,
|
| 208 |
+
subfolder=subfolder,
|
| 209 |
+
use_safetensors=use_safetensors,
|
| 210 |
+
variant=variant,
|
| 211 |
+
dtype=dtype,
|
| 212 |
+
device=device,
|
| 213 |
+
)
|
| 214 |
+
config_path, ckpt_path = smart_load_model(
|
| 215 |
+
model_path,
|
| 216 |
+
subfolder=subfolder,
|
| 217 |
+
use_safetensors=use_safetensors,
|
| 218 |
+
variant=variant
|
| 219 |
+
)
|
| 220 |
+
return cls.from_single_file(
|
| 221 |
+
ckpt_path,
|
| 222 |
+
config_path,
|
| 223 |
+
device=device,
|
| 224 |
+
dtype=dtype,
|
| 225 |
+
use_safetensors=use_safetensors,
|
| 226 |
+
**kwargs
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
def __init__(
|
| 230 |
+
self,
|
| 231 |
+
vae,
|
| 232 |
+
model,
|
| 233 |
+
scheduler,
|
| 234 |
+
conditioner,
|
| 235 |
+
image_processor,
|
| 236 |
+
device='cuda',
|
| 237 |
+
dtype=torch.float16,
|
| 238 |
+
**kwargs
|
| 239 |
+
):
|
| 240 |
+
self.vae = vae
|
| 241 |
+
self.model = model
|
| 242 |
+
self.scheduler = scheduler
|
| 243 |
+
self.conditioner = conditioner
|
| 244 |
+
self.image_processor = image_processor
|
| 245 |
+
self.kwargs = kwargs
|
| 246 |
+
self.to(device, dtype)
|
| 247 |
+
|
| 248 |
+
def compile(self):
|
| 249 |
+
self.vae = torch.compile(self.vae)
|
| 250 |
+
self.model = torch.compile(self.model)
|
| 251 |
+
self.conditioner = torch.compile(self.conditioner)
|
| 252 |
+
|
| 253 |
+
def enable_flashvdm(
|
| 254 |
+
self,
|
| 255 |
+
enabled: bool = True,
|
| 256 |
+
adaptive_kv_selection=True,
|
| 257 |
+
topk_mode='mean',
|
| 258 |
+
mc_algo='mc',
|
| 259 |
+
replace_vae=True,
|
| 260 |
+
):
|
| 261 |
+
if enabled:
|
| 262 |
+
model_path = self.kwargs['from_pretrained_kwargs']['model_path']
|
| 263 |
+
turbo_vae_mapping = {
|
| 264 |
+
'Hunyuan3D-2': ('tencent/Hunyuan3D-2', 'hunyuan3d-vae-v2-0-turbo'),
|
| 265 |
+
'Hunyuan3D-2mv': ('tencent/Hunyuan3D-2', 'hunyuan3d-vae-v2-0-turbo'),
|
| 266 |
+
'Hunyuan3D-2mini': ('tencent/Hunyuan3D-2mini', 'hunyuan3d-vae-v2-mini-turbo'),
|
| 267 |
+
}
|
| 268 |
+
model_name = model_path.split('/')[-1]
|
| 269 |
+
if replace_vae and model_name in turbo_vae_mapping:
|
| 270 |
+
model_path, subfolder = turbo_vae_mapping[model_name]
|
| 271 |
+
self.vae = ShapeVAE.from_pretrained(
|
| 272 |
+
model_path, subfolder=subfolder,
|
| 273 |
+
use_safetensors=self.kwargs['from_pretrained_kwargs']['use_safetensors'],
|
| 274 |
+
device=self.device,
|
| 275 |
+
)
|
| 276 |
+
self.vae.enable_flashvdm_decoder(
|
| 277 |
+
enabled=enabled,
|
| 278 |
+
adaptive_kv_selection=adaptive_kv_selection,
|
| 279 |
+
topk_mode=topk_mode,
|
| 280 |
+
mc_algo=mc_algo
|
| 281 |
+
)
|
| 282 |
+
else:
|
| 283 |
+
model_path = self.kwargs['from_pretrained_kwargs']['model_path']
|
| 284 |
+
vae_mapping = {
|
| 285 |
+
'Hunyuan3D-2': ('tencent/Hunyuan3D-2', 'hunyuan3d-vae-v2-0'),
|
| 286 |
+
'Hunyuan3D-2mv': ('tencent/Hunyuan3D-2', 'hunyuan3d-vae-v2-0'),
|
| 287 |
+
'Hunyuan3D-2mini': ('tencent/Hunyuan3D-2mini', 'hunyuan3d-vae-v2-mini'),
|
| 288 |
+
}
|
| 289 |
+
model_name = model_path.split('/')[-1]
|
| 290 |
+
if model_name in vae_mapping:
|
| 291 |
+
model_path, subfolder = vae_mapping[model_name]
|
| 292 |
+
self.vae = ShapeVAE.from_pretrained(model_path, subfolder=subfolder)
|
| 293 |
+
self.vae.enable_flashvdm_decoder(enabled=False)
|
| 294 |
+
|
| 295 |
+
def to(self, device=None, dtype=None):
|
| 296 |
+
if dtype is not None:
|
| 297 |
+
self.dtype = dtype
|
| 298 |
+
self.vae.to(dtype=dtype)
|
| 299 |
+
self.model.to(dtype=dtype)
|
| 300 |
+
self.conditioner.to(dtype=dtype)
|
| 301 |
+
if device is not None:
|
| 302 |
+
self.device = torch.device(device)
|
| 303 |
+
self.vae.to(device)
|
| 304 |
+
self.model.to(device)
|
| 305 |
+
self.conditioner.to(device)
|
| 306 |
+
|
| 307 |
+
@property
|
| 308 |
+
def _execution_device(self):
|
| 309 |
+
r"""
|
| 310 |
+
Returns the device on which the pipeline's models will be executed. After calling
|
| 311 |
+
[`~DiffusionPipeline.enable_sequential_cpu_offload`] the execution device can only be inferred from
|
| 312 |
+
Accelerate's module hooks.
|
| 313 |
+
"""
|
| 314 |
+
for name, model in self.components.items():
|
| 315 |
+
if not isinstance(model, torch.nn.Module) or name in self._exclude_from_cpu_offload:
|
| 316 |
+
continue
|
| 317 |
+
|
| 318 |
+
if not hasattr(model, "_hf_hook"):
|
| 319 |
+
return self.device
|
| 320 |
+
for module in model.modules():
|
| 321 |
+
if (
|
| 322 |
+
hasattr(module, "_hf_hook")
|
| 323 |
+
and hasattr(module._hf_hook, "execution_device")
|
| 324 |
+
and module._hf_hook.execution_device is not None
|
| 325 |
+
):
|
| 326 |
+
return torch.device(module._hf_hook.execution_device)
|
| 327 |
+
return self.device
|
| 328 |
+
|
| 329 |
+
def enable_model_cpu_offload(self, gpu_id: Optional[int] = None, device: Union[torch.device, str] = "cuda"):
|
| 330 |
+
r"""
|
| 331 |
+
Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
|
| 332 |
+
to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward`
|
| 333 |
+
method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
|
| 334 |
+
`enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`.
|
| 335 |
+
|
| 336 |
+
Arguments:
|
| 337 |
+
gpu_id (`int`, *optional*):
|
| 338 |
+
The ID of the accelerator that shall be used in inference. If not specified, it will default to 0.
|
| 339 |
+
device (`torch.Device` or `str`, *optional*, defaults to "cuda"):
|
| 340 |
+
The PyTorch device type of the accelerator that shall be used in inference. If not specified, it will
|
| 341 |
+
default to "cuda".
|
| 342 |
+
"""
|
| 343 |
+
if self.model_cpu_offload_seq is None:
|
| 344 |
+
raise ValueError(
|
| 345 |
+
"Model CPU offload cannot be enabled because no `model_cpu_offload_seq` class attribute is set."
|
| 346 |
+
)
|
| 347 |
+
|
| 348 |
+
if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"):
|
| 349 |
+
from accelerate import cpu_offload_with_hook
|
| 350 |
+
else:
|
| 351 |
+
raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.")
|
| 352 |
+
|
| 353 |
+
torch_device = torch.device(device)
|
| 354 |
+
device_index = torch_device.index
|
| 355 |
+
|
| 356 |
+
if gpu_id is not None and device_index is not None:
|
| 357 |
+
raise ValueError(
|
| 358 |
+
f"You have passed both `gpu_id`={gpu_id} and an index as part of the passed device `device`={device}"
|
| 359 |
+
f"Cannot pass both. Please make sure to either not define `gpu_id` or not pass the index as part of the device: `device`={torch_device.type}"
|
| 360 |
+
)
|
| 361 |
+
|
| 362 |
+
# _offload_gpu_id should be set to passed gpu_id (or id in passed `device`) or default to previously set id or default to 0
|
| 363 |
+
self._offload_gpu_id = gpu_id or torch_device.index or getattr(self, "_offload_gpu_id", 0)
|
| 364 |
+
|
| 365 |
+
device_type = torch_device.type
|
| 366 |
+
device = torch.device(f"{device_type}:{self._offload_gpu_id}")
|
| 367 |
+
|
| 368 |
+
if self.device.type != "cpu":
|
| 369 |
+
self.to("cpu")
|
| 370 |
+
device_mod = getattr(torch, self.device.type, None)
|
| 371 |
+
if hasattr(device_mod, "empty_cache") and device_mod.is_available():
|
| 372 |
+
device_mod.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
|
| 373 |
+
|
| 374 |
+
all_model_components = {k: v for k, v in self.components.items() if isinstance(v, torch.nn.Module)}
|
| 375 |
+
|
| 376 |
+
self._all_hooks = []
|
| 377 |
+
hook = None
|
| 378 |
+
for model_str in self.model_cpu_offload_seq.split("->"):
|
| 379 |
+
model = all_model_components.pop(model_str, None)
|
| 380 |
+
if not isinstance(model, torch.nn.Module):
|
| 381 |
+
continue
|
| 382 |
+
|
| 383 |
+
_, hook = cpu_offload_with_hook(model, device, prev_module_hook=hook)
|
| 384 |
+
self._all_hooks.append(hook)
|
| 385 |
+
|
| 386 |
+
# CPU offload models that are not in the seq chain unless they are explicitly excluded
|
| 387 |
+
# these models will stay on CPU until maybe_free_model_hooks is called
|
| 388 |
+
# some models cannot be in the seq chain because they are iteratively called, such as controlnet
|
| 389 |
+
for name, model in all_model_components.items():
|
| 390 |
+
if not isinstance(model, torch.nn.Module):
|
| 391 |
+
continue
|
| 392 |
+
|
| 393 |
+
if name in self._exclude_from_cpu_offload:
|
| 394 |
+
model.to(device)
|
| 395 |
+
else:
|
| 396 |
+
_, hook = cpu_offload_with_hook(model, device)
|
| 397 |
+
self._all_hooks.append(hook)
|
| 398 |
+
|
| 399 |
+
def maybe_free_model_hooks(self):
|
| 400 |
+
r"""
|
| 401 |
+
Function that offloads all components, removes all model hooks that were added when using
|
| 402 |
+
`enable_model_cpu_offload` and then applies them again. In case the model has not been offloaded this function
|
| 403 |
+
is a no-op. Make sure to add this function to the end of the `__call__` function of your pipeline so that it
|
| 404 |
+
functions correctly when applying enable_model_cpu_offload.
|
| 405 |
+
"""
|
| 406 |
+
if not hasattr(self, "_all_hooks") or len(self._all_hooks) == 0:
|
| 407 |
+
# `enable_model_cpu_offload` has not be called, so silently do nothing
|
| 408 |
+
return
|
| 409 |
+
|
| 410 |
+
for hook in self._all_hooks:
|
| 411 |
+
# offload model and remove hook from model
|
| 412 |
+
hook.offload()
|
| 413 |
+
hook.remove()
|
| 414 |
+
|
| 415 |
+
# make sure the model is in the same state as before calling it
|
| 416 |
+
self.enable_model_cpu_offload()
|
| 417 |
+
|
| 418 |
+
@synchronize_timer('Encode cond')
|
| 419 |
+
def encode_cond(self, image, additional_cond_inputs, do_classifier_free_guidance, dual_guidance):
|
| 420 |
+
bsz = image.shape[0]
|
| 421 |
+
cond = self.conditioner(image=image, **additional_cond_inputs)
|
| 422 |
+
|
| 423 |
+
if do_classifier_free_guidance:
|
| 424 |
+
un_cond = self.conditioner.unconditional_embedding(bsz, **additional_cond_inputs)
|
| 425 |
+
|
| 426 |
+
if dual_guidance:
|
| 427 |
+
un_cond_drop_main = copy.deepcopy(un_cond)
|
| 428 |
+
un_cond_drop_main['additional'] = cond['additional']
|
| 429 |
+
|
| 430 |
+
def cat_recursive(a, b, c):
|
| 431 |
+
if isinstance(a, torch.Tensor):
|
| 432 |
+
return torch.cat([a, b, c], dim=0).to(self.dtype)
|
| 433 |
+
out = {}
|
| 434 |
+
for k in a.keys():
|
| 435 |
+
out[k] = cat_recursive(a[k], b[k], c[k])
|
| 436 |
+
return out
|
| 437 |
+
|
| 438 |
+
cond = cat_recursive(cond, un_cond_drop_main, un_cond)
|
| 439 |
+
else:
|
| 440 |
+
def cat_recursive(a, b):
|
| 441 |
+
if isinstance(a, torch.Tensor):
|
| 442 |
+
return torch.cat([a, b], dim=0).to(self.dtype)
|
| 443 |
+
out = {}
|
| 444 |
+
for k in a.keys():
|
| 445 |
+
out[k] = cat_recursive(a[k], b[k])
|
| 446 |
+
return out
|
| 447 |
+
|
| 448 |
+
cond = cat_recursive(cond, un_cond)
|
| 449 |
+
return cond
|
| 450 |
+
|
| 451 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 452 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 453 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 454 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 455 |
+
# and should be between [0, 1]
|
| 456 |
+
|
| 457 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 458 |
+
extra_step_kwargs = {}
|
| 459 |
+
if accepts_eta:
|
| 460 |
+
extra_step_kwargs["eta"] = eta
|
| 461 |
+
|
| 462 |
+
# check if the scheduler accepts generator
|
| 463 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 464 |
+
if accepts_generator:
|
| 465 |
+
extra_step_kwargs["generator"] = generator
|
| 466 |
+
return extra_step_kwargs
|
| 467 |
+
|
| 468 |
+
def prepare_latents(self, batch_size, dtype, device, generator, latents=None):
|
| 469 |
+
shape = (batch_size, *self.vae.latent_shape)
|
| 470 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 471 |
+
raise ValueError(
|
| 472 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 473 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
if latents is None:
|
| 477 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 478 |
+
else:
|
| 479 |
+
latents = latents.to(device)
|
| 480 |
+
|
| 481 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 482 |
+
latents = latents * getattr(self.scheduler, 'init_noise_sigma', 1.0)
|
| 483 |
+
return latents
|
| 484 |
+
|
| 485 |
+
def prepare_image(self, image) -> dict:
|
| 486 |
+
if isinstance(image, str) and not os.path.exists(image):
|
| 487 |
+
raise FileNotFoundError(f"Couldn't find image at path {image}")
|
| 488 |
+
|
| 489 |
+
if not isinstance(image, list):
|
| 490 |
+
image = [image]
|
| 491 |
+
|
| 492 |
+
outputs = []
|
| 493 |
+
for img in image:
|
| 494 |
+
output = self.image_processor(img)
|
| 495 |
+
outputs.append(output)
|
| 496 |
+
|
| 497 |
+
cond_input = {k: [] for k in outputs[0].keys()}
|
| 498 |
+
for output in outputs:
|
| 499 |
+
for key, value in output.items():
|
| 500 |
+
cond_input[key].append(value)
|
| 501 |
+
for key, value in cond_input.items():
|
| 502 |
+
if isinstance(value[0], torch.Tensor):
|
| 503 |
+
cond_input[key] = torch.cat(value, dim=0)
|
| 504 |
+
|
| 505 |
+
return cond_input
|
| 506 |
+
|
| 507 |
+
def get_guidance_scale_embedding(self, w, embedding_dim=512, dtype=torch.float32):
|
| 508 |
+
"""
|
| 509 |
+
See https://github.com/google-research/vdm/blob/dc27b98a554f65cdc654b800da5aa1846545d41b/model_vdm.py#L298
|
| 510 |
+
|
| 511 |
+
Args:
|
| 512 |
+
timesteps (`torch.Tensor`):
|
| 513 |
+
generate embedding vectors at these timesteps
|
| 514 |
+
embedding_dim (`int`, *optional*, defaults to 512):
|
| 515 |
+
dimension of the embeddings to generate
|
| 516 |
+
dtype:
|
| 517 |
+
data type of the generated embeddings
|
| 518 |
+
|
| 519 |
+
Returns:
|
| 520 |
+
`torch.FloatTensor`: Embedding vectors with shape `(len(timesteps), embedding_dim)`
|
| 521 |
+
"""
|
| 522 |
+
assert len(w.shape) == 1
|
| 523 |
+
w = w * 1000.0
|
| 524 |
+
|
| 525 |
+
half_dim = embedding_dim // 2
|
| 526 |
+
emb = torch.log(torch.tensor(10000.0)) / (half_dim - 1)
|
| 527 |
+
emb = torch.exp(torch.arange(half_dim, dtype=dtype) * -emb)
|
| 528 |
+
emb = w.to(dtype)[:, None] * emb[None, :]
|
| 529 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 530 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 531 |
+
emb = torch.nn.functional.pad(emb, (0, 1))
|
| 532 |
+
assert emb.shape == (w.shape[0], embedding_dim)
|
| 533 |
+
return emb
|
| 534 |
+
|
| 535 |
+
def set_surface_extractor(self, mc_algo):
|
| 536 |
+
if mc_algo is None:
|
| 537 |
+
return
|
| 538 |
+
logger.info('The parameters `mc_algo` is deprecated, and will be removed in future versions.\n'
|
| 539 |
+
'Please use: \n'
|
| 540 |
+
'from hy3dgen.shapegen.models.autoencoders import SurfaceExtractors\n'
|
| 541 |
+
'pipeline.vae.surface_extractor = SurfaceExtractors[mc_algo]() instead\n')
|
| 542 |
+
if mc_algo not in SurfaceExtractors.keys():
|
| 543 |
+
raise ValueError(f"Unknown mc_algo {mc_algo}")
|
| 544 |
+
self.vae.surface_extractor = SurfaceExtractors[mc_algo]()
|
| 545 |
+
|
| 546 |
+
@torch.no_grad()
|
| 547 |
+
def __call__(
|
| 548 |
+
self,
|
| 549 |
+
image: Union[str, List[str], Image.Image] = None,
|
| 550 |
+
num_inference_steps: int = 50,
|
| 551 |
+
timesteps: List[int] = None,
|
| 552 |
+
sigmas: List[float] = None,
|
| 553 |
+
eta: float = 0.0,
|
| 554 |
+
guidance_scale: float = 7.5,
|
| 555 |
+
dual_guidance_scale: float = 10.5,
|
| 556 |
+
dual_guidance: bool = True,
|
| 557 |
+
generator=None,
|
| 558 |
+
box_v=1.01,
|
| 559 |
+
octree_resolution=384,
|
| 560 |
+
mc_level=-1 / 512,
|
| 561 |
+
num_chunks=8000,
|
| 562 |
+
mc_algo=None,
|
| 563 |
+
output_type: Optional[str] = "trimesh",
|
| 564 |
+
enable_pbar=True,
|
| 565 |
+
**kwargs,
|
| 566 |
+
) -> List[List[trimesh.Trimesh]]:
|
| 567 |
+
callback = kwargs.pop("callback", None)
|
| 568 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 569 |
+
|
| 570 |
+
self.set_surface_extractor(mc_algo)
|
| 571 |
+
|
| 572 |
+
device = self.device
|
| 573 |
+
dtype = self.dtype
|
| 574 |
+
do_classifier_free_guidance = guidance_scale >= 0 and \
|
| 575 |
+
getattr(self.model, 'guidance_cond_proj_dim', None) is None
|
| 576 |
+
dual_guidance = dual_guidance_scale >= 0 and dual_guidance
|
| 577 |
+
|
| 578 |
+
cond_inputs = self.prepare_image(image)
|
| 579 |
+
image = cond_inputs.pop('image')
|
| 580 |
+
cond = self.encode_cond(
|
| 581 |
+
image=image,
|
| 582 |
+
additional_cond_inputs=cond_inputs,
|
| 583 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 584 |
+
dual_guidance=False,
|
| 585 |
+
)
|
| 586 |
+
batch_size = image.shape[0]
|
| 587 |
+
|
| 588 |
+
t_dtype = torch.long
|
| 589 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 590 |
+
self.scheduler, num_inference_steps, device, timesteps, sigmas)
|
| 591 |
+
|
| 592 |
+
latents = self.prepare_latents(batch_size, dtype, device, generator)
|
| 593 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 594 |
+
|
| 595 |
+
guidance_cond = None
|
| 596 |
+
if getattr(self.model, 'guidance_cond_proj_dim', None) is not None:
|
| 597 |
+
logger.info('Using lcm guidance scale')
|
| 598 |
+
guidance_scale_tensor = torch.tensor(guidance_scale - 1).repeat(batch_size)
|
| 599 |
+
guidance_cond = self.get_guidance_scale_embedding(
|
| 600 |
+
guidance_scale_tensor, embedding_dim=self.model.guidance_cond_proj_dim
|
| 601 |
+
).to(device=device, dtype=latents.dtype)
|
| 602 |
+
with synchronize_timer('Diffusion Sampling'):
|
| 603 |
+
for i, t in enumerate(tqdm(timesteps, disable=not enable_pbar, desc="Diffusion Sampling:", leave=False)):
|
| 604 |
+
# expand the latents if we are doing classifier free guidance
|
| 605 |
+
if do_classifier_free_guidance:
|
| 606 |
+
latent_model_input = torch.cat([latents] * (3 if dual_guidance else 2))
|
| 607 |
+
else:
|
| 608 |
+
latent_model_input = latents
|
| 609 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 610 |
+
|
| 611 |
+
# predict the noise residual
|
| 612 |
+
timestep_tensor = torch.tensor([t], dtype=t_dtype, device=device)
|
| 613 |
+
timestep_tensor = timestep_tensor.expand(latent_model_input.shape[0])
|
| 614 |
+
noise_pred = self.model(latent_model_input, timestep_tensor, cond, guidance_cond=guidance_cond)
|
| 615 |
+
|
| 616 |
+
# no drop, drop clip, all drop
|
| 617 |
+
if do_classifier_free_guidance:
|
| 618 |
+
if dual_guidance:
|
| 619 |
+
noise_pred_clip, noise_pred_dino, noise_pred_uncond = noise_pred.chunk(3)
|
| 620 |
+
noise_pred = (
|
| 621 |
+
noise_pred_uncond
|
| 622 |
+
+ guidance_scale * (noise_pred_clip - noise_pred_dino)
|
| 623 |
+
+ dual_guidance_scale * (noise_pred_dino - noise_pred_uncond)
|
| 624 |
+
)
|
| 625 |
+
else:
|
| 626 |
+
noise_pred_cond, noise_pred_uncond = noise_pred.chunk(2)
|
| 627 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
| 628 |
+
|
| 629 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 630 |
+
outputs = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs)
|
| 631 |
+
latents = outputs.prev_sample
|
| 632 |
+
|
| 633 |
+
if callback is not None and i % callback_steps == 0:
|
| 634 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 635 |
+
callback(step_idx, t, outputs)
|
| 636 |
+
|
| 637 |
+
return self._export(
|
| 638 |
+
latents,
|
| 639 |
+
output_type,
|
| 640 |
+
box_v, mc_level, num_chunks, octree_resolution, mc_algo,
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
def _export(
|
| 644 |
+
self,
|
| 645 |
+
latents,
|
| 646 |
+
output_type='trimesh',
|
| 647 |
+
box_v=1.01,
|
| 648 |
+
mc_level=0.0,
|
| 649 |
+
num_chunks=20000,
|
| 650 |
+
octree_resolution=256,
|
| 651 |
+
mc_algo='mc',
|
| 652 |
+
enable_pbar=True
|
| 653 |
+
):
|
| 654 |
+
if not output_type == "latent":
|
| 655 |
+
latents = 1. / self.vae.scale_factor * latents
|
| 656 |
+
latents = self.vae(latents)
|
| 657 |
+
outputs = self.vae.latents2mesh(
|
| 658 |
+
latents,
|
| 659 |
+
bounds=box_v,
|
| 660 |
+
mc_level=mc_level,
|
| 661 |
+
num_chunks=num_chunks,
|
| 662 |
+
octree_resolution=octree_resolution,
|
| 663 |
+
mc_algo=mc_algo,
|
| 664 |
+
enable_pbar=enable_pbar,
|
| 665 |
+
)
|
| 666 |
+
else:
|
| 667 |
+
outputs = latents
|
| 668 |
+
|
| 669 |
+
if output_type == 'trimesh':
|
| 670 |
+
outputs = export_to_trimesh(outputs)
|
| 671 |
+
|
| 672 |
+
return outputs
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
class Hunyuan3DDiTFlowMatchingPipeline(Hunyuan3DDiTPipeline):
|
| 676 |
+
|
| 677 |
+
@torch.inference_mode()
|
| 678 |
+
def __call__(
|
| 679 |
+
self,
|
| 680 |
+
image: Union[str, List[str], Image.Image, dict, List[dict]] = None,
|
| 681 |
+
num_inference_steps: int = 50,
|
| 682 |
+
timesteps: List[int] = None,
|
| 683 |
+
sigmas: List[float] = None,
|
| 684 |
+
eta: float = 0.0,
|
| 685 |
+
guidance_scale: float = 5.0,
|
| 686 |
+
generator=None,
|
| 687 |
+
box_v=1.01,
|
| 688 |
+
octree_resolution=384,
|
| 689 |
+
mc_level=0.0,
|
| 690 |
+
mc_algo=None,
|
| 691 |
+
num_chunks=8000,
|
| 692 |
+
output_type: Optional[str] = "trimesh",
|
| 693 |
+
enable_pbar=True,
|
| 694 |
+
**kwargs,
|
| 695 |
+
) -> List[List[trimesh.Trimesh]]:
|
| 696 |
+
callback = kwargs.pop("callback", None)
|
| 697 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 698 |
+
|
| 699 |
+
self.set_surface_extractor(mc_algo)
|
| 700 |
+
|
| 701 |
+
device = self.device
|
| 702 |
+
dtype = self.dtype
|
| 703 |
+
do_classifier_free_guidance = guidance_scale >= 0 and not (
|
| 704 |
+
hasattr(self.model, 'guidance_embed') and
|
| 705 |
+
self.model.guidance_embed is True
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
cond_inputs = self.prepare_image(image)
|
| 709 |
+
image = cond_inputs.pop('image')
|
| 710 |
+
cond = self.encode_cond(
|
| 711 |
+
image=image,
|
| 712 |
+
additional_cond_inputs=cond_inputs,
|
| 713 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
| 714 |
+
dual_guidance=False,
|
| 715 |
+
)
|
| 716 |
+
batch_size = image.shape[0]
|
| 717 |
+
|
| 718 |
+
# 5. Prepare timesteps
|
| 719 |
+
# NOTE: this is slightly different from common usage, we start from 0.
|
| 720 |
+
sigmas = np.linspace(0, 1, num_inference_steps) if sigmas is None else sigmas
|
| 721 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
| 722 |
+
self.scheduler,
|
| 723 |
+
num_inference_steps,
|
| 724 |
+
device,
|
| 725 |
+
sigmas=sigmas,
|
| 726 |
+
)
|
| 727 |
+
latents = self.prepare_latents(batch_size, dtype, device, generator)
|
| 728 |
+
|
| 729 |
+
guidance = None
|
| 730 |
+
if hasattr(self.model, 'guidance_embed') and \
|
| 731 |
+
self.model.guidance_embed is True:
|
| 732 |
+
guidance = torch.tensor([guidance_scale] * batch_size, device=device, dtype=dtype)
|
| 733 |
+
# logger.info(f'Using guidance embed with scale {guidance_scale}')
|
| 734 |
+
|
| 735 |
+
with synchronize_timer('Diffusion Sampling'):
|
| 736 |
+
for i, t in enumerate(tqdm(timesteps, disable=not enable_pbar, desc="Diffusion Sampling:")):
|
| 737 |
+
# expand the latents if we are doing classifier free guidance
|
| 738 |
+
if do_classifier_free_guidance:
|
| 739 |
+
latent_model_input = torch.cat([latents] * 2)
|
| 740 |
+
else:
|
| 741 |
+
latent_model_input = latents
|
| 742 |
+
|
| 743 |
+
# NOTE: we assume model get timesteps ranged from 0 to 1
|
| 744 |
+
timestep = t.expand(latent_model_input.shape[0]).to(
|
| 745 |
+
latents.dtype) / self.scheduler.config.num_train_timesteps
|
| 746 |
+
noise_pred = self.model(latent_model_input, timestep, cond, guidance=guidance)
|
| 747 |
+
|
| 748 |
+
if do_classifier_free_guidance:
|
| 749 |
+
noise_pred_cond, noise_pred_uncond = noise_pred.chunk(2)
|
| 750 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
| 751 |
+
|
| 752 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 753 |
+
outputs = self.scheduler.step(noise_pred, t, latents)
|
| 754 |
+
latents = outputs.prev_sample
|
| 755 |
+
|
| 756 |
+
if callback is not None and i % callback_steps == 0:
|
| 757 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 758 |
+
callback(step_idx, t, outputs)
|
| 759 |
+
|
| 760 |
+
return self._export(
|
| 761 |
+
latents,
|
| 762 |
+
output_type,
|
| 763 |
+
box_v, mc_level, num_chunks, octree_resolution, mc_algo,
|
| 764 |
+
enable_pbar=enable_pbar,
|
| 765 |
+
)
|
OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/postprocessors.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import tempfile
|
| 17 |
+
from typing import Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pymeshlab
|
| 21 |
+
import torch
|
| 22 |
+
import trimesh
|
| 23 |
+
|
| 24 |
+
from .models.autoencoders import Latent2MeshOutput
|
| 25 |
+
from .utils import synchronize_timer
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def load_mesh(path):
|
| 29 |
+
if path.endswith(".glb"):
|
| 30 |
+
mesh = trimesh.load(path)
|
| 31 |
+
else:
|
| 32 |
+
mesh = pymeshlab.MeshSet()
|
| 33 |
+
mesh.load_new_mesh(path)
|
| 34 |
+
return mesh
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def reduce_face(mesh: pymeshlab.MeshSet, max_facenum: int = 200000):
|
| 38 |
+
if max_facenum > mesh.current_mesh().face_number():
|
| 39 |
+
return mesh
|
| 40 |
+
|
| 41 |
+
mesh.apply_filter(
|
| 42 |
+
"meshing_decimation_quadric_edge_collapse",
|
| 43 |
+
targetfacenum=max_facenum,
|
| 44 |
+
qualitythr=1.0,
|
| 45 |
+
preserveboundary=True,
|
| 46 |
+
boundaryweight=3,
|
| 47 |
+
preservenormal=True,
|
| 48 |
+
preservetopology=True,
|
| 49 |
+
autoclean=True
|
| 50 |
+
)
|
| 51 |
+
return mesh
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def remove_floater(mesh: pymeshlab.MeshSet):
|
| 55 |
+
mesh.apply_filter("compute_selection_by_small_disconnected_components_per_face",
|
| 56 |
+
nbfaceratio=0.005)
|
| 57 |
+
mesh.apply_filter("compute_selection_transfer_face_to_vertex", inclusive=False)
|
| 58 |
+
mesh.apply_filter("meshing_remove_selected_vertices_and_faces")
|
| 59 |
+
return mesh
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def pymeshlab2trimesh(mesh: pymeshlab.MeshSet):
|
| 63 |
+
tmp_dir = os.path.join(os.environ.get('TMPDIR', tempfile.gettempdir()), 'hy3dgen_tmp')
|
| 64 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 65 |
+
temp_file_path = os.path.join(tmp_dir, f'temp_mesh_{os.getpid()}.ply')
|
| 66 |
+
mesh.save_current_mesh(temp_file_path)
|
| 67 |
+
mesh = trimesh.load(temp_file_path)
|
| 68 |
+
# Check loaded object type
|
| 69 |
+
if isinstance(mesh, trimesh.Scene):
|
| 70 |
+
combined_mesh = trimesh.Trimesh()
|
| 71 |
+
# If it's a Scene, iterate through all geometries and merge them
|
| 72 |
+
for geom in mesh.geometry.values():
|
| 73 |
+
combined_mesh = trimesh.util.concatenate([combined_mesh, geom])
|
| 74 |
+
mesh = combined_mesh
|
| 75 |
+
return mesh
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def trimesh2pymeshlab(mesh: trimesh.Trimesh):
|
| 79 |
+
with tempfile.NamedTemporaryFile(suffix='.ply', delete=False) as temp_file:
|
| 80 |
+
if isinstance(mesh, trimesh.scene.Scene):
|
| 81 |
+
for idx, obj in enumerate(mesh.geometry.values()):
|
| 82 |
+
if idx == 0:
|
| 83 |
+
temp_mesh = obj
|
| 84 |
+
else:
|
| 85 |
+
temp_mesh = temp_mesh + obj
|
| 86 |
+
mesh = temp_mesh
|
| 87 |
+
mesh.export(temp_file.name)
|
| 88 |
+
mesh = pymeshlab.MeshSet()
|
| 89 |
+
mesh.load_new_mesh(temp_file.name)
|
| 90 |
+
return mesh
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def export_mesh(input, output):
|
| 94 |
+
if isinstance(input, pymeshlab.MeshSet):
|
| 95 |
+
mesh = output
|
| 96 |
+
elif isinstance(input, Latent2MeshOutput):
|
| 97 |
+
output = Latent2MeshOutput()
|
| 98 |
+
output.mesh_v = output.current_mesh().vertex_matrix()
|
| 99 |
+
output.mesh_f = output.current_mesh().face_matrix()
|
| 100 |
+
mesh = output
|
| 101 |
+
else:
|
| 102 |
+
mesh = pymeshlab2trimesh(output)
|
| 103 |
+
return mesh
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def import_mesh(mesh: Union[pymeshlab.MeshSet, trimesh.Trimesh, Latent2MeshOutput, str]) -> pymeshlab.MeshSet:
|
| 107 |
+
if isinstance(mesh, str):
|
| 108 |
+
mesh = load_mesh(mesh)
|
| 109 |
+
elif isinstance(mesh, Latent2MeshOutput):
|
| 110 |
+
mesh = pymeshlab.MeshSet()
|
| 111 |
+
mesh_pymeshlab = pymeshlab.Mesh(vertex_matrix=mesh.mesh_v, face_matrix=mesh.mesh_f)
|
| 112 |
+
mesh.add_mesh(mesh_pymeshlab, "converted_mesh")
|
| 113 |
+
|
| 114 |
+
if isinstance(mesh, (trimesh.Trimesh, trimesh.scene.Scene)):
|
| 115 |
+
mesh = trimesh2pymeshlab(mesh)
|
| 116 |
+
|
| 117 |
+
return mesh
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class FaceReducer:
|
| 121 |
+
@synchronize_timer('FaceReducer')
|
| 122 |
+
def __call__(
|
| 123 |
+
self,
|
| 124 |
+
mesh: Union[pymeshlab.MeshSet, trimesh.Trimesh, Latent2MeshOutput, str],
|
| 125 |
+
max_facenum: int = 40000
|
| 126 |
+
) -> Union[pymeshlab.MeshSet, trimesh.Trimesh]:
|
| 127 |
+
ms = import_mesh(mesh)
|
| 128 |
+
ms = reduce_face(ms, max_facenum=max_facenum)
|
| 129 |
+
mesh = export_mesh(mesh, ms)
|
| 130 |
+
return mesh
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class FloaterRemover:
|
| 134 |
+
@synchronize_timer('FloaterRemover')
|
| 135 |
+
def __call__(
|
| 136 |
+
self,
|
| 137 |
+
mesh: Union[pymeshlab.MeshSet, trimesh.Trimesh, Latent2MeshOutput, str],
|
| 138 |
+
) -> Union[pymeshlab.MeshSet, trimesh.Trimesh, Latent2MeshOutput]:
|
| 139 |
+
ms = import_mesh(mesh)
|
| 140 |
+
ms = remove_floater(ms)
|
| 141 |
+
mesh = export_mesh(mesh, ms)
|
| 142 |
+
return mesh
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class DegenerateFaceRemover:
|
| 146 |
+
@synchronize_timer('DegenerateFaceRemover')
|
| 147 |
+
def __call__(
|
| 148 |
+
self,
|
| 149 |
+
mesh: Union[pymeshlab.MeshSet, trimesh.Trimesh, Latent2MeshOutput, str],
|
| 150 |
+
) -> Union[pymeshlab.MeshSet, trimesh.Trimesh, Latent2MeshOutput]:
|
| 151 |
+
ms = import_mesh(mesh)
|
| 152 |
+
|
| 153 |
+
with tempfile.NamedTemporaryFile(suffix='.ply', delete=False) as temp_file:
|
| 154 |
+
ms.save_current_mesh(temp_file.name)
|
| 155 |
+
ms = pymeshlab.MeshSet()
|
| 156 |
+
ms.load_new_mesh(temp_file.name)
|
| 157 |
+
|
| 158 |
+
mesh = export_mesh(mesh, ms)
|
| 159 |
+
return mesh
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def mesh_normalize(mesh):
|
| 163 |
+
"""
|
| 164 |
+
Normalize mesh vertices to sphere
|
| 165 |
+
"""
|
| 166 |
+
scale_factor = 1.2
|
| 167 |
+
vtx_pos = np.asarray(mesh.vertices)
|
| 168 |
+
max_bb = (vtx_pos - 0).max(0)[0]
|
| 169 |
+
min_bb = (vtx_pos - 0).min(0)[0]
|
| 170 |
+
|
| 171 |
+
center = (max_bb + min_bb) / 2
|
| 172 |
+
|
| 173 |
+
scale = torch.norm(torch.tensor(vtx_pos - center, dtype=torch.float32), dim=1).max() * 2.0
|
| 174 |
+
|
| 175 |
+
vtx_pos = (vtx_pos - center) * (scale_factor / float(scale))
|
| 176 |
+
mesh.vertices = vtx_pos
|
| 177 |
+
|
| 178 |
+
return mesh
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class MeshSimplifier:
|
| 182 |
+
def __init__(self, executable: str = None):
|
| 183 |
+
if executable is None:
|
| 184 |
+
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 185 |
+
executable = os.path.join(CURRENT_DIR, "mesh_simplifier.bin")
|
| 186 |
+
self.executable = executable
|
| 187 |
+
|
| 188 |
+
@synchronize_timer('MeshSimplifier')
|
| 189 |
+
def __call__(
|
| 190 |
+
self,
|
| 191 |
+
mesh: Union[trimesh.Trimesh],
|
| 192 |
+
) -> Union[trimesh.Trimesh]:
|
| 193 |
+
with tempfile.NamedTemporaryFile(suffix='.obj', delete=False) as temp_input:
|
| 194 |
+
with tempfile.NamedTemporaryFile(suffix='.obj', delete=False) as temp_output:
|
| 195 |
+
mesh.export(temp_input.name)
|
| 196 |
+
os.system(f'{self.executable} {temp_input.name} {temp_output.name}')
|
| 197 |
+
ms = trimesh.load(temp_output.name, process=False)
|
| 198 |
+
if isinstance(ms, trimesh.Scene):
|
| 199 |
+
combined_mesh = trimesh.Trimesh()
|
| 200 |
+
for geom in ms.geometry.values():
|
| 201 |
+
combined_mesh = trimesh.util.concatenate([combined_mesh, geom])
|
| 202 |
+
ms = combined_mesh
|
| 203 |
+
ms = mesh_normalize(ms)
|
| 204 |
+
return ms
|
OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/preprocessors.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
import cv2
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
from PIL import Image
|
| 19 |
+
from einops import repeat, rearrange
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def array_to_tensor(np_array):
|
| 23 |
+
image_pt = torch.tensor(np_array).float()
|
| 24 |
+
image_pt = image_pt / 255 * 2 - 1
|
| 25 |
+
image_pt = rearrange(image_pt, "h w c -> c h w")
|
| 26 |
+
image_pts = repeat(image_pt, "c h w -> b c h w", b=1)
|
| 27 |
+
return image_pts
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ImageProcessorV2:
|
| 31 |
+
def __init__(self, size=512, border_ratio=None):
|
| 32 |
+
self.size = size
|
| 33 |
+
self.border_ratio = border_ratio
|
| 34 |
+
|
| 35 |
+
@staticmethod
|
| 36 |
+
def recenter(image, border_ratio: float = 0.2):
|
| 37 |
+
""" recenter an image to leave some empty space at the image border.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
image (ndarray): input image, float/uint8 [H, W, 3/4]
|
| 41 |
+
mask (ndarray): alpha mask, bool [H, W]
|
| 42 |
+
border_ratio (float, optional): border ratio, image will be resized to (1 - border_ratio). Defaults to 0.2.
|
| 43 |
+
|
| 44 |
+
Returns:
|
| 45 |
+
ndarray: output image, float/uint8 [H, W, 3/4]
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
if image.shape[-1] == 4:
|
| 49 |
+
mask = image[..., 3]
|
| 50 |
+
else:
|
| 51 |
+
mask = np.ones_like(image[..., 0:1]) * 255
|
| 52 |
+
image = np.concatenate([image, mask], axis=-1)
|
| 53 |
+
mask = mask[..., 0]
|
| 54 |
+
|
| 55 |
+
H, W, C = image.shape
|
| 56 |
+
|
| 57 |
+
size = max(H, W)
|
| 58 |
+
result = np.zeros((size, size, C), dtype=np.uint8)
|
| 59 |
+
|
| 60 |
+
coords = np.nonzero(mask)
|
| 61 |
+
x_min, x_max = coords[0].min(), coords[0].max()
|
| 62 |
+
y_min, y_max = coords[1].min(), coords[1].max()
|
| 63 |
+
h = x_max - x_min
|
| 64 |
+
w = y_max - y_min
|
| 65 |
+
if h == 0 or w == 0:
|
| 66 |
+
raise ValueError('input image is empty')
|
| 67 |
+
desired_size = int(size * (1 - border_ratio))
|
| 68 |
+
scale = desired_size / max(h, w)
|
| 69 |
+
h2 = int(h * scale)
|
| 70 |
+
w2 = int(w * scale)
|
| 71 |
+
x2_min = (size - h2) // 2
|
| 72 |
+
x2_max = x2_min + h2
|
| 73 |
+
|
| 74 |
+
y2_min = (size - w2) // 2
|
| 75 |
+
y2_max = y2_min + w2
|
| 76 |
+
|
| 77 |
+
result[x2_min:x2_max, y2_min:y2_max] = cv2.resize(image[x_min:x_max, y_min:y_max], (w2, h2),
|
| 78 |
+
interpolation=cv2.INTER_AREA)
|
| 79 |
+
|
| 80 |
+
bg = np.ones((result.shape[0], result.shape[1], 3), dtype=np.uint8) * 255
|
| 81 |
+
|
| 82 |
+
mask = result[..., 3:].astype(np.float32) / 255
|
| 83 |
+
result = result[..., :3] * mask + bg * (1 - mask)
|
| 84 |
+
|
| 85 |
+
mask = mask * 255
|
| 86 |
+
result = result.clip(0, 255).astype(np.uint8)
|
| 87 |
+
mask = mask.clip(0, 255).astype(np.uint8)
|
| 88 |
+
return result, mask
|
| 89 |
+
|
| 90 |
+
def load_image(self, image, border_ratio=0.15, to_tensor=True):
|
| 91 |
+
if isinstance(image, str):
|
| 92 |
+
image = cv2.imread(image, cv2.IMREAD_UNCHANGED)
|
| 93 |
+
image, mask = self.recenter(image, border_ratio=border_ratio)
|
| 94 |
+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
|
| 95 |
+
elif isinstance(image, Image.Image):
|
| 96 |
+
image = image.convert("RGBA")
|
| 97 |
+
image = np.asarray(image)
|
| 98 |
+
image, mask = self.recenter(image, border_ratio=border_ratio)
|
| 99 |
+
|
| 100 |
+
image = cv2.resize(image, (self.size, self.size), interpolation=cv2.INTER_CUBIC)
|
| 101 |
+
mask = cv2.resize(mask, (self.size, self.size), interpolation=cv2.INTER_NEAREST)
|
| 102 |
+
mask = mask[..., np.newaxis]
|
| 103 |
+
|
| 104 |
+
if to_tensor:
|
| 105 |
+
image = array_to_tensor(image)
|
| 106 |
+
mask = array_to_tensor(mask)
|
| 107 |
+
return image, mask
|
| 108 |
+
|
| 109 |
+
def __call__(self, image, border_ratio=0.15, to_tensor=True, **kwargs):
|
| 110 |
+
if self.border_ratio is not None:
|
| 111 |
+
border_ratio = self.border_ratio
|
| 112 |
+
image, mask = self.load_image(image, border_ratio=border_ratio, to_tensor=to_tensor)
|
| 113 |
+
outputs = {
|
| 114 |
+
'image': image,
|
| 115 |
+
'mask': mask
|
| 116 |
+
}
|
| 117 |
+
return outputs
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class MVImageProcessorV2(ImageProcessorV2):
|
| 121 |
+
"""
|
| 122 |
+
view order: front, front clockwise 90, back, front clockwise 270
|
| 123 |
+
"""
|
| 124 |
+
return_view_idx = True
|
| 125 |
+
|
| 126 |
+
def __init__(self, size=512, border_ratio=None):
|
| 127 |
+
super().__init__(size, border_ratio)
|
| 128 |
+
self.view2idx = {
|
| 129 |
+
'front': 0,
|
| 130 |
+
'left': 1,
|
| 131 |
+
'back': 2,
|
| 132 |
+
'right': 3
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
def __call__(self, image_dict, border_ratio=0.15, to_tensor=True, **kwargs):
|
| 136 |
+
if self.border_ratio is not None:
|
| 137 |
+
border_ratio = self.border_ratio
|
| 138 |
+
|
| 139 |
+
images = []
|
| 140 |
+
masks = []
|
| 141 |
+
view_idxs = []
|
| 142 |
+
for idx, (view_tag, image) in enumerate(image_dict.items()):
|
| 143 |
+
view_idxs.append(self.view2idx[view_tag])
|
| 144 |
+
image, mask = self.load_image(image, border_ratio=border_ratio, to_tensor=to_tensor)
|
| 145 |
+
images.append(image)
|
| 146 |
+
masks.append(mask)
|
| 147 |
+
|
| 148 |
+
zipped_lists = zip(view_idxs, images, masks)
|
| 149 |
+
sorted_zipped_lists = sorted(zipped_lists)
|
| 150 |
+
view_idxs, images, masks = zip(*sorted_zipped_lists)
|
| 151 |
+
|
| 152 |
+
image = torch.cat(images, 0).unsqueeze(0)
|
| 153 |
+
mask = torch.cat(masks, 0).unsqueeze(0)
|
| 154 |
+
outputs = {
|
| 155 |
+
'image': image,
|
| 156 |
+
'mask': mask,
|
| 157 |
+
'view_idxs': view_idxs
|
| 158 |
+
}
|
| 159 |
+
return outputs
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
IMAGE_PROCESSORS = {
|
| 163 |
+
"v2": ImageProcessorV2,
|
| 164 |
+
'mv_v2': MVImageProcessorV2,
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
DEFAULT_IMAGEPROCESSOR = 'v2'
|
OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/schedulers.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Stability AI, Katherine Crowson and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 16 |
+
# except for the third-party components listed below.
|
| 17 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 18 |
+
# in the repsective licenses of these third-party components.
|
| 19 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 20 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 21 |
+
# all relevant laws and regulations.
|
| 22 |
+
|
| 23 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 24 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 25 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 26 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 27 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 28 |
+
|
| 29 |
+
import math
|
| 30 |
+
from dataclasses import dataclass
|
| 31 |
+
from typing import List, Optional, Tuple, Union
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 36 |
+
from diffusers.schedulers.scheduling_utils import SchedulerMixin
|
| 37 |
+
from diffusers.utils import BaseOutput, logging
|
| 38 |
+
|
| 39 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class FlowMatchEulerDiscreteSchedulerOutput(BaseOutput):
|
| 44 |
+
"""
|
| 45 |
+
Output class for the scheduler's `step` function output.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
|
| 49 |
+
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
|
| 50 |
+
denoising loop.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
prev_sample: torch.FloatTensor
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class FlowMatchEulerDiscreteScheduler(SchedulerMixin, ConfigMixin):
|
| 57 |
+
"""
|
| 58 |
+
NOTE: this is very similar to diffusers.FlowMatchEulerDiscreteScheduler. Except our timesteps are reversed
|
| 59 |
+
|
| 60 |
+
Euler scheduler.
|
| 61 |
+
|
| 62 |
+
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
|
| 63 |
+
methods the library implements for all schedulers such as loading and saving.
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
num_train_timesteps (`int`, defaults to 1000):
|
| 67 |
+
The number of diffusion steps to train the model.
|
| 68 |
+
timestep_spacing (`str`, defaults to `"linspace"`):
|
| 69 |
+
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
|
| 70 |
+
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
|
| 71 |
+
shift (`float`, defaults to 1.0):
|
| 72 |
+
The shift value for the timestep schedule.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
_compatibles = []
|
| 76 |
+
order = 1
|
| 77 |
+
|
| 78 |
+
@register_to_config
|
| 79 |
+
def __init__(
|
| 80 |
+
self,
|
| 81 |
+
num_train_timesteps: int = 1000,
|
| 82 |
+
shift: float = 1.0,
|
| 83 |
+
use_dynamic_shifting=False,
|
| 84 |
+
):
|
| 85 |
+
timesteps = np.linspace(1, num_train_timesteps, num_train_timesteps, dtype=np.float32).copy()
|
| 86 |
+
timesteps = torch.from_numpy(timesteps).to(dtype=torch.float32)
|
| 87 |
+
|
| 88 |
+
sigmas = timesteps / num_train_timesteps
|
| 89 |
+
if not use_dynamic_shifting:
|
| 90 |
+
# when use_dynamic_shifting is True, we apply the timestep shifting on the fly based on the image resolution
|
| 91 |
+
sigmas = shift * sigmas / (1 + (shift - 1) * sigmas)
|
| 92 |
+
|
| 93 |
+
self.timesteps = sigmas * num_train_timesteps
|
| 94 |
+
|
| 95 |
+
self._step_index = None
|
| 96 |
+
self._begin_index = None
|
| 97 |
+
|
| 98 |
+
self.sigmas = sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 99 |
+
self.sigma_min = self.sigmas[-1].item()
|
| 100 |
+
self.sigma_max = self.sigmas[0].item()
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def step_index(self):
|
| 104 |
+
"""
|
| 105 |
+
The index counter for current timestep. It will increase 1 after each scheduler step.
|
| 106 |
+
"""
|
| 107 |
+
return self._step_index
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def begin_index(self):
|
| 111 |
+
"""
|
| 112 |
+
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
|
| 113 |
+
"""
|
| 114 |
+
return self._begin_index
|
| 115 |
+
|
| 116 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
|
| 117 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 118 |
+
"""
|
| 119 |
+
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
begin_index (`int`):
|
| 123 |
+
The begin index for the scheduler.
|
| 124 |
+
"""
|
| 125 |
+
self._begin_index = begin_index
|
| 126 |
+
|
| 127 |
+
def scale_noise(
|
| 128 |
+
self,
|
| 129 |
+
sample: torch.FloatTensor,
|
| 130 |
+
timestep: Union[float, torch.FloatTensor],
|
| 131 |
+
noise: Optional[torch.FloatTensor] = None,
|
| 132 |
+
) -> torch.FloatTensor:
|
| 133 |
+
"""
|
| 134 |
+
Forward process in flow-matching
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
sample (`torch.FloatTensor`):
|
| 138 |
+
The input sample.
|
| 139 |
+
timestep (`int`, *optional*):
|
| 140 |
+
The current timestep in the diffusion chain.
|
| 141 |
+
|
| 142 |
+
Returns:
|
| 143 |
+
`torch.FloatTensor`:
|
| 144 |
+
A scaled input sample.
|
| 145 |
+
"""
|
| 146 |
+
# Make sure sigmas and timesteps have the same device and dtype as original_samples
|
| 147 |
+
sigmas = self.sigmas.to(device=sample.device, dtype=sample.dtype)
|
| 148 |
+
|
| 149 |
+
if sample.device.type == "mps" and torch.is_floating_point(timestep):
|
| 150 |
+
# mps does not support float64
|
| 151 |
+
schedule_timesteps = self.timesteps.to(sample.device, dtype=torch.float32)
|
| 152 |
+
timestep = timestep.to(sample.device, dtype=torch.float32)
|
| 153 |
+
else:
|
| 154 |
+
schedule_timesteps = self.timesteps.to(sample.device)
|
| 155 |
+
timestep = timestep.to(sample.device)
|
| 156 |
+
|
| 157 |
+
# self.begin_index is None when scheduler is used for training, or pipeline does not implement set_begin_index
|
| 158 |
+
if self.begin_index is None:
|
| 159 |
+
step_indices = [self.index_for_timestep(t, schedule_timesteps) for t in timestep]
|
| 160 |
+
elif self.step_index is not None:
|
| 161 |
+
# add_noise is called after first denoising step (for inpainting)
|
| 162 |
+
step_indices = [self.step_index] * timestep.shape[0]
|
| 163 |
+
else:
|
| 164 |
+
# add noise is called before first denoising step to create initial latent(img2img)
|
| 165 |
+
step_indices = [self.begin_index] * timestep.shape[0]
|
| 166 |
+
|
| 167 |
+
sigma = sigmas[step_indices].flatten()
|
| 168 |
+
while len(sigma.shape) < len(sample.shape):
|
| 169 |
+
sigma = sigma.unsqueeze(-1)
|
| 170 |
+
|
| 171 |
+
sample = sigma * noise + (1.0 - sigma) * sample
|
| 172 |
+
|
| 173 |
+
return sample
|
| 174 |
+
|
| 175 |
+
def _sigma_to_t(self, sigma):
|
| 176 |
+
return sigma * self.config.num_train_timesteps
|
| 177 |
+
|
| 178 |
+
def time_shift(self, mu: float, sigma: float, t: torch.Tensor):
|
| 179 |
+
return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
|
| 180 |
+
|
| 181 |
+
def set_timesteps(
|
| 182 |
+
self,
|
| 183 |
+
num_inference_steps: int = None,
|
| 184 |
+
device: Union[str, torch.device] = None,
|
| 185 |
+
sigmas: Optional[List[float]] = None,
|
| 186 |
+
mu: Optional[float] = None,
|
| 187 |
+
):
|
| 188 |
+
"""
|
| 189 |
+
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
|
| 190 |
+
|
| 191 |
+
Args:
|
| 192 |
+
num_inference_steps (`int`):
|
| 193 |
+
The number of diffusion steps used when generating samples with a pre-trained model.
|
| 194 |
+
device (`str` or `torch.device`, *optional*):
|
| 195 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
if self.config.use_dynamic_shifting and mu is None:
|
| 199 |
+
raise ValueError(" you have a pass a value for `mu` when `use_dynamic_shifting` is set to be `True`")
|
| 200 |
+
|
| 201 |
+
if sigmas is None:
|
| 202 |
+
self.num_inference_steps = num_inference_steps
|
| 203 |
+
timesteps = np.linspace(
|
| 204 |
+
self._sigma_to_t(self.sigma_max), self._sigma_to_t(self.sigma_min), num_inference_steps
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
sigmas = timesteps / self.config.num_train_timesteps
|
| 208 |
+
|
| 209 |
+
if self.config.use_dynamic_shifting:
|
| 210 |
+
sigmas = self.time_shift(mu, 1.0, sigmas)
|
| 211 |
+
else:
|
| 212 |
+
sigmas = self.config.shift * sigmas / (1 + (self.config.shift - 1) * sigmas)
|
| 213 |
+
|
| 214 |
+
sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32, device=device)
|
| 215 |
+
timesteps = sigmas * self.config.num_train_timesteps
|
| 216 |
+
|
| 217 |
+
self.timesteps = timesteps.to(device=device)
|
| 218 |
+
self.sigmas = torch.cat([sigmas, torch.ones(1, device=sigmas.device)])
|
| 219 |
+
|
| 220 |
+
self._step_index = None
|
| 221 |
+
self._begin_index = None
|
| 222 |
+
|
| 223 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 224 |
+
if schedule_timesteps is None:
|
| 225 |
+
schedule_timesteps = self.timesteps
|
| 226 |
+
|
| 227 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 228 |
+
|
| 229 |
+
# The sigma index that is taken for the **very** first `step`
|
| 230 |
+
# is always the second index (or the last index if there is only 1)
|
| 231 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 232 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 233 |
+
pos = 1 if len(indices) > 1 else 0
|
| 234 |
+
|
| 235 |
+
return indices[pos].item()
|
| 236 |
+
|
| 237 |
+
def _init_step_index(self, timestep):
|
| 238 |
+
if self.begin_index is None:
|
| 239 |
+
if isinstance(timestep, torch.Tensor):
|
| 240 |
+
timestep = timestep.to(self.timesteps.device)
|
| 241 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 242 |
+
else:
|
| 243 |
+
self._step_index = self._begin_index
|
| 244 |
+
|
| 245 |
+
def step(
|
| 246 |
+
self,
|
| 247 |
+
model_output: torch.FloatTensor,
|
| 248 |
+
timestep: Union[float, torch.FloatTensor],
|
| 249 |
+
sample: torch.FloatTensor,
|
| 250 |
+
s_churn: float = 0.0,
|
| 251 |
+
s_tmin: float = 0.0,
|
| 252 |
+
s_tmax: float = float("inf"),
|
| 253 |
+
s_noise: float = 1.0,
|
| 254 |
+
generator: Optional[torch.Generator] = None,
|
| 255 |
+
return_dict: bool = True,
|
| 256 |
+
) -> Union[FlowMatchEulerDiscreteSchedulerOutput, Tuple]:
|
| 257 |
+
"""
|
| 258 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
|
| 259 |
+
process from the learned model outputs (most often the predicted noise).
|
| 260 |
+
|
| 261 |
+
Args:
|
| 262 |
+
model_output (`torch.FloatTensor`):
|
| 263 |
+
The direct output from learned diffusion model.
|
| 264 |
+
timestep (`float`):
|
| 265 |
+
The current discrete timestep in the diffusion chain.
|
| 266 |
+
sample (`torch.FloatTensor`):
|
| 267 |
+
A current instance of a sample created by the diffusion process.
|
| 268 |
+
s_churn (`float`):
|
| 269 |
+
s_tmin (`float`):
|
| 270 |
+
s_tmax (`float`):
|
| 271 |
+
s_noise (`float`, defaults to 1.0):
|
| 272 |
+
Scaling factor for noise added to the sample.
|
| 273 |
+
generator (`torch.Generator`, *optional*):
|
| 274 |
+
A random number generator.
|
| 275 |
+
return_dict (`bool`):
|
| 276 |
+
Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
|
| 277 |
+
tuple.
|
| 278 |
+
|
| 279 |
+
Returns:
|
| 280 |
+
[`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
|
| 281 |
+
If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
|
| 282 |
+
returned, otherwise a tuple is returned where the first element is the sample tensor.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
if (
|
| 286 |
+
isinstance(timestep, int)
|
| 287 |
+
or isinstance(timestep, torch.IntTensor)
|
| 288 |
+
or isinstance(timestep, torch.LongTensor)
|
| 289 |
+
):
|
| 290 |
+
raise ValueError(
|
| 291 |
+
(
|
| 292 |
+
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
|
| 293 |
+
" `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
|
| 294 |
+
" one of the `scheduler.timesteps` as a timestep."
|
| 295 |
+
),
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
if self.step_index is None:
|
| 299 |
+
self._init_step_index(timestep)
|
| 300 |
+
|
| 301 |
+
# Upcast to avoid precision issues when computing prev_sample
|
| 302 |
+
sample = sample.to(torch.float32)
|
| 303 |
+
|
| 304 |
+
sigma = self.sigmas[self.step_index]
|
| 305 |
+
sigma_next = self.sigmas[self.step_index + 1]
|
| 306 |
+
|
| 307 |
+
prev_sample = sample + (sigma_next - sigma) * model_output
|
| 308 |
+
|
| 309 |
+
# Cast sample back to model compatible dtype
|
| 310 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 311 |
+
|
| 312 |
+
# upon completion increase step index by one
|
| 313 |
+
self._step_index += 1
|
| 314 |
+
|
| 315 |
+
if not return_dict:
|
| 316 |
+
return (prev_sample,)
|
| 317 |
+
|
| 318 |
+
return FlowMatchEulerDiscreteSchedulerOutput(prev_sample=prev_sample)
|
| 319 |
+
|
| 320 |
+
def __len__(self):
|
| 321 |
+
return self.config.num_train_timesteps
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@dataclass
|
| 325 |
+
class ConsistencyFlowMatchEulerDiscreteSchedulerOutput(BaseOutput):
|
| 326 |
+
prev_sample: torch.FloatTensor
|
| 327 |
+
pred_original_sample: torch.FloatTensor
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class ConsistencyFlowMatchEulerDiscreteScheduler(SchedulerMixin, ConfigMixin):
|
| 331 |
+
_compatibles = []
|
| 332 |
+
order = 1
|
| 333 |
+
|
| 334 |
+
@register_to_config
|
| 335 |
+
def __init__(
|
| 336 |
+
self,
|
| 337 |
+
num_train_timesteps: int = 1000,
|
| 338 |
+
pcm_timesteps: int = 50,
|
| 339 |
+
):
|
| 340 |
+
sigmas = np.linspace(0, 1, num_train_timesteps)
|
| 341 |
+
step_ratio = num_train_timesteps // pcm_timesteps
|
| 342 |
+
|
| 343 |
+
euler_timesteps = (np.arange(1, pcm_timesteps) * step_ratio).round().astype(np.int64) - 1
|
| 344 |
+
euler_timesteps = np.asarray([0] + euler_timesteps.tolist())
|
| 345 |
+
|
| 346 |
+
self.euler_timesteps = euler_timesteps
|
| 347 |
+
self.sigmas = sigmas[self.euler_timesteps]
|
| 348 |
+
self.sigmas = torch.from_numpy((self.sigmas.copy())).to(dtype=torch.float32)
|
| 349 |
+
self.timesteps = self.sigmas * num_train_timesteps
|
| 350 |
+
self._step_index = None
|
| 351 |
+
self._begin_index = None
|
| 352 |
+
self.sigmas = self.sigmas.to("cpu") # to avoid too much CPU/GPU communication
|
| 353 |
+
|
| 354 |
+
@property
|
| 355 |
+
def step_index(self):
|
| 356 |
+
"""
|
| 357 |
+
The index counter for current timestep. It will increase 1 after each scheduler step.
|
| 358 |
+
"""
|
| 359 |
+
return self._step_index
|
| 360 |
+
|
| 361 |
+
@property
|
| 362 |
+
def begin_index(self):
|
| 363 |
+
"""
|
| 364 |
+
The index for the first timestep. It should be set from pipeline with `set_begin_index` method.
|
| 365 |
+
"""
|
| 366 |
+
return self._begin_index
|
| 367 |
+
|
| 368 |
+
# Copied from diffusers.schedulers.scheduling_dpmsolver_multistep.DPMSolverMultistepScheduler.set_begin_index
|
| 369 |
+
def set_begin_index(self, begin_index: int = 0):
|
| 370 |
+
"""
|
| 371 |
+
Sets the begin index for the scheduler. This function should be run from pipeline before the inference.
|
| 372 |
+
|
| 373 |
+
Args:
|
| 374 |
+
begin_index (`int`):
|
| 375 |
+
The begin index for the scheduler.
|
| 376 |
+
"""
|
| 377 |
+
self._begin_index = begin_index
|
| 378 |
+
|
| 379 |
+
def _sigma_to_t(self, sigma):
|
| 380 |
+
return sigma * self.config.num_train_timesteps
|
| 381 |
+
|
| 382 |
+
def set_timesteps(
|
| 383 |
+
self,
|
| 384 |
+
num_inference_steps: int = None,
|
| 385 |
+
device: Union[str, torch.device] = None,
|
| 386 |
+
sigmas: Optional[List[float]] = None,
|
| 387 |
+
):
|
| 388 |
+
"""
|
| 389 |
+
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
|
| 390 |
+
|
| 391 |
+
Args:
|
| 392 |
+
num_inference_steps (`int`):
|
| 393 |
+
The number of diffusion steps used when generating samples with a pre-trained model.
|
| 394 |
+
device (`str` or `torch.device`, *optional*):
|
| 395 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 396 |
+
"""
|
| 397 |
+
self.num_inference_steps = num_inference_steps if num_inference_steps is not None else len(sigmas)
|
| 398 |
+
inference_indices = np.linspace(
|
| 399 |
+
0, self.config.pcm_timesteps, num=self.num_inference_steps, endpoint=False
|
| 400 |
+
)
|
| 401 |
+
inference_indices = np.floor(inference_indices).astype(np.int64)
|
| 402 |
+
inference_indices = torch.from_numpy(inference_indices).long()
|
| 403 |
+
|
| 404 |
+
self.sigmas_ = self.sigmas[inference_indices]
|
| 405 |
+
timesteps = self.sigmas_ * self.config.num_train_timesteps
|
| 406 |
+
self.timesteps = timesteps.to(device=device)
|
| 407 |
+
self.sigmas_ = torch.cat(
|
| 408 |
+
[self.sigmas_, torch.ones(1, device=self.sigmas_.device)]
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
self._step_index = None
|
| 412 |
+
self._begin_index = None
|
| 413 |
+
|
| 414 |
+
def index_for_timestep(self, timestep, schedule_timesteps=None):
|
| 415 |
+
if schedule_timesteps is None:
|
| 416 |
+
schedule_timesteps = self.timesteps
|
| 417 |
+
|
| 418 |
+
indices = (schedule_timesteps == timestep).nonzero()
|
| 419 |
+
|
| 420 |
+
# The sigma index that is taken for the **very** first `step`
|
| 421 |
+
# is always the second index (or the last index if there is only 1)
|
| 422 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 423 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 424 |
+
pos = 1 if len(indices) > 1 else 0
|
| 425 |
+
|
| 426 |
+
return indices[pos].item()
|
| 427 |
+
|
| 428 |
+
def _init_step_index(self, timestep):
|
| 429 |
+
if self.begin_index is None:
|
| 430 |
+
if isinstance(timestep, torch.Tensor):
|
| 431 |
+
timestep = timestep.to(self.timesteps.device)
|
| 432 |
+
self._step_index = self.index_for_timestep(timestep)
|
| 433 |
+
else:
|
| 434 |
+
self._step_index = self._begin_index
|
| 435 |
+
|
| 436 |
+
def step(
|
| 437 |
+
self,
|
| 438 |
+
model_output: torch.FloatTensor,
|
| 439 |
+
timestep: Union[float, torch.FloatTensor],
|
| 440 |
+
sample: torch.FloatTensor,
|
| 441 |
+
generator: Optional[torch.Generator] = None,
|
| 442 |
+
return_dict: bool = True,
|
| 443 |
+
) -> Union[ConsistencyFlowMatchEulerDiscreteSchedulerOutput, Tuple]:
|
| 444 |
+
if (
|
| 445 |
+
isinstance(timestep, int)
|
| 446 |
+
or isinstance(timestep, torch.IntTensor)
|
| 447 |
+
or isinstance(timestep, torch.LongTensor)
|
| 448 |
+
):
|
| 449 |
+
raise ValueError(
|
| 450 |
+
(
|
| 451 |
+
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
|
| 452 |
+
" `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
|
| 453 |
+
" one of the `scheduler.timesteps` as a timestep."
|
| 454 |
+
),
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
if self.step_index is None:
|
| 458 |
+
self._init_step_index(timestep)
|
| 459 |
+
|
| 460 |
+
sample = sample.to(torch.float32)
|
| 461 |
+
|
| 462 |
+
sigma = self.sigmas_[self.step_index]
|
| 463 |
+
sigma_next = self.sigmas_[self.step_index + 1]
|
| 464 |
+
|
| 465 |
+
prev_sample = sample + (sigma_next - sigma) * model_output
|
| 466 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 467 |
+
|
| 468 |
+
pred_original_sample = sample + (1.0 - sigma) * model_output
|
| 469 |
+
pred_original_sample = pred_original_sample.to(model_output.dtype)
|
| 470 |
+
|
| 471 |
+
self._step_index += 1
|
| 472 |
+
|
| 473 |
+
if not return_dict:
|
| 474 |
+
return (prev_sample,)
|
| 475 |
+
|
| 476 |
+
return ConsistencyFlowMatchEulerDiscreteSchedulerOutput(prev_sample=prev_sample,
|
| 477 |
+
pred_original_sample=pred_original_sample)
|
| 478 |
+
|
| 479 |
+
def __len__(self):
|
| 480 |
+
return self.config.num_train_timesteps
|
OVOW/third_party/Motion324/scripts/hy3dgen/shapegen/utils.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
import logging
|
| 16 |
+
import os
|
| 17 |
+
from functools import wraps
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_logger(name):
|
| 23 |
+
logger = logging.getLogger(name)
|
| 24 |
+
logger.setLevel(logging.INFO)
|
| 25 |
+
|
| 26 |
+
console_handler = logging.StreamHandler()
|
| 27 |
+
console_handler.setLevel(logging.INFO)
|
| 28 |
+
|
| 29 |
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
| 30 |
+
console_handler.setFormatter(formatter)
|
| 31 |
+
logger.addHandler(console_handler)
|
| 32 |
+
return logger
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
logger = get_logger('hy3dgen.shapgen')
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class synchronize_timer:
|
| 39 |
+
""" Synchronized timer to count the inference time of `nn.Module.forward`.
|
| 40 |
+
|
| 41 |
+
Supports both context manager and decorator usage.
|
| 42 |
+
|
| 43 |
+
Example as context manager:
|
| 44 |
+
```python
|
| 45 |
+
with synchronize_timer('name') as t:
|
| 46 |
+
run()
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Example as decorator:
|
| 50 |
+
```python
|
| 51 |
+
@synchronize_timer('Export to trimesh')
|
| 52 |
+
def export_to_trimesh(mesh_output):
|
| 53 |
+
pass
|
| 54 |
+
```
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
def __init__(self, name=None):
|
| 58 |
+
self.name = name
|
| 59 |
+
|
| 60 |
+
def __enter__(self):
|
| 61 |
+
"""Context manager entry: start timing."""
|
| 62 |
+
if os.environ.get('HY3DGEN_DEBUG', '0') == '1':
|
| 63 |
+
self.start = torch.cuda.Event(enable_timing=True)
|
| 64 |
+
self.end = torch.cuda.Event(enable_timing=True)
|
| 65 |
+
self.start.record()
|
| 66 |
+
return lambda: self.time
|
| 67 |
+
|
| 68 |
+
def __exit__(self, exc_type, exc_value, exc_tb):
|
| 69 |
+
"""Context manager exit: stop timing and log results."""
|
| 70 |
+
if os.environ.get('HY3DGEN_DEBUG', '0') == '1':
|
| 71 |
+
self.end.record()
|
| 72 |
+
torch.cuda.synchronize()
|
| 73 |
+
self.time = self.start.elapsed_time(self.end)
|
| 74 |
+
if self.name is not None:
|
| 75 |
+
logger.info(f'{self.name} takes {self.time} ms')
|
| 76 |
+
|
| 77 |
+
def __call__(self, func):
|
| 78 |
+
"""Decorator: wrap the function to time its execution."""
|
| 79 |
+
|
| 80 |
+
@wraps(func)
|
| 81 |
+
def wrapper(*args, **kwargs):
|
| 82 |
+
with self:
|
| 83 |
+
result = func(*args, **kwargs)
|
| 84 |
+
return result
|
| 85 |
+
|
| 86 |
+
return wrapper
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def smart_load_model(
|
| 90 |
+
model_path,
|
| 91 |
+
subfolder,
|
| 92 |
+
use_safetensors,
|
| 93 |
+
variant,
|
| 94 |
+
):
|
| 95 |
+
original_model_path = model_path
|
| 96 |
+
# try local path
|
| 97 |
+
base_dir = os.environ.get('HY3DGEN_MODELS', '~/.cache/hy3dgen')
|
| 98 |
+
model_path = os.path.expanduser(os.path.join(base_dir, model_path, subfolder))
|
| 99 |
+
logger.info(f'Try to load model from local path: {model_path}')
|
| 100 |
+
if not os.path.exists(model_path):
|
| 101 |
+
logger.info('Model path not exists, try to download from huggingface')
|
| 102 |
+
try:
|
| 103 |
+
from huggingface_hub import snapshot_download
|
| 104 |
+
# Only download specified subdirectory
|
| 105 |
+
path = snapshot_download(
|
| 106 |
+
repo_id=original_model_path,
|
| 107 |
+
allow_patterns=[f"{subfolder}/*"], # Key modification: pattern match subfolder
|
| 108 |
+
)
|
| 109 |
+
model_path = os.path.join(path, subfolder) # Keep path concatenation logic unchanged
|
| 110 |
+
except ImportError:
|
| 111 |
+
logger.warning(
|
| 112 |
+
"You need to install HuggingFace Hub to load models from the hub."
|
| 113 |
+
)
|
| 114 |
+
raise RuntimeError(f"Model path {model_path} not found")
|
| 115 |
+
except Exception as e:
|
| 116 |
+
raise e
|
| 117 |
+
|
| 118 |
+
if not os.path.exists(model_path):
|
| 119 |
+
raise FileNotFoundError(f"Model path {original_model_path} not found")
|
| 120 |
+
|
| 121 |
+
extension = 'ckpt' if not use_safetensors else 'safetensors'
|
| 122 |
+
variant = '' if variant is None else f'.{variant}'
|
| 123 |
+
ckpt_name = f'model{variant}.{extension}'
|
| 124 |
+
config_path = os.path.join(model_path, 'config.yaml')
|
| 125 |
+
ckpt_path = os.path.join(model_path, ckpt_name)
|
| 126 |
+
return config_path, ckpt_path
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
from .pipelines import Hunyuan3DPaintPipeline, Hunyuan3DTexGenConfig
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
'''
|
| 16 |
+
from .hierarchy import BuildHierarchy, BuildHierarchyWithColor
|
| 17 |
+
from .io_obj import LoadObj, LoadObjWithTexture
|
| 18 |
+
from .render import rasterize, interpolate
|
| 19 |
+
'''
|
| 20 |
+
from .io_glb import *
|
| 21 |
+
from .io_obj import *
|
| 22 |
+
from .render import *
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_glb.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
import base64
|
| 16 |
+
import io
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
from PIL import Image as PILImage
|
| 21 |
+
from pygltflib import GLTF2
|
| 22 |
+
from scipy.spatial.transform import Rotation as R
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Function to extract buffer data
|
| 26 |
+
def get_buffer_data(gltf, buffer_view):
|
| 27 |
+
buffer = gltf.buffers[buffer_view.buffer]
|
| 28 |
+
buffer_data = gltf.get_data_from_buffer_uri(buffer.uri)
|
| 29 |
+
byte_offset = buffer_view.byteOffset if buffer_view.byteOffset else 0
|
| 30 |
+
byte_length = buffer_view.byteLength
|
| 31 |
+
return buffer_data[byte_offset:byte_offset + byte_length]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# Function to extract attribute data
|
| 35 |
+
def get_attribute_data(gltf, accessor_index):
|
| 36 |
+
accessor = gltf.accessors[accessor_index]
|
| 37 |
+
buffer_view = gltf.bufferViews[accessor.bufferView]
|
| 38 |
+
buffer_data = get_buffer_data(gltf, buffer_view)
|
| 39 |
+
|
| 40 |
+
comptype = {5120: np.int8, 5121: np.uint8, 5122: np.int16, 5123: np.uint16, 5125: np.uint32, 5126: np.float32}
|
| 41 |
+
dtype = comptype[accessor.componentType]
|
| 42 |
+
|
| 43 |
+
t2n = {'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16}
|
| 44 |
+
num_components = t2n[accessor.type]
|
| 45 |
+
|
| 46 |
+
# Calculate the correct slice of data
|
| 47 |
+
byte_offset = accessor.byteOffset if accessor.byteOffset else 0
|
| 48 |
+
byte_stride = buffer_view.byteStride if buffer_view.byteStride else num_components * np.dtype(dtype).itemsize
|
| 49 |
+
count = accessor.count
|
| 50 |
+
|
| 51 |
+
# Extract the attribute data
|
| 52 |
+
attribute_data = np.zeros((count, num_components), dtype=dtype)
|
| 53 |
+
for i in range(count):
|
| 54 |
+
start = byte_offset + i * byte_stride
|
| 55 |
+
end = start + num_components * np.dtype(dtype).itemsize
|
| 56 |
+
attribute_data[i] = np.frombuffer(buffer_data[start:end], dtype=dtype)
|
| 57 |
+
|
| 58 |
+
return attribute_data
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# Function to extract image data
|
| 62 |
+
def get_image_data(gltf, image, folder):
|
| 63 |
+
if image.uri:
|
| 64 |
+
if image.uri.startswith('data:'):
|
| 65 |
+
# Data URI
|
| 66 |
+
header, encoded = image.uri.split(',', 1)
|
| 67 |
+
data = base64.b64decode(encoded)
|
| 68 |
+
else:
|
| 69 |
+
# External file
|
| 70 |
+
fn = image.uri
|
| 71 |
+
if not os.path.isabs(fn):
|
| 72 |
+
fn = folder + '/' + fn
|
| 73 |
+
with open(fn, 'rb') as f:
|
| 74 |
+
data = f.read()
|
| 75 |
+
else:
|
| 76 |
+
buffer_view = gltf.bufferViews[image.bufferView]
|
| 77 |
+
data = get_buffer_data(gltf, buffer_view)
|
| 78 |
+
return data
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# Function to convert triangle strip to triangles
|
| 82 |
+
def convert_triangle_strip_to_triangles(indices):
|
| 83 |
+
triangles = []
|
| 84 |
+
for i in range(len(indices) - 2):
|
| 85 |
+
if i % 2 == 0:
|
| 86 |
+
triangles.append([indices[i], indices[i + 1], indices[i + 2]])
|
| 87 |
+
else:
|
| 88 |
+
triangles.append([indices[i], indices[i + 2], indices[i + 1]])
|
| 89 |
+
return np.array(triangles).reshape(-1, 3)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Function to convert triangle fan to triangles
|
| 93 |
+
def convert_triangle_fan_to_triangles(indices):
|
| 94 |
+
triangles = []
|
| 95 |
+
for i in range(1, len(indices) - 1):
|
| 96 |
+
triangles.append([indices[0], indices[i], indices[i + 1]])
|
| 97 |
+
return np.array(triangles).reshape(-1, 3)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# Function to get the transformation matrix from a node
|
| 101 |
+
def get_node_transform(node):
|
| 102 |
+
if node.matrix:
|
| 103 |
+
return np.array(node.matrix).reshape(4, 4).T
|
| 104 |
+
else:
|
| 105 |
+
T = np.eye(4)
|
| 106 |
+
if node.translation:
|
| 107 |
+
T[:3, 3] = node.translation
|
| 108 |
+
if node.rotation:
|
| 109 |
+
R_mat = R.from_quat(node.rotation).as_matrix()
|
| 110 |
+
T[:3, :3] = R_mat
|
| 111 |
+
if node.scale:
|
| 112 |
+
S = np.diag(node.scale + [1])
|
| 113 |
+
T = T @ S
|
| 114 |
+
return T
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def get_world_transform(gltf, node_index, parents, world_transforms):
|
| 118 |
+
if parents[node_index] == -2:
|
| 119 |
+
return world_transforms[node_index]
|
| 120 |
+
|
| 121 |
+
node = gltf.nodes[node_index]
|
| 122 |
+
if parents[node_index] == -1:
|
| 123 |
+
world_transforms[node_index] = get_node_transform(node)
|
| 124 |
+
parents[node_index] = -2
|
| 125 |
+
return world_transforms[node_index]
|
| 126 |
+
|
| 127 |
+
parent_index = parents[node_index]
|
| 128 |
+
parent_transform = get_world_transform(gltf, parent_index, parents, world_transforms)
|
| 129 |
+
world_transforms[node_index] = parent_transform @ get_node_transform(node)
|
| 130 |
+
parents[node_index] = -2
|
| 131 |
+
return world_transforms[node_index]
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def LoadGlb(path):
|
| 135 |
+
# Load the GLB file using pygltflib
|
| 136 |
+
gltf = GLTF2().load(path)
|
| 137 |
+
|
| 138 |
+
primitives = []
|
| 139 |
+
images = {}
|
| 140 |
+
# Iterate through the meshes in the GLB file
|
| 141 |
+
|
| 142 |
+
world_transforms = [np.identity(4) for i in range(len(gltf.nodes))]
|
| 143 |
+
parents = [-1 for i in range(len(gltf.nodes))]
|
| 144 |
+
for node_index, node in enumerate(gltf.nodes):
|
| 145 |
+
for idx in node.children:
|
| 146 |
+
parents[idx] = node_index
|
| 147 |
+
# for i in range(len(gltf.nodes)):
|
| 148 |
+
# get_world_transform(gltf, i, parents, world_transform)
|
| 149 |
+
|
| 150 |
+
for node_index, node in enumerate(gltf.nodes):
|
| 151 |
+
if node.mesh is not None:
|
| 152 |
+
world_transform = get_world_transform(gltf, node_index, parents, world_transforms)
|
| 153 |
+
# Iterate through the primitives in the mesh
|
| 154 |
+
mesh = gltf.meshes[node.mesh]
|
| 155 |
+
for primitive in mesh.primitives:
|
| 156 |
+
# Access the attributes of the primitive
|
| 157 |
+
attributes = primitive.attributes.__dict__
|
| 158 |
+
mode = primitive.mode if primitive.mode is not None else 4 # Default to TRIANGLES
|
| 159 |
+
result = {}
|
| 160 |
+
if primitive.indices is not None:
|
| 161 |
+
indices = get_attribute_data(gltf, primitive.indices)
|
| 162 |
+
if mode == 4: # TRIANGLES
|
| 163 |
+
face_indices = indices.reshape(-1, 3)
|
| 164 |
+
elif mode == 5: # TRIANGLE_STRIP
|
| 165 |
+
face_indices = convert_triangle_strip_to_triangles(indices)
|
| 166 |
+
elif mode == 6: # TRIANGLE_FAN
|
| 167 |
+
face_indices = convert_triangle_fan_to_triangles(indices)
|
| 168 |
+
else:
|
| 169 |
+
continue
|
| 170 |
+
result['F'] = face_indices
|
| 171 |
+
|
| 172 |
+
# Extract vertex positions
|
| 173 |
+
if 'POSITION' in attributes and attributes['POSITION'] is not None:
|
| 174 |
+
positions = get_attribute_data(gltf, attributes['POSITION'])
|
| 175 |
+
# Apply the world transformation to the positions
|
| 176 |
+
positions_homogeneous = np.hstack([positions, np.ones((positions.shape[0], 1))])
|
| 177 |
+
transformed_positions = (world_transform @ positions_homogeneous.T).T[:, :3]
|
| 178 |
+
result['V'] = transformed_positions
|
| 179 |
+
|
| 180 |
+
# Extract vertex colors
|
| 181 |
+
if 'COLOR_0' in attributes and attributes['COLOR_0'] is not None:
|
| 182 |
+
colors = get_attribute_data(gltf, attributes['COLOR_0'])
|
| 183 |
+
if colors.shape[-1] > 3:
|
| 184 |
+
colors = colors[..., :3]
|
| 185 |
+
result['VC'] = colors
|
| 186 |
+
|
| 187 |
+
# Extract UVs
|
| 188 |
+
if 'TEXCOORD_0' in attributes and not attributes['TEXCOORD_0'] is None:
|
| 189 |
+
uvs = get_attribute_data(gltf, attributes['TEXCOORD_0'])
|
| 190 |
+
result['UV'] = uvs
|
| 191 |
+
|
| 192 |
+
if primitive.material is not None:
|
| 193 |
+
material = gltf.materials[primitive.material]
|
| 194 |
+
if (
|
| 195 |
+
material.pbrMetallicRoughness is not None
|
| 196 |
+
and material.pbrMetallicRoughness.baseColorTexture is not None
|
| 197 |
+
):
|
| 198 |
+
texture_index = material.pbrMetallicRoughness.baseColorTexture.index
|
| 199 |
+
texture = gltf.textures[texture_index]
|
| 200 |
+
image_index = texture.source
|
| 201 |
+
if not image_index in images:
|
| 202 |
+
image = gltf.images[image_index]
|
| 203 |
+
image_data = get_image_data(gltf, image, os.path.dirname(path))
|
| 204 |
+
pil_image = PILImage.open(io.BytesIO(image_data))
|
| 205 |
+
if pil_image.mode != 'RGB':
|
| 206 |
+
pil_image = pil_image.convert('RGB')
|
| 207 |
+
images[image_index] = pil_image
|
| 208 |
+
result['TEX'] = image_index
|
| 209 |
+
elif material.emissiveTexture is not None:
|
| 210 |
+
texture_index = material.emissiveTexture.index
|
| 211 |
+
texture = gltf.textures[texture_index]
|
| 212 |
+
image_index = texture.source
|
| 213 |
+
if not image_index in images:
|
| 214 |
+
image = gltf.images[image_index]
|
| 215 |
+
image_data = get_image_data(gltf, image, os.path.dirname(path))
|
| 216 |
+
pil_image = PILImage.open(io.BytesIO(image_data))
|
| 217 |
+
if pil_image.mode != 'RGB':
|
| 218 |
+
pil_image = pil_image.convert('RGB')
|
| 219 |
+
images[image_index] = pil_image
|
| 220 |
+
result['TEX'] = image_index
|
| 221 |
+
else:
|
| 222 |
+
if material.pbrMetallicRoughness is not None:
|
| 223 |
+
base_color = material.pbrMetallicRoughness.baseColorFactor
|
| 224 |
+
else:
|
| 225 |
+
base_color = np.array([0.8, 0.8, 0.8], dtype=np.float32)
|
| 226 |
+
result['MC'] = base_color
|
| 227 |
+
|
| 228 |
+
primitives.append(result)
|
| 229 |
+
|
| 230 |
+
return primitives, images
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def RotatePrimitives(primitives, transform):
|
| 234 |
+
for i in range(len(primitives)):
|
| 235 |
+
if 'V' in primitives[i]:
|
| 236 |
+
primitives[i]['V'] = primitives[i]['V'] @ transform.T
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
if __name__ == '__main__':
|
| 240 |
+
path = 'data/test.glb'
|
| 241 |
+
LoadGlb(path)
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/io_obj.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
import cv2
|
| 16 |
+
import numpy as np
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def LoadObj(fn):
|
| 20 |
+
lines = [l.strip() for l in open(fn)]
|
| 21 |
+
vertices = []
|
| 22 |
+
faces = []
|
| 23 |
+
for l in lines:
|
| 24 |
+
words = [w for w in l.split(' ') if w != '']
|
| 25 |
+
if len(words) == 0:
|
| 26 |
+
continue
|
| 27 |
+
if words[0] == 'v':
|
| 28 |
+
v = [float(words[i]) for i in range(1, 4)]
|
| 29 |
+
vertices.append(v)
|
| 30 |
+
elif words[0] == 'f':
|
| 31 |
+
f = [int(words[i]) - 1 for i in range(1, 4)]
|
| 32 |
+
faces.append(f)
|
| 33 |
+
|
| 34 |
+
return np.array(vertices).astype('float32'), np.array(faces).astype('int32')
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def LoadObjWithTexture(fn, tex_fn):
|
| 38 |
+
lines = [l.strip() for l in open(fn)]
|
| 39 |
+
vertices = []
|
| 40 |
+
vertex_textures = []
|
| 41 |
+
faces = []
|
| 42 |
+
face_textures = []
|
| 43 |
+
for l in lines:
|
| 44 |
+
words = [w for w in l.split(' ') if w != '']
|
| 45 |
+
if len(words) == 0:
|
| 46 |
+
continue
|
| 47 |
+
if words[0] == 'v':
|
| 48 |
+
v = [float(words[i]) for i in range(1, len(words))]
|
| 49 |
+
vertices.append(v)
|
| 50 |
+
elif words[0] == 'vt':
|
| 51 |
+
v = [float(words[i]) for i in range(1, len(words))]
|
| 52 |
+
vertex_textures.append(v)
|
| 53 |
+
elif words[0] == 'f':
|
| 54 |
+
f = []
|
| 55 |
+
ft = []
|
| 56 |
+
for i in range(1, len(words)):
|
| 57 |
+
t = words[i].split('/')
|
| 58 |
+
f.append(int(t[0]) - 1)
|
| 59 |
+
ft.append(int(t[1]) - 1)
|
| 60 |
+
for i in range(2, len(f)):
|
| 61 |
+
faces.append([f[0], f[i - 1], f[i]])
|
| 62 |
+
face_textures.append([ft[0], ft[i - 1], ft[i]])
|
| 63 |
+
|
| 64 |
+
tex_image = cv2.cvtColor(cv2.imread(tex_fn), cv2.COLOR_BGR2RGB)
|
| 65 |
+
return np.array(vertices).astype('float32'), np.array(vertex_textures).astype('float32'), np.array(faces).astype(
|
| 66 |
+
'int32'), np.array(face_textures).astype('int32'), tex_image
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/custom_rasterizer/render.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
| 14 |
+
|
| 15 |
+
import custom_rasterizer_kernel
|
| 16 |
+
import torch
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def rasterize(pos, tri, resolution, clamp_depth=torch.zeros(0), use_depth_prior=0):
|
| 20 |
+
assert (pos.device == tri.device)
|
| 21 |
+
findices, barycentric = custom_rasterizer_kernel.rasterize_image(pos[0], tri, clamp_depth, resolution[1],
|
| 22 |
+
resolution[0], 1e-6, use_depth_prior)
|
| 23 |
+
return findices, barycentric
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def interpolate(col, findices, barycentric, tri):
|
| 27 |
+
f = findices - 1 + (findices == 0)
|
| 28 |
+
vcol = col[0, tri.long()[f.long()]]
|
| 29 |
+
result = barycentric.view(*barycentric.shape, 1) * vcol
|
| 30 |
+
result = torch.sum(result, axis=-2)
|
| 31 |
+
return result.view(1, *result.shape)
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
|
| 2 |
+
# except for the third-party components listed below.
|
| 3 |
+
# Hunyuan 3D does not impose any additional limitations beyond what is outlined
|
| 4 |
+
# in the repsective licenses of these third-party components.
|
| 5 |
+
# Users must comply with all terms and conditions of original licenses of these third-party
|
| 6 |
+
# components and must ensure that the usage of the third party components adheres to
|
| 7 |
+
# all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
# For avoidance of doubts, Hunyuan 3D means the large language models and
|
| 10 |
+
# their software and algorithms, including trained model weights, parameters (including
|
| 11 |
+
# optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
|
| 12 |
+
# fine-tuning enabling code and other elements of the foregoing made publicly available
|
| 13 |
+
# by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/grid_neighbor.cpp
ADDED
|
@@ -0,0 +1,574 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "rasterizer.h"
|
| 2 |
+
#include <fstream>
|
| 3 |
+
|
| 4 |
+
inline int pos2key(float* p, int resolution) {
|
| 5 |
+
int x = (p[0] * 0.5 + 0.5) * resolution;
|
| 6 |
+
int y = (p[1] * 0.5 + 0.5) * resolution;
|
| 7 |
+
int z = (p[2] * 0.5 + 0.5) * resolution;
|
| 8 |
+
return (x * resolution + y) * resolution + z;
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
inline void key2pos(int key, int resolution, float* p) {
|
| 12 |
+
int x = key / resolution / resolution;
|
| 13 |
+
int y = key / resolution % resolution;
|
| 14 |
+
int z = key % resolution;
|
| 15 |
+
p[0] = ((x + 0.5) / resolution - 0.5) * 2;
|
| 16 |
+
p[1] = ((y + 0.5) / resolution - 0.5) * 2;
|
| 17 |
+
p[2] = ((z + 0.5) / resolution - 0.5) * 2;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
inline void key2cornerpos(int key, int resolution, float* p) {
|
| 21 |
+
int x = key / resolution / resolution;
|
| 22 |
+
int y = key / resolution % resolution;
|
| 23 |
+
int z = key % resolution;
|
| 24 |
+
p[0] = ((x + 0.75) / resolution - 0.5) * 2;
|
| 25 |
+
p[1] = ((y + 0.25) / resolution - 0.5) * 2;
|
| 26 |
+
p[2] = ((z + 0.75) / resolution - 0.5) * 2;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
inline float* pos_ptr(int l, int i, int j, torch::Tensor t) {
|
| 30 |
+
float* pdata = t.data_ptr<float>();
|
| 31 |
+
int height = t.size(1);
|
| 32 |
+
int width = t.size(2);
|
| 33 |
+
return &pdata[((l * height + i) * width + j) * 4];
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
struct Grid
|
| 37 |
+
{
|
| 38 |
+
std::vector<int> seq2oddcorner;
|
| 39 |
+
std::vector<int> seq2evencorner;
|
| 40 |
+
std::vector<int> seq2grid;
|
| 41 |
+
std::vector<int> seq2normal;
|
| 42 |
+
std::vector<int> seq2neighbor;
|
| 43 |
+
std::unordered_map<int, int> grid2seq;
|
| 44 |
+
std::vector<int> downsample_seq;
|
| 45 |
+
int num_origin_seq;
|
| 46 |
+
int resolution;
|
| 47 |
+
int stride;
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
inline void pos_from_seq(Grid& grid, int seq, float* p) {
|
| 51 |
+
auto k = grid.seq2grid[seq];
|
| 52 |
+
key2pos(k, grid.resolution, p);
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
inline int fetch_seq(Grid& grid, int l, int i, int j, torch::Tensor pdata) {
|
| 56 |
+
float* p = pos_ptr(l, i, j, pdata);
|
| 57 |
+
if (p[3] == 0)
|
| 58 |
+
return -1;
|
| 59 |
+
auto key = pos2key(p, grid.resolution);
|
| 60 |
+
int seq = grid.grid2seq[key];
|
| 61 |
+
return seq;
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
inline int fetch_last_seq(Grid& grid, int i, int j, torch::Tensor pdata) {
|
| 65 |
+
int num_layers = pdata.size(0);
|
| 66 |
+
int l = 0;
|
| 67 |
+
int idx = fetch_seq(grid, l, i, j, pdata);
|
| 68 |
+
while (l < num_layers - 1) {
|
| 69 |
+
l += 1;
|
| 70 |
+
int new_idx = fetch_seq(grid, l, i, j, pdata);
|
| 71 |
+
if (new_idx == -1)
|
| 72 |
+
break;
|
| 73 |
+
idx = new_idx;
|
| 74 |
+
}
|
| 75 |
+
return idx;
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
inline int fetch_nearest_seq(Grid& grid, int i, int j, int dim, float d, torch::Tensor pdata) {
|
| 79 |
+
float p[3];
|
| 80 |
+
float max_dist = 1e10;
|
| 81 |
+
int best_idx = -1;
|
| 82 |
+
int num_layers = pdata.size(0);
|
| 83 |
+
for (int l = 0; l < num_layers; ++l) {
|
| 84 |
+
int idx = fetch_seq(grid, l, i, j, pdata);
|
| 85 |
+
if (idx == -1)
|
| 86 |
+
break;
|
| 87 |
+
pos_from_seq(grid, idx, p);
|
| 88 |
+
float dist = std::abs(d - p[(dim + 2) % 3]);
|
| 89 |
+
if (dist < max_dist) {
|
| 90 |
+
max_dist = dist;
|
| 91 |
+
best_idx = idx;
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
return best_idx;
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
inline int fetch_nearest_seq_layer(Grid& grid, int i, int j, int dim, float d, torch::Tensor pdata) {
|
| 98 |
+
float p[3];
|
| 99 |
+
float max_dist = 1e10;
|
| 100 |
+
int best_layer = -1;
|
| 101 |
+
int num_layers = pdata.size(0);
|
| 102 |
+
for (int l = 0; l < num_layers; ++l) {
|
| 103 |
+
int idx = fetch_seq(grid, l, i, j, pdata);
|
| 104 |
+
if (idx == -1)
|
| 105 |
+
break;
|
| 106 |
+
pos_from_seq(grid, idx, p);
|
| 107 |
+
float dist = std::abs(d - p[(dim + 2) % 3]);
|
| 108 |
+
if (dist < max_dist) {
|
| 109 |
+
max_dist = dist;
|
| 110 |
+
best_layer = l;
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
return best_layer;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
void FetchNeighbor(Grid& grid, int seq, float* pos, int dim, int boundary_info, std::vector<torch::Tensor>& view_layer_positions,
|
| 117 |
+
int* output_indices)
|
| 118 |
+
{
|
| 119 |
+
auto t = view_layer_positions[dim];
|
| 120 |
+
int height = t.size(1);
|
| 121 |
+
int width = t.size(2);
|
| 122 |
+
int top = 0;
|
| 123 |
+
int ci = 0;
|
| 124 |
+
int cj = 0;
|
| 125 |
+
if (dim == 0) {
|
| 126 |
+
ci = (pos[1]/2+0.5)*height;
|
| 127 |
+
cj = (pos[0]/2+0.5)*width;
|
| 128 |
+
}
|
| 129 |
+
else if (dim == 1) {
|
| 130 |
+
ci = (pos[1]/2+0.5)*height;
|
| 131 |
+
cj = (pos[2]/2+0.5)*width;
|
| 132 |
+
}
|
| 133 |
+
else {
|
| 134 |
+
ci = (-pos[2]/2+0.5)*height;
|
| 135 |
+
cj = (pos[0]/2+0.5)*width;
|
| 136 |
+
}
|
| 137 |
+
int stride = grid.stride;
|
| 138 |
+
for (int ni = ci + stride; ni >= ci - stride; ni -= stride) {
|
| 139 |
+
for (int nj = cj - stride; nj <= cj + stride; nj += stride) {
|
| 140 |
+
int idx = -1;
|
| 141 |
+
if (ni == ci && nj == cj)
|
| 142 |
+
idx = seq;
|
| 143 |
+
else if (!(ni < 0 || ni >= height || nj < 0 || nj >= width)) {
|
| 144 |
+
if (boundary_info == -1)
|
| 145 |
+
idx = fetch_seq(grid, 0, ni, nj, t);
|
| 146 |
+
else if (boundary_info == 1)
|
| 147 |
+
idx = fetch_last_seq(grid, ni, nj, t);
|
| 148 |
+
else
|
| 149 |
+
idx = fetch_nearest_seq(grid, ni, nj, dim, pos[(dim + 2) % 3], t);
|
| 150 |
+
}
|
| 151 |
+
output_indices[top] = idx;
|
| 152 |
+
top += 1;
|
| 153 |
+
}
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
void DownsampleGrid(Grid& src, Grid& tar)
|
| 158 |
+
{
|
| 159 |
+
src.downsample_seq.resize(src.seq2grid.size(), -1);
|
| 160 |
+
tar.resolution = src.resolution / 2;
|
| 161 |
+
tar.stride = src.stride * 2;
|
| 162 |
+
float pos[3];
|
| 163 |
+
std::vector<int> seq2normal_count;
|
| 164 |
+
for (int i = 0; i < src.seq2grid.size(); ++i) {
|
| 165 |
+
key2pos(src.seq2grid[i], src.resolution, pos);
|
| 166 |
+
int k = pos2key(pos, tar.resolution);
|
| 167 |
+
int s = seq2normal_count.size();
|
| 168 |
+
if (!tar.grid2seq.count(k)) {
|
| 169 |
+
tar.grid2seq[k] = tar.seq2grid.size();
|
| 170 |
+
tar.seq2grid.emplace_back(k);
|
| 171 |
+
seq2normal_count.emplace_back(0);
|
| 172 |
+
seq2normal_count.emplace_back(0);
|
| 173 |
+
seq2normal_count.emplace_back(0);
|
| 174 |
+
//tar.seq2normal.emplace_back(src.seq2normal[i]);
|
| 175 |
+
} else {
|
| 176 |
+
s = tar.grid2seq[k] * 3;
|
| 177 |
+
}
|
| 178 |
+
seq2normal_count[s + src.seq2normal[i]] += 1;
|
| 179 |
+
src.downsample_seq[i] = tar.grid2seq[k];
|
| 180 |
+
}
|
| 181 |
+
tar.seq2normal.resize(seq2normal_count.size() / 3);
|
| 182 |
+
for (int i = 0; i < seq2normal_count.size(); i += 3) {
|
| 183 |
+
int t = 0;
|
| 184 |
+
for (int j = 1; j < 3; ++j) {
|
| 185 |
+
if (seq2normal_count[i + j] > seq2normal_count[i + t])
|
| 186 |
+
t = j;
|
| 187 |
+
}
|
| 188 |
+
tar.seq2normal[i / 3] = t;
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
void NeighborGrid(Grid& grid, std::vector<torch::Tensor> view_layer_positions, int v)
|
| 193 |
+
{
|
| 194 |
+
grid.seq2evencorner.resize(grid.seq2grid.size(), 0);
|
| 195 |
+
grid.seq2oddcorner.resize(grid.seq2grid.size(), 0);
|
| 196 |
+
std::unordered_set<int> visited_seq;
|
| 197 |
+
for (int vd = 0; vd < 3; ++vd) {
|
| 198 |
+
auto t = view_layer_positions[vd];
|
| 199 |
+
auto t0 = view_layer_positions[v];
|
| 200 |
+
int height = t.size(1);
|
| 201 |
+
int width = t.size(2);
|
| 202 |
+
int num_layers = t.size(0);
|
| 203 |
+
int num_view_layers = t0.size(0);
|
| 204 |
+
for (int i = 0; i < height; ++i) {
|
| 205 |
+
for (int j = 0; j < width; ++j) {
|
| 206 |
+
for (int l = 0; l < num_layers; ++l) {
|
| 207 |
+
int seq = fetch_seq(grid, l, i, j, t);
|
| 208 |
+
if (seq == -1)
|
| 209 |
+
break;
|
| 210 |
+
int dim = grid.seq2normal[seq];
|
| 211 |
+
if (dim != v)
|
| 212 |
+
continue;
|
| 213 |
+
|
| 214 |
+
float pos[3];
|
| 215 |
+
pos_from_seq(grid, seq, pos);
|
| 216 |
+
|
| 217 |
+
int ci = 0;
|
| 218 |
+
int cj = 0;
|
| 219 |
+
if (dim == 0) {
|
| 220 |
+
ci = (pos[1]/2+0.5)*height;
|
| 221 |
+
cj = (pos[0]/2+0.5)*width;
|
| 222 |
+
}
|
| 223 |
+
else if (dim == 1) {
|
| 224 |
+
ci = (pos[1]/2+0.5)*height;
|
| 225 |
+
cj = (pos[2]/2+0.5)*width;
|
| 226 |
+
}
|
| 227 |
+
else {
|
| 228 |
+
ci = (-pos[2]/2+0.5)*height;
|
| 229 |
+
cj = (pos[0]/2+0.5)*width;
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
if ((ci % (grid.stride * 2) < grid.stride) && (cj % (grid.stride * 2) >= grid.stride))
|
| 233 |
+
grid.seq2evencorner[seq] = 1;
|
| 234 |
+
|
| 235 |
+
if ((ci % (grid.stride * 2) >= grid.stride) && (cj % (grid.stride * 2) < grid.stride))
|
| 236 |
+
grid.seq2oddcorner[seq] = 1;
|
| 237 |
+
|
| 238 |
+
bool is_boundary = false;
|
| 239 |
+
if (vd == v) {
|
| 240 |
+
if (l == 0 || l == num_layers - 1)
|
| 241 |
+
is_boundary = true;
|
| 242 |
+
else {
|
| 243 |
+
int seq_new = fetch_seq(grid, l + 1, i, j, t);
|
| 244 |
+
if (seq_new == -1)
|
| 245 |
+
is_boundary = true;
|
| 246 |
+
}
|
| 247 |
+
}
|
| 248 |
+
int boundary_info = 0;
|
| 249 |
+
if (is_boundary && (l == 0))
|
| 250 |
+
boundary_info = -1;
|
| 251 |
+
else if (is_boundary)
|
| 252 |
+
boundary_info = 1;
|
| 253 |
+
if (visited_seq.count(seq))
|
| 254 |
+
continue;
|
| 255 |
+
visited_seq.insert(seq);
|
| 256 |
+
|
| 257 |
+
FetchNeighbor(grid, seq, pos, dim, boundary_info, view_layer_positions, &grid.seq2neighbor[seq * 9]);
|
| 258 |
+
}
|
| 259 |
+
}
|
| 260 |
+
}
|
| 261 |
+
}
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
void PadGrid(Grid& src, Grid& tar, std::vector<torch::Tensor>& view_layer_positions) {
|
| 265 |
+
auto& downsample_seq = src.downsample_seq;
|
| 266 |
+
auto& seq2evencorner = src.seq2evencorner;
|
| 267 |
+
auto& seq2oddcorner = src.seq2oddcorner;
|
| 268 |
+
int indices[9];
|
| 269 |
+
std::vector<int> mapped_even_corners(tar.seq2grid.size(), 0);
|
| 270 |
+
std::vector<int> mapped_odd_corners(tar.seq2grid.size(), 0);
|
| 271 |
+
for (int i = 0; i < downsample_seq.size(); ++i) {
|
| 272 |
+
if (seq2evencorner[i] > 0) {
|
| 273 |
+
mapped_even_corners[downsample_seq[i]] = 1;
|
| 274 |
+
}
|
| 275 |
+
if (seq2oddcorner[i] > 0) {
|
| 276 |
+
mapped_odd_corners[downsample_seq[i]] = 1;
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
auto& tar_seq2normal = tar.seq2normal;
|
| 280 |
+
auto& tar_seq2grid = tar.seq2grid;
|
| 281 |
+
for (int i = 0; i < tar_seq2grid.size(); ++i) {
|
| 282 |
+
if (mapped_even_corners[i] == 1 && mapped_odd_corners[i] == 1)
|
| 283 |
+
continue;
|
| 284 |
+
auto k = tar_seq2grid[i];
|
| 285 |
+
float p[3];
|
| 286 |
+
key2cornerpos(k, tar.resolution, p);
|
| 287 |
+
|
| 288 |
+
int src_key = pos2key(p, src.resolution);
|
| 289 |
+
if (!src.grid2seq.count(src_key)) {
|
| 290 |
+
int seq = src.seq2grid.size();
|
| 291 |
+
src.grid2seq[src_key] = seq;
|
| 292 |
+
src.seq2evencorner.emplace_back((mapped_even_corners[i] == 0));
|
| 293 |
+
src.seq2oddcorner.emplace_back((mapped_odd_corners[i] == 0));
|
| 294 |
+
src.seq2grid.emplace_back(src_key);
|
| 295 |
+
src.seq2normal.emplace_back(tar_seq2normal[i]);
|
| 296 |
+
FetchNeighbor(src, seq, p, tar_seq2normal[i], 0, view_layer_positions, indices);
|
| 297 |
+
for (int j = 0; j < 9; ++j) {
|
| 298 |
+
src.seq2neighbor.emplace_back(indices[j]);
|
| 299 |
+
}
|
| 300 |
+
src.downsample_seq.emplace_back(i);
|
| 301 |
+
} else {
|
| 302 |
+
int seq = src.grid2seq[src_key];
|
| 303 |
+
if (mapped_even_corners[i] == 0)
|
| 304 |
+
src.seq2evencorner[seq] = 1;
|
| 305 |
+
if (mapped_odd_corners[i] == 0)
|
| 306 |
+
src.seq2oddcorner[seq] = 1;
|
| 307 |
+
}
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
std::vector<std::vector<torch::Tensor>> build_hierarchy(std::vector<torch::Tensor> view_layer_positions,
|
| 312 |
+
std::vector<torch::Tensor> view_layer_normals, int num_level, int resolution)
|
| 313 |
+
{
|
| 314 |
+
if (view_layer_positions.size() != 3 || num_level < 1) {
|
| 315 |
+
printf("Alert! We require 3 layers and at least 1 level! (%d %d)\n", view_layer_positions.size(), num_level);
|
| 316 |
+
return {{},{},{},{}};
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
std::vector<Grid> grids;
|
| 320 |
+
grids.resize(num_level);
|
| 321 |
+
|
| 322 |
+
std::vector<float> seq2pos;
|
| 323 |
+
auto& seq2grid = grids[0].seq2grid;
|
| 324 |
+
auto& seq2normal = grids[0].seq2normal;
|
| 325 |
+
auto& grid2seq = grids[0].grid2seq;
|
| 326 |
+
grids[0].resolution = resolution;
|
| 327 |
+
grids[0].stride = 1;
|
| 328 |
+
|
| 329 |
+
auto int64_options = torch::TensorOptions().dtype(torch::kInt64).requires_grad(false);
|
| 330 |
+
auto float_options = torch::TensorOptions().dtype(torch::kFloat32).requires_grad(false);
|
| 331 |
+
|
| 332 |
+
for (int v = 0; v < 3; ++v) {
|
| 333 |
+
int num_layers = view_layer_positions[v].size(0);
|
| 334 |
+
int height = view_layer_positions[v].size(1);
|
| 335 |
+
int width = view_layer_positions[v].size(2);
|
| 336 |
+
float* data = view_layer_positions[v].data_ptr<float>();
|
| 337 |
+
float* data_normal = view_layer_normals[v].data_ptr<float>();
|
| 338 |
+
for (int l = 0; l < num_layers; ++l) {
|
| 339 |
+
for (int i = 0; i < height; ++i) {
|
| 340 |
+
for (int j = 0; j < width; ++j) {
|
| 341 |
+
float* p = &data[(i * width + j) * 4];
|
| 342 |
+
float* n = &data_normal[(i * width + j) * 3];
|
| 343 |
+
if (p[3] == 0)
|
| 344 |
+
continue;
|
| 345 |
+
auto k = pos2key(p, resolution);
|
| 346 |
+
if (!grid2seq.count(k)) {
|
| 347 |
+
int dim = 0;
|
| 348 |
+
for (int d = 0; d < 3; ++d) {
|
| 349 |
+
if (std::abs(n[d]) > std::abs(n[dim]))
|
| 350 |
+
dim = d;
|
| 351 |
+
}
|
| 352 |
+
dim = (dim + 1) % 3;
|
| 353 |
+
grid2seq[k] = seq2grid.size();
|
| 354 |
+
seq2grid.emplace_back(k);
|
| 355 |
+
seq2pos.push_back(p[0]);
|
| 356 |
+
seq2pos.push_back(p[1]);
|
| 357 |
+
seq2pos.push_back(p[2]);
|
| 358 |
+
seq2normal.emplace_back(dim);
|
| 359 |
+
}
|
| 360 |
+
}
|
| 361 |
+
}
|
| 362 |
+
data += (height * width * 4);
|
| 363 |
+
data_normal += (height * width * 3);
|
| 364 |
+
}
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
for (int i = 0; i < num_level - 1; ++i) {
|
| 368 |
+
DownsampleGrid(grids[i], grids[i + 1]);
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
for (int l = 0; l < num_level; ++l) {
|
| 372 |
+
grids[l].seq2neighbor.resize(grids[l].seq2grid.size() * 9, -1);
|
| 373 |
+
grids[l].num_origin_seq = grids[l].seq2grid.size();
|
| 374 |
+
for (int d = 0; d < 3; ++d) {
|
| 375 |
+
NeighborGrid(grids[l], view_layer_positions, d);
|
| 376 |
+
}
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
for (int i = num_level - 2; i >= 0; --i) {
|
| 380 |
+
PadGrid(grids[i], grids[i + 1], view_layer_positions);
|
| 381 |
+
}
|
| 382 |
+
for (int i = grids[0].num_origin_seq; i < grids[0].seq2grid.size(); ++i) {
|
| 383 |
+
int k = grids[0].seq2grid[i];
|
| 384 |
+
float p[3];
|
| 385 |
+
key2pos(k, grids[0].resolution, p);
|
| 386 |
+
seq2pos.push_back(p[0]);
|
| 387 |
+
seq2pos.push_back(p[1]);
|
| 388 |
+
seq2pos.push_back(p[2]);
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
std::vector<torch::Tensor> texture_positions(2);
|
| 392 |
+
std::vector<torch::Tensor> grid_neighbors(grids.size());
|
| 393 |
+
std::vector<torch::Tensor> grid_downsamples(grids.size() - 1);
|
| 394 |
+
std::vector<torch::Tensor> grid_evencorners(grids.size());
|
| 395 |
+
std::vector<torch::Tensor> grid_oddcorners(grids.size());
|
| 396 |
+
|
| 397 |
+
texture_positions[0] = torch::zeros({static_cast<int64_t>(seq2pos.size() / 3), static_cast<int64_t>(3)}, float_options);
|
| 398 |
+
texture_positions[1] = torch::zeros({static_cast<int64_t>(seq2pos.size() / 3)}, float_options);
|
| 399 |
+
float* positions_out_ptr = texture_positions[0].data_ptr<float>();
|
| 400 |
+
memcpy(positions_out_ptr, seq2pos.data(), sizeof(float) * seq2pos.size());
|
| 401 |
+
positions_out_ptr = texture_positions[1].data_ptr<float>();
|
| 402 |
+
for (int i = 0; i < grids[0].seq2grid.size(); ++i) {
|
| 403 |
+
positions_out_ptr[i] = (i < grids[0].num_origin_seq);
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
for (int i = 0; i < grids.size(); ++i) {
|
| 407 |
+
grid_neighbors[i] = torch::zeros({static_cast<int64_t>(grids[i].seq2grid.size()), static_cast<int64_t>(9)}, int64_options);
|
| 408 |
+
int64_t* nptr = grid_neighbors[i].data_ptr<int64_t>();
|
| 409 |
+
for (int j = 0; j < grids[i].seq2neighbor.size(); ++j) {
|
| 410 |
+
nptr[j] = grids[i].seq2neighbor[j];
|
| 411 |
+
}
|
| 412 |
+
|
| 413 |
+
grid_evencorners[i] = torch::zeros({static_cast<int64_t>(grids[i].seq2evencorner.size())}, int64_options);
|
| 414 |
+
grid_oddcorners[i] = torch::zeros({static_cast<int64_t>(grids[i].seq2oddcorner.size())}, int64_options);
|
| 415 |
+
int64_t* dptr = grid_evencorners[i].data_ptr<int64_t>();
|
| 416 |
+
for (int j = 0; j < grids[i].seq2evencorner.size(); ++j) {
|
| 417 |
+
dptr[j] = grids[i].seq2evencorner[j];
|
| 418 |
+
}
|
| 419 |
+
dptr = grid_oddcorners[i].data_ptr<int64_t>();
|
| 420 |
+
for (int j = 0; j < grids[i].seq2oddcorner.size(); ++j) {
|
| 421 |
+
dptr[j] = grids[i].seq2oddcorner[j];
|
| 422 |
+
}
|
| 423 |
+
if (i + 1 < grids.size()) {
|
| 424 |
+
grid_downsamples[i] = torch::zeros({static_cast<int64_t>(grids[i].downsample_seq.size())}, int64_options);
|
| 425 |
+
int64_t* dptr = grid_downsamples[i].data_ptr<int64_t>();
|
| 426 |
+
for (int j = 0; j < grids[i].downsample_seq.size(); ++j) {
|
| 427 |
+
dptr[j] = grids[i].downsample_seq[j];
|
| 428 |
+
}
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
}
|
| 432 |
+
return {texture_positions, grid_neighbors, grid_downsamples, grid_evencorners, grid_oddcorners};
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
std::vector<std::vector<torch::Tensor>> build_hierarchy_with_feat(
|
| 436 |
+
std::vector<torch::Tensor> view_layer_positions,
|
| 437 |
+
std::vector<torch::Tensor> view_layer_normals,
|
| 438 |
+
std::vector<torch::Tensor> view_layer_feats,
|
| 439 |
+
int num_level, int resolution)
|
| 440 |
+
{
|
| 441 |
+
if (view_layer_positions.size() != 3 || num_level < 1) {
|
| 442 |
+
printf("Alert! We require 3 layers and at least 1 level! (%d %d)\n", view_layer_positions.size(), num_level);
|
| 443 |
+
return {{},{},{},{}};
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
std::vector<Grid> grids;
|
| 447 |
+
grids.resize(num_level);
|
| 448 |
+
|
| 449 |
+
std::vector<float> seq2pos;
|
| 450 |
+
std::vector<float> seq2feat;
|
| 451 |
+
auto& seq2grid = grids[0].seq2grid;
|
| 452 |
+
auto& seq2normal = grids[0].seq2normal;
|
| 453 |
+
auto& grid2seq = grids[0].grid2seq;
|
| 454 |
+
grids[0].resolution = resolution;
|
| 455 |
+
grids[0].stride = 1;
|
| 456 |
+
|
| 457 |
+
auto int64_options = torch::TensorOptions().dtype(torch::kInt64).requires_grad(false);
|
| 458 |
+
auto float_options = torch::TensorOptions().dtype(torch::kFloat32).requires_grad(false);
|
| 459 |
+
|
| 460 |
+
int feat_channel = 3;
|
| 461 |
+
for (int v = 0; v < 3; ++v) {
|
| 462 |
+
int num_layers = view_layer_positions[v].size(0);
|
| 463 |
+
int height = view_layer_positions[v].size(1);
|
| 464 |
+
int width = view_layer_positions[v].size(2);
|
| 465 |
+
float* data = view_layer_positions[v].data_ptr<float>();
|
| 466 |
+
float* data_normal = view_layer_normals[v].data_ptr<float>();
|
| 467 |
+
float* data_feat = view_layer_feats[v].data_ptr<float>();
|
| 468 |
+
feat_channel = view_layer_feats[v].size(3);
|
| 469 |
+
for (int l = 0; l < num_layers; ++l) {
|
| 470 |
+
for (int i = 0; i < height; ++i) {
|
| 471 |
+
for (int j = 0; j < width; ++j) {
|
| 472 |
+
float* p = &data[(i * width + j) * 4];
|
| 473 |
+
float* n = &data_normal[(i * width + j) * 3];
|
| 474 |
+
float* f = &data_feat[(i * width + j) * feat_channel];
|
| 475 |
+
if (p[3] == 0)
|
| 476 |
+
continue;
|
| 477 |
+
auto k = pos2key(p, resolution);
|
| 478 |
+
if (!grid2seq.count(k)) {
|
| 479 |
+
int dim = 0;
|
| 480 |
+
for (int d = 0; d < 3; ++d) {
|
| 481 |
+
if (std::abs(n[d]) > std::abs(n[dim]))
|
| 482 |
+
dim = d;
|
| 483 |
+
}
|
| 484 |
+
dim = (dim + 1) % 3;
|
| 485 |
+
grid2seq[k] = seq2grid.size();
|
| 486 |
+
seq2grid.emplace_back(k);
|
| 487 |
+
seq2pos.push_back(p[0]);
|
| 488 |
+
seq2pos.push_back(p[1]);
|
| 489 |
+
seq2pos.push_back(p[2]);
|
| 490 |
+
for (int c = 0; c < feat_channel; ++c) {
|
| 491 |
+
seq2feat.emplace_back(f[c]);
|
| 492 |
+
}
|
| 493 |
+
seq2normal.emplace_back(dim);
|
| 494 |
+
}
|
| 495 |
+
}
|
| 496 |
+
}
|
| 497 |
+
data += (height * width * 4);
|
| 498 |
+
data_normal += (height * width * 3);
|
| 499 |
+
data_feat += (height * width * feat_channel);
|
| 500 |
+
}
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
for (int i = 0; i < num_level - 1; ++i) {
|
| 504 |
+
DownsampleGrid(grids[i], grids[i + 1]);
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
for (int l = 0; l < num_level; ++l) {
|
| 508 |
+
grids[l].seq2neighbor.resize(grids[l].seq2grid.size() * 9, -1);
|
| 509 |
+
grids[l].num_origin_seq = grids[l].seq2grid.size();
|
| 510 |
+
for (int d = 0; d < 3; ++d) {
|
| 511 |
+
NeighborGrid(grids[l], view_layer_positions, d);
|
| 512 |
+
}
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
for (int i = num_level - 2; i >= 0; --i) {
|
| 516 |
+
PadGrid(grids[i], grids[i + 1], view_layer_positions);
|
| 517 |
+
}
|
| 518 |
+
for (int i = grids[0].num_origin_seq; i < grids[0].seq2grid.size(); ++i) {
|
| 519 |
+
int k = grids[0].seq2grid[i];
|
| 520 |
+
float p[3];
|
| 521 |
+
key2pos(k, grids[0].resolution, p);
|
| 522 |
+
seq2pos.push_back(p[0]);
|
| 523 |
+
seq2pos.push_back(p[1]);
|
| 524 |
+
seq2pos.push_back(p[2]);
|
| 525 |
+
for (int c = 0; c < feat_channel; ++c) {
|
| 526 |
+
seq2feat.emplace_back(0.5);
|
| 527 |
+
}
|
| 528 |
+
}
|
| 529 |
+
|
| 530 |
+
std::vector<torch::Tensor> texture_positions(2);
|
| 531 |
+
std::vector<torch::Tensor> texture_feats(1);
|
| 532 |
+
std::vector<torch::Tensor> grid_neighbors(grids.size());
|
| 533 |
+
std::vector<torch::Tensor> grid_downsamples(grids.size() - 1);
|
| 534 |
+
std::vector<torch::Tensor> grid_evencorners(grids.size());
|
| 535 |
+
std::vector<torch::Tensor> grid_oddcorners(grids.size());
|
| 536 |
+
|
| 537 |
+
texture_positions[0] = torch::zeros({static_cast<int64_t>(seq2pos.size() / 3), static_cast<int64_t>(3)}, float_options);
|
| 538 |
+
texture_positions[1] = torch::zeros({static_cast<int64_t>(seq2pos.size() / 3)}, float_options);
|
| 539 |
+
texture_feats[0] = torch::zeros({static_cast<int64_t>(seq2feat.size() / feat_channel), static_cast<int64_t>(feat_channel)}, float_options);
|
| 540 |
+
float* positions_out_ptr = texture_positions[0].data_ptr<float>();
|
| 541 |
+
memcpy(positions_out_ptr, seq2pos.data(), sizeof(float) * seq2pos.size());
|
| 542 |
+
positions_out_ptr = texture_positions[1].data_ptr<float>();
|
| 543 |
+
for (int i = 0; i < grids[0].seq2grid.size(); ++i) {
|
| 544 |
+
positions_out_ptr[i] = (i < grids[0].num_origin_seq);
|
| 545 |
+
}
|
| 546 |
+
float* feats_out_ptr = texture_feats[0].data_ptr<float>();
|
| 547 |
+
memcpy(feats_out_ptr, seq2feat.data(), sizeof(float) * seq2feat.size());
|
| 548 |
+
|
| 549 |
+
for (int i = 0; i < grids.size(); ++i) {
|
| 550 |
+
grid_neighbors[i] = torch::zeros({static_cast<int64_t>(grids[i].seq2grid.size()), static_cast<int64_t>(9)}, int64_options);
|
| 551 |
+
int64_t* nptr = grid_neighbors[i].data_ptr<int64_t>();
|
| 552 |
+
for (int j = 0; j < grids[i].seq2neighbor.size(); ++j) {
|
| 553 |
+
nptr[j] = grids[i].seq2neighbor[j];
|
| 554 |
+
}
|
| 555 |
+
grid_evencorners[i] = torch::zeros({static_cast<int64_t>(grids[i].seq2evencorner.size())}, int64_options);
|
| 556 |
+
grid_oddcorners[i] = torch::zeros({static_cast<int64_t>(grids[i].seq2oddcorner.size())}, int64_options);
|
| 557 |
+
int64_t* dptr = grid_evencorners[i].data_ptr<int64_t>();
|
| 558 |
+
for (int j = 0; j < grids[i].seq2evencorner.size(); ++j) {
|
| 559 |
+
dptr[j] = grids[i].seq2evencorner[j];
|
| 560 |
+
}
|
| 561 |
+
dptr = grid_oddcorners[i].data_ptr<int64_t>();
|
| 562 |
+
for (int j = 0; j < grids[i].seq2oddcorner.size(); ++j) {
|
| 563 |
+
dptr[j] = grids[i].seq2oddcorner[j];
|
| 564 |
+
}
|
| 565 |
+
if (i + 1 < grids.size()) {
|
| 566 |
+
grid_downsamples[i] = torch::zeros({static_cast<int64_t>(grids[i].downsample_seq.size())}, int64_options);
|
| 567 |
+
int64_t* dptr = grid_downsamples[i].data_ptr<int64_t>();
|
| 568 |
+
for (int j = 0; j < grids[i].downsample_seq.size(); ++j) {
|
| 569 |
+
dptr[j] = grids[i].downsample_seq[j];
|
| 570 |
+
}
|
| 571 |
+
}
|
| 572 |
+
}
|
| 573 |
+
return {texture_positions, texture_feats, grid_neighbors, grid_downsamples, grid_evencorners, grid_oddcorners};
|
| 574 |
+
}
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.cpp
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "rasterizer.h"
|
| 2 |
+
|
| 3 |
+
void rasterizeTriangleCPU(int idx, float* vt0, float* vt1, float* vt2, int width, int height, INT64* zbuffer, float* d, float occlusion_truncation) {
|
| 4 |
+
float x_min = std::min(vt0[0], std::min(vt1[0],vt2[0]));
|
| 5 |
+
float x_max = std::max(vt0[0], std::max(vt1[0],vt2[0]));
|
| 6 |
+
float y_min = std::min(vt0[1], std::min(vt1[1],vt2[1]));
|
| 7 |
+
float y_max = std::max(vt0[1], std::max(vt1[1],vt2[1]));
|
| 8 |
+
|
| 9 |
+
for (int px = x_min; px < x_max + 1; ++px) {
|
| 10 |
+
if (px < 0 || px >= width)
|
| 11 |
+
continue;
|
| 12 |
+
for (int py = y_min; py < y_max + 1; ++py) {
|
| 13 |
+
if (py < 0 || py >= height)
|
| 14 |
+
continue;
|
| 15 |
+
float vt[2] = {px + 0.5, py + 0.5};
|
| 16 |
+
float baryCentricCoordinate[3];
|
| 17 |
+
calculateBarycentricCoordinate(vt0, vt1, vt2, vt, baryCentricCoordinate);
|
| 18 |
+
if (isBarycentricCoordInBounds(baryCentricCoordinate)) {
|
| 19 |
+
int pixel = py * width + px;
|
| 20 |
+
if (zbuffer == 0) {
|
| 21 |
+
zbuffer[pixel] = (INT64)(idx + 1);
|
| 22 |
+
continue;
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
float depth = baryCentricCoordinate[0] * vt0[2] + baryCentricCoordinate[1] * vt1[2] + baryCentricCoordinate[2] * vt2[2];
|
| 26 |
+
float depth_thres = 0;
|
| 27 |
+
if (d) {
|
| 28 |
+
depth_thres = d[pixel] * 0.49999f + 0.5f + occlusion_truncation;
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
int z_quantize = depth * (2<<17);
|
| 32 |
+
INT64 token = (INT64)z_quantize * MAXINT + (INT64)(idx + 1);
|
| 33 |
+
if (depth < depth_thres)
|
| 34 |
+
continue;
|
| 35 |
+
zbuffer[pixel] = std::min(zbuffer[pixel], token);
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
void barycentricFromImgcoordCPU(float* V, int* F, int* findices, INT64* zbuffer, int width, int height, int num_vertices, int num_faces,
|
| 42 |
+
float* barycentric_map, int pix)
|
| 43 |
+
{
|
| 44 |
+
INT64 f = zbuffer[pix] % MAXINT;
|
| 45 |
+
if (f == (MAXINT-1)) {
|
| 46 |
+
findices[pix] = 0;
|
| 47 |
+
barycentric_map[pix * 3] = 0;
|
| 48 |
+
barycentric_map[pix * 3 + 1] = 0;
|
| 49 |
+
barycentric_map[pix * 3 + 2] = 0;
|
| 50 |
+
return;
|
| 51 |
+
}
|
| 52 |
+
findices[pix] = f;
|
| 53 |
+
f -= 1;
|
| 54 |
+
float barycentric[3] = {0, 0, 0};
|
| 55 |
+
if (f >= 0) {
|
| 56 |
+
float vt[2] = {float(pix % width) + 0.5f, float(pix / width) + 0.5f};
|
| 57 |
+
float* vt0_ptr = V + (F[f * 3] * 4);
|
| 58 |
+
float* vt1_ptr = V + (F[f * 3 + 1] * 4);
|
| 59 |
+
float* vt2_ptr = V + (F[f * 3 + 2] * 4);
|
| 60 |
+
|
| 61 |
+
float vt0[2] = {(vt0_ptr[0] / vt0_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt0_ptr[1] / vt0_ptr[3]) * (height - 1) + 0.5f};
|
| 62 |
+
float vt1[2] = {(vt1_ptr[0] / vt1_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt1_ptr[1] / vt1_ptr[3]) * (height - 1) + 0.5f};
|
| 63 |
+
float vt2[2] = {(vt2_ptr[0] / vt2_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt2_ptr[1] / vt2_ptr[3]) * (height - 1) + 0.5f};
|
| 64 |
+
|
| 65 |
+
calculateBarycentricCoordinate(vt0, vt1, vt2, vt, barycentric);
|
| 66 |
+
|
| 67 |
+
barycentric[0] = barycentric[0] / vt0_ptr[3];
|
| 68 |
+
barycentric[1] = barycentric[1] / vt1_ptr[3];
|
| 69 |
+
barycentric[2] = barycentric[2] / vt2_ptr[3];
|
| 70 |
+
float w = 1.0f / (barycentric[0] + barycentric[1] + barycentric[2]);
|
| 71 |
+
barycentric[0] *= w;
|
| 72 |
+
barycentric[1] *= w;
|
| 73 |
+
barycentric[2] *= w;
|
| 74 |
+
|
| 75 |
+
}
|
| 76 |
+
barycentric_map[pix * 3] = barycentric[0];
|
| 77 |
+
barycentric_map[pix * 3 + 1] = barycentric[1];
|
| 78 |
+
barycentric_map[pix * 3 + 2] = barycentric[2];
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
void rasterizeImagecoordsKernelCPU(float* V, int* F, float* d, INT64* zbuffer, float occlusion_trunc, int width, int height, int num_vertices, int num_faces, int f)
|
| 82 |
+
{
|
| 83 |
+
float* vt0_ptr = V + (F[f * 3] * 4);
|
| 84 |
+
float* vt1_ptr = V + (F[f * 3 + 1] * 4);
|
| 85 |
+
float* vt2_ptr = V + (F[f * 3 + 2] * 4);
|
| 86 |
+
|
| 87 |
+
float vt0[3] = {(vt0_ptr[0] / vt0_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt0_ptr[1] / vt0_ptr[3]) * (height - 1) + 0.5f, vt0_ptr[2] / vt0_ptr[3] * 0.49999f + 0.5f};
|
| 88 |
+
float vt1[3] = {(vt1_ptr[0] / vt1_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt1_ptr[1] / vt1_ptr[3]) * (height - 1) + 0.5f, vt1_ptr[2] / vt1_ptr[3] * 0.49999f + 0.5f};
|
| 89 |
+
float vt2[3] = {(vt2_ptr[0] / vt2_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt2_ptr[1] / vt2_ptr[3]) * (height - 1) + 0.5f, vt2_ptr[2] / vt2_ptr[3] * 0.49999f + 0.5f};
|
| 90 |
+
|
| 91 |
+
rasterizeTriangleCPU(f, vt0, vt1, vt2, width, height, zbuffer, d, occlusion_trunc);
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
std::vector<torch::Tensor> rasterize_image_cpu(torch::Tensor V, torch::Tensor F, torch::Tensor D,
|
| 95 |
+
int width, int height, float occlusion_truncation, int use_depth_prior)
|
| 96 |
+
{
|
| 97 |
+
int num_faces = F.size(0);
|
| 98 |
+
int num_vertices = V.size(0);
|
| 99 |
+
auto options = torch::TensorOptions().dtype(torch::kInt32).requires_grad(false);
|
| 100 |
+
auto INT64_options = torch::TensorOptions().dtype(torch::kInt64).requires_grad(false);
|
| 101 |
+
auto findices = torch::zeros({height, width}, options);
|
| 102 |
+
INT64 maxint = (INT64)MAXINT * (INT64)MAXINT + (MAXINT - 1);
|
| 103 |
+
auto z_min = torch::ones({height, width}, INT64_options) * (int64_t)maxint;
|
| 104 |
+
|
| 105 |
+
if (!use_depth_prior) {
|
| 106 |
+
for (int i = 0; i < num_faces; ++i) {
|
| 107 |
+
rasterizeImagecoordsKernelCPU(V.data_ptr<float>(), F.data_ptr<int>(), 0,
|
| 108 |
+
(INT64*)z_min.data_ptr<int64_t>(), occlusion_truncation, width, height, num_vertices, num_faces, i);
|
| 109 |
+
}
|
| 110 |
+
} else {
|
| 111 |
+
for (int i = 0; i < num_faces; ++i)
|
| 112 |
+
rasterizeImagecoordsKernelCPU(V.data_ptr<float>(), F.data_ptr<int>(), D.data_ptr<float>(),
|
| 113 |
+
(INT64*)z_min.data_ptr<int64_t>(), occlusion_truncation, width, height, num_vertices, num_faces, i);
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
auto float_options = torch::TensorOptions().dtype(torch::kFloat32).requires_grad(false);
|
| 117 |
+
auto barycentric = torch::zeros({height, width, 3}, float_options);
|
| 118 |
+
for (int i = 0; i < width * height; ++i)
|
| 119 |
+
barycentricFromImgcoordCPU(V.data_ptr<float>(), F.data_ptr<int>(),
|
| 120 |
+
findices.data_ptr<int>(), (INT64*)z_min.data_ptr<int64_t>(), width, height, num_vertices, num_faces, barycentric.data_ptr<float>(), i);
|
| 121 |
+
|
| 122 |
+
return {findices, barycentric};
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
std::vector<torch::Tensor> rasterize_image(torch::Tensor V, torch::Tensor F, torch::Tensor D,
|
| 126 |
+
int width, int height, float occlusion_truncation, int use_depth_prior)
|
| 127 |
+
{
|
| 128 |
+
int device_id = V.get_device();
|
| 129 |
+
if (device_id == -1)
|
| 130 |
+
return rasterize_image_cpu(V, F, D, width, height, occlusion_truncation, use_depth_prior);
|
| 131 |
+
else
|
| 132 |
+
return rasterize_image_gpu(V, F, D, width, height, occlusion_truncation, use_depth_prior);
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
| 136 |
+
m.def("rasterize_image", &rasterize_image, "Custom image rasterization");
|
| 137 |
+
m.def("build_hierarchy", &build_hierarchy, "Custom image rasterization");
|
| 138 |
+
m.def("build_hierarchy_with_feat", &build_hierarchy_with_feat, "Custom image rasterization");
|
| 139 |
+
}
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer.h
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#ifndef RASTERIZER_H_
|
| 2 |
+
#define RASTERIZER_H_
|
| 3 |
+
|
| 4 |
+
#include <torch/extension.h>
|
| 5 |
+
#include <vector>
|
| 6 |
+
#include <ATen/ATen.h>
|
| 7 |
+
#include <ATen/cuda/CUDAContext.h> // For CUDA context
|
| 8 |
+
|
| 9 |
+
#define INT64 unsigned long long
|
| 10 |
+
#define MAXINT 2147483647
|
| 11 |
+
|
| 12 |
+
__host__ __device__ inline float calculateSignedArea2(float* a, float* b, float* c) {
|
| 13 |
+
return ((c[0] - a[0]) * (b[1] - a[1]) - (b[0] - a[0]) * (c[1] - a[1]));
|
| 14 |
+
}
|
| 15 |
+
|
| 16 |
+
__host__ __device__ inline void calculateBarycentricCoordinate(float* a, float* b, float* c, float* p,
|
| 17 |
+
float* barycentric)
|
| 18 |
+
{
|
| 19 |
+
float beta_tri = calculateSignedArea2(a, p, c);
|
| 20 |
+
float gamma_tri = calculateSignedArea2(a, b, p);
|
| 21 |
+
float area = calculateSignedArea2(a, b, c);
|
| 22 |
+
if (area == 0) {
|
| 23 |
+
barycentric[0] = -1.0;
|
| 24 |
+
barycentric[1] = -1.0;
|
| 25 |
+
barycentric[2] = -1.0;
|
| 26 |
+
return;
|
| 27 |
+
}
|
| 28 |
+
float tri_inv = 1.0 / area;
|
| 29 |
+
float beta = beta_tri * tri_inv;
|
| 30 |
+
float gamma = gamma_tri * tri_inv;
|
| 31 |
+
float alpha = 1.0 - beta - gamma;
|
| 32 |
+
barycentric[0] = alpha;
|
| 33 |
+
barycentric[1] = beta;
|
| 34 |
+
barycentric[2] = gamma;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
__host__ __device__ inline bool isBarycentricCoordInBounds(float* barycentricCoord) {
|
| 38 |
+
return barycentricCoord[0] >= 0.0 && barycentricCoord[0] <= 1.0 &&
|
| 39 |
+
barycentricCoord[1] >= 0.0 && barycentricCoord[1] <= 1.0 &&
|
| 40 |
+
barycentricCoord[2] >= 0.0 && barycentricCoord[2] <= 1.0;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
std::vector<torch::Tensor> rasterize_image_gpu(torch::Tensor V, torch::Tensor F, torch::Tensor D,
|
| 44 |
+
int width, int height, float occlusion_truncation, int use_depth_prior);
|
| 45 |
+
|
| 46 |
+
std::vector<std::vector<torch::Tensor>> build_hierarchy(std::vector<torch::Tensor> view_layer_positions, std::vector<torch::Tensor> view_layer_normals, int num_level, int resolution);
|
| 47 |
+
|
| 48 |
+
std::vector<std::vector<torch::Tensor>> build_hierarchy_with_feat(
|
| 49 |
+
std::vector<torch::Tensor> view_layer_positions,
|
| 50 |
+
std::vector<torch::Tensor> view_layer_normals,
|
| 51 |
+
std::vector<torch::Tensor> view_layer_feats,
|
| 52 |
+
int num_level, int resolution);
|
| 53 |
+
|
| 54 |
+
#endif
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/lib/custom_rasterizer_kernel/rasterizer_gpu.cu
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#include "rasterizer.h"
|
| 2 |
+
|
| 3 |
+
__device__ void rasterizeTriangleGPU(int idx, float* vt0, float* vt1, float* vt2, int width, int height, INT64* zbuffer, float* d, float occlusion_truncation) {
|
| 4 |
+
float x_min = std::min(vt0[0], std::min(vt1[0],vt2[0]));
|
| 5 |
+
float x_max = std::max(vt0[0], std::max(vt1[0],vt2[0]));
|
| 6 |
+
float y_min = std::min(vt0[1], std::min(vt1[1],vt2[1]));
|
| 7 |
+
float y_max = std::max(vt0[1], std::max(vt1[1],vt2[1]));
|
| 8 |
+
|
| 9 |
+
for (int px = x_min; px < x_max + 1; ++px) {
|
| 10 |
+
if (px < 0 || px >= width)
|
| 11 |
+
continue;
|
| 12 |
+
for (int py = y_min; py < y_max + 1; ++py) {
|
| 13 |
+
if (py < 0 || py >= height)
|
| 14 |
+
continue;
|
| 15 |
+
float vt[2] = {px + 0.5f, py + 0.5f};
|
| 16 |
+
float baryCentricCoordinate[3];
|
| 17 |
+
calculateBarycentricCoordinate(vt0, vt1, vt2, vt, baryCentricCoordinate);
|
| 18 |
+
if (isBarycentricCoordInBounds(baryCentricCoordinate)) {
|
| 19 |
+
int pixel = py * width + px;
|
| 20 |
+
if (zbuffer == 0) {
|
| 21 |
+
atomicExch(&zbuffer[pixel], (INT64)(idx + 1));
|
| 22 |
+
continue;
|
| 23 |
+
}
|
| 24 |
+
float depth = baryCentricCoordinate[0] * vt0[2] + baryCentricCoordinate[1] * vt1[2] + baryCentricCoordinate[2] * vt2[2];
|
| 25 |
+
float depth_thres = 0;
|
| 26 |
+
if (d) {
|
| 27 |
+
depth_thres = d[pixel] * 0.49999f + 0.5f + occlusion_truncation;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
int z_quantize = depth * (2<<17);
|
| 31 |
+
INT64 token = (INT64)z_quantize * MAXINT + (INT64)(idx + 1);
|
| 32 |
+
if (depth < depth_thres)
|
| 33 |
+
continue;
|
| 34 |
+
atomicMin(&zbuffer[pixel], token);
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
__global__ void barycentricFromImgcoordGPU(float* V, int* F, int* findices, INT64* zbuffer, int width, int height, int num_vertices, int num_faces,
|
| 41 |
+
float* barycentric_map)
|
| 42 |
+
{
|
| 43 |
+
int pix = blockIdx.x * blockDim.x + threadIdx.x;
|
| 44 |
+
if (pix >= width * height)
|
| 45 |
+
return;
|
| 46 |
+
INT64 f = zbuffer[pix] % MAXINT;
|
| 47 |
+
if (f == (MAXINT-1)) {
|
| 48 |
+
findices[pix] = 0;
|
| 49 |
+
barycentric_map[pix * 3] = 0;
|
| 50 |
+
barycentric_map[pix * 3 + 1] = 0;
|
| 51 |
+
barycentric_map[pix * 3 + 2] = 0;
|
| 52 |
+
return;
|
| 53 |
+
}
|
| 54 |
+
findices[pix] = f;
|
| 55 |
+
f -= 1;
|
| 56 |
+
float barycentric[3] = {0, 0, 0};
|
| 57 |
+
if (f >= 0) {
|
| 58 |
+
float vt[2] = {float(pix % width) + 0.5f, float(pix / width) + 0.5f};
|
| 59 |
+
float* vt0_ptr = V + (F[f * 3] * 4);
|
| 60 |
+
float* vt1_ptr = V + (F[f * 3 + 1] * 4);
|
| 61 |
+
float* vt2_ptr = V + (F[f * 3 + 2] * 4);
|
| 62 |
+
|
| 63 |
+
float vt0[2] = {(vt0_ptr[0] / vt0_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt0_ptr[1] / vt0_ptr[3]) * (height - 1) + 0.5f};
|
| 64 |
+
float vt1[2] = {(vt1_ptr[0] / vt1_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt1_ptr[1] / vt1_ptr[3]) * (height - 1) + 0.5f};
|
| 65 |
+
float vt2[2] = {(vt2_ptr[0] / vt2_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt2_ptr[1] / vt2_ptr[3]) * (height - 1) + 0.5f};
|
| 66 |
+
|
| 67 |
+
calculateBarycentricCoordinate(vt0, vt1, vt2, vt, barycentric);
|
| 68 |
+
|
| 69 |
+
barycentric[0] = barycentric[0] / vt0_ptr[3];
|
| 70 |
+
barycentric[1] = barycentric[1] / vt1_ptr[3];
|
| 71 |
+
barycentric[2] = barycentric[2] / vt2_ptr[3];
|
| 72 |
+
float w = 1.0f / (barycentric[0] + barycentric[1] + barycentric[2]);
|
| 73 |
+
barycentric[0] *= w;
|
| 74 |
+
barycentric[1] *= w;
|
| 75 |
+
barycentric[2] *= w;
|
| 76 |
+
|
| 77 |
+
}
|
| 78 |
+
barycentric_map[pix * 3] = barycentric[0];
|
| 79 |
+
barycentric_map[pix * 3 + 1] = barycentric[1];
|
| 80 |
+
barycentric_map[pix * 3 + 2] = barycentric[2];
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
__global__ void rasterizeImagecoordsKernelGPU(float* V, int* F, float* d, INT64* zbuffer, float occlusion_trunc, int width, int height, int num_vertices, int num_faces)
|
| 84 |
+
{
|
| 85 |
+
int f = blockIdx.x * blockDim.x + threadIdx.x;
|
| 86 |
+
if (f >= num_faces)
|
| 87 |
+
return;
|
| 88 |
+
|
| 89 |
+
float* vt0_ptr = V + (F[f * 3] * 4);
|
| 90 |
+
float* vt1_ptr = V + (F[f * 3 + 1] * 4);
|
| 91 |
+
float* vt2_ptr = V + (F[f * 3 + 2] * 4);
|
| 92 |
+
|
| 93 |
+
float vt0[3] = {(vt0_ptr[0] / vt0_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt0_ptr[1] / vt0_ptr[3]) * (height - 1) + 0.5f, vt0_ptr[2] / vt0_ptr[3] * 0.49999f + 0.5f};
|
| 94 |
+
float vt1[3] = {(vt1_ptr[0] / vt1_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt1_ptr[1] / vt1_ptr[3]) * (height - 1) + 0.5f, vt1_ptr[2] / vt1_ptr[3] * 0.49999f + 0.5f};
|
| 95 |
+
float vt2[3] = {(vt2_ptr[0] / vt2_ptr[3] * 0.5f + 0.5f) * (width - 1) + 0.5f, (0.5f + 0.5f * vt2_ptr[1] / vt2_ptr[3]) * (height - 1) + 0.5f, vt2_ptr[2] / vt2_ptr[3] * 0.49999f + 0.5f};
|
| 96 |
+
|
| 97 |
+
rasterizeTriangleGPU(f, vt0, vt1, vt2, width, height, zbuffer, d, occlusion_trunc);
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
std::vector<torch::Tensor> rasterize_image_gpu(torch::Tensor V, torch::Tensor F, torch::Tensor D,
|
| 101 |
+
int width, int height, float occlusion_truncation, int use_depth_prior)
|
| 102 |
+
{
|
| 103 |
+
int device_id = V.get_device();
|
| 104 |
+
cudaSetDevice(device_id);
|
| 105 |
+
int num_faces = F.size(0);
|
| 106 |
+
int num_vertices = V.size(0);
|
| 107 |
+
auto options = torch::TensorOptions().dtype(torch::kInt32).device(torch::kCUDA, device_id).requires_grad(false);
|
| 108 |
+
auto INT64_options = torch::TensorOptions().dtype(torch::kInt64).device(torch::kCUDA, device_id).requires_grad(false);
|
| 109 |
+
auto findices = torch::zeros({height, width}, options);
|
| 110 |
+
INT64 maxint = (INT64)MAXINT * (INT64)MAXINT + (MAXINT - 1);
|
| 111 |
+
auto z_min = torch::ones({height, width}, INT64_options) * (int64_t)maxint;
|
| 112 |
+
|
| 113 |
+
if (!use_depth_prior) {
|
| 114 |
+
rasterizeImagecoordsKernelGPU<<<(num_faces+255)/256,256,0,at::cuda::getCurrentCUDAStream()>>>(V.data_ptr<float>(), F.data_ptr<int>(), 0,
|
| 115 |
+
(INT64*)z_min.data_ptr<int64_t>(), occlusion_truncation, width, height, num_vertices, num_faces);
|
| 116 |
+
} else {
|
| 117 |
+
rasterizeImagecoordsKernelGPU<<<(num_faces+255)/256,256,0,at::cuda::getCurrentCUDAStream()>>>(V.data_ptr<float>(), F.data_ptr<int>(), D.data_ptr<float>(),
|
| 118 |
+
(INT64*)z_min.data_ptr<int64_t>(), occlusion_truncation, width, height, num_vertices, num_faces);
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
auto float_options = torch::TensorOptions().dtype(torch::kFloat32).device(torch::kCUDA, device_id).requires_grad(false);
|
| 122 |
+
auto barycentric = torch::zeros({height, width, 3}, float_options);
|
| 123 |
+
barycentricFromImgcoordGPU<<<(width * height + 255)/256, 256>>>(V.data_ptr<float>(), F.data_ptr<int>(),
|
| 124 |
+
findices.data_ptr<int>(), (INT64*)z_min.data_ptr<int64_t>(), width, height, num_vertices, num_faces, barycentric.data_ptr<float>());
|
| 125 |
+
|
| 126 |
+
return {findices, barycentric};
|
| 127 |
+
}
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/setup.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from setuptools import setup, find_packages
|
| 2 |
+
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
|
| 3 |
+
|
| 4 |
+
# build custom rasterizer
|
| 5 |
+
# build with `python setup.py install`
|
| 6 |
+
# nvcc is needed
|
| 7 |
+
|
| 8 |
+
custom_rasterizer_module = CUDAExtension('custom_rasterizer_kernel', [
|
| 9 |
+
'lib/custom_rasterizer_kernel/rasterizer.cpp',
|
| 10 |
+
'lib/custom_rasterizer_kernel/grid_neighbor.cpp',
|
| 11 |
+
'lib/custom_rasterizer_kernel/rasterizer_gpu.cu',
|
| 12 |
+
])
|
| 13 |
+
|
| 14 |
+
setup(
|
| 15 |
+
packages=find_packages(),
|
| 16 |
+
version='0.1',
|
| 17 |
+
name='custom_rasterizer',
|
| 18 |
+
include_package_data=True,
|
| 19 |
+
package_dir={'': '.'},
|
| 20 |
+
ext_modules=[
|
| 21 |
+
custom_rasterizer_module,
|
| 22 |
+
],
|
| 23 |
+
cmdclass={
|
| 24 |
+
'build_ext': BuildExtension
|
| 25 |
+
}
|
| 26 |
+
)
|
OVOW/third_party/Motion324/scripts/hy3dgen/texgen/custom_rasterizer/setup.py.hy3d
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from setuptools import setup, find_packages
|
| 2 |
+
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
|
| 3 |
+
|
| 4 |
+
# build custom rasterizer
|
| 5 |
+
# build with `python setup.py install`
|
| 6 |
+
# nvcc is needed
|
| 7 |
+
|
| 8 |
+
custom_rasterizer_module = CUDAExtension('custom_rasterizer_kernel', [
|
| 9 |
+
'lib/custom_rasterizer_kernel/rasterizer.cpp',
|
| 10 |
+
'lib/custom_rasterizer_kernel/grid_neighbor.cpp',
|
| 11 |
+
'lib/custom_rasterizer_kernel/rasterizer_gpu.cu',
|
| 12 |
+
])
|
| 13 |
+
|
| 14 |
+
setup(
|
| 15 |
+
packages=find_packages(),
|
| 16 |
+
version='0.1',
|
| 17 |
+
name='custom_rasterizer',
|
| 18 |
+
include_package_data=True,
|
| 19 |
+
package_dir={'': '.'},
|
| 20 |
+
ext_modules=[
|
| 21 |
+
custom_rasterizer_module,
|
| 22 |
+
],
|
| 23 |
+
cmdclass={
|
| 24 |
+
'build_ext': BuildExtension
|
| 25 |
+
}
|
| 26 |
+
)
|