Skip to content

A straightforward method for training your LLM, from downloading data to generating text.

test: check tensor shapes and types at runtime during the tests

FareedKhan-dev52aa613350e7
diff --git a/tests/_typecheck.py b/tests/_typecheck.py
new file mode 100644
index 0000000..fcd444a
--- /dev/null
+++ b/tests/_typecheck.py
@@ -0,0 +1,10 @@
+"""The runtime type checker used by tests/conftest.py.
+
+beartype with the PEP 484 numeric tower turned on, so an ``int`` is accepted where a ``float``
+is annotated, exactly like mypy does. Without it, ``apply_lora(model, rank=4, alpha=8)``
+would be rejected for passing 8 instead of 8.0.
+"""
+
+from beartype import BeartypeConf, beartype
+
+typechecker = beartype(conf=BeartypeConf(is_pep484_tower=True))
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..bc1478d
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,35 @@
+"""
+Test-wide setup: check tensor shapes and types at runtime.
+
+The newer modules annotate their tensors with jaxtyping, for example
+``Float[Tensor, "batch seq vocab"]``. While the tests run, jaxtyping's import hook wraps every
+function in those modules with beartype, so a wrong shape, a wrong dtype or a mismatched
+dimension name raises at the call instead of producing a silently wrong number later.
+
+Set ``SHAPE_CHECKS=0`` to run the tests without it (for example to time them).
+"""
+
+from __future__ import annotations
+
+import os
+
+CHECKED_MODULES = [
+ "src.inference",
+ "src.models.lora",
+ "src.models.modern",
+ "src.optim",
+ "src.post_training.dpo",
+ "src.post_training.grpo",
+]
+
+if os.environ.get("SHAPE_CHECKS", "1") != "0":
+ try:
+ from jaxtyping import install_import_hook
+
+ import tests._typecheck # noqa: F401 (jaxtyping looks the checker up as tests -> _typecheck)
+ except ImportError: # beartype is a dev dependency; plain runs still work without it
+ pass
+ else:
+ # Installed for the whole session (no `with`), before any test imports these modules.
+ # tests/_typecheck.py is beartype with PEP 484 int-for-float promotion, like mypy.
+ install_import_hook(CHECKED_MODULES, "tests._typecheck.typechecker")
diff --git a/tests/test_optim.py b/tests/test_optim.py
index 321c780..4078cd8 100644
--- a/tests/test_optim.py
+++ b/tests/test_optim.py
@@ -93,5 +93,6 @@ def test_schedules_hit_their_anchor_points() -> None:
assert wsd_lr(80, **kw) == pytest.approx(1.0) # still in the stable phase
assert wsd_lr(99, **kw) == pytest.approx(0.55, abs=0.03) # halfway through the final 20%
assert lr_at("wsd", 80, **kw) == wsd_lr(80, **kw)
- with pytest.raises(ValueError):
+ # A bad name is a ValueError, or a TypeError first when the runtime shape/type checks are on.
+ with pytest.raises((ValueError, TypeError)):
lr_at("constant", 0, **kw) # type: ignore[arg-type]
diff --git a/tests/test_type_checks.py b/tests/test_type_checks.py
new file mode 100644
index 0000000..4bad824
--- /dev/null
+++ b/tests/test_type_checks.py
@@ -0,0 +1,25 @@
+"""The runtime shape checks from conftest.py are really on: wrong shapes fail at the call."""
+
+from __future__ import annotations
+
+import os
+
+import pytest
+import torch
+
+from src.inference.sampling import sample_next_token
+from src.models.modern import apply_rope, rope_cache
+
+pytestmark = pytest.mark.skipif(os.environ.get("SHAPE_CHECKS") == "0", reason="shape checks turned off")
+
+
+def test_a_shape_mismatch_is_caught_at_the_call() -> None:
+ x = torch.randn(2, 4, 8) # 4 positions
+ cos, sin = rope_cache(8, 5) # tables for 5 positions: "seq" does not match
+ with pytest.raises(TypeError, match="seq"):
+ apply_rope(x, cos, sin)
+
+
+def test_a_wrong_dtype_is_caught_at_the_call() -> None:
+ with pytest.raises(TypeError):
+ sample_next_token(torch.ones(1, 5, dtype=torch.long)) # logits must be floats