Skip to content

Commit 1192657

Browse files
Address PR review: improve cholesky comment and add upper=true test
- Reword THSTensor_cholesky comment to clarify we use the default lower-triangular form and conjugate-transpose for upper=true - Add CholeskyUpperTest to validate upper=true path after migration from deprecated torch::cholesky to torch::linalg_cholesky Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 5d56600 commit 1192657

2 files changed

Lines changed: 16 additions & 1 deletion

File tree

src/Native/LibTorchSharp/THSLinearAlgebra.cpp

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,8 @@ Tensor THSLinalg_lu_solve(const Tensor B, const Tensor LU, const Tensor pivots,
359359
Tensor THSTensor_cholesky(const Tensor tensor, const bool upper)
360360
{
361361
// torch::cholesky is deprecated in favor of torch::linalg_cholesky.
362-
// linalg_cholesky always returns lower-triangular; use .mH() for upper.
362+
// Here we call torch::linalg_cholesky with its default (lower-triangular) output,
363+
// and return its conjugate transpose via .mH() when upper is true.
363364
CATCH_TENSOR(upper ? torch::linalg_cholesky(*tensor).mH() : torch::linalg_cholesky(*tensor))
364365
}
365366

test/TorchSharpTest/LinearAlgebra.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,20 @@ public void CholeskyTest()
305305
Assert.True(a.allclose(l.matmul(l.swapaxes(-2, -1)))); // Worked this in to get it tested. Alias for 'transpose'
306306
}
307307

308+
[Fact]
309+
[TestOf(nameof(Tensor.cholesky))]
310+
public void CholeskyUpperTest()
311+
{
312+
var a = randn(new long[] { 3, 2, 2 }, float64);
313+
a = a.matmul(a.swapdims(-2, -1));
314+
#pragma warning disable CS0618 // Obsolete
315+
var u = a.cholesky(upper: true);
316+
#pragma warning restore CS0618
317+
318+
// U should be upper-triangular: U^T * U == A
319+
Assert.True(a.allclose(u.swapaxes(-2, -1).matmul(u)));
320+
}
321+
308322
[Fact]
309323
[TestOf(nameof(linalg.cholesky_ex))]
310324
public void CholeskyExTest()

0 commit comments

Comments
 (0)