-
Notifications
You must be signed in to change notification settings - Fork 655
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
🚜 Refactor loss computation #364
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8568c73
remove unused variable
djdameln d0ec1f5
refactor fastflow loss
djdameln 0adecf5
add fastflow loss class
djdameln 06b4a4b
refactor STFPM loss
djdameln 673a7c3
refactor ganomaly loss
djdameln 6938ef1
Add missing fastflow loss description
samet-akcay 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 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 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 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 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 |
---|---|---|
@@ -0,0 +1,28 @@ | ||
"""Loss function for the FastFlow Model Implementation.""" | ||
|
||
# Copyright (C) 2022 Intel Corporation | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from typing import List | ||
|
||
import torch | ||
from torch import Tensor, nn | ||
|
||
|
||
class FastflowLoss(nn.Module): | ||
"""FastFlow Loss.""" | ||
|
||
def forward(self, hidden_variables: List[Tensor], jacobians: List[Tensor]) -> Tensor: | ||
"""Calculate the Fastflow loss. | ||
|
||
Args: | ||
hidden_variables (List[Tensor]): Hidden variables from the fastflow model. f: X -> Z | ||
jacobians (List[Tensor]): Log of the jacobian determinants from the fastflow model. | ||
|
||
Returns: | ||
Tensor: _description_ | ||
""" | ||
loss = torch.tensor(0.0, device=hidden_variables[0].device) # pylint: disable=not-callable | ||
for (hidden_variable, jacobian) in zip(hidden_variables, jacobians): | ||
loss += torch.mean(0.5 * torch.sum(hidden_variable**2, dim=(1, 2, 3)) - jacobian) | ||
return loss |
This file contains 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 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,7 +51,7 @@ metrics: | |
adaptive: true | ||
|
||
project: | ||
seed: 0 | ||
seed: 42 | ||
path: ./results | ||
|
||
logging: | ||
|
This file contains 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 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 |
---|---|---|
@@ -0,0 +1,79 @@ | ||
"""Loss function for the GANomaly Model Implementation.""" | ||
|
||
# Copyright (C) 2022 Intel Corporation | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
import torch | ||
from torch import Tensor, nn | ||
|
||
|
||
class GeneratorLoss(nn.Module): | ||
"""Generator loss for the GANomaly model. | ||
|
||
Args: | ||
wadv (int, optional): Weight for adversarial loss. Defaults to 1. | ||
wcon (int, optional): Image regeneration weight. Defaults to 50. | ||
wenc (int, optional): Latent vector encoder weight. Defaults to 1. | ||
""" | ||
|
||
def __init__(self, wadv=1, wcon=50, wenc=1): | ||
super().__init__() | ||
|
||
self.loss_enc = nn.SmoothL1Loss() | ||
self.loss_adv = nn.MSELoss() | ||
self.loss_con = nn.L1Loss() | ||
|
||
self.wadv = wadv | ||
self.wcon = wcon | ||
self.wenc = wenc | ||
|
||
def forward( | ||
self, latent_i: Tensor, latent_o: Tensor, images: Tensor, fake: Tensor, pred_real: Tensor, pred_fake: Tensor | ||
) -> Tensor: | ||
"""Compute the loss for a batch. | ||
|
||
Args: | ||
latent_i (Tensor): Latent features of the first encoder. | ||
latent_o (Tensor): Latent features of the second encoder. | ||
images (Tensor): Real image that served as input of the generator. | ||
fake (Tensor): Generated image. | ||
pred_real (Tensor): Discriminator predictions for the real image. | ||
pred_fake (Tensor): Discriminator predictions for the fake image. | ||
|
||
Returns: | ||
Tensor: The computed generator loss. | ||
""" | ||
error_enc = self.loss_enc(latent_i, latent_o) | ||
error_con = self.loss_con(images, fake) | ||
error_adv = self.loss_adv(pred_real, pred_fake) | ||
|
||
loss = error_adv * self.wadv + error_con * self.wcon + error_enc * self.wenc | ||
return loss | ||
|
||
|
||
class DiscriminatorLoss(nn.Module): | ||
"""Discriminator loss for the GANomaly model.""" | ||
|
||
def __init__(self): | ||
super().__init__() | ||
|
||
self.loss_bce = nn.BCELoss() | ||
|
||
def forward(self, pred_real, pred_fake): | ||
"""Compye the loss for a predicted batch. | ||
|
||
Args: | ||
pred_real (Tensor): Discriminator predictions for the real image. | ||
pred_fake (Tensor): Discriminator predictions for the fake image. | ||
|
||
Returns: | ||
Tensor: The computed discriminator loss. | ||
""" | ||
error_discriminator_real = self.loss_bce( | ||
pred_real, torch.ones(size=pred_real.shape, dtype=torch.float32, device=pred_real.device) | ||
) | ||
error_discriminator_fake = self.loss_bce( | ||
pred_fake, torch.zeros(size=pred_fake.shape, dtype=torch.float32, device=pred_fake.device) | ||
) | ||
loss_discriminator = (error_discriminator_fake + error_discriminator_real) * 0.5 | ||
return loss_discriminator |
This file contains 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 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.
This is a leftover from the previous PR, but would be good to add a description here in this PR.