dist_saver.py 9.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2022 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 errno
import logging
17 18 19 20
import os
import pickle
import re

21 22
import numpy as np

23
import paddle
24
from paddle.framework import core
25

R
Roc 已提交
26
from ..utils.log_utils import get_logger
27 28
from .process_group import _g_process_group_map
from .utils import get_dist_attr
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57


def check_filename(re_exp, filename):
    if re.search(re_exp, filename):
        return True
    else:
        return False


def _process_path(path):
    filename = os.path.basename(path)
    if filename == "":
        raise ValueError(
            "path should be of 'dirname/filename' format, but received filename is empty string"
        )
    try:
        dirname = os.path.dirname(path)
        os.makedirs(dirname)
    except OSError as e:
        if e.errno != errno.EEXIST:
            raise
    return dirname, filename


class DistributedSaver:
    def __init__(self):
        self._logger = get_logger(logging.INFO)

    def save(self, path, serial_program, dist_main_program, dist_context):
58 59
        def _save_state(program, path, mode="param"):
            state = {
60
                k: np.array(v) for k, v in program.state_dict(mode).items()
61 62 63 64
            }
            with open(path, "wb") as f:
                pickle.dump(state, f)

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        dirname, filename = _process_path(path)

        rank_id = paddle.distributed.get_rank()
        # save serial program when rank id is 0
        if rank_id == 0:
            self._save_rank_mapping(dirname)
            serial_model_filename = filename + "_serial.pdmodel"
            serial_model_path = os.path.join(dirname, serial_model_filename)
            with open(serial_model_path, "wb") as f:
                f.write(serial_program.desc.serialize_to_string())

        # save distributed main program
        dist_model_filename = filename + "_dist" + str(rank_id) + ".pdmodel"
        dist_model_path = os.path.join(dirname, dist_model_filename)
        with open(dist_model_path, "wb") as f:
            f.write(dist_main_program.desc.serialize_to_string())

        # save distributed attribute
        dist_attr_filename = filename + "_dist" + str(rank_id) + ".pdattr"
        dist_attr_path = os.path.join(dirname, dist_attr_filename)
        dist_attrs = get_dist_attr(dist_main_program, dist_context)
        with open(dist_attr_path, "wb") as f:
            pickle.dump(dist_attrs, f)

89 90 91 92 93 94 95 96 97 98
        # save distributed params
        dist_param_filename = filename + "_dist" + str(rank_id) + ".pdparams"
        dist_param_path = os.path.join(dirname, dist_param_filename)
        _save_state(dist_main_program, dist_param_path)

        # save distributed opt states
        dist_opt_filename = filename + "_dist" + str(rank_id) + ".pdopt"
        dist_opt_path = os.path.join(dirname, dist_opt_filename)
        _save_state(dist_main_program, dist_opt_path, "opt")

99 100
        # TODO:save cluster.json

101
    def load(self, path, load_optimizer=True):
102
        # TODO: if `program` is None, load `path.pdmodel`.
103 104 105
        def _load_file(filename, dirname, suffix="pdparams"):
            file_list = []
            for file in os.listdir(dirname):
106
                if check_filename(f'{filename}(.*)_dist(.*).{suffix}', file):
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
                    file_list.append(os.path.join(dirname, file))
            file_list.sort()
            return file_list

        def _load_state(filename, dirname, suffix="pdparams"):
            file_list = _load_file(filename, dirname, suffix)
            state_dict = {}
            for file in file_list:
                with open(file, 'rb') as f:
                    state_dict_info = pickle.load(f, encoding='latin1')
                for name, value in state_dict_info.items():
                    if name in state_dict:
                        state_dict[name].append(np.array(value))
                    else:
                        state_dict[name] = [np.array(value)]
122
            self._logger.info(f"Load param file: {file_list}")
123 124
            return state_dict

125 126 127 128 129 130
        filename = os.path.basename(path)
        if filename == "":
            raise ValueError(
                "path should be of 'dirname/filename' format, but received filename is empty string"
            )
        dirname = os.path.dirname(path)
131 132 133

        # load path.pdparam and path.pdopt
        param_state_dict = _load_state(filename, dirname)
134 135 136
        opt_state_dict = (
            _load_state(filename, dirname, "pdopt") if load_optimizer else {}
        )
137
        state_dict = dict(param_state_dict, **opt_state_dict)
138 139

        # load path.pdattr
140
        dist_attr_file_list = _load_file(filename, dirname, "pdattr")
141
        self._logger.info(
142
            f"Load distributed attribute file: {dist_attr_file_list}"
143
        )
144
        dist_attr = {}
145 146
        for dist_attr_file in dist_attr_file_list:
            with open(dist_attr_file, 'rb') as f:
147 148 149 150 151 152
                dist_attr_info = pickle.load(f, encoding='latin1')
            for name, attr in dist_attr_info.items():
                if name not in dist_attr:
                    dist_attr[name] = attr

        return state_dict, dist_attr
153 154 155 156 157 158 159 160 161 162 163 164 165 166

    def save_inference_model(self, path, feed_vars, fetch_vars, exe, **kwargs):

        dirname, filename = _process_path(path)

        # save distributed inference program
        rank_id = paddle.distributed.get_rank()
        if rank_id == 0:
            self._save_rank_mapping(dirname)
        op_role_key = core.op_proto_and_checker_maker.kOpRoleAttrName()
        op_role_forward = int(core.op_proto_and_checker_maker.OpRole.Forward)

        dist_main_prog = kwargs.get('program', None)
        if not dist_main_prog:
167
            dist_main_prog = paddle.static.default_main_program()
168 169 170
        global_block = dist_main_prog.global_block()

        ops = global_block.ops
171 172
        feed_vars_names = [x.name for x in feed_vars]
        fetch_vars_names = [x.name for x in fetch_vars]
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

        last_idx = -1
        for idx, op in enumerate(ops):
            if op.attr(op_role_key) != op_role_forward:
                continue
            if op.type == "read" or op.type == "feed" or op.type == 'recv_v2':
                feed_vars_names += op.output("Out")
            if op.type == "send_v2":
                fetch_vars_names += op.input("X")
                last_idx = max(idx, last_idx)
            for out_name in op.output_arg_names:
                if out_name in fetch_vars_names:
                    last_idx = max(idx, last_idx)

        used_inputs = []
        used_outputs = []
        for idx, op in enumerate(ops):
            if idx > last_idx:
                break
            used_inputs += op.input_arg_names
            used_outputs += op.output_arg_names

195 196 197 198 199 200 201 202 203 204 205 206 207 208
        # delete duplicated elements and keep order
        feed_vars_names = list({}.fromkeys(feed_vars_names).keys())
        used_inputs = list({}.fromkeys(used_inputs).keys())
        fetch_vars_names = list({}.fromkeys(fetch_vars_names).keys())
        used_outputs = list({}.fromkeys(used_outputs).keys())

        dist_feed_vars_names = [
            var_name for var_name in feed_vars_names if var_name in used_inputs
        ]
        dist_fetch_vars_names = [
            var_name
            for var_name in fetch_vars_names
            if var_name in used_outputs
        ]
209

210
        dist_feed_vars = list(
211
            reversed([global_block.vars[name] for name in dist_feed_vars_names])
212
        )
213 214 215
        dist_fetch_vars = [
            global_block.vars[name] for name in dist_fetch_vars_names
        ]
216 217 218

        dist_filename = filename + "_dist" + str(rank_id)
        dist_path = os.path.join(dirname, dist_filename)
219
        legacy_format = kwargs.get("legacy_format", False)
220 221 222 223 224 225
        paddle.static.save_inference_model(
            dist_path,
            dist_feed_vars,
            dist_fetch_vars,
            exe,
            program=dist_main_prog,
226
            legacy_format=legacy_format,
227
        )
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254

    def _save_rank_mapping(self, dirname):
        path = os.path.join(dirname, 'rank_mapping.csv')
        f = open(path, 'w')
        f.write('[ring_id -> ranks]\n')
        for process_group in _g_process_group_map.values():
            ring_id = process_group._group_id
            ranks = [str(rank) for rank in process_group._ranks]
            id_to_rank = str(ring_id) + "," + ",".join(ranks) + '\n'
            f.write(id_to_rank)
            id_to_rank = ""
        f.write('[rank -> ring_ids]\n')
        rank_to_id_dict = {}
        for process_group in _g_process_group_map.values():
            ring_id = process_group._group_id
            for rank in process_group._ranks:
                if rank in rank_to_id_dict:
                    rank_to_id_dict[rank].append(str(ring_id))
                else:
                    rank_to_id_dict[rank] = [str(ring_id)]
        rank_to_id = ""
        for item, val in rank_to_id_dict.items():
            rank_to_id += str(item) + ","
            rank_to_id += ",".join(val) + "\n"
            f.write(rank_to_id)
            rank_to_id = ""
        f.close()