ruxla-kernels 0.1.0

Internal crate of ruxla (use the `ruxla` crate): semantics of ruxla's operations, shared by the native backend and the IR interpreter
Documentation
//! Fast Fourier transforms (`lax.fft`), with XLA's conventions: the
//! forward transforms are not normalized, and the inverse transforms divide
//! by the number of elements transformed.
//!
//! The transforms are computed in `f64` (radix-2 for powers of two,
//! Bluestein's algorithm for other lengths) and rounded once to the result
//! type, so the results agree with XLA's (which computes `complex64` in
//! `f32`) within rounding, not bit for bit.

use std::f64::consts::PI;

use crate::buffer::Buffer;
use crate::complex::c128;
use crate::dtype::DType;

/// The kind of a Fourier transform (`lax.FftType`).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum FftType {
    /// The forward complex-to-complex transform.
    Fft,
    /// The inverse complex-to-complex transform.
    Ifft,
    /// The forward real-to-complex transform: the result has `n / 2 + 1`
    /// elements along the last axis (the others follow by symmetry).
    Rfft,
    /// The inverse complex-to-real transform of `n / 2 + 1` elements along
    /// the last axis.
    Irfft,
}

impl FftType {
    /// Every kind, in the order of JAX's `FftType` values.
    pub const ALL: [FftType; 4] = [FftType::Fft, FftType::Ifft, FftType::Rfft, FftType::Irfft];

    /// The value of JAX's `FftType` (`FFT = 0`, `IFFT = 1`, `RFFT = 2`,
    /// `IRFFT = 3`).
    pub fn index(self) -> u8 {
        match self {
            FftType::Fft => 0,
            FftType::Ifft => 1,
            FftType::Rfft => 2,
            FftType::Irfft => 3,
        }
    }

    /// The kind with a JAX `FftType` value.
    pub fn from_index(i: u8) -> Option<FftType> {
        FftType::ALL.into_iter().find(|t| t.index() == i)
    }

    /// The name, as StableHLO's `fft_type` attribute writes it.
    pub fn name(self) -> &'static str {
        match self {
            FftType::Fft => "FFT",
            FftType::Ifft => "IFFT",
            FftType::Rfft => "RFFT",
            FftType::Irfft => "IRFFT",
        }
    }

    /// The type of the result for an operand of type `dtype`, or `None` if
    /// the transform does not accept it.
    pub fn result_dtype(self, dtype: DType) -> Option<DType> {
        match (self, dtype) {
            (FftType::Fft | FftType::Ifft, DType::C64 | DType::C128) => Some(dtype),
            (FftType::Rfft, DType::F32 | DType::F64) => dtype.complex_dtype(),
            (FftType::Irfft, DType::C64 | DType::C128) => Some(dtype.real_dtype()),
            _ => None,
        }
    }

    /// The shape of the result for an operand of shape `shape`.
    ///
    /// # Panics
    ///
    /// Panics if `fft_lengths` is longer than `shape`.
    pub fn result_shape(self, shape: &[usize], fft_lengths: &[usize]) -> Vec<usize> {
        let mut out = shape.to_vec();
        let rank = out.len();
        let k = fft_lengths.len();
        match self {
            FftType::Fft | FftType::Ifft => {}
            FftType::Rfft => {
                if let Some(&n) = fft_lengths.last() {
                    out[rank - 1] = n / 2 + 1;
                }
            }
            FftType::Irfft => out[rank - k..].copy_from_slice(fft_lengths),
        }
        out
    }
}

/// `fft`: the transform of the last `fft_lengths.len()` axes of `x` (of
/// shape `shape`). The operand must have been checked: its type is accepted
/// by `fft_type`, and its trailing dimensions match `fft_lengths` (for
/// `Irfft`, the last one is `n / 2 + 1`).
pub fn fft(x: &Buffer, shape: &[usize], fft_type: FftType, fft_lengths: &[usize]) -> Buffer {
    let out_dtype = fft_type
        .result_dtype(x.dtype())
        .expect("a checked operand type");
    let data = x
        .convert(DType::C128)
        .as_slice::<c128>()
        .expect("converted")
        .to_vec();
    let rank = shape.len();
    let k = fft_lengths.len();
    let axes = rank - k..rank;
    let out = match fft_type {
        FftType::Fft | FftType::Ifft => {
            let inverse = fft_type == FftType::Ifft;
            let mut v = data;
            for axis in axes {
                transform_axis(&mut v, shape, axis, inverse);
            }
            v
        }
        FftType::Rfft => {
            let mut v = data;
            for axis in axes {
                transform_axis(&mut v, shape, axis, false);
            }
            let out_shape = fft_type.result_shape(shape, fft_lengths);
            truncate_last(&v, shape, out_shape[rank - 1])
        }
        FftType::Irfft => {
            let mut v = data;
            for axis in rank - k..rank - 1 {
                transform_axis(&mut v, shape, axis, true);
            }
            let n = fft_lengths[k - 1];
            let m = shape[rank - 1];
            let lines = v.len().checked_div(m).unwrap_or(0);
            let mut out = Vec::with_capacity(lines * n);
            for l in 0..lines {
                out.extend(inverse_real(&v[l * m..(l + 1) * m], n));
            }
            out
        }
    };
    Buffer::from_vec(out).convert(out_dtype)
}

/// Keeps the first `m` elements of each line along the last axis.
fn truncate_last(v: &[c128], shape: &[usize], m: usize) -> Vec<c128> {
    let n = *shape.last().expect("at least one axis");
    if n == 0 {
        return Vec::new();
    }
    v.chunks_exact(n)
        .flat_map(|l| l[..m].iter().copied())
        .collect()
}

/// The complex-to-real inverse transform of length `n` of the first
/// `n / 2 + 1` coefficients `x`: the spectrum is extended by Hermitian
/// symmetry, and the imaginary parts of the zero (and, for even `n`, the
/// Nyquist) coefficients are ignored.
fn inverse_real(x: &[c128], n: usize) -> Vec<c128> {
    let mut full = vec![c128::default(); n];
    for (j, f) in full.iter_mut().enumerate() {
        let k = if j <= n / 2 { j } else { n - j };
        let v = x.get(k).copied().unwrap_or_default();
        *f = if k == 0 || 2 * k == n {
            c128::new(v.re, 0.0)
        } else if j <= n / 2 {
            v
        } else {
            v.conj()
        };
    }
    dft(&mut full, true);
    full.into_iter()
        .map(|v| c128::new(v.re / n as f64, 0.0))
        .collect()
}

/// Transforms every line of `v` (of shape `shape`) along `axis`; the inverse
/// transform divides by the length.
fn transform_axis(v: &mut [c128], shape: &[usize], axis: usize, inverse: bool) {
    let n = shape[axis];
    if n == 0 || v.is_empty() {
        return;
    }
    let inner: usize = shape[axis + 1..].iter().product();
    let outer = v.len() / (n * inner);
    let mut line = vec![c128::default(); n];
    for o in 0..outer {
        for i in 0..inner {
            let base = o * n * inner + i;
            for (k, l) in line.iter_mut().enumerate() {
                *l = v[base + k * inner];
            }
            dft(&mut line, inverse);
            for (k, l) in line.iter().enumerate() {
                v[base + k * inner] = if inverse {
                    c128::new(l.re / n as f64, l.im / n as f64)
                } else {
                    *l
                };
            }
        }
    }
}

/// `e^(sign * 2 pi i k / n)`.
fn twiddle(k: usize, n: usize, inverse: bool) -> c128 {
    let angle = 2.0 * PI * (k % n) as f64 / n as f64;
    let s = if inverse { 1.0 } else { -1.0 };
    c128::new(angle.cos(), s * angle.sin())
}

/// The unnormalized discrete Fourier transform of `x` in place (with the
/// sign `+` in the exponent for the inverse).
fn dft(x: &mut [c128], inverse: bool) {
    let n = x.len();
    if n <= 1 {
        return;
    }
    if n.is_power_of_two() {
        radix2(x, inverse);
    } else {
        bluestein(x, inverse);
    }
}

/// The iterative radix-2 Cooley-Tukey transform (`n` a power of two).
fn radix2(x: &mut [c128], inverse: bool) {
    let n = x.len();
    let bits = n.trailing_zeros();
    for i in 0..n {
        let j = i.reverse_bits() >> (usize::BITS - bits);
        if i < j {
            x.swap(i, j);
        }
    }
    let mut len = 2;
    while len <= n {
        let half = len / 2;
        let w: Vec<c128> = (0..half).map(|k| twiddle(k, len, inverse)).collect();
        for start in (0..n).step_by(len) {
            for k in 0..half {
                let a = x[start + k];
                let b = x[start + k + half] * w[k];
                x[start + k] = a + b;
                x[start + k + half] = a - b;
            }
        }
        len *= 2;
    }
}

/// Bluestein's transform of any length, as a convolution computed with
/// radix-2 transforms.
fn bluestein(x: &mut [c128], inverse: bool) {
    let n = x.len();
    let m = (2 * n - 1).next_power_of_two();
    // The chirp e^(-+ pi i k^2 / n), with k^2 reduced modulo 2n.
    let chirp: Vec<c128> = (0..n)
        .map(|k| {
            let k2 = (k * k) % (2 * n);
            let angle = PI * k2 as f64 / n as f64;
            let s = if inverse { 1.0 } else { -1.0 };
            c128::new(angle.cos(), s * angle.sin())
        })
        .collect();
    let mut a = vec![c128::default(); m];
    for k in 0..n {
        a[k] = x[k] * chirp[k];
    }
    let mut b = vec![c128::default(); m];
    b[0] = chirp[0].conj();
    for k in 1..n {
        b[k] = chirp[k].conj();
        b[m - k] = chirp[k].conj();
    }
    radix2(&mut a, false);
    radix2(&mut b, false);
    for (p, q) in a.iter_mut().zip(&b) {
        *p = *p * *q;
    }
    radix2(&mut a, true);
    for k in 0..n {
        let c = c128::new(a[k].re / m as f64, a[k].im / m as f64);
        x[k] = c * chirp[k];
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn naive(x: &[c128], inverse: bool) -> Vec<c128> {
        let n = x.len();
        (0..n)
            .map(|k| {
                x.iter().enumerate().fold(c128::default(), |acc, (j, &v)| {
                    acc + v * twiddle(j * k, n, inverse)
                })
            })
            .collect()
    }

    #[test]
    fn transforms_match_the_definition() {
        for n in [1, 2, 3, 5, 8, 12, 16, 17] {
            let x: Vec<c128> = (0..n)
                .map(|i| c128::new((i as f64 * 0.7).sin(), (i as f64 * 1.3).cos()))
                .collect();
            for inverse in [false, true] {
                let mut y = x.clone();
                dft(&mut y, inverse);
                for (a, b) in y.iter().zip(naive(&x, inverse)) {
                    assert!((a.re - b.re).abs() < 1e-12 && (a.im - b.im).abs() < 1e-12);
                }
            }
        }
    }

    #[test]
    fn real_transforms_invert() {
        let x: Vec<f64> = vec![1.0, -2.0, 0.5, 3.0, 4.0, -1.5];
        for n in [5, 6] {
            let x = Buffer::from_vec(x[..n].to_vec());
            let r = fft(&x, &[n], FftType::Rfft, &[n]);
            assert_eq!(r.len(), n / 2 + 1);
            let back = fft(&r, &[n / 2 + 1], FftType::Irfft, &[n]);
            let (a, b) = (
                x.as_slice::<f64>().unwrap(),
                back.as_slice::<f64>().unwrap(),
            );
            for (p, q) in a.iter().zip(b) {
                assert!((p - q).abs() < 1e-12);
            }
        }
    }
}