Paddle icon indicating copy to clipboard operation
Paddle copied to clipboard

switch 的case下能组网么

Open irukawang opened this issue 7 years ago • 17 comments

为使您的问题得到快速解决,在建立Issues前,请您先通过如下方式搜索是否有相似问题:【搜索issue关键字】【使用labels筛选】【官方文档】

如果您没有查询到相似问题,为快速解决您的提问,建立issue时请提供如下细节信息:

  • 标题:简洁、精准概括您的问题
  • 版本、环境信息:    1)PaddlePaddle版本:请提供您的PaddlePaddle版本号,例如1.1或CommitID    2)CPU/GPU:如果您使用GPU训练,请提供GPU驱动版本、CUDA和cuDNN版本号    3)系统环境:请您描述系统类型、版本,例如Mac OS 10.14    4)Python版本号    5)显存信息
  • 复现信息:如为报错,请给出复现环境、复现步骤
  • 问题描述:请详细描述您的问题,同步贴出报错信息、日志/代码关键片段

Thank you for contributing to PaddlePaddle. Before submitting the issue, you could search issue in the github in case that there was a similar issue submitted or resolved before. If there is no solution,please provide us with the following details : System information -PaddlePaddle version (eg.1.1)or CommitID -CPU: including CPUMKL/OpenBlas/MKLDNN version -GPU: including CUDA/cuDNN version -OS Platform and Distribution(eg.Mac OS 10.14) -Python version To Reproduce Steps to reproduce the behavior Describe your current behavior Code to reproduce the issue Other info / logs

版本:paddle1.4 环境:linux

不知switch是否可以如下方式使用

task_ids = fluid.layers.data(name='task_ids', shape=[1], dtype='float32', stop_gradient=False)
    base = fluid.layers.fill_constant([1], dtype='float32', value=2.)
    cond = fluid.layers.equal(task_ids, base)

    param = fluid.layers.create_parameter(shape=[1], dtype="float32")

    output = fluid.layers.create_tensor(dtype="float32")
    with fluid.layers.Switch() as switch:
        with switch.case(cond):
            words_b = fluid.layers.exp(task_ids)
            words_c = fluid.layers.matmul(words_b, param)

            fluid.layers.assign(words_c, output)

        with switch.default():
            words_b = fluid.layers.square(task_ids)
            words_c = fluid.layers.matmul(words_b, param)

            fluid.layers.assign(words_c, output)

    fluid.layers.Print(output)

    c = fluid.layers.mean(output)
    optim = fluid.optimizer.Adam(learning_rate=0.1)
    optim.minimize(c)

    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
    exe.run(fluid.default_startup_program())

    for _ in xrange(10):
        c_ = exe.run(fluid.default_main_program(),
                        feed={"task_ids": np.array([4.]).astype(np.float32)},
                        fetch_list=[c.name])
        print c_[0], c_[0].shape

错误如下
1562068009		Tensor[create_tensor_0]
	shape: [1,]
	dtype: f
	data: -9.99984,
Traceback (most recent call last):
  File "model.py", line 273, in <module>
    fetch_list=[c.name])
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/executor.py", line 565, in run
    use_program_cache=use_program_cache)
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/executor.py", line 642, in _run
    exe.run(program.desc, scope, 0, True, True, fetch_var_name)
paddle.fluid.core.EnforceNotMet: Cannot find original variable with name logical_not_0.tmp_0@GRAD at [/paddle/paddle/fluid/framework/scope.cc:177]
PaddlePaddle Call Stacks:
0       0x7f51fb59f640p void paddle::platform::EnforceNotMet::Init<char const*>(char const*, char const*, int) + 352
1       0x7f51fb59f9b9p paddle::platform::EnforceNotMet::EnforceNotMet(std::__exception_ptr::exception_ptr, char const*, int) + 137
2       0x7f51fd27b6dbp paddle::framework::Scope::RenameInternal(std::string const&, std::string const&) const + 651
3       0x7f51fd27b863p paddle::framework::Scope::Rename(std::string const&) const + 99
4       0x7f51fccfb6f3p paddle::operators::ConditionalBlockGradOp::AssignLocalGradientToGlobal(boost::variant<paddle::platform::CUDAPlace, paddle::platform::CPUPlace, paddle::platform::CUDAPinnedPlace, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_> const&, paddle::framework::Scope const&, std::vector<std::string, std::allocator<std::string> > const&, std::vector<std::string, std::allocator<std::string> > const&) const + 179
5       0x7f51fccfc1c1p paddle::operators::ConditionalBlockGradOp::RunImpl(paddle::framework::Scope const&, boost::variant<paddle::platform::CUDAPlace, paddle::platform::CPUPlace, paddle::platform::CUDAPinnedPlace, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_> const&) const + 913
6       0x7f51fd22f78cp paddle::framework::OperatorBase::Run(paddle::framework::Scope const&, boost::variant<paddle::platform::CUDAPlace, paddle::platform::CPUPlace, paddle::platform::CUDAPinnedPlace, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_> const&) + 332
7       0x7f51fb7148bep paddle::framework::Executor::RunPreparedContext(paddle::framework::ExecutorPrepareContext*, paddle::framework::Scope*, bool, bool, bool) + 382
8       0x7f51fb7156ffp paddle::framework::Executor::Run(paddle::framework::ProgramDesc const&, paddle::framework::Scope*, int, bool, bool, std::vector<std::string, std::allocator<std::string> > const&, bool) + 143
9       0x7f51fb58f35ep
10      0x7f51fb5d272ep
11      0x7f526de15414p PyEval_EvalFrameEx + 25956
12      0x7f526de16160p PyEval_EvalCodeEx + 2240
13      0x7f526de144d1p PyEval_EvalFrameEx + 22049
14      0x7f526de16160p PyEval_EvalCodeEx + 2240
15      0x7f526de144d1p PyEval_EvalFrameEx + 22049
16      0x7f526de16160p PyEval_EvalCodeEx + 2240
17      0x7f526de16272p PyEval_EvalCode + 50
18      0x7f526de3065cp
19      0x7f526de30730p PyRun_FileExFlags + 144
20      0x7f526de31c3cp PyRun_SimpleFileExFlags + 220
21      0x7f526de434fcp Py_Main + 3164
22        0x38bfc21b45p __libc_start_main + 245
23            0x400699p

irukawang avatar Jul 02 '19 11:07 irukawang

麻烦报错信息截全一点,把下面的栈信息截出来

heavengate avatar Jul 02 '19 11:07 heavengate

麻烦报错信息截全一点,把下面的栈信息截出来

已追加

irukawang avatar Jul 02 '19 11:07 irukawang

cond = fluid.layers.equal(task_ids, base)
cond.stop_gradient = True

试下

heavengate avatar Jul 02 '19 11:07 heavengate

cond.stop_gradient = True

还是不行

irukawang avatar Jul 02 '19 11:07 irukawang

错误原因是assign没有梯度,这里不能用assign。 你这种情况没必要用switch吧, fluid.layers.cast把cond转换成float32,和output做word_c做elementwise_mul不就可以了

heavengate avatar Jul 02 '19 12:07 heavengate

错误原因是assign没有梯度,这里不能用assign。 你这种情况没必要用switch吧, fluid.layers.cast把cond转换成float32,和output做word_c做elementwise_mul不就可以了

我具体的网络不是这个样子的,这个就是实验一下可不可以, 我的需求就是类似tf.cond 或者tf.case这种,有多个tensor流入,但是会根据条件选择一个tensor流出,

irukawang avatar Jul 02 '19 12:07 irukawang

错误原因是assign没有梯度,这里不能用assign。 你这种情况没必要用switch吧, fluid.layers.cast把cond转换成float32,和output做word_c做elementwise_mul不就可以了

我具体的网络不是这个样子的,这个就是实验一下可不可以, 我的需求就是类似tf.cond 或者tf.case这种,有多个tensor流入,但是会根据条件选择一个tensor流出,

两种方案:

  1. 不要用assign,直接output = fluid.layers.matmul(words_b, param)
  2. 其实一样的,多个tensor对应多个cond,你选的那个tensor的cond是全1,其余是全0, cast成float之后,各自的tensor和各自的cond相乘再求和

heavengate avatar Jul 02 '19 12:07 heavengate

错误原因是assign没有梯度,这里不能用assign。 你这种情况没必要用switch吧, fluid.layers.cast把cond转换成float32,和output做word_c做elementwise_mul不就可以了

我具体的网络不是这个样子的,这个就是实验一下可不可以, 我的需求就是类似tf.cond 或者tf.case这种,有多个tensor流入,但是会根据条件选择一个tensor流出,

两种方案:

  1. 不要用assign,直接output = fluid.layers.matmul(words_b, param)
  2. 其实一样的,多个tensor对应多个cond,你选的那个tensor的cond是全1,其余是全0, cast成float之后,各自的tensor和各自的cond相乘再求和

很有道理,就是不知道,这个样子的效率如何,好像这样,多个网络都会计算,而不是只计算一条了吧。

irukawang avatar Jul 02 '19 12:07 irukawang

错误原因是assign没有梯度,这里不能用assign。 你这种情况没必要用switch吧, fluid.layers.cast把cond转换成float32,和output做word_c做elementwise_mul不就可以了

我具体的网络不是这个样子的,这个就是实验一下可不可以, 我的需求就是类似tf.cond 或者tf.case这种,有多个tensor流入,但是会根据条件选择一个tensor流出,

两种方案:

  1. 不要用assign,直接output = fluid.layers.matmul(words_b, param)
  2. 其实一样的,多个tensor对应多个cond,你选的那个tensor的cond是全1,其余是全0, cast成float之后,各自的tensor和各自的cond相乘再求和

很有道理,就是不知道,这个样子的效率如何,好像这样,多个网络都会计算,而不是只计算一条了吧。

case里面不要用assign应该是可以的,你可以试下方案1

heavengate avatar Jul 02 '19 12:07 heavengate

错误原因是assign没有梯度,这里不能用assign。 你这种情况没必要用switch吧, fluid.layers.cast把cond转换成float32,和output做word_c做elementwise_mul不就可以了

我具体的网络不是这个样子的,这个就是实验一下可不可以, 我的需求就是类似tf.cond 或者tf.case这种,有多个tensor流入,但是会根据条件选择一个tensor流出,

两种方案:

  1. 不要用assign,直接output = fluid.layers.matmul(words_b, param)
  2. 其实一样的,多个tensor对应多个cond,你选的那个tensor的cond是全1,其余是全0, cast成float之后,各自的tensor和各自的cond相乘再求和

很有道理,就是不知道,这个样子的效率如何,好像这样,多个网络都会计算,而不是只计算一条了吧。

case里面不要用assign应该是可以的,你可以试下方案1

# output = fluid.layers.create_tensor(dtype="float32")
    with fluid.layers.Switch() as switch:
        with switch.case(cond):
            words_b = fluid.layers.exp(task_ids)
            # words_c = fluid.layers.matmul(words_b, param)
            output = fluid.layers.matmul(words_b, param)

            # fluid.layers.assign(words_c, output)


        with switch.default():
            words_b = fluid.layers.square(task_ids)
            # words_c = fluid.layers.matmul(words_b, param)
            output = fluid.layers.matmul(words_b, param)

            # fluid.layers.assign(words_c, output)

    fluid.layers.Print(output)

    c = fluid.layers.mean(output)
    optim = fluid.optimizer.Adam(learning_rate=0.1)
    optim.minimize(c)

    place = fluid.CPUPlace()
    exe = fluid.Executor(place)
    exe.run(fluid.default_startup_program())

    for _ in xrange(10):
        c_ = exe.run(fluid.default_main_program(),
                        feed={"task_ids": np.array([4.]).astype(np.float32)},
                                  fetch_list=[c.name])
好像会因为scope的原因找不到变量呢
错误如下:
Traceback (most recent call last):
  File "model.py", line 268, in <module>
    optim.minimize(c)
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/optimizer.py", line 498, in minimize
    no_grad_set=no_grad_set)
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/optimizer.py", line 403, in backward
    no_grad_set, callbacks)
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/backward.py", line 511, in append_backward
    grad_to_var, callbacks)
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/backward.py", line 318, in _append_backward_ops_
    cb(block=target_block, context=grad_to_var)
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/clip.py", line 87, in error_clip_callback
    fwd_var = block._var_recursive(grad_to_var[grad_n])
  File "/home/wanglongfei02/.jumbo/lib/python2.7/site-packages/paddle/fluid/framework.py", line 1505, in _var_recursive
    raise ValueError("Var {0} is not found recursively".format(name))
ValueError: Var matmul_1.tmp_0 is not found recursively

irukawang avatar Jul 02 '19 12:07 irukawang

output.persistable = True 试下?

heavengate avatar Jul 02 '19 12:07 heavengate

两个matmul的name给一下,让两个output的name一致,然后persistable=True

heavengate avatar Jul 02 '19 12:07 heavengate

两个matmul的name给一下,让两个output的name一致,然后persistable=True 还是不行。诶。。。

irukawang avatar Jul 02 '19 12:07 irukawang

两个matmul的name给一下,让两个output的name一致,然后persistable=True 还是不行。诶。。。

那目前应该只能用方案2了,switch和case的优化问题我记录上报一下

heavengate avatar Jul 02 '19 12:07 heavengate

两个matmul的name给一下,让两个output的name一致,然后persistable=True 还是不行。诶。。。

那目前应该只能用方案2了,switch和case的优化问题我记录上报一下 其实switch能达到ifelse那种功能就行,奈何ifelse不支持嵌套,只能有两种分支,建议咱们这边可以 实现类似tf.cond 或者 tf.case这种op

irukawang avatar Jul 02 '19 12:07 irukawang

请问可以用IfElse分支来实现这样的功能吗 @heavengate

        limit = fluid.layers.fill_constant_batch_size_like(
                input=cond1, shape=[1], value=0, dtype=cond1.dtype)
        cond = fluid.layers.less_than(x=cond1, y=limit)
        ie = fluid.layers.IfElse(cond)
        with ie.true_block():
            ie_input = ie.input(input)
            zero_output = paddle.fluid.layers.zeros(shape=ie_input.shape, dtype=input.dtype)
            ie.output(zero_output)
        with ie.false_block():
            ie_input = ie.input(input)
            op_output = self.conv_bn_layer(input=ie_input, num_filters=filter1, filter_size=5, stride=2, act='relu')
            ie.output(op_output)

        conv1 = ie()[0]

Gaffey avatar Jul 03 '19 03:07 Gaffey

Since you haven't replied for more than a year, we have closed this issue/pr. If the problem is not solved or there is a follow-up one, please reopen it at any time and we will continue to follow up. 由于您超过一年未回复,我们将关闭这个issue/pr。 若问题未解决或有后续问题,请随时重新打开,我们会继续跟进。

paddle-bot-old avatar Jul 06 '20 09:07 paddle-bot-old