Skip to content

Commit

Permalink
Add AdaptiveLogSoftmaxWithLoss
Browse files Browse the repository at this point in the history
  • Loading branch information
robinbg committed Oct 7, 2021
1 parent dc4d571 commit bdeac75
Show file tree
Hide file tree
Showing 3 changed files with 264 additions and 2 deletions.
1 change: 1 addition & 0 deletions python/paddle/nn/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
from .layer.loss import MarginRankingLoss # noqa: F401
from .layer.loss import CTCLoss # noqa: F401
from .layer.loss import SmoothL1Loss # noqa: F401
from .layer.loss import AdaptiveLogSoftmaxWithLoss # noqa: F401
from .layer.norm import BatchNorm # noqa: F401
from .layer.norm import SyncBatchNorm # noqa: F401
from .layer.norm import GroupNorm # noqa: F401
Expand Down
1 change: 1 addition & 0 deletions python/paddle/nn/layer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
from .loss import MarginRankingLoss # noqa: F401
from .loss import CTCLoss # noqa: F401
from .loss import SmoothL1Loss # noqa: F401
from .loss import AdaptiveLogSoftmaxWithLoss # noqa: F401
from .norm import BatchNorm1D # noqa: F401
from .norm import BatchNorm2D # noqa: F401
from .norm import BatchNorm3D # noqa: F401
Expand Down
264 changes: 262 additions & 2 deletions python/paddle/nn/layer/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,21 @@
# limitations under the License.

# TODO: define loss functions of neural network
from collections import namedtuple
from typing import List, Sequence

import numpy as np
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle
from .. import functional as F
from paddle.fluid.framework import core, in_dygraph_mode, _varbase_creator
from .. import Layer
from .. import Layer, Sequential, LayerList
from paddle.nn.layer import Linear
from paddle import Tensor

__all__ = []

_ASMoutput = namedtuple('_ASMoutput', ['output', 'loss'])

class BCEWithLogitsLoss(Layer):
r"""
Expand Down Expand Up @@ -1207,3 +1212,258 @@ def forward(self, input, label):
reduction=self.reduction,
delta=self.delta,
name=self.name)


class AdaptiveLogSoftmaxWithLoss(Layer):
r"""Efficient softmax approximation as described in
`Efficient softmax approximation for GPUs by Edouard Grave, Armand Joulin,
Moustapha Cissé, David Grangier, and Hervé Jégou
<https://arxiv.org/abs/1609.04309>`__.
Adaptive softmax is an approximate strategy for training models with large
output spaces. It is most effective when the label distribution is highly
imbalanced, for example in natural language modelling, where the word
frequency distribution approximately follows the `Zipf's law`_.
Adaptive softmax partitions the labels into several clusters, according to
their frequency. These clusters may contain different number of targets
each.
Additionally, clusters containing less frequent labels assign lower
dimensional embeddings to those labels, which speeds up the computation.
For each minibatch, only clusters for which at least one target is
present are evaluated.
The idea is that the clusters which are accessed frequently
(like the first one, containing most frequent labels), should also be cheap
to compute -- that is, contain a small number of assigned labels.
We highly recommend taking a look at the original paper for more details.
* :attr:`cutoffs` should be an ordered Sequence of integers sorted
in the increasing order.
It controls number of clusters and the partitioning of targets into
clusters. For example setting ``cutoffs = [10, 100, 1000]``
means that first `10` targets will be assigned
to the 'head' of the adaptive softmax, targets `11, 12, ..., 100` will be
assigned to the first cluster, and targets `101, 102, ..., 1000` will be
assigned to the second cluster, while targets
`1001, 1002, ..., n_classes - 1` will be assigned
to the last, third cluster.
* :attr:`div_value` is used to compute the size of each additional cluster,
which is given as
:math:`\left\lfloor\frac{\texttt{in\_features}}{\texttt{div\_value}^{idx}}\right\rfloor`,
where :math:`idx` is the cluster index (with clusters
for less frequent words having larger indices,
and indices starting from :math:`1`).
* :attr:`head_bias` if set to True, adds a bias term to the 'head' of the
adaptive softmax. See paper for details. Set to False in the official
implementation.
.. warning::
Labels passed as inputs to this module should be sorted according to
their frequency. This means that the most frequent label should be
represented by the index `0`, and the least frequent
label should be represented by the index `n_classes - 1`.
.. note::
This module returns a ``NamedTuple`` with ``output``
and ``loss`` fields. See further documentation for details.
.. note::
To compute log-probabilities for all classes, the ``log_prob``
method can be used.
Args:
in_features (int): Number of features in the input tensor
n_classes (int): Number of classes in the dataset
cutoffs (Sequence): Cutoffs used to assign targets to their buckets
div_value (float, optional): value used as an exponent to compute sizes
of the clusters. Default: 4.0
head_bias (bool, optional): If ``True``, adds a bias term to the 'head' of the
adaptive softmax. Default: ``False``
Returns:
``NamedTuple`` with ``output`` and ``loss`` fields:
* **output** is a Tensor of size ``N`` containing computed target
log probabilities for each example
* **loss** is a Scalar representing the computed negative
log likelihood loss
Shape:
- input: :math:`(N, \texttt{in\_features})`
- target: :math:`(N)` where each value satisfies :math:`0 <= \texttt{target[i]} <= \texttt{n\_classes}`
- output1: :math:`(N)`
- output2: ``Scalar``
.. _Zipf's law: https://en.wikipedia.org/wiki/Zipf%27s_law
"""

in_features: int
n_classes: int
cutoffs: List[int]
div_value: float
head_bias: bool
head: Linear
tail: LayerList

def __init__(
self,
in_features: int,
n_classes: int,
cutoffs: Sequence[int],
div_value: float = 4.,
head_bias: bool = False,
device=None,
dtype=None
) -> None:
factory_kwargs = {'device': device, 'dtype': dtype}
super(AdaptiveLogSoftmaxWithLoss, self).__init__()

cutoffs = list(cutoffs)

if (cutoffs != sorted(cutoffs)) \
or (min(cutoffs) <= 0) \
or (max(cutoffs) > (n_classes - 1)) \
or (len(set(cutoffs)) != len(cutoffs)) \
or any([int(c) != c for c in cutoffs]):

raise ValueError("cutoffs should be a sequence of unique, positive "
"integers sorted in an increasing order, where "
"each value is between 1 and n_classes-1")

self.in_features = in_features
self.n_classes = n_classes
self.cutoffs = cutoffs + [n_classes]
self.div_value = div_value
self.head_bias = head_bias

self.shortlist_size = self.cutoffs[0]
self.n_clusters = len(self.cutoffs) - 1
self.head_size = self.shortlist_size + self.n_clusters

self.head = Linear(self.in_features, self.head_size, bias=self.head_bias,
**factory_kwargs)
self.tail = LayerList()

for i in range(self.n_clusters):

hsz = int(self.in_features // (self.div_value ** (i + 1)))
osz = self.cutoffs[i + 1] - self.cutoffs[i]

projection = Sequential(
Linear(self.in_features, hsz, bias=False, **factory_kwargs),
Linear(hsz, osz, bias=False, **factory_kwargs),
)

self.tail.append(projection)


def forward(self, input: Tensor, target: Tensor) -> _ASMoutput:
if input.shape[0]!= target.shape[0]:
raise RuntimeError('Input and target should have the same size '
'in the batch dimension.')

used_rows = 0
batch_size = target.shape[0]

output = paddle.zeros([batch_size])
gather_inds = paddle.empty([batch_size])

cutoff_values = [0] + self.cutoffs
for i in range(len(cutoff_values) - 1):

low_idx = cutoff_values[i]
high_idx = cutoff_values[i + 1]

target_mask = (target >= low_idx) & (target < high_idx)
row_indices = target_mask.nonzero().squeeze()

if row_indices.numel() == 0:
continue

if i == 0:
for i, j in enumerate(row_indices):
gather_inds[j,:] = target[target_mask][i,:]

else:
relative_target = target[target_mask] - low_idx
input_subset = input.index_select(row_indices, 0)

cluster_output = self.tail[i - 1](input_subset)
cluster_index = self.shortlist_size + i - 1


for idx in row_indices:
gather_inds[idx, :] = cluster_index

cluster_logprob = F.log_softmax(cluster_output, axis=1)
local_logprob = cluster_logprob.gather(1, relative_target.unsqueeze(1)).squeeze(1)
for i, j in enumerate(row_indices):
gather_inds[j,:] = local_logprob[i,:]
used_rows += row_indices.numel()

if used_rows != batch_size:
raise RuntimeError("Target values should be in [0, {}], "
"but values in range [{}, {}] "
"were found. ".format(self.n_classes - 1,
target.min().item(),
target.max().item()))

head_output = self.head(input)
head_logprob = F.log_softmax(head_output, axis=1)
output += head_logprob.gather(1, gather_inds.unsqueeze(1)).squeeze()
loss = (-output).mean()

return _ASMoutput(output, loss)

def _get_full_log_prob(self, input, head_output):
""" Given input tensor, and output of `self.head`,
compute the log of the full distribution """

out = paddle.empty((head_output.shape[0], self.n_classes))
head_logprob = F.log_softmax(head_output, axis=1)

out[:, :self.shortlist_size] = head_logprob[:, :self.shortlist_size]

for i, (start_idx, stop_idx) in enumerate(zip(self.cutoffs, self.cutoffs[1:])):
cluster_output = self.tail[i](input)
cluster_logprob = F.log_softmax(cluster_output, axis=1)
output_logprob = cluster_logprob + head_logprob[:, self.shortlist_size + i].unsqueeze(1)

out[:, start_idx:stop_idx] = output_logprob

return out

def log_prob(self, input: Tensor) -> Tensor:
r""" Computes log probabilities for all :math:`\texttt{n\_classes}`
Args:
input (Tensor): a minibatch of examples
Returns:
log-probabilities of for each class :math:`c`
in range :math:`0 <= c <= \texttt{n\_classes}`, where :math:`\texttt{n\_classes}` is a
parameter passed to ``AdaptiveLogSoftmaxWithLoss`` constructor.
Shape:
- Input: :math:`(N, \texttt{in\_features})`
- Output: :math:`(N, \texttt{n\_classes})`
"""

head_output = self.head(input)
return self._get_full_log_prob(input, head_output)

def predict(self, input: Tensor) -> Tensor:
r""" This is equivalent to `self.log_pob(input).argmax(dim=1)`,
but is more efficient in some cases.
Args:
input (Tensor): a minibatch of examples
Returns:
output (Tensor): a class with the highest probability for each example
Shape:
- Input: :math:`(N, \texttt{in\_features})`
- Output: :math:`(N)`
"""

head_output = self.head(input)
output = paddle.argmax(head_output, axis=1)
not_in_shortlist = (output >= self.shortlist_size)
all_in_shortlist = not (not_in_shortlist.any())

if all_in_shortlist:
return output

elif not_in_shortlist.all():
log_prob = self._get_full_log_prob(input, head_output)
return paddle.argmax(log_prob, axis=1)

else:
log_prob = self._get_full_log_prob(input[not_in_shortlist],
head_output[not_in_shortlist])
output[not_in_shortlist] = paddle.argmax(log_prob, axis=1)
return output

1 comment on commit bdeac75

@paddle-bot-old
Copy link

@paddle-bot-old paddle-bot-old bot commented on bdeac75 Oct 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵️ CI failures summary

🔍 PR: #36267 Commit ID: bdeac75 contains failed CI.

🔹 Failed: PR-CI-iScan-C

Unknown Failed
Unknown Failed

🔹 Failed: PR-CI-CPU-Py2

code_style_failed
2021-10-07 18:37:38     with_avx: ON
2021-10-07 18:37:38 with_gpu: ON
2021-10-07 18:37:38 with_mkl: ON
2021-10-07 18:37:38 with_mkldnn: ON
2021-10-07 18:37:38 with_python: ON'
2021-10-07 18:37:38 + set +x
2021-10-07 18:37:38 ========================================
2021-10-07 18:37:38 summary problems:
2021-10-07 18:37:38 There is 1 error: Code format error.
2021-10-07 18:37:38 ========================================
2021-10-07 18:37:38 Code format error Please fix it according to the diff information:
2021-10-07 18:37:38 code format error
2021-10-07 18:37:38 diff --git a/python/paddle/nn/init.py b/python/paddle/nn/init.py
2021-10-07 18:37:38 index b9c0b76..c94ef9e 100644
2021-10-07 18:37:38 --- a/python/paddle/nn/init.py
2021-10-07 18:37:38 +++ b/python/paddle/nn/init.py
2021-10-07 18:37:38 @@ -99,7 +99,7 @@ from .layer.loss import KLDivLoss # noqa: F401
2021-10-07 18:37:38 from .layer.loss import MarginRankingLoss # noqa: F401
2021-10-07 18:37:38 from .layer.loss import CTCLoss # noqa: F401
2021-10-07 18:37:38 from .layer.loss import SmoothL1Loss # noqa: F401
2021-10-07 18:37:38 -from .layer.loss import AdaptiveLogSoftmaxWithLoss # noqa: F401

🔹 Failed: PR-CI-Coverage

coverage_failed
2021-10-07 18:42:50 ./nn/layer/index-sort-l.html
2021-10-07 18:42:50 ./nn/index-sort-l.html
2021-10-07 18:42:50 ./index.html
2021-10-07 18:42:50 ./updown.png
2021-10-07 18:42:50 ./glass.png
2021-10-07 18:42:50 ./index-sort-l.html
2021-10-07 18:42:50 ./amber.png
2021-10-07 18:42:50 ./ruby.png
2021-10-07 18:42:50 + du -hs /tmp/upload-90d1a225-fafa-4791-83a9-cce62d6976cc.tar.gz
2021-10-07 18:42:50 40K /tmp/upload-90d1a225-fafa-4791-83a9-cce62d6976cc.tar.gz
2021-10-07 18:42:50 + curl -s --connect-timeout 600 --retry 10 --retry-delay 10 -u paddle:915eedab953b6f51151f50eb -F buildId=8114694 -F path=python-coverage -F file=@/tmp/upload-90d1a225-fafa-4791-83a9-cce62d6976cc.tar.gz https://xly.bce.baidu.com/ipipe/ipipe-report/upload
2021-10-07 18:42:51 + rm -f /tmp/upload-90d1a225-fafa-4791-83a9-cce62d6976cc.tar.gz
2021-10-07 18:42:51 report uploaded
2021-10-07 18:42:51 9
2021-10-07 18:42:51 ipipe_log_param_EXCODE: 9
2021-10-07 18:42:51 Sorry, coverage check failed.
2021-10-07 18:42:51 + exit 9
2021-10-07 18:42:51 {build code state=9}
2021-10-07 18:43:01 kill agent BUILD_CODE_FAIL

🔹 Failed: PR-CI-Model-benchmark

Unknown Failed
2021-10-07 18:45:41 result_loss:4.19546
2021-10-07 18:45:41 model:ResNet50_bs32_dygraph
2021-10-07 18:45:41 standard_result:597.617
2021-10-07 18:45:41 ResNet50_bs32_dygraph, Performance_test, SUCCESS
2021-10-07 18:45:41 loss result:4.19546
2021-10-07 18:45:41 loss standard result:4.29
2021-10-07 18:45:41 ResNet50_bs32_dygraph, Precision_test, SUCCESS
2021-10-07 18:45:41 model benchmark ci job success!
2021-10-07 18:45:41 + EXCODE=0
2021-10-07 18:45:41 + echo 'EXCODE: 0'
2021-10-07 18:45:41 EXCODE: 0
2021-10-07 18:45:41 + echo 'ipipe_log_param_EXCODE: 0'
2021-10-07 18:45:41 ipipe_log_param_EXCODE: 0
2021-10-07 18:45:41 + [[ 0 -eq 22 ]]
2021-10-07 18:45:41 + set +x
2021-10-07 18:45:41 Congratulations! Your PR passed the paddle-test.
2021-10-07 18:45:41 + exit 0
2021-10-07 18:45:41 {build code state=0}
2021-10-07 18:45:41 build Paddle success!

🔹 Failed: PR-CI-OP-benchmark

Unknown Failed
2021-10-07 18:11:20 log path: /data/docker/containers/a8cc2462148933dcf80fb21cc5042aab647ddb2870030a15d5b5a04a9eb6d4d8
2021-10-07 18:11:20 mkdir file PaddlePaddle/Paddle start!
2021-10-07 18:11:20 mkdir -p /workspace/Paddle
2021-10-07 18:11:20 exe task(buildId=c89a676570244dc79c5f897cfe76430a, actionName=BUILD_CODE) confirm status is true
2021-10-07 18:11:20 build Paddle start!
2021-10-07 18:11:20 build code setEnvCmd and buildCmd
2021-10-07 18:11:20 + set -e
2021-10-07 18:11:20 + set +e
2021-10-07 18:11:20 ++ cat /home/data/cfs/op_benchmark/36267/bdeac7522e074b9106d01d1447057a5249bfedbd/pass.txt
2021-10-07 18:11:20 + cpu_benchmark=cpu_benchmark=ON
2021-10-07 18:11:20 + '[' cpu_benchmark=ON == cpu_benchmark=ON ']'
2021-10-07 18:11:20 + echo 'pass op-benchamrk test'
2021-10-07 18:11:20 pass op-benchamrk test
2021-10-07 18:11:20 + exit 0
2021-10-07 18:11:20 {build code state=0}
2021-10-07 18:11:20 build Paddle success!
2021-10-07 18:11:20 SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
2021-10-07 18:11:20 SLF4J: Defaulting to no-operation (NOP) logger implementation
2021-10-07 18:11:20 SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

🔹 Failed: PR-CI-Py3

Unknown Failed
2021-10-07 18:28:55 ipipe_log_param_TestCases_Total_Time: 566s
2021-10-07 18:28:55 ========================================================
2021-10-07 18:28:55 paddle_build script finished as expected
2021-10-07 18:28:55 + EXCODE=0
2021-10-07 18:28:55 + echo 'EXCODE: 0'
2021-10-07 18:28:55 EXCODE: 0
2021-10-07 18:28:55 + echo 'ipipe_log_param_EXCODE: 0'
2021-10-07 18:28:55 ipipe_log_param_EXCODE: 0
2021-10-07 18:28:55 + [[ 0 -eq 0 ]]
2021-10-07 18:28:55 + cd /workspace/Paddle/build
2021-10-07 18:28:55 + set +x
2021-10-07 18:28:55 + push_dir=/home
2021-10-07 18:28:55 + push_file=/home/BosClient.py
2021-10-07 18:28:55 + tar xf /home/bce_whl.tar.gz -C /home
2021-10-07 18:28:55 + set +x
2021-10-07 18:28:55 Congratulations! Your PR passed the paddle-test.
2021-10-07 18:28:55 + exit 0
2021-10-07 18:28:55 {build code state=0}
2021-10-07 18:28:55 build Paddle success!

🔹 Failed: PR-CE-Framework

Unknown Failed
2021-10-07 18:41:26 total bugs: 0
2021-10-07 18:41:26 [device cases result]
2021-10-07 18:41:26 ============ failed cases =============
2021-10-07 18:41:26 total bugs: 0
2021-10-07 18:41:26 [paddlebase cases result]
2021-10-07 18:41:26 ============ failed cases =============
2021-10-07 18:41:26 total bugs: 0
2021-10-07 18:41:26 [loss cases result]
2021-10-07 18:41:26 ============ failed cases =============
2021-10-07 18:41:26 total bugs: 0
2021-10-07 18:41:26 [incubate cases result]
2021-10-07 18:41:26 ============ failed cases =============
2021-10-07 18:41:26 total bugs: 0
2021-10-07 18:41:26 [nn cases result]
2021-10-07 18:41:26 ============ failed cases =============
2021-10-07 18:41:26 total bugs: 0
2021-10-07 18:41:26 success!
2021-10-07 18:41:26 {build code state=0}
2021-10-07 18:41:26 build Paddle success!

Please sign in to comment.