Skip to content

Commit

Permalink
Add inits and explicit gradient test.
Browse files Browse the repository at this point in the history
  • Loading branch information
tillahoffmann committed Jan 23, 2025
1 parent 48b5a7e commit f059ceb
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
4 changes: 3 additions & 1 deletion cmdstanpy/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2221,6 +2221,8 @@ def diagnose(
* "model": Gradients evaluated using autodiff.
* "finite_diff": Gradients evaluated using finite differences.
* "error": Delta between autodiff and finite difference gradients.
Gradients are evaluated in the unconstrained space.
"""

with temp_single_json(data) as _data, \
Expand All @@ -2237,7 +2239,7 @@ def diagnose(
if _data is not None:
cmd += ["data", f"file={_data}"]
if _inits is not None:
cmd.append(f"inits={_inits}")
cmd.append(f"init={_inits}")

output_dir = tempfile.mkdtemp(prefix=self.name, dir=_TMPDIR)

Expand Down
5 changes: 5 additions & 0 deletions test/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,11 @@ def test_diagnose():
"error",
}

# Check gradients against the same value as in `log_prob`.
inits = {"theta": 0.34903938392023830482}
gradients = model.diagnose(data=BERN_DATA, inits=inits)
np.testing.assert_allclose(gradients.model.iloc[0], -1.18847)

# Simulate bad gradients by using large finite difference.
with pytest.raises(RuntimeError, match="may exceed the error threshold"):
model.diagnose(data=BERN_DATA, epsilon=3)
Expand Down

0 comments on commit f059ceb

Please sign in to comment.