test_sparse_momentum_op.py 7.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
# 
# 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
# 
#     http://www.apache.org/licenses/LICENSE-2.0
# 
# 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.

from __future__ import print_function

import unittest
import numpy as np
import paddle.fluid.core as core
from paddle.fluid.op import Operator
from op_test import OpTest
import paddle
import paddle.fluid as fluid


def calculate_sparse_momentum_by_numpy(param,
                                       grad,
                                       mu,
                                       velocity,
                                       use_nesterov,
                                       learning_rate,
                                       index,
                                       axis,
                                       regularization_method=None,
                                       regularization_coeff=1.0):
    sub_grad = grad.copy()
    grad = np.zeros_like(param)
    if axis == 0:
        unique_index = np.unique(index)
        for idx in unique_index:
            grad[idx, :] = np.sum(sub_grad[index == idx, :], axis=0)
    else:
        unique_index = np.unique(index)
        for idx in unique_index:
            grad[:, idx] = np.sum(sub_grad[:, index == idx], axis=1)
    if regularization_method == "l2_decay":
        grad = grad + regularization_coeff * param

        velocity_out = mu * velocity + grad
        if use_nesterov:
            param_out = param - (grad + velocity_out * mu) * learning_rate
        else:
            param_out = param - learning_rate * velocity_out
    else:
        velocity_out = mu * velocity + grad
        if use_nesterov:
            param_out = param - grad * learning_rate - \
                        velocity_out * mu * learning_rate
        else:
            param_out = param - learning_rate * velocity_out

    return param_out, velocity_out


class TestSparseMomentumOp(OpTest):
    def setUp(self):
        self.op_type = "sparse_momentum"
        self.dtype = np.float32
        self.index_dtype = np.int32
        self.axis = 0
        self.multi_precision = False
        self.use_nesterov = False
        self.batch_size = 20
        self.num_classes = 20
        self.init_dtype()
        self.init_axis()
        self.init_multi_precision()
        self.init_use_nesterov()

        if self.multi_precision:
            assert self.dtype == np.float16

        param = np.random.random(
            (self.batch_size, self.num_classes)).astype(self.dtype)
        grad = np.random.random(
            (self.batch_size, self.num_classes)).astype(self.dtype)
        if self.axis == 0:
            index = np.random.randint(
                0,
                self.batch_size,
                size=(self.batch_size // 2, ),
                dtype=self.index_dtype)
            grad = grad[index]
        else:
            index = np.random.randint(
                0,
                self.num_classes,
                size=(self.num_classes // 2, ),
                dtype=self.index_dtype)
            grad = grad[:, index]
        velocity = np.random.random(
            (self.batch_size, self.num_classes)).astype(self.dtype)
        learning_rate = np.array([0.001]).astype(self.dtype)

        mu = 0.9
        regularization_method = "l2_decay"
        regularization_coeff = 1.0

        param_out, velocity_out = calculate_sparse_momentum_by_numpy(
            param=param,
            grad=grad,
            mu=mu,
            velocity=velocity,
            use_nesterov=self.use_nesterov,
            learning_rate=learning_rate,
            regularization_method=regularization_method,
            regularization_coeff=regularization_coeff,
            index=index,
            axis=self.axis)

        self.attrs = {
            'mu': mu,
            'use_nesterov': self.use_nesterov,
            'regularization_method': regularization_method,
            'regularization_coeff': regularization_coeff,
            'multi_precision': self.multi_precision,
            'axis': self.axis,
        }

        self.inputs = {
            'Param': param.astype("float16") if self.multi_precision else param,
            'Velocity': velocity.astype("float32")
            if self.multi_precision else velocity,
            'LearningRate': learning_rate.astype("float32")
            if self.multi_precision else learning_rate,
            'Grad': grad.astype("float16") if self.multi_precision else grad,
            'Index': index,
            'Axis': np.array(self.axis).astype(np.int32),
        }
        self.outputs = {
            'ParamOut': param_out.astype("float16")
            if self.multi_precision else param_out,
            'VelocityOut': velocity_out.astype("float32")
            if self.multi_precision else velocity_out,
        }

        if self.multi_precision:
            self.inputs['MasterParam'] = param.astype(
                "float32") if self.multi_precision else param
            self.outputs['MasterParamOut'] = param_out.astype(
                "float32") if self.multi_precision else param_out

    def init_dtype(self):
        pass

    def init_axis(self):
        pass

    def init_multi_precision(self):
        pass

    def init_use_nesterov(self):
        pass

    def test_check_output(self):
        self.check_output(atol=5e-3 if self.multi_precision else 1e-5)


class TestSparseMomentumOpDtype1(TestSparseMomentumOp):
    def init_dtype(self):
        self.dtype = np.float32
        self.index_dtype = np.int64


class TestSparseMomentumOpDtype2(TestSparseMomentumOp):
    def init_dtype(self):
        self.dtype = np.float64
        self.index_dtype = np.int32


class TestSparseMomentumOpDtype3(TestSparseMomentumOp):
    def init_dtype(self):
        self.dtype = np.float64
        self.index_dtype = np.int64


class TestSparseMomentumOpAxis(TestSparseMomentumOp):
    def init_axis(self):
        self.axis = 1


class TestSparseMomentumOpNesterov(TestSparseMomentumOp):
    def init_use_nesterov(self):
        self.use_nesterov = True


class TestSparseMomentumOpMultiPrecision(TestSparseMomentumOp):
    def init_dtype(self):
        self.dtype = np.float16
        self.index_dtype = np.int32

    def init_multi_precision(self):
        self.multi_precision = True

    def init_use_nesterov(self):
        self.use_nesterov = True


class TestSparseMomentumOpMultiPrecision1(TestSparseMomentumOp):
    def init_dtype(self):
        self.dtype = np.float16
        self.index_dtype = np.int64

    def init_multi_precision(self):
        self.multi_precision = True

    def init_use_nesterov(self):
        self.use_nesterov = True


class TestSparseMomentumOpMultiPrecision2(TestSparseMomentumOp):
    def init_dtype(self):
        self.dtype = np.float16
        self.index_dtype = np.int32

    def init_multi_precision(self):
        self.multi_precision = True

    def init_use_nesterov(self):
        self.use_nesterov = False


class TestSparseMomentumOpMultiPrecision3(TestSparseMomentumOp):
    def init_dtype(self):
        self.dtype = np.float16
        self.index_dtype = np.int64

    def init_multi_precision(self):
        self.multi_precision = True

    def init_use_nesterov(self):
        self.use_nesterov = False