From a521a4a24b4b3484979d6006e161385798e02be3 Mon Sep 17 00:00:00 2001 From: Theodore Omtzigt Date: Sun, 6 Dec 2026 09:05:03 -0500 Subject: [PATCH 1/3] test: sum_k/dot_k limits and non-finite input, extended types at their edges, dtype-list sync, #226's smoother and perf tests (#235) The regression gaps of the QA sweep in #228, outside pandas and the Universal interop. sum_k / dot_k: - The paper's bounds now run k = 2..10 and cond up to 1e100, where a k dispatched to K - 1 fails; k = 8..10 round correctly at cond 1e100. - inf, opposite infinities, NaN, an intermediate overflow and subnormals, pinned as measured: inf stays inf for every k (the sweep's NaN does not reproduce), and a subnormal survives 1 - 1 for k >= 2 in float32 and float64. - complex, 2-D, longdouble, strings and every non-IEEE or integer container are refused; float16 is summed in float32, bool in float64. A read-only array, a zero-length DenseVector, and a 0-d scalar, which is accepted as a vector of one, as np.sum and np.dot accept it. Extended types: - cfloat32 at binary32's edges (overflow, subnormals, ties, -0.0, inf, NaN), bit for bit against np.float32. - takum16/32: round to nearest, ties to even, on the [1, 2) grid; overflow and underflow saturate at maxpos / minpos; NaN and inf are NaR. - A conversion is held to half an ulp (takum16 was at 1e-2, the cascades at 1e-14; they are exact). - Cascade GEMM and GEMV against correctly rounded references at cond 1e20, where float64 has no correct digit. Dtype lists: tests/test_dtype_lists.py checks the bound classes against type_suffix() and dtypes() against the bound types without the integer and complex ones. Only the Universal types have vector_ factories; the native ones are built by mtl5.vector from the dtype. CLAUDE.md said every type had one, and now says which. #226's tests: - mg._smoother_builds(), a construction counter: a vcycle or wcycle call builds one smoother per level for 1 cycle as for 10, and smooth() one for any sweeps. A timing guard could not tell this from a rebuild per sweep, which costs about 1.7x. - k cycles equal k single cycles bit for bit, for every smoother. - A perf guard that an unsorted sparse_vector build stays near-linear. - default_rtol refuses integer and complex dtypes. - test_every_solver_converges_in_float32 derives its forward-error bound from cond(A) and the float64 residual instead of rtol=0.5. Resolves #235 Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- python/src/mtl5_multigrid.cpp | 12 ++ tests/test_accurate_sum_dot.py | 165 +++++++++++++++++++++++++++- tests/test_dtype_lists.py | 104 ++++++++++++++++++ tests/test_extended_number_types.py | 150 ++++++++++++++++++++++++- tests/test_krylov_dispatch.py | 23 +++- tests/test_multigrid.py | 44 ++++++++ tests/test_sparse_vector.py | 31 ++++++ 8 files changed, 521 insertions(+), 10 deletions(-) create mode 100644 tests/test_dtype_lists.py diff --git a/CLAUDE.md b/CLAUDE.md index 2fdc56f..54574bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,7 +64,7 @@ sphinx-build -E -W --keep-going -b html docs docs/_build/html ### Element types -Every element type has its own `DenseVector_` / `DenseMatrix_` class and `vector_` / `matrix_` factory. The source of truth is `type_suffix()` in `python/src/mtl5_types.hpp`. +Every element type has its own `DenseVector_` / `DenseMatrix_` class. The Universal types also have a `vector_` / `matrix_` factory; the NumPy-native ones (float, complex, integer) have none, as `mtl5.vector` / `mtl5.matrix` pick their class from the ndarray's dtype. The source of truth is `type_suffix()` in `python/src/mtl5_types.hpp`; `tests/test_dtype_lists.py` keeps the lists in step. | Suffix | C++ type | Notes | |---|---|---| diff --git a/python/src/mtl5_multigrid.cpp b/python/src/mtl5_multigrid.cpp index 3e74039..746cab7 100644 --- a/python/src/mtl5_multigrid.cpp +++ b/python/src/mtl5_multigrid.cpp @@ -44,6 +44,7 @@ #include #include +#include #include #include #include @@ -81,10 +82,17 @@ void check_omega(const std::string& kind, double omega) { /// One relaxation sweep, in place on x. using SmoothFn = std::function; +/// Smoothers built since the module loaded, read by mg._smoother_builds(): +/// the tests pin that a cycle call builds one per level whatever its cycles +/// and sweeps (#223, #235). A timing test could not tell that from one per +/// sweep, which costs only about 1.7x as much. +std::atomic g_smoother_builds{0}; + /// Build the named smoother for A once. The result is copyable, as /// mg::multigrid needs (it copies what the factory returns), and its copies /// share one smoother. It keeps a reference to A, which must outlive it. SmoothFn make_smoother(const std::string& kind, const SMat& A, double omega) { + g_smoother_builds.fetch_add(1, std::memory_order_relaxed); auto wrap = [](auto ptr) -> SmoothFn { return [ptr](Vec& x, const Vec& b) { (*ptr)(x, b); }; }; @@ -258,6 +266,10 @@ void register_multigrid(nb::module_& m) { "symmetric_gauss_seidel", "sor", "backward_sor", "symmetric_sor"}; }, "The smoothers accepted by smooth() and multigrid_1d()"); + g.def("_smoother_builds", []() { + return g_smoother_builds.load(std::memory_order_relaxed); + }, "Smoothers constructed since import; a test hook, not a public API."); + g.def("make_restriction_1d", &mg::make_restriction_1d, "n_fine"_a, "Full-weighting restriction from n_fine to (n_fine - 1) / 2 points"); g.def("make_prolongation_1d", &mg::make_prolongation_1d, "n_coarse"_a, diff --git a/tests/test_accurate_sum_dot.py b/tests/test_accurate_sum_dot.py index d5a5905..77878ac 100644 --- a/tests/test_accurate_sum_dot.py +++ b/tests/test_accurate_sum_dot.py @@ -71,8 +71,12 @@ def test_k1_is_the_plain_recursive_sum(self): p = np.random.default_rng(1).standard_normal(1000) * 1e3 assert mtl5.sum_k(p, k=1) == reduce(lambda a, b: a + b, p.tolist(), 0.0) - @pytest.mark.parametrize("cond", [1e4, 1e12, 1e20, 1e40]) - @pytest.mark.parametrize("k", [2, 3, 4, 5]) + # k runs to the maximum of 10: an off-by-one in the C++ dispatch over + # K = 1..10 would show only at the top of the range (#235). At cond 1e100 + # the bound for k = 7 is about 1e16 times looser than for k = 8, so a k + # dispatched to K - 1 fails it. + @pytest.mark.parametrize("cond", [1e4, 1e12, 1e20, 1e40, 1e100]) + @pytest.mark.parametrize("k", range(2, 11)) def test_meets_the_papers_bound(self, cond, k): g = mtl5.generators.gen_sum(200, cond, seed=7) p = np.asarray(g.p) @@ -120,13 +124,20 @@ def test_k_out_of_range(self, k): with pytest.raises(ValueError, match="k must be between 1 and 10"): mtl5.sum_k(np.ones(3), k=k) + @pytest.mark.parametrize("k", [8, 9, 10]) + def test_correctly_rounded_at_the_top_of_the_range(self, k): + # Each pass gains a factor of about 1e16, so from k = 8 a sum at cond + # 1e100 rounds correctly. A k = 10 that reached no K would return 0. + g = mtl5.generators.gen_sum(200, 1e100, seed=7) + assert mtl5.sum_k(g.p, k=k) == g.sum != 0.0 + # --------------------------------------------------------------------------- # dot_k # --------------------------------------------------------------------------- class TestDotK: - @pytest.mark.parametrize("cond", [1e4, 1e12, 1e24, 1e40]) - @pytest.mark.parametrize("k", [2, 3, 4, 6]) + @pytest.mark.parametrize("cond", [1e4, 1e12, 1e24, 1e40, 1e100]) + @pytest.mark.parametrize("k", range(2, 11)) def test_meets_the_papers_bound(self, cond, k): g = mtl5.generators.gen_dot(100, cond, seed=11) x, y = np.asarray(g.x), np.asarray(g.y) @@ -175,6 +186,11 @@ def test_k_out_of_range(self, k): with pytest.raises(ValueError, match="k must be between 2 and 10"): mtl5.dot_k(np.ones(3), np.ones(3), k=k) + @pytest.mark.parametrize("k", [8, 9, 10]) + def test_correctly_rounded_at_the_top_of_the_range(self, k): + g = mtl5.generators.gen_dot(100, 1e100, seed=11) + assert mtl5.dot_k(g.x, g.y, k=k) == g.dot != 0.0 + def test_float32_with_float64_widens_exactly(self): # nanobind converts the float32 operand to float64, which is exact, so # the result is the float64 DotK of the same values. @@ -357,3 +373,144 @@ def test_core_functions_refuse_rather_than_cast(self): # wrapper; the C++ function itself is kept as _core_mixed_dot. with pytest.raises(TypeError): mtl5._core_mixed_dot(np.ones(4)[::2], np.ones(4)[::2]) + + +# --------------------------------------------------------------------------- +# Non-finite, overflowing and subnormal input (#235) +# --------------------------------------------------------------------------- +SUM_KS = list(range(1, 11)) +DOT_KS = list(range(2, 11)) + + +class TestNonFiniteAndSubnormal: + """Pinned on main as measured. A textbook TwoSum of an infinity gives an + error term of inf - inf = NaN, so the sweep (#228) expected sum_k to turn an + infinite sum into NaN. It does not: every k returns the infinity, as a plain + sum does, and only a NaN input or opposite infinities give NaN.""" + + @pytest.mark.parametrize("k", SUM_KS) + def test_an_infinity_stays_infinite(self, k): + assert mtl5.sum_k([np.inf, 1.0], k) == np.inf + assert mtl5.sum_k([-np.inf, 1.0], k) == -np.inf + + @pytest.mark.parametrize("k", SUM_KS) + def test_opposite_infinities_are_nan(self, k): + assert math.isnan(mtl5.sum_k([np.inf, -np.inf], k)) + + @pytest.mark.parametrize("k", SUM_KS) + def test_an_intermediate_overflow_is_infinite(self, k): + # The exact sum, 1e308, is finite: the recursive sum overflows at its + # first addition, and no compensation brings it back. + assert mtl5.sum_k([1e308, 1e308, -1e308], k) == np.inf + + @pytest.mark.parametrize("k", SUM_KS) + def test_a_nan_propagates(self, k): + assert math.isnan(mtl5.sum_k(np.array([np.nan, 1.0]), k)) + assert math.isnan(mtl5.sum_k(np.array([1.0, np.nan], dtype=np.float32), k)) + + @pytest.mark.parametrize("k", DOT_KS) + def test_an_overflowing_product_is_infinite_as_in_numpy(self, k): + assert mtl5.dot_k([1e200], [1e200], k) == np.dot([1e200], [1e200]) == np.inf + + @pytest.mark.parametrize("k", DOT_KS) + def test_dot_with_an_infinity_or_a_nan(self, k): + assert mtl5.dot_k([np.inf, 1.0], [1.0, 1.0], k) == np.inf + assert math.isnan(mtl5.dot_k([np.nan, 1.0], [1.0, 1.0], k)) + + @pytest.mark.parametrize("k", SUM_KS) + def test_subnormals_add_exactly(self, k): + tiny = 5e-324 # the smallest float64 subnormal + assert mtl5.sum_k(np.array([tiny, tiny]), k) == 2 * tiny + + @pytest.mark.parametrize("k", range(2, 11)) + @pytest.mark.parametrize("dt", [np.float64, np.float32]) + def test_a_subnormal_survives_cancellation(self, k, dt): + # 1 + tiny rounds to 1, so the plain sum loses tiny; the compensated + # sums keep it, in float32 as in float64. + tiny = np.finfo(dt).smallest_subnormal + p = np.array([tiny, 1.0, -1.0], dtype=dt) + assert mtl5.sum_k(p, k=1) == 0.0 + assert mtl5.sum_k(p, k) == float(tiny) + + +# --------------------------------------------------------------------------- +# What the wrappers accept (#235) +# --------------------------------------------------------------------------- +class TestInputTypes: + """mtl5.sum_k / dot_k make the layout contiguous and widen integers, bools + and float16 (mtl5/__init__.py `_ieee`). Anything else that is not float32 + or float64 is refused by the C++ overloads, never cast.""" + + @pytest.mark.parametrize( + "x", + [ + np.ones(3, dtype=np.complex128), + np.ones(3, dtype=np.complex64), + np.ones((2, 2)), + np.ones(3, dtype=np.longdouble), + ["a", "b"], + ], + ids=["complex128", "complex64", "2-D", "longdouble", "strings"], + ) + def test_refused(self, x): + if isinstance(x, np.ndarray) and x.dtype == np.longdouble: + if np.dtype(np.longdouble).itemsize == 8: + pytest.skip("longdouble is float64 on this platform") + with pytest.raises(TypeError): + mtl5.sum_k(x) + with pytest.raises(TypeError): + mtl5.dot_k(x, x) + + @pytest.mark.parametrize("name", ["posit16", "fp16", "cfloat32", "takum32", "dd_cascade"]) + def test_a_non_ieee_container_is_refused(self, name): + # The error-free transformations are defined for binary IEEE types + # only; cfloat32 emulates binary32 but is not the hardware type. + v = mtl5.convert(np.ones(3), name) + with pytest.raises(TypeError): + mtl5.sum_k(v) + with pytest.raises(TypeError): + mtl5.dot_k(v, v) + + @pytest.mark.parametrize("dt", [np.int8, np.int64, np.complex128]) + def test_a_native_non_float_container_is_refused(self, dt): + # Containers pass through unconverted, so an integer DenseVector is + # refused where an integer ndarray would be widened to float64. + v = mtl5.vector(np.ones(3, dtype=dt)) + with pytest.raises(TypeError): + mtl5.sum_k(v) + with pytest.raises(TypeError): + mtl5.dot_k(v, v) + if dt is not np.complex128: + assert mtl5.sum_k(np.ones(3, dtype=dt)) == 3.0 + + def test_float16_is_summed_in_float32(self): + x = np.array([2048, 1, -2048, 0.5], dtype=np.float16) + assert mtl5.sum_k(x) == mtl5.sum_k(x.astype(np.float32)) == 1.5 + assert mtl5.dot_k(x, x) == mtl5.dot_k(x.astype(np.float32), x.astype(np.float32)) + + def test_bool_is_float64(self): + b = np.array([True, False, True]) + assert mtl5.sum_k(b) == 2.0 + assert mtl5.dot_k(b, b) == 2.0 + + def test_a_read_only_array(self): + x = np.array([1e16, 1.0, -1e16]) + x.flags.writeable = False + assert mtl5.sum_k(x) == 1.0 + assert mtl5.dot_k(x, np.ones(3)) == 1.0 + assert mtl5.dot_k(x, x) == 2e32 + 1.0 + + def test_a_zero_length_densevector(self): + v = mtl5.vector(np.array([])) + assert len(v) == 0 + assert mtl5.sum_k(v, k=10) == 0.0 + assert mtl5.dot_k(v, v, k=10) == 0.0 + + def test_a_scalar_is_a_vector_of_one(self): + """Accepted, as np.sum and np.dot accept one: np.ascontiguousarray + makes a 0-d input 1-d (#235 asked to accept or refuse it, and pin + which).""" + assert mtl5.sum_k(5.0) == np.sum(5.0) == 5.0 + assert mtl5.sum_k(np.float32(2.5)) == 2.5 + assert mtl5.sum_k(np.array(7.0)) == 7.0 + assert mtl5.dot_k(2.0, 3.0) == np.dot(2.0, 3.0) == 6.0 diff --git a/tests/test_dtype_lists.py b/tests/test_dtype_lists.py new file mode 100644 index 0000000..c3d277d --- /dev/null +++ b/tests/test_dtype_lists.py @@ -0,0 +1,104 @@ +"""The element-type lists stay in step (#235). + +Three lists name the bound element types: `type_suffix()` in +python/src/mtl5_types.hpp (the source of truth), the classes the module +exports, and `mtl5.dtypes()`, which is what `convert()` can target. A type +added to one list and not the others would otherwise go unnoticed until a +caller asked for it. + +How a container is built differs by kind. A NumPy-native type (float, complex, +integer) has no factory of its own: `mtl5.vector` and `mtl5.matrix` pick the +class from the ndarray's dtype, zero-copy. The Universal types have none in +NumPy, so each has a `vector_` / `matrix_` factory that +converts from float64. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import numpy as np +import pytest + +import mtl5 + +TYPES_HPP = Path(__file__).resolve().parent.parent / "python" / "src" / "mtl5_types.hpp" + +# Not convert() targets: converting reals to an integer type is a quantization +# scheme, not a cast, and convert() has no complex overload. +INTEGER = {"i8", "i16", "i32", "i64", "u8", "u32"} +COMPLEX = {"c64", "c128"} +# The suffix of each NumPy-native type, as mtl5.vector picks it from the dtype. +NATIVE = { + "f32": np.float32, + "f64": np.float64, + "c64": np.complex64, + "c128": np.complex128, + "i8": np.int8, + "i16": np.int16, + "i32": np.int32, + "i64": np.int64, + "u8": np.uint8, + "u32": np.uint32, +} + + +def bound(prefix): + return {m.group(1) for n in dir(mtl5) if (m := re.fullmatch(prefix + r"_(\w+)", n))} + + +BOUND = bound("DenseVector") + + +def test_every_vector_class_has_its_matrix_class(): + assert BOUND, "no DenseVector_ classes found" + assert bound("DenseMatrix") == BOUND + + +def test_factories_are_exactly_the_universal_types(): + universal = BOUND - set(NATIVE) + # vector_copy / matrix_copy are not factories of a type. + assert bound("vector") - {"copy"} == universal + assert bound("matrix") - {"copy"} == universal + + +@pytest.mark.parametrize("name", sorted(NATIVE)) +def test_vector_and_matrix_pick_the_native_class_from_the_dtype(name): + dt = NATIVE[name] + assert type(mtl5.vector(np.ones(3, dtype=dt))) is getattr(mtl5, f"DenseVector_{name}") + assert type(mtl5.matrix(np.ones((2, 2), dtype=dt))) is getattr(mtl5, f"DenseMatrix_{name}") + + +@pytest.mark.skipif(not TYPES_HPP.exists(), reason="the C++ sources are not present") +def test_the_bound_suffixes_are_type_suffix(): + src = TYPES_HPP.read_text() + suffixes = set( + re.findall(r'constexpr const char\* type_suffix<[^>]+>\(\)\s*\{\s*return "(\w+)"', src) + ) + assert len(suffixes) >= 26, f"the pattern found only {sorted(suffixes)}" + assert suffixes == BOUND + + +def test_dtypes_is_every_bound_type_but_the_integers_and_complex(): + dt = mtl5.dtypes() + assert len(dt) == len(set(dt)) + assert set(dt) == BOUND - INTEGER - COMPLEX + + +@pytest.mark.parametrize("name", mtl5.dtypes()) +def test_each_dtype_has_its_classes_and_converts_to_them(name): + v = mtl5.convert(np.array([1.0, 2.0]), name) + assert isinstance(v, getattr(mtl5, f"DenseVector_{name}")) + assert v.dtype == name + M = mtl5.convert(np.ones((2, 2)), name) + assert isinstance(M, getattr(mtl5, f"DenseMatrix_{name}")) + if name not in NATIVE: + assert type(getattr(mtl5, f"vector_{name}")(np.array([1.0]))) is type(v) + assert type(getattr(mtl5, f"matrix_{name}")(np.ones((1, 1)))) is type(M) + + +@pytest.mark.parametrize("name", sorted(INTEGER | COMPLEX)) +def test_convert_refuses_the_integer_and_complex_types(name): + with pytest.raises(ValueError, match="unknown dtype"): + mtl5.convert(np.ones(3), name) diff --git a/tests/test_extended_number_types.py b/tests/test_extended_number_types.py index 983d468..ccc846c 100644 --- a/tests/test_extended_number_types.py +++ b/tests/test_extended_number_types.py @@ -40,6 +40,20 @@ ] EXTENDED_NAMES = [name for name, _ in EXTENDED] +# A single conversion rounds once, so it is held to half an ulp, not to the +# BLAS tolerances above: takum16's 1e-2 would pass a conversion that truncated, +# or one that rounded to 8 bits instead of 11 (#235). takum16 keeps 9 fraction +# bits at the smallest |x| of the round-trip grid (about 0.065) and 11 near 1; +# takum32 keeps 25 and 27; the cascades carry float64 through exactly. +ROUNDTRIP_RTOL = { + "cfloat32": 2.0**-24, + "takum16": 2.0**-10, + "takum32": 2.0**-26, + "dd_cascade": 0.0, + "td_cascade": 0.0, + "qd_cascade": 0.0, +} + @pytest.mark.parametrize("name, tol", EXTENDED) class TestExtendedTypeBasics: @@ -63,13 +77,13 @@ def test_matrix_factory_and_class(self, name, tol): M = factory(A) assert isinstance(M, mat_cls) assert M.shape == (3, 4) - npt.assert_allclose(M.to_numpy(), A, rtol=tol) + npt.assert_allclose(M.to_numpy(), A, rtol=ROUNDTRIP_RTOL[name], atol=0) def test_convert_roundtrip(self, name, tol): x = np.linspace(-2.0, 2.0, 32) v = mtl5.convert(x, name) assert v.dtype == name - npt.assert_allclose(v.to_numpy(), x, rtol=tol, atol=tol) + npt.assert_allclose(v.to_numpy(), x, rtol=ROUNDTRIP_RTOL[name], atol=0) def test_small_integers_are_exact(self, name, tol): # Every one of these formats has enough significand to hold small @@ -201,6 +215,105 @@ def test_loses_precision_float64_keeps(self): x = np.array([1.0 + 2.0**-40]) assert mtl5.convert(x, "cfloat32").to_numpy()[0] == 1.0 + # The edges of binary32, compared bit for bit with np.float32 (#235). + F32_MAX = float(np.finfo(np.float32).max) + TINY = 2.0**-149 # the smallest binary32 subnormal + EDGES = { + "max": F32_MAX, + "just under the overflow threshold": F32_MAX * (1 + 2.0**-25), + "at the overflow threshold": F32_MAX * (1 + 2.0**-24), + "past 3.4e38": 3.5e38, + "far past": 1e39, + "far past, negative": -1e39, + "inf": np.inf, + "-inf": -np.inf, + "-0.0": -0.0, + "subnormal": 1e-40, + "smallest subnormal": TINY, + "half the smallest, a tie to 0": TINY / 2, + "just over half the smallest": TINY * 0.5000001, + "below half the smallest": TINY / 4, + "1.5 tiny, a tie up to even": TINY * 1.5, + "2.5 tiny, a tie down to even": TINY * 2.5, + "-2.5 tiny": -TINY * 2.5, + "1 + 2^-24, a tie to 1": 1.0 + 2.0**-24, + "1 + 3 * 2^-24, a tie up to even": 1.0 + 3 * 2.0**-24, + "1 + 2^-24 + 2^-50, past the tie": 1.0 + 2.0**-24 + 2.0**-50, + } + + @pytest.mark.parametrize("label", list(EDGES)) + def test_edges_match_numpy_float32_bit_for_bit(self, label): + x = np.array([self.EDGES[label]]) + got = mtl5.convert(x, "cfloat32").to_numpy() + with np.errstate(over="ignore"): + want = x.astype(np.float32).astype(np.float64) + assert got.view(np.uint64)[0] == want.view(np.uint64)[0], (got[0], want[0]) + + def test_nan_stays_nan(self): + got = mtl5.convert(np.array([np.nan, 1.0]), "cfloat32").to_numpy() + assert np.isnan(got[0]) and got[1] == 1.0 + m = mtl5.convert(np.array([[np.nan, -0.0]]), "cfloat32").to_numpy() + assert np.isnan(m[0, 0]) and np.signbit(m[0, 1]) + + +class TestTakumEdges: + """The linear takum at its edges (#235): round to nearest, ties to even; + saturation at maxpos and minpos, about 2^255 and 2^-255, never infinity or + zero; and NaR, its one non-real, for NaN and both infinities.""" + + # Fraction bits in [1, 2): n - 5 (sign, direction, 3 regime bits, and a + # characteristic of 0 that takes no bits). + FRACTION_BITS = {"takum16": 11, "takum32": 27} + + @pytest.mark.parametrize("name", ["takum16", "takum32"]) + def test_rounds_to_nearest_ties_to_even_on_the_grid(self, name): + p = self.FRACTION_BITS[name] + ulp = 2.0**-p + rng = np.random.default_rng(6) + j = rng.integers(0, 2**p - 1, size=200).astype(np.float64) + c = lambda x: mtl5.convert(np.asarray(x), name).to_numpy() # noqa: E731 + # Below and above the midpoint go to the nearer neighbour. + npt.assert_array_equal(c(1 + (j + 0.25) * ulp), 1 + j * ulp) + npt.assert_array_equal(c(1 + (j + 0.75) * ulp), 1 + (j + 1) * ulp) + # At it, to the even one: a truncating or ties-away conversion fails. + even = j + (j % 2) + npt.assert_array_equal(c(1 + (j + 0.5) * ulp), 1 + even * ulp) + + @pytest.mark.parametrize("name", ["takum16", "takum32"]) + def test_the_grid_is_exact(self, name): + # Every point of the grid is representable, and one bit finer is not. + p = self.FRACTION_BITS[name] + c = lambda x: mtl5.convert(np.asarray(x), name).to_numpy() # noqa: E731 + assert c([1 + 2.0**-p])[0] == 1 + 2.0**-p + assert c([1 + 2.0 ** -(p + 1)])[0] == 1.0 # a tie, to the even 1 + + @pytest.mark.parametrize("name", ["takum16", "takum32"]) + def test_overflow_saturates_at_maxpos(self, name): + big = np.array([1e300, np.finfo(np.float64).max, 2.0**256, -1e300]) + got = mtl5.convert(big, name).to_numpy() + maxpos = got[0] + assert np.isfinite(got).all() + assert 2.0**254 < maxpos <= 2.0**255 + npt.assert_array_equal(got, [maxpos, maxpos, maxpos, -maxpos]) + # maxpos is reached, not passed: the largest finite value converts to + # itself. + assert mtl5.convert(np.array([maxpos]), name).to_numpy()[0] == maxpos + + @pytest.mark.parametrize("name", ["takum16", "takum32"]) + def test_underflow_saturates_at_minpos_not_zero(self, name): + tiny = np.array([1e-300, 5e-324, -1e-300]) + got = mtl5.convert(tiny, name).to_numpy() + minpos = got[0] + assert 2.0**-256 <= minpos < 2.0**-254 + npt.assert_array_equal(got, [minpos, minpos, -minpos]) + assert mtl5.convert(np.array([0.0]), name).to_numpy()[0] == 0.0 + + @pytest.mark.parametrize("name", ["takum16", "takum32"]) + def test_nan_and_infinities_are_nar(self, name): + got = mtl5.convert(np.array([np.nan, np.inf, -np.inf, 1.0]), name).to_numpy() + assert np.isnan(got[:3]).all() + assert got[3] == 1.0 + class TestCascadesExceedFloat64Internally: """The cascades' reason for existing: intermediate accumulation that @@ -240,6 +353,39 @@ def test_cascade_dot_beats_float64_on_a_cancelling_sum(self): # test would pass while demonstrating nothing about the cascade. assert err_naive > 0.0 + @staticmethod + def _ill_conditioned(cond, m=3): + """m rows x_i and m columns y_i whose dots are ill-conditioned (GenDot), + with each dot's correctly rounded value.""" + gs = [mtl5.generators.gen_dot(64, cond, seed=s) for s in range(m)] + X = np.vstack([np.asarray(g.x) for g in gs]) + Y = np.column_stack([np.asarray(g.y) for g in gs]) + return X, Y, np.array([g.dot for g in gs]) + + # At cond 1e20 a float64 dot has no correct digit. dd (106 bits) keeps + # about 1e20 * 2^-106 * n ~ 1e-10 of relative error; td and qd (159 and + # 212 bits) are correctly rounded. Measured: f64 4.7e4, dd 6e-12, td 0. + CASCADE_REL_ERR = {"dd_cascade": 1e-9, "td_cascade": 0.0, "qd_cascade": 0.0} + + @pytest.mark.parametrize("name", ["dd_cascade", "td_cascade", "qd_cascade"]) + def test_cascade_gemm_beats_float64_on_ill_conditioned_products(self, name): + X, Y, exact = self._ill_conditioned(1e20) + f64_err = np.abs(np.diag(X @ Y) - exact) / np.abs(exact) + assert f64_err.max() > 1.0 # the premise: float64 gets nothing right + C = mtl5.mixed.matmul(mtl5.convert(X, name), mtl5.convert(Y, name)).to_numpy() + err = np.abs(np.diag(C) - exact) / np.abs(exact) + assert err.max() <= self.CASCADE_REL_ERR[name] + + @pytest.mark.parametrize("name", ["dd_cascade", "td_cascade", "qd_cascade"]) + def test_cascade_gemv_beats_float64_on_an_ill_conditioned_product(self, name): + X, Y, exact = self._ill_conditioned(1e20, m=1) + A = np.vstack([X[0], 2 * X[0]]) # scaling by 2 is exact + y = Y[:, 0] + want = np.array([exact[0], 2 * exact[0]]) + assert np.max(np.abs(A @ y - want) / np.abs(want)) > 1e-3 + got = mtl5.mixed.matvec(mtl5.convert(A, name), mtl5.convert(y, name)).to_numpy() + assert np.max(np.abs(got - want) / np.abs(want)) <= self.CASCADE_REL_ERR[name] + @pytest.mark.parametrize("name", ["dd_cascade", "td_cascade", "qd_cascade"]) def test_cascade_roundtrip_is_float64_exact(self, name): # Boundary precision is float64 by construction — assert it rather than diff --git a/tests/test_krylov_dispatch.py b/tests/test_krylov_dispatch.py index 3ede8ca..d92cd5c 100644 --- a/tests/test_krylov_dispatch.py +++ b/tests/test_krylov_dispatch.py @@ -387,6 +387,13 @@ def test_the_defaults(self): with pytest.raises(TypeError, match="float32 or float64"): ms.default_rtol(np.float16) + @pytest.mark.parametrize( + "dtype", [np.int32, np.int64, "int32", np.complex64, np.complex128, "complex128", "f16"] + ) + def test_no_default_for_other_types(self, dtype): + with pytest.raises(TypeError, match="float32 or float64"): + ms.default_rtol(dtype) + @pytest.mark.parametrize("solver", ALL_SOLVERS) def test_every_solver_converges_in_float32(self, solver): n = 50 @@ -395,9 +402,19 @@ def test_every_solver_converges_in_float32(self, solver): b = (A @ x_true).astype(np.float32) x, info, rep = ms.iterative_solve(A, b, solver=solver, full_output=True) assert info == 0, f"{solver}: info={info} after {rep.iterations} iterations" - assert rep.relative_residual <= ms.default_rtol(np.float32) * (1 + 1e-3) - # Forward error is bounded by cond(A) ~ 1e3 times the residual. - np.testing.assert_allclose(x, x_true, rtol=0.5) + rtol = ms.default_rtol(np.float32) + assert rep.relative_residual <= rtol * (1 + 1e-3) + # The forward error is at most cond(A) times the relative residual + # (2-norms), and cond(A) is about 1e3 here, so float32's default rtol + # of 3.5e-4 allows about 0.35. The residual is recomputed in float64: + # the solver's recurrence can drift from the true one. + A64, x64, b64 = A.astype(np.float64), x.astype(np.float64), b.astype(np.float64) + cond = np.linalg.cond(A64.toarray()) + assert 1e3 < cond < 1.1e3 + true_res = np.linalg.norm(b64 - A64 @ x64) / np.linalg.norm(b64) + assert true_res <= rtol * 1.01 + fwd = np.linalg.norm(x64 - x_true) / np.linalg.norm(x_true) + assert fwd <= cond * true_res * (1 + 1e-6) @pytest.mark.parametrize("solver", ["cg", "gmres", "bicgstab"]) def test_named_wrappers_default_too(self, solver): diff --git a/tests/test_multigrid.py b/tests/test_multigrid.py index cef0497..4e2e83c 100644 --- a/tests/test_multigrid.py +++ b/tests/test_multigrid.py @@ -311,6 +311,50 @@ def test_cycles_argument_compounds(self): assert residual(A, three.to_numpy(), b) < residual(A, one.to_numpy(), b) +class TestSmootherReuse: + """#223 built each level's smoother once per cycle call instead of once + per sweep. Pinned here by counting constructions (mg._smoother_builds, a + test hook) rather than by timing: a rebuild per sweep costs only about + 1.7x, which no order-of-magnitude timing band can tell from noise (#235). + The smoothers keep scratch between sweeps once they are reused, so the + second test checks that a cycle's result does not depend on the reuse.""" + + @pytest.mark.parametrize("kind", SMOOTHERS) + @pytest.mark.parametrize("method", ["vcycle", "wcycle"]) + def test_one_build_per_level_per_call(self, kind, method): + n = 63 + A = poisson1d(n) + b = mtl5.vector(np.ones(n)) + x0 = mtl5.vector(np.zeros(n)) + M = g.multigrid_1d(ms.from_scipy(A), n_levels=4, smoother=kind, nu_pre=3, nu_post=2) + for cycles in (1, 10): + before = g._smoother_builds() + getattr(M, method)(x0, b, cycles=cycles) + # The levels' smoothers and the coarse solve's: one per level. + assert g._smoother_builds() - before == M.n_levels + + @pytest.mark.parametrize("kind", SMOOTHERS) + def test_smooth_builds_one_whatever_the_sweeps(self, kind): + n = 15 + A = ms.from_scipy(poisson1d(n)) + before = g._smoother_builds() + g.smooth(A, mtl5.vector(np.zeros(n)), mtl5.vector(np.ones(n)), kind=kind, sweeps=7) + assert g._smoother_builds() - before == 1 + + @pytest.mark.parametrize("kind", SMOOTHERS) + @pytest.mark.parametrize("method", ["vcycle", "wcycle"]) + def test_k_cycles_are_k_single_cycles_exactly(self, kind, method): + n = 63 + A = poisson1d(n) + b = mtl5.vector(np.ones(n)) + M = g.multigrid_1d(ms.from_scipy(A), n_levels=4, smoother=kind) + step = mtl5.vector(np.zeros(n)) + for _ in range(4): + step = getattr(M, method)(step, b, cycles=1) + at_once = getattr(M, method)(mtl5.vector(np.zeros(n)), b, cycles=4) + np.testing.assert_array_equal(at_once.to_numpy(), step.to_numpy()) + + class TestUndampedJacobiIsAPoorSmoother: """Jacobi is excluded from the hierarchy test above, deliberately. diff --git a/tests/test_sparse_vector.py b/tests/test_sparse_vector.py index 4f42565..433a0f7 100644 --- a/tests/test_sparse_vector.py +++ b/tests/test_sparse_vector.py @@ -225,3 +225,34 @@ def test_size_zero(): def test_f32_dot_with_a_float64_vector(): v = ms.sparse_vector(4, [0, 2], [1.5, 2.5], dtype="f32") assert v.dot(np.ones(4, np.float64)) == pytest.approx(4.0) + + +def _best_time(f, repeat=5): + import time + + best = float("inf") + for _ in range(repeat): + t = time.perf_counter() + f() + best = min(best, time.perf_counter() - t) + return best + + +@pytest.mark.perf +@pytest.mark.parametrize("accumulate", [False, True]) +def test_an_unsorted_build_stays_near_linear(accumulate): + """#223: each entry was inserted into the sorted storage as it came, so an + unsorted build of k entries was O(k^2); it now sorts first (#226). Ten + times the entries must cost about ten times as much, not a hundred: the + band's ceiling of 40 is 4x above n log n and 2.5x below quadratic. Measured + at 10.5x (k = 1e4: 1.9 ms, 1e5: 20 ms).""" + rng = np.random.default_rng(0) + + def build(k): + idx = rng.permutation(10 * k)[:k] + vals = np.ones(k) + return lambda: ms.sparse_vector(10 * k, idx, vals, accumulate=accumulate) + + small, large = build(10**4), build(10**5) + ratio = _best_time(large) / _best_time(small) + assert ratio < 40, f"a 10x larger unsorted build took {ratio:.1f}x as long" From 2a8814a1524f442c5a98da68bf99a0022cb8452d Mon Sep 17 00:00:00 2001 From: Theodore Omtzigt Date: Sun, 6 Dec 2026 09:17:58 -0500 Subject: [PATCH 2/3] fix(sparse): default_rtol refuses a dtype name NumPy does not know like any other np.dtype("f16") is float128 on Linux and a TypeError on macOS, so default_rtol("f16") raised "data type 'f16' not understood" there instead of its own message; so did "fp16", MTL5's half, everywhere. An unparseable name now gets the same TypeError as an unsupported one. Found by #235's new test on the macOS runner. Co-Authored-By: Claude Opus 5.5 --- mtl5/sparse/__init__.py | 10 ++++++++-- tests/test_krylov_dispatch.py | 6 +++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/mtl5/sparse/__init__.py b/mtl5/sparse/__init__.py index 4c311bf..ab38185 100644 --- a/mtl5/sparse/__init__.py +++ b/mtl5/sparse/__init__.py @@ -448,11 +448,17 @@ def default_rtol(dtype): 1e-10 for float64 and sqrt(eps) of float32 (about 3.5e-4) for float32. `dtype` is a NumPy dtype or type, or MTL5's "f64" / "f32". """ + msg = f"no default rtol for {dtype!r}: the solvers take float32 or float64" key = {"f64": np.float64, "f32": np.float32}.get(dtype, None) if key is None: - key = np.dtype(dtype).type + try: + key = np.dtype(dtype).type + except TypeError: + # A name NumPy does not know on this platform, such as "f16" + # (float128) on macOS: the same answer as for a known one. + raise TypeError(msg) from None if key not in _DEFAULT_RTOL: - raise TypeError(f"no default rtol for {dtype!r}: the solvers take float32 or float64") + raise TypeError(msg) return _DEFAULT_RTOL[key] diff --git a/tests/test_krylov_dispatch.py b/tests/test_krylov_dispatch.py index d92cd5c..c139bf6 100644 --- a/tests/test_krylov_dispatch.py +++ b/tests/test_krylov_dispatch.py @@ -388,9 +388,13 @@ def test_the_defaults(self): ms.default_rtol(np.float16) @pytest.mark.parametrize( - "dtype", [np.int32, np.int64, "int32", np.complex64, np.complex128, "complex128", "f16"] + "dtype", + [np.int32, np.int64, "int32", np.complex64, np.complex128, "complex128", "f16", "fp16"], ) def test_no_default_for_other_types(self, dtype): + # "f16" is float128 where NumPy has it and unknown where it does not + # (macOS); "fp16" is MTL5's half, a name NumPy never knows. Both are + # refused the same way. with pytest.raises(TypeError, match="float32 or float64"): ms.default_rtol(dtype) From 0ad3a13623bd1ce6b39589f59c4f82ba5c0d1d9f Mon Sep 17 00:00:00 2001 From: Theodore Omtzigt Date: Sun, 6 Dec 2026 10:12:36 -0500 Subject: [PATCH 3/3] test(extended): cfloat32 at the exact binary32 overflow midpoint F32_MAX * (1 + 2^-24) is 2^128 - 2^80, above the midpoint 2^128 - 2^103, so the "at the overflow threshold" case never tested the tie. Now the midpoint itself (a tie to inf: F32_MAX's significand is odd) and its two binary64 neighbours, bit for bit against np.float32. CodeRabbit on #239. Co-Authored-By: Claude Opus 5.5 --- tests/test_extended_number_types.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/test_extended_number_types.py b/tests/test_extended_number_types.py index ccc846c..86b2ff5 100644 --- a/tests/test_extended_number_types.py +++ b/tests/test_extended_number_types.py @@ -216,12 +216,17 @@ def test_loses_precision_float64_keeps(self): assert mtl5.convert(x, "cfloat32").to_numpy()[0] == 1.0 # The edges of binary32, compared bit for bit with np.float32 (#235). - F32_MAX = float(np.finfo(np.float32).max) + F32_MAX = float(np.finfo(np.float32).max) # 2^128 - 2^104 + # Halfway from F32_MAX to 2^128, where binary32 overflows. F32_MAX's + # significand is odd, so the tie goes to infinity. + OVERFLOW_MIDPOINT = 2.0**128 - 2.0**103 TINY = 2.0**-149 # the smallest binary32 subnormal EDGES = { "max": F32_MAX, - "just under the overflow threshold": F32_MAX * (1 + 2.0**-25), - "at the overflow threshold": F32_MAX * (1 + 2.0**-24), + "just under the overflow midpoint": float(np.nextafter(OVERFLOW_MIDPOINT, 0.0)), + "at the overflow midpoint, a tie to inf": OVERFLOW_MIDPOINT, + "just over the overflow midpoint": float(np.nextafter(OVERFLOW_MIDPOINT, np.inf)), + "between the midpoint and 2^128": F32_MAX * (1 + 2.0**-24), "past 3.4e38": 3.5e38, "far past": 1e39, "far past, negative": -1e39,