Spaces:
Runtime error
Runtime error
File size: 138,338 Bytes
be13417 |
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 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 |
"""
Copyright (c) 2023, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
"""
Requires Transformer 4.28 and above, implementation may change according the Llama implementation
"""
import logging
import string
from packaging import version
import os
from omegaconf import OmegaConf
import torch
from torch.cuda.amp import autocast as autocast
import torch.nn as nn
from torch.nn.modules.module import _IncompatibleKeys
from peft import (
get_peft_model,
LoraConfig,
TaskType,
)
import transformers
import random
from lavis.common.registry import registry
from lavis.models.base_model import BaseModel
from lavis.models.blip2_models.blip2 import Blip2Base, disabled_train, LayerNorm
from lavis.models.ulip_models.ULIP_models import ULIP_PointBERT
from lavis.tasks.multimodal_classification import MultimodalClassificationTask
from lavis.common.utils import is_url
from lavis.models.blip2_models.Qformer import BertConfig, BertLMHeadModel
from lavis.common.dist_utils import download_cached_file
from lavis.processors.blip_processors import BlipCaptionProcessor
class CastOutputToFloat(nn.Sequential):
def forward(self, x): return super().forward(x).to(torch.float32)
@registry.register_model("blip2_vicuna_xinstruct")
class Blip2VicunaXInstruct(Blip2Base):
"""
BLIP2 Vicuna model.
Supported model types:
- vicuna7b
- vicuna13b
Usage:
>>> from lavis.models import load_model
>>> model = load_model("blip2_vicuna_xinstruct", "vicuna7b")
"""
PRETRAINED_MODEL_CONFIG_DICT = {
"vicuna7b": "configs/models/blip2/blip2_xinstruct_vicuna7b.yaml",
"vicuna13b": "configs/models/blip2/blip2_xinstruct_vicuna13b.yaml",
}
SEQUENCIAL_ENCODERS = [
"eva_clip_g",
"beats"
]
SEQUENCIAL_MODALITIES = [
"video",
"audio"
]
MODALITY_TO_CUE = {
"image": " image: ",
"pc": " 3d: ",
"video": " video: ",
"audio": " audio: ",
}
def __init__(
self,
modalities = ["image", "pc", "audio", "video"],
use_cues=True,
num_query_token=32,
qformer_text_input=True,
llm_text_input=False,
apply_lemmatizer=False,
## encoders
image_model="eva_clip_g",
pc_model="ulip2_pointbert",
video_model="eva_clip_g",
audio_model="beats",
image_encoder_kwargs = {"image_size": 224, "drop_path_rate": 0, "use_grad_checkpoint": False},
pc_encoder_kwargs = {},
video_encoder_kwargs = {},
audio_encoder_kwargs = {},
image_precision="fp16",
pc_precision="fp16",
video_precision="fp16",
audio_precision="fp16",
freeze_image=True,
freeze_pc=True,
freeze_video=True,
freeze_audio=True,
## load pretrained parameters
pretrained_image_qformer=None,
pretrained_pc_qformer=None,
pretrained_video_qformer=None,
pretrained_audio_qformer=None,
load_attention_image_qformer=False,
load_attention_pc_qformer=False,
load_attention_video_qformer=False,
load_attention_audio_qformer=False,
load_qformer_type_image="",
load_qformer_type_pc="",
load_qformer_type_video="",
load_qformer_type_audio="",
load_ln_type_image="",
load_ln_type_pc="",
load_ln_type_video="",
load_ln_type_audio="",
load_projection_image=True,
load_projection_pc=True,
load_projection_video=True,
load_projection_audio=True,
load_projection_type_image="",
load_projection_type_pc="",
load_projection_type_video="",
load_projection_type_audio="",
## llm model parameters
llm_model="",
lora_model="",
lora=False,
## generation parameters
prompt="",
prefix="",
postfix="",
max_txt_len=128,
max_output_txt_len=256,
special_qformer_input_prompt=False,
enumerate_inputs=False,
add_space=False,
remove_start=False,
clean_tokenization=False, # if set to true removes whitespace from cue, and start token from prompt.
## shared Q-former setup
shared_qformer=False,
pretrained_shared_qformer=None,
load_attention_shared_qformer=False,
load_qformer_type_shared="",
load_projection_shared=False,
load_projection_type_shared="",
encoder_projection_type_image="",
encoder_projection_type_pc="",
encoder_projection_type_video="",
encoder_projection_type_audio="",
shared_qformer_num_features=512,
## use cached features
cached_audio=False,
cached_image=False,
cached_pc=False,
cached_video=False,
## num features for modality (only needed in cached cases.)
num_features_audio=768,
num_features_image=1408,
num_features_video=1408,
num_features_pc=512,
joint_video_audio=False,
## DisCRN
use_caption=False,
use_describe=False,
## classification setup
predict_with_gen=False,
format_candidates_prompt="{}",
## projection only parameters
projection_only=False,
projection_only_audio=False,
projection_only_pc=False,
projection_only_video=False,
projection_only_image=False,
projection_path_audio=False,
projection_path_pc=False,
projection_path_video=False,
projection_path_image=False,
proj_dim=1,
):
super().__init__()
transformers_version = version.parse(transformers.__version__)
assert transformers_version >= version.parse("4.28"), "BLIP-2 Vicuna requires transformers>=4.28"
from transformers import LlamaTokenizer
from lavis.models.blip2_models.modeling_llama import LlamaForCausalLM
logging.info(f"Using modalities {modalities}")
self.modalities = modalities
logging.info(f"Shared Qformer is set to {shared_qformer}")
self.shared_qformer = shared_qformer
logging.info(f"Video-audio interleaving is set to {joint_video_audio}")
self.joint_video_audio = joint_video_audio
logging.info(f"Using Spacy en_core_wb_sm lemmatizer is set to {apply_lemmatizer}")
self._lemmatizer = None
self.apply_lemmatizer = apply_lemmatizer
logging.info(f"Qformer text input {qformer_text_input} and LLM Text Input {llm_text_input}")
self.qformer_text_input = qformer_text_input
self.llm_text_input = llm_text_input
self.projection_only = projection_only
self.proj_dim = proj_dim
logging.info(f"Projection only setup is set to {projection_only} with dimension {proj_dim}")
for modality in self.modalities:
setattr(self, f"cached_{modality}", locals()[f"cached_{modality}"])
if locals()[f"cached_{modality}"]:
setattr(self, f"num_features_{modality}", locals()[f"num_features_{modality}"])
logging.info(f"Using cached {modality} representation with {getattr(self, f'num_features_{modality}')} embedding dim.")
### Initialize modality enoders ###
for modality in self.modalities:
modality_model = locals()[f"{modality}_model"]
modality_precision = locals()[f"{modality}_precision"]
modality_kwargs = locals()[f"{modality}_encoder_kwargs"]
modality_kwargs['load_ln_path'] = locals()[f"pretrained_shared_qformer"] if shared_qformer else \
locals()[f"pretrained_{modality}_qformer"]
setattr(self, f"projection_only_{modality}", locals()[f"projection_only_{modality}"])
setattr(self, f"projection_path_{modality}", locals()[f"projection_path_{modality}"])
modality_kwargs['load_ln_type'] = locals()[f"load_ln_type_{modality}"]
if self.projection_only or locals()[f"projection_only_{modality}"]:
modality_kwargs['load_ln_path'] = getattr(self, f"projection_path_{modality}")
modality_kwargs['load_ln_type'] = modality
setattr(self, f"load_ln_type_{modality}", locals()[f"load_ln_type_{modality}"])
setattr(self, f"pretrained_{modality}_qformer", locals()[f"pretrained_{modality}_qformer"])
modality_encoder, modality_ln = getattr(self, f"init_{modality}_encoder")(
modality_model,
precision=modality_precision,
**modality_kwargs
)
freeze_modality = locals()[f"freeze_{modality}"]
cached_modality = locals()[f"cached_{modality}"]
if cached_modality:
setattr(self, f"{modality}_encoder", modality_encoder)
setattr(self, f"{modality}_ln", modality_ln)
continue
if freeze_modality:
for name, param in modality_encoder.named_parameters():
param.requires_grad = False
modality_encoder = modality_encoder.eval()
modality_encoder.train = disabled_train
logging.info(f"freeze {modality} encoder")
setattr(self, f"{modality}_encoder", modality_encoder)
setattr(self, f"{modality}_ln", modality_ln)
##### Init QFormers ####
self.tokenizer = self.init_tokenizer(truncation_side="left") # 30523 tokens.
self.num_query_token = num_query_token
if self.shared_qformer:
logging.info(f"Initializing shared QFormer with {shared_qformer_num_features} \
number of features and query tokens of length {num_query_token}")
setattr(self, f"pretrained_shared_qformer", pretrained_shared_qformer)
setattr(self, f"load_qformer_type_shared", load_qformer_type_shared)
self.shared_Qformer, self.shared_query_tokens = self.init_Qformer(
num_query_token,
shared_qformer_num_features,
pretrained_qformer=pretrained_shared_qformer,
load_attention=load_attention_shared_qformer,
load_qformer_type=load_qformer_type_shared
)
if not qformer_text_input:
self.shared_Qformer.bert.embeddings.word_embeddings = None
self.shared_Qformer.bert.embeddings.position_embeddings = None
for layer in self.shared_Qformer.bert.encoder.layer:
layer.output = None
layer.intermediate = None
else:
self.shared_Qformer.resize_token_embeddings(len(self.tokenizer))
self.shared_Qformer.cls = None
# Map shared Qformer by reference to all modalities.
for modality in self.modalities:
setattr(self, f"{modality}_Qformer", self.shared_Qformer)
setattr(self, f"{modality}_query_tokens", self.shared_query_tokens)
encoder_proj_type=locals()[f"encoder_projection_type_{modality}"]
setattr(self, f"encoder_projection_type_{modality}", locals()[f"encoder_projection_type_{modality}"])
modality_encoder_features = getattr(self, f"{modality}_encoder").num_features
setattr(self, f"{modality}_encoder_projection", self.init_encoder_projection(modality_encoder_features, shared_qformer_num_features, pretrained_shared_qformer, encoder_proj_type))
else:
for modality in self.modalities:
if getattr(self,f"cached_{modality}"):
modality_num_features = locals()[f"num_features_{modality}"]
else:
modality_num_features = getattr(self, f"{modality}_encoder").num_features
setattr(self, f"pretrained_{modality}_qformer", locals()[f"pretrained_{modality}_qformer"])
setattr(self, f"load_qformer_type_{modality}", locals()[f"load_qformer_type_{modality}"])
setattr(self, f"projection_only_{modality}", locals()[f"projection_only_{modality}"])
setattr(self, f"projection_path_{modality}", locals()[f"projection_path_{modality}"])
if self.projection_only or locals()[f"projection_only_{modality}"]:
logging.info(f"Initializing {modality} projection")
setattr(self, f"pretrained_{modality}_qformer", False)
if modality == 'audio' and proj_dim == 1:
modality_num_features *= 256 # hack to get full beats embedding. define better.
modality_projection = self.init_vicuna_projection(
modality_num_features,
num_query_token*proj_dim,
load_projection_path=getattr(self, f"projection_path_{modality}"),
load_projection_type=modality,
projection_key=f"{modality}_projection"
)
setattr(self, f"{modality}_projection", modality_projection)
else:
logging.info(f"Initializing {modality} QFormer and query tokens of length {num_query_token}")
modality_qformer, modality_query_tokens = self.init_Qformer(
num_query_token,
modality_num_features,
pretrained_qformer=locals()[f"pretrained_{modality}_qformer"],
load_attention=locals()[f"load_attention_{modality}_qformer"],
load_qformer_type=locals()[f"load_qformer_type_{modality}"]
)
if not qformer_text_input:
modality_qformer.bert.embeddings.word_embeddings = None
modality_qformer.bert.embeddings.position_embeddings = None
for layer in modality_qformer.bert.encoder.layer:
layer.output = None
layer.intermediate = None
else:
modality_qformer.resize_token_embeddings(len(self.tokenizer))
modality_qformer.cls = None
setattr(self, f"{modality}_Qformer", modality_qformer)
setattr(self, f"{modality}_query_tokens", modality_query_tokens)
### Set up LLM ###
logging.info(f"Setting up llm model {llm_model}")
self.lora = lora
print(f"Lora is set to {self.lora}")
self.llm_tokenizer = LlamaTokenizer.from_pretrained(llm_model, use_fast=False, truncation_side="left")
self.llm_tokenizer.add_special_tokens({'pad_token': '[PAD]'})
self.llm_tokenizer.add_special_tokens({'bos_token': '</s>'})
self.llm_tokenizer.add_special_tokens({'eos_token': '</s>'})
self.llm_tokenizer.add_special_tokens({'unk_token': '</s>'})
if self.lora:
# https://github.com/lxe/llama-peft-tuner/blob/main/finetune_peft.py
self.llm_model = LlamaForCausalLM.from_pretrained(
llm_model,
load_in_8bit=True,
torch_dtype=torch.float16
)
self.llm_model.resize_token_embeddings(len(self.llm_tokenizer))
self.peft_config = LoraConfig(
task_type=TaskType.CAUSAL_LM,
r=8,
lora_alpha=32, lora_dropout=0.1,
target_modules=['q_proj', 'v_proj']
)
self.llm_model.gradient_checkpointing_enable()
self.llm_model.enable_input_require_grads()
self.llm_model.lm_head = CastOutputToFloat(self.llm_model.lm_head)
self.llm_model.config.use_cache = False # silence the warnings. Please re-enable for inference!
self.llm_hidden_size = self.llm_model.config.hidden_size
self.llm_model = get_peft_model(self.llm_model, self.peft_config)
self.lora_model = lora_model
else:
self.llm_model = LlamaForCausalLM.from_pretrained(
llm_model, torch_dtype=torch.float16
)
self.llm_model.resize_token_embeddings(len(self.llm_tokenizer))
self.llm_hidden_size = self.llm_model.config.hidden_size
for name, param in self.llm_model.named_parameters():
param.requires_grad = False
# Load LM projections
if self.shared_qformer and load_projection_shared:
qformer = getattr(self, f"shared_Qformer")
load_projection_path = locals()[f"load_projection_shared"]
if load_projection_path:
load_projection_path = locals()[f"pretrained_shared_qformer"]
load_projection_type = locals()[f"load_projection_type_shared"]
setattr(self, f"load_projection_shared", load_projection_path)
setattr(self, f"load_projection_type_shared", locals()[f"load_projection_type_shared"])
logging.info(f"Loading shared Qformer projection.")
proj = self.init_vicuna_projection(
qformer.config.hidden_size,
self.llm_hidden_size,
load_projection_path=load_projection_path
)
# Map projection by reference to all modalities.
for modality in self.modalities:
setattr(self, f"{modality}_llm_proj", proj)
else:
for modality in self.modalities:
load_projection_path = locals()[f"load_projection_{modality}"]
if load_projection_path == True:
load_projection_path = locals()[f"pretrained_{modality}_qformer"]
load_projection_type = locals()[f"load_projection_type_{modality}"]
setattr(self, f"load_projection_{modality}", load_projection_path)
setattr(self, f"load_projection_type_{modality}", load_projection_type)
if self.projection_only or getattr(self, f"projection_only_{modality}"):
proj = self.init_vicuna_projection(
self.num_query_token if proj_dim==1 else proj_dim,
self.num_query_token*self.llm_hidden_size if proj_dim==1 else self.llm_hidden_size,
load_projection_path=getattr(self, f"projection_path_{modality}"),
load_projection_type=load_projection_type,
)
else:
qformer = getattr(self, f"{modality}_Qformer")
proj = self.init_vicuna_projection(
qformer.config.hidden_size,
self.llm_hidden_size,
load_projection_path=load_projection_path,
load_projection_type=load_projection_type
)
setattr(self, f"{modality}_llm_proj", proj)
self.clean_tokenization = clean_tokenization
logging.info(f"Clean tokenization is set to {self.clean_tokenization}")
self.max_txt_len = max_txt_len
self.max_output_txt_len = max_output_txt_len
self.prompt = prompt
self.prefix = prefix
if self.prefix:
self.tokenized_prefix = self.llm_tokenizer(self.prefix, return_tensors="pt")
self.postfix = postfix
if type(self.postfix) != str or not self.postfix:
self.postfix = ""
logging.info(f"Using prefix set to {self.prefix} and postfix set to {self.postfix}.")
self.use_cues = use_cues
logging.info(f"Using cues set to {self.use_cues}.")
if self.use_cues:
logging.info(f"Modality to cue {Blip2VicunaXInstruct.MODALITY_TO_CUE}")
self.tokenized_cue = {}
self.emb_cue = {}
self.att_cue = {}
for modality in self.modalities:
if self.clean_tokenization:
Blip2VicunaXInstruct.MODALITY_TO_CUE[modality] = Blip2VicunaXInstruct.MODALITY_TO_CUE[modality].lstrip()
self.tokenized_cue[modality] = self.llm_tokenizer(Blip2VicunaXInstruct.MODALITY_TO_CUE[modality], return_tensors="pt")
self.emb_cue[modality] = self.llm_model.get_input_embeddings()(self.tokenized_cue[modality].input_ids.to(self.device))
self.att_cue[modality] = self.tokenized_cue[modality].attention_mask.to(self.device)
## generation parameters
self.use_caption=use_caption
self.use_describe=use_describe
self.predict_with_gen=predict_with_gen
self.format_candidates_prompt=format_candidates_prompt
self.special_qformer_input_prompt=special_qformer_input_prompt
self.enumerate_inputs=enumerate_inputs
self.add_space=add_space
self.remove_start=remove_start
if self.projection_only:
self.qformer_text_input=False
def concat_text_input_output(self, input_ids, input_atts, output_ids, output_atts):
input_part_targets_len = []
llm_tokens = {"input_ids": [], "attention_mask": []}
for i in range(input_ids.size(0)):
this_input_ones = input_atts[i].sum()
input_part_targets_len.append(this_input_ones)
llm_tokens['input_ids'].append(
torch.cat([
input_ids[i][:this_input_ones],
output_ids[i][1:],
input_ids[i][this_input_ones:]
])
)
llm_tokens['attention_mask'].append(
torch.cat([
input_atts[i][:this_input_ones],
output_atts[i][1:],
input_atts[i][this_input_ones:]
])
)
llm_tokens['input_ids'] = torch.stack(llm_tokens['input_ids'])
llm_tokens['attention_mask'] = torch.stack(llm_tokens['attention_mask'])
return llm_tokens, input_part_targets_len
def forward(self, samples):
# print('-----------------')
# print(samples["text_input"])
# print(samples["text_output"])
# print('-----------------')
if samples == None or samples == {} or not any([modality in samples for modality in self.modalities]):
return {"loss": torch.tensor(0.0)}
random.shuffle(self.modalities)
curr_modalities = [modality for modality in self.modalities if modality in samples]
excess_modalities = [modality for modality in self.modalities if modality not in curr_modalities]
# disable gradient in excess modalities
dummy_loss = 0.
for modality in excess_modalities:
if self.shared_qformer:
for name, param in getattr(self, f"{modality}_encoder_projection").named_parameters():
# param.requires_grad = False
dummy_loss += param.sum()*0.
for name, param in getattr(self,f"{modality}_ln").named_parameters():
# param.requires_grad = False
dummy_loss += param.sum()*0.
dummy_loss += getattr(self, f"{modality}_query_tokens").sum()*0.
for name, param in getattr(self, f'{modality}_Qformer').named_parameters():
# param.requires_grad = False
dummy_loss += param.sum()*0.
for name, param in getattr(self, f'{modality}_llm_proj').named_parameters():
# param.requires_grad = False
dummy_loss += param.sum()*0.
embeds = {}
query_tokens = {}
data_atts = {}
for modality in curr_modalities:
data = samples[modality]
ln = getattr(self, f"{modality}_ln")
encoder = getattr(self, f"{modality}_encoder")
if modality == "video" and self.video_enc_name in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(2)):
this_frame = data[:,:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][-1] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
# B, Token Size, LM EMB
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(data.size(0), -1, -1)
elif modality == 'audio' and self.audio_enc_name in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(1)):
this_frame = data[:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][j] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
# B, Token Size, LM EMB
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(data.size(0), -1, -1)
else:
with self.maybe_autocast():
embeds[modality] = ln(encoder(data))
if len(embeds[modality].size()) == 2:
# B, C, D
embeds[modality] = embeds[modality].unsqueeze(1)
# B, C
if self.shared_qformer:
embeds[modality] = getattr(self, f"{modality}_encoder_projection")(embeds[modality])
data_atts[modality] = torch.ones(embeds[modality].size()[:-1], dtype=torch.long).to(self.device)
# B, Token Size, LM EMB
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(embeds[modality].shape[0], -1, -1)
query_outputs = {}
if self.qformer_text_input:
text_Qformer = self.tokenizer(
samples["text_input"] if not self.special_qformer_input_prompt else self.special_qformer_input_prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
Qformer_atts = {}
query_atts = {}
for modality in curr_modalities:
# B, Token Size
query_atts[modality] = torch.ones(query_tokens[modality].size()[:-1], dtype=torch.long).to(self.device)
# B, Token Size + Inp Size
Qformer_atts[modality] = torch.cat([query_atts[modality],text_Qformer.attention_mask],dim=1)
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num)]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num, self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids.repeat(num, 1),
attention_mask=Qformer_atts[modality].repeat(num, 1),
query_embeds=query_tokens[modality].repeat(num, 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids,
attention_mask=Qformer_atts[modality],
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32),
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
else:
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num)]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num, self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality].repeat(num, 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
bs = embeds[modality].shape[0]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32), # pc data is floa16.
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
inputs_llm = {}
atts_llm = {}
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
# num*bs, num query tokens, llm emb size
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].unsqueeze(1)).reshape(bs*num, self.num_query_token, -1)
else:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality]).reshape(bs*num, self.num_query_token, -1)
inputs_llm[modality] = inputs_llm[modality].reshape(bs, num, self.num_query_token, -1).view(bs, num*self.num_query_token, -1)
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
continue
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].last_hidden_state[:,:query_tokens[modality].size(1),:])
# bs, num, num query tokens, llm emb size -> bs, num*num query tokens, llm emb size
inputs_llm[modality] = inputs_llm[modality].reshape(bs, num, self.num_query_token, -1).view(bs, num*self.num_query_token, -1)
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
else:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim == 1:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].mean(-1)).reshape(bs, self.num_query_token, -1)
else:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].reshape(bs, self.num_query_token, -1))
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
continue
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].last_hidden_state[:,:query_tokens[modality].size(1),:])
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
self.llm_tokenizer.padding_side = "right"
self.llm_tokenizer.truncation_side = 'left'
if self.llm_text_input:
text_input_tokens = self.llm_tokenizer(
[f"{t}{self.postfix}" for t in samples['text_input']] if self.postfix else samples['text_input'],
return_tensors="pt",
padding="longest",
truncation=True,
max_length=self.max_txt_len,
add_special_tokens= not self.clean_tokenization
).to(self.device)
self.llm_tokenizer.truncation_side = 'right'
text_output_tokens = self.llm_tokenizer(
[t + self.llm_tokenizer.eos_token for t in samples['text_output']],
return_tensors="pt",
padding="longest",
truncation=True,
max_length=self.max_output_txt_len,
).to(self.device)
if self.llm_text_input:
llm_tokens, input_part_targets_len = self.concat_text_input_output(
text_input_tokens.input_ids,
text_input_tokens.attention_mask,
text_output_tokens.input_ids,
text_output_tokens.attention_mask,
)
else:
llm_tokens = text_output_tokens
input_part_targets_len = [0 for _ in range(llm_tokens['input_ids'].shape[0])] # input length is 0
# do not apply loss to the padding
targets = llm_tokens['input_ids'].masked_fill(
llm_tokens['input_ids'] == self.llm_tokenizer.pad_token_id, -100
)
# do not apply loss to the text input (i.e., instruction)
for i, l in enumerate(input_part_targets_len):
targets[i][:l] = -100
inputs_embeds = self.llm_model.get_input_embeddings()(llm_tokens['input_ids'])
bs = inputs_embeds.shape[0]
att_list = []
inp_list = []
if self.prefix:
att_list = [self.tokenized_prefix.attention_mask.repeat(bs, 1).to(self.device)]
inp_list = [self.llm_model.get_input_embeddings()(self.tokenized_prefix.input_ids.to(self.device)).repeat(bs, 1, 1)]
for modality in curr_modalities:
if self.use_cues:
if self.prefix and self.clean_tokenization:
att_list.extend([self.att_cue[modality][:,1:].repeat(bs, 1).to(self.device), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality][:,1:].repeat(bs, 1, 1).to(self.device), inputs_llm[modality]])
att_list.extend([self.att_cue[modality].repeat(bs, 1).to(self.device), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality].repeat(bs, 1, 1).to(self.device), inputs_llm[modality]])
else:
att_list.extend([atts_llm[modality]])
inp_list.extend([inputs_llm[modality]])
# do not apply loss to the query tokens
empty_targets = (
torch.ones(torch.cat(att_list, dim=1).size(), dtype=torch.long).to(self.device).fill_(-100)
)
# append llm prompt + output to queries
att_list.append(llm_tokens['attention_mask'])
inp_list.append(inputs_embeds)
inputs_embeds = torch.cat(inp_list, dim=1)
attention_mask = torch.cat(att_list, dim=1)
targets = torch.cat([empty_targets, targets], dim=1)
with self.maybe_autocast():
outputs = self.llm_model(
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
return_dict=True,
labels=targets,
)
loss = dummy_loss+outputs.loss
return {"loss": loss}
def init_image_encoder(self,
model_name,
precision,
**kwargs):
load_ln_path = kwargs['load_ln_path']
del kwargs['load_ln_path']
load_ln_type=kwargs['load_ln_type']
del kwargs['load_ln_type']
encoder, _ = super().init_vision_encoder(model_name, kwargs['image_size'], kwargs['drop_path_rate'], kwargs['use_grad_checkpoint'], precision)
ln = self.init_ln(encoder.num_features, load_ln_path=load_ln_path, load_ln_type=load_ln_type)
return encoder, ln
def init_pc_encoder(
self, model_name, precision, **kwargs
):
assert model_name in [
"ulip1_pointbert",
"ulip2_pointbert",
"ulip_shapenet",
"ulip_objaverse",
"objaverse_shapenet_k_1",
"ulip2_scaledup"
""
], "pc model must be in [ulip1_pointbert,ulip2_pointbert]"
load_ln_path = kwargs['load_ln_path']
del kwargs['load_ln_path']
load_ln_type=kwargs['load_ln_type']
del kwargs['load_ln_type']
if model_name == "ulip2_pointbert":
pc_encoder = ULIP_PointBERT(ulip_v=2)
elif model_name == "ulip_shapenet":
pc_encoder = ULIP_PointBERT(ulip_v="shapenet")
elif model_name == "ulip_objaverse":
pc_encoder = ULIP_PointBERT(ulip_v="objaverse_k_1")
elif model_name == "objaverse_shapenet_k_1":
pc_encoder = ULIP_PointBERT(ulip_v="objaverse_shapenet_k_1")
elif model_name == "ulip2_scaledup":
pc_encoder = ULIP_PointBERT(ulip_v="ulip2_scaledup")
else:
pc_encoder = ULIP_PointBERT(ulip_v=1)
ln_pc = self.init_ln(pc_encoder.num_features, load_ln_path=load_ln_path, load_ln_type=load_ln_type)
self.pc_enc_name = model_name
return pc_encoder, ln_pc
def init_video_encoder(
self, model_name, precision, **kwargs
):
assert model_name in [
"eva_clip_g",
"eva2_clip_L",
"clip_L",
], "video_model must be in [eva_clip_g, eva2_clip_L, clip_L]"
if model_name in ["eva_clip_g","eva2_clip_L","clip_L",]:
video_encoder, ln_video = self.init_image_encoder(
model_name, precision=precision, **kwargs
)
self.video_enc_name = model_name
return video_encoder, ln_video
def init_audio_encoder(
self, model_name, precision, **kwargs
):
assert model_name in [
'beats'
], "audio model must be in [beats]"
load_ln_path = kwargs['load_ln_path']
del kwargs['load_ln_path']
load_ln_type=kwargs['load_ln_type']
del kwargs['load_ln_type']
if "beats" in model_name:
from lavis.models.beats_encoder import BeatsEncoder
if self.cached_audio:
audio_encoder = lambda x: x
ln_audio = self.init_ln(768, load_ln_path=load_ln_path, load_ln_type=load_ln_type)
else:
audio_encoder = BeatsEncoder(**kwargs)
if not self.cached_audio:
ln_audio = self.init_ln(audio_encoder.num_features, load_ln_path=load_ln_path, load_ln_type=load_ln_type)
self.audio_enc_name = model_name
return audio_encoder, ln_audio
@torch.no_grad()
def get_query_outputs(
self,
samples
):
if samples == None or samples == {}:
return
curr_modalities = [modality for modality in self.modalities if modality in samples]
if len(curr_modalities) == 0:
print("Model modalities do not match sample modalities.")
return
# get batch size
bs = None
for modality in curr_modalities:
data = samples[modality]
bs = data.size(0)
break
if "prompt" in samples.keys():
prompt = samples["prompt"]
elif "text_input" in samples.keys():
prompt = samples["text_input"]
else:
prompt = self.prompt
if isinstance(prompt, str):
prompt = [prompt] * bs
else:
assert len(prompt) == bs, "The number of prompts must be equal to the batch size."
embeds = {}
query_tokens = {}
data_atts = {}
for modality in curr_modalities:
data = samples[modality]
ln = getattr(self, f"{modality}_ln")
encoder = getattr(self, f"{modality}_encoder")
if modality == "video" and self.video_enc_name in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(2)):
this_frame = data[:,:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][-1] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
# B, Token Size, LM EMB
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(data.size(0), -1, -1)
elif modality == 'audio' and self.audio_enc_name in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(1)):
this_frame = data[:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][j] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
# B, Token Size, LM EMB
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(data.size(0), -1, -1)
else:
with self.maybe_autocast():
embeds[modality] = ln(encoder(data))
if len(embeds[modality].size()) == 2:
# B, C, D
embeds[modality] = embeds[modality].unsqueeze(1)
# B, C
if self.shared_qformer:
embeds[modality] = getattr(self, f"{modality}_encoder_projection")(embeds[modality])
data_atts[modality] = torch.ones(embeds[modality].size()[:-1], dtype=torch.long).to(self.device)
# B, Token Size, LM EMB
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(embeds[modality].shape[0], -1, -1)
query_outputs = {}
if self.qformer_text_input:
text_Qformer = self.tokenizer(
prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
Qformer_atts = {}
query_atts = {}
num = {}
for modality in curr_modalities:
# B, Token Size
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_atts[modality] = torch.ones(query_tokens[modality].size()[:-1], dtype=torch.long).to(self.device)
# B, Token Size + Inp Size
Qformer_atts[modality] = torch.cat([query_atts[modality],text_Qformer.attention_mask],dim=1)
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num[modality] = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num[modality])]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num[modality], self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids.repeat(num[modality], 1),
attention_mask=Qformer_atts[modality].repeat(num[modality], 1),
query_embeds=query_tokens[modality].repeat(num[modality], 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids,
attention_mask=Qformer_atts[modality],
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32),
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
else:
num = {}
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num[modality] = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num[modality])]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num, self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality].repeat(num[modality], 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32), # pc data is floa16.
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[f'llm_proj_{modality}'] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].unsqueeze(1)).reshape(bs*num, self.num_query_token, -1)
else:
query_outputs[f'llm_proj_{modality}'] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality]).reshape(bs*num, self.num_query_token, -1)
query_outputs[f'llm_proj_{modality}'] = query_outputs[f'llm_proj_{modality}'].reshape(bs, num[modality], self.num_query_token, -1).contiguous().view(bs, num[modality]*self.num_query_token, -1)
query_outputs[modality] = query_outputs[modality].view(bs, num[modality]*self.num_query_token, -1)
else:
query_outputs[f'llm_proj_{modality}'] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality]['last_hidden_state'][:,:query_tokens[modality].size(1),:]).contiguous().view(bs, num[modality]*self.num_query_token, -1)
query_outputs[modality] = query_outputs[modality]['last_hidden_state'][:,:query_tokens[modality].size(1),:].contiguous().view(bs, num[modality]*self.num_query_token, -1)
else:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim == 1:
query_outputs[f'llm_proj_{modality}'] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].mean(-1)).reshape(bs, self.num_query_token, -1)
else:
query_outputs[f'llm_proj_{modality}']= getattr(self, f"{modality}_llm_proj")(query_outputs[modality].reshape(bs, self.num_query_token, -1))
else:
query_outputs[modality] = query_outputs[modality].last_hidden_state[:,:query_tokens[modality].size(1),:]
query_outputs[f'llm_proj_{modality}'] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality])
for modality in curr_modalities:
query_outputs[f'embeds_{modality}'] = embeds[modality]
return query_outputs
@torch.no_grad()
def generate(
self,
samples,
use_nucleus_sampling=False,
num_beams=5,
max_length=256,
min_length=1,
top_p=0.9,
repetition_penalty=1.5,
length_penalty=1,
num_captions=1,
temperature=1,
special_qformer_input_prompt=False
):
self.llm_tokenizer.padding_side = "left"
if samples == None or samples == {}:
return
if 'modalities' in samples:
curr_modalities = samples['modalities'][0] if isinstance(samples['modalities'][0], list) else samples['modalities']
elif self.joint_video_audio:
curr_modalities = ["video", "audio"]
else:
curr_modalities = [modality for modality in self.modalities if modality in samples]
if len(curr_modalities) == 0:
print("Model modalities do not match sample modalities.")
return
# get batch size
bs = None
for modality in curr_modalities:
data = samples[modality]
if isinstance(data, torch.Tensor):
bs = data.size(0)
else:
bs = len(data)
break
if "prompt" in samples.keys():
prompt = samples["prompt"]
elif self.prompt and 'text_input' in samples and '{}' in self.prompt:
prompt = [self.prompt.format(t) for t in samples["text_input"]]
elif "text_input" in samples.keys():
prompt = samples["text_input"]
else:
prompt = self.prompt
if isinstance(prompt, str):
prompt = [prompt] * bs
else:
assert len(prompt) == bs, "The number of prompts must be equal to the batch size."
# For TextCaps
if "ocr_tokens" in samples.keys() and "{}" in prompt[0]:
prompt = [p.format(', '.join(samples['ocr_tokens'][i][:30])) for i, p in enumerate(prompt)]
if 'discrn' in samples and self.use_caption: ## discriminatory reasoning
if self.postfix:
prompt = [f'{t}{self.postfix}' for t in prompt]
if self.enumerate_inputs:
prompt = [f'{self.prefix}(a){Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][0]] if self.use_cues else " "}{samples["baseline_captions"][i][0]} (b){Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][1]] if self.use_cues else " "}{samples["baseline_captions"][i][1]} {prompt[i]}' for i in range(bs)]
else:
prompt = [f'{self.prefix}{Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][0]]}{samples["baseline_captions"][i][0] if self.use_cues else " "}{Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][1]] if self.use_cues else " "}{samples["baseline_captions"][i][1]} {prompt[i]}' for i in range(bs)]
llm_tokens = self.llm_tokenizer(
prompt,
padding="longest",
return_tensors="pt"
).to(self.device)
inputs_embeds = self.llm_model.get_input_embeddings()(llm_tokens.input_ids)
with self.maybe_autocast():
outputs = self.llm_model.generate(
inputs_embeds=inputs_embeds,
attention_mask=llm_tokens.attention_mask,
do_sample=use_nucleus_sampling,
top_p=top_p,
temperature=temperature,
num_beams=num_beams,
max_length=max_length,
min_length=min_length,
repetition_penalty=repetition_penalty,
length_penalty=length_penalty,
num_return_sequences=num_captions,
)
outputs[outputs == 0] = 2 # convert output id 0 to 2 (eos_token_id)
output_text = self.llm_tokenizer.batch_decode(outputs, skip_special_tokens=True)
output_text = [o.strip() for o in output_text]
# print(output)
return output_text
query_tokens = {}
for modality in curr_modalities:
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(bs, -1, -1)
if self.qformer_text_input:
if self.special_qformer_input_prompt or special_qformer_input_prompt:
qformer_prompt = special_qformer_input_prompt if special_qformer_input_prompt else self.special_qformer_input_prompt
qformer_prompt = [qformer_prompt] * len(prompt)
if "text_input" in samples.keys():
if type(samples["text_input"][0]) == list:
qformer_prompt = [qformer_prompt[i].format(*samples["text_input"][i]) for i in range(len(qformer_prompt))]
else:
qformer_prompt = [qformer_prompt[i].format(samples["text_input"][i]) for i in range(len(qformer_prompt))]
text_Qformer = self.tokenizer(
qformer_prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
elif self.use_describe:
modality2prompt = {
"video": "a short description of the video",
"audio": "an audio that shows",
"image": "a short image caption",
"pc": "a 3d model of"
}
qformer_prompt = [modality2prompt[modality] for _ in samples['text_input']]
text_Qformer = self.tokenizer(
qformer_prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
else:
text_Qformer = self.tokenizer(
prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
Qformer_atts = {}
query_atts = {}
for modality in curr_modalities:
if not getattr(self, f"projection_only_{modality}"):
# B, Token Size
query_atts[modality] = torch.ones(query_tokens[modality].size()[:-1], dtype=torch.long).to(self.device)
# B, Token Size + Inp Size
Qformer_atts[modality] = torch.cat([query_atts[modality],text_Qformer.attention_mask],dim=1)
embeds = {}
data_atts = {}
for modality in curr_modalities:
data = samples[modality]
ln = getattr(self, f"{modality}_ln")
encoder = getattr(self, f"{modality}_encoder")
if modality == "video" and "clip" in self.video_enc_name:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(2)):
this_frame = data[:,:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][j] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
elif modality == 'audio' and 'beats' in self.audio_enc_name:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(1)):
this_frame = data[:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][j] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
else:
with self.maybe_autocast():
embeds[modality] = ln(encoder(data))
if len(embeds[modality].size()) == 2:
embeds[modality] = embeds[modality].unsqueeze(1)
if self.shared_qformer:
with self.maybe_autocast():
embeds[modality] = getattr(self, f"{modality}_encoder_projection")(embeds[modality])
data_atts[modality] = torch.ones(embeds[modality].size()[:-1], dtype=torch.long).to(self.device)
query_outputs = {}
num = {}
if self.qformer_text_input:
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num[modality] = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num[modality])]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num[modality], self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids.repeat(num[modality], 1),
attention_mask=Qformer_atts[modality].repeat(num[modality], 1),
query_embeds=query_tokens[modality].repeat(num[modality], 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
bs = embeds[modality].shape[0]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids,
attention_mask=Qformer_atts[modality],
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32),
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
else:
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num[modality] = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num[modality])]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num[modality], self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality].repeat(num[modality], 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
bs = embeds[modality].shape[0]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
with self.maybe_autocast():
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32),
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
inputs_llm = {}
atts_llm = {}
enumeration = {}
for i,modality in enumerate(curr_modalities):
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].unsqueeze(1)).reshape(bs*num[modality], self.num_query_token, -1)
else:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].reshape(bs*num, self.num_query_token, -1))
inputs_llm[modality] = inputs_llm[modality].reshape(bs, num[modality], self.num_query_token, -1).view(bs, num[modality]*self.num_query_token, -1)
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
continue
# num*bs, num query tokens, llm emb size
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].last_hidden_state[:,:query_tokens[modality].size(1),:])
# bs, num, num query tokens, llm emb size -> bs, num*num query tokens, llm emb size
inputs_llm[modality] = inputs_llm[modality].reshape(bs, num[modality], self.num_query_token, -1).view(bs, num[modality]*self.num_query_token, -1)
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
else:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim == 1:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].mean(-1)).reshape(bs, self.num_query_token, -1)
else:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].reshape(bs, self.num_query_token, -1))
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
continue
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality]['last_hidden_state'][:,:query_tokens[modality].size(1),:])
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
if self.enumerate_inputs:
enumeration[modality] = self.llm_tokenizer(
[f"{'' if i == 0 else ' '}({chr(97+i)}) " for _ in prompt],
return_tensors="pt",
add_special_tokens=False if (i!= 0 or self.prefix) else True
).to(self.device)
## remove trailing whitespace
prompt = [p.strip() for p in prompt]
if 'dialog' in samples:
llm_tokens = self.llm_tokenizer(
[f"{d} {p}" if d else p for d, p in zip(samples['dialog'], prompt)],
padding="longest",
return_tensors="pt",
add_special_tokens= not self.clean_tokenization
).to(self.device)
else:
llm_tokens = self.llm_tokenizer(
[f"{p}{self.postfix}" for p in prompt] if self.postfix else prompt,
padding="longest",
return_tensors="pt",
add_special_tokens= not self.clean_tokenization
).to(self.device)
bs = llm_tokens.input_ids.shape[0]
att_list = []
inp_list = []
if self.prefix:
att_list = [self.tokenized_prefix.attention_mask.repeat(bs, 1).to(self.device)]
inp_list = [self.llm_model.get_input_embeddings()(self.tokenized_prefix.input_ids.to(self.device)).repeat(bs, 1, 1)]
if self.joint_video_audio:
for pos in range(num['video']):
if self.enumerate_inputs:
enumeration_pos = self.llm_tokenizer(
[f"{'' if pos == 0 else ' '}({chr(97+pos)}) " for _ in prompt],
return_tensors="pt",
add_special_tokens=False if (pos!= 0 or self.prefix) else True
).to(self.device)
enumeration_inputs_llm = self.llm_model.get_input_embeddings()(enumeration_pos.input_ids)
enumeration_atts_llm = enumeration_pos.attention_mask.to(self.device)
inp_list.extend([enumeration_inputs_llm])
att_list.extend([enumeration_atts_llm])
if self.use_cues:
for modality in ['video', 'audio']:
if self.clean_tokenization:
if self.prefix or pos > 1 or self.enumerate_inputs or modality == 'audio':
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask[:,1:]).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality].view(bs, num[modality], self.num_query_token)[:, pos, :]])
inp_list.extend([self.emb_cue[modality][:,1:].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality].view(bs, num[modality], self.num_query_token, -1)[:, pos, :, :]])
continue
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality].view(bs, num[modality], self.num_query_token)[:, pos, :]])
inp_list.extend([self.emb_cue[modality].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality].view(bs, num[modality], self.num_query_token, -1)[:, pos, :, :]])
else:
att_list.extend([atts_llm[modality].view(bs, num[modality], self.num_query_token)[:, pos, :]])
inp_list.extend([inputs_llm[modality].view(bs, num[modality], self.num_query_token, -1)[:, pos, :, :]])
else:
for modality in curr_modalities:
if self.enumerate_inputs:
enumeration_inputs_llm = self.llm_model.get_input_embeddings()(enumeration[modality].input_ids.to(self.device))
enumeration_atts_llm = enumeration[modality].attention_mask.to(self.device)
inp_list.extend([enumeration_inputs_llm])
att_list.extend([enumeration_atts_llm])
if self.use_cues:
if self.clean_tokenization or self.remove_start:
if (modality==curr_modalities[0] and not (self.prefix or self.enumerate_inputs)):
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality]])
else:
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask[:,1:]).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality][:,1:].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality]])
else:
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality]])
else:
att_list.extend([atts_llm[modality]])
inp_list.extend([inputs_llm[modality]])
if self.add_space:
space_tok = self.llm_tokenizer(
[f" " for _ in prompt],
return_tensors="pt",
add_special_tokens=False
)
space_inputs_llm = self.llm_model.get_input_embeddings()(space_tok.input_ids.to(self.device))
space_atts_llm = space_tok.attention_mask.to(self.device)
inp_list.extend([space_inputs_llm])
att_list.extend([space_atts_llm])
att_list.append(llm_tokens.attention_mask)
inputs_embeds = self.llm_model.get_input_embeddings()(llm_tokens.input_ids)
inp_list.append(inputs_embeds)
attention_mask = torch.cat(att_list, dim=1)
inputs_embeds = torch.cat(inp_list, dim=1)
with self.maybe_autocast():
outputs = self.llm_model.generate(
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
do_sample=use_nucleus_sampling,
top_p=top_p,
temperature=temperature,
num_beams=num_beams,
max_length=max_length,
min_length=min_length,
repetition_penalty=repetition_penalty,
length_penalty=length_penalty,
num_return_sequences=num_captions,
)
outputs[outputs == 0] = 2 # convert output id 0 to 2 (eos_token_id)
output_text = self.llm_tokenizer.batch_decode(outputs, skip_special_tokens=True)
output_text = [o.strip() for o in output_text]
return output_text
@torch.no_grad()
def predict_answers(
self,
samples,
num_beams=5,
inference_method="generate",
max_len=10,
min_len=1,
num_ans_candidates=128,
answer_list=None,
prompt="",
length_penalty=-1,
**kwargs
):
if samples == None or samples == {}:
return None
# get batch size
bs = None
if 'modalities' in samples:
curr_modalities = samples['modalities'][0] if isinstance(samples['modalities'][0], list) else samples['modalities']
else:
curr_modalities = [modality for modality in self.modalities if modality in samples]
for modality in curr_modalities:
data = samples[modality]
if isinstance(data, torch.Tensor):
bs = data.size(0)
else:
bs = len(data)
break
if "text_input" not in samples:
samples["text_input"] = self.prompt
if isinstance(samples["text_input"], str):
samples["text_input"] = [samples["text_input"]] * bs
text_input = samples['text_input']
if not prompt and self.prompt:
prompt=self.prompt
if prompt:
if prompt.count("{}") == 2:
if 'ocr_tokens' in samples:
text_input = [
prompt.format(', '.join(samples['ocr_tokens'][i][:30]), samples["text_input"][i])
for i in range(len(samples["text_input"]))]
elif 'choices' in samples:
text_input = []
for i in range(len(samples["text_input"])):
this_choices = [f"({string.ascii_lowercase[j]}) {ch}" for j, ch in enumerate(samples["choices"][i])]
this_choices = " ".join(this_choices)
text_input.append(prompt.format(samples["text_input"][i], this_choices))
else:
text_input = [prompt.format(question) for question in samples["text_input"]]
samples["prompt"] = text_input
if 'discrn' in samples and self.use_caption: ## discriminatory reasoning
self.llm_tokenizer.padding_side = "left"
text_input = samples['text_input'] if 'prompt' not in samples else samples['prompt']
if self.postfix:
text_input = [f'{t}{self.postfix}' for t in text_input]
if self.enumerate_inputs:
prompt = [f'{self.prefix}(a){Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][0]] if self.use_cues else " "}{samples["baseline_captions"][i][0]} (b){Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][1]] if self.use_cues else " "}{samples["baseline_captions"][i][1]} {text_input[i]}' for i in range(bs)]
else:
prompt = [f'{self.prefix}{Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][0]]}{samples["baseline_captions"][i][0] if self.use_cues else " "}{Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][1]] if self.use_cues else " "}{samples["baseline_captions"][i][1]} {text_input[i]}' for i in range(bs)]
llm_tokens = self.llm_tokenizer(
prompt,
padding="longest",
return_tensors="pt"
).to(self.device)
with self.maybe_autocast():
outputs = self.llm_model.generate(
inputs_embeds=self.llm_model.get_input_embeddings()(llm_tokens.input_ids),
attention_mask=llm_tokens.attention_mask,
do_sample=False,
num_beams=num_beams,
max_length=max_len,
min_length=min_len,
repetition_penalty=1.5,
# eos_token_id=self.eos_token_id,
length_penalty=length_penalty,
)
outputs[outputs == 0] = 2 # convert output id 0 to 2 (eos_token_id)
output_text = self.llm_tokenizer.batch_decode(outputs, skip_special_tokens=True)
return output_text
output_text = self.generate(
samples,
num_beams=num_beams,
max_length=max_len,
min_length=min_len,
length_penalty=length_penalty
)
if "apply_lemmatizer" in samples.keys() and samples["apply_lemmatizer"]:
output_text = self._lemmatize(output_text)
#vizwiz
output_text = [o if o != "" else "unanswerable" for o in output_text]
return output_text
def predict(
self,
samples,
candidates=None,
n_segments=1,
max_length=10,
min_length=1,
length_penalty=-1.,
special_qformer_input_prompt=False
):
self.llm_tokenizer.padding_side = "left"
if candidates == None:
candidates = self.candidates
else:
self.candidates = candidates # for the output targets.
if self.predict_with_gen:
output = self.generate(samples,max_length=max_length,min_length=min_length,length_penalty=length_penalty)
result = []
for text in output:
text = BlipCaptionProcessor().pre_caption(text)
pred_label = "" # default to an empty string
for cand in candidates:
cand = BlipCaptionProcessor().pre_caption(cand)
if cand in text.split(" "):
pred_label = cand
break # stop as soon as we find a match
result.append(pred_label)
return {"predictions":result, "target": samples["label"]}
# If candidates is a list of lists, each sample has its candidates, then we need to iterate one by one
if type(candidates[0]) == list:
results = []
for i in range(samples["image"].size(0)):
this_sample = {
"image": samples["image"][i].unsqueeze(0),
"prompt": samples["prompt"],
}
if "text_input" in samples.keys():
this_sample["text_input"] = [samples["text_input"][i]]
if 'context' in samples.keys():
this_sample['context'] = [samples["context"][i]]
if 'history' in samples.keys():
this_sample['history'] = [samples["history"][i]]
if 'caption' in samples.keys():
this_sample['caption'] = [samples["caption"][i]]
this_result = self._predict_class(this_sample, candidates[i], n_segments, special_qformer_input_prompt)
results.append(this_result)
try:
results = torch.cat(results, dim=0)
except:
results = [res.tolist()[0] for res in results]
return results
return self._predict_class(samples, candidates, n_segments, special_qformer_input_prompt)
def _predict_class(
self,
samples,
candidates,
n_segments=1,
special_qformer_input_prompt=False,
):
if list(samples.keys()) == []:
return None
if "prompt" in samples:
prompt = samples["prompt"]
else:
prompt = self.prompt
candidates = [self.format_candidates_prompt.format(c) for c in candidates]
if 'modalities' in samples:
curr_modalities = samples['modalities'][0] if isinstance(samples['modalities'][0], list) else samples['modalities']
else:
curr_modalities = [modality for modality in self.modalities if modality in samples]
# get batch size
for modality in curr_modalities:
data = samples[modality]
if isinstance(data, torch.Tensor):
bs = data.size(0)
else:
bs = len(data)
break
if isinstance(prompt, str):
prompt = [prompt] * bs
else:
assert len(prompt) == bs, "The number of prompts must be equal to the batch size."
if "text_input" in samples.keys():
if type(samples["text_input"][0]) == list:
prompt = [prompt[i].format(*samples["text_input"][i]) for i in range(len(prompt))]
else:
prompt = [prompt[i].format(samples["text_input"][i]) for i in range(len(prompt))]
# scienceqa
if 'context' in samples.keys() and samples['context'] != '':
prompt = [f'context: {samples["context"][i]}. {prompt[i]}' for i in range(len(prompt))]
# visual dialog
if 'history' in samples.keys() and samples['history'][0] != '':
prompt = [f'dialog history: {samples["history"][i]}\n{prompt[i]}' for i in range(len(prompt))]
if 'caption' in samples.keys() and samples['caption'][0] != '':
prompt = [f'This image has the caption "{samples["caption"][i]}". {prompt[i]}' for i in range(len(prompt))]
if 'discrn' in samples and self.use_caption: ## discriminatory reasoning
if self.postfix:
prompt = [f'{p}{self.postfix}' for p in prompt]
if self.enumerate_inputs:
prompt = [f'{self.prefix}(a){Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][0]] if self.use_cues else " "}{samples["baseline_captions"][i][0]} (b){Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][1]] if self.use_cues else " "}{samples["baseline_captions"][i][1]} {prompt[i]}' for i in range(bs)]
else:
prompt = [f'{self.prefix}{Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][0]]}{samples["baseline_captions"][i][0] if self.use_cues else " "}{Blip2VicunaXInstruct.MODALITY_TO_CUE[samples["modalities"][i][1]] if self.use_cues else " "}{samples["baseline_captions"][i][1]} {prompt[i]}' for i in range(bs)]
text_input_tokens = self.llm_tokenizer(
prompt,
padding="longest",
return_tensors="pt"
).to(self.device)
else:
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
query_tokens = {}
for modality in self.modalities:
if modality not in samples:
continue
query_tokens[modality] = getattr(self, f"{modality}_query_tokens").expand(bs, -1, -1)
if self.qformer_text_input:
if self.special_qformer_input_prompt or special_qformer_input_prompt:
qformer_prompt = special_qformer_input_prompt if special_qformer_input_prompt else self.special_qformer_input_prompt
qformer_prompt = [qformer_prompt] * len(prompt)
if "text_input" in samples.keys():
if type(samples["text_input"][0]) == list:
qformer_prompt = [qformer_prompt[i].format(*samples["text_input"][i]) for i in range(len(qformer_prompt))]
else:
qformer_prompt = [qformer_prompt[i].format(samples["text_input"][i]) for i in range(len(qformer_prompt))]
text_Qformer = self.tokenizer(
qformer_prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
elif self.use_describe:
modality2prompt = {
"video": "a short description of the video",
"audio": "an audio that shows",
"image": "a short image caption",
"pc": "a 3d model of"
}
qformer_prompt = [modality2prompt[modality] for _ in samples['text_input']]
# qformer_prompt = [f'Describe the {Blip2VicunaXInstruct.MODALITY_TO_CUE[modality].replace(":", "").strip() if modality != "pc" else "3d model"}.' for _ in samples["text_input"]]
text_Qformer = self.tokenizer(
qformer_prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
else:
text_Qformer = self.tokenizer(
prompt,
padding='longest',
truncation=True,
max_length=self.max_txt_len,
return_tensors="pt",
).to(self.device)
Qformer_atts = {}
query_atts = {}
for modality in curr_modalities:
# B, Token Size
query_atts[modality] = torch.ones(query_tokens[modality].size()[:-1], dtype=torch.long).to(self.device)
# B, Token Size + Inp Size
Qformer_atts[modality] = torch.cat([query_atts[modality],text_Qformer.attention_mask],dim=1)
embeds = {}
data_atts = {}
for modality in curr_modalities:
data = samples[modality]
ln = getattr(self, f"{modality}_ln")
encoder = getattr(self, f"{modality}_encoder")
if modality == "video" and "clip" in self.video_enc_name:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(2)):
this_frame = data[:,:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][j] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
elif modality == 'audio' and 'beats' in self.audio_enc_name:
embeds[modality] = []
data_atts[modality] = []
for j in range(data.size(1)):
this_frame = data[:,j,:,:]
with self.maybe_autocast():
embeds[modality].append(ln(encoder(this_frame)))
if self.shared_qformer:
embeds[modality][j] = getattr(self, f"{modality}_encoder_projection")(embeds[modality][j])
data_atts[modality].append(torch.ones(embeds[modality][j].size()[:-1], dtype=torch.long).to(self.device))
else:
with self.maybe_autocast():
embeds[modality] = ln(encoder(data))
if len(embeds[modality].size()) == 2:
# B, C, D
embeds[modality] = embeds[modality].unsqueeze(1)
# B, C
if self.shared_qformer:
embeds[modality] = getattr(self, f"{modality}_encoder_projection")(embeds[modality])
data_atts[modality] = torch.ones(embeds[modality].size()[:-1], dtype=torch.long).to(self.device)
query_outputs = {}
num = {}
if self.qformer_text_input:
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num[modality] = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num[modality])]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num[modality], self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids.repeat(num[modality], 1),
attention_mask=Qformer_atts[modality].repeat(num[modality], 1),
query_embeds=query_tokens[modality].repeat(num[modality], 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
bs = embeds[modality].shape[0]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
text_Qformer.input_ids,
attention_mask=Qformer_atts[modality],
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32),
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
else:
for modality in curr_modalities:
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
num[modality] = len(embeds[modality])
bs = embeds[modality][0].shape[0]
indices = [j_+r for r,j in enumerate([[i*bs for i in range(num[modality])]]*bs) for j_ in j]
reordered_embeds = torch.cat(embeds[modality])[indices]
reordered_atts = torch.cat(data_atts[modality])[indices]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.mean(1,keepdim=True)).view(bs*num[modality], self.num_query_token, -1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(reordered_embeds.view(reordered_embeds.shape[0],-1))
continue
query_output = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality].repeat(num[modality], 1, 1),
encoder_hidden_states=reordered_embeds,
encoder_attention_mask=reordered_atts,
return_dict=True,
)
query_outputs[modality] = query_output
else:
bs = embeds[modality].shape[0]
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality].mean(1, keepdim=True)).reshape(bs, self.num_query_token,-1)
else:
query_outputs[modality] = getattr(self, f"{modality}_projection")(embeds[modality]).reshape(bs, self.num_query_token,-1)
continue
query_outputs[modality] = getattr(self, f"{modality}_Qformer").bert(
query_embeds=query_tokens[modality],
encoder_hidden_states=embeds[modality].to(torch.float32),
encoder_attention_mask=data_atts[modality],
return_dict=True,
)
inputs_llm = {}
atts_llm = {}
enumeration = {}
# from pdb import set_trace; set_trace()
for i,modality in enumerate(curr_modalities):
if modality in Blip2VicunaXInstruct.SEQUENCIAL_MODALITIES and getattr(self, f'{modality}_enc_name') in Blip2VicunaXInstruct.SEQUENCIAL_ENCODERS:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim != 1:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].unsqueeze(1)).reshape(bs*num[modality], self.num_query_token, -1)
else:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].reshape(bs*num, self.num_query_token, -1))
inputs_llm[modality] = inputs_llm[modality].reshape(bs, num[modality], self.num_query_token, -1).view(bs, num[modality]*self.num_query_token, -1)
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
continue
# num*bs, num query tokens, llm emb size
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].last_hidden_state[:,:query_tokens[modality].size(1),:])
# bs, num, num query tokens, llm emb size -> bs, num*num query tokens, llm emb size
inputs_llm[modality] = inputs_llm[modality].reshape(bs, num[modality], self.num_query_token, -1).view(bs, num[modality]*self.num_query_token, -1)
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
else:
if self.projection_only or getattr(self, f"projection_only_{modality}"):
if self.proj_dim == 1:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].mean(-1)).reshape(bs, self.num_query_token, -1)
else:
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality].reshape(bs, self.num_query_token, -1))
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
continue
inputs_llm[modality] = getattr(self, f"{modality}_llm_proj")(query_outputs[modality]['last_hidden_state'][:,:query_tokens[modality].size(1),:])
atts_llm[modality] = torch.ones(inputs_llm[modality].size()[:-1], dtype=torch.long).to(self.device)
if self.enumerate_inputs:
enumeration[modality] = self.llm_tokenizer(
[f"{'' if i == 0 else ' '}({chr(97+i)}) " for _ in prompt],
return_tensors="pt",
add_special_tokens=False if (i!= 0 or self.prefix) else True
).to(self.device)
att_list = []
inp_list = []
if self.prefix:
att_list = [self.tokenized_prefix.attention_mask.repeat(bs, 1).to(self.device)]
inp_list = [self.llm_model.get_input_embeddings()(self.tokenized_prefix.input_ids.to(self.device)).repeat(bs, 1, 1)]
for modality in curr_modalities:
if self.enumerate_inputs:
enumeration_inputs_llm = self.llm_model.get_input_embeddings()(enumeration[modality].input_ids.to(self.device))
enumeration_atts_llm = enumeration[modality].attention_mask.to(self.device)
inp_list.extend([enumeration_inputs_llm])
att_list.extend([enumeration_atts_llm])
if self.use_cues:
if self.clean_tokenization or self.remove_start:
if (modality==curr_modalities[0] and not (self.prefix or self.enumerate_inputs)):
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality]])
else:
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask[:,1:]).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality][:,1:].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality]])
else:
att_list.extend([torch.tensor(self.tokenized_cue[modality].attention_mask).to(self.device).repeat(atts_llm[modality].shape[0], 1), atts_llm[modality]])
inp_list.extend([self.emb_cue[modality].to(self.device).repeat(inputs_llm[modality].shape[0], 1, 1), inputs_llm[modality]])
else:
att_list.extend([atts_llm[modality]])
inp_list.extend([inputs_llm[modality]])
if self.add_space:
space_tok = self.llm_tokenizer(
[f" " for _ in prompt],
return_tensors="pt",
add_special_tokens=False
)
space_inputs_llm = self.llm_model.get_input_embeddings()(space_tok.input_ids.to(self.device))
space_atts_llm = space_tok.attention_mask.to(self.device)
inp_list.extend([space_inputs_llm])
att_list.extend([space_atts_llm])
atts_llm = torch.cat(att_list, dim=1)
empty_targets = torch.ones(atts_llm.size(), dtype=torch.long).to(self.device).fill_(-100)
inputs_llm = torch.cat(inp_list, dim=1)
self.llm_tokenizer.padding_side = "right"
self.llm_tokenizer.truncation_side = 'left'
text_input_tokens = self.llm_tokenizer(
[f"{p}{self.postfix}" for p in prompt] if self.postfix else prompt,
padding="longest",
return_tensors="pt",
add_special_tokens= not self.clean_tokenization
).to(self.device)
self.llm_tokenizer.truncation_side = 'right'
n_cands = len(candidates)
with self.maybe_autocast():
all_losses = []
for n in range(n_segments):
seg_len = n_cands // n_segments
if n == (n_segments - 1):
seg_len = n_cands - seg_len * (n_segments - 1)
start_i = n * (n_cands // n_segments)
end_i = start_i + seg_len
this_output_tokens = self.llm_tokenizer(
candidates[start_i:end_i],
return_tensors="pt",
padding="longest",
# truncation=True,
# max_length=self.max_output_txt_len,
).to(self.device)
this_input_tokens_ids = text_input_tokens.input_ids.repeat_interleave(seg_len, dim=0)
this_input_tokens_atts = text_input_tokens.attention_mask.repeat_interleave(seg_len, dim=0)
this_output_tokens_ids = this_output_tokens.input_ids.repeat(bs, 1)
this_output_tokens_atts = this_output_tokens.attention_mask.repeat(bs, 1)
this_llm_tokens, this_input_targets_len = self.concat_text_input_output(
this_input_tokens_ids,
this_input_tokens_atts,
this_output_tokens_ids,
this_output_tokens_atts
)
this_llm_input_ids = this_llm_tokens['input_ids']
this_llm_atts = this_llm_tokens['attention_mask']
inputs_embeds = self.llm_model.get_input_embeddings()(this_llm_input_ids)
if self.use_caption:
inputs_embeds = torch.cat([inputs_embeds], dim=1)
attention_mask = torch.cat([this_llm_atts], dim=1)
else:
inputs_embeds = torch.cat([inputs_llm.repeat_interleave(seg_len, dim=0), inputs_embeds], dim=1)
attention_mask = torch.cat([atts_llm.repeat_interleave(seg_len, dim=0), this_llm_atts], dim=1)
this_targets = this_llm_input_ids.masked_fill(this_llm_input_ids == self.llm_tokenizer.pad_token_id, -100)
for i, l in enumerate(this_input_targets_len):
this_targets[i][:l] = -100
if self.use_caption:
torch.cat([this_targets], dim=1)
else:
this_targets = torch.cat([empty_targets.repeat_interleave(seg_len, dim=0), this_targets], dim=1)
outputs = self.llm_model(
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
return_dict=True,
labels=this_targets,
reduction="none",
)
loss = outputs.loss
loss = loss.reshape(bs, seg_len)
all_losses.append(loss)
all_losses = torch.cat(all_losses, dim=-1)
all_losses = -all_losses
output_class_ranks = torch.argsort(all_losses, dim=-1)
return {"predictions": all_losses, "targets": torch.tensor([self.candidates.index(l) for l in samples["label"]])}
def _lemmatize(self, answers):
def apply(answer):
doc = self.lemmatizer(answer)
words = []
for token in doc:
if token.pos_ in ["NOUN", "VERB"]:
words.append(token.lemma_)
else:
words.append(token.text)
answer = " ".join(words)
return answer
return [apply(answer) for answer in answers]
@property
def lemmatizer(self):
if self._lemmatizer is None:
try:
import spacy
self._lemmatizer = spacy.load("en_core_web_sm")
except ImportError:
logging.error(
"""
Please install spacy and en_core_web_sm model to apply lemmatization.
python -m spacy download en_core_web_sm
OR
import spacy.cli
spacy.cli.download("en_core_web_sm")
"""
)
exit(1)
return self._lemmatizer
def get_optimizer_params(self, weight_decay, lr_scale=1):
return BaseModel.get_optimizer_params(self, weight_decay, lr_scale=lr_scale)
@classmethod
def from_config(cls, cfg):
image_model = cfg.get("image_model","eva_clip_g")
pc_model = cfg.get("pc_model","ulip2_pointbert")
video_model = cfg.get("video_model","eva_clip_g")
audio_model = cfg.get("audio_model","beats")
pretrained_image_qformer = cfg.get("pretrained_image_qformer",None)
pretrained_pc_qformer = cfg.get("pretrained_pc_qformer",None)
pretrained_video_qformer = cfg.get("pretrained_video_qformer",None)
pretrained_audio_qformer = cfg.get("pretrained_audio_qformer",None)
load_attention_image_qformer = cfg.get("load_attention_image_qformer",False)
load_attention_pc_qformer = cfg.get("load_attention_pc_qformer",False)
load_attention_video_qformer = cfg.get("load_attention_video_qformer",False)
load_attention_audio_qformer = cfg.get("load_attention_audio_qformer",False)
load_qformer_type_image=cfg.get('load_qformer_type_image', "")
load_qformer_type_pc=cfg.get('load_qformer_type_pc', "")
load_qformer_type_video=cfg.get('load_qformer_type_video', "")
load_qformer_type_audio=cfg.get('load_qformer_type_audio',"")
load_projection_image=cfg.get('load_projection_image', True)
load_projection_pc=cfg.get('load_projection_pc', True)
load_projection_video=cfg.get('load_projection_video', True)
load_projection_audio=cfg.get('load_projection_audio', True)
load_projection_type_image=cfg.get('load_projection_type_image', "")
load_projection_type_pc=cfg.get('load_projection_type_pc', "")
load_projection_type_video=cfg.get('load_projection_type_video', "")
load_projection_type_audio=cfg.get('load_projection_type_audio', "")
load_ln_type_image=cfg.get('load_ln_type_image', "")
load_ln_type_pc=cfg.get('load_ln_type_pc', "")
load_ln_type_video=cfg.get('load_ln_type_video', "")
load_ln_type_audio=cfg.get('load_ln_type_audio', "")
image_encoder_kwargs = cfg.get("image_encoder_kwargs", {"image_size": 224, "drop_path_rate": 0, "use_grad_checkpoint": False})
pc_encoder_kwargs = cfg.get("pc_encoder_kwargs",{})
video_encoder_kwargs = cfg.get("video_encoder_kwargs",{})
audio_encoder_kwargs = cfg.get("audio_encoder_kwargs",{})
image_precision = cfg.get("image_precision","fp16")
pc_precision = cfg.get("pc_precision","fp16")
video_precision = cfg.get("video_precision","fp16")
audio_precision = cfg.get("audio_precision","fp16")
freeze_image = cfg.get("freeze_image",True)
freeze_pc = cfg.get("freeze_pc",True)
freeze_video = cfg.get("freeze_video",True)
freeze_audio = cfg.get("freeze_audio",True)
num_query_token = cfg.get("num_query_token")
llm_model = cfg.get("llm_model")
freeze_pc = cfg.get("freeze_pc", True)
freeze_video = cfg.get("freeze_video", True)
freeze_audio = cfg.get("freeze_audio", True)
prompt = cfg.get("prompt", "")
max_txt_len = cfg.get("max_txt_len", 128)
max_output_txt_len = cfg.get("max_output_txt_len", 256)
apply_lemmatizer = cfg.get("apply_lemmatizer", False)
qformer_text_input = cfg.get("qformer_text_input", True)
modalities = cfg.get("modalities", ["image"])
use_cues = cfg.get("use_cues", True)
shared_qformer = cfg.get("shared_qformer",False)
pretrained_shared_qformer = cfg.get("pretrained_shared_qformer", None)
load_attention_shared_qformer = cfg.get("load_attention_shared_qformer", None)
load_qformer_type_shared= cfg.get('load_qformer_type_shared',"")
load_projection_shared= cfg.get('load_projection_shared',False)
load_projection_type_shared= cfg.get('load_projection_type_shared',"")
shared_qformer_num_features=cfg.get("shared_qformer_num_features", 512)
encoder_projection_type_image=cfg.get("encoder_projection_type_image","")
encoder_projection_type_video=cfg.get("encoder_projection_type_video","")
encoder_projection_type_audio=cfg.get("encoder_projection_type_audio","")
encoder_projection_type_pc=cfg.get("encoder_projection_type_pc","")
llm_text_input = cfg.get("llm_text_input", True)
lora = cfg.get("lora", False)
prefix = cfg.get("prefix", "")
postfix = cfg.get("postfix", "")
cached_audio= cfg.get("cached_audio", False)
cached_image= cfg.get("cached_image", False)
cached_video= cfg.get("cached_video", False)
cached_pc= cfg.get("cached_pc", False)
num_features_audio=cfg.get('num_features_audio', 768)
num_features_image=cfg.get('num_features_image', 1408)
num_features_video=cfg.get('num_features_video', 14080)
num_features_pc=cfg.get('num_features_depth', 512)
joint_video_audio=cfg.get('joint_video_audio', False)
use_caption=cfg.get('use_caption', False)
use_describe=cfg.get('use_describe', False)
predict_with_gen = cfg.get('predict_with_gen', False)
format_candidates_prompt = cfg.get('format_candidates_prompt', "{}")
special_qformer_input_prompt = cfg.get('special_qformer_input_prompt', False)
enumerate_inputs = cfg.get('enumerate_inputs', False)
add_space = cfg.get('add_space', True)
projection_only = cfg.get('projection_only', False)
lora_model = cfg.get('lora_model', '')
projection_only_audio= cfg.get('projection_only_audio', False)
projection_only_pc= cfg.get('projection_only_pc', False)
projection_only_video= cfg.get('projection_only_video', False)
projection_only_image= cfg.get('projection_only_image', False)
projection_path_audio=cfg.get('projection_path_audio', False)
projection_path_pc=cfg.get('projection_path_pc', False)
projection_path_video=cfg.get('projection_path_video', False)
projection_path_image=cfg.get('projection_path_image', False)
remove_start=cfg.get('remove_start', False)
proj_dim=cfg.get('proj_dim', 1)
clean_tokenization=cfg.get('clean_tokenization', False)
logging.info("Model Config Arguments:")
logging.info(OmegaConf.to_yaml(cfg))
model = cls(
image_model=image_model,
pc_model=pc_model,
video_model=video_model,
audio_model=audio_model,
pretrained_image_qformer=pretrained_image_qformer,
pretrained_pc_qformer=pretrained_pc_qformer,
pretrained_video_qformer=pretrained_video_qformer,
pretrained_audio_qformer=pretrained_audio_qformer,
load_attention_image_qformer=load_attention_image_qformer,
load_attention_pc_qformer=load_attention_pc_qformer,
load_attention_video_qformer=load_attention_video_qformer,
load_attention_audio_qformer=load_attention_audio_qformer,
load_qformer_type_image=load_qformer_type_image,
load_qformer_type_pc=load_qformer_type_pc,
load_qformer_type_video=load_qformer_type_video,
load_qformer_type_audio=load_qformer_type_audio,
load_projection_image=load_projection_image,
load_projection_pc=load_projection_pc,
load_projection_video=load_projection_video,
load_projection_audio=load_projection_audio,
load_projection_type_image=load_projection_type_image,
load_projection_type_pc=load_projection_type_pc,
load_projection_type_video=load_projection_type_video,
load_projection_type_audio=load_projection_type_audio,
load_ln_type_image=load_ln_type_image,
load_ln_type_pc=load_ln_type_pc,
load_ln_type_video=load_ln_type_video,
load_ln_type_audio=load_ln_type_audio,
image_encoder_kwargs = image_encoder_kwargs,
pc_encoder_kwargs = pc_encoder_kwargs,
video_encoder_kwargs = video_encoder_kwargs,
audio_encoder_kwargs = audio_encoder_kwargs,
image_precision=image_precision,
pc_precision=pc_precision,
video_precision=video_precision,
audio_precision=audio_precision,
freeze_image=freeze_image,
freeze_pc=freeze_pc,
freeze_video=freeze_video,
freeze_audio=freeze_audio,
num_query_token=num_query_token,
llm_model=llm_model,
lora_model=lora_model,
lora = lora,
prompt=prompt,
max_txt_len=max_txt_len,
max_output_txt_len=max_output_txt_len,
apply_lemmatizer=apply_lemmatizer,
qformer_text_input=qformer_text_input,
modalities=modalities,
use_cues=use_cues,
llm_text_input=llm_text_input,
shared_qformer=shared_qformer,
pretrained_shared_qformer = pretrained_shared_qformer,
load_attention_shared_qformer = load_attention_shared_qformer,
shared_qformer_num_features=shared_qformer_num_features,
load_qformer_type_shared= load_qformer_type_shared,
load_projection_shared= load_projection_shared,
encoder_projection_type_image=encoder_projection_type_image,
encoder_projection_type_video=encoder_projection_type_video,
encoder_projection_type_audio=encoder_projection_type_audio,
encoder_projection_type_pc=encoder_projection_type_pc,
projection_path_audio=projection_path_audio,
projection_path_pc=projection_path_pc,
projection_path_video=projection_path_video,
projection_path_image=projection_path_image,
load_projection_type_shared= load_projection_type_shared,
prefix=prefix,
postfix=postfix,
cached_audio=cached_audio,
cached_image=cached_image,
cached_video=cached_video,
cached_pc=cached_pc,
num_features_audio=num_features_audio,
num_features_image=num_features_image,
num_features_video=num_features_video,
num_features_pc=num_features_pc,
joint_video_audio=joint_video_audio,
use_caption=use_caption,
use_describe=use_describe,
predict_with_gen=predict_with_gen,
format_candidates_prompt=format_candidates_prompt,
special_qformer_input_prompt=special_qformer_input_prompt,
enumerate_inputs=enumerate_inputs,
add_space=add_space,
projection_only=projection_only,
projection_only_audio= projection_only_audio,
projection_only_pc= projection_only_pc,
projection_only_video= projection_only_video,
projection_only_image= projection_only_image,
remove_start= remove_start,
proj_dim=proj_dim,
clean_tokenization=clean_tokenization
)
stage1_url_or_filename = cfg.get("stage1_url_or_filename","")
if stage1_url_or_filename:
model.load_from_pretrained(stage1_url_or_filename)
model.load_checkpoint_from_config(cfg)
return model
@classmethod
def init_ln(cls, num_features, load_ln_path=False, load_ln_type=""):
ln = LayerNorm(num_features)
if load_ln_path and load_ln_type:
url_or_filename=load_ln_path
logging.info(f"Loading pretrained layer norm weights from {url_or_filename} of type {load_ln_type}")
if is_url(url_or_filename):
cached_file = download_cached_file(
url_or_filename, check_hash=False, progress=True
)
checkpoint = torch.load(cached_file, map_location="cpu")
elif os.path.isfile(url_or_filename):
checkpoint = torch.load(url_or_filename, map_location="cpu")
else:
raise RuntimeError("checkpoint url or path is invalid")
if load_ln_type:
load_ln_type = f"{load_ln_type}_ln" if "vision" not in load_ln_type else "ln_vision"
loaded_state_dict = {}
if 'model' in checkpoint:
checkpoint = checkpoint['model']
for k in checkpoint.keys():
if load_ln_type in k:
loaded_state_dict['.'.join(k.split('.')[1:])] = checkpoint[k]
ln.load_state_dict(loaded_state_dict, strict=False)
return ln
@classmethod
def init_encoder_projection(cls, enc_num_features, shared_qformer_num_features, load_proj_path=False, load_proj_type=""):
encoder_projection = nn.Linear(enc_num_features, shared_qformer_num_features)
if load_proj_path and load_proj_type:
url_or_filename=load_proj_path
logging.info(f"Loading shared Qformer encoder projection weights from {url_or_filename} of type {load_proj_type}")
if is_url(url_or_filename):
cached_file = download_cached_file(
url_or_filename, check_hash=False, progress=True
)
checkpoint = torch.load(cached_file, map_location="cpu")
elif os.path.isfile(url_or_filename):
checkpoint = torch.load(url_or_filename, map_location="cpu")
else:
raise RuntimeError("checkpoint url or path is invalid")
if load_proj_type:
load_proj_type = f"{load_proj_type}_"
loaded_state_dict = {}
if 'model' in checkpoint:
checkpoint = checkpoint['model']
for k in checkpoint.keys():
if load_proj_type+'encoder_projection' in k:
loaded_state_dict['.'.join(k.split('.')[1:])] = checkpoint[k]
encoder_projection.load_state_dict(loaded_state_dict, strict=False)
return encoder_projection
@classmethod
def init_vicuna_projection(cls, input_size, output_size, load_projection_path=False, load_projection_type="", projection_key=None):
proj = nn.Linear(input_size, output_size)
if load_projection_path:
url_or_filename=load_projection_path
logging.info(f"Loading pretrained projection weights from {url_or_filename} of type {load_projection_type} with key {projection_key if projection_key else load_projection_type+'_llm_proj.'}")
if is_url(url_or_filename):
cached_file = download_cached_file(
url_or_filename, check_hash=False, progress=True
)
checkpoint = torch.load(cached_file, map_location="cpu")
elif os.path.isfile(url_or_filename):
checkpoint = torch.load(url_or_filename, map_location="cpu")
else:
raise RuntimeError("checkpoint url or path is invalid")
if load_projection_type:
load_projection_type = f"{load_projection_type}_"
loaded_state_dict = {}
if 'model' in checkpoint:
checkpoint = checkpoint['model']
for k in checkpoint.keys():
if projection_key:
if projection_key in k:
loaded_state_dict['.'.join(k.split('.')[1:])] = checkpoint[k]
else:
if load_projection_type+'llm_proj.' in k:
loaded_state_dict['.'.join(k.split('.')[1:])] = checkpoint[k]
proj.load_state_dict(loaded_state_dict, strict=False)
return proj
@classmethod
def init_Qformer(cls, num_query_token, modality_width, cross_attention_freq=2, pretrained_qformer=None, load_attention=False, load_qformer_type=""):
encoder_config = BertConfig.from_pretrained("bert-base-uncased")
encoder_config.encoder_width = modality_width
# insert cross-attention layer every other block
encoder_config.add_cross_attention = True
encoder_config.cross_attention_freq = cross_attention_freq
encoder_config.query_length = num_query_token
encoder_config.vocab_size += 1 # for special token [DEC]
Qformer = BertLMHeadModel(config=encoder_config)
query_tokens = nn.Parameter(
torch.zeros(1, num_query_token, encoder_config.hidden_size)
)
query_tokens.data.normal_(mean=0.0, std=encoder_config.initializer_range)
if pretrained_qformer:
url_or_filename=pretrained_qformer
logging.info(f"Loading pretrained qformer weights and query tokens from {url_or_filename} of type {load_qformer_type}")
if is_url(url_or_filename):
cached_file = download_cached_file(
url_or_filename, check_hash=False, progress=True
)
checkpoint = torch.load(cached_file, map_location="cpu")
elif os.path.isfile(url_or_filename):
checkpoint = torch.load(url_or_filename, map_location="cpu")
else:
raise RuntimeError("checkpoint url or path is invalid")
if load_qformer_type:
load_qformer_type = f"{load_qformer_type}_"
loaded_state_dict = {}
if 'model' in checkpoint:
checkpoint = checkpoint['model']
for k in checkpoint.keys():
if load_qformer_type+'Qformer.' in k:
if not load_attention and 'attention' in k:
continue
loaded_state_dict['.'.join(k.split('.')[1:])] = checkpoint[k]
Qformer.load_state_dict(loaded_state_dict, strict=False)
query_tokens.data = checkpoint[load_qformer_type+'query_tokens']
return Qformer, query_tokens
def get_state_dict(self, url_or_filename, **kwargs):
if is_url(url_or_filename):
cached_file = download_cached_file(
url_or_filename, check_hash=False, progress=True
)
checkpoint = torch.load(cached_file, map_location="cpu")
elif os.path.isfile(url_or_filename):
checkpoint = torch.load(url_or_filename, map_location="cpu")
else:
raise RuntimeError("checkpoint url or path is invalid")
if "model" in checkpoint.keys():
state_dict = checkpoint["model"]
else:
state_dict = checkpoint
return state_dict
def load_from_pretrained(self, url_or_filename, **kwargs):
state_dict = self.get_state_dict(url_or_filename)
self.load_state_dict(state_dict, strict=False)
logging.info("load checkpoint from %s" % url_or_filename)
def load_checkpoint(self, url_or_filename, **kwargs):
"""
Load from a finetuned checkpoint.
This should expect no mismatch in the model keys and the checkpoint keys.
"""
state_dict = self.get_state_dict(url_or_filename)
self.load_state_dict(state_dict, strict=True)
logging.info("load checkpoint from %s" % url_or_filename)
def load_state_dict(self, state_dict, strict=True):
# from pdb import set_trace; set_trace()
unexpected_keys = []
missing_keys = []
if self.shared_qformer and not self.projection_only:
## Load Q-Former if it is not loaded from config
if not getattr(self, "pretrained_shared_qformer"):
shared_qformer_state_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if "shared_Qformer" == k.split('.')[0]}
msg = self.shared_Qformer.load_state_dict(shared_qformer_state_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
## Load query tokens
if "shared_query_tokens" not in state_dict:
missing_keys.append("shared_query_tokens")
else:
self.shared_query_tokens = state_dict["shared_query_tokens"]
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
for modality in self.modalities:
# Map shared Qformer by reference to all modalities.
setattr(self, f"{modality}_Qformer", self.shared_Qformer)
getattr(self, f"{modality}_query_tokens").data = state_dict[f"shared_query_tokens"]
# load encoder projections
modality_encoder_projection_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"{modality}_encoder_projection" in k.split('.')[0]}
msg = getattr(self, f"{modality}_encoder_projection").load_state_dict(modality_encoder_projection_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
# load modality layer norm
if getattr(self,f"load_ln_type_{modality}") == "vision":
modality_ln_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"ln_vision" in k.split('.')[0]}
else:
modality_ln_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"{modality}_ln" in k.split('.')[0]}
msg = getattr(self, f"{modality}_ln").load_state_dict(modality_ln_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
## Load Shared LLM projection if not loaded by config
if not getattr(self, "load_projection_shared"):
shared_llm_projection_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"shared_llm_proj" in k.split('.')[0]}
msg = self.shared_llm_proj.load_state_dict(shared_llm_projection_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
for modality in self.modalities:
## Map to modality projections by reference
msg = setattr(self, f"{modality}_llm_proj", self.shared_llm_proj)
else:
for modality in self.modalities:
## Load Q-Former if not loaded from config
if not getattr(self, f"pretrained_{modality}_qformer") or ((self.projection_only or getattr(self, f"projection_only_{modality}")) and not getattr(self, f"projection_path_{modality}")):
if self.projection_only or getattr(self, f"projection_only_{modality}") :
if not getattr(self, f"projection_path_{modality}"):
logging.info(f"Loaded {modality} projection")
modality_qformer_state_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"{modality}_projection" == k.split('.')[0]}
msg = getattr(self, f"{modality}_projection").load_state_dict(modality_qformer_state_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
else:
modality_qformer_state_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"{modality}_Qformer" == k.split('.')[0]}
msg = getattr(self, f"{modality}_Qformer").load_state_dict(modality_qformer_state_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
## Load query tokens
if not self.projection_only and not getattr(self, f"projection_only_{modality}"):
if f"{modality}_query_tokens" not in state_dict:
missing_keys.append(f"{modality}_query_tokens")
else:
logging.info(f"Loaded {modality} query tokens")
getattr(self, f"{modality}_query_tokens").data = state_dict[f"{modality}_query_tokens"]
# load modality layer norm if not loaded from config
if getattr(self,f"load_ln_type_{modality}") == "vision":
logging.info(f"Loaded {modality} vision ln")
modality_ln_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"ln_vision" in k.split('.')[0]}
else:
modality_ln_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"{modality}_ln" in k.split('.')[0]}
msg = getattr(self, f"{modality}_ln").load_state_dict(modality_ln_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
## Load LLM projections if not loaded from config
if not getattr(self, f"load_projection_{modality}") or (getattr(self, f"projection_only_{modality}") or self.projection_only):
if not getattr(self, f"projection_path_{modality}"):
logging.info(f"Loaded {modality} llm projection")
modality_llm_projection_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"{modality}_llm_proj" in k.split('.')[0]}
msg = getattr(self, f"{modality}_llm_proj").load_state_dict(modality_llm_projection_dict, strict=strict)
missing_keys.extend(msg.missing_keys)
unexpected_keys.extend(msg.unexpected_keys)
## llm model is loaded from pretrained
lora_state_dict = {'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"llm_model" in k.split('.')[0]}
if not self.lora or len(lora_state_dict) == 0:
unexpected_keys = [k for k in unexpected_keys if k.split('.')[0] != 'llm_model']
else:
msg = self.llm_model.load_state_dict({'.'.join(k.split('.')[1:]):v for k,v in state_dict.items() if f"llm_model" in k.split('.')[0]}, strict=False)
missing_keys.extend(["llm_model."+k for k in msg.missing_keys])
missing_keys = [k for k in missing_keys if 'encoder' not in k.split('.')[0]]
missing_keys = [k for k in missing_keys if k.split('.')[0] != 'llm_model']
return _IncompatibleKeys(missing_keys, unexpected_keys)
def before_evaluation(self, dataset, task_type, **kwargs):
if task_type == MultimodalClassificationTask:
self.candidates = dataset.classnames
print(self.candidates) |