Download gmnet/code/journal_exp/tests/test_training_audit.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/tests/test_training_audit.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/tests/test_training_audit.py
-
curl -L -o test_training_audit.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/tests/test_training_audit.py
13 kB
| """Regression tests for long-run training audit safeguards.""" | |
| from __future__ import annotations | |
| import random | |
| from unittest import mock | |
| import numpy as np | |
| import pytest | |
| import torch | |
| from torch import nn | |
| from gmnet.data.build import _build_manifest, _validate_expected_samples | |
| from gmnet.engine import state_dict_schema_sha256 | |
| from gmnet.models import SmoothClippedSelfGate | |
| from gmnet.train import ( | |
| capture_rng_state, | |
| checkpoint_path_for_progress, | |
| collect_rng_states, | |
| fail_if_nonfinite, | |
| parameter_groups, | |
| make_scheduler, | |
| reduce_batchnorm_statistics, | |
| restore_rng_state, | |
| should_evaluate_epoch, | |
| smooth_clip_diagnostics, | |
| stable_config_fingerprint, | |
| validate_resume_checkpoint, | |
| validate_resume_data_manifest, | |
| validate_resume_training_progress, | |
| ) | |
| class _Parameters(nn.Module): | |
| def __init__(self) -> None: | |
| super().__init__() | |
| self.weight = nn.Parameter(torch.ones(2, 2)) | |
| self.raw_clip = nn.Parameter(torch.ones(1, 2, 1, 1)) | |
| self.bias = nn.Parameter(torch.ones(2)) | |
| def test_raw_clip_pattern_disables_weight_decay() -> None: | |
| model = _Parameters() | |
| groups = parameter_groups(model, 0.03, ["raw_clip"]) | |
| assert [id(value) for value in groups[0]["params"]] == [id(model.weight)] | |
| assert {id(value) for value in groups[1]["params"]} == { | |
| id(model.raw_clip), | |
| id(model.bias), | |
| } | |
| assert groups[1]["weight_decay"] == 0.0 | |
| def test_no_weight_decay_pattern_supports_glob() -> None: | |
| model = nn.Sequential(_Parameters()) | |
| groups = parameter_groups(model, 0.03, ["*.raw_clip"]) | |
| assert id(model[0].raw_clip) in {id(value) for value in groups[1]["params"]} | |
| def test_config_fingerprint_is_stable_and_sensitive() -> None: | |
| first = {"train": {"epochs": 300}, "seed": 1} | |
| reordered = {"seed": 1, "train": {"epochs": 300}} | |
| changed = {"seed": 2, "train": {"epochs": 300}} | |
| assert stable_config_fingerprint(first) == stable_config_fingerprint(reordered) | |
| assert stable_config_fingerprint(first) != stable_config_fingerprint(changed) | |
| def test_strict_resume_checks_all_experiment_identity_fields() -> None: | |
| checkpoint = { | |
| "config_fingerprint": "abc", | |
| "run_name": "run", | |
| "seed": 7, | |
| "world_size": 8, | |
| "epoch_complete": True, | |
| "rng_state_by_rank": [{} for _ in range(8)], | |
| } | |
| validate_resume_checkpoint( | |
| checkpoint, config_fingerprint="abc", run_name="run", seed=7, world_size=8 | |
| ) | |
| with pytest.raises(ValueError, match="config_fingerprint.*run_name.*seed.*world_size"): | |
| validate_resume_checkpoint( | |
| checkpoint, | |
| config_fingerprint="different", | |
| run_name="other", | |
| seed=8, | |
| world_size=4, | |
| ) | |
| with pytest.raises(ValueError, match="missing config_fingerprint"): | |
| validate_resume_checkpoint( | |
| {}, config_fingerprint="abc", run_name="run", seed=7, world_size=8 | |
| ) | |
| def test_strict_resume_requires_a_complete_consistent_epoch() -> None: | |
| checkpoint = { | |
| "epoch": 2, | |
| "global_step": 30, | |
| "epoch_complete": True, | |
| "steps_in_epoch": 10, | |
| "expected_steps_per_epoch": 10, | |
| "training_complete": False, | |
| } | |
| validate_resume_training_progress( | |
| checkpoint, expected_steps_per_epoch=10, epochs=4 | |
| ) | |
| with pytest.raises(ValueError, match="steps_in_epoch.*global_step"): | |
| validate_resume_training_progress( | |
| {**checkpoint, "steps_in_epoch": 1, "global_step": 21}, | |
| expected_steps_per_epoch=10, | |
| epochs=4, | |
| ) | |
| def test_partial_epoch_uses_recovery_checkpoint_only(tmp_path) -> None: | |
| assert checkpoint_path_for_progress( | |
| tmp_path, epoch_complete=False | |
| ) == tmp_path / "checkpoint_recovery.pt" | |
| assert checkpoint_path_for_progress( | |
| tmp_path, epoch_complete=True | |
| ) == tmp_path / "checkpoint_last.pt" | |
| def test_state_schema_hash_tracks_names_shapes_and_dtypes() -> None: | |
| first = {"weight": torch.zeros(2, 3), "count": torch.zeros((), dtype=torch.int64)} | |
| same = {"weight": torch.ones(2, 3), "count": torch.ones((), dtype=torch.int64)} | |
| changed = {"weight": torch.ones(3, 2), "count": torch.ones((), dtype=torch.int64)} | |
| assert state_dict_schema_sha256(first) == state_dict_schema_sha256(same) | |
| assert state_dict_schema_sha256(first) != state_dict_schema_sha256(changed) | |
| def test_scheduler_supports_epoch_steps_and_cooldown() -> None: | |
| parameter = nn.Parameter(torch.ones(())) | |
| optimizer = torch.optim.SGD([parameter], lr=1.0) | |
| scheduler = make_scheduler( | |
| optimizer, | |
| epochs=6, | |
| steps_per_epoch=10, | |
| warmup_epochs=1, | |
| warmup_lr=0.1, | |
| base_lr=1.0, | |
| min_lr=0.01, | |
| step_unit="epoch", | |
| cooldown_epochs=2, | |
| ) | |
| observed = [optimizer.param_groups[0]["lr"]] | |
| for _ in range(6): | |
| optimizer.step() | |
| scheduler.step() | |
| observed.append(optimizer.param_groups[0]["lr"]) | |
| assert observed[0] == pytest.approx(0.1) | |
| assert observed[1] == pytest.approx(1.0) | |
| assert observed[4:] == pytest.approx([0.01, 0.01, 0.01]) | |
| def test_scheduler_rejects_invalid_protocol() -> None: | |
| optimizer = torch.optim.SGD([nn.Parameter(torch.ones(()))], lr=1.0) | |
| with pytest.raises(ValueError, match="step_unit"): | |
| make_scheduler( | |
| optimizer, | |
| epochs=2, | |
| steps_per_epoch=1, | |
| warmup_epochs=0, | |
| warmup_lr=0.0, | |
| base_lr=1.0, | |
| min_lr=0.0, | |
| step_unit="batch", | |
| ) | |
| def test_strict_resume_checks_data_manifest() -> None: | |
| manifest = {"manifest_sha256": "same"} | |
| validate_resume_data_manifest({"data_manifest": manifest}, manifest) | |
| with pytest.raises(ValueError, match="data manifest changed"): | |
| validate_resume_data_manifest( | |
| {"data_manifest": {"manifest_sha256": "old"}}, manifest | |
| ) | |
| def test_rank_local_rng_state_round_trip() -> None: | |
| generator = torch.Generator().manual_seed(41) | |
| random.seed(11) | |
| np.random.seed(21) | |
| torch.manual_seed(31) | |
| with mock.patch("gmnet.train.torch.cuda.is_available", return_value=False): | |
| state = capture_rng_state(generator) | |
| expected = ( | |
| random.random(), | |
| float(np.random.random()), | |
| float(torch.rand(())), | |
| float(torch.rand((), generator=generator)), | |
| ) | |
| random.random() | |
| np.random.random() | |
| torch.rand(()) | |
| torch.rand((), generator=generator) | |
| restore_rng_state( | |
| {"rng_state_by_rank": [state]}, | |
| rank=0, | |
| world_size=1, | |
| generator=generator, | |
| ) | |
| actual = ( | |
| random.random(), | |
| float(np.random.random()), | |
| float(torch.rand(())), | |
| float(torch.rand((), generator=generator)), | |
| ) | |
| assert actual == pytest.approx(expected) | |
| def test_rng_collection_keeps_one_state_per_rank() -> None: | |
| local = {"rank": 0} | |
| def gather(output: list[object], value: object) -> None: | |
| assert value is local | |
| output[:] = [value, {"rank": 1}] | |
| with ( | |
| mock.patch("gmnet.train.capture_rng_state", return_value=local), | |
| mock.patch("gmnet.train.dist.all_gather_object", side_effect=gather), | |
| ): | |
| states = collect_rng_states( | |
| torch.Generator(), distributed=True, world_size=2 | |
| ) | |
| assert states == [{"rank": 0}, {"rank": 1}] | |
| def test_rng_restore_rejects_wrong_world_size_or_schema() -> None: | |
| with pytest.raises(ValueError, match="exactly 2 entries"): | |
| restore_rng_state( | |
| {"rng_state_by_rank": [{}]}, | |
| rank=0, | |
| world_size=2, | |
| generator=torch.Generator(), | |
| ) | |
| with pytest.raises(ValueError, match="rank-local RNG state schema"): | |
| restore_rng_state( | |
| {"rng_state_by_rank": [{}]}, | |
| rank=0, | |
| world_size=1, | |
| generator=torch.Generator(), | |
| ) | |
| def test_eval_interval_always_evaluates_final_or_stopped_epoch() -> None: | |
| assert not should_evaluate_epoch( | |
| epoch=0, epochs=12, eval_interval=5, stop_after_epoch=False | |
| ) | |
| assert should_evaluate_epoch( | |
| epoch=4, epochs=12, eval_interval=5, stop_after_epoch=False | |
| ) | |
| assert should_evaluate_epoch( | |
| epoch=11, epochs=12, eval_interval=5, stop_after_epoch=False | |
| ) | |
| assert should_evaluate_epoch( | |
| epoch=2, epochs=12, eval_interval=5, stop_after_epoch=True | |
| ) | |
| with pytest.raises(ValueError, match="positive"): | |
| should_evaluate_epoch( | |
| epoch=0, epochs=1, eval_interval=0, stop_after_epoch=False | |
| ) | |
| def test_nonfinite_guard_rejects_nonfinite_gradient() -> None: | |
| model = nn.Linear(2, 1) | |
| loss = model(torch.ones(1, 2)).sum() | |
| loss.backward() | |
| fail_if_nonfinite(loss, model, epoch=1, step=2) | |
| model.weight.grad[0, 0] = torch.inf | |
| with pytest.raises(FloatingPointError, match="weight"): | |
| fail_if_nonfinite(loss, model, epoch=1, step=2) | |
| def test_bn_reduction_averages_running_statistics() -> None: | |
| model = nn.BatchNorm1d(2) | |
| model.running_mean.copy_(torch.tensor([2.0, 4.0])) | |
| model.running_var.copy_(torch.tensor([6.0, 8.0])) | |
| def double(tensor: torch.Tensor, **_: object) -> None: | |
| tensor.mul_(2) | |
| with mock.patch("gmnet.train.dist.all_reduce", side_effect=double) as reduce: | |
| reduce_batchnorm_statistics(model, world_size=2) | |
| assert reduce.call_count == 2 | |
| assert torch.equal(model.running_mean, torch.tensor([2.0, 4.0])) | |
| assert torch.equal(model.running_var, torch.tensor([6.0, 8.0])) | |
| def test_smooth_clip_diagnostics_include_stage_statistics() -> None: | |
| model = nn.Module() | |
| model.stages = nn.ModuleList( | |
| [ | |
| nn.Sequential(SmoothClippedSelfGate(2, init_clip=2.0)), | |
| nn.Sequential(SmoothClippedSelfGate(3, init_clip=3.0)), | |
| ] | |
| ) | |
| result = smooth_clip_diagnostics(model) | |
| assert result is not None | |
| assert result["module_count"] == 2 | |
| assert result["overall"]["count"] == 5 | |
| assert set(result["by_stage"]) == {"stage1", "stage2"} | |
| assert result["by_stage"]["stage1"]["count"] == 2 | |
| def test_expected_sample_counts_are_strict() -> None: | |
| _validate_expected_samples( | |
| {"expected_samples": {"train": 10, "val": 4}}, | |
| train_samples=10, | |
| val_samples=4, | |
| ) | |
| with pytest.raises(ValueError, match="train dataset has 10"): | |
| _validate_expected_samples( | |
| {"expected_train_samples": 11}, train_samples=10, val_samples=4 | |
| ) | |
| def test_imagefolder_manifest_is_root_independent(tmp_path) -> None: | |
| from PIL import Image | |
| from torchvision import datasets | |
| manifests = [] | |
| for root_name in ("first", "second"): | |
| root = tmp_path / root_name | |
| for split in ("train", "val"): | |
| directory = root / split / "class0" | |
| directory.mkdir(parents=True) | |
| Image.new("RGB", (2, 2), color="white").save(directory / "a.png") | |
| train = datasets.ImageFolder(root / "train") | |
| val = datasets.ImageFolder(root / "val") | |
| manifests.append( | |
| _build_manifest( | |
| dataset_name="imagefolder", | |
| train_split="train", | |
| val_split="val", | |
| train_dataset=train, | |
| val_dataset=val, | |
| train_root=root / "train", | |
| val_root=root / "val", | |
| class_to_idx=train.class_to_idx, | |
| ) | |
| ) | |
| assert manifests[0] == manifests[1] | |
| assert manifests[0]["schema_version"] == 2 | |
| assert manifests[0]["sampled_content_samples"] == {"train": 1, "val": 1} | |
| def test_imagefolder_manifest_detects_sampled_file_content_change(tmp_path) -> None: | |
| from PIL import Image | |
| from torchvision import datasets | |
| root = tmp_path / "data" | |
| for split in ("train", "val"): | |
| directory = root / split / "class0" | |
| directory.mkdir(parents=True) | |
| Image.new("RGB", (2, 2), color="white").save(directory / "a.png") | |
| def build() -> dict[str, object]: | |
| train = datasets.ImageFolder(root / "train") | |
| val = datasets.ImageFolder(root / "val") | |
| return _build_manifest( | |
| dataset_name="imagefolder", | |
| train_split="train", | |
| val_split="val", | |
| train_dataset=train, | |
| val_dataset=val, | |
| train_root=root / "train", | |
| val_root=root / "val", | |
| class_to_idx=train.class_to_idx, | |
| ) | |
| before = build() | |
| Image.new("RGB", (2, 2), color="black").save( | |
| root / "val" / "class0" / "a.png" | |
| ) | |
| after = build() | |
| assert before["sample_index_sha256"] == after["sample_index_sha256"] | |
| assert before["sampled_content_sha256"]["train"] == after[ | |
| "sampled_content_sha256" | |
| ]["train"] | |
| assert before["sampled_content_sha256"]["val"] != after[ | |
| "sampled_content_sha256" | |
| ]["val"] | |
| assert before["manifest_sha256"] != after["manifest_sha256"] | |