prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  SNLE + multiple independent prior + MCMC with num_workers > 1 throws error
  SNLE:
  - multiple independent prior + num_workers=2 leads to an error (ValueError: Expected value argument to be within the support of the distribution Uniform)
  - no error if either num_workers=1 or using a BoxUniform prior
  
  SNPE:
  - seems to work
  
  ```
  from sbi.inference.snpe import SNPE_A
  from sbi.inference.snle import SNLE_A
  from sbi.utils import BoxUniform
  from sbi.inference.posteriors import MCMCPosterior
  from sbi.inference.potentials import posterior_estimator_based_potential, likelihood_estimator_based_potential
  from sbi.utils.user_input_checks import process_prior
  from sbi.analysis.sbc import run_sbc
  import torch
  
  default_params = torch.rand(size=(4, 3),dtype=torch.float32)
  default_obs = torch.rand(size=(4, 1), dtype=torch.float32)
  
  # multiple independent prior
  prior = [torch.distributions.Uniform(torch.FloatTensor([0]), torch.FloatTensor([20])),
          torch.distributions.Uniform(torch.FloatTensor([-10]), torch.FloatTensor([10])),
          torch.distributions.Uniform(torch.FloatTensor([0.5]), torch.FloatTensor([3]))]
  # box uniform prior
  # prior = BoxUniform(torch.Tensor([0, -10, 0.5]), torch.Tensor([20, 10, 3]))
  prior, _, _ = process_prior(prior)
  
  # inference = SNPE_A()
  # density_estimator = inference.append_simulations(default_params, default_obs).train()
  # potential_fn, theta_transform = posterior_estimator_based_potential(density_estimator, prior, default_obs[0])
  
  inference = SNLE_A()
  density_estimator = inference.append_simulations(default_params, default_obs).train()
  potential_fn, theta_transform = likelihood_estimator_based_potential(density_estimator, prior, default_obs[0])
  
  posterior = MCMCPosterior(potential_fn, proposal=prior, theta_transform=theta_transform)
  
  # this line throws an error
  ranks, dap_samples = run_sbc(default_params, default_obs, posterior, num_posterior_samples=10, num_workers=2, sbc_batch_size=2)
  ```
  
  
  </issue>
  <code>
  [start of sbi/samplers/mcmc/init_strategy.py]
  1 # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
  2 # under the Affero General Public License v3, see <https://www.gnu.org/licenses/>.
  3 
  4 from typing import Any, Callable
  5 
  6 import torch
  7 import torch.distributions.transforms as torch_tf
  8 from torch import Tensor
  9 
  10 
  11 class IterateParameters:
  12     """Iterates through parameters by rows"""
  13 
  14     def __init__(self, parameters: torch.Tensor, **kwargs):
  15         self.iter = self._make_iterator(parameters)
  16 
  17     @staticmethod
  18     def _make_iterator(t):
  19         for i in range(t.shape[0]):
  20             yield t[i, :].reshape(1, -1)
  21 
  22     def __call__(self):
  23         return next(self.iter)
  24 
  25 
  26 def proposal_init(
  27     proposal: Any, transform: torch_tf.Transform, **kwargs: Any
  28 ) -> Tensor:
  29     """Return a sample from the proposal."""
  30     prior_samples = proposal.sample((1,)).detach()
  31     transformed_prior_samples = transform(prior_samples)
  32     return transformed_prior_samples
  33 
  34 
  35 def sir(
  36     proposal: Any,
  37     potential_fn: Callable,
  38     transform: torch_tf.Transform,
  39     sir_num_batches: int = 10,
  40     sir_batch_size: int = 1000,
  41     **kwargs: Any,
  42 ) -> Tensor:
  43     r"""Return a sample obtained by sequential importance reweighting.
  44 
  45     See Rubin 1988, "Using the sir algorithm to simulate posterior distributions."
  46 
  47     This function can also do `SIR` on the conditional posterior
  48     $p(\theta_i|\theta_j, x)$ when a `condition` and `dims_to_sample` are passed.
  49 
  50     Args:
  51         proposal: Proposal distribution, candidate samples are drawn from it.
  52         potential_fn: Potential function that the candidate samples are weighted with.
  53             Note that the function needs to return log probabilities.
  54         sir_num_batches: Number of candidate batches drawn.
  55         sir_batch_size: Batch size used for evaluating candidates.
  56 
  57     Returns:
  58         A single sample.
  59     """
  60 
  61     with torch.set_grad_enabled(False):
  62         log_weights = []
  63         init_param_candidates = []
  64         for i in range(sir_num_batches):
  65             batch_draws = proposal.sample((sir_batch_size,)).detach()
  66             transformed_batch_draws = transform(batch_draws)
  67             init_param_candidates.append(transformed_batch_draws)
  68             log_weights.append(potential_fn(transformed_batch_draws).detach())
  69         log_weights = torch.cat(log_weights)
  70         init_param_candidates = torch.cat(init_param_candidates)
  71 
  72         # Norm weights in log space
  73         log_weights -= torch.logsumexp(log_weights, dim=0)
  74         probs = torch.exp(log_weights.view(-1))
  75         probs[torch.isnan(probs)] = 0.0
  76         probs[torch.isinf(probs)] = 0.0
  77         probs /= probs.sum()
  78 
  79         idxs = torch.multinomial(probs, 1, replacement=False)
  80         return init_param_candidates[idxs, :]
  81
  [end of sbi/samplers/mcmc/init_strategy.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/sbi/samplers/mcmc/init_strategy.py b/sbi/samplers/mcmc/init_strategy.py
  --- a/sbi/samplers/mcmc/init_strategy.py
  +++ b/sbi/samplers/mcmc/init_strategy.py
  @@ -63,9 +63,8 @@
           init_param_candidates = []
           for i in range(sir_num_batches):
               batch_draws = proposal.sample((sir_batch_size,)).detach()
  -            transformed_batch_draws = transform(batch_draws)
  -            init_param_candidates.append(transformed_batch_draws)
  -            log_weights.append(potential_fn(transformed_batch_draws).detach())
  +            init_param_candidates.append(batch_draws)
  +            log_weights.append(potential_fn(batch_draws).detach())
           log_weights = torch.cat(log_weights)
           init_param_candidates = torch.cat(init_param_candidates)
   
  @@ -77,4 +76,5 @@
           probs /= probs.sum()
   
           idxs = torch.multinomial(probs, 1, replacement=False)
  -        return init_param_candidates[idxs, :]
  +        # Return transformed sample.
  +        return transform(init_param_candidates[idxs, :])
  
verification_info: {"golden_diff": "diff --git a/sbi/samplers/mcmc/init_strategy.py b/sbi/samplers/mcmc/init_strategy.py\n--- a/sbi/samplers/mcmc/init_strategy.py\n+++ b/sbi/samplers/mcmc/init_strategy.py\n@@ -63,9 +63,8 @@\n         init_param_candidates = []\n         for i in range(sir_num_batches):\n             batch_draws = proposal.sample((sir_batch_size,)).detach()\n-            transformed_batch_draws = transform(batch_draws)\n-            init_param_candidates.append(transformed_batch_draws)\n-            log_weights.append(potential_fn(transformed_batch_draws).detach())\n+            init_param_candidates.append(batch_draws)\n+            log_weights.append(potential_fn(batch_draws).detach())\n         log_weights = torch.cat(log_weights)\n         init_param_candidates = torch.cat(init_param_candidates)\n \n@@ -77,4 +76,5 @@\n         probs /= probs.sum()\n \n         idxs = torch.multinomial(probs, 1, replacement=False)\n-        return init_param_candidates[idxs, :]\n+        # Return transformed sample.\n+        return transform(init_param_candidates[idxs, :])\n", "issue": "SNLE + multiple independent prior + MCMC with num_workers > 1 throws error\nSNLE:\r\n- multiple independent prior + num_workers=2 leads to an error (ValueError: Expected value argument to be within the support of the distribution Uniform)\r\n- no error if either num_workers=1 or using a BoxUniform prior\r\n\r\nSNPE:\r\n- seems to work\r\n\r\n```\r\nfrom sbi.inference.snpe import SNPE_A\r\nfrom sbi.inference.snle import SNLE_A\r\nfrom sbi.utils import BoxUniform\r\nfrom sbi.inference.posteriors import MCMCPosterior\r\nfrom sbi.inference.potentials import posterior_estimator_based_potential, likelihood_estimator_based_potential\r\nfrom sbi.utils.user_input_checks import process_prior\r\nfrom sbi.analysis.sbc import run_sbc\r\nimport torch\r\n\r\ndefault_params = torch.rand(size=(4, 3),dtype=torch.float32)\r\ndefault_obs = torch.rand(size=(4, 1), dtype=torch.float32)\r\n\r\n# multiple independent prior\r\nprior = [torch.distributions.Uniform(torch.FloatTensor([0]), torch.FloatTensor([20])),\r\n        torch.distributions.Uniform(torch.FloatTensor([-10]), torch.FloatTensor([10])),\r\n        torch.distributions.Uniform(torch.FloatTensor([0.5]), torch.FloatTensor([3]))]\r\n# box uniform prior\r\n# prior = BoxUniform(torch.Tensor([0, -10, 0.5]), torch.Tensor([20, 10, 3]))\r\nprior, _, _ = process_prior(prior)\r\n\r\n# inference = SNPE_A()\r\n# density_estimator = inference.append_simulations(default_params, default_obs).train()\r\n# potential_fn, theta_transform = posterior_estimator_based_potential(density_estimator, prior, default_obs[0])\r\n\r\ninference = SNLE_A()\r\ndensity_estimator = inference.append_simulations(default_params, default_obs).train()\r\npotential_fn, theta_transform = likelihood_estimator_based_potential(density_estimator, prior, default_obs[0])\r\n\r\nposterior = MCMCPosterior(potential_fn, proposal=prior, theta_transform=theta_transform)\r\n\r\n# this line throws an error\r\nranks, dap_samples = run_sbc(default_params, default_obs, posterior, num_posterior_samples=10, num_workers=2, sbc_batch_size=2)\r\n```\r\n\n", "before_files": [{"content": "# This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed\n# under the Affero General Public License v3, see <https://www.gnu.org/licenses/>.\n\nfrom typing import Any, Callable\n\nimport torch\nimport torch.distributions.transforms as torch_tf\nfrom torch import Tensor\n\n\nclass IterateParameters:\n    \"\"\"Iterates through parameters by rows\"\"\"\n\n    def __init__(self, parameters: torch.Tensor, **kwargs):\n        self.iter = self._make_iterator(parameters)\n\n    @staticmethod\n    def _make_iterator(t):\n        for i in range(t.shape[0]):\n            yield t[i, :].reshape(1, -1)\n\n    def __call__(self):\n        return next(self.iter)\n\n\ndef proposal_init(\n    proposal: Any, transform: torch_tf.Transform, **kwargs: Any\n) -> Tensor:\n    \"\"\"Return a sample from the proposal.\"\"\"\n    prior_samples = proposal.sample((1,)).detach()\n    transformed_prior_samples = transform(prior_samples)\n    return transformed_prior_samples\n\n\ndef sir(\n    proposal: Any,\n    potential_fn: Callable,\n    transform: torch_tf.Transform,\n    sir_num_batches: int = 10,\n    sir_batch_size: int = 1000,\n    **kwargs: Any,\n) -> Tensor:\n    r\"\"\"Return a sample obtained by sequential importance reweighting.\n\n    See Rubin 1988, \"Using the sir algorithm to simulate posterior distributions.\"\n\n    This function can also do `SIR` on the conditional posterior\n    $p(\\theta_i|\\theta_j, x)$ when a `condition` and `dims_to_sample` are passed.\n\n    Args:\n        proposal: Proposal distribution, candidate samples are drawn from it.\n        potential_fn: Potential function that the candidate samples are weighted with.\n            Note that the function needs to return log probabilities.\n        sir_num_batches: Number of candidate batches drawn.\n        sir_batch_size: Batch size used for evaluating candidates.\n\n    Returns:\n        A single sample.\n    \"\"\"\n\n    with torch.set_grad_enabled(False):\n        log_weights = []\n        init_param_candidates = []\n        for i in range(sir_num_batches):\n            batch_draws = proposal.sample((sir_batch_size,)).detach()\n            transformed_batch_draws = transform(batch_draws)\n            init_param_candidates.append(transformed_batch_draws)\n            log_weights.append(potential_fn(transformed_batch_draws).detach())\n        log_weights = torch.cat(log_weights)\n        init_param_candidates = torch.cat(init_param_candidates)\n\n        # Norm weights in log space\n        log_weights -= torch.logsumexp(log_weights, dim=0)\n        probs = torch.exp(log_weights.view(-1))\n        probs[torch.isnan(probs)] = 0.0\n        probs[torch.isinf(probs)] = 0.0\n        probs /= probs.sum()\n\n        idxs = torch.multinomial(probs, 1, replacement=False)\n        return init_param_candidates[idxs, :]\n", "path": "sbi/samplers/mcmc/init_strategy.py"}]}