Skip to main content

ruxla_prims/
linalg.rs

1//! Linear algebra, following JAX's `jax._src.lax.linalg`: `cholesky`,
2//! `triangular_solve`, `lu`, `lu_pivots_to_permutation`, `qr`, `eigh`,
3//! `svd`, `eig`, `schur`, `hessenberg`, `householder_product`, `ormqr`,
4//! `tridiagonal`, `tridiagonal_solve`, `cholesky_update`, and
5//! `symmetric_product`.
6//!
7//! Every primitive takes batches of matrices (`[..., m, n]`, the batch
8//! dimensions first) of `f32`, `f64`, `c64`, or `c128` (the eigenvalues of
9//! `eigh` and the singular values of `svd` are real). The kernels are in
10//! `ruxla_kernels::linalg`; the lowering is in `linalg_lower`, the
11//! differentiation rules in `linalg_ad`.
12
13use ruxla_ir::ad::{AdCx, Tangent, TransposeInput};
14use ruxla_ir::batching::{BatchCx, Batched};
15use ruxla_ir::lowering::{HloValue, LowerCx, Platform, Target, i64_array};
16use ruxla_ir::{
17    AVal, Atom, DType, EighImplementation, Error, EvalCx, HostArray, Params, Prim, Primitive,
18    Result, SvdAlgorithm,
19};
20use ruxla_kernels::linalg::{self as k, TriangularSolveOptions};
21use ruxla_kernels::{Buffer, Value};
22
23use crate::batching::{self as b, bdim_at_front};
24use crate::linalg_ad as lad;
25use crate::linalg_lower::{
26    Abi, FfiCall, abi, conj_hlo, eigh_phases, eye, ffi_call, info_aval, info_ok, lapack_target,
27    lower_pivots_to_permutation, replace_not_ok_with_nan, slice_to, svd_phases, transpose_last,
28    tri_mask, triu,
29};
30use crate::structural::RESHAPE;
31use crate::util::{arity, no_params, wrong_params};
32
33/// Evaluates `$body` with `$v` bound to the elements of a buffer of
34/// linear algebra and `$t` to their type (`f32`, `f64`, `c64`, or `c128`).
35macro_rules! with_float {
36    ($prim:expr, $x:expr, |$v:ident: $t:ident| $body:expr) => {
37        match $x.buffer() {
38            Buffer::F32($v) => {
39                type $t = f32;
40                $body
41            }
42            Buffer::F64($v) => {
43                type $t = f64;
44                $body
45            }
46            Buffer::C64($v) => {
47                type $t = ruxla_kernels::c64;
48                $body
49            }
50            Buffer::C128($v) => {
51                type $t = ruxla_kernels::c128;
52                $body
53            }
54            _ => return Err(not_float($prim, &$x.aval())),
55        }
56    };
57}
58
59fn not_float(prim: &'static str, a: &AVal) -> Error {
60    Error::type_error(
61        prim,
62        format!("expected f32, f64, c64, or c128 matrices, got {a}"),
63    )
64}
65
66/// Checks a batch of `f32`, `f64`, `c64`, or `c128` matrices and returns
67/// the batch dimensions and the matrix size.
68fn matrices(prim: &'static str, a: &AVal) -> Result<(Vec<usize>, usize, usize)> {
69    if !matches!(a.dtype, DType::F32 | DType::F64 | DType::C64 | DType::C128) {
70        return Err(not_float(prim, a));
71    }
72    let rank = a.shape.rank();
73    if rank < 2 {
74        return Err(Error::type_error(
75            prim,
76            format!("expected a matrix or a batch of matrices, got {a}"),
77        ));
78    }
79    let d = a.shape.dims();
80    Ok((d[..rank - 2].to_vec(), d[rank - 2], d[rank - 1]))
81}
82
83/// The shape `batch + [rows, cols]`.
84fn batched(batch: &[usize], rows: usize, cols: usize, dtype: DType) -> AVal {
85    let mut d = batch.to_vec();
86    d.push(rows);
87    d.push(cols);
88    AVal::new(d, dtype)
89}
90
91/// The shape `batch + [len]`.
92fn batched_vec(batch: &[usize], len: usize, dtype: DType) -> AVal {
93    let mut d = batch.to_vec();
94    d.push(len);
95    AVal::new(d, dtype)
96}
97
98/// JAX's `expand_dims_batcher`: every operand with its batch dimension
99/// first (broadcast if unbatched), and every output batched there.
100fn batch_leading(
101    cx: &mut dyn BatchCx,
102    prim: Prim,
103    inputs: &[Batched],
104    params: &Params,
105) -> Result<Vec<Batched>> {
106    let atoms = inputs
107        .iter()
108        .map(|x| bdim_at_front(cx, x))
109        .collect::<Result<Vec<_>>>()?;
110    let outs = cx.bind(prim, &atoms, params.clone())?;
111    Ok(outs.into_iter().map(|a| Batched::mapped(a, 0)).collect())
112}
113
114/// Whether the call is compiled for a GPU by a PJRT plugin from Rust, where
115/// XLA's own decompositions (`stablehlo.cholesky`, `stablehlo.triangular_solve`,
116/// and the `Qr` and `ProductOfElementaryHouseholderReflectors` custom calls,
117/// which XLA expands into operations) run on the device instead of ruxla's
118/// handlers, which copy to the host.
119fn xla_gpu(cx: &dyn LowerCx) -> bool {
120    cx.target() == Target::Pjrt && cx.platform() == Platform::Gpu
121}
122
123/// A custom call that XLA implements itself (row-major, no attributes).
124fn xla_call(
125    cx: &mut dyn LowerCx,
126    target: &str,
127    operands: &[HloValue],
128    results: &[AVal],
129) -> Vec<HloValue> {
130    ffi_call(
131        cx,
132        &FfiCall {
133            target,
134            operands,
135            results,
136            config: "",
137            column_major: false,
138            aliases: &[],
139            num_non_batch_dims: None,
140        },
141    )
142}
143
144/// The arguments of a ruxla handler: row-major operands, no aliasing.
145fn ruxla_call(
146    cx: &mut dyn LowerCx,
147    target: &str,
148    operands: &[HloValue],
149    results: &[AVal],
150    config: &str,
151) -> Vec<HloValue> {
152    ffi_call(
153        cx,
154        &FfiCall {
155            target,
156            operands,
157            results,
158            config,
159            column_major: false,
160            aliases: &[],
161            num_non_batch_dims: None,
162        },
163    )
164}
165
166/// A call of a LAPACK or cuSOLVER handler as JAX's `_linalg_ffi_lowering`
167/// emits it: column-major matrices, the first operand aliased with the
168/// first result unless `aliases` says otherwise.
169fn jax_call(
170    cx: &mut dyn LowerCx,
171    target: &str,
172    operands: &[HloValue],
173    results: &[AVal],
174    config: &str,
175    aliases: &[(usize, usize)],
176) -> Vec<HloValue> {
177    ffi_call(
178        cx,
179        &FfiCall {
180            target,
181            operands,
182            results,
183            config,
184            column_major: true,
185            aliases,
186            num_non_batch_dims: Some(2),
187        },
188    )
189}
190
191/// An attribute of a character for LAPACK (`uplo = 76 : ui8` for `'L'`).
192fn char_attr(name: &str, c: char) -> String {
193    format!("{name} = {} : ui8", u32::from(c))
194}
195
196// --- cholesky ---------------------------------------------------------
197
198/// `cholesky`.
199#[derive(Debug)]
200pub(crate) struct Cholesky;
201/// The Cholesky factor `L` (`A = L L^T`) of each symmetric positive
202/// definite matrix, read from its lower triangle; the strictly upper
203/// triangle of the result is that of the input, and matrices that are not
204/// positive definite give NaNs (as JAX's `cholesky_p` on CPU and GPU).
205pub static CHOLESKY: Prim = Prim::new(&Cholesky);
206
207impl Primitive for Cholesky {
208    fn name(&self) -> &'static str {
209        "cholesky"
210    }
211
212    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
213        arity(self.name(), inputs, 1)?;
214        no_params(self.name(), params)?;
215        let (_, m, n) = matrices(self.name(), &inputs[0])?;
216        if m != n {
217            return Err(Error::type_error(
218                self.name(),
219                format!("the input must be square, got {}", inputs[0]),
220            ));
221        }
222        Ok(vec![inputs[0].clone()])
223    }
224
225    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
226        let x = &inputs[0];
227        let (batch, n, _) = matrices(self.name(), &x.aval())?;
228        let count = batch.iter().product();
229        let out = with_float!(self.name(), x, |v: T| Buffer::from_vec(k::cholesky::<T>(
230            v, count, n
231        )));
232        Ok(vec![HostArray::from_buffer(out, x.shape().clone())])
233    }
234
235    fn batch(
236        &'static self,
237        cx: &mut dyn BatchCx,
238        inputs: &[Batched],
239        params: &Params,
240    ) -> Result<Vec<Batched>> {
241        batch_leading(cx, CHOLESKY, inputs, params)
242    }
243
244    fn lower(
245        &self,
246        cx: &mut dyn LowerCx,
247        inputs: &[HloValue],
248        _: &Params,
249        outputs: &[AVal],
250    ) -> Result<Vec<HloValue>> {
251        let x = &inputs[0];
252        let (batch, n, _) = matrices(self.name(), &x.aval)?;
253        if xla_gpu(cx) && n > 0 {
254            // XLA's Cholesky factorization on the device: NaNs everywhere
255            // for matrices that are not positive definite. The strictly
256            // upper triangle is the input's (NaN too on failure, through a
257            // factor `1 + 0 l[0, 0]`).
258            let aval = x.aval.clone();
259            let l = cx.op1("stablehlo.cholesky", inputs, "lower = true", &aval);
260            let rank = aval.shape.rank();
261            let mut limits = aval.shape.dims().to_vec();
262            limits[rank - 2] = 1;
263            limits[rank - 1] = 1;
264            let corner = slice_to(cx, l.clone(), &limits);
265            let corner = cx.op1(
266                "stablehlo.broadcast_in_dim",
267                &[corner],
268                &format!(
269                    "broadcast_dimensions = {}",
270                    i64_array(&(0..rank).collect::<Vec<_>>())
271                ),
272                &aval,
273            );
274            let zero = cx.splat(Value::Int(0), &aval);
275            let one = cx.splat(Value::Int(1), &aval);
276            let factor = cx.op1("stablehlo.multiply", &[zero, corner], "", &aval);
277            let factor = cx.op1("stablehlo.add", &[one, factor], "", &aval);
278            let upper = cx.op1("stablehlo.multiply", &[x.clone(), factor], "", &aval);
279            let lower = tri_mask(cx, &aval.shape, 0);
280            return Ok(vec![cx.op1(
281                "stablehlo.select",
282                &[lower, l, upper],
283                "",
284                &aval,
285            )]);
286        }
287        let abi = abi(cx);
288        let (target, config) = match abi {
289            Abi::Ruxla => return Ok(ruxla_call(cx, "ruxla_cholesky", inputs, outputs, "")),
290            Abi::Lapack => (lapack_target("potrf", x.aval.dtype), char_attr("uplo", 'L')),
291            Abi::Cusolver => (
292                String::from("cusolver_potrf_ffi"),
293                String::from("lower = true"),
294            ),
295        };
296        let results = [x.aval.clone(), info_aval(&batch)];
297        let mut outs = jax_call(cx, &target, inputs, &results, &config, &[(0, 0)]);
298        let info = outs.pop().expect("info");
299        let ok = info_ok(cx, &info, false);
300        Ok(vec![replace_not_ok_with_nan(cx, &ok, outs.remove(0))])
301    }
302
303    fn jvp(
304        &'static self,
305        cx: &mut dyn AdCx,
306        primals: &[Atom],
307        tangents: &[Tangent],
308        _: &Params,
309    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
310        lad::cholesky_jvp(cx, &primals[0], &tangents[0])
311    }
312}
313
314// --- triangular_solve -------------------------------------------------
315
316/// `triangular_solve`.
317#[derive(Debug)]
318pub(crate) struct TriangularSolve;
319/// Solves `op(a) x = b` or `x op(a) = b` for a triangular `a`
320/// ([`Params::TriangularSolve`]); only the triangle of `a` given by `lower`
321/// is read (without the diagonal for `unit_diagonal`).
322pub static TRIANGULAR_SOLVE: Prim = Prim::new(&TriangularSolve);
323
324fn tri_options(prim: &'static str, params: &Params) -> Result<TriangularSolveOptions> {
325    match *params {
326        Params::TriangularSolve {
327            left_side,
328            lower,
329            transpose_a,
330            conjugate_a,
331            unit_diagonal,
332        } => Ok(TriangularSolveOptions {
333            left_side,
334            lower,
335            transpose_a,
336            conjugate_a,
337            unit_diagonal,
338        }),
339        _ => Err(wrong_params(prim)),
340    }
341}
342
343impl Primitive for TriangularSolve {
344    fn name(&self) -> &'static str {
345        "triangular_solve"
346    }
347
348    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
349        arity(self.name(), inputs, 2)?;
350        let o = tri_options(self.name(), params)?;
351        let (a, b) = (&inputs[0], &inputs[1]);
352        let (a_batch, k1, k2) = matrices(self.name(), a)?;
353        let (b_batch, m, n) = matrices(self.name(), b)?;
354        if k1 != k2 {
355            return Err(Error::type_error(
356                self.name(),
357                format!("the first input must be square, got {a}"),
358            ));
359        }
360        if a.dtype != b.dtype || a_batch != b_batch {
361            return Err(Error::type_error(
362                self.name(),
363                format!("the inputs must have the same type and batch dimensions, got {a} and {b}"),
364            ));
365        }
366        let common = if o.left_side { m } else { n };
367        if common != k1 {
368            return Err(Error::type_error(
369                self.name(),
370                format!("incompatible shapes {a} and {b}"),
371            ));
372        }
373        Ok(vec![b.clone()])
374    }
375
376    fn eval(
377        &self,
378        _: &dyn EvalCx,
379        inputs: &[HostArray],
380        params: &Params,
381    ) -> Result<Vec<HostArray>> {
382        let o = tri_options(self.name(), params)?;
383        let (a, b) = (&inputs[0], &inputs[1]);
384        let (batch, m, n) = matrices(self.name(), &b.aval())?;
385        let count = batch.iter().product();
386        let out = with_float!(self.name(), a, |av: T| {
387            let bv = b.as_slice::<T>()?;
388            Buffer::from_vec(k::triangular_solve::<T>(av, bv, count, m, n, o))
389        });
390        Ok(vec![HostArray::from_buffer(out, b.shape().clone())])
391    }
392
393    /// JAX's `_triangular_solve_batching_rule`: an unbatched `a` solves
394    /// for the batch of `b` folded into its columns (or rows); otherwise
395    /// both are batched first.
396    fn batch(
397        &'static self,
398        cx: &mut dyn BatchCx,
399        inputs: &[Batched],
400        params: &Params,
401    ) -> Result<Vec<Batched>> {
402        let o = tri_options(self.name(), params)?;
403        let (a, y) = (&inputs[0], &inputs[1]);
404        if a.bdim.is_some() || y.bdim.is_none() {
405            return batch_leading(cx, TRIANGULAR_SOLVE, inputs, params);
406        }
407        let y_aval = y.atom.aval();
408        let rank = y_aval.shape.rank();
409        // Move the batch dimension next to the dimension it folds into.
410        let to = if o.left_side { rank - 1 } else { rank - 2 };
411        let moved = b::move_bdim(cx, y, to)?;
412        let moved_shape = moved.aval().shape;
413        let mut flat = moved_shape.dims().to_vec();
414        if o.left_side {
415            let last = flat.pop().expect("rank") * flat.pop().expect("rank");
416            flat.push(last);
417        } else {
418            let cols = flat.pop().expect("rank");
419            let rows = flat.pop().expect("rank") * flat.pop().expect("rank");
420            flat.push(rows);
421            flat.push(cols);
422        }
423        let y_flat = b::bind1(
424            cx,
425            RESHAPE,
426            &[moved],
427            Params::Reshape {
428                new_sizes: flat.into(),
429            },
430        )?;
431        let out = b::bind1(
432            cx,
433            TRIANGULAR_SOLVE,
434            &[a.atom.clone(), y_flat],
435            params.clone(),
436        )?;
437        let out = b::bind1(
438            cx,
439            RESHAPE,
440            &[out],
441            Params::Reshape {
442                new_sizes: moved_shape,
443            },
444        )?;
445        Ok(vec![Batched::mapped(out, to)])
446    }
447
448    fn lower(
449        &self,
450        cx: &mut dyn LowerCx,
451        inputs: &[HloValue],
452        params: &Params,
453        outputs: &[AVal],
454    ) -> Result<Vec<HloValue>> {
455        let o = tri_options(self.name(), params)?;
456        // XLA's triangular solve on the device, as JAX's on GPU.
457        let abi = if xla_gpu(cx) { Abi::Cusolver } else { abi(cx) };
458        match abi {
459            Abi::Ruxla => {
460                let config = format!(
461                    "conjugate_a = {}, left_side = {}, lower = {}, transpose_a = {}, \
462                     unit_diagonal = {}",
463                    o.conjugate_a, o.left_side, o.lower, o.transpose_a, o.unit_diagonal
464                );
465                Ok(ruxla_call(
466                    cx,
467                    "ruxla_triangular_solve",
468                    inputs,
469                    outputs,
470                    &config,
471                ))
472            }
473            Abi::Lapack => {
474                let (inputs, conjugate) = conjugate_untransposed(cx, inputs, o);
475                let target = lapack_target("trsm", inputs[0].aval.dtype);
476                let trans = match (o.transpose_a, conjugate) {
477                    (false, _) => 'N',
478                    (true, false) => 'T',
479                    (true, true) => 'C',
480                };
481                let config = [
482                    char_attr("diag", if o.unit_diagonal { 'U' } else { 'N' }),
483                    char_attr("side", if o.left_side { 'L' } else { 'R' }),
484                    char_attr("trans_x", trans),
485                    char_attr("uplo", if o.lower { 'L' } else { 'U' }),
486                ]
487                .join(", ");
488                Ok(jax_call(cx, &target, &inputs, outputs, &config, &[(1, 0)]))
489            }
490            Abi::Cusolver => {
491                let (inputs, conjugate) = conjugate_untransposed(cx, inputs, o);
492                let inputs = &inputs[..];
493                let transpose = match (o.transpose_a, conjugate) {
494                    (false, _) => "NO_TRANSPOSE",
495                    (true, false) => "TRANSPOSE",
496                    (true, true) => "ADJOINT",
497                };
498                let attrs = format!(
499                    "left_side = {}, lower = {}, transpose_a = #stablehlo<transpose {transpose}>, \
500                     unit_diagonal = {}",
501                    o.left_side, o.lower, o.unit_diagonal
502                );
503                Ok(vec![cx.op1(
504                    "stablehlo.triangular_solve",
505                    inputs,
506                    &attrs,
507                    &outputs[0],
508                )])
509            }
510        }
511    }
512
513    fn jvp(
514        &'static self,
515        cx: &mut dyn AdCx,
516        primals: &[Atom],
517        tangents: &[Tangent],
518        params: &Params,
519    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
520        lad::triangular_solve_jvp(cx, primals, tangents, params)
521    }
522
523    fn transpose(
524        &'static self,
525        cx: &mut dyn AdCx,
526        cotangents: &[Tangent],
527        inputs: &[TransposeInput],
528        params: &Params,
529    ) -> Result<Vec<Tangent>> {
530        lad::triangular_solve_transpose(cx, &cotangents[0], inputs, params)
531    }
532}
533
534/// JAX's lowering of `conjugate_a` without `transpose_a`: `a` is
535/// conjugated first (complex `a` only). Returns the inputs and whether the
536/// solve still conjugates (with a transpose: the adjoint).
537fn conjugate_untransposed(
538    cx: &mut dyn LowerCx,
539    inputs: &[HloValue],
540    o: TriangularSolveOptions,
541) -> (Vec<HloValue>, bool) {
542    let complex = inputs[0].aval.dtype.is_complex();
543    let mut inputs = inputs.to_vec();
544    if complex && o.conjugate_a && !o.transpose_a {
545        inputs[0] = conj_hlo(cx, &inputs[0]);
546        return (inputs, false);
547    }
548    (inputs, complex && o.conjugate_a)
549}
550
551// --- lu -----------------------------------------------------------------
552
553/// `lu`.
554#[derive(Debug)]
555pub(crate) struct Lu;
556/// The LU factorization with partial pivoting of each matrix: the factors
557/// (`L` below the diagonal with an implicit unit diagonal, `U` on and
558/// above it), the pivots (`i32[..., min(m, n)]`, 0-based row swaps), and
559/// the permutation (`i32[..., m]`), as JAX's `lu_p`.
560pub static LU: Prim = Prim::new(&Lu);
561
562impl Primitive for Lu {
563    fn name(&self) -> &'static str {
564        "lu"
565    }
566
567    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
568        arity(self.name(), inputs, 1)?;
569        no_params(self.name(), params)?;
570        let (batch, m, n) = matrices(self.name(), &inputs[0])?;
571        if i32::try_from(m).is_err() {
572            return Err(Error::type_error(
573                self.name(),
574                format!("{m} rows overflow i32 pivots"),
575            ));
576        }
577        Ok(vec![
578            inputs[0].clone(),
579            batched_vec(&batch, m.min(n), DType::I32),
580            batched_vec(&batch, m, DType::I32),
581        ])
582    }
583
584    fn eval(&self, _: &dyn EvalCx, inputs: &[HostArray], _: &Params) -> Result<Vec<HostArray>> {
585        let x = &inputs[0];
586        let (batch, m, n) = matrices(self.name(), &x.aval())?;
587        let count = batch.iter().product();
588        let (lu, pivots, perm) = with_float!(self.name(), x, |v: T| {
589            let (lu, pivots, perm) = k::lu::<T>(v, count, m, n);
590            (Buffer::from_vec(lu), pivots, perm)
591        });
592        Ok(vec![
593            HostArray::from_buffer(lu, x.shape().clone()),
594            HostArray::from_vec(pivots, batched_vec(&batch, m.min(n), DType::I32).shape),
595            HostArray::from_vec(perm, batched_vec(&batch, m, DType::I32).shape),
596        ])
597    }
598
599    fn batch(
600        &'static self,
601        cx: &mut dyn BatchCx,
602        inputs: &[Batched],
603        params: &Params,
604    ) -> Result<Vec<Batched>> {
605        batch_leading(cx, LU, inputs, params)
606    }
607
608    fn lower(
609        &self,
610        cx: &mut dyn LowerCx,
611        inputs: &[HloValue],
612        _: &Params,
613        outputs: &[AVal],
614    ) -> Result<Vec<HloValue>> {
615        let x = &inputs[0];
616        let (batch, _, _) = matrices(self.name(), &x.aval)?;
617        let target = match abi(cx) {
618            // cuSOLVER on the device, called by ruxla's handler.
619            Abi::Ruxla if xla_gpu(cx) => String::from("ruxla_cusolver_getrf"),
620            Abi::Ruxla => return Ok(ruxla_call(cx, "ruxla_lu", inputs, outputs, "")),
621            Abi::Lapack => lapack_target("getrf", x.aval.dtype),
622            Abi::Cusolver => String::from("cusolver_getrf_ffi"),
623        };
624        let results = [x.aval.clone(), outputs[1].clone(), info_aval(&batch)];
625        let mut outs = jax_call(cx, &target, inputs, &results, "", &[(0, 0)]);
626        let info = outs.pop().expect("info");
627        let pivots = outs.pop().expect("pivots");
628        // 1-based pivots to 0-based.
629        let one = cx.splat(Value::Int(1), &pivots.aval);
630        let pivots = cx.op1("stablehlo.subtract", &[pivots, one], "", &outputs[1]);
631        let ok = info_ok(cx, &info, true);
632        let lu = replace_not_ok_with_nan(cx, &ok, outs.remove(0));
633        let perm = lower_pivots_to_permutation(cx, &pivots, &outputs[2])?;
634        Ok(vec![lu, pivots, perm])
635    }
636
637    fn jvp(
638        &'static self,
639        cx: &mut dyn AdCx,
640        primals: &[Atom],
641        tangents: &[Tangent],
642        _: &Params,
643    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
644        lad::lu_jvp(cx, &primals[0], &tangents[0])
645    }
646}
647
648// --- lu_pivots_to_permutation -------------------------------------------
649
650/// `lu_pivots_to_permutation`.
651#[derive(Debug)]
652pub(crate) struct LuPivotsToPermutation;
653/// Converts the pivots of `lu` (`i32[..., k]`) to permutations
654/// (`i32[..., permutation_size]`): starting from the identity, swaps
655/// element `i` with element `pivots[i]` for each `i` in order
656/// ([`Params::LuPivotsToPermutation`]).
657pub static LU_PIVOTS_TO_PERMUTATION: Prim = Prim::new(&LuPivotsToPermutation);
658
659fn permutation_size(prim: &'static str, params: &Params) -> Result<usize> {
660    match *params {
661        Params::LuPivotsToPermutation { permutation_size } => Ok(permutation_size),
662        _ => Err(wrong_params(prim)),
663    }
664}
665
666impl Primitive for LuPivotsToPermutation {
667    fn name(&self) -> &'static str {
668        "lu_pivots_to_permutation"
669    }
670
671    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
672        arity(self.name(), inputs, 1)?;
673        let size = permutation_size(self.name(), params)?;
674        let p = &inputs[0];
675        if p.dtype != DType::I32 || p.shape.rank() == 0 {
676            return Err(Error::type_error(
677                self.name(),
678                format!("expected i32 pivots of rank at least 1, got {p}"),
679            ));
680        }
681        let rank = p.shape.rank();
682        let k = p.shape[rank - 1];
683        if size < k {
684            return Err(Error::type_error(
685                self.name(),
686                format!("the permutation size {size} must be at least the number of pivots {k}"),
687            ));
688        }
689        if i32::try_from(size).is_err() {
690            return Err(Error::type_error(
691                self.name(),
692                format!("the permutation size {size} overflows i32"),
693            ));
694        }
695        Ok(vec![batched_vec(
696            &p.shape.dims()[..rank - 1],
697            size,
698            DType::I32,
699        )])
700    }
701
702    fn eval(
703        &self,
704        _: &dyn EvalCx,
705        inputs: &[HostArray],
706        params: &Params,
707    ) -> Result<Vec<HostArray>> {
708        let size = permutation_size(self.name(), params)?;
709        let p = &inputs[0];
710        let dims = p.shape().dims();
711        let k = dims[dims.len() - 1];
712        let batch = &dims[..dims.len() - 1];
713        let count = batch.iter().product();
714        let perm = k::lu_pivots_to_permutation(p.as_slice::<i32>()?, count, k, size);
715        Ok(vec![HostArray::from_vec(
716            perm,
717            batched_vec(batch, size, DType::I32).shape,
718        )])
719    }
720
721    fn batch(
722        &'static self,
723        cx: &mut dyn BatchCx,
724        inputs: &[Batched],
725        params: &Params,
726    ) -> Result<Vec<Batched>> {
727        batch_leading(cx, LU_PIVOTS_TO_PERMUTATION, inputs, params)
728    }
729
730    fn lower(
731        &self,
732        cx: &mut dyn LowerCx,
733        inputs: &[HloValue],
734        _: &Params,
735        outputs: &[AVal],
736    ) -> Result<Vec<HloValue>> {
737        Ok(vec![lower_pivots_to_permutation(
738            cx,
739            &inputs[0],
740            &outputs[0],
741        )?])
742    }
743}
744
745// --- qr -------------------------------------------------------------------
746
747/// `qr`.
748#[derive(Debug)]
749pub(crate) struct Qr;
750/// The QR decomposition of each matrix ([`Params::Qr`]): `q` with
751/// orthonormal columns and an upper triangular `r`, with the signs of
752/// LAPACK's Householder reflectors (as JAX's `qr_p`, which it computes with
753/// `geqrf` and `orgqr`). With `pivoting`, the decomposition of the columns
754/// permuted by LAPACK's `geqp3` (`x[..., p] = q r`) and the permutation `p`
755/// (`i32[..., n]`) as a third output.
756pub static QR: Prim = Prim::new(&Qr);
757
758fn qr_params(prim: &'static str, params: &Params) -> Result<(bool, bool)> {
759    match *params {
760        Params::Qr {
761            full_matrices,
762            pivoting,
763        } => Ok((full_matrices, pivoting)),
764        _ => Err(wrong_params(prim)),
765    }
766}
767
768impl Primitive for Qr {
769    fn name(&self) -> &'static str {
770        "qr"
771    }
772
773    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
774        arity(self.name(), inputs, 1)?;
775        let (full, pivoting) = qr_params(self.name(), params)?;
776        let a = &inputs[0];
777        let (batch, m, n) = matrices(self.name(), a)?;
778        if pivoting && i32::try_from(n).is_err() {
779            return Err(Error::type_error(
780                self.name(),
781                format!("{n} columns overflow i32 pivots"),
782            ));
783        }
784        let kq = if full { m } else { m.min(n) };
785        let mut out = vec![
786            batched(&batch, m, kq, a.dtype),
787            batched(&batch, kq, n, a.dtype),
788        ];
789        if pivoting {
790            out.push(batched_vec(&batch, n, DType::I32));
791        }
792        Ok(out)
793    }
794
795    fn eval(
796        &self,
797        _: &dyn EvalCx,
798        inputs: &[HostArray],
799        params: &Params,
800    ) -> Result<Vec<HostArray>> {
801        let (full, pivoting) = qr_params(self.name(), params)?;
802        let x = &inputs[0];
803        let outs = self.abstract_eval(&[x.aval()], params)?;
804        let (batch, m, n) = matrices(self.name(), &x.aval())?;
805        let count = batch.iter().product();
806        let (q, r, p) = with_float!(self.name(), x, |v: T| {
807            let (q, r, p) = if pivoting {
808                k::qr_pivoting::<T>(v, count, m, n, full)
809            } else {
810                let (q, r) = k::qr::<T>(v, count, m, n, full);
811                (q, r, Vec::new())
812            };
813            (Buffer::from_vec(q), Buffer::from_vec(r), p)
814        });
815        let mut result = vec![
816            HostArray::from_buffer(q, outs[0].shape.clone()),
817            HostArray::from_buffer(r, outs[1].shape.clone()),
818        ];
819        if pivoting {
820            result.push(HostArray::from_vec(p, outs[2].shape.clone()));
821        }
822        Ok(result)
823    }
824
825    fn batch(
826        &'static self,
827        cx: &mut dyn BatchCx,
828        inputs: &[Batched],
829        params: &Params,
830    ) -> Result<Vec<Batched>> {
831        batch_leading(cx, QR, inputs, params)
832    }
833
834    /// JAX's `_qr_lowering`: `geqrf`, then `orgqr` (`householder_product`)
835    /// on the reflectors, padded or sliced to the shape of `q`.
836    fn lower(
837        &self,
838        cx: &mut dyn LowerCx,
839        inputs: &[HloValue],
840        params: &Params,
841        outputs: &[AVal],
842    ) -> Result<Vec<HloValue>> {
843        let (full, pivoting) = qr_params(self.name(), params)?;
844        let a = &inputs[0];
845        let (batch, m, n) = matrices(self.name(), &a.aval)?;
846        let abi = abi(cx);
847        // XLA's `Qr` and Householder product on the device (without
848        // pivoting, which ruxla's handler computes on the host).
849        let xla = xla_gpu(cx) && !pivoting;
850        if abi == Abi::Ruxla && !xla {
851            let config = format!("full_matrices = {full}, pivoting = {pivoting}");
852            return Ok(ruxla_call(cx, "ruxla_qr", inputs, outputs, &config));
853        }
854        if m == 0 || n == 0 {
855            let q = eye(cx, &outputs[0]);
856            let r = cx.splat(Value::Int(0), &outputs[1]);
857            let mut out = vec![q, r];
858            if pivoting {
859                out.push(cx.splat(Value::Int(0), &outputs[2]));
860            }
861            return Ok(out);
862        }
863        let dtype = a.aval.dtype;
864        let (geqrf, orgqr) = match abi {
865            Abi::Lapack => {
866                // `ungqr` for complex numbers.
867                let orgqr = if dtype.is_complex() { "ungqr" } else { "orgqr" };
868                (lapack_target("geqrf", dtype), lapack_target(orgqr, dtype))
869            }
870            _ => (
871                String::from("cusolver_geqrf_ffi"),
872                String::from("cusolver_orgqr_ffi"),
873            ),
874        };
875        let k = m.min(n);
876        let (taus, mut r, p) = if pivoting {
877            // `geqp3` with all columns free (`jpvt = 0`); it returns 1-based
878            // pivots.
879            let (geqp3, config) = match abi {
880                Abi::Lapack => (lapack_target("geqp3", dtype), String::new()),
881                _ => (
882                    String::from("cuhybrid_geqp3"),
883                    String::from("magma = \"auto\""),
884                ),
885            };
886            let jpvt = cx.splat(Value::Int(0), &outputs[2]);
887            let results = [
888                a.aval.clone(),
889                outputs[2].clone(),
890                batched_vec(&batch, k, dtype),
891            ];
892            let mut outs = jax_call(
893                cx,
894                &geqp3,
895                &[a.clone(), jpvt],
896                &results,
897                &config,
898                &[(0, 0), (1, 1)],
899            );
900            let taus = outs.pop().expect("taus");
901            let jpvt = outs.pop().expect("jpvt");
902            let one = cx.splat(Value::Int(1), &jpvt.aval);
903            let p = cx.op1("stablehlo.subtract", &[jpvt, one], "", &outputs[2]);
904            (taus, outs.pop().expect("r"), Some(p))
905        } else {
906            let results = [a.aval.clone(), batched_vec(&batch, k, dtype)];
907            let mut outs = if xla {
908                xla_call(cx, "Qr", inputs, &results)
909            } else {
910                jax_call(cx, &geqrf, inputs, &results, "", &[(0, 0)])
911            };
912            let taus = outs.pop().expect("taus");
913            (taus, outs.pop().expect("r"), None)
914        };
915        let householder = |cx: &mut dyn LowerCx, a: HloValue| {
916            let aval = a.aval.clone();
917            if xla {
918                return xla_call(
919                    cx,
920                    "ProductOfElementaryHouseholderReflectors",
921                    &[a, taus.clone()],
922                    &[aval],
923                )
924                .remove(0);
925            }
926            jax_call(cx, &orgqr, &[a, taus.clone()], &[aval], "", &[(0, 0)]).remove(0)
927        };
928        let nb = batch.len();
929        let limits = |rows: usize, cols: usize| {
930            let mut d = batch.clone();
931            d.push(rows);
932            d.push(cols);
933            d
934        };
935        let q = if m < n {
936            let square = slice_to(cx, r.clone(), &limits(m, m));
937            householder(cx, square)
938        } else if full {
939            let zero = cx.splat(Value::Int(0), &AVal::scalar(dtype));
940            let mut high = vec![0; nb + 2];
941            high[nb + 1] = m - n;
942            let attrs = format!(
943                "edge_padding_low = {}, edge_padding_high = {}, interior_padding = {}",
944                i64_array(&vec![0; nb + 2]),
945                i64_array(&high),
946                i64_array(&vec![0; nb + 2])
947            );
948            let padded = cx.op1(
949                "stablehlo.pad",
950                &[r.clone(), zero],
951                &attrs,
952                &batched(&batch, m, m, dtype),
953            );
954            householder(cx, padded)
955        } else {
956            let q = householder(cx, r.clone());
957            r = slice_to(cx, r, &limits(n, n));
958            q
959        };
960        let mut out = vec![q, triu(cx, r)];
961        out.extend(p);
962        Ok(out)
963    }
964
965    fn jvp(
966        &'static self,
967        cx: &mut dyn AdCx,
968        primals: &[Atom],
969        tangents: &[Tangent],
970        params: &Params,
971    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
972        let (full, pivoting) = qr_params(self.name(), params)?;
973        lad::qr_jvp(cx, &primals[0], &tangents[0], full, pivoting)
974    }
975}
976
977// --- eigh -----------------------------------------------------------------
978
979/// The range of `subset_by_index` out of `full` entries, or `None` for all
980/// of them (`None` or `(0, full)`).
981fn subset_range(
982    prim: &'static str,
983    subset: Option<(usize, usize)>,
984    full: usize,
985) -> Result<Option<(usize, usize)>> {
986    match subset {
987        None => Ok(None),
988        Some((0, end)) if end == full => Ok(None),
989        Some((start, end)) if start <= end && end <= full => Ok(Some((start, end))),
990        Some((start, end)) => Err(Error::type_error(
991            prim,
992            format!("subset_by_index ({start}, {end}) out of {full}"),
993        )),
994    }
995}
996
997/// `x[..., start..end]` along `axis` (an evaluated result).
998fn slice_host(
999    cx: &dyn EvalCx,
1000    x: &HostArray,
1001    axis: usize,
1002    (start, end): (usize, usize),
1003) -> Result<HostArray> {
1004    let dims = x.shape().dims().to_vec();
1005    let mut start_indices = vec![0; dims.len()];
1006    let mut limit_indices = dims.clone();
1007    start_indices[axis] = start;
1008    limit_indices[axis] = end;
1009    let params = Params::Slice {
1010        start_indices,
1011        limit_indices,
1012        strides: vec![1; dims.len()],
1013    };
1014    Ok(crate::structural::SLICE
1015        .eval(cx, std::slice::from_ref(x), &params)?
1016        .remove(0))
1017}
1018
1019/// `x[..., start..end]` along `axis` (a lowered result).
1020fn slice_hlo(
1021    cx: &mut dyn LowerCx,
1022    x: HloValue,
1023    axis: usize,
1024    (start, end): (usize, usize),
1025) -> HloValue {
1026    let dims = x.aval.shape.dims().to_vec();
1027    let mut start_indices = vec![0; dims.len()];
1028    let mut limit_indices = dims.clone();
1029    start_indices[axis] = start;
1030    limit_indices[axis] = end;
1031    let mut shape = dims;
1032    shape[axis] = end - start;
1033    let attrs = format!(
1034        "start_indices = {}, limit_indices = {}, strides = {}",
1035        i64_array(&start_indices),
1036        i64_array(&limit_indices),
1037        i64_array(&vec![1; shape.len()])
1038    );
1039    let aval = AVal::new(shape, x.aval.dtype);
1040    cx.op1("stablehlo.slice", &[x], &attrs, &aval)
1041}
1042
1043/// `eigh`.
1044#[derive(Debug)]
1045pub(crate) struct Eigh;
1046/// The eigendecomposition of each symmetric matrix, read from the triangle
1047/// given by `lower` ([`Params::Eigh`]): the eigenvectors `v` (columns) and
1048/// the eigenvalues `w` in ascending order, as JAX's `eigh_p` (which returns
1049/// `v` first). With `subset_by_index`, the eigenvalues of that range of
1050/// indices and their eigenvectors (computed from the whole decomposition;
1051/// JAX supports it on TPU only).
1052pub static EIGH: Prim = Prim::new(&Eigh);
1053
1054fn eigh_lower(prim: &'static str, params: &Params) -> Result<bool> {
1055    match *params {
1056        Params::Eigh { lower, .. } => Ok(lower),
1057        _ => Err(wrong_params(prim)),
1058    }
1059}
1060
1061/// Whether `eigh` or `svd` uses Jacobi rotations (`algorithm = JACOBI`).
1062fn uses_jacobi(params: &Params) -> bool {
1063    matches!(
1064        params,
1065        Params::Eigh {
1066            algorithm: Some(EighImplementation::Jacobi),
1067            ..
1068        } | Params::Svd {
1069            algorithm: Some(SvdAlgorithm::Jacobi),
1070            ..
1071        }
1072    )
1073}
1074
1075/// The range of `subset_by_index` of `eigh` or `svd` out of `full`
1076/// entries (`None` for all of them), and the parameters without it.
1077fn split_subset(
1078    prim: &'static str,
1079    params: &Params,
1080    full: usize,
1081) -> Result<(Option<(usize, usize)>, Params)> {
1082    let mut whole = params.clone();
1083    let subset = match &mut whole {
1084        Params::Eigh {
1085            subset_by_index, ..
1086        }
1087        | Params::Svd {
1088            subset_by_index, ..
1089        } => subset_by_index.take(),
1090        _ => return Err(wrong_params(prim)),
1091    };
1092    Ok((subset_range(prim, subset, full)?, whole))
1093}
1094
1095impl Primitive for Eigh {
1096    fn name(&self) -> &'static str {
1097        "eigh"
1098    }
1099
1100    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1101        arity(self.name(), inputs, 1)?;
1102        eigh_lower(self.name(), params)?;
1103        let a = &inputs[0];
1104        let (batch, m, n) = matrices(self.name(), a)?;
1105        if m != n {
1106            return Err(Error::type_error(
1107                self.name(),
1108                format!("the input must be square, got {a}"),
1109            ));
1110        }
1111        let (range, _) = split_subset(self.name(), params, n)?;
1112        let d = range.map_or(n, |(start, end)| end - start);
1113        Ok(vec![
1114            batched(&batch, n, d, a.dtype),
1115            batched_vec(&batch, d, a.dtype.real_dtype()),
1116        ])
1117    }
1118
1119    fn eval(
1120        &self,
1121        cx: &dyn EvalCx,
1122        inputs: &[HostArray],
1123        params: &Params,
1124    ) -> Result<Vec<HostArray>> {
1125        let lower = eigh_lower(self.name(), params)?;
1126        let x = &inputs[0];
1127        let (batch, n, _) = matrices(self.name(), &x.aval())?;
1128        if let (Some(range), whole) = split_subset(self.name(), params, n)? {
1129            let outs = self.eval(cx, inputs, &whole)?;
1130            let rank = outs[0].shape().rank();
1131            return Ok(vec![
1132                slice_host(cx, &outs[0], rank - 1, range)?,
1133                slice_host(cx, &outs[1], rank - 2, range)?,
1134            ]);
1135        }
1136        let count = batch.iter().product();
1137        let (v, w) = with_float!(self.name(), x, |a: T| {
1138            let (v, w) = k::eigh::<T>(a, count, n, lower, uses_jacobi(params));
1139            (Buffer::from_vec(v), Buffer::from_vec(w))
1140        });
1141        Ok(vec![
1142            HostArray::from_buffer(v, x.shape().clone()),
1143            HostArray::from_buffer(w, batched_vec(&batch, n, x.dtype().real_dtype()).shape),
1144        ])
1145    }
1146
1147    fn batch(
1148        &'static self,
1149        cx: &mut dyn BatchCx,
1150        inputs: &[Batched],
1151        params: &Params,
1152    ) -> Result<Vec<Batched>> {
1153        batch_leading(cx, EIGH, inputs, params)
1154    }
1155
1156    fn lower(
1157        &self,
1158        cx: &mut dyn LowerCx,
1159        inputs: &[HloValue],
1160        params: &Params,
1161        outputs: &[AVal],
1162    ) -> Result<Vec<HloValue>> {
1163        let lower = eigh_lower(self.name(), params)?;
1164        let x = &inputs[0];
1165        let (batch, n, _) = matrices(self.name(), &x.aval)?;
1166        if let (Some(range), whole) = split_subset(self.name(), params, n)? {
1167            let avals = self.abstract_eval(std::slice::from_ref(&x.aval), &whole)?;
1168            let mut outs = self.lower(cx, inputs, &whole, &avals)?;
1169            let rank = x.aval.shape.rank();
1170            let w = slice_hlo(cx, outs.pop().expect("w"), rank - 2, range);
1171            let v = slice_hlo(cx, outs.pop().expect("v"), rank - 1, range);
1172            return Ok(vec![v, w]);
1173        }
1174        let device = xla_gpu(cx);
1175        let (target, config) = match abi(cx) {
1176            // cuSOLVER on the device, called by ruxla's handler (the phases
1177            // set as natively below).
1178            Abi::Ruxla if device => (
1179                String::from("ruxla_cusolver_syevd"),
1180                format!("algorithm = 0 : ui8, lower = {lower}"),
1181            ),
1182            Abi::Ruxla => {
1183                let config = format!("jacobi = {}, lower = {lower}", uses_jacobi(params));
1184                return Ok(ruxla_call(cx, "ruxla_eigh", inputs, outputs, &config));
1185            }
1186            Abi::Lapack => (
1187                // `heevd` for complex numbers.
1188                lapack_target(
1189                    if x.aval.dtype.is_complex() {
1190                        "heevd"
1191                    } else {
1192                        "syevd"
1193                    },
1194                    x.aval.dtype,
1195                ),
1196                format!(
1197                    "{}, {}",
1198                    char_attr("mode", 'V'),
1199                    char_attr("uplo", if lower { 'L' } else { 'U' })
1200                ),
1201            ),
1202            Abi::Cusolver => (
1203                String::from("cusolver_syevd_ffi"),
1204                // JAX's choice: 0 by default, 2 for Jacobi, 1 otherwise.
1205                format!(
1206                    "algorithm = {} : ui8, lower = {lower}",
1207                    match params {
1208                        Params::Eigh {
1209                            algorithm: None, ..
1210                        } => 0,
1211                        _ if uses_jacobi(params) => 2,
1212                        _ => 1,
1213                    }
1214                ),
1215            ),
1216        };
1217        let results = [outputs[0].clone(), outputs[1].clone(), info_aval(&batch)];
1218        let mut outs = jax_call(cx, &target, inputs, &results, &config, &[(0, 0)]);
1219        let info = outs.pop().expect("info");
1220        let ok = info_ok(cx, &info, false);
1221        let w = outs.pop().expect("w");
1222        let mut v = replace_not_ok_with_nan(cx, &ok, outs.pop().expect("v"));
1223        let w = replace_not_ok_with_nan(cx, &ok, w);
1224        if device {
1225            v = eigh_phases(cx, v)?;
1226        }
1227        Ok(vec![v, w])
1228    }
1229
1230    fn jvp(
1231        &'static self,
1232        cx: &mut dyn AdCx,
1233        primals: &[Atom],
1234        tangents: &[Tangent],
1235        params: &Params,
1236    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
1237        let n = primals[0].aval().shape.dims().last().copied().unwrap_or(0);
1238        if split_subset(self.name(), params, n)?.0.is_some() {
1239            return Err(Error::unsupported(
1240                self.name(),
1241                "derivatives are not defined for partial eigendecompositions (as in JAX)",
1242            ));
1243        }
1244        lad::eigh_jvp(cx, &primals[0], &tangents[0], params)
1245    }
1246}
1247
1248// --- eig ------------------------------------------------------------------
1249
1250/// `eig`.
1251#[derive(Debug)]
1252pub(crate) struct Eig;
1253/// The eigendecomposition of each general matrix ([`Params::Eig`]): the
1254/// complex eigenvalues (`[..., n]`), and the left and right eigenvectors
1255/// (`[..., n, n]`, one per column) that are requested, of the complex type
1256/// of the input, as JAX's `eig_p`, which it computes with LAPACK's `geev`
1257/// (see `ruxla_kernels::linalg::eig` for the conventions).
1258pub static EIG: Prim = Prim::new(&Eig);
1259
1260fn eig_params(prim: &'static str, params: &Params) -> Result<(bool, bool, bool)> {
1261    match *params {
1262        Params::Eig {
1263            compute_left_eigenvectors,
1264            compute_right_eigenvectors,
1265            enable_eigvec_derivs,
1266        } => Ok((
1267            compute_left_eigenvectors,
1268            compute_right_eigenvectors,
1269            enable_eigvec_derivs,
1270        )),
1271        _ => Err(wrong_params(prim)),
1272    }
1273}
1274
1275/// The complex type of a real or complex type.
1276fn complex_dtype(d: DType) -> DType {
1277    match d {
1278        DType::F32 | DType::C64 => DType::C64,
1279        _ => DType::C128,
1280    }
1281}
1282
1283impl Primitive for Eig {
1284    fn name(&self) -> &'static str {
1285        "eig"
1286    }
1287
1288    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1289        arity(self.name(), inputs, 1)?;
1290        let (left, right, _) = eig_params(self.name(), params)?;
1291        let a = &inputs[0];
1292        let (batch, m, n) = matrices(self.name(), a)?;
1293        if m != n {
1294            return Err(Error::type_error(
1295                self.name(),
1296                format!("the input must be square, got {a}"),
1297            ));
1298        }
1299        let c = complex_dtype(a.dtype);
1300        let mut out = vec![batched_vec(&batch, n, c)];
1301        for _ in 0..usize::from(left) + usize::from(right) {
1302            out.push(batched(&batch, n, n, c));
1303        }
1304        Ok(out)
1305    }
1306
1307    fn eval(
1308        &self,
1309        _: &dyn EvalCx,
1310        inputs: &[HostArray],
1311        params: &Params,
1312    ) -> Result<Vec<HostArray>> {
1313        let (left, right, _) = eig_params(self.name(), params)?;
1314        let x = &inputs[0];
1315        let outs = self.abstract_eval(&[x.aval()], params)?;
1316        let (batch, n, _) = matrices(self.name(), &x.aval())?;
1317        let count = batch.iter().product();
1318        let (w, vl, vr) = with_float!(self.name(), x, |a: T| {
1319            let (w, vl, vr) = k::eig::<T>(a, count, n, left, right);
1320            (
1321                Buffer::from_vec(w),
1322                Buffer::from_vec(vl),
1323                Buffer::from_vec(vr),
1324            )
1325        });
1326        let mut result = vec![HostArray::from_buffer(w, outs[0].shape.clone())];
1327        if left {
1328            result.push(HostArray::from_buffer(vl, outs[1].shape.clone()));
1329        }
1330        if right {
1331            result.push(HostArray::from_buffer(vr, outs[result.len()].shape.clone()));
1332        }
1333        Ok(result)
1334    }
1335
1336    fn batch(
1337        &'static self,
1338        cx: &mut dyn BatchCx,
1339        inputs: &[Batched],
1340        params: &Params,
1341    ) -> Result<Vec<Batched>> {
1342        batch_leading(cx, EIG, inputs, params)
1343    }
1344
1345    fn lower(
1346        &self,
1347        cx: &mut dyn LowerCx,
1348        inputs: &[HloValue],
1349        params: &Params,
1350        outputs: &[AVal],
1351    ) -> Result<Vec<HloValue>> {
1352        let (left, right, _) = eig_params(self.name(), params)?;
1353        let a = &inputs[0];
1354        let (batch, n, _) = matrices(self.name(), &a.aval)?;
1355        let abi = abi(cx);
1356        if abi == Abi::Ruxla {
1357            let config = format!("compute_left = {left}, compute_right = {right}");
1358            return Ok(ruxla_call(cx, "ruxla_eig", inputs, outputs, &config));
1359        }
1360        let dtype = a.aval.dtype;
1361        let real = !dtype.is_complex();
1362        let c = complex_dtype(dtype);
1363        let w_part = batched_vec(&batch, n, dtype);
1364        let vecs = batched(&batch, n, n, c);
1365        let mut results = vec![w_part.clone()];
1366        if real {
1367            results.push(w_part);
1368        }
1369        results.extend([vecs.clone(), vecs, info_aval(&batch)]);
1370        let (target, config) = match abi {
1371            Abi::Lapack => {
1372                let mode = |b: bool| if b { 'V' } else { 'N' };
1373                (
1374                    lapack_target("geev", dtype),
1375                    format!(
1376                        "{}, {}",
1377                        char_attr("compute_left", mode(left)),
1378                        char_attr("compute_right", mode(right))
1379                    ),
1380                )
1381            }
1382            _ => (
1383                String::from(if real {
1384                    "cuhybrid_eig_real"
1385                } else {
1386                    "cuhybrid_eig_comp"
1387                }),
1388                format!("left = {left}, magma = \"auto\", right = {right}"),
1389            ),
1390        };
1391        let mut outs = jax_call(cx, &target, inputs, &results, &config, &[]);
1392        let info = outs.pop().expect("info");
1393        let vr = outs.pop().expect("vr");
1394        let vl = outs.pop().expect("vl");
1395        let w = if real {
1396            let wi = outs.pop().expect("wi");
1397            let wr = outs.pop().expect("wr");
1398            crate::elementwise::make_complex(cx, &wr, &wi)
1399        } else {
1400            outs.pop().expect("w")
1401        };
1402        let ok = info_ok(cx, &info, false);
1403        let mut out = vec![replace_not_ok_with_nan(cx, &ok, w)];
1404        if left {
1405            out.push(replace_not_ok_with_nan(cx, &ok, vl));
1406        }
1407        if right {
1408            out.push(replace_not_ok_with_nan(cx, &ok, vr));
1409        }
1410        Ok(out)
1411    }
1412
1413    fn jvp(
1414        &'static self,
1415        cx: &mut dyn AdCx,
1416        primals: &[Atom],
1417        tangents: &[Tangent],
1418        params: &Params,
1419    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
1420        let (left, right, derivs) = eig_params(self.name(), params)?;
1421        lad::eig_jvp(cx, &primals[0], &tangents[0], left, right, derivs)
1422    }
1423}
1424
1425// --- schur, hessenberg, householder_product, ormqr ------------------------
1426
1427/// `schur`.
1428#[derive(Debug)]
1429pub(crate) struct Schur;
1430/// The Schur decomposition `x = z t z^H` of each square matrix
1431/// ([`Params::Schur`]): `t` (quasi-triangular with standardized 2 x 2 blocks
1432/// for real matrices, triangular for complex ones) and, if requested, the
1433/// Schur vectors `z`, as JAX's `schur_p` (LAPACK's `gees`, without sorting).
1434/// Not differentiable, as in JAX.
1435pub static SCHUR: Prim = Prim::new(&Schur);
1436
1437fn schur_vectors(prim: &'static str, params: &Params) -> Result<bool> {
1438    match *params {
1439        Params::Schur {
1440            compute_schur_vectors,
1441        } => Ok(compute_schur_vectors),
1442        _ => Err(wrong_params(prim)),
1443    }
1444}
1445
1446/// Checks a batch of square matrices and returns the batch dimensions and
1447/// the size.
1448fn square_matrices(prim: &'static str, a: &AVal) -> Result<(Vec<usize>, usize)> {
1449    let (batch, m, n) = matrices(prim, a)?;
1450    if m != n {
1451        return Err(Error::type_error(
1452            prim,
1453            format!("the input must be square, got {a}"),
1454        ));
1455    }
1456    Ok((batch, n))
1457}
1458
1459/// `jax_call` for the primitives that JAX lowers on CPU only.
1460fn cpu_only(prim: &'static str, abi: Abi) -> Result<()> {
1461    if abi == Abi::Cusolver {
1462        return Err(Error::unsupported(
1463            prim,
1464            "JAX implements it on CPU only (there is no GPU lowering)",
1465        ));
1466    }
1467    Ok(())
1468}
1469
1470impl Primitive for Schur {
1471    fn name(&self) -> &'static str {
1472        "schur"
1473    }
1474
1475    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1476        arity(self.name(), inputs, 1)?;
1477        let vectors = schur_vectors(self.name(), params)?;
1478        square_matrices(self.name(), &inputs[0])?;
1479        let mut out = vec![inputs[0].clone()];
1480        if vectors {
1481            out.push(inputs[0].clone());
1482        }
1483        Ok(out)
1484    }
1485
1486    fn eval(
1487        &self,
1488        _: &dyn EvalCx,
1489        inputs: &[HostArray],
1490        params: &Params,
1491    ) -> Result<Vec<HostArray>> {
1492        let vectors = schur_vectors(self.name(), params)?;
1493        let x = &inputs[0];
1494        let (batch, n) = square_matrices(self.name(), &x.aval())?;
1495        let count = batch.iter().product();
1496        let (t, z) = with_float!(self.name(), x, |a: T| {
1497            let (t, z) = k::schur::<T>(a, count, n, vectors);
1498            (Buffer::from_vec(t), Buffer::from_vec(z))
1499        });
1500        let mut out = vec![HostArray::from_buffer(t, x.shape().clone())];
1501        if vectors {
1502            out.push(HostArray::from_buffer(z, x.shape().clone()));
1503        }
1504        Ok(out)
1505    }
1506
1507    fn batch(
1508        &'static self,
1509        cx: &mut dyn BatchCx,
1510        inputs: &[Batched],
1511        params: &Params,
1512    ) -> Result<Vec<Batched>> {
1513        batch_leading(cx, SCHUR, inputs, params)
1514    }
1515
1516    fn lower(
1517        &self,
1518        cx: &mut dyn LowerCx,
1519        inputs: &[HloValue],
1520        params: &Params,
1521        outputs: &[AVal],
1522    ) -> Result<Vec<HloValue>> {
1523        let vectors = schur_vectors(self.name(), params)?;
1524        let a = &inputs[0];
1525        let (batch, n) = square_matrices(self.name(), &a.aval)?;
1526        let abi = abi(cx);
1527        if abi == Abi::Ruxla {
1528            let config = format!("compute_schur_vectors = {vectors}");
1529            return Ok(ruxla_call(cx, "ruxla_schur", inputs, outputs, &config));
1530        }
1531        cpu_only(self.name(), abi)?;
1532        let dtype = a.aval.dtype;
1533        let w = batched_vec(&batch, n, dtype);
1534        let mut results = vec![a.aval.clone(), a.aval.clone(), w.clone()];
1535        if !dtype.is_complex() {
1536            results.push(w);
1537        }
1538        results.extend([info_aval(&batch), info_aval(&batch)]);
1539        let config = format!(
1540            "{}, {}",
1541            char_attr("mode", if vectors { 'V' } else { 'N' }),
1542            char_attr("sort", 'N')
1543        );
1544        let mut outs = jax_call(
1545            cx,
1546            &lapack_target("gees", dtype),
1547            inputs,
1548            &results,
1549            &config,
1550            &[(0, 0)],
1551        );
1552        let info = outs.pop().expect("info");
1553        let ok = info_ok(cx, &info, false);
1554        let t = outs.remove(0);
1555        let z = outs.remove(0);
1556        let mut out = vec![replace_not_ok_with_nan(cx, &ok, t)];
1557        if vectors {
1558            out.push(replace_not_ok_with_nan(cx, &ok, z));
1559        }
1560        Ok(out)
1561    }
1562}
1563
1564/// `hessenberg`.
1565#[derive(Debug)]
1566pub(crate) struct Hessenberg;
1567/// The reduction of each square matrix to upper Hessenberg form, as JAX's
1568/// `hessenberg_p` (LAPACK's `gehrd`): the matrix with `h` on and above the
1569/// subdiagonal and the Householder reflectors below it, and the `n - 1`
1570/// factors `tau`. Not differentiable, as in JAX.
1571pub static HESSENBERG: Prim = Prim::new(&Hessenberg);
1572
1573impl Primitive for Hessenberg {
1574    fn name(&self) -> &'static str {
1575        "hessenberg"
1576    }
1577
1578    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1579        arity(self.name(), inputs, 1)?;
1580        no_params(self.name(), params)?;
1581        let (batch, n) = square_matrices(self.name(), &inputs[0])?;
1582        Ok(vec![
1583            inputs[0].clone(),
1584            batched_vec(&batch, n.saturating_sub(1), inputs[0].dtype),
1585        ])
1586    }
1587
1588    fn eval(
1589        &self,
1590        _: &dyn EvalCx,
1591        inputs: &[HostArray],
1592        params: &Params,
1593    ) -> Result<Vec<HostArray>> {
1594        let x = &inputs[0];
1595        let outs = self.abstract_eval(&[x.aval()], params)?;
1596        let (batch, n) = square_matrices(self.name(), &x.aval())?;
1597        let count = batch.iter().product();
1598        let (h, taus) = with_float!(self.name(), x, |a: T| {
1599            let (h, taus) = k::hessenberg::<T>(a, count, n);
1600            (Buffer::from_vec(h), Buffer::from_vec(taus))
1601        });
1602        Ok(vec![
1603            HostArray::from_buffer(h, outs[0].shape.clone()),
1604            HostArray::from_buffer(taus, outs[1].shape.clone()),
1605        ])
1606    }
1607
1608    fn batch(
1609        &'static self,
1610        cx: &mut dyn BatchCx,
1611        inputs: &[Batched],
1612        params: &Params,
1613    ) -> Result<Vec<Batched>> {
1614        batch_leading(cx, HESSENBERG, inputs, params)
1615    }
1616
1617    fn lower(
1618        &self,
1619        cx: &mut dyn LowerCx,
1620        inputs: &[HloValue],
1621        _: &Params,
1622        outputs: &[AVal],
1623    ) -> Result<Vec<HloValue>> {
1624        let a = &inputs[0];
1625        let (batch, n) = square_matrices(self.name(), &a.aval)?;
1626        let abi = abi(cx);
1627        if abi == Abi::Ruxla {
1628            return Ok(ruxla_call(cx, "ruxla_hessenberg", inputs, outputs, ""));
1629        }
1630        cpu_only(self.name(), abi)?;
1631        let results = [outputs[0].clone(), outputs[1].clone(), info_aval(&batch)];
1632        let config = format!("high = {n} : i32, low = 1 : i32");
1633        let mut outs = jax_call(
1634            cx,
1635            &lapack_target("gehrd", a.aval.dtype),
1636            inputs,
1637            &results,
1638            &config,
1639            &[(0, 0)],
1640        );
1641        let info = outs.pop().expect("info");
1642        let ok = info_ok(cx, &info, false);
1643        let taus = outs.pop().expect("taus");
1644        let h = outs.pop().expect("h");
1645        Ok(vec![
1646            replace_not_ok_with_nan(cx, &ok, h),
1647            replace_not_ok_with_nan(cx, &ok, taus),
1648        ])
1649    }
1650}
1651
1652/// `householder_product`.
1653#[derive(Debug)]
1654pub(crate) struct HouseholderProduct;
1655/// The first `n` columns of the product of the Householder reflectors below
1656/// the diagonal of `a` (`[..., m, n]`, `m >= n`) with the factors `taus`
1657/// (`[..., k]`, `k <= n`), as JAX's `householder_product_p` (LAPACK's
1658/// `orgqr`). Not differentiable, as in JAX.
1659pub static HOUSEHOLDER_PRODUCT: Prim = Prim::new(&HouseholderProduct);
1660
1661/// Checks the reflectors `a` and the factors `taus` and returns the batch
1662/// dimensions, the shape of `a`, and the number of reflectors.
1663fn reflectors(
1664    prim: &'static str,
1665    a: &AVal,
1666    taus: &AVal,
1667) -> Result<(Vec<usize>, usize, usize, usize)> {
1668    let (batch, m, n) = matrices(prim, a)?;
1669    let r = taus.shape.rank();
1670    if taus.dtype != a.dtype || r == 0 || taus.shape.dims()[..r - 1] != batch[..] {
1671        return Err(Error::type_error(
1672            prim,
1673            format!("the factors {taus} do not match the reflectors {a}"),
1674        ));
1675    }
1676    let k = taus.shape[r - 1];
1677    if k > m.min(n) {
1678        return Err(Error::type_error(
1679            prim,
1680            format!("{k} factors for reflectors {a}"),
1681        ));
1682    }
1683    Ok((batch, m, n, k))
1684}
1685
1686impl Primitive for HouseholderProduct {
1687    fn name(&self) -> &'static str {
1688        "householder_product"
1689    }
1690
1691    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1692        arity(self.name(), inputs, 2)?;
1693        no_params(self.name(), params)?;
1694        let (_, m, n, _) = reflectors(self.name(), &inputs[0], &inputs[1])?;
1695        if m < n {
1696            return Err(Error::type_error(
1697                self.name(),
1698                format!(
1699                    "the reflectors need at least as many rows as columns, got {}",
1700                    inputs[0]
1701                ),
1702            ));
1703        }
1704        Ok(vec![inputs[0].clone()])
1705    }
1706
1707    fn eval(
1708        &self,
1709        _: &dyn EvalCx,
1710        inputs: &[HostArray],
1711        params: &Params,
1712    ) -> Result<Vec<HostArray>> {
1713        self.abstract_eval(&[inputs[0].aval(), inputs[1].aval()], params)?;
1714        let (a, taus) = (&inputs[0], &inputs[1]);
1715        let (batch, m, n, k) = reflectors(self.name(), &a.aval(), &taus.aval())?;
1716        let count = batch.iter().product();
1717        let q = with_float!(self.name(), a, |av: T| {
1718            Buffer::from_vec(k::householder_product::<T>(
1719                av,
1720                taus.as_slice::<T>()?,
1721                count,
1722                m,
1723                n,
1724                k,
1725            ))
1726        });
1727        Ok(vec![HostArray::from_buffer(q, a.shape().clone())])
1728    }
1729
1730    fn batch(
1731        &'static self,
1732        cx: &mut dyn BatchCx,
1733        inputs: &[Batched],
1734        params: &Params,
1735    ) -> Result<Vec<Batched>> {
1736        batch_leading(cx, HOUSEHOLDER_PRODUCT, inputs, params)
1737    }
1738
1739    fn lower(
1740        &self,
1741        cx: &mut dyn LowerCx,
1742        inputs: &[HloValue],
1743        _: &Params,
1744        outputs: &[AVal],
1745    ) -> Result<Vec<HloValue>> {
1746        if xla_gpu(cx) {
1747            return Ok(xla_call(
1748                cx,
1749                "ProductOfElementaryHouseholderReflectors",
1750                inputs,
1751                outputs,
1752            ));
1753        }
1754        let target = match abi(cx) {
1755            Abi::Ruxla => {
1756                return Ok(ruxla_call(
1757                    cx,
1758                    "ruxla_householder_product",
1759                    inputs,
1760                    outputs,
1761                    "",
1762                ));
1763            }
1764            Abi::Lapack => {
1765                let dtype = inputs[0].aval.dtype;
1766                lapack_target(if dtype.is_complex() { "ungqr" } else { "orgqr" }, dtype)
1767            }
1768            Abi::Cusolver => String::from("cusolver_orgqr_ffi"),
1769        };
1770        Ok(jax_call(cx, &target, inputs, outputs, "", &[(0, 0)]))
1771    }
1772}
1773
1774/// `ormqr`.
1775#[derive(Debug)]
1776pub(crate) struct Ormqr;
1777/// The product of `c` with `Q` (or `Q^H`) of the Householder reflectors of
1778/// `a` and the factors `taus`, from the left or the right
1779/// ([`Params::Ormqr`]), without forming `Q`, as JAX's `ormqr_p` (LAPACK's
1780/// `ormqr`). Not differentiable, as in JAX.
1781pub static ORMQR: Prim = Prim::new(&Ormqr);
1782
1783fn ormqr_params(prim: &'static str, params: &Params) -> Result<(bool, bool)> {
1784    match *params {
1785        Params::Ormqr { left, transpose } => Ok((left, transpose)),
1786        _ => Err(wrong_params(prim)),
1787    }
1788}
1789
1790impl Primitive for Ormqr {
1791    fn name(&self) -> &'static str {
1792        "ormqr"
1793    }
1794
1795    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1796        arity(self.name(), inputs, 3)?;
1797        let (left, _) = ormqr_params(self.name(), params)?;
1798        let (batch, m, _, _) = reflectors(self.name(), &inputs[0], &inputs[1])?;
1799        let (cbatch, rows, cols) = matrices(self.name(), &inputs[2])?;
1800        let matching = if left { rows } else { cols };
1801        if cbatch != batch || inputs[2].dtype != inputs[0].dtype || matching != m {
1802            return Err(Error::type_error(
1803                self.name(),
1804                format!(
1805                    "incompatible reflectors {} and matrices {}",
1806                    inputs[0], inputs[2]
1807                ),
1808            ));
1809        }
1810        Ok(vec![inputs[2].clone()])
1811    }
1812
1813    fn eval(
1814        &self,
1815        _: &dyn EvalCx,
1816        inputs: &[HostArray],
1817        params: &Params,
1818    ) -> Result<Vec<HostArray>> {
1819        let (left, transpose) = ormqr_params(self.name(), params)?;
1820        let avals: Vec<AVal> = inputs.iter().map(HostArray::aval).collect();
1821        self.abstract_eval(&avals, params)?;
1822        let (a, taus, c) = (&inputs[0], &inputs[1], &inputs[2]);
1823        let (batch, m, n, kk) = reflectors(self.name(), &avals[0], &avals[1])?;
1824        let (_, rows, cols) = matrices(self.name(), &avals[2])?;
1825        let count = batch.iter().product();
1826        let out = with_float!(self.name(), a, |av: T| {
1827            Buffer::from_vec(k::ormqr::<T>(
1828                av,
1829                taus.as_slice::<T>()?,
1830                c.as_slice::<T>()?,
1831                count,
1832                (m, n, kk),
1833                (rows, cols),
1834                left,
1835                transpose,
1836            ))
1837        });
1838        Ok(vec![HostArray::from_buffer(out, c.shape().clone())])
1839    }
1840
1841    fn batch(
1842        &'static self,
1843        cx: &mut dyn BatchCx,
1844        inputs: &[Batched],
1845        params: &Params,
1846    ) -> Result<Vec<Batched>> {
1847        batch_leading(cx, ORMQR, inputs, params)
1848    }
1849
1850    fn lower(
1851        &self,
1852        cx: &mut dyn LowerCx,
1853        inputs: &[HloValue],
1854        params: &Params,
1855        outputs: &[AVal],
1856    ) -> Result<Vec<HloValue>> {
1857        let (left, transpose) = ormqr_params(self.name(), params)?;
1858        let config = format!("left = {left}, transpose = {transpose}");
1859        let target = match abi(cx) {
1860            Abi::Ruxla => return Ok(ruxla_call(cx, "ruxla_ormqr", inputs, outputs, &config)),
1861            Abi::Lapack => {
1862                let dtype = inputs[0].aval.dtype;
1863                lapack_target(if dtype.is_complex() { "unmqr" } else { "ormqr" }, dtype)
1864            }
1865            Abi::Cusolver => String::from("cusolver_ormqr_ffi"),
1866        };
1867        Ok(jax_call(cx, &target, inputs, outputs, &config, &[(2, 0)]))
1868    }
1869}
1870
1871// --- tridiagonal -----------------------------------------------------------
1872
1873/// `tridiagonal`.
1874#[derive(Debug)]
1875pub(crate) struct Tridiagonal;
1876/// The reduction of each Hermitian (symmetric) matrix, read from its lower
1877/// (or upper) triangle ([`Params::Tridiagonal`]), to real tridiagonal form
1878/// by a unitary similarity, as JAX's `tridiagonal_p` (LAPACK's `sytrd` and
1879/// `hetrd`): the matrix with the tridiagonal form and the Householder
1880/// reflectors in that triangle (the other one untouched), the real
1881/// diagonal `d`, the real off-diagonal `e`, and the `n - 1` factors `taus`.
1882/// Not differentiable, as in JAX.
1883pub static TRIDIAGONAL: Prim = Prim::new(&Tridiagonal);
1884
1885fn tridiagonal_params(prim: &'static str, params: &Params) -> Result<bool> {
1886    match *params {
1887        Params::Tridiagonal { lower } => Ok(lower),
1888        _ => Err(wrong_params(prim)),
1889    }
1890}
1891
1892impl Primitive for Tridiagonal {
1893    fn name(&self) -> &'static str {
1894        "tridiagonal"
1895    }
1896
1897    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
1898        arity(self.name(), inputs, 1)?;
1899        tridiagonal_params(self.name(), params)?;
1900        let a = &inputs[0];
1901        let (batch, n) = square_matrices(self.name(), a)?;
1902        if n == 0 {
1903            return Err(Error::type_error(
1904                self.name(),
1905                format!("expected nonempty square matrices, got {a}"),
1906            ));
1907        }
1908        let real = a.dtype.real_dtype();
1909        Ok(vec![
1910            a.clone(),
1911            batched_vec(&batch, n, real),
1912            batched_vec(&batch, n - 1, real),
1913            batched_vec(&batch, n - 1, a.dtype),
1914        ])
1915    }
1916
1917    fn eval(
1918        &self,
1919        _: &dyn EvalCx,
1920        inputs: &[HostArray],
1921        params: &Params,
1922    ) -> Result<Vec<HostArray>> {
1923        let lower = tridiagonal_params(self.name(), params)?;
1924        let x = &inputs[0];
1925        let outs = self.abstract_eval(&[x.aval()], params)?;
1926        let (batch, n) = square_matrices(self.name(), &x.aval())?;
1927        let count = batch.iter().product();
1928        let results = with_float!(self.name(), x, |a: T| {
1929            let (a, d, e, taus) = k::tridiagonal::<T>(a, count, n, lower);
1930            [
1931                Buffer::from_vec(a),
1932                Buffer::from_vec(d),
1933                Buffer::from_vec(e),
1934                Buffer::from_vec(taus),
1935            ]
1936        });
1937        Ok(results
1938            .into_iter()
1939            .zip(&outs)
1940            .map(|(b, o)| HostArray::from_buffer(b, o.shape.clone()))
1941            .collect())
1942    }
1943
1944    fn batch(
1945        &'static self,
1946        cx: &mut dyn BatchCx,
1947        inputs: &[Batched],
1948        params: &Params,
1949    ) -> Result<Vec<Batched>> {
1950        batch_leading(cx, TRIDIAGONAL, inputs, params)
1951    }
1952
1953    fn lower(
1954        &self,
1955        cx: &mut dyn LowerCx,
1956        inputs: &[HloValue],
1957        params: &Params,
1958        outputs: &[AVal],
1959    ) -> Result<Vec<HloValue>> {
1960        let lower = tridiagonal_params(self.name(), params)?;
1961        let a = &inputs[0];
1962        let (batch, _) = square_matrices(self.name(), &a.aval)?;
1963        let (target, config) = match abi(cx) {
1964            Abi::Ruxla => {
1965                let config = format!("lower = {lower}");
1966                return Ok(ruxla_call(
1967                    cx,
1968                    "ruxla_tridiagonal",
1969                    inputs,
1970                    outputs,
1971                    &config,
1972                ));
1973            }
1974            Abi::Lapack => {
1975                let dtype = a.aval.dtype;
1976                let name = if dtype.is_complex() { "hetrd" } else { "sytrd" };
1977                (
1978                    lapack_target(name, dtype),
1979                    char_attr("uplo", if lower { 'L' } else { 'U' }),
1980                )
1981            }
1982            Abi::Cusolver => (
1983                String::from("cusolver_sytrd_ffi"),
1984                format!("lower = {lower}"),
1985            ),
1986        };
1987        let mut results = outputs.to_vec();
1988        results.push(info_aval(&batch));
1989        let mut outs = jax_call(cx, &target, inputs, &results, &config, &[(0, 0)]);
1990        let info = outs.pop().expect("info");
1991        let ok = info_ok(cx, &info, false);
1992        Ok(outs
1993            .into_iter()
1994            .map(|x| replace_not_ok_with_nan(cx, &ok, x))
1995            .collect())
1996    }
1997}
1998
1999// --- tridiagonal_solve -----------------------------------------------------
2000
2001/// `tridiagonal_solve`.
2002#[derive(Debug)]
2003pub(crate) struct TridiagonalSolve;
2004/// The solution `x` of `A x = b` for each tridiagonal matrix `A`, given by
2005/// its diagonals `dl` (`dl[..., i] = A[i, i - 1]`, `dl[..., 0]` ignored),
2006/// `d`, and `du` (`du[..., i] = A[i, i + 1]`, the last one ignored), each
2007/// `[..., m]`, and `b` (`[..., m, n]`), as JAX's `tridiagonal_solve_p`
2008/// ([`Params::TridiagonalSolve`]): Gaussian elimination with partial
2009/// pivoting, where singular systems give NaNs, or with `perturb_singular`,
2010/// tiny pivots perturbed so that numerically singular systems give finite
2011/// solutions. Differentiable in all inputs, linear in `b`.
2012pub static TRIDIAGONAL_SOLVE: Prim = Prim::new(&TridiagonalSolve);
2013
2014fn tridiagonal_solve_params(prim: &'static str, params: &Params) -> Result<bool> {
2015    match *params {
2016        Params::TridiagonalSolve { perturb_singular } => Ok(perturb_singular),
2017        _ => Err(wrong_params(prim)),
2018    }
2019}
2020
2021impl Primitive for TridiagonalSolve {
2022    fn name(&self) -> &'static str {
2023        "tridiagonal_solve"
2024    }
2025
2026    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
2027        arity(self.name(), inputs, 4)?;
2028        tridiagonal_solve_params(self.name(), params)?;
2029        let b = &inputs[3];
2030        let (batch, m, _) = matrices(self.name(), b)?;
2031        let diagonal = batched_vec(&batch, m, b.dtype);
2032        if inputs[..3].iter().any(|x| *x != diagonal) {
2033            return Err(Error::type_error(
2034                self.name(),
2035                format!(
2036                    "the diagonals must be {diagonal} for b of {b}, got {}, {}, and {}",
2037                    inputs[0], inputs[1], inputs[2]
2038                ),
2039            ));
2040        }
2041        Ok(vec![b.clone()])
2042    }
2043
2044    fn eval(
2045        &self,
2046        _: &dyn EvalCx,
2047        inputs: &[HostArray],
2048        params: &Params,
2049    ) -> Result<Vec<HostArray>> {
2050        let perturb = tridiagonal_solve_params(self.name(), params)?;
2051        let avals: Vec<AVal> = inputs.iter().map(HostArray::aval).collect();
2052        self.abstract_eval(&avals, params)?;
2053        let b = &inputs[3];
2054        let (batch, m, n) = matrices(self.name(), &avals[3])?;
2055        let count = batch.iter().product();
2056        let out = with_float!(self.name(), b, |bv: T| {
2057            Buffer::from_vec(k::tridiagonal_solve::<T>(
2058                inputs[0].as_slice::<T>()?,
2059                inputs[1].as_slice::<T>()?,
2060                inputs[2].as_slice::<T>()?,
2061                bv,
2062                count,
2063                m,
2064                n,
2065                perturb,
2066            ))
2067        });
2068        Ok(vec![HostArray::from_buffer(out, b.shape().clone())])
2069    }
2070
2071    /// JAX's `_tridiagonal_solve_batching_rule`: with unbatched diagonals,
2072    /// the batch of `b` is folded into its columns; otherwise every
2073    /// operand is batched first.
2074    fn batch(
2075        &'static self,
2076        cx: &mut dyn BatchCx,
2077        inputs: &[Batched],
2078        params: &Params,
2079    ) -> Result<Vec<Batched>> {
2080        let y = &inputs[3];
2081        if inputs[..3].iter().any(|x| x.bdim.is_some()) || y.bdim.is_none() {
2082            return batch_leading(cx, TRIDIAGONAL_SOLVE, inputs, params);
2083        }
2084        // `[..., m, n]` with the batch dimension moved last, folded into
2085        // the columns.
2086        let rank = y.atom.aval().shape.rank();
2087        let moved = b::move_bdim(cx, y, rank - 1)?;
2088        let moved_shape = moved.aval().shape;
2089        let mut flat = moved_shape.dims().to_vec();
2090        let last = flat.pop().expect("rank") * flat.pop().expect("rank");
2091        flat.push(last);
2092        let y_flat = b::bind1(
2093            cx,
2094            RESHAPE,
2095            &[moved],
2096            Params::Reshape {
2097                new_sizes: flat.into(),
2098            },
2099        )?;
2100        let mut atoms: Vec<Atom> = inputs[..3].iter().map(|x| x.atom.clone()).collect();
2101        atoms.push(y_flat);
2102        let out = b::bind1(cx, TRIDIAGONAL_SOLVE, &atoms, params.clone())?;
2103        let out = b::bind1(
2104            cx,
2105            RESHAPE,
2106            &[out],
2107            Params::Reshape {
2108                new_sizes: moved_shape,
2109            },
2110        )?;
2111        Ok(vec![Batched::mapped(out, rank - 1)])
2112    }
2113
2114    fn lower(
2115        &self,
2116        cx: &mut dyn LowerCx,
2117        inputs: &[HloValue],
2118        params: &Params,
2119        outputs: &[AVal],
2120    ) -> Result<Vec<HloValue>> {
2121        let perturb = tridiagonal_solve_params(self.name(), params)?;
2122        let b_aval = &inputs[3].aval;
2123        let (batch, m, _) = matrices(self.name(), b_aval)?;
2124        match abi(cx) {
2125            Abi::Ruxla => {
2126                let config = format!("perturb_singular = {perturb}");
2127                Ok(ruxla_call(
2128                    cx,
2129                    "ruxla_tridiagonal_solve",
2130                    inputs,
2131                    outputs,
2132                    &config,
2133                ))
2134            }
2135            Abi::Lapack if perturb => Ok(jax_call(
2136                cx,
2137                "tridiagonal_solve_perturbed_ffi",
2138                inputs,
2139                outputs,
2140                "",
2141                &[],
2142            )),
2143            Abi::Lapack => {
2144                let target = lapack_target("gtsv", b_aval.dtype);
2145                let mut results: Vec<AVal> = inputs.iter().map(|x| x.aval.clone()).collect();
2146                results.push(info_aval(&batch));
2147                let aliases = [(0, 0), (1, 1), (2, 2), (3, 3)];
2148                let mut outs = jax_call(cx, &target, inputs, &results, "", &aliases);
2149                let info = outs.pop().expect("info");
2150                let ok = info_ok(cx, &info, false);
2151                let x = outs.pop().expect("b");
2152                Ok(vec![replace_not_ok_with_nan(cx, &ok, x)])
2153            }
2154            Abi::Cusolver if perturb => Ok(jax_call(
2155                cx,
2156                "cu_tridiagonal_solve_perturbed",
2157                inputs,
2158                outputs,
2159                "",
2160                &[],
2161            )),
2162            // cuSPARSE's `gtsv2` needs `m >= 3`; JAX solves smaller
2163            // systems with its own elimination without pivoting.
2164            Abi::Cusolver if m <= 2 => Ok(vec![thomas_small(cx, inputs, m)]),
2165            Abi::Cusolver => Ok(jax_call(
2166                cx,
2167                "cusparse_gtsv2_ffi",
2168                inputs,
2169                outputs,
2170                "",
2171                &[(3, 0)],
2172            )),
2173        }
2174    }
2175
2176    fn jvp(
2177        &'static self,
2178        cx: &mut dyn AdCx,
2179        primals: &[Atom],
2180        tangents: &[Tangent],
2181        params: &Params,
2182    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
2183        lad::tridiagonal_solve_jvp(cx, primals, tangents, params)
2184    }
2185
2186    fn transpose(
2187        &'static self,
2188        cx: &mut dyn AdCx,
2189        cotangents: &[Tangent],
2190        inputs: &[TransposeInput],
2191        params: &Params,
2192    ) -> Result<Vec<Tangent>> {
2193        lad::tridiagonal_solve_transpose(cx, &cotangents[0], inputs, params)
2194    }
2195}
2196
2197/// JAX's `_tridiagonal_solve_jax_impl` (the Thomas algorithm, without
2198/// pivoting) for `m <= 2`, which JAX lowers on GPU in place of cuSPARSE:
2199/// `x[0] = b[0] / d[0]` for `m = 1`; for `m = 2`, with `c = du[0] / d[0]`
2200/// and `p = b[0] / d[0]`, `x[1] = (b[1] - dl[1] p) / (d[1] - dl[1] c)` and
2201/// `x[0] = p - c x[1]`.
2202fn thomas_small(cx: &mut dyn LowerCx, inputs: &[HloValue], m: usize) -> HloValue {
2203    let b = &inputs[3];
2204    if m == 0 {
2205        return b.clone();
2206    }
2207    let dims = b.aval.shape.dims().to_vec();
2208    let rank = dims.len();
2209    let dtype = b.aval.dtype;
2210    let mut row_dims = dims.clone();
2211    row_dims[rank - 2] = 1;
2212    let row_aval = AVal::new(row_dims.clone(), dtype);
2213    // `x[..., i]` of a diagonal, broadcast to a row of `b` (`[..., 1, n]`).
2214    let entry = |cx: &mut dyn LowerCx, x: &HloValue, i: usize| {
2215        let mut start = vec![0; rank - 1];
2216        let mut limit = dims[..rank - 1].to_vec();
2217        start[rank - 2] = i;
2218        limit[rank - 2] = i + 1;
2219        let attrs = format!(
2220            "start_indices = {}, limit_indices = {}, strides = {}",
2221            i64_array(&start),
2222            i64_array(&limit),
2223            i64_array(&vec![1; rank - 1])
2224        );
2225        let sliced = cx.op1(
2226            "stablehlo.slice",
2227            std::slice::from_ref(x),
2228            &attrs,
2229            &AVal::new(
2230                limit
2231                    .iter()
2232                    .zip(&start)
2233                    .map(|(l, s)| l - s)
2234                    .collect::<Vec<_>>(),
2235                dtype,
2236            ),
2237        );
2238        let broadcast_dims: Vec<usize> = (0..rank - 1).collect();
2239        cx.op1(
2240            "stablehlo.broadcast_in_dim",
2241            &[sliced],
2242            &format!("broadcast_dimensions = {}", i64_array(&broadcast_dims)),
2243            &row_aval,
2244        )
2245    };
2246    // Row `i` of `b`.
2247    let row = |cx: &mut dyn LowerCx, i: usize| {
2248        let mut start = vec![0; rank];
2249        let mut limit = dims.clone();
2250        start[rank - 2] = i;
2251        limit[rank - 2] = i + 1;
2252        let attrs = format!(
2253            "start_indices = {}, limit_indices = {}, strides = {}",
2254            i64_array(&start),
2255            i64_array(&limit),
2256            i64_array(&vec![1; rank])
2257        );
2258        cx.op1(
2259            "stablehlo.slice",
2260            std::slice::from_ref(b),
2261            &attrs,
2262            &row_aval,
2263        )
2264    };
2265    let bin = |cx: &mut dyn LowerCx, op: &str, a: &HloValue, c: &HloValue| {
2266        cx.op1(op, &[a.clone(), c.clone()], "", &row_aval)
2267    };
2268    let d0 = entry(cx, &inputs[1], 0);
2269    let b0 = row(cx, 0);
2270    let p = bin(cx, "stablehlo.divide", &b0, &d0);
2271    if m == 1 {
2272        return p;
2273    }
2274    let du0 = entry(cx, &inputs[2], 0);
2275    let c = bin(cx, "stablehlo.divide", &du0, &d0);
2276    let dl1 = entry(cx, &inputs[0], 1);
2277    let d1 = entry(cx, &inputs[1], 1);
2278    let b1 = row(cx, 1);
2279    let t = bin(cx, "stablehlo.multiply", &dl1, &c);
2280    let denominator = bin(cx, "stablehlo.subtract", &d1, &t);
2281    let t = bin(cx, "stablehlo.multiply", &dl1, &p);
2282    let numerator = bin(cx, "stablehlo.subtract", &b1, &t);
2283    let x1 = bin(cx, "stablehlo.divide", &numerator, &denominator);
2284    let t = bin(cx, "stablehlo.multiply", &c, &x1);
2285    let x0 = bin(cx, "stablehlo.subtract", &p, &t);
2286    cx.op1(
2287        "stablehlo.concatenate",
2288        &[x0, x1],
2289        &format!("dimension = {} : i64", rank - 2),
2290        &b.aval,
2291    )
2292}
2293
2294// --- cholesky_update and symmetric_product --------------------------------
2295
2296/// Checks real (`f32` or `f64`) matrices.
2297fn real_matrices(prim: &'static str, a: &AVal) -> Result<(Vec<usize>, usize, usize)> {
2298    if !matches!(a.dtype, DType::F32 | DType::F64) {
2299        return Err(Error::type_error(
2300            prim,
2301            format!("expected f32 or f64 matrices, got {a}"),
2302        ));
2303    }
2304    matrices(prim, a)
2305}
2306
2307/// `cholesky_update`.
2308#[derive(Debug)]
2309pub(crate) struct CholeskyUpdate;
2310/// The rank-1 update of each upper triangular Cholesky factor `r`
2311/// (`a = r^T r`) by the vector `w`: the factor of `a + w w^T`, as JAX's
2312/// `cholesky_update_p` (real matrices; Givens rotations, as JAX computes
2313/// it on CPU). Not differentiable, as in JAX.
2314pub static CHOLESKY_UPDATE: Prim = Prim::new(&CholeskyUpdate);
2315
2316impl Primitive for CholeskyUpdate {
2317    fn name(&self) -> &'static str {
2318        "cholesky_update"
2319    }
2320
2321    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
2322        arity(self.name(), inputs, 2)?;
2323        no_params(self.name(), params)?;
2324        let (r, w) = (&inputs[0], &inputs[1]);
2325        let (batch, n, cols) = real_matrices(self.name(), r)?;
2326        if cols != n || *w != batched_vec(&batch, n, r.dtype) {
2327            return Err(Error::type_error(
2328                self.name(),
2329                format!("expected a square matrix and a vector of its size, got {r} and {w}"),
2330            ));
2331        }
2332        Ok(vec![r.clone()])
2333    }
2334
2335    fn eval(
2336        &self,
2337        _: &dyn EvalCx,
2338        inputs: &[HostArray],
2339        params: &Params,
2340    ) -> Result<Vec<HostArray>> {
2341        let avals: Vec<AVal> = inputs.iter().map(HostArray::aval).collect();
2342        self.abstract_eval(&avals, params)?;
2343        let (batch, n, _) = matrices(self.name(), &avals[0])?;
2344        let count = batch.iter().product();
2345        let (r, w) = (&inputs[0], &inputs[1]);
2346        let out = match (r.buffer(), w.buffer()) {
2347            (Buffer::F32(r), Buffer::F32(w)) => {
2348                Buffer::from_vec(k::cholesky_update(r, w, count, n))
2349            }
2350            (Buffer::F64(r), Buffer::F64(w)) => {
2351                Buffer::from_vec(k::cholesky_update(r, w, count, n))
2352            }
2353            _ => return Err(not_float(self.name(), &avals[0])),
2354        };
2355        Ok(vec![HostArray::from_buffer(out, r.shape().clone())])
2356    }
2357
2358    fn batch(
2359        &'static self,
2360        cx: &mut dyn BatchCx,
2361        inputs: &[Batched],
2362        params: &Params,
2363    ) -> Result<Vec<Batched>> {
2364        batch_leading(cx, CHOLESKY_UPDATE, inputs, params)
2365    }
2366
2367    fn lower(
2368        &self,
2369        cx: &mut dyn LowerCx,
2370        inputs: &[HloValue],
2371        _: &Params,
2372        _: &[AVal],
2373    ) -> Result<Vec<HloValue>> {
2374        // JAX calls its CUDA kernel for single matrices, and otherwise
2375        // lowers its Givens rotations, as here.
2376        if abi(cx) == Abi::Cusolver && inputs[0].aval.shape.rank() == 2 {
2377            let results = [inputs[0].aval.clone(), inputs[1].aval.clone()];
2378            let mut outs = ffi_call(
2379                cx,
2380                &FfiCall {
2381                    target: "cu_cholesky_update_ffi",
2382                    operands: inputs,
2383                    results: &results,
2384                    config: "",
2385                    column_major: false,
2386                    aliases: &[(0, 0), (1, 1)],
2387                    num_non_batch_dims: None,
2388                },
2389            );
2390            outs.truncate(1);
2391            return Ok(outs);
2392        }
2393        Ok(vec![givens_update(cx, &inputs[0], &inputs[1])])
2394    }
2395}
2396
2397/// JAX's `_cholesky_update_jax_fn` in StableHLO: for each `k`, the Givens
2398/// rotation `(c, s)` of `_drotg(r[k, k], z[k])` (`(1, 0)` for `z[k] = 0`)
2399/// turns the row `r[k]` into `c r[k] - s z` and `z` into `c z + s r[k]`.
2400fn givens_update(cx: &mut dyn LowerCx, r: &HloValue, w: &HloValue) -> HloValue {
2401    let dims = r.aval.shape.dims().to_vec();
2402    let rank = dims.len();
2403    let n = dims[rank - 1];
2404    if n == 0 {
2405        return r.clone();
2406    }
2407    let dtype = r.aval.dtype;
2408    let batch = &dims[..rank - 2];
2409    let scalar_aval = AVal::new(batch.to_vec(), dtype);
2410    let row_aval = w.aval.clone();
2411    let mut row_dims = dims.clone();
2412    row_dims[rank - 2] = 1;
2413    let row1_aval = AVal::new(row_dims, dtype);
2414    let slice = |cx: &mut dyn LowerCx, x: &HloValue, start: &[usize], limit: &[usize]| {
2415        let attrs = format!(
2416            "start_indices = {}, limit_indices = {}, strides = {}",
2417            i64_array(start),
2418            i64_array(limit),
2419            i64_array(&vec![1; start.len()])
2420        );
2421        let shape: Vec<usize> = limit.iter().zip(start).map(|(l, s)| l - s).collect();
2422        cx.op1(
2423            "stablehlo.slice",
2424            std::slice::from_ref(x),
2425            &attrs,
2426            &AVal::new(shape, dtype),
2427        )
2428    };
2429    let reshape = |cx: &mut dyn LowerCx, x: HloValue, aval: &AVal| {
2430        cx.op1("stablehlo.reshape", &[x], "", aval)
2431    };
2432    let bin = |cx: &mut dyn LowerCx, op: &str, a: &HloValue, b: &HloValue, aval: &AVal| {
2433        cx.op1(op, &[a.clone(), b.clone()], "", aval)
2434    };
2435    let compare = |cx: &mut dyn LowerCx, dir: &str, a: &HloValue, b: &HloValue| {
2436        cx.op1(
2437            "stablehlo.compare",
2438            &[a.clone(), b.clone()],
2439            &format!(
2440                "comparison_direction = #stablehlo<comparison_direction {dir}>, \
2441                 compare_type = #stablehlo<comparison_type FLOAT>"
2442            ),
2443            &AVal::new(batch.to_vec(), DType::Bool),
2444        )
2445    };
2446    let broadcast_dims: Vec<usize> = (0..rank - 2).collect();
2447    let to_row = |cx: &mut dyn LowerCx, x: &HloValue| {
2448        cx.op1(
2449            "stablehlo.broadcast_in_dim",
2450            std::slice::from_ref(x),
2451            &format!("broadcast_dimensions = {}", i64_array(&broadcast_dims)),
2452            &row_aval,
2453        )
2454    };
2455    let zero = cx.splat(Value::Float(0.0), &scalar_aval);
2456    let one = cx.splat(Value::Float(1.0), &scalar_aval);
2457    let mut z = w.clone();
2458    let mut rows = Vec::with_capacity(n);
2459    for k in 0..n {
2460        let mut start = vec![0; rank];
2461        let mut limit = dims.clone();
2462        start[rank - 2] = k;
2463        limit[rank - 2] = k + 1;
2464        let row = slice(cx, r, &start, &limit);
2465        let row = reshape(cx, row, &row_aval);
2466        let mut start = vec![0; rank - 1];
2467        let mut limit = dims[..rank - 1].to_vec();
2468        start[rank - 2] = k;
2469        limit[rank - 2] = k + 1;
2470        let x = slice(cx, &row, &start, &limit);
2471        let x = reshape(cx, x, &scalar_aval);
2472        let y = slice(cx, &z, &start, &limit);
2473        let y = reshape(cx, y, &scalar_aval);
2474        // `_drotg`.
2475        let ax = cx.op1("stablehlo.abs", std::slice::from_ref(&x), "", &scalar_aval);
2476        let ay = cx.op1("stablehlo.abs", std::slice::from_ref(&y), "", &scalar_aval);
2477        let larger = compare(cx, "GT", &ax, &ay);
2478        let denominator = cx.op1("stablehlo.select", &[larger, ax, ay], "", &scalar_aval);
2479        let xs = bin(cx, "stablehlo.divide", &x, &denominator, &scalar_aval);
2480        let ys = bin(cx, "stablehlo.divide", &y, &denominator, &scalar_aval);
2481        let x2 = bin(cx, "stablehlo.multiply", &xs, &xs, &scalar_aval);
2482        let y2 = bin(cx, "stablehlo.multiply", &ys, &ys, &scalar_aval);
2483        let sum = bin(cx, "stablehlo.add", &x2, &y2, &scalar_aval);
2484        let root = cx.op1("stablehlo.sqrt", &[sum], "", &scalar_aval);
2485        let rh = bin(cx, "stablehlo.divide", &one, &root, &scalar_aval);
2486        let c = bin(cx, "stablehlo.multiply", &xs, &rh, &scalar_aval);
2487        let neg_y = cx.op1("stablehlo.negate", &[ys], "", &scalar_aval);
2488        let s = bin(cx, "stablehlo.multiply", &neg_y, &rh, &scalar_aval);
2489        let is_zero = compare(cx, "EQ", &y, &zero);
2490        let c = cx.op1(
2491            "stablehlo.select",
2492            &[is_zero.clone(), one.clone(), c],
2493            "",
2494            &scalar_aval,
2495        );
2496        let s = cx.op1(
2497            "stablehlo.select",
2498            &[is_zero, zero.clone(), s],
2499            "",
2500            &scalar_aval,
2501        );
2502        // `_drot`.
2503        let c = to_row(cx, &c);
2504        let s = to_row(cx, &s);
2505        let cr = bin(cx, "stablehlo.multiply", &c, &row, &row_aval);
2506        let sz = bin(cx, "stablehlo.multiply", &s, &z, &row_aval);
2507        let new_row = bin(cx, "stablehlo.subtract", &cr, &sz, &row_aval);
2508        let cz = bin(cx, "stablehlo.multiply", &c, &z, &row_aval);
2509        let sr = bin(cx, "stablehlo.multiply", &s, &row, &row_aval);
2510        z = bin(cx, "stablehlo.add", &cz, &sr, &row_aval);
2511        rows.push(reshape(cx, new_row, &row1_aval));
2512    }
2513    cx.op1(
2514        "stablehlo.concatenate",
2515        &rows,
2516        &format!("dimension = {} : i64", rank - 2),
2517        &r.aval,
2518    )
2519}
2520
2521/// `symmetric_product`.
2522#[derive(Debug)]
2523pub(crate) struct SymmetricProduct;
2524/// `alpha a a^T + beta c` for each real `a` (`[..., m, n]`) and `c`
2525/// (`[..., m, m]`) ([`Params::SymmetricProduct`]), as JAX's
2526/// `symmetric_product_p`: the whole matrix, as JAX computes it on CPU (on
2527/// GPU, where JAX calls cuBLAS's `syrk`, only the lower triangle is
2528/// guaranteed, as in JAX).
2529/// Not differentiable, as in JAX.
2530pub static SYMMETRIC_PRODUCT: Prim = Prim::new(&SymmetricProduct);
2531
2532fn symmetric_product_params(prim: &'static str, params: &Params) -> Result<(f64, f64)> {
2533    match *params {
2534        Params::SymmetricProduct { alpha, beta } => Ok((alpha, beta)),
2535        _ => Err(wrong_params(prim)),
2536    }
2537}
2538
2539impl Primitive for SymmetricProduct {
2540    fn name(&self) -> &'static str {
2541        "symmetric_product"
2542    }
2543
2544    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
2545        arity(self.name(), inputs, 2)?;
2546        symmetric_product_params(self.name(), params)?;
2547        let (a, c) = (&inputs[0], &inputs[1]);
2548        let (batch, m, _) = real_matrices(self.name(), a)?;
2549        if *c != batched(&batch, m, m, a.dtype) {
2550            return Err(Error::type_error(
2551                self.name(),
2552                format!("expected c of [..., m, m] for a of [..., m, n], got {a} and {c}"),
2553            ));
2554        }
2555        Ok(vec![c.clone()])
2556    }
2557
2558    fn eval(
2559        &self,
2560        _: &dyn EvalCx,
2561        inputs: &[HostArray],
2562        params: &Params,
2563    ) -> Result<Vec<HostArray>> {
2564        let (alpha, beta) = symmetric_product_params(self.name(), params)?;
2565        let avals: Vec<AVal> = inputs.iter().map(HostArray::aval).collect();
2566        self.abstract_eval(&avals, params)?;
2567        let (batch, m, n) = matrices(self.name(), &avals[0])?;
2568        let count = batch.iter().product();
2569        let (a, c) = (&inputs[0], &inputs[1]);
2570        #[allow(clippy::cast_possible_truncation)] // f32 parameters, as JAX's
2571        let out = match (a.buffer(), c.buffer()) {
2572            (Buffer::F32(a), Buffer::F32(c)) => Buffer::from_vec(k::symmetric_product(
2573                a,
2574                c,
2575                count,
2576                m,
2577                n,
2578                alpha as f32,
2579                beta as f32,
2580            )),
2581            (Buffer::F64(a), Buffer::F64(c)) => {
2582                Buffer::from_vec(k::symmetric_product(a, c, count, m, n, alpha, beta))
2583            }
2584            _ => return Err(not_float(self.name(), &avals[0])),
2585        };
2586        Ok(vec![HostArray::from_buffer(out, c.shape().clone())])
2587    }
2588
2589    fn batch(
2590        &'static self,
2591        cx: &mut dyn BatchCx,
2592        inputs: &[Batched],
2593        params: &Params,
2594    ) -> Result<Vec<Batched>> {
2595        batch_leading(cx, SYMMETRIC_PRODUCT, inputs, params)
2596    }
2597
2598    fn lower(
2599        &self,
2600        cx: &mut dyn LowerCx,
2601        inputs: &[HloValue],
2602        params: &Params,
2603        outputs: &[AVal],
2604    ) -> Result<Vec<HloValue>> {
2605        let (alpha, beta) = symmetric_product_params(self.name(), params)?;
2606        let (a, c) = (&inputs[0], &inputs[1]);
2607        if abi(cx) == Abi::Cusolver {
2608            let scalar = AVal::new(Vec::<usize>::new(), a.aval.dtype);
2609            let alpha = cx.splat(Value::Float(alpha), &scalar);
2610            let beta = cx.splat(Value::Float(beta), &scalar);
2611            let operands = [a.clone(), c.clone(), alpha, beta];
2612            return Ok(ffi_call(
2613                cx,
2614                &FfiCall {
2615                    target: "cusolver_syrk_ffi",
2616                    operands: &operands,
2617                    results: outputs,
2618                    config: "transpose = false",
2619                    column_major: false,
2620                    aliases: &[(1, 0)],
2621                    num_non_batch_dims: None,
2622                },
2623            ));
2624        }
2625        // JAX's `_symmetric_product_jax_fn`: `alpha (a a^T) + beta c`.
2626        let rank = a.aval.shape.rank();
2627        let batch: Vec<String> = (0..rank - 2).map(|d| d.to_string()).collect();
2628        let batch = batch.join(", ");
2629        let batching = if rank > 2 {
2630            format!("lhs_batching_dimensions = [{batch}], rhs_batching_dimensions = [{batch}], ")
2631        } else {
2632            String::new()
2633        };
2634        let attrs = format!(
2635            "dot_dimension_numbers = #stablehlo.dot<{batching}lhs_contracting_dimensions = \
2636             [{k}], rhs_contracting_dimensions = [{k}]>, precision_config = \
2637             [#stablehlo<precision HIGHEST>, #stablehlo<precision HIGHEST>]",
2638            k = rank - 1,
2639        );
2640        let product = cx.op1(
2641            "stablehlo.dot_general",
2642            &[a.clone(), a.clone()],
2643            &attrs,
2644            &outputs[0],
2645        );
2646        let alpha = cx.splat(Value::Float(alpha), &outputs[0]);
2647        let beta = cx.splat(Value::Float(beta), &outputs[0]);
2648        let scaled = cx.op1("stablehlo.multiply", &[alpha, product], "", &outputs[0]);
2649        let shifted = cx.op1("stablehlo.multiply", &[beta, c.clone()], "", &outputs[0]);
2650        Ok(vec![cx.op1(
2651            "stablehlo.add",
2652            &[scaled, shifted],
2653            "",
2654            &outputs[0],
2655        )])
2656    }
2657}
2658
2659// --- svd ------------------------------------------------------------------
2660
2661/// `svd`.
2662#[derive(Debug)]
2663pub(crate) struct Svd;
2664/// The singular value decomposition of each matrix ([`Params::Svd`]): the
2665/// singular values `s` in descending order, and with `compute_uv`, `u` and
2666/// `vt` (`a = u diag(s) vt`), as JAX's `svd_p`. With `subset_by_index`
2667/// (not with `full_matrices`), the singular values of that range of
2668/// indices and their vectors (computed from the whole decomposition; JAX
2669/// supports it on TPU only).
2670pub static SVD: Prim = Prim::new(&Svd);
2671
2672fn svd_params(prim: &'static str, params: &Params) -> Result<(bool, bool)> {
2673    match *params {
2674        Params::Svd {
2675            full_matrices,
2676            compute_uv,
2677            ..
2678        } => Ok((full_matrices, compute_uv)),
2679        _ => Err(wrong_params(prim)),
2680    }
2681}
2682
2683/// The types of `u` and `vt` (computed even without `compute_uv`).
2684fn svd_uv_avals(batch: &[usize], m: usize, n: usize, full: bool, dtype: DType) -> (AVal, AVal) {
2685    let k = m.min(n);
2686    if full {
2687        (batched(batch, m, m, dtype), batched(batch, n, n, dtype))
2688    } else {
2689        (batched(batch, m, k, dtype), batched(batch, k, n, dtype))
2690    }
2691}
2692
2693impl Primitive for Svd {
2694    fn name(&self) -> &'static str {
2695        "svd"
2696    }
2697
2698    fn abstract_eval(&self, inputs: &[AVal], params: &Params) -> Result<Vec<AVal>> {
2699        arity(self.name(), inputs, 1)?;
2700        let (full, compute_uv) = svd_params(self.name(), params)?;
2701        let a = &inputs[0];
2702        let (batch, m, n) = matrices(self.name(), a)?;
2703        let (range, _) = split_subset(self.name(), params, m.min(n))?;
2704        if let Some((start, end)) = range {
2705            if full {
2706                return Err(Error::type_error(
2707                    self.name(),
2708                    "full_matrices and subset_by_index cannot both be set",
2709                ));
2710            }
2711            let k = end - start;
2712            let s = batched_vec(&batch, k, a.dtype.real_dtype());
2713            if !compute_uv {
2714                return Ok(vec![s]);
2715            }
2716            return Ok(vec![
2717                s,
2718                batched(&batch, m, k, a.dtype),
2719                batched(&batch, k, n, a.dtype),
2720            ]);
2721        }
2722        let s = batched_vec(&batch, m.min(n), a.dtype.real_dtype());
2723        if !compute_uv {
2724            return Ok(vec![s]);
2725        }
2726        let (u, vt) = svd_uv_avals(&batch, m, n, full, a.dtype);
2727        Ok(vec![s, u, vt])
2728    }
2729
2730    fn eval(
2731        &self,
2732        cx: &dyn EvalCx,
2733        inputs: &[HostArray],
2734        params: &Params,
2735    ) -> Result<Vec<HostArray>> {
2736        let (full, compute_uv) = svd_params(self.name(), params)?;
2737        let x = &inputs[0];
2738        let outs = self.abstract_eval(&[x.aval()], params)?;
2739        let (batch, m, n) = matrices(self.name(), &x.aval())?;
2740        if let (Some(range), whole) = split_subset(self.name(), params, m.min(n))? {
2741            let outs = self.eval(cx, inputs, &whole)?;
2742            let rank = x.shape().rank();
2743            let mut result = vec![slice_host(cx, &outs[0], rank - 2, range)?];
2744            if compute_uv {
2745                result.push(slice_host(cx, &outs[1], rank - 1, range)?);
2746                result.push(slice_host(cx, &outs[2], rank - 2, range)?);
2747            }
2748            return Ok(result);
2749        }
2750        let count = batch.iter().product();
2751        let (s, u, vt) = with_float!(self.name(), x, |a: T| {
2752            let (s, u, vt) = k::svd::<T>(a, count, m, n, full, compute_uv, uses_jacobi(params));
2753            (
2754                Buffer::from_vec(s),
2755                Buffer::from_vec(u),
2756                Buffer::from_vec(vt),
2757            )
2758        });
2759        let mut result = vec![HostArray::from_buffer(s, outs[0].shape.clone())];
2760        if compute_uv {
2761            result.push(HostArray::from_buffer(u, outs[1].shape.clone()));
2762            result.push(HostArray::from_buffer(vt, outs[2].shape.clone()));
2763        }
2764        Ok(result)
2765    }
2766
2767    fn batch(
2768        &'static self,
2769        cx: &mut dyn BatchCx,
2770        inputs: &[Batched],
2771        params: &Params,
2772    ) -> Result<Vec<Batched>> {
2773        batch_leading(cx, SVD, inputs, params)
2774    }
2775
2776    fn lower(
2777        &self,
2778        cx: &mut dyn LowerCx,
2779        inputs: &[HloValue],
2780        params: &Params,
2781        outputs: &[AVal],
2782    ) -> Result<Vec<HloValue>> {
2783        let (full, compute_uv) = svd_params(self.name(), params)?;
2784        let a = &inputs[0];
2785        let (batch, m, n) = matrices(self.name(), &a.aval)?;
2786        if let (Some(range), whole) = split_subset(self.name(), params, m.min(n))? {
2787            let avals = self.abstract_eval(std::slice::from_ref(&a.aval), &whole)?;
2788            let outs = self.lower(cx, inputs, &whole, &avals)?;
2789            let rank = a.aval.shape.rank();
2790            let axes = [rank - 2, rank - 1, rank - 2];
2791            return Ok(outs
2792                .into_iter()
2793                .zip(axes)
2794                .map(|(x, axis)| slice_hlo(cx, x, axis, range))
2795                .collect());
2796        }
2797        let abi = abi(cx);
2798        // On GPU from Rust: cuSOLVER's `gesvdj` on the device, called by
2799        // ruxla's handler, with the phases set as natively.
2800        let device = xla_gpu(cx);
2801        if abi == Abi::Ruxla && !device {
2802            let config = format!(
2803                "compute_uv = {compute_uv}, full_matrices = {full}, jacobi = {}",
2804                uses_jacobi(params)
2805            );
2806            return Ok(ruxla_call(cx, "ruxla_svd", inputs, outputs, &config));
2807        }
2808        let algorithm = match *params {
2809            Params::Svd { algorithm, .. } => algorithm,
2810            _ => None,
2811        };
2812        if m == 0 || n == 0 {
2813            return Ok(empty_svd(cx, outputs, full, compute_uv, m, n));
2814        }
2815        let dtype = a.aval.dtype;
2816        let (s, u, vt, info) = if abi == Abi::Lapack {
2817            let mode = match (compute_uv, full) {
2818                (false, _) => 'N',
2819                (true, true) => 'A',
2820                (true, false) => 'S',
2821            };
2822            let (u_aval, vt_aval) = svd_uv_avals(&batch, m, n, full, dtype);
2823            let results = [
2824                a.aval.clone(),
2825                outputs[0].clone(),
2826                u_aval,
2827                vt_aval,
2828                info_aval(&batch),
2829            ];
2830            let mut outs = jax_call(
2831                cx,
2832                // JAX: `gesvd` for the QR algorithm, `gesdd` otherwise (JAX
2833                // rejects Jacobi and polar on CPU).
2834                &lapack_target(
2835                    if algorithm == Some(SvdAlgorithm::Qr) {
2836                        "gesvd"
2837                    } else {
2838                        "gesdd"
2839                    },
2840                    dtype,
2841                ),
2842                inputs,
2843                &results,
2844                &char_attr("mode", mode),
2845                &[(0, 0)],
2846            );
2847            let info = outs.pop().expect("info");
2848            let vt = outs.pop().expect("vt");
2849            let u = outs.pop().expect("u");
2850            (outs.pop().expect("s"), u, vt, info)
2851        } else {
2852            gpu_svd(
2853                cx,
2854                a,
2855                outputs,
2856                &batch,
2857                (m, n),
2858                full,
2859                compute_uv,
2860                algorithm,
2861                device,
2862            )
2863        };
2864        let ok = info_ok(cx, &info, false);
2865        let mut result = vec![replace_not_ok_with_nan(cx, &ok, s)];
2866        if compute_uv {
2867            let u = replace_not_ok_with_nan(cx, &ok, u);
2868            let vt = replace_not_ok_with_nan(cx, &ok, vt);
2869            let (u, vt) = if device {
2870                svd_phases(cx, u, vt, m.min(n))?
2871            } else {
2872                (u, vt)
2873            };
2874            result.push(u);
2875            result.push(vt);
2876        }
2877        Ok(result)
2878    }
2879
2880    fn jvp(
2881        &'static self,
2882        cx: &mut dyn AdCx,
2883        primals: &[Atom],
2884        tangents: &[Tangent],
2885        params: &Params,
2886    ) -> Result<(Vec<Atom>, Vec<Tangent>)> {
2887        let (full, compute_uv) = svd_params(self.name(), params)?;
2888        let (_, m, n) = matrices(self.name(), &primals[0].aval())?;
2889        let (range, _) = split_subset(self.name(), params, m.min(n))?;
2890        if compute_uv && range.is_some() {
2891            return Err(Error::unsupported(
2892                self.name(),
2893                "the JVP is not implemented for subset_by_index with compute_uv (as in JAX)",
2894            ));
2895        }
2896        let algorithm = match *params {
2897            Params::Svd { algorithm, .. } => algorithm,
2898            _ => None,
2899        };
2900        lad::svd_jvp(
2901            cx,
2902            &primals[0],
2903            &tangents[0],
2904            full,
2905            compute_uv,
2906            range,
2907            algorithm,
2908        )
2909    }
2910}
2911
2912/// JAX's `_empty_svd`, for matrices with no rows or no columns.
2913fn empty_svd(
2914    cx: &mut dyn LowerCx,
2915    outputs: &[AVal],
2916    full: bool,
2917    compute_uv: bool,
2918    m: usize,
2919    n: usize,
2920) -> Vec<HloValue> {
2921    let s = cx.splat(Value::Int(0), &outputs[0]);
2922    if !compute_uv {
2923        return vec![s];
2924    }
2925    // The square factor of the nonempty side is the identity; the others
2926    // are empty or zeros.
2927    let square = |cx: &mut dyn LowerCx, aval: &AVal| {
2928        if full {
2929            eye(cx, aval)
2930        } else {
2931            cx.splat(Value::Int(0), aval)
2932        }
2933    };
2934    let (u, vt) = if m >= n {
2935        (
2936            square(cx, &outputs[1]),
2937            cx.splat(Value::Int(0), &outputs[2]),
2938        )
2939    } else {
2940        (
2941            cx.splat(Value::Int(0), &outputs[1]),
2942            square(cx, &outputs[2]),
2943        )
2944    };
2945    vec![s, u, vt]
2946}
2947
2948/// JAX's `_svd_gpu_sub_lowering` for CUDA: by default Jacobi (`gesvdj`)
2949/// for matrices of up to 1024 rows and columns, `gesvd` otherwise; `gesvd`
2950/// for the QR algorithm, `gesvdj` for Jacobi, `gesvdp` for polar. Returns
2951/// `s`, `u`, `vt`, and `info`.
2952#[allow(clippy::too_many_arguments)] // The shapes and parameters of the call.
2953fn gpu_svd(
2954    cx: &mut dyn LowerCx,
2955    a: &HloValue,
2956    outputs: &[AVal],
2957    batch: &[usize],
2958    (m, n): (usize, usize),
2959    full: bool,
2960    compute_uv: bool,
2961    algorithm: Option<SvdAlgorithm>,
2962    ruxla: bool,
2963) -> (HloValue, HloValue, HloValue, HloValue) {
2964    let dtype = a.aval.dtype;
2965    let k = m.min(n);
2966    let s_aval = outputs[0].clone();
2967    let info = info_aval(batch);
2968    // JAX's `_resolve_gpu_svd_implementation`: Jacobi (`gesvdj`) by default
2969    // up to 1024 x 1024, polar (`gesvdp`), or `gesvd` (for the QR
2970    // algorithm and larger matrices).
2971    let (jacobi_like, target) = match algorithm {
2972        // ruxla's handler of cuSOLVER's `gesvdj` (for every size).
2973        _ if ruxla => (true, "ruxla_cusolver_gesvdj"),
2974        Some(SvdAlgorithm::Qr) => (false, ""),
2975        Some(SvdAlgorithm::Jacobi) => (true, "cusolver_gesvdj_ffi"),
2976        Some(SvdAlgorithm::Polar) => (true, "cusolver_gesvdp_ffi"),
2977        _ if m <= 1024 && n <= 1024 => (true, "cusolver_gesvdj_ffi"),
2978        _ => (false, ""),
2979    };
2980    if jacobi_like {
2981        // `gesvdjBatched` has no economy mode; it is used up to 32 x 32.
2982        let econ = if target == "cusolver_gesvdj_ffi" {
2983            !full && m > 32 && n > 32
2984        } else {
2985            !full
2986        };
2987        let u_aval = batched(batch, m, if econ { k } else { m }, dtype);
2988        let v_aval = batched(batch, n, if econ { k } else { n }, dtype);
2989        let results = [a.aval.clone(), s_aval, u_aval, v_aval, info];
2990        let config = format!("compute_uv = {compute_uv}, full_matrices = {}", !econ);
2991        let mut outs = jax_call(
2992            cx,
2993            target,
2994            std::slice::from_ref(a),
2995            &results,
2996            &config,
2997            &[(0, 0)],
2998        );
2999        let info = outs.pop().expect("info");
3000        let mut vt = outs.pop().expect("v");
3001        let mut u = outs.pop().expect("u");
3002        let s = outs.pop().expect("s");
3003        if compute_uv {
3004            // `V^H` (JAX conjugates the transpose of complex `V`).
3005            vt = transpose_last(cx, vt);
3006            if dtype.is_complex() {
3007                vt = conj_hlo(cx, &vt);
3008            }
3009            if !full && !econ {
3010                let mut lu = batch.to_vec();
3011                lu.extend([m, k]);
3012                u = slice_to(cx, u, &lu);
3013                let mut lv = batch.to_vec();
3014                lv.extend([k, n]);
3015                vt = slice_to(cx, vt, &lv);
3016            }
3017        }
3018        return (s, u, vt, info);
3019    }
3020    let transposed = m < n;
3021    let (u_aval, vt_aval) = if compute_uv {
3022        (outputs[1].clone(), outputs[2].clone())
3023    } else {
3024        (AVal::scalar(dtype), AVal::scalar(dtype))
3025    };
3026    let results = if transposed {
3027        [a.aval.clone(), s_aval, vt_aval, u_aval, info]
3028    } else {
3029        [a.aval.clone(), s_aval, u_aval, vt_aval, info]
3030    };
3031    let config =
3032        format!("compute_uv = {compute_uv}, full_matrices = {full}, transposed = {transposed}");
3033    let mut outs = ffi_call(
3034        cx,
3035        &FfiCall {
3036            target: "cusolver_gesvd_ffi",
3037            operands: std::slice::from_ref(a),
3038            results: &results,
3039            config: &config,
3040            column_major: !transposed,
3041            aliases: &[(0, 0)],
3042            num_non_batch_dims: Some(2),
3043        },
3044    );
3045    let info = outs.pop().expect("info");
3046    let second = outs.pop().expect("vt");
3047    let first = outs.pop().expect("u");
3048    let s = outs.pop().expect("s");
3049    if transposed {
3050        (s, second, first, info)
3051    } else {
3052        (s, first, second, info)
3053    }
3054}