-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathklujax.py
More file actions
2085 lines (1619 loc) · 68.4 KB
/
klujax.py
File metadata and controls
2085 lines (1619 loc) · 68.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""klujax: a KLU solver for JAX."""
# Metadata ============================================================================
__version__ = "0.5.0"
__author__ = "Floris Laporte"
__all__ = [
"analyze",
"coalesce",
"dot",
"factor",
"free_numeric",
"free_symbolic",
"refactor",
"refactor_and_solve",
"solve",
"solve_with_numeric",
"solve_with_symbol",
"tsolve_with_numeric",
"tsolve_with_symbol",
]
# Imports =============================================================================
import contextlib
import os
import sys
from collections.abc import Callable
from types import TracebackType
from typing import Any, Self
import jax
import jax.core
import jax.extend.core
import jax.numpy as jnp
import klujax_cpp # ty: ignore[unresolved-import]
import numpy as np
from jax import lax
from jax.core import ShapedArray
from jax.interpreters import ad, batching, mlir
from jaxtyping import Array
# Config ==============================================================================
DEBUG = bool(int(os.environ.get("KLUJAX_DEBUG", "0")))
jax.config.update(name="jax_enable_x64", val=True)
jax.config.update(name="jax_platform_name", val="cpu")
debug = lambda s: None if not DEBUG else print(s, file=sys.stderr) # noqa: E731,T201
debug("KLUJAX DEBUG MODE.")
# Constants ===========================================================================
COMPLEX_DTYPES = (
np.complex64,
np.complex128,
jnp.complex64,
jnp.complex128,
)
# Main Functions ======================================================================
@jax.jit
def solve(Ai: Array, Aj: Array, Ax: Array, b: Array) -> Array:
"""Solve for x in the sparse linear system Ax=b.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [n_lhs? x n_nz; float64|complex128]: the values of the sparse matrix A
b: [n_lhs? x n_col x n_rhs?; float64|complex128]: the target vector
Returns:
x: the result (x≈A^-1b)
"""
debug("solve")
Ai, Aj, Ax, b, shape = validate_args(Ai, Aj, Ax, b, x_name="b")
if any(x.dtype in COMPLEX_DTYPES for x in (Ax, b)):
debug("solve-complex128")
x = solve_c128.bind(
Ai.astype(jnp.int32),
Aj.astype(jnp.int32),
Ax.astype(jnp.complex128),
b.astype(jnp.complex128),
)
else:
debug("solve-float64")
x = solve_f64.bind(
Ai.astype(jnp.int32),
Aj.astype(jnp.int32),
Ax.astype(jnp.float64),
b.astype(jnp.float64),
)
return x.reshape(*shape)
@jax.jit
def dot(Ai: Array, Aj: Array, Ax: Array, x: Array) -> Array:
"""Multiply a sparse matrix with a vector: Ax=b.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [n_lhs? x n_nz; float64|complex128]: the values of the sparse matrix A
x: [n_lhs? x n_col x n_rhs?; float64|complex128]: the vector multiplied by A
Returns:
b: the result (b=A@x)
"""
debug("dot")
Ai, Aj, Ax, x, shape = validate_args(Ai, Aj, Ax, x, x_name="x")
if any(x.dtype in COMPLEX_DTYPES for x in (Ax, x)):
debug("dot-complex128")
b = dot_c128.bind(
Ai.astype(jnp.int32),
Aj.astype(jnp.int32),
Ax.astype(jnp.complex128),
x.astype(jnp.complex128),
)
else:
debug("dot-float64")
b = dot_f64.bind(
Ai.astype(jnp.int32),
Aj.astype(jnp.int32),
Ax.astype(jnp.float64),
x.astype(jnp.float64),
)
return b.reshape(*shape)
def coalesce(
Ai: Array,
Aj: Array,
Ax: Array,
) -> tuple[Array, Array, Array]:
"""Coalesce a sparse matrix by summing duplicate indices.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [... x n_nz; float64|complex128]: the values of the sparse matrix A
Returns:
coalesced Ai, Aj, Ax
"""
with jax.ensure_compile_time_eval():
shape = Ax.shape
order = jnp.lexsort((Aj, Ai))
Ai = Ai[order]
Aj = Aj[order]
# Compute unique indices
unique_mask = jnp.concatenate(
[jnp.array([True]), (Ai[1:] != Ai[:-1]) | (Aj[1:] != Aj[:-1])],
)
unique_idxs = jnp.where(unique_mask)[0]
# Assign each entry to a unique group
groups = jnp.cumsum(unique_mask) - 1
# Sum Ax values over groups
Ai = Ai[unique_idxs]
Aj = Aj[unique_idxs]
Ax = Ax.reshape(-1, shape[-1])
Ax = Ax[:, order]
Ax = jax.vmap(jax.ops.segment_sum, [0, None], 0)(Ax, groups)
return Ai, Aj, Ax.reshape(*shape[:-1], -1)
# Split Solve pointer management =====================================================
class KLUHandleManager:
"""RAII wrapper for KLU handles. Handles are freed on __del__ or __exit__."""
def __init__(
self,
handle: Array,
free_callable: Callable,
owner: bool = True, # noqa: FBT001, FBT002
) -> None:
self.handle = handle
self.free_callable = free_callable
self._owner = owner
self._freed = False
def close(self) -> None:
"""Release the C++ resource if this instance is the owner."""
# Safety check: If the interpreter is shutting down, 'jax' might be None.
# If so, we can simply return, as the OS will reclaim the memory momentarily.
if jax is None:
return
if self._freed or isinstance(self.handle, jax.core.Tracer):
return
if self._owner and self.free_callable:
with contextlib.suppress(Exception):
self.free_callable(self.handle)
self._freed = True
def __enter__(self) -> Self:
return self
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.close()
def __del__(self) -> None:
if hasattr(self, "close"):
self.close()
def _klu_flatten(obj: KLUHandleManager) -> tuple[tuple[()], tuple[Array, Callable]]:
# No leaves — handle and callable are both static aux data
return (), (obj.handle, obj.free_callable)
def _klu_unflatten(
aux: tuple[Array, Callable], children: tuple[()]
) -> KLUHandleManager:
handle, free_callable = aux
return KLUHandleManager(handle, free_callable=free_callable, owner=False)
jax.tree_util.register_pytree_node(KLUHandleManager, _klu_flatten, _klu_unflatten)
def free_symbolic(symbolic: KLUHandleManager | Array, dependency: Any = None) -> Array: # noqa: ANN401
"""Free the KLU symbolic analysis object.
Args:
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
dependency: [Any]: optional dependency to enforce ordering in JIT
Returns:
result: [int32]: 0 if successful
"""
if isinstance(symbolic, KLUHandleManager):
symbolic.close()
return jnp.array(0, dtype=jnp.int32)
handle = getattr(symbolic, "handle", symbolic)
if isinstance(handle, jax.core.Tracer) and dependency is not None:
token = jax.tree_util.tree_leaves(dependency)[0]
return lax.cond(
jnp.array(True), # noqa: FBT003
lambda ops: free_symbolic_p.bind(ops[0]),
lambda _: jnp.array(0, dtype=jnp.int32),
operand=(handle, token),
)
return free_symbolic_p.bind(handle)
def free_numeric(numeric: KLUHandleManager | Array, dependency: Any = None) -> Array: # noqa: ANN401
"""Free the KLU numeric factorization object.
Args:
numeric: [KLUHandleManager|Array]: the numeric factorization object or handle
dependency: [Any]: optional dependency to enforce ordering in JIT
Returns:
result: [int32]: 0 if successful
"""
if isinstance(numeric, KLUHandleManager):
numeric.close()
return jnp.array(0, dtype=jnp.int32)
handle = getattr(numeric, "handle", numeric)
if isinstance(handle, jax.core.Tracer) and dependency is not None:
token = jax.tree_util.tree_leaves(dependency)[0]
return lax.cond(
jnp.array(True), # noqa: FBT003
lambda ops: free_numeric_p.bind(ops[0]),
lambda _: jnp.array(0, dtype=jnp.int32),
operand=(handle, token),
)
return free_numeric_p.bind(handle)
# Split Solve routines =============================================================
def analyze(Ai: Array, Aj: Array, n_col: int) -> KLUHandleManager:
"""Analyze the sparsity pattern of a matrix A.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
n_col: [int]: the number of columns in the sparse matrix A
Returns:
symbolic: [KLUHandleManager]: the symbolic analysis object
"""
Ai = jnp.asarray(Ai, dtype=jnp.int32)
Aj = jnp.asarray(Aj, dtype=jnp.int32)
raw_symbol = analyze_p.bind(Ai, Aj, jnp.int32(n_col))
return KLUHandleManager(raw_symbol, free_symbolic, owner=True)
def validate_numeric_solve(
Ai: Array, Aj: Array, Ax: Array, b: Array
) -> tuple[Array, Array, Array, Array, tuple[int, ...]]:
"""Reduced set of validate_args for use with solve_with_symbol."""
order = jnp.lexsort((Aj, Ai))
Ai, Aj = Ai[order], Aj[order]
Ax = Ax[..., order] if Ax.ndim == 2 else Ax[order]
shape = b.shape
# 2. Dimension expansion to base case: (n_lhs, n_nz) and (n_lhs, n_col, n_rhs)
if Ax.ndim == 1 and b.ndim == 1:
Ax, b = Ax[None, :], b[None, :, None]
elif Ax.ndim == 1 and b.ndim == 2:
Ax, b = Ax[None, :], b[None, :, :]
elif Ax.ndim == 1 and b.ndim == 3:
Ax = Ax[None, :]
elif Ax.ndim == 2 and b.ndim == 1:
b = b[None, :, None]
shape = (Ax.shape[0], shape[0])
elif Ax.ndim == 2 and b.ndim == 2:
if Ax.shape[0] != b.shape[0] and Ax.shape[0] != 1 and b.shape[0] != 1:
msg = f"Batch mismatch: {Ax.shape=} vs {b.shape=}"
raise ValueError(msg)
b = b[:, :, None]
if b.shape[0] == 1 and Ax.shape[0] > 1:
shape = (Ax.shape[0], *shape[1:])
# 3. Final broadcasting for C++ FFI
n_lhs = max(Ax.shape[0], b.shape[0])
Ax = jnp.broadcast_to(Ax, (n_lhs, Ax.shape[1]))
b = jnp.broadcast_to(b, (n_lhs, b.shape[1], b.shape[2]))
if len(shape) == 3 and shape[0] != b.shape[0]:
shape = (Ax.shape[0], shape[1], shape[2])
return Ai, Aj, Ax, b, shape
@jax.jit
def _solve_with_symbol_jit(
Ai: Array, Aj: Array, Ax: Array, b: Array, sym_h: Array
) -> Array:
# Use the robust validator
Ai, Aj, Ax, b, out_shape = validate_numeric_solve(Ai, Aj, Ax, b)
is_complex = any(x.dtype in COMPLEX_DTYPES for x in (Ax, b))
prim = solve_with_symbol_c128 if is_complex else solve_with_symbol_f64
# Pass standardized arrays to the C++ extension
x = prim.bind(
Ai.astype(jnp.int32),
Aj.astype(jnp.int32),
Ax.astype(jnp.complex128 if is_complex else jnp.float64),
b.astype(jnp.complex128 if is_complex else jnp.float64),
sym_h.astype(jnp.uint64),
)
return x.reshape(*out_shape)
def solve_with_symbol(
Ai: Array, Aj: Array, Ax: Array, b: Array, symbolic: KLUHandleManager | Array
) -> Array:
"""Solve Ax=b using a pre-computed symbolic analysis.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [n_lhs? x n_nz; float64|complex128]: the values of the sparse matrix A
b: [n_lhs? x n_col x n_rhs?; float64|complex128]: the target vector
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
Returns:
x: the result (x≈A^-1b)
"""
handle = getattr(symbolic, "handle", symbolic)
return _solve_with_symbol_jit(Ai, Aj, Ax, b, handle)
@jax.jit
def _tsolve_with_symbol_jit(
Ai: Array, Aj: Array, Ax: Array, b: Array, sym_h: Array
) -> Array:
Ai, Aj, Ax, b, out_shape = validate_numeric_solve(Ai, Aj, Ax, b)
is_complex = any(x.dtype in COMPLEX_DTYPES for x in (Ax, b))
prim = tsolve_with_symbol_c128 if is_complex else tsolve_with_symbol_f64
x = prim.bind(
Ai.astype(jnp.int32),
Aj.astype(jnp.int32),
Ax.astype(jnp.complex128 if is_complex else jnp.float64),
b.astype(jnp.complex128 if is_complex else jnp.float64),
sym_h.astype(jnp.uint64),
)
return x.reshape(*out_shape)
def tsolve_with_symbol(
Ai: Array, Aj: Array, Ax: Array, b: Array, symbolic: KLUHandleManager | Array
) -> Array:
"""Solve A^T x=b (transpose solve) using a pre-computed symbolic analysis.
Factors A numerically, then solves the transposed system using klu_tsolve.
The symbolic handle describes the sparsity pattern of A (not A^T), and is
reused as-is — KLU's triangular transpose solver handles the direction internally.
For complex matrices, this solves A^T x = b (plain transpose, not conjugate).
Use the conjugate transpose if you need A^H x = b.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [n_lhs? x n_nz; float64|complex128]: the values of the sparse matrix A
b: [n_lhs? x n_col x n_rhs?; float64|complex128]: the target vector
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
Returns:
x: the result (x≈(A^T)^-1 b)
"""
handle = getattr(symbolic, "handle", symbolic)
return _tsolve_with_symbol_jit(Ai, Aj, Ax, b, handle)
@jax.jit
def _factor_jit(Ai: Array, Aj: Array, Ax: Array, sym_h: Array) -> Array:
dummy_b = jnp.zeros((1,), dtype=Ax.dtype)
Ai, Aj, Ax, _, _ = validate_args(Ai, Aj, Ax, dummy_b)
prim = factor_c128 if Ax.dtype in COMPLEX_DTYPES else factor_f64
return prim.bind(Ai.astype(jnp.int32), Aj.astype(jnp.int32), Ax, sym_h)
def factor(
Ai: Array, Aj: Array, Ax: Array, symbolic: KLUHandleManager | Array
) -> KLUHandleManager:
"""Compute the numeric factorization of a matrix A given its symbolic analysis.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [n_lhs? x n_nz; float64|complex128]: the values of the sparse matrix A
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
Returns:
numeric: [KLUHandleManager]: the numeric factorization object
"""
sym_h = getattr(symbolic, "handle", symbolic)
raw_numeric = _factor_jit(Ai, Aj, Ax, sym_h)
return KLUHandleManager(raw_numeric, free_numeric, owner=True)
@jax.jit
def _refactor_jit(Ai: Array, Aj: Array, Ax: Array, sym_h: Array, num_h: Array) -> Array:
dummy_b = jnp.zeros((1,), dtype=Ax.dtype)
Ai, Aj, Ax, _, _ = validate_args(Ai, Aj, Ax, dummy_b)
prim = refactor_c128 if Ax.dtype in COMPLEX_DTYPES else refactor_f64
return prim.bind(Ai.astype(jnp.int32), Aj.astype(jnp.int32), Ax, sym_h, num_h)
def refactor(
Ai: Array,
Aj: Array,
Ax: Array,
numeric: KLUHandleManager | Array,
symbolic: KLUHandleManager | Array,
) -> KLUHandleManager:
"""Re-factorize matrix A numerically, reusing the symbolic analysis.
Use when the sparsity pattern is unchanged but values have changed.
Modifies the numeric factorization in-place. Faster than calling factor().
Returns a KLUHandleManager holding the same underlying pointer as the input
numeric handle. The returned handle must be threaded into subsequent
solve_with_numeric calls so that XLA/JAX sees the dependency edge:
factor → refactor → solve.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [n_lhs? x n_nz; float64|complex128]: the values of the sparse matrix A
numeric: [KLUHandleManager|Array]: existing numeric factorization
(modified in-place)
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
Returns:
numeric: [KLUHandleManager]: the updated numeric handle
(same pointer, for XLA dep tracking)
"""
num_h = getattr(numeric, "handle", numeric)
sym_h = getattr(symbolic, "handle", symbolic)
raw_handle = _refactor_jit(Ai, Aj, Ax, sym_h, num_h)
return KLUHandleManager(raw_handle, free_numeric, owner=False)
@jax.jit
def _solve_with_numeric_jit(num_h: Array, b: Array, sym_h: Array) -> Array:
prim = (
solve_with_numeric_c128 if b.dtype in COMPLEX_DTYPES else solve_with_numeric_f64
)
return prim.bind(sym_h.astype(jnp.uint64), num_h.astype(jnp.uint64), b)
def solve_with_numeric(
numeric: KLUHandleManager | Array,
b: Array,
symbolic: KLUHandleManager | Array,
) -> Array:
"""Solve Ax=b using a pre-computed numeric factorization.
Args:
numeric: [KLUHandleManager|Array]: the numeric factorization object or handle
b: [n_lhs? x n_col x n_rhs?; float64|complex128]: the target vector
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
Returns:
x: the result (x≈A^-1b)
"""
num_h = getattr(numeric, "handle", numeric)
sym_h = getattr(symbolic, "handle", symbolic)
result = _solve_with_numeric_jit(num_h, b, sym_h)
# Auto-cleanup if the handle was created inside a JIT block.
if isinstance(num_h, jax.core.Tracer) and isinstance(numeric, KLUHandleManager):
free_numeric(numeric, dependency=result)
return result
@jax.jit
def _tsolve_with_numeric_jit(num_h: Array, b: Array, sym_h: Array) -> Array:
prim = (
tsolve_with_numeric_c128
if b.dtype in COMPLEX_DTYPES
else tsolve_with_numeric_f64
)
return prim.bind(sym_h.astype(jnp.uint64), num_h.astype(jnp.uint64), b)
def tsolve_with_numeric(
numeric: KLUHandleManager | Array,
b: Array,
symbolic: KLUHandleManager | Array,
) -> Array:
"""Solve A^T x=b (transpose solve) using a pre-computed numeric factorization.
Uses klu_tsolve internally. The numeric factorization must have been computed
for A (not A^T); KLU handles the transposition during the triangular solve.
For complex matrices, this solves A^T x = b (plain transpose, not conjugate).
Args:
numeric: [KLUHandleManager|Array]: the numeric factorization object or handle
b: [n_lhs? x n_col x n_rhs?; float64|complex128]: the target vector
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
Returns:
x: the result (x≈(A^T)^-1 b)
"""
num_h = getattr(numeric, "handle", numeric)
sym_h = getattr(symbolic, "handle", symbolic)
result = _tsolve_with_numeric_jit(num_h, b, sym_h)
if isinstance(num_h, jax.core.Tracer) and isinstance(numeric, KLUHandleManager):
free_numeric(numeric, dependency=result)
return result
@jax.jit
def _refactor_and_solve_jit(
Ai: Array, Aj: Array, Ax: Array, b: Array, sym_h: Array, num_h: Array
) -> tuple[Array, Array]:
# Use validate_numeric_solve to standardize shapes and get the expected out_shape
Ai, Aj, Ax, b, out_shape = validate_numeric_solve(Ai, Aj, Ax, b)
is_complex = any(x.dtype in COMPLEX_DTYPES for x in (Ax, b))
prim = refactor_and_solve_c128 if is_complex else refactor_and_solve_f64
x, out_num = prim.bind(
Ai.astype(jnp.int32),
Aj.astype(jnp.int32),
Ax.astype(jnp.complex128 if is_complex else jnp.float64),
b.astype(jnp.complex128 if is_complex else jnp.float64),
sym_h.astype(jnp.uint64),
num_h.astype(jnp.uint64),
)
# Reshape x back to the original dimensions of b
return x.reshape(*out_shape), out_num
def refactor_and_solve(
Ai: Array,
Aj: Array,
Ax: Array,
b: Array,
numeric: KLUHandleManager | Array,
symbolic: KLUHandleManager | Array,
) -> tuple[Array, KLUHandleManager]:
"""Fused in-place refactorization followed by triangular solve.
Equivalent to calling refactor() then solve_with_numeric(), but executes as a
single C++ kernel call. This avoids allocating the COO→CSC work buffer twice
and saves a JAX dispatch round-trip, which matters in tight iteration loops.
The numeric factorization is modified in-place (same behaviour as refactor()).
The returned KLUHandleManager wraps the same underlying pointer as the input
numeric handle with owner=False — the original owner is still responsible for
calling free_numeric.
Args:
Ai: [n_nz; int32]: the row indices of the sparse matrix A
Aj: [n_nz; int32]: the column indices of the sparse matrix A
Ax: [n_lhs? x n_nz; float64|complex128]: the values of the sparse matrix A
b: [n_lhs? x n_col x n_rhs?; float64|complex128]: the right-hand side
numeric: [KLUHandleManager|Array]: existing numeric factorization
(modified in-place)
symbolic: [KLUHandleManager|Array]: the symbolic analysis object or handle
Returns:
(x, numeric): solution array and the updated numeric handle
(same pointer as input, owner=False, for XLA dep tracking)
"""
num_h = getattr(numeric, "handle", numeric)
sym_h = getattr(symbolic, "handle", symbolic)
x, raw_numeric = _refactor_and_solve_jit(Ai, Aj, Ax, b, sym_h, num_h)
return x, KLUHandleManager(raw_numeric, free_numeric, owner=False)
# Primitives ==========================================================================
dot_f64 = jax.extend.core.Primitive("dot_f64")
dot_c128 = jax.extend.core.Primitive("dot_c128")
solve_f64 = jax.extend.core.Primitive("solve_f64")
solve_c128 = jax.extend.core.Primitive("solve_c128")
analyze_p = jax.extend.core.Primitive("analyze")
solve_with_symbol_f64 = jax.extend.core.Primitive("solve_with_symbol_f64")
solve_with_symbol_c128 = jax.extend.core.Primitive("solve_with_symbol_c128")
tsolve_with_symbol_f64 = jax.extend.core.Primitive("tsolve_with_symbol_f64")
tsolve_with_symbol_c128 = jax.extend.core.Primitive("tsolve_with_symbol_c128")
free_symbolic_p = jax.extend.core.Primitive("free_symbolic")
factor_f64 = jax.extend.core.Primitive("factor_f64")
factor_c128 = jax.extend.core.Primitive("factor_c128")
solve_with_numeric_f64 = jax.extend.core.Primitive("solve_with_numeric_f64")
solve_with_numeric_c128 = jax.extend.core.Primitive("solve_with_numeric_c128")
tsolve_with_numeric_f64 = jax.extend.core.Primitive("tsolve_with_numeric_f64")
tsolve_with_numeric_c128 = jax.extend.core.Primitive("tsolve_with_numeric_c128")
free_numeric_p = jax.extend.core.Primitive("free_numeric")
refactor_f64 = jax.extend.core.Primitive("refactor_f64")
refactor_c128 = jax.extend.core.Primitive("refactor_c128")
refactor_and_solve_f64 = jax.extend.core.Primitive("refactor_and_solve_f64")
refactor_and_solve_c128 = jax.extend.core.Primitive("refactor_and_solve_c128")
refactor_and_solve_f64.multiple_results = True
refactor_and_solve_c128.multiple_results = True
# Implementations ========================================================
@dot_f64.def_impl
def dot_f64_impl(Ai: Array, Aj: Array, Ax: Array, x: Array) -> Array:
return general_impl("dot_f64", Ai, Aj, Ax, x)
@dot_c128.def_impl
def dot_c128_impl(Ai: Array, Aj: Array, Ax: Array, x: Array) -> Array:
return general_impl("dot_c128", Ai, Aj, Ax, x)
@solve_f64.def_impl
def solve_f64_impl(Ai: Array, Aj: Array, Ax: Array, x: Array) -> Array:
return general_impl("solve_f64", Ai, Aj, Ax, x)
@solve_c128.def_impl
def solve_c128_impl(Ai: Array, Aj: Array, Ax: Array, x: Array) -> Array:
return general_impl("solve_c128", Ai, Aj, Ax, x)
@solve_with_symbol_f64.def_impl
def solve_with_symbol_f64_impl(
Ai: Array, Aj: Array, Ax: Array, b: Array, symbolic: Array
) -> Array:
return general_impl("solve_with_symbol_f64", Ai, Aj, Ax, b, symbolic)
@solve_with_symbol_c128.def_impl
def solve_with_symbol_c128_impl(
Ai: Array, Aj: Array, Ax: Array, b: Array, symbolic: Array
) -> Array:
return general_impl("solve_with_symbol_c128", Ai, Aj, Ax, b, symbolic)
@tsolve_with_symbol_f64.def_impl
def tsolve_with_symbol_f64_impl(
Ai: Array, Aj: Array, Ax: Array, b: Array, symbolic: Array
) -> Array:
return general_impl("tsolve_with_symbol_f64", Ai, Aj, Ax, b, symbolic)
@tsolve_with_symbol_c128.def_impl
def tsolve_with_symbol_c128_impl(
Ai: Array, Aj: Array, Ax: Array, b: Array, symbolic: Array
) -> Array:
return general_impl("tsolve_with_symbol_c128", Ai, Aj, Ax, b, symbolic)
@analyze_p.def_impl
def analyze_impl(Ai: Array, Aj: Array, n_col: Array) -> Array:
return jax.ffi.ffi_call("analyze", ShapedArray((), jnp.uint64))(Ai, Aj, n_col)
@factor_f64.def_impl
def factor_f64_impl(Ai, Aj, Ax, symbolic):
n_lhs = Ax.shape[0]
call = jax.ffi.ffi_call("factor_f64", jax.ShapeDtypeStruct((n_lhs,), jnp.uint64))
return call(Ai, Aj, Ax, symbolic)
@factor_c128.def_impl
def factor_c128_impl(Ai, Aj, Ax, symbolic):
n_lhs = Ax.shape[0]
call = jax.ffi.ffi_call("factor_c128", jax.ShapeDtypeStruct((n_lhs,), jnp.uint64))
return call(Ai, Aj, Ax, symbolic)
@refactor_f64.def_impl
def refactor_f64_impl(Ai, Aj, Ax, symbolic, numeric):
n_lhs = Ax.shape[0]
call = jax.ffi.ffi_call("refactor_f64", jax.ShapeDtypeStruct((n_lhs,), jnp.uint64))
return call(Ai, Aj, Ax, symbolic, numeric)
@refactor_c128.def_impl
def refactor_c128_impl(Ai, Aj, Ax, symbolic, numeric):
n_lhs = Ax.shape[0]
call = jax.ffi.ffi_call("refactor_c128", jax.ShapeDtypeStruct((n_lhs,), jnp.uint64))
return call(Ai, Aj, Ax, symbolic, numeric)
@solve_with_numeric_f64.def_impl
def solve_with_numeric_f64_impl(symbolic, numeric, b):
call = jax.ffi.ffi_call(
"solve_with_numeric_f64", jax.ShapeDtypeStruct(b.shape, b.dtype)
)
return call(symbolic, numeric, b)
@solve_with_numeric_c128.def_impl
def solve_with_numeric_c128_impl(symbolic, numeric, b):
call = jax.ffi.ffi_call(
"solve_with_numeric_c128", jax.ShapeDtypeStruct(b.shape, b.dtype)
)
return call(symbolic, numeric, b)
@tsolve_with_numeric_f64.def_impl
def tsolve_with_numeric_f64_impl(symbolic, numeric, b):
call = jax.ffi.ffi_call(
"tsolve_with_numeric_f64", jax.ShapeDtypeStruct(b.shape, b.dtype)
)
return call(symbolic, numeric, b)
@tsolve_with_numeric_c128.def_impl
def tsolve_with_numeric_c128_impl(symbolic, numeric, b):
call = jax.ffi.ffi_call(
"tsolve_with_numeric_c128", jax.ShapeDtypeStruct(b.shape, b.dtype)
)
return call(symbolic, numeric, b)
@refactor_and_solve_f64.def_impl
def refactor_and_solve_f64_impl(Ai, Aj, Ax, b, symbolic, numeric):
n_lhs = Ax.shape[0]
call = jax.ffi.ffi_call(
"refactor_and_solve_f64",
(
jax.ShapeDtypeStruct(b.shape, b.dtype),
jax.ShapeDtypeStruct((n_lhs,), jnp.uint64),
),
)
return call(Ai, Aj, Ax, b, symbolic, numeric)
@refactor_and_solve_c128.def_impl
def refactor_and_solve_c128_impl(Ai, Aj, Ax, b, symbolic, numeric):
n_lhs = Ax.shape[0]
call = jax.ffi.ffi_call(
"refactor_and_solve_c128",
(
jax.ShapeDtypeStruct(b.shape, b.dtype),
jax.ShapeDtypeStruct((n_lhs,), jnp.uint64),
),
)
return call(Ai, Aj, Ax, b, symbolic, numeric)
def general_impl(
name: str, Ai: Array, Aj: Array, Ax: Array, x: Array, *args: Array
) -> Array:
call = jax.ffi.ffi_call(
name,
jax.ShapeDtypeStruct(x.shape, x.dtype),
)
if not callable(call):
msg = "jax.ffi.ffi_call did not return a callable."
raise RuntimeError(msg) # noqa: TRY004
return call(Ai, Aj, Ax, x, *args)
# Lowerings ===========================================================================
jax.ffi.register_ffi_target(
"dot_f64",
klujax_cpp.dot_f64(),
platform="cpu",
)
dot_f64_low = mlir.lower_fun(dot_f64_impl, multiple_results=False)
mlir.register_lowering(dot_f64, dot_f64_low)
jax.ffi.register_ffi_target(
"dot_c128",
klujax_cpp.dot_c128(),
platform="cpu",
)
dot_c128_low = mlir.lower_fun(dot_c128_impl, multiple_results=False)
mlir.register_lowering(dot_c128, dot_c128_low)
jax.ffi.register_ffi_target(
"solve_f64",
klujax_cpp.solve_f64(),
platform="cpu",
)
solve_f64_low = mlir.lower_fun(solve_f64_impl, multiple_results=False)
mlir.register_lowering(solve_f64, solve_f64_low)
jax.ffi.register_ffi_target(
"solve_c128",
klujax_cpp.solve_c128(),
platform="cpu",
)
solve_c128_low = mlir.lower_fun(solve_c128_impl, multiple_results=False)
mlir.register_lowering(solve_c128, solve_c128_low)
jax.ffi.register_ffi_target(
"analyze",
klujax_cpp.analyze(),
platform="cpu",
)
analyze_low = mlir.lower_fun(analyze_impl, multiple_results=False)
mlir.register_lowering(analyze_p, analyze_low)
jax.ffi.register_ffi_target(
"solve_with_symbol_f64",
klujax_cpp.solve_with_symbol_f64(),
platform="cpu",
)
solve_with_symbol_f64_low = mlir.lower_fun(
solve_with_symbol_f64_impl, multiple_results=False
)
mlir.register_lowering(solve_with_symbol_f64, solve_with_symbol_f64_low)
jax.ffi.register_ffi_target(
"solve_with_symbol_c128",
klujax_cpp.solve_with_symbol_c128(),
platform="cpu",
)
solve_with_symbol_c128_low = mlir.lower_fun(
solve_with_symbol_c128_impl, multiple_results=False
)
mlir.register_lowering(solve_with_symbol_c128, solve_with_symbol_c128_low)
jax.ffi.register_ffi_target(
"tsolve_with_symbol_f64",
klujax_cpp.tsolve_with_symbol_f64(),
platform="cpu",
)
tsolve_with_symbol_f64_low = mlir.lower_fun(
tsolve_with_symbol_f64_impl, multiple_results=False
)
mlir.register_lowering(tsolve_with_symbol_f64, tsolve_with_symbol_f64_low)
jax.ffi.register_ffi_target(
"tsolve_with_symbol_c128",
klujax_cpp.tsolve_with_symbol_c128(),
platform="cpu",
)
tsolve_with_symbol_c128_low = mlir.lower_fun(
tsolve_with_symbol_c128_impl, multiple_results=False
)
mlir.register_lowering(tsolve_with_symbol_c128, tsolve_with_symbol_c128_low)
jax.ffi.register_ffi_target(
"free_symbolic",
klujax_cpp.free_symbolic(),
platform="cpu",
)
jax.ffi.register_ffi_target(
"free_numeric",
klujax_cpp.free_numeric(),
platform="cpu",
)
@free_numeric_p.def_impl
def free_numeric_impl(numeric):
call = jax.ffi.ffi_call("free_numeric", jax.ShapeDtypeStruct((), jnp.int32))
return call(numeric)
@free_symbolic_p.def_impl
def free_symbolic_impl(symbolic):
call = jax.ffi.ffi_call("free_symbolic", jax.ShapeDtypeStruct((), jnp.int32))
return call(symbolic)
@free_numeric_p.def_abstract_eval
def free_numeric_abstract_eval(numeric):
return ShapedArray((), jnp.int32)
jax.ffi.register_ffi_target("factor_f64", klujax_cpp.factor_f64(), platform="cpu")
factor_f64_low = mlir.lower_fun(factor_f64_impl, multiple_results=False)
mlir.register_lowering(factor_f64, factor_f64_low)
jax.ffi.register_ffi_target("factor_c128", klujax_cpp.factor_c128(), platform="cpu")
factor_c128_low = mlir.lower_fun(factor_c128_impl, multiple_results=False)
mlir.register_lowering(factor_c128, factor_c128_low)
jax.ffi.register_ffi_target("refactor_f64", klujax_cpp.refactor_f64(), platform="cpu")
refactor_f64_low = mlir.lower_fun(refactor_f64_impl, multiple_results=False)
mlir.register_lowering(refactor_f64, refactor_f64_low)
jax.ffi.register_ffi_target("refactor_c128", klujax_cpp.refactor_c128(), platform="cpu")
refactor_c128_low = mlir.lower_fun(refactor_c128_impl, multiple_results=False)
mlir.register_lowering(refactor_c128, refactor_c128_low)
jax.ffi.register_ffi_target(
"solve_with_numeric_f64", klujax_cpp.solve_with_numeric_f64(), platform="cpu"
)
solve_with_numeric_f64_low = mlir.lower_fun(
solve_with_numeric_f64_impl, multiple_results=False
)
mlir.register_lowering(solve_with_numeric_f64, solve_with_numeric_f64_low)
jax.ffi.register_ffi_target(
"solve_with_numeric_c128", klujax_cpp.solve_with_numeric_c128(), platform="cpu"
)
solve_with_numeric_c128_low = mlir.lower_fun(
solve_with_numeric_c128_impl, multiple_results=False
)
mlir.register_lowering(solve_with_numeric_c128, solve_with_numeric_c128_low)
jax.ffi.register_ffi_target(
"tsolve_with_numeric_f64", klujax_cpp.tsolve_with_numeric_f64(), platform="cpu"
)
tsolve_with_numeric_f64_low = mlir.lower_fun(
tsolve_with_numeric_f64_impl, multiple_results=False
)
mlir.register_lowering(tsolve_with_numeric_f64, tsolve_with_numeric_f64_low)
jax.ffi.register_ffi_target(
"tsolve_with_numeric_c128", klujax_cpp.tsolve_with_numeric_c128(), platform="cpu"
)
tsolve_with_numeric_c128_low = mlir.lower_fun(
tsolve_with_numeric_c128_impl, multiple_results=False
)
mlir.register_lowering(tsolve_with_numeric_c128, tsolve_with_numeric_c128_low)