-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Fix VarAutoEncoder reparameterize returning mu+std at inference (#8413) #8933
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Shizoqua
wants to merge
3
commits into
Project-MONAI:dev
Choose a base branch
from
Shizoqua:fix/8413-varautoencoder-eval
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -51,6 +51,8 @@ class VarAutoEncoder(AutoEncoder): | |
| According to `Performance Tuning Guide <https://pytorch.org/tutorials/recipes/recipes/tuning_guide.html>`_, | ||
| if a conv layer is directly followed by a batch norm layer, bias should be False. | ||
| use_sigmoid: whether to use the sigmoid function on final output. Defaults to True. | ||
| use_mean_at_inference: whether to return the posterior mean (rather than ``mu + std``) | ||
| as the latent code during inference. Defaults to False for backward compatibility. | ||
|
|
||
| Examples:: | ||
|
|
||
|
|
@@ -90,9 +92,11 @@ def __init__( | |
| dropout: tuple | str | float | None = None, | ||
| bias: bool = True, | ||
| use_sigmoid: bool = True, | ||
| use_mean_at_inference: bool = False, | ||
| ) -> None: | ||
| self.in_channels, *self.in_shape = in_shape | ||
| self.use_sigmoid = use_sigmoid | ||
| self.use_mean_at_inference = use_mean_at_inference | ||
|
|
||
| self.latent_size = latent_size | ||
| self.final_size = np.asarray(self.in_shape, dtype=int) | ||
|
|
@@ -142,12 +146,27 @@ def decode_forward(self, z: torch.Tensor, use_sigmoid: bool = True) -> torch.Ten | |
| return x | ||
|
|
||
| def reparameterize(self, mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: | ||
| """Sample a latent code using the reparameterization trick. | ||
|
|
||
| At inference (eval mode), if ``use_mean_at_inference`` is enabled, the posterior | ||
| mean is returned directly. Otherwise, ``mu + std`` is returned, matching the | ||
| original behaviour. During training, returns ``mu + eps * std`` with | ||
| ``eps ~ N(0, I)``. | ||
|
|
||
| Args: | ||
| mu: Posterior mean, shape ``(batch, latent_size)``. | ||
| logvar: Log-variance of the posterior, same shape as ``mu``. | ||
|
|
||
| Returns: | ||
| Sampled latent code, same shape as ``mu``. | ||
| """ | ||
| if not self.training and self.use_mean_at_inference: | ||
| # At inference the latent code is the posterior mean; the random | ||
| # term is only added during training (the reparameterization trick). | ||
| return mu | ||
| std = torch.exp(0.5 * logvar) | ||
|
|
||
| if self.training: # multiply random noise with std only during training | ||
| std = torch.randn_like(std).mul(std) | ||
|
|
||
| return std.add_(mu) | ||
| eps = torch.randn_like(std) if self.training else torch.ones_like(std) | ||
| return mu + eps * std | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same change here as the above to avoid |
||
|
|
||
| def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: | ||
| mu, logvar = self.encode_forward(x) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd like to make a change back to something like the original to avoid making a large
ones_liketensor just to do a no-op multiplication, and to use inline operators to avoid further copies.