Spaces:
Runtime error
Runtime error
File size: 12,762 Bytes
2df809d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 |
import tqdm
import torch
from dust3r.utils.device import to_cpu, collate_with_cat
from dust3r.utils.misc import invalid_to_nans
from dust3r.utils.geometry import depthmap_to_pts3d, geotrf
from dust3r.model import ARCroco3DStereo
from accelerate import Accelerator
import re
def custom_sort_key(key):
text = key.split("/")
if len(text) > 1:
text, num = text[0], text[-1]
return (text, int(num))
else:
return (key, -1)
def merge_chunk_dict(old_dict, curr_dict, add_number):
new_dict = {}
for key, value in curr_dict.items():
match = re.search(r"(\d+)$", key)
if match:
num_part = int(match.group()) + add_number
new_key = re.sub(r"(\d+)$", str(num_part), key, 1)
new_dict[new_key] = value
else:
new_dict[key] = value
new_dict = old_dict | new_dict
return {k: new_dict[k] for k in sorted(new_dict.keys(), key=custom_sort_key)}
def _interleave_imgs(img1, img2):
res = {}
for key, value1 in img1.items():
value2 = img2[key]
if isinstance(value1, torch.Tensor):
value = torch.stack((value1, value2), dim=1).flatten(0, 1)
else:
value = [x for pair in zip(value1, value2) for x in pair]
res[key] = value
return res
def make_batch_symmetric(batch):
view1, view2 = batch
view1, view2 = (_interleave_imgs(view1, view2), _interleave_imgs(view2, view1))
return view1, view2
def loss_of_one_batch(
batch,
model,
criterion,
accelerator: Accelerator,
symmetrize_batch=False,
use_amp=False,
ret=None,
img_mask=None,
inference=False,
):
if len(batch) > 2:
assert (
symmetrize_batch is False
), "cannot symmetrize batch with more than 2 views"
if symmetrize_batch:
batch = make_batch_symmetric(batch)
with torch.cuda.amp.autocast(enabled=not inference):
if inference:
output, state_args = model(batch, ret_state=True)
preds, batch = output.ress, output.views
result = dict(views=batch, pred=preds)
return result[ret] if ret else result, state_args
else:
output = model(batch)
preds, batch = output.ress, output.views
with torch.cuda.amp.autocast(enabled=False):
loss = criterion(batch, preds) if criterion is not None else None
result = dict(views=batch, pred=preds, loss=loss)
return result[ret] if ret else result
def loss_of_one_batch_tbptt(
batch,
model,
criterion,
chunk_size,
loss_scaler,
optimizer,
accelerator: Accelerator,
log_writer=None,
symmetrize_batch=False,
use_amp=False,
ret=None,
img_mask=None,
inference=False,
):
if len(batch) > 2:
assert (
symmetrize_batch is False
), "cannot symmetrize batch with more than 2 views"
if symmetrize_batch:
batch = make_batch_symmetric(batch)
all_preds = []
all_loss = 0.0
all_loss_details = {}
with torch.cuda.amp.autocast(enabled=not inference):
with torch.no_grad():
(feat, pos, shape), (
init_state_feat,
init_mem,
state_feat,
state_pos,
mem,
) = accelerator.unwrap_model(model)._forward_encoder(batch)
feat = [f.detach() for f in feat]
pos = [p.detach() for p in pos]
shape = [s.detach() for s in shape]
init_state_feat = init_state_feat.detach()
init_mem = init_mem.detach()
for chunk_id in range((len(batch) - 1) // chunk_size + 1):
preds = []
chunk = []
state_feat = state_feat.detach()
state_pos = state_pos.detach()
mem = mem.detach()
if chunk_id < ((len(batch) - 1) // chunk_size + 1) - 4:
with torch.no_grad():
for in_chunk_idx in range(chunk_size):
i = chunk_id * chunk_size + in_chunk_idx
if i >= len(batch):
break
res, (state_feat, mem) = accelerator.unwrap_model(
model
)._forward_decoder_step(
batch,
i,
feat_i=feat[i],
pos_i=pos[i],
shape_i=shape[i],
init_state_feat=init_state_feat,
init_mem=init_mem,
state_feat=state_feat,
state_pos=state_pos,
mem=mem,
)
preds.append(res)
all_preds.append({k: v.detach() for k, v in res.items()})
chunk.append(batch[i])
with torch.cuda.amp.autocast(enabled=False):
loss, loss_details = (
criterion(chunk, preds, camera1=batch[0]["camera_pose"])
if criterion is not None
else None
)
all_loss += float(loss)
all_loss_details = merge_chunk_dict(
all_loss_details, loss_details, chunk_id * chunk_size
)
del loss
else:
for in_chunk_idx in range(chunk_size):
i = chunk_id * chunk_size + in_chunk_idx
if i >= len(batch):
break
res, (state_feat, mem) = accelerator.unwrap_model(
model
)._forward_decoder_step(
batch,
i,
feat_i=feat[i],
pos_i=pos[i],
shape_i=shape[i],
init_state_feat=init_state_feat,
init_mem=init_mem,
state_feat=state_feat,
state_pos=state_pos,
mem=mem,
)
preds.append(res)
all_preds.append({k: v.detach() for k, v in res.items()})
chunk.append(batch[i])
with torch.cuda.amp.autocast(enabled=False):
loss, loss_details = (
criterion(chunk, preds, camera1=batch[0]["camera_pose"])
if criterion is not None
else None
)
all_loss += float(loss)
all_loss_details = merge_chunk_dict(
all_loss_details, loss_details, chunk_id * chunk_size
)
loss_scaler(
loss,
optimizer,
parameters=model.parameters(),
update_grad=True,
clip_grad=1.0,
)
optimizer.zero_grad()
del loss
result = dict(
views=batch,
pred=all_preds,
loss=(all_loss / ((len(batch) - 1) // chunk_size + 1), all_loss_details),
already_backprop=True,
)
return result[ret] if ret else result
@torch.no_grad()
def inference(groups, model, device, verbose=True):
ignore_keys = set(
["depthmap", "dataset", "label", "instance", "idx", "true_shape", "rng"]
)
for view in groups:
for name in view.keys(): # pseudo_focal
if name in ignore_keys:
continue
if isinstance(view[name], tuple) or isinstance(view[name], list):
view[name] = [x.to(device, non_blocking=True) for x in view[name]]
else:
view[name] = view[name].to(device, non_blocking=True)
if verbose:
print(f">> Inference with model on {len(groups)} image/raymaps")
res, state_args = loss_of_one_batch(groups, model, None, None, inference=True)
result = to_cpu(res)
return result, state_args
@torch.no_grad()
def inference_step(view, state_args, model, device, verbose=True):
ignore_keys = set(
["depthmap", "dataset", "label", "instance", "idx", "true_shape", "rng"]
)
for name in view.keys(): # pseudo_focal
if name in ignore_keys:
continue
if isinstance(view[name], tuple) or isinstance(view[name], list):
view[name] = [x.to(device, non_blocking=True) for x in view[name]]
else:
view[name] = view[name].to(device, non_blocking=True)
with torch.cuda.amp.autocast(enabled=False):
state_feat, state_pos, init_state_feat, mem, init_mem = state_args
pred, _ = model.inference_step(
view, state_feat, state_pos, init_state_feat, mem, init_mem
)
res = dict(pred=pred)
result = to_cpu(res)
return result
@torch.no_grad()
def inference_recurrent(groups, model, device, verbose=True):
ignore_keys = set(
["depthmap", "dataset", "label", "instance", "idx", "true_shape", "rng"]
)
for view in groups:
for name in view.keys(): # pseudo_focal
if name in ignore_keys:
continue
if isinstance(view[name], tuple) or isinstance(view[name], list):
view[name] = [x.to(device, non_blocking=True) for x in view[name]]
else:
view[name] = view[name].to(device, non_blocking=True)
if verbose:
print(f">> Inference with model on {len(groups)} image/raymaps")
with torch.cuda.amp.autocast(enabled=False):
preds, batch, state_args = model.forward_recurrent(
groups, device, ret_state=True
)
res = dict(views=batch, pred=preds)
result = to_cpu(res)
return result, state_args
def check_if_same_size(pairs):
shapes1 = [img1["img"].shape[-2:] for img1, img2 in pairs]
shapes2 = [img2["img"].shape[-2:] for img1, img2 in pairs]
return all(shapes1[0] == s for s in shapes1) and all(
shapes2[0] == s for s in shapes2
)
def get_pred_pts3d(gt, pred, use_pose=False, inplace=False):
if "depth" in pred and "pseudo_focal" in pred:
try:
pp = gt["camera_intrinsics"][..., :2, 2]
except KeyError:
pp = None
pts3d = depthmap_to_pts3d(**pred, pp=pp)
elif "pts3d" in pred:
pts3d = pred["pts3d"]
elif "pts3d_in_other_view" in pred:
assert use_pose is True
return (
pred["pts3d_in_other_view"]
if inplace
else pred["pts3d_in_other_view"].clone()
)
if use_pose:
camera_pose = pred.get("camera_pose")
assert camera_pose is not None
pts3d = geotrf(camera_pose, pts3d)
return pts3d
def find_opt_scaling(
gt_pts1,
gt_pts2,
pr_pts1,
pr_pts2=None,
fit_mode="weiszfeld_stop_grad",
valid1=None,
valid2=None,
):
assert gt_pts1.ndim == pr_pts1.ndim == 4
assert gt_pts1.shape == pr_pts1.shape
if gt_pts2 is not None:
assert gt_pts2.ndim == pr_pts2.ndim == 4
assert gt_pts2.shape == pr_pts2.shape
nan_gt_pts1 = invalid_to_nans(gt_pts1, valid1).flatten(1, 2)
nan_gt_pts2 = (
invalid_to_nans(gt_pts2, valid2).flatten(1, 2) if gt_pts2 is not None else None
)
pr_pts1 = invalid_to_nans(pr_pts1, valid1).flatten(1, 2)
pr_pts2 = (
invalid_to_nans(pr_pts2, valid2).flatten(1, 2) if pr_pts2 is not None else None
)
all_gt = (
torch.cat((nan_gt_pts1, nan_gt_pts2), dim=1)
if gt_pts2 is not None
else nan_gt_pts1
)
all_pr = torch.cat((pr_pts1, pr_pts2), dim=1) if pr_pts2 is not None else pr_pts1
dot_gt_pr = (all_pr * all_gt).sum(dim=-1)
dot_gt_gt = all_gt.square().sum(dim=-1)
if fit_mode.startswith("avg"):
scaling = dot_gt_pr.nanmean(dim=1) / dot_gt_gt.nanmean(dim=1)
elif fit_mode.startswith("median"):
scaling = (dot_gt_pr / dot_gt_gt).nanmedian(dim=1).values
elif fit_mode.startswith("weiszfeld"):
scaling = dot_gt_pr.nanmean(dim=1) / dot_gt_gt.nanmean(dim=1)
for iter in range(10):
dis = (all_pr - scaling.view(-1, 1, 1) * all_gt).norm(dim=-1)
w = dis.clip_(min=1e-8).reciprocal()
scaling = (w * dot_gt_pr).nanmean(dim=1) / (w * dot_gt_gt).nanmean(dim=1)
else:
raise ValueError(f"bad {fit_mode=}")
if fit_mode.endswith("stop_grad"):
scaling = scaling.detach()
scaling = scaling.clip(min=1e-3)
return scaling
|