nucleobench 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 (27) hide show
  1. nucleobench-0.1.0/LICENSE +201 -0
  2. nucleobench-0.1.0/PKG-INFO +82 -0
  3. nucleobench-0.1.0/README.md +52 -0
  4. nucleobench-0.1.0/nucleobench/common/__init__.py +0 -0
  5. nucleobench-0.1.0/nucleobench/common/argparse_lib.py +64 -0
  6. nucleobench-0.1.0/nucleobench/common/attribution_lib_torch.py +199 -0
  7. nucleobench-0.1.0/nucleobench/common/attribution_lib_torch_test.py +175 -0
  8. nucleobench-0.1.0/nucleobench/common/constants.py +7 -0
  9. nucleobench-0.1.0/nucleobench/common/gcp_utils.py +150 -0
  10. nucleobench-0.1.0/nucleobench/common/memory_utils.py +10 -0
  11. nucleobench-0.1.0/nucleobench/common/priority_queue.py +105 -0
  12. nucleobench-0.1.0/nucleobench/common/priority_queue_test.py +55 -0
  13. nucleobench-0.1.0/nucleobench/common/string_utils.py +173 -0
  14. nucleobench-0.1.0/nucleobench/common/string_utils_test.py +48 -0
  15. nucleobench-0.1.0/nucleobench/common/testing_utils.py +82 -0
  16. nucleobench-0.1.0/nucleobench/common/testing_utils_test.py +52 -0
  17. nucleobench-0.1.0/nucleobench/optimizations/__init__.py +37 -0
  18. nucleobench-0.1.0/nucleobench/optimizations/optimization_class.py +35 -0
  19. nucleobench-0.1.0/nucleobench/optimizations/utils.py +65 -0
  20. nucleobench-0.1.0/nucleobench/optimizations/utils_test.py +19 -0
  21. nucleobench-0.1.0/nucleobench.egg-info/PKG-INFO +82 -0
  22. nucleobench-0.1.0/nucleobench.egg-info/SOURCES.txt +25 -0
  23. nucleobench-0.1.0/nucleobench.egg-info/dependency_links.txt +1 -0
  24. nucleobench-0.1.0/nucleobench.egg-info/requires.txt +11 -0
  25. nucleobench-0.1.0/nucleobench.egg-info/top_level.txt +1 -0
  26. nucleobench-0.1.0/pyproject.toml +58 -0
  27. nucleobench-0.1.0/setup.cfg +4 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: nucleobench
3
+ Version: 0.1.0
4
+ Summary: Optimizers from the nucleobench package.
5
+ Author-email: Move37 Labs <joel.shor@move37labs.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/move37-labs/nucleobench
8
+ Project-URL: Bug Tracker, https://github.com/move37-labs/nucleobench/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.8
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Requires-Python: >=3.8
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: numpy
20
+ Requires-Dist: scipy
21
+ Requires-Dist: pandas
22
+ Requires-Dist: h5py
23
+ Requires-Dist: pyarrow
24
+ Requires-Dist: torch
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest; extra == "dev"
27
+ Requires-Dist: coverage; extra == "dev"
28
+ Requires-Dist: pyclean; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # NucleoBench
32
+
33
+ This is the initial repo for an upcoming paper, `NucleoBench: A Large-Scale Benchmark of Neural Nucleic Acid Design Algorithms`.
34
+
35
+ This repo is covered by the MIT license.
36
+
37
+ This repo is intended to be used in a few ways:
38
+
39
+ 1. Reproducing the results from our paper.
40
+ 1. Running the NucleoBench sequence designers on custom problems.
41
+ 1. Using our new designer, AdaBeam, on a custom problem.
42
+
43
+ To do these, you can clone this repo, use the Docker image (for the benchmark), or use the PyPi package for our designers.
44
+
45
+ ## Results
46
+
47
+ ![Summary of results.](assets/images/results_summary.png)
48
+
49
+ ## Installation & testing
50
+
51
+ Once this repo is cloned, you can make the conda/mamba/micromamba environment with:
52
+
53
+ ```bash
54
+ conda env create -f environment.yml
55
+ conda activate nucleobench
56
+ ```
57
+
58
+ To test that you've install NucleoBench, run all the unittests:
59
+
60
+ ```bash
61
+ pytest nucleobench/
62
+ ```
63
+
64
+ You can also run the integration tests, which require an internet connection:
65
+
66
+ ```bash
67
+ pytest docker_entrypoint_test.py
68
+ ```
69
+
70
+ Nucleic acid design benchmark.
71
+
72
+ ## Running NucleoBench
73
+
74
+ See the folder `recipes` for examples of how to run the designer locally.
75
+
76
+ ## Building a Docker image
77
+
78
+ To help deploy NucleoBench to the cloud, we've created a docker container. To build it yourself, see the top of `Dockerfile` for instructions. One way of creating a docker file is:
79
+
80
+ ```bash
81
+ docker build -t nucleobench -f Dockerfile .
82
+ ```
@@ -0,0 +1,52 @@
1
+ # NucleoBench
2
+
3
+ This is the initial repo for an upcoming paper, `NucleoBench: A Large-Scale Benchmark of Neural Nucleic Acid Design Algorithms`.
4
+
5
+ This repo is covered by the MIT license.
6
+
7
+ This repo is intended to be used in a few ways:
8
+
9
+ 1. Reproducing the results from our paper.
10
+ 1. Running the NucleoBench sequence designers on custom problems.
11
+ 1. Using our new designer, AdaBeam, on a custom problem.
12
+
13
+ To do these, you can clone this repo, use the Docker image (for the benchmark), or use the PyPi package for our designers.
14
+
15
+ ## Results
16
+
17
+ ![Summary of results.](assets/images/results_summary.png)
18
+
19
+ ## Installation & testing
20
+
21
+ Once this repo is cloned, you can make the conda/mamba/micromamba environment with:
22
+
23
+ ```bash
24
+ conda env create -f environment.yml
25
+ conda activate nucleobench
26
+ ```
27
+
28
+ To test that you've install NucleoBench, run all the unittests:
29
+
30
+ ```bash
31
+ pytest nucleobench/
32
+ ```
33
+
34
+ You can also run the integration tests, which require an internet connection:
35
+
36
+ ```bash
37
+ pytest docker_entrypoint_test.py
38
+ ```
39
+
40
+ Nucleic acid design benchmark.
41
+
42
+ ## Running NucleoBench
43
+
44
+ See the folder `recipes` for examples of how to run the designer locally.
45
+
46
+ ## Building a Docker image
47
+
48
+ To help deploy NucleoBench to the cloud, we've created a docker container. To build it yourself, see the top of `Dockerfile` for instructions. One way of creating a docker file is:
49
+
50
+ ```bash
51
+ docker build -t nucleobench -f Dockerfile .
52
+ ```
File without changes
@@ -0,0 +1,64 @@
1
+ """Utilities for parsing arguments."""
2
+
3
+ from typing import Iterable
4
+
5
+ import argparse
6
+ import dataclasses
7
+
8
+ @dataclasses.dataclass
9
+ class ParsedArgs:
10
+ main_args: argparse.Namespace
11
+ model_init_args: argparse.Namespace
12
+ opt_init_args: argparse.Namespace
13
+ opt_run_args: argparse.Namespace
14
+
15
+
16
+ def parse_long_start_sequence(known_args: argparse.Namespace) -> argparse.Namespace:
17
+ """Parse a long start sequence from a file."""
18
+ assert known_args.seed_sequence.startswith('local://')
19
+ local_fileloc = known_args.seed_sequence[len('local://'):]
20
+ with open(local_fileloc, 'r') as f:
21
+ known_args.seed_sequence = f.read()
22
+ return known_args
23
+
24
+
25
+ def possibly_parse_positions_to_mutate(known_args: argparse.Namespace) -> argparse.Namespace:
26
+ """Possibly parse `positions_to_mutate` from a file, or leave it untouched, depending on the value."""
27
+ if isinstance(known_args.positions_to_mutate, str) and known_args.positions_to_mutate.startswith('local://'):
28
+ local_fileloc = known_args.positions_to_mutate[len('local://'):]
29
+ with open(local_fileloc, 'r') as f:
30
+ loc_str = f.read()
31
+ known_args.positions_to_mutate = [int(x) for x in loc_str.split('\n')]
32
+ elif known_args.positions_to_mutate is None or known_args.positions_to_mutate == '' or known_args.positions_to_mutate == []:
33
+ known_args.positions_to_mutate = None
34
+ else:
35
+ assert isinstance(known_args.positions_to_mutate, list), (type(known_args.positions_to_mutate), known_args.positions_to_mutate)
36
+ known_args.positions_to_mutate = [int(x) for x in known_args.positions_to_mutate.split(',')]
37
+ return known_args
38
+
39
+
40
+ def handle_leftover_args(known_args: argparse.Namespace, leftover_args: Iterable):
41
+ """Handle leftover arguments, either by failing or by ignoring them."""
42
+ if known_args.ignore_empty_cmd_args:
43
+ # Check that every "value" is either `None` or `empty`. If so, allow it to continue.
44
+ for i in leftover_args:
45
+ if i.startswith('--'):
46
+ if '=' in i:
47
+ arg_val = i.split('=')[1]
48
+ if arg_val not in [None, '']:
49
+ raise ValueError(f'Unused arg, not empty: {leftover_args}')
50
+ continue
51
+ else:
52
+ if i not in [None, '']:
53
+ raise ValueError(f'Unused arg, not empty: {leftover_args}')
54
+ else:
55
+ raise ValueError(f'Unused args: {leftover_args}')
56
+
57
+
58
+ def str_to_bool(s):
59
+ if s.lower() in ('yes', 'true', 't', '1'):
60
+ return True
61
+ elif s.lower() in ('no', 'false', 'f', '0'):
62
+ return False
63
+ else:
64
+ raise argparse.ArgumentTypeError('Boolean value expected.')
@@ -0,0 +1,199 @@
1
+ """Library for smoothgrad and genome-specific attribution methods.
2
+
3
+ Ref:
4
+ 1. [Correcting gradient-based interpretations of deep neural networks for genomics](https://genomebiology.biomedcentral.com/articles/10.1186/s13059-023-02956-3)
5
+ 2. [SmoothGrad: removing noise by adding noise](https://arxiv.org/abs/1706.03825)
6
+ 3. [Quick and effective approximation of in silico saturation mutagenesis experiments with first-order taylor expansion](https://pubmed.ncbi.nlm.nih.gov/39286491/)
7
+
8
+ TODO(joelshor): Consider using public version of attribution tools, such as:
9
+ - PyTorch Smoothgrad: https://github.com/pkmr06/pytorch-smoothgrad
10
+ - PyTorch GradCam and others: https://github.com/jacobgil/pytorch-grad-cam?tab=readme-ov-file
11
+ - PyTorch Smoothgrad and others: https://tf-explain.readthedocs.io/en/latest/
12
+
13
+ To test locally:
14
+ ```zsh
15
+ python -m nucleobench.common.attribution_lib
16
+ ```
17
+ """
18
+
19
+ import gc
20
+ import numpy as np
21
+ import torch
22
+ from typing import Callable, Optional
23
+
24
+
25
+ TISMOutputType = list[dict[str, float]]
26
+ SmoothgradVocabType = list[dict[str, torch.Tensor]]
27
+ TISMLocationsType = list[int]
28
+
29
+
30
+ def noise_inputs(
31
+ input_tensor: torch.Tensor,
32
+ noise_stdev: float,
33
+ times: int,
34
+ ) -> torch.Tensor:
35
+ """Generates noisy inputs.
36
+
37
+ NOTE: For simplicity, for now, we work with SINGLE TENSORS. Assume no batch dimension.
38
+
39
+ Args:
40
+ input_tensor: Input tensor. Doesn't have to be genomic. Should NOT be batched.
41
+ noise_stdev: Noise to add.
42
+ times: Number of times to add noise.
43
+ """
44
+ if noise_stdev < 0:
45
+ raise ValueError(f'Requires non-negative noise stdev: {noise_stdev}')
46
+ x = input_tensor # Syntactic sugar.
47
+
48
+ # Stack N versions of the input, to add uncorrelated noise to.
49
+ with torch.no_grad():
50
+ x = x.unsqueeze(0)
51
+ x = x.repeat([times] + [1] * (x.ndim-1))
52
+
53
+ # Add noise for hte smoothgrad algorithm.
54
+ if noise_stdev > 0:
55
+ noise_to_add = torch.normal(mean=torch.zeros(x.shape), std=noise_stdev)
56
+ x += noise_to_add
57
+ return x
58
+
59
+ def noisy_grads_torch(
60
+ input_tensor: torch.Tensor,
61
+ model: Callable[[torch.Tensor], torch.Tensor],
62
+ noise_stdev: float,
63
+ times: int,
64
+ idxs: Optional[TISMLocationsType] = None,
65
+ ) -> torch.Tensor:
66
+ """Generates noisy gradients from a function.
67
+
68
+ NOTE: For simplicity, for now, we work with SINGLE TENSORS. Assume no batch dimension.
69
+
70
+ This replicates the input `times` times, and runs it through the network all at once.
71
+
72
+ TODO(joelshor): Add batching, for the situation where `times` is larger than the possible batch size
73
+ of a single inference with a network.
74
+ TODO(joelshor): Add ability to efficiently compute multiple inputs at once.
75
+
76
+ Args:
77
+ input_tensor (torch.Tensor): Input tensor. Doesn't have to be genomic. Should NOT be batched.
78
+ model: PyTorch model to use. The model must return a scalar per batch element.
79
+ noise_stdev: Noise to add.
80
+ times: Number of times to add noise.
81
+ idx: If present, only backprop through this location.
82
+ """
83
+ x = noise_inputs(
84
+ input_tensor=input_tensor,
85
+ noise_stdev=noise_stdev,
86
+ times=times)
87
+
88
+ # Run inference to get grads.
89
+ if idxs is None:
90
+ x_grad = x
91
+ x_grad.requires_grad = True
92
+ else:
93
+ x, x_grad = apply_gradient_mask(x, idxs)
94
+
95
+ y = model(x)
96
+ y_sum = y.sum()
97
+ y_sum.backward(retain_graph=False)
98
+ noisy_grads = x_grad.grad.numpy()
99
+
100
+ gc.collect()
101
+ torch.cuda.empty_cache()
102
+
103
+ assert noisy_grads.shape == x_grad.shape
104
+ return noisy_grads
105
+
106
+
107
+ def smoothgrad_torch(
108
+ input_tensor: torch.Tensor,
109
+ model: Callable[[torch.Tensor], torch.Tensor],
110
+ noise_stdev: float,
111
+ times: int,
112
+ idxs: Optional[TISMLocationsType] = None,
113
+ ) -> torch.Tensor:
114
+ """Custom implementation of SmoothGrad.
115
+ https://arxiv.org/pdf/1706.03825
116
+
117
+ NOTE: For simplicity, for now, we work with SINGLE TENSORS. Assume no batch dimension.
118
+
119
+ This replicates the input `times` times, and runs it through the network all at once.
120
+
121
+ TODO(joelshor): Add batching, for the situation where `times` is larger than the possible batch size
122
+ of a single inference with a network.
123
+ TODO(joelshor): Add ability to efficiently compute multiple inputs at once.
124
+
125
+ Args:
126
+ input_tensor (torch.Tensor): Input tensor. Doesn't have to be genomic. Should NOT be batched.
127
+ model: PyTorch model to use. The model must return a scalar per batch element.
128
+ noise_stdev: Noise to add.
129
+ times: Number of times to add noise.
130
+ idx: If present, only backprop to this location.
131
+
132
+ Returns:
133
+ Per-nucleotide smoothgrad.
134
+ """
135
+ noisy_grads = noisy_grads_torch(
136
+ input_tensor=input_tensor,
137
+ model=model,
138
+ noise_stdev=noise_stdev,
139
+ times=times,
140
+ idxs=idxs,
141
+ )
142
+
143
+ return np.mean(noisy_grads, axis=0)
144
+
145
+
146
+ # TODO(joelshor): Add `attribution_lib.py` test, taken from `malinois/model_def_test.py`.
147
+ def smoothgrad_tensor_to_dict(smooth_grad: torch.Tensor, vocab: list[str]) -> SmoothgradVocabType:
148
+ """Map the smoothgrad indices to the vocab."""
149
+ assert smooth_grad.ndim == 2
150
+ assert list(smooth_grad.shape)[0] == len(vocab)
151
+ def _to_dict(x: torch.Tensor) -> dict[str, torch.Tensor]:
152
+ return {vocab[i]: x[i] for i in range(len(vocab))}
153
+ return [_to_dict(x) for x in smooth_grad.T]
154
+
155
+
156
+ def smoothgrad_to_tism(sg: SmoothgradVocabType, base_seq: str) -> TISMOutputType:
157
+ """Returns result according to Taylor in-silico mutagenesis.
158
+
159
+ Paper: https://www.cell.com/iscience/fulltext/S2589-0042(24)02032-7"""
160
+ assert len(sg) == len(base_seq)
161
+
162
+ tism = []
163
+ for base_nt, sg_dict in zip(base_seq, sg):
164
+ cur_tism = {}
165
+ for nt, sg in sg_dict.items():
166
+ if nt == base_nt: continue
167
+ cur_tism[nt] = float(sg - sg_dict[base_nt])
168
+ tism.append(cur_tism)
169
+
170
+ return tism
171
+
172
+
173
+ def apply_gradient_mask(x: torch.Tensor, idxs: TISMLocationsType) -> tuple[torch.Tensor, torch.Tensor]:
174
+ """Applies a gradient mask to the input tensor.
175
+
176
+ NOTE: Do NOT just multiply by 0. This will run out of memory in large models.
177
+
178
+ Returns:
179
+ Tuple of (x, masked_x), where masked_x is the input tensor with the gradient mask applied.
180
+ """
181
+ assert min(idxs) >= 0
182
+ assert max(idxs) < x.shape[2]
183
+ assert x.ndim == 3, x.shape
184
+
185
+ no_gradient = x.clone().detach()
186
+ no_gradient.requires_grad = False
187
+
188
+ x_grad = x[:, :, idxs].clone().detach()
189
+ x_grad.requires_grad = True
190
+ x_grad_i = {idx: i for i, idx in enumerate(idxs)}
191
+
192
+ # Instead of using `torch.where`, we use this method to make our gradient tensor
193
+ # as small as possible, to preserve memory.
194
+ tensor_slices = [x_grad[:, :, x_grad_i[i]:x_grad_i[i]+1] if i in idxs
195
+ else no_gradient[:, :, i:i+1]
196
+ for i in range(no_gradient.shape[2])]
197
+ x = torch.concat(tensor_slices, dim=2)
198
+
199
+ return x, x_grad