Skip to content
fn

kl_div

→Tensor
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 pp (the target) with distribution qq (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⁡q\log q (log-predicted), and target is pp (target probability) — or log⁡p\log p if log_target=True. Note this is asymmetric in its arguments — KL is not a metric.

Parameters

inputTensor
Log-probabilities of the predicted distribution log⁡q\log q, any shape.
targetTensor
Probabilities of the target distribution pp, or its log when log_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= False
When True, treat target as already-logged (log⁡p\log p).

Returns

Tensor

Scalar or full-shape per reduction.

Notes

Per-element loss:

Li=pi⋅(log⁡pi−log⁡qi)L_i = p_i \cdot (\log p_i - \log q_i)

with 0log⁡0=00 \log 0 = 0, so a target with zero entries (one-hot, sparse) contributes nothing there rather than nan. Globally:

DKL(p ∥ q)=∑ipilog⁡piqi≥0,D_{\mathrm{KL}}(p \,\|\, q) = \sum_i p_i \log \tfrac{p_i}{q_i} \ge 0,

with equality iff p=qp = q 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)

Used by 2