_linalg_utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. # mypy: allow-untyped-defs
  2. """Various linear algebra utility methods for internal use."""
  3. import torch
  4. from torch import Tensor
  5. def is_sparse(A):
  6. """Check if tensor A is a sparse COO tensor. All other sparse storage formats (CSR, CSC, etc...) will return False."""
  7. if isinstance(A, torch.Tensor):
  8. return A.layout == torch.sparse_coo
  9. error_str = "expected Tensor"
  10. if not torch.jit.is_scripting():
  11. error_str += f" but got {type(A)}"
  12. raise TypeError(error_str)
  13. def get_floating_dtype(A):
  14. """Return the floating point dtype of tensor A.
  15. Integer types map to float32.
  16. """
  17. dtype = A.dtype
  18. if dtype in (torch.float16, torch.float32, torch.float64):
  19. return dtype
  20. return torch.float32
  21. def matmul(A: Tensor | None, B: Tensor) -> Tensor:
  22. """Multiply two matrices.
  23. If A is None, return B. A can be sparse or dense. B is always
  24. dense.
  25. """
  26. if A is None:
  27. return B
  28. if is_sparse(A):
  29. return torch.sparse.mm(A, B)
  30. return torch.matmul(A, B)
  31. def bform(X: Tensor, A: Tensor | None, Y: Tensor) -> Tensor:
  32. """Return bilinear form of matrices: :math:`X^T A Y`."""
  33. return matmul(X.mT, matmul(A, Y))
  34. def qform(A: Tensor | None, S: Tensor):
  35. """Return quadratic form :math:`S^T A S`."""
  36. return bform(S, A, S)
  37. def basis(A):
  38. """Return orthogonal basis of A columns."""
  39. return torch.linalg.qr(A).Q
  40. def symeig(A: Tensor, largest: bool | None = False) -> tuple[Tensor, Tensor]:
  41. """Return eigenpairs of A with specified ordering."""
  42. if largest is None:
  43. largest = False
  44. E, Z = torch.linalg.eigh(A, UPLO="U")
  45. # assuming that E is ordered
  46. if largest:
  47. E = torch.flip(E, dims=(-1,))
  48. Z = torch.flip(Z, dims=(-1,))
  49. return E, Z
  50. # These functions were deprecated and removed
  51. # This nice error message can be removed in version 1.13+
  52. def matrix_rank(input, tol=None, symmetric=False, *, out=None) -> Tensor:
  53. raise RuntimeError(
  54. "This function was deprecated since version 1.9 and is now removed.\n"
  55. "Please use the `torch.linalg.matrix_rank` function instead. "
  56. "The parameter 'symmetric' was renamed in `torch.linalg.matrix_rank()` to 'hermitian'."
  57. )
  58. def solve(input: Tensor, A: Tensor, *, out=None) -> tuple[Tensor, Tensor]:
  59. raise RuntimeError(
  60. "This function was deprecated since version 1.9 and is now removed. "
  61. "`torch.solve` is deprecated in favor of `torch.linalg.solve`. "
  62. "`torch.linalg.solve` has its arguments reversed and does not return the LU factorization.\n\n"
  63. "To get the LU factorization see `torch.lu`, which can be used with `torch.lu_solve` or `torch.lu_unpack`.\n"
  64. "X = torch.solve(B, A).solution "
  65. "should be replaced with:\n"
  66. "X = torch.linalg.solve(A, B)"
  67. )
  68. def lstsq(input: Tensor, A: Tensor, *, out=None) -> tuple[Tensor, Tensor]:
  69. raise RuntimeError(
  70. "This function was deprecated since version 1.9 and is now removed. "
  71. "`torch.lstsq` is deprecated in favor of `torch.linalg.lstsq`.\n"
  72. "`torch.linalg.lstsq` has reversed arguments and does not return the QR decomposition in "
  73. "the returned tuple (although it returns other information about the problem).\n\n"
  74. "To get the QR decomposition consider using `torch.linalg.qr`.\n\n"
  75. "The returned solution in `torch.lstsq` stored the residuals of the solution in the "
  76. "last m - n columns of the returned value whenever m > n. In torch.linalg.lstsq, "
  77. "the residuals are in the field 'residuals' of the returned named tuple.\n\n"
  78. "The unpacking of the solution, as in\n"
  79. "X, _ = torch.lstsq(B, A).solution[:A.size(1)]\n"
  80. "should be replaced with:\n"
  81. "X = torch.linalg.lstsq(A, B).solution"
  82. )
  83. def _symeig(
  84. input,
  85. eigenvectors=False,
  86. upper=True,
  87. *,
  88. out=None,
  89. ) -> tuple[Tensor, Tensor]:
  90. raise RuntimeError(
  91. "This function was deprecated since version 1.9 and is now removed. "
  92. "The default behavior has changed from using the upper triangular portion of the matrix by default "
  93. "to using the lower triangular portion.\n\n"
  94. "L, _ = torch.symeig(A, upper=upper) "
  95. "should be replaced with:\n"
  96. "L = torch.linalg.eigvalsh(A, UPLO='U' if upper else 'L')\n\n"
  97. "and\n\n"
  98. "L, V = torch.symeig(A, eigenvectors=True) "
  99. "should be replaced with:\n"
  100. "L, V = torch.linalg.eigh(A, UPLO='U' if upper else 'L')"
  101. )
  102. def eig(
  103. self: Tensor,
  104. eigenvectors: bool = False,
  105. *,
  106. e=None,
  107. v=None,
  108. ) -> tuple[Tensor, Tensor]:
  109. raise RuntimeError(
  110. "This function was deprecated since version 1.9 and is now removed. "
  111. "`torch.linalg.eig` returns complex tensors of dtype `cfloat` or `cdouble` rather than real tensors "
  112. "mimicking complex tensors.\n\n"
  113. "L, _ = torch.eig(A) "
  114. "should be replaced with:\n"
  115. "L_complex = torch.linalg.eigvals(A)\n\n"
  116. "and\n\n"
  117. "L, V = torch.eig(A, eigenvectors=True) "
  118. "should be replaced with:\n"
  119. "L_complex, V_complex = torch.linalg.eig(A)"
  120. )