From daea9a65ac6aefabce110e0f3a79c483138c3d08 Mon Sep 17 00:00:00 2001 From: Ben Zickel <35469979+BenZickel@users.noreply.github.com> Date: Wed, 10 Jul 2024 05:45:37 +0300 Subject: [PATCH 1/7] Equalize effect handler (#3375) --- docs/source/pyro.poutine.txt | 8 ++++ pyro/poutine/__init__.py | 2 + pyro/poutine/equalize_messenger.py | 77 ++++++++++++++++++++++++++++++ pyro/poutine/handlers.py | 24 ++++++++++ tests/poutine/test_poutines.py | 44 +++++++++++++++++ 5 files changed, 155 insertions(+) create mode 100644 pyro/poutine/equalize_messenger.py diff --git a/docs/source/pyro.poutine.txt b/docs/source/pyro.poutine.txt index f975759586..443b527ce6 100644 --- a/docs/source/pyro.poutine.txt +++ b/docs/source/pyro.poutine.txt @@ -54,6 +54,14 @@ ________________ :undoc-members: :show-inheritance: +EqualizeMessenger +____________________ + +.. automodule:: pyro.poutine.equalize_messenger + :members: + :undoc-members: + :show-inheritance: + EscapeMessenger ________________ diff --git a/pyro/poutine/__init__.py b/pyro/poutine/__init__.py index 6ea794c6bc..78d11a9655 100644 --- a/pyro/poutine/__init__.py +++ b/pyro/poutine/__init__.py @@ -8,6 +8,7 @@ condition, do, enum, + equalize, escape, infer_config, lift, @@ -36,6 +37,7 @@ "enable_validation", "enum", "escape", + "equalize", "get_mask", "infer_config", "is_validation_enabled", diff --git a/pyro/poutine/equalize_messenger.py b/pyro/poutine/equalize_messenger.py new file mode 100644 index 0000000000..035d96c06b --- /dev/null +++ b/pyro/poutine/equalize_messenger.py @@ -0,0 +1,77 @@ +# Copyright Contributors to the Pyro project. +# SPDX-License-Identifier: Apache-2.0 + +import re +from typing import List, Optional, Union + +from typing_extensions import Self + +from pyro.distributions import Delta +from pyro.poutine.messenger import Messenger +from pyro.poutine.runtime import Message + + +class EqualizeMessenger(Messenger): + """ + Given a stochastic function with some primitive statements and a list of names, + force the primitive statements at those names to have the same value, + with that value being the result of the first primitive statement matching those names. + + Consider the following Pyro program: + + >>> def per_category_model(category): + ... shift = pyro.param(f'{category}_shift', torch.randn(1)) + ... mean = pyro.sample(f'{category}_mean', pyro.distributions.Normal(0, 1)) + ... std = pyro.sample(f'{category}_std', pyro.distributions.LogNormal(0, 1)) + ... return pyro.sample(f'{category}_values', pyro.distributions.Normal(mean + shift, std)) + + Running the program for multiple categories can be done by + + >>> def model(categories): + ... return {category:per_category_model(category) for category in categories} + + To make the `std` sample sites have the same value, we can write + + >>> equal_std_model = pyro.poutine.equalize(model, '.+_std') + + If on top of the above we would like to make the 'shift' parameters identical, we can write + + >>> equal_std_param_model = pyro.poutine.equalize(equal_std_model, '.+_shift', 'param') + + :param fn: a stochastic function (callable containing Pyro primitive calls) + :param sites: a string or list of strings to match site names (the strings can be regular expressions) + :param type: a string specifying the site type (default is 'sample') + :returns: stochastic function decorated with a :class:`~pyro.poutine.equalize_messenger.EqualizeMessenger` + """ + + def __init__( + self, sites: Union[str, List[str]], type: Optional[str] = "sample" + ) -> None: + super().__init__() + self.sites = [sites] if isinstance(sites, str) else sites + self.type = type + + def __enter__(self) -> Self: + self.value = None + return super().__enter__() + + def _is_matching(self, msg: Message) -> bool: + if msg["type"] == self.type: + for site in self.sites: + if re.compile(site).fullmatch(msg["name"]) is not None: # type: ignore[arg-type] + return True + return False + + def _postprocess_message(self, msg: Message) -> None: + if self.value is None and self._is_matching(msg): + value = msg["value"] + assert value is not None + self.value = value + + def _process_message(self, msg: Message) -> None: + if self.value is not None and self._is_matching(msg): # type: ignore[unreachable] + msg["value"] = self.value # type: ignore[unreachable] + if msg["type"] == "sample": + msg["fn"] = Delta(self.value, event_dim=msg["fn"].event_dim) + msg["infer"] = {"_deterministic": True} + msg["is_observed"] = True diff --git a/pyro/poutine/handlers.py b/pyro/poutine/handlers.py index 278f6a60f2..343b1a1f4b 100644 --- a/pyro/poutine/handlers.py +++ b/pyro/poutine/handlers.py @@ -74,6 +74,7 @@ from pyro.poutine.condition_messenger import ConditionMessenger from pyro.poutine.do_messenger import DoMessenger from pyro.poutine.enum_messenger import EnumMessenger +from pyro.poutine.equalize_messenger import EqualizeMessenger from pyro.poutine.escape_messenger import EscapeMessenger from pyro.poutine.infer_config_messenger import InferConfigMessenger from pyro.poutine.lift_messenger import LiftMessenger @@ -301,6 +302,29 @@ def escape( # type: ignore[empty-body] ) -> Union[EscapeMessenger, Callable[_P, _T]]: ... +@overload +def equalize( + sites: Union[str, List[str]], + type: Optional[str], +) -> ConditionMessenger: ... + + +@overload +def equalize( + fn: Callable[_P, _T], + sites: Union[str, List[str]], + type: Optional[str], +) -> Callable[_P, _T]: ... + + +@_make_handler(EqualizeMessenger) +def equalize( # type: ignore[empty-body] + fn: Callable[_P, _T], + sites: Union[str, List[str]], + type: Optional[str], +) -> Union[EqualizeMessenger, Callable[_P, _T]]: ... + + @overload def infer_config( config_fn: Callable[["Message"], "InferDict"], diff --git a/tests/poutine/test_poutines.py b/tests/poutine/test_poutines.py index 944d26988d..7e2f7cfa8e 100644 --- a/tests/poutine/test_poutines.py +++ b/tests/poutine/test_poutines.py @@ -755,6 +755,50 @@ def test_infer_config_sample(self): assert tr.nodes["p"]["infer"] == {} +class EqualizeHandlerTests(TestCase): + def setUp(self): + def per_category_model(category): + shift = pyro.param(f"{category}_shift", torch.randn(1)) + mean = pyro.sample(f"{category}_mean", pyro.distributions.Normal(0, 1)) + std = pyro.sample(f"{category}_std", pyro.distributions.LogNormal(0, 1)) + with pyro.plate(f"{category}_num_samples", 5): + return pyro.sample( + f"{category}_values", pyro.distributions.Normal(mean + shift, std) + ) + + def model(categories=["dogs", "cats"]): + return {category: per_category_model(category) for category in categories} + + self.model = model + + def test_sample_site_equalization(self): + pyro.set_rng_seed(20240616) + pyro.clear_param_store() + model = poutine.equalize(self.model, ".+_std") + tr = pyro.poutine.trace(model).get_trace() + assert_equal(tr.nodes["cats_std"]["value"], tr.nodes["dogs_std"]["value"]) + assert_not_equal( + tr.nodes["cats_shift"]["value"], tr.nodes["dogs_shift"]["value"] + ) + guide = pyro.infer.autoguide.AutoNormal(model) + guide_sites = [*guide()] + assert guide_sites == [ + "dogs_mean", + "dogs_std", + "dogs_values", + "cats_mean", + "cats_values", + ] + + def test_param_equalization(self): + pyro.set_rng_seed(20240616) + pyro.clear_param_store() + model = poutine.equalize(self.model, ".+_shift", "param") + tr = pyro.poutine.trace(model).get_trace() + assert_equal(tr.nodes["cats_shift"]["value"], tr.nodes["dogs_shift"]["value"]) + assert_not_equal(tr.nodes["cats_std"]["value"], tr.nodes["dogs_std"]["value"]) + + @pytest.mark.parametrize("first_available_dim", [-1, -2, -3]) @pytest.mark.parametrize("depth", [0, 1, 2]) def test_enumerate_poutine(depth, first_available_dim): From b450623b225e4ea84c0b7b94d875860e22433d1a Mon Sep 17 00:00:00 2001 From: Ben Zickel <35469979+BenZickel@users.noreply.github.com> Date: Sun, 14 Jul 2024 03:11:08 +0300 Subject: [PATCH 2/7] Update mappings to Sphnix documentation of other projects. (#3383) Co-authored-by: Ben Zickel --- docs/source/conf.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/source/conf.py b/docs/source/conf.py index 1d55424c4d..26e0b7ef15 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -194,10 +194,10 @@ intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "torch": ("https://pytorch.org/docs/master/", None), - "funsor": ("http://funsor.pyro.ai/en/stable/", None), + "funsor": ("https://funsor.pyro.ai/en/stable/", None), "opt_einsum": ("https://optimized-einsum.readthedocs.io/en/stable/", None), - "scipy": ("https://docs.scipy.org/doc/scipy/reference/", None), - "Bio": ("https://biopython.org/docs/latest/api/", None), + "scipy": ("https://docs.scipy.org/doc/scipy/", None), + "Bio": ("https://biopython.org/docs/latest/", None), "horovod": ("https://horovod.readthedocs.io/en/stable/", None), "graphviz": ("https://graphviz.readthedocs.io/en/stable/", None), } From e3091e32b30c8614c0683b600edd62665c07c18a Mon Sep 17 00:00:00 2001 From: Ben Zickel <35469979+BenZickel@users.noreply.github.com> Date: Tue, 23 Jul 2024 16:25:10 +0300 Subject: [PATCH 3/7] Fix models not rendering after application of the equalize effect handler (#3387) * Fix models not rendering after application of the equalize effect handler. * Ignore newly added mypy callability check. --------- Co-authored-by: Ben Zickel --- pyro/nn/module.py | 2 +- pyro/poutine/equalize_messenger.py | 2 +- tests/poutine/test_poutines.py | 6 ++++++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/pyro/nn/module.py b/pyro/nn/module.py index b84a17875b..05190e24d7 100644 --- a/pyro/nn/module.py +++ b/pyro/nn/module.py @@ -138,7 +138,7 @@ def __get__( if name not in obj.__dict__["_pyro_params"]: init_value, constraint, event_dim = self # bind method's self arg - init_value = functools.partial(init_value, obj) # type: ignore[arg-type] + init_value = functools.partial(init_value, obj) # type: ignore[arg-type,misc,operator] setattr(obj, name, PyroParam(init_value, constraint, event_dim)) value: PyroParam = obj.__getattr__(name) return value diff --git a/pyro/poutine/equalize_messenger.py b/pyro/poutine/equalize_messenger.py index 035d96c06b..e17693267b 100644 --- a/pyro/poutine/equalize_messenger.py +++ b/pyro/poutine/equalize_messenger.py @@ -72,6 +72,6 @@ def _process_message(self, msg: Message) -> None: if self.value is not None and self._is_matching(msg): # type: ignore[unreachable] msg["value"] = self.value # type: ignore[unreachable] if msg["type"] == "sample": - msg["fn"] = Delta(self.value, event_dim=msg["fn"].event_dim) + msg["fn"] = Delta(self.value, event_dim=msg["fn"].event_dim).mask(False) msg["infer"] = {"_deterministic": True} msg["is_observed"] = True diff --git a/tests/poutine/test_poutines.py b/tests/poutine/test_poutines.py index 7e2f7cfa8e..c06a2a8778 100644 --- a/tests/poutine/test_poutines.py +++ b/tests/poutine/test_poutines.py @@ -798,6 +798,12 @@ def test_param_equalization(self): assert_equal(tr.nodes["cats_shift"]["value"], tr.nodes["dogs_shift"]["value"]) assert_not_equal(tr.nodes["cats_std"]["value"], tr.nodes["dogs_std"]["value"]) + def test_render_model(self): + pyro.set_rng_seed(20240616) + pyro.clear_param_store() + model = poutine.equalize(self.model, ".+_std") + pyro.render_model(model) + @pytest.mark.parametrize("first_available_dim", [-1, -2, -3]) @pytest.mark.parametrize("depth", [0, 1, 2]) From e0d6671637d47c6987e53b86958d2ab58a16b7f2 Mon Sep 17 00:00:00 2001 From: Ben Zickel <35469979+BenZickel@users.noreply.github.com> Date: Sat, 27 Jul 2024 19:33:58 +0300 Subject: [PATCH 4/7] Support PyTorch 2.4 in tests (#3389) --- examples/air/main.py | 2 +- examples/cvae/cvae.py | 2 +- examples/dmm.py | 2 +- pyro/contrib/examples/bart.py | 5 +++-- pyro/contrib/examples/nextstrain.py | 2 +- pyro/optim/optim.py | 4 +++- pyro/params/param_store.py | 2 +- tests/contrib/cevae/test_cevae.py | 2 +- tests/contrib/easyguide/test_easyguide.py | 2 +- tests/distributions/test_pickle.py | 2 +- tests/infer/mcmc/test_valid_models.py | 2 +- tests/infer/test_autoguide.py | 2 +- tests/nn/test_module.py | 6 +++--- tests/ops/einsum/test_adjoint.py | 2 +- tests/poutine/test_poutines.py | 2 +- 15 files changed, 21 insertions(+), 18 deletions(-) diff --git a/examples/air/main.py b/examples/air/main.py index b516cf28bb..dadf77260c 100644 --- a/examples/air/main.py +++ b/examples/air/main.py @@ -200,7 +200,7 @@ def z_pres_prior_p(opt_step, time_step): if "load" in args: print("Loading parameters...") - air.load_state_dict(torch.load(args.load)) + air.load_state_dict(torch.load(args.load, weights_only=False)) # Viz sample from prior. if args.viz: diff --git a/examples/cvae/cvae.py b/examples/cvae/cvae.py index 5f38a7ad93..80af6ca0f4 100644 --- a/examples/cvae/cvae.py +++ b/examples/cvae/cvae.py @@ -184,6 +184,6 @@ def train( break # Save model weights - cvae_net.load_state_dict(torch.load(model_path)) + cvae_net.load_state_dict(torch.load(model_path, weights_only=False)) cvae_net.eval() return cvae_net diff --git a/examples/dmm.py b/examples/dmm.py index 1c90e72f3e..aff48dd9a8 100644 --- a/examples/dmm.py +++ b/examples/dmm.py @@ -465,7 +465,7 @@ def load_checkpoint(): args.load_model ), "--load-model and/or --load-opt misspecified" logging.info("loading model from %s..." % args.load_model) - dmm.load_state_dict(torch.load(args.load_model)) + dmm.load_state_dict(torch.load(args.load_model, weights_only=False)) logging.info("loading optimizer states from %s..." % args.load_opt) adam.load(args.load_opt) logging.info("done loading model and optimizer states.") diff --git a/pyro/contrib/examples/bart.py b/pyro/contrib/examples/bart.py index f2ea719566..f7b1e852ca 100644 --- a/pyro/contrib/examples/bart.py +++ b/pyro/contrib/examples/bart.py @@ -11,6 +11,7 @@ import subprocess import sys import urllib +from functools import partial import torch @@ -120,12 +121,12 @@ def load_bart_od(): except urllib.error.HTTPError: logging.debug("cache miss, preprocessing from scratch") if os.path.exists(pkl_file): - return torch.load(pkl_file) + return torch.load(pkl_file, weights_only=False) filenames = multiprocessing.Pool(len(SOURCE_FILES)).map( _load_hourly_od, SOURCE_FILES ) - datasets = list(map(torch.load, filenames)) + datasets = list(map(partial(torch.load, weights_only=False), filenames)) stations = sorted(set().union(*(d["stations"].keys() for d in datasets))) min_time = min(int(d["rows"][:, 0].min()) for d in datasets) diff --git a/pyro/contrib/examples/nextstrain.py b/pyro/contrib/examples/nextstrain.py index df21c710de..4782d9b8e0 100644 --- a/pyro/contrib/examples/nextstrain.py +++ b/pyro/contrib/examples/nextstrain.py @@ -41,4 +41,4 @@ def load_nextstrain_counts(map_location=None) -> dict: # Load tensors to the default location. if map_location is None: map_location = torch.tensor(0.0).device - return torch.load(filename, map_location=map_location) + return torch.load(filename, map_location=map_location, weights_only=False) diff --git a/pyro/optim/optim.py b/pyro/optim/optim.py index b123d26bcb..b3d97300bf 100644 --- a/pyro/optim/optim.py +++ b/pyro/optim/optim.py @@ -192,7 +192,9 @@ def load(self, filename: str, map_location=None) -> None: Load optimizer state from disk """ with open(filename, "rb") as input_file: - state = torch.load(input_file, map_location=map_location) + state = torch.load( + input_file, map_location=map_location, weights_only=False + ) self.set_state(state) def _get_optim(self, param: Union[Iterable[Tensor], Iterable[Dict[Any, Any]]]): diff --git a/pyro/params/param_store.py b/pyro/params/param_store.py index ec9a7d645d..62e10fdb08 100644 --- a/pyro/params/param_store.py +++ b/pyro/params/param_store.py @@ -331,7 +331,7 @@ def load(self, filename: str, map_location: MAP_LOCATION = None) -> None: :type map_location: function, torch.device, string or a dict """ with open(filename, "rb") as input_file: - state = torch.load(input_file, map_location) + state = torch.load(input_file, map_location, weights_only=False) self.set_state(state) @contextmanager diff --git a/tests/contrib/cevae/test_cevae.py b/tests/contrib/cevae/test_cevae.py index 849927429a..b79774c362 100644 --- a/tests/contrib/cevae/test_cevae.py +++ b/tests/contrib/cevae/test_cevae.py @@ -64,7 +64,7 @@ def test_serialization(jit, feature_dim, outcome_dist): warnings.filterwarnings("ignore", category=UserWarning) torch.save(cevae, f) f.seek(0) - loaded_cevae = torch.load(f) + loaded_cevae = torch.load(f, weights_only=False) pyro.set_rng_seed(0) actual_ite = loaded_cevae.ite(x) diff --git a/tests/contrib/easyguide/test_easyguide.py b/tests/contrib/easyguide/test_easyguide.py index 4166cfc5a1..b4ee78d6fb 100644 --- a/tests/contrib/easyguide/test_easyguide.py +++ b/tests/contrib/easyguide/test_easyguide.py @@ -89,7 +89,7 @@ def test_serialize(): f = io.BytesIO() torch.save(guide, f) f.seek(0) - actual = torch.load(f) + actual = torch.load(f, weights_only=False) assert type(actual) == type(guide) assert dir(actual) == dir(guide) diff --git a/tests/distributions/test_pickle.py b/tests/distributions/test_pickle.py index b8ff30a456..c9bfd1a497 100644 --- a/tests/distributions/test_pickle.py +++ b/tests/distributions/test_pickle.py @@ -88,5 +88,5 @@ def test_pickle(Dist): # Note that pickling torch.Size() requires protocol >= 2 torch.save(dist, buffer, pickle_protocol=pickle.HIGHEST_PROTOCOL) buffer.seek(0) - deserialized = torch.load(buffer) + deserialized = torch.load(buffer, weights_only=False) assert isinstance(deserialized, Dist) diff --git a/tests/infer/mcmc/test_valid_models.py b/tests/infer/mcmc/test_valid_models.py index c173b2fad8..0e9b160860 100644 --- a/tests/infer/mcmc/test_valid_models.py +++ b/tests/infer/mcmc/test_valid_models.py @@ -420,7 +420,7 @@ def test_potential_fn_pickling(jit): buffer = io.BytesIO() torch.save(potential_fn, buffer) buffer.seek(0) - deser_potential_fn = torch.load(buffer) + deser_potential_fn = torch.load(buffer, weights_only=False) assert_close(deser_potential_fn(test_data), potential_fn(test_data)) diff --git a/tests/infer/test_autoguide.py b/tests/infer/test_autoguide.py index f316ee049d..9b640e6fcb 100644 --- a/tests/infer/test_autoguide.py +++ b/tests/infer/test_autoguide.py @@ -489,7 +489,7 @@ def test_serialization(auto_class, jit): f = io.BytesIO() torch.save(guide, f) f.seek(0) - guide_deser = torch.load(f) + guide_deser = torch.load(f, weights_only=False) # Check .call() result. pyro.set_rng_seed(0) diff --git a/tests/nn/test_module.py b/tests/nn/test_module.py index 07c4daedd1..64520033d3 100644 --- a/tests/nn/test_module.py +++ b/tests/nn/test_module.py @@ -598,7 +598,7 @@ def test_mixin_factory(): del module pyro.clear_param_store() f.seek(0) - module = torch.load(f) + module = torch.load(f, weights_only=False) assert type(module).__name__ == "PyroSequential" actual = module(data) assert_equal(actual, expected) @@ -680,7 +680,7 @@ def test_torch_serialize_attributes(local_params): torch.save(module, f) pyro.clear_param_store() f.seek(0) - actual = torch.load(f) + actual = torch.load(f, weights_only=False) assert_equal(actual.x, module.x) actual_names = {name for name, _ in actual.named_parameters()} @@ -704,7 +704,7 @@ def test_torch_serialize_decorators(local_params): torch.save(module, f) pyro.clear_param_store() f.seek(0) - actual = torch.load(f) + actual = torch.load(f, weights_only=False) assert_equal(actual.x, module.x) assert_equal(actual.y, module.y) diff --git a/tests/ops/einsum/test_adjoint.py b/tests/ops/einsum/test_adjoint.py index 4fc8b047b8..9c71432020 100644 --- a/tests/ops/einsum/test_adjoint.py +++ b/tests/ops/einsum/test_adjoint.py @@ -117,7 +117,7 @@ def test_marginal(equation): assert_equal(expected, actual) -@pytest.mark.filterwarnings("ignore:.*reduce_op is deprecated") +@pytest.mark.filterwarnings("ignore:.*reduce_op`? is deprecated") def test_require_backward_memory_leak(): tensors = [o for o in gc.get_objects() if torch.is_tensor(o)] num_global_tensors = len(tensors) diff --git a/tests/poutine/test_poutines.py b/tests/poutine/test_poutines.py index c06a2a8778..63d4a2b73c 100644 --- a/tests/poutine/test_poutines.py +++ b/tests/poutine/test_poutines.py @@ -1027,7 +1027,7 @@ def test_pickling(wrapper): # default protocol cannot serialize torch.Size objects (see https://github.com/pytorch/pytorch/issues/20823) torch.save(wrapped, buffer, pickle_protocol=pickle.HIGHEST_PROTOCOL) buffer.seek(0) - deserialized = torch.load(buffer) + deserialized = torch.load(buffer, weights_only=False) obs = torch.tensor(0.5) pyro.set_rng_seed(0) actual_trace = poutine.trace(deserialized).get_trace(obs) From 871abb8d5fb032887ad10809aa65c2ba329a694d Mon Sep 17 00:00:00 2001 From: Swarnim <134050970+Swarnim114@users.noreply.github.com> Date: Wed, 31 Jul 2024 12:42:51 +0530 Subject: [PATCH 5/7] Update CODE_OF_CONDUCT.md (#3391) --- CODE_OF_CONDUCT.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 8ef523520a..ed2f71d6fa 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -34,7 +34,7 @@ This Code of Conduct applies both within project spaces and in public spaces whe ## Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at fritzo@uber.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at fritz.obermeyer@gmail.com or fehiepsi@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. From a756d2f31cf19d958b591ac49bea602040ece1e7 Mon Sep 17 00:00:00 2001 From: Andreas Fehlner Date: Sun, 4 Aug 2024 16:48:18 +0200 Subject: [PATCH 6/7] add copyright and license headers to various files (#3384) --- .codecov.yml | 4 + .coveragerc | 4 + .gitattributes | 4 + .github/FUNDING.yml | 4 + .github/issue_template.md | 6 ++ .gitignore | 4 + .readthedocs.yml | 4 + CODE_OF_CONDUCT.md | 7 ++ CONTRIBUTING.md | 6 ++ LICENSES/Apache-2.0.txt | 73 +++++++++++++++++++ LICENSES/BSD-3-Clause.txt | 11 +++ LICENSES/MIT.txt | 9 +++ README.md | 6 ++ RELEASE-MANAGEMENT.md | 6 ++ docker/Dockerfile | 4 + docker/Makefile | 4 + docker/README.md | 6 ++ docker/install.sh | 5 ++ docs/Makefile | 4 + docs/README.md | 6 ++ docs/requirements.txt | 4 + docs/source/_static/css/pyro.css | 6 ++ .../_static/img/favicon/browserconfig.xml | 7 ++ examples/eight_schools/README.md | 6 ++ examples/mixed_hmm/README.md | 6 ++ examples/rsa/README.md | 6 ++ pyproject.toml | 4 + pyro/contrib/README.md | 6 ++ scripts/install_pytorch.sh | 4 + scripts/perf_test.sh | 4 + scripts/profile_model.sh | 4 + setup.cfg | 4 + tests/README.md | 6 ++ tutorial/Makefile | 4 + tutorial/README.md | 6 ++ tutorial/source/_static/css/pyro.css | 6 ++ tutorial/source/_static/img/dmm.tex | 4 + tutorial/source/sir_hmc.rst | 4 + 38 files changed, 268 insertions(+) create mode 100644 LICENSES/Apache-2.0.txt create mode 100644 LICENSES/BSD-3-Clause.txt create mode 100644 LICENSES/MIT.txt diff --git a/.codecov.yml b/.codecov.yml index 0f1430acfa..d74c7ec781 100644 --- a/.codecov.yml +++ b/.codecov.yml @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + ignore: - "pyro/docutil.py" - "pyro/logger.py" diff --git a/.coveragerc b/.coveragerc index 45b8e8e715..30f3c0dd8f 100644 --- a/.coveragerc +++ b/.coveragerc @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + [report] omit = pyro/docutil.py diff --git a/.gitattributes b/.gitattributes index 2f77e919cd..38a7c00c06 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,5 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + *.ipynb linguist-documentation diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 325287e1a3..a84d4dfdc0 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + # These are supported funding model platforms github: [fritzo] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] diff --git a/.github/issue_template.md b/.github/issue_template.md index 4549578b82..e3eb03eb16 100644 --- a/.github/issue_template.md +++ b/.github/issue_template.md @@ -1,3 +1,9 @@ + + ### Guidelines **NOTE:** Issues are for bugs and feature requests only. If you have a question about using Pyro or general modeling questions, please post it on the [forum](https://forum.pyro.ai/). diff --git a/.gitignore b/.gitignore index b35b756605..4e682ce1f7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + run_outputs* .DS_Store .benchmarks diff --git a/.readthedocs.yml b/.readthedocs.yml index ca4e808c59..d27cb95338 100644 --- a/.readthedocs.yml +++ b/.readthedocs.yml @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + # Required version: 2 diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index ed2f71d6fa..efd8260b09 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,3 +1,10 @@ + + + # Contributor Covenant Code of Conduct ## Our Pledge diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 981a2b715c..d4ffc33d26 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,3 +1,9 @@ + + # Development Please follow our established coding style including variable names, module imports, and function definitions. diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000000..137069b823 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,73 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + +To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSES/BSD-3-Clause.txt b/LICENSES/BSD-3-Clause.txt new file mode 100644 index 0000000000..ea890afbc7 --- /dev/null +++ b/LICENSES/BSD-3-Clause.txt @@ -0,0 +1,11 @@ +Copyright (c) . + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000000..2071b23b0e --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 027a1b4e21..66b7407e42 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,9 @@ + + diff --git a/RELEASE-MANAGEMENT.md b/RELEASE-MANAGEMENT.md index 87944fb532..762d85e7cc 100644 --- a/RELEASE-MANAGEMENT.md +++ b/RELEASE-MANAGEMENT.md @@ -1,3 +1,9 @@ + + # Pyro release management This describes the process by which versions of Pyro are officially released to the public. diff --git a/docker/Dockerfile b/docker/Dockerfile index f8c67fb178..730256fccb 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + ARG base_img=ubuntu:18.04 FROM ${base_img} diff --git a/docker/Makefile b/docker/Makefile index d13ff2f351..0f9abdc53b 100644 --- a/docker/Makefile +++ b/docker/Makefile @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + .PHONY: help create-host-workspace build build-gpu run run-gpu notebook notebook-gpu DOCKER_FILE=Dockerfile diff --git a/docker/README.md b/docker/README.md index fd80be555a..92e5d1e627 100644 --- a/docker/README.md +++ b/docker/README.md @@ -1,3 +1,9 @@ + + ## Using Pyro Docker Some utilities for building docker images and running Pyro inside a Docker container are diff --git a/docker/install.sh b/docker/install.sh index 705533bbaa..1f1f53323f 100755 --- a/docker/install.sh +++ b/docker/install.sh @@ -1,4 +1,9 @@ #!/usr/bin/env bash + +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + set -xe pip install --upgrade pip diff --git a/docs/Makefile b/docs/Makefile index 06bbf77d2f..3dca05ce3a 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + # Minimal makefile for Sphinx documentation # diff --git a/docs/README.md b/docs/README.md index 38e2a34673..c724cb1246 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,3 +1,9 @@ + + # Documentation # Pyro Documentation is supported by [Sphinx](http://www.sphinx-doc.org/en/stable/). To build the docs, run from the toplevel directory: diff --git a/docs/requirements.txt b/docs/requirements.txt index b14a67b6c4..3bae619297 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + sphinx==4.2.0 sphinx-rtd-theme==1.0.0 graphviz>=0.8 diff --git a/docs/source/_static/css/pyro.css b/docs/source/_static/css/pyro.css index 335d437a81..0561ba35e6 100644 --- a/docs/source/_static/css/pyro.css +++ b/docs/source/_static/css/pyro.css @@ -1,3 +1,9 @@ +/* + * Copyright Contributors to the Pyro project. + * + * SPDX-License-Identifier: Apache-2.0 + */ + @import url("theme.css"); .wy-side-nav-search { diff --git a/docs/source/_static/img/favicon/browserconfig.xml b/docs/source/_static/img/favicon/browserconfig.xml index c554148223..6430a6715b 100644 --- a/docs/source/_static/img/favicon/browserconfig.xml +++ b/docs/source/_static/img/favicon/browserconfig.xml @@ -1,2 +1,9 @@ + + + #ffffff \ No newline at end of file diff --git a/examples/eight_schools/README.md b/examples/eight_schools/README.md index 2b934eb145..c7066b90c1 100644 --- a/examples/eight_schools/README.md +++ b/examples/eight_schools/README.md @@ -1,3 +1,9 @@ + + Analysis of the eight schools data (chapter 5 of [Gelman et al 2013]) using MCMC (NUTS) and SVI. The starting model is the Stan model: diff --git a/examples/mixed_hmm/README.md b/examples/mixed_hmm/README.md index 649c8253ab..380d9d641b 100644 --- a/examples/mixed_hmm/README.md +++ b/examples/mixed_hmm/README.md @@ -1,3 +1,9 @@ + + # Hierarchical mixed-effect hidden Markov models Note: This is a cleaned-up version of the seal experiments in [Bingham et al 2019] that is a simplified variant of some of the analysis in the [momentuHMM harbour seal example](https://github.com/bmcclintock/momentuHMM/blob/master/vignettes/harbourSealExample.R) [McClintock et al 2018]. diff --git a/examples/rsa/README.md b/examples/rsa/README.md index 270dce7aae..2ca69a16f4 100644 --- a/examples/rsa/README.md +++ b/examples/rsa/README.md @@ -1,3 +1,9 @@ + + ## Rational Speech Acts (RSA) examples This folder contains examples of reasoning about reasoning with nested inference diff --git a/pyproject.toml b/pyproject.toml index fac4c43928..4ae021c471 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + [tool.ruff] line-length = 120 diff --git a/pyro/contrib/README.md b/pyro/contrib/README.md index b6195f026f..bbb71554ad 100644 --- a/pyro/contrib/README.md +++ b/pyro/contrib/README.md @@ -1,3 +1,9 @@ + + # Contributed Code Code in `pyro.contrib` is under various stages of development. diff --git a/scripts/install_pytorch.sh b/scripts/install_pytorch.sh index 73447e5cfa..c7d5910f4d 100644 --- a/scripts/install_pytorch.sh +++ b/scripts/install_pytorch.sh @@ -1,5 +1,9 @@ #!/usr/bin/env bash +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + set -xe diff --git a/scripts/perf_test.sh b/scripts/perf_test.sh index ed911d8cff..86186ad218 100644 --- a/scripts/perf_test.sh +++ b/scripts/perf_test.sh @@ -1,5 +1,9 @@ #!/usr/bin/env bash +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + set -xe function _cleanup() { diff --git a/scripts/profile_model.sh b/scripts/profile_model.sh index 5304196be5..b2a1005e4d 100644 --- a/scripts/profile_model.sh +++ b/scripts/profile_model.sh @@ -1,5 +1,9 @@ #!/usr/bin/env bash +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + set -xe function _cleanup() { diff --git a/setup.cfg b/setup.cfg index 1da059e331..a92c6f00d7 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + [tool:pytest] filterwarnings = error ignore:numpy.ufunc size changed:RuntimeWarning diff --git a/tests/README.md b/tests/README.md index 54111e3266..a6fc03918e 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,3 +1,9 @@ + + # Testing ### Building PyTorch binaries for Travis CI diff --git a/tutorial/Makefile b/tutorial/Makefile index ee10d1f4ed..a1410d5f0e 100644 --- a/tutorial/Makefile +++ b/tutorial/Makefile @@ -1,3 +1,7 @@ +# Copyright Contributors to the Pyro project. +# +# SPDX-License-Identifier: Apache-2.0 + # Minimal makefile for Sphinx documentation # diff --git a/tutorial/README.md b/tutorial/README.md index 9e498f8a04..190fbe2beb 100644 --- a/tutorial/README.md +++ b/tutorial/README.md @@ -1 +1,7 @@ + + [http://pyro.ai/examples](http://pyro.ai/examples) diff --git a/tutorial/source/_static/css/pyro.css b/tutorial/source/_static/css/pyro.css index 335d437a81..0561ba35e6 100644 --- a/tutorial/source/_static/css/pyro.css +++ b/tutorial/source/_static/css/pyro.css @@ -1,3 +1,9 @@ +/* + * Copyright Contributors to the Pyro project. + * + * SPDX-License-Identifier: Apache-2.0 + */ + @import url("theme.css"); .wy-side-nav-search { diff --git a/tutorial/source/_static/img/dmm.tex b/tutorial/source/_static/img/dmm.tex index 4b8b4e6ac0..1d2053b2b2 100644 --- a/tutorial/source/_static/img/dmm.tex +++ b/tutorial/source/_static/img/dmm.tex @@ -1,3 +1,7 @@ +% Copyright Contributors to the Pyro project. +% +% SPDX-License-Identifier: Apache-2.0 + \documentclass[12pt]{article} \usepackage{amsmath,amscd,amssymb} \usepackage[pdftex]{graphicx} diff --git a/tutorial/source/sir_hmc.rst b/tutorial/source/sir_hmc.rst index ccc26a33e3..8a196d90f1 100644 --- a/tutorial/source/sir_hmc.rst +++ b/tutorial/source/sir_hmc.rst @@ -1,3 +1,7 @@ +.. Copyright Contributors to the Pyro project. +.. +.. SPDX-License-Identifier: Apache-2.0 + Example: Epidemiological inference via HMC ========================================== From 6130da03dd8654250567aa9bd456ea000242e7a6 Mon Sep 17 00:00:00 2001 From: Ben Zickel <35469979+BenZickel@users.noreply.github.com> Date: Sun, 4 Aug 2024 17:55:41 +0300 Subject: [PATCH 7/7] Make Predictive work with the SplitReparam reparameterizer [bugfix] (#3388) --- pyro/infer/predictive.py | 8 +++- tests/infer/reparam/test_split.py | 77 ++++++++++++++++++++++--------- 2 files changed, 62 insertions(+), 23 deletions(-) diff --git a/pyro/infer/predictive.py b/pyro/infer/predictive.py index e30099c85e..b57a193f4d 100644 --- a/pyro/infer/predictive.py +++ b/pyro/infer/predictive.py @@ -10,6 +10,7 @@ import pyro import pyro.poutine as poutine +from pyro.infer.autoguide.initialization import InitMessenger, init_to_sample from pyro.infer.importance import LogWeightsMixin from pyro.infer.util import CloneMixin, plate_log_prob_sum from pyro.poutine.trace_struct import Trace @@ -86,12 +87,15 @@ def _predictive( mask=True, ): model = torch.no_grad()(poutine.mask(model, mask=False) if mask else model) - max_plate_nesting = _guess_max_plate_nesting(model, model_args, model_kwargs) + initailized_model = InitMessenger(init_to_sample)(model) + max_plate_nesting = _guess_max_plate_nesting( + initailized_model, model_args, model_kwargs + ) vectorize = pyro.plate( _predictive_vectorize_plate_name, num_samples, dim=-max_plate_nesting - 1 ) model_trace = prune_subsample_sites( - poutine.trace(model).get_trace(*model_args, **model_kwargs) + poutine.trace(initailized_model).get_trace(*model_args, **model_kwargs) ) reshaped_samples = {} diff --git a/tests/infer/reparam/test_split.py b/tests/infer/reparam/test_split.py index 6337069ea0..fb450c4220 100644 --- a/tests/infer/reparam/test_split.py +++ b/tests/infer/reparam/test_split.py @@ -13,8 +13,7 @@ from .util import check_init_reparam - -@pytest.mark.parametrize( +event_shape_splits_dim = pytest.mark.parametrize( "event_shape,splits,dim", [ ((6,), [2, 1, 3], -1), @@ -31,7 +30,13 @@ ], ids=str, ) -@pytest.mark.parametrize("batch_shape", [(), (4,), (3, 2)], ids=str) + + +batch_shape = pytest.mark.parametrize("batch_shape", [(), (4,), (3, 2)], ids=str) + + +@event_shape_splits_dim +@batch_shape def test_normal(batch_shape, event_shape, splits, dim): shape = batch_shape + event_shape loc = torch.empty(shape).uniform_(-1.0, 1.0).requires_grad_() @@ -72,24 +77,8 @@ def model(): assert_close(actual_grads, expected_grads) -@pytest.mark.parametrize( - "event_shape,splits,dim", - [ - ((6,), [2, 1, 3], -1), - ( - ( - 2, - 5, - ), - [2, 3], - -1, - ), - ((4, 2), [1, 3], -2), - ((2, 3, 1), [1, 2], -2), - ], - ids=str, -) -@pytest.mark.parametrize("batch_shape", [(), (4,), (3, 2)], ids=str) +@event_shape_splits_dim +@batch_shape def test_init(batch_shape, event_shape, splits, dim): shape = batch_shape + event_shape loc = torch.empty(shape).uniform_(-1.0, 1.0) @@ -100,3 +89,49 @@ def model(): return pyro.sample("x", dist.Normal(loc, scale).to_event(len(event_shape))) check_init_reparam(model, SplitReparam(splits, dim)) + + +@event_shape_splits_dim +@batch_shape +def test_predictive(batch_shape, event_shape, splits, dim): + shape = batch_shape + event_shape + loc = torch.empty(shape).uniform_(-1.0, 1.0) + scale = torch.empty(shape).uniform_(0.5, 1.5) + + def model(): + with pyro.plate_stack("plates", batch_shape): + pyro.sample("x", dist.Normal(loc, scale).to_event(len(event_shape))) + + # Reparametrize model + rep = SplitReparam(splits, dim) + reparam_model = poutine.reparam(model, {"x": rep}) + + # Fit guide to reparametrized model + guide = pyro.infer.autoguide.guides.AutoMultivariateNormal(reparam_model) + optimizer = pyro.optim.Adam(dict(lr=0.01)) + loss = pyro.infer.JitTrace_ELBO( + num_particles=20, vectorize_particles=True, ignore_jit_warnings=True + ) + svi = pyro.infer.SVI(reparam_model, guide, optimizer, loss) + for count in range(1001): + loss = svi.step() + if count % 100 == 0: + print(f"iteration {count} loss = {loss}") + + # Sample from model using the guide + num_samples = 100000 + parallel = True + sites = ["x_split_{}".format(i) for i in range(len(splits))] + values = pyro.infer.Predictive( + reparam_model, + guide=guide, + num_samples=num_samples, + parallel=parallel, + return_sites=sites, + )() + + # Verify sampling + mean = torch.cat([values[site].mean(0) for site in sites], dim=dim) + std = torch.cat([values[site].std(0) for site in sites], dim=dim) + assert_close(mean, loc, atol=0.1) + assert_close(std, scale, rtol=0.1)