未验证 提交 ac596a39 编写于 作者: Y Yu Yang 提交者: GitHub

Feature/switch program (#5932)

* Unify fluid submodules to fluid module

Change books just use `import fluid`, not submodules

* Remove g_main_program/g_startup_program

Use default_main_program/default_startup_program instead

* Typo

* Add API for switch default program

* Two functions: switch_main_program/switch_startup_program
* A guard: program_guard. Users can use the `with` statement change
  default programs
* Change unittests in `test_layers`

* Fix CI

* Fix CI

* Fix CI
上级 35453df1
...@@ -3,10 +3,12 @@ import collections ...@@ -3,10 +3,12 @@ import collections
import numpy as np import numpy as np
from . import core from . import core
import proto.framework_pb2 as framework_pb2 import proto.framework_pb2 as framework_pb2
import contextlib
__all__ = [ __all__ = [
'Block', 'Variable', 'Program', 'Operator', 'default_startup_program', 'Block', 'Variable', 'Program', 'Operator', 'default_startup_program',
'default_main_program' 'default_main_program', 'program_guard', 'switch_startup_program',
'switch_main_program'
] ]
...@@ -659,8 +661,83 @@ _startup_program_ = Program() ...@@ -659,8 +661,83 @@ _startup_program_ = Program()
def default_startup_program(): def default_startup_program():
"""
Get default startup program. In startup program, Paddle will initialize
parameters, initialize nccl handle, etc.
Returns:
Program: startup program
"""
return _startup_program_ return _startup_program_
def default_main_program(): def default_main_program():
"""
Get default main program. The main program is used for training or testing.
Returns:
Program: main program
"""
return _main_program_ return _main_program_
def switch_main_program(program):
"""
Switch the main program to a new program.
Args:
program(Program): The new main program
Returns:
Program: The previous main program
"""
global _main_program_
prev_program = _main_program_
_main_program_ = program
return prev_program
def switch_startup_program(program):
"""
Switch the startup program to a new program
Args:
program(Program): The new startup program
Returns:
Program: The previous startup program
"""
global _startup_program_
prev_program = _startup_program_
_startup_program_ = program
return prev_program
@contextlib.contextmanager
def program_guard(main_program, startup_program=None):
"""
Switch program with `with` statement
Examples:
>>> with program_guard(Program()):
>>> data = fluid.layers.data(...)
>>> hidden = fluid.layers.fc(...)
Args:
main_program(Program): New main program inside `with` statement
startup_program(Program): New startup program inside `with` statement.
None means do not change startup program.
Returns:
None
"""
if not isinstance(main_program, Program):
raise TypeError("main_program should be Program")
main_program = switch_main_program(main_program)
if startup_program is not None:
if not isinstance(startup_program, Program):
raise TypeError("startup_program should be Program")
startup_program = switch_startup_program(startup_program)
yield
switch_main_program(main_program)
if startup_program is not None:
switch_startup_program(startup_program)
from __future__ import print_function
import unittest import unittest
import paddle.v2.fluid.layers as layers import paddle.v2.fluid.layers as layers
import paddle.v2.fluid.nets as nets import paddle.v2.fluid.nets as nets
from paddle.v2.fluid.framework import Program from paddle.v2.fluid.framework import Program, program_guard
class TestBook(unittest.TestCase): class TestBook(unittest.TestCase):
def test_fit_a_line(self): def test_fit_a_line(self):
program = Program() program = Program()
x = layers.data( with program_guard(program, startup_program=Program()):
name='x', shape=[13], dtype='float32', main_program=program) x = layers.data(name='x', shape=[13], dtype='float32')
y_predict = layers.fc(input=x, size=1, act=None, main_program=program) y_predict = layers.fc(input=x, size=1, act=None)
y = layers.data(name='y', shape=[1], dtype='float32')
cost = layers.square_error_cost(input=y_predict, label=y)
avg_cost = layers.mean(x=cost)
self.assertIsNotNone(avg_cost)
program.append_backward(avg_cost)
y = layers.data( print(str(program))
name='y', shape=[1], dtype='float32', main_program=program)
cost = layers.square_error_cost(
input=y_predict, label=y, main_program=program)
avg_cost = layers.mean(x=cost, main_program=program)
self.assertIsNotNone(avg_cost)
program.append_backward(avg_cost)
print str(program)
def test_recognize_digits_mlp(self): def test_recognize_digits_mlp(self):
program = Program() program = Program()
with program_guard(program, startup_program=Program()):
# Change g_program, so the rest layers use `g_program` # Change g_program, so the rest layers use `g_program`
images = layers.data( images = layers.data(name='pixel', shape=[784], dtype='float32')
name='pixel', shape=[784], dtype='float32', main_program=program) label = layers.data(name='label', shape=[1], dtype='int32')
label = layers.data( hidden1 = layers.fc(input=images, size=128, act='relu')
name='label', shape=[1], dtype='int32', main_program=program) hidden2 = layers.fc(input=hidden1, size=64, act='relu')
hidden1 = layers.fc(input=images, predict = layers.fc(input=hidden2, size=10, act='softmax')
size=128, cost = layers.cross_entropy(input=predict, label=label)
act='relu', avg_cost = layers.mean(x=cost)
main_program=program) self.assertIsNotNone(avg_cost)
hidden2 = layers.fc(input=hidden1,
size=64, print(str(program))
act='relu',
main_program=program)
predict = layers.fc(input=hidden2,
size=10,
act='softmax',
main_program=program)
cost = layers.cross_entropy(
input=predict, label=label, main_program=program)
avg_cost = layers.mean(x=cost, main_program=program)
self.assertIsNotNone(avg_cost)
print str(program)
def test_simple_conv2d(self): def test_simple_conv2d(self):
program = Program() program = Program()
images = layers.data( with program_guard(program, startup_program=Program()):
name='pixel', images = layers.data(name='pixel', shape=[3, 48, 48], dtype='int32')
shape=[3, 48, 48], layers.conv2d(input=images, num_filters=3, filter_size=[4, 4])
dtype='int32',
main_program=program) print(str(program))
layers.conv2d(
input=images,
num_filters=3,
filter_size=[4, 4],
main_program=program)
print str(program)
def test_conv2d_transpose(self): def test_conv2d_transpose(self):
program = Program() program = Program()
kwargs = {'main_program': program} with program_guard(program):
img = layers.data( img = layers.data(name='pixel', shape=[3, 2, 2], dtype='float32')
name='pixel', shape=[3, 2, 2], dtype='float32', **kwargs) layers.conv2d_transpose(input=img, num_filters=10, output_size=28)
layers.conv2d_transpose( print(str(program))
input=img, num_filters=10, output_size=28, **kwargs)
print str(program)
def test_recognize_digits_conv(self): def test_recognize_digits_conv(self):
program = Program() program = Program()
with program_guard(program, startup_program=Program()):
images = layers.data( images = layers.data(
name='pixel', name='pixel', shape=[1, 28, 28], dtype='float32')
shape=[1, 28, 28], label = layers.data(name='label', shape=[1], dtype='int32')
dtype='float32', conv_pool_1 = nets.simple_img_conv_pool(
main_program=program) input=images,
label = layers.data( filter_size=5,
name='label', shape=[1], dtype='int32', main_program=program) num_filters=2,
conv_pool_1 = nets.simple_img_conv_pool( pool_size=2,
input=images, pool_stride=2,
filter_size=5, act="relu")
num_filters=2, conv_pool_2 = nets.simple_img_conv_pool(
pool_size=2, input=conv_pool_1,
pool_stride=2, filter_size=5,
act="relu", num_filters=4,
main_program=program) pool_size=2,
conv_pool_2 = nets.simple_img_conv_pool( pool_stride=2,
input=conv_pool_1, act="relu")
filter_size=5,
num_filters=4, predict = layers.fc(input=conv_pool_2, size=10, act="softmax")
pool_size=2, cost = layers.cross_entropy(input=predict, label=label)
pool_stride=2, avg_cost = layers.mean(x=cost)
act="relu",
main_program=program) program.append_backward(avg_cost)
predict = layers.fc(input=conv_pool_2, print(str(program))
size=10,
act="softmax",
main_program=program)
cost = layers.cross_entropy(
input=predict, label=label, main_program=program)
avg_cost = layers.mean(x=cost, main_program=program)
program.append_backward(avg_cost)
print str(program)
def test_word_embedding(self): def test_word_embedding(self):
program = Program() program = Program()
dict_size = 10000 with program_guard(program, startup_program=Program()):
embed_size = 32 dict_size = 10000
first_word = layers.data( embed_size = 32
name='firstw', shape=[1], dtype='int64', main_program=program) first_word = layers.data(name='firstw', shape=[1], dtype='int64')
second_word = layers.data( second_word = layers.data(name='secondw', shape=[1], dtype='int64')
name='secondw', shape=[1], dtype='int64', main_program=program) third_word = layers.data(name='thirdw', shape=[1], dtype='int64')
third_word = layers.data( forth_word = layers.data(name='forthw', shape=[1], dtype='int64')
name='thirdw', shape=[1], dtype='int64', main_program=program) next_word = layers.data(name='nextw', shape=[1], dtype='int64')
forth_word = layers.data(
name='forthw', shape=[1], dtype='int64', main_program=program) embed_first = layers.embedding(
next_word = layers.data( input=first_word,
name='nextw', shape=[1], dtype='int64', main_program=program) size=[dict_size, embed_size],
dtype='float32',
embed_first = layers.embedding( param_attr='shared_w')
input=first_word, embed_second = layers.embedding(
size=[dict_size, embed_size], input=second_word,
dtype='float32', size=[dict_size, embed_size],
param_attr='shared_w', dtype='float32',
main_program=program) param_attr='shared_w')
embed_second = layers.embedding(
input=second_word, embed_third = layers.embedding(
size=[dict_size, embed_size], input=third_word,
dtype='float32', size=[dict_size, embed_size],
param_attr='shared_w', dtype='float32',
main_program=program) param_attr='shared_w')
embed_forth = layers.embedding(
embed_third = layers.embedding( input=forth_word,
input=third_word, size=[dict_size, embed_size],
size=[dict_size, embed_size], dtype='float32',
dtype='float32', param_attr='shared_w')
param_attr='shared_w',
main_program=program) concat_embed = layers.concat(
embed_forth = layers.embedding( input=[embed_first, embed_second, embed_third, embed_forth],
input=forth_word, axis=1)
size=[dict_size, embed_size],
dtype='float32', hidden1 = layers.fc(input=concat_embed, size=256, act='sigmoid')
param_attr='shared_w', predict_word = layers.fc(input=hidden1,
main_program=program) size=dict_size,
act='softmax')
concat_embed = layers.concat( cost = layers.cross_entropy(input=predict_word, label=next_word)
input=[embed_first, embed_second, embed_third, embed_forth], avg_cost = layers.mean(x=cost)
axis=1, self.assertIsNotNone(avg_cost)
main_program=program)
print(str(program))
hidden1 = layers.fc(input=concat_embed,
size=256,
act='sigmoid',
main_program=program)
predict_word = layers.fc(input=hidden1,
size=dict_size,
act='softmax',
main_program=program)
cost = layers.cross_entropy(
input=predict_word, label=next_word, main_program=program)
avg_cost = layers.mean(x=cost, main_program=program)
self.assertIsNotNone(avg_cost)
print str(program)
def test_linear_chain_crf(self): def test_linear_chain_crf(self):
program = Program() program = Program()
with program_guard(program, startup_program=Program()):
# Change g_program, so the rest layers use `g_program` images = layers.data(name='pixel', shape=[784], dtype='float32')
images = layers.data( label = layers.data(name='label', shape=[1], dtype='int32')
name='pixel', shape=[784], dtype='float32', main_program=program) hidden = layers.fc(input=images, size=128)
label = layers.data( crf = layers.linear_chain_crf(input=hidden, label=label)
name='label', shape=[1], dtype='int32', main_program=program) self.assertNotEqual(crf, None)
hidden = layers.fc(input=images, size=128, main_program=program)
crf = layers.linear_chain_crf( print(str(program))
input=hidden, label=label, main_program=program)
print str(program)
if __name__ == '__main__': if __name__ == '__main__':
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册