-
-
Notifications
You must be signed in to change notification settings - Fork 983
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 support for named dims (torchdim
)
#3347
Open
ordabayevy
wants to merge
14
commits into
dev
Choose a base branch
from
torchdim
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
14 commits
Select commit
Hold shift + click to select a range
014119e
wip
ordabayevy f1bc917
prototype
ordabayevy 76be6d4
Merge branch 'dev' into torchdim
ordabayevy 4dcfca2
rm named
ordabayevy 1874ead
clean up
ordabayevy 98d4f3f
Merge branch 'dev' into torchdim
ordabayevy 8cbbf2f
named_shape
ordabayevy 252661b
add test
ordabayevy c124798
Merge branch 'dev' into torchdim
ordabayevy 5538caa
fixes
ordabayevy 76bd184
minor fix
ordabayevy d458ec3
ignore
ordabayevy b6e8e05
fix test
ordabayevy a3bb34b
Merge branch 'dev' into torchdim
ordabayevy 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
Empty file.
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,6 @@ | ||
# Copyright Contributors to the Pyro project. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from pyro.contrib.named.infer.elbo import Trace_ELBO | ||
|
||
__all__ = ["Trace_ELBO"] |
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,133 @@ | ||
# Copyright Contributors to the Pyro project. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from typing import Any, Callable, Tuple | ||
|
||
import torch | ||
from functorch.dim import Dim | ||
from typing_extensions import ParamSpec | ||
|
||
import pyro | ||
from pyro import poutine | ||
from pyro.distributions.torch_distribution import TorchDistributionMixin | ||
from pyro.infer import ELBO as _OrigELBO | ||
from pyro.poutine.messenger import Messenger | ||
from pyro.poutine.runtime import Message | ||
|
||
_P = ParamSpec("_P") | ||
|
||
|
||
class ELBO(_OrigELBO): | ||
def _get_trace(self, *args, **kwargs): | ||
raise RuntimeError("shouldn't be here!") | ||
|
||
def differentiable_loss(self, model, guide, *args, **kwargs): | ||
raise NotImplementedError("Must implement differentiable_loss") | ||
|
||
def loss(self, model, guide, *args, **kwargs): | ||
return self.differentiable_loss(model, guide, *args, **kwargs).detach().item() | ||
|
||
def loss_and_grads(self, model, guide, *args, **kwargs): | ||
loss = self.differentiable_loss(model, guide, *args, **kwargs) | ||
loss.backward() | ||
return loss.item() | ||
|
||
|
||
def track_provenance(x: torch.Tensor, provenance: Dim) -> torch.Tensor: | ||
return x.unsqueeze(0)[provenance] | ||
|
||
|
||
class track_nonreparam(Messenger): | ||
def _pyro_post_sample(self, msg: Message) -> None: | ||
if ( | ||
msg["type"] == "sample" | ||
and isinstance(msg["fn"], TorchDistributionMixin) | ||
and not msg["is_observed"] | ||
and not msg["fn"].has_rsample | ||
): | ||
provenance = Dim(msg["name"]) | ||
msg["value"] = track_provenance(msg["value"], provenance) | ||
|
||
|
||
def get_importance_trace( | ||
model: Callable[_P, Any], | ||
guide: Callable[_P, Any], | ||
*args: _P.args, | ||
**kwargs: _P.kwargs | ||
) -> Tuple[poutine.Trace, poutine.Trace]: | ||
""" | ||
Returns traces from the guide and the model that is run against it. | ||
The returned traces also store the log probability at each site. | ||
""" | ||
with track_nonreparam(): | ||
guide_trace = poutine.trace(guide).get_trace(*args, **kwargs) | ||
replay_model = poutine.replay(model, trace=guide_trace) | ||
model_trace = poutine.trace(replay_model).get_trace(*args, **kwargs) | ||
|
||
for is_guide, trace in zip((True, False), (guide_trace, model_trace)): | ||
for site in list(trace.nodes.values()): | ||
if site["type"] == "sample" and isinstance( | ||
site["fn"], TorchDistributionMixin | ||
): | ||
log_prob = site["fn"].log_prob(site["value"]) | ||
site["log_prob"] = log_prob | ||
|
||
if is_guide and not site["fn"].has_rsample: | ||
# importance sampling weights | ||
site["log_measure"] = log_prob - log_prob.detach() | ||
else: | ||
trace.remove_node(site["name"]) | ||
return model_trace, guide_trace | ||
|
||
|
||
class Trace_ELBO(ELBO): | ||
def differentiable_loss( | ||
self, | ||
model: Callable[_P, Any], | ||
guide: Callable[_P, Any], | ||
*args: _P.args, | ||
**kwargs: _P.kwargs | ||
) -> torch.Tensor: | ||
if self.num_particles > 1: | ||
vectorize = pyro.plate( | ||
"num_particles", self.num_particles, dim=Dim("num_particles") | ||
) | ||
model = vectorize(model) | ||
guide = vectorize(guide) | ||
|
||
model_trace, guide_trace = get_importance_trace(model, guide, *args, **kwargs) | ||
|
||
cost_terms = [] | ||
# logp terms | ||
for site in model_trace.nodes.values(): | ||
cost = site["log_prob"] | ||
scale = site["scale"] | ||
batch_dims = tuple(f.dim for f in site["cond_indep_stack"]) | ||
deps = tuple(set(getattr(cost, "dims", ())) - set(batch_dims)) | ||
cost_terms.append((cost, scale, batch_dims, deps)) | ||
# -logq terms | ||
for site in guide_trace.nodes.values(): | ||
cost = -site["log_prob"] | ||
scale = site["scale"] | ||
batch_dims = tuple(f.dim for f in site["cond_indep_stack"]) | ||
deps = tuple(set(getattr(cost, "dims", ())) - set(batch_dims)) | ||
cost_terms.append((cost, scale, batch_dims, deps)) | ||
|
||
elbo = 0.0 | ||
for cost, scale, batch_dims, deps in cost_terms: | ||
if deps: | ||
dice_factor = 0.0 | ||
for key in deps: | ||
dice_factor += guide_trace.nodes[str(key)]["log_measure"] | ||
dice_factor_dims = getattr(dice_factor, "dims", ()) | ||
cost_dims = getattr(cost, "dims", ()) | ||
sum_dims = tuple(set(dice_factor_dims) - set(cost_dims)) | ||
if sum_dims: | ||
dice_factor = dice_factor.sum(sum_dims) | ||
cost = torch.exp(dice_factor) * cost | ||
cost = cost.mean(deps) | ||
if scale is not None: | ||
cost = cost * scale | ||
elbo += cost.sum(batch_dims) / self.num_particles | ||
|
||
return -elbo |
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 |
---|---|---|
|
@@ -215,3 +215,7 @@ def __init__(self, tensor): | |
|
||
def __getitem__(self, args): | ||
return vindex(self._tensor, args) | ||
|
||
|
||
def index_select(input, dim, index): | ||
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. Add type annotation. Move to contrib/named in the follow up PR. |
||
return input.order(dim)[index] |
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.
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.
Unit tests for distribution shapes for log_prob, mean, sample, rsample, entropy (fail when named and positional dims are mixed in the batch/event/sample shape; conflicting named dims)
Generalize named dim binding implementation.
Test transforms and support.
Shape inference.