File size: 13,006 Bytes
10979b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
"""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"]