Skip to content

Add capability of regularization towards random weights. #27

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
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all 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
23 changes: 18 additions & 5 deletions enn/losses/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ def noisy_loss(
def add_l2_weight_decay(
loss_fn: _LossFn,
scale: Union[float, Callable[[hk.Params], hk.Params]],
predicate: Optional[PredicateFn] = None
predicate: Optional[PredicateFn] = None,
regularize_towards_random_weights: bool = False,
) -> _LossFn:
"""Adds scale * l2 weight decay to an existing loss function."""
try: # Scale is numeric.
Expand All @@ -79,14 +80,26 @@ def add_l2_weight_decay(

def new_loss(
enn: base.EpistemicNetwork[base.Input, base.Output],
params: hk.Params, state: hk.State, batch: base.Data,
key: chex.PRNGKey) -> base.LossOutput:
loss, (state, metrics) = loss_fn(enn, params, state, batch, key)
params: hk.Params,
state: hk.State,
batch: base.Data,
key: chex.PRNGKey,
) -> base.LossOutput:
loss_key, params_key = jax.random.split(key)
loss, (state, metrics) = loss_fn(enn, params, state, batch, loss_key)
if regularize_towards_random_weights:
random_params = jax.tree_util.tree_map(
lambda x: jax.random.normal(params_key, x.shape), params
)
params = jax.tree_util.tree_map(
lambda p, rp: p - rp, params, random_params
)
decay = l2_weights_with_predicate(scale_fn(params), predicate)
total_loss = loss + decay
total_loss = loss + decay
metrics['decay'] = decay
metrics['raw_loss'] = loss
return total_loss, (state, metrics)

return new_loss


Expand Down
Loading