amp_base_models.py 8.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2023 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.

15 16
import unittest

17 18 19 20
import numpy as np

import paddle
from paddle import nn
21
from paddle.fluid import core
22 23 24 25 26

_fixed_add_param = np.random.random(size=[16, 16]).astype("float32")


def _build_optimizer(
27 28 29 30 31
    use_amp,
    amp_dtype="float16",
    amp_level="O1",
    amp_lists=None,
    use_grad_clip=False,
32
    use_promote=False,
33 34 35 36 37 38 39 40 41 42 43 44 45 46
):
    if use_grad_clip:
        grad_clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0)
    else:
        grad_clip = None
    optimizer = paddle.optimizer.AdamW(
        learning_rate=0.01,
        grad_clip=grad_clip,
        beta1=0.78,
        beta2=0.836,
        epsilon=1e-4,
        weight_decay=0.01,
    )
    if use_amp:
47
        optimizer = paddle.static.amp.decorate(
48 49 50 51 52
            optimizer,
            amp_lists,
            level=amp_level,
            dtype=amp_dtype,
            use_promote=use_promote,
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
        )
    return optimizer


class SimpleAddNet(nn.Layer):
    def __init__(self, dtype):
        super().__init__()
        global _fixed_add_param
        self.weight = paddle.create_parameter(
            name="add_w",
            shape=[16, 16],
            dtype=dtype,
            attr=paddle.ParamAttr(
                initializer=paddle.nn.initializer.Assign(_fixed_add_param)
            ),
        )

    def forward(self, x):
        return x + self.weight


74 75 76
def build_add_model(
    use_amp, amp_dtype="float16", amp_level="O1", use_promote=False
):
77 78 79 80 81 82 83 84 85 86 87 88 89 90
    main_program = paddle.static.Program()
    startup_program = paddle.static.Program()
    with paddle.utils.unique_name.guard():
        with paddle.static.program_guard(main_program, startup_program):
            x_dtype = "float32"
            if use_amp and amp_level == "O2":
                if amp_dtype == "bfloat16":
                    x_dtype = "uint16"
                elif amp_dtype == "float16":
                    x_dtype = "float16"
            model = SimpleAddNet(x_dtype)
            x = paddle.static.data(name='input', shape=[16, 16], dtype=x_dtype)
            out = model(x)
            loss = paddle.mean(out)
91 92 93 94 95 96 97 98 99 100

            if use_amp:
                amp_lists = paddle.static.amp.AutoMixedPrecisionLists(
                    custom_white_list=["elementwise_add"],
                    custom_black_list=["reduce_mean"],
                    dtype=amp_dtype,
                )
            else:
                amp_lists = None
            optimizer = _build_optimizer(
101 102 103 104 105
                use_amp,
                amp_dtype,
                amp_level,
                amp_lists,
                use_promote=use_promote,
106
            )
107 108 109 110 111 112 113 114 115 116
            optimizer.minimize(loss)
    feed_vars = [x]
    fetch_vars = [loss]
    return main_program, startup_program, optimizer, feed_vars, fetch_vars


class SimpleConvNet(nn.Layer):
    def __init__(self):
        super().__init__()
        self.conv = nn.Conv2D(in_channels=1, out_channels=6, kernel_size=3)
117
        self.linear = nn.Linear(in_features=96, out_features=4)
118 119 120 121

    def forward(self, x):
        out = self.conv(x)
        out = nn.functional.relu(out)
122
        out = out.flatten(start_axis=1, stop_axis=3)
123 124 125 126 127
        out = self.linear(out)
        out = nn.functional.softmax(out)
        return out


128 129 130
def build_conv_model(
    use_amp, amp_dtype="float16", amp_level="O1", use_promote=False
):
131 132 133 134 135 136
    main_program = paddle.static.Program()
    startup_program = paddle.static.Program()
    with paddle.utils.unique_name.guard():
        with paddle.static.program_guard(main_program, startup_program):
            model = SimpleConvNet()
            x = paddle.static.data(
137
                name='input', shape=[None, 1, 6, 6], dtype='float32'
138 139 140
            )
            out = model(x)
            loss = paddle.mean(out)
141 142 143
            optimizer = _build_optimizer(
                use_amp, amp_dtype, amp_level, use_promote=use_promote
            )
144
            optimizer.minimize(loss)
145 146 147
    feed_vars = [x]
    fetch_vars = [loss]
    return main_program, startup_program, optimizer, feed_vars, fetch_vars
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168


class SimpleEmbeddingNet(nn.Layer):
    def __init__(self):
        super().__init__()
        self.vocab_size = 128
        self.hidden_size = 16
        self.vocab_size = 128
        self.hidden_size = 16
        self.embedding = nn.Embedding(self.vocab_size, self.hidden_size)
        self.linear = nn.Linear(in_features=16, out_features=10)

    def forward(self, x):
        out = self.embedding(x)
        scale = paddle.full(shape=[1], fill_value=2, dtype="int64")
        out = paddle.multiply(out, scale.astype("float32"))
        out = self.linear(out)
        out = nn.functional.dropout(out, p=0.2)
        return out


169 170 171
def build_embedding_model(
    use_amp, amp_dtype="float16", amp_level="O1", use_promote=False
):
172 173 174 175 176 177 178 179
    main_program = paddle.static.Program()
    startup_program = paddle.static.Program()
    with paddle.utils.unique_name.guard():
        with paddle.static.program_guard(main_program, startup_program):
            model = SimpleEmbeddingNet()
            x = paddle.static.data(name='x', shape=[None, 32], dtype='int64')
            out = model(x)
            loss = paddle.mean(out)
180
            optimizer = _build_optimizer(
181 182 183 184 185 186
                use_amp,
                amp_dtype,
                amp_level,
                None,
                True,
                use_promote=use_promote,
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
            optimizer.minimize(loss)
    return main_program, startup_program


class SimpleWhileNet(nn.Layer):
    def __init__(self):
        super().__init__()
        self.linear = paddle.nn.Linear(16, 10)

    def forward(self, x):
        def cond(i, loop_len, x, result):
            return i < loop_len

        def body(i, loop_len, x, result):
            result = self.linear(x)
            paddle.increment(i)
            return [i, loop_len, x, result]

        i = paddle.zeros(shape=[1], dtype='int64')
        loop_len = paddle.ones(shape=[1], dtype='int64')
        result = paddle.zeros(
            shape=x.shape[:-1] + self.linear.weight.shape[-1:], dtype="float32"
        )
        result.stop_gradient = False
        _, _, _, results = paddle.static.nn.while_loop(
            cond, body, [i, loop_len, x, result]
        )
        return results


def build_while_model():
    main_program = paddle.static.Program()
    startup_program = paddle.static.Program()
    with paddle.utils.unique_name.guard():
        with paddle.static.program_guard(main_program, startup_program):
            model = SimpleWhileNet()
            x = paddle.static.data(name='x', shape=[32, 16], dtype='float32')
            out = model(x)
            loss = paddle.mean(out)
    return main_program, startup_program
228 229 230 231 232 233 234 235 236 237


@unittest.skipIf(
    not core.is_compiled_with_cuda(),
    "core is not complied with CUDA and not support amp.",
)
class AmpTestBase(unittest.TestCase):
    def setUp(self):
        self.amp_dtype = None
        self.amp_level = None
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

    def _check_op_calls(
        self, op_stats_dict, expected_bf16_calls={}, expected_fp16_calls={}
    ):
        for op_type, value in expected_bf16_calls.items():
            self.assertEqual(
                op_stats_dict[op_type].bf16_calls,
                value,
                f"The number of bf16 calls of operator < {op_type} > is expected to be {value}, but recieved {op_stats_dict[op_type].bf16_calls}.",
            )
        for op_type, value in expected_fp16_calls.items():
            self.assertEqual(
                op_stats_dict[op_type].fp16_calls,
                value,
                f"The number of fp16 calls of operator < {op_type} > is expected to be {value}, but recieved {op_stats_dict[op_type].fp16_calls}.",
            )

    def run_program(
        self,
        main_program,
        startup_program,
        optimizer,
        feed_vars,
        fetch_vars,
        place,
        exe,
        x_np,
        max_iters,
        level,
    ):
        losses = []
        scope = paddle.static.Scope()
        with paddle.static.scope_guard(scope):
            exe.run(startup_program)
            if level == 'O2':
                optimizer.amp_init(place)
            for iter_id in range(max_iters):
                results = exe.run(
                    program=main_program,
                    feed={feed_vars[0].name: x_np},
                    fetch_list=fetch_vars,
                )
                print(f"-- [BF16 {level}] iter={iter_id}, loss={results[0]}")
                losses.append(results[0])
        return losses