fritzo: @neerajprad after this merges I will copy the changes to funsor.minipyro. At some point we should also port the changes to numpyro.minipyro.
fritzo: > how important is it to maintain backwards compatibility

I agree with @eb8680 that in the case of *.minipyro it is more important to be able to write simple implementations than to support all previous features. This version is still compatible with the use `[pyro.param(name) for name in pyro.get_param_store()]`, and I think it's reasonable to limit the informal minipyro spec to this narrow usage.
eb8680: > get_param_store() API

I suppose we could support this by constructing a new dictionary:
```
def get_param_store():
    return {name: pyro.param(name) for name in PYRO_PARAM_STORE.keys()}
```
diff --git a/examples/minipyro.py b/examples/minipyro.py
index b5044465..ecddf18a 100644
--- a/examples/minipyro.py
+++ b/examples/minipyro.py
@@ -53,7 +53,8 @@ def main(args):
 
         # Report the final values of the variational parameters
         # in the guide after training.
-        for name, value in pyro.get_param_store().items():
+        for name in pyro.get_param_store():
+            value = pyro.param(name)
             print("{} = {}".format(name, value.detach().cpu().numpy()))
 
         # For this simple (conjugate) model we know the exact posterior. In
diff --git a/pyro/contrib/minipyro.py b/pyro/contrib/minipyro.py
index 367190fc..d60bf8d2 100644
--- a/pyro/contrib/minipyro.py
+++ b/pyro/contrib/minipyro.py
@@ -14,6 +14,7 @@ found at examples/minipyro.py.
 from __future__ import absolute_import, division, print_function
 
 from collections import OrderedDict
+import weakref
 
 import torch
 
@@ -25,7 +26,7 @@ import torch
 #     See http://docs.pyro.ai/en/0.3.1/parameters.html
 
 PYRO_STACK = []
-PARAM_STORE = {}
+PARAM_STORE = {}  # maps name -> (unconstrained_value, constraint)
 
 
 def get_param_store():
@@ -167,25 +168,37 @@ def sample(name, fn, obs=None):
     return msg["value"]
 
 
-# param is an effectful version of PARAM_STORE.setdefault
+# param is an effectful version of PARAM_STORE.setdefault that also handles constraints.
 # When any effect handlers are active, it constructs an initial message and calls apply_stack.
-def param(name, init_value=None):
-
-    def fn(init_value):
-        value = PARAM_STORE.setdefault(name, init_value)
-        value.requires_grad_()
-        return value
+def param(name, init_value=None, constraint=torch.distributions.constraints.real):
+
+    def fn(init_value, constraint):
+        if name in PARAM_STORE:
+            unconstrained_value, constraint = PARAM_STORE[name]
+        else:
+            # Initialize with a constrained value.
+            assert init_value is not None
+            with torch.no_grad():
+                constrained_value = init_value.detach()
+                unconstrained_value = torch.distributions.transform_to(constraint).inv(constrained_value)
+            unconstrained_value.requires_grad_()
+            PARAM_STORE[name] = unconstrained_value, constraint
+
+        # Transform from unconstrained space to constrained space.
+        constrained_value = torch.distributions.transform_to(constraint)(unconstrained_value)
+        constrained_value.unconstrained = weakref.ref(unconstrained_value)
+        return constrained_value
 
     # if there are no active Messengers, we just draw a sample and return it as expected:
     if not PYRO_STACK:
-        return fn(init_value)
+        return fn(init_value, constraint)
 
     # Otherwise, we initialize a message...
     initial_msg = {
         "type": "param",
         "name": name,
         "fn": fn,
-        "args": (init_value,),
+        "args": (init_value, constraint),
         "value": None,
     }
 
@@ -247,7 +260,8 @@ class SVI(object):
         # Differentiate the loss.
         loss.backward()
         # Grab all the parameters from the trace.
-        params = [site["value"] for site in param_capture.values()]
+        params = [site["value"].unconstrained()
+                  for site in param_capture.values()]
         # Take a step w.r.t. each parameter in params.
         self.optim(params)
         # Zero out the gradients so that they don't accumulate.

[FR] Support constraints in minipyro
Currently constraints in Pyro are handled by a `ParamStoreDict` class. The `ParamStoreDict` interface was simplified in #1363, but the class remains complex to retain backwards compatibility. It would be nice to pull out the minimal logic needed to handle constraints.

We could do this in minipyro in two different ways:
1. Simplify the `ParamStoreDict` to be a simple dict whose values are `(unconstrained_value, constraint)` pairs, and move `transform_to(constraint)` logic into `pyro.param()`.
    Advantages: less code overall
2. Keep the logic in `ParamStoreDict` but simplify its interface.
    Advantages: easier for users to use the `PARAM_STORE` directly
diff --git a/tests/contrib/test_minipyro.py b/tests/contrib/test_minipyro.py
new file mode 100644
index 00000000..9e99b768
--- /dev/null
+++ b/tests/contrib/test_minipyro.py
@@ -0,0 +1,192 @@
+from __future__ import absolute_import, division, print_function
+
+import warnings
+
+import pytest
+import torch
+from torch.distributions import constraints
+
+from pyro.generic import distributions as dist
+from pyro.generic import infer, optim, pyro, pyro_backend
+from tests.common import assert_close, xfail_param
+
+# This file tests a variety of model,guide pairs with valid and invalid structure.
+# See https://github.com/pyro-ppl/pyro/blob/0.3.1/tests/infer/test_valid_models.py
+
+
+def assert_ok(model, guide, elbo, *args, **kwargs):
+    """
+    Assert that inference works without warnings or errors.
+    """
+    pyro.get_param_store().clear()
+    adam = optim.Adam({"lr": 1e-6})
+    inference = infer.SVI(model, guide, adam, elbo)
+    for i in range(2):
+        inference.step(*args, **kwargs)
+
+
+def assert_error(model, guide, elbo, match=None):
+    """
+    Assert that inference fails with an error.
+    """
+    pyro.get_param_store().clear()
+    adam = optim.Adam({"lr": 1e-6})
+    inference = infer.SVI(model,  guide, adam, elbo)
+    with pytest.raises((NotImplementedError, UserWarning, KeyError, ValueError, RuntimeError),
+                       match=match):
+        inference.step()
+
+
+def assert_warning(model, guide, elbo):
+    """
+    Assert that inference works but with a warning.
+    """
+    pyro.get_param_store().clear()
+    adam = optim.Adam({"lr": 1e-6})
+    inference = infer.SVI(model, guide, adam, elbo)
+    with warnings.catch_warnings(record=True) as w:
+        warnings.simplefilter("always")
+        inference.step()
+        assert len(w), 'No warnings were raised'
+        for warning in w:
+            print(warning)
+
+
+@pytest.mark.parametrize("backend", ["pyro", "minipyro"])
+def test_generate_data(backend):
+
+    def model(data=None):
+        loc = pyro.param("loc", torch.tensor(2.0))
+        scale = pyro.param("scale", torch.tensor(1.0))
+        x = pyro.sample("x", dist.Normal(loc, scale), obs=data)
+        return x
+
+    with pyro_backend(backend):
+        data = model().data
+        assert data.shape == ()
+
+
+@pytest.mark.parametrize("backend", ["pyro", "minipyro"])
+def test_generate_data_plate(backend):
+    num_points = 1000
+
+    def model(data=None):
+        loc = pyro.param("loc", torch.tensor(2.0))
+        scale = pyro.param("scale", torch.tensor(1.0))
+        with pyro.plate("data", 1000, dim=-1):
+            x = pyro.sample("x", dist.Normal(loc, scale), obs=data)
+        return x
+
+    with pyro_backend(backend):
+        data = model().data
+        assert data.shape == (num_points,)
+        mean = data.sum().item() / num_points
+        assert 1.9 <= mean <= 2.1
+
+
+@pytest.mark.parametrize("backend", ["pyro", "minipyro"])
+def test_nonempty_model_empty_guide_ok(backend):
+
+    def model(data):
+        loc = pyro.param("loc", torch.tensor(0.0))
+        pyro.sample("x", dist.Normal(loc, 1.), obs=data)
+
+    def guide(data):
+        pass
+
+    data = torch.tensor(2.)
+    with pyro_backend(backend):
+        elbo = infer.Trace_ELBO()
+        assert_ok(model, guide, elbo, data)
+
+
+@pytest.mark.parametrize("backend", ["pyro", "minipyro"])
+def test_plate_ok(backend):
+    data = torch.randn(10)
+
+    def model():
+        locs = pyro.param("locs", torch.tensor([0.2, 0.3, 0.5]))
+        p = torch.tensor([0.2, 0.3, 0.5])
+        with pyro.plate("plate", len(data), dim=-1):
+            x = pyro.sample("x", dist.Categorical(p))
+            pyro.sample("obs", dist.Normal(locs[x], 1.), obs=data)
+
+    def guide():
+        p = pyro.param("p", torch.tensor([0.5, 0.3, 0.2]))
+        with pyro.plate("plate", len(data), dim=-1):
+            pyro.sample("x", dist.Categorical(p))
+
+    with pyro_backend(backend):
+        elbo = infer.Trace_ELBO()
+        assert_ok(model, guide, elbo)
+
+
+@pytest.mark.parametrize("backend", ["pyro", "minipyro"])
+def test_nested_plate_plate_ok(backend):
+    data = torch.randn(2, 3)
+
+    def model():
+        loc = torch.tensor(3.0)
+        with pyro.plate("plate_outer", data.size(-1), dim=-1):
+            x = pyro.sample("x", dist.Normal(loc, 1.))
+            with pyro.plate("plate_inner", data.size(-2), dim=-2):
+                pyro.sample("y", dist.Normal(x, 1.), obs=data)
+
+    def guide():
+        loc = pyro.param("loc", torch.tensor(0.))
+        scale = pyro.param("scale", torch.tensor(1.))
+        with pyro.plate("plate_outer", data.size(-1), dim=-1):
+            pyro.sample("x", dist.Normal(loc, scale))
+
+    with pyro_backend(backend):
+        elbo = infer.Trace_ELBO()
+        assert_ok(model, guide, elbo)
+
+
+@pytest.mark.parametrize("backend", [
+    "pyro",
+    xfail_param("minipyro", reason="not implemented"),
+])
+def test_local_param_ok(backend):
+    data = torch.randn(10)
+
+    def model():
+        locs = pyro.param("locs", torch.tensor([-1., 0., 1.]))
+        with pyro.plate("plate", len(data), dim=-1):
+            x = pyro.sample("x", dist.Categorical(torch.ones(3) / 3))
+            pyro.sample("obs", dist.Normal(locs[x], 1.), obs=data)
+
+    def guide():
+        with pyro.plate("plate", len(data), dim=-1):
+            p = pyro.param("p", torch.ones(len(data), 3) / 3, event_dim=1)
+            pyro.sample("x", dist.Categorical(p))
+        return p
+
+    with pyro_backend(backend):
+        elbo = infer.Trace_ELBO()
+        assert_ok(model, guide, elbo)
+
+        # Check that pyro.param() can be called without init_value.
+        expected = guide()
+        actual = pyro.param("p")
+        assert_close(actual, expected)
+
+
+@pytest.mark.parametrize("backend", ["pyro", "minipyro"])
+def test_constraints(backend):
+    data = torch.tensor(0.5)
+
+    def model():
+        locs = pyro.param("locs", torch.randn(3), constraint=constraints.real)
+        scales = pyro.param("scales", torch.randn(3).exp(), constraint=constraints.positive)
+        p = torch.tensor([0.5, 0.3, 0.2])
+        x = pyro.sample("x", dist.Categorical(p))
+        pyro.sample("obs", dist.Normal(locs[x], scales[x]), obs=data)
+
+    def guide():
+        q = pyro.param("q", torch.randn(3).exp(), constraint=constraints.simplex)
+        pyro.sample("x", dist.Categorical(q))
+
+    with pyro_backend(backend):
+        elbo = infer.Trace_ELBO()
+        assert_ok(model, guide, elbo)

pip install -e .[dev]
parse_log_pytest
pytest
pytest pytest-cov pytest-xdist
3.6
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
alabaster==0.7.13
anyio==3.6.2
argon2-cffi==21.3.0
argon2-cffi-bindings==21.2.0
async-generator==1.10
attrs @ file:///opt/conda/conda-bld/attrs_1642510447205/work
Babel==2.11.0
backcall==0.2.0
bleach==4.1.0
certifi==2021.5.30
cffi==1.15.1
charset-normalizer==2.0.12
comm==0.1.4
contextlib2==21.6.0
contextvars==2.4
coverage==6.2
cycler==0.11.0
dataclasses==0.8
decorator==4.4.2
defusedxml==0.7.1
docutils==0.18.1
entrypoints==0.4
execnet==1.9.0
flake8==3.9.2
graphviz==0.19.1
idna==3.10
imagesize==1.4.1
immutables==0.19
importlib-metadata @ file:///tmp/build/80754af9/importlib-metadata_1631916693255/work
importlib-resources==5.4.0
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
ipykernel==5.5.6
ipython==7.16.3
ipython-genutils==0.2.0
ipywidgets==7.8.5
isort==5.10.1
jedi==0.17.2
Jinja2==3.0.3
json5==0.9.16
jsonpatch==1.32
jsonpointer==2.3
jsonschema==3.2.0
jupyter==1.1.1
jupyter-client==7.1.2
jupyter-console==6.4.3
jupyter-core==4.9.2
jupyter-server==1.13.1
jupyterlab==3.2.9
jupyterlab-pygments==0.1.2
jupyterlab-server==2.10.3
jupyterlab_widgets==1.1.11
kiwisolver==1.3.1
MarkupSafe==2.0.1
matplotlib==3.3.4
mccabe==0.6.1
mistune==0.8.4
more-itertools @ file:///tmp/build/80754af9/more-itertools_1637733554872/work
nbclassic==0.3.5
nbclient==0.5.9
nbconvert==6.0.7
nbformat==5.1.3
nbsphinx==0.8.8
nbstripout==0.6.2
nbval==0.10.0
nest-asyncio==1.6.0
networkx==2.5.1
notebook==6.4.10
numpy==1.19.5
observations==0.1.4
opt-einsum==3.3.0
packaging @ file:///tmp/build/80754af9/packaging_1637314298585/work
pandas==1.1.5
pandocfilters==1.5.1
parso==0.7.1
pexpect==4.9.0
pickleshare==0.7.5
Pillow==8.4.0
pluggy @ file:///tmp/build/80754af9/pluggy_1615976315926/work
prometheus-client==0.17.1
prompt-toolkit==3.0.36
ptyprocess==0.7.0
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pycodestyle==2.7.0
pycparser==2.21
pyflakes==2.3.1
Pygments==2.14.0
pypandoc==1.14
pyparsing @ file:///tmp/build/80754af9/pyparsing_1635766073266/work
-e git+https://github.com/pyro-ppl/pyro.git@75b0fc1c78be439c1a96afdde68d79e8455b0314#egg=pyro_ppl
pyrsistent==0.18.0
pytest==6.2.4
pytest-cov==4.0.0
pytest-xdist==3.0.2
python-dateutil==2.9.0.post0
pytz==2025.2
pyzmq==25.1.2
requests==2.27.1
scipy==1.5.4
seaborn==0.11.2
Send2Trash==1.8.3
six==1.17.0
sniffio==1.2.0
snowballstemmer==2.2.0
Sphinx==5.3.0
sphinx-rtd-theme==2.0.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jquery==4.1
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
terminado==0.12.1
testpath==0.6.0
toml @ file:///tmp/build/80754af9/toml_1616166611790/work
tomli==1.2.3
torch==1.10.2
torchvision==0.2.1
tornado==6.1
tqdm==4.64.1
traitlets==4.3.3
typing_extensions @ file:///opt/conda/conda-bld/typing_extensions_1647553014482/work
urllib3==1.26.20
visdom==0.2.4
wcwidth==0.2.13
webencodings==0.5.1
websocket-client==1.3.1
wget==3.2
widgetsnbextension==3.6.10
yapf==0.32.0
zipp @ file:///tmp/build/80754af9/zipp_1633618647012/work

name: pyro
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - attrs=21.4.0=pyhd3eb1b0_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2021.5.30=py36h06a4308_0
  - importlib-metadata=4.8.1=py36h06a4308_0
  - importlib_metadata=4.8.1=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.3=he6710b0_2
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - more-itertools=8.12.0=pyhd3eb1b0_0
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=21.3=pyhd3eb1b0_0
  - pip=21.2.2=py36h06a4308_0
  - pluggy=0.13.1=py36h06a4308_0
  - py=1.11.0=pyhd3eb1b0_0
  - pyparsing=3.0.4=pyhd3eb1b0_0
  - pytest=6.2.4=py36h06a4308_2
  - python=3.6.13=h12debd9_1
  - readline=8.2=h5eee18b_0
  - setuptools=58.0.4=py36h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - toml=0.10.2=pyhd3eb1b0_0
  - typing_extensions=4.1.1=pyh06a4308_0
  - wheel=0.37.1=pyhd3eb1b0_0
  - xz=5.6.4=h5eee18b_1
  - zipp=3.6.0=pyhd3eb1b0_0
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - alabaster==0.7.13
      - anyio==3.6.2
      - argon2-cffi==21.3.0
      - argon2-cffi-bindings==21.2.0
      - async-generator==1.10
      - babel==2.11.0
      - backcall==0.2.0
      - bleach==4.1.0
      - cffi==1.15.1
      - charset-normalizer==2.0.12
      - comm==0.1.4
      - contextlib2==21.6.0
      - contextvars==2.4
      - coverage==6.2
      - cycler==0.11.0
      - dataclasses==0.8
      - decorator==4.4.2
      - defusedxml==0.7.1
      - docutils==0.18.1
      - entrypoints==0.4
      - execnet==1.9.0
      - flake8==3.9.2
      - graphviz==0.19.1
      - idna==3.10
      - imagesize==1.4.1
      - immutables==0.19
      - importlib-resources==5.4.0
      - ipykernel==5.5.6
      - ipython==7.16.3
      - ipython-genutils==0.2.0
      - ipywidgets==7.8.5
      - isort==5.10.1
      - jedi==0.17.2
      - jinja2==3.0.3
      - json5==0.9.16
      - jsonpatch==1.32
      - jsonpointer==2.3
      - jsonschema==3.2.0
      - jupyter==1.1.1
      - jupyter-client==7.1.2
      - jupyter-console==6.4.3
      - jupyter-core==4.9.2
      - jupyter-server==1.13.1
      - jupyterlab==3.2.9
      - jupyterlab-pygments==0.1.2
      - jupyterlab-server==2.10.3
      - jupyterlab-widgets==1.1.11
      - kiwisolver==1.3.1
      - markupsafe==2.0.1
      - matplotlib==3.3.4
      - mccabe==0.6.1
      - mistune==0.8.4
      - nbclassic==0.3.5
      - nbclient==0.5.9
      - nbconvert==6.0.7
      - nbformat==5.1.3
      - nbsphinx==0.8.8
      - nbstripout==0.6.2
      - nbval==0.10.0
      - nest-asyncio==1.6.0
      - networkx==2.5.1
      - notebook==6.4.10
      - numpy==1.19.5
      - observations==0.1.4
      - opt-einsum==3.3.0
      - pandas==1.1.5
      - pandocfilters==1.5.1
      - parso==0.7.1
      - pexpect==4.9.0
      - pickleshare==0.7.5
      - pillow==8.4.0
      - prometheus-client==0.17.1
      - prompt-toolkit==3.0.36
      - ptyprocess==0.7.0
      - pycodestyle==2.7.0
      - pycparser==2.21
      - pyflakes==2.3.1
      - pygments==2.14.0
      - pypandoc==1.14
      - pyrsistent==0.18.0
      - pytest-cov==4.0.0
      - pytest-xdist==3.0.2
      - python-dateutil==2.9.0.post0
      - pytz==2025.2
      - pyzmq==25.1.2
      - requests==2.27.1
      - scipy==1.5.4
      - seaborn==0.11.2
      - send2trash==1.8.3
      - six==1.17.0
      - sniffio==1.2.0
      - snowballstemmer==2.2.0
      - sphinx==5.3.0
      - sphinx-rtd-theme==2.0.0
      - sphinxcontrib-applehelp==1.0.2
      - sphinxcontrib-devhelp==1.0.2
      - sphinxcontrib-htmlhelp==2.0.0
      - sphinxcontrib-jquery==4.1
      - sphinxcontrib-jsmath==1.0.1
      - sphinxcontrib-qthelp==1.0.3
      - sphinxcontrib-serializinghtml==1.1.5
      - terminado==0.12.1
      - testpath==0.6.0
      - tomli==1.2.3
      - torch==1.10.2
      - torchvision==0.2.1
      - tornado==6.1
      - tqdm==4.64.1
      - traitlets==4.3.3
      - urllib3==1.26.20
      - visdom==0.2.4
      - wcwidth==0.2.13
      - webencodings==0.5.1
      - websocket-client==1.3.1
      - wget==3.2
      - widgetsnbextension==3.6.10
      - yapf==0.32.0
prefix: /opt/conda/envs/pyro

tests/contrib/test_minipyro.py::test_constraints[minipyro]
tests/contrib/test_minipyro.py::test_generate_data[pyro] tests/contrib/test_minipyro.py::test_generate_data[minipyro] tests/contrib/test_minipyro.py::test_generate_data_plate[pyro] tests/contrib/test_minipyro.py::test_generate_data_plate[minipyro] tests/contrib/test_minipyro.py::test_nonempty_model_empty_guide_ok[pyro] tests/contrib/test_minipyro.py::test_nonempty_model_empty_guide_ok[minipyro] tests/contrib/test_minipyro.py::test_plate_ok[pyro] tests/contrib/test_minipyro.py::test_plate_ok[minipyro] tests/contrib/test_minipyro.py::test_nested_plate_plate_ok[pyro] tests/contrib/test_minipyro.py::test_nested_plate_plate_ok[minipyro] tests/contrib/test_minipyro.py::test_local_param_ok[pyro] tests/contrib/test_minipyro.py::test_constraints[pyro]
examples/minipyro.py pyro/contrib/minipyro.py
examples/minipyro.py pyro/contrib/minipyro.py