File size: 88,084 Bytes
b9c622a |
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 |
"""
modeling_prismatic.py
Core HuggingFace-style PrismaticPreTrainedModel and PrismaticForConditionalGeneration class definitions.
Inherits from the default `transformers.PretrainedModel`. Meant to be standalone and self-contained,
but exactly replicate the logic in `prismatic.models.vlms.prismatic.py`.
"""
import logging
from dataclasses import dataclass
from functools import partial
from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple, Union
import numpy as np
import timm
import tokenizers
import torch
import torch.nn as nn
import transformers
from timm.models.vision_transformer import LayerScale
from transformers import AutoModelForCausalLM, PretrainedConfig, PreTrainedModel
from transformers.modeling_outputs import ModelOutput
from prismatic.training.train_utils import (
get_current_action_mask,
get_next_actions_mask,
)
from prismatic.vla.constants import (
ACTION_DIM,
ACTION_PROPRIO_NORMALIZATION_TYPE,
ACTION_TOKEN_BEGIN_IDX,
IGNORE_INDEX,
NUM_ACTIONS_CHUNK,
STOP_INDEX,
NormalizationType,
)
from .configuration_prismatic import OpenVLAConfig, PrismaticConfig
# Set up logger
logger = logging.getLogger(__name__)
# === Utility Functions for Monkey-Patching ===
def unpack_tuple(fn: Callable[[Any], Tuple[Any]]) -> Callable[[Any], Any]:
def wrapper(*args: Any, **kwargs: Any) -> Any:
result = fn(*args, **kwargs)
return result[0] if isinstance(result, tuple) else result
return wrapper
# HF Transformers overwrites parameters with names containing `gamma`; we're going to patch VisionBackbone.LayerScale.
# =>> TIMM :: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L109
# =>> Transformers :: https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_utils.py#L3960
def _ls_new_forward(self, x: torch.Tensor) -> torch.Tensor:
return x.mul_(self.scale_factor) if self.inplace else x * self.scale_factor
def ls_apply_patch(ls_module: LayerScale):
ls_module.scale_factor = nn.Parameter(ls_module.gamma.clone())
ls_module.forward = _ls_new_forward.__get__(ls_module, LayerScale)
del ls_module.gamma
# === Prismatic Vision Backbone (nn.Module) Definitions (w/ Fused Backbone Support) ===
class PrismaticVisionBackbone(nn.Module):
"""
Vision backbone for Prismatic models that handles image feature extraction.
Supports both single backbone (e.g., SigLIP) and fused backbone (e.g., SigLIP + DINOv2) configurations.
For fused backbones, features from both models are concatenated along the feature dimension.
"""
def __init__(
self,
use_fused_vision_backbone: bool,
image_sizes: List[int],
timm_model_ids: List[str],
timm_override_act_layers: List[Optional[str]],
) -> None:
"""
Initialize the vision backbone.
Args:
use_fused_vision_backbone: Whether to use two backbones and fuse their features
image_sizes: List of image sizes for each backbone
timm_model_ids: List of TIMM model IDs to use for each backbone
timm_override_act_layers: List of activation layer overrides for each backbone
"""
super().__init__()
self.use_fused_vision_backbone = use_fused_vision_backbone
self.num_images_in_input = 1 # Default value, can be overridden later
# Validate number of (fused) vision backbones
if len(timm_model_ids) > 2:
raise ValueError("Prismatic models only support up to 2 (fused) vision backbones!")
# Create primary featurizer
self.featurizer = self._create_featurizer(
model_id=timm_model_ids[0], img_size=image_sizes[0], act_layer=timm_override_act_layers[0]
)
self.embed_dim = self.featurizer.embed_dim
# Create secondary featurizer if using fused backbone
if self.use_fused_vision_backbone:
self.fused_featurizer = self._create_featurizer(
model_id=timm_model_ids[1], img_size=image_sizes[1], act_layer=timm_override_act_layers[1]
)
self.embed_dim += self.fused_featurizer.embed_dim
# Patch LayerScale modules for HF compatibility
self._patch_layer_scales()
def _create_featurizer(self, model_id: str, img_size: int, act_layer: Optional[str]) -> nn.Module:
"""
Create a TIMM-based featurizer model with appropriate configurations.
Args:
model_id: The TIMM model ID to load
img_size: Input image size for the model
act_layer: Override for the activation layer type
Returns:
A configured featurizer model
"""
featurizer = timm.create_model(
model_id,
pretrained=False,
num_classes=0,
img_size=img_size,
act_layer=act_layer,
)
# Monkey-patch the forward function to extract the second-to-last layer features
num_blocks = len(featurizer.blocks)
featurizer.forward = unpack_tuple(partial(featurizer.get_intermediate_layers, n={num_blocks - 2}))
return featurizer
def _patch_layer_scales(self) -> None:
"""
Patch all LayerScale modules to be compatible with HF's parameter naming.
HF Transformers overwrites parameters with names containing 'gamma',
so we need to rename and modify the forward method.
"""
# Patch primary featurizer
for module in self.featurizer.modules():
if isinstance(module, LayerScale):
ls_apply_patch(module)
# Patch secondary featurizer if it exists
if self.use_fused_vision_backbone:
for module in self.fused_featurizer.modules():
if isinstance(module, LayerScale):
ls_apply_patch(module)
def get_num_patches(self) -> int:
"""
Returns the number of vision patches output by the vision backbone.
Returns:
Number of patches per image
"""
return self.featurizer.patch_embed.num_patches
def get_num_images_in_input(self) -> int:
"""
Returns the number of input images for the vision backbone.
Returns:
Number of images expected in the input
"""
return self.num_images_in_input
def set_num_images_in_input(self, num_images_in_input: int) -> None:
"""
Sets the number of input images for the vision backbone.
Args:
num_images_in_input: Number of images to expect in the input
"""
self.num_images_in_input = num_images_in_input
def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
"""
Implements the forward pass for the vision backbone.
If `self.use_fused_vision_backbone == True`, uses both SigLIP and DINOv2 transformers to extract visual features
(otherwise uses SigLIP only). Allows multi-image inputs (but only for fused vision backbone).
Args:
pixel_values (torch.Tensor): Pixels for input image(s), (B, C, H, W).
"""
if self.num_images_in_input == 1:
if not self.use_fused_vision_backbone:
return self.featurizer(pixel_values)
# Split `pixel_values :: [bsz, 2 * 3, resolution, resolution]` =>> featurize =>> channel stack
img, img_fused = torch.split(pixel_values, [3, 3], dim=1)
patches, patches_fused = self.featurizer(img), self.fused_featurizer(img_fused)
return torch.cat([patches, patches_fused], dim=2)
else:
assert self.use_fused_vision_backbone, "Multi-image inputs require using fused backbone!"
# Split `pixel_values` into individual images (each with 6 channels: 3 for SigLIP + 3 for DINOv2)
images = torch.split(pixel_values, [6] * self.num_images_in_input, dim=1)
# Process each image and collect patches
all_patches = []
for img in images:
# Split each image further into two stacks of channels (each with 3 channels)
img_regular, img_fused = torch.split(img, [3, 3], dim=1)
# Get patches from both SigLIP and DINOv2 vision transformers
patches = self.featurizer(img_regular)
patches_fused = self.fused_featurizer(img_fused)
# Concatenate SigLIP and DINOv2 patches along the hidden dimension
combined_patches = torch.cat([patches, patches_fused], dim=2)
all_patches.append(combined_patches)
# Concatenate all patches along the patch dimension
return torch.cat(all_patches, dim=1)
# === Prismatic Projector (nn.Module) Definitions ===
class PrismaticProjector(nn.Module):
def __init__(self, use_fused_vision_backbone: bool, vision_dim: int, llm_dim: int) -> None:
super().__init__()
self.use_fused_vision_backbone = use_fused_vision_backbone
self.vision_dim, self.llm_dim = vision_dim, llm_dim
# Switch on `use_fused_vision_backbone` =>> use slightly different MLPs and projection factors!
if not self.use_fused_vision_backbone:
self.fc1 = nn.Linear(self.vision_dim, self.llm_dim, bias=True)
self.fc2 = nn.Linear(self.llm_dim, self.llm_dim, bias=True)
self.act_fn1 = nn.GELU()
else:
initial_projection_dim = 4 * vision_dim
self.fc1 = nn.Linear(self.vision_dim, initial_projection_dim, bias=True)
self.fc2 = nn.Linear(initial_projection_dim, self.llm_dim, bias=True)
self.fc3 = nn.Linear(self.llm_dim, self.llm_dim, bias=True)
self.act_fn1 = nn.GELU()
self.act_fn2 = nn.GELU()
def forward(self, img_patches: torch.Tensor) -> torch.Tensor:
if not self.use_fused_vision_backbone:
projected_features = self.fc1(img_patches)
projected_features = self.act_fn1(projected_features)
projected_features = self.fc2(projected_features)
else:
projected_features = self.fc1(img_patches)
projected_features = self.act_fn1(projected_features)
projected_features = self.fc2(projected_features)
projected_features = self.act_fn2(projected_features)
projected_features = self.fc3(projected_features)
return projected_features
# === Main HF Class Definitions ===
@dataclass
class PrismaticCausalLMOutputWithPast(ModelOutput):
"""Base class for Prismatic casual (visually-conditioned) language model outputs; also exposes visual features."""
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
# Additions for VLMs
projector_features: Optional[torch.FloatTensor] = None
class PrismaticPreTrainedModel(PreTrainedModel):
config_class: PretrainedConfig = PrismaticConfig
base_model_prefix: str = "model"
supports_gradient_checkpointing: bool = True
_no_split_modules: ClassVar[List[str]] = ["PrismaticProjector"]
_skip_keys_device_placement: str = "past_key_values"
_supports_flash_attn_2: bool = True
def _init_weights(self, module: nn.Module) -> None:
# Important :: this HF ported version is *not* meant for training from scratch; only inference and fine-tuning!
# => As such, this init_weights code is not correct; if training VLMs from scratch, use the main codebase at
# https://github.com/TRI-ML/prismatic-vlms
std = (
self.config.initializer_range
if hasattr(self.config, "initializer_range")
else self.config.text_config.initializer_range
)
if hasattr(module, "class_embedding"):
module.class_embedding.data.normal_(mean=0.0, std=std)
if isinstance(module, (nn.Linear, nn.Conv2d)):
module.weight.data.normal_(mean=0.0, std=std)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=std)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
@property
def _supports_sdpa(self) -> bool:
"""Check LLM supports SDPA Attention"""
return self.language_model._supports_sdpa
class PrismaticForConditionalGeneration(PrismaticPreTrainedModel):
def __init__(self, config: PrismaticConfig) -> None:
super().__init__(config)
# [Validation] Lightweight Validate on `config` Fields + Dependency Versions
if config.use_fused_vision_backbone is None:
raise ValueError("Missing config field `use_fused_vision_backbone`")
if timm.__version__ not in {"0.9.10", "0.9.11", "0.9.12", "0.9.16"}:
raise NotImplementedError(
"TIMM Version must be >= 0.9.10 and < 1.0.0 (breaking); please raise a GitHub Issue "
"if you urgently need support for latest TIMM versions."
)
if (transformers.__version__ != "4.40.1") or (tokenizers.__version__ != "0.19.1"):
logger.warning(
f"Expected `transformers==4.40.1` and `tokenizers==0.19.1` but got "
f"`transformers=={transformers.__version__}` and `tokenizers=={tokenizers.__version__}`; "
f"there might be inference-time regressions due to dependency changes. If in doubt, please"
f"use the above versions."
)
# Instantiate PrismaticVisionBackbone (w/ Potential Fused Backbone)
self.vision_backbone = PrismaticVisionBackbone(
config.use_fused_vision_backbone, config.image_sizes, config.timm_model_ids, config.timm_override_act_layers
)
# Create Multimodal Projector
self.projector = PrismaticProjector(
config.use_fused_vision_backbone,
vision_dim=self.vision_backbone.embed_dim,
llm_dim=config.text_config.hidden_size,
)
# Instantiate LLM Backbone
self.language_model = AutoModelForCausalLM.from_config(
config.text_config, attn_implementation=config._attn_implementation
)
self.vocab_size = config.text_config.vocab_size
self.pad_token_id = config.pad_token_id
self.llm_dim = config.text_config.hidden_size
# HF Boilerplate =>> initializes weights via `_init_weights()` and sets gradient checkpointing
self.post_init()
# === `PreTrainedModel` Boilerplate ===
def get_input_embeddings(self) -> nn.Module:
return self.language_model.get_input_embeddings()
def set_input_embeddings(self, value: nn.Module) -> None:
self.language_model.set_input_embeddings(value)
def get_output_embeddings(self) -> nn.Module:
return self.language_model.get_output_embeddings()
def set_output_embeddings(self, new_embeddings: nn.Module) -> None:
self.language_model.set_output_embeddings(new_embeddings)
def get_decoder(self) -> nn.Module:
return self.language_model.get_decoder()
def set_decoder(self, decoder: nn.Module) -> None:
self.language_model.set_decoder(decoder)
def tie_weights(self) -> None:
self.language_model.tie_weights() # Note: `Llama-2` and `Mistral` don't tie weights (no-op)
def resize_token_embeddings(
self, new_num_tokens: Optional[int] = None, pad_to_multiple_of: Optional[int] = None
) -> nn.Embedding:
updated_embeddings = self.language_model.resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
# Update config/instance variables
self.config.text_config.vocab_size = updated_embeddings.num_embeddings
self.vocab_size = updated_embeddings.num_embeddings
return updated_embeddings
def _replace_input_embeddings(self, input_embeddings, all_actions_mask, noisy_action_features):
"""
Replace embeddings in input_embeddings at positions where all_actions_mask is True
with embeddings from noisy_action_features, using vectorized operations.
Args:
input_embeddings: Tensor of shape (B, S, D)
all_actions_mask: Boolean tensor of shape (B, S)
noisy_action_features: Tensor of shape (B, K, D) where K is the number of True values in mask per sample
Returns:
Modified input_embeddings tensor
"""
# Clone input to avoid modifying the original tensor
new_input_embeddings = input_embeddings.clone()
# Create a tensor with the same shape of input_embeddings to hold the noisy action features
repositioned_noisy_action_features = torch.zeros_like(input_embeddings)
# Create batch indices for splicing
batch_indices = torch.arange(input_embeddings.shape[0], device=input_embeddings.device)
batch_indices = batch_indices.unsqueeze(1).expand(-1, noisy_action_features.shape[1])
# Get indices where mask is True for each sample
masked_indices = torch.stack([torch.where(mask)[0] for mask in all_actions_mask])
# Move the noisy action features into their correct positions
repositioned_noisy_action_features[batch_indices, masked_indices] = noisy_action_features
# Combine original input embeddings and noisy action embeddings using the mask
new_input_embeddings = torch.where(
all_actions_mask.unsqueeze(-1), repositioned_noisy_action_features, new_input_embeddings
)
return new_input_embeddings
def _process_action_masks(self, labels):
"""Helper to get action masks from labels"""
current_action_mask = get_current_action_mask(labels)
next_actions_mask = get_next_actions_mask(labels)
all_actions_mask = current_action_mask | next_actions_mask # (B, seq_len)
return all_actions_mask
def _process_vision_features(self, pixel_values, language_embeddings=None, use_film=False):
"""Process vision features with optional FiLM conditioning"""
if use_film:
# FiLM: Infuse language inputs into visual features
patch_features = self.vision_backbone(pixel_values, language_embeddings) # (bsz, 256 * num_images, D)
else:
patch_features = self.vision_backbone(pixel_values) # (bsz, 256 * num_images, D)
# Project patch embeddings into language embedding space
return self.projector(patch_features)
def _process_proprio_features(self, projected_patch_embeddings, proprio, proprio_projector):
"""Process proprioceptive features and append to vision features"""
if proprio_projector is not None and proprio is not None:
# projected_patch_embeddings: (bsz, num_patches * num_images, llm_dim)
# proprio: (bsz, proprio_dim) or (propro_dim,)
proprio = proprio.reshape(projected_patch_embeddings.shape[0], -1) # (bsz, proprio_dim)
proprio_features = proprio_projector(proprio) # (bsz, llm_dim)
proprio_features = proprio_features.unsqueeze(dim=1) # (bsz, 1, llm_dim)
# For simplicity, just append proprio token to the end of projected vision patch tokens
return torch.cat((projected_patch_embeddings, proprio_features), dim=1)
return projected_patch_embeddings
def _build_multimodal_attention(self, input_embeddings, projected_patch_embeddings, attention_mask):
"""Build multimodal embeddings and attention mask"""
# Update attention mask
projected_patch_attention_mask = None
if attention_mask is not None:
projected_patch_attention_mask = torch.full(
(projected_patch_embeddings.shape[0], projected_patch_embeddings.shape[1]),
fill_value=True,
dtype=attention_mask.dtype,
device=attention_mask.device,
)
# Build multimodal embeddings & attention mask; insert embeddings after <BOS> token (1:)
multimodal_embeddings = torch.cat(
[input_embeddings[:, :1, :], projected_patch_embeddings, input_embeddings[:, 1:, :]], dim=1
)
multimodal_attention_mask = None
if attention_mask is not None:
multimodal_attention_mask = torch.cat(
[attention_mask[:, :1], projected_patch_attention_mask, attention_mask[:, 1:]], dim=1
)
return multimodal_embeddings, multimodal_attention_mask
def _build_multimodal_labels(self, labels, projected_patch_embeddings):
"""Build multimodal labels with IGNORE_INDEX for patch embeddings"""
if labels is not None:
projected_patch_labels = torch.full(
(projected_patch_embeddings.shape[0], projected_patch_embeddings.shape[1]),
fill_value=IGNORE_INDEX,
dtype=labels.dtype,
device=labels.device,
)
return torch.cat([labels[:, :1], projected_patch_labels, labels[:, 1:]], dim=1)
return None
# === Core Prismatic VLM `forward()` Logic ===
# def forward(
# self,
# input_ids: Optional[torch.LongTensor] = None,
# attention_mask: Optional[torch.Tensor] = None,
# pixel_values: Optional[torch.FloatTensor] = None,
# labels: Optional[torch.LongTensor] = None,
# inputs_embeds: Optional[torch.FloatTensor] = None,
# past_key_values: Optional[List[torch.FloatTensor]] = None,
# use_cache: Optional[bool] = None,
# output_attentions: Optional[bool] = None,
# output_hidden_states: Optional[bool] = None,
# output_projector_features: Optional[bool] = None,
# return_dict: Optional[bool] = None,
# proprio=None,
# proprio_projector=None,
# noisy_actions=None,
# noisy_action_projector=None,
# diffusion_timestep_embeddings=None,
# use_film: bool = False,
# ) -> Union[Tuple, PrismaticCausalLMOutputWithPast]:
# """Run a forward pass through the VLM, returning a PrismaticCausalLMOutputWithPast instance."""
# output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
# output_hidden_states = (
# output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
# )
# output_projector_features = output_projector_features if output_projector_features is not None else False
# return_dict = return_dict if return_dict is not None else self.config.use_return_dict
# # Respect `use_cache` only if not training (even if `gradient_checkpointing` is off)
# use_cache = use_cache and not self.training
# # Instantiate Placeholder for Projector Features
# projected_patch_embeddings = None
# # === Handle Generation with Cache (`input_ids.shape[1] == 1`) =>> requires `past_keys_values` ===
# if input_ids.shape[1] == 1:
# assert input_ids.shape[0] == 1, "Generation is only currently supported for batch size of 1!"
# assert past_key_values is not None, "You must provide `past_key_values` during cached generation!"
# assert labels is None, "Unexpected key `labels` provided during cached generation!"
# language_model_output = self.language_model(
# input_ids=input_ids,
# attention_mask=None,
# position_ids=None,
# past_key_values=past_key_values,
# inputs_embeds=None,
# labels=None,
# use_cache=use_cache,
# output_attentions=output_attentions,
# output_hidden_states=output_hidden_states,
# return_dict=return_dict,
# )
# # === Handle Unimodal Forward ===
# elif pixel_values is None:
# assert (input_ids is not None) and (inputs_embeds is None), "Missing `input_ids` in language-only forward!"
# assert past_key_values is None, "Unexpected key `past_key_values` provided during language-only forward!"
# language_model_output = self.language_model(
# input_ids=input_ids,
# attention_mask=attention_mask,
# position_ids=None,
# past_key_values=None,
# inputs_embeds=None,
# labels=labels,
# use_cache=use_cache,
# output_attentions=output_attentions,
# output_hidden_states=output_hidden_states,
# return_dict=return_dict,
# )
# # === Handle Multimodal Forward ===
# elif (input_ids.shape[0] == pixel_values.shape[0]) or (inputs_embeds.shape[0] == pixel_values.shape[0]):
# assert past_key_values is None, "Unexpected key `past_key_values` provided during multimodal forward!"
# #test
#
# #test end
# # Get input embeddings (from language model embeddings)
# input_embeddings = self.get_input_embeddings()(input_ids) # (B, seq_len, D)
# # Extract action masks
# all_actions_mask = self._process_action_masks(labels)
# # Extract the language portion of the input embeddings (i.e. remove the action tokens portion)
# language_embeddings = input_embeddings[~all_actions_mask].reshape(
# input_embeddings.shape[0], -1, input_embeddings.shape[2]
# ) # (B, lang_seq_len, llm_dim)
# # Get visual features
# projected_patch_embeddings = self._process_vision_features(pixel_values, language_embeddings, use_film)
# # Add proprioceptive state if provided
# projected_patch_embeddings = self._process_proprio_features(
# projected_patch_embeddings, proprio, proprio_projector
# )
# # [Diffusion] Add diffusion timestep embedding if provided
# if diffusion_timestep_embeddings is not None:
# # For simplicity, just append diffusion timestep embedding to the end of projected vision patch tokens
# projected_patch_embeddings = torch.cat(
# (projected_patch_embeddings, diffusion_timestep_embeddings), dim=1
# )
# # Process action embeddings
# if noisy_actions is not None:
# # Get mask corresponding to all action tokens
# all_actions_mask = self._process_action_masks(labels)
# # Reshape noisy actions into individual action tokens
# # noisy_actions: (B, chunk_len, action_dim) -> (B, chunk_len * action_dim, 1)
# B = noisy_actions.shape[0]
# noisy_actions = noisy_actions.reshape(B, -1).unsqueeze(-1)
# # Project noisy action tokens into language model embedding space
# noisy_action_features = noisy_action_projector(noisy_actions) # (B, chunk_len * action_dim, llm_dim)
# # Replace embeddings of the action tokens with noisy action embeddings
# input_embeddings = self._replace_input_embeddings(
# input_embeddings, all_actions_mask, noisy_action_features
# )
# else:
# # Replace the embeddings of the action tokens with zeros
# # (Later on, the positional embeddings will be added to them)
# all_actions_mask = all_actions_mask.unsqueeze(-1) # (B, seq_len, 1)
# input_embeddings = input_embeddings * ~all_actions_mask
# # Build multimodal embeddings & attention mask
# multimodal_embeddings, multimodal_attention_mask = self._build_multimodal_attention(
# input_embeddings, projected_patch_embeddings, attention_mask
# )
# # Build labels for multimodal sequence if needed
# multimodal_labels = self._build_multimodal_labels(labels, projected_patch_embeddings)
# # Dispatch to language model
# language_model_output = self.language_model(
# input_ids=None,
# attention_mask=multimodal_attention_mask,
# position_ids=None,
# past_key_values=None,
# inputs_embeds=multimodal_embeddings,
# labels=multimodal_labels,
# use_cache=use_cache,
# output_attentions=output_attentions,
# output_hidden_states=output_hidden_states,
# return_dict=return_dict,
# )
# # === Otherwise =>> Assume Invalid! ===
# elif (input_ids.shape[0] != pixel_values.shape[0]) or (inputs_embeds.shape[0] != pixel_values.shape[0]):
# raise ValueError("Non-homogenous batch of (text, image) input -- forward() does not support mixed batches!")
# else:
# raise ValueError(
# "Invalid PrismaticForConditionalGeneration `forward()` call with provided arguments:\n"
# f"=> `input_ids` = {input_ids is not None}\n"
# f"=> `attention_mask` = {attention_mask is not None}\n"
# f"=> `pixel_values` = {pixel_values is not None}\n"
# f"=> `labels` = {labels is not None}\n"
# f"=> `input_embeds` = {inputs_embeds is not None}\n"
# f"=> `past_key_values` = {past_key_values is not None}\n"
# f"=> `use_cache` = {use_cache}"
# )
# # Unpack `language_model_output` and return PrismaticCausalLMOutputWithPast (or tuple if not `return_dict`)
# if not return_dict:
# if output_projector_features and (projected_patch_embeddings is not None):
# return *language_model_output, projected_patch_embeddings
# return language_model_output
# return PrismaticCausalLMOutputWithPast(
# loss=language_model_output.loss,
# logits=language_model_output.logits,
# past_key_values=language_model_output.past_key_values,
# hidden_states=language_model_output.hidden_states,
# attentions=language_model_output.attentions,
# projector_features=projected_patch_embeddings,
# )
# === GenerationMixin Methods ===
def prepare_inputs_for_generation(
self,
input_ids: Optional[torch.Tensor] = None,
past_key_values: Optional[List[torch.FloatTensor]] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
**kwargs: str,
) -> Dict[str, torch.Tensor]:
"""Borrowed from `LlamaForCausalLM` and simplified for batch size = 1; mirrors original PrismaticVLM logic."""
if ((input_ids is not None) and (input_ids.shape[0] > 1)) or (
(inputs_embeds is not None) and (inputs_embeds.shape[0] > 1)
):
raise ValueError("Generation with batch size > 1 is not currently supported!")
# Handle `past_key_values` (cache) =>> assume `input_ids` just has unprocessed tokens
if past_key_values is not None:
input_ids = input_ids[:, -1:]
# If `input_embeds` are passed, we only want to use them in the 1st generation step
if inputs_embeds is not None and past_key_values is None:
model_inputs = {"input_embeds": inputs_embeds}
else:
model_inputs = {"input_ids": input_ids}
# Make sure `pixel_values` are preserved in `model_inputs`
model_inputs.update(
{
"attention_mask": attention_mask,
"pixel_values": pixel_values,
"past_key_values": past_key_values,
"use_cache": kwargs.get("use_cache"),
}
)
return model_inputs
# Defer to Language Model (all handle this differently, with different return types)
def _reorder_cache(self, *args, **kwargs) -> Any:
return self.language_model._reorder_cache(*args, **kwargs)
def _prepare_input_for_action_prediction_verl(self, input_ids, attention_mask):
"""Prepares input for action prediction by adding necessary tokens"""
# Add (ACTION_DIM * NUM_ACTIONS_CHUNK) placeholder tokens to input_ids to simulate action tokens
placeholder_action_token_ids = (
torch.ones((input_ids.shape[0], ACTION_DIM * NUM_ACTIONS_CHUNK)).to(input_ids.device).to(input_ids.dtype)
)
input_ids = torch.cat([input_ids, placeholder_action_token_ids], dim=-1)
# Add stop token to sequence (needed in non-causal bi-directional self-attention, as it appears at train time)
stop_token_id = torch.ones((input_ids.shape[0], 1)).to(input_ids.device).to(input_ids.dtype) * STOP_INDEX
input_ids = torch.cat([input_ids, stop_token_id], dim=-1)
# Extend the attention mask to fit the new shape of input
# Note: Only batch size == 1 supported right now
mask_extension = (
torch.ones((attention_mask.shape[0], input_ids.shape[-1] - attention_mask.shape[-1]))
.to(attention_mask.device)
.to(attention_mask.dtype)
)
attention_mask = torch.cat([attention_mask, mask_extension], dim=-1)
return input_ids, attention_mask
def _prepare_labels_for_action_prediction_verl(self, labels, input_ids):
"""Creates labels tensor for action prediction if not provided"""
# Extend labels tensor with fake action labels
ARBITRARY_ACTION_TOKEN_IDX = ACTION_TOKEN_BEGIN_IDX + 1
labels_extension = (
torch.ones((labels.shape[0], input_ids.shape[-1] - labels.shape[-1])).to(labels.device).to(labels.dtype)
* ARBITRARY_ACTION_TOKEN_IDX
)
labels = torch.cat([labels, labels_extension], dim=-1)
# Replace last label token with stop token
labels[:, -1] = STOP_INDEX
return labels
def _verl_discrete_compute_logits(
self,
input_embeddings,
all_actions_mask,
projected_patch_embeddings,
attention_mask,
labels,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
action_head=None,
):#contintue!!!!!
"""Run L1 regression-based continuous action prediction or discrete action tokens prediction."""
# Zero out action token embeddings
all_actions_mask = all_actions_mask.unsqueeze(-1) # (B, seq_len, 1)
input_embeddings = input_embeddings * ~all_actions_mask
# Build multimodal embeddings and attention mask
multimodal_embeddings, multimodal_attention_mask = self._build_multimodal_attention(
input_embeddings, projected_patch_embeddings, attention_mask
)
# Forward pass through language model
language_model_output = self.language_model(
input_ids=None,
attention_mask=multimodal_attention_mask,
position_ids=None,
past_key_values=None,
inputs_embeds=multimodal_embeddings,
labels=None,
use_cache=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
)
# Extract hidden states for action tokens
#last_hidden_states = language_model_output.hidden_states[-1] # (B, seq_len, D)
# actions_hidden_states = last_hidden_states[
# :,
# NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
# :,
# ] # (B, act_chunk_len, D)
# Handle different prediction methods
# if action_head is not None:
# # L1 regression prediction
# normalized_actions = action_head.predict_action(actions_hidden_states)
# normalized_actions = normalized_actions.reshape(NUM_ACTIONS_CHUNK, ACTION_DIM)
# normalized_actions = normalized_actions.float().cpu().detach().numpy()
# else:
# Discrete token-based prediction
compute_logits = language_model_output.logits[
:,
NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
]
return compute_logits
# def forward(
# self,
# input_ids: Optional[torch.LongTensor] = None,
# unnorm_key: Optional[str] = None,
# proprio=None,
# proprio_projector=None,
# action_head=None,
# noisy_action_projector=None,
# use_film: bool = False,
# **kwargs: str,
# ) :
# """Predict actions from input sequence, with options for different prediction methods.
# Args:
# input_ids: Input token ids
# unnorm_key: Key for unnormalization statistics
# proprio: Proprioceptive features
# proprio_projector: Projector for proprioceptive features
# action_head: Optional head for L1 regression or diffusion-based prediction
# noisy_action_projector: Projector for noisy actions in diffusion-based prediction
# use_film: Whether to use FiLM conditioning
# **kwargs: Additional arguments including pixel_values and attention_mask
# Returns:
# Tuple of (unnormalized_actions, action_hidden_states)
# """
# # If the special empty token ('') does not already appear after the colon (':') token in the prompt
# # (after "OUT:" or "ASSISTANT:"), insert it to match the inputs seen at training time
# # if not torch.all(input_ids[:, -1] == 29871):
# # input_ids = torch.cat(
# # (input_ids, torch.unsqueeze(torch.Tensor([29871]).long(), dim=0).to(input_ids.device)), dim=1
# # )
# #print("!!!!!!!!!!!!!!Entering forward!!!!!!!!!!")
# pixel_values = kwargs["pixel_values"]
# attention_mask = kwargs["attention_mask"]
# # Create fake labels tensor (needed for action mask)
# labels = input_ids.clone()
# labels[:] = IGNORE_INDEX
# # Get number of tokens in prompt (excluding the start token)
# NUM_PROMPT_TOKENS = input_ids.shape[-1] - 1 # Subtract action tokens and stop token
# # Prepare inputs by adding necessary tokens
# #input_ids, attention_mask = self._prepare_input_for_action_prediction_verl(input_ids, attention_mask)
# #test
# placeholder_action_token_ids = (
# torch.ones((input_ids.shape[0], ACTION_DIM * NUM_ACTIONS_CHUNK)).to(input_ids.device).to(input_ids.dtype)
# )
# input_ids = torch.cat([input_ids, placeholder_action_token_ids], dim=-1)
# # Add stop token to sequence (needed in non-causal bi-directional self-attention, as it appears at train time)
# stop_token_id = torch.ones((input_ids.shape[0], 1)).to(input_ids.device).to(input_ids.dtype) * STOP_INDEX
# input_ids = torch.cat([input_ids, stop_token_id], dim=-1)
# # Extend the attention mask to fit the new shape of input
# # Note: Only batch size == 1 supported right now
# mask_extension = (
# torch.ones((attention_mask.shape[0], input_ids.shape[-1] - attention_mask.shape[-1]))
# .to(attention_mask.device)
# .to(attention_mask.dtype)
# )
# attention_mask = torch.cat([attention_mask, mask_extension], dim=-1)
# #return input_ids, attention_mask
# #test end
# # Update labels tensor for action mask computation later
# #labels = self._prepare_labels_for_action_prediction_verl(labels, input_ids)
# #test
# ARBITRARY_ACTION_TOKEN_IDX = ACTION_TOKEN_BEGIN_IDX + 1
# labels_extension = (
# torch.ones((labels.shape[0], input_ids.shape[-1] - labels.shape[-1])).to(labels.device).to(labels.dtype)
# * ARBITRARY_ACTION_TOKEN_IDX
# )
# labels = torch.cat([labels, labels_extension], dim=-1)
# # Replace last label token with stop token
# labels[:, -1] = STOP_INDEX
# #return labels
# #test ed
# # Get input embeddings and action masks
# input_embeddings = self.get_input_embeddings()(input_ids)
# #all_actions_mask = self._process_action_masks(labels)
# #test
# #current_action_mask = get_current_action_mask(labels)
# newline_positions = labels != IGNORE_INDEX
# # Calculate cumulative sum to identify regions between newlines
# cumsum = torch.cumsum(newline_positions, dim=1)
# # Create the mask
# mask = (1 <= cumsum) & (cumsum <= ACTION_DIM)
# # Extract the action part only
# action_tokens_only_mask = labels > ACTION_TOKEN_BEGIN_IDX
# current_action_mask = action_tokens_only_mask * mask
# #next_actions_mask = get_next_actions_mask(labels)
# newline_positions = labels != IGNORE_INDEX
# # Calculate cumulative sum to identify regions between newlines
# cumsum = torch.cumsum(newline_positions, dim=1)
# # Create the mask
# mask = cumsum > ACTION_DIM
# # Extract the action part only
# action_tokens_only_mask = labels > ACTION_TOKEN_BEGIN_IDX
# next_actions_mask = action_tokens_only_mask * mask
# all_actions_mask = current_action_mask | next_actions_mask # (B, seq_len)
# #test end
# # Extract language embeddings
# language_embeddings = input_embeddings[~all_actions_mask].reshape(
# input_embeddings.shape[0], -1, input_embeddings.shape[2]
# )
# # Process vision features
# #projected_patch_embeddings = self._process_vision_features(pixel_values, language_embeddings, use_film)
# #test
# if use_film:
# # FiLM: Infuse language inputs into visual features
# raise ValueError
# patch_features = self.vision_backbone(pixel_values, language_embeddings) # (bsz, 256 * num_images, D)
# else:
# patch_features = self.vision_backbone(pixel_values) # (bsz, 256 * num_images, D)
# projected_patch_embeddings = self.projector(patch_features)
# #test end
# # Add proprioceptive features if provided
# use_proprio = proprio_projector is not None and proprio is not None
# if use_proprio:
# proprio = torch.Tensor(proprio).to(projected_patch_embeddings.device, dtype=projected_patch_embeddings.dtype)
# projected_patch_embeddings = self._process_proprio_features(
# projected_patch_embeddings, proprio, proprio_projector
# )
# # Use diffusion if provided, otherwise use regression or discrete prediction
# use_diffusion = noisy_action_projector is not None and hasattr(action_head, "noise_scheduler")
# # Calculate number of patches (including proprio token and/or diffusion timestep embedding if present)
# NUM_PATCHES = self.vision_backbone.get_num_patches() * self.vision_backbone.get_num_images_in_input()
# if use_proprio:
# NUM_PATCHES += 1
# if use_diffusion:
# NUM_PATCHES += 1
# if use_diffusion:
# raise ValueError
# # Sample random noise with shape equal to output action, used as the starting state for reverse diffusion
# noise = torch.randn(
# size=(1, NUM_ACTIONS_CHUNK, ACTION_DIM), device=input_embeddings.device, dtype=input_embeddings.dtype
# )
# # Run diffusion-based prediction
# normalized_actions, actions_hidden_states = self._run_diffusion_prediction(
# input_embeddings,
# all_actions_mask,
# noise,
# action_head,
# projected_patch_embeddings,
# labels,
# attention_mask,
# NUM_PATCHES,
# NUM_PROMPT_TOKENS,
# noisy_action_projector,
# )
# else:
# # Run regression or discrete token-based prediction
# # compute_logits = self._verl_discrete_compute_logits(
# # input_embeddings,
# # all_actions_mask,
# # projected_patch_embeddings,
# # attention_mask,
# # labels,
# # NUM_PATCHES,
# # NUM_PROMPT_TOKENS,
# # action_head,
# # )
# #test
# all_actions_mask = all_actions_mask.unsqueeze(-1) # (B, seq_len, 1)
# input_embeddings = input_embeddings * ~all_actions_mask
# # Build multimodal embeddings and attention mask
# # multimodal_embeddings, multimodal_attention_mask = self._build_multimodal_attention(
# # input_embeddings, projected_patch_embeddings, attention_mask
# # )
# #test
# projected_patch_attention_mask = None
# if attention_mask is not None:
# projected_patch_attention_mask = torch.full(
# (projected_patch_embeddings.shape[0], projected_patch_embeddings.shape[1]),
# fill_value=True,
# dtype=attention_mask.dtype,
# device=attention_mask.device,
# )
# # Build multimodal embeddings & attention mask; insert embeddings after <BOS> token (1:)
# multimodal_embeddings = torch.cat(
# [input_embeddings[:, :1, :], projected_patch_embeddings, input_embeddings[:, 1:, :]], dim=1
# )
# multimodal_attention_mask = None
# if attention_mask is not None:
# multimodal_attention_mask = torch.cat(
# [attention_mask[:, :1], projected_patch_attention_mask, attention_mask[:, 1:]], dim=1
# )
# #return multimodal_embeddings, multimodal_attention_mask
# #test end
# # Forward pass through language model
# language_model_output = self.language_model(
# input_ids=None,
# attention_mask=multimodal_attention_mask,
# position_ids=None,
# past_key_values=None,
# inputs_embeds=multimodal_embeddings,
# labels=None,
# use_cache=None,
# output_attentions=False,
# output_hidden_states=False,
# return_dict=True,
# )
# compute_logits = language_model_output.logits[
# :,
# NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
# ]
# #test end
# return compute_logits
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values=None,
attention_mask=None,
#labels=None,
proprio=None,
proprio_projector=None,
action_head=None,
noisy_action_projector=None,
use_film: bool = False,
**kwargs: str,
) :
"""Predict actions from input sequence, with options for different prediction methods.
Args:
input_ids: Input token ids
unnorm_key: Key for unnormalization statistics
proprio: Proprioceptive features
proprio_projector: Projector for proprioceptive features
action_head: Optional head for L1 regression or diffusion-based prediction
noisy_action_projector: Projector for noisy actions in diffusion-based prediction
use_film: Whether to use FiLM conditioning
**kwargs: Additional arguments including pixel_values and attention_mask
Returns:
Tuple of (unnormalized_actions, action_hidden_states)
"""
# If the special empty token ('') does not already appear after the colon (':') token in the prompt
# (after "OUT:" or "ASSISTANT:"), insert it to match the inputs seen at training time
# if not torch.all(input_ids[:, -1] == 29871):
# input_ids = torch.cat(
# (input_ids, torch.unsqueeze(torch.Tensor([29871]).long(), dim=0).to(input_ids.device)), dim=1
# )
#pixel_values = kwargs["pixel_values"]
#attention_mask = kwargs["attention_mask"]
# Create fake labels tensor (needed for action mask)
labels = input_ids.clone()
labels[:] = IGNORE_INDEX
# # Get number of tokens in prompt (excluding the start token)
NUM_PROMPT_TOKENS = input_ids.shape[-1] - 1 # Subtract action tokens and stop token
# # Prepare inputs by adding necessary tokens
# #input_ids, attention_mask = self._prepare_input_for_action_prediction_verl(input_ids, attention_mask)
# #test
placeholder_action_token_ids = (
torch.ones((input_ids.shape[0], ACTION_DIM * NUM_ACTIONS_CHUNK)).to(input_ids.device).to(input_ids.dtype)
)
input_ids = torch.cat([input_ids, placeholder_action_token_ids], dim=-1)
# Add stop token to sequence (needed in non-causal bi-directional self-attention, as it appears at train time)
stop_token_id = torch.ones((input_ids.shape[0], 1)).to(input_ids.device).to(input_ids.dtype) * STOP_INDEX
input_ids = torch.cat([input_ids, stop_token_id], dim=-1)
# Extend the attention mask to fit the new shape of input
# Note: Only batch size == 1 supported right now
mask_extension = (
torch.ones((attention_mask.shape[0], input_ids.shape[-1] - attention_mask.shape[-1]))
.to(attention_mask.device)
.to(attention_mask.dtype)
)
attention_mask = torch.cat([attention_mask, mask_extension], dim=-1)
ARBITRARY_ACTION_TOKEN_IDX = ACTION_TOKEN_BEGIN_IDX + 1
labels_extension = (
torch.ones((labels.shape[0], input_ids.shape[-1] - labels.shape[-1])).to(labels.device).to(labels.dtype)
* ARBITRARY_ACTION_TOKEN_IDX
)
labels = torch.cat([labels, labels_extension], dim=-1)
# # Replace last label token with stop token
labels[:, -1] = STOP_INDEX
# Get input embeddings and action masks
#NUM_PROMPT_TOKENS = kwargs["num_prompt_tokens"]
input_embeddings = self.get_input_embeddings()(input_ids)
#all_actions_mask = self._process_action_masks(labels)
#test
#current_action_mask = get_current_action_mask(labels)
newline_positions = labels != IGNORE_INDEX
# Calculate cumulative sum to identify regions between newlines
cumsum = torch.cumsum(newline_positions, dim=1)
# Create the mask
mask = (1 <= cumsum) & (cumsum <= ACTION_DIM)
# Extract the action part only
action_tokens_only_mask = labels > ACTION_TOKEN_BEGIN_IDX
current_action_mask = action_tokens_only_mask * mask
#next_actions_mask = get_next_actions_mask(labels)
newline_positions = labels != IGNORE_INDEX
# Calculate cumulative sum to identify regions between newlines
cumsum = torch.cumsum(newline_positions, dim=1)
# Create the mask
mask = cumsum > ACTION_DIM
# Extract the action part only
action_tokens_only_mask = labels > ACTION_TOKEN_BEGIN_IDX
next_actions_mask = action_tokens_only_mask * mask
all_actions_mask = current_action_mask | next_actions_mask # (B, seq_len)
#test end
# Extract language embeddings
language_embeddings = input_embeddings[~all_actions_mask].reshape(
input_embeddings.shape[0], -1, input_embeddings.shape[2]
)
# Process vision features
#projected_patch_embeddings = self._process_vision_features(pixel_values, language_embeddings, use_film)
#test
if use_film:
# FiLM: Infuse language inputs into visual features
raise ValueError
patch_features = self.vision_backbone(pixel_values, language_embeddings) # (bsz, 256 * num_images, D)
else:
patch_features = self.vision_backbone(pixel_values) # (bsz, 256 * num_images, D)
projected_patch_embeddings = self.projector(patch_features)
#test end
# Add proprioceptive features if provided
use_proprio = proprio_projector is not None and proprio is not None
if use_proprio:
proprio = torch.Tensor(proprio).to(projected_patch_embeddings.device, dtype=projected_patch_embeddings.dtype)
projected_patch_embeddings = self._process_proprio_features(
projected_patch_embeddings, proprio, proprio_projector
)
# Use diffusion if provided, otherwise use regression or discrete prediction
use_diffusion = noisy_action_projector is not None and hasattr(action_head, "noise_scheduler")
# Calculate number of patches (including proprio token and/or diffusion timestep embedding if present)
NUM_PATCHES = self.vision_backbone.get_num_patches() * self.vision_backbone.get_num_images_in_input()
if use_proprio:
NUM_PATCHES += 1
if use_diffusion:
NUM_PATCHES += 1
if use_diffusion:
raise ValueError
# Sample random noise with shape equal to output action, used as the starting state for reverse diffusion
noise = torch.randn(
size=(1, NUM_ACTIONS_CHUNK, ACTION_DIM), device=input_embeddings.device, dtype=input_embeddings.dtype
)
# Run diffusion-based prediction
normalized_actions, actions_hidden_states = self._run_diffusion_prediction(
input_embeddings,
all_actions_mask,
noise,
action_head,
projected_patch_embeddings,
labels,
attention_mask,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
noisy_action_projector,
)
else:
# Run regression or discrete token-based prediction
# compute_logits = self._verl_discrete_compute_logits(
# input_embeddings,
# all_actions_mask,
# projected_patch_embeddings,
# attention_mask,
# labels,
# NUM_PATCHES,
# NUM_PROMPT_TOKENS,
# action_head,
# )
#test
all_actions_mask = all_actions_mask.unsqueeze(-1) # (B, seq_len, 1)
input_embeddings = input_embeddings * ~all_actions_mask
# Build multimodal embeddings and attention mask
# multimodal_embeddings, multimodal_attention_mask = self._build_multimodal_attention(
# input_embeddings, projected_patch_embeddings, attention_mask
# )
#test
projected_patch_attention_mask = None
if attention_mask is not None:
projected_patch_attention_mask = torch.full(
(projected_patch_embeddings.shape[0], projected_patch_embeddings.shape[1]),
fill_value=True,
dtype=attention_mask.dtype,
device=attention_mask.device,
)
# Build multimodal embeddings & attention mask; insert embeddings after <BOS> token (1:)
multimodal_embeddings = torch.cat(
[input_embeddings[:, :1, :], projected_patch_embeddings, input_embeddings[:, 1:, :]], dim=1
)
multimodal_attention_mask = None
if attention_mask is not None:
multimodal_attention_mask = torch.cat(
[attention_mask[:, :1], projected_patch_attention_mask, attention_mask[:, 1:]], dim=1
)
#return multimodal_embeddings, multimodal_attention_mask
#test end
# Forward pass through language model
language_model_output = self.language_model(
input_ids=None,
attention_mask=multimodal_attention_mask,
position_ids=None,
past_key_values=None,
inputs_embeds=multimodal_embeddings,
labels=None,
use_cache=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
)
compute_logits = language_model_output.logits[
:,
NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
]
#test end
return compute_logits
class OpenVLAForActionPrediction(PrismaticForConditionalGeneration):
config_class: PretrainedConfig = OpenVLAConfig
def __init__(self, config: OpenVLAConfig) -> None:
super().__init__(config)
self.norm_stats = config.norm_stats
# Compute action bins
self.bins = np.linspace(-1, 1, config.n_action_bins)
self.bin_centers = (self.bins[:-1] + self.bins[1:]) / 2.0
# Compute vocab size for de-tokenization -- revert added "multiple of"
self.vocab_size = self.config.text_config.vocab_size - self.config.pad_to_multiple_of
def _prepare_input_for_action_prediction(self, input_ids, attention_mask):
"""Prepares input for action prediction by adding necessary tokens"""
# Add (ACTION_DIM * NUM_ACTIONS_CHUNK) placeholder tokens to input_ids to simulate action tokens
placeholder_action_token_ids = (
torch.ones((input_ids.shape[0], ACTION_DIM * NUM_ACTIONS_CHUNK)).to(input_ids.device).to(input_ids.dtype)
)
input_ids = torch.cat([input_ids, placeholder_action_token_ids], dim=-1)
# Add stop token to sequence (needed in non-causal bi-directional self-attention, as it appears at train time)
stop_token_id = torch.ones((input_ids.shape[0], 1)).to(input_ids.device).to(input_ids.dtype) * STOP_INDEX
input_ids = torch.cat([input_ids, stop_token_id], dim=-1)
# Extend the attention mask to fit the new shape of input
# Note: Only batch size == 1 supported right now
mask_extension = (
torch.ones((attention_mask.shape[0], input_ids.shape[-1] - attention_mask.shape[-1]))
.to(attention_mask.device)
.to(attention_mask.dtype)
)
attention_mask = torch.cat([attention_mask, mask_extension], dim=-1)
return input_ids, attention_mask
def _prepare_labels_for_action_prediction(self, labels, input_ids):
"""Creates labels tensor for action prediction if not provided"""
# Extend labels tensor with fake action labels
ARBITRARY_ACTION_TOKEN_IDX = ACTION_TOKEN_BEGIN_IDX + 1
labels_extension = (
torch.ones((labels.shape[0], input_ids.shape[-1] - labels.shape[-1])).to(labels.device).to(labels.dtype)
* ARBITRARY_ACTION_TOKEN_IDX
)
labels = torch.cat([labels, labels_extension], dim=-1)
# Replace last label token with stop token
labels[:, -1] = STOP_INDEX
return labels
def _unnormalize_actions(self, normalized_actions, unnorm_key=None):
"""Unnormalize actions using dataset statistics"""
action_norm_stats = self.get_action_stats(unnorm_key)
if ACTION_PROPRIO_NORMALIZATION_TYPE == NormalizationType.BOUNDS:
mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["min"], dtype=bool))
action_high, action_low = np.array(action_norm_stats["max"]), np.array(action_norm_stats["min"])
elif ACTION_PROPRIO_NORMALIZATION_TYPE == NormalizationType.BOUNDS_Q99:
mask = action_norm_stats.get("mask", np.ones_like(action_norm_stats["q01"], dtype=bool))
action_high, action_low = np.array(action_norm_stats["q99"]), np.array(action_norm_stats["q01"])
else:
raise ValueError("Unsupported action/proprio normalization type detected!")
actions = np.where(
mask,
0.5 * (normalized_actions + 1) * (action_high - action_low + 1e-8) + action_low,
normalized_actions,
)
return actions
def _run_diffusion_prediction(
self,
input_embeddings,
all_actions_mask,
noise,
action_head,
projected_patch_embeddings,
labels,
attention_mask,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
noisy_action_projector,
):
"""Run diffusion-based action prediction"""
# Set diffusion timestep values
action_head.noise_scheduler.set_timesteps(action_head.num_diffusion_steps)
# Clone embedding for reuse in each timestep
orig_projected_patch_embeddings = projected_patch_embeddings.clone()
curr_noisy_actions = noise
# Reverse diffusion: Iteratively denoise to generate action prediction
for t in action_head.noise_scheduler.timesteps:
# Get diffusion model's noise prediction (conditioned on VLA latent embedding, current noisy action
# embedding, and diffusion timestep embedding)
timesteps = torch.Tensor([t]).to(labels.device)
diffusion_timestep_embeddings = (
action_head.time_encoder(timesteps).to(curr_noisy_actions.dtype).to(curr_noisy_actions.device)
) # (B, llm_dim)
diffusion_timestep_embeddings = diffusion_timestep_embeddings.unsqueeze(1) # (B, 1, llm_dim)
# [Diffusion] Replace the embeddings of the action tokens with noisy actions
# (Later on, the positional embeddings will be added to them)
# For simplicity, append diffusion timestep embedding to the end of projected vision tokens
projected_patch_embeddings = torch.cat(
(orig_projected_patch_embeddings, diffusion_timestep_embeddings), dim=1
)
# Reshape and project noisy actions into language embedding space
B = curr_noisy_actions.shape[0]
orig_curr_noisy_actions_shape = curr_noisy_actions.shape
curr_noisy_actions = curr_noisy_actions.reshape(B, -1).unsqueeze(-1)
noisy_action_features = noisy_action_projector(curr_noisy_actions)
curr_noisy_actions = curr_noisy_actions.reshape(orig_curr_noisy_actions_shape)
# Replace action token embeddings with noisy action embeddings
input_embeddings = self._replace_input_embeddings(
input_embeddings.clone(), all_actions_mask, noisy_action_features
)
# Build multimodal embeddings and attention mask
multimodal_embeddings, multimodal_attention_mask = self._build_multimodal_attention(
input_embeddings, projected_patch_embeddings, attention_mask
)
# Forward pass through language model
language_model_output = self.language_model(
input_ids=None,
attention_mask=multimodal_attention_mask,
position_ids=None,
past_key_values=None,
inputs_embeds=multimodal_embeddings,
labels=None,
use_cache=None,
output_attentions=False,
output_hidden_states=True,
return_dict=True,
)
# Extract hidden states for action portion of response
last_hidden_states = language_model_output.hidden_states[-1] # (B, seq_len, D)
actions_hidden_states = last_hidden_states[
:,
NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
:,
] # (B, act_chunk_len, D)
# Predict noise and update noisy actions: x_t -> x_{t-1}
noise_pred = action_head.predict_noise(actions_hidden_states)
curr_noisy_actions = action_head.noise_scheduler.step(noise_pred, t, curr_noisy_actions).prev_sample
curr_noisy_actions = curr_noisy_actions.reshape(NUM_ACTIONS_CHUNK, ACTION_DIM)
# Return final actions
return curr_noisy_actions.float().cpu().detach().numpy(), actions_hidden_states
def _regression_or_discrete_prediction(
self,
input_embeddings,
all_actions_mask,
projected_patch_embeddings,
attention_mask,
labels,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
action_head=None,
):
"""Run L1 regression-based continuous action prediction or discrete action tokens prediction."""
# Zero out action token embeddings
all_actions_mask = all_actions_mask.unsqueeze(-1) # (B, seq_len, 1)
input_embeddings = input_embeddings * ~all_actions_mask
# Build multimodal embeddings and attention mask
multimodal_embeddings, multimodal_attention_mask = self._build_multimodal_attention(
input_embeddings, projected_patch_embeddings, attention_mask
)
# Forward pass through language model
language_model_output = self.language_model(
input_ids=None,
attention_mask=multimodal_attention_mask,
position_ids=None,
past_key_values=None,
inputs_embeds=multimodal_embeddings,
labels=None,
use_cache=None,
output_attentions=False,
output_hidden_states=True,
return_dict=True,
)
# Extract hidden states for action tokens
last_hidden_states = language_model_output.hidden_states[-1] # (B, seq_len, D)
actions_hidden_states = last_hidden_states[
:,
NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
:,
] # (B, act_chunk_len, D)
# Handle different prediction methods
if action_head is not None:
# L1 regression prediction
normalized_actions = action_head.predict_action(actions_hidden_states)
normalized_actions = normalized_actions.reshape(NUM_ACTIONS_CHUNK, ACTION_DIM)
normalized_actions = normalized_actions.float().cpu().detach().numpy()
else:
# Discrete token-based prediction
predicted_action_token_ids = (
language_model_output.logits[
:,
NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
]
.argmax(dim=2)
.cpu()
.numpy()
)
discretized_actions = self.vocab_size - predicted_action_token_ids
discretized_actions = np.clip(discretized_actions - 1, a_min=0, a_max=self.bin_centers.shape[0] - 1)
normalized_actions = self.bin_centers[discretized_actions]
normalized_actions = normalized_actions.reshape(NUM_ACTIONS_CHUNK, ACTION_DIM)
return normalized_actions, actions_hidden_states
def _verl_discrete_prediction(
self,
input_embeddings,
all_actions_mask,
projected_patch_embeddings,
attention_mask,
labels,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
action_head=None,
do_sample=True,
temperature=1,
):
"""Run L1 regression-based continuous action prediction or discrete action tokens prediction."""
# Zero out action token embeddings
all_actions_mask = all_actions_mask.unsqueeze(-1) # (B, seq_len, 1)
input_embeddings = input_embeddings * ~all_actions_mask
# Build multimodal embeddings and attention mask
multimodal_embeddings, multimodal_attention_mask = self._build_multimodal_attention(
input_embeddings, projected_patch_embeddings, attention_mask
)
# Forward pass through language model
language_model_output = self.language_model(
input_ids=None,
attention_mask=multimodal_attention_mask,
position_ids=None,
past_key_values=None,
inputs_embeds=multimodal_embeddings,
labels=None,
use_cache=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
)
# Extract hidden states for action tokens
#last_hidden_states = language_model_output.hidden_states[-1] # (B, seq_len, D)
# actions_hidden_states = last_hidden_states[
# :,
# NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
# :,
# ] # (B, act_chunk_len, D)
# Handle different prediction methods
# if action_head is not None:
# # L1 regression prediction
# normalized_actions = action_head.predict_action(actions_hidden_states)
# normalized_actions = normalized_actions.reshape(NUM_ACTIONS_CHUNK, ACTION_DIM)
# normalized_actions = normalized_actions.float().cpu().detach().numpy()
# else:
# Discrete token-based prediction
#test
# NUM_PROMPT_TOKENS = NUM_PROMPT_TOKENS + NUM_PATCHES
# j = torch.arange(language_model_output.logits.shape[1], device=NUM_PROMPT_TOKENS.device)
# start = NUM_PROMPT_TOKENS.unsqueeze(1)
# end = start + ACTION_DIM * NUM_ACTIONS_CHUNK
# mask_2d = (j >= start) & (j < end)
# mask = mask_2d.unsqueeze(-1)
# actions_masks = mask.expand_as(language_model_output.logits)
NUM_PROMPT_TOKENS = NUM_PROMPT_TOKENS + NUM_PATCHES
batch_size = language_model_output.logits.shape[0]
device = language_model_output.logits.device
start_indices = NUM_PROMPT_TOKENS.unsqueeze(1) # [batch_size, 1]
position_offsets = torch.arange(ACTION_DIM * NUM_ACTIONS_CHUNK, device=device).unsqueeze(0) # [1, seq_length]
seq_indices = start_indices + position_offsets # [batch_size, ACTION_DIM*NUM_ACTIONS_CHUNK]
#test end
#test add
#print("language_model_output",language_model_output.logits.shape[-1])
#print("self.vocab_size",self.vocab_size) 32000
#topk_values, topk_indices = torch.topk(language_model_output.logits, k=256, dim=-1)
#print(topk_indices)
#assert language_model_output.logits.shape[-1] == self.vocab_size
#test add
if do_sample == False:
#org
# reponse_ids = language_model_output.logits[
# :,
# NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
# ].argmax(dim=2)
#reponse_ids = language_model_output.logits[actions_masks].argmax(dim=2)
#org end
#padding
# reponse_ids = language_model_output.logits[
# torch.arange(batch_size, device=device).unsqueeze(-1),
# seq_indices,
# :
# ].argmax(dim=2)
#padding end
#padding + only get last 256 token
reponse_ids_logits = language_model_output.logits[
torch.arange(batch_size, device=device).unsqueeze(-1),
seq_indices,
:
]
start_index = self.vocab_size - 256
response_last256 = reponse_ids_logits[..., -256-64:-64] # Shape: [batch_size, seq_len, 256]
last256_argmax = response_last256.argmax(dim=-1) # Shape: [batch_size, seq_len]
reponse_ids = last256_argmax + start_index # Shape: [batch_size, seq_len]
#padding + only get last 256 token end
predicted_action_token_ids = reponse_ids.cpu().numpy()
else:
assert temperature>0
#org
# action_logits = language_model_output.logits[
# :,
# NUM_PATCHES + NUM_PROMPT_TOKENS : NUM_PATCHES + NUM_PROMPT_TOKENS + ACTION_DIM * NUM_ACTIONS_CHUNK,
# ]
#action_logits = language_model_output.logits[actions_masks]
#org end
action_logits = language_model_output.logits[
torch.arange(batch_size, device=device).unsqueeze(-1),
seq_indices,
:
]
# padding
# scaled_logits = action_logits / temperature
# probs = torch.softmax(scaled_logits, dim=-1)
# probs_flat = probs.reshape(-1, probs.shape[-1]) # (B*act_chunk_len, vocab_size)
# sampled_indices_flat = torch.multinomial(probs_flat, num_samples=1) # (B*act_chunk_len, 1)
# reponse_ids = sampled_indices_flat.view(action_logits.shape[0], -1)
# padding end
#padding + only get last 256 token
action_logits_last256 = action_logits[..., -256-64:-64]
scaled_logits = action_logits_last256 / temperature
probs = torch.softmax(scaled_logits, dim=-1)
assert probs.shape[-1] == 256
probs_flat = probs.reshape(-1, probs.shape[-1])
sampled_indices_flat = torch.multinomial(probs_flat, num_samples=1)
original_ids_flat = sampled_indices_flat + (self.vocab_size - 256)
reponse_ids = original_ids_flat.view(action_logits.shape[0], -1)
#padding + only get last 256 token end
predicted_action_token_ids = reponse_ids.cpu().numpy()
discretized_actions = self.vocab_size - predicted_action_token_ids
discretized_actions = np.clip(discretized_actions - 1, a_min=0, a_max=self.bin_centers.shape[0] - 1)
normalized_actions = self.bin_centers[discretized_actions]
#normalized_actions = normalized_actions.reshape(NUM_ACTIONS_CHUNK, ACTION_DIM)
normalized_actions = normalized_actions.reshape(-1, ACTION_DIM)
return normalized_actions, reponse_ids
#return normalized_actions, actions_hidden_states
def predict_action(
self,
input_ids: Optional[torch.LongTensor] = None,
unnorm_key: Optional[str] = None,
proprio=None,
proprio_projector=None,
action_head=None,
noisy_action_projector=None,
use_film: bool = False,
**kwargs: str,
) -> np.ndarray:
"""Predict actions from input sequence, with options for different prediction methods.
Args:
input_ids: Input token ids
unnorm_key: Key for unnormalization statistics
proprio: Proprioceptive features
proprio_projector: Projector for proprioceptive features
action_head: Optional head for L1 regression or diffusion-based prediction
noisy_action_projector: Projector for noisy actions in diffusion-based prediction
use_film: Whether to use FiLM conditioning
**kwargs: Additional arguments including pixel_values and attention_mask
Returns:
Tuple of (unnormalized_actions, action_hidden_states)
"""
# If the special empty token ('') does not already appear after the colon (':') token in the prompt
# (after "OUT:" or "ASSISTANT:"), insert it to match the inputs seen at training time
if not torch.all(input_ids[:, -1] == 29871):
input_ids = torch.cat(
(input_ids, torch.unsqueeze(torch.Tensor([29871]).long(), dim=0).to(input_ids.device)), dim=1
)
pixel_values = kwargs["pixel_values"]
attention_mask = kwargs["attention_mask"]
# Create fake labels tensor (needed for action mask)
labels = input_ids.clone()
labels[:] = IGNORE_INDEX
# Get number of tokens in prompt (excluding the start token)
NUM_PROMPT_TOKENS = input_ids.shape[-1] - 1 # Subtract action tokens and stop token
# Prepare inputs by adding necessary tokens
input_ids, attention_mask = self._prepare_input_for_action_prediction(input_ids, attention_mask)
# Update labels tensor for action mask computation later
labels = self._prepare_labels_for_action_prediction(labels, input_ids)
# Get input embeddings and action masks
input_embeddings = self.get_input_embeddings()(input_ids)
all_actions_mask = self._process_action_masks(labels)
# Extract language embeddings
language_embeddings = input_embeddings[~all_actions_mask].reshape(
input_embeddings.shape[0], -1, input_embeddings.shape[2]
)
# Process vision features
projected_patch_embeddings = self._process_vision_features(pixel_values, language_embeddings, use_film)
# Add proprioceptive features if provided
use_proprio = proprio_projector is not None and proprio is not None
if use_proprio:
proprio = torch.Tensor(proprio).to(projected_patch_embeddings.device, dtype=projected_patch_embeddings.dtype)
projected_patch_embeddings = self._process_proprio_features(
projected_patch_embeddings, proprio, proprio_projector
)
# Use diffusion if provided, otherwise use regression or discrete prediction
use_diffusion = noisy_action_projector is not None and hasattr(action_head, "noise_scheduler")
# Calculate number of patches (including proprio token and/or diffusion timestep embedding if present)
NUM_PATCHES = self.vision_backbone.get_num_patches() * self.vision_backbone.get_num_images_in_input()
if use_proprio:
NUM_PATCHES += 1
if use_diffusion:
NUM_PATCHES += 1
if use_diffusion:
# Sample random noise with shape equal to output action, used as the starting state for reverse diffusion
noise = torch.randn(
size=(1, NUM_ACTIONS_CHUNK, ACTION_DIM), device=input_embeddings.device, dtype=input_embeddings.dtype
)
# Run diffusion-based prediction
normalized_actions, actions_hidden_states = self._run_diffusion_prediction(
input_embeddings,
all_actions_mask,
noise,
action_head,
projected_patch_embeddings,
labels,
attention_mask,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
noisy_action_projector,
)
else:
# Run regression or discrete token-based prediction
normalized_actions, actions_hidden_states = self._regression_or_discrete_prediction(
input_embeddings,
all_actions_mask,
projected_patch_embeddings,
attention_mask,
labels,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
action_head,
)
# Unnormalize predicted actions
actions = self._unnormalize_actions(normalized_actions, unnorm_key)
return actions, actions_hidden_states
def generate_action_verl(
self,
input_ids: Optional[torch.LongTensor] = None,
unnorm_key: Optional[str] = None,
proprio=None,
proprio_projector=None,
action_head=None,
noisy_action_projector=None,
use_film: bool = False,
**kwargs: str,
) -> np.ndarray:
"""Predict actions from input sequence, with options for different prediction methods.
Args:
input_ids: Input token ids
unnorm_key: Key for unnormalization statistics
proprio: Proprioceptive features
proprio_projector: Projector for proprioceptive features
action_head: Optional head for L1 regression or diffusion-based prediction
noisy_action_projector: Projector for noisy actions in diffusion-based prediction
use_film: Whether to use FiLM conditioning
**kwargs: Additional arguments including pixel_values and attention_mask
Returns:
Tuple of (unnormalized_actions, action_hidden_states)
"""
# If the special empty token ('') does not already appear after the colon (':') token in the prompt
# (after "OUT:" or "ASSISTANT:"), insert it to match the inputs seen at training time
# if not torch.all(input_ids[:, -1] == 29871):
# input_ids = torch.cat(
# (input_ids, torch.unsqueeze(torch.Tensor([29871]).long(), dim=0).to(input_ids.device)), dim=1
# )
pixel_values = kwargs["pixel_values"]
attention_mask = kwargs["attention_mask"]
do_sample = kwargs["do_sample"]
temperature = kwargs["temperature"]
# Create fake labels tensor (needed for action mask)
labels = input_ids.clone()
labels[:] = IGNORE_INDEX
# Get number of tokens in prompt (excluding the start token)
#NUM_PROMPT_TOKENS = input_ids.shape[-1] - 1 # Subtract action tokens and stop token
#test
padding_idx = kwargs["padding_idx"]
num_prompt_tokens = input_ids.ne(padding_idx).sum(dim=1) - 1
#test end
# Prepare inputs by adding necessary tokens
input_ids, attention_mask = self._prepare_input_for_action_prediction(input_ids, attention_mask)
# Update labels tensor for action mask computation later
labels = self._prepare_labels_for_action_prediction(labels, input_ids)
#here to convert padding from before to last
#test
padding_mask = input_ids.ne(padding_idx)
assert torch.all(padding_mask==attention_mask.ne(0))
#print("in predict_action padding_mask:", padding_mask)
padding_mask = padding_mask.int()
sorted_indices = torch.argsort(padding_mask, dim=1, descending=True, stable=True)
input_ids = torch.gather(input_ids, 1, sorted_indices)
attention_mask = torch.gather(attention_mask, 1, sorted_indices)
labels = torch.gather(labels, 1, sorted_indices)
assert use_film==False
#test end
# Get input embeddings and action masks
input_embeddings = self.get_input_embeddings()(input_ids)
all_actions_mask = self._process_action_masks(labels)
# Extract language embeddings
language_embeddings = input_embeddings[~all_actions_mask].reshape(
input_embeddings.shape[0], -1, input_embeddings.shape[2]
)
# Process vision features
projected_patch_embeddings = self._process_vision_features(pixel_values, language_embeddings, use_film)
# Add proprioceptive features if provided
use_proprio = proprio_projector is not None and proprio is not None
if use_proprio:
proprio = torch.Tensor(proprio).to(projected_patch_embeddings.device, dtype=projected_patch_embeddings.dtype)
projected_patch_embeddings = self._process_proprio_features(
projected_patch_embeddings, proprio, proprio_projector
)
# Use diffusion if provided, otherwise use regression or discrete prediction
use_diffusion = noisy_action_projector is not None and hasattr(action_head, "noise_scheduler")
# Calculate number of patches (including proprio token and/or diffusion timestep embedding if present)
NUM_PATCHES = self.vision_backbone.get_num_patches() * self.vision_backbone.get_num_images_in_input()
if use_proprio:
NUM_PATCHES += 1
if use_diffusion:
NUM_PATCHES += 1
if use_diffusion:
raise ValueError
# Sample random noise with shape equal to output action, used as the starting state for reverse diffusion
noise = torch.randn(
size=(1, NUM_ACTIONS_CHUNK, ACTION_DIM), device=input_embeddings.device, dtype=input_embeddings.dtype
)
# Run diffusion-based prediction
normalized_actions, actions_hidden_states = self._run_diffusion_prediction(
input_embeddings,
all_actions_mask,
noise,
action_head,
projected_patch_embeddings,
labels,
attention_mask,
NUM_PATCHES,
NUM_PROMPT_TOKENS,
noisy_action_projector,
)
else:
# Run regression or discrete token-based prediction
normalized_actions, reponse_ids = self._verl_discrete_prediction(
input_embeddings,
all_actions_mask,
projected_patch_embeddings,
attention_mask,
labels,
NUM_PATCHES,
num_prompt_tokens,
action_head,
do_sample=do_sample,
temperature=temperature,
)
# Unnormalize predicted actions
actions = self._unnormalize_actions(normalized_actions, unnorm_key)
#verl add!
actions = actions.reshape(-1 ,NUM_ACTIONS_CHUNK, ACTION_DIM)
#
return actions, reponse_ids
@staticmethod
def _check_unnorm_key(norm_stats: Dict[str, Dict[str, Any]], unnorm_key: Optional[str]) -> str:
"""Validate and resolve the unnormalization key for action statistics"""
if unnorm_key is None:
assert len(norm_stats) == 1, (
f"Your model was trained on more than one dataset, "
f"please pass a `unnorm_key` from the following options to choose the statistics "
f"used for un-normalizing actions: {norm_stats.keys()}"
)
unnorm_key = next(iter(norm_stats.keys()))
assert unnorm_key in norm_stats, (
f"The `unnorm_key` you chose is not in the set of available dataset statistics, "
f"please choose from: {norm_stats.keys()}"
)
return unnorm_key
def get_action_dim(self, unnorm_key: Optional[str] = None) -> int:
"""Get the dimensionality of the policy's action space."""
unnorm_key = self._check_unnorm_key(self.norm_stats, unnorm_key)
return len(self.norm_stats[unnorm_key]["action"]["min"])
def get_action_stats(self, unnorm_key: Optional[str] = None) -> Dict[str, Any]:
"""Get all the logged statistics for the given dataset."""
unnorm_key = self._check_unnorm_key(self.norm_stats, unnorm_key)
return self.norm_stats[unnorm_key]["action"]
|