Skip to main content

tenferro_linalg/
backend.rs

1use std::ops::Range;
2
3use tenferro_tensor::{Engine, Tensor, TensorRead, TensorWrite};
4
5/// Compact provider-neutral Householder QR payload used by backend hooks.
6#[doc(hidden)]
7#[derive(Debug)]
8pub struct CompactQrResult {
9    pub(crate) packed: Tensor,
10    pub(crate) coeff: Tensor,
11}
12
13pub(crate) use crate::error::unsupported_dtype;
14use crate::extension::{
15    apply_eigh_gauge, apply_qr_gauge, apply_svd_gauge, reject_required_batched,
16    validate_derivative_eps, EighDriver, EighOptions, QrOptions, SvdDriver, SvdOptions,
17};
18use crate::RankRevealingQrOptions;
19
20/// Backend surface required by the linalg extension runtime.
21///
22/// # Examples
23///
24/// ```rust
25/// use tenferro_cpu::{with_cpu_engine, CpuEngine};
26/// use tenferro_linalg::backend::LinalgBackend;
27///
28/// fn assert_linalg_backend<B: LinalgBackend>() {}
29///
30/// assert_linalg_backend::<CpuEngine>();
31/// let mut host = tenferro_cpu::CpuEngine::serial();
32/// {
33///     with_cpu_engine(&mut host, |_backend| ())
34///         .expect("CpuEngine must expose a CpuEngine");
35/// };
36/// # Ok::<(), Box<dyn std::error::Error>>(())
37/// ```
38pub trait LinalgBackend: Engine {
39    /// Compute a Cholesky factorization.
40    ///
41    /// # Errors
42    ///
43    /// Returns `Error::Validation` for non-matrix, non-square, or unsupported
44    /// input dtypes; `Error::Extension` with `ErrorKind::NumericalFailure`
45    /// when the matrix is not positive definite; or a typed backend source
46    /// when the provider cannot execute the factorization.
47    fn cholesky(&mut self, input: &Tensor) -> tenferro_tensor::Result<Tensor>;
48
49    /// Solve a triangular linear system with explicit side, triangle,
50    /// transpose, and unit-diagonal flags.
51    ///
52    /// # Errors
53    ///
54    /// Returns `Error::Validation` for incompatible matrix/rhs shapes, rank,
55    /// or dtype; `Error::Extension` with `ErrorKind::NumericalFailure` for a
56    /// singular or zero-diagonal system; or a typed backend source for a
57    /// provider failure.
58    fn triangular_solve(
59        &mut self,
60        a: &Tensor,
61        b: &Tensor,
62        left_side: bool,
63        lower: bool,
64        transpose_a: bool,
65        unit_diagonal: bool,
66    ) -> tenferro_tensor::Result<Tensor>;
67
68    // INVARIANT: the six flags are the public triangular-solve contract and mirror the owned hook.
69    #[allow(clippy::too_many_arguments)]
70    /// Solve a triangular linear system from tensor read targets.
71    ///
72    /// Backends may canonicalize the inputs inside the same placement family,
73    /// but must not silently transfer between CPU and GPU memory.
74    ///
75    /// # Examples
76    ///
77    /// ```rust
78    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
79    /// use tenferro_linalg::LinalgBackend;
80    /// use tenferro_tensor::{Tensor, TensorRead};
81    ///
82    /// let a = Tensor::from_vec_col_major(vec![2, 2], vec![2.0_f64, 0.0, 1.0, 3.0])?;
83    /// let b = Tensor::from_vec_col_major(vec![2, 1], vec![4.0_f64, 9.0])?;
84    /// let mut host = tenferro_cpu::CpuEngine::serial();
85    /// let x = {
86    ///     with_cpu_engine(&mut host, |backend| {
87    ///         backend.triangular_solve_read(
88    ///             TensorRead::from_tensor(&a),
89    ///             TensorRead::from_tensor(&b),
90    ///             true,
91    ///             false,
92    ///             false,
93    ///             false,
94    ///         )
95    ///     })
96    ///     .expect("CpuEngine must expose a CpuEngine")
97    /// }?;
98    /// let x = x.into_typed::<f64>().expect("F64 inputs return F64 output");
99    /// assert_eq!(x.host_data()?, &[0.5, 3.0]);
100    /// # Ok::<(), tenferro_tensor::Error>(())
101    /// ```
102    ///
103    /// # Errors
104    ///
105    /// The default implementation returns `Error::Unsupported` because the
106    /// backend does not accept tensor read targets. Implementations may return
107    /// `Error::Validation` for incompatible shapes or dtypes,
108    /// `Error::RuntimeState` for invalid placement, `Error::Extension` for a
109    /// singular system, or a typed backend-source error.
110    fn triangular_solve_read(
111        &mut self,
112        _a: TensorRead<'_>,
113        _b: TensorRead<'_>,
114        _left_side: bool,
115        _lower: bool,
116        _transpose_a: bool,
117        _unit_diagonal: bool,
118    ) -> tenferro_tensor::Result<Tensor> {
119        Err(tenferro_tensor::Error::unsupported(
120            "triangular_solve",
121            "backend does not accept tensor reads at this execution boundary",
122        ))
123    }
124
125    /// Compute public LU outputs `(P, L, U, parity)`.
126    ///
127    /// # Errors
128    ///
129    /// Returns `Error::Validation` when the input is not a supported matrix or
130    /// dtype, and `Error::Extension` or a typed backend source when LU
131    /// execution or pivot storage fails.
132    fn lu(&mut self, input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>>;
133
134    #[doc(hidden)]
135    fn lu_factor(&mut self, _input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>> {
136        Err(tenferro_tensor::Error::unsupported(
137            "lu_factor",
138            format!(
139                "backend {} does not implement internal packed LU factorization",
140                std::any::type_name::<Self>()
141            ),
142        ))
143    }
144
145    /// Compute complete-pivot LU outputs `(P, L, U, Q, parity)`.
146    ///
147    /// The reconstruction convention is `A = P^T * L * U * Q`, equivalently
148    /// `P * A * Q^T = L * U`. `parity` is a scalar real tensor containing
149    /// `+1` or `-1`: `F32` for `F32`/`C32` inputs and `F64` for `F64`/`C64`
150    /// inputs.
151    ///
152    /// # Errors
153    ///
154    /// Returns `Error::Validation` for an invalid rank, square-shape
155    /// requirement, or dtype, and `Error::Extension` or a typed backend source
156    /// when complete-pivot factorization cannot be executed.
157    fn full_piv_lu(&mut self, input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>>;
158
159    /// Solve a linear system through the complete-pivot LU path.
160    ///
161    /// With `transpose_a = false`, this solves `A * x = b`. With
162    /// `transpose_a = true`, this solves `A^T * x = b`.
163    ///
164    /// # Errors
165    ///
166    /// Returns `Error::Validation` for incompatible coefficient/rhs shapes or
167    /// dtypes, `Error::Extension` with `ErrorKind::NumericalFailure` for a
168    /// singular system, or a typed backend source for provider failure.
169    fn full_piv_lu_solve(
170        &mut self,
171        a: &Tensor,
172        b: &Tensor,
173        transpose_a: bool,
174    ) -> tenferro_tensor::Result<Tensor>;
175
176    /// Compute public SVD outputs `(U, S, Vt)`.
177    ///
178    /// # Errors
179    ///
180    /// Returns `Error::Validation` for an unsupported rank or dtype and a
181    /// typed `Error::Extension` or backend source when the solver fails.
182    fn svd(&mut self, input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>>;
183
184    /// Compute public SVD outputs `(U, S, Vt)` with explicit options.
185    ///
186    /// `derivative_eps` is validated for API consistency, but concrete backend
187    /// execution does not perform AD. `gauge` controls optional singular-vector
188    /// post-processing. `driver` selects the cuSOLVER routine on the CUDA
189    /// backend; the default implementation ignores it because the CPU provider
190    /// have a single SVD kernel.
191    ///
192    /// # Examples
193    ///
194    /// ```rust
195    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
196    /// use tenferro_linalg::{LinalgBackend, SvdGauge, SvdOptions};
197    /// use tenferro_tensor::Tensor;
198    ///
199    /// let input = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 0.0, 0.0, 2.0])?;
200    /// let mut host = tenferro_cpu::CpuEngine::serial();
201    /// let outputs = {
202    ///     with_cpu_engine(&mut host, |backend| {
203    ///         backend.svd_with_options(
204    ///             &input,
205    ///             SvdOptions::default().gauge(SvdGauge::CanonicalPivot),
206    ///         )
207    ///     })
208    ///     .expect("CpuEngine must expose a CpuEngine")
209    /// }?;
210    /// assert_eq!(outputs[1].shape(), &[2]);
211    /// # Ok::<(), tenferro_tensor::Error>(())
212    /// ```
213    ///
214    /// # Errors
215    ///
216    /// Returns [`tenferro_tensor::Error::Validation`] containing
217    /// [`tenferro_tensor::ValidationError::InvalidArgument`] when
218    /// `derivative_eps` is non-finite or non-positive, or when canonical gauge
219    /// output metadata is malformed. It can return
220    /// [`tenferro_tensor::Error::Validation`] with
221    /// [`tenferro_tensor::ValidationError::RankMismatch`],
222    /// [`tenferro_tensor::ValidationError::ShapeMismatch`], or
223    /// [`tenferro_tensor::ValidationError::DTypeMismatch`] for the input
224    /// or generated outputs, [`tenferro_tensor::Error::Extension`] with the
225    /// typed `tenferro_linalg::Error::UnsupportedDType` or
226    /// `NonConvergence` source, [`tenferro_tensor::Error::BackendSource`] for
227    /// provider calls, and [`tenferro_tensor::Error::RuntimeState`] for
228    /// placement failures.
229    fn svd_with_options(
230        &mut self,
231        input: &Tensor,
232        options: SvdOptions,
233    ) -> tenferro_tensor::Result<Vec<Tensor>> {
234        validate_derivative_eps("svd_with_options", options.derivative_eps)?;
235        let mut outputs = self.svd(input)?;
236        apply_svd_gauge(options.gauge, &mut outputs)?;
237        Ok(outputs)
238    }
239
240    /// Compute public full-matrices SVD outputs `(U, S, Vt)` with `U` shaped
241    /// `m x m` and `Vt` shaped `n x n`, so the trailing `Vt` rows span the
242    /// input's right nullspace.
243    ///
244    /// # Errors
245    ///
246    /// The default implementation returns `Error::Unsupported`: a backend that
247    /// does not implement the full variant reports it explicitly rather than
248    /// silently falling back to the thin decomposition. Implementing backends
249    /// may additionally return `Error::Validation` for an unsupported rank or
250    /// dtype and a typed backend source when the solver fails.
251    fn svd_full(&mut self, _input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>> {
252        Err(tenferro_tensor::Error::unsupported(
253            "svd_full",
254            format!(
255                "backend {} does not implement full-matrices SVD",
256                std::any::type_name::<Self>()
257            ),
258        ))
259    }
260
261    /// Compute full-matrices SVD outputs `(U, S, Vt)` from a tensor read target.
262    ///
263    /// This is the borrowed-input counterpart of [`LinalgBackend::svd_full`] and
264    /// keeps the same output contract: `U` is `m x m`, `S` has `min(m, n)`
265    /// entries, and `Vt` is `n x n`. Backends may canonicalize the input inside
266    /// the same placement family, but must not silently transfer between CPU
267    /// and GPU memory, and must not substitute the thin decomposition.
268    ///
269    /// # Examples
270    ///
271    /// ```rust
272    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
273    /// use tenferro_linalg::LinalgBackend;
274    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
275    ///
276    /// let input = TypedTensor::<f64>::from_vec_col_major(vec![1, 2], vec![1.0, 1.0])?;
277    /// let mut host = tenferro_cpu::CpuEngine::serial();
278    /// let outputs = {
279    ///     with_cpu_engine(&mut host, |backend| {
280    ///         backend.svd_full_read(TensorRead::from_view(TensorView::F64(input.as_view())))
281    ///     })
282    ///     .expect("CpuEngine must expose a CpuEngine")
283    /// }?;
284    /// assert_eq!(outputs[0].shape(), &[1, 1]);
285    /// assert_eq!(outputs[1].shape(), &[1]);
286    /// assert_eq!(outputs[2].shape(), &[2, 2]);
287    /// # Ok::<(), tenferro_tensor::Error>(())
288    /// ```
289    ///
290    /// # Errors
291    ///
292    /// The default implementation returns `Error::Unsupported` because the
293    /// backend does not accept tensor read targets for the full variant; an
294    /// implementation may instead return `Error::Validation` for an unsupported
295    /// rank or dtype, `Error::Unsupported` when the selected provider has no
296    /// full-matrices kernel, and a typed backend source when the solver fails.
297    fn svd_full_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Vec<Tensor>> {
298        Err(tenferro_tensor::Error::unsupported(
299            "svd_full",
300            "backend does not accept tensor reads for full-matrices SVD at this execution boundary",
301        ))
302    }
303
304    #[doc(hidden)]
305    fn svd_values(&mut self, _input: &Tensor) -> tenferro_tensor::Result<Tensor> {
306        Err(tenferro_tensor::Error::unsupported(
307            "svd_values",
308            format!(
309                "backend {} does not implement internal singular-values-only decomposition",
310                std::any::type_name::<Self>()
311            ),
312        ))
313    }
314
315    /// Singular values only with an explicit CUDA driver. The default
316    /// implementation ignores the driver, matching [`LinalgBackend::svd_with_options`].
317    #[doc(hidden)]
318    fn svd_values_with_driver(
319        &mut self,
320        input: &Tensor,
321        _driver: SvdDriver,
322    ) -> tenferro_tensor::Result<Tensor> {
323        self.svd_values(input)
324    }
325
326    /// Compute a singular value decomposition from a tensor read target.
327    ///
328    /// Backends may canonicalize the input inside the same placement family, but
329    /// must not silently transfer between CPU and GPU memory.
330    ///
331    /// # Examples
332    ///
333    /// ```rust
334    /// use tenferro_linalg::LinalgBackend;
335    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
336    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
337    ///
338    /// let input = TypedTensor::<f64>::from_vec_col_major(
339    ///     vec![2, 2],
340    ///     vec![1.0, 0.0, 0.0, 2.0],
341    /// )?;
342    /// let mut host = tenferro_cpu::CpuEngine::serial();
343    /// let outputs = {
344    ///     with_cpu_engine(&mut host, |backend| {
345    ///         backend.svd_read(TensorRead::from_view(TensorView::F64(input.as_view())))
346    ///     })
347    ///     .expect("CpuEngine must expose a CpuEngine")
348    /// }?;
349    /// assert_eq!(outputs[1].shape(), &[2]);
350    /// # Ok::<(), tenferro_tensor::Error>(())
351    /// ```
352    ///
353    /// # Errors
354    ///
355    /// The default implementation returns `Error::Unsupported` because the
356    /// backend does not accept tensor read targets; an implementation may instead
357    /// return validation or typed backend-source errors after canonicalizing
358    /// the view.
359    fn svd_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Vec<Tensor>> {
360        Err(tenferro_tensor::Error::unsupported(
361            "svd",
362            "backend does not accept tensor reads at this execution boundary",
363        ))
364    }
365
366    /// Compute public SVD outputs `(U, S, Vt)` from a tensor read target with
367    /// explicit options.
368    ///
369    /// This is the borrowed-input counterpart of
370    /// [`LinalgBackend::svd_with_options`]. The default implementation runs
371    /// [`LinalgBackend::svd_read`] and applies the gauge on the host; it
372    /// ignores `driver` because the CPU provider has a single SVD kernel. The
373    /// CUDA backend overrides it so the driver reaches cuSOLVER.
374    ///
375    /// # Examples
376    ///
377    /// ```rust
378    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
379    /// use tenferro_linalg::{LinalgBackend, SvdDriver, SvdOptions};
380    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
381    ///
382    /// let input = TypedTensor::<f64>::from_vec_col_major(
383    ///     vec![2, 2],
384    ///     vec![1.0, 0.0, 0.0, 2.0],
385    /// )?;
386    /// let mut host = tenferro_cpu::CpuEngine::serial();
387    /// let outputs = {
388    ///     with_cpu_engine(&mut host, |backend| {
389    ///         backend.svd_with_options_read(
390    ///             TensorRead::from_view(TensorView::F64(input.as_view())),
391    ///             SvdOptions::default().driver(SvdDriver::QrBased),
392    ///         )
393    ///     })
394    ///     .expect("CpuEngine must expose a CpuEngine")
395    /// }?;
396    /// assert_eq!(outputs[1].shape(), &[2]);
397    /// # Ok::<(), tenferro_tensor::Error>(())
398    /// ```
399    ///
400    /// # Errors
401    ///
402    /// Returns [`tenferro_tensor::Error::Validation`] containing
403    /// [`tenferro_tensor::ValidationError::InvalidArgument`] when
404    /// `derivative_eps` is non-finite or non-positive, plus the validation,
405    /// unsupported-dtype, numerical, placement, or typed backend/provider
406    /// errors from [`LinalgBackend::svd_read`] and the gauge metadata and
407    /// host-access errors from the default host gauge path.
408    fn svd_with_options_read(
409        &mut self,
410        input: TensorRead<'_>,
411        options: SvdOptions,
412    ) -> tenferro_tensor::Result<Vec<Tensor>> {
413        validate_derivative_eps("svd_with_options_read", options.derivative_eps)?;
414        let mut outputs = self.svd_read(input)?;
415        apply_svd_gauge(options.gauge, &mut outputs)?;
416        Ok(outputs)
417    }
418
419    #[doc(hidden)]
420    fn svd_values_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Tensor> {
421        Err(tenferro_tensor::Error::unsupported(
422            "svd_values",
423            "backend does not implement borrowed singular-values-only decomposition",
424        ))
425    }
426
427    /// Borrowed-input counterpart of [`LinalgBackend::svd_values_with_driver`].
428    #[doc(hidden)]
429    fn svd_values_with_driver_read(
430        &mut self,
431        input: TensorRead<'_>,
432        _driver: SvdDriver,
433    ) -> tenferro_tensor::Result<Tensor> {
434        self.svd_values_read(input)
435    }
436
437    /// Compute public QR outputs `(Q, R)`.
438    ///
439    /// QR is thin: for an `m x n` input, `Q` has shape `m x min(m, n)` and
440    /// `R` has shape `min(m, n) x n`.
441    ///
442    /// This is [`LinalgBackend::qr_with_options`] with default options. The
443    /// CUDA provider does not inspect the cuSOLVER device status flags for
444    /// ordinary QR; synchronous provider errors still propagate. It does not
445    /// report rank deficiency: shapes and dtypes are validated up front, and a
446    /// rank-deficient input still yields its valid `(Q, R)` factors.
447    ///
448    /// # Errors
449    ///
450    /// Returns `Error::Validation` for an unsupported rank, shape, or dtype,
451    /// and a typed `Error::Extension` or backend source when QR execution
452    /// fails.
453    fn qr(&mut self, input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>>;
454
455    /// Compute public QR outputs `(Q, R)` with explicit options.
456    ///
457    /// `gauge` controls optional sign or phase post-processing. The CUDA
458    /// provider does not inspect the cuSOLVER device status flags for ordinary
459    /// QR; synchronous provider errors still propagate. It does not report
460    /// rank deficiency: shapes and dtypes are validated up front, and a
461    /// rank-deficient input still yields its valid factors. The caller's own
462    /// verification decides whether those factors are acceptable.
463    ///
464    /// # Examples
465    ///
466    /// ```rust
467    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
468    /// use tenferro_linalg::{LinalgBackend, QrGauge, QrOptions};
469    /// use tenferro_tensor::Tensor;
470    ///
471    /// let input = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 0.0, 0.0, 2.0])?;
472    /// let mut host = tenferro_cpu::CpuEngine::serial();
473    /// let outputs = {
474    ///     with_cpu_engine(&mut host, |backend| {
475    ///         backend.qr_with_options(
476    ///             &input,
477    ///             QrOptions::default().gauge(QrGauge::PositiveDiagonal),
478    ///         )
479    ///     })
480    ///     .expect("CpuEngine must expose a CpuEngine")
481    /// }?;
482    /// assert_eq!(outputs[0].shape(), &[2, 2]);
483    /// # Ok::<(), tenferro_tensor::Error>(())
484    /// ```
485    ///
486    /// # Errors
487    ///
488    /// Returns [`tenferro_tensor::Error::Validation`] containing
489    /// [`tenferro_tensor::ValidationError::RankMismatch`] or
490    /// [`tenferro_tensor::ValidationError::ShapeMismatch`] for an invalid
491    /// matrix input, or [`tenferro_tensor::ValidationError::InvalidArgument`]
492    /// for malformed gauge output metadata, checked size arithmetic, or an
493    /// unavailable compiled provider. A mismatched generated `Q`/`R` dtype is reported as
494    /// [`tenferro_tensor::ValidationError::DTypeMismatch`]. Provider
495    /// unsupported dtype or numerical rejection is
496    /// [`tenferro_tensor::Error::Extension`] with a typed linalg source, while
497    /// provider failures use [`tenferro_tensor::Error::BackendSource`] and a
498    /// backend-resident input uses [`tenferro_tensor::Error::RuntimeState`].
499    fn qr_with_options(
500        &mut self,
501        input: &Tensor,
502        options: QrOptions,
503    ) -> tenferro_tensor::Result<Vec<Tensor>> {
504        let mut outputs = self.qr(input)?;
505        apply_qr_gauge(options.gauge, &mut outputs)?;
506        Ok(outputs)
507    }
508
509    /// Compute public QR outputs `(Q, R)` from a tensor read target.
510    ///
511    /// Backends may canonicalize the input inside the same placement family, but
512    /// must not silently transfer between CPU and GPU memory.
513    ///
514    /// # Examples
515    ///
516    /// ```rust
517    /// use tenferro_linalg::LinalgBackend;
518    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
519    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
520    ///
521    /// let input = TypedTensor::<f64>::from_vec_col_major(
522    ///     vec![2, 2],
523    ///     vec![1.0, 0.0, 0.0, 2.0],
524    /// )?;
525    /// let mut host = tenferro_cpu::CpuEngine::serial();
526    /// let outputs = {
527    ///     with_cpu_engine(&mut host, |backend| {
528    ///         backend.qr_read(TensorRead::from_view(TensorView::F64(input.as_view())))
529    ///     })
530    ///     .expect("CpuEngine must expose a CpuEngine")
531    /// }?;
532    /// assert_eq!(outputs[0].shape(), &[2, 2]);
533    /// assert_eq!(outputs[1].shape(), &[2, 2]);
534    /// # Ok::<(), tenferro_tensor::Error>(())
535    /// ```
536    ///
537    /// # Errors
538    ///
539    /// The default implementation returns `Error::Unsupported` because the
540    /// backend does not accept tensor read targets; implementations may return
541    /// validation or typed backend-source errors.
542    fn qr_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Vec<Tensor>> {
543        Err(tenferro_tensor::Error::unsupported(
544            "qr",
545            "backend does not accept tensor reads at this execution boundary",
546        ))
547    }
548
549    /// Compute public QR outputs `(Q, R)` from a tensor read target with options.
550    ///
551    /// Device backends override this hook to keep gauge processing in the input
552    /// placement. The default is appropriate for host backends.
553    ///
554    /// # Examples
555    ///
556    /// ```rust
557    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
558    /// use tenferro_linalg::{LinalgBackend, QrGauge, QrOptions};
559    /// use tenferro_tensor::{Tensor, TensorRead};
560    ///
561    /// let input = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 0.0, 0.0, 2.0])?;
562    /// let mut host = tenferro_cpu::CpuEngine::serial();
563    /// let outputs = {
564    ///     with_cpu_engine(&mut host, |backend| {
565    ///         backend.qr_with_options_read(
566    ///             TensorRead::from_tensor(&input),
567    ///             QrOptions::default().gauge(QrGauge::PositiveDiagonal),
568    ///         )
569    ///     })
570    ///     .expect("CpuEngine must expose a CpuEngine")
571    /// }?;
572    /// assert_eq!(outputs[0].shape(), &[2, 2]);
573    /// # Ok::<(), tenferro_tensor::Error>(())
574    /// ```
575    ///
576    /// # Errors
577    ///
578    /// Returns the validation, unsupported-dtype, numerical, placement, or
579    /// typed backend/provider errors from [`LinalgBackend::qr_read`], plus
580    /// gauge metadata and host-access errors from the default host gauge path.
581    fn qr_with_options_read(
582        &mut self,
583        input: TensorRead<'_>,
584        options: QrOptions,
585    ) -> tenferro_tensor::Result<Vec<Tensor>> {
586        let mut outputs = self.qr_read(input)?;
587        apply_qr_gauge(options.gauge, &mut outputs)?;
588        Ok(outputs)
589    }
590
591    #[doc(hidden)]
592    fn rank_revealing_qr(
593        &mut self,
594        _input: &Tensor,
595        _options: RankRevealingQrOptions,
596    ) -> tenferro_tensor::Result<Vec<Tensor>> {
597        Err(tenferro_tensor::Error::unsupported(
598            "rank_revealing_qr",
599            "backend does not implement rank-revealing QR",
600        ))
601    }
602
603    #[doc(hidden)]
604    fn rank_revealing_qr_read(
605        &mut self,
606        _input: TensorRead<'_>,
607        _options: RankRevealingQrOptions,
608    ) -> tenferro_tensor::Result<Vec<Tensor>> {
609        Err(tenferro_tensor::Error::unsupported(
610            "rank_revealing_qr",
611            "backend does not implement borrowed rank-revealing QR",
612        ))
613    }
614
615    #[doc(hidden)]
616    fn householder_qr(&mut self, _input: &Tensor) -> tenferro_tensor::Result<CompactQrResult> {
617        Err(tenferro_tensor::Error::unsupported(
618            "householder_qr",
619            "backend does not implement compact Householder QR",
620        ))
621    }
622
623    #[doc(hidden)]
624    fn householder_qr_from_factors(
625        &mut self,
626        _q: &Tensor,
627        _r: &Tensor,
628    ) -> tenferro_tensor::Result<CompactQrResult> {
629        Err(tenferro_tensor::Error::unsupported(
630            "householder_qr_from_factors",
631            "backend does not implement compact Householder QR factor import",
632        ))
633    }
634
635    #[doc(hidden)]
636    fn householder_qr_append(
637        &mut self,
638        _packed: &Tensor,
639        _coeff: &Tensor,
640        _block: &Tensor,
641    ) -> tenferro_tensor::Result<CompactQrResult> {
642        Err(tenferro_tensor::Error::unsupported(
643            "householder_qr_append",
644            "backend does not implement compact Householder QR append",
645        ))
646    }
647
648    #[doc(hidden)]
649    fn householder_qr_r(
650        &mut self,
651        _packed: &Tensor,
652        _coeff: &Tensor,
653        _options: QrOptions,
654    ) -> tenferro_tensor::Result<Tensor> {
655        Err(tenferro_tensor::Error::unsupported(
656            "householder_qr_r",
657            "backend does not implement compact Householder QR extraction",
658        ))
659    }
660
661    /// Materialize Q columns `columns` from compact Householder state.
662    ///
663    /// The reachable width is full Q: for an `m x n` input, `columns` may run
664    /// to `m`, and the columns past `k = min(m, n)` span the orthogonal
665    /// complement of the input's column space. `QrOptions::gauge` comes from
666    /// R's diagonal and therefore applies to the first `k` columns only.
667    #[doc(hidden)]
668    fn householder_qr_q_columns(
669        &mut self,
670        _packed: &Tensor,
671        _coeff: &Tensor,
672        _columns: Range<usize>,
673        _options: QrOptions,
674    ) -> tenferro_tensor::Result<Tensor> {
675        Err(tenferro_tensor::Error::unsupported(
676            "householder_qr_q_columns",
677            "backend does not implement compact Householder Q-column materialization",
678        ))
679    }
680
681    /// Compute public Hermitian eigendecomposition outputs `(values, vectors)`.
682    ///
683    /// The returned vector order is `[values, vectors]`, where `values` has
684    /// shape `[n]` and `vectors` has shape `[n, n]`.
685    ///
686    /// # Errors
687    ///
688    /// Returns `Error::Validation` for a non-square or unsupported-dtype input
689    /// and a typed `Error::Extension` or backend source when eigendecomposition
690    /// fails.
691    fn eigh(&mut self, input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>>;
692
693    /// Compute public Hermitian eigendecomposition outputs with explicit options.
694    ///
695    /// `derivative_eps` is validated for API consistency, but concrete backend
696    /// execution does not perform AD. `gauge` controls optional eigenvector
697    /// post-processing.
698    ///
699    /// # Examples
700    ///
701    /// ```rust
702    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
703    /// use tenferro_linalg::{EighGauge, EighOptions, LinalgBackend};
704    /// use tenferro_tensor::Tensor;
705    ///
706    /// let input = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 0.0, 0.0, 2.0])?;
707    /// let mut host = tenferro_cpu::CpuEngine::serial();
708    /// let outputs = {
709    ///     with_cpu_engine(&mut host, |backend| {
710    ///         backend.eigh_with_options(
711    ///             &input,
712    ///             EighOptions::default()
713    ///                 .gauge(EighGauge::CanonicalPivot)
714    ///                 .derivative_eps(1.0e-10),
715    ///         )
716    ///     })
717    ///     .expect("CpuEngine must expose a CpuEngine")
718    /// }?;
719    /// assert_eq!(outputs[0].shape(), &[2]);
720    /// # Ok::<(), tenferro_tensor::Error>(())
721    /// ```
722    ///
723    /// # Errors
724    ///
725    /// Returns [`tenferro_tensor::Error::Validation`] containing
726    /// [`tenferro_tensor::ValidationError::InvalidArgument`] when
727    /// `derivative_eps` is non-finite or non-positive, when canonical gauge
728    /// output metadata is malformed, or when checked output-size arithmetic
729    /// overflows. It can return [`tenferro_tensor::Error::Validation`] with
730    /// [`tenferro_tensor::ValidationError::RankMismatch`] or
731    /// [`tenferro_tensor::ValidationError::ShapeMismatch`] for the
732    /// matrix input, or [`tenferro_tensor::ValidationError::DTypeMismatch`]
733    /// for generated outputs. It can also return
734    /// [`tenferro_tensor::Error::Extension`] with typed
735    /// `tenferro_linalg::Error::UnsupportedDType` or `NonConvergence`, and
736    /// [`tenferro_tensor::Error::BackendSource`] or
737    /// [`tenferro_tensor::Error::RuntimeState`] for provider and placement
738    /// failures.
739    ///
740    /// `EighOptions::batch_policy` of
741    /// [`crate::EighBatchPolicy::RequireBatched`] adds
742    /// [`tenferro_tensor::Error::Unsupported`] for a real batch on a provider
743    /// without a batched eigensolver — this default implementation among them,
744    /// because it runs [`LinalgBackend::eigh`], one launch per matrix.
745    fn eigh_with_options(
746        &mut self,
747        input: &Tensor,
748        options: EighOptions,
749    ) -> tenferro_tensor::Result<Vec<Tensor>> {
750        validate_derivative_eps("eigh_with_options", options.derivative_eps)?;
751        reject_required_batched("eigh_with_options", &options, input.shape())?;
752        let mut outputs = self.eigh(input)?;
753        apply_eigh_gauge(options.gauge, &mut outputs)?;
754        Ok(outputs)
755    }
756
757    /// Compute public eigh outputs `(values, vectors)` from a tensor read
758    /// target with explicit options.
759    ///
760    /// This is the borrowed-input counterpart of
761    /// [`LinalgBackend::eigh_with_options`]. The default implementation runs
762    /// [`LinalgBackend::eigh_read`] and applies the gauge on the host; it
763    /// ignores `driver` because the CPU provider has a single eigh kernel. The
764    /// CUDA backend overrides it so the driver reaches cuSOLVER.
765    ///
766    /// # Examples
767    ///
768    /// ```rust
769    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
770    /// use tenferro_linalg::{EighDriver, EighOptions, LinalgBackend};
771    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
772    ///
773    /// let input = TypedTensor::<f64>::from_vec_col_major(
774    ///     vec![2, 2],
775    ///     vec![2.0, 0.0, 0.0, 3.0],
776    /// )?;
777    /// let mut host = tenferro_cpu::CpuEngine::serial();
778    /// let outputs = {
779    ///     with_cpu_engine(&mut host, |backend| {
780    ///         backend.eigh_with_options_read(
781    ///             TensorRead::from_view(TensorView::F64(input.as_view())),
782    ///             EighOptions::default().driver(EighDriver::Jacobi),
783    ///         )
784    ///     })
785    ///     .expect("CpuEngine must expose a CpuEngine")
786    /// }?;
787    /// assert_eq!(outputs[0].shape(), &[2]);
788    /// # Ok::<(), tenferro_tensor::Error>(())
789    /// ```
790    ///
791    /// # Errors
792    ///
793    /// Returns [`tenferro_tensor::Error::Validation`] containing
794    /// [`tenferro_tensor::ValidationError::InvalidArgument`] when
795    /// `derivative_eps` is non-finite or non-positive, plus the validation,
796    /// unsupported-dtype, numerical, placement, or typed backend/provider
797    /// errors from [`LinalgBackend::eigh_read`] and the gauge metadata and
798    /// host-access errors from the default host gauge path.
799    /// [`crate::EighBatchPolicy::RequireBatched`] adds the same
800    /// [`tenferro_tensor::Error::Unsupported`] refusal as
801    /// [`LinalgBackend::eigh_with_options`] for a real batch.
802    fn eigh_with_options_read(
803        &mut self,
804        input: TensorRead<'_>,
805        options: EighOptions,
806    ) -> tenferro_tensor::Result<Vec<Tensor>> {
807        validate_derivative_eps("eigh_with_options_read", options.derivative_eps)?;
808        reject_required_batched("eigh_with_options_read", &options, input.shape())?;
809        let mut outputs = self.eigh_read(input)?;
810        apply_eigh_gauge(options.gauge, &mut outputs)?;
811        Ok(outputs)
812    }
813
814    /// Compute public Hermitian eigendecomposition outputs from a tensor read target.
815    ///
816    /// Backends may canonicalize the input inside the same placement family, but
817    /// must not silently transfer between CPU and GPU memory.
818    ///
819    /// # Examples
820    ///
821    /// ```rust
822    /// use tenferro_linalg::LinalgBackend;
823    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
824    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
825    ///
826    /// let input = TypedTensor::<f64>::from_vec_col_major(
827    ///     vec![2, 2],
828    ///     vec![1.0, 0.0, 0.0, 2.0],
829    /// )?;
830    /// let mut host = tenferro_cpu::CpuEngine::serial();
831    /// let outputs = {
832    ///     with_cpu_engine(&mut host, |backend| {
833    ///         backend.eigh_read(TensorRead::from_view(TensorView::F64(input.as_view())))
834    ///     })
835    ///     .expect("CpuEngine must expose a CpuEngine")
836    /// }?;
837    /// assert_eq!(outputs[0].shape(), &[2]);
838    /// assert_eq!(outputs[1].shape(), &[2, 2]);
839    /// # Ok::<(), tenferro_tensor::Error>(())
840    /// ```
841    ///
842    /// # Errors
843    ///
844    /// The default implementation returns `Error::Unsupported` because the
845    /// backend does not accept tensor read targets; implementations may return
846    /// validation or typed backend-source errors.
847    fn eigh_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Vec<Tensor>> {
848        Err(tenferro_tensor::Error::unsupported(
849            "eigh",
850            "backend does not accept tensor reads at this execution boundary",
851        ))
852    }
853
854    /// Compute Cholesky factorization from a tensor read target.
855    ///
856    /// Backends may canonicalize the input inside the same placement family, but
857    /// must not silently transfer between CPU and GPU memory.
858    ///
859    /// # Examples
860    ///
861    /// ```rust
862    /// use tenferro_linalg::LinalgBackend;
863    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
864    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
865    ///
866    /// let input = TypedTensor::<f64>::from_vec_col_major(
867    ///     vec![2, 2],
868    ///     vec![4.0, 2.0, 2.0, 3.0],
869    /// )?;
870    /// let mut host = tenferro_cpu::CpuEngine::serial();
871    /// let output = {
872    ///     with_cpu_engine(&mut host, |backend| {
873    ///         backend.cholesky_read(TensorRead::from_view(TensorView::F64(input.as_view())))
874    ///     })
875    ///     .expect("CpuEngine must expose a CpuEngine")
876    /// }?;
877    /// assert_eq!(output.shape(), &[2, 2]);
878    /// # Ok::<(), tenferro_tensor::Error>(())
879    /// ```
880    ///
881    /// # Errors
882    ///
883    /// The default implementation returns `Error::Unsupported` because the
884    /// backend does not accept tensor read targets; implementations may return
885    /// validation or typed backend-source errors.
886    fn cholesky_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Tensor> {
887        Err(tenferro_tensor::Error::unsupported(
888            "cholesky",
889            "backend does not accept tensor reads at this execution boundary",
890        ))
891    }
892
893    /// Compute public LU outputs from a tensor read target.
894    ///
895    /// Backends may canonicalize the input inside the same placement family, but
896    /// must not silently transfer between CPU and GPU memory.
897    ///
898    /// # Examples
899    ///
900    /// ```rust
901    /// use tenferro_linalg::LinalgBackend;
902    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
903    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
904    ///
905    /// let input = TypedTensor::<f64>::from_vec_col_major(
906    ///     vec![2, 2],
907    ///     vec![1.0, 3.0, 2.0, 4.0],
908    /// )?;
909    /// let mut host = tenferro_cpu::CpuEngine::serial();
910    /// let outputs = {
911    ///     with_cpu_engine(&mut host, |backend| {
912    ///         backend.lu_read(TensorRead::from_view(TensorView::F64(input.as_view())))
913    ///     })
914    ///     .expect("CpuEngine must expose a CpuEngine")
915    /// }?;
916    /// assert_eq!(outputs.len(), 4);
917    /// # Ok::<(), tenferro_tensor::Error>(())
918    /// ```
919    ///
920    /// # Errors
921    ///
922    /// The default implementation returns `Error::Unsupported` because the
923    /// backend does not accept tensor read targets; implementations may return
924    /// validation or typed backend-source errors.
925    fn lu_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Vec<Tensor>> {
926        Err(tenferro_tensor::Error::unsupported(
927            "lu",
928            "backend does not accept tensor reads at this execution boundary",
929        ))
930    }
931
932    /// Compute public full-pivoting LU outputs from a tensor read target.
933    ///
934    /// Backends may canonicalize the input inside the same placement family, but
935    /// must not silently transfer between CPU and GPU memory.
936    ///
937    /// # Examples
938    ///
939    /// ```rust
940    /// use tenferro_linalg::LinalgBackend;
941    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
942    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
943    ///
944    /// let input = TypedTensor::<f64>::from_vec_col_major(
945    ///     vec![2, 2],
946    ///     vec![1.0, 3.0, 2.0, 4.0],
947    /// )?;
948    /// let mut host = tenferro_cpu::CpuEngine::serial();
949    /// let outputs = {
950    ///     with_cpu_engine(&mut host, |backend| {
951    ///         backend.full_piv_lu_read(TensorRead::from_view(TensorView::F64(input.as_view())))
952    ///     })
953    ///     .expect("CpuEngine must expose a CpuEngine")
954    /// }?;
955    /// assert_eq!(outputs.len(), 5);
956    /// # Ok::<(), tenferro_tensor::Error>(())
957    /// ```
958    ///
959    /// # Errors
960    ///
961    /// The default implementation returns `Error::Unsupported` because the
962    /// backend does not accept tensor read targets; implementations may return
963    /// validation or typed backend-source errors.
964    fn full_piv_lu_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Vec<Tensor>> {
965        Err(tenferro_tensor::Error::unsupported(
966            "full_piv_lu",
967            "backend does not accept tensor reads at this execution boundary",
968        ))
969    }
970
971    /// Compute general eigendecomposition outputs from a tensor read target.
972    ///
973    /// Backends may canonicalize the input inside the same placement family, but
974    /// must not silently transfer between CPU and GPU memory.
975    ///
976    /// # Examples
977    ///
978    /// ```rust
979    /// use tenferro_linalg::LinalgBackend;
980    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
981    /// use tenferro_tensor::{TensorRead, TensorView, TypedTensor};
982    ///
983    /// let input = TypedTensor::<f64>::from_vec_col_major(
984    ///     vec![2, 2],
985    ///     vec![2.0, 0.0, 0.0, 3.0],
986    /// )?;
987    /// let mut host = tenferro_cpu::CpuEngine::serial();
988    /// let outputs = {
989    ///     with_cpu_engine(&mut host, |backend| {
990    ///         backend.eig_read(TensorRead::from_view(TensorView::F64(input.as_view())))
991    ///     })
992    ///     .expect("CpuEngine must expose a CpuEngine")
993    /// }?;
994    /// assert_eq!(outputs.len(), 2);
995    /// # Ok::<(), tenferro_tensor::Error>(())
996    /// ```
997    ///
998    /// # Errors
999    ///
1000    /// The default implementation returns `Error::Unsupported` because the
1001    /// backend does not accept tensor read targets; implementations may return
1002    /// validation or typed backend-source errors.
1003    fn eig_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Vec<Tensor>> {
1004        Err(tenferro_tensor::Error::unsupported(
1005            "eig",
1006            "backend does not accept tensor reads at this execution boundary",
1007        ))
1008    }
1009
1010    #[doc(hidden)]
1011    fn eigh_values(&mut self, _input: &Tensor) -> tenferro_tensor::Result<Tensor> {
1012        Err(tenferro_tensor::Error::unsupported(
1013            "eigh_values",
1014            format!(
1015                "backend {} does not implement internal Hermitian eigenvalues-only decomposition",
1016                std::any::type_name::<Self>()
1017            ),
1018        ))
1019    }
1020
1021    /// Eigenvalues only with an explicit CUDA driver. The default
1022    /// implementation ignores the driver, matching
1023    /// [`LinalgBackend::eigh_with_options`].
1024    #[doc(hidden)]
1025    fn eigh_values_with_driver(
1026        &mut self,
1027        input: &Tensor,
1028        _driver: EighDriver,
1029    ) -> tenferro_tensor::Result<Tensor> {
1030        self.eigh_values(input)
1031    }
1032
1033    #[doc(hidden)]
1034    fn eigh_values_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Tensor> {
1035        Err(tenferro_tensor::Error::unsupported(
1036            "eigh_values",
1037            "backend does not implement borrowed Hermitian eigenvalues-only decomposition",
1038        ))
1039    }
1040
1041    /// Borrowed-input counterpart of
1042    /// [`LinalgBackend::eigh_values_with_driver`].
1043    #[doc(hidden)]
1044    fn eigh_values_with_driver_read(
1045        &mut self,
1046        input: TensorRead<'_>,
1047        _driver: EighDriver,
1048    ) -> tenferro_tensor::Result<Tensor> {
1049        self.eigh_values_read(input)
1050    }
1051
1052    /// Compute public general eigendecomposition outputs `(values, vectors)`.
1053    /// Eigenvectors come back with unit 2-norm columns, whichever provider computed them;
1054    /// a column the provider left non-finite is reported as a numerical failure instead
1055    /// of being returned as `NaN` (#2148).
1056    ///
1057    /// # Errors
1058    ///
1059    /// Returns `Error::Validation` for a non-square, rank, or dtype mismatch,
1060    /// and a typed `Error::Extension` or backend source when the eigensolver
1061    /// fails.
1062    fn eig(&mut self, input: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>>;
1063
1064    #[doc(hidden)]
1065    fn eig_values(&mut self, _input: &Tensor) -> tenferro_tensor::Result<Tensor> {
1066        Err(tenferro_tensor::Error::unsupported(
1067            "eig_values",
1068            format!(
1069                "backend {} does not implement internal general eigenvalues-only decomposition",
1070                std::any::type_name::<Self>()
1071            ),
1072        ))
1073    }
1074
1075    #[doc(hidden)]
1076    fn eig_values_read(&mut self, _input: TensorRead<'_>) -> tenferro_tensor::Result<Tensor> {
1077        Err(tenferro_tensor::Error::unsupported(
1078            "eig_values",
1079            "backend does not implement borrowed general eigenvalues-only decomposition",
1080        ))
1081    }
1082
1083    /// Solve a dense linear system.
1084    ///
1085    /// The CUDA provider does not inspect the cuSOLVER `getrf` status flag on
1086    /// the forward solve path, so it performs no per-call non-singularity check
1087    /// and issues no host round trip. An exactly singular input is left to the
1088    /// caller's verification, as in `torch.linalg.solve`. A CPU backend may
1089    /// still report its own exactly singular factor as `Error::Singular`.
1090    ///
1091    /// # Errors
1092    ///
1093    /// Returns `Error::Validation` for incompatible matrix/rhs shapes, rank,
1094    /// or dtype; `Error::Extension` with `ErrorKind::NumericalFailure` for a
1095    /// singular system; or a typed backend source for provider failure.
1096    fn solve(&mut self, a: &Tensor, b: &Tensor) -> tenferro_tensor::Result<Tensor>;
1097
1098    /// Solve a linear system from tensor read targets.
1099    ///
1100    /// Backends may canonicalize the inputs inside the same placement family,
1101    /// but must not silently transfer between CPU and GPU memory.
1102    ///
1103    /// # Examples
1104    ///
1105    /// ```rust
1106    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
1107    /// use tenferro_linalg::LinalgBackend;
1108    /// use tenferro_tensor::{Tensor, TensorRead};
1109    ///
1110    /// let a = Tensor::from_vec_col_major(vec![2, 2], vec![2.0_f64, 0.0, 0.0, 3.0])?;
1111    /// let b = Tensor::from_vec_col_major(vec![2, 1], vec![4.0_f64, 9.0])?;
1112    /// let mut host = tenferro_cpu::CpuEngine::serial();
1113    /// let x = {
1114    ///     with_cpu_engine(&mut host, |backend| {
1115    ///         backend.solve_read(
1116    ///             TensorRead::from_tensor(&a),
1117    ///             TensorRead::from_tensor(&b),
1118    ///         )
1119    ///     })
1120    ///     .expect("CpuEngine must expose a CpuEngine")
1121    /// }?;
1122    /// let x = x.into_typed::<f64>().expect("F64 inputs return F64 output");
1123    /// assert_eq!(x.host_data()?, &[2.0, 3.0]);
1124    /// # Ok::<(), tenferro_tensor::Error>(())
1125    /// ```
1126    ///
1127    /// The CUDA provider does not inspect the cuSOLVER `getrf` status flag on
1128    /// the forward solve path, so it performs no per-call non-singularity check
1129    /// and issues no host round trip. An exactly singular input is left to the
1130    /// caller's verification, as in `torch.linalg.solve`. A CPU backend may
1131    /// still report its own exactly singular factor as `Error::Singular`.
1132    ///
1133    /// # Errors
1134    ///
1135    /// The default implementation returns `Error::Unsupported` because the
1136    /// backend does not accept tensor read targets. Implementations may return
1137    /// `Error::Validation` for incompatible shapes or dtypes,
1138    /// `Error::RuntimeState` for invalid placement, `Error::Extension` for a
1139    /// singular system, or a typed backend-source error.
1140    fn solve_read(
1141        &mut self,
1142        _a: TensorRead<'_>,
1143        _b: TensorRead<'_>,
1144    ) -> tenferro_tensor::Result<Tensor> {
1145        Err(tenferro_tensor::Error::unsupported(
1146            "solve",
1147            "backend does not accept tensor reads at this execution boundary",
1148        ))
1149    }
1150
1151    /// Solve into a caller-owned destination.
1152    ///
1153    /// The default preserves the ordinary read path and copies its result into
1154    /// `out`. Backends with a native destination path may override this method,
1155    /// but must validate the destination before the first write and preserve
1156    /// the same shape, dtype, placement, aliasing, and error contracts.
1157    ///
1158    /// The CUDA provider does not inspect the cuSOLVER `getrf` status flag on
1159    /// the forward solve path, so it performs no per-call non-singularity check
1160    /// and issues no host round trip. An exactly singular input is left to the
1161    /// caller's verification, as in `torch.linalg.solve`. A CPU backend may
1162    /// still report its own exactly singular factor as `Error::Singular`.
1163    ///
1164    /// # Errors
1165    ///
1166    /// Returns `tenferro_tensor_core::ShapeMismatch` or
1167    /// `tenferro_tensor_core::ValidationError::DTypeMismatch` for incompatible
1168    /// destination metadata, `tenferro_tensor_core::ValidationError::InvalidArgument`
1169    /// for aliasing or placement violations, `Error::Unsupported` when the
1170    /// provider is unavailable, and `Error::Singular` for a singular system.
1171    ///
1172    /// # Examples
1173    ///
1174    /// ```rust
1175    /// use tenferro_cpu::{with_cpu_engine, CpuEngine};
1176    /// use tenferro_linalg::LinalgBackend;
1177    /// use tenferro_tensor::{Tensor, TensorRead, TensorWrite};
1178    ///
1179    /// let a = Tensor::from_vec_col_major(vec![2, 2], vec![2.0_f64, 0.0, 0.0, 4.0])?;
1180    /// let b = Tensor::from_vec_col_major(vec![2, 1], vec![4.0_f64, 8.0])?;
1181    /// let mut out = Tensor::from_vec_col_major(vec![2, 1], vec![0.0_f64; 2])?;
1182    /// let mut host = tenferro_cpu::CpuEngine::serial();
1183    /// {
1184    ///     with_cpu_engine(&mut host, |backend| {
1185    ///         backend.solve_read_into(
1186    ///             TensorRead::from_tensor(&a),
1187    ///             TensorRead::from_tensor(&b),
1188    ///             TensorWrite::from_tensor(&mut out),
1189    ///         )
1190    ///     })
1191    ///     .expect("CpuEngine must expose a CpuEngine")
1192    /// }?;
1193    /// assert_eq!(out.as_slice::<f64>()?, &[2.0, 2.0]);
1194    /// # Ok::<(), tenferro_tensor::Error>(())
1195    /// ```
1196    fn solve_read_into(
1197        &mut self,
1198        a: TensorRead<'_>,
1199        b: TensorRead<'_>,
1200        out: TensorWrite<'_>,
1201    ) -> tenferro_tensor::Result<()> {
1202        solve_read_into_default(self, a, b, out)
1203    }
1204
1205    #[doc(hidden)]
1206    fn lu_solve_prepared(
1207        &mut self,
1208        _a: &Tensor,
1209        _packed_lu: &Tensor,
1210        _pivots: &Tensor,
1211        _b: &Tensor,
1212        _transpose_a: bool,
1213        _conjugate_a: bool,
1214    ) -> tenferro_tensor::Result<Tensor> {
1215        Err(tenferro_tensor::Error::unsupported(
1216            "lu_solve_prepared",
1217            format!(
1218                "backend {} does not implement internal prepared LU solve",
1219                std::any::type_name::<Self>()
1220            ),
1221        ))
1222    }
1223
1224    /// Factor `a` and solve `a x = b`, returning `(x, packed_lu, pivots)`.
1225    ///
1226    /// This is the fused primal of `lu_factor` followed by
1227    /// `lu_solve_prepared`. The default composes those two hooks; a backend
1228    /// overrides it to run both steps in one batched kernel without the
1229    /// intermediate parity output.
1230    ///
1231    /// # Errors
1232    ///
1233    /// Returns the errors of `lu_factor` and `lu_solve_prepared`, including
1234    /// `Error::Extension` for an exactly singular `a` with a nonempty `b`.
1235    #[doc(hidden)]
1236    fn lu_factor_solve(&mut self, a: &Tensor, b: &Tensor) -> tenferro_tensor::Result<Vec<Tensor>> {
1237        let mut factors = self.lu_factor(a)?.into_iter();
1238        let (Some(packed_lu), Some(pivots)) = (factors.next(), factors.next()) else {
1239            return Err(tenferro_tensor::Error::Internal(
1240                "lu_factor_solve: lu_factor returned fewer than two outputs".into(),
1241            ));
1242        };
1243        let x = self.lu_solve_prepared(a, &packed_lu, &pivots, b, false, false)?;
1244        Ok(vec![x, packed_lu, pivots])
1245    }
1246}
1247
1248pub(crate) fn solve_read_into_default<B: LinalgBackend + ?Sized>(
1249    backend: &mut B,
1250    a: TensorRead<'_>,
1251    b: TensorRead<'_>,
1252    out: TensorWrite<'_>,
1253) -> tenferro_tensor::Result<()> {
1254    validate_solve_read_into(&a, &b, &out)?;
1255    let result = backend.solve_read(a, b)?;
1256    backend.copy_read_into(TensorRead::from_tensor(&result), out)
1257}
1258
1259pub(crate) fn validate_solve_read_into(
1260    _a: &TensorRead<'_>,
1261    b: &TensorRead<'_>,
1262    out: &TensorWrite<'_>,
1263) -> tenferro_tensor::Result<()> {
1264    if b.shape() != out.shape() {
1265        return Err(tenferro_tensor::Error::shape_mismatch(
1266            "solve_read_into",
1267            b.shape().to_vec(),
1268            out.shape().to_vec(),
1269        ));
1270    }
1271    if b.dtype() != out.dtype() {
1272        return Err(tenferro_tensor::Error::dtype_mismatch(
1273            "solve_read_into",
1274            b.dtype(),
1275            out.dtype(),
1276        ));
1277    }
1278    if b.placement() != out.as_read().placement() {
1279        return Err(tenferro_tensor::Error::invalid_argument(
1280            "solve_read_into",
1281            "out",
1282            format!(
1283                "destination placement {:?} does not match rhs placement {:?}",
1284                out.as_read().placement(),
1285                b.placement()
1286            ),
1287        ));
1288    }
1289    let inputs = [_a.clone(), b.clone()];
1290    tenferro_tensor::backend::validate_read_into_destination("solve_read_into", &inputs, out)
1291}