发布于: iPhone转发:0回复:0喜欢:0
$百度集团-SW(09888)$ 百度 可以用起来了! 两百行代码实现微型 ChatGPT: 刚看到一个 AI 教学视频, 李飞飞的门生 Andrej Karpathy 现场讲学,仅用了 225 行代码就实现了一个 nanoGPT,自学莎士比亚戏剧然后可以产生类似对白。而且其中约一半代码是过场(如加载数据、注解之类),关键点 (多头注意力机制 -- Multihead Attention)是从头写起。核心代码其实只有100多行(其中nn调用来自开源库PyTorch)。这应该是 GPT 最简化的模型与代码了。但它包括了主要核心思想,对学习相关入门知识是很好的材料。链接在某最大开源 HUB上,在中国网站上无法贴出 -- 好像是曾有反革命分子在此开源网站张贴反动言论,被全网封杀 。我把他实现 多头注意力的代码拷贝在下面(程序员大多是会“科学上网”的,有兴趣可以搜索全部200行代码)。 自从谷歌2017年发表 Attention Is All You Need 这篇论文以来,AI 技术获得爆炸式突破,而这个突破的核心就是下面这几行代码。
Karpathy 的博士导师李飛飛1976年7月3日出生于北京,斯坦福大學首位红杉讲席教授,美國国家工程院院士,美国国家医学院院士, 美国文理科学院(美国艺术与科学院)院士)。。。

class Head(nn.Module):
""" one head of self-attention """

def __init__(self, head_size):
super().__init__()
self.key = nn.Linear(n_embd, head_size, bias=False)
self.query = nn.Linear(n_embd, head_size, bias=False)
self.value = nn.Linear(n_embd, head_size, bias=False)
self.register_buffer('tril', torch.tril(torch.ones(block_size, block_size)))

self.dropout = nn.Dropout(dropout)

def forward(self, x):
# input of size (batch, time-step, channels)
# output of size (batch, time-step, head size)
B,T,C = x.shape
k = self.key(x) # (B,T,hs)
q = self.query(x) # (B,T,hs)
# compute attention scores ("affinities")
wei = q @ k.transpose(-2,-1) * k.shape[-1]**-0.5 # (B, T, hs) @ (B, hs, T) -> (B, T, T)
wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) # (B, T, T)
wei = F.softmax(wei, dim=-1) # (B, T, T)
wei = self.dropout(wei)
# perform the weighted aggregation of the values
v = self.value(x) # (B,T,hs)
out = wei @ v # (B, T, T) @ (B, T, hs) -> (B, T, hs)
return out

class MultiHeadAttention(nn.Module):
""" multiple heads of self-attention in parallel """

def __init__(self, num_heads, head_size):
super().__init__()
self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])
self.proj = nn.Linear(head_size * num_heads, n_embd)
self.dropout = nn.Dropout(dropout)

def forward(self, x):
out = torch.cat([h(x) for h in self.heads], dim=-1)
out = self.dropout(self.proj(out))
return out

#chatgpt##人工智能#