Coverage for src/bartz/_jaxext/_linalg.py: 96%
56 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-30 12:50 +0000
1# bartz/src/bartz/_jaxext/_linalg.py
2#
3# Copyright (c) 2026, The Bartz Contributors
4#
5# This file is part of bartz.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in all
15# copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
25"""Cholesky and triangular solve, unrolled for small matrices."""
27from typing import Literal
29from jax import numpy as jnp
30from jax.scipy.linalg import solve_triangular as library_solve_triangular # noqa: TID251
31from jaxtyping import Array, Float
33# largest matrix size handled by the unrolled implementations; above this, the
34# unrolled code is still faster at runtime in some configurations, but it gets
35# slow to compile. Empty matrices go to the library too.
36UNROLL_MAX_SIZE = 4
39def cholesky(a: Float[Array, '*batch k k']) -> Float[Array, '*batch k k']:
40 """Lower Cholesky factor, like `jax.numpy.linalg.cholesky`."""
41 *_, k, _ = a.shape
42 if 0 < k <= UNROLL_MAX_SIZE:
43 return cholesky_unrolled(a)
44 else:
45 return jnp.linalg.cholesky(a) # noqa: TID251
48def solve_triangular(
49 a: Float[Array, '*batch_a k k'],
50 b: Float[Array, '*batch_b k n'],
51 *,
52 trans: Literal[0, 1, 'N', 'T'] = 0,
53 lower: bool = False,
54) -> Float[Array, '*batch k n']:
55 """Solve a triangular system, like `jax.scipy.linalg.solve_triangular`."""
56 *_, k, _ = a.shape
57 if 0 < k <= UNROLL_MAX_SIZE:
58 return solve_triangular_unrolled(a, b, trans=trans, lower=lower)
59 else:
60 # WORKAROUND(jax<0.10.0): the library does not broadcast batch axes
61 batch = jnp.broadcast_shapes(a.shape[:-2], b.shape[:-2])
62 a = jnp.broadcast_to(a, (*batch, *a.shape[-2:]))
63 b = jnp.broadcast_to(b, (*batch, *b.shape[-2:]))
64 return library_solve_triangular(a, b, trans=trans, lower=lower)
67def cholesky_unrolled(a: Float[Array, '*batch k k']) -> Float[Array, '*batch k k']:
68 """Unrolled `cholesky`."""
69 *_, k, _ = a.shape
70 L = {}
71 pivots = []
72 for j in range(k):
73 pivot = a[..., j, j]
74 for m in range(j):
75 pivot -= jnp.square(L[j, m])
76 pivots.append(pivot)
77 L[j, j] = jnp.sqrt(pivot)
78 inv_diag = jnp.reciprocal(L[j, j])
79 for i in range(j + 1, k):
80 # symmetrize like the library
81 x = 0.5 * (a[..., i, j] + a[..., j, i])
82 for m in range(j):
83 x -= L[i, m] * L[j, m]
84 L[i, j] = x * inv_diag
86 zero = jnp.zeros_like(a[..., 0, 0])
87 rows = [jnp.stack([L.get((i, j), zero) for j in range(k)], -1) for i in range(k)]
88 out = jnp.stack(rows, -2)
89 # like the library, fill the lower triangle with nan if not positive definite
90 ok = jnp.all(jnp.stack(pivots) > 0, axis=0)
91 keep = ok[..., None, None] | ~jnp.tri(k, dtype=bool)
92 return jnp.where(keep, out, jnp.nan)
95def solve_triangular_unrolled(
96 a: Float[Array, '*batch_a k k'],
97 b: Float[Array, '*batch_b k n'],
98 *,
99 trans: Literal[0, 1, 'N', 'T'] = 0,
100 lower: bool = False,
101) -> Float[Array, '*batch k n']:
102 """Unrolled `solve_triangular`."""
103 if trans in (1, 'T'):
104 a = a.mT
105 lower = not lower
106 elif trans not in (0, 'N'): 106 ↛ 107line 106 didn't jump to line 107 because the condition on line 106 was never true
107 msg = f'invalid {trans=}'
108 raise ValueError(msg)
110 *_, k, _ = a.shape
111 order = range(k) if lower else range(k - 1, -1, -1)
112 x = {}
113 for i in order:
114 xi = b[..., i, :]
115 for m, xm in x.items():
116 xi -= a[..., i, m, None] * xm
117 x[i] = xi / a[..., i, i, None]
118 return jnp.stack([x[i] for i in range(k)], -2)