translated_layer.py 59.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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.

import os
import pickle
17

18 19
import numpy as np

20
import paddle
21 22
from paddle import _legacy_C_ops
from paddle.fluid import backward, core, framework, unique_name
23
from paddle.fluid.data_feeder import check_type
24
from paddle.fluid.dygraph.base import switch_to_static_graph
25
from paddle.fluid.framework import OpProtoHolder, _non_static_mode
26
from paddle.jit.dy2static.partial_program import (
27
    LazyInitialized,
28
    add_build_strategy_for,
29
)
30
from paddle.jit.dy2static.utils import construct_grad_names
31
from paddle.nn.layer import layers
32

J
JYChen 已提交
33
__all__ = []
34

35 36 37
INFER_MODEL_SUFFIX = ".pdmodel"
INFER_PARAMS_SUFFIX = ".pdiparams"
INFER_PARAMS_INFO_SUFFIX = ".pdiparams.info"
38
INFER_PROPERTY_SUFFIX = '.meta'
39

40 41 42
LOADED_VAR_SUFFIX = "load"
PARAMETER_NAME_PREFIX = "param"
BUFFER_NAME_PREFIX = "buffer"
43 44 45 46 47 48 49 50 51


def _load_program_desc(model_file_path):
    # 1. parse program desc
    with open(model_file_path, "rb") as f:
        program_desc_str = f.read()

    program_desc = core.ProgramDesc(program_desc_str)
    if not core._is_program_version_supported(program_desc._version()):
52 53 54
        raise ValueError(
            "Unsupported program version: %d\n" % program_desc._version()
        )
55 56 57 58
    return program_desc


def _is_persistable(var_desc):
59 60 61 62 63 64
    if (
        var_desc.type() == core.VarDesc.VarType.FEED_MINIBATCH
        or var_desc.type() == core.VarDesc.VarType.FETCH_LIST
        or var_desc.type() == core.VarDesc.VarType.READER
        or var_desc.type() == core.VarDesc.VarType.RAW
    ):
65 66 67 68 69 70 71
        return False
    return var_desc.persistable()


def _is_parameter(persistable_var_desc, program_desc):
    # 1. firstly, param should be input of op
    input_ops = []  # op can be repeated
72
    for block_idx in range(program_desc.num_blocks()):
73
        block = program_desc.block(block_idx)
74
        for op_idx in range(block.op_size()):
75 76 77 78 79
            op = block.op(op_idx)
            # NOTE: parameter is the input of a certain op
            if persistable_var_desc.name() in op.input_arg_names():
                input_ops.append(op)
    # 2. secondly, param should not be output of op or be same op's output
80
    for block_idx in range(program_desc.num_blocks()):
81
        block = program_desc.block(block_idx)
82
        for op_idx in range(block.op_size()):
83 84 85 86 87 88 89 90 91 92 93 94
            op = block.op(op_idx)
            if persistable_var_desc.name() in op.output_arg_names():
                # such as batch_norm_op
                if op in input_ops:
                    continue
                else:
                    return False
    return True


def _get_persistable_vars(program_desc):
    persistable_vars = []
95
    for i in range(program_desc.num_blocks()):
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        block = program_desc.block(i)
        persistable_vars.extend(list(filter(_is_persistable, block.all_vars())))
    return persistable_vars


def _get_persistable_var_names(program_desc):
    """
    Get all persistable variable names in ProgramDesc.
    """
    var_names = []
    persistable_vars = _get_persistable_vars(program_desc)
    for var in persistable_vars:
        var_names.append(var.name())
    return var_names


def _get_all_var_names(program_desc):
    all_var_names = set()
114
    for i in range(program_desc.num_blocks()):
115 116 117 118 119 120
        block = program_desc.block(i)
        for var in block.all_vars():
            all_var_names.add(var.name())
    return all_var_names


121
@switch_to_static_graph
122 123 124
def _append_loaded_suffix(name):
    """
    Append loaded suffix to the given variable name
125
    e.g. x ==> x.load_0, x.load_0 ==> x.load_0.load_0
126
    """
127 128 129
    suffix = LOADED_VAR_SUFFIX
    new_name = unique_name.generate_with_ignorable_key('.'.join((name, suffix)))
    return new_name
130 131


132 133 134
@switch_to_static_graph
def _generate_unique_var_name(prefix):
    return unique_name.generate_with_ignorable_key(prefix)
135 136 137


def _append_loaded_suffix_to_var(program_desc):
138
    suffix_varname_dict = {}
139 140 141 142
    persistable_vars = _get_persistable_vars(program_desc)
    for var_desc in persistable_vars:
        old_name = var_desc.name()
        new_name = _append_loaded_suffix(var_desc.name())
143
        suffix_varname_dict[new_name] = old_name
144
        var_desc.set_name(new_name)
145
        for block_idx in range(program_desc.num_blocks()):
146
            block = program_desc.block(block_idx)
147
            block._rename_var(old_name.encode(), new_name.encode())
148
            for op_idx in range(block.op_size()):
149 150 151
                op = block.op(op_idx)
                op._rename_input(old_name, new_name)
                op._rename_output(old_name, new_name)
152
    return suffix_varname_dict
153 154


155 156 157 158 159 160
@switch_to_static_graph
def _generate_unique_var_name_sync_with_main_program(prefix):
    return unique_name.generate(prefix)


def _get_loaded_var_new_old(program_desc, all_new_old_dict_all):
161
    new_old_dict = {}
162 163 164 165 166 167 168
    persistable_vars = _get_persistable_vars(program_desc)
    for var_desc in persistable_vars:
        name_new = var_desc.name()
        new_old_dict[name_new] = all_new_old_dict_all[name_new]
    return new_old_dict


W
WeiXin 已提交
169
def _rename_var_program_desc(program_desc, include=None, exclude=None):
170
    """
171 172 173 174 175 176 177 178
    Change the name of the loaded variables.Use 'unique_name.generate' to avoid duplication.
    It is used when loading multiple program during inference.

    e.g. linear_0.tmp_3 ==> linear_0.tmp_1, x ==> x_0. For double grad, x@GRAD ==> x_0@GRAD
    If 'include' is not `None`,variables in include and the corresponding
      double grad variables (if exist) are renamed.
    If 'exclude' is not `None`,variables that are in exclude and the
      corresponding double grad variables (if exist) are not renamed.
W
WeiXin 已提交
179 180 181 182 183

    Args:
        program_desc(ProgramDesc):the variables in it will be modified.
        include(List):list of names of variables.
        exclude(List):list of names of variables.
184 185 186 187 188

    Returns:
        tuple of (dict_rename_var_new_old, dict_rename_var_old_new)
        dict_rename_var_new_old is a dict mapping from new name to old name
        dict_rename_var_old_new is a dict mapping from old name to new name
189
    """
190 191
    dict_rename_var_old_new = {}
    dict_rename_var_new_old = {}
192
    old_names = []
193
    # Store all old names
194
    for b_idx in range(program_desc.num_blocks()):
195 196 197
        cur_block = program_desc.block(b_idx)
        for var in cur_block.all_vars():
            old_names.append(var.name())
198 199 200 201

    # Create dict_rename_var_new_old and dict_rename_var_old_new for non double
    # grad variables
    has_double_grad = False
202
    for b_idx in range(program_desc.num_blocks()):
203 204 205
        cur_block = program_desc.block(b_idx)
        for var_idx, var in enumerate(cur_block.all_vars()):
            name_old = var.name()
206 207
            is_double_grad_var = "@GRAD" in name_old
            has_double_grad = has_double_grad or is_double_grad_var
208 209 210 211 212
            should_rename = (
                (include is None or name_old in include)
                and (exclude is None or name_old not in exclude)
                and not is_double_grad_var
            )
W
WeiXin 已提交
213
            if should_rename:
214 215 216 217
                temp_name = name_old.split('_')
                if len(temp_name) > 1 and temp_name[-1].isnumeric():
                    temp_name = "_".join(temp_name[:-1])
                else:
W
WeiXin 已提交
218 219 220
                    temp_name = name_old
                while True:
                    name_new = _generate_unique_var_name_sync_with_main_program(
221 222 223 224 225 226
                        temp_name
                    )
                    if (
                        name_new
                        not in old_names[:var_idx] + old_names[var_idx + 1 :]
                    ):
W
WeiXin 已提交
227 228 229
                        break
            else:
                name_new = name_old
230
            if name_old != name_new:
231
                cur_block._rename_var(name_old.encode(), name_new.encode())
232 233 234 235 236 237 238 239
            if not is_double_grad_var:
                dict_rename_var_old_new[name_old] = name_new
                dict_rename_var_new_old[name_new] = name_old

    # Handle double grad names
    if has_double_grad:
        double_grad_rename_dict = {}
        for name_old in dict_rename_var_old_new:
240
            for b_idx in range(program_desc.num_blocks()):
241 242 243 244 245
                cur_block = program_desc.block(b_idx)
                for var_idx, var in enumerate(cur_block.all_vars()):
                    var_name = var.name()
                    if "@GRAD" in var_name and name_old in var_name:
                        new_var_name = var_name.replace(
246 247
                            name_old, dict_rename_var_old_new[name_old]
                        )
248 249 250
                        double_grad_rename_dict[var_name] = new_var_name
        for var_name in double_grad_rename_dict:
            dict_rename_var_old_new[var_name] = double_grad_rename_dict[
251 252
                var_name
            ]
253
            dict_rename_var_new_old[
254 255
                double_grad_rename_dict[var_name]
            ] = var_name
256 257

    # Rename on program desc
258
    for b_idx in range(program_desc.num_blocks()):
259
        cur_block = program_desc.block(b_idx)
260
        for op_idx in range(cur_block.op_size()):
261 262 263
            op = cur_block.op(op_idx)
            for input_arg_name in op.input_arg_names():
                if input_arg_name in dict_rename_var_old_new:
264 265 266 267
                    if (
                        input_arg_name
                        != dict_rename_var_old_new[input_arg_name]
                    ):
268 269
                        op._rename_input(
                            input_arg_name,
270 271
                            dict_rename_var_old_new[input_arg_name],
                        )
272
                        if cur_block.has_var(input_arg_name.encode()):
273
                            cur_block._rename_var(
274
                                input_arg_name.encode(),
275 276 277 278
                                dict_rename_var_old_new[
                                    input_arg_name
                                ].encode(),
                            )
279 280
            for output_arg_name in op.output_arg_names():
                if output_arg_name in dict_rename_var_old_new:
281 282 283 284
                    if (
                        output_arg_name
                        != dict_rename_var_old_new[output_arg_name]
                    ):
285 286
                        op._rename_output(
                            output_arg_name,
287 288
                            dict_rename_var_old_new[output_arg_name],
                        )
289
                        if cur_block.has_var(output_arg_name.encode()):
290
                            cur_block._rename_var(
291
                                output_arg_name.encode(),
292 293 294 295
                                dict_rename_var_old_new[
                                    output_arg_name
                                ].encode(),
                            )
296 297 298 299
    program_desc.flush()
    return dict_rename_var_new_old, dict_rename_var_old_new


300 301 302 303 304
@switch_to_static_graph
def _build_program_by_desc(program_desc):
    prog = framework.Program()
    prog.desc = program_desc
    prog.blocks = [
305
        framework.Block(prog, i) for i in range(prog.desc.num_blocks())
306 307 308 309 310 311 312
    ]
    prog._sync_with_cpp()
    return prog


def _change_is_test_status(program_desc, is_test):
    # change all `is_test` attributes
313
    for i in range(program_desc.num_blocks()):
314
        block = program_desc.block(i)
315
        for j in range(block.op_size()):
316 317 318 319 320
            op = block.op(j)
            if op.has_attr('is_test'):
                op._set_attr('is_test', is_test)


321
class _ProgramHolder:
322 323 324
    """
    Holds the execution information of a Program.

325 326
    _ProgramHolder is the execution unit of TranslatedLayer,
    if TranslatedLayer contains multiple _ProgramHolder,
327 328 329 330 331 332
    it can execute multiple methods

    _ProgramHolder is an internal concept.
    """

    def __init__(self, program_desc):
333
        super().__init__()
334

335
        # input, output, persistable, double_grads var info
336
        self._input_descs = []
337
        self._output_descs = []
338
        self._double_grad_descs = []
339
        self._persistable_names = []
340 341 342 343

        # execution scope
        self._inner_scope = core.Scope()

344 345
        # append suffix var name dict
        self._suffix_varname_dict = None
346 347 348 349
        # forward program
        self._infer_program_desc = self._preprocess(program_desc)
        # forward + backward program
        self._train_program_desc = self._append_backward_desc(
350 351
            self._infer_program_desc
        )
352
        self._grad_var_names = {}
353

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
    # forward:
    @switch_to_static_graph
    def _create_forward_train_program(self):
        whole_program = _build_program_by_desc(self._train_program_desc)
        end_op_index = self._infer_program_desc.block(0).op_size()
        if end_op_index > 0:
            return add_build_strategy_for(whole_program, 0, end_op_index)
        else:
            return whole_program

    @LazyInitialized
    def _forward_program_desc(self):
        return self._create_forward_train_program().desc

    # backward
    @switch_to_static_graph
    def _create_backward_train_program(self):
        whole_program = _build_program_by_desc(self._train_program_desc)
372
        start_op_index = self._infer_program_desc.block(0).op_size() + len(
373 374
            self._output_descs
        )
375
        end_op_index = whole_program.desc.block(0).op_size()
376 377 378 379
        if start_op_index < end_op_index:
            return add_build_strategy_for(
                whole_program, start_op_index, end_op_index
            )
380 381 382 383 384 385 386
        else:
            return paddle.static.Program()

    @LazyInitialized
    def _backward_program_desc(self):
        return self._create_backward_train_program().desc

387 388 389 390 391 392 393 394
    @property
    def infer_program(self):
        return self._infer_program_desc

    @property
    def train_program(self):
        return self._train_program_desc

395 396 397 398 399 400 401 402
    @property
    def forward_program(self):
        return self._forward_program_desc

    @property
    def backward_program(self):
        return self._backward_program_desc

403
    @property
404 405
    def input_descs(self):
        return self._input_descs
406 407

    @property
408
    def output_descs(self):
409 410 411 412 413 414
        return self._output_descs

    @property
    def persistable_names(self):
        return self._persistable_names

415 416 417 418
    @property
    def double_grad_descs(self):
        return self._double_grad_descs

419 420 421 422
    @property
    def scope(self):
        return self._inner_scope

423 424 425 426
    @property
    def grad_var_names(self):
        return self._grad_var_names

427
    def _preprocess(self, program_desc):
W
WeiXin 已提交
428 429
        # rename persistable variables of 'program_desc'
        list_persistable_var = _get_persistable_var_names(program_desc)
430
        rename_new_old_dict, _ = _rename_var_program_desc(
431 432
            program_desc, list_persistable_var
        )
433 434 435 436
        # 1. Prune original program
        # remove feed, fetch and scale-1 op, remove op_callstack attr
        ops_to_remove = []
        root_block = program_desc.block(0)
437
        for i in range(root_block.op_size()):
438 439 440
            op = root_block.op(i)
            if op.type() == 'feed':
                ops_to_remove.append(i)
441
                feed_var_name = op.input('X')[0].encode()
442
                root_block._remove_var(feed_var_name)
443
                self._input_descs.append(
444 445
                    root_block.find_var(op.output('Out')[0].encode())
                )
446
            elif op.type() == 'scale' and op.output('Out')[0].startswith(
447 448
                'save_infer_model/scale_'
            ):
449
                ops_to_remove.append(i)
450
                out_var_name = op.output('Out')[0].encode()
451 452
                root_block._remove_var(out_var_name)
                self._output_descs.append(
453 454
                    root_block.find_var(op.input('X')[0].encode())
                )
455 456
            elif op.type() == 'fetch':
                ops_to_remove.append(i)
457
                fetch_var_name = op.output('Out')[0].encode()
458 459 460 461
                root_block._remove_var(fetch_var_name)
                # NOTE: some old pre-train models have no extra scale_op
                if not op.input('X')[0].startswith('save_infer_model/scale_'):
                    self._output_descs.append(
462 463
                        root_block.find_var(op.input('X')[0].encode())
                    )
464 465 466 467 468 469 470
            else:
                if op.has_attr("op_callstack"):
                    op.remove_attr("op_callstack")

        for op_idx in reversed(ops_to_remove):
            root_block._remove_op(op_idx, op_idx + 1)

471 472 473 474 475 476
        for i in range(program_desc.num_blocks()):
            block_desc = program_desc.block(i)
            for var_desc in block_desc.all_vars():
                if "@GRAD" in var_desc.name():
                    self._double_grad_descs.append(var_desc)

477
        # 2. Input processing, reverse feed vars
478
        self._input_descs.reverse()
479 480 481 482

        # 3. Output processing, add scale for outputs
        tmp_program = _build_program_by_desc(program_desc)
        # NOTE: [why need append scale for outputs]
483 484 485 486 487
        # When dealing with some more complex pre-training models, there
        # will be situations where the pre-training model has multiple
        # fetch outputs. In the scenario of multiple fetch outputs,
        # there is a special case where multiple outputs of the model
        # may be on the same branch. According to the user's subsequent
488
        # use, multiple outputs may be associated with multiple branches.
489 490 491 492
        # These subsequent operations are added in TranslatedLayer is
        # agnostic during initialization, which results in subsequent
        # gradient accumulation operations that are required on the
        # output node in the middle of the branch will not be performed,
493 494 495 496 497
        # resulting in error, details see pull request:
        # [https://github.com/PaddlePaddle/Paddle/pull/24627]
        self._append_scale_to_output(tmp_program)

        # 4. Persistable vars processing
498
        # - append loaded suffix to persistable vars
499
        # NOTE: [why need to append suffix to persistable vars]
500 501 502 503 504 505
        # Dygraph and static graph mode use the same naming mechanism.
        # If users want to load the model fine-tune, it is possible
        # to add the existing Layer in the loaded model to enhance
        # the network. For example, the original saved model has linear,
        # and later after loading, a new linear is added. At this time,
        # there will be a problem of duplicate names, so here is unified
506
        # to add the LOADED suffix to the parameters of the model loaded
507
        self._suffix_varname_dict = _get_loaded_var_new_old(
508 509
            program_desc, rename_new_old_dict
        )
510

511 512 513 514 515 516 517 518 519 520 521 522
        # - get persistable var
        self._persistable_names = _get_persistable_var_names(program_desc)

        return program_desc

    @switch_to_static_graph
    def _append_scale_to_output(self, program):
        # 1. append scale & save var
        scale_output_vars = []
        with framework.program_guard(program):
            for i, out in enumerate(self._output_descs):
                var = program.global_block().var(out.name())
523
                var = paddle.scale(var, 1.0, name=f"translated_layer/scale_{i}")
524 525 526 527 528 529
                scale_output_vars.append(var)
        # 2. update output names & descs
        for i, var in enumerate(scale_output_vars):
            self._output_descs[i] = var.desc

    @switch_to_static_graph
530
    def _get_train_forward_program(self, infer_program_desc):
531 532 533 534 535 536 537 538
        program_desc_copy = core.ProgramDesc(infer_program_desc)

        # 1. set all `is_test` attributes to False
        _change_is_test_status(program_desc_copy, False)

        # 2. prepare program and related var
        # NOTE: To reuse backward interfaces, build Program firstly.
        # Originally, there is no need to build a program, but need to almost
539
        # rewrite a series of methods for append_backward for program_desc.
540 541
        # Therefore, in order to reuse the method of backward.py, build the program here.
        program = _build_program_by_desc(program_desc_copy)
542 543
        # 3. Add the outputs which is only used for training and not saved in
        # inference program.
544
        for block_idx in range(program.num_blocks):
545 546 547
            block = program.block(block_idx)
            for op in block.ops:
                if op.type == "batch_norm":
548 549 550 551
                    if (
                        "ReserveSpace" not in op.output_names
                        or len(op.output("ReserveSpace")) == 0
                    ):
552 553
                        reserve_space = block.create_var(
                            name=unique_name.generate_with_ignorable_key(
554 555
                                ".".join(["reserve_space", 'tmp'])
                            ),
556 557 558
                            dtype=block.var(op.input("X")[0]).dtype,
                            type=core.VarDesc.VarType.LOD_TENSOR,
                            persistable=False,
559 560
                            stop_gradient=True,
                        )
561
                        op.desc.set_output("ReserveSpace", [reserve_space.name])
562 563
                    continue

564 565 566 567 568
                # There are some situations that users will add backward op in Forward
                # function of Layer. And because backward op doesn't have proto. So, we
                # should skip it when we meet it.
                if not OpProtoHolder.instance().has_op_proto(op.type):
                    continue
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
                proto = OpProtoHolder.instance().get_op_proto(op.type)
                has_create_intermediate_out = False
                for output_proto in proto.outputs:
                    if output_proto.intermediate:
                        intermediate_name = output_proto.name
                        if intermediate_name not in op.output_names:
                            has_create_intermediate_out = True
                            intermediate_var = block.create_var(
                                name=unique_name.generate_with_ignorable_key(
                                    ".".join(
                                        [
                                            op.type + '_' + intermediate_name,
                                            'tmp',
                                        ]
                                    )
                                ),
                                type=core.VarDesc.VarType.LOD_TENSOR,
                                persistable=False,
                                stop_gradient=True,
                            )
                            op.desc.set_output(
                                intermediate_name, [intermediate_var.name]
                            )
                if has_create_intermediate_out:
                    op.desc.infer_var_type(block.desc)
                    op.desc.infer_shape(block.desc)

596 597 598 599 600
        return program

    @switch_to_static_graph
    def _append_backward_desc(self, infer_program_desc):
        program = self._get_train_forward_program(infer_program_desc)
601

602 603 604 605 606
        targets = []
        for out in self._output_descs:
            targets.append(program.global_block().var(out.name()))

        # 3. append backward
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        check_type(
            targets,
            'targets',
            (framework.Variable, list, tuple),
            'paddle.static.gradients',
        )
        grad_info_map = backward.calc_gradient_helper(
            targets=targets, inputs=[]
        )
        x_vars = [
            program.block(0).var(desc.name()) for desc in self._input_descs
        ]
        param_vars = [
            program.block(0).var(name) for name in self._persistable_names
        ]
        out_vars = [
            program.block(0).var(desc.name()) for desc in self._output_descs
        ]

        self._grad_var_names = construct_grad_names(
            grad_info_map, x_vars, param_vars, out_vars
        )

630 631 632 633
        return program.desc


# [ TranslatedLayer : Run program in imperative mode ]
634
#
635 636 637 638 639 640 641
# DESIGN IDEA: using an special operator `RunProgram`, execute program inside operator.
#
# Op's Inputs:
#   - the input variable of the user feed
#   - the necessary parameters of the network
# Op's Outputs:
#   - the output variable of fetch
642
#
643 644 645
# This op receives a complete program desc, internally creates scope
# and executor, executes this program. Key points:
#
646
# 1. Data Sharing:
647
#   The variable/parameter of the dynamic graph is not in the scope, so before the op
648 649 650
#   executes the program internally, create persistent variables with the
#   same name as feed, parameters, and fetch in the scope, and share the
#   LoDTensor of the op input.
651
#
652 653 654 655
# 2. Forward and Backward Separation:
#   Because the dynamic graph op performs the forward and backward separately,
#   in the forward op RunProgram, we only execute the forward part of whole program,
#   and in the backward op RunProgramGrad, we execute the backward part of program.
656
#   We can not separate the program into forward and backward part, which will
657 658 659 660 661
#   make some control flow execution logic wrong.


# NOTE: [compatible] deal with model saved by save_inference_model,
# which need get var info from program desc
662 663 664
def _load_persistable_vars_by_program(
    model_path, program_holder, params_filename=None
):
665 666 667 668
    # make sure the path has been checked
    persistable_vars = _get_persistable_vars(program_holder.infer_program)
    load_var_dict = {}
    for each_var in persistable_vars:
669
        orig_each_name = program_holder._suffix_varname_dict[each_var.name()]
670
        if _is_parameter(each_var, program_holder.infer_program):
671
            # create output param
W
wanghuancoder 已提交
672 673 674 675 676 677 678
            new_var = framework.EagerParamBase(
                shape=each_var.shape(),
                dtype=each_var.dtype(),
                name=each_var.name(),
                type=each_var.type(),
                persistable=True,
            )
679
        else:
680
            new_var = framework._create_tensor(
681 682 683 684 685 686
                type=each_var.type(),
                name=each_var.name(),
                shape=each_var.shape(),
                dtype=each_var.dtype(),
                persistable=True,
            )
687 688 689 690 691
        if params_filename is None:
            framework._dygraph_tracer().trace_op(
                type='load',
                inputs={},
                outputs={'Out': new_var},
692 693
                attrs={'file_path': os.path.join(model_path, orig_each_name)},
            )
694 695 696 697 698
        new_var.stop_gradient = False
        load_var_dict[each_var.name()] = new_var

    if params_filename is not None:
        load_var_list = []
699
        dict_name_old_new = {
700
            v: k for k, v in program_holder._suffix_varname_dict.items()
701 702 703
        }
        for name in sorted(dict_name_old_new.keys()):
            load_var_list.append(load_var_dict[dict_name_old_new[name]])
704 705 706 707 708

        framework._dygraph_tracer().trace_op(
            type='load_combine',
            inputs={},
            outputs={'Out': load_var_list},
709 710
            attrs={'file_path': os.path.join(model_path, params_filename)},
        )
711 712 713 714 715 716 717 718

        for each_var in persistable_vars:
            if not _is_parameter(each_var, program_holder.infer_program):
                continue
            param = load_var_dict[each_var.name()]
            param.stop_gradient = False

    # NOTE: [Recovery stop gradient information based on the program]
719
    # After loading the model, the stop_gradient information
720 721 722 723 724 725 726 727 728 729 730 731
    # of the original variable is lost, but if a parameter does not
    # have a corresponding @GRAD variable in the backward program,
    # it can be said that it is also stop_gradient
    all_var_names = _get_all_var_names(program_holder.train_program)
    for var_name in load_var_dict:
        grad_var_name = var_name + core.grad_var_suffix()
        if grad_var_name not in all_var_names:
            load_var_dict[var_name].stop_gradient = True

    return load_var_dict


732 733 734
def _load_persistable_vars(
    model_path, var_info_path, program_holder, params_filename
):
735 736
    # 1. load extra var info
    with open(var_info_path, 'rb') as f:
737
        extra_var_info = pickle.load(f)
738 739

    # 2. construct var dict
740
    load_var_dict = {}
741
    load_var_list = []
742
    inv_suffix_varname_dict = {
743
        value: key for key, value in program_holder._suffix_varname_dict.items()
744
    }
745 746 747

    # NOTE(chenweihang): we need load persistable vars based the program,
    # because the program may be pruned when `save_inference_model`, some
748
    # var in `extra_var_info` may have been pruned
749 750 751 752 753
    for name in sorted(inv_suffix_varname_dict):
        if name not in extra_var_info:
            raise RuntimeError(
                "The model to be loaded is not complete."
                "The variable `%s` of program cannot be found in loaded model.",
754 755
                name,
            )
756 757
        # get suffix var name, see [why need to append suffix to persistable vars]
        new_name = inv_suffix_varname_dict[name]
758
        # create output var or param
759 760
        if extra_var_info[name].get('trainable', None) is not None:
            # use default shape and dtype
W
wanghuancoder 已提交
761 762 763 764 765 766
            new_var = framework.EagerParamBase(
                shape=[1],  # only to pass check, this shape is not meaningful
                dtype=core.VarDesc.VarType.FP32,
                name=new_name,
                persistable=True,
            )
767
        else:
768
            new_var = framework._create_tensor(name=new_name, persistable=True)
769 770 771 772 773 774

        new_var.stop_gradient = extra_var_info[name]['stop_gradient']
        load_var_dict[new_name] = new_var
        load_var_list.append(new_var)

    # 3. load all vars
775 776 777 778 779 780
    assert params_filename is not None, "params_filename should not be None."
    var_file_path = os.path.join(model_path, params_filename)
    if not os.path.exists(var_file_path):
        if len(extra_var_info) != 0:
            raise ValueError("The model to be loaded is incomplete.")
    else:
781 782 783 784 785 786
        framework._dygraph_tracer().trace_op(
            type='load_combine',
            inputs={},
            outputs={'Out': load_var_list},
            attrs={'file_path': var_file_path},
        )
787 788 789 790

    return load_var_dict


791 792
# NOTE(chenweihang): to adapt paddle.load to get state_dict
def _remove_varname_suffix(var_dict, program_holder):
793
    no_suffix_var_dict = {}
794 795 796 797 798 799
    for var_name in var_dict:
        no_suffix_name = program_holder._suffix_varname_dict[var_name]
        no_suffix_var_dict[no_suffix_name] = var_dict[var_name]
    return no_suffix_var_dict


800 801
def _construct_program_holders(model_path, model_filename=None):
    # make sure the path has been checked
802
    program_holder_dict = {}
803 804 805 806 807

    if model_filename is not None:
        # [compatible] if assign model_filename, only can load one program as Layer.forward
        model_filename = os.path.basename(model_filename)
        model_file_path = os.path.join(model_path, model_filename)
808 809
        model_name = model_filename[: -len(INFER_MODEL_SUFFIX)]
        # Load every file that meets the requirements in the directory model_path.
810 811 812 813 814
        for filename in os.listdir(model_path):
            if model_filename == filename:
                func_name = 'forward'
                model_file_path = os.path.join(model_path, model_filename)
            elif filename.endswith(INFER_MODEL_SUFFIX) and filename.startswith(
815 816 817 818 819
                model_name
            ):
                parsing_names = filename[
                    len(model_name) : -len(INFER_MODEL_SUFFIX) + 1
                ].split('.')
820 821 822 823 824
                if len(parsing_names) == 3 and len(parsing_names[1]) > 0:
                    func_name = parsing_names[1]
                    model_file_path = os.path.join(model_path, filename)
                else:
                    continue
825 826 827
            else:
                continue
            program_holder_dict[func_name] = _ProgramHolder(
828 829
                _load_program_desc(model_file_path)
            )
830 831 832 833 834 835 836 837 838 839 840
    else:
        for _, _, file_names in os.walk(model_path):
            for name in file_names:
                if 'model' in name:
                    model_file_path = os.path.join(model_path, name)
                    method_name = name.strip('_')
                    if method_name == 'model':
                        method_name = 'forward'
                    else:
                        method_name.replace('model', '')
                    program_holder_dict[method_name] = _ProgramHolder(
841 842
                        _load_program_desc(model_file_path)
                    )
843 844 845 846

    return program_holder_dict


847 848 849
def _construct_params_and_buffers(
    model_path, programs, params_filename=None, append_suffix=True
):
850 851
    var_info_filename = str(params_filename) + ".info"
    var_info_path = os.path.join(model_path, var_info_filename)
852
    params_path = os.path.join(model_path, str(params_filename))
853

854
    if os.path.exists(var_info_path):
855 856 857 858 859
        var_dict = _load_persistable_vars(
            model_path, var_info_path, programs['forward'], params_filename
        )
        model_name = params_filename[: -len(INFER_PARAMS_SUFFIX)]
        # Load every file that meets the requirements in the directory model_path.
860
        for file_name in os.listdir(model_path):
861
            if file_name.startswith(model_name) and file_name.endswith(
862 863 864 865 866
                INFER_PARAMS_SUFFIX
            ):
                parsing_names = file_name[
                    len(model_name) : -len(INFER_PARAMS_SUFFIX) + 1
                ].split('.')
867 868 869 870
                if len(parsing_names) == 3 and len(parsing_names[1]) > 0:
                    func_name = parsing_names[1]
                else:
                    continue
871 872 873 874
            else:
                continue
            var_info_path = os.path.join(model_path, var_info_filename)
            var_dict.update(
875 876 877 878
                _load_persistable_vars(
                    model_path, var_info_path, programs[func_name], file_name
                )
            )
879 880
    elif params_filename is not None and not os.path.exists(params_path):
        # When saving XX, there is only '*.pdmodel'
881
        return {}
882
    else:
883 884 885
        var_dict = _load_persistable_vars_by_program(
            model_path, programs['forward'], params_filename
        )
886 887 888 889

    if not append_suffix:
        var_dict = _remove_varname_suffix(var_dict, programs['forward'])

890 891 892
    return var_dict


0
0x45f 已提交
893
def _valid_vars(vars):
894
    return vars if vars else None
0
0x45f 已提交
895 896


W
WeiXin 已提交
897 898 899 900 901
def _run_dygraph(instance, input, program_holder):

    # 1. prepare inputs, outputs, attrs
    input_vars = []
    for i, value in enumerate(input):
W
wanghuancoder 已提交
902
        if not isinstance(value, (np.ndarray, core.eager.Tensor)):
W
WeiXin 已提交
903
            raise TypeError(
W
wanghuancoder 已提交
904
                "The type of input in TranslatedLayer must be numpy array or Variable(Tensor), but received %s."
905 906
                % type(value)
            )
W
wanghuancoder 已提交
907
        # NOTE: In order to unify the API, firstly convert the input to Tensor
W
WeiXin 已提交
908
        if isinstance(value, np.ndarray):
W
wanghuancoder 已提交
909 910 911 912 913 914 915
            var = core.eager.Tensor(
                value=value,
                name=program_holder.input_descs[i].name(),
                persistable=False,
                place=framework._current_expected_place(),
                zero_copy=True,
            )
W
WeiXin 已提交
916 917
        else:
            var = value
918
            # NOTE: we changed var name here,
W
WeiXin 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
            # but it may be an important name set by user
            var.name = program_holder.input_descs[i].name()
        input_vars.append(var)
    if instance._input_args_names is None:
        instance._input_args_names = [
            ins.name() for ins in program_holder.input_descs
        ]

    persistable_vars = []
    for var_name in program_holder.persistable_names:
        dy_var_name = instance._persistable_var_name_dict[var_name]
        if dy_var_name in instance._parameters:
            persistable_vars.append(instance._parameters[dy_var_name])
        elif dy_var_name in instance._buffers:
            persistable_vars.append(instance._buffers[dy_var_name])
        else:
            raise ValueError(
                "The persistable variable %s does not exist in current TranslatedLayer."
937 938
                % var_name
            )
W
WeiXin 已提交
939 940 941

    output_vars = []
    for var_desc in program_holder.output_descs:
W
wanghuancoder 已提交
942 943 944 945 946 947 948
        var = core.eager.Tensor(
            dtype=var_desc.dtype(),
            dims=var_desc.shape(),
            name=var_desc.name(),
            type=var_desc.type(),
            persistable=False,
        )
W
WeiXin 已提交
949 950 951
        output_vars.append(var)

    # hold forward variables
W
wanghuancoder 已提交
952
    tmp_scope_vec = [program_holder.scope]
W
WeiXin 已提交
953

954 955
    double_grad_vars = []
    for var_desc in program_holder.double_grad_descs:
W
wanghuancoder 已提交
956 957 958 959 960 961 962
        var = core.eager.Tensor(
            dtype=var_desc.dtype(),
            dims=var_desc.shape(),
            name=var_desc.name(),
            type=var_desc.type(),
            persistable=False,
        )
963 964
        double_grad_vars.append(var)

W
WeiXin 已提交
965
    # 2. run program by op
966 967 968 969 970 971 972 973 974 975
    trace_program = (
        program_holder.infer_program
        if instance._is_test
        else program_holder.train_program
    )
    forward_program = (
        program_holder._infer_program_desc
        if instance._is_test
        else program_holder.forward_program
    )
W
WeiXin 已提交
976
    end_op_index = program_holder.infer_program.block(0).op_size()
977 978 979

    attrs = [
        'global_block',
980 981 982 983 984 985 986 987
        trace_program.block(0),
        'start_op_index',
        0,
        'end_op_index',
        end_op_index,
        'is_test',
        instance._is_test,
        'program_id',
988
        paddle.utils._hash_with_id(trace_program, instance),
989
    ]
990 991 992 993
    if not instance._is_test:
        attrs.extend(
            (
                'param_grad_names',
994
                program_holder.grad_var_names.get('param', []),
995
                'out_grad_names',
996 997 998
                program_holder.grad_var_names.get('out', []),
                'x_grad_names',
                program_holder.grad_var_names.get('x', []),
999 1000
            )
        )
1001

1002
    use_interpretorcore = True
1003 1004 1005
    attrs.extend(('use_interpretorcore', use_interpretorcore))
    if use_interpretorcore:
        attrs.extend(
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
            (
                'forward_global_block',
                forward_program.block(0),
                'backward_global_block',
                program_holder.backward_program.block(0),
            )
        )

    _legacy_C_ops.run_program(
        _valid_vars(input_vars),
        _valid_vars(persistable_vars),
        _valid_vars(output_vars),
        tmp_scope_vec,
        _valid_vars(double_grad_vars),
        None,
1021
        *attrs,
1022
    )
1023

W
WeiXin 已提交
1024 1025 1026
    # NOTE: [ why need set param's gradient type here ]
    # if user set sparse gradient mode, the param's gradient
    # will be SelectedRows, not LoDTensor. But tracer will just
W
wanghuancoder 已提交
1027
    # set param grad Tensor by forward Tensor(LoDTensor)
W
WeiXin 已提交
1028 1029 1030 1031
    # If we don't change grad_var type here, RunProgramOp need
    # transform SelectedRows to LoDTensor forcibly, it may not
    # be user wanted result.
    for persistable_var in persistable_vars:
0
0x45f 已提交
1032
        grad_var_name = persistable_var.name + core.grad_var_suffix()
1033
        grad_var = trace_program.block(0).find_var(grad_var_name.encode())
1034
        # NOTE: cannot find var desc maybe not problem,
W
WeiXin 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        # such as in batch_norm
        if grad_var is None:
            continue
        persistable_var._set_grad_type(grad_var.type())

    # 3. prepare output, keep same form with inputs
    outs = output_vars
    if len(output_vars) == 1:
        outs = output_vars[0]
    return outs


def _run_static_graph(input, program_holder, trace_program):
    main_program = framework.default_main_program()
    param_var_names = _get_persistable_var_names(trace_program)
    _, dict_rename_var_old_new = _rename_var_program_desc(
1051 1052
        trace_program, exclude=param_var_names
    )
W
WeiXin 已提交
1053 1054 1055
    trace_program.flush()
    output_names = [var.name() for var in program_holder.output_descs]
    # append blocks from 'trace_program'
1056 1057 1058 1059 1060 1061 1062
    _append_block(
        main_program,
        trace_program,
        program_holder,
        input,
        dict_rename_var_old_new,
    )
W
WeiXin 已提交
1063
    main_program._sync_with_cpp()
1064 1065 1066
    outs = _get_output_from_program(
        main_program, program_holder, dict_rename_var_old_new
    )
W
WeiXin 已提交
1067 1068 1069 1070 1071 1072 1073 1074
    if len(outs) == 1:
        outs = outs[0]
    return outs


def _collect_current_and_parent_var(program, block_idx):
    '''
    Get variables in current block and its parent block.
1075

W
WeiXin 已提交
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
    Args:
        program(Program): The program containing the current block.
        block_idx(int): index of current block.

    Returns:
        List: list of variables.
    '''
    vars = []
    if block_idx < 0:
        return vars
    for var in program.block(block_idx).vars:
        vars.append(var)
    parent_idx = program.block(block_idx).parent_idx
    if parent_idx > -1:
        vars += _collect_current_and_parent_var(program, parent_idx)
    return vars


1094 1095 1096 1097 1098 1099 1100
def _append_block(
    dest_program,
    src_program_desc,
    program_holder,
    input_variables,
    dict_rename_var_old_new=None,
):
W
WeiXin 已提交
1101 1102
    '''
    Append Variables and Operators in 'src_program_desc' to dest_program.
1103

W
WeiXin 已提交
1104 1105 1106 1107 1108
    Args:
        dest_program(Program): Variables and Operators are appended to it.
        src_program_desc(ProgramDesc): Variables in it will be appended to 'dest_program'.
        program_holder(_ProgramHolder): program_holder of TranslatedLayer
        input_variables(list): list of input variables
1109
        dict_rename_var_old_new(None|dict): When using '_rename_var_program_desc',
W
WeiXin 已提交
1110 1111 1112 1113
        use it to map the name of the variable before it was modified and the new name.
    '''

    origin_block_idx = dest_program.current_block_idx
1114 1115 1116 1117 1118 1119 1120 1121
    param_var_names = _collect_current_and_parent_var(
        dest_program, origin_block_idx
    )
    append_var_from_block_desc_static(
        dest_program.block(origin_block_idx),
        src_program_desc.block(0),
        exclude=param_var_names,
    )
W
WeiXin 已提交
1122 1123 1124 1125 1126

    name_inp_desc = [inp.name() for inp in program_holder.input_descs]
    input_names = [inp.name for inp in input_variables]
    if len(name_inp_desc) != len(input_names):
        raise ValueError(
1127 1128 1129 1130
            "The number of input is invalid, expected {}, but received {}.".format(
                len(name_inp_desc), len(input_names)
            )
        )
W
WeiXin 已提交
1131 1132 1133 1134 1135 1136
    for i, out_name in enumerate(name_inp_desc):
        if dict_rename_var_old_new:
            out_name = dict_rename_var_old_new[out_name]
        dest_program.block(origin_block_idx).append_op(
            type='assign',
            inputs={'X': [input_names[i]]},
1137 1138
            outputs={'Out': [out_name]},
        )
W
WeiXin 已提交
1139 1140

    append_ops = append_op_from_block_desc_static(
1141 1142
        dest_program.block(origin_block_idx), src_program_desc.block(0)
    )
W
WeiXin 已提交
1143 1144 1145
    dest_program._sync_with_cpp()

    offset_block_idx = dest_program.num_blocks - 1
1146
    parent_idx = 0
W
WeiXin 已提交
1147 1148 1149 1150 1151 1152 1153 1154 1155
    if src_program_desc.num_blocks() > 1:
        for src_block_idx in range(1, src_program_desc.num_blocks()):
            src_block = src_program_desc.block(src_block_idx)
            src_parent_idx = src_block.parent
            if src_parent_idx > 0:
                parent_idx = offset_block_idx + parent_idx
            else:
                parent_idx = origin_block_idx
            dest_block = dest_program._create_block(parent_idx=parent_idx)
1156 1157 1158
            append_var_from_block_desc_static(
                dest_block, src_block, exclude=param_var_names
            )
1159
            append_ops += append_op_from_block_desc_static(
1160 1161
                dest_block, src_block
            )
W
WeiXin 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170

    dest_program._sync_with_cpp()
    for op in append_ops:
        if op.has_attr('sub_block'):
            sub = op.attr('sub_block')
            if isinstance(sub, framework.core.BlockDesc):
                origin_id = sub.id
            if isinstance(sub, framework.Block):
                origin_id = sub.idx
1171 1172 1173
            op._set_attr(
                'sub_block', dest_program.block(offset_block_idx + origin_id)
            )
W
WeiXin 已提交
1174 1175 1176 1177
    dest_program._sync_with_cpp()
    dest_program.current_block_idx = origin_block_idx


1178 1179 1180
def _get_output_from_program(
    program, program_holder, dict_rename_var_old_new=None
):
W
WeiXin 已提交
1181 1182 1183
    """
    Get output name of 'program' according to program_holder
    """
1184
    outs = []
W
WeiXin 已提交
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    for var in program_holder.output_descs:
        for idx in range(program.num_blocks):
            vars = program.block(idx).vars
            var_name = var.name()
            if dict_rename_var_old_new:
                var_name = dict_rename_var_old_new[var_name]
            if var_name in vars:
                out = vars[var_name]
                if out not in outs:
                    outs.append(out)
    return outs


def append_op_from_block_desc_static(block, src_block_desc):
    """
    Append Operators of 'src_block_desc' to current block.

    Args:
        block(Block): append OP of  'src_block_desc' to it.
        src_block_desc(BlockDesc): append var of  'src_block_desc'

    Returns:
        List: list of the OP that are append to current block.
    """
    ops = []
    for i in range(src_block_desc.op_size()):
        ops.append(append_op_from_desc_static(block, src_block_desc.op(i)))
    return ops


def append_op_from_desc_static(block, op_desc):
    """
    Append Operators to 'block' according to 'op_desc'.

    Args:
        block(Block): append OP of  'src_block_desc' to it.
        op_desc(OpDesc): create OP according to it.

    Returns:
        Operator: OP appended to 'block'.
    """
    op_type = op_desc.type()
    op_append = block.desc.append_op()
    op_append.copy_from(op_desc)
1229 1230 1231 1232 1233 1234 1235 1236
    op = framework.Operator(
        block=block,
        desc=op_append,
        type=op_type,
        inputs=None,
        outputs=None,
        attrs=None,
    )
W
WeiXin 已提交
1237 1238 1239 1240
    block.ops.append(op)
    return op


1241 1242 1243
def append_var_from_block_desc_static(
    block, src_block_desc, include=None, exclude=None
):
W
WeiXin 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
    """
    Append Variables of 'src_block_desc' to current block.
    If 'include' is not `None`,variables that are not in include are not append.
    If 'exclude' is not `None`,variables that are in exclude will are not append.

    Args:
        block(Block): append Variables of  'src_block_desc' to it.
        src_block_desc(BlockDesc): append var of  'src_block_desc'
        include(List):list of names of variables
        exclude(List):list of names of variables

    Returns:
        List: list of the variables that are append to current block.
    """
    vars_append = []
    for var_desc in src_block_desc.all_vars():
        var_desc_name = var_desc.name()
        should_append = (include is None or var_desc_name in include) and (
1262 1263
            exclude is None or var_desc_name not in exclude
        )
W
WeiXin 已提交
1264 1265 1266
        if not block.has_var(var_desc_name) and should_append:
            var_type = var_desc.type()
            if var_type in [
1267 1268 1269
                core.VarDesc.VarType.SELECTED_ROWS,
                core.VarDesc.VarType.LOD_TENSOR,
                core.VarDesc.VarType.LOD_TENSOR_ARRAY,
W
WeiXin 已提交
1270 1271 1272 1273 1274 1275 1276
            ]:
                data_type = var_desc.dtype()
                var_shape = var_desc.shape()
            else:
                data_type = None
                var_shape = None
            if var_type in [
1277 1278
                core.VarDesc.VarType.LOD_TENSOR,
                core.VarDesc.VarType.LOD_TENSOR_ARRAY,
W
WeiXin 已提交
1279 1280 1281 1282 1283
            ]:
                lod_level = var_desc.lod_level()
            else:
                lod_level = None

1284 1285 1286 1287 1288
            if var_desc.persistable():
                current_block = block.program.global_block()
            else:
                current_block = block

W
WeiXin 已提交
1289
            vars_append.append(
1290
                current_block.create_var(
W
WeiXin 已提交
1291 1292 1293 1294 1295 1296
                    name=var_desc.name(),
                    dtype=data_type,
                    type=var_type,
                    shape=var_shape,
                    lod_level=lod_level,
                    persistable=var_desc.persistable(),
1297 1298 1299
                    set_need_check_feed=var_desc.need_check_feed(),
                )
            )
W
WeiXin 已提交
1300 1301 1302
    return vars_append


1303 1304
class TranslatedLayer(layers.Layer):
    """
1305 1306
    TranslatedLayer is a ``paddle.nn.Layer`` for holding the model
    loaded by :ref:`api_paddle_jit_load` . It can be used like a
1307
    general Layer object in eval or train mode.
1308

1309
    .. note:
1310
        The TranslatedLayer objects should not be created by constructor, it only can be loaded and constructed by :ref:`api_paddle_jit_load` .
1311 1312 1313 1314 1315

    Examples:
        .. code-block:: python

            import numpy as np
1316 1317 1318
            import paddle
            import paddle.nn as nn
            import paddle.optimizer as opt
1319

1320 1321 1322
            BATCH_SIZE = 16
            BATCH_NUM = 4
            EPOCH_NUM = 4
1323

1324 1325 1326 1327 1328 1329 1330
            IMAGE_SIZE = 784
            CLASS_NUM = 10

            # define a random dataset
            class RandomDataset(paddle.io.Dataset):
                def __init__(self, num_samples):
                    self.num_samples = num_samples
1331

1332 1333 1334 1335
                def __getitem__(self, idx):
                    image = np.random.random([IMAGE_SIZE]).astype('float32')
                    label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
                    return image, label
1336

1337 1338
                def __len__(self):
                    return self.num_samples
1339

1340 1341
            class LinearNet(nn.Layer):
                def __init__(self):
1342
                    super().__init__()
1343
                    self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)
1344

1345
                @paddle.jit.to_static
1346 1347 1348
                def forward(self, x):
                    return self._linear(x)

1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
            def train(layer, loader, loss_fn, opt):
                for epoch_id in range(EPOCH_NUM):
                    for batch_id, (image, label) in enumerate(loader()):
                        out = layer(image)
                        loss = loss_fn(out, label)
                        loss.backward()
                        opt.step()
                        opt.clear_grad()
                        print("Epoch {} batch {}: loss = {}".format(
                            epoch_id, batch_id, np.mean(loss.numpy())))

1360 1361
            # 1. train & save model.

1362 1363 1364 1365
            # create network
            layer = LinearNet()
            loss_fn = nn.CrossEntropyLoss()
            adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())
1366

1367 1368 1369 1370 1371 1372 1373
            # create data loader
            dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
            loader = paddle.io.DataLoader(dataset,
                batch_size=BATCH_SIZE,
                shuffle=True,
                drop_last=True,
                num_workers=2)
1374

1375 1376
            # train
            train(layer, loader, loss_fn, adam)
1377

1378
            # save
1379
            model_path = "linear.example.model"
1380
            paddle.jit.save(layer, model_path)
1381 1382

            # 2. load model as TranslatedLayer
1383 1384 1385 1386

            # load
            translated_layer = paddle.jit.load(model_path)

1387 1388
            # inference
            translated_layer.eval()
1389
            x = paddle.randn([1, IMAGE_SIZE], 'float32')
1390
            pred = translated_layer(x)
1391

1392 1393
            # fine-tune
            translated_layer.train()
1394 1395
            adam = opt.Adam(learning_rate=0.001, parameters=translated_layer.parameters())
            train(translated_layer, loader, loss_fn, adam)
1396 1397 1398 1399

    """

    def __init__(self, programs, persistable_vars):
1400
        super().__init__()
1401 1402 1403 1404 1405 1406 1407

        if not isinstance(programs, dict):
            raise TypeError(
                "TranslatedLayer need to use _ProgramHolder's dict for initialization."
            )
        if not isinstance(persistable_vars, dict):
            raise TypeError(
1408
                "TranslatedLayer need to use persistable variable dict for initialization."
1409 1410 1411 1412
            )

        self._program_holder_dict = programs

1413 1414 1415 1416
        # NOTE(chenweihang): [ why not use var name directly? ]
        # When add parameter or buffer to Layer by follow apis,
        # the variable name can't contain `.`, beccause which may cause
        # AttributeError when access the newly added parameter or buffer
W
wanghuancoder 已提交
1417
        # in the form of `self.**.**``, but the EagerParamBase or BarBase
1418 1419
        # name contains `.` originally, such as `linear_0.w_0`, so here
        # need to generate new var name for each var
1420
        self._persistable_var_name_dict = {}
1421 1422 1423
        # the TranslatedLayer object holded var names count started from 0
        with unique_name.guard():
            for name, var in persistable_vars.items():
W
wanghuancoder 已提交
1424
                if isinstance(var, framework.EagerParamBase):
1425 1426 1427
                    dy_name = _generate_unique_var_name(PARAMETER_NAME_PREFIX)
                    self._persistable_var_name_dict[name] = dy_name
                    self.add_parameter(dy_name, var)
W
wanghuancoder 已提交
1428
                elif isinstance(var, core.eager.Tensor):
1429 1430 1431 1432 1433 1434 1435
                    dy_name = _generate_unique_var_name(BUFFER_NAME_PREFIX)
                    self._persistable_var_name_dict[name] = dy_name
                    self.register_buffer(dy_name, var)
                else:
                    raise TypeError(
                        "Adding persistent variable which  to layer is not supported now"
                    )
1436 1437

        self._is_test = True
W
WeiXin 已提交
1438
        self._input_args_names = None
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455

    @staticmethod
    @framework.dygraph_only
    def _construct(model_path, configs=None):
        # 0. dir and filename check
        model_path = os.path.normpath(model_path)
        if not os.path.isdir(model_path):
            raise ValueError("There is no directory named '%s'" % model_path)
        model_filename = None
        params_filename = None
        if configs is not None:
            model_filename = configs.model_filename
            params_filename = configs.params_filename

        # 1. load program desc & construct _ProgramHolder
        programs = _construct_program_holders(model_path, model_filename)

1456
        # 2. load layer parameters & buffers
1457
        persistable_vars = _construct_params_and_buffers(
1458 1459
            model_path, programs, params_filename
        )
1460 1461 1462 1463 1464 1465

        # 3. construct TranslatedLayer object
        translated_layer = TranslatedLayer(programs, persistable_vars)

        # 4. create TranslatedLayer's execution method
        for method_name, program_holder in programs.items():
1466 1467 1468 1469
            if translated_layer._input_args_names is None:
                translated_layer._input_args_names = [
                    ins.name() for ins in program_holder.input_descs
                ]
1470
            setattr(
1471 1472
                TranslatedLayer,
                method_name,
1473
                TranslatedLayer._execution_method_creator(
1474 1475 1476
                    method_name, program_holder
                ),
            )
1477 1478 1479 1480 1481 1482 1483 1484

        # 5. set TranslatedLayer's default mode to eval
        translated_layer.eval()

        return translated_layer

    @staticmethod
    def _execution_method_creator(method_name, program_holder):
W
WeiXin 已提交
1485 1486 1487 1488
        def __i_m_p_l__(self, *input):
            program_holder = self._program_holder_dict[__i_m_p_l__.__name__]
            # When using jit.save, it runs in static graph mode.
            # Run in dynamic graph mode when the model is inferring.
J
Jiabin Yang 已提交
1489
            if _non_static_mode():
W
WeiXin 已提交
1490 1491 1492 1493 1494 1495 1496
                return _run_dygraph(self, input, program_holder)
            else:
                # NOTE(weixin): [ why not use 'program_holder.infer_program' directly? ]
                # When use '_run_static_graph(input, program_holder, program_holder.infer_program)',
                # because '_run_static_graph' modifies 'ProgramDesc', 'OpDesc.op_size()' will return a very large wrong number.
                # A Segmentation fault error may occur if used 'p=ProgramDesc(program_holder.infer_program)'.
                p = framework.Program._construct_from_desc(
1497 1498
                    core.ProgramDesc(program_holder.infer_program)
                )
W
WeiXin 已提交
1499 1500 1501 1502
                return _run_static_graph(input, program_holder, p.desc)

        __i_m_p_l__.__name__ = method_name
        return __i_m_p_l__
1503 1504 1505

    def train(self):
        self._is_test = False
1506
        self.training = True
1507 1508 1509

    def eval(self):
        self._is_test = True
1510
        self.training = False
1511 1512 1513 1514 1515 1516 1517 1518

    def program(self, method_name='forward'):
        """
        Gets translated program of specified method.

        Args:
            - method_name (string): mehtod name corresponding to the program
                to be obtained. Default: 'forward'.
1519

1520 1521 1522 1523 1524
        Returns:
            Program

        Examples:
            .. code-block:: python
1525

1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
                import numpy as np
                import paddle
                import paddle.nn as nn
                import paddle.optimizer as opt

                BATCH_SIZE = 16
                BATCH_NUM = 4
                EPOCH_NUM = 4

                IMAGE_SIZE = 784
                CLASS_NUM = 10

                # define a random dataset
                class RandomDataset(paddle.io.Dataset):
                    def __init__(self, num_samples):
                        self.num_samples = num_samples

                    def __getitem__(self, idx):
                        image = np.random.random([IMAGE_SIZE]).astype('float32')
                        label = np.random.randint(0, CLASS_NUM - 1, (1, )).astype('int64')
                        return image, label

                    def __len__(self):
                        return self.num_samples

                class LinearNet(nn.Layer):
                    def __init__(self):
1553
                        super().__init__()
1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
                        self._linear = nn.Linear(IMAGE_SIZE, CLASS_NUM)

                    @paddle.jit.to_static
                    def forward(self, x):
                        return self._linear(x)

                def train(layer, loader, loss_fn, opt):
                    for epoch_id in range(EPOCH_NUM):
                        for batch_id, (image, label) in enumerate(loader()):
                            out = layer(image)
                            loss = loss_fn(out, label)
                            loss.backward()
                            opt.step()
                            opt.clear_grad()
                            print("Epoch {} batch {}: loss = {}".format(
                                epoch_id, batch_id, np.mean(loss.numpy())))

                # create network
                layer = LinearNet()
                loss_fn = nn.CrossEntropyLoss()
                adam = opt.Adam(learning_rate=0.001, parameters=layer.parameters())

                # create data loader
                dataset = RandomDataset(BATCH_NUM * BATCH_SIZE)
                loader = paddle.io.DataLoader(dataset,
                    batch_size=BATCH_SIZE,
                    shuffle=True,
                    drop_last=True,
                    num_workers=2)

                # train
                train(layer, loader, loss_fn, adam)

                # save
                model_path = "linear.example.model"
                paddle.jit.save(layer, model_path)

                # load
                translated_layer = paddle.jit.load(model_path)

                # get program
                program = translated_layer.program()
        """
        # 1. get program holder
1598
        program_holder = self._get_program_holder(method_name)
1599 1600 1601 1602 1603 1604 1605

        # 2. get inference program desc
        program_desc = program_holder.infer_program

        # 3. construct program
        program = _build_program_by_desc(program_desc)
        return program
1606 1607 1608 1609 1610

    def _get_program_holder(self, method_name='forward'):
        program_holder = self._program_holder_dict.get(method_name, None)
        if program_holder is None:
            raise ValueError(
1611 1612 1613
                "The method `%s` does not exist in loaded TranslatedLayer."
                % method_name
            )
1614 1615 1616 1617 1618 1619 1620 1621 1622
        return program_holder

    def _input_spec(self, method_name='forward'):
        # 1. get program holder
        program_holder = self._get_program_holder(method_name)

        # 2. build input spec by input desc
        input_spec = []
        for var_desc in program_holder.input_descs:
1623 1624 1625 1626 1627
            spec = paddle.static.InputSpec(
                shape=var_desc.shape(),
                dtype=var_desc.dtype(),
                name=var_desc.name(),
            )
1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
            input_spec.append(spec)

        return input_spec

    def _output_spec(self, method_name='forward'):
        # 1. get program holder
        program_holder = self._get_program_holder(method_name)

        # 2. build output spec by output desc
        output_spec = []
        for var_desc in program_holder.output_descs:
1639 1640
            # NOTE(chenweihang): InputSpec describes a tensor, not just input.
            # Maybe the name is not good enough. Here we use InputSpec to
1641
            # construct the description of Output tensor
1642 1643 1644 1645 1646
            spec = paddle.static.InputSpec(
                shape=var_desc.shape(),
                dtype=var_desc.dtype(),
                name=var_desc.name(),
            )
1647 1648 1649
            output_spec.append(spec)

        return output_spec