Image-Text-to-Text
Transformers
Safetensors
English
Chinese
venusocr
text-generation
ocr
document-parsing
vision-language-model
formula-recognition
table-recognition
speculative-decoding
ptp2
vllm
conversational
custom_code
Instructions to use flow3rdown/VenusOCR with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use flow3rdown/VenusOCR with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="flow3rdown/VenusOCR", trust_remote_code=True) messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("flow3rdown/VenusOCR", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use flow3rdown/VenusOCR with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "flow3rdown/VenusOCR" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "flow3rdown/VenusOCR", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/flow3rdown/VenusOCR
- SGLang
How to use flow3rdown/VenusOCR with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "flow3rdown/VenusOCR" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "flow3rdown/VenusOCR", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "flow3rdown/VenusOCR" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "flow3rdown/VenusOCR", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use flow3rdown/VenusOCR with Docker Model Runner:
docker model run hf.co/flow3rdown/VenusOCR
File size: 83,912 Bytes
e096bf2 | 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 | # Copyright 2025 The VenusOCR Authors and the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""PyTorch VenusOCR model."""
import itertools
from collections.abc import Callable
from dataclasses import dataclass
from typing import Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from transformers.activations import ACT2FN, GELUActivation
from transformers.cache_utils import Cache
from transformers.generation.utils import GenerationMixin
from transformers.modeling_layers import GradientCheckpointingLayer
from transformers.modeling_outputs import BaseModelOutput, BaseModelOutputWithPast, BaseModelOutputWithPooling
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
from transformers.utils import logging
from transformers.utils.auto_docstring import auto_docstring
from transformers.utils.generic import (
ModelOutput, maybe_autocast, can_return_tuple,
is_flash_attention_requested, merge_with_config_defaults
)
from transformers.utils.import_utils import torch_compilable_check
from transformers.masking_utils import create_bidirectional_mask, create_causal_mask
from transformers.cache_utils import DynamicCache
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
from transformers.integrations.hub_kernels import use_kernel_forward_from_hub
from transformers.utils.output_capturing import capture_outputs
from .configuration_venusocr import VenusOCRConfig
logger = logging.get_logger(__name__)
_IGNORE_INDEX = -100
def _cross_entropy_loss(
hidden_states: torch.Tensor,
lm_head: nn.Module,
position_ids: torch.Tensor,
labels: torch.Tensor,
reduction_scope: str = "sequence",
**loss_kwargs,
) -> torch.Tensor:
"""Compute next-token prediction loss (inline copy, no external VenusOCR dependency).
Args:
hidden_states: ``[B, T, C]``
lm_head: linear projection to vocab logits
position_ids: ``[B, T]``
labels: ``[B, T]``
reduction_scope: ``"sequence"`` (per-sample normalisation, recommended for
packing) or ``"batch"`` (divide by total valid tokens in batch).
"""
batch_size = hidden_states.size(0)
shift_hidden = hidden_states[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
mask = shift_labels != _IGNORE_INDEX
if mask.sum() == 0:
pseudo = lm_head(hidden_states[:, 0:1])
return 0.0 * pseudo.mean()
valid_hidden = shift_hidden[mask]
valid_labels = shift_labels[mask]
if "num_items_in_batch" not in loss_kwargs:
logits = lm_head(valid_hidden)
return F.cross_entropy(logits, valid_labels, reduction="mean")
if reduction_scope == "batch":
logits = lm_head(valid_hidden)
loss = F.cross_entropy(logits, valid_labels, reduction="sum")
return loss / loss_kwargs["num_items_in_batch"]
if reduction_scope == "sequence":
if batch_size == 1:
starts = torch.nonzero(position_ids[0] == 0)[:, 0]
ends = F.pad(starts[1:], (0, 1), value=position_ids.size(1))
seq_ids = torch.cat([
torch.full((int(e - s),), i, device=position_ids.device, dtype=torch.long)
for i, (s, e) in enumerate(zip(starts.tolist(), ends.tolist()))
]).unsqueeze(0)
else:
seq_ids = torch.arange(batch_size, device=position_ids.device)
seq_ids = seq_ids.unsqueeze(1).expand(-1, hidden_states.size(1))
shift_seq_ids = seq_ids[..., :-1][mask]
num_tokens = F.one_hot(shift_seq_ids).sum(dim=0)
denominator = num_tokens[shift_seq_ids] * loss_kwargs["num_items_in_batch"]
logits = lm_head(valid_hidden)
loss = F.cross_entropy(logits, valid_labels, reduction="none")
return (loss / denominator).sum()
raise ValueError(f"Unknown reduction_scope: {reduction_scope!r}")
@dataclass
@auto_docstring(
custom_intro="""
Base class for VenusOCR model outputs, with hidden states and attentions.
"""
)
class VenusOCRModelOutputWithPast(BaseModelOutputWithPast):
r"""
image_hidden_states (`torch.FloatTensor`, *optional*):
A ``torch.FloatTensor`` of size ``(total_image_tokens, hidden_size)``.
Image hidden states produced by the vision encoder and projected by the
multimodal projector.
rope_deltas (`torch.LongTensor`, *optional*):
Per-sample offset (shape ``(batch_size, 1)``) that accounts for the
difference between the 2D RoPE position span and the number of image
tokens actually inserted. Used during incremental decoding to restore
correct position ids from the KV-cache length.
"""
image_hidden_states: Optional[torch.FloatTensor] = None
rope_deltas: Optional[torch.LongTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for VenusOCR causal language model outputs.
"""
)
class VenusOCRCausalLMOutputWithPast(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape ``(1,)``, *optional*, returned when ``labels`` is provided):
Language modelling loss (next-token prediction).
logits (`torch.FloatTensor` of shape ``(batch_size, sequence_length, config.vocab_size)``):
Prediction scores of the language modelling head (before SoftMax).
past_key_values (`Cache`, *optional*, returned when ``use_cache=True``):
Pre-computed key/value hidden states that can be used to speed up auto-regressive decoding.
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when ``output_hidden_states=True``):
Hidden states at each layer of the decoder.
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when ``output_attentions=True``):
Attention weights at each layer of the decoder.
image_hidden_states (`torch.FloatTensor`, *optional*):
Projected image features that were merged into the input embeddings.
rope_deltas (`torch.LongTensor`, *optional*):
Stored 2D RoPE offset for incremental decoding.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
past_key_values: Optional[Cache] = None
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
image_hidden_states: Optional[torch.FloatTensor] = None
rope_deltas: Optional[torch.LongTensor] = None
class VenusOCRVisionRotaryEmbedding(nn.Module):
"""1D RoPE for the vision encoder, applied over 2D patch grids.
Returns ``freqs`` of shape ``(seqlen, dim // 2)`` which are then indexed
by per-patch ``(h, w)`` coordinates and concatenated to form the full
rotary embeddings used in attention.
"""
inv_freq: torch.Tensor # type annotation for register_buffer
def __init__(self, dim: int, theta: float = 10000.0) -> None:
super().__init__()
self.dim = dim
self.theta = theta
inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, seqlen: int) -> torch.Tensor:
seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
freqs = torch.outer(seq, self.inv_freq) # (seqlen, dim // 2)
return freqs
def rotate_half(x: torch.Tensor) -> torch.Tensor:
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def apply_multimodal_rotary_pos_emb(q, k, cos, sin, mrope_section, unsqueeze_dim=1):
"""Applies Rotary Position Embedding with Multimodal Sections to the query and key tensors (https://qwenlm.github.io/blog/qwen2-vl/).
Explanation:
Multimodal 3D rotary position embedding is an extension to 1D rotary position embedding. The input embedding
sequence contains vision (images / videos) embedding and text embedding or just contains text embedding. For
vision embedding part, we apply rotary position embedding on temporal, height and width dimension separately.
Here we split the channel dimension to 3 chunks for the temporal, height and width rotary position embedding.
For text embedding part, we just apply 1D rotary position embedding. The three rotary position index (temporal,
height and width) of text embedding is always the same, so the text embedding rotary position embedding has no
difference with modern LLMs.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`):
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
used to pass offsetted position ids when working with a KV-cache.
mrope_section(`List(int)`):
Multimodal rope section is for channel dimension of temporal, height and width in rope calculation.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
mrope_section = mrope_section * 2
cos = torch.cat([m[i % 3] for i, m in enumerate(cos.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
unsqueeze_dim
)
sin = torch.cat([m[i % 3] for i, m in enumerate(sin.split(mrope_section, dim=-1))], dim=-1).unsqueeze(
unsqueeze_dim
)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def apply_rotary_pos_emb_vision(
q: torch.Tensor,
k: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Apply RoPE to vision query/key tensors.
Args:
q, k: ``(seq_len, num_heads, head_dim)``
cos, sin: ``(seq_len, head_dim)`` – note: **no** batch/head dimension.
"""
orig_q_dtype = q.dtype
orig_k_dtype = k.dtype
q, k = q.float(), k.float()
cos = cos.unsqueeze(-2).float() # (seq_len, 1, head_dim)
sin = sin.unsqueeze(-2).float()
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
q_embed = q_embed.to(orig_q_dtype)
k_embed = k_embed.to(orig_k_dtype)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: torch.Tensor | None,
scaling: float,
dropout: float = 0.0,
**kwargs,
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
@auto_docstring
class VenusOCRPreTrainedModel(PreTrainedModel):
"""Base class for VenusOCR models. Handles weight initialisation and
gradient-checkpointing boilerplate.
"""
config_class = VenusOCRConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
def _init_weights(self, module: nn.Module) -> None:
super()._init_weights(module)
if isinstance(module, VenusOCRVisionRotaryEmbedding):
inv_freq = 1.0 / (
module.theta ** (torch.arange(0, module.dim, 2, dtype=torch.float) / module.dim)
)
module.inv_freq.data.copy_(inv_freq)
elif isinstance(module, VenusOCRVisionEmbeddings):
# Re-initialise position_ids buffer to identity arange
n = module.num_patches # plain int attribute
module.position_ids.data.copy_(torch.arange(n).expand((1, -1))) # type: ignore[arg-type]
class VenusOCRVisionEmbeddings(nn.Module):
"""Patch embedding + interpolated 2D absolute position embedding.
Key differences from the original ``SiglipVisionEmbeddings``:
1. **Input format** – accepts pre-patchified tensors of shape
``(total_patches, C, patch_h, patch_w)`` (as produced by the VenusOCR
processor via the same tiling scheme as PaddleOCR-VL / Qwen2-VL),
rather than a raw ``(B, C, H, W)`` image.
2. **Dynamic position interpolation** – for each image the position
embedding is bilinearly interpolated from the training resolution
``(image_size // patch_size) ** 2`` to the actual ``(h, w)`` grid,
enabling arbitrary-resolution inputs. This matches the approach used
in PaddleOCR-VL and differs from the standard SiglipVisionEmbeddings
which only optionally interpolates via ``interpolate_pos_encoding=True``.
3. **Per-image processing** – images in a batch may have different grid
sizes; they are processed individually and concatenated, producing a
flat ``(total_tokens, embed_dim)`` sequence ready for the packed-sequence
attention in the encoder.
"""
def __init__(self, config) -> None: # type: ignore[name-defined]
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.patch_embedding = nn.Conv2d(
in_channels=config.num_channels,
out_channels=self.embed_dim,
kernel_size=self.patch_size,
stride=self.patch_size,
padding="valid",
)
self.num_patches = (self.image_size // self.patch_size) ** 2
self.num_positions = self.num_patches
self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
self.register_buffer(
"position_ids",
torch.arange(self.num_positions).expand((1, -1)),
persistent=False,
)
def interpolate_pos_encoding(
self, embeddings: torch.Tensor, height: int, width: int
) -> torch.Tensor:
"""Bilinearly interpolate position embedding to ``(height, width)`` patch grid.
Adapted from DINO / DINOv2 and PaddleOCR-VL. Always uses bilinear
interpolation (as opposed to the bicubic used in the original
``SiglipVisionEmbeddings``).
Args:
embeddings: unused except for device / dtype information
height, width: target grid dimensions **in patches** (not pixels)
Returns:
``(1, height * width, embed_dim)`` interpolated position embeddings.
"""
num_positions = self.position_embedding.weight.shape[0]
patch_pos_embed = self.position_embedding.weight.unsqueeze(0) # (1, N, D)
dim = embeddings.shape[-1]
sqrt_num_positions = int(num_positions ** 0.5)
patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2) # (1, D, H, W)
patch_pos_embed = nn.functional.interpolate(
patch_pos_embed,
size=(height, width),
mode="bilinear",
align_corners=False,
)
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim) # (1, h*w, D)
return patch_pos_embed
def forward(
self,
pixel_values: torch.FloatTensor,
image_grid_thw: Optional[torch.LongTensor] = None,
) -> torch.Tensor:
"""
Args:
pixel_values: ``(total_patches, C, patch_size, patch_size)`` – pre-patchified
tensor where the batch and temporal dimensions are merged.
image_grid_thw: ``(num_images, 3)`` containing ``(t, h, w)`` for each image.
Must be provided to correctly add per-image position embeddings.
Returns:
Flat ``(total_tokens, embed_dim)`` embedding tensor.
"""
target_dtype = self.patch_embedding.weight.dtype
# pixel_values: (total_patches, C, patch_h, patch_w)
patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype))
# patch_embeds: (total_patches, embed_dim, 1, 1) → squeeze → (total_patches, embed_dim)
embeddings = patch_embeds.flatten(1) # (total_patches, embed_dim)
if image_grid_thw is None:
# Fallback: add default position embedding (assumes fixed-resolution square images)
embeddings = embeddings + self.position_embedding(self.position_ids).squeeze(0)
return embeddings
# Add per-image interpolated position embeddings
processed = []
offset = 0
for grid in image_grid_thw:
t, h, w = int(grid[0]), int(grid[1]), int(grid[2])
n_tokens = t * h * w
img_emb = embeddings[offset : offset + n_tokens] # (t*h*w, D)
# Interpolate position encoding to the current (h, w) grid
pos_enc = self.interpolate_pos_encoding(img_emb, h, w) # (1, h*w, D)
pos_enc = pos_enc.squeeze(0).repeat(t, 1) # (t*h*w, D)
processed.append(img_emb + pos_enc)
offset += n_tokens
embeddings = torch.concat(processed, dim=0)
return embeddings # (total_tokens, D)
class VenusOCRVisionAttention(nn.Module):
"""Full-attention (non-causal) multi-head attention for the vision encoder.
Compared with the original ``SiglipAttention``:
* Uses **2D rotary position embeddings** (computed per-image from patch
``(h, w)`` coordinates) instead of the learned absolute position
embeddings added in ``VenusOCRVisionEmbeddings.forward``.
* Accepts **packed sequences** via ``cu_seqlens`` + Flash Attention 2, or
falls back to chunked eager attention for shorter sequences / other
backends.
* The projection layer is still a single ``out_proj`` (same as Siglip),
not a split ``q/k/v_proj + o_proj`` (same weight shapes, just naming).
"""
def __init__(self, config) -> None: # type: ignore[name-defined]
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = self.embed_dim // self.num_heads
self.scaling = self.head_dim ** -0.5
self.attention_dropout = config.attention_dropout
self.is_causal = False
# keep the same Siglip naming convention (q/k/v/out_proj)
self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
self.num_key_value_groups = 1 # required by eager_attention_forward
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
**kwargs,
) -> tuple[torch.Tensor, Optional[torch.Tensor] | None]:
"""
Args:
hidden_states: ``(seq_len, embed_dim)`` – packed (all images concatenated).
cu_seqlens: ``(num_images + 1,)`` cumulative sequence lengths.
position_embeddings: ``(cos, sin)`` each of shape ``(seq_len, head_dim)``.
"""
seq_len = hidden_states.shape[0]
query = self.q_proj(hidden_states).view(seq_len, self.num_heads, self.head_dim)
key = self.k_proj(hidden_states).view(seq_len, self.num_heads, self.head_dim)
value = self.v_proj(hidden_states).view(seq_len, self.num_heads, self.head_dim)
cos, sin = position_embeddings
query, key = apply_rotary_pos_emb_vision(query, key, cos, sin)
# Reshape to (1, num_heads, seq_len, head_dim) for attention backends
query = query.transpose(0, 1).unsqueeze(0) # (1, H, S, D)
key = key.transpose(0, 1).unsqueeze(0)
value = value.transpose(0, 1).unsqueeze(0)
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
self.config._attn_implementation, eager_attention_forward
)
if is_flash_attention_requested(self.config):
# Flash Attention 2: packed variable-length attention
max_seqlen = int((cu_seqlens[1:] - cu_seqlens[:-1]).max())
attn_output, _ = attention_interface(
self,
query, key, value,
attention_mask=None,
scaling=self.scaling,
dropout=0.0 if not self.training else self.attention_dropout,
cu_seq_lens_q=cu_seqlens,
cu_seq_lens_k=cu_seqlens,
max_length_q=max_seqlen,
max_length_k=max_seqlen,
is_causal=False,
**kwargs,
)
else:
# Chunked eager attention: process each image independently
lengths = (cu_seqlens[1:] - cu_seqlens[:-1]).tolist()
q_chunks = torch.split(query, lengths, dim=2)
k_chunks = torch.split(key, lengths, dim=2)
v_chunks = torch.split(value, lengths, dim=2)
attn_outputs = []
for q, k, v in zip(q_chunks, k_chunks, v_chunks):
out, _ = attention_interface(
self, q, k, v,
attention_mask=None,
scaling=self.scaling,
dropout=0.0 if not self.training else self.attention_dropout,
is_causal=False,
**kwargs,
)
attn_outputs.append(out)
attn_output = torch.cat(attn_outputs, dim=1)
attn_output = attn_output.reshape(seq_len, -1).contiguous() # (S, embed_dim)
attn_output = self.out_proj(attn_output)
return attn_output
class VenusOCRVisionMLP(nn.Module):
"""Feed-forward block for the vision encoder (identical to ``SiglipMLP``)."""
def __init__(self, config) -> None: # type: ignore[name-defined]
super().__init__()
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
class VenusOCRVisionEncoderLayer(GradientCheckpointingLayer):
"""Single Transformer encoder layer for the vision encoder.
Structurally identical to ``SiglipEncoderLayer``
(pre-norm, self-attn, pre-norm, MLP with residuals), but uses
``VenusOCRVisionAttention`` which supports 2D RoPE and packed sequences.
"""
def __init__(self, config) -> None: # type: ignore[name-defined]
super().__init__()
self.embed_dim = config.hidden_size
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.self_attn = VenusOCRVisionAttention(config)
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = VenusOCRVisionMLP(config)
def forward(
self,
hidden_states: torch.Tensor,
cu_seqlens: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
**kwargs,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.layer_norm1(hidden_states)
hidden_states = self.self_attn(
hidden_states,
cu_seqlens=cu_seqlens,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
class VenusOCRVisionEncoder(nn.Module):
"""Stack of ``VenusOCRVisionEncoderLayer`` with 2D RoPE pre-computation.
Before passing through the layers, height/width position indices are
extracted from ``image_grid_thw`` and used to look up the rotary
embeddings from ``VenusOCRVisionRotaryEmbedding``, following the same
approach as PaddleOCR-VL.
"""
def __init__(self, config) -> None: # type: ignore[name-defined]
super().__init__()
self.config = config
self.layers = nn.ModuleList(
[VenusOCRVisionEncoderLayer(config) for _ in range(config.num_hidden_layers)]
)
self.gradient_checkpointing = False
head_dim = config.hidden_size // config.num_attention_heads
self.rotary_pos_emb = VenusOCRVisionRotaryEmbedding(head_dim // 2)
def forward(
self,
inputs_embeds: torch.FloatTensor,
cu_seqlens: torch.Tensor,
image_grid_thw: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> BaseModelOutput:
"""
Args:
inputs_embeds: ``(total_tokens, hidden_size)`` packed sequence.
cu_seqlens: ``(num_images + 1,)`` cumulative lengths for FA2.
image_grid_thw: ``(num_images, 3)`` grid metadata used to build
2D position ids for rotary embeddings.
"""
device = inputs_embeds.device
hidden_states = inputs_embeds
# ── Build 2D rotary position embeddings ───────────────────────────────
# For each token, compute its (h_id, w_id) within its image.
h_ids_list, w_ids_list = [], []
for t, h, w in image_grid_thw:
t, h, w = int(t), int(h), int(w)
patch_ids = torch.arange(t * h * w, device=device) % (h * w)
h_ids_list.append(patch_ids // w)
w_ids_list.append(patch_ids % w)
height_ids = torch.cat(h_ids_list, dim=0) # (total_tokens,)
width_ids = torch.cat(w_ids_list, dim=0)
# Stack to (total_tokens, 2) for lookup
pids = torch.stack([height_ids, width_ids], dim=-1)
max_grid_size = int(pids.max().item()) + 1
rotary_freqs = self.rotary_pos_emb(max_grid_size) # (max_grid, dim//2)
rotary_emb = rotary_freqs[pids].flatten(1) # (total_tokens, dim)
rotary_emb = rotary_emb.repeat(1, 2) # (total_tokens, head_dim)
position_embeddings = (rotary_emb.cos(), rotary_emb.sin())
# ── Bidirectional attention mask (for non-FA2 backends) ───────────────
attention_mask = create_bidirectional_mask(
config=self.config,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
)
for layer in self.layers:
hidden_states = layer(
hidden_states,
cu_seqlens=cu_seqlens,
position_embeddings=position_embeddings,
**kwargs,
)
return BaseModelOutput(last_hidden_state=hidden_states)
class VenusOCRVisionTransformer(VenusOCRPreTrainedModel):
"""Vision Transformer backbone (encoder-only, non-causal).
Pipeline: ``VenusOCRVisionEmbeddings → VenusOCRVisionEncoder → LayerNorm``
"""
def __init__(self, config) -> None:
super().__init__(config)
self.config = config
self.embeddings = VenusOCRVisionEmbeddings(config)
self.encoder = VenusOCRVisionEncoder(config)
self.post_layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
@auto_docstring
def forward(
self,
pixel_values: torch.FloatTensor,
cu_seqlens: torch.Tensor,
image_grid_thw: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
**kwargs,
) -> BaseModelOutputWithPooling:
r"""
pixel_values (`torch.FloatTensor` of shape `(total_patches, C, patch_size, patch_size)`):
Pre-patchified pixel tensor.
cu_seqlens (`torch.Tensor` of shape `(num_images + 1,)`):
Cumulative sequence lengths for packed attention (FA2).
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
``(temporal, height, width)`` grid metadata for each image.
"""
hidden_states = self.embeddings(pixel_values, image_grid_thw=image_grid_thw)
encoder_outputs: BaseModelOutput = self.encoder(
inputs_embeds=hidden_states,
cu_seqlens=cu_seqlens,
image_grid_thw=image_grid_thw,
attention_mask=attention_mask,
**kwargs,
)
last_hidden_state = encoder_outputs.last_hidden_state
last_hidden_state = self.post_layernorm(last_hidden_state)
return BaseModelOutputWithPooling(
last_hidden_state=last_hidden_state,
pooler_output=None,
)
class VenusOCRProjector(nn.Module):
"""Spatial-merge MLP projector that maps vision encoder features into the
LLM embedding space.
Architecture (following PaddleOCR-VL)::
input: (total_tokens, vision_hidden_size)
↓ group spatial_merge_size × spatial_merge_size patches
↓ pre_norm (LayerNorm over vision_hidden_size)
↓ reshape: (N_blocks, vision_hidden_size * merge_size²)
↓ Linear → GELU → Linear
output: (N_blocks, text_hidden_size)
This reduces the total token count by ``merge_size²``.
"""
def __init__(self, config: VenusOCRConfig) -> None:
super().__init__()
m = config.vision_config.spatial_merge_size
vision_dim = config.vision_config.hidden_size
merged_dim = vision_dim * m * m
text_dim = config.text_config.hidden_size
self.merge_size = m
self.pre_norm = nn.LayerNorm(vision_dim, eps=1e-5)
self.linear_1 = nn.Linear(merged_dim, merged_dim, bias=True)
self.act = GELUActivation()
self.linear_2 = nn.Linear(merged_dim, text_dim, bias=True)
def forward(
self,
image_features: torch.Tensor,
image_grid_thw: torch.LongTensor,
) -> torch.Tensor:
"""
Args:
image_features: ``(total_tokens, vision_hidden_size)`` flat sequence.
image_grid_thw: ``(num_images, 3)`` grid metadata.
Returns:
``(total_merged_tokens, text_hidden_size)``
"""
m = self.merge_size
chunks = image_features.split(image_grid_thw.prod(dim=1).tolist(), dim=0)
processed = []
for feat, grid in zip(chunks, image_grid_thw):
feat = self.pre_norm(feat)
t, h, w = int(grid[0]), int(grid[1]), int(grid[2])
d = feat.shape[-1]
h_block, w_block = h // m, w // m
# Reshape to group (m × m) spatial blocks
feat = feat.reshape(t, h_block, m, w_block, m, d)
feat = feat.transpose(2, 3) # (t, h_block, w_block, m, m, d)
feat = feat.reshape(t * h_block * w_block, m * m * d)
hidden = self.linear_1(feat)
hidden = self.act(hidden)
hidden = self.linear_2(hidden)
processed.append(hidden)
return torch.cat(processed, dim=0)
class VenusOCRRotaryEmbedding(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
@staticmethod
def compute_default_rope_parameters(
config: VenusOCRConfig | None = None,
device: Optional["torch.device"] = None,
seq_len: int | None = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
# Ignore copy
def forward(self, x, position_ids):
# In contrast to other models, PaddleOCR has different position ids for the grids
# So we expand the inv_freq to shape (3, ...)
inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
position_ids_expanded = position_ids[:, :, None, :].float() # shape (3, bs, 1, positions)
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(2, 3)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
@use_kernel_forward_from_hub("RMSNorm")
class VenusOCRRMSNorm(nn.Module):
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
"""
Qwen3VLTextRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
input_dtype = hidden_states.dtype
hidden_states = hidden_states.to(torch.float32)
variance = hidden_states.pow(2).mean(-1, keepdim=True)
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
return self.weight * hidden_states.to(input_dtype)
def extra_repr(self):
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
class VenusOCRTextAttention(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config, layer_idx: int):
super().__init__()
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.config = config
self.layer_idx = layer_idx
self.hidden_size = config.hidden_size
self.num_heads = config.num_attention_heads
self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
self.num_key_value_heads = config.num_key_value_heads
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
self.scaling = self.head_dim**-0.5
self.attention_dropout = config.attention_dropout
self.rope_parameters = config.rope_parameters
self.is_causal = True
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
self.q_norm = VenusOCRRMSNorm(self.head_dim, eps=config.rms_norm_eps) # unlike olmo, only on the head dim!
self.k_norm = VenusOCRRMSNorm(self.head_dim, eps=config.rms_norm_eps) # thus post q_norm does not need reshape
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None,
past_key_values: Cache | None = None,
**kwargs,
) -> tuple[torch.Tensor, torch.Tensor | None]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_norm(self.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_multimodal_rotary_pos_emb(query_states, key_states, cos, sin, self.config.rope_parameters["mrope_section"])
if past_key_values is not None:
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
self.config._attn_implementation, eager_attention_forward
)
attn_output, attn_weights = attention_interface(
self,
query_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
class VenusOCRTextMLP(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
self.act_fn = ACT2FN[config.hidden_act]
def forward(self, x):
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
return down_proj
class VenusOCRTextDecoderLayer(GradientCheckpointingLayer):
def __init__(self, config, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = VenusOCRTextAttention(config=config, layer_idx=layer_idx)
self.mlp = VenusOCRTextMLP(config)
self.input_layernorm = VenusOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = VenusOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: tuple[torch.Tensor, torch.Tensor],
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: Cache | None = None,
use_cache: bool | None = False,
**kwargs,
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
class VenusOCRTextModel(VenusOCRPreTrainedModel):
input_modalities = ("text",)
def __init__(self, config) -> None:
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.layers = nn.ModuleList(
[VenusOCRTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = VenusOCRRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.rotary_emb = VenusOCRRotaryEmbedding(config=config)
self.gradient_checkpointing = False
# Initialize weights and apply final processing
self.post_init()
@merge_with_config_defaults
@capture_outputs
@auto_docstring
def forward(
self,
input_ids: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
position_ids: torch.LongTensor | None = None,
past_key_values: Cache | None = None,
inputs_embeds: torch.FloatTensor | None = None,
use_cache: bool | None = None,
**kwargs,
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
if use_cache and past_key_values is None and not torch.jit.is_tracing():
past_key_values = DynamicCache(config=self.config)
if inputs_embeds is None:
inputs_embeds = self.embed_tokens(input_ids)
# the hard coded `4` is for text, temporal, height and width.
if position_ids is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
position_ids = torch.arange(inputs_embeds.shape[1], device=inputs_embeds.device) + past_seen_tokens
position_ids = position_ids.view(1, 1, -1).expand(3, inputs_embeds.shape[0], -1)
elif position_ids.ndim == 2:
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
if position_ids.ndim == 3 and position_ids.shape[0] == 4:
text_position_ids = position_ids[0]
position_ids = position_ids[1:]
else:
text_position_ids = None
causal_mask = create_causal_mask(
config=self.config,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
past_key_values=past_key_values,
position_ids=text_position_ids,
)
hidden_states = inputs_embeds
# create position embeddings to be shared across the decoder layers
position_embeddings = self.rotary_emb(hidden_states, position_ids=position_ids)
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask,
position_embeddings=position_embeddings,
position_ids=text_position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
@auto_docstring
class VenusOCRModel(VenusOCRPreTrainedModel):
base_model_prefix = "model"
# Reference: fix gemma3 grad acc #37208
accepts_loss_kwargs = False
config: VenusOCRConfig
def __init__(self, config) -> None:
super().__init__(config)
# Propagate _attn_implementation to vision_config so that
# VenusOCRVisionAttention.forward() correctly enters the FA2 branch.
attn_impl = getattr(config, "_attn_implementation", "eager")
config.vision_config._attn_implementation = attn_impl
self.visual = VenusOCRVisionTransformer._from_config(config.vision_config)
self.projector = VenusOCRProjector(config)
self.language_model = VenusOCRTextModel._from_config(config.text_config)
# Cached rope offset for incremental decoding with 2D M-RoPE.
# Shape: (batch_size, 1) – set during prefill, reused during decode.
self.rope_deltas = None
self.post_init()
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_vision_position_ids(
self,
start_position: int,
grid_thw: list[int, int, int] | torch.Tensor,
temp_merge_size: int = 1,
spatial_merge_size: int = 1,
time_interval: int = 1,
device: str | torch.device | None = None,
):
"""
Compute 3D positional indices for vision tokens derived from a single image or video input.
The positions are generated from the input grid defined by temporal (T), height (H), and
width (W) dimensions. Temporal and spatial dimensions can be downscaled according to the
merge sizes used in the vision backbone. The resulting positions are offset by `start_position`.
Args:
start_position (`int`):
Offset added to all computed positional indices.
grid_thw (`Sequence[int]` or `torch.Tensor` of shape `(3,)`):
The (T, H, W) grid representing the feature layout of the current image or video after patch embedding.
temp_merge_size (`int`, *optional*):
Factor by which the temporal dimension is reduced in the backbone. The temporal grid size is divided
by this value. Defaults to 1.
spatial_merge_size (`int`, *optional*):
Factor by which the spatial dimensions (H and W) are reduced in the backbone. Both H and W are divided
by this value. Defaults to 1.
time_interval (`int`, *optional*):
Spacing factor applied between consecutive temporal position indices.Defaults to 1.
device (`str` or `torch.device`, *optional*):
Device on which the resulting tensor is allocated. If `None`, uses the current default device.
Returns:
torch.LongTensor of shape (3, sequence_length):
Positional indices for temporal, height, and width dimensions,
flattened into sequence form and offset by `start_position`.
"""
llm_grid_t, llm_grid_h, llm_grid_w = (
grid_thw[0].item() // temp_merge_size,
grid_thw[1].item() // spatial_merge_size,
grid_thw[2].item() // spatial_merge_size,
)
image_seq_length = llm_grid_h * llm_grid_w * llm_grid_t
position_width = torch.arange(start_position, start_position + llm_grid_w, device=device).repeat(
llm_grid_h * llm_grid_t
)
position_height = torch.arange(start_position, start_position + llm_grid_h, device=device).repeat_interleave(
llm_grid_w * llm_grid_t
)
position_temporal = torch.full((image_seq_length,), start_position, device=device, dtype=torch.long)
position_temporal = position_temporal * time_interval
vision_position_ids = torch.stack([position_temporal, position_height, position_width], dim=0)
return vision_position_ids
def get_rope_index(
self,
input_ids: torch.LongTensor,
mm_token_type_ids: torch.IntTensor,
image_grid_thw: torch.LongTensor | None = None,
video_grid_thw: torch.LongTensor | None = None,
attention_mask: torch.Tensor | None = None,
seq_ids: torch.LongTensor | None = None,
**kwargs,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Compute 4D M-RoPE position ids with optional sub-sequence (packing) awareness.
Channels of the returned ``position_ids`` (shape ``(4, B, T)``):
- ``[0]`` text 1D axis – advances by 1 per token regardless of modality;
**resets to 0 at every sub-sequence boundary** when ``seq_ids`` is
provided. Consumed by the LLM's attention layer for FA2 varlen
``cu_seqlens`` reset detection and for ``create_causal_mask``.
- ``[1]`` temporal axis (vision tokens use ``start_position`` constant,
text tokens advance like the text axis).
- ``[2]`` height axis (varies inside an image, constant for text).
- ``[3]`` width axis (varies inside an image, constant for text).
Args:
input_ids: ``(B, T)`` token ids.
mm_token_type_ids: ``(B, T)`` modality ids (0=text, 1=image, 2=video).
image_grid_thw: ``(num_images, 3)`` ``(T, H, W)`` per image.
video_grid_thw: ``(num_videos, 3)`` ``(T, H, W)`` per video.
attention_mask: optional ``(B, T)`` mask to ignore padding.
seq_ids: optional ``(B, T)`` sub-sequence id per token (for
sequence packing). Same value within a sub-seq, different value
between adjacent sub-seqs marks a boundary at which BOTH the
text axis and the vision ``start_position`` reset to 0. When
``None`` (default / non-packing), the whole row is treated as a
single sub-sequence – behaviour matches the original
non-packing path.
Returns:
position_ids: ``(4, B, T)`` LongTensor.
mrope_position_deltas: ``(B, 1)`` – ``max(position) + 1 - seq_len``.
"""
spatial_merge_size = self.config.vision_config.spatial_merge_size
mrope_position_deltas = []
# 4 channels: text(0), temporal(1), height(2), width(3)
position_ids = torch.zeros(
4,
input_ids.shape[0],
input_ids.shape[1],
dtype=input_ids.dtype,
device=input_ids.device,
)
grid_iters = {
1: iter(image_grid_thw) if image_grid_thw is not None else None,
2: iter(video_grid_thw) if video_grid_thw is not None else None,
}
for batch_idx, current_input_ids in enumerate(input_ids):
input_token_type = mm_token_type_ids[batch_idx]
current_seq_ids = seq_ids[batch_idx] if seq_ids is not None else None
if attention_mask is not None:
mask_bool = attention_mask[batch_idx].bool()
current_input_ids = current_input_ids[mask_bool]
input_token_type = input_token_type[mask_bool]
if current_seq_ids is not None:
current_seq_ids = current_seq_ids[mask_bool]
# Group by (modality, seq_id) so that runs are split BOTH at modality
# changes and sub-seq boundaries. When seq_ids is None we fall back
# to grouping by modality alone (one sub-seq for the whole row).
if current_seq_ids is not None:
pair_iter = zip(input_token_type.tolist(), current_seq_ids.tolist())
key_fn = lambda x: x[1] # group by (modality, seq_id) tuple
else:
pair_iter = ((m, 0) for m in input_token_type.tolist())
key_fn = lambda x: x[1][0] # group by modality only
input_type_group = []
for key, group in itertools.groupby(enumerate(pair_iter), key_fn):
group = list(group)
start_index = group[0][0]
end_index = group[-1][0] + 1
if isinstance(key, tuple):
modality_type, seg_seq_id = key
else:
modality_type, seg_seq_id = key, 0
input_type_group.append((modality_type, seg_seq_id, start_index, end_index))
text_pos = 0 # text 1D axis counter (advances 1 per token)
vision_pos = 0 # vision-axes start_position counter (matches legacy current_pos)
prev_seq_id = None
llm_pos_ids_list = [] # each element: (4, seg_len) tensor
for modality_type, seg_seq_id, start_idx, end_idx in input_type_group:
# Reset BOTH counters at every sub-seq boundary.
if prev_seq_id is not None and seg_seq_id != prev_seq_id:
text_pos = 0
vision_pos = 0
prev_seq_id = seg_seq_id
seg_len = end_idx - start_idx
if modality_type == 0:
# ---- text segment ----
text_axis = (
torch.arange(seg_len, device=input_ids.device, dtype=position_ids.dtype) + text_pos
)
vision_axis = (
torch.arange(seg_len, device=input_ids.device, dtype=position_ids.dtype) + vision_pos
)
seg_pos = torch.stack(
[text_axis, vision_axis, vision_axis, vision_axis], dim=0
)
llm_pos_ids_list.append(seg_pos)
text_pos += seg_len
vision_pos += seg_len
else:
# ---- image / video segment ----
grid_thw = next(grid_iters[modality_type])
vision_position_ids = self.get_vision_position_ids(
vision_pos, grid_thw, 1, spatial_merge_size, device=input_ids.device
) # (3, seg_len) channels = (T, H, W)
text_axis = (
torch.arange(seg_len, device=input_ids.device, dtype=position_ids.dtype) + text_pos
)
seg_pos = torch.cat(
[text_axis.unsqueeze(0), vision_position_ids.to(position_ids.dtype)], dim=0
) # (4, seg_len)
llm_pos_ids_list.append(seg_pos)
text_pos += seg_len
vision_pos += max(grid_thw[1], grid_thw[2]) // spatial_merge_size
llm_positions = torch.cat(llm_pos_ids_list, dim=1).reshape(4, -1)
if attention_mask is not None:
position_ids[:, batch_idx, attention_mask[batch_idx].bool()] = llm_positions.to(position_ids.device)
else:
position_ids[:, batch_idx] = llm_positions.to(position_ids.device)
mrope_position_deltas.append(llm_positions.max() + 1 - len(current_input_ids))
mrope_position_deltas = torch.tensor(mrope_position_deltas, device=input_ids.device).unsqueeze(1)
return position_ids, mrope_position_deltas
def get_image_features(
self,
pixel_values: torch.FloatTensor,
image_grid_thw: torch.LongTensor,
**kwargs,
) -> torch.Tensor:
"""Run the vision encoder + projector, returning merged patch tokens.
Args:
pixel_values: ``(total_patches, C, patch_size, patch_size)``
pre-patchified tensor produced by the VenusOCR processor.
image_grid_thw: ``(num_images, 3)`` grid metadata ``(t, h, w)``.
Returns:
``(total_merged_tokens, text_hidden_size)`` projected features.
"""
pixel_values = pixel_values.to(dtype=self.visual.dtype) # type: ignore[assignment]
# Compute cumulative sequence lengths for packed attention (FA2)
cu_seqlens = torch.repeat_interleave(
image_grid_thw[:, 1] * image_grid_thw[:, 2],
image_grid_thw[:, 0],
).cumsum(
dim=0,
dtype=image_grid_thw.dtype if torch.jit.is_tracing() else torch.int32, # type: ignore[attr-defined]
)
cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
vision_outputs = self.visual(
pixel_values=pixel_values,
cu_seqlens=cu_seqlens,
image_grid_thw=image_grid_thw,
return_dict=True,
**kwargs,
)
image_embeds = vision_outputs.last_hidden_state
image_embeds = self.projector(image_embeds, image_grid_thw)
vision_outputs.pooler_output = image_embeds
return vision_outputs
def get_placeholder_mask(
self,
input_ids: torch.LongTensor,
inputs_embeds: torch.FloatTensor,
image_features: torch.FloatTensor,
):
"""
Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
equal to the length of multimodal features. If the lengths are different, an error is raised.
"""
if input_ids is None:
special_image_mask = inputs_embeds == self.get_input_embeddings()(
torch.tensor(self.config.image_token_id, dtype=torch.long, device=inputs_embeds.device)
)
special_image_mask = special_image_mask.all(-1)
else:
special_image_mask = input_ids == self.config.image_token_id
n_image_tokens = special_image_mask.sum()
special_image_mask = special_image_mask.unsqueeze(-1).expand_as(inputs_embeds).to(inputs_embeds.device)
n_image_features = image_features.shape[0] * image_features.shape[1]
torch_compilable_check(
inputs_embeds[special_image_mask].numel() == image_features.numel(),
f"Image features and image tokens do not match: tokens: {n_image_tokens}, features {n_image_features}",
)
return special_image_mask
def compute_3d_position_ids(
self,
input_ids: torch.Tensor | None,
inputs_embeds: torch.Tensor | None,
image_grid_thw: torch.Tensor | None = None,
video_grid_thw: torch.Tensor | None = None,
attention_mask: torch.Tensor | None = None,
past_key_values: torch.Tensor | None = None,
mm_token_type_ids: torch.IntTensor | None = None,
seq_ids: torch.LongTensor | None = None,
) -> torch.Tensor | None:
past_key_values_length = 0 if past_key_values is None else past_key_values.get_seq_length()
has_multimodal = image_grid_thw is not None or video_grid_thw is not None
if has_multimodal and mm_token_type_ids is None and input_ids is not None:
raise ValueError(
"Multimodal data was passed (via `image_grid_thw` or `video_grid_thw`) but `mm_token_type_ids` is "
"missing. Please pass `mm_token_type_ids` to the model so that multimodal RoPE (M-RoPE) can be "
"computed correctly. `mm_token_type_ids` is returned by the processor alongside `input_ids`."
)
can_compute_mrope = input_ids is not None and mm_token_type_ids is not None and has_multimodal
if can_compute_mrope and (self.rope_deltas is None or past_key_values_length == 0):
position_ids, rope_deltas = self.get_rope_index(
input_ids,
image_grid_thw=image_grid_thw,
video_grid_thw=video_grid_thw,
attention_mask=attention_mask,
mm_token_type_ids=mm_token_type_ids,
seq_ids=seq_ids,
)
self.rope_deltas = rope_deltas
# Use pre-calculated rope-deltas to infer correct 4D position ids during incremental
# generation (past_key_values_length > 0) or when only inputs_embeds is provided (no input_ids
# to recompute from). Skip when input_ids is provided without past_key_values to avoid shape
# mismatches from stale rope_deltas (e.g., training forward pass after generation).
elif self.rope_deltas is not None and (past_key_values_length > 0 or input_ids is None):
batch_size, seq_length, _ = inputs_embeds.shape
if attention_mask is not None:
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids = position_ids.masked_fill(attention_mask == 0, 0)
# 4 channels: text(0), temporal(1), height(2), width(3)
position_ids = position_ids.view(1, batch_size, -1).repeat(4, 1, 1).to(inputs_embeds.device)
else:
position_ids = torch.arange(past_key_values_length, past_key_values_length + seq_length)
position_ids = position_ids.view(1, 1, -1).expand(4, batch_size, -1).to(inputs_embeds.device)
delta = self.rope_deltas.repeat_interleave(batch_size // self.rope_deltas.shape[0], dim=0)
position_ids = position_ids + delta.to(device=inputs_embeds.device)
else:
# Can't build correct M-RoPE positions. Let the model infer it.
position_ids = None
return position_ids
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
pixel_values: Optional[torch.FloatTensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
mm_token_type_ids: Optional[torch.IntTensor] = None,
seq_ids: Optional[torch.LongTensor] = None,
**kwargs,
) -> Union[tuple, VenusOCRModelOutputWithPast]:
r"""
pixel_values (`torch.FloatTensor`, *optional*):
Pre-patchified tensor ``(total_patches, C, patch_size, patch_size)``.
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
``(temporal, height, width)`` grid size for each image.
mm_token_type_ids (`torch.IntTensor` of shape `(batch_size, seq_len)`, *optional*):
Modality type ids: 0=text, 1=image. Returned by the processor.
seq_ids (`torch.LongTensor` of shape `(batch_size, seq_len)`, *optional*):
Per-token sub-sequence id used by sequence packing. Different
values delimit packed sub-sequences and trigger M-RoPE position
resets at their boundaries (see ``get_rope_index``). When
``None`` the whole row is treated as a single sub-sequence.
"""
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.get_input_embeddings()(input_ids)
if pixel_values is not None:
image_outputs = self.get_image_features(
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
)
image_embeds = image_outputs.pooler_output
image_embeds = image_embeds.to(inputs_embeds.device, inputs_embeds.dtype)
image_mask = self.get_placeholder_mask(
input_ids=input_ids,
inputs_embeds=inputs_embeds,
image_features=image_embeds,
)
inputs_embeds = inputs_embeds.masked_scatter(image_mask, image_embeds) # type: ignore[assignment]
if position_ids is None:
position_ids = self.compute_3d_position_ids( # type: ignore[assignment]
input_ids=input_ids,
inputs_embeds=inputs_embeds,
image_grid_thw=image_grid_thw,
attention_mask=attention_mask,
past_key_values=past_key_values,
mm_token_type_ids=mm_token_type_ids,
seq_ids=seq_ids,
)
outputs = self.language_model(
input_ids=None,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
**kwargs,
)
return VenusOCRModelOutputWithPast(
**outputs,
rope_deltas=self.rope_deltas, # type: ignore[arg-type]
)
@auto_docstring(
custom_intro="""
VenusOCR multimodal model with a language modelling head on top, suitable
for conditional text generation from image-text interleaved sequences.
The model architecture is:
1. **Vision encoder** – SigLIP-based ViT (customised with 2D RoPE + packed-sequence attention)
2. **Spatial-merge projector** – groups spatial_merge_size² patches, MLP to LLM hidden size
3. **Language decoder** – Qwen3-0.6B causal language model
"""
)
class VenusOCRForConditionalGeneration(VenusOCRPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
# Tell HF Trainer to pass num_items_in_batch (and other loss kwargs) into forward().
accepts_loss_kwargs = True
def __init__(self, config: VenusOCRConfig) -> None:
super().__init__(config)
self.model = VenusOCRModel(config)
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self) -> nn.Module:
return self.model.get_input_embeddings()
def set_input_embeddings(self, value: nn.Module) -> None:
self.model.set_input_embeddings(value)
def get_image_features(
self,
pixel_values: torch.FloatTensor,
image_grid_thw: torch.LongTensor,
**kwargs,
) -> torch.Tensor:
"""Convenience wrapper – see :meth:`VenusOCRModel.get_image_features`."""
return self.model.get_image_features(pixel_values=pixel_values, image_grid_thw=image_grid_thw, **kwargs,)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
mm_token_type_ids: Optional[torch.IntTensor] = None,
seq_ids: Optional[torch.LongTensor] = None,
labels: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
num_items_in_batch: Optional[int] = None,
**kwargs,
) -> Union[tuple, VenusOCRCausalLMOutputWithPast]:
r"""
pixel_values (`torch.FloatTensor`, *optional*):
Pre-patchified tensor ``(total_patches, C, patch_size, patch_size)``.
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
``(temporal, height, width)`` grid size. Required for 2D M-RoPE.
mm_token_type_ids (`torch.IntTensor`, *optional*):
Modality type ids (0=text, 1=image). Returned by the processor.
seq_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Per-token sub-sequence id used by sequence packing. Different
values delimit packed sub-sequences and trigger M-RoPE position
resets at their boundaries (see ``VenusOCRModel.get_rope_index``).
``None`` (default) means the whole row is treated as a single
sub-sequence (non-packing inference / training).
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Target token ids. Positions set to ``-100`` are ignored.
logits_to_keep (`int` or `torch.Tensor`, *optional*, defaults to 0):
If an ``int``, compute logits for only the last ``logits_to_keep`` tokens.
``0`` computes logits for all tokens.
num_items_in_batch (`int`, *optional*):
Number of sequences (or tokens, depending on loss_reduction_scope) in
the full gradient-accumulation window across all devices. Supplied by
VenusOCRTrainer.get_batch_samples and used by cross_entropy_loss for
consistent normalisation regardless of world size.
Example::
>>> from transformers import AutoModelForCausalLM, AutoProcessor
>>> model = AutoModelForCausalLM.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True)
>>> processor = AutoProcessor.from_pretrained("VenusOCR/VenusOCR2-1B", trust_remote_code=True)
>>> inputs = processor(images=image, text=prompt, return_tensors="pt")
>>> output = model.generate(**inputs, max_new_tokens=256)
"""
outputs = self.model(
input_ids=input_ids,
pixel_values=pixel_values,
image_grid_thw=image_grid_thw,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
mm_token_type_ids=mm_token_type_ids,
seq_ids=seq_ids,
**kwargs,
)
hidden_states = outputs[0]
slice_indices = (
slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
)
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
reduction_scope = getattr(self.config, "loss_reduction_scope", "batch")
loss_kwargs = {}
if num_items_in_batch is not None:
loss_kwargs["num_items_in_batch"] = num_items_in_batch
# position_ids may be 3D (M-RoPE): take first row for sequence boundary detection
_pos = outputs.get("position_ids", position_ids) if hasattr(outputs, "get") else position_ids
if _pos is not None and _pos.dim() == 3:
_pos = _pos[0] # (seq_len,) or (1, seq_len)
loss = _cross_entropy_loss(
hidden_states=hidden_states,
lm_head=self.lm_head,
position_ids=_pos if _pos is not None else torch.zeros(
hidden_states.shape[:2], dtype=torch.long, device=hidden_states.device
),
labels=labels,
reduction_scope=reduction_scope,
**loss_kwargs,
)
return VenusOCRCausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
rope_deltas=outputs.rope_deltas,
)
def prepare_inputs_for_generation(
self,
input_ids,
next_sequence_length=None,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
is_first_iteration=False,
**kwargs,
):
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
model_inputs = super().prepare_inputs_for_generation(
input_ids,
next_sequence_length=next_sequence_length,
past_key_values=past_key_values,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
is_first_iteration=is_first_iteration,
**kwargs,
)
# Only pass pixel_values and image_grid_thw on the first generation step;
# afterwards the image features are already in the KV-cache.
if not is_first_iteration and model_inputs.get("use_cache", True):
model_inputs["pixel_values"] = None
model_inputs["image_grid_thw"] = None
return model_inputs
def _prepare_position_ids_for_generation(self, inputs_tensor, model_kwargs):
# Overwritten -- requires 4D position ids for M-RoPE (text + temporal + height + width)
text_positions = super()._prepare_position_ids_for_generation(inputs_tensor, model_kwargs)
# Early exit in case we are continuing generation from past kv
past_length = 0
if (cache := model_kwargs.get("past_key_values")) is not None:
past_length = cache.get_seq_length()
if past_length != 0 and self.model.rope_deltas is not None:
# Incremental decode: text_positions is (B, T), expand to (4, B, T) + delta
position_ids = text_positions[None, ...].expand(4, -1, -1) + self.model.rope_deltas
return position_ids
# Otherwise compute 4D position ids for vision tokens
if "input_ids" in model_kwargs and model_kwargs["input_ids"].shape[1] > 0:
inputs_tensor = model_kwargs["input_ids"]
is_input_ids = len(inputs_tensor.shape) == 2 and inputs_tensor.dtype in [torch.int, torch.long]
if (
is_input_ids
and model_kwargs.get("mm_token_type_ids") is not None
and model_kwargs.get("image_grid_thw") is not None
):
model_kwargs = {k: v for k, v in model_kwargs.items() if k != "input_ids"}
# get_rope_index returns (4, B, T) position_ids already containing
# [text_axis, temporal, height, width]
position_ids, rope_deltas = self.model.get_rope_index(inputs_tensor, **model_kwargs)
self.model.rope_deltas = rope_deltas
else:
# Pure text: all 4 channels use the same text_positions
position_ids = text_positions[None, ...].expand(4, -1, -1).contiguous()
self.model.rope_deltas = torch.zeros(
inputs_tensor.shape[0], 1, dtype=torch.long, device=inputs_tensor.device
)
return position_ids
def _get_image_nums(
self,
input_ids: Optional[torch.LongTensor],
inputs_embeds: Optional[torch.Tensor] = None,
) -> torch.Tensor:
"""
Get the number of images for each sample in the batch.
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
inputs_embeds (`torch.Tensor`, *optional*):
Optional input embeddings (used when input_ids is None).
Returns:
image_nums (`torch.LongTensor` of shape `(batch_size,)`)
"""
image_token_id = self.config.image_token_id
if inputs_embeds is not None:
image_mask = (
inputs_embeds
== self.get_input_embeddings()(
torch.tensor(image_token_id, dtype=torch.long, device=inputs_embeds.device)
)
)[..., 0]
device = inputs_embeds.device
batch_size = inputs_embeds.shape[0]
else:
image_mask = input_ids == image_token_id
device = input_ids.device
batch_size = input_ids.shape[0]
# Count number of contiguous image-token blocks per sample (= number of images)
image_nums = torch.zeros(batch_size, dtype=torch.long, device=device)
for b in range(batch_size):
mask_b = image_mask[b]
if mask_b.any():
padded = torch.cat([mask_b.new_zeros(1), mask_b])
rising_edges = (padded[1:].long() - padded[:-1].long()).clamp(min=0)
image_nums[b] = rising_edges.sum()
return image_nums
@staticmethod
def _expand_inputs_for_generation(
expand_size: int = 1,
is_encoder_decoder: bool = False,
input_ids: Optional[torch.LongTensor] = None,
**model_kwargs,
) -> tuple:
# Overwritten -- support for expanding tensors without a batch size dimension
# e.g., pixel_values (shape: [total_patches, C, pH, pW]) and image_grid_thw (shape: [num_images, 3])
# whose first dimension is NOT the batch size.
if expand_size == 1:
return input_ids, model_kwargs
visual_keys = ["pixel_values", "image_grid_thw"]
def _get_image_nums_static(input_ids_local, model_kwargs_local):
"""Count contiguous image-token groups per sample."""
from .configuration_venusocr import VenusOCRConfig # avoid circular at module level
# Obtain image_token_id via model_kwargs if possible; fall back to searching input_ids
image_grid_thw = model_kwargs_local.get("image_grid_thw", None)
if image_grid_thw is None or input_ids_local is None:
return None
# Simple heuristic: total images = image_grid_thw.shape[0], assume evenly distributed
# across batch. For expand we just need per-sample image counts.
# Use mm_token_type_ids if available, otherwise count from input_ids.
mm_token_type_ids = model_kwargs_local.get("mm_token_type_ids", None)
batch_size = input_ids_local.shape[0]
if mm_token_type_ids is not None:
# Count runs of type 1 (image) per sample
image_nums = torch.zeros(batch_size, dtype=torch.long, device=input_ids_local.device)
for b in range(batch_size):
mask_b = (mm_token_type_ids[b] == 1)
if mask_b.any():
padded = torch.cat([mask_b.new_zeros(1), mask_b])
rising = (padded[1:].long() - padded[:-1].long()).clamp(min=0)
image_nums[b] = rising.sum()
return image_nums
return None
def _expand_dict_for_generation_visual(dict_to_expand):
image_grid_thw = model_kwargs.get("image_grid_thw", None)
if image_grid_thw is None:
return dict_to_expand
image_nums = _get_image_nums_static(input_ids, model_kwargs)
if image_nums is None:
return dict_to_expand
def _repeat_interleave_samples(x, lengths, repeat_times):
samples = torch.split(x, lengths)
repeat_args = [repeat_times] + [1] * (x.dim() - 1)
result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
return result
for key in list(dict_to_expand.keys()):
if key == "pixel_values" and dict_to_expand[key] is not None:
samples = torch.split(image_grid_thw, image_nums.tolist())
lengths = [int(s.prod(dim=1).sum().item()) for s in samples]
dict_to_expand[key] = _repeat_interleave_samples(
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
)
elif key == "image_grid_thw" and dict_to_expand[key] is not None:
lengths = image_nums.tolist()
dict_to_expand[key] = _repeat_interleave_samples(
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
)
return dict_to_expand
def _expand_dict_for_generation(dict_to_expand):
for key in dict_to_expand:
if key == "position_ids" and dict_to_expand[key] is not None and dict_to_expand[key].ndim == 3:
dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=1)
elif (
dict_to_expand[key] is not None
and isinstance(dict_to_expand[key], torch.Tensor)
and key not in visual_keys
):
dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
return dict_to_expand
model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
if input_ids is not None:
input_ids = input_ids.repeat_interleave(expand_size, dim=0)
model_kwargs = _expand_dict_for_generation(model_kwargs)
if is_encoder_decoder:
if model_kwargs.get("encoder_outputs") is None:
raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
return input_ids, model_kwargs
__all__ = [
"VenusOCRPreTrainedModel",
"VenusOCRModel",
"VenusOCRForConditionalGeneration",
"VenusOCRVisionTransformer",
"VenusOCRTextModel",
]
|