Add files using upload-large-folder tool
Browse files- upstream/CoDA/coda/model/common_utils/scheduler.py +29 -0
- upstream/CoDA/coda/model/diff/__pycache__/diffusion_pl.cpython-310.pyc +0 -0
- upstream/CoDA/coda/model/diff/callbacks/metric_arctic.py +435 -0
- upstream/CoDA/coda/model/diff/callbacks/metric_grab.py +400 -0
- upstream/CoDA/coda/model/diff/callbacks/utils.py +53 -0
- upstream/CoDA/coda/model/diff/pipeline/bps_pipeline.py +160 -0
- upstream/CoDA/coda/model/diff/pipeline/mini_pipeline.py +283 -0
- upstream/CoDA/coda/model/diff/pipeline/text_pipeline.py +172 -0
- upstream/CoDA/coda/model/diff/pipeline/wholebodypartobj_pipeline.py +1313 -0
- upstream/CoDA/coda/model/diff/utils/__pycache__/motion3d_endecoder.cpython-310.pyc +0 -0
- upstream/CoDA/coda/model/diff/utils/__pycache__/optimization.cpython-310.pyc +0 -0
- upstream/CoDA/coda/model/diff/utils/metric_endecoder.py +320 -0
- upstream/CoDA/coda/model/diff/utils/optimization.py +505 -0
- upstream/CoDA/coda/model/diff/utils/stats_compose.py +0 -0
- upstream/CoDA/coda/network/base_arch/embeddings/cape.py +144 -0
- upstream/CoDA/coda/network/base_arch/transformer/__pycache__/layer.cpython-310.pyc +0 -0
- upstream/CoDA/coda/network/base_arch/transformer/encoder_trajrope.py +189 -0
- upstream/CoDA/coda/network/base_arch/transformer/layer.py +18 -0
- upstream/CoDA/coda/network/transformer/rope_transformer.py +349 -0
- upstream/CoDA/coda/network/transformer/trajrope_transformer.py +210 -0
upstream/CoDA/coda/model/common_utils/scheduler.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from bisect import bisect_right
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class WarmupMultiStepLR(torch.optim.lr_scheduler.LRScheduler):
|
| 6 |
+
def __init__(self, optimizer, milestones, warmup=0, gamma=0.1, last_epoch=-1, verbose="deprecated"):
|
| 7 |
+
"""Assume optimizer does not change lr; Scheduler is called epoch-based"""
|
| 8 |
+
self.milestones = milestones
|
| 9 |
+
self.warmup = warmup
|
| 10 |
+
assert warmup < milestones[0]
|
| 11 |
+
self.gamma = gamma
|
| 12 |
+
super().__init__(optimizer, last_epoch, verbose)
|
| 13 |
+
|
| 14 |
+
def get_lr(self):
|
| 15 |
+
base_lrs = self.base_lrs # base lr for each groups
|
| 16 |
+
n_groups = len(base_lrs)
|
| 17 |
+
comming_epoch = self.last_epoch # the lr will be set for the comming epoch, starts from 0
|
| 18 |
+
|
| 19 |
+
# add extra warmup
|
| 20 |
+
if comming_epoch < self.warmup:
|
| 21 |
+
# e.g. comming_epoch [0, 1, 2] for warmup == 3
|
| 22 |
+
# lr should be base_lr * (last_epoch+1) / (warmup + 1), e.g. [0.25, 0.5, 0.75] * base_lr
|
| 23 |
+
lr_factor = (self.last_epoch + 1) / (self.warmup + 1)
|
| 24 |
+
return [base_lrs[i] * lr_factor for i in range(n_groups)]
|
| 25 |
+
else:
|
| 26 |
+
# bisect_right([3,5,7], 0) -> 0; bisect_right([3,5,7], 5) -> 2
|
| 27 |
+
p = bisect_right(self.milestones, comming_epoch)
|
| 28 |
+
lr_factor = self.gamma**p
|
| 29 |
+
return [base_lrs[i] * lr_factor for i in range(n_groups)]
|
upstream/CoDA/coda/model/diff/__pycache__/diffusion_pl.cpython-310.pyc
ADDED
|
Binary file (3.57 kB). View file
|
|
|
upstream/CoDA/coda/model/diff/callbacks/metric_arctic.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
import pytorch_lightning as pl
|
| 4 |
+
import os
|
| 5 |
+
from pytorch_lightning.utilities import rank_zero_only
|
| 6 |
+
from coda.configs import MainStore, builds
|
| 7 |
+
from hydra.utils import instantiate
|
| 8 |
+
|
| 9 |
+
from coda.utils.comm.gather import all_gather
|
| 10 |
+
from coda.utils.pylogger import Log
|
| 11 |
+
|
| 12 |
+
from coda.utils.eval.eval_utils import (
|
| 13 |
+
compute_camcoord_metrics,
|
| 14 |
+
compute_global_metrics,
|
| 15 |
+
compute_camcoord_perjoint_metrics,
|
| 16 |
+
rearrange_by_mask,
|
| 17 |
+
as_np_array,
|
| 18 |
+
)
|
| 19 |
+
import coda.utils.matrix as matrix
|
| 20 |
+
from coda.utils.eval.metric_utils import ListAggregator
|
| 21 |
+
from coda.model.diff.utils.motion3d_endecoder import HmlvecArcticEnDecoder, HmlobjvecArcticEnDecoder
|
| 22 |
+
from coda.utils.smplx_utils import make_smplx
|
| 23 |
+
from einops import einsum, rearrange
|
| 24 |
+
from coda.utils.arctic.object_tensors import ObjectTensors
|
| 25 |
+
import coda.network.evaluator.t2m_motionenc as t2m_motionenc
|
| 26 |
+
import coda.network.evaluator.t2m_textenc as t2m_textenc
|
| 27 |
+
from coda.network.evaluator.word_vectorizer import POS_enumerator
|
| 28 |
+
from coda.utils.hml3d.metric import (
|
| 29 |
+
euclidean_distance_matrix,
|
| 30 |
+
calculate_top_k,
|
| 31 |
+
calculate_top_k_with_duplicates,
|
| 32 |
+
calculate_diversity_np,
|
| 33 |
+
calculate_activation_statistics_np,
|
| 34 |
+
calculate_frechet_distance_np,
|
| 35 |
+
calculate_multimodality_np,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
from coda.utils.wis3d_utils import make_wis3d, add_motion_as_lines
|
| 40 |
+
from coda.model.diff.callbacks.utils import compute_mpjpe, compute_distance_error, calculate_foot_sliding
|
| 41 |
+
import imageio
|
| 42 |
+
from tqdm import tqdm
|
| 43 |
+
from pathlib import Path
|
| 44 |
+
import numpy as np
|
| 45 |
+
import cv2
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class MetricWholeBodyObjPose(pl.Callback):
|
| 49 |
+
def __init__(self, prefix=""):
|
| 50 |
+
"""
|
| 51 |
+
Args:
|
| 52 |
+
emdb_split: 1 to evaluate incam, 2 to evaluate global
|
| 53 |
+
"""
|
| 54 |
+
super().__init__()
|
| 55 |
+
# vid->result
|
| 56 |
+
self.target_dataset_id = "ARCTIC_WHOLEBODYPOSE"
|
| 57 |
+
self.metric_aggregator = {}
|
| 58 |
+
self.prefix = prefix
|
| 59 |
+
|
| 60 |
+
self.object_tensor = ObjectTensors().cuda()
|
| 61 |
+
|
| 62 |
+
self.top_k = 3
|
| 63 |
+
self.R_size = 32
|
| 64 |
+
self.diversity_times = 300
|
| 65 |
+
self.checkpoint_name = "arcticobj"
|
| 66 |
+
self.endecoder_opt = {"_target_": "coda.model.diff.utils.motion3d_endecoder.HmlobjvecArcticEnDecoder"}
|
| 67 |
+
|
| 68 |
+
self.fs_aggregator = ListAggregator()
|
| 69 |
+
self.gt_fs_aggregator = ListAggregator()
|
| 70 |
+
|
| 71 |
+
self.is_fid = True
|
| 72 |
+
try:
|
| 73 |
+
self.text_embeddings = ListAggregator()
|
| 74 |
+
self.gen_motion_embeddings = ListAggregator()
|
| 75 |
+
self.gt_motion_embeddings = ListAggregator()
|
| 76 |
+
self.ori_text = ListAggregator()
|
| 77 |
+
self._get_t2m_evaluator()
|
| 78 |
+
except Exception as e:
|
| 79 |
+
self.is_fid = False
|
| 80 |
+
|
| 81 |
+
self.data_endecoder: HmlobjvecArcticEnDecoder = instantiate(self.endecoder_opt, _recursive_=False)
|
| 82 |
+
self.encoder_motion3d = self.data_endecoder.encode
|
| 83 |
+
|
| 84 |
+
self.on_test_epoch_start = self.on_validation_epoch_start = self.on_predict_epoch_start
|
| 85 |
+
|
| 86 |
+
# The metrics are calculated similarly for val/test/predict
|
| 87 |
+
self.on_test_batch_end = self.on_validation_batch_end = self.on_predict_batch_end
|
| 88 |
+
|
| 89 |
+
# Only validation record the metrics with logger
|
| 90 |
+
self.on_test_epoch_end = self.on_validation_epoch_end = self.on_predict_epoch_end
|
| 91 |
+
|
| 92 |
+
def _get_t2m_evaluator(self):
|
| 93 |
+
"""
|
| 94 |
+
load T2M text encoder and motion encoder for evaluating
|
| 95 |
+
"""
|
| 96 |
+
######
|
| 97 |
+
# OPT is from https://github.com/GuyTevet/motion-diffusion-model/blob/main/data_loaders/humanml/networks/evaluator_wrapper.py
|
| 98 |
+
######
|
| 99 |
+
checkpoints_dir = f"./inputs/checkpoints/{self.checkpoint_name}"
|
| 100 |
+
Log.info(f"Loading {self.checkpoint_name} evaluators")
|
| 101 |
+
|
| 102 |
+
opt = {
|
| 103 |
+
"dim_word": 300,
|
| 104 |
+
"max_motion_length": 300,
|
| 105 |
+
"dim_pos_ohot": len(POS_enumerator),
|
| 106 |
+
"dim_motion_hidden": 1024,
|
| 107 |
+
"max_text_len": 20,
|
| 108 |
+
"dim_text_hidden": 512,
|
| 109 |
+
"dim_coemb_hidden": 512,
|
| 110 |
+
"dim_pose": 52 * 3 * 3 + 4,
|
| 111 |
+
"dim_movement_enc_hidden": 512,
|
| 112 |
+
"dim_movement_latent": 512,
|
| 113 |
+
"checkpoints_dir": checkpoints_dir,
|
| 114 |
+
"unit_length": 4,
|
| 115 |
+
}
|
| 116 |
+
# init module
|
| 117 |
+
self.t2m_textencoder = t2m_textenc.TextEncoderBiGRUCo(
|
| 118 |
+
word_size=opt["dim_word"],
|
| 119 |
+
pos_size=opt["dim_pos_ohot"],
|
| 120 |
+
hidden_size=opt["dim_text_hidden"],
|
| 121 |
+
output_size=opt["dim_coemb_hidden"],
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
self.t2m_moveencoder = t2m_motionenc.MovementConvEncoder(
|
| 125 |
+
input_size=opt["dim_pose"] - 4,
|
| 126 |
+
hidden_size=opt["dim_movement_enc_hidden"],
|
| 127 |
+
output_size=opt["dim_movement_latent"],
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
self.t2m_motionencoder = t2m_motionenc.MotionEncoderBiGRUCo(
|
| 131 |
+
input_size=opt["dim_movement_latent"],
|
| 132 |
+
hidden_size=opt["dim_motion_hidden"],
|
| 133 |
+
output_size=opt["dim_coemb_hidden"],
|
| 134 |
+
)
|
| 135 |
+
# load pretrianed
|
| 136 |
+
t2m_checkpoint = torch.load(
|
| 137 |
+
os.path.join(opt["checkpoints_dir"], "text_mot_match/model/latest.tar"),
|
| 138 |
+
map_location="cpu",
|
| 139 |
+
)
|
| 140 |
+
self.t2m_textencoder.load_state_dict(t2m_checkpoint["text_encoder"])
|
| 141 |
+
self.t2m_moveencoder.load_state_dict(t2m_checkpoint["movement_encoder"])
|
| 142 |
+
self.t2m_motionencoder.load_state_dict(t2m_checkpoint["motion_encoder"])
|
| 143 |
+
|
| 144 |
+
# freeze params
|
| 145 |
+
self.t2m_textencoder.eval()
|
| 146 |
+
self.t2m_moveencoder.eval()
|
| 147 |
+
self.t2m_motionencoder.eval()
|
| 148 |
+
for p in self.t2m_textencoder.parameters():
|
| 149 |
+
p.requires_grad = False
|
| 150 |
+
for p in self.t2m_moveencoder.parameters():
|
| 151 |
+
p.requires_grad = False
|
| 152 |
+
for p in self.t2m_motionencoder.parameters():
|
| 153 |
+
p.requires_grad = False
|
| 154 |
+
|
| 155 |
+
# ================== Batch-based Computation ================== #
|
| 156 |
+
def on_predict_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=0):
|
| 157 |
+
"""The behaviour is the same for val/test/predict"""
|
| 158 |
+
assert batch["B"] == 1
|
| 159 |
+
dataset_id = batch["meta"][0]["dataset_id"]
|
| 160 |
+
if dataset_id != self.target_dataset_id:
|
| 161 |
+
return
|
| 162 |
+
|
| 163 |
+
vid = batch["meta"][0]["vid"]
|
| 164 |
+
seq_length = batch["length"][0].item()
|
| 165 |
+
mask = batch["mask"][0]
|
| 166 |
+
|
| 167 |
+
finger_ind = [
|
| 168 |
+
1,
|
| 169 |
+
2,
|
| 170 |
+
3, # index
|
| 171 |
+
5,
|
| 172 |
+
6,
|
| 173 |
+
7, # middle
|
| 174 |
+
9,
|
| 175 |
+
10,
|
| 176 |
+
11, # pinky
|
| 177 |
+
13,
|
| 178 |
+
14,
|
| 179 |
+
15, # ring
|
| 180 |
+
17,
|
| 181 |
+
18,
|
| 182 |
+
19, # thumb
|
| 183 |
+
]
|
| 184 |
+
|
| 185 |
+
# Groundtruth
|
| 186 |
+
body_pos = outputs["gt_output"]["global_pos"][0]
|
| 187 |
+
lefthand_pos = outputs["gt_output"]["lefthand_global_pos"][0]
|
| 188 |
+
righthand_pos = outputs["gt_output"]["righthand_global_pos"][0]
|
| 189 |
+
gt_pos = torch.cat([body_pos, lefthand_pos[..., finger_ind, :], righthand_pos[..., finger_ind, :]], dim=-2)
|
| 190 |
+
gt_pos = gt_pos[None]
|
| 191 |
+
|
| 192 |
+
foot_sliding = calculate_foot_sliding(gt_pos)
|
| 193 |
+
self.gt_fs_aggregator.update(foot_sliding)
|
| 194 |
+
|
| 195 |
+
obj_root_mat = batch["obj"][..., 0, :, :]
|
| 196 |
+
center = batch["center"]
|
| 197 |
+
obj_center = matrix.get_position_from(center[:, None], obj_root_mat)
|
| 198 |
+
obj_center_mat = matrix.get_TRS(matrix.get_rotation(obj_root_mat), obj_center)
|
| 199 |
+
|
| 200 |
+
# pred
|
| 201 |
+
if "pred_joint_pos" in outputs:
|
| 202 |
+
pred_pos = outputs["pred_joint_pos"]
|
| 203 |
+
pred_obj_root_mat = outputs["pred_objmat"]
|
| 204 |
+
pred_angles = outputs["pred_obj_angles"] # (B, L, 1)
|
| 205 |
+
else:
|
| 206 |
+
body_pos = outputs["global_pos"][0]
|
| 207 |
+
lefthand_pos = outputs["lefthand_global_pos"][0]
|
| 208 |
+
righthand_pos = outputs["righthand_global_pos"][0]
|
| 209 |
+
pred_pos = torch.cat(
|
| 210 |
+
[body_pos, lefthand_pos[..., finger_ind, :], righthand_pos[..., finger_ind, :]], dim=-2
|
| 211 |
+
)
|
| 212 |
+
pred_pos = pred_pos[None]
|
| 213 |
+
pred_obj_root_mat = outputs["obj"]
|
| 214 |
+
pred_angles = outputs["obj_angles"]
|
| 215 |
+
|
| 216 |
+
foot_sliding = calculate_foot_sliding(pred_pos)
|
| 217 |
+
self.fs_aggregator.update(foot_sliding)
|
| 218 |
+
|
| 219 |
+
pred_obj_center = matrix.get_position_from(center[:, None], pred_obj_root_mat) # (B, L, 3)
|
| 220 |
+
pred_obj_center_mat = matrix.get_TRS(matrix.get_rotation(pred_obj_root_mat), pred_obj_center) # (B, L, 4, 4)
|
| 221 |
+
|
| 222 |
+
articulated_axis = torch.tensor([0, 0, -1], dtype=torch.float32, device=pred_obj_center_mat.device) # (3, )
|
| 223 |
+
articulated_axis = articulated_axis[None, None].expand(-1, pred_obj_center_mat.shape[1], -1) # (B, L, 3)
|
| 224 |
+
pred_aa = pred_angles * articulated_axis
|
| 225 |
+
pred_arti_rotmat = matrix.axis_angle_to_matrix(pred_aa) # (B, L, 3, 3)
|
| 226 |
+
pred_arti_mat = matrix.get_TRS(pred_arti_rotmat, torch.zeros_like(pred_obj_center)) # (B, L, 4, 4)
|
| 227 |
+
pred_arti_mat = matrix.get_mat_BfromA(pred_obj_root_mat, pred_arti_mat)
|
| 228 |
+
|
| 229 |
+
gt_angles = batch["angles"]
|
| 230 |
+
gt_aa = gt_angles * articulated_axis
|
| 231 |
+
gt_arti_rotmat = matrix.axis_angle_to_matrix(gt_aa)
|
| 232 |
+
gt_arti_mat = matrix.get_TRS(gt_arti_rotmat, torch.zeros_like(obj_center))
|
| 233 |
+
gt_arti_mat = matrix.get_mat_BfromA(obj_root_mat, gt_arti_mat)
|
| 234 |
+
|
| 235 |
+
pred_invpos1 = matrix.get_relative_position_to(pred_pos, pred_obj_center_mat)
|
| 236 |
+
pred_invpos2 = matrix.get_relative_position_to(pred_pos, pred_arti_mat)
|
| 237 |
+
pred_vec = torch.cat([pred_pos.flatten(-2), pred_invpos1.flatten(-2), pred_invpos2.flatten(-2)], dim=-1)
|
| 238 |
+
pred_vec = torch.cat([pred_vec, pred_obj_center, pred_angles], dim=-1)
|
| 239 |
+
|
| 240 |
+
gt_invpos1 = matrix.get_relative_position_to(gt_pos, obj_center_mat)
|
| 241 |
+
gt_invpos2 = matrix.get_relative_position_to(gt_pos, gt_arti_mat)
|
| 242 |
+
gt_vec = torch.cat([gt_pos.flatten(-2), gt_invpos1.flatten(-2), gt_invpos2.flatten(-2)], dim=-1)
|
| 243 |
+
gt_vec = torch.cat([gt_vec, obj_center, gt_angles], dim=-1)
|
| 244 |
+
|
| 245 |
+
# normalize
|
| 246 |
+
pred_ayfz_motion_vec = self.encoder_motion3d(pred_vec)
|
| 247 |
+
gt_ayfz_motion_vec = self.encoder_motion3d(gt_vec)
|
| 248 |
+
# (B, C, L) -> (B, L, C)
|
| 249 |
+
pred_ayfz_motion_vec = pred_ayfz_motion_vec.transpose(1, 2)
|
| 250 |
+
gt_ayfz_motion_vec = gt_ayfz_motion_vec.transpose(1, 2)
|
| 251 |
+
|
| 252 |
+
# t2m motion encoder
|
| 253 |
+
m_lens = torch.div(batch["length"], 4, rounding_mode="floor")
|
| 254 |
+
|
| 255 |
+
word_embs = batch["word_embs"]
|
| 256 |
+
pos_onehot = batch["pos_onehot"]
|
| 257 |
+
text_length = batch["text_len"]
|
| 258 |
+
ori_text = batch["caption"]
|
| 259 |
+
|
| 260 |
+
# motion length should be sorted in decreasing order for RNN batch forward
|
| 261 |
+
align_m_idx = np.argsort(m_lens.data.tolist())[::-1].copy()
|
| 262 |
+
pred_ayfz_motion_vec = pred_ayfz_motion_vec[align_m_idx]
|
| 263 |
+
gt_ayfz_motion_vec = gt_ayfz_motion_vec[align_m_idx]
|
| 264 |
+
m_lens = m_lens[align_m_idx]
|
| 265 |
+
|
| 266 |
+
motion_mov = self.t2m_moveencoder(pred_ayfz_motion_vec[..., :-4]).detach()
|
| 267 |
+
motion_emb = self.t2m_motionencoder(motion_mov, m_lens)
|
| 268 |
+
|
| 269 |
+
gt_motion_mov = self.t2m_moveencoder(gt_ayfz_motion_vec[..., :-4]).detach()
|
| 270 |
+
gt_motion_emb = self.t2m_motionencoder(gt_motion_mov, m_lens)
|
| 271 |
+
|
| 272 |
+
# t2m text encoder
|
| 273 |
+
# text length should be sorted in decreasing order for RNN batch forward
|
| 274 |
+
align_t_idx = np.argsort(text_length.data.tolist())[::-1].copy()
|
| 275 |
+
word_embs = word_embs[align_t_idx]
|
| 276 |
+
pos_onehot = pos_onehot[align_t_idx]
|
| 277 |
+
text_length = text_length[align_t_idx]
|
| 278 |
+
text_emb = self.t2m_textencoder(word_embs, pos_onehot, text_length)
|
| 279 |
+
# text order convert to motion order
|
| 280 |
+
inverse_align_t_idx = np.argsort(align_t_idx)
|
| 281 |
+
text_emb = text_emb[inverse_align_t_idx][align_m_idx]
|
| 282 |
+
|
| 283 |
+
self.text_embeddings.update(text_emb)
|
| 284 |
+
self.gen_motion_embeddings.update(motion_emb)
|
| 285 |
+
self.gt_motion_embeddings.update(gt_motion_emb)
|
| 286 |
+
self.ori_text.update(ori_text)
|
| 287 |
+
|
| 288 |
+
def on_predict_epoch_start(self, trainer, pl_module):
|
| 289 |
+
|
| 290 |
+
self.wis_i = 0
|
| 291 |
+
|
| 292 |
+
if not self.is_fid:
|
| 293 |
+
return
|
| 294 |
+
|
| 295 |
+
self.text_embeddings.reset()
|
| 296 |
+
self.gen_motion_embeddings.reset()
|
| 297 |
+
self.gt_motion_embeddings.reset()
|
| 298 |
+
|
| 299 |
+
# NOTE: not sure whether this way is beautiful
|
| 300 |
+
self.t2m_textencoder = self.t2m_textencoder.to(pl_module.device)
|
| 301 |
+
self.t2m_moveencoder = self.t2m_moveencoder.to(pl_module.device)
|
| 302 |
+
self.t2m_motionencoder = self.t2m_motionencoder.to(pl_module.device)
|
| 303 |
+
self.data_endecoder = self.data_endecoder.to(pl_module.device)
|
| 304 |
+
|
| 305 |
+
return
|
| 306 |
+
|
| 307 |
+
# ================== Epoch Summary ================== #
|
| 308 |
+
def on_predict_epoch_end(self, trainer, pl_module):
|
| 309 |
+
"""Without logger"""
|
| 310 |
+
|
| 311 |
+
metrics = {
|
| 312 |
+
"Matching_score": 0.0,
|
| 313 |
+
"gt_Matching_score": 0.0,
|
| 314 |
+
"Diversity": 0.0,
|
| 315 |
+
"gt_Diversity": 0.0,
|
| 316 |
+
}
|
| 317 |
+
for i in range(self.top_k):
|
| 318 |
+
metrics[f"R_precision_top_{str(i + 1)}"] = 0.0
|
| 319 |
+
metrics[f"gt_R_precision_top_{str(i + 1)}"] = 0.0
|
| 320 |
+
|
| 321 |
+
count_seq = self.text_embeddings.length()
|
| 322 |
+
|
| 323 |
+
# cat all embeddings
|
| 324 |
+
shuffle_idx = torch.randperm(count_seq)
|
| 325 |
+
all_texts = self.text_embeddings.get_tensor()[shuffle_idx]
|
| 326 |
+
all_genmotions = self.gen_motion_embeddings.get_tensor()[shuffle_idx]
|
| 327 |
+
all_gtmotions = self.gt_motion_embeddings.get_tensor()[shuffle_idx]
|
| 328 |
+
all_ori_texts = []
|
| 329 |
+
for idx in shuffle_idx:
|
| 330 |
+
all_ori_texts.append(self.ori_text.get_tensor()[idx])
|
| 331 |
+
device = all_genmotions.device
|
| 332 |
+
|
| 333 |
+
# Compute r-precision
|
| 334 |
+
# assert count_seq > self.R_size
|
| 335 |
+
R_N = count_seq // self.R_size
|
| 336 |
+
if R_N == 0:
|
| 337 |
+
R_N = 1
|
| 338 |
+
Log.warn(
|
| 339 |
+
f"Generation metric - Matching_score and R_precision required at least {self.R_size} sequences, "
|
| 340 |
+
f"but only uses {count_seq} sequences to calculate!"
|
| 341 |
+
)
|
| 342 |
+
matching_score = 0.0
|
| 343 |
+
top_k_mat = torch.zeros((self.top_k,), device=device)
|
| 344 |
+
for i in range(R_N):
|
| 345 |
+
# [bs=32, 1*256]
|
| 346 |
+
group_texts = all_texts[i * self.R_size : (i + 1) * self.R_size]
|
| 347 |
+
# [bs=32, 1*256]
|
| 348 |
+
group_motions = all_genmotions[i * self.R_size : (i + 1) * self.R_size]
|
| 349 |
+
# dist_mat = pairwise_euclidean_distance(group_texts, group_motions)
|
| 350 |
+
# [bs=32, 32]
|
| 351 |
+
dist_mat = euclidean_distance_matrix(group_texts, group_motions).nan_to_num()
|
| 352 |
+
# print(dist_mat[:5])
|
| 353 |
+
matching_score += dist_mat.trace()
|
| 354 |
+
argsmax = torch.argsort(dist_mat, dim=1)
|
| 355 |
+
top_k_mat += calculate_top_k(argsmax, top_k=self.top_k).sum(axis=0)
|
| 356 |
+
group_ori_texts = all_ori_texts[i * self.R_size : (i + 1) * self.R_size]
|
| 357 |
+
R_count = count_seq // self.R_size * self.R_size
|
| 358 |
+
metrics["Matching_score"] = matching_score / R_count
|
| 359 |
+
for k in range(self.top_k):
|
| 360 |
+
metrics[f"R_precision_top_{str(k+1)}"] = top_k_mat[k] / R_count
|
| 361 |
+
|
| 362 |
+
# Compute r-precision with gt
|
| 363 |
+
# assert count_seq >= self.R_size
|
| 364 |
+
matching_score = 0.0
|
| 365 |
+
top_k_mat = torch.zeros((self.top_k,), device=device)
|
| 366 |
+
for i in range(R_N):
|
| 367 |
+
# [bs=32, 1*256]
|
| 368 |
+
group_texts = all_texts[i * self.R_size : (i + 1) * self.R_size]
|
| 369 |
+
# [bs=32, 1*256]
|
| 370 |
+
group_motions = all_gtmotions[i * self.R_size : (i + 1) * self.R_size]
|
| 371 |
+
# [bs=32, 32]
|
| 372 |
+
dist_mat = euclidean_distance_matrix(group_texts, group_motions).nan_to_num()
|
| 373 |
+
# match score
|
| 374 |
+
matching_score += dist_mat.trace()
|
| 375 |
+
argsmax = torch.argsort(dist_mat, dim=1)
|
| 376 |
+
top_k_mat += calculate_top_k(argsmax, top_k=self.top_k).sum(axis=0)
|
| 377 |
+
metrics["gt_Matching_score"] = matching_score / R_count
|
| 378 |
+
for k in range(self.top_k):
|
| 379 |
+
metrics[f"gt_R_precision_top_{str(k+1)}"] = top_k_mat[k] / R_count
|
| 380 |
+
|
| 381 |
+
# tensor -> numpy for FID
|
| 382 |
+
all_genmotions = all_genmotions.detach().cpu().numpy()
|
| 383 |
+
all_gtmotions = all_gtmotions.detach().cpu().numpy()
|
| 384 |
+
|
| 385 |
+
# Compute fid
|
| 386 |
+
mu, cov = calculate_activation_statistics_np(all_genmotions)
|
| 387 |
+
gt_mu, gt_cov = calculate_activation_statistics_np(all_gtmotions)
|
| 388 |
+
metrics["FID"] = calculate_frechet_distance_np(gt_mu, gt_cov, mu, cov)
|
| 389 |
+
|
| 390 |
+
# Compute diversity
|
| 391 |
+
if count_seq > self.diversity_times:
|
| 392 |
+
diversity_times = self.diversity_times
|
| 393 |
+
else:
|
| 394 |
+
diversity_times = count_seq
|
| 395 |
+
Log.warn(
|
| 396 |
+
f"Generation metric - Diversity required {self.diversity_times} sequences, "
|
| 397 |
+
f"but only uses {diversity_times} sequences to calculate!"
|
| 398 |
+
)
|
| 399 |
+
metrics["Diversity"] = calculate_diversity_np(all_genmotions, diversity_times)
|
| 400 |
+
metrics["gt_Diversity"] = calculate_diversity_np(all_gtmotions, diversity_times)
|
| 401 |
+
|
| 402 |
+
metrics["foot_sliding"] = self.fs_aggregator.get_tensor().mean()
|
| 403 |
+
metrics["gt_foot_sliding"] = self.gt_fs_aggregator.get_tensor().mean()
|
| 404 |
+
|
| 405 |
+
# log to stdout
|
| 406 |
+
for k, v in metrics.items():
|
| 407 |
+
if isinstance(v, (torch.Tensor, np.ndarray)):
|
| 408 |
+
v = v.item()
|
| 409 |
+
Log.info(f"{k}: {v:.3f}")
|
| 410 |
+
|
| 411 |
+
# save to logger if available
|
| 412 |
+
if pl_module.logger is not None:
|
| 413 |
+
cur_epoch = pl_module.current_epoch
|
| 414 |
+
for k, v in metrics.items():
|
| 415 |
+
if isinstance(v, torch.Tensor):
|
| 416 |
+
v = v.item()
|
| 417 |
+
pl_module.logger.log_metrics({f"val_metric_{self.target_dataset_id}/{k}": v}, step=cur_epoch)
|
| 418 |
+
|
| 419 |
+
self.text_embeddings.reset()
|
| 420 |
+
self.gen_motion_embeddings.reset()
|
| 421 |
+
self.gt_motion_embeddings.reset()
|
| 422 |
+
|
| 423 |
+
self.t2m_textencoder = self.t2m_textencoder.cpu()
|
| 424 |
+
self.t2m_moveencoder = self.t2m_moveencoder.cpu()
|
| 425 |
+
self.t2m_motionencoder = self.t2m_motionencoder.cpu()
|
| 426 |
+
self.data_endecoder = self.data_endecoder.cpu()
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
wholebodyobjpose_node = builds(MetricWholeBodyObjPose)
|
| 430 |
+
MainStore.store(
|
| 431 |
+
name="metric_wholebodyobjpose",
|
| 432 |
+
node=wholebodyobjpose_node,
|
| 433 |
+
group="callbacks",
|
| 434 |
+
package="callbacks.metric_wholebodyobjpose",
|
| 435 |
+
)
|
upstream/CoDA/coda/model/diff/callbacks/metric_grab.py
ADDED
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
import pytorch_lightning as pl
|
| 4 |
+
import os
|
| 5 |
+
from pytorch_lightning.utilities import rank_zero_only
|
| 6 |
+
from coda.configs import MainStore, builds
|
| 7 |
+
from hydra.utils import instantiate
|
| 8 |
+
|
| 9 |
+
from coda.utils.pylogger import Log
|
| 10 |
+
|
| 11 |
+
import coda.utils.matrix as matrix
|
| 12 |
+
from coda.utils.eval.metric_utils import ListAggregator
|
| 13 |
+
from coda.model.diff.utils.motion3d_endecoder import (
|
| 14 |
+
HmlobjvecGrabEnDecoder,
|
| 15 |
+
)
|
| 16 |
+
from coda.utils.hml3d.metric import (
|
| 17 |
+
euclidean_distance_matrix,
|
| 18 |
+
calculate_top_k,
|
| 19 |
+
calculate_diversity_np,
|
| 20 |
+
calculate_activation_statistics_np,
|
| 21 |
+
calculate_frechet_distance_np,
|
| 22 |
+
calculate_multimodality_np,
|
| 23 |
+
)
|
| 24 |
+
import coda.network.evaluator.t2m_motionenc as t2m_motionenc
|
| 25 |
+
import coda.network.evaluator.t2m_textenc as t2m_textenc
|
| 26 |
+
|
| 27 |
+
from coda.network.evaluator.word_vectorizer import POS_enumerator
|
| 28 |
+
from coda.utils.wis3d_utils import make_wis3d, add_motion_as_lines
|
| 29 |
+
from coda.model.diff.callbacks.utils import compute_mpjpe, compute_distance_error, calculate_foot_sliding
|
| 30 |
+
import imageio
|
| 31 |
+
from tqdm import tqdm
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
import numpy as np
|
| 34 |
+
import cv2
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class MetricWholeBodyObjPose(pl.Callback):
|
| 38 |
+
def __init__(self, prefix=""):
|
| 39 |
+
"""
|
| 40 |
+
Args:
|
| 41 |
+
emdb_split: 1 to evaluate incam, 2 to evaluate global
|
| 42 |
+
"""
|
| 43 |
+
super().__init__()
|
| 44 |
+
# vid->result
|
| 45 |
+
self.target_dataset_id = "GRAB_WHOLEBODYPOSE"
|
| 46 |
+
self.metric_aggregator = {}
|
| 47 |
+
self.prefix = prefix
|
| 48 |
+
|
| 49 |
+
self.top_k = 3
|
| 50 |
+
self.R_size = 32
|
| 51 |
+
self.diversity_times = 300
|
| 52 |
+
self.checkpoint_name = "grab_short"
|
| 53 |
+
self.endecoder_opt = {"_target_": "coda.model.diff.utils.motion3d_endecoder.HmlobjvecGrabEnDecoder"}
|
| 54 |
+
|
| 55 |
+
self.fs_aggregator = ListAggregator()
|
| 56 |
+
self.gt_fs_aggregator = ListAggregator()
|
| 57 |
+
|
| 58 |
+
self.is_fid = True
|
| 59 |
+
try:
|
| 60 |
+
self.text_embeddings = ListAggregator()
|
| 61 |
+
self.gen_motion_embeddings = ListAggregator()
|
| 62 |
+
self.gt_motion_embeddings = ListAggregator()
|
| 63 |
+
self._get_t2m_evaluator()
|
| 64 |
+
except Exception as e:
|
| 65 |
+
self.is_fid = False
|
| 66 |
+
|
| 67 |
+
self.data_endecoder: HmlobjvecGrabEnDecoder = instantiate(self.endecoder_opt, _recursive_=False)
|
| 68 |
+
self.encoder_motion3d = self.data_endecoder.encode
|
| 69 |
+
|
| 70 |
+
self.on_test_epoch_start = self.on_validation_epoch_start = self.on_predict_epoch_start
|
| 71 |
+
|
| 72 |
+
# The metrics are calculated similarly for val/test/predict
|
| 73 |
+
self.on_test_batch_end = self.on_validation_batch_end = self.on_predict_batch_end
|
| 74 |
+
|
| 75 |
+
# Only validation record the metrics with logger
|
| 76 |
+
self.on_test_epoch_end = self.on_validation_epoch_end = self.on_predict_epoch_end
|
| 77 |
+
|
| 78 |
+
def _get_t2m_evaluator(self):
|
| 79 |
+
"""
|
| 80 |
+
load T2M text encoder and motion encoder for evaluating
|
| 81 |
+
"""
|
| 82 |
+
######
|
| 83 |
+
# OPT is from https://github.com/GuyTevet/motion-diffusion-model/blob/main/data_loaders/humanml/networks/evaluator_wrapper.py
|
| 84 |
+
######
|
| 85 |
+
checkpoints_dir = f"./inputs/checkpoints/{self.checkpoint_name}"
|
| 86 |
+
Log.info(f"Loading {self.checkpoint_name} evaluators")
|
| 87 |
+
|
| 88 |
+
opt = {
|
| 89 |
+
"dim_word": 300,
|
| 90 |
+
"max_motion_length": 300,
|
| 91 |
+
"dim_pos_ohot": len(POS_enumerator),
|
| 92 |
+
"dim_motion_hidden": 1024,
|
| 93 |
+
"max_text_len": 20,
|
| 94 |
+
"dim_text_hidden": 512,
|
| 95 |
+
"dim_coemb_hidden": 512,
|
| 96 |
+
"dim_pose": 52 * 3 * 2 + 3,
|
| 97 |
+
"dim_movement_enc_hidden": 512,
|
| 98 |
+
"dim_movement_latent": 512,
|
| 99 |
+
"checkpoints_dir": checkpoints_dir,
|
| 100 |
+
"unit_length": 4,
|
| 101 |
+
}
|
| 102 |
+
# init module
|
| 103 |
+
self.t2m_textencoder = t2m_textenc.TextEncoderBiGRUCo(
|
| 104 |
+
word_size=opt["dim_word"],
|
| 105 |
+
pos_size=opt["dim_pos_ohot"],
|
| 106 |
+
hidden_size=opt["dim_text_hidden"],
|
| 107 |
+
output_size=opt["dim_coemb_hidden"],
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
self.t2m_moveencoder = t2m_motionenc.MovementConvEncoder(
|
| 111 |
+
input_size=opt["dim_pose"] - 4,
|
| 112 |
+
hidden_size=opt["dim_movement_enc_hidden"],
|
| 113 |
+
output_size=opt["dim_movement_latent"],
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
self.t2m_motionencoder = t2m_motionenc.MotionEncoderBiGRUCo(
|
| 117 |
+
input_size=opt["dim_movement_latent"],
|
| 118 |
+
hidden_size=opt["dim_motion_hidden"],
|
| 119 |
+
output_size=opt["dim_coemb_hidden"],
|
| 120 |
+
)
|
| 121 |
+
# load pretrianed
|
| 122 |
+
t2m_checkpoint = torch.load(
|
| 123 |
+
os.path.join(opt["checkpoints_dir"], "text_mot_match/model/finest.tar"),
|
| 124 |
+
map_location="cpu",
|
| 125 |
+
)
|
| 126 |
+
self.t2m_textencoder.load_state_dict(t2m_checkpoint["text_encoder"])
|
| 127 |
+
self.t2m_moveencoder.load_state_dict(t2m_checkpoint["movement_encoder"])
|
| 128 |
+
self.t2m_motionencoder.load_state_dict(t2m_checkpoint["motion_encoder"])
|
| 129 |
+
|
| 130 |
+
# freeze params
|
| 131 |
+
self.t2m_textencoder.eval()
|
| 132 |
+
self.t2m_moveencoder.eval()
|
| 133 |
+
self.t2m_motionencoder.eval()
|
| 134 |
+
for p in self.t2m_textencoder.parameters():
|
| 135 |
+
p.requires_grad = False
|
| 136 |
+
for p in self.t2m_moveencoder.parameters():
|
| 137 |
+
p.requires_grad = False
|
| 138 |
+
for p in self.t2m_motionencoder.parameters():
|
| 139 |
+
p.requires_grad = False
|
| 140 |
+
|
| 141 |
+
# ================== Batch-based Computation ================== #
|
| 142 |
+
def on_predict_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx=0):
|
| 143 |
+
"""The behaviour is the same for val/test/predict"""
|
| 144 |
+
assert batch["B"] == 1
|
| 145 |
+
dataset_id = batch["meta"][0]["dataset_id"]
|
| 146 |
+
if dataset_id != self.target_dataset_id:
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
vid = batch["meta"][0]["vid"]
|
| 150 |
+
seq_length = batch["length"][0].item()
|
| 151 |
+
|
| 152 |
+
finger_ind = [
|
| 153 |
+
1,
|
| 154 |
+
2,
|
| 155 |
+
3, # index
|
| 156 |
+
5,
|
| 157 |
+
6,
|
| 158 |
+
7, # middle
|
| 159 |
+
9,
|
| 160 |
+
10,
|
| 161 |
+
11, # pinky
|
| 162 |
+
13,
|
| 163 |
+
14,
|
| 164 |
+
15, # ring
|
| 165 |
+
17,
|
| 166 |
+
18,
|
| 167 |
+
19, # thumb
|
| 168 |
+
]
|
| 169 |
+
|
| 170 |
+
# Groundtruth
|
| 171 |
+
body_pos = outputs["gt_output"]["global_pos"][0]
|
| 172 |
+
lefthand_pos = outputs["gt_output"]["lefthand_global_pos"][0]
|
| 173 |
+
righthand_pos = outputs["gt_output"]["righthand_global_pos"][0]
|
| 174 |
+
gt_pos = torch.cat([body_pos, lefthand_pos[..., finger_ind, :], righthand_pos[..., finger_ind, :]], dim=-2)
|
| 175 |
+
gt_pos = gt_pos[None]
|
| 176 |
+
|
| 177 |
+
foot_sliding = calculate_foot_sliding(gt_pos)
|
| 178 |
+
self.gt_fs_aggregator.update(foot_sliding)
|
| 179 |
+
|
| 180 |
+
obj_root_mat = batch["obj"][..., 0, :, :]
|
| 181 |
+
center = batch["center"]
|
| 182 |
+
obj_center = matrix.get_position_from(center[:, None], obj_root_mat)
|
| 183 |
+
obj_center_mat = matrix.get_TRS(matrix.get_rotation(obj_root_mat), obj_center)
|
| 184 |
+
|
| 185 |
+
# pred
|
| 186 |
+
if "pred_joint_pos" in outputs:
|
| 187 |
+
pred_pos = outputs["pred_joint_pos"]
|
| 188 |
+
pred_obj_root_mat = outputs["pred_objmat"]
|
| 189 |
+
else:
|
| 190 |
+
body_pos = outputs["global_pos"][0]
|
| 191 |
+
lefthand_pos = outputs["lefthand_global_pos"][0]
|
| 192 |
+
righthand_pos = outputs["righthand_global_pos"][0]
|
| 193 |
+
pred_pos = torch.cat(
|
| 194 |
+
[body_pos, lefthand_pos[..., finger_ind, :], righthand_pos[..., finger_ind, :]], dim=-2
|
| 195 |
+
)
|
| 196 |
+
pred_pos = pred_pos[None]
|
| 197 |
+
pred_obj_root_mat = outputs["obj"]
|
| 198 |
+
|
| 199 |
+
foot_sliding = calculate_foot_sliding(pred_pos)
|
| 200 |
+
self.fs_aggregator.update(foot_sliding)
|
| 201 |
+
|
| 202 |
+
pred_obj_center = matrix.get_position_from(center[:, None], pred_obj_root_mat) # (B, L, 3)
|
| 203 |
+
pred_obj_center_mat = matrix.get_TRS(matrix.get_rotation(pred_obj_root_mat), pred_obj_center) # (B, L, 4, 4)
|
| 204 |
+
|
| 205 |
+
pred_invpos1 = matrix.get_relative_position_to(pred_pos, pred_obj_center_mat)
|
| 206 |
+
pred_vec = torch.cat([pred_pos.flatten(-2), pred_invpos1.flatten(-2)], dim=-1)
|
| 207 |
+
pred_vec = torch.cat([pred_vec, pred_obj_center], dim=-1)
|
| 208 |
+
|
| 209 |
+
# identtity_mat = matrix.identity_mat(obj_center_mat)
|
| 210 |
+
# obj_center_mat = matrix.get_TRS(matrix.get_rotation(identtity_mat), matrix.get_position(obj_center_mat))
|
| 211 |
+
gt_invpos1 = matrix.get_relative_position_to(gt_pos, obj_center_mat)
|
| 212 |
+
gt_vec = torch.cat([gt_pos.flatten(-2), gt_invpos1.flatten(-2)], dim=-1)
|
| 213 |
+
gt_vec = torch.cat([gt_vec, obj_center], dim=-1)
|
| 214 |
+
|
| 215 |
+
# normalize
|
| 216 |
+
pred_ayfz_motion_vec = self.encoder_motion3d(pred_vec)
|
| 217 |
+
gt_ayfz_motion_vec = self.encoder_motion3d(gt_vec)
|
| 218 |
+
# (B, C, L) -> (B, L, C)
|
| 219 |
+
pred_ayfz_motion_vec = pred_ayfz_motion_vec.transpose(1, 2)
|
| 220 |
+
gt_ayfz_motion_vec = gt_ayfz_motion_vec.transpose(1, 2)
|
| 221 |
+
|
| 222 |
+
# t2m motion encoder
|
| 223 |
+
m_lens = torch.div(batch["length"], 4, rounding_mode="floor")
|
| 224 |
+
|
| 225 |
+
word_embs = batch["word_embs"]
|
| 226 |
+
pos_onehot = batch["pos_onehot"]
|
| 227 |
+
text_length = batch["text_len"]
|
| 228 |
+
|
| 229 |
+
# motion length should be sorted in decreasing order for RNN batch forward
|
| 230 |
+
align_m_idx = np.argsort(m_lens.data.tolist())[::-1].copy()
|
| 231 |
+
pred_ayfz_motion_vec = pred_ayfz_motion_vec[align_m_idx]
|
| 232 |
+
gt_ayfz_motion_vec = gt_ayfz_motion_vec[align_m_idx]
|
| 233 |
+
m_lens = m_lens[align_m_idx]
|
| 234 |
+
|
| 235 |
+
motion_mov = self.t2m_moveencoder(pred_ayfz_motion_vec[..., :-4]).detach()
|
| 236 |
+
motion_emb = self.t2m_motionencoder(motion_mov, m_lens)
|
| 237 |
+
|
| 238 |
+
gt_motion_mov = self.t2m_moveencoder(gt_ayfz_motion_vec[..., :-4]).detach()
|
| 239 |
+
gt_motion_emb = self.t2m_motionencoder(gt_motion_mov, m_lens)
|
| 240 |
+
|
| 241 |
+
# t2m text encoder
|
| 242 |
+
# text length should be sorted in decreasing order for RNN batch forward
|
| 243 |
+
align_t_idx = np.argsort(text_length.data.tolist())[::-1].copy()
|
| 244 |
+
word_embs = word_embs[align_t_idx]
|
| 245 |
+
pos_onehot = pos_onehot[align_t_idx]
|
| 246 |
+
text_length = text_length[align_t_idx]
|
| 247 |
+
text_emb = self.t2m_textencoder(word_embs, pos_onehot, text_length)
|
| 248 |
+
# text order convert to motion order
|
| 249 |
+
inverse_align_t_idx = np.argsort(align_t_idx)
|
| 250 |
+
text_emb = text_emb[inverse_align_t_idx][align_m_idx]
|
| 251 |
+
|
| 252 |
+
self.text_embeddings.update(text_emb)
|
| 253 |
+
self.gen_motion_embeddings.update(motion_emb)
|
| 254 |
+
self.gt_motion_embeddings.update(gt_motion_emb)
|
| 255 |
+
|
| 256 |
+
def on_predict_epoch_start(self, trainer, pl_module):
|
| 257 |
+
|
| 258 |
+
self.wis_i = 0
|
| 259 |
+
|
| 260 |
+
if not self.is_fid:
|
| 261 |
+
return
|
| 262 |
+
|
| 263 |
+
self.text_embeddings.reset()
|
| 264 |
+
self.gen_motion_embeddings.reset()
|
| 265 |
+
self.gt_motion_embeddings.reset()
|
| 266 |
+
|
| 267 |
+
# NOTE: not sure whether this way is beautiful
|
| 268 |
+
self.t2m_textencoder = self.t2m_textencoder.to(pl_module.device)
|
| 269 |
+
self.t2m_moveencoder = self.t2m_moveencoder.to(pl_module.device)
|
| 270 |
+
self.t2m_motionencoder = self.t2m_motionencoder.to(pl_module.device)
|
| 271 |
+
self.data_endecoder = self.data_endecoder.to(pl_module.device)
|
| 272 |
+
|
| 273 |
+
return
|
| 274 |
+
|
| 275 |
+
# ================== Epoch Summary ================== #
|
| 276 |
+
def on_predict_epoch_end(self, trainer, pl_module):
|
| 277 |
+
"""Without logger"""
|
| 278 |
+
|
| 279 |
+
metrics = {
|
| 280 |
+
"Matching_score": 0.0,
|
| 281 |
+
"gt_Matching_score": 0.0,
|
| 282 |
+
"Diversity": 0.0,
|
| 283 |
+
"gt_Diversity": 0.0,
|
| 284 |
+
}
|
| 285 |
+
for i in range(self.top_k):
|
| 286 |
+
metrics[f"R_precision_top_{str(i + 1)}"] = 0.0
|
| 287 |
+
metrics[f"gt_R_precision_top_{str(i + 1)}"] = 0.0
|
| 288 |
+
|
| 289 |
+
count_seq = self.text_embeddings.length()
|
| 290 |
+
|
| 291 |
+
# cat all embeddings
|
| 292 |
+
shuffle_idx = torch.randperm(count_seq)
|
| 293 |
+
all_texts = self.text_embeddings.get_tensor()[shuffle_idx]
|
| 294 |
+
all_genmotions = self.gen_motion_embeddings.get_tensor()[shuffle_idx]
|
| 295 |
+
all_gtmotions = self.gt_motion_embeddings.get_tensor()[shuffle_idx]
|
| 296 |
+
|
| 297 |
+
device = all_genmotions.device
|
| 298 |
+
|
| 299 |
+
# Compute r-precision
|
| 300 |
+
# assert count_seq > self.R_size
|
| 301 |
+
R_N = count_seq // self.R_size
|
| 302 |
+
if R_N == 0:
|
| 303 |
+
R_N = 1
|
| 304 |
+
Log.warn(
|
| 305 |
+
f"Generation metric - Matching_score and R_precision required at least {self.R_size} sequences, "
|
| 306 |
+
f"but only uses {count_seq} sequences to calculate!"
|
| 307 |
+
)
|
| 308 |
+
matching_score = 0.0
|
| 309 |
+
top_k_mat = torch.zeros((self.top_k,), device=device)
|
| 310 |
+
for i in range(R_N):
|
| 311 |
+
# [bs=32, 1*256]
|
| 312 |
+
group_texts = all_texts[i * self.R_size : (i + 1) * self.R_size]
|
| 313 |
+
# [bs=32, 1*256]
|
| 314 |
+
group_motions = all_genmotions[i * self.R_size : (i + 1) * self.R_size]
|
| 315 |
+
# dist_mat = pairwise_euclidean_distance(group_texts, group_motions)
|
| 316 |
+
# [bs=32, 32]
|
| 317 |
+
dist_mat = euclidean_distance_matrix(group_texts, group_motions).nan_to_num()
|
| 318 |
+
# print(dist_mat[:5])
|
| 319 |
+
matching_score += dist_mat.trace()
|
| 320 |
+
argsmax = torch.argsort(dist_mat, dim=1)
|
| 321 |
+
top_k_mat += calculate_top_k(argsmax, top_k=self.top_k).sum(axis=0)
|
| 322 |
+
R_count = count_seq // self.R_size * self.R_size
|
| 323 |
+
metrics["Matching_score"] = matching_score / R_count
|
| 324 |
+
for k in range(self.top_k):
|
| 325 |
+
metrics[f"R_precision_top_{str(k+1)}"] = top_k_mat[k] / R_count
|
| 326 |
+
|
| 327 |
+
# Compute r-precision with gt
|
| 328 |
+
# assert count_seq >= self.R_size
|
| 329 |
+
matching_score = 0.0
|
| 330 |
+
top_k_mat = torch.zeros((self.top_k,), device=device)
|
| 331 |
+
for i in range(R_N):
|
| 332 |
+
# [bs=32, 1*256]
|
| 333 |
+
group_texts = all_texts[i * self.R_size : (i + 1) * self.R_size]
|
| 334 |
+
# [bs=32, 1*256]
|
| 335 |
+
group_motions = all_gtmotions[i * self.R_size : (i + 1) * self.R_size]
|
| 336 |
+
# [bs=32, 32]
|
| 337 |
+
dist_mat = euclidean_distance_matrix(group_texts, group_motions).nan_to_num()
|
| 338 |
+
# match score
|
| 339 |
+
matching_score += dist_mat.trace()
|
| 340 |
+
argsmax = torch.argsort(dist_mat, dim=1)
|
| 341 |
+
top_k_mat += calculate_top_k(argsmax, top_k=self.top_k).sum(axis=0)
|
| 342 |
+
metrics["gt_Matching_score"] = matching_score / R_count
|
| 343 |
+
for k in range(self.top_k):
|
| 344 |
+
metrics[f"gt_R_precision_top_{str(k+1)}"] = top_k_mat[k] / R_count
|
| 345 |
+
|
| 346 |
+
# tensor -> numpy for FID
|
| 347 |
+
all_genmotions = all_genmotions.detach().cpu().numpy()
|
| 348 |
+
all_gtmotions = all_gtmotions.detach().cpu().numpy()
|
| 349 |
+
|
| 350 |
+
# Compute fid
|
| 351 |
+
mu, cov = calculate_activation_statistics_np(all_genmotions)
|
| 352 |
+
gt_mu, gt_cov = calculate_activation_statistics_np(all_gtmotions)
|
| 353 |
+
metrics["FID"] = calculate_frechet_distance_np(gt_mu, gt_cov, mu, cov)
|
| 354 |
+
|
| 355 |
+
# Compute diversity
|
| 356 |
+
if count_seq > self.diversity_times:
|
| 357 |
+
diversity_times = self.diversity_times
|
| 358 |
+
else:
|
| 359 |
+
diversity_times = count_seq
|
| 360 |
+
Log.warn(
|
| 361 |
+
f"Generation metric - Diversity required {self.diversity_times} sequences, "
|
| 362 |
+
f"but only uses {diversity_times} sequences to calculate!"
|
| 363 |
+
)
|
| 364 |
+
metrics["Diversity"] = calculate_diversity_np(all_genmotions, diversity_times)
|
| 365 |
+
metrics["gt_Diversity"] = calculate_diversity_np(all_gtmotions, diversity_times)
|
| 366 |
+
|
| 367 |
+
metrics["foot_sliding"] = self.fs_aggregator.get_tensor().mean()
|
| 368 |
+
metrics["gt_foot_sliding"] = self.gt_fs_aggregator.get_tensor().mean()
|
| 369 |
+
|
| 370 |
+
# log to stdout
|
| 371 |
+
for k, v in metrics.items():
|
| 372 |
+
if isinstance(v, (torch.Tensor, np.ndarray)):
|
| 373 |
+
v = v.item()
|
| 374 |
+
Log.info(f"{k}: {v:.3f}")
|
| 375 |
+
|
| 376 |
+
# save to logger if available
|
| 377 |
+
if pl_module.logger is not None:
|
| 378 |
+
cur_epoch = pl_module.current_epoch
|
| 379 |
+
for k, v in metrics.items():
|
| 380 |
+
if isinstance(v, torch.Tensor):
|
| 381 |
+
v = v.item()
|
| 382 |
+
pl_module.logger.log_metrics({f"val_metric_{self.target_dataset_id}/{k}": v}, step=cur_epoch)
|
| 383 |
+
|
| 384 |
+
self.text_embeddings.reset()
|
| 385 |
+
self.gen_motion_embeddings.reset()
|
| 386 |
+
self.gt_motion_embeddings.reset()
|
| 387 |
+
|
| 388 |
+
self.t2m_textencoder = self.t2m_textencoder.cpu()
|
| 389 |
+
self.t2m_moveencoder = self.t2m_moveencoder.cpu()
|
| 390 |
+
self.t2m_motionencoder = self.t2m_motionencoder.cpu()
|
| 391 |
+
self.data_endecoder = self.data_endecoder.cpu()
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
wholebodyobjpose_node = builds(MetricWholeBodyObjPose)
|
| 395 |
+
MainStore.store(
|
| 396 |
+
name="metric_grab_wholebodyobjpose",
|
| 397 |
+
node=wholebodyobjpose_node,
|
| 398 |
+
group="callbacks",
|
| 399 |
+
package="callbacks.metric_grab_wholebodyobjpose",
|
| 400 |
+
)
|
upstream/CoDA/coda/model/diff/callbacks/utils.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def compute_mpjpe(pred, target, mask=None):
|
| 6 |
+
pred = pred.reshape(-1, 3)
|
| 7 |
+
target = target.reshape(-1, 3)
|
| 8 |
+
if mask is not None:
|
| 9 |
+
mask = mask.reshape(-1, 3)
|
| 10 |
+
mpjpe = ((pred - target) * mask).norm(dim=-1)
|
| 11 |
+
N = mask.sum() // 3 + 1e-6
|
| 12 |
+
return mpjpe.sum() / N
|
| 13 |
+
else:
|
| 14 |
+
mpjpe = (pred - target).norm(dim=-1)
|
| 15 |
+
return mpjpe.mean()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def resample_motion_fps(motion, target_length):
|
| 19 |
+
N, J, C = motion.shape # N: 帧数,J: 关节点数,C: 坐标数(通常为3)
|
| 20 |
+
|
| 21 |
+
motion = motion.permute(1, 2, 0)
|
| 22 |
+
|
| 23 |
+
upsampled_motion = F.interpolate(motion, size=target_length, mode="linear", align_corners=True)
|
| 24 |
+
|
| 25 |
+
upsampled_motion = upsampled_motion.permute(2, 0, 1)
|
| 26 |
+
return upsampled_motion
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def compute_distance_error(pred, target, mask=None):
|
| 30 |
+
pred = pred.reshape(-1, 1)
|
| 31 |
+
target = target.reshape(-1, 1)
|
| 32 |
+
if mask is not None:
|
| 33 |
+
mask = mask.reshape(-1, 1)
|
| 34 |
+
mpjpe = ((pred - target) * mask).norm(dim=-1)
|
| 35 |
+
N = mask.sum() + 1e-6
|
| 36 |
+
return mpjpe.sum() / N
|
| 37 |
+
else:
|
| 38 |
+
mpjpe = (pred - target).norm(dim=-1)
|
| 39 |
+
return mpjpe.mean()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def calculate_foot_sliding(motion):
|
| 43 |
+
# motion: (B, L, J, 3)
|
| 44 |
+
foot_ind = [10, 11]
|
| 45 |
+
foot_global_pos = motion[..., foot_ind, :]
|
| 46 |
+
foot_global_h = foot_global_pos[..., :-1, :, 1] # (B, L, j)
|
| 47 |
+
foot_global_vel = foot_global_pos[..., 1:, :, [0, 2]] - foot_global_pos[..., :-1, :, [0, 2]]
|
| 48 |
+
# assume 30 fps
|
| 49 |
+
foot_global_vel = 30 * torch.norm(foot_global_vel, dim=-1) # (B, L-1, j)
|
| 50 |
+
left_foot_mask = (foot_global_h[..., 0] < foot_global_h[..., 1]).float()
|
| 51 |
+
foot_sliding = foot_global_vel[..., 0] * left_foot_mask + foot_global_vel[..., 1] * (1 - left_foot_mask)
|
| 52 |
+
foot_sliding = foot_sliding.mean(dim=-1) # (B, )
|
| 53 |
+
return foot_sliding
|
upstream/CoDA/coda/model/diff/pipeline/bps_pipeline.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch.cuda.amp import autocast
|
| 5 |
+
import numpy as np
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import inspect
|
| 8 |
+
from einops import einsum, rearrange, repeat
|
| 9 |
+
from hydra.utils import instantiate
|
| 10 |
+
from coda.utils.pylogger import Log
|
| 11 |
+
from coda.utils.net_utils import gaussian_smooth
|
| 12 |
+
from diffusers.schedulers import DDPMScheduler
|
| 13 |
+
from pytorch_lightning.utilities import rank_zero_only
|
| 14 |
+
|
| 15 |
+
from coda.model.diff.utils.endecoder import EnDecoder
|
| 16 |
+
from coda.model.diff.pipeline.mini_pipeline import randomly_set_null_condition
|
| 17 |
+
from coda.model.diff.pipeline.text_pipeline import Pipeline as TextPipeline, randomly_set_null_text
|
| 18 |
+
|
| 19 |
+
from pytorch3d.transforms import (
|
| 20 |
+
matrix_to_rotation_6d,
|
| 21 |
+
rotation_6d_to_matrix,
|
| 22 |
+
axis_angle_to_matrix,
|
| 23 |
+
matrix_to_axis_angle,
|
| 24 |
+
)
|
| 25 |
+
from coda.utils.wis3d_utils import make_wis3d, add_motion_as_lines
|
| 26 |
+
from coda.utils.smplx_utils import make_smplx
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Pipeline(TextPipeline):
|
| 30 |
+
# ========== Training ========== #
|
| 31 |
+
def forward_train(self, inputs):
|
| 32 |
+
outputs = dict()
|
| 33 |
+
length = inputs["length"] # (B,) effective length of each sample
|
| 34 |
+
B = length.size(0)
|
| 35 |
+
scheduler = self.train_scheduler
|
| 36 |
+
|
| 37 |
+
condition_dict = self.endecoder.encode_condition(inputs)
|
| 38 |
+
x = self.endecoder.encode(inputs)
|
| 39 |
+
|
| 40 |
+
# *. Add noise
|
| 41 |
+
noise = torch.randn_like(x)
|
| 42 |
+
t = torch.randint(0, scheduler.config.num_train_timesteps, (B,), device=x.device).long()
|
| 43 |
+
noisy_x = scheduler.add_noise(x, noise, t)
|
| 44 |
+
|
| 45 |
+
# *. Conditions
|
| 46 |
+
f_condition = condition_dict
|
| 47 |
+
f_condition = randomly_set_null_condition(f_condition, 0.1)
|
| 48 |
+
|
| 49 |
+
# Encode CLIP embedding
|
| 50 |
+
assert self.training
|
| 51 |
+
text = inputs["caption"]
|
| 52 |
+
text = randomly_set_null_text(text, 0.1)
|
| 53 |
+
clip_text = self.clip.encode_text(text, enable_cfg=False, with_projection=True) # (B, D)
|
| 54 |
+
f_condition["f_text"] = clip_text.f_text
|
| 55 |
+
|
| 56 |
+
model_kwargs = self.build_model_kwargs(noisy_x, t, inputs, f_condition, enable_cfg=False)
|
| 57 |
+
|
| 58 |
+
# Forward & output
|
| 59 |
+
model_output = self.denoiser3d(**model_kwargs)
|
| 60 |
+
model_pred = model_output["sample"] # (B, L, C)
|
| 61 |
+
seq_mask = model_output["mask"] # (B, L)
|
| 62 |
+
|
| 63 |
+
# ========== Compute Loss ========== #
|
| 64 |
+
prediction_type = scheduler.config.prediction_type
|
| 65 |
+
if prediction_type == "sample":
|
| 66 |
+
target = x
|
| 67 |
+
else:
|
| 68 |
+
assert prediction_type == "epsilon"
|
| 69 |
+
target = noise
|
| 70 |
+
|
| 71 |
+
mask = inputs["mask"] * seq_mask[..., None] # (B, L, C)
|
| 72 |
+
|
| 73 |
+
M = inputs["basis_finger_point"].shape[-2]
|
| 74 |
+
L = inputs["bps"].shape[-2]
|
| 75 |
+
|
| 76 |
+
dist_pred = model_pred[..., :-20]
|
| 77 |
+
contact_pred = model_pred[..., -20:-10]
|
| 78 |
+
vert_pred = model_pred[..., -10:]
|
| 79 |
+
dist_target = target[..., :-20]
|
| 80 |
+
contact_target = target[..., -20:-10]
|
| 81 |
+
vert_target = target[..., -10:]
|
| 82 |
+
dist_mask = mask[..., :-20]
|
| 83 |
+
contact_mask = mask[..., -20:-10]
|
| 84 |
+
vert_mask = mask[..., -10:]
|
| 85 |
+
|
| 86 |
+
dist_pred = dist_pred.reshape(B, L, M, -1) * dist_mask[..., None, :]
|
| 87 |
+
dist_target = dist_target.reshape(B, L, M, -1) * dist_mask[..., None, :]
|
| 88 |
+
contact_pred = contact_pred * contact_mask
|
| 89 |
+
contact_target = contact_target * contact_mask
|
| 90 |
+
vert_pred = vert_pred * vert_mask
|
| 91 |
+
vert_target = vert_target * vert_mask
|
| 92 |
+
|
| 93 |
+
loss_sum = 0.0
|
| 94 |
+
wrist_dist_loss = F.l1_loss(dist_pred[..., :2].float(), dist_target[..., :2].float(), reduction="mean")
|
| 95 |
+
loss_sum += wrist_dist_loss
|
| 96 |
+
figner_dist_loss = F.l1_loss(dist_pred[..., 2:].float(), dist_target[..., 2:].float(), reduction="mean")
|
| 97 |
+
loss_sum += figner_dist_loss
|
| 98 |
+
contact_loss = F.l1_loss(contact_pred.float(), contact_target.float(), reduction="mean")
|
| 99 |
+
loss_sum += contact_loss
|
| 100 |
+
vert_loss = F.l1_loss(vert_pred.float(), vert_target.float(), reduction="mean")
|
| 101 |
+
loss_sum += vert_loss
|
| 102 |
+
|
| 103 |
+
outputs["loss"] = loss_sum
|
| 104 |
+
outputs["wrist_dist_loss"] = wrist_dist_loss
|
| 105 |
+
outputs["finger_dist_loss"] = figner_dist_loss
|
| 106 |
+
outputs["contact_loss"] = contact_loss
|
| 107 |
+
outputs["vert_loss"] = vert_loss
|
| 108 |
+
return outputs
|
| 109 |
+
|
| 110 |
+
# ========== Sample ========== #
|
| 111 |
+
def forward_sample(self, inputs):
|
| 112 |
+
# Setup
|
| 113 |
+
outputs = dict()
|
| 114 |
+
enable_cfg = False if self.guidance_scale == 0 else True
|
| 115 |
+
scheduler = self.test_scheduler
|
| 116 |
+
|
| 117 |
+
length = inputs["length"].max()
|
| 118 |
+
B = inputs["length"].shape[0]
|
| 119 |
+
gt_x = self.endecoder.encode(inputs)
|
| 120 |
+
gt_output = self.endecoder.decode(gt_x, inputs=inputs)
|
| 121 |
+
|
| 122 |
+
# 1. Prepare target variable x, which will be denoised progressively
|
| 123 |
+
x = torch.randn((B, length, self.denoiser3d.output_dim), device=gt_x.device)
|
| 124 |
+
|
| 125 |
+
# 2. Conditions
|
| 126 |
+
condition_dict = self.endecoder.encode_condition(inputs)
|
| 127 |
+
f_condition = condition_dict
|
| 128 |
+
|
| 129 |
+
# *. Denoising loop
|
| 130 |
+
# scheduler: timestep, extra_step_kwargs
|
| 131 |
+
scheduler.set_timesteps(self.num_inference_steps)
|
| 132 |
+
timesteps = scheduler.timesteps
|
| 133 |
+
num_warmup_steps = len(timesteps) - self.num_inference_steps * scheduler.order
|
| 134 |
+
prog_bar = self.get_prog_bar(self.num_inference_steps)
|
| 135 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 136 |
+
for i, t in enumerate(timesteps):
|
| 137 |
+
# 1. Denoiser + Sampler.step
|
| 138 |
+
model_kwargs = self.build_model_kwargs(
|
| 139 |
+
x=x,
|
| 140 |
+
timesteps=t,
|
| 141 |
+
inputs=inputs,
|
| 142 |
+
f_condition=f_condition,
|
| 143 |
+
enable_cfg=enable_cfg,
|
| 144 |
+
)
|
| 145 |
+
x0_, _ = self.cfg_denoise_func(self.denoiser3d, model_kwargs, scheduler, enable_cfg)
|
| 146 |
+
|
| 147 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 148 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 149 |
+
|
| 150 |
+
# *. Update and store intermediate results
|
| 151 |
+
x = xprev_
|
| 152 |
+
|
| 153 |
+
# progress bar
|
| 154 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
|
| 155 |
+
if prog_bar is not None:
|
| 156 |
+
prog_bar.update()
|
| 157 |
+
|
| 158 |
+
outputs = self.endecoder.decode(x, inputs=inputs)
|
| 159 |
+
outputs["gt_output"] = gt_output
|
| 160 |
+
return outputs
|
upstream/CoDA/coda/model/diff/pipeline/mini_pipeline.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch.cuda.amp import autocast
|
| 5 |
+
import numpy as np
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import inspect
|
| 8 |
+
from einops import einsum, rearrange, repeat
|
| 9 |
+
from hydra.utils import instantiate
|
| 10 |
+
from coda.utils.pylogger import Log
|
| 11 |
+
from coda.utils.net_utils import gaussian_smooth
|
| 12 |
+
from diffusers.schedulers import DDPMScheduler
|
| 13 |
+
from pytorch_lightning.utilities import rank_zero_only
|
| 14 |
+
|
| 15 |
+
from coda.model.diff.utils.endecoder import EnDecoder
|
| 16 |
+
|
| 17 |
+
from pytorch3d.transforms import (
|
| 18 |
+
matrix_to_rotation_6d,
|
| 19 |
+
rotation_6d_to_matrix,
|
| 20 |
+
axis_angle_to_matrix,
|
| 21 |
+
matrix_to_axis_angle,
|
| 22 |
+
)
|
| 23 |
+
from coda.utils.wis3d_utils import make_wis3d, add_motion_as_lines
|
| 24 |
+
from coda.utils.smplx_utils import make_smplx
|
| 25 |
+
import coda.utils.matrix as matrix
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Pipeline(nn.Module):
|
| 29 |
+
def __init__(self, args, args_denoiser3d, **kwargs):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.args = args
|
| 32 |
+
|
| 33 |
+
self.train_scheduler = DDPMScheduler(**args.scheduler_opt_train)
|
| 34 |
+
self.test_scheduler = instantiate(args.scheduler_opt_sample)
|
| 35 |
+
self.guidance_scale = args.guidance_scale
|
| 36 |
+
self.num_inference_steps = args.num_inference_steps
|
| 37 |
+
|
| 38 |
+
# Networks
|
| 39 |
+
self.denoiser3d = instantiate(args_denoiser3d, _recursive_=False)
|
| 40 |
+
Log.info(self.denoiser3d)
|
| 41 |
+
self.build_endecoder(args)
|
| 42 |
+
self.load_vae(args)
|
| 43 |
+
self.endecoder.set_vae(self.vae)
|
| 44 |
+
|
| 45 |
+
def build_endecoder(self, args):
|
| 46 |
+
# Normalizer
|
| 47 |
+
self.endecoder: EnDecoder = instantiate(args.endecoder_opt, _recursive_=False)
|
| 48 |
+
|
| 49 |
+
def load_vae(self, args):
|
| 50 |
+
if "vae_args" in args:
|
| 51 |
+
self.vae = instantiate(args.vae_args, _recursive_=False)
|
| 52 |
+
vae_path = args.get("vae_path", None)
|
| 53 |
+
if vae_path is None:
|
| 54 |
+
return
|
| 55 |
+
vae_state_dict = torch.load(args.vae_path, map_location="cpu")["state_dict"]
|
| 56 |
+
print(f"Load VAE from {args.vae_path}")
|
| 57 |
+
filter_state_dict = {}
|
| 58 |
+
prefix = "pipeline.denoiser3d."
|
| 59 |
+
for k, v in vae_state_dict.items():
|
| 60 |
+
filter_state_dict[k[len(prefix) :]] = v
|
| 61 |
+
self.vae.load_state_dict(filter_state_dict, strict=True)
|
| 62 |
+
self.vae.eval()
|
| 63 |
+
self.vae.requires_grad_(False)
|
| 64 |
+
else:
|
| 65 |
+
self.vae = None
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def build_model_kwargs(x, timesteps, inputs, f_condition, enable_cfg, **kwargs):
|
| 69 |
+
"""override this if you want to add more kwargs"""
|
| 70 |
+
# supermotion/decoder_multiple_crossattn
|
| 71 |
+
length = torch.cat([inputs["length"]] * 2) if enable_cfg else inputs["length"]
|
| 72 |
+
if enable_cfg:
|
| 73 |
+
new_f_condition = {}
|
| 74 |
+
for k in f_condition.keys():
|
| 75 |
+
if k == "f_text":
|
| 76 |
+
new_f_condition[k] = f_condition[k].clone()
|
| 77 |
+
elif "trajmat" in k:
|
| 78 |
+
identity_mat = matrix.identity_mat(f_condition[k], device=x.device)
|
| 79 |
+
new_f_condition[k] = torch.cat([identity_mat, f_condition[k]], dim=0)
|
| 80 |
+
else:
|
| 81 |
+
new_f_condition[k] = torch.cat([torch.zeros_like(f_condition[k]), f_condition[k]], dim=0)
|
| 82 |
+
f_condition = new_f_condition
|
| 83 |
+
|
| 84 |
+
model_kwargs = dict(
|
| 85 |
+
x=x,
|
| 86 |
+
timesteps=timesteps,
|
| 87 |
+
length=length,
|
| 88 |
+
)
|
| 89 |
+
model_kwargs.update(f_condition)
|
| 90 |
+
return model_kwargs
|
| 91 |
+
|
| 92 |
+
# ========== Training ========== #
|
| 93 |
+
def forward_train(self, inputs):
|
| 94 |
+
outputs = dict()
|
| 95 |
+
length = inputs["length"] # (B,) effective length of each sample
|
| 96 |
+
B = length.size(0)
|
| 97 |
+
scheduler = self.train_scheduler
|
| 98 |
+
|
| 99 |
+
condition_dict = self.endecoder.encode_condition(inputs)
|
| 100 |
+
x = self.endecoder.encode(inputs)
|
| 101 |
+
|
| 102 |
+
####### debug vae output #######
|
| 103 |
+
# out_x = self.endecoder.decode(x, inputs=inputs)
|
| 104 |
+
# pos = out_x["tip_global_pos"]
|
| 105 |
+
|
| 106 |
+
# for i in range(16):
|
| 107 |
+
# wis3d = make_wis3d(name=f"debug_endecoder_{i:03d}")
|
| 108 |
+
# add_motion_as_lines(pos[i].float(), wis3d, name=f"output_hand_tip", skeleton_type="handtip", radius=0.005)
|
| 109 |
+
# raise NotImplementedError
|
| 110 |
+
#################################
|
| 111 |
+
|
| 112 |
+
# *. Add noise
|
| 113 |
+
noise = torch.randn_like(x)
|
| 114 |
+
t = torch.randint(0, scheduler.config.num_train_timesteps, (B,), device=x.device).long()
|
| 115 |
+
noisy_x = scheduler.add_noise(x, noise, t)
|
| 116 |
+
|
| 117 |
+
# *. Conditions
|
| 118 |
+
f_condition = condition_dict
|
| 119 |
+
f_condition = randomly_set_null_condition(f_condition, 0.1)
|
| 120 |
+
|
| 121 |
+
model_kwargs = self.build_model_kwargs(noisy_x, t, inputs, f_condition, enable_cfg=False)
|
| 122 |
+
|
| 123 |
+
# Forward & output
|
| 124 |
+
model_output = self.denoiser3d(**model_kwargs)
|
| 125 |
+
model_pred = model_output["sample"] # (B, L, C)
|
| 126 |
+
if "mask" in model_output:
|
| 127 |
+
seq_mask = model_output["mask"] # (B, L)
|
| 128 |
+
else:
|
| 129 |
+
seq_mask = None
|
| 130 |
+
|
| 131 |
+
# ========== Compute Loss ========== #
|
| 132 |
+
prediction_type = scheduler.config.prediction_type
|
| 133 |
+
if prediction_type == "sample":
|
| 134 |
+
target = x
|
| 135 |
+
else:
|
| 136 |
+
assert prediction_type == "epsilon"
|
| 137 |
+
target = noise
|
| 138 |
+
|
| 139 |
+
if "mask" in inputs:
|
| 140 |
+
mask = inputs["mask"]
|
| 141 |
+
if seq_mask is not None:
|
| 142 |
+
mask = mask * seq_mask[..., None] # (B, L, C)
|
| 143 |
+
else:
|
| 144 |
+
if seq_mask is not None:
|
| 145 |
+
mask = seq_mask[..., None] # (B, L, C)
|
| 146 |
+
else:
|
| 147 |
+
mask = None
|
| 148 |
+
|
| 149 |
+
if mask is not None:
|
| 150 |
+
model_pred = model_pred * mask
|
| 151 |
+
target = target * mask
|
| 152 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 153 |
+
|
| 154 |
+
outputs["loss"] = loss
|
| 155 |
+
return outputs
|
| 156 |
+
|
| 157 |
+
def cfg_denoise_func(self, denoiser, model_kwargs, scheduler, enable_cfg):
|
| 158 |
+
x = model_kwargs.pop("x")
|
| 159 |
+
t = model_kwargs.pop("timesteps")
|
| 160 |
+
|
| 161 |
+
# expand the x if we are doing classifier free guidance
|
| 162 |
+
x_model_input = torch.cat([x] * 2) if enable_cfg else x
|
| 163 |
+
x_model_input = scheduler.scale_model_input(x_model_input, t)
|
| 164 |
+
|
| 165 |
+
# predict
|
| 166 |
+
denoiser_out = denoiser(x_model_input, t, **model_kwargs)
|
| 167 |
+
noise_pred = denoiser_out["sample"]
|
| 168 |
+
|
| 169 |
+
# classifier-free guidance
|
| 170 |
+
if enable_cfg:
|
| 171 |
+
noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
|
| 172 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
| 173 |
+
|
| 174 |
+
# a special case since our motion prior is predicting x0 # TODO: extra check may be needed
|
| 175 |
+
x0_ = noise_pred
|
| 176 |
+
return x0_, denoiser_out
|
| 177 |
+
|
| 178 |
+
# ========== Sample ========== #
|
| 179 |
+
@staticmethod
|
| 180 |
+
def prepare_extra_step_kwargs(scheduler, eta=0.0):
|
| 181 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 182 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 183 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 184 |
+
# and should be between [0, 1]
|
| 185 |
+
|
| 186 |
+
accepts_eta = "eta" in set(inspect.signature(scheduler.step).parameters.keys())
|
| 187 |
+
extra_step_kwargs = {}
|
| 188 |
+
if accepts_eta:
|
| 189 |
+
extra_step_kwargs["eta"] = eta
|
| 190 |
+
|
| 191 |
+
# # check if the scheduler accepts generator
|
| 192 |
+
# accepts_generator = "generator" in set(inspect.signature(scheduler.step).parameters.keys())
|
| 193 |
+
# if accepts_generator:
|
| 194 |
+
# extra_step_kwargs["generator"] = generator
|
| 195 |
+
return extra_step_kwargs
|
| 196 |
+
|
| 197 |
+
def get_prog_bar(self, total, **kwargs):
|
| 198 |
+
return ProgBarWrapper(total=total, leave=False, bar_format="{l_bar}{bar:10}{r_bar}", **kwargs)
|
| 199 |
+
|
| 200 |
+
# ========== Sample ========== #
|
| 201 |
+
def forward_sample(self, inputs):
|
| 202 |
+
# return {}
|
| 203 |
+
# Setup
|
| 204 |
+
outputs = dict()
|
| 205 |
+
enable_cfg = False if self.guidance_scale == 0 else True
|
| 206 |
+
scheduler = self.test_scheduler
|
| 207 |
+
|
| 208 |
+
length = inputs["length"].max()
|
| 209 |
+
B = inputs["length"].shape[0]
|
| 210 |
+
gt_x = self.endecoder._encode(inputs)
|
| 211 |
+
gt_output = self.endecoder._decode(gt_x, inputs=inputs)
|
| 212 |
+
|
| 213 |
+
# 1. Prepare target variable x, which will be denoised progressively
|
| 214 |
+
if self.vae is None:
|
| 215 |
+
x = torch.randn((B, length, self.denoiser3d.output_dim), device=gt_x.device)
|
| 216 |
+
else:
|
| 217 |
+
x = torch.randn((B, self.denoiser3d.latent_size, self.denoiser3d.latent_dim), device=gt_x.device)
|
| 218 |
+
|
| 219 |
+
# 2. Conditions
|
| 220 |
+
condition_dict = self.endecoder.encode_condition(inputs)
|
| 221 |
+
f_condition = condition_dict
|
| 222 |
+
|
| 223 |
+
# *. Denoising loop
|
| 224 |
+
# scheduler: timestep, extra_step_kwargs
|
| 225 |
+
scheduler.set_timesteps(self.num_inference_steps)
|
| 226 |
+
timesteps = scheduler.timesteps
|
| 227 |
+
num_warmup_steps = len(timesteps) - self.num_inference_steps * scheduler.order
|
| 228 |
+
prog_bar = self.get_prog_bar(self.num_inference_steps)
|
| 229 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 230 |
+
for i, t in enumerate(timesteps):
|
| 231 |
+
# 1. Denoiser + Sampler.step
|
| 232 |
+
model_kwargs = self.build_model_kwargs(
|
| 233 |
+
x=x,
|
| 234 |
+
timesteps=t,
|
| 235 |
+
inputs=inputs,
|
| 236 |
+
f_condition=f_condition,
|
| 237 |
+
enable_cfg=enable_cfg,
|
| 238 |
+
)
|
| 239 |
+
x0_, _ = self.cfg_denoise_func(self.denoiser3d, model_kwargs, scheduler, enable_cfg)
|
| 240 |
+
|
| 241 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 242 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 243 |
+
|
| 244 |
+
# *. Update and store intermediate results
|
| 245 |
+
x = xprev_
|
| 246 |
+
|
| 247 |
+
# progress bar
|
| 248 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
|
| 249 |
+
if prog_bar is not None:
|
| 250 |
+
prog_bar.update()
|
| 251 |
+
|
| 252 |
+
outputs = self.endecoder.decode(x, inputs=inputs)
|
| 253 |
+
outputs["gt_output"] = gt_output
|
| 254 |
+
return outputs
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def randomly_set_null_condition(f_condition, uncond_prob=0.1):
|
| 258 |
+
"""Conditions are in shape (B, L, *)"""
|
| 259 |
+
keys = list(f_condition.keys())
|
| 260 |
+
for k in keys:
|
| 261 |
+
if f_condition[k] is None:
|
| 262 |
+
continue
|
| 263 |
+
f_condition[k] = f_condition[k].clone()
|
| 264 |
+
mask = torch.rand(f_condition[k].shape[:2]) < uncond_prob
|
| 265 |
+
if "trajmat" in k:
|
| 266 |
+
identity_mat = matrix.identity_mat(f_condition[k], device=f_condition[k].device)
|
| 267 |
+
f_condition[k][mask] = identity_mat[mask]
|
| 268 |
+
else:
|
| 269 |
+
f_condition[k][mask] = 0.0
|
| 270 |
+
return f_condition
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class ProgBarWrapper:
|
| 274 |
+
def __init__(self, **kwargs):
|
| 275 |
+
self.prog_bar = self.get_prog_bar(**kwargs)
|
| 276 |
+
|
| 277 |
+
@rank_zero_only
|
| 278 |
+
def get_prog_bar(self, **kwargs):
|
| 279 |
+
return tqdm(**kwargs)
|
| 280 |
+
|
| 281 |
+
@rank_zero_only
|
| 282 |
+
def update(self, **kwargs):
|
| 283 |
+
self.prog_bar.update(**kwargs)
|
upstream/CoDA/coda/model/diff/pipeline/text_pipeline.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch.cuda.amp import autocast
|
| 5 |
+
import numpy as np
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import inspect
|
| 8 |
+
from einops import einsum, rearrange, repeat
|
| 9 |
+
from hydra.utils import instantiate
|
| 10 |
+
from coda.utils.pylogger import Log
|
| 11 |
+
from coda.utils.net_utils import gaussian_smooth
|
| 12 |
+
from diffusers.schedulers import DDPMScheduler, DDIMScheduler, DDIMInverseScheduler
|
| 13 |
+
from pytorch_lightning.utilities import rank_zero_only
|
| 14 |
+
|
| 15 |
+
from coda.model.diff.utils.endecoder import EnDecoder
|
| 16 |
+
|
| 17 |
+
from pytorch3d.transforms import (
|
| 18 |
+
matrix_to_rotation_6d,
|
| 19 |
+
rotation_6d_to_matrix,
|
| 20 |
+
axis_angle_to_matrix,
|
| 21 |
+
matrix_to_axis_angle,
|
| 22 |
+
)
|
| 23 |
+
from coda.model.diff.pipeline.mini_pipeline import Pipeline as MiniPipeline
|
| 24 |
+
from coda.model.diff.pipeline.mini_pipeline import randomly_set_null_condition
|
| 25 |
+
from coda.utils.wis3d_utils import make_wis3d, add_motion_as_lines
|
| 26 |
+
from coda.utils.smplx_utils import make_smplx
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Pipeline(MiniPipeline):
|
| 30 |
+
def __init__(self, args, args_denoiser3d, args_clip, **kwargs):
|
| 31 |
+
super().__init__(args, args_denoiser3d, **kwargs)
|
| 32 |
+
self.clip = instantiate(args_clip, _recursive_=False)
|
| 33 |
+
|
| 34 |
+
# ----- Freeze ----- #
|
| 35 |
+
self.freeze_clip()
|
| 36 |
+
|
| 37 |
+
def freeze_clip(self):
|
| 38 |
+
self.clip.eval()
|
| 39 |
+
self.clip.requires_grad_(False)
|
| 40 |
+
|
| 41 |
+
# ========== Training ========== #
|
| 42 |
+
def forward_train(self, inputs):
|
| 43 |
+
outputs = dict()
|
| 44 |
+
length = inputs["length"] # (B,) effective length of each sample
|
| 45 |
+
B = length.size(0)
|
| 46 |
+
scheduler = self.train_scheduler
|
| 47 |
+
|
| 48 |
+
condition_dict = self.endecoder.encode_condition(inputs)
|
| 49 |
+
x = self.endecoder.encode(inputs)
|
| 50 |
+
|
| 51 |
+
# *. Add noise
|
| 52 |
+
noise = torch.randn_like(x)
|
| 53 |
+
t = torch.randint(0, scheduler.config.num_train_timesteps, (B,), device=x.device).long()
|
| 54 |
+
noisy_x = scheduler.add_noise(x, noise, t)
|
| 55 |
+
|
| 56 |
+
# *. Conditions
|
| 57 |
+
f_condition = condition_dict
|
| 58 |
+
f_condition = randomly_set_null_condition(f_condition, 0.1)
|
| 59 |
+
|
| 60 |
+
# Encode CLIP embedding
|
| 61 |
+
assert self.training
|
| 62 |
+
text = inputs["caption"]
|
| 63 |
+
text = randomly_set_null_text(text, 0.1)
|
| 64 |
+
clip_text = self.clip.encode_text(text, enable_cfg=False, with_projection=True) # (B, D)
|
| 65 |
+
f_condition["f_text"] = clip_text.f_text
|
| 66 |
+
|
| 67 |
+
model_kwargs = self.build_model_kwargs(noisy_x, t, inputs, f_condition, enable_cfg=False)
|
| 68 |
+
|
| 69 |
+
# Forward & output
|
| 70 |
+
model_output = self.denoiser3d(**model_kwargs)
|
| 71 |
+
model_pred = model_output["sample"] # (B, L, C)
|
| 72 |
+
if "mask" in model_output:
|
| 73 |
+
seq_mask = model_output["mask"] # (B, L)
|
| 74 |
+
else:
|
| 75 |
+
seq_mask = None
|
| 76 |
+
|
| 77 |
+
# ========== Compute Loss ========== #
|
| 78 |
+
prediction_type = scheduler.config.prediction_type
|
| 79 |
+
if prediction_type == "sample":
|
| 80 |
+
target = x
|
| 81 |
+
else:
|
| 82 |
+
assert prediction_type == "epsilon"
|
| 83 |
+
target = noise
|
| 84 |
+
|
| 85 |
+
if seq_mask is not None:
|
| 86 |
+
mask = seq_mask[..., None] # (B, L, C)
|
| 87 |
+
model_pred = model_pred * mask
|
| 88 |
+
target = target * mask
|
| 89 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 90 |
+
|
| 91 |
+
outputs["loss"] = loss
|
| 92 |
+
return outputs
|
| 93 |
+
|
| 94 |
+
# ========== Sample ========== #
|
| 95 |
+
def forward_sample(self, inputs):
|
| 96 |
+
# return {}
|
| 97 |
+
# Setup
|
| 98 |
+
outputs = dict()
|
| 99 |
+
enable_cfg = False if self.guidance_scale == 0 else True
|
| 100 |
+
scheduler = self.test_scheduler
|
| 101 |
+
|
| 102 |
+
max_length = inputs["length"].max()
|
| 103 |
+
try:
|
| 104 |
+
max_length = max(inputs["transl"].shape[1], max_length)
|
| 105 |
+
except:
|
| 106 |
+
pass
|
| 107 |
+
B = inputs["length"].shape[0]
|
| 108 |
+
gt_x = self.endecoder._encode(inputs)
|
| 109 |
+
gt_output = self.endecoder._decode(gt_x, inputs=inputs)
|
| 110 |
+
|
| 111 |
+
# 1. Prepare target variable x, which will be denoised progressively
|
| 112 |
+
x = torch.randn((B, max_length, self.denoiser3d.output_dim), device=gt_x.device)
|
| 113 |
+
|
| 114 |
+
# 2. Conditions
|
| 115 |
+
condition_dict = self.endecoder.encode_condition(inputs)
|
| 116 |
+
f_condition = condition_dict
|
| 117 |
+
|
| 118 |
+
# Encode CLIP embedding
|
| 119 |
+
text = inputs["caption"]
|
| 120 |
+
|
| 121 |
+
if not enable_cfg:
|
| 122 |
+
text = ["" for _ in range(len(text))]
|
| 123 |
+
|
| 124 |
+
clip_text = self.clip.encode_text(text, enable_cfg=enable_cfg, with_projection=True) # (B, D)
|
| 125 |
+
f_condition["f_text"] = clip_text.f_text
|
| 126 |
+
|
| 127 |
+
# *. Denoising loop
|
| 128 |
+
# scheduler: timestep, extra_step_kwargs
|
| 129 |
+
scheduler.set_timesteps(self.num_inference_steps)
|
| 130 |
+
timesteps = scheduler.timesteps
|
| 131 |
+
num_warmup_steps = len(timesteps) - self.num_inference_steps * scheduler.order
|
| 132 |
+
prog_bar = self.get_prog_bar(self.num_inference_steps)
|
| 133 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 134 |
+
for i, t in enumerate(timesteps):
|
| 135 |
+
# 1. Denoiser + Sampler.step
|
| 136 |
+
model_kwargs = self.build_model_kwargs(
|
| 137 |
+
x=x,
|
| 138 |
+
timesteps=t,
|
| 139 |
+
inputs=inputs,
|
| 140 |
+
f_condition=f_condition,
|
| 141 |
+
enable_cfg=enable_cfg,
|
| 142 |
+
)
|
| 143 |
+
x0_, _ = self.cfg_denoise_func(self.denoiser3d, model_kwargs, scheduler, enable_cfg)
|
| 144 |
+
|
| 145 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 146 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 147 |
+
|
| 148 |
+
# *. Update and store intermediate results
|
| 149 |
+
x = xprev_
|
| 150 |
+
|
| 151 |
+
# progress bar
|
| 152 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
|
| 153 |
+
if prog_bar is not None:
|
| 154 |
+
prog_bar.update()
|
| 155 |
+
|
| 156 |
+
outputs = self.endecoder.decode(x, inputs=inputs)
|
| 157 |
+
outputs["gt_output"] = gt_output
|
| 158 |
+
return outputs
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def randomly_set_null_text(text, uncond_prob=0.1):
|
| 162 |
+
"""
|
| 163 |
+
Args:
|
| 164 |
+
text: List of str
|
| 165 |
+
"""
|
| 166 |
+
# To support classifier-free guidance, randomly set-to-unconditioned
|
| 167 |
+
B = len(text)
|
| 168 |
+
# text
|
| 169 |
+
text_mask = torch.rand(B) < uncond_prob
|
| 170 |
+
text_ = ["" if m else t for m, t in zip(text_mask, text)]
|
| 171 |
+
|
| 172 |
+
return text_
|
upstream/CoDA/coda/model/diff/pipeline/wholebodypartobj_pipeline.py
ADDED
|
@@ -0,0 +1,1313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from torch.cuda.amp import autocast
|
| 6 |
+
import numpy as np
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
import inspect
|
| 9 |
+
from einops import einsum, rearrange, repeat
|
| 10 |
+
from hydra.utils import instantiate
|
| 11 |
+
from coda.utils.pylogger import Log
|
| 12 |
+
from coda.utils.net_utils import gaussian_smooth
|
| 13 |
+
from diffusers.schedulers import DDPMScheduler, DDIMScheduler, DDIMInverseScheduler
|
| 14 |
+
from diffusers import StableDiffusionPipeline
|
| 15 |
+
from coda.utils.grab.object_model import ObjectModel
|
| 16 |
+
from coda.utils.grab.mesh import Mesh
|
| 17 |
+
from pytorch_lightning.utilities import rank_zero_only
|
| 18 |
+
from coda.dataset.arctic.utils import get_wrist_trajectory, get_finger_trajectory
|
| 19 |
+
|
| 20 |
+
from coda.model.diff.utils.endecoder import EnDecoder
|
| 21 |
+
from coda.utils.bps import bps_gen_ball_inside, calculate_bps, get_pc_center, get_pc_scale
|
| 22 |
+
|
| 23 |
+
from pytorch3d.ops.sample_farthest_points import sample_farthest_points
|
| 24 |
+
from pytorch3d.transforms import (
|
| 25 |
+
matrix_to_rotation_6d,
|
| 26 |
+
rotation_6d_to_matrix,
|
| 27 |
+
axis_angle_to_matrix,
|
| 28 |
+
matrix_to_axis_angle,
|
| 29 |
+
)
|
| 30 |
+
from coda.model.diff.pipeline.mini_pipeline import Pipeline as MiniPipeline
|
| 31 |
+
from coda.model.diff.pipeline.text_pipeline import Pipeline as TextPipeline
|
| 32 |
+
from coda.model.diff.pipeline.mini_pipeline import randomly_set_null_condition
|
| 33 |
+
from coda.model.diff.utils.optimization import (
|
| 34 |
+
WholeBodyPartCondKeyLocationsLoss,
|
| 35 |
+
warmup_scheduler,
|
| 36 |
+
cosine_decay_scheduler,
|
| 37 |
+
noise_regularize_1d,
|
| 38 |
+
)
|
| 39 |
+
from coda.utils.wis3d_utils import make_wis3d, add_motion_as_lines
|
| 40 |
+
from coda.utils.smplx_utils import make_smplx
|
| 41 |
+
from coda.utils.arctic.object_tensors import ObjectTensors
|
| 42 |
+
import coda.utils.matrix as matrix
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class Pipeline(TextPipeline):
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
args,
|
| 49 |
+
args_denoiser3d,
|
| 50 |
+
args_denoiser3d_lefthand,
|
| 51 |
+
args_denoiser3d_righthand,
|
| 52 |
+
args_denoiser3d_invtraj,
|
| 53 |
+
args_denoiser3d_obj,
|
| 54 |
+
args_clip,
|
| 55 |
+
args_diffusion_optimization,
|
| 56 |
+
args_traj_optimization,
|
| 57 |
+
**kwargs,
|
| 58 |
+
):
|
| 59 |
+
super().__init__(args, args_denoiser3d, args_clip, **kwargs)
|
| 60 |
+
self.args_diffusion_optimization = args_diffusion_optimization
|
| 61 |
+
self.args_traj_optimization = args_traj_optimization
|
| 62 |
+
self.num_optim_ddim_steps = args_diffusion_optimization.num_ddim_steps
|
| 63 |
+
self.args_denoiser3d_obj = args_denoiser3d_obj
|
| 64 |
+
self.inverse_scheduler = instantiate(args.scheduler_opt_inverse)
|
| 65 |
+
# inverse_scheduler = DDIMInverseScheduler.from_pretrained('stabilityai/stable-diffusion-2-1', subfolder='scheduler')
|
| 66 |
+
self.endecoder.is_to_ayfz = False
|
| 67 |
+
|
| 68 |
+
# Networks
|
| 69 |
+
self.denoiser3d_lefthand = instantiate(args_denoiser3d_lefthand, _recursive_=False)
|
| 70 |
+
self.denoiser3d_righthand = instantiate(args_denoiser3d_righthand, _recursive_=False)
|
| 71 |
+
self.denoiser3d_invtraj = instantiate(args_denoiser3d_invtraj, _recursive_=False)
|
| 72 |
+
self.denoiser3d_obj = instantiate(args_denoiser3d_obj, _recursive_=False)
|
| 73 |
+
|
| 74 |
+
# Normalizer
|
| 75 |
+
self.endecoder_lefthand: EnDecoder = instantiate(args.lefthand_endecoder_opt, _recursive_=False)
|
| 76 |
+
self.endecoder_righthand: EnDecoder = instantiate(args.righthand_endecoder_opt, _recursive_=False)
|
| 77 |
+
self.endecoder_invtraj: EnDecoder = instantiate(args.invtraj_endecoder_opt, _recursive_=False)
|
| 78 |
+
self.endecoder_obj: EnDecoder = instantiate(args.obj_endecoder_opt, _recursive_=False)
|
| 79 |
+
|
| 80 |
+
self.object_tensor = ObjectTensors().cuda()
|
| 81 |
+
self.smplx = make_smplx(type="wholebody")
|
| 82 |
+
|
| 83 |
+
self.vis_i = 0
|
| 84 |
+
|
| 85 |
+
def set_lr(self, lr):
|
| 86 |
+
for i, param_group in enumerate(self.optimizer.param_groups):
|
| 87 |
+
param_group["lr"] = lr
|
| 88 |
+
|
| 89 |
+
@torch.enable_grad()
|
| 90 |
+
def diffusion_optim(
|
| 91 |
+
self, inputs, invtraj_outputs, obj_verts, obj_normals, is_vis=False, is_moving_obj=False, moving_obj_kwargs=None
|
| 92 |
+
):
|
| 93 |
+
self.optim_noise_body = inputs["init_noise_body"].clone().detach().requires_grad_()
|
| 94 |
+
self.optim_noise_lefthand = inputs["init_noise_lefthand"].clone().detach().requires_grad_()
|
| 95 |
+
self.optim_noise_righthand = inputs["init_noise_righthand"].clone().detach().requires_grad_()
|
| 96 |
+
self.start_noise_body = self.optim_noise_body.clone().detach()
|
| 97 |
+
self.start_noise_lefthand = self.optim_noise_lefthand.clone().detach()
|
| 98 |
+
self.start_noise_righthand = self.optim_noise_righthand.clone().detach()
|
| 99 |
+
|
| 100 |
+
B, _, _ = self.optim_noise_body.shape
|
| 101 |
+
motion_length = inputs["length"]
|
| 102 |
+
L = motion_length.max()
|
| 103 |
+
J = 62
|
| 104 |
+
target = torch.zeros((B, L, J, 3), dtype=torch.float32, device=self.optim_noise_body.device)
|
| 105 |
+
select_ind = [20, 21]
|
| 106 |
+
left_hand_ind = [25, 29, 33, 37, 41]
|
| 107 |
+
right_hand_ind = [45, 49, 53, 57, 61]
|
| 108 |
+
hand_localind = [4, 8, 12, 16, 20]
|
| 109 |
+
target_mask = torch.zeros_like(target, dtype=torch.float32, device=self.optim_noise_body.device)
|
| 110 |
+
wrist_traj = invtraj_outputs["wrist_traj_global"]
|
| 111 |
+
finger_traj = invtraj_outputs["finger_traj_global"]
|
| 112 |
+
left_finger_traj = finger_traj[..., :5, :]
|
| 113 |
+
right_finger_traj = finger_traj[..., 5:, :]
|
| 114 |
+
wrist_mask = invtraj_outputs["wrist_mask"]
|
| 115 |
+
contact_mask = invtraj_outputs["contact_mask"]
|
| 116 |
+
left_finger_mask = contact_mask[..., :5]
|
| 117 |
+
right_finger_mask = contact_mask[..., 5:]
|
| 118 |
+
|
| 119 |
+
target[..., select_ind, :] = wrist_traj
|
| 120 |
+
target[..., left_hand_ind, :] = left_finger_traj
|
| 121 |
+
target[..., right_hand_ind, :] = right_finger_traj
|
| 122 |
+
target_mask[..., select_ind, :] = wrist_mask[..., None].float()
|
| 123 |
+
target_mask[..., left_hand_ind, :] = left_finger_mask[..., None].float()
|
| 124 |
+
target_mask[..., right_hand_ind, :] = right_finger_mask[..., None].float()
|
| 125 |
+
|
| 126 |
+
# first frame
|
| 127 |
+
target[:, 0, :22, :] = inputs["gt_body_global_pos"][:, 0]
|
| 128 |
+
target[:, 0, 22:42] = inputs["gt_lefthand_global_pos"][:, 0, 1:]
|
| 129 |
+
target[:, 0, 42:] = inputs["gt_righthand_global_pos"][:, 0, 1:]
|
| 130 |
+
target_mask[:, 0] = 1.0
|
| 131 |
+
target[:, :, 0, :] = target[:, 0, 0, :]
|
| 132 |
+
|
| 133 |
+
body_endecoder = self.endecoder
|
| 134 |
+
lefthand_endecoder = self.endecoder_lefthand
|
| 135 |
+
righthand_endecoder = self.endecoder_righthand
|
| 136 |
+
loss_fn = WholeBodyPartCondKeyLocationsLoss(
|
| 137 |
+
target=target,
|
| 138 |
+
target_mask=target_mask,
|
| 139 |
+
motion_length=motion_length,
|
| 140 |
+
body_inv_transform=body_endecoder.decode,
|
| 141 |
+
lefthand_inv_transform=lefthand_endecoder.decode,
|
| 142 |
+
righthand_inv_transform=righthand_endecoder.decode,
|
| 143 |
+
use_mse_loss=False,
|
| 144 |
+
only_body_steps=self.args_diffusion_optimization.only_body_steps,
|
| 145 |
+
no_body_steps=self.args_diffusion_optimization.no_body_steps,
|
| 146 |
+
no_pene_steps=self.args_diffusion_optimization.no_pene_steps,
|
| 147 |
+
body_w=self.args_diffusion_optimization.body_w,
|
| 148 |
+
hand_w=self.args_diffusion_optimization.hand_w,
|
| 149 |
+
detach_hand_w=self.args_diffusion_optimization.detach_hand_w,
|
| 150 |
+
delta_w=self.args_diffusion_optimization.delta_w,
|
| 151 |
+
sdf_w=self.args_diffusion_optimization.sdf_w,
|
| 152 |
+
root_height_reg_w=self.args_diffusion_optimization.root_height_reg_w,
|
| 153 |
+
foot_sliding_reg_w=self.args_diffusion_optimization.foot_sliding_reg_w,
|
| 154 |
+
foot_floating_reg_w=self.args_diffusion_optimization.foot_floating_reg_w,
|
| 155 |
+
is_vis=is_vis,
|
| 156 |
+
is_moving_obj=is_moving_obj,
|
| 157 |
+
moving_obj_kwargs=moving_obj_kwargs,
|
| 158 |
+
)
|
| 159 |
+
criterion = lambda body_x, lefthand_x, righthand_x, iter: loss_fn(
|
| 160 |
+
body_x,
|
| 161 |
+
lefthand_x,
|
| 162 |
+
righthand_x,
|
| 163 |
+
left_hand_ind,
|
| 164 |
+
right_hand_ind,
|
| 165 |
+
obj_verts,
|
| 166 |
+
obj_normals,
|
| 167 |
+
self.smplx,
|
| 168 |
+
inputs,
|
| 169 |
+
iter,
|
| 170 |
+
self.vis_i,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
num_steps = self.args_diffusion_optimization.num_opt_steps
|
| 174 |
+
self.optimizer = torch.optim.Adam(
|
| 175 |
+
[self.optim_noise_body, self.optim_noise_lefthand, self.optim_noise_righthand],
|
| 176 |
+
lr=self.args_diffusion_optimization.lr,
|
| 177 |
+
)
|
| 178 |
+
self.lr_scheduler = []
|
| 179 |
+
if self.args_diffusion_optimization.lr_warm_up_steps > 0:
|
| 180 |
+
self.lr_scheduler.append(
|
| 181 |
+
lambda step: warmup_scheduler(step, self.args_diffusion_optimization.lr_warm_up_steps)
|
| 182 |
+
)
|
| 183 |
+
self.lr_scheduler.append(
|
| 184 |
+
lambda step: cosine_decay_scheduler(
|
| 185 |
+
step, self.args_diffusion_optimization.lr_decay_steps, num_steps, decay_first=False
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
self.step_count = 0
|
| 189 |
+
|
| 190 |
+
batch_size = self.optim_noise_body.shape[0]
|
| 191 |
+
prog_bar = self.get_prog_bar(num_steps, desc="Diffusion Optimization")
|
| 192 |
+
for i in range(num_steps):
|
| 193 |
+
info = {"step": [i] * batch_size}
|
| 194 |
+
|
| 195 |
+
# learning rate scheduler
|
| 196 |
+
lr_frac = 1
|
| 197 |
+
if len(self.lr_scheduler) > 0:
|
| 198 |
+
for scheduler in self.lr_scheduler:
|
| 199 |
+
lr_frac *= scheduler(self.step_count)
|
| 200 |
+
self.set_lr(self.args_diffusion_optimization.lr * lr_frac)
|
| 201 |
+
info["lr"] = [self.args_diffusion_optimization.lr * lr_frac] * batch_size
|
| 202 |
+
|
| 203 |
+
# criterion
|
| 204 |
+
pred_sample_body = body_ddim_loop_with_gradient(self.optim_noise_body, self, inputs)
|
| 205 |
+
pred_sample_lefthand = hand_ddim_loop_with_gradient(self.optim_noise_lefthand, self, inputs, is_right=False)
|
| 206 |
+
pred_sample_righthand = hand_ddim_loop_with_gradient(
|
| 207 |
+
self.optim_noise_righthand, self, inputs, is_right=True
|
| 208 |
+
)
|
| 209 |
+
loss, loss_dict = criterion(pred_sample_body, pred_sample_lefthand, pred_sample_righthand, i)
|
| 210 |
+
info["loss"] = loss.detach().cpu()
|
| 211 |
+
loss = loss.sum()
|
| 212 |
+
info.update(loss_dict)
|
| 213 |
+
|
| 214 |
+
# diff penalty
|
| 215 |
+
if self.args_diffusion_optimization.diff_penalty_scale > 0:
|
| 216 |
+
# [batch_size,]
|
| 217 |
+
body_loss_diff = (self.optim_noise_body - self.start_noise_body).norm(p=2, dim=[1, 2])
|
| 218 |
+
lefthand_loss_diff = (self.optim_noise_lefthand - self.start_noise_lefthand).norm(p=2, dim=[1, 2])
|
| 219 |
+
righthand_loss_diff = (self.optim_noise_righthand - self.start_noise_righthand).norm(p=2, dim=[1, 2])
|
| 220 |
+
loss += (
|
| 221 |
+
self.args_diffusion_optimization.diff_penalty_scale
|
| 222 |
+
* (body_loss_diff + lefthand_loss_diff + righthand_loss_diff).sum()
|
| 223 |
+
)
|
| 224 |
+
info["loss_diff"] = (body_loss_diff + lefthand_loss_diff + righthand_loss_diff).detach().cpu()
|
| 225 |
+
else:
|
| 226 |
+
info["loss_diff"] = [0] * batch_size
|
| 227 |
+
|
| 228 |
+
# decorrelate
|
| 229 |
+
body_loss_decorrelate = noise_regularize_1d(
|
| 230 |
+
self.optim_noise_body.permute(0, 2, 1)[..., None, :],
|
| 231 |
+
)
|
| 232 |
+
lefthand_loss_decorrelate = noise_regularize_1d(
|
| 233 |
+
self.optim_noise_lefthand.permute(0, 2, 1)[..., None, :],
|
| 234 |
+
)
|
| 235 |
+
righthand_loss_decorrelate = noise_regularize_1d(
|
| 236 |
+
self.optim_noise_righthand.permute(0, 2, 1)[..., None, :],
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
if i < self.args_diffusion_optimization.only_body_steps:
|
| 240 |
+
lefthand_loss_decorrelate *= 0.0
|
| 241 |
+
righthand_loss_decorrelate *= 0.0
|
| 242 |
+
|
| 243 |
+
decorrelate_loss = (
|
| 244 |
+
self.args_diffusion_optimization.decorrelate_scale
|
| 245 |
+
* (body_loss_decorrelate + lefthand_loss_decorrelate + righthand_loss_decorrelate).sum()
|
| 246 |
+
)
|
| 247 |
+
if self.args_diffusion_optimization.decorrelate_scale > 0:
|
| 248 |
+
loss += decorrelate_loss
|
| 249 |
+
info["loss_decorrelate"] = decorrelate_loss.detach().cpu()
|
| 250 |
+
else:
|
| 251 |
+
loss += decorrelate_loss * 0.0
|
| 252 |
+
info["loss_decorrelate"] = decorrelate_loss.detach().cpu() * 0.0
|
| 253 |
+
|
| 254 |
+
# backward
|
| 255 |
+
self.optimizer.zero_grad()
|
| 256 |
+
loss.backward()
|
| 257 |
+
|
| 258 |
+
# grad mode
|
| 259 |
+
self.optim_noise_body.grad.data /= self.optim_noise_body.grad.norm(p=2, dim=[1, 2], keepdim=True) + 1e-8
|
| 260 |
+
self.optim_noise_lefthand.grad.data /= (
|
| 261 |
+
self.optim_noise_lefthand.grad.norm(p=2, dim=[1, 2], keepdim=True) + 1e-8
|
| 262 |
+
)
|
| 263 |
+
self.optim_noise_righthand.grad.data /= (
|
| 264 |
+
self.optim_noise_righthand.grad.norm(p=2, dim=[1, 2], keepdim=True) + 1e-8
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# optimize z
|
| 268 |
+
self.optimizer.step()
|
| 269 |
+
|
| 270 |
+
# noise perturbation
|
| 271 |
+
# match the noise fraction to the learning rate fraction
|
| 272 |
+
noise_frac = lr_frac
|
| 273 |
+
info["perturb_scale"] = [self.args_diffusion_optimization.perturb_scale * noise_frac] * batch_size
|
| 274 |
+
|
| 275 |
+
noise_body = torch.randn_like(self.optim_noise_body)
|
| 276 |
+
noise_lefthand = torch.randn_like(self.optim_noise_lefthand)
|
| 277 |
+
noise_righthand = torch.randn_like(self.optim_noise_righthand)
|
| 278 |
+
self.optim_noise_body.data += noise_body * self.args_diffusion_optimization.perturb_scale * noise_frac
|
| 279 |
+
self.optim_noise_lefthand.data += (
|
| 280 |
+
noise_lefthand * self.args_diffusion_optimization.perturb_scale * noise_frac
|
| 281 |
+
)
|
| 282 |
+
self.optim_noise_righthand.data += (
|
| 283 |
+
noise_righthand * self.args_diffusion_optimization.perturb_scale * noise_frac
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# log the norm(z - start_z)
|
| 287 |
+
info["body_diff_norm"] = (
|
| 288 |
+
(self.optim_noise_body - self.start_noise_body).norm(p=2, dim=[1, 2]).detach().cpu()
|
| 289 |
+
)
|
| 290 |
+
info["lefthand_diff_norm"] = (
|
| 291 |
+
(self.optim_noise_lefthand - self.start_noise_lefthand).norm(p=2, dim=[1, 2]).detach().cpu()
|
| 292 |
+
)
|
| 293 |
+
info["righthand_diff_norm"] = (
|
| 294 |
+
(self.optim_noise_righthand - self.start_noise_righthand).norm(p=2, dim=[1, 2]).detach().cpu()
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
# log current z
|
| 298 |
+
info["body_z"] = self.optim_noise_body.detach().cpu()
|
| 299 |
+
info["lefthand_z"] = self.optim_noise_lefthand.detach().cpu()
|
| 300 |
+
info["righthand_z"] = self.optim_noise_righthand.detach().cpu()
|
| 301 |
+
info["pred_sample_body"] = pred_sample_body.detach().cpu()
|
| 302 |
+
info["pred_sample_lefthand"] = pred_sample_lefthand.detach().cpu()
|
| 303 |
+
info["pred_sample_righthand"] = pred_sample_righthand.detach().cpu()
|
| 304 |
+
|
| 305 |
+
self.step_count += 1
|
| 306 |
+
prog_bar.update()
|
| 307 |
+
postfix_dict = {
|
| 308 |
+
"loss": info["loss"].mean().item(),
|
| 309 |
+
"decorrelate": info["loss_decorrelate"].mean().item(),
|
| 310 |
+
"target_pos": info["target_pos_loss"].mean().item(),
|
| 311 |
+
"delta": info["delta_loss"].mean().item(),
|
| 312 |
+
"r_h_reg": info["root_height_reg_loss"].mean().item(),
|
| 313 |
+
"f_s_reg": info["foot_sliding_reg_loss"].mean().item(),
|
| 314 |
+
"f_f_reg": info["foot_floating_reg_loss"].mean().item(),
|
| 315 |
+
"lr": self.args_diffusion_optimization.lr * lr_frac,
|
| 316 |
+
}
|
| 317 |
+
if "sdf_loss" in info.keys():
|
| 318 |
+
postfix_dict["loss_sdf"] = info["sdf_loss"].mean().item()
|
| 319 |
+
prog_bar.prog_bar.set_postfix(postfix_dict)
|
| 320 |
+
|
| 321 |
+
body_outputs = self.endecoder.decode(pred_sample_body, inputs=inputs)
|
| 322 |
+
gt_body_outputs = self.endecoder.decode(self.endecoder.encode(inputs), inputs=inputs)
|
| 323 |
+
|
| 324 |
+
lefthand_inputs = {}
|
| 325 |
+
for k, v in inputs.items():
|
| 326 |
+
if k in [
|
| 327 |
+
"left_base_rotmat",
|
| 328 |
+
"left_base_pos",
|
| 329 |
+
"left_handpose",
|
| 330 |
+
"left_hand_localpos",
|
| 331 |
+
"left_handtip_localpos",
|
| 332 |
+
]:
|
| 333 |
+
lefthand_inputs[k.replace("left_", "")] = v
|
| 334 |
+
continue
|
| 335 |
+
lefthand_inputs[k] = v
|
| 336 |
+
gt_lefthand_outputs = self.endecoder_lefthand.decode(
|
| 337 |
+
self.endecoder_lefthand.encode(lefthand_inputs), inputs=lefthand_inputs
|
| 338 |
+
)
|
| 339 |
+
lefthand_inputs["base_pos"] = body_outputs["global_pos"][..., 20, :]
|
| 340 |
+
lefthand_inputs["base_rotmat"] = matrix.get_rotation(body_outputs["global_mat"])[..., 20, :, :]
|
| 341 |
+
lefthand_outputs = self.endecoder_lefthand.decode(pred_sample_lefthand, inputs=lefthand_inputs)
|
| 342 |
+
|
| 343 |
+
righthand_inputs = {}
|
| 344 |
+
for k, v in inputs.items():
|
| 345 |
+
if k in [
|
| 346 |
+
"right_base_rotmat",
|
| 347 |
+
"right_base_pos",
|
| 348 |
+
"right_handpose",
|
| 349 |
+
"right_hand_localpos",
|
| 350 |
+
"right_handtip_localpos",
|
| 351 |
+
]:
|
| 352 |
+
righthand_inputs[k.replace("right_", "")] = v
|
| 353 |
+
continue
|
| 354 |
+
righthand_inputs[k] = v
|
| 355 |
+
gt_righthand_outputs = self.endecoder_righthand.decode(
|
| 356 |
+
self.endecoder_righthand.encode(righthand_inputs), inputs=righthand_inputs
|
| 357 |
+
)
|
| 358 |
+
righthand_inputs["base_pos"] = body_outputs["global_pos"][..., 21, :]
|
| 359 |
+
righthand_inputs["base_rotmat"] = matrix.get_rotation(body_outputs["global_mat"])[..., 21, :, :]
|
| 360 |
+
righthand_outputs = self.endecoder_righthand.decode(pred_sample_righthand, inputs=righthand_inputs)
|
| 361 |
+
|
| 362 |
+
outputs = {
|
| 363 |
+
# last step's z
|
| 364 |
+
"body_z": self.optim_noise_body.detach(),
|
| 365 |
+
"lefthand_z": self.optim_noise_lefthand.detach(),
|
| 366 |
+
"righthand_z": self.optim_noise_righthand.detach(),
|
| 367 |
+
# previous steps' x
|
| 368 |
+
"body_x": pred_sample_body.detach(),
|
| 369 |
+
"lefthand_x": pred_sample_lefthand.detach(),
|
| 370 |
+
"righthand_x": pred_sample_righthand.detach(),
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
outputs["global_pos"] = body_outputs["global_pos"]
|
| 374 |
+
outputs["lefthand_global_pos"] = lefthand_outputs["tip_global_pos"]
|
| 375 |
+
outputs["righthand_global_pos"] = righthand_outputs["tip_global_pos"]
|
| 376 |
+
|
| 377 |
+
outputs["gt_output"] = {
|
| 378 |
+
"global_pos": inputs["gt_body_global_pos"],
|
| 379 |
+
"lefthand_global_pos": inputs["gt_lefthand_global_pos"],
|
| 380 |
+
"righthand_global_pos": inputs["gt_righthand_global_pos"],
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
outputs["transl"] = body_outputs["transl"]
|
| 384 |
+
outputs["global_orient"] = body_outputs["global_orient"]
|
| 385 |
+
outputs["body_pose"] = body_outputs["body_pose"]
|
| 386 |
+
outputs["left_hand_pose"] = lefthand_outputs["hand_pose"]
|
| 387 |
+
outputs["right_hand_pose"] = righthand_outputs["hand_pose"]
|
| 388 |
+
outputs["gt_output"]["transl"] = inputs["transl"]
|
| 389 |
+
outputs["gt_output"]["global_orient"] = inputs["global_orient"]
|
| 390 |
+
outputs["gt_output"]["body_pose"] = inputs["body_pose"]
|
| 391 |
+
outputs["gt_output"]["left_hand_pose"] = inputs["left_hand_pose"]
|
| 392 |
+
outputs["gt_output"]["right_hand_pose"] = inputs["right_hand_pose"]
|
| 393 |
+
|
| 394 |
+
if is_vis:
|
| 395 |
+
for i in range(B):
|
| 396 |
+
wis3d = make_wis3d(name=f"debug_wholebody_{self.vis_i:03d}")
|
| 397 |
+
beta = inputs["beta"][i]
|
| 398 |
+
l = inputs["length"][i]
|
| 399 |
+
transl = body_outputs["transl"][i]
|
| 400 |
+
body_pose = body_outputs["body_pose"][i]
|
| 401 |
+
global_orient = body_outputs["global_orient"][i]
|
| 402 |
+
left_hand_pose = lefthand_outputs["hand_pose"][i]
|
| 403 |
+
right_hand_pose = righthand_outputs["hand_pose"][i]
|
| 404 |
+
smplx_out = self.smplx(
|
| 405 |
+
transl=transl,
|
| 406 |
+
global_orient=global_orient,
|
| 407 |
+
body_pose=body_pose,
|
| 408 |
+
left_hand_pose=left_hand_pose,
|
| 409 |
+
right_hand_pose=right_hand_pose,
|
| 410 |
+
betas=beta,
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
gt_transl = inputs["transl"][i]
|
| 414 |
+
gt_global_orient = inputs["global_orient"][i]
|
| 415 |
+
gt_body_pose = inputs["body_pose"][i]
|
| 416 |
+
gt_left_hand_pose = inputs["left_hand_pose"][i]
|
| 417 |
+
gt_right_hand_pose = inputs["right_hand_pose"][i]
|
| 418 |
+
gt_smplx_out = self.smplx(
|
| 419 |
+
transl=gt_transl,
|
| 420 |
+
global_orient=gt_global_orient,
|
| 421 |
+
body_pose=gt_body_pose,
|
| 422 |
+
left_hand_pose=gt_left_hand_pose,
|
| 423 |
+
right_hand_pose=gt_right_hand_pose,
|
| 424 |
+
betas=beta,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
for j in range(transl.shape[0]):
|
| 428 |
+
wis3d.set_scene_id(j)
|
| 429 |
+
wis3d.add_mesh(smplx_out.vertices[j], self.smplx.bm.faces, name="pred_smplx")
|
| 430 |
+
wis3d.add_mesh(gt_smplx_out.vertices[j], self.smplx.bm.faces, name="gt_smplx")
|
| 431 |
+
|
| 432 |
+
return outputs
|
| 433 |
+
|
| 434 |
+
def sample_obj_instance(self, inputs, is_vis=False, GRAB_PRE_N=40, ARCTIC_PRE_N=20):
|
| 435 |
+
# Setup
|
| 436 |
+
outputs = dict()
|
| 437 |
+
enable_cfg = False if self.guidance_scale == 0 else True
|
| 438 |
+
scheduler = self.test_scheduler
|
| 439 |
+
|
| 440 |
+
max_length = inputs["length"].max()
|
| 441 |
+
B = inputs["length"].shape[0]
|
| 442 |
+
|
| 443 |
+
gt_x = self.endecoder_obj._encode(inputs)
|
| 444 |
+
gt_output = self.endecoder_obj._decode(gt_x, inputs=inputs)
|
| 445 |
+
|
| 446 |
+
# 1. Prepare target variable x, which will be denoised progressively
|
| 447 |
+
x = torch.randn((B, max_length, self.denoiser3d_obj.output_dim), device=gt_x.device)
|
| 448 |
+
|
| 449 |
+
# 2. Conditions
|
| 450 |
+
condition_dict = self.endecoder_obj.encode_condition(inputs)
|
| 451 |
+
f_condition = condition_dict
|
| 452 |
+
|
| 453 |
+
# Encode CLIP embedding
|
| 454 |
+
text = inputs["caption"]
|
| 455 |
+
|
| 456 |
+
if not enable_cfg:
|
| 457 |
+
text = ["" for _ in range(len(text))]
|
| 458 |
+
|
| 459 |
+
clip_text = self.clip.encode_text(text, enable_cfg=enable_cfg, with_projection=True) # (B, D)
|
| 460 |
+
f_condition["f_text"] = clip_text.f_text
|
| 461 |
+
|
| 462 |
+
# *. Denoising loop
|
| 463 |
+
# scheduler: timestep, extra_step_kwargs
|
| 464 |
+
scheduler.set_timesteps(self.num_inference_steps)
|
| 465 |
+
timesteps = scheduler.timesteps
|
| 466 |
+
num_warmup_steps = len(timesteps) - self.num_inference_steps * scheduler.order
|
| 467 |
+
prog_bar = self.get_prog_bar(self.num_inference_steps, desc="DDIM Sampling Obj")
|
| 468 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 469 |
+
for i, t in enumerate(timesteps):
|
| 470 |
+
# 1. Denoiser + Sampler.step
|
| 471 |
+
model_kwargs = self.build_model_kwargs(
|
| 472 |
+
x=x,
|
| 473 |
+
timesteps=t,
|
| 474 |
+
inputs=inputs,
|
| 475 |
+
f_condition=f_condition,
|
| 476 |
+
enable_cfg=enable_cfg,
|
| 477 |
+
)
|
| 478 |
+
x0_, _ = self.cfg_denoise_func(self.denoiser3d_obj, model_kwargs, scheduler, enable_cfg)
|
| 479 |
+
|
| 480 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 481 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 482 |
+
|
| 483 |
+
# *. Update and store intermediate results
|
| 484 |
+
x = xprev_
|
| 485 |
+
|
| 486 |
+
# progress bar
|
| 487 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
|
| 488 |
+
if prog_bar is not None:
|
| 489 |
+
prog_bar.update()
|
| 490 |
+
|
| 491 |
+
outputs = self.endecoder_obj.decode(x, inputs=inputs)
|
| 492 |
+
contact = outputs["contact_mask"] > 0.95 # (B, L, 1)
|
| 493 |
+
contact = contact[..., 0].float() # (B, L)
|
| 494 |
+
first_con_index = torch.argmax(contact.float(), dim=-1).item()
|
| 495 |
+
if "GRAB" in inputs["meta"][0]["dataset_id"]:
|
| 496 |
+
PRE_N = GRAB_PRE_N
|
| 497 |
+
if first_con_index <= PRE_N:
|
| 498 |
+
if first_con_index > 0:
|
| 499 |
+
new_transl = torch.zeros_like(outputs["transl"])
|
| 500 |
+
L = outputs["transl"].shape[1] - PRE_N
|
| 501 |
+
new_transl[:, PRE_N:] = outputs["transl"][:, first_con_index : first_con_index + L]
|
| 502 |
+
new_transl[:, : first_con_index - 1] = outputs["transl"][:, : first_con_index - 1]
|
| 503 |
+
new_transl[:, first_con_index - 1 : PRE_N] = outputs["transl"][
|
| 504 |
+
:, first_con_index - 1 : first_con_index
|
| 505 |
+
]
|
| 506 |
+
outputs["transl"] = new_transl
|
| 507 |
+
|
| 508 |
+
new_global_orient = torch.zeros_like(outputs["global_orient"])
|
| 509 |
+
new_global_orient[:, PRE_N:] = outputs["global_orient"][:, first_con_index : first_con_index + L]
|
| 510 |
+
new_global_orient[:, : first_con_index - 1] = outputs["global_orient"][:, : first_con_index - 1]
|
| 511 |
+
new_global_orient[:, first_con_index - 1 : PRE_N] = outputs["global_orient"][
|
| 512 |
+
:, first_con_index - 1 : first_con_index
|
| 513 |
+
]
|
| 514 |
+
outputs["global_orient"] = new_global_orient
|
| 515 |
+
|
| 516 |
+
new_objmat = torch.zeros_like(outputs["obj"])
|
| 517 |
+
new_objmat[:, PRE_N:] = outputs["obj"][:, first_con_index : first_con_index + L]
|
| 518 |
+
new_objmat[:, : first_con_index - 1] = outputs["obj"][:, : first_con_index - 1]
|
| 519 |
+
new_objmat[:, first_con_index - 1 : PRE_N] = outputs["obj"][
|
| 520 |
+
:, first_con_index - 1 : first_con_index
|
| 521 |
+
]
|
| 522 |
+
outputs["obj"] = new_objmat
|
| 523 |
+
|
| 524 |
+
contact_mask_new = torch.zeros_like(outputs["contact_mask"])
|
| 525 |
+
contact_mask_new[:, PRE_N:] = outputs["contact_mask"][:, first_con_index : first_con_index + L]
|
| 526 |
+
contact_mask_new[:, : first_con_index - 1] = outputs["contact_mask"][:, : first_con_index - 1]
|
| 527 |
+
contact_mask_new[:, first_con_index - 1 : PRE_N] = outputs["contact_mask"][
|
| 528 |
+
:, first_con_index - 1 : first_con_index
|
| 529 |
+
]
|
| 530 |
+
outputs["contact_mask"] = contact_mask_new
|
| 531 |
+
else:
|
| 532 |
+
new_transl = torch.zeros_like(outputs["transl"])
|
| 533 |
+
L = outputs["transl"].shape[1] - PRE_N
|
| 534 |
+
new_transl[:, PRE_N:] = outputs["transl"][:, first_con_index : first_con_index + L]
|
| 535 |
+
new_transl[:, :PRE_N] = outputs["transl"][:, :1]
|
| 536 |
+
outputs["transl"] = new_transl
|
| 537 |
+
|
| 538 |
+
new_global_orient = torch.zeros_like(outputs["global_orient"])
|
| 539 |
+
new_global_orient[:, PRE_N:] = outputs["global_orient"][:, first_con_index : first_con_index + L]
|
| 540 |
+
new_global_orient[:, :PRE_N] = outputs["global_orient"][:, :1]
|
| 541 |
+
outputs["global_orient"] = new_global_orient
|
| 542 |
+
|
| 543 |
+
new_objmat = torch.zeros_like(outputs["obj"])
|
| 544 |
+
new_objmat[:, PRE_N:] = outputs["obj"][:, first_con_index : first_con_index + L]
|
| 545 |
+
new_objmat[:, :PRE_N] = outputs["obj"][:, :1]
|
| 546 |
+
outputs["obj"] = new_objmat
|
| 547 |
+
|
| 548 |
+
contact_mask_new = torch.zeros_like(outputs["contact_mask"])
|
| 549 |
+
contact_mask_new[:, PRE_N:] = outputs["contact_mask"][:, first_con_index : first_con_index + L]
|
| 550 |
+
contact_mask_new[:, :PRE_N] = 0.0
|
| 551 |
+
outputs["contact_mask"] = contact_mask_new
|
| 552 |
+
elif "ARCTIC" in inputs["meta"][0]["dataset_id"]:
|
| 553 |
+
PRE_N = ARCTIC_PRE_N
|
| 554 |
+
if PRE_N > 0:
|
| 555 |
+
L = outputs["transl"].shape[1]
|
| 556 |
+
if inputs["is_start"][0]:
|
| 557 |
+
new_transl = torch.zeros_like(outputs["transl"])
|
| 558 |
+
new_transl[:, :PRE_N] = outputs["transl"][:, :1]
|
| 559 |
+
new_transl[:, PRE_N:] = outputs["transl"][:, 1 : L - PRE_N + 1]
|
| 560 |
+
outputs["transl"] = new_transl
|
| 561 |
+
|
| 562 |
+
new_global_orient = torch.zeros_like(outputs["global_orient"])
|
| 563 |
+
new_global_orient[:, :PRE_N] = outputs["global_orient"][:, :1]
|
| 564 |
+
new_global_orient[:, PRE_N:] = outputs["global_orient"][:, 1 : L - PRE_N + 1]
|
| 565 |
+
outputs["global_orient"] = new_global_orient
|
| 566 |
+
|
| 567 |
+
new_angles = torch.zeros_like(outputs["angles"])
|
| 568 |
+
new_angles[:, :PRE_N] = outputs["angles"][:, :1]
|
| 569 |
+
new_angles[:, PRE_N:] = outputs["angles"][:, 1 : L - PRE_N + 1]
|
| 570 |
+
outputs["angles"] = new_angles
|
| 571 |
+
|
| 572 |
+
new_objmat = torch.zeros_like(outputs["obj"])
|
| 573 |
+
new_objmat[:, :PRE_N] = outputs["obj"][:, :1]
|
| 574 |
+
new_objmat[:, PRE_N:] = outputs["obj"][:, 1 : L - PRE_N + 1]
|
| 575 |
+
outputs["obj"] = new_objmat
|
| 576 |
+
|
| 577 |
+
contact_mask_new = torch.zeros_like(outputs["contact_mask"])
|
| 578 |
+
contact_mask_new[:, :PRE_N] = 0.0
|
| 579 |
+
contact_mask_new[:, PRE_N:] = outputs["contact_mask"][:, 1 : L - PRE_N + 1]
|
| 580 |
+
outputs["contact_mask"] = contact_mask_new
|
| 581 |
+
|
| 582 |
+
outputs["gt_output"] = gt_output
|
| 583 |
+
return outputs
|
| 584 |
+
|
| 585 |
+
def obj_forward(self, inputs, obj_outputs):
|
| 586 |
+
|
| 587 |
+
if "ARCTIC" in inputs["meta"][0]["dataset_id"]:
|
| 588 |
+
obj_name = inputs["meta"][0]["obj_name"]
|
| 589 |
+
arctic_obj_data = {}
|
| 590 |
+
arctic_obj_data["angles"] = obj_outputs["angles"][0].cpu()
|
| 591 |
+
arctic_obj_data["transl"] = obj_outputs["transl"][0].cpu()
|
| 592 |
+
arctic_obj_data["global_orient"] = obj_outputs["global_orient"][0].cpu()
|
| 593 |
+
with torch.no_grad():
|
| 594 |
+
obj_ns = [obj_name for _ in range(arctic_obj_data["angles"].shape[0])]
|
| 595 |
+
obj_out = self.object_tensor(**arctic_obj_data, query_names=obj_ns)
|
| 596 |
+
obj_verts = obj_out["v"]
|
| 597 |
+
obj_faces = obj_out["f"][0]
|
| 598 |
+
obj_normals = obj_out["v_normal"].to(inputs["scale"].device)
|
| 599 |
+
obj_verts = obj_verts.to(inputs["scale"].device)
|
| 600 |
+
filter_obj_verts = obj_verts.clone()
|
| 601 |
+
|
| 602 |
+
basis_point = inputs["basis_point"]
|
| 603 |
+
M = basis_point.shape[-2]
|
| 604 |
+
basis_point_bottom = basis_point.clone()
|
| 605 |
+
basis_point_top = basis_point.clone() # (B, M, 3)
|
| 606 |
+
top_mask, bottom_mask = self.object_tensor.get_part_obj_mask(obj_name)
|
| 607 |
+
|
| 608 |
+
top_verts = obj_verts[..., top_mask, :]
|
| 609 |
+
bottom_verts = obj_verts[..., bottom_mask, :]
|
| 610 |
+
center = inputs["center"]
|
| 611 |
+
obj_globalmat = obj_outputs["obj"] # (B, L, 4, 4)
|
| 612 |
+
scale = inputs["scale"] # (B, 1)
|
| 613 |
+
global_obj_center = matrix.get_position_from(center[:, None], obj_globalmat) # (B, N, 3)
|
| 614 |
+
global_obj_center_mat = matrix.get_TRS(
|
| 615 |
+
matrix.get_rotation(obj_globalmat), global_obj_center
|
| 616 |
+
) # (B, N, 4, 4)
|
| 617 |
+
global_obj_center_mat = global_obj_center_mat[0] # assume batch is always 0
|
| 618 |
+
obj_local_top_verts = matrix.get_relative_position_to(top_verts, global_obj_center_mat) # (N, M, 3)
|
| 619 |
+
obj_local_bottom_verts = matrix.get_relative_position_to(bottom_verts, global_obj_center_mat) # (N, M, 3)
|
| 620 |
+
scaled_obj_local_top_verts = obj_local_top_verts / scale[0]
|
| 621 |
+
scaled_obj_local_bottom_verts = obj_local_bottom_verts / scale[0]
|
| 622 |
+
bps_bottom, bps_bottom_ind = calculate_bps(
|
| 623 |
+
basis_point_bottom, scaled_obj_local_bottom_verts, return_xyz=False
|
| 624 |
+
)
|
| 625 |
+
bps_top, bps_top_ind = calculate_bps(basis_point_top, scaled_obj_local_top_verts, return_xyz=False)
|
| 626 |
+
bps = torch.cat([bps_bottom, bps_top], dim=-1)
|
| 627 |
+
|
| 628 |
+
else:
|
| 629 |
+
obj_name = inputs["meta"][0]["obj_name"]
|
| 630 |
+
grab_path = "./inputs/grab_extracted/tools/object_meshes/contact_meshes"
|
| 631 |
+
obj_mesh = os.path.join(grab_path, f"{obj_name}.ply")
|
| 632 |
+
obj_mesh = Mesh(filename=obj_mesh)
|
| 633 |
+
obj_vtemp = np.array(obj_mesh.vertices)
|
| 634 |
+
grab_object_tensor = ObjectModel(v_template=obj_vtemp)
|
| 635 |
+
grab_object_tensor = grab_object_tensor.to(inputs["scale"].device)
|
| 636 |
+
|
| 637 |
+
grab_obj_data = {}
|
| 638 |
+
grab_obj_data["transl"] = obj_outputs["transl"][0]
|
| 639 |
+
grab_obj_data["global_orient"] = obj_outputs["global_orient"][0]
|
| 640 |
+
with torch.no_grad():
|
| 641 |
+
obj_out = grab_object_tensor(**grab_obj_data)
|
| 642 |
+
obj_verts = obj_out.vertices
|
| 643 |
+
obj_faces = obj_mesh.faces
|
| 644 |
+
N = 4096
|
| 645 |
+
filter_obj_verts = obj_verts.clone()
|
| 646 |
+
_, select_ind = sample_farthest_points(
|
| 647 |
+
torch.tensor(obj_vtemp, dtype=torch.float32, device=obj_verts.device)[None], K=N
|
| 648 |
+
)
|
| 649 |
+
select_ind = select_ind[0]
|
| 650 |
+
filter_obj_verts = filter_obj_verts[..., select_ind, :].clone()
|
| 651 |
+
obj_normals = filter_obj_verts.clone() # BUG: this is not normals
|
| 652 |
+
|
| 653 |
+
basis_point = inputs["basis_point"]
|
| 654 |
+
center = inputs["center"]
|
| 655 |
+
obj_globalmat = obj_outputs["obj"] # (B, L, 4, 4)
|
| 656 |
+
scale = inputs["scale"] # (B, 1)
|
| 657 |
+
global_obj_center = matrix.get_position_from(center[:, None], obj_globalmat) # (B, N, 3)
|
| 658 |
+
global_obj_center_mat = matrix.get_TRS(
|
| 659 |
+
matrix.get_rotation(obj_globalmat), global_obj_center
|
| 660 |
+
) # (B, N, 4, 4)
|
| 661 |
+
global_obj_center_mat = global_obj_center_mat[0] # assume batch is always 0
|
| 662 |
+
obj_local_verts = matrix.get_relative_position_to(filter_obj_verts, global_obj_center_mat) # (N, M, 3)
|
| 663 |
+
scaled_obj_local_verts = obj_local_verts / scale[0]
|
| 664 |
+
bps, bps_ind = calculate_bps(basis_point, scaled_obj_local_verts, return_xyz=False)
|
| 665 |
+
|
| 666 |
+
return obj_verts, obj_faces, obj_normals, filter_obj_verts, bps
|
| 667 |
+
|
| 668 |
+
def sample_bpstraj(self, inputs, obj_verts, obj_outputs):
|
| 669 |
+
# Setup
|
| 670 |
+
outputs = dict()
|
| 671 |
+
enable_cfg = False if self.guidance_scale == 0 else True
|
| 672 |
+
scheduler = self.test_scheduler
|
| 673 |
+
|
| 674 |
+
length = inputs["length"]
|
| 675 |
+
B = inputs["length"].shape[0]
|
| 676 |
+
|
| 677 |
+
gt_x = self.endecoder_invtraj.encode(inputs)
|
| 678 |
+
gt_output = self.endecoder_invtraj.decode(gt_x, inputs=inputs)
|
| 679 |
+
|
| 680 |
+
# 1. Prepare target variable x, which will be denoised progressively
|
| 681 |
+
x = torch.randn((B, length, self.denoiser3d_invtraj.output_dim), device=length.device)
|
| 682 |
+
|
| 683 |
+
# 2. Conditions
|
| 684 |
+
condition_dict = self.endecoder_invtraj.encode_condition(inputs, obj_outputs)
|
| 685 |
+
f_condition = condition_dict
|
| 686 |
+
|
| 687 |
+
# *. Denoising loop
|
| 688 |
+
# scheduler: timestep, extra_step_kwargs
|
| 689 |
+
scheduler.set_timesteps(self.num_inference_steps)
|
| 690 |
+
timesteps = scheduler.timesteps
|
| 691 |
+
num_warmup_steps = len(timesteps) - self.num_inference_steps * scheduler.order
|
| 692 |
+
prog_bar = self.get_prog_bar(self.num_inference_steps, desc="DDIM Sampling invtraj")
|
| 693 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 694 |
+
for i, t in enumerate(timesteps):
|
| 695 |
+
# 1. Denoiser + Sampler.step
|
| 696 |
+
model_kwargs = self.build_model_kwargs(
|
| 697 |
+
x=x,
|
| 698 |
+
timesteps=t,
|
| 699 |
+
inputs=inputs,
|
| 700 |
+
f_condition=f_condition,
|
| 701 |
+
enable_cfg=enable_cfg,
|
| 702 |
+
)
|
| 703 |
+
x0_, _ = self.cfg_denoise_func(self.denoiser3d_invtraj, model_kwargs, scheduler, enable_cfg)
|
| 704 |
+
|
| 705 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 706 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 707 |
+
|
| 708 |
+
# *. Update and store intermediate results
|
| 709 |
+
x = xprev_
|
| 710 |
+
|
| 711 |
+
# progress bar
|
| 712 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
|
| 713 |
+
if prog_bar is not None:
|
| 714 |
+
prog_bar.update()
|
| 715 |
+
|
| 716 |
+
outputs = self.endecoder_invtraj.decode(x, inputs=inputs)
|
| 717 |
+
|
| 718 |
+
CONTACT_TRESH = 0.95
|
| 719 |
+
contact = outputs["contact"]
|
| 720 |
+
# if no contact in objtraj, no finger contact
|
| 721 |
+
contact_mask = (obj_outputs["contact_mask"] > CONTACT_TRESH).float() * contact
|
| 722 |
+
contact_mask = contact_mask > CONTACT_TRESH
|
| 723 |
+
# contact_mask_bkp = contact_mask.clone()
|
| 724 |
+
for j in range(contact_mask.shape[-1]):
|
| 725 |
+
for t_ in range(contact_mask.shape[1]):
|
| 726 |
+
prev_t = max(0, t_ - 1)
|
| 727 |
+
after_t = min(contact_mask.shape[1] - 1, t_ + 1)
|
| 728 |
+
if contact_mask[0, t_, j]:
|
| 729 |
+
if contact_mask[0, prev_t, j] == 0 and contact_mask[0, after_t, j] == 0:
|
| 730 |
+
contact_mask[0, t_, j] = 0
|
| 731 |
+
outputs["contact_mask"] = contact_mask
|
| 732 |
+
left_wrist_mask = torch.any(contact_mask[..., :5], dim=-1)
|
| 733 |
+
right_wrist_mask = torch.any(contact_mask[..., 5:], dim=-1)
|
| 734 |
+
wrist_mask = torch.stack([left_wrist_mask, right_wrist_mask], dim=-1)
|
| 735 |
+
outputs["wrist_mask"] = wrist_mask
|
| 736 |
+
|
| 737 |
+
with torch.enable_grad():
|
| 738 |
+
traj_mask = torch.cat([wrist_mask, contact_mask], dim=-1) # (B, L, 12)
|
| 739 |
+
basis_point = inputs["basis_finger_point"].clone().detach() # (B, M, 3)
|
| 740 |
+
M = basis_point.shape[1]
|
| 741 |
+
center = inputs["center"] # (B, 3)
|
| 742 |
+
obj_mat = inputs["obj"] # (B, L, 2, 4, 4)
|
| 743 |
+
scale = inputs["scale"] # (B, 1)
|
| 744 |
+
global_obj_center_pos = matrix.get_position_from(center[:, None], obj_mat[..., 0, :, :]) # (B, L, 3)
|
| 745 |
+
global_obj_center_rotmat = matrix.get_rotation(obj_mat[..., 0, :, :]) # (B, L, 3, 3)
|
| 746 |
+
global_obj_center_mat = matrix.get_TRS(global_obj_center_rotmat, global_obj_center_pos) # (B, L, 4, 4)
|
| 747 |
+
B, L = obj_mat.shape[:2]
|
| 748 |
+
finger_dist = outputs["finger_dist"].clone().detach()
|
| 749 |
+
finger_dist = torch.clamp(finger_dist, min=0.0, max=10.0)
|
| 750 |
+
finger_dist = finger_dist.reshape(B, L, M, -1)
|
| 751 |
+
threshold = 10.0
|
| 752 |
+
finger_dist_mask = finger_dist < threshold
|
| 753 |
+
J = finger_dist.shape[-1]
|
| 754 |
+
|
| 755 |
+
finger_vert_dist = outputs["finger_vert_dist"].clone().detach() # (B, 10, 3)
|
| 756 |
+
|
| 757 |
+
optim_finger_traj = torch.zeros(B, L, J, 3).cuda().detach().requires_grad_()
|
| 758 |
+
|
| 759 |
+
optimizer = torch.optim.Adam([optim_finger_traj], lr=self.args_traj_optimization.lr)
|
| 760 |
+
lr_scheduler = []
|
| 761 |
+
lr_warm_up_steps = self.args_traj_optimization.lr_warm_up_steps
|
| 762 |
+
total_steps = self.args_traj_optimization.num_opt_steps
|
| 763 |
+
lr_scheduler.append(lambda step: warmup_scheduler(step, lr_warm_up_steps))
|
| 764 |
+
lr_scheduler.append(lambda step: cosine_decay_scheduler(step, total_steps, total_steps, decay_first=False))
|
| 765 |
+
|
| 766 |
+
prog_bar = self.get_prog_bar(total_steps, desc="Traj Optimization")
|
| 767 |
+
for i in range(total_steps):
|
| 768 |
+
# set lr
|
| 769 |
+
lr_frac = 1
|
| 770 |
+
if len(lr_scheduler) > 0:
|
| 771 |
+
for scheduler in lr_scheduler:
|
| 772 |
+
lr_frac *= scheduler(i)
|
| 773 |
+
lr = self.args_traj_optimization.lr * lr_frac
|
| 774 |
+
for _, param_group in enumerate(optimizer.param_groups):
|
| 775 |
+
param_group["lr"] = lr
|
| 776 |
+
|
| 777 |
+
optim_finger_delta_pos = (
|
| 778 |
+
basis_point[:, None, :, None] - optim_finger_traj[:, :, None]
|
| 779 |
+
) # (B, L, M, J, 3)
|
| 780 |
+
optim_finger_delta_dist = torch.norm(optim_finger_delta_pos, dim=-1) # (B, L, M, J)
|
| 781 |
+
|
| 782 |
+
loss_bps = (
|
| 783 |
+
(optim_finger_delta_dist - finger_dist) * traj_mask[:, :, None] * finger_dist_mask
|
| 784 |
+
) # (B, L, M, J)
|
| 785 |
+
loss_bps = loss_bps.abs() # (B, L, M, J)
|
| 786 |
+
loss_bps = loss_bps.mean()
|
| 787 |
+
|
| 788 |
+
unscale_optim_finger_traj = optim_finger_traj * scale[:, None, None] # (B, L, J, 3)
|
| 789 |
+
global_optim_finger_traj = matrix.get_position_from(
|
| 790 |
+
unscale_optim_finger_traj, global_obj_center_mat
|
| 791 |
+
) # (B, L, J, 3)
|
| 792 |
+
global_optim_finger_traj = global_optim_finger_traj[..., 2:, :] # only fingertip
|
| 793 |
+
# obj_verts: (L, M, 3)
|
| 794 |
+
optim_finger_vert_dist = (
|
| 795 |
+
global_optim_finger_traj[..., None, :] - obj_verts[None, :, None]
|
| 796 |
+
) # (B, L, J, M, 3)
|
| 797 |
+
optim_finger_vert_dist = torch.norm(optim_finger_vert_dist, dim=-1) # (B, L, J, M)
|
| 798 |
+
optim_finger_vert_dist = optim_finger_vert_dist.min(dim=-1)[0] # (B, L, J)
|
| 799 |
+
loss_vert_dist = (finger_vert_dist - optim_finger_vert_dist) * traj_mask[..., 2:] # (B, L, J)
|
| 800 |
+
loss_vert_dist = loss_vert_dist.abs()
|
| 801 |
+
loss_vert_dist = loss_vert_dist.mean()
|
| 802 |
+
|
| 803 |
+
vert_dist_w = 0.0 if i > 300 else 0.0
|
| 804 |
+
loss = loss_bps + vert_dist_w * loss_vert_dist
|
| 805 |
+
# print(f"{i:03d}: loss_bps: {loss_bps.item()}, loss_vert_dist: {loss_vert_dist.item()}, loss: {loss.item()}")
|
| 806 |
+
|
| 807 |
+
optimizer.zero_grad()
|
| 808 |
+
loss.backward()
|
| 809 |
+
optimizer.step()
|
| 810 |
+
|
| 811 |
+
if prog_bar is not None:
|
| 812 |
+
prog_bar.update()
|
| 813 |
+
prog_bar.prog_bar.set_postfix(
|
| 814 |
+
{
|
| 815 |
+
"loss": loss.item(),
|
| 816 |
+
"loss_bps": loss_bps.item(),
|
| 817 |
+
"loss_vert_dist": loss_vert_dist.item(),
|
| 818 |
+
"lr": lr,
|
| 819 |
+
}
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
unscale_optim_finger_traj = optim_finger_traj.clone().detach() * scale[:, None, None] # (B, L, J, 3)
|
| 823 |
+
global_optim_finger_traj = matrix.get_position_from(unscale_optim_finger_traj, global_obj_center_mat)
|
| 824 |
+
|
| 825 |
+
outputs["wrist_traj_global"] = global_optim_finger_traj[..., :2, :]
|
| 826 |
+
outputs["finger_traj_global"] = global_optim_finger_traj[..., 2:, :]
|
| 827 |
+
|
| 828 |
+
outputs["gt_output"] = gt_output
|
| 829 |
+
outputs["gt_output"]["wrist_traj_global"] = get_wrist_trajectory(inputs["humanoid"])
|
| 830 |
+
gt_left_finger_traj = get_finger_trajectory(inputs["humanoid"], is_right=False, istip=True)
|
| 831 |
+
gt_right_finger_traj = get_finger_trajectory(inputs["humanoid"], is_right=True, istip=True)
|
| 832 |
+
outputs["gt_output"]["finger_traj_global"] = torch.cat([gt_left_finger_traj, gt_right_finger_traj], dim=-2)
|
| 833 |
+
|
| 834 |
+
contact_mask = outputs["contact_mask"].clone()
|
| 835 |
+
wrist_mask = outputs["wrist_mask"].clone()
|
| 836 |
+
wrist_traj_global = outputs["wrist_traj_global"].clone()
|
| 837 |
+
finger_traj_global = outputs["finger_traj_global"].clone()
|
| 838 |
+
|
| 839 |
+
finger_obj_dist = torch.norm(
|
| 840 |
+
global_optim_finger_traj - global_obj_center_pos[..., None, :], dim=-1
|
| 841 |
+
) # (B, L, J)
|
| 842 |
+
for i in range(finger_obj_dist.shape[0]):
|
| 843 |
+
for j in range(finger_obj_dist.shape[1]):
|
| 844 |
+
for k in range(finger_obj_dist.shape[2]):
|
| 845 |
+
if finger_obj_dist[i, j, k] > 0.5:
|
| 846 |
+
if k == 0:
|
| 847 |
+
wrist_mask[i, j, k] = False
|
| 848 |
+
contact_mask[i, j, :5] = False
|
| 849 |
+
wrist_traj_global[i, j, k] = 0.0
|
| 850 |
+
finger_traj_global[i, j, :5] = 0.0
|
| 851 |
+
elif k == 1:
|
| 852 |
+
wrist_mask[i, j, k] = False
|
| 853 |
+
contact_mask[i, j, 5:] = False
|
| 854 |
+
wrist_traj_global[i, j, k] = 0.0
|
| 855 |
+
finger_traj_global[i, j, 5:] = 0.0
|
| 856 |
+
else:
|
| 857 |
+
contact_mask[i, j, k - 2] = False
|
| 858 |
+
finger_traj_global[i, j, k - 2] = 0.0
|
| 859 |
+
|
| 860 |
+
outputs["contact_mask"] = contact_mask
|
| 861 |
+
outputs["wrist_traj_global"] = wrist_traj_global
|
| 862 |
+
outputs["finger_traj_global"] = finger_traj_global
|
| 863 |
+
return outputs
|
| 864 |
+
|
| 865 |
+
def sample_hand_instance(self, inputs, is_right=False, is_vis=False):
|
| 866 |
+
# Setup
|
| 867 |
+
outputs = dict()
|
| 868 |
+
enable_cfg = False if self.guidance_scale == 0 else True
|
| 869 |
+
scheduler = self.test_scheduler
|
| 870 |
+
|
| 871 |
+
if is_right:
|
| 872 |
+
denoiser3d = self.denoiser3d_righthand
|
| 873 |
+
endecoder = self.endecoder_righthand
|
| 874 |
+
else:
|
| 875 |
+
denoiser3d = self.denoiser3d_lefthand
|
| 876 |
+
endecoder = self.endecoder_lefthand
|
| 877 |
+
|
| 878 |
+
max_length = inputs["length"].max()
|
| 879 |
+
max_length = max(inputs["transl"].shape[1], max_length)
|
| 880 |
+
B = inputs["length"].shape[0]
|
| 881 |
+
hand_inputs = {}
|
| 882 |
+
for k, v in inputs.items():
|
| 883 |
+
if is_right:
|
| 884 |
+
if k in [
|
| 885 |
+
"right_base_rotmat",
|
| 886 |
+
"right_base_pos",
|
| 887 |
+
"right_handpose",
|
| 888 |
+
"right_hand_localpos",
|
| 889 |
+
"right_handtip_localpos",
|
| 890 |
+
]:
|
| 891 |
+
hand_inputs[k.replace("right_", "")] = v.clone()
|
| 892 |
+
continue
|
| 893 |
+
else:
|
| 894 |
+
if k in [
|
| 895 |
+
"left_base_rotmat",
|
| 896 |
+
"left_base_pos",
|
| 897 |
+
"left_handpose",
|
| 898 |
+
"left_hand_localpos",
|
| 899 |
+
"left_handtip_localpos",
|
| 900 |
+
]:
|
| 901 |
+
hand_inputs[k.replace("left_", "")] = v.clone()
|
| 902 |
+
continue
|
| 903 |
+
hand_inputs[k] = v
|
| 904 |
+
|
| 905 |
+
gt_x = endecoder._encode(hand_inputs)
|
| 906 |
+
gt_output = endecoder._decode(gt_x, inputs=hand_inputs)
|
| 907 |
+
|
| 908 |
+
# 1. Prepare target variable x, which will be denoised progressively
|
| 909 |
+
if endecoder.vae is None:
|
| 910 |
+
x = torch.randn((B, max_length, denoiser3d.output_dim), device=gt_x.device)
|
| 911 |
+
else:
|
| 912 |
+
x = torch.randn((B, denoiser3d.latent_size, denoiser3d.latent_dim), device=gt_x.device)
|
| 913 |
+
init_noise = x.clone()
|
| 914 |
+
|
| 915 |
+
# 2. Conditions
|
| 916 |
+
condition_dict = endecoder.encode_condition(hand_inputs)
|
| 917 |
+
f_condition = condition_dict
|
| 918 |
+
|
| 919 |
+
# *. Denoising loop
|
| 920 |
+
# scheduler: timestep, extra_step_kwargs
|
| 921 |
+
scheduler.set_timesteps(self.num_inference_steps)
|
| 922 |
+
timesteps = scheduler.timesteps
|
| 923 |
+
num_warmup_steps = len(timesteps) - self.num_inference_steps * scheduler.order
|
| 924 |
+
prefix = "right" if is_right else "left"
|
| 925 |
+
prog_bar = self.get_prog_bar(self.num_inference_steps, desc=f"DDIM Sampling {prefix}hand")
|
| 926 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 927 |
+
for i, t in enumerate(timesteps):
|
| 928 |
+
# 1. Denoiser + Sampler.step
|
| 929 |
+
model_kwargs = self.build_model_kwargs(
|
| 930 |
+
x=x,
|
| 931 |
+
timesteps=t,
|
| 932 |
+
inputs=hand_inputs,
|
| 933 |
+
f_condition=f_condition,
|
| 934 |
+
enable_cfg=enable_cfg,
|
| 935 |
+
)
|
| 936 |
+
x0_, _ = self.cfg_denoise_func(denoiser3d, model_kwargs, scheduler, enable_cfg)
|
| 937 |
+
|
| 938 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 939 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 940 |
+
|
| 941 |
+
# *. Update and store intermediate results
|
| 942 |
+
x = xprev_
|
| 943 |
+
|
| 944 |
+
# progress bar
|
| 945 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
|
| 946 |
+
if prog_bar is not None:
|
| 947 |
+
prog_bar.update()
|
| 948 |
+
|
| 949 |
+
outputs = endecoder.decode(x, inputs=hand_inputs)
|
| 950 |
+
outputs["init_noise"] = init_noise
|
| 951 |
+
outputs["pred_sample"] = x
|
| 952 |
+
outputs["gt_output"] = gt_output
|
| 953 |
+
|
| 954 |
+
if is_vis:
|
| 955 |
+
for i in range(1):
|
| 956 |
+
wis3d = make_wis3d(name=f"debug_wholebody_{i:03d}")
|
| 957 |
+
l = hand_inputs["length"][i]
|
| 958 |
+
pred_motion = outputs["tip_global_pos"][i]
|
| 959 |
+
gt_motion = outputs["gt_output"]["tip_global_pos"][i]
|
| 960 |
+
pred_motion[l:] = pred_motion[l - 1 : l]
|
| 961 |
+
gt_motion[l:] = gt_motion[l - 1 : l]
|
| 962 |
+
prefix = "right" if is_right else "left"
|
| 963 |
+
add_motion_as_lines(
|
| 964 |
+
pred_motion, wis3d, name=f"pred-{prefix}hand-ddpm", skeleton_type="handtip", radius=0.005
|
| 965 |
+
)
|
| 966 |
+
add_motion_as_lines(gt_motion, wis3d, name=f"gt-{prefix}hand", skeleton_type="handtip", radius=0.005)
|
| 967 |
+
return outputs
|
| 968 |
+
|
| 969 |
+
def sample_body_instance(self, inputs, is_vis=False):
|
| 970 |
+
# Setup
|
| 971 |
+
outputs = dict()
|
| 972 |
+
enable_cfg = False if self.guidance_scale == 0 else True
|
| 973 |
+
scheduler = self.test_scheduler
|
| 974 |
+
|
| 975 |
+
max_length = inputs["length"].max()
|
| 976 |
+
max_length = max(inputs["transl"].shape[1], max_length)
|
| 977 |
+
B = inputs["length"].shape[0]
|
| 978 |
+
body_inputs = {}
|
| 979 |
+
for k, v in inputs.items():
|
| 980 |
+
if k == "beta":
|
| 981 |
+
# this makes smplx shape different, but we use skeleton in endecoder, so it is fine.
|
| 982 |
+
body_inputs[k] = v[..., :10]
|
| 983 |
+
else:
|
| 984 |
+
body_inputs[k] = v
|
| 985 |
+
|
| 986 |
+
# will make foot at ground, cause slightly height difference here for gt.
|
| 987 |
+
gt_x = self.endecoder._encode(body_inputs)
|
| 988 |
+
gt_output = self.endecoder._decode(gt_x, inputs=body_inputs)
|
| 989 |
+
|
| 990 |
+
# 1. Prepare target variable x, which will be denoised progressively
|
| 991 |
+
if self.endecoder.vae is None:
|
| 992 |
+
x = torch.randn((B, max_length, self.denoiser3d.output_dim), device=gt_x.device)
|
| 993 |
+
else:
|
| 994 |
+
x = torch.randn((B, self.denoiser3d.latent_size, self.denoiser3d.latent_dim), device=gt_x.device)
|
| 995 |
+
init_noise = x.clone()
|
| 996 |
+
|
| 997 |
+
# 2. Conditions
|
| 998 |
+
condition_dict = self.endecoder.encode_condition(body_inputs)
|
| 999 |
+
f_condition = condition_dict
|
| 1000 |
+
|
| 1001 |
+
# Encode CLIP embedding
|
| 1002 |
+
text = body_inputs["caption"]
|
| 1003 |
+
|
| 1004 |
+
if not enable_cfg:
|
| 1005 |
+
text = ["" for _ in range(len(text))]
|
| 1006 |
+
|
| 1007 |
+
clip_text = self.clip.encode_text(text, enable_cfg=enable_cfg, with_projection=True) # (B, D)
|
| 1008 |
+
f_condition["f_text"] = clip_text.f_text
|
| 1009 |
+
|
| 1010 |
+
# *. Denoising loop
|
| 1011 |
+
# scheduler: timestep, extra_step_kwargs
|
| 1012 |
+
scheduler.set_timesteps(self.num_inference_steps)
|
| 1013 |
+
timesteps = scheduler.timesteps
|
| 1014 |
+
num_warmup_steps = len(timesteps) - self.num_inference_steps * scheduler.order
|
| 1015 |
+
prog_bar = self.get_prog_bar(self.num_inference_steps, desc="DDIM Sampling body")
|
| 1016 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 1017 |
+
for i, t in enumerate(timesteps):
|
| 1018 |
+
# 1. Denoiser + Sampler.step
|
| 1019 |
+
model_kwargs = self.build_model_kwargs(
|
| 1020 |
+
x=x,
|
| 1021 |
+
timesteps=t,
|
| 1022 |
+
inputs=body_inputs,
|
| 1023 |
+
f_condition=f_condition,
|
| 1024 |
+
enable_cfg=enable_cfg,
|
| 1025 |
+
)
|
| 1026 |
+
x0_, _ = self.cfg_denoise_func(self.denoiser3d, model_kwargs, scheduler, enable_cfg)
|
| 1027 |
+
|
| 1028 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 1029 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 1030 |
+
|
| 1031 |
+
# *. Update and store intermediate results
|
| 1032 |
+
x = xprev_
|
| 1033 |
+
|
| 1034 |
+
# progress bar
|
| 1035 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % scheduler.order == 0):
|
| 1036 |
+
if prog_bar is not None:
|
| 1037 |
+
prog_bar.update()
|
| 1038 |
+
|
| 1039 |
+
outputs = self.endecoder.decode(x, inputs=body_inputs)
|
| 1040 |
+
outputs["init_noise"] = init_noise
|
| 1041 |
+
outputs["pred_sample"] = x
|
| 1042 |
+
outputs["gt_output"] = gt_output
|
| 1043 |
+
|
| 1044 |
+
if is_vis:
|
| 1045 |
+
for i in range(1):
|
| 1046 |
+
wis3d = make_wis3d(name=f"debug_wholebody_{self.vis_i:03d}")
|
| 1047 |
+
text_ = body_inputs["caption"][i]
|
| 1048 |
+
l = body_inputs["length"][i]
|
| 1049 |
+
pred_motion = outputs["global_pos"][i]
|
| 1050 |
+
gt_motion = outputs["gt_output"]["global_pos"][i]
|
| 1051 |
+
pred_motion[l:] = pred_motion[l - 1 : l]
|
| 1052 |
+
gt_motion[l:] = gt_motion[l - 1 : l]
|
| 1053 |
+
add_motion_as_lines(pred_motion, wis3d, name=f"pred-{text_}-ddpm")
|
| 1054 |
+
add_motion_as_lines(gt_motion, wis3d, name=f"gt-{text_}", radius=0.005)
|
| 1055 |
+
return outputs
|
| 1056 |
+
|
| 1057 |
+
# ========== Sample ========== #
|
| 1058 |
+
def forward_sample(self, inputs, is_vis=False):
|
| 1059 |
+
is_vis = False
|
| 1060 |
+
|
| 1061 |
+
obj_outputs = self.sample_obj_instance(inputs, is_vis=is_vis, ARCTIC_PRE_N=20)
|
| 1062 |
+
|
| 1063 |
+
obj_verts, obj_faces, obj_normals, filter_obj_verts, input_bps = self.obj_forward(inputs, obj_outputs)
|
| 1064 |
+
gt_obj_verts, gt_obj_faces, gt_obj_normals, gt_filter_obj_verts, gt_input_bps = self.obj_forward(
|
| 1065 |
+
inputs, obj_outputs["gt_output"]
|
| 1066 |
+
)
|
| 1067 |
+
|
| 1068 |
+
if is_vis:
|
| 1069 |
+
wis3d = make_wis3d(name=f"debug_wholebody_{self.vis_i:03d}")
|
| 1070 |
+
for i in range(obj_verts.shape[0]):
|
| 1071 |
+
wis3d.set_scene_id(i)
|
| 1072 |
+
wis3d.add_mesh(obj_verts[i], obj_faces, name="ori_obj")
|
| 1073 |
+
wis3d.add_mesh(gt_obj_verts[i], gt_obj_faces, name="gt_obj")
|
| 1074 |
+
|
| 1075 |
+
body_outputs = self.sample_body_instance(inputs, is_vis=is_vis)
|
| 1076 |
+
lefthand_outputs = self.sample_hand_instance(inputs, is_right=False, is_vis=is_vis)
|
| 1077 |
+
righthand_outputs = self.sample_hand_instance(inputs, is_right=True, is_vis=is_vis)
|
| 1078 |
+
|
| 1079 |
+
obj_inputs = {}
|
| 1080 |
+
obj_inputs["length"] = inputs["length"]
|
| 1081 |
+
obj_inputs["obj"] = obj_outputs["obj"][..., None, :, :] # (B, N, 4, 4) -> (B, N, 1, 4, 4)
|
| 1082 |
+
obj_inputs["obj_frame0"] = inputs["obj_frame0"]
|
| 1083 |
+
obj_inputs["scale"] = inputs["scale"]
|
| 1084 |
+
obj_inputs["center"] = inputs["center"]
|
| 1085 |
+
if "angles" in obj_outputs:
|
| 1086 |
+
obj_inputs["angles"] = obj_outputs["angles"]
|
| 1087 |
+
obj_inputs["transl"] = obj_outputs["transl"]
|
| 1088 |
+
obj_inputs["beta"] = inputs["beta"]
|
| 1089 |
+
obj_inputs["bps"] = input_bps[None] # (B, N, M)
|
| 1090 |
+
obj_inputs["basis_finger_point"] = inputs["basis_finger_point"]
|
| 1091 |
+
|
| 1092 |
+
obj_inputs["contact"] = inputs["contact"]
|
| 1093 |
+
obj_inputs["finger_dist"] = inputs["finger_dist"]
|
| 1094 |
+
obj_inputs["finger_vert_dist"] = inputs["finger_vert_dist"]
|
| 1095 |
+
obj_inputs["humanoid"] = inputs["humanoid"]
|
| 1096 |
+
|
| 1097 |
+
invtraj_outputs = self.sample_bpstraj(obj_inputs, filter_obj_verts, obj_outputs)
|
| 1098 |
+
invtraj_outputs["obj"] = obj_outputs["obj"]
|
| 1099 |
+
|
| 1100 |
+
if is_vis:
|
| 1101 |
+
gt_wrist_traj = invtraj_outputs["gt_output"]["wrist_traj_global"][0]
|
| 1102 |
+
gt_finger_traj = invtraj_outputs["gt_output"]["finger_traj_global"][0]
|
| 1103 |
+
wrist_traj = invtraj_outputs["wrist_traj_global"][0]
|
| 1104 |
+
finger_traj = invtraj_outputs["finger_traj_global"][0]
|
| 1105 |
+
wis3d = make_wis3d(name=f"debug_wholebody_{self.vis_i:03d}")
|
| 1106 |
+
for i in range(gt_wrist_traj.shape[0]):
|
| 1107 |
+
wis3d.set_scene_id(i)
|
| 1108 |
+
prefix = ""
|
| 1109 |
+
wis3d.add_point_cloud(gt_wrist_traj[i, [0]], name="gt_left_wrist_traj")
|
| 1110 |
+
wis3d.add_point_cloud(gt_wrist_traj[i, [1]], name="gt_right_wrist_traj")
|
| 1111 |
+
wis3d.add_point_cloud(wrist_traj[i, [0]], name=f"{prefix}reverse_bps_left_wrist_traj")
|
| 1112 |
+
wis3d.add_point_cloud(wrist_traj[i, [1]], name=f"{prefix}reverse_bps_right_wrist_traj")
|
| 1113 |
+
wis3d.add_point_cloud(gt_finger_traj[i, :5], name="gt_left_finger_traj")
|
| 1114 |
+
wis3d.add_point_cloud(gt_finger_traj[i, 5:], name="gt_right_finger_traj")
|
| 1115 |
+
wis3d.add_point_cloud(finger_traj[i, :5], name=f"{prefix}reverse_bps_left_finger_traj")
|
| 1116 |
+
wis3d.add_point_cloud(finger_traj[i, 5:], name=f"{prefix}reverse_bps_right_finger_traj")
|
| 1117 |
+
|
| 1118 |
+
center = inputs["center"] # (B, 3)
|
| 1119 |
+
obj_mat = obj_outputs["obj"][..., None, :, :] # (B, L, 1, 4, 4)
|
| 1120 |
+
global_obj_center_pos = matrix.get_position_from(center[:, None], obj_mat[..., 0, :, :]) # (B, L, 3)
|
| 1121 |
+
obj_local_verts = obj_verts - global_obj_center_pos[0, :, None] # (L, M, 3)
|
| 1122 |
+
obj_verts = obj_local_verts + global_obj_center_pos[0, :, None] # (L, M, 3)
|
| 1123 |
+
|
| 1124 |
+
if is_vis:
|
| 1125 |
+
wis3d = make_wis3d(name=f"debug_wholebody_{self.vis_i:03d}")
|
| 1126 |
+
for i in range(obj_verts.shape[0]):
|
| 1127 |
+
wis3d.set_scene_id(i)
|
| 1128 |
+
wis3d.add_mesh(obj_verts[i], obj_faces, name="obj")
|
| 1129 |
+
|
| 1130 |
+
body_pred_sample = body_outputs["pred_sample"]
|
| 1131 |
+
lefthand_pred_sample = lefthand_outputs["pred_sample"]
|
| 1132 |
+
righthand_pred_sample = righthand_outputs["pred_sample"]
|
| 1133 |
+
inputs["init_noise_body"] = torch.randn_like(body_pred_sample)
|
| 1134 |
+
inputs["init_noise_lefthand"] = torch.randn_like(lefthand_pred_sample)
|
| 1135 |
+
inputs["init_noise_righthand"] = torch.randn_like(righthand_pred_sample)
|
| 1136 |
+
|
| 1137 |
+
inputs["gt_body_global_pos"] = body_outputs["gt_output"]["global_pos"]
|
| 1138 |
+
inputs["gt_lefthand_global_pos"] = lefthand_outputs["gt_output"]["tip_global_pos"]
|
| 1139 |
+
inputs["gt_righthand_global_pos"] = righthand_outputs["gt_output"]["tip_global_pos"]
|
| 1140 |
+
torch.cuda.empty_cache()
|
| 1141 |
+
|
| 1142 |
+
outputs = self.diffusion_optim(
|
| 1143 |
+
inputs, invtraj_outputs, filter_obj_verts[None], obj_normals[None], is_vis=is_vis
|
| 1144 |
+
)
|
| 1145 |
+
|
| 1146 |
+
outputs["target_finger_traj"] = invtraj_outputs["finger_traj_global"]
|
| 1147 |
+
outputs["target_wrist_traj"] = invtraj_outputs["wrist_traj_global"]
|
| 1148 |
+
outputs["gt_output"]["finger_traj_global"] = invtraj_outputs["gt_output"]["finger_traj_global"]
|
| 1149 |
+
outputs["gt_output"]["wrist_traj_global"] = invtraj_outputs["gt_output"]["wrist_traj_global"]
|
| 1150 |
+
outputs["invtraj_outputs"] = invtraj_outputs
|
| 1151 |
+
|
| 1152 |
+
outputs["obj"] = obj_outputs["obj"]
|
| 1153 |
+
if "angles" in obj_outputs:
|
| 1154 |
+
outputs["obj_angles"] = obj_outputs["angles"]
|
| 1155 |
+
outputs["obj_global_orient"] = obj_outputs["global_orient"]
|
| 1156 |
+
outputs["obj_transl"] = obj_outputs["transl"]
|
| 1157 |
+
|
| 1158 |
+
if is_vis:
|
| 1159 |
+
pass
|
| 1160 |
+
# raise NotImplementedError
|
| 1161 |
+
self.vis_i += 1
|
| 1162 |
+
return outputs
|
| 1163 |
+
|
| 1164 |
+
def load_pretrained_model(self, ckpt_path):
|
| 1165 |
+
main_ckpt_path = ckpt_path["body"]
|
| 1166 |
+
invtraj_ckpt_path = ckpt_path["invtraj"]
|
| 1167 |
+
obj_ckpt_path = ckpt_path["obj"]
|
| 1168 |
+
lefthand_ckpt_path = ckpt_path.get("lefthand", None)
|
| 1169 |
+
righthand_ckpt_path = ckpt_path.get("righthand", None)
|
| 1170 |
+
|
| 1171 |
+
body_state_dict = torch.load(main_ckpt_path, "cpu")["state_dict"]
|
| 1172 |
+
|
| 1173 |
+
new_state_dict = {}
|
| 1174 |
+
for k, v in body_state_dict.items():
|
| 1175 |
+
new_state_dict[k] = v
|
| 1176 |
+
if lefthand_ckpt_path is not None:
|
| 1177 |
+
lefthand_state_dict = torch.load(lefthand_ckpt_path, "cpu")["state_dict"]
|
| 1178 |
+
for k, v in lefthand_state_dict.items():
|
| 1179 |
+
new_state_dict[k.replace("denoiser3d", "denoiser3d_lefthand")] = v
|
| 1180 |
+
if righthand_ckpt_path is not None:
|
| 1181 |
+
righthand_state_dict = torch.load(righthand_ckpt_path, "cpu")["state_dict"]
|
| 1182 |
+
for k, v in righthand_state_dict.items():
|
| 1183 |
+
new_state_dict[k.replace("denoiser3d", "denoiser3d_righthand")] = v
|
| 1184 |
+
invtraj_state_dict = torch.load(invtraj_ckpt_path, "cpu")["state_dict"]
|
| 1185 |
+
for k, v in invtraj_state_dict.items():
|
| 1186 |
+
new_state_dict[k.replace("denoiser3d", "denoiser3d_invtraj")] = v
|
| 1187 |
+
obj_state_dict = torch.load(obj_ckpt_path, "cpu")["state_dict"]
|
| 1188 |
+
for k, v in obj_state_dict.items():
|
| 1189 |
+
new_state_dict[k.replace("denoiser3d", "denoiser3d_obj")] = v
|
| 1190 |
+
|
| 1191 |
+
state_dict = new_state_dict
|
| 1192 |
+
return state_dict
|
| 1193 |
+
|
| 1194 |
+
|
| 1195 |
+
@torch.enable_grad()
|
| 1196 |
+
def body_ddim_loop_with_gradient(init_noise, pipeline, inputs):
|
| 1197 |
+
# Setup
|
| 1198 |
+
outputs = dict()
|
| 1199 |
+
enable_cfg = False if pipeline.guidance_scale == 0 else True
|
| 1200 |
+
scheduler = pipeline.test_scheduler
|
| 1201 |
+
|
| 1202 |
+
max_length = inputs["length"].max()
|
| 1203 |
+
max_length = max(inputs["transl"].shape[1], max_length)
|
| 1204 |
+
B = inputs["length"].shape[0]
|
| 1205 |
+
body_inputs = {}
|
| 1206 |
+
for k, v in inputs.items():
|
| 1207 |
+
if k == "beta":
|
| 1208 |
+
body_inputs[k] = v[..., :10]
|
| 1209 |
+
else:
|
| 1210 |
+
body_inputs[k] = v
|
| 1211 |
+
|
| 1212 |
+
x = init_noise
|
| 1213 |
+
|
| 1214 |
+
# 2. Conditions
|
| 1215 |
+
condition_dict = pipeline.endecoder.encode_condition(body_inputs)
|
| 1216 |
+
f_condition = condition_dict
|
| 1217 |
+
# use zero condition
|
| 1218 |
+
for k in f_condition.keys():
|
| 1219 |
+
f_condition[k] = torch.zeros_like(f_condition[k])
|
| 1220 |
+
|
| 1221 |
+
# Encode CLIP embedding
|
| 1222 |
+
text = body_inputs["caption"]
|
| 1223 |
+
|
| 1224 |
+
if not enable_cfg:
|
| 1225 |
+
text = ["" for _ in range(len(text))]
|
| 1226 |
+
|
| 1227 |
+
# Follow DNO, do not use text during optimization
|
| 1228 |
+
text = ["" for _ in range(len(text))]
|
| 1229 |
+
|
| 1230 |
+
clip_text = pipeline.clip.encode_text(text, enable_cfg=enable_cfg, with_projection=True) # (B, D)
|
| 1231 |
+
f_condition["f_text"] = clip_text.f_text
|
| 1232 |
+
|
| 1233 |
+
# *. Denoising loop
|
| 1234 |
+
# scheduler: timestep, extra_step_kwargs
|
| 1235 |
+
scheduler.set_timesteps(pipeline.num_optim_ddim_steps)
|
| 1236 |
+
timesteps = scheduler.timesteps
|
| 1237 |
+
num_warmup_steps = len(timesteps) - pipeline.num_optim_ddim_steps * scheduler.order
|
| 1238 |
+
extra_step_kwargs = pipeline.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 1239 |
+
for i, t in enumerate(timesteps):
|
| 1240 |
+
# 1. Denoiser + Sampler.step
|
| 1241 |
+
model_kwargs = pipeline.build_model_kwargs(
|
| 1242 |
+
x=x,
|
| 1243 |
+
timesteps=t,
|
| 1244 |
+
inputs=body_inputs,
|
| 1245 |
+
f_condition=f_condition,
|
| 1246 |
+
enable_cfg=enable_cfg,
|
| 1247 |
+
)
|
| 1248 |
+
x0_, _ = pipeline.cfg_denoise_func(pipeline.denoiser3d, model_kwargs, scheduler, enable_cfg)
|
| 1249 |
+
|
| 1250 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 1251 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 1252 |
+
|
| 1253 |
+
# *. Update and store intermediate results
|
| 1254 |
+
x = xprev_
|
| 1255 |
+
return x
|
| 1256 |
+
|
| 1257 |
+
|
| 1258 |
+
@torch.enable_grad()
|
| 1259 |
+
def hand_ddim_loop_with_gradient(init_noise, pipeline, inputs, is_right=False):
|
| 1260 |
+
# Setup
|
| 1261 |
+
enable_cfg = False if pipeline.guidance_scale == 0 else True
|
| 1262 |
+
scheduler = pipeline.test_scheduler
|
| 1263 |
+
if is_right:
|
| 1264 |
+
denoiser3d = pipeline.denoiser3d_righthand
|
| 1265 |
+
endecoder = pipeline.endecoder_righthand
|
| 1266 |
+
else:
|
| 1267 |
+
denoiser3d = pipeline.denoiser3d_lefthand
|
| 1268 |
+
endecoder = pipeline.endecoder_lefthand
|
| 1269 |
+
|
| 1270 |
+
max_length = inputs["length"].max()
|
| 1271 |
+
max_length = max(inputs["transl"].shape[1], max_length)
|
| 1272 |
+
B = inputs["length"].shape[0]
|
| 1273 |
+
hand_inputs = {}
|
| 1274 |
+
for k, v in inputs.items():
|
| 1275 |
+
if is_right:
|
| 1276 |
+
if k in ["right_base_rotmat", "right_base_pos", "right_handpose", "right_hand_localpos"]:
|
| 1277 |
+
hand_inputs[k.replace("right_", "")] = v
|
| 1278 |
+
continue
|
| 1279 |
+
else:
|
| 1280 |
+
if k in ["left_base_rotmat", "left_base_pos", "left_handpose", "left_hand_localpos"]:
|
| 1281 |
+
hand_inputs[k.replace("left_", "")] = v
|
| 1282 |
+
continue
|
| 1283 |
+
hand_inputs[k] = v
|
| 1284 |
+
|
| 1285 |
+
x = init_noise
|
| 1286 |
+
|
| 1287 |
+
# 2. Conditions
|
| 1288 |
+
condition_dict = endecoder.encode_condition(hand_inputs)
|
| 1289 |
+
f_condition = condition_dict
|
| 1290 |
+
|
| 1291 |
+
# *. Denoising loop
|
| 1292 |
+
# scheduler: timestep, extra_step_kwargs
|
| 1293 |
+
scheduler.set_timesteps(pipeline.num_optim_ddim_steps)
|
| 1294 |
+
timesteps = scheduler.timesteps
|
| 1295 |
+
num_warmup_steps = len(timesteps) - pipeline.num_optim_ddim_steps * scheduler.order
|
| 1296 |
+
extra_step_kwargs = pipeline.prepare_extra_step_kwargs(scheduler) # for scheduler.step()
|
| 1297 |
+
for i, t in enumerate(timesteps):
|
| 1298 |
+
# 1. Denoiser + Sampler.step
|
| 1299 |
+
model_kwargs = pipeline.build_model_kwargs(
|
| 1300 |
+
x=x,
|
| 1301 |
+
timesteps=t,
|
| 1302 |
+
inputs=hand_inputs,
|
| 1303 |
+
f_condition=f_condition,
|
| 1304 |
+
enable_cfg=enable_cfg,
|
| 1305 |
+
)
|
| 1306 |
+
x0_, _ = pipeline.cfg_denoise_func(denoiser3d, model_kwargs, scheduler, enable_cfg)
|
| 1307 |
+
|
| 1308 |
+
scheduler_out = scheduler.step(x0_, t, x, **extra_step_kwargs)
|
| 1309 |
+
x0_, xprev_ = scheduler_out.pred_original_sample, scheduler_out.prev_sample
|
| 1310 |
+
|
| 1311 |
+
# *. Update and store intermediate results
|
| 1312 |
+
x = xprev_
|
| 1313 |
+
return x
|
upstream/CoDA/coda/model/diff/utils/__pycache__/motion3d_endecoder.cpython-310.pyc
ADDED
|
Binary file (2.37 kB). View file
|
|
|
upstream/CoDA/coda/model/diff/utils/__pycache__/optimization.cpython-310.pyc
ADDED
|
Binary file (10.8 kB). View file
|
|
|
upstream/CoDA/coda/model/diff/utils/metric_endecoder.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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matrix_to_rotation_6d,
|
| 10 |
+
matrix_to_quaternion,
|
| 11 |
+
quaternion_to_matrix,
|
| 12 |
+
)
|
| 13 |
+
from coda.configs import MainStore, builds
|
| 14 |
+
from coda.utils.text2hoi.utils import get_NN, get_interior
|
| 15 |
+
from coda.utils.geo.augment_noisy_pose import gaussian_augment
|
| 16 |
+
import coda.utils.matrix as matrix
|
| 17 |
+
from coda.utils.pylogger import Log
|
| 18 |
+
from coda.dataset.arctic.utils import *
|
| 19 |
+
from coda.utils.geo.hmr_global import (
|
| 20 |
+
get_transl_to0,
|
| 21 |
+
get_transl_from_translto0,
|
| 22 |
+
get_local_transl_vel,
|
| 23 |
+
rollout_local_transl_vel,
|
| 24 |
+
)
|
| 25 |
+
from coda.utils.smplx_utils import make_smplx
|
| 26 |
+
from coda.utils.hml3d_utils.utils import detect_foot_contact
|
| 27 |
+
from coda.model.diff.utils.endecoder import EnDecoder
|
| 28 |
+
from . import stats_compose
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class WholeBodyEnDecoder(EnDecoder):
|
| 32 |
+
def __init__(self, stats_name="DEFAULT_01", with_obj=False):
|
| 33 |
+
super().__init__(stats_name)
|
| 34 |
+
self.with_obj = with_obj
|
| 35 |
+
stats = getattr(stats_compose, stats_name)
|
| 36 |
+
if "bps_mean" in stats:
|
| 37 |
+
self.register_buffer("bps_mean", torch.tensor(stats["bps_mean"]).float(), False)
|
| 38 |
+
self.register_buffer("bps_std", torch.tensor(stats["bps_std"]).float(), False)
|
| 39 |
+
else:
|
| 40 |
+
self.register_buffer("bps_mean", torch.tensor([0.0]).float(), False)
|
| 41 |
+
self.register_buffer("bps_std", torch.tensor([1.0]).float(), False)
|
| 42 |
+
if "beta_mean" in stats:
|
| 43 |
+
self.register_buffer("beta_mean", torch.tensor(stats["beta_mean"]).float(), False)
|
| 44 |
+
self.register_buffer("beta_std", torch.tensor(stats["beta_std"]).float(), False)
|
| 45 |
+
else:
|
| 46 |
+
self.register_buffer("beta_mean", torch.tensor([0.0]).float(), False)
|
| 47 |
+
self.register_buffer("beta_std", torch.tensor([1.0]).float(), False)
|
| 48 |
+
self.parent = [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19]
|
| 49 |
+
self.tip_parent = [-1, 0, 1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 0, 13, 14, 15, 0, 17, 18, 19]
|
| 50 |
+
|
| 51 |
+
def encode_condition(self, inputs):
|
| 52 |
+
"""
|
| 53 |
+
definition: {
|
| 54 |
+
}
|
| 55 |
+
"""
|
| 56 |
+
obj_mat = inputs["obj"] # (B, N, 2, 4, 4)
|
| 57 |
+
beta = inputs["beta"]
|
| 58 |
+
scale = inputs["scale"] # (B,)
|
| 59 |
+
angles = inputs["angles"]
|
| 60 |
+
center = inputs["center"] # (B, 3)
|
| 61 |
+
objframe0 = inputs["obj_frame0"] # (B, 2, 4, 4)
|
| 62 |
+
bps = inputs["bps"]
|
| 63 |
+
idle_bps = inputs["idle_bps"] # (B, 1, 256)
|
| 64 |
+
fps = 30.0
|
| 65 |
+
|
| 66 |
+
obj_root_mat = obj_mat[..., 0, :, :] # (B, N, 4, 4)
|
| 67 |
+
obj_root_pos = matrix.get_position_from(center[..., None, :], obj_root_mat) # (B, N, 3)
|
| 68 |
+
bps_norm = (bps - self.bps_mean) / self.bps_std
|
| 69 |
+
idle_bps_norm = (idle_bps - self.bps_mean) / self.bps_std
|
| 70 |
+
|
| 71 |
+
beta_norm = (beta - self.beta_mean) / self.beta_std
|
| 72 |
+
|
| 73 |
+
transl = inputs["transl"] # (B, N, 3)
|
| 74 |
+
global_orient = inputs["global_orient"] # (B, N, 3)
|
| 75 |
+
body_pose = inputs["body_pose"] # (B, N, 63)
|
| 76 |
+
lefthand_pose = inputs["left_hand_pose"] # (B, N, 15)
|
| 77 |
+
righthand_pose = inputs["right_hand_pose"] # (B, N, 15)
|
| 78 |
+
skeleton = inputs["skeleton"][..., :22, :] # (B, 1, 22, 3)
|
| 79 |
+
|
| 80 |
+
root_transl = transl + skeleton[..., 0, :] # (B, N, 3)
|
| 81 |
+
|
| 82 |
+
rotmat = matrix.axis_angle_to_matrix(
|
| 83 |
+
torch.cat([global_orient, body_pose], dim=-1).reshape(body_pose.shape[:-1] + (-1, 3))
|
| 84 |
+
)
|
| 85 |
+
local_pos = torch.cat(
|
| 86 |
+
[root_transl[..., None, :], skeleton[..., 1:, :] + torch.zeros_like(root_transl)[..., None, :]], dim=-2
|
| 87 |
+
)
|
| 88 |
+
local_mat = matrix.get_TRS(rotmat, local_pos)
|
| 89 |
+
global_mat = matrix.forward_kinematics(local_mat, self.parent)
|
| 90 |
+
global_pos = matrix.get_position(global_mat)
|
| 91 |
+
|
| 92 |
+
fps = 30.0
|
| 93 |
+
global_orient_rotmat = matrix.axis_angle_to_matrix(global_orient) # (B, N, 3, 3)
|
| 94 |
+
global_orinet_rot6d = matrix.matrix_to_rotation_6d(global_orient_rotmat) # (B, N, 6)
|
| 95 |
+
|
| 96 |
+
pose = body_pose # (B, N, 63)
|
| 97 |
+
pose_6d = matrix.axis_angle_to_rotation_6d(pose.reshape(pose.shape[:-1] + (-1, 3))) # (B, N, 21, 6)
|
| 98 |
+
pose_6d = pose_6d.flatten(-2) # (B, N, 132)
|
| 99 |
+
lefthand_pose6d = lefthand_pose.reshape(lefthand_pose.shape[:-1] + (-1, 3)) # (B, N, 15, 3)
|
| 100 |
+
lefthand_pose6d = matrix.axis_angle_to_rotation_6d(lefthand_pose6d) # (B, N, 15, 6)
|
| 101 |
+
lefthand_pose6d = lefthand_pose6d.flatten(-2) # (B, N, 90)
|
| 102 |
+
righthand_pose6d = righthand_pose.reshape(righthand_pose.shape[:-1] + (-1, 3)) # (B, N, 15, 3)
|
| 103 |
+
righthand_pose6d = matrix.axis_angle_to_rotation_6d(righthand_pose6d) # (B, N, 15, 6)
|
| 104 |
+
righthand_pose6d = righthand_pose6d.flatten(-2) # (B, N, 90)
|
| 105 |
+
|
| 106 |
+
human_x = torch.cat(
|
| 107 |
+
[
|
| 108 |
+
root_transl, # (3, )
|
| 109 |
+
global_orinet_rot6d, # (6, )
|
| 110 |
+
pose_6d, # (126, )
|
| 111 |
+
lefthand_pose6d, # (90, )
|
| 112 |
+
righthand_pose6d, # (90, )
|
| 113 |
+
],
|
| 114 |
+
dim=-1,
|
| 115 |
+
) # (B, N, 315)
|
| 116 |
+
|
| 117 |
+
obj_root_pos = matrix.get_position(obj_mat[..., 0, :, :]) # (B, L, 3)
|
| 118 |
+
|
| 119 |
+
obj_root_rot = matrix.get_rotation(obj_mat[..., 0, :, :]) # (B, L, 3, 3)
|
| 120 |
+
obj_root_rot6d = matrix.matrix_to_rotation_6d(obj_root_rot) # (B, L, 6)
|
| 121 |
+
obj_x = torch.cat(
|
| 122 |
+
[
|
| 123 |
+
obj_root_pos,
|
| 124 |
+
obj_root_rot6d,
|
| 125 |
+
angles,
|
| 126 |
+
],
|
| 127 |
+
dim=-1,
|
| 128 |
+
) # (B, N, 10)
|
| 129 |
+
|
| 130 |
+
first_x = torch.cat([human_x[..., :1, :], obj_x[..., :1, :]], dim=-1) # (B, 1, 325)
|
| 131 |
+
|
| 132 |
+
if self.with_obj:
|
| 133 |
+
condition_dict = {
|
| 134 |
+
"obj_pos": scale[..., None, :],
|
| 135 |
+
"bps": idle_bps_norm,
|
| 136 |
+
"beta": beta_norm,
|
| 137 |
+
"first_x": first_x,
|
| 138 |
+
}
|
| 139 |
+
else:
|
| 140 |
+
condition_dict = {
|
| 141 |
+
"obj_pos": obj_root_pos,
|
| 142 |
+
"bps": bps_norm,
|
| 143 |
+
"beta": beta_norm,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
return condition_dict
|
| 147 |
+
|
| 148 |
+
def _encode(self, inputs):
|
| 149 |
+
"""
|
| 150 |
+
definition: {
|
| 151 |
+
}
|
| 152 |
+
"""
|
| 153 |
+
obj_mat = inputs["obj"].clone() # (B, N, 2, 4, 4)
|
| 154 |
+
angles = inputs["angles"]
|
| 155 |
+
human_global_mat = inputs["humanoid"] # (B, N, 4, 4)
|
| 156 |
+
center = inputs["center"] # (B, 3)
|
| 157 |
+
|
| 158 |
+
global_obj_center = matrix.get_position_from(center[..., None, :], obj_mat[..., 0, :, :]) # (B, L, 3)
|
| 159 |
+
obj_root_rot = matrix.get_rotation(obj_mat[..., 0, :, :]) # (B, L, 3, 3)
|
| 160 |
+
obj_arti_rot = matrix.get_rotation(obj_mat[..., 1, :, :]) # (B, L, 3, 3)
|
| 161 |
+
global_obj_mat = matrix.get_TRS(obj_root_rot, global_obj_center) # (B, L, 4, 4)
|
| 162 |
+
global_obj_arti_mat = matrix.get_TRS(obj_arti_rot, global_obj_center) # (B, L, 4, 4)
|
| 163 |
+
|
| 164 |
+
human_pos = matrix.get_position(human_global_mat)[..., HUMANOID2SMPLX, :] # (B, N, J, 3)
|
| 165 |
+
invhuman_pos1 = matrix.get_relative_position_to(human_pos, global_obj_mat)
|
| 166 |
+
invhuman_pos2 = matrix.get_relative_position_to(human_pos, global_obj_arti_mat)
|
| 167 |
+
human_vec = torch.cat(
|
| 168 |
+
[human_pos.flatten(-2), invhuman_pos1.flatten(-2), invhuman_pos2.flatten(-2)], dim=-1
|
| 169 |
+
) # (B, N, J*9)
|
| 170 |
+
obj_vec = torch.cat([global_obj_center, angles], dim=-1) # (B, N, 4)
|
| 171 |
+
|
| 172 |
+
x = torch.cat([human_vec, obj_vec], dim=-1) # (B, N, J*9+4)
|
| 173 |
+
|
| 174 |
+
return x
|
| 175 |
+
|
| 176 |
+
def _decode(self, x_norm, inputs=None):
|
| 177 |
+
return {}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class GRABWholeBodyEnDecoder(EnDecoder):
|
| 181 |
+
def __init__(self, stats_name="DEFAULT_01", with_obj=False):
|
| 182 |
+
super().__init__(stats_name)
|
| 183 |
+
self.with_obj = with_obj
|
| 184 |
+
stats = getattr(stats_compose, stats_name)
|
| 185 |
+
if "bps_mean" in stats:
|
| 186 |
+
self.register_buffer("bps_mean", torch.tensor(stats["bps_mean"]).float(), False)
|
| 187 |
+
self.register_buffer("bps_std", torch.tensor(stats["bps_std"]).float(), False)
|
| 188 |
+
else:
|
| 189 |
+
self.register_buffer("bps_mean", torch.tensor([0.0]).float(), False)
|
| 190 |
+
self.register_buffer("bps_std", torch.tensor([1.0]).float(), False)
|
| 191 |
+
if "beta_mean" in stats:
|
| 192 |
+
self.register_buffer("beta_mean", torch.tensor(stats["beta_mean"]).float(), False)
|
| 193 |
+
self.register_buffer("beta_std", torch.tensor(stats["beta_std"]).float(), False)
|
| 194 |
+
else:
|
| 195 |
+
self.register_buffer("beta_mean", torch.tensor([0.0]).float(), False)
|
| 196 |
+
self.register_buffer("beta_std", torch.tensor([1.0]).float(), False)
|
| 197 |
+
self.parent = [-1, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 12, 13, 14, 16, 17, 18, 19]
|
| 198 |
+
self.tip_parent = [-1, 0, 1, 2, 3, 0, 5, 6, 7, 0, 9, 10, 11, 0, 13, 14, 15, 0, 17, 18, 19]
|
| 199 |
+
|
| 200 |
+
def encode_condition(self, inputs):
|
| 201 |
+
"""
|
| 202 |
+
definition: {
|
| 203 |
+
}
|
| 204 |
+
"""
|
| 205 |
+
obj_mat = inputs["obj"] # (B, N, 2, 4, 4)
|
| 206 |
+
beta = inputs["beta"]
|
| 207 |
+
scale = inputs["scale"] # (B,)
|
| 208 |
+
center = inputs["center"] # (B, 3)
|
| 209 |
+
objframe0 = inputs["obj_frame0"] # (B, 2, 4, 4)
|
| 210 |
+
bps = inputs["bps"]
|
| 211 |
+
idle_bps = inputs["idle_bps"] # (B, 1, 256)
|
| 212 |
+
fps = 30.0
|
| 213 |
+
|
| 214 |
+
obj_root_mat = obj_mat[..., 0, :, :] # (B, N, 4, 4)
|
| 215 |
+
obj_root_pos = matrix.get_position_from(center[..., None, :], obj_root_mat) # (B, N, 3)
|
| 216 |
+
bps_norm = (bps - self.bps_mean) / self.bps_std
|
| 217 |
+
idle_bps_norm = (idle_bps - self.bps_mean) / self.bps_std
|
| 218 |
+
|
| 219 |
+
beta_norm = (beta - self.beta_mean) / self.beta_std
|
| 220 |
+
|
| 221 |
+
transl = inputs["transl"] # (B, N, 3)
|
| 222 |
+
global_orient = inputs["global_orient"] # (B, N, 3)
|
| 223 |
+
body_pose = inputs["body_pose"] # (B, N, 63)
|
| 224 |
+
lefthand_pose = inputs["left_hand_pose"] # (B, N, 15)
|
| 225 |
+
righthand_pose = inputs["right_hand_pose"] # (B, N, 15)
|
| 226 |
+
skeleton = inputs["skeleton"][..., :22, :] # (B, 1, 22, 3)
|
| 227 |
+
|
| 228 |
+
root_transl = transl + skeleton[..., 0, :] # (B, N, 3)
|
| 229 |
+
|
| 230 |
+
rotmat = matrix.axis_angle_to_matrix(
|
| 231 |
+
torch.cat([global_orient, body_pose], dim=-1).reshape(body_pose.shape[:-1] + (-1, 3))
|
| 232 |
+
)
|
| 233 |
+
local_pos = torch.cat(
|
| 234 |
+
[root_transl[..., None, :], skeleton[..., 1:, :] + torch.zeros_like(root_transl)[..., None, :]], dim=-2
|
| 235 |
+
)
|
| 236 |
+
local_mat = matrix.get_TRS(rotmat, local_pos)
|
| 237 |
+
global_mat = matrix.forward_kinematics(local_mat, self.parent)
|
| 238 |
+
global_pos = matrix.get_position(global_mat)
|
| 239 |
+
|
| 240 |
+
fps = 30.0
|
| 241 |
+
global_orient_rotmat = matrix.axis_angle_to_matrix(global_orient) # (B, N, 3, 3)
|
| 242 |
+
global_orinet_rot6d = matrix.matrix_to_rotation_6d(global_orient_rotmat) # (B, N, 6)
|
| 243 |
+
|
| 244 |
+
pose = body_pose # (B, N, 63)
|
| 245 |
+
pose_6d = matrix.axis_angle_to_rotation_6d(pose.reshape(pose.shape[:-1] + (-1, 3))) # (B, N, 21, 6)
|
| 246 |
+
pose_6d = pose_6d.flatten(-2) # (B, N, 132)
|
| 247 |
+
lefthand_pose6d = lefthand_pose.reshape(lefthand_pose.shape[:-1] + (-1, 3)) # (B, N, 15, 3)
|
| 248 |
+
lefthand_pose6d = matrix.axis_angle_to_rotation_6d(lefthand_pose6d) # (B, N, 15, 6)
|
| 249 |
+
lefthand_pose6d = lefthand_pose6d.flatten(-2) # (B, N, 90)
|
| 250 |
+
righthand_pose6d = righthand_pose.reshape(righthand_pose.shape[:-1] + (-1, 3)) # (B, N, 15, 3)
|
| 251 |
+
righthand_pose6d = matrix.axis_angle_to_rotation_6d(righthand_pose6d) # (B, N, 15, 6)
|
| 252 |
+
righthand_pose6d = righthand_pose6d.flatten(-2) # (B, N, 90)
|
| 253 |
+
|
| 254 |
+
human_x = torch.cat(
|
| 255 |
+
[
|
| 256 |
+
root_transl, # (3, )
|
| 257 |
+
global_orinet_rot6d, # (6, )
|
| 258 |
+
pose_6d, # (126, )
|
| 259 |
+
lefthand_pose6d, # (90, )
|
| 260 |
+
righthand_pose6d, # (90, )
|
| 261 |
+
],
|
| 262 |
+
dim=-1,
|
| 263 |
+
) # (B, N, 315)
|
| 264 |
+
|
| 265 |
+
obj_root_pos = matrix.get_position(obj_mat[..., 0, :, :]) # (B, L, 3)
|
| 266 |
+
|
| 267 |
+
obj_root_rot = matrix.get_rotation(obj_mat[..., 0, :, :]) # (B, L, 3, 3)
|
| 268 |
+
obj_root_rot6d = matrix.matrix_to_rotation_6d(obj_root_rot) # (B, L, 6)
|
| 269 |
+
obj_x = torch.cat(
|
| 270 |
+
[
|
| 271 |
+
obj_root_pos,
|
| 272 |
+
obj_root_rot6d,
|
| 273 |
+
],
|
| 274 |
+
dim=-1,
|
| 275 |
+
) # (B, N, 10)
|
| 276 |
+
|
| 277 |
+
first_x = torch.cat([human_x[..., :1, :], obj_x[..., :1, :]], dim=-1) # (B, 1, 325)
|
| 278 |
+
|
| 279 |
+
if self.with_obj:
|
| 280 |
+
condition_dict = {
|
| 281 |
+
"obj_pos": scale[..., None, :],
|
| 282 |
+
"bps": idle_bps_norm,
|
| 283 |
+
"beta": beta_norm,
|
| 284 |
+
"first_x": first_x,
|
| 285 |
+
}
|
| 286 |
+
else:
|
| 287 |
+
condition_dict = {
|
| 288 |
+
"obj_pos": obj_root_pos,
|
| 289 |
+
"bps": bps_norm,
|
| 290 |
+
"beta": beta_norm,
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
return condition_dict
|
| 294 |
+
|
| 295 |
+
def _encode(self, inputs):
|
| 296 |
+
"""
|
| 297 |
+
definition: {
|
| 298 |
+
}
|
| 299 |
+
"""
|
| 300 |
+
obj_mat = inputs["obj"].clone() # (B, N, 2, 4, 4)
|
| 301 |
+
human_global_mat = inputs["humanoid"] # (B, N, 4, 4)
|
| 302 |
+
center = inputs["center"] # (B, 3)
|
| 303 |
+
|
| 304 |
+
global_obj_center = matrix.get_position_from(center[..., None, :], obj_mat[..., 0, :, :]) # (B, L, 3)
|
| 305 |
+
obj_root_rot = matrix.get_rotation(obj_mat[..., 0, :, :]) # (B, L, 3, 3)
|
| 306 |
+
obj_identity_mat = matrix.identity_mat(obj_mat[..., 0, :, :]) # (B, L, 4, 4)
|
| 307 |
+
obj_root_rot = matrix.get_rotation(obj_identity_mat) # (B, L, 3, 3)
|
| 308 |
+
global_obj_mat = matrix.get_TRS(obj_root_rot, global_obj_center) # (B, L, 4, 4)
|
| 309 |
+
|
| 310 |
+
human_pos = matrix.get_position(human_global_mat)[..., HUMANOID2SMPLX, :] # (B, N, J, 3)
|
| 311 |
+
invhuman_pos1 = matrix.get_relative_position_to(human_pos, global_obj_mat)
|
| 312 |
+
human_vec = torch.cat([human_pos.flatten(-2), invhuman_pos1.flatten(-2)], dim=-1) # (B, N, J*6)
|
| 313 |
+
obj_vec = torch.cat([global_obj_center], dim=-1) # (B, N, 4)
|
| 314 |
+
|
| 315 |
+
x = torch.cat([human_vec, obj_vec], dim=-1) # (B, N, J*6+3)
|
| 316 |
+
|
| 317 |
+
return x
|
| 318 |
+
|
| 319 |
+
def _decode(self, x_norm, inputs=None):
|
| 320 |
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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
import math
|
| 4 |
+
from coda.utils.wis3d_utils import make_wis3d, add_motion_as_lines
|
| 5 |
+
import coda.utils.matrix as matrix
|
| 6 |
+
|
| 7 |
+
# import chamfer_distance as chd
|
| 8 |
+
from einops import einsum
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class WholeBodyPartCondKeyLocationsLoss:
|
| 12 |
+
def __init__(
|
| 13 |
+
self,
|
| 14 |
+
target=None,
|
| 15 |
+
target_mask=None,
|
| 16 |
+
motion_length=None,
|
| 17 |
+
body_inv_transform=None,
|
| 18 |
+
lefthand_inv_transform=None,
|
| 19 |
+
righthand_inv_transform=None,
|
| 20 |
+
use_mse_loss=False,
|
| 21 |
+
only_body_steps=None,
|
| 22 |
+
no_body_steps=None,
|
| 23 |
+
no_pene_steps=None,
|
| 24 |
+
body_w=1.0,
|
| 25 |
+
hand_w=1.0,
|
| 26 |
+
detach_hand_w=0.0,
|
| 27 |
+
delta_w=1.0,
|
| 28 |
+
sdf_w=1.0,
|
| 29 |
+
root_height_reg_w=1.0,
|
| 30 |
+
foot_sliding_reg_w=1.0,
|
| 31 |
+
foot_floating_reg_w=1.0,
|
| 32 |
+
head_w=0.2,
|
| 33 |
+
is_vis=False,
|
| 34 |
+
is_moving_obj=False,
|
| 35 |
+
moving_obj_kwargs=None,
|
| 36 |
+
save_res=False,
|
| 37 |
+
):
|
| 38 |
+
self.target = target
|
| 39 |
+
self.target_mask = target_mask
|
| 40 |
+
self.motion_length = motion_length
|
| 41 |
+
self.body_inv_transform = body_inv_transform
|
| 42 |
+
self.lefthand_inv_transform = lefthand_inv_transform
|
| 43 |
+
self.righthand_inv_transform = righthand_inv_transform
|
| 44 |
+
self.use_mse_loss = use_mse_loss
|
| 45 |
+
self.only_body_steps = only_body_steps
|
| 46 |
+
self.no_body_steps = no_body_steps
|
| 47 |
+
self.no_pene_steps = no_pene_steps
|
| 48 |
+
self.body_w = body_w
|
| 49 |
+
self.hand_w = hand_w
|
| 50 |
+
self.detach_hand_w = detach_hand_w
|
| 51 |
+
self.delta_w = delta_w
|
| 52 |
+
self.sdf_w = sdf_w
|
| 53 |
+
self.root_height_reg_w = root_height_reg_w
|
| 54 |
+
self.foot_sliding_reg_w = foot_sliding_reg_w
|
| 55 |
+
self.foot_floating_reg_w = foot_floating_reg_w
|
| 56 |
+
self.head_w = head_w
|
| 57 |
+
self.is_vis = is_vis
|
| 58 |
+
self.is_moving_obj = is_moving_obj
|
| 59 |
+
self.moving_obj_kwargs = moving_obj_kwargs
|
| 60 |
+
# save_res = True
|
| 61 |
+
self.save_res = save_res
|
| 62 |
+
# NOTE: DNO says optimizing to the whole trajectory is not good.
|
| 63 |
+
|
| 64 |
+
def __call__(
|
| 65 |
+
self,
|
| 66 |
+
body_xstart_in,
|
| 67 |
+
lefthand_xstart_in,
|
| 68 |
+
righthand_xstart_in,
|
| 69 |
+
left_hand_ind,
|
| 70 |
+
right_hand_ind,
|
| 71 |
+
obj_verts,
|
| 72 |
+
obj_normals,
|
| 73 |
+
smplx_model,
|
| 74 |
+
inputs=None,
|
| 75 |
+
iter=None,
|
| 76 |
+
vis_i=None,
|
| 77 |
+
):
|
| 78 |
+
"""
|
| 79 |
+
Args:
|
| 80 |
+
xstart_in: [bs, L, C]
|
| 81 |
+
target: [bs, L, J, 3]
|
| 82 |
+
motion_length: [bs]
|
| 83 |
+
target_mask: [bs, L, J, 3]
|
| 84 |
+
"""
|
| 85 |
+
# TODO: try relative joint distance loss
|
| 86 |
+
target = self.target.clone()
|
| 87 |
+
target_mask = self.target_mask.clone()
|
| 88 |
+
detach_target_mask = self.target_mask.clone()
|
| 89 |
+
delta_target_mask = self.target_mask.clone()
|
| 90 |
+
motion_length = self.motion_length
|
| 91 |
+
|
| 92 |
+
# motion_mask shape [bs, 120, 22, 3]
|
| 93 |
+
if motion_length is None:
|
| 94 |
+
motion_mask = torch.ones_like(target_mask)
|
| 95 |
+
else:
|
| 96 |
+
# the mask is only for the first motion_length frames
|
| 97 |
+
motion_mask = torch.zeros_like(target_mask)
|
| 98 |
+
for i, m_len in enumerate(motion_length):
|
| 99 |
+
motion_mask[i, :m_len, :, :] = 1.0
|
| 100 |
+
|
| 101 |
+
with torch.enable_grad():
|
| 102 |
+
idle_body_global_out = self.body_inv_transform(torch.zeros_like(body_xstart_in), inputs=inputs)
|
| 103 |
+
idle_global_pos = idle_body_global_out["global_pos"] # (B, L, J, 3)
|
| 104 |
+
idle_root_height = idle_global_pos[:, 0, 0, 1] - idle_global_pos[:, 0, :, 1].min(dim=-1)[0] # (B, )
|
| 105 |
+
|
| 106 |
+
body_global_out = self.body_inv_transform(body_xstart_in, inputs=inputs)
|
| 107 |
+
body_global_mat = body_global_out["global_mat"]
|
| 108 |
+
body_global_pos = body_global_out["global_pos"]
|
| 109 |
+
|
| 110 |
+
left_hand_inputs = {}
|
| 111 |
+
for k, v in inputs.items():
|
| 112 |
+
if k in [
|
| 113 |
+
"left_base_rotmat",
|
| 114 |
+
"left_base_pos",
|
| 115 |
+
"left_handpose",
|
| 116 |
+
"left_hand_localpos",
|
| 117 |
+
"left_handtip_localpos",
|
| 118 |
+
]:
|
| 119 |
+
left_hand_inputs[k.replace("left_", "")] = v
|
| 120 |
+
continue
|
| 121 |
+
left_hand_inputs[k] = v
|
| 122 |
+
left_hand_inputs["base_rotmat"] = matrix.get_rotation(body_global_mat[..., 20, :, :])
|
| 123 |
+
left_hand_inputs["base_pos"] = body_global_pos[..., 20, :]
|
| 124 |
+
lefthand_global_out = self.lefthand_inv_transform(lefthand_xstart_in, inputs=left_hand_inputs)
|
| 125 |
+
lefthand_global_mat = lefthand_global_out["tip_global_mat"]
|
| 126 |
+
lefthand_global_pos = lefthand_global_out["tip_global_pos"]
|
| 127 |
+
|
| 128 |
+
detach_lefthand_xstart_in = lefthand_xstart_in.clone().detach()
|
| 129 |
+
detach_lefthand_global_out = self.lefthand_inv_transform(detach_lefthand_xstart_in, inputs=left_hand_inputs)
|
| 130 |
+
detach_lefthand_global_mat = detach_lefthand_global_out["tip_global_mat"]
|
| 131 |
+
detach_lefthand_global_pos = detach_lefthand_global_out["tip_global_pos"]
|
| 132 |
+
|
| 133 |
+
right_hand_inputs = {}
|
| 134 |
+
for k, v in inputs.items():
|
| 135 |
+
if k in [
|
| 136 |
+
"right_base_rotmat",
|
| 137 |
+
"right_base_pos",
|
| 138 |
+
"right_handpose",
|
| 139 |
+
"right_hand_localpos",
|
| 140 |
+
"right_handtip_localpos",
|
| 141 |
+
]:
|
| 142 |
+
right_hand_inputs[k.replace("right_", "")] = v
|
| 143 |
+
continue
|
| 144 |
+
right_hand_inputs[k] = v
|
| 145 |
+
right_hand_inputs["base_rotmat"] = matrix.get_rotation(body_global_mat[..., 21, :, :])
|
| 146 |
+
right_hand_inputs["base_pos"] = body_global_pos[..., 21, :]
|
| 147 |
+
righthand_global_out = self.righthand_inv_transform(righthand_xstart_in, inputs=right_hand_inputs)
|
| 148 |
+
righthand_global_mat = righthand_global_out["tip_global_mat"]
|
| 149 |
+
righthand_global_pos = righthand_global_out["tip_global_pos"]
|
| 150 |
+
|
| 151 |
+
detach_righthand_xstart_in = righthand_xstart_in.clone().detach()
|
| 152 |
+
detach_righthand_global_out = self.righthand_inv_transform(
|
| 153 |
+
detach_righthand_xstart_in, inputs=right_hand_inputs
|
| 154 |
+
)
|
| 155 |
+
detach_righthand_global_mat = detach_righthand_global_out["tip_global_mat"]
|
| 156 |
+
detach_righthand_global_pos = detach_righthand_global_out["tip_global_pos"]
|
| 157 |
+
|
| 158 |
+
global_pos = torch.cat(
|
| 159 |
+
[body_global_pos, lefthand_global_pos[..., 1:, :], righthand_global_pos[..., 1:, :]], dim=-2
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
global_pos_detachhand = torch.cat(
|
| 163 |
+
[body_global_pos, detach_lefthand_global_pos[..., 1:, :], detach_righthand_global_pos[..., 1:, :]],
|
| 164 |
+
dim=-2,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
if ((iter + 1) % 100 == 0 or iter == 0) and self.is_vis:
|
| 168 |
+
wis3d = make_wis3d(name=f"debug_wholebody_{vis_i:03d}")
|
| 169 |
+
add_motion_as_lines(body_global_pos[0].clone(), wis3d, name=f"{iter:03d}_optim-body")
|
| 170 |
+
add_motion_as_lines(
|
| 171 |
+
lefthand_global_pos[0].clone(),
|
| 172 |
+
wis3d,
|
| 173 |
+
name=f"{iter:03d}_optim-left_hand",
|
| 174 |
+
skeleton_type="handtip",
|
| 175 |
+
radius=0.005,
|
| 176 |
+
)
|
| 177 |
+
add_motion_as_lines(
|
| 178 |
+
righthand_global_pos[0].clone(),
|
| 179 |
+
wis3d,
|
| 180 |
+
name=f"{iter:03d}_optim-right_hand",
|
| 181 |
+
skeleton_type="handtip",
|
| 182 |
+
radius=0.005,
|
| 183 |
+
)
|
| 184 |
+
for j in range(body_global_pos.shape[1]):
|
| 185 |
+
wis3d.set_scene_id(j)
|
| 186 |
+
wis3d.add_point_cloud(target[0, j, [20, 21]], name=f"target_wrist")
|
| 187 |
+
wis3d.add_point_cloud(target[0, j, left_hand_ind], name=f"target_lefthand")
|
| 188 |
+
wis3d.add_point_cloud(target[0, j, right_hand_ind], name=f"target_righthand")
|
| 189 |
+
|
| 190 |
+
if self.save_res:
|
| 191 |
+
pred_data = {
|
| 192 |
+
"transl": body_global_out["transl"],
|
| 193 |
+
"global_orient": body_global_out["global_orient"],
|
| 194 |
+
"body_pose": body_global_out["body_pose"],
|
| 195 |
+
"left_hand_pose": lefthand_global_out["hand_pose"],
|
| 196 |
+
"right_hand_pose": righthand_global_out["hand_pose"],
|
| 197 |
+
}
|
| 198 |
+
torch.save(pred_data, f"wholebody_iter{iter:03d}.pt")
|
| 199 |
+
|
| 200 |
+
if iter < self.only_body_steps:
|
| 201 |
+
target_mask[..., 22:, :] = 0.0
|
| 202 |
+
|
| 203 |
+
loss_dict = {}
|
| 204 |
+
|
| 205 |
+
obj_pos = obj_verts.mean(dim=-2)[:, 0] # (B, 3)
|
| 206 |
+
obj_dist = torch.norm(obj_pos[..., [2]], dim=-1) # (B, )
|
| 207 |
+
# if vis_i == 3 or vis_i == 8 or vis_i == 12:
|
| 208 |
+
# print(obj_dist)
|
| 209 |
+
# import ipdb
|
| 210 |
+
|
| 211 |
+
# ipdb.set_trace()
|
| 212 |
+
DIST_THRESH = 0.5 # GRAB
|
| 213 |
+
# DIST_THRESH = 0.3 # ARCTIC modify
|
| 214 |
+
# PRE_N = 60 # ARCTIC modify
|
| 215 |
+
PRE_N = 40 # GRAB
|
| 216 |
+
is_obj_far = obj_dist > DIST_THRESH
|
| 217 |
+
if is_obj_far[0]:
|
| 218 |
+
|
| 219 |
+
for i in range(is_obj_far.shape[0]):
|
| 220 |
+
if is_obj_far[i]:
|
| 221 |
+
PRE_N = min(PRE_N, target_mask.shape[1])
|
| 222 |
+
target_mask[i, 1 : PRE_N + 1] = 0.0 # (L, J, 3)
|
| 223 |
+
delta_target_mask[i, 1 : PRE_N + 1] = 0.0
|
| 224 |
+
detach_target_mask[i, 1 : PRE_N + 1] = 0.0
|
| 225 |
+
for j in range(1, PRE_N + 1, 10):
|
| 226 |
+
target_mask[i, j, 0, 0] = 1.0
|
| 227 |
+
target_mask[i, j, 0, 2] = 1.0
|
| 228 |
+
target[i, j, 0, 0] = 0.0 + j * obj_pos[i, 0] / PRE_N
|
| 229 |
+
target[i, j, 0, 2] = 0.0 + j * (obj_pos[i, 2] - DIST_THRESH) / PRE_N
|
| 230 |
+
|
| 231 |
+
else:
|
| 232 |
+
# already very close, do not move root
|
| 233 |
+
target_mask[i, :, 0, :] = 1.0
|
| 234 |
+
|
| 235 |
+
IS_MOVING_OBJ = self.is_moving_obj
|
| 236 |
+
if IS_MOVING_OBJ:
|
| 237 |
+
if iter < 100:
|
| 238 |
+
# only optim root during first 100 steps
|
| 239 |
+
# target_mask[...] = 0.0
|
| 240 |
+
detach_target_mask[...] = 0.0
|
| 241 |
+
START_T = 2 * 30
|
| 242 |
+
MOVE_T = 6 * 30
|
| 243 |
+
MOVE_DIST = self.moving_obj_kwargs["MOVE_DIST"]
|
| 244 |
+
axis = self.moving_obj_kwargs["AXIS"]
|
| 245 |
+
target_mask[:, :START_T, 0, axis] = 1.0
|
| 246 |
+
for i in range(0, MOVE_T + 1, 15):
|
| 247 |
+
target[:, START_T + i, 0, axis] = i * MOVE_DIST / MOVE_T
|
| 248 |
+
target_mask[:, START_T + i, 0, axis] = 1.0
|
| 249 |
+
# target_mask[:, START_T + i, 0, 0] = 1.0
|
| 250 |
+
for i in range(START_T + MOVE_T, target_mask.shape[1], 15):
|
| 251 |
+
target[:, i, 0, axis] = MOVE_DIST
|
| 252 |
+
target_mask[:, i, 0, axis] = 1.0
|
| 253 |
+
# target_mask[:, i, 0, 0] = 1.0
|
| 254 |
+
|
| 255 |
+
#### body and hand tracking loss ####
|
| 256 |
+
loss_fn = F.mse_loss if self.use_mse_loss else F.l1_loss
|
| 257 |
+
body_loss_sum = (
|
| 258 |
+
loss_fn(global_pos[..., :22, :], target[..., :22, :], reduction="none")
|
| 259 |
+
* target_mask[..., :22, :]
|
| 260 |
+
* motion_mask[..., :22, :]
|
| 261 |
+
)
|
| 262 |
+
hand_loss_sum = (
|
| 263 |
+
loss_fn(global_pos[..., 22:, :], target[..., 22:, :], reduction="none")
|
| 264 |
+
* target_mask[..., 22:, :]
|
| 265 |
+
* motion_mask[..., 22:, :]
|
| 266 |
+
)
|
| 267 |
+
detach_hand_loss_sum = (
|
| 268 |
+
loss_fn(global_pos_detachhand[..., 22:, :], target[..., 22:, :], reduction="none")
|
| 269 |
+
* detach_target_mask[..., 22:, :]
|
| 270 |
+
* motion_mask[..., 22:, :]
|
| 271 |
+
) # for wrist rotation
|
| 272 |
+
if iter >= self.no_body_steps:
|
| 273 |
+
body_loss_sum = body_loss_sum * 0.0
|
| 274 |
+
detach_hand_loss_sum = detach_hand_loss_sum * 0.0
|
| 275 |
+
loss_sum = (
|
| 276 |
+
self.body_w * body_loss_sum.sum(dim=[1, 2, 3])
|
| 277 |
+
+ self.hand_w * hand_loss_sum.sum(dim=[1, 2, 3])
|
| 278 |
+
+ self.detach_hand_w * detach_hand_loss_sum.sum(dim=[1, 2, 3])
|
| 279 |
+
)
|
| 280 |
+
# average the loss over the number of valid joints
|
| 281 |
+
loss_sum = loss_sum / (target_mask * motion_mask).sum(dim=[1, 2, 3])
|
| 282 |
+
loss_dict["target_pos_loss"] = loss_sum
|
| 283 |
+
#########################################################
|
| 284 |
+
|
| 285 |
+
########### head loss ###########
|
| 286 |
+
head_rotmat = matrix.get_rotation(body_global_mat[..., 15, :, :])
|
| 287 |
+
# z vec is the head direction
|
| 288 |
+
head_dir = head_rotmat[..., :, 2] # (B, L, 3)
|
| 289 |
+
head_pos = body_global_pos[..., 15, :] # (B, L, 3)
|
| 290 |
+
target_pos = obj_verts.mean(dim=-2) # (B, L, 3)
|
| 291 |
+
target_head_dir = target_pos - head_pos # (B, L, 3)
|
| 292 |
+
target_head_dir = target_head_dir / (torch.norm(target_head_dir, dim=-1, keepdim=True) + 1e-6)
|
| 293 |
+
head_loss = 1 - (head_dir * target_head_dir).sum(dim=-1) # (B, L)
|
| 294 |
+
head_loss = self.head_w * head_loss.mean()
|
| 295 |
+
loss_dict["head_loss"] = head_loss
|
| 296 |
+
loss_sum = loss_sum + head_loss
|
| 297 |
+
#########################################################
|
| 298 |
+
|
| 299 |
+
#### hand relative wrist loss ####
|
| 300 |
+
left_finger_pos = global_pos[..., left_hand_ind, :]
|
| 301 |
+
right_finger_pos = global_pos[..., right_hand_ind, :]
|
| 302 |
+
left_wrist_pos = global_pos[..., [20], :]
|
| 303 |
+
right_wrist_pos = global_pos[..., [21], :]
|
| 304 |
+
left_delta_pos = left_finger_pos - left_wrist_pos
|
| 305 |
+
right_delta_pos = right_finger_pos - right_wrist_pos
|
| 306 |
+
|
| 307 |
+
target_left_finger_pos = target[..., left_hand_ind, :]
|
| 308 |
+
target_right_finger_pos = target[..., right_hand_ind, :]
|
| 309 |
+
target_left_wrist_pos = target[..., [20], :]
|
| 310 |
+
target_right_wrist_pos = target[..., [21], :]
|
| 311 |
+
target_left_delta_pos = target_left_finger_pos - target_left_wrist_pos
|
| 312 |
+
target_right_delta_pos = target_right_finger_pos - target_right_wrist_pos
|
| 313 |
+
|
| 314 |
+
left_delta_loss = (
|
| 315 |
+
loss_fn(left_delta_pos, target_left_delta_pos, reduction="none")
|
| 316 |
+
* delta_target_mask[..., left_hand_ind, :]
|
| 317 |
+
* motion_mask[..., left_hand_ind, :]
|
| 318 |
+
)
|
| 319 |
+
right_delta_loss = (
|
| 320 |
+
loss_fn(right_delta_pos, target_right_delta_pos, reduction="none")
|
| 321 |
+
* delta_target_mask[..., right_hand_ind, :]
|
| 322 |
+
* motion_mask[..., right_hand_ind, :]
|
| 323 |
+
)
|
| 324 |
+
delta_loss_sum = left_delta_loss.sum(dim=[1, 2, 3]) + right_delta_loss.sum(dim=[1, 2, 3])
|
| 325 |
+
delta_loss_sum = delta_loss_sum / (delta_target_mask * motion_mask).sum(dim=[1, 2, 3])
|
| 326 |
+
if iter >= self.no_body_steps:
|
| 327 |
+
delta_loss_sum = delta_loss_sum * 0.0
|
| 328 |
+
if iter <= self.only_body_steps:
|
| 329 |
+
delta_loss_sum = delta_loss_sum * 0.0
|
| 330 |
+
loss_dict["delta_loss"] = delta_loss_sum * self.delta_w
|
| 331 |
+
loss_sum = loss_sum + delta_loss_sum * self.delta_w
|
| 332 |
+
#########################################################
|
| 333 |
+
|
| 334 |
+
#### root height reg loss ####
|
| 335 |
+
root_global_h = body_global_pos[..., 0, 1] # (B, L)
|
| 336 |
+
root_height_reg_loss = (root_global_h - idle_root_height).abs()
|
| 337 |
+
loss_dict["root_height_reg_loss"] = root_height_reg_loss * self.root_height_reg_w
|
| 338 |
+
loss_sum = loss_sum + root_height_reg_loss * self.root_height_reg_w
|
| 339 |
+
#########################################################
|
| 340 |
+
|
| 341 |
+
#### foot sliding reg loss ####
|
| 342 |
+
FOOT_THRESH = 0.05
|
| 343 |
+
foot_ind = [7, 8, 10, 11]
|
| 344 |
+
foot_global_pos = body_global_pos[..., foot_ind, :]
|
| 345 |
+
foot_global_h = foot_global_pos[..., 1] # (B, L, j)
|
| 346 |
+
foot_global_vel = foot_global_pos[:, 1:, :, [0, 2]] - foot_global_pos[:, :-1, :, [0, 2]]
|
| 347 |
+
foot_global_vel = torch.abs(30 * foot_global_vel).mean(dim=-1) # (B, L-1, j)
|
| 348 |
+
foot_global_h_min = foot_global_h.min(dim=-1)[0] # at least one foot is on the ground
|
| 349 |
+
foot_floating_loss_1 = torch.maximum(foot_global_h_min - 0.02, torch.zeros_like(foot_global_h_min)).mean()
|
| 350 |
+
foot_floating_loss_2 = torch.maximum(-0.02 - foot_global_h_min, torch.zeros_like(foot_global_h_min)).mean()
|
| 351 |
+
foot_floating_loss = foot_floating_loss_1 + foot_floating_loss_2
|
| 352 |
+
foot_global_vel = foot_global_vel * (foot_global_h[:, :-1] < FOOT_THRESH).float() # (B, L-1, j)
|
| 353 |
+
foot_sliding_reg_loss = foot_global_vel.mean()
|
| 354 |
+
if iter <= self.only_body_steps:
|
| 355 |
+
foot_sliding_reg_loss = foot_sliding_reg_loss * 0.0
|
| 356 |
+
loss_sum = (
|
| 357 |
+
loss_sum
|
| 358 |
+
+ foot_sliding_reg_loss * self.foot_sliding_reg_w
|
| 359 |
+
+ foot_floating_loss * self.foot_floating_reg_w
|
| 360 |
+
)
|
| 361 |
+
loss_dict["foot_sliding_reg_loss"] = foot_sliding_reg_loss * self.foot_sliding_reg_w
|
| 362 |
+
loss_dict["foot_floating_reg_loss"] = foot_floating_loss * self.foot_floating_reg_w
|
| 363 |
+
#########################################################
|
| 364 |
+
|
| 365 |
+
#### pene loss ####
|
| 366 |
+
if iter >= self.no_pene_steps:
|
| 367 |
+
# obj_verts: [B, L, M, 3]
|
| 368 |
+
radius = 0.005 # 5mm
|
| 369 |
+
min_dist = 0.005 # 5mm
|
| 370 |
+
positive_threshold = 0.02 # 5mm
|
| 371 |
+
negative_threshold = 0.02 # 5mm
|
| 372 |
+
finger_ind = [
|
| 373 |
+
1,
|
| 374 |
+
2,
|
| 375 |
+
3,
|
| 376 |
+
4, # index
|
| 377 |
+
5,
|
| 378 |
+
6,
|
| 379 |
+
7,
|
| 380 |
+
8, # middle
|
| 381 |
+
9,
|
| 382 |
+
10,
|
| 383 |
+
11,
|
| 384 |
+
12, # pinky
|
| 385 |
+
13,
|
| 386 |
+
14,
|
| 387 |
+
15,
|
| 388 |
+
16, # ring
|
| 389 |
+
17,
|
| 390 |
+
18,
|
| 391 |
+
19,
|
| 392 |
+
20, # thumb
|
| 393 |
+
]
|
| 394 |
+
hand_global_mat = torch.cat(
|
| 395 |
+
[lefthand_global_mat[..., finger_ind, :, :], righthand_global_mat[..., finger_ind, :, :]],
|
| 396 |
+
dim=-3,
|
| 397 |
+
) # (B, L, J, 4, 4)
|
| 398 |
+
# add finger root with wrist rot to avoid strange rot (close to obj but wierd rot to avoid y penetration)
|
| 399 |
+
finger_root_ind = [1, 5, 9, 13, 17]
|
| 400 |
+
left_finger_root_pos = matrix.get_position(lefthand_global_mat[..., finger_root_ind, :, :])
|
| 401 |
+
right_finger_root_pos = matrix.get_position(righthand_global_mat[..., finger_root_ind, :, :])
|
| 402 |
+
left_wrist_rot = matrix.get_rotation(lefthand_global_mat[..., [0], :, :])
|
| 403 |
+
right_wrist_rot = matrix.get_rotation(righthand_global_mat[..., [0], :, :])
|
| 404 |
+
left_wrist_rot = left_wrist_rot.expand(-1, -1, 5, -1, -1)
|
| 405 |
+
right_wrist_rot = right_wrist_rot.expand(-1, -1, 5, -1, -1)
|
| 406 |
+
left_finger_root_globalmat = matrix.get_TRS(left_wrist_rot, left_finger_root_pos)
|
| 407 |
+
right_finger_root_globalmat = matrix.get_TRS(right_wrist_rot, right_finger_root_pos)
|
| 408 |
+
hand_global_mat = torch.cat(
|
| 409 |
+
[left_finger_root_globalmat, right_finger_root_globalmat], dim=-3
|
| 410 |
+
) # (B, L, J, 4, 4)
|
| 411 |
+
#########################################################
|
| 412 |
+
|
| 413 |
+
obj_verts_in_hand = matrix.get_relative_position_to(
|
| 414 |
+
obj_verts[..., None, :, :], hand_global_mat
|
| 415 |
+
) # (B, L, J, M, 3)
|
| 416 |
+
obj_verts_in_hand_y = -obj_verts_in_hand[..., 1] # ray is along -y axis
|
| 417 |
+
obj_verts_in_hand_xz = obj_verts_in_hand[..., [0, 2]]
|
| 418 |
+
obj_verts_in_hand_xzdist = torch.norm(obj_verts_in_hand_xz, dim=-1)
|
| 419 |
+
# not along ray assign very big number to filter out
|
| 420 |
+
obj_verts_in_hand_y = obj_verts_in_hand_y + 1000000.0 * (obj_verts_in_hand_xzdist > radius).float()
|
| 421 |
+
obj_verts_in_hand_signdist = obj_verts_in_hand_y.min(dim=-1)[0] # (B, L, J)
|
| 422 |
+
# filter out the verts that are too far away
|
| 423 |
+
sdf_out_mask = torch.logical_or(
|
| 424 |
+
obj_verts_in_hand_signdist > positive_threshold,
|
| 425 |
+
obj_verts_in_hand_signdist < -negative_threshold,
|
| 426 |
+
)
|
| 427 |
+
sdf_mask = ~sdf_out_mask
|
| 428 |
+
# obj verts should always in front of finger, negative sd is behind finger, should be penalized
|
| 429 |
+
sdf_loss = F.relu(-obj_verts_in_hand_signdist + min_dist) * sdf_mask.float()
|
| 430 |
+
sdf_loss = sdf_loss.mean()
|
| 431 |
+
|
| 432 |
+
loss_dict["sdf_loss"] = sdf_loss * self.sdf_w
|
| 433 |
+
loss_sum = loss_sum + sdf_loss * self.sdf_w
|
| 434 |
+
#########################################################
|
| 435 |
+
|
| 436 |
+
return loss_sum, loss_dict
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def warmup_scheduler(step, warmup_steps):
|
| 440 |
+
if step < warmup_steps:
|
| 441 |
+
return step / warmup_steps
|
| 442 |
+
return 1
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def cosine_decay_scheduler(step, decay_steps, total_steps, decay_first=True):
|
| 446 |
+
# decay the last "decay_steps" steps from 1 to 0 using cosine decay
|
| 447 |
+
# if decay_first is True, then the first "decay_steps" steps will be decayed from 1 to 0
|
| 448 |
+
# if decay_first is False, then the last "decay_steps" steps will be decayed from 1 to 0
|
| 449 |
+
if step >= total_steps:
|
| 450 |
+
return 0
|
| 451 |
+
if decay_first:
|
| 452 |
+
if step >= decay_steps:
|
| 453 |
+
return 0
|
| 454 |
+
return (math.cos((step) / decay_steps * math.pi) + 1) / 2
|
| 455 |
+
else:
|
| 456 |
+
if step < total_steps - decay_steps:
|
| 457 |
+
return 1
|
| 458 |
+
return (math.cos((step - (total_steps - decay_steps)) / decay_steps * math.pi) + 1) / 2
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def noise_regularize_1d(noise, stop_at=2, dim=3):
|
| 462 |
+
"""
|
| 463 |
+
Args:
|
| 464 |
+
noise (torch.Tensor): (N, C, 1, size)
|
| 465 |
+
stop_at (int): stop decorrelating when size is less than or equal to stop_at
|
| 466 |
+
dim (int): the dimension to decorrelate
|
| 467 |
+
"""
|
| 468 |
+
all_dims = set(range(len(noise.shape)))
|
| 469 |
+
loss = 0
|
| 470 |
+
size = noise.shape[dim]
|
| 471 |
+
|
| 472 |
+
# pad noise in the size dimention so that it is the power of 2
|
| 473 |
+
if size != 2 ** int(math.log2(size)):
|
| 474 |
+
new_size = 2 ** int(math.log2(size) + 1)
|
| 475 |
+
pad = new_size - size
|
| 476 |
+
pad_shape = list(noise.shape)
|
| 477 |
+
pad_shape[dim] = pad
|
| 478 |
+
pad_noise = torch.randn(*pad_shape).to(noise.device)
|
| 479 |
+
|
| 480 |
+
noise = torch.cat([noise, pad_noise], dim=dim)
|
| 481 |
+
size = noise.shape[dim]
|
| 482 |
+
|
| 483 |
+
while True:
|
| 484 |
+
# this loss penalizes spatially correlated noise
|
| 485 |
+
# the noise is rolled in the size direction and the dot product is taken
|
| 486 |
+
# (bs, )
|
| 487 |
+
loss = loss + (noise * torch.roll(noise, shifts=1, dims=dim)).mean(
|
| 488 |
+
# average over all dimensions except 0 (batch)
|
| 489 |
+
dim=list(all_dims - {0})
|
| 490 |
+
).pow(2)
|
| 491 |
+
|
| 492 |
+
# stop when size is 8
|
| 493 |
+
if size <= stop_at:
|
| 494 |
+
break
|
| 495 |
+
|
| 496 |
+
# (N, C, 1, size) -> (N, C, 1, size // 2, 2)
|
| 497 |
+
noise_shape = list(noise.shape)
|
| 498 |
+
noise_shape[dim] = size // 2
|
| 499 |
+
noise_shape.insert(dim + 1, 2)
|
| 500 |
+
noise = noise.reshape(noise_shape)
|
| 501 |
+
# average pool over (2,) window
|
| 502 |
+
noise = noise.mean([dim + 1])
|
| 503 |
+
size //= 2
|
| 504 |
+
|
| 505 |
+
return loss
|
upstream/CoDA/coda/model/diff/utils/stats_compose.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
upstream/CoDA/coda/network/base_arch/embeddings/cape.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import einops
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def cape_embed(f, P, is_query=False):
|
| 7 |
+
"""
|
| 8 |
+
Apply CaPE on feature.
|
| 9 |
+
:param f: feature vector of shape [..., d]
|
| 10 |
+
:param P: 4x4 transformation matrix
|
| 11 |
+
:return: rotated feature f by pose P: f@P
|
| 12 |
+
"""
|
| 13 |
+
f = einops.rearrange(f, "... (d k) -> ... d k", k=4) # (B, N, L, C) -> (B, N, L, C//4, 4)
|
| 14 |
+
if is_query:
|
| 15 |
+
P = torch.inverse(P).permute(0, 1, 3, 2) # we need transpose here as key would be transposes in attention
|
| 16 |
+
P = einops.repeat(P, "b t m n -> b l t m n", l=f.shape[1])
|
| 17 |
+
return einops.rearrange(f @ P, "... d k -> ... (d k)", k=4)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
########################## 6DoF CaPE ####################################
|
| 21 |
+
# class CaPE_6DoF:
|
| 22 |
+
# def cape_embed(self, f, P):
|
| 23 |
+
# """
|
| 24 |
+
# Apply CaPE on feature.
|
| 25 |
+
# :param f: feature vector of shape [..., d]
|
| 26 |
+
# :param P: 4x4 transformation matrix
|
| 27 |
+
# :return: rotated feature f by pose P: f@P
|
| 28 |
+
# """
|
| 29 |
+
# f = einops.rearrange(f, '... (d k) -> ... d k', k=4)
|
| 30 |
+
# return einops.rearrange(f@P, '... d k -> ... (d k)', k=4)
|
| 31 |
+
|
| 32 |
+
# def attn_with_CaPE(self, f1, f2, p1, p2):
|
| 33 |
+
# """
|
| 34 |
+
# Do attention dot production with CaPE pose encoding.
|
| 35 |
+
# # query = cape_embed(query, p_out_inv) # query f_q @ (p_out)^(-T)
|
| 36 |
+
# # key = cape_embed(key, p_in) # key f_k @ p_in
|
| 37 |
+
# :param f1: b (t1 l) d
|
| 38 |
+
# :param f2: b (t2 l) d
|
| 39 |
+
# :param p1: [b, t, 4, 4]
|
| 40 |
+
# :param p2: [b, t, 4, 4]
|
| 41 |
+
# :return: attention score: q@k.T
|
| 42 |
+
# """
|
| 43 |
+
# l = f1.shape[1] // p1.shape[1]
|
| 44 |
+
# assert f1.shape[1] // p1.shape[1] == f2.shape[1] // p2.shape[1]
|
| 45 |
+
# p1_invT = einops.repeat(torch.inverse(p1).permute(0, 1, 3, 2), 'b t m n -> b (t l) m n', l=l) # f1 [b, l*t1, d]
|
| 46 |
+
# query = self.cape_embed(f1, p1_invT) # [b, l*t1, d] query: f1 @ (p1)^(-T), transpose the last two dim
|
| 47 |
+
# p2_copy = einops.repeat(p2, 'b t m n -> b (t l) m n', l=l) # f2 [b, l*t2, d]
|
| 48 |
+
# key = self.cape_embed(f2, p2_copy) # [b, l*t2, d] key: f2 @ p2
|
| 49 |
+
# att = query @ key.permute(0, 2, 1) # [b, l*t1, l*t2] attention: query@key^T
|
| 50 |
+
# return att
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
# ################### 6DoF Verification ###################################
|
| 54 |
+
# def euler_to_matrix(alpha, beta, gamma, x, y, z):
|
| 55 |
+
# # radian
|
| 56 |
+
# r = R.from_euler('xyz', [alpha, beta, gamma], degrees=True)
|
| 57 |
+
# t = np.array([[x], [y], [z]])
|
| 58 |
+
# rot_matrix = r.as_matrix()
|
| 59 |
+
# rot_matrix = np.concatenate([rot_matrix, t], axis=-1)
|
| 60 |
+
# rot_matrix = np.concatenate([rot_matrix, [[0, 0, 0, 1]]], axis=0)
|
| 61 |
+
# return rot_matrix
|
| 62 |
+
|
| 63 |
+
# def random_6dof_pose(B, T):
|
| 64 |
+
# pose_euler = torch.rand([B, T, 6]).numpy() # euler
|
| 65 |
+
# pose_matrix = []
|
| 66 |
+
# for b in range(B):
|
| 67 |
+
# p = []
|
| 68 |
+
# for t in range(T):
|
| 69 |
+
# p.append(torch.from_numpy(euler_to_matrix(*pose_euler[b, t])))
|
| 70 |
+
# pose_matrix.append(torch.stack(p))
|
| 71 |
+
# pose_matrix = torch.stack(pose_matrix)
|
| 72 |
+
# return pose_matrix.float()
|
| 73 |
+
|
| 74 |
+
# bs = 6 # batch size
|
| 75 |
+
# t1 = 3 # num of target views in each batch, can be arbitrary number
|
| 76 |
+
# t2 = 5 # num of reference views in each batch, can be arbitrary number
|
| 77 |
+
# l = 10 # len of token
|
| 78 |
+
# d = 16 # dim of token feature, need to mod 4 in this case
|
| 79 |
+
# assert d % 4 == 0
|
| 80 |
+
|
| 81 |
+
# # random init query and key
|
| 82 |
+
# f1 = torch.rand(bs, t1, l, d) # query
|
| 83 |
+
# f2 = torch.rand(bs, t2, l, d) # key
|
| 84 |
+
# f1 = einops.rearrange(f1, 'b t l d -> b (t l) d')
|
| 85 |
+
# f2 = einops.rearrange(f2, 'b t l d -> b (t l) d')
|
| 86 |
+
|
| 87 |
+
# # random init pose p1, p2, delta_p, [bs, t, 4, 4]
|
| 88 |
+
# p1 = random_6dof_pose(bs, t1) # [bs, t1, 4, 4]
|
| 89 |
+
# p2 = random_6dof_pose(bs, t2) # [bs, t2, 4, 4]
|
| 90 |
+
# p_delta = random_6dof_pose(bs, 1) # [bs, 1, 4, 4]
|
| 91 |
+
# # delta p is identical to p1 and p2 in each batch
|
| 92 |
+
# p1_delta = einops.repeat(p_delta, 'b 1 m n -> b (1 t) m n', t=t1//1)
|
| 93 |
+
# p2_delta = einops.repeat(p_delta, 'b 1 m n -> b (1 t) m n', t=t2//1)
|
| 94 |
+
|
| 95 |
+
# # run attention with CaPE 6DoF
|
| 96 |
+
# cape_6dof = CaPE_6DoF()
|
| 97 |
+
# # att
|
| 98 |
+
# att = cape_6dof.attn_with_CaPE(f1, f2, p1, p2)
|
| 99 |
+
# # att_delta
|
| 100 |
+
# att_delta = cape_6dof.attn_with_CaPE(f1, f2, p1@p1_delta, p2@p2_delta)
|
| 101 |
+
|
| 102 |
+
# # condition: att score should be the same i.e. non effect from any delta_p
|
| 103 |
+
# assert torch.allclose(att, att_delta, 1e-3)
|
| 104 |
+
# print("6DoF CaPE Verified")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class PointRoPE(nn.Module):
|
| 108 |
+
def __init__(self, d_model):
|
| 109 |
+
super().__init__()
|
| 110 |
+
self.d_model = d_model
|
| 111 |
+
assert d_model % 6 == 0
|
| 112 |
+
|
| 113 |
+
def rotate_every_two(self, x):
|
| 114 |
+
x = einops.rearrange(x, "... (d j) -> ... d j", j=2) # (B, N, M, C) -> (B, N, M, C//2, 2)
|
| 115 |
+
x1, x2 = x.unbind(dim=-1)
|
| 116 |
+
x = torch.stack((-x2, x1), dim=-1) # (B, N, M, C//2, 2) -> (B, N, M, C//2, 2)
|
| 117 |
+
return einops.rearrange(x, "... d j -> ... (d j)") # (B, N, M, C//2, 2) -> (B, N, M, C)
|
| 118 |
+
|
| 119 |
+
def cape(self, x, p):
|
| 120 |
+
d, m, n = x.shape[-1], p.shape[-2], p.shape[-1]
|
| 121 |
+
assert d % (2 * n) == 0
|
| 122 |
+
emb = einops.repeat(p, "... n -> ... (n k)", k=d // n) # (B, N, M, 3) => (B, N, M, C)
|
| 123 |
+
return emb
|
| 124 |
+
|
| 125 |
+
def cape_embed(self, qq, kk, p1, p2):
|
| 126 |
+
"""
|
| 127 |
+
Embed camera position encoding into attention map
|
| 128 |
+
:param qq: query feature map [b, n, l_q, feature_dim]
|
| 129 |
+
:param kk: key feature map [b, n, l_k, feature_dim]
|
| 130 |
+
:param p1: query pose [b, l_q, pose_dim]
|
| 131 |
+
:param p2: key pose [b, l_k, pose_dim]
|
| 132 |
+
:return: cape embedded attention map [b, n, l_q, l_k]
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
p1 = einops.repeat(p1, "b l d -> b n l d", n=qq.shape[1])
|
| 136 |
+
p2 = einops.repeat(p2, "b l d -> b n l d", n=kk.shape[1])
|
| 137 |
+
|
| 138 |
+
m1 = self.cape(qq, p1)
|
| 139 |
+
m2 = self.cape(kk, p2)
|
| 140 |
+
|
| 141 |
+
q = (qq * m1.cos()) + (self.rotate_every_two(qq) * m1.sin())
|
| 142 |
+
k = (kk * m2.cos()) + (self.rotate_every_two(kk) * m2.sin())
|
| 143 |
+
|
| 144 |
+
return q, k
|
upstream/CoDA/coda/network/base_arch/transformer/__pycache__/layer.cpython-310.pyc
ADDED
|
Binary file (661 Bytes). View file
|
|
|
upstream/CoDA/coda/network/base_arch/transformer/encoder_trajrope.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import math
|
| 5 |
+
from timm.models.vision_transformer import Mlp
|
| 6 |
+
from typing import Optional, Tuple
|
| 7 |
+
from einops import einsum, rearrange, repeat
|
| 8 |
+
from coda.network.base_arch.embeddings.rotary_embedding import ROPE
|
| 9 |
+
from coda.network.base_arch.embeddings.cape import cape_embed
|
| 10 |
+
from coda.network.base_arch.transformer.encoder_rope import RoPEAttention
|
| 11 |
+
from coda.network.base_arch.transformer.encoder import Attention
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TrajRoPEAttention(nn.Module):
|
| 15 |
+
def __init__(self, embed_dim, num_heads, dropout=0.1):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.embed_dim = embed_dim
|
| 18 |
+
self.num_heads = num_heads
|
| 19 |
+
self.head_dim = embed_dim // num_heads
|
| 20 |
+
|
| 21 |
+
self.query = nn.Linear(embed_dim, embed_dim)
|
| 22 |
+
self.key = nn.Linear(embed_dim, embed_dim)
|
| 23 |
+
self.value = nn.Linear(embed_dim, embed_dim)
|
| 24 |
+
self.dropout = nn.Dropout(dropout)
|
| 25 |
+
self.proj = nn.Linear(embed_dim, embed_dim)
|
| 26 |
+
|
| 27 |
+
def forward(self, x, traj, attn_mask=None, key_padding_mask=None):
|
| 28 |
+
# x: (B, L, C)
|
| 29 |
+
# traj: (B, L, 4, 4)
|
| 30 |
+
# attn_mask: (L, L)
|
| 31 |
+
# key_padding_mask: (B, L)
|
| 32 |
+
B, L, _ = x.shape
|
| 33 |
+
xq, xk, xv = self.query(x), self.key(x), self.value(x)
|
| 34 |
+
|
| 35 |
+
xq = xq.reshape(B, L, self.num_heads, -1).transpose(1, 2) # B, N, L, C
|
| 36 |
+
xk = xk.reshape(B, L, self.num_heads, -1).transpose(1, 2) # B, N, L, C
|
| 37 |
+
xv = xv.reshape(B, L, self.num_heads, -1).transpose(1, 2) # B, N, L, C
|
| 38 |
+
|
| 39 |
+
xq = cape_embed(xq, traj, is_query=True) # B, N, L, C
|
| 40 |
+
xk = cape_embed(xk, traj, is_query=False) # B, N, L, C
|
| 41 |
+
|
| 42 |
+
attn_score = einsum(xq, xk, "b n i c, b n j c -> b n i j") / math.sqrt(self.head_dim)
|
| 43 |
+
if attn_mask is not None:
|
| 44 |
+
attn_mask = attn_mask.reshape(1, 1, L, L).expand(B, self.num_heads, -1, -1)
|
| 45 |
+
attn_score = attn_score.masked_fill(attn_mask, float("-inf"))
|
| 46 |
+
if key_padding_mask is not None:
|
| 47 |
+
key_padding_mask = key_padding_mask.reshape(B, 1, 1, L).expand(-1, self.num_heads, L, -1)
|
| 48 |
+
attn_score = attn_score.masked_fill(key_padding_mask, float("-inf"))
|
| 49 |
+
|
| 50 |
+
attn_score = torch.softmax(attn_score, dim=-1)
|
| 51 |
+
attn_score = self.dropout(attn_score)
|
| 52 |
+
output = einsum(attn_score, xv, "b n i j, b n j c -> b n i c") # B, N, L, C
|
| 53 |
+
output = output.transpose(1, 2).reshape(B, L, -1) # B, L, C
|
| 54 |
+
output = self.proj(output) # B, L, C
|
| 55 |
+
return output
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class EncoderTrajRoPEBlock(nn.Module):
|
| 59 |
+
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, dropout=0.1, **block_kwargs):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 62 |
+
self.attn = RoPEAttention(hidden_size, num_heads, dropout)
|
| 63 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 64 |
+
self.trajattn = TrajRoPEAttention(hidden_size, num_heads, dropout)
|
| 65 |
+
self.norm3 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 66 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 67 |
+
approx_gelu = lambda: nn.GELU(approximate="tanh")
|
| 68 |
+
self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=dropout)
|
| 69 |
+
|
| 70 |
+
self.gate_msa = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 71 |
+
self.gate_msa2 = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 72 |
+
self.gate_mlp = nn.Parameter(torch.zeros(1, 1, hidden_size))
|
| 73 |
+
|
| 74 |
+
# Zero-out adaLN modulation layers
|
| 75 |
+
nn.init.constant_(self.gate_msa, 0)
|
| 76 |
+
nn.init.constant_(self.gate_msa2, 0)
|
| 77 |
+
nn.init.constant_(self.gate_mlp, 0)
|
| 78 |
+
|
| 79 |
+
def forward(self, x, traj, attn_mask=None, tgt_key_padding_mask=None):
|
| 80 |
+
x = x + self.gate_msa * self._sa_block(
|
| 81 |
+
self.norm1(x), attn_mask=attn_mask, key_padding_mask=tgt_key_padding_mask
|
| 82 |
+
)
|
| 83 |
+
x = x + self.gate_msa2 * self._traja_block(
|
| 84 |
+
self.norm2(x), traj, attn_mask=attn_mask, key_padding_mask=tgt_key_padding_mask
|
| 85 |
+
)
|
| 86 |
+
x = x + self.gate_mlp * self.mlp(self.norm3(x))
|
| 87 |
+
return x
|
| 88 |
+
|
| 89 |
+
def _sa_block(self, x, attn_mask=None, key_padding_mask=None):
|
| 90 |
+
# x: (B, L, C)
|
| 91 |
+
x = self.attn(x, attn_mask=attn_mask, key_padding_mask=key_padding_mask)
|
| 92 |
+
return x
|
| 93 |
+
|
| 94 |
+
def _traja_block(self, x, traj, attn_mask=None, key_padding_mask=None):
|
| 95 |
+
# x: (B, L, C)
|
| 96 |
+
x = self.trajattn(x, traj, attn_mask=attn_mask, key_padding_mask=key_padding_mask)
|
| 97 |
+
return x
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def modulate(x, shift, scale):
|
| 101 |
+
return x * (1 + scale) + shift
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class EncoderTrajRoPEBlockDIT(nn.Module):
|
| 105 |
+
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, dropout=0.1, **block_kwargs):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 108 |
+
self.attn = RoPEAttention(hidden_size, num_heads, dropout)
|
| 109 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 110 |
+
self.trajattn = TrajRoPEAttention(hidden_size, num_heads, dropout)
|
| 111 |
+
self.norm3 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 112 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 113 |
+
approx_gelu = lambda: nn.GELU(approximate="tanh")
|
| 114 |
+
self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=dropout)
|
| 115 |
+
|
| 116 |
+
self.adaLN_modulation = nn.Sequential(
|
| 117 |
+
nn.SiLU(),
|
| 118 |
+
nn.Linear(hidden_size, hidden_size * 9, bias=True),
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
def forward(self, x, traj, c, attn_mask=None, tgt_key_padding_mask=None):
|
| 122 |
+
shift_msa, scale_msa, gate_msa, shift_traj, scale_traj, gate_traj, shift_mlp, scale_mlp, gate_mlp = (
|
| 123 |
+
self.adaLN_modulation(c).chunk(9, dim=-1)
|
| 124 |
+
)
|
| 125 |
+
x = x + gate_msa * self._sa_block(
|
| 126 |
+
modulate(self.norm1(x), shift_msa, scale_msa), attn_mask=attn_mask, key_padding_mask=tgt_key_padding_mask
|
| 127 |
+
)
|
| 128 |
+
x = x + gate_traj * self._traja_block(
|
| 129 |
+
modulate(self.norm2(x), shift_traj, scale_traj),
|
| 130 |
+
traj,
|
| 131 |
+
attn_mask=attn_mask,
|
| 132 |
+
key_padding_mask=tgt_key_padding_mask,
|
| 133 |
+
)
|
| 134 |
+
x = x + gate_mlp * self.mlp(modulate(self.norm3(x), shift_mlp, scale_mlp))
|
| 135 |
+
return x
|
| 136 |
+
|
| 137 |
+
def _sa_block(self, x, attn_mask=None, key_padding_mask=None):
|
| 138 |
+
# x: (B, L, C)
|
| 139 |
+
x = self.attn(x, attn_mask=attn_mask, key_padding_mask=key_padding_mask)
|
| 140 |
+
return x
|
| 141 |
+
|
| 142 |
+
def _traja_block(self, x, traj, attn_mask=None, key_padding_mask=None):
|
| 143 |
+
# x: (B, L, C)
|
| 144 |
+
x = self.trajattn(x, traj, attn_mask=attn_mask, key_padding_mask=key_padding_mask)
|
| 145 |
+
return x
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class EncoderTrajRoPEBlockDITabsT(nn.Module):
|
| 149 |
+
def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, dropout=0.1, **block_kwargs):
|
| 150 |
+
super().__init__()
|
| 151 |
+
self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 152 |
+
self.attn = Attention(hidden_size, num_heads, dropout)
|
| 153 |
+
self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 154 |
+
self.trajattn = TrajRoPEAttention(hidden_size, num_heads, dropout)
|
| 155 |
+
self.norm3 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
|
| 156 |
+
mlp_hidden_dim = int(hidden_size * mlp_ratio)
|
| 157 |
+
approx_gelu = lambda: nn.GELU(approximate="tanh")
|
| 158 |
+
self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=dropout)
|
| 159 |
+
|
| 160 |
+
self.adaLN_modulation = nn.Sequential(
|
| 161 |
+
nn.SiLU(),
|
| 162 |
+
nn.Linear(hidden_size, hidden_size * 9, bias=True),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
def forward(self, x, traj, c, attn_mask=None, tgt_key_padding_mask=None):
|
| 166 |
+
shift_msa, scale_msa, gate_msa, shift_traj, scale_traj, gate_traj, shift_mlp, scale_mlp, gate_mlp = (
|
| 167 |
+
self.adaLN_modulation(c).chunk(9, dim=-1)
|
| 168 |
+
)
|
| 169 |
+
x = x + gate_msa * self._sa_block(
|
| 170 |
+
modulate(self.norm1(x), shift_msa, scale_msa), attn_mask=attn_mask, key_padding_mask=tgt_key_padding_mask
|
| 171 |
+
)
|
| 172 |
+
x = x + gate_traj * self._traja_block(
|
| 173 |
+
modulate(self.norm2(x), shift_traj, scale_traj),
|
| 174 |
+
traj,
|
| 175 |
+
attn_mask=attn_mask,
|
| 176 |
+
key_padding_mask=tgt_key_padding_mask,
|
| 177 |
+
)
|
| 178 |
+
x = x + gate_mlp * self.mlp(modulate(self.norm3(x), shift_mlp, scale_mlp))
|
| 179 |
+
return x
|
| 180 |
+
|
| 181 |
+
def _sa_block(self, x, attn_mask=None, key_padding_mask=None):
|
| 182 |
+
# x: (B, L, C)
|
| 183 |
+
x = self.attn(x, attn_mask=attn_mask, key_padding_mask=key_padding_mask)
|
| 184 |
+
return x
|
| 185 |
+
|
| 186 |
+
def _traja_block(self, x, traj, attn_mask=None, key_padding_mask=None):
|
| 187 |
+
# x: (B, L, C)
|
| 188 |
+
x = self.trajattn(x, traj, attn_mask=attn_mask, key_padding_mask=key_padding_mask)
|
| 189 |
+
return x
|
upstream/CoDA/coda/network/base_arch/transformer/layer.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def zero_module(module, nozero=False):
|
| 7 |
+
"""
|
| 8 |
+
Zero out the parameters of a module and return it.
|
| 9 |
+
"""
|
| 10 |
+
if nozero:
|
| 11 |
+
return module
|
| 12 |
+
for p in module.parameters():
|
| 13 |
+
p.detach().zero_()
|
| 14 |
+
return module
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def modulate(x, shift, scale):
|
| 18 |
+
return x * (1 + scale) + shift
|
upstream/CoDA/coda/network/transformer/rope_transformer.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 7 |
+
from coda.network.base_arch.transformer.encoder_rope import EncoderRoPEBlock, EncoderRoPEBlockDIT
|
| 8 |
+
from coda.network.base_arch.embeddings.pos_emb import PositionalEncoding, TimestepEmbedder
|
| 9 |
+
from coda.network.base_arch.transformer.layer import zero_module
|
| 10 |
+
|
| 11 |
+
from coda.utils.net_utils import length_to_mask
|
| 12 |
+
from timm.models.vision_transformer import Mlp
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class NetworkEncoderRoPE(nn.Module):
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
# x
|
| 19 |
+
output_dim=46, # 3 * 12 + 10
|
| 20 |
+
max_len=300,
|
| 21 |
+
# condition
|
| 22 |
+
objtraj_dim=19, # 6+12+1
|
| 23 |
+
obj_dim=0,
|
| 24 |
+
beta_dim=16,
|
| 25 |
+
skeleton_dim=0,
|
| 26 |
+
bps_dim=0,
|
| 27 |
+
clip_dim=0,
|
| 28 |
+
verts_dim=0,
|
| 29 |
+
first_x_dim=0,
|
| 30 |
+
contact_mask_dim=0,
|
| 31 |
+
# intermediate
|
| 32 |
+
latent_dim=512,
|
| 33 |
+
num_layers=12,
|
| 34 |
+
num_heads=8,
|
| 35 |
+
mlp_ratio=4.0,
|
| 36 |
+
# training
|
| 37 |
+
dropout=0.1,
|
| 38 |
+
is_dit=False,
|
| 39 |
+
):
|
| 40 |
+
super().__init__()
|
| 41 |
+
|
| 42 |
+
# input
|
| 43 |
+
self.output_dim = output_dim
|
| 44 |
+
self.max_len = max_len
|
| 45 |
+
|
| 46 |
+
# condition
|
| 47 |
+
self.objtraj_dim = objtraj_dim
|
| 48 |
+
self.obj_dim = obj_dim
|
| 49 |
+
self.beta_dim = beta_dim
|
| 50 |
+
self.skeleton_dim = skeleton_dim
|
| 51 |
+
self.bps_dim = bps_dim
|
| 52 |
+
self.verts_dim = verts_dim
|
| 53 |
+
self.clip_dim = clip_dim
|
| 54 |
+
self.first_x_dim = first_x_dim
|
| 55 |
+
self.contact_mask_dim = contact_mask_dim
|
| 56 |
+
# intermediate
|
| 57 |
+
self.latent_dim = latent_dim
|
| 58 |
+
self.num_layers = num_layers
|
| 59 |
+
self.num_heads = num_heads
|
| 60 |
+
self.dropout = dropout
|
| 61 |
+
|
| 62 |
+
self.is_dit = is_dit
|
| 63 |
+
|
| 64 |
+
# ===== build model ===== #
|
| 65 |
+
self._build_condition_embedder()
|
| 66 |
+
|
| 67 |
+
block_cls = EncoderRoPEBlockDIT if self.is_dit else EncoderRoPEBlock
|
| 68 |
+
|
| 69 |
+
# Transformer
|
| 70 |
+
self.blocks = nn.ModuleList(
|
| 71 |
+
[
|
| 72 |
+
block_cls(self.latent_dim, self.num_heads, mlp_ratio=mlp_ratio, dropout=dropout)
|
| 73 |
+
for _ in range(self.num_layers)
|
| 74 |
+
]
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# Output heads
|
| 78 |
+
self.final_layer = Mlp(self.latent_dim, out_features=self.output_dim)
|
| 79 |
+
|
| 80 |
+
def _build_condition_embedder(self):
|
| 81 |
+
latent_dim = self.latent_dim
|
| 82 |
+
dropout = self.dropout
|
| 83 |
+
self.sequence_pos_encoder = PositionalEncoding(self.latent_dim, self.dropout)
|
| 84 |
+
self.embed_timestep = TimestepEmbedder(self.latent_dim, self.sequence_pos_encoder)
|
| 85 |
+
self.input_layer = nn.Sequential(
|
| 86 |
+
nn.Linear(self.output_dim, latent_dim),
|
| 87 |
+
nn.SiLU(),
|
| 88 |
+
)
|
| 89 |
+
if self.objtraj_dim > 0:
|
| 90 |
+
self.objtraj_embedder = nn.Sequential(
|
| 91 |
+
nn.Linear(self.objtraj_dim, latent_dim),
|
| 92 |
+
nn.SiLU(),
|
| 93 |
+
nn.Dropout(dropout),
|
| 94 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 95 |
+
)
|
| 96 |
+
if self.obj_dim > 0:
|
| 97 |
+
self.obj_embedder = nn.Sequential(
|
| 98 |
+
nn.Linear(self.obj_dim, latent_dim),
|
| 99 |
+
nn.SiLU(),
|
| 100 |
+
nn.Dropout(dropout),
|
| 101 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 102 |
+
)
|
| 103 |
+
if self.beta_dim > 0:
|
| 104 |
+
self.beta_embedder = nn.Sequential(
|
| 105 |
+
nn.Linear(self.beta_dim, latent_dim),
|
| 106 |
+
nn.SiLU(),
|
| 107 |
+
nn.Dropout(dropout),
|
| 108 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 109 |
+
)
|
| 110 |
+
if self.skeleton_dim > 0:
|
| 111 |
+
self.skeleton_embedder = nn.Sequential(
|
| 112 |
+
nn.Linear(self.skeleton_dim, latent_dim),
|
| 113 |
+
nn.SiLU(),
|
| 114 |
+
nn.Dropout(dropout),
|
| 115 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 116 |
+
)
|
| 117 |
+
if self.clip_dim > 0:
|
| 118 |
+
self.clip_embedder = nn.Sequential(
|
| 119 |
+
nn.Linear(self.clip_dim, latent_dim),
|
| 120 |
+
nn.SiLU(),
|
| 121 |
+
nn.Dropout(dropout),
|
| 122 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 123 |
+
)
|
| 124 |
+
if self.bps_dim > 0:
|
| 125 |
+
self.bps_embedder = nn.Sequential(
|
| 126 |
+
nn.Linear(self.bps_dim, latent_dim),
|
| 127 |
+
nn.SiLU(),
|
| 128 |
+
nn.Dropout(dropout),
|
| 129 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 130 |
+
)
|
| 131 |
+
if self.verts_dim > 0:
|
| 132 |
+
self.verts_embedder = nn.Sequential(
|
| 133 |
+
nn.Linear(self.verts_dim, latent_dim),
|
| 134 |
+
nn.SiLU(),
|
| 135 |
+
nn.Dropout(dropout),
|
| 136 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 137 |
+
)
|
| 138 |
+
if self.first_x_dim > 0:
|
| 139 |
+
self.first_x_embedder = nn.Sequential(
|
| 140 |
+
nn.Linear(self.first_x_dim, latent_dim),
|
| 141 |
+
nn.SiLU(),
|
| 142 |
+
nn.Dropout(dropout),
|
| 143 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 144 |
+
)
|
| 145 |
+
if self.contact_mask_dim > 0:
|
| 146 |
+
self.contact_mask_embedder = nn.Sequential(
|
| 147 |
+
nn.Linear(self.contact_mask_dim, latent_dim),
|
| 148 |
+
nn.SiLU(),
|
| 149 |
+
nn.Dropout(dropout),
|
| 150 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def forward(
|
| 154 |
+
self,
|
| 155 |
+
x,
|
| 156 |
+
timesteps,
|
| 157 |
+
length,
|
| 158 |
+
obj=None,
|
| 159 |
+
objtraj=None,
|
| 160 |
+
beta=None,
|
| 161 |
+
skeleton=None,
|
| 162 |
+
bps=None,
|
| 163 |
+
verts=None,
|
| 164 |
+
f_text=None,
|
| 165 |
+
first_x=None,
|
| 166 |
+
contact_mask=None,
|
| 167 |
+
**kwargs
|
| 168 |
+
):
|
| 169 |
+
"""
|
| 170 |
+
Args:
|
| 171 |
+
length: (B), valid length of x, if None then use x.shape[2]
|
| 172 |
+
x: (B, L, C)
|
| 173 |
+
timesteps: (B) int
|
| 174 |
+
obj: (B, C)
|
| 175 |
+
objtraj: (B, L, C)
|
| 176 |
+
beta: (B, L, C)
|
| 177 |
+
bps: (B, L, C)
|
| 178 |
+
verts: (B, L, C)
|
| 179 |
+
f_text: (B, D)
|
| 180 |
+
first_x: (B, 1, C)
|
| 181 |
+
"""
|
| 182 |
+
B, L, _ = x.shape
|
| 183 |
+
|
| 184 |
+
emb = self.embed_timestep(timesteps, is_BLC=True) # (B, 1, C)
|
| 185 |
+
x = self.input_layer(x) # (B, L, C)
|
| 186 |
+
x = x + emb
|
| 187 |
+
|
| 188 |
+
# Condition
|
| 189 |
+
f_to_add = []
|
| 190 |
+
if obj is not None and hasattr(self, "obj_embedder"):
|
| 191 |
+
f_to_add.append(self.obj_embedder(obj))
|
| 192 |
+
if objtraj is not None and hasattr(self, "objtraj_embedder"):
|
| 193 |
+
f_to_add.append(self.objtraj_embedder(objtraj))
|
| 194 |
+
if beta is not None and hasattr(self, "beta_embedder"):
|
| 195 |
+
f_to_add.append(self.beta_embedder(beta))
|
| 196 |
+
if bps is not None and hasattr(self, "bps_embedder"):
|
| 197 |
+
f_to_add.append(self.bps_embedder(bps))
|
| 198 |
+
if f_text is not None and hasattr(self, "clip_embedder"):
|
| 199 |
+
f_to_add.append(self.clip_embedder(f_text)[..., None, :])
|
| 200 |
+
if verts is not None and hasattr(self, "verts_embedder"):
|
| 201 |
+
f_to_add.append(self.verts_embedder(verts))
|
| 202 |
+
if skeleton is not None and hasattr(self, "skeleton_embedder"):
|
| 203 |
+
f_to_add.append(self.skeleton_embedder(skeleton))
|
| 204 |
+
if first_x is not None and hasattr(self, "first_x_embedder"):
|
| 205 |
+
f_to_add.append(self.first_x_embedder(first_x))
|
| 206 |
+
if contact_mask is not None and hasattr(self, "contact_mask_embedder"):
|
| 207 |
+
f_to_add.append(self.contact_mask_embedder(contact_mask))
|
| 208 |
+
|
| 209 |
+
if self.is_dit:
|
| 210 |
+
c = torch.zeros_like(x)
|
| 211 |
+
for f_delta in f_to_add:
|
| 212 |
+
c = c + f_delta
|
| 213 |
+
else:
|
| 214 |
+
for f_delta in f_to_add:
|
| 215 |
+
x = x + f_delta
|
| 216 |
+
|
| 217 |
+
# Setup length and make padding mask
|
| 218 |
+
assert B == length.size(0)
|
| 219 |
+
pmask = length_to_mask(length, L) # (B, L)
|
| 220 |
+
|
| 221 |
+
if L > self.max_len:
|
| 222 |
+
attnmask = torch.ones((L, L), device=x.device, dtype=torch.bool)
|
| 223 |
+
for i in range(L):
|
| 224 |
+
min_ind = max(0, i - self.max_len // 2)
|
| 225 |
+
max_ind = min(L, i + self.max_len // 2)
|
| 226 |
+
max_ind = max(self.max_len, max_ind)
|
| 227 |
+
min_ind = min(L - self.max_len, min_ind)
|
| 228 |
+
attnmask[i, min_ind:max_ind] = False
|
| 229 |
+
else:
|
| 230 |
+
attnmask = None
|
| 231 |
+
|
| 232 |
+
# Transformer
|
| 233 |
+
for block in self.blocks:
|
| 234 |
+
if self.is_dit:
|
| 235 |
+
x = block(x, c=c, attn_mask=attnmask, tgt_key_padding_mask=~pmask)
|
| 236 |
+
else:
|
| 237 |
+
x = block(x, attn_mask=attnmask, tgt_key_padding_mask=~pmask)
|
| 238 |
+
|
| 239 |
+
# Output
|
| 240 |
+
sample = self.final_layer(x) # (B, L, C)
|
| 241 |
+
|
| 242 |
+
output = {
|
| 243 |
+
"pred_context": x,
|
| 244 |
+
"sample": sample,
|
| 245 |
+
"mask": pmask,
|
| 246 |
+
}
|
| 247 |
+
return output
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# Add to MainStore
|
| 251 |
+
group_name = "network/diffusion"
|
| 252 |
+
MainStore.store(
|
| 253 |
+
name="invtraj_transformer",
|
| 254 |
+
node=builds(NetworkEncoderRoPE, populate_full_signature=True),
|
| 255 |
+
group=group_name,
|
| 256 |
+
)
|
| 257 |
+
MainStore.store(
|
| 258 |
+
name="bpsinvtraj_transformer",
|
| 259 |
+
node=builds(NetworkEncoderRoPE, objtraj_dim=11, bps_dim=256, populate_full_signature=True),
|
| 260 |
+
group=group_name,
|
| 261 |
+
)
|
| 262 |
+
MainStore.store(
|
| 263 |
+
name="bpstraj_transformer",
|
| 264 |
+
node=builds(NetworkEncoderRoPE, output_dim=3082, objtraj_dim=17, bps_dim=256, populate_full_signature=True),
|
| 265 |
+
group=group_name,
|
| 266 |
+
)
|
| 267 |
+
MainStore.store(
|
| 268 |
+
name="bpstrajnorot_transformer",
|
| 269 |
+
node=builds(NetworkEncoderRoPE, output_dim=3082, objtraj_dim=4, bps_dim=256, populate_full_signature=True),
|
| 270 |
+
group=group_name,
|
| 271 |
+
)
|
| 272 |
+
MainStore.store(
|
| 273 |
+
name="handpose_transformer",
|
| 274 |
+
node=builds(NetworkEncoderRoPE, max_len=300, output_dim=90, objtraj_dim=0, populate_full_signature=True),
|
| 275 |
+
group=group_name,
|
| 276 |
+
)
|
| 277 |
+
MainStore.store(
|
| 278 |
+
name="bodypose_transformer",
|
| 279 |
+
node=builds(
|
| 280 |
+
NetworkEncoderRoPE,
|
| 281 |
+
max_len=300,
|
| 282 |
+
output_dim=143,
|
| 283 |
+
objtraj_dim=0,
|
| 284 |
+
beta_dim=10,
|
| 285 |
+
clip_dim=512,
|
| 286 |
+
populate_full_signature=True,
|
| 287 |
+
),
|
| 288 |
+
group=group_name,
|
| 289 |
+
)
|
| 290 |
+
MainStore.store(
|
| 291 |
+
name="bodypose_angley_transformer",
|
| 292 |
+
node=builds(
|
| 293 |
+
NetworkEncoderRoPE,
|
| 294 |
+
max_len=300,
|
| 295 |
+
output_dim=140,
|
| 296 |
+
objtraj_dim=0,
|
| 297 |
+
beta_dim=10,
|
| 298 |
+
clip_dim=512,
|
| 299 |
+
populate_full_signature=True,
|
| 300 |
+
),
|
| 301 |
+
group=group_name,
|
| 302 |
+
)
|
| 303 |
+
MainStore.store(
|
| 304 |
+
name="wholebody_transformer",
|
| 305 |
+
node=builds(
|
| 306 |
+
NetworkEncoderRoPE,
|
| 307 |
+
max_len=300,
|
| 308 |
+
output_dim=333,
|
| 309 |
+
objtraj_dim=11,
|
| 310 |
+
beta_dim=16,
|
| 311 |
+
bps_dim=256,
|
| 312 |
+
clip_dim=512,
|
| 313 |
+
populate_full_signature=True,
|
| 314 |
+
),
|
| 315 |
+
group=group_name,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
group_name = "network1/diffusion"
|
| 320 |
+
MainStore.store(
|
| 321 |
+
name="handpose_transformer",
|
| 322 |
+
node=builds(NetworkEncoderRoPE, max_len=300, output_dim=90, objtraj_dim=0, populate_full_signature=True),
|
| 323 |
+
group=group_name,
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
group_name = "network2/diffusion"
|
| 328 |
+
MainStore.store(
|
| 329 |
+
name="handpose_transformer",
|
| 330 |
+
node=builds(NetworkEncoderRoPE, max_len=300, output_dim=90, objtraj_dim=0, populate_full_signature=True),
|
| 331 |
+
group=group_name,
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
group_name = "network3/diffusion"
|
| 335 |
+
MainStore.store(
|
| 336 |
+
name="invtraj_transformer",
|
| 337 |
+
node=builds(NetworkEncoderRoPE, populate_full_signature=True),
|
| 338 |
+
group=group_name,
|
| 339 |
+
)
|
| 340 |
+
MainStore.store(
|
| 341 |
+
name="bpstraj_transformer",
|
| 342 |
+
node=builds(NetworkEncoderRoPE, output_dim=3082, objtraj_dim=17, bps_dim=256, populate_full_signature=True),
|
| 343 |
+
group=group_name,
|
| 344 |
+
)
|
| 345 |
+
MainStore.store(
|
| 346 |
+
name="bpsinvtraj_transformer",
|
| 347 |
+
node=builds(NetworkEncoderRoPE, objtraj_dim=11, bps_dim=256, populate_full_signature=True),
|
| 348 |
+
group=group_name,
|
| 349 |
+
)
|
upstream/CoDA/coda/network/transformer/trajrope_transformer.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 5 |
+
from coda.configs import MainStore, builds
|
| 6 |
+
|
| 7 |
+
from coda.network.base_arch.transformer.encoder_trajrope import EncoderTrajRoPEBlock, EncoderTrajRoPEBlockDIT
|
| 8 |
+
from coda.network.base_arch.embeddings.pos_emb import PositionalEncoding, TimestepEmbedder
|
| 9 |
+
from coda.network.base_arch.transformer.layer import zero_module
|
| 10 |
+
|
| 11 |
+
from coda.utils.net_utils import length_to_mask
|
| 12 |
+
from timm.models.vision_transformer import Mlp
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class NetworkEncoderRoPE(nn.Module):
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
# x
|
| 19 |
+
output_dim=46, # 3 * 12 + 10
|
| 20 |
+
max_len=300,
|
| 21 |
+
# condition
|
| 22 |
+
objtraj_dim=19, # 6+12+1
|
| 23 |
+
beta_dim=16,
|
| 24 |
+
bps_dim=0,
|
| 25 |
+
clip_dim=0,
|
| 26 |
+
verts_dim=0,
|
| 27 |
+
contact_mask_dim=0,
|
| 28 |
+
# intermediate
|
| 29 |
+
latent_dim=512,
|
| 30 |
+
num_layers=12,
|
| 31 |
+
num_heads=8,
|
| 32 |
+
mlp_ratio=4.0,
|
| 33 |
+
# training
|
| 34 |
+
dropout=0.1,
|
| 35 |
+
is_dit=False,
|
| 36 |
+
):
|
| 37 |
+
super().__init__()
|
| 38 |
+
|
| 39 |
+
# input
|
| 40 |
+
self.output_dim = output_dim
|
| 41 |
+
self.max_len = max_len
|
| 42 |
+
|
| 43 |
+
# condition
|
| 44 |
+
self.objtraj_dim = objtraj_dim
|
| 45 |
+
self.beta_dim = beta_dim
|
| 46 |
+
self.bps_dim = bps_dim
|
| 47 |
+
self.verts_dim = verts_dim
|
| 48 |
+
self.clip_dim = clip_dim
|
| 49 |
+
self.contact_mask_dim = contact_mask_dim
|
| 50 |
+
# intermediate
|
| 51 |
+
self.latent_dim = latent_dim
|
| 52 |
+
self.num_layers = num_layers
|
| 53 |
+
self.num_heads = num_heads
|
| 54 |
+
self.dropout = dropout
|
| 55 |
+
|
| 56 |
+
self.is_dit = is_dit
|
| 57 |
+
|
| 58 |
+
# ===== build model ===== #
|
| 59 |
+
self._build_condition_embedder()
|
| 60 |
+
|
| 61 |
+
block_cls = EncoderTrajRoPEBlockDIT if self.is_dit else EncoderTrajRoPEBlock
|
| 62 |
+
|
| 63 |
+
# Transformer
|
| 64 |
+
self.blocks = nn.ModuleList(
|
| 65 |
+
[
|
| 66 |
+
block_cls(self.latent_dim, self.num_heads, mlp_ratio=mlp_ratio, dropout=dropout)
|
| 67 |
+
for _ in range(self.num_layers)
|
| 68 |
+
]
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Output heads
|
| 72 |
+
self.final_layer = Mlp(self.latent_dim, out_features=self.output_dim)
|
| 73 |
+
|
| 74 |
+
def _build_condition_embedder(self):
|
| 75 |
+
latent_dim = self.latent_dim
|
| 76 |
+
dropout = self.dropout
|
| 77 |
+
self.sequence_pos_encoder = PositionalEncoding(self.latent_dim, self.dropout)
|
| 78 |
+
self.embed_timestep = TimestepEmbedder(self.latent_dim, self.sequence_pos_encoder)
|
| 79 |
+
self.input_layer = nn.Sequential(
|
| 80 |
+
nn.Linear(self.output_dim, latent_dim),
|
| 81 |
+
nn.SiLU(),
|
| 82 |
+
)
|
| 83 |
+
if self.objtraj_dim > 0:
|
| 84 |
+
self.objtraj_embedder = nn.Sequential(
|
| 85 |
+
nn.Linear(self.objtraj_dim, latent_dim),
|
| 86 |
+
nn.SiLU(),
|
| 87 |
+
nn.Dropout(dropout),
|
| 88 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 89 |
+
)
|
| 90 |
+
if self.beta_dim > 0:
|
| 91 |
+
self.beta_embedder = nn.Sequential(
|
| 92 |
+
nn.Linear(self.beta_dim, latent_dim),
|
| 93 |
+
nn.SiLU(),
|
| 94 |
+
nn.Dropout(dropout),
|
| 95 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 96 |
+
)
|
| 97 |
+
if self.clip_dim > 0:
|
| 98 |
+
self.clip_embedder = nn.Sequential(
|
| 99 |
+
nn.Linear(self.clip_dim, latent_dim),
|
| 100 |
+
nn.SiLU(),
|
| 101 |
+
nn.Dropout(dropout),
|
| 102 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 103 |
+
)
|
| 104 |
+
if self.bps_dim > 0:
|
| 105 |
+
self.bps_embedder = nn.Sequential(
|
| 106 |
+
nn.Linear(self.bps_dim, latent_dim),
|
| 107 |
+
nn.SiLU(),
|
| 108 |
+
nn.Dropout(dropout),
|
| 109 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 110 |
+
)
|
| 111 |
+
if self.verts_dim > 0:
|
| 112 |
+
self.verts_embedder = nn.Sequential(
|
| 113 |
+
nn.Linear(self.verts_dim, latent_dim),
|
| 114 |
+
nn.SiLU(),
|
| 115 |
+
nn.Dropout(dropout),
|
| 116 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 117 |
+
)
|
| 118 |
+
if self.contact_mask_dim > 0:
|
| 119 |
+
self.contact_mask_embedder = nn.Sequential(
|
| 120 |
+
nn.Linear(self.contact_mask_dim, latent_dim),
|
| 121 |
+
nn.SiLU(),
|
| 122 |
+
nn.Dropout(dropout),
|
| 123 |
+
zero_module(nn.Linear(latent_dim, latent_dim), nozero=self.is_dit),
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def forward(
|
| 127 |
+
self,
|
| 128 |
+
x,
|
| 129 |
+
timesteps,
|
| 130 |
+
length,
|
| 131 |
+
trajmat,
|
| 132 |
+
objtraj=None,
|
| 133 |
+
beta=None,
|
| 134 |
+
bps=None,
|
| 135 |
+
verts=None,
|
| 136 |
+
f_text=None,
|
| 137 |
+
contact_mask=None,
|
| 138 |
+
):
|
| 139 |
+
"""
|
| 140 |
+
Args:
|
| 141 |
+
length: (B), valid length of x, if None then use x.shape[2]
|
| 142 |
+
x: (B, L, C)
|
| 143 |
+
timesteps: (B) int
|
| 144 |
+
objtraj: (B, L, C)
|
| 145 |
+
beta: (B, L, C)
|
| 146 |
+
bps: (B, L, C)
|
| 147 |
+
verts: (B, L, C)
|
| 148 |
+
f_text: (B, D)
|
| 149 |
+
contact_mask: (B, L, 1)
|
| 150 |
+
"""
|
| 151 |
+
B, L, _ = x.shape
|
| 152 |
+
|
| 153 |
+
emb = self.embed_timestep(timesteps, is_BLC=True) # (B, 1, C)
|
| 154 |
+
x = self.input_layer(x) # (B, L, C)
|
| 155 |
+
x = x + emb
|
| 156 |
+
|
| 157 |
+
# Condition
|
| 158 |
+
f_to_add = []
|
| 159 |
+
if objtraj is not None and hasattr(self, "objtraj_embedder"):
|
| 160 |
+
f_to_add.append(self.objtraj_embedder(objtraj))
|
| 161 |
+
if beta is not None and hasattr(self, "beta_embedder"):
|
| 162 |
+
f_to_add.append(self.beta_embedder(beta))
|
| 163 |
+
if bps is not None and hasattr(self, "bps_embedder"):
|
| 164 |
+
f_to_add.append(self.bps_embedder(bps))
|
| 165 |
+
if f_text is not None and hasattr(self, "clip_embedder"):
|
| 166 |
+
f_to_add.append(self.clip_embedder(f_text)[..., None, :])
|
| 167 |
+
if verts is not None and hasattr(self, "verts_embedder"):
|
| 168 |
+
f_to_add.append(self.verts_embedder(verts))
|
| 169 |
+
if contact_mask is not None and hasattr(self, "contact_mask_embedder"):
|
| 170 |
+
f_to_add.append(self.contact_mask_embedder(contact_mask))
|
| 171 |
+
|
| 172 |
+
if self.is_dit:
|
| 173 |
+
c = torch.zeros_like(x)
|
| 174 |
+
for f_delta in f_to_add:
|
| 175 |
+
c = c + f_delta
|
| 176 |
+
else:
|
| 177 |
+
for f_delta in f_to_add:
|
| 178 |
+
x = x + f_delta
|
| 179 |
+
|
| 180 |
+
# Setup length and make padding mask
|
| 181 |
+
assert B == length.size(0)
|
| 182 |
+
pmask = length_to_mask(length, L) # (B, L)
|
| 183 |
+
|
| 184 |
+
if L > self.max_len:
|
| 185 |
+
attnmask = torch.ones((L, L), device=x.device, dtype=torch.bool)
|
| 186 |
+
for i in range(L):
|
| 187 |
+
min_ind = max(0, i - self.max_len // 2)
|
| 188 |
+
max_ind = min(L, i + self.max_len // 2)
|
| 189 |
+
max_ind = max(self.max_len, max_ind)
|
| 190 |
+
min_ind = min(L - self.max_len, min_ind)
|
| 191 |
+
attnmask[i, min_ind:max_ind] = False
|
| 192 |
+
else:
|
| 193 |
+
attnmask = None
|
| 194 |
+
|
| 195 |
+
# Transformer
|
| 196 |
+
for block in self.blocks:
|
| 197 |
+
if self.is_dit:
|
| 198 |
+
x = block(x, traj=trajmat, c=c, attn_mask=attnmask, tgt_key_padding_mask=~pmask)
|
| 199 |
+
else:
|
| 200 |
+
x = block(x, traj=trajmat, attn_mask=attnmask, tgt_key_padding_mask=~pmask)
|
| 201 |
+
|
| 202 |
+
# Output
|
| 203 |
+
sample = self.final_layer(x) # (B, L, C)
|
| 204 |
+
|
| 205 |
+
output = {
|
| 206 |
+
"pred_context": x,
|
| 207 |
+
"sample": sample,
|
| 208 |
+
"mask": pmask,
|
| 209 |
+
}
|
| 210 |
+
return output
|