神经网络-Chap.3
本系列神经网络课程根据Youtube上Andrej Karpathy的系列视频: Neural Networks: Zero to Hero整理而来.
应当可以作为对于LLM进行内部原理理解的入门视频之一.
3.1 引子
上一节, 我们完成了一件伟大的事情!
我们通过一个数据集, 通过两种方式(计数Counting以及神经网络Neural Network)达成了一个目标, 我们根据上一个字母能够预测出下一个字母了.
但我们从结果上来看也确实能明白, 只看前面一个字母不太够. 生成的那几串玩意着实不能算作是名字(笑
这节, 我们要尝试更进一步, 我们要考虑前面更多的字母.
我们试着再用Counting的思路来看看这个问题, 我们会发现这个事情一下子变得超级复杂. 我们如果只考虑前一个字母, 我们上一节中的那个表格是27行.
如果变成了两个字母, 一下子这个表格变成了 27 * 27 行. 我们会发现这个玩意一下子变成了一个指数爆炸的计数方案.
所以本节中, 我们得引入一种新的神经网络模型, 叫做 MLP(Multi-Layer Perceptron) .
额外提一嘴, 读者在看代码的时候还是要参考作者的GitHub Repo: https://github.com/karpathy/makemore
3.2 Rebuilding Dataset
我们现在需要考虑前面的多个字母. 那么第一步, 很遗憾, 我们之前的组织的数据集格式没法用了. 我们得重新组织数据集.
先引入原始数据.
import torch
import torch.nn.functional as F
words = open('names.txt', 'r').read().splitlines()output# words[:8] ['emma', 'olivia', 'ava', 'isabella', 'sophia', 'charlotte', 'mia', 'amelia'] # len(words) 32033
建立字母和数字的映射表.
# build the vucabulary of characters and mapping them to integers
chars = sorted(list(set(''.join(words))))
stoi = {s:i+1 for i, s in enumerate(chars)}
stoi['.'] = 0
itos = {i:s for s, i in stoi.items()}output{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z', 0: '.'}
建立数据集.
# build the dataset
block_size = 3 # context length: how many characters we want to consider in the process of our generation?
X, Y = [], []
for w in words[:5]: # take the first 5 words as examples
print(w)
context = [0] * block_size
for ch in w + '.':
ix = stoi[ch]
X.append(ch)
Y.append(ix)
print(''.join(itos[i] for i in context), '--->' itos[ix])
context = context[1:] + [ix] # corp and append
X = torch.tensor(X)
Y = torch.tensor(Y)output# output emma ... ---> e ..e ---> m .em ---> m emm ---> a mma ---> . olivia ... ---> o ..o ---> l .ol ---> i oli ---> v liv ---> i ivi ---> a via ---> . ava ... ---> a ..a ---> v .av ---> a ava ---> . isabella ... ---> i ..i ---> s .is ---> a isa ---> b sab ---> e abe ---> l bel ---> l ell ---> a lla ---> . sophia ... ---> s ..s ---> o .so ---> p sop ---> h oph ---> i phi ---> a hia ---> . # X tensor([[ 0, 0, 0], [ 0, 0, 5], [ 0, 5, 13], [ 5, 13, 13], [13, 13, 1], [ 0, 0, 0], [ 0, 0, 15], ... [15, 16, 8], [16, 8, 9], [ 8, 9, 1]]) # Y tensor([ 5, 13, 13, 1, 0, 15, 12, 9, 22, 9, 1, 0, 1, 22, 1, 0, 9, 19, 1, 2, 5, 12, 12, 1, 0, 19, 15, 16, 8, 9, 1, 0])
读者可以仔细理解一下这段代码, 本质上它在做的是一个
滑动窗口(Rolling Window)的工作.实在不成问问AI(笑
3.3 Embedding
第二步, 我们需要将我们构造的输入进行向量化, 事实上, 这也是Embedding这一步骤一直在做的事情.
在原论文中, 作者针对了17000个词汇, 进行了一个30维的向量化. 但我们这里的工作要简单许多. 我们只有27个可能性, 所以, 在这里我们不妨选择一个2维的向量就足够了.
C = torch.randn((27, 2))output# C tensor([[ 1.5674, -0.2373], [-0.0274, -1.1008], [ 0.2859, -0.0296], [-1.5471, 0.6049], [ 0.0791, 0.9046], [-0.4713, 0.7868], ... [-0.5177, -0.8141], [ 0.0663, -0.1712], [ 1.0706, 0.3125]])
所以现在我们理应做一个一一映射, 也就是把X中的每个字母映射到对应行的向量上.
写几个循环理论上能很轻松的实现这一点. 幸运的是, pytorch已经完全实现了这个过程, 我们不需要这样做.
emb = C[X]output# emb tensor([[[ 1.5674, -0.2373], [ 1.5674, -0.2373], [ 1.5674, -0.2373]], [[ 1.5674, -0.2373], [ 1.5674, -0.2373], [-0.4713, 0.7868]], [[ 1.5674, -0.2373], [-0.4713, 0.7868], [-0.3120, 0.4518]], ... [[ 0.1425, -0.6312], [ 0.8914, 0.2105], [-0.0274, -1.1008]]]) # emb.shape() torch.Size([32, 3, 2])
这个C[X]做了什么事呢?
作为一个tensor变量, 它会将X中的每个值提取出来, 对C进行映射. 并形成一个映射完毕后的数组.
这个操作有几个坑, 权且为了严谨, 我们尽可能的还是提一下.
首先是, 如果被映射的数组有越界元素(比如
X里面有个30, 超过了C的下标), 会直接报错.
但如果X里面出现了负数, 类似于循环队列, 会从C的后面往前取, 这往往可能造成一些不应当出现的错误.另外, 既然这种映射是以下标为基础的, 所以必然被映射的数组的数据类型一定得是
int, 如果出现了浮点数, 也会直接报错.
新版本的pytorch已经支持了int32, 但有些工具库仍然不支持32位整数. 所以实际中尽可能还是使用int64.
3.4 Hidden Layer
所谓的这个Hidden Layer, 其实本质上就是一次运算, 类似于我们在第一节micrograd中进行的一次y = wx + b. 只不过现在我们面临的问题要稍微复杂一些.
首先我们考虑输入的变量, 也就是这个x. 现在它显然不应该是一个数字:
input ---> output
... ---> numbers of nueruns in hidden layer所以, 输入是三个字符, 而我们前面确认过了, 一个字符是一个二维向量. 所以,对于一条数据, 输入应该是一个 2*3 = 6 的数组.
所以我们应当这样建立weight数组:
W1 = torch.randn((6, 100)) # take 100 nuerons as an example
b1 = torch.randn(100)下一步, 我们遇到的问题是, 这个输入的数组emb, 是一个32*3*2的数组. 我们应该把它进行一个降维的操作, 把它转变成32*6的数组来使得它能够直接与我们的这个weight数组相乘.
这件事情, 在torch中有很多解决方式.
最简单的一种是直接用cat函数:
torch.cat([emb[:, 0, :], emb[:, 1, :], emb[:, 2, :]], 1)outputtensor([[ 1.5674, -0.2373, 1.5674, -0.2373, 1.5674, -0.2373], [ 1.5674, -0.2373, 1.5674, -0.2373, -0.4713, 0.7868], [ 1.5674, -0.2373, -0.4713, 0.7868, -0.3120, 0.4518], ... [ 0.1425, -0.6312, 0.8914, 0.2105, -0.0274, -1.1008]])
cat这个函数允许传入多个想要拼接的torch对象, 并通过指定维度的方式将其对应维度进行拼接操作. 但这种方案有个问题:
我们上面的这个代码是基于block_size = 3的情况写的. 如果这玩意变了, 我们还得手动改代码.
所以我们实际上是要对这个emb先进行针对其第一维度的拆分, 随后再用cat函数进行合并, 幸运的是, torch仍然给了这个功能:
torch.cat(torch.unbind(emb, 1), 1)unbind函数会根据传入的维度, 将对应的torch对象进行拆分, 并返回一个list(在上文中, 也就是前面我们传入的那个[emb[:, 0, :], emb[:, 1, :], emb[:, 2, :]]).
上面的代码已经能解决我们的问题, 但是还有更高效的解决方案:
emb.view(32, 6)outputtensor([[ 1.5674, -0.2373, 1.5674, -0.2373, 1.5674, -0.2373], [ 1.5674, -0.2373, 1.5674, -0.2373, -0.4713, 0.7868], [ 1.5674, -0.2373, -0.4713, 0.7868, -0.3120, 0.4518], ... [ 0.1425, -0.6312, 0.8914, 0.2105, -0.0274, -1.1008]])
view函数能够让一个torch对象中的元素以我们传入的方式进行重排列. 这是因为本质在计算机内存中, tensor对象内部的元素仍然是以线性表的格式存储的, 而维度的改变或创建, 其实只是更改了这个torch本身的一些attribute. 总之, view函数能够以更加高效, 更加便捷的方式来改变这些值.
view相比于刚刚的cat来说, 除了操作简单, 还有些别的好处:
view函数本身是Zero Copy, 也就是原地复制.cat需要在内存中新malloc出一片位置.view可以通过传入值-1来自动求某一维度的值. 也就是说刚刚的代码也可以直接写成:emb.view(-1, 6)
所以, 现在得到Hidden Layer的结果就很简单了:
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)output# h.shape() torch.Size([32, 100]) # h tensor([[-0.6614, -0.4457, 1.8936, ..., 3.0503, -1.0967, 0.6217], [-2.2609, -1.6344, 2.0673, ..., 2.0218, -1.4204, 1.6971], [ 0.7078, 1.4857, 1.8753, ..., 1.8343, 0.7811, 0.0421], ..., [ 3.2790, -4.2715, 4.5682, ..., 1.5552, -4.8461, 4.0639], [-1.5379, -0.9901, 1.0622, ..., 3.3071, 1.9993, 0.9852], [ 1.1637, -1.1451, -1.7129, ..., 1.2161, -2.4059, 0.4325]])
3.5 Output Layer
有刚刚的讲述, Output Layer要做的事情就非常简单, 且容易理解了:
W2 = torch.randn((100, 27)) # 27 possiblities of output
b2 = torch.randn(27)
logits = h @ W2 + b2output# logits.size() torch.Size([32, 27]) # logits tensor([[ -2.7089, 2.4772, 13.5240, -10.1370, 2.2995, 5.8828, -13.0180, 9.0839, 2.9229, 9.5662, 13.3377, -2.6514, -8.9848, 10.7011, -0.0634, -0.1430, 16.9297, -12.9581, -6.0219, -4.3970, -12.3881, 1.7148, 2.8595, -2.3126, -10.8813, 4.0471, 10.2728], [ -4.3219, -5.0109, 1.3675, -5.7973, 1.4368, -8.3227, -2.2152, 20.2000, 10.9026, 10.8394, 0.4914, 2.6188, -4.4259, 3.8898, -2.3895, -3.2129, -1.3941, -3.1875, -3.9822, 10.4584, -1.8025, 6.0152, -9.8757, 2.0277, -2.0008, -7.0103, 12.3840], ...])
3.6 NLL
第三次提这个词了奥, 应该记住了(NLL, Negative Log Likelihood).
counts = logits.exp()
prob = counts / counts.sum(1, keepdim = True)
loss = -prob[torch.arenge(32), Y].log().mean()output#prob.size() torch.Size([32, 27]) # loss tensor(17.2955)
正常来说, forward流程到这里就结束了. 就是有一点还是不够方便, 这个NLL, 每次都要写这么一茬, 有点费劲.
那自然又要请出我们伟大的pytorch.
loss = F.cross_entropy(logits, Y)output# loss tensor(17.2955)
Pytorch通过
cross_entropy这个函数能够直接根据logits和预期输出数组来计算loss, 它是一个非常常用的封装函数.
使用它而不是我们自己重复造轮子的理由有三:
- 首先, 它更省内存, 时间与空间上的复杂度更低.
- 第二, 它有完善的防上溢机制. 它在计算
exp步骤前, 会在每行的元素上减去改行的最大值.(同减一个值, 对概率没有影响)- 第三, 它在
backwards的过程中能够进行自动化简, 效率更高.
3.7 backward
这一步如果读者阅读过上一节, 应该理解起来很容易了:
# backward
parameters = [C, W1, W2, b1, b2]
for p in parameters:
p.grad = None
loss.backward()
# update
for p in parameters:
p.data += -0.1 * p.grad至此, 我们应该可以把前向和后向的代码都总结一下:
import torch
import torch.nn.functional as F
words = open('names.txt', 'r').read().splitlines()
chars = sorted(list(set(''.join(words))))
stoi = {s: i + 1 for i, s in enumerate(chars)}
stoi['.'] = 0
itos = {i: s for s, i in stoi.items()}
# dataset construct
block_size = 3
X, Y = [], []
for w in words[:5]:
context = [0] * block_size
for ch in w + '.':
ix = stoi[ch]
X.append(context)
Y.append(ix)
context = context[1:] + [ix]
X = torch.tensor(X)
Y = torch.tensor(Y)
# parameters init
g = torch.Generator().manual_seed(2147483647)
C = torch.randn((27, 2), generator=g)
W1 = torch.randn((6, 100), generator=g)
b1 = torch.randn(100, generator=g)
W2 = torch.randn((100, 27), generator=g)
b2 = torch.randn(27, generator=g)
parameters = [C, W1, b1, W2, b2]
for p in parameters:
p.requires_grad = True
for _ in range(10):
# forward
emb = C[X]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Y)
print(loss.item())
# backward
for p in parameters:
p.grad = None
loss.backward()
# update
for p in parameters:
p.data += -0.1 * p.grad3.8 Minibatch
上面的代码已经很完善了. 但我们实际在全测试集上进行运行时, 会发现一个比较尴尬的问题: 这个loss算的有点太慢了.
我们的全数据集只有228k左右的大小, 尚且需要1-2s才能真正算出一个loss, 在更大的数据集上进行训练, 这个代价几乎是不可估量的.
这事情在真正的训练上时, 通常会采用被称为minibatch的方法. 顾名思义, 我们在算loss的时候只进行少量的取样计算:
for w in words: # full dataset
context = [0] * block_size
...
for _ in range(10):
# minibatch construct
ix = torch.randint(0, X.shape[0], (32, )) # pull 32 random row in torch X
# forward
emb = C[X[ix]]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Y[ix]) # compare the 32 rows results with corrsponding Y
print(loss.item())
# backward
for p in parameters:
p.grad = None
loss.backward()
# update
for p in parameters:
p.data += -0.1 * p.grad这里只算是举个例子, 所以取了一个很小的样本量
32
在现实训练流程中, 这个例子应当比我们想的要大很多, 大到足够表现整体数据集合在当前参数上的准确率, 同时又不会过于拖慢训练以及loss计算的速度.
3.9 Learning Rate Range Test
我们上面对参数的更改幅度, 实际上并没有经过严格的讨论, 我们好像只是拍了下脑袋, 写了个-0.1上去.
这个玩意, 在这个领域叫做Learning Rate. 显然, 这个东西该取多少是有讲究的, 绝对值太小了, 会导致我们的训练速度非常慢, 绝对值太大了, 则过犹不及, 反而会把loss往大了推.
所以, 我们需要先对不同的learning rate进行尝试. 但这里有个坑, 我们不能直接均分.
假设我们的取值范围希望放在[0.001, 1.0]之间, 如果我们直接均分:
torch.linspace(0.001, 1.0, 1000)outputtensor([0.0010, 0.0020, 0.0030, 0.0040, 0.0050, 0.0060, ... 0.9950, 0.9960, 0.9970, 0.9980, 0.9990, 1.0000])
如果像这样直接线性均分, 0.001~0.01这种小学习率区间被几步略过了, 这显然不符合我们的认知.
更加理想的情况应当是: 0.001~0.01, 0.01~0.1, 0.1~1各占三分之一的取样. 要实现这个方式, 需要引入指数均匀采样:
lre = torch.linspace(-3, 0, 1000)
lrs = 10**lreoutput# lrs tensor([0.0010, 0.0010, 0.0010, 0.0010, 0.0010, 0.0010, ... 0.9660, 0.9727, 0.9795, 0.9863, 0.9931, 1.0000])
即, 在指数上进行均匀取样, 再进行指数运算作为learning rate, 显然这样的取样方式要均匀许多.
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
words = open('names.txt', 'r').read().splitlines()
chars = sorted(list(set(''.join(words))))
stoi = {s: i + 1 for i, s in enumerate(chars)}
stoi['.'] = 0
itos = {i: s for s, i in stoi.items()}
block_size = 3
X, Y = [], []
for w in words:
context = [0] * block_size
for ch in w + '.':
ix = stoi[ch]
X.append(context)
Y.append(ix)
context = context[1:] + [ix]
X = torch.tensor(X)
Y = torch.tensor(Y)
g = torch.Generator().manual_seed(2147483647)
C = torch.randn((27, 2), generator=g)
W1 = torch.randn((6, 100), generator=g)
b1 = torch.randn(100, generator=g)
W2 = torch.randn((100, 27), generator=g)
b2 = torch.randn(27, generator=g)
parameters = [C, W1, b1, W2, b2]
for p in parameters:
p.requires_grad = True
lre = torch.linspace(-3, 0, 1000)
lrs = 10**lre
lri = []
lossi = []
for i in range(1000):
ix = torch.randint(0, X.shape[0], (32,))
emb = C[X[ix]]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Y[ix])
for p in parameters:
p.grad = None
loss.backward()
lr = lrs[i]
for p in parameters:
p.data += -lr * p.grad
lri.append(lre[i])
lossi.append(loss.item())
plt.plot(lri, lossi)如果我们画个图, 能看到这样的图像:
从图上其实可以看出, 我们把LRE取在[-1.0, -0.5]之间, 貌似都是比较合适的值.
3.10 Train / Validation / Test Set
在真正的训练中, 通常我们不会将整个数据集都作为训练数据, 这是因为我们如果只针对训练集做优化, 非常容易出现 过拟合(Overfitting) 的现象, 即模型通过大量参数, 只针对数据集进行针对性记忆, 而无法对数据集以外的数据进行有效的回复(类似于死记硬背?).
所以, 比较常用的方案是将测试以及评测所用到的集合分开, 常用的分割法是:
- Train Set : 用于优化参数(Parameters)
- Validation Set : 用于优化超参数(Hyper Parameters)
- Test Set : 用于检验模型训练的结果
所谓 超参数 , 指的是神经网络每层有几个神经元, Embedding过程中将一个字母表示为几个维度的向量. 在训练初期就确定好, 并且在整个参数优化过程中不会改变的值.
所以, 我们可以按照这个思路来改造我们的代码:
import random
# ... (前文读取 words 与构建 stoi / itos 词表的代码保持不变) ...
# Build dataset
def build_dataset(words):
block_size = 3
X, Y = [], []
for w in words:
context = [0] * block_size
for ch in w + '.':
ix = stoi[ch]
X.append(context)
Y.append(ix)
context = context[1:] + [ix]
X = torch.tensor(X)
Y = torch.tensor(Y)
print(X.shape, Y.shape)
return X, Y
random.seed(42)
random.shuffle(words)
n1 = int(0.8 * len(words))
n2 = int(0.9 * len(words))
Xtr, Ytr = build_dataset(words[:n1])
Xdev, Ydev = build_dataset(words[n1:n2])
Xte, Yte = build_dataset(words[n2:])
# ... (初始化 g, C, W1, b1, W2, b2 并设置 p.requires_grad = True,与前文一致) ...
# Training
for i in range(40000):
ix = torch.randint(0, Xtr.shape[0], (32,))
emb = C[Xtr[ix]]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Ytr[ix])
# ... (清空梯度 p.grad = None 与反向传播 loss.backward(),与前文一致) ...
lr = 0.1 if i < 30000 else 0.01
for p in parameters:
p.data += -lr * p.grad
# Evaluation
emb = C[Xtr]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss_tr = F.cross_entropy(logits, Ytr)
print('train loss:', loss_tr.item())
emb = C[Xdev]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss_dev = F.cross_entropy(logits, Ydev)
print('dev loss: ', loss_dev.item())outputtrain loss: 2.331170082092285 dev loss: 2.3310039043426514
通常而言, 如果train loss与dev loss几乎一致, 说明模型在面对新题目和旧题目时表现几乎一致. 这代表着模型在当前规模下几乎没有过拟合的风险.
但与此同时, 我们注意到我们的loss还是偏高, 这个状态又被称为 欠拟合(Underfitting) , 通常这意味着我们需要增大模型的规模来获得更好的结果.
train loss | val loss | 诊断结论 | 参数调整策略 |
|---|---|---|---|
| 偏高 | 偏高(≈ train) | 欠拟合 | 扩大参数规模 |
| 偏高 | 更高(> train) | 欠拟合 + 过拟合 | 不可盲目扩参 |
| 很低 | 偏高(> train) | 过拟合 | 不可扩参 |
| 极低(近理论下界) | 极低(≈ train) | 理想拟合 | 停止扩参 |
3.11 Larger Hidden Layer
所以我们尝试增加我们模型的规模:
g = torch.Generator().manual_seed(2147483647)
C = torch.randn((27, 2), generator=g)
W1 = torch.randn((6, 300), generator=g) # 300 hidden size
b1 = torch.randn(300, generator=g)
W2 = torch.randn((300, 27), generator=g)
b2 = torch.randn(27, generator=g)
parameters = [C, W1, b1, W2, b2]
print(sum(p.nelement() for p in parameters))
for p in parameters:
p.requires_grad = True
for i in range(60000):
ix = torch.randint(0, Xtr.shape[0], (32,))
emb = C[Xtr[ix]]
h = torch.tanh(emb.view(-1, 6) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Ytr[ix])
# ... (清空梯度与 loss.backward(),与前文一致) ...
lr = 0.1 if i < 30000 else (0.05 if i < 45000 else 0.01)
for p in parameters:
p.data += -lr * p.grad
# ... (分别在全量 Xtr 和 Xdev 上前向传播求 loss_tr 与 loss_dev,与前文一致) ...
print('train loss:', loss_tr.item())
print('dev loss: ', loss_dev.item())outputtrain loss: 2.2822530269622803 dev loss: 2.2862548828125
降了吗? 确实降了. 从2.33降至2.28.
但是这个下降幅度确实有点小. 我们是不是漏了什么?
有的, 我们的超参数不仅仅只有模型的大小, 还有向量化时候的维度.
我们可以合理的怀疑, 向量化的时候我们给的维度太小了(也就是2维向量没法很好的表示一个字母的信息.)
3.12 Larger Embedding Size
那么我们继续增加向量化的维度:
g = torch.Generator().manual_seed(2147483647)
C = torch.randn((27, 10), generator=g) # 10 embedding size
W1 = torch.randn((30, 200), generator=g)
b1 = torch.randn(200, generator=g)
W2 = torch.randn((200, 27), generator=g)
b2 = torch.randn(27, generator=g)
parameters = [C, W1, b1, W2, b2]
print(sum(p.nelement() for p in parameters))
for p in parameters:
p.requires_grad = True
for i in range(200000):
ix = torch.randint(0, Xtr.shape[0], (32,))
emb = C[Xtr[ix]]
h = torch.tanh(emb.view(-1, 30) @ W1 + b1)
logits = h @ W2 + b2
loss = F.cross_entropy(logits, Ytr[ix])
for p in parameters:
p.grad = None
loss.backward()
lr = 0.1 if i < 100000 else 0.01
for p in parameters:
p.data += -lr * p.grad
emb = C[Xtr]
h = torch.tanh(emb.view(-1, 30) @ W1 + b1)
logits = h @ W2 + b2
loss_tr = F.cross_entropy(logits, Ytr)
print('train loss:', loss_tr.item())
emb = C[Xdev]
h = torch.tanh(emb.view(-1, 30) @ W1 + b1)
logits = h @ W2 + b2
loss_dev = F.cross_entropy(logits, Ydev)
print('dev loss: ', loss_dev.item())outputtrain loss: 2.1248738765716553 dev loss: 2.169715642929077
看来我们的猜测是正确的. 确实是这个Embedding Size限制了模型的发挥.
3.13 看看我们搞出来的效果
g = torch.Generator().manual_seed(2147483647 + 10)
for _ in range(20):
out = []
context = [0] * block_size
while True:
emb = C[torch.tensor([context])]
h = torch.tanh(emb.view(1, -1) @ W1 + b1)
logits = h @ W2 + b2
probs = F.softmax(logits, dim=1)
ix = torch.multinomial(probs, num_samples=1, generator=g).item()
context = context[1:] + [ix]
out.append(ix)
if ix == 0:
break
print(''.join(itos[i] for i in out))outputcarmah. amelle. khi. mir. reh. cassanden. jazhnen. delyah. jareei. ner. kia. chaiir. kaleigph. bro. din. quinn. shon. raivan. quince. madiarynix.
与上一次的Bigram模型对比, 这显然要看起来好得多, 对吧.
好, 这篇博文我们从头到尾, 用MLP的方式搞出来了一个模型, 达成了比之前Bigram模型好不少的效果.
并且, 涉及到了一些后续训练过程中很常用的思路, 比如参数 / 超参的区分, 比如对数据集的划分, 等等.
这篇博文就到这里~