从零开始,我决定用14周手撕出一个大模型
·
大家好,我是小琛,从今天开始,我将在14周内,持续学习大模型开发的知识,实现从0到1手撕大模型,欢迎对大模型开发感兴趣的朋友加入!
每日定位
阶段: 14周死磕大模型开发
进度: Day 01 / 99
当前坐标: 第一周·Python核心知识、神经网络必备基础速通
今日格言: “万物皆Tensor,底层见乾坤”
深度学习基础
一、张量
1)tensor(Pytorch)和ndarray(numpy)的本质区别:
ndarry:CPU 内存中的通用数值数组(仅支持CPU不支持GPU加速]
tensor:可自动微分、自动求导、支持GPU加速的计算图节点(计算引擎载体)
2)创建张量,张量属性,检查GPU可用性
import torch
# 创建未初始化的张量
x = torch.empty(2, 3)
print(x)
# 创建随机张量
y = torch.rand(2, 3)
print(y)
# 创建全零张量
z = torch.zeros(3,4)
print(z)
# 从 Python 列表创建张量
d = torch.tensor([7, 8, 9])
print(d)
# 从 NumPy 数组创建张量
import numpy as np
n = np.array([10, 11, 12])
print(n)
# 将 NumPy 数组转换为张量并移动到指定设备
t = torch.from_numpy(n).to(device)
print(t)
# 输出张量的属性
print(t.shape)
print(t.dtype)
print(t.device)
# 检查是否有可用的 GPU 设备
if torch.cuda.is_available():
device = 'cuda'
else:
device = 'cpu'
# 检查 CUDA 可用性和设备数量
print(torch.cuda.is_available())
print(torch.cuda.device_count())
# 输出
tensor([[ 0.0272, -0.0307, -0.0208],
[ 0.0254, -0.0025, 0.0182]])
tensor([[0.0964, 0.5315, 0.1824],
[0.7523, 0.4048, 0.5317]])
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
tensor([7, 8, 9])
[10 11 12]
tensor([10, 11, 12], device='cuda:0')
torch.Size([3])
torch.int64
cuda:0
True
1
3)张量运算
import torch
# 创建 2x3 的张量 x 和 y 在 GPU 上
x = torch.tensor([[1, 2, 3], [4, 5, 6]], device='cuda')
y = torch.tensor([[7, 8, 9], [10, 11, 12]], device='cuda')
z = x + y # 等价于 torch.add(x, y)
print(z)
torch.add(x, y, out=z) # 指定输出张量
print(z)
# 索引(与 NumPy 类似)
print(x[:, 1]) # 所有行的第1列
x = x.view(6) # 变为 6 元素的一维张量
x = x.reshape(2, 3) # 调整形状为 2
print(x)
print(x.device)
# 转换为 NumPy
import numpy as np
# 支持流式编程
n = x.to('cpu').numpy() # 将张量移动到CPU后转换为NumPy数组
print(n.device)
# 输出
tensor([[ 8, 10, 12],
[14, 16, 18]], device='cuda:0')
tensor([[ 8, 10, 12],
[14, 16, 18]], device='cuda:0')
tensor([2, 5], device='cuda:0')
tensor([[1, 2, 3],
[4, 5, 6]], device='cuda:0')
cuda:0
cpu
4)tensor与ndarray的转换:
tensor 转换 ndarray:
import torch
import numpy as np
t = torch.tensor([2, 3]) # 创建一个数据为2,3的tensor向量
print(t)
n = t.numpy()
print(n)
# 输出:
# tensor([2, 3])
# [2 3]
ndarray 转 tensor:
new_n = np.array([5, 6])
print(new_n)
new_t = torch.from_numpy(new_n)
print(new_t)
# 输出
# [5 6]
# tensor([5, 6])
二、自动求导
import torch
x = torch.tensor(2.2, requires_grad=True)
y = x ** 2 + 3 * x + 1
y.backward() # 计算梯度
print(x.grad) # 输出 dy/dx = 2x + 3 = 7.0
x = torch.tensor([2.2, 3.3], requires_grad=True)
y = x ** 2 + 3 * x + 1
# y 现在是 tensor([11., 19.], grad_fn=<AddBackward0>)
# 当 y 是非标量时,需要为 backward() 提供一个 'gradient' 参数
# 通常,如果想计算 y 中每个元素对 x 的梯度之和,可以将 gradient 设为与 y 形状相同的全1张量。
y.backward(gradient=torch.ones_like(y)) # 指定梯度输出的形状
print(x.grad) # 输出 dy/dx = 2x + 3 = [7.0, 9.0]
# 输出
tensor(7.4000)
tensor([7.4000, 9.6000])
三、模型构建
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 256) # 输入层到隐藏层
self.fc2 = nn.Linear(256, 10) # 隐藏层到输出层
def forward(self, x):
x = torch.gelu(self.fc1(x))
x = self.fc2(x)
return x
model = Net()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device) # 将模型移动到 GPU(如果可用)
#输出
Net(
(fc1): Linear(in_features=784, out_features=256, bias=True)
(fc2): Linear(in_features=256, out_features=10, bias=True)
)
四、数据处理
from torch.utils.data import Dataset, DataLoader
# 假设 data 和 labels 是你的数据集和标签
data = [[1, 2], [3, 4], [5, 6]] # 示例数据
labels = [0, 1, 0] # 示例标签
class CustomDataset(Dataset):
def __init__(self, data, labels):
self.data = data
self.labels = labels
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
return self.data[idx], self.labels[idx]
# 创建数据集实例
dataset = CustomDataset(data, labels)
# 创建 DataLoader 实例
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
# 测试 DataLoader
for batch in dataloader:
print(batch)
# 输出
[[tensor([3, 1, 5]), tensor([4, 2, 6])], tensor([1, 0, 0])]
今日提问:
a = np.array([1, 2, 3])
t = torch.from_numpy(a)
a[0] = 999
print(t) 将会输出什么?欢迎在评论区讨论!
预告下一篇:
《神经网络核心概念速通:前向传播、反向传播、损失函数、梯度下降、激活函数》
关于我
笔者正专注于从 Java 转行大模型开发,微信搜索公众号 小琛码不停 ,每日获取最新大模型开发第一手资料哦~~
更多推荐

所有评论(0)