Skip to content

Kullback-Leibler divergence #131

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions nn/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,52 @@ def cross_entropy(*, target: nn.Tensor, estimated: nn.Tensor, estimated_type: st
else:
raise ValueError("estimated_kind must be 'probs', 'log-probs' or 'logits'")
return -nn.dot(target, log_prob, reduce=axis)


def kl_div(*, target: nn.Tensor, target_type: str,
estimated: nn.Tensor, estimated_type: str,
axis: Optional[nn.Dim] = None) -> nn.Tensor:
"""
Kullback-Leibler divergence (https://en.wikipedia.org/wiki/Kullback-Leibler_divergence)

L(target, estimated) = target * log(target / estimated)
= target * (log(target) - log(estimated)

:param target: probs, normalized. can also be sparse
:param target_type: "probs", "log-probs" or "logits"
:param estimated: probs, log-probs or logits, specified via ``estimated_type``
:param estimated_type: "probs", "log-probs" or "logits"
:param axis: the axis to reduce over
:return: KL-div
"""
if not axis:
assert target.feature_dim
axis = target.feature_dim

if target.data.sparse:
raise NotImplementedError(f"Sparse target {target} not supported for KL. Use cross entropy instead?")
if target_type == "probs":
log_target = nn.safe_log(target)
elif estimated_type == "log-probs":
log_target = target
elif estimated_type == "logits":
log_target = nn.log_softmax(target, axis=axis)
else:
raise ValueError("target_kind must be 'probs', 'log-probs' or 'logits'")

if estimated_type == "probs":
log_est = nn.safe_log(estimated)
elif estimated_type == "log-probs":
log_est = estimated
elif estimated_type == "logits":
log_est = nn.log_softmax(estimated, axis=axis)
else:
raise ValueError("estimated_kind must be 'probs', 'log-probs' or 'logits'")

# Assuming target = softmax(...):
# Using nn.exp(log_target) instead of target (but not nn.safe_exp!)
# to avoid calculating softmax twice (efficiency)
# (because nn.safe_log(target) = log_softmax(...), so a separate softmax calculation).
kl = nn.dot(nn.exp(log_target), log_target - log_est, reduce=axis)

return kl