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
|
import itertools
import unittest
from functools import partial
from itertools import product
from typing import Iterable, List
import numpy as np
from numpy import inf
import torch
from torch.testing import make_tensor
from torch.testing._internal.common_cuda import (
_get_magma_version,
_get_torch_cuda_version,
CUDA11OrLater,
with_tf32_off,
)
from torch.testing._internal.common_device_type import (
has_cusolver,
skipCPUIfNoLapack,
skipCUDAIf,
skipCUDAIfNoCusolver,
skipCUDAIfNoMagma,
skipCUDAIfNoMagmaAndNoCusolver,
skipCUDAIfRocm,
tol,
toleranceOverride,
)
from torch.testing._internal.common_dtype import (
all_types_and_complex,
all_types_and_complex_and,
floating_and_complex_types,
floating_and_complex_types_and,
)
from torch.testing._internal.common_utils import (
GRADCHECK_NONDET_TOL,
make_fullrank_matrices_with_distinct_singular_values,
slowTest,
TEST_WITH_ROCM,
)
from torch.testing._internal.opinfo.core import (
clone_sample,
DecorateInfo,
ErrorInput,
gradcheck_wrapper_hermitian_input,
OpInfo,
ReductionOpInfo,
S,
SampleInput,
)
from torch.testing._internal.opinfo.refs import PythonRefInfo, ReductionPythonRefInfo
def sample_kwargs_vector_norm(t, **kwargs):
# orders with / without identity
def ords():
has_id = (6, 4, 2, 1, 0, 0.9)
no_id = (inf, -2.1, -inf)
if t.numel() == 0:
dim = kwargs.get("dim")
if dim is None:
return has_id
if not isinstance(dim, Iterable):
dim = (dim,)
for d in dim:
if t.size(d) == 0:
return has_id
return has_id + no_id
return (((), dict(ord=o)) for o in ords())
def sample_inputs_svd(op_info, device, dtype, requires_grad=False, **kwargs):
make_fullrank = make_fullrank_matrices_with_distinct_singular_values
make_arg = partial(
make_fullrank, dtype=dtype, device=device, requires_grad=requires_grad
)
is_linalg_svd = "linalg.svd" in op_info.name
batches = [(), (0,), (3,)]
ns = [0, 3, 5]
def uniformize(usv):
S = usv[1]
k = S.shape[-1]
U = usv[0][..., :k]
Vh = usv[2] if is_linalg_svd else usv[2].mH
Vh = Vh[..., :k, :]
return U, S, Vh
def fn_U(usv):
U, _, _ = uniformize(usv)
return U.abs()
def fn_S(usv):
return uniformize(usv)[1]
def fn_Vh(usv):
# We also return S to test
_, S, Vh = uniformize(usv)
return S, Vh.abs()
def fn_UVh(usv):
U, S, Vh = uniformize(usv)
return U @ Vh, S
fns = (fn_U, fn_S, fn_Vh, fn_UVh)
fullmat = "full_matrices" if is_linalg_svd else "some"
for batch, n, k, fullmat_val, fn in product(batches, ns, ns, (True, False), fns):
shape = batch + (n, k)
yield SampleInput(
make_arg(*shape), kwargs={fullmat: fullmat_val}, output_process_fn_grad=fn
)
def sample_inputs_cross(op_info, device, dtype, requires_grad, **kwargs):
make_arg = partial(
make_tensor, dtype=dtype, device=device, requires_grad=requires_grad
)
yield SampleInput(make_arg((S, 3)), args=(make_arg((S, 3)),))
yield SampleInput(
make_arg((S, 3, S)), args=(make_arg((S, 3, S)),), kwargs=dict(dim=1)
)
yield SampleInput(make_arg((1, 3)), args=(make_arg((S, 3)),), kwargs=dict(dim=-1))
def error_inputs_cross(op_info, device, **kwargs):
make_arg = partial(make_tensor, device=device, dtype=torch.float32)
sample = SampleInput(input=make_arg((S, 3)), args=(make_arg((S, 1)),))
err = "inputs dimension -1 must have length 3"
yield ErrorInput(sample, error_regex=err, error_type=RuntimeError)
sample = SampleInput(input=make_arg((5, S, 3)), args=(make_arg((S, 3)),))
err = "inputs must have the same number of dimensions"
yield ErrorInput(sample, error_regex=err, error_type=RuntimeError)
sample = SampleInput(input=make_arg((S, 2)), args=(make_arg((S, 2)),))
err = "must have length 3"
yield ErrorInput(sample, error_regex=err, error_type=RuntimeError)
sample = SampleInput(
input=make_arg((S, 2)), args=(make_arg((S, 2)),), kwargs=dict(dim=2)
)
err = "Dimension out of range"
yield ErrorInput(sample, error_regex=err, error_type=IndexError)
def sample_inputs_householder_product(op_info, device, dtype, requires_grad, **kwargs):
"""
This function generates input for torch.linalg.householder_product (torch.orgqr).
The first argument should be a square matrix or batch of square matrices, the second argument is a vector or batch of vectors.
Empty, square, rectangular, batched square and batched rectangular input is generated.
"""
# Each column of the matrix is getting multiplied many times leading to very large values for
# the Jacobian matrix entries and making the finite-difference result of grad check less accurate.
# That's why gradcheck with the default range [-9, 9] fails and [-2, 2] is used here.
samples = (
SampleInput(
make_tensor(
(S, S),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
args=(
make_tensor(
(S,),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
),
),
SampleInput(
make_tensor(
(S + 1, S),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
args=(
make_tensor(
(S,),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
),
),
SampleInput(
make_tensor(
(2, 1, S, S),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
args=(
make_tensor(
(
2,
1,
S,
),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
),
),
SampleInput(
make_tensor(
(2, 1, S + 1, S),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
args=(
make_tensor(
(
2,
1,
S,
),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
),
),
SampleInput(
make_tensor(
(0, 0),
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
args=(
make_tensor(
(0,),
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
),
),
SampleInput(
make_tensor(
(S, S),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
args=(
make_tensor(
(0,),
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
),
),
# m = n = S, k = S - 2
SampleInput(
make_tensor(
(S, S),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
args=(
make_tensor(
(S - 2,),
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
),
),
# m = S, n = S -1, k = S - 2
SampleInput(
make_tensor(
(S, S - 1),
dtype=dtype,
device=device,
low=-2,
high=2,
requires_grad=requires_grad,
),
args=(
make_tensor(
(S - 2,),
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
),
),
)
return samples
def sample_inputs_linalg_det_singular(op_info, device, dtype, requires_grad, **kwargs):
make_arg = partial(make_tensor, device=device, dtype=dtype)
def make_singular_matrix_batch_base(size, rank):
assert size[-1] == size[-2]
assert rank > 0 and rank < size[-1]
n = size[-1]
a = make_arg(size[:-2] + (n, rank)) / 10
b = make_arg(size[:-2] + (rank, n)) / 10
x = a @ b
lu, pivs, _ = torch.linalg.lu_factor_ex(x)
p, l, u = torch.lu_unpack(lu, pivs)
u_diag_abs = u.diagonal(0, -2, -1).abs()
u_diag_abs_largest = u_diag_abs.max(dim=-1, keepdim=True).values
u_diag_abs_smallest_idxs = torch.topk(
u_diag_abs, k=(n - rank), largest=False
).indices
u.diagonal(0, -2, -1).div_(u_diag_abs_largest)
u.diagonal(0, -2, -1)[..., u_diag_abs_smallest_idxs] = torch.finfo(dtype).eps
matrix = p @ l @ u
matrix.requires_grad_(requires_grad)
return matrix
def sample_generator():
for batch, size in product(((), (2,), (2, 2)), range(6)):
shape = batch + (size, size)
for rank in range(1, size):
yield make_singular_matrix_batch_base(shape, rank)
return [SampleInput(t) for t in sample_generator()]
def sample_inputs_linalg_matrix_power(op_info, device, dtype, requires_grad, **kwargs):
make_fullrank = make_fullrank_matrices_with_distinct_singular_values
make_arg = partial(
make_tensor, dtype=dtype, device=device, requires_grad=requires_grad
)
make_arg_fullrank = partial(
make_fullrank, dtype=dtype, device=device, requires_grad=requires_grad
)
# (<matrix_size>, (<batch_sizes, ...>))
test_sizes = [
(1, ()),
(2, (0,)),
(2, (2,)),
]
for matrix_size, batch_sizes in test_sizes:
size = batch_sizes + (matrix_size, matrix_size)
for n in (0, 3, 5):
yield SampleInput(make_arg(size), args=(n,))
for n in [-4, -2, -1]:
yield SampleInput(make_arg_fullrank(*size), args=(n,))
def sample_inputs_linalg_det_logdet_slogdet(
op_info, device, dtype, requires_grad, **kwargs
):
make_fullrank = make_fullrank_matrices_with_distinct_singular_values
make_arg = partial(
make_fullrank, dtype=dtype, device=device, requires_grad=requires_grad
)
batches = [(), (0,), (3,)]
ns = [0, 1, 5]
is_logdet = op_info.name == "logdet"
for (
batch,
n,
) in product(batches, ns):
shape = batch + (n, n)
A = make_arg(*shape)
# Need to make the matrices in A have positive determinant for autograd
# To do so, we multiply A by its determinant to flip the sign of its determinant
if is_logdet and not A.is_complex() and A.numel() > 0:
s = torch.linalg.slogdet(A).sign
A = A * s.unsqueeze(-1).unsqueeze(-1)
A.requires_grad_(requires_grad)
yield SampleInput(A)
def sample_inputs_lu_solve(op_info, device, dtype, requires_grad=False, **kwargs):
"""Samples the inputs for both linalg.lu_solve and lu_solve"""
make_fn = make_fullrank_matrices_with_distinct_singular_values
make_a = partial(make_fn, dtype=dtype, device=device)
make_b = partial(make_tensor, dtype=dtype, device=device)
def clone(X, requires_grad):
Y = X.clone()
Y.requires_grad_(requires_grad)
return Y
is_linalg_lu_solve = op_info.name == "linalg.lu_solve"
batches = ((), (0,), (2,))
ns = (3, 1, 0)
nrhs = (4, 1, 0)
for n, batch, rhs in product(ns, batches, nrhs):
A = make_a(*(batch + (n, n)))
LU, pivots = torch.linalg.lu_factor(A)
B = make_b(batch + (n, rhs))
grads = (False,) if not requires_grad else (True, False)
# we try all possible combinations of requires_grad for each input
for LU_grad, B_grad in product(grads, grads):
# when requires_grad == True, at least one input has to have requires_grad enabled
if requires_grad and not LU_grad and not B_grad:
continue
if is_linalg_lu_solve:
for adjoint, left in product((True, False), repeat=2):
yield SampleInput(
clone(LU, LU_grad),
args=(pivots, clone(B if left else B.mT, B_grad)),
kwargs=dict(adjoint=adjoint, left=left),
)
else:
yield SampleInput(clone(B, B_grad), args=(clone(LU, LU_grad), pivots))
def sample_inputs_linalg_multi_dot(op_info, device, dtype, requires_grad, **kwargs):
# Each test case consists of the sizes in the chain of multiplications
# e.g. [2, 3, 4, 5] generates matrices (2, 3) @ (3, 4) @ (4, 5)
test_cases = [
[1, 2, 1],
[2, 0, 2],
[0, 2, 2],
[2, 2, 2, 2],
[2, 3, 4, 5],
[5, 4, 0, 2],
[2, 4, 3, 5, 3, 2],
]
result = []
for sizes in test_cases:
tensors = []
for size in zip(sizes[:-1], sizes[1:]):
t = make_tensor(
size, dtype=dtype, device=device, requires_grad=requires_grad
)
tensors.append(t)
result.append(SampleInput(tensors))
return result
def sample_inputs_linalg_matrix_norm(op_info, device, dtype, requires_grad, **kwargs):
low_precision_dtypes = (torch.float16, torch.bfloat16, torch.complex32)
make_arg = partial(
make_tensor, device=device, dtype=dtype, requires_grad=requires_grad
)
sizes = ((2, 2), (2, 3, 2))
if dtype in low_precision_dtypes:
# svdvals not supported for low precision dtypes
ords = ("fro", inf, -inf, 1, -1)
else:
ords = ("fro", "nuc", inf, -inf, 1, -1, 2, -2)
dims = ((-2, -1), (-1, 0))
for size, ord, dim, keepdim in product(sizes, ords, dims, [True, False]):
yield SampleInput(make_arg(size), args=(ord, dim, keepdim))
def sample_inputs_linalg_norm(
op_info, device, dtype, requires_grad, *, variant=None, **kwargs
):
if variant is not None and variant not in ("subgradient_at_zero",):
raise ValueError(
f"Unsupported variant, expected variant to be 'subgradient_at_zero' but got: {variant}"
)
test_sizes = [
(S,),
(0,),
(S, S),
(0, 0),
(S, 0),
(0, S),
(S, S, S),
(0, S, S),
(S, 0, S),
(0, 0, 0),
]
vector_ords = (None, 0, 0.5, 1, 2, 3.5, inf, -0.5, -1, -2, -3.5, -inf)
if dtype in {torch.float16, torch.bfloat16, torch.complex32}:
# svdvals not supported for low precision dtypes
matrix_ords = ("fro", inf, -inf, 1, -1)
else:
matrix_ords = (None, "fro", "nuc", inf, -inf, 1, -1, 2, -2)
inputs = []
for test_size in test_sizes:
is_vector_norm = len(test_size) == 1
is_matrix_norm = len(test_size) == 2
# IndexError: amax(): Expected reduction dim 0 to have non-zero size.
is_valid_for_p2 = is_vector_norm or (test_size[-1] != 0 and test_size[-2] != 0)
for keepdim in [False, True]:
if variant != "subgradient_at_zero" and is_valid_for_p2:
inputs.append(
SampleInput(
make_tensor(
test_size,
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
kwargs=dict(keepdim=keepdim),
)
)
if not (is_vector_norm or is_matrix_norm):
continue
ords = vector_ords if is_vector_norm else matrix_ords
for ord in ords:
if is_vector_norm and test_size[-1] == 0:
if ord == np.inf or (ord is not None and ord < 0):
# RuntimeError: linalg.vector_norm cannot compute the
# {ord} norm on an empty tensor because the operation
# does not have an identity
continue
elif is_matrix_norm:
dims_to_check = {
None: (0,),
np.inf: (0,),
2: (0, 1),
1: (1,),
-1: (1,),
-2: (0, 1),
-np.inf: (0,),
}.get(ord, ())
if any(test_size[d] == 0 for d in dims_to_check):
# IndexError: amax(): Expected reduction dim {dim} to
# have non-zero size.
continue
if variant == "subgradient_at_zero":
inputs.append(
SampleInput(
torch.zeros(
test_size,
dtype=dtype,
device=device,
requires_grad=requires_grad,
),
args=(ord,),
kwargs=dict(keepdim=keepdim),
)
)
else:
inputs.append(
SampleInput(
make_tensor(
test_size,
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
args=(ord,),
kwargs=dict(keepdim=keepdim),
)
)
if ord in ["nuc", "fro"]:
inputs.append(
SampleInput(
make_tensor(
test_size,
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
),
kwargs=dict(ord=ord, keepdim=keepdim, dim=(0, 1)),
)
)
return inputs
def sample_inputs_linalg_vecdot(op_info, device, dtype, requires_grad, **kwargs):
make_arg = partial(
make_tensor, device=device, dtype=dtype, requires_grad=requires_grad
)
batches = ((), (0,), (1,), (5,))
ns = (0, 1, 3, 5)
for b, n in product(batches, ns):
shape = b + (n,)
yield SampleInput(make_arg(shape), args=(make_arg(shape),))
for i in range(len(shape)):
yield SampleInput(
make_arg(shape), args=(make_arg(shape),), kwargs=dict(dim=i)
)
def sample_inputs_linalg_invertible(
op_info, device, dtype, requires_grad=False, **kwargs
):
"""
This function generates invertible inputs for linear algebra ops
The input is generated as the itertools.product of 'batches' and 'ns'.
In total this function generates 8 SampleInputs
'batches' cases include:
() - single input,
(0,) - zero batched dimension,
(2,) - batch of two matrices,
(1, 1) - 1x1 batch of matrices
'ns' gives 0x0 and 5x5 matrices.
Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.
"""
make_fn = make_fullrank_matrices_with_distinct_singular_values
make_arg = partial(make_fn, dtype=dtype, device=device, requires_grad=requires_grad)
batches = [(), (0,), (2,), (1, 1)]
ns = [5, 0]
for batch, n in product(batches, ns):
yield SampleInput(make_arg(*batch, n, n))
def sample_inputs_matrix_rank(op_info, device, dtype, requires_grad=False, **kwargs):
"""
This function produces inputs for matrix rank that test
all possible combinations for atol and rtol
"""
def make_tol_arg(kwarg_type, inp):
if kwarg_type == "none":
return None
if kwarg_type == "float":
return 1.0
assert kwarg_type == "tensor"
return torch.ones(inp.shape[:-2], device=device)
for tol_type in ["float", "tensor"]:
for atol_type, rtol_type in product(["none", tol_type], repeat=2):
if (
not atol_type and not rtol_type
): # default behavior, so skipped here so it's not tested 2 extra times
continue
for sample in sample_inputs_linalg_invertible(
op_info, device, dtype, requires_grad
):
assert sample.kwargs == {}
sample.kwargs = {
"atol": make_tol_arg(atol_type, sample.input),
"rtol": make_tol_arg(rtol_type, sample.input),
}
yield sample
for sample in sample_inputs_linalg_invertible(
op_info, device, dtype, requires_grad
):
yield sample # default kwargs
def sample_inputs_linalg_pinv_singular(
op_info, device, dtype, requires_grad=False, **kwargs
):
"""
This function produces factors `a` and `b` to generate inputs of the form `a @ b.t()` to
test the backward method of `linalg_pinv`. That way we always preserve the rank of the
input no matter the perturbations applied to it by the gradcheck.
Note that `pinv` is Frechet-differentiable in a rank-preserving neighborhood.
"""
batches = [(), (0,), (2,), (1, 1)]
# the size of at least 30 is required to cause failures for the previous implicit implementation
# of the pinv's backward method, albeit it is slow.
size = [0, 3, 50]
for batch, m, n in product(batches, size, size):
for k in range(min(3, min(m, n))):
# Note that by making the columns of `a` and `b` orthonormal we make sure that
# the product matrix `a @ b.t()` has condition number 1 when restricted to its image
a = (
torch.rand(*batch, m, k, device=device, dtype=dtype)
.qr()
.Q.requires_grad_(requires_grad)
)
b = (
torch.rand(*batch, n, k, device=device, dtype=dtype)
.qr()
.Q.requires_grad_(requires_grad)
)
yield SampleInput(a, args=(b,))
def sample_inputs_linalg_cond(op_info, device, dtype, requires_grad=False, **kwargs):
make_arg = partial(
make_tensor, dtype=dtype, device=device, requires_grad=requires_grad
)
# autograd is not supported for inputs with zero number of elements
shapes = (
(S, S),
(2, S, S),
(2, 1, S, S),
)
for shape in shapes:
yield SampleInput(make_arg(shape))
def sample_inputs_linalg_vander(op_info, device, dtype, requires_grad=False, **kwargs):
make_arg = partial(
make_tensor, dtype=dtype, device=device, requires_grad=requires_grad
)
shapes = (
(),
(1,),
(S,),
(2, S),
)
for shape in shapes:
if len(shape) > 0 and shape[-1] > 1:
yield SampleInput(make_arg(shape))
n = shape[-1] if len(shape) > 0 else 1
for i in range(3):
# n-1, n, n+1
N = n + i - 1
if N < 2:
continue
yield SampleInput(make_arg(shape), kwargs=dict(N=N))
def np_vander_batched(x, N=None):
# Wrapper around np.vander that supports batches of 1 dimension (enough for the tests)
if x.ndim == 0:
x = x[np.newaxis]
if x.ndim == 1:
y = np.vander(x, N=N, increasing=True)
return y
else:
if N is None:
N = x.shape[-1]
y = np.vander(x.ravel(), N=N, increasing=True).reshape((*x.shape, N))
return y
def sample_inputs_linalg_cholesky_inverse(
op_info, device, dtype, requires_grad=False, **kwargs
):
from torch.testing._internal.common_utils import random_well_conditioned_matrix
# Cholesky factorization is for positive-definite matrices
single_well_conditioned_matrix = random_well_conditioned_matrix(
S, S, dtype=dtype, device=device
)
batch_well_conditioned_matrices = random_well_conditioned_matrix(
2, S, S, dtype=dtype, device=device
)
single_pd = single_well_conditioned_matrix @ single_well_conditioned_matrix.mH
batch_pd = batch_well_conditioned_matrices @ batch_well_conditioned_matrices.mH
inputs = (
torch.zeros(0, 0, dtype=dtype, device=device), # 0x0 matrix
torch.zeros(0, 2, 2, dtype=dtype, device=device), # zero batch of matrices
single_pd,
batch_pd,
)
test_cases = (torch.linalg.cholesky(a, upper=False) for a in inputs)
for l in test_cases:
# generated lower-triangular samples
l.requires_grad = requires_grad
yield SampleInput(l) # upper=False by default
yield SampleInput(
l.detach().clone().requires_grad_(requires_grad), kwargs=dict(upper=False)
)
# generate upper-triangular inputs
u = l.detach().clone().mT.contiguous().requires_grad_(requires_grad)
yield SampleInput(u, kwargs=dict(upper=True))
def sample_inputs_linalg_ldl_factor(
op_info, device, dtype, requires_grad=False, **kwargs
):
from torch.testing._internal.common_utils import (
random_hermitian_pd_matrix,
random_symmetric_pd_matrix,
)
device = torch.device(device)
# Symmetric inputs
yield SampleInput(
random_symmetric_pd_matrix(S, dtype=dtype, device=device),
kwargs=dict(hermitian=False),
) # single matrix
yield SampleInput(
random_symmetric_pd_matrix(S, 2, dtype=dtype, device=device),
kwargs=dict(hermitian=False),
) # batch of matrices
yield SampleInput(
torch.zeros(0, 0, dtype=dtype, device=device), kwargs=dict(hermitian=False)
) # 0x0 matrix
yield SampleInput(
torch.zeros(0, 2, 2, dtype=dtype, device=device), kwargs=dict(hermitian=False)
) # zero batch of matrices
# Hermitian inputs
# hermitian=True for complex inputs on CUDA is supported only with MAGMA 2.5.4+
magma_254_available = device.type == "cuda" and _get_magma_version() >= (2, 5, 4)
if dtype.is_complex and (device.type == "cpu" or magma_254_available):
yield SampleInput(
random_hermitian_pd_matrix(S, dtype=dtype, device=device),
kwargs=dict(hermitian=True),
) # single matrix
yield SampleInput(
random_hermitian_pd_matrix(S, 2, dtype=dtype, device=device),
kwargs=dict(hermitian=True),
) # batch of matrices
def sample_inputs_linalg_ldl_solve(
op_info, device, dtype, requires_grad=False, **kwargs
):
# Generate LDL factors of symmetric (and Hermitian on CPU) matrices
from torch.testing._internal.common_utils import (
random_hermitian_pd_matrix,
random_symmetric_pd_matrix,
)
device = torch.device(device)
symmetric_inputs = (
random_symmetric_pd_matrix(S, dtype=dtype, device=device), # single matrix
random_symmetric_pd_matrix(
S, 2, dtype=dtype, device=device
), # batch of matrices
torch.zeros(0, 0, dtype=dtype, device=device), # 0x0 matrix
torch.zeros(0, 2, 2, dtype=dtype, device=device), # zero batch of matrices
)
hermitian_inputs = (
(
random_hermitian_pd_matrix(S, dtype=dtype, device=device),
random_hermitian_pd_matrix(S, 2, dtype=dtype, device=device),
)
if device.type == "cpu" and dtype.is_complex
else ()
)
test_cases1 = (
torch.linalg.ldl_factor_ex(a, hermitian=False) for a in symmetric_inputs
)
test_cases2 = (
torch.linalg.ldl_factor_ex(a, hermitian=True) for a in hermitian_inputs
)
# Symmetric case
for test_case in test_cases1:
factors, pivots, _ = test_case
factors.requires_grad = requires_grad
for B_batch_shape in ((), factors.shape[:-2]):
B = make_tensor(
(*B_batch_shape, factors.shape[-1], S),
device=device,
dtype=dtype,
requires_grad=requires_grad,
)
yield SampleInput(factors, args=(pivots, B), kwargs=dict(hermitian=False))
clone_factors = factors.detach().clone().requires_grad_(requires_grad)
yield SampleInput(
clone_factors, args=(pivots, B), kwargs=dict(hermitian=False)
)
# Hermitian case
for test_case in test_cases2:
factors, pivots, _ = test_case
factors.requires_grad = requires_grad
for B_batch_shape in ((), factors.shape[:-2]):
B = make_tensor(
(*B_batch_shape, factors.shape[-1], S),
device=device,
dtype=dtype,
requires_grad=requires_grad,
)
yield SampleInput(factors, args=(pivots, B), kwargs=dict(hermitian=True))
clone_factors = factors.detach().clone().requires_grad_(requires_grad)
yield SampleInput(
clone_factors, args=(pivots, B), kwargs=dict(hermitian=True)
)
def sample_inputs_linalg_lstsq(op_info, device, dtype, requires_grad=False, **kwargs):
from torch.testing._internal.common_utils import random_well_conditioned_matrix
device = torch.device(device)
drivers: Tuple[str, ...]
if device.type == "cuda":
drivers = ("gels",)
else:
drivers = ("gels", "gelsy", "gelss", "gelsd")
# we generate matrices of shape (..., n + delta, n)
deltas: Tuple[int, ...]
if device.type == "cpu" or has_cusolver():
deltas = (-1, 0, +1)
# only square systems if Cusolver is not available
# becase we solve a lstsq problem with a transposed matrix in the backward
else:
deltas = (0,)
out = []
for batch, driver, delta in product(((), (3,), (3, 3)), drivers, deltas):
shape = batch + (3 + delta, 3)
a = random_well_conditioned_matrix(*shape, dtype=dtype, device=device)
a.requires_grad_(requires_grad)
b = make_tensor(
shape,
dtype=dtype,
device=device,
low=None,
high=None,
requires_grad=requires_grad,
)
out.append(SampleInput(a, args=(b,), kwargs=dict(driver=driver)))
return out
def error_inputs_lstsq(op_info, device, **kwargs):
zero_d = torch.randn((), device=device)
yield ErrorInput(
SampleInput(zero_d, args=(zero_d,)),
error_type=RuntimeError,
error_regex="at least 2 dimensions",
)
def error_inputs_lstsq_grad_oriented(op_info, device, **kwargs):
zero_d = torch.randn((), device=device)
yield ErrorInput(
SampleInput(zero_d, args=(zero_d, None)),
error_type=RuntimeError,
error_regex="at least 2 dimensions",
)
def sample_inputs_linalg_cholesky(
op_info, device, dtype, requires_grad=False, **kwargs
):
"""
This function generates always positive-definite input for torch.linalg.cholesky using
random_hermitian_pd_matrix.
The input is generated as the itertools.product of 'batches' and 'ns'.
In total this function generates 8 SampleInputs
'batches' cases include:
() - single input,
(0,) - zero batched dimension,
(2,) - batch of two matrices,
(1, 1) - 1x1 batch of matrices
'ns' gives 0x0 and 5x5 matrices.
Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.
"""
from torch.testing._internal.common_utils import random_hermitian_pd_matrix
batches = [(), (0,), (2,), (1, 1)]
ns = [5, 0]
out = []
for batch, n, upper in product(batches, ns, [True, False]):
a = random_hermitian_pd_matrix(n, *batch, dtype=dtype, device=device)
a.requires_grad = requires_grad
out.append(SampleInput(a, kwargs={"upper": upper}))
return out
def sample_inputs_linalg_eig(op_info, device, dtype, requires_grad=False, **kwargs):
"""
This function generates input for torch.linalg.eig
"""
def out_fn(output):
return output[0], abs(output[1])
samples = sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad)
for sample in samples:
sample.output_process_fn_grad = out_fn
yield sample
def sample_inputs_linalg_eigh(op_info, device, dtype, requires_grad=False, **kwargs):
"""
This function generates input for torch.linalg.eigh/eigvalsh with UPLO="U" or "L" keyword argument.
"""
def out_fn(output):
if isinstance(output, tuple):
# eigh function
return output[0], abs(output[1])
else:
# eigvalsh function
return output
# Samples do not need to be Hermitian, as we're using gradcheck_wrapper_hermitian_input
samples = sample_inputs_linalg_invertible(op_info, device, dtype, requires_grad)
for sample in samples:
sample.kwargs = {"UPLO": np.random.choice(["L", "U"])}
sample.output_process_fn_grad = out_fn
yield sample
def sample_inputs_linalg_pinv(op_info, device, dtype, requires_grad=False, **kwargs):
"""
This function generates input for torch.linalg.pinv with hermitian=False keyword argument.
"""
for o in sample_inputs_linalg_invertible(
op_info, device, dtype, requires_grad, **kwargs
):
real_dtype = o.input.real.dtype if dtype.is_complex else dtype
# requires_grad path for rtol tensor is not implemented
for rtol in (None, 1.0, torch.tensor(1.0, dtype=real_dtype, device=device)):
o = clone_sample(o)
o.kwargs = {"rtol": rtol}
yield o
def sample_inputs_linalg_pinv_hermitian(
op_info, device, dtype, requires_grad=False, **kwargs
):
"""
This function generates input for torch.linalg.pinv with hermitian=True keyword argument.
"""
for o in sample_inputs_linalg_invertible(
op_info, device, dtype, requires_grad, **kwargs
):
o.kwargs = {"hermitian": True}
yield o
def sample_inputs_linalg_solve(
op_info, device, dtype, requires_grad=False, vector_rhs_allowed=True, **kwargs
):
"""
This function generates always solvable input for torch.linalg.solve
We sample a fullrank square matrix (i.e. invertible) A
The first input to torch.linalg.solve is generated as the itertools.product of 'batches' and 'ns'.
The second input is generated as the product of 'batches', 'ns' and 'nrhs'.
In total this function generates 18 SampleInputs
'batches' cases include:
() - single input,
(0,) - zero batched dimension,
(2,) - batch of two matrices.
'ns' gives 0x0 and 5x5 matrices.
and 'nrhs' controls the number of vectors to solve for:
() - using 1 as the number of vectors implicitly
(1,) - same as () but explicit
(3,) - solve for 3 vectors.
Zeros in dimensions are edge cases in the implementation and important to test for in order to avoid unexpected crashes.
'vector_rhs_allowed' controls whether to include nrhs = () to the list of SampleInputs.
torch.solve / triangular_solve / cholesky_solve (opposed to torch.linalg.solve) do not allow
1D tensors (vectors) as the right-hand-side.
Once torch.solve / triangular_solve / cholesky_solve and its testing are removed,
'vector_rhs_allowed' may be removed here as well.
"""
make_fullrank = make_fullrank_matrices_with_distinct_singular_values
make_a = partial(
make_fullrank, dtype=dtype, device=device, requires_grad=requires_grad
)
make_b = partial(
make_tensor, dtype=dtype, device=device, requires_grad=requires_grad
)
batches = [(), (0,), (2,)]
ns = [5, 0]
if vector_rhs_allowed:
nrhs = [(), (1,), (3,)]
else:
nrhs = [(1,), (3,)]
for n, batch, rhs in product(ns, batches, nrhs):
yield SampleInput(make_a(*batch, n, n), args=(make_b((batch + (n,) + rhs)),))
def sample_inputs_linalg_solve_triangular(
op_info, device, dtype, requires_grad=False, **kwargs
):
make_arg = partial(make_tensor, dtype=dtype, device=device)
bs = (1, 2, 0)
ns = (3, 0)
ks = (1, 3, 0)
for b, n, k, (left, upper, uni) in product(
bs, ns, ks, product((True, False), repeat=3)
):
if b == 1:
A = make_arg((n, n)) if left else make_arg((k, k))
B = make_arg((n, k))
else:
A = make_arg((b, n, n)) if left else make_arg((b, k, k))
B = make_arg((b, n, k))
if uni:
# Not really necessary, but writing it for consistency
A.diagonal(0, -2, -1).fill_(1.0)
else:
d = A.diagonal(0, -2, -1)
d[d.abs() < 1e-6] = 1.0
if upper:
A.triu_()
else:
A.tril_()
kwargs = {"upper": upper, "left": left, "unitriangular": uni}
if requires_grad:
for grad_A, grad_B in product((True, False), repeat=2):
# Either A or B needs to have a gradient
if not grad_A and not grad_B:
continue
yield SampleInput(
A.clone().requires_grad_(grad_A),
args=(B.clone().requires_grad_(grad_B),),
kwargs=kwargs,
)
else:
yield SampleInput(A, args=(B,), kwargs=kwargs)
def sample_inputs_legacy_solve(op_info, device, dtype, requires_grad=False, **kwargs):
"""
This function generates always solvable input for legacy solve functions
(the ones that are not in torch.linalg module).
The difference from sample_inputs_linalg_solve is that here the right-hand-side of A x = b equation
should have b.ndim >= 2, vectors are not allowed.
Also the arguments order is swapped.
"""
out = sample_inputs_linalg_solve(
op_info, device, dtype, requires_grad=requires_grad, vector_rhs_allowed=False
)
def out_fn(output):
return output[0]
# Reverses tensor order
for sample in out:
sample.input, sample.args = sample.args[0], (sample.input,)
if op_info.name == "solve":
sample.output_process_fn_grad = out_fn
yield sample
def sample_inputs_linalg_lu(op_info, device, dtype, requires_grad=False, **kwargs):
full_rank = op_info.name == "linalg.lu_factor"
make_fn = (
make_tensor
if not full_rank
else make_fullrank_matrices_with_distinct_singular_values
)
make_arg = partial(make_fn, dtype=dtype, device=device, requires_grad=requires_grad)
def out_fn(output):
if op_info.name == "linalg.lu":
return output[1], output[2]
else:
return output
batch_shapes = ((), (3,), (3, 3))
# pivot=False only supported in CUDA
pivots = (True, False) if torch.device(device).type == "cuda" else (True,)
deltas = (-2, -1, 0, +1, +2)
for batch_shape, pivot, delta in product(batch_shapes, pivots, deltas):
shape = batch_shape + (S + delta, S)
# Insanely annoying that make_fullrank_blablabla accepts a *shape and not a tuple!
A = make_arg(shape) if not full_rank else make_arg(*shape)
yield SampleInput(A, kwargs={"pivot": pivot}, output_process_fn_grad=out_fn)
def sample_inputs_linalg_svdvals(op_info, device, dtype, requires_grad=False, **kwargs):
make_arg = partial(
make_tensor, dtype=dtype, device=device, requires_grad=requires_grad
)
batches = [(), (0,), (2,), (1, 1)]
ns = [5, 2, 0]
for batch, m, n in product(batches, ns, ns):
yield SampleInput(make_arg(batch + (m, n)))
def sample_inputs_linalg_qr_geqrf(
op_info, device, dtype, requires_grad=False, **kwargs
):
# QR is just well defined when the matrix is full rank
make_fullrank = make_fullrank_matrices_with_distinct_singular_values
make_arg = partial(
make_fullrank, dtype=dtype, device=device, requires_grad=requires_grad
)
batches = [(), (0,), (2,), (1, 1)]
ns = [5, 2, 0]
for batch, (m, n) in product(batches, product(ns, ns)):
shape = batch + (m, n)
yield SampleInput(make_arg(*shape))
def sample_inputs_tensorsolve(op_info, device, dtype, requires_grad, **kwargs):
a_shapes = [(2, 3, 6), (3, 4, 4, 3)]
# Zero-dim tensors are not supported in NumPy, so we skip them for now.
# NumPy is used in reference check tests.
# See https://github.com/numpy/numpy/pull/20482 for tracking NumPy bugfix.
# a_shapes += [(0, 0, 1, 2, 3, 0)]
dimss = [None, (0, 2)]
for a_shape, dims in itertools.product(a_shapes, dimss):
a = make_tensor(
a_shape, dtype=dtype, device=device, requires_grad=requires_grad
)
b = make_tensor(
a_shape[:2], dtype=dtype, device=device, requires_grad=requires_grad
)
yield SampleInput(a, args=(b,), kwargs=dict(dims=dims))
def sample_inputs_tensorinv(op_info, device, dtype, requires_grad, **kwargs):
make_arg = make_fullrank_matrices_with_distinct_singular_values
def make_input():
return make_arg(12, 12, device=device, dtype=dtype, requires_grad=requires_grad)
# lhs / rhs shape can have any number of dimensions as long as their product equals 12
shapes = [
((2, 2, 3), (12, 1)),
((4, 3), (6, 1, 2)),
]
samples = []
for shape_lhs, shape_rhs in shapes:
inp = make_input().reshape(*shape_lhs, *shape_rhs).detach()
inp.requires_grad_(requires_grad)
samples.append(SampleInput(inp, kwargs=dict(ind=len(shape_lhs))))
return samples
op_db: List[OpInfo] = [
OpInfo(
"linalg.cross",
ref=lambda x, y, dim=-1: np.cross(x, y, axis=dim),
op=torch.linalg.cross,
dtypes=all_types_and_complex_and(torch.bfloat16),
dtypesIfCUDA=all_types_and_complex_and(torch.half),
aten_name="linalg_cross",
sample_inputs_func=sample_inputs_cross,
error_inputs_func=error_inputs_cross,
supports_out=True,
supports_fwgrad_bwgrad=True,
supports_forward_ad=True,
),
OpInfo(
"linalg.det",
aten_name="linalg_det",
op=torch.linalg.det,
aliases=("det",),
dtypes=floating_and_complex_types(),
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_linalg_det_logdet_slogdet,
decorators=[skipCPUIfNoLapack, skipCUDAIfNoMagmaAndNoCusolver],
check_batched_gradgrad=False,
),
OpInfo(
"linalg.det",
aten_name="linalg_det",
op=torch.linalg.det,
variant_test_name="singular",
aliases=("det",),
dtypes=floating_and_complex_types(),
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
check_batched_gradgrad=False,
sample_inputs_func=sample_inputs_linalg_det_singular,
decorators=[skipCPUIfNoLapack, skipCUDAIfNoMagmaAndNoCusolver],
skips=(
DecorateInfo(
unittest.skip("The backward may give different results"),
"TestCommon",
"test_noncontiguous_samples",
),
# Both Hessians are incorrect on complex inputs??
DecorateInfo(
unittest.expectedFailure,
"TestGradients",
"test_fn_gradgrad",
dtypes=(torch.complex128,),
),
DecorateInfo(
unittest.expectedFailure,
"TestGradients",
"test_fn_fwgrad_bwgrad",
dtypes=(torch.complex128,),
),
DecorateInfo(
unittest.skip("Skipped, see https://github.com//issues/84192"),
"TestGradients",
"test_fn_gradgrad",
device_type="cuda",
),
DecorateInfo(
unittest.skip("Skipped, see https://github.com//issues/84192"),
"TestGradients",
"test_fn_fwgrad_bwgrad",
device_type="cuda",
),
),
),
OpInfo(
"linalg.cholesky",
aten_name="linalg_cholesky",
dtypes=floating_and_complex_types(),
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
# See https://github.com/pytorch/pytorch/pull/78358
check_batched_forward_grad=False,
sample_inputs_func=sample_inputs_linalg_cholesky,
gradcheck_wrapper=gradcheck_wrapper_hermitian_input,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
),
OpInfo(
"linalg.cholesky_ex",
aten_name="linalg_cholesky_ex",
dtypes=floating_and_complex_types(),
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
# See https://github.com/pytorch/pytorch/pull/78358
check_batched_forward_grad=False,
sample_inputs_func=sample_inputs_linalg_cholesky,
gradcheck_wrapper=gradcheck_wrapper_hermitian_input,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
),
OpInfo(
"linalg.vecdot",
aten_name="linalg_vecdot",
ref=lambda x, y, *, dim=-1: (x.conj() * y).sum(dim),
dtypes=floating_and_complex_types_and(torch.bfloat16),
dtypesIfCUDA=floating_and_complex_types_and(
torch.half, *[torch.bfloat16] if (CUDA11OrLater or TEST_WITH_ROCM) else []
),
sample_inputs_func=sample_inputs_linalg_vecdot,
check_batched_forward_grad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
skips=(
# Issue with conj and torch dispatch, see https://github.com/pytorch/pytorch/issues/82479
DecorateInfo(
unittest.skip("Skipped!"),
"TestSchemaCheckModeOpInfo",
"test_schema_correctness",
dtypes=(torch.complex64, torch.complex128),
),
),
),
OpInfo(
"linalg.cond",
aten_name="linalg_cond",
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_cond,
check_batched_gradgrad=False,
check_batched_forward_grad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, with_tf32_off],
),
OpInfo(
"linalg.eig",
aten_name="linalg_eig",
op=torch.linalg.eig,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_eig,
check_batched_forward_grad=False,
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
skips=(
# AssertionError: Scalars are not equal!
DecorateInfo(
unittest.expectedFailure, "TestCommon", "test_out", device_type="cpu"
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack, with_tf32_off],
),
OpInfo(
"linalg.eigvals",
aten_name="linalg_eigvals",
op=torch.linalg.eigvals,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_invertible,
check_batched_forward_grad=False,
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],
skips=(
# exits early on eager extremal value test
DecorateInfo(
unittest.skip("Skipped!"),
"TestCudaFuserOpInfo",
"test_nvfuser_extremal_values",
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.eigh",
aten_name="linalg_eigh",
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_eigh,
gradcheck_wrapper=gradcheck_wrapper_hermitian_input,
check_batched_forward_grad=False,
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack, with_tf32_off],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.eigvalsh",
aten_name="linalg_eigvalsh",
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_eigh,
gradcheck_wrapper=gradcheck_wrapper_hermitian_input,
check_batched_forward_grad=False,
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],
skips=(
# Pre-existing condition; Needs to be fixed
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.householder_product",
aten_name="linalg_householder_product",
op=torch.linalg.householder_product,
aliases=("orgqr",),
dtypes=floating_and_complex_types(),
# https://github.com/pytorch/pytorch/issues/80411
gradcheck_fast_mode=True,
# TODO: backward uses in-place operations that vmap doesn't like
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
check_batched_forward_grad=False,
sample_inputs_func=sample_inputs_householder_product,
decorators=[
skipCUDAIfNoCusolver,
skipCPUIfNoLapack,
DecorateInfo(
toleranceOverride({torch.complex64: tol(atol=1e-3, rtol=1e-3)})
),
],
),
OpInfo(
"linalg.ldl_factor",
aten_name="linalg_ldl_factor",
dtypes=floating_and_complex_types(),
supports_autograd=False,
sample_inputs_func=sample_inputs_linalg_ldl_factor,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, skipCUDAIfRocm],
),
OpInfo(
"linalg.ldl_factor_ex",
aten_name="linalg_ldl_factor_ex",
dtypes=floating_and_complex_types(),
supports_autograd=False,
sample_inputs_func=sample_inputs_linalg_ldl_factor,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, skipCUDAIfRocm],
),
OpInfo(
"linalg.ldl_solve",
aten_name="linalg_ldl_solve",
dtypes=floating_and_complex_types(),
supports_autograd=False,
sample_inputs_func=sample_inputs_linalg_ldl_solve,
decorators=[
skipCUDAIf(
_get_torch_cuda_version() < (11, 4), "not available before CUDA 11.3.1"
),
skipCUDAIfNoCusolver,
skipCUDAIfRocm,
skipCPUIfNoLapack,
],
),
OpInfo(
"linalg.lstsq",
aten_name="linalg_lstsq",
dtypes=floating_and_complex_types(),
supports_out=True,
sample_inputs_func=sample_inputs_linalg_lstsq,
error_inputs_func=error_inputs_lstsq,
decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],
skips=(
# we skip gradient checks for this suite as they are tested in
# variant_test_name='grad_oriented'
DecorateInfo(unittest.skip("Skipped!"), "TestGradients"),
# The values for attribute 'shape' do not match
DecorateInfo(unittest.skip("Skipped!"), "TestCommon", "test_out"),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.lstsq",
aten_name="linalg_lstsq",
variant_test_name="grad_oriented",
# gradchecks for forward AD fails with multi-Tensor outputs
op=lambda a, b, driver: torch.linalg.lstsq(a, b, driver=driver)[0],
supports_out=False,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_lstsq,
error_inputs_func=error_inputs_lstsq_grad_oriented,
# Runs very slowly on slow gradcheck - alternatively reduce input sizes
gradcheck_fast_mode=True,
supports_autograd=True,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],
skips=(
# tests do not work with passing lambda for op
DecorateInfo(
unittest.expectedFailure, "TestJit", "test_variant_consistency_jit"
),
DecorateInfo(
unittest.expectedFailure,
"TestOperatorSignatures",
"test_get_torch_func_signature_exhaustive",
),
),
),
OpInfo(
"linalg.matrix_power",
aliases=("matrix_power",),
aten_name="linalg_matrix_power",
dtypes=floating_and_complex_types(),
# https://github.com/pytorch/pytorch/issues/80411
gradcheck_fast_mode=True,
supports_inplace_autograd=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
check_batched_grad=False,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, with_tf32_off],
sample_inputs_func=sample_inputs_linalg_matrix_power,
),
OpInfo(
"linalg.multi_dot",
# Need this lambda because gradcheck does not work with TensorList inputs
aten_name="linalg_multi_dot",
dtypes=all_types_and_complex_and(torch.bfloat16),
dtypesIfCUDA=floating_and_complex_types_and(
torch.half, *[torch.bfloat16] if (CUDA11OrLater or TEST_WITH_ROCM) else []
),
supports_inplace_autograd=False,
# Batched grad checks fail for empty input tensors (see https://github.com/pytorch/pytorch/issues/53407)
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
# https://github.com/pytorch/pytorch/issues/66357
check_batched_forward_grad=False,
sample_inputs_func=sample_inputs_linalg_multi_dot,
gradcheck_nondet_tol=GRADCHECK_NONDET_TOL,
skips=(
# https://github.com/pytorch/pytorch/issues/67470
DecorateInfo(
unittest.skip("67470!"), "TestCommon", "test_noncontiguous_samples"
),
# Fails on XLA.
# AssertionError: False is not true : Tensors failed to compare as equal!
DecorateInfo(
unittest.skip("Skipped!"),
"TestOpInfo",
device_type="xla",
dtypes=(torch.long,),
),
# https://github.com/pytorch/pytorch/issues/71774
DecorateInfo(
unittest.skip("Skipped!"),
"TestNNCOpInfo",
"test_nnc_correctness",
device_type="cpu",
dtypes=(torch.long,),
),
),
),
# NB: linalg.norm has two variants so that different skips can be used for different sample inputs
OpInfo(
"linalg.norm",
aten_name="linalg_norm",
op=torch.linalg.norm,
dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, with_tf32_off],
sample_inputs_func=sample_inputs_linalg_norm,
supports_forward_ad=True,
check_batched_forward_grad=False,
supports_fwgrad_bwgrad=True,
skips=(
DecorateInfo(unittest.expectedFailure, "TestGradients", "test_fn_gradgrad"),
),
),
OpInfo(
"linalg.norm",
op=torch.linalg.norm,
variant_test_name="subgradients_at_zero",
dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, with_tf32_off],
sample_inputs_func=partial(
sample_inputs_linalg_norm, variant="subgradient_at_zero"
),
aten_name="linalg_norm",
supports_forward_ad=True,
# torch.autograd.gradcheck.GradcheckError: While computing batched gradients, got:
# Could not allocate memory to change Tensor SizesAndStrides!
check_batched_forward_grad=False,
supports_fwgrad_bwgrad=True,
skips=(
# [NEW] Skips specifically for sample inputs at zero
# norm's vjp/jvp are not well-conditioned near zero
DecorateInfo(unittest.expectedFailure, "TestGradients", "test_fn_gradgrad"),
DecorateInfo(
unittest.expectedFailure, "TestGradients", "test_fn_fwgrad_bwgrad"
),
DecorateInfo(
unittest.expectedFailure, "TestGradients", "test_forward_mode_AD"
),
DecorateInfo(unittest.expectedFailure, "TestGradients", "test_fn_grad"),
),
),
OpInfo(
"linalg.matrix_norm",
aten_name="linalg_matrix_norm",
dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),
supports_forward_ad=True,
check_batched_forward_grad=False,
check_batched_gradgrad=False,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, with_tf32_off],
sample_inputs_func=sample_inputs_linalg_matrix_norm,
),
OpInfo(
"linalg.qr",
aten_name="linalg_qr",
op=torch.linalg.qr,
dtypes=floating_and_complex_types(),
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
# In-place ops
check_batched_gradgrad=False,
sample_inputs_func=sample_inputs_linalg_qr_geqrf,
decorators=[skipCUDAIfNoCusolver, skipCPUIfNoLapack],
),
OpInfo(
"linalg.slogdet",
aten_name="linalg_slogdet",
op=torch.linalg.slogdet,
dtypes=floating_and_complex_types(),
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_linalg_det_logdet_slogdet,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
),
OpInfo(
"linalg.vander",
aten_name="linalg_vander",
ref=np_vander_batched,
op=torch.linalg.vander,
dtypes=all_types_and_complex(),
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
supports_out=False,
sample_inputs_func=sample_inputs_linalg_vander,
),
ReductionOpInfo(
"linalg.vector_norm",
op=torch.linalg.vector_norm,
identity=0,
nan_policy="propagate",
supports_multiple_dims=True,
complex_to_real=True,
supports_forward_ad=True,
# torch.autograd.gradcheck.GradcheckError: While computing batched gradients
# got: Could not allocate memory to change Tensor SizesAndStrides!
check_batched_forward_grad=False,
supports_fwgrad_bwgrad=True,
dtypes=floating_and_complex_types_and(torch.float16, torch.bfloat16),
generate_args_kwargs=sample_kwargs_vector_norm,
aten_name="linalg_vector_norm",
skips=(
# FIXME: sum reduces all dimensions when dim=[]
DecorateInfo(unittest.expectedFailure, "TestReductions", "test_dim_empty"),
DecorateInfo(
unittest.expectedFailure, "TestReductions", "test_dim_empty_keepdim"
),
),
),
OpInfo(
"linalg.lu_factor",
aten_name="linalg_lu_factor",
op=torch.linalg.lu_factor,
dtypes=floating_and_complex_types(),
# Runs very slowly on slow gradcheck - alternatively reduce input sizes
# https://github.com/pytorch/pytorch/issues/80411
gradcheck_fast_mode=True,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_linalg_lu,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
),
OpInfo(
"linalg.lu_factor_ex",
aten_name="linalg_lu_factor_ex",
op=torch.linalg.lu_factor_ex,
dtypes=floating_and_complex_types(),
# https://github.com/pytorch/pytorch/issues/80411
gradcheck_fast_mode=True,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_linalg_lu,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
),
OpInfo(
"linalg.lu",
aten_name="linalg_lu",
op=torch.linalg.lu,
dtypes=floating_and_complex_types(),
# https://github.com/pytorch/pytorch/issues/80411
# Runs very slowly on slow-gradcheck - alternatively reduce input sizes
gradcheck_fast_mode=True,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_linalg_lu,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
),
OpInfo(
"linalg.lu_solve",
op=torch.linalg.lu_solve,
aten_name="linalg_lu_solve",
dtypes=floating_and_complex_types(),
# Runs very slowly on slow gradcheck - alternatively reduce input sizes
gradcheck_fast_mode=True,
supports_forward_ad=True,
check_batched_forward_grad=False,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_lu_solve,
skips=(
DecorateInfo(
unittest.skip("Tests different backward paths"),
"TestCommon",
"test_floating_inputs_are_differentiable",
),
),
decorators=[skipCPUIfNoLapack, skipCUDAIfNoMagmaAndNoCusolver],
),
OpInfo(
"linalg.inv",
aten_name="linalg_inv",
op=torch.linalg.inv,
aliases=("inverse",),
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_invertible,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.inv_ex",
aten_name="linalg_inv_ex",
op=torch.linalg.inv_ex,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_invertible,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.solve",
aten_name="linalg_solve",
op=torch.linalg.solve,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_solve,
# Runs very slowly on slow gradcheck - alternatively reduce input sizes
gradcheck_fast_mode=True,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.solve_ex",
aten_name="linalg_solve_ex",
op=torch.linalg.solve_ex,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_solve,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.solve_triangular",
aten_name="linalg_solve_triangular",
op=torch.linalg.solve_triangular,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_linalg_solve_triangular,
supports_fwgrad_bwgrad=True,
skips=(skipCPUIfNoLapack,),
# linalg.solve_triangular cannot be batched over because of a call to out.copy_(result);
supports_forward_ad=True,
),
OpInfo(
"linalg.matrix_rank",
aten_name="linalg_matrix_rank",
dtypes=floating_and_complex_types(),
supports_autograd=False,
sample_inputs_func=sample_inputs_matrix_rank,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
# jit doesn't accept tensor inputs for matrix rank
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
dtypes=[torch.complex64, torch.float32],
),
),
),
OpInfo(
"linalg.matrix_rank",
aten_name="linalg_matrix_rank",
variant_test_name="hermitian",
dtypes=floating_and_complex_types(),
supports_autograd=False,
sample_inputs_func=sample_inputs_linalg_pinv_hermitian,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.pinv",
aten_name="linalg_pinv",
op=torch.linalg.pinv,
dtypes=floating_and_complex_types(),
# Runs very slowly on slow gradcheck - alternatively reduce input sizes
gradcheck_fast_mode=True,
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_linalg_pinv,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack],
skips=(
# errors with "leaked XXXX bytes CUDA memory on device 0"
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="cuda",
),
),
),
OpInfo(
"linalg.pinv",
aten_name="linalg_pinv",
variant_test_name="singular",
# pinv is Frechet-differentiable in a rank-preserving neighborhood,
# so we feed inputs that are the products of two full-rank factors,
# to avoid any rank changes caused by the perturbations in the gradcheck
op=lambda a, b: torch.linalg.pinv(a @ b.mT),
dtypes=floating_and_complex_types(),
supports_out=False,
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
sample_inputs_func=sample_inputs_linalg_pinv_singular,
# Only large tensors show issues with implicit backward used prior to
# explicit backward implementation.
decorators=[slowTest, skipCUDAIfNoCusolver, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.expectedFailure, "TestJit", "test_variant_consistency_jit"
),
# CUDA runs out of memory
DecorateInfo(
unittest.skip("Skipped!"),
"TestGradients",
"test_fn_fwgrad_bwgrad",
device_type="cuda",
dtypes=[torch.cdouble],
),
# This test takes almost 2 hours to run!
DecorateInfo(
unittest.skip("Skipped!"),
"TestGradients",
"test_fn_gradgrad",
device_type="cuda",
dtypes=[torch.cdouble],
),
),
),
OpInfo(
"linalg.pinv",
aten_name="linalg_pinv",
variant_test_name="hermitian",
dtypes=floating_and_complex_types(),
check_batched_grad=False,
check_batched_gradgrad=False,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
# See https://github.com/pytorch/pytorch/pull/78358
check_batched_forward_grad=False,
sample_inputs_func=sample_inputs_linalg_pinv_hermitian,
gradcheck_wrapper=gradcheck_wrapper_hermitian_input,
decorators=[skipCUDAIfNoMagma, skipCPUIfNoLapack],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.svd",
op=torch.linalg.svd,
aten_name="linalg_svd",
decomp_aten_name="_linalg_svd",
dtypes=floating_and_complex_types(),
# Runs very slowly on slow-gradcheck - alternatively reduce input sizes
gradcheck_fast_mode=True,
supports_fwgrad_bwgrad=True,
supports_forward_ad=True,
check_batched_forward_grad=False,
# We're using at::allclose, which does not have a batching rule
check_batched_grad=False,
check_batched_gradgrad=False,
sample_inputs_func=sample_inputs_svd,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, with_tf32_off],
skips=(
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_out",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestCommon",
"test_variant_consistency_eager",
device_type="mps",
dtypes=[torch.float32],
),
DecorateInfo(
unittest.skip("Skipped!"),
"TestJit",
"test_variant_consistency_jit",
device_type="mps",
dtypes=[torch.float32],
),
),
),
OpInfo(
"linalg.svdvals",
op=torch.linalg.svdvals,
aten_name="linalg_svdvals",
decomp_aten_name="_linalg_svd",
dtypes=floating_and_complex_types(),
check_batched_forward_grad=False,
supports_fwgrad_bwgrad=True,
supports_forward_ad=True,
# We're using at::allclose, which does not have a batching rule
check_batched_gradgrad=False,
sample_inputs_func=sample_inputs_linalg_svdvals,
decorators=[skipCUDAIfNoMagmaAndNoCusolver, skipCPUIfNoLapack, with_tf32_off],
),
OpInfo(
"linalg.tensorinv",
ref=np.linalg.tensorinv,
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_tensorinv,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
# See https://github.com/pytorch/pytorch/pull/78358
check_batched_forward_grad=False,
decorators=[skipCPUIfNoLapack, skipCUDAIfNoMagmaAndNoCusolver],
),
OpInfo(
"linalg.tensorsolve",
ref=lambda a, b, dims=None: np.linalg.tensorsolve(a, b, axes=dims),
dtypes=floating_and_complex_types(),
sample_inputs_func=sample_inputs_tensorsolve,
supports_forward_ad=True,
supports_fwgrad_bwgrad=True,
decorators=[
skipCUDAIfNoMagmaAndNoCusolver,
skipCPUIfNoLapack,
DecorateInfo(
toleranceOverride({torch.float32: tol(atol=1e-03, rtol=1e-03)}),
"TestCommon",
"test_noncontiguous_samples",
device_type="cuda",
),
],
),
]
python_ref_db: List[OpInfo] = [
#
# torch.linalg
#
ReductionPythonRefInfo(
"_refs.linalg.vector_norm",
torch_opinfo_name="linalg.vector_norm",
supports_out=True,
supports_nvfuser=False, # clone_default
op_db=op_db,
),
PythonRefInfo(
"_refs.linalg.matrix_norm",
torch_opinfo_name="linalg.matrix_norm",
supports_out=True,
# Uses svdvals which does not support nvfuser
supports_nvfuser=False,
# Uses vector_norm inside and vector_norm is affected by
# https://github.com/pytorch/pytorch/issues/77216
validate_view_consistency=False,
op_db=op_db,
),
PythonRefInfo(
"_refs.linalg.norm",
torch_opinfo_name="linalg.norm",
supports_out=True,
# Uses svdvals which does not support nvfuser
supports_nvfuser=False,
# Uses vector_norm inside and vector_norm is affected by
# https://github.com/pytorch/pytorch/issues/77216
validate_view_consistency=False,
op_db=op_db,
),
PythonRefInfo(
"_refs.linalg.svd",
torch_opinfo_name="linalg.svd",
supports_out=True,
supports_nvfuser=False,
op_db=op_db,
),
PythonRefInfo(
"_refs.linalg.svdvals",
torch_opinfo_name="linalg.svdvals",
supports_out=True,
supports_nvfuser=False,
op_db=op_db,
),
]
|