Skip to main content

tenferro_tensor/
dest.rs

1//! Output destinations for `_into` operations (the #2552 `Dest` grammar).
2//!
3//! [`Dest`] states where an operation writes and how the result combines with
4//! the previous contents. Conjugation is operation configuration and lives in
5//! the operation's options, never here.
6
7use crate::{
8    Complex32, Complex64, ContractionScalar, DType, DotGeneralAccumulation, Error, Tensor,
9    TensorViewMut, TensorWrite, ValidationError,
10};
11
12/// Whether an operand enters an operation conjugated. Conjugation is operation
13/// configuration, so it lives in the operation's options, never in [`Dest`].
14///
15/// # Examples
16///
17/// ```
18/// use tenferro_tensor::Conj;
19///
20/// assert_eq!(Conj::default(), Conj::No);
21/// assert!(Conj::Yes.is_yes());
22/// assert!(!Conj::No.is_yes());
23/// ```
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
25pub enum Conj {
26    /// Use the operand as it is.
27    #[default]
28    No,
29    /// Use the complex conjugate of the operand.
30    Yes,
31}
32
33impl Conj {
34    /// Return `true` for [`Conj::Yes`].
35    ///
36    /// # Examples
37    ///
38    /// ```
39    /// use tenferro_tensor::Conj;
40    ///
41    /// assert!(Conj::Yes.is_yes());
42    /// ```
43    pub fn is_yes(self) -> bool {
44        matches!(self, Self::Yes)
45    }
46}
47
48/// Options of `dot_general`: which operand enters conjugated.
49///
50/// # Examples
51///
52/// ```
53/// use tenferro_tensor::{Conj, DotGeneralOptions};
54///
55/// let options = DotGeneralOptions::default().lhs(Conj::Yes);
56/// assert_eq!((options.lhs, options.rhs), (Conj::Yes, Conj::No));
57/// ```
58#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
59#[non_exhaustive]
60pub struct DotGeneralOptions {
61    /// Conjugate the left operand. The default is [`Conj::No`].
62    pub lhs: Conj,
63    /// Conjugate the right operand. The default is [`Conj::No`].
64    pub rhs: Conj,
65}
66
67impl DotGeneralOptions {
68    /// Return options with the requested left-operand conjugation.
69    ///
70    /// # Examples
71    ///
72    /// ```
73    /// use tenferro_tensor::{Conj, DotGeneralOptions};
74    ///
75    /// assert_eq!(DotGeneralOptions::default().lhs(Conj::Yes).lhs, Conj::Yes);
76    /// ```
77    pub fn lhs(mut self, lhs: Conj) -> Self {
78        self.lhs = lhs;
79        self
80    }
81
82    /// Return options with the requested right-operand conjugation.
83    ///
84    /// # Examples
85    ///
86    /// ```
87    /// use tenferro_tensor::{Conj, DotGeneralOptions};
88    ///
89    /// assert_eq!(DotGeneralOptions::default().rhs(Conj::Yes).rhs, Conj::Yes);
90    /// ```
91    pub fn rhs(mut self, rhs: Conj) -> Self {
92        self.rhs = rhs;
93        self
94    }
95}
96
97/// Which [`Dest`] variant a destination is, without its target.
98///
99/// The operation registry uses this to declare the accepted modes.
100///
101/// # Examples
102///
103/// ```
104/// use tenferro_tensor::{Dest, DestMode, Tensor};
105///
106/// let mut t = Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?;
107/// let dest: Dest<tenferro_tensor::TensorWrite<'_>> = Dest::accumulate(&mut t);
108/// assert_eq!(dest.mode(), DestMode::Accumulate);
109/// # Ok::<(), tenferro_tensor::Error>(())
110/// ```
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
112pub enum DestMode {
113    /// [`Dest::Overwrite`].
114    Overwrite,
115    /// [`Dest::Accumulate`].
116    Accumulate,
117    /// [`Dest::Scaled`].
118    Scaled,
119}
120
121/// Where an `_into` operation writes, and how it combines with what is there.
122///
123/// `W` is `TensorWrite<'a>` for dtype-erased outputs and
124/// `TypedTensorWrite<'a, T>` for typed outputs.
125///
126/// # Examples
127///
128/// ```
129/// use tenferro_tensor::{Dest, DestMode, Tensor, TensorWrite};
130///
131/// let mut out = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
132/// let dest: Dest<TensorWrite<'_>> = Dest::scaled(&mut out, 2.0_f64, 0.5_f64);
133/// assert_eq!(dest.mode(), DestMode::Scaled);
134/// assert_eq!(dest.target().shape(), &[2]);
135/// # Ok::<(), tenferro_tensor::Error>(())
136/// ```
137#[derive(Debug)]
138#[non_exhaustive]
139pub enum Dest<W> {
140    /// `out = op(...)`; the previous contents are never read.
141    Overwrite(W),
142    /// `out = op(...) + out`.
143    Accumulate(W),
144    /// `out = alpha * op(...) + beta * out`; with `beta == 0` the previous
145    /// contents are never read (NaN or -0 in `out` does not leak).
146    Scaled {
147        /// The destination.
148        out: W,
149        /// Scale applied to the operation result.
150        alpha: ContractionScalar,
151        /// Scale applied to the previous contents of `out`.
152        beta: ContractionScalar,
153    },
154}
155
156impl<W> Dest<W> {
157    /// Build an [`Dest::Overwrite`] destination.
158    ///
159    /// # Examples
160    ///
161    /// ```
162    /// use tenferro_tensor::{Dest, DestMode, Tensor, TensorWrite};
163    ///
164    /// let mut t = Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?;
165    /// let dest: Dest<TensorWrite<'_>> = Dest::overwrite(&mut t);
166    /// assert_eq!(dest.mode(), DestMode::Overwrite);
167    /// # Ok::<(), tenferro_tensor::Error>(())
168    /// ```
169    pub fn overwrite(out: impl Into<W>) -> Self {
170        Self::Overwrite(out.into())
171    }
172
173    /// Build an [`Dest::Accumulate`] destination.
174    ///
175    /// # Examples
176    ///
177    /// ```
178    /// use tenferro_tensor::{Dest, DestMode, Tensor, TensorWrite};
179    ///
180    /// let mut t = Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?;
181    /// let dest: Dest<TensorWrite<'_>> = Dest::accumulate(&mut t);
182    /// assert_eq!(dest.mode(), DestMode::Accumulate);
183    /// # Ok::<(), tenferro_tensor::Error>(())
184    /// ```
185    pub fn accumulate(out: impl Into<W>) -> Self {
186        Self::Accumulate(out.into())
187    }
188
189    /// Build a [`Dest::Scaled`] destination, `out = alpha * op + beta * out`.
190    ///
191    /// # Examples
192    ///
193    /// ```
194    /// use tenferro_tensor::{Dest, DestMode, Tensor, TensorWrite};
195    ///
196    /// let mut t = Tensor::from_vec_col_major(vec![1], vec![0.0_f64])?;
197    /// let dest: Dest<TensorWrite<'_>> = Dest::scaled(&mut t, 1.0_f64, 0.0_f64);
198    /// assert_eq!(dest.mode(), DestMode::Scaled);
199    /// # Ok::<(), tenferro_tensor::Error>(())
200    /// ```
201    pub fn scaled(
202        out: impl Into<W>,
203        alpha: impl Into<ContractionScalar>,
204        beta: impl Into<ContractionScalar>,
205    ) -> Self {
206        Self::Scaled {
207            out: out.into(),
208            alpha: alpha.into(),
209            beta: beta.into(),
210        }
211    }
212
213    /// Return which variant this destination is, without its target.
214    ///
215    /// # Examples
216    ///
217    /// ```
218    /// use tenferro_tensor::{Dest, DestMode};
219    ///
220    /// let dest = Dest::Overwrite(());
221    /// assert_eq!(dest.mode(), DestMode::Overwrite);
222    /// ```
223    pub fn mode(&self) -> DestMode {
224        match self {
225            Self::Overwrite(_) => DestMode::Overwrite,
226            Self::Accumulate(_) => DestMode::Accumulate,
227            Self::Scaled { .. } => DestMode::Scaled,
228        }
229    }
230
231    /// Borrow the destination.
232    ///
233    /// # Examples
234    ///
235    /// ```
236    /// use tenferro_tensor::Dest;
237    ///
238    /// let dest = Dest::Accumulate(7);
239    /// assert_eq!(*dest.target(), 7);
240    /// ```
241    pub fn target(&self) -> &W {
242        match self {
243            Self::Overwrite(out) | Self::Accumulate(out) | Self::Scaled { out, .. } => out,
244        }
245    }
246
247    /// Consume the destination and return its target.
248    ///
249    /// # Examples
250    ///
251    /// ```
252    /// use tenferro_tensor::Dest;
253    ///
254    /// assert_eq!(Dest::Overwrite(7).into_target(), 7);
255    /// ```
256    pub fn into_target(self) -> W {
257        match self {
258            Self::Overwrite(out) | Self::Accumulate(out) | Self::Scaled { out, .. } => out,
259        }
260    }
261
262    /// Map this destination to the backend accumulation contract.
263    ///
264    /// Owner-scoped bridge owned by `tenferro-tensor` for the #2552
265    /// `Dest` to [`DotGeneralAccumulation`] mapping; it is not user API.
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use tenferro_tensor::{Conj, ContractionScalar, DType, Dest};
271    ///
272    /// let (out, accum) = Dest::Accumulate(5).into_accumulation(DType::F64, Conj::Yes, Conj::No)?;
273    /// assert_eq!(out, 5);
274    /// assert_eq!(accum.beta, ContractionScalar::F64(1.0));
275    /// assert!(accum.lhs_conj && !accum.rhs_conj);
276    /// # Ok::<(), tenferro_tensor::Error>(())
277    /// ```
278    ///
279    /// # Errors
280    ///
281    /// Returns [`Error::Validation`] with a [`ValidationError::DTypeMismatch`]
282    /// source when `dtype` has no contraction scalar or `alpha`/`beta` of a
283    /// scaled destination do not have `dtype`.
284    #[doc(hidden)]
285    pub fn into_accumulation(
286        self,
287        dtype: DType,
288        lhs: Conj,
289        rhs: Conj,
290    ) -> crate::Result<(W, DotGeneralAccumulation)> {
291        const OP: &str = "Dest::into_accumulation";
292        let (out, mut accum) = match self {
293            Self::Overwrite(out) => (out, DotGeneralAccumulation::overwrite(dtype)?),
294            Self::Accumulate(out) => (out, DotGeneralAccumulation::add_to(dtype)?),
295            Self::Scaled { out, alpha, beta } => {
296                for scalar in [alpha, beta] {
297                    if scalar.dtype() != dtype {
298                        return Err(Error::validation(
299                            OP,
300                            ValidationError::DTypeMismatch {
301                                expected: dtype,
302                                actual: scalar.dtype(),
303                            },
304                        ));
305                    }
306                }
307                let accum = DotGeneralAccumulation {
308                    lhs_conj: false,
309                    rhs_conj: false,
310                    alpha,
311                    beta,
312                };
313                (out, accum)
314            }
315        };
316        accum.lhs_conj = lhs.is_yes();
317        accum.rhs_conj = rhs.is_yes();
318        Ok((out, accum))
319    }
320}
321
322impl<'a> From<&'a mut Tensor> for TensorWrite<'a> {
323    fn from(tensor: &'a mut Tensor) -> Self {
324        TensorWrite::from_tensor(tensor)
325    }
326}
327
328impl<'a> From<TensorViewMut<'a>> for TensorWrite<'a> {
329    fn from(view: TensorViewMut<'a>) -> Self {
330        TensorWrite::from_view(view)
331    }
332}
333
334impl From<f32> for ContractionScalar {
335    fn from(value: f32) -> Self {
336        Self::F32(value)
337    }
338}
339
340impl From<f64> for ContractionScalar {
341    fn from(value: f64) -> Self {
342        Self::F64(value)
343    }
344}
345
346impl From<Complex32> for ContractionScalar {
347    fn from(value: Complex32) -> Self {
348        Self::C32(value)
349    }
350}
351
352impl From<Complex64> for ContractionScalar {
353    fn from(value: Complex64) -> Self {
354        Self::C64(value)
355    }
356}
357
358#[cfg(test)]
359mod tests;