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
|
/****************************************************************/
/* Parallel Combinatorial BLAS Library (for Graph Computations) */
/* version 1.6 -------------------------------------------------*/
/* date: 6/15/2017 ---------------------------------------------*/
/* authors: Ariful Azad, Aydin Buluc --------------------------*/
/****************************************************************/
/*
Copyright (c) 2010-2017, The Regents of the University of California
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef _PAR_FRIENDS_H_
#define _PAR_FRIENDS_H_
#include "mpi.h"
#include <iostream>
#include <cstdarg>
#include "SpParMat.h"
#include "SpParMat3D.h"
#include "SpParHelper.h"
#include "MPIType.h"
#include "Friends.h"
#include "OptBuf.h"
#include "mtSpGEMM.h"
#include "MultiwayMerge.h"
#include <unistd.h>
#include <type_traits>
namespace combblas {
template <class IT, class NT, class DER>
class SpParMat;
/*************************************************************************************************/
/**************************** FRIEND FUNCTIONS FOR PARALLEL CLASSES ******************************/
/*************************************************************************************************/
/**
** Concatenate all the FullyDistVec<IT,NT> objects into a single one
**/
template <typename IT, typename NT>
FullyDistVec<IT,NT> Concatenate ( std::vector< FullyDistVec<IT,NT> > & vecs)
{
if(vecs.size() < 1)
{
SpParHelper::Print("Warning: Nothing to concatenate, returning empty ");
return FullyDistVec<IT,NT>();
}
else if (vecs.size() < 2)
{
return vecs[1];
}
else
{
typename std::vector< FullyDistVec<IT,NT> >::iterator it = vecs.begin();
std::shared_ptr<CommGrid> commGridPtr = it->getcommgrid();
MPI_Comm World = commGridPtr->GetWorld();
IT nglen = it->TotalLength(); // new global length
IT cumloclen = it->MyLocLength(); // existing cumulative local lengths
++it;
for(; it != vecs.end(); ++it)
{
if(*(commGridPtr) != *(it->getcommgrid()))
{
SpParHelper::Print("Grids are not comparable for FullyDistVec<IT,NT>::EWiseApply\n");
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
}
nglen += it->TotalLength();
cumloclen += it->MyLocLength();
}
FullyDistVec<IT,NT> ConCat (commGridPtr, nglen, NT());
int nprocs = commGridPtr->GetSize();
std::vector< std::vector< NT > > data(nprocs);
std::vector< std::vector< IT > > inds(nprocs);
IT gloffset = 0;
for(it = vecs.begin(); it != vecs.end(); ++it)
{
IT loclen = it->LocArrSize();
for(IT i=0; i < loclen; ++i)
{
IT locind;
IT loffset = it->LengthUntil();
int owner = ConCat.Owner(gloffset+loffset+i, locind);
data[owner].push_back(it->arr[i]);
inds[owner].push_back(locind);
}
gloffset += it->TotalLength();
}
int * sendcnt = new int[nprocs];
int * sdispls = new int[nprocs];
for(int i=0; i<nprocs; ++i)
sendcnt[i] = (int) data[i].size();
int * rdispls = new int[nprocs];
int * recvcnt = new int[nprocs];
MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, World); // share the request counts
sdispls[0] = 0;
rdispls[0] = 0;
for(int i=0; i<nprocs-1; ++i)
{
sdispls[i+1] = sdispls[i] + sendcnt[i];
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
IT totrecv = std::accumulate(recvcnt,recvcnt+nprocs,static_cast<IT>(0));
NT * senddatabuf = new NT[cumloclen];
for(int i=0; i<nprocs; ++i)
{
std::copy(data[i].begin(), data[i].end(), senddatabuf+sdispls[i]);
std::vector<NT>().swap(data[i]); // delete data vectors
}
NT * recvdatabuf = new NT[totrecv];
MPI_Alltoallv(senddatabuf, sendcnt, sdispls, MPIType<NT>(), recvdatabuf, recvcnt, rdispls, MPIType<NT>(), World); // send data
delete [] senddatabuf;
IT * sendindsbuf = new IT[cumloclen];
for(int i=0; i<nprocs; ++i)
{
std::copy(inds[i].begin(), inds[i].end(), sendindsbuf+sdispls[i]);
std::vector<IT>().swap(inds[i]); // delete inds vectors
}
IT * recvindsbuf = new IT[totrecv];
MPI_Alltoallv(sendindsbuf, sendcnt, sdispls, MPIType<IT>(), recvindsbuf, recvcnt, rdispls, MPIType<IT>(), World); // send new inds
DeleteAll(sendindsbuf, sendcnt, sdispls);
for(int i=0; i<nprocs; ++i)
{
for(int j = rdispls[i]; j < rdispls[i] + recvcnt[i]; ++j)
{
ConCat.arr[recvindsbuf[j]] = recvdatabuf[j];
}
}
DeleteAll(recvindsbuf, recvcnt, rdispls);
return ConCat;
}
}
template <typename MATRIXA, typename MATRIXB>
bool CheckSpGEMMCompliance(const MATRIXA & A, const MATRIXB & B)
{
if(A.getncol() != B.getnrow())
{
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match"<< std::endl;
outs << A.getncol() << " != " << B.getnrow() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
return false;
}
if((void*) &A == (void*) &B)
{
std::ostringstream outs;
outs << "Can not multiply, inputs alias (make a temporary copy of one of them first)"<< std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, MATRIXALIAS);
return false;
}
return true;
}
// Combined logic for prune, recovery, and select
template <typename IT, typename NT, typename DER>
void MCLPruneRecoverySelect(SpParMat<IT,NT,DER> & A, NT hardThreshold, IT selectNum, IT recoverNum, NT recoverPct, int kselectVersion)
{
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
#ifdef TIMING
double t0, t1;
#endif
// Prune and create a new pruned matrix
SpParMat<IT,NT,DER> PrunedA = A.Prune(std::bind2nd(std::less_equal<NT>(), hardThreshold), false);
// column-wise statistics of the pruned matrix
FullyDistVec<IT,NT> colSums = PrunedA.Reduce(Column, std::plus<NT>(), 0.0);
FullyDistVec<IT,NT> nnzPerColumnUnpruned = A.Reduce(Column, std::plus<NT>(), 0.0, [](NT val){return 1.0;});
FullyDistVec<IT,NT> nnzPerColumn = PrunedA.Reduce(Column, std::plus<NT>(), 0.0, [](NT val){return 1.0;});
//FullyDistVec<IT,NT> pruneCols(A.getcommgrid(), A.getncol(), hardThreshold);
FullyDistVec<IT,NT> pruneCols(nnzPerColumn);
pruneCols = hardThreshold;
PrunedA.FreeMemory();
FullyDistSpVec<IT,NT> recoverCols(nnzPerColumn, std::bind2nd(std::less<NT>(), recoverNum));
// recover only when nnzs in unprunned columns are greater than nnzs in pruned column
recoverCols = EWiseApply<NT>(recoverCols, nnzPerColumnUnpruned,
[](NT spval, NT dval){return spval;},
[](NT spval, NT dval){return dval > spval;},
false, NT());
recoverCols = recoverPct;
// columns with nnz < r AND sum < recoverPct (pct)
recoverCols = EWiseApply<NT>(recoverCols, colSums,
[](NT spval, NT dval){return spval;},
[](NT spval, NT dval){return dval < spval;},
false, NT());
IT nrecover = recoverCols.getnnz();
if(nrecover > 0)
{
#ifdef TIMING
t0=MPI_Wtime();
#endif
A.Kselect(recoverCols, recoverNum, kselectVersion);
#ifdef TIMING
t1=MPI_Wtime();
mcl_kselecttime += (t1-t0);
#endif
pruneCols.Set(recoverCols);
#ifdef COMBBLAS_DEBUG
std::ostringstream outs;
outs << "Number of columns needing recovery: " << nrecover << std::endl;
SpParHelper::Print(outs.str());
#endif
}
if(selectNum>0)
{
// remaining columns will be up for selection
FullyDistSpVec<IT,NT> selectCols = EWiseApply<NT>(recoverCols, colSums,
[](NT spval, NT dval){return spval;},
[](NT spval, NT dval){return spval==-1;},
true, static_cast<NT>(-1));
selectCols = selectNum;
selectCols = EWiseApply<NT>(selectCols, nnzPerColumn,
[](NT spval, NT dval){return spval;},
[](NT spval, NT dval){return dval > spval;},
false, NT());
IT nselect = selectCols.getnnz();
if(nselect > 0 )
{
#ifdef TIMING
t0=MPI_Wtime();
#endif
A.Kselect(selectCols, selectNum, kselectVersion); // PrunedA would also work
#ifdef TIMING
t1=MPI_Wtime();
mcl_kselecttime += (t1-t0);
#endif
pruneCols.Set(selectCols);
#ifdef COMBBLAS_DEBUG
std::ostringstream outs;
outs << "Number of columns needing selection: " << nselect << std::endl;
SpParHelper::Print(outs.str());
#endif
#ifdef TIMING
t0=MPI_Wtime();
#endif
SpParMat<IT,NT,DER> selectedA = A.PruneColumn(pruneCols, std::less<NT>(), false);
#ifdef TIMING
t1=MPI_Wtime();
mcl_prunecolumntime += (t1-t0);
#endif
if(recoverNum>0 ) // recovery can be attempted after selection
{
FullyDistVec<IT,NT> nnzPerColumn1 = selectedA.Reduce(Column, std::plus<NT>(), 0.0, [](NT val){return 1.0;});
FullyDistVec<IT,NT> colSums1 = selectedA.Reduce(Column, std::plus<NT>(), 0.0);
selectedA.FreeMemory();
// slected columns with nnz < recoverNum (r)
selectCols = recoverNum;
selectCols = EWiseApply<NT>(selectCols, nnzPerColumn1,
[](NT spval, NT dval){return spval;},
[](NT spval, NT dval){return dval < spval;},
false, NT());
// selected columns with sum < recoverPct (pct)
selectCols = recoverPct;
selectCols = EWiseApply<NT>(selectCols, colSums1,
[](NT spval, NT dval){return spval;},
[](NT spval, NT dval){return dval < spval;},
false, NT());
IT n_recovery_after_select = selectCols.getnnz();
if(n_recovery_after_select>0)
{
// mclExpandVector2 does it on the original vector
// mclExpandVector1 does it one pruned vector
#ifdef TIMING
t0=MPI_Wtime();
#endif
A.Kselect(selectCols, recoverNum, kselectVersion); // Kselect on PrunedA might give different result
#ifdef TIMING
t1=MPI_Wtime();
mcl_kselecttime += (t1-t0);
#endif
pruneCols.Set(selectCols);
#ifdef COMBBLAS_DEBUG
std::ostringstream outs1;
outs1 << "Number of columns needing recovery after selection: " << nselect << std::endl;
SpParHelper::Print(outs1.str());
#endif
}
}
}
}
// final prune
#ifdef TIMING
t0=MPI_Wtime();
#endif
A.PruneColumn(pruneCols, std::less<NT>(), true);
#ifdef TIMING
t1=MPI_Wtime();
mcl_prunecolumntime += (t1-t0);
#endif
// Add loops for empty columns
if(recoverNum<=0 ) // if recoverNum>0, recovery would have added nonzeros in empty columns
{
FullyDistVec<IT,NT> nnzPerColumnA = A.Reduce(Column, std::plus<NT>(), 0.0, [](NT val){return 1.0;});
FullyDistSpVec<IT,NT> emptyColumns(nnzPerColumnA, std::bind2nd(std::equal_to<NT>(), 0.0));
emptyColumns = 1.00;
//Ariful: We need a selective AddLoops function with a sparse vector
//A.AddLoops(emptyColumns);
}
}
template <typename SR, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
IU EstimateFLOP
(SpParMat<IU,NU1,UDERA> & A, SpParMat<IU,NU2,UDERB> & B, bool clearA = false, bool clearB = false)
{
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
int stages, dummy; // last two parameters of ProductGrid are ignored for Synch multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
IU C_m = A.spSeq->getnrow();
IU C_n = B.spSeq->getncol();
//const_cast< UDERB* >(B.spSeq)->Transpose(); // do not transpose for colum-by-column multiplication
IU ** ARecvSizes = SpHelper::allocate2D<IU>(UDERA::esscount, stages);
IU ** BRecvSizes = SpHelper::allocate2D<IU>(UDERB::esscount, stages);
SpParHelper::GetSetSizes( *(A.spSeq), ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes( *(B.spSeq), BRecvSizes, (B.commGrid)->GetColWorld());
// Remotely fetched matrices are stored as pointers
UDERA * ARecv;
UDERB * BRecv;
IU local_flops = 0;
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
for(int i = 0; i < stages; ++i)
{
std::vector<IU> ess;
if(i == Aself)
{
ARecv = A.spSeq; // shallow-copy
}
else
{
ess.resize(UDERA::esscount);
for(int j=0; j< UDERA::esscount; ++j)
{
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess, i); // then, receive its elements
ess.clear();
if(i == Bself)
{
BRecv = B.spSeq; // shallow-copy
}
else
{
ess.resize(UDERB::esscount);
for(int j=0; j< UDERB::esscount; ++j)
{
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess, i); // then, receive its elements
local_flops += EstimateLocalFLOP<SR>
(*ARecv, *BRecv, // parameters themselves
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
}
if(clearA && A.spSeq != NULL) {
delete A.spSeq;
A.spSeq = NULL;
}
if(clearB && B.spSeq != NULL) {
delete B.spSeq;
B.spSeq = NULL;
}
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
//if(!clearB)
// const_cast< UDERB* >(B.spSeq)->Transpose(); // transpose back to original
IU global_flops = 0;
MPI_Allreduce(&local_flops, &global_flops, 1, MPI_LONG_LONG_INT, MPI_SUM, A.getcommgrid()->GetWorld());
return global_flops;
}
/**
* Broadcasts A multiple times (#phases) in order to save storage in the output
* Only uses 1/phases of C memory if the threshold/max limits are proper
* Parameters:
* - computationKernel: 1 means hash-based, 2 means heap-based
*/
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
SpParMat<IU,NUO,UDERO> MemEfficientSpGEMM (SpParMat<IU,NU1,UDERA> & A, SpParMat<IU,NU2,UDERB> & B,
int phases, NUO hardThreshold, IU selectNum, IU recoverNum, NUO recoverPct, int kselectVersion, int computationKernel, int64_t perProcessMemory)
{
typedef typename UDERA::LocalIT LIA;
typedef typename UDERB::LocalIT LIB;
typedef typename UDERO::LocalIT LIC;
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
if(A.getncol() != B.getnrow())
{
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match"<< std::endl;
outs << A.getncol() << " != " << B.getnrow() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
return SpParMat< IU,NUO,UDERO >();
}
if(phases <1 || phases >= A.getncol())
{
SpParHelper::Print("MemEfficientSpGEMM: The value of phases is too small or large. Resetting to 1.\n");
phases = 1;
}
int stages, dummy; // last two parameters of ProductGrid are ignored for Synch multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
double t0, t1, t2, t3, t4, t5;
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
t0 = MPI_Wtime();
#endif
if(perProcessMemory>0) // estimate the number of phases permitted by memory
{
int p;
MPI_Comm World = GridC->GetWorld();
MPI_Comm_size(World,&p);
int64_t perNNZMem_in = sizeof(IU)*2 + sizeof(NU1);
int64_t perNNZMem_out = sizeof(IU)*2 + sizeof(NUO);
// max nnz(A) in a porcess
int64_t lannz = A.getlocalnnz();
int64_t gannz;
MPI_Allreduce(&lannz, &gannz, 1, MPIType<int64_t>(), MPI_MAX, World);
int64_t inputMem = gannz * perNNZMem_in * 4; // for four copies (two for SUMMA)
// max nnz(A^2) stored by SUMMA in a porcess
int64_t asquareNNZ = EstPerProcessNnzSUMMA(A,B, false);
int64_t asquareMem = asquareNNZ * perNNZMem_out * 2; // an extra copy in multiway merge and in selection/recovery step
// estimate kselect memory
int64_t d = ceil( (asquareNNZ * sqrt(p))/ B.getlocalcols() ); // average nnz per column in A^2 (it is an overestimate because asquareNNZ is estimated based on unmerged matrices)
// this is equivalent to (asquareNNZ * p) / B.getcol()
int64_t k = std::min(int64_t(std::max(selectNum, recoverNum)), d );
int64_t kselectmem = B.getlocalcols() * k * 8 * 3;
// estimate output memory
int64_t outputNNZ = (B.getlocalcols() * k)/sqrt(p);
int64_t outputMem = outputNNZ * perNNZMem_in * 2;
//inputMem + outputMem + asquareMem/phases + kselectmem/phases < memory
int64_t remainingMem = perProcessMemory*1000000000 - inputMem - outputMem;
if(remainingMem > 0)
{
phases = 1 + (asquareMem+kselectmem) / remainingMem;
}
if(myrank==0)
{
if(remainingMem < 0)
{
std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n Warning: input and output memory requirement is greater than per-process avaiable memory. Keeping phase to the value supplied at the command line. The program may go out of memory and crash! \n !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl;
}
#ifdef SHOW_MEMORY_USAGE
int64_t maxMemory = kselectmem/phases + inputMem + outputMem + asquareMem / phases;
if(maxMemory>1000000000)
std::cout << "phases: " << phases << ": per process memory: " << perProcessMemory << " GB asquareMem: " << asquareMem/1000000000.00 << " GB" << " inputMem: " << inputMem/1000000000.00 << " GB" << " outputMem: " << outputMem/1000000000.00 << " GB" << " kselectmem: " << kselectmem/1000000000.00 << " GB" << std::endl;
else
std::cout << "phases: " << phases << ": per process memory: " << perProcessMemory << " GB asquareMem: " << asquareMem/1000000.00 << " MB" << " inputMem: " << inputMem/1000000.00 << " MB" << " outputMem: " << outputMem/1000000.00 << " MB" << " kselectmem: " << kselectmem/1000000.00 << " MB" << std::endl;
#endif
}
}
//if(myrank == 0){
//fprintf(stderr, "[MemEfficientSpGEMM] Running with phase: %d\n", phases);
//}
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
t1 = MPI_Wtime();
mcl_symbolictime += (t1-t0);
#endif
LIA C_m = A.spSeq->getnrow();
LIB C_n = B.spSeq->getncol();
std::vector< UDERB > PiecesOfB;
UDERB CopyB = *(B.spSeq); // we allow alias matrices as input because of this local copy
CopyB.ColSplit(phases, PiecesOfB); // CopyB's memory is destroyed at this point
MPI_Barrier(GridC->GetWorld());
LIA ** ARecvSizes = SpHelper::allocate2D<LIA>(UDERA::esscount, stages);
LIB ** BRecvSizes = SpHelper::allocate2D<LIB>(UDERB::esscount, stages);
static_assert(std::is_same<LIA, LIB>::value, "local index types for both input matrices should be the same");
static_assert(std::is_same<LIA, LIC>::value, "local index types for input and output matrices should be the same");
SpParHelper::GetSetSizes( *(A.spSeq), ARecvSizes, (A.commGrid)->GetRowWorld());
// Remotely fetched matrices are stored as pointers
UDERA * ARecv;
UDERB * BRecv;
std::vector< UDERO > toconcatenate;
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
for(int p = 0; p< phases; ++p)
{
SpParHelper::GetSetSizes( PiecesOfB[p], BRecvSizes, (B.commGrid)->GetColWorld());
std::vector< SpTuples<LIC,NUO> *> tomerge;
for(int i = 0; i < stages; ++i)
{
std::vector<LIA> ess;
if(i == Aself) ARecv = A.spSeq; // shallow-copy
else
{
ess.resize(UDERA::esscount);
for(int j=0; j< UDERA::esscount; ++j)
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
ARecv = new UDERA(); // first, create the object
}
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
t0 = MPI_Wtime();
#endif
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess, i); // then, receive its elements
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
t1 = MPI_Wtime();
mcl_Abcasttime += (t1-t0);
#endif
ess.clear();
if(i == Bself) BRecv = &(PiecesOfB[p]); // shallow-copy
else
{
ess.resize(UDERB::esscount);
for(int j=0; j< UDERB::esscount; ++j)
ess[j] = BRecvSizes[j][i];
BRecv = new UDERB();
}
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
double t2=MPI_Wtime();
#endif
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess, i); // then, receive its elements
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
double t3=MPI_Wtime();
mcl_Bbcasttime += (t3-t2);
#endif
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
double t4=MPI_Wtime();
#endif
SpTuples<LIC,NUO> * C_cont;
if(computationKernel == 1) C_cont = LocalSpGEMMHash<SR, NUO>(*ARecv, *BRecv,i != Aself, i != Bself, false); // Hash SpGEMM without per-column sorting
else if(computationKernel == 2) C_cont=LocalSpGEMM<SR, NUO>(*ARecv, *BRecv,i != Aself, i != Bself);
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
double t5=MPI_Wtime();
mcl_localspgemmtime += (t5-t4);
#endif
if(!C_cont->isZero())
tomerge.push_back(C_cont);
else
delete C_cont;
} // all stages executed
#ifdef SHOW_MEMORY_USAGE
int64_t gcnnz_unmerged, lcnnz_unmerged = 0;
for(size_t i = 0; i < tomerge.size(); ++i)
{
lcnnz_unmerged += tomerge[i]->getnnz();
}
MPI_Allreduce(&lcnnz_unmerged, &gcnnz_unmerged, 1, MPIType<int64_t>(), MPI_MAX, MPI_COMM_WORLD);
int64_t summa_memory = gcnnz_unmerged*20;//(gannz*2 + phase_nnz + gcnnz_unmerged + gannz + gannz/phases) * 20; // last two for broadcasts
if(myrank==0)
{
if(summa_memory>1000000000)
std::cout << p+1 << ". unmerged: " << summa_memory/1000000000.00 << "GB " ;
else
std::cout << p+1 << ". unmerged: " << summa_memory/1000000.00 << " MB " ;
}
#endif
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
double t6=MPI_Wtime();
#endif
// TODO: MultiwayMerge can directly return UDERO inorder to avoid the extra copy
SpTuples<LIC,NUO> * OnePieceOfC_tuples;
if(computationKernel == 1) OnePieceOfC_tuples = MultiwayMergeHash<SR>(tomerge, C_m, PiecesOfB[p].getncol(), true, false);
else if(computationKernel == 2) OnePieceOfC_tuples = MultiwayMerge<SR>(tomerge, C_m, PiecesOfB[p].getncol(), true);
#ifdef SHOW_MEMORY_USAGE
int64_t gcnnz_merged, lcnnz_merged ;
lcnnz_merged = OnePieceOfC_tuples->getnnz();
MPI_Allreduce(&lcnnz_merged, &gcnnz_merged, 1, MPIType<int64_t>(), MPI_MAX, MPI_COMM_WORLD);
// TODO: we can remove gcnnz_merged memory here because we don't need to concatenate anymore
int64_t merge_memory = gcnnz_merged*2*20;//(gannz*2 + phase_nnz + gcnnz_unmerged + gcnnz_merged*2) * 20;
if(myrank==0)
{
if(merge_memory>1000000000)
std::cout << " merged: " << merge_memory/1000000000.00 << "GB " ;
else
std::cout << " merged: " << merge_memory/1000000.00 << " MB " ;
}
#endif
#ifdef TIMING
MPI_Barrier(A.getcommgrid()->GetWorld());
double t7=MPI_Wtime();
mcl_multiwaymergetime += (t7-t6);
#endif
UDERO * OnePieceOfC = new UDERO(* OnePieceOfC_tuples, false);
delete OnePieceOfC_tuples;
SpParMat<IU,NUO,UDERO> OnePieceOfC_mat(OnePieceOfC, GridC);
MCLPruneRecoverySelect(OnePieceOfC_mat, hardThreshold, selectNum, recoverNum, recoverPct, kselectVersion);
#ifdef SHOW_MEMORY_USAGE
int64_t gcnnz_pruned, lcnnz_pruned ;
lcnnz_pruned = OnePieceOfC_mat.getlocalnnz();
MPI_Allreduce(&lcnnz_pruned, &gcnnz_pruned, 1, MPIType<int64_t>(), MPI_MAX, MPI_COMM_WORLD);
// TODO: we can remove gcnnz_merged memory here because we don't need to concatenate anymore
int64_t prune_memory = gcnnz_pruned*2*20;//(gannz*2 + phase_nnz + gcnnz_pruned*2) * 20 + kselectmem; // 3 extra copies of OnePieceOfC_mat, we can make it one extra copy!
//phase_nnz += gcnnz_pruned;
if(myrank==0)
{
if(prune_memory>1000000000)
std::cout << "Prune: " << prune_memory/1000000000.00 << "GB " << std::endl ;
else
std::cout << "Prune: " << prune_memory/1000000.00 << " MB " << std::endl ;
}
#endif
// ABAB: Change this to accept pointers to objects
toconcatenate.push_back(OnePieceOfC_mat.seq());
}
UDERO * C = new UDERO(0,C_m, C_n,0);
C->ColConcatenate(toconcatenate); // ABAB: Change this to accept a vector of pointers to pointers to DER objects
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERA::esscount);
return SpParMat<IU,NUO,UDERO> (C, GridC);
}
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
int CalculateNumberOfPhases (SpParMat<IU,NU1,UDERA> & A, SpParMat<IU,NU2,UDERB> & B,
NUO hardThreshold, IU selectNum, IU recoverNum, NUO recoverPct, int kselectVersion, int64_t perProcessMemory){
int phases;
typedef typename UDERA::LocalIT LIA;
typedef typename UDERB::LocalIT LIB;
typedef typename UDERO::LocalIT LIC;
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
int stages, dummy; // last two parameters of ProductGrid are ignored for Synch multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
double t0, t1, t2, t3, t4, t5;
int p;
MPI_Comm World = GridC->GetWorld();
MPI_Comm_size(World,&p);
int64_t perNNZMem_in = sizeof(IU)*2 + sizeof(NU1);
int64_t perNNZMem_out = sizeof(IU)*2 + sizeof(NUO);
// max nnz(A) in a porcess
int64_t lannz = A.getlocalnnz();
int64_t gannz;
MPI_Allreduce(&lannz, &gannz, 1, MPIType<int64_t>(), MPI_MAX, World);
int64_t inputMem = gannz * perNNZMem_in * 4; // for four copies (two for SUMMA)
// max nnz(A^2) stored by SUMMA in a porcess
int64_t asquareNNZ = EstPerProcessNnzSUMMA(A,B, false);
int64_t asquareMem = asquareNNZ * perNNZMem_out * 2; // an extra copy in multiway merge and in selection/recovery step
// estimate kselect memory
int64_t d = ceil( (asquareNNZ * sqrt(p))/ B.getlocalcols() ); // average nnz per column in A^2 (it is an overestimate because asquareNNZ is estimated based on unmerged matrices)
// this is equivalent to (asquareNNZ * p) / B.getcol()
int64_t k = std::min(int64_t(std::max(selectNum, recoverNum)), d );
int64_t kselectmem = B.getlocalcols() * k * 8 * 3;
// estimate output memory
int64_t outputNNZ = (B.getlocalcols() * d)/sqrt(p);
//int64_t outputNNZ = (B.getlocalcols() * k)/sqrt(p); // if kselect is used
int64_t outputMem = outputNNZ * perNNZMem_in * 2;
//inputMem + outputMem + asquareMem/phases + kselectmem/phases < memory
//int64_t remainingMem = perProcessMemory*1000000000 - inputMem - outputMem;
int64_t remainingMem = perProcessMemory*1000000000 - inputMem; // if each phase result is discarded
//if(remainingMem > 0)
//{
//phases = 1 + (asquareMem+kselectmem) / remainingMem;
//}
phases = 1 + asquareMem / remainingMem;
return phases;
}
/**
* Parallel C = A*B routine that uses a double buffered broadcasting scheme
* @pre { Input matrices, A and B, should not alias }
* Most memory efficient version available. Total stages: 2*sqrt(p)
* Memory requirement during first sqrt(p) stages: <= (3/2)*(nnz(A)+nnz(B))+(1/2)*nnz(C)
* Memory requirement during second sqrt(p) stages: <= nnz(A)+nnz(B)+nnz(C)
* Final memory requirement: nnz(C) if clearA and clearB are true
**/
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
SpParMat<IU,NUO,UDERO> Mult_AnXBn_DoubleBuff
(SpParMat<IU,NU1,UDERA> & A, SpParMat<IU,NU2,UDERB> & B, bool clearA = false, bool clearB = false )
{
if(!CheckSpGEMMCompliance(A,B) )
{
return SpParMat< IU,NUO,UDERO >();
}
typedef typename UDERA::LocalIT LIA;
typedef typename UDERB::LocalIT LIB;
typedef typename UDERO::LocalIT LIC;
static_assert(std::is_same<LIA, LIB>::value, "local index types for both input matrices should be the same");
static_assert(std::is_same<LIA, LIC>::value, "local index types for input and output matrices should be the same");
int stages, dummy; // last two parameters of ProductGrid are ignored for Synch multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
LIA C_m = A.spSeq->getnrow();
LIB C_n = B.spSeq->getncol();
UDERA * A1seq = new UDERA();
UDERA * A2seq = new UDERA();
UDERB * B1seq = new UDERB();
UDERB * B2seq = new UDERB();
(A.spSeq)->Split( *A1seq, *A2seq);
const_cast< UDERB* >(B.spSeq)->Transpose();
(B.spSeq)->Split( *B1seq, *B2seq);
// Transpose back for the column-by-column algorithm
const_cast< UDERB* >(B1seq)->Transpose();
const_cast< UDERB* >(B2seq)->Transpose();
LIA ** ARecvSizes = SpHelper::allocate2D<LIA>(UDERA::esscount, stages);
LIB ** BRecvSizes = SpHelper::allocate2D<LIB>(UDERB::esscount, stages);
SpParHelper::GetSetSizes( *A1seq, ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes( *B1seq, BRecvSizes, (B.commGrid)->GetColWorld());
// Remotely fetched matrices are stored as pointers
UDERA * ARecv;
UDERB * BRecv;
std::vector< SpTuples<LIC,NUO> *> tomerge;
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
for(int i = 0; i < stages; ++i)
{
std::vector<LIA> ess;
if(i == Aself)
{
ARecv = A1seq; // shallow-copy
}
else
{
ess.resize(UDERA::esscount);
for(int j=0; j< UDERA::esscount; ++j)
{
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess, i); // then, receive its elements
ess.clear();
if(i == Bself)
{
BRecv = B1seq; // shallow-copy
}
else
{
ess.resize(UDERB::esscount);
for(int j=0; j< UDERB::esscount; ++j)
{
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess, i); // then, receive its elements
// before activating this remove transposing B1seq
/*
SpTuples<LIC,NUO> * C_cont = MultiplyReturnTuples<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
false, true, // transpose information (B is transposed)
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
*/
SpTuples<LIC,NUO> * C_cont = LocalHybridSpGEMM<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
if(!C_cont->isZero())
tomerge.push_back(C_cont);
else
delete C_cont;
}
if(clearA) delete A1seq;
if(clearB) delete B1seq;
// Set the new dimensions
SpParHelper::GetSetSizes( *A2seq, ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes( *B2seq, BRecvSizes, (B.commGrid)->GetColWorld());
// Start the second round
for(int i = 0; i < stages; ++i)
{
std::vector<LIA> ess;
if(i == Aself)
{
ARecv = A2seq; // shallow-copy
}
else
{
ess.resize(UDERA::esscount);
for(int j=0; j< UDERA::esscount; ++j)
{
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess, i); // then, receive its elements
ess.clear();
if(i == Bself)
{
BRecv = B2seq; // shallow-copy
}
else
{
ess.resize(UDERB::esscount);
for(int j=0; j< UDERB::esscount; ++j)
{
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess, i); // then, receive its elements
// before activating this remove transposing B2seq
/*
SpTuples<LIC,NUO> * C_cont = MultiplyReturnTuples<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
false, true, // transpose information (B is transposed)
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
*/
SpTuples<LIC,NUO> * C_cont = LocalHybridSpGEMM<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
if(!C_cont->isZero())
tomerge.push_back(C_cont);
else
delete C_cont;
}
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
if(clearA)
{
delete A2seq;
delete A.spSeq;
A.spSeq = NULL;
}
else
{
(A.spSeq)->Merge(*A1seq, *A2seq);
delete A1seq;
delete A2seq;
}
if(clearB)
{
delete B2seq;
delete B.spSeq;
B.spSeq = NULL;
}
else
{
B1seq->Transpose();
B2seq->Transpose();
(B.spSeq)->Merge(*B1seq, *B2seq);
delete B1seq;
delete B2seq;
const_cast< UDERB* >(B.spSeq)->Transpose(); // transpose back to original
}
UDERO * C = new UDERO(MergeAll<SR>(tomerge, C_m, C_n,true), false);
return SpParMat<IU,NUO,UDERO> (C, GridC); // return the result object
}
/**
* Parallel A = B*C routine that uses only MPI-1 features
* Relies on simple blocking broadcast
* @pre { Input matrices, A and B, should not alias }
**/
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
SpParMat<IU, NUO, UDERO> Mult_AnXBn_Synch
(SpParMat<IU,NU1,UDERA> & A, SpParMat<IU,NU2,UDERB> & B, bool clearA = false, bool clearB = false )
{
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
if(!CheckSpGEMMCompliance(A,B) )
{
return SpParMat< IU,NUO,UDERO >();
}
int stages, dummy; // last two parameters of ProductGrid are ignored for Synch multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
IU C_m = A.spSeq->getnrow();
IU C_n = B.spSeq->getncol();
//const_cast< UDERB* >(B.spSeq)->Transpose(); // do not transpose for colum-by-column multiplication
IU ** ARecvSizes = SpHelper::allocate2D<IU>(UDERA::esscount, stages);
IU ** BRecvSizes = SpHelper::allocate2D<IU>(UDERB::esscount, stages);
SpParHelper::GetSetSizes( *(A.spSeq), ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes( *(B.spSeq), BRecvSizes, (B.commGrid)->GetColWorld());
// Remotely fetched matrices are stored as pointers
UDERA * ARecv;
UDERB * BRecv;
std::vector< SpTuples<IU,NUO> *> tomerge;
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
for(int i = 0; i < stages; ++i)
{
std::vector<IU> ess;
if(i == Aself)
{
ARecv = A.spSeq; // shallow-copy
}
else
{
ess.resize(UDERA::esscount);
for(int j=0; j< UDERA::esscount; ++j)
{
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess, i); // then, receive its elements
ess.clear();
if(i == Bself)
{
BRecv = B.spSeq; // shallow-copy
}
else
{
ess.resize(UDERB::esscount);
for(int j=0; j< UDERB::esscount; ++j)
{
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess, i); // then, receive its elements
SpTuples<IU,NUO> * C_cont = LocalHybridSpGEMM<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
if(!C_cont->isZero())
tomerge.push_back(C_cont);
#ifdef COMBBLAS_DEBUG
std::ostringstream outs;
outs << i << "th SUMMA iteration"<< std::endl;
SpParHelper::Print(outs.str());
#endif
}
if(clearA && A.spSeq != NULL)
{
delete A.spSeq;
A.spSeq = NULL;
}
if(clearB && B.spSeq != NULL)
{
delete B.spSeq;
B.spSeq = NULL;
}
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
SpTuples<IU,NUO> * C_tuples = MultiwayMerge<SR>(tomerge, C_m, C_n,false);
UDERO * C = new UDERO(*C_tuples, false);
delete C_tuples;
//if(!clearB)
// const_cast< UDERB* >(B.spSeq)->Transpose(); // transpose back to original
return SpParMat<IU,NUO,UDERO> (C, GridC); // return the result object
}
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
SpParMat<IU, NUO, UDERO> Mult_AnXBn_Overlap
(SpParMat<IU,NU1,UDERA> & A, SpParMat<IU,NU2,UDERB> & B, bool clearA = false, bool clearB = false )
{
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
if(!CheckSpGEMMCompliance(A,B) )
{
return SpParMat< IU,NUO,UDERO >();
}
int stages, dummy; // last two parameters of ProductGrid are ignored for Synch multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
IU C_m = A.spSeq->getnrow();
IU C_n = B.spSeq->getncol();
//const_cast< UDERB* >(B.spSeq)->Transpose(); // do not transpose for colum-by-column multiplication
IU ** ARecvSizes = SpHelper::allocate2D<IU>(UDERA::esscount, stages);
IU ** BRecvSizes = SpHelper::allocate2D<IU>(UDERB::esscount, stages);
SpParHelper::GetSetSizes( *(A.spSeq), ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes( *(B.spSeq), BRecvSizes, (B.commGrid)->GetColWorld());
// Remotely fetched matrices are stored as pointers
UDERA ** ARecv = new UDERA* [stages];
UDERB ** BRecv = new UDERB* [stages];
Arr<IU,NU1> Aarrinfo = A.seqptr()->GetArrays();
Arr<IU,NU2> Barrinfo = B.seqptr()->GetArrays();
std::vector< std::vector<MPI_Request> > ABCastIndarrayReq;
std::vector< std::vector<MPI_Request> > ABCastNumarrayReq;
std::vector< std::vector<MPI_Request> > BBCastIndarrayReq;
std::vector< std::vector<MPI_Request> > BBCastNumarrayReq;
for(int i = 0; i < stages; i++){
ABCastIndarrayReq.push_back( std::vector<MPI_Request>(Aarrinfo.indarrs.size(), MPI_REQUEST_NULL) );
ABCastNumarrayReq.push_back( std::vector<MPI_Request>(Aarrinfo.numarrs.size(), MPI_REQUEST_NULL) );
BBCastIndarrayReq.push_back( std::vector<MPI_Request>(Barrinfo.indarrs.size(), MPI_REQUEST_NULL) );
BBCastNumarrayReq.push_back( std::vector<MPI_Request>(Barrinfo.numarrs.size(), MPI_REQUEST_NULL) );
}
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
std::vector< SpTuples<IU,NUO> *> tomerge;
for(int i = 0; i < stages; ++i){
std::vector<IU> ess;
if(i == Aself) ARecv[i] = A.spSeq; // shallow-copy
else{
ess.resize(UDERA::esscount);
for(int j=0; j< UDERA::esscount; ++j) ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
ARecv[i] = new UDERA(); // first, create the object
}
SpParHelper::IBCastMatrix(GridC->GetRowWorld(), *(ARecv[i]), ess, i, ABCastIndarrayReq[i], ABCastNumarrayReq[i]); // then, receive its elements
ess.clear();
if(i == Bself) BRecv[i] = B.spSeq; // shallow-copy
else{
ess.resize(UDERB::esscount);
for(int j=0; j< UDERB::esscount; ++j) ess[j] = BRecvSizes[j][i];
BRecv[i] = new UDERB();
}
SpParHelper::IBCastMatrix(GridC->GetColWorld(), *(BRecv[i]), ess, i, BBCastIndarrayReq[i], BBCastNumarrayReq[i]); // then, receive its elements
if(i > 0){
MPI_Waitall(ABCastIndarrayReq[i-1].size(), ABCastIndarrayReq[i-1].data(), MPI_STATUSES_IGNORE);
MPI_Waitall(ABCastNumarrayReq[i-1].size(), ABCastNumarrayReq[i-1].data(), MPI_STATUSES_IGNORE);
MPI_Waitall(BBCastIndarrayReq[i-1].size(), BBCastIndarrayReq[i-1].data(), MPI_STATUSES_IGNORE);
MPI_Waitall(BBCastNumarrayReq[i-1].size(), BBCastNumarrayReq[i-1].data(), MPI_STATUSES_IGNORE);
SpTuples<IU,NUO> * C_cont = LocalHybridSpGEMM<SR, NUO>
(*(ARecv[i-1]), *(BRecv[i-1]), // parameters themselves
i-1 != Aself, // 'delete A' condition
i-1 != Bself); // 'delete B' condition
if(!C_cont->isZero()) tomerge.push_back(C_cont);
SpTuples<IU,NUO> * C_tuples = MultiwayMerge<SR>(tomerge, C_m, C_n,true);
std::vector< SpTuples<IU,NUO> *>().swap(tomerge);
tomerge.push_back(C_tuples);
}
#ifdef COMBBLAS_DEBUG
std::ostringstream outs;
outs << i << "th SUMMA iteration"<< std::endl;
SpParHelper::Print(outs.str());
#endif
}
MPI_Waitall(ABCastIndarrayReq[stages-1].size(), ABCastIndarrayReq[stages-1].data(), MPI_STATUSES_IGNORE);
MPI_Waitall(ABCastNumarrayReq[stages-1].size(), ABCastNumarrayReq[stages-1].data(), MPI_STATUSES_IGNORE);
MPI_Waitall(BBCastIndarrayReq[stages-1].size(), BBCastIndarrayReq[stages-1].data(), MPI_STATUSES_IGNORE);
MPI_Waitall(BBCastNumarrayReq[stages-1].size(), BBCastNumarrayReq[stages-1].data(), MPI_STATUSES_IGNORE);
SpTuples<IU,NUO> * C_cont = LocalHybridSpGEMM<SR, NUO>
(*(ARecv[stages-1]), *(BRecv[stages-1]), // parameters themselves
stages-1 != Aself, // 'delete A' condition
stages-1 != Bself); // 'delete B' condition
if(!C_cont->isZero()) tomerge.push_back(C_cont);
if(clearA && A.spSeq != NULL) {
delete A.spSeq;
A.spSeq = NULL;
}
if(clearB && B.spSeq != NULL) {
delete B.spSeq;
B.spSeq = NULL;
}
delete ARecv;
delete BRecv;
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
// the last parameter to MergeAll deletes tomerge arrays
SpTuples<IU,NUO> * C_tuples = MultiwayMerge<SR>(tomerge, C_m, C_n,true);
std::vector< SpTuples<IU,NUO> *>().swap(tomerge);
UDERO * C = new UDERO(*C_tuples, false);
delete C_tuples;
//if(!clearB)
// const_cast< UDERB* >(B.spSeq)->Transpose(); // transpose back to original
return SpParMat<IU,NUO,UDERO> (C, GridC); // return the result object
}
/**
* Estimate the maximum nnz needed to store in a process from all stages of SUMMA before reduction
* @pre { Input matrices, A and B, should not alias }
**/
template <typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
int64_t EstPerProcessNnzSUMMA(SpParMat<IU,NU1,UDERA> & A, SpParMat<IU,NU2,UDERB> & B, bool hashEstimate)
{
typedef typename UDERA::LocalIT LIA;
typedef typename UDERB::LocalIT LIB;
static_assert(std::is_same<LIA, LIB>::value, "local index types for both input matrices should be the same");
double t0, t1;
int64_t nnzC_SUMMA = 0;
if(A.getncol() != B.getnrow())
{
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match"<< std::endl;
outs << A.getncol() << " != " << B.getnrow() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
return nnzC_SUMMA;
}
int stages, dummy; // last two parameters of ProductGrid are ignored for Synch multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.commGrid).get(), (B.commGrid).get(), stages, dummy, dummy);
MPI_Barrier(GridC->GetWorld());
LIA ** ARecvSizes = SpHelper::allocate2D<LIA>(UDERA::esscount, stages);
LIB ** BRecvSizes = SpHelper::allocate2D<LIB>(UDERB::esscount, stages);
SpParHelper::GetSetSizes( *(A.spSeq), ARecvSizes, (A.commGrid)->GetRowWorld());
SpParHelper::GetSetSizes( *(B.spSeq), BRecvSizes, (B.commGrid)->GetColWorld());
// Remotely fetched matrices are stored as pointers
UDERA * ARecv;
UDERB * BRecv;
int Aself = (A.commGrid)->GetRankInProcRow();
int Bself = (B.commGrid)->GetRankInProcCol();
for(int i = 0; i < stages; ++i)
{
std::vector<LIA> ess;
if(i == Aself)
{
ARecv = A.spSeq; // shallow-copy
}
else
{
ess.resize(UDERA::esscount);
for(int j=0; j< UDERA::esscount; ++j)
{
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
SpParHelper::BCastMatrix(GridC->GetRowWorld(), *ARecv, ess, i); // then, receive its elements
ess.clear();
if(i == Bself)
{
BRecv = B.spSeq; // shallow-copy
}
else
{
ess.resize(UDERB::esscount);
for(int j=0; j< UDERB::esscount; ++j)
{
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
SpParHelper::BCastMatrix(GridC->GetColWorld(), *BRecv, ess, i); // then, receive its elements
// no need to keep entries of colnnzC in larger precision
// because colnnzC is of length nzc and estimates nnzs per column
// @OGUZ-EDIT Using hash spgemm for estimation
//LIB * colnnzC = estimateNNZ(*ARecv, *BRecv);
LIB* flopC = estimateFLOP(*ARecv, *BRecv);
LIB* colnnzC = estimateNNZ_Hash(*ARecv, *BRecv, flopC);
LIB nzc = BRecv->GetDCSC()->nzc;
if (flopC) delete [] flopC;
if(colnnzC) delete [] colnnzC;
// sampling-based estimation (comment the estimation above, and
// comment out below to use)
// int64_t nnzC_stage = estimateNNZ_sampling(*ARecv, *BRecv);
// nnzC_SUMMA += nnzC_stage;
// delete received data
if(i != Aself)
delete ARecv;
if(i != Bself)
delete BRecv;
}
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
int64_t nnzC_SUMMA_max = 0;
MPI_Allreduce(&nnzC_SUMMA, &nnzC_SUMMA_max, 1, MPIType<int64_t>(), MPI_MAX, GridC->GetWorld());
return nnzC_SUMMA_max;
}
template <typename MATRIX, typename VECTOR>
void CheckSpMVCompliance(const MATRIX & A, const VECTOR & x)
{
if(A.getncol() != x.TotalLength())
{
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match"<< std::endl;
outs << A.getncol() << " != " << x.TotalLength() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
if(! ( *(A.getcommgrid()) == *(x.getcommgrid())) )
{
std::cout << "Grids are not comparable for SpMV" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
}
}
template <typename SR, typename IU, typename NUM, typename UDER>
FullyDistSpVec<IU,typename promote_trait<NUM,IU>::T_promote> SpMV
(const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IU> & x, bool indexisvalue, OptBuf<int32_t, typename promote_trait<NUM,IU>::T_promote > & optbuf);
template <typename SR, typename IU, typename NUM, typename UDER>
FullyDistSpVec<IU,typename promote_trait<NUM,IU>::T_promote> SpMV
(const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IU> & x, bool indexisvalue)
{
typedef typename promote_trait<NUM,IU>::T_promote T_promote;
OptBuf<int32_t, T_promote > optbuf = OptBuf<int32_t, T_promote >();
return SpMV<SR>(A, x, indexisvalue, optbuf);
}
/**
* Step 1 of the sparse SpMV algorithm
* @param[in,out] trxlocnz, lenuntil,trxinds,trxnums { set or allocated }
* @param[in] indexisvalue
**/
template<typename IU, typename NV>
void TransposeVector(MPI_Comm & World, const FullyDistSpVec<IU,NV> & x, int32_t & trxlocnz, IU & lenuntil, int32_t * & trxinds, NV * & trxnums, bool indexisvalue)
{
int32_t xlocnz = (int32_t) x.getlocnnz();
int32_t roffst = (int32_t) x.RowLenUntil(); // since trxinds is int32_t
int32_t roffset;
IU luntil = x.LengthUntil();
int diagneigh = x.commGrid->GetComplementRank();
MPI_Status status;
MPI_Sendrecv(&roffst, 1, MPIType<int32_t>(), diagneigh, TROST, &roffset, 1, MPIType<int32_t>(), diagneigh, TROST, World, &status);
MPI_Sendrecv(&xlocnz, 1, MPIType<int32_t>(), diagneigh, TRNNZ, &trxlocnz, 1, MPIType<int32_t>(), diagneigh, TRNNZ, World, &status);
MPI_Sendrecv(&luntil, 1, MPIType<IU>(), diagneigh, TRLUT, &lenuntil, 1, MPIType<IU>(), diagneigh, TRLUT, World, &status);
// ABAB: Important observation is that local indices (given by x.ind) is 32-bit addressible
// Copy them to 32 bit integers and transfer that to save 50% of off-node bandwidth
trxinds = new int32_t[trxlocnz];
int32_t * temp_xind = new int32_t[xlocnz];
#ifdef THREADED
#pragma omp parallel for
#endif
for(int i=0; i< xlocnz; ++i)
temp_xind[i] = (int32_t) x.ind[i];
MPI_Sendrecv(temp_xind, xlocnz, MPIType<int32_t>(), diagneigh, TRI, trxinds, trxlocnz, MPIType<int32_t>(), diagneigh, TRI, World, &status);
delete [] temp_xind;
if(!indexisvalue)
{
trxnums = new NV[trxlocnz];
MPI_Sendrecv(const_cast<NV*>(SpHelper::p2a(x.num)), xlocnz, MPIType<NV>(), diagneigh, TRX, trxnums, trxlocnz, MPIType<NV>(), diagneigh, TRX, World, &status);
}
std::transform(trxinds, trxinds+trxlocnz, trxinds, std::bind2nd(std::plus<int32_t>(), roffset)); // fullydist indexing (p pieces) -> matrix indexing (sqrt(p) pieces)
}
/**
* Step 2 of the sparse SpMV algorithm
* @param[in,out] trxinds, trxnums { deallocated }
* @param[in,out] indacc, numacc { allocated }
* @param[in,out] accnz { set }
* @param[in] trxlocnz, lenuntil, indexisvalue
**/
template<typename IU, typename NV>
void AllGatherVector(MPI_Comm & ColWorld, int trxlocnz, IU lenuntil, int32_t * & trxinds, NV * & trxnums,
int32_t * & indacc, NV * & numacc, int & accnz, bool indexisvalue)
{
int colneighs, colrank;
MPI_Comm_size(ColWorld, &colneighs);
MPI_Comm_rank(ColWorld, &colrank);
int * colnz = new int[colneighs];
colnz[colrank] = trxlocnz;
MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT, colnz, 1, MPI_INT, ColWorld);
int * dpls = new int[colneighs](); // displacements (zero initialized pid)
std::partial_sum(colnz, colnz+colneighs-1, dpls+1);
accnz = std::accumulate(colnz, colnz+colneighs, 0);
indacc = new int32_t[accnz];
numacc = new NV[accnz];
// ABAB: Future issues here, colnz is of type int (MPI limitation)
// What if the aggregate vector size along the processor row/column is not 32-bit addressible?
// This will happen when n/sqrt(p) > 2^31
// Currently we can solve a small problem (scale 32) with 4096 processor
// For a medium problem (scale 35), we'll need 32K processors which gives sqrt(p) ~ 180
// 2^35 / 180 ~ 2^29 / 3 which is not an issue !
#ifdef TIMING
double t0=MPI_Wtime();
#endif
MPI_Allgatherv(trxinds, trxlocnz, MPIType<int32_t>(), indacc, colnz, dpls, MPIType<int32_t>(), ColWorld);
delete [] trxinds;
if(indexisvalue)
{
IU lenuntilcol;
if(colrank == 0) lenuntilcol = lenuntil;
MPI_Bcast(&lenuntilcol, 1, MPIType<IU>(), 0, ColWorld);
for(int i=0; i< accnz; ++i) // fill numerical values from indices
{
numacc[i] = indacc[i] + lenuntilcol;
}
}
else
{
MPI_Allgatherv(trxnums, trxlocnz, MPIType<NV>(), numacc, colnz, dpls, MPIType<NV>(), ColWorld);
delete [] trxnums;
}
#ifdef TIMING
double t1=MPI_Wtime();
cblas_allgathertime += (t1-t0);
#endif
DeleteAll(colnz,dpls);
}
/**
* Step 3 of the sparse SpMV algorithm, with the semiring
* @param[in,out] optbuf {scratch space for all-to-all (fold) communication}
* @param[in,out] indacc, numacc {index and values of the input vector, deleted upon exit}
* @param[in,out] sendindbuf, sendnumbuf {index and values of the output vector, created}
**/
template<typename SR, typename IVT, typename OVT, typename IU, typename NUM, typename UDER>
void LocalSpMV(const SpParMat<IU,NUM,UDER> & A, int rowneighs, OptBuf<int32_t, OVT > & optbuf, int32_t * & indacc, IVT * & numacc,
int32_t * & sendindbuf, OVT * & sendnumbuf, int * & sdispls, int * sendcnt, int accnz, bool indexisvalue, PreAllocatedSPA<OVT> & SPA)
{
if(optbuf.totmax > 0) // graph500 optimization enabled
{
if(A.spSeq->getnsplit() > 0)
{
// optbuf.{inds/nums/dspls} and sendcnt are all pre-allocated and only filled by dcsc_gespmv_threaded
generic_gespmv_threaded_setbuffers<SR> (*(A.spSeq), indacc, numacc, accnz, optbuf.inds, optbuf.nums, sendcnt, optbuf.dspls, rowneighs);
}
else
{
generic_gespmv<SR> (*(A.spSeq), indacc, numacc, accnz, optbuf.inds, optbuf.nums, sendcnt, optbuf.dspls, rowneighs, indexisvalue);
}
DeleteAll(indacc,numacc);
}
else
{
if(A.spSeq->getnsplit() > 0)
{
// sendindbuf/sendnumbuf/sdispls are all allocated and filled by dcsc_gespmv_threaded
int totalsent = generic_gespmv_threaded<SR> (*(A.spSeq), indacc, numacc, accnz, sendindbuf, sendnumbuf, sdispls, rowneighs, SPA);
DeleteAll(indacc, numacc);
for(int i=0; i<rowneighs-1; ++i)
sendcnt[i] = sdispls[i+1] - sdispls[i];
sendcnt[rowneighs-1] = totalsent - sdispls[rowneighs-1];
}
else
{
// default SpMSpV
std::vector< int32_t > indy;
std::vector< OVT > numy;
generic_gespmv<SR>(*(A.spSeq), indacc, numacc, accnz, indy, numy, SPA);
DeleteAll(indacc, numacc);
int32_t bufsize = indy.size(); // as compact as possible
sendindbuf = new int32_t[bufsize];
sendnumbuf = new OVT[bufsize];
int32_t perproc = A.getlocalrows() / rowneighs;
int k = 0; // index to buffer
for(int i=0; i<rowneighs; ++i)
{
int32_t end_this = (i==rowneighs-1) ? A.getlocalrows(): (i+1)*perproc;
while(k < bufsize && indy[k] < end_this)
{
sendindbuf[k] = indy[k] - i*perproc;
sendnumbuf[k] = numy[k];
++sendcnt[i];
++k;
}
}
sdispls = new int[rowneighs]();
std::partial_sum(sendcnt, sendcnt+rowneighs-1, sdispls+1);
//#endif
}
}
}
// non threaded
template <typename SR, typename IU, typename OVT>
void MergeContributions(int* listSizes, std::vector<int32_t *> & indsvec, std::vector<OVT *> & numsvec, std::vector<IU>& mergedind, std::vector<OVT>& mergednum)
{
int nlists = indsvec.size();
// this condition is checked in the caller SpMV function.
// I am still putting it here for completeness
if(nlists == 1)
{
// simply copy data
int veclen = listSizes[0];
mergedind.resize(veclen);
mergednum.resize(veclen);
for(int i=0; i<veclen; i++)
{
mergedind[i] = indsvec[0][i];
mergednum[i] = numsvec[0][i];
}
return;
}
int32_t hsize = 0;
int32_t inf = std::numeric_limits<int32_t>::min();
int32_t sup = std::numeric_limits<int32_t>::max();
KNHeap< int32_t, int32_t > sHeap(sup, inf);
int * processed = new int[nlists]();
for(int i=0; i<nlists; ++i)
{
if(listSizes[i] > 0)
{
// key, list_id
sHeap.insert(indsvec[i][0], i);
++hsize;
}
}
int32_t key, locv;
if(hsize > 0)
{
sHeap.deleteMin(&key, &locv);
mergedind.push_back( static_cast<IU>(key));
mergednum.push_back(numsvec[locv][0]); // nothing is processed yet
if( (++(processed[locv])) < listSizes[locv] )
sHeap.insert(indsvec[locv][processed[locv]], locv);
else
--hsize;
}
while(hsize > 0)
{
sHeap.deleteMin(&key, &locv);
if(mergedind.back() == static_cast<IU>(key))
{
mergednum.back() = SR::add(mergednum.back(), numsvec[locv][processed[locv]]);
// ABAB: Benchmark actually allows us to be non-deterministic in terms of parent selection
// We can just skip this addition operator (if it's a max/min select)
}
else
{
mergedind.push_back(static_cast<IU>(key));
mergednum.push_back(numsvec[locv][processed[locv]]);
}
if( (++(processed[locv])) < listSizes[locv] )
sHeap.insert(indsvec[locv][processed[locv]], locv);
else
--hsize;
}
DeleteAll(processed);
}
template <typename SR, typename IU, typename OVT>
void MergeContributions_threaded(int * & listSizes, std::vector<int32_t *> & indsvec, std::vector<OVT *> & numsvec, std::vector<IU> & mergedind, std::vector<OVT> & mergednum, IU maxindex)
{
int nlists = indsvec.size();
// this condition is checked in the caller SpMV function.
// I am still putting it here for completeness
if(nlists == 1)
{
// simply copy data
int veclen = listSizes[0];
mergedind.resize(veclen);
mergednum.resize(veclen);
#ifdef THREADED
#pragma omp parallel for
#endif
for(int i=0; i<veclen; i++)
{
mergedind[i] = indsvec[0][i];
mergednum[i] = numsvec[0][i];
}
return;
}
int nthreads=1;
#ifdef THREADED
#pragma omp parallel
{
nthreads = omp_get_num_threads();
}
#endif
int nsplits = 4*nthreads; // oversplit for load balance
nsplits = std::min(nsplits, (int)maxindex);
std::vector< std::vector<int32_t> > splitters(nlists);
for(int k=0; k< nlists; k++)
{
splitters[k].resize(nsplits+1);
splitters[k][0] = static_cast<int32_t>(0);
#pragma omp parallel for
for(int i=1; i< nsplits; i++)
{
IU cur_idx = i * (maxindex/nsplits);
auto it = std::lower_bound (indsvec[k], indsvec[k] + listSizes[k], cur_idx);
splitters[k][i] = (int32_t) (it - indsvec[k]);
}
splitters[k][nsplits] = listSizes[k];
}
// ------ perform merge in parallel ------
std::vector<std::vector<IU>> indsBuf(nsplits);
std::vector<std::vector<OVT>> numsBuf(nsplits);
//TODO: allocate these vectors here before calling MergeContributions
#pragma omp parallel for schedule(dynamic)
for(int i=0; i< nsplits; i++)
{
std::vector<int32_t *> tIndsVec(nlists);
std::vector<OVT *> tNumsVec(nlists);
std::vector<int> tLengths(nlists);
for(int j=0; j< nlists; ++j)
{
tIndsVec[j] = indsvec[j] + splitters[j][i];
tNumsVec[j] = numsvec[j] + splitters[j][i];
tLengths[j]= splitters[j][i+1] - splitters[j][i];
}
MergeContributions<SR>(tLengths.data(), tIndsVec, tNumsVec, indsBuf[i], numsBuf[i]);
}
// ------ concatenate merged tuples processed by threads ------
std::vector<IU> tdisp(nsplits+1);
tdisp[0] = 0;
for(int i=0; i<nsplits; ++i)
{
tdisp[i+1] = tdisp[i] + indsBuf[i].size();
}
mergedind.resize(tdisp[nsplits]);
mergednum.resize(tdisp[nsplits]);
#pragma omp parallel for schedule(dynamic)
for(int i=0; i< nsplits; i++)
{
std::copy(indsBuf[i].data() , indsBuf[i].data() + indsBuf[i].size(), mergedind.data() + tdisp[i]);
std::copy(numsBuf[i].data() , numsBuf[i].data() + numsBuf[i].size(), mergednum.data() + tdisp[i]);
}
}
/**
* This version is the most flexible sparse matrix X sparse vector [Used in KDT]
* It accepts different types for the matrix (NUM), the input vector (IVT) and the output vector (OVT)
* without relying on automatic type promotion
* Input (x) and output (y) vectors can be ALIASED because y is not written until the algorithm is done with x.
*/
template <typename SR, typename IVT, typename OVT, typename IU, typename NUM, typename UDER>
void SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IVT> & x, FullyDistSpVec<IU,OVT> & y,
bool indexisvalue, OptBuf<int32_t, OVT > & optbuf, PreAllocatedSPA<OVT> & SPA)
{
CheckSpMVCompliance(A,x);
optbuf.MarkEmpty();
y.glen = A.getnrow(); // in case it is not set already
MPI_Comm World = x.commGrid->GetWorld();
MPI_Comm ColWorld = x.commGrid->GetColWorld();
MPI_Comm RowWorld = x.commGrid->GetRowWorld();
int accnz;
int32_t trxlocnz;
IU lenuntil;
int32_t *trxinds, *indacc;
IVT *trxnums, *numacc;
#ifdef TIMING
double t0=MPI_Wtime();
#endif
TransposeVector(World, x, trxlocnz, lenuntil, trxinds, trxnums, indexisvalue);
#ifdef TIMING
double t1=MPI_Wtime();
cblas_transvectime += (t1-t0);
#endif
if(x.commGrid->GetGridRows() > 1)
{
AllGatherVector(ColWorld, trxlocnz, lenuntil, trxinds, trxnums, indacc, numacc, accnz, indexisvalue); // trxindS/trxnums deallocated, indacc/numacc allocated, accnz set
}
else
{
accnz = trxlocnz;
indacc = trxinds; // aliasing ptr
numacc = trxnums; // aliasing ptr
}
int rowneighs;
MPI_Comm_size(RowWorld, &rowneighs);
int * sendcnt = new int[rowneighs]();
int32_t * sendindbuf;
OVT * sendnumbuf;
int * sdispls;
#ifdef TIMING
double t2=MPI_Wtime();
#endif
LocalSpMV<SR>(A, rowneighs, optbuf, indacc, numacc, sendindbuf, sendnumbuf, sdispls, sendcnt, accnz, indexisvalue, SPA); // indacc/numacc deallocated, sendindbuf/sendnumbuf/sdispls allocated
#ifdef TIMING
double t3=MPI_Wtime();
cblas_localspmvtime += (t3-t2);
#endif
if(x.commGrid->GetGridCols() == 1)
{
y.ind.resize(sendcnt[0]);
y.num.resize(sendcnt[0]);
if(optbuf.totmax > 0 ) // graph500 optimization enabled
{
#ifdef THREADED
#pragma omp parallel for
#endif
for(int i=0; i<sendcnt[0]; i++)
{
y.ind[i] = optbuf.inds[i];
y.num[i] = optbuf.nums[i];
}
}
else
{
#ifdef THREADED
#pragma omp parallel for
#endif
for(int i=0; i<sendcnt[0]; i++)
{
y.ind[i] = sendindbuf[i];
y.num[i] = sendnumbuf[i];
}
DeleteAll(sendindbuf, sendnumbuf,sdispls);
}
delete [] sendcnt;
return;
}
int * rdispls = new int[rowneighs];
int * recvcnt = new int[rowneighs];
MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, RowWorld); // share the request counts
// receive displacements are exact whereas send displacements have slack
rdispls[0] = 0;
for(int i=0; i<rowneighs-1; ++i)
{
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
int totrecv = std::accumulate(recvcnt,recvcnt+rowneighs,0);
int32_t * recvindbuf = new int32_t[totrecv];
OVT * recvnumbuf = new OVT[totrecv];
#ifdef TIMING
double t4=MPI_Wtime();
#endif
if(optbuf.totmax > 0 ) // graph500 optimization enabled
{
MPI_Alltoallv(optbuf.inds, sendcnt, optbuf.dspls, MPIType<int32_t>(), recvindbuf, recvcnt, rdispls, MPIType<int32_t>(), RowWorld);
MPI_Alltoallv(optbuf.nums, sendcnt, optbuf.dspls, MPIType<OVT>(), recvnumbuf, recvcnt, rdispls, MPIType<OVT>(), RowWorld);
delete [] sendcnt;
}
else
{
MPI_Alltoallv(sendindbuf, sendcnt, sdispls, MPIType<int32_t>(), recvindbuf, recvcnt, rdispls, MPIType<int32_t>(), RowWorld);
MPI_Alltoallv(sendnumbuf, sendcnt, sdispls, MPIType<OVT>(), recvnumbuf, recvcnt, rdispls, MPIType<OVT>(), RowWorld);
DeleteAll(sendindbuf, sendnumbuf, sendcnt, sdispls);
}
#ifdef TIMING
double t5=MPI_Wtime();
cblas_alltoalltime += (t5-t4);
#endif
#ifdef TIMING
double t6=MPI_Wtime();
#endif
//MergeContributions<SR>(y,recvcnt, rdispls, recvindbuf, recvnumbuf, rowneighs);
// free memory of y, in case it was aliased
std::vector<IU>().swap(y.ind);
std::vector<OVT>().swap(y.num);
std::vector<int32_t *> indsvec(rowneighs);
std::vector<OVT *> numsvec(rowneighs);
#ifdef THREADED
#pragma omp parallel for
#endif
for(int i=0; i<rowneighs; i++)
{
indsvec[i] = recvindbuf+rdispls[i];
numsvec[i] = recvnumbuf+rdispls[i];
}
#ifdef THREADED
MergeContributions_threaded<SR>(recvcnt, indsvec, numsvec, y.ind, y.num, y.MyLocLength());
#else
MergeContributions<SR>(recvcnt, indsvec, numsvec, y.ind, y.num);
#endif
DeleteAll(recvcnt, rdispls,recvindbuf, recvnumbuf);
#ifdef TIMING
double t7=MPI_Wtime();
cblas_mergeconttime += (t7-t6);
#endif
}
template <typename SR, typename IVT, typename OVT, typename IU, typename NUM, typename UDER>
void SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IVT> & x, FullyDistSpVec<IU,OVT> & y, bool indexisvalue, PreAllocatedSPA<OVT> & SPA)
{
OptBuf< int32_t, OVT > optbuf = OptBuf< int32_t,OVT >();
SpMV<SR>(A, x, y, indexisvalue, optbuf, SPA);
}
template <typename SR, typename IVT, typename OVT, typename IU, typename NUM, typename UDER>
void SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IVT> & x, FullyDistSpVec<IU,OVT> & y, bool indexisvalue)
{
OptBuf< int32_t, OVT > optbuf = OptBuf< int32_t,OVT >();
PreAllocatedSPA<OVT> SPA;
SpMV<SR>(A, x, y, indexisvalue, optbuf, SPA);
}
template <typename SR, typename IVT, typename OVT, typename IU, typename NUM, typename UDER>
void SpMV (const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IVT> & x, FullyDistSpVec<IU,OVT> & y, bool indexisvalue, OptBuf<int32_t, OVT > & optbuf)
{
PreAllocatedSPA<OVT> SPA;
SpMV<SR>(A, x, y, indexisvalue, optbuf, SPA);
}
/**
* Automatic type promotion is ONLY done here, all the callee functions (in Friends.h and below) are initialized with the promoted type
* If indexisvalues = true, then we do not need to transfer values for x (happens for BFS iterations with boolean matrices and integer rhs vectors)
**/
template <typename SR, typename IU, typename NUM, typename UDER>
FullyDistSpVec<IU,typename promote_trait<NUM,IU>::T_promote> SpMV
(const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,IU> & x, bool indexisvalue, OptBuf<int32_t, typename promote_trait<NUM,IU>::T_promote > & optbuf)
{
typedef typename promote_trait<NUM,IU>::T_promote T_promote;
FullyDistSpVec<IU, T_promote> y ( x.getcommgrid(), A.getnrow()); // identity doesn't matter for sparse vectors
SpMV<SR>(A, x, y, indexisvalue, optbuf);
return y;
}
/**
* Parallel dense SpMV
**/
template <typename SR, typename IU, typename NUM, typename NUV, typename UDER>
FullyDistVec<IU,typename promote_trait<NUM,NUV>::T_promote> SpMV
(const SpParMat<IU,NUM,UDER> & A, const FullyDistVec<IU,NUV> & x )
{
typedef typename promote_trait<NUM,NUV>::T_promote T_promote;
CheckSpMVCompliance(A, x);
MPI_Comm World = x.commGrid->GetWorld();
MPI_Comm ColWorld = x.commGrid->GetColWorld();
MPI_Comm RowWorld = x.commGrid->GetRowWorld();
int xsize = (int) x.LocArrSize();
int trxsize = 0;
int diagneigh = x.commGrid->GetComplementRank();
MPI_Status status;
MPI_Sendrecv(&xsize, 1, MPI_INT, diagneigh, TRX, &trxsize, 1, MPI_INT, diagneigh, TRX, World, &status);
NUV * trxnums = new NUV[trxsize];
MPI_Sendrecv(const_cast<NUV*>(SpHelper::p2a(x.arr)), xsize, MPIType<NUV>(), diagneigh, TRX, trxnums, trxsize, MPIType<NUV>(), diagneigh, TRX, World, &status);
int colneighs, colrank;
MPI_Comm_size(ColWorld, &colneighs);
MPI_Comm_rank(ColWorld, &colrank);
int * colsize = new int[colneighs];
colsize[colrank] = trxsize;
MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT, colsize, 1, MPI_INT, ColWorld);
int * dpls = new int[colneighs](); // displacements (zero initialized pid)
std::partial_sum(colsize, colsize+colneighs-1, dpls+1);
int accsize = std::accumulate(colsize, colsize+colneighs, 0);
NUV * numacc = new NUV[accsize];
MPI_Allgatherv(trxnums, trxsize, MPIType<NUV>(), numacc, colsize, dpls, MPIType<NUV>(), ColWorld);
delete [] trxnums;
// serial SpMV with dense vector
T_promote id = SR::id();
IU ysize = A.getlocalrows();
T_promote * localy = new T_promote[ysize];
std::fill_n(localy, ysize, id);
#ifdef THREADED
dcsc_gespmv_threaded<SR>(*(A.spSeq), numacc, localy);
#else
dcsc_gespmv<SR>(*(A.spSeq), numacc, localy);
#endif
DeleteAll(numacc,colsize, dpls);
// FullyDistVec<IT,NT>(shared_ptr<CommGrid> grid, IT globallen, NT initval, NT id)
FullyDistVec<IU, T_promote> y ( x.commGrid, A.getnrow(), id);
int rowneighs;
MPI_Comm_size(RowWorld, &rowneighs);
IU begptr, endptr;
for(int i=0; i< rowneighs; ++i)
{
begptr = y.RowLenUntil(i);
if(i == rowneighs-1)
{
endptr = ysize;
}
else
{
endptr = y.RowLenUntil(i+1);
}
MPI_Reduce(localy+begptr, SpHelper::p2a(y.arr), endptr-begptr, MPIType<T_promote>(), SR::mpi_op(), i, RowWorld);
}
delete [] localy;
return y;
}
/**
* \TODO: Old version that is no longer considered optimal
* Kept for legacy purposes
* To be removed when other functionals are fully tested.
**/
template <typename SR, typename IU, typename NUM, typename NUV, typename UDER>
FullyDistSpVec<IU,typename promote_trait<NUM,NUV>::T_promote> SpMV
(const SpParMat<IU,NUM,UDER> & A, const FullyDistSpVec<IU,NUV> & x)
{
typedef typename promote_trait<NUM,NUV>::T_promote T_promote;
CheckSpMVCompliance(A, x);
MPI_Comm World = x.commGrid->GetWorld();
MPI_Comm ColWorld = x.commGrid->GetColWorld();
MPI_Comm RowWorld = x.commGrid->GetRowWorld();
int xlocnz = (int) x.getlocnnz();
int trxlocnz = 0;
int roffst = x.RowLenUntil();
int offset;
int diagneigh = x.commGrid->GetComplementRank();
MPI_Status status;
MPI_Sendrecv(&xlocnz, 1, MPI_INT, diagneigh, TRX, &trxlocnz, 1, MPI_INT, diagneigh, TRX, World, &status);
MPI_Sendrecv(&roffst, 1, MPI_INT, diagneigh, TROST, &offset, 1, MPI_INT, diagneigh, TROST, World, &status);
IU * trxinds = new IU[trxlocnz];
NUV * trxnums = new NUV[trxlocnz];
MPI_Sendrecv(const_cast<IU*>(SpHelper::p2a(x.ind)), xlocnz, MPIType<IU>(), diagneigh, TRX, trxinds, trxlocnz, MPIType<IU>(), diagneigh, TRX, World, &status);
MPI_Sendrecv(const_cast<NUV*>(SpHelper::p2a(x.num)), xlocnz, MPIType<NUV>(), diagneigh, TRX, trxnums, trxlocnz, MPIType<NUV>(), diagneigh, TRX, World, &status);
std::transform(trxinds, trxinds+trxlocnz, trxinds, std::bind2nd(std::plus<IU>(), offset)); // fullydist indexing (n pieces) -> matrix indexing (sqrt(p) pieces)
int colneighs, colrank;
MPI_Comm_size(ColWorld, &colneighs);
MPI_Comm_rank(ColWorld, &colrank);
int * colnz = new int[colneighs];
colnz[colrank] = trxlocnz;
MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT, colnz, 1, MPI_INT, ColWorld);
int * dpls = new int[colneighs](); // displacements (zero initialized pid)
std::partial_sum(colnz, colnz+colneighs-1, dpls+1);
int accnz = std::accumulate(colnz, colnz+colneighs, 0);
IU * indacc = new IU[accnz];
NUV * numacc = new NUV[accnz];
// ABAB: Future issues here, colnz is of type int (MPI limitation)
// What if the aggregate vector size along the processor row/column is not 32-bit addressible?
MPI_Allgatherv(trxinds, trxlocnz, MPIType<IU>(), indacc, colnz, dpls, MPIType<IU>(), ColWorld);
MPI_Allgatherv(trxnums, trxlocnz, MPIType<NUV>(), numacc, colnz, dpls, MPIType<NUV>(), ColWorld);
DeleteAll(trxinds, trxnums);
// serial SpMV with sparse vector
std::vector< int32_t > indy;
std::vector< T_promote > numy;
int32_t * tmpindacc = new int32_t[accnz];
for(int i=0; i< accnz; ++i) tmpindacc[i] = indacc[i];
delete [] indacc;
dcsc_gespmv<SR>(*(A.spSeq), tmpindacc, numacc, accnz, indy, numy); // actual multiplication
DeleteAll(tmpindacc, numacc);
DeleteAll(colnz, dpls);
FullyDistSpVec<IU, T_promote> y ( x.commGrid, A.getnrow()); // identity doesn't matter for sparse vectors
IU yintlen = y.MyRowLength();
int rowneighs;
MPI_Comm_size(RowWorld,&rowneighs);
std::vector< std::vector<IU> > sendind(rowneighs);
std::vector< std::vector<T_promote> > sendnum(rowneighs);
typename std::vector<int32_t>::size_type outnz = indy.size();
for(typename std::vector<IU>::size_type i=0; i< outnz; ++i)
{
IU locind;
int rown = y.OwnerWithinRow(yintlen, static_cast<IU>(indy[i]), locind);
sendind[rown].push_back(locind);
sendnum[rown].push_back(numy[i]);
}
IU * sendindbuf = new IU[outnz];
T_promote * sendnumbuf = new T_promote[outnz];
int * sendcnt = new int[rowneighs];
int * sdispls = new int[rowneighs];
for(int i=0; i<rowneighs; ++i)
sendcnt[i] = sendind[i].size();
int * rdispls = new int[rowneighs];
int * recvcnt = new int[rowneighs];
MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, RowWorld); // share the request counts
sdispls[0] = 0;
rdispls[0] = 0;
for(int i=0; i<rowneighs-1; ++i)
{
sdispls[i+1] = sdispls[i] + sendcnt[i];
rdispls[i+1] = rdispls[i] + recvcnt[i];
}
int totrecv = std::accumulate(recvcnt,recvcnt+rowneighs,0);
IU * recvindbuf = new IU[totrecv];
T_promote * recvnumbuf = new T_promote[totrecv];
for(int i=0; i<rowneighs; ++i)
{
std::copy(sendind[i].begin(), sendind[i].end(), sendindbuf+sdispls[i]);
std::vector<IU>().swap(sendind[i]);
}
for(int i=0; i<rowneighs; ++i)
{
std::copy(sendnum[i].begin(), sendnum[i].end(), sendnumbuf+sdispls[i]);
std::vector<T_promote>().swap(sendnum[i]);
}
MPI_Alltoallv(sendindbuf, sendcnt, sdispls, MPIType<IU>(), recvindbuf, recvcnt, rdispls, MPIType<IU>(), RowWorld);
MPI_Alltoallv(sendnumbuf, sendcnt, sdispls, MPIType<T_promote>(), recvnumbuf, recvcnt, rdispls, MPIType<T_promote>(), RowWorld);
DeleteAll(sendindbuf, sendnumbuf);
DeleteAll(sendcnt, recvcnt, sdispls, rdispls);
// define a SPA-like data structure
IU ysize = y.MyLocLength();
T_promote * localy = new T_promote[ysize];
bool * isthere = new bool[ysize];
std::vector<IU> nzinds; // nonzero indices
std::fill_n(isthere, ysize, false);
for(int i=0; i< totrecv; ++i)
{
if(!isthere[recvindbuf[i]])
{
localy[recvindbuf[i]] = recvnumbuf[i]; // initial assignment
nzinds.push_back(recvindbuf[i]);
isthere[recvindbuf[i]] = true;
}
else
{
localy[recvindbuf[i]] = SR::add(localy[recvindbuf[i]], recvnumbuf[i]);
}
}
DeleteAll(isthere, recvindbuf, recvnumbuf);
sort(nzinds.begin(), nzinds.end());
int nnzy = nzinds.size();
y.ind.resize(nnzy);
y.num.resize(nnzy);
for(int i=0; i< nnzy; ++i)
{
y.ind[i] = nzinds[i];
y.num[i] = localy[nzinds[i]];
}
delete [] localy;
return y;
}
// Aydin (June 2021):
// This currently duplicates the work of EWiseMult with exclude = true
// However, this is the right way of implementing it because it allows set difference when
// the types of two matrices do not have a valid multiplication operator defined
// set difference should not require such an operator so we will move all code
// bases that use EWiseMult(..., exclude=true) to this one
template <typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
SpParMat<IU,NU1,UDERA> SetDifference(const SpParMat<IU,NU1,UDERA> & A, const SpParMat<IU,NU2,UDERB> & B)
{
if(*(A.commGrid) == *(B.commGrid))
{
UDERA * result = new UDERA( SetDifference(*(A.spSeq),*(B.spSeq)));
return SpParMat<IU, NU1, UDERA> (result, A.commGrid);
}
else
{
std::cout << "Grids are not comparable for set difference" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParMat< IU,NU1,UDERA >();
}
}
template <typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
SpParMat<IU,typename promote_trait<NU1,NU2>::T_promote,typename promote_trait<UDERA,UDERB>::T_promote> EWiseMult
(const SpParMat<IU,NU1,UDERA> & A, const SpParMat<IU,NU2,UDERB> & B , bool exclude)
{
typedef typename promote_trait<NU1,NU2>::T_promote N_promote;
typedef typename promote_trait<UDERA,UDERB>::T_promote DER_promote;
if(*(A.commGrid) == *(B.commGrid))
{
DER_promote * result = new DER_promote( EWiseMult(*(A.spSeq),*(B.spSeq),exclude) );
return SpParMat<IU, N_promote, DER_promote> (result, A.commGrid);
}
else
{
std::cout << "Grids are not comparable elementwise multiplication" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParMat< IU,N_promote,DER_promote >();
}
}
template <typename RETT, typename RETDER, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB, typename _BinaryOperation>
SpParMat<IU,RETT,RETDER> EWiseApply
(const SpParMat<IU,NU1,UDERA> & A, const SpParMat<IU,NU2,UDERB> & B, _BinaryOperation __binary_op, bool notB, const NU2& defaultBVal)
{
if(*(A.commGrid) == *(B.commGrid))
{
RETDER * result = new RETDER( EWiseApply<RETT>(*(A.spSeq),*(B.spSeq), __binary_op, notB, defaultBVal) );
return SpParMat<IU, RETT, RETDER> (result, A.commGrid);
}
else
{
std::cout << "Grids are not comparable elementwise apply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParMat< IU,RETT,RETDER >();
}
}
template <typename RETT, typename RETDER, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB, typename _BinaryOperation, typename _BinaryPredicate>
SpParMat<IU,RETT,RETDER> EWiseApply
(const SpParMat<IU,NU1,UDERA> & A, const SpParMat<IU,NU2,UDERB> & B, _BinaryOperation __binary_op, _BinaryPredicate do_op, bool allowANulls, bool allowBNulls, const NU1& ANullVal, const NU2& BNullVal, const bool allowIntersect, const bool useExtendedBinOp)
{
if(*(A.commGrid) == *(B.commGrid))
{
RETDER * result = new RETDER( EWiseApply<RETT>(*(A.spSeq),*(B.spSeq), __binary_op, do_op, allowANulls, allowBNulls, ANullVal, BNullVal, allowIntersect) );
return SpParMat<IU, RETT, RETDER> (result, A.commGrid);
}
else
{
std::cout << "Grids are not comparable elementwise apply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return SpParMat< IU,RETT,RETDER >();
}
}
// plain adapter
template <typename RETT, typename RETDER, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB, typename _BinaryOperation, typename _BinaryPredicate>
SpParMat<IU,RETT,RETDER>
EWiseApply (const SpParMat<IU,NU1,UDERA> & A, const SpParMat<IU,NU2,UDERB> & B, _BinaryOperation __binary_op, _BinaryPredicate do_op, bool allowANulls, bool allowBNulls, const NU1& ANullVal, const NU2& BNullVal, const bool allowIntersect = true)
{
return EWiseApply<RETT, RETDER>(A, B,
EWiseExtToPlainAdapter<RETT, NU1, NU2, _BinaryOperation>(__binary_op),
EWiseExtToPlainAdapter<bool, NU1, NU2, _BinaryPredicate>(do_op),
allowANulls, allowBNulls, ANullVal, BNullVal, allowIntersect, true);
}
// end adapter
/**
* if exclude is true, then we prune all entries W[i] != zero from V
* if exclude is false, then we perform a proper elementwise multiplication
**/
template <typename IU, typename NU1, typename NU2>
FullyDistSpVec<IU,typename promote_trait<NU1,NU2>::T_promote> EWiseMult
(const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , bool exclude, NU2 zero)
{
typedef typename promote_trait<NU1,NU2>::T_promote T_promote;
if(*(V.commGrid) == *(W.commGrid))
{
FullyDistSpVec< IU, T_promote> Product(V.commGrid);
if(V.glen != W.glen)
{
std::cerr << "Vector dimensions don't match for EWiseMult\n";
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
else
{
Product.glen = V.glen;
IU size= V.getlocnnz();
if(exclude)
{
#if defined(_OPENMP) && defined(CBLAS_EXPERIMENTAL) // not faster than serial
int actual_splits = cblas_splits * 1; // 1 is the parallel slackness
std::vector <IU> tlosizes (actual_splits, 0);
std::vector < std::vector<IU> > tlinds(actual_splits);
std::vector < std::vector<T_promote> > tlnums(actual_splits);
IU tlsize = size / actual_splits;
#pragma omp parallel for //schedule(dynamic, 1)
for(IU t = 0; t < actual_splits; ++t)
{
IU tlbegin = t*tlsize;
IU tlend = (t==actual_splits-1)? size : (t+1)*tlsize;
for(IU i=tlbegin; i<tlend; ++i)
{
if(W.arr[V.ind[i]] == zero) // keep only those
{
tlinds[t].push_back(V.ind[i]);
tlnums[t].push_back(V.num[i]);
tlosizes[t]++;
}
}
}
std::vector<IU> prefix_sum(actual_splits+1,0);
std::partial_sum(tlosizes.begin(), tlosizes.end(), prefix_sum.begin()+1);
Product.ind.resize(prefix_sum[actual_splits]);
Product.num.resize(prefix_sum[actual_splits]);
#pragma omp parallel for //schedule(dynamic, 1)
for(IU t=0; t< actual_splits; ++t)
{
std::copy(tlinds[t].begin(), tlinds[t].end(), Product.ind.begin()+prefix_sum[t]);
std::copy(tlnums[t].begin(), tlnums[t].end(), Product.num.begin()+prefix_sum[t]);
}
#else
for(IU i=0; i<size; ++i)
{
if(W.arr[V.ind[i]] == zero) // keep only those
{
Product.ind.push_back(V.ind[i]);
Product.num.push_back(V.num[i]);
}
}
#endif
}
else
{
for(IU i=0; i<size; ++i)
{
if(W.arr[V.ind[i]] != zero) // keep only those
{
Product.ind.push_back(V.ind[i]);
Product.num.push_back(V.num[i] * W.arr[V.ind[i]]);
}
}
}
}
return Product;
}
else
{
std::cout << "Grids are not comparable elementwise multiplication" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec< IU,T_promote>();
}
}
/**
Threaded EWiseApply. Only called internally from EWiseApply.
**/
template <typename RET, typename IU, typename NU1, typename NU2, typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU,RET> EWiseApply_threaded
(const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , _BinaryOperation _binary_op, _BinaryPredicate _doOp, bool allowVNulls, NU1 Vzero, const bool useExtendedBinOp)
{
typedef RET T_promote; //typedef typename promote_trait<NU1,NU2>::T_promote T_promote;
if(*(V.commGrid) == *(W.commGrid))
{
FullyDistSpVec< IU, T_promote> Product(V.commGrid);
if(V.TotalLength() != W.TotalLength())
{
std::ostringstream outs;
outs << "Vector dimensions don't match (" << V.TotalLength() << " vs " << W.TotalLength() << ") for EWiseApply (short version)\n";
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
else
{
int nthreads=1;
#ifdef _OPENMP
#pragma omp parallel
{
nthreads = omp_get_num_threads();
}
#endif
Product.glen = V.glen;
IU size= W.LocArrSize();
IU spsize = V.getlocnnz();
// temporary result vectors per thread
std::vector<std::vector<IU>> tProductInd(nthreads);
std::vector<std::vector<T_promote>> tProductVal(nthreads);
IU perthread; //chunk of tProductInd or tProductVal allocated to each thread
if (allowVNulls)
perthread = size/nthreads;
else
perthread = spsize/nthreads;
#ifdef _OPENMP
#pragma omp parallel
#endif
{
int curthread = 0;
#ifdef _OPENMP
curthread = omp_get_thread_num();
#endif
IU tStartIdx = perthread * curthread;
IU tNextIdx = perthread * (curthread+1);
if (allowVNulls)
{
if(curthread == nthreads-1) tNextIdx = size;
// get sparse part for the current thread
auto it = std::lower_bound (V.ind.begin(), V.ind.end(), tStartIdx);
IU tSpIdx = (IU) std::distance(V.ind.begin(), it);
// iterate over the dense vector
for(IU tIdx=tStartIdx; tIdx < tNextIdx; ++tIdx)
{
if(tSpIdx < spsize && V.ind[tSpIdx] < tNextIdx && V.ind[tSpIdx] == tIdx)
{
if (_doOp(V.num[tSpIdx], W.arr[tIdx], false, false))
{
tProductInd[curthread].push_back(tIdx);
tProductVal[curthread].push_back (_binary_op(V.num[tSpIdx], W.arr[tIdx], false, false));
}
tSpIdx++;
}
else
{
if (_doOp(Vzero, W.arr[tIdx], true, false))
{
tProductInd[curthread].push_back(tIdx);
tProductVal[curthread].push_back (_binary_op(Vzero, W.arr[tIdx], true, false));
}
}
}
}
else // iterate over the sparse vector
{
if(curthread == nthreads-1) tNextIdx = spsize;
for(IU tSpIdx=tStartIdx; tSpIdx < tNextIdx; ++tSpIdx)
{
if (_doOp(V.num[tSpIdx], W.arr[V.ind[tSpIdx]], false, false))
{
tProductInd[curthread].push_back( V.ind[tSpIdx]);
tProductVal[curthread].push_back (_binary_op(V.num[tSpIdx], W.arr[V.ind[tSpIdx]], false, false));
}
}
}
}
std::vector<IU> tdisp(nthreads+1);
tdisp[0] = 0;
for(int i=0; i<nthreads; ++i)
{
tdisp[i+1] = tdisp[i] + tProductInd[i].size();
}
// copy results from temporary vectors
Product.ind.resize(tdisp[nthreads]);
Product.num.resize(tdisp[nthreads]);
#ifdef _OPENMP
#pragma omp parallel
#endif
{
int curthread = 0;
#ifdef _OPENMP
curthread = omp_get_thread_num();
#endif
std::copy(tProductInd[curthread].begin(), tProductInd[curthread].end(), Product.ind.data() + tdisp[curthread]);
std::copy(tProductVal[curthread].begin() , tProductVal[curthread].end(), Product.num.data() + tdisp[curthread]);
}
}
return Product;
}
else
{
std::cout << "Grids are not comparable for EWiseApply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec< IU,T_promote>();
}
}
/**
* Performs an arbitrary binary operation _binary_op on the corresponding elements of two vectors with the result stored in a return vector ret.
* The binary operatiation is only performed if the binary predicate _doOp returns true for those elements. Otherwise the binary operation is not
* performed and ret does not contain an element at that position.
* More formally the operation is defined as:
* if (_doOp(V[i], W[i]))
* ret[i] = _binary_op(V[i], W[i])
* else
* // ret[i] is not set
* Hence _doOp can be used to implement a filter on either of the vectors.
*
* The above is only defined if both V[i] and W[i] exist (i.e. an intersection). To allow a union operation (ex. when V[i] doesn't exist but W[i] does)
* the allowVNulls flag is set to true and the Vzero argument is used as the missing V[i] value.
*
* The type of each element of ret must not necessarily be related to the types of V or W, so the return type must be explicitly specified as a template parameter:
* FullyDistSpVec<int, double> r = EWiseApply<double>(V, W, plus, retTrue, false, 0)
**/
template <typename RET, typename IU, typename NU1, typename NU2, typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU,RET> EWiseApply
(const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , _BinaryOperation _binary_op, _BinaryPredicate _doOp, bool allowVNulls, NU1 Vzero, const bool useExtendedBinOp)
{
#ifdef _OPENMP
return EWiseApply_threaded<RET>(V, W, _binary_op, _doOp, allowVNulls, Vzero, useExtendedBinOp);
#else
typedef RET T_promote; //typedef typename promote_trait<NU1,NU2>::T_promote T_promote;
if(*(V.commGrid) == *(W.commGrid))
{
FullyDistSpVec< IU, T_promote> Product(V.commGrid);
//FullyDistVec< IU, NU1> DV (V); // Ariful: I am not sure why it was there??
if(V.TotalLength() != W.TotalLength())
{
std::ostringstream outs;
outs << "Vector dimensions don't match (" << V.TotalLength() << " vs " << W.TotalLength() << ") for EWiseApply (short version)\n";
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
else
{
Product.glen = V.glen;
IU size= W.LocArrSize();
IU spsize = V.getlocnnz();
IU sp_iter = 0;
if (allowVNulls)
{
// iterate over the dense vector
for(IU i=0; i<size; ++i)
{
if(sp_iter < spsize && V.ind[sp_iter] == i)
{
if (_doOp(V.num[sp_iter], W.arr[i], false, false))
{
Product.ind.push_back(i);
Product.num.push_back(_binary_op(V.num[sp_iter], W.arr[i], false, false));
}
sp_iter++;
}
else
{
if (_doOp(Vzero, W.arr[i], true, false))
{
Product.ind.push_back(i);
Product.num.push_back(_binary_op(Vzero, W.arr[i], true, false));
}
}
}
}
else
{
// iterate over the sparse vector
for(sp_iter = 0; sp_iter < spsize; ++sp_iter)
{
if (_doOp(V.num[sp_iter], W.arr[V.ind[sp_iter]], false, false))
{
Product.ind.push_back(V.ind[sp_iter]);
Product.num.push_back(_binary_op(V.num[sp_iter], W.arr[V.ind[sp_iter]], false, false));
}
}
}
}
return Product;
}
else
{
std::cout << "Grids are not comparable for EWiseApply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec< IU,T_promote>();
}
#endif
}
/**
* Performs an arbitrary binary operation _binary_op on the corresponding elements of two vectors with the result stored in a return vector ret.
* The binary operatiation is only performed if the binary predicate _doOp returns true for those elements. Otherwise the binary operation is not
* performed and ret does not contain an element at that position.
* More formally the operation is defined as:
* if (_doOp(V[i], W[i]))
* ret[i] = _binary_op(V[i], W[i])
* else
* // ret[i] is not set
* Hence _doOp can be used to implement a filter on either of the vectors.
*
* The above is only defined if both V[i] and W[i] exist (i.e. an intersection). To allow a union operation (ex. when V[i] doesn't exist but W[i] does)
* the allowVNulls flag is set to true and the Vzero argument is used as the missing V[i] value.
* !allowVNulls && !allowWNulls => intersection
* !allowVNulls && allowWNulls => operate on all elements of V
* allowVNulls && !allowWNulls => operate on all elements of W
* allowVNulls && allowWNulls => union
*
* The type of each element of ret must not necessarily be related to the types of V or W, so the return type must be explicitly specified as a template parameter:
* FullyDistSpVec<int, double> r = EWiseApply<double>(V, W, plus, ...)
* For intersection, Vzero and Wzero are irrelevant
* ABAB: \todo: Should allowIntersect be "false" for all SetDifference uses?
**/
template <typename RET, typename IU, typename NU1, typename NU2, typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU,RET> EWiseApply
(const FullyDistSpVec<IU,NU1> & V, const FullyDistSpVec<IU,NU2> & W , _BinaryOperation _binary_op, _BinaryPredicate _doOp, bool allowVNulls, bool allowWNulls, NU1 Vzero, NU2 Wzero, const bool allowIntersect, const bool useExtendedBinOp)
{
typedef RET T_promote; // typename promote_trait<NU1,NU2>::T_promote T_promote;
if(*(V.commGrid) == *(W.commGrid))
{
FullyDistSpVec< IU, T_promote> Product(V.commGrid);
if(V.glen != W.glen)
{
std::ostringstream outs;
outs << "Vector dimensions don't match (" << V.glen << " vs " << W.glen << ") for EWiseApply (full version)\n";
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
else
{
Product.glen = V.glen;
typename std::vector< IU >::const_iterator indV = V.ind.begin();
typename std::vector< NU1 >::const_iterator numV = V.num.begin();
typename std::vector< IU >::const_iterator indW = W.ind.begin();
typename std::vector< NU2 >::const_iterator numW = W.num.begin();
while (indV < V.ind.end() && indW < W.ind.end())
{
if (*indV == *indW)
{
// overlap
if (allowIntersect)
{
if (_doOp(*numV, *numW, false, false))
{
Product.ind.push_back(*indV);
Product.num.push_back(_binary_op(*numV, *numW, false, false));
}
}
indV++; numV++;
indW++; numW++;
}
else if (*indV < *indW)
{
// V has value but W does not
if (allowWNulls)
{
if (_doOp(*numV, Wzero, false, true))
{
Product.ind.push_back(*indV);
Product.num.push_back(_binary_op(*numV, Wzero, false, true));
}
}
indV++; numV++;
}
else //(*indV > *indW)
{
// W has value but V does not
if (allowVNulls)
{
if (_doOp(Vzero, *numW, true, false))
{
Product.ind.push_back(*indW);
Product.num.push_back(_binary_op(Vzero, *numW, true, false));
}
}
indW++; numW++;
}
}
// clean up
while (allowWNulls && indV < V.ind.end())
{
if (_doOp(*numV, Wzero, false, true))
{
Product.ind.push_back(*indV);
Product.num.push_back(_binary_op(*numV, Wzero, false, true));
}
indV++; numV++;
}
while (allowVNulls && indW < W.ind.end())
{
if (_doOp(Vzero, *numW, true, false))
{
Product.ind.push_back(*indW);
Product.num.push_back(_binary_op(Vzero, *numW, true, false));
}
indW++; numW++;
}
}
return Product;
}
else
{
std::cout << "Grids are not comparable for EWiseApply" << std::endl;
MPI_Abort(MPI_COMM_WORLD, GRIDMISMATCH);
return FullyDistSpVec< IU,T_promote>();
}
}
// plain callback versions
template <typename RET, typename IU, typename NU1, typename NU2, typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU,RET> EWiseApply
(const FullyDistSpVec<IU,NU1> & V, const FullyDistVec<IU,NU2> & W , _BinaryOperation _binary_op, _BinaryPredicate _doOp, bool allowVNulls, NU1 Vzero)
{
return EWiseApply<RET>(V, W,
EWiseExtToPlainAdapter<RET, NU1, NU2, _BinaryOperation>(_binary_op),
EWiseExtToPlainAdapter<bool, NU1, NU2, _BinaryPredicate>(_doOp),
allowVNulls, Vzero, true);
}
template <typename RET, typename IU, typename NU1, typename NU2, typename _BinaryOperation, typename _BinaryPredicate>
FullyDistSpVec<IU,RET> EWiseApply
(const FullyDistSpVec<IU,NU1> & V, const FullyDistSpVec<IU,NU2> & W , _BinaryOperation _binary_op, _BinaryPredicate _doOp, bool allowVNulls, bool allowWNulls, NU1 Vzero, NU2 Wzero, const bool allowIntersect = true)
{
return EWiseApply<RET>(V, W,
EWiseExtToPlainAdapter<RET, NU1, NU2, _BinaryOperation>(_binary_op),
EWiseExtToPlainAdapter<bool, NU1, NU2, _BinaryPredicate>(_doOp),
allowVNulls, allowWNulls, Vzero, Wzero, allowIntersect, true);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// sampling-based nnz estimation via SpMV
// @OGUZ-NOTE This is not based on SUMMA, do not use. Estimates the number of
// nonzeros in the final output matrix.
#define NROUNDS 5
typedef std::array<float, NROUNDS> samparr_t;
template <typename NZT>
struct promote_trait<NZT, samparr_t>
{
typedef samparr_t T_promote;
};
class SamplesSaveHandler
{
public:
template<typename c, typename t, typename V>
void save(std::basic_ostream<c, t> &os,
std::array<V, NROUNDS> &sample_vec,
int64_t index)
{
for (auto it = sample_vec.begin(); it != sample_vec.end(); ++it)
os << *it << " ";
}
};
template<typename NZT>
struct SelectMinxSR
{
static samparr_t id()
{
samparr_t arr;
for (auto it = arr.begin(); it != arr.end(); ++it)
*it = std::numeric_limits<float>::max();
return arr;
}
static bool returnedSAID()
{
return false;
}
static samparr_t
add (const samparr_t &arg1, const samparr_t &arg2)
{
samparr_t out;
for (int i = 0; i < NROUNDS; ++i)
out[i] = std::min(arg1[i], arg2[i]);
return out;
}
static samparr_t
multiply (const NZT arg1, const samparr_t &arg2)
{
return arg2;
}
static void axpy (const NZT a, const samparr_t &x, samparr_t &y)
{
y = add(y, multiply(a, x));
}
static MPI_Op mpi_op()
{
static MPI_Op mpiop;
static bool exists = false;
if (exists)
return mpiop;
else
{
MPI_Op_create(MPI_func, true, &mpiop);
exists = true;
return mpiop;
}
}
static void
MPI_func(void *invec, void *inoutvec, int *len, MPI_Datatype *datatype)
{
samparr_t *in = static_cast<samparr_t *>(invec);
samparr_t *inout = static_cast<samparr_t *>(inoutvec);
for (int i = 0; i < *len; ++i)
inout[i] = add(inout[i], in[i]);
}
};
template <typename IU, typename NU1, typename NU2,
typename UDERA, typename UDERB>
int64_t
EstPerProcessNnzSpMV(
SpParMat<IU, NU1, UDERA> &A, SpParMat<IU, NU2, UDERB> &B
)
{
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
float lambda = 1.0f;
int nthds = 1;
#ifdef THREADED
#pragma omp parallel
#endif
{
nthds = omp_get_num_threads();
}
if (myrank == 0)
std::cout << "taking transposes." << std::endl;
A.Transpose();
B.Transpose();
if (myrank == 0)
std::cout << "setting initial samples." << std::endl;
samparr_t sa;
FullyDistVec<IU, samparr_t> samples_init(A.getcommgrid(), A.getncol(), sa);
#ifdef THREADED
#pragma omp parallel
#endif
{
std::default_random_engine gen;
std::exponential_distribution<float> exp_dist(lambda);
#ifdef THREADED
#pragma omp parallel for
#endif
for (IU i = 0; i < samples_init.LocArrSize(); ++i)
{
samparr_t tmp;
for (auto it = tmp.begin(); it != tmp.end(); ++it)
*it = exp_dist(gen);
samples_init.SetLocalElement(i, tmp);
}
}
// std::string fname("samples_init");
// samples_init.ParallelWrite(fname, 1, SamplesSaveHandler(), true);
if (myrank == 0)
std::cout << "computing mid samples." << std::endl;
FullyDistVec<IU, samparr_t> samples_mid =
SpMV<SelectMinxSR<NU1> > (A, samples_init);
// fname = "samples_mid";
// samples_mid.ParallelWrite(fname, 1, SamplesSaveHandler(), true);
if (myrank == 0)
std::cout << "computing final samples." << std::endl;
FullyDistVec<IU, samparr_t> samples_final =
SpMV<SelectMinxSR<NU2> > (B, samples_mid);
// fname = "samples_final";
// samples_final.ParallelWrite(fname, 1, SamplesSaveHandler(), true);
if (myrank == 0)
std::cout << "computing nnz estimation." << std::endl;
float nnzest = 0.0f;
std::cout << myrank << "samples_final loc size: "
<< samples_final.LocArrSize() << std::endl;
const samparr_t *lsamples = samples_final.GetLocArr();
#ifdef THREADED
#pragma omp parallel for reduction (+:nnzest)
#endif
for (IU i = 0; i < samples_final.LocArrSize(); ++i)
{
float tmp = 0.0f;
for (auto it = lsamples[i].begin(); it != lsamples[i].end(); ++it)
tmp += *it;
nnzest += static_cast<float>(NROUNDS - 1) / tmp;
}
if (myrank == 0)
std::cout << "taking transposes again." << std::endl;
int64_t nnzC_est = nnzest;
int64_t nnzC_tot = 0;
MPI_Allreduce(&nnzC_est, &nnzC_tot, 1, MPIType<int64_t>(), MPI_SUM,
(B.commGrid)->GetWorld());
if (myrank == 0)
std::cout << "sampling-based spmv est tot: " << nnzC_tot << std::endl;
// revert back
A.Transpose();
B.Transpose();
return nnzC_tot;
}
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1, typename NU2, typename UDER1, typename UDER2>
SpParMat3D<IU,NUO,UDERO> Mult_AnXBn_SUMMA3D(SpParMat3D<IU,NU1,UDER1> & A, SpParMat3D<IU,NU2,UDER2> & B){
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
typedef typename UDERO::LocalIT LIC;
typedef typename UDER1::LocalIT LIA;
typedef typename UDER2::LocalIT LIB;
#ifdef TIMING
double t0, t1, t2, t3;
#endif
/*
* Check if A and B are multipliable
* */
if(A.getncol() != B.getnrow()){
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match"<< std::endl;
outs << A.getncol() << " != " << B.getnrow() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
/*
* Calculate, accross fibers, which process should get how many columns after redistribution
* */
vector<LIB> divisions3d;
// Calcuclate split boundaries as if all contents of the layer is being re-distributed along fiber
// These boundaries will be used later on
B.CalculateColSplitDistributionOfLayer(divisions3d);
#ifdef TIMING
t0 = MPI_Wtime();
#endif
/*
* SUMMA Starts
* */
int stages, dummy; // last two parameters of ProductGrid are ignored for this multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.GetLayerMat()->getcommgrid()).get(),
(B.GetLayerMat()->getcommgrid()).get(),
stages, dummy, dummy);
IU C_m = A.GetLayerMat()->seqptr()->getnrow();
IU C_n = B.GetLayerMat()->seqptr()->getncol();
IU ** ARecvSizes = SpHelper::allocate2D<IU>(UDERO::esscount, stages);
IU ** BRecvSizes = SpHelper::allocate2D<IU>(UDERO::esscount, stages);
SpParHelper::GetSetSizes( *(A.GetLayerMat()->seqptr()), ARecvSizes, (A.GetLayerMat()->getcommgrid())->GetRowWorld() );
SpParHelper::GetSetSizes( *(B.GetLayerMat()->seqptr()), BRecvSizes, (B.GetLayerMat()->getcommgrid())->GetColWorld() );
// Remotely fetched matrices are stored as pointers
UDERO * ARecv;
UDER2 * BRecv;
std::vector< SpTuples<IU,NUO> *> tomerge;
int Aself = (A.GetLayerMat()->getcommgrid())->GetRankInProcRow();
int Bself = (B.GetLayerMat()->getcommgrid())->GetRankInProcCol();
double Abcast_time = 0;
double Bbcast_time = 0;
double Local_multiplication_time = 0;
for(int i = 0; i < stages; ++i) {
std::vector<IU> ess;
if(i == Aself){
ARecv = A.GetLayerMat()->seqptr(); // shallow-copy
}
else{
ess.resize(UDER1::esscount);
for(int j=0; j<UDER1::esscount; ++j) {
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDER1(); // first, create the object
}
#ifdef TIMING
t2 = MPI_Wtime();
#endif
if (Aself != i) {
ARecv->Create(ess);
}
Arr<IU,NU1> Aarrinfo = ARecv->GetArrays();
for(unsigned int idx = 0; idx < Aarrinfo.indarrs.size(); ++idx) {
MPI_Bcast(Aarrinfo.indarrs[idx].addr, Aarrinfo.indarrs[idx].count, MPIType<IU>(), i, GridC->GetRowWorld());
}
for(unsigned int idx = 0; idx < Aarrinfo.numarrs.size(); ++idx) {
MPI_Bcast(Aarrinfo.numarrs[idx].addr, Aarrinfo.numarrs[idx].count, MPIType<NU1>(), i, GridC->GetRowWorld());
}
#ifdef TIMING
t3 = MPI_Wtime();
Abcast_time += (t3-t2);
#endif
ess.clear();
if(i == Bself){
BRecv = B.GetLayerMat()->seqptr(); // shallow-copy
}
else{
ess.resize(UDER2::esscount);
for(int j=0; j<UDER2::esscount; ++j) {
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDER2();
}
MPI_Barrier(A.GetLayerMat()->getcommgrid()->GetWorld());
#ifdef TIMING
t2 = MPI_Wtime();
#endif
if (Bself != i) {
BRecv->Create(ess);
}
Arr<IU,NU2> Barrinfo = BRecv->GetArrays();
for(unsigned int idx = 0; idx < Barrinfo.indarrs.size(); ++idx) {
MPI_Bcast(Barrinfo.indarrs[idx].addr, Barrinfo.indarrs[idx].count, MPIType<IU>(), i, GridC->GetColWorld());
}
for(unsigned int idx = 0; idx < Barrinfo.numarrs.size(); ++idx) {
MPI_Bcast(Barrinfo.numarrs[idx].addr, Barrinfo.numarrs[idx].count, MPIType<NU2>(), i, GridC->GetColWorld());
}
#ifdef TIMING
t3 = MPI_Wtime();
Bbcast_time += (t3-t2);
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
SpTuples<IU,NUO> * C_cont = LocalSpGEMMHash<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
i != Aself, // 'delete A' condition
i != Bself, // 'delete B' condition
false); // not to sort each column
#ifdef TIMING
t3 = MPI_Wtime();
Local_multiplication_time += (t3-t2);
#endif
if(!C_cont->isZero()) tomerge.push_back(C_cont);
}
SpHelper::deallocate2D(ARecvSizes, UDER1::esscount);
SpHelper::deallocate2D(BRecvSizes, UDER2::esscount);
#ifdef TIMING
t2 = MPI_Wtime();
#endif
SpTuples<IU,NUO> * C_tuples = MultiwayMergeHash<SR>(tomerge, C_m, C_n, true, false); // Delete input arrays and do not sort
//SpTuples<IU,NUO> * C_tuples = MultiwayMergeHashSliding<SR>(tomerge, C_m, C_n, true, false); // Delete input arrays and do not sort
#ifdef TIMING
t3 = MPI_Wtime();
#endif
#ifdef TIMING
if(myrank == 0){
fprintf(stderr, "[SUMMA3D]\tAbcast_time: %lf\n", Abcast_time);
fprintf(stderr, "[SUMMA3D]\tBbcast_time: %lf\n", Bbcast_time);
fprintf(stderr, "[SUMMA3D]\tLocal_multiplication_time: %lf\n", Local_multiplication_time);
fprintf(stderr, "[SUMMA3D]\tMerge_layer_time: %lf\n", (t3-t2));
}
#endif
/*
* SUMMA Ends
* */
#ifdef TIMING
t1 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[SUMMA3D]\tSUMMA time: %lf\n", (t1-t0));
#endif
/*
* 3d-reduction starts
* */
#ifdef TIMING
//MPI_Barrier(getcommgrid3D()->GetWorld());
t0 = MPI_Wtime();
#endif
MPI_Datatype MPI_tuple;
MPI_Type_contiguous(sizeof(std::tuple<LIC,LIC,NUO>), MPI_CHAR, &MPI_tuple);
MPI_Type_commit(&MPI_tuple);
/*
* Create a profile with information regarding data to be sent and received between layers
* These memory allocation needs to be `int` specifically because some of these arrays would be used in communication
* This is requirement is for MPI as MPI_Alltoallv takes pointer to integer exclusively as count and displacement
* */
int * sendcnt = new int[A.getcommgrid3D()->GetGridLayers()];
int * sendprfl = new int[A.getcommgrid3D()->GetGridLayers()*3];
int * sdispls = new int[A.getcommgrid3D()->GetGridLayers()]();
int * recvcnt = new int[A.getcommgrid3D()->GetGridLayers()];
int * recvprfl = new int[A.getcommgrid3D()->GetGridLayers()*3];
int * rdispls = new int[A.getcommgrid3D()->GetGridLayers()]();
vector<IU> divisions3dPrefixSum(divisions3d.size());
divisions3dPrefixSum[0] = 0;
std::partial_sum(divisions3d.begin(), divisions3d.end()-1, divisions3dPrefixSum.begin()+1);
ColLexiCompare<IU,NUO> comp;
IU totsend = C_tuples->getnnz();
#pragma omp parallel for
for(int i=0; i < A.getcommgrid3D()->GetGridLayers(); ++i){
IU start_col = divisions3dPrefixSum[i];
IU end_col = divisions3dPrefixSum[i] + divisions3d[i];
std::tuple<IU, IU, NUO> search_tuple_start(0, start_col, NUO());
std::tuple<IU, IU, NUO> search_tuple_end(0, end_col, NUO());
std::tuple<IU, IU, NUO>* start_it = std::lower_bound(C_tuples->tuples, C_tuples->tuples + C_tuples->getnnz(), search_tuple_start, comp);
std::tuple<IU, IU, NUO>* end_it = std::lower_bound(C_tuples->tuples, C_tuples->tuples + C_tuples->getnnz(), search_tuple_end, comp);
// This type casting is important from semantic point of view
sendcnt[i] = (int)(end_it - start_it);
sendprfl[i*3+0] = (int)(sendcnt[i]); // Number of nonzeros in ith chunk
sendprfl[i*3+1] = (int)(A.GetLayerMat()->seqptr()->getnrow()); // Number of rows in ith chunk
sendprfl[i*3+2] = (int)(divisions3d[i]); // Number of columns in ith chunk
}
std::partial_sum(sendcnt, sendcnt+A.getcommgrid3D()->GetGridLayers()-1, sdispls+1);
// Send profile ready. Now need to update the tuples to reflect correct column id after column split.
for(int i=0; i < A.getcommgrid3D()->GetGridLayers(); ++i){
#pragma omp parallel for schedule(static)
for(int j = 0; j < sendcnt[i]; j++){
std::get<1>(C_tuples->tuples[sdispls[i]+j]) = std::get<1>(C_tuples->tuples[sdispls[i]+j]) - divisions3dPrefixSum[i];
}
}
MPI_Alltoall(sendprfl, 3, MPI_INT, recvprfl, 3, MPI_INT, A.getcommgrid3D()->GetFiberWorld());
for(int i = 0; i < A.getcommgrid3D()->GetGridLayers(); i++) recvcnt[i] = recvprfl[i*3];
std::partial_sum(recvcnt, recvcnt+A.getcommgrid3D()->GetGridLayers()-1, rdispls+1);
IU totrecv = std::accumulate(recvcnt,recvcnt+A.getcommgrid3D()->GetGridLayers(), static_cast<IU>(0));
std::tuple<LIC,LIC,NUO>* recvTuples = static_cast<std::tuple<LIC,LIC,NUO>*> (::operator new (sizeof(std::tuple<LIC,LIC,NUO>[totrecv])));
#ifdef TIMING
t2 = MPI_Wtime();
#endif
MPI_Alltoallv(C_tuples->tuples, sendcnt, sdispls, MPI_tuple, recvTuples, recvcnt, rdispls, MPI_tuple, A.getcommgrid3D()->GetFiberWorld());
delete C_tuples;
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[SUMMA3D]\tAlltoallv: %lf\n", (t3-t2));
#endif
vector<SpTuples<IU, NUO>*> recvChunks(A.getcommgrid3D()->GetGridLayers());
#pragma omp parallel for
for (int i = 0; i < A.getcommgrid3D()->GetGridLayers(); i++){
recvChunks[i] = new SpTuples<LIC, NUO>(recvcnt[i], recvprfl[i*3+1], recvprfl[i*3+2], recvTuples + rdispls[i], true, false);
}
// Free all memory except tempTuples; Because that memory is holding data of newly created local matrices after receiving.
DeleteAll(sendcnt, sendprfl, sdispls);
DeleteAll(recvcnt, recvprfl, rdispls);
MPI_Type_free(&MPI_tuple);
/*
* 3d-reduction ends
* */
#ifdef TIMING
t1 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[SUMMA3D]\tReduction time: %lf\n", (t1-t0));
#endif
#ifdef TIMING
t0 = MPI_Wtime();
#endif
/*
* 3d-merge starts
* */
SpTuples<IU, NUO> * merged_tuples = MultiwayMergeHash<SR, IU, NUO>(recvChunks, recvChunks[0]->getnrow(), recvChunks[0]->getncol(), false, false); // Do not delete
#ifdef TIMING
t1 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[SUMMA3D]\tMerge_fiber_time: %lf\n", (t1-t0));
#endif
//Create SpDCCol and delete merged_tuples;
UDERO * localResultant = new UDERO(*merged_tuples, false);
delete merged_tuples;
// Do not delete elements of recvChunks, because that would give segmentation fault due to double free
//delete [] recvTuples;
::operator delete(recvTuples);
for(int i = 0; i < recvChunks.size(); i++){
recvChunks[i]->tuples_deleted = true; // Temporary patch to avoid memory leak and segfault
delete recvChunks[i];
}
vector<SpTuples<IU,NUO>*>().swap(recvChunks);
/*
* 3d-merge ends
* */
std::shared_ptr<CommGrid3D> grid3d;
grid3d.reset(new CommGrid3D(A.getcommgrid3D()->GetWorld(), A.getcommgrid3D()->GetGridLayers(), A.getcommgrid3D()->GetGridRows(), A.getcommgrid3D()->GetGridCols(), A.isSpecial()));
SpParMat3D<IU, NUO, UDERO> C(localResultant, grid3d, A.isColSplit(), A.isSpecial());
return C;
}
/*
* Parameters:
* - computationKernel: 1 for hash-based, 2 for heap-based
* */
template <typename SR, typename NUO, typename UDERO, typename IU, typename NU1, typename NU2, typename UDERA, typename UDERB>
SpParMat3D<IU, NUO, UDERO> MemEfficientSpGEMM3D(SpParMat3D<IU, NU1, UDERA> & A, SpParMat3D<IU, NU2, UDERB> & B,
int phases, NUO hardThreshold, IU selectNum, IU recoverNum, NUO recoverPct, int kselectVersion, int computationKernel, int64_t perProcessMemory){
int myrank;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
typedef typename UDERA::LocalIT LIA;
typedef typename UDERB::LocalIT LIB;
typedef typename UDERO::LocalIT LIC;
/*
* Check if A and B are multipliable
* */
if(A.getncol() != B.getnrow()){
std::ostringstream outs;
outs << "Can not multiply, dimensions does not match"<< std::endl;
outs << A.getncol() << " != " << B.getnrow() << std::endl;
SpParHelper::Print(outs.str());
MPI_Abort(MPI_COMM_WORLD, DIMMISMATCH);
}
/*
* If provided number of phase is too low or too high then reset value of phase as 1
* */
if(phases < 1 || phases >= B.getncol()){
SpParHelper::Print("[MemEfficientSpGEMM3D]\tThe value of phases is too small or large. Resetting to 1.\n");
phases = 1;
}
double t0, t1, t2, t3, t4, t5, t6, t7, t8, t9; // To time different parts of the function
#ifdef TIMING
MPI_Barrier(B.getcommgrid3D()->GetWorld());
t0 = MPI_Wtime();
#endif
/*
* If per process memory is provided then calculate number of phases
* Otherwise, proceed to multiplication.
* */
if(perProcessMemory > 0) {
int p, calculatedPhases;
MPI_Comm_size(A.getcommgrid3D()->GetLayerWorld(),&p);
int64_t perNNZMem_in = sizeof(IU)*2 + sizeof(NU1);
int64_t perNNZMem_out = sizeof(IU)*2 + sizeof(NUO);
int64_t lannz = A.GetLayerMat()->getlocalnnz();
int64_t gannz = 0;
// Get maximum number of nnz owned by one process
MPI_Allreduce(&lannz, &gannz, 1, MPIType<int64_t>(), MPI_MAX, A.getcommgrid3D()->GetWorld());
//int64_t ginputMem = gannz * perNNZMem_in * 4; // Four pieces per process: one piece of own A and B, one piece of received A and B
int64_t ginputMem = gannz * perNNZMem_in * 5; // One extra copy for safety
// Estimate per layer nnz after multiplication. After this estimation each process would know an estimation of
// how many nnz the corresponding layer will have after the layerwise operation.
int64_t asquareNNZ = EstPerProcessNnzSUMMA(*(A.GetLayerMat()), *(B.GetLayerMat()), true);
int64_t gasquareNNZ;
MPI_Allreduce(&asquareNNZ, &gasquareNNZ, 1, MPIType<int64_t>(), MPI_MAX, A.getcommgrid3D()->GetFiberWorld());
// Atmost two copies, one of a process's own, another received from fiber reduction
int64_t gasquareMem = gasquareNNZ * perNNZMem_out * 2;
// Calculate estimated average degree after multiplication
int64_t d = ceil( ( ( gasquareNNZ / B.getcommgrid3D()->GetGridLayers() ) * sqrt(p) ) / B.GetLayerMat()->getlocalcols() );
// Calculate per column nnz how left after k-select. Minimum of average degree and k-select parameters.
int64_t k = std::min(int64_t(std::max(selectNum, recoverNum)), d );
//estimate output memory
int64_t postKselectOutputNNZ = ceil(( (B.GetLayerMat()->getlocalcols() / B.getcommgrid3D()->GetGridLayers() ) * k)/sqrt(p)); // If kselect is run
int64_t postKselectOutputMem = postKselectOutputNNZ * perNNZMem_out * 2;
double remainingMem = perProcessMemory*1000000000 - ginputMem - postKselectOutputMem;
int64_t kselectMem = B.GetLayerMat()->getlocalcols() * k * sizeof(NUO) * 3;
//inputMem + outputMem + asquareMem/phases + kselectmem/phases < memory
if(remainingMem > 0){
calculatedPhases = ceil( (gasquareMem + kselectMem) / remainingMem ); // If kselect is run
}
else calculatedPhases = -1;
int gCalculatedPhases;
MPI_Allreduce(&calculatedPhases, &gCalculatedPhases, 1, MPI_INT, MPI_MAX, A.getcommgrid3D()->GetFiberWorld());
if(gCalculatedPhases > phases) phases = gCalculatedPhases;
}
else{
// Do nothing
}
#ifdef TIMING
MPI_Barrier(B.getcommgrid3D()->GetWorld());
t1 = MPI_Wtime();
mcl3d_symbolictime+=(t1-t0);
//if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tSymbolic stage time: %lf\n", (t1-t0));
#endif
/*
* Calculate, accross fibers, which process should get how many columns after redistribution
* */
vector<LIB> divisions3d;
// Calculate split boundaries as if all contents of the layer is being re-distributed along fiber
// These boundaries will be used later on
B.CalculateColSplitDistributionOfLayer(divisions3d);
/*
* Split B according to calculated number of phases
* For better load balancing split B into nlayers*phases chunks
* */
vector<UDERB*> PiecesOfB;
vector<UDERB*> tempPiecesOfB;
UDERB CopyB = *(B.GetLayerMat()->seqptr());
CopyB.ColSplit(divisions3d, tempPiecesOfB); // Split B into `nlayers` chunks at first
for(int i = 0; i < tempPiecesOfB.size(); i++){
vector<UDERB*> temp;
tempPiecesOfB[i]->ColSplit(phases, temp); // Split each chunk of B into `phases` chunks
for(int j = 0; j < temp.size(); j++){
PiecesOfB.push_back(temp[j]);
}
}
vector<UDERO> toconcatenate;
//if(myrank == 0){
//fprintf(stderr, "[MemEfficientSpGEMM3D]\tRunning with phase: %d\n", phases);
//}
for(int p = 0; p < phases; p++){
/*
* At the start of each phase take appropriate pieces from previously created pieces of local B matrix
* Appropriate means correct pieces so that 3D-merge can be properly load balanced.
* */
vector<LIB> lbDivisions3d; // load balance friendly division
LIB totalLocalColumnInvolved = 0;
vector<UDERB*> targetPiecesOfB; // Pieces of B involved in current phase
for(int i = 0; i < PiecesOfB.size(); i++){
if(i % phases == p){
targetPiecesOfB.push_back(new UDERB(*(PiecesOfB[i])));
lbDivisions3d.push_back(PiecesOfB[i]->getncol());
totalLocalColumnInvolved += PiecesOfB[i]->getncol();
}
}
/*
* Create new local matrix by concatenating appropriately picked pieces
* */
UDERB * OnePieceOfB = new UDERB(0, (B.GetLayerMat())->seqptr()->getnrow(), totalLocalColumnInvolved, 0);
OnePieceOfB->ColConcatenate(targetPiecesOfB);
vector<UDERB*>().swap(targetPiecesOfB);
/*
* Create a new layer-wise distributed matrix with the newly created local matrix for this phase
* This matrix is used in SUMMA multiplication of respective layer
* */
SpParMat<IU, NU2, UDERB> OnePieceOfBLayer(OnePieceOfB, A.getcommgrid3D()->GetLayerWorld());
#ifdef TIMING
t0 = MPI_Wtime();
#endif
/*
* SUMMA Starts
* */
int stages, dummy; // last two parameters of ProductGrid are ignored for this multiplication
std::shared_ptr<CommGrid> GridC = ProductGrid((A.GetLayerMat()->getcommgrid()).get(),
(OnePieceOfBLayer.getcommgrid()).get(),
stages, dummy, dummy);
LIA C_m = A.GetLayerMat()->seqptr()->getnrow();
LIB C_n = OnePieceOfBLayer.seqptr()->getncol();
LIA ** ARecvSizes = SpHelper::allocate2D<LIA>(UDERA::esscount, stages);
LIB ** BRecvSizes = SpHelper::allocate2D<LIB>(UDERB::esscount, stages);
SpParHelper::GetSetSizes( *(A.GetLayerMat()->seqptr()), ARecvSizes, (A.GetLayerMat()->getcommgrid())->GetRowWorld() );
SpParHelper::GetSetSizes( *(OnePieceOfBLayer.seqptr()), BRecvSizes, (OnePieceOfBLayer.getcommgrid())->GetColWorld() );
// Remotely fetched matrices are stored as pointers
UDERA * ARecv;
UDERB * BRecv;
std::vector< SpTuples<LIC,NUO> *> tomerge;
int Aself = (A.GetLayerMat()->getcommgrid())->GetRankInProcRow();
int Bself = (OnePieceOfBLayer.getcommgrid())->GetRankInProcCol();
double Abcast_time = 0;
double Bbcast_time = 0;
double Local_multiplication_time = 0;
for(int i = 0; i < stages; ++i) {
std::vector<LIA> ess;
if(i == Aself){
ARecv = A.GetLayerMat()->seqptr(); // shallow-copy
}
else{
ess.resize(UDERA::esscount);
for(int j=0; j<UDERA::esscount; ++j) {
ess[j] = ARecvSizes[j][i]; // essentials of the ith matrix in this row
}
ARecv = new UDERA(); // first, create the object
}
#ifdef TIMING
t2 = MPI_Wtime();
#endif
if (Aself != i) {
ARecv->Create(ess);
}
Arr<LIA,NU1> Aarrinfo = ARecv->GetArrays();
for(unsigned int idx = 0; idx < Aarrinfo.indarrs.size(); ++idx) {
MPI_Bcast(Aarrinfo.indarrs[idx].addr, Aarrinfo.indarrs[idx].count, MPIType<IU>(), i, GridC->GetRowWorld());
}
for(unsigned int idx = 0; idx < Aarrinfo.numarrs.size(); ++idx) {
MPI_Bcast(Aarrinfo.numarrs[idx].addr, Aarrinfo.numarrs[idx].count, MPIType<NU1>(), i, GridC->GetRowWorld());
}
#ifdef TIMING
t3 = MPI_Wtime();
mcl3d_Abcasttime += (t3-t2);
Abcast_time += (t3-t2);
#endif
ess.clear();
if(i == Bself){
BRecv = OnePieceOfBLayer.seqptr(); // shallow-copy
}
else{
ess.resize(UDERB::esscount);
for(int j=0; j<UDERB::esscount; ++j) {
ess[j] = BRecvSizes[j][i];
}
BRecv = new UDERB();
}
MPI_Barrier(A.GetLayerMat()->getcommgrid()->GetWorld());
#ifdef TIMING
t2 = MPI_Wtime();
#endif
if (Bself != i) {
BRecv->Create(ess);
}
Arr<LIB,NU2> Barrinfo = BRecv->GetArrays();
for(unsigned int idx = 0; idx < Barrinfo.indarrs.size(); ++idx) {
MPI_Bcast(Barrinfo.indarrs[idx].addr, Barrinfo.indarrs[idx].count, MPIType<IU>(), i, GridC->GetColWorld());
}
for(unsigned int idx = 0; idx < Barrinfo.numarrs.size(); ++idx) {
MPI_Bcast(Barrinfo.numarrs[idx].addr, Barrinfo.numarrs[idx].count, MPIType<NU2>(), i, GridC->GetColWorld());
}
#ifdef TIMING
t3 = MPI_Wtime();
mcl3d_Bbcasttime += (t3-t2);
Bbcast_time += (t3-t2);
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
SpTuples<LIC,NUO> * C_cont;
if(computationKernel == 1){
C_cont = LocalSpGEMMHash<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
i != Aself, // 'delete A' condition
i != Bself, // 'delete B' condition
false); // not to sort each column
}
else if(computationKernel == 2){
C_cont = LocalSpGEMM<SR, NUO>
(*ARecv, *BRecv, // parameters themselves
i != Aself, // 'delete A' condition
i != Bself); // 'delete B' condition
}
#ifdef TIMING
t3 = MPI_Wtime();
mcl3d_localspgemmtime += (t3-t2);
Local_multiplication_time += (t3-t2);
#endif
if(!C_cont->isZero()) tomerge.push_back(C_cont);
}
SpHelper::deallocate2D(ARecvSizes, UDERA::esscount);
SpHelper::deallocate2D(BRecvSizes, UDERB::esscount);
#ifdef TIMING
t2 = MPI_Wtime();
#endif
SpTuples<LIC,NUO> * C_tuples;
if(computationKernel == 1) C_tuples = MultiwayMergeHash<SR>(tomerge, C_m, C_n, true, true); // Delete input arrays and sort
else if(computationKernel == 2) C_tuples = MultiwayMerge<SR>(tomerge, C_m, C_n, true); // Delete input arrays and sort
#ifdef TIMING
t3 = MPI_Wtime();
mcl3d_SUMMAmergetime += (t3-t2);
#endif
#ifdef TIMING
if(myrank == 0){
fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tAbcast_time: %lf\n", p, Abcast_time);
fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tBbcast_time: %lf\n", p, Bbcast_time);
fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tLocal_multiplication_time: %lf\n", p, Local_multiplication_time);
fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tSUMMA Merge time: %lf\n", p, (t3-t2));
}
#endif
/*
* SUMMA Ends
* */
#ifdef TIMING
t1 = MPI_Wtime();
mcl3d_SUMMAtime += (t1-t0);
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tSUMMA time: %lf\n", p, (t1-t0));
#endif
/*
* 3d-reduction starts
* */
#ifdef TIMING
t0 = MPI_Wtime();
t2 = MPI_Wtime();
#endif
MPI_Datatype MPI_tuple;
MPI_Type_contiguous(sizeof(std::tuple<LIC,LIC,NUO>), MPI_CHAR, &MPI_tuple);
MPI_Type_commit(&MPI_tuple);
/*
* Create a profile with information regarding data to be sent and received between layers
* These memory allocation needs to be `int` specifically because some of these arrays would be used in communication
* This is requirement is for MPI as MPI_Alltoallv takes pointer to integer exclusively as count and displacement
* */
int * sendcnt = new int[A.getcommgrid3D()->GetGridLayers()];
int * sendprfl = new int[A.getcommgrid3D()->GetGridLayers()*3];
int * sdispls = new int[A.getcommgrid3D()->GetGridLayers()]();
int * recvcnt = new int[A.getcommgrid3D()->GetGridLayers()];
int * recvprfl = new int[A.getcommgrid3D()->GetGridLayers()*3];
int * rdispls = new int[A.getcommgrid3D()->GetGridLayers()]();
vector<LIC> lbDivisions3dPrefixSum(lbDivisions3d.size());
lbDivisions3dPrefixSum[0] = 0;
std::partial_sum(lbDivisions3d.begin(), lbDivisions3d.end()-1, lbDivisions3dPrefixSum.begin()+1);
ColLexiCompare<LIC,NUO> comp;
LIC totsend = C_tuples->getnnz();
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tAllocation of alltoall information: %lf\n", p, (t3-t2));
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
#pragma omp parallel for
for(int i=0; i < A.getcommgrid3D()->GetGridLayers(); ++i){
LIC start_col = lbDivisions3dPrefixSum[i];
LIC end_col = lbDivisions3dPrefixSum[i] + lbDivisions3d[i];
std::tuple<LIC, LIC, NUO> search_tuple_start(0, start_col, NUO());
std::tuple<LIC, LIC, NUO> search_tuple_end(0, end_col, NUO());
std::tuple<LIC, LIC, NUO>* start_it = std::lower_bound(C_tuples->tuples, C_tuples->tuples + C_tuples->getnnz(), search_tuple_start, comp);
std::tuple<LIC, LIC, NUO>* end_it = std::lower_bound(C_tuples->tuples, C_tuples->tuples + C_tuples->getnnz(), search_tuple_end, comp);
// This type casting is important from semantic point of view
sendcnt[i] = (int)(end_it - start_it);
sendprfl[i*3+0] = (int)(sendcnt[i]); // Number of nonzeros in ith chunk
sendprfl[i*3+1] = (int)(A.GetLayerMat()->seqptr()->getnrow()); // Number of rows in ith chunk
sendprfl[i*3+2] = (int)(lbDivisions3d[i]); // Number of columns in ith chunk
}
std::partial_sum(sendcnt, sendcnt+A.getcommgrid3D()->GetGridLayers()-1, sdispls+1);
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tGetting Alltoall data ready: %lf\n", p, (t3-t2));
#endif
// Send profile ready. Now need to update the tuples to reflect correct column id after column split.
#ifdef TIMING
t2 = MPI_Wtime();
#endif
for(int i=0; i < A.getcommgrid3D()->GetGridLayers(); ++i){
#pragma omp parallel for schedule(static)
for(int j = 0; j < sendcnt[i]; j++){
std::get<1>(C_tuples->tuples[sdispls[i]+j]) = std::get<1>(C_tuples->tuples[sdispls[i]+j]) - lbDivisions3dPrefixSum[i];
}
}
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tGetting Alltoallv data ready: %lf\n", p, (t3-t2));
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
MPI_Alltoall(sendprfl, 3, MPI_INT, recvprfl, 3, MPI_INT, A.getcommgrid3D()->GetFiberWorld());
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tAlltoall: %lf\n", p, (t3-t2));
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
for(int i = 0; i < A.getcommgrid3D()->GetGridLayers(); i++) recvcnt[i] = recvprfl[i*3];
std::partial_sum(recvcnt, recvcnt+A.getcommgrid3D()->GetGridLayers()-1, rdispls+1);
LIC totrecv = std::accumulate(recvcnt,recvcnt+A.getcommgrid3D()->GetGridLayers(), static_cast<IU>(0));
std::tuple<LIC,LIC,NUO>* recvTuples = static_cast<std::tuple<LIC,LIC,NUO>*> (::operator new (sizeof(std::tuple<LIC,LIC,NUO>[totrecv])));
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tAllocation of receive data: %lf\n", p, (t3-t2));
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
MPI_Alltoallv(C_tuples->tuples, sendcnt, sdispls, MPI_tuple, recvTuples, recvcnt, rdispls, MPI_tuple, A.getcommgrid3D()->GetFiberWorld());
delete C_tuples;
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tAlltoallv: %lf\n", p, (t3-t2));
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
vector<SpTuples<LIC, NUO>*> recvChunks(A.getcommgrid3D()->GetGridLayers());
#pragma omp parallel for
for (int i = 0; i < A.getcommgrid3D()->GetGridLayers(); i++){
recvChunks[i] = new SpTuples<LIC, NUO>(recvcnt[i], recvprfl[i*3+1], recvprfl[i*3+2], recvTuples + rdispls[i], true, false);
}
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\trecvChunks creation: %lf\n", p, (t3-t2));
#endif
#ifdef TIMING
t2 = MPI_Wtime();
#endif
// Free all memory except tempTuples; Because that is holding data of newly created local matrices after receiving.
DeleteAll(sendcnt, sendprfl, sdispls);
DeleteAll(recvcnt, recvprfl, rdispls);
MPI_Type_free(&MPI_tuple);
#ifdef TIMING
t3 = MPI_Wtime();
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tMemory freeing: %lf\n", p, (t3-t2));
#endif
/*
* 3d-reduction ends
* */
#ifdef TIMING
t1 = MPI_Wtime();
mcl3d_reductiontime += (t1-t0);
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tReduction time: %lf\n", p, (t1-t0));
#endif
#ifdef TIMING
t0 = MPI_Wtime();
#endif
/*
* 3d-merge starts
* */
SpTuples<LIC, NUO> * merged_tuples;
if(computationKernel == 1) merged_tuples = MultiwayMergeHash<SR, LIC, NUO>(recvChunks, recvChunks[0]->getnrow(), recvChunks[0]->getncol(), false, false); // Do not delete
else if(computationKernel == 2) merged_tuples = MultiwayMerge<SR, LIC, NUO>(recvChunks, recvChunks[0]->getnrow(), recvChunks[0]->getncol(), false); // Do not delete
#ifdef TIMING
t1 = MPI_Wtime();
mcl3d_3dmergetime += (t1-t0);
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\t3D Merge time: %lf\n", p, (t1-t0));
#endif
/*
* 3d-merge ends
* */
#ifdef TIMING
t0 = MPI_Wtime();
#endif
// Do not delete elements of recvChunks, because that would give segmentation fault due to double free
::operator delete(recvTuples);
for(int i = 0; i < recvChunks.size(); i++){
recvChunks[i]->tuples_deleted = true; // Temporary patch to avoid memory leak and segfault
delete recvChunks[i]; // As the patch is used, now delete each element of recvChunks
}
vector<SpTuples<LIC,NUO>*>().swap(recvChunks); // As the patch is used, now delete recvChunks
// This operation is not needed if result can be used and discareded right away
// This operation is being done because it is needed by MCLPruneRecoverySelect
UDERO * phaseResultant = new UDERO(*merged_tuples, false);
delete merged_tuples;
SpParMat<IU, NUO, UDERO> phaseResultantLayer(phaseResultant, A.getcommgrid3D()->GetLayerWorld());
MCLPruneRecoverySelect(phaseResultantLayer, hardThreshold, selectNum, recoverNum, recoverPct, kselectVersion);
#ifdef TIMING
t1 = MPI_Wtime();
mcl3d_kselecttime += (t1-t0);
if(myrank == 0) fprintf(stderr, "[MemEfficientSpGEMM3D]\tPhase: %d\tMCLPruneRecoverySelect time: %lf\n",p, (t1-t0));
#endif
toconcatenate.push_back(phaseResultantLayer.seq());
#ifdef TIMING
if(myrank == 0) fprintf(stderr, "***\n");
#endif
}
for(int i = 0; i < PiecesOfB.size(); i++) delete PiecesOfB[i];
std::shared_ptr<CommGrid3D> grid3d;
grid3d.reset(new CommGrid3D(A.getcommgrid3D()->GetWorld(), A.getcommgrid3D()->GetGridLayers(), A.getcommgrid3D()->GetGridRows(), A.getcommgrid3D()->GetGridCols(), A.isSpecial()));
UDERO * localResultant = new UDERO(0, A.GetLayerMat()->seqptr()->getnrow(), divisions3d[A.getcommgrid3D()->GetRankInFiber()], 0);
localResultant->ColConcatenate(toconcatenate);
SpParMat3D<IU, NUO, UDERO> C3D(localResultant, grid3d, A.isColSplit(), A.isSpecial());
return C3D;
}
}
#endif
|