doctosae 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.
Files changed (59) hide show
  1. doctosae-0.1.0/.gitignore +64 -0
  2. doctosae-0.1.0/LICENSE +202 -0
  3. doctosae-0.1.0/PKG-INFO +181 -0
  4. doctosae-0.1.0/README.md +132 -0
  5. doctosae-0.1.0/examples/01_quickstart.py +115 -0
  6. doctosae-0.1.0/examples/02_reproduce_cure.py +146 -0
  7. doctosae-0.1.0/examples/03_interpret_features.py +149 -0
  8. doctosae-0.1.0/examples/quickstart.ipynb +248 -0
  9. doctosae-0.1.0/pyproject.toml +125 -0
  10. doctosae-0.1.0/src/doctosae/__init__.py +98 -0
  11. doctosae-0.1.0/src/doctosae/_ids.py +132 -0
  12. doctosae-0.1.0/src/doctosae/cli.py +1035 -0
  13. doctosae-0.1.0/src/doctosae/data/__init__.py +39 -0
  14. doctosae-0.1.0/src/doctosae/data/dataset.py +278 -0
  15. doctosae-0.1.0/src/doctosae/data/loaders.py +570 -0
  16. doctosae-0.1.0/src/doctosae/data/registry.py +236 -0
  17. doctosae-0.1.0/src/doctosae/data/splits.py +140 -0
  18. doctosae-0.1.0/src/doctosae/embed.py +636 -0
  19. doctosae-0.1.0/src/doctosae/hub.py +330 -0
  20. doctosae-0.1.0/src/doctosae/interpret/__init__.py +49 -0
  21. doctosae-0.1.0/src/doctosae/interpret/activations.py +320 -0
  22. doctosae-0.1.0/src/doctosae/interpret/cards.py +157 -0
  23. doctosae-0.1.0/src/doctosae/interpret/explain.py +184 -0
  24. doctosae-0.1.0/src/doctosae/interpret/interpreter.py +483 -0
  25. doctosae-0.1.0/src/doctosae/interpret/labeling.py +257 -0
  26. doctosae-0.1.0/src/doctosae/interpret/llm.py +383 -0
  27. doctosae-0.1.0/src/doctosae/interpret/prompts.py +285 -0
  28. doctosae-0.1.0/src/doctosae/interpret/scoring.py +677 -0
  29. doctosae-0.1.0/src/doctosae/interpret/selection.py +102 -0
  30. doctosae-0.1.0/src/doctosae/interpret/tfidf.py +86 -0
  31. doctosae-0.1.0/src/doctosae/metrics.py +303 -0
  32. doctosae-0.1.0/src/doctosae/py.typed +0 -0
  33. doctosae-0.1.0/src/doctosae/retrieval.py +165 -0
  34. doctosae-0.1.0/src/doctosae/sae.py +387 -0
  35. doctosae-0.1.0/src/doctosae/training/__init__.py +6 -0
  36. doctosae-0.1.0/src/doctosae/training/config.py +116 -0
  37. doctosae-0.1.0/src/doctosae/training/losses.py +111 -0
  38. doctosae-0.1.0/src/doctosae/training/sampling.py +155 -0
  39. doctosae-0.1.0/src/doctosae/training/trainer.py +820 -0
  40. doctosae-0.1.0/tests/test_cli.py +492 -0
  41. doctosae-0.1.0/tests/test_data.py +528 -0
  42. doctosae-0.1.0/tests/test_embed.py +512 -0
  43. doctosae-0.1.0/tests/test_hub.py +286 -0
  44. doctosae-0.1.0/tests/test_interpret_evidence.py +233 -0
  45. doctosae-0.1.0/tests/test_interpret_explain.py +134 -0
  46. doctosae-0.1.0/tests/test_interpret_interpreter.py +376 -0
  47. doctosae-0.1.0/tests/test_interpret_llm.py +307 -0
  48. doctosae-0.1.0/tests/test_interpret_paper_equivalence.py +573 -0
  49. doctosae-0.1.0/tests/test_interpret_parsing.py +109 -0
  50. doctosae-0.1.0/tests/test_interpret_prompts.py +190 -0
  51. doctosae-0.1.0/tests/test_interpret_scoring.py +430 -0
  52. doctosae-0.1.0/tests/test_losses.py +119 -0
  53. doctosae-0.1.0/tests/test_metrics.py +234 -0
  54. doctosae-0.1.0/tests/test_paper_equivalence.py +497 -0
  55. doctosae-0.1.0/tests/test_retrieval.py +129 -0
  56. doctosae-0.1.0/tests/test_sae.py +197 -0
  57. doctosae-0.1.0/tests/test_sampling.py +118 -0
  58. doctosae-0.1.0/tests/test_splits.py +154 -0
  59. doctosae-0.1.0/tests/test_training.py +472 -0
@@ -0,0 +1,64 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
11
+ .coverage
12
+ coverage.xml
13
+ htmlcov/
14
+
15
+ # Environments
16
+ .venv/
17
+ venv/
18
+ env/
19
+ .python-version
20
+
21
+ # Secrets and credentials: never commit them
22
+ .env
23
+ .env.*
24
+ *.pem
25
+ *.key
26
+ .streamlit/secrets.toml
27
+ **/.streamlit/secrets.toml
28
+ *service-account*.json
29
+ *service_account*.json
30
+ *credentials*.json
31
+ gcp-*.json
32
+ # cloud key files keep their download name: the project id, then 12 hex digits, then .json
33
+ *-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f].json
34
+ # no JSON file is versioned at the root or at the top of the package
35
+ /*.json
36
+ /package/*.json
37
+
38
+ # Data, embeddings, checkpoints and experiment outputs
39
+ # (anchored: an unanchored "data/" would also hide the package/src/doctosae/data subpackage)
40
+ /data/
41
+ /paper/data/
42
+ /package/data/
43
+ runs/
44
+ /logs/
45
+ outputs/
46
+ cache/
47
+ .doctosae_cache/
48
+ *.pkl
49
+ *.npy
50
+ *.npz
51
+ *.pt
52
+ *.pth
53
+ *.safetensors
54
+ *.parquet
55
+ wandb/
56
+
57
+ # Annotation app local answers (annotator ids and comments)
58
+ annotation_app/**/*.csv
59
+
60
+ # Notebooks and OS noise
61
+ .ipynb_checkpoints/
62
+ .DS_Store
63
+ .idea/
64
+ .vscode/
doctosae-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.5
2
+ Name: doctosae
3
+ Version: 0.1.0
4
+ Summary: Sparse autoencoders for interpretable and transferable medical information retrieval
5
+ Project-URL: Homepage, https://github.com/doctolib-lab/doctosae
6
+ Project-URL: Repository, https://github.com/doctolib-lab/doctosae
7
+ Project-URL: Issues, https://github.com/doctolib-lab/doctosae/issues
8
+ Project-URL: Paper, https://arxiv.org/abs/2611.18179
9
+ Project-URL: Hugging Face, https://huggingface.co/collections/doctolib-lab/doctosae
10
+ Author: Gaëtan Brison, Diane Bouchacourt
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: embeddings,explainability,information retrieval,interpretability,medical,sparse autoencoder
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
23
+ Requires-Python: >=3.11
24
+ Requires-Dist: huggingface-hub<3,>=0.30
25
+ Requires-Dist: jinja2>=3.1
26
+ Requires-Dist: numpy>=1.26
27
+ Requires-Dist: pandas>=2.0
28
+ Requires-Dist: pyarrow>=16
29
+ Requires-Dist: safetensors>=0.4.3
30
+ Requires-Dist: scikit-learn>=1.3
31
+ Requires-Dist: scipy>=1.10
32
+ Requires-Dist: sentence-transformers>=3.0
33
+ Requires-Dist: torch>=2.4
34
+ Requires-Dist: tqdm>=4.66
35
+ Provides-Extra: dev
36
+ Requires-Dist: build>=1.2; extra == 'dev'
37
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
38
+ Requires-Dist: pytest>=8; extra == 'dev'
39
+ Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
40
+ Requires-Dist: twine>=7; extra == 'dev'
41
+ Provides-Extra: gemini
42
+ Requires-Dist: google-genai>=1.0; extra == 'gemini'
43
+ Provides-Extra: llm
44
+ Requires-Dist: openai<4,>=1.40; extra == 'llm'
45
+ Provides-Extra: local-llm
46
+ Requires-Dist: accelerate>=0.33; extra == 'local-llm'
47
+ Requires-Dist: transformers>=4.50.1; extra == 'local-llm'
48
+ Description-Content-Type: text/markdown
49
+
50
+ # DoctoSAE
51
+
52
+ **Sparse autoencoders for interpretable and transferable medical retrieval.** Reference implementation of the ML4H
53
+ 2026 paper [*Explanations that Transfer: Interpreting Medical Retrieval with Sparse AutoEncoders*](https://arxiv.org/abs/2611.18179) (Diane Bouchacourt and
54
+ Gaëtan Brison).
55
+
56
+ ![DoctoSAE overview](https://raw.githubusercontent.com/doctolib-lab/doctosae/main/.github/assets/doctosae_overview.png)
57
+
58
+ DoctoSAE trains a TopK sparse autoencoder (SAE) on the frozen embeddings of a text encoder, with a reconstruction loss
59
+ and an InfoNCE loss that keeps queries close to their relevant documents. Documents are then ranked by cosine
60
+ similarity of codes with at most k active features, and every feature can be described from the texts that activate
61
+ it: top snippets, TF IDF terms and a topic written by an Interpreter LLM. These descriptions explain single
62
+ retrievals, and they transfer to corpora the SAE never saw.
63
+
64
+ > **Warning:** DoctoSAE is in active development and its API may change before version 1.0. It is a research tool:
65
+ > do not use it for diagnosis, treatment or any other clinical decision.
66
+
67
+ ## Install
68
+
69
+ ```bash
70
+ pip install doctosae
71
+ pip install "doctosae[llm]" # optional: LLM descriptions through any OpenAI compatible server
72
+ pip install "doctosae[local-llm]" # optional: local LLM such as google/medgemma-4b-it
73
+ ```
74
+
75
+ DoctoSAE needs Python 3.11 or newer. A GPU is advised for CURE; the small examples run on a laptop CPU.
76
+
77
+ ## Quickstart
78
+
79
+ ```python
80
+ from doctosae import DoctoSAE, Embedder, Interpreter, Trainer, TrainingConfig, evaluate, load_dataset
81
+
82
+ dataset = load_dataset("nfcorpus") # cure, miriad, r2med_biology, ...
83
+ data = Embedder("BAAI/bge-small-en-v1.5").embed_dataset(dataset) # frozen encoder
84
+
85
+ sae = DoctoSAE(d_in=data.dim, n_latents=3 * data.dim, k=32, embedder=data.embedder)
86
+ sae = Trainer(sae, TrainingConfig(), output_dir="runs/nfcorpus/sae").fit(data).best_model # paper settings
87
+
88
+ print(evaluate(None, data, split="test")) # dense embeddings
89
+ print(evaluate(sae, data, split="test")) # sparse codes: ndcg@10, recall@100, mrr@10
90
+
91
+ interpreter = Interpreter(sae, data, split="train")
92
+ for card in interpreter.describe(interpreter.select_features(n=3)):
93
+ print(card.to_markdown())
94
+ ```
95
+
96
+ The same steps from the command line:
97
+
98
+ ```bash
99
+ doctosae embed --dataset nfcorpus --model BAAI/bge-small-en-v1.5 --output runs/nfcorpus/embeddings
100
+ doctosae train --dataset nfcorpus --embeddings runs/nfcorpus/embeddings --k 32 --output-dir runs/nfcorpus/sae
101
+ doctosae evaluate --dataset nfcorpus --embeddings runs/nfcorpus/embeddings --sae runs/nfcorpus/sae
102
+ doctosae interpret --dataset nfcorpus --embeddings runs/nfcorpus/embeddings --sae runs/nfcorpus/sae \
103
+ --output runs/nfcorpus/features --n-features 20
104
+ ```
105
+
106
+ ## What is inside
107
+
108
+ * `doctosae.load_dataset`: CURE, NFCorpus, MIRIAD and the three R2MED subsets, downloaded from the Hugging Face Hub
109
+ at pinned revisions with the splits of the paper; `doctosae.load_beir_folder` for your own data.
110
+ * `doctosae.Embedder`: sentence transformers encoders; queries of the BGE v1.5 models get the retrieval instruction
111
+ of their model card, the one the paper used for BGE large, and the embeddings record every setting.
112
+ * `doctosae.DoctoSAE`: the TopK SAE, saved and shared through the Hugging Face Hub (`save_pretrained`, `push_to_hub`,
113
+ `from_pretrained`, `doctosae.load_pretrained`).
114
+ * `doctosae.Trainer`: the paper objective, sampler and checkpoint selection. The defaults are the values the paper
115
+ holds fixed, and one point of its grid for the InfoNCE weight and temperature, which it selects per k.
116
+ * `doctosae.evaluate` and `doctosae.search`: retrieval on sparse codes, NDCG@10 computed as in the paper.
117
+ * `doctosae.Interpreter`: feature selection, feature cards, Interpreter and Activation Prediction LLMs (OpenAI
118
+ compatible servers, local Transformers models), and retrieval explanations as in Figure 2 of the paper.
119
+ * `doctosae` command line: `datasets`, `pretrained`, `embed`, `train`, `evaluate`, `interpret`, `explain`, `push`,
120
+ `convert`.
121
+
122
+ ## Pretrained sparse autoencoders
123
+
124
+ The checkpoints of the paper, trained on CURE, are in the
125
+ [DoctoSAE collection](https://huggingface.co/collections/doctolib-lab/doctosae) of the Hugging Face Hub: one repository
126
+ per encoder, one folder per configuration.
127
+
128
+ | Encoder | Alias | Repository | Checkpoints |
129
+ | --- | --- | --- | --- |
130
+ | `BAAI/bge-large-en-v1.5` | `bge` | `doctolib-lab/doctosae-bge-large-en-v1.5` | `k64_m3072`, `k256_m3072` |
131
+ | `abhinand/MedEmbed-large-v0.1` | `medembed` | `doctolib-lab/doctosae-medembed-large-v0.1` | `k64_m3072`, `k256_m3072` |
132
+ | `gemini-embedding-001` | `gemini` | `doctolib-lab/doctosae-gemini-embedding-001` | `k128_m9216`, `k256_m9216` |
133
+
134
+ ```python
135
+ from doctosae import load_pretrained
136
+
137
+ sae = load_pretrained("bge", k=64) # doctolib-lab/doctosae-bge-large-en-v1.5/k64_m3072
138
+ sae = load_pretrained("gemini") # the smallest k: doctolib-lab/doctosae-gemini-embedding-001/k128_m9216
139
+ ```
140
+
141
+ The smallest k is the configuration the paper interprets, k = 256 the one that retrieves best. `doctosae pretrained`
142
+ lists every checkpoint id. Weights trained on CURE are `cc-by-nc-4.0` (noncommercial), the license of CURE.
143
+
144
+ ## Results from the paper
145
+
146
+ NDCG@10 (%) with `BAAI/bge-large-en-v1.5`, SAEs trained on CURE, mean over three seeds (Table 1 of the paper):
147
+
148
+ | BGE | CURE | NFCorpus | MIRIAD | R2MED Bioinformatics | R2MED Biology | R2MED Medical Sciences |
149
+ | --- | --- | --- | --- | --- | --- | --- |
150
+ | original | 53.06 | 38.17 | 77.24 | 27.04 | 12.72 | 27.78 |
151
+ | k = 64 | 57.07 | 31.89 | 68.75 | 22.50 | 8.30 | 22.72 |
152
+ | k = 128 | 59.35 | 34.48 | 71.83 | 27.42 | 9.76 | 26.60 |
153
+ | k = 256 | 60.50 | 35.61 | 73.85 | 28.10 | 10.06 | 29.05 |
154
+ | dense (k = 1024) | 61.87 | 36.62 | 75.05 | 27.21 | 8.37 | 27.33 |
155
+
156
+ ## Links
157
+
158
+ * Source code, paper code and full documentation: <https://github.com/doctolib-lab/doctosae>
159
+ * Examples: <https://github.com/doctolib-lab/doctosae/tree/main/package/examples>
160
+ * Issues: <https://github.com/doctolib-lab/doctosae/issues>
161
+ * Contributing: <https://github.com/doctolib-lab/doctosae/blob/main/CONTRIBUTING.md>
162
+
163
+ ## Citation
164
+
165
+ ```bibtex
166
+ @misc{bouchacourt2026explanationstransferinterpretingmedical,
167
+ title={Explanations that Transfer: Interpreting Medical Retrieval with Sparse AutoEncoders},
168
+ author={Diane Bouchacourt and Gaëtan Brison},
169
+ year={2026},
170
+ eprint={2611.18179},
171
+ archivePrefix={arXiv},
172
+ primaryClass={cs.IR},
173
+ url={https://arxiv.org/abs/2611.18179},
174
+ }
175
+ ```
176
+
177
+ ## License
178
+
179
+ The code is released under the Apache 2.0 license. Datasets keep their own licenses and are downloaded from the
180
+ Hugging Face Hub at pinned revisions (CURE is `cc-by-nc-4.0`, noncommercial). SAE weights trained on CURE are
181
+ `cc-by-nc-4.0`.
@@ -0,0 +1,132 @@
1
+ # DoctoSAE
2
+
3
+ **Sparse autoencoders for interpretable and transferable medical retrieval.** Reference implementation of the ML4H
4
+ 2026 paper [*Explanations that Transfer: Interpreting Medical Retrieval with Sparse AutoEncoders*](https://arxiv.org/abs/2611.18179) (Diane Bouchacourt and
5
+ Gaëtan Brison).
6
+
7
+ ![DoctoSAE overview](../.github/assets/doctosae_overview.png)
8
+
9
+ DoctoSAE trains a TopK sparse autoencoder (SAE) on the frozen embeddings of a text encoder, with a reconstruction loss
10
+ and an InfoNCE loss that keeps queries close to their relevant documents. Documents are then ranked by cosine
11
+ similarity of codes with at most k active features, and every feature can be described from the texts that activate
12
+ it: top snippets, TF IDF terms and a topic written by an Interpreter LLM. These descriptions explain single
13
+ retrievals, and they transfer to corpora the SAE never saw.
14
+
15
+ > **Warning:** DoctoSAE is in active development and its API may change before version 1.0. It is a research tool:
16
+ > do not use it for diagnosis, treatment or any other clinical decision.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install doctosae
22
+ pip install "doctosae[llm]" # optional: LLM descriptions through any OpenAI compatible server
23
+ pip install "doctosae[local-llm]" # optional: local LLM such as google/medgemma-4b-it
24
+ ```
25
+
26
+ DoctoSAE needs Python 3.11 or newer. A GPU is advised for CURE; the small examples run on a laptop CPU.
27
+
28
+ ## Quickstart
29
+
30
+ ```python
31
+ from doctosae import DoctoSAE, Embedder, Interpreter, Trainer, TrainingConfig, evaluate, load_dataset
32
+
33
+ dataset = load_dataset("nfcorpus") # cure, miriad, r2med_biology, ...
34
+ data = Embedder("BAAI/bge-small-en-v1.5").embed_dataset(dataset) # frozen encoder
35
+
36
+ sae = DoctoSAE(d_in=data.dim, n_latents=3 * data.dim, k=32, embedder=data.embedder)
37
+ sae = Trainer(sae, TrainingConfig(), output_dir="runs/nfcorpus/sae").fit(data).best_model # paper settings
38
+
39
+ print(evaluate(None, data, split="test")) # dense embeddings
40
+ print(evaluate(sae, data, split="test")) # sparse codes: ndcg@10, recall@100, mrr@10
41
+
42
+ interpreter = Interpreter(sae, data, split="train")
43
+ for card in interpreter.describe(interpreter.select_features(n=3)):
44
+ print(card.to_markdown())
45
+ ```
46
+
47
+ The same steps from the command line:
48
+
49
+ ```bash
50
+ doctosae embed --dataset nfcorpus --model BAAI/bge-small-en-v1.5 --output runs/nfcorpus/embeddings
51
+ doctosae train --dataset nfcorpus --embeddings runs/nfcorpus/embeddings --k 32 --output-dir runs/nfcorpus/sae
52
+ doctosae evaluate --dataset nfcorpus --embeddings runs/nfcorpus/embeddings --sae runs/nfcorpus/sae
53
+ doctosae interpret --dataset nfcorpus --embeddings runs/nfcorpus/embeddings --sae runs/nfcorpus/sae \
54
+ --output runs/nfcorpus/features --n-features 20
55
+ ```
56
+
57
+ ## What is inside
58
+
59
+ * `doctosae.load_dataset`: CURE, NFCorpus, MIRIAD and the three R2MED subsets, downloaded from the Hugging Face Hub
60
+ at pinned revisions with the splits of the paper; `doctosae.load_beir_folder` for your own data.
61
+ * `doctosae.Embedder`: sentence transformers encoders; queries of the BGE v1.5 models get the retrieval instruction
62
+ of their model card, the one the paper used for BGE large, and the embeddings record every setting.
63
+ * `doctosae.DoctoSAE`: the TopK SAE, saved and shared through the Hugging Face Hub (`save_pretrained`, `push_to_hub`,
64
+ `from_pretrained`, `doctosae.load_pretrained`).
65
+ * `doctosae.Trainer`: the paper objective, sampler and checkpoint selection. The defaults are the values the paper
66
+ holds fixed, and one point of its grid for the InfoNCE weight and temperature, which it selects per k.
67
+ * `doctosae.evaluate` and `doctosae.search`: retrieval on sparse codes, NDCG@10 computed as in the paper.
68
+ * `doctosae.Interpreter`: feature selection, feature cards, Interpreter and Activation Prediction LLMs (OpenAI
69
+ compatible servers, local Transformers models), and retrieval explanations as in Figure 2 of the paper.
70
+ * `doctosae` command line: `datasets`, `pretrained`, `embed`, `train`, `evaluate`, `interpret`, `explain`, `push`,
71
+ `convert`.
72
+
73
+ ## Pretrained sparse autoencoders
74
+
75
+ The checkpoints of the paper, trained on CURE, are in the
76
+ [DoctoSAE collection](https://huggingface.co/collections/doctolib-lab/doctosae) of the Hugging Face Hub: one repository
77
+ per encoder, one folder per configuration.
78
+
79
+ | Encoder | Alias | Repository | Checkpoints |
80
+ | --- | --- | --- | --- |
81
+ | `BAAI/bge-large-en-v1.5` | `bge` | `doctolib-lab/doctosae-bge-large-en-v1.5` | `k64_m3072`, `k256_m3072` |
82
+ | `abhinand/MedEmbed-large-v0.1` | `medembed` | `doctolib-lab/doctosae-medembed-large-v0.1` | `k64_m3072`, `k256_m3072` |
83
+ | `gemini-embedding-001` | `gemini` | `doctolib-lab/doctosae-gemini-embedding-001` | `k128_m9216`, `k256_m9216` |
84
+
85
+ ```python
86
+ from doctosae import load_pretrained
87
+
88
+ sae = load_pretrained("bge", k=64) # doctolib-lab/doctosae-bge-large-en-v1.5/k64_m3072
89
+ sae = load_pretrained("gemini") # the smallest k: doctolib-lab/doctosae-gemini-embedding-001/k128_m9216
90
+ ```
91
+
92
+ The smallest k is the configuration the paper interprets, k = 256 the one that retrieves best. `doctosae pretrained`
93
+ lists every checkpoint id. Weights trained on CURE are `cc-by-nc-4.0` (noncommercial), the license of CURE.
94
+
95
+ ## Results from the paper
96
+
97
+ NDCG@10 (%) with `BAAI/bge-large-en-v1.5`, SAEs trained on CURE, mean over three seeds (Table 1 of the paper):
98
+
99
+ | BGE | CURE | NFCorpus | MIRIAD | R2MED Bioinformatics | R2MED Biology | R2MED Medical Sciences |
100
+ | --- | --- | --- | --- | --- | --- | --- |
101
+ | original | 53.06 | 38.17 | 77.24 | 27.04 | 12.72 | 27.78 |
102
+ | k = 64 | 57.07 | 31.89 | 68.75 | 22.50 | 8.30 | 22.72 |
103
+ | k = 128 | 59.35 | 34.48 | 71.83 | 27.42 | 9.76 | 26.60 |
104
+ | k = 256 | 60.50 | 35.61 | 73.85 | 28.10 | 10.06 | 29.05 |
105
+ | dense (k = 1024) | 61.87 | 36.62 | 75.05 | 27.21 | 8.37 | 27.33 |
106
+
107
+ ## Links
108
+
109
+ * Source code, paper code and full documentation: <https://github.com/doctolib-lab/doctosae>
110
+ * Examples: <https://github.com/doctolib-lab/doctosae/tree/main/package/examples>
111
+ * Issues: <https://github.com/doctolib-lab/doctosae/issues>
112
+ * Contributing: <https://github.com/doctolib-lab/doctosae/blob/main/CONTRIBUTING.md>
113
+
114
+ ## Citation
115
+
116
+ ```bibtex
117
+ @misc{bouchacourt2026explanationstransferinterpretingmedical,
118
+ title={Explanations that Transfer: Interpreting Medical Retrieval with Sparse AutoEncoders},
119
+ author={Diane Bouchacourt and Gaëtan Brison},
120
+ year={2026},
121
+ eprint={2611.18179},
122
+ archivePrefix={arXiv},
123
+ primaryClass={cs.IR},
124
+ url={https://arxiv.org/abs/2611.18179},
125
+ }
126
+ ```
127
+
128
+ ## License
129
+
130
+ The code is released under the Apache 2.0 license. Datasets keep their own licenses and are downloaded from the
131
+ Hugging Face Hub at pinned revisions (CURE is `cc-by-nc-4.0`, noncommercial). SAE weights trained on CURE are
132
+ `cc-by-nc-4.0`.