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,445 @@
|
|
|
1
|
+
"""Methods for Loss Computation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Optional, Union
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
from careamics.losses.lvae.loss_utils import free_bits_kl, get_kl_weight
|
|
11
|
+
from careamics.models.lvae.likelihoods import (
|
|
12
|
+
GaussianLikelihood,
|
|
13
|
+
LikelihoodModule,
|
|
14
|
+
NoiseModelLikelihood,
|
|
15
|
+
)
|
|
16
|
+
from careamics.models.lvae.utils import compute_batch_mean
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from careamics.losses.loss_factory import LVAELossParameters
|
|
20
|
+
|
|
21
|
+
Likelihood = Union[LikelihoodModule, GaussianLikelihood, NoiseModelLikelihood]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get_reconstruction_loss(
|
|
25
|
+
reconstruction: torch.Tensor, # TODO: naming -> predictions?
|
|
26
|
+
target: torch.Tensor,
|
|
27
|
+
likelihood_obj: Likelihood,
|
|
28
|
+
) -> dict[str, torch.Tensor]:
|
|
29
|
+
"""Compute the reconstruction loss.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
reconstruction: torch.Tensor
|
|
34
|
+
The output of the LVAE decoder. Shape is (B, C, [Z], Y, X), where C is the
|
|
35
|
+
number of output channels (e.g., 1 in HDN, >1 in muSplit/denoiSplit).
|
|
36
|
+
target: torch.Tensor
|
|
37
|
+
The target image used to compute the reconstruction loss. Shape is
|
|
38
|
+
(B, C, [Z], Y, X), where C is the number of output channels
|
|
39
|
+
(e.g., 1 in HDN, >1 in muSplit/denoiSplit).
|
|
40
|
+
likelihood_obj: Likelihood
|
|
41
|
+
The likelihood object used to compute the reconstruction loss.
|
|
42
|
+
|
|
43
|
+
Returns
|
|
44
|
+
-------
|
|
45
|
+
dict[str, torch.Tensor]
|
|
46
|
+
A dictionary containing the overall loss `["loss"]` and the loss for
|
|
47
|
+
individual output channels `["ch{i}_loss"]`.
|
|
48
|
+
"""
|
|
49
|
+
loss_dict = _get_reconstruction_loss_vector(
|
|
50
|
+
reconstruction=reconstruction,
|
|
51
|
+
target=target,
|
|
52
|
+
likelihood_obj=likelihood_obj,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
loss_dict["loss"] = loss_dict["loss"].sum() / len(reconstruction)
|
|
56
|
+
for i in range(1, 1 + target.shape[1]):
|
|
57
|
+
key = f"ch{i}_loss"
|
|
58
|
+
loss_dict[key] = loss_dict[key].sum() / len(reconstruction)
|
|
59
|
+
|
|
60
|
+
return loss_dict
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _get_reconstruction_loss_vector(
|
|
64
|
+
reconstruction: torch.Tensor, # TODO: naming -> predictions?
|
|
65
|
+
target: torch.Tensor,
|
|
66
|
+
likelihood_obj: LikelihoodModule,
|
|
67
|
+
) -> dict[str, torch.Tensor]:
|
|
68
|
+
"""Compute the reconstruction loss.
|
|
69
|
+
|
|
70
|
+
Parameters
|
|
71
|
+
----------
|
|
72
|
+
return_predicted_img: bool
|
|
73
|
+
If set to `True`, the besides the loss, the reconstructed image is returned.
|
|
74
|
+
Default is `False`.
|
|
75
|
+
|
|
76
|
+
Returns
|
|
77
|
+
-------
|
|
78
|
+
dict[str, torch.Tensor]
|
|
79
|
+
A dictionary containing the overall loss `["loss"]` and the loss for
|
|
80
|
+
individual output channels `["ch{i}_loss"]`. Shape of individual
|
|
81
|
+
tensors is (B, ).
|
|
82
|
+
"""
|
|
83
|
+
output = {"loss": None}
|
|
84
|
+
for i in range(1, 1 + target.shape[1]):
|
|
85
|
+
output[f"ch{i}_loss"] = None
|
|
86
|
+
|
|
87
|
+
# Compute Log likelihood
|
|
88
|
+
ll, _ = likelihood_obj(reconstruction, target) # shape: (B, C, [Z], Y, X)
|
|
89
|
+
|
|
90
|
+
output = {"loss": compute_batch_mean(-1 * ll)} # shape: (B, )
|
|
91
|
+
if ll.shape[1] > 1: # target_ch > 1
|
|
92
|
+
for i in range(1, 1 + target.shape[1]):
|
|
93
|
+
output[f"ch{i}_loss"] = compute_batch_mean(-ll[:, i - 1]) # shape: (B, )
|
|
94
|
+
else: # target_ch == 1
|
|
95
|
+
# TODO: hacky!!! Refactor this
|
|
96
|
+
assert ll.shape[1] == 1
|
|
97
|
+
output["ch1_loss"] = output["loss"]
|
|
98
|
+
output["ch2_loss"] = output["loss"]
|
|
99
|
+
|
|
100
|
+
return output
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def reconstruction_loss_musplit_denoisplit(
|
|
104
|
+
predictions: Union[torch.Tensor, tuple[torch.Tensor, torch.Tensor]],
|
|
105
|
+
targets: torch.Tensor,
|
|
106
|
+
nm_likelihood: NoiseModelLikelihood,
|
|
107
|
+
gaussian_likelihood: GaussianLikelihood,
|
|
108
|
+
nm_weight: float,
|
|
109
|
+
gaussian_weight: float,
|
|
110
|
+
) -> torch.Tensor:
|
|
111
|
+
"""Compute the reconstruction loss for muSplit-denoiSplit loss.
|
|
112
|
+
|
|
113
|
+
The resulting loss is a weighted mean of the noise model likelihood and the
|
|
114
|
+
Gaussian likelihood.
|
|
115
|
+
|
|
116
|
+
Parameters
|
|
117
|
+
----------
|
|
118
|
+
predictions : torch.Tensor
|
|
119
|
+
The output of the LVAE decoder. Shape is (B, C, [Z], Y, X), or
|
|
120
|
+
(B, 2*C, [Z], Y, X), where C is the number of output channels,
|
|
121
|
+
and the factor of 2 is for the case of predicted log-variance.
|
|
122
|
+
targets : torch.Tensor
|
|
123
|
+
The target image used to compute the reconstruction loss. Shape is
|
|
124
|
+
(B, C, [Z], Y, X), where C is the number of output channels
|
|
125
|
+
(e.g., 1 in HDN, >1 in muSplit/denoiSplit).
|
|
126
|
+
nm_likelihood : NoiseModelLikelihood
|
|
127
|
+
A `NoiseModelLikelihood` object used to compute the noise model likelihood.
|
|
128
|
+
gaussian_likelihood : GaussianLikelihood
|
|
129
|
+
A `GaussianLikelihood` object used to compute the Gaussian likelihood.
|
|
130
|
+
nm_weight : float
|
|
131
|
+
The weight for the noise model likelihood.
|
|
132
|
+
gaussian_weight : float
|
|
133
|
+
The weight for the Gaussian likelihood.
|
|
134
|
+
|
|
135
|
+
Returns
|
|
136
|
+
-------
|
|
137
|
+
recons_loss : torch.Tensor
|
|
138
|
+
The reconstruction loss. Shape is (1, ).
|
|
139
|
+
"""
|
|
140
|
+
# TODO: is this safe to check for predict_logvar value?
|
|
141
|
+
# otherwise use `gaussian_likelihood.predict_logvar` (or both)
|
|
142
|
+
if predictions.shape[1] == 2 * targets.shape[1]:
|
|
143
|
+
# predictions contain both mean and log-variance
|
|
144
|
+
out_mean, _ = predictions.chunk(2, dim=1)
|
|
145
|
+
else:
|
|
146
|
+
out_mean = predictions
|
|
147
|
+
|
|
148
|
+
recons_loss_nm = -1 * nm_likelihood(out_mean, targets)[0].mean()
|
|
149
|
+
recons_loss_gm = -1 * gaussian_likelihood(predictions, targets)[0].mean()
|
|
150
|
+
recons_loss = nm_weight * recons_loss_nm + gaussian_weight * recons_loss_gm
|
|
151
|
+
return recons_loss
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def get_kl_divergence_loss_usplit(
|
|
155
|
+
topdown_data: dict[str, list[torch.Tensor]], kl_key: str = "kl"
|
|
156
|
+
) -> torch.Tensor:
|
|
157
|
+
"""Compute the KL divergence loss for muSplit.
|
|
158
|
+
|
|
159
|
+
Parameters
|
|
160
|
+
----------
|
|
161
|
+
topdown_data : dict[str, list[torch.Tensor]]
|
|
162
|
+
A dictionary containing information computed for each layer during the top-down
|
|
163
|
+
pass. The dictionary must include the following keys:
|
|
164
|
+
- "kl": The KL-loss values for each layer. Shape of each tensor is (B,).
|
|
165
|
+
- "z": The sampled latents for each layer. Shape of each tensor is
|
|
166
|
+
(B, layers, `z_dims[i]`, H, W).
|
|
167
|
+
kl_key : str
|
|
168
|
+
The key for the KL-loss values in the top-down layer data dictionary.
|
|
169
|
+
To choose among ["kl", "kl_restricted", "kl_spatial", "kl_channelwise"]
|
|
170
|
+
Default is "kl".
|
|
171
|
+
"""
|
|
172
|
+
kl = torch.cat(
|
|
173
|
+
[kl_layer.unsqueeze(1) for kl_layer in topdown_data[kl_key]], dim=1
|
|
174
|
+
) # shape: (B, n_layers)
|
|
175
|
+
# NOTE: Values are sum() and so are of the order 30000
|
|
176
|
+
|
|
177
|
+
nlayers = kl.shape[1]
|
|
178
|
+
for i in range(nlayers):
|
|
179
|
+
# NOTE: we want to normalize the KL-loss w.r.t. the latent space dimensions,
|
|
180
|
+
# i.e., the number of entries in the latent space tensors (C, [Z], Y, X).
|
|
181
|
+
# We assume z has shape (B, C, [Z], Y, X), where `C = z_dims[i]`.
|
|
182
|
+
norm_factor = np.prod(topdown_data["z"][i].shape[1:])
|
|
183
|
+
kl[:, i] = kl[:, i] / norm_factor
|
|
184
|
+
|
|
185
|
+
kl_loss = free_bits_kl(kl, 0.0).mean() # shape: (1, )
|
|
186
|
+
# NOTE: free_bits disabled!
|
|
187
|
+
return kl_loss
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def get_kl_divergence_loss_denoisplit(
|
|
191
|
+
topdown_data: dict[str, torch.Tensor],
|
|
192
|
+
img_shape: tuple[int],
|
|
193
|
+
kl_key: str = "kl",
|
|
194
|
+
) -> torch.Tensor:
|
|
195
|
+
"""Compute the KL divergence loss for denoiSplit.
|
|
196
|
+
|
|
197
|
+
Parameters
|
|
198
|
+
----------
|
|
199
|
+
topdown_data : dict[str, torch.Tensor]
|
|
200
|
+
A dictionary containing information computed for each layer during the top-down
|
|
201
|
+
pass. The dictionary must include the following keys:
|
|
202
|
+
- "kl": The KL-loss values for each layer. Shape of each tensor is (B,).
|
|
203
|
+
- "z": The sampled latents for each layer. Shape of each tensor is
|
|
204
|
+
(B, layers, `z_dims[i]`, H, W).
|
|
205
|
+
img_shape : tuple[int]
|
|
206
|
+
The shape of the input image to the LVAE model. Shape is ([Z], Y, X).
|
|
207
|
+
kl_key : str
|
|
208
|
+
The key for the KL-loss values in the top-down layer data dictionary.
|
|
209
|
+
To choose among ["kl", "kl_restricted", "kl_spatial", "kl_channelwise"]
|
|
210
|
+
Default is "kl"
|
|
211
|
+
|
|
212
|
+
kl[i] for each i has length batch_size resulting kl shape: (bs, layers).
|
|
213
|
+
"""
|
|
214
|
+
kl = torch.cat(
|
|
215
|
+
[kl_layer.unsqueeze(1) for kl_layer in topdown_data[kl_key]],
|
|
216
|
+
dim=1,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
kl_loss = free_bits_kl(kl, 1.0).sum()
|
|
220
|
+
# NOTE: as compared to uSplit kl divergence, this KL loss is larger by a factor of
|
|
221
|
+
# `n_layers` since we sum KL contributions from different layers instead of taking
|
|
222
|
+
# the mean.
|
|
223
|
+
|
|
224
|
+
# NOTE: at each hierarchy, the KL loss is larger by a factor of (128/i**2).
|
|
225
|
+
# 128/(2*2) = 32 (bottommost layer)
|
|
226
|
+
# 128/(4*4) = 8
|
|
227
|
+
# 128/(8*8) = 2
|
|
228
|
+
# 128/(16*16) = 0.5 (topmost layer)
|
|
229
|
+
|
|
230
|
+
# Normalize the KL-loss w.r.t. the input image spatial dimensions (e.g., 64x64)
|
|
231
|
+
kl_loss = kl_loss / np.prod(img_shape)
|
|
232
|
+
return kl_loss
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
# TODO: @melisande-c suggested to refactor this as a class (see PR #208)
|
|
236
|
+
# - loss computation happens by calling the `__call__` method
|
|
237
|
+
# - `__init__` method initializes the loss parameters now contained in
|
|
238
|
+
# the `LVAELossParameters` class
|
|
239
|
+
# NOTE: same for the other loss functions
|
|
240
|
+
def musplit_loss(
|
|
241
|
+
model_outputs: tuple[torch.Tensor, dict[str, Any]],
|
|
242
|
+
targets: torch.Tensor,
|
|
243
|
+
loss_parameters: LVAELossParameters,
|
|
244
|
+
) -> Optional[dict[str, torch.Tensor]]:
|
|
245
|
+
"""Loss function for muSplit.
|
|
246
|
+
|
|
247
|
+
Parameters
|
|
248
|
+
----------
|
|
249
|
+
model_outputs : tuple[torch.Tensor, dict[str, Any]]
|
|
250
|
+
Tuple containing the model predictions (shape is (B, `target_ch`, [Z], Y, X))
|
|
251
|
+
and the top-down layer data (e.g., sampled latents, KL-loss values, etc.).
|
|
252
|
+
targets : torch.Tensor
|
|
253
|
+
The target image used to compute the reconstruction loss. Shape is
|
|
254
|
+
(B, `target_ch`, [Z], Y, X).
|
|
255
|
+
loss_parameters : LVAELossParameters
|
|
256
|
+
The loss parameters for muSplit (e.g., KL hyperparameters, likelihood module,
|
|
257
|
+
noise model, etc.).
|
|
258
|
+
|
|
259
|
+
Returns
|
|
260
|
+
-------
|
|
261
|
+
output : Optional[dict[str, torch.Tensor]]
|
|
262
|
+
A dictionary containing the overall loss `["loss"]`, the reconstruction loss
|
|
263
|
+
`["reconstruction_loss"]`, and the KL divergence loss `["kl_loss"]`.
|
|
264
|
+
"""
|
|
265
|
+
predictions, td_data = model_outputs
|
|
266
|
+
|
|
267
|
+
# Reconstruction loss computation
|
|
268
|
+
recons_loss_dict = get_reconstruction_loss(
|
|
269
|
+
reconstruction=predictions,
|
|
270
|
+
target=targets,
|
|
271
|
+
likelihood_obj=loss_parameters.gaussian_likelihood,
|
|
272
|
+
)
|
|
273
|
+
recons_loss = recons_loss_dict["loss"] * loss_parameters.reconstruction_weight
|
|
274
|
+
if torch.isnan(recons_loss).any():
|
|
275
|
+
recons_loss = 0.0
|
|
276
|
+
|
|
277
|
+
# KL loss computation
|
|
278
|
+
kl_weight = get_kl_weight(
|
|
279
|
+
loss_parameters.kl_annealing,
|
|
280
|
+
loss_parameters.kl_start,
|
|
281
|
+
loss_parameters.kl_annealtime,
|
|
282
|
+
loss_parameters.kl_weight,
|
|
283
|
+
loss_parameters.current_epoch,
|
|
284
|
+
)
|
|
285
|
+
kl_loss = kl_weight * get_kl_divergence_loss_usplit(td_data)
|
|
286
|
+
|
|
287
|
+
net_loss = recons_loss + kl_loss
|
|
288
|
+
output = {
|
|
289
|
+
"loss": net_loss,
|
|
290
|
+
"reconstruction_loss": (
|
|
291
|
+
recons_loss.detach()
|
|
292
|
+
if isinstance(recons_loss, torch.Tensor)
|
|
293
|
+
else recons_loss
|
|
294
|
+
),
|
|
295
|
+
"kl_loss": kl_loss.detach(),
|
|
296
|
+
}
|
|
297
|
+
# https://github.com/openai/vdvae/blob/main/train.py#L26
|
|
298
|
+
if torch.isnan(net_loss).any():
|
|
299
|
+
return None
|
|
300
|
+
|
|
301
|
+
return output
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def denoisplit_loss(
|
|
305
|
+
model_outputs: tuple[torch.Tensor, dict[str, Any]],
|
|
306
|
+
targets: torch.Tensor,
|
|
307
|
+
loss_parameters: LVAELossParameters,
|
|
308
|
+
) -> Optional[dict[str, torch.Tensor]]:
|
|
309
|
+
"""Loss function for DenoiSplit.
|
|
310
|
+
|
|
311
|
+
Parameters
|
|
312
|
+
----------
|
|
313
|
+
model_outputs : tuple[torch.Tensor, dict[str, Any]]
|
|
314
|
+
Tuple containing the model predictions (shape is (B, `target_ch`, [Z], Y, X))
|
|
315
|
+
and the top-down layer data (e.g., sampled latents, KL-loss values, etc.).
|
|
316
|
+
targets : torch.Tensor
|
|
317
|
+
The target image used to compute the reconstruction loss. Shape is
|
|
318
|
+
(B, `target_ch`, [Z], Y, X).
|
|
319
|
+
loss_parameters : LVAELossParameters
|
|
320
|
+
The loss parameters for muSplit (e.g., KL hyperparameters, likelihood module,
|
|
321
|
+
noise model, etc.).
|
|
322
|
+
|
|
323
|
+
Returns
|
|
324
|
+
-------
|
|
325
|
+
output : Optional[dict[str, torch.Tensor]]
|
|
326
|
+
A dictionary containing the overall loss `["loss"]`, the reconstruction loss
|
|
327
|
+
`["reconstruction_loss"]`, and the KL divergence loss `["kl_loss"]`.
|
|
328
|
+
"""
|
|
329
|
+
predictions, td_data = model_outputs
|
|
330
|
+
|
|
331
|
+
# Reconstruction loss computation
|
|
332
|
+
recons_loss_dict = get_reconstruction_loss(
|
|
333
|
+
reconstruction=predictions,
|
|
334
|
+
target=targets,
|
|
335
|
+
likelihood_obj=loss_parameters.noise_model_likelihood,
|
|
336
|
+
)
|
|
337
|
+
recons_loss = recons_loss_dict["loss"] * loss_parameters.reconstruction_weight
|
|
338
|
+
if torch.isnan(recons_loss).any():
|
|
339
|
+
recons_loss = 0.0
|
|
340
|
+
|
|
341
|
+
# KL loss computation
|
|
342
|
+
if loss_parameters.non_stochastic: # TODO always false ?
|
|
343
|
+
kl_loss = torch.Tensor([0.0]).cuda()
|
|
344
|
+
else:
|
|
345
|
+
kl_weight = get_kl_weight(
|
|
346
|
+
loss_parameters.kl_annealing,
|
|
347
|
+
loss_parameters.kl_start,
|
|
348
|
+
loss_parameters.kl_annealtime,
|
|
349
|
+
loss_parameters.kl_weight,
|
|
350
|
+
loss_parameters.current_epoch,
|
|
351
|
+
)
|
|
352
|
+
kl_loss = kl_weight * get_kl_divergence_loss_denoisplit(
|
|
353
|
+
topdown_data=td_data,
|
|
354
|
+
img_shape=targets.shape[2:], # input img spatial dims
|
|
355
|
+
)
|
|
356
|
+
|
|
357
|
+
net_loss = recons_loss + kl_loss
|
|
358
|
+
output = {
|
|
359
|
+
"loss": net_loss,
|
|
360
|
+
"reconstruction_loss": (
|
|
361
|
+
recons_loss.detach()
|
|
362
|
+
if isinstance(recons_loss, torch.Tensor)
|
|
363
|
+
else recons_loss
|
|
364
|
+
),
|
|
365
|
+
"kl_loss": kl_loss.detach(),
|
|
366
|
+
}
|
|
367
|
+
# https://github.com/openai/vdvae/blob/main/train.py#L26
|
|
368
|
+
if torch.isnan(net_loss).any():
|
|
369
|
+
return None
|
|
370
|
+
|
|
371
|
+
return output
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def denoisplit_musplit_loss(
|
|
375
|
+
model_outputs: tuple[torch.Tensor, dict[str, Any]],
|
|
376
|
+
targets: torch.Tensor,
|
|
377
|
+
loss_parameters: LVAELossParameters,
|
|
378
|
+
) -> Optional[dict[str, torch.Tensor]]:
|
|
379
|
+
"""Loss function for DenoiSplit.
|
|
380
|
+
|
|
381
|
+
Parameters
|
|
382
|
+
----------
|
|
383
|
+
model_outputs : tuple[torch.Tensor, dict[str, Any]]
|
|
384
|
+
Tuple containing the model predictions (shape is (B, `target_ch`, [Z], Y, X))
|
|
385
|
+
and the top-down layer data (e.g., sampled latents, KL-loss values, etc.).
|
|
386
|
+
targets : torch.Tensor
|
|
387
|
+
The target image used to compute the reconstruction loss. Shape is
|
|
388
|
+
(B, `target_ch`, [Z], Y, X).
|
|
389
|
+
loss_parameters : LVAELossParameters
|
|
390
|
+
The loss parameters for muSplit (e.g., KL hyperparameters, likelihood module,
|
|
391
|
+
noise model, etc.).
|
|
392
|
+
|
|
393
|
+
Returns
|
|
394
|
+
-------
|
|
395
|
+
output : Optional[dict[str, torch.Tensor]]
|
|
396
|
+
A dictionary containing the overall loss `["loss"]`, the reconstruction loss
|
|
397
|
+
`["reconstruction_loss"]`, and the KL divergence loss `["kl_loss"]`.
|
|
398
|
+
"""
|
|
399
|
+
predictions, td_data = model_outputs
|
|
400
|
+
|
|
401
|
+
# Reconstruction loss computation
|
|
402
|
+
recons_loss = reconstruction_loss_musplit_denoisplit(
|
|
403
|
+
predictions=predictions,
|
|
404
|
+
targets=targets,
|
|
405
|
+
nm_likelihood=loss_parameters.noise_model_likelihood,
|
|
406
|
+
gaussian_likelihood=loss_parameters.gaussian_likelihood,
|
|
407
|
+
nm_weight=loss_parameters.denoisplit_weight,
|
|
408
|
+
gaussian_weight=loss_parameters.musplit_weight,
|
|
409
|
+
)
|
|
410
|
+
if torch.isnan(recons_loss).any():
|
|
411
|
+
recons_loss = 0.0
|
|
412
|
+
|
|
413
|
+
# KL loss computation
|
|
414
|
+
if loss_parameters.non_stochastic: # TODO always false ?
|
|
415
|
+
kl_loss = torch.Tensor([0.0]).cuda()
|
|
416
|
+
else:
|
|
417
|
+
# NOTE: 'kl' key stands for the 'kl_samplewise' key in the TopDownLayer class.
|
|
418
|
+
# The different naming comes from `top_down_pass()` method in the LadderVAE.
|
|
419
|
+
denoisplit_kl = get_kl_divergence_loss_denoisplit(
|
|
420
|
+
topdown_data=td_data,
|
|
421
|
+
img_shape=targets.shape[2:], # input img spatial dims
|
|
422
|
+
)
|
|
423
|
+
musplit_kl = get_kl_divergence_loss_usplit(td_data)
|
|
424
|
+
kl_loss = (
|
|
425
|
+
loss_parameters.denoisplit_weight * denoisplit_kl
|
|
426
|
+
+ loss_parameters.musplit_weight * musplit_kl
|
|
427
|
+
)
|
|
428
|
+
# TODO `kl_weight` is hardcoded (???)
|
|
429
|
+
kl_loss = loss_parameters.kl_weight * kl_loss
|
|
430
|
+
|
|
431
|
+
net_loss = recons_loss + kl_loss
|
|
432
|
+
output = {
|
|
433
|
+
"loss": net_loss,
|
|
434
|
+
"reconstruction_loss": (
|
|
435
|
+
recons_loss.detach()
|
|
436
|
+
if isinstance(recons_loss, torch.Tensor)
|
|
437
|
+
else recons_loss
|
|
438
|
+
),
|
|
439
|
+
"kl_loss": kl_loss.detach(),
|
|
440
|
+
}
|
|
441
|
+
# https://github.com/openai/vdvae/blob/main/train.py#L26
|
|
442
|
+
if torch.isnan(net_loss).any():
|
|
443
|
+
return None
|
|
444
|
+
|
|
445
|
+
return output
|
|
File without changes
|
|
File without changes
|