Skip to content
Edit this page View source of this page

optora.divergences.kl

Kullback-Leibler divergence between discrete probability distributions.

KLDivergence

Bases: Divergence

Kullback-Leibler divergence of a candidate distribution from a reference.

For discrete distributions represented as nonnegative tensors that sum to one along their last dimension, computes

\[ D_{\mathrm{KL}}(p \,\|\, q) = \sum_i p_i \log \frac{p_i}{q_i}. \]

optora.dro.kl_dro uses this divergence to define KL-based ambiguity sets.

Attributes:

Name Type Description
eps

Small positive constant used to clamp p and q away from zero before taking the logarithm, avoiding division by zero and log(0) without branching on masked entries.

__init__(eps=1e-12)

Initialize the KL divergence.

Parameters:

Name Type Description Default
eps float

Small positive constant used to clamp p and q away from zero before taking the logarithm.

1e-12

Raises:

Type Description
ValueError

If eps is not positive.

forward(p, q)

Compute the KL divergence of p from q.

Parameters:

Name Type Description Default
p Tensor

Candidate distribution of shape (..., n), nonnegative and summing to one along its last dimension.

required
q Tensor

Reference distribution of shape (..., n), broadcasting against p.

required

Returns:

Type Description
Tensor

\(D_{\mathrm{KL}}(p \,\|\, q)\) over the broadcast batch, of shape

Tensor

(...), clamped to be nonnegative to absorb floating-point

Tensor

error near zero, computed in optora.core.working_dtype(p, q)

Tensor

and returned in the promoted dtype of p and q.