-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Refactor of Sequential Monte Carlo internals #5274
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
Closed
ciguaran
wants to merge
10
commits into
pymc-devs:main
from
ciguaran:ciguaran_exploratory_refactor_smc
Closed
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
095efad
more
ciguaran dd7ebcc
Refactor chain sampling methods
ciguaran 61bb6d8
Create utils.py
ciguaran 5848044
runners file
ciguaran 6c134be
Update sample_smc.py
ciguaran 7b771a0
a
ciguaran 8bc0fa1
f
ciguaran cc59278
Update test_smc.py
ciguaran 19b4495
pre commit running
ciguaran e822eea
reorder
ciguaran File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,51 @@ | ||
import multiprocessing as mp | ||
|
||
from itertools import repeat | ||
|
||
import cloudpickle | ||
|
||
from fastprogress.fastprogress import progress_bar | ||
|
||
|
||
def run_chains_parallel(chains, progressbar, to_run, params, random_seed, kernel_kwargs, cores): | ||
pbar = progress_bar((), total=100, display=progressbar) | ||
pbar.update(0) | ||
pbars = [pbar] + [None] * (chains - 1) | ||
|
||
pool = mp.Pool(cores) | ||
|
||
# "manually" (de)serialize params before/after multiprocessing | ||
params = tuple(cloudpickle.dumps(p) for p in params) | ||
kernel_kwargs = {key: cloudpickle.dumps(value) for key, value in kernel_kwargs.items()} | ||
results = _starmap_with_kwargs( | ||
pool, | ||
to_run, | ||
[(*params, random_seed[chain], chain, pbars[chain]) for chain in range(chains)], | ||
repeat(kernel_kwargs), | ||
) | ||
results = tuple(cloudpickle.loads(r) for r in results) | ||
pool.close() | ||
pool.join() | ||
return results | ||
|
||
|
||
def run_chains_sequential(chains, progressbar, to_run, params, random_seed, kernel_kwargs): | ||
results = [] | ||
pbar = progress_bar((), total=100 * chains, display=progressbar) | ||
pbar.update(0) | ||
for chain in range(chains): | ||
pbar.offset = 100 * chain | ||
pbar.base_comment = f"Chain: {chain + 1}/{chains}" | ||
results.append(to_run(*params, random_seed[chain], chain, pbar, **kernel_kwargs)) | ||
return results | ||
|
||
|
||
def _starmap_with_kwargs(pool, fn, args_iter, kwargs_iter): | ||
# Helper function to allow kwargs with Pool.starmap | ||
# Copied from https://stackoverflow.com/a/53173433/13311693 | ||
args_for_starmap = zip(repeat(fn), args_iter, kwargs_iter) | ||
return pool.starmap(_apply_args_and_kwargs, args_for_starmap) | ||
|
||
|
||
def _apply_args_and_kwargs(fn, args, kwargs): | ||
return fn(*args, **kwargs) |
This file contains hidden or 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 hidden or 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 hidden or 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 |
---|---|---|
|
@@ -42,7 +42,7 @@ def setup_class(self): | |
super().setup_class() | ||
self.samples = 1000 | ||
n = 4 | ||
mu1 = np.ones(n) * (1.0 / 2) | ||
mu1 = np.ones(n) * 0.5 | ||
mu2 = -mu1 | ||
|
||
stdev = 0.1 | ||
|
@@ -54,6 +54,9 @@ def setup_class(self): | |
w2 = 1 - stdev | ||
|
||
def two_gaussians(x): | ||
""" | ||
Mixture of gaussians likelihood | ||
""" | ||
log_like1 = ( | ||
-0.5 * n * at.log(2 * np.pi) | ||
- 0.5 * at.log(dsigma) | ||
|
@@ -80,8 +83,9 @@ def test_sample(self): | |
initial_rng_state = np.random.get_state() | ||
with self.SMC_test: | ||
mtrace = pm.sample_smc(draws=self.samples, return_inferencedata=False) | ||
assert_random_state_equal(initial_rng_state, np.random.get_state()) | ||
|
||
assert_random_state_equal( | ||
initial_rng_state, np.random.get_state() | ||
) # TODO: why this? maybe to verify that nothing was sampled? | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The PR where this test was added provides some context: #5131 Since it was not obvious why it was there, a comment before the assert explaining the purpose of the check could be helpful. |
||
x = mtrace["X"] | ||
mu1d = np.abs(x).mean(axis=0) | ||
np.testing.assert_allclose(self.muref, mu1d, rtol=0.0, atol=0.03) | ||
|
@@ -109,7 +113,6 @@ def test_discrete_rounding_proposal(self): | |
def test_unobserved_discrete(self): | ||
n = 10 | ||
rng = self.get_random_state() | ||
|
||
z_true = np.zeros(n, dtype=int) | ||
z_true[int(n / 2) :] = 1 | ||
y = st.norm(np.array([-1, 1])[z_true], 0.25).rvs(random_state=rng) | ||
|
@@ -124,6 +127,10 @@ def test_unobserved_discrete(self): | |
assert np.all(np.median(trace["z"], axis=0) == z_true) | ||
|
||
def test_marginal_likelihood(self): | ||
""" | ||
Verifies that the log marginal likelihood function | ||
can be correctly computed for a Beta-Bernoulli model. | ||
""" | ||
data = np.repeat([1, 0], [50, 50]) | ||
marginals = [] | ||
a_prior_0, b_prior_0 = 1.0, 1.0 | ||
|
@@ -135,6 +142,7 @@ def test_marginal_likelihood(self): | |
y = pm.Bernoulli("y", a, observed=data) | ||
trace = pm.sample_smc(2000, return_inferencedata=False) | ||
marginals.append(trace.report.log_marginal_likelihood) | ||
|
||
# compare to the analytical result | ||
assert abs(np.exp(np.nanmean(marginals[1]) - np.nanmean(marginals[0])) - 4.0) <= 1 | ||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am not sure this needs to be in its own separate file. The original file is pretty concise
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right I didn't extracted due to size, but because it feels that running parallel vs sequential is kind of independent of SMC, and that it could be reused somewhere else. LMK if its enough reason to be outside or I move it again in.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If a similar need emerges on another sampler we can refactor it then. Doing it now seems like some premature refactoring.
Also it wouldn't make sense to host it inside the SMC module