SpectralHarmonicRouting 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,32 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10", "3.11", "3.12"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - uses: actions/setup-python@v5
19
+ with:
20
+ python-version: ${{ matrix.python-version }}
21
+ - name: Install package and dev dependencies
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ pip install ".[dev]"
25
+ - name: Lint with ruff
26
+ run: ruff check src tests
27
+ - name: Run tests
28
+ run: pytest
29
+ - name: Build and check distributions
30
+ run: |
31
+ python -m build
32
+ twine check dist/*
@@ -0,0 +1,46 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - "v*"
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ build:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: actions/setup-python@v5
17
+ with:
18
+ python-version: "3.11"
19
+ - name: Build sdist and wheel
20
+ run: |
21
+ python -m pip install --upgrade pip
22
+ pip install build twine
23
+ python -m build
24
+ twine check dist/*
25
+ - name: Upload distribution artifacts
26
+ uses: actions/upload-artifact@v4
27
+ with:
28
+ name: dist
29
+ path: dist/
30
+
31
+ publish-pypi:
32
+ needs: build
33
+ runs-on: ubuntu-latest
34
+ environment:
35
+ name: pypi
36
+ url: https://pypi.org/p/spectralharmonicrouting
37
+ permissions:
38
+ id-token: write
39
+ steps:
40
+ - name: Download distribution artifacts
41
+ uses: actions/download-artifact@v4
42
+ with:
43
+ name: dist
44
+ path: dist/
45
+ - name: Publish to PyPI via Trusted Publishing
46
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .pytest_cache/
7
+ .mypy_cache/
8
+ .ruff_cache/
9
+ .venv/
10
+ *.pt
11
+ *.png
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ All notable changes to `shr` will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-12-05
9
+
10
+ ### Added
11
+ - Initial public release of `shr` (Spectral Head Routing).
12
+ - `UniversalSHRAnalyzer` for architecture-agnostic Vision/Audio Transformer routing attribution.
13
+ - `compute_signal_flow` and `draw_signal_flow_acfg` for layer-to-layer causal signal flow and Attention/MLP decomposition.
14
+ - `discover_acoustic_clusters`, `select_optimal_k`, `separate_outlier_patches`, and `draw_data_driven_acfg` for Acoustic Causal Flow Graphs (ACFG).
15
+ - Causal intervention suite: `LayerAblator`, `evaluate_causal_ablation`, `sweep_layer_bypass`, `patch_activation_mediation`, and `sweep_activation_patching`.
16
+ - Faithfulness evaluation suite: `deletion_insertion_auc`, `run_faithfulness_comparison`, `vanilla_gradient_saliency`, `integrated_gradients_saliency`, `vit_gradcam`, `vit_gradcam_plusplus`, and `attention_rollout`.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SpectralRouting Authors
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. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.5
2
+ Name: SpectralHarmonicRouting
3
+ Version: 0.1.0
4
+ Summary: Spectral Head Routing (SHR): Mechanistic interpretability, causal signal flow, and acoustic causal flow graphs for Vision and Audio Transformers.
5
+ Author: SpectralRouting Authors
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: audio-spectrogram-transformer,causal-ablation,explainable-ai,mechanistic-interpretability,spectral-routing,transformers,vision-transformer
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: matplotlib>=3.7
21
+ Requires-Dist: numpy>=1.24
22
+ Requires-Dist: pandas>=2.0
23
+ Requires-Dist: scikit-learn>=1.3
24
+ Requires-Dist: scipy>=1.10
25
+ Requires-Dist: torch>=2.1
26
+ Requires-Dist: tqdm>=4.65
27
+ Provides-Extra: dev
28
+ Requires-Dist: build>=1.2; extra == 'dev'
29
+ Requires-Dist: mypy>=1.10; extra == 'dev'
30
+ Requires-Dist: pytest>=8.0; extra == 'dev'
31
+ Requires-Dist: ruff>=0.5; extra == 'dev'
32
+ Requires-Dist: twine>=5.0; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # shr — Spectral Head Routing
36
+
37
+ Mechanistic interpretability, causal signal flow, and Acoustic Causal Flow Graphs (ACFG) for Vision and Audio Transformers.
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ pip install SpectralHarmonicRouting
43
+ ```
44
+
45
+ For development (testing, linting, type-checking, and building):
46
+
47
+ ```bash
48
+ pip install "SpectralHarmonicRouting[dev]"
49
+ ```
50
+
51
+ ## Key Features
52
+
53
+ - **Universal Transformer Routing (`UniversalSHRAnalyzer`):** Computes layerwise and patch-level Spectral Head Routing (SHR) scores across Vision Transformers (ViT, LingBot-Vision, DINOv3) and Audio Spectrogram Transformers (AST), as well as dual-backbone 24-layer ensembles.
54
+ - **Acoustic Causal Flow Graphs (`discover_acoustic_clusters`, `draw_data_driven_acfg`):** Automatically separates outlier patches, selects optimal functional cluster count $K$ via silhouette score, and renders class-conditional routing bottlenecks.
55
+ - **Causal Signal Flow (`compute_signal_flow`, `draw_signal_flow_acfg`):** Decomposes layer-to-layer causal propagation into Attention vs. MLP stream contributions.
56
+ - **Causal Interventions (`evaluate_causal_ablation`, `sweep_layer_bypass`, `sweep_activation_patching`):** Validates routing bottlenecks with Top-$k$ vs. Bottom-$k$ vs. Random-$k$ layer ablation, single-layer bypass sweeps, and activation patching mediation.
57
+ - **Faithfulness Benchmarking (`run_faithfulness_comparison`, `deletion_insertion_auc`):** Evaluates Deletion AUC, Insertion AUC, and Faithfulness Gap against Vanilla Gradients, Integrated Gradients, Grad-CAM, Grad-CAM++, and Attention Rollout.
58
+
59
+ ## Quickstart
60
+
61
+ ```python
62
+ import torch
63
+ from shr import (
64
+ UniversalSHRAnalyzer,
65
+ compute_signal_flow,
66
+ discover_acoustic_clusters,
67
+ draw_data_driven_acfg,
68
+ evaluate_causal_ablation,
69
+ select_optimal_k,
70
+ separate_outlier_patches,
71
+ )
72
+
73
+ analyzer = UniversalSHRAnalyzer(model, device="cuda")
74
+ layer_scores, patch_scores_norm, patch_energy_norm = analyzer.compute_patch_routing_scores(batches)
75
+
76
+ inlier_mask, outlier_idx, _ = separate_outlier_patches(patch_scores_norm)
77
+ optimal_k, _, _ = select_optimal_k(patch_scores_norm[inlier_mask])
78
+ cluster_info = discover_acoustic_clusters(
79
+ patch_scores_norm=patch_scores_norm,
80
+ patch_energy_norm=patch_energy_norm,
81
+ n_clusters=optimal_k,
82
+ inlier_mask=inlier_mask,
83
+ outlier_indices=outlier_idx,
84
+ freq_range_hz=(20.0, 8000.0),
85
+ )
86
+
87
+ draw_data_driven_acfg(
88
+ layer_scores=layer_scores,
89
+ cluster_info=cluster_info,
90
+ output_classes=["Chordektomie", "Laryngitis", "Rekurrensparese", "healthy"],
91
+ save_dir="runs/acfg",
92
+ filename="acfg.png",
93
+ )
94
+
95
+ flow = compute_signal_flow(analyzer, batches, cluster_info)
96
+ ablation = evaluate_causal_ablation(analyzer, batches, ablate_indices=[0, 1])
97
+ ```
98
+
99
+ ## License
100
+
101
+ MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,67 @@
1
+ # shr — Spectral Head Routing
2
+
3
+ Mechanistic interpretability, causal signal flow, and Acoustic Causal Flow Graphs (ACFG) for Vision and Audio Transformers.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install SpectralHarmonicRouting
9
+ ```
10
+
11
+ For development (testing, linting, type-checking, and building):
12
+
13
+ ```bash
14
+ pip install "SpectralHarmonicRouting[dev]"
15
+ ```
16
+
17
+ ## Key Features
18
+
19
+ - **Universal Transformer Routing (`UniversalSHRAnalyzer`):** Computes layerwise and patch-level Spectral Head Routing (SHR) scores across Vision Transformers (ViT, LingBot-Vision, DINOv3) and Audio Spectrogram Transformers (AST), as well as dual-backbone 24-layer ensembles.
20
+ - **Acoustic Causal Flow Graphs (`discover_acoustic_clusters`, `draw_data_driven_acfg`):** Automatically separates outlier patches, selects optimal functional cluster count $K$ via silhouette score, and renders class-conditional routing bottlenecks.
21
+ - **Causal Signal Flow (`compute_signal_flow`, `draw_signal_flow_acfg`):** Decomposes layer-to-layer causal propagation into Attention vs. MLP stream contributions.
22
+ - **Causal Interventions (`evaluate_causal_ablation`, `sweep_layer_bypass`, `sweep_activation_patching`):** Validates routing bottlenecks with Top-$k$ vs. Bottom-$k$ vs. Random-$k$ layer ablation, single-layer bypass sweeps, and activation patching mediation.
23
+ - **Faithfulness Benchmarking (`run_faithfulness_comparison`, `deletion_insertion_auc`):** Evaluates Deletion AUC, Insertion AUC, and Faithfulness Gap against Vanilla Gradients, Integrated Gradients, Grad-CAM, Grad-CAM++, and Attention Rollout.
24
+
25
+ ## Quickstart
26
+
27
+ ```python
28
+ import torch
29
+ from shr import (
30
+ UniversalSHRAnalyzer,
31
+ compute_signal_flow,
32
+ discover_acoustic_clusters,
33
+ draw_data_driven_acfg,
34
+ evaluate_causal_ablation,
35
+ select_optimal_k,
36
+ separate_outlier_patches,
37
+ )
38
+
39
+ analyzer = UniversalSHRAnalyzer(model, device="cuda")
40
+ layer_scores, patch_scores_norm, patch_energy_norm = analyzer.compute_patch_routing_scores(batches)
41
+
42
+ inlier_mask, outlier_idx, _ = separate_outlier_patches(patch_scores_norm)
43
+ optimal_k, _, _ = select_optimal_k(patch_scores_norm[inlier_mask])
44
+ cluster_info = discover_acoustic_clusters(
45
+ patch_scores_norm=patch_scores_norm,
46
+ patch_energy_norm=patch_energy_norm,
47
+ n_clusters=optimal_k,
48
+ inlier_mask=inlier_mask,
49
+ outlier_indices=outlier_idx,
50
+ freq_range_hz=(20.0, 8000.0),
51
+ )
52
+
53
+ draw_data_driven_acfg(
54
+ layer_scores=layer_scores,
55
+ cluster_info=cluster_info,
56
+ output_classes=["Chordektomie", "Laryngitis", "Rekurrensparese", "healthy"],
57
+ save_dir="runs/acfg",
58
+ filename="acfg.png",
59
+ )
60
+
61
+ flow = compute_signal_flow(analyzer, batches, cluster_info)
62
+ ablation = evaluate_causal_ablation(analyzer, batches, ablate_indices=[0, 1])
63
+ ```
64
+
65
+ ## License
66
+
67
+ MIT License. See [LICENSE](LICENSE).
@@ -0,0 +1,76 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "SpectralHarmonicRouting"
7
+ dynamic = ["version"]
8
+ description = "Spectral Head Routing (SHR): Mechanistic interpretability, causal signal flow, and acoustic causal flow graphs for Vision and Audio Transformers."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "SpectralRouting Authors" },
14
+ ]
15
+ keywords = [
16
+ "mechanistic-interpretability",
17
+ "spectral-routing",
18
+ "transformers",
19
+ "vision-transformer",
20
+ "audio-spectrogram-transformer",
21
+ "explainable-ai",
22
+ "causal-ablation",
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 4 - Beta",
26
+ "Intended Audience :: Science/Research",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Operating System :: OS Independent",
29
+ "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
34
+ "Typing :: Typed",
35
+ ]
36
+ dependencies = [
37
+ "matplotlib>=3.7",
38
+ "numpy>=1.24",
39
+ "pandas>=2.0",
40
+ "scikit-learn>=1.3",
41
+ "scipy>=1.10",
42
+ "torch>=2.1",
43
+ "tqdm>=4.65",
44
+ ]
45
+
46
+ [project.optional-dependencies]
47
+ dev = [
48
+ "build>=1.2",
49
+ "mypy>=1.10",
50
+ "pytest>=8.0",
51
+ "ruff>=0.5",
52
+ "twine>=5.0",
53
+ ]
54
+
55
+ [tool.hatch.version]
56
+ path = "src/shr/__init__.py"
57
+
58
+ [tool.hatch.build.targets.wheel]
59
+ packages = ["src/shr"]
60
+
61
+ [tool.pytest.ini_options]
62
+ testpaths = ["tests"]
63
+ addopts = "-ra -q"
64
+
65
+ [tool.ruff]
66
+ target-version = "py310"
67
+ line-length = 120
68
+
69
+ [tool.ruff.lint]
70
+ select = ["E", "F"]
71
+ ignore = ["E501", "E741"]
72
+
73
+ [tool.mypy]
74
+ python_version = "3.10"
75
+ ignore_missing_imports = true
76
+ warn_unused_configs = true
@@ -0,0 +1,51 @@
1
+ """Spectral Head Routing (SHR) mechanistic interpretability package."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .ablation import (
6
+ LayerAblator,
7
+ evaluate_causal_ablation,
8
+ patch_activation_mediation,
9
+ sweep_activation_patching,
10
+ sweep_layer_bypass,
11
+ )
12
+ from .acfg import draw_data_driven_acfg
13
+ from .analyzer import UniversalSHRAnalyzer
14
+ from .clustering import (
15
+ discover_acoustic_clusters,
16
+ select_optimal_k,
17
+ separate_outlier_patches,
18
+ )
19
+ from .flow import compute_signal_flow, draw_signal_flow_acfg
20
+ from .faithfulness import (
21
+ attention_rollout,
22
+ deletion_insertion_auc,
23
+ integrated_gradients_saliency,
24
+ run_faithfulness_comparison,
25
+ vanilla_gradient_saliency,
26
+ vit_gradcam,
27
+ vit_gradcam_plusplus,
28
+ )
29
+
30
+ __all__ = [
31
+ "__version__",
32
+ "UniversalSHRAnalyzer",
33
+ "LayerAblator",
34
+ "evaluate_causal_ablation",
35
+ "patch_activation_mediation",
36
+ "sweep_activation_patching",
37
+ "sweep_layer_bypass",
38
+ "separate_outlier_patches",
39
+ "select_optimal_k",
40
+ "discover_acoustic_clusters",
41
+ "draw_data_driven_acfg",
42
+ "deletion_insertion_auc",
43
+ "vanilla_gradient_saliency",
44
+ "integrated_gradients_saliency",
45
+ "vit_gradcam",
46
+ "vit_gradcam_plusplus",
47
+ "attention_rollout",
48
+ "run_faithfulness_comparison",
49
+ "compute_signal_flow",
50
+ "draw_signal_flow_acfg",
51
+ ]