test_print_op.py 1.9 KB
Newer Older
Y
Yan Chunwei 已提交
1 2
import unittest
import paddle.v2.fluid.core as core
Y
yangyaming 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
from paddle.v2.fluid.executor import Executor
import paddle.v2.fluid.layers as layers
from paddle.v2.fluid.backward import append_backward
from paddle.v2.fluid.framework import switch_main_program
from paddle.v2.fluid.framework import Program
import numpy as np


class TestPrintOpCPU(unittest.TestCase):
    def setUp(self):
        self.place = core.CPUPlace()
        self.x_tensor = core.LoDTensor()
        tensor_np = np.random.random(size=(2, 3)).astype('float32')
        self.x_tensor.set(tensor_np, self.place)
        self.x_tensor.set_lod([[0, 1, 1]])
Y
Yan Chunwei 已提交
18

Y
yangyaming 已提交
19 20 21 22 23 24 25 26
    def build_network(self, only_forward, **kargs):
        x = layers.data('x', shape=[3], dtype='float32', lod_level=1)
        x.stop_gradient = False
        printed = layers.Print(input=x, **kargs)
        if only_forward: return printed
        loss = layers.mean(x=printed)
        append_backward(loss=loss)
        return loss
Y
Yan Chunwei 已提交
27

Y
yangyaming 已提交
28 29 30 31 32 33 34
    def test_forward(self):
        switch_main_program(Program())
        printed = self.build_network(True, print_phase='forward')
        exe = Executor(self.place)
        outs = exe.run(feed={'x': self.x_tensor},
                       fetch_list=[printed],
                       return_numpy=False)
Y
Yan Chunwei 已提交
35

Y
yangyaming 已提交
36 37 38 39 40 41 42
    def test_backward(self):
        switch_main_program(Program())
        loss = self.build_network(False, print_phase='backward')
        exe = Executor(self.place)
        outs = exe.run(feed={'x': self.x_tensor},
                       fetch_list=[loss],
                       return_numpy=False)
Y
Yan Chunwei 已提交
43 44


Y
yangyaming 已提交
45 46 47 48 49 50 51
class TestPrintOpGPU(TestPrintOpCPU):
    def setUp(self):
        self.place = core.CUDAPlace(0)
        self.x_tensor = core.LoDTensor()
        tensor_np = np.random.random(size=(2, 3)).astype('float32')
        self.x_tensor.set(tensor_np, self.place)
        self.x_tensor.set_lod([[0, 1, 1]])
Y
Yan Chunwei 已提交
52 53 54 55


if __name__ == '__main__':
    unittest.main()