Skip to main content

burn_std/data/
compare.rs

1use alloc::format;
2use alloc::string::String;
3use num_traits::{Float, ToPrimitive};
4
5use super::TensorData;
6use crate::{
7    BoolStore, DType, Element, ElementOrdered, bf16, f16, quantization::global_scale_dtype,
8};
9
10/// The tolerance used to compare to floating point numbers.
11///
12/// Generally, two numbers `x` and `y` are approximately equal if
13///
14/// ```text
15/// |x - y| < max(R * (|x + y|), A)
16/// ```
17///
18/// where `R` is the relative tolerance and `A` is the absolute tolerance.
19///
20///
21/// The most common way to initialize this struct is to use `Tolerance::<F>::default()`.
22/// In that case, the relative and absolute tolerances are computed using an heuristic based
23/// on the EPSILON and MIN_POSITIVE values of the given floating point type `F`.
24///
25/// Another common initialization is `Tolerance::<F>::rel_abs(1e-4, 1e-5).set_half_precision_relative(1e-2)`.
26/// This will use a sane default to manage values too close to 0.0 and
27/// use different relative tolerances depending on the floating point precision.
28#[derive(Debug, Clone, Copy)]
29pub struct Tolerance<F> {
30    relative: F,
31    absolute: F,
32}
33
34impl<F: Float> Default for Tolerance<F> {
35    fn default() -> Self {
36        Self::balanced()
37    }
38}
39
40impl<F: Float> Tolerance<F> {
41    /// Create a tolerance with strict precision setting.
42    pub fn strict() -> Self {
43        Self {
44            relative: F::from(0.00).unwrap(),
45            absolute: F::from(64).unwrap() * F::min_positive_value(),
46        }
47    }
48    /// Create a tolerance with balanced precision setting.
49    pub fn balanced() -> Self {
50        Self {
51            relative: F::from(0.005).unwrap(), // 0.5%
52            absolute: F::from(1e-5).unwrap(),
53        }
54    }
55
56    /// Create a tolerance with permissive precision setting.
57    pub fn permissive() -> Self {
58        Self {
59            relative: F::from(0.01).unwrap(), // 1.0%
60            absolute: F::from(0.01).unwrap(),
61        }
62    }
63    /// When comparing two numbers, this uses both the relative and absolute differences.
64    ///
65    /// That is, `x` and `y` are approximately equal if
66    ///
67    /// ```text
68    /// |x - y| < max(R * (|x + y|), A)
69    /// ```
70    ///
71    /// where `R` is the `relative` tolerance and `A` is the `absolute` tolerance.
72    pub fn rel_abs<FF: ToPrimitive>(relative: FF, absolute: FF) -> Self {
73        let relative = Self::check_relative(relative);
74        let absolute = Self::check_absolute(absolute);
75
76        Self { relative, absolute }
77    }
78
79    /// When comparing two numbers, this uses only the relative difference.
80    ///
81    /// That is, `x` and `y` are approximately equal if
82    ///
83    /// ```text
84    /// |x - y| < R * max(|x|, |y|)
85    /// ```
86    ///
87    /// where `R` is the relative `tolerance`.
88    pub fn relative<FF: ToPrimitive>(tolerance: FF) -> Self {
89        let relative = Self::check_relative(tolerance);
90
91        Self {
92            relative,
93            absolute: F::from(0.0).unwrap(),
94        }
95    }
96
97    /// When comparing two numbers, this uses only the absolute difference.
98    ///
99    /// That is, `x` and `y` are approximately equal if
100    ///
101    /// ```text
102    /// |x - y| < A
103    /// ```
104    ///
105    /// where `A` is the absolute `tolerance`.
106    pub fn absolute<FF: ToPrimitive>(tolerance: FF) -> Self {
107        let absolute = Self::check_absolute(tolerance);
108
109        Self {
110            relative: F::from(0.0).unwrap(),
111            absolute,
112        }
113    }
114
115    /// Change the relative tolerance to the given one.
116    pub fn set_relative<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
117        self.relative = Self::check_relative(tolerance);
118        self
119    }
120
121    /// Change the relative tolerance to the given one only if `F` is half precision.
122    pub fn set_half_precision_relative<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
123        if core::mem::size_of::<F>() == 2 {
124            self.relative = Self::check_relative(tolerance);
125        }
126        self
127    }
128
129    /// Change the relative tolerance to the given one only if `F` is single precision.
130    pub fn set_single_precision_relative<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
131        if core::mem::size_of::<F>() == 4 {
132            self.relative = Self::check_relative(tolerance);
133        }
134        self
135    }
136
137    /// Change the relative tolerance to the given one only if `F` is double precision.
138    pub fn set_double_precision_relative<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
139        if core::mem::size_of::<F>() == 8 {
140            self.relative = Self::check_relative(tolerance);
141        }
142        self
143    }
144
145    /// Change the absolute tolerance to the given one.
146    pub fn set_absolute<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
147        self.absolute = Self::check_absolute(tolerance);
148        self
149    }
150
151    /// Change the absolute tolerance to the given one only if `F` is half precision.
152    pub fn set_half_precision_absolute<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
153        if core::mem::size_of::<F>() == 2 {
154            self.absolute = Self::check_absolute(tolerance);
155        }
156        self
157    }
158
159    /// Change the absolute tolerance to the given one only if `F` is single precision.
160    pub fn set_single_precision_absolute<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
161        if core::mem::size_of::<F>() == 4 {
162            self.absolute = Self::check_absolute(tolerance);
163        }
164        self
165    }
166
167    /// Change the absolute tolerance to the given one only if `F` is double precision.
168    pub fn set_double_precision_absolute<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
169        if core::mem::size_of::<F>() == 8 {
170            self.absolute = Self::check_absolute(tolerance);
171        }
172        self
173    }
174
175    /// Checks if `x` and `y` are approximately equal given the tolerance.
176    pub fn approx_eq(&self, x: F, y: F) -> bool {
177        // See the accepted answer here
178        // https://stackoverflow.com/questions/4915462/how-should-i-do-floating-point-comparison
179
180        // This also handles the case where both a and b are infinity so that we don't need
181        // to manage it in the rest of the function.
182        if x == y {
183            return true;
184        }
185
186        let diff = (x - y).abs();
187        let max = F::max(x.abs(), y.abs());
188
189        diff < self.absolute.max(self.relative * max)
190    }
191
192    fn check_relative<FF: ToPrimitive>(tolerance: FF) -> F {
193        let tolerance = F::from(tolerance).unwrap();
194        assert!(tolerance <= F::one());
195        tolerance
196    }
197
198    fn check_absolute<FF: ToPrimitive>(tolerance: FF) -> F {
199        let tolerance = F::from(tolerance).unwrap();
200        assert!(tolerance >= F::zero());
201        tolerance
202    }
203}
204
205impl TensorData {
206    /// Asserts the data is equal to another data.
207    ///
208    /// # Arguments
209    ///
210    /// * `other` - The other data.
211    /// * `strict` - If true, the data types must the be same.
212    ///   Otherwise, the comparison is done in the current data type.
213    ///
214    /// # Panics
215    ///
216    /// Panics if the data is not equal.
217    #[track_caller]
218    pub fn assert_eq(&self, other: &Self, strict: bool) {
219        if strict {
220            assert_eq!(
221                self.dtype, other.dtype,
222                "Data types differ ({:?} != {:?})",
223                self.dtype, other.dtype
224            );
225        }
226
227        match self.dtype {
228            DType::F64 => self.assert_eq_elem::<f64>(other),
229            DType::F32 | DType::Flex32 => self.assert_eq_elem::<f32>(other),
230            DType::F16 => self.assert_eq_elem::<f16>(other),
231            DType::BF16 => self.assert_eq_elem::<bf16>(other),
232            DType::I64 => self.assert_eq_elem::<i64>(other),
233            DType::I32 => self.assert_eq_elem::<i32>(other),
234            DType::I16 => self.assert_eq_elem::<i16>(other),
235            DType::I8 => self.assert_eq_elem::<i8>(other),
236            DType::U64 => self.assert_eq_elem::<u64>(other),
237            DType::U32 => self.assert_eq_elem::<u32>(other),
238            DType::U16 => self.assert_eq_elem::<u16>(other),
239            DType::U8 => self.assert_eq_elem::<u8>(other),
240            DType::Bool(BoolStore::Native) => self.assert_eq_elem::<bool>(other),
241            DType::Bool(BoolStore::U8) => self.assert_eq_elem::<u8>(other),
242            DType::Bool(BoolStore::U32) => self.assert_eq_elem::<u32>(other),
243            DType::QFloat(q) => {
244                // Strict or not, it doesn't make sense to compare quantized data to not quantized data for equality
245                let q_other = if let DType::QFloat(q_other) = other.dtype {
246                    q_other
247                } else {
248                    panic!("Quantized data differs from other not quantized data")
249                };
250
251                // Data equality mostly depends on input quantization type, but we also check levels
252                if q.value == q_other.value
253                    && q.block_size() == q_other.block_size()
254                    && global_scale_dtype(&q) == global_scale_dtype(&q_other)
255                {
256                    self.assert_eq_elem::<i8>(other)
257                } else {
258                    panic!("Quantization schemes differ ({q:?} != {q_other:?})")
259                }
260            }
261        }
262    }
263
264    #[track_caller]
265    fn assert_eq_elem<E: Element>(&self, other: &Self) {
266        let mut message = String::new();
267        if self.shape != other.shape {
268            message += format!(
269                "\n  => Shape is different: {:?} != {:?}",
270                self.shape, other.shape
271            )
272            .as_str();
273        }
274
275        let mut num_diff = 0;
276        let max_num_diff = 5;
277        for (i, (a, b)) in self.iter::<E>().zip(other.iter::<E>()).enumerate() {
278            if !a.eq(&b) {
279                // Only print the first 5 different values.
280                if num_diff < max_num_diff {
281                    message += format!("\n  => Position {i}: {a} != {b}").as_str();
282                }
283                num_diff += 1;
284            }
285        }
286
287        if num_diff >= max_num_diff {
288            message += format!("\n{} more errors...", num_diff - max_num_diff).as_str();
289        }
290
291        if !message.is_empty() {
292            panic!("Tensors are not eq:{message}");
293        }
294    }
295
296    /// Asserts the data is approximately equal to another data.
297    ///
298    /// # Arguments
299    ///
300    /// * `other` - The other data.
301    /// * `tolerance` - The tolerance of the comparison.
302    ///
303    /// # Panics
304    ///
305    /// Panics if the data is not approximately equal.
306    #[track_caller]
307    pub fn assert_approx_eq<F: Float + Element>(&self, other: &Self, tolerance: Tolerance<F>) {
308        let mut message = String::new();
309        if self.shape != other.shape {
310            message += format!(
311                "\n  => Shape is different: {:?} != {:?}",
312                self.shape, other.shape
313            )
314            .as_str();
315        }
316
317        let iter = self.iter::<F>().zip(other.iter::<F>());
318
319        let mut num_diff = 0;
320        let max_num_diff = 5;
321
322        for (i, (a, b)) in iter.enumerate() {
323            //if they are both nan, then they are equally nan
324            let both_nan = a.is_nan() && b.is_nan();
325            //this works for both infinities
326            let both_inf =
327                a.is_infinite() && b.is_infinite() && ((a > F::zero()) == (b > F::zero()));
328
329            if both_nan || both_inf {
330                continue;
331            }
332
333            if !tolerance.approx_eq(F::from(a).unwrap(), F::from(b).unwrap()) {
334                // Only print the first 5 different values.
335                if num_diff < max_num_diff {
336                    let diff_abs = ToPrimitive::to_f64(&(a - b).abs()).unwrap();
337                    let max = F::max(a.abs(), b.abs());
338                    let diff_rel = diff_abs / ToPrimitive::to_f64(&max).unwrap();
339
340                    let tol_rel = ToPrimitive::to_f64(&tolerance.relative).unwrap();
341                    let tol_abs = ToPrimitive::to_f64(&tolerance.absolute).unwrap();
342
343                    message += format!(
344                        "\n  => Position {i}: {a} != {b}\n     diff (rel = {diff_rel:+.2e}, abs = {diff_abs:+.2e}), tol (rel = {tol_rel:+.2e}, abs = {tol_abs:+.2e})"
345                    )
346                    .as_str();
347                }
348                num_diff += 1;
349            }
350        }
351
352        if num_diff >= max_num_diff {
353            message += format!("\n{} more errors...", num_diff - 5).as_str();
354        }
355
356        if !message.is_empty() {
357            panic!("Tensors are not approx eq:{message}");
358        }
359    }
360
361    /// Asserts each value is within a given range.
362    ///
363    /// # Arguments
364    ///
365    /// * `range` - The range.
366    ///
367    /// # Panics
368    ///
369    /// If any value is not within the half-open range bounded inclusively below
370    /// and exclusively above (`start..end`).
371    pub fn assert_within_range<E: ElementOrdered>(&self, range: core::ops::Range<E>) {
372        for elem in self.iter::<E>() {
373            if elem.cmp(&range.start).is_lt() || elem.cmp(&range.end).is_ge() {
374                panic!("Element ({elem:?}) is not within range {range:?}");
375            }
376        }
377    }
378
379    /// Asserts each value is within a given inclusive range.
380    ///
381    /// # Arguments
382    ///
383    /// * `range` - The range.
384    ///
385    /// # Panics
386    ///
387    /// If any value is not within the half-open range bounded inclusively (`start..=end`).
388    pub fn assert_within_range_inclusive<E: ElementOrdered>(
389        &self,
390        range: core::ops::RangeInclusive<E>,
391    ) {
392        let start = range.start();
393        let end = range.end();
394
395        for elem in self.iter::<E>() {
396            if elem.cmp(start).is_lt() || elem.cmp(end).is_gt() {
397                panic!("Element ({elem:?}) is not within range {range:?}");
398            }
399        }
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::*;
406
407    #[test]
408    fn should_assert_appox_eq_limit() {
409        let data1 = TensorData::from([[3.0, 5.0, 6.0]]);
410        let data2 = TensorData::from([[3.03, 5.0, 6.0]]);
411
412        data1.assert_approx_eq::<f32>(&data2, Tolerance::absolute(3e-2));
413        data1.assert_approx_eq::<f16>(&data2, Tolerance::absolute(3e-2));
414    }
415
416    #[test]
417    #[should_panic]
418    fn should_assert_approx_eq_above_limit() {
419        let data1 = TensorData::from([[3.0, 5.0, 6.0]]);
420        let data2 = TensorData::from([[3.031, 5.0, 6.0]]);
421
422        data1.assert_approx_eq::<f32>(&data2, Tolerance::absolute(1e-2));
423    }
424
425    #[test]
426    #[should_panic]
427    fn should_assert_approx_eq_check_shape() {
428        let data1 = TensorData::from([[3.0, 5.0, 6.0, 7.0]]);
429        let data2 = TensorData::from([[3.0, 5.0, 6.0]]);
430
431        data1.assert_approx_eq::<f32>(&data2, Tolerance::absolute(1e-2));
432    }
433}