Skip to content

Commit 52a7358

Browse files
dzhwinterreyoung
authored andcommitted
"add asnumpy interface" (#5620)
* "add asnumpy interface" * Just for unittest * Change unittests for numpy I/O * Fix CI
1 parent a619695 commit 52a7358

16 files changed

+166
-126
lines changed

python/paddle/v2/fluid/executor.py

Lines changed: 81 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,38 @@
1+
import numpy as np
12
import paddle.v2.fluid.core as core
23
from paddle.v2.fluid.framework import Block, Program, g_main_program
34

45
g_scope = core.Scope()
56

67

8+
def as_numpy(tensor):
9+
if isinstance(tensor, list):
10+
return [as_numpy(t) for t in tensor]
11+
assert isinstance(tensor, core.LoDTensor)
12+
lod = tensor.lod()
13+
tensor_data = np.array(tensor)
14+
if len(lod) == 0:
15+
ans = tensor_data
16+
else:
17+
raise RuntimeError("LoD Calculate lacks unit tests and buggy")
18+
# elif len(lod) == 1:
19+
# ans = []
20+
# idx = 0
21+
# while idx < len(lod) - 1:
22+
# ans.append(tensor_data[lod[idx]:lod[idx + 1]])
23+
# idx += 1
24+
# else:
25+
# for l in reversed(lod):
26+
# ans = []
27+
# idx = 0
28+
# while idx < len(l) - 1:
29+
# ans.append(tensor_data[l[idx]:l[idx + 1]])
30+
# idx += 1
31+
# tensor_data = ans
32+
# ans = tensor_data
33+
return ans
34+
35+
736
class Executor(object):
837
def __init__(self, places):
938
if not isinstance(places, list) and not isinstance(places, tuple):
@@ -16,14 +45,56 @@ def __init__(self, places):
1645
act_places.append(p)
1746

1847
self.executor = core.Executor(act_places)
48+
self.places = places
49+
50+
def aslodtensor(self, data):
51+
def accumulate(data):
52+
if not isinstance(data, list):
53+
return 1
54+
return sum([accumulate(sub) for sub in data])
55+
56+
def parselod(data):
57+
seq_lens = [accumulate(seq) for seq in data]
58+
cur_len = 0
59+
lod = [cur_len]
60+
for l in seq_lens:
61+
cur_len += l
62+
lod.append(cur_len)
63+
return lod
64+
65+
assert len(self.places) != 0
66+
if not isinstance(data, list):
67+
# pure tensor case
68+
tensor = core.LoDTensor()
69+
tensor.set(data, self.places[0])
70+
return tensor
71+
else:
72+
raise RuntimeError("Current implementation lacks unittests")
73+
# lodtensor case
74+
lod = []
75+
if not isinstance(data[0], list):
76+
lod.append(parselod(data))
77+
flattened_data = np.concatenate(data, axis=0).astype("int64")
78+
else:
79+
while isinstance(data[0], list):
80+
lod.append(parselod(seq))
81+
flattened_data = [item for seq in data for item in seq]
82+
data = flattened_data
83+
flattened_data = np.concatenate(data, axis=0).astype("int64")
84+
flattened_data = flattened_data.reshape([len(flattened_data), 1])
85+
tensor = core.LoDTensor()
86+
tensor.set(flattened_data, self.places[0])
87+
tensor.set_lod(lod)
88+
return tensor
1989

2090
def run(self,
2191
program=None,
2292
feed=None,
2393
fetch_list=None,
2494
feed_var_name='feed',
2595
fetch_var_name='fetch',
26-
scope=None):
96+
scope=None,
97+
return_numpy=True):
2798
if feed is None:
2899
feed = {}
29100
if fetch_list is None:
@@ -52,7 +123,10 @@ def run(self,
52123
inputs={'X': [feed_var]},
53124
outputs={'Out': [out]},
54125
attrs={'col': i})
55-
core.set_feed_variable(scope, feed[name], feed_var.name, i)
126+
cur_feed = feed[name]
127+
if not isinstance(cur_feed, core.LoDTensor):
128+
cur_feed = self.aslodtensor(cur_feed)
129+
core.set_feed_variable(scope, cur_feed, feed_var.name, i)
56130

57131
fetch_var = global_block.create_var(
58132
name=fetch_var_name,
@@ -66,7 +140,11 @@ def run(self,
66140
attrs={'col': i})
67141

68142
self.executor.run(program.desc, scope, 0, True)
69-
return [
143+
outs = [
70144
core.get_fetch_variable(scope, fetch_var_name, i)
71145
for i in xrange(len(fetch_list))
72146
]
147+
148+
if return_numpy:
149+
outs = as_numpy(outs)
150+
return outs
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
image/
22
fit_a_line.model/
3+
tmp

python/paddle/v2/fluid/tests/op_test.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,10 @@ def check_output_with_place(self, place, atol):
261261
feed_map = self.feed_var(inputs, place)
262262

263263
exe = Executor(place)
264-
outs = exe.run(program, feed=feed_map, fetch_list=fetch_list)
264+
outs = exe.run(program,
265+
feed=feed_map,
266+
fetch_list=fetch_list,
267+
return_numpy=False)
265268

266269
for out_name, out_dup in Operator.get_op_outputs(self.op_type):
267270
if out_name not in self.outputs:
@@ -500,5 +503,6 @@ def _get_gradient(self, input_to_check, place, output_names, no_grad_set):
500503

501504
fetch_list = [g for p, g in param_grad_list]
502505
executor = Executor(place)
503-
result = executor.run(prog, feed_dict, fetch_list)
504-
return map(np.array, result)
506+
return map(
507+
np.array,
508+
executor.run(prog, feed_dict, fetch_list, return_numpy=False))

python/paddle/v2/fluid/tests/test_array_read_write_op.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,13 @@ def test_read_write(self):
5252

5353
exe = Executor(cpu)
5454

55-
tensor = core.LoDTensor()
56-
tensor.set(numpy.random.random(size=(100, 100)).astype('float32'), cpu)
57-
58-
outs = map(numpy.array,
59-
exe.run(feed={'x0': tensor,
60-
'x1': tensor,
61-
'x2': tensor},
62-
fetch_list=[a_sum, x_sum],
63-
scope=scope))
55+
tensor = numpy.random.random(size=(100, 100)).astype('float32')
56+
57+
outs = exe.run(feed={'x0': tensor,
58+
'x1': tensor,
59+
'x2': tensor},
60+
fetch_list=[a_sum, x_sum],
61+
scope=scope)
6462
self.assertEqual(outs[0], outs[1])
6563

6664
total_sum = layers.sums(input=[a_sum, x_sum])
@@ -72,12 +70,11 @@ def test_read_write(self):
7270
[each_x.name + "@GRAD" for each_x in x])
7371
g_out = [
7472
item.sum()
75-
for item in map(
76-
numpy.array,
77-
exe.run(feed={'x0': tensor,
78-
'x1': tensor,
79-
'x2': tensor},
80-
fetch_list=g_vars))
73+
for item in exe.run(
74+
feed={'x0': tensor,
75+
'x1': tensor,
76+
'x2': tensor},
77+
fetch_list=g_vars)
8178
]
8279
g_out_sum = numpy.array(g_out).sum()
8380

python/paddle/v2/fluid/tests/test_conditional_block.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,18 +21,15 @@ def test_forward(self):
2121
exe = Executor(cpu)
2222
exe.run(g_startup_program)
2323

24-
x = core.LoDTensor()
25-
x.set(numpy.random.random(size=(10, 1)).astype('float32'), cpu)
24+
x = numpy.random.random(size=(10, 1)).astype('float32')
2625

27-
outs = map(numpy.array, exe.run(feed={'X': x}, fetch_list=[out]))[0]
26+
outs = exe.run(feed={'X': x}, fetch_list=[out])[0]
2827
print outs
2928
loss = layers.mean(x=out)
3029
append_backward_ops(loss=loss)
31-
outs = map(numpy.array,
32-
exe.run(feed={'X': x},
33-
fetch_list=[
34-
g_main_program.block(0).var(data.name + "@GRAD")
35-
]))[0]
30+
outs = exe.run(
31+
feed={'X': x},
32+
fetch_list=[g_main_program.block(0).var(data.name + "@GRAD")])[0]
3633
print outs
3734

3835

python/paddle/v2/fluid/tests/test_executor_and_mul.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import unittest
2-
from paddle.v2.fluid.layers import mul, data
2+
from paddle.v2.fluid.layers import mul, data, sequence_pool
33
import paddle.v2.fluid.core as core
44
from paddle.v2.fluid.executor import Executor
55
from paddle.v2.fluid.framework import g_main_program
@@ -17,17 +17,13 @@ def test_mul(self):
1717
out = mul(x=a, y=b)
1818
place = core.CPUPlace()
1919
a_np = numpy.random.random((100, 784)).astype('float32')
20-
tensor_a = core.LoDTensor()
21-
tensor_a.set(a_np, place)
2220
b_np = numpy.random.random((784, 100)).astype('float32')
23-
tensor_b = core.LoDTensor()
24-
tensor_b.set(b_np, place)
2521
exe = Executor(place)
2622
outs = exe.run(g_main_program,
27-
feed={'a': tensor_a,
28-
'b': tensor_b},
23+
feed={'a': a_np,
24+
'b': b_np},
2925
fetch_list=[out])
30-
out = numpy.array(outs[0])
26+
out = outs[0]
3127
self.assertEqual((100, 100), out.shape)
3228
self.assertTrue(numpy.allclose(out, numpy.dot(a_np, b_np)))
3329

python/paddle/v2/fluid/tests/test_inference_model_io.py

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
import paddle.v2 as paddle
2-
import paddle.v2.fluid.layers as layers
1+
import unittest
2+
3+
import numpy as np
34
import paddle.v2.fluid.core as core
4-
import paddle.v2.fluid.optimizer as optimizer
55

6+
import paddle.v2.fluid.executor as executor
7+
import paddle.v2.fluid.layers as layers
8+
import paddle.v2.fluid.optimizer as optimizer
69
from paddle.v2.fluid.framework import Program
710
from paddle.v2.fluid.io import save_inference_model, load_inference_model
8-
import paddle.v2.fluid.executor as executor
9-
import unittest
10-
import numpy as np
1111

1212

1313
class TestBook(unittest.TestCase):
@@ -44,33 +44,28 @@ def test_fit_line_inference_model(self):
4444
x=cost, main_program=program, startup_program=init_program)
4545

4646
sgd_optimizer = optimizer.SGDOptimizer(learning_rate=0.001)
47-
opts = sgd_optimizer.minimize(avg_cost, init_program)
47+
sgd_optimizer.minimize(avg_cost, init_program)
4848

4949
place = core.CPUPlace()
5050
exe = executor.Executor(place)
5151

5252
exe.run(init_program, feed={}, fetch_list=[])
5353

5454
for i in xrange(100):
55-
x_data = np.array(
55+
tensor_x = np.array(
5656
[[1, 1], [1, 2], [3, 4], [5, 2]]).astype("float32")
57-
y_data = np.array([[-2], [-3], [-7], [-7]]).astype("float32")
57+
tensor_y = np.array([[-2], [-3], [-7], [-7]]).astype("float32")
5858

59-
tensor_x = core.LoDTensor()
60-
tensor_x.set(x_data, place)
61-
tensor_y = core.LoDTensor()
62-
tensor_y.set(y_data, place)
6359
exe.run(program,
6460
feed={'x': tensor_x,
6561
'y': tensor_y},
6662
fetch_list=[avg_cost])
6763

6864
save_inference_model(MODEL_DIR, ["x", "y"], [avg_cost], exe, program)
69-
outs = exe.run(program,
70-
feed={'x': tensor_x,
71-
'y': tensor_y},
72-
fetch_list=[avg_cost])
73-
expected = np.array(outs[0])
65+
expected = exe.run(program,
66+
feed={'x': tensor_x,
67+
'y': tensor_y},
68+
fetch_list=[avg_cost])[0]
7469

7570
reload(executor) # reload to build a new scope
7671
exe = executor.Executor(place)
@@ -83,7 +78,7 @@ def test_fit_line_inference_model(self):
8378
feed={feed_var_names[0]: tensor_x,
8479
feed_var_names[1]: tensor_y},
8580
fetch_list=fetch_vars)
86-
actual = np.array(outs[0])
81+
actual = outs[0]
8782

8883
self.assertEqual(feed_var_names, ["x", "y"])
8984
self.assertEqual(len(fetch_vars), 1)

python/paddle/v2/fluid/tests/test_lod_array_length_op.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def test_array_length(self):
1313
arr_len = layers.array_length(arr)
1414
cpu = core.CPUPlace()
1515
exe = Executor(cpu)
16-
result = numpy.array(exe.run(fetch_list=[arr_len])[0])
16+
result = exe.run(fetch_list=[arr_len])[0]
1717
self.assertEqual(11, result[0])
1818

1919

python/paddle/v2/fluid/tests/test_lod_tensor_array_ops.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -151,10 +151,11 @@ def test_grad(self):
151151

152152
exe = Executor(place)
153153
g_out = [
154-
item.sum()
155-
for item in map(
156-
numpy.array,
157-
exe.run(program, feed={'x': tensor}, fetch_list=[g_vars]))
154+
numpy.array(item).sum()
155+
for item in exe.run(program,
156+
feed={'x': tensor},
157+
fetch_list=[g_vars],
158+
return_numpy=False)
158159
]
159160
g_out_sum = numpy.array(g_out).sum()
160161

python/paddle/v2/fluid/tests/test_mnist_if_else_op.py

Lines changed: 9 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -65,17 +65,10 @@ def test_raw_api(self):
6565
y_data = np.array(map(lambda x: x[1], data)).astype("int64")
6666
y_data = np.expand_dims(y_data, axis=1)
6767

68-
tensor_x = core.LoDTensor()
69-
tensor_x.set(x_data, place)
70-
71-
tensor_y = core.LoDTensor()
72-
tensor_y.set(y_data, place)
73-
74-
outs = map(np.array,
75-
exe.run(kwargs['main_program'],
76-
feed={'x': tensor_x,
77-
'y': tensor_y},
78-
fetch_list=[avg_loss]))
68+
outs = exe.run(kwargs['main_program'],
69+
feed={'x': x_data,
70+
'y': y_data},
71+
fetch_list=[avg_loss])
7972
print outs[0]
8073
if outs[0] < 1.0:
8174
return
@@ -129,19 +122,12 @@ def test_ifelse(self):
129122
for data in train_reader():
130123
x_data = np.array(map(lambda x: x[0], data)).astype("float32")
131124
y_data = np.array(map(lambda x: x[1], data)).astype("int64")
132-
y_data = np.expand_dims(y_data, axis=1)
133-
134-
tensor_x = core.LoDTensor()
135-
tensor_x.set(x_data, place)
136-
137-
tensor_y = core.LoDTensor()
138-
tensor_y.set(y_data, place)
125+
y_data = y_data.reshape((y_data.shape[0], 1))
139126

140-
outs = map(np.array,
141-
exe.run(kwargs['main_program'],
142-
feed={'x': tensor_x,
143-
'y': tensor_y},
144-
fetch_list=[avg_loss]))
127+
outs = exe.run(kwargs['main_program'],
128+
feed={'x': x_data,
129+
'y': y_data},
130+
fetch_list=[avg_loss])
145131
print outs[0]
146132
if outs[0] < 1.0:
147133
return

0 commit comments

Comments
 (0)