Torch Lua中addmm函数定义位置及Lua与C代码关联疑问
addmm Binding to TH C Code Let's break down how the addmm method you're seeing in Linear:updateGradInput connects to the TH library's C implementation—this is a common point of confusion when diving into Torch's internals.
First: addmm is a Tensor Method, Not a Lua Function Defined in the Codebase
When you see self.gradInput:addmm(0, 1, gradOutput, self.weight) in Linear.lua, you're calling a member method of the Torch Tensor object. This method isn't written in Lua—it's a wrapper around a C function from the TH library, exposed to Lua via Torch's Lua/C binding system.
How the Lua-C Binding Works
Torch7 is built on LuaJIT, which has robust support for calling C functions. Here's the high-level flow:
- TH Library Implements Core Logic: The actual matrix multiplication logic for
addmm(short for "add matrix-matrix product") lives in TH's C code. There are type-specific versions (likeTHFloatTensor_addmmorTHDoubleTensor_addmm) inTHTensorMath.cto handle different tensor types (float, double, etc.). - Torch Registers C Functions as Lua Tensor Methods: During Torch's initialization, the core library registers these C functions as methods on the
torch.Tensormetatable. So when you calltensor:addmm(...), Lua looks up the method in the tensor's metatable and invokes the corresponding C function. - Automatic Type Dispatch: The Lua method automatically routes your call to the correct C function based on the tensor's underlying type. For example, a float tensor will use
THFloatTensor_addmm, while a double tensor usesTHDoubleTensor_addmm.
Verifying This Yourself
If you want to confirm this, fire up a Torch Lua shell and run:
print(torch.Tensor.addmm)
You'll see output like function: 0x..., which signals this is a C function (not a Lua-defined function) exposed to the Lua environment.
Why You Can't Find a Lua Definition for addmm
Simply put: there isn't one. All low-level tensor operations in Torch are implemented in C for performance, and only exposed to Lua via bindings. The Linear.lua code just uses these pre-registered methods to handle the computations needed for backpropagation.
内容的提问来源于stack exchange,提问作者krngrvr09

