test_lamb_op.py 10.4 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2019 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.

import unittest
import numpy as np
from op_test import OpTest
18
import paddle
Y
Yibing Liu 已提交
19 20 21
from paddle.fluid import core
from paddle.fluid.op import Operator

22 23
paddle.enable_static()

Y
Yibing Liu 已提交
24 25

class TestLambOp1(OpTest):
26

Y
Yibing Liu 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    def set_attrs(self):
        self.attrs = {
            'epsilon': 1e-4,
            'beta1': 0.78,
            'beta2': 0.836,
            'weight_decay': 0.01
        }

    def setUp(self):
        '''Test Lamb Op with supplied attributes
        '''
        self.op_type = "lamb"
        param = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        grad = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment1 = np.random.uniform(-1, 1, (102, 105)).astype("float32")
        moment2 = np.random.random((102, 105)).astype("float32")

        learning_rate = 0.001
        self.set_attrs()
46 47
        beta1_pow = self.attrs['beta1']
        beta2_pow = self.attrs['beta2']
Y
Yibing Liu 已提交
48 49 50 51 52 53 54 55 56 57 58 59

        self.inputs = {
            'Param': param,
            'Grad': grad,
            'Moment1': moment1,
            'Moment2': moment2,
            'LearningRate': np.array([learning_rate]).astype("float32"),
            'Beta1Pow': np.array([beta1_pow]).astype("float32"),
            'Beta2Pow': np.array([beta2_pow]).astype("float32")
        }


60 61
        param_out, moment1_out, moment2_out, \
            beta1_pow_out, beta2_pow_out = lamb_step(self.inputs, self.attrs)
Y
Yibing Liu 已提交
62 63 64 65

        self.outputs = {
            'Moment1Out': moment1_out,
            'Moment2Out': moment2_out,
66 67 68
            'ParamOut': param_out,
            'Beta1PowOut': beta1_pow_out,
            'Beta2PowOut': beta2_pow_out
Y
Yibing Liu 已提交
69 70 71 72 73 74 75
        }

    def test_check_output(self):
        self.check_output()


class TestLambOp2(TestLambOp1):
76

Y
Yibing Liu 已提交
77 78 79 80 81 82 83 84 85 86
    def set_attrs(self):
        self.attrs = {
            'epsilon': 1e-8,
            'beta1': 0.9,
            'beta2': 0.999,
            'weight_decay': 0.01
        }


class TestLambOpMultipleSteps(TestLambOp1):
87

Y
Yibing Liu 已提交
88 89 90 91 92 93 94 95 96 97
    def set_attrs(self):
        self.attrs = {
            'epsilon': 1e-8,
            'beta1': 0.9,
            'beta2': 0.999,
            'weight_decay': 0.01
        }
        self.num_steps = 10

    def test_check_output(self):
98 99 100
        for i in range(self.num_steps):
            param_out, moment1_out, moment2_out, \
                beta1_pow_out, beta2_pow_out = lamb_step(self.inputs, self.attrs)
Y
Yibing Liu 已提交
101 102 103 104

            self.outputs = {
                'Moment1Out': moment1_out,
                'Moment2Out': moment2_out,
105 106 107
                'ParamOut': param_out,
                'Beta1PowOut': beta1_pow_out,
                'Beta2PowOut': beta2_pow_out
Y
Yibing Liu 已提交
108 109 110 111 112 113 114 115 116 117 118
            }

            # Verify output for this step
            self.check_output()

            # Output of this step becomes input for next step
            self.inputs['Param'] = param_out
            self.inputs['Moment1'] = moment1_out
            self.inputs['Moment2'] = moment2_out

            # Update powers of Beta1 and Beta2 for next time step
119 120
            self.inputs['Beta1Pow'] = beta1_pow_out
            self.inputs['Beta2Pow'] = beta2_pow_out
Y
Yibing Liu 已提交
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

            # Randomize gradient for next step
            self.inputs['Grad'] = np.random.uniform(
                -1, 1, (102, 105)).astype("float32")


def lamb_step(inputs, attributes):
    '''
    Simulate one step of the lamb optimizer
    :param inputs: dict of inputs
    :param attributes: dict of attributes
    :return tuple: tuple of output param, moment1, moment2,
    beta1 power accumulator and beta2 power accumulator
    '''
    param = inputs['Param']
    grad = inputs['Grad']
    moment1 = inputs['Moment1']
    moment2 = inputs['Moment2']
    lr = inputs['LearningRate']
    beta1_pow = inputs['Beta1Pow']
    beta2_pow = inputs['Beta2Pow']

    beta1 = attributes['beta1']
    beta2 = attributes['beta2']
    epsilon = attributes['epsilon']
    weight_decay = attributes['weight_decay']

    moment1_out = beta1 * moment1 + (1 - beta1) * grad
    moment2_out = beta2 * moment2 + (1 - beta2) * np.square(grad)

151 152 153
    moment1_unbiased = moment1_out / (1 - beta1_pow)
    moment2_unbiased = moment2_out / (1 - beta2_pow)

Y
Yibing Liu 已提交
154
    r_1 = np.linalg.norm(param)
155 156 157
    r_2 = np.linalg.norm(moment1_unbiased /
                         (np.sqrt(moment2_unbiased) + epsilon) +
                         weight_decay * param)
Y
Yibing Liu 已提交
158 159
    lr_t = lr * r_1 / r_2

160 161 162
    param_out = param - lr_t * (moment1_unbiased /
                                (np.sqrt(moment2_unbiased) + epsilon) +
                                weight_decay * param)
163 164 165 166 167

    beta1_pow_out = beta1_pow * beta1
    beta2_pow_out = beta2_pow * beta2

    return param_out, moment1_out, moment2_out, beta1_pow_out, beta2_pow_out
Y
Yibing Liu 已提交
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


def lamb_step_sparse(inputs, attributes, height, rows, row_numel, np_grad):
    '''
    Simulate one step of the lamb optimizer
    :param inputs: dict of inputs
    :param attributes: dict of attributes
    :return tuple: tuple of output param, moment1, moment2,
    beta1 power accumulator and beta2 power accumulator
    '''
    param = inputs['Param']
    # grad = inputs['Grad']
    moment1 = inputs['Moment1']
    moment2 = inputs['Moment2']
    lr = inputs['LearningRate']
    beta1_pow = inputs['Beta1Pow']
    beta2_pow = inputs['Beta2Pow']

    beta1 = attributes['beta1']
    beta2 = attributes['beta2']
    epsilon = attributes['epsilon']
    weight_decay = attributes['weight_decay']

    moment1_out = np.zeros(shape=[height, row_numel])
    moment2_out = np.zeros(shape=[height, row_numel])
    param_out = np.zeros(shape=[height, row_numel])
194 195
    moment1_unbiased = np.zeros(shape=[height, row_numel])
    moment2_unbiased = np.zeros(shape=[height, row_numel])
Y
Yibing Liu 已提交
196 197

    def update_mom(row_id, update_value):
198 199
        moment1_out[row_id] = beta1 * moment1[row_id] + (1 -
                                                         beta1) * update_value
Y
Yibing Liu 已提交
200 201 202
        moment2_out[row_id] = beta2 * moment2[row_id] + (
            1 - beta2) * np.square(update_value)

203 204
        moment1_out[row_id] = beta1 * moment1[row_id] + (1 -
                                                         beta1) * update_value
Y
Yibing Liu 已提交
205 206 207 208 209
        moment2_out[row_id] = beta2 * moment2[row_id] + (
            1 - beta2) * np.square(update_value)

    def update_param():
        r_1 = np.linalg.norm(param)
Y
Yibing Liu 已提交
210
        r_2 = np.linalg.norm(moment1_out / (np.sqrt(moment2_out) + epsilon) +
Y
Yibing Liu 已提交
211 212 213
                             weight_decay * param)
        lr_t = lr * r_1 / r_2

214 215 216
        param_out = param - lr_t * (moment1_out /
                                    (np.sqrt(moment2_out) + epsilon) +
                                    weight_decay * param)
Y
Yibing Liu 已提交
217 218 219 220 221 222 223 224

    for row_id in range(param_out.shape[0]):
        update_value = np.zeros(np_grad[0].shape).astype("float32")
        if row_id in rows:
            update_value = np_grad[rows.index(row_id)]
        update_mom(row_id, update_value)

    update_param()
225 226
    beta1_pow_out = beta1_pow * beta1
    beta2_pow_out = beta2_pow * beta2
Y
Yibing Liu 已提交
227

228
    return param_out, moment1_out, moment2_out, beta1_pow_out, beta2_pow_out
Y
Yibing Liu 已提交
229 230 231


class TestSparseLambOp(unittest.TestCase):
232

Y
Yibing Liu 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246
    def setup(self, scope, place):
        beta1 = 0.78
        beta2 = 0.836
        epsilon = 1e-4

        height = 10
        rows = [0, 4, 7]
        self.rows = rows
        row_numel = 12
        self.row_numel = row_numel
        self.dense_inputs = {
            "Param": np.full((height, row_numel), 5.0).astype("float32"),
            "Moment1": np.full((height, row_numel), 5.0).astype("float32"),
            "Moment2": np.full((height, row_numel), 5.0).astype("float32"),
247 248
            'Beta1Pow': np.array([beta1]).astype("float32"),
            'Beta2Pow': np.array([beta2]).astype("float32"),
Y
Yibing Liu 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
            "LearningRate": np.full((1), 2.0).astype("float32")
        }
        self.init_output = np.full((height, row_numel), 0.0).astype("float32")
        self.attrs = {
            'epsilon': epsilon,
            'beta1': beta1,
            'beta2': beta2,
            'weight_decay': 0.05
        }

        grad_selected_rows = scope.var('Grad').get_selected_rows()
        grad_selected_rows.set_height(height)
        grad_selected_rows.set_rows(rows)
        np_array = np.ones((len(rows), row_numel)).astype("float32")
        np_array[0, 0] = 2.0
        np_array[2, 8] = 4.0

        grad_tensor = grad_selected_rows.get_tensor()
        grad_tensor.set(np_array, place)

        self.sparse_inputs = ["Grad"]

271
        param_out, mom1, mom2, beta1_pow_out, beta2_pow_out = lamb_step_sparse(
Y
Yibing Liu 已提交
272 273 274 275
            self.dense_inputs, self.attrs, height, rows, row_numel, np_array)
        self.outputs = {
            "ParamOut": param_out,
            "Moment1Out": mom1,
276 277 278
            "Moment2Out": mom2,
            'Beta1PowOut': beta1_pow_out,
            'Beta2PowOut': beta2_pow_out
Y
Yibing Liu 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        }

    def check_with_place(self, place):
        scope = core.Scope()
        self.setup(scope, place)

        op_args = dict()
        for key, np_array in self.dense_inputs.items():
            var = scope.var(key).get_tensor()
            var.set(np_array, place)
            op_args[key] = key
        for s in self.sparse_inputs:
            op_args[s] = s
        for s in self.outputs:
            var = scope.var(s).get_tensor()
            var.set(self.init_output, place)
            op_args[s] = s
        for k in self.attrs:
            op_args[k] = self.attrs[k]

        # create and run sgd operator
        lamb_op = Operator("lamb", **op_args)
        lamb_op.run(scope, place)

        for key, np_array in self.outputs.items():
            out_var = scope.var(key).get_tensor()
            actual = np.array(out_var)
            actual = actual.reshape([actual.size])
            np_array = np_array.reshape([np_array.size])

            for i in range(np_array.size):
                self.assertLess((actual[i] - np_array[i]), 0.00001)

    def test_sparse_lamb(self):
        places = [core.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(core.CUDAPlace(0))
        for place in places:
            self.check_with_place(place)


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