paddle.fluid.io. load_vars ( executor, dirname, main_program=None, vars=None, predicate=None, filename=None ) [source]

Static Graph

This API loads variables from files by executor.

There are two ways to specify the variables to be loaded: the first way, set variables in a list and assign it to the vars; the second way, use the predicate function to select variables that make predicate(variable) == True. The first way has a higher priority.

The dirname is used to specify the folder where to load variables. If variables were saved in separate files in the folder dirname, set filename None. If all variables were saved in a single file, use filename to specify it.

  • executor (Executor) – The executor to run for loading variables.

  • dirname (str) – The folder where to load the variables.

  • main_program (Program, optional) – The program whose variables will be loaded. If it is None, the default main program will be used automatically. Default: None

  • vars (list[Variable], optional) – The list that contains all variables to be loaded. Default: None

  • predicate (function, optional) – The function selects variables that make predicate(variable) == True. Default: None

  • filename (str, optional) – The file which saved all required variables. If variables were saved in separate files, set it to be None. Default: None




import paddle
import paddle.fluid as fluid

main_prog = fluid.Program()
startup_prog = fluid.Program()
with fluid.program_guard(main_prog, startup_prog):
    data = fluid.layers.data(name="img", shape=[64, 784], append_batch_size=False)
    w = fluid.layers.create_parameter(shape=[784, 200], dtype='float32', name='fc_w')
    b = fluid.layers.create_parameter(shape=[200], dtype='float32', name='fc_b')
    hidden_w = fluid.layers.matmul(x=data, y=w)
    hidden_b = fluid.layers.elementwise_add(hidden_w, b)
place = fluid.CPUPlace()
exe = fluid.Executor(place)

# The first usage: using `vars` to specify the variables.
path = "./my_paddle_vars"
var_list = [w, b]
fluid.io.save_vars(executor=exe, dirname=path, vars=var_list,
fluid.io.load_vars(executor=exe, dirname=path, vars=var_list,
# w and b will be loaded, and they are supposed to
# be saved in the same file named 'var_file' in the path "./my_paddle_vars".

# The second usage: using the `predicate` function to select variables
param_path = "./my_paddle_model"
def name_has_fc(var):
    res = "fc" in var.name
    return res
fluid.io.save_vars(executor=exe, dirname=param_path, main_program=main_prog,
                  vars=None, predicate=name_has_fc)
fluid.io.load_vars(executor=exe, dirname=param_path, main_program=main_prog,
                   vars=None, predicate=name_has_fc)
# Load All variables in the `main_program` whose name includes "fc".
# And all the variables are supposed to be saved in separate files.