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

Add allow_unused arg for models with task-specific parameters #145

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
20 changes: 16 additions & 4 deletions torchmeta/utils/gradient_based.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ def gradient_update_parameters(model,
loss,
params=None,
step_size=0.5,
first_order=False):
first_order=False,
allow_unused=False):
"""Update of the meta-parameters with one step of gradient descent on the
loss function.

Expand All @@ -33,6 +34,10 @@ def gradient_update_parameters(model,
first_order : bool (default: `False`)
If `True`, then the first order approximation of MAML is used.

allow_unused : bool (default: `False`)
If `True`, set `allow_unused` to `True` when computing gradients. This
is useful, e.g., when your model has task-specific parameters.

Returns
-------
updated_params : `collections.OrderedDict` instance
Expand All @@ -48,16 +53,23 @@ def gradient_update_parameters(model,

grads = torch.autograd.grad(loss,
params.values(),
create_graph=not first_order)
create_graph=not first_order,
allow_unused=allow_unused)

updated_params = OrderedDict()

if isinstance(step_size, (dict, OrderedDict)):
for (name, param), grad in zip(params.items(), grads):
updated_params[name] = param - step_size[name] * grad
if grad is not None:
updated_params[name] = param - step_size[name] * grad
else:
updated_params[name] = param

else:
for (name, param), grad in zip(params.items(), grads):
updated_params[name] = param - step_size * grad
if grad is not None:
updated_params[name] = param - step_size * grad
else:
updated_params[name] = param

return updated_params