Spaces:
Runtime error
Runtime error
File size: 91,349 Bytes
1b00369 d6d3a5b |
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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 |
# from model.mdm import MDM
# from model.mdm_ours import MDM as MDM_Ours
# from model.mdm_ours import MDMV3 as MDM_Ours_V3
# from model.mdm_ours import MDMV4 as MDM_Ours_V4
# from model.mdm_ours import MDMV5 as MDM_Ours_V5
# from model.mdm_ours import MDMV6 as MDM_Ours_V6
# from model.mdm_ours import MDMV7 as MDM_Ours_V7
# from model.mdm_ours import MDMV8 as MDM_Ours_V8
# from model.mdm_ours import MDMV9 as MDM_Ours_V9
from model.mdm_ours import MDMV10 as MDM_Ours_V10
# from model.mdm_ours import MDMV11 as MDM_Ours_V11
# MDM_Ours_V12
from model.mdm_ours import MDMV12 as MDM_Ours_V12
# MDM_Ours_V13
# from model.mdm_ours import MDMV13 as MDM_Ours_V13
# # MDM_Ours_V14
# from model.mdm_ours import MDMV14 as MDM_Ours_V14
from diffusion import gaussian_diffusion as gd
from diffusion.respace import SpacedDiffusion, space_timesteps
from utils.parser_util import get_cond_mode
import torch
from torch import optim, nn
import torch.nn.functional as F
from manopth.manolayer import ManoLayer
import numpy as np
import trimesh
import os
from diffusion.respace_ours import SpacedDiffusion as SpacedDiffusion_Ours
# SpacedDiffusionV2
from diffusion.respace_ours import SpacedDiffusionV2 as SpacedDiffusion_OursV2
from diffusion.respace_ours import SpacedDiffusionV3 as SpacedDiffusion_OursV3
# SpacedDiffusionV4
from diffusion.respace_ours import SpacedDiffusionV4 as SpacedDiffusion_OursV4
# SpacedDiffusion_OursV5
from diffusion.respace_ours import SpacedDiffusionV5 as SpacedDiffusion_OursV5
# SpacedDiffusion_OursV6
from diffusion.respace_ours import SpacedDiffusionV6 as SpacedDiffusion_OursV6
# SpacedDiffusion_OursV7
from diffusion.respace_ours import SpacedDiffusionV7 as SpacedDiffusion_OursV7
from diffusion.respace_ours import SpacedDiffusionV9 as SpacedDiffusion_OursV9
def batched_index_select_ours(values, indices, dim = 1):
value_dims = values.shape[(dim + 1):]
values_shape, indices_shape = map(lambda t: list(t.shape), (values, indices))
indices = indices[(..., *((None,) * len(value_dims)))]
indices = indices.expand(*((-1,) * len(indices_shape)), *value_dims)
value_expand_len = len(indices_shape) - (dim + 1)
values = values[(*((slice(None),) * dim), *((None,) * value_expand_len), ...)]
value_expand_shape = [-1] * len(values.shape)
expand_slice = slice(dim, (dim + value_expand_len))
value_expand_shape[expand_slice] = indices.shape[expand_slice]
values = values.expand(*value_expand_shape)
dim += value_expand_len
return values.gather(dim, indices)
def gaussian_entropy(logvar): # gaussian entropy ##
const = 0.5 * float(logvar.size(1)) * (1. + np.log(np.pi * 2))
ent = 0.5 * logvar.sum(dim=1, keepdim=False) + const
return ent
def standard_normal_logprob(z): # feature dim
dim = z.size(-1) # dim size -1
log_z = -0.5 * dim * np.log(2 * np.pi)
return log_z - z.pow(2) / 2
def load_multiple_models_fr_path(model_path, model):
model_paths = model_path.split(";")
print(f"Loading multiple models with split model_path: {model_paths}")
setting_to_model_path = {}
for cur_path in model_paths:
cur_setting_nm, cur_model_path = cur_path.split(':')
setting_to_model_path[cur_setting_nm] = cur_model_path
loaded_dict = {}
for cur_setting in setting_to_model_path:
cur_model_path = setting_to_model_path[cur_setting]
cur_model_state_dict = torch.load(cur_model_path, map_location='cpu')
if cur_setting == 'diff_realbasejtsrel':
interested_keys = [
'real_basejtsrel_input_process', 'real_basejtsrel_sequence_pos_encoder', 'real_basejtsrel_seqTransEncoder', 'real_basejtsrel_embed_timestep', 'real_basejtsrel_sequence_pos_denoising_encoder', 'real_basejtsrel_denoising_seqTransEncoder', 'real_basejtsrel_output_process'
]
elif cur_setting == 'diff_basejtsrel':
interested_keys = [
'avg_joints_sequence_input_process', 'joints_offset_input_process', 'sequence_pos_encoder', 'seqTransEncoder', 'logvar_seqTransEncoder', 'embed_timestep', 'basejtsrel_denoising_embed_timestep', 'sequence_pos_denoising_encoder', 'basejtsrel_denoising_seqTransEncoder', 'basejtsrel_glb_denoising_latents_trans_layer', 'avg_joint_sequence_output_process', 'joint_offset_output_process', 'output_process'
]
elif cur_setting == 'diff_realbasejtsrel_to_joints':
interested_keys = [
'real_basejtsrel_to_joints_input_process', 'real_basejtsrel_to_joints_sequence_pos_encoder', 'real_basejtsrel_to_joints_seqTransEncoder', 'real_basejtsrel_to_joints_embed_timestep', 'real_basejtsrel_to_joints_sequence_pos_denoising_encoder', 'real_basejtsrel_to_joints_denoising_seqTransEncoder', 'real_basejtsrel_to_joints_output_process',
]
else:
raise ValueError(f"cur_setting:{cur_setting} Not implemented yet")
for k in cur_model_state_dict:
for cur_inter_key in interested_keys:
if cur_inter_key in k:
loaded_dict[k] = cur_model_state_dict[k]
model_dict = model.state_dict()
model_dict.update(loaded_dict)
model.load_state_dict(model_dict)
def load_model_wo_clip(model, state_dict): # missing_keys: in the current model but not found in the state_dict? # unexpected_keys: not in the current model but found inthe state_dict?
missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
# print(unexpected_keys)
assert len(unexpected_keys) == 0
assert all([k.startswith('clip_model.') for k in missing_keys])
### create model and diffusion ## #
def create_model_and_diffusion(args, data):
if args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist", "ambient_obj_base_rel_dist"]:
model = MDM_Ours(**get_model_args(args, data))
elif args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist_we"]:
model = MDM_Ours_V3(**get_model_args(args, data))
# MDM_Ours_V4
elif args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist_we_wj"]:
model = MDM_Ours_V4(**get_model_args(args, data))
# obj_base_rel_dist_we_wj_latents
elif args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist_we_wj_latents"]:
if args.diff_spatial:
if args.pred_joints_offset:
if args.diff_joint_quants:
model = MDM_Ours_V13(**get_model_args(args, data))
elif args.diff_hand_params:
model = MDM_Ours_V14(**get_model_args(args, data))
else:
if args.finetune_with_cond:
print(f"Using MDM ours V12!!!!")
model = MDM_Ours_V12(**get_model_args(args, data))
else:
print(f"Using MDM ours V10!!!!")
model = MDM_Ours_V10(**get_model_args(args, data))
else:
print(f"Using MDM ours V9!!!!")
model = MDM_Ours_V9(**get_model_args(args, data))
elif args.diff_latents:
print(f"Using MDM ours V11!!!!")
model = MDM_Ours_V11(**get_model_args(args, data))
elif args.use_sep_models:
if args.use_vae:
if args.pred_basejtsrel_avgjts:
print(f"Using MDM ours V8!!!!")
model = MDM_Ours_V8(**get_model_args(args, data))
else:
model = MDM_Ours_V7(**get_model_args(args, data))
else:
model = MDM_Ours_V6(**get_model_args(args, data))
else:
model = MDM_Ours_V5(**get_model_args(args, data))
else:
model = MDM(**get_model_args(args, data))
diffusion = create_gaussian_diffusion(args)
return model, diffusion
# give utils to models #
def get_model_args(args, data):
# default_args
clip_version = 'ViT-B/32'
action_emb = 'tensor' ## get model arguments ##
cond_mode = get_cond_mode(args)
if hasattr(data.dataset, 'num_actions'):
num_actions = data.dataset.num_actions
else:
num_actions = 1
# SMPL defaults
data_rep = 'rot6d'
njoints = 25
nfeats = 6
if args.dataset in ['humanml']: ## from
data_rep = 'hml_vec'
njoints = 263 # joints
nfeats = 1
elif args.dataset in ['motion_ours']:
data_rep = 'xyz'
njoints = 21
nfeats = 3
elif args.dataset == 'kit':
data_rep = 'hml_vec'
njoints = 251
nfeats = 1
## modeltype;
return {'modeltype': '', 'njoints': njoints, 'nfeats': nfeats, 'num_actions': num_actions,
'translation': True, 'pose_rep': 'rot6d', 'glob': True, 'glob_rot': True,
'latent_dim': args.latent_dim, 'ff_size': 1024, 'num_layers': args.layers, 'num_heads': 4,
'dropout': 0.1, 'activation': "gelu", 'data_rep': data_rep, 'cond_mode': cond_mode,
'cond_mask_prob': args.cond_mask_prob, 'action_emb': action_emb, 'arch': args.arch,
'emb_trans_dec': args.emb_trans_dec, 'clip_version': clip_version, 'dataset': args.dataset, 'args': args}
def optimize_sampled_hand_joints(sampled_joints, rel_base_pts_to_joints, dists_base_pts_to_joints, base_pts, base_normals):
# sampled_joints: bsz x ws x nnj x 3
# signed distances
# smoothness
bsz, ws, nnj = sampled_joints.shape[:3]
device = sampled_joints.device
coarse_lr = 0.1
num_iters = 100 # if i_iter > 0 else 1 ## nn-coarse-iters for global transformations #
mano_path = "/data1/sim/mano_models/mano/models"
base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
base_normals_exp = base_normals.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
signed_dist_e_coeff = 1.0
signed_dist_e_coeff = 0.0
### start optimization ###
# setup MANO layer
mano_layer = ManoLayer(
flat_hand_mean=True,
side='right',
mano_root=mano_path, # mano_path for the mano model #
ncomps=24,
use_pca=True,
root_rot_mode='axisang',
joint_rot_mode='axisang'
).to(device)
## random init variables ##
beta_var = torch.randn([bsz, 10]).to(device)
rot_var = torch.randn([bsz * ws, 3]).to(device)
theta_var = torch.randn([bsz * ws, 24]).to(device)
transl_var = torch.randn([bsz * ws, 3]).to(device)
beta_var.requires_grad_()
rot_var.requires_grad_()
theta_var.requires_grad_()
transl_var.requires_grad_()
opt = optim.Adam([rot_var, transl_var], lr=coarse_lr)
for i_iter in range(num_iters):
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
if dists_base_pts_to_joints is not None:
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).to(device).mean()
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
''' strategy 2: use all base pts, rel, dists for resolving '''
# rel_base_pts_to_hand_joints: bsz x ws x nnj x nnb x 3 #
signed_dist_mask = signed_dist_base_pts_to_hand_joints < 0.
l2_dist_rel_joints_to_base_pts_mask = torch.sqrt(
torch.sum(rel_base_pts_to_hand_joints ** 2, dim=-1)
) < 0.05
signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_base_pts_mask.float()) > 1.5
dot_rel_with_normals = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# dot_rel_with_normals: bsz x ws x nnj x nnb
avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
signed_dist_e = dot_rel_with_normals * signed_dist_base_pts_to_hand_joints
signed_dist_e = torch.sum(
signed_dist_e[signed_dist_mask]
) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
###### ====== get loss for signed distances ==== ###
''' strategy 2: use all base pts, rel, dists for resolving '''
''' strategy 1: use nearest base pts, rel, dists for resolving '''
# dist_rhand_joints_to_base_pts = torch.sum(
# (hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
# )
# # minn_dists_idxes: bsz x ws x nnj -->
# minn_dists_to_base_pts, minn_dists_idxes = torch.min(
# dist_rhand_joints_to_base_pts, dim=-1
# )
# # base_pts: bsz x nn_base_pts x 3 #
# # base_pts: bsz x ws x nn_base_pts x 3 #
# # bsz x ws x nnj
# # object verts and object faces #
# ## other than the sampling process; not
# # bsz x ws x nnj x 3 ##
# nearest_base_pts = batched_index_select_ours(
# base_pts_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 # # base normalse #
# nearest_base_normals = batched_index_select_ours(
# base_normals_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 # # the nearest distance points may be of some ambiguous
# rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# # bsz x ws x nnj #
# signed_dist_joints_to_base_pts = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# # should not be negative
# signed_dist_mask = signed_dist_joints_to_base_pts < 0.
# l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# ) < 0.05
# signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
# ### ==== mean of signed distances ==== ###
# signed_dist_e = torch.sum( # penetration
# -1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
# ) / torch.clamp(
# torch.sum(signed_dist_mask.float()), min=1e-5
# ).item()
''' strategy 1: use nearest base pts, rel, dists for resolving '''
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
### signed distance coeff -> the distance coeff #
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
fine_lr = 0.1
num_iters = 1000
opt = optim.Adam([rot_var, transl_var, beta_var, theta_var], lr=fine_lr)
for i_iter in range(num_iters):
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
# dists_base_pts_to_joints ## dists_base_pts_to_joints ##
if dists_base_pts_to_joints is not None: ## dists_base_pts_to_joints ##
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).mean()
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
dist_rhand_joints_to_base_pts = torch.sum(
(hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
)
# minn_dists_idxes: bsz x ws x nnj -->
minn_dists_to_base_pts, minn_dists_idxes = torch.min(
dist_rhand_joints_to_base_pts, dim=-1
)
# base_pts: bsz x nn_base_pts x 3 #
# base_pts: bsz x ws x nn_base_pts x 3 #
# bsz x ws x nnj
# base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
# bsz x ws x nnj x 3 ##
nearest_base_pts = batched_index_select_ours(
base_pts_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
nearest_base_normals = batched_index_select_ours(
base_normals_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# bsz x ws x nnj #
signed_dist_joints_to_base_pts = torch.sum(
rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
)
# should not be negative
signed_dist_mask = signed_dist_joints_to_base_pts < 0.
l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
) < 0.05
signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
### ==== mean of signed distances ==== ###
signed_dist_e = torch.sum(
-1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
) / torch.clamp(
torch.sum(signed_dist_mask.float()), min=1e-5
).item()
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
### refine the optimization with signed energy ##
signed_dist_e_coeff = 1.0
fine_lr = 0.1
num_iters = 1000
opt = optim.Adam([rot_var, transl_var, beta_var, theta_var], lr=fine_lr)
for i_iter in range(num_iters):
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
# dists_base_pts_to_joints ## dists_base_pts_to_joints ##
if dists_base_pts_to_joints is not None: ## dists_base_pts_to_joints ##
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).mean()
''' strategy 2: use all base pts, rel, dists for resolving '''
# rel_base_pts_to_hand_joints: bsz x ws x nnj x nnb x 3 #
signed_dist_mask = signed_dist_base_pts_to_hand_joints < 0.
l2_dist_rel_joints_to_base_pts_mask = torch.sqrt(
torch.sum(rel_base_pts_to_hand_joints ** 2, dim=-1)
) < 0.05
signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_base_pts_mask.float()) > 1.5
## === dot rel with normals === ##
# dot_rel_with_normals = torch.sum(
# rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
# )
## === dot rel with normals === ##
## === dot rel with rel, strategy 3 === ##
dot_rel_with_normals = torch.sum(
-1.0 * rel_base_pts_to_hand_joints * rel_base_pts_to_hand_joints, dim=-1
)
## === dot rel with rel, strategy 3 === ##
signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# dot_rel_with_normals: bsz x ws x nnj x nnb
avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
signed_dist_e = dot_rel_with_normals * signed_dist_base_pts_to_hand_joints
signed_dist_e = torch.sum(
signed_dist_e[signed_dist_mask]
) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
###### ====== get loss for signed distances ==== ###
''' strategy 2: use all base pts, rel, dists for resolving '''
# hard projections for
''' strategy 1: use nearest base pts, rel, dists for resolving '''
# ### === e2 the signed distances to nearest points should not be negative to the neareste === ###
# ## base_pts: bsz x nn_base_pts x 3
# ## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
# ## bsz x ws x nnj x nnb ##
# dist_rhand_joints_to_base_pts = torch.sum(
# (hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
# )
# # minn_dists_idxes: bsz x ws x nnj -->
# minn_dists_to_base_pts, minn_dists_idxes = torch.min(
# dist_rhand_joints_to_base_pts, dim=-1
# )
#
# # base_pts: bsz x nn_base_pts x 3 #
# # base_pts: bsz x ws x nn_base_pts x 3 #
# # bsz x ws x nnj
# # base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
# # bsz x ws x nnj x 3 ##
# nearest_base_pts = batched_index_select_ours(
# base_pts_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 #
# nearest_base_normals = batched_index_select_ours(
# base_normals_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 #
# rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# # bsz x ws x nnj #
# signed_dist_joints_to_base_pts = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# # should not be negative
# signed_dist_mask = signed_dist_joints_to_base_pts < 0.
# ## === luojisiwei and others === ##
# # l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# # torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# # ) < 0.05
# ## === luojisiwei and others === ##
# l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# ) < 0.1
# signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
# ### ==== mean of signed distances ==== ###
# # signed_dist_e = torch.sum(
# # -1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
# # ) / torch.clamp(
# # torch.sum(signed_dist_mask.float()), min=1e-5
# # ).item()
# # signed_dist_joints_to_base_pts: bsz x ws x nnj # -> disstances
# signed_dist_joints_to_base_pts = signed_dist_joints_to_base_pts.detach()
# #
## penetraition resolving --- strategy
# dot_rel_with_normals = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# # bsz x ws x nnj --> the loss term
# ## signed distances 3 #### isgned distance 3 ###
# ## dotrelwithnormals, ##
# # # signed_dist_mask -> the distances
# # dot_rel_with_normals: bsz x ws x nnj x nnb
# avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
# signed_dist_e = dot_rel_with_normals * signed_dist_joints_to_base_pts
# signed_dist_e = torch.sum(
# signed_dist_e[signed_dist_mask]
# ) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
# ###### ====== get loss for signed distances ==== ###
''' strategy 1: use nearest base pts, rel, dists for resolving '''
## judeg whether inside the object and only project those one inside of the object
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
# shoudl take a
# how to proejct the jvertex
# hwo to project the veretex
# weighted sum of the projectiondirection
# weights of each base point
# atraction field -> should be able to learn the penetration resolving strategy
# stochestic penetration resolving strategy #
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
# avg_masks
print('\tAvg masks: {}'.format(avg_masks.item()))
''' returning sampled_joints '''
sampled_joints = hand_joints
np.save("optimized_verts.npy", hand_verts.detach().cpu().numpy())
print(f"Optimized verts saved to optimized_verts.npy")
return sampled_joints.detach()
def get_obj_trimesh_list(obj_verts, obj_faces):
tot_trimeshes = []
tot_n = len(obj_verts)
for i_obj in range(tot_n):
cur_obj_verts, cur_obj_faces = obj_verts[i_obj], obj_faces[i_obj]
if isinstance(cur_obj_verts, torch.Tensor):
cur_obj_verts = cur_obj_verts.detach().cpu().numpy()
if isinstance(cur_obj_faces, torch.Tensor):
cur_obj_faces = cur_obj_faces.detach().cpu().numpy()
cur_obj_mesh = trimesh.Trimesh(vertices=cur_obj_verts, faces=cur_obj_faces,
process=False, use_embree=True)
tot_trimeshes.append(cur_obj_mesh)
return tot_trimeshes
def judge_penetrated_points(obj_mesh, subj_pts):
# bsz
tot_pts_inside_objmesh_labels = []
nn_bsz = len(obj_mesh)
for i_bsz in range(nn_bsz):
cur_obj_mesh = obj_mesh[i_bsz]
cur_subj_pts = subj_pts[i_bsz].detach().cpu().numpy()
ori_subj_pts_shape = cur_subj_pts.shape
if len(cur_subj_pts.shape) > 2:
cur_subj_pts = cur_subj_pts.reshape(cur_subj_pts.shape[0] * cur_subj_pts.shape[1], 3)
#
pts_inside_objmesh = cur_obj_mesh.contains(cur_subj_pts)
pts_inside_objmesh = pts_inside_objmesh.astype(np.float32)
### reshape inside_objmesh labels ###
pts_inside_objmesh = pts_inside_objmesh.reshape(*ori_subj_pts_shape[:-1])
tot_pts_inside_objmesh_labels.append(pts_inside_objmesh)
tot_pts_inside_objmesh_labels = np.stack(tot_pts_inside_objmesh_labels, axis=0) # nn_bsz x nn_subj_pts
tot_pts_inside_objmesh_labels = torch.from_numpy(tot_pts_inside_objmesh_labels).float()
return tot_pts_inside_objmesh_labels.to(subj_pts.device) # gt inside objmesh labels and to the pts device #
# TODO: other optimization strategies? e.g. sequential optimziation> #
def optimize_sampled_hand_joints_wobj(sampled_joints, rel_base_pts_to_joints, dists_base_pts_to_joints, base_pts, base_normals, obj_verts, obj_normals, obj_faces):
# sampled_joints: bsz x ws x nnj x 3
# signed distances
# smoothness
# tot_n_objs #
tot_obj_trimeshes = get_obj_trimesh_list(obj_verts, obj_faces)
## TODO: write the collect function for object verts, normals, faces ##
### A simple penetration resolving strategy is as follows:
#### 1) get vertices in the object; 2) get nearest base points (for simplicity); 3) project the vertex to the base point ####
## 1) for joints only;
## 2) for vertices;
## 3) for vertices ##
## TODO: optimzie the resolvign strategy stated above ##
bsz, ws, nnj = sampled_joints.shape[:3]
device = sampled_joints.device
coarse_lr = 0.1
num_iters = 100 # if i_iter > 0 else 1 ## nn-coarse-iters for global transformations #
mano_path = "/data1/sim/mano_models/mano/models"
# obj_verts: bsz x nnobjverts x
base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
base_normals_exp = base_normals.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
signed_dist_e_coeff = 1.0
signed_dist_e_coeff = 0.0
### start optimization ###
# setup MANO layer
mano_layer = ManoLayer(
flat_hand_mean=True,
side='right',
mano_root=mano_path, # mano_path for the mano model #
ncomps=24,
use_pca=True,
root_rot_mode='axisang',
joint_rot_mode='axisang'
).to(device)
## random init variables ##
beta_var = torch.randn([bsz, 10]).to(device)
rot_var = torch.randn([bsz * ws, 3]).to(device)
theta_var = torch.randn([bsz * ws, 24]).to(device)
transl_var = torch.randn([bsz * ws, 3]).to(device)
beta_var.requires_grad_()
rot_var.requires_grad_()
theta_var.requires_grad_()
transl_var.requires_grad_()
opt = optim.Adam([rot_var, transl_var], lr=coarse_lr)
for i_iter in range(num_iters):
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
if dists_base_pts_to_joints is not None:
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).to(device).mean()
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
''' strategy 2: use all base pts, rel, dists for resolving '''
# rel_base_pts_to_hand_joints: bsz x ws x nnj x nnb x 3 #
signed_dist_mask = signed_dist_base_pts_to_hand_joints < 0.
l2_dist_rel_joints_to_base_pts_mask = torch.sqrt(
torch.sum(rel_base_pts_to_hand_joints ** 2, dim=-1)
) < 0.05
signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_base_pts_mask.float()) > 1.5
dot_rel_with_normals = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# dot_rel_with_normals: bsz x ws x nnj x nnb
avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
signed_dist_e = dot_rel_with_normals * signed_dist_base_pts_to_hand_joints
signed_dist_e = torch.sum(
signed_dist_e[signed_dist_mask]
) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
###### ====== get loss for signed distances ==== ###
''' strategy 2: use all base pts, rel, dists for resolving '''
''' strategy 1: use nearest base pts, rel, dists for resolving '''
# dist_rhand_joints_to_base_pts = torch.sum(
# (hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
# )
# # minn_dists_idxes: bsz x ws x nnj -->
# minn_dists_to_base_pts, minn_dists_idxes = torch.min(
# dist_rhand_joints_to_base_pts, dim=-1
# )
# # base_pts: bsz x nn_base_pts x 3 #
# # base_pts: bsz x ws x nn_base_pts x 3 #
# # bsz x ws x nnj
# # object verts and object faces #
# ## other than the sampling process; not
# # bsz x ws x nnj x 3 ##
# nearest_base_pts = batched_index_select_ours(
# base_pts_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 # # base normalse #
# nearest_base_normals = batched_index_select_ours(
# base_normals_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 # # the nearest distance points may be of some ambiguous
# rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# # bsz x ws x nnj #
# signed_dist_joints_to_base_pts = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# # should not be negative
# signed_dist_mask = signed_dist_joints_to_base_pts < 0.
# l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# ) < 0.05
# signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
# ### ==== mean of signed distances ==== ###
# signed_dist_e = torch.sum( # penetration
# -1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
# ) / torch.clamp(
# torch.sum(signed_dist_mask.float()), min=1e-5
# ).item()
''' strategy 1: use nearest base pts, rel, dists for resolving '''
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
### signed distance coeff -> the distance coeff #
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
fine_lr = 0.1
num_iters = 1000
opt = optim.Adam([rot_var, transl_var, beta_var, theta_var], lr=fine_lr)
for i_iter in range(num_iters):
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
# dists_base_pts_to_joints ## dists_base_pts_to_joints ##
if dists_base_pts_to_joints is not None: ## dists_base_pts_to_joints ##
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).mean()
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
dist_rhand_joints_to_base_pts = torch.sum(
(hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
)
# minn_dists_idxes: bsz x ws x nnj -->
minn_dists_to_base_pts, minn_dists_idxes = torch.min(
dist_rhand_joints_to_base_pts, dim=-1
)
# base_pts: bsz x nn_base_pts x 3 #
# base_pts: bsz x ws x nn_base_pts x 3 #
# bsz x ws x nnj
# base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
# bsz x ws x nnj x 3 ##
nearest_base_pts = batched_index_select_ours(
base_pts_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
nearest_base_normals = batched_index_select_ours(
base_normals_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# bsz x ws x nnj #
signed_dist_joints_to_base_pts = torch.sum(
rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
)
# should not be negative
signed_dist_mask = signed_dist_joints_to_base_pts < 0.
l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
) < 0.05
signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
### ==== mean of signed distances ==== ###
signed_dist_e = torch.sum(
-1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
) / torch.clamp(
torch.sum(signed_dist_mask.float()), min=1e-5
).item()
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
# tot_obj_trimeshes
### refine the optimization with signed energy ##
signed_dist_e_coeff = 1.0 #
fine_lr = 0.1
# num_iters = 1000 #
num_iters = 100 # reinement #
opt = optim.Adam([rot_var, transl_var, beta_var, theta_var], lr=fine_lr)
for i_iter in range(num_iters): #
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
# dists_base_pts_to_joints ## dists_base_pts_to_joints ##
if dists_base_pts_to_joints is not None: ## dists_base_pts_to_joints ##
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).mean()
''' strategy 2: use all base pts, rel, dists for resolving '''
# # rel_base_pts_to_hand_joints: bsz x ws x nnj x nnb x 3 #
# signed_dist_mask = signed_dist_base_pts_to_hand_joints < 0.
# l2_dist_rel_joints_to_base_pts_mask = torch.sqrt(
# torch.sum(rel_base_pts_to_hand_joints ** 2, dim=-1)
# ) < 0.05
# signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_base_pts_mask.float()) > 1.5
# ## === dot rel with normals === ##
# # dot_rel_with_normals = torch.sum(
# # rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
# # )
# ## === dot rel with normals === ##
# ## === dot rel with rel, strategy 3 === ##
# dot_rel_with_normals = torch.sum(
# -1.0 * rel_base_pts_to_hand_joints * rel_base_pts_to_hand_joints, dim=-1
# )
# ## === dot rel with rel, strategy 3 === ##
# signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# # dot_rel_with_normals: bsz x ws x nnj x nnb
# avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
# signed_dist_e = dot_rel_with_normals * signed_dist_base_pts_to_hand_joints
# signed_dist_e = torch.sum(
# signed_dist_e[signed_dist_mask]
# ) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
# ###### ====== get loss for signed distances ==== ###
''' strategy 2: use all base pts, rel, dists for resolving '''
## use all base pts ##
{
# hard projections for
''' strategy 1: use nearest base pts, rel, dists for resolving '''
# ### === e2 the signed distances to nearest points should not be negative to the neareste === ###
# ## base_pts: bsz x nn_base_pts x 3
# ## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
# ## bsz x ws x nnj x nnb ##
# dist_rhand_joints_to_base_pts = torch.sum(
# (hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
# )
# # minn_dists_idxes: bsz x ws x nnj -->
# minn_dists_to_base_pts, minn_dists_idxes = torch.min(
# dist_rhand_joints_to_base_pts, dim=-1
# )
#
# # base_pts: bsz x nn_base_pts x 3 #
# # base_pts: bsz x ws x nn_base_pts x 3 #
# # bsz x ws x nnj
# # base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
# # bsz x ws x nnj x 3 ##
# nearest_base_pts = batched_index_select_ours(
# base_pts_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 #
# nearest_base_normals = batched_index_select_ours(
# base_normals_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 #
# rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# # bsz x ws x nnj #
# signed_dist_joints_to_base_pts = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# # should not be negative
# signed_dist_mask = signed_dist_joints_to_base_pts < 0.
# ## === luojisiwei and others === ##
# # l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# # torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# # ) < 0.05
# ## === luojisiwei and others === ##
# l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# ) < 0.1
# signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
# ### ==== mean of signed distances ==== ###
# # signed_dist_e = torch.sum(
# # -1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
# # ) / torch.clamp(
# # torch.sum(signed_dist_mask.float()), min=1e-5
# # ).item()
# # signed_dist_joints_to_base_pts: bsz x ws x nnj # -> disstances
# signed_dist_joints_to_base_pts = signed_dist_joints_to_base_pts.detach()
# #
## penetraition resolving --- strategy
# dot_rel_with_normals = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# # bsz x ws x nnj --> the loss term
# ## signed distances 3 #### isgned distance 3 ###
# ## dotrelwithnormals, ##
# # # signed_dist_mask -> the distances
# # dot_rel_with_normals: bsz x ws x nnj x nnb
# avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
# signed_dist_e = dot_rel_with_normals * signed_dist_joints_to_base_pts
# signed_dist_e = torch.sum(
# signed_dist_e[signed_dist_mask]
# ) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
# ###### ====== get loss for signed distances ==== ###
''' strategy 1: use nearest base pts, rel, dists for resolving '''
}
# bsz x ws x nnj # --> objmesh insides pts labels
pts_inside_objmesh_labels = judge_penetrated_points(tot_obj_trimeshes, hand_joints)
pts_inside_objmesh_labels_mask = pts_inside_objmesh_labels.bool()
# {
# hard projections for
''' strategy 1: use nearest base pts, rel, dists for resolving '''
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
dist_rhand_joints_to_base_pts = torch.sum(
(hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
)
# minn_dists_idxes: bsz x ws x nnj -->
# base_pts
minn_dists_to_base_pts, minn_dists_idxes = torch.min(
dist_rhand_joints_to_base_pts, dim=-1
)
# base_pts: bsz x nn_base_pts x 3 #
# base_pts: bsz x ws x nn_base_pts x 3 #
# bsz x ws x nnj
# base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
# bsz x ws x nnj x 3 ##
# simple penetration ##
nearest_base_pts = batched_index_select_ours(
base_pts_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
nearest_base_normals = batched_index_select_ours(
base_normals_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# bsz x ws x nnj #
# signed_dist_joints_to_base_pts = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# # should not be negative
# signed_dist_mask = signed_dist_joints_to_base_pts < 0.
## === luojisiwei and others === ##
# l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# ) < 0.05
## === luojisiwei and others === ##
##### ===== GET l2_distance mask ===== #####
# l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# ) < 0.1
# signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
##### ===== GET l2_distance mask ===== #####
### ==== mean of signed distances ==== ###
# signed_dist_e = torch.sum(
# -1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
# ) / torch.clamp(
# torch.sum(signed_dist_mask.float()), min=1e-5
# ).item()
# signed_dist_joints_to_base_pts: bsz x ws x nnj # -> disstances
signed_dist_joints_to_base_pts = signed_dist_joints_to_base_pts.detach()
#
# dot rel
# penetraition resolving --- strategy
# dot_rel_with_normals = torch.sum( # dot rhand joints with normals #
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
#
dot_rel_with_normals = torch.sum( # dot rhand joints with normals #
-rel_joints_to_nearest_base_pts * rel_joints_to_nearest_base_pts, dim=-1
)
#### Get masks for penetrated joint points ####
# signed_dist_mask = (signed_dist_mask.float() + pts_inside_objmesh_labels_mask.float()) > 1.5
signed_dist_mask = pts_inside_objmesh_labels_mask
# bsz x ws x nnj
signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# bsz x ws x nnj --> the loss term
## signed distances 3 #### isgned distance 3 ###
## dotrelwithnormals, ##
# # signed_dist_mask -> the distances
# dot_rel_with_normals: bsz x ws x nnj x nnb # avg over windows and batches #
avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
## get singed distance energies ### ## projection ##
# signed_dist_e = dot_rel_with_normals * signed_dist_joints_to_base_pts
signed_dist_e = -1.0 * dot_rel_with_normals
signed_dist_e = torch.sum(
signed_dist_e[signed_dist_mask]
) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
###### ====== get loss for signed distances ==== ###
''' strategy 1: use nearest base pts, rel, dists for resolving '''
# cannot mask in some caes
# change of isgned distances #
# intersection spline
## judeg whether inside the object and only project those one inside of the object
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
#### ==== sv_dict ==== ####
sv_dict = {
'pts_inside_objmesh_labels_mask': pts_inside_objmesh_labels_mask.detach().cpu().numpy(),
'hand_joints': hand_joints.detach().cpu().numpy(),
'obj_verts': [cur_verts.detach().cpu().numpy() for cur_verts in obj_verts],
'obj_faces': [cur_faces.detach().cpu().numpy() for cur_faces in obj_faces],
'base_pts': base_pts.detach().cpu().numpy(),
'base_normals': base_normals.detach().cpu().numpy(), # bsz x nnb x 3 -> bsz x nnb x 3 -> base normals #
'nearest_base_pts': nearest_base_pts.detach().cpu().numpy(), # bsz x ws x nnj x 3 #
'nearest_base_normals': nearest_base_normals.detach().cpu().numpy(), # bsz x ws x nnj x 3 --> base normals and pts
}
#
sv_dict_folder = "/data1/sim/mdm/tmp_saving"
os.makedirs(sv_dict_folder, exist_ok=True)
sv_dict_fn = os.path.join(sv_dict_folder, f"optim_iter_{i_iter}.npy")
np.save(sv_dict_fn, sv_dict)
print(f"Obj and subj saved to {sv_dict_fn}")
#### ==== sv_dict ==== ####
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
# shoudl take a
# how to proejct the jvertex
# hwo to project the veretex
# weighted sum of the projectiondirection
# weights of each base point
# atraction field -> should be able to learn the penetration resolving strategy
# stochestic penetration resolving strategy #
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
# avg_masks
print('\tAvg masks: {}'.format(avg_masks.item()))
''' returning sampled_joints '''
sampled_joints = hand_joints
np.save("optimized_verts.npy", hand_verts.detach().cpu().numpy())
print(f"Optimized verts saved to optimized_verts.npy")
return sampled_joints.detach()
# TODO: other optimization strategies? e.g. sequential optimziation> #
def optimize_sampled_hand_joints_wobj_v2(sampled_joints, rel_base_pts_to_joints, dists_base_pts_to_joints, base_pts, base_normals, obj_verts, obj_normals, obj_faces):
# sampled_joints: bsz x ws x nnj x 3 #
# sampled_joints: bsz x ws x nnj x 3 # obj trimeshes #
tot_obj_trimeshes = get_obj_trimesh_list(obj_verts, obj_faces)
## TODO: write the collect function for object verts, normals, faces ##
### A simple penetration resolving strategy is as follows:
#### 1) get vertices in the object; 2) get nearest base points (for simplicity); 3) project the vertex to the base point ####
## 1) for joints only;
## 2) for vertices;
## 3) for vertices;
## TODO: optimzie the resolvign strategy stated above ##
bsz, ws, nnj = sampled_joints.shape[:3]
device = sampled_joints.device
coarse_lr = 0.1
num_iters = 100 # if i_iter > 0 else 1 ## nn-coarse-iters for global transformations #
mano_path = "/data1/sim/mano_models/mano/models"
# obj_verts: bsz x nnobjverts x
base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
base_normals_exp = base_normals.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
signed_dist_e_coeff = 1.0
signed_dist_e_coeff = 0.0
### start optimization ###
# setup MANO layer
mano_layer = ManoLayer(
flat_hand_mean=True,
side='right',
mano_root=mano_path, # mano_path for the mano model #
ncomps=24,
use_pca=True,
root_rot_mode='axisang',
joint_rot_mode='axisang'
).to(device)
## random init variables ##
beta_var = torch.randn([bsz, 10]).to(device)
rot_var = torch.randn([bsz * ws, 3]).to(device)
theta_var = torch.randn([bsz * ws, 24]).to(device)
transl_var = torch.randn([bsz * ws, 3]).to(device)
beta_var.requires_grad_()
rot_var.requires_grad_()
theta_var.requires_grad_()
transl_var.requires_grad_()
opt = optim.Adam([rot_var, transl_var], lr=coarse_lr)
for i_iter in range(num_iters):
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
if dists_base_pts_to_joints is not None:
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).to(device).mean()
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
''' strategy 2: use all base pts, rel, dists for resolving '''
# rel_base_pts_to_hand_joints: bsz x ws x nnj x nnb x 3 #
signed_dist_mask = signed_dist_base_pts_to_hand_joints < 0.
l2_dist_rel_joints_to_base_pts_mask = torch.sqrt(
torch.sum(rel_base_pts_to_hand_joints ** 2, dim=-1)
) < 0.05
signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_base_pts_mask.float()) > 1.5
dot_rel_with_normals = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# dot_rel_with_normals: bsz x ws x nnj x nnb
avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
signed_dist_e = dot_rel_with_normals * signed_dist_base_pts_to_hand_joints
signed_dist_e = torch.sum(
signed_dist_e[signed_dist_mask]
) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
###### ====== get loss for signed distances ==== ###
''' strategy 2: use all base pts, rel, dists for resolving '''
''' strategy 1: use nearest base pts, rel, dists for resolving '''
# dist_rhand_joints_to_base_pts = torch.sum(
# (hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
# )
# # minn_dists_idxes: bsz x ws x nnj -->
# minn_dists_to_base_pts, minn_dists_idxes = torch.min(
# dist_rhand_joints_to_base_pts, dim=-1
# )
# # base_pts: bsz x nn_base_pts x 3 #
# # base_pts: bsz x ws x nn_base_pts x 3 #
# # bsz x ws x nnj
# # object verts and object faces #
# ## other than the sampling process; not
# # bsz x ws x nnj x 3 ##
# nearest_base_pts = batched_index_select_ours(
# base_pts_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 # # base normalse #
# nearest_base_normals = batched_index_select_ours(
# base_normals_exp, indices=minn_dists_idxes, dim=2
# )
# # bsz x ws x nnj x 3 # # the nearest distance points may be of some ambiguous
# rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# # bsz x ws x nnj #
# signed_dist_joints_to_base_pts = torch.sum(
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
# # should not be negative
# signed_dist_mask = signed_dist_joints_to_base_pts < 0.
# l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
# torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
# ) < 0.05
# signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
# ### ==== mean of signed distances ==== ###
# signed_dist_e = torch.sum( # penetration
# -1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
# ) / torch.clamp(
# torch.sum(signed_dist_mask.float()), min=1e-5
# ).item()
''' strategy 1: use nearest base pts, rel, dists for resolving '''
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
### signed distance coeff -> the distance coeff #
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
fine_lr = 0.1
num_iters = 1000
opt = optim.Adam([rot_var, transl_var, beta_var, theta_var], lr=fine_lr)
for i_iter in range(num_iters):
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
# dists_base_pts_to_joints ## dists_base_pts_to_joints ##
if dists_base_pts_to_joints is not None: ## dists_base_pts_to_joints ##
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).mean()
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
dist_rhand_joints_to_base_pts = torch.sum(
(hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
)
# minn_dists_idxes: bsz x ws x nnj -->
minn_dists_to_base_pts, minn_dists_idxes = torch.min(
dist_rhand_joints_to_base_pts, dim=-1
)
# base_pts: bsz x nn_base_pts x 3 #
# base_pts: bsz x ws x nn_base_pts x 3 #
# bsz x ws x nnj
# base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
# bsz x ws x nnj x 3 ##
nearest_base_pts = batched_index_select_ours(
base_pts_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
nearest_base_normals = batched_index_select_ours(
base_normals_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 #
rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# bsz x ws x nnj #
signed_dist_joints_to_base_pts = torch.sum(
rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
)
# should not be negative
signed_dist_mask = signed_dist_joints_to_base_pts < 0.
l2_dist_rel_joints_to_nearest_base_pts_mask = torch.sqrt(
torch.sum(rel_joints_to_nearest_base_pts ** 2, dim=-1)
) < 0.05
signed_dist_mask = (signed_dist_mask.float() + l2_dist_rel_joints_to_nearest_base_pts_mask.float()) > 1.5
### ==== mean of signed distances ==== ###
signed_dist_e = torch.sum(
-1.0 * signed_dist_joints_to_base_pts[signed_dist_mask]
) / torch.clamp(
torch.sum(signed_dist_mask.float()), min=1e-5
).item()
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
# tot_obj_trimeshes
### refine the optimization with signed energy ##
#
# signed_dist_jts_to_nearest_base_pts = []
# tot_nearest_base_pts = []
# tot_nearest_base_normals = []
signed_dist_e_coeff = 1.0 #
fine_lr = 0.1
# num_iters = 1000 #
num_iters = 100 # reinement #
opt = optim.Adam([rot_var, transl_var, beta_var, theta_var], lr=fine_lr)
for i_iter in range(num_iters): #
opt.zero_grad()
# mano_layer #
hand_verts, hand_joints = mano_layer(torch.cat([rot_var, theta_var], dim=-1),
beta_var.unsqueeze(1).repeat(1, ws, 1).view(-1, 10), transl_var)
hand_verts = hand_verts.view(bsz, ws, 778, 3) * 0.001 ## bsz x ws x nn
hand_joints = hand_joints.view(bsz, ws, -1, 3) * 0.001
### === e1 should be close to predicted values === ###
# bsz x ws x nnj x nnb x 3 #
rel_base_pts_to_hand_joints = hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
# bs zx ws x nnj x nnb #
signed_dist_base_pts_to_hand_joints = torch.sum(
rel_base_pts_to_hand_joints * base_normals.unsqueeze(1).unsqueeze(1), dim=-1
)
rel_e = torch.sum(
(rel_base_pts_to_hand_joints - rel_base_pts_to_joints) ** 2, dim=-1
).mean()
# dists_base_pts_to_joints ## dists_base_pts_to_joints ##
if dists_base_pts_to_joints is not None: ## dists_base_pts_to_joints ##
dist_e = torch.sum(
(signed_dist_base_pts_to_hand_joints - dists_base_pts_to_joints) ** 2, dim=-1
).mean()
else:
dist_e = torch.zeros((1,), dtype=torch.float32).mean()
### ==== inside the objemesh labels ==== ###
# bsz x ws x nnj # --> objmesh insides pts labels #
pts_inside_objmesh_labels = judge_penetrated_points(tot_obj_trimeshes, hand_joints)
pts_inside_objmesh_labels_mask = pts_inside_objmesh_labels.bool()
# {
# hard projections for
''' strategy 1: use nearest base pts, rel, dists for resolving '''
### === e2 the signed distances to nearest points should not be negative to the neareste === ###
## base_pts: bsz x nn_base_pts x 3
## bsz x ws x nnj x 1 x 3 -- bsz x 1 x 1 x nnb x 3 ##
## bsz x ws x nnj x nnb ##
dist_rhand_joints_to_base_pts = torch.sum(
(hand_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)) ** 2, dim=-1
)
# minn_dists_idxes: bsz x ws x nnj #
# base_pts
minn_dists_to_base_pts, minn_dists_idxes = torch.min(
dist_rhand_joints_to_base_pts, dim=-1
)
# base_pts: bsz x nn_base_pts x 3 #
# base_pts: bsz x ws x nn_base_pts x 3 #
# bsz x ws x nnj
# base_pts_exp = base_pts.unsqueeze(1).repeat(1, ws, 1, 1).contiguous()
# bsz x ws x nnj x 3 ##
# simple penetration ##
nearest_base_pts = batched_index_select_ours(
base_pts_exp, indices=minn_dists_idxes, dim=2
)
# bsz x ws x nnj x 3 # #
nearest_base_normals = batched_index_select_ours(
base_normals_exp, indices=minn_dists_idxes, dim=2
)
tot_masks = []
tot_base_pts = []
tot_base_normals = []
tot_base_signed_dists = []
## === nearest base pts === ##
for i_bsz in range(nearest_base_pts.size(0)):
# masks, base_pts, base_normals for each frame here
# cur_bsz_
cur_bsz_masks = [pts_inside_objmesh_labels_mask[i_bsz][0]]
cur_bsz_base_pts = [nearest_base_pts[i_bsz][0]]
cur_bsz_base_normals = [nearest_base_normals[i_bsz][0]]
# nnjts #
## st frame signed dist ##
cur_bsz_st_frame_signed_dist = torch.sum(
(hand_joints[i_bsz][0] - cur_bsz_base_pts[0]) * cur_bsz_base_normals[0], dim=-1
)
cur_bsz_signed_dist = [cur_bsz_st_frame_signed_dist]
for i_fr in range(1, nearest_base_pts.size(1)):
cur_bsz_cur_fr_jts = hand_joints[i_bsz][i_fr]
# cur_bsz_cur_fr_base_pts = nearest_base_pts
# cur_fr_jts -
cur_bsz_cur_fr_prev_fr_signed_dist = torch.sum(
(cur_bsz_cur_fr_jts - cur_bsz_base_pts[-1]) * cur_bsz_base_normals[-1], dim=-1
)
# nnjts # cur
cur_bsz_cur_fr_mask = ((cur_bsz_signed_dist[-1] >= 0.).float() + (cur_bsz_cur_fr_prev_fr_signed_dist < 0.).float()) > 1.5
cur_bsz_cur_fr_base_pts = nearest_base_pts[i_bsz][i_fr].clone()
cur_bsz_cur_fr_base_pts[cur_bsz_cur_fr_mask] = cur_bsz_base_pts[-1][cur_bsz_cur_fr_mask]
cur_bsz_cur_fr_base_normals = nearest_base_normals[i_bsz][i_fr].clone()
# ### curbsz curfr base normals; ### #
cur_bsz_cur_fr_base_normals[cur_bsz_cur_fr_mask] = cur_bsz_base_normals[-1][cur_bsz_cur_fr_mask]
cur_bsz_cur_fr_signed_dist = torch.sum(
(cur_bsz_cur_fr_jts - cur_bsz_cur_fr_base_pts) * cur_bsz_cur_fr_base_normals, dim=-1
)
cur_bsz_cur_fr_signed_dist[cur_bsz_cur_fr_mask] = 0. # ot the bes points
### for masks ###
cur_bsz_masks.append(cur_bsz_cur_fr_mask)
cur_bsz_base_pts.append(cur_bsz_cur_fr_base_pts)
cur_bsz_base_normals.append(cur_bsz_cur_fr_base_normals)
#
cur_bsz_masks = torch.stack(cur_bsz_masks, dim=0)
cur_bsz_base_pts = torch.stack(cur_bsz_base_pts, dim=0)
cur_bsz_base_normals = torch.stack(cur_bsz_base_normals, dim=0)
cur_bsz_signed_dist = torch.stack(cur_bsz_signed_dist, dim=0)
tot_masks.append(cur_bsz_masks)
tot_base_pts.append(cur_bsz_base_pts)
tot_base_normals.append(cur_bsz_base_normals)
tot_base_signed_dists.append(cur_bsz_signed_dist)
# masks;
tot_masks = torch.stack(tot_masks, dim=0)
tot_base_pts = torch.stack(tot_base_pts, dim=0)
tot_base_normals = torch.stack(tot_base_normals, dim=0)
tot_base_signed_dists = torch.stack(tot_base_signed_dists, dim=0)
#
nearest_base_pts = tot_base_pts.clone() # tot base pts
nearest_base_normals = tot_base_normals.clone()
pts_inside_objmesh_labels_mask = tot_masks.clone()
# if len()
# bsz x ws x nnj x 3 #
rel_joints_to_nearest_base_pts = hand_joints - nearest_base_pts
# signed_dist_joints_to_base_pts: bsz x ws x nnj # -> disstances
# signed_dist_joints_to_base_pts = signed_dist_joints_to_base_pts.detach()
#
# dot rel
# penetraition resolving --- strategy
# dot_rel_with_normals = torch.sum( # dot rhand joints with normals #
# rel_joints_to_nearest_base_pts * nearest_base_normals, dim=-1
# )
#
dot_rel_with_normals = torch.sum( # dot rhand joints with normals #
-rel_joints_to_nearest_base_pts * rel_joints_to_nearest_base_pts, dim=-1
)
#### Get masks for penetrated joint points ####
# signed_dist_mask = (signed_dist_mask.float() + pts_inside_objmesh_labels_mask.float()) > 1.5
signed_dist_mask = pts_inside_objmesh_labels_mask
# bsz x ws x nnj
signed_dist_mask = signed_dist_mask.detach() # detach the mask #
# bsz x ws x nnj --> the loss term
## signed distances 3 #### isgned distance 3 ###
## dotrelwithnormals, ##
# # signed_dist_mask -> the distances
# dot_rel_with_normals: bsz x ws x nnj x nnb # avg over windows and batches #
avg_masks = (signed_dist_mask.float()).sum(dim=-1).mean()
## get singed distance energies ### ## projection ##
# signed_dist_e = dot_rel_with_normals * signed_dist_joints_to_base_pts
### dot_rel_with_normals -->
signed_dist_e = -1.0 * dot_rel_with_normals
signed_dist_e = torch.sum(
signed_dist_e[signed_dist_mask]
) / torch.clamp(torch.sum(signed_dist_mask.float()), min=1e-5).item()
###### ====== get loss for signed distances ==== ###
''' strategy 1: use nearest base pts, rel, dists for resolving '''
# cannot mask in some caes
# change of isgned distances #
# intersection spline
## judeg whether inside the object and only project those one inside of the object
## === e3 smoothness and prior losses === ##
pose_smoothness_loss = F.mse_loss(theta_var.view(bsz, ws, -1)[:, 1:], theta_var.view(bsz, ws, -1)[:, :-1])
shape_prior_loss = torch.mean(beta_var**2)
pose_prior_loss = torch.mean(theta_var**2)
## === e3 smoothness and prior losses === ##
# points to object vertices
#### ==== sv_dict ==== ####
sv_dict = {
'pts_inside_objmesh_labels_mask': pts_inside_objmesh_labels_mask.detach().cpu().numpy(),
'hand_joints': hand_joints.detach().cpu().numpy(),
'obj_verts': [cur_verts.detach().cpu().numpy() for cur_verts in obj_verts],
'obj_faces': [cur_faces.detach().cpu().numpy() for cur_faces in obj_faces],
'base_pts': base_pts.detach().cpu().numpy(),
'base_normals': base_normals.detach().cpu().numpy(), # bsz x nnb x 3 -> bsz x nnb x 3 -> base normals #
'nearest_base_pts': nearest_base_pts.detach().cpu().numpy(), # bsz x ws x nnj x 3 #
'nearest_base_normals': nearest_base_normals.detach().cpu().numpy(), # bsz x ws x nnj x 3 --> base normals and pts
}
#
sv_dict_folder = "/data1/sim/mdm/tmp_saving"
os.makedirs(sv_dict_folder, exist_ok=True)
sv_dict_fn = os.path.join(sv_dict_folder, f"optim_iter_{i_iter}.npy")
np.save(sv_dict_fn, sv_dict)
print(f"Obj and subj saved to {sv_dict_fn}")
#### ==== sv_dict ==== ####
## === e4 hand joints should be close to sampled hand joints === ##
dist_dec_jts_to_sampled_pts = torch.sum(
(hand_joints - sampled_joints) ** 2, dim=-1
).mean()
# shoudl take a
# how to proejct the jvertex
# hwo to project the veretex
# weighted sum of the projectiondirection
# weights of each base point
# atraction field -> should be able to learn the penetration resolving strategy
# stochestic penetration resolving strategy #
loss = pose_smoothness_loss * 0.05 + shape_prior_loss*0.001 + pose_prior_loss * 0.0001 + signed_dist_e * signed_dist_e_coeff + rel_e + dist_e + dist_dec_jts_to_sampled_pts
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tShape Prior Loss: {}'.format(shape_prior_loss.item()))
print('\tPose Prior Loss: {}'.format(pose_prior_loss.item()))
print('\tPose Smoothness Loss: {}'.format(pose_smoothness_loss.item()))
print('\tsigned_dist_e Loss: {}'.format(signed_dist_e.item()))
print('\trel_e Loss: {}'.format(rel_e.item()))
print('\tdist_e Loss: {}'.format(dist_e.item()))
print('\tdist_dec_jts_to_sampled_pts Loss: {}'.format(dist_dec_jts_to_sampled_pts.item()))
# avg_masks
print('\tAvg masks: {}'.format(avg_masks.item()))
''' returning sampled_joints '''
sampled_joints = hand_joints
np.save("optimized_verts.npy", hand_verts.detach().cpu().numpy())
print(f"Optimized verts saved to optimized_verts.npy")
return sampled_joints.detach()
##
def create_gaussian_diffusion(args): ## create guassian diffusion ##
# default params
predict_xstart = True # we always predict x_start (a.k.a. x0), that's our deal!
steps = 1000 #
scale_beta = 1. # no scaling
timestep_respacing = '' # can be used for ddim sampling, we don't use it.
learn_sigma = False # learn sigma #
rescale_timesteps = False
## noose schedule; steps; scale_beta ## ## MSE ##
betas = gd.get_named_beta_schedule(args.noise_schedule, steps, scale_beta)
loss_type = gd.LossType.MSE
if not timestep_respacing:
timestep_respacing = [steps]
print(f"dataset: {args.dataset}, rep_type: {args.rep_type}")
if args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist", "ambient_obj_base_rel_dist"]:
print(f"here! dataset: {args.dataset}, rep_type: {args.rep_type}")
cur_spaced_diffusion_model = SpacedDiffusion_Ours
# SpacedDiffusion_OursV2
elif args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist_we"]:
cur_spaced_diffusion_model = SpacedDiffusion_OursV2
elif args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist_we_wj"]:
cur_spaced_diffusion_model = SpacedDiffusion_OursV3
# SpacedDiffusion_OursV4
elif args.dataset in ['motion_ours'] and args.rep_type in ["obj_base_rel_dist_we_wj_latents"]:
if args.diff_joint_quants:
cur_spaced_diffusion_model = SpacedDiffusion_OursV7
elif args.diff_hand_params:
cur_spaced_diffusion_model = SpacedDiffusion_OursV9
else:
if args.diff_spatial:
cur_spaced_diffusion_model = SpacedDiffusion_OursV5
elif args.diff_latents:
cur_spaced_diffusion_model = SpacedDiffusion_OursV6
else:
cur_spaced_diffusion_model = SpacedDiffusion_OursV4
else:
cur_spaced_diffusion_model = SpacedDiffusion
### ==== predict xstart other than the noise in the model === ###
return cur_spaced_diffusion_model(
use_timesteps=space_timesteps(steps, timestep_respacing),
betas=betas,
model_mean_type=(
gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X
),
model_var_type=( ## use fixed sigmas / variances ##
(
gd.ModelVarType.FIXED_LARGE
if not args.sigma_small
else gd.ModelVarType.FIXED_SMALL # fixed small #
)
if not learn_sigma ## use learned sigmas ##
else gd.ModelVarType.LEARNED_RANGE
), ## modelvartype ##
loss_type=loss_type, ## loss_type ##
rescale_timesteps=rescale_timesteps,
lambda_vel=args.lambda_vel,
lambda_rcxyz=args.lambda_rcxyz, ## lambda
lambda_fc=args.lambda_fc,
# motion_to_rep
denoising_stra=args.denoising_stra,
inter_optim=args.inter_optim,
args=args,
)
### from decoded energies to optimized joints ###
## latent variables ##
## encoded energies ## from energies calculated from perturbed energies ##
## decoded energies should also match the clean energy term ##
## and those values should be all denormed ##
def optimize_joints_according_to_e(dec_joints, base_pts, base_normals, dec_e):
# dec_e_along_normals: bsz x (ws - 1) x nnj x nnb
dec_e_along_normals = dec_e['dec_e_along_normals']
# dec_e_vt_normals: bsz x (ws - 1) x nnj x nnb
dec_e_vt_normals = dec_e['dec_e_vt_normals']
nn_iters = 10
coarse_lr = 0.001
dec_joints.requires_grad_()
opt = optim.Adam([dec_joints], lr=coarse_lr)
for i_iter in range(nn_iters):
# dec_joints: bsz x ws x nnj x 3
# base_pts: bsz x nnb x 3
k_f = 1.
# bsz x ws x nnj x nnb x 3 #
denormed_rel_base_pts_to_rhand_joints = dec_joints.unsqueeze(-2) - base_pts.unsqueeze(1).unsqueeze(1)
k_f = 1. ## l2 rel base pts to pert rhand joints ##
# l2_rel_base_pts_to_pert_rhand_joints: bsz x nf x nnj x nnb #
l2_rel_base_pts_to_pert_rhand_joints = torch.norm(denormed_rel_base_pts_to_rhand_joints, dim=-1)
### att_forces ##
att_forces = torch.exp(-k_f * l2_rel_base_pts_to_pert_rhand_joints) # bsz x nf x nnj x nnb #
# bsz x (ws - 1) x nnj x nnb #
att_forces = att_forces[:, :-1, :, :] # attraction forces -1 #
# rhand_joints: ws x nnj x 3 # -> (ws - 1) x nnj x 3 ## rhand_joints ##
# bsz x (ws - 1) x nnj x 3 --> displacements s#
denormed_rhand_joints_disp = dec_joints[:, 1:, :, :] - dec_joints[:, :-1, :, :]
# distance -- base_normalss,; (ws - 1) x nnj x nnb x 3 --> bsz x (ws - 1) x nnj x nnb #
# signed_dist_base_pts_to_pert_rhand_joints_along_normal # bsz x (ws - 1) x nnj x nnb #
signed_dist_base_pts_to_rhand_joints_along_normal = torch.sum(
base_normals.unsqueeze(1).unsqueeze(1) * denormed_rhand_joints_disp.unsqueeze(-2), dim=-1
)
# rel_base_pts_to_pert_rhand_joints_vt_normal: bsz x (ws -1) x nnj x nnb x 3 -> the relative positions vertical to base normals #
rel_base_pts_to_rhand_joints_vt_normal = denormed_rhand_joints_disp.unsqueeze(-2) - signed_dist_base_pts_to_rhand_joints_along_normal.unsqueeze(-1) * base_normals.unsqueeze(1).unsqueeze(1)
dist_base_pts_to_rhand_joints_vt_normal = torch.sqrt(torch.sum(
rel_base_pts_to_rhand_joints_vt_normal ** 2, dim=-1
))
k_a = 1.
k_b = 1.
### bsz x (ws - 1) x nnj x nnb ###
e_disp_rel_to_base_along_normals = k_a * att_forces * torch.abs(signed_dist_base_pts_to_rhand_joints_along_normal)
# (ws - 1) x nnj x nnb # -> dist vt normals # ##
e_disp_rel_to_baes_vt_normals = k_b * att_forces * dist_base_pts_to_rhand_joints_vt_normal
# nf x nnj x nnb ---> dist_vt_normals -> nf x nnj x nnb # # torch.sqrt() ##
#
loss_cur_e_pred_e_along_normals = ((e_disp_rel_to_base_along_normals - dec_e_along_normals) ** 2).mean()
loss_cur_e_pred_e_vt_normals = ((e_disp_rel_to_baes_vt_normals - dec_e_vt_normals) ** 2).mean()
loss = loss_cur_e_pred_e_along_normals + loss_cur_e_pred_e_vt_normals
opt.zero_grad()
loss.backward()
opt.step()
print('Iter {}: {}'.format(i_iter, loss.item()), flush=True)
print('\tloss_cur_e_pred_e_along_normals: {}'.format(loss_cur_e_pred_e_along_normals.item()))
print('\tloss_cur_e_pred_e_vt_normals: {}'.format(loss_cur_e_pred_e_vt_normals.item()))
return dec_joints.detach() |