Skip to content

Add check for variables in step samplers #6524

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

Merged
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions pymc/sampling/mcmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,11 @@ def assign_step_methods(model, step=None, methods=None, step_kwargs=None):
except TypeError:
steps.append(step)
for step in steps:
for var in step.vars:
if var not in model.value_vars:
raise ValueError(
f"{var} assigned to {step} sampler is not a value variable in the model. You can use `util.get_value_vars_from_user_vars` to parse user provided variables."
)
assigned_vars = assigned_vars.union(set(step.vars))

# Use competence classmethods to select step methods for remaining
Expand Down
18 changes: 18 additions & 0 deletions tests/sampling/test_mcmc.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
NUTS,
BinaryGibbsMetropolis,
CategoricalGibbsMetropolis,
CompoundStep,
HamiltonianMC,
Metropolis,
Slice,
Expand Down Expand Up @@ -817,6 +818,23 @@ def test_modify_step_methods(self):
steps = assign_step_methods(model, [])
assert isinstance(steps, NUTS)

def test_step_vars_in_model(self):
"""Test if error is raised if step variable is not found in model.value_vars"""
with pm.Model() as model:
c1 = pm.HalfNormal("c1")
c2 = pm.HalfNormal("c2")

with pytensor.config.change_flags(mode=fast_unstable_sampling_mode):
step1 = NUTS([c1])
step2 = NUTS([c2])
step2.vars = [c2]
step = CompoundStep([step1, step2])
with pytest.raises(
ValueError,
match=r".* assigned to .* sampler is not a value variable in the model. You can use `util.get_value_vars_from_user_vars` to parse user provided variables.",
):
assign_step_methods(model, step)


class TestType:
samplers = (Metropolis, Slice, HamiltonianMC, NUTS)
Expand Down