io.py 14.2 KB
Newer Older
D
dzhwinter 已提交
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16
import os

17
from paddle.v2.fluid.evaluator import Evaluator
Y
Yu Yang 已提交
18
from paddle.v2.fluid.framework import Program, Parameter, default_main_program, Variable
K
fix bug  
Kexin Zhao 已提交
19
from . import core
20 21

__all__ = [
22 23 24 25 26 27 28 29 30
    'save_vars',
    'save_params',
    'save_persistables',
    'load_vars',
    'load_params',
    'load_persistables',
    'save_inference_model',
    'load_inference_model',
    'get_inference_program',
31 32 33 34
]


def is_parameter(var):
K
Kavya Srinet 已提交
35
    """Check whether the variable is a Parameter.
36 37 38 39 40 41 42

    This function checks whether the input variable is a Parameter.

    Args:
        var : The input variable.

    Returns:
K
Kavya Srinet 已提交
43
        boolean result whether the variable is a Parameter.
44
    """
45 46 47 48
    return isinstance(var, Parameter)


def is_persistable(var):
49 50 51
    if var.desc.type() == core.VarDesc.VarType.FEED_MINIBATCH or \
       var.desc.type() == core.VarDesc.VarType.FETCH_LIST:
        return False
52 53 54 55 56 57 58 59
    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 已提交
60
        dtype=var.dtype,
61 62 63 64 65
        type=var.type,
        lod_level=var.lod_level,
        persistable=True)


66 67 68 69 70 71
def save_vars(executor,
              dirname,
              main_program=None,
              vars=None,
              predicate=None,
              save_file_name=None):
72 73
    """
    Save variables to directory by executor.
74

75 76
    :param executor: executor that save variable
    :param dirname: directory path
X
xuwei06 已提交
77
    :param main_program: program. If vars is None, then filter all variables in this
78
    program which fit `predicate`. Default default_main_program.
79
    :param predicate: The Predicate describes a callable that returns a variable
80 81
    as a bool. If it returns true, the corresponding input variable will be saved.
    :param vars: variables need to be saved. If vars is specified, program & predicate
82
    will be ignored
83 84 85
    :param save_file_name: The name of a single file that all vars are saved to. 
    If it is None, save variables to separate files.

86 87 88
    :return: None
    """
    if vars is None:
89
        if main_program is None:
Y
Yu Yang 已提交
90
            main_program = default_main_program()
91
        if not isinstance(main_program, Program):
92 93 94 95 96
            raise TypeError("program should be as Program type or None")

        save_vars(
            executor,
            dirname=dirname,
97 98
            vars=filter(predicate, main_program.list_vars()),
            save_file_name=save_file_name)
99 100 101
    else:
        save_program = Program()
        save_block = save_program.global_block()
102 103

        save_var_map = {}
104 105
        for each_var in vars:
            new_var = _clone_var_in_block_(save_block, each_var)
106 107 108 109 110 111 112 113 114 115 116 117 118 119
            if save_file_name is None:
                save_block.append_op(
                    type='save',
                    inputs={'X': [new_var]},
                    outputs={},
                    attrs={'file_path': os.path.join(dirname, new_var.name)})
            else:
                save_var_map[new_var.name] = new_var

        if save_file_name is not None:
            save_var_list = []
            for name in sorted(save_var_map.keys()):
                save_var_list.append(save_var_map[name])

120
            save_block.append_op(
121 122
                type='save_combine',
                inputs={'X': save_var_list},
123
                outputs={},
124 125
                attrs={'file_path': os.path.join(dirname, save_file_name)})

126 127 128
        executor.run(save_program)


129
def save_params(executor, dirname, main_program=None, save_file_name=None):
130 131 132 133 134 135
    """
    Save all parameters to directory with executor.
    """
    save_vars(
        executor,
        dirname=dirname,
136
        main_program=main_program,
137
        vars=None,
138 139
        predicate=is_parameter,
        save_file_name=save_file_name)
140 141


142 143
def save_persistables(executor, dirname, main_program=None,
                      save_file_name=None):
144 145 146 147 148 149
    """
    Save all persistables to directory with executor.
    """
    save_vars(
        executor,
        dirname=dirname,
150
        main_program=main_program,
151
        vars=None,
152 153
        predicate=is_persistable,
        save_file_name=save_file_name)
154 155


156 157 158 159 160 161
def load_vars(executor,
              dirname,
              main_program=None,
              vars=None,
              predicate=None,
              load_file_name=None):
162 163
    """
    Load variables from directory by executor.
164

165
    :param executor: executor that load variable
166
    :param dirname: directory path
X
xuwei06 已提交
167
    :param main_program: program. If vars is None, then filter all variables in this
Y
Yu Yang 已提交
168
    program which fit `predicate`. Default default_main_program().
169
    :param predicate: The Predicate describes a callable that returns a variable
170 171
    as a bool. If it returns true, the corresponding input variable will be loaded.
    :param vars: variables need to be loaded. If vars is specified, program &
172
    predicate will be ignored
173 174 175
    :param load_file_name: The name of the single file that all vars are loaded from.   
    If it is None, load variables from separate files.

176 177 178
    :return: None
    """
    if vars is None:
179
        if main_program is None:
Y
Yu Yang 已提交
180
            main_program = default_main_program()
181
        if not isinstance(main_program, Program):
182 183 184 185 186
            raise TypeError("program's type should be Program")

        load_vars(
            executor,
            dirname=dirname,
187 188
            vars=filter(predicate, main_program.list_vars()),
            load_file_name=load_file_name)
189 190 191
    else:
        load_prog = Program()
        load_block = load_prog.global_block()
192 193

        load_var_map = {}
194 195 196
        for each_var in vars:
            assert isinstance(each_var, Variable)
            new_var = _clone_var_in_block_(load_block, each_var)
197 198 199 200 201 202 203 204 205 206 207 208 209 210
            if load_file_name is None:
                load_block.append_op(
                    type='load',
                    inputs={},
                    outputs={'Out': [new_var]},
                    attrs={'file_path': os.path.join(dirname, new_var.name)})
            else:
                load_var_map[new_var.name] = new_var

        if load_file_name is not None:
            load_var_list = []
            for name in sorted(load_var_map.keys()):
                load_var_list.append(load_var_map[name])

211
            load_block.append_op(
212
                type='load_combine',
213
                inputs={},
214 215
                outputs={"Out": load_var_list},
                attrs={'file_path': os.path.join(dirname, load_file_name)})
216

217 218 219
        executor.run(load_prog)


220
def load_params(executor, dirname, main_program=None, load_file_name=None):
221 222 223 224
    """
    load all parameters from directory by executor.
    """
    load_vars(
225 226 227
        executor,
        dirname=dirname,
        main_program=main_program,
228 229
        predicate=is_parameter,
        load_file_name=load_file_name)
230 231


232 233
def load_persistables(executor, dirname, main_program=None,
                      load_file_name=None):
234 235 236 237
    """
    load all persistables from directory by executor.
    """
    load_vars(
238 239 240
        executor,
        dirname=dirname,
        main_program=main_program,
241 242
        predicate=is_persistable,
        load_file_name=load_file_name)
243 244


245 246
def get_inference_program(target_vars, main_program=None):
    if main_program is None:
Y
Yu Yang 已提交
247
        main_program = default_main_program()
248 249
    if not isinstance(target_vars, list):
        target_vars = [target_vars]
W
wanghaoshuang 已提交
250 251 252
    vars = []
    for var in target_vars:
        if isinstance(var, Evaluator):
W
wanghaoshuang 已提交
253 254
            vars.extend(var.states)
            vars.extend(var.metrics)
W
wanghaoshuang 已提交
255 256 257
        else:
            vars.append(var)
    pruned_program = main_program.prune(targets=vars)
258 259 260 261
    inference_program = pruned_program.inference_optimize()
    return inference_program


262 263 264
def prepend_feed_ops(inference_program,
                     feed_target_names,
                     feed_holder_name='feed'):
K
Kexin Zhao 已提交
265 266
    global_block = inference_program.global_block()
    feed_var = global_block.create_var(
267 268 269
        name=feed_holder_name,
        type=core.VarDesc.VarType.FEED_MINIBATCH,
        persistable=True)
K
Kexin Zhao 已提交
270

271
    for i, name in enumerate(feed_target_names):
K
fix bug  
Kexin Zhao 已提交
272
        out = global_block.var(name)
K
Kexin Zhao 已提交
273 274 275
        global_block.prepend_op(
            type='feed',
            inputs={'X': [feed_var]},
K
fix bug  
Kexin Zhao 已提交
276
            outputs={'Out': [out]},
K
Kexin Zhao 已提交
277 278 279
            attrs={'col': i})


280 281 282
def append_fetch_ops(inference_program,
                     fetch_target_names,
                     fetch_holder_name='fetch'):
K
Kexin Zhao 已提交
283 284
    global_block = inference_program.global_block()
    fetch_var = global_block.create_var(
285 286 287
        name=fetch_holder_name,
        type=core.VarDesc.VarType.FETCH_LIST,
        persistable=True)
K
Kexin Zhao 已提交
288

289
    for i, name in enumerate(fetch_target_names):
K
Kexin Zhao 已提交
290 291 292 293 294 295 296
        global_block.append_op(
            type='fetch',
            inputs={'X': [name]},
            outputs={'Out': [fetch_var]},
            attrs={'col': i})


297 298 299 300
def save_inference_model(dirname,
                         feeded_var_names,
                         target_vars,
                         executor,
301 302
                         main_program=None,
                         save_file_name=None):
303
    """
X
xuwei06 已提交
304
    Build a model especially for inference,
305 306 307 308 309 310
    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 已提交
311
    :param main_program: original program, which will be pruned to build the inference model.
Y
Yu Yang 已提交
312
            Default default_main_program().
313 314
    :param save_file_name: The name of a single file that all parameters are saved to. 
    If it is None, save parameters to separate files.
315 316 317

    :return: None
    """
F
fengjiayi 已提交
318 319 320 321 322 323 324 325
    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 已提交
326
        target_vars = [target_vars]
F
fengjiayi 已提交
327 328 329 330 331
    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.")

332
    if main_program is None:
Y
Yu Yang 已提交
333
        main_program = default_main_program()
334 335 336 337

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

338 339
    pruned_program = main_program.prune(targets=target_vars)
    inference_program = pruned_program.inference_optimize()
340 341
    fetch_var_names = [v.name for v in target_vars]

K
Kexin Zhao 已提交
342 343
    prepend_feed_ops(inference_program, feeded_var_names)
    append_fetch_ops(inference_program, fetch_var_names)
344

345 346 347 348 349 350
    # save for checking
    curstr = inference_program.to_string(True)
    f = open("save_inf_prog_after_feed_fetch.txt", 'w')
    f.write(curstr)
    f.close()

351 352 353
    model_file_name = dirname + "/__model__"
    with open(model_file_name, "wb") as f:
        f.write(inference_program.desc.serialize_to_string())
354

355
    save_persistables(executor, dirname, inference_program, save_file_name)
356 357


358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375
def get_feed_targets_names(program):
    feed_targets_names = []
    global_block = program.global_block()
    for op in global_block.ops:
        if op.desc.type() == 'feed':
            feed_targets_names.insert(0, op.desc.output('Out')[0])
    return feed_targets_names


def get_fetch_targets_names(program):
    fetch_targets_names = []
    global_block = program.global_block()
    for op in global_block.ops:
        if op.desc.type() == 'fetch':
            fetch_targets_names.append(op.desc.input('X')[0])
    return fetch_targets_names


376
def load_inference_model(dirname, executor, load_file_name=None):
377 378 379 380 381
    """
    Load inference model from a directory

    :param dirname: directory path
    :param executor: executor that load inference model
382 383 384
    :param load_file_name: The name of the single file that all parameters are loaded from.   
    If it is None, load parameters from separate files.
    
385
    :return: [program, feed_target_names, fetch_targets]
386
             program: program especially for inference.
387 388
             feed_target_names: Names of variables that need to feed data
             fetch_targets: Variables from which we can get inference results.
389 390 391 392 393
    """
    if not os.path.isdir(dirname):
        raise ValueError("There is no directory named '%s'", dirname)

    model_file_name = dirname + "/__model__"
394 395 396
    with open(model_file_name, "rb") as f:
        program_desc_str = f.read()

397
    program = Program.parse_from_string(program_desc_str)
398
    load_persistables(executor, dirname, program, load_file_name)
399

400 401 402 403 404 405 406
    feed_target_names = get_feed_targets_names(program)
    fetch_target_names = get_fetch_targets_names(program)
    fetch_targets = [
        program.global_block().var(name) for name in fetch_target_names
    ]

    return [program, feed_target_names, fetch_targets]
X
xuwei06 已提交
407 408 409 410 411 412 413 414


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

    :param executor: executor for retrieving the value
    :param para: the given parameter
415

X
xuwei06 已提交
416 417
    :return: the LoDTensor for the parameter
    """
X
xuwei06 已提交
418 419
    assert is_parameter(para)

X
xuwei06 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432
    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 已提交
433
            Default default_main_program().
434

X
xuwei06 已提交
435 436 437
    :return: the LoDTensor for the variable
    """
    if program is None:
Y
Yu Yang 已提交
438
        program = default_main_program()
X
xuwei06 已提交
439 440
    var = program.global_block().var(name)
    return get_parameter_value(var, executor)