1
0

test-double-float.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // These tests may take a long time!
  2. // They are to prove that conversion from double to float of various functions in ggml.c doesn't affect the result.
  3. // This is done by checking all finite (non-NaN, non-infinite) floats.
  4. #undef NDEBUG
  5. #include <cassert>
  6. #include <immintrin.h>
  7. #include <cmath>
  8. #include <cstdint>
  9. #include <cstring>
  10. #pragma GCC diagnostic push
  11. #pragma GCC diagnostic ignored "-Wdouble-promotion"
  12. // ggml.c::quantize_row_q4_0_reference
  13. inline static uint8_t round_orig(float v0) { return ((int8_t) (round(v0))) + 8; }
  14. // ggml.c::ggml_silu_f32
  15. inline static float silu_orig(float x) {
  16. return x/(1.0 + exp(-x));
  17. }
  18. #pragma GCC diagnostic pop
  19. // ggml.c::quantize_row_q4_0_reference
  20. inline static uint8_t round_float(float v0) { return (int8_t)roundf(v0) + 8; }
  21. // ggml.c::ggml_silu_f32
  22. inline static float silu_float(float x) {
  23. return x/(1.0f + expf(-x));
  24. }
  25. int main(void) {
  26. uint32_t x = UINT32_MAX;
  27. do {
  28. float f;
  29. memcpy(&f, &x, sizeof(x));
  30. assert(!std::isfinite(f) || (round_orig(f) == round_float(f)));
  31. } while (x--);
  32. #ifdef __F16C__
  33. // GELU and SILU implementations are used with a FP16 lookup table.
  34. // The original and float-only results are not equal for all inputs after converting to FP16.
  35. // GELU is an approximation anyway (tanh), not tested here.
  36. // For SILU, verify that the results are at least the closest floating point numbers, if the FP16 values don't match.
  37. for (x = 0; x <= UINT16_MAX; x++) {
  38. float f = _cvtsh_ss(x);
  39. const float so = silu_orig(f);
  40. const float sf = silu_float(f);
  41. assert( (_cvtss_sh(so, 0) == _cvtss_sh(sf, 0))
  42. || (nextafterf(so, sf) == sf)
  43. || (nextafterf(sf, so) == so));
  44. }
  45. #endif
  46. }