RenyiDivergenceOptimizer (vi_method='alpha') with dreg=True scales gradients by n_particles and uses biased weights for alpha != 0

Open
#2,272 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 6 days

@Rohan-Dedhia is already working on this.

Since Dec 1, 2026.

  • #2273 by @Rohan-Dedhia — open

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
python, pytorch

Research direction

Start with sbi/samplers/vi/vi_divergence_optimizers.py, focusing on get_importance_weight, loss_alpha, and loss_alpha_unbiased, and run the reported minimal example to reproduce the scaling and bias. Add or update coverage in tests/vi_test.py for alpha-zero equivalence, DReG weights across alpha values, Monte Carlo gradient expectations, and the unbiased=True, dreg=True case. The work is done when normalized weights and the general DReG surrogate are used and all relevant tests pass.

Written by the indexing model from the issue text.

Description

Bug description

RenyiDivergenceOptimizer(..., dreg=True) (vi_method="alpha", in sbi/samplers/vi/vi_divergence_optimizers.py) produces mis-scaled and biased gradients:

  1. weights in get_importance_weight are scaled by n_particles before squaring:
    get_importance_weight computes mean_log_weights = torch.logsumexp(logweights, 0) - np.log(self.n_particles), so weights = (logweights - mean_log_weights).exp() sums to n_particles instead of 1. When dreg=False, taking torch.mean(weights * elbo_particles_masked) in loss_alpha cancels this factor. When dreg=True, weights = weights**2 leaves an extra factor of n_particles (256x at the default n_particles=256). At alpha=0, RenyiDivergenceOptimizer(..., dreg=True) gives gradients n_particles times larger than the documented-equivalent IWElboOptimizer(n_particles=1, K=n_particles, dreg=True).

  2. weights**2 only applies to alpha = 0 (IWAE), not general Rényi VR-alpha:
    For w_k = softmax((1 - alpha) * elbo_k), differentiating w_k with respect to theta_k gives (1 - alpha) * w_k * (1 - w_k) * d_elbo_k / d_theta_k. Integrating the score-function term by parts and adding the pathwise term gives DReG weights alpha * w_k + (1 - alpha) * w_k**2 (reduces to w_k**2 at alpha = 0 and 1 / n_particles at alpha = 1). Using weights**2 for alpha != 0 gives biased gradients.

  3. dreg=True with unbiased=True ignores dreg:
    _detach_log_q() detaches log_q whenever dreg=True, but loss_alpha_unbiased discards the weights returned by get_importance_weight (_, mean_log_weights = ...) and differentiates -torch.exp(mean_log_weights) instead of using the DReG surrogate (-alpha * (1 - alpha) * exp((1 - alpha) * elbo)).

Proposed fix and tests
  • Normalize weights in get_importance_weight using sum_log_weights = torch.logsumexp(logweights, 0) (summing to 1, matching IWElboOptimizer) and change loss_alpha from -torch.mean(weights * elbo_particles_masked) to -torch.sum(weights * elbo_particles_masked).
  • When self.dreg is True, use self.alpha * weights + (1 - self.alpha) * weights**2 in get_importance_weight.
  • When self.dreg is True in loss_alpha_unbiased, compute -self.alpha * (1 - self.alpha) * torch.mean(unnorm_weights * (elbo_particles_masked - elbo_particles_masked.detach())).
  • Test in tests/vi_test.py: equivalence with IWElboOptimizer at alpha = 0, exact DReG weights across alpha values, Monte Carlo expectation agreement with pathwise VR-alpha gradients, and unbiased=True, dreg=True.
Minimal code example
import torch
from torch.distributions import MultivariateNormal

from sbi.inference.potentials.base_potential import BasePotential
from sbi.samplers.vi.vi_divergence_optimizers import (
    IWElboOptimizer,
    RenyiDivergenceOptimizer,
)
from sbi.samplers.vi.vi_utils import LearnableGaussian


class GaussianPotential(BasePotential):
    def __call__(self, theta, track_gradients=True):
        return -0.5 * ((theta - 2.0) ** 2).sum(-1)


prior = MultivariateNormal(torch.zeros(1), torch.eye(1))
potential = GaussianPotential(prior)
p = torch.tensor([-2.0, -1.0, 0.0, 0.5, 1.0, 2.0, 2.5, 3.0], requires_grad=True)

# 1. alpha=0.0, dreg=True is n_particles times larger than IWElboOptimizer(n_particles=1, K=n_particles)
iw = IWElboOptimizer(
    potential,
    LearnableGaussian(1, False),
    prior=prior,
    n_particles=1,
    K=8,
    dreg=True,
    lr=1e-3,
    gamma=0.999,
)
ren0 = RenyiDivergenceOptimizer(
    potential,
    LearnableGaussian(1, False),
    prior=prior,
    n_particles=8,
    alpha=0.0,
    dreg=True,
    lr=1e-3,
    gamma=0.999,
)
iw.generate_elbo_particles = lambda x_o, num_samples=None: p
ren0.generate_elbo_particles = lambda x_o, num_samples=None: p
g_iw = torch.autograd.grad(iw.loss(torch.zeros(1))[0], p, retain_graph=True)[0]
g_ren0 = torch.autograd.grad(ren0.loss(torch.zeros(1))[0], p)[0]
print("1) alpha=0 dreg grad ratio (renyi / iw):", (g_ren0 / g_iw).mean().item())

# 2. alpha != 0 uses w**2 instead of alpha * w + (1 - alpha) * w**2
ren_half = RenyiDivergenceOptimizer(
    potential,
    LearnableGaussian(1, False),
    prior=prior,
    n_particles=8,
    alpha=0.5,
    dreg=True,
    lr=1e-3,
    gamma=0.999,
)
ren_half.generate_elbo_particles = lambda x_o, num_samples=None: p
g_half = torch.autograd.grad(ren_half.loss(torch.zeros(1))[0], p)[0]
w = torch.softmax(0.5 * p.detach(), dim=0)
expected_half = -(0.5 * w + 0.5 * w**2)
print(
    "2) alpha=0.5 dreg grad sum:",
    g_half.sum().item(),
    "expected sum:",
    expected_half.sum().item(),
)

# 3. unbiased=True + dreg=True ignores dreg (nonzero gradient at alpha=0)
ren_unb = RenyiDivergenceOptimizer(
    potential,
    LearnableGaussian(1, False),
    prior=prior,
    n_particles=8,
    alpha=0.0,
    unbiased=True,
    dreg=True,
    lr=1e-3,
    gamma=0.999,
)
ren_unb.generate_elbo_particles = lambda x_o, num_samples=None: p
g_unb = torch.autograd.grad(ren_unb.loss(torch.zeros(1))[0], p)[0]
print("3) alpha=0 unbiased+dreg max |grad|:", g_unb.abs().max().item(), "expected: 0.0")
Error message or traceback
1) alpha=0 dreg grad ratio (renyi / iw): 8.0
2) alpha=0.5 dreg grad sum: -1.4971097707748413 expected sum: -0.5935693979263306
3) alpha=0 unbiased+dreg max |grad|: 2.5106921195983887 expected: 0.0
sbi version

0.27.0 (upstream/main @ 1c3d53d7)

Python version

Python 3.12.16

Device

CPU

Inference method

Not method-specific

Single-round or multi-round

Not applicable

Additional context

Method: Variational Inference (vi_method="alpha"), tested on Windows 11 with torch 2.15.0.

Dominant language
Python
Stars
894
Forks
306
Avg merge
5d 21h
Merged PRs (30d)
61

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from sbi-dev/sbi

All issues in sbi-dev/sbi

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.