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)
| 1020 | |
| 1021 | |
| 1022 | def normal_kl(mean1, logvar1, mean2, logvar2): |
| 1023 | """ |
| 1024 | Compute the KL divergence between two gaussians. |
| 1025 | Shapes are automatically broadcasted, so batches can be compared to |
| 1026 | scalars, among other use cases. |
| 1027 | """ |
| 1028 | tensor = None |
| 1029 | for obj in (mean1, logvar1, mean2, logvar2): |
| 1030 | if isinstance(obj, th.Tensor): |
| 1031 | tensor = obj |
| 1032 | break |
| 1033 | assert tensor is not None, "at least one argument must be a Tensor" |
| 1034 | |
| 1035 | # Force variances to be Tensors. Broadcasting helps convert scalars to |
| 1036 | # Tensors, but it does not work for th.exp(). |
| 1037 | logvar1, logvar2 = [ |
| 1038 | x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor) for x in (logvar1, logvar2) |
| 1039 | ] |
| 1040 | |
| 1041 | return 0.5 * ( |
| 1042 | -1.0 |
| 1043 | + logvar2 |
| 1044 | - logvar1 |
| 1045 | + th.exp(logvar1 - logvar2) |
| 1046 | + ((mean1 - mean2) ** 2) * th.exp(-logvar2) |
| 1047 | ) |
| 1048 | |
| 1049 | |
| 1050 | def approx_standard_normal_cdf(x): |
no outgoing calls
no test coverage detected