ultrams 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.
- ultrams-0.1.0/LICENSE +202 -0
- ultrams-0.1.0/PKG-INFO +67 -0
- ultrams-0.1.0/README.md +50 -0
- ultrams-0.1.0/pyproject.toml +26 -0
- ultrams-0.1.0/setup.cfg +4 -0
- ultrams-0.1.0/src/ultrams/__init__.py +6 -0
- ultrams-0.1.0/src/ultrams/_architecture.py +251 -0
- ultrams-0.1.0/src/ultrams/inference.py +261 -0
- ultrams-0.1.0/src/ultrams.egg-info/PKG-INFO +67 -0
- ultrams-0.1.0/src/ultrams.egg-info/SOURCES.txt +11 -0
- ultrams-0.1.0/src/ultrams.egg-info/dependency_links.txt +1 -0
- ultrams-0.1.0/src/ultrams.egg-info/requires.txt +6 -0
- ultrams-0.1.0/src/ultrams.egg-info/top_level.txt +1 -0
ultrams-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.
|
ultrams-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ultrams
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: UltraMS spectrum representations and model inference
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/Dsadd4/UltraMS
|
|
7
|
+
Project-URL: Source, https://github.com/Dsadd4/UltraMS
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: numpy<3,>=1.24
|
|
12
|
+
Requires-Dist: torch>=2.1
|
|
13
|
+
Requires-Dist: transformers<5,>=4.33
|
|
14
|
+
Provides-Extra: hub
|
|
15
|
+
Requires-Dist: huggingface-hub<2,>=0.23; extra == "hub"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# UltraMS
|
|
19
|
+
|
|
20
|
+
Encode an MS/MS spectrum in three lines. Fine-tune the same encoder with your own labels.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install "ultrams[hub]"
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from ultrams import UltraMS
|
|
28
|
+
|
|
29
|
+
model = UltraMS.from_hub("dsadd4/UltraMS-RT-only")
|
|
30
|
+
embedding = model.encode(
|
|
31
|
+
mz=[100.1, 121.1, 150.0], intensity=[20, 100, 35], precursor_mz=301.2
|
|
32
|
+
).embedding # NumPy vector
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Fine-tune
|
|
36
|
+
|
|
37
|
+
`encode_tensor` keeps gradients. Add a task head and train the encoder and head together:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import torch
|
|
41
|
+
from ultrams import UltraMS
|
|
42
|
+
|
|
43
|
+
model = UltraMS.from_hub("dsadd4/UltraMS-RT-only").train()
|
|
44
|
+
head = torch.nn.Linear(model.embedding_dim, 1)
|
|
45
|
+
optimizer = torch.optim.AdamW([*model.parameters(), *head.parameters()], lr=1e-5)
|
|
46
|
+
|
|
47
|
+
for mz, intensity, precursor_mz, target in training_rows:
|
|
48
|
+
prediction = head(model.encode_tensor(mz, intensity, precursor_mz=precursor_mz))
|
|
49
|
+
loss = torch.nn.functional.mse_loss(prediction.flatten(), torch.tensor([target], dtype=torch.float32))
|
|
50
|
+
optimizer.zero_grad()
|
|
51
|
+
loss.backward()
|
|
52
|
+
optimizer.step()
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`training_rows` contains your labelled spectra. For MoNA or UltraAtlas fine-tuning, replace the model ID in the same code.
|
|
56
|
+
|
|
57
|
+
## Checkpoints
|
|
58
|
+
|
|
59
|
+
| Model | Hugging Face | Use |
|
|
60
|
+
| --- | --- | --- |
|
|
61
|
+
| RT-only D11 | [UltraMS-RT-only](https://huggingface.co/dsadd4/UltraMS-RT-only) | General MS/MS representation |
|
|
62
|
+
| MoNA contrastive | [UltraMS-MoNA](https://huggingface.co/dsadd4/UltraMS-MoNA) | MoNA spectrum similarity |
|
|
63
|
+
| UltraAtlas contrastive | [UltraMS-UltraAtlas](https://huggingface.co/dsadd4/UltraMS-UltraAtlas) | Figure 5 Atlas application |
|
|
64
|
+
|
|
65
|
+
All three can also be loaded from a downloaded `model.pt` with `UltraMS.from_checkpoint(path)`.
|
|
66
|
+
|
|
67
|
+
The current pure Ae3 pretraining and RT/ion-mode adaptation source is in [training/](training/).
|
ultrams-0.1.0/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
# UltraMS
|
|
2
|
+
|
|
3
|
+
Encode an MS/MS spectrum in three lines. Fine-tune the same encoder with your own labels.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install "ultrams[hub]"
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from ultrams import UltraMS
|
|
11
|
+
|
|
12
|
+
model = UltraMS.from_hub("dsadd4/UltraMS-RT-only")
|
|
13
|
+
embedding = model.encode(
|
|
14
|
+
mz=[100.1, 121.1, 150.0], intensity=[20, 100, 35], precursor_mz=301.2
|
|
15
|
+
).embedding # NumPy vector
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Fine-tune
|
|
19
|
+
|
|
20
|
+
`encode_tensor` keeps gradients. Add a task head and train the encoder and head together:
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import torch
|
|
24
|
+
from ultrams import UltraMS
|
|
25
|
+
|
|
26
|
+
model = UltraMS.from_hub("dsadd4/UltraMS-RT-only").train()
|
|
27
|
+
head = torch.nn.Linear(model.embedding_dim, 1)
|
|
28
|
+
optimizer = torch.optim.AdamW([*model.parameters(), *head.parameters()], lr=1e-5)
|
|
29
|
+
|
|
30
|
+
for mz, intensity, precursor_mz, target in training_rows:
|
|
31
|
+
prediction = head(model.encode_tensor(mz, intensity, precursor_mz=precursor_mz))
|
|
32
|
+
loss = torch.nn.functional.mse_loss(prediction.flatten(), torch.tensor([target], dtype=torch.float32))
|
|
33
|
+
optimizer.zero_grad()
|
|
34
|
+
loss.backward()
|
|
35
|
+
optimizer.step()
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`training_rows` contains your labelled spectra. For MoNA or UltraAtlas fine-tuning, replace the model ID in the same code.
|
|
39
|
+
|
|
40
|
+
## Checkpoints
|
|
41
|
+
|
|
42
|
+
| Model | Hugging Face | Use |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| RT-only D11 | [UltraMS-RT-only](https://huggingface.co/dsadd4/UltraMS-RT-only) | General MS/MS representation |
|
|
45
|
+
| MoNA contrastive | [UltraMS-MoNA](https://huggingface.co/dsadd4/UltraMS-MoNA) | MoNA spectrum similarity |
|
|
46
|
+
| UltraAtlas contrastive | [UltraMS-UltraAtlas](https://huggingface.co/dsadd4/UltraMS-UltraAtlas) | Figure 5 Atlas application |
|
|
47
|
+
|
|
48
|
+
All three can also be loaded from a downloaded `model.pt` with `UltraMS.from_checkpoint(path)`.
|
|
49
|
+
|
|
50
|
+
The current pure Ae3 pretraining and RT/ion-mode adaptation source is in [training/](training/).
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ultrams"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "UltraMS spectrum representations and model inference"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"numpy>=1.24,<3",
|
|
14
|
+
"torch>=2.1",
|
|
15
|
+
"transformers>=4.33,<5",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.urls]
|
|
19
|
+
Homepage = "https://github.com/Dsadd4/UltraMS"
|
|
20
|
+
Source = "https://github.com/Dsadd4/UltraMS"
|
|
21
|
+
|
|
22
|
+
[project.optional-dependencies]
|
|
23
|
+
hub = ["huggingface-hub>=0.23,<2"]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
where = ["src"]
|
ultrams-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
"""Inference architecture with the state-dict names of the UltraMS v9 trainer."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import torch
|
|
9
|
+
from torch import nn
|
|
10
|
+
from transformers import BertConfig, BertModel
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
MODEL_DEFAULTS: dict[str, Any] = {
|
|
14
|
+
"d_model": 1024,
|
|
15
|
+
"num_heads": 16,
|
|
16
|
+
"num_layers": 16,
|
|
17
|
+
"dim_feedforward": 4096,
|
|
18
|
+
"dropout": 0.1,
|
|
19
|
+
"max_peaks": 150,
|
|
20
|
+
"mz_range": (0, 2000),
|
|
21
|
+
"mz_bin_size": 0.1,
|
|
22
|
+
"int_bin_size": 0.1,
|
|
23
|
+
"mask_ratio": 0.15,
|
|
24
|
+
"mz_codebook_dim": 512,
|
|
25
|
+
"int_codebook_dim": 512,
|
|
26
|
+
"coarse_num": 2000,
|
|
27
|
+
"teacher_forcing_ratio": 0.0,
|
|
28
|
+
"difficulty_weight_alpha": 2.0,
|
|
29
|
+
"int_loss_weight": 0.1,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def model_config(saved: Mapping[str, Any] | None) -> dict[str, Any]:
|
|
34
|
+
result = dict(MODEL_DEFAULTS)
|
|
35
|
+
if isinstance(saved, Mapping):
|
|
36
|
+
for source in (saved, saved.get("model")):
|
|
37
|
+
if isinstance(source, Mapping):
|
|
38
|
+
for key in result:
|
|
39
|
+
if key in source:
|
|
40
|
+
result[key] = source[key]
|
|
41
|
+
result["mz_range"] = tuple(result["mz_range"])
|
|
42
|
+
return result
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SoftCodebookLookup(nn.Module):
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
num_codes: int,
|
|
49
|
+
d_out: int,
|
|
50
|
+
val_min: float = 0.0,
|
|
51
|
+
val_max: float = 1.0,
|
|
52
|
+
alpha_init: float = 0.1,
|
|
53
|
+
circular: bool = False,
|
|
54
|
+
) -> None:
|
|
55
|
+
super().__init__()
|
|
56
|
+
self.circular = circular
|
|
57
|
+
self.val_range = val_max - val_min
|
|
58
|
+
self.codebook = nn.Embedding(num_codes, d_out)
|
|
59
|
+
self.register_buffer("centers", torch.linspace(val_min, val_max, num_codes))
|
|
60
|
+
self.alpha = nn.Parameter(torch.full((num_codes,), alpha_init))
|
|
61
|
+
|
|
62
|
+
def forward(self, values: torch.Tensor) -> torch.Tensor:
|
|
63
|
+
diff = values.unsqueeze(-1) - self.centers
|
|
64
|
+
if self.circular:
|
|
65
|
+
abs_diff = diff.abs()
|
|
66
|
+
diff = torch.min(abs_diff, self.val_range - abs_diff)
|
|
67
|
+
weights = torch.softmax(-diff.pow(2) / (self.alpha.abs() + 1e-6), dim=-1)
|
|
68
|
+
return weights @ self.codebook.weight
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class MultiResolutionMzCodebook(nn.Module):
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
d_out: int,
|
|
75
|
+
mz_max: float = 2000.0,
|
|
76
|
+
l0_num: int = 200,
|
|
77
|
+
l1_num: int = 2000,
|
|
78
|
+
l2_num: int = 200,
|
|
79
|
+
l3_num: int = 200,
|
|
80
|
+
) -> None:
|
|
81
|
+
super().__init__()
|
|
82
|
+
d_each = d_out // 4
|
|
83
|
+
d_last = d_out - 3 * d_each
|
|
84
|
+
self.level0 = SoftCodebookLookup(l0_num, d_each, 0.0, mz_max, 100.0)
|
|
85
|
+
self.level1 = SoftCodebookLookup(l1_num, d_each, 0.0, mz_max, 1.0)
|
|
86
|
+
self.level2 = SoftCodebookLookup(l2_num, d_each, 0.0, 1.0, 0.01, True)
|
|
87
|
+
self.level3 = SoftCodebookLookup(l3_num, d_last, 0.0, 0.1, 0.001, True)
|
|
88
|
+
|
|
89
|
+
def forward(self, mz: torch.Tensor) -> torch.Tensor:
|
|
90
|
+
return torch.cat(
|
|
91
|
+
(
|
|
92
|
+
self.level0(mz),
|
|
93
|
+
self.level1(mz),
|
|
94
|
+
self.level2(torch.fmod(mz.abs(), 1.0)),
|
|
95
|
+
self.level3(torch.fmod(mz.abs(), 0.1)),
|
|
96
|
+
),
|
|
97
|
+
dim=-1,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class CodebookIntensityEmbedding(nn.Module):
|
|
102
|
+
def __init__(self, d_out: int, num_codes: int = 100, alpha_init: float = 0.1):
|
|
103
|
+
super().__init__()
|
|
104
|
+
self.lookup = SoftCodebookLookup(num_codes, d_out, 0.0, 1.0, alpha_init)
|
|
105
|
+
|
|
106
|
+
def forward(self, intensity: torch.Tensor) -> torch.Tensor:
|
|
107
|
+
return self.lookup(intensity)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class CodebookPeakEncoder(nn.Module):
|
|
111
|
+
def __init__(
|
|
112
|
+
self,
|
|
113
|
+
d_model: int,
|
|
114
|
+
mz_dim: int = 512,
|
|
115
|
+
int_dim: int = 512,
|
|
116
|
+
int_num_codes: int = 100,
|
|
117
|
+
mz_max: float = 2000.0,
|
|
118
|
+
coarse_num: int = 2000,
|
|
119
|
+
) -> None:
|
|
120
|
+
super().__init__()
|
|
121
|
+
self.mz_dim = mz_dim
|
|
122
|
+
self.int_dim = int_dim
|
|
123
|
+
self.mz_codebook = MultiResolutionMzCodebook(
|
|
124
|
+
mz_dim, mz_max=mz_max, l1_num=coarse_num
|
|
125
|
+
)
|
|
126
|
+
self.int_codebook = CodebookIntensityEmbedding(int_dim, int_num_codes)
|
|
127
|
+
self.mz_type_emb = nn.Parameter(torch.zeros(mz_dim))
|
|
128
|
+
self.int_type_emb = nn.Parameter(torch.zeros(int_dim))
|
|
129
|
+
self.proj = nn.Linear(mz_dim + int_dim, d_model)
|
|
130
|
+
|
|
131
|
+
def forward(self, peaks: torch.Tensor) -> torch.Tensor:
|
|
132
|
+
mz = self.mz_codebook(peaks[..., 0]) + self.mz_type_emb
|
|
133
|
+
intensity = self.int_codebook(peaks[..., 1]) + self.int_type_emb
|
|
134
|
+
return self.proj(torch.cat((mz, intensity), dim=-1))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class UltraMSBackbone(nn.Module):
|
|
138
|
+
"""The full pretraining model layout, with an inference-only forward path."""
|
|
139
|
+
|
|
140
|
+
def __init__(self, config: Mapping[str, Any]) -> None:
|
|
141
|
+
super().__init__()
|
|
142
|
+
self.max_peaks = int(config["max_peaks"])
|
|
143
|
+
self.mz_range = tuple(config["mz_range"])
|
|
144
|
+
self.mz_bin_size = float(config["mz_bin_size"])
|
|
145
|
+
self.mz_num_bins = int((self.mz_range[1] - self.mz_range[0]) / self.mz_bin_size) + 1
|
|
146
|
+
self.int_bin_size = float(config["int_bin_size"])
|
|
147
|
+
self.int_num_bins = int(1.0 / self.int_bin_size)
|
|
148
|
+
self.ms_start_idx = 2
|
|
149
|
+
self.mask_ratio = float(config["mask_ratio"])
|
|
150
|
+
self.int_loss_weight = float(config.get("int_loss_weight", 1.0))
|
|
151
|
+
self.teacher_forcing_ratio = 0.0
|
|
152
|
+
self.difficulty_weight_alpha = float(config.get("difficulty_weight_alpha", 2.0))
|
|
153
|
+
|
|
154
|
+
d_model = int(config["d_model"])
|
|
155
|
+
mz_dim = int(config["mz_codebook_dim"])
|
|
156
|
+
self.peak_encoder = CodebookPeakEncoder(
|
|
157
|
+
d_model=d_model,
|
|
158
|
+
mz_dim=mz_dim,
|
|
159
|
+
int_dim=int(config["int_codebook_dim"]),
|
|
160
|
+
mz_max=float(self.mz_range[1]),
|
|
161
|
+
coarse_num=int(config.get("coarse_num", 2000)),
|
|
162
|
+
)
|
|
163
|
+
self.cls_emb = nn.Parameter(torch.zeros(1, 1, d_model))
|
|
164
|
+
self.precursor_type_emb = nn.Parameter(torch.zeros(1, 1, d_model))
|
|
165
|
+
max_seq_len = self.max_peaks + 2
|
|
166
|
+
self.pos_emb = nn.Embedding(max_seq_len, d_model)
|
|
167
|
+
mz_precision = 1.0
|
|
168
|
+
vocab_size = 13 + len(torch.arange(*self.mz_range, mz_precision))
|
|
169
|
+
bert_config = BertConfig(
|
|
170
|
+
vocab_size=vocab_size,
|
|
171
|
+
hidden_size=d_model,
|
|
172
|
+
num_hidden_layers=int(config["num_layers"]),
|
|
173
|
+
num_attention_heads=int(config["num_heads"]),
|
|
174
|
+
intermediate_size=int(config["dim_feedforward"]),
|
|
175
|
+
hidden_dropout_prob=float(config["dropout"]),
|
|
176
|
+
attention_probs_dropout_prob=float(config["dropout"]),
|
|
177
|
+
max_position_embeddings=max(max_seq_len * 2, 512),
|
|
178
|
+
layer_norm_eps=1e-6,
|
|
179
|
+
is_decoder=False,
|
|
180
|
+
add_cross_attention=False,
|
|
181
|
+
)
|
|
182
|
+
self.encoder = BertModel(bert_config, add_pooling_layer=False)
|
|
183
|
+
self.encoder.embeddings.word_embeddings.requires_grad_(False)
|
|
184
|
+
self.dropout = nn.Dropout(float(config["dropout"]))
|
|
185
|
+
self.mz_level0_bins = 200
|
|
186
|
+
self.mz_level1_bins = 10
|
|
187
|
+
self.mz_level2_bins = 10
|
|
188
|
+
self.register_buffer("level0_centers", torch.linspace(5.0, 1995.0, 200))
|
|
189
|
+
self.register_buffer("level1_offsets", torch.linspace(0.5, 9.5, 10))
|
|
190
|
+
self.register_buffer("level2_offsets", torch.linspace(0.05, 0.95, 10))
|
|
191
|
+
self.mz_level0_head = nn.Linear(d_model, self.mz_level0_bins)
|
|
192
|
+
self.mz_level1_head = nn.Sequential(
|
|
193
|
+
nn.Linear(d_model + mz_dim, d_model // 2),
|
|
194
|
+
nn.GELU(),
|
|
195
|
+
nn.Linear(d_model // 2, self.mz_level1_bins),
|
|
196
|
+
)
|
|
197
|
+
self.mz_level2_head = nn.Sequential(
|
|
198
|
+
nn.Linear(d_model + mz_dim, d_model // 2),
|
|
199
|
+
nn.GELU(),
|
|
200
|
+
nn.Linear(d_model // 2, self.mz_level2_bins),
|
|
201
|
+
)
|
|
202
|
+
self.int_predictor = nn.Linear(d_model, self.int_num_bins)
|
|
203
|
+
|
|
204
|
+
def encode(
|
|
205
|
+
self, spectra: torch.Tensor, attention_mask: torch.Tensor, precursor_mz: torch.Tensor
|
|
206
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
207
|
+
batch_size = spectra.shape[0]
|
|
208
|
+
peak_embeddings = self.peak_encoder(spectra)
|
|
209
|
+
cls_embedding = self.cls_emb.expand(batch_size, 1, -1)
|
|
210
|
+
precursor_input = torch.stack(
|
|
211
|
+
(precursor_mz, torch.full_like(precursor_mz, 1.1)), dim=-1
|
|
212
|
+
).unsqueeze(1)
|
|
213
|
+
precursor_embedding = self.peak_encoder(precursor_input) + self.precursor_type_emb
|
|
214
|
+
embeddings = torch.cat((cls_embedding, precursor_embedding, peak_embeddings), dim=1)
|
|
215
|
+
positions = torch.arange(embeddings.shape[1], device=spectra.device).unsqueeze(0)
|
|
216
|
+
embeddings = self.dropout(embeddings + self.pos_emb(positions))
|
|
217
|
+
prefix_attention = torch.ones(
|
|
218
|
+
batch_size, 2, dtype=attention_mask.dtype, device=spectra.device
|
|
219
|
+
)
|
|
220
|
+
full_attention = torch.cat((prefix_attention, attention_mask), dim=1)
|
|
221
|
+
hidden = self.encoder(
|
|
222
|
+
inputs_embeds=embeddings, attention_mask=full_attention
|
|
223
|
+
).last_hidden_state
|
|
224
|
+
return hidden, hidden[:, 0, :]
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class _Head(nn.Module):
|
|
228
|
+
def __init__(self, d_model: int) -> None:
|
|
229
|
+
super().__init__()
|
|
230
|
+
self.head = nn.Sequential(
|
|
231
|
+
nn.Linear(d_model, d_model // 2),
|
|
232
|
+
nn.GELU(),
|
|
233
|
+
nn.LayerNorm(d_model // 2),
|
|
234
|
+
nn.Linear(d_model // 2, 1),
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
def forward(self, cls_embedding: torch.Tensor) -> torch.Tensor:
|
|
238
|
+
return self.head(cls_embedding).squeeze(-1)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class UltraMSWithHeads(nn.Module):
|
|
242
|
+
def __init__(self, config: Mapping[str, Any]) -> None:
|
|
243
|
+
super().__init__()
|
|
244
|
+
self.base = UltraMSBackbone(config)
|
|
245
|
+
self.rt_head = _Head(int(config["d_model"]))
|
|
246
|
+
self.pol_head = _Head(int(config["d_model"]))
|
|
247
|
+
|
|
248
|
+
def encode(
|
|
249
|
+
self, spectra: torch.Tensor, attention_mask: torch.Tensor, precursor_mz: torch.Tensor
|
|
250
|
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
|
251
|
+
return self.base.encode(spectra, attention_mask, precursor_mz)
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""Load an UltraMS checkpoint and encode one MS/MS spectrum."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from itertools import chain
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import torch
|
|
12
|
+
import torch.nn.functional as F
|
|
13
|
+
|
|
14
|
+
from ._architecture import UltraMSBackbone, UltraMSWithHeads, model_config
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class SpectrumEmbedding:
|
|
19
|
+
cls: np.ndarray
|
|
20
|
+
peak_intensity_weighted: np.ndarray
|
|
21
|
+
fusion: np.ndarray
|
|
22
|
+
projection: np.ndarray | None = None
|
|
23
|
+
rt_seconds: float | None = None
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def embedding(self) -> np.ndarray:
|
|
27
|
+
"""The model-specific representation used for similarity search."""
|
|
28
|
+
return self.projection if self.projection is not None else self.cls
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _prepare_spectrum(
|
|
32
|
+
mz: Any, intensity: Any, max_peaks: int
|
|
33
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
34
|
+
mz_array = np.asarray(mz, dtype=np.float32)
|
|
35
|
+
intensity_array = np.asarray(intensity, dtype=np.float32)
|
|
36
|
+
if mz_array.ndim != 1 or intensity_array.ndim != 1 or len(mz_array) != len(intensity_array):
|
|
37
|
+
raise ValueError("mz and intensity must be one-dimensional arrays of equal length")
|
|
38
|
+
if not np.isfinite(mz_array).all() or not np.isfinite(intensity_array).all():
|
|
39
|
+
raise ValueError("mz and intensity must contain finite values")
|
|
40
|
+
valid = mz_array > 0
|
|
41
|
+
mz_array = mz_array[valid]
|
|
42
|
+
intensity_array = intensity_array[valid]
|
|
43
|
+
if len(mz_array) < 3:
|
|
44
|
+
raise ValueError("a spectrum needs at least three peaks with positive m/z")
|
|
45
|
+
maximum = intensity_array.max()
|
|
46
|
+
if maximum > 0:
|
|
47
|
+
intensity_array = intensity_array / maximum
|
|
48
|
+
intensity_array = np.clip(intensity_array, 0, 1)
|
|
49
|
+
if len(mz_array) > max_peaks:
|
|
50
|
+
selected = np.argsort(intensity_array)[-max_peaks:]
|
|
51
|
+
selected = np.sort(selected)
|
|
52
|
+
mz_array = mz_array[selected]
|
|
53
|
+
intensity_array = intensity_array[selected]
|
|
54
|
+
order = np.argsort(mz_array)
|
|
55
|
+
peaks = np.stack((mz_array[order], intensity_array[order]), axis=-1).astype(np.float32)
|
|
56
|
+
mask = np.ones(len(peaks), dtype=np.int64)
|
|
57
|
+
return peaks, mask
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _checkpoint_state(
|
|
61
|
+
payload: Any,
|
|
62
|
+
) -> tuple[dict[str, torch.Tensor], dict[str, Any], int, str, torch.nn.Module | None]:
|
|
63
|
+
if not isinstance(payload, dict):
|
|
64
|
+
raise ValueError("checkpoint must be a mapping")
|
|
65
|
+
model_family = "base"
|
|
66
|
+
projection = None
|
|
67
|
+
if "encoder_state_dict" in payload:
|
|
68
|
+
state = payload["encoder_state_dict"]
|
|
69
|
+
if "proj_state_dict" in payload:
|
|
70
|
+
model_family = "atlas"
|
|
71
|
+
projection = _atlas_projection(payload["proj_state_dict"])
|
|
72
|
+
elif "projection_state_dict" in payload:
|
|
73
|
+
model_family = "mona"
|
|
74
|
+
projection = _mona_projection(payload["projection_state_dict"])
|
|
75
|
+
else:
|
|
76
|
+
raise ValueError("encoder checkpoint has no projection state")
|
|
77
|
+
else:
|
|
78
|
+
state = payload.get("model_state_dict")
|
|
79
|
+
if state is None:
|
|
80
|
+
state = payload.get("base_state_dict")
|
|
81
|
+
if not isinstance(state, dict) or not state:
|
|
82
|
+
raise ValueError("checkpoint has no supported model state")
|
|
83
|
+
if all(key.startswith("module.") for key in state):
|
|
84
|
+
state = {key[len("module."):]: value for key, value in state.items()}
|
|
85
|
+
if not all(isinstance(key, str) and isinstance(value, torch.Tensor) for key, value in state.items()):
|
|
86
|
+
raise ValueError("checkpoint state must contain named tensors")
|
|
87
|
+
saved_config = payload.get("config")
|
|
88
|
+
config = model_config(saved_config)
|
|
89
|
+
first_key = "base.pos_emb.weight" if any(key.startswith("base.") for key in state) else "pos_emb.weight"
|
|
90
|
+
if first_key in state:
|
|
91
|
+
config["max_peaks"] = int(state[first_key].shape[0]) - 2
|
|
92
|
+
input_max_peaks = config["max_peaks"]
|
|
93
|
+
if model_family == "mona" and isinstance(saved_config, dict):
|
|
94
|
+
input_max_peaks = int(saved_config.get("max_peaks", 100))
|
|
95
|
+
return state, config, input_max_peaks, model_family, projection
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _mona_projection(state: Any) -> torch.nn.Module:
|
|
99
|
+
if not isinstance(state, dict):
|
|
100
|
+
raise ValueError("MoNA checkpoint has no projection weights")
|
|
101
|
+
if set(state) == {"weight", "bias"}:
|
|
102
|
+
size = int(state["weight"].shape[1])
|
|
103
|
+
projection: torch.nn.Module = torch.nn.Linear(size, size)
|
|
104
|
+
elif "1.weight" in state and "4.weight" in state:
|
|
105
|
+
size = int(state["1.weight"].shape[1])
|
|
106
|
+
hidden = int(state["1.weight"].shape[0])
|
|
107
|
+
projection = torch.nn.Sequential(
|
|
108
|
+
torch.nn.LayerNorm(size),
|
|
109
|
+
torch.nn.Linear(size, hidden),
|
|
110
|
+
torch.nn.GELU(),
|
|
111
|
+
torch.nn.Dropout(0.0),
|
|
112
|
+
torch.nn.Linear(hidden, size),
|
|
113
|
+
)
|
|
114
|
+
else:
|
|
115
|
+
raise ValueError("unrecognized MoNA projection layout")
|
|
116
|
+
projection.load_state_dict(state, strict=True)
|
|
117
|
+
return projection.eval()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _atlas_projection(state: Any) -> torch.nn.Module:
|
|
121
|
+
if not isinstance(state, dict) or "net.3.weight" not in state:
|
|
122
|
+
raise ValueError("unrecognized UltraAtlas projection layout")
|
|
123
|
+
hidden = int(state["net.1.weight"].shape[0])
|
|
124
|
+
output = int(state["net.3.weight"].shape[0])
|
|
125
|
+
projection = torch.nn.Sequential(
|
|
126
|
+
torch.nn.LayerNorm(hidden),
|
|
127
|
+
torch.nn.Linear(hidden, hidden),
|
|
128
|
+
torch.nn.GELU(),
|
|
129
|
+
torch.nn.Linear(hidden, output),
|
|
130
|
+
)
|
|
131
|
+
named_state = {key.removeprefix("net."): value for key, value in state.items()}
|
|
132
|
+
projection.load_state_dict(named_state, strict=True)
|
|
133
|
+
return projection.eval()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class UltraMS:
|
|
137
|
+
"""Inference wrapper for the pretraining and RT/polarity model layouts."""
|
|
138
|
+
|
|
139
|
+
def __init__(
|
|
140
|
+
self,
|
|
141
|
+
model: UltraMSBackbone | UltraMSWithHeads,
|
|
142
|
+
config: dict[str, Any],
|
|
143
|
+
input_max_peaks: int,
|
|
144
|
+
model_family: str,
|
|
145
|
+
projection: torch.nn.Module | None,
|
|
146
|
+
):
|
|
147
|
+
self.model = model.eval()
|
|
148
|
+
self.config = config
|
|
149
|
+
self.input_max_peaks = input_max_peaks
|
|
150
|
+
self.model_family = model_family
|
|
151
|
+
self.projection = projection
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def embedding_dim(self) -> int:
|
|
155
|
+
if self.projection is not None:
|
|
156
|
+
for layer in reversed(list(self.projection.modules())):
|
|
157
|
+
if isinstance(layer, torch.nn.Linear):
|
|
158
|
+
return layer.out_features
|
|
159
|
+
return int(self.config["d_model"])
|
|
160
|
+
|
|
161
|
+
def parameters(self):
|
|
162
|
+
"""Parameters of the encoder and its optional contrastive projection."""
|
|
163
|
+
return chain(
|
|
164
|
+
self.model.parameters(),
|
|
165
|
+
self.projection.parameters() if self.projection is not None else (),
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def train(self) -> "UltraMS":
|
|
169
|
+
self.model.train()
|
|
170
|
+
if self.projection is not None:
|
|
171
|
+
self.projection.train()
|
|
172
|
+
return self
|
|
173
|
+
|
|
174
|
+
def eval(self) -> "UltraMS":
|
|
175
|
+
self.model.eval()
|
|
176
|
+
if self.projection is not None:
|
|
177
|
+
self.projection.eval()
|
|
178
|
+
return self
|
|
179
|
+
|
|
180
|
+
def encode_tensor(
|
|
181
|
+
self, mz: Any, intensity: Any, *, precursor_mz: float
|
|
182
|
+
) -> torch.Tensor:
|
|
183
|
+
"""Differentiable model embedding of one spectrum, shape ``(1, embedding_dim)``."""
|
|
184
|
+
peaks, attention = _prepare_spectrum(mz, intensity, self.input_max_peaks)
|
|
185
|
+
if not np.isfinite(precursor_mz) or precursor_mz <= 0:
|
|
186
|
+
raise ValueError("precursor_mz must be a positive finite number")
|
|
187
|
+
device = next(self.model.parameters()).device
|
|
188
|
+
spectra = torch.as_tensor(peaks, device=device).unsqueeze(0)
|
|
189
|
+
mask = torch.as_tensor(attention, device=device).unsqueeze(0)
|
|
190
|
+
precursor = torch.tensor([precursor_mz], dtype=torch.float32, device=device)
|
|
191
|
+
_, cls = self.model.encode(spectra, mask, precursor)
|
|
192
|
+
embedding = self.projection(cls) if self.projection is not None else cls
|
|
193
|
+
return F.normalize(embedding.float(), dim=-1)
|
|
194
|
+
|
|
195
|
+
@classmethod
|
|
196
|
+
def from_checkpoint(
|
|
197
|
+
cls, checkpoint: str | Path, *, device: str | torch.device = "cpu"
|
|
198
|
+
) -> "UltraMS":
|
|
199
|
+
path = Path(checkpoint).expanduser()
|
|
200
|
+
payload = torch.load(path, map_location="cpu", weights_only=False)
|
|
201
|
+
state, config, input_max_peaks, model_family, projection = _checkpoint_state(payload)
|
|
202
|
+
unified = any(key.startswith("base.") for key in state)
|
|
203
|
+
model = UltraMSWithHeads(config) if unified else UltraMSBackbone(config)
|
|
204
|
+
model.load_state_dict(state, strict=True)
|
|
205
|
+
model.to(torch.device(device))
|
|
206
|
+
if projection is not None:
|
|
207
|
+
projection.to(torch.device(device))
|
|
208
|
+
return cls(model, config, input_max_peaks, model_family, projection)
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def from_hub(
|
|
212
|
+
cls,
|
|
213
|
+
repo_id: str,
|
|
214
|
+
*,
|
|
215
|
+
filename: str = "model.pt",
|
|
216
|
+
revision: str | None = None,
|
|
217
|
+
device: str | torch.device = "cpu",
|
|
218
|
+
) -> "UltraMS":
|
|
219
|
+
try:
|
|
220
|
+
from huggingface_hub import hf_hub_download
|
|
221
|
+
except ImportError as exc:
|
|
222
|
+
raise ImportError("Hugging Face downloads require pip install 'ultrams[hub]'") from exc
|
|
223
|
+
path = hf_hub_download(repo_id=repo_id, filename=filename, revision=revision)
|
|
224
|
+
return cls.from_checkpoint(path, device=device)
|
|
225
|
+
|
|
226
|
+
@torch.inference_mode()
|
|
227
|
+
def encode(
|
|
228
|
+
self, mz: Any, intensity: Any, *, precursor_mz: float
|
|
229
|
+
) -> SpectrumEmbedding:
|
|
230
|
+
peaks, attention = _prepare_spectrum(mz, intensity, self.input_max_peaks)
|
|
231
|
+
if not np.isfinite(precursor_mz) or precursor_mz <= 0:
|
|
232
|
+
raise ValueError("precursor_mz must be a positive finite number")
|
|
233
|
+
device = next(self.model.parameters()).device
|
|
234
|
+
spectra = torch.as_tensor(peaks, device=device).unsqueeze(0)
|
|
235
|
+
mask = torch.as_tensor(attention, device=device).unsqueeze(0)
|
|
236
|
+
precursor = torch.tensor([precursor_mz], dtype=torch.float32, device=device)
|
|
237
|
+
hidden, raw_cls = self.model.encode(spectra, mask, precursor)
|
|
238
|
+
peak_hidden = hidden[:, 2 : 2 + spectra.shape[1]]
|
|
239
|
+
weights = spectra[:, :, 1] * mask.float()
|
|
240
|
+
weighted = (peak_hidden * weights.unsqueeze(-1)).sum(1) / weights.sum(
|
|
241
|
+
1, keepdim=True
|
|
242
|
+
).clamp_min(1e-8)
|
|
243
|
+
cls = F.normalize(raw_cls.float(), dim=-1)
|
|
244
|
+
weighted = F.normalize(weighted.float(), dim=-1)
|
|
245
|
+
projected = None
|
|
246
|
+
if self.projection is not None:
|
|
247
|
+
projected = self.projection(raw_cls)
|
|
248
|
+
if self.model_family == "atlas":
|
|
249
|
+
projected = F.normalize(projected, dim=-1)
|
|
250
|
+
fusion_cls = F.normalize(projected.float(), dim=-1) if self.model_family == "mona" else cls
|
|
251
|
+
fusion = F.normalize(torch.cat((fusion_cls, weighted), dim=-1), dim=-1)
|
|
252
|
+
rt_seconds = None
|
|
253
|
+
if isinstance(self.model, UltraMSWithHeads):
|
|
254
|
+
rt_seconds = float(self.model.rt_head(hidden[:, 0])[0] * 600.0)
|
|
255
|
+
return SpectrumEmbedding(
|
|
256
|
+
cls=cls[0].cpu().numpy(),
|
|
257
|
+
peak_intensity_weighted=weighted[0].cpu().numpy(),
|
|
258
|
+
fusion=fusion[0].cpu().numpy(),
|
|
259
|
+
projection=projected[0].cpu().numpy() if projected is not None else None,
|
|
260
|
+
rt_seconds=rt_seconds,
|
|
261
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ultrams
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: UltraMS spectrum representations and model inference
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://github.com/Dsadd4/UltraMS
|
|
7
|
+
Project-URL: Source, https://github.com/Dsadd4/UltraMS
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: numpy<3,>=1.24
|
|
12
|
+
Requires-Dist: torch>=2.1
|
|
13
|
+
Requires-Dist: transformers<5,>=4.33
|
|
14
|
+
Provides-Extra: hub
|
|
15
|
+
Requires-Dist: huggingface-hub<2,>=0.23; extra == "hub"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# UltraMS
|
|
19
|
+
|
|
20
|
+
Encode an MS/MS spectrum in three lines. Fine-tune the same encoder with your own labels.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install "ultrams[hub]"
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from ultrams import UltraMS
|
|
28
|
+
|
|
29
|
+
model = UltraMS.from_hub("dsadd4/UltraMS-RT-only")
|
|
30
|
+
embedding = model.encode(
|
|
31
|
+
mz=[100.1, 121.1, 150.0], intensity=[20, 100, 35], precursor_mz=301.2
|
|
32
|
+
).embedding # NumPy vector
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Fine-tune
|
|
36
|
+
|
|
37
|
+
`encode_tensor` keeps gradients. Add a task head and train the encoder and head together:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import torch
|
|
41
|
+
from ultrams import UltraMS
|
|
42
|
+
|
|
43
|
+
model = UltraMS.from_hub("dsadd4/UltraMS-RT-only").train()
|
|
44
|
+
head = torch.nn.Linear(model.embedding_dim, 1)
|
|
45
|
+
optimizer = torch.optim.AdamW([*model.parameters(), *head.parameters()], lr=1e-5)
|
|
46
|
+
|
|
47
|
+
for mz, intensity, precursor_mz, target in training_rows:
|
|
48
|
+
prediction = head(model.encode_tensor(mz, intensity, precursor_mz=precursor_mz))
|
|
49
|
+
loss = torch.nn.functional.mse_loss(prediction.flatten(), torch.tensor([target], dtype=torch.float32))
|
|
50
|
+
optimizer.zero_grad()
|
|
51
|
+
loss.backward()
|
|
52
|
+
optimizer.step()
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`training_rows` contains your labelled spectra. For MoNA or UltraAtlas fine-tuning, replace the model ID in the same code.
|
|
56
|
+
|
|
57
|
+
## Checkpoints
|
|
58
|
+
|
|
59
|
+
| Model | Hugging Face | Use |
|
|
60
|
+
| --- | --- | --- |
|
|
61
|
+
| RT-only D11 | [UltraMS-RT-only](https://huggingface.co/dsadd4/UltraMS-RT-only) | General MS/MS representation |
|
|
62
|
+
| MoNA contrastive | [UltraMS-MoNA](https://huggingface.co/dsadd4/UltraMS-MoNA) | MoNA spectrum similarity |
|
|
63
|
+
| UltraAtlas contrastive | [UltraMS-UltraAtlas](https://huggingface.co/dsadd4/UltraMS-UltraAtlas) | Figure 5 Atlas application |
|
|
64
|
+
|
|
65
|
+
All three can also be loaded from a downloaded `model.pt` with `UltraMS.from_checkpoint(path)`.
|
|
66
|
+
|
|
67
|
+
The current pure Ae3 pretraining and RT/ion-mode adaptation source is in [training/](training/).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/ultrams/__init__.py
|
|
5
|
+
src/ultrams/_architecture.py
|
|
6
|
+
src/ultrams/inference.py
|
|
7
|
+
src/ultrams.egg-info/PKG-INFO
|
|
8
|
+
src/ultrams.egg-info/SOURCES.txt
|
|
9
|
+
src/ultrams.egg-info/dependency_links.txt
|
|
10
|
+
src/ultrams.egg-info/requires.txt
|
|
11
|
+
src/ultrams.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ultrams
|