test-double-float.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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 <assert.h>
  6. #include <immintrin.h>
  7. #include <math.h>
  8. #include <stdint.h>
  9. #pragma GCC diagnostic push
  10. #pragma GCC diagnostic ignored "-Wdouble-promotion"
  11. // ggml.c::quantize_row_q4_0_reference
  12. inline static uint8_t round_orig(float v0) { return ((int8_t) (round(v0))) + 8; }
  13. // ggml.c::ggml_silu_f32
  14. inline static float silu_orig(float x) {
  15. return x/(1.0 + exp(-x));
  16. }
  17. #pragma GCC diagnostic pop
  18. // ggml.c::quantize_row_q4_0_reference
  19. inline static uint8_t round_float(float v0) { return (int8_t)roundf(v0) + 8; }
  20. // ggml.c::ggml_silu_f32
  21. inline static float silu_float(float x) {
  22. return x/(1.0f + expf(-x));
  23. }
  24. int main(void) {
  25. uint32_t x = UINT32_MAX;
  26. do {
  27. float f = *(float *)&x;
  28. assert(!isfinite(f) || (round_orig(f) == round_float(f)));
  29. } while (x--);
  30. #ifdef __F16C__
  31. // GELU and SILU implementations are used with a FP16 lookup table.
  32. // The original and float-only results are not equal for all inputs after converting to FP16.
  33. // GELU is an approximation anyway (tanh), not tested here.
  34. // For SILU, verify that the results are at least the closest floating point numbers, if the FP16 values don't match.
  35. for (x = 0; x <= UINT16_MAX; x++) {
  36. float f = _cvtsh_ss(x);
  37. const float so = silu_orig(f);
  38. const float sf = silu_float(f);
  39. assert( (_cvtss_sh(so, 0) == _cvtss_sh(sf, 0))
  40. || (nextafterf(so, sf) == sf)
  41. || (nextafterf(sf, so) == so));
  42. }
  43. #endif
  44. }