MCPcopy Create free account
hub / github.com/MotrixLab/FineMoGen / normal_kl

Function normal_kl

mogen/models/utils/gaussian_diffusion.py:172–193  ·  view source on GitHub ↗

Compute the KL divergence between two gaussians. Shapes are automatically broadcasted, so batches can be compared to scalars, among other use cases.

(mean1, logvar1, mean2, logvar2)

Source from the content-addressed store, hash-verified

170
171
172def normal_kl(mean1, logvar1, mean2, logvar2):
173 """
174 Compute the KL divergence between two gaussians.
175 Shapes are automatically broadcasted, so batches can be compared to
176 scalars, among other use cases.
177 """
178 tensor = None
179 for obj in (mean1, logvar1, mean2, logvar2):
180 if isinstance(obj, th.Tensor):
181 tensor = obj
182 break
183 assert tensor is not None, "at least one argument must be a Tensor"
184
185 # Force variances to be Tensors. Broadcasting helps convert scalars to
186 # Tensors, but it does not work for th.exp().
187 logvar1, logvar2 = [
188 x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)
189 for x in (logvar1, logvar2)
190 ]
191
192 return 0.5 * (-1.0 + logvar2 - logvar1 + th.exp(logvar1 - logvar2) +
193 ((mean1 - mean2)**2) * th.exp(-logvar2))
194
195
196def approx_standard_normal_cdf(x):

Callers 2

_vb_terms_bpdMethod · 0.85
_prior_bpdMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected