Skip to content

Add API: Switch global program #5260

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions python/paddle/v2/framework/framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,5 +538,20 @@ def __init__(self, block, shape, dtype, **kwargs):


# program is a global instance.
g_program = Program()
g_init_program = Program()
g_program_dict = dict()


def switch_g_program(prog, init_prog):
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this API supposed to exposed to PaddlePaddle users? It might be dangerous to expose the fact that we are having two programs -- the main one and the initializer -- to the user at this moment.

I think it is reasonable to have the main program and the initializer program -- the former is like the main function in C/C++, and the latter the C/C++ runtime entry point that initializes the global variables. It is just that we might expose only the main program to the users.

g_program_dict['program'] = prog
g_program_dict['init_program'] = init_prog


def g_program():
Copy link
Collaborator

Choose a reason for hiding this comment

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

g_program => main_program

It seems that the C/C++ code that initializes the global variables is known as "startup code", and the main function is known as the main program. https://gcc.gnu.org/ml/gcc-help/2007-07/msg00097.html

return g_program_dict['program']


def g_init_program():
Copy link
Collaborator

Choose a reason for hiding this comment

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

g_init_program => startup_program

It seems that the C/C++ code that initializes the global variables is known as "startup code", and the main function is known as the main program. https://gcc.gnu.org/ml/gcc-help/2007-07/msg00097.html

return g_program_dict['init_program']


switch_g_program(Program(), Program())
6 changes: 3 additions & 3 deletions python/paddle/v2/framework/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def save_vars(executor, dirname, program=None, vars=None, predicate=None):
"""
if vars is None:
if program is None:
program = g_program
program = g_program()
if not isinstance(program, Program):
raise TypeError("program should be as Program type or None")

Expand Down Expand Up @@ -106,7 +106,7 @@ def load_vars(executor, dirname, program=None, vars=None, predicate=None):
"""
if vars is None:
if program is None:
program = g_program
program = g_program()
if not isinstance(program, Program):
raise TypeError("program's type should be Program")

Expand Down Expand Up @@ -164,7 +164,7 @@ def save_inference_model(dirname,
:return: None
"""
if program is None:
program = g_program
program = g_program()
if not isinstance(target_vars, list):
target_vars = [target_vars]

Expand Down
4 changes: 2 additions & 2 deletions python/paddle/v2/framework/layer_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,15 @@ def name(self):
def program(self):
prog = self.kwargs.get('program', None)
if prog is None:
return g_program
return g_program()
else:
return prog

@property
def init_program(self):
prog = self.kwargs.get('init_program', None)
if prog is None:
return g_init_program
return g_init_program()
else:
return prog

Expand Down
2 changes: 1 addition & 1 deletion python/paddle/v2/framework/tests/test_executor_and_mul.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_mul(self):
tensor_b = core.LoDTensor()
tensor_b.set(b_np, place)
exe = Executor(place)
outs = exe.run(g_program,
outs = exe.run(g_program(),
feed={'a': tensor_a,
'b': tensor_b},
fetch_list=[out])
Expand Down
42 changes: 14 additions & 28 deletions python/paddle/v2/framework/tests/test_fit_a_line.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,24 @@
import numpy as np
import paddle.v2.framework.core as core

import paddle.v2 as paddle
import paddle.v2.framework.layers as layers
import paddle.v2.framework.core as core
import paddle.v2.framework.optimizer as optimizer

from paddle.v2.framework.framework import Program, g_program
from paddle.v2.framework.io import save_persistables, load_persistables
from paddle.v2.framework.executor import Executor

import numpy as np
from paddle.v2.framework.framework import Program, switch_g_program
from paddle.v2.framework.io import save_persistables, load_persistables

init_program = Program()
program = Program()
x = layers.data(
name='x',
shape=[13],
data_type='float32',
program=program,
init_program=init_program)
switch_g_program(program, init_program)
x = layers.data(name='x', shape=[13], data_type='float32')

y_predict = layers.fc(input=x,
size=1,
act=None,
program=program,
init_program=init_program)
y_predict = layers.fc(input=x, size=1, act=None)

y = layers.data(
name='y',
shape=[1],
data_type='float32',
program=program,
init_program=init_program)
y = layers.data(name='y', shape=[1], data_type='float32')

cost = layers.square_error_cost(
input=y_predict, label=y, program=program, init_program=init_program)
avg_cost = layers.mean(x=cost, program=program, init_program=init_program)
cost = layers.square_error_cost(input=y_predict, label=y)
avg_cost = layers.mean(x=cost)

sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.001)
opts = sgd_optimizer.minimize(avg_cost)
Expand All @@ -52,8 +37,8 @@

PASS_NUM = 100
for pass_id in range(PASS_NUM):
save_persistables(exe, "./fit_a_line.model/", program=program)
load_persistables(exe, "./fit_a_line.model/", program=program)
save_persistables(exe, "./fit_a_line.model/")
load_persistables(exe, "./fit_a_line.model/")
for data in train_reader():
x_data = np.array(map(lambda x: x[0], data)).astype("float32")
y_data = np.array(map(lambda x: x[1], data)).astype("float32")
Expand All @@ -71,6 +56,7 @@
fetch_list=[avg_cost])
out = np.array(outs[0])

print out
Copy link
Collaborator

Choose a reason for hiding this comment

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

Remove print?

if out[0] < 10.0:
exit(0) # if avg cost less than 10.0, we think our code is good.
exit(1)
2 changes: 1 addition & 1 deletion python/paddle/v2/framework/tests/test_operator_desc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

class TestOperator(unittest.TestCase):
def test_error_type(self):
block = g_program.create_block()
block = g_program().create_block()
try:
block.append_op()
self.assertFail()
Expand Down
2 changes: 1 addition & 1 deletion python/paddle/v2/framework/tests/test_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

class TestParameter(unittest.TestCase):
def test_param(self):
b = g_program.create_block()
b = g_program().create_block()
param = b.create_parameter(
name='fc.w',
shape=[784, 100],
Expand Down
16 changes: 8 additions & 8 deletions python/paddle/v2/framework/tests/test_program.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,30 @@

class TestProgram(unittest.TestCase):
def test_program(self):
b = g_program.current_block()
b = g_program().current_block()
self.assertEqual(-1, b.parent_idx)
self.assertEqual(0, b.idx)

b = g_program.create_block()
b = g_program().create_block()
self.assertEqual(1, b.idx)
self.assertEqual(0, b.parent_idx)

b = g_program.create_block()
b = g_program().create_block()
self.assertEqual(2, b.idx)
self.assertEqual(1, b.parent_idx)

g_program.rollback()
g_program().rollback()

b = g_program.current_block()
b = g_program().current_block()
self.assertEqual(1, b.idx)
self.assertEqual(0, b.parent_idx)

b = g_program.create_block()
b = g_program().create_block()
self.assertEqual(3, b.idx)
self.assertEqual(1, b.parent_idx)

g_program.rollback()
b = g_program.current_block()
g_program().rollback()
b = g_program().current_block()
self.assertEqual(1, b.idx)
self.assertEqual(0, b.parent_idx)

Expand Down
2 changes: 1 addition & 1 deletion python/paddle/v2/framework/tests/test_rnn_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def test_rnn(self):

out = rnn()
self.assertEqual((-1, 80, 32), out.shape)
print g_program
print g_program()


if __name__ == '__main__':
Expand Down