parameters.py 5.1 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 30 31 32
    """
    The parameters
    """

Y
Yu Yang 已提交
33
    def __init__(self):
Y
Yu Yang 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
        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()

Y
Yu Yang 已提交
56 57 58
    def __iter__(self):
        return iter(self.__param_conf__)

Y
Yu Yang 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72
    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)
Y
Yu Yang 已提交
73 74
                val = val.copyToNumpyArray()
                return val
Y
Yu Yang 已提交
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
                # 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)

Y
Yu Yang 已提交
104 105 106 107 108 109
    def get(self, parameter_name):
        return self.__getitem__(key=parameter_name)

    def set(self, parameter_name, value):
        self.__setitem__(key=parameter_name, value=value)

Y
Yu Yang 已提交
110 111 112 113 114 115 116 117 118 119 120 121
    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
Y
Yu Yang 已提交
122
            self.__gradient_machines__.append(gradient_machine)
Y
Yu Yang 已提交
123 124 125 126


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

Y
Yu Yang 已提交
128 129 130 131 132 133 134 135
    :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 已提交
136

Y
Yu Yang 已提交
137 138 139 140 141 142
    if len(params) == 0:
        raise ValueError("No such parameter")
    elif len(params) > 1:
        raise ValueError("Unexpected branch")
    else:
        return params[0]
Y
Yu Yang 已提交
143 144


Y
Yu Yang 已提交
145
def __copy_parameter_to_gradient_machine__(gradient_machine, name, arr):
Y
Yu Yang 已提交
146
    """
Y
Yu Yang 已提交
147
    Copy a python ndarray into the gradient machine.
Y
Yu Yang 已提交
148

Y
Yu Yang 已提交
149 150 151 152 153
    :param gradient_machine:
    :type gradient_machine: api.GradientMachine
    :param name:
    :param arr:
    :type arr: np.ndarray
Y
Yu Yang 已提交
154
    :return:
Y
Yu Yang 已提交
155
    :rtype: api.Parameter
Y
Yu Yang 已提交
156
    """
Y
Yu Yang 已提交
157 158 159 160
    param = __get_parameter_in_gradient_machine__(gradient_machine, name)
    vec = param.getBuf(api.PARAMETER_VALUE)
    assert isinstance(vec, api.Vector)
    vec.copyFromNumpyArray(arr.flatten())