File size: 73,816 Bytes
2415c4c | 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 | # SPDX-FileCopyrightText: © 2026 Tenstorrent AI ULC
# SPDX-License-Identifier: Apache-2.0
"""Generic host-only executor/generator integration for migrated siblings."""
import inspect
from dataclasses import replace
from importlib import import_module
from types import SimpleNamespace
from unittest.mock import MagicMock, create_autospec
import pytest
import torch
import ttnn
from models.common.llm_runtime.config import PagedKVCacheConfig, PageTableLayout, TraceConfig, WarmupConfig
from models.common.llm_runtime.decode import DecodeTraceSignature
from models.common.llm_runtime.execution import EagerExecutor
from models.common.llm_runtime.lane_group import LaneGroupExecutor
from models.common.llm_runtime.prefill.signatures import PrefillProgramSignature
from models.common.llm_runtime.program_compiler import ProgramKey
from models.common.llm_runtime.warmup import _build_plan
from models.common.models import executor as shared_model_executor
from models.common.models import llama3_executor as llama3_family_executor
from models.common.models import qwen2_executor as qwen2_family_executor
from models.common.models.deepseek_r1_distill_qwen_14b import executor as deepseek_executor
from models.common.models.deepseek_r1_distill_qwen_14b import generator as deepseek_generator
from models.common.models.llama32_1b import executor as llama32_executor
from models.common.models.llama32_1b import generator as llama32_generator
from models.common.models.llama32_3b import executor as llama32_3b_executor
from models.common.models.llama32_3b import generator as llama32_3b_generator
from models.common.models.llama33_70b import executor as llama33_70b_executor
from models.common.models.llama33_70b import generator as llama33_70b_generator
from models.common.models.mistral_7b import executor as mistral_executor
from models.common.models.mistral_7b import generator as mistral_generator
from models.common.models.phi4 import executor as phi4_executor
from models.common.models.phi4 import generator as phi4_generator
from models.common.models.qwen2_7b import executor as qwen2_executor
from models.common.models.qwen2_7b import generator as qwen2_generator
from models.common.models.qwen3_32b import executor as qwen3_32b_executor
from models.common.models.qwen3_32b import generator as qwen3_32b_generator
from models.common.models.qwen25_7b import executor as qwen25_executor
from models.common.models.qwen25_7b import generator as qwen25_generator
from models.common.models.qwen25_72b import executor as qwen25_72b_executor
from models.common.models.qwen25_72b import generator as qwen25_72b_generator
from models.common.models.qwen25_coder_32b import executor as qwen25_coder_32b_executor
from models.common.models.qwen25_coder_32b import generator as qwen25_coder_32b_generator
EXECUTOR_BINDINGS = {
"llama32_1b": SimpleNamespace(
executor_module=llama32_executor,
executor_class=llama32_executor.Llama32_1BExecutor,
executor_config_class=llama32_executor.Llama32_1BExecutorConfig,
generator_module=llama32_generator,
generator_class=llama32_generator.Llama32_1BGenerator,
generator_config_class=llama32_generator.Llama32_1BGeneratorConfig,
build_generator_name="build_llama32_1b_generator",
build_executor_name="build_llama32_1b_executor",
make_model=lambda **kwargs: _make_llama32_model(**kwargs),
make_runtime_config=lambda: _make_llama32_runtime_config(),
make_executor_config=lambda mode="none": _make_llama32_executor_config(mode),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_llama32_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_llama32_product(mesh_device, max_batch_size),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="meta-llama/Llama-3.2-1B-Instruct",
),
"llama32_3b": SimpleNamespace(
executor_module=llama32_3b_executor,
executor_class=llama32_3b_executor.Llama32_3BExecutor,
executor_config_class=llama32_3b_executor.Llama32_3BExecutorConfig,
generator_module=llama32_3b_generator,
generator_class=llama32_3b_generator.Llama32_3BGenerator,
generator_config_class=llama32_3b_generator.Llama32_3BGeneratorConfig,
build_generator_name="build_llama32_3b_generator",
build_executor_name="build_llama32_3b_executor",
make_model=lambda **kwargs: _make_llama32_model(**kwargs),
make_runtime_config=lambda: _make_llama32_runtime_config(),
make_executor_config=lambda mode="none": _make_llama32_executor_config(mode, module=llama32_3b_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_llama32_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_llama32_product(mesh_device, max_batch_size),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="meta-llama/Llama-3.2-3B-Instruct",
),
"llama33_70b": SimpleNamespace(
executor_module=llama33_70b_executor,
executor_class=llama33_70b_executor.Llama33_70BExecutor,
executor_config_class=llama33_70b_executor.Llama33_70BExecutorConfig,
generator_module=llama33_70b_generator,
generator_class=llama33_70b_generator.Llama33_70BGenerator,
generator_config_class=llama33_70b_generator.Llama33_70BGeneratorConfig,
build_generator_name="build_llama33_70b_generator",
build_executor_name="build_llama33_70b_executor",
make_model=lambda **kwargs: _make_llama32_model(**kwargs),
make_runtime_config=lambda: _make_llama32_runtime_config(),
make_executor_config=lambda mode="none": _make_llama32_executor_config(mode, module=llama33_70b_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(
_make_llama32_model(),
request_state_fields=llama33_70b_executor.Llama33_70BExecutor.request_state_fields,
**kwargs,
),
make_product=lambda mesh_device, max_batch_size: _make_llama32_product(mesh_device, max_batch_size),
make_lane=lambda llm, config: _FakeLane(
llm, config, request_state_fields=llama33_70b_executor.Llama33_70BExecutor.request_state_fields
),
hf_model="meta-llama/Llama-3.3-70B-Instruct",
),
"qwen2_7b": SimpleNamespace(
executor_module=qwen2_executor,
executor_class=qwen2_executor.Qwen2Executor,
executor_config_class=qwen2_executor.Qwen2ExecutorConfig,
generator_module=qwen2_generator,
generator_class=qwen2_generator.Qwen2Generator,
generator_config_class=qwen2_generator.Qwen2GeneratorConfig,
build_generator_name="build_qwen2_7b_generator",
build_executor_name="build_qwen2_7b_executor",
make_model=lambda **kwargs: _make_qwen2_model(**kwargs),
make_runtime_config=lambda: _make_qwen2_runtime_config(),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_qwen2_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_qwen2_product(mesh_device, max_batch_size),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="Qwen/Qwen2-7B-Instruct",
),
"qwen25_7b": SimpleNamespace(
executor_module=qwen25_executor,
executor_class=qwen25_executor.Qwen25Executor,
executor_config_class=qwen25_executor.Qwen25ExecutorConfig,
generator_module=qwen25_generator,
generator_class=qwen25_generator.Qwen25Generator,
generator_config_class=qwen25_generator.Qwen25GeneratorConfig,
build_generator_name="build_qwen25_7b_generator",
build_executor_name="build_qwen25_7b_executor",
make_model=lambda **kwargs: _make_qwen2_model(**kwargs),
make_runtime_config=lambda: _make_qwen2_runtime_config(max_prefill_batch_size=8),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode, module=qwen25_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_qwen2_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_qwen2_product(
mesh_device, max_batch_size, max_prefill_batch_size=8
),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="Qwen/Qwen2.5-7B-Instruct",
),
"qwen25_72b": SimpleNamespace(
executor_module=qwen25_72b_executor,
executor_class=qwen25_72b_executor.Qwen25_72BExecutor,
executor_config_class=qwen25_72b_executor.Qwen25_72BExecutorConfig,
generator_module=qwen25_72b_generator,
generator_class=qwen25_72b_generator.Qwen25_72BGenerator,
generator_config_class=qwen25_72b_generator.Qwen25_72BGeneratorConfig,
build_generator_name="build_qwen25_72b_generator",
build_executor_name="build_qwen25_72b_executor",
make_model=lambda **kwargs: _make_qwen25_72b_model(**kwargs),
make_runtime_config=lambda: _make_qwen25_72b_runtime_config(),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode, module=qwen25_72b_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_qwen25_72b_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_qwen25_72b_product(mesh_device, max_batch_size),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="Qwen/Qwen2.5-72B-Instruct",
),
"qwen25_coder_32b": SimpleNamespace(
executor_module=qwen25_coder_32b_executor,
executor_class=qwen25_coder_32b_executor.Qwen25Coder32BExecutor,
executor_config_class=qwen25_coder_32b_executor.Qwen25Coder32BExecutorConfig,
generator_module=qwen25_coder_32b_generator,
generator_class=qwen25_coder_32b_generator.Qwen25Coder32BGenerator,
generator_config_class=qwen25_coder_32b_generator.Qwen25Coder32BGeneratorConfig,
build_generator_name="build_qwen25_coder_32b_generator",
build_executor_name="build_qwen25_coder_32b_executor",
make_model=lambda **kwargs: _make_qwen25_coder_32b_model(**kwargs),
make_runtime_config=lambda: _make_qwen25_coder_32b_runtime_config(),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode, module=qwen25_coder_32b_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_qwen25_coder_32b_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_qwen25_coder_32b_product(mesh_device, max_batch_size),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="Qwen/Qwen2.5-Coder-32B-Instruct",
),
"qwen3_32b": SimpleNamespace(
executor_module=qwen3_32b_executor,
executor_class=qwen3_32b_executor.Qwen3_32BExecutor,
executor_config_class=qwen3_32b_executor.Qwen3_32BExecutorConfig,
generator_module=qwen3_32b_generator,
generator_class=qwen3_32b_generator.Qwen3_32BGenerator,
generator_config_class=qwen3_32b_generator.Qwen3_32BGeneratorConfig,
build_generator_name="build_qwen3_32b_generator",
build_executor_name="build_qwen3_32b_executor",
make_model=lambda **kwargs: _make_qwen3_32b_model(**kwargs),
make_runtime_config=lambda: _make_qwen3_32b_runtime_config(),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode, module=qwen3_32b_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(
_make_qwen3_32b_model(),
request_state_fields=qwen3_32b_executor.Qwen3_32BExecutor.request_state_fields,
**kwargs,
),
make_product=lambda mesh_device, max_batch_size: _make_qwen3_32b_product(mesh_device, max_batch_size),
make_lane=lambda llm, config: _FakeLane(
llm, config, request_state_fields=qwen3_32b_executor.Qwen3_32BExecutor.request_state_fields
),
hf_model="Qwen/Qwen3-32B",
),
"deepseek_r1_distill_qwen_14b": SimpleNamespace(
executor_module=deepseek_executor,
executor_class=deepseek_executor.DeepSeekR1Qwen14BExecutor,
executor_config_class=deepseek_executor.DeepSeekR1Qwen14BExecutorConfig,
generator_module=deepseek_generator,
generator_class=deepseek_generator.DeepSeekR1Qwen14BGenerator,
generator_config_class=deepseek_generator.DeepSeekR1Qwen14BGeneratorConfig,
build_generator_name="build_deepseek_r1_distill_qwen_14b_generator",
build_executor_name="build_deepseek_r1_distill_qwen_14b_executor",
make_model=lambda **kwargs: _make_qwen2_model(**kwargs),
make_runtime_config=lambda: _make_qwen2_runtime_config(max_prefill_batch_size=32),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode, module=deepseek_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_qwen2_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_qwen2_product(
mesh_device, max_batch_size, max_prefill_batch_size=32
),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="deepseek-ai/DeepSeek-R1-Distill-Qwen-14B",
),
"mistral_7b": SimpleNamespace(
executor_module=mistral_executor,
executor_class=mistral_executor.Mistral7BExecutor,
executor_config_class=mistral_executor.Mistral7BExecutorConfig,
generator_module=mistral_generator,
generator_class=mistral_generator.Mistral7BGenerator,
generator_config_class=mistral_generator.Mistral7BGeneratorConfig,
build_generator_name="build_mistral_7b_generator",
build_executor_name="build_mistral_7b_executor",
make_model=lambda **kwargs: _make_qwen2_model(**kwargs),
make_runtime_config=lambda: _make_qwen2_runtime_config(max_prefill_batch_size=8),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode, module=mistral_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_qwen2_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_qwen2_product(
mesh_device, max_batch_size, max_prefill_batch_size=8
),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="mistralai/Mistral-7B-Instruct-v0.3",
),
"phi4": SimpleNamespace(
executor_module=phi4_executor,
executor_class=phi4_executor.Phi4Executor,
executor_config_class=phi4_executor.Phi4ExecutorConfig,
generator_module=phi4_generator,
generator_class=phi4_generator.Phi4Generator,
generator_config_class=phi4_generator.Phi4GeneratorConfig,
build_generator_name="build_phi4_generator",
build_executor_name="build_phi4_executor",
make_model=lambda **kwargs: _make_qwen2_model(**kwargs),
make_runtime_config=lambda: _make_qwen2_runtime_config(max_prefill_batch_size=8),
make_executor_config=lambda mode="none": _make_qwen2_executor_config(mode, module=phi4_executor),
make_recording_target=lambda **kwargs: _RecordingTarget(_make_qwen2_model(), **kwargs),
make_product=lambda mesh_device, max_batch_size: _make_qwen2_product(
mesh_device, max_batch_size, max_prefill_batch_size=8
),
make_lane=lambda llm, config: _FakeLane(llm, config),
hf_model="microsoft/phi-4",
),
}
GENERATOR_PATHS = {
"llama32_1b": "models.common.models.llama32_1b.generator:Llama32_1BGenerator",
"llama32_3b": "models.common.models.llama32_3b.generator:Llama32_3BGenerator",
"llama33_70b": "models.common.models.llama33_70b.generator:Llama33_70BGenerator",
"mistral_7b": "models.common.models.mistral_7b.generator:Mistral7BGenerator",
"phi4": "models.common.models.phi4.generator:Phi4Generator",
"qwen2_7b": "models.common.models.qwen2_7b.generator:Qwen2Generator",
"qwen25_7b": "models.common.models.qwen25_7b.generator:Qwen25Generator",
"qwen25_72b": "models.common.models.qwen25_72b.generator:Qwen25_72BGenerator",
"qwen25_coder_32b": "models.common.models.qwen25_coder_32b.generator:Qwen25Coder32BGenerator",
"qwen3_32b": "models.common.models.qwen3_32b.generator:Qwen3_32BGenerator",
"deepseek_r1_distill_qwen_14b": (
"models.common.models.deepseek_r1_distill_qwen_14b.generator:DeepSeekR1Qwen14BGenerator"
),
}
@pytest.fixture(params=EXECUTOR_BINDINGS.items(), ids=lambda item: item[0])
def binding(request):
return request.param[1]
_LLAMA_FAMILY_EXECUTOR_MODULES = (llama32_executor, llama32_3b_executor, llama33_70b_executor)
_QWEN2_FAMILY_EXECUTOR_MODULES = (
qwen2_executor,
qwen25_executor,
qwen25_72b_executor,
qwen25_coder_32b_executor,
)
_SHARED_MODEL_EXECUTOR_MODULES = (
*_LLAMA_FAMILY_EXECUTOR_MODULES,
*_QWEN2_FAMILY_EXECUTOR_MODULES,
qwen3_32b_executor,
)
def _composition_module(binding):
if binding.executor_module in _SHARED_MODEL_EXECUTOR_MODULES:
return shared_model_executor
return binding.executor_module
def _sampling_policy_module(binding):
if binding.executor_module in _LLAMA_FAMILY_EXECUTOR_MODULES:
return llama3_family_executor
if binding.executor_module in _QWEN2_FAMILY_EXECUTOR_MODULES:
return qwen2_family_executor
return binding.executor_module
class _Mesh:
shape = (1, 1)
@staticmethod
def get_num_devices():
return 1
class _Mesh2:
shape = (1, 2)
@staticmethod
def get_num_devices():
return 2
class _Mesh8:
shape = (1, 8)
@staticmethod
def get_num_devices():
return 8
def _make_llama32_model(max_batch_size=4):
paged = SimpleNamespace(block_size=32, max_num_blocks=132)
attention = SimpleNamespace(
n_kv_heads=8,
head_dim=64,
kv_cache_dtype=ttnn.bfloat8_b,
paged_attention_config=paged,
use_vllm_paged_kv_cache=True,
kv_cache=None,
)
live = SimpleNamespace(config=attention, kv_cache=None)
model = SimpleNamespace(
config=SimpleNamespace(
mesh_device=_Mesh(),
max_batch_size=max_batch_size,
max_seq_len=4096,
n_layers=1,
num_devices=1,
block_configs=(SimpleNamespace(attention_config=attention),),
),
layers=(SimpleNamespace(attention=live),),
iter_executor_named_modules=lambda: (),
vocab_size=128256,
num_devices=1,
)
def configure_paged_attention(*, block_size, max_num_blocks):
assert attention.kv_cache is None
assert live.kv_cache is None
attention.paged_attention_config = SimpleNamespace(
block_size=block_size,
max_num_blocks=max_num_blocks,
)
model.configure_paged_attention = configure_paged_attention
return model
def _make_llama32_runtime_config():
return SimpleNamespace(
model_cache_path="cache",
max_prefill_chunk_size=2048,
trace_prefill_supported_seq_lens=(128,),
can_enable_trace=lambda length, num_cached_tokens=0: length == 128,
supports_batched_prefill=True,
disable_batched_prefill=False,
max_prefill_batch_size=32,
batched_prefill_batched_extract=True,
)
def _make_llama32_executor_config(mode="none", *, module=llama32_executor):
config_class = next(
getattr(module, name)
for name in (
"Llama32_1BExecutorConfig",
"Llama32_3BExecutorConfig",
"Llama33_70BExecutorConfig",
)
if hasattr(module, name)
)
return config_class(
trace=TraceConfig(mode),
warmup=WarmupConfig(prefill_seq_lens=(128,), prefill_batch_sizes=(1,)),
paged_kv_cache=PagedKVCacheConfig(block_size=32, max_num_blocks=132, dtype=ttnn.bfloat8_b),
device_sampling_enabled=False,
)
def _make_llama32_product(mesh_device, max_batch_size):
model = _make_llama32_model(max_batch_size=max_batch_size)
model.config.mesh_device = mesh_device
return SimpleNamespace(model=model, runtime_config=_make_llama32_runtime_config())
def _make_qwen2_model(max_batch_size=4):
model = _make_llama32_model(max_batch_size=max_batch_size)
model.config.mesh_device = _Mesh2()
model.config.num_devices = 2
model.num_devices = 2
attention = model.layers[0].attention.config
attention.n_kv_heads = 4
attention.head_dim = 128
return model
def _make_qwen2_runtime_config(*, max_prefill_batch_size=32):
runtime = _make_llama32_runtime_config()
runtime.trace_prefill_supported_seq_lens = (128, 1024)
runtime.can_enable_trace = lambda length, num_cached_tokens=0: length in (128, 1024)
runtime.max_prefill_batch_size = max_prefill_batch_size
return runtime
def _make_qwen2_executor_config(mode="none", *, module=qwen2_executor):
config_class = (
getattr(module, "Qwen2ExecutorConfig", None)
or getattr(module, "Qwen25ExecutorConfig", None)
or getattr(module, "Qwen25_72BExecutorConfig", None)
or getattr(module, "Qwen25Coder32BExecutorConfig", None)
or getattr(module, "Qwen3_32BExecutorConfig", None)
or getattr(module, "DeepSeekR1Qwen14BExecutorConfig", None)
or getattr(module, "Mistral7BExecutorConfig", None)
or module.Phi4ExecutorConfig
)
return config_class(
trace=TraceConfig(mode),
warmup=WarmupConfig(prefill_seq_lens=(128, 1024), prefill_batch_sizes=(1,)),
paged_kv_cache=PagedKVCacheConfig(block_size=32, max_num_blocks=132, dtype=ttnn.bfloat8_b),
device_sampling_enabled=False,
)
def _make_qwen2_product(mesh_device, max_batch_size, *, max_prefill_batch_size=32):
model = _make_qwen2_model(max_batch_size=max_batch_size)
model.config.mesh_device = mesh_device
return SimpleNamespace(
model=model,
runtime_config=_make_qwen2_runtime_config(max_prefill_batch_size=max_prefill_batch_size),
)
def _make_qwen25_72b_model(max_batch_size=4):
model = _make_llama32_model(max_batch_size=max_batch_size)
model.config.mesh_device = _Mesh8()
model.config.num_devices = 8
model.num_devices = 8
attention = model.layers[0].attention.config
attention.n_kv_heads = 8
attention.head_dim = 128
return model
def _make_qwen25_72b_runtime_config():
return _make_qwen2_runtime_config(max_prefill_batch_size=32)
def _make_qwen25_72b_product(mesh_device, max_batch_size):
model = _make_qwen25_72b_model(max_batch_size=max_batch_size)
model.config.mesh_device = mesh_device
return SimpleNamespace(model=model, runtime_config=_make_qwen25_72b_runtime_config())
def _make_qwen25_coder_32b_model(max_batch_size=4):
model = _make_qwen25_72b_model(max_batch_size=max_batch_size)
model.config.dim = 5120
model.config.n_heads = 40
model.config.hidden_dim = 27648
model.config.hf_model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
return model
def _make_qwen25_coder_32b_runtime_config():
runtime = _make_qwen25_72b_runtime_config()
runtime.max_prefill_chunk_size = 4096
runtime.can_enable_trace = lambda length, num_cached_tokens=0: num_cached_tokens == 0 and length in (128, 1024)
return runtime
def _make_qwen25_coder_32b_product(mesh_device, max_batch_size):
model = _make_qwen25_coder_32b_model(max_batch_size=max_batch_size)
model.config.mesh_device = mesh_device
return SimpleNamespace(model=model, runtime_config=_make_qwen25_coder_32b_runtime_config())
def _make_qwen3_32b_model(max_batch_size=4):
model = _make_qwen25_72b_model(max_batch_size=max_batch_size)
model.config.dim = 5120
model.config.n_heads = 64
model.config.hidden_dim = 27648
model.config.vocab_size = 151936
model.config.hf_model_id = "Qwen/Qwen3-32B"
model.padded_vocab_size = 152064
return model
def _make_qwen3_32b_runtime_config():
runtime = _make_qwen25_coder_32b_runtime_config()
runtime.max_prefill_chunk_size = 4096
return runtime
def _make_qwen3_32b_product(mesh_device, max_batch_size):
model = _make_qwen3_32b_model(max_batch_size=max_batch_size)
model.config.mesh_device = mesh_device
return SimpleNamespace(model=model, runtime_config=_make_qwen3_32b_runtime_config())
def test_qwen2_binding_preserves_tp2_runtime_and_sampling_defaults():
model = _make_qwen2_model()
_, num_layers, kv_heads_per_device, head_dim = qwen2_generator._model_kv_metadata(model)
runtime = _make_qwen2_runtime_config()
config = qwen2_generator.Qwen2GeneratorConfig(
hf_model="Qwen/Qwen2-7B-Instruct",
hf_revision="test-revision",
mesh_device=model.config.mesh_device,
max_batch_size=32,
max_seq_len=4096,
)
assert model.config.mesh_device.shape == (1, 2)
assert (num_layers, kv_heads_per_device, head_dim) == (1, 2, 128)
assert runtime.trace_prefill_supported_seq_lens == (128, 1024)
assert runtime.max_prefill_chunk_size == 2048
assert runtime.max_prefill_batch_size == 32
assert config.hf_revision == "test-revision"
assert config.device_sampling_enabled is False
def test_qwen25_72b_binding_preserves_tp8_runtime_and_sampling_defaults():
model = _make_qwen25_72b_model()
_, num_layers, kv_heads_per_device, head_dim = qwen25_72b_generator._model_kv_metadata(model)
runtime = _make_qwen25_72b_runtime_config()
config = qwen25_72b_generator.Qwen25_72BGeneratorConfig(
hf_model="Qwen/Qwen2.5-72B-Instruct",
mesh_device=model.config.mesh_device,
max_batch_size=32,
max_seq_len=4096,
)
assert model.config.mesh_device.shape == (1, 8)
assert (num_layers, kv_heads_per_device, head_dim) == (1, 1, 128)
assert runtime.trace_prefill_supported_seq_lens == (128, 1024)
assert runtime.max_prefill_chunk_size == 2048
assert runtime.max_prefill_batch_size == 32
assert config.hf_revision == qwen25_72b_generator.DEFAULT_HF_REVISION
assert config.device_sampling_enabled is False
def test_qwen25_coder_32b_binding_preserves_tp8_runtime_and_sampling_defaults():
model = _make_qwen25_coder_32b_model()
_, num_layers, kv_heads_per_device, head_dim = qwen25_coder_32b_generator._model_kv_metadata(model)
runtime = _make_qwen25_coder_32b_runtime_config()
config = qwen25_coder_32b_generator.Qwen25Coder32BGeneratorConfig(
hf_model="Qwen/Qwen2.5-Coder-32B-Instruct",
mesh_device=model.config.mesh_device,
max_batch_size=32,
max_seq_len=4096,
)
assert model.config.mesh_device.shape == (1, 8)
assert (num_layers, kv_heads_per_device, head_dim) == (1, 1, 128)
assert runtime.trace_prefill_supported_seq_lens == (128, 1024)
assert runtime.max_prefill_chunk_size == 4096
assert runtime.can_enable_trace(128, 0) is True
assert runtime.can_enable_trace(128, 1) is False
assert runtime.max_prefill_batch_size == 32
assert config.hf_revision == qwen25_coder_32b_generator.DEFAULT_HF_REVISION
assert config.device_sampling_enabled is False
@pytest.mark.parametrize(
"product_binding",
(EXECUTOR_BINDINGS["qwen25_72b"], EXECUTOR_BINDINGS["qwen25_coder_32b"]),
ids=("qwen25_72b", "qwen25_coder_32b"),
)
@pytest.mark.parametrize("device_sampling_enabled", (False, True), ids=("sampling-off", "sampling-on"))
def test_large_qwen_builder_threads_exact_decode_sampling_coverage(
monkeypatch,
product_binding,
device_sampling_enabled,
):
mesh_device = _Mesh()
product = product_binding.make_product(mesh_device, 4)
executor_configs = []
monkeypatch.setattr(product_binding.generator_module, "from_pretrained", lambda **kwargs: product)
monkeypatch.setattr(
product_binding.generator_module,
"_model_kv_metadata",
lambda model: ((ttnn.bfloat8_b,), 1, 1, 128),
)
def build_executor(llm, config):
executor_configs.append(config)
return product_binding.make_lane(llm, config)
monkeypatch.setattr(product_binding.generator_module, product_binding.build_executor_name, build_executor)
generator = getattr(product_binding.generator_module, product_binding.build_generator_name)(
product_binding.generator_config_class(
hf_model=product_binding.hf_model,
mesh_device=mesh_device,
max_batch_size=4,
max_seq_len=1024,
n_layers=1,
device_sampling_enabled=device_sampling_enabled,
)
)
try:
assert len(executor_configs) == 1
warmup = executor_configs[0].warmup
assert warmup.include_decode_top_k is device_sampling_enabled
plan = _build_plan(
warmup=warmup,
layout=PageTableLayout(block_size=32, raw_capacity_width=32, prefill_width=64, decode_width=32),
prefill_sequence_lengths=(128,),
lane_batch_size=4,
allow_force_argmax=True,
can_sample_on_device=device_sampling_enabled,
)
assert [case.sampling_path for case in plan.decode] == (
["logits", "argmax", "topk"] if device_sampling_enabled else ["logits"]
)
finally:
generator.cleanup()
def test_qwen3_32b_binding_preserves_tp8_runtime_and_padded_vocab_defaults():
model = _make_qwen3_32b_model()
_, num_layers, kv_heads_per_device, head_dim = qwen3_32b_generator._model_kv_metadata(model)
runtime = _make_qwen3_32b_runtime_config()
config = qwen3_32b_generator.Qwen3_32BGeneratorConfig(
hf_model="Qwen/Qwen3-32B",
mesh_device=model.config.mesh_device,
max_batch_size=32,
max_seq_len=4096,
)
assert model.config.mesh_device.shape == (1, 8)
assert (num_layers, kv_heads_per_device, head_dim) == (1, 1, 128)
assert model.config.vocab_size == 151936
assert model.padded_vocab_size == 152064
assert runtime.trace_prefill_supported_seq_lens == (128, 1024)
assert runtime.max_prefill_chunk_size == 4096
assert runtime.can_enable_trace(128, 0) is True
assert runtime.can_enable_trace(128, 1) is False
assert config.hf_revision == qwen3_32b_generator.DEFAULT_HF_REVISION
assert config.device_sampling_enabled is False
@pytest.mark.parametrize(
("cluster_shape", "disable_batched_prefill", "advertised_lengths", "expected"),
[
([1, 8], False, (128, 1024), (128, 1024)),
([1, 8], True, (128, 1024), (128, 1024)),
([1, 4], False, (128, 1024), ()),
([1, 8], False, (128,), (128,)),
],
ids=("t3k-batched", "t3k-sequential", "bh-batched", "t3k-low-ceiling"),
)
def test_qwen3_prefill_capture_primes_are_t3k_product_owned(
cluster_shape,
disable_batched_prefill,
advertised_lengths,
expected,
):
runtime = SimpleNamespace(
cluster_shape=cluster_shape,
disable_batched_prefill=disable_batched_prefill,
trace_prefill_supported_seq_lens=advertised_lengths,
can_enable_trace=lambda length, cached: length in advertised_lengths and cached == 0,
)
num_devices = int(cluster_shape[0]) * int(cluster_shape[1])
assert (
qwen3_32b_executor._resolve_trace_capture_prime_sequence_lengths(
runtime,
num_devices=num_devices,
)
== expected
)
def test_phi4_binding_preserves_cap8_trace_buckets_and_pinned_revision():
runtime = _make_qwen2_runtime_config(max_prefill_batch_size=8)
config = phi4_generator.Phi4GeneratorConfig(
hf_model="microsoft/phi-4",
mesh_device=_Mesh2(),
max_batch_size=32,
max_seq_len=4096,
)
assert runtime.trace_prefill_supported_seq_lens == (128, 1024)
assert runtime.max_prefill_chunk_size == 2048
assert runtime.max_prefill_batch_size == 8
assert config.hf_revision == phi4_generator.DEFAULT_HF_REVISION
assert config.device_sampling_enabled is False
@pytest.mark.parametrize("mode", ["none", "decode_only", "all"])
def test_model_owned_executor_has_exact_composition_and_owner_counts(binding, mode, monkeypatch):
owner_names = (
"PagedKVCacheManager",
"OutputReader",
"PrefillRuntime",
"DecodeRuntime",
"ProgramCompiler",
"EagerExecutor",
"TraceCompiler",
"TracedExecutor",
"WarmupCoordinator",
)
composition_module = _composition_module(binding)
owner_factories = {}
for name in owner_names:
factory = MagicMock(wraps=getattr(composition_module, name))
monkeypatch.setattr(composition_module, name, factory)
owner_factories[name] = factory
executor = binding.executor_class(
binding.make_model(),
binding.make_runtime_config(),
binding.make_executor_config(mode),
)
expected_counts = {name: 1 for name in owner_names}
if mode == "none":
expected_counts["TraceCompiler"] = 0
expected_counts["TracedExecutor"] = 0
assert {name: factory.call_count for name, factory in owner_factories.items()} == expected_counts
assert executor.eager_executor.program_compiler is executor.program_compiler
assert executor.eager_executor.prefill is executor.prefill_runtime
assert executor.eager_executor.decode is executor.decode_runtime
assert executor.warmup.eager is executor.eager_executor
assert executor.warmup.trace_compiler is executor.trace_compiler
assert executor.eager_execution is executor.eager_executor
assert executor.prefill_runtime.config.trace_capture_prime_sequence_lengths == (
(128, 1024) if binding.executor_module is qwen3_32b_executor else ()
)
if mode == "none":
assert executor.warmup.execution is executor.eager_executor
assert executor.trace_compiler is None
assert executor.traced_executor is None
assert executor.traced_prefill_execution is None
assert executor.traced_decode_execution is None
else:
assert executor.warmup.execution is executor.traced_executor
assert executor.traced_executor.eager_executor is executor.eager_executor
assert executor.traced_executor.trace_compiler is executor.trace_compiler
assert executor.trace_compiler.program_compiler is executor.program_compiler
assert (executor.traced_prefill_execution is not None) is (mode == "all")
assert executor.traced_decode_execution is executor.traced_executor
def test_llama3_create_sampling_state_disables_duplicate_seed_salting(monkeypatch):
captured = {}
class FakeSampling1D:
def __init__(self):
self.config = SimpleNamespace(is_resolved=lambda: True)
class FakeSamplingState1D:
def __init__(self, sampling, *, salt_duplicate_seeds=True, **_kwargs):
captured["salt_duplicate_seeds"] = salt_duplicate_seeds
self.sampling = sampling
def create_state(self):
return object()
monkeypatch.setattr(llama3_family_executor, "Sampling1D", FakeSampling1D)
monkeypatch.setattr(llama3_family_executor, "SamplingState1D", FakeSamplingState1D)
controller, state = llama3_family_executor._create_sampling_state(SimpleNamespace(sampling=FakeSampling1D()), True)
assert captured["salt_duplicate_seeds"] is False
assert controller is not None
assert state is not None
def test_qwen3_create_sampling_state_disables_duplicate_seed_salting(monkeypatch):
captured = {}
class FakeSampling1D:
def __init__(self):
self.config = SimpleNamespace(is_resolved=lambda: True)
class FakeSamplingState1D:
def __init__(self, sampling, *, salt_duplicate_seeds=True, **_kwargs):
captured["salt_duplicate_seeds"] = salt_duplicate_seeds
self.sampling = sampling
def create_state(self):
return object()
monkeypatch.setattr(qwen3_32b_executor, "Sampling1D", FakeSampling1D)
monkeypatch.setattr(qwen3_32b_executor, "SamplingState1D", FakeSamplingState1D)
controller, state = qwen3_32b_executor._create_sampling_state(SimpleNamespace(sampling=FakeSampling1D()), True)
assert captured["salt_duplicate_seeds"] is False
assert controller is not None
assert state is not None
def _device_sampling_executor(binding, monkeypatch, *, runtime_disable: bool):
class FakeSampling1D:
config = SimpleNamespace(
is_resolved=lambda: True,
allow_force_argmax=False,
max_batch_size=32,
max_top_k=32,
)
def decode_forward(self):
raise AssertionError("construction-policy test must not execute sampling")
sampling_policy_module = _sampling_policy_module(binding)
monkeypatch.setattr(sampling_policy_module, "Sampling1D", FakeSampling1D)
model = binding.make_model()
model.sampling = FakeSampling1D()
if binding.executor_module in (llama33_70b_executor, qwen3_32b_executor):
class FakeSamplingState1D:
def __init__(self, sampling, **_kwargs):
self.sampling = sampling
self.seed_manager = SimpleNamespace()
def create_state(self):
return SimpleNamespace(seed_state=SimpleNamespace(capacity=32))
def admit(self, *args, **kwargs):
return None
def decode_forward(self, *args, **kwargs):
return None
def release(self, *args, **kwargs):
return None
monkeypatch.setattr(sampling_policy_module, "SamplingState1D", FakeSamplingState1D)
runtime_config = binding.make_runtime_config()
runtime_config.disable_batched_prefill = runtime_disable
config = replace(
binding.make_executor_config("none"),
device_sampling_enabled=True,
)
return binding.executor_class(model, runtime_config, config)
@pytest.mark.parametrize(
("runtime_disable", "environment_disable", "expected_kinds"),
[
(False, False, ("batched",)),
(True, False, ("single", "single")),
(False, True, ("single", "single")),
],
ids=("device-sampled-batched", "runtime-disabled", "environment-disabled"),
)
def test_device_sampling_prefill_batch_policy_is_model_owned(
binding,
monkeypatch,
runtime_disable,
environment_disable,
expected_kinds,
):
if environment_disable:
monkeypatch.setenv("DISABLE_BATCHED_PREFILL", "1")
else:
monkeypatch.delenv("DISABLE_BATCHED_PREFILL", raising=False)
executor = _device_sampling_executor(
binding,
monkeypatch,
runtime_disable=runtime_disable,
)
prepared = executor.prefill_runtime.prepare(
tokens=torch.ones((2, 128), dtype=torch.long),
page_table=torch.arange(8, dtype=torch.int32).reshape(2, 4),
prompt_lens=torch.full((2,), 128, dtype=torch.long),
empty_slots=[0, 1],
)
if binding.executor_module in (llama33_70b_executor, qwen3_32b_executor):
expected_kinds = ("single", "single")
assert tuple(item.request.kind for item in prepared) == expected_kinds
if expected_kinds == ("batched",):
assert prepared[0].request.source_rows == (0, 1)
assert not prepared[0].request.uses_chunked_prefill
def test_llama32_1b_warms_every_q128_topk_tile_start_once_per_execution_mode():
executor = object.__new__(llama32_executor.Llama32_1BExecutor)
executor._q128_topk_tile_ends_warmed = set()
executor.eager_executor = object()
executor.traced_executor = object()
executor.page_table_layout = SimpleNamespace(block_size=32)
executor.prefill_runtime = SimpleNamespace(config=SimpleNamespace(static_q128_topk_supported=True))
executor.warmup = SimpleNamespace(
config=SimpleNamespace(
prefill_sequence_lengths=(128,),
prime_q128_tile_ends=False,
)
)
executor.compile_prefill = MagicMock()
kv_cache = object()
for enable_trace in (False, False, True, True):
executor._warmup_q128_topk_tile_ends(
kv_cache=kv_cache,
can_sample_on_device=True,
enable_trace=enable_trace,
)
assert executor.compile_prefill.call_count == 6
calls = executor.compile_prefill.call_args_list
assert [call.kwargs["tokens"].shape[1] for call in calls] == [32, 64, 96, 32, 64, 96]
assert [call.kwargs["page_table"].shape[1] for call in calls] == [1, 2, 3, 1, 2, 3]
assert all(call.kwargs["kv_cache"] is kv_cache for call in calls)
assert all(call.kwargs["execution"] is executor.eager_executor for call in calls[:3])
assert all(call.kwargs["execution"] is executor.traced_executor for call in calls[3:])
assert executor._q128_topk_tile_ends_warmed == {False, True}
@pytest.mark.parametrize(
("enable_trace", "expected_order"),
[
(False, ("default", 96, 0, 32, 64)),
(True, (0, 32, 64, "default", 96)),
],
ids=("eager", "traced"),
)
def test_qwen3_lane4_warms_every_runtime_q128_topk_signature_before_activation(enable_trace, expected_order):
executor = SimpleNamespace(
_q128_topk_tile_ends_warmed=set(),
eager_executor=object(),
traced_executor=object(),
page_table_layout=SimpleNamespace(block_size=32),
prefill_runtime=SimpleNamespace(config=SimpleNamespace(static_q128_topk_supported=True)),
warmup=SimpleNamespace(
config=SimpleNamespace(
prefill_sequence_lengths=(128, 1024),
prime_q128_tile_ends=False,
)
),
)
compiled = []
order = []
activation = []
def record_signature(prompt_length):
assert not activation
order.append(((prompt_length - 1) // 32) * 32)
compiled.append(
PrefillProgramSignature(
operation_variant="regular-single",
padded_batch_size=1,
invocation_sequence_length=128,
page_table_width=64,
chunk_page_table_width=None,
sampling_path="topk",
penalties_enabled=False,
logprobs_enabled=False,
last_token_tile_start=((prompt_length - 1) // 32) * 32,
)
)
def compile_prefill(**kwargs):
expected_execution = executor.traced_executor if enable_trace else executor.eager_executor
assert kwargs["execution"] is expected_execution
assert kwargs["kv_cache"] == "cache"
assert kwargs["sampling_params"].top_k.tolist() == [32]
record_signature(int(kwargs["prompt_lens"][0]))
executor.compile_prefill = compile_prefill
default_warmed = False
def default_warmup():
nonlocal default_warmed
if default_warmed:
return
default_warmed = True
order.append("default")
# The coordinator's ordinary Q128 top-k case covers the final tile.
record_signature(128)
for _ in range(2):
qwen3_32b_executor._warmup_q128_around_prefill(
executor,
default_warmup,
kv_cache="cache",
can_sample_on_device=True,
enable_trace=enable_trace,
)
activation.append(True)
assert tuple(order) == expected_order
assert {signature.last_token_tile_start for signature in compiled} == {0, 32, 64, 96}
compiled_keys = {ProgramKey.from_signature(signature) for signature in compiled}
runtime_signatures = {replace(compiled[0], last_token_tile_start=tile_start) for tile_start in (0, 32, 64, 96)}
assert {ProgramKey.from_signature(signature) for signature in runtime_signatures} == compiled_keys
assert executor._q128_topk_tile_ends_warmed == {enable_trace}
def test_qwen3_lane4_executor_installs_model_owned_q128_warmup(monkeypatch):
executor = _device_sampling_executor(EXECUTOR_BINDINGS["qwen3_32b"], monkeypatch, runtime_disable=False)
assert executor._prefill_warmup is qwen3_32b_executor._warmup_q128_around_prefill
assert executor._q128_topk_tile_ends_warmed == set()
@pytest.mark.parametrize("device_sampling_enabled", (False, True), ids=("disabled", "enabled"))
def test_qwen3_generator_sampling_policy_controls_decode_topk_warmup(monkeypatch, device_sampling_enabled):
mesh_device = _Mesh8()
product = _make_qwen3_32b_product(mesh_device, max_batch_size=4)
executor_configs = []
monkeypatch.setattr(qwen3_32b_generator, "from_pretrained", lambda **kwargs: product)
monkeypatch.setattr(
qwen3_32b_generator,
"_model_kv_metadata",
lambda model: ((ttnn.bfloat8_b,), 1, 8, 64),
)
def build_executor(llm, config):
executor_configs.append(config)
return _FakeLane(
llm,
config,
request_state_fields=qwen3_32b_executor.Qwen3_32BExecutor.request_state_fields,
)
monkeypatch.setattr(qwen3_32b_generator, "build_qwen3_32b_executor", build_executor)
generator = qwen3_32b_generator.build_qwen3_32b_generator(
qwen3_32b_generator.Qwen3_32BGeneratorConfig(
hf_model="Qwen/Qwen3-32B",
mesh_device=mesh_device,
max_batch_size=4,
max_seq_len=1024,
trace_mode="decode_only",
device_sampling_enabled=device_sampling_enabled,
)
)
assert len(executor_configs) == 1
assert executor_configs[0].warmup.include_decode_top_k is device_sampling_enabled
if device_sampling_enabled:
observed_missing_signature = DecodeTraceSignature(
batch_size=4,
page_table_width=32,
sampling_path="topk",
device_feedback=True,
)
assert (
ProgramKey.from_signature(observed_missing_signature).digest
== "6f8351f51a0c90eaea5fca6700b3887e380a015dad7ee6f6a9e8be971dfebbd5"
)
generator.cleanup()
@pytest.mark.parametrize(
"method,positional,keyword_only",
[
(
"compile_prefill",
["self"],
[
"tokens",
"page_table",
"prompt_lens",
"start_pos",
"empty_slots",
"kv_cache",
"sampling_params",
"prompt_tokens",
"output_tokens",
"slot_remap",
"execution",
],
),
(
"compile_decode",
["self"],
[
"tokens",
"start_pos",
"page_table",
"kv_cache",
"sampling_params",
"prompt_tokens",
"output_tokens",
"slot_remap",
"reset_batch",
"execution",
],
),
(
"prefill_forward",
["self", "tokens", "page_table"],
[
"prompt_lens",
"start_pos",
"empty_slots",
"kv_cache",
"sampling_params",
"prompt_tokens",
"output_tokens",
"slot_remap",
"execution",
],
),
(
"decode_forward",
["self", "tokens", "start_pos", "page_table"],
[
"kv_cache",
"sampling_params",
"prompt_tokens",
"output_tokens",
"slot_remap",
"reset_batch",
"read_from_device",
"execution",
],
),
("read_decode_output", ["self", "tt_out"], ["async_read"]),
("process_decode_output_host", ["self", "tt_out"], ["is_tokens"]),
("can_trace_prefill", ["self"], ["tokens", "prompt_lens", "start_pos", "empty_slots"]),
("warmup_model_prefill", ["self"], ["kv_cache", "can_sample_on_device", "enable_trace"]),
(
"warmup_model_decode",
["self"],
["kv_cache", "max_batch_size", "num_blocks", "can_sample_on_device", "enable_trace"],
),
],
)
def test_executor_call_contract(binding, method, positional, keyword_only):
if binding.executor_module not in (llama33_70b_executor, qwen3_32b_executor):
keyword_only = [name for name in keyword_only if name not in {"prompt_tokens", "output_tokens", "slot_remap"}]
signature = inspect.signature(getattr(binding.executor_class, method))
parameters = signature.parameters
required = {
"compile_prefill": {"tokens", "page_table"},
"compile_decode": {"tokens", "start_pos", "page_table"},
"prefill_forward": {"tokens", "page_table"},
"decode_forward": {"tokens", "start_pos", "page_table"},
"read_decode_output": {"tt_out"},
"process_decode_output_host": {"tt_out"},
"can_trace_prefill": {"tokens"},
"warmup_model_prefill": {"kv_cache", "can_sample_on_device", "enable_trace"},
"warmup_model_decode": {
"kv_cache",
"max_batch_size",
"num_blocks",
"can_sample_on_device",
"enable_trace",
},
}[method]
non_none_defaults = {"reset_batch": False, "read_from_device": True, "async_read": False, "is_tokens": False}
assert list(parameters) == positional + keyword_only
assert all(parameters[name].kind is inspect.Parameter.POSITIONAL_OR_KEYWORD for name in positional)
assert all(parameters[name].kind is inspect.Parameter.KEYWORD_ONLY for name in keyword_only)
for name, parameter in tuple(parameters.items())[1:]:
expected_default = inspect.Parameter.empty if name in required else non_none_defaults.get(name)
assert parameter.default == expected_default
assert parameter.annotation is not inspect.Parameter.empty
assert signature.return_annotation is not inspect.Signature.empty
@pytest.mark.parametrize(
"executor_class",
[
qwen3_32b_executor.Qwen3_32BExecutor,
],
)
def test_qwen3_delegates_resolved_sampling_warmup_and_activation_to_coordinator(executor_class):
warmup = SimpleNamespace(warmup_prefill=MagicMock(), warmup_decode=MagicMock())
executor = SimpleNamespace(_ensure_active=MagicMock(), warmup=warmup)
executor_class.warmup_model_prefill(
executor,
kv_cache="cache",
can_sample_on_device=True,
enable_trace=True,
)
executor_class.warmup_model_decode(
executor,
kv_cache="cache",
max_batch_size=32,
num_blocks=64,
can_sample_on_device=True,
enable_trace=True,
)
warmup.warmup_prefill.assert_called_once_with(
kv_cache="cache",
can_sample_on_device=True,
enable_trace=True,
)
warmup.warmup_decode.assert_called_once_with(
kv_cache="cache",
max_batch_size=32,
num_blocks=64,
can_sample_on_device=True,
enable_trace=True,
)
assert "capture_all" not in inspect.getsource(executor_class.warmup_model_decode)
class _RecordingTarget:
model_args = object()
mesh_device = object()
cache_path = "cache"
already_warmed_up_prefill = False
eager_execution = object()
traced_prefill_execution = object()
traced_decode_execution = object()
def __init__(self, model, traceable=True, request_state_fields=()):
self.model = model
self.traceable = traceable
self._request_state_fields = tuple(request_state_fields)
self.calls = []
def can_trace_prefill(self, **kwargs):
self.calls.append(("can_trace_prefill", kwargs))
return self.traceable
def prefill_forward(self, **kwargs):
self.calls.append(("prefill_forward", kwargs))
return kwargs["execution"]
def decode_forward(self, **kwargs):
self.calls.append(("decode_forward", kwargs))
return kwargs["execution"]
def cleanup(self):
self.calls.append(("cleanup", {}))
def test_generator_preserves_required_trace_intent_for_ineligible_prefill(binding):
target = binding.make_recording_target(traceable=False)
target.config = binding.make_executor_config("all")
generator = binding.generator_class(target, binding.generator_module._build_vllm_adapter(target))
tokens = __import__("torch").tensor([[1]])
page_table = __import__("torch").tensor([[0]], dtype=__import__("torch").int32)
assert generator.prefill_forward(tokens, page_table, enable_trace=True) is target.traced_prefill_execution
assert [name for name, _ in target.calls] == ["prefill_forward"]
def test_generator_routes_external_decode_only_policy_with_all_trace_targets(binding):
target = binding.make_recording_target()
target.config = binding.make_executor_config("all")
generator = binding.generator_class(target, binding.generator_module._build_vllm_adapter(target))
torch = __import__("torch")
tokens = torch.tensor([[1]])
page_table = torch.tensor([[0]], dtype=torch.int32)
start_pos = torch.tensor([0])
assert generator.prefill_forward(tokens, page_table, enable_trace=False) is target.eager_execution
assert (
generator.decode_forward(tokens[:, 0], start_pos, page_table, enable_trace=True)
is target.traced_decode_execution
)
assert [name for name, _ in target.calls] == ["prefill_forward", "decode_forward"]
def test_executor_validates_borrowed_cache_then_omits_it_from_execution(binding):
execution = create_autospec(EagerExecutor, instance=True)
events = []
execution.compile_prefill.side_effect = lambda **kwargs: events.append("dispatch_compile_prefill")
execution.compile_decode.side_effect = lambda **kwargs: events.append("dispatch_compile_decode")
execution.prefill_forward.side_effect = lambda **kwargs: events.append("dispatch_prefill") or "prefill"
execution.decode_forward.side_effect = lambda **kwargs: events.append("dispatch_decode") or "decode"
executor = object.__new__(binding.executor_class)
executor._prefill_execution = execution
executor._decode_execution = execution
executor._ensure_active = lambda: None
executor._validate_bound_cache = lambda cache: events.append(("validate_cache", cache))
executor._ensure_sampling_for = lambda params: events.append(("validate_sampling", params))
tokens = torch.zeros((1, 4), dtype=torch.long)
start_pos = torch.zeros((1,), dtype=torch.long)
page_table = torch.zeros((1, 1), dtype=torch.int32)
prompt_lens = torch.full((1,), 4, dtype=torch.long)
empty_slots = [0]
kv_cache = object()
sampling_params = object()
executor.compile_prefill(
tokens=tokens,
page_table=page_table,
prompt_lens=prompt_lens,
start_pos=start_pos,
empty_slots=empty_slots,
kv_cache=kv_cache,
sampling_params=sampling_params,
)
executor.compile_decode(
tokens=tokens,
start_pos=start_pos,
page_table=page_table,
kv_cache=kv_cache,
sampling_params=sampling_params,
reset_batch=True,
)
assert (
executor.prefill_forward(
tokens,
page_table,
prompt_lens=prompt_lens,
start_pos=start_pos,
empty_slots=empty_slots,
kv_cache=kv_cache,
sampling_params=sampling_params,
)
== "prefill"
)
assert (
executor.decode_forward(
tokens,
start_pos,
page_table,
kv_cache=kv_cache,
sampling_params=sampling_params,
reset_batch=True,
read_from_device=False,
)
== "decode"
)
expected_validation = [("validate_cache", kv_cache), ("validate_sampling", sampling_params)]
assert events == [
*expected_validation,
"dispatch_compile_prefill",
*expected_validation,
"dispatch_compile_decode",
*expected_validation,
"dispatch_prefill",
*expected_validation,
"dispatch_decode",
]
request_state_names = (
("prompt_tokens", "output_tokens", "slot_remap")
if "prompt_tokens" in inspect.signature(binding.executor_class.compile_prefill).parameters
else ()
)
for target, expected_names in (
(
execution.compile_prefill,
(
"tokens",
"page_table",
"prompt_lens",
"start_pos",
"empty_slots",
"sampling_params",
*request_state_names,
),
),
(
execution.compile_decode,
("tokens", "start_pos", "page_table", "sampling_params", *request_state_names, "reset_batch"),
),
(
execution.prefill_forward,
(
"tokens",
"page_table",
"prompt_lens",
"start_pos",
"empty_slots",
"sampling_params",
*request_state_names,
),
),
(
execution.decode_forward,
(
"tokens",
"start_pos",
"page_table",
"sampling_params",
*request_state_names,
"reset_batch",
"read_from_device",
),
),
):
assert target.call_count == 1
assert tuple(target.call_args.kwargs) == expected_names
assert "kv_cache" not in target.call_args.kwargs
def test_late_capacity_reconfigures_existing_owners_before_allocation(binding, monkeypatch):
executor = binding.executor_class(
binding.make_model(), binding.make_runtime_config(), binding.make_executor_config()
)
owner_ids = tuple(
id(owner)
for owner in (executor.prefill_runtime, executor.decode_runtime, executor.warmup, executor.program_compiler)
)
assert executor.page_table_layout.raw_capacity_width == 128
executor.configure_paged_kv_cache(
PagedKVCacheConfig(
block_size=16,
max_num_blocks=200,
dtype=ttnn.bfloat8_b,
num_blocks=200,
)
)
assert (
tuple(
id(owner)
for owner in (executor.prefill_runtime, executor.decode_runtime, executor.warmup, executor.program_compiler)
)
== owner_ids
)
assert executor.config.paged_kv_cache is executor.kv_cache_manager.config
assert executor.kv_cache_manager.config.block_size == 16
assert executor.kv_cache_manager.config.max_num_blocks == executor.kv_cache_manager.config.num_blocks == 200
assert executor.model.layers[0].attention.config.paged_attention_config.block_size == 16
assert executor.model.layers[0].attention.config.paged_attention_config.max_num_blocks == 200
assert executor.page_table_layout.block_size == 16
assert executor.page_table_layout.raw_capacity_width == 200
assert executor.prefill_runtime.config.page_table_layout is executor.page_table_layout
assert executor.decode_runtime.config.page_table_layout is executor.page_table_layout
assert executor.warmup.config.page_table_layout is executor.page_table_layout
assert executor.prefill_runtime.config.trace_capture_prime_sequence_lengths == (
(128, 1024) if binding.executor_module is qwen3_32b_executor else ()
)
def fake_allocate():
assert executor._runtime_configuration_sealed
assert executor.warmup._configuration_sealed
return ["allocated"]
monkeypatch.setattr(executor.kv_cache_manager, "allocate", fake_allocate)
assert executor.allocate_kv_cache() == ["allocated"]
def test_late_capacity_failure_is_atomic(binding, expect_error):
executor = binding.executor_class(
binding.make_model(), binding.make_runtime_config(), binding.make_executor_config()
)
executor._seal_runtime_configuration()
unresolved = executor.kv_cache_manager.config
original_layout = executor.page_table_layout
original_model_paged = executor.model.layers[0].attention.config.paged_attention_config
with expect_error(RuntimeError, "runtime configuration is sealed"):
executor.configure_paged_kv_cache(
PagedKVCacheConfig(
block_size=32,
max_num_blocks=132,
dtype=ttnn.bfloat8_b,
num_blocks=64,
)
)
assert executor.kv_cache_manager.config is unresolved
assert not unresolved.is_resolved()
assert executor.page_table_layout is original_layout
assert executor.model.layers[0].attention.config.paged_attention_config is original_model_paged
def test_generator_resolves_configures_then_allocates_vllm_kv_shape(binding):
events = []
resolved = object()
cache = object()
shape = (129, 8, 64, 128)
dtype = object()
target = SimpleNamespace(
configure_paged_kv_cache=lambda config: events.append(("configure", config)),
allocate_kv_cache=lambda: events.append(("allocate",)) or cache,
)
adapter = SimpleNamespace(
resolve_legacy_kv_cache_config=lambda *args: events.append(("resolve", args)) or resolved,
)
generator = binding.generator_class(target, adapter)
assert generator.allocate_kv_cache(shape, dtype, 32) is cache
assert events == [
("resolve", (shape, dtype, 32)),
("configure", resolved),
("allocate",),
]
def test_generator_allocates_model_owned_kv_without_reconfiguration(binding):
events = []
cache = object()
target = SimpleNamespace(
configure_paged_kv_cache=lambda config: events.append(("configure", config)),
allocate_kv_cache=lambda: events.append(("allocate",)) or cache,
)
adapter = SimpleNamespace(
resolve_legacy_kv_cache_config=lambda *args: events.append(("resolve", args)),
)
generator = binding.generator_class(target, adapter)
assert generator.allocate_kv_cache() is cache
assert events == [("allocate",)]
@pytest.mark.parametrize(
"arguments",
(
((64, 8, 32, 128), None, None),
(None, object(), None),
(None, None, 32),
((64, 8, 32, 128), object(), None),
),
)
def test_generator_rejects_partial_vllm_kv_shape_atomically(binding, arguments, expect_error):
events = []
target = SimpleNamespace(
configure_paged_kv_cache=lambda config: events.append(("configure", config)),
allocate_kv_cache=lambda: events.append(("allocate",)),
)
adapter = SimpleNamespace(
resolve_legacy_kv_cache_config=lambda *args: events.append(("resolve", args)),
)
generator = binding.generator_class(target, adapter)
with expect_error(TypeError, "must be supplied together"):
generator.allocate_kv_cache(*arguments)
assert events == []
def test_generator_does_not_configure_or_allocate_after_vllm_kv_resolution_failure(binding, expect_error):
events = []
def fail_resolution(*args):
events.append(("resolve", args))
raise ValueError("invalid vLLM KV geometry")
target = SimpleNamespace(
configure_paged_kv_cache=lambda config: events.append(("configure", config)),
allocate_kv_cache=lambda: events.append(("allocate",)),
)
generator = binding.generator_class(
target,
SimpleNamespace(resolve_legacy_kv_cache_config=fail_resolution),
)
with expect_error(ValueError, "invalid vLLM KV geometry"):
generator.allocate_kv_cache((129, 8, 64, 128), object(), 32)
assert tuple(name for name, *_ in events) == ("resolve",)
def test_generator_reports_unmultiplied_per_submesh_token_capacity(binding):
assert (
binding.generator_class.get_max_tokens_all_users(
model_name="ignored",
num_devices=8,
tt_data_parallel=4,
max_model_len=32768,
max_num_seqs=64,
)
== 32768
)
def test_generator_rejects_unavailable_traced_execution(binding, expect_error):
target = binding.make_recording_target()
target.traced_decode_execution = None
target.config = binding.make_executor_config("none")
generator = binding.generator_class(target, binding.generator_module._build_vllm_adapter(target))
with expect_error(RuntimeError, "unavailable traced decode execution"):
generator._select_execution("decode", True)
def test_initialize_vllm_model_threads_policy(binding, monkeypatch):
captured = []
sentinel = object()
mesh_device = object()
monkeypatch.setattr(
binding.generator_module,
binding.build_generator_name,
lambda config: captured.append(config) or sentinel,
)
result = binding.generator_class.initialize_vllm_model(
SimpleNamespace(_name_or_path=binding.hf_model),
mesh_device,
8,
4096,
n_layers=3,
tt_data_parallel=2,
optimizations="accuracy",
trace_mode="decode_only",
device_sampling_enabled=True,
)
assert result is sentinel
config = captured[0]
assert isinstance(config, binding.generator_config_class)
assert config.hf_model == binding.hf_model
assert config.mesh_device is mesh_device
assert config.max_batch_size == 8
assert config.max_seq_len == 4096
assert config.n_layers == 3
assert config.tt_data_parallel == 2
assert config.optimizations == "accuracy"
assert config.trace_mode == "decode_only"
assert config.device_sampling_enabled is True
@pytest.mark.parametrize("model_id,generator_path", GENERATOR_PATHS.items(), ids=GENERATOR_PATHS)
def test_vllm_generator_path_and_construction_defaults(model_id, generator_path):
module_name, class_name = generator_path.split(":", maxsplit=1)
generator_class = getattr(import_module(module_name), class_name)
assert generator_class is EXECUTOR_BINDINGS[model_id].generator_class
assert callable(getattr(generator_class, "initialize_vllm_model", None))
parameters = inspect.signature(generator_class.initialize_vllm_model).parameters
assert parameters["trace_mode"].default == "all"
assert parameters["device_sampling_enabled"].default is True
class _FakeLane:
requires_prefill_trace_warmup = True
def __init__(self, llm, config, request_state_fields=()):
self.model = llm.model
self.model_args = llm.runtime_config
self.mesh_device = llm.model.config.mesh_device
self.cache_path = llm.runtime_config.model_cache_path
self.config = config
self._request_state_fields = tuple(request_state_fields)
self.paged_kv_cache_config = config.paged_kv_cache
self.already_warmed_up_prefill = False
self.eager_execution = object()
self.traced_prefill_execution = object()
self.traced_decode_execution = object()
self.cleanup_calls = 0
def cleanup(self):
self.cleanup_calls += 1
def test_generator_constructs_data_parallel_lane_group(binding, monkeypatch):
executor_calls = []
built_lanes = []
pretrained_calls = []
parent_mesh = object()
submeshes = [_Mesh(), _Mesh()]
create_submeshes = MagicMock(return_value=submeshes)
monkeypatch.setattr(binding.generator_module, "_create_submeshes", create_submeshes)
def fake_from_pretrained(mesh_device, **kwargs):
pretrained_calls.append((mesh_device, kwargs))
return binding.make_product(mesh_device, kwargs["max_batch_size"])
def fake_build_executor(llm, config):
executor_calls.append((llm, config))
lane = binding.make_lane(llm, config)
built_lanes.append(lane)
return lane
monkeypatch.setattr(binding.generator_module, "from_pretrained", fake_from_pretrained)
monkeypatch.setattr(binding.generator_module, binding.build_executor_name, fake_build_executor)
monkeypatch.setattr(
binding.generator_module,
"_model_kv_metadata",
lambda model: ((ttnn.bfloat8_b,), 1, 8, 64),
)
generator = getattr(binding.generator_module, binding.build_generator_name)(
binding.generator_config_class(
hf_model=binding.hf_model,
mesh_device=parent_mesh,
max_batch_size=4,
max_seq_len=4096,
n_layers=1,
tt_data_parallel=2,
trace_mode="all",
device_sampling_enabled=True,
)
)
try:
create_submeshes.assert_called_once_with(parent_mesh, 2)
assert [mesh for mesh, _ in pretrained_calls] == submeshes
assert all(call[1]["max_batch_size"] == 2 for call in pretrained_calls)
assert all(call[1]["max_seq_len"] == 4096 for call in pretrained_calls)
assert all(call[1]["n_layers"] == 1 for call in pretrained_calls)
assert isinstance(generator.target, LaneGroupExecutor)
assert generator.target.mesh_device is parent_mesh
assert generator.target.tt_data_parallel == 2
assert len(executor_calls) == 2
assert executor_calls[0][0] is not executor_calls[1][0]
assert generator.target.lanes == built_lanes
assert [lane.model for lane in generator.target.lanes] == [llm.model for llm, _ in executor_calls]
assert [lane.mesh_device for lane in generator.target.lanes] == submeshes
assert len({id(lane) for lane in generator.target.lanes}) == 2
assert all(isinstance(config, binding.executor_config_class) for _, config in executor_calls)
assert all(llm.model.config.max_batch_size == 2 for llm, _ in executor_calls)
assert generator._adapter.config.trace.mode == "all"
assert generator._adapter.config.expected_num_layers == 1
assert generator._adapter.config.expected_kv_heads_per_device == 8
assert generator._adapter.config.expected_head_dim == 64
finally:
generator.cleanup()
def test_executor_cleanup_is_ordered_retryable_and_idempotent(binding, expect_error):
calls = []
failures = {"reader", "trace"}
class _Owner:
def __init__(self, name):
self.name = name
def cleanup(self, *args):
calls.append(self.name)
if self.name in failures:
raise RuntimeError(self.name)
drain = cleanup
drain_external_outputs = cleanup
cleanup_transients = cleanup
release = cleanup
executor = object.__new__(binding.executor_class)
executor._terminal = False
executor._cleaned_up = False
executor.decode_runtime = _Owner("decode-external")
executor.output_reader = _Owner("reader")
executor.prefill_runtime = _Owner("prefill")
executor.trace_compiler = _Owner("trace")
executor.program_compiler = _Owner("program")
executor.config = SimpleNamespace(device_sampling_enabled=True)
executor.model = SimpleNamespace(sampling=_Owner("sampling"))
if binding.executor_module in (llama33_70b_executor, qwen3_32b_executor):
executor.sampling_state_controller = _Owner("sampling-state")
executor.sampling_state = object()
else:
executor.sampling_state_controller = None
executor.sampling_state = None
executor.kv_cache_manager = _Owner("kv")
with expect_error(RuntimeError, "reader") as raised:
executor.cleanup()
expected_order = [
"decode-external",
"reader",
"prefill",
"decode-external",
"trace",
"program",
]
if binding.executor_module in (llama33_70b_executor, qwen3_32b_executor):
expected_order.append("sampling-state")
expected_order.extend(["sampling", "kv"])
assert calls == expected_order
assert tuple(error.args[0] for error in raised.value.cleanup_failures) == ("trace",)
assert executor.terminal
assert not executor._cleaned_up
failures.clear()
executor.cleanup()
assert calls == expected_order * 2
assert executor._cleaned_up
executor.cleanup()
assert calls == expected_order * 2
def test_llama33_generator_emits_runtime_summary_before_owned_cleanup():
events = []
traced = SimpleNamespace(log_runtime_summary=lambda **kwargs: events.append(("summary", kwargs)))
target = SimpleNamespace(
traced_executor=traced,
cleanup=lambda: events.append("cleanup"),
)
generator = llama33_70b_generator.Llama33_70BGenerator(target, SimpleNamespace())
generator.cleanup()
assert events == [("summary", {"phase": "shutdown"}), "cleanup"]
def test_llama33_generator_emits_serving_ready_and_idempotent_shutdown_summaries():
phases = []
trace_compiler = SimpleNamespace(trace_active=False)
traced = SimpleNamespace(
trace_compiler=trace_compiler,
log_runtime_summary=lambda **kwargs: phases.append(kwargs["phase"]),
)
target = SimpleNamespace(
traced_executor=traced,
warmup_model_prefill=lambda **kwargs: None,
warmup_model_decode=lambda **kwargs: None,
cleanup=lambda: None,
)
generator = llama33_70b_generator.Llama33_70BGenerator(target, SimpleNamespace())
generator.warmup_model_prefill(kv_cache="cache", can_sample_on_device=True, enable_trace=True)
trace_compiler.trace_active = True
generator.warmup_model_decode(
kv_cache="cache",
max_batch_size=16,
num_blocks=128,
can_sample_on_device=True,
enable_trace=True,
)
generator.warmup_model_prefill(kv_cache="cache", can_sample_on_device=True, enable_trace=True)
generator._shutdown_summary_callback()
generator.cleanup()
assert phases == ["serving_ready", "shutdown"]
|