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)
| 170 | |
| 171 | |
| 172 | def 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 | |
| 196 | def approx_standard_normal_cdf(x): |
no outgoing calls
no test coverage detected