Skip to content

Commit 4df0b4b

Browse files
cxlclpre-commit-ci[bot]KumoLiuericspod
authored andcommitted
Stein's Unbiased Risk Estimator (SURE) loss and Conjugate Gradient (Project-MONAI#7308)
### Description Based on the discussion topic [here](Project-MONAI#7161 (comment)), we implemented the Conjugate-Gradient algorithm for linear operator inversion, and Stein's Unbiased Risk Estimator (SURE) [1] loss for ground-truth-date free diffusion process guidance that is proposed in [2] and illustrated in the algorithm below: <img width="650" alt="Screenshot 2023-12-10 at 10 19 25 PM" src="https://github.com/Project-MONAI/MONAI/assets/8581162/97069466-cbaf-44e0-b7a7-ae9deb8fd7f2"> The Conjugate-Gradient (CG) algorithm is used to solve for the inversion of the linear operator in Line-4 in the algorithm above, where the linear operator is too large to store explicitly as a matrix (such as FFT/IFFT of an image) and invert directly. Instead, we can solve for the linear inversion iteratively as in CG. The SURE loss is applied for Line-6 above. This is a differentiable loss function that can be used to train/giude an operator (e.g. neural network), where the pseudo ground truth is available but the reference ground truth is not. For example, in the MRI reconstruction, the pseudo ground truth is the zero-filled reconstruction and the reference ground truth is the fully sampled reconstruction. The reference ground truth is not available due to the lack of fully sampled. **Reference** [1] Stein, C.M.: Estimation of the mean of a multivariate normal distribution. Annals of Statistics 1981 [[paper link](https://projecteuclid.org/journals/annals-of-statistics/volume-9/issue-6/Estimation-of-the-Mean-of-a-Multivariate-Normal-Distribution/10.1214/aos/1176345632.full)] [2] B. Ozturkler et al. SMRD: SURE-based Robust MRI Reconstruction with Diffusion Models. MICCAI 2023 [[paper link](https://arxiv.org/pdf/2310.01799.pdf)] ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [x] New tests added to cover the changes. - [x] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [x] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [x] In-line docstrings updated. - [x] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: chaoliu <[email protected]> Signed-off-by: cxlcl <[email protected]> Signed-off-by: chaoliu <[email protected]> Signed-off-by: YunLiu <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: YunLiu <[email protected]> Co-authored-by: Eric Kerfoot <[email protected]> Signed-off-by: Nikolas Schmitz <[email protected]>
1 parent 8194026 commit 4df0b4b

File tree

8 files changed

+450
-0
lines changed

8 files changed

+450
-0
lines changed

docs/source/losses.rst

+5
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,11 @@ Reconstruction Losses
139139
.. autoclass:: JukeboxLoss
140140
:members:
141141

142+
`SURELoss`
143+
~~~~~~~~~~
144+
.. autoclass:: SURELoss
145+
:members:
146+
142147

143148
Loss Wrappers
144149
-------------

docs/source/networks.rst

+5
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,11 @@ Layers
408408
.. autoclass:: LLTM
409409
:members:
410410

411+
`ConjugateGradient`
412+
~~~~~~~~~~~~~~~~~~~
413+
.. autoclass:: ConjugateGradient
414+
:members:
415+
411416
`Utilities`
412417
~~~~~~~~~~~
413418
.. automodule:: monai.networks.layers.convutils

monai/losses/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,6 @@
4141
from .spatial_mask import MaskedLoss
4242
from .spectral_loss import JukeboxLoss
4343
from .ssim_loss import SSIMLoss
44+
from .sure_loss import SURELoss
4445
from .tversky import TverskyLoss
4546
from .unified_focal_loss import AsymmetricUnifiedFocalLoss

monai/losses/sure_loss.py

+200
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
# Copyright (c) MONAI Consortium
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
# Unless required by applicable law or agreed to in writing, software
7+
# distributed under the License is distributed on an "AS IS" BASIS,
8+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9+
# See the License for the specific language governing permissions and
10+
# limitations under the License.
11+
12+
from __future__ import annotations
13+
14+
from typing import Callable, Optional
15+
16+
import torch
17+
import torch.nn as nn
18+
from torch.nn.modules.loss import _Loss
19+
20+
21+
def complex_diff_abs_loss(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
22+
"""
23+
First compute the difference in the complex domain,
24+
then get the absolute value and take the mse
25+
26+
Args:
27+
x, y - B, 2, H, W real valued tensors representing complex numbers
28+
or B,1,H,W complex valued tensors
29+
Returns:
30+
l2_loss - scalar
31+
"""
32+
if not x.is_complex():
33+
x = torch.view_as_complex(x.permute(0, 2, 3, 1).contiguous())
34+
if not y.is_complex():
35+
y = torch.view_as_complex(y.permute(0, 2, 3, 1).contiguous())
36+
37+
diff = torch.abs(x - y)
38+
return nn.functional.mse_loss(diff, torch.zeros_like(diff), reduction="mean")
39+
40+
41+
def sure_loss_function(
42+
operator: Callable,
43+
x: torch.Tensor,
44+
y_pseudo_gt: torch.Tensor,
45+
y_ref: Optional[torch.Tensor] = None,
46+
eps: Optional[float] = -1.0,
47+
perturb_noise: Optional[torch.Tensor] = None,
48+
complex_input: Optional[bool] = False,
49+
) -> torch.Tensor:
50+
"""
51+
Args:
52+
operator (function): The operator function that takes in an input
53+
tensor x and returns an output tensor y. We will use this to compute
54+
the divergence. More specifically, we will perturb the input x by a
55+
small amount and compute the divergence between the perturbed output
56+
and the reference output
57+
58+
x (torch.Tensor): The input tensor of shape (B, C, H, W) to the
59+
operator. For complex input, the shape is (B, 2, H, W) aka C=2 real.
60+
For real input, the shape is (B, 1, H, W) real.
61+
62+
y_pseudo_gt (torch.Tensor): The pseudo ground truth tensor of shape
63+
(B, C, H, W) used to compute the L2 loss. For complex input, the shape is
64+
(B, 2, H, W) aka C=2 real. For real input, the shape is (B, 1, H, W)
65+
real.
66+
67+
y_ref (torch.Tensor, optional): The reference output tensor of shape
68+
(B, C, H, W) used to compute the divergence. Defaults to None. For
69+
complex input, the shape is (B, 2, H, W) aka C=2 real. For real input,
70+
the shape is (B, 1, H, W) real.
71+
72+
eps (float, optional): The perturbation scalar. Set to -1 to set it
73+
automatically estimated based on y_pseudo_gtk
74+
75+
perturb_noise (torch.Tensor, optional): The noise vector of shape (B, C, H, W).
76+
Defaults to None. For complex input, the shape is (B, 2, H, W) aka C=2 real.
77+
For real input, the shape is (B, 1, H, W) real.
78+
79+
complex_input(bool, optional): Whether the input is complex or not.
80+
Defaults to False.
81+
82+
Returns:
83+
sure_loss (torch.Tensor): The SURE loss scalar.
84+
"""
85+
# perturb input
86+
if perturb_noise is None:
87+
perturb_noise = torch.randn_like(x)
88+
if eps == -1.0:
89+
eps = float(torch.abs(y_pseudo_gt.max())) / 1000
90+
# get y_ref if not provided
91+
if y_ref is None:
92+
y_ref = operator(x)
93+
94+
# get perturbed output
95+
x_perturbed = x + eps * perturb_noise
96+
y_perturbed = operator(x_perturbed)
97+
# divergence
98+
divergence = torch.sum(1.0 / eps * torch.matmul(perturb_noise.permute(0, 1, 3, 2), y_perturbed - y_ref)) # type: ignore
99+
# l2 loss between y_ref, y_pseudo_gt
100+
if complex_input:
101+
l2_loss = complex_diff_abs_loss(y_ref, y_pseudo_gt)
102+
else:
103+
# real input
104+
l2_loss = nn.functional.mse_loss(y_ref, y_pseudo_gt, reduction="mean")
105+
106+
# sure loss
107+
sure_loss = l2_loss * divergence / (x.shape[0] * x.shape[2] * x.shape[3])
108+
return sure_loss
109+
110+
111+
class SURELoss(_Loss):
112+
"""
113+
Calculate the Stein's Unbiased Risk Estimator (SURE) loss for a given operator.
114+
115+
This is a differentiable loss function that can be used to train/guide an
116+
operator (e.g. neural network), where the pseudo ground truth is available
117+
but the reference ground truth is not. For example, in the MRI
118+
reconstruction, the pseudo ground truth is the zero-filled reconstruction
119+
and the reference ground truth is the fully sampled reconstruction. Often,
120+
the reference ground truth is not available due to the lack of fully sampled
121+
data.
122+
123+
The original SURE loss is proposed in [1]. The SURE loss used for guiding
124+
the diffusion model based MRI reconstruction is proposed in [2].
125+
126+
Reference
127+
128+
[1] Stein, C.M.: Estimation of the mean of a multivariate normal distribution. Annals of Statistics
129+
130+
[2] B. Ozturkler et al. SMRD: SURE-based Robust MRI Reconstruction with Diffusion Models.
131+
(https://arxiv.org/pdf/2310.01799.pdf)
132+
"""
133+
134+
def __init__(self, perturb_noise: Optional[torch.Tensor] = None, eps: Optional[float] = None) -> None:
135+
"""
136+
Args:
137+
perturb_noise (torch.Tensor, optional): The noise vector of shape
138+
(B, C, H, W). Defaults to None. For complex input, the shape is (B, 2, H, W) aka C=2 real.
139+
For real input, the shape is (B, 1, H, W) real.
140+
141+
eps (float, optional): The perturbation scalar. Defaults to None.
142+
"""
143+
super().__init__()
144+
self.perturb_noise = perturb_noise
145+
self.eps = eps
146+
147+
def forward(
148+
self,
149+
operator: Callable,
150+
x: torch.Tensor,
151+
y_pseudo_gt: torch.Tensor,
152+
y_ref: Optional[torch.Tensor] = None,
153+
complex_input: Optional[bool] = False,
154+
) -> torch.Tensor:
155+
"""
156+
Args:
157+
operator (function): The operator function that takes in an input
158+
tensor x and returns an output tensor y. We will use this to compute
159+
the divergence. More specifically, we will perturb the input x by a
160+
small amount and compute the divergence between the perturbed output
161+
and the reference output
162+
163+
x (torch.Tensor): The input tensor of shape (B, C, H, W) to the
164+
operator. C=1 or 2: For complex input, the shape is (B, 2, H, W) aka
165+
C=2 real. For real input, the shape is (B, 1, H, W) real.
166+
167+
y_pseudo_gt (torch.Tensor): The pseudo ground truth tensor of shape
168+
(B, C, H, W) used to compute the L2 loss. C=1 or 2: For complex
169+
input, the shape is (B, 2, H, W) aka C=2 real. For real input, the
170+
shape is (B, 1, H, W) real.
171+
172+
y_ref (torch.Tensor, optional): The reference output tensor of the
173+
same shape as y_pseudo_gt
174+
175+
Returns:
176+
sure_loss (torch.Tensor): The SURE loss scalar.
177+
"""
178+
179+
# check inputs shapes
180+
if x.dim() != 4:
181+
raise ValueError(f"Input tensor x should be 4D, got {x.dim()}.")
182+
if y_pseudo_gt.dim() != 4:
183+
raise ValueError(f"Input tensor y_pseudo_gt should be 4D, but got {y_pseudo_gt.dim()}.")
184+
if y_ref is not None and y_ref.dim() != 4:
185+
raise ValueError(f"Input tensor y_ref should be 4D, but got {y_ref.dim()}.")
186+
if x.shape != y_pseudo_gt.shape:
187+
raise ValueError(
188+
f"Input tensor x and y_pseudo_gt should have the same shape, but got x shape {x.shape}, "
189+
f"y_pseudo_gt shape {y_pseudo_gt.shape}."
190+
)
191+
if y_ref is not None and y_pseudo_gt.shape != y_ref.shape:
192+
raise ValueError(
193+
f"Input tensor y_pseudo_gt and y_ref should have the same shape, but got y_pseudo_gt shape {y_pseudo_gt.shape}, "
194+
f"y_ref shape {y_ref.shape}."
195+
)
196+
197+
# compute loss
198+
loss = sure_loss_function(operator, x, y_pseudo_gt, y_ref, self.eps, self.perturb_noise, complex_input)
199+
200+
return loss

monai/networks/layers/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from __future__ import annotations
1313

14+
from .conjugate_gradient import ConjugateGradient
1415
from .convutils import calculate_out_shape, gaussian_1d, polyval, same_padding, stride_minus_kernel_padding
1516
from .drop_path import DropPath
1617
from .factories import Act, Conv, Dropout, LayerFactory, Norm, Pad, Pool, split_args
+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Copyright (c) MONAI Consortium
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
# Unless required by applicable law or agreed to in writing, software
7+
# distributed under the License is distributed on an "AS IS" BASIS,
8+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9+
# See the License for the specific language governing permissions and
10+
# limitations under the License.
11+
12+
from __future__ import annotations
13+
14+
from typing import Callable
15+
16+
import torch
17+
from torch import nn
18+
19+
20+
def _zdot(x1: torch.Tensor, x2: torch.Tensor) -> torch.Tensor:
21+
"""
22+
Complex dot product between tensors x1 and x2: sum(x1.*x2)
23+
"""
24+
if torch.is_complex(x1):
25+
assert torch.is_complex(x2), "x1 and x2 must both be complex"
26+
return torch.sum(x1.conj() * x2)
27+
else:
28+
return torch.sum(x1 * x2)
29+
30+
31+
def _zdot_single(x: torch.Tensor) -> torch.Tensor:
32+
"""
33+
Complex dot product between tensor x and itself
34+
"""
35+
res = _zdot(x, x)
36+
if torch.is_complex(res):
37+
return res.real
38+
else:
39+
return res
40+
41+
42+
class ConjugateGradient(nn.Module):
43+
"""
44+
Congugate Gradient (CG) solver for linear systems Ax = y.
45+
46+
For linear_op that is positive definite and self-adjoint, CG is
47+
guaranteed to converge CG is often used to solve linear systems of the form
48+
Ax = y, where A is too large to store explicitly, but can be computed via a
49+
linear operator.
50+
51+
As a result, here we won't set A explicitly as a matrix, but rather as a
52+
linear operator. For example, A could be a FFT/IFFT operation
53+
"""
54+
55+
def __init__(self, linear_op: Callable, num_iter: int):
56+
"""
57+
Args:
58+
linear_op: Linear operator
59+
num_iter: Number of iterations to run CG
60+
"""
61+
super().__init__()
62+
63+
self.linear_op = linear_op
64+
self.num_iter = num_iter
65+
66+
def update(
67+
self, x: torch.Tensor, p: torch.Tensor, r: torch.Tensor, rsold: torch.Tensor
68+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
69+
"""
70+
perform one iteration of the CG method. It takes the current solution x,
71+
the current search direction p, the current residual r, and the old
72+
residual norm rsold as inputs. Then it computes the new solution, search
73+
direction, residual, and residual norm, and returns them.
74+
"""
75+
76+
dy = self.linear_op(p)
77+
p_dot_dy = _zdot(p, dy)
78+
alpha = rsold / p_dot_dy
79+
x = x + alpha * p
80+
r = r - alpha * dy
81+
rsnew = _zdot_single(r)
82+
beta = rsnew / rsold
83+
rsold = rsnew
84+
p = beta * p + r
85+
return x, p, r, rsold
86+
87+
def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
88+
"""
89+
run conjugate gradient for num_iter iterations to solve Ax = y
90+
91+
Args:
92+
x: tensor (real or complex); Initial guess for linear system Ax = y.
93+
The size of x should be applicable to the linear operator. For
94+
example, if the linear operator is FFT, then x is HCHW; if the
95+
linear operator is a matrix multiplication, then x is a vector
96+
97+
y: tensor (real or complex); Measurement. Same size as x
98+
99+
Returns:
100+
x: Solution to Ax = y
101+
"""
102+
# Compute residual
103+
r = y - self.linear_op(x)
104+
rsold = _zdot_single(r)
105+
p = r
106+
107+
# Update
108+
for _i in range(self.num_iter):
109+
x, p, r, rsold = self.update(x, p, r, rsold)
110+
if rsold < 1e-10:
111+
break
112+
return x

0 commit comments

Comments
 (0)