File size: 5,628 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
from __future__ import annotations

import json
import tempfile
import unittest
from pathlib import Path

import torch
from torch import nn

from gmnet.analysis.aggregation import aggregate_e4, aggregate_e12
from gmnet.analysis.interventions import InterventionSelfGate
from gmnet.analysis.profiling import percentile


class InterventionGateTests(unittest.TestCase):
    def test_stop_gradient_preserves_forward_and_changes_gradient(self) -> None:
        baseline = InterventionSelfGate(nn.ReLU6(), seed=7)
        stopped = InterventionSelfGate(nn.ReLU6(), seed=7)
        stopped.set_mode("stop_gradient")
        x_baseline = torch.tensor([-1.0, 2.0, 7.0], requires_grad=True)
        x_stopped = x_baseline.detach().clone().requires_grad_(True)

        y_baseline = baseline(x_baseline)
        y_stopped = stopped(x_stopped)
        torch.testing.assert_close(y_baseline, y_stopped)
        y_baseline.sum().backward()
        y_stopped.sum().backward()
        self.assertFalse(torch.equal(x_baseline.grad, x_stopped.grad))

    def test_shuffle_modes_are_deterministic_and_shape_preserving(self) -> None:
        x = torch.arange(2 * 4 * 3 * 3, dtype=torch.float32).view(2, 4, 3, 3)
        for mode in ("batch_shuffle", "spatial_shuffle", "channel_shuffle"):
            first = InterventionSelfGate(nn.ReLU6(), seed=19)
            second = InterventionSelfGate(nn.ReLU6(), seed=19)
            first.set_mode(mode)
            second.set_mode(mode)
            first_output = first(x)
            second_output = second(x)
            self.assertEqual(first_output.shape, x.shape)
            torch.testing.assert_close(first_output, second_output)

    def test_mean_gate_is_shape_preserving(self) -> None:
        gate = InterventionSelfGate(nn.ReLU6(), seed=3)
        gate.set_mode("mean_gate")
        x = torch.randn(3, 4, 5, 5)
        self.assertEqual(gate(x).shape, x.shape)


class ProfilingTests(unittest.TestCase):
    def test_percentile_interpolates(self) -> None:
        self.assertEqual(percentile([1.0, 2.0, 3.0], 0.5), 2.0)
        self.assertAlmostEqual(percentile([1.0, 3.0], 0.25), 1.5)


class AggregationTests(unittest.TestCase):
    def _write_json(self, directory: Path, name: str, value: dict) -> Path:
        path = directory / name
        path.write_text(json.dumps(value), encoding="utf-8")
        return path

    def test_e4_aggregates_full_validation_seed_results(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            paths = []
            for seed, top1 in enumerate((70.0, 72.0, 74.0)):
                metrics = {
                    "top1_percent": top1,
                    "top5_percent": 90.0,
                    "nll": 1.0,
                    "ece_percent": 2.0,
                    "prediction_agreement_with_baseline_percent": 100.0,
                    "mean_kl_from_baseline": 0.0,
                    "logit_rmse_from_baseline": 0.0,
                }
                paths.append(
                    self._write_json(
                        root,
                        f"seed{seed}.json",
                        {
                            "checkpoint": {
                                "seed": seed,
                                "sha256": f"sha{seed}",
                            },
                            "data": {
                                "evaluated_samples": 10_000,
                                "full_validation_samples": 10_000,
                            },
                            "interventions": {"baseline": metrics},
                            "claim_scope": "frozen diagnostic",
                        },
                    )
                )
            result = aggregate_e4(paths)
            top1 = result["interventions"]["baseline"]["top1_percent"]
            self.assertEqual(top1["mean"], 72.0)
            self.assertEqual(top1["sample_std"], 2.0)
            self.assertEqual(result["seeds"], [0, 1, 2])

    def test_e12_requires_and_aggregates_five_processes(self) -> None:
        with tempfile.TemporaryDirectory() as temporary_directory:
            root = Path(temporary_directory)
            paths = []
            for process in range(5):
                measurement = {
                    "device": "cuda:0",
                    "precision": "fp32",
                    "batch_size": 1,
                    "latency_mean_ms": 1.0 + process,
                    "latency_p50_ms": 1.0 + process,
                    "latency_p95_ms": 2.0 + process,
                    "throughput_mean_images_per_second": 100.0 - process,
                    "throughput_at_p50_images_per_second": 100.0 - process,
                    "peak_cuda_memory_mb": 200.0,
                }
                paths.append(
                    self._write_json(
                        root,
                        f"process{process}.json",
                        {
                            "status": "completed",
                            "checkpoint": {"sha256": "same-checkpoint"},
                            "measurements": [measurement],
                            "int8": {"status": "blocked"},
                        },
                    )
                )
            result = aggregate_e12(paths)
            self.assertEqual(result["process_count"], 5)
            latency = result["configurations"][0]["metrics"][
                "latency_p50_ms"
            ]
            self.assertEqual(latency["count"], 5)
            self.assertEqual(latency["mean"], 3.0)


if __name__ == "__main__":
    unittest.main()