py_func

    • py_func(func, x, out, backward_func=None, skip_vars_in_backward_input=None)[源代码]

    PaddlePaddle Fluid通过py_func在Python端注册OP。py_func的设计原理在于Paddle中的LodTensor与numpy数组可以方便的互相转换,从而可使用Python中的numpy API来自定义一个Python OP。

    该自定义的Python OP的前向函数是 func, 反向函数是 backward_func 。 Paddle将在前向部分调用 func ,并在反向部分调用 backward_func (如果 backward_func 不是None)。 xfunc 的输入,必须为LoDTensor类型; outfunc 的输出, 既可以是LoDTensor类型, 也可以是numpy数组。

    在调用该接口之前,还应正确设置 out 的数据类型和形状,而 outx 对应梯度的数据类型和形状将自动推断而出。

    此功能还可用于调试正在运行的网络,可以通过添加没有输出的 py_func 运算,并在 func 中打印输入 x

    • 参数:
      • func (callable) - 所注册的Python OP的前向函数,运行网络时,将根据该函数与前向输入 x ,计算前向输出 out 。 在 func 建议先主动将LoDTensor转换为numpy数组,方便灵活的使用numpy相关的操作,如果未转换成numpy,则可能某些操作无法兼容。
      • x (Variable|tuple(Variable)|list[Variale]) - 前向函数 的输入,多个LoDTensor以tuple(Variable)或list[Variale]的形式传入,其中Variable为LoDTensor或Tenosr。
      • out (Variable|tuple(Variable)|list[Variale]) - 前向函数 func 的输出,可以为Variable|tuple(Variable)|list[Variale],其中Variable既可以为LoDTensor或Tensor,也可以为numpy数组。由于Paddle无法自动推断 out 的形状和数据类型,必须应事先创建 out
      • backward_func (callable,可选) - 所注册的Python OP的反向函数。默认值为None,意味着没有反向计算。若不为None,则会在运行网络反向时调用 backward_func 计算 x 的梯度。
      • skip_vars_in_backward_input (Variable,可选) - backward_func 的输入中不需要的变量,可以是Variable|tuple(Variable)|list[Variale]。 这些变量必须是 xout 中的一个。默认值为None,意味着没有变量需要从 xout 中去除。若不为None,则这些变量将不是 backward_func 的输入。该参数仅在 backward_func 不为None时有用。

    返回类型: Variable|tuple(Variable)|list[Variable]

    示例代码1:

    1. # 该示例展示了如何将LoDTensor转化为numpy数组,并利用numpy API来自定义一个OP
    2. import paddle.fluid as fluid
    3. import numpy as np
    4.  
    5. def element_wise_add(x, y):
    6. # 必须先手动将LodTensor转换为numpy数组,否则无法支持numpy的shape操作
    7. x = np.array(x)
    8. y = np.array(y)
    9.  
    10. if x.shape != y.shape:
    11. raise AssertionError("the shape of inputs must be the same!")
    12. result = np.zeros(x.shape, dtype='int32')
    13. for i in range(len(x)):
    14. for j in range(len(x[0])):
    15. result[i][j] = x[i][j] + y[i][j]
    16.  
    17. return result
    18.  
    19. def create_tmp_var(name, dtype, shape):
    20. return fluid.default_main_program().current_block().create_var(
    21. name=name, dtype=dtype, shape=shape)
    22.  
    23. def py_func_demo():
    24. start_program = fluid.default_startup_program()
    25. main_program = fluid.default_main_program()
    26.  
    27. # 创建前向函数的输入变量
    28. x = fluid.data(name='x', shape=[2,3], dtype='int32')
    29. y = fluid.data(name='y', shape=[2,3], dtype='int32')
    30.  
    31. # 创建前向函数的输出变量,必须指明变量名称name/数据类型dtype/维度shape
    32.  
    33. # 输入多个LodTensor以list[Variable]或tuple(Variable)形式
    34. fluid.layers.py_func(func=element_wise_add, x=[x,y], out=output)
    35.  
    36. exe=fluid.Executor(fluid.CPUPlace())
    37. exe.run(start_program)
    38.  
    39. # 给program喂入numpy数组
    40. input1 = np.random.randint(1, 10, size=[2,3], dtype='int32')
    41. input2 = np.random.randint(1, 10, size=[2,3], dtype='int32')
    42. out = exe.run(main_program,
    43. feed={'x':input1, 'y':input2},
    44. fetch_list=[output.name])
    45. print("{0} + {1} = {2}".format(input1, input2, out))
    46.  
    47. py_func_demo()
    48.  
    49. # 参考输出:
    50. # [[5, 9, 9] + [[7, 8, 4] = [array([[12, 17, 13]
    51. # [7, 5, 2]] [1, 3, 3]] [8, 8, 5]], dtype=int32)]