Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/python.paddle.v2 #1108

Closed
wants to merge 16 commits into from
76 changes: 34 additions & 42 deletions demo/mnist/api_train.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,42 +6,32 @@

The user api could be simpler and carefully designed.
"""
import py_paddle.swig_paddle as api
from py_paddle import DataProviderConverter
import paddle.trainer.PyDataProvider2 as dp
import numpy as np
import random

import paddle.v2 as paddle

from mnist_util import read_from_mnist
from paddle.trainer_config_helpers import *


def optimizer_config():
settings(
paddle.config.settings(
learning_rate=1e-4,
learning_method=AdamOptimizer(),
learning_method=paddle.config.AdamOptimizer(),
batch_size=1000,
model_average=ModelAverage(average_window=0.5),
regularization=L2Regularization(rate=0.5))
model_average=paddle.config.ModelAverage(average_window=0.5),
regularization=paddle.config.L2Regularization(rate=0.5))


def network_config():
imgs = data_layer(name='pixel', size=784)
hidden1 = fc_layer(input=imgs, size=200)
hidden2 = fc_layer(input=hidden1, size=200)
inference = fc_layer(input=hidden2, size=10, act=SoftmaxActivation())
cost = classification_cost(
input=inference, label=data_layer(
imgs = paddle.config.data_layer(name='pixel', size=784)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

network的config和上边那些optimizer的config是不是分开比较好

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

其实都是生成protobuf的东西。先放到一个包里面了。

hidden1 = paddle.config.fc_layer(input=imgs, size=200)
hidden2 = paddle.config.fc_layer(input=hidden1, size=200)
inference = paddle.config.fc_layer(
input=hidden2, size=10, act=paddle.config.SoftmaxActivation())
cost = paddle.config.classification_cost(
input=inference, label=paddle.config.data_layer(
name='label', size=10))
outputs(cost)


def init_parameter(network):
assert isinstance(network, api.GradientMachine)
for each_param in network.getParameters():
assert isinstance(each_param, api.Parameter)
array_size = len(each_param)
array = np.random.uniform(-1.0, 1.0, array_size).astype('float32')
each_param.getBuf(api.PARAMETER_VALUE).copyFromNumpyArray(array)
paddle.config.outputs(cost)


def generator_to_batch(generator, batch_size):
Expand Down Expand Up @@ -73,42 +63,44 @@ def input_order_converter(generator):


def main():
api.initPaddle("-use_gpu=false", "-trainer_count=4") # use 4 cpu cores
paddle.raw.initPaddle("-use_gpu=false",
"-trainer_count=4") # use 4 cpu cores

# get enable_types for each optimizer.
# enable_types = [value, gradient, momentum, etc]
# For each optimizer(SGD, Adam), GradientMachine should enable different
# buffers.
opt_config_proto = parse_optimizer_config(optimizer_config)
opt_config = api.OptimizationConfig.createFromProto(opt_config_proto)
_temp_optimizer_ = api.ParameterOptimizer.create(opt_config)
opt_config_proto = paddle.config.parse_optimizer(optimizer_config)
opt_config = paddle.raw.OptimizationConfig.createFromProto(opt_config_proto)
_temp_optimizer_ = paddle.raw.ParameterOptimizer.create(opt_config)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

L73 到 L75 看上去是要按照根据一些config信息创建一个optimizer?如果是这样为什么需要 protobuf message 和一个高阶函数 parse_optimizer 呢?是不是下面这样就可以了:

optimizer = paddle.v2.optimizer.Adam(
    learning_rate=1e-4,
    batch_size=1000,
    model_averager=paddle.v2.config.ModelAverage(average_window=0.5),
    regularizator=paddle.v2.regularizer.L2(rate=0.5))

这样也不需要定义 def optimizer_config() 这个函数了。

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

当然,这样更好些。

enable_types = _temp_optimizer_.getParameterTypes()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这一段没看明白——我们需要optimizer吗?为什么只create了一个temproary optimzier,然后取了其中一个property(enable_types),用来生成一个 gradient machine 就完了。我们到底需不需要optimizer这个概念呢?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不需要optimizer这个概念。


# Create Simple Gradient Machine.
model_config = parse_network_config(network_config)
m = api.GradientMachine.createFromConfigProto(
model_config, api.CREATE_MODE_NORMAL, enable_types)
model_config = paddle.config.parse_network(network_config)
m = paddle.raw.GradientMachine.createFromConfigProto(
model_config, paddle.raw.CREATE_MODE_NORMAL, enable_types)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

类似的,如果这里只是要create一个gradient mahcine,貌似应该是:

images  = paddle.v2.layer.data(name='pixel', size=784)
hidden1 = paddle.v2.layer.fc(input=images, size=200)
hidden2 = paddle.v2.layer.fc(input=hidden1, size=200)
classes = paddle.v2.layer.fc(input=hidden2, size=10, act=paddle.config.SoftmaxActivation())
cost    = paddle.v2.cost.classification(
    input=classes, 
    label=paddle.v2.layer.data(name='label', size=10))
gm = paddle.gradient_machine.create(cost)

这样也不需要定义 network_config 函数了?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这样实现,Paddle需要比较大规模的重构。

主要是现在Paddle解析网络配置的过程,是调用fc之类的函数,在这个函数里面写了一个全局的变量。
而传cost的方式,相当于在这个cost变量里,记录了网络的所有拓扑。这需要我们的返回值记录原来全局变量中的信息。

并且,其实还有一个问题,就是有可能一个神经网络会有多个输出值。可能不只有一个cost。使用传函数的办法也并不算非常不优雅。

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

在目前config_parser的实现里边,还必须是一个函数,或者是一个独立的文件,而且这里的改造代价比较大。https://github.com/PaddlePaddle/Paddle/blob/develop/python/paddle/trainer/config_parser.py#L3444
这是一个几千行代码的文件,后续应该是要重构掉的。

Copy link
Collaborator Author

@reyoung reyoung Jan 12, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wangkuiyi 如果确定传变量的方式没有问题的话,那么我们要不就重构一下这个解析了?


# This type check is not useful. Only enable type hint in IDE.
# Such as PyCharm
assert isinstance(m, api.GradientMachine)
assert isinstance(m, paddle.raw.GradientMachine)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我理解如果 m/gm 是上面一行 gm = paddle.v2.gradient_machine.create(...) 这样产生的,读者自然相信 gm 的类型是一个 gradient machine,也就不需要这个 assertation 来增加程序的可读性了。

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这行完全可以不需要。主要是为IDE增加的type信息。常见的IDE可以根据这个type信息做代码提示。

写这行的主要原因是我们用swig生成的python代码。swig并没有按照Python的风格注释函数返回值的类型。如果我们从C-API写的话,就没这个问题了。


# Initialize Parameter by numpy.
init_parameter(network=m)
m.randParameters()
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

randParameters是一个函数吗?按照Python style guide,函数名应该是 randomize_parameters

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

是。但这里因为使用的是SWIG编译的C++头文件,所以还是按照C++的命名方式了。如果用C-API暴露,就没有这个问题了。

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

randParameters是从cpp文件中通过swig暴露出来的接口


# Create Local Updater. Local means not run in cluster.
# For a cluster training, here we can change to createRemoteUpdater
# in future.
updater = api.ParameterUpdater.createLocalUpdater(opt_config)
assert isinstance(updater, api.ParameterUpdater)
updater = paddle.raw.ParameterUpdater.createLocalUpdater(opt_config)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updater = paddle.v2.parameter_updater.create(
    optimizer = paddle.v2.optimizer.Adam(),
    learning_rate=1e-4,
    batch_size=1000,
    model_averager=paddle.v2.config.ModelAverage(average_window=0.5),
    regularizator=paddle.v2.regularizer.L2(rate=0.5))

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

没问题。有道理。

assert isinstance(updater, paddle.raw.ParameterUpdater)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

类似的,如果 updater 是上面一行那样create的,读者应该不依赖这一行来了解updater的类型了。


# Initialize ParameterUpdater.
updater.init(m)

# DataProvider Converter is a utility convert Python Object to Paddle C++
# Input. The input format is as same as Paddle's DataProvider.
converter = DataProviderConverter(
input_types=[dp.dense_vector(784), dp.integer_value(10)])
converter = paddle.data.DataProviderConverter(input_types=[
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里为什么需要暴露一个 converter 出来呢?按照上面comment的解释——把一个Python obj转换为一个C++ obj——这个样的逻辑不应该出现在API里,暴露给用户吧?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

是的,可以封装到数据的Iterator里面。

paddle.data.dense_vector(784), paddle.data.integer_value(10)
])

train_file = './data/raw_data/train'
test_file = './data/raw_data/t10k'
Expand All @@ -130,7 +122,7 @@ def main():

# outArgs is Neural Network forward result. Here is not useful, just passed
# to gradient_machine.forward
outArgs = api.Arguments.createArguments(0)
outArgs = paddle.raw.Arguments.createArguments(0)

for pass_id in xrange(2): # we train 2 passes.
updater.startPass()
Expand Down Expand Up @@ -178,7 +170,7 @@ def main():
test_data_generator = input_order_converter(read_from_mnist(test_file))
for data_batch in generator_to_batch(test_data_generator, 512):
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

如果能写成下面这样会更容易让用户理解:
data_reader = read_from_mnist(test_file)
for data_batch in data_reader:
m.forward(data_batch, outArgs, paddle.raw.PASS_TEST)
...

input_order_converter 和 converter这两个东西会让用户难以理解。用户能做的多半只是照抄代码,但是并不知道为什么要用这些converter. 前面创建optimizer的那段代码也是同样的问题。

一个好的API最好能做到每一步调用都让用户很容易理解为什么要做。

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

有道理。好的。

这两个可以直接patch到forward这个函数里面。

# in testing stage, only forward is needed.
m.forward(converter(data_batch), outArgs, api.PASS_TEST)
m.forward(converter(data_batch), outArgs, paddle.raw.PASS_TEST)
m.eval(test_evaluator)

# print error rate for test data set
Expand All @@ -189,8 +181,8 @@ def main():
updater.catchUpWith()
params = m.getParameters()
for each_param in params:
assert isinstance(each_param, api.Parameter)
value = each_param.getBuf(api.PARAMETER_VALUE)
assert isinstance(each_param, paddle.raw.Parameter)
value = each_param.getBuf(paddle.raw.PARAMETER_VALUE)
value = value.copyToNumpyArray()

# Here, we could save parameter to every where you want
Expand Down
5 changes: 3 additions & 2 deletions python/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ set(OUTPUT_DIR
file(GLOB TRAINER_PY_FILES . ./paddle/trainer/*.py)
file(GLOB HELPERS_PY_FILES . ./paddle/trainer_config_helpers/*.py)
file(GLOB UTILS_PY_FILES . ./paddle/utils/*.py)

file(GLOB V2_PY_FILES . ./paddle/v2/*.py)
set(PY_FILES paddle/__init__.py
${TRAINER_PY_FILES}
${HELPERS_PY_FILES}
${UTILS_PY_FILES})
${UTILS_PY_FILES}
${V2_PY_FILES})

configure_file(${CMAKE_CURRENT_SOURCE_DIR}/setup.py.in
${CMAKE_CURRENT_BINARY_DIR}/setup.py)
Expand Down
1 change: 1 addition & 0 deletions python/paddle/trainer_config_helpers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@
from optimizers import *
from attrs import *
from config_parser_utils import *

# This will enable operator overload for LayerOutput
import layer_math
19 changes: 19 additions & 0 deletions python/paddle/v2/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
This is an experimental package for Paddle new API.

Currently, we use should always use

.. code-block: python

import paddle.v2 as paddle

as our import statement. The API is in flux, never use this package in
production.
"""

import py_paddle.swig_paddle as raw
import config
import data
import paddle.proto as proto

__all__ = ['config', 'data', 'raw', 'proto']
12 changes: 12 additions & 0 deletions python/paddle/v2/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from paddle.trainer_config_helpers import *
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里 import *,让我们丧失了对 paddle.v2 package 里的内容的掌握——只要有人修改了 paddle.trianer_config_helpers 里的内容,这里的symbols就发生变化了吧?

我建议,我们趁此机会,先把 mnist 这个 demo 需要的内容 copy-n-paste 过来。然后依据把 mnist demo 写的让读者能“顾名思义”的原则,修改 copy 过来的库。

随后我们一个一个demo的过,重复上述过程,得到的 paddle.v2 应该就是我们想要的了吧。

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

不过其实paddle.trainer_config_helpers里面暴露的符号是严格控制的。里面使用了__all__来控制符号暴露。

copy and paste这个包,会少暴露非常多东西。比如,我们教程里面的MNIST可能使用全连接做的。用户可能想改成卷积之类的操作。但是,如果只是copy and paste demo需要的接口的话,卷积很可能就没复制过去。这用户就缺乏了这部分灵活性了。

同时,和之前的一个comment类似,如果我们真的需要使用『返回值』而不是『函数』来去定义网络结构的话,那其实所有的配置解析都要重写一下。copy and paste反而不好,不如直接重写一个解析过程。

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我建议copy-n-paste,就是为了“重写”,而不只是为现有symbols在v2 package下面建立一个link。

from paddle.trainer.config_parser import parse_config as parse
from paddle.trainer_config_helpers.config_parser_utils import \
parse_network_config as parse_network
from paddle.trainer_config_helpers.config_parser_utils import \
parse_optimizer_config as parse_optimizer

import paddle.trainer_config_helpers as tmp

__all__ = ['parse', 'parse_network', 'parse_optimizer']

__all__.extend(filter(lambda x: x[:2] != '__', dir(tmp)))
11 changes: 11 additions & 0 deletions python/paddle/v2/data.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from paddle.trainer.PyDataProvider2 import *
from py_paddle.dataprovider_converter import DataProviderConverter

__all__ = [
'dense_vector', 'dense_vector_sequence', 'dense_vector_sub_sequence',
'integer_value', 'integer_sequence', 'integer_value_sub_sequence',
'sparse_binary_vector', 'sparse_binary_vector_sequence',
'sparse_binary_vector_sub_sequence', 'sparse_vector',
'sparse_vector_sequence', 'sparse_vector_sub_sequence', 'provider',
'CacheType', 'DataProviderConverter'
]
3 changes: 2 additions & 1 deletion python/setup.py.in
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ packages=['paddle',
'paddle.proto',
'paddle.trainer',
'paddle.trainer_config_helpers',
'paddle.utils']
'paddle.utils',
'paddle.v2']

setup(name='paddle',
version='${PADDLE_VERSION}',
Expand Down