layer-wise-integrated-gradients 0.1.0__py3-none-any.whl

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.
Files changed (88) hide show
  1. layer_wise_integrated_gradients-0.1.0.dist-info/METADATA +240 -0
  2. layer_wise_integrated_gradients-0.1.0.dist-info/RECORD +88 -0
  3. layer_wise_integrated_gradients-0.1.0.dist-info/WHEEL +5 -0
  4. layer_wise_integrated_gradients-0.1.0.dist-info/entry_points.txt +2 -0
  5. layer_wise_integrated_gradients-0.1.0.dist-info/licenses/LICENSE +21 -0
  6. layer_wise_integrated_gradients-0.1.0.dist-info/top_level.txt +2 -0
  7. lig/__init__.py +38 -0
  8. lig/adapter.py +21 -0
  9. lig/adapters/__init__.py +20 -0
  10. lig/adapters/decoder.py +130 -0
  11. lig/adapters/encoder.py +226 -0
  12. lig/adapters/factory.py +46 -0
  13. lig/api.py +814 -0
  14. lig/boundaries.py +371 -0
  15. lig/cli.py +82 -0
  16. lig/config.py +58 -0
  17. lig/demo/__init__.py +0 -0
  18. lig/demo/streamlit_app.py +45 -0
  19. lig/encoder_access.py +126 -0
  20. lig/publication.py +109 -0
  21. lig/viz/__init__.py +5 -0
  22. lig/viz/z2z_contribution.py +4099 -0
  23. utils/__init__.py +135 -0
  24. utils/calculations/ig/__init__.py +0 -0
  25. utils/calculations/ig/adaptive_batch_size.py +211 -0
  26. utils/calculations/ig/att_itb/__init__.py +16 -0
  27. utils/calculations/ig/att_itb/att_itb.py +120 -0
  28. utils/calculations/ig/attention/__init__.py +0 -0
  29. utils/calculations/ig/attention/attention_ig.py +2317 -0
  30. utils/calculations/ig/attention/attention_map_alpha.py +45 -0
  31. utils/calculations/ig/attention/attention_models.py +371 -0
  32. utils/calculations/ig/attention/core/__init__.py +19 -0
  33. utils/calculations/ig/attention/core/baseline_computation.py +93 -0
  34. utils/calculations/ig/attention/core/embedding_extraction.py +128 -0
  35. utils/calculations/ig/attention/core/value_extraction.py +117 -0
  36. utils/calculations/ig/attention/direct_computation.py +392 -0
  37. utils/calculations/ig/attention/direct_computation_batch.py +488 -0
  38. utils/calculations/ig/attention/gpt2_attention_models.py +390 -0
  39. utils/calculations/ig/attention/methods/__init__.py +6 -0
  40. utils/calculations/ig/attention/methods/v_to_u/__init__.py +6 -0
  41. utils/calculations/ig/attention/methods/z_to_u/__init__.py +6 -0
  42. utils/calculations/ig/attention/multi_layer_attention_ig.py +226 -0
  43. utils/calculations/ig/attention/scratch_ig.py +322 -0
  44. utils/calculations/ig/global_analysis.py +1558 -0
  45. utils/calculations/ig/gpt2/__init__.py +1 -0
  46. utils/calculations/ig/gpt2/block_forward.py +66 -0
  47. utils/calculations/ig/gpu_memory_monitor.py +241 -0
  48. utils/calculations/ig/mlp/__init__.py +0 -0
  49. utils/calculations/ig/mlp/att_itb_mlp_baseline.py +61 -0
  50. utils/calculations/ig/mlp/gpt2_mlp_lig_ig.py +138 -0
  51. utils/calculations/ig/mlp/mlp_ig.py +1134 -0
  52. utils/calculations/ig/mlp/mlp_lig_ig.py +136 -0
  53. utils/calculations/ig/mlp/mlp_models.py +384 -0
  54. utils/calculations/ig/optimized_ig.py +2340 -0
  55. utils/calculations/ig/optimized_runtime/__init__.py +22 -0
  56. utils/calculations/ig/optimized_runtime/device_pool.py +293 -0
  57. utils/calculations/ig/optimized_runtime/executors.py +1481 -0
  58. utils/calculations/ig/optimized_runtime/registry.py +35 -0
  59. utils/calculations/ig/optimized_runtime/tasks.py +43 -0
  60. utils/calculations/ig/parallel_ig_calculator.py +360 -0
  61. utils/calculations/ig/resource_planner.py +118 -0
  62. utils/calculations/ig/shared/__init__.py +1 -0
  63. utils/calculations/ig/shared/encoder_access.py +108 -0
  64. utils/calculations/ig/shared/itb_self_contrib.py +58 -0
  65. utils/calculations/ig/shared/release_scope.py +13 -0
  66. utils/calculations/ig/z2z/compose_att_mlp.py +62 -0
  67. utils/calculations/ig/z2z/global_z2z_analysis.py +193 -0
  68. utils/calculations/ig/z2z/gpt2_layer_direct_ig.py +113 -0
  69. utils/calculations/ig/z2z/layer_direct_ig.py +255 -0
  70. utils/calculations/ig/z2z/layer_itb_zero_ratio.py +80 -0
  71. utils/calculations/shared/__init__.py +0 -0
  72. utils/calculations/shared/device_utils.py +35 -0
  73. utils/calculations/shared/ig_calculations.py +1402 -0
  74. utils/common/__init__.py +23 -0
  75. utils/common/bert_hooks.py +352 -0
  76. utils/common/logging_setup.py +315 -0
  77. utils/common/model_loader.py +72 -0
  78. utils/common/system/__init__.py +38 -0
  79. utils/common/system/background_execution.py +171 -0
  80. utils/common/system/dynamic_worker_manager.py +421 -0
  81. utils/common/system/multi_gpu_manager.py +436 -0
  82. utils/common/system/system_info.py +321 -0
  83. utils/common/unified_bert_model.py +29 -0
  84. utils/common/visualization/__init__.py +16 -0
  85. utils/common/visualization/visualization.py +522 -0
  86. utils/reproduce/__init__.py +0 -0
  87. utils/reproduce/ptb_loader.py +86 -0
  88. utils/scripts/__init__.py +1 -0
@@ -0,0 +1,240 @@
1
+ Metadata-Version: 2.4
2
+ Name: layer-wise-integrated-gradients
3
+ Version: 0.1.0
4
+ Summary: Layer-wise Integrated Gradients (LIG) for within-layer flow analysis in Transformers
5
+ Author: Eight Suzuki, Hideitsu Hino, Noboru Murata
6
+ License: MIT
7
+ Project-URL: Homepage, https://eightsuzuki.github.io/layer-wise-integrated-gradients/
8
+ Project-URL: Documentation, https://eightsuzuki.github.io/layer-wise-integrated-gradients/
9
+ Project-URL: Repository, https://github.com/eightsuzuki/layer-wise-integrated-gradients
10
+ Project-URL: Issues, https://github.com/eightsuzuki/layer-wise-integrated-gradients/issues
11
+ Project-URL: PyPI, https://pypi.org/project/layer-wise-integrated-gradients/
12
+ Keywords: transformers,explainability,integrated-gradients,lig,attention,bert
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy>=2.0.0
26
+ Requires-Dist: captum
27
+ Requires-Dist: transformers<5.0.0,>=4.21.0
28
+ Requires-Dist: tokenizers>=0.13.0
29
+ Requires-Dist: lightning
30
+ Requires-Dist: pandas
31
+ Requires-Dist: joblib
32
+ Requires-Dist: pyyaml>=6.0
33
+ Requires-Dist: scipy>=1.10.0
34
+ Provides-Extra: demo
35
+ Requires-Dist: streamlit>=1.28.0; extra == "demo"
36
+ Provides-Extra: reproduce
37
+ Requires-Dist: openpyxl>=3.1.0; extra == "reproduce"
38
+ Provides-Extra: dev
39
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
40
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
41
+ Requires-Dist: build>=1.0.0; extra == "dev"
42
+ Requires-Dist: twine>=5.0.0; extra == "dev"
43
+ Dynamic: license-file
44
+
45
+ # Layer-wise Integrated Gradients (LIG)
46
+
47
+ <p align="center">
48
+ <img src="logo/LIG-LOGO.png" alt="LIG logo" width="660">
49
+ </p>
50
+
51
+ **Set-to-set Integrated Gradients for within-layer flow analysis in Transformers.**
52
+
53
+ [![Website](https://img.shields.io/badge/website-GitHub%20Pages-0d9488)](https://eightsuzuki.github.io/layer-wise-integrated-gradients/)
54
+ [![PyPI version](https://img.shields.io/pypi/v/layer-wise-integrated-gradients)](https://pypi.org/project/layer-wise-integrated-gradients/)
55
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
56
+ [![GitHub](https://img.shields.io/badge/code-GitHub-181717)](https://github.com/eightsuzuki/layer-wise-integrated-gradients)
57
+
58
+ LIG applies Integrated Gradients (IG) at ATT and MLP module boundaries inside each Transformer layer, composes within-layer token-to-token contributions, and compares them with layer-whole attribution under an $L_2$ diagnostic — without model-specific retraining or per-operation interpreter design.
59
+
60
+ - **Website &amp; interactive demo:** [eightsuzuki.github.io/layer-wise-integrated-gradients](https://eightsuzuki.github.io/layer-wise-integrated-gradients/)
61
+ - **Paper &amp; arXiv:** Coming soon
62
+
63
+ This release implements **L2-scalarized set-to-set IG** at module boundaries (z→u, u→z, z→z), with baselines **ITB** (`self_input_token`), **ITB-zeroRatio** (`itb_zero_ratio`), **ITB-mapRatio** (`itb_map_ratio`), **Zero**, and **ATTITBa=0** (`att_itb_a0`) for MLP.
64
+
65
+ ---
66
+
67
+ ## Quick start
68
+
69
+ Install **PyTorch first** (CUDA/CPU wheel index differs), then LIG:
70
+
71
+ ```bash
72
+ # GPU (CUDA 12.1 example)
73
+ pip install torch --index-url https://download.pytorch.org/whl/cu121
74
+
75
+ # From PyPI
76
+ pip install layer-wise-integrated-gradients
77
+
78
+ # Or from GitHub
79
+ pip install "layer-wise-integrated-gradients @ git+https://github.com/eightsuzuki/layer-wise-integrated-gradients.git"
80
+
81
+ # Development clone
82
+ git clone https://github.com/eightsuzuki/layer-wise-integrated-gradients.git
83
+ cd layer-wise-integrated-gradients
84
+ pip install torch --index-url https://download.pytorch.org/whl/cu121
85
+ pip install -e ".[dev]"
86
+ ```
87
+
88
+ ### Explain one sentence → JSON
89
+
90
+ ```python
91
+ from lig import explain
92
+
93
+ result = explain(
94
+ "The cat sat on the mat.",
95
+ model="bert-base-uncased",
96
+ num_steps=32,
97
+ granularity="all", # att (z→u), mlp (u→z), layer (z→z)
98
+ layers=[0, 11],
99
+ )
100
+ ```
101
+
102
+ ```bash
103
+ lig explain "The cat sat on the mat." --steps 32 --granularity all -o attributions.json
104
+ ```
105
+
106
+ ### Supported models
107
+
108
+ | Family | Models | `granularity` |
109
+ |--------|--------|---------------|
110
+ | BERT-style | BERT, RoBERTa, DeBERTa, ELECTRA, XLM-RoBERTa, … | z→u, u→z, z→z |
111
+ | Block-only | MPNet, DistilBERT, ModernBERT, Switch MoE encoder, Mamba | **z→z (layer) only** |
112
+ | GPT-2 (decoder) | z→u, u→z, z→z (`granularity="all"`) | — |
113
+
114
+ GPT-2 example:
115
+
116
+ ```python
117
+ explain(
118
+ "Hello world",
119
+ model="gpt2",
120
+ granularity="all",
121
+ baseline_att="self_input_token", # or itb_zero_ratio / itb_map_ratio
122
+ baseline_mlp="att_itb_a0", # or zero
123
+ layers=[0],
124
+ )
125
+ ```
126
+
127
+ ATT ITB self-contribution variants (see method section in the upcoming paper):
128
+
129
+ ```python
130
+ explain("Hello world", baseline_att="itb_zero_ratio", granularity="att", layers=[0])
131
+ explain("Hello world", baseline_att="itb_map_ratio", granularity="att", layers=[0])
132
+ explain("Hello world", baseline_layer="itb_zero_ratio", granularity="layer", layers=[0])
133
+ ```
134
+
135
+ Other decoders (Llama, …): [docs/DECODER_DESIGN.md](docs/DECODER_DESIGN.md).
136
+
137
+ ### Inspect boundaries (no IG run)
138
+
139
+ ```python
140
+ from lig import describe_boundaries
141
+
142
+ # Config-only (no weight download)
143
+ describe_boundaries("gpt2", load_weights=False)
144
+
145
+ # Full module introspection
146
+ describe_boundaries("bert-base-uncased", load_weights=True, device="cpu")
147
+ ```
148
+
149
+ ```bash
150
+ python examples/detect_model_boundaries.py bert-base-uncased gpt2 distilbert-base-uncased
151
+ ```
152
+
153
+ ### Docker
154
+
155
+ ```bash
156
+ docker compose -f docker-compose.cpu.yml build
157
+ docker compose -f docker-compose.cpu.yml run --rm lig explain "Hello world" \
158
+ --steps 4 --granularity layer --layers 0 --target-tokens 1 -o /output/out.json
159
+ ```
160
+
161
+ See [docs/DOCKER.md](docs/DOCKER.md).
162
+
163
+ ### Dev setup (uv)
164
+
165
+ ```bash
166
+ bash scripts/ops/setup_uv_env.sh # GPU torch + pip install -e ".[dev]"
167
+ bash scripts/ops/setup_uv_env.sh --cpu # CPU torch
168
+ source .venv/bin/activate
169
+ ```
170
+
171
+ ### Regression tests
172
+
173
+ ```bash
174
+ bash scripts/run_regression_tests.sh
175
+ ```
176
+
177
+ ### Paper demo (no PTB download)
178
+
179
+ Interactive z2z map for the paper example sentence (PTB dev sample 410, Zero baseline):
180
+
181
+ - **GitHub Pages**: [demo](https://eightsuzuki.github.io/layer-wise-integrated-gradients/githubpage/z2z_token_contribution.html) — switch samples and routes (direct z→z / composed ATT×MLP; Zero / ITB / ITB-zeroRatio)
182
+ - **Regenerate** (PTB cache required): `python scripts/build_paper_demos.py && python scripts/build_demo_html.py`
183
+ - **Streamlit**: `pip install -e ".[demo]"` then `streamlit run lig/demo/streamlit_app.py`
184
+ - Precomputed JSON: `examples/paper_demo/json/` (see [DATA_NOTICE](examples/paper_demo/DATA_NOTICE.md))
185
+
186
+ ### Paper reproduction (Experiment A)
187
+
188
+ Requires [Treebank-3 (LDC99T42)](https://catalog.ldc.upenn.edu/LDC99T42). See [docs/REPRODUCTION.md](docs/REPRODUCTION.md).
189
+
190
+ ---
191
+
192
+ ## Features
193
+
194
+ - **One-call API** — `explain(text)` → JSON with z→u, u→z, and z→z attributions
195
+ - **CLI** — `lig explain "..." -o out.json`
196
+ - **Model-agnostic block boundaries** — auto-detect z (residual stream) and u (ATT output / MLP input) from module layout; BERT-family + GPT-2 full granularity; block-level z→z for MPNet, DistilBERT, Switch, Mamba
197
+ - **Boundary introspection** — `describe_boundaries("bert-base-uncased")` or `python examples/detect_model_boundaries.py`
198
+ - **Configurable** — integration steps, baselines, granularity, layers, target tokens
199
+
200
+ ---
201
+
202
+ ## Project layout
203
+
204
+ ```
205
+ .
206
+ ├── lig/ # Public API + encoder adapters + viz demo
207
+ ├── examples/paper_demo/ # One-sentence PTB excerpt + LIG JSON
208
+ ├── docs/ # DOCKER, PyPI, REPRODUCTION, Pages demo
209
+ ├── utils/calculations/ig/ # Core LIG implementations
210
+ ├── scripts/
211
+ │ ├── reproduce/ # Experiment A (PTB-gated)
212
+ │ ├── build_demo_html.py
213
+ │ └── run_regression_tests.sh
214
+ └── test/
215
+ ```
216
+
217
+ ---
218
+
219
+ ## Citation
220
+
221
+ ```bibtex
222
+ @inproceedings{suzuki2026lig,
223
+ title = {LIG: Layer-wise Integrated Gradients for Within-Layer Flow Analysis in Transformers},
224
+ author = {Suzuki, Eight and Hino, Hideitsu and Murata, Noboru},
225
+ year = {2026},
226
+ note = {Code: https://github.com/eightsuzuki/layer-wise-integrated-gradients}
227
+ }
228
+ ```
229
+
230
+ ---
231
+
232
+ ## License
233
+
234
+ [MIT License](LICENSE) for this software.
235
+
236
+ ## PyPI
237
+
238
+ Package metadata and publish steps: [docs/PYPI.md](docs/PYPI.md).
239
+
240
+ Maintainers: sync core IG code from the parent monorepo with `bash scripts/sync_from_monorepo.sh` when needed. See [MANIFEST.md](MANIFEST.md).
@@ -0,0 +1,88 @@
1
+ layer_wise_integrated_gradients-0.1.0.dist-info/licenses/LICENSE,sha256=a7lA-t26eOg7-Gw-bPjdNJRp0A1VkgriR1rK14sGiRY,1069
2
+ lig/__init__.py,sha256=HxkJ3SOCBpKp-hlwJ_ZneRf9W9ms6x-nDR8Us9zdXYo,1057
3
+ lig/adapter.py,sha256=cvj-ylcNl8gsut9A9Lu5-kGRe_odhsmjvYKSxmrzKAs,541
4
+ lig/api.py,sha256=LIHnwlf67dEA5Ao57747lIRZbPATuRXkX5hMChCTu3k,28619
5
+ lig/boundaries.py,sha256=iND68I5BjNgkQ7p-YK9a5jnpMdQIqEmXdbVGaGS_o30,12727
6
+ lig/cli.py,sha256=32HbW_E4heKZWpV9ocX17NbdRSTGKNx8rZFHBRn6uN4,3189
7
+ lig/config.py,sha256=K2T4_gSS4URYprRf6Si0y2NARp3pTmJDyD8G2tSOey0,2395
8
+ lig/encoder_access.py,sha256=Ztn2mkDBPEzQk574zSYsyed-Fcks5rmUmL0fw_iqbjg,4073
9
+ lig/publication.py,sha256=PHPJCoXuw9pSyQUaVfFuPesrIgsUXoyFBYDPH4MKktw,3672
10
+ lig/adapters/__init__.py,sha256=N0TYESY_FsdHGeYxV_qDRMPvKWF2RUo7IaY-vER08K4,488
11
+ lig/adapters/decoder.py,sha256=EFwgg52mIcCOKRGdovDLo1lALER0TFsoJCvVFfDlE1U,4090
12
+ lig/adapters/encoder.py,sha256=byY0PcmToZM9qHWmabfnQzUSfCb172jh-BNBQRSkisA,7231
13
+ lig/adapters/factory.py,sha256=DUnmDTbjort_r6qz7RF2ZlTyp38is8qpEvM4QOVFJkc,1545
14
+ lig/demo/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ lig/demo/streamlit_app.py,sha256=WZTN2eqKJTHpvb_QamgZZZ78ongRoDS0Q-YYGKoywwY,1328
16
+ lig/viz/__init__.py,sha256=P2wW-MCNl7Z4s5kOP2Lea7wIT3Wur8HJ4dkLy2PxnqU,168
17
+ lig/viz/z2z_contribution.py,sha256=QBvuHyXIhIHTUgYoBXeOuE6Vk-Q4bqT0--ZquYehs3c,206956
18
+ utils/__init__.py,sha256=SqqWVER7Z7YBuBwRoyP44-ebbjs7LL6CpEaWXSodMdg,3673
19
+ utils/calculations/ig/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
20
+ utils/calculations/ig/adaptive_batch_size.py,sha256=6ySa6jmVuvdSrcscP9niu56d47Bg2CWztIZ83oHvImY,8826
21
+ utils/calculations/ig/global_analysis.py,sha256=IGTb9tC_srNDmiSNNadjA1jJotVTnM1cdRik8rRP85o,59733
22
+ utils/calculations/ig/gpu_memory_monitor.py,sha256=e6SWQbLGZ6wXOSmUUHvs6rFBRPQBnlmDnQy6Y3yCmBo,9039
23
+ utils/calculations/ig/optimized_ig.py,sha256=wEQM7MPNG_CvPuhez_l3vzo8z6g6zXx-weqYKnjWSJs,122929
24
+ utils/calculations/ig/parallel_ig_calculator.py,sha256=jhcA5s2-vZ9tN7S5sinF7jnf2ES9tqvAOKfbLry9Whk,12038
25
+ utils/calculations/ig/resource_planner.py,sha256=IxElts71-VrWPZVgKbiH-pKyk4TxsjIJcyWqyW64tKE,3921
26
+ utils/calculations/ig/att_itb/__init__.py,sha256=CmlSOPS1I2QnBGfCeYhYWEWzLtCagz8ElCbDIgTlzik,451
27
+ utils/calculations/ig/att_itb/att_itb.py,sha256=i5MZYpMGzEeZ_G6RMGQnPMS8AgDdvxBA-zt4go-hLyI,4784
28
+ utils/calculations/ig/attention/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
+ utils/calculations/ig/attention/attention_ig.py,sha256=oyr-I5LkjpqLgGaDg4huEindlOr0vBESJ9R2MyI_cLg,105466
30
+ utils/calculations/ig/attention/attention_map_alpha.py,sha256=eGFPBcZabiHfekaRA5CLiGLmNvjwPpaY8LetIpWOwJ0,1338
31
+ utils/calculations/ig/attention/attention_models.py,sha256=ORGorqBfDgE0qPQTrUwKorJQ1DrptV51p19qAx8ug9w,13295
32
+ utils/calculations/ig/attention/direct_computation.py,sha256=cYI3ToG2-6RH3R9NYFnaChjqb-he7cLWtKnbF2NgU8M,14450
33
+ utils/calculations/ig/attention/direct_computation_batch.py,sha256=ZWRpr-MQGwbCWPgObFFj2XUX2HTAOymElGlU380-97M,19199
34
+ utils/calculations/ig/attention/gpt2_attention_models.py,sha256=0Rd3kMqwlHHR45sa2hT2vInazzO63vyUGvLphsc2y6I,13905
35
+ utils/calculations/ig/attention/multi_layer_attention_ig.py,sha256=hlMjCYRe91j-aD4p9XMqDFWQYmuFhmcGjT_K3v3JNpg,9623
36
+ utils/calculations/ig/attention/scratch_ig.py,sha256=9iNW80naBkpuwzXEhjD75Ds2XI23kfo-LPSmsNLvoVo,12874
37
+ utils/calculations/ig/attention/core/__init__.py,sha256=0LbnHOAktVGqR-1HfJFhZf4qe_L66yeukUlMdQi6kYg,540
38
+ utils/calculations/ig/attention/core/baseline_computation.py,sha256=xJsnyCnN23NU8YLOP9sJKd8C0UIsvRPXdLqmLG2zHF8,3780
39
+ utils/calculations/ig/attention/core/embedding_extraction.py,sha256=9KRyGc8rVLxn1r7RN59btvcfq794HRvJ7THL4ITjahQ,5295
40
+ utils/calculations/ig/attention/core/value_extraction.py,sha256=iz-O0UrpaxzKY6EgpbtuAIIscF7NnT2OC2Gq-nRxKXE,4016
41
+ utils/calculations/ig/attention/methods/__init__.py,sha256=nUiP9MH2x4AyP1kAV8pZnu18Azf8yu11T21iJ7PjAoM,78
42
+ utils/calculations/ig/attention/methods/v_to_u/__init__.py,sha256=_Zp2s-jozLVekEw8JpD39ca5iLxN7fZBhKORmFrGpA4,110
43
+ utils/calculations/ig/attention/methods/z_to_u/__init__.py,sha256=A33nb-xYeRO41lYgC2RaLCV_GEAQdmSGU_-9DUkbvsY,105
44
+ utils/calculations/ig/gpt2/__init__.py,sha256=KlxdfFcj_Dgv34DjvhiPfP9ir1iGDAkIPQ05fQHvK5s,59
45
+ utils/calculations/ig/gpt2/block_forward.py,sha256=bmSd8zBFvPzCTEgl18SskMYhzcdTRNUFwbnoqJbdSeI,2052
46
+ utils/calculations/ig/mlp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
47
+ utils/calculations/ig/mlp/att_itb_mlp_baseline.py,sha256=5zK6u7GPRNN56TrynbxYjrwHt9peFac6NB9vqgQ6e6c,2176
48
+ utils/calculations/ig/mlp/gpt2_mlp_lig_ig.py,sha256=39a2Xod0ff7y6FFDLXX7SdyqCwnvjhZstB0aiNQUxFc,4260
49
+ utils/calculations/ig/mlp/mlp_ig.py,sha256=SGObQ9lb9H9XyHl2Ml8U2VcMyLgPbSPphJaPKT2tRls,52925
50
+ utils/calculations/ig/mlp/mlp_lig_ig.py,sha256=yU_mDoq-42S-gp6dqnMqrp9UdwdhGR6W7yjXH0cgx4A,4566
51
+ utils/calculations/ig/mlp/mlp_models.py,sha256=rDOvLF8ZHF7oZxK2yG-S4TX0qrSboJl4v2OBa8XGc3Q,16581
52
+ utils/calculations/ig/optimized_runtime/__init__.py,sha256=yUx8C8lUncQOdzMEYxhR8JrdFy4LMlXdEwtG6qAHyqs,625
53
+ utils/calculations/ig/optimized_runtime/device_pool.py,sha256=JXKDcQQSM1VPkDR5r_wK2qjNS6u-t3VsBo6Y3zLJG8s,13886
54
+ utils/calculations/ig/optimized_runtime/executors.py,sha256=LBUP7-gxzR8b9rdEslUvObqRXsLrDjIK2hHZzetPARk,62366
55
+ utils/calculations/ig/optimized_runtime/registry.py,sha256=5Z-gSllPqB_0QJrrfHQxzPDXd8BsXu8Pgiiptqk7dQ0,966
56
+ utils/calculations/ig/optimized_runtime/tasks.py,sha256=Ynpug49a1UjYcg3AkUBaL17ec6OlYo2uOSfisdq9V8A,1258
57
+ utils/calculations/ig/shared/__init__.py,sha256=v31UmUkJWzk2HEHMHx2aPjFCpTvtjhnpKdxRIfDg0fM,49
58
+ utils/calculations/ig/shared/encoder_access.py,sha256=rseXFn2CLbb7E7A68NoVd5gHGLZ8GDsYe4RYpQZll3Q,3422
59
+ utils/calculations/ig/shared/itb_self_contrib.py,sha256=wgZbPrj4yI1vvoIv7PB0K5VULPXvmZXs-8T6aLc0Zeg,1668
60
+ utils/calculations/ig/shared/release_scope.py,sha256=NePY6-dfjrHyghu133N62Sk-2uaN-MHuitLenbJ9NJM,401
61
+ utils/calculations/ig/z2z/compose_att_mlp.py,sha256=Gm4uNi4nWbgRyjRG92_kYWnYApdzgNsiG76bmkOqy2c,2133
62
+ utils/calculations/ig/z2z/global_z2z_analysis.py,sha256=y8hE3RfO9xTfdvu_vfOvA_x6CNsqi8KiErAzpB9vzUg,6870
63
+ utils/calculations/ig/z2z/gpt2_layer_direct_ig.py,sha256=gE7vaowAUfxz2-S5GVoqqUmcE5rdg-JRtm8louEc2wg,3920
64
+ utils/calculations/ig/z2z/layer_direct_ig.py,sha256=1MMtXfNwUMu1ZrC-tYZbRHj9o1vVF7Alpbak2qwTLfA,9253
65
+ utils/calculations/ig/z2z/layer_itb_zero_ratio.py,sha256=ibKKwIADcFShhIgFveLprHp8ssNOjzoKgV7m2n-KrqM,2731
66
+ utils/calculations/shared/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
67
+ utils/calculations/shared/device_utils.py,sha256=UsHa_MTCHr7s1yNT2kG0WSxukoEDcpkhV-BKs_jLmYQ,1183
68
+ utils/calculations/shared/ig_calculations.py,sha256=g3Yi1sCkYXl84b6lCZk6h3pa3SzjYIy7nAc-XOtaZsE,55499
69
+ utils/common/__init__.py,sha256=x1wu4k-933UK3trpoYcl64lf1iMqe76lj1fgpfGT_8I,615
70
+ utils/common/bert_hooks.py,sha256=U64gBWpjWDqlxlmDZ7UThoFxe26noTOJVS8MC06Z9UA,15146
71
+ utils/common/logging_setup.py,sha256=IkBaadZ86AaUMQhoUa1tpgMUu8jkcQRhWDdgP2Zl0n0,12267
72
+ utils/common/model_loader.py,sha256=1Ulv9RK0bd-4vvu6vLfJL2h07kpz0TtMtoVn1tmwB-c,2131
73
+ utils/common/unified_bert_model.py,sha256=s9J2P7Cx8f5td-DSorRb0eFWPPGX8e6ht6LdJwTdOOQ,730
74
+ utils/common/system/__init__.py,sha256=9UdyD7gLI-EpVMQE3zPhLV94tkicdqOnei62KCacnJU,889
75
+ utils/common/system/background_execution.py,sha256=4xUItpaaNGb4IVPqrws5jMVWfelCMXBlaXdRzuN0BJA,4792
76
+ utils/common/system/dynamic_worker_manager.py,sha256=sNB98gbaLzMLmMIsXfQDxJjTeTmU9PEaDyZp3Zmr9L4,15594
77
+ utils/common/system/multi_gpu_manager.py,sha256=3P_3hnY8W_L6YQtBDbtwh6B0Wv0L0EQCyZXUULyG21k,16048
78
+ utils/common/system/system_info.py,sha256=4CzsedXtoZM6DKnO9msZibyCouTJqmwrmNoXHCyEXyQ,11625
79
+ utils/common/visualization/__init__.py,sha256=ZKpF7TBHl3OQvY-oNNAizHwG1K9phbZJ2yzwKRN_VEc,227
80
+ utils/common/visualization/visualization.py,sha256=N-kxSlMuGotfkz6lKjjqjpAncU-VQMnBZyEMuAu9YFI,19244
81
+ utils/reproduce/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
82
+ utils/reproduce/ptb_loader.py,sha256=LoNhJjEwmlnWzub8CY0gn232v50TBx5re5BV4eyhS7M,2680
83
+ utils/scripts/__init__.py,sha256=wl_Al81pKp67__DWmd6R5AdPsjiRI4KeoRbjeRijKjI,56
84
+ layer_wise_integrated_gradients-0.1.0.dist-info/METADATA,sha256=kiSJ-_UMGfHiztBf_g7RbxvR9fRuDa7C9JMiM8weqpI,8829
85
+ layer_wise_integrated_gradients-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
86
+ layer_wise_integrated_gradients-0.1.0.dist-info/entry_points.txt,sha256=N_k33-d_ixHnGJpmak_jasroUItuMQdIejfJVFGWAls,37
87
+ layer_wise_integrated_gradients-0.1.0.dist-info/top_level.txt,sha256=2KLYSYs9GdQ_nruX3aLqkrvYef8sIwdywMhiSiHkMXA,10
88
+ layer_wise_integrated_gradients-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ lig = lig.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eight Suzuki
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.
lig/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """
2
+ Layer-wise Integrated Gradients (LIG) — public API.
3
+
4
+ Quick start::
5
+
6
+ from lig import explain
7
+ result = explain("The cat sat on the mat.", model="bert-base-uncased")
8
+ # result is a JSON-serializable dict
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import TYPE_CHECKING
14
+
15
+ __all__ = ["explain", "describe_boundaries", "LIGConfig", "__version__"]
16
+ __version__ = "0.1.0"
17
+
18
+ if TYPE_CHECKING:
19
+ from lig.api import describe_boundaries as describe_boundaries
20
+ from lig.api import explain as explain
21
+ from lig.config import LIGConfig as LIGConfig
22
+
23
+
24
+ def __getattr__(name: str):
25
+ """Lazy imports so optional tooling does not require torch at import time."""
26
+ if name == "explain":
27
+ from lig.api import explain
28
+
29
+ return explain
30
+ if name == "describe_boundaries":
31
+ from lig.api import describe_boundaries
32
+
33
+ return describe_boundaries
34
+ if name == "LIGConfig":
35
+ from lig.config import LIGConfig
36
+
37
+ return LIGConfig
38
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
lig/adapter.py ADDED
@@ -0,0 +1,21 @@
1
+ """Backward-compatible re-exports. Prefer ``lig.adapters.load_adapter``."""
2
+
3
+ from lig.adapters.decoder import DECODER_FAMILY_TYPES, DecoderAdapter
4
+ from lig.adapters.encoder import (
5
+ BERT_FAMILY_TYPES,
6
+ ENCODER_TYPES,
7
+ LAYER_ONLY_ENCODER_TYPES,
8
+ EncoderAdapter,
9
+ )
10
+ from lig.adapters.factory import ModelAdapter, load_adapter
11
+
12
+ __all__ = [
13
+ "BERT_FAMILY_TYPES",
14
+ "ENCODER_TYPES",
15
+ "LAYER_ONLY_ENCODER_TYPES",
16
+ "DECODER_FAMILY_TYPES",
17
+ "DecoderAdapter",
18
+ "EncoderAdapter",
19
+ "ModelAdapter",
20
+ "load_adapter",
21
+ ]
@@ -0,0 +1,20 @@
1
+ """Model adapters for encoder / decoder Transformers."""
2
+
3
+ from lig.adapters.decoder import DECODER_FAMILY_TYPES, DecoderAdapter
4
+ from lig.adapters.encoder import (
5
+ BERT_FAMILY_TYPES,
6
+ ENCODER_TYPES,
7
+ LAYER_ONLY_ENCODER_TYPES,
8
+ EncoderAdapter,
9
+ )
10
+ from lig.adapters.factory import load_adapter
11
+
12
+ __all__ = [
13
+ "BERT_FAMILY_TYPES",
14
+ "ENCODER_TYPES",
15
+ "LAYER_ONLY_ENCODER_TYPES",
16
+ "DECODER_FAMILY_TYPES",
17
+ "DecoderAdapter",
18
+ "EncoderAdapter",
19
+ "load_adapter",
20
+ ]
@@ -0,0 +1,130 @@
1
+ """
2
+ Decoder-only adapter (design stub).
3
+
4
+ Full design: docs/DECODER_DESIGN.md
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Any, Dict, List, Optional, Tuple
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
15
+
16
+ # Planned first wave (GPT-2 block layout)
17
+ DECODER_FAMILY_TYPES = frozenset(
18
+ {
19
+ "gpt2",
20
+ "gpt_neox",
21
+ "llama",
22
+ "mistral",
23
+ "qwen2",
24
+ "gemma",
25
+ }
26
+ )
27
+
28
+
29
+ @dataclass
30
+ class DecoderAdapter:
31
+ """
32
+ Decoder-only causal LM adapter (not yet wired to IG).
33
+
34
+ Block mapping (GPT-2 style)::
35
+ z^(l) = hidden before block l self-attention
36
+ u^(l) = hidden after self-attention + residual (MLP input)
37
+ z^(l+1) = hidden after MLP + residual
38
+ """
39
+
40
+ model: nn.Module
41
+ tokenizer: Any
42
+ model_name: str
43
+ model_type: str
44
+ device: torch.device
45
+ architecture: str = "decoder"
46
+
47
+ @classmethod
48
+ def from_pretrained(
49
+ cls,
50
+ model_name: str,
51
+ device: Optional[str] = None,
52
+ torch_dtype: Optional[torch.dtype] = None,
53
+ ) -> "DecoderAdapter":
54
+ config = AutoConfig.from_pretrained(model_name)
55
+ model_type = getattr(config, "model_type", "unknown")
56
+ if model_type not in DECODER_FAMILY_TYPES:
57
+ raise ValueError(
58
+ f"Unsupported decoder model_type '{model_type}' for '{model_name}'."
59
+ )
60
+
61
+ load_kwargs: Dict[str, Any] = {
62
+ "output_hidden_states": True,
63
+ "attn_implementation": "eager",
64
+ }
65
+ if torch_dtype is not None:
66
+ load_kwargs["torch_dtype"] = torch_dtype
67
+
68
+ model = AutoModelForCausalLM.from_pretrained(model_name, **load_kwargs)
69
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
70
+ if tokenizer.pad_token is None:
71
+ tokenizer.pad_token = tokenizer.eos_token
72
+
73
+ if device is None:
74
+ device = "cuda" if torch.cuda.is_available() else "cpu"
75
+ dev = torch.device(device)
76
+ model = model.to(dev)
77
+ model.eval()
78
+
79
+ return cls(
80
+ model=model,
81
+ tokenizer=tokenizer,
82
+ model_name=model_name,
83
+ model_type=model_type,
84
+ device=dev,
85
+ )
86
+
87
+ def get_blocks(self) -> nn.ModuleList:
88
+ """Return transformer blocks (model-specific)."""
89
+ if hasattr(self.model, "transformer") and hasattr(self.model.transformer, "h"):
90
+ return self.model.transformer.h # GPT-2
91
+ if hasattr(self.model, "model") and hasattr(self.model.model, "layers"):
92
+ return self.model.model.layers # Llama-style
93
+ raise NotImplementedError(
94
+ f"Block enumeration not implemented for {self.model_type}. "
95
+ "See docs/DECODER_DESIGN.md"
96
+ )
97
+
98
+ @property
99
+ def num_layers(self) -> int:
100
+ return len(self.get_blocks())
101
+
102
+ def tokenize(self, text: str) -> Dict[str, torch.Tensor]:
103
+ encoded = self.tokenizer(
104
+ text,
105
+ return_tensors="pt",
106
+ truncation=True,
107
+ max_length=512,
108
+ )
109
+ return {k: v.to(self.device) for k, v in encoded.items()}
110
+
111
+ def tokens_as_strings(self, text: str) -> List[str]:
112
+ encoded = self.tokenizer(text, truncation=True, max_length=512)
113
+ return self.tokenizer.convert_ids_to_tokens(encoded["input_ids"])
114
+
115
+ def forward_hidden_states(
116
+ self, inputs: Dict[str, torch.Tensor]
117
+ ) -> Tuple[torch.Tensor, ...]:
118
+ with torch.no_grad():
119
+ outputs = self.model(**inputs, output_hidden_states=True)
120
+ hidden = outputs.hidden_states
121
+ if hidden is None:
122
+ raise RuntimeError("Model did not return hidden_states")
123
+ return hidden
124
+
125
+ def ensure_ig_ready(self) -> None:
126
+ raise NotImplementedError(
127
+ f"Decoder LIG is not implemented yet for {self.model_type} ({self.model_name}). "
128
+ "Encoder models (BERT, RoBERTa, …) are supported via lig.explain(). "
129
+ "See docs/DECODER_DESIGN.md for the planned API."
130
+ )