neuronlab 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.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: neuronlab
3
+ Version: 0.1.0
4
+ Summary: A small PyTorch tool for testing neuron ablation and visualizing its effect on model accuracy.
5
+ Keywords: pytorch,neural-network,interpretability,neuron-ablation,explainable-ai
6
+ Classifier: Development Status :: 3 - Alpha
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: torch>=2.0
13
+ Provides-Extra: demo
14
+ Requires-Dist: scikit-learn; extra == "demo"
15
+
16
+ # NeuronLab
17
+
18
+ NeuronLab is an experimental PyTorch utility for measuring the effect of temporarily zeroing units in one selected model layer.
19
+
20
+ ## Features
21
+
22
+ - Measure baseline accuracy on a labeled evaluation dataset.
23
+ - Temporarily zero one or more units in a selected layer.
24
+ - Scan units one at a time and rank them by accuracy change.
25
+ - Print a compact terminal report.
26
+ - Generate an offline interactive HTML visualization with precomputed ablation scores.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ python -m pip install neuronlab
32
+ ```
33
+
34
+ For the demo, install the optional dependency:
35
+
36
+ ```bash
37
+ python -m pip install "neuronlab[demo]"
38
+ ```
39
+
40
+ ## Quick start
41
+
42
+ ```python
43
+ import torch
44
+ from torch import nn
45
+ from neuronlab import Analyzer
46
+
47
+ model = nn.Sequential(
48
+ nn.Linear(2, 3),
49
+ nn.ReLU(),
50
+ nn.Linear(3, 2),
51
+ )
52
+
53
+ X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
54
+ y = torch.tensor([0, 1, 1, 1], dtype=torch.long)
55
+
56
+ analyzer = Analyzer(model, X, y, layer="1")
57
+ print(analyzer.evaluate())
58
+ print(analyzer.evaluate(remove=0))
59
+ print(analyzer.scan())
60
+ analyzer.report()
61
+ analyzer.visualize("neuronlab.html")
62
+ ```
63
+
64
+ ## Current limitations
65
+
66
+ - The selected layer must return a 2D tensor shaped `[batch, neurons]` and execute exactly once per model forward pass.
67
+ - The model must accept one input tensor and return multiclass logits shaped `[batch, classes]`.
68
+ - `X` and `y` must be PyTorch tensors on the model's device; `y` must contain class indices with dtype `torch.long`.
69
+ - Ablation temporarily sets selected activation values to zero. It does not delete model parameters or retrain the model.
70
+ - The HTML visualization precomputes all masks and currently supports layers with 1–10 units. It is not live inference in the browser.
71
+ - Results depend on the chosen dataset and intervention. Validate important findings on a separate holdout set.
72
+
73
+ ## Demo and tests
74
+
75
+ ```bash
76
+ python demo.py
77
+ python -m unittest discover -s tests -v
78
+ ```
79
+
80
+ This project is an early experimental release. APIs and behavior may change.
@@ -0,0 +1,65 @@
1
+ # NeuronLab
2
+
3
+ NeuronLab is an experimental PyTorch utility for measuring the effect of temporarily zeroing units in one selected model layer.
4
+
5
+ ## Features
6
+
7
+ - Measure baseline accuracy on a labeled evaluation dataset.
8
+ - Temporarily zero one or more units in a selected layer.
9
+ - Scan units one at a time and rank them by accuracy change.
10
+ - Print a compact terminal report.
11
+ - Generate an offline interactive HTML visualization with precomputed ablation scores.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ python -m pip install neuronlab
17
+ ```
18
+
19
+ For the demo, install the optional dependency:
20
+
21
+ ```bash
22
+ python -m pip install "neuronlab[demo]"
23
+ ```
24
+
25
+ ## Quick start
26
+
27
+ ```python
28
+ import torch
29
+ from torch import nn
30
+ from neuronlab import Analyzer
31
+
32
+ model = nn.Sequential(
33
+ nn.Linear(2, 3),
34
+ nn.ReLU(),
35
+ nn.Linear(3, 2),
36
+ )
37
+
38
+ X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
39
+ y = torch.tensor([0, 1, 1, 1], dtype=torch.long)
40
+
41
+ analyzer = Analyzer(model, X, y, layer="1")
42
+ print(analyzer.evaluate())
43
+ print(analyzer.evaluate(remove=0))
44
+ print(analyzer.scan())
45
+ analyzer.report()
46
+ analyzer.visualize("neuronlab.html")
47
+ ```
48
+
49
+ ## Current limitations
50
+
51
+ - The selected layer must return a 2D tensor shaped `[batch, neurons]` and execute exactly once per model forward pass.
52
+ - The model must accept one input tensor and return multiclass logits shaped `[batch, classes]`.
53
+ - `X` and `y` must be PyTorch tensors on the model's device; `y` must contain class indices with dtype `torch.long`.
54
+ - Ablation temporarily sets selected activation values to zero. It does not delete model parameters or retrain the model.
55
+ - The HTML visualization precomputes all masks and currently supports layers with 1–10 units. It is not live inference in the browser.
56
+ - Results depend on the chosen dataset and intervention. Validate important findings on a separate holdout set.
57
+
58
+ ## Demo and tests
59
+
60
+ ```bash
61
+ python demo.py
62
+ python -m unittest discover -s tests -v
63
+ ```
64
+
65
+ This project is an early experimental release. APIs and behavior may change.
@@ -0,0 +1,4 @@
1
+ from .core import Analyzer
2
+
3
+ __version__ = '0.1.0'
4
+ __all__ = ['Analyzer']
@@ -0,0 +1,91 @@
1
+ import json
2
+ from pathlib import Path
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+
8
+ class Analyzer:
9
+ """Measure temporary zero-ablation of units in one [batch, neurons] module.
10
+
11
+ Supports single-input PyTorch multiclass classifiers returning [batch, classes].
12
+ X and y must be tensors on the model's device. A target module must execute once.
13
+ """
14
+
15
+ def __init__(self, model, X, y, layer):
16
+ self.model, self.X, self.y = model, X, y
17
+ self.layer = model.get_submodule(layer) if isinstance(layer, str) else layer
18
+ if not isinstance(self.layer, nn.Module) or not any(m is self.layer for m in model.modules()):
19
+ raise ValueError('layer must be a module belonging to model')
20
+ if X.ndim < 2 or y.ndim != 1 or len(X) != len(y) or not len(y):
21
+ raise ValueError('Expected nonempty X and 1D class labels y of equal length')
22
+ if y.dtype != torch.long:
23
+ raise ValueError('y must contain torch.long class indices')
24
+ self.n_neurons = None
25
+ self.baseline = self.evaluate()
26
+ self.results = []
27
+
28
+ def evaluate(self, remove=()):
29
+ if isinstance(remove, int):
30
+ remove = (remove,)
31
+ remove = tuple(sorted(set(remove)))
32
+ calls = 0
33
+ def hook(module, inputs, output):
34
+ nonlocal calls
35
+ calls += 1
36
+ if not isinstance(output, torch.Tensor) or output.ndim != 2:
37
+ raise ValueError('Target must return a [batch, neurons] tensor')
38
+ width = output.shape[1]
39
+ if self.n_neurons is not None and width != self.n_neurons:
40
+ raise ValueError('Target width changed')
41
+ self.n_neurons = width
42
+ if any(not isinstance(i, int) or i < 0 or i >= width for i in remove):
43
+ raise IndexError('Invalid neuron index')
44
+ if not remove:
45
+ return output
46
+ out = output.clone()
47
+ out[:, list(remove)] = 0
48
+ return out
49
+ modes = [(m, m.training) for m in self.model.modules()]
50
+ handle = self.layer.register_forward_hook(hook)
51
+ try:
52
+ self.model.eval()
53
+ with torch.inference_mode():
54
+ logits = self.model(self.X)
55
+ if calls != 1:
56
+ raise ValueError('Target module must run exactly once per forward pass')
57
+ if not isinstance(logits, torch.Tensor) or logits.ndim != 2 or logits.shape[0] != len(self.y) or logits.shape[1] < 2:
58
+ raise ValueError('Expected multiclass logits [batch, classes]')
59
+ if self.y.min().item() < 0 or self.y.max().item() >= logits.shape[1]:
60
+ raise ValueError('Class index outside model outputs')
61
+ correct = logits.argmax(1).eq(self.y)
62
+ return correct.float().mean().item()
63
+ finally:
64
+ handle.remove()
65
+ for m, mode in modes:
66
+ m.training = mode
67
+
68
+ def scan(self):
69
+ self.results = []
70
+ for i in range(self.n_neurons):
71
+ score = self.evaluate(i)
72
+ self.results.append({'neuron': i, 'accuracy': score, 'impact': self.baseline - score})
73
+ return sorted(self.results, key=lambda row: row['impact'], reverse=True)
74
+
75
+ def report(self):
76
+ print(f'Baseline: {self.baseline:.2%}')
77
+ for row in self.scan():
78
+ print(f"Neuron {row['neuron']}: {row['accuracy']:.2%} | drop {row['impact']*100:+.2f} pp")
79
+
80
+ def visualize(self, path='neuronlab.html'):
81
+ """Create an offline interactive schematic, exhaustively testing all masks (max 10 units)."""
82
+ if not 1 <= self.n_neurons <= 10:
83
+ raise ValueError('Exhaustive visualization supports 1–10 neurons; use scan for larger layers')
84
+ scores = []
85
+ for mask in range(1 << self.n_neurons):
86
+ scores.append(self.evaluate([i for i in range(self.n_neurons) if mask & (1 << i)]))
87
+ data = json.dumps({'n': self.n_neurons, 'scores': scores, 'samples': len(self.y)})
88
+ template = Path(__file__).with_name('viewer.html').read_text(encoding='utf-8')
89
+ path = Path(path)
90
+ path.write_text(template.replace('__NEURON_DATA__', data), encoding='utf-8')
91
+ return path
@@ -0,0 +1,3 @@
1
+ <!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>NeuronLab | Ablation explorer</title><style>
2
+ *{box-sizing:border-box}body{font:16px system-ui,sans-serif;background:#f4f6fa;color:#172339;margin:0;padding:24px}main{max-width:800px;margin:auto;background:white;border:1px solid #dbe2eb;border-radius:20px;padding:24px}h1{margin:0;font-size:28px}p{color:#526278;line-height:1.55}svg{width:100%;height:auto;display:block}button{border:1px solid #c9d4e3;border-radius:9px;padding:10px 15px;background:white;color:#172339;cursor:pointer;font:inherit}button.off{background:#fff0ed;border-color:#d94c40;color:#9f3028}button:focus-visible{outline:3px solid #2463e8}#buttons{display:flex;gap:8px;flex-wrap:wrap;margin:15px 0}.metrics{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:20px 0}.metrics div{padding:12px;background:#f4f6fa;border-radius:12px}.metrics strong{display:block;font-size:clamp(18px,4vw,30px);margin-top:5px}.small{font-size:13px}#drop{color:#a33b2d} @media(max-width:500px){body{padding:8px}main{padding:14px}.metrics div{padding:8px}}</style></head><body><main><h1>NeuronLab <span style="font-size:14px;color:#526278">v0.1.0</span></h1><p>Toggle hidden neurons to see measured changes in classification accuracy. Zero ablation leaves the original model weights intact.</p><svg id="network" viewBox="0 0 600 360" aria-label="Interactive neural network schematic"></svg><div id="buttons"></div><button id="reset">Restore all neurons</button> <button id="all">Disable all</button><div class="metrics"><div>Baseline<strong id="base"></strong></div><div>Accuracy<strong id="acc"></strong></div><div>Drop (pp)<strong id="drop"></strong></div></div><p id="info" class="small"></p><p class="small">Each combination was evaluated on the supplied data before this file was generated. This viewer looks up measured results; it does not run the PyTorch model in the browser. Input and output blocks are schematic.</p></main><script>
3
+ const data=__NEURON_DATA__;let mask=0;const svg=document.getElementById('network'),ns='http://www.w3.org/2000/svg';const $=id=>document.getElementById(id);function node(tag,attrs,text){let e=document.createElementNS(ns,tag);for(let k in attrs)e.setAttribute(k,attrs[k]);if(text!==undefined)e.textContent=text;svg.appendChild(e);return e}function flip(i){mask^=1<<i;render()}function render(){svg.replaceChildren();$('buttons').replaceChildren();const ys=Array.from({length:data.n},(_,i)=>35+i*(290/Math.max(1,data.n-1)));for(let i=0;i<data.n;i++){let off=!!(mask&(1<<i));for(let x of [130,470])node('line',{x1:x,y1:180,x2:300,y2:ys[i],stroke:off?'#d94c40':'#a6b4c9','stroke-opacity':off?.28:.85,'stroke-dasharray':off?'5 5':'none','stroke-width':2})}for(let [x,label] of [[85,'Input'],[515,'Output']]){node('rect',{x:x-45,y:147,width:90,height:66,rx:13,fill:'#e9f0ff',stroke:'#7294db'});node('text',{x,y:185,'text-anchor':'middle',fill:'#23477d','font-size':16},label)}for(let i=0;i<data.n;i++){let off=!!(mask&(1<<i)),c=node('circle',{cx:300,cy:ys[i],r:Math.min(20,125/data.n),fill:off?'#d94c40':'#6352bd',tabindex:0,role:'button','aria-label':'Toggle neuron '+i,'aria-pressed':String(off),style:'cursor:pointer'});c.onclick=()=>flip(i);c.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();flip(i)}};node('text',{x:300,y:ys[i]+5,'text-anchor':'middle',fill:'white','font-size':13,'pointer-events':'none'},off?'×':'N'+i);let b=document.createElement('button');b.textContent='N'+i+(off?' OFF':' ON');b.className=off?'off':'';b.setAttribute('aria-pressed',String(off));b.onclick=()=>flip(i);$('buttons').appendChild(b)}const f=x=>(100*x).toFixed(2)+'%';$('base').textContent=f(data.scores[0]);$('acc').textContent=f(data.scores[mask]);$('drop').textContent=((data.scores[0]-data.scores[mask])*100).toFixed(2);$('info').textContent=`${data.samples} evaluation examples • ${data.scores.length} measured masks • ${mask.toString(2).replace(/0/g,'').length} disabled neurons`;} $('reset').onclick=()=>{mask=0;render()};$('all').onclick=()=>{mask=(1<<data.n)-1;render()};render();</script></body></html>
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: neuronlab
3
+ Version: 0.1.0
4
+ Summary: A small PyTorch tool for testing neuron ablation and visualizing its effect on model accuracy.
5
+ Keywords: pytorch,neural-network,interpretability,neuron-ablation,explainable-ai
6
+ Classifier: Development Status :: 3 - Alpha
7
+ Classifier: Intended Audience :: Developers
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
10
+ Requires-Python: >=3.9
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: torch>=2.0
13
+ Provides-Extra: demo
14
+ Requires-Dist: scikit-learn; extra == "demo"
15
+
16
+ # NeuronLab
17
+
18
+ NeuronLab is an experimental PyTorch utility for measuring the effect of temporarily zeroing units in one selected model layer.
19
+
20
+ ## Features
21
+
22
+ - Measure baseline accuracy on a labeled evaluation dataset.
23
+ - Temporarily zero one or more units in a selected layer.
24
+ - Scan units one at a time and rank them by accuracy change.
25
+ - Print a compact terminal report.
26
+ - Generate an offline interactive HTML visualization with precomputed ablation scores.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ python -m pip install neuronlab
32
+ ```
33
+
34
+ For the demo, install the optional dependency:
35
+
36
+ ```bash
37
+ python -m pip install "neuronlab[demo]"
38
+ ```
39
+
40
+ ## Quick start
41
+
42
+ ```python
43
+ import torch
44
+ from torch import nn
45
+ from neuronlab import Analyzer
46
+
47
+ model = nn.Sequential(
48
+ nn.Linear(2, 3),
49
+ nn.ReLU(),
50
+ nn.Linear(3, 2),
51
+ )
52
+
53
+ X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])
54
+ y = torch.tensor([0, 1, 1, 1], dtype=torch.long)
55
+
56
+ analyzer = Analyzer(model, X, y, layer="1")
57
+ print(analyzer.evaluate())
58
+ print(analyzer.evaluate(remove=0))
59
+ print(analyzer.scan())
60
+ analyzer.report()
61
+ analyzer.visualize("neuronlab.html")
62
+ ```
63
+
64
+ ## Current limitations
65
+
66
+ - The selected layer must return a 2D tensor shaped `[batch, neurons]` and execute exactly once per model forward pass.
67
+ - The model must accept one input tensor and return multiclass logits shaped `[batch, classes]`.
68
+ - `X` and `y` must be PyTorch tensors on the model's device; `y` must contain class indices with dtype `torch.long`.
69
+ - Ablation temporarily sets selected activation values to zero. It does not delete model parameters or retrain the model.
70
+ - The HTML visualization precomputes all masks and currently supports layers with 1–10 units. It is not live inference in the browser.
71
+ - Results depend on the chosen dataset and intervention. Validate important findings on a separate holdout set.
72
+
73
+ ## Demo and tests
74
+
75
+ ```bash
76
+ python demo.py
77
+ python -m unittest discover -s tests -v
78
+ ```
79
+
80
+ This project is an early experimental release. APIs and behavior may change.
@@ -0,0 +1,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ neuronlab/__init__.py
4
+ neuronlab/core.py
5
+ neuronlab/viewer.html
6
+ neuronlab.egg-info/PKG-INFO
7
+ neuronlab.egg-info/SOURCES.txt
8
+ neuronlab.egg-info/dependency_links.txt
9
+ neuronlab.egg-info/requires.txt
10
+ neuronlab.egg-info/top_level.txt
11
+ tests/test_core.py
@@ -0,0 +1,4 @@
1
+ torch>=2.0
2
+
3
+ [demo]
4
+ scikit-learn
@@ -0,0 +1 @@
1
+ neuronlab
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "neuronlab"
7
+ version = "0.1.0"
8
+ description = "A small PyTorch tool for testing neuron ablation and visualizing its effect on model accuracy."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ dependencies = ["torch>=2.0"]
12
+ keywords = ["pytorch", "neural-network", "interpretability", "neuron-ablation", "explainable-ai"]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Developers",
16
+ "Programming Language :: Python :: 3",
17
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ demo = ["scikit-learn"]
22
+
23
+ [tool.setuptools.packages.find]
24
+ include = ["neuronlab*"]
25
+
26
+ [tool.setuptools.package-data]
27
+ neuronlab = ["viewer.html"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,42 @@
1
+ import tempfile
2
+ import unittest
3
+ from pathlib import Path
4
+ import torch
5
+ from torch import nn
6
+ from neuronlab import Analyzer
7
+
8
+
9
+ class TestAnalyzer(unittest.TestCase):
10
+ def setUp(self):
11
+ self.model = nn.Sequential(nn.Linear(2,2,bias=False), nn.ReLU(), nn.Linear(2,2,bias=False))
12
+ with torch.no_grad():
13
+ self.model[0].weight.copy_(torch.eye(2))
14
+ self.model[2].weight.copy_(torch.eye(2))
15
+ self.X = torch.eye(2)
16
+ self.y = torch.tensor([0,1])
17
+ self.a = Analyzer(self.model,self.X,self.y,'1')
18
+
19
+ def test_known_ablation(self):
20
+ self.assertEqual(self.a.baseline,1.)
21
+ self.assertEqual(self.a.evaluate(1),.5)
22
+ self.assertEqual(self.a.evaluate(0),1.)
23
+ self.assertEqual(self.a.evaluate([0,1]),.5)
24
+ self.assertEqual(self.a.scan()[0]['neuron'],1)
25
+
26
+ def test_restore(self):
27
+ self.model.train(); self.model[1].eval()
28
+ modes = [m.training for m in self.model.modules()]
29
+ weights = [p.detach().clone() for p in self.model.parameters()]
30
+ self.a.evaluate(1)
31
+ with self.assertRaises(IndexError): self.a.evaluate(9)
32
+ self.assertEqual(modes,[m.training for m in self.model.modules()])
33
+ self.assertTrue(all(torch.equal(a,b) for a,b in zip(weights,self.model.parameters())))
34
+ self.assertEqual(len(self.model[1]._forward_hooks),0)
35
+ self.assertEqual(self.a.evaluate(),1.)
36
+
37
+ def test_visualize(self):
38
+ with tempfile.TemporaryDirectory() as d:
39
+ p = self.a.visualize(Path(d)/'demo.html')
40
+ self.assertIn('"scores": [1.0, 1.0, 0.5, 0.5]',p.read_text())
41
+
42
+ if __name__ == '__main__': unittest.main()