careamics 0.0.1__py3-none-any.whl → 0.0.3__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.
Potentially problematic release.
This version of careamics might be problematic. Click here for more details.
- careamics/__init__.py +6 -1
- careamics/careamist.py +729 -0
- careamics/config/__init__.py +39 -0
- careamics/config/architectures/__init__.py +17 -0
- careamics/config/architectures/architecture_model.py +37 -0
- careamics/config/architectures/custom_model.py +162 -0
- careamics/config/architectures/lvae_model.py +174 -0
- careamics/config/architectures/register_model.py +103 -0
- careamics/config/architectures/unet_model.py +118 -0
- careamics/config/callback_model.py +123 -0
- careamics/config/configuration_factory.py +583 -0
- careamics/config/configuration_model.py +604 -0
- careamics/config/data_model.py +527 -0
- careamics/config/fcn_algorithm_model.py +147 -0
- careamics/config/inference_model.py +239 -0
- careamics/config/likelihood_model.py +43 -0
- careamics/config/nm_model.py +101 -0
- careamics/config/optimizer_models.py +187 -0
- careamics/config/references/__init__.py +45 -0
- careamics/config/references/algorithm_descriptions.py +132 -0
- careamics/config/references/references.py +39 -0
- careamics/config/support/__init__.py +31 -0
- careamics/config/support/supported_activations.py +27 -0
- careamics/config/support/supported_algorithms.py +33 -0
- careamics/config/support/supported_architectures.py +17 -0
- careamics/config/support/supported_data.py +109 -0
- careamics/config/support/supported_loggers.py +10 -0
- careamics/config/support/supported_losses.py +29 -0
- careamics/config/support/supported_optimizers.py +57 -0
- careamics/config/support/supported_pixel_manipulations.py +15 -0
- careamics/config/support/supported_struct_axis.py +21 -0
- careamics/config/support/supported_transforms.py +11 -0
- careamics/config/tile_information.py +65 -0
- careamics/config/training_model.py +72 -0
- careamics/config/transformations/__init__.py +15 -0
- careamics/config/transformations/n2v_manipulate_model.py +64 -0
- careamics/config/transformations/normalize_model.py +60 -0
- careamics/config/transformations/transform_model.py +45 -0
- careamics/config/transformations/xy_flip_model.py +43 -0
- careamics/config/transformations/xy_random_rotate90_model.py +35 -0
- careamics/config/vae_algorithm_model.py +171 -0
- careamics/config/validators/__init__.py +5 -0
- careamics/config/validators/validator_utils.py +101 -0
- careamics/conftest.py +39 -0
- careamics/dataset/__init__.py +17 -0
- careamics/dataset/dataset_utils/__init__.py +19 -0
- careamics/dataset/dataset_utils/dataset_utils.py +101 -0
- careamics/dataset/dataset_utils/file_utils.py +141 -0
- careamics/dataset/dataset_utils/iterate_over_files.py +83 -0
- careamics/dataset/dataset_utils/running_stats.py +186 -0
- careamics/dataset/in_memory_dataset.py +310 -0
- careamics/dataset/in_memory_pred_dataset.py +88 -0
- careamics/dataset/in_memory_tiled_pred_dataset.py +129 -0
- careamics/dataset/iterable_dataset.py +295 -0
- careamics/dataset/iterable_pred_dataset.py +122 -0
- careamics/dataset/iterable_tiled_pred_dataset.py +140 -0
- careamics/dataset/patching/__init__.py +1 -0
- careamics/dataset/patching/patching.py +299 -0
- careamics/dataset/patching/random_patching.py +201 -0
- careamics/dataset/patching/sequential_patching.py +212 -0
- careamics/dataset/patching/validate_patch_dimension.py +64 -0
- careamics/dataset/tiling/__init__.py +10 -0
- careamics/dataset/tiling/collate_tiles.py +33 -0
- careamics/dataset/tiling/lvae_tiled_patching.py +282 -0
- careamics/dataset/tiling/tiled_patching.py +164 -0
- careamics/dataset/zarr_dataset.py +151 -0
- careamics/file_io/__init__.py +15 -0
- careamics/file_io/read/__init__.py +12 -0
- careamics/file_io/read/get_func.py +56 -0
- careamics/file_io/read/tiff.py +58 -0
- careamics/file_io/read/zarr.py +60 -0
- careamics/file_io/write/__init__.py +15 -0
- careamics/file_io/write/get_func.py +63 -0
- careamics/file_io/write/tiff.py +40 -0
- careamics/lightning/__init__.py +18 -0
- careamics/lightning/callbacks/__init__.py +11 -0
- careamics/lightning/callbacks/hyperparameters_callback.py +49 -0
- careamics/lightning/callbacks/prediction_writer_callback/__init__.py +20 -0
- careamics/lightning/callbacks/prediction_writer_callback/file_path_utils.py +56 -0
- careamics/lightning/callbacks/prediction_writer_callback/prediction_writer_callback.py +233 -0
- careamics/lightning/callbacks/prediction_writer_callback/write_strategy.py +398 -0
- careamics/lightning/callbacks/prediction_writer_callback/write_strategy_factory.py +215 -0
- careamics/lightning/callbacks/progress_bar_callback.py +90 -0
- careamics/lightning/lightning_module.py +632 -0
- careamics/lightning/predict_data_module.py +333 -0
- careamics/lightning/train_data_module.py +680 -0
- careamics/losses/__init__.py +15 -0
- careamics/losses/fcn/__init__.py +1 -0
- careamics/losses/fcn/losses.py +98 -0
- careamics/losses/loss_factory.py +155 -0
- careamics/losses/lvae/__init__.py +1 -0
- careamics/losses/lvae/loss_utils.py +83 -0
- careamics/losses/lvae/losses.py +445 -0
- careamics/lvae_training/__init__.py +0 -0
- careamics/lvae_training/dataset/__init__.py +0 -0
- careamics/lvae_training/dataset/data_utils.py +701 -0
- careamics/lvae_training/dataset/lc_dataset.py +259 -0
- careamics/lvae_training/dataset/lc_dataset_config.py +13 -0
- careamics/lvae_training/dataset/vae_data_config.py +179 -0
- careamics/lvae_training/dataset/vae_dataset.py +1054 -0
- careamics/lvae_training/eval_utils.py +905 -0
- careamics/lvae_training/get_config.py +84 -0
- careamics/lvae_training/lightning_module.py +701 -0
- careamics/lvae_training/metrics.py +214 -0
- careamics/lvae_training/train_lvae.py +342 -0
- careamics/lvae_training/train_utils.py +121 -0
- careamics/model_io/__init__.py +7 -0
- careamics/model_io/bioimage/__init__.py +11 -0
- careamics/model_io/bioimage/_readme_factory.py +121 -0
- careamics/model_io/bioimage/bioimage_utils.py +52 -0
- careamics/model_io/bioimage/model_description.py +327 -0
- careamics/model_io/bmz_io.py +246 -0
- careamics/model_io/model_io_utils.py +95 -0
- careamics/models/__init__.py +5 -0
- careamics/models/activation.py +39 -0
- careamics/models/layers.py +493 -0
- careamics/models/lvae/__init__.py +3 -0
- careamics/models/lvae/layers.py +1998 -0
- careamics/models/lvae/likelihoods.py +364 -0
- careamics/models/lvae/lvae.py +901 -0
- careamics/models/lvae/noise_models.py +541 -0
- careamics/models/lvae/utils.py +395 -0
- careamics/models/model_factory.py +67 -0
- careamics/models/unet.py +443 -0
- careamics/prediction_utils/__init__.py +10 -0
- careamics/prediction_utils/lvae_prediction.py +158 -0
- careamics/prediction_utils/lvae_tiling_manager.py +362 -0
- careamics/prediction_utils/prediction_outputs.py +135 -0
- careamics/prediction_utils/stitch_prediction.py +112 -0
- careamics/transforms/__init__.py +20 -0
- careamics/transforms/compose.py +107 -0
- careamics/transforms/n2v_manipulate.py +146 -0
- careamics/transforms/normalize.py +243 -0
- careamics/transforms/pixel_manipulation.py +407 -0
- careamics/transforms/struct_mask_parameters.py +20 -0
- careamics/transforms/transform.py +24 -0
- careamics/transforms/tta.py +88 -0
- careamics/transforms/xy_flip.py +123 -0
- careamics/transforms/xy_random_rotate90.py +101 -0
- careamics/utils/__init__.py +19 -0
- careamics/utils/autocorrelation.py +40 -0
- careamics/utils/base_enum.py +60 -0
- careamics/utils/context.py +66 -0
- careamics/utils/logging.py +322 -0
- careamics/utils/metrics.py +188 -0
- careamics/utils/path_utils.py +26 -0
- careamics/utils/ram.py +15 -0
- careamics/utils/receptive_field.py +108 -0
- careamics/utils/torch_utils.py +127 -0
- careamics-0.0.3.dist-info/METADATA +78 -0
- careamics-0.0.3.dist-info/RECORD +154 -0
- {careamics-0.0.1.dist-info → careamics-0.0.3.dist-info}/WHEEL +1 -1
- {careamics-0.0.1.dist-info → careamics-0.0.3.dist-info}/licenses/LICENSE +1 -1
- careamics-0.0.1.dist-info/METADATA +0 -46
- careamics-0.0.1.dist-info/RECORD +0 -6
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Function to export to the BioImage Model Zoo format."""
|
|
2
|
+
|
|
3
|
+
import tempfile
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import List, Optional, Tuple, Union
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pkg_resources
|
|
9
|
+
from bioimageio.core import load_description, test_model
|
|
10
|
+
from bioimageio.spec import ValidationSummary, save_bioimageio_package
|
|
11
|
+
from torch import __version__, load, save
|
|
12
|
+
|
|
13
|
+
from careamics.config import Configuration, load_configuration, save_configuration
|
|
14
|
+
from careamics.config.support import SupportedArchitecture
|
|
15
|
+
from careamics.lightning.lightning_module import FCNModule, VAEModule
|
|
16
|
+
|
|
17
|
+
from .bioimage import (
|
|
18
|
+
create_env_text,
|
|
19
|
+
create_model_description,
|
|
20
|
+
extract_model_path,
|
|
21
|
+
get_unzip_path,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _export_state_dict(
|
|
26
|
+
model: Union[FCNModule, VAEModule], path: Union[Path, str]
|
|
27
|
+
) -> Path:
|
|
28
|
+
"""
|
|
29
|
+
Export the model state dictionary to a file.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
model : CAREamicsKiln
|
|
34
|
+
CAREamics model to export.
|
|
35
|
+
path : Union[Path, str]
|
|
36
|
+
Path to the file where to save the model state dictionary.
|
|
37
|
+
|
|
38
|
+
Returns
|
|
39
|
+
-------
|
|
40
|
+
Path
|
|
41
|
+
Path to the saved model state dictionary.
|
|
42
|
+
"""
|
|
43
|
+
path = Path(path)
|
|
44
|
+
|
|
45
|
+
# make sure it has the correct suffix
|
|
46
|
+
if path.suffix not in ".pth":
|
|
47
|
+
path = path.with_suffix(".pth")
|
|
48
|
+
|
|
49
|
+
# save model state dictionary
|
|
50
|
+
# we save through the torch model itself to avoid the initial "model." in the
|
|
51
|
+
# layers naming, which is incompatible with the way the BMZ load torch state dicts
|
|
52
|
+
save(model.model.state_dict(), path)
|
|
53
|
+
|
|
54
|
+
return path
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _load_state_dict(
|
|
58
|
+
model: Union[FCNModule, VAEModule], path: Union[Path, str]
|
|
59
|
+
) -> None:
|
|
60
|
+
"""
|
|
61
|
+
Load a model from a state dictionary.
|
|
62
|
+
|
|
63
|
+
Parameters
|
|
64
|
+
----------
|
|
65
|
+
model : CAREamicsKiln
|
|
66
|
+
CAREamics model to be updated with the weights.
|
|
67
|
+
path : Union[Path, str]
|
|
68
|
+
Path to the model state dictionary.
|
|
69
|
+
"""
|
|
70
|
+
path = Path(path)
|
|
71
|
+
|
|
72
|
+
# load model state dictionary
|
|
73
|
+
# same as in _export_state_dict, we load through the torch model to be compatible
|
|
74
|
+
# witht bioimageio.core expectations for a torch state dict
|
|
75
|
+
state_dict = load(path)
|
|
76
|
+
model.model.load_state_dict(state_dict)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# TODO break down in subfunctions
|
|
80
|
+
def export_to_bmz(
|
|
81
|
+
model: Union[FCNModule, VAEModule],
|
|
82
|
+
config: Configuration,
|
|
83
|
+
path_to_archive: Union[Path, str],
|
|
84
|
+
model_name: str,
|
|
85
|
+
general_description: str,
|
|
86
|
+
authors: List[dict],
|
|
87
|
+
input_array: np.ndarray,
|
|
88
|
+
output_array: np.ndarray,
|
|
89
|
+
channel_names: Optional[List[str]] = None,
|
|
90
|
+
data_description: Optional[str] = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
"""Export the model to BioImage Model Zoo format.
|
|
93
|
+
|
|
94
|
+
Arrays are expected to be SC(Z)YX with singleton dimensions allowed for S and C.
|
|
95
|
+
|
|
96
|
+
`model_name` should consist of letters, numbers, dashes, underscores and parentheses
|
|
97
|
+
only.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
model : CAREamicsModule
|
|
102
|
+
CAREamics model to export.
|
|
103
|
+
config : Configuration
|
|
104
|
+
Model configuration.
|
|
105
|
+
path_to_archive : Union[Path, str]
|
|
106
|
+
Path to the output file.
|
|
107
|
+
model_name : str
|
|
108
|
+
Model name.
|
|
109
|
+
general_description : str
|
|
110
|
+
General description of the model.
|
|
111
|
+
authors : List[dict]
|
|
112
|
+
Authors of the model.
|
|
113
|
+
input_array : np.ndarray
|
|
114
|
+
Input array, should not have been normalized.
|
|
115
|
+
output_array : np.ndarray
|
|
116
|
+
Output array, should have been denormalized.
|
|
117
|
+
channel_names : Optional[List[str]], optional
|
|
118
|
+
Channel names, by default None.
|
|
119
|
+
data_description : Optional[str], optional
|
|
120
|
+
Description of the data, by default None.
|
|
121
|
+
|
|
122
|
+
Raises
|
|
123
|
+
------
|
|
124
|
+
ValueError
|
|
125
|
+
If the model is a Custom model.
|
|
126
|
+
"""
|
|
127
|
+
path_to_archive = Path(path_to_archive)
|
|
128
|
+
|
|
129
|
+
# method is not compatible with Custom models
|
|
130
|
+
if config.algorithm_config.model.architecture == SupportedArchitecture.CUSTOM:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
"Exporting Custom models to BioImage Model Zoo format is not supported."
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
if path_to_archive.suffix != ".zip":
|
|
136
|
+
raise ValueError(
|
|
137
|
+
f"Path to archive must point to a zip file, got {path_to_archive}."
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
if not path_to_archive.parent.exists():
|
|
141
|
+
path_to_archive.parent.mkdir(parents=True, exist_ok=True)
|
|
142
|
+
|
|
143
|
+
# versions
|
|
144
|
+
pytorch_version = __version__
|
|
145
|
+
careamics_version = pkg_resources.get_distribution("careamics").version
|
|
146
|
+
|
|
147
|
+
# save files in temporary folder
|
|
148
|
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
|
149
|
+
temp_path = Path(tmpdirname)
|
|
150
|
+
|
|
151
|
+
# create environment file
|
|
152
|
+
# TODO move in bioimage module
|
|
153
|
+
env_path = temp_path / "environment.yml"
|
|
154
|
+
env_path.write_text(create_env_text(pytorch_version))
|
|
155
|
+
|
|
156
|
+
# export input and ouputs
|
|
157
|
+
inputs = temp_path / "inputs.npy"
|
|
158
|
+
np.save(inputs, input_array)
|
|
159
|
+
outputs = temp_path / "outputs.npy"
|
|
160
|
+
np.save(outputs, output_array)
|
|
161
|
+
|
|
162
|
+
# export configuration
|
|
163
|
+
config_path = save_configuration(config, temp_path)
|
|
164
|
+
|
|
165
|
+
# export model state dictionary
|
|
166
|
+
weight_path = _export_state_dict(model, temp_path / "weights.pth")
|
|
167
|
+
|
|
168
|
+
# create model description
|
|
169
|
+
model_description = create_model_description(
|
|
170
|
+
config=config,
|
|
171
|
+
name=model_name,
|
|
172
|
+
general_description=general_description,
|
|
173
|
+
authors=authors,
|
|
174
|
+
inputs=inputs,
|
|
175
|
+
outputs=outputs,
|
|
176
|
+
weights_path=weight_path,
|
|
177
|
+
torch_version=pytorch_version,
|
|
178
|
+
careamics_version=careamics_version,
|
|
179
|
+
config_path=config_path,
|
|
180
|
+
env_path=env_path,
|
|
181
|
+
channel_names=channel_names,
|
|
182
|
+
data_description=data_description,
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
# test model description
|
|
186
|
+
summary: ValidationSummary = test_model(model_description, decimal=1)
|
|
187
|
+
if summary.status == "failed":
|
|
188
|
+
raise ValueError(f"Model description test failed: {summary}")
|
|
189
|
+
|
|
190
|
+
# save bmz model
|
|
191
|
+
save_bioimageio_package(model_description, output_path=path_to_archive)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def load_from_bmz(
|
|
195
|
+
path: Union[Path, str]
|
|
196
|
+
) -> Tuple[Union[FCNModule, VAEModule], Configuration]:
|
|
197
|
+
"""Load a model from a BioImage Model Zoo archive.
|
|
198
|
+
|
|
199
|
+
Parameters
|
|
200
|
+
----------
|
|
201
|
+
path : Union[Path, str]
|
|
202
|
+
Path to the BioImage Model Zoo archive.
|
|
203
|
+
|
|
204
|
+
Returns
|
|
205
|
+
-------
|
|
206
|
+
Tuple[CAREamicsKiln, Configuration]
|
|
207
|
+
CAREamics model and configuration.
|
|
208
|
+
|
|
209
|
+
Raises
|
|
210
|
+
------
|
|
211
|
+
ValueError
|
|
212
|
+
If the path is not a zip file.
|
|
213
|
+
"""
|
|
214
|
+
path = Path(path)
|
|
215
|
+
|
|
216
|
+
if path.suffix != ".zip":
|
|
217
|
+
raise ValueError(f"Path must be a bioimage.io zip file, got {path}.")
|
|
218
|
+
|
|
219
|
+
# load description, this creates an unzipped folder next to the archive
|
|
220
|
+
model_desc = load_description(path)
|
|
221
|
+
|
|
222
|
+
# extract relative paths
|
|
223
|
+
weights_path, config_path = extract_model_path(model_desc)
|
|
224
|
+
|
|
225
|
+
# create folder path and absolute paths
|
|
226
|
+
unzip_path = get_unzip_path(path)
|
|
227
|
+
weights_path = unzip_path / weights_path
|
|
228
|
+
config_path = unzip_path / config_path
|
|
229
|
+
|
|
230
|
+
# load configuration
|
|
231
|
+
config = load_configuration(config_path)
|
|
232
|
+
|
|
233
|
+
# create careamics lightning module
|
|
234
|
+
if config.algorithm_config.model.architecture == SupportedArchitecture.UNET:
|
|
235
|
+
model = FCNModule(algorithm_config=config.algorithm_config)
|
|
236
|
+
elif config.algorithm_config.model.architecture == SupportedArchitecture.LVAE:
|
|
237
|
+
model = VAEModule(algorithm_config=config.algorithm_config)
|
|
238
|
+
else:
|
|
239
|
+
raise ValueError(
|
|
240
|
+
f"Unsupported architecture {config.algorithm_config.model.architecture}"
|
|
241
|
+
) # TODO ugly ?
|
|
242
|
+
|
|
243
|
+
# load model state dictionary
|
|
244
|
+
_load_state_dict(model, weights_path)
|
|
245
|
+
|
|
246
|
+
return model, config
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Utility functions to load pretrained models."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Tuple, Union
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
|
|
8
|
+
from careamics.config import Configuration
|
|
9
|
+
from careamics.lightning.lightning_module import FCNModule, VAEModule
|
|
10
|
+
from careamics.model_io.bmz_io import load_from_bmz
|
|
11
|
+
from careamics.utils import check_path_exists
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_pretrained(
|
|
15
|
+
path: Union[Path, str]
|
|
16
|
+
) -> Tuple[Union[FCNModule, VAEModule], Configuration]:
|
|
17
|
+
"""
|
|
18
|
+
Load a pretrained model from a checkpoint or a BioImage Model Zoo model.
|
|
19
|
+
|
|
20
|
+
Expected formats are .ckpt or .zip files.
|
|
21
|
+
|
|
22
|
+
Parameters
|
|
23
|
+
----------
|
|
24
|
+
path : Union[Path, str]
|
|
25
|
+
Path to the pretrained model.
|
|
26
|
+
|
|
27
|
+
Returns
|
|
28
|
+
-------
|
|
29
|
+
Tuple[CAREamicsKiln, Configuration]
|
|
30
|
+
Tuple of CAREamics model and its configuration.
|
|
31
|
+
|
|
32
|
+
Raises
|
|
33
|
+
------
|
|
34
|
+
ValueError
|
|
35
|
+
If the model format is not supported.
|
|
36
|
+
"""
|
|
37
|
+
path = check_path_exists(path)
|
|
38
|
+
|
|
39
|
+
if path.suffix == ".ckpt":
|
|
40
|
+
return _load_checkpoint(path)
|
|
41
|
+
elif path.suffix == ".zip":
|
|
42
|
+
return load_from_bmz(path)
|
|
43
|
+
else:
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"Invalid model format. Expected .ckpt or .zip, got {path.suffix}."
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _load_checkpoint(
|
|
50
|
+
path: Union[Path, str]
|
|
51
|
+
) -> Tuple[Union[FCNModule, VAEModule], Configuration]:
|
|
52
|
+
"""
|
|
53
|
+
Load a model from a checkpoint and return both model and configuration.
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
path : Union[Path, str]
|
|
58
|
+
Path to the checkpoint.
|
|
59
|
+
|
|
60
|
+
Returns
|
|
61
|
+
-------
|
|
62
|
+
Tuple[CAREamicsKiln, Configuration]
|
|
63
|
+
Tuple of CAREamics model and its configuration.
|
|
64
|
+
|
|
65
|
+
Raises
|
|
66
|
+
------
|
|
67
|
+
ValueError
|
|
68
|
+
If the checkpoint file does not contain hyper parameters (configuration).
|
|
69
|
+
"""
|
|
70
|
+
# load checkpoint
|
|
71
|
+
# here we might run into issues between devices
|
|
72
|
+
# see https://pytorch.org/tutorials/recipes/recipes/save_load_across_devices.html
|
|
73
|
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
|
74
|
+
checkpoint: dict = torch.load(path, map_location=device)
|
|
75
|
+
|
|
76
|
+
# attempt to load configuration
|
|
77
|
+
try:
|
|
78
|
+
cfg_dict = checkpoint["hyper_parameters"]
|
|
79
|
+
except KeyError as e:
|
|
80
|
+
raise ValueError(
|
|
81
|
+
f"Invalid checkpoint file. No `hyper_parameters` found in the "
|
|
82
|
+
f"checkpoint: {checkpoint.keys()}"
|
|
83
|
+
) from e
|
|
84
|
+
|
|
85
|
+
if cfg_dict["algorithm_config"]["model"]["architecture"] == "UNet":
|
|
86
|
+
model = FCNModule.load_from_checkpoint(path)
|
|
87
|
+
elif cfg_dict["algorithm_config"]["model"]["architecture"] == "LVAE":
|
|
88
|
+
model = VAEModule.load_from_checkpoint(path)
|
|
89
|
+
else:
|
|
90
|
+
raise ValueError(
|
|
91
|
+
"Invalid model architecture: "
|
|
92
|
+
f"{cfg_dict['algorithm_config']['model']['architecture']}"
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
return model, Configuration(**cfg_dict)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Activations for CAREamics models."""
|
|
2
|
+
|
|
3
|
+
from typing import Callable, Union
|
|
4
|
+
|
|
5
|
+
import torch.nn as nn
|
|
6
|
+
|
|
7
|
+
from ..config.support import SupportedActivation
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def get_activation(activation: Union[SupportedActivation, str]) -> Callable:
|
|
11
|
+
"""
|
|
12
|
+
Get activation function.
|
|
13
|
+
|
|
14
|
+
Parameters
|
|
15
|
+
----------
|
|
16
|
+
activation : str
|
|
17
|
+
Activation function name.
|
|
18
|
+
|
|
19
|
+
Returns
|
|
20
|
+
-------
|
|
21
|
+
Callable
|
|
22
|
+
Activation function.
|
|
23
|
+
"""
|
|
24
|
+
if activation == SupportedActivation.RELU:
|
|
25
|
+
return nn.ReLU()
|
|
26
|
+
elif activation == SupportedActivation.ELU:
|
|
27
|
+
return nn.ELU()
|
|
28
|
+
elif activation == SupportedActivation.LEAKYRELU:
|
|
29
|
+
return nn.LeakyReLU()
|
|
30
|
+
elif activation == SupportedActivation.TANH:
|
|
31
|
+
return nn.Tanh()
|
|
32
|
+
elif activation == SupportedActivation.SIGMOID:
|
|
33
|
+
return nn.Sigmoid()
|
|
34
|
+
elif activation == SupportedActivation.SOFTMAX:
|
|
35
|
+
return nn.Softmax(dim=1)
|
|
36
|
+
elif activation == SupportedActivation.NONE:
|
|
37
|
+
return nn.Identity()
|
|
38
|
+
else:
|
|
39
|
+
raise ValueError(f"Activation {activation} not supported.")
|