File size: 76,520 Bytes
38fb1f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 | /*
* SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include <algorithm>
#include <array>
#include <chrono>
#include <cuda.h>
#include <cuda_profiler_api.h>
#include <functional>
#include <iterator>
#include <limits>
#include <memory>
#include <mutex>
#include <thread>
#include <utility>
#include <vector>
#if defined(__QNX__)
#include <sys/neutrino.h>
#include <sys/syspage.h>
#endif
#include "NvInferRuntime.h"
#include "bfloat16.h"
#include "common.h"
#include "debugTensorWriter.h"
#include "logger.h"
#include "sampleDevice.h"
#include "sampleEngines.h"
#include "sampleInference.h"
#include "sampleOptions.h"
#include "sampleReporting.h"
#include "sampleUtils.h"
#include <cuda.h>
#if CUDA_VERSION >= 11060
#include <cuda_fp8.h>
#endif
using namespace nvinfer1;
#if ENABLE_UNIFIED_BUILDER
using namespace nvinfer2::safe;
// Provide a weak default definition that can be overridden
__attribute__((weak)) std::shared_ptr<sample::SampleSafeRecorder> gSafeRecorder
= std::make_shared<sample::SampleSafeRecorder>(nvinfer2::safe::Severity::kINFO);
#endif
namespace sample
{
#if !TRT_STATIC
std::string const& getRuntimeLibraryName(RuntimeMode const mode)
{
switch (mode)
{
case RuntimeMode::kFULL: return kNVINFER_LIBNAME;
case RuntimeMode::kDISPATCH: return kNVINFER_DISPATCH_LIBNAME;
case RuntimeMode::kLEAN: return kNVINFER_LEAN_LIBNAME;
case RuntimeMode::kSAFE: return kNVINFER_SAFE_LIBNAME;
}
throw std::runtime_error("Unknown runtime mode");
}
#endif // !TRT_STATIC
#if ENABLE_UNIFIED_BUILDER
namespace safe
{
namespace
{
std::function<nvinfer1::ErrorCode(
nvinfer2::safe::ITRTGraph*&, void const*, int64_t, ISafeRecorder&, bool, ISafeMemAllocator*)>
pcreateTRTGraphInternal{};
std::function<nvinfer1::ErrorCode(nvinfer2::safe::ITRTGraph* graph)> pdestroyTRTGraphInternal{};
std::function<nvinfer2::safe::ISafePluginRegistry*(ISafeRecorder& recorder)> pgetSafePluginRegistryInternal{};
} // namespace
//! Track runtime used for the execution of trtexec.
//! Must be tracked as a global variable due to how library init functions APIs are organized.
RuntimeMode gUseRuntime = RuntimeMode::kSAFE;
//!
//! \brief Initialize the NVIDIA Inference Safe Runtime library
//!
//! This function dynamically loads the Safe TensorRT runtime library and initializes
//! function pointers for safe TensorRT operations. It is used to set up the safe runtime
//! environment for inference with safety-certified TensorRT engines.
//!
//! The function performs the following operations:
//! - Dynamically loads the safe TensorRT runtime library
//! - Retrieves and stores function pointers for:
//! - createTRTGraph: Creates a safe TRT graph from serialized engine data
//! - destroyTRTGraph: Destroys a safe TRT graph and releases resources
//! - getSafePluginRegistry: Gets the safe plugin registry for loading plugins
//!
//! \return true if the safe runtime library was successfully loaded and initialized,
//! false otherwise (e.g., in static builds or if library loading fails)
//!
bool initNvinferSafe()
{
#if !TRT_STATIC
static LibraryPtr libnvinfersafePtr{};
auto fetchPtrs = [](samplesCommon::DynamicLibrary* l) {
if (gUseRuntime == RuntimeMode::kSAFE)
{
pcreateTRTGraphInternal = l->symbolAddress<nvinfer2::safe::ErrorCode(nvinfer2::safe::ITRTGraph*&,
void const*, int64_t, ISafeRecorder&, bool, ISafeMemAllocator*)>("createTRTGraph");
pdestroyTRTGraphInternal
= l->symbolAddress<nvinfer2::safe::ErrorCode(nvinfer2::safe::ITRTGraph * graph)>("destroyTRTGraph");
pgetSafePluginRegistryInternal
= l->symbolAddress<nvinfer2::safe::ISafePluginRegistry*(ISafeRecorder & recorder)>(
"getSafePluginRegistry");
}
};
return initLibrary(libnvinfersafePtr, sample::getRuntimeLibraryName(gUseRuntime), fetchPtrs);
#else
return false;
#endif // !TRT_STATIC
}
//!
//! \brief Create a safe TRT graph from serialized engine data
//!
//! This function creates a safe TRT graph from serialized engine data. It is used to create
//! a safe TRT graph for inference with safety-certified TensorRT engines.
//!
nvinfer1::ErrorCode createSafeTRTGraph(nvinfer2::safe::ITRTGraph*& graph, void const* blob, int64_t size,
ISafeRecorder& recorder, bool useManaged, ISafeMemAllocator* allocator)
{
if (!initNvinferSafe())
{
return nvinfer1::ErrorCode::kINTERNAL_ERROR;
}
ASSERT(pcreateTRTGraphInternal != nullptr);
return pcreateTRTGraphInternal(graph, blob, size, recorder, useManaged, allocator);
}
//!
//! \brief Destroy a safe TRT graph and release resources
//!
//! This function destroys a safe TRT graph and releases the associated resources. It is used to clean up
//! the safe TRT graph after inference with safety-certified TensorRT engines.
//!
nvinfer1::ErrorCode destroySafeTRTGraph(nvinfer2::safe::ITRTGraph*& graph)
{
if (!initNvinferSafe())
{
return nvinfer1::ErrorCode::kINTERNAL_ERROR;
}
ASSERT(pdestroyTRTGraphInternal != nullptr);
return pdestroyTRTGraphInternal(graph);
}
//!
//! \brief Get the safe plugin registry for loading plugins
//!
//! This function retrieves the safe plugin registry for loading plugins. It is used to get the safe plugin registry
//! for loading plugins with safety-certified TensorRT engines.
//!
nvinfer2::safe::ISafePluginRegistry* getSafePluginRegistry(ISafeRecorder& recorder)
{
if (!initNvinferSafe())
{
return nullptr;
}
ASSERT(pgetSafePluginRegistryInternal != nullptr);
return pgetSafePluginRegistryInternal(recorder);
}
namespace
{
nvinfer2::safe::TypedArray createTypedArray(void* const ptr, DataType const type, uint64_t bufferSize)
{
switch (type)
{
case DataType::kFLOAT: return nvinfer2::safe::TypedArray(static_cast<float*>(ptr), bufferSize);
case DataType::kHALF: return nvinfer2::safe::TypedArray(static_cast<nvinfer2::safe::half_t*>(ptr), bufferSize);
case DataType::kINT32: return nvinfer2::safe::TypedArray(static_cast<int32_t*>(ptr), bufferSize);
case DataType::kINT8: return nvinfer2::safe::TypedArray(static_cast<int8_t*>(ptr), bufferSize);
default:
{
sample::gLogError << "Invalid tensor DataType encountered." << std::endl;
return nvinfer2::safe::TypedArray{};
}
}
}
} // namespace
} // namespace safe
#endif
template <class TMapType, class TEngineType>
bool validateTensorNames(TMapType const& map, TEngineType const* engine, int32_t const endBindingIndex)
{
// Check if the provided input tensor names match the input tensors of the engine.
// Throw an error if the provided input tensor names cannot be found because it implies a potential typo.
for (auto const& item : map)
{
bool tensorNameFound{false};
for (int32_t b = 0; b < endBindingIndex; ++b)
{
auto const tensorName = engine->getIOTensorName(b);
auto const tensorIOMode = engine->getTensorIOMode(tensorName);
if (tensorIOMode == nvinfer1::TensorIOMode::kINPUT && matchStringWithOneWildcard(item.first, tensorName))
{
tensorNameFound = true;
break;
}
}
if (!tensorNameFound)
{
sample::gLogError << "Cannot find input tensor with name \"" << item.first << "\" in the engine bindings! "
<< "Please make sure the input tensor names are correct." << std::endl;
return false;
}
}
return true;
}
template <class TEngineType>
class FillBindingClosure
{
private:
using InputsMap = std::unordered_map<std::string, std::string>;
using BindingsVector = std::vector<std::unique_ptr<BindingsStd>>;
TEngineType const* mEngine;
nvinfer1::IExecutionContext const* mContext;
InputsMap const& inputs;
BindingsVector& bindings;
int32_t batch;
int32_t endBindingIndex;
int32_t profileIndex;
void fillOneBinding(TensorInfo const& tensorInfo)
{
auto const name = tensorInfo.name;
auto const* bindingInOutStr = tensorInfo.isInput ? "Input" : "Output";
for (auto& binding : bindings)
{
auto const input = findPlausible(inputs, name);
if (tensorInfo.isInput && input != inputs.end())
{
sample::gLogInfo << "Using values loaded from " << input->second << " for input " << name << std::endl;
binding->addBinding(tensorInfo, input->second);
}
else
{
if (tensorInfo.isInput)
{
sample::gLogInfo << "Using random values for input " << name << std::endl;
}
binding->addBinding(tensorInfo);
}
if (tensorInfo.isDynamic)
{
sample::gLogInfo << bindingInOutStr << " binding for " << name
<< " is dynamic and will be created during execution using OutputAllocator."
<< std::endl;
}
else
{
sample::gLogInfo << bindingInOutStr << " binding for " << name << " with dimensions " << tensorInfo.dims
<< " is created." << std::endl;
}
}
}
bool fillAllBindings(int32_t batch, int32_t endBindingIndex)
{
if (!validateTensorNames(inputs, mEngine, endBindingIndex))
{
sample::gLogError << "Invalid tensor names found in --loadInputs flag." << std::endl;
return false;
}
for (int32_t b = 0; b < endBindingIndex; b++)
{
TensorInfo tensorInfo;
tensorInfo.bindingIndex = b;
getTensorInfo(tensorInfo);
tensorInfo.updateVolume(batch);
fillOneBinding(tensorInfo);
}
return true;
}
void getTensorInfo(TensorInfo& tensorInfo);
public:
FillBindingClosure(TEngineType const* _engine, nvinfer1::IExecutionContext const* _context,
InputsMap const& _inputs, BindingsVector& _bindings, int32_t _batch, int32_t _endBindingIndex,
int32_t _profileIndex)
: mEngine(_engine)
, mContext(_context)
, inputs(_inputs)
, bindings(_bindings)
, batch(_batch)
, endBindingIndex(_endBindingIndex)
, profileIndex(_profileIndex)
{
}
bool operator()()
{
return fillAllBindings(batch, endBindingIndex);
}
};
template <>
void FillBindingClosure<nvinfer1::ICudaEngine>::getTensorInfo(TensorInfo& tensorInfo)
{
auto const b = tensorInfo.bindingIndex;
auto const name = mEngine->getIOTensorName(b);
tensorInfo.name = name;
tensorInfo.dims = mContext->getTensorShape(name);
tensorInfo.isDynamic = std::any_of(
tensorInfo.dims.d, tensorInfo.dims.d + tensorInfo.dims.nbDims, [](int32_t dim) { return dim == -1; });
tensorInfo.comps = mEngine->getTensorComponentsPerElement(name, profileIndex);
tensorInfo.strides = mContext->getTensorStrides(name);
tensorInfo.vectorDimIndex = mEngine->getTensorVectorizedDim(name, profileIndex);
tensorInfo.isInput = mEngine->getTensorIOMode(name) == TensorIOMode::kINPUT;
tensorInfo.dataType = mEngine->getTensorDataType(name);
}
namespace
{
bool allocateContextMemory(InferenceEnvironmentStd& iEnv, InferenceOptions const& inference)
{
auto* engine = iEnv.engine.get();
iEnv.deviceMemory.resize(inference.infStreams);
// Delay context memory allocation until input shapes are specified because runtime allocation would require actual
// input shapes.
for (int32_t i = 0; i < inference.infStreams; ++i)
{
auto const& ec = iEnv.contexts.at(i);
if (inference.memoryAllocationStrategy == MemoryAllocationStrategy::kSTATIC)
{
sample::gLogInfo << "Created execution context with device memory size: "
<< (engine->getDeviceMemorySize() / 1.0_MiB) << " MiB" << std::endl;
}
else
{
size_t sizeToAlloc{0};
const char* allocReason{nullptr};
if (inference.memoryAllocationStrategy == MemoryAllocationStrategy::kPROFILE)
{
auto const p = inference.optProfileIndex;
sizeToAlloc = engine->getDeviceMemorySizeForProfile(p);
allocReason = "current profile";
}
else if (inference.memoryAllocationStrategy == MemoryAllocationStrategy::kRUNTIME)
{
sizeToAlloc = ec->updateDeviceMemorySizeForShapes();
allocReason = "current input shapes";
}
else
{
sample::gLogError << "Unrecognizable memory allocation strategy." << std::endl;
return false;
}
iEnv.deviceMemory.at(i) = TrtDeviceBuffer(sizeToAlloc);
ec->setDeviceMemoryV2(iEnv.deviceMemory.at(i).get(), iEnv.deviceMemory.at(i).getSize());
sample::gLogInfo << "Maximum device memory size across all profiles: "
<< (engine->getDeviceMemorySizeV2() / 1.0_MiB) << " MiB" << std::endl;
sample::gLogInfo << "Only allocated device memory enough for " << allocReason << ": "
<< (sizeToAlloc / 1.0_MiB) << " MiB" << std::endl;
}
}
return true;
}
//! \brief Transform shapeData so that it can be type-punned to array of int32_t.
//!
//! Transform shapeData so if data() is type-punned to (int32_t*), the sequence
//! of values are equal to the original elements of shapeData.
void contractInt64ToInt32(std::vector<int64_t>& shapeData)
{
int64_t const size = shapeData.size();
for (int64_t const& val : shapeData)
{
ASSERT(val <= std::numeric_limits<int32_t>::max() && val >= std::numeric_limits<int32_t>::min()
&& "Value out of range for int32_t conversion");
}
int64_t const* src = shapeData.data();
int32_t* dst = reinterpret_cast<int32_t*>(shapeData.data());
std::copy(src, src + size, dst);
shapeData.resize((size + 1) / 2);
}
} // namespace
bool setUpInference(InferenceEnvironmentBase& iEnv, InferenceOptions const& inference, SystemOptions const& system)
{
#if ENABLE_UNIFIED_BUILDER
if (iEnv.safe)
{
return setUpSafeInference(static_cast<InferenceEnvironmentSafe&>(iEnv), inference, system);
}
#endif
return setUpStdInference(static_cast<InferenceEnvironmentStd&>(iEnv), inference, system);
}
#if ENABLE_UNIFIED_BUILDER
void getSafeTensorInfo(uint32_t profileIndex, nvinfer2::safe::ITRTGraph* safeGraph, TensorInfo& tensorInfo)
{
nvinfer2::safe::TensorDescriptor desc;
auto const b = tensorInfo.bindingIndex;
const char* name = nullptr;
safeGraph->getIOTensorName(name, b);
tensorInfo.name = name;
safeGraph->getIOTensorDescriptor(desc, name);
tensorInfo.dims = desc.shape;
tensorInfo.isDynamic = std::any_of(
tensorInfo.dims.d, tensorInfo.dims.d + tensorInfo.dims.nbDims, [](int32_t dim) { return dim == -1; });
tensorInfo.strides = desc.stride;
tensorInfo.isInput = desc.ioMode == TensorIOMode::kINPUT;
tensorInfo.dataType = desc.dataType;
}
bool setUpSafeInference(InferenceEnvironmentSafe& iEnv, InferenceOptions const& inference, SystemOptions const& system)
{
int32_t device{};
CHECK(cudaGetDevice(&device));
cudaDeviceProp properties;
CHECK(cudaGetDeviceProperties(&properties, device));
int32_t const isIntegrated{properties.integrated};
ASSERT(sample::hasSafeRuntime());
ASSERT(sample::safe::initNvinferSafe());
auto safeEngineBlob = iEnv.engine.getBlob();
SMP_RETVAL_IF_FALSE(safeEngineBlob.data != nullptr, "Engine blob is empty.", false, sample::gLogError);
SMP_RETVAL_IF_FALSE(iEnv.engine.checkDLASafe(),
"Safe DLA engine built with kDLA_STANDALONE should not be infered in TRT!", false, sample::gLogError);
std::unique_ptr<nvinfer2::safe::ITRTGraph> safeGraph;
// Use managed memory on integrated devices when transfers are skipped
// and when it is explicitly requested on the commandline.
bool useManagedMemory{(inference.skipTransfers && isIntegrated) || inference.useManaged};
nvinfer2::safe::ITRTGraph* tempGraph = nullptr;
if (sample::safe::createSafeTRTGraph(
tempGraph, safeEngineBlob.data, safeEngineBlob.size, *gSafeRecorder, true, nullptr)
!= nvinfer2::safe::ErrorCode::kSUCCESS)
{
sample::gLogError << "Create Safe TRT Graph Failed." << std::endl;
}
safeGraph.reset(tempGraph);
// Release serialized blob to save memory space.
iEnv.engine.releaseBlob();
for (int32_t s = 0; s < inference.infStreams; ++s)
{
nvinfer2::safe::ITRTGraph* clonedGraph{nullptr};
safeGraph->clone(clonedGraph, *gSafeRecorder); // return errorcode
iEnv.mClonedGraphs.emplace_back(clonedGraph);
iEnv.bindings.emplace_back(std::make_unique<BindingsSafe>(useManagedMemory));
}
int64_t endBindingIndex = 0;
safeGraph->getNbIOTensors(endBindingIndex);
for (int32_t b = 0; b < endBindingIndex; b++)
{
TensorInfo tensorInfo;
tensorInfo.bindingIndex = b;
getSafeTensorInfo(inference.optProfileIndex, safeGraph.get(), tensorInfo);
tensorInfo.updateVolume(1);
auto const name = tensorInfo.name;
auto const* bindingInOutStr = tensorInfo.isInput ? "Input" : "Output";
for (auto& binding : iEnv.bindings)
{
auto const input = findPlausible(inference.inputs, name);
if (tensorInfo.isInput && input != inference.inputs.end())
{
sample::gLogInfo << "Using values loaded from " << input->second << " for input " << name << std::endl;
binding->addBinding(tensorInfo, input->second);
}
else
{
if (tensorInfo.isInput)
{
sample::gLogInfo << "Using random values for input " << name << std::endl;
}
binding->addBinding(tensorInfo);
}
if (tensorInfo.isDynamic)
{
sample::gLogInfo << bindingInOutStr << " binding for " << name
<< " is dynamic and will be created during execution using OutputAllocator."
<< std::endl;
}
else
{
sample::gLogInfo << bindingInOutStr << " binding for " << name << " with dimensions " << tensorInfo.dims
<< " is created." << std::endl;
}
}
}
return true;
}
#endif
bool setUpStdInference(InferenceEnvironmentStd& iEnv, InferenceOptions const& inference, SystemOptions const& system)
{
int32_t device{};
CHECK(cudaGetDevice(&device));
cudaDeviceProp properties;
CHECK(cudaGetDeviceProperties(&properties, device));
int32_t const isIntegrated{properties.integrated};
// Use managed memory on integrated devices when transfers are skipped
// and when it is explicitly requested on the commandline.
bool useManagedMemory{(inference.skipTransfers && isIntegrated) || inference.useManaged};
using FillStdBindings = FillBindingClosure<nvinfer1::ICudaEngine>;
auto* engine = iEnv.engine.get();
SMP_RETVAL_IF_FALSE(engine != nullptr, "Got invalid engine!", false, sample::gLogError);
// Release serialized blob to save memory space.
iEnv.engine.releaseBlob();
// Setup weight streaming if enabled
if (engine->getStreamableWeightsSize() > 0)
{
auto const& budget = inference.weightStreamingBudget;
int64_t wsBudget = budget.bytes;
if (budget.percent != 100.0)
{
double const percent = budget.percent;
ASSERT(percent < 100.0);
auto const max = engine->getStreamableWeightsSize();
wsBudget = (max >= 0) ? (percent / 100) * (max) : WeightStreamingBudget::kDISABLE;
}
if (wsBudget == WeightStreamingBudget::kDISABLE)
{
wsBudget = engine->getStreamableWeightsSize();
}
else if (wsBudget == WeightStreamingBudget::kAUTOMATIC)
{
wsBudget = engine->getWeightStreamingAutomaticBudget();
}
ASSERT(wsBudget >= 0);
bool success = engine->setWeightStreamingBudgetV2(wsBudget);
SMP_RETVAL_IF_FALSE(success, "Failed to set weight streaming limit!", false, sample::gLogError);
switch (wsBudget)
{
case WeightStreamingBudget::kDISABLE:
{
sample::gLogInfo << "Weight streaming has been disabled at runtime." << std::endl;
break;
}
case WeightStreamingBudget::kAUTOMATIC:
{
sample::gLogInfo << "The weight streaming budget will automatically be chosen by TensorRT." << std::endl;
break;
}
default:
{
sample::gLogInfo << "Weight streaming is enabled with a device memory limit of " << wsBudget << " bytes."
<< std::endl;
break;
}
}
}
int32_t const nbOptProfiles = engine->getNbOptimizationProfiles();
if (inference.optProfileIndex >= nbOptProfiles)
{
sample::gLogError << "Selected profile index " << inference.optProfileIndex
<< " exceeds the number of profiles that the engine holds. " << std::endl;
return false;
}
if (nbOptProfiles > 1 && !inference.setOptProfile)
{
sample::gLogWarning << nbOptProfiles
<< " profiles detected but not set. Running with profile 0. Please use "
"--dumpOptimizationProfile to see all available profiles."
<< std::endl;
}
cudaStream_t setOptProfileStream;
CHECK(cudaStreamCreate(&setOptProfileStream));
for (int32_t s = 0; s < inference.infStreams; ++s)
{
IExecutionContext* ec{nullptr};
//! \return the `ExecutionContextAllocationStrategy` to use for the given allocation strategy, \p s.
auto getExecutionContextAllocationStrategy = [](MemoryAllocationStrategy s) {
return s == MemoryAllocationStrategy::kSTATIC
// Let TRT pre-allocate and manage the memory.
? ExecutionContextAllocationStrategy::kSTATIC
// Allocate based on the current profile or runtime shapes.
: ExecutionContextAllocationStrategy::kUSER_MANAGED;
};
ec = engine->createExecutionContext(getExecutionContextAllocationStrategy(inference.memoryAllocationStrategy));
if (ec == nullptr)
{
sample::gLogError << "Unable to create execution context for stream " << s << "." << std::endl;
return false;
}
ec->setNvtxVerbosity(inference.nvtxVerbosity);
int32_t const persistentCacheLimit
= samplesCommon::getMaxPersistentCacheSize() * inference.persistentCacheRatio;
sample::gLogInfo << "Setting persistentCacheLimit to " << persistentCacheLimit << " bytes." << std::endl;
ec->setPersistentCacheLimit(persistentCacheLimit);
auto setProfile = ec->setOptimizationProfileAsync(inference.optProfileIndex, setOptProfileStream);
CHECK(cudaStreamSynchronize(setOptProfileStream));
if (!setProfile)
{
sample::gLogError << "Set optimization profile failed. " << std::endl;
if (inference.infStreams > 1)
{
sample::gLogError
<< "Please ensure that the engine is built with preview feature profileSharing0806 enabled. "
<< std::endl;
}
return false;
}
iEnv.contexts.emplace_back(ec);
iEnv.bindings.emplace_back(std::make_unique<BindingsStd>(useManagedMemory));
}
CHECK(cudaStreamDestroy(setOptProfileStream));
if (iEnv.profiler)
{
iEnv.contexts.front()->setProfiler(iEnv.profiler.get());
// Always run reportToProfiler() after enqueue launch
iEnv.contexts.front()->setEnqueueEmitsProfile(false);
}
int32_t const endBindingIndex = engine->getNbIOTensors();
// Make sure that the tensor names provided in command-line args actually exist in any of the engine bindings
// to avoid silent typos.
if (!validateTensorNames(inference.shapes, engine, endBindingIndex))
{
sample::gLogError << "Invalid tensor names found in --shapes flag." << std::endl;
return false;
}
for (int32_t b = 0; b < endBindingIndex; ++b)
{
auto const& name = engine->getIOTensorName(b);
auto const& mode = engine->getTensorIOMode(name);
if (mode == TensorIOMode::kINPUT)
{
Dims const dims = iEnv.contexts.front()->getTensorShape(name);
bool isShapeInferenceIO{false};
isShapeInferenceIO = engine->isShapeInferenceIO(name);
bool const hasRuntimeDim = std::any_of(dims.d, dims.d + dims.nbDims, [](int32_t dim) { return dim == -1; });
auto const shape = findPlausible(inference.shapes, name);
if (hasRuntimeDim || isShapeInferenceIO)
{
// Set shapeData to either dimensions of the input (if it has a dynamic shape)
// or set to values of the input (if it is an input shape tensor).
std::vector<int64_t> shapeData;
if (shape == inference.shapes.end())
{
// No information provided. Use default value for missing data.
constexpr int32_t kDEFAULT_VALUE = 1;
if (isShapeInferenceIO)
{
// Set shape tensor to all ones.
shapeData.assign(volume(dims, 0, dims.nbDims), kDEFAULT_VALUE);
sample::gLogWarning << "Values missing for input shape tensor: " << name
<< "Automatically setting values to: " << shapeData << std::endl;
}
else
{
// Use default value for unspecified runtime dimensions.
shapeData.resize(dims.nbDims);
std::transform(dims.d, dims.d + dims.nbDims, shapeData.begin(),
[&](int32_t dimension) { return dimension >= 0 ? dimension : kDEFAULT_VALUE; });
sample::gLogWarning << "Shape missing for input with dynamic shape: " << name
<< "Automatically setting shape to: " << shapeData << std::endl;
}
}
else if (inference.inputs.count(shape->first) && isShapeInferenceIO)
{
// Load shape tensor from file.
int64_t const size = volume(dims, 0, dims.nbDims);
shapeData.resize(size);
auto const& filename = inference.inputs.at(shape->first);
auto dst = reinterpret_cast<char*>(shapeData.data());
loadFromFile(filename, dst, size * sizeof(decltype(shapeData)::value_type));
}
else
{
shapeData = shape->second;
}
int64_t* shapeTensorData{nullptr};
if (isShapeInferenceIO)
{
// Save the data in iEnv, in a way that its address does not change
// before enqueueV3 is called.
DataType const type = engine->getTensorDataType(name);
switch (type)
{
case DataType::kINT64: break;
case DataType::kINT32: contractInt64ToInt32(shapeData); break;
default:
sample::gLogError << "Shape tensor " << name << " has unexpected type " << type << std::endl;
return false;
}
iEnv.inputShapeTensorValues.emplace_back(shapeData);
shapeTensorData = iEnv.inputShapeTensorValues.back().data();
}
for (auto& c : iEnv.contexts)
{
if (isShapeInferenceIO)
{
sample::gLogInfo << "Set input shape tensor " << name << " to: " << shapeData << std::endl;
if (!c->setTensorAddress(name, shapeTensorData))
{
return false;
}
}
else
{
sample::gLogInfo << "Set shape of input tensor " << name << " to: " << shapeData << std::endl;
if (!c->setInputShape(name, toDims(shapeData)))
{
return false;
}
}
}
}
else if (nbOptProfiles && shape != inference.shapes.end())
{
// Check if the provided shape matches the static dimensions in the engine.
for (auto& c : iEnv.contexts)
{
if (!c->setInputShape(name, toDims(shape->second)))
{
sample::gLogError << "The engine was built with static shapes for input tensor " << name
<< " but the provided shapes do not match the static shapes!" << std::endl;
return false;
}
}
}
}
}
// Create Debug Listener and turn on debug states if client requested dumping debug tensors.
if (!inference.debugTensorFileNames.empty() || !inference.dumpAlldebugTensorFormats.empty())
{
iEnv.listener = std::make_unique<DebugTensorWriter>(
inference.debugTensorFileNames, inference.dumpAlldebugTensorFormats, engine->getName(), iEnv.cmdline);
iEnv.contexts.front()->setDebugListener(iEnv.listener.get());
for (auto const& s : inference.debugTensorFileNames)
{
iEnv.contexts.front()->setTensorDebugState(s.first.c_str(), true);
}
if (!inference.dumpAlldebugTensorFormats.empty())
{
iEnv.contexts.front()->setUnfusedTensorsDebugState(true);
}
}
if (!allocateContextMemory(iEnv, inference))
{
return false;
}
auto const* context = iEnv.contexts.front().get();
bool fillBindingsSuccess = FillStdBindings(
engine, context, inference.inputs, iEnv.bindings, 1, endBindingIndex, inference.optProfileIndex)();
return fillBindingsSuccess;
}
TaskInferenceEnvironment::TaskInferenceEnvironment(std::string engineFile, InferenceOptions const& inference,
ReportingOptions const& reporting, int32_t deviceId, int32_t DLACore, int32_t bs)
: iOptions(inference)
, rOptions(reporting)
, device(deviceId)
, batch(bs)
{
BuildEnvironment bEnv(/* isSafe */ false, /* versionCompatible */ false, DLACore, "", getTempfileControlDefaults());
loadEngineToBuildEnv(engineFile, bEnv, sample::gLogError, false);
iEnv = std::make_unique<InferenceEnvironmentStd>(bEnv);
CHECK(cudaSetDevice(device));
SystemOptions system{};
system.device = device;
system.DLACore = DLACore;
if (!setUpStdInference(*iEnv, iOptions, system))
{
sample::gLogError << "Inference set up failed" << std::endl;
}
}
namespace
{
#if defined(__QNX__)
using TimePoint = double;
#else
using TimePoint = std::chrono::time_point<std::chrono::high_resolution_clock>;
#endif
TimePoint getCurrentTime()
{
#if defined(__QNX__)
uint64_t const currentCycles = ClockCycles();
uint64_t const cyclesPerSecond = SYSPAGE_ENTRY(qtime)->cycles_per_sec;
// Return current timestamp in ms.
return static_cast<TimePoint>(currentCycles) * 1000. / cyclesPerSecond;
#else
return std::chrono::high_resolution_clock::now();
#endif
}
//!
//! \struct SyncStruct
//! \brief Threads synchronization structure
//!
struct SyncStruct
{
std::mutex mutex;
TrtCudaStream mainStream;
TrtCudaEvent gpuStart{cudaEventBlockingSync};
TimePoint cpuStart{};
float sleep{};
};
struct Enqueue
{
explicit Enqueue(nvinfer1::IExecutionContext& context)
: mContext(context)
{
}
nvinfer1::IExecutionContext& mContext;
};
#if ENABLE_UNIFIED_BUILDER
struct SafeEnqueue
{
explicit SafeEnqueue(nvinfer2::safe::ITRTGraph& graph)
: mGraph(graph)
{
}
nvinfer2::safe::ITRTGraph& mGraph;
};
#endif
//!
//! \class EnqueueExplicit
//! \brief Functor to enqueue inference with explict batch
//!
class EnqueueExplicit : private Enqueue
{
public:
explicit EnqueueExplicit(nvinfer1::IExecutionContext& context, BindingsStd const& bindings)
: Enqueue(context)
, mBindings(bindings)
{
ASSERT(mBindings.setTensorAddresses(mContext));
}
bool operator()(TrtCudaStream& stream) const
{
try
{
bool const result = mContext.enqueueV3(stream.get());
// Collecting layer timing info from current profile index of execution context, except under capturing
// mode.
if (!isStreamCapturing(stream) && mContext.getProfiler() && !mContext.getEnqueueEmitsProfile()
&& !mContext.reportToProfiler())
{
gLogWarning << "Failed to collect layer timing info from previous enqueueV3()" << std::endl;
}
return result;
}
catch (const std::exception&)
{
return false;
}
return false;
}
private:
// Helper function to check if a stream is in capturing mode.
bool isStreamCapturing(TrtCudaStream& stream) const
{
cudaStreamCaptureStatus status{cudaStreamCaptureStatusNone};
CHECK(cudaStreamIsCapturing(stream.get(), &status));
return status != cudaStreamCaptureStatusNone;
}
BindingsStd const& mBindings;
};
#if ENABLE_UNIFIED_BUILDER
//!
//! \class EnqueueExplicitSafe
//! \brief Functor to safeEnqueue inference with explict batch
//!
class EnqueueExplicitSafe : private SafeEnqueue
{
public:
explicit EnqueueExplicitSafe(nvinfer2::safe::ITRTGraph& graph, BindingsSafe const& bindings)
: SafeEnqueue(graph)
, mBindings(bindings)
{
ASSERT(mBindings.setTensorAddresses(graph));
}
bool operator()(TrtCudaStream& stream) const
{
try
{
bool const result = (mGraph.executeAsync(stream.get()) == nvinfer1::ErrorCode::kSUCCESS);
return result;
}
catch (const std::exception&)
{
return false;
}
return false;
}
private:
BindingsSafe const& mBindings;
};
#endif
//!
//! \class EnqueueGraph
//! \brief Functor to enqueue inference from CUDA Graph
//!
class EnqueueGraph
{
public:
explicit EnqueueGraph(nvinfer1::IExecutionContext& context, TrtCudaGraph& graph)
: mGraph(graph)
, mContext(context)
{
}
bool operator()(TrtCudaStream& stream) const
{
if (mGraph.launch(stream))
{
// Collecting layer timing info from current profile index of execution context
if (mContext.getProfiler() && !mContext.getEnqueueEmitsProfile() && !mContext.reportToProfiler())
{
gLogWarning << "Failed to collect layer timing info from previous CUDA graph launch" << std::endl;
}
return true;
}
return false;
}
TrtCudaGraph& mGraph;
nvinfer1::IExecutionContext& mContext;
};
#if ENABLE_UNIFIED_BUILDER
//!
//! \class EnqueueGraphSafe
//! \brief Functor to enqueue inference from CUDA Graph
//!
class EnqueueGraphSafe
{
public:
explicit EnqueueGraphSafe(nvinfer2::safe::ITRTGraph& graph)
: mGraph(graph)
{
}
bool operator()(TrtCudaStream& stream) const
{
return mGraph.executeAsync(stream.get()) == nvinfer1::ErrorCode::kSUCCESS;
}
nvinfer2::safe::ITRTGraph& mGraph;
};
#endif
using EnqueueFunction = std::function<bool(TrtCudaStream&)>;
enum class StreamType : int32_t
{
kINPUT = 0,
kCOMPUTE = 1,
kOUTPUT = 2,
kNUM = 3
};
enum class EventType : int32_t
{
kINPUT_S = 0,
kINPUT_E = 1,
kCOMPUTE_S = 2,
kCOMPUTE_E = 3,
kOUTPUT_S = 4,
kOUTPUT_E = 5,
kNUM = 6
};
using MultiStream = std::array<TrtCudaStream, static_cast<int32_t>(StreamType::kNUM)>;
using MultiEvent = std::array<std::unique_ptr<TrtCudaEvent>, static_cast<int32_t>(EventType::kNUM)>;
using EnqueueTimes = std::array<TimePoint, 2>;
//!
//! \class IterationBase
//! \brief Inference iteration and streams management
//!
class IterationBase
{
public:
explicit IterationBase(int32_t id, InferenceOptions const& inference, BindingsBase& bindings)
: mBindings(bindings)
, mStreamId(id)
, mDepth(1 + inference.overlap)
, mActive(mDepth)
, mEvents(mDepth)
, mEnqueueTimes(mDepth)
{
for (auto& eventsAtDepth : mEvents)
{
std::generate(eventsAtDepth.begin(), eventsAtDepth.end(),
[&] { return std::make_unique<TrtCudaEvent>(!inference.spin); });
}
}
bool query(bool skipTransfers)
{
if (mActive[mNext])
{
return true;
}
if (!skipTransfers)
{
record(EventType::kINPUT_S, StreamType::kINPUT);
setInputData(false);
record(EventType::kINPUT_E, StreamType::kINPUT);
wait(EventType::kINPUT_E, StreamType::kCOMPUTE); // Wait for input DMA before compute
}
record(EventType::kCOMPUTE_S, StreamType::kCOMPUTE);
recordEnqueueTime();
if (!mEnqueue(getStream(StreamType::kCOMPUTE)))
{
return false;
}
recordEnqueueTime();
record(EventType::kCOMPUTE_E, StreamType::kCOMPUTE);
if (!skipTransfers)
{
wait(EventType::kCOMPUTE_E, StreamType::kOUTPUT); // Wait for compute before output DMA
record(EventType::kOUTPUT_S, StreamType::kOUTPUT);
fetchOutputData(false);
record(EventType::kOUTPUT_E, StreamType::kOUTPUT);
}
mActive[mNext] = true;
moveNext();
return true;
}
float sync(
TimePoint const& cpuStart, TrtCudaEvent const& gpuStart, std::vector<InferenceTrace>& trace, bool skipTransfers)
{
if (mActive[mNext])
{
if (skipTransfers)
{
getEvent(EventType::kCOMPUTE_E).synchronize();
}
else
{
getEvent(EventType::kOUTPUT_E).synchronize();
}
trace.emplace_back(getTrace(cpuStart, gpuStart, skipTransfers));
mActive[mNext] = false;
return getEvent(EventType::kCOMPUTE_S) - gpuStart;
}
return 0;
}
void syncAll(
TimePoint const& cpuStart, TrtCudaEvent const& gpuStart, std::vector<InferenceTrace>& trace, bool skipTransfers)
{
for (int32_t d = 0; d < mDepth; ++d)
{
sync(cpuStart, gpuStart, trace, skipTransfers);
moveNext();
}
}
void wait(TrtCudaEvent& gpuStart)
{
getStream(StreamType::kINPUT).wait(gpuStart);
}
void setInputData(bool sync)
{
mBindings.transferInputToDevice(getStream(StreamType::kINPUT));
// additional sync to avoid overlapping with inference execution.
if (sync)
{
getStream(StreamType::kINPUT).synchronize();
}
}
void fetchOutputData(bool sync)
{
mBindings.transferOutputToHost(getStream(StreamType::kOUTPUT));
// additional sync to avoid overlapping with inference execution.
if (sync)
{
getStream(StreamType::kOUTPUT).synchronize();
}
}
protected:
void moveNext()
{
mNext = mDepth - 1 - mNext;
}
TrtCudaStream& getStream(StreamType t)
{
return mStream[static_cast<int32_t>(t)];
}
TrtCudaEvent& getEvent(EventType t)
{
return *mEvents[mNext][static_cast<int32_t>(t)];
}
void record(EventType e, StreamType s)
{
getEvent(e).record(getStream(s));
}
void recordEnqueueTime()
{
mEnqueueTimes[mNext][enqueueStart] = getCurrentTime();
enqueueStart = 1 - enqueueStart;
}
TimePoint getEnqueueTime(bool start)
{
return mEnqueueTimes[mNext][start ? 0 : 1];
}
void wait(EventType e, StreamType s)
{
getStream(s).wait(getEvent(e));
}
InferenceTrace getTrace(TimePoint const& cpuStart, TrtCudaEvent const& gpuStart, bool skipTransfers)
{
float is
= skipTransfers ? getEvent(EventType::kCOMPUTE_S) - gpuStart : getEvent(EventType::kINPUT_S) - gpuStart;
float ie
= skipTransfers ? getEvent(EventType::kCOMPUTE_S) - gpuStart : getEvent(EventType::kINPUT_E) - gpuStart;
float os
= skipTransfers ? getEvent(EventType::kCOMPUTE_E) - gpuStart : getEvent(EventType::kOUTPUT_S) - gpuStart;
float oe
= skipTransfers ? getEvent(EventType::kCOMPUTE_E) - gpuStart : getEvent(EventType::kOUTPUT_E) - gpuStart;
return InferenceTrace(mStreamId,
std::chrono::duration<float, std::milli>(getEnqueueTime(true) - cpuStart).count(),
std::chrono::duration<float, std::milli>(getEnqueueTime(false) - cpuStart).count(), is, ie,
getEvent(EventType::kCOMPUTE_S) - gpuStart, getEvent(EventType::kCOMPUTE_E) - gpuStart, os, oe);
}
BindingsBase& mBindings;
TrtCudaGraph mGraph;
EnqueueFunction mEnqueue;
int32_t mStreamId{0};
int32_t mNext{0};
int32_t mDepth{2}; // default to double buffer to hide DMA transfers
std::vector<bool> mActive;
MultiStream mStream;
std::vector<MultiEvent> mEvents;
int32_t enqueueStart{0};
std::vector<EnqueueTimes> mEnqueueTimes;
};
//!
//! \class IterationStd
//! \brief Inference iteration and streams management for standard inference
//!
class IterationStd : public IterationBase
{
public:
explicit IterationStd(
int32_t id, InferenceOptions const& inference, nvinfer1::IExecutionContext& context, BindingsStd& bindings)
: IterationBase(id, inference, bindings)
{
createEnqueueFunction(inference, context, bindings);
}
private:
void createEnqueueFunction(
InferenceOptions const& inference, nvinfer1::IExecutionContext& context, BindingsStd& bindings)
{
mEnqueue = EnqueueFunction(EnqueueExplicit(context, bindings));
if (inference.graph)
{
sample::gLogInfo << "Capturing CUDA graph for the current execution context" << std::endl;
TrtCudaStream& stream = getStream(StreamType::kCOMPUTE);
// Avoid capturing initialization calls by executing the enqueue function at least
// once before starting CUDA graph capture.
auto const ret = mEnqueue(stream);
if (!ret)
{
throw std::runtime_error("Inference enqueue failed.");
}
stream.synchronize();
mGraph.beginCapture(stream);
// The built TRT engine may contain operations that are not permitted under CUDA graph capture mode.
// When the stream is capturing, the enqueue call may return false if the current CUDA graph capture fails.
if (mEnqueue(stream))
{
mGraph.endCapture(stream);
mEnqueue = EnqueueFunction(EnqueueGraph(context, mGraph));
sample::gLogInfo << "Successfully captured CUDA graph for the current execution context" << std::endl;
}
else
{
mGraph.endCaptureOnError(stream);
// Ensure any CUDA error has been cleaned up.
CHECK(cudaGetLastError());
sample::gLogWarning << "The built TensorRT engine contains operations that are not permitted under "
"CUDA graph capture mode."
<< std::endl;
sample::gLogWarning << "The specified --useCudaGraph flag has been ignored. The inference will be "
"launched without using CUDA graph launch."
<< std::endl;
}
}
}
};
#if ENABLE_UNIFIED_BUILDER
//!
//! \class IterationSafe
//! \brief Inference iteration and streams management for safe inference
//!
class IterationSafe : public IterationBase
{
public:
explicit IterationSafe(
int32_t id, InferenceOptions const& inference, nvinfer2::safe::ITRTGraph& graph, BindingsSafe& bindings)
: IterationBase(id, inference, bindings)
{
createEnqueueFunction(inference, graph, bindings);
}
private:
void createEnqueueFunction(
InferenceOptions const& inference, nvinfer2::safe::ITRTGraph& graph, BindingsSafe& bindings)
{
mEnqueue = EnqueueFunction(EnqueueExplicitSafe(graph, bindings));
if (inference.graph)
{
sample::gLogInfo << "Capturing CUDA graph for the current execution context" << std::endl;
TrtCudaStream& stream = getStream(StreamType::kCOMPUTE);
// Avoid capturing initialization calls by executing the enqueue function at least
// once before starting CUDA graph capture.
auto const ret = mEnqueue(stream);
if (!ret)
{
throw std::runtime_error("Inference enqueue failed.");
}
stream.synchronize();
mGraph.beginCapture(stream);
// The built TRT engine may contain operations that are not permitted under CUDA graph capture mode.
// When the stream is capturing, the enqueue call may return false if the current CUDA graph capture fails.
if (mEnqueue(stream))
{
mGraph.endCapture(stream);
mEnqueue = EnqueueFunction(EnqueueGraphSafe(graph));
sample::gLogInfo << "Successfully captured CUDA graph for the current execution context" << std::endl;
}
else
{
mGraph.endCaptureOnError(stream);
// Ensure any CUDA error has been cleaned up.
CHECK(cudaGetLastError());
sample::gLogWarning << "The built TensorRT engine contains operations that are not permitted under "
"CUDA graph capture mode."
<< std::endl;
sample::gLogWarning << "The specified --useCudaGraph flag has been ignored. The inference will be "
"launched without using CUDA graph launch."
<< std::endl;
}
}
}
};
#endif
bool inferenceLoop(std::vector<std::unique_ptr<IterationBase>>& iStreams, TimePoint const& cpuStart,
TrtCudaEvent const& gpuStart, int iterations, float maxDurationMs, float warmupMs,
std::vector<InferenceTrace>& trace, bool skipTransfers, float idleMs)
{
float durationMs = 0;
int32_t skip = 0;
if (maxDurationMs == -1.F)
{
sample::gLogWarning << "--duration=-1 is specified, inference will run in an endless loop until"
<< " aborted with CTRL-C (SIGINT)" << std::endl;
while (true)
{
for (auto& s : iStreams)
{
if (!s->query(skipTransfers))
{
return false;
}
}
for (auto& s : iStreams)
{
s->sync(cpuStart, gpuStart, trace, skipTransfers);
}
}
}
for (int32_t i = 0; i < iterations + skip || durationMs < maxDurationMs; ++i)
{
for (auto& s : iStreams)
{
if (!s->query(skipTransfers))
{
return false;
}
}
for (auto& s : iStreams)
{
durationMs = std::max(durationMs, s->sync(cpuStart, gpuStart, trace, skipTransfers));
}
if (durationMs < warmupMs) // Warming up
{
if (durationMs) // Skip complete iterations
{
++skip;
}
continue;
}
if (idleMs != 0.F)
{
std::this_thread::sleep_for(std::chrono::duration<float, std::milli>(idleMs));
}
}
for (auto& s : iStreams)
{
s->syncAll(cpuStart, gpuStart, trace, skipTransfers);
}
return true;
}
void inferenceExecution(InferenceOptions const& inference, InferenceEnvironmentBase& iEnv, SyncStruct& sync,
int32_t const threadIdx, int32_t const streamsPerThread, int32_t device, std::vector<InferenceTrace>& trace,
ReportingOptions const& reporting) noexcept
{
try
{
float warmupMs = inference.warmup;
float durationMs = -1.F;
if (inference.duration != -1.F)
{
durationMs = inference.duration * 1000.F + warmupMs;
}
CHECK(cudaSetDevice(device));
#if ENABLE_UNIFIED_BUILDER
if (iEnv.safe)
{
//! Function to make one iteration:
auto makeIteration = [&](int32_t s) -> std::unique_ptr<IterationSafe> {
int32_t const streamId{threadIdx * streamsPerThread + s};
auto iteration = std::make_unique<IterationSafe>(streamId, inference,
*static_cast<InferenceEnvironmentSafe&>(iEnv).mClonedGraphs[streamId],
*static_cast<InferenceEnvironmentSafe&>(iEnv).bindings[streamId]);
if (inference.skipTransfers)
{
iteration->setInputData(true);
}
return iteration;
};
std::vector<std::unique_ptr<IterationBase>> iStreams;
for (int32_t s = 0; s < streamsPerThread; ++s)
{
iStreams.emplace_back(makeIteration(s));
}
for (auto& s : iStreams)
{
s->wait(sync.gpuStart);
}
std::vector<InferenceTrace> localTrace;
if (!inferenceLoop(iStreams, sync.cpuStart, sync.gpuStart, inference.iterations, durationMs, warmupMs,
localTrace, inference.skipTransfers, inference.idle))
{
std::lock_guard<std::mutex> lock{sync.mutex};
iEnv.error = true;
}
if (inference.skipTransfers)
{
for (auto& s : iStreams)
{
s->fetchOutputData(true);
}
}
std::lock_guard<std::mutex> lock{sync.mutex};
trace.insert(trace.end(), localTrace.begin(), localTrace.end());
return;
}
#endif
//! Function to make one iteration:
auto makeIteration = [&](int32_t s) -> std::unique_ptr<IterationStd> {
int32_t const streamId{threadIdx * streamsPerThread + s};
auto iteration = std::make_unique<IterationStd>(streamId, inference,
*static_cast<InferenceEnvironmentStd&>(iEnv).getContext(streamId),
*static_cast<InferenceEnvironmentStd&>(iEnv).bindings[streamId]);
if (inference.skipTransfers)
{
iteration->setInputData(true);
}
return iteration;
};
std::vector<std::unique_ptr<IterationBase>> iStreams;
for (int32_t s = 0; s < streamsPerThread; ++s)
{
iStreams.emplace_back(makeIteration(s));
}
for (auto& s : iStreams)
{
s->wait(sync.gpuStart);
}
std::vector<InferenceTrace> localTrace;
if (!inferenceLoop(iStreams, sync.cpuStart, sync.gpuStart, inference.iterations, durationMs, warmupMs,
localTrace, inference.skipTransfers, inference.idle))
{
std::lock_guard<std::mutex> lock{sync.mutex};
iEnv.error = true;
}
auto const needOutput = reporting.output || !reporting.exportOutput.empty();
if (inference.skipTransfers && needOutput)
{
for (auto& s : iStreams)
{
s->fetchOutputData(true);
}
}
{
std::lock_guard<std::mutex> lock{sync.mutex};
trace.insert(trace.end(), localTrace.begin(), localTrace.end());
}
}
catch (...)
{
std::lock_guard<std::mutex> lock{sync.mutex};
iEnv.error = true;
}
}
inline std::thread makeThread(InferenceOptions const& inference, InferenceEnvironmentBase& iEnv, SyncStruct& sync,
int32_t threadIdx, int32_t streamsPerThread, int32_t device, std::vector<InferenceTrace>& trace,
ReportingOptions const& reporting)
{
return std::thread(inferenceExecution, std::cref(inference), std::ref(iEnv), std::ref(sync), threadIdx,
streamsPerThread, device, std::ref(trace), std::cref(reporting));
}
} // namespace
bool runInference(InferenceOptions const& inference, InferenceEnvironmentBase& iEnv, int32_t device,
std::vector<InferenceTrace>& trace, ReportingOptions const& reporting)
{
CHECK(cudaProfilerStart());
trace.resize(0);
SyncStruct sync;
sync.sleep = inference.sleep;
sync.mainStream.sleep(&sync.sleep);
sync.cpuStart = getCurrentTime();
sync.gpuStart.record(sync.mainStream);
// When multiple streams are used, trtexec can run inference in two modes:
// (1) if inference.threads is true, then run each stream on each thread.
// (2) if inference.threads is false, then run all streams on the same thread.
int32_t const numThreads = inference.threads ? inference.infStreams : 1;
int32_t const streamsPerThread = inference.threads ? 1 : inference.infStreams;
std::vector<std::thread> threads;
for (int32_t threadIdx = 0; threadIdx < numThreads; ++threadIdx)
{
threads.emplace_back(makeThread(inference, iEnv, sync, threadIdx, streamsPerThread, device, trace, reporting));
}
for (auto& th : threads)
{
th.join();
}
CHECK(cudaProfilerStop());
auto cmpTrace = [](InferenceTrace const& a, InferenceTrace const& b) { return a.h2dStart < b.h2dStart; };
std::sort(trace.begin(), trace.end(), cmpTrace);
return !iEnv.error;
}
bool runMultiTasksInference(std::vector<std::unique_ptr<TaskInferenceEnvironment>>& tEnvList)
{
CHECK(cudaProfilerStart());
cudaSetDeviceFlags(cudaDeviceScheduleSpin);
SyncStruct sync;
sync.sleep = 0;
sync.mainStream.sleep(&sync.sleep);
sync.cpuStart = getCurrentTime();
sync.gpuStart.record(sync.mainStream);
std::vector<std::thread> threads;
for (size_t i = 0; i < tEnvList.size(); ++i)
{
auto& tEnv = tEnvList[i];
threads.emplace_back(makeThread(
tEnv->iOptions, *(tEnv->iEnv), sync, /*threadIdx*/ 0, /*streamsPerThread*/ 1, tEnv->device, tEnv->trace,
tEnv->rOptions));
}
for (auto& th : threads)
{
th.join();
}
CHECK(cudaProfilerStop());
auto cmpTrace = [](InferenceTrace const& a, InferenceTrace const& b) { return a.h2dStart < b.h2dStart; };
for (auto& tEnv : tEnvList)
{
std::sort(tEnv->trace.begin(), tEnv->trace.end(), cmpTrace);
}
return std::none_of(tEnvList.begin(), tEnvList.end(),
[](std::unique_ptr<TaskInferenceEnvironment>& tEnv) { return tEnv->iEnv->error; });
}
namespace
{
size_t reportGpuMemory()
{
static size_t prevFree{0};
size_t free{0};
size_t total{0};
size_t newlyAllocated{0};
CHECK(cudaMemGetInfo(&free, &total));
sample::gLogInfo << "Free GPU memory = " << free / 1024.0_MiB << " GiB";
if (prevFree != 0)
{
newlyAllocated = (prevFree - free);
sample::gLogInfo << ", newly allocated GPU memory = " << newlyAllocated / 1024.0_MiB << " GiB";
}
sample::gLogInfo << ", total GPU memory = " << total / 1024.0_MiB << " GiB" << std::endl;
prevFree = free;
return newlyAllocated;
}
} // namespace
//! Returns true if deserialization is slower than expected or fails.
bool timeDeserialize(InferenceEnvironmentBase& iEnv, SystemOptions const& sys)
{
constexpr int32_t kNB_ITERS{20};
std::unique_ptr<IRuntime> rt{createRuntime()};
std::unique_ptr<ICudaEngine> engine;
SMP_RETVAL_IF_FALSE(!iEnv.safe, "Safe inference is not supported!", false, sample::gLogError);
auto timeDeserializeFn = [&]() -> float {
bool deserializeOK{false};
engine.reset(nullptr);
auto startClock = std::chrono::high_resolution_clock::now();
SMP_RETVAL_IF_FALSE(!iEnv.safe, "Safe inference is not supported!", false, sample::gLogError);
for (auto const& pluginPath : sys.dynamicPlugins)
{
rt->getPluginRegistry().loadLibrary(pluginPath.c_str());
}
auto& reader = iEnv.engine.getFileReader();
auto& asyncReader = iEnv.engine.getAsyncFileReader();
ASSERT(reader.isOpen() || asyncReader.isOpen());
if (asyncReader.isOpen())
{
asyncReader.reset();
engine.reset(rt->deserializeCudaEngine(asyncReader));
}
else
{
reader.reset();
engine.reset(rt->deserializeCudaEngine(reader));
}
deserializeOK = (engine != nullptr);
auto endClock = std::chrono::high_resolution_clock::now();
// return NAN if deserialization failed.
return deserializeOK ? std::chrono::duration<float, std::milli>(endClock - startClock).count() : NAN;
};
// Warmup the caches to make sure that cache thrashing isn't throwing off the results
{
sample::gLogInfo << "Begin deserialization warmup..." << std::endl;
for (int32_t i = 0, e = 2; i < e; ++i)
{
timeDeserializeFn();
}
}
sample::gLogInfo << "Begin deserialization engine timing..." << std::endl;
float const first = timeDeserializeFn();
// Check if first deserialization succeeded.
if (std::isnan(first))
{
sample::gLogError << "Engine deserialization failed." << std::endl;
return true;
}
sample::gLogInfo << "First deserialization time = " << first << " milliseconds" << std::endl;
// Record initial gpu memory state.
reportGpuMemory();
float totalTime{0.F};
for (int32_t i = 0; i < kNB_ITERS; ++i)
{
totalTime += timeDeserializeFn();
}
auto const averageTime = totalTime / kNB_ITERS;
// reportGpuMemory sometimes reports zero after a single deserialization of a small engine,
// so use the size of memory for all the iterations.
auto const totalEngineSizeGpu = reportGpuMemory();
sample::gLogInfo << "Total deserialization time = " << totalTime << " milliseconds in " << kNB_ITERS
<< " iterations, average time = " << averageTime << " milliseconds, first time = " << first
<< " milliseconds." << std::endl;
sample::gLogInfo << "Deserialization Bandwidth = " << 1E-6 * totalEngineSizeGpu / totalTime << " GB/s" << std::endl;
// If the first deserialization is more than tolerance slower than
// the average deserialization, return true, which means an error occurred.
// The tolerance is set to 2x since the deserialization time is quick and susceptible
// to caching issues causing problems in the first timing.
auto const tolerance = 2.0F;
bool const isSlowerThanExpected = first > averageTime * tolerance;
if (isSlowerThanExpected)
{
sample::gLogInfo << "First deserialization time divided by average time is " << (first / averageTime)
<< ". Exceeds tolerance of " << tolerance << "x." << std::endl;
}
return isSlowerThanExpected;
}
std::string getLayerInformation(
nvinfer1::ICudaEngine* engine, nvinfer1::IExecutionContext* context, nvinfer1::LayerInformationFormat format)
{
auto runtime = std::unique_ptr<IRuntime>{createRuntime()};
auto inspector = std::unique_ptr<IEngineInspector>(engine->createEngineInspector());
if (context != nullptr)
{
inspector->setExecutionContext(context);
}
std::string result = inspector->getEngineInformation(format);
return result;
}
void Binding::fill(std::string const& fileName)
{
loadFromFile(fileName, static_cast<char*>(buffer->getHostBuffer()), buffer->getSize());
}
void Binding::fill()
{
switch (dataType)
{
case nvinfer1::DataType::kBOOL:
{
fillBuffer<bool>(buffer->getHostBuffer(), volume, 0, 1);
break;
}
case nvinfer1::DataType::kINT32:
{
fillBuffer<int32_t>(buffer->getHostBuffer(), volume, -128, 127);
break;
}
case nvinfer1::DataType::kINT64:
{
fillBuffer<int64_t>(buffer->getHostBuffer(), volume, -128, 127);
break;
}
case nvinfer1::DataType::kINT8:
{
fillBuffer<int8_t>(buffer->getHostBuffer(), volume, -128, 127);
break;
}
case nvinfer1::DataType::kFLOAT:
{
fillBuffer<float>(buffer->getHostBuffer(), volume, -1.0F, 1.0F);
break;
}
case nvinfer1::DataType::kHALF:
{
fillBuffer<__half>(buffer->getHostBuffer(), volume, -1.0F, 1.0F);
break;
}
case nvinfer1::DataType::kBF16:
{
fillBuffer<BFloat16>(buffer->getHostBuffer(), volume, -1.0F, 1.0F);
break;
}
case nvinfer1::DataType::kUINT8:
{
fillBuffer<uint8_t>(buffer->getHostBuffer(), volume, 0, 255);
break;
}
case nvinfer1::DataType::kFP8:
#if CUDA_VERSION < 11060
ASSERT(false && "FP8 is not supported");
#else
{
fillBuffer<__nv_fp8_e4m3>(buffer->getHostBuffer(), volume, -1.0F, 1.0F);
break;
}
#endif
case nvinfer1::DataType::kINT4:
{
// int4 is implemented as packing two elements into a single byte,
// so all possible bit patterns of the two int4 elements coincides with all possible bit patterns of
// an uint8.
fillBuffer<uint8_t>(buffer->getHostBuffer(), volume, 0, 255);
break;
}
case DataType::kFP4: ASSERT(false && "FP4 is not supported");
case DataType::kE8M0: ASSERT(false && "E8M0 is not supported");
}
}
void Binding::dump(std::ostream& os, Dims dims, Dims strides, int32_t vectorDim, int32_t spv,
std::string const separator /*= " "*/) const
{
void* outputBuffer{};
if (outputAllocator != nullptr)
{
outputBuffer = outputAllocator->getBuffer()->getHostBuffer();
// Overwrite dimensions with those reported by the output allocator.
dims = outputAllocator->getFinalDims();
os << "Final shape is " << dims << " reported by the output allocator." << std::endl;
}
else
{
outputBuffer = buffer->getHostBuffer();
}
switch (dataType)
{
case nvinfer1::DataType::kBOOL:
{
dumpBuffer<bool>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kINT32:
{
dumpBuffer<int32_t>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kINT8:
{
dumpBuffer<int8_t>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kFLOAT:
{
dumpBuffer<float>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kHALF:
{
dumpBuffer<__half>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kBF16:
{
dumpBuffer<BFloat16>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kUINT8:
{
dumpBuffer<uint8_t>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kINT64:
{
dumpBuffer<int64_t>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kFP8:
#if CUDA_VERSION < 11060
ASSERT(false && "FP8 is not supported");
#else
{
dumpBuffer<__nv_fp8_e4m3>(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
#endif
case nvinfer1::DataType::kINT4:
{
dumpInt4Buffer(outputBuffer, separator, os, dims, strides, vectorDim, spv);
break;
}
case nvinfer1::DataType::kFP4: ASSERT(false && "FP4 is not supported");
case nvinfer1::DataType::kE8M0: ASSERT(false && "E8M0 is not supported");
}
}
void BindingsBase::addBinding(TensorInfo const& tensorInfo, std::string const& fileName /*= ""*/)
{
auto const b = tensorInfo.bindingIndex;
while (mBindings.size() <= static_cast<size_t>(b))
{
mBindings.emplace_back();
mDevicePointers.emplace_back();
}
mNames[tensorInfo.name] = b;
mBindings[b].isInput = tensorInfo.isInput;
mBindings[b].volume = tensorInfo.vol;
mBindings[b].dataType = tensorInfo.dataType;
//! Make a UnifiedMirroredBuffer if useManaged or Discrete othereise:
auto makeBuffer = [](bool useManaged) -> std::unique_ptr<IMirroredBuffer> {
if (useManaged)
{
return std::make_unique<UnifiedMirroredBuffer>();
}
else
{
return std::make_unique<DiscreteMirroredBuffer>();
}
};
if (tensorInfo.isDynamic)
{
ASSERT(!tensorInfo.isInput); // Only output shape can be possibly unknown because of DDS.
if (mBindings[b].outputAllocator == nullptr)
{
mBindings[b].outputAllocator = std::make_unique<OutputAllocator>(makeBuffer(mUseManaged));
}
}
else
{
if (mBindings[b].buffer == nullptr)
{
mBindings[b].buffer = makeBuffer(mUseManaged);
}
// Some memory allocators return nullptr when allocating zero bytes, but TensorRT requires a non-null ptr
// even for empty tensors, so allocate a dummy byte.
if (tensorInfo.vol == 0)
{
mBindings[b].buffer->allocate(1);
}
else
{
mBindings[b].buffer->allocate(samplesCommon::getNbBytes(tensorInfo.dataType, tensorInfo.vol));
}
mDevicePointers[b] = mBindings[b].buffer->getDeviceBuffer();
}
if (tensorInfo.isInput)
{
if (fileName.empty())
{
fill(b);
}
else
{
fill(b, fileName);
}
}
}
void** BindingsBase::getDeviceBuffers()
{
return mDevicePointers.data();
}
void BindingsBase::transferInputToDevice(TrtCudaStream& stream)
{
for (auto& b : mNames)
{
if (mBindings[b.second].isInput)
{
mBindings[b.second].buffer->hostToDevice(stream);
}
}
}
void BindingsBase::transferOutputToHost(TrtCudaStream& stream)
{
for (auto& b : mNames)
{
if (!mBindings[b.second].isInput)
{
if (mBindings[b.second].outputAllocator != nullptr)
{
mBindings[b.second].outputAllocator->getBuffer()->deviceToHost(stream);
}
else
{
mBindings[b.second].buffer->deviceToHost(stream);
}
}
}
}
void BindingsStd::dumpBindingValues(nvinfer1::IExecutionContext const& context, int32_t binding, std::ostream& os,
std::string const& separator /*= " "*/, int32_t batch /*= 1*/) const
{
auto const tensorName = context.getEngine().getIOTensorName(binding);
Dims dims = context.getTensorShape(tensorName);
Dims strides = context.getTensorStrides(tensorName);
int32_t vectorDim = context.getEngine().getTensorVectorizedDim(tensorName);
int32_t const spv = context.getEngine().getTensorComponentsPerElement(tensorName);
mBindings[binding].dump(os, dims, strides, vectorDim, spv, separator);
}
namespace
{
Dims getBindingDimensions(nvinfer1::IExecutionContext const& context, std::string const& name)
{
return context.getTensorShape(name.c_str());
}
} // namespace
void BindingsStd::dumpRawBindingToFiles(nvinfer1::IExecutionContext const& context, std::ostream& os) const
{
os << "Dumping I/O Bindings to RAW Files:" << std::endl;
for (auto const& n : mNames)
{
auto name = n.first;
auto bIndex = n.second;
auto const& binding = mBindings[bIndex];
void* outputBuffer{};
if (binding.outputAllocator != nullptr)
{
outputBuffer = binding.outputAllocator->getBuffer()->getHostBuffer();
}
else
{
outputBuffer = binding.buffer->getHostBuffer();
}
Dims dims = getBindingDimensions(context, name);
std::string dimsStr;
std::string dotStr;
for (int32_t i = 0; i < dims.nbDims; i++)
{
dimsStr += dotStr + std::to_string(dims.d[i]);
dotStr = ".";
}
std::string const bindingTypeStr = (binding.isInput ? "input" : "output");
std::stringstream fileNameStream;
fileNameStream << name << "." << bindingTypeStr << "." << dimsStr << "." << binding.dataType << ".raw";
std::string fileName = genFilenameSafeString(fileNameStream.str());
os << "Writing file for " << bindingTypeStr << " binding " << name << " (with datatype " << binding.dataType
<< " and dimensions " << dimsStr << ") to " << fileName << std::endl;
std::ofstream f(fileName, std::ios::out | std::ios::binary);
ASSERT(f && "Cannot open file for write");
f.write(static_cast<char*>(outputBuffer), samplesCommon::getNbBytes(binding.dataType, binding.volume));
f.close();
}
}
void BindingsStd::dumpBindingDimensions(
std::string const& name, nvinfer1::IExecutionContext const& context, std::ostream& os) const
{
auto const dims = context.getTensorShape(name.c_str());
// Do not add a newline terminator, because the caller may be outputting a JSON string.
os << dims;
}
std::unordered_map<std::string, int> BindingsBase::getBindings(std::function<bool(Binding const&)> predicate) const
{
std::unordered_map<std::string, int> bindings;
for (auto const& n : mNames)
{
auto const binding = n.second;
if (predicate(mBindings[binding]))
{
bindings.insert(n);
}
}
return bindings;
}
bool BindingsStd::setTensorAddresses(nvinfer1::IExecutionContext& context) const
{
for (auto const& b : mNames)
{
auto const name = b.first.c_str();
auto const location = context.getEngine().getTensorLocation(name);
if (location == TensorLocation::kDEVICE)
{
if (mBindings[b.second].outputAllocator != nullptr)
{
if (!context.setOutputAllocator(name, mBindings[b.second].outputAllocator.get()))
{
return false;
}
}
else
{
if (!context.setTensorAddress(name, mDevicePointers[b.second]))
{
return false;
}
}
}
}
return true;
}
#if ENABLE_UNIFIED_BUILDER
namespace
{
Dims getBindingDimensions(ITRTGraph& graph, std::string const& name)
{
nvinfer2::safe::TensorDescriptor desc;
graph.getIOTensorDescriptor(desc, name.c_str());
return desc.shape;
}
} // namespace
void BindingsSafe::dumpBindingDimensions(std::string const& name, ITRTGraph const& graph, std::ostream& os) const
{
// Do not add a newline terminator, because the caller may be outputting a JSON string.
os << getBindingDimensions(const_cast<ITRTGraph&>(graph), name);
}
void BindingsSafe::dumpBindingValues(ITRTGraph const& graph, int32_t binding, std::ostream& os,
std::string const& separator /*= " "*/, int32_t batch /*= 1*/) const
{
char const* tensorName;
graph.getIOTensorName(tensorName, binding);
nvinfer2::safe::TensorDescriptor desc;
graph.getIOTensorDescriptor(desc, tensorName);
Dims dims = desc.shape;
Dims strides = desc.stride;
// int32_t vectorDim = desc.vectorizedDim;
// int32_t const spv = desc.componentsPerVector;
mBindings[binding].dump(os, dims, strides, -1, -1, separator);
}
void BindingsSafe::dumpRawBindingToFiles(ITRTGraph& graph, std::ostream& os) const
{
os << "Dumping I/O Bindings to RAW Files:" << std::endl;
for (auto const& n : mNames)
{
auto name = n.first;
auto bIndex = n.second;
auto const& binding = mBindings[bIndex];
void* outputBuffer{};
if (binding.outputAllocator != nullptr)
{
outputBuffer = binding.outputAllocator->getBuffer()->getHostBuffer();
}
else
{
outputBuffer = binding.buffer->getHostBuffer();
}
Dims dims = getBindingDimensions(graph, name);
std::string dimsStr;
std::string dotStr;
for (int32_t i = 0; i < dims.nbDims; i++)
{
dimsStr += dotStr + std::to_string(dims.d[i]);
dotStr = ".";
}
std::string const bindingTypeStr = (binding.isInput ? "input" : "output");
std::stringstream fileName;
fileName << genFilenameSafeString(name) << "." << bindingTypeStr << "." << dimsStr << "." << binding.dataType
<< ".raw";
os << "Writing file for " << bindingTypeStr << " binding " << name << " (with datatype " << binding.dataType
<< " and dimensions " << dimsStr << ") to " << fileName.str() << std::endl;
std::ofstream f(fileName.str(), std::ios::out | std::ios::binary);
ASSERT(f && "Cannot open file for write");
f.write(static_cast<char*>(outputBuffer), samplesCommon::getNbBytes(binding.dataType, binding.volume));
f.close();
}
}
bool BindingsSafe::setTensorAddresses(ITRTGraph& graph) const
{
for (auto const& b : mNames)
{
auto const name = b.first.c_str();
nvinfer2::safe::TensorDescriptor desc;
graph.getIOTensorDescriptor(desc, name);
bool onGpu = desc.memPlacement == nvinfer2::safe::MemoryPlacement::kGPU
|| desc.memPlacement == nvinfer2::safe::MemoryPlacement::kNONE;
if (onGpu)
{
if (mBindings[b.second].outputAllocator != nullptr)
{
nvinfer2::safe::TypedArray tensor = safe::createTypedArray(
mBindings[b.second].outputAllocator->getBuffer(), desc.dataType, desc.sizeInBytes);
graph.setIOTensorAddress(name, tensor);
}
else
{
nvinfer2::safe::TypedArray tensor
= safe::createTypedArray(mDevicePointers[b.second], desc.dataType, desc.sizeInBytes);
graph.setIOTensorAddress(name, tensor);
}
}
}
return true;
}
#endif
} // namespace sample
|