Spaces:
Sleeping
Sleeping
File size: 117,162 Bytes
dc2106c |
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 |
// Copyright (c) ONNX Project Contributors
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "onnx/defs/controlflow/utils.h"
#include "onnx/defs/schema.h"
namespace ONNX_NAMESPACE {
using SupportType = OpSchema::SupportType;
static std::vector<std::string> control_flow_types_ir9() {
auto t = OpSchema::all_tensor_types_ir9();
auto s = OpSchema::all_tensor_sequence_types_ir9();
auto o = OpSchema::all_optional_types_ir9();
t.insert(t.end(), s.begin(), s.end());
t.insert(t.end(), o.begin(), o.end());
return t;
}
static std::vector<std::string> control_flow_types_ir4() {
auto t = OpSchema::all_tensor_types_ir4();
auto s = OpSchema::all_tensor_sequence_types_ir4();
auto o = OpSchema::all_optional_types_ir4();
t.insert(t.end(), s.begin(), s.end());
t.insert(t.end(), o.begin(), o.end());
return t;
}
ONNX_OPERATOR_SET_SCHEMA(
If,
19,
OpSchema()
.SetDoc("If conditional")
.Input(0, "cond", "Condition for the if. The tensor must contain a single element.", "B")
.Output(
0,
"outputs",
"Values that are live-out to the enclosing scope. The return values in "
"the `then_branch` and `else_branch` must be of the same data type. "
"The `then_branch` and `else_branch` may produce tensors with the same "
"element type and different shapes. "
"If corresponding outputs from the then-branch and the else-branch have "
"static shapes S1 and S2, then the shape of the corresponding output "
"variable of the if-node (if present) must be compatible with both S1 "
"and S2 as it represents the union of both possible shapes."
"For example, if in a model file, the first "
"output of `then_branch` is typed float tensor with shape [2] and the "
"first output of `else_branch` is another float tensor with shape [3], "
"If's first output should have (a) no shape set, or (b) "
"a shape of rank 1 with neither `dim_value` nor `dim_param` set, or (c) "
"a shape of rank 1 with a unique `dim_param`. "
"In contrast, the first output cannot have the shape [2] since [2] and "
"[3] are not compatible.",
"V",
OpSchema::Variadic,
false)
.Attr(
"then_branch",
"Graph to run if condition is true. Has N outputs: values you wish to "
"be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the else_branch.",
AttributeProto::GRAPH)
.Attr(
"else_branch",
"Graph to run if condition is false. Has N outputs: values you wish to"
" be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the then_branch.",
AttributeProto::GRAPH)
.TypeConstraint(
"V",
control_flow_types_ir9(),
"All Tensor, Sequence(Tensor), Optional(Tensor), and Optional(Sequence(Tensor)) types up to IRv9.")
.TypeConstraint("B", {"tensor(bool)"}, "Only bool")
.TypeAndShapeInferenceFunction(IfInferenceFunction));
ONNX_OPERATOR_SET_SCHEMA(
If,
16,
OpSchema()
.SetDoc("If conditional")
.Input(0, "cond", "Condition for the if. The tensor must contain a single element.", "B")
.Output(
0,
"outputs",
"Values that are live-out to the enclosing scope. The return values in "
"the `then_branch` and `else_branch` must be of the same data type. "
"The `then_branch` and `else_branch` may produce tensors with the same "
"element type and different shapes. "
"If corresponding outputs from the then-branch and the else-branch have "
"static shapes S1 and S2, then the shape of the corresponding output "
"variable of the if-node (if present) must be compatible with both S1 "
"and S2 as it represents the union of both possible shapes."
"For example, if in a model file, the first "
"output of `then_branch` is typed float tensor with shape [2] and the "
"first output of `else_branch` is another float tensor with shape [3], "
"If's first output should have (a) no shape set, or (b) "
"a shape of rank 1 with neither `dim_value` nor `dim_param` set, or (c) "
"a shape of rank 1 with a unique `dim_param`. "
"In contrast, the first output cannot have the shape [2] since [2] and "
"[3] are not compatible.",
"V",
OpSchema::Variadic,
false)
.Attr(
"then_branch",
"Graph to run if condition is true. Has N outputs: values you wish to "
"be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the else_branch.",
AttributeProto::GRAPH)
.Attr(
"else_branch",
"Graph to run if condition is false. Has N outputs: values you wish to"
" be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the then_branch.",
AttributeProto::GRAPH)
.TypeConstraint(
"V",
control_flow_types_ir4(),
"All Tensor, Sequence(Tensor), Optional(Tensor), and Optional(Sequence(Tensor)) types up to IRv4.")
.TypeConstraint("B", {"tensor(bool)"}, "Only bool")
.TypeAndShapeInferenceFunction(IfInferenceFunction));
static const char* Loop_ver16_doc = R"DOC(
Generic Looping construct. This loop has multiple termination conditions:
1) Trip count. Iteration count specified at runtime. Set by
specifying the input M. Optional. Set to empty string to omit.
Note that a static trip count (specified at graph construction time) can be
specified by passing in a constant node for input M.
2) Loop termination condition. This is an input to the op that determines
whether to run the first iteration and also a loop-carried dependency for
the body graph. The body graph must yield a value for the condition variable,
whether this input is provided or not.
This table summarizes the operating modes of this operator with equivalent
C-style code:
Operator inputs defined as (max_trip_count, condition_var).
* input ("", ""):
for (int i=0; ; ++i) {
cond = ... // Note this value is ignored, but is required in the body
}
* input ("", cond) // Note this is analogous to a while loop
bool cond = ...;
for (int i=0; cond; ++i) {
cond = ...;
}
* input ("", 1) // Note this is analogous to a do-while loop
bool cond = true
for (int i=0; cond; ++i) {
cond = ...;
}
* input (trip_count, "") // Note this is analogous to a for loop
int trip_count = ...
for (int i=0; i < trip_count; ++i) {
cond = ...; // ignored
}
* input (trip_count, cond)
int trip_count = ...;
bool cond = ...;
for (int i=0; i < trip_count && cond; ++i) {
cond = ...;
}
*Sample usage - cond as well as trip count*
graph predict-net {
%a = Constant[value = <Scalar Tensor [3]>]()
%b = Constant[value = <Scalar Tensor [6]>]()
%keepgoing = Constant[value = <Scalar Tensor [1]>]()
%max_trip_count = Constant[value = <Scalar Tensor [10]>]()
%keepgoing_out, %b_out, %user_defined_vals = Loop[body = <graph body-net>](%max_trip_count, %keepgoing, %b)
return
}
graph body-net (
%i[INT32, scalar] // iteration number
%keepgoing_in[BOOL, scalar] // incoming loop-termination-condition; not used
%b_in[INT32, scalar] // incoming value of loop-carried-dependency b
) {
%my_local = Add(%a, %b_in)
%b_out = Sub(%a, %b_in) // outgoing value of loop-carried-dependency b
%keepgoing_out = Greater(%my_local, %b_out) // outgoing loop-termination-condition
%user_defined_val = Add(%b_in, %b_in) // scan-output value to be accumulated
return %keepgoing_out, %b_out, %user_defined_val
}
*Sample equivalent C code*
{
/* User-defined code (enclosing scope) */
int a = 3, b = 6;
bool keepgoing = true; // Analogous to input cond
/* End user-defined code */
/* Implicitly-defined code */
const int max_trip_count = 10; // Analogous to input M
int user_defined_vals[]; // Imagine this is resizable
/* End implicitly-defined code */
/* initialize loop-carried variables and scan-output variables */
bool keepgoing_out = keepgoing
int b_out = b
for (int i=0; i < max_trip_count && keepgoing_out; ++i) {
/* Implicitly-defined code: bind actual parameter values
to formal parameter variables of loop-body */
bool keepgoing_in = keepgoing_out;
bool b_in = b_out;
/* User-defined code (loop body) */
int my_local = a + b_in; // Reading value "a" from the enclosing scope is fine
b_out = a - b_in;
keepgoing_out = my_local > b_out;
user_defined_val = b_in + b_in; // b_in and b_out are different variables
/* End user-defined code */
/* Implicitly defined-code */
user_defined_vals[i] = user_defined_val // accumulate scan-output values
}
// int t = my_local; // Can't do this. my_local is not accessible here.
// The values below are bound to the output variables of the loop and therefore accessible
// b_out; user_defined_vals; keepgoing_out;
}
There are several things of note in this code snippet:
1) Values from the enclosing scope (i.e. variable "a" here) are in scope and can
be referenced in the inputs of the loop.
2) Any values computed in the loop body that needs to be used in a subsequent
iteration or after the loop are modelled using a pair of variables in the loop-body,
consisting of an input variable (eg., b_in) and an output variable (eg., b_out).
These are referred to as loop-carried dependences. The loop operation node
supplies the input value of the input variable for the first iteration, and
returns the output value of the output variable produced by the final
iteration.
3) Scan_output variables are used to implicitly concatenate values computed across
all the iterations. In the above example, the value of user_defined_val computed
over all iterations are concatenated and returned as the value of user_defined_vals
after the loop.
4) Values created in the body cannot be accessed in the enclosing scope,
except using the mechanism described above.
Note that the semantics of this op support "diagonal" or "wavefront" execution.
(See Step 3 here for an example:
https://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).
Frontends should emit multi-layer RNNs as a series of While operators (with
time being the inner looping dimension), with each successive layer consuming
the scan_outputs from the previous layer, possibly going through several
point-wise operators (e.g. dropout, residual connections, linear layer).
The input/output of subgraph (produced by loop node) matching is based on order instead of name. The implementation will figure out the names based on this order.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Loop,
19,
OpSchema()
.SetDoc(Loop_ver16_doc)
.Input(
0,
"M",
"A maximum trip-count for the loop specified at runtime. Optional."
" Pass empty string to skip.",
"I",
OpSchema::Optional)
.Input(
1,
"cond",
"A boolean termination condition. Optional. Pass empty string to skip.",
"B",
OpSchema::Optional)
.Input(
2,
"v_initial",
"The initial values of any loop-carried dependencies (values that "
"change across loop iterations)",
"V",
OpSchema::Variadic,
false,
0)
.Output(
0,
"v_final_and_scan_outputs",
"Final N loop carried dependency values then K scan_outputs. "
"Scan outputs must be Tensors.",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has 2+N inputs: (iteration_num, "
"condition, loop carried dependencies...). It has 1+N+K outputs: "
"(condition, loop carried dependencies..., scan_outputs...). Each "
"scan_output is created by concatenating the value of the specified "
"output value at the end of each iteration of the loop. It is an error"
" if the dimensions or data type of these scan_outputs change across loop"
" iterations.",
AttributeProto::GRAPH)
.TypeConstraint(
"V",
control_flow_types_ir9(),
"All Tensor, Sequence(Tensor), Optional(Tensor), and Optional(Sequence(Tensor)) types up to IRv9.")
.TypeConstraint("I", {"tensor(int64)"}, "tensor of int64, which should be a scalar.")
.TypeConstraint("B", {"tensor(bool)"}, "tensor of bool, which should be a scalar.")
.TypeAndShapeInferenceFunction(LoopInferenceFunction));
ONNX_OPERATOR_SET_SCHEMA(
Loop,
16,
OpSchema()
.SetDoc(Loop_ver16_doc)
.Input(
0,
"M",
"A maximum trip-count for the loop specified at runtime. Optional."
" Pass empty string to skip.",
"I",
OpSchema::Optional)
.Input(
1,
"cond",
"A boolean termination condition. Optional. Pass empty string to skip.",
"B",
OpSchema::Optional)
.Input(
2,
"v_initial",
"The initial values of any loop-carried dependencies (values that "
"change across loop iterations)",
"V",
OpSchema::Variadic,
false,
0)
.Output(
0,
"v_final_and_scan_outputs",
"Final N loop carried dependency values then K scan_outputs. "
"Scan outputs must be Tensors.",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has 2+N inputs: (iteration_num, "
"condition, loop carried dependencies...). It has 1+N+K outputs: "
"(condition, loop carried dependencies..., scan_outputs...). Each "
"scan_output is created by concatenating the value of the specified "
"output value at the end of each iteration of the loop. It is an error"
" if the dimensions or data type of these scan_outputs change across loop"
" iterations.",
AttributeProto::GRAPH)
.TypeConstraint(
"V",
control_flow_types_ir4(),
"All Tensor, Sequence(Tensor), Optional(Tensor), and Optional(Sequence(Tensor)) types up to IRv4.")
.TypeConstraint("I", {"tensor(int64)"}, "tensor of int64, which should be a scalar.")
.TypeConstraint("B", {"tensor(bool)"}, "tensor of bool, which should be a scalar.")
.TypeAndShapeInferenceFunction(LoopInferenceFunction));
static const char* scan_16_doc = R"DOC(
Scan can be used to iterate over one or more scan_input tensors,
constructing zero or more scan_output tensors. It combines ideas from general recurrences,
functional programming constructs such as scan, fold, map, and zip, and is intended to enable
generalizations of RNN-like constructs for sequence-to-sequence processing.
Other tensors (referred to as state_variables here) can be used to carry a state
when iterating from one element to another (similar to hidden-state in RNNs, also referred
to as loop-carried dependences in the context of loops).
Many common usages involve a single scan_input tensor (where functionality
similar to scan, fold and map can be obtained). When more than one scan_input is used,
a behavior similar to zip is obtained.
The attribute body must be a graph, specifying the computation to be performed in
every iteration. It takes as input the current values of the state_variables and
the current iterated element of the scan_inputs. It must return the (updated) values
of the state_variables and zero or more scan_output_element tensors. The values of the
scan_output_element tensors are concatenated over all the iterations to produce the
scan_output values of the scan construct (similar to the concatenated intermediate
hidden-state values of RNN-like constructs). All the output tensors (state_variables as
well as scan_output_element tensors) are required to have the same shape in each iteration
of the loop (a restriction imposed to enable efficient memory allocation).
Note that the iterated element passed to the body subgraph does not have a sequence
axis. It will have a rank one less than the rank of the corresponding scan_input.
The scan operation returns the final values of the state_variables as well as the
scan_outputs.
The optional attribute scan_input_directions specifies the direction (forward or backward)
for each scan input. If this attribute is omitted, all sequences are scanned in the forward
direction. A bidirectional scan may be performed by specifying the same tensor input twice
in the scan_inputs, once with a forward direction, and once with a backward direction.
The scan_output of the operation is produced by concatenating the scan_output_element
values produced by the body in each iteration. The optional attribute scan_output_directions
specifies the direction in which scan_output is constructed (by appending or prepending the
scan_output_element to scan_output in each iteration) for each scan_output. If this attribute
is omitted, the scan_output_element is appended to the scan_output in each iteration.
The optional attribute scan_input_axes specifies the axis to be scanned for each scan_input.
If omitted, every scan_input will be scanned in axis 0. For example, if axis 0 is the
batch axis and axis 1 is the time axis (to be scanned), specify an axis value of 1.
Note that scanning a non-zero axis may be less efficient than scanning axis zero.
The optional attribute scan_output_axes specifies the axis along which the scan_outputs
are accumulated for each scan_output. For example, if axis 1 is the time axis (to be
scanned) for both inputs and outputs, specify a scan_input axis and scan_output axis
value of 1.
Note that because of the ONNX restriction that only the last parameter of an operator can
be variadic, the initial-states and scan-inputs are listed together as one input parameter.
Similarly, the final-states and scan-outputs are listed together as one output parameter.
The attribute num_scan_inputs indicates the number M of scan-inputs.
The behavior of
Scan <
num_scan_inputs = m,
body = loop-body,
scan_input_axes = [axis_1, ..., axis_m]
> (init_1, ..., init_n, scan_1, ..., scan_m)
is equivalent to the following pseudo-code:
// scan_i.shape[axis_i] denotes the (max) sequence-length of scan_i
// scan_i.shape[axis_i] is required to be equal to scan_j.shape[axis_j] for all i,j.
sequence_length = scan_1.shape[axis_1];
// initialize state-variables
st_1 = init_1; ... st_n = init_n;
// initialize scan-output variables: [] denotes an empty tensor
scan_out_1 = []; ...; scan_out_k = [];
// identify number of iterations:
// execute loop
for (int t = 0; t < sequence_length; ++t) {
// generate the scan-input elements: the notation T<axis=k>[t] indicates the sub-tensor
// of rank one less than T obtained by indexing T at position t along axis k.
si_1 = scan_1<axis=axis_1>[t];
... ;
si_m = scan_m<axis=axis_m>[t];
// execute loop-body
st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)
// accumulate the scan-output elements
scan_out_1 = Concat<axis=0>(scan_out_1, so_1); ... ; scan_out_k = Concat<axis=0>(scan_out_k, so_k);
}
return st_1, ..., st_n, scan_out_1, ..., scan_out_k;
*Sample usage: Encoding RNN using a Scan*
The following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,
recurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can
be encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes
%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these
values are computed in the outer graph, they need to be passed in as extra state_variables.
graph rnn-encoding {
%H_0 = ...
%X = ...
%Y_h, %Y = Scan[body = <graph rnn-cell-1>, num_scan_inputs=1](%H_0, %X)
return %Y, %Y_h
}
graph rnn-cell-1 (
%H_tminus1[FLOAT, tensor]
%X_t[FLOAT, tensor]
) {
%Wi = ...
%Ri = ...
%Wbi = ...
%Rbi = ...
%t1 = X_t * (Wi^T)
%t2 = H_tminus1*(Ri^T)
%t3 = Add(%t1, %t2)
%t4 = Add(%t3, %Wbi)
%t5 = Add(%t4, %Rbi)
%Ht = Tanh(%t5)
%Accumulate = Identity(%Ht)
return %Ht, %Accumulate
}
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Scan,
19,
OpSchema()
.SetDoc(scan_16_doc)
.Input(
0,
"initial_state_and_scan_inputs",
"Initial values of the loop's N state variables followed by M scan_inputs",
"V",
OpSchema::Variadic,
false)
.Output(
0,
"final_state_and_scan_outputs",
"Final values of the loop's N state variables followed by K scan_outputs",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has N+M inputs: "
"(loop state variables..., scan_input_elts...). It has N+K outputs: "
"(loop state variables..., scan_output_elts...). Each "
"scan_output is created by concatenating the value of the specified "
"scan_output_elt value at the end of each iteration of the loop. It is an error"
" if the dimensions of these values change across loop iterations.",
AttributeProto::GRAPH,
true)
.Attr("num_scan_inputs", "An attribute specifying the number of scan_inputs M. ", AttributeProto::INT, true)
.Attr(
"scan_input_directions",
"An optional list of M flags. The i-th element of the list specifies the direction "
"to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 "
"indicates reverse direction. "
"If omitted, all scan_input tensors will be scanned in the forward direction.",
AttributeProto::INTS,
false)
.Attr(
"scan_output_directions",
"An optional list of K flags, one for each scan_output. The i-th element of the list "
"specifies whether the i-th scan_output should be constructed by appending or "
"prepending a new value in each iteration: 0 indicates appending and 1 "
"indicates prepending. "
"If omitted, all scan_output tensors will be produced by appending a value "
"in each iteration.",
AttributeProto::INTS,
false)
.Attr(
"scan_input_axes",
"An optional list of M flags. The i-th element of the list specifies the axis "
"to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will "
"be used as the scan axis for every scan_input. Negative value for an axis means "
"counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).",
AttributeProto::INTS,
false)
.Attr(
"scan_output_axes",
"An optional list of K flags. The i-th element of the list specifies the axis "
"for the i-th scan_output. The scan outputs are accumulated along the specified "
"axis. If omitted, 0 will be used as the scan axis for every scan_output. "
"Negative value for an axis means counting dimensions from the back. Accepted "
"range is [-r, r-1].",
AttributeProto::INTS,
false)
.TypeConstraint("V", OpSchema::all_tensor_types_ir9(), "All Tensor types up to IRv9.")
.TypeAndShapeInferenceFunction(ScanInferenceFunction)); // Shares same shape inference as opset 11
ONNX_OPERATOR_SET_SCHEMA(
Scan,
16,
OpSchema()
.SetDoc(scan_16_doc)
.Input(
0,
"initial_state_and_scan_inputs",
"Initial values of the loop's N state variables followed by M scan_inputs",
"V",
OpSchema::Variadic,
false)
.Output(
0,
"final_state_and_scan_outputs",
"Final values of the loop's N state variables followed by K scan_outputs",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has N+M inputs: "
"(loop state variables..., scan_input_elts...). It has N+K outputs: "
"(loop state variables..., scan_output_elts...). Each "
"scan_output is created by concatenating the value of the specified "
"scan_output_elt value at the end of each iteration of the loop. It is an error"
" if the dimensions of these values change across loop iterations.",
AttributeProto::GRAPH,
true)
.Attr("num_scan_inputs", "An attribute specifying the number of scan_inputs M. ", AttributeProto::INT, true)
.Attr(
"scan_input_directions",
"An optional list of M flags. The i-th element of the list specifies the direction "
"to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 "
"indicates reverse direction. "
"If omitted, all scan_input tensors will be scanned in the forward direction.",
AttributeProto::INTS,
false)
.Attr(
"scan_output_directions",
"An optional list of K flags, one for each scan_output. The i-th element of the list "
"specifies whether the i-th scan_output should be constructed by appending or "
"prepending a new value in each iteration: 0 indicates appending and 1 "
"indicates prepending. "
"If omitted, all scan_output tensors will be produced by appending a value "
"in each iteration.",
AttributeProto::INTS,
false)
.Attr(
"scan_input_axes",
"An optional list of M flags. The i-th element of the list specifies the axis "
"to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will "
"be used as the scan axis for every scan_input. Negative value for an axis means "
"counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).",
AttributeProto::INTS,
false)
.Attr(
"scan_output_axes",
"An optional list of K flags. The i-th element of the list specifies the axis "
"for the i-th scan_output. The scan outputs are accumulated along the specified "
"axis. If omitted, 0 will be used as the scan axis for every scan_output. "
"Negative value for an axis means counting dimensions from the back. Accepted "
"range is [-r, r-1].",
AttributeProto::INTS,
false)
.TypeConstraint("V", OpSchema::all_tensor_types_ir4(), "All Tensor types up to IRv4.")
.TypeAndShapeInferenceFunction(ScanInferenceFunction)); // Shares same shape inference as opset 11
void ScanInferenceFunctionOpset8(InferenceContext& ctx) {
// NOTE:
// The first input to Scan is sequence_lens. We skip that when processing
// inputs in many places below, so the - 1 in multiple places is due to that.
auto num_inputs = ctx.getNumInputs();
auto num_scan_inputs = narrow_cast<size_t>(ctx.getAttribute("num_scan_inputs")->i());
auto num_loop_state_vars = num_inputs - 1 - num_scan_inputs;
std::vector<TypeProto> temporary_type_protos;
temporary_type_protos.reserve(num_inputs);
std::vector<const TypeProto*> subgraph_input_types;
TensorShapeProto_Dimension batch_size_dim;
TensorShapeProto_Dimension sequence_len_dim;
for (size_t i = 1; i < num_inputs; ++i) {
bool is_loop_state_var = (i - 1) < num_loop_state_vars;
bool has_shape = hasInputShape(ctx, i);
const auto* input_type = ctx.getInputType(i);
// Enforce type constraint for inputs
if (!input_type || !input_type->has_tensor_type()) {
fail_type_inference("Scan input ", i, " was not a tensor.");
}
if (is_loop_state_var) {
// If it's a loop state variable we can propagate type and shape 1:1 to
// the matching Scan output.
// We can also pass through the type and shape to the subgraph but need to
// remove the batch size dimension from the shape.
propagateElemTypeFromInputToOutput(ctx, i, i - 1);
if (has_shape) {
propagateShapeFromInputToOutput(ctx, i, i - 1);
// remove batch size dimension and add to subgraph_input_types
temporary_type_protos.push_back(RemoveDimensionsFromShape(*input_type, 1));
subgraph_input_types.push_back(&temporary_type_protos.back());
} else {
subgraph_input_types.push_back(input_type);
}
} else {
// For other inputs there is no fixed relationships to the Scan outputs,
// so we don't propagate type/shape information.
// We can pass through the type and shape to the subgraph inputs but need
// to remove the batch size and sequence length dimensions from the shape.
if (has_shape) {
// remove batch size and sequence length dimensions and add to
// subgraph_input_types
temporary_type_protos.push_back(RemoveDimensionsFromShape(*input_type, 2));
subgraph_input_types.push_back(&temporary_type_protos.back());
// update batch_size and sequence_len if a value is available
const auto& shape = input_type->tensor_type().shape();
if (shape.dim_size() > 2) {
const auto& dims = shape.dim();
mergeInDimensionInfo(dims.Get(0), batch_size_dim, 0);
mergeInDimensionInfo(dims.Get(1), sequence_len_dim, 1);
}
} else {
subgraph_input_types.push_back(input_type);
}
}
}
// Run inferencing on the subgraph
std::vector<const TypeProto*> output_types;
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("body");
if (graphInferencer) {
std::vector<const TensorProto*> input_data;
for (size_t i = 1; i < num_inputs; ++i) {
input_data.push_back(ctx.getInputData(i));
}
output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
// if empty(), assume inferencing was skipped
if (!output_types.empty()) {
auto num_outputs = ctx.getNumOutputs();
if (output_types.size() != num_outputs) {
fail_type_inference(
"Graph attribute inferencing returned type information for ",
output_types.size(),
" outputs. Expected ",
num_outputs);
}
// propagate type/shape information for loop state variables and outputs
for (size_t i = 0; i < num_outputs; ++i) {
const bool is_loop_state_var = i < num_loop_state_vars;
auto* subgraph_output_type = output_types[i];
auto* scan_output_type = ctx.getOutputType(i);
if (!subgraph_output_type->has_tensor_type()) {
fail_type_inference("Scan 'body' subgraph outputs should all be tensors but output ", i, " was not");
}
// propagate output type. loop state vars were done in the above code.
if (!is_loop_state_var) {
scan_output_type->mutable_tensor_type()->set_elem_type(subgraph_output_type->tensor_type().elem_type());
}
// propagate shape
if (subgraph_output_type->tensor_type().has_shape()) {
// we need to add in the batch size and sequence length values if
// available before merging with any existing info. Create a copy of the
// inferred type info from the subgraph to do that.
TypeProto inferred_type(*subgraph_output_type);
auto* mutable_inferred_tensor_type = inferred_type.mutable_tensor_type();
auto* mutable_inferred_shape = mutable_inferred_tensor_type->mutable_shape();
mutable_inferred_shape->clear_dim();
*mutable_inferred_shape->add_dim() = batch_size_dim;
if (!is_loop_state_var) {
*mutable_inferred_shape->add_dim() = sequence_len_dim;
}
for (const auto& dim : subgraph_output_type->tensor_type().shape().dim()) {
(*mutable_inferred_shape->add_dim()) = dim;
}
auto* mutable_scan_output_tensor_type = scan_output_type->mutable_tensor_type();
mergeInShapeInfo(*mutable_inferred_tensor_type, *mutable_scan_output_tensor_type);
}
}
}
}
int handle_negative_axis_validate_opset9(const std::string& attrib, int axis, int rank) {
if (!(-rank <= axis && axis < rank)) {
fail_shape_inference(attrib, " axis value ", axis, " is invalid for a tensor of rank ", rank);
}
return (axis >= 0 ? axis : axis + rank);
}
void ScanInferenceFunctionOpset9(InferenceContext& ctx) {
auto num_inputs = ctx.getNumInputs();
auto num_scan_inputs = narrow_cast<size_t>(ctx.getAttribute("num_scan_inputs")->i());
auto num_loop_state_vars = num_inputs - num_scan_inputs;
auto num_outputs = ctx.getNumOutputs();
auto num_scan_outputs = num_outputs - num_loop_state_vars;
std::vector<int64_t> axes, output_axes;
if (getRepeatedAttribute(ctx, "scan_input_axes", axes)) {
if (axes.size() != num_scan_inputs) {
fail_shape_inference(
"Number of scan input axes specified (",
axes.size(),
") is not equal to number of scan inputs (",
num_scan_inputs,
").");
}
} else {
axes.insert(axes.end(), num_scan_inputs, 0);
}
if (getRepeatedAttribute(ctx, "scan_output_axes", output_axes)) {
if (output_axes.size() != num_scan_outputs) {
fail_shape_inference(
"Number of scan output axes specified (",
output_axes.size(),
") is not equal to number of scan outputs (",
num_scan_outputs,
").");
}
} else {
output_axes.insert(output_axes.end(), num_scan_outputs, 0);
}
std::vector<TypeProto> temporary_type_protos;
temporary_type_protos.reserve(num_inputs);
std::vector<const TypeProto*> subgraph_input_types;
TensorShapeProto_Dimension sequence_len_dim;
for (size_t i = 0; i < num_inputs; ++i) {
bool is_loop_state_var = i < num_loop_state_vars;
bool has_shape = hasInputShape(ctx, i);
const auto* input_type = ctx.getInputType(i);
// Enforce type constraint for inputs
if (!input_type || !input_type->has_tensor_type()) {
fail_type_inference("Scan input ", i, " was not a tensor.");
}
if (is_loop_state_var) {
// If it's a loop state variable we can propagate type and shape 1:1 to
// the matching Scan output.
// We can also pass through the type and shape to the subgraph but need to
// remove the batch size dimension from the shape.
propagateElemTypeFromInputToOutput(ctx, i, i);
if (has_shape)
propagateShapeFromInputToOutput(ctx, i, i);
subgraph_input_types.push_back(input_type);
} else {
// For other inputs there is no fixed relationships to the Scan outputs,
// so we don't propagate type/shape information.
// We can pass through the type and shape to the subgraph inputs but
// need to remove the sequence length dimensions from the shape.
if (has_shape) {
const auto& shape = input_type->tensor_type().shape();
// remove sequence length dimensions and add to subgraph_input_types
int axis = static_cast<int>(axes[i - num_loop_state_vars]);
axis = handle_negative_axis_validate_opset9("scan_input_axes", axis, shape.dim_size());
// update sequence_len if a value is available
const auto& dims = shape.dim();
mergeInDimensionInfo(dims.Get(axis), sequence_len_dim, 1);
temporary_type_protos.push_back(RemoveIthDimensionFromShape(*input_type, axis));
subgraph_input_types.push_back(&temporary_type_protos.back());
} else {
subgraph_input_types.push_back(input_type);
}
}
}
// Run inferencing on the subgraph
std::vector<const TypeProto*> output_types;
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("body");
if (graphInferencer) {
std::vector<const TensorProto*> input_data;
for (size_t i = 0; i < num_inputs; ++i) {
// ctx.getInputData(i), the input to scan, does not represent the input to
// scan body. So, we pass in null, to represent an unknown value.
input_data.push_back(nullptr);
}
output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
// if empty(), assume inferencing was skipped
if (!output_types.empty()) {
if (output_types.size() != num_outputs) {
fail_type_inference(
"Graph attribute inferencing returned type information for ",
output_types.size(),
" outputs. Expected ",
num_outputs);
}
// propagate type/shape information for loop state variables and outputs
for (size_t i = 0; i < num_outputs; ++i) {
const bool is_loop_state_var = i < num_loop_state_vars;
auto* subgraph_output_type = output_types[i];
auto* scan_output_type = ctx.getOutputType(i);
auto* mutable_scan_output_tensor_type = scan_output_type->mutable_tensor_type();
if (!subgraph_output_type->has_tensor_type()) {
fail_type_inference("Scan 'body' subgraph outputs should all be tensors but output ", i, " was not");
}
auto& subgraph_output_tensor_type = subgraph_output_type->tensor_type();
if (is_loop_state_var) {
// merge shape; type already propagated
mergeInShapeInfo(subgraph_output_tensor_type, *mutable_scan_output_tensor_type);
} else {
scan_output_type->mutable_tensor_type()->set_elem_type(subgraph_output_tensor_type.elem_type());
// propagate shape
if (subgraph_output_tensor_type.has_shape()) {
// infer shape of scan-output from the shape of scan-output-element
// by adding sequence-length at the correct axis position
const TensorShapeProto& subgraph_output_shape = subgraph_output_tensor_type.shape();
TensorShapeProto inferred_shape;
auto subgraph_output_rank = subgraph_output_shape.dim_size();
auto output_rank = subgraph_output_rank + 1;
int output_axis = static_cast<int>(output_axes[i - num_loop_state_vars]);
output_axis = handle_negative_axis_validate_opset9("scan_output_axes", output_axis, output_rank);
for (int j = 0; j < output_axis; ++j)
*(inferred_shape.add_dim()) = subgraph_output_shape.dim(j);
*(inferred_shape.add_dim()) = sequence_len_dim;
for (int j = output_axis; j < subgraph_output_rank; ++j)
*(inferred_shape.add_dim()) = subgraph_output_shape.dim(j);
// Merge inferred shape with existing shape information
mergeInShapeInfo(inferred_shape, *mutable_scan_output_tensor_type);
}
}
}
}
}
static const char* scan_opset8_doc = R"DOC(
Scan can be used to iterate over one or more scan_input tensors,
constructing zero or more scan_output tensors. It combines ideas from general recurrences,
functional programming constructs such as scan, fold, map, and zip, and is intended to enable
generalizations of RNN-like constructs for sequence-to-sequence processing.
Other tensors (referred to as state_variables here) can be used to carry a state
when iterating from one element to another (similar to hidden-state in RNNs, also referred
to as loop-carried dependences in the context of loops). All these tensors are required to
have the same shape in each iteration of the loop (a restriction imposed to enable efficient
memory allocation). Many common usages involve a single scan_input tensor (where functionality
similar to scan, fold and map can be obtained). When more than one scan_input is used,
a behavior similar to zip is obtained.
The attribute body must be a graph, specifying the computation to be performed in
every iteration. It takes as input the current values of the state_variables and
the current iterated element of the scan_inputs. It must return the (updated) values
of the state_variables and zero or more scan_output_element tensors. The values of the
scan_output_element tensors are concatenated over all the iterations to produce the
scan_output values of the scan construct (similar to the concatenated intermediate
hidden-state values of RNN-like constructs).
The scan operation returns the final values of the state_variables as well as the
scan_outputs.
The operation supports batching, and the batch-axis is required to be 0.
When multiple scan_input tensors are used, they must all have the same batch-size,
and they must all have the same maximum-sequence-length (the dimensionality of the
sequence axis or scan axis). The sequence axis or scan axis is required to be 1.
The operation has an optional sequence_lens input (of shape [BATCH_SIZE]) to
allow variable length sequences of length <= the maximum-sequence-length. If this
input is not specified, all sequences are assumed to be of length equal to
maximum-sequence-length. For variable length input sequences, the scan_outputs
will consist of a sequence of same length as the input, padded to the
maximum-sequence-length.
The optional attribute directions can be used to scan a sequence in the reverse direction.
If this attribute is omitted, all sequences are scanned in the forward direction.
A bidirectional scan be performed by specifying the same tensor input twice in the
scan_inputs, once with a forward direction, and once with a backward direction.
Note that because of the ONNX restriction that only the last parameter of an operator can
be variadic, the initial-states and scan-inputs are listed together as one input parameter.
Similarly, the final-states and scan-outputs are listed together as one output parameter.
The attribute num_scan_inputs indicates the number M of scan-inputs.
The behavior of
Scan <
num_scan_inputs = m,
body = loop-body
> (sequence_lengths, init_1, ..., init_n, scan_1, ..., scan_m)
is equivalent to the following pseudo-code:
// T.shape[0] denotes the batch-size of T
// The batch-size of scan_1, ..., scan_m are all required to be equal
batch_size = scan_1.shape[0];
// scan_i.shape[1] denotes the (max) sequence-length of scan_i
// scan_i.shape[1] is required to be equal to scan_j.shape[1] for all i,j.
max_sequence_length = scan_1.shape[1];
for (int batch = 0; batch < batch_size; ++batch) {
// initialize state-variables
st_1 = init_1; ... st_n = init_n;
// initialize scan-output variables: [] denotes an empty tensor
scan_out_1 = []; ...; scan_out_k = [];
// identify number of iterations:
N = (sequence_lengths specified) ? sequence_lengths[batch] : max_sequence_length;
// execute loop
for (int t = 0; t < N; ++t) {
// generate the scan-input elements: the notation T<axis=k>[t] indicates the sub-tensor
// of rank one less than T obtained by indexing T at position t along axis k.
si_1 = (scan_1<axis=0>[batch])<axis=1>[t];
... ;
si_m = (scan_m<axis=0>[batch])<axis=1>[t];
// execute loop-body
st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)
// accumulate the scan-output elements
scan_out_1 = Concat<axis=0>(scan_out_1, so_1); ... ; scan_out_k = Concat<axis=0>(scan_out_k, so_k);
}
// accumulate the outputs for this batch:
bst_1[batch] = st_1; ..., bst_n[batch] = st_n;
// Note scan-outputs will have size max_sequence_length, but only first N values will be meaningful.
// The remaining values have an undefined value.
b_scan_out_1[batch] = scan_out_1; ...; b_scan_out_k[batch] = scan_out_k;
}
return bst_1, ..., bst_n, b_scan_out_1, ..., b_scan_out_k;
*Sample usage: Encoding RNN using a Scan*
The following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,
recurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can
be encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes
%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these
values are computed in the outer graph, they need to be passed in as extra state_variables.
graph rnn-encoding {
%H_0 = ...
%X = ...
%Y_h, %Y = Scan[body = <graph rnn-cell-1>, num_scan_inputs=1]("", %H_0, %X)
return %Y, %Y_h
}
graph rnn-cell-1 (
%H_tminus1[FLOAT, tensor]
%X_t[FLOAT, tensor]
) {
%Wi = ...
%Ri = ...
%Wbi = ...
%Rbi = ...
%t1 = X_t * (Wi^T)
%t2 = H_tminus1*(Ri^T)
%t3 = Add(%t1, %t2)
%t4 = Add(%t3, %Wbi)
%t5 = Add(%t4, %Rbi)
%Ht = Tanh(%t5)
%Accumulate = Identity(%Ht)
return %Ht, %Accumulate
}
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Scan,
8,
OpSchema()
.SetDoc(scan_opset8_doc)
.Input(
0,
"sequence_lens",
"Optional tensor specifying lengths of the sequences in a batch. "
"If this input is not specified, all sequences are assumed to be of "
"the maximum sequence length (the dimension of the sequence axis of "
"the scan_input tensors).",
"I",
OpSchema::Optional)
.Input(
1,
"initial_state_and_scan_inputs",
"Initial values of the loop's N state variables followed by M scan_inputs",
"V",
OpSchema::Variadic,
false)
.Output(
0,
"final_state_and_scan_outputs",
"Final values of the loop's N state variables followed by K scan_outputs",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has N+M inputs: "
"(loop state variables..., scan_input_elts...). It has N+K outputs: "
"(loop state variables..., scan_output_elts...). Each "
"scan_output is created by concatenating the value of the specified "
"scan_output_elt value at the end of each iteration of the loop. It is an error"
" if the dimensions of these values change across loop iterations.",
AttributeProto::GRAPH,
true)
.Attr("num_scan_inputs", "An attribute specifying the number of scan_inputs M. ", AttributeProto::INT, true)
.Attr(
"directions",
"An optional list of M flags. The i-th element of the list specifies the direction "
"to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 "
"indicates reverse direction. "
"If omitted, all scan_input tensors will be scanned in the forward direction.",
AttributeProto::INTS,
false)
.TypeConstraint("I", {"tensor(int64)"}, "Int64 tensor")
.TypeConstraint("V", OpSchema::all_tensor_types(), "All Tensor types")
.TypeAndShapeInferenceFunction(ScanInferenceFunctionOpset8));
void LoopInferenceFunctionOpset8(InferenceContext& ctx) {
auto num_inputs = ctx.getNumInputs();
auto num_loop_state_vars = num_inputs - 2; // skip 'M' and 'cond'
std::vector<const TypeProto*> subgraph_input_types;
std::vector<TypeProto> temporary_type_protos;
temporary_type_protos.reserve(num_inputs - 2);
// create TypeProto to validate iteration number type is the same as the
// optional 'M' input for max iterations.
TypeProto iter_num_type;
iter_num_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT64);
subgraph_input_types.push_back(&iter_num_type);
// 'cond'
subgraph_input_types.push_back(ctx.getInputType(1));
// loop state value types get propagated to outputs, but shape may change
// across iterations so don't propagate it to the outputs and don't pass it
// into the subgraph inferencing
for (size_t i = 2; i < num_inputs; ++i) {
propagateElemTypeFromInputToOutput(ctx, i, i - 2);
// copy so we can remove the shape before passing to the subgraph
// inferencing
temporary_type_protos.push_back(*ctx.getInputType(i));
auto& input_type = temporary_type_protos.back();
input_type.mutable_tensor_type()->clear_shape();
subgraph_input_types.push_back(&input_type);
}
// Run inferencing on the subgraph
std::vector<const TypeProto*> subgraph_output_types;
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("body");
if (graphInferencer) {
std::vector<const TensorProto*> input_data;
input_data.push_back(nullptr); // iteration number
for (size_t i = 1; i < num_inputs; ++i) {
input_data.push_back(ctx.getInputData(i));
}
subgraph_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
// if empty(), assume inferencing was skipped
if (!subgraph_output_types.empty()) {
auto num_outputs = ctx.getNumOutputs();
// subgraph outputs the condition value first but that is only used
// internally and not returned by Loop.
if (subgraph_output_types.size() != num_outputs + 1) {
fail_type_inference(
"Graph attribute inferencing returned type information for ",
subgraph_output_types.size(),
" outputs. Expected ",
num_outputs + 1);
}
// check loop state values match. we should already have type/shape info
for (size_t i = 0; i < num_outputs; ++i) {
auto* subgraph_output_type = subgraph_output_types[i + 1]; // skip 'cond'
auto* loop_output_type = ctx.getOutputType(i);
const bool is_loop_state_var = i < num_loop_state_vars;
if (!subgraph_output_type->has_tensor_type()) {
fail_type_inference(
"Loop 'body' subgraph outputs should all be tensors but output ",
i,
" was ",
subgraph_output_type->value_case());
}
// if there's an existing type check it matches. otherwise propagate
propagateElemTypeWithValidation(subgraph_output_type, loop_output_type);
if (is_loop_state_var) {
// shape may change across iterations so ignore.
} else {
// propagate shape
if (subgraph_output_type->tensor_type().has_shape()) {
// per iteration output. first dimension will be number of iterations
// but we don't know that value yet
TypeProto inferred_type(*subgraph_output_type);
auto* mutable_inferred_tensor_type = inferred_type.mutable_tensor_type();
auto* mutable_inferred_shape = mutable_inferred_tensor_type->mutable_shape();
mutable_inferred_shape->clear_dim();
// add empty dimension for number of iterations
mutable_inferred_shape->add_dim();
// add dimensions from subgraph output shape
for (const auto& dim : subgraph_output_type->tensor_type().shape().dim()) {
(*mutable_inferred_shape->add_dim()) = dim;
}
mergeInShapeInfo(*mutable_inferred_tensor_type, *loop_output_type->mutable_tensor_type());
}
}
}
}
}
static const char* Loop_ver1_doc = R"DOC(
Generic Looping construct. This loop has multiple termination conditions:
1) Trip count. Iteration count specified at runtime. Set by
specifying the input M. Optional. Set to empty string to omit.
Note that a static trip count (specified at graph construction time) can be
specified by passing in a constant node for input M.
2) Loop termination condition. This is an input to the op that determines
whether to run the first iteration and also a loop-carried dependency for
the body graph. The body graph must yield a value for the condition variable,
whether this input is provided or not.
This table summarizes the operating modes of this operator with equivalent
C-style code:
Operator inputs defined as (max_trip_count, condition_var).
input ("", ""):
for (int i=0; ; ++i) {
cond = ... // Note this value is ignored, but is required in the body
}
input ("", cond) // Note this is analogous to a while loop
bool cond = ...;
for (int i=0; cond; ++i) {
cond = ...;
}
input ("", 1) // Note this is analogous to a do-while loop
bool cond = true
for (int i=0; cond; ++i) {
cond = ...;
}
input (trip_count, "") // Note this is analogous to a for loop
int trip_count = ...
for (int i=0; i < trip_count; ++i) {
cond = ...; // ignored
}
input (trip_count, cond)
int trip_count = ...;
bool cond = ...;
for (int i=0; i < trip_count && cond; ++i) {
cond = ...;
}
*Sample usage - cond as well as trip count*
graph predict-net {
%a = Constant[value = <Scalar Tensor [3]>]()
%b = Constant[value = <Scalar Tensor [6]>]()
%keepgoing = Constant[value = <Scalar Tensor [1]>]()
%max_trip_count = Constant[value = <Scalar Tensor [10]>]()
%keepgoing_out, %b_out, %user_defined_vals = Loop[body = <graph body-net>](%max_trip_count, %keepgoing, %b)
return
}
graph body-net (
%i[INT32, scalar]
%keepgoing[BOOL, scalar]
%b[INT32, scalar]
) {
%my_local = Add(%a, %b)
%b_out = Sub(%a, %b)
%keepgoing_out = Greater(%my_local, %b_out)
%user_defined_vals = Add(%b, %b)
return %keepgoing_out, %b_out, %user_defined_vals
}
*Sample equivalent C code*
{
/* User-defined code (enclosing scope) */
int a = 3, b = 6;
bool keepgoing = true; // Analogous to input cond
/* End user-defined code */
/* Implicitly-defined code */
const int max_trip_count = 10; // Analogous to input M
int user_defined_vals[]; // Imagine this is resizable
/* End implicitly-defined code */
for (int i=0; i < max_trip_count && keepgoing; ++i) {
/* User-defined code (loop body) */
int my_local = a + b; // Reading values in the enclosing scope is fine
b = a - b; // writes fine if we specify b as a loop-carried dependency
keepgoing = my_local > b; // keepgoing is a loop-carried dependency
user_defined_vals[i] = b + b;
/* End user-defined code */
}
// my_local = 123; // Can't do this. my_local was defined in the body
// These below values are live-out from the loop and therefore accessible
b_out; user_defined_vals; keepgoing_out;
}
There are several things of note in this code snippet:
1) Values from the enclosing scope (i.e. variable a here) are in scope and can
be referenced in the inputs of the loop.
2) Any variables which you wish to make available in the enclosing scope (i.e.
the variables b and keepgoing) must be declared as either loop-carried
dependencies (both at the op inputs and output and at the body net input and
output) or scan_outputs.
3) Values created in the body cannot be accessed in the enclosing scope.
Note that the semantics of this op support "diagonal" or "wavefront" execution.
(See Step 3 here for an example:
https://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).
Frontends should emit multi-layer RNNs as a series of While operators (with
time being the inner looping dimension), with each successive layer consuming
the scan_outputs from the previous layer, possibly going through several
point-wise operators (e.g. dropout, residual connections, linear layer).
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Loop,
1,
OpSchema()
.SetDoc(Loop_ver1_doc)
.Input(
0,
"M",
"A maximum trip-count for the loop specified at runtime. Optional."
" Pass empty string to skip.",
"I",
OpSchema::Optional)
.Input(
1,
"cond",
"A boolean termination condition. Optional. Pass empty string to skip.",
"B",
OpSchema::Optional)
.Input(
2,
"v_initial",
"The initial values of any loop-carried dependencies (values that "
"change across loop iterations)",
"V",
OpSchema::Variadic,
false)
.Output(
0,
"v_final_and_scan_outputs",
"Final N loop carried dependency values then K scan_outputs",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has 2+N inputs: (iteration_num, "
"condition, loop carried dependencies...). It has 1+N+K outputs: "
"(condition, loop carried dependencies..., scan_outputs...). Each "
"scan_output is created by concatenating the value of the specified "
"output value at the end of each iteration of the loop. It is an error"
" if the dimensions or data type of these scan_outputs change across loop"
" iterations.",
AttributeProto::GRAPH)
.TypeConstraint("V", OpSchema::all_tensor_types(), "All Tensor types")
.TypeConstraint("I", {"tensor(int64)"}, "tensor of int64, which should be a scalar.")
.TypeConstraint("B", {"tensor(bool)"}, "tensor of bool, which should be a scalar.")
.TypeAndShapeInferenceFunction(LoopInferenceFunctionOpset8));
void LoopInferenceFunctionOpset11(InferenceContext& ctx) {
auto num_inputs = ctx.getNumInputs();
auto num_loop_state_vars = num_inputs - 2; // skip 'M' and 'cond'
std::vector<const TypeProto*> subgraph_input_types;
std::vector<TypeProto> temporary_type_protos;
temporary_type_protos.reserve(num_inputs - 2);
// create TypeProto to validate iteration number type is the same as the
// optional 'M' input for max iterations.
TypeProto iter_num_type;
iter_num_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT64);
subgraph_input_types.push_back(&iter_num_type);
// 'cond'
subgraph_input_types.push_back(ctx.getInputType(1));
// loop state value types get propagated to outputs, but shape may change
// across iterations so don't propagate it to the outputs and don't pass it
// into the subgraph inferencing
for (size_t i = 2; i < num_inputs; ++i) {
propagateElemTypeFromInputToOutput(ctx, i, i - 2);
// copy so we can remove the shape before passing to the subgraph
// inferencing
temporary_type_protos.push_back(*ctx.getInputType(i));
auto& input_type = temporary_type_protos.back();
input_type.mutable_tensor_type()->clear_shape();
subgraph_input_types.push_back(&input_type);
}
// Run inferencing on the subgraph
std::vector<const TypeProto*> subgraph_output_types;
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("body");
if (graphInferencer) {
std::vector<const TensorProto*> input_data;
input_data.push_back(nullptr); // iteration number
for (size_t i = 1; i < num_inputs; ++i) {
input_data.push_back(ctx.getInputData(i));
}
subgraph_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
// if empty(), assume inferencing was skipped
if (!subgraph_output_types.empty()) {
auto num_outputs = ctx.getNumOutputs();
// subgraph outputs the condition value first but that is only used
// internally and not returned by Loop.
if (subgraph_output_types.size() != num_outputs + 1) {
fail_type_inference(
"Graph attribute inferencing returned type information for ",
subgraph_output_types.size(),
" outputs. Expected ",
num_outputs + 1);
}
// check loop state values match. we should already have type/shape info
for (size_t i = 0; i < num_outputs; ++i) {
auto* subgraph_output_type = subgraph_output_types[i + 1]; // skip 'cond'
auto* loop_output_type = ctx.getOutputType(i);
const bool is_loop_state_var = i < num_loop_state_vars;
if (!subgraph_output_type->has_tensor_type()) {
fail_type_inference(
"Loop 'body' subgraph outputs should all be tensors but output ",
i,
" was ",
subgraph_output_type->value_case());
}
// if there's an existing type check it matches. otherwise propagate
propagateElemTypeWithValidation(subgraph_output_type, loop_output_type);
if (is_loop_state_var) {
// shape may change across iterations so ignore.
} else {
// propagate shape
if (subgraph_output_type->tensor_type().has_shape()) {
// per iteration output. first dimension will be number of iterations
// but we don't know that value yet
TypeProto inferred_type(*subgraph_output_type);
auto* mutable_inferred_tensor_type = inferred_type.mutable_tensor_type();
auto* mutable_inferred_shape = mutable_inferred_tensor_type->mutable_shape();
mutable_inferred_shape->clear_dim();
// add empty dimension for number of iterations
mutable_inferred_shape->add_dim();
// add dimensions from subgraph output shape
for (const auto& dim : subgraph_output_type->tensor_type().shape().dim()) {
(*mutable_inferred_shape->add_dim()) = dim;
}
mergeInShapeInfo(*mutable_inferred_tensor_type, *loop_output_type->mutable_tensor_type());
}
}
}
}
}
static const char* Loop_ver11_doc = R"DOC(
Generic Looping construct. This loop has multiple termination conditions:
1) Trip count. Iteration count specified at runtime. Set by
specifying the input M. Optional. Set to empty string to omit.
Note that a static trip count (specified at graph construction time) can be
specified by passing in a constant node for input M.
2) Loop termination condition. This is an input to the op that determines
whether to run the first iteration and also a loop-carried dependency for
the body graph. The body graph must yield a value for the condition variable,
whether this input is provided or not.
This table summarizes the operating modes of this operator with equivalent
C-style code:
Operator inputs defined as (max_trip_count, condition_var).
input ("", ""):
for (int i=0; ; ++i) {
cond = ... // Note this value is ignored, but is required in the body
}
input ("", cond) // Note this is analogous to a while loop
bool cond = ...;
for (int i=0; cond; ++i) {
cond = ...;
}
input ("", 1) // Note this is analogous to a do-while loop
bool cond = true
for (int i=0; cond; ++i) {
cond = ...;
}
input (trip_count, "") // Note this is analogous to a for loop
int trip_count = ...
for (int i=0; i < trip_count; ++i) {
cond = ...; // ignored
}
input (trip_count, cond)
int trip_count = ...;
bool cond = ...;
for (int i=0; i < trip_count && cond; ++i) {
cond = ...;
}
*Sample usage - cond as well as trip count*
graph predict-net {
%a = Constant[value = <Scalar Tensor [3]>]()
%b = Constant[value = <Scalar Tensor [6]>]()
%keepgoing = Constant[value = <Scalar Tensor [1]>]()
%max_trip_count = Constant[value = <Scalar Tensor [10]>]()
%keepgoing_out, %b_out, %user_defined_vals = Loop[body = <graph body-net>](%max_trip_count, %keepgoing, %b)
return
}
graph body-net (
%i[INT32, scalar] // iteration number
%keepgoing_in[BOOL, scalar] // incoming loop-termination-condition; not used
%b_in[INT32, scalar] // incoming value of loop-carried-dependency b
) {
%my_local = Add(%a, %b_in)
%b_out = Sub(%a, %b_in) // outgoing value of loop-carried-dependency b
%keepgoing_out = Greater(%my_local, %b_out) // outgoing loop-termination-condition
%user_defined_val = Add(%b_in, %b_in) // scan-output value to be accumulated
return %keepgoing_out, %b_out, %user_defined_val
}
*Sample equivalent C code*
{
/* User-defined code (enclosing scope) */
int a = 3, b = 6;
bool keepgoing = true; // Analogous to input cond
/* End user-defined code */
/* Implicitly-defined code */
const int max_trip_count = 10; // Analogous to input M
int user_defined_vals[]; // Imagine this is resizable
/* End implicitly-defined code */
/* initialize loop-carried variables and scan-output variables */
bool keepgoing_out = keepgoing
int b_out = b
for (int i=0; i < max_trip_count && keepgoing_out; ++i) {
/* Implicitly-defined code: bind actual parameter values
to formal parameter variables of loop-body */
bool keepgoing_in = keepgoing_out;
bool b_in = b_out;
/* User-defined code (loop body) */
int my_local = a + b_in; // Reading value "a" from the enclosing scope is fine
b_out = a - b_in;
keepgoing_out = my_local > b_out;
user_defined_val = b_in + b_in; // b_in and b_out are different variables
/* End user-defined code */
/* Implicitly defined-code */
user_defined_vals[i] = user_defined_val // accumulate scan-output values
}
// int t = my_local; // Can't do this. my_local is not accessible here.
// The values below are bound to the output variables of the loop and therefore accessible
// b_out; user_defined_vals; keepgoing_out;
}
There are several things of note in this code snippet:
1) Values from the enclosing scope (i.e. variable "a" here) are in scope and can
be referenced in the inputs of the loop.
2) Any values computed in the loop body that needs to be used in a subsequent
iteration or after the loop are modelled using a pair of variables in the loop-body,
consisting of an input variable (eg., b_in) and an output variable (eg., b_out).
These are referred to as loop-carried dependences. The loop operation node
supplies the input value of the input variable for the first iteration, and
returns the output value of the output variable produced by the final
iteration.
3) Scan_output variables are used to implicitly concatenate values computed across
all the iterations. In the above example, the value of user_defined_val computed
over all iterations are concatenated and returned as the value of user_defined_vals
after the loop.
4) Values created in the body cannot be accessed in the enclosing scope,
except using the mechanism described above.
Note that the semantics of this op support "diagonal" or "wavefront" execution.
(See Step 3 here for an example:
https://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).
Frontends should emit multi-layer RNNs as a series of While operators (with
time being the inner looping dimension), with each successive layer consuming
the scan_outputs from the previous layer, possibly going through several
point-wise operators (e.g. dropout, residual connections, linear layer).
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Loop,
11,
OpSchema()
.SetDoc(Loop_ver11_doc)
.Input(
0,
"M",
"A maximum trip-count for the loop specified at runtime. Optional."
" Pass empty string to skip.",
"I",
OpSchema::Optional)
.Input(
1,
"cond",
"A boolean termination condition. Optional. Pass empty string to skip.",
"B",
OpSchema::Optional)
.Input(
2,
"v_initial",
"The initial values of any loop-carried dependencies (values that "
"change across loop iterations)",
"V",
OpSchema::Variadic,
false,
0)
.Output(
0,
"v_final_and_scan_outputs",
"Final N loop carried dependency values then K scan_outputs",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has 2+N inputs: (iteration_num, "
"condition, loop carried dependencies...). It has 1+N+K outputs: "
"(condition, loop carried dependencies..., scan_outputs...). Each "
"scan_output is created by concatenating the value of the specified "
"output value at the end of each iteration of the loop. It is an error"
" if the dimensions or data type of these scan_outputs change across loop"
" iterations.",
AttributeProto::GRAPH)
.TypeConstraint("V", OpSchema::all_tensor_types(), "All Tensor types")
.TypeConstraint("I", {"tensor(int64)"}, "tensor of int64, which should be a scalar.")
.TypeConstraint("B", {"tensor(bool)"}, "tensor of bool, which should be a scalar.")
.TypeAndShapeInferenceFunction(LoopInferenceFunctionOpset11));
static const char* scan_9_doc = R"DOC(
Scan can be used to iterate over one or more scan_input tensors,
constructing zero or more scan_output tensors. It combines ideas from general recurrences,
functional programming constructs such as scan, fold, map, and zip, and is intended to enable
generalizations of RNN-like constructs for sequence-to-sequence processing.
Other tensors (referred to as state_variables here) can be used to carry a state
when iterating from one element to another (similar to hidden-state in RNNs, also referred
to as loop-carried dependences in the context of loops).
Many common usages involve a single scan_input tensor (where functionality
similar to scan, fold and map can be obtained). When more than one scan_input is used,
a behavior similar to zip is obtained.
The attribute body must be a graph, specifying the computation to be performed in
every iteration. It takes as input the current values of the state_variables and
the current iterated element of the scan_inputs. It must return the (updated) values
of the state_variables and zero or more scan_output_element tensors. The values of the
scan_output_element tensors are concatenated over all the iterations to produce the
scan_output values of the scan construct (similar to the concatenated intermediate
hidden-state values of RNN-like constructs). All the output tensors (state_variables as
well as scan_output_element tensors) are required to have the same shape in each iteration
of the loop (a restriction imposed to enable efficient memory allocation).
Note that the iterated element passed to the body subgraph does not have a sequence
axis. It will have a rank one less than the rank of the corresponding scan_input.
The scan operation returns the final values of the state_variables as well as the
scan_outputs.
The optional attribute scan_input_directions specifies the direction (forward or backward)
for each scan input. If this attribute is omitted, all sequences are scanned in the forward
direction. A bidirectional scan may be performed by specifying the same tensor input twice
in the scan_inputs, once with a forward direction, and once with a backward direction.
The scan_output of the operation is produced by concatenating the scan_output_element
values produced by the body in each iteration. The optional attribute scan_output_directions
specifies the direction in which scan_output is constructed (by appending or prepending the
scan_output_element to scan_output in each iteration) for each scan_output. If this attribute
is omitted, the scan_output_element is appended to the scan_output in each iteration.
The optional attribute scan_input_axes specifies the axis to be scanned for each scan_input.
If omitted, every scan_input will be scanned in axis 0. For example, if axis 0 is the
batch axis and axis 1 is the time axis (to be scanned), specify an axis value of 1.
Note that scanning a non-zero axis may be less efficient than scanning axis zero.
The optional attribute scan_output_axes specifies the axis along which the scan_outputs
are accumulated for each scan_output. For example, if axis 1 is the time axis (to be
scanned) for both inputs and outputs, specify a scan_input axis and scan_output axis
value of 1.
Note that because of the ONNX restriction that only the last parameter of an operator can
be variadic, the initial-states and scan-inputs are listed together as one input parameter.
Similarly, the final-states and scan-outputs are listed together as one output parameter.
The attribute num_scan_inputs indicates the number M of scan-inputs.
The behavior of
Scan <
num_scan_inputs = m,
body = loop-body,
scan_input_axes = [axis_1, ..., axis_m]
> (init_1, ..., init_n, scan_1, ..., scan_m)
is equivalent to the following pseudo-code:
// scan_i.shape[axis_i] denotes the (max) sequence-length of scan_i
// scan_i.shape[axis_i] is required to be equal to scan_j.shape[axis_j] for all i,j.
sequence_length = scan_1.shape[axis_1];
// initialize state-variables
st_1 = init_1; ... st_n = init_n;
// initialize scan-output variables: [] denotes an empty tensor
scan_out_1 = []; ...; scan_out_k = [];
// identify number of iterations:
// execute loop
for (int t = 0; t < sequence_length; ++t) {
// generate the scan-input elements: the notation T<axis=k>[t] indicates the sub-tensor
// of rank one less than T obtained by indexing T at position t along axis k.
si_1 = scan_1<axis=axis_1>[t];
... ;
si_m = scan_m<axis=axis_m>[t];
// execute loop-body
st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)
// accumulate the scan-output elements
scan_out_1 = Concat<axis=0>(scan_out_1, so_1); ... ; scan_out_k = Concat<axis=0>(scan_out_k, so_k);
}
return st_1, ..., st_n, scan_out_1, ..., scan_out_k;
*Sample usage: Encoding RNN using a Scan*
The following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,
recurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can
be encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes
%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these
values are computed in the outer graph, they need to be passed in as extra state_variables.
graph rnn-encoding {
%H_0 = ...
%X = ...
%Y_h, %Y = Scan[body = <graph rnn-cell-1>, num_scan_inputs=1](%H_0, %X)
return %Y, %Y_h
}
graph rnn-cell-1 (
%H_tminus1[FLOAT, tensor]
%X_t[FLOAT, tensor]
) {
%Wi = ...
%Ri = ...
%Wbi = ...
%Rbi = ...
%t1 = X_t * (Wi^T)
%t2 = H_tminus1*(Ri^T)
%t3 = Add(%t1, %t2)
%t4 = Add(%t3, %Wbi)
%t5 = Add(%t4, %Rbi)
%Ht = Tanh(%t5)
%Accumulate = Identity(%Ht)
return %Ht, %Accumulate
}
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Scan,
9,
OpSchema()
.SetDoc(scan_9_doc)
.Input(
0,
"initial_state_and_scan_inputs",
"Initial values of the loop's N state variables followed by M scan_inputs",
"V",
OpSchema::Variadic,
false)
.Output(
0,
"final_state_and_scan_outputs",
"Final values of the loop's N state variables followed by K scan_outputs",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has N+M inputs: "
"(loop state variables..., scan_input_elts...). It has N+K outputs: "
"(loop state variables..., scan_output_elts...). Each "
"scan_output is created by concatenating the value of the specified "
"scan_output_elt value at the end of each iteration of the loop. It is an error"
" if the dimensions of these values change across loop iterations.",
AttributeProto::GRAPH,
true)
.Attr("num_scan_inputs", "An attribute specifying the number of scan_inputs M. ", AttributeProto::INT, true)
.Attr(
"scan_input_directions",
"An optional list of M flags. The i-th element of the list specifies the direction "
"to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 "
"indicates reverse direction. "
"If omitted, all scan_input tensors will be scanned in the forward direction.",
AttributeProto::INTS,
false)
.Attr(
"scan_output_directions",
"An optional list of K flags, one for each scan_output. The i-th element of the list "
"specifies whether the i-th scan_output should be constructed by appending or "
"prepending a new value in each iteration: 0 indicates appending and 1 "
"indicates prepending. "
"If omitted, all scan_output tensors will be produced by appending a value "
"in each iteration.",
AttributeProto::INTS,
false)
.Attr(
"scan_input_axes",
"An optional list of M flags. The i-th element of the list specifies the axis "
"to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will "
"be used as the scan axis for every scan_input.",
AttributeProto::INTS,
false)
.Attr(
"scan_output_axes",
"An optional list of K flags. The i-th element of the list specifies the axis "
"for the i-th scan_output. The scan outputs are accumulated along the specified "
"axis. If omitted, 0 will be used as the scan axis for every scan_output.",
AttributeProto::INTS,
false)
.TypeConstraint("V", OpSchema::all_tensor_types(), "All Tensor types")
.TypeAndShapeInferenceFunction(ScanInferenceFunctionOpset9));
void IfInferenceFunction1(InferenceContext& ctx) {
// there are no inputs so we just need to run the subgraph inferencing for
// then/else subgraphs and apply those to the outputs.
std::vector<const TypeProto*> subgraph_input_types; // none
std::vector<const TensorProto*> input_data; // none
std::vector<const TypeProto*> then_output_types;
std::vector<const TypeProto*> else_output_types;
// Run inferencing on the subgraph
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("then_branch");
if (graphInferencer) {
then_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
graphInferencer = ctx.getGraphAttributeInferencer("else_branch");
if (graphInferencer) {
else_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
auto num_outputs = ctx.getNumOutputs();
auto num_then_outputs = then_output_types.size();
auto num_else_outputs = else_output_types.size();
// the output types for then and else should be the same
if (num_then_outputs != num_else_outputs) {
fail_type_inference(
"then_branch and else_branch produce different number of outputs. ",
num_then_outputs,
" != ",
num_else_outputs);
}
if (num_then_outputs != num_outputs) {
fail_type_inference("If node has ", num_outputs, " but subgraphs produce ", num_then_outputs);
}
for (size_t i = 0, end = then_output_types.size(); i < end; ++i) {
auto then_output = then_output_types[i];
auto else_output = else_output_types[i];
if (then_output->value_case() != else_output->value_case()) {
fail_type_inference(
"Mismatched type for output ", i, " then=", then_output->value_case(), " else=", else_output->value_case());
}
auto* if_output = ctx.getOutputType(i);
*if_output = *then_output;
if (then_output->has_tensor_type()) {
auto then_elem_type = then_output->tensor_type().elem_type();
auto else_elem_type = else_output->tensor_type().elem_type();
if (then_elem_type != else_elem_type) {
fail_type_inference(
"Mismatched tensor element type for output ", i, " then=", then_elem_type, " else=", else_elem_type);
}
// merge the 'else' shape information to check it's consistent and
// augment the 'if' output if possible
mergeInShapeInfo(else_output->tensor_type(), *if_output->mutable_tensor_type());
}
}
}
ONNX_OPERATOR_SET_SCHEMA(
If,
1,
OpSchema()
.SetDoc("If conditional")
.Input(0, "cond", "Condition for the if. The tensor must contain a single element.", "B")
.Output(
0,
"outputs",
"Values that are live-out to the enclosing scope. The return values in "
"the `then_branch` and `else_branch` must be of the same shape and same "
"data type.",
"V",
OpSchema::Variadic,
false)
.Attr(
"then_branch",
"Graph to run if condition is true. Has N outputs: values you wish to "
"be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the else_branch.",
AttributeProto::GRAPH)
.Attr(
"else_branch",
"Graph to run if condition is false. Has N outputs: values you wish to"
" be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the then_branch.",
AttributeProto::GRAPH)
.TypeConstraint("V", OpSchema::all_tensor_types(), "All Tensor types")
.TypeConstraint("B", {"tensor(bool)"}, "Only bool")
.TypeAndShapeInferenceFunction(IfInferenceFunction1));
void IfInferenceFunction_11(InferenceContext& ctx) {
// there are no inputs so we just need to run the subgraph inferencing for
// then/else subgraphs and apply those to the outputs.
std::vector<const TypeProto*> subgraph_input_types; // none
std::vector<const TensorProto*> input_data; // none
std::vector<const TypeProto*> then_output_types;
std::vector<const TypeProto*> else_output_types;
// Run inferencing on the subgraph
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("then_branch");
if (graphInferencer) {
then_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
graphInferencer = ctx.getGraphAttributeInferencer("else_branch");
if (graphInferencer) {
else_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
auto num_outputs = ctx.getNumOutputs();
auto num_then_outputs = then_output_types.size();
auto num_else_outputs = else_output_types.size();
// the output types for then and else should be the same
if (num_then_outputs != num_else_outputs) {
fail_type_inference(
"then_branch and else_branch produce different number of outputs. ",
num_then_outputs,
" != ",
num_else_outputs);
}
if (num_then_outputs != num_outputs) {
fail_type_inference("If node has ", num_outputs, " but subgraphs produce ", num_then_outputs);
}
for (size_t i = 0, end = then_output_types.size(); i < end; ++i) {
auto then_output = then_output_types[i];
auto else_output = else_output_types[i];
if (then_output->value_case() != else_output->value_case()) {
fail_type_inference(
"Mismatched type for output ", i, " then=", then_output->value_case(), " else=", else_output->value_case());
}
auto* if_output = ctx.getOutputType(i);
*if_output = *then_output;
if (then_output->has_tensor_type()) {
auto then_elem_type = then_output->tensor_type().elem_type();
auto else_elem_type = else_output->tensor_type().elem_type();
if (then_elem_type != else_elem_type) {
fail_type_inference(
"Mismatched tensor element type for output ", i, " then=", then_elem_type, " else=", else_elem_type);
}
UnionShapeInfo(else_output->tensor_type().shape(), *if_output->mutable_tensor_type());
}
}
}
ONNX_OPERATOR_SET_SCHEMA(
If,
11,
OpSchema()
.SetDoc("If conditional")
.Input(0, "cond", "Condition for the if. The tensor must contain a single element.", "B")
.Output(
0,
"outputs",
"Values that are live-out to the enclosing scope. The return values in "
"the `then_branch` and `else_branch` must be of the same data type. "
"The `then_branch` and `else_branch` may produce tensors with the same "
"element type and different shapes. "
"If corresponding outputs from the then-branch and the else-branch have "
"static shapes S1 and S2, then the shape of the corresponding output "
"variable of the if-node (if present) must be compatible with both S1 "
"and S2 as it represents the union of both possible shapes."
"For example, if in a model file, the first "
"output of `then_branch` is typed float tensor with shape [2] and the "
"first output of `else_branch` is another float tensor with shape [3], "
"If's first output should have (a) no shape set, or (b) "
"a shape of rank 1 with neither `dim_value` nor `dim_param` set, or (c) "
"a shape of rank 1 with a unique `dim_param`. "
"In contrast, the first output cannot have the shape [2] since [2] and "
"[3] are not compatible.",
"V",
OpSchema::Variadic,
false)
.Attr(
"then_branch",
"Graph to run if condition is true. Has N outputs: values you wish to "
"be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the else_branch.",
AttributeProto::GRAPH)
.Attr(
"else_branch",
"Graph to run if condition is false. Has N outputs: values you wish to"
" be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the then_branch.",
AttributeProto::GRAPH)
.TypeConstraint("V", OpSchema::all_tensor_types(), "All Tensor types")
.TypeConstraint("B", {"tensor(bool)"}, "Only bool")
.TypeAndShapeInferenceFunction(IfInferenceFunction_11));
void IfInferenceFunction_13(InferenceContext& ctx) {
// there are no inputs so we just need to run the subgraph inferencing for
// then/else subgraphs and apply those to the outputs.
std::vector<const TypeProto*> subgraph_input_types; // none
std::vector<const TensorProto*> input_data; // none
std::vector<const TypeProto*> then_output_types;
std::vector<const TypeProto*> else_output_types;
// Run inferencing on the subgraph
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("then_branch");
if (graphInferencer) {
then_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
graphInferencer = ctx.getGraphAttributeInferencer("else_branch");
if (graphInferencer) {
else_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
auto num_outputs = ctx.getNumOutputs();
auto num_then_outputs = then_output_types.size();
auto num_else_outputs = else_output_types.size();
// the output types for then and else should be the same
if (num_then_outputs != num_else_outputs) {
fail_type_inference(
"then_branch and else_branch produce different number of outputs. ",
num_then_outputs,
" != ",
num_else_outputs);
}
if (num_then_outputs != num_outputs) {
fail_type_inference("If node has ", num_outputs, " but subgraphs produce ", num_then_outputs);
}
for (size_t i = 0, end = then_output_types.size(); i < end; ++i) {
auto then_output = then_output_types[i];
auto else_output = else_output_types[i];
auto* if_output = ctx.getOutputType(i);
*if_output = *then_output;
UnionTypeInfo(*else_output, *if_output);
}
}
ONNX_OPERATOR_SET_SCHEMA(
If,
13,
OpSchema()
.SetDoc("If conditional")
.Input(0, "cond", "Condition for the if. The tensor must contain a single element.", "B")
.Output(
0,
"outputs",
"Values that are live-out to the enclosing scope. The return values in "
"the `then_branch` and `else_branch` must be of the same data type. "
"The `then_branch` and `else_branch` may produce tensors with the same "
"element type and different shapes. "
"If corresponding outputs from the then-branch and the else-branch have "
"static shapes S1 and S2, then the shape of the corresponding output "
"variable of the if-node (if present) must be compatible with both S1 "
"and S2 as it represents the union of both possible shapes."
"For example, if in a model file, the first "
"output of `then_branch` is typed float tensor with shape [2] and the "
"first output of `else_branch` is another float tensor with shape [3], "
"If's first output should have (a) no shape set, or (b) "
"a shape of rank 1 with neither `dim_value` nor `dim_param` set, or (c) "
"a shape of rank 1 with a unique `dim_param`. "
"In contrast, the first output cannot have the shape [2] since [2] and "
"[3] are not compatible.",
"V",
OpSchema::Variadic,
false)
.Attr(
"then_branch",
"Graph to run if condition is true. Has N outputs: values you wish to "
"be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the else_branch.",
AttributeProto::GRAPH)
.Attr(
"else_branch",
"Graph to run if condition is false. Has N outputs: values you wish to"
" be live-out to the enclosing scope. The number of outputs must match"
" the number of outputs in the then_branch.",
AttributeProto::GRAPH)
.TypeConstraint(
"V",
[]() {
auto t = OpSchema::all_tensor_types();
auto s = OpSchema::all_tensor_sequence_types();
t.insert(t.end(), s.begin(), s.end());
return t;
}(),
"All Tensor and Sequence types")
.TypeConstraint("B", {"tensor(bool)"}, "Only bool")
.TypeAndShapeInferenceFunction(IfInferenceFunction_13));
void LoopInferenceFunction_13(InferenceContext& ctx) {
auto num_inputs = ctx.getNumInputs();
assert(num_inputs >= 2);
auto num_loop_state_vars = num_inputs - 2; // skip 'M' and 'cond'
std::vector<const TypeProto*> subgraph_input_types;
subgraph_input_types.reserve(num_inputs);
std::vector<TypeProto> temporary_type_protos;
temporary_type_protos.reserve(num_inputs - 2);
// create TypeProto to validate iteration number type is the same as the
// optional 'M' input for max iterations.
TypeProto iter_num_type;
iter_num_type.mutable_tensor_type()->set_elem_type(TensorProto_DataType_INT64);
subgraph_input_types.push_back(&iter_num_type);
// 'cond'
subgraph_input_types.push_back(ctx.getInputType(1));
// loop state value types get propagated to outputs, but shape may change
// across iterations so don't propagate it to the outputs and don't pass it
// into the subgraph inferencing
for (size_t i = 2; i < num_inputs; ++i) {
propagateElemTypeFromInputToOutput(ctx, i, i - 2);
// copy so we can remove the shape before passing to the subgraph
// inferencing
temporary_type_protos.push_back(*ctx.getInputType(i));
auto& input_type = temporary_type_protos.back();
if (input_type.has_tensor_type()) {
input_type.mutable_tensor_type()->clear_shape();
} else if (input_type.has_sequence_type()) {
auto& seq_type = *input_type.mutable_sequence_type();
if (seq_type.has_elem_type() && seq_type.elem_type().has_tensor_type()) {
seq_type.mutable_elem_type()->mutable_tensor_type()->clear_shape();
}
}
subgraph_input_types.push_back(&input_type);
}
// Run inferencing on the subgraph
std::vector<const TypeProto*> subgraph_output_types;
GraphInferencer* graphInferencer = ctx.getGraphAttributeInferencer("body");
if (graphInferencer) {
std::vector<const TensorProto*> input_data;
input_data.push_back(nullptr); // iteration number
for (size_t i = 1; i < num_inputs; ++i) {
input_data.push_back(ctx.getInputData(i));
}
subgraph_output_types = graphInferencer->doInferencing(subgraph_input_types, input_data);
}
// if empty(), assume inferencing was skipped
if (!subgraph_output_types.empty()) {
auto num_outputs = ctx.getNumOutputs();
// subgraph outputs the condition value first but that is only used
// internally and not returned by Loop.
if (subgraph_output_types.size() != num_outputs + 1) {
fail_type_inference(
"Graph attribute inferencing returned type information for ",
subgraph_output_types.size(),
" outputs. Expected ",
num_outputs + 1);
}
// check loop state values match. we should already have type/shape info
for (size_t i = 0; i < num_outputs; ++i) {
auto* subgraph_output_type = subgraph_output_types[i + 1]; // skip 'cond'
auto* loop_output_type = ctx.getOutputType(i);
const bool is_loop_state_var = i < num_loop_state_vars;
if (!subgraph_output_type->has_tensor_type() && !subgraph_output_type->has_sequence_type()) {
fail_type_inference(
"Loop 'body' subgraph outputs should all be tensors or sequences but output ",
i,
" was ",
subgraph_output_type->value_case());
}
if (!is_loop_state_var && !subgraph_output_type->has_tensor_type()) {
fail_type_inference(
"Loop 'body' subgraph scan outputs should all be tensors but output ",
i,
" was ",
subgraph_output_type->value_case());
}
// if there's an existing type check it matches. otherwise propagate
propagateElemTypeWithValidation(subgraph_output_type, loop_output_type);
if (is_loop_state_var) {
// shape may change across iterations so ignore.
} else {
// propagate shape
if (subgraph_output_type->tensor_type().has_shape()) {
// per iteration output. first dimension will be number of iterations
// but we don't know that value yet
TypeProto inferred_type(*subgraph_output_type);
auto* mutable_inferred_tensor_type = inferred_type.mutable_tensor_type();
auto* mutable_inferred_shape = mutable_inferred_tensor_type->mutable_shape();
mutable_inferred_shape->clear_dim();
// add empty dimension for number of iterations
mutable_inferred_shape->add_dim();
// add dimensions from subgraph output shape
for (const auto& dim : subgraph_output_type->tensor_type().shape().dim()) {
(*mutable_inferred_shape->add_dim()) = dim;
}
mergeInShapeInfo(*mutable_inferred_tensor_type, *loop_output_type->mutable_tensor_type());
}
}
}
}
}
static const char* Loop_ver13_doc = R"DOC(
Generic Looping construct. This loop has multiple termination conditions:
1) Trip count. Iteration count specified at runtime. Set by
specifying the input M. Optional. Set to empty string to omit.
Note that a static trip count (specified at graph construction time) can be
specified by passing in a constant node for input M.
2) Loop termination condition. This is an input to the op that determines
whether to run the first iteration and also a loop-carried dependency for
the body graph. The body graph must yield a value for the condition variable,
whether this input is provided or not.
This table summarizes the operating modes of this operator with equivalent
C-style code:
Operator inputs defined as (max_trip_count, condition_var).
input ("", ""):
for (int i=0; ; ++i) {
cond = ... // Note this value is ignored, but is required in the body
}
input ("", cond) // Note this is analogous to a while loop
bool cond = ...;
for (int i=0; cond; ++i) {
cond = ...;
}
input ("", 1) // Note this is analogous to a do-while loop
bool cond = true
for (int i=0; cond; ++i) {
cond = ...;
}
input (trip_count, "") // Note this is analogous to a for loop
int trip_count = ...
for (int i=0; i < trip_count; ++i) {
cond = ...; // ignored
}
input (trip_count, cond)
int trip_count = ...;
bool cond = ...;
for (int i=0; i < trip_count && cond; ++i) {
cond = ...;
}
*Sample usage - cond as well as trip count*
graph predict-net {
%a = Constant[value = <Scalar Tensor [3]>]()
%b = Constant[value = <Scalar Tensor [6]>]()
%keepgoing = Constant[value = <Scalar Tensor [1]>]()
%max_trip_count = Constant[value = <Scalar Tensor [10]>]()
%keepgoing_out, %b_out, %user_defined_vals = Loop[body = <graph body-net>](%max_trip_count, %keepgoing, %b)
return
}
graph body-net (
%i[INT32, scalar] // iteration number
%keepgoing_in[BOOL, scalar] // incoming loop-termination-condition; not used
%b_in[INT32, scalar] // incoming value of loop-carried-dependency b
) {
%my_local = Add(%a, %b_in)
%b_out = Sub(%a, %b_in) // outgoing value of loop-carried-dependency b
%keepgoing_out = Greater(%my_local, %b_out) // outgoing loop-termination-condition
%user_defined_val = Add(%b_in, %b_in) // scan-output value to be accumulated
return %keepgoing_out, %b_out, %user_defined_val
}
*Sample equivalent C code*
{
/* User-defined code (enclosing scope) */
int a = 3, b = 6;
bool keepgoing = true; // Analogous to input cond
/* End user-defined code */
/* Implicitly-defined code */
const int max_trip_count = 10; // Analogous to input M
int user_defined_vals[]; // Imagine this is resizable
/* End implicitly-defined code */
/* initialize loop-carried variables and scan-output variables */
bool keepgoing_out = keepgoing
int b_out = b
for (int i=0; i < max_trip_count && keepgoing_out; ++i) {
/* Implicitly-defined code: bind actual parameter values
to formal parameter variables of loop-body */
bool keepgoing_in = keepgoing_out;
bool b_in = b_out;
/* User-defined code (loop body) */
int my_local = a + b_in; // Reading value "a" from the enclosing scope is fine
b_out = a - b_in;
keepgoing_out = my_local > b_out;
user_defined_val = b_in + b_in; // b_in and b_out are different variables
/* End user-defined code */
/* Implicitly defined-code */
user_defined_vals[i] = user_defined_val // accumulate scan-output values
}
// int t = my_local; // Can't do this. my_local is not accessible here.
// The values below are bound to the output variables of the loop and therefore accessible
// b_out; user_defined_vals; keepgoing_out;
}
There are several things of note in this code snippet:
1) Values from the enclosing scope (i.e. variable "a" here) are in scope and can
be referenced in the inputs of the loop.
2) Any values computed in the loop body that needs to be used in a subsequent
iteration or after the loop are modelled using a pair of variables in the loop-body,
consisting of an input variable (eg., b_in) and an output variable (eg., b_out).
These are referred to as loop-carried dependences. The loop operation node
supplies the input value of the input variable for the first iteration, and
returns the output value of the output variable produced by the final
iteration.
3) Scan_output variables are used to implicitly concatenate values computed across
all the iterations. In the above example, the value of user_defined_val computed
over all iterations are concatenated and returned as the value of user_defined_vals
after the loop.
4) Values created in the body cannot be accessed in the enclosing scope,
except using the mechanism described above.
Note that the semantics of this op support "diagonal" or "wavefront" execution.
(See Step 3 here for an example:
https://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/).
Frontends should emit multi-layer RNNs as a series of While operators (with
time being the inner looping dimension), with each successive layer consuming
the scan_outputs from the previous layer, possibly going through several
point-wise operators (e.g. dropout, residual connections, linear layer).
The input/output of subgraph (produced by loop node) matching is based on order instead of name. The implementation will figure out the names based on this order.
)DOC";
ONNX_OPERATOR_SET_SCHEMA(
Loop,
13,
OpSchema()
.SetDoc(Loop_ver13_doc)
.Input(
0,
"M",
"A maximum trip-count for the loop specified at runtime. Optional."
" Pass empty string to skip.",
"I",
OpSchema::Optional)
.Input(
1,
"cond",
"A boolean termination condition. Optional. Pass empty string to skip.",
"B",
OpSchema::Optional)
.Input(
2,
"v_initial",
"The initial values of any loop-carried dependencies (values that "
"change across loop iterations)",
"V",
OpSchema::Variadic,
false,
0)
.Output(
0,
"v_final_and_scan_outputs",
"Final N loop carried dependency values then K scan_outputs. "
"Scan outputs must be Tensors.",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has 2+N inputs: (iteration_num, "
"condition, loop carried dependencies...). It has 1+N+K outputs: "
"(condition, loop carried dependencies..., scan_outputs...). Each "
"scan_output is created by concatenating the value of the specified "
"output value at the end of each iteration of the loop. It is an error"
" if the dimensions or data type of these scan_outputs change across loop"
" iterations.",
AttributeProto::GRAPH)
.TypeConstraint(
"V",
[]() {
auto t = OpSchema::all_tensor_types();
auto s = OpSchema::all_tensor_sequence_types();
t.insert(t.end(), s.begin(), s.end());
return t;
}(),
"All Tensor and Sequence types")
.TypeConstraint("I", {"tensor(int64)"}, "tensor of int64, which should be a scalar.")
.TypeConstraint("B", {"tensor(bool)"}, "tensor of bool, which should be a scalar.")
.TypeAndShapeInferenceFunction(LoopInferenceFunction_13));
static const char* scan_11_doc = R"DOC(
Scan can be used to iterate over one or more scan_input tensors,
constructing zero or more scan_output tensors. It combines ideas from general recurrences,
functional programming constructs such as scan, fold, map, and zip, and is intended to enable
generalizations of RNN-like constructs for sequence-to-sequence processing.
Other tensors (referred to as state_variables here) can be used to carry a state
when iterating from one element to another (similar to hidden-state in RNNs, also referred
to as loop-carried dependences in the context of loops).
Many common usages involve a single scan_input tensor (where functionality
similar to scan, fold and map can be obtained). When more than one scan_input is used,
a behavior similar to zip is obtained.
The attribute body must be a graph, specifying the computation to be performed in
every iteration. It takes as input the current values of the state_variables and
the current iterated element of the scan_inputs. It must return the (updated) values
of the state_variables and zero or more scan_output_element tensors. The values of the
scan_output_element tensors are concatenated over all the iterations to produce the
scan_output values of the scan construct (similar to the concatenated intermediate
hidden-state values of RNN-like constructs). All the output tensors (state_variables as
well as scan_output_element tensors) are required to have the same shape in each iteration
of the loop (a restriction imposed to enable efficient memory allocation).
Note that the iterated element passed to the body subgraph does not have a sequence
axis. It will have a rank one less than the rank of the corresponding scan_input.
The scan operation returns the final values of the state_variables as well as the
scan_outputs.
The optional attribute scan_input_directions specifies the direction (forward or backward)
for each scan input. If this attribute is omitted, all sequences are scanned in the forward
direction. A bidirectional scan may be performed by specifying the same tensor input twice
in the scan_inputs, once with a forward direction, and once with a backward direction.
The scan_output of the operation is produced by concatenating the scan_output_element
values produced by the body in each iteration. The optional attribute scan_output_directions
specifies the direction in which scan_output is constructed (by appending or prepending the
scan_output_element to scan_output in each iteration) for each scan_output. If this attribute
is omitted, the scan_output_element is appended to the scan_output in each iteration.
The optional attribute scan_input_axes specifies the axis to be scanned for each scan_input.
If omitted, every scan_input will be scanned in axis 0. For example, if axis 0 is the
batch axis and axis 1 is the time axis (to be scanned), specify an axis value of 1.
Note that scanning a non-zero axis may be less efficient than scanning axis zero.
The optional attribute scan_output_axes specifies the axis along which the scan_outputs
are accumulated for each scan_output. For example, if axis 1 is the time axis (to be
scanned) for both inputs and outputs, specify a scan_input axis and scan_output axis
value of 1.
Note that because of the ONNX restriction that only the last parameter of an operator can
be variadic, the initial-states and scan-inputs are listed together as one input parameter.
Similarly, the final-states and scan-outputs are listed together as one output parameter.
The attribute num_scan_inputs indicates the number M of scan-inputs.
The behavior of
Scan <
num_scan_inputs = m,
body = loop-body,
scan_input_axes = [axis_1, ..., axis_m]
> (init_1, ..., init_n, scan_1, ..., scan_m)
is equivalent to the following pseudo-code:
// scan_i.shape[axis_i] denotes the (max) sequence-length of scan_i
// scan_i.shape[axis_i] is required to be equal to scan_j.shape[axis_j] for all i,j.
sequence_length = scan_1.shape[axis_1];
// initialize state-variables
st_1 = init_1; ... st_n = init_n;
// initialize scan-output variables: [] denotes an empty tensor
scan_out_1 = []; ...; scan_out_k = [];
// identify number of iterations:
// execute loop
for (int t = 0; t < sequence_length; ++t) {
// generate the scan-input elements: the notation T<axis=k>[t] indicates the sub-tensor
// of rank one less than T obtained by indexing T at position t along axis k.
si_1 = scan_1<axis=axis_1>[t];
... ;
si_m = scan_m<axis=axis_m>[t];
// execute loop-body
st_1, ..., st_n, so_1, ..., so_k = loop-body(st_1, ..., st_n, si_1, ..., si_m)
// accumulate the scan-output elements
scan_out_1 = Concat<axis=0>(scan_out_1, so_1); ... ; scan_out_k = Concat<axis=0>(scan_out_k, so_k);
}
return st_1, ..., st_n, scan_out_1, ..., scan_out_k;
*Sample usage: Encoding RNN using a Scan*
The following example shows how a simple RNN over an input tensor %X, with weight tensor %Wi,
recurrence weight tensor %Ri, bias tensors %Wbi and %Rbi, and initial hidden-state %H_0 can
be encoded as a ScanLoop. Note that the loop-body is a nested graph, and it directly computes
%Wi, %Ri, %Wbi, and %Rbi (typically constants or initializers in the body graph). If these
values are computed in the outer graph, they need to be passed in as extra state_variables.
graph rnn-encoding {
%H_0 = ...
%X = ...
%Y_h, %Y = Scan[body = <graph rnn-cell-1>, num_scan_inputs=1](%H_0, %X)
return %Y, %Y_h
}
graph rnn-cell-1 (
%H_tminus1[FLOAT, tensor]
%X_t[FLOAT, tensor]
) {
%Wi = ...
%Ri = ...
%Wbi = ...
%Rbi = ...
%t1 = X_t * (Wi^T)
%t2 = H_tminus1*(Ri^T)
%t3 = Add(%t1, %t2)
%t4 = Add(%t3, %Wbi)
%t5 = Add(%t4, %Rbi)
%Ht = Tanh(%t5)
%Accumulate = Identity(%Ht)
return %Ht, %Accumulate
}
)DOC";
extern void ScanInferenceFunction(InferenceContext& ctx);
ONNX_OPERATOR_SET_SCHEMA(
Scan,
11,
OpSchema()
.SetDoc(scan_11_doc)
.Input(
0,
"initial_state_and_scan_inputs",
"Initial values of the loop's N state variables followed by M scan_inputs",
"V",
OpSchema::Variadic,
false)
.Output(
0,
"final_state_and_scan_outputs",
"Final values of the loop's N state variables followed by K scan_outputs",
"V",
OpSchema::Variadic,
false)
.Attr(
"body",
"The graph run each iteration. It has N+M inputs: "
"(loop state variables..., scan_input_elts...). It has N+K outputs: "
"(loop state variables..., scan_output_elts...). Each "
"scan_output is created by concatenating the value of the specified "
"scan_output_elt value at the end of each iteration of the loop. It is an error"
" if the dimensions of these values change across loop iterations.",
AttributeProto::GRAPH,
true)
.Attr("num_scan_inputs", "An attribute specifying the number of scan_inputs M. ", AttributeProto::INT, true)
.Attr(
"scan_input_directions",
"An optional list of M flags. The i-th element of the list specifies the direction "
"to be scanned for the i-th scan_input tensor: 0 indicates forward direction and 1 "
"indicates reverse direction. "
"If omitted, all scan_input tensors will be scanned in the forward direction.",
AttributeProto::INTS,
false)
.Attr(
"scan_output_directions",
"An optional list of K flags, one for each scan_output. The i-th element of the list "
"specifies whether the i-th scan_output should be constructed by appending or "
"prepending a new value in each iteration: 0 indicates appending and 1 "
"indicates prepending. "
"If omitted, all scan_output tensors will be produced by appending a value "
"in each iteration.",
AttributeProto::INTS,
false)
.Attr(
"scan_input_axes",
"An optional list of M flags. The i-th element of the list specifies the axis "
"to be scanned (the sequence axis) for the i-th scan_input. If omitted, 0 will "
"be used as the scan axis for every scan_input. Negative value for an axis means "
"counting dimensions from the back. Accepted range is [-r, r-1] where r = rank(input).",
AttributeProto::INTS,
false)
.Attr(
"scan_output_axes",
"An optional list of K flags. The i-th element of the list specifies the axis "
"for the i-th scan_output. The scan outputs are accumulated along the specified "
"axis. If omitted, 0 will be used as the scan axis for every scan_output. "
"Negative value for an axis means counting dimensions from the back. Accepted "
"range is [-r, r-1].",
AttributeProto::INTS,
false)
.TypeConstraint("V", OpSchema::all_tensor_types(), "All Tensor types")
.TypeAndShapeInferenceFunction(ScanInferenceFunction));
} // namespace ONNX_NAMESPACE
|