【问题标题】:How does this function: input.nn.MSECriterion_updateOutput(self, input, target) work (in Lua/Torch)?这个函数:input.nn.MSECriterion_updateOutput(self, input, target) 是如何工作的(在 Lua/Torch 中)?
【发布时间】:2015-08-05 02:32:14
【问题描述】:

我有这个功能:

    function MSECriterion:updateOutput(input, target)
        return input.nn.MSECriterion_updateOutput(self, input, target)
    end

现在,

   input.nn.MSECriterion_updateOutput(self, input, target)

返回一个数字。我不知道它是怎么做到的。我在调试器中一步一步走,似乎这只是计算一个没有中间步骤的数字。

 input is a Tensor of size 1 (say, -.234). And the 

 nn.MSECriterion_updateOutput(self, input, target) looks like it is just the function MSECriterion:updateOutput(input, target).

我很困惑这如何计算一个数字。

我对为什么甚至允许这样做感到困惑。参数输入是一个张量,它甚至没有任何名为 nn.MSE input.nn.MSECriterion_updateOutput 的方法。

【问题讨论】:

    标签: function lua lua-table torch


    【解决方案1】:

    当您执行require "nn" 时,这会加载init.lua,而后者又会执行require('libnn')。这是 torch/nn 的 C 扩展。

    如果你查看init.c,你会发现luaopen_libnn:这是当libnn.sorequire-ed 时调用的初始化函数。

    这个函数负责初始化torch/nn的所有部分,包括MSECriterion通过nn_FloatMSECriterion_init(L)nn_DoubleMSECriterion_init(L)的原生部分。

    如果您查看generic/MSECriterion.c,您会发现通用(即为floatdouble 扩展的宏)initialization function

    static void nn_(MSECriterion_init)(lua_State *L)
    {
      luaT_pushmetatable(L, torch_Tensor);
      luaT_registeratname(L, nn_(MSECriterion__), "nn");
      lua_pop(L,1);
    }
    

    这个初始化函数修改任何torch.FloatTensortorch.DoubleTensor 的元表,以便在nn 键下填充一堆函数(有关详细信息,请参阅Torch7 Lua C API)。这些函数是在之前定义的:

    static const struct luaL_Reg nn_(MSECriterion__) [] = {
      {"MSECriterion_updateOutput", nn_(MSECriterion_updateOutput)},
      {"MSECriterion_updateGradInput", nn_(MSECriterion_updateGradInput)},
      {NULL, NULL}
    };
    

    换句话说,任何张量都有这些函数附加,这要归功于它的元表:

    luajit -lnn
    > print(torch.Tensor().nn.MSECriterion_updateOutput)
    function: 0x40921df8
    > print(torch.Tensor().nn.MSECriterion_updateGradInput)
    function: 0x40921e20
    

    注意:对于所有具有 C 本机实现对应的 torch/nn 模块,此机制都是相同的。

    所以input.nn.MSECriterion_updateOutput(self, input, target) 必须调用static int nn_(MSECriterion_updateOutput)(lua_State *L),正如您在generic/MSECriterion.c 上看到的那样。

    此函数计算输入张量之间的均方误差。

    【讨论】:

    • 你怎么知道init.c 用于构建libnn.so?我认为它是由 luarocks 完成的,但我不确定如何...
    • Luarocks 支持 cmake 作为构建类型。如您所见,torch/nn rockspec 使用它。 torch/nn CMakeLists.txt 包含一个 SET(src init.c) 指令。感谢torch cmake extensions,它用于构建libnn 库。
    猜你喜欢
    • 2015-10-10
    • 2016-07-15
    • 1970-01-01
    • 2013-08-01
    • 2013-09-17
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多