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#[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 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 pub fn balanced() -> Self {
50 Self {
51 relative: F::from(0.005).unwrap(), absolute: F::from(1e-5).unwrap(),
53 }
54 }
55
56 pub fn permissive() -> Self {
58 Self {
59 relative: F::from(0.01).unwrap(), absolute: F::from(0.01).unwrap(),
61 }
62 }
63 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 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 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 pub fn set_relative<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
117 self.relative = Self::check_relative(tolerance);
118 self
119 }
120
121 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 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 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 pub fn set_absolute<FF: ToPrimitive>(mut self, tolerance: FF) -> Self {
147 self.absolute = Self::check_absolute(tolerance);
148 self
149 }
150
151 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 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 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 pub fn approx_eq(&self, x: F, y: F) -> bool {
177 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 #[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 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 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 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 #[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 let both_nan = a.is_nan() && b.is_nan();
325 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 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 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 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}