Skip to main content

ruxla_kernels/
dtype.rs

1//! Element types and conversions between them.
2
3use std::fmt;
4
5use half::{bf16, f16};
6
7use crate::complex::{c64, c128};
8
9/// The element type of a value.
10#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord)]
11pub enum DType {
12    /// `bool`.
13    Bool,
14    /// `i8`.
15    I8,
16    /// `i16`.
17    I16,
18    /// `i32`.
19    I32,
20    /// `i64`.
21    I64,
22    /// `u8`.
23    U8,
24    /// `u16`.
25    U16,
26    /// `u32`.
27    U32,
28    /// `u64`.
29    U64,
30    /// IEEE half precision.
31    F16,
32    /// bfloat16.
33    BF16,
34    /// `f32`.
35    F32,
36    /// `f64`.
37    F64,
38    /// A complex number made of two `f32`s (`complex64`).
39    C64,
40    /// A complex number made of two `f64`s (`complex128`).
41    C128,
42}
43
44/// The kind of an element type.
45#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
46pub enum DTypeKind {
47    /// `bool`.
48    Bool,
49    /// Signed integers.
50    SignedInt,
51    /// Unsigned integers.
52    UnsignedInt,
53    /// Floating point numbers.
54    Float,
55    /// Complex numbers.
56    Complex,
57}
58
59impl DType {
60    /// Every element type.
61    pub const ALL: [DType; 15] = [
62        DType::Bool,
63        DType::I8,
64        DType::I16,
65        DType::I32,
66        DType::I64,
67        DType::U8,
68        DType::U16,
69        DType::U32,
70        DType::U64,
71        DType::F16,
72        DType::BF16,
73        DType::F32,
74        DType::F64,
75        DType::C64,
76        DType::C128,
77    ];
78
79    /// Returns the kind.
80    pub fn kind(self) -> DTypeKind {
81        match self {
82            DType::Bool => DTypeKind::Bool,
83            DType::I8 | DType::I16 | DType::I32 | DType::I64 => DTypeKind::SignedInt,
84            DType::U8 | DType::U16 | DType::U32 | DType::U64 => DTypeKind::UnsignedInt,
85            DType::F16 | DType::BF16 | DType::F32 | DType::F64 => DTypeKind::Float,
86            DType::C64 | DType::C128 => DTypeKind::Complex,
87        }
88    }
89
90    /// Returns whether this is a floating point type.
91    pub fn is_float(self) -> bool {
92        self.kind() == DTypeKind::Float
93    }
94
95    /// Returns whether this is a complex type.
96    pub fn is_complex(self) -> bool {
97        self.kind() == DTypeKind::Complex
98    }
99
100    /// Returns whether this is a floating point or complex type (NumPy's
101    /// `inexact`): the types that have derivatives.
102    pub fn is_inexact(self) -> bool {
103        matches!(self.kind(), DTypeKind::Float | DTypeKind::Complex)
104    }
105
106    /// The type of the real and imaginary parts of a complex type (`f32`
107    /// for `c64`), or the type itself for other types.
108    pub fn real_dtype(self) -> DType {
109        match self {
110            DType::C64 => DType::F32,
111            DType::C128 => DType::F64,
112            d => d,
113        }
114    }
115
116    /// The complex type made of `f32`s or `f64`s, or `None` for other types.
117    pub fn complex_dtype(self) -> Option<DType> {
118        match self {
119            DType::F32 | DType::C64 => Some(DType::C64),
120            DType::F64 | DType::C128 => Some(DType::C128),
121            _ => None,
122        }
123    }
124
125    /// Returns whether this is an integer type.
126    pub fn is_int(self) -> bool {
127        matches!(self.kind(), DTypeKind::SignedInt | DTypeKind::UnsignedInt)
128    }
129
130    /// Returns the size of an element in bytes.
131    pub fn size_in_bytes(self) -> usize {
132        match self {
133            DType::Bool | DType::I8 | DType::U8 => 1,
134            DType::I16 | DType::U16 | DType::F16 | DType::BF16 => 2,
135            DType::I32 | DType::U32 | DType::F32 => 4,
136            DType::I64 | DType::U64 | DType::F64 | DType::C64 => 8,
137            DType::C128 => 16,
138        }
139    }
140
141    /// Returns the name, as JAX prints it in jaxprs (`f32`, `i32`, ...).
142    pub fn name(self) -> &'static str {
143        match self {
144            DType::Bool => "bool",
145            DType::I8 => "i8",
146            DType::I16 => "i16",
147            DType::I32 => "i32",
148            DType::I64 => "i64",
149            DType::U8 => "u8",
150            DType::U16 => "u16",
151            DType::U32 => "u32",
152            DType::U64 => "u64",
153            DType::F16 => "f16",
154            DType::BF16 => "bf16",
155            DType::F32 => "f32",
156            DType::F64 => "f64",
157            DType::C64 => "c64",
158            DType::C128 => "c128",
159        }
160    }
161
162    /// Returns the element type with the given name.
163    pub fn from_name(name: &str) -> Option<DType> {
164        DType::ALL.into_iter().find(|d| d.name() == name)
165    }
166}
167
168impl fmt::Display for DType {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        f.write_str(self.name())
171    }
172}
173
174/// A value of any element type, widened without loss: the common form
175/// through which conversions go.
176#[derive(Clone, Copy, PartialEq, Debug)]
177pub enum Value {
178    /// A boolean.
179    Bool(bool),
180    /// A signed integer.
181    Int(i64),
182    /// An unsigned integer.
183    UInt(u64),
184    /// A floating point number (every element type's values are exact).
185    Float(f64),
186    /// A complex number: the real and imaginary parts.
187    Complex(f64, f64),
188}
189
190mod sealed {
191    pub trait Sealed {}
192}
193
194/// A Rust type that is an element type of ruxla. It is implemented for
195/// `bool`, the integer types, `f16`, `bf16`, `f32`, `f64`, [`c64`], and
196/// [`c128`].
197pub trait Element:
198    Copy
199    + Send
200    + Sync
201    + PartialEq
202    + PartialOrd
203    + Default
204    + fmt::Debug
205    + 'static
206    + sealed::Sealed
207    + crate::ops::Ops
208    + crate::buffer::BufferElement
209{
210    /// The element type.
211    const DTYPE: DType;
212
213    /// The type of the real and imaginary parts of a complex type, or the
214    /// type itself for other types (the type of `abs`).
215    type Real: Element;
216
217    /// The real part (the value itself for other types than complex).
218    fn re(self) -> Self::Real;
219
220    /// The imaginary part (zero for other types than complex).
221    fn im(self) -> Self::Real;
222
223    /// The complex number with the given parts (for other types than
224    /// complex, the real part; the imaginary part is ignored).
225    fn from_parts(re: Self::Real, im: Self::Real) -> Self;
226
227    /// Widens the value without loss.
228    fn to_value(self) -> Value;
229
230    /// Converts a value, with the semantics of XLA's `convert` (see
231    /// [`cast`]).
232    fn from_value(v: Value) -> Self;
233
234    /// Writes the native-endian bytes of the value.
235    fn write_bytes(self, out: &mut Vec<u8>);
236
237    /// Reads a value from native-endian bytes of the right length.
238    fn read_bytes(bytes: &[u8]) -> Self;
239
240    /// The bit pattern, zero-extended to 64 bits (`bool` is 0 or 1).
241    fn to_bits(self) -> u64;
242
243    /// The value of a bit pattern in the low bits (the rest is ignored).
244    fn from_bits(bits: u64) -> Self;
245}
246
247/// Converts between element types with the semantics of XLA's `convert` on
248/// CPU:
249///
250/// - from complex to other types: the real part is converted (as
251///   `lax.convert_element_type` lowers it);
252/// - to complex: the real part is converted, and the imaginary part is 0;
253/// - to `bool`: nonzero (and NaN) is `true`;
254/// - float to integer: rounds toward zero and saturates; NaN is 0;
255/// - integer to integer: wraps around;
256/// - to `f32` and `f64`: rounded once;
257/// - to `f16` and `bf16`: rounded through `f32`, as XLA does.
258#[inline]
259pub fn cast<T: Element, U: Element>(x: T) -> U {
260    U::from_value(x.to_value())
261}
262
263macro_rules! impl_int {
264    ($($t:ty => $d:ident, $v:ident;)*) => {$(
265        impl sealed::Sealed for $t {}
266        impl Element for $t {
267            const DTYPE: DType = DType::$d;
268            type Real = $t;
269            #[inline]
270            fn re(self) -> Self {
271                self
272            }
273            #[inline]
274            fn im(self) -> Self {
275                Self::default()
276            }
277            #[inline]
278            fn from_parts(re: Self, _: Self) -> Self {
279                re
280            }
281            #[inline]
282            fn to_value(self) -> Value {
283                Value::$v(self as _)
284            }
285            #[inline]
286            fn from_value(v: Value) -> Self {
287                match v {
288                    Value::Bool(b) => b as $t,
289                    Value::Int(i) => i as $t,
290                    Value::UInt(u) => u as $t,
291                    // `as` rounds toward zero, saturates, and maps NaN to 0.
292                    Value::Float(f) | Value::Complex(f, _) => f as $t,
293                }
294            }
295            fn write_bytes(self, out: &mut Vec<u8>) {
296                out.extend_from_slice(&self.to_ne_bytes());
297            }
298            fn read_bytes(bytes: &[u8]) -> Self {
299                <$t>::from_ne_bytes(bytes.try_into().expect("element size"))
300            }
301            #[inline]
302            fn to_bits(self) -> u64 {
303                (self as u64) & (u64::MAX >> (64 - <$t>::BITS))
304            }
305            #[inline]
306            fn from_bits(bits: u64) -> Self {
307                bits as $t
308            }
309        }
310    )*};
311}
312
313impl_int! {
314    i8 => I8, Int;
315    i16 => I16, Int;
316    i32 => I32, Int;
317    i64 => I64, Int;
318    u8 => U8, UInt;
319    u16 => U16, UInt;
320    u32 => U32, UInt;
321    u64 => U64, UInt;
322}
323
324impl sealed::Sealed for bool {}
325impl Element for bool {
326    const DTYPE: DType = DType::Bool;
327    type Real = bool;
328    #[inline]
329    fn re(self) -> Self {
330        self
331    }
332    #[inline]
333    fn im(self) -> Self {
334        Self::default()
335    }
336    #[inline]
337    fn from_parts(re: Self, _: Self) -> Self {
338        re
339    }
340    #[inline]
341    fn to_value(self) -> Value {
342        Value::Bool(self)
343    }
344    #[inline]
345    fn from_value(v: Value) -> Self {
346        match v {
347            Value::Bool(b) => b,
348            Value::Int(i) => i != 0,
349            Value::UInt(u) => u != 0,
350            Value::Float(f) | Value::Complex(f, _) => f != 0.0,
351        }
352    }
353    fn write_bytes(self, out: &mut Vec<u8>) {
354        out.push(u8::from(self));
355    }
356    fn read_bytes(bytes: &[u8]) -> Self {
357        bytes[0] != 0
358    }
359    #[inline]
360    fn to_bits(self) -> u64 {
361        u64::from(self)
362    }
363    #[inline]
364    fn from_bits(bits: u64) -> Self {
365        bits & 1 != 0
366    }
367}
368
369impl sealed::Sealed for f64 {}
370impl Element for f64 {
371    const DTYPE: DType = DType::F64;
372    type Real = f64;
373    #[inline]
374    fn re(self) -> Self {
375        self
376    }
377    #[inline]
378    fn im(self) -> Self {
379        Self::default()
380    }
381    #[inline]
382    fn from_parts(re: Self, _: Self) -> Self {
383        re
384    }
385    #[inline]
386    fn to_value(self) -> Value {
387        Value::Float(self)
388    }
389    #[inline]
390    fn from_value(v: Value) -> Self {
391        match v {
392            Value::Bool(b) => f64::from(u8::from(b)),
393            Value::Int(i) => i as f64,
394            Value::UInt(u) => u as f64,
395            Value::Float(f) | Value::Complex(f, _) => f,
396        }
397    }
398    fn write_bytes(self, out: &mut Vec<u8>) {
399        out.extend_from_slice(&self.to_ne_bytes());
400    }
401    fn read_bytes(bytes: &[u8]) -> Self {
402        f64::from_ne_bytes(bytes.try_into().expect("element size"))
403    }
404    #[inline]
405    fn to_bits(self) -> u64 {
406        f64::to_bits(self)
407    }
408    #[inline]
409    fn from_bits(bits: u64) -> Self {
410        f64::from_bits(bits)
411    }
412}
413
414impl sealed::Sealed for f32 {}
415impl Element for f32 {
416    const DTYPE: DType = DType::F32;
417    type Real = f32;
418    #[inline]
419    fn re(self) -> Self {
420        self
421    }
422    #[inline]
423    fn im(self) -> Self {
424        Self::default()
425    }
426    #[inline]
427    fn from_parts(re: Self, _: Self) -> Self {
428        re
429    }
430    #[inline]
431    fn to_value(self) -> Value {
432        Value::Float(f64::from(self))
433    }
434    #[inline]
435    fn from_value(v: Value) -> Self {
436        match v {
437            Value::Bool(b) => f32::from(u8::from(b)),
438            // `as` rounds integers to f32 once (correctly rounded).
439            Value::Int(i) => i as f32,
440            Value::UInt(u) => u as f32,
441            Value::Float(f) | Value::Complex(f, _) => f as f32,
442        }
443    }
444    fn write_bytes(self, out: &mut Vec<u8>) {
445        out.extend_from_slice(&self.to_ne_bytes());
446    }
447    fn read_bytes(bytes: &[u8]) -> Self {
448        f32::from_ne_bytes(bytes.try_into().expect("element size"))
449    }
450    #[inline]
451    fn to_bits(self) -> u64 {
452        u64::from(f32::to_bits(self))
453    }
454    #[inline]
455    fn from_bits(bits: u64) -> Self {
456        f32::from_bits(bits as u32)
457    }
458}
459
460macro_rules! impl_half {
461    ($($t:ty => $d:ident;)*) => {$(
462        impl sealed::Sealed for $t {}
463        impl Element for $t {
464            const DTYPE: DType = DType::$d;
465            type Real = $t;
466            #[inline]
467            fn re(self) -> Self {
468                self
469            }
470            #[inline]
471            fn im(self) -> Self {
472                Self::default()
473            }
474            #[inline]
475            fn from_parts(re: Self, _: Self) -> Self {
476                re
477            }
478            #[inline]
479            fn to_value(self) -> Value {
480                Value::Float(self.to_f64())
481            }
482            #[inline]
483            fn from_value(v: Value) -> Self {
484                // Through f32, as XLA converts to 16-bit floats.
485                <$t>::from_f32(f32::from_value(v))
486            }
487            fn write_bytes(self, out: &mut Vec<u8>) {
488                out.extend_from_slice(&self.to_ne_bytes());
489            }
490            fn read_bytes(bytes: &[u8]) -> Self {
491                <$t>::from_ne_bytes(bytes.try_into().expect("element size"))
492            }
493            #[inline]
494            fn to_bits(self) -> u64 {
495                u64::from(<$t>::to_bits(self))
496            }
497            #[inline]
498            fn from_bits(bits: u64) -> Self {
499                <$t>::from_bits(bits as u16)
500            }
501        }
502    )*};
503}
504
505impl_half! {
506    f16 => F16;
507    bf16 => BF16;
508}
509
510macro_rules! impl_complex {
511    ($($t:ty => $d:ident, $f:ty, $bits:ty;)*) => {$(
512        impl sealed::Sealed for $t {}
513        impl Element for $t {
514            const DTYPE: DType = DType::$d;
515            type Real = $f;
516            #[inline]
517            fn re(self) -> $f {
518                self.re
519            }
520            #[inline]
521            fn im(self) -> $f {
522                self.im
523            }
524            #[inline]
525            fn from_parts(re: $f, im: $f) -> Self {
526                Self::new(re, im)
527            }
528            #[inline]
529            fn to_value(self) -> Value {
530                Value::Complex(f64::from(self.re), f64::from(self.im))
531            }
532            #[inline]
533            fn from_value(v: Value) -> Self {
534                match v {
535                    Value::Complex(re, im) => Self::new(re as $f, im as $f),
536                    v => Self::new(<$f>::from_value(v), 0.0),
537                }
538            }
539            fn write_bytes(self, out: &mut Vec<u8>) {
540                out.extend_from_slice(&self.re.to_ne_bytes());
541                out.extend_from_slice(&self.im.to_ne_bytes());
542            }
543            fn read_bytes(bytes: &[u8]) -> Self {
544                let (re, im) = bytes.split_at(bytes.len() / 2);
545                Self::new(
546                    <$f>::from_ne_bytes(re.try_into().expect("element size")),
547                    <$f>::from_ne_bytes(im.try_into().expect("element size")),
548                )
549            }
550            /// The bits of the real part in the low half and those of the
551            /// imaginary part in the high half (`c128` has more bits than
552            /// fit, and panics).
553            #[inline]
554            fn to_bits(self) -> u64 {
555                assert!(
556                    std::mem::size_of::<$bits>() <= 4,
557                    "{} has more than 64 bits",
558                    Self::DTYPE
559                );
560                (self.re.to_bits() as u64) | ((self.im.to_bits() as u64) << 32)
561            }
562            #[inline]
563            fn from_bits(bits: u64) -> Self {
564                assert!(
565                    std::mem::size_of::<$bits>() <= 4,
566                    "{} has more than 64 bits",
567                    Self::DTYPE
568                );
569                Self::new(<$f>::from_bits(bits as $bits), <$f>::from_bits((bits >> 32) as $bits))
570            }
571        }
572    )*};
573}
574
575impl_complex! {
576    c64 => C64, f32, u32;
577    c128 => C128, f64, u64;
578}
579
580#[cfg(test)]
581mod tests {
582    use super::*;
583
584    #[test]
585    fn conversions_follow_xla() {
586        assert_eq!(cast::<f32, i32>(f32::NAN), 0);
587        assert_eq!(cast::<f32, i32>(1e10), i32::MAX);
588        assert_eq!(cast::<f32, u8>(-3.5), 0);
589        assert_eq!(cast::<i32, u8>(-2), 254);
590        assert!(cast::<f32, bool>(f32::NAN));
591        assert_eq!(cast::<bool, f32>(true), 1.0);
592        // Integers are rounded to f32 once: halfway between two f32s plus
593        // one rounds up, although the nearest f64 is exactly halfway.
594        let x = (1i64 << 60) + (1 << 36) + 1;
595        assert_eq!(cast::<i64, f32>(x), ((1i64 << 60) + (1 << 37)) as f32);
596        // 16-bit floats are rounded through f32.
597        let y = (1u64 << 60) + (1 << 52) + 1;
598        assert_eq!(cast::<u64, bf16>(y), bf16::from_f32((1u64 << 60) as f32));
599    }
600
601    #[test]
602    fn bits_round_trip() {
603        assert_eq!((-1i8).to_bits(), 0xFF);
604        assert_eq!(i8::from_bits(0xFF), -1);
605        assert_eq!(f32::from_bits(1.5f32.to_bits()), 1.5);
606        assert_eq!(bf16::from_bits(bf16::ONE.to_bits()), bf16::ONE);
607        assert_eq!(<u16 as Element>::to_bits(0xABCD), 0xABCD);
608    }
609
610    #[test]
611    fn names_round_trip() {
612        for d in DType::ALL {
613            assert_eq!(DType::from_name(d.name()), Some(d));
614        }
615    }
616}