fp16_utils.py 1.7 KB
Newer Older
W
wuyefeilin 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# coding: utf8
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
# 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.

W
wuzewu 已提交
16 17 18
import os
from paddle import fluid

W
wuyefeilin 已提交
19

W
wuzewu 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
def load_fp16_vars(executor, dirname, program):
    load_dirname = os.path.normpath(dirname)

    def _if_exist(var):
        name = var.name[:-7] if var.name.endswith('.master') else var.name
        b = os.path.exists(os.path.join(load_dirname, name))
        if not b and isinstance(var, fluid.framework.Parameter):
            print("===== {} not found ====".format(var.name))
        return b

    load_prog = fluid.Program()
    load_block = load_prog.global_block()
    vars = list(filter(_if_exist, program.list_vars()))

    for var in vars:
        new_var = fluid.io._clone_var_in_block_(load_block, var)
        name = var.name[:-7] if var.name.endswith('.master') else var.name
        file_path = os.path.join(load_dirname, name)
        load_block.append_op(
            type='load',
            inputs={},
            outputs={'Out': [new_var]},
            attrs={
                'file_path': file_path,
                'load_as_fp16': var.dtype == fluid.core.VarDesc.VarType.FP16
            })

W
wuyefeilin 已提交
47
    executor.run(load_prog)