parallel_margin_cross_entropy.py 8.5 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
import random
16 17 18
import unittest

import numpy as np
19 20

import paddle
21
import paddle.distributed as dist
22
from paddle.distributed import fleet
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60


def set_random_seed(seed):
    """Set random seed for reproducability."""
    random.seed(seed)
    np.random.seed(seed)
    paddle.seed(seed)
    fleet.meta_parallel.model_parallel_random_seed(seed)


class TestParallelMarginSoftmaxCrossEntropyOp(unittest.TestCase):
    def setUp(self):
        strategy = fleet.DistributedStrategy()
        fleet.init(is_collective=True, strategy=strategy)

    def test_parallel_margin_softmax_cross_entropy(self):
        margin1s = [1.0, 1.0, 1.35]
        margin2s = [0.5, 0.0, 0.0]
        margin3s = [0.0, 0.35, 0.0]
        scales = [64.0, 64.0, 64.0]

        rank_id = dist.get_rank()
        num_trainer = dist.get_world_size()
        batch_size = 2
        feature_length = 4
        seed = 1025
        set_random_seed(seed)
        paddle.seed(rank_id * 10)
        random.seed(seed)
        np.random.seed(seed)

        check_group = dist.new_group(list(range(num_trainer)))
        for dtype in ('float32', 'float64'):

            num_class_per_cards = [[4, 8], [2, 2], [4, 2], [3, 9]]
            for num_class_per_card in num_class_per_cards:

                num_class = np.sum(num_class_per_card)
61
                for margin1, margin2, margin3, scale in zip(
62 63
                    margin1s, margin2s, margin3s, scales
                ):
64 65

                    for _ in range(5):
66 67 68
                        np_label = np.random.randint(
                            0, num_class, (batch_size,)
                        )
69 70
                        label = paddle.to_tensor(np_label, dtype="int64")

71 72 73
                        input = paddle.randn(
                            shape=[batch_size, feature_length], dtype=dtype
                        )
74 75
                        input.stop_gradient = False
                        input_l2 = paddle.sqrt(
76 77 78 79
                            paddle.sum(
                                paddle.square(input), axis=1, keepdim=True
                            )
                        )
80 81 82
                        norm_input = paddle.divide(input, input_l2)

                        weight = paddle.randn(
83
                            shape=[feature_length, num_class_per_card[rank_id]],
84 85
                            dtype=dtype,
                        )
86 87
                        weight.stop_gradient = False
                        weight_l2 = paddle.sqrt(
88 89 90 91
                            paddle.sum(
                                paddle.square(weight), axis=0, keepdim=True
                            )
                        )
92 93 94
                        norm_weight = paddle.divide(weight, weight_l2)

                        data = paddle.matmul(norm_input, norm_weight)
姜永久 已提交
95
                        data.retain_grads()
96 97
                        data.stop_gradient = False

98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
                        sta = (
                            np.sum(num_class_per_card[:rank_id])
                            if rank_id > 0
                            else 0
                        )
                        end = np.sum(num_class_per_card[: rank_id + 1])

                        integral_data = np.zeros(
                            (batch_size, num_class), dtype=dtype
                        )
                        integral_data[:, sta:end] = (
                            data.clone().detach().numpy()
                        )
                        integral_data = paddle.to_tensor(
                            integral_data, dtype=dtype
                        )
114 115 116 117

                        paddle.distributed.all_reduce(
                            integral_data,
                            op=paddle.distributed.ReduceOp.SUM,
118 119
                            group=check_group,
                        )
120
                        integral_data = integral_data.detach().clone()
姜永久 已提交
121
                        integral_data.retain_grads()
122 123 124 125 126
                        integral_data.stop_gradient = False

                        # add arcface margin to logit
                        theta = paddle.acos(integral_data)
                        one_hot_label = paddle.nn.functional.one_hot(
127 128
                            label, num_classes=num_class
                        )
129 130 131 132 133 134 135 136 137 138 139 140
                        one_hot_label.stop_gradient = False

                        if margin1 != 1.0:
                            theta = margin1 * theta
                        if margin2 != 0.0:
                            theta = theta + margin2
                        margin_cos = paddle.cos(theta)
                        if margin3 != 0.0:
                            margin_cos = margin_cos - margin3
                        diff = one_hot_label * (margin_cos - integral_data)
                        arc_data = (integral_data + diff) * scale

141 142 143 144
                        (
                            loss_a,
                            softmax_a,
                        ) = paddle.nn.functional.margin_cross_entropy(
145 146 147 148 149 150 151 152
                            data,
                            label,
                            margin1=margin1,
                            margin2=margin2,
                            margin3=margin3,
                            scale=scale,
                            group=check_group,
                            return_softmax=True,
153 154 155 156 157 158
                            reduction=None,
                        )
                        (
                            loss_b,
                            softmax_b,
                        ) = paddle.nn.functional.softmax_with_cross_entropy(
159 160
                            logits=arc_data,
                            label=paddle.reshape(label, (-1, 1)),
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
                            return_softmax=True,
                        )

                        np.testing.assert_allclose(
                            loss_a.numpy(), loss_b.numpy(), rtol=1e-5, atol=1e-7
                        )

                        integral_prob = np.zeros(
                            (batch_size, num_class), dtype=dtype
                        )
                        integral_prob[:, sta:end] = (
                            softmax_a.clone().detach().numpy()
                        )
                        integral_prob = paddle.to_tensor(
                            integral_prob, dtype=dtype
                        )
177 178 179
                        paddle.distributed.all_reduce(
                            integral_prob,
                            op=paddle.distributed.ReduceOp.SUM,
180 181
                            group=check_group,
                        )
182 183 184
                        integral_prob = integral_prob.detach().clone()
                        integral_prob.stop_gradient = False

185 186 187 188 189 190
                        np.testing.assert_allclose(
                            integral_prob.numpy(),
                            softmax_b.numpy(),
                            rtol=1e-5,
                            atol=1e-6,
                        )
191 192 193 194 195 196

                        loss_a = loss_a.sum() / batch_size
                        loss_b = loss_b.sum() / batch_size
                        loss_a.backward()
                        loss_b.backward()

197 198 199
                        integral_grad = np.zeros(
                            (batch_size, num_class), dtype=dtype
                        )
200
                        integral_grad[:, sta:end] = data.grad.clone().detach()
201 202 203
                        integral_grad = paddle.to_tensor(
                            integral_grad, dtype=dtype
                        )
204 205 206
                        paddle.distributed.all_reduce(
                            integral_grad,
                            op=paddle.distributed.ReduceOp.SUM,
207 208 209 210 211 212 213 214 215
                            group=check_group,
                        )

                        np.testing.assert_allclose(
                            integral_data.grad.numpy(),
                            integral_grad.numpy(),
                            rtol=1e-5,
                            atol=1e-7,
                        )
216 217 218 219


if __name__ == '__main__':
    unittest.main()