60行代碼就能構(gòu)建GPT!網(wǎng)友:比之前的教程都要清晰
Pine 發(fā)自 凹非寺
量子位 | 公眾號 QbitAI
現(xiàn)在只用60行代碼,就能從0構(gòu)建GPT了!
想當(dāng)初,前特斯拉前AI總監(jiān)的minGPT和nanoGPT也都還要300行代碼。
這個60行代碼的GPT也有名字,博主將它命名為PicoGPT。
不過和此前minGPT和nanoGPT的教程不同,今天要講的這個博主的教程,更側(cè)重于代碼實現(xiàn)部分,模型的權(quán)重則用已經(jīng)訓(xùn)練好的。
對此,博主解釋稱這篇教程的重點在于提供一個簡單且易于破解的完整技術(shù)介紹。
這對還不理解GPT背后概念的盆友,算是非常友好了。

還有網(wǎng)友稱贊,這篇博客介紹得非常清晰,第一部分尤為如此。
這篇介紹GPT模型的文章太好了,它比我之前看到的介紹都要清晰,至少在第一部分討論文本生成和取樣是這樣的。

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

從GPT是什么講起
在介紹之前,還是需要說明一下,這篇教程不是完全零門檻,需要讀者提前熟悉Python、NumPy以及一些基本的訓(xùn)練神經(jīng)網(wǎng)絡(luò)。
教程的重點聚焦在技術(shù)介紹上,統(tǒng)共有六大部分:
什么是GPT?
按照慣例,在正式構(gòu)建GPT之前得先對它做一些基本介紹,教程從輸入/輸出、生成文本以及訓(xùn)練三個部分分別來講GPT是如何工作的。

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

,在輸入這一部分,作者將句子比作一條繩子,tokenizer則會將其分割成一小段一小段(單詞),被稱作token。
又比如說,在生成文本這part介紹自動回歸時,博主直接貼上代碼:
def generate(inputs, n_tokens_to_generate):for _ in range(n_tokens_to_generate): # auto-regressive decode loopoutput = gpt(inputs) # model forward passnext_id = np.argmax(output[-1]) # greedy samplinginputs = np.append(out, [next_id]) # append prediction to inputreturn list(inputs[len(inputs) - n_tokens_to_generate :]) # only return generated idsinput_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"
在每次迭代中,它會將預(yù)測的token追加回輸入,這個預(yù)測未來值并將其添加回輸入的過程就是GPT被描述為自動回歸的原因。
60行代碼怎么運行?
了解完GPT的基本概念之后,就直接快進到了如何在電腦上運行這個PicoGPT。
博主先是甩出了他那只有60行的代碼:
import numpy as npdef gpt2(inputs, wte, wpe, blocks, ln_f, n_head):pass # TODO: implement thisdef generate(inputs, params, n_head, n_tokens_to_generate):from tqdm import tqdmfor _ in tqdm(range(n_tokens_to_generate), "generating"): # auto-regressive decode looplogits = gpt2(inputs, **params, n_head=n_head) # model forward passnext_id = np.argmax(logits[-1]) # greedy samplinginputs = np.append(inputs, [next_id]) # append prediction to inputreturn list(inputs[len(inputs) - n_tokens_to_generate :]) # only return generated idsdef 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 filesencoder, hparams, params = load_encoder_hparams_and_params(model_size, models_dir)# encode the input string using the BPE tokenizerinput_ids = encoder.encode(prompt)# make sure we are not surpassing the max sequence length of our modelassert len(input_ids) + n_tokens_to_generate < hparams["n_ctx"]# generate output idsoutput_ids = generate(input_ids, params, hparams["n_head"], n_tokens_to_generate)# decode the ids back into a stringoutput_text = encoder.decode(output_ids)return output_textif name == "__main__":import firefire.Fire(main)
然后從克隆存儲庫,安裝依賴項等步驟一步步教你如何在電腦上運行GPT。
其中,還不乏一些貼心的小tips,比如說如果使用的是M1 Macbook,那在運行pip install之前,需要將requments.txt中的tensorflow更改為tensorflow-macos。
此外,對于代碼的四個部分:gpt2,generate,main以及fire.Fire(main),博主也有做詳細(xì)解釋。
等到代碼能夠運行之后,下一步博主就準(zhǔn)備詳細(xì)介紹編碼器、超參數(shù)(hparams)以及參數(shù)(params)這三部分了。

直接在筆記本或者Python會話中運行下面這個代碼:
from utils import load_encoder_hparams_and_paramsencoder, 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ò)層的介紹
這一趴涉及到的知識就更加基礎(chǔ)了,因為下一趴是實際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é)成了三大部分:
文本 + 位置嵌入變壓器解碼器堆棧下一個token預(yù)測頭并且還將這三部分用代碼展示了出來,是醬紫的:
def gpt2(inputs, wte, wpe, blocks, ln_f, n_head): # [n_seq] -> [n_seq, n_vocab]# token + positional embeddingsx = wte[inputs] + wpe[range(len(inputs))] # [n_seq] -> [n_seq, n_embd]# forward pass through n_layer transformer blocksfor block in blocks:x = transformer_block(x, block, n_head=n_head) # [n_seq, n_embd] -> [n_seq, n_embd]# projection to vocabx = 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é)……
測試構(gòu)建的GPT
這部分將全部的代碼組合在一起,就得到了gpt2.py,統(tǒng)共有120行代碼,刪除注釋和空格的話,就是60行。
然后測試一下!
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ù)補充
最后一部分,博主也總結(jié)了這短短60行代碼的不足:非常低效!
不過他還是給出了兩個可以讓GPT變高效的方法:
同時地而不是順序地執(zhí)行注意力計算。實現(xiàn) KV 緩存。此外,博主還推薦了一些訓(xùn)練模型、評估模型以及改進架構(gòu)的方法和教程。
感興趣的話,直接戳文末鏈接~
作者介紹
Jay Mody,目前在加拿大一家NLP初創(chuàng)公司Cohere從事機器學(xué)習(xí)的工作,此前,他還分別在特斯拉和亞馬遜作為軟件工程師實習(xí)過一段時間。

除了這篇教程之外,小哥的博客網(wǎng)站上還有更新其他文章,并且都有附代碼~

代碼傳送門:/uploads/pic/20231229/00npmxq53gs.py data-track="69">
— 完 —
量子位 QbitAI · 頭條號簽約
- 免責(zé)聲明
- 本文所包含的觀點僅代表作者個人看法,不代表新火種的觀點。在新火種上獲取的所有信息均不應(yīng)被視為投資建議。新火種對本文可能提及或鏈接的任何項目不表示認(rèn)可。 交易和投資涉及高風(fēng)險,讀者在采取與本文內(nèi)容相關(guān)的任何行動之前,請務(wù)必進行充分的盡職調(diào)查。最終的決策應(yīng)該基于您自己的獨立判斷。新火種不對因依賴本文觀點而產(chǎn)生的任何金錢損失負(fù)任何責(zé)任。