-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add observe operation and new condition handler (#175)
* Separate observe and condition * Split up files and create observational handlers folder * imports * lint * rename test * add test about commutativity of do and condition * doc * union * fix particle test case * fix bug * chirho
- Loading branch information
Showing
8 changed files
with
247 additions
and
8 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
import chirho.observational.internals # noqa: F401 |
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 @@ | ||
from .condition import condition # noqa: F401 |
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,63 @@ | ||
from typing import Generic, Hashable, Mapping, TypeVar | ||
|
||
import pyro | ||
|
||
from chirho.observational.internals import ObserveNameMessenger | ||
from chirho.observational.ops import AtomicObservation, observe | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
class ConditionMessenger(Generic[T], ObserveNameMessenger): | ||
""" | ||
Condition on values in a probabilistic program. | ||
Can be used as a drop-in replacement for :func:`pyro.condition` that supports | ||
a richer set of observational data types and enables counterfactual inference. | ||
""" | ||
|
||
def __init__(self, data: Mapping[Hashable, AtomicObservation[T]]): | ||
self.data = data | ||
super().__init__() | ||
|
||
def _pyro_sample(self, msg): | ||
if pyro.poutine.util.site_is_subsample(msg) or pyro.poutine.util.site_is_factor( | ||
msg | ||
): | ||
return | ||
|
||
if msg["name"] not in self.data or msg["infer"].get("_do_not_observe", None): | ||
if ( | ||
"_markov_scope" in msg["infer"] | ||
and getattr(self, "_current_site", None) is not None | ||
): | ||
msg["infer"]["_markov_scope"].pop(self._current_site, None) | ||
return | ||
|
||
msg["stop"] = True | ||
msg["done"] = True | ||
|
||
# flags to guarantee commutativity of condition, intervene, trace | ||
msg["mask"] = False | ||
msg["is_observed"] = False | ||
msg["infer"]["is_auxiliary"] = True | ||
msg["infer"]["_do_not_trace"] = True | ||
msg["infer"]["_do_not_intervene"] = True | ||
msg["infer"]["_do_not_observe"] = True | ||
|
||
with pyro.poutine.infer_config( | ||
config_fn=lambda msg_: { | ||
"_do_not_observe": msg["name"] == msg_["name"] | ||
or msg_["infer"].get("_do_not_observe", False) | ||
} | ||
): | ||
try: | ||
self._current_site = msg["name"] | ||
msg["value"] = observe( | ||
msg["fn"], self.data[msg["name"]], name=msg["name"], **msg["kwargs"] | ||
) | ||
finally: | ||
self._current_site = None | ||
|
||
|
||
condition = pyro.poutine.handlers._make_handler(ConditionMessenger)[1] |
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 |
---|---|---|
|
@@ -8,6 +8,7 @@ | |
|
||
T = TypeVar("T") | ||
|
||
|
||
Kernel = Callable[[T, T], torch.Tensor] | ||
|
||
|
||
|
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,47 @@ | ||
from typing import Optional, TypeVar | ||
|
||
import pyro | ||
import pyro.distributions | ||
import torch | ||
|
||
from chirho.observational.ops import AtomicObservation, observe | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
@observe.register(int) | ||
@observe.register(float) | ||
@observe.register(bool) | ||
@observe.register(torch.Tensor) | ||
def _observe_deterministic(rv: T, obs: Optional[AtomicObservation[T]] = None, **kwargs): | ||
""" | ||
Observe a tensor in a probabilistic program. | ||
""" | ||
rv_dist = pyro.distributions.Delta( | ||
torch.as_tensor(rv), event_dim=kwargs.pop("event_dim", 0) | ||
) | ||
return observe(rv_dist, obs, **kwargs) | ||
|
||
|
||
@observe.register(pyro.distributions.Distribution) | ||
@pyro.poutine.runtime.effectful(type="observe") | ||
def _observe_distribution( | ||
rv: pyro.distributions.Distribution, | ||
obs: Optional[AtomicObservation[T]] = None, | ||
*, | ||
name: Optional[str] = None, | ||
**kwargs, | ||
) -> T: | ||
if name is None: | ||
raise ValueError("name must be specified when observing a distribution") | ||
|
||
if callable(obs): | ||
raise NotImplementedError("Dependent observations are not yet supported") | ||
|
||
return pyro.sample(name, rv, obs=obs, **kwargs) | ||
|
||
|
||
class ObserveNameMessenger(pyro.poutine.messenger.Messenger): | ||
def _pyro_observe(self, msg): | ||
if "name" not in msg["kwargs"]: | ||
msg["kwargs"]["name"] = msg["name"] |
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,18 @@ | ||
import functools | ||
from typing import Callable, Hashable, Mapping, Optional, TypeVar, Union | ||
|
||
T = TypeVar("T") | ||
|
||
AtomicObservation = Union[T, Callable[..., T]] # TODO add support for more atomic types | ||
CompoundObservation = Union[ | ||
Mapping[Hashable, AtomicObservation[T]], Callable[..., AtomicObservation[T]] | ||
] | ||
Observation = Union[AtomicObservation[T], CompoundObservation[T]] | ||
|
||
|
||
@functools.singledispatch | ||
def observe(rv, obs: Optional[Observation[T]] = None, **kwargs) -> T: | ||
""" | ||
Observe a random value in a probabilistic program. | ||
""" | ||
raise NotImplementedError(f"observe not implemented for type {type(rv)}") |
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