Paddle icon indicating copy to clipboard operation
Paddle copied to clipboard

多program互相影响的问题

Open shuoyin opened this issue 6 years ago • 4 comments

hi 我下边这个程序,定义了两个Program,分别在两个Program里定义了一个FC层,名字相同但是输出不同。我理解这两个program里的变量应该是互相不影响的,所以两个program的输出应该也是不同的(虽然他们名字一样),但是实际输出并不是。

import paddle.fluid as fluid
import numpy as np 

prog1 = fluid.Program()
start_prog1 = fluid.Program()
with fluid.program_guard(prog1, start_prog1):
    with fluid.unique_name.guard():
        x = fluid.layers.data(name='x', shape=[-1, 4], dtype='float32')
        y1 = fluid.layers.fc(x, size=1) 

prog2 = fluid.Program()
start_prog2 = fluid.Program()
with fluid.program_guard(prog2, start_prog2):
    with fluid.unique_name.guard():
        x = fluid.layers.data(name='x', shape=[-1, 4], dtype='float32')
        y2 = fluid.layers.fc(x, size=2) 

place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(start_prog1)
exe.run(start_prog2)

feed_x = np.random.rand(3,4).astype('float32')
print feed_x
print exe.run(prog1, feed={'x':feed_x}, fetch_list=[y1])[0]
print exe.run(prog2, feed={'x':feed_x}, fetch_list=[y2])[0]

输出如下:

[[0.15301736 0.47217232 0.43869737 0.00271489]
 [0.4223052  0.5610767  0.5118477  0.180553  ]
 [0.0171026  0.61575365 0.324812   0.45415097]]
[[-0.45586294  0.14294818]
 [-0.71337724  0.3381655 ]
 [-0.23540677  0.6197809 ]]
[[-0.45586294  0.14294818]
 [-0.71337724  0.3381655 ]
 [-0.23540677  0.6197809 ]]

看起来prog2把prog1覆盖了。请问这是什么情况,要怎么解决使得两个program各自分别输出互不影响啊 谢谢

shuoyin avatar Sep 23 '20 07:09 shuoyin

两个fc的名称一样,意味着fc的weight的名字一样,在计算时,fc会默认从fluid.global_scope()里按weight的名字取对应的数值。

所以,两个fc输出结果一样的原因是用了同一个scope,即fluid.global_scope()

如果希望两个program完全独立,需要各自用不同的scope,构造scope的方法如下:

scope = fluid.Scope()

然后将初始化和执行program的代码放在scope_guard block中,如下所示:

scope1 = fluid.Scope()
with fluid.scope_guard(scope1):
    exe.run(start_prog1)
    print exe.run(prog1, feed={'x':feed_x}, fetch_list=[y1])[0]

scope2 = fluid.Scope()
with fluid.scope_guard(scope2):
    exe.run(start_prog1)
    print exe.run(prog1, feed={'x':feed_x}, fetch_list=[y1])[0]    

wanghaoshuang avatar Sep 23 '20 07:09 wanghaoshuang

可以解释一下scope和program的关系吗,我看官网上说

作用域记录了变量名和变量 ( Variable ) 之间的映射关系

我理解program也是保存了变量和变量名的一个空间吧。 我最开始定义prog1和prog2的FC的时候,这两个FC的变量是在哪个scope下边的呢

shuoyin avatar Sep 23 '20 07:09 shuoyin

program是用来存放网络结构的数据结构; scope是用来存放变量数值的dict结构;

我最开始定义prog1和prog2的FC的时候,这两个FC的变量是在哪个scope下边的呢

当你执行exe.run(start_prog1)的时候,start_prog1中的fc的weight会被初始化并放到fluid.global_scope()中。 当你执行exe.run(start_prog2)的时候,start_prog2中的fc的weight会被初始化并放到fluid.global_scope()中,覆盖掉start_prog1创建的同名变量。

wanghaoshuang avatar Sep 23 '20 07:09 wanghaoshuang

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 Sep 28 '21 08:09 paddle-bot-old