_linalg_utils.py 5.0 KB

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