oneflow.nn.KLDivLoss

class oneflow.nn.KLDivLoss(reduction: str = 'mean', log_target: bool = False)

The Kullback-Leibler divergence loss measure

Kullback-Leibler divergence is a useful distance measure for continuous distributions and is often useful when performing direct regression over the space of (discretely sampled) continuous output distributions.

As with NLLLoss, the input given is expected to contain log-probabilities and is not restricted to a 2D Tensor. The targets are interpreted as probabilities by default, but could be considered as log-probabilities with log_target set to True.

This criterion expects a target Tensor of the same size as the input Tensor.

The unreduced (i.e. with reduction set to 'none') loss can be described as:

\[l(x,y) = L = \{ l_1,\dots,l_N \}, \quad l_n = y_n \cdot \left( \log y_n - x_n \right)\]

where the index \(N\) spans all dimensions of input and \(L\) has the same shape as input. If reduction is not 'none' (default 'mean'), then:

\[\begin{split}\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';} \\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}\end{split}\]

In default reduction mode 'mean', the losses are averaged for each minibatch over observations as well as over dimensions. 'batchmean' mode gives the correct KL divergence where losses are averaged over batch dimension only. 'mean' mode’s behavior will be changed to the same as 'batchmean' in the next major release.

The interface is consistent with PyTorch. The documentation is referenced from: https://pytorch.org/docs/1.10/generated/torch.nn.KLDivLoss.html.

Parameters
  • reduction (string, optional) – Specifies the reduction to apply to the output: 'none' | 'batchmean' | 'sum' | 'mean'. 'none': no reduction will be applied. 'batchmean': the sum of the output will be divided by batchsize. 'sum': the output will be summed. 'mean': the output will be divided by the number of elements in the output. Default: 'mean'

  • log_target (bool, optional) – Specifies whether target is passed in the log space. Default: False

Note

reduction = 'mean' doesn’t return the true kl divergence value, please use reduction = 'batchmean' which aligns with KL math definition. In the next major release, 'mean' will be changed to be the same as 'batchmean'.

Shape:
  • Input: \((N, *)\) where \(*\) means, any number of additional dimensions

  • Target: \((N, *)\), same shape as the input

  • Output: scalar by default. If :attr:reduction is 'none', then \((N, *)\), the same shape as the input

For example:

>>> import oneflow as flow
>>> import numpy as np
>>> input = flow.tensor([-0.9021705, 0.08798598, 1.04686249], dtype=flow.float32)
>>> target = flow.tensor([1.22386942, -0.89729659, 0.01615712], dtype=flow.float32)
>>> m = flow.nn.KLDivLoss(reduction="none", log_target=False)
>>> out = m(input, target)
>>> out
tensor([ 1.3514,  0.0000, -0.0836], dtype=oneflow.float32)
>>> m = flow.nn.KLDivLoss(reduction="mean", log_target=False)
>>> out = m(input, target)
>>> out
tensor(0.4226, dtype=oneflow.float32)
>>> m = flow.nn.KLDivLoss(reduction="sum", log_target=True)
>>> out = m(input, target)
>>> out
tensor(5.7801, dtype=oneflow.float32)
__init__(reduction: str = 'mean', log_target: bool = False)None

Initialize self. See help(type(self)) for accurate signature.

Methods

__call__(*args, **kwargs)

Call self as a function.

__delattr__(name, /)

Implement delattr(self, name).

__dir__()

Default dir() implementation.

__eq__(value, /)

Return self==value.

__format__(format_spec, /)

Default object formatter.

__ge__(value, /)

Return self>=value.

__getattr__(name)

__getattribute__(name, /)

Return getattr(self, name).

__gt__(value, /)

Return self>value.

__hash__()

Return hash(self).

__init__([reduction, log_target])

Initialize self.

__init_subclass__

This method is called when a class is subclassed.

__le__(value, /)

Return self<=value.

__lt__(value, /)

Return self<value.

__ne__(value, /)

Return self!=value.

__new__(**kwargs)

Create and return a new object.

__reduce__()

Helper for pickle.

__reduce_ex__(protocol, /)

Helper for pickle.

__repr__()

Return repr(self).

__setattr__(name, value)

Implement setattr(self, name, value).

__sizeof__()

Size of object in memory, in bytes.

__str__()

Return str(self).

__subclasshook__

Abstract classes can override this to customize issubclass().

_apply(fn[, applied_dict])

_get_name()

_load_from_state_dict(state_dict, prefix, …)

_named_members(get_members_fn[, prefix, recurse])

_save_to_state_dict(destination, prefix, …)

_shallow_repr()

add_module(name, module)

Adds a child module to the current module.

apply(fn)

Applies fn recursively to every submodule (as returned by .children()) as well as self.

buffers([recurse])

Returns an iterator over module buffers.

children()

Returns an iterator over immediate children modules.

cpu()

Moves all model parameters and buffers to the CPU.

cuda([device])

Moves all model parameters and buffers to the GPU.

double()

Casts all floating point parameters and buffers to double datatype.

eval()

Sets the module in evaluation mode.

extra_repr()

Set the extra representation of the module

float()

Casts all floating point parameters and buffers to float datatype.

forward(input, target)

half()

Casts all floating point parameters and buffers to half datatype.

load_state_dict(state_dict[, strict])

Copies parameters and buffers from state_dict into this module and its descendants.

modules()

Returns an iterator over all modules in the network.

named_buffers([prefix, recurse])

Returns an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.

named_children()

Returns an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

named_modules([memo, prefix])

Returns an iterator over all modules in the network, yielding both the name of the module as well as the module itself.

named_parameters([prefix, recurse])

Returns an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.

parameters([recurse])

Returns an iterator over module parameters.

register_buffer(name, tensor[, persistent])

Adds a buffer to the module.

register_forward_hook(hook)

Registers a forward hook on the module.

register_forward_pre_hook(hook)

Registers a forward pre-hook on the module.

register_parameter(name, param)

Adds a parameter to the module.

state_dict([destination, prefix, keep_vars])

Returns a dictionary containing a whole state of the module.

to([device])

Moves the parameters and buffers.

to_consistent(*args, **kwargs)

This interface is no longer available, please use oneflow.nn.Module.to_global() instead.

to_global([placement, sbp])

Convert the parameters and buffers to global.

train([mode])

Sets the module in training mode.

zero_grad([set_to_none])

Sets gradients of all model parameters to zero.