通过gModule的torch反向传播。

我有一个如下的图形,其中输入x有两个到达y的路径。它们与使用cMulTable的gModule结合使用。现在,如果我执行gModule:backward(x,y),我会得到一个包含两个值的表。它们对应于从两个路径导出的误差导数吗?

但由于路径2包含其他nn层,我想我需要逐步推导出这个路径中的导数。但是为什么我在dy/dx上得到了一个包含两个值的表?

为了使事情更清晰,测试代码如下:

input1 = nn.Identity()()
input2 = nn.Identity()()
score = nn.CAddTable()({nn.Linear(3, 5)(input1),nn.Linear(3, 5)(input2)})
g = nn.gModule({input1, input2}, {score})  #gModule

mlp = nn.Linear(3,3) #path2 layer

x = torch.rand(3,3)
x_p = mlp:forward(x)
result = g:forward({x,x_p})
error = torch.rand(result:size())
gradient1 = g:backward(x, error)  #this is a table of 2 tensors
gradient2 = g:backward(x_p, error)  #this is also  a table of 2 tensors

那么我的步骤有什么问题吗?

顺便说一句,也许我已经找到了原因,因为g:backward({x,x_p},error)导致相同的表。所以我想这两个值分别代表dy/dx和dy/dx_p。

点赞
用户4850610
用户4850610

我认为你构建gModule时只是简单地犯了一个错误。每个nn.ModulegradInput必须与它的input完全相同,这是反向传播的工作方式。

这是如何使用nngraph创建一个类似你的模块的示例:

require 'torch'
require 'nn'
require 'nngraph'

function CreateModule(input_size)
    local input = nn.Identity()()   -- network input

    local nn_module_1 = nn.Linear(input_size, 100)(input)
    local nn_module_2 = nn.Linear(100, input_size)(nn_module_1)

    local output = nn.CMulTable()({input, nn_module_2})

    -- pack a graph into a convenient module with standard API (:forward(), :backward())
    return nn.gModule({input}, {output})
end

input = torch.rand(30)

my_module = CreateModule(input:size(1))

output = my_module:forward(input)
criterion_err = torch.rand(output:size())

gradInput = my_module:backward(input, criterion_err)
print(gradInput)

更新

正如我所说,每个nn.ModulegradInput必须与其input完全相同。因此,如果您将您的模块定义为nn.gModule({input1,input2},{score}),则gradOutput(后向传递的结果)将是一个关于input1input2的梯度表,在您的情况下为xx_p

唯一的问题是:为什么在调用以下代码时不会出错:

gradient1 = g:backward(x, error)
gradient2 = g:backward(x_p, error)

这将引发一个异常,因为第一个参数必须不是张量,而是一个包含两个张量的表格。嗯,大多数(也许是全部)的torch模块在计算:backward(input,gradOutput)时不使用input 参数(通常它们会存储从上次的:forward(input)调用中的input的副本)。实际上,这个参数是如此没有用,以至于模块甚至不再费心验证它。

2015-11-05 20:31:34