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)
| 8 | |
| 9 | |
| 10 | def 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 | |
| 39 | def approx_standard_normal_cdf(x): |
no outgoing calls
no test coverage detected