offload_helper.py 21.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2020 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
from ..common import is_optimizer_op, OP_ROLE_KEY, OpRole, is_update_op
16 17
from paddle.framework import core
from paddle.utils import unique_name
18

19 20
__all__ = []

21

W
WangXi 已提交
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
class PlaceType:
    # sync with memcpy op, maybe not a good design
    CPU = 0
    CUDA = 1
    CUDA_PINNED = 2
    XPU = 3  # unsupport for now
    NPU = 4
    NPU_PINNED = 5

    @staticmethod
    def default_device():
        if core.is_compiled_with_cuda():
            return PlaceType.CUDA
        elif core.is_compiled_with_npu():
            return PlaceType.NPU
        return PlaceType.CPU

    @staticmethod
    def default_pinned():
        if core.is_compiled_with_cuda():
            return PlaceType.CUDA_PINNED
        elif core.is_compiled_with_npu():
            return PlaceType.NPU_PINNED
        return PlaceType.CPU


48
class OffloadHelper:
49
    cpu_place_type = 0
W
WangXi 已提交
50 51
    cuda_place_type = PlaceType.default_device()
    cuda_pinned_place_type = PlaceType.default_pinned()
52

53 54 55
    def __init__(self, mp_ring_id=None, dp_ring_id=None):
        self.mp_ring_id = mp_ring_id
        self.dp_ring_id = dp_ring_id
56 57 58 59

    def _insert_cast_op(self, block, idx, src_name, dst_name):
        src_var = block.var(src_name)
        if not block.has_var(dst_name):
60 61 62 63 64 65
            block.create_var(
                name=dst_name,
                shape=src_var.shape,
                dtype=core.VarDesc.VarType.FP16,
                persistable=True,
            )
66 67
        dst_var = block.var(dst_name)
        assert dst_var.dtype == core.VarDesc.VarType.FP16
68 69 70 71 72 73 74 75 76 77 78
        block._insert_op_without_sync(
            idx,
            type='cast',
            inputs={'X': src_var},
            outputs={'Out': dst_var},
            attrs={
                'in_dtype': src_var.dtype,
                'out_dtype': dst_var.dtype,
                OP_ROLE_KEY: OpRole.Optimize,
            },
        )
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93
    def _insert_broadcast_op(self, block, idx, param_name):
        rings = []

        if self.dp_ring_id is not None:
            rings.append(self.dp_ring_id)

        # need sync non distributed param in mp group
        if self.mp_ring_id is not None:
            param = block.var(param_name)
            if not hasattr(param, 'is_distributed') or not param.is_distributed:
                rings.append(self.mp_ring_id)

        # the insert op order is: mp, dp
        for ring in rings:
94 95 96 97 98 99 100 101 102 103 104 105
            block._insert_op_without_sync(
                idx,
                type="c_broadcast",
                inputs={'X': param_name},
                outputs={'Out': param_name},
                attrs={
                    'ring_id': ring,
                    'root': 0,
                    'use_calc_stream': True,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
106

107 108 109
    def _insert_memcpy_op(self, block, idx, src_name, dst_name, dst_place_type):
        src_var = block.var(src_name)
        dst_var = block.var(dst_name)
110 111 112 113 114 115 116 117 118 119
        block._insert_op_without_sync(
            idx,
            type='memcpy',
            inputs={'X': src_var},
            outputs={'Out': dst_var},
            attrs={
                'dst_place_type': dst_place_type,
                OP_ROLE_KEY: OpRole.Optimize,
            },
        )
120 121

    def _insert_fetch_op(self, block, idx, src_name, dst_name):
122 123 124
        self._insert_memcpy_op(
            block, idx, src_name, dst_name, OffloadHelper.cuda_place_type
        )
125 126

    def _insert_offload_op(self, block, idx, src_name, dst_name):
127 128 129
        self._insert_memcpy_op(
            block, idx, src_name, dst_name, OffloadHelper.cuda_pinned_place_type
        )
130 131 132 133 134 135 136 137

    def _get_offload_var_name(self, name):
        return unique_name.generate(name + '@offload')

    def _create_offload_var(self, var_name, offload_var_name, blocks):
        for block in blocks:
            var = block.var(var_name)
            var.persistable = False
138 139 140 141 142 143
            offload_var = block.create_var(
                name=offload_var_name,
                shape=var.shape,
                dtype=var.dtype,
                persistable=True,
            )
144

145
    def offload_fp32param(self, block, startup_block, offload=True):
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
        """
        (p_fp16) = cast(p)
        (p_fp16_recompute) = cast(p)
        (pout,) = adam(p)
        ===========================>
        rename(p_fp16_recompute, p_fp16)

        (p,) = prefetch(p@offload)
        (pout,) = adam(p)
        (p_fp16) = cast(p)
        (p@offload) = memcpy(p)
        """
        param_to_idx = dict()
        param_to_fp16 = dict()
        # recompute_var which need rename to fp16_param
        fp16_param_to_recompute = dict()
        recompute_to_fp16 = dict()

        def remove_param(input_name):
            param_to_idx.pop(input_name)
            if input_name in param_to_fp16:
                fp16_param = param_to_fp16.pop(input_name)
                if fp16_param in fp16_param_to_recompute:
                    recompute = fp16_param_to_recompute.pop(fp16_param)
                    recompute_to_fp16.pop(recompute)

        # step1: record param
        for idx, op in reversed(list(enumerate(block.ops))):
174
            if is_update_op(op):
175 176 177
                param = op.desc.input("Param")[0]
                param_to_idx[param] = idx

178 179
        # step2: remove param which can't offload and
        #        record param->fp16param, fp16param->recompute_var
180 181 182
        for idx, op in enumerate(block.ops):
            if is_optimizer_op(op):
                break
183 184 185
            # TODO (Yuang Liu): tmp solution for fuse_grad_merge + optimize_cast
            if not offload and op.type == 'coalesce_tensor':
                continue
186 187 188 189
            for input_name in op.desc.input_arg_names():
                if input_name not in param_to_idx:
                    continue

190
                # param which will be used by fp32 op
191 192 193 194 195 196 197 198 199 200 201 202 203
                if op.type != 'cast':
                    remove_param(input_name)
                    continue

                # param is only used by cast op,
                # which to cast fp32_param to fp16_param
                output_name = op.output_arg_names[0]
                if 'cast_fp16' not in output_name:
                    remove_param(input_name)
                    continue

                if 'subprog' not in output_name:
                    assert output_name == input_name + '.cast_fp16'
204 205 206
                    assert (
                        input_name not in param_to_fp16
                    ), "There must be only one cast op from fp32 param to fp16 param."
207 208 209
                    param_to_fp16[input_name] = output_name
                else:
                    # fp16-->recompute_var
210 211 212
                    assert (
                        input_name in param_to_fp16
                    ), "param must first be cast to fp16"
213 214 215 216 217 218 219 220
                    fp16_param = param_to_fp16[input_name]
                    fp16_param_to_recompute[fp16_param] = output_name
                    recompute_to_fp16[output_name] = fp16_param

        param_name_to_offload_name = dict()
        # step3: main_block add offload, cast op
        # change recompute to fp16, remove cast(param) to fp16
        for idx, op in reversed(list(enumerate(block.ops))):
221
            if is_update_op(op):
222
                param = op.desc.input("Param")[0]
223 224
                if param not in param_to_idx:
                    continue
225 226 227
                # step3.1: create offload_var
                offload_var_name = self._get_offload_var_name(param)
                param_name_to_offload_name[param] = offload_var_name
228
                if offload:
229 230 231
                    self._create_offload_var(
                        param, offload_var_name, [block, startup_block]
                    )
232

233
                    # step3.2: insert cast op and offload op
234 235 236
                    self._insert_offload_op(
                        block, idx + 1, param, offload_var_name
                    )
237 238 239 240 241

                assert param in param_to_fp16
                fp16_param_name = param_to_fp16[param]
                fp16_param_var = block.var(fp16_param_name)
                fp16_param_var.persistable = True
242 243 244
                self._insert_cast_op(
                    block, idx + 1, param, param_to_fp16[param]
                )
245

246 247 248
                if offload:
                    # step3.3: insert fetch op
                    self._insert_fetch_op(block, idx, offload_var_name, param)
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
                continue

            # step3.4: remove cast op
            if op.type == 'cast':
                input_name = op.desc.input_arg_names()[0]
                if input_name in param_to_idx:
                    block._remove_op(idx, sync=False)
                    continue

            # step3.5: change recompute_param to fp16_param
            for input_name in op.desc.input_arg_names():
                if input_name in recompute_to_fp16:
                    op._rename_input(input_name, recompute_to_fp16[input_name])
            for output_name in op.desc.output_arg_names():
                if output_name in recompute_to_fp16:
264 265 266
                    op._rename_output(
                        output_name, recompute_to_fp16[output_name]
                    )
267 268 269 270 271 272 273

        # step4: remove recompute_param
        for name in recompute_to_fp16.keys():
            block._remove_var(name, sync=False)

        # step5: startup_block add offload
        visited_vars = set()
274 275
        # FIXME(wangxi): should insert in idx, need move comm init to the head.
        insert_idx = len(startup_block.ops)
276 277 278 279 280 281 282
        for idx, op in reversed(list(enumerate(startup_block.ops))):
            for out_name in op.output_arg_names:
                if out_name in visited_vars:
                    continue

                if out_name in param_name_to_offload_name:
                    var_name = out_name
283 284
                    if offload:
                        offload_var_name = param_name_to_offload_name[var_name]
285 286 287 288 289 290 291 292 293 294 295 296
                        self._insert_offload_op(
                            startup_block,
                            insert_idx,
                            var_name,
                            offload_var_name,
                        )
                    self._insert_cast_op(
                        startup_block,
                        insert_idx,
                        var_name,
                        param_to_fp16[var_name],
                    )
297
                    # NOTE(wangxi): cast and offload should insert after broadcast param.
298
                    # the insert op order is: {mp, dp}broadcast, cast, offload
299 300 301
                    self._insert_broadcast_op(
                        startup_block, insert_idx, var_name
                    )
302 303 304 305 306 307

                visited_vars.add(out_name)

        block._sync_with_cpp()
        startup_block._sync_with_cpp()

308 309 310 311 312 313 314 315 316 317 318 319 320
    def cast_fp32param_in_optimize(self, block, startup_block):
        """
        (p_fp16) = cast(p)
        (p_fp16_recompute) = cast(p)
        (pout,) = adam(p)
        ===========================>
        rename(p_fp16_recompute, p_fp16)

        (pout,) = adam(p)
        (p_fp16) = cast(p)
        """
        self.offload_fp32param(block, startup_block, offload=False)

321 322 323 324 325 326 327 328 329 330 331 332 333 334
    def offload(self, block, startup_block):
        """
        (m1, m2) = prefetch(m1@offload, m2@offload)
        (m1out, m2out, pout) = adam(m1, m2, p)
        (m1@offload, m2@offload) = memcpy(m1, m2)
        """
        vars_name_to_offload_name = dict()

        # main_block add offload
        for idx, op in reversed(list(enumerate(block.ops))):
            if not is_optimizer_op(op):
                break

            vars_name = []
335
            if op.type == "adam" or op.type == "adamw":
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
                # {Moment1Out = [''], Moment2Out = [''], ParamOut = ['']} =
                # adam(inputs={Moment1 = [''], Moment2 = [''], Param = ['']})
                vars_name.append(op.desc.input("Moment1")[0])
                vars_name.append(op.desc.input("Moment2")[0])
            elif op.type == 'momentum':
                pass
            elif op.type == 'lars':
                pass
            elif op.type == 'lamb':
                pass

            # step1: create and init offload_var
            for var_name in vars_name:
                assert var_name not in vars_name_to_offload_name

                offload_var_name = self._get_offload_var_name(var_name)
                vars_name_to_offload_name[var_name] = offload_var_name

354 355 356
                self._create_offload_var(
                    var_name, offload_var_name, [block, startup_block]
                )
357 358 359 360

            # step2: insert offload op
            for var_name in vars_name:
                offload_var_name = vars_name_to_offload_name[var_name]
361 362 363
                self._insert_offload_op(
                    block, idx + 1, var_name, offload_var_name
                )
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

            # step3: insert fetch op
            for var_name in vars_name:
                offload_var_name = vars_name_to_offload_name[var_name]
                self._insert_fetch_op(block, idx, offload_var_name, var_name)

        # startup_block add offload
        visited_vars = set()
        for idx, op in reversed(list(enumerate(startup_block.ops))):
            for out_name in op.output_arg_names:
                if out_name in visited_vars:
                    continue

                if out_name in vars_name_to_offload_name:
                    var_name = out_name
                    offload_var_name = vars_name_to_offload_name[var_name]
                    # insert offload op after var is generated
381 382 383
                    self._insert_offload_op(
                        startup_block, idx + 1, var_name, offload_var_name
                    )
384 385 386 387
                visited_vars.add(out_name)

        block._sync_with_cpp()
        startup_block._sync_with_cpp()
388

389 390 391
    def opt_sharding_cast_fp32param(
        self, block, startup_block, params, offload=False
    ):
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        """
        (p_fp16) = cast(p)
        (p_fp16_recompute) = cast(p)
        (pout,) = adam(p)
        ===========================>
        rename(p_fp16_recompute, p_fp16)

        (pout,) = adam(p)
        (p_fp16) = cast(p)
        broadcast(p_fp16)
        """
        global_params = set()
        local_params = set()
        param_to_fp16 = dict()
        # recompute_var which need rename to fp16_param
        fp16_param_to_recompute = dict()
        recompute_to_fp16 = dict()

        def remove_param(input_name):
            global_params.remove(input_name)
            if input_name in local_params:
                local_params.remove(input_name)
            if input_name in param_to_fp16:
                fp16_param = param_to_fp16.pop(input_name)
                if fp16_param in fp16_param_to_recompute:
                    recompute = fp16_param_to_recompute.pop(fp16_param)
                    recompute_to_fp16.pop(recompute)

        # step1: record param
        global_params = set(params)
        for idx, op in reversed(list(enumerate(block.ops))):
            if is_update_op(op):
                param = op.desc.input("Param")[0]
                local_params.add(param)

        # step2: remove param which can't offload and
        #        record param->fp16param, fp16param->recompute_var
        for idx, op in enumerate(block.ops):
            if is_optimizer_op(op):
                break
            # TODO (Yuang Liu): tmp solution for fuse_grad_merge + optimize_cast
            if op.type == 'coalesce_tensor':
                continue
            for input_name in op.desc.input_arg_names():
                if input_name not in global_params:
                    continue

                # param which will be used by fp32 op
                if op.type != 'cast':
                    remove_param(input_name)
                    continue

                # param is only used by cast op,
                # which to cast fp32_param to fp16_param
                output_name = op.output_arg_names[0]
                if 'cast_fp16' not in output_name:
                    remove_param(input_name)
                    continue

                if 'subprog' not in output_name:
                    assert output_name == input_name + '.cast_fp16'
453 454 455
                    assert (
                        input_name not in param_to_fp16
                    ), "There must be only one cast op from fp32 param to fp16 param."
456 457 458
                    param_to_fp16[input_name] = output_name
                else:
                    # fp16-->recompute_var
459 460 461
                    assert (
                        input_name in param_to_fp16
                    ), "param must first be cast to fp16"
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
                    fp16_param = param_to_fp16[input_name]
                    fp16_param_to_recompute[fp16_param] = output_name
                    recompute_to_fp16[output_name] = fp16_param

        param_name_to_offload_name = dict()
        # step3: main_block add offload, cast op
        # change recompute to fp16, remove cast(param) to fp16
        for idx, op in reversed(list(enumerate(block.ops))):
            if is_update_op(op):
                param = op.desc.input("Param")[0]
                if param not in global_params:
                    continue
                # step3.1: create offload_var
                offload_var_name = self._get_offload_var_name(param)
                param_name_to_offload_name[param] = offload_var_name
                if offload:
478 479 480
                    self._create_offload_var(
                        param, offload_var_name, [block, startup_block]
                    )
481 482

                    # step3.2: insert cast op and offload op
483 484 485
                    self._insert_offload_op(
                        block, idx + 1, param, offload_var_name
                    )
486 487 488 489 490

                assert param in param_to_fp16
                fp16_param_name = param_to_fp16[param]
                fp16_param_var = block.var(fp16_param_name)
                fp16_param_var.persistable = True
491 492 493
                self._insert_cast_op(
                    block, idx + 1, param, param_to_fp16[param]
                )
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

                if offload:
                    # step3.3: insert fetch op
                    self._insert_fetch_op(block, idx, offload_var_name, param)

                continue

            # step3.4: remove cast op
            if op.type == 'cast':
                input_name = op.desc.input_arg_names()[0]
                if input_name in global_params:
                    block._remove_op(idx, sync=False)
                    continue

            # step3.5: change recompute_param to fp16_param
            for input_name in op.desc.input_arg_names():
                if input_name in recompute_to_fp16:
                    op._rename_input(input_name, recompute_to_fp16[input_name])
            for output_name in op.desc.output_arg_names():
                if output_name in recompute_to_fp16:
514 515 516
                    op._rename_output(
                        output_name, recompute_to_fp16[output_name]
                    )
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

        # step4: remove recompute_param
        for name in recompute_to_fp16.keys():
            block._remove_var(name, sync=False)

        # step5: remove fp32 param which not need
        for idx, op in enumerate(block.ops):
            if op.type not in ['coalesce_tensor', 'c_broadcast']:
                continue
            for input_name in op.desc.input_arg_names():
                if input_name in param_to_fp16:
                    op._rename_input(input_name, param_to_fp16[input_name])
            for output_name in op.desc.output_arg_names():
                if output_name in param_to_fp16:
                    op._rename_output(output_name, param_to_fp16[output_name])

        for param in global_params:
            assert param in param_to_fp16
            fp16_param_name = param_to_fp16[param]
            fp16_param_var = block.var(fp16_param_name)
            fp16_param_var.persistable = True

            if param not in local_params:
                block._remove_var(param, sync=False)

        # step6: startup_block add offload
        visited_vars = set()
        insert_idx = len(startup_block.ops)
        for idx, op in reversed(list(enumerate(startup_block.ops))):
            for out_name in op.output_arg_names:
547 548
                if out_name in visited_vars:
                    continue
549 550 551 552 553

                if out_name in param_to_fp16:
                    var_name = out_name
                    if offload:
                        self._insert_offload_op(
554 555 556 557 558 559 560 561 562 563 564 565
                            startup_block,
                            idx + 1,
                            var_name,
                            param_name_to_offload_name[var_name],
                        )

                    self._insert_cast_op(
                        startup_block,
                        insert_idx,
                        var_name,
                        param_to_fp16[var_name],
                    )
566

567 568
                    # NOTE(wangxi): cast and offload should insert after broadcast param.
                    # the insert op order is: {mp, dp}broadcast, cast, offload
569 570 571
                    self._insert_broadcast_op(
                        startup_block, insert_idx, var_name
                    )
572 573 574 575 576 577 578 579 580

                    if var_name not in local_params:
                        param = startup_block.var(out_name)
                        param.persistable = False

                visited_vars.add(out_name)

        block._sync_with_cpp()
        startup_block._sync_with_cpp()