File size: 75,043 Bytes
be903e2 | 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 | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "allocator.h"
#include "gpu.h"
#include "pipeline.h"
#if __ANDROID_API__ >= 26
#include <android/hardware_buffer.h>
#endif // __ANDROID_API__ >= 26
namespace ncnn {
Allocator::~Allocator()
{
}
class PoolAllocatorPrivate
{
public:
Mutex budgets_lock;
Mutex payouts_lock;
unsigned int size_compare_ratio; // 0~256
size_t size_drop_threshold;
std::list<std::pair<size_t, void*> > budgets;
std::list<std::pair<size_t, void*> > payouts;
};
PoolAllocator::PoolAllocator()
: Allocator(), d(new PoolAllocatorPrivate)
{
d->size_compare_ratio = 0;
d->size_drop_threshold = 10;
}
PoolAllocator::~PoolAllocator()
{
clear();
if (!d->payouts.empty())
{
NCNN_LOGE("FATAL ERROR! pool allocator destroyed too early");
#if NCNN_STDIO
std::list<std::pair<size_t, void*> >::iterator it = d->payouts.begin();
for (; it != d->payouts.end(); ++it)
{
void* ptr = it->second;
NCNN_LOGE("%p still in use", ptr);
}
#endif
}
delete d;
}
PoolAllocator::PoolAllocator(const PoolAllocator&)
: d(0)
{
}
PoolAllocator& PoolAllocator::operator=(const PoolAllocator&)
{
return *this;
}
void PoolAllocator::clear()
{
d->budgets_lock.lock();
std::list<std::pair<size_t, void*> >::iterator it = d->budgets.begin();
for (; it != d->budgets.end(); ++it)
{
void* ptr = it->second;
ncnn::fastFree(ptr);
}
d->budgets.clear();
d->budgets_lock.unlock();
}
void PoolAllocator::set_size_compare_ratio(float scr)
{
if (scr < 0.f || scr > 1.f)
{
NCNN_LOGE("invalid size compare ratio %f", scr);
return;
}
d->size_compare_ratio = (unsigned int)(scr * 256);
}
void PoolAllocator::set_size_drop_threshold(size_t threshold)
{
d->size_drop_threshold = threshold;
}
void* PoolAllocator::fastMalloc(size_t size)
{
d->budgets_lock.lock();
// find free budget
std::list<std::pair<size_t, void*> >::iterator it = d->budgets.begin(), it_max = d->budgets.begin(), it_min = d->budgets.begin();
for (; it != d->budgets.end(); ++it)
{
size_t bs = it->first;
// size_compare_ratio ~ 100%
if (bs >= size && ((bs * d->size_compare_ratio) >> 8) <= size)
{
void* ptr = it->second;
d->budgets.erase(it);
d->budgets_lock.unlock();
d->payouts_lock.lock();
d->payouts.push_back(std::make_pair(bs, ptr));
d->payouts_lock.unlock();
return ptr;
}
if (bs < it_min->first)
{
it_min = it;
}
if (bs > it_max->first)
{
it_max = it;
}
}
if (d->budgets.size() >= d->size_drop_threshold)
{
// All chunks in pool are not chosen. Then try to drop some outdated
// chunks and return them to OS.
if (it_max->first < size)
{
// Current query is asking for a chunk larger than any cached chunks.
// Then remove the smallest one.
ncnn::fastFree(it_min->second);
d->budgets.erase(it_min);
}
else if (it_min->first > size)
{
// Current query is asking for a chunk smaller than any cached chunks.
// Then remove the largest one.
ncnn::fastFree(it_max->second);
d->budgets.erase(it_max);
}
}
d->budgets_lock.unlock();
// new
void* ptr = ncnn::fastMalloc(size);
d->payouts_lock.lock();
d->payouts.push_back(std::make_pair(size, ptr));
d->payouts_lock.unlock();
return ptr;
}
void PoolAllocator::fastFree(void* ptr)
{
d->payouts_lock.lock();
// return to budgets
std::list<std::pair<size_t, void*> >::iterator it = d->payouts.begin();
for (; it != d->payouts.end(); ++it)
{
if (it->second == ptr)
{
size_t size = it->first;
d->payouts.erase(it);
d->payouts_lock.unlock();
d->budgets_lock.lock();
d->budgets.push_back(std::make_pair(size, ptr));
d->budgets_lock.unlock();
return;
}
}
d->payouts_lock.unlock();
NCNN_LOGE("FATAL ERROR! pool allocator get wild %p", ptr);
ncnn::fastFree(ptr);
}
class UnlockedPoolAllocatorPrivate
{
public:
unsigned int size_compare_ratio; // 0~256
size_t size_drop_threshold;
std::list<std::pair<size_t, void*> > budgets;
std::list<std::pair<size_t, void*> > payouts;
};
UnlockedPoolAllocator::UnlockedPoolAllocator()
: Allocator(), d(new UnlockedPoolAllocatorPrivate)
{
d->size_compare_ratio = 0;
d->size_drop_threshold = 10;
}
UnlockedPoolAllocator::~UnlockedPoolAllocator()
{
clear();
if (!d->payouts.empty())
{
NCNN_LOGE("FATAL ERROR! unlocked pool allocator destroyed too early");
#if NCNN_STDIO
std::list<std::pair<size_t, void*> >::iterator it = d->payouts.begin();
for (; it != d->payouts.end(); ++it)
{
void* ptr = it->second;
NCNN_LOGE("%p still in use", ptr);
}
#endif
}
delete d;
}
UnlockedPoolAllocator::UnlockedPoolAllocator(const UnlockedPoolAllocator&)
: d(0)
{
}
UnlockedPoolAllocator& UnlockedPoolAllocator::operator=(const UnlockedPoolAllocator&)
{
return *this;
}
void UnlockedPoolAllocator::clear()
{
std::list<std::pair<size_t, void*> >::iterator it = d->budgets.begin();
for (; it != d->budgets.end(); ++it)
{
void* ptr = it->second;
ncnn::fastFree(ptr);
}
d->budgets.clear();
}
void UnlockedPoolAllocator::set_size_compare_ratio(float scr)
{
if (scr < 0.f || scr > 1.f)
{
NCNN_LOGE("invalid size compare ratio %f", scr);
return;
}
d->size_compare_ratio = (unsigned int)(scr * 256);
}
void UnlockedPoolAllocator::set_size_drop_threshold(size_t threshold)
{
d->size_drop_threshold = threshold;
}
void* UnlockedPoolAllocator::fastMalloc(size_t size)
{
// find free budget
std::list<std::pair<size_t, void*> >::iterator it = d->budgets.begin(), it_max = d->budgets.begin(), it_min = d->budgets.begin();
for (; it != d->budgets.end(); ++it)
{
size_t bs = it->first;
// size_compare_ratio ~ 100%
if (bs >= size && ((bs * d->size_compare_ratio) >> 8) <= size)
{
void* ptr = it->second;
d->budgets.erase(it);
d->payouts.push_back(std::make_pair(bs, ptr));
return ptr;
}
if (bs > it_max->first)
{
it_max = it;
}
if (bs < it_min->first)
{
it_min = it;
}
}
if (d->budgets.size() >= d->size_drop_threshold)
{
if (it_max->first < size)
{
ncnn::fastFree(it_min->second);
d->budgets.erase(it_min);
}
else if (it_min->first > size)
{
ncnn::fastFree(it_max->second);
d->budgets.erase(it_max);
}
}
// new
void* ptr = ncnn::fastMalloc(size);
d->payouts.push_back(std::make_pair(size, ptr));
return ptr;
}
void UnlockedPoolAllocator::fastFree(void* ptr)
{
// return to budgets
std::list<std::pair<size_t, void*> >::iterator it = d->payouts.begin();
for (; it != d->payouts.end(); ++it)
{
if (it->second == ptr)
{
size_t size = it->first;
d->payouts.erase(it);
d->budgets.push_back(std::make_pair(size, ptr));
return;
}
}
NCNN_LOGE("FATAL ERROR! unlocked pool allocator get wild %p", ptr);
ncnn::fastFree(ptr);
}
#if NCNN_VULKAN
VkAllocator::VkAllocator(const VulkanDevice* _vkdev)
: vkdev(_vkdev)
{
buffer_memory_type_index = (uint32_t)-1;
image_memory_type_index = (uint32_t)-1;
reserved_type_index = (uint32_t)-1;
mappable = false;
coherent = false;
}
VkAllocator::~VkAllocator()
{
clear();
}
void VkAllocator::clear()
{
}
static inline size_t round_up(size_t n, size_t multiple)
{
return (n + multiple - 1) / multiple * multiple;
}
static inline size_t round_down(size_t n, size_t multiple)
{
return n / multiple * multiple;
}
int VkAllocator::flush(VkBufferMemory* ptr)
{
if (coherent)
return 0;
VkMappedMemoryRange mappedMemoryRange;
mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
mappedMemoryRange.pNext = 0;
mappedMemoryRange.memory = ptr->memory;
mappedMemoryRange.offset = round_down(ptr->offset, vkdev->info.non_coherent_atom_size());
mappedMemoryRange.size = round_up(ptr->offset + ptr->capacity, vkdev->info.non_coherent_atom_size()) - mappedMemoryRange.offset;
VkResult ret = vkFlushMappedMemoryRanges(vkdev->vkdevice(), 1, &mappedMemoryRange);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkFlushMappedMemoryRanges failed %d", ret);
return -1;
}
return 0;
}
int VkAllocator::invalidate(VkBufferMemory* ptr)
{
if (coherent)
return 0;
VkMappedMemoryRange mappedMemoryRange;
mappedMemoryRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
mappedMemoryRange.pNext = 0;
mappedMemoryRange.memory = ptr->memory;
mappedMemoryRange.offset = round_down(ptr->offset, vkdev->info.non_coherent_atom_size());
mappedMemoryRange.size = round_up(ptr->offset + ptr->capacity, vkdev->info.non_coherent_atom_size()) - mappedMemoryRange.offset;
VkResult ret = vkInvalidateMappedMemoryRanges(vkdev->vkdevice(), 1, &mappedMemoryRange);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkInvalidateMappedMemoryRanges failed %d", ret);
return -1;
}
return 0;
}
VkBuffer VkAllocator::create_buffer(size_t size, VkBufferUsageFlags usage)
{
VkBufferCreateInfo bufferCreateInfo;
bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferCreateInfo.pNext = 0;
bufferCreateInfo.flags = 0;
bufferCreateInfo.size = size;
bufferCreateInfo.usage = usage;
bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
bufferCreateInfo.queueFamilyIndexCount = 0;
bufferCreateInfo.pQueueFamilyIndices = 0;
VkBuffer buffer = 0;
VkResult ret = vkCreateBuffer(vkdev->vkdevice(), &bufferCreateInfo, 0, &buffer);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkCreateBuffer failed %d", ret);
return 0;
}
return buffer;
}
VkDeviceMemory VkAllocator::allocate_memory(size_t size, uint32_t memory_type_index)
{
VkMemoryAllocateInfo memoryAllocateInfo;
memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memoryAllocateInfo.pNext = 0;
memoryAllocateInfo.allocationSize = size;
memoryAllocateInfo.memoryTypeIndex = memory_type_index;
VkDeviceMemory memory = 0;
VkResult ret = vkAllocateMemory(vkdev->vkdevice(), &memoryAllocateInfo, 0, &memory);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkAllocateMemory failed %d", ret);
return 0;
}
return memory;
}
VkDeviceMemory VkAllocator::allocate_dedicated_memory(size_t size, uint32_t memory_type_index, VkImage image, VkBuffer buffer)
{
VkMemoryAllocateInfo memoryAllocateInfo;
memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memoryAllocateInfo.pNext = 0;
memoryAllocateInfo.allocationSize = size;
memoryAllocateInfo.memoryTypeIndex = memory_type_index;
VkMemoryDedicatedAllocateInfoKHR memoryDedicatedAllocateInfo;
memoryDedicatedAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR;
memoryDedicatedAllocateInfo.pNext = 0;
memoryDedicatedAllocateInfo.image = image;
memoryDedicatedAllocateInfo.buffer = buffer;
memoryAllocateInfo.pNext = &memoryDedicatedAllocateInfo;
VkDeviceMemory memory = 0;
VkResult ret = vkAllocateMemory(vkdev->vkdevice(), &memoryAllocateInfo, 0, &memory);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkAllocateMemory failed %d", ret);
return 0;
}
return memory;
}
VkImage VkAllocator::create_image(int width, int height, int depth, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage)
{
VkImageCreateInfo imageCreateInfo;
imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
imageCreateInfo.pNext = 0;
imageCreateInfo.flags = 0;
imageCreateInfo.imageType = VK_IMAGE_TYPE_3D;
imageCreateInfo.format = format;
imageCreateInfo.extent.width = width;
imageCreateInfo.extent.height = height;
imageCreateInfo.extent.depth = depth;
imageCreateInfo.mipLevels = 1;
imageCreateInfo.arrayLayers = 1;
imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageCreateInfo.tiling = tiling;
imageCreateInfo.usage = usage;
imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageCreateInfo.queueFamilyIndexCount = 0;
imageCreateInfo.pQueueFamilyIndices = 0;
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VkImage image;
VkResult ret = vkCreateImage(vkdev->vkdevice(), &imageCreateInfo, 0, &image);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkCreateImage failed %d %d %d %d %d %d %d", ret, width, height, depth, format, tiling, usage);
return 0;
}
return image;
}
VkImageView VkAllocator::create_imageview(VkImage image, VkFormat format)
{
VkImageViewCreateInfo imageViewCreateInfo;
imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewCreateInfo.pNext = 0;
imageViewCreateInfo.flags = 0;
imageViewCreateInfo.image = image;
imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_3D;
imageViewCreateInfo.format = format;
imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
imageViewCreateInfo.subresourceRange.levelCount = 1;
imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
imageViewCreateInfo.subresourceRange.layerCount = 1;
VkImageView imageview;
VkResult ret = vkCreateImageView(vkdev->vkdevice(), &imageViewCreateInfo, 0, &imageview);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkCreateImageView failed %d", ret);
return 0;
}
return imageview;
}
static inline size_t least_common_multiple(size_t a, size_t b)
{
if (a == b)
return a;
if (a > b)
return least_common_multiple(b, a);
size_t lcm = b;
while (lcm % a != 0)
{
lcm += b;
}
return lcm;
}
class VkBlobAllocatorPrivate
{
public:
size_t block_size;
size_t buffer_offset_alignment;
size_t bind_memory_offset_alignment;
std::vector<std::list<std::pair<size_t, size_t> > > buffer_budgets;
std::vector<VkBufferMemory*> buffer_blocks;
std::vector<std::list<std::pair<size_t, size_t> > > image_memory_budgets;
std::vector<VkDeviceMemory> image_memory_blocks;
};
VkBlobAllocator::VkBlobAllocator(const VulkanDevice* _vkdev, size_t preferred_block_size)
: VkAllocator(_vkdev), d(new VkBlobAllocatorPrivate)
{
d->buffer_offset_alignment = vkdev->info.buffer_offset_alignment();
d->bind_memory_offset_alignment = vkdev->info.buffer_image_granularity();
if (vkdev->info.type() == 1)
{
// on integrated gpu, there may be device local only memory too, eg. AMD APU
// assuming larger alignment always keeps us safe :)
// least common multiple for memory_map_alignment and buffer_offset_alignment and non_coherent_atom_size
d->buffer_offset_alignment = least_common_multiple(d->buffer_offset_alignment, vkdev->info.memory_map_alignment());
d->buffer_offset_alignment = least_common_multiple(d->buffer_offset_alignment, vkdev->info.non_coherent_atom_size());
}
d->block_size = alignSize(preferred_block_size, d->buffer_offset_alignment);
}
VkBlobAllocator::~VkBlobAllocator()
{
clear();
delete d;
}
VkBlobAllocator::VkBlobAllocator(const VkBlobAllocator&)
: VkAllocator(0), d(0)
{
}
VkBlobAllocator& VkBlobAllocator::operator=(const VkBlobAllocator&)
{
return *this;
}
void VkBlobAllocator::clear()
{
// NCNN_LOGE("VkBlobAllocator %lu", buffer_blocks.size());
for (size_t i = 0; i < d->buffer_blocks.size(); i++)
{
VkBufferMemory* ptr = d->buffer_blocks[i];
// std::list< std::pair<size_t, size_t> >::iterator it = buffer_budgets[i].begin();
// while (it != buffer_budgets[i].end())
// {
// NCNN_LOGE("VkBlobAllocator budget %p %lu %lu", ptr->buffer, it->first, it->second);
// it++;
// }
if (mappable)
vkUnmapMemory(vkdev->vkdevice(), ptr->memory);
vkDestroyBuffer(vkdev->vkdevice(), ptr->buffer, 0);
vkFreeMemory(vkdev->vkdevice(), ptr->memory, 0);
delete ptr;
}
d->buffer_blocks.clear();
d->buffer_budgets.clear();
for (size_t i = 0; i < d->image_memory_blocks.size(); i++)
{
VkDeviceMemory memory = d->image_memory_blocks[i];
// std::list< std::pair<size_t, size_t> >::iterator it = d->image_memory_budgets[i].begin();
// while (it != d->image_memory_budgets[i].end())
// {
// NCNN_LOGE("VkBlobAllocator budget %p %lu %lu", memory, it->first, it->second);
// it++;
// }
vkFreeMemory(vkdev->vkdevice(), memory, 0);
}
d->image_memory_blocks.clear();
d->image_memory_budgets.clear();
}
VkBufferMemory* VkBlobAllocator::fastMalloc(size_t size)
{
size_t aligned_size = alignSize(size, d->buffer_offset_alignment);
const int buffer_block_count = d->buffer_blocks.size();
// find first spare space in buffer_blocks
for (int i = 0; i < buffer_block_count; i++)
{
std::list<std::pair<size_t, size_t> >::iterator it = d->buffer_budgets[i].begin();
while (it != d->buffer_budgets[i].end())
{
size_t budget_size = it->second;
if (budget_size < aligned_size)
{
it++;
continue;
}
// return sub buffer
VkBufferMemory* ptr = new VkBufferMemory;
ptr->buffer = d->buffer_blocks[i]->buffer;
ptr->offset = it->first;
ptr->memory = d->buffer_blocks[i]->memory;
ptr->capacity = aligned_size;
ptr->mapped_ptr = d->buffer_blocks[i]->mapped_ptr;
ptr->access_flags = 0;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
// adjust buffer_budgets
if (budget_size == aligned_size)
{
d->buffer_budgets[i].erase(it);
}
else
{
it->first += aligned_size;
it->second -= aligned_size;
}
// NCNN_LOGE("VkBlobAllocator M %p +%lu %lu", ptr->buffer, ptr->offset, ptr->capacity);
return ptr;
}
}
size_t new_block_size = std::max(d->block_size, aligned_size);
// create new block
VkBufferMemory* block = new VkBufferMemory;
block->buffer = create_buffer(new_block_size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
block->offset = 0;
// TODO respect VK_KHR_dedicated_allocation ?
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements(vkdev->vkdevice(), block->buffer, &memoryRequirements);
// setup memory type and alignment
if (buffer_memory_type_index == (uint32_t)-1)
{
if (vkdev->info.type() == 1)
{
// integrated gpu, prefer unified memory
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0);
// on amd integrated gpu, there is a faster and larger device-only heap
uint32_t device_local_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
const VkPhysicalDeviceMemoryProperties& memory_properties = vkdev->info.physical_device_memory_properties();
uint32_t buffer_heap_index = memory_properties.memoryTypes[buffer_memory_type_index].heapIndex;
uint32_t device_local_heap_index = memory_properties.memoryTypes[device_local_memory_type_index].heapIndex;
if (device_local_heap_index < buffer_heap_index && memory_properties.memoryHeaps[device_local_heap_index].size > memory_properties.memoryHeaps[buffer_heap_index].size)
{
buffer_memory_type_index = device_local_memory_type_index;
}
}
else
{
// discrete gpu, device local
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
}
mappable = vkdev->is_mappable(buffer_memory_type_index);
coherent = vkdev->is_coherent(buffer_memory_type_index);
}
block->memory = allocate_memory(memoryRequirements.size, buffer_memory_type_index);
// ignore memoryRequirements.alignment as we always bind at zero offset
vkBindBufferMemory(vkdev->vkdevice(), block->buffer, block->memory, 0);
block->mapped_ptr = 0;
if (mappable)
{
vkMapMemory(vkdev->vkdevice(), block->memory, 0, new_block_size, 0, &block->mapped_ptr);
}
d->buffer_blocks.push_back(block);
// return sub buffer
VkBufferMemory* ptr = new VkBufferMemory;
ptr->buffer = block->buffer;
ptr->offset = 0;
ptr->memory = block->memory;
ptr->capacity = aligned_size;
ptr->mapped_ptr = block->mapped_ptr;
ptr->access_flags = 0;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
// adjust buffer_budgets
std::list<std::pair<size_t, size_t> > budget;
if (new_block_size > aligned_size)
{
budget.push_back(std::make_pair(aligned_size, new_block_size - aligned_size));
}
d->buffer_budgets.push_back(budget);
// NCNN_LOGE("VkBlobAllocator M %p +%lu %lu", ptr->buffer, ptr->offset, ptr->capacity);
return ptr;
}
void VkBlobAllocator::fastFree(VkBufferMemory* ptr)
{
// NCNN_LOGE("VkBlobAllocator F %p +%lu %lu", ptr->buffer, ptr->offset, ptr->capacity);
const int buffer_block_count = d->buffer_blocks.size();
int block_index = -1;
for (int i = 0; i < buffer_block_count; i++)
{
if (d->buffer_blocks[i]->buffer == ptr->buffer && d->buffer_blocks[i]->memory == ptr->memory)
{
block_index = i;
break;
}
}
if (block_index == -1)
{
NCNN_LOGE("FATAL ERROR! unlocked VkBlobAllocator get wild %p", ptr->buffer);
delete ptr;
return;
}
// merge
std::list<std::pair<size_t, size_t> >::iterator it_merge_left = d->buffer_budgets[block_index].end();
std::list<std::pair<size_t, size_t> >::iterator it_merge_right = d->buffer_budgets[block_index].end();
std::list<std::pair<size_t, size_t> >::iterator it = d->buffer_budgets[block_index].begin();
for (; it != d->buffer_budgets[block_index].end(); it++)
{
if (it->first + it->second == ptr->offset)
{
it_merge_left = it;
}
else if (ptr->offset + ptr->capacity == it->first)
{
it_merge_right = it;
}
}
if (it_merge_left != d->buffer_budgets[block_index].end() && it_merge_right != d->buffer_budgets[block_index].end())
{
it_merge_left->second = it_merge_right->first + it_merge_right->second - it_merge_left->first;
d->buffer_budgets[block_index].erase(it_merge_right);
}
else if (it_merge_left != d->buffer_budgets[block_index].end())
{
it_merge_left->second = ptr->offset + ptr->capacity - it_merge_left->first;
}
else if (it_merge_right != d->buffer_budgets[block_index].end())
{
it_merge_right->second = it_merge_right->first + it_merge_right->second - ptr->offset;
it_merge_right->first = ptr->offset;
}
else
{
if (ptr->offset == 0)
{
// chain leading block
d->buffer_budgets[block_index].push_front(std::make_pair(ptr->offset, ptr->capacity));
}
else
{
d->buffer_budgets[block_index].push_back(std::make_pair(ptr->offset, ptr->capacity));
}
}
delete ptr;
}
VkImageMemory* VkBlobAllocator::fastMalloc(int w, int h, int c, size_t elemsize, int elempack)
{
if (elempack != 1 && elempack != 4 && elempack != 8)
{
NCNN_LOGE("elempack must be 1 4 8");
return 0;
}
// resolve format
VkFormat format = VK_FORMAT_UNDEFINED;
if (elemsize / elempack == 4)
{
// fp32
if (elempack == 1) format = VK_FORMAT_R32_SFLOAT;
if (elempack == 4) format = VK_FORMAT_R32G32B32A32_SFLOAT;
if (elempack == 8) format = VK_FORMAT_R32G32B32A32_SFLOAT;
}
if (elemsize / elempack == 2)
{
// fp16
if (elempack == 1) format = VK_FORMAT_R16_SFLOAT;
if (elempack == 4) format = VK_FORMAT_R16G16B16A16_SFLOAT;
if (elempack == 8) format = VK_FORMAT_R16G16B16A16_SFLOAT;
}
// resolve image width height depth
int width = w;
int height = h;
int depth = c;
// large elempack spills on image w
if (elempack == 8) width *= 2;
if (width > (int)vkdev->info.max_image_dimension_3d() || height > (int)vkdev->info.max_image_dimension_3d() || depth > (int)vkdev->info.max_image_dimension_3d())
{
NCNN_LOGE("image dimension too large %d %d %d > %d", width, height, depth, (int)vkdev->info.max_image_dimension_3d());
return 0;
}
VkImageMemory* ptr = new VkImageMemory;
ptr->image = create_image(width, height, depth, format, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
ptr->width = width;
ptr->height = height;
ptr->depth = depth;
ptr->format = format;
// TODO respect VK_KHR_dedicated_allocation ?
VkMemoryRequirements memoryRequirements;
vkGetImageMemoryRequirements(vkdev->vkdevice(), ptr->image, &memoryRequirements);
const size_t size = memoryRequirements.size;
const size_t alignment = std::max((size_t)memoryRequirements.alignment, d->bind_memory_offset_alignment);
size_t aligned_size = alignSize(size, alignment);
const int image_memory_block_count = d->image_memory_blocks.size();
// find first spare space in image_memory_blocks
for (int i = 0; i < image_memory_block_count; i++)
{
#if __APPLE__
// HACK moltenvk v1.2.3 is unhappy for image binding with offset :(
break;
#endif
std::list<std::pair<size_t, size_t> >::iterator it = d->image_memory_budgets[i].begin();
while (it != d->image_memory_budgets[i].end())
{
// we cannot use it->first directly for base offset alignment
size_t bind_base_offset = it->first;
size_t bind_offset = alignSize(bind_base_offset, alignment);
size_t budget_size = it->second;
if (budget_size < aligned_size + (bind_offset - bind_base_offset))
{
it++;
continue;
}
// bind at memory offset
ptr->memory = d->image_memory_blocks[i];
ptr->bind_offset = bind_offset;
ptr->bind_capacity = aligned_size;
vkBindImageMemory(vkdev->vkdevice(), ptr->image, ptr->memory, ptr->bind_offset);
// do not allow host access to optimal tiling image
ptr->mapped_ptr = 0;
ptr->imageview = create_imageview(ptr->image, format);
ptr->access_flags = 0;
ptr->image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
ptr->command_refcount = 0;
if (bind_base_offset != bind_offset)
{
// NOTE there is small offset inside bind_base_offset and bind_offset
// adjust ptr->bind_offset and ptr->bind_capacity after vkBindImageMemory
// so that memory management could be easier
aligned_size += (bind_offset - bind_base_offset);
ptr->bind_offset = bind_base_offset;
ptr->bind_capacity = aligned_size;
}
// adjust image_memory_budgets
if (budget_size == aligned_size)
{
d->image_memory_budgets[i].erase(it);
}
else
{
it->first += aligned_size;
it->second -= aligned_size;
}
// NCNN_LOGE("VkBlobAllocator M %p +%lu %lu", ptr->memory, ptr->bind_offset, ptr->bind_capacity);
return ptr;
}
}
// setup memory type and alignment
if (image_memory_type_index == (uint32_t)-1)
{
if (vkdev->info.type() == 1)
{
// integrated gpu, prefer unified memory
image_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0);
// on amd integrated gpu, there is a faster and larger device-only heap
uint32_t device_local_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
const VkPhysicalDeviceMemoryProperties& memory_properties = vkdev->info.physical_device_memory_properties();
uint32_t buffer_heap_index = memory_properties.memoryTypes[image_memory_type_index].heapIndex;
uint32_t device_local_heap_index = memory_properties.memoryTypes[device_local_memory_type_index].heapIndex;
if (device_local_heap_index < buffer_heap_index && memory_properties.memoryHeaps[device_local_heap_index].size > memory_properties.memoryHeaps[buffer_heap_index].size)
{
image_memory_type_index = device_local_memory_type_index;
}
}
else
{
// discrete gpu, device local
image_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
}
mappable = vkdev->is_mappable(image_memory_type_index);
coherent = vkdev->is_coherent(image_memory_type_index);
}
// create new block
size_t new_block_size = std::max(d->block_size, aligned_size);
#if __APPLE__
// HACK moltenvk v1.2.3 is unhappy for image binding with offset
// always ignore block size for smaller memory footprint :(
new_block_size = aligned_size;
#endif
// bind at memory offset
ptr->memory = allocate_memory(new_block_size, image_memory_type_index);
ptr->bind_offset = 0;
ptr->bind_capacity = aligned_size;
// ignore memoryRequirements2.memoryRequirements.alignment as we always bind at zero offset
vkBindImageMemory(vkdev->vkdevice(), ptr->image, ptr->memory, ptr->bind_offset);
// do not allow host access to optimal tiling image
ptr->mapped_ptr = 0;
ptr->imageview = create_imageview(ptr->image, format);
ptr->access_flags = 0;
ptr->image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
ptr->command_refcount = 0;
// adjust image_memory_budgets
d->image_memory_blocks.push_back(ptr->memory);
std::list<std::pair<size_t, size_t> > budget;
if (new_block_size > aligned_size)
{
budget.push_back(std::make_pair(aligned_size, new_block_size - aligned_size));
}
d->image_memory_budgets.push_back(budget);
// NCNN_LOGE("VkBlobAllocator M %p +%lu %lu", ptr->memory, ptr->bind_offset, ptr->bind_capacity);
return ptr;
}
void VkBlobAllocator::fastFree(VkImageMemory* ptr)
{
// NCNN_LOGE("VkBlobAllocator F %p +%lu %lu", ptr->memory, ptr->bind_offset, ptr->bind_capacity);
const int image_memory_block_count = d->image_memory_blocks.size();
int block_index = -1;
for (int i = 0; i < image_memory_block_count; i++)
{
if (d->image_memory_blocks[i] == ptr->memory)
{
block_index = i;
break;
}
}
if (block_index == -1)
{
NCNN_LOGE("FATAL ERROR! unlocked VkBlobAllocator get wild %p", ptr->memory);
if (!ptr->command_refcount)
{
vkDestroyImageView(vkdev->vkdevice(), ptr->imageview, 0);
vkDestroyImage(vkdev->vkdevice(), ptr->image, 0);
delete ptr;
}
return;
}
// merge
std::list<std::pair<size_t, size_t> >::iterator it_merge_left = d->image_memory_budgets[block_index].end();
std::list<std::pair<size_t, size_t> >::iterator it_merge_right = d->image_memory_budgets[block_index].end();
std::list<std::pair<size_t, size_t> >::iterator it = d->image_memory_budgets[block_index].begin();
for (; it != d->image_memory_budgets[block_index].end(); it++)
{
if (it->first + it->second == ptr->bind_offset)
{
it_merge_left = it;
}
else if (ptr->bind_offset + ptr->bind_capacity == it->first)
{
it_merge_right = it;
}
}
if (it_merge_left != d->image_memory_budgets[block_index].end() && it_merge_right != d->image_memory_budgets[block_index].end())
{
it_merge_left->second = it_merge_right->first + it_merge_right->second - it_merge_left->first;
d->image_memory_budgets[block_index].erase(it_merge_right);
}
else if (it_merge_left != d->image_memory_budgets[block_index].end())
{
it_merge_left->second = ptr->bind_offset + ptr->bind_capacity - it_merge_left->first;
}
else if (it_merge_right != d->image_memory_budgets[block_index].end())
{
it_merge_right->second = it_merge_right->first + it_merge_right->second - ptr->bind_offset;
it_merge_right->first = ptr->bind_offset;
}
else
{
if (ptr->bind_offset == 0)
{
// chain leading block
d->image_memory_budgets[block_index].push_front(std::make_pair(ptr->bind_offset, ptr->bind_capacity));
}
else
{
d->image_memory_budgets[block_index].push_back(std::make_pair(ptr->bind_offset, ptr->bind_capacity));
}
}
if (!ptr->command_refcount)
{
vkDestroyImageView(vkdev->vkdevice(), ptr->imageview, 0);
vkDestroyImage(vkdev->vkdevice(), ptr->image, 0);
delete ptr;
}
}
class VkWeightAllocatorPrivate
{
public:
size_t block_size;
size_t buffer_offset_alignment;
size_t bind_memory_offset_alignment;
std::vector<size_t> buffer_block_free_spaces;
std::vector<VkBufferMemory*> buffer_blocks;
std::vector<VkBufferMemory*> dedicated_buffer_blocks;
std::vector<size_t> image_memory_block_free_spaces;
std::vector<VkDeviceMemory> image_memory_blocks;
std::vector<VkDeviceMemory> dedicated_image_memory_blocks;
};
VkWeightAllocator::VkWeightAllocator(const VulkanDevice* _vkdev, size_t preferred_block_size)
: VkAllocator(_vkdev), d(new VkWeightAllocatorPrivate)
{
d->buffer_offset_alignment = vkdev->info.buffer_offset_alignment();
d->bind_memory_offset_alignment = vkdev->info.buffer_image_granularity();
if (vkdev->info.type() == 1)
{
// on integrated gpu, there may be device local only memory too, eg. AMD APU
// assuming larger alignment always keeps us safe :)
// least common multiple for memory_map_alignment and buffer_offset_alignment and non_coherent_atom_size
d->buffer_offset_alignment = least_common_multiple(d->buffer_offset_alignment, vkdev->info.memory_map_alignment());
d->buffer_offset_alignment = least_common_multiple(d->buffer_offset_alignment, vkdev->info.non_coherent_atom_size());
}
d->block_size = alignSize(preferred_block_size, d->buffer_offset_alignment);
}
VkWeightAllocator::~VkWeightAllocator()
{
clear();
delete d;
}
VkWeightAllocator::VkWeightAllocator(const VkWeightAllocator&)
: VkAllocator(0), d(0)
{
}
VkWeightAllocator& VkWeightAllocator::operator=(const VkWeightAllocator&)
{
return *this;
}
void VkWeightAllocator::clear()
{
// NCNN_LOGE("VkWeightAllocator %lu %lu", d->buffer_blocks.size(), d->dedicated_buffer_blocks.size());
d->buffer_block_free_spaces.clear();
for (size_t i = 0; i < d->buffer_blocks.size(); i++)
{
VkBufferMemory* ptr = d->buffer_blocks[i];
if (mappable)
vkUnmapMemory(vkdev->vkdevice(), ptr->memory);
vkDestroyBuffer(vkdev->vkdevice(), ptr->buffer, 0);
vkFreeMemory(vkdev->vkdevice(), ptr->memory, 0);
delete ptr;
}
d->buffer_blocks.clear();
for (size_t i = 0; i < d->dedicated_buffer_blocks.size(); i++)
{
VkBufferMemory* ptr = d->dedicated_buffer_blocks[i];
if (mappable)
vkUnmapMemory(vkdev->vkdevice(), ptr->memory);
vkDestroyBuffer(vkdev->vkdevice(), ptr->buffer, 0);
vkFreeMemory(vkdev->vkdevice(), ptr->memory, 0);
delete ptr;
}
d->dedicated_buffer_blocks.clear();
d->image_memory_block_free_spaces.clear();
for (size_t i = 0; i < d->image_memory_blocks.size(); i++)
{
VkDeviceMemory memory = d->image_memory_blocks[i];
vkFreeMemory(vkdev->vkdevice(), memory, 0);
}
d->image_memory_blocks.clear();
for (size_t i = 0; i < d->dedicated_image_memory_blocks.size(); i++)
{
VkDeviceMemory memory = d->dedicated_image_memory_blocks[i];
vkFreeMemory(vkdev->vkdevice(), memory, 0);
}
d->dedicated_image_memory_blocks.clear();
}
VkBufferMemory* VkWeightAllocator::fastMalloc(size_t size)
{
// NCNN_LOGE("VkWeightAllocator fastMalloc %lu", size);
size_t aligned_size = alignSize(size, d->buffer_offset_alignment);
const int buffer_block_count = d->buffer_blocks.size();
// find first spare space in buffer_blocks
for (int i = 0; i < buffer_block_count; i++)
{
size_t free_size = d->buffer_block_free_spaces[i];
if (free_size >= aligned_size)
{
size_t block_offset = d->block_size - free_size;
// return sub buffer
VkBufferMemory* ptr = new VkBufferMemory;
ptr->buffer = d->buffer_blocks[i]->buffer;
ptr->offset = block_offset;
ptr->memory = d->buffer_blocks[i]->memory;
ptr->capacity = aligned_size;
ptr->mapped_ptr = d->buffer_blocks[i]->mapped_ptr;
ptr->access_flags = 0;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
d->buffer_block_free_spaces[i] -= aligned_size;
return ptr;
}
}
size_t new_block_size = std::max(d->block_size, aligned_size);
// create new block
VkBufferMemory* block = new VkBufferMemory;
block->buffer = create_buffer(new_block_size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
block->offset = 0;
if (vkdev->info.support_VK_KHR_get_memory_requirements2() && vkdev->info.support_VK_KHR_dedicated_allocation())
{
VkBufferMemoryRequirementsInfo2KHR bufferMemoryRequirementsInfo2;
bufferMemoryRequirementsInfo2.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR;
bufferMemoryRequirementsInfo2.pNext = 0;
bufferMemoryRequirementsInfo2.buffer = block->buffer;
VkMemoryRequirements2KHR memoryRequirements2;
memoryRequirements2.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR;
memoryRequirements2.pNext = 0;
VkMemoryDedicatedRequirementsKHR memoryDedicatedRequirements;
memoryDedicatedRequirements.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR;
memoryDedicatedRequirements.pNext = 0;
memoryRequirements2.pNext = &memoryDedicatedRequirements;
vkdev->vkGetBufferMemoryRequirements2KHR(vkdev->vkdevice(), &bufferMemoryRequirementsInfo2, &memoryRequirements2);
bool dedicatedAllocation = memoryDedicatedRequirements.requiresDedicatedAllocation || memoryDedicatedRequirements.prefersDedicatedAllocation;
if (dedicatedAllocation)
{
// setup memory type and alignment
if (buffer_memory_type_index == (uint32_t)-1)
{
if (vkdev->info.type() == 1)
{
// integrated gpu, prefer unified memory
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0);
// on amd integrated gpu, there is a faster and larger device-only heap
uint32_t device_local_memory_type_index = vkdev->find_memory_index(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
const VkPhysicalDeviceMemoryProperties& memory_properties = vkdev->info.physical_device_memory_properties();
uint32_t buffer_heap_index = memory_properties.memoryTypes[buffer_memory_type_index].heapIndex;
uint32_t device_local_heap_index = memory_properties.memoryTypes[device_local_memory_type_index].heapIndex;
if (device_local_heap_index < buffer_heap_index && memory_properties.memoryHeaps[device_local_heap_index].size > memory_properties.memoryHeaps[buffer_heap_index].size)
{
buffer_memory_type_index = device_local_memory_type_index;
}
}
else
{
// discrete gpu, device local
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
}
mappable = vkdev->is_mappable(buffer_memory_type_index);
coherent = vkdev->is_coherent(buffer_memory_type_index);
}
block->memory = allocate_dedicated_memory(memoryRequirements2.memoryRequirements.size, buffer_memory_type_index, 0, block->buffer);
// ignore memoryRequirements2.memoryRequirements.alignment as we always bind at zero offset
vkBindBufferMemory(vkdev->vkdevice(), block->buffer, block->memory, 0);
block->mapped_ptr = 0;
if (mappable)
{
vkMapMemory(vkdev->vkdevice(), block->memory, 0, new_block_size, 0, &block->mapped_ptr);
}
d->dedicated_buffer_blocks.push_back(block);
// return sub buffer
VkBufferMemory* ptr = new VkBufferMemory;
ptr->buffer = block->buffer;
ptr->offset = 0;
ptr->memory = block->memory;
ptr->capacity = new_block_size;
ptr->mapped_ptr = block->mapped_ptr;
ptr->access_flags = 0;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
return ptr;
}
}
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements(vkdev->vkdevice(), block->buffer, &memoryRequirements);
// setup memory type and alignment
if (buffer_memory_type_index == (uint32_t)-1)
{
if (vkdev->info.type() == 1)
{
// integrated gpu, prefer unified memory
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0);
// on amd integrated gpu, there is a faster and larger device-only heap
uint32_t device_local_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
const VkPhysicalDeviceMemoryProperties& memory_properties = vkdev->info.physical_device_memory_properties();
uint32_t buffer_heap_index = memory_properties.memoryTypes[buffer_memory_type_index].heapIndex;
uint32_t device_local_heap_index = memory_properties.memoryTypes[device_local_memory_type_index].heapIndex;
if (device_local_heap_index < buffer_heap_index && memory_properties.memoryHeaps[device_local_heap_index].size > memory_properties.memoryHeaps[buffer_heap_index].size)
{
buffer_memory_type_index = device_local_memory_type_index;
}
}
else
{
// discrete gpu, device local
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
}
mappable = vkdev->is_mappable(buffer_memory_type_index);
coherent = vkdev->is_coherent(buffer_memory_type_index);
}
block->memory = allocate_memory(memoryRequirements.size, buffer_memory_type_index);
// ignore memoryRequirements.alignment as we always bind at zero offset
vkBindBufferMemory(vkdev->vkdevice(), block->buffer, block->memory, 0);
// NCNN_LOGE("VkWeightAllocator M %p", block->buffer);
block->mapped_ptr = 0;
if (mappable)
{
vkMapMemory(vkdev->vkdevice(), block->memory, 0, new_block_size, 0, &block->mapped_ptr);
}
d->buffer_blocks.push_back(block);
d->buffer_block_free_spaces.push_back(new_block_size - aligned_size);
// return sub buffer
VkBufferMemory* ptr = new VkBufferMemory;
ptr->buffer = block->buffer;
ptr->offset = 0;
ptr->memory = block->memory;
ptr->capacity = aligned_size;
ptr->mapped_ptr = block->mapped_ptr;
ptr->access_flags = 0;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
return ptr;
}
void VkWeightAllocator::fastFree(VkBufferMemory* ptr)
{
// NCNN_LOGE("VkWeightAllocator F %p", ptr->buffer);
delete ptr;
}
VkImageMemory* VkWeightAllocator::fastMalloc(int w, int h, int c, size_t elemsize, int elempack)
{
if (elempack != 1 && elempack != 4 && elempack != 8 && elempack != 16 && elempack != 32 && elempack != 64)
{
NCNN_LOGE("elempack must be 1 4 8 16 32 64");
return 0;
}
// resolve format
VkFormat format = VK_FORMAT_UNDEFINED;
if (elemsize / elempack == 4)
{
// fp32
if (elempack == 1) format = VK_FORMAT_R32_SFLOAT;
if (elempack == 4) format = VK_FORMAT_R32G32B32A32_SFLOAT;
if (elempack == 8) format = VK_FORMAT_R32G32B32A32_SFLOAT;
if (elempack == 16) format = VK_FORMAT_R32G32B32A32_SFLOAT;
if (elempack == 32) format = VK_FORMAT_R32G32B32A32_SFLOAT;
if (elempack == 64) format = VK_FORMAT_R32G32B32A32_SFLOAT;
}
if (elemsize / elempack == 2)
{
// fp16
if (elempack == 1) format = VK_FORMAT_R16_SFLOAT;
if (elempack == 4) format = VK_FORMAT_R16G16B16A16_SFLOAT;
if (elempack == 8) format = VK_FORMAT_R16G16B16A16_SFLOAT;
if (elempack == 16) format = VK_FORMAT_R16G16B16A16_SFLOAT;
if (elempack == 32) format = VK_FORMAT_R16G16B16A16_SFLOAT;
if (elempack == 64) format = VK_FORMAT_R16G16B16A16_SFLOAT;
}
// resolve image width height depth
int width = w;
int height = h;
int depth = c;
// large elempack spills on image w
if (elempack == 8) width *= 2;
if (elempack == 16) width *= 4;
if (elempack == 32) width *= 8;
if (elempack == 64) width *= 16;
if (width > (int)vkdev->info.max_image_dimension_3d() || height > (int)vkdev->info.max_image_dimension_3d() || depth > (int)vkdev->info.max_image_dimension_3d())
{
NCNN_LOGE("image dimension too large %d %d %d > %d", width, height, depth, (int)vkdev->info.max_image_dimension_3d());
return 0;
}
VkImageMemory* ptr = new VkImageMemory;
ptr->image = create_image(width, height, depth, format, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT);
ptr->width = width;
ptr->height = height;
ptr->depth = depth;
ptr->format = format;
if (vkdev->info.support_VK_KHR_get_memory_requirements2() && vkdev->info.support_VK_KHR_dedicated_allocation())
{
VkImageMemoryRequirementsInfo2KHR imageMemoryRequirementsInfo2;
imageMemoryRequirementsInfo2.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR;
imageMemoryRequirementsInfo2.pNext = 0;
imageMemoryRequirementsInfo2.image = ptr->image;
VkMemoryRequirements2KHR memoryRequirements2;
memoryRequirements2.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR;
memoryRequirements2.pNext = 0;
VkMemoryDedicatedRequirementsKHR memoryDedicatedRequirements;
memoryDedicatedRequirements.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR;
memoryDedicatedRequirements.pNext = 0;
memoryRequirements2.pNext = &memoryDedicatedRequirements;
vkdev->vkGetImageMemoryRequirements2KHR(vkdev->vkdevice(), &imageMemoryRequirementsInfo2, &memoryRequirements2);
bool dedicatedAllocation = memoryDedicatedRequirements.requiresDedicatedAllocation || memoryDedicatedRequirements.prefersDedicatedAllocation;
if (dedicatedAllocation)
{
// setup memory type and alignment
if (image_memory_type_index == (uint32_t)-1)
{
if (vkdev->info.type() == 1)
{
// integrated gpu, prefer unified memory
image_memory_type_index = vkdev->find_memory_index(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0);
// on amd integrated gpu, there is a faster and larger device-only heap
uint32_t device_local_memory_type_index = vkdev->find_memory_index(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
const VkPhysicalDeviceMemoryProperties& memory_properties = vkdev->info.physical_device_memory_properties();
uint32_t buffer_heap_index = memory_properties.memoryTypes[image_memory_type_index].heapIndex;
uint32_t device_local_heap_index = memory_properties.memoryTypes[device_local_memory_type_index].heapIndex;
if (device_local_heap_index < buffer_heap_index && memory_properties.memoryHeaps[device_local_heap_index].size > memory_properties.memoryHeaps[buffer_heap_index].size)
{
image_memory_type_index = device_local_memory_type_index;
}
}
else
{
// discrete gpu, device local
image_memory_type_index = vkdev->find_memory_index(memoryRequirements2.memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
}
mappable = vkdev->is_mappable(image_memory_type_index);
coherent = vkdev->is_coherent(image_memory_type_index);
}
// bind memory
ptr->memory = allocate_dedicated_memory(memoryRequirements2.memoryRequirements.size, image_memory_type_index, ptr->image, 0);
ptr->bind_offset = 0;
ptr->bind_capacity = memoryRequirements2.memoryRequirements.size;
// ignore memoryRequirements2.memoryRequirements.alignment as we always bind at zero offset
vkBindImageMemory(vkdev->vkdevice(), ptr->image, ptr->memory, ptr->bind_offset);
// do not allow host access to optimal tiling image
ptr->mapped_ptr = 0;
ptr->imageview = create_imageview(ptr->image, format);
ptr->access_flags = 0;
ptr->image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
ptr->command_refcount = 0;
d->dedicated_image_memory_blocks.push_back(ptr->memory);
return ptr;
}
}
VkMemoryRequirements memoryRequirements;
vkGetImageMemoryRequirements(vkdev->vkdevice(), ptr->image, &memoryRequirements);
const size_t size = memoryRequirements.size;
const size_t alignment = std::max((size_t)memoryRequirements.alignment, d->bind_memory_offset_alignment);
size_t aligned_size = alignSize(size, alignment);
const int image_memory_block_count = d->image_memory_blocks.size();
// find first spare space in buffer_blocks
for (int i = 0; i < image_memory_block_count; i++)
{
// we cannot use image_memory_block_free_spaces[i] directly for base offset alignment
size_t bind_base_offset = d->block_size - d->image_memory_block_free_spaces[i];
size_t bind_offset = alignSize(bind_base_offset, alignment);
if (d->image_memory_block_free_spaces[i] >= aligned_size + (bind_offset - bind_base_offset))
{
// bind at memory offset
ptr->memory = d->image_memory_blocks[i];
ptr->bind_offset = bind_offset;
ptr->bind_capacity = aligned_size;
vkBindImageMemory(vkdev->vkdevice(), ptr->image, ptr->memory, ptr->bind_offset);
// do not allow host access to optimal tiling image
ptr->mapped_ptr = 0;
ptr->imageview = create_imageview(ptr->image, format);
ptr->access_flags = 0;
ptr->image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
ptr->command_refcount = 0;
if (bind_base_offset != bind_offset)
{
// NOTE there is small offset inside bind_base_offset and bind_offset
// adjust ptr->bind_offset and ptr->bind_capacity after vkBindImageMemory
// so that memory management could be easier
aligned_size += (bind_offset - bind_base_offset);
ptr->bind_offset = bind_base_offset;
ptr->bind_capacity = aligned_size;
}
d->image_memory_block_free_spaces[i] -= aligned_size;
return ptr;
}
}
// setup memory type and alignment
if (image_memory_type_index == (uint32_t)-1)
{
if (vkdev->info.type() == 1)
{
// integrated gpu, prefer unified memory
image_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, 0);
// on amd integrated gpu, there is a faster and larger device-only heap
uint32_t device_local_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
const VkPhysicalDeviceMemoryProperties& memory_properties = vkdev->info.physical_device_memory_properties();
uint32_t buffer_heap_index = memory_properties.memoryTypes[image_memory_type_index].heapIndex;
uint32_t device_local_heap_index = memory_properties.memoryTypes[device_local_memory_type_index].heapIndex;
if (device_local_heap_index < buffer_heap_index && memory_properties.memoryHeaps[device_local_heap_index].size > memory_properties.memoryHeaps[buffer_heap_index].size)
{
image_memory_type_index = device_local_memory_type_index;
}
}
else
{
// discrete gpu, device local
image_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
}
mappable = vkdev->is_mappable(image_memory_type_index);
coherent = vkdev->is_coherent(image_memory_type_index);
}
// create new block
size_t new_block_size = std::max(d->block_size, aligned_size);
// bind at memory offset
ptr->memory = allocate_memory(new_block_size, image_memory_type_index);
ptr->bind_offset = 0;
ptr->bind_capacity = aligned_size;
// ignore memoryRequirements2.memoryRequirements.alignment as we always bind at zero offset
vkBindImageMemory(vkdev->vkdevice(), ptr->image, ptr->memory, ptr->bind_offset);
// do not allow host access to optimal tiling image
ptr->mapped_ptr = 0;
ptr->imageview = create_imageview(ptr->image, format);
ptr->access_flags = 0;
ptr->image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
ptr->command_refcount = 0;
d->image_memory_blocks.push_back(ptr->memory);
d->image_memory_block_free_spaces.push_back(new_block_size - aligned_size);
return ptr;
}
void VkWeightAllocator::fastFree(VkImageMemory* ptr)
{
// NCNN_LOGE("VkWeightAllocator F %p", ptr->memory);
if (!ptr->command_refcount)
{
vkDestroyImageView(vkdev->vkdevice(), ptr->imageview, 0);
vkDestroyImage(vkdev->vkdevice(), ptr->image, 0);
delete ptr;
}
}
class VkStagingAllocatorPrivate
{
public:
unsigned int size_compare_ratio; // 0~256
std::list<VkBufferMemory*> buffer_budgets;
};
VkStagingAllocator::VkStagingAllocator(const VulkanDevice* _vkdev)
: VkAllocator(_vkdev), d(new VkStagingAllocatorPrivate)
{
mappable = true;
coherent = true;
d->size_compare_ratio = 192; // 0.75f * 256
}
VkStagingAllocator::~VkStagingAllocator()
{
clear();
delete d;
}
VkStagingAllocator::VkStagingAllocator(const VkStagingAllocator&)
: VkAllocator(0), d(0)
{
}
VkStagingAllocator& VkStagingAllocator::operator=(const VkStagingAllocator&)
{
return *this;
}
void VkStagingAllocator::set_size_compare_ratio(float scr)
{
if (scr < 0.f || scr > 1.f)
{
NCNN_LOGE("invalid size compare ratio %f", scr);
return;
}
d->size_compare_ratio = (unsigned int)(scr * 256);
}
void VkStagingAllocator::clear()
{
// NCNN_LOGE("VkStagingAllocator %lu", buffer_budgets.size());
for (std::list<VkBufferMemory*>::iterator it = d->buffer_budgets.begin(); it != d->buffer_budgets.end(); it++)
{
VkBufferMemory* ptr = *it;
// NCNN_LOGE("VkStagingAllocator F %p", ptr->buffer);
vkUnmapMemory(vkdev->vkdevice(), ptr->memory);
vkDestroyBuffer(vkdev->vkdevice(), ptr->buffer, 0);
vkFreeMemory(vkdev->vkdevice(), ptr->memory, 0);
delete ptr;
}
d->buffer_budgets.clear();
}
VkBufferMemory* VkStagingAllocator::fastMalloc(size_t size)
{
// find free budget
std::list<VkBufferMemory*>::iterator it = d->buffer_budgets.begin();
for (; it != d->buffer_budgets.end(); it++)
{
VkBufferMemory* ptr = *it;
size_t capacity = ptr->capacity;
// size_compare_ratio ~ 100%
if (capacity >= size && ((capacity * d->size_compare_ratio) >> 8) <= size)
{
d->buffer_budgets.erase(it);
// NCNN_LOGE("VkStagingAllocator M %p %lu reused %lu", ptr->buffer, size, capacity);
return ptr;
}
}
VkBufferMemory* ptr = new VkBufferMemory;
ptr->buffer = create_buffer(size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
ptr->offset = 0;
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements(vkdev->vkdevice(), ptr->buffer, &memoryRequirements);
// setup memory type
if (buffer_memory_type_index == (uint32_t)-1)
{
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}
ptr->memory = allocate_memory(memoryRequirements.size, buffer_memory_type_index);
// ignore memoryRequirements.alignment as we always bind at zero offset
vkBindBufferMemory(vkdev->vkdevice(), ptr->buffer, ptr->memory, 0);
ptr->capacity = size;
vkMapMemory(vkdev->vkdevice(), ptr->memory, 0, size, 0, &ptr->mapped_ptr);
ptr->access_flags = 0;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
// NCNN_LOGE("VkStagingAllocator M %p %lu", ptr->buffer, size);
return ptr;
}
void VkStagingAllocator::fastFree(VkBufferMemory* ptr)
{
// NCNN_LOGE("VkStagingAllocator F %p", ptr->buffer);
// return to buffer_budgets
d->buffer_budgets.push_back(ptr);
}
VkImageMemory* VkStagingAllocator::fastMalloc(int w, int h, int c, size_t elemsize, int /* elempack */)
{
// staging image is mainly used for storing small piece of dynamic parameters
// we allocate host memory as a fake image, it's simple and good
const size_t size = w * h * c * elemsize;
VkImageMemory* ptr = new VkImageMemory;
ptr->image = 0;
ptr->width = w;
ptr->height = h;
ptr->depth = c;
ptr->format = VK_FORMAT_UNDEFINED;
ptr->memory = 0;
ptr->bind_offset = 0;
ptr->bind_capacity = size;
ptr->mapped_ptr = malloc(size);
ptr->imageview = 0;
ptr->access_flags = 0;
ptr->image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
ptr->stage_flags = VK_PIPELINE_STAGE_HOST_BIT;
ptr->command_refcount = 0;
// NCNN_LOGE("VkStagingAllocator M %p %d %d %d %d %d", ptr->image, dims, width, height, depth, format);
return ptr;
}
void VkStagingAllocator::fastFree(VkImageMemory* ptr)
{
// NCNN_LOGE("VkStagingAllocator F %p", ptr->image);
free(ptr->mapped_ptr);
delete ptr;
}
class VkWeightStagingAllocatorPrivate
{
public:
};
VkWeightStagingAllocator::VkWeightStagingAllocator(const VulkanDevice* _vkdev)
: VkAllocator(_vkdev), d(new VkWeightStagingAllocatorPrivate)
{
mappable = true;
coherent = true;
}
VkWeightStagingAllocator::~VkWeightStagingAllocator()
{
delete d;
}
VkWeightStagingAllocator::VkWeightStagingAllocator(const VkWeightStagingAllocator&)
: VkAllocator(0), d(0)
{
}
VkWeightStagingAllocator& VkWeightStagingAllocator::operator=(const VkWeightStagingAllocator&)
{
return *this;
}
VkBufferMemory* VkWeightStagingAllocator::fastMalloc(size_t size)
{
VkBufferMemory* ptr = new VkBufferMemory;
ptr->buffer = create_buffer(size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT);
ptr->offset = 0;
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements(vkdev->vkdevice(), ptr->buffer, &memoryRequirements);
// setup memory type
if (buffer_memory_type_index == (uint32_t)-1)
{
buffer_memory_type_index = vkdev->find_memory_index(memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, VK_MEMORY_PROPERTY_HOST_CACHED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}
ptr->memory = allocate_memory(memoryRequirements.size, buffer_memory_type_index);
// ignore memoryRequirements.alignment as we always bind at zero offset
vkBindBufferMemory(vkdev->vkdevice(), ptr->buffer, ptr->memory, 0);
ptr->capacity = size;
vkMapMemory(vkdev->vkdevice(), ptr->memory, 0, size, 0, &ptr->mapped_ptr);
ptr->access_flags = 0;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
// NCNN_LOGE("VkWeightStagingAllocator M %p %lu", ptr->buffer, size);
return ptr;
}
void VkWeightStagingAllocator::fastFree(VkBufferMemory* ptr)
{
// NCNN_LOGE("VkWeightStagingAllocator F %p", ptr->buffer);
vkUnmapMemory(vkdev->vkdevice(), ptr->memory);
vkDestroyBuffer(vkdev->vkdevice(), ptr->buffer, 0);
vkFreeMemory(vkdev->vkdevice(), ptr->memory, 0);
delete ptr;
}
VkImageMemory* VkWeightStagingAllocator::fastMalloc(int /*w*/, int /*h*/, int /*c*/, size_t /*elemsize*/, int /*elempack*/)
{
return 0;
}
void VkWeightStagingAllocator::fastFree(VkImageMemory* /*ptr*/)
{
}
#if __ANDROID_API__ >= 26
VkAndroidHardwareBufferImageAllocator::VkAndroidHardwareBufferImageAllocator(const VulkanDevice* _vkdev, AHardwareBuffer* _hb)
: VkAllocator(_vkdev), hb(_hb)
{
samplerYcbcrConversion = 0;
init();
}
VkAndroidHardwareBufferImageAllocator::~VkAndroidHardwareBufferImageAllocator()
{
if (samplerYcbcrConversion)
{
vkdev->vkDestroySamplerYcbcrConversionKHR(vkdev->vkdevice(), samplerYcbcrConversion, 0);
samplerYcbcrConversion = 0;
}
}
VkAndroidHardwareBufferImageAllocator::VkAndroidHardwareBufferImageAllocator(const VkAndroidHardwareBufferImageAllocator&)
: VkAllocator(0)
{
}
VkAndroidHardwareBufferImageAllocator& VkAndroidHardwareBufferImageAllocator::operator=(const VkAndroidHardwareBufferImageAllocator&)
{
return *this;
}
VkBufferMemory* VkAndroidHardwareBufferImageAllocator::fastMalloc(size_t /*size*/)
{
return 0;
}
void VkAndroidHardwareBufferImageAllocator::fastFree(VkBufferMemory* /*ptr*/)
{
}
VkImageMemory* VkAndroidHardwareBufferImageAllocator::fastMalloc(int /*w*/, int /*h*/, int /*c*/, size_t /*elemsize*/, int /*elempack*/)
{
VkResult ret;
VkExternalFormatANDROID externalFormat;
externalFormat.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
externalFormat.pNext = 0;
externalFormat.externalFormat = bufferFormatProperties.externalFormat;
VkExternalMemoryImageCreateInfo externalMemoryImageCreateInfo;
externalMemoryImageCreateInfo.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
externalMemoryImageCreateInfo.pNext = &externalFormat,
externalMemoryImageCreateInfo.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
VkImageCreateInfo imageCreateInfo;
imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
imageCreateInfo.pNext = &externalMemoryImageCreateInfo;
imageCreateInfo.flags = 0;
imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
imageCreateInfo.format = VK_FORMAT_UNDEFINED;
imageCreateInfo.extent.width = bufferDesc.width;
imageCreateInfo.extent.height = bufferDesc.height;
imageCreateInfo.extent.depth = 1;
imageCreateInfo.mipLevels = 1;
imageCreateInfo.arrayLayers = 1;
imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT;
imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
imageCreateInfo.queueFamilyIndexCount = 0;
imageCreateInfo.pQueueFamilyIndices = 0;
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
VkImage image = 0;
ret = vkCreateImage(vkdev->vkdevice(), &imageCreateInfo, 0, &image);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkCreateImage failed %d", ret);
return 0;
}
// setup memory type
if (image_memory_type_index == (uint32_t)-1)
{
image_memory_type_index = vkdev->find_memory_index(bufferProperties.memoryTypeBits, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT);
}
VkImportAndroidHardwareBufferInfoANDROID importAndroidHardwareBufferInfo;
importAndroidHardwareBufferInfo.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID;
importAndroidHardwareBufferInfo.pNext = 0;
importAndroidHardwareBufferInfo.buffer = hb;
VkMemoryDedicatedAllocateInfo memoryDedicatedAllocateInfo;
memoryDedicatedAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO;
memoryDedicatedAllocateInfo.pNext = &importAndroidHardwareBufferInfo;
memoryDedicatedAllocateInfo.image = image;
memoryDedicatedAllocateInfo.buffer = VK_NULL_HANDLE;
VkMemoryAllocateInfo memoryAllocateInfo;
memoryAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memoryAllocateInfo.pNext = &memoryDedicatedAllocateInfo;
memoryAllocateInfo.allocationSize = bufferProperties.allocationSize;
memoryAllocateInfo.memoryTypeIndex = image_memory_type_index;
VkDeviceMemory memory = 0;
ret = vkAllocateMemory(vkdev->vkdevice(), &memoryAllocateInfo, 0, &memory);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkAllocateMemory failed %d", ret);
return 0;
}
VkBindImageMemoryInfo bindImageMemoryInfo;
bindImageMemoryInfo.sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO;
bindImageMemoryInfo.pNext = 0;
bindImageMemoryInfo.image = image;
bindImageMemoryInfo.memory = memory;
bindImageMemoryInfo.memoryOffset = 0;
ret = vkdev->vkBindImageMemory2KHR(vkdev->vkdevice(), 1, &bindImageMemoryInfo);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkBindImageMemory2KHR failed %d", ret);
vkDestroyImage(vkdev->vkdevice(), image, 0);
return 0;
}
VkSamplerYcbcrConversionInfoKHR samplerYcbcrConversionInfo;
samplerYcbcrConversionInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_INFO_KHR;
samplerYcbcrConversionInfo.pNext = &externalFormat;
samplerYcbcrConversionInfo.conversion = samplerYcbcrConversion;
VkImageViewCreateInfo imageViewCreateInfo;
imageViewCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
imageViewCreateInfo.pNext = &samplerYcbcrConversionInfo;
imageViewCreateInfo.flags = 0;
imageViewCreateInfo.image = image;
imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewCreateInfo.format = VK_FORMAT_UNDEFINED;
imageViewCreateInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
imageViewCreateInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
imageViewCreateInfo.subresourceRange.baseMipLevel = 0;
imageViewCreateInfo.subresourceRange.levelCount = 1;
imageViewCreateInfo.subresourceRange.baseArrayLayer = 0;
imageViewCreateInfo.subresourceRange.layerCount = 1;
VkImageView imageview = 0;
ret = vkCreateImageView(vkdev->vkdevice(), &imageViewCreateInfo, 0, &imageview);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkCreateImageView failed %d", ret);
vkDestroyImage(vkdev->vkdevice(), image, 0);
vkFreeMemory(vkdev->vkdevice(), memory, 0);
return 0;
}
VkImageMemory* ptr = new VkImageMemory;
ptr->image = image;
ptr->memory = memory;
ptr->imageview = imageview;
ptr->access_flags = 0;
ptr->image_layout = VK_IMAGE_LAYOUT_UNDEFINED;
ptr->stage_flags = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
return ptr;
}
void VkAndroidHardwareBufferImageAllocator::fastFree(VkImageMemory* ptr)
{
vkDestroyImageView(vkdev->vkdevice(), ptr->imageview, 0);
vkDestroyImage(vkdev->vkdevice(), ptr->image, 0);
vkFreeMemory(vkdev->vkdevice(), ptr->memory, 0);
delete ptr;
}
int VkAndroidHardwareBufferImageAllocator::init()
{
AHardwareBuffer_describe(hb, &bufferDesc);
VkResult ret;
// resolve externalFormat
bufferFormatProperties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID;
bufferFormatProperties.pNext = 0;
bufferProperties.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID;
bufferProperties.pNext = &bufferFormatProperties;
ret = vkdev->vkGetAndroidHardwareBufferPropertiesANDROID(vkdev->vkdevice(), hb, &bufferProperties);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkGetAndroidHardwareBufferPropertiesANDROID failed %d", ret);
return -1;
}
// setup samplerYcbcrConversion
VkExternalFormatANDROID externalFormat;
externalFormat.sType = VK_STRUCTURE_TYPE_EXTERNAL_FORMAT_ANDROID;
externalFormat.pNext = 0;
externalFormat.externalFormat = bufferFormatProperties.externalFormat;
VkSamplerYcbcrConversionCreateInfoKHR samplerYcbcrConversionCreateInfo;
samplerYcbcrConversionCreateInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_YCBCR_CONVERSION_CREATE_INFO_KHR;
samplerYcbcrConversionCreateInfo.pNext = &externalFormat;
samplerYcbcrConversionCreateInfo.format = VK_FORMAT_UNDEFINED;
samplerYcbcrConversionCreateInfo.ycbcrModel = bufferFormatProperties.suggestedYcbcrModel;
samplerYcbcrConversionCreateInfo.ycbcrRange = bufferFormatProperties.suggestedYcbcrRange;
samplerYcbcrConversionCreateInfo.components = bufferFormatProperties.samplerYcbcrConversionComponents;
samplerYcbcrConversionCreateInfo.xChromaOffset = bufferFormatProperties.suggestedXChromaOffset;
samplerYcbcrConversionCreateInfo.yChromaOffset = bufferFormatProperties.suggestedYChromaOffset;
samplerYcbcrConversionCreateInfo.chromaFilter = VK_FILTER_NEAREST;
samplerYcbcrConversionCreateInfo.forceExplicitReconstruction = VK_FALSE;
ret = vkdev->vkCreateSamplerYcbcrConversionKHR(vkdev->vkdevice(), &samplerYcbcrConversionCreateInfo, 0, &samplerYcbcrConversion);
if (ret != VK_SUCCESS)
{
NCNN_LOGE("vkCreateSamplerYcbcrConversionKHR failed %d", ret);
return -1;
}
return 0;
}
int VkAndroidHardwareBufferImageAllocator::width() const
{
return bufferDesc.width;
}
int VkAndroidHardwareBufferImageAllocator::height() const
{
return bufferDesc.height;
}
uint64_t VkAndroidHardwareBufferImageAllocator::external_format() const
{
return bufferFormatProperties.externalFormat;
}
#endif // __ANDROID_API__ >= 26
#endif // NCNN_VULKAN
} // namespace ncnn
|