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
13 changes: 13 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,21 @@ dev = [
"networkx",
"types-networkx",
"nbformat>=5.0",
# Gated below 3.14 because PyTorch doesn't publish wheels for 3.14 yet; the torch tests
# skip themselves when torch isn't installed (e.g. on the 3.14 CI job).
"torch>=2.0; python_version < '3.14'",
]

[tool.uv.sources]
# Use the CPU-only PyTorch wheels on Linux so CI (and the grader images) don't pull the
# multi-gigabyte CUDA build. macOS/Windows fall back to the default index, which is CPU-only.
torch = [{ index = "pytorch-cpu", marker = "sys_platform == 'linux'" }]

[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true

[build-system]
requires = ["hatchling", "uv-dynamic-versioning"]
build-backend = "hatchling.build"
Expand Down
4 changes: 4 additions & 0 deletions src/pytest_prairielearn_grader/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
from .assertions import assert_false
from .assertions import assert_fn_approx_equal
from .assertions import assert_fn_equal
from .assertions import assert_tensor_allclose
from .assertions import assert_tensor_equal
from .assertions import assert_true
from .config import ConfigObject
from .fixture import WorkspaceFixture
Expand All @@ -23,5 +25,7 @@
"assert_false",
"assert_fn_approx_equal",
"assert_fn_equal",
"assert_tensor_allclose",
"assert_tensor_equal",
"assert_true",
]
190 changes: 190 additions & 0 deletions src/pytest_prairielearn_grader/assertions.py
Original file line number Diff line number Diff line change
Expand Up @@ -369,3 +369,193 @@ def assert_fn_approx_equal(
call_description = description or format_call(func_name, args, kwargs)
assert_approx_equal(actual, expected, rtol=rtol, atol=atol, msg=msg, description=call_description)
return actual


# ---------------------------------------------------------------------------
# PyTorch tensor assertions
# ---------------------------------------------------------------------------


def _as_cpu_tensor(value: Any) -> Any:
"""Coerce a value to a detached CPU tensor so comparisons never touch autograd or a device."""
import torch # noqa: PLC0415

return torch.as_tensor(value).detach().cpu()


def _tensor_detail(value: Any) -> str:
"""A short, student-readable description of a tensor's shape, dtype and (if small) values."""
tensor = _as_cpu_tensor(value)
dtype = str(tensor.dtype).removeprefix("torch.")
detail = f"a tensor with shape {tuple(tensor.shape)} and dtype {dtype}"
if tensor.numel() <= 12:
detail += f" and values {tensor.tolist()}"
return detail


def assert_tensor_allclose(
actual: Any,
expected: Any,
*,
rtol: float = 1e-5,
atol: float = 1e-8,
check_dtype: bool = False,
equal_nan: bool = True,
msg: str | None = None,
description: str | None = None,
) -> None:
"""Assert two PyTorch tensors are equal within a tolerance.

Uses the formula ``|actual - expected| <= atol + rtol * |expected|`` elementwise.
``actual`` and ``expected`` may be anything ``torch.as_tensor`` accepts (a tensor,
a NumPy array, or a nested list). Tensors are detached and moved to the CPU before
comparison, so gradients and device placement don't matter.

Parameters
----------
actual:
The tensor produced by student code.
expected:
The correct / reference tensor.
rtol:
Relative tolerance (default ``1e-5``).
atol:
Absolute tolerance (default ``1e-8``).
check_dtype:
When True, the two tensors must also share a dtype. When False (default), an
integer tensor and the equivalent float tensor compare equal.
equal_nan:
When True (default), NaNs in matching positions compare equal.
msg:
Optional custom failure message.
description:
Optional label for the *Checking:* line.

Raises
------
AssertionError
When the shapes differ, the dtypes differ (with ``check_dtype``), or the
values are not within tolerance.
"""
import torch # noqa: PLC0415

actual_tensor = _as_cpu_tensor(actual)
expected_tensor = _as_cpu_tensor(expected)

if actual_tensor.shape != expected_tensor.shape:
raise AssertionError(
_build_failure_lines(
expected=_tensor_detail(expected_tensor),
actual=_tensor_detail(actual_tensor),
description=description,
msg=msg or "The tensors have different shapes.",
)
)

if check_dtype and actual_tensor.dtype != expected_tensor.dtype:
raise AssertionError(
_build_failure_lines(
expected=_tensor_detail(expected_tensor),
actual=_tensor_detail(actual_tensor),
description=description,
msg=msg or "The tensors have different dtypes.",
)
)

target = torch.complex128 if (actual_tensor.is_complex() or expected_tensor.is_complex()) else torch.float64
actual_cast = actual_tensor.to(target)
expected_cast = expected_tensor.to(target)

if torch.allclose(actual_cast, expected_cast, rtol=rtol, atol=atol, equal_nan=equal_nan):
return

mismatches = ~torch.isclose(actual_cast, expected_cast, rtol=rtol, atol=atol, equal_nan=equal_nan)
num_mismatch = int(mismatches.sum().item())
abs_diff = (actual_cast - expected_cast).abs()
max_diff = float(torch.nan_to_num(abs_diff, nan=float("inf")).max().item()) if abs_diff.numel() else 0.0
default_msg = (
f"The tensors are not close enough (rtol={rtol}, atol={atol}): "
f"{num_mismatch} of {actual_tensor.numel()} elements differ, "
f"max absolute difference {max_diff:.3g}."
)
raise AssertionError(
_build_failure_lines(
expected=_tensor_detail(expected_tensor),
actual=_tensor_detail(actual_tensor),
description=description,
msg=msg or default_msg,
)
)


def assert_tensor_equal(
actual: Any,
expected: Any,
*,
check_dtype: bool = False,
msg: str | None = None,
description: str | None = None,
) -> None:
"""Assert two PyTorch tensors are exactly equal.

Prefer this for integer, boolean, or index tensors where exact equality is meaningful;
use :func:`assert_tensor_allclose` for floating-point tensors. ``actual`` and ``expected``
may be anything ``torch.as_tensor`` accepts, and are detached and moved to the CPU before
comparison.

Parameters
----------
actual:
The tensor produced by student code.
expected:
The correct / reference tensor.
check_dtype:
When True, the two tensors must also share a dtype (default False).
msg:
Optional custom failure message.
description:
Optional label for the *Checking:* line.

Raises
------
AssertionError
When the shapes differ, the dtypes differ (with ``check_dtype``), or any
elements differ.
"""
actual_tensor = _as_cpu_tensor(actual)
expected_tensor = _as_cpu_tensor(expected)

if actual_tensor.shape != expected_tensor.shape:
raise AssertionError(
_build_failure_lines(
expected=_tensor_detail(expected_tensor),
actual=_tensor_detail(actual_tensor),
description=description,
msg=msg or "The tensors have different shapes.",
)
)

if check_dtype and actual_tensor.dtype != expected_tensor.dtype:
raise AssertionError(
_build_failure_lines(
expected=_tensor_detail(expected_tensor),
actual=_tensor_detail(actual_tensor),
description=description,
msg=msg or "The tensors have different dtypes.",
)
)

elementwise_equal = actual_tensor == expected_tensor
if bool(elementwise_equal.all()):
return

num_mismatch = int((~elementwise_equal).sum().item())
default_msg = f"The tensors are not equal: {num_mismatch} of {actual_tensor.numel()} elements differ."
raise AssertionError(
_build_failure_lines(
expected=_tensor_detail(expected_tensor),
actual=_tensor_detail(actual_tensor),
description=description,
msg=msg or default_msg,
)
)
19 changes: 19 additions & 0 deletions src/pytest_prairielearn_grader/json_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ def to_json(v: Any) -> Any:

if is_plot(v):
return plot_to_json(v)
elif module == "torch":
import torch

if isinstance(v, torch.Tensor):
# Detach from any autograd graph and move to CPU so the tensor serializes
# whether or not it carries gradients or lives on an accelerator.
detached = v.detach().cpu()
return {
"_type": "torch_tensor",
"_value": detached.tolist(),
"_dtype": str(detached.dtype).removeprefix("torch."),
}
else:
return v

Expand Down Expand Up @@ -158,6 +170,13 @@ def from_json(v_json) -> Any:
raise ValueError("variable of type matplotlib_figure should have value")
elif v_json["_type"] == "sparse":
return _sparse_from_json(v_json)
elif v_json["_type"] == "torch_tensor":
import torch

if "_value" not in v_json:
raise ValueError("variable of type torch_tensor should have value")
dtype = getattr(torch, v_json["_dtype"]) if "_dtype" in v_json else None
return torch.tensor(v_json["_value"], dtype=dtype)
else:
raise ValueError("variable has unknown type {}".format(v_json["_type"]))
return v_json
Expand Down
117 changes: 117 additions & 0 deletions tests/test_torch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
"""Tests for PyTorch tensor serialization and assertion helpers.

torch is an optional, heavy dependency, so these tests are skipped when it isn't installed.
"""

from typing import TYPE_CHECKING

import pytest

if TYPE_CHECKING:
import torch
else:
torch = pytest.importorskip("torch")

from pytest_prairielearn_grader.assertions import assert_tensor_allclose
from pytest_prairielearn_grader.assertions import assert_tensor_equal
from pytest_prairielearn_grader.json_utils import from_json
from pytest_prairielearn_grader.json_utils import to_json

# ---------------------------------------------------------------------------
# Serialization round-trips
# ---------------------------------------------------------------------------


@pytest.mark.parametrize(
"tensor",
[
torch.tensor([1.0, 2.0, 3.0]),
torch.tensor([[1, 2], [3, 4]], dtype=torch.int64),
torch.tensor(3.5), # 0-dim scalar
torch.tensor([True, False, True]),
torch.zeros(0), # empty
torch.tensor([1 + 2j, 3 - 4j], dtype=torch.complex64),
],
)
def test_tensor_round_trip(tensor: "torch.Tensor") -> None:
restored = from_json(to_json(tensor))
assert isinstance(restored, torch.Tensor)
assert restored.shape == tensor.shape
assert restored.dtype == tensor.dtype
assert torch.equal(restored, tensor)


def test_tensor_serialization_detaches_grad_and_device() -> None:
tensor = torch.tensor([1.0, 2.0], requires_grad=True)
# Serializing a tensor that tracks gradients must not raise.
restored = from_json(to_json(tensor))
assert not restored.requires_grad
assert torch.equal(restored, tensor.detach())


def test_to_json_ignores_non_tensor_torch_objects() -> None:
# A torch dtype is in the torch module but isn't a tensor; it should pass through unchanged.
assert to_json(torch.float32) is torch.float32


# ---------------------------------------------------------------------------
# assert_tensor_allclose
# ---------------------------------------------------------------------------


def test_allclose_passes_within_tolerance() -> None:
assert_tensor_allclose(torch.tensor([1.0, 2.0]), torch.tensor([1.0 + 1e-9, 2.0]))


def test_allclose_accepts_arrays_and_lists() -> None:
assert_tensor_allclose([1.0, 2.0, 3.0], torch.tensor([1.0, 2.0, 3.0]))


def test_allclose_ignores_dtype_by_default() -> None:
assert_tensor_allclose(torch.tensor([1, 2, 3]), torch.tensor([1.0, 2.0, 3.0]))


def test_allclose_check_dtype_rejects_mismatch() -> None:
with pytest.raises(AssertionError, match="different dtypes"):
assert_tensor_allclose(torch.tensor([1, 2]), torch.tensor([1.0, 2.0]), check_dtype=True)


def test_allclose_reports_shape_mismatch() -> None:
with pytest.raises(AssertionError, match="different shapes"):
assert_tensor_allclose(torch.zeros(3), torch.zeros(4))


def test_allclose_reports_value_mismatch_detail() -> None:
with pytest.raises(AssertionError, match="max absolute difference"):
assert_tensor_allclose(torch.tensor([1.0, 2.0]), torch.tensor([1.0, 5.0]))


def test_allclose_description_in_message() -> None:
with pytest.raises(AssertionError, match="Checking: forward pass"):
assert_tensor_allclose(torch.zeros(2), torch.ones(2), description="forward pass")


def test_allclose_equal_nan() -> None:
nan = float("nan")
assert_tensor_allclose(torch.tensor([nan, 1.0]), torch.tensor([nan, 1.0]))
with pytest.raises(AssertionError):
assert_tensor_allclose(torch.tensor([nan, 1.0]), torch.tensor([nan, 1.0]), equal_nan=False)


# ---------------------------------------------------------------------------
# assert_tensor_equal
# ---------------------------------------------------------------------------


def test_equal_passes() -> None:
assert_tensor_equal(torch.tensor([1, 2, 3]), torch.tensor([1, 2, 3]))


def test_equal_reports_mismatch_count() -> None:
with pytest.raises(AssertionError, match="2 of 3 elements differ"):
assert_tensor_equal(torch.tensor([1, 9, 9]), torch.tensor([1, 2, 3]))


def test_equal_shape_mismatch() -> None:
with pytest.raises(AssertionError, match="different shapes"):
assert_tensor_equal(torch.tensor([1, 2]), torch.tensor([1, 2, 3]))
Loading
Loading