PyTorch前向传播nn.Linear用法解析 复刻代码报错求助
研究目标
本研究旨在搭建简化的前向传播模型,完整复刻PyTorch中的前向传播代码结构,全程不依赖任何PyTorch官方库,核心目标是在模拟PyTorch类定义规范的基础上实现矩阵乘法运算。
参考的PyTorch原生前向传播实现
from torch import nn #DEFINE THE REQUIRED CLASS class Network(nn.Module): def __init__(self): super().__init__() # Inputs to hidden layer linear transformation self.hidden = nn.Linear(784, 256) # Output layer, 10 units - one for each digit self.output = nn.Linear(256, 10) # Define sigmoid activation and softmax output self.sigmoid = nn.Sigmoid() self.softmax = nn.Softmax(dim=1) def forward(self, x): # Pass the input tensor through each of our operations x = self.hidden(x) x = self.sigmoid(x) x = self.output(x) x = self.softmax(x) return x #use model = Network() ... ps = model.forward(some_tensor)
自研无依赖复刻的现有代码
class my_mul: def __init__(self, h, w): self.dim1 = h self.dim2 = w self.layer = LAYER(self.dim1, self.dim2) def forward(self, X): X = self.layer.doit( X) return X class LAYER: def __init__(self, h, w): self.dim1 = h self.dim2 = w def __call__(self, Z): self.matrix2 = Z def doit(self, X): self.matrix1 = np.random.rand(self.dim1, self.dim2) print('matrix 1 in class LAYER ',self.matrix1) X = np.matmul(self.matrix1, self.matrix2) import numpy as np # np.random.seed(0) # initialize matrix2 which emulates the tensor being passed down to the forward # propagation step within a deep network training matrix2 = np.random.rand(2,2) print('matrix2 ',matrix2) # # use the __call__ method of LAYER to pass matrix2 to LL LL = LAYER(2,2) LL(matrix2) MM = my_mul(2,2) P = MM.forward(matrix2) print('the product of the 2 matrices is ', P)
运行异常堆栈
matrix2 [[0.5488135 0.71518937] [0.60276338 0.54488318]] matrix 1 in class LAYER [[0.4236548 0.64589411] [0.43758721 0.891773 ]] Traceback (most recent call last): File "all_s.py", line 30, in <module> P = MM.forward(matrix2) File "all_s.py", line 7, in forward X = self.layer.doit( X) File "all_s.py", line 19, in doit X = np.matmul(self.matrix1, self.matrix2) AttributeError: 'LAYER' object has no attribute 'matrix2'
问题根因
- 类内部属性赋值缺失:原
LAYER类的doit方法收到输入参数X后,完全没有将输入赋值给self.matrix2属性,而是直接尝试访问该实例上不存在的属性。 - 对象实例混淆:代码中单独创建的
LL = LAYER(2,2)实例、和my_mul类内部初始化生成的self.layer实例是两个完全独立的对象。前者通过__call__方法存储了输入矩阵,后者从初始化到执行计算的全流程都没有被传入任何输入数据,两个实例的属性完全隔离,进一步放大了属性不存在的问题。 - 调用逻辑偏离PyTorch范式:原复刻代码冗余拆分了输入存储和矩阵乘法的执行流程,没有对齐PyTorch中层被调用时直接完成计算的设计——PyTorch中执行
self.hidden(x)时,会直接把输入x传入层的计算逻辑完成线性变换,不需要单独通过外部实例提前存储输入。 - 维度设计缺失:原代码中生成的随机权重矩阵、和待乘的输入矩阵没有做匹配设计,即使修复了属性报错,后续也会出现矩阵乘法维度不匹配的运行错误。
修复后符合PyTorch结构规范的完整实现
import numpy as np # 模拟PyTorch的nn.Module基类 class Module: def __call__(self, *args, **kwargs): return self.forward(*args, **kwargs) def forward(self, x): raise NotImplementedError # 模拟nn.Linear线性层 class Linear(Module): def __init__(self, in_features, out_features): super().__init__() # 权重形状对齐PyTorch官方实现 self.weight = np.random.randn(out_features, in_features) * 0.01 self.bias = np.zeros(out_features) def forward(self, x): # 矩阵乘法维度对齐:支持批次输入计算 return np.dot(x, self.weight.T) + self.bias # 模拟nn.Sigmoid激活层 class Sigmoid(Module): def forward(self, x): return 1 / (1 + np.exp(-x)) # 模拟nn.Softmax输出层 class Softmax(Module): def __init__(self, dim=1): super().__init__() self.dim = dim def forward(self, x): # 加入数值稳定处理的softmax实现 exp_x = np.exp(x - np.max(x, axis=self.dim, keepdims=True)) return exp_x / np.sum(exp_x, axis=self.dim, keepdims=True) # 完全对齐参考结构的网络定义 class Network(Module): def __init__(self): super().__init__() self.hidden = Linear(784, 256) self.output = Linear(256, 10) self.sigmoid = Sigmoid() self.softmax = Softmax(dim=1) def forward(self, x): x = self.hidden(x) x = self.sigmoid(x) x = self.output(x) x = self.softmax(x) return x # 演示运行流程 if __name__ == "__main__": np.random.seed(0) # 模拟输入:64个样本,每个样本为784维向量 sample_input = np.random.rand(64, 784) model = Network() output = model(sample_input) print(f"前向传播输出形状:{output.shape}")
内容的提问来源于stack exchange,提问作者LP0
相关产品推荐
相关产品推荐

