Download gmnet/code/journal_exp/tests/test_analysis.py from YFanwang/Backup: direct link, hf CLI and curl.
- Browser
- Download file 5.63 kB
-
https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/tests/test_analysis.py
- Command line
-
hf download hf://datasets/YFanwang/Backup/gmnet/code/journal_exp/tests/test_analysis.py
-
curl -L -o test_analysis.py https://huggingface.co/datasets/YFanwang/Backup/resolve/main/gmnet/code/journal_exp/tests/test_analysis.py
5.63 kB
| 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() | |