MCPcopy Create free account
hub / github.com/Vchitect/Latte / normal_kl

Function normal_kl

diffusion/diffusion_utils.py:10–36  ·  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

8
9
10def normal_kl(mean1, logvar1, mean2, logvar2):
11 """
12 Compute the KL divergence between two gaussians.
13 Shapes are automatically broadcasted, so batches can be compared to
14 scalars, among other use cases.
15 """
16 tensor = None
17 for obj in (mean1, logvar1, mean2, logvar2):
18 if isinstance(obj, th.Tensor):
19 tensor = obj
20 break
21 assert tensor is not None, "at least one argument must be a Tensor"
22
23 # Force variances to be Tensors. Broadcasting helps convert scalars to
24 # Tensors, but it does not work for th.exp().
25 logvar1, logvar2 = [
26 x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)
27 for x in (logvar1, logvar2)
28 ]
29
30 return 0.5 * (
31 -1.0
32 + logvar2
33 - logvar1
34 + th.exp(logvar1 - logvar2)
35 + ((mean1 - mean2) ** 2) * th.exp(-logvar2)
36 )
37
38
39def 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