File size: 209,154 Bytes
08c8a6d |
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 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330 8331 8332 8333 8334 8335 8336 8337 8338 8339 8340 8341 8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834 8835 8836 8837 8838 8839 8840 8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902 8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918 8919 8920 8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936 8937 8938 8939 8940 8941 8942 8943 8944 8945 8946 8947 8948 8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010 9011 9012 9013 9014 9015 9016 9017 9018 9019 9020 9021 9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061 9062 9063 9064 9065 9066 9067 9068 9069 9070 9071 9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088 9089 9090 9091 9092 9093 9094 9095 9096 9097 9098 9099 9100 9101 9102 9103 9104 9105 9106 9107 9108 9109 9110 9111 9112 9113 9114 9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233 9234 9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257 9258 9259 9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281 9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304 9305 9306 9307 9308 9309 9310 9311 9312 9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347 9348 9349 9350 9351 9352 9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520 9521 9522 9523 9524 9525 9526 9527 9528 9529 9530 9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543 9544 9545 9546 9547 9548 9549 9550 9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561 9562 9563 9564 9565 9566 9567 9568 9569 9570 9571 9572 9573 9574 9575 9576 9577 9578 9579 9580 9581 9582 9583 9584 9585 9586 9587 9588 9589 9590 9591 9592 9593 9594 9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628 9629 9630 9631 9632 9633 9634 9635 9636 9637 9638 9639 9640 9641 9642 9643 9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654 9655 9656 9657 9658 9659 9660 9661 9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688 9689 9690 9691 9692 9693 9694 9695 9696 9697 9698 9699 9700 9701 9702 9703 9704 9705 9706 9707 9708 9709 9710 9711 9712 9713 9714 9715 9716 9717 9718 9719 9720 9721 9722 9723 9724 9725 9726 9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757 9758 9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784 9785 9786 9787 9788 9789 9790 9791 9792 9793 9794 9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808 9809 9810 9811 9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822 9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836 9837 9838 9839 9840 9841 9842 9843 9844 9845 9846 9847 9848 9849 9850 9851 9852 9853 9854 9855 9856 9857 9858 9859 9860 9861 9862 9863 9864 9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932 9933 9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944 9945 9946 9947 9948 9949 9950 9951 9952 9953 9954 9955 9956 9957 9958 9959 9960 9961 9962 9963 9964 9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007 10008 10009 10010 10011 10012 10013 10014 10015 10016 10017 10018 10019 10020 10021 10022 10023 10024 10025 10026 10027 10028 10029 10030 10031 10032 10033 10034 10035 10036 10037 10038 10039 10040 10041 10042 10043 10044 10045 10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066 10067 10068 10069 10070 10071 10072 10073 10074 10075 10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128 10129 10130 10131 10132 10133 10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151 10152 10153 10154 10155 |
CUDA C++ Best Practices Guide
Release 12.5
NVIDIA
May 09, 2024
Contents
1 What Is This Document?
2 Who Should Read This Guide?
3 Assess, Parallelize, Optimize, Deploy
.
Assess .
.
.
.
Parallelize .
.
.
Optimize .
.
.
.
Deploy .
3.1
3.2
3.3
3.4
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
4 Recommendations and Best Practices
5 Assessing Your Application
6 Heterogeneous Computing
6.1
6.2
.
Differences between Host and Device .
What Runs on a CUDA-Enabled Device? .
.
.
.
.
.
.
.
.
.
.
.
7.1
Profile .
7.1.1
7.1.2
7.1.3
7 Application Profiling
.
.
.
.
.
.
.
Creating the Profile .
Identifying Hotspots .
.
Understanding Scaling .
.
.
.
.
Strong Scaling and Amdahl’s Law .
.
.
.
.
7.1.3.1
.
7.1.3.2 Weak Scaling and Gustafson’s Law .
Applying Strong and Weak Scaling .
7.1.3.3
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
8 Parallelizing Your Application
9 Getting Started
9.1
9.2
9.3
.
Parallel Libraries .
.
Parallelizing Compilers .
.
Coding to Expose Parallelism .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
10 Getting the Right Answer
.
Verification .
10.1
10.2
10.3
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
10.1.1 Reference Comparison .
.
.
10.1.2 Unit Testing .
Debugging .
.
.
.
Numerical Accuracy and Precision .
.
.
.
.
.
.
10.3.1 Single vs. Double Precision .
.
10.3.2 Floating Point Math Is not Associative .
.
10.3.3 IEEE 754 Compliance .
.
.
10.3.4 x86 80-bit Computations .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
3
5
7
8
8
8
9
.
.
.
.
11
13
15
. 15
. 16
19
. 19
. 19
. 20
. 20
. 20
. 21
. 21
23
25
. 25
. 25
. 26
27
. 27
. 27
. 27
. 28
. 28
. 28
. 29
. 29
. 29
i
11 Optimizing CUDA Applications
12 Performance Metrics
.
12.1
12.2
.
.
.
.
.
.
.
.
.
.
.
.
.
Timing .
.
.
12.1.1 Using CPU Timers .
.
12.1.2 Using CUDA GPU Timers .
.
.
.
.
.
.
.
.
.
.
.
12.2.1 Theoretical Bandwidth Calculation .
12.2.2 Effective Bandwidth Calculation .
.
.
12.2.3 Throughput Reported by Visual Profiler .
Bandwidth .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13 Memory Optimizations
13.1
13.2
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13.2.2.1
13.2.2.2
13.2.2 L2 Cache .
Data Transfer Between Host and Device .
.
Effects of Misaligned Accesses .
.
Strided Accesses .
.
.
.
.
.
.
.
13.2.1 Coalesced Access to Global Memory .
.
.
.
.
13.1.1 Pinned Memory .
13.1.2 Asynchronous and Overlapping Transfers with Computation .
.
13.1.3 Zero Copy .
.
.
.
13.1.4 Unified Virtual Addressing .
.
.
Device Memory Spaces .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13.2.1.1 A Simple Access Pattern .
.
.
.
13.2.1.2 A Sequential but Misaligned Access Pattern .
.
.
.
13.2.1.3
.
.
.
.
13.2.1.4
.
.
.
.
.
.
.
.
.
.
.
.
L2 Cache Access Window .
.
.
.
.
Tuning the Access Window Hit-Ratio .
.
.
.
.
.
.
.
.
.
Shared Memory and Memory Banks .
.
.
13.2.3.1
.
Shared Memory in Matrix Multiplication (C=AB)
.
13.2.3.2
13.2.3.3
.
Shared Memory in Matrix Multiplication (C=AAT) .
13.2.3.4 Asynchronous Copy from Global Memory to Shared Memory .
.
.
.
.
.
.
.
.
.
.
.
.
13.2.5.1 Additional Texture Capabilities .
.
.
.
.
.
.
.
.
Register Pressure .
.
.
.
13.2.6 Constant Memory .
.
13.2.7 Registers .
13.2.4 Local Memory .
.
13.2.5 Texture Memory .
Allocation .
.
NUMA Best Practices .
13.2.3 Shared Memory .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13.2.7.1
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
13.3
13.4
.
.
.
.
.
.
.
.
14.1 Occupancy .
.
14.1.1 Calculating Occupancy .
14 Execution Configuration Optimizations
.
.
.
.
.
.
.
.
.
14.2 Hiding Register Dependencies .
.
14.3
.
14.4
.
14.5
.
14.6 Multiple contexts .
Thread and Block Heuristics .
Effects of Shared Memory .
.
Concurrent Kernel Execution .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
15 Instruction Optimization
15.1
.
.
Arithmetic Instructions .
.
15.1.1 Division Modulo Operations .
15.1.2 Loop Counters Signed vs. Unsigned .
.
15.1.3 Reciprocal Square Root
.
.
15.1.4 Other Arithmetic Instructions .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
ii
31
33
. 33
. 33
. 34
. 34
. 35
. 35
. 36
37
. 37
. 38
. 38
. 40
. 41
. 42
. 43
. 44
. 44
. 45
. 46
. 47
. 47
. 48
. 50
. 51
. 51
. 54
. 56
. 58
. 59
. 59
. 60
. 60
. 60
. 60
. 61
63
. 63
. 64
. 64
. 65
. 66
. 67
. 67
69
. 69
. 69
. 69
. 70
. 70
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
15.1.5 Exponentiation With Small Fractional Arguments .
.
15.1.6 Math Libraries .
.
.
.
15.1.7 Precision-related Compiler Flags .
.
.
15.2 Memory Instructions .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
16 Control Flow
16.1
16.2
Branching and Divergence .
.
Branch Predication .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
17 Deploying CUDA Applications
18 Understanding the Programming Environment
.
.
.
.
.
CUDA Compute Capability .
18.1
.
Additional Hardware Data .
18.2
18.3 Which Compute Capability Target .
.
18.4
CUDA Runtime .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
19.4
19.1
19.2
19.3
19 CUDA Compatibility Developer’s Guide
.
.
.
CUDA Toolkit Versioning .
.
Source Compatibility .
.
Binary Compatibility .
.
.
.
19.3.1 CUDA Binary (cubin) Compatibility .
.
.
.
.
CUDA Compatibility Across Minor Releases .
.
.
.
.
.
19.4.1 Existing CUDA Applications within Minor Versions of CUDA .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Recommendations for building a minor-version compatible library .
.
Recommendations for taking advantage of minor version compatibility in your
.
.
.
application .
19.4.1.1 Handling New CUDA Features and Driver APIs .
.
19.4.1.2 Using PTX .
.
.
.
.
19.4.1.3 Dynamic Code Generation .
19.4.1.4
19.4.1.5
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
20 Preparing for Deployment
.
.
.
20.1
20.2
20.3
20.4
.
.
Testing for CUDA Availability .
.
Error Handling .
.
.
.
.
Building for Maximum Compatibility .
Distributing the CUDA Runtime and Libraries .
.
.
.
.
.
.
.
20.4.1 CUDA Toolkit Library Redistribution .
20.4.1.1 Which Files to Redistribute .
.
.
20.4.1.2 Where to Install Redistributed CUDA Libraries .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
21.1
Nvidia-SMI
21 Deployment Infrastructure Tools
.
.
.
.
.
21.1.1 Queryable state .
21.1.2 Modifiable state .
.
.
.
.
.
.
.
.
NVML .
.
.
Cluster Management Tools .
.
Compiler JIT Cache Management Tools .
.
CUDA_VISIBLE_DEVICES .
21.2
21.3
21.4
21.5
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
22 Recommendations and Best Practices
22.1 Overall Performance Optimization Strategies .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
23 nvcc Compiler Switches
.
nvcc .
23.1
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 70
. 71
. 73
. 73
75
. 75
. 75
77
79
. 79
. 79
. 80
. 80
83
. 84
. 85
. 85
. 87
. 88
. 88
. 89
. 90
. 91
. 93
. 94
95
. 95
. 96
. 96
. 97
. 98
. 99
. 100
103
. 103
. 103
. 104
. 104
. 104
. 105
. 105
107
. 107
109
. 109
iii
24 Notices
Notice .
24.1
.
24.2 OpenCL .
24.3
.
.
Trademarks .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
111
. 111
. 112
. 112
iv
CUDA C++ Best Practices Guide, Release 12.5
CUDA C++ Best Practices Guide
The programming guide to using the CUDA Toolkit to obtain the best performance from NVIDIA GPUs.
Contents
1
CUDA C++ Best Practices Guide, Release 12.5
2
Contents
Chapter 1. What Is This Document?
This Best Practices Guide is a manual to help developers obtain the best performance from NVIDIA®
CUDA® GPUs. It presents established parallelization and optimization techniques and explains coding
metaphors and idioms that can greatly simplify programming for CUDA-capable GPU architectures.
While the contents can be used as a reference manual, you should be aware that some topics are revis-
ited in different contexts as various programming and configuration topics are explored. As a result,
it is recommended that first-time readers proceed through the guide sequentially. This approach will
greatly improve your understanding of effective programming practices and enable you to better use
the guide for reference later.
3
CUDA C++ Best Practices Guide, Release 12.5
4
Chapter 1. What Is This Document?
Chapter 2. Who Should Read This
Guide?
The discussions in this guide all use the C++ programming language, so you should be comfortable
reading C++ code.
This guide refers to and relies on several other documents that you should have at your disposal for
reference, all of which are available at no cost from the CUDA website https://docs.nvidia.com/cuda/.
The following documents are especially important resources:
▶ CUDA Installation Guide
▶ CUDA C++ Programming Guide
▶ CUDA Toolkit Reference Manual
In particular, the optimization section of this guide assumes that you have already successfully down-
loaded and installed the CUDA Toolkit (if not, please refer to the relevant CUDA Installation Guide for
your platform) and that you have a basic familiarity with the CUDA C++ programming language and
environment (if not, please refer to the CUDA C++ Programming Guide).
5
CUDA C++ Best Practices Guide, Release 12.5
6
Chapter 2. Who Should Read This Guide?
Chapter 3. Assess, Parallelize, Optimize,
Deploy
This guide introduces the Assess, Parallelize, Optimize, Deploy(APOD) design cycle for applications with
the goal of helping application developers to rapidly identify the portions of their code that would most
readily benefit from GPU acceleration, rapidly realize that benefit, and begin leveraging the resulting
speedups in production as early as possible.
APOD is a cyclical process: initial speedups can be achieved, tested, and deployed with only minimal
initial investment of time, at which point the cycle can begin again by identifying further optimiza-
tion opportunities, seeing additional speedups, and then deploying the even faster versions of the
application into production.
7
CUDA C++ Best Practices Guide, Release 12.5
3.1. Assess
For an existing project, the first step is to assess the application to locate the parts of the code that
are responsible for the bulk of the execution time. Armed with this knowledge, the developer can
evaluate these bottlenecks for parallelization and start to investigate GPU acceleration.
By understanding the end-user’s requirements and constraints and by applying Amdahl’s and
Gustafson’s laws, the developer can determine the upper bound of performance improvement from
acceleration of the identified portions of the application.
3.2. Parallelize
Having identified the hotspots and having done the basic exercises to set goals and expectations, the
developer needs to parallelize the code. Depending on the original code, this can be as simple as calling
into an existing GPU-optimized library such as cuBLAS, cuFFT, or Thrust, or it could be as simple as
adding a few preprocessor directives as hints to a parallelizing compiler.
On the other hand, some applications’ designs will require some amount of refactoring to expose their
inherent parallelism. As even CPU architectures will require exposing parallelism in order to improve or
simply maintain the performance of sequential applications, the CUDA family of parallel programming
languages (CUDA C++, CUDA Fortran, etc.) aims to make the expression of this parallelism as simple
as possible, while simultaneously enabling operation on CUDA-capable GPUs designed for maximum
parallel throughput.
3.3. Optimize
After each round of application parallelization is complete, the developer can move to optimizing the
implementation to improve performance. Since there are many possible optimizations that can be
considered, having a good understanding of the needs of the application can help to make the pro-
cess as smooth as possible. However, as with APOD as a whole, program optimization is an iterative
process (identify an opportunity for optimization, apply and test the optimization, verify the speedup
achieved, and repeat), meaning that it is not necessary for a programmer to spend large amounts of
In-
time memorizing the bulk of all possible optimization strategies prior to seeing good speedups.
stead, strategies can be applied incrementally as they are learned.
Optimizations can be applied at various levels, from overlapping data transfers with computation all the
way down to fine-tuning floating-point operation sequences. The available profiling tools are invaluable
for guiding this process, as they can help suggest a next-best course of action for the developer’s
optimization efforts and provide references into the relevant portions of the optimization section of
this guide.
8
Chapter 3. Assess, Parallelize, Optimize, Deploy
CUDA C++ Best Practices Guide, Release 12.5
3.4. Deploy
Having completed the GPU acceleration of one or more components of the application it is possible
to compare the outcome with the original expectation. Recall that the initial assess step allowed the
developer to determine an upper bound for the potential speedup attainable by accelerating given
hotspots.
Before tackling other hotspots to improve the total speedup, the developer should consider taking
the partially parallelized implementation and carry it through to production. This is important for a
number of reasons; for example, it allows the user to profit from their investment as early as possible
(the speedup may be partial but is still valuable), and it minimizes risk for the developer and the user
by providing an evolutionary rather than revolutionary set of changes to the application.
3.4. Deploy
9
CUDA C++ Best Practices Guide, Release 12.5
10
Chapter 3. Assess, Parallelize, Optimize, Deploy
Chapter 4. Recommendations and Best
Practices
Throughout this guide, specific recommendations are made regarding the design and implementation
of CUDA C++ code. These recommendations are categorized by priority, which is a blend of the effect
of the recommendation and its scope. Actions that present substantial improvements for most CUDA
applications have the highest priority, while small optimizations that affect only very specific situations
are given a lower priority.
Before implementing lower priority recommendations, it is good practice to make sure all higher pri-
ority recommendations that are relevant have already been applied. This approach will tend to provide
the best results for the time invested and will avoid the trap of premature optimization.
The criteria of benefit and scope for establishing priority will vary depending on the nature of the
program. In this guide, they represent a typical case. Your code might reflect different priority factors.
Regardless of this possibility, it is good practice to verify that no higher-priority recommendations
have been overlooked before undertaking lower-priority items.
Note: Code samples throughout the guide omit error checking for conciseness. Production code
should, however, systematically check the error code returned by each API call and check for failures
in kernel launches by calling cudaGetLastError().
11
CUDA C++ Best Practices Guide, Release 12.5
12
Chapter 4. Recommendations and Best Practices
Chapter 5. Assessing Your Application
From supercomputers to mobile phones, modern processors increasingly rely on parallelism to provide
performance. The core computational unit, which includes control, arithmetic, registers and typically
some cache, is replicated some number of times and connected to memory via a network. As a result,
all modern processors require parallel code in order to achieve good utilization of their computational
power.
While processors are evolving to expose more fine-grained parallelism to the programmer, many ex-
isting applications have evolved either as serial codes or as coarse-grained parallel codes (for example,
where the data is decomposed into regions processed in parallel, with sub-regions shared using MPI).
In order to profit from any modern processor architecture, GPUs included, the first steps are to assess
the application to identify the hotspots, determine whether they can be parallelized, and understand
the relevant workloads both now and in the future.
13
CUDA C++ Best Practices Guide, Release 12.5
14
Chapter 5. Assessing Your Application
Chapter 6. Heterogeneous Computing
CUDA programming involves running code on two different platforms concurrently: a host system with
one or more CPUs and one or more CUDA-enabled NVIDIA GPU devices.
While NVIDIA GPUs are frequently associated with graphics, they are also powerful arithmetic engines
capable of running thousands of lightweight threads in parallel. This capability makes them well suited
to computations that can leverage parallel execution.
However, the device is based on a distinctly different design from the host system, and it’s important
to understand those differences and how they determine the performance of CUDA applications in
order to use CUDA effectively.
6.1. Differences between Host and Device
The primary differences are in threading model and in separate physical memories:
Threading resources
Execution pipelines on host systems can support a limited number of concurrent threads. For ex-
ample, servers that have two 32 core processors can run only 64 threads concurrently (or small
multiple of that if the CPUs support simultaneous multithreading). By comparison, the small-
est executable unit of parallelism on a CUDA device comprises 32 threads (termed a warp of
threads). Modern NVIDIA GPUs can support up to 2048 active threads concurrently per multi-
processor (see Features and Specifications of the CUDA C++ Programming Guide) On GPUs with
80 multiprocessors, this leads to more than 160,000 concurrently active threads.
Threads
Threads on a CPU are generally heavyweight entities. The operating system must swap threads
on and off CPU execution channels to provide multithreading capability. Context switches (when
two threads are swapped) are therefore slow and expensive. By comparison, threads on GPUs
In a typical system, thousands of threads are queued up for work
are extremely lightweight.
(in warps of 32 threads each).
If the GPU must wait on one warp of threads, it simply begins
executing work on another. Because separate registers are allocated to all active threads, no
swapping of registers or other state need occur when switching among GPU threads. Resources
stay allocated to each thread until it completes its execution. In short, CPU cores are designed
to minimize latency for a small number of threads at a time each, whereas GPUs are designed to
handle a large number of concurrent, lightweight threads in order to maximize throughput.
RAM
The host system and the device each have their own distinct attached physical memories1. As
the host and device memories are separated, items in the host memory must occasionally be
1 On Systems on a Chip with integrated GPUs, such as NVIDIA® Tegra®, host and device memory are physically the same, but
there is still a logical distinction between host and device memory. See the Application Note on CUDA for Tegra for details.
15
CUDA C++ Best Practices Guide, Release 12.5
communicated between device memory and host memory as described in What Runs on a CUDA-
Enabled Device?.
These are the primary hardware differences between CPU hosts and GPU devices with respect to par-
allel programming. Other differences are discussed as they arise elsewhere in this document. Applica-
tions composed with these differences in mind can treat the host and device together as a cohesive
heterogeneous system wherein each processing unit is leveraged to do the kind of work it does best:
sequential work on the host and parallel work on the device.
6.2. What Runs on a CUDA-Enabled Device?
The following issues should be considered when determining what parts of an application to run on
the device:
▶ The device is ideally suited for computations that can be run on numerous data elements si-
multaneously in parallel. This typically involves arithmetic on large data sets (such as matrices)
where the same operation can be performed across thousands, if not millions, of elements at
the same time. This is a requirement for good performance on CUDA: the software must use a
large number (generally thousands or tens of thousands) of concurrent threads. The support for
running numerous threads in parallel derives from CUDA’s use of a lightweight threading model
described above.
▶ To use CUDA, data values must be transferred from the host to the device. These transfers are
costly in terms of performance and should be minimized. (See Data Transfer Between Host and
Device.) This cost has several ramifications:
▶ The complexity of operations should justify the cost of moving data to and from the device.
Code that transfers data for brief use by a small number of threads will see little or no per-
formance benefit. The ideal scenario is one in which many threads perform a substantial
amount of work.
For example, transferring two matrices to the device to perform a matrix addition and then
transferring the results back to the host will not realize much performance benefit. The
issue here is the number of operations performed per data element transferred. For the
preceding procedure, assuming matrices of size NxN, there are N2 operations (additions) and
3N2 elements transferred, so the ratio of operations to elements transferred is 1:3 or O(1).
Performance benefits can be more readily achieved when this ratio is higher. For example, a
matrix multiplication of the same matrices requires N3 operations (multiply-add), so the ratio
of operations to elements transferred is O(N), in which case the larger the matrix the greater
the performance benefit. The types of operations are an additional factor, as additions have
different complexity profiles than, for example, trigonometric functions. It is important to
include the overhead of transferring data to and from the device in determining whether
operations should be performed on the host or on the device.
▶ Data should be kept on the device as long as possible. Because transfers should be mini-
mized, programs that run multiple kernels on the same data should favor leaving the data
on the device between kernel calls, rather than transferring intermediate results to the host
and then sending them back to the device for subsequent calculations. So, in the previous
example, had the two matrices to be added already been on the device as a result of some
previous calculation, or if the results of the addition would be used in some subsequent
calculation, the matrix addition should be performed locally on the device. This approach
should be used even if one of the steps in a sequence of calculations could be performed
faster on the host. Even a relatively slow kernel may be advantageous if it avoids one or
more transfers between host and device memory. Data Transfer Between Host and Device
16
Chapter 6. Heterogeneous Computing
CUDA C++ Best Practices Guide, Release 12.5
provides further details, including the measurements of bandwidth between the host and
the device versus within the device proper.
▶ For best performance, there should be some coherence in memory access by adjacent threads
running on the device. Certain memory access patterns enable the hardware to coalesce groups
of reads or writes of multiple data items into one operation. Data that cannot be laid out so as to
enable coalescing, or that doesn’t have enough locality to use the L1 or texture caches effectively,
will tend to see lesser speedups when used in computations on GPUs. A noteworthy exception
to this are completely random memory access patterns. In general, they should be avoided, be-
cause compared to peak capabilities any architecture processes these memory access patterns
at a low efficiency. However, compared to cache based architectures, like CPUs, latency hiding
architectures, like GPUs, tend to cope better with completely random memory access patterns.
6.2. What Runs on a CUDA-Enabled Device?
17
CUDA C++ Best Practices Guide, Release 12.5
18
Chapter 6. Heterogeneous Computing
Chapter 7. Application Profiling
7.1. Profile
Many codes accomplish a significant portion of the work with a relatively small amount of code. Us-
ing a profiler, the developer can identify such hotspots and start to compile a list of candidates for
parallelization.
7.1.1. Creating the Profile
There are many possible approaches to profiling the code, but in all cases the objective is the same:
to identify the function or functions in which the application is spending most of its execution time.
Note: High Priority: To maximize developer productivity, profile the application to determine hotspots
and bottlenecks.
The most important consideration with any profiling activity is to ensure that the workload is realistic
- i.e., that information gained from the test and decisions based upon that information are relevant
to real data. Using unrealistic workloads can lead to sub-optimal results and wasted effort both by
causing developers to optimize for unrealistic problem sizes and by causing developers to concentrate
on the wrong functions.
There are a number of tools that can be used to generate the profile. The following example is based
on gprof, which is an open-source profiler for Linux platforms from the GNU Binutils collection.
$ gcc -O2 -g -pg myprog.c
$ gprof .∕a.out > profile.txt
Each sample counts as 0.01 seconds.
%
time
33.34
16.67
16.67
16.67
16.67
0.00
0.00
0.00
0.00
0.00
cumulative
seconds
0.02
0.03
0.04
0.05
0.06
0.06
0.06
0.06
0.06
0.06
self
seconds
0.02
0.01
0.01
0.01
0.01
0.00
0.00
0.00
0.00
0.00
calls
7208
240
8
7
236
192
47
45
1
self
total
ms∕call ms∕call
0.00
0.12
1.25
1.43
0.00
0.04
1.25
1.43
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
0.00
50.00
name
genTimeStep
calcStats
calcSummaryData
write
mcount
tzset
tolower
strlen
strchr
main
(continues on next page)
19
CUDA C++ Best Practices Guide, Release 12.5
0.00
0.00
0.00
0.00
0.06
0.06
0.06
0.06
0.00
0.00
0.00
0.00
1
1
1
1
0.00
0.00
0.00
0.00
0.00
10.11
0.00
50.00
memcpy
print
profil
report
(continued from previous page)
7.1.2. Identifying Hotspots
In the example above, we can clearly see that the function genTimeStep() takes one-third of the
total running time of the application. This should be our first candidate function for parallelization.
Understanding Scaling discusses the potential benefit we might expect from such parallelization.
It is worth noting that several of the other functions in the above example also take up a significant por-
tion of the overall running time, such as calcStats() and calcSummaryData(). Parallelizing these
functions as well should increase our speedup potential. However, since APOD is a cyclical process,
we might opt to parallelize these functions in a subsequent APOD pass, thereby limiting the scope of
our work in any given pass to a smaller set of incremental changes.
7.1.3. Understanding Scaling
The amount of performance benefit an application will realize by running on CUDA depends entirely
on the extent to which it can be parallelized. Code that cannot be sufficiently parallelized should run
on the host, unless doing so would result in excessive transfers between the host and the device.
Note: High Priority: To get the maximum benefit from CUDA, focus first on finding ways to parallelize
sequential code.
By understanding how applications can scale it is possible to set expectations and plan an incremental
parallelization strategy. Strong Scaling and Amdahl’s Law describes strong scaling, which allows us to
set an upper bound for the speedup with a fixed problem size. Weak Scaling and Gustafson’s Law de-
scribes weak scaling, where the speedup is attained by growing the problem size. In many applications,
a combination of strong and weak scaling is desirable.
7.1.3.1 Strong Scaling and Amdahl’s Law
Strong scaling is a measure of how, for a fixed overall problem size, the time to solution decreases
as more processors are added to a system. An application that exhibits linear strong scaling has a
speedup equal to the number of processors used.
Strong scaling is usually equated with Amdahl’s Law, which specifies the maximum speedup that can
be expected by parallelizing portions of a serial program. Essentially, it states that the maximum
speedup S of a program is:
S =
1
(1−P )+ P
N
Here P is the fraction of the total serial execution time taken by the portion of code that can be par-
allelized and N is the number of processors over which the parallel portion of the code runs.
The larger N is(that is, the greater the number of processors), the smaller the P/N fraction. It can be
simpler to view N as a very large number, which essentially transforms the equation into S = 1/(1 − P ).
20
Chapter 7. Application Profiling
CUDA C++ Best Practices Guide, Release 12.5
Now, if 3/4 of the running time of a sequential program is parallelized, the maximum speedup over
serial code is 1 / (1 - 3/4) = 4.
In reality, most applications do not exhibit perfectly linear strong scaling, even if they do exhibit some
degree of strong scaling. For most purposes, the key point is that the larger the parallelizable portion
P is, the greater the potential speedup. Conversely, if P is a small number (meaning that the applica-
tion is not substantially parallelizable), increasing the number of processors N does little to improve
performance. Therefore, to get the largest speedup for a fixed problem size, it is worthwhile to spend
effort on increasing P, maximizing the amount of code that can be parallelized.
7.1.3.2 Weak Scaling and Gustafson’s Law
Weak scaling is a measure of how the time to solution changes as more processors are added to a
system with a fixed problem size per processor; i.e., where the overall problem size increases as the
number of processors is increased.
Weak scaling is often equated with Gustafson’s Law, which states that in practice, the problem size
scales with the number of processors. Because of this, the maximum speedup S of a program is:
S = N + (1 − P )(1 − N )
Here P is the fraction of the total serial execution time taken by the portion of code that can be par-
allelized and N is the number of processors over which the parallel portion of the code runs.
Another way of looking at Gustafson’s Law is that it is not the problem size that remains constant
as we scale up the system but rather the execution time. Note that Gustafson’s Law assumes that
the ratio of serial to parallel execution remains constant, reflecting additional cost in setting up and
handling the larger problem.
7.1.3.3 Applying Strong and Weak Scaling
Understanding which type of scaling is most applicable to an application is an important part of esti-
mating speedup. For some applications the problem size will remain constant and hence only strong
scaling is applicable. An example would be modeling how two molecules interact with each other,
where the molecule sizes are fixed.
For other applications, the problem size will grow to fill the available processors. Examples include
modeling fluids or structures as meshes or grids and some Monte Carlo simulations, where increasing
the problem size provides increased accuracy.
Having understood the application profile, the developer should understand how the problem
size would change if the computational performance changes and then apply either Amdahl’s or
Gustafson’s Law to determine an upper bound for the speedup.
7.1. Profile
21
CUDA C++ Best Practices Guide, Release 12.5
22
Chapter 7. Application Profiling
Chapter 8. Parallelizing Your Application
Having identified the hotspots and having done the basic exercises to set goals and expectations, the
developer needs to parallelize the code. Depending on the original code, this can be as simple as calling
into an existing GPU-optimized library such as cuBLAS, cuFFT, or Thrust, or it could be as simple as
adding a few preprocessor directives as hints to a parallelizing compiler.
On the other hand, some applications’ designs will require some amount of refactoring to expose their
inherent parallelism. As even CPU architectures require exposing this parallelism in order to improve or
simply maintain the performance of sequential applications, the CUDA family of parallel programming
languages (CUDA C++, CUDA Fortran, etc.) aims to make the expression of this parallelism as simple
as possible, while simultaneously enabling operation on CUDA-capable GPUs designed for maximum
parallel throughput.
23
CUDA C++ Best Practices Guide, Release 12.5
24
Chapter 8. Parallelizing Your Application
Chapter 9. Getting Started
There are several key strategies for parallelizing sequential code. While the details of how to apply
these strategies to a particular application is a complex and problem-specific topic, the general themes
listed here apply regardless of whether we are parallelizing code to run on for multicore CPUs or for
use on CUDA GPUs.
9.1. Parallel Libraries
The most straightforward approach to parallelizing an application is to leverage existing libraries that
take advantage of parallel architectures on our behalf. The CUDA Toolkit includes a number of such
libraries that have been fine-tuned for NVIDIA CUDA GPUs, such as cuBLAS, cuFFT, and so on.
The key here is that libraries are most useful when they match well with the needs of the application.
Applications already using other BLAS libraries can often quite easily switch to cuBLAS, for example,
whereas applications that do little to no linear algebra will have little use for cuBLAS. The same goes
for other CUDA Toolkit libraries: cuFFT has an interface similar to that of FFTW, etc.
Also of note is the Thrust library, which is a parallel C++ template library similar to the C++ Standard
Template Library. Thrust provides a rich collection of data parallel primitives such as scan, sort, and
reduce, which can be composed together to implement complex algorithms with concise, readable
source code. By describing your computation in terms of these high-level abstractions you provide
Thrust with the freedom to select the most efficient implementation automatically. As a result, Thrust
can be utilized in rapid prototyping of CUDA applications, where programmer productivity matters
most, as well as in production, where robustness and absolute performance are crucial.
9.2. Parallelizing Compilers
Another common approach to parallelization of sequential codes is to make use of parallelizing compil-
ers. Often this means the use of directives-based approaches, where the programmer uses a pragma
or other similar notation to provide hints to the compiler about where parallelism can be found with-
out needing to modify or adapt the underlying code itself. By exposing parallelism to the compiler,
directives allow the compiler to do the detailed work of mapping the computation onto the parallel
architecture.
The OpenACC standard provides a set of compiler directives to specify loops and regions of code in
standard C, C++ and Fortran that should be offloaded from a host CPU to an attached accelerator such
as a CUDA GPU. The details of managing the accelerator device are handled implicitly by an OpenACC-
enabled compiler and runtime.
25
CUDA C++ Best Practices Guide, Release 12.5
See http://www.openacc.org/ for details.
9.3. Coding to Expose Parallelism
For applications that need additional functionality or performance beyond what existing parallel li-
braries or parallelizing compilers can provide, parallel programming languages such as CUDA C++ that
integrate seamlessly with existing sequential code are essential.
Once we have located a hotspot in our application’s profile assessment and determined that custom
code is the best approach, we can use CUDA C++ to expose the parallelism in that portion of our
code as a CUDA kernel. We can then launch this kernel onto the GPU and retrieve the results without
requiring major rewrites to the rest of our application.
This approach is most straightforward when the majority of the total running time of our application
is spent in a few relatively isolated portions of the code. More difficult to parallelize are applications
with a very flat profile - i.e., applications where the time spent is spread out relatively evenly across a
wide portion of the code base. For the latter variety of application, some degree of code refactoring
to expose the inherent parallelism in the application might be necessary, but keep in mind that this
refactoring work will tend to benefit all future architectures, CPU and GPU alike, so it is well worth the
effort should it become necessary.
26
Chapter 9. Getting Started
Chapter 10. Getting the Right Answer
Obtaining the right answer is clearly the principal goal of all computation. On parallel systems, it is
possible to run into difficulties not typically found in traditional serial-oriented programming. These
include threading issues, unexpected values due to the way floating-point values are computed, and
challenges arising from differences in the way CPU and GPU processors operate. This chapter exam-
ines issues that can affect the correctness of returned data and points to appropriate solutions.
10.1. Verification
10.1.1. Reference Comparison
A key aspect of correctness verification for modifications to any existing program is to establish some
mechanism whereby previous known-good reference outputs from representative inputs can be com-
pared to new results. After each change is made, ensure that the results match using whatever criteria
apply to the particular algorithm. Some will expect bitwise identical results, which is not always pos-
sible, especially where floating-point arithmetic is concerned; see Numerical Accuracy and Precision
regarding numerical accuracy. For other algorithms, implementations may be considered correct if
they match the reference within some small epsilon.
Note that the process used for validating numerical results can easily be extended to validate perfor-
mance results as well. We want to ensure that each change we make is correct and that it improves
performance (and by how much). Checking these things frequently as an integral part of our cyclical
APOD process will help ensure that we achieve the desired results as rapidly as possible.
10.1.2. Unit Testing
A useful counterpart to the reference comparisons described above is to structure the code itself
in such a way that is readily verifiable at the unit level. For example, we can write our CUDA kernels
as a collection of many short __device__ functions rather than one large monolithic __global__
function; each device function can be tested independently before hooking them all together.
For example, many kernels have complex addressing logic for accessing memory in addition to their
actual computation.
If we validate our addressing logic separately prior to introducing the bulk of
the computation, then this will simplify any later debugging efforts. (Note that the CUDA compiler
considers any device code that does not contribute to a write to global memory as dead code subject
to elimination, so we must at least write something out to global memory as a result of our addressing
logic in order to successfully apply this strategy.)
27
CUDA C++ Best Practices Guide, Release 12.5
Going a step further, if most functions are defined as __host__ __device__ rather than just __de-
vice__ functions, then these functions can be tested on both the CPU and the GPU, thereby increas-
ing our confidence that the function is correct and that there will not be any unexpected differences
in the results. If there are differences, then those differences will be seen early and can be understood
in the context of a simple function.
As a useful side effect, this strategy will allow us a means to reduce code duplication should we wish
to include both CPU and GPU execution paths in our application: if the bulk of the work of our CUDA
kernels is done in __host__ __device__ functions, we can easily call those functions from both the
host code and the device code without duplication.
10.2. Debugging
CUDA-GDB is a port of the GNU Debugger that runs on Linux and Mac; see: https://developer.nvidia.
com/cuda-gdb.
The NVIDIA Nsight Visual Studio Edition for Microsoft Windows 7, Windows HPC Server 2008, Windows
8.1, and Windows 10 is available as a free plugin for Microsoft Visual Studio; see: https://developer.
nvidia.com/nsight-visual-studio-edition.
Several third-party debuggers support CUDA debugging as well; see: https://developer.nvidia.com/
debugging-solutions for more details.
10.3. Numerical Accuracy and Precision
Incorrect or unexpected results arise principally from issues of floating-point accuracy due to the way
floating-point values are computed and stored. The following sections explain the principal items of
interest. Other peculiarities of floating-point arithmetic are presented in Features and Technical Spec-
ifications of the CUDA C++ Programming Guide as well as in a whitepaper and accompanying webi-
nar on floating-point precision and performance available from https://developer.nvidia.com/content/
precision-performance-floating-point-and-ieee-754-compliance-nvidia-gpus.
10.3.1. Single vs. Double Precision
Devices of compute capability 1.3 and higher provide native support for double-precision floating-
point values (that is, values 64 bits wide). Results obtained using double-precision arithmetic will fre-
quently differ from the same operation performed via single-precision arithmetic due to the greater
precision of the former and due to rounding issues. Therefore, it is important to be sure to compare
values of like precision and to express the results within a certain tolerance rather than expecting
them to be exact.
28
Chapter 10. Getting the Right Answer
CUDA C++ Best Practices Guide, Release 12.5
10.3.2. Floating Point Math Is not Associative
Each floating-point arithmetic operation involves a certain amount of rounding. Consequently, the
order in which arithmetic operations are performed is important.
If A, B, and C are floating-point
values, (A+B)+C is not guaranteed to equal A+(B+C) as it is in symbolic math. When you parallelize
computations, you potentially change the order of operations and therefore the parallel results might
not match sequential results. This limitation is not specific to CUDA, but an inherent part of parallel
computation on floating-point values.
10.3.3. IEEE 754 Compliance
All CUDA compute devices follow the IEEE 754 standard for binary floating-point representation, with
some small exceptions. These exceptions, which are detailed in Features and Technical Specifications
of the CUDA C++ Programming Guide, can lead to results that differ from IEEE 754 values computed
on the host system.
One of the key differences is the fused multiply-add (FMA) instruction, which combines multiply-add
operations into a single instruction execution. Its result will often differ slightly from results obtained
by doing the two operations separately.
10.3.4. x86 80-bit Computations
x86 processors can use an 80-bit double extended precision math when performing floating-point cal-
culations. The results of these calculations can frequently differ from pure 64-bit operations per-
formed on the CUDA device. To get a closer match between values, set the x86 host processor to use
regular double or single precision (64 bits and 32 bits, respectively). This is done with the FLDCW x86
assembly instruction or the equivalent operating system API.
10.3. Numerical Accuracy and Precision
29
CUDA C++ Best Practices Guide, Release 12.5
30
Chapter 10. Getting the Right Answer
Chapter 11. Optimizing CUDA
Applications
After each round of application parallelization is complete, the developer can move to optimizing the
implementation to improve performance. Since there are many possible optimizations that can be
considered, having a good understanding of the needs of the application can help to make the pro-
cess as smooth as possible. However, as with APOD as a whole, program optimization is an iterative
process (identify an opportunity for optimization, apply and test the optimization, verify the speedup
achieved, and repeat), meaning that it is not necessary for a programmer to spend large amounts of
In-
time memorizing the bulk of all possible optimization strategies prior to seeing good speedups.
stead, strategies can be applied incrementally as they are learned.
Optimizations can be applied at various levels, from overlapping data transfers with computation all the
way down to fine-tuning floating-point operation sequences. The available profiling tools are invaluable
for guiding this process, as they can help suggest a next-best course of action for the developer’s
optimization efforts and provide references into the relevant portions of the optimization section of
this guide.
31
CUDA C++ Best Practices Guide, Release 12.5
32
Chapter 11. Optimizing CUDA Applications
Chapter 12. Performance Metrics
When attempting to optimize CUDA code, it pays to know how to measure performance accurately and
to understand the role that bandwidth plays in performance measurement. This chapter discusses
how to correctly measure performance using CPU timers and CUDA events.
It then explores how
bandwidth affects performance metrics and how to mitigate some of the challenges it poses.
12.1. Timing
CUDA calls and kernel executions can be timed using either CPU or GPU timers. This section examines
the functionality, advantages, and pitfalls of both approaches.
12.1.1. Using CPU Timers
Any CPU timer can be used to measure the elapsed time of a CUDA call or kernel execution. The
details of various CPU timing approaches are outside the scope of this document, but developers
should always be aware of the resolution their timing calls provide.
When using CPU timers, it is critical to remember that many CUDA API functions are asynchronous;
that is, they return control back to the calling CPU thread prior to completing their work. All ker-
nel launches are asynchronous, as are memory-copy functions with the Async suffix on their names.
Therefore, to accurately measure the elapsed time for a particular call or sequence of CUDA calls, it
is necessary to synchronize the CPU thread with the GPU by calling cudaDeviceSynchronize() im-
mediately before starting and stopping the CPU timer. cudaDeviceSynchronize()blocks the calling
CPU thread until all CUDA calls previously issued by the thread are completed.
Although it is also possible to synchronize the CPU thread with a particular stream or event on the
GPU, these synchronization functions are not suitable for timing code in streams other than the default
stream. cudaStreamSynchronize() blocks the CPU thread until all CUDA calls previously issued into
the given stream have completed. cudaEventSynchronize() blocks until a given event in a particular
stream has been recorded by the GPU. Because the driver may interleave execution of CUDA calls from
other non-default streams, calls in other streams may be included in the timing.
Because the default stream, stream 0, exhibits serializing behavior for work on the device (an operation
in the default stream can begin only after all preceding calls in any stream have completed; and no
subsequent operation in any stream can begin until it finishes), these functions can be used reliably
for timing in the default stream.
Be aware that CPU-to-GPU synchronization points such as those mentioned in this section imply a
stall in the GPU’s processing pipeline and should thus be used sparingly to minimize their performance
33
CUDA C++ Best Practices Guide, Release 12.5
impact.
12.1.2. Using CUDA GPU Timers
The CUDA event API provides calls that create and destroy events, record events (including a times-
tamp), and convert timestamp differences into a floating-point value in milliseconds. How to time
code using CUDA events illustrates their use.
How to time code using CUDA events
cudaEvent_t start, stop;
float time;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord( start, 0 );
kernel<<<grid,threads>>> ( d_odata, d_idata, size_x, size_y,
cudaEventRecord( stop, 0 );
cudaEventSynchronize( stop );
NUM_REPS);
cudaEventElapsedTime( &time, start, stop );
cudaEventDestroy( start );
cudaEventDestroy( stop );
Here cudaEventRecord() is used to place the start and stop events into the default stream, stream
0. The device will record a timestamp for the event when it reaches that event in the stream. The
cudaEventElapsedTime() function returns the time elapsed between the recording of the start
and stop events. This value is expressed in milliseconds and has a resolution of approximately half a
microsecond. Like the other calls in this listing, their specific operation, parameters, and return values
are described in the CUDA Toolkit Reference Manual. Note that the timings are measured on the GPU
clock, so the timing resolution is operating-system-independent.
12.2. Bandwidth
Bandwidth - the rate at which data can be transferred - is one of the most important gating factors for
performance. Almost all changes to code should be made in the context of how they affect bandwidth.
As described in Memory Optimizations of this guide, bandwidth can be dramatically affected by the
choice of memory in which data is stored, how the data is laid out and the order in which it is accessed,
as well as other factors.
To measure performance accurately, it is useful to calculate theoretical and effective bandwidth. When
the latter is much lower than the former, design or implementation details are likely to reduce band-
width, and it should be the primary goal of subsequent optimization efforts to increase it.
Note: High Priority: Use the effective bandwidth of your computation as a metric when measuring
performance and optimization benefits.
34
Chapter 12. Performance Metrics
CUDA C++ Best Practices Guide, Release 12.5
12.2.1. Theoretical Bandwidth Calculation
Theoretical bandwidth can be calculated using hardware specifications available in the product liter-
ature. For example, the NVIDIA Tesla V100 uses HBM2 (double data rate) RAM with a memory clock
rate of 877 MHz and a 4096-bit-wide memory interface.
Using these data items, the peak theoretical memory bandwidth of the NVIDIA Tesla V100 is 898 GB/s:
(
)
0.877 × 109 × (4096/8) × 2
÷ 109 = 898GB/s
In this calculation, the memory clock rate is converted in to Hz, multiplied by the interface width (di-
vided by 8, to convert bits to bytes) and multiplied by 2 due to the double data rate. Finally, this product
is divided by 109 to convert the result to GB/s.
Note: Some calculations use 10243 instead of 109 for the final calculation. In such a case, the band-
width would be 836.4 GiB/s. It is important to use the same divisor when calculating theoretical and
effective bandwidth so that the comparison is valid.
Note: On GPUs with GDDR memory with ECC enabled the available DRAM is reduced by 6.25% to
allow for the storage of ECC bits. Fetching ECC bits for each memory transaction also reduced the
effective bandwidth by approximately 20% compared to the same GPU with ECC disabled, though
the exact impact of ECC on bandwidth can be higher and depends on the memory access pattern.
HBM2 memories, on the other hand, provide dedicated ECC resources, allowing overhead-free ECC
protection.2
12.2.2. Effective Bandwidth Calculation
Effective bandwidth is calculated by timing specific program activities and by knowing how data is
accessed by the program. To do so, use this equation:
Effective bandwidth =
(Br + Bw) ÷ 109
÷ time
(
)
Here, the effective bandwidth is in units of GB/s, Br is the number of bytes read per kernel, Bw is the
number of bytes written per kernel, and time is given in seconds.
For example, to compute the effective bandwidth of a 2048 x 2048 matrix copy, the following formula
could be used:
Effective bandwidth =
((
)
20482 × 4 × 2
)
÷ 109
÷ time
The number of elements is multiplied by the size of each element (4 bytes for a float), multiplied by 2
(because of the read and write), divided by 109 (or 1,0243) to obtain GB of memory transferred. This
number is divided by the time in seconds to obtain GB/s.
2 As an exception, scattered writes to HBM2 see some overhead from ECC but much less than the overhead with similar
access patterns on ECC-protected GDDR5 memory.
12.2. Bandwidth
35
CUDA C++ Best Practices Guide, Release 12.5
12.2.3. Throughput Reported by Visual Profiler
For devices with compute capability of 2.0 or greater, the Visual Profiler can be used to collect several
different memory throughput measures. The following throughput metrics can be displayed in the
Details or Detail Graphs view:
▶ Requested Global Load Throughput
▶ Requested Global Store Throughput
▶ Global Load Throughput
▶ Global Store Throughput
▶ DRAM Read Throughput
▶ DRAM Write Throughput
The Requested Global Load Throughput and Requested Global Store Throughput values indicate the
global memory throughput requested by the kernel and therefore correspond to the effective band-
width obtained by the calculation shown under Effective Bandwidth Calculation.
Because the minimum memory transaction size is larger than most word sizes, the actual memory
throughput required for a kernel can include the transfer of data not used by the kernel. For global
memory accesses, this actual throughput is reported by the Global Load Throughput and Global Store
Throughput values.
It’s important to note that both numbers are useful. The actual memory throughput shows how close
the code is to the hardware limit, and a comparison of the effective or requested bandwidth to the
actual bandwidth presents a good estimate of how much bandwidth is wasted by suboptimal coalesc-
ing of memory accesses (see Coalesced Access to Global Memory). For global memory accesses, this
comparison of requested memory bandwidth to actual memory bandwidth is reported by the Global
Memory Load Efficiency and Global Memory Store Efficiency metrics.
36
Chapter 12. Performance Metrics
Chapter 13. Memory Optimizations
Memory optimizations are the most important area for performance. The goal is to maximize the use
of the hardware by maximizing bandwidth. Bandwidth is best served by using as much fast memory
and as little slow-access memory as possible. This chapter discusses the various kinds of memory on
the host and device and how best to set up data items to use the memory effectively.
13.1. Data Transfer Between Host and Device
The peak theoretical bandwidth between the device memory and the GPU is much higher (898 GB/s
on the NVIDIA Tesla V100, for example) than the peak theoretical bandwidth between host memory
and device memory (16 GB/s on the PCIe x16 Gen3). Hence, for best overall application performance,
it is important to minimize data transfer between the host and the device, even if that means running
kernels on the GPU that do not demonstrate any speedup compared with running them on the host
CPU.
Note: High Priority: Minimize data transfer between the host and the device, even if it means running
some kernels on the device that do not show performance gains when compared with running them
on the host CPU.
Intermediate data structures should be created in device memory, operated on by the device, and
destroyed without ever being mapped by the host or copied to host memory.
Also, because of the overhead associated with each transfer, batching many small transfers into one
larger transfer performs significantly better than making each transfer separately, even if doing so
requires packing non-contiguous regions of memory into a contiguous buffer and then unpacking
after the transfer.
Finally, higher bandwidth between the host and the device is achieved when using page-locked (or
pinned) memory, as discussed in the CUDA C++ Programming Guide and the Pinned Memory section
of this document.
37
CUDA C++ Best Practices Guide, Release 12.5
13.1.1. Pinned Memory
Page-locked or pinned memory transfers attain the highest bandwidth between the host and the
device. On PCIe x16 Gen3 cards, for example, pinned memory can attain roughly 12 GB/s transfer
rates.
Pinned memory is allocated using the cudaHostAlloc() functions in the Runtime API. The band-
widthTest CUDA Sample shows how to use these functions as well as how to measure memory trans-
fer performance.
For regions of system memory that have already been pre-allocated, cudaHostRegister() can be
used to pin the memory on-the-fly without the need to allocate a separate buffer and copy the data
into it.
Pinned memory should not be overused. Excessive use can reduce overall system performance be-
cause pinned memory is a scarce resource, but how much is too much is difficult to know in advance.
Furthermore, the pinning of system memory is a heavyweight operation compared to most normal
system memory allocations, so as with all optimizations, test the application and the systems it runs
on for optimal performance parameters.
13.1.2. Asynchronous and Overlapping Transfers with
Computation
Data transfers between the host and the device using cudaMemcpy() are blocking transfers; that
is, control is returned to the host thread only after the data transfer is complete. The cudaMem-
cpyAsync() function is a non-blocking variant of cudaMemcpy() in which control is returned immedi-
ately to the host thread. In contrast with cudaMemcpy(), the asynchronous transfer version requires
pinned host memory (see Pinned Memory), and it contains an additional argument, a stream ID. A
stream is simply a sequence of operations that are performed in order on the device. Operations in
different streams can be interleaved and in some cases overlapped - a property that can be used to
hide data transfers between the host and the device.
Asynchronous transfers enable overlap of data transfers with computation in two different ways. On
all CUDA-enabled devices, it is possible to overlap host computation with asynchronous data transfers
and with device computations. For example, Overlapping computation and data transfers demon-
strates how host computation in the routine cpuFunction() is performed while data is transferred
to the device and a kernel using the device is executed.
Overlapping computation and data transfers
cudaMemcpyAsync(a_d, a_h, size, cudaMemcpyHostToDevice, 0);
kernel<<<grid, block>>>(a_d);
cpuFunction();
The last argument to the cudaMemcpyAsync() function is the stream ID, which in this case uses the
default stream, stream 0. The kernel also uses the default stream, and it will not begin execution until
the memory copy completes; therefore, no explicit synchronization is needed. Because the memory
copy and the kernel both return control to the host immediately, the host function cpuFunction()
overlaps their execution.
38
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
In Overlapping computation and data transfers, the memory copy and kernel execution occur sequen-
tially. On devices that are capable of concurrent copy and compute, it is possible to overlap kernel ex-
ecution on the device with data transfers between the host and the device. Whether a device has this
capability is indicated by the asyncEngineCount field of the cudaDeviceProp structure (or listed in
the output of the deviceQuery CUDA Sample). On devices that have this capability, the overlap once
again requires pinned host memory, and, in addition, the data transfer and kernel must use different,
non-default streams (streams with non-zero stream IDs). Non-default streams are required for this
overlap because memory copy, memory set functions, and kernel calls that use the default stream
begin only after all preceding calls on the device (in any stream) have completed, and no operation on
the device (in any stream) commences until they are finished.
Concurrent copy and execute illustrates the basic technique.
Concurrent copy and execute
cudaStreamCreate(&stream1);
cudaStreamCreate(&stream2);
cudaMemcpyAsync(a_d, a_h, size, cudaMemcpyHostToDevice, stream1);
kernel<<<grid, block, 0, stream2>>>(otherData_d);
In this code, two streams are created and used in the data transfer and kernel executions as specified
in the last arguments of the cudaMemcpyAsync call and the kernel’s execution configuration.
Concurrent copy and execute demonstrates how to overlap kernel execution with asynchronous data
transfer. This technique could be used when the data dependency is such that the data can be broken
into chunks and transferred in multiple stages, launching multiple kernels to operate on each chunk
as it arrives. Sequential copy and execute and Staged concurrent copy and execute demonstrate this.
They produce equivalent results. The first segment shows the reference sequential implementation,
which transfers and operates on an array of N floats (where N is assumed to be evenly divisible by
nThreads).
Sequential copy and execute
cudaMemcpy(a_d, a_h, N*sizeof(float), dir);
kernel<<<N∕nThreads, nThreads>>>(a_d);
Staged concurrent copy and execute shows how the transfer and kernel execution can be broken up
into nStreams stages. This approach permits some overlapping of the data transfer and execution.
Staged concurrent copy and execute
size=N*sizeof(float)∕nStreams;
for (i=0; i<nStreams; i++) {
offset = i*N∕nStreams;
cudaMemcpyAsync(a_d+offset, a_h+offset, size, dir, stream[i]);
kernel<<<N∕(nThreads*nStreams), nThreads, 0,
stream[i]>>>(a_d+offset);
}
is assumed that N is evenly divisible by
it
(In Staged concurrent copy and execute,
nThreads*nStreams.) Because execution within a stream occurs sequentially, none of the ker-
nels will launch until the data transfers in their respective streams complete. Current GPUs can
13.1. Data Transfer Between Host and Device
39
CUDA C++ Best Practices Guide, Release 12.5
simultaneously process asynchronous data transfers and execute kernels. GPUs with a single copy
engine can perform one asynchronous data transfer and execute kernels whereas GPUs with two copy
engines can simultaneously perform one asynchronous data transfer from the host to the device, one
asynchronous data transfer from the device to the host, and execute kernels. The number of copy
engines on a GPU is given by the asyncEngineCount field of the cudaDeviceProp structure, which
is also listed in the output of the deviceQuery CUDA Sample. (It should be mentioned that it is not
possible to overlap a blocking transfer with an asynchronous transfer, because the blocking transfer
occurs in the default stream, so it will not begin until all previous CUDA calls complete. It will not allow
any other CUDA call to begin until it has completed.) A diagram depicting the timeline of execution
for the two code segments is shown in Figure 1, and nStreams is equal to 4 for Staged concurrent
copy and execute in the bottom half of the figure.
Fig. 1: Timeline comparison for copy and kernel execution
Top Sequential
Bottom
Concurrent
For this example, it is assumed that the data transfer and kernel execution times are comparable. In
such cases, and when the execution time (tE) exceeds the transfer time (tT), a rough estimate for the
overall time is tE + tT/nStreams for the staged version versus tE + tT for the sequential version. If the
transfer time exceeds the execution time, a rough estimate for the overall time is tT + tE/nStreams.
13.1.3. Zero Copy
Zero copy is a feature that was added in version 2.2 of the CUDA Toolkit. It enables GPU threads to
directly access host memory. For this purpose, it requires mapped pinned (non-pageable) memory.
On integrated GPUs (i.e., GPUs with the integrated field of the CUDA device properties structure set
to 1), mapped pinned memory is always a performance gain because it avoids superfluous copies as
integrated GPU and CPU memory are physically the same. On discrete GPUs, mapped pinned memory
is advantageous only in certain cases. Because the data is not cached on the GPU, mapped pinned
memory should be read or written only once, and the global loads and stores that read and write the
memory should be coalesced. Zero copy can be used in place of streams because kernel-originated
data transfers automatically overlap kernel execution without the overhead of setting up and deter-
mining the optimal number of streams.
Note: Low Priority: Use zero-copy operations on integrated GPUs for CUDA Toolkit version 2.2 and
later.
40
Chapter 13. Memory Optimizations
The host code in Zero-copy host code shows how zero copy is typically set up.
CUDA C++ Best Practices Guide, Release 12.5
Zero-copy host code
float *a_h, *a_map;
...
cudaGetDeviceProperties(&prop, 0);
if (!prop.canMapHostMemory)
exit(0);
cudaSetDeviceFlags(cudaDeviceMapHost);
cudaHostAlloc(&a_h, nBytes, cudaHostAllocMapped);
cudaHostGetDevicePointer(&a_map, a_h, 0);
kernel<<<gridSize, blockSize>>>(a_map);
In this code, the canMapHostMemory field of the structure returned by cudaGetDeviceProper-
ties() is used to check that the device supports mapping host memory to the device’s address
space. Page-locked memory mapping is enabled by calling cudaSetDeviceFlags() with cudaDe-
viceMapHost. Note that cudaSetDeviceFlags() must be called prior to setting a device or making
a CUDA call that requires state (that is, essentially, before a context is created). Page-locked mapped
host memory is allocated using cudaHostAlloc(), and the pointer to the mapped device address
space is obtained via the function cudaHostGetDevicePointer().
In the code in Zero-copy host
code, kernel() can reference the mapped pinned host memory using the pointer a_map in exactly
the same was as it would if a_map referred to a location in device memory.
Note: Mapped pinned host memory allows you to overlap CPU-GPU memory transfers with compu-
tation while avoiding the use of CUDA streams. But since any repeated access to such memory areas
causes repeated CPU-GPU transfers, consider creating a second area in device memory to manually
cache the previously read host memory data.
13.1.4. Unified Virtual Addressing
Devices of compute capability 2.0 and later support a special addressing mode called Unified Virtual
Addressing (UVA) on 64-bit Linux and Windows. With UVA, the host memory and the device memories
of all installed supported devices share a single virtual address space.
Prior to UVA, an application had to keep track of which pointers referred to device memory (and for
which device) and which referred to host memory as a separate bit of metadata (or as hard-coded
information in the program) for each pointer. Using UVA, on the other hand, the physical memory
space to which a pointer points can be determined simply by inspecting the value of the pointer using
cudaPointerGetAttributes().
Under UVA, pinned host memory allocated with cudaHostAlloc() will have identical host and de-
vice pointers, so it is not necessary to call cudaHostGetDevicePointer() for such allocations. Host
memory allocations pinned after-the-fact via cudaHostRegister(), however, will continue to have
different device pointers than their host pointers, so cudaHostGetDevicePointer() remains nec-
essary in that case.
UVA is also a necessary precondition for enabling peer-to-peer (P2P) transfer of data directly across
the PCIe bus or NVLink for supported GPUs in supported configurations, bypassing host memory.
See the CUDA C++ Programming Guide for further explanations and software requirements for UVA
and P2P.
13.1. Data Transfer Between Host and Device
41
CUDA C++ Best Practices Guide, Release 12.5
13.2. Device Memory Spaces
CUDA devices use several memory spaces, which have different characteristics that reflect their dis-
tinct usages in CUDA applications. These memory spaces include global, local, shared, texture, and
registers, as shown in Figure 2.
Fig. 2: Memory spaces on a CUDA device
Of these different memory spaces, global memory is the most plentiful; see Features and Technical
Specifications of the CUDA C++ Programming Guide for the amounts of memory available in each
memory space at each compute capability level. Global, local, and texture memory have the greatest
access latency, followed by constant memory, shared memory, and the register file.
The various principal traits of the memory types are shown in Table 1.
42
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
Table 1: Table 1. Salient Features of Device Memory
Location
on/off
chip
On
Off
On
CachedAc-
cess
Scope
Life-
time
n/a
R/W 1 thread
Thread
Yes†† R/W 1 thread
Thread
n/a
R/W All
Block
threads
in block
Off
†
R/W All
Off
Yes
R
Off
Yes
R
threads +
host
All
threads +
host
All
threads +
host
Host
alloca-
tion
Host
alloca-
tion
Host
alloca-
tion
Memory
Register
Local
Shared
Global
Constant
Texture
† Cached in L1 and L2 by default on devices of com-
pute capability 6.0 and 7.x; cached only in L2 by
default on devices of lower compute capabilities,
though some allow opt-in to caching in L1 as well
via compilation flags.
†† Cached in L1 and L2 by default except on devices
of compute capability 5.x; devices of compute capa-
bility 5.x cache locals only in L2.
In the case of texture access, if a texture reference is bound to a linear array in global memory, then
the device code can write to the underlying array. Texture references that are bound to CUDA arrays
can be written to via surface-write operations by binding a surface to the same underlying CUDA array
storage). Reading from a texture while writing to its underlying global memory array in the same kernel
launch should be avoided because the texture caches are read-only and are not invalidated when the
associated global memory is modified.
13.2.1. Coalesced Access to Global Memory
A very important performance consideration in programming for CUDA-capable GPU architectures is
the coalescing of global memory accesses. Global memory loads and stores by threads of a warp are
coalesced by the device into as few as possible transactions.
Note: High Priority: Ensure global memory accesses are coalesced whenever possible.
The access requirements for coalescing depend on the compute capability of the device and are doc-
umented in the CUDA C++ Programming Guide.
13.2. Device Memory Spaces
43
CUDA C++ Best Practices Guide, Release 12.5
For devices of compute capability 6.0 or higher, the requirements can be summarized quite easily: the
concurrent accesses of the threads of a warp will coalesce into a number of transactions equal to the
number of 32-byte transactions necessary to service all of the threads of the warp.
For certain devices of compute capability 5.2, L1-caching of accesses to global memory can be option-
ally enabled. If L1-caching is enabled on these devices, the number of required transactions is equal
to the number of required 128-byte aligned segments.
Note: On devices of compute capability 6.0 or higher, L1-caching is the default, however the data
access unit is 32-byte regardless of whether global loads are cached in L1 or not.
On devices with GDDR memory, accessing memory in a coalesced way is even more important when
ECC is turned on. Scattered accesses increase ECC memory transfer overhead, especially when writing
data to global memory.
Coalescing concepts are illustrated in the following simple examples. These examples assume com-
pute capability 6.0 or higher and that accesses are for 4-byte words, unless otherwise noted.
13.2.1.1 A Simple Access Pattern
The first and simplest case of coalescing can be achieved by any CUDA-enabled device of compute
capability 6.0 or higher: the k-th thread accesses the k-th word in a 32-byte aligned array. Not all
threads need to participate.
For example, if the threads of a warp access adjacent 4-byte words (e.g., adjacent float values), four
coalesced 32-byte transactions will service that memory access. Such a pattern is shown in Figure 3.
Fig. 3: Coalesced access
This access pattern results in four 32-byte transactions, indicated by the red rectangles.
If from any of the four 32-byte segments only a subset of the words are requested (e.g.
if several
threads had accessed the same word or if some threads did not participate in the access), the full
segment is fetched anyway. Furthermore, if accesses by the threads of the warp had been permuted
within or accross the four segments, still only four 32-byte transactions would have been performed
by a device with compute capability 6.0 or higher.
13.2.1.2 A Sequential but Misaligned Access Pattern
If sequential threads in a warp access memory that is sequential but not aligned with a 32-byte seg-
ment, five 32-byte segments will be requested, as shown in Figure 4.
Memory allocated through the CUDA Runtime API, such as via cudaMalloc(), is guaranteed to be
aligned to at least 256 bytes. Therefore, choosing sensible thread block sizes, such as multiples of the
warp size (i.e., 32 on current GPUs), facilitates memory accesses by warps that are properly aligned.
(Consider what would happen to the memory addresses accessed by the second, third, and subse-
quent thread blocks if the thread block size was not a multiple of warp size, for example.)
44
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
Fig. 4: Misaligned sequential addresses that fall within five 32-byte segments
13.2.1.3 Effects of Misaligned Accesses
It is easy and informative to explore the ramifications of misaligned accesses using a simple copy
kernel, such as the one in A copy kernel that illustrates misaligned accesses.
A copy kernel that illustrates misaligned accesses
__global__ void offsetCopy(float *odata, float* idata, int offset)
{
int xid = blockIdx.x * blockDim.x + threadIdx.x + offset;
odata[xid] = idata[xid];
}
In A copy kernel that illustrates misaligned accesses, data is copied from the input array idata to the
output array, both of which exist in global memory. The kernel is executed within a loop in host code
that varies the parameter offset from 0 to 32. (e.g. Figure 4 corresponds to this misalignments) The
effective bandwidth for the copy with various offsets on an NVIDIA Tesla V100 (compute capability
7.0) is shown in Figure 5.
Fig. 5: Performance of offsetCopy kernel
13.2. Device Memory Spaces
45
CUDA C++ Best Practices Guide, Release 12.5
For the NVIDIA Tesla V100, global memory accesses with no offset or with offsets that are multiples
of 8 words result in four 32-byte transactions. The achieved bandwidth is approximately 790 GB/s.
Otherwise, five 32-byte segments are loaded per warp, and we would expect approximately 4/5th of
the memory throughput achieved with no offsets.
In this particular example, the offset memory throughput achieved is, however, approximately 9/10th,
because adjacent warps reuse the cache lines their neighbors fetched. So while the impact is still
evident it is not as large as we might have expected. It would have been more so if adjacent warps had
not exhibited such a high degree of reuse of the over-fetched cache lines.
13.2.1.4 Strided Accesses
As seen above, in the case of misaligned sequential accesses, caches help to alleviate the performance
impact. It may be different with non-unit-strided accesses, however, and this is a pattern that occurs
frequently when dealing with multidimensional data or matrices. For this reason, ensuring that as
much as possible of the data in each cache line fetched is actually used is an important part of per-
formance optimization of memory accesses on these devices.
To illustrate the effect of strided access on effective bandwidth, see the kernel strideCopy() in
A kernel to illustrate non-unit stride data copy, which copies data with a stride of stride elements
between threads from idata to odata.
A kernel to illustrate non-unit stride data copy
__global__ void strideCopy(float *odata, float* idata, int stride)
{
int xid = (blockIdx.x*blockDim.x + threadIdx.x)*stride;
odata[xid] = idata[xid];
}
Figure 6 illustrates such a situation; in this case, threads within a warp access words in memory with a
stride of 2. This action leads to a load of eight L2 cache segments per warp on the Tesla V100 (compute
capability 7.0).
Fig. 6: Adjacent threads accessing memory with a stride of 2
A stride of 2 results in a 50% of load/store efficiency since half the elements in the transaction are not
used and represent wasted bandwidth. As the stride increases, the effective bandwidth decreases
46
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
until the point where 32 32-byte segments are loaded for the 32 threads in a warp, as indicated in
Figure 7.
Fig. 7: Performance of strideCopy kernel
As illustrated in Figure 7, non-unit-stride global memory accesses should be avoided whenever possi-
ble. One method for doing so utilizes shared memory, which is discussed in the next section.
13.2.2. L2 Cache
Starting with CUDA 11.0, devices of compute capability 8.0 and above have the capability to influ-
ence persistence of data in the L2 cache. Because L2 cache is on-chip, it potentially provides higher
bandwidth and lower latency accesses to global memory.
For more details refer to the L2 Access Management section in the CUDA C++ Programming Guide.
13.2.2.1 L2 Cache Access Window
When a CUDA kernel accesses a data region in the global memory repeatedly, such data accesses can
be considered to be persisting. On the other hand, if the data is only accessed once, such data accesses
can be considered to be streaming. A portion of the L2 cache can be set aside for persistent accesses
to a data region in global memory. If this set-aside portion is not used by persistent accesses, then
streaming or normal data accesses can use it.
The L2 cache set-aside size for persisting accesses may be adjusted, within limits:
cudaGetDeviceProperties(&prop, device_id);
cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, prop.persistingL2CacheMaxSize); ∕*
,→Set aside max possible size of L2 cache for persisting accesses *∕
13.2. Device Memory Spaces
47
∕∕
∕∕
∕∕ (Must
∕∕ Hint
CUDA C++ Best Practices Guide, Release 12.5
Mapping of user data to L2 set-aside portion can be controlled using an access policy window on a
CUDA stream or CUDA graph kernel node. The example below shows how to use the access policy
window on a CUDA stream.
cudaStreamAttrValue stream_attribute;
,→Stream level attributes data structure
stream_attribute.accessPolicyWindow.base_ptr
,→Global Memory data pointer
stream_attribute.accessPolicyWindow.num_bytes = num_bytes;
,→Number of bytes for persisting accesses.
= reinterpret_cast<void*>(ptr); ∕∕
,→be less than cudaDeviceProp::accessPolicyMaxWindowSize)
stream_attribute.accessPolicyWindow.hitRatio
,→for L2 cache hit ratio for persisting accesses in the num_bytes region
stream_attribute.accessPolicyWindow.hitProp
,→of access property on cache hit
stream_attribute.accessPolicyWindow.missProp
,→of access property on cache miss.
= 1.0;
= cudaAccessPropertyPersisting; ∕∕ Type
= cudaAccessPropertyStreaming;
∕∕ Type
∕∕Set the attributes to a CUDA stream of type cudaStream_t
cudaStreamSetAttribute(stream, cudaStreamAttributeAccessPolicyWindow, &stream_
,→attribute);
The access policy window requires a value for hitRatio and num_bytes. Depending on the value of
the num_bytes parameter and the size of L2 cache, one may need to tune the value of hitRatio to
avoid thrashing of L2 cache lines.
13.2.2.2 Tuning the Access Window Hit-Ratio
The hitRatio parameter can be used to specify the fraction of accesses that receive the hitProp
property. For example, if the hitRatio value is 0.6, 60% of the memory accesses in the global memory
region [ptr..ptr+num_bytes) have the persisting property and 40% of the memory accesses have the
streaming property. To understand the effect of hitRatio and num_bytes, we use a sliding window
micro benchmark.
This microbenchmark uses a 1024 MB region in GPU global memory. First, we set aside 30 MB of the
L2 cache for persisting accesses using cudaDeviceSetLimit(), as discussed above. Then, as shown
in the figure below, we specify that the accesses to the first freqSize * sizeof(int) bytes of the
memory region are persistent. This data will thus use the L2 set-aside portion. In our experiment, we
vary the size of this persistent data region from 10 MB to 60 MB to model various scenarios where
data fits in or exceeds the available L2 set-aside portion of 30 MB. Note that the NVIDIA Tesla A100
GPU has 40 MB of total L2 cache capacity. Accesses to the remaining data of the memory region (i.e.,
streaming data) are considered normal or streaming accesses and will thus use the remaining 10 MB
of the non set-aside L2 portion (unless part of the L2 set-aside portion is unused).
Consider the following kernel code and access window parameters, as the implementation of the slid-
ing window experiment.
__global__ void kernel(int *data_persistent, int *data_streaming, int dataSize, int
,→freqSize) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
∕*Each CUDA thread accesses one element in the persistent data section
and one element in the streaming data section.
Because the size of the persistent memory region (freqSize * sizeof(int) bytes)
,→is much
48
(continues on next page)
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
Fig. 8: Mapping Persistent data accesses to set-aside L2 in sliding window experiment
smaller than the size of the streaming memory region (dataSize * sizeof(int)
,→bytes), data
in the persistent region is accessed more frequently*∕
(continued from previous page)
data_persistent[tid % freqSize] = 2 * data_persistent[tid % freqSize];
data_streaming[tid % dataSize] = 2 * data_streaming[tid % dataSize];
}
stream_attribute.accessPolicyWindow.base_ptr
,→persistent);
stream_attribute.accessPolicyWindow.num_bytes = freqSize * sizeof(int);
,→bytes for persisting accesses in range 10-60 MB
stream_attribute.accessPolicyWindow.hitRatio
,→cache hit ratio. Fixed value 1.0
= 1.0;
= reinterpret_cast<void*>(data_
∕∕Number of
∕∕Hint for
The performance of the above kernel is shown in the chart below. When the persistent data region
fits well into the 30 MB set-aside portion of the L2 cache, a performance increase of as much as 50%
is observed. However, once the size of this persistent data region exceeds the size of the L2 set-aside
cache portion, approximately 10% performance drop is observed due to thrashing of L2 cache lines.
Fig. 9: The performance of the sliding-window benchmark with fixed hit-ratio of 1.0
13.2. Device Memory Spaces
49
CUDA C++ Best Practices Guide, Release 12.5
In order to optimize the performance, when the size of the persistent data is more than the size of the
set-aside L2 cache portion, we tune the num_bytes and hitRatio parameters in the access window
as below.
stream_attribute.accessPolicyWindow.base_ptr
,→persistent);
stream_attribute.accessPolicyWindow.num_bytes = 20*1024*1024;
,→
stream_attribute.accessPolicyWindow.hitRatio
,→((float)freqSize*sizeof(int));
∕∕20 MB
= (20*1024*1024)∕
∕∕Such that up to 20MB of data is resident.
= reinterpret_cast<void*>(data_
We fix the num_bytes in the access window to 20 MB and tune the hitRatio such that a random 20
MB of the total persistent data is resident in the L2 set-aside cache portion. The remaining portion
of this persistent data will be accessed using the streaming property. This helps in reducing cache
thrashing. The results are shown in the chart below, where we see good performance regardless of
whether the persistent data fits in the L2 set-aside or not.
Fig. 10: The performance of the sliding-window benchmark with tuned hit-ratio
13.2.3. Shared Memory
Because it is on-chip, shared memory has much higher bandwidth and lower latency than local and
global memory - provided there are no bank conflicts between the threads, as detailed in the following
section.
50
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
13.2.3.1 Shared Memory and Memory Banks
To achieve high memory bandwidth for concurrent accesses, shared memory is divided into equally
sized memory modules (banks) that can be accessed simultaneously. Therefore, any memory load or
store of n addresses that spans n distinct memory banks can be serviced simultaneously, yielding an
effective bandwidth that is n times as high as the bandwidth of a single bank.
However, if multiple addresses of a memory request map to the same memory bank, the accesses
are serialized. The hardware splits a memory request that has bank conflicts into as many separate
conflict-free requests as necessary, decreasing the effective bandwidth by a factor equal to the num-
ber of separate memory requests. The one exception here is when multiple threads in a warp address
the same shared memory location, resulting in a broadcast.
In this case, multiple broadcasts from
different banks are coalesced into a single multicast from the requested shared memory locations to
the threads.
To minimize bank conflicts, it is important to understand how memory addresses map to memory
banks and how to optimally schedule memory requests.
On devices of compute capability 5.x or newer, each bank has a bandwidth of 32 bits every clock cycle,
and successive 32-bit words are assigned to successive banks. The warp size is 32 threads and the
number of banks is also 32, so bank conflicts can occur between any threads in the warp. See Compute
Capability 5.x in the CUDA C++ Programming Guide for further details.
13.2.3.2 Shared Memory in Matrix Multiplication (C=AB)
Shared memory enables cooperation between threads in a block. When multiple threads in a block
use the same data from global memory, shared memory can be used to access the data from global
memory only once. Shared memory can also be used to avoid uncoalesced memory accesses by loading
and storing data in a coalesced pattern from global memory and then reordering it in shared memory.
Aside from memory bank conflicts, there is no penalty for non-sequential or unaligned accesses by a
warp in shared memory.
The use of shared memory is illustrated via the simple example of a matrix multiplication C = AB for
the case with A of dimension Mxw, B of dimension wxN, and C of dimension MxN. To keep the kernels
simple, M and N are multiples of 32, since the warp size (w) is 32 for current devices.
A natural decomposition of the problem is to use a block and tile size of wxw threads. Therefore, in
terms of wxw tiles, A is a column matrix, B is a row matrix, and C is their outer product; see Figure 11. A
grid of N/w by M/w blocks is launched, where each thread block calculates the elements of a different
tile in C from a single tile of A and a single tile of B.
To do this, the simpleMultiply kernel (Unoptimized matrix multiplication) calculates the output el-
ements of a tile of matrix C.
Unoptimized matrix multiplication
__global__ void simpleMultiply(float *a, float* b, float *c,
int N)
{
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
float sum = 0.0f;
for (int i = 0; i < TILE_DIM; i++) {
sum += a[row*TILE_DIM+i] * b[i*N+col];
13.2. Device Memory Spaces
51
(continues on next page)
CUDA C++ Best Practices Guide, Release 12.5
Fig. 11: Block-column matrix multiplied by block-row matrix. Block-column matrix (A) multiplied by
block-row matrix (B) with resulting product matrix (C).
(continued from previous page)
}
c[row*N+col] = sum;
}
In Unoptimized matrix multiplication, a, b, and c are pointers to global memory for the matrices A, B,
and C, respectively; blockDim.x, blockDim.y, and TILE_DIM are all equal to w. Each thread in the
wxw-thread block calculates one element in a tile of C. row and col are the row and column of the
element in C being calculated by a particular thread. The for loop over i multiplies a row of A by a
column of B, which is then written to C.
The effective bandwidth of this kernel is 119.9 GB/s on an NVIDIA Tesla V100. To analyze performance,
it is necessary to consider how warps access global memory in the for loop. Each warp of threads
calculates one row of a tile of C, which depends on a single row of A and an entire tile of B as illustrated
in Figure 12.
Fig. 12: Computing a row of a tile. Computing a row of a tile in C using one row of A and an entire tile
of B.
For each iteration i of the for loop, the threads in a warp read a row of the B tile, which is a sequential
and coalesced access for all compute capabilities.
52
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
However, for each iteration i, all threads in a warp read the same value from global memory for matrix
A, as the index row*TILE_DIM+i is constant within a warp. Even though such an access requires
only 1 transaction on devices of compute capability 2.0 or higher, there is wasted bandwidth in the
transaction, because only one 4-byte word out of 8 words in a 32-byte cache segment is used. We can
reuse this cache line in subsequent iterations of the loop, and we would eventually utilize all 8 words;
however, when many warps execute on the same multiprocessor simultaneously, as is generally the
case, the cache line may easily be evicted from the cache between iterations i and i+1.
The performance on a device of any compute capability can be improved by reading a tile of A into
shared memory as shown in Using shared memory to improve the global memory load efficiency in
matrix multiplication.
Using shared memory to improve the global memory load efficiency in matrix multiplication
__global__ void coalescedMultiply(float *a, float* b, float *c,
int N)
{
}
__shared__ float aTile[TILE_DIM][TILE_DIM];
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
float sum = 0.0f;
aTile[threadIdx.y][threadIdx.x] = a[row*TILE_DIM+threadIdx.x];
__syncwarp();
for (int i = 0; i < TILE_DIM; i++) {
sum += aTile[threadIdx.y][i]* b[i*N+col];
}
c[row*N+col] = sum;
In Using shared memory to improve the global memory load efficiency in matrix multiplication, each
element in a tile of A is read from global memory only once, in a fully coalesced fashion (with no
wasted bandwidth), to shared memory. Within each iteration of the for loop, a value in shared mem-
ory is broadcast to all threads in a warp. Instead of a __syncthreads()synchronization barrier call,
a __syncwarp() is sufficient after reading the tile of A into shared memory because only threads
within the warp that write the data into shared memory read this data. This kernel has an effective
bandwidth of 144.4 GB/s on an NVIDIA Tesla V100. This illustrates the use of the shared memory as
a user-managed cache when the hardware L1 cache eviction policy does not match up well with the
needs of the application or when L1 cache is not used for reads from global memory.
A further improvement can be made to how Using shared memory to improve the global memory load
efficiency in matrix multiplication deals with matrix B. In calculating each of the rows of a tile of matrix
C, the entire tile of B is read. The repeated reading of the B tile can be eliminated by reading it into
shared memory once (Improvement by reading additional data into shared memory).
13.2. Device Memory Spaces
53
CUDA C++ Best Practices Guide, Release 12.5
Improvement by reading additional data into shared memory
__global__ void sharedABMultiply(float *a, float* b, float *c,
int N)
{
}
__shared__ float aTile[TILE_DIM][TILE_DIM],
bTile[TILE_DIM][TILE_DIM];
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
float sum = 0.0f;
aTile[threadIdx.y][threadIdx.x] = a[row*TILE_DIM+threadIdx.x];
bTile[threadIdx.y][threadIdx.x] = b[threadIdx.y*N+col];
__syncthreads();
for (int i = 0; i < TILE_DIM; i++) {
sum += aTile[threadIdx.y][i]* bTile[i][threadIdx.x];
}
c[row*N+col] = sum;
Note that in Improvement by reading additional data into shared memory, a __syncthreads() call is
required after reading the B tile because a warp reads data from shared memory that were written to
shared memory by different warps. The effective bandwidth of this routine is 195.5 GB/s on an NVIDIA
Tesla V100. Note that the performance improvement is not due to improved coalescing in either case,
but to avoiding redundant transfers from global memory.
The results of the various optimizations are summarized in Table 2.
Table 2: Table 2. Performance Improvements Optimizing C =
AB Matrix Multiply :class table-no-stripes
Optimization
No optimization
Coalesced using shared memory to store a tile of A
NVIDIA Tesla V100
119.9 GB/s
144.4 GB/s
Using shared memory to eliminate redundant reads of a tile of B 195.5 GB/s
Note: Medium Priority: Use shared memory to avoid redundant transfers from global memory.
13.2.3.3 Shared Memory in Matrix Multiplication (C=AAT)
A variant of the previous matrix multiplication can be used to illustrate how strided accesses to global
memory, as well as shared memory bank conflicts, are handled. This variant simply uses the transpose
of A in place of B, so C = AAT.
A simple implementation for C = AAT is shown in Unoptimized handling of strided accesses to global
memory
54
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
Unoptimized handling of strided accesses to global memory
__global__ void simpleMultiply(float *a, float *c, int M)
{
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
float sum = 0.0f;
for (int i = 0; i < TILE_DIM; i++) {
sum += a[row*TILE_DIM+i] * a[col*TILE_DIM+i];
}
c[row*M+col] = sum;
}
In Unoptimized handling of strided accesses to global memory, the row-th, col-th element of C is ob-
tained by taking the dot product of the row-th and col-th rows of A. The effective bandwidth for this
kernel is 12.8 GB/s on an NVIDIA Tesla V100. These results are substantially lower than the corre-
sponding measurements for the C = AB kernel. The difference is in how threads in a half warp access
elements of A in the second term, a[col*TILE_DIM+i], for each iteration i. For a warp of threads,
col represents sequential columns of the transpose of A, and therefore col*TILE_DIM represents a
strided access of global memory with a stride of w, resulting in plenty of wasted bandwidth.
The way to avoid strided access is to use shared memory as before, except in this case a warp reads a
row of A into a column of a shared memory tile, as shown in An optimized handling of strided accesses
using coalesced reads from global memory.
An optimized handling of strided accesses using coalesced reads from global memory
__global__ void coalescedMultiply(float *a, float *c, int M)
{
__shared__ float aTile[TILE_DIM][TILE_DIM],
transposedTile[TILE_DIM][TILE_DIM];
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
float sum = 0.0f;
aTile[threadIdx.y][threadIdx.x] = a[row*TILE_DIM+threadIdx.x];
transposedTile[threadIdx.x][threadIdx.y] =
a[(blockIdx.x*blockDim.x + threadIdx.y)*TILE_DIM +
threadIdx.x];
__syncthreads();
for (int i = 0; i < TILE_DIM; i++) {
sum += aTile[threadIdx.y][i]* transposedTile[i][threadIdx.x];
}
c[row*M+col] = sum;
}
An optimized handling of strided accesses using coalesced reads from global memory uses the shared
transposedTile to avoid uncoalesced accesses in the second term in the dot product and the shared
aTile technique from the previous example to avoid uncoalesced accesses in the first term. The
effective bandwidth of this kernel is 140.2 GB/s on an NVIDIA Tesla V100.These results are lower than
those obtained by the final kernel for C = AB. The cause of the difference is shared memory bank
conflicts.
The reads of elements in transposedTile within the for loop are free of conflicts, because threads
of each half warp read across rows of the tile, resulting in unit stride across the banks. However, bank
conflicts occur when copying the tile from global memory into shared memory. To enable the loads
from global memory to be coalesced, data are read from global memory sequentially. However, this
13.2. Device Memory Spaces
55
CUDA C++ Best Practices Guide, Release 12.5
requires writing to shared memory in columns, and because of the use of wxw tiles in shared memory,
this results in a stride between threads of w banks - every thread of the warp hits the same bank (Recall
that w is selected as 32). These many-way bank conflicts are very expensive. The simple remedy is to
pad the shared memory array so that it has an extra column, as in the following line of code.
__shared__ float transposedTile[TILE_DIM][TILE_DIM+1];
This padding eliminates the conflicts entirely, because now the stride between threads is w+1 banks
(i.e., 33 for current devices), which, due to modulo arithmetic used to compute bank indices, is equiva-
lent to a unit stride. After this change, the effective bandwidth is 199.4 GB/s on an NVIDIA Tesla V100,
which is comparable to the results from the last C = AB kernel.
The results of these optimizations are summarized in Table 3.
Table 3: Table 3. Performance Improvements Optimizing C =
AAT Matrix Multiplication
Optimization
No optimization
NVIDIA Tesla V100
12.8 GB/s
Using shared memory to coalesce global reads 140.2 GB/s
Removing bank conflicts
199.4 GB/s
These results should be compared with those in Table 2. As can be seen from these tables, judicious
use of shared memory can dramatically improve performance.
The examples in this section have illustrated three reasons to use shared memory:
▶ To enable coalesced accesses to global memory, especially to avoid large strides (for general
matrices, strides are much larger than 32)
▶ To eliminate (or reduce) redundant loads from global memory
▶ To avoid wasted bandwidth
13.2.3.4 Asynchronous Copy from Global Memory to Shared Memory
CUDA 11.0 introduces an async-copy feature that can be used within device code to explicitly manage
the asynchronous copying of data from global memory to shared memory. This feature enables CUDA
It also avoids an
kernels to overlap copying data from global to shared memory with computation.
intermediary register file access traditionally present between the global memory read and the shared
memory write.
For more details refer to the memcpy_async section in the CUDA C++ Programming Guide.
To understand the performance difference between synchronous copy and asynchronous copy of data
from global memory to shared memory, consider the following micro benchmark CUDA kernels for
demonstrating the synchronous and asynchronous approaches. Asynchronous copies are hardware
accelerated for NVIDIA A100 GPU.
template <typename T>
__global__ void pipeline_kernel_sync(T *global, uint64_t *clock, size_t copy_count) {
extern __shared__ char s[];
T *shared = reinterpret_cast<T *>(s);
uint64_t clock_start = clock64();
(continues on next page)
56
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
(continued from previous page)
for (size_t i = 0; i < copy_count; ++i) {
shared[blockDim.x * i + threadIdx.x] = global[blockDim.x * i + threadIdx.x];
}
uint64_t clock_end = clock64();
atomicAdd(reinterpret_cast<unsigned long long *>(clock),
clock_end - clock_start);
}
template <typename T>
__global__ void pipeline_kernel_async(T *global, uint64_t *clock, size_t copy_count) {
extern __shared__ char s[];
T *shared = reinterpret_cast<T *>(s);
uint64_t clock_start = clock64();
∕∕pipeline pipe;
for (size_t i = 0; i < copy_count; ++i) {
__pipeline_memcpy_async(&shared[blockDim.x * i + threadIdx.x],
&global[blockDim.x * i + threadIdx.x], sizeof(T));
}
__pipeline_commit();
__pipeline_wait_prior(0);
uint64_t clock_end = clock64();
atomicAdd(reinterpret_cast<unsigned long long *>(clock),
clock_end - clock_start);
}
The synchronous version for the kernel loads an element from global memory to an intermediate regis-
ter and then stores the intermediate register value to shared memory. In the asynchronous version of
the kernel, instructions to load from global memory and store directly into shared memory are issued
as soon as __pipeline_memcpy_async() function is called. The __pipeline_wait_prior(0) will
wait until all the instructions in the pipe object have been executed. Using asynchronous copies does
not use any intermediate register. Not using intermediate registers can help reduce register pressure
and can increase kernel occupancy. Data copied from global memory to shared memory using asyn-
chronous copy instructions can be cached in the L1 cache or the L1 cache can be optionally bypassed.
If individual CUDA threads are copying elements of 16 bytes, the L1 cache can be bypassed. This
difference is illustrated in Figure 13.
Fig. 13: Comparing Synchronous vs Asynchronous Copy from Global Memory to Shared Memory
We evaluate the performance of both kernels using elements of size 4B, 8B and 16B per thread i.e.,
using int, int2 and int4 for the template parameter. We adjust the copy_count in the kernels such
that each thread block copies from 512 bytes up to 48 MB. The performance of the kernels is shown
in Figure 14.
From the performance chart, the following observations can be made for this experiment.
13.2. Device Memory Spaces
57
CUDA C++ Best Practices Guide, Release 12.5
Fig. 14: Comparing Performance of Synchronous vs Asynchronous Copy from Global Memory to Shared
Memory
▶ Best performance with synchronous copy is achieved when the copy_count parameter is a mul-
tiple of 4 for all three element sizes. The compiler can optimize groups of 4 load and store in-
structions. This is evident from the saw tooth curves.
▶ Asynchronous copy achieves better performance in nearly all cases.
▶ The async-copy does not require the copy_count parameter to be a multiple of 4, to maximize
performance through compiler optimizations.
▶ Overall, best performance is achieved when using asynchronous copies with an element of size
8 or 16 bytes.
13.2.4. Local Memory
Local memory is so named because its scope is local to the thread, not because of its physical location.
In fact, local memory is off-chip. Hence, access to local memory is as expensive as access to global
memory. In other words, the term local in the name does not imply faster access.
Local memory is used only to hold automatic variables. This is done by the nvcc compiler when it
determines that there is insufficient register space to hold the variable. Automatic variables that are
likely to be placed in local memory are large structures or arrays that would consume too much register
space and arrays that the compiler determines may be indexed dynamically.
Inspection of the PTX assembly code (obtained by compiling with -ptx or -keep command-line op-
tions to nvcc) reveals whether a variable has been placed in local memory during the first compilation
phases. If it has, it will be declared using the .local mnemonic and accessed using the ld.local
and st.local mnemonics. If it has not, subsequent compilation phases might still decide otherwise,
if they find the variable consumes too much register space for the targeted architecture. There is no
58
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
way to check this for a specific variable, but the compiler reports total local memory usage per kernel
(lmem) when run with the--ptxas-options=-v option.
13.2.5. Texture Memory
The read-only texture memory space is cached. Therefore, a texture fetch costs one device memory
read only on a cache miss; otherwise, it just costs one read from the texture cache. The texture cache
is optimized for 2D spatial locality, so threads of the same warp that read texture addresses that are
close together will achieve best performance. Texture memory is also designed for streaming fetches
with a constant latency; that is, a cache hit reduces DRAM bandwidth demand, but not fetch latency.
In certain addressing situations, reading device memory through texture fetching can be an advanta-
geous alternative to reading device memory from global or constant memory.
13.2.5.1 Additional Texture Capabilities
If textures are fetched using tex1D(),tex2D(), or tex3D() rather than tex1Dfetch(), the hardware
provides other capabilities that might be useful for some applications such as image processing, as
shown in Table 4.
Table 4: Table 4. Useful Features for tex1D(), tex2D(), and
tex3D() Fetches
Feature
Filtering
Use
Caveat
Fast, low-precision in-
terpolation between
texels
Valid only if the texture
reference returns floating-
point data
Normalized texture coordinates
Resolution-
independent coding
None
Addressing modes
Automatic
of boundary cases1
handling
Can be used only with
normalized texture coordi-
nates
1 The automatic handling of boundary cases
in the bottom row of Table 4 refers to how
a texture coordinate is resolved when it falls
outside the valid addressing range. There are
two options: clamp and wrap.
If x is the co-
ordinate and N is the number of texels for
a one-dimensional texture, then with clamp,
x is replaced by 0 if x < 0 and by 1-1/N if 1
<x. With wrap, x is replaced by frac(x) where
frac(x) = x - floor(x). Floor returns the largest
integer less than or equal to x. So, in clamp
mode where N = 1, an x of 1.3 is clamped to
1.0; whereas in wrap mode, it is converted to
0.3
Within a kernel call, the texture cache is not kept coherent with respect to global memory writes, so
texture fetches from addresses that have been written via global stores in the same kernel call return
13.2. Device Memory Spaces
59
CUDA C++ Best Practices Guide, Release 12.5
undefined data. That is, a thread can safely read a memory location via texture if the location has
been updated by a previous kernel call or memory copy, but not if it has been previously updated by
the same thread or another thread within the same kernel call.
13.2.6. Constant Memory
There is a total of 64 KB constant memory on a device. The constant memory space is cached. As
a result, a read from constant memory costs one memory read from device memory only on a cache
miss; otherwise, it just costs one read from the constant cache. Accesses to different addresses by
threads within a warp are serialized, thus the cost scales linearly with the number of unique addresses
read by all threads within a warp. As such, the constant cache is best when threads in the same warp
accesses only a few distinct locations. If all threads of a warp access the same location, then constant
memory can be as fast as a register access.
13.2.7. Registers
Generally, accessing a register consumes zero extra clock cycles per instruction, but delays may occur
due to register read-after-write dependencies and register memory bank conflicts.
The compiler and hardware thread scheduler will schedule instructions as optimally as possible to
avoid register memory bank conflicts. An application has no direct control over these bank conflicts.
In particular, there is no register-related reason to pack data into vector data types such as float4 or
int4 types.
13.2.7.1 Register Pressure
Register pressure occurs when there are not enough registers available for a given task. Even though
each multiprocessor contains thousands of 32-bit registers (see Features and Technical Specifications
of the CUDA C++ Programming Guide), these are partitioned among concurrent threads. To prevent
the compiler from allocating too many registers, use the -maxrregcount=N compiler command-line
option (see nvcc) or the launch bounds kernel definition qualifier (see Execution Configuration of the
CUDA C++ Programming Guide) to control the maximum number of registers to allocated per thread.
13.3. Allocation
Device memory allocation and de-allocation via cudaMalloc() and cudaFree() are expensive op-
erations. It is recommended to use cudaMallocAsync() and cudaFreeAsync() which are stream
ordered pool allocators to manage device memory.
60
Chapter 13. Memory Optimizations
CUDA C++ Best Practices Guide, Release 12.5
13.4. NUMA Best Practices
Some recent Linux distributions enable automatic NUMA balancing (or “AutoNUMA”) by default.
In
some instances, operations performed by automatic NUMA balancing may degrade the performance
of applications running on NVIDIA GPUs. For optimal performance, users should manually tune the
NUMA characteristics of their application.
The optimal NUMA tuning will depend on the characteristics and desired hardware affinities of each
application and node, but in general applications computing on NVIDIA GPUs are advised to choose a
policy that disables automatic NUMA balancing. For example, on IBM Newell POWER9 nodes (where
the CPUs correspond to NUMA nodes 0 and 8), use:
numactl --membind=0,8
to bind memory allocations to the CPUs.
13.4. NUMA Best Practices
61
CUDA C++ Best Practices Guide, Release 12.5
62
Chapter 13. Memory Optimizations
Chapter 14. Execution Configuration
Optimizations
One of the keys to good performance is to keep the multiprocessors on the device as busy as pos-
sible. A device in which work is poorly balanced across the multiprocessors will deliver suboptimal
performance. Hence, it’s important to design your application to use threads and blocks in a way that
maximizes hardware utilization and to limit practices that impede the free distribution of work. A key
concept in this effort is occupancy, which is explained in the following sections.
Hardware utilization can also be improved in some cases by designing your application so that multiple,
independent kernels can execute at the same time. Multiple kernels executing at the same time is
known as concurrent kernel execution. Concurrent kernel execution is described below.
Another important concept is the management of system resources allocated for a particular task.
How to manage this resource utilization is discussed in the final sections of this chapter.
14.1. Occupancy
Thread instructions are executed sequentially in CUDA, and, as a result, executing other warps when
one warp is paused or stalled is the only way to hide latencies and keep the hardware busy. Some metric
related to the number of active warps on a multiprocessor is therefore important in determining how
effectively the hardware is kept busy. This metric is occupancy.
Occupancy is the ratio of the number of active warps per multiprocessor to the maximum number of
possible active warps. (To determine the latter number, see the deviceQuery CUDA Sample or refer
to Compute Capabilities in the CUDA C++ Programming Guide.) Another way to view occupancy is the
percentage of the hardware’s ability to process warps that is actively in use.
Higher occupancy does not always equate to higher performance-there is a point above which addi-
tional occupancy does not improve performance. However, low occupancy always interferes with the
ability to hide memory latency, resulting in performance degradation.
Per thread resources required by a CUDA kernel might limit the maximum block size in an un-
wanted way.
In order to maintain forward compatibility to future hardware and toolkits and to
ensure that at least one thread block can run on an SM, developers should include the single ar-
gument __launch_bounds__(maxThreadsPerBlock) which specifies the largest block size that
the kernel will be launched with. Failure to do so could lead to “too many resources requested for
launch” errors. Providing the two argument version of __launch_bounds__(maxThreadsPerBlock,
minBlocksPerMultiprocessor) can improve performance in some cases. The right value for min-
BlocksPerMultiprocessor should be determined using a detailed per kernel analysis.
63
CUDA C++ Best Practices Guide, Release 12.5
14.1.1. Calculating Occupancy
One of several factors that determine occupancy is register availability. Register storage enables
threads to keep local variables nearby for low-latency access. However, the set of registers (known
as the register file) is a limited commodity that all threads resident on a multiprocessor must share.
Registers are allocated to an entire block all at once. So, if each thread block uses many registers,
the number of thread blocks that can be resident on a multiprocessor is reduced, thereby lower-
ing the occupancy of the multiprocessor. The maximum number of registers per thread can be
set manually at compilation time per-file using the -maxrregcount option or per-kernel using the
__launch_bounds__ qualifier (see Register Pressure).
For purposes of calculating occupancy, the number of registers used by each thread is one of the
key factors. For example, on devices of compute capability 7.0 each multiprocessor has 65,536 32-
bit registers and can have a maximum of 2048 simultaneous threads resident (64 warps x 32 threads
per warp). This means that in one of these devices, for a multiprocessor to have 100% occupancy,
each thread can use at most 32 registers. However, this approach of determining how register count
affects occupancy does not take into account the register allocation granularity. For example, on a
device of compute capability 7.0, a kernel with 128-thread blocks using 37 registers per thread results
in an occupancy of 75% with 12 active 128-thread blocks per multi-processor, whereas a kernel with
320-thread blocks using the same 37 registers per thread results in an occupancy of 63% because only
four 320-thread blocks can reside on a multiprocessor. Furthermore, register allocations are rounded
up to the nearest 256 registers per warp.
The number of registers available, the maximum number of simultaneous threads resident on each
multiprocessor, and the register allocation granularity vary over different compute capabilities. Be-
cause of these nuances in register allocation and the fact that a multiprocessor’s shared memory is
also partitioned between resident thread blocks, the exact relationship between register usage and oc-
cupancy can be difficult to determine. The --ptxas options=v option of nvcc details the number of
registers used per thread for each kernel. See Hardware Multithreading of the CUDA C++ Programming
Guide for the register allocation formulas for devices of various compute capabilities and Features and
Technical Specifications of the CUDA C++ Programming Guide for the total number of registers avail-
able on those devices. Alternatively, NVIDIA provides an occupancy calculator in the form of an Excel
spreadsheet that enables developers to hone in on the optimal balance and to test different possible
scenarios more easily. This spreadsheet, shown in Figure 15, is called CUDA_Occupancy_Calculator.
xls and is located in the tools subdirectory of the CUDA Toolkit installation.
In addition to the calculator spreadsheet, occupancy can be determined using the NVIDIA Nsight Com-
pute Profiler. Details about occupancy are displayed in the Occupancy section.
An application can also use the Occupancy API from the CUDA Runtime, e.g. cudaOccupancyMax-
ActiveBlocksPerMultiprocessor, to dynamically select launch configurations based on runtime
parameters.
14.2. Hiding Register Dependencies
Note: Medium Priority: To hide latency arising from register dependencies, maintain sufficient num-
bers of active threads per multiprocessor (i.e., sufficient occupancy).
Register dependencies arise when an instruction uses a result stored in a register written by an instruc-
tion before it. The latency of most arithmetic instructions is typically 4 cycles on devices of compute
capability 7.0. So threads must wait approximatly 4 cycles before using an arithmetic result. However,
64
Chapter 14. Execution Configuration Optimizations
CUDA C++ Best Practices Guide, Release 12.5
Fig. 1: Using the CUDA Occupancy Calculator to project GPU multiprocessor occupancy
this latency can be completely hidden by the execution of threads in other warps. See Registers for
details.
14.3. Thread and Block Heuristics
Note: Medium Priority: The number of threads per block should be a multiple of 32 threads, because
this provides optimal computing efficiency and facilitates coalescing.
The dimension and size of blocks per grid and the dimension and size of threads per block are both
important factors. The multidimensional aspect of these parameters allows easier mapping of mul-
tidimensional problems to CUDA and does not play a role in performance. As a result, this section
discusses size but not dimension.
Latency hiding and occupancy depend on the number of active warps per multiprocessor, which is
implicitly determined by the execution parameters along with resource (register and shared memory)
constraints. Choosing execution parameters is a matter of striking a balance between latency hiding
(occupancy) and resource utilization.
Choosing the execution configuration parameters should be done in tandem; however, there are cer-
tain heuristics that apply to each parameter individually. When choosing the first execution configu-
ration parameter-the number of blocks per grid, or grid size - the primary concern is keeping the entire
GPU busy. The number of blocks in a grid should be larger than the number of multiprocessors so that
all multiprocessors have at least one block to execute. Furthermore, there should be multiple active
blocks per multiprocessor so that blocks that aren’t waiting for a __syncthreads() can keep the
14.3. Thread and Block Heuristics
65
CUDA C++ Best Practices Guide, Release 12.5
hardware busy. This recommendation is subject to resource availability; therefore, it should be deter-
mined in the context of the second execution parameter - the number of threads per block, or block
size - as well as shared memory usage. To scale to future devices, the number of blocks per kernel
launch should be in the thousands.
When choosing the block size, it is important to remember that multiple concurrent blocks can reside
on a multiprocessor, so occupancy is not determined by block size alone. In particular, a larger block
size does not imply a higher occupancy.
As mentioned in Occupancy, higher occupancy does not always equate to better performance. For
example, improving occupancy from 66 percent to 100 percent generally does not translate to a similar
increase in performance. A lower occupancy kernel will have more registers available per thread than
a higher occupancy kernel, which may result in less register spilling to local memory; in particular, with
a high degree of exposed instruction-level parallelism (ILP) it is, in some cases, possible to fully cover
latency with a low occupancy.
There are many such factors involved in selecting block size, and inevitably some experimentation is
required. However, a few rules of thumb should be followed:
▶ Threads per block should be a multiple of warp size to avoid wasting computation on under-
populated warps and to facilitate coalescing.
▶ A minimum of 64 threads per block should be used, and only if there are multiple concurrent
blocks per multiprocessor.
▶ Between 128 and 256 threads per block is a good initial range for experimentation with different
block sizes.
▶ Use several smaller thread blocks rather than one large thread block per multiprocessor if la-
tency affects performance. This is particularly beneficial to kernels that frequently call __sync-
threads().
Note that when a thread block allocates more registers than are available on a multiprocessor, the
kernel launch fails, as it will when too much shared memory or too many threads are requested.
14.4. Effects of Shared Memory
Shared memory can be helpful in several situations, such as helping to coalesce or eliminate redundant
access to global memory. However, it also can act as a constraint on occupancy. In many cases, the
amount of shared memory required by a kernel is related to the block size that was chosen, but the
mapping of threads to shared memory elements does not need to be one-to-one. For example, it
may be desirable to use a 64x64 element shared memory array in a kernel, but because the maximum
number of threads per block is 1024, it is not possible to launch a kernel with 64x64 threads per block.
In such cases, kernels with 32x32 or 64x16 threads can be launched with each thread processing
four elements of the shared memory array. The approach of using a single thread to process multiple
elements of a shared memory array can be beneficial even if limits such as threads per block are not
an issue. This is because some operations common to each element can be performed by the thread
once, amortizing the cost over the number of shared memory elements processed by the thread.
A useful technique to determine the sensitivity of performance to occupancy is through experimen-
tation with the amount of dynamically allocated shared memory, as specified in the third parameter
of the execution configuration. By simply increasing this parameter (without modifying the kernel), it
is possible to effectively reduce the occupancy of the kernel and measure its effect on performance.
66
Chapter 14. Execution Configuration Optimizations
CUDA C++ Best Practices Guide, Release 12.5
14.5. Concurrent Kernel Execution
As described in Asynchronous and Overlapping Transfers with Computation, CUDA streams can be
used to overlap kernel execution with data transfers. On devices that are capable of concurrent ker-
nel execution, streams can also be used to execute multiple kernels simultaneously to more fully take
advantage of the device’s multiprocessors. Whether a device has this capability is indicated by the
concurrentKernels field of the cudaDeviceProp structure (or listed in the output of the device-
Query CUDA Sample). Non-default streams (streams other than stream 0) are required for concurrent
execution because kernel calls that use the default stream begin only after all preceding calls on the
device (in any stream) have completed, and no operation on the device (in any stream) commences
until they are finished.
The following example illustrates the basic technique. Because kernel1 and kernel2 are executed
in different, non-default streams, a capable device can execute the kernels at the same time.
cudaStreamCreate(&stream1);
cudaStreamCreate(&stream2);
kernel1<<<grid, block, 0, stream1>>>(data_1);
kernel2<<<grid, block, 0, stream2>>>(data_2);
14.6. Multiple contexts
CUDA work occurs within a process space for a particular GPU known as a context. The context encap-
sulates kernel launches and memory allocations for that GPU as well as supporting constructs such
as the page tables. The context is explicit in the CUDA Driver API but is entirely implicit in the CUDA
Runtime API, which creates and manages contexts automatically.
With the CUDA Driver API, a CUDA application process can potentially create more than one context for
a given GPU. If multiple CUDA application processes access the same GPU concurrently, this almost
always implies multiple contexts, since a context is tied to a particular host process unless Multi-
Process Service is in use.
While multiple contexts (and their associated resources such as global memory allocations) can be
allocated concurrently on a given GPU, only one of these contexts can execute work at any given mo-
ment on that GPU; contexts sharing the same GPU are time-sliced. Creating additional contexts incurs
memory overhead for per-context data and time overhead for context switching. Furthermore, the
need for context switching can reduce utilization when work from several contexts could otherwise
execute concurrently (see also Concurrent Kernel Execution).
Therefore, it is best to avoid multiple contexts per GPU within the same CUDA application. To assist
with this, the CUDA Driver API provides methods to access and manage a special context on each GPU
called the primary context. These are the same contexts used implicitly by the CUDA Runtime when
there is not already a current context for a thread.
∕∕ When initializing the program∕library
CUcontext ctx;
cuDevicePrimaryCtxRetain(&ctx, dev);
∕∕ When the program∕library launches work
cuCtxPushCurrent(ctx);
kernel<<<...>>>(...);
cuCtxPopCurrent(&ctx);
14.5. Concurrent Kernel Execution
(continues on next page)
67
CUDA C++ Best Practices Guide, Release 12.5
∕∕ When the program∕library is finished with the context
cuDevicePrimaryCtxRelease(dev);
(continued from previous page)
Note: NVIDIA-SMI can be used to configure a GPU for exclusive process mode, which limits the num-
ber of contexts per GPU to one. This context can be current to as many threads as desired within
the creating process, and cuDevicePrimaryCtxRetain will fail if a non-primary context that was
created with the CUDA driver API already exists on the device.
68
Chapter 14. Execution Configuration Optimizations
Chapter 15. Instruction Optimization
Awareness of how instructions are executed often permits low-level optimizations that can be useful,
especially in code that is run frequently (the so-called hot spot in a program). Best practices suggest
that this optimization be performed after all higher-level optimizations have been completed.
15.1. Arithmetic Instructions
Single-precision floats provide the best performance, and their use is highly encouraged. The through-
put of individual arithmetic operations is detailed in the CUDA C++ Programming Guide.
15.1.1. Division Modulo Operations
Note: Low Priority: Use shift operations to avoid expensive division and modulo calculations.
Integer division and modulo operations are particularly costly and should be avoided or replaced with
bitwise operations whenever possible: If n is a power of 2, ( i/n ) is equivalent to ( i ≫ log2(n) ) and (
i%n ) is equivalent to ( i& (n − 1) ).
The compiler will perform these conversions if n is literal. (For further information, refer to Perfor-
mance Guidelines in the CUDA C++ Programming Guide).
15.1.2. Loop Counters Signed vs. Unsigned
Note: Low Medium Priority: Use signed integers rather than unsigned integers as loop counters.
In the C language standard, unsigned integer overflow semantics are well defined, whereas signed in-
teger overflow causes undefined results. Therefore, the compiler can optimize more aggressively with
signed arithmetic than it can with unsigned arithmetic. This is of particular note with loop counters:
since it is common for loop counters to have values that are always positive, it may be tempting to
declare the counters as unsigned. For slightly better performance, however, they should instead be
declared as signed.
For example, consider the following code:
69
CUDA C++ Best Practices Guide, Release 12.5
for (i = 0; i < n; i++) {
out[i] = in[offset + stride*i];
}
Here, the sub-expression stride*i could overflow a 32-bit integer, so if i is declared as unsigned, the
overflow semantics prevent the compiler from using some optimizations that might otherwise have
applied, such as strength reduction. If instead i is declared as signed, where the overflow semantics
are undefined, the compiler has more leeway to use these optimizations.
15.1.3. Reciprocal Square Root
The reciprocal square root should always be invoked explicitly as rsqrtf() for single precision and
rsqrt() for double precision. The compiler optimizes 1.0f∕sqrtf(x) into rsqrtf() only when this
does not violate IEEE-754 semantics.
15.1.4. Other Arithmetic Instructions
Note: Low Priority: Avoid automatic conversion of doubles to floats.
The compiler must on occasion insert conversion instructions, introducing additional execution cycles.
This is the case for:
▶ Functions operating on char or short whose operands generally need to be converted to an int
▶ Double-precision floating-point constants (defined without any type suffix) used as input to
single-precision floating-point computations
The latter case can be avoided by using single-precision floating-point constants, defined with an f
suffix such as 3.141592653589793f, 1.0f, 0.5f.
For single-precision code, use of the float type and the single-precision math functions are highly
recommended.
It should also be noted that the CUDA math library’s complementary error function, erfcf(), is par-
ticularly fast with full single-precision accuracy.
15.1.5. Exponentiation With Small Fractional Arguments
For some fractional exponents, exponentiation can be accelerated significantly compared to the use
of pow() by using square roots, cube roots, and their inverses. For those exponentiations where the
exponent is not exactly representable as a floating-point number, such as 1/3, this can also provide
much more accurate results, as use of pow() magnifies the initial representational error.
The formulas in the table below are valid for x >= 0, x != -0, that is, signbit(x) == 0.
70
Chapter 15. Instruction Optimization
CUDA C++ Best Practices Guide, Release 12.5
Table 1: Table 5. Formulae for exponentiation by small fractions
Computation Formula
x1/9
x-1/9
x1/6
x-1/6
x1/4
x-1/4
x1/3
x-1/3
x1/2
x-1/2
x2/3
x-2/3
x3/4
x-3/4
x7/6
x-7/6
x5/4
x-5/4
x4/3
x-4/3
x3/2
x-3/2
r = rcbrt(rcbrt(x))
r = cbrt(rcbrt(x))
r = rcbrt(rsqrt(x))
r = rcbrt(sqrt(x))
r = rsqrt(rsqrt(x))
r = sqrt(rsqrt(x))
r = cbrt(x)
r = rcbrt(x)
r = sqrt(x)
r = rsqrt(x)
r = cbrt(x); r = r*r
r = rcbrt(x); r = r*r
r = sqrt(x); r = r*sqrt(r)
r = rsqrt(x); r = r*sqrt(r)
r = x*rcbrt(rsqrt(x))
r = (1∕x) * rcbrt(sqrt(x))
r = x*rsqrt(rsqrt(x))
r = (1∕x)*sqrt(rsqrt(x))
r = x*cbrt(x)
r = (1∕x)*rcbrt(x)
r = x*sqrt(x)
r = (1∕x)*rsqrt(x)
15.1.6. Math Libraries
Note: Medium Priority: Use the fast math library whenever speed trumps precision.
Two types of runtime math operations are supported. They can be distinguished by their names:
some have names with prepended underscores, whereas others do not (e.g., __functionName() ver-
sus functionName()). Functions following the __functionName() naming convention map directly
to the hardware level. They are faster but provide somewhat lower accuracy (e.g., __sinf(x) and
__expf(x)). Functions following functionName() naming convention are slower but have higher ac-
curacy (e.g., sinf(x) and expf(x)). The throughput of __sinf(x), __cosf(x), and__expf(x) is
much greater than that of sinf(x), cosf(x), and expf(x). The latter become even more expensive
(about an order of magnitude slower) if the magnitude of the argument x needs to be reduced. More-
15.1. Arithmetic Instructions
71
CUDA C++ Best Practices Guide, Release 12.5
over, in such cases, the argument-reduction code uses local memory, which can affect performance
even more because of the high latency of local memory. More details are available in the CUDA C++
Programming Guide.
Note also that whenever sine and cosine of the same argument are computed, the sincos family of
instructions should be used to optimize performance:
▶ __sincosf() for single-precision fast math (see next paragraph)
▶ sincosf() for regular single-precision
▶ sincos() for double precision
The -use_fast_math compiler option of nvcc coerces every functionName() call to the equivalent
__functionName() call. It also disables single-precision denormal support and lowers the precision of
single-precision division in general. This is an aggressive optimization that can both reduce numerical
accuracy and alter special case handling. A more robust approach is to selectively introduce calls
to fast intrinsic functions only if merited by performance gains and where altered behavior can be
tolerated. Note this switch is effective only on single-precision floating point.
Note: Medium Priority: Prefer faster, more specialized math functions over slower, more general ones
when possible.
For small integer powers (e.g., x2 or x3), explicit multiplication is almost certainly faster than the use of
general exponentiation routines such as pow(). While compiler optimization improvements continually
seek to narrow this gap, explicit multiplication (or the use of an equivalent purpose-built inline function
or macro) can have a significant advantage. This advantage is increased when several powers of the
same base are needed (e.g., where both x2 and x5 are calculated in close proximity), as this aids the
compiler in its common sub-expression elimination (CSE) optimization.
For exponentiation using base 2 or 10, use the functions exp2() or expf2() and exp10() or
expf10() rather than the functions pow() or powf(). Both pow() and powf() are heavy-weight
functions in terms of register pressure and instruction count due to the numerous special cases aris-
ing in general exponentiation and the difficulty of achieving good accuracy across the entire ranges of
the base and the exponent. The functions exp2(), exp2f(), exp10(), and exp10f(), on the other
hand, are similar to exp() and expf() in terms of performance, and can be as much as ten times
faster than their pow()/powf() equivalents.
For exponentiation with an exponent of 1/3, use the cbrt() or cbrtf() function rather than the
generic exponentiation functions pow() or powf(), as the former are significantly faster than the
latter. Likewise, for exponentation with an exponent of -1/3, use rcbrt() or rcbrtf().
Replace sin(π*<expr>) with sinpi(<expr>), cos(π*<expr>) with cospi(<expr>), and sin-
cos(π*<expr>) with sincospi(<expr>). This is advantageous with regard to both accuracy and
performance. As a particular example, to evaluate the sine function in degrees instead of radians, use
sinpi(x∕180.0). Similarly, the single-precision functions sinpif(), cospif(), and sincospif()
should replace calls to sinf(), cosf(), and sincosf() when the function argument is of the form
π*<expr>. (The performance advantage sinpi() has over sin() is due to simplified argument re-
duction; the accuracy advantage is because sinpi() multiplies by π only implicitly, effectively using
an infinitely precise mathematical π rather than a single- or double-precision approximation thereof.)
72
Chapter 15. Instruction Optimization
CUDA C++ Best Practices Guide, Release 12.5
15.1.7. Precision-related Compiler Flags
By default, the nvcc compiler generates IEEE-compliant code, but it also provides options to generate
code that somewhat less accurate but faster:
▶ -ftz=true (denormalized numbers are flushed to zero)
▶ -prec-div=false (less precise division)
▶ -prec-sqrt=false (less precise square root)
Another, more aggressive, option is -use_fast_math, which coerces every functionName() call to
the equivalent __functionName() call. This makes the code run faster at the cost of diminished
precision and accuracy. See Math Libraries.
15.2. Memory Instructions
Note: High Priority: Minimize the use of global memory. Prefer shared memory access where possible.
Memory instructions include any instruction that reads from or writes to shared, local, or global mem-
ory. When accessing uncached local or global memory, there are hundreds of clock cycles of memory
latency.
As an example, the assignment operator in the following sample code has a high throughput, but,
crucially, there is a latency of hundreds of clock cycles to read data from global memory:
__shared__ float shared[32];
__device__ float device[32];
shared[threadIdx.x] = device[threadIdx.x];
Much of this global memory latency can be hidden by the thread scheduler if there are sufficient
independent arithmetic instructions that can be issued while waiting for the global memory access to
complete. However, it is best to avoid accessing global memory whenever possible.
15.2. Memory Instructions
73
CUDA C++ Best Practices Guide, Release 12.5
74
Chapter 15. Instruction Optimization
Chapter 16. Control Flow
16.1. Branching and Divergence
Note: High Priority: Avoid different execution paths within the same warp.
Flow control instructions (if, switch, do, for, while) can significantly affect the instruction through-
put by causing threads of the same warp to diverge; that is, to follow different execution paths. If this
happens, the different execution paths must be executed separately; this increases the total number
of instructions executed for this warp.
To obtain best performance in cases where the control flow depends on the thread ID, the controlling
condition should be written so as to minimize the number of divergent warps.
This is possible because the distribution of the warps across the block is deterministic as mentioned
in SIMT Architecture of the CUDA C++ Programming Guide. A trivial example is when the controlling
condition depends only on (threadIdx / WSIZE) where WSIZE is the warp size.
In this case, no warp diverges because the controlling condition is perfectly aligned with the warps.
For branches including just a few instructions, warp divergence generally results in marginal perfor-
mance losses. For example, the compiler may use predication to avoid an actual branch. Instead, all
instructions are scheduled, but a per-thread condition code or predicate controls which threads ex-
ecute the instructions. Threads with a false predicate do not write results, and also do not evaluate
addresses or read operands.
Starting with the Volta architecture, Independent Thread Scheduling allows a warp to remain diverged
outside of the data-dependent conditional block. An explicit __syncwarp() can be used to guarantee
that the warp has reconverged for subsequent instructions.
16.2. Branch Predication
Note: Low Priority: Make it easy for the compiler to use branch predication in lieu of loops or control
statements.
Sometimes, the compiler may unroll loops or optimize out if or switch statements by using branch
predication instead. In these cases, no warp can ever diverge. The programmer can also control loop
unrolling using
75
CUDA C++ Best Practices Guide, Release 12.5
#pragma unroll
For more information on this pragma, refer to the CUDA C++ Programming Guide.
When using branch predication, none of the instructions whose execution depends on the controlling
condition is skipped. Instead, each such instruction is associated with a per-thread condition code or
predicate that is set to true or false according to the controlling condition. Although each of these
instructions is scheduled for execution, only the instructions with a true predicate are actually exe-
cuted. Instructions with a false predicate do not write results, and they also do not evaluate addresses
or read operands.
The compiler replaces a branch instruction with predicated instructions only if the number of instruc-
tions controlled by the branch condition is less than or equal to a certain threshold.
76
Chapter 16. Control Flow
Chapter 17. Deploying CUDA
Applications
Having completed the GPU acceleration of one or more components of the application it is possible
to compare the outcome with the original expectation. Recall that the initial assess step allowed the
developer to determine an upper bound for the potential speedup attainable by accelerating given
hotspots.
Before tackling other hotspots to improve the total speedup, the developer should consider taking
the partially parallelized implementation and carry it through to production. This is important for a
number of reasons; for example, it allows the user to profit from their investment as early as possible
(the speedup may be partial but is still valuable), and it minimizes risk for the developer and the user
by providing an evolutionary rather than revolutionary set of changes to the application.
77
CUDA C++ Best Practices Guide, Release 12.5
78
Chapter 17. Deploying CUDA Applications
Chapter 18. Understanding the
Programming Environment
With each generation of NVIDIA processors, new features are added to the GPU that CUDA can lever-
age. Consequently, it’s important to understand the characteristics of the architecture.
Programmers should be aware of two version numbers. The first is the compute capability, and the
second is the version number of the CUDA Runtime and CUDA Driver APIs.
18.1. CUDA Compute Capability
The compute capability describes the features of the hardware and reflects the set of instructions
supported by the device as well as other specifications, such as the maximum number of threads
per block and the number of registers per multiprocessor. Higher compute capability versions are
supersets of lower (that is, earlier) versions, so they are backward compatible.
The compute capability of the GPU in the device can be queried programmatically as illustrated in the
deviceQuery CUDA Sample. The output for that program is shown in Figure 16. This information is
obtained by calling cudaGetDeviceProperties() and accessing the information in the structure it
returns.
The major and minor revision numbers of the compute capability are shown on the seventh line of
Figure 16. Device 0 of this system has compute capability 7.0.
More details about the compute capabilities of various GPUs are in CUDA-Enabled GPUs and Compute
Capabilities of the CUDA C++ Programming Guide. In particular, developers should note the number
of multiprocessors on the device, the number of registers and the amount of memory available, and
any special capabilities of the device.
18.2. Additional Hardware Data
Certain hardware features are not described by the compute capability. For example, the ability to
overlap kernel execution with asynchronous data transfers between the host and the device is avail-
able on most but not all GPUs irrespective of the compute capability. In such cases, call cudaGetDe-
viceProperties() to determine whether the device is capable of a certain feature. For example, the
asyncEngineCount field of the device property structure indicates whether overlapping kernel exe-
cution and data transfers is possible (and, if so, how many concurrent transfers are possible); likewise,
the canMapHostMemory field indicates whether zero-copy data transfers can be performed.
79
CUDA C++ Best Practices Guide, Release 12.5
Fig. 1: Sample CUDA configuration data reported by deviceQuery
18.3. Which Compute Capability Target
To target specific versions of NVIDIA hardware and CUDA software, use the -arch, -code, and
-gencode options of nvcc. Code that uses the warp shuffle operation, for example, must be com-
piled with -arch=sm_30 (or higher compute capability).
See Building for Maximum Compatibility for further discussion of the flags used for building code for
multiple generations of CUDA-capable device simultaneously.
18.4. CUDA Runtime
The host runtime component of the CUDA software environment can be used only by host functions.
It provides functions to handle the following:
▶ Device management
▶ Context management
▶ Memory management
▶ Code module management
▶ Execution control
▶ Texture reference management
▶ Interoperability with OpenGL and Direct3D
80
Chapter 18. Understanding the Programming Environment
CUDA C++ Best Practices Guide, Release 12.5
As compared to the lower-level CUDA Driver API, the CUDA Runtime greatly eases device management
by providing implicit initialization, context management, and device code module management. The
C++ host code generated by nvcc utilizes the CUDA Runtime, so applications that link to this code
will depend on the CUDA Runtime; similarly, any code that uses the cuBLAS, cuFFT, and other CUDA
Toolkit libraries will also depend on the CUDA Runtime, which is used internally by these libraries.
The functions that make up the CUDA Runtime API are explained in the CUDA Toolkit Reference Man-
ual.
The CUDA Runtime handles kernel loading and setting up kernel parameters and launch configuration
before the kernel is launched. The implicit driver version checking, code initialization, CUDA context
management, CUDA module management (cubin to function mapping), kernel configuration, and pa-
rameter passing are all performed by the CUDA Runtime.
It comprises two principal parts:
▶ A C-style function interface (cuda_runtime_api.h).
▶ C++-style convenience wrappers (cuda_runtime.h) built on top of the C-style functions.
For more information on the Runtime API, refer to CUDA Runtime of the CUDA C++ Programming
Guide.
18.4. CUDA Runtime
81
CUDA C++ Best Practices Guide, Release 12.5
82
Chapter 18. Understanding the Programming Environment
Chapter 19. CUDA Compatibility
Developer’s Guide
CUDA Toolkit is released on a monthly release cadence to deliver new features, performance improve-
ments, and critical bug fixes. CUDA compatibility allows users to update the latest CUDA Toolkit soft-
ware (including the compiler, libraries, and tools) without requiring update to the entire driver stack.
The CUDA software environment consists of three parts:
▶ CUDA Toolkit (libraries, CUDA runtime and developer tools) - SDK for developers to build CUDA
applications.
▶ CUDA driver - User-mode driver component used to run CUDA applications (e.g.
libcuda.so on
Linux systems).
▶ NVIDIA GPU device driver - Kernel-mode driver component for NVIDIA GPUs.
On Linux systems, the CUDA driver and kernel mode components are delivered together in the NVIDIA
display driver package. This is shown in Figure 1.
The
CUDA
com-
piler
(nvcc),
pro-
vides
a
way
to
han-
dle
CUDA
and
non-
CUDA
code
(by
split-
ting
and
steer-
ing
com-
pi-
83
Fig. 1: Components of CUDA
la-
tion),
along
with
the
CUDA
run-
time,
is
part
CUDA C++ Best Practices Guide, Release 12.5
of the CUDA compiler toolchain. The CUDA Runtime API provides developers with high-level C++
interface for simplified management of devices, kernel executions etc., While the CUDA driver API
provides (CUDA Driver API) a low-level programming interface for applications to target NVIDIA
hardware.
Built on top of these technologies are CUDA libraries, some of which are included in the CUDA Toolkit,
while others such as cuDNN may be released independently of the CUDA Toolkit.
19.1. CUDA Toolkit Versioning
Starting with CUDA 11, the toolkit versions are based on an industry-standard semantic versioning
scheme: .X.Y.Z, where:
▶ .X stands for the major version - APIs have changed and binary compatibility is broken.
▶ .Y stands for the minor version - Introduction of new APIs, deprecation of old APIs, and source
compatibility might be broken but binary compatibility is maintained.
▶ .Z stands for the release/patch version - new updates and patches will increment this.
Each component in the toolkit is recommended to be semantically versioned. From CUDA 11.3 NVRTC
is also semantically versioned. We will note some of them later on in the document. The versions of
the components in the toolkit are available in this table.
Compatibility of the CUDA platform is thus intended to address a few scenarios:
1. NVIDIA driver upgrades to systems with GPUs running in production for enterprises or datacen-
ters can be complex and may need advance planning. Delays in rolling out new NVIDIA drivers
could mean that users of such systems may not have access to new features available in CUDA
releases. Not requiring driver updates for new CUDA releases can mean that new versions of the
software can be made available faster to users.
2. Many software libraries and applications built on top of CUDA (e.g. math libraries or deep learning
frameworks) do not have a direct dependency on the CUDA runtime, compiler or driver. In such
cases, users or developers can still benefit from not having to upgrade the entire CUDA Toolkit
or driver to use these libraries or frameworks.
3. Upgrading dependencies is error-prone and time consuming, and in some corner cases, can even
change the semantics of a program. Constantly recompiling with the latest CUDA Toolkit means
forcing upgrades on the end-customers of an application product. Package managers facilitate
this process but unexpected issues can still arise and if a bug is found, it necessitates a repeat
of the above upgrade process.
CUDA supports several compatibility choices:
84
Chapter 19. CUDA Compatibility Developer’s Guide
CUDA C++ Best Practices Guide, Release 12.5
1. First introduced in CUDA 10, the CUDA Forward Compatible Upgrade is designed to allow users
to get access to new CUDA features and run applications built with new CUDA releases on sys-
tems with older installations of the NVIDIA datacenter driver.
2. First introduced in CUDA 11.1, CUDA Enhanced Compatibility provides two benefits:
▶ By leveraging semantic versioning across components in the CUDA Toolkit, an application
can be built for one CUDA minor release (for example 11.1) and work across all future minor
releases within the major family (i.e. 11.x).
▶ The CUDA runtime has relaxed the minimum driver version check and thus no longer requires
a driver upgrade when moving to a new minor release.
3. The CUDA driver ensures backward Binary Compatibility is maintained for compiled CUDA appli-
cations. Applications compiled with CUDA toolkit versions as old as 3.2 will run on newer drivers.
19.2. Source Compatibility
We define source compatibility as a set of guarantees provided by the library, where a well-formed
application built against a specific version of the library (using the SDK) will continue to build and run
without errors when a newer version of the SDK is installed.
Both the CUDA driver and the CUDA runtime are not source compatible across the different SDK re-
leases. APIs can be deprecated and removed. Therefore, an application that compiled successfully on
an older version of the toolkit may require changes in order to compile against a newer version of the
toolkit.
Developers are notified through deprecation and documentation mechanisms of any current or up-
coming changes. This does not mean that application binaries compiled using an older toolkit will
not be supported anymore. Application binaries rely on CUDA Driver API interface and even though
the CUDA Driver API itself may also have changed across toolkit versions, CUDA guarantees Binary
Compatibility of the CUDA Driver API interface.
19.3. Binary Compatibility
We define binary compatibility as a set of guarantees provided by the library, where an application
targeting the said library will continue to work when dynamically linked against a different version of
the library.
The CUDA Driver API has a versioned C-style ABI, which guarantees that applications that were running
against an older driver (for example CUDA 3.2) will still run and function correctly against a modern
driver (for example one shipped with CUDA 11.0). This means that even though an application source
might need to be changed if it has to be recompiled against a newer CUDA Toolkit in order to use the
newer features, replacing the driver components installed in a system with a newer version will always
support existing applications and its functions.
The CUDA Driver API thus is binary-compatible (the OS loader can pick up a newer version and the
application continues to work) but not source-compatible (rebuilding your application against a newer
SDK might require source changes).
19.2. Source Compatibility
85
CUDA C++ Best Practices Guide, Release 12.5
Be-
fore
we
pro-
ceed
fur-
ther
on
this
topic,
it’s
im-
por-
tant
for
de-
vel-
op-
ers
to
un-
der-
stand
the
con-
cept
of
Min-
i-
mum
Driver
Ver-
sion
and
how
that
Fig. 2: CUDA Toolkit and Minimum Driver Versions
may affect them.
Each version of the CUDA Toolkit (and runtime) requires a minimum version of the NVIDIA driver. Appli-
cations compiled against a CUDA Toolkit version will only run on systems with the specified minimum
driver version for that toolkit version. Prior to CUDA 11.0, the minimum driver version for a toolkit was
the same as the driver shipped with that version of the CUDA Toolkit.
So, when an application is built with CUDA 11.0, it can only run on a system with an R450 or later driver.
If such an application is run on a system with the R418 driver installed, CUDA initialization will return
an error as can be seen in the example below.
In this example, the deviceQuery sample is compiled with CUDA 11.1 and is run on a system with R418.
In this scenario, CUDA initialization returns an error due to the minimum driver requirement.
ubuntu@:~∕samples∕1_Utilities∕deviceQuery
$ make
∕usr∕local∕cuda-11.1∕bin∕nvcc -ccbin g++ -I..∕..∕common∕inc
,→arch=compute_35,code=sm_35 -gencode arch=compute_37,code=sm_37 -gencode
,→arch=compute_50,code=sm_50 -gencode arch=compute_52,code=sm_52 -gencode
,→arch=compute_60,code=sm_60 -gencode arch=compute_61,code=sm_61 -gencode
,→arch=compute_70,code=sm_70 -gencode arch=compute_75,code=sm_75 -gencode
,→arch=compute_80,code=sm_80 -gencode arch=compute_86,code=sm_86 -gencode
,→arch=compute_86,code=compute_86 -o deviceQuery.o -c deviceQuery.cpp
86
-m64
-gencode
Chapter 19. CUDA Compatibility Developer’s Guide
(continues on next page)
CUDA C++ Best Practices Guide, Release 12.5
(continued from previous page)
∕usr∕local∕cuda-11.1∕bin∕nvcc -ccbin g++
-gencode arch=compute_35,code=sm_
,→35 -gencode arch=compute_37,code=sm_37 -gencode arch=compute_50,code=sm_50 -gencode
,→arch=compute_52,code=sm_52 -gencode arch=compute_60,code=sm_60 -gencode
,→arch=compute_61,code=sm_61 -gencode arch=compute_70,code=sm_70 -gencode
,→arch=compute_75,code=sm_75 -gencode arch=compute_80,code=sm_80 -gencode
,→arch=compute_86,code=sm_86 -gencode arch=compute_86,code=compute_86 -o deviceQuery
,→deviceQuery.o
-m64
$ nvidia-smi
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 418.165.02
|
Driver Version: 418.165.02
|-------------------------------+----------------------+----------------------+
| GPU
Disp.A | Volatile Uncorr. ECC |
| Fan
Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
0 |
0
|
| N∕A
Default |
+-------------------------------+----------------------+----------------------+
| 00000000:00:1E.0 Off |
0MiB ∕ 15079MiB |
Persistence-M| Bus-Id
Pwr:Usage∕Cap|
CUDA Version: 10.1
Name
Temp
Tesla T4
28W ∕
70W |
Perf
42C
0%
On
P0
GPU
+-----------------------------------------------------------------------------+
GPU Memory |
| Processes:
|
|
Usage
|=============================================================================|
|
|
+-----------------------------------------------------------------------------+
No running processes found
Process name
Type
PID
$ samples∕bin∕x86_64∕linux∕release∕deviceQuery
samples∕bin∕x86_64∕linux∕release∕deviceQuery Starting...
CUDA Device Query (Runtime API) version (CUDART static linking)
cudaGetDeviceCount returned 3
-> initialization error
Result = FAIL
Refer to the CUDA Toolkit Release Notes for details for the minimum driver version and the version of
the driver shipped with the toolkit.
19.3.1. CUDA Binary (cubin) Compatibility
A slightly related but important topic is one of application binary compatibility across GPU architec-
tures in CUDA.
CUDA C++ provides a simple path for users familiar with the C++ programming language to easily write
programs for execution by the device. Kernels can be written using the CUDA instruction set architec-
ture, called PTX, which is described in the PTX reference manual. It is however usually more effective
to use a high-level programming language such as C++. In both cases, kernels must be compiled into
binary code by nvcc (called cubins) to execute on the device.
The cubins are architecture-specific. Binary compatibility for cubins is guaranteed from one compute
capability minor revision to the next one, but not from one compute capability minor revision to the
19.3. Binary Compatibility
87
CUDA C++ Best Practices Guide, Release 12.5
previous one or across major compute capability revisions. In other words, a cubin object generated
for compute capability X.y will only execute on devices of compute capability X.z where zy.
To execute code on devices of specific compute capability, an application must load binary or PTX code
that is compatible with this compute capability. For portability, that is, to be able to execute code on
future GPU architectures with higher compute capability (for which no binary code can be generated
yet), an application must load PTX code that will be just-in-time compiled by the NVIDIA driver for
these future devices.
More information on cubins, PTX and application compatibility can be found in the CUDA C++ Pro-
gramming Guide.
19.4. CUDA Compatibility Across Minor Releases
By leveraging the semantic versioning, starting with CUDA 11, components in the CUDA Toolkit will
remain binary compatible across the minor versions of the toolkit. In order to maintain binary com-
patibility across minor versions, the CUDA runtime no longer bumps up the minimum driver version
required for every minor release - this only happens when a major release is shipped.
One of the main reasons a new toolchain requires a new minimum driver is to handle the JIT compilation
of PTX code and the JIT linking of binary code.
In this section, we will review the usage patterns that may require new user workflows when taking
advantage of the compatibility features of the CUDA platform.
19.4.1. Existing CUDA Applications within Minor Versions
of CUDA
$ nvidia-smi
Name
Temp
Driver Version: 450.80.02
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 450.80.02
|
|-------------------------------+----------------------+----------------------+
Disp.A | Volatile Uncorr. ECC |
| GPU
| Fan
Compute M. |
MIG M. |
|
|===============================+======================+======================|
|
0 |
0
Default |
| N∕A
N∕A |
|
+-------------------------------+----------------------+----------------------+
| 00000000:00:1E.0 Off |
0MiB ∕ 15109MiB |
|
Persistence-M| Bus-Id
Pwr:Usage∕Cap|
|
Memory-Usage | GPU-Util
CUDA Version: 11.0
70W |
|
Tesla T4
9W ∕
Perf
39C
0%
On
P8
|
GPU
+-----------------------------------------------------------------------------+
| Processes:
|
GPU Memory |
|
|
|
Usage
|=============================================================================|
|
|
+-----------------------------------------------------------------------------+
No running processes found
Process name
CI
ID
GI
ID
Type
PID
88
Chapter 19. CUDA Compatibility Developer’s Guide
CUDA C++ Best Practices Guide, Release 12.5
When our CUDA 11.1 application (i.e. cudart 11.1 is statically linked) is run on the system, we see that
it runs successfully even when the driver reports a 11.0 version - that is, without requiring the driver
or other toolkit components to be updated on the system.
$ samples∕bin∕x86_64∕linux∕release∕deviceQuery
samples∕bin∕x86_64∕linux∕release∕deviceQuery Starting...
CUDA Device Query (Runtime API) version (CUDART static linking)
Detected 1 CUDA Capable device(s)
Device 0: "Tesla T4"
CUDA Driver Version ∕ Runtime Version
CUDA Capability Major∕Minor version number:
11.0 ∕ 11.1
7.5
...<snip>...
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 11.0, CUDA Runtime Version =
,→11.1, NumDevs = 1
Result = PASS
By using new CUDA versions, users can benefit from new CUDA programming model APIs, compiler
optimizations and math library features.
The following sections discuss some caveats and considerations.
19.4.1.1 Handling New CUDA Features and Driver APIs
A subset of CUDA APIs don’t need a new driver and they can all be used without any driver depen-
dencies. For example, cuMemMap APIs or any of APIs introduced prior to CUDA 11.0, such as cudaDe-
viceSynchronize, do not require a driver upgrade. To use other CUDA APIs introduced in a minor
release (that require a new driver), one would have to implement fallbacks or fail gracefully. This situa-
tion is not different from what is available today where developers use macros to compile out features
based on CUDA versions. Users should refer to the CUDA headers and documentation for new CUDA
APIs introduced in a release.
When working with a feature exposed in a minor version of the toolkit, the feature might not be avail-
able at runtime if the application is running against an older CUDA driver. Users wishing to take ad-
vantage of such a feature should query its availability with a dynamic check in the code:
static bool hostRegisterFeatureSupported = false;
static bool hostRegisterIsDeviceAddress = false;
static error_t cuFooFunction(int *ptr)
{
int *dptr = null;
if (hostRegisterFeatureSupported) {
cudaHostRegister(ptr, size, flags);
if (hostRegisterIsDeviceAddress) {
qptr = ptr;
}
else {
cudaHostGetDevicePointer(&qptr, ptr, 0);
}
}
else {
19.4. CUDA Compatibility Across Minor Releases
89
(continues on next page)
(continued from previous page)
CUDA C++ Best Practices Guide, Release 12.5
∕∕ cudaMalloc();
∕∕ cudaMemcpy();
}
gemm<<<1,1>>>(dptr);
cudaDeviceSynchronize();
}
int main()
{
∕∕ rest of code here
cudaDeviceGetAttribute(
&hostRegisterFeatureSupported,
cudaDevAttrHostRegisterSupported,
0);
cudaDeviceGetAttribute(
&hostRegisterIsDeviceAddress,
cudaDevAttrCanUseHostPointerForRegisteredMem,
0);
cuFooFunction(∕* malloced pointer *∕);
}
Alternatively the application’s interface might not work at all without a new CUDA driver and then its
best to return an error right away:
#define MIN_VERSION 11010
cudaError_t foo()
{
int version = 0;
cudaGetDriverVersion(&version);
if (version < MIN_VERSION) {
return CUDA_ERROR_INSUFFICIENT_DRIVER;
}
∕∕ proceed as normal
}
A new error code is added to indicate that the functionality is missing from the driver you are running
against: cudaErrorCallRequiresNewerDriver.
19.4.1.2 Using PTX
PTX defines a virtual machine and ISA for general purpose parallel thread execution. PTX programs
are translated at load time to the target hardware instruction set via the JIT Compiler which is part
of the CUDA driver. As PTX is compiled by the CUDA driver, new toolchains will generate PTX that is
not compatible with the older CUDA driver. This is not a problem when PTX is used for future device
compatibility (the most common case), but can lead to issues when used for runtime compilation.
For codes continuing to make use of PTX, in order to support compiling on an older driver, your code
must be first transformed into device code via the static ptxjitcompiler library or NVRTC with the
option of generating code for a specific architecture (e.g. sm_80) rather than a virtual architecture
(e.g. compute_80). For this workflow, a new nvptxcompiler_static library is shipped with the CUDA
Toolkit.
We can see this usage in the following example:
90
Chapter 19. CUDA Compatibility Developer’s Guide
CUDA C++ Best Practices Guide, Release 12.5
char* compilePTXToNVElf()
{
nvPTXCompilerHandle compiler = NULL;
nvPTXCompileResult status;
size_t elfSize, infoSize, errorSize;
char *elf, *infoLog, *errorLog;
int minorVer, majorVer;
const char* compile_options[] = { "--gpu-name=sm_80",
"--device-debug"
};
nvPTXCompilerGetVersion(&majorVer, &minorVer);
nvPTXCompilerCreate(&compiler, (size_t)strlen(ptxCode), ptxCode);
status = nvPTXCompilerCompile(compiler, 2, compile_options);
if (status != NVPTXCOMPILE_SUCCESS) {
nvPTXCompilerGetErrorLogSize(compiler, (void*)&errorSize);
if (errorSize != 0) {
errorLog = (char*)malloc(errorSize+1);
nvPTXCompilerGetErrorLog(compiler, (void*)errorLog);
printf("Error log: %s\n", errorLog);
free(errorLog);
}
exit(1);
}
nvPTXCompilerGetCompiledProgramSize(compiler, &elfSize));
elf = (char*)malloc(elfSize);
nvPTXCompilerGetCompiledProgram(compiler, (void*)elf);
nvPTXCompilerGetInfoLogSize(compiler, (void*)&infoSize);
if (infoSize != 0) {
infoLog = (char*)malloc(infoSize+1);
nvPTXCompilerGetInfoLog(compiler, (void*)infoLog);
printf("Info log: %s\n", infoLog);
free(infoLog);
}
nvPTXCompilerDestroy(&compiler);
return elf;
}
19.4.1.3 Dynamic Code Generation
NVRTC is a runtime compilation library for CUDA C++. It accepts CUDA C++ source code in character
string form and creates handles that can be used to obtain the PTX. The PTX string generated by
NVRTC can be loaded by cuModuleLoadData and cuModuleLoadDataEx.
Dealing with relocatable objects is not yet supported, therefore the cuLink* set of APIs in the CUDA
driver will not work with enhanced compatibility. An upgraded driver matching the CUDA runtime
version is currently required for those APIs.
As mentioned in the PTX section, the compilation of PTX to device code lives along with the CUDA
driver, hence the generated PTX might be newer than what is supported by the driver on the deploy-
ment system. When using NVRTC, it is recommended that the resulting PTX code is first transformed
19.4. CUDA Compatibility Across Minor Releases
91
CUDA C++ Best Practices Guide, Release 12.5
to the final device code via the steps outlined by the PTX user workflow. This ensures your code is
compatible. Alternatively, NVRTC can generate cubins directly starting with CUDA 11.1. Applications
using the new API can load the final device code directly using driver APIs cuModuleLoadData and
cuModuleLoadDataEx.
NVRTC used to support only virtual architectures through the option -arch, since it was only emit-
ting PTX. It will now support actual architectures as well to emit SASS. The interface is augmented to
retrieve either the PTX or cubin if an actual architecture is specified.
The example below shows how an existing example can be adapted to use the new features, guarded
by the USE_CUBIN macro in this case:
#include <nvrtc.h>
#include <cuda.h>
#include <iostream>
void NVRTC_SAFE_CALL(nvrtcResult result) {
if (result != NVRTC_SUCCESS) {
std::cerr << "\nnvrtc error: " << nvrtcGetErrorString(result) << '\n';
std::exit(1);
}
}
void CUDA_SAFE_CALL(CUresult result) {
if (result != CUDA_SUCCESS) {
const char *msg;
cuGetErrorName(result, &msg);
std::cerr << "\ncuda error: " << msg << '\n';
std::exit(1);
}
}
const char *hello = "
extern \"C\" __global__ void hello() {
printf(\"hello world\\n\");
}
int main()
{
\n\
\n\
\n\
\n";
nvrtcProgram prog;
NVRTC_SAFE_CALL(nvrtcCreateProgram(&prog, hello, "hello.cu", 0, NULL, NULL));
#ifdef USE_CUBIN
const char *opts[] = {"-arch=sm_70"};
#else
const char *opts[] = {"-arch=compute_70"};
#endif
nvrtcResult compileResult = nvrtcCompileProgram(prog, 1, opts);
size_t logSize;
NVRTC_SAFE_CALL(nvrtcGetProgramLogSize(prog, &logSize));
char *log = new char[logSize];
NVRTC_SAFE_CALL(nvrtcGetProgramLog(prog, log));
std::cout << log << '\n';
delete[] log;
if (compileResult != NVRTC_SUCCESS)
exit(1);
size_t codeSize;
#ifdef USE_CUBIN
NVRTC_SAFE_CALL(nvrtcGetCUBINSize(prog, &codeSize));
(continues on next page)
92
Chapter 19. CUDA Compatibility Developer’s Guide
CUDA C++ Best Practices Guide, Release 12.5
(continued from previous page)
char *code = new char[codeSize];
NVRTC_SAFE_CALL(nvrtcGetCUBIN(prog, code));
#else
NVRTC_SAFE_CALL(nvrtcGetPTXSize(prog, &codeSize));
char *code = new char[codeSize];
NVRTC_SAFE_CALL(nvrtcGetPTX(prog, code));
#endif
NVRTC_SAFE_CALL(nvrtcDestroyProgram(&prog));
CUdevice cuDevice;
CUcontext context;
CUmodule module;
CUfunction kernel;
CUDA_SAFE_CALL(cuInit(0));
CUDA_SAFE_CALL(cuDeviceGet(&cuDevice, 0));
CUDA_SAFE_CALL(cuCtxCreate(&context, 0, cuDevice));
CUDA_SAFE_CALL(cuModuleLoadDataEx(&module, code, 0, 0, 0));
CUDA_SAFE_CALL(cuModuleGetFunction(&kernel, module, "hello"));
CUDA_SAFE_CALL(cuLaunchKernel(kernel, 1, 1, 1, 1, 1, 1, 0, NULL, NULL, 0));
CUDA_SAFE_CALL(cuCtxSynchronize());
CUDA_SAFE_CALL(cuModuleUnload(module));
CUDA_SAFE_CALL(cuCtxDestroy(context));
delete[] code;
}
19.4.1.4 Recommendations for building a minor-version compatible library
We recommend that the CUDA runtime be statically linked to minimize dependencies. Verify that your
library doesn’t leak dependencies, breakages, namespaces, etc. outside your established ABI contract.
Follow semantic versioning for your library’s soname. Having a semantically versioned ABI means the
interfaces need to be maintained and versioned. The library should follow semantic rules and incre-
ment the version number when a change is made that affects this ABI contract. Missing dependencies
is also a binary compatibility break, hence you should provide fallbacks or guards for functionality that
depends on those interfaces. Increment major versions when there are ABI breaking changes such as
API deprecation and modifications. New APIs can be added in minor versions.
Conditionally use features to remain compatible against older drivers. If no new features are used (or
if they are used conditionally with fallbacks provided) you’ll be able to remain compatible.
Don’t expose ABI structures that can change. A pointer to a structure with a size embedded is a better
solution.
When linking with dynamic libraries from the toolkit, the library must be equal to or newer than what
is needed by any one of the components involved in the linking of your application. For example, if you
link against the CUDA 11.1 dynamic runtime, and use functionality from 11.1, as well as a separate
shared library that was linked against the CUDA 11.2 dynamic runtime that requires 11.2 functionality,
the final link step must include a CUDA 11.2 or newer dynamic runtime.
19.4. CUDA Compatibility Across Minor Releases
93
CUDA C++ Best Practices Guide, Release 12.5
19.4.1.5 Recommendations for taking advantage of minor version compatibility in your application
Certain functionality might not be available so you should query where applicable. This is common for
building applications that are GPU architecture, platform and compiler agnostic. However we now add
“the underlying driver” to that mix.
As with the previous section on library building recommendations, if using the CUDA runtime, we rec-
ommend linking to the CUDA runtime statically when building your application. When using the driver
APIs directly, we recommend using the new driver entry point access API (cuGetProcAddress) doc-
umented here: CUDA Driver API :: CUDA Toolkit Documentation.
When using a shared or static library, follow the release notes of said library to determine if the library
supports minor version compatibility.
94
Chapter 19. CUDA Compatibility Developer’s Guide
Chapter 20. Preparing for Deployment
20.1. Testing for CUDA Availability
When deploying a CUDA application, it is often desirable to ensure that the application will continue
to function properly even if the target machine does not have a CUDA-capable GPU and/or a sufficient
version of the NVIDIA Driver installed. (Developers targeting a single machine with known configura-
tion may choose to skip this section.)
Detecting a CUDA-Capable GPU
When an application will be deployed to target machines of arbitrary/unknown configuration, the ap-
plication should explicitly test for the existence of a CUDA-capable GPU in order to take appropri-
ate action when no such device is available. The cudaGetDeviceCount() function can be used to
query for the number of available devices. Like all CUDA Runtime API functions, this function will fail
gracefully and return cudaErrorNoDevice to the application if there is no CUDA-capable GPU or cu-
daErrorInsufficientDriver if there is not an appropriate version of the NVIDIA Driver installed.
If cudaGetDeviceCount() reports an error, the application should fall back to an alternative code
path.
A system with multiple GPUs may contain GPUs of different hardware versions and capabilities. When
using multiple GPUs from the same application, it is recommended to use GPUs of the same type,
rather than mixing hardware generations. The cudaChooseDevice() function can be used to select
the device that most closely matches a desired set of features.
Detecting Hardware and Software Configuration
When an application depends on the availability of certain hardware or software capabilities to enable
certain functionality, the CUDA API can be queried for details about the configuration of the available
device and for the installed software versions.
The cudaGetDeviceProperties() function reports various features of the available devices, includ-
ing the CUDA Compute Capability of the device (see also the Compute Capabilities section of the CUDA
C++ Programming Guide). See Version Management for details on how to query the available CUDA
software API versions.
95
CUDA C++ Best Practices Guide, Release 12.5
20.2. Error Handling
All CUDA Runtime API calls return an error code of type cudaError_t; the return value will be equal
to cudaSuccess if no errors have occurred. (The exceptions to this are kernel launches, which return
void, and cudaGetErrorString(), which returns a character string describing the cudaError_t
code that was passed into it.) The CUDA Toolkit libraries (cuBLAS, cuFFT, etc.) likewise return their
own sets of error codes.
Since some CUDA API calls and all kernel launches are asynchronous with respect to the host code, er-
rors may be reported to the host asynchronously as well; often this occurs the next time the host and
device synchronize with each other, such as during a call to cudaMemcpy() or to cudaDeviceSyn-
chronize().
Always check the error return values on all CUDA API functions, even for functions that are not ex-
pected to fail, as this will allow the application to detect and recover from errors as soon as possible
should they occur. To check for errors occurring during kernel launches using the <<<...>>> syntax,
which does not return any error code, the return code of cudaGetLastError() should be checked
immediately after the kernel launch. Applications that do not check for CUDA API errors could at times
run to completion without having noticed that the data calculated by the GPU is incomplete, invalid,
or uninitialized.
Note: The CUDA Toolkit Samples provide several helper functions for error checking with the various
CUDA APIs; these helper functions are located in the samples∕common∕inc∕helper_cuda.h file in
the CUDA Toolkit.
20.3. Building for Maximum Compatibility
Each generation of CUDA-capable device has an associated compute capability version that indicates
the feature set supported by the device (see CUDA Compute Capability). One or more compute ca-
pability versions can be specified to the nvcc compiler while building a file; compiling for the native
compute capability for the target GPU(s) of the application is important to ensure that application
kernels achieve the best possible performance and are able to use the features that are available on a
given generation of GPU.
When an application is built for multiple compute capabilities simultaneously (using several instances
of the -gencode flag to nvcc), the binaries for the specified compute capabilities are combined into
the executable, and the CUDA Driver selects the most appropriate binary at runtime according to the
compute capability of the present device. If an appropriate native binary (cubin) is not available, but
the intermediate PTX code (which targets an abstract virtual instruction set and is used for forward-
compatibility) is available, then the kernel will be compiled Just In Time (JIT) (see Compiler JIT Cache
Management Tools) from the PTX to the native cubin for the device. If the PTX is also not available,
then the kernel launch will fail.
Windows
nvcc.exe -ccbin "C:\vs2008\VC\bin"
-Xcompiler "∕EHsc ∕W3 ∕nologo ∕O2 ∕Zi ∕MT"
-gencode=arch=compute_30,code=sm_30
-gencode=arch=compute_35,code=sm_35
-gencode=arch=compute_50,code=sm_50
96
Chapter 20. Preparing for Deployment
(continues on next page)
CUDA C++ Best Practices Guide, Release 12.5
(continued from previous page)
-gencode=arch=compute_60,code=sm_60
-gencode=arch=compute_70,code=sm_70
-gencode=arch=compute_75,code=sm_75
-gencode=arch=compute_75,code=compute_75
--compile -o "Release\mykernel.cu.obj" "mykernel.cu"
Mac/Linux
∕usr∕local∕cuda∕bin∕nvcc
-gencode=arch=compute_30,code=sm_30
-gencode=arch=compute_35,code=sm_35
-gencode=arch=compute_50,code=sm_50
-gencode=arch=compute_60,code=sm_60
-gencode=arch=compute_70,code=sm_70
-gencode=arch=compute_75,code=sm_75
-gencode=arch=compute_75,code=compute_75
-O2 -o mykernel.o -c mykernel.cu
Alternatively, the nvcc command-line option -arch=sm_XX can be used as a shorthand equivalent to
the following more explicit -gencode= command-line options described above:
-gencode=arch=compute_XX,code=sm_XX
-gencode=arch=compute_XX,code=compute_XX
However, while the -arch=sm_XX command-line option does result in inclusion of a PTX back-end
target by default (due to the code=compute_XX target it implies), it can only specify a single target
cubin architecture at a time, and it is not possible to use multiple -arch= options on the same nvcc
command line, which is why the examples above use -gencode= explicitly.
20.4. Distributing the CUDA Runtime and
Libraries
CUDA applications are built against the CUDA Runtime library, which handles device, memory, and ker-
nel management. Unlike the CUDA Driver, the CUDA Runtime guarantees neither forward nor back-
ward binary compatibility across versions. It is therefore best to redistribute the CUDA Runtime library
with the application when using dynamic linking or else to statically link against the CUDA Runtime.
This will ensure that the executable will be able to run even if the user does not have the same CUDA
Toolkit installed that the application was built against.
Note: When statically linking to the CUDA Runtime, multiple versions of the runtime can peacably
coexist in the same application process simultaneously; for example, if an application uses one version
of the CUDA Runtime, and a plugin to that application is statically linked to a different version, that is
perfectly acceptable, as long as the installed NVIDIA Driver is sufficient for both.
20.4. Distributing the CUDA Runtime and Libraries
97
CUDA C++ Best Practices Guide, Release 12.5
Statically-linked CUDA Runtime
The easiest option is to statically link against the CUDA Runtime. This is the default if using nvcc to
link in CUDA 5.5 and later. Static linking makes the executable slightly larger, but it ensures that the
correct version of runtime library functions are included in the application binary without requiring
separate redistribution of the CUDA Runtime library.
Dynamically-linked CUDA Runtime
If static linking against the CUDA Runtime is impractical for some reason, then a dynamically-linked
version of the CUDA Runtime library is also available. (This was the default and only option provided in
CUDA versions 5.0 and earlier.)
To use dynamic linking with the CUDA Runtime when using the nvcc from CUDA 5.5 or later to link the
application, add the --cudart=shared flag to the link command line; otherwise the statically-linked
CUDA Runtime library is used by default.
After the application is dynamically linked against the CUDA Runtime, this version of the runtime library
should be bundled with the application. It can be copied into the same directory as the application
executable or into a subdirectory of that installation path.
Other CUDA Libraries
Although the CUDA Runtime provides the option of static linking, some libraries included in the CUDA
Toolkit are available only in dynamically-linked form. As with the dynamically-linked version of the
CUDA Runtime library, these libraries should be bundled with the application executable when dis-
tributing that application.
20.4.1. CUDA Toolkit Library Redistribution
The CUDA Toolkit’s End-User License Agreement (EULA) allows for redistribution of many of the CUDA
libraries under certain terms and conditions. This allows applications that depend on these libraries
to redistribute the exact versions of the libraries against which they were built and tested, thereby
avoiding any trouble for end users who might have a different version of the CUDA Toolkit (or perhaps
none at all) installed on their machines. Please refer to the EULA for details.
Note: This does not apply to the NVIDIA Driver; the end user must still download and install an NVIDIA
Driver appropriate to their GPU(s) and operating system.
98
Chapter 20. Preparing for Deployment
CUDA C++ Best Practices Guide, Release 12.5
20.4.1.1 Which Files to Redistribute
When redistributing the dynamically-linked versions of one or more CUDA libraries, it is important to
identify the exact files that need to be redistributed. The following examples use the cuBLAS library
from CUDA Toolkit 5.5 as an illustration:
Linux
In a shared library on Linux, there is a string field called the SONAME that indicates the binary compati-
bility level of the library. The SONAME of the library against which the application was built must match
the filename of the library that is redistributed with the application.
For example, in the standard CUDA Toolkit installation, the files libcublas.so and libcublas.so.
5.5 are both symlinks pointing to a specific build of cuBLAS, which is named like libcublas.so.5.
5.x, where x is the build number (e.g., libcublas.so.5.5.17). However, the SONAME of this library
is given as “libcublas.so.5.5”:
$ objdump -p ∕usr∕local∕cuda∕lib64∕libcublas.so | grep SONAME
SONAME
libcublas.so.5.5
Because of this, even if -lcublas (with no version number specified) is used when linking the appli-
cation, the SONAME found at link time implies that “libcublas.so.5.5” is the name of the file that
the dynamic loader will look for when loading the application and therefore must be the name of the
file (or a symlink to the same) that is redistributed with the application.
The ldd tool is useful for identifying the exact filenames of the libraries that the application expects
to find at runtime as well as the path, if any, of the copy of that library that the dynamic loader would
select when loading the application given the current library search path:
$ ldd a.out | grep libcublas
libcublas.so.5.5 => ∕usr∕local∕cuda∕lib64∕libcublas.so.5.5
Mac
In a shared library on Mac OS X, there is a field called the install name that indicates the expected
installation path and filename the library; the CUDA libraries also use this filename to indicate binary
compatibility. The value of this field is propagated into an application built against the library and is
used to locate the library of the correct version at runtime.
For example, if the install name of the cuBLAS library is given as @rpath∕libcublas.5.5.dylib,
then the library is version 5.5 and the copy of this library redistributed with the application must be
named libcublas.5.5.dylib, even though only -lcublas (with no version number specified) is
used at link time. Furthermore, this file should be installed into the @rpath of the application; see
Where to Install Redistributed CUDA Libraries.
To view a library’s install name, use the otool -L command:
$ otool -L a.out
a.out:
@rpath∕libcublas.5.5.dylib (...)
Windows
The binary compatibility version of the CUDA libraries on Windows is indicated as part of the filename.
For example, a 64-bit application linked to cuBLAS 5.5 will look for cublas64_55.dll at runtime, so
this is the file that should be redistributed with that application, even though cublas.lib is the file
that the application is linked against. For 32-bit applications, the file would be cublas32_55.dll.
20.4. Distributing the CUDA Runtime and Libraries
99
CUDA C++ Best Practices Guide, Release 12.5
To verify the exact DLL filename that the application expects to find at runtime, use the dumpbin tool
from the Visual Studio command prompt:
$ dumpbin ∕IMPORTS a.exe
Microsoft (R) COFF∕PE Dumper Version 10.00.40219.01
Copyright (C) Microsoft Corporation.
All rights reserved.
Dump of file a.exe
File Type: EXECUTABLE IMAGE
Section contains the following imports:
...
cublas64_55.dll
...
20.4.1.2 Where to Install Redistributed CUDA Libraries
Once the correct library files are identified for redistribution, they must be configured for installation
into a location where the application will be able to find them.
On Windows, if the CUDA Runtime or other dynamically-linked CUDA Toolkit library is placed in the
same directory as the executable, Windows will locate it automatically. On Linux and Mac, the -rpath
linker option should be used to instruct the executable to search its local path for these libraries before
searching the system paths:
Linux/Mac
nvcc -I $(CUDA_HOME)∕include
-Xlinker "-rpath '$ORIGIN'" --cudart=shared
-o myprogram myprogram.cu
Windows
nvcc.exe -ccbin "C:\vs2008\VC\bin"
-Xcompiler "∕EHsc ∕W3 ∕nologo ∕O2 ∕Zi ∕MT" --cudart=shared
-o "Release\myprogram.exe" "myprogram.cu"
It may be necessary to adjust the value of -ccbin to reflect the location of your Visual Studio
Note:
installation.
To specify an alternate path where the libraries will be distributed, use linker options similar to those
below:
Linux/Mac
nvcc -I $(CUDA_HOME)∕include
-Xlinker "-rpath '$ORIGIN∕lib'" --cudart=shared
-o myprogram myprogram.cu
Windows
100
Chapter 20. Preparing for Deployment
CUDA C++ Best Practices Guide, Release 12.5
nvcc.exe -ccbin "C:\vs2008\VC\bin"
-Xcompiler "∕EHsc ∕W3 ∕nologo ∕O2 ∕Zi ∕MT ∕DELAY" --cudart=shared
-o "Release\myprogram.exe" "myprogram.cu"
For Linux and Mac, the -rpath option is used as before. For Windows, the ∕DELAY option is used; this
requires that the application call SetDllDirectory() before the first call to any CUDA API function
in order to specify the directory containing the CUDA DLLs.
Note: For Windows 8, SetDefaultDLLDirectories() and AddDllDirectory() should be used
instead of SetDllDirectory(). Please see the MSDN documentation for these routines for more
information.
20.4. Distributing the CUDA Runtime and Libraries
101
CUDA C++ Best Practices Guide, Release 12.5
102
Chapter 20. Preparing for Deployment
Chapter 21. Deployment Infrastructure
Tools
21.1. Nvidia-SMI
The NVIDIA System Management Interface (nvidia-smi) is a command line utility that aids in the
management and monitoring of NVIDIA GPU devices. This utility allows administrators to query GPU
device state and, with the appropriate privileges, permits administrators to modify GPU device state.
nvidia-smi is targeted at Tesla and certain Quadro GPUs, though limited support is also available
on other NVIDIA GPUs. nvidia-smi ships with NVIDIA GPU display drivers on Linux, and with 64-bit
Windows Server 2008 R2 and Windows 7. nvidia-smi can output queried information as XML or as
human-readable plain text either to standard output or to a file. See the nvidia-smi documenation for
details. Please note that new versions of nvidia-smi are not guaranteed to be backward-compatible
with previous versions.
21.1.1. Queryable state
ECC error counts
Both correctable single-bit and detectable double-bit errors are reported. Error counts are pro-
vided for both the current boot cycle and the lifetime of the GPU.
GPU utilization
Current utilization rates are reported for both the compute resources of the GPU and the memory
interface.
Active compute process
The list of active processes running on the GPU is reported, along with the corresponding process
name/ID and allocated GPU memory.
Clocks and performance state
Max and current clock rates are reported for several important clock domains, as well as the
current GPU performance state (pstate).
Temperature and fan speed
The current GPU core temperature is reported, along with fan speeds for products with active
cooling.
Power management
The current board power draw and power limits are reported for products that report these mea-
surements.
103
CUDA C++ Best Practices Guide, Release 12.5
Identification
Various dynamic and static information is reported, including board serial numbers, PCI device
IDs, VBIOS/Inforom version numbers and product names.
21.1.2. Modifiable state
ECC mode
Enable and disable ECC reporting.
ECC reset
Clear single-bit and double-bit ECC error counts.
Compute mode
Indicate whether compute processes can run on the GPU and whether they run exclusively or
concurrently with other compute processes.
Persistence mode
Indicate whether the NVIDIA driver stays loaded when no applications are connected to the GPU.
It is best to enable this option in most circumstances.
GPU reset
Reinitialize the GPU hardware and software state via a secondary bus reset.
21.2. NVML
The NVIDIA Management Library (NVML) is a C-based interface that provides direct access to the
queries and commands exposed via nvidia-smi intended as a platform for building 3rd-party system
management applications. The NVML API is shipped with the CUDA Toolkit (since version 8.0) and is
also available standalone on the NVIDIA developer website as part of the GPU Deployment Kit through
a single header file accompanied by PDF documentation, stub libraries, and sample applications; see
https://developer.nvidia.com/gpu-deployment-kit. Each new version of NVML is backward-compatible.
An additional set of Perl and Python bindings are provided for the NVML API. These bindings expose the
same features as the C-based interface and also provide backwards compatibility. The Perl bindings
are provided via CPAN and the Python bindings via PyPI.
All of these products (nvidia-smi, NVML, and the NVML language bindings) are updated with each
new CUDA release and provide roughly the same functionality.
See https://developer.nvidia.com/nvidia-management-library-nvml for additional information.
21.3. Cluster Management Tools
Managing your GPU cluster will help achieve maximum GPU utilization and help you and your users
extract the best possible performance. Many of the industry’s most popular cluster management
tools support CUDA GPUs via NVML. For a listing of some of these tools, see https://developer.nvidia.
com/cluster-management.
104
Chapter 21. Deployment Infrastructure Tools
CUDA C++ Best Practices Guide, Release 12.5
21.4. Compiler JIT Cache Management Tools
Any PTX device code loaded by an application at runtime is compiled further to binary code by the
device driver. This is called just-in-time compilation (JIT). Just-in-time compilation increases application
load time but allows applications to benefit from latest compiler improvements. It is also the only way
for applications to run on devices that did not exist at the time the application was compiled.
When JIT compilation of PTX device code is used, the NVIDIA driver caches the resulting binary code on
disk. Some aspects of this behavior such as cache location and maximum cache size can be controlled
via the use of environment variables; see Just in Time Compilation of the CUDA C++ Programming
Guide.
21.5. CUDA_VISIBLE_DEVICES
It is possible to rearrange the collection of installed CUDA devices that will be visible to and enumerated
by a CUDA application prior to the start of that application by way of the CUDA_VISIBLE_DEVICES
environment variable.
Devices to be made visible to the application should be included as a comma-separated list in terms
of the system-wide list of enumerable devices. For example, to use only devices 0 and 2 from the
system-wide list of devices, set CUDA_VISIBLE_DEVICES=0,2 before launching the application. The
application will then enumerate these devices as device 0 and device 1, respectively.
21.4. Compiler JIT Cache Management Tools
105
CUDA C++ Best Practices Guide, Release 12.5
106
Chapter 21. Deployment Infrastructure Tools
Chapter 22. Recommendations and
Best Practices
This chapter contains a summary of the recommendations for optimization that are explained in this
document.
22.1. Overall Performance Optimization
Strategies
Performance optimization revolves around three basic strategies:
▶ Maximizing parallel execution
▶ Optimizing memory usage to achieve maximum memory bandwidth
▶ Optimizing instruction usage to achieve maximum instruction throughput
Maximizing parallel execution starts with structuring the algorithm in a way that exposes as much par-
allelism as possible. Once the parallelism of the algorithm has been exposed, it needs to be mapped
to the hardware as efficiently as possible. This is done by carefully choosing the execution configu-
ration of each kernel launch. The application should also maximize parallel execution at a higher level
by explicitly exposing concurrent execution on the device through streams, as well as maximizing con-
current execution between the host and the device.
Optimizing memory usage starts with minimizing data transfers between the host and the device
because those transfers have much lower bandwidth than internal device data transfers. Kernel access
to global memory also should be minimized by maximizing the use of shared memory on the device.
Sometimes, the best optimization might even be to avoid any data transfer in the first place by simply
recomputing the data whenever it is needed.
The effective bandwidth can vary by an order of magnitude depending on the access pattern for each
type of memory. The next step in optimizing memory usage is therefore to organize memory accesses
according to the optimal memory access patterns. This optimization is especially important for global
memory accesses, because latency of access costs hundreds of clock cycles. Shared memory ac-
cesses, in counterpoint, are usually worth optimizing only when there exists a high degree of bank
conflicts.
As for optimizing instruction usage, the use of arithmetic instructions that have low throughput should
be avoided. This suggests trading precision for speed when it does not affect the end result, such as
using intrinsics instead of regular functions or single precision instead of double precision. Finally, par-
107
CUDA C++ Best Practices Guide, Release 12.5
ticular attention must be paid to control flow instructions due to the SIMT (single instruction multiple
thread) nature of the device.
108
Chapter 22. Recommendations and Best Practices
Chapter 23. nvcc Compiler Switches
23.1. nvcc
The NVIDIA nvcc compiler driver converts .cu files into C++ for the host system and CUDA assembly
or binary instructions for the device. It supports a number of command-line parameters, of which the
following are especially useful for optimization and related best practices:
▶ -maxrregcount=N specifies the maximum number of registers kernels can use at a per-file level.
See Register Pressure. (See also the__launch_bounds__ qualifier discussed in Execution Con-
figuration of the CUDA C++ Programming Guide to control the number of registers used on a
per-kernel basis.)
▶ --ptxas-options=-v or -Xptxas=-v lists per-kernel register, shared, and constant memory
usage.
▶ -ftz=true (denormalized numbers are flushed to zero)
▶ -prec-div=false (less precise division)
▶ -prec-sqrt=false (less precise square root)
▶ -use_fast_math compiler option of nvcc coerces every functionName() call to the equivalent
__functionName() call. This makes the code run faster at the cost of diminished precision and
accuracy. See Math Libraries.
109
CUDA C++ Best Practices Guide, Release 12.5
110
Chapter 23. nvcc Compiler Switches
Chapter 24. Notices
24.1. Notice
This document is provided for information purposes only and shall not be regarded as a warranty of a
certain functionality, condition, or quality of a product. NVIDIA Corporation (“NVIDIA”) makes no repre-
sentations or warranties, expressed or implied, as to the accuracy or completeness of the information
contained in this document and assumes no responsibility for any errors contained herein. NVIDIA shall
have no liability for the consequences or use of such information or for any infringement of patents
or other rights of third parties that may result from its use. This document is not a commitment to
develop, release, or deliver any Material (defined below), code, or functionality.
NVIDIA reserves the right to make corrections, modifications, enhancements, improvements, and any
other changes to this document, at any time without notice.
Customer should obtain the latest relevant information before placing orders and should verify that
such information is current and complete.
NVIDIA products are sold subject to the NVIDIA standard terms and conditions of sale supplied at the
time of order acknowledgement, unless otherwise agreed in an individual sales agreement signed by
authorized representatives of NVIDIA and customer (“Terms of Sale”). NVIDIA hereby expressly objects
to applying any customer general terms and conditions with regards to the purchase of the NVIDIA
product referenced in this document. No contractual obligations are formed either directly or indirectly
by this document.
NVIDIA products are not designed, authorized, or warranted to be suitable for use in medical, military,
aircraft, space, or life support equipment, nor in applications where failure or malfunction of the NVIDIA
product can reasonably be expected to result in personal injury, death, or property or environmental
damage. NVIDIA accepts no liability for inclusion and/or use of NVIDIA products in such equipment or
applications and therefore such inclusion and/or use is at customer’s own risk.
NVIDIA makes no representation or warranty that products based on this document will be suitable for
any specified use. Testing of all parameters of each product is not necessarily performed by NVIDIA.
It is customer’s sole responsibility to evaluate and determine the applicability of any information con-
tained in this document, ensure the product is suitable and fit for the application planned by customer,
and perform the necessary testing for the application in order to avoid a default of the application or
the product. Weaknesses in customer’s product designs may affect the quality and reliability of the
NVIDIA product and may result in additional or different conditions and/or requirements beyond those
contained in this document. NVIDIA accepts no liability related to any default, damage, costs, or prob-
lem which may be based on or attributable to: (i) the use of the NVIDIA product in any manner that is
contrary to this document or (ii) customer product designs.
No license, either expressed or implied, is granted under any NVIDIA patent right, copyright, or other
NVIDIA intellectual property right under this document.
Information published by NVIDIA regarding
third-party products or services does not constitute a license from NVIDIA to use such products or
111
CUDA C++ Best Practices Guide, Release 12.5
services or a warranty or endorsement thereof. Use of such information may require a license from a
third party under the patents or other intellectual property rights of the third party, or a license from
NVIDIA under the patents or other intellectual property rights of NVIDIA.
Reproduction of information in this document is permissible only if approved in advance by NVIDIA
in writing, reproduced without alteration and in full compliance with all applicable export laws and
regulations, and accompanied by all associated conditions, limitations, and notices.
THIS DOCUMENT AND ALL NVIDIA DESIGN SPECIFICATIONS, REFERENCE BOARDS, FILES, DRAWINGS,
DIAGNOSTICS, LISTS, AND OTHER DOCUMENTS (TOGETHER AND SEPARATELY, “MATERIALS”) ARE
BEING PROVIDED “AS IS.” NVIDIA MAKES NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR
OTHERWISE WITH RESPECT TO THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WAR-
RANTIES OF NONINFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
TO THE EXTENT NOT PROHIBITED BY LAW, IN NO EVENT WILL NVIDIA BE LIABLE FOR ANY DAMAGES,
INCLUDING WITHOUT LIMITATION ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, PUNITIVE, OR CON-
SEQUENTIAL DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARIS-
ING OUT OF ANY USE OF THIS DOCUMENT, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGES. Notwithstanding any damages that customer might incur for any reason whatso-
ever, NVIDIA’s aggregate and cumulative liability towards customer for the products described herein
shall be limited in accordance with the Terms of Sale for the product.
24.2. OpenCL
OpenCL is a trademark of Apple Inc. used under license to the Khronos Group Inc.
24.3. Trademarks
NVIDIA and the NVIDIA logo are trademarks or registered trademarks of NVIDIA Corporation in the
U.S. and other countries. Other company and product names may be trademarks of the respective
companies with which they are associated.
Copyright
©2007-2024, NVIDIA Corporation & affiliates. All rights reserved
112
Chapter 24. Notices
|