创作不易,如果对你有帮助,点个免费的赞
前言:在此系列中,之前手动实现了个神经网络全连接层以及它的反向传播算法,实现过程真的是脑子要裂开了。大模型本质上可以说是一个极其复杂又很长的公式,自己实现代码求解导数的过程对我来说很难,但是最后还是实现了,之前的章节有介绍到求导数对反向传播的逻辑以及意义,有兴趣可以看看,本质上就是求其中一个权重对于结果的影响程度和影响方向。
最近在学习torch很疑惑实现模型代码的过程中,我们只需要定义模型的结构,却不需要手动实现其反向传播的逻辑,真的很神奇,但我还未研究其底层代码实现逻辑,这里只展示一下这个神奇的过程。
一个简单的数学公式,简单编写代码即可求出 x 和 y 对 z 的影响程度和影响方向
import torch
# Define tensors with requires_grad=True to track their operations
x = torch.tensor(1.0, requires_grad=True)
y = torch.tensor(2.0, requires_grad=True)
# 一个简单的数学公式
z = x**2 + y**3
# Perform backpropagation to compute the gradients
z.backward()
# z 分别对x和y求导
print(f"dz/dx: {x.grad}") # Should output 2*x = 2*1 = 2
print(f"dz/dy: {y.grad}") # Should output 3*y^2 = 3*2^2 = 12
就算再复杂的公式,也可以一下子求出来。但是如果你使用到了特别公式,如下图画红线部分,你一定要使用torch给的,例如你写模型结构你使用到了sin函数,你不能自己实现sin函数,否则torch将无法依据链路继续往上求解模型的其他的权重导数,因为根据我之前的实现,求导是一个链式的过程。写到这里,忽然也大概知道其底层的实现逻辑,虽然我没看过源码。
import torch
# Step 1: Define the variables with requires_grad=True
x = torch.tensor(1.0, requires_grad=True) # Example value for x
y = torch.tensor(2.0, requires_grad=True) # Example value for y
z = torch.tensor(3.0, requires_grad=True) # Example value for z
# Step 2: Define the complex function
f = torch.sin(x) * torch.exp(y) + torch.log(z**2 + 1) - torch.sqrt(x * y + z**3)
# Step 3: Compute the gradient
f.backward()
# Now, x.grad, y.grad, and z.grad hold the gradients of f with respect to x, y, and z
print(f"Gradient with respect to x: {x.grad}") # df/dx Gradient with respect to x: tensor(-0.0801)
print(f"Gradient with respect to y: {y.grad}") # df/dy Gradient with respect to y: tensor(7.1892)
print(f"Gradient with respect to z: {z.grad}") # df/dz Gradient with respect to z: tensor(0.2356)