io.py 9.5 KB
Newer Older
1
import os
2
import cPickle as pickle
3

Y
Yu Yang 已提交
4
from paddle.v2.fluid.framework import Program, Parameter, default_main_program, Variable
5 6

__all__ = [
7 8 9 10 11 12 13 14 15
    'save_vars',
    'save_params',
    'save_persistables',
    'load_vars',
    'load_params',
    'load_persistables',
    'save_inference_model',
    'load_inference_model',
    'get_inference_program',
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
]


def is_parameter(var):
    return isinstance(var, Parameter)


def is_persistable(var):
    return var.persistable


def _clone_var_in_block_(block, var):
    assert isinstance(var, Variable)
    return block.create_var(
        name=var.name,
        shape=var.shape,
F
fengjiayi 已提交
32
        dtype=var.dtype,
33 34 35 36 37
        type=var.type,
        lod_level=var.lod_level,
        persistable=True)


38
def save_vars(executor, dirname, main_program=None, vars=None, predicate=None):
39 40
    """
    Save variables to directory by executor.
41

42 43
    :param executor: executor that save variable
    :param dirname: directory path
X
xuwei06 已提交
44
    :param main_program: program. If vars is None, then filter all variables in this
45
    program which fit `predicate`. Default default_main_program.
46 47 48 49 50 51 52
    :param predicate: The Predicate describes a callable that returns a variable
    as a bool. If it returns true, the variables will be saved.
    :param vars: variables need to be saved. If specify vars, program & predicate
    will be ignored
    :return: None
    """
    if vars is None:
53
        if main_program is None:
Y
Yu Yang 已提交
54
            main_program = default_main_program()
55
        if not isinstance(main_program, Program):
56 57 58 59 60
            raise TypeError("program should be as Program type or None")

        save_vars(
            executor,
            dirname=dirname,
61
            vars=filter(predicate, main_program.list_vars()))
62 63 64 65 66 67 68 69 70 71 72 73 74
    else:
        save_program = Program()
        save_block = save_program.global_block()
        for each_var in vars:
            new_var = _clone_var_in_block_(save_block, each_var)
            save_block.append_op(
                type='save',
                inputs={'X': [new_var]},
                outputs={},
                attrs={'file_path': os.path.join(dirname, new_var.name)})
        executor.run(save_program)


75
def save_params(executor, dirname, main_program=None):
76 77 78 79 80 81
    """
    Save all parameters to directory with executor.
    """
    save_vars(
        executor,
        dirname=dirname,
82
        main_program=main_program,
83 84 85 86
        vars=None,
        predicate=is_parameter)


87
def save_persistables(executor, dirname, main_program=None):
88 89 90 91 92 93
    """
    Save all persistables to directory with executor.
    """
    save_vars(
        executor,
        dirname=dirname,
94
        main_program=main_program,
95 96 97 98
        vars=None,
        predicate=is_persistable)


99
def load_vars(executor, dirname, main_program=None, vars=None, predicate=None):
100 101
    """
    Load variables from directory by executor.
102

103 104
    :param executor: executor that save variable
    :param dirname: directory path
X
xuwei06 已提交
105
    :param main_program: program. If vars is None, then filter all variables in this
Y
Yu Yang 已提交
106
    program which fit `predicate`. Default default_main_program().
107 108
    :param predicate: The Predicate describes a callable that returns a variable
    as a bool. If it returns true, the variables will be loaded.
X
xuwei06 已提交
109
    :param vars: variables need to be loaded. If specify vars, program &
110 111 112 113
    predicate will be ignored
    :return: None
    """
    if vars is None:
114
        if main_program is None:
Y
Yu Yang 已提交
115
            main_program = default_main_program()
116
        if not isinstance(main_program, Program):
117 118 119 120 121
            raise TypeError("program's type should be Program")

        load_vars(
            executor,
            dirname=dirname,
122
            vars=filter(predicate, main_program.list_vars()))
123 124 125 126 127 128 129 130 131 132 133
    else:
        load_prog = Program()
        load_block = load_prog.global_block()
        for each_var in vars:
            assert isinstance(each_var, Variable)
            new_var = _clone_var_in_block_(load_block, each_var)
            load_block.append_op(
                type='load',
                inputs={},
                outputs={"Out": [new_var]},
                attrs={'file_path': os.path.join(dirname, new_var.name)})
134

135 136 137
        executor.run(load_prog)


138
def load_params(executor, dirname, main_program=None):
139 140 141 142
    """
    load all parameters from directory by executor.
    """
    load_vars(
143 144 145 146
        executor,
        dirname=dirname,
        main_program=main_program,
        predicate=is_parameter)
147 148


149
def load_persistables(executor, dirname, main_program=None):
150 151 152 153
    """
    load all persistables from directory by executor.
    """
    load_vars(
154 155 156 157
        executor,
        dirname=dirname,
        main_program=main_program,
        predicate=is_persistable)
158 159


160 161
def get_inference_program(target_vars, main_program=None):
    if main_program is None:
Y
Yu Yang 已提交
162
        main_program = default_main_program()
163 164 165 166 167 168 169 170
    if not isinstance(target_vars, list):
        target_vars = [target_vars]

    pruned_program = main_program.prune(targets=target_vars)
    inference_program = pruned_program.inference_optimize()
    return inference_program


171 172 173 174
def save_inference_model(dirname,
                         feeded_var_names,
                         target_vars,
                         executor,
175
                         main_program=None):
176
    """
X
xuwei06 已提交
177
    Build a model especially for inference,
178 179 180 181 182 183
    and save it to directory by the executor.

    :param dirname: directory path
    :param feeded_var_names: Names of variables that need to be feeded data during inference
    :param target_vars: Variables from which we can get inference results.
    :param executor: executor that save inference model
X
xuwei06 已提交
184
    :param main_program: original program, which will be pruned to build the inference model.
Y
Yu Yang 已提交
185
            Default default_main_program().
186 187 188

    :return: None
    """
F
fengjiayi 已提交
189 190 191 192 193 194 195 196
    if isinstance(feeded_var_names, basestring):
        feeded_var_names = [feeded_var_names]
    else:
        if not (bool(feeded_var_names) and all(
                isinstance(name, basestring) for name in feeded_var_names)):
            raise ValueError("'feed_var_names' should be a list of str.")

    if isinstance(target_vars, Variable):
F
fengjiayi 已提交
197
        target_vars = [target_vars]
F
fengjiayi 已提交
198 199 200 201 202
    else:
        if not (bool(target_vars) and all(
                isinstance(var, Variable) for var in target_vars)):
            raise ValueError("'target_vars' should be a list of Variable.")

203
    if main_program is None:
Y
Yu Yang 已提交
204
        main_program = default_main_program()
205 206 207 208

    if not os.path.isdir(dirname):
        os.makedirs(dirname)

209 210
    pruned_program = main_program.prune(targets=target_vars)
    inference_program = pruned_program.inference_optimize()
211 212 213 214 215
    fetch_var_names = [v.name for v in target_vars]

    model_file_name = dirname + "/__model__"
    with open(model_file_name, "w") as f:
        pickle.dump({
216
            "program_desc_str": inference_program.desc.serialize_to_string(),
217 218 219 220
            "feed_var_names": feeded_var_names,
            "fetch_var_names": fetch_var_names
        }, f, -1)

221 222 223 224 225
    # Save only programDesc of inference_program in binary format
    # in another file: __model__.dat
    with open(model_file_name + ".dat", "wb") as fp:
        fp.write(inference_program.desc.serialize_to_string())

226
    save_params(executor, dirname, main_program)
227 228


229
def load_persistables_if_exist(executor, dirname, main_program=None):
230 231 232 233 234 235 236 237 238 239 240 241
    filenames = next(os.walk(dirname))[2]
    filenames = set(filenames)

    def _is_presistable_and_exist_(var):
        if not is_persistable(var):
            return False
        else:
            return var.name in filenames

    load_vars(
        executor,
        dirname,
242
        main_program=main_program,
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
        vars=None,
        predicate=_is_presistable_and_exist_)


def load_inference_model(dirname, executor):
    """
    Load inference model from a directory

    :param dirname: directory path
    :param executor: executor that load inference model

    :return: [program, feed_var_names, fetch_var_names]
             program: program especially for inference.
             feeded_var_names: Names of variables that need to feed data
             fetch_vars: Variables from which we can get inference results.
    """
    if not os.path.isdir(dirname):
        raise ValueError("There is no directory named '%s'", dirname)

    model_file_name = dirname + "/__model__"
    model = pickle.load(open(model_file_name, "r"))
    program_desc_str = model["program_desc_str"]
    feed_var_names = model["feed_var_names"]
    fetch_var_names = model["fetch_var_names"]
    program = Program.parse_from_string(program_desc_str)
    load_persistables_if_exist(executor, dirname, program)
    fetch_vars = [program.global_block().var(name) for name in fetch_var_names]

    return [program, feed_var_names, fetch_vars]
X
xuwei06 已提交
272 273 274 275 276 277 278 279 280 281


def get_parameter_value(para, executor):
    """
    Get the LoDTensor for the parameter

    :param executor: executor for retrieving the value
    :param para: the given parameter
    :return: the LoDTensor for the parameter
    """
X
xuwei06 已提交
282 283
    assert is_parameter(para)

X
xuwei06 已提交
284 285 286 287 288 289 290 291 292 293 294 295 296
    get_program = Program()
    block = get_program.global_block()
    new_var = _clone_var_in_block_(block, para)
    return executor.run(get_program, feed={}, fetch_list=[new_var])[0]


def get_parameter_value_by_name(name, executor, program=None):
    """
    Get the LoDTensor for paramter with the given name

    :param executor: executor for retrieving the value
    :param name: the name of the parameter
    :param program: the program where the variable is found
Y
Yu Yang 已提交
297
            Default default_main_program().
X
xuwei06 已提交
298 299 300
    :return: the LoDTensor for the variable
    """
    if program is None:
Y
Yu Yang 已提交
301
        program = default_main_program()
X
xuwei06 已提交
302 303
    var = program.global_block().var(name)
    return get_parameter_value(var, executor)