torchdoctor 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- torchdoctor-0.1.0/LICENSE.txt +17 -0
- torchdoctor-0.1.0/PKG-INFO +53 -0
- torchdoctor-0.1.0/README.md +33 -0
- torchdoctor-0.1.0/pyproject.toml +29 -0
- torchdoctor-0.1.0/setup.cfg +4 -0
- torchdoctor-0.1.0/tests/test_activation_monitor.py +319 -0
- torchdoctor-0.1.0/tests/test_basic.py +2 -0
- torchdoctor-0.1.0/tests/test_datasets.py +137 -0
- torchdoctor-0.1.0/tests/test_html_report.py +508 -0
- torchdoctor-0.1.0/tests/test_html_report_browser.py +129 -0
- torchdoctor-0.1.0/tests/test_report.py +56 -0
- torchdoctor-0.1.0/torchdoctor/__init__.py +22 -0
- torchdoctor-0.1.0/torchdoctor/activations.py +102 -0
- torchdoctor-0.1.0/torchdoctor/core.py +156 -0
- torchdoctor-0.1.0/torchdoctor/datasets.py +223 -0
- torchdoctor-0.1.0/torchdoctor/doctor.py +143 -0
- torchdoctor-0.1.0/torchdoctor/gradients.py +157 -0
- torchdoctor-0.1.0/torchdoctor/losses.py +120 -0
- torchdoctor-0.1.0/torchdoctor/numerics.py +132 -0
- torchdoctor-0.1.0/torchdoctor/report.py +817 -0
- torchdoctor-0.1.0/torchdoctor/updates.py +99 -0
- torchdoctor-0.1.0/torchdoctor.egg-info/PKG-INFO +53 -0
- torchdoctor-0.1.0/torchdoctor.egg-info/SOURCES.txt +24 -0
- torchdoctor-0.1.0/torchdoctor.egg-info/dependency_links.txt +1 -0
- torchdoctor-0.1.0/torchdoctor.egg-info/requires.txt +1 -0
- torchdoctor-0.1.0/torchdoctor.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 YOUSSEF AMIN
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: torchdoctor
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Training diagnostics and health monitoring for PyTorch models
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Classifier: Development Status :: 3 - Alpha
|
|
7
|
+
Classifier: Intended Audience :: Developers
|
|
8
|
+
Classifier: Intended Audience :: Science/Research
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE.txt
|
|
18
|
+
Requires-Dist: torch
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# TorchDoctor
|
|
22
|
+
|
|
23
|
+
**Training diagnostics and health monitoring for PyTorch models.**
|
|
24
|
+
|
|
25
|
+
TorchDoctor is a diagnostic toolkit for identifying training problems and dataset issues.
|
|
26
|
+
|
|
27
|
+
## Features
|
|
28
|
+
|
|
29
|
+
### Model diagnostics
|
|
30
|
+
- Activation monitoring
|
|
31
|
+
- Gradient health checks
|
|
32
|
+
- Weight update monitoring
|
|
33
|
+
- Training and validation loss monitoring
|
|
34
|
+
- Numerical stability checks
|
|
35
|
+
- Automatic optimizer-step tracking
|
|
36
|
+
|
|
37
|
+
### Dataset diagnostics
|
|
38
|
+
- Duplicate sample detection
|
|
39
|
+
- Class imbalance detection
|
|
40
|
+
- Invalid label detection
|
|
41
|
+
- Train/validation leakage detection
|
|
42
|
+
|
|
43
|
+
### Reporting
|
|
44
|
+
- Structured diagnostic findings
|
|
45
|
+
- INFO, WARNING, and CRITICAL severity levels
|
|
46
|
+
- Plain-text reports
|
|
47
|
+
- Interactive HTML reports
|
|
48
|
+
- Evidence and suggested corrective actions
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install torchdoctor
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# TorchDoctor
|
|
2
|
+
|
|
3
|
+
**Training diagnostics and health monitoring for PyTorch models.**
|
|
4
|
+
|
|
5
|
+
TorchDoctor is a diagnostic toolkit for identifying training problems and dataset issues.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
### Model diagnostics
|
|
10
|
+
- Activation monitoring
|
|
11
|
+
- Gradient health checks
|
|
12
|
+
- Weight update monitoring
|
|
13
|
+
- Training and validation loss monitoring
|
|
14
|
+
- Numerical stability checks
|
|
15
|
+
- Automatic optimizer-step tracking
|
|
16
|
+
|
|
17
|
+
### Dataset diagnostics
|
|
18
|
+
- Duplicate sample detection
|
|
19
|
+
- Class imbalance detection
|
|
20
|
+
- Invalid label detection
|
|
21
|
+
- Train/validation leakage detection
|
|
22
|
+
|
|
23
|
+
### Reporting
|
|
24
|
+
- Structured diagnostic findings
|
|
25
|
+
- INFO, WARNING, and CRITICAL severity levels
|
|
26
|
+
- Plain-text reports
|
|
27
|
+
- Interactive HTML reports
|
|
28
|
+
- Evidence and suggested corrective actions
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install torchdoctor
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "torchdoctor"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Training diagnostics and health monitoring for PyTorch models"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"torch",
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 3 - Alpha",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"Operating System :: OS Independent",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.packages.find]
|
|
28
|
+
include = ["torchdoctor*"]
|
|
29
|
+
exclude = ["tests*", "data*"]
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import torch
|
|
3
|
+
import torch.nn as nn
|
|
4
|
+
|
|
5
|
+
from torchdoctor import ActivationMonitor
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# ---------------- helpers ----------------
|
|
9
|
+
def make_mlp(bias, activation=nn.ReLU):
|
|
10
|
+
"""Linear (weights zero) + activation. Each channel's output is a constant: its bias."""
|
|
11
|
+
layer = nn.Linear(4, len(bias))
|
|
12
|
+
with torch.no_grad():
|
|
13
|
+
layer.weight.zero_()
|
|
14
|
+
layer.bias.copy_(torch.tensor(bias))
|
|
15
|
+
return nn.Sequential(layer, activation())
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def run(model, mon, shape=(8, 4), n=3):
|
|
19
|
+
model.train()
|
|
20
|
+
for _ in range(n):
|
|
21
|
+
model(torch.randn(*shape))
|
|
22
|
+
mon.step()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def watched(mon):
|
|
26
|
+
return {name for name, records in mon.history.items() if records}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def total_records(mon):
|
|
30
|
+
return sum(len(records) for records in mon.history.values())
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---------------- recording basics ----------------
|
|
34
|
+
def test_one_record_per_watched_layer_per_pass():
|
|
35
|
+
model = nn.Sequential(nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 3), nn.ReLU())
|
|
36
|
+
mon = ActivationMonitor(model)
|
|
37
|
+
mon.attach()
|
|
38
|
+
model(torch.randn(8, 4))
|
|
39
|
+
assert watched(mon) == {"1", "3"}
|
|
40
|
+
assert len(mon.history["1"]) == 1 and len(mon.history["3"]) == 1
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_record_contents():
|
|
44
|
+
model = make_mlp([-1.0, 1.0, 1.0]) # ReLU output per row: [0, 1, 1]
|
|
45
|
+
mon = ActivationMonitor(model)
|
|
46
|
+
mon.attach()
|
|
47
|
+
model(torch.randn(8, 4))
|
|
48
|
+
rec = mon.history["1"][0]
|
|
49
|
+
assert set(rec) == {"step", "zero_rate", "mean", "finite"}
|
|
50
|
+
assert rec["step"] == 0
|
|
51
|
+
assert rec["zero_rate"] == pytest.approx(1 / 3)
|
|
52
|
+
assert rec["mean"] == pytest.approx(2 / 3)
|
|
53
|
+
assert rec["finite"] is True
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def test_eval_passes_are_ignored():
|
|
57
|
+
model = make_mlp([-1.0, 1.0, 1.0])
|
|
58
|
+
mon = ActivationMonitor(model)
|
|
59
|
+
mon.attach()
|
|
60
|
+
model.eval()
|
|
61
|
+
model(torch.randn(8, 4))
|
|
62
|
+
assert total_records(mon) == 0
|
|
63
|
+
model.train()
|
|
64
|
+
model(torch.randn(8, 4))
|
|
65
|
+
assert total_records(mon) == 1
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---------------- cleanup ----------------
|
|
69
|
+
def test_remove_stops_recording():
|
|
70
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
71
|
+
mon = ActivationMonitor(model)
|
|
72
|
+
mon.attach()
|
|
73
|
+
model(torch.randn(8, 4))
|
|
74
|
+
mon.remove()
|
|
75
|
+
model(torch.randn(8, 4))
|
|
76
|
+
assert len(mon.history["1"]) == 1
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_remove_leaves_no_hooks_on_modules():
|
|
80
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
81
|
+
mon = ActivationMonitor(model)
|
|
82
|
+
mon.attach()
|
|
83
|
+
mon.remove()
|
|
84
|
+
# internal check: relies on PyTorch's private _forward_hooks attribute
|
|
85
|
+
assert all(len(m._forward_hooks) == 0 for m in model.modules())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_remove_is_idempotent():
|
|
89
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
90
|
+
mon = ActivationMonitor(model)
|
|
91
|
+
mon.remove() # before attach
|
|
92
|
+
mon.attach()
|
|
93
|
+
mon.remove()
|
|
94
|
+
mon.remove() # twice
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def test_attach_is_idempotent():
|
|
98
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
99
|
+
mon = ActivationMonitor(model)
|
|
100
|
+
mon.attach()
|
|
101
|
+
mon.attach()
|
|
102
|
+
model(torch.randn(8, 4))
|
|
103
|
+
assert len(mon.history["1"]) == 1 # not 2
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def test_context_manager_removes_hooks_on_exit():
|
|
107
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
108
|
+
with ActivationMonitor(model) as mon:
|
|
109
|
+
model(torch.randn(8, 4))
|
|
110
|
+
model(torch.randn(8, 4))
|
|
111
|
+
assert len(mon.history["1"]) == 1
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def test_context_manager_removes_hooks_on_exception():
|
|
115
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
116
|
+
with pytest.raises(RuntimeError):
|
|
117
|
+
with ActivationMonitor(model):
|
|
118
|
+
raise RuntimeError("boom")
|
|
119
|
+
assert all(len(m._forward_hooks) == 0 for m in model.modules())
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------- independence ----------------
|
|
123
|
+
def test_two_monitors_have_independent_state():
|
|
124
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
125
|
+
a = ActivationMonitor(model)
|
|
126
|
+
b = ActivationMonitor(model, every=2)
|
|
127
|
+
a.attach()
|
|
128
|
+
b.attach()
|
|
129
|
+
for _ in range(4):
|
|
130
|
+
model(torch.randn(8, 4))
|
|
131
|
+
a.step()
|
|
132
|
+
b.step()
|
|
133
|
+
assert len(a.history["1"]) == 4
|
|
134
|
+
assert len(b.history["1"]) == 2 # steps 0 and 2
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def test_removing_one_monitor_keeps_the_other_working():
|
|
138
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
139
|
+
a = ActivationMonitor(model)
|
|
140
|
+
b = ActivationMonitor(model)
|
|
141
|
+
a.attach()
|
|
142
|
+
b.attach()
|
|
143
|
+
model(torch.randn(8, 4))
|
|
144
|
+
a.remove()
|
|
145
|
+
model(torch.randn(8, 4))
|
|
146
|
+
assert len(a.history["1"]) == 1
|
|
147
|
+
assert len(b.history["1"]) == 2
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# ---------------- safety ----------------
|
|
151
|
+
def test_monitor_does_not_change_model_output():
|
|
152
|
+
torch.manual_seed(0)
|
|
153
|
+
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 2))
|
|
154
|
+
x = torch.randn(5, 4)
|
|
155
|
+
expected = model(x)
|
|
156
|
+
with ActivationMonitor(model):
|
|
157
|
+
observed = model(x)
|
|
158
|
+
assert torch.equal(expected, observed)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def test_training_still_works_with_monitor_attached():
|
|
162
|
+
model = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
|
|
163
|
+
opt = torch.optim.SGD(model.parameters(), lr=0.1)
|
|
164
|
+
with ActivationMonitor(model) as mon:
|
|
165
|
+
for _ in range(3):
|
|
166
|
+
opt.zero_grad()
|
|
167
|
+
loss = model(torch.randn(8, 4)).pow(2).mean()
|
|
168
|
+
loss.backward()
|
|
169
|
+
opt.step()
|
|
170
|
+
mon.step()
|
|
171
|
+
assert all(p.grad is not None for p in model.parameters())
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def test_history_contains_no_tensors():
|
|
175
|
+
model = make_mlp([-1.0, 1.0, 1.0])
|
|
176
|
+
mon = ActivationMonitor(model)
|
|
177
|
+
mon.attach()
|
|
178
|
+
run(model, mon, n=2)
|
|
179
|
+
for records in mon.history.values():
|
|
180
|
+
for rec in records:
|
|
181
|
+
assert not any(isinstance(v, torch.Tensor) for v in rec.values())
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def test_non_tensor_output_is_skipped():
|
|
185
|
+
class LSTMNet(nn.Module):
|
|
186
|
+
def __init__(self):
|
|
187
|
+
super().__init__()
|
|
188
|
+
self.lstm = nn.LSTM(4, 3, batch_first=True)
|
|
189
|
+
|
|
190
|
+
def forward(self, x):
|
|
191
|
+
return self.lstm(x)[0]
|
|
192
|
+
|
|
193
|
+
model = LSTMNet()
|
|
194
|
+
mon = ActivationMonitor(model, layer_types=(nn.LSTM,))
|
|
195
|
+
mon.attach()
|
|
196
|
+
model(torch.randn(2, 5, 4)) # LSTM returns a tuple: must not crash
|
|
197
|
+
assert total_records(mon) == 0
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ---------------- scope and limits ----------------
|
|
201
|
+
def test_functional_relu_is_not_observed():
|
|
202
|
+
class FunctionalNet(nn.Module):
|
|
203
|
+
def __init__(self):
|
|
204
|
+
super().__init__()
|
|
205
|
+
self.fc = nn.Linear(4, 3)
|
|
206
|
+
|
|
207
|
+
def forward(self, x):
|
|
208
|
+
return torch.relu(self.fc(x))
|
|
209
|
+
|
|
210
|
+
model = FunctionalNet()
|
|
211
|
+
mon = ActivationMonitor(model)
|
|
212
|
+
mon.attach()
|
|
213
|
+
model(torch.randn(8, 4))
|
|
214
|
+
assert total_records(mon) == 0 # documented limitation
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def test_layer_types_restricts_watched_layers():
|
|
218
|
+
model = nn.Sequential(nn.Linear(4, 3), nn.ReLU(), nn.Linear(3, 3), nn.GELU())
|
|
219
|
+
mon = ActivationMonitor(model, layer_types=(nn.GELU,))
|
|
220
|
+
mon.attach()
|
|
221
|
+
model(torch.randn(8, 4))
|
|
222
|
+
assert watched(mon) == {"3"}
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
# ---------------- sampling and memory ----------------
|
|
226
|
+
def test_every_n_steps_samples_correctly():
|
|
227
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
228
|
+
mon = ActivationMonitor(model, every=3)
|
|
229
|
+
mon.attach()
|
|
230
|
+
run(model, mon, n=9)
|
|
231
|
+
assert [r["step"] for r in mon.history["1"]] == [0, 3, 6]
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def test_max_history_bounds_memory_but_counts_everything():
|
|
235
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
236
|
+
mon = ActivationMonitor(model, max_history=5)
|
|
237
|
+
mon.attach()
|
|
238
|
+
run(model, mon, n=20)
|
|
239
|
+
assert [r["step"] for r in mon.history["1"]] == list(range(15, 20))
|
|
240
|
+
assert mon.observations["1"] == 20
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# ---------------- diagnostics ----------------
|
|
244
|
+
def test_nan_is_flagged():
|
|
245
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
246
|
+
mon = ActivationMonitor(model)
|
|
247
|
+
mon.attach()
|
|
248
|
+
model(torch.full((2, 4), float("nan")))
|
|
249
|
+
assert mon.history["1"][0]["finite"] is False
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def test_dead_channel_is_detected():
|
|
253
|
+
model = make_mlp([-1.0, 1.0, 1.0])
|
|
254
|
+
mon = ActivationMonitor(model)
|
|
255
|
+
mon.attach()
|
|
256
|
+
run(model, mon, n=3)
|
|
257
|
+
assert mon.inactive_channels(min_observations=3) == {"1": [0]}
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def test_healthy_model_has_no_inactive_channels():
|
|
261
|
+
model = make_mlp([1.0, 1.0, 1.0])
|
|
262
|
+
mon = ActivationMonitor(model)
|
|
263
|
+
mon.attach()
|
|
264
|
+
run(model, mon, n=3)
|
|
265
|
+
assert mon.inactive_channels(min_observations=3) == {"1": []}
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def test_inactive_channels_needs_min_observations():
|
|
269
|
+
model = make_mlp([-1.0, 1.0, 1.0])
|
|
270
|
+
mon = ActivationMonitor(model)
|
|
271
|
+
mon.attach()
|
|
272
|
+
run(model, mon, n=2)
|
|
273
|
+
assert "1" not in mon.inactive_channels(min_observations=3)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def test_channel_active_even_once_is_not_inactive():
|
|
277
|
+
model = make_mlp([-1.0, 1.0, 1.0])
|
|
278
|
+
mon = ActivationMonitor(model)
|
|
279
|
+
mon.attach()
|
|
280
|
+
run(model, mon, n=2)
|
|
281
|
+
with torch.no_grad():
|
|
282
|
+
model[0].bias.copy_(torch.tensor([1.0, 1.0, 1.0])) # channel 0 comes alive
|
|
283
|
+
run(model, mon, n=1)
|
|
284
|
+
assert mon.inactive_channels(min_observations=3) == {"1": []}
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def test_conv_channels_are_detected_in_4d_outputs():
|
|
288
|
+
conv = nn.Conv2d(1, 3, 3)
|
|
289
|
+
with torch.no_grad():
|
|
290
|
+
conv.weight.zero_()
|
|
291
|
+
conv.bias.copy_(torch.tensor([-100.0, 1.0, 1.0]))
|
|
292
|
+
model = nn.Sequential(conv, nn.ReLU())
|
|
293
|
+
mon = ActivationMonitor(model)
|
|
294
|
+
mon.attach()
|
|
295
|
+
run(model, mon, shape=(4, 1, 8, 8), n=3)
|
|
296
|
+
assert mon.inactive_channels(min_observations=3) == {"1": [0]}
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def test_gelu_uses_near_zero_threshold():
|
|
300
|
+
model = make_mlp([-10.0, 1.0, 1.0], activation=nn.GELU) # GELU(-10) is about -7.6e-23
|
|
301
|
+
mon = ActivationMonitor(model)
|
|
302
|
+
mon.attach()
|
|
303
|
+
run(model, mon, n=3)
|
|
304
|
+
assert mon.inactive_channels(min_observations=3) == {"1": [0]}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def test_leaky_relu_respects_zero_tol():
|
|
308
|
+
# LeakyReLU(-1) = -0.01, which is not "inactive" at the default tolerance
|
|
309
|
+
strict = make_mlp([-1.0, 1.0, 1.0], activation=nn.LeakyReLU)
|
|
310
|
+
mon_strict = ActivationMonitor(strict)
|
|
311
|
+
mon_strict.attach()
|
|
312
|
+
run(strict, mon_strict, n=3)
|
|
313
|
+
assert mon_strict.inactive_channels(min_observations=3) == {"1": []}
|
|
314
|
+
|
|
315
|
+
loose = make_mlp([-1.0, 1.0, 1.0], activation=nn.LeakyReLU)
|
|
316
|
+
mon_loose = ActivationMonitor(loose, zero_tol=0.05)
|
|
317
|
+
mon_loose.attach()
|
|
318
|
+
run(loose, mon_loose, n=3)
|
|
319
|
+
assert mon_loose.inactive_channels(min_observations=3) == {"1": [0]}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
from torchdoctor.core import Severity
|
|
5
|
+
from torchdoctor.datasets import DatasetAnalyzer
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_duplicate_samples_detected():
|
|
9
|
+
analyzer = DatasetAnalyzer(
|
|
10
|
+
samples=["img1", "img2", "img1", "img3", "img2"]
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
findings = analyzer.findings()
|
|
14
|
+
|
|
15
|
+
assert len(findings) == 1
|
|
16
|
+
assert findings[0].code == "duplicate_samples"
|
|
17
|
+
assert findings[0].evidence["unique_duplicated_samples"] == 2
|
|
18
|
+
assert findings[0].evidence["extra_occurrences"] == 2
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_no_duplicates():
|
|
22
|
+
analyzer = DatasetAnalyzer(
|
|
23
|
+
samples=["img1", "img2", "img3"]
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
assert analyzer.findings() == []
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_class_imbalance_detected():
|
|
30
|
+
analyzer = DatasetAnalyzer(
|
|
31
|
+
labels=["cat"] * 90 + ["dog"] * 10
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
findings = analyzer.findings()
|
|
35
|
+
|
|
36
|
+
imbalance = next(
|
|
37
|
+
f for f in findings if f.code == "class_imbalance"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
assert imbalance.severity == Severity.WARNING
|
|
41
|
+
assert imbalance.evidence["imbalance_ratio"] == 9.0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def test_balanced_classes():
|
|
45
|
+
analyzer = DatasetAnalyzer(
|
|
46
|
+
labels=["cat"] * 50 + ["dog"] * 50
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
assert analyzer.findings() == []
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_invalid_labels_detected():
|
|
53
|
+
analyzer = DatasetAnalyzer(
|
|
54
|
+
labels=["cat", "dog", None, "bird"],
|
|
55
|
+
allowed_labels=["cat", "dog"],
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
findings = analyzer.findings()
|
|
59
|
+
|
|
60
|
+
invalid = next(
|
|
61
|
+
f for f in findings if f.code == "invalid_labels"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
assert invalid.severity == Severity.CRITICAL
|
|
65
|
+
assert invalid.evidence["invalid_count"] == 2
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_data_leakage_detected():
|
|
69
|
+
analyzer = DatasetAnalyzer(
|
|
70
|
+
train_samples=["img1", "img2", "img3"],
|
|
71
|
+
val_samples=["img3", "img4"],
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
findings = analyzer.findings()
|
|
75
|
+
|
|
76
|
+
leakage = next(
|
|
77
|
+
f for f in findings if f.code == "data_leakage"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
assert leakage.severity == Severity.CRITICAL
|
|
81
|
+
assert leakage.evidence["overlapping_samples"] == 1
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_no_data_leakage():
|
|
85
|
+
analyzer = DatasetAnalyzer(
|
|
86
|
+
train_samples=["img1", "img2"],
|
|
87
|
+
val_samples=["img3", "img4"],
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
assert analyzer.findings() == []
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def test_mismatched_sample_and_label_lengths():
|
|
94
|
+
with pytest.raises(ValueError):
|
|
95
|
+
DatasetAnalyzer(
|
|
96
|
+
samples=["img1", "img2"],
|
|
97
|
+
labels=["cat"],
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_invalid_imbalance_threshold():
|
|
102
|
+
with pytest.raises(ValueError):
|
|
103
|
+
DatasetAnalyzer(imbalance_threshold=1.0)
|
|
104
|
+
|
|
105
|
+
def test_single_class_dataset_detected():
|
|
106
|
+
analyzer = DatasetAnalyzer(
|
|
107
|
+
labels=["cat", "cat", "cat", "cat"]
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
findings = analyzer.findings()
|
|
111
|
+
|
|
112
|
+
single_class = next(
|
|
113
|
+
f for f in findings if f.code == "single_class_dataset"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
assert single_class.severity == Severity.CRITICAL
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_duplicate_tensors_detected():
|
|
120
|
+
import torch
|
|
121
|
+
|
|
122
|
+
first = torch.tensor([1.0, 2.0, 3.0])
|
|
123
|
+
second = torch.tensor([1.0, 2.0, 3.0])
|
|
124
|
+
third = torch.tensor([4.0, 5.0, 6.0])
|
|
125
|
+
|
|
126
|
+
analyzer = DatasetAnalyzer(
|
|
127
|
+
samples=[first, second, third]
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
findings = analyzer.findings()
|
|
131
|
+
|
|
132
|
+
duplicate = next(
|
|
133
|
+
f for f in findings if f.code == "duplicate_samples"
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
assert duplicate.evidence["unique_duplicated_samples"] == 1
|
|
137
|
+
assert duplicate.evidence["extra_occurrences"] == 1
|