網(wǎng)絡(luò)消費(fèi)網(wǎng) >  科技 > > 正文
【天天時(shí)快訊】60行代碼就能構(gòu)建GPT!網(wǎng)友:比之前的教程都要清晰
時(shí)間:2023-02-19 13:08:10

Pine 發(fā)自 凹非寺

量子位 | 公眾號(hào) QbitAI

現(xiàn)在只用60行代碼,就能從0構(gòu)建GPT了!


(資料圖片僅供參考)

想當(dāng)初,前特斯拉前AI總監(jiān)的minGPT和nanoGPT也都還要300行代碼。

這個(gè)60行代碼的GPT也有名字,博主將它命名為PicoGPT。

不過和此前minGPT和nanoGPT的教程不同,今天要講的這個(gè)博主的教程,更側(cè)重于代碼實(shí)現(xiàn)部分,模型的權(quán)重則用已經(jīng)訓(xùn)練好的。

對(duì)此,博主解釋稱這篇教程的重點(diǎn)在于提供一個(gè)簡(jiǎn)單且易于破解的完整技術(shù)介紹

這對(duì)還不理解GPT背后概念的盆友,算是非常友好了。

還有網(wǎng)友稱贊,這篇博客介紹得非常清晰,第一部分尤為如此。

這篇介紹GPT模型的文章太好了,它比我之前看到的介紹都要清晰,至少在第一部分討論文本生成和取樣是這樣的。

目前,此項(xiàng)目在GitHub上標(biāo)星已破百,HackerNews上的點(diǎn)擊量也即將破千。

從GPT是什么講起

在介紹之前,還是需要說明一下,這篇教程不是完全零門檻,需要讀者提前熟悉Python、NumPy以及一些基本的訓(xùn)練神經(jīng)網(wǎng)絡(luò)。

教程的重點(diǎn)聚焦在技術(shù)介紹上,統(tǒng)共有六大部分:

什么是GPT?

按照慣例,在正式構(gòu)建GPT之前得先對(duì)它做一些基本介紹,教程從輸入/輸出、生成文本以及訓(xùn)練三個(gè)部分分別來講GPT是如何工作的。

在這趴,博主附上代碼,甚至還用了一些比喻來讓讀者們更好地理解GPT。

舉個(gè)栗子

,在輸入這一部分,作者將句子比作一條繩子,tokenizer則會(huì)將其分割成一小段一小段(單詞),被稱作token。

又比如說,在生成文本這part介紹自動(dòng)回歸時(shí),博主直接貼上代碼:

def generate(inputs, n_tokens_to_generate):

for _ in range(n_tokens_to_generate): # auto-regressive decode loop

output = gpt(inputs) # model forward pass

next_id = np.argmax(output[-1]) # greedy sampling

inputs = np.append(out, [next_id]) # append prediction to input

return list(inputs[len(inputs) - n_tokens_to_generate :]) # only return generated ids

input_ids = [1, 0] # "not" "all"

output_ids = generate(input_ids, 3) # output_ids = [2, 4, 6]

output_tokens = [vocab[i] for i in output_ids] # "heroes" "wear" "capes"

在每次迭代中,它會(huì)將預(yù)測(cè)的token追加回輸入,這個(gè)預(yù)測(cè)未來值并將其添加回輸入的過程就是GPT被描述為自動(dòng)回歸的原因。

60行代碼怎么運(yùn)行?

了解完GPT的基本概念之后,就直接快進(jìn)到了如何在電腦上運(yùn)行這個(gè)PicoGPT。

博主先是甩出了他那只有60行的代碼:

import numpy as np

def gpt2(inputs, wte, wpe, blocks, ln_f, n_head):

pass # TODO: implement this

def generate(inputs, params, n_head, n_tokens_to_generate):

from tqdm import tqdm

for _ in tqdm(range(n_tokens_to_generate), "generating"): # auto-regressive decode loop

logits = gpt2(inputs, **params, n_head=n_head) # model forward pass

next_id = np.argmax(logits[-1]) # greedy sampling

inputs = np.append(inputs, [next_id]) # append prediction to input

return list(inputs[len(inputs) - n_tokens_to_generate :]) # only return generated ids

def main(prompt: str, n_tokens_to_generate: int = 40, model_size: str = "124M", models_dir: str = "models"):

from utils import load_encoder_hparams_and_params

# load encoder, hparams, and params from the released open-ai gpt-2 files

encoder, hparams, params = load_encoder_hparams_and_params(model_size, models_dir)

# encode the input string using the BPE tokenizer

input_ids = encoder.encode(prompt)

# make sure we are not surpassing the max sequence length of our model

assert len(input_ids) + n_tokens_to_generate < hparams["n_ctx"]

# generate output ids

output_ids = generate(input_ids, params, hparams["n_head"], n_tokens_to_generate)

# decode the ids back into a string

output_text = encoder.decode(output_ids)

return output_text

if name == "__main__":

import fire

fire.Fire(main)

然后從克隆存儲(chǔ)庫(kù),安裝依賴項(xiàng)等步驟一步步教你如何在電腦上運(yùn)行GPT。

其中,還不乏一些貼心的小tips,比如說如果使用的是M1 Macbook,那在運(yùn)行pip install之前,需要將requments.txt中的tensorflow更改為tensorflow-macos。

此外,對(duì)于代碼的四個(gè)部分:gpt2,generate,main以及fire.Fire(main),博主也有做詳細(xì)解釋。

等到代碼能夠運(yùn)行之后,下一步博主就準(zhǔn)備詳細(xì)介紹編碼器、超參數(shù)(hparams)以及參數(shù)(params)這三部分了。

直接在筆記本或者Python會(huì)話中運(yùn)行下面這個(gè)代碼:

from utils import load_encoder_hparams_and_params

encoder, hparams, params = load_encoder_hparams_and_params("124M", "models")

Bingo!一些必要的模型和tokenizer文件就直接下載到model/124M,編碼器、hparams和params也能直接加載。

更具體的內(nèi)容這里就不多說了,教程的鏈接已經(jīng)附在文末。

一些基礎(chǔ)神經(jīng)網(wǎng)絡(luò)層的介紹

這一趴涉及到的知識(shí)就更加基礎(chǔ)了,因?yàn)橄乱慌渴菍?shí)際GPT自身的架構(gòu),所以在此之前,需要了解一些非特定于GPT的更基本的神經(jīng)網(wǎng)絡(luò)層。

博主介紹了GeLU、Softmax函數(shù)以及Layer Normalization和Linear。

GPT架構(gòu)

終于!這部分要來講GPT自身的架構(gòu)了,博主從transformer的架構(gòu)引入。

△transformer架構(gòu)

GPT的架構(gòu)只使用了transformer中的解碼器堆棧(即圖表的右邊部分),并且其中的的“交叉注意”層也沒有用到。

△GPT架構(gòu)

隨后,博主將GPT的架構(gòu)總結(jié)成了三大部分:

文本 + 位置嵌入

變壓器解碼器堆棧

下一個(gè)token預(yù)測(cè)頭

并且還將這三部分用代碼展示了出來,是醬紫的:

def gpt2(inputs, wte, wpe, blocks, ln_f, n_head): # [n_seq] -> [n_seq, n_vocab]

# token + positional embeddings

x = wte[inputs] + wpe[range(len(inputs))] # [n_seq] -> [n_seq, n_embd]

# forward pass through n_layer transformer blocks

for block in blocks:

x = transformer_block(x, block, n_head=n_head) # [n_seq, n_embd] -> [n_seq, n_embd]

# projection to vocab

x = layer_norm(x, ln_f) # [n_seq, n_embd] -> [n_seq, n_embd]

return x @ wte.T # [n_seq, n_embd] -> [n_seq, n_vocab]

再后面,就是關(guān)于這三部分的更多細(xì)節(jié)……

測(cè)試構(gòu)建的GPT

這部分將全部的代碼組合在一起,就得到了gpt2.py,統(tǒng)共有120行代碼,刪除注釋和空格的話,就是60行。

然后測(cè)試一下!

python gpt2.py \

"Alan Turing theorized that computers would one day become" \

--n_tokens_to_generate 8

結(jié)果是這樣的:

the most powerful machines on the planet.

成功了!

一些后續(xù)補(bǔ)充

最后一部分,博主也總結(jié)了這短短60行代碼的不足:非常低效!

不過他還是給出了兩個(gè)可以讓GPT變高效的方法:

同時(shí)地而不是順序地執(zhí)行注意力計(jì)算。

實(shí)現(xiàn) KV 緩存。

此外,博主還推薦了一些訓(xùn)練模型、評(píng)估模型以及改進(jìn)架構(gòu)的方法和教程。

關(guān)鍵詞: inputs params

版權(quán)聲明:
    凡注明來網(wǎng)絡(luò)消費(fèi)網(wǎng)的作品,版權(quán)均屬網(wǎng)絡(luò)消費(fèi)網(wǎng)所有,未經(jīng)授權(quán)不得轉(zhuǎn)載、摘編或利用其它方式使用上述作品。已經(jīng)本網(wǎng)授權(quán)使用作品的,應(yīng)在授權(quán)范圍內(nèi)使用,并注明"來源:網(wǎng)絡(luò)消費(fèi)網(wǎng)"。違反上述聲明者,本網(wǎng)將追究其相關(guān)法律責(zé)任。
    除來源署名為網(wǎng)絡(luò)消費(fèi)網(wǎng)稿件外,其他所轉(zhuǎn)載內(nèi)容之原創(chuàng)性、真實(shí)性、完整性、及時(shí)性本站不作任何保證或承諾,請(qǐng)讀者僅作參考并自行核實(shí)。
熱文

網(wǎng)站首頁(yè) |網(wǎng)站簡(jiǎn)介 | 關(guān)于我們 | 廣告業(yè)務(wù) | 投稿信箱
 

Copyright © 2000-2020 www.netfop.cn All Rights Reserved.
 

中國(guó)網(wǎng)絡(luò)消費(fèi)網(wǎng) 版權(quán)所有 未經(jīng)書面授權(quán) 不得復(fù)制或建立鏡像
 

聯(lián)系郵箱:920 891 263@qq.com

備案號(hào):京ICP備2022016840號(hào)-15

營(yíng)業(yè)執(zhí)照公示信息