Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<suffix>` / `DenseMatrix_<suffix>` class and `vector_<suffix>` / `matrix_<suffix>` factory. The source of truth is `type_suffix<T>()` in `python/src/mtl5_types.hpp`.
Every element type has its own `DenseVector_<suffix>` / `DenseMatrix_<suffix>` class. The Universal types also have a `vector_<suffix>` / `matrix_<suffix>` 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<T>()` in `python/src/mtl5_types.hpp`; `tests/test_dtype_lists.py` keeps the lists in step.

| Suffix | C++ type | Notes |
|---|---|---|
Expand Down
10 changes: 8 additions & 2 deletions mtl5/sparse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]


Expand Down
12 changes: 12 additions & 0 deletions python/src/mtl5_multigrid.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
#include <mtl/itl/smoother/sor.hpp>
#include <mtl/operation/mult.hpp>

#include <atomic>
#include <cstddef>
#include <functional>
#include <memory>
Expand Down Expand Up @@ -81,10 +82,17 @@ void check_omega(const std::string& kind, double omega) {
/// One relaxation sweep, in place on x.
using SmoothFn = std::function<void(Vec&, const Vec&)>;

/// 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<std::size_t> 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); };
};
Expand Down Expand Up @@ -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,
Expand Down
165 changes: 161 additions & 4 deletions tests/test_accurate_sum_dot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
104 changes: 104 additions & 0 deletions tests/test_dtype_lists.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""The element-type lists stay in step (#235).

Three lists name the bound element types: `type_suffix<T>()` 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_<suffix>` / `matrix_<suffix>` 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_<suffix> 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)
Loading
Loading