Loss Kl Divergence#
kl_divergence
#
| CLASS | DESCRIPTION |
|---|---|
KLDivergenceLoss |
Kullback-Leibler divergence loss with optional sample weights. |
| FUNCTION | DESCRIPTION |
|---|---|
kl_divergence_loss |
Compute Kullback-Leibler divergence loss with optional weighting. |
Classes#
KLDivergenceLoss(log_prob: bool = False, reduce: Literal['mean', 'sum'] = 'mean', sign: float = 1.0, eps: float = torch.finfo(torch.float32).eps, context_prefix: str | None = None)
#
Bases: Loss
Kullback-Leibler divergence loss with optional sample weights.
Computes \(\mathrm{KL}(P \| Q) = \sum_k w_k P(x_k) \log(P(x_k) / Q(x_k))\), where \(P\) and \(Q\) are probability distributions and \(w_k\) are optional sample weights.
| PARAMETER | DESCRIPTION |
|---|---|
log_prob
|
Whether inputs are log probabilities.
TYPE:
|
reduce
|
Reduction method.
TYPE:
|
sign
|
Loss sign multiplier.
TYPE:
|
eps
|
Small value for numerical stability.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
forward |
Compute KL divergence loss. |
Source code in spectre/loss/kl_divergence.py
Functions#
forward(context: dict, **kwargs) -> torch.Tensor
#
Compute KL divergence loss.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Context dictionary containing the tensors
TYPE:
|
**kwargs
|
Additional keyword arguments.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
KL divergence loss. |
Source code in spectre/loss/kl_divergence.py
Functions#
kl_divergence_loss(P: torch.Tensor, Q: torch.Tensor, weights: Optional[torch.Tensor] = None, reduce: str = 'mean', log_prob: bool = False, sign: float = 1.0) -> torch.Tensor
#
Compute Kullback-Leibler divergence loss with optional weighting.
Computes \(\mathrm{KL}(P \| Q) = \sum_k w_k P(x_k) \log(P(x_k) / Q(x_k))\), where \(P\) and \(Q\) are probability distributions and \(w_k\) are optional sample weights.
| PARAMETER | DESCRIPTION |
|---|---|
P
|
Reference distribution (2D tensor).
TYPE:
|
Q
|
Target distribution (2D tensor).
TYPE:
|
weights
|
Sample weights (1D tensor).
TYPE:
|
reduce
|
Reduction method. Options: "sum", "mean".
TYPE:
|
log_prob
|
Whether inputs are log probabilities.
TYPE:
|
sign
|
Loss sign multiplier.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
KL divergence loss. |