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

Function normal_kl

diffplanner/models/utils/gaussian_diffusion.py:163–189  ·  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

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