|
| 1 | +# Copyright (c) Facebook, Inc. and its affiliates. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the BSD-style license found in the |
| 5 | +# LICENSE file in the root directory of this source tree. |
| 6 | + |
| 7 | +from typing import Tuple |
| 8 | + |
| 9 | +import torch |
| 10 | + |
| 11 | + |
| 12 | +""" |
| 13 | +Some functions which depend on PyTorch versions. |
| 14 | +""" |
| 15 | + |
| 16 | + |
| 17 | +def solve(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor: # pragma: no cover |
| 18 | + """ |
| 19 | + Like torch.linalg.solve, tries to return X |
| 20 | + such that AX=B, with A square. |
| 21 | + """ |
| 22 | + if hasattr(torch.linalg, "solve"): |
| 23 | + # PyTorch version >= 1.8.0 |
| 24 | + return torch.linalg.solve(A, B) |
| 25 | + |
| 26 | + return torch.solve(B, A).solution |
| 27 | + |
| 28 | + |
| 29 | +def lstsq(A: torch.Tensor, B: torch.Tensor) -> torch.Tensor: # pragma: no cover |
| 30 | + """ |
| 31 | + Like torch.linalg.lstsq, tries to return X |
| 32 | + such that AX=B. |
| 33 | + """ |
| 34 | + if hasattr(torch.linalg, "lstsq"): |
| 35 | + # PyTorch version >= 1.9 |
| 36 | + return torch.linalg.lstsq(A, B).solution |
| 37 | + |
| 38 | + solution = torch.lstsq(B, A).solution |
| 39 | + if A.shape[1] < A.shape[0]: |
| 40 | + return solution[: A.shape[1]] |
| 41 | + return solution |
| 42 | + |
| 43 | + |
| 44 | +def qr(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # pragma: no cover |
| 45 | + """ |
| 46 | + Like torch.linalg.qr. |
| 47 | + """ |
| 48 | + if hasattr(torch.linalg, "qr"): |
| 49 | + # PyTorch version >= 1.9 |
| 50 | + return torch.linalg.qr(A) |
| 51 | + return torch.qr(A) |
0 commit comments