RenyiDivergenceOptimizer (vi_method='alpha') with dreg=True scales gradients by n_particles and uses biased weights for alpha != 0
Maintainers usually reply within 6 days
Assessment
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Newbie friendliness
- 35/100
- Issue type
- Bug
- Clarity
- Clearly specified
- Activity status
- Stale
- Domain
- machine-learning
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:
-
weightsinget_importance_weightare scaled byn_particlesbefore squaring:
get_importance_weightcomputesmean_log_weights = torch.logsumexp(logweights, 0) - np.log(self.n_particles), soweights = (logweights - mean_log_weights).exp()sums ton_particlesinstead of1. Whendreg=False, takingtorch.mean(weights * elbo_particles_masked)inloss_alphacancels this factor. Whendreg=True,weights = weights**2leaves an extra factor ofn_particles(256x at the defaultn_particles=256). Atalpha=0,RenyiDivergenceOptimizer(..., dreg=True)gives gradientsn_particlestimes larger than the documented-equivalentIWElboOptimizer(n_particles=1, K=n_particles, dreg=True). -
weights**2only applies toalpha = 0(IWAE), not general Rényi VR-alpha:
Forw_k = softmax((1 - alpha) * elbo_k), differentiatingw_kwith respect totheta_kgives(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 weightsalpha * w_k + (1 - alpha) * w_k**2(reduces tow_k**2atalpha = 0and1 / n_particlesatalpha = 1). Usingweights**2foralpha != 0gives biased gradients. -
dreg=Truewithunbiased=Trueignoresdreg:
_detach_log_q()detacheslog_qwheneverdreg=True, butloss_alpha_unbiaseddiscards the weights returned byget_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
weightsinget_importance_weightusingsum_log_weights = torch.logsumexp(logweights, 0)(summing to 1, matchingIWElboOptimizer) and changeloss_alphafrom-torch.mean(weights * elbo_particles_masked)to-torch.sum(weights * elbo_particles_masked). - When
self.dregis True, useself.alpha * weights + (1 - self.alpha) * weights**2inget_importance_weight. - When
self.dregis True inloss_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 withIWElboOptimizeratalpha = 0, exact DReG weights acrossalphavalues, Monte Carlo expectation agreement with pathwise VR-alphagradients, andunbiased=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
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from sbi-dev/sbi
-
simulate_for_sbi(num_simulations=0) returns 1D empty theta/x tensors and breaks append_simulationsOpenbug
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
sbi-dev/sbi#2310 · 3 comments ·
Maintainers usually reply within 6 days
-
bug: RestrictionEstimator.train(subsample_invalid_sims="auto") raises TypeErrorPossibly taken @Nitesh780 claimed this 2 days ago. Openbug
Difficulty 1/5 1-3 hours Newbie friendliness 85/100
sbi-dev/sbi#2309 · 1 comment ·
Maintainers usually reply within 6 days
-
TARP reference sampling fails when a parameter coordinate is fixedPossibly taken @Jayant-kernel claimed this 4 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
sbi-dev/sbi#2264 · 2 comments ·
Maintainers usually reply within 6 days
-
fix: broadcast UniformNormalConvolution batch shapePossibly taken @studentarijitpaul claimed this 32 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
sbi-dev/sbi#2151 · 2 comments ·
Maintainers usually reply within 6 days
-
bug
sbi-dev/sbi#2321 · 1 comment ·
Maintainers usually reply within 6 days
Similar issues
-
docs(contributing): the two things that silently block a PRPossibly taken A pull request linked to this issue is open or already merged. Openavailable documentation good first issue
Difficulty 1/5 1-3 hours Newbie friendliness 95/100
Nixitov/Riptide-Native#944 ·
Maintainers usually reply within 1 day
-
bug
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
JTHCode/secretguard#24 ·
Maintainers usually reply within 1 day
-
area: middleware documentation good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
-
enhancement good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
Maintainers usually reply within 1 day
-
good first issue
Difficulty 1/5 Under an hour Newbie friendliness 95/100
omarelshamy25x/shamy-hijri#63 ·
Maintainers usually reply within 1 day