salt-ml 0.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
salt/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.6"
salt/main.py ADDED
@@ -0,0 +1,31 @@
1
+ """Top level training script, powered by the lightning CLI."""
2
+
3
+ import pathlib
4
+
5
+ import comet_ml # noqa: F401
6
+ from lightning.pytorch.cli import ArgsType
7
+
8
+ from salt.callbacks import SaveConfigCallback
9
+ from salt.data.datamodules import SaltDataModule
10
+ from salt.modelwrapper import ModelWrapper
11
+ from salt.utils.cli import SaltCLI
12
+
13
+
14
+ def main(args: ArgsType = None) -> None:
15
+ config_dir = pathlib.Path(__file__).parent / "configs"
16
+
17
+ SaltCLI(
18
+ model_class=ModelWrapper,
19
+ datamodule_class=SaltDataModule,
20
+ save_config_callback=SaveConfigCallback,
21
+ args=args,
22
+ parser_kwargs={
23
+ "default_env": True,
24
+ "fit": {"default_config_files": [f"{config_dir}/base.yaml"]},
25
+ "test": {"default_config_files": [f"{config_dir}/base.yaml"]},
26
+ },
27
+ )
28
+
29
+
30
+ if __name__ == "__main__":
31
+ main()
salt/modelwrapper.py ADDED
@@ -0,0 +1,252 @@
1
+ import math
2
+ import warnings
3
+ from collections.abc import Mapping
4
+
5
+ import lightning as L
6
+ import torch
7
+ from torch import nn
8
+
9
+ from salt.models import InputNorm
10
+
11
+
12
+ def check_unique(modules: nn.ModuleList, attr_name: str) -> None:
13
+ assert len({getattr(m, attr_name) for m in modules}) == len(
14
+ modules
15
+ ), f"Attribute '{attr_name}' must be unique for class {modules[0].__class__.__name__}"
16
+
17
+
18
+ class ModelWrapper(L.LightningModule):
19
+ def __init__(
20
+ self,
21
+ model: nn.Module,
22
+ lrs_config: Mapping[str, float],
23
+ global_object: str,
24
+ norm_config: dict | None = None,
25
+ name: str = "salt",
26
+ muP_config: dict | None = None,
27
+ loss_mode: str = "wsum",
28
+ ):
29
+ """A wrapper class for any model implemented in Salt.
30
+
31
+ This wrapper class allows is as generic as possible. It wraps
32
+ [`SaltModel`][salt.models.SaltModel], but could also be used to
33
+ wrap any other model if you want to do train something that doesn't
34
+ fit into the [`SaltModel`][salt.models.SaltModel] architecture.
35
+
36
+ This class is responsible for containing things that are common to all
37
+ salt models. These are:
38
+
39
+ - A generic forward pass, including input normalisation
40
+ - Training, validation and test steps, which include logging
41
+ - Some sanity checks on the model configuration
42
+
43
+ Parameters
44
+ ----------
45
+ model : nn.Module
46
+ Model to be wrapped
47
+ lrs_config: Mapping
48
+ LRS config which has to be set manually for now
49
+ https://github.com/omni-us/jsonargparse/issues/170#issuecomment-1288167674
50
+ global_object : str
51
+ Name of the global input object, as opposed to the constituent-level
52
+ inputs. This argument is set automatically by the framework.
53
+ norm_config : dict, optional
54
+ Keyword arguments for [`salt.models.InputNorm`][salt.models.InputNorm].
55
+ name: str, optional
56
+ Name of the model, used for logging and inference output names
57
+ muP_config: dict, optional
58
+ The muP configuration.
59
+ loss_mode: str, optional
60
+ The loss mode to use. Default is "wsum" (weighted sum).
61
+ Other options are
62
+ - 'GLS' : arxiv.org/1904.08492
63
+ """
64
+ super().__init__()
65
+ with warnings.catch_warnings():
66
+ warnings.simplefilter("ignore")
67
+ self.save_hyperparameters(logger=False)
68
+
69
+ self.model = model
70
+ self.lrs_config = lrs_config
71
+ self.global_object = global_object
72
+ self.name = name
73
+ self.muP = muP_config or {}
74
+ self.last_val_batch_outs = None
75
+ # Here the model should pick it up
76
+ if self.muP:
77
+ from salt.utils.muP_utils.configuration_muP import instantiate_mup
78
+
79
+ load_path = None
80
+ if "shape_path" in self.muP:
81
+ load_path = self.muP["shape_path"]
82
+ instantiate_mup(model, load_path)
83
+
84
+ # all tasks should inherit the global object type and model name
85
+ self.model.global_object = self.global_object
86
+ for task in self.model.tasks:
87
+ task.global_object = self.global_object
88
+ task.model_name = self.name
89
+
90
+ # ensure unique names for init_nets and tasks
91
+ check_unique(self.model.init_nets, "input_name")
92
+ check_unique(self.model.tasks, "name")
93
+
94
+ # check that the model has the same output size for all init nets
95
+ assert len({t.net.output_size for t in self.model.init_nets if t.input_name != "EDGE"}) == 1
96
+
97
+ # create input normaliser
98
+ assert norm_config is not None
99
+ self.norm = InputNorm(**norm_config)
100
+ allowed_loss_modes = ["wsum", "GLS"]
101
+ assert loss_mode in allowed_loss_modes, f"Loss mode must be one of {allowed_loss_modes}"
102
+ self.loss_mode = loss_mode
103
+ if loss_mode == "GLS":
104
+ assert all(
105
+ task.weight == 1.0 for task in self.model.tasks
106
+ ), "GLS does not utilise task weights - remove all/set to 1"
107
+
108
+ def total_loss(self, loss: dict):
109
+ """Computes the final loss based on the loss mode."""
110
+ if self.loss_mode == "GLS":
111
+ # Calculate the geometric mean of the losses
112
+ loss_prod = math.prod(subloss for subloss in loss.values())
113
+ return torch.pow(loss_prod, 1.0 / len(loss))
114
+
115
+ # Return the default weighted sum
116
+ return sum(subloss for subloss in loss.values())
117
+
118
+ def forward(self, inputs, pad_masks=None, labels=None):
119
+ """Generic forward pass through any salt-compatible model.
120
+
121
+ This function performs input normalisation and then calls the `self.model`'s
122
+ forward pass. Don't call this method directy, instead use `__call__`.
123
+
124
+ Parameters
125
+ ----------
126
+ inputs
127
+ Any generic input to the model.
128
+ pad_masks
129
+ Input padding masks.
130
+ labels
131
+ Training targets. If not specified, assume we are running model inference
132
+ (i.e. no loss computation).
133
+
134
+ Returns
135
+ -------
136
+ Whatever is returned by `self.model`'s forward pass.
137
+ """
138
+ x = self.norm(inputs)
139
+ return self.model(x, pad_masks, labels)
140
+
141
+ def shared_step(self, batch, evaluation=False):
142
+ """Function used to unpack the batch, run the forward pass, and compute
143
+ losses, used by training, validation and test steps.
144
+
145
+ Parameters
146
+ ----------
147
+ batch : tuple
148
+ A single batch of inputs, pad_masks and labels
149
+ evaluation : bool
150
+ If true, don't compute the losses and return early
151
+
152
+ Returns
153
+ -------
154
+ preds
155
+ Model predictions
156
+ labels
157
+ True labels
158
+ loss
159
+ Reduced loss over the input batch
160
+ """
161
+ # unpack the batch
162
+ inputs, pad_masks, labels = batch
163
+
164
+ # forward pass through model
165
+ preds, loss = self(inputs, pad_masks, labels)
166
+
167
+ if evaluation:
168
+ return preds, labels, pad_masks, None
169
+
170
+ # compute total loss
171
+ loss["loss"] = self.total_loss(loss)
172
+
173
+ return preds, labels, pad_masks, loss
174
+
175
+ def log_losses(self, loss, stage):
176
+ kwargs = {"sync_dist": len(self.trainer.device_ids) > 1}
177
+ self.log(f"{stage}_loss", loss["loss"], **kwargs)
178
+ for t, loss_value in loss.items():
179
+ n = f"{stage}_{t}_loss" if "loss" not in t else f"{stage}_{t}"
180
+ self.log(n, loss_value, **kwargs)
181
+
182
+ def training_step(self, batch):
183
+ # foward pass
184
+ preds, labels, pad_masks, loss = self.shared_step(batch)
185
+
186
+ if loss["loss"].isnan():
187
+ raise RuntimeError(
188
+ "Loss is NaN - this indicates something significant has gone wrong."
189
+ "Check for any NaNs or infs in the input dataset. If nothing is found here, "
190
+ "check 'docs/training.md - NaNs' for more information"
191
+ )
192
+
193
+ # log losses
194
+ self.log_losses(loss, stage="train")
195
+
196
+ outputs = {
197
+ "preds": preds,
198
+ "labels": labels,
199
+ "pad_masks": pad_masks,
200
+ }
201
+
202
+ return {**loss, "outputs": outputs}
203
+
204
+ def validation_step(self, batch):
205
+ # foward pass
206
+ preds, labels, pad_masks, loss = self.shared_step(batch)
207
+
208
+ # log losses
209
+ self.log_losses(loss, stage="val")
210
+
211
+ # Store outputs to be used by the MaskformerMetrics callback
212
+ outputs = {
213
+ "preds": preds,
214
+ "labels": labels,
215
+ "pad_masks": pad_masks,
216
+ }
217
+
218
+ return {**loss, "outputs": outputs}
219
+
220
+ def test_step(self, batch):
221
+ inputs, pad_masks, _ = batch
222
+ batch = (inputs, pad_masks, None)
223
+ return self.shared_step(batch, evaluation=True)[0]
224
+
225
+ def configure_optimizers(self):
226
+ if self.muP:
227
+ from mup import MuAdamW as AdamW
228
+ else:
229
+ from torch.optim import AdamW
230
+ opt = AdamW(
231
+ self.parameters(),
232
+ lr=self.lrs_config["initial"],
233
+ weight_decay=self.lrs_config.get("weight_decay", 1e-5),
234
+ )
235
+
236
+ # 1cycle
237
+ sch = torch.optim.lr_scheduler.OneCycleLR(
238
+ opt,
239
+ max_lr=self.lrs_config["max"],
240
+ total_steps=self.trainer.estimated_stepping_batches,
241
+ div_factor=self.lrs_config["max"] / self.lrs_config["initial"],
242
+ final_div_factor=self.lrs_config["initial"] / self.lrs_config["end"],
243
+ pct_start=float(self.lrs_config["pct_start"]),
244
+ last_epoch=int(self.lrs_config.get("last_epoch", -1)),
245
+ )
246
+ sch = {"scheduler": sch, "interval": "step"}
247
+
248
+ return [opt], [sch]
249
+
250
+ @property
251
+ def input_dims(self) -> dict[str, int]:
252
+ return {k: len(v) for k, v in self.norm.variables.items()}
salt/stypes.py ADDED
@@ -0,0 +1,8 @@
1
+ from typing import TypeAlias
2
+
3
+ from torch import BoolTensor, Tensor
4
+
5
+ Vars: TypeAlias = dict[str, list[str]]
6
+ Tensors: TypeAlias = dict[str, Tensor]
7
+ BoolTensors: TypeAlias = dict[str, BoolTensor]
8
+ NestedTensors: TypeAlias = dict[str, dict[str, Tensor]]
@@ -0,0 +1,7 @@
1
+ Copyright 2024 CERN
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,32 @@
1
+ Metadata-Version: 2.1
2
+ Name: salt-ml
3
+ Version: 0.6
4
+ Summary: Multimodal and Multiclass Machine Learning for High Energy Physics
5
+ License: MIT
6
+ Project-URL: Homepage, https://gitlab.cern.ch/atlas-flavor-tagging-tools/algorithms/salt
7
+ Project-URL: Issue Tracker, https://gitlab.cern.ch/atlas-flavor-tagging-tools/algorithms/salt/-/issues
8
+ Requires-Python: <3.12,>=3.10
9
+ License-File: LICENSE
10
+ Requires-Dist: pytest ==7.4.2
11
+ Requires-Dist: pytest-cov ==4.1.0
12
+ Requires-Dist: comet-ml ==3.35.3
13
+ Requires-Dist: tqdm ==4.66.1
14
+ Requires-Dist: rich ==13.6.0
15
+ Requires-Dist: pre-commit ==3.5.0
16
+ Requires-Dist: ruff ==0.2.2
17
+ Requires-Dist: h5py ==3.10.0
18
+ Requires-Dist: numpy ==1.24.2
19
+ Requires-Dist: torch ==2.2.1
20
+ Requires-Dist: lightning ==2.2.0
21
+ Requires-Dist: jsonargparse[all] ==4.32.0
22
+ Requires-Dist: torchmetrics ==1.2.1
23
+ Requires-Dist: onnx ==1.16.0
24
+ Requires-Dist: onnxruntime ==1.15.1
25
+ Requires-Dist: atlas-ftag-tools ==0.2.2
26
+ Requires-Dist: scipy ==1.12.0
27
+ Requires-Dist: mup ==1.0.0
28
+ Requires-Dist: boto3 ==1.28.17
29
+ Requires-Dist: s3fs ==2023.9.2
30
+ Requires-Dist: s3path ==0.5.0
31
+ Requires-Dist: tensorboard ==2.14.1
32
+
@@ -0,0 +1,10 @@
1
+ salt/__init__.py,sha256=ncKOhmMshkKH0hADIDc1EohSZbPVhx6HkN9Q9lGRlpc,20
2
+ salt/main.py,sha256=k080VQ4T6Qt7tFOwFnuDZeIEKf5x9Yyr9Zx7kDr99v0,849
3
+ salt/modelwrapper.py,sha256=rxL6hk7tTiEpLKmADqfH0wC9_b-eGRs2cb3IsQxr9D8,8849
4
+ salt/stypes.py,sha256=YrnZOfdpYNFrpanHeQEKc0oHAyiyXFMtpJr3T18INoc,249
5
+ salt_ml-0.6.dist-info/LICENSE,sha256=xhKDC68K3tkxStAz7NqUflkVqfvXR_Zw4nsWbsisXq8,1052
6
+ salt_ml-0.6.dist-info/METADATA,sha256=XOI1YNi7hA77jnm1jNKZvS1Q4ZBxkFARBlI-3-4BKAU,1089
7
+ salt_ml-0.6.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
8
+ salt_ml-0.6.dist-info/entry_points.txt,sha256=U3e3HaUskBtZQMhevO_XNhXDZyxP4DNVpe9USQZIVEE,317
9
+ salt_ml-0.6.dist-info/top_level.txt,sha256=BqSzl_xwRerFJ8Kuw_9GzuXOMAFsdg8jjCbnmQL-Z7Y,5
10
+ salt_ml-0.6.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,8 @@
1
+ [console_scripts]
2
+ compare_models = salt.utils.compare_models:main
3
+ download_S3 = salt.utils.file_utils:download_from_S3
4
+ get_onnx_metadata = salt.utils.get_onnx_metadata:main
5
+ repair_ckpt = salt.utils.repair_ckpt:main
6
+ salt = salt.main:main
7
+ setup_muP = salt.utils.muP_utils.main_muP:main
8
+ to_onnx = salt.onnx.to_onnx:main
@@ -0,0 +1 @@
1
+ salt