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)
| 161 | |
| 162 | |
| 163 | def 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 | |
| 192 | def approx_standard_normal_cdf(x): |
no outgoing calls
no test coverage detected