kl_div(input: Tensor, target: Tensor, size_average: bool | None = None, reduce: bool | None = None, reduction: ReductionKL = 'mean', log_target: bool = False)Kullback-Leibler divergence between two distributions.
Measures the "information gain" from approximating distribution (the target) with distribution (the input). Used heavily in knowledge distillation (matching student logits to a teacher's), variational inference (the ELBO's KL term), and policy-gradient regularisation in RL.
The convention here matches the reference framework: input is
(log-predicted), and target is
(target probability) — or if log_target=True.
Note this is asymmetric in its arguments — KL is not a metric.
Parameters
inputTensortargetTensorlog_target=True. Same shape as input, or
one that broadcasts with it (another raises ValueError).reductionstr= 'mean'"none", "mean", "sum", or "batchmean" (default
"mean"). "batchmean" divides the summed loss by the
leading (batch) dimension (or the sum for a 0-d input) and is
the only reduction that yields the mathematically correct KL
value in expectation.size_ averagestr= 'mean'"none", "mean", "sum", or "batchmean" (default
"mean"). "batchmean" divides the summed loss by the
leading (batch) dimension (or the sum for a 0-d input) and is
the only reduction that yields the mathematically correct KL
value in expectation.reducestr= 'mean'"none", "mean", "sum", or "batchmean" (default
"mean"). "batchmean" divides the summed loss by the
leading (batch) dimension (or the sum for a 0-d input) and is
the only reduction that yields the mathematically correct KL
value in expectation.log_ targetbool= FalseTrue, treat target as already-logged ().Returns
TensorScalar or full-shape per reduction.
Notes
Per-element loss:
with , so a target with zero entries (one-hot,
sparse) contributes nothing there rather than nan. Globally:
with equality iff almost everywhere. The standard
"mean" reduction divides by the element count, not the
batch size, so it under-reports the divergence value — prefer
"batchmean" whenever the absolute scale matters.
Examples
>>> import lucid
>>> from lucid.nn.functional import kl_div, log_softmax
>>> log_q = log_softmax(lucid.tensor([[2.0, 0.5, 0.1]]), dim=1)
>>> p = lucid.tensor([[0.8, 0.15, 0.05]])
>>> kl_div(log_q, p, reduction="batchmean")
tensor(0.02391)