"""Tests for the PyTorch claims the book makes. Same contract as test_tour.py: these test PyTorch, not the narration. They are skipped rather than failed when PyTorch is not installed, so the language half of the course runs on a machine with nothing but Python. python -m unittest discover -s code -t code -v """ from __future__ import annotations import unittest try: import torch from torch import nn except ImportError: # pragma: no cover torch = None # type: ignore[assignment] import torch_intro requires_torch = unittest.skipIf(torch is None, "PyTorch is not installed") @requires_torch class TestTensors(unittest.TestCase): def test_dtype_is_inferred_from_the_python_values(self) -> None: self.assertEqual(torch.tensor([1, 2]).dtype, torch.int64) self.assertEqual(torch.tensor([1.0, 2.0]).dtype, torch.float32) def test_broadcasting_aligns_from_the_right(self) -> None: out = torch.ones(4, 3) + torch.tensor([1.0, 2.0, 3.0]) self.assertEqual(tuple(out.shape), (4, 3)) self.assertTrue(torch.equal(out[0], torch.tensor([2.0, 3.0, 4.0]))) def test_misaligned_shapes_are_refused(self) -> None: with self.assertRaises(RuntimeError): torch.ones(4, 3) + torch.ones(4) def test_view_shares_storage_and_clone_does_not(self) -> None: base = torch.arange(6) base.view(2, 3)[0, 0] = 99 self.assertEqual(base[0].item(), 99) cloned = base.clone() cloned[0] = 0 self.assertEqual(base[0].item(), 99) def test_underscore_suffix_mutates_in_place(self) -> None: t = torch.ones(3) self.assertIs(t.add_(1), t) self.assertEqual(t.tolist(), [2.0, 2.0, 2.0]) self.assertIsNot(t.add(1), t) @requires_torch class TestAutograd(unittest.TestCase): def test_gradient_matches_the_hand_derivative(self) -> None: x = torch.tensor(4.0, requires_grad=True) (x ** 2 + 3 * x).backward() self.assertEqual(x.grad.item(), 11.0) # 2x + 3 at x = 4 def test_gradients_accumulate_until_zeroed(self) -> None: x = torch.tensor(4.0, requires_grad=True) (x ** 2 + 3 * x).backward() (x ** 2 + 3 * x).backward() self.assertEqual(x.grad.item(), 22.0) x.grad = None (x ** 2 + 3 * x).backward() self.assertEqual(x.grad.item(), 11.0) def test_no_grad_stops_recording(self) -> None: x = torch.tensor(2.0, requires_grad=True) with torch.no_grad(): self.assertFalse((x * 2).requires_grad) self.assertTrue((x * 2).requires_grad) def test_detach_cuts_one_tensor_loose(self) -> None: x = torch.tensor(2.0, requires_grad=True) self.assertFalse(x.detach().requires_grad) self.assertTrue(x.requires_grad) @requires_torch class TestTraining(unittest.TestCase): def test_the_loop_recovers_the_weights_it_was_given(self) -> None: result = torch_intro.part_c_training(steps=400) for learned, truth in zip(result["learned_weights"], torch_intro.TRUE_WEIGHTS, strict=True): self.assertAlmostEqual(learned, truth, delta=0.02) self.assertAlmostEqual(result["learned_bias"], torch_intro.TRUE_BIAS, delta=0.02) self.assertLess(result["final_loss"], result["first_loss"] / 100) def test_zero_grad_changes_the_outcome(self) -> None: """Dropping zero_grad() is not cosmetic: the updates stop being correct.""" def run(zero: bool) -> float: torch.manual_seed(torch_intro.SEED) inputs = torch.randn(256, 2) targets = inputs @ torch.tensor(torch_intro.TRUE_WEIGHTS).unsqueeze(1) + torch_intro.TRUE_BIAS model = nn.Linear(2, 1) opt = torch.optim.SGD(model.parameters(), lr=0.1) loss = torch.tensor(float("nan")) for _ in range(60): loss = nn.functional.mse_loss(model(inputs), targets) if zero: opt.zero_grad() loss.backward() opt.step() return loss.item() self.assertLess(run(zero=True), run(zero=False)) @requires_torch class TestModule(unittest.TestCase): def test_submodule_parameters_are_discovered_by_traversal(self) -> None: model = torch_intro.TinyMLP() self.assertEqual( [name for name, _ in model.named_parameters()], ["stem.weight", "stem.bias", "head.weight", "head.bias"], ) def test_a_plain_list_hides_parameters_but_modulelist_does_not(self) -> None: class WithList(nn.Module): def __init__(self) -> None: super().__init__() self.layers = [nn.Linear(2, 2)] # invisible to PyTorch class WithModuleList(nn.Module): def __init__(self) -> None: super().__init__() self.layers = nn.ModuleList([nn.Linear(2, 2)]) self.assertEqual(list(WithList().parameters()), []) self.assertEqual(len(list(WithModuleList().parameters())), 2) def test_eval_disables_dropout(self) -> None: model = torch_intro.TinyMLP() model.train() self.assertTrue(model.drop.training) model.eval() self.assertFalse(model.drop.training) def test_state_dict_round_trips(self) -> None: torch.manual_seed(torch_intro.SEED) model = torch_intro.TinyMLP().eval() restored = torch_intro.TinyMLP() restored.load_state_dict(model.state_dict()) restored.eval() sample = torch.randn(8, 2) with torch.no_grad(): self.assertTrue(torch.allclose(model(sample), restored(sample))) def test_a_different_width_refuses_the_weights(self) -> None: state = torch_intro.TinyMLP().state_dict() with self.assertRaises(RuntimeError): torch_intro.TinyMLP(hidden=8).load_state_dict(state) if __name__ == "__main__": unittest.main(verbosity=2)