diff --git a/fork.yaml b/fork.yaml index 16854c7466..969d6e683f 100644 --- a/fork.yaml +++ b/fork.yaml @@ -318,6 +318,27 @@ def: - "mlx/scheduler.cpp" - "mlx/transforms.cpp" - "tests/scheduler_tests.cpp" + - title: "half and bfloat16 floor divide in float32" + description: | + Upstream computes float16 and bfloat16 `floor_divide`, and the `divmod` quotient, as + `floor(a / b)` in the half type. The quotient is rounded to the half type before the + floor, so a true quotient that is less than half an ulp below an integer n rounds + to n, and the result is n instead of n - 1. numpy's float16 divmod computes in + float32 from `fmod` (`npy_divmodf`) and gives n - 1. Upstream's unseeded + `test_divmod` fails for this reason in about 4% of runs per device. The fork now + computes these two operations for float16 and bfloat16 in float32 with the same + method as `npy_divmodf` (`mod = fmod(a, b)`, `div = (a - mod) / b`, then a floor + with the sign correction), and rounds the result once to the output type: in the + Metal `FloorDivide` (which `DivMod` uses), in the CPU scalar and SIMD + `floor_divide`, and in the CPU `DivMod`. float32, float64 and integer paths do not + change. `test_floor_divide_half_rounding_window` uses pairs in the rounding window + and compares with numpy on the CPU and the GPU. The CUDA kernels do not change; no + workflow in this fork builds CUDA. + globs: + - "mlx/backend/metal/kernels/binary_ops.h" + - "mlx/backend/cpu/simd/base_simd.h" + - "mlx/backend/cpu/simd/accelerate_simd.h" + - "mlx/backend/cpu/binary.cpp" - title: "Fork tooling" description: | The fork deletes the upstream workflows that cannot run here: the PyPI release build, diff --git a/mlx/backend/cpu/binary.cpp b/mlx/backend/cpu/binary.cpp index 150cf58339..b167304b5c 100644 --- a/mlx/backend/cpu/binary.cpp +++ b/mlx/backend/cpu/binary.cpp @@ -58,11 +58,23 @@ void DivMod::eval_cpu( return std::make_pair(q, r); }; auto float_op = [](auto x, auto y) { - auto r = std::fmod(x, y); - if (r != 0 && (r < 0) != (y < 0)) { - r += y; + using T = decltype(x); + if constexpr (simd::is_half_v) { + // Compute in float32 and round once. See exact_floor_divide. + float xf = static_cast(x); + float yf = static_cast(y); + float r = std::fmod(xf, yf); + if (r != 0 && (r < 0) != (yf < 0)) { + r += yf; + } + return std::make_pair(T(simd::exact_floor_divide(xf, yf)), T(r)); + } else { + auto r = std::fmod(x, y); + if (r != 0 && (r < 0) != (y < 0)) { + r += y; + } + return std::make_pair(std::floor(x / y), r); } - return std::make_pair(std::floor(x / y), r); }; dispatch_all_types(out_a.dtype(), [&](auto type_tag) { diff --git a/mlx/backend/cpu/simd/accelerate_simd.h b/mlx/backend/cpu/simd/accelerate_simd.h index b3cea20b22..5a3af8f135 100644 --- a/mlx/backend/cpu/simd/accelerate_simd.h +++ b/mlx/backend/cpu/simd/accelerate_simd.h @@ -267,6 +267,14 @@ Simd floor_divide(Simd a, Simd b) { return q; } else if constexpr (is_complex) { return a / b; + } else if constexpr (is_half_v) { + // See exact_floor_divide in base_simd.h. + Simd q; + for (int i = 0; i < N; ++i) { + q[i] = T(exact_floor_divide( + static_cast(a[i]), static_cast(b[i]))); + } + return q; } else { return floor(divide(a, b)); } diff --git a/mlx/backend/cpu/simd/base_simd.h b/mlx/backend/cpu/simd/base_simd.h index 483eff69e8..9cadc8538d 100644 --- a/mlx/backend/cpu/simd/base_simd.h +++ b/mlx/backend/cpu/simd/base_simd.h @@ -219,6 +219,33 @@ Simd divide(Simd a_, Simd b_) { return a / b; } +// The floor of a / b, computed as numpy's npy_divmodf does: from fmod, so the +// quotient is not rounded before the floor. float16 and bfloat16 use it in +// float32: floor(a / b) in the half type rounds a quotient that is just below +// an integer up to that integer. +inline float exact_floor_divide(float a, float b) { + if (b == 0) { + return a / b; + } + float mod = std::fmod(a, b); + float div = (a - mod) / b; + if (mod != 0 && ((b < 0) != (mod < 0))) { + div -= 1.0f; + } + if (div == 0) { + return std::copysign(0.0f, a / b); + } + float floordiv = std::floor(div); + if (div - floordiv > 0.5f) { + floordiv += 1.0f; + } + return floordiv; +} + +template +constexpr bool is_half_v = + std::is_same_v || std::is_same_v; + template Simd floor_divide(Simd a_, Simd b_) { T a = a_.value; @@ -243,6 +270,8 @@ Simd floor_divide(Simd a_, Simd b_) { return q; } else if constexpr (is_complex) { return a / b; + } else if constexpr (is_half_v) { + return T(exact_floor_divide(static_cast(a), static_cast(b))); } else { return floor(divide(a_, b_)); } diff --git a/mlx/backend/metal/kernels/binary_ops.h b/mlx/backend/metal/kernels/binary_ops.h index 968087f8ef..ee6222f157 100644 --- a/mlx/backend/metal/kernels/binary_ops.h +++ b/mlx/backend/metal/kernels/binary_ops.h @@ -14,6 +14,29 @@ struct Add { } }; +// The floor of x / y, computed as numpy's npy_divmodf does: from fmod, so the +// quotient is not rounded before the floor. float16 and bfloat16 use it in +// float32: floor(x / y) in the half type rounds a quotient that is just below +// an integer up to that integer. +inline float exact_floor_divide(float x, float y) { + if (y == 0) { + return x / y; + } + float mod = metal::fmod(x, y); + float div = (x - mod) / y; + if (mod != 0 && ((y < 0) != (mod < 0))) { + div -= 1.0f; + } + if (div == 0) { + return metal::copysign(0.0f, x / y); + } + float floordiv = metal::floor(div); + if (div - floordiv > 0.5f) { + floordiv += 1.0f; + } + return floordiv; +} + struct FloorDivide { template metal::enable_if_t & !metal::is_signed_v, T> @@ -31,7 +54,12 @@ struct FloorDivide { } template metal::enable_if_t, T> operator()(T x, T y) thread { - return floor(x / y); + if constexpr ( + metal::is_same_v || metal::is_same_v) { + return static_cast(exact_floor_divide(float(x), float(y))); + } else { + return floor(x / y); + } } template <> complex64_t operator()(complex64_t x, complex64_t y) thread { diff --git a/python/tests/test_ops.py b/python/tests/test_ops.py index 42a7f10ad3..99c9085b3e 100644 --- a/python/tests/test_ops.py +++ b/python/tests/test_ops.py @@ -3960,6 +3960,72 @@ def test_outer(self): np.outer, ) + def test_floor_divide_half_rounding_window(self): + # Pairs whose true quotient is just below an integer n. Rounded to + # float16 or bfloat16, that quotient becomes n, so floor(a / b) in the + # half type gives n. The floor of the exact quotient is n - 1, which + # is what numpy's float16 divmod gives. + def window_pairs(bits): + # bits: stored mantissa bits (10 for float16, 7 for bfloat16). + pairs = [] + for k in range(1, 2**bits): + b = 1.0 + k * 2.0**-bits + for n in range(2, 24): + exact = n * b + if bits == 10: + a = float(np.float16(exact)) + if a > exact: + a = float(np.nextafter(np.float16(a), np.float16(0))) + else: + # Keep the top 16 bits of the float32 value: the + # largest bfloat16 value at or below it. + f = np.array([exact], dtype=np.float32).view(np.uint32) + a = float((f & np.uint32(0xFFFF0000)).view(np.float32)[0]) + if a == exact: + continue + q = a / b + ulp = 2.0 ** (math.floor(math.log2(q)) - bits) + if 0 < n - q < ulp / 4: + pairs.append((a, b)) + if len(pairs) == 24: + return pairs + return pairs + + devices = [mx.cpu] + if mx.metal.is_available(): + devices.append(mx.gpu) + for dtype, bits in ((mx.float16, 10), (mx.bfloat16, 7)): + pairs = window_pairs(bits) + self.assertGreater(len(pairs), 8) + av = [a for a, _ in pairs] + bv = [b for _, b in pairs] + expected_q = np.floor_divide(np.array(av), np.array(bv)) + if dtype == mx.float16: + np_q, np_r = np.divmod( + np.array(av, np.float16), np.array(bv, np.float16) + ) + self.assertEqual(np_q.astype(np.float64).tolist(), expected_q.tolist()) + for device in devices: + with self.subTest(dtype=dtype, device=device): + a = mx.array(av, dtype) + b = mx.array(bv, dtype) + self.assertEqual(a.astype(mx.float32).tolist(), av) + self.assertEqual(b.astype(mx.float32).tolist(), bv) + for q in ( + mx.floor_divide(a, b, stream=device), + mx.divmod(a, b, stream=device)[0], + ): + self.assertEqual( + q.astype(mx.float32).tolist(), expected_q.tolist() + ) + q, r = mx.divmod(a, b, stream=device) + r = np.array(r.astype(mx.float32)) + if dtype == mx.float16: + self.assertEqual(r.tolist(), np_r.astype(np.float32).tolist()) + self.assertTrue(np.all((r >= 0) & (r < np.array(bv)))) + q = np.array(q.astype(mx.float32), np.float64) + self.assertTrue(np.allclose(q * np.array(bv) + r, av)) + def test_divmod(self): # A few sizes for the inputs with and without broadcasting sizes = [