Download tests/train/test_checkpoint.py from Kolgrim/hades: direct link, hf CLI and curl.
- Browser
- Download file 1.95 kB
-
https://huggingface.co/Kolgrim/hades/resolve/main/tests/train/test_checkpoint.py
- Command line
-
hf download hf://Kolgrim/hades/tests/train/test_checkpoint.py
-
curl -L -o test_checkpoint.py https://huggingface.co/Kolgrim/hades/resolve/main/tests/train/test_checkpoint.py
1.95 kB
| import random | |
| import numpy as np | |
| import torch | |
| from hades.train.checkpoint import checkpoint_path, latest_checkpoint, load_checkpoint, prune_checkpoints, save_checkpoint | |
| def _model(): | |
| torch.manual_seed(0) | |
| return torch.nn.Linear(4, 3) | |
| def test_roundtrip_restores_model_and_rng(tmp_path): | |
| m = _model() | |
| opt = torch.optim.AdamW(m.parameters(), lr=1e-3) | |
| m(torch.randn(2, 4)).sum().backward() | |
| opt.step() | |
| random.seed(1), np.random.seed(1), torch.manual_seed(1) | |
| save_checkpoint(checkpoint_path(tmp_path, 10), m, opt, None, 10, {"best": 1.5}) | |
| expected = (random.random(), np.random.rand(), torch.rand(3)) | |
| m2 = torch.nn.Linear(4, 3) | |
| opt2 = torch.optim.AdamW(m2.parameters(), lr=1e-3) | |
| info = load_checkpoint(checkpoint_path(tmp_path, 10), m2, opt2) | |
| got = (random.random(), np.random.rand(), torch.rand(3)) | |
| assert got[0] == expected[0] and got[1] == expected[1] and torch.equal(got[2], expected[2]) | |
| assert info == {"step": 10, "extra": {"best": 1.5}} | |
| x = torch.randn(2, 4) | |
| assert torch.equal(m(x), m2(x)) | |
| assert opt2.state_dict()["state"][0]["step"] == opt.state_dict()["state"][0]["step"] | |
| def test_latest_ignores_tmp_and_best(tmp_path): | |
| assert latest_checkpoint(tmp_path) is None | |
| m = _model() | |
| save_checkpoint(checkpoint_path(tmp_path, 200), m, None, None, 200, {}) | |
| (tmp_path / "step_0000300.tmp").write_bytes(b"partial") | |
| save_checkpoint(tmp_path / "best.pt", m, None, None, 150, {}) | |
| assert latest_checkpoint(tmp_path) == checkpoint_path(tmp_path, 200) | |
| def test_prune_keeps_last_two_and_best(tmp_path): | |
| m = _model() | |
| for s in (100, 200, 300, 400): | |
| save_checkpoint(checkpoint_path(tmp_path, s), m, None, None, s, {}) | |
| save_checkpoint(tmp_path / "best.pt", m, None, None, 100, {}) | |
| prune_checkpoints(tmp_path, keep_last=2) | |
| assert sorted(p.name for p in tmp_path.glob("*.pt")) == ["best.pt", "step_0000300.pt", "step_0000400.pt"] | |