parameters.py 4.8 KB
Newer Older
Y
Yu Yang 已提交
1 2 3 4
import numpy as np

from paddle.proto.ModelConfig_pb2 import ModelConfig
from paddle.proto.ParameterConfig_pb2 import ParameterConfig
Y
Yu Yang 已提交
5
import py_paddle.swig_paddle as api
Y
Yu Yang 已提交
6

Y
Yu Yang 已提交
7
__all__ = ['Parameters', 'create']
Y
Yu Yang 已提交
8 9


Y
Yu Yang 已提交
10
def create(*topologies):
Y
Yu Yang 已提交
11
    """
Y
Yu Yang 已提交
12
    Create parameter pool by topologies.
Y
Yu Yang 已提交
13

Y
Yu Yang 已提交
14 15
    :param topologies:
    :return:
Y
Yu Yang 已提交
16
    """
Y
Yu Yang 已提交
17 18 19 20 21
    pool = Parameters()
    for topo in topologies:
        if not isinstance(topo, ModelConfig):
            raise ValueError(
                'create must pass a topologies which type is ModelConfig')
Y
Yu Yang 已提交
22

Y
Yu Yang 已提交
23 24 25
        for param in topo.parameters:
            pool.append_config(param)
    return pool
Y
Yu Yang 已提交
26 27


Y
Yu Yang 已提交
28
class Parameters(object):
Y
Yu Yang 已提交
29
    def __init__(self):
Y
Yu Yang 已提交
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        self.__param_conf__ = dict()
        self.__gradient_machines__ = []
        self.__tmp_params__ = []

    def append_config(self, param_conf):
        if not isinstance(param_conf, ParameterConfig):
            raise ValueError("param_conf must be paddle.proto.ParameterConfig")

        if param_conf.name in self.__param_conf__:
            raise ValueError("duplicated parameter %s" % param_conf.name)

        self.__param_conf__[param_conf.name] = param_conf

    def keys(self):
        return self.__param_conf__.keys()

    def names(self):
        return self.keys()

    def has_key(self, key):
        return key in self.__param_conf__.keys()

    def __getitem__(self, key):
        shape = self.get_shape(key)

        if len(self.__gradient_machines__) == 0:
            # create new parameter in python numpy.
            return np.ndarray(shape=shape, dtype=np.float32)
        else:
            for each_gradient_machine in self.__gradient_machines__:
                param = __get_parameter_in_gradient_machine__(
                    each_gradient_machine, key)
                # for simplify implementation now, we always copy from C++
                assert isinstance(param, api.Parameter)
                val = param.getBuf(api.PARAMETER_VALUE)
                assert isinstance(val, api.Vector)
                return val.copyToNumpyArray().reshape(shape=shape)
                # else continue

            raise RuntimeError("Unexpected branch")

    def get_shape(self, key):
        if not isinstance(key, basestring):
            raise ValueError("parameter name should be string")
        if not self.has_key(key):
            raise ValueError("No such parameter %s" % key)
        conf = self.__param_conf__[key]
        return map(int, conf.dims)

    def __setitem__(self, key, value):
        if not isinstance(value, np.ndarray):
            raise ValueError("Must return ndarray")
        value = value.astype(dtype=np.float32)
        shape = self.get_shape(key)
        if not reduce(lambda a, b: a and b,
                      map(lambda x: x[0] == x[1], zip(value.shape, shape))):
            raise ValueError("Value shape mismatch, expect %s, should %s" %
                             (shape, value.shape))

        if len(self.__gradient_machines__) == 0:
            self.__tmp_params__.append((key, value))
        else:
            for each_gradient_machine in self.__gradient_machines__:
                __copy_parameter_to_gradient_machine__(each_gradient_machine,
                                                       key, value)

    def append_gradient_machine(self, gradient_machine):
        if not isinstance(gradient_machine, api.GradientMachine):
            raise ValueError("gradient_machine should be api.GradientMachine")

        if len(self.__tmp_params__) != 0:
            for name, val in self.__tmp_params__:
                try:
                    __copy_parameter_to_gradient_machine__(gradient_machine,
                                                           name, val)
                except ValueError:
                    # If no such parameter in gradient machine, then don't copy
                    pass


def __get_parameter_in_gradient_machine__(gradient_machine, name):
    """
Y
Yu Yang 已提交
112

Y
Yu Yang 已提交
113 114 115 116 117 118 119 120
    :param gradient_machine:
    :type gradient_machine: api.GradientMachine
    :param name:
    :return:
    :rtype: api.Parameter
    """
    params = filter(lambda p: p.getName() == name,
                    gradient_machine.getParameters())
Y
Yu Yang 已提交
121

Y
Yu Yang 已提交
122 123 124 125 126 127
    if len(params) == 0:
        raise ValueError("No such parameter")
    elif len(params) > 1:
        raise ValueError("Unexpected branch")
    else:
        return params[0]
Y
Yu Yang 已提交
128 129


Y
Yu Yang 已提交
130
def __copy_parameter_to_gradient_machine__(gradient_machine, name, arr):
Y
Yu Yang 已提交
131
    """
Y
Yu Yang 已提交
132
    Copy a python ndarray into the gradient machine.
Y
Yu Yang 已提交
133

Y
Yu Yang 已提交
134 135 136 137 138
    :param gradient_machine:
    :type gradient_machine: api.GradientMachine
    :param name:
    :param arr:
    :type arr: np.ndarray
Y
Yu Yang 已提交
139
    :return:
Y
Yu Yang 已提交
140
    :rtype: api.Parameter
Y
Yu Yang 已提交
141
    """
Y
Yu Yang 已提交
142 143 144 145
    param = __get_parameter_in_gradient_machine__(gradient_machine, name)
    vec = param.getBuf(api.PARAMETER_VALUE)
    assert isinstance(vec, api.Vector)
    vec.copyFromNumpyArray(arr.flatten())