60行代碼就能構(gòu)建GPT!網(wǎng)友:比之前的教程都要清晰|附代碼
還有完整技術(shù)介紹
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)練好的。
對此,博主解釋稱這篇教程的重點(diǎn)在于提供一個簡單且易于破解的完整技術(shù)介紹。
這對還不理解GPT背后概念的盆友,算是非常友好了。
還有網(wǎng)友稱贊,這篇博客介紹得非常清晰,第一部分尤為如此。
這篇介紹GPT模型的文章太好了,它比我之前看到的介紹都要清晰,至少在第一部分討論文本生成和取樣是這樣的。
目前,此項目在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之前得先對它做一些基本介紹,教程從輸入/輸出、生成文本以及訓(xùn)練三個部分分別來講GPT是如何工作的。
在這趴,博主附上代碼,甚至還用了一些比喻來讓讀者們更好地理解GPT。
舉個栗子
,在輸入這一部分,作者將句子比作一條繩子,tokenizer則會將其分割成一小段一小段(單詞),被稱作token。
又比如說,在生成文本這part介紹自動回歸時,博主直接貼上代碼:
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”
在每次迭代中,它會將預(yù)測的token追加回輸入,這個預(yù)測未來值并將其添加回輸入的過程就是GPT被描述為自動回歸的原因。
60行代碼怎么運(yùn)行?
了解完GPT的基本概念之后,就直接快進(jìn)到了如何在電腦上運(yùn)行這個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)
然后從克隆存儲庫,安裝依賴項等步驟一步步教你如何在電腦上運(yùn)行GPT。
其中,還不乏一些貼心的小tips,比如說如果使用的是M1 Macbook,那在運(yùn)行pip install之前,需要將requments.txt中的tensorflow更改為tensorflow-macos。
此外,對于代碼的四個部分:gpt2,generate,main以及fire.Fire(main),博主也有做詳細(xì)解釋。
等到代碼能夠運(yùn)行之后,下一步博主就準(zhǔn)備詳細(xì)介紹編碼器、超參數(shù)(hparams)以及參數(shù)(params)這三部分了。
直接在筆記本或者Python會話中運(yùn)行下面這個代碼:
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ò)層的介紹
這一趴涉及到的知識就更加基礎(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 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é)……
測試構(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ù)補(bǔ)充
最后一部分,博主也總結(jié)了這短短60行代碼的不足:非常低效!
不過他還是給出了兩個可以讓GPT變高效的方法:
- 同時地而不是順序地執(zhí)行注意力計算。
- 實現(xiàn) KV 緩存。
此外,博主還推薦了一些訓(xùn)練模型、評估模型以及改進(jìn)架構(gòu)的方法和教程。
感興趣的話,直接戳文末鏈接~
作者介紹
Jay Mody,目前在加拿大一家NLP初創(chuàng)公司Cohere從事機(jī)器學(xué)習(xí)的工作,此前,他還分別在特斯拉和亞馬遜作為軟件工程師實習(xí)過一段時間。
除了這篇教程之外,小哥的博客網(wǎng)站上還有更新其他文章,并且都有附代碼~
代碼傳送門:
https://github.com/jaymody/picoGPT/blob/29e78cc52b58ed2c1c483ffea2eb46ff6bdec785/gpt2_pico.py#L3-L58
教程鏈接:
https://jaykmody.com/blog/gpt-from-scratch/#putting-it-all-together
- “智元機(jī)器人收購A股上市公司是創(chuàng)新需要…現(xiàn)金流能撐三年”2025-08-22
- 稚暉君新大招:機(jī)器人二次開發(fā)0門檻了!2025-08-22
- 賣酒的茅臺要學(xué)AI了!和奔馳麥當(dāng)勞一起拜師百度2025-08-17
- VLA進(jìn)化后降維打擊!雙手揀貨,漂移操作,還能批量化秀舞,太空艙直接開上街,被銀河通用卷到了2025-08-11