Skip to content
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

Towards SoftAdapt loss balancing for tf.compat.v1 #1586

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions deepxde/callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,3 +571,34 @@ def on_epoch_end(self):
raise ValueError(
"`num_bcs` changed! Please update the loss function by `model.compile`."
)


class SoftAdapt(Callback):
"""Use adaptive loss balancing.

Args:
beta: If beta > 0, then softAdapt will pay more attention the worst performing
loss component. If beta < 0, then SoftAdapt will assign higher weights
to the better performing components. Beta==0 is the trivial case and
all loss components will have coefficient 1.
epsilon: parameter to prevent overflows.

"""

def __init__(self, beta=.1, epsilon=1e-8):
super().__init__()

self.beta = beta
self.epsilon = epsilon

def on_train_begin(self):
loss_weights = tf.constant(self.model.loss_weights)
loss_weights = dde.Variable(loss_weights, trainable=False, dtype=loss_weights.dtype)
loss_weights *= 0

Copy link
Contributor Author

@pescap pescap Dec 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am trying to allow loss_weights to be Variable, such that the loss function updates automatically every time that the weights change. Any clue @lululxvi ?

Here, I was trying to set the loss_weights to 0. Therefore, the loss shall give 0 for next epochs (which is not the case so far).

Shall we define loss_weights differently in model.compile?

Maybe we need to work here in:

deepxde/deepxde/model.py

Lines 169 to 183 in 3b08fe3

def losses(losses_fn):
# Data losses
losses = losses_fn(
self.net.targets, self.net.outputs, loss_fn, self.net.inputs, self
)
if not isinstance(losses, list):
losses = [losses]
# Regularization loss
if self.net.regularizer is not None:
losses.append(tf.losses.get_regularization_loss())
losses = tf.convert_to_tensor(losses)
# Weighted losses
if loss_weights is not None:
losses *= loss_weights
return losses

Thank you!

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do you plan to update loss_weights?

self.model.loss_weights = loss_weights

print(loss_weights, 'loss_weights')
# Allow instances to be re-used.
# Evaluate coefficients.
# Update weights.