由 AI 翻譯。經人工以英文驗證。 閱讀原文
教學套件
版次 2026.11.20 為本書目前的版次,會隨本書更新而變動。可自由使用與改編,但須標示本書出處。
課程大綱
閱讀時間僅計算本章的文字。學生也會在 Lab 或自己的電腦上執行範例。
每週一章:11 週
| 週 | 各章 | 閱讀 | 範例 |
|---|---|---|---|
| 1 | 1. 預測下一個詞 | 61 分鐘 | 9 |
| 2 | 2. 詞元 | 35 分鐘 | 8 |
| 3 | 3. Counting further back | 49 分鐘 | 8 |
| 4 | 4. Words as vectors | 45 分鐘 | 9 |
| 5 | 5. 神經語言模型 | 48 分鐘 | 11 |
| 6 | 6. 注意力 | 46 分鐘 | 10 |
| 7 | 7. Transformer 區塊 | 60 分鐘 | 9 |
| 8 | 8. 訓練小型模型 | 49 分鐘 | 8 |
| 9 | 9. Choosing the next token | 39 分鐘 | 8 |
| 10 | 10. Inside an open model | 55 分鐘 | 9 |
| 11 | 11. 從預測到遵循指令 | 46 分鐘 | 11 |
5 週後
| 週 | 各章 | 閱讀 | 範例 |
|---|---|---|---|
| 1 | 1. 預測下一個詞 2. 詞元 | 96 分鐘 | 17 |
| 2 | 3. Counting further back 4. Words as vectors | 94 分鐘 | 17 |
| 3 | 5. 神經語言模型 6. 注意力 | 94 分鐘 | 21 |
| 4 | 7. Transformer 區塊 8. 訓練小型模型 | 109 分鐘 | 17 |
| 5 | 9. Choosing the next token 10. Inside an open model 11. 從預測到遵循指令 | 140 分鐘 | 28 |
學習目標與大綱
每章的學習目標即為其第一句。每份大綱依循該章各節,列出該節定義的名詞、執行範例前要求的預測,以及每節結尾所歸納的規則。 其關鍵術語與要提問的預測內容,依題庫所列,採用英文版次的內容。
1. 預測下一個詞
閱讀約需 61 分鐘,含 9 個範例。
讀完本章後,你可以僅靠計數,從一家商店的商品名稱建立一個完整的語言模型,用它在購物者輸入時建議下一個詞、生成文字,並以一個數字衡量它對從未見過的文字預測得有多好。
課程大綱:10 節
-
載入商店的文字
- 執行
store-text.py - 實用原則 在任何模型看到文字之前,先把文字切分為訓練、驗證與測試三部分,並且以文件為單位來切分(此處即以商品為單位),讓同一項目的近似重複內容不會橫跨兩個部分。進行工作時,以驗證集文字比較模型,只在最終報告時才動用測試集文字。先從手上最短、最規律的文字學起;本章從名稱開始,描述留待本書後面再談。
- 執行
-
計算哪個詞接在哪個詞之後
- 關鍵詞 bigram
- 執行
count-next-words.py - 實用原則 只在訓練切分中計算配對,並為每段文字補上開頭與結尾標記,讓模型學會文字如何開始與結束。請保留原始計數,不要只留下由它推導出的機率:計數能告訴你每個機率背後有多少證據,後續各節也會用到。
-
Turn counts into probabilities
- 執行
next-word-probabilities.py - 執行
figure-next-word-distribution.py - 實用原則 Derive probabilities from counts by division, and check that each word's probabilities sum to one; a sum that doesn't is a bug in the counting. Treat a probability as only as good as the count under it: 0.9 from 1,000 pairs is evidence, while 1.0 from a single pair is an anecdote.
- 執行
-
Suggest the next word as a shopper types
- 執行
autocomplete.py - 實用原則 For autocomplete, offer the top few next words by probability, and drop tokens that aren't words, such as punctuation. Expect a bigram model's suggestions to be good after words that are almost always followed by the same thing, such as
coffee, and poor after words with many possible continuations, such asoutdoor. When the earlier words matter, as they do inpatio bar, a bigram model can't help, however much text it learns from.
- 執行
-
一次產生一個詞來生成名稱
- 執行
generate-names.py - 實用原則 每次更動模型時都要生成樣本並閱讀,因為樣本會呈現分數所掩蓋的失敗,例如文字從一項產品飄移到另一項產品。使用固定的種子,讓樣本可以重現。切勿以樣本來比較模型;應以驗證文字上的困惑度來比較。
- 執行
-
Score a model with perplexity
- 關鍵詞 Perplexity
- 執行
perplexity-by-hand.py - 實用原則 Score every language model by its perplexity on validation text, computed exactly as above, with natural logarithms and every predicted word counted, the end marker included. Compare perplexities only between models that use the same tokens and the same validation text, since splitting text differently changes N and what counts as a word. Report training perplexity only beside validation perplexity, to show how much the model memorized.
-
Unseen word pairs break the model
- 執行
perplexity-on-new-names.py - 實用原則 Never trust a language model that gives zero probability to anything; check for infinite or undefined perplexity on validation text before you compare models. When you see one, count the unseen pairs, as above, to know how much of the text the model can't handle.
- 執行
-
Give unseen pairs a little probability
- 執行
add-one-smoothing.py - 實用原則 Never ship a counted model without smoothing, and never ship one with add-one smoothing: measure validation perplexity and expect add-one to lose to every method in chapter 3, which compares them on the same tokens. Use add-one only as this chapter does, to show that zero probabilities are fixable and that the fix needs care.
- 執行
- 正式環境中會出什麼問題
- 本章的決定
2. 詞元
閱讀約需 35 分鐘,含 8 個範例。
讀完本章後,你可以從零開始建立位元組對編碼(byte-pair encoding)的 tokenizer,透過衡量各種詞彙表大小所付出的代價來選定詞彙表大小,並且能讀懂開放語言模型的斷詞器,進而以手工套用它的合併規則。
課程大綱:9 節
-
以單字為單位會留下缺口
- 執行
unseen-words.py - 實用原則 在選擇以單字作為詞元之前,先在保留的資料上衡量文字的詞彙表外比率。經驗法則是,如果保留資料中有超過百分之一或二的單字是未見過的,如同這家商店的名稱,就不要以單字作為詞元。對於詞彙表封閉的文字,例如固定的一組指令,以單字作為詞元仍然合理。
- 執行
-
字元涵蓋一切
- 執行
character-tokens.py - 實用原則 只在小型實驗中,或在較大方案內作為後備時,才使用字元作為詞元,如接下來各節所做的。請檢查文字平均每個單字有多少個字元,因為這個係數會乘上每一個序列長度與每一個訓練步驟。
- 執行
-
一再合併最常出現的符號對
- 執行
merge-pairs-by-hand.py - 實用原則 與訓練任何其他模型時一樣,只從訓練切分中學習合併,並保留合併的順序,因為編碼取決於這個順序。出現次數相同的符號對若需決定先後,應以固定規則處理,讓相同的文字永遠得到相同的分詞器。
- 執行
-
訓練商店的分詞器
- 執行
store-tokenizer.py - 實用原則 以模型將要學習的同一份文字來訓練分詞器,此處是名稱與描述合併,使該文字中的常見詞成為單一詞元。只建立一次,並用於你要比較的每個模型;本書的所有模型都透過
lib.bpe.store_tokenizer()讀取商店的文字。
- 執行
-
選擇合併次數
- 執行
vocabulary-size.py - 執行
figure-merges-trade-off.py - 實用原則 以量測決定合併次數:在訓練文字上量測罕見詞元型別的比例,在保留文字上量測每詞詞元數;當每詞詞元數不再明顯下降、罕見型別開始上升時停止。詞彙表要隨訓練文字調整;經驗上,在數百萬詞上訓練的小型模型適合數千次合併,而非數萬次。
- 執行
-
讀取開放模型的分詞器
- 執行
smollm2-tokens.py - 實用原則 只要使用開放模型的分詞器,就要完全照發布的原樣使用;模型只能理解它訓練時見過的詞元。只要需要規劃上下文長度或成本,就用該分詞器計算詞元數,而不是計算單字數。當你以狹窄領域的文字訓練自己的模型時,也要用那些文字訓練自己的分詞器。
- 執行
-
手動套用 SmolLM2 的合併規則
- 執行
merges-by-hand.py - 實用原則 把分詞器視為模型的一部分:與模型一同進行版本管理,從模型本身的檔案載入,並且在升級兩者之一時,以你自己的文字進行測試。當兩個分詞器對同一段文字即使只有一個詞元不一致,在信任以它們為基礎的模型所輸出的任何內容之前,都要先查明原因。
- 執行
- 正式環境中會出什麼問題
- 本章的決定
3. Counting further back
閱讀約需 49 分鐘,含 8 個範例。
學習結束時,學員能夠build an n-gram language model that looks several tokens back, smooth it with Kneser-Ney so it handles text it hasn't seen (smoothing gives some probability to what the counts never saw, as chapter 1 showed), measure the baseline that every neural model in this book is measured against, and see why counting, however clever, runs out of road。
課程大綱:9 節
-
較長的上下文更能擬合訓練文本
- 執行
ngram-memorizes.py - 實用原則 絕不要以 n-gram 模型(或任何語言模型)在自己訓練文本上的困惑度來判斷其優劣:隨著模型記住文本,困惑度會趨近 1。應如本章其餘部分所做的,以保留文本(held-out text)上的困惑度來選擇階數。
- 執行
-
越長的上下文,證據越不足
- 執行
unseen-ngrams.py - 實用原則 選擇 n-gram 階數之前,先測量訓練文本從未包含的保留資料 n-gram 所占的比例。經驗上,當這個比例接近三分之一時(如商店名稱中的三元組),該階數的模型主要取決於它如何處理未見過的情況,因此平滑方法比階數更重要。
- 執行
-
混合短脈絡與長脈絡
- 執行
interpolate-orders.py - 實用原則 不要單獨使用單一階數的 n 元模型;一律將它與較低階數結合,讓每個詞元都保有一些機率。相較於固定權重,應優先採用依各脈絡的計數來設定其權重的方法,例如下文的 Kneser-Ney。如果確實使用固定權重,應在保留的驗證文本上選擇,而不是在用來計數的文本上選擇。
- 執行
-
計算詞元所接續的上下文數量
- 執行
continuation-counts.py - 實用原則 每當從長上下文退回到短上下文時,應依詞元所接續的不同上下文數量加權,而非依其出現頻率。只有在最高階、也就是上下文確實已經見過的情況下,才使用原始計數。
- 執行
-
Smooth with Kneser-Ney
- 執行
kneser-ney-by-hand.py - 執行
kneser-ney-by-order.py - 執行
figure-perplexity-by-order.py - 實用原則 Smooth n-gram models with interpolated Kneser-Ney and a discount of 0.75 unless held-out text says otherwise. Raise the order only while validation perplexity keeps falling noticeably, and stop when a step barely helps or hurts, as the step from 4-gram to 5-gram does. A variant, modified Kneser-Ney, uses three discounts instead of one and is the one toolkits such as KenLM build; it would likely lower the baseline a little, and this book keeps the single discount because it's easier to follow by hand.
- 執行
-
以三個詞元作為上下文的自動完成
- 執行
ngram-autocomplete.py - 實用原則 為建議功能採用模型能支援的最長上下文,並將訓練中罕見的上下文(例如
outdoor bar)的建議與常見上下文分開檢查:計數式模型正是在這種地方退回到泛用的猜測。
- 執行
-
The baseline every later model is measured against
- 實用原則 Before building a learned model, build the strongest counted model you can and record its held-out perplexity as the baseline. Report every later model against it, on the same text and with the same tokenizer, and treat a learned model that doesn't beat it as a result to explain, never as a success. Later chapters find exactly that, and earn the learned models their place another way.
- 在正式環境中會出什麼問題
- 本章的決定
4. Words as vectors
閱讀約需 45 分鐘,含 9 個範例。
學習結束時,學員能夠turn every token of the store's text into a short vector of numbers, so that tokens used in similar ways get similar vectors, by two methods:
- compressing counts of which tokens appear together, training a small model to predict each token's neighbours
課程大綱:10 節
-
One-hot 向量什麼也不知道
- 執行
one-hot-vectors.py - 實用原則 不要把 one-hot 向量餵給需要讓詞元彼此關聯的模型。只把它們當作索引,如接下來幾節所做的,用來查出每個詞元所對應的已學得向量。
- 執行
-
以周圍的詞元來描述詞元
- 執行
cooccurrence-counts.py - 實用原則 在模型要學習的文字中,於小視窗(兩到五個詞元)內計算共現次數,且絕不跨越文件邊界。不要把原始計數直接當作向量:請重新加權,如下一節所做的,讓高頻鄰近詞不再佔據主導。
- 執行
-
以意外程度加權共現次數
- 執行
ppmi-neighbours.py - 實用原則 在將共現計數當作向量使用之前,先以正 PMI 重新加權。要預期 PMI 會高估由罕見詞元組成的詞對,因為它們僅有的幾次共現看起來遠高於隨機預期;這也是本章只保留高頻詞元,或要求設定最低計數的原因之一。
- 執行
-
將計數壓縮成稠密向量
- 執行
svd-neighbours.py - 執行
figure-token-map.py - 實用原則 以 SVD 將 PPMI 壓縮到 50 至 300 維,並用本節的方式檢查結果:列出少數詞元的最近鄰居並加以閱讀。如果鄰居大多是高頻的功能詞,就表示重新加權出了問題;如果鄰居彼此無關,就表示視窗或詞彙表太小。
- 執行
-
透過預測鄰近詞元來學習向量
- 執行
skipgram-step.py - 實用原則 訓練嵌入時,如同
lib.skipgram.train所做的,讓第二組向量從零開始、第一組從小的隨機值開始,並依詞元頻率的 0.75 次方成比例抽取雜訊詞元,Mikolov et al. 發現這比單純依頻率抽取效果更好。在執行數百萬次之前,先以手算檢查一次更新:機率若朝錯誤的方向變動,就表示梯度的正負號有誤。
- 執行
-
比較學得的向量與計數得到的向量
- 執行
skipgram-neighbours.py - 實用原則 把計數得到的嵌入(PPMI 與 SVD)和學得的嵌入(skip-gram)視為相近的替代方案:在數百萬個詞元的規模上,兩者給出相似的鄰近詞,而計數得到的嵌入具有確定性且速度快。當嵌入本來就是你要訓練的較大模型的一部分時,優先選用學得的嵌入,本書後續每一章都是如此。切勿在未檢查反義詞的情況下,就把高相似度解讀為同義。
- 執行
-
Analogies, and where they fail
- 執行
analogies.py - 實用原則 Don't judge embeddings by analogies; judge them by how much they help the task they're for, as the next section and every later chapter do. When an analogy fails, check whether the answer is in the vocabulary and whether the words mean what you assume in your text.
- 執行
-
用向量找出相似的名稱
- 執行
name-vectors.py - 實用原則 需要為短文字取得快速、不考慮順序的表示方式時,可以對詞元嵌入取平均,並預期它能找出相關項目,但排序會較為鬆散。若要做真正的語意檢索,請使用專為此目的訓練的模型,如 Primer 所做的那樣。至於語言建模,則把嵌入向量本身交給模型,讓它自己學習如何組合,第 5 章即開始這麼做。
- 執行
- 實際運作時會出什麼問題
- 本章的決定
5. 神經語言模型
閱讀約需 48 分鐘,含 11 個範例。
讀完本章後,你將能建立一個神經語言模型,根據前面一段視窗內的詞元預測下一個詞元;能手動計算它的梯度並加以檢查;能用 PyTorch 訓練它;也能與計數式基準模型做公平的比較。
課程大綱:11 節
-
從嵌入視窗預測
- 執行
window-model-by-hand.py - 實用原則 親手建立你所訓練的任何模型的前向傳遞(forward pass)至少一次,並印出每個中間陣列的形狀,如本範例所做的:形狀錯誤是神經網路程式碼中常見的錯誤,而形狀正好說明了模型所計算的內容。只要詞彙表很大,就要預期輸出層會占據大部分的參數。
- 執行
-
以反向傳播計算梯度
- 執行
gradients-by-hand.py - 實用原則 在信任手寫的梯度之前,先在微型模型上以微調估計值檢查。若使用替你計算梯度的函式庫,如 PyTorch 一節所做的,則改為檢查函式庫的前向傳遞是否與你自己寫的一致。
- 執行
-
執行梯度下降步驟
- 執行
gradient-descent-by-hand.py - 實用原則 開始訓練任何新模型時,先在少數幾個範例上執行幾步,並確認損失有下降:如果損失在三個範例上都降不下來,代表程式有錯誤,而不是問題困難。步長的選擇要多試幾個值:太小,損失下降得很慢;太大,損失會上下跳動,甚至增加。
- 執行
-
Train with PyTorch
- 執行
same-as-pytorch.py - 實用原則 Train with a library that computes gradients for you, and keep a short, independent forward pass of your own to check its outputs, as
lib.neuraldoes here. Record the library's outputs for a few inputs whenever you save weights, so the check can run anywhere, long after training.
- 執行
-
Stop when validation loss turns up
- 執行
training-curve.py - 實用原則 Always record validation loss per epoch and keep the best epoch's weights, never the last. When the curves part early, as they do here after a few epochs, the model has more capacity than its training text supports: regularize it, use a smaller model, or get more text of the same kind.
- 執行
-
與基準模型比較
- 執行
neural-vs-baseline.py - 執行
seen-and-unseen-contexts.py - 實用原則 在宣稱學習得來的模型有幫助之前,務必在相同的文本與詞元上,將它與強大的計數基準模型比較,並依見過與未見過的上下文拆分比較結果,以看出各模型在哪裡勝出。不要僅憑一個小型資料集,就斷定神經模型無效,或斷定它們總是有效。
- 執行
-
將神經網路與計數模型混合
- 執行
mix-neural-and-counts.py - 執行
figure-mixing-curve.py - 實用原則 當學習得到的模型與計數模型表現接近時,先嘗試混合兩者的機率,再決定採用哪一個,並在保留的文本上選擇比重。若其中一個模型明顯較強,比重宜保持在較小的值,並在依賴這項增益之前,先以獨立的測試集確認。
- 執行
-
更多文字只有在種類相同時才有幫助
- 執行
more-text-of-another-kind.py - 實用原則 在加入訓練文字之前,先確認它與你要預測的文字相似;同時以兩者訓練,並在目標文字上評量,而不要假設越多越好。當額外的文字差異很大時,就只用目標文字訓練,或安排每種文字的版面,讓模型能分辨它們的種類,如第 8 章在商品名稱與描述之間放置分隔符號的做法。
- 執行
-
Suggest from similar contexts
- 執行
neural-autocomplete.py - 實用原則 Look at a learned model's predictions on contexts the training text lacks, with control prefixes beside them, but judge it by measurements over many contexts, not by examples. For autocomplete in production, use the mix, and test it on rare prefixes as well as common ones.
- 執行
- 正式環境中會出什麼問題
- 本章的決定
6. 注意力
閱讀約需 46 分鐘,含 10 個範例。
讀完本章後,你就能親手計算注意力:為每個詞元的查詢(query)與之前每個詞元的鍵(key)之間的匹配程度打分數,把分數轉成權重,再對這些權重所選出的值(value)取加權平均。
課程大綱:10 節
-
以加權平均回顧前文
- 執行
attention-by-hand.py - 實用原則 像本範例那樣,把注意力的四行運算親手寫出一次,並印出權重矩陣:它的各列確切顯示了每個位置看向何處。學習時,請把查詢、鍵與值保持為各自獨立的矩陣。函式庫常把它們放在同一個矩陣中,例如 PyTorch 的
MultiheadAttention使用in_proj_weight(原始碼),再把結果拆開,所算出的內容是相同的。
- 執行
-
以因果遮罩隱藏未來
- 執行
causal-mask.py - 實用原則 在 softmax 之前對分數套用遮罩,而不是在 softmax 之後對權重套用,這樣每一列的總和仍然是 1。測試時比照本範例的做法:檢查後面位置的權重恰好為零,並檢查更動後面的詞元不會改變較前面的輸出。如果模型的訓練損失下降得遠比預期快,先檢查遮罩。
- 執行
-
縮放分數
- 執行
scaling-matters.py - 執行
figure-scaling-keeps-spread.py - 實用原則 如同 transformer 論文所做,將注意力分數除以查詢大小的平方根。少數模型(例如 T5)省略這個除法,改將該係數納入查詢權重的初始化方式(來源),因此載入模型權重之前,請先確認該模型採用哪一種做法。若你更動了查詢與鍵的計算或初始化方式,請印出未訓練模型的平均最大權重,並預期它遠低於 1。
- 執行
-
多個注意力頭尋找不同的事物
- 執行
attention-heads.py - 實用原則 經驗上,每個頭的寬度至少應維持在 32 個數值。在 Transformer 論文的實驗中,16 個寬度為 32 的頭與 8 個寬度為 64 的頭表現相當,而 32 個寬度為 16 的頭表現較差,縮小鍵的大小也會造成損害(Vaswani et al., 2017,表 3)。每當修改模型時,請檢查權重張量的形狀,也就是頭數乘以位置數再乘以位置數:頭的軸若放錯位置,會把各頭混在一起,卻不會產生任何錯誤。
- 執行
-
Read what trained heads attend to
- 執行
trained-attention.py - 實用原則 Inspect a trained model by starting with specific tokens in texts you understand, where you know what the model should look at. Treat what the weights suggest as a hypothesis, and test it by changing the input, as the next section does.
- 執行
-
測試模型複製了什麼
- 執行
copy-from-the-name.py - 實用原則 要檢驗關於模型使用了什麼的說法,應更改該輸入並測量輸出,同時加入一項理應不影響輸出的更改。注意力權重適合用來提出假設,而像這樣的測試才適合用來下結論。
- 執行
-
有些注意力頭會關注前一個詞元
- 執行
previous-token-heads.py - 執行
figure-previous-token-pattern.py - 實用原則 以量測得到的平均值來描述訓練後的注意力頭,例如它在前一個詞元、當前詞元或起始標記上的權重,並以數百筆文本計算。將每項數值與以相同方式平均的均勻分布相比,這樣像 0.3 這樣的數字才能判讀為大或小。
- 執行
-
越過視窗
- 執行
attention-reaches-back.py - 實用原則 在決定模型的上下文需要多長之前,先量測訓練好的模型向前注意多遠,並與平均分配比較,讓這個數字有意義。把標記上的權重分開回報,以免標記權重看起來像長距離注意力;而在為了節省空間而截短模型的上下文時,要保留最前面的詞元。
- 執行
- 正式環境中會出什麼問題
- 本章的決定
7. Transformer 區塊
閱讀約需 60 分鐘,含 9 個範例。
讀完本章後,你能把注意力、正規化、門控前饋層和位置資訊這幾個部分,以殘差連接組合成一個 transformer 區塊,再將多個區塊堆疊成完整的語言模型。
課程大綱:11 節
-
將每個部分的輸出加到殘差串流
- 執行
residual-stream.py - 實用原則 將每個區塊都寫成對殘差串流的加法,而不是取代,並讓串流的寬度在整個模型中保持一致,使各次加法能夠對齊。除錯深層模型時,請量測每個部分所加入的內容:幾乎沒有加入任何東西的部分,就幾乎沒有做任何事。
- 執行
-
在每個部分之前先正規化
- 執行
rms-norm-by-hand.py - 實用原則 在區塊的每個部分之前做正規化,而不是之後,並在輸出層之前再對殘差流正規化一次。除非你要與使用層正規化的模型保持一致,否則使用 RMSNorm。載入其他模型的權重時,要先檢查它使用哪一種正規化、用在何處,以及 ε 為何,再進行其他事情:細節不一致的範例顯示了小小的不一致會付出什麼代價。
- 執行
-
Transform each position with a gated feed-forward layer
- 執行
gated-feed-forward.py - 實用原則 Use a gated feed-forward layer with SiLU. Set its width so its three matrices hold as many parameters as a plain layer four times the stream's width, the original transformer's ratio, 2,048 for 512 (Vaswani et al., 2017, section 3.3): that's about 8/3 times the width. SmolLM2-360M uses exactly 8/3, 2,560 for 960. The store's model rounds 8/3 of its width up to a multiple of 32, a rule of thumb that keeps matrix sizes convenient for hardware. When you load another model, check whether its feed-forward layer is gated, since a gated layer has three matrices where a plain one has two.
- 執行
-
Give attention positions with rotations
- 執行
rope-by-hand.py - 執行
figure-rope-depends-on-offset.py - 實用原則 Use rotary position embeddings, applied to queries and keys, never values. When you load another model's weights, check how its RoPE pairs the numbers and what base it uses. Some implementations pair neighbouring numbers; others pair the first half with the second, as
lib.transformer.ropedoes and as SmolLM2's configuration states with"rope_interleaved": false. SmolLM2 uses a base of 100,000 where the store's model uses 10,000.
- 執行
-
將輸出層與嵌入綁定
- 實用原則 在小型模型中將輸出層與嵌入綁定,而且在尋找獨立的輸出矩陣之前,先檢查你載入的模型是否已經綁定。讓自己撰寫的前向傳遞短到可以整段讀完,就像
lib.transformer那樣,如此後續各節所測試的每個細節都看得見。
- 實用原則 在小型模型中將輸出層與嵌入綁定,而且在尋找獨立的輸出矩陣之前,先檢查你載入的模型是否已經綁定。讓自己撰寫的前向傳遞短到可以整段讀完,就像
-
Check the model against PyTorch
- 執行
transformer-same-as-pytorch.py - 實用原則 Check your own forward pass against the training library's outputs on a full text, not a single position. Where the library has its own implementation of a part, train with it, so the check compares two independent implementations; where it doesn't, as with RoPE here, test the part's properties by hand.
- 執行
-
移除一個區塊,看它做了什麼
- 先詢問 Predict one, then score the names and descriptions of the first 100 validation products, 7,624 predictions in all, with the full model and with each block left out in turn:
- 執行
skip-a-block.py - 實用原則 要了解模型的某個部分做了什麼,應將它移除並加以衡量,而不是從權重去推論。可預期第一個區塊最為重要,因為後面的一切都建立在它之上;除此之外就要實際衡量,因為在這裡第二個與最後一個區塊的重要性大致相當,且都高於第三個。對於移除某個部分後損失很小的情況,解讀時要謹慎:其餘部分是與它一起訓練的,所以這項衡量說明的是已訓練模型依賴什麼,而不是該部分單獨能做什麼。
-
衡量不相符的細節所造成的代價
- 執行
mismatched-details.py - 實用原則 載入其他模型的權重時,要將它的設定與你的程式碼逐行核對:正規化及其 ε、RoPE 的配對方式與基底、前饋層的閘控、綁定的輸出,以及有多少個頭共用鍵與值。接著用你熟悉的文字,對照原始實作的輸出來評分;損失很小又沒有錯誤,才是最該提防的情況。
- 執行
-
Count where the parameters go
- 執行
transformer-parameters.py - 實用原則 Count parameters by part whenever you design or load a model. At small sizes, the embedding table is a large share of the total, so tie it to the output layer, and choose the vocabulary size with that cost in mind, as chapter 2's choice of merges did.
- 執行
- 正式環境中會出什麼問題
- 本章的決定
8. 訓練小型模型
閱讀約需 49 分鐘,含 8 個範例。
讀完本章,你就能從頭到尾訓練一個小型 transformer,並評斷訓練的結果。
課程大綱:10 節
-
將商品轉為批次
- 關鍵詞 inputs, targets
- 執行
training-batches.py - 實用原則 將批次建構為輸入與位移後的目標,在損失中遮蔽填充,並在每個 epoch 以固定的種子對文字洗牌,使執行過程可以重現。請測量批次中填充所占的比例;若比例很大,在購買更大的機器之前,先封裝文字或依長度將它們分組。
-
使用 AdamW 與梯度裁剪進行更新
- 實用原則 使用 AdamW 並搭配適度的權重衰減,同時依梯度的合併長度進行裁剪。讓訓練步驟短到可以完整讀完,使其中每個選擇都清楚可見:損失忽略什麼、優化器衰減什麼,以及裁剪什麼。
-
先暖身,再衰減步長
- 執行
learning-rate-schedule.py - 執行
figure-learning-rate-schedule.py - 實用原則 在最初幾百步內將步長暖身上升,然後使其衰減,並讓排程的長度與訓練的長度相符。如同訓練腳本所做的,在訓練進行時儲存步長,並與你原本打算使用的排程核對:排程的錯誤看起來像是訓練上的問題,用這種方式要容易找出得多。
- 執行
-
解讀訓練曲線
- 執行
transformer-training-curve.py - 實用原則 針對你在意的每一種文字,逐 epoch 記錄驗證損失,並保留最佳 epoch 的權重。要把訓練與驗證之間的差距當作警訊來解讀,而不是只看訓練損失。絕不要跨不同種類的文字比較困惑度。
- 執行
-
與名稱上的基準線比較
- 執行
transformer-on-names.py - 實用原則 以完全相同的預測,將新模型與你能建立的最強基準線比較,包括各自如何標示文本的結尾。當學習得到的模型與計數模型表現接近時,就把兩者混合,並在保留的文本上選擇混合比例。
- 執行
-
Compare on descriptions
- 執行
transformer-on-descriptions.py - 實用原則 Measure a model on the kind of text it will predict, against a baseline that sees the same text, and expect the ranking to change from one kind of text to another. Split the comparison by seen and unseen contexts to see where each model wins. Try a mix before concluding that either model is enough: the mix gained more than any change to either model that this chapter measured.
- 執行
-
寬度、資料與訓練步數能換來什麼
- 執行
width-data-and-steps.py - 實用原則 在把手上的文字重複超過數次之前,先取得更多與你要預測的內容同類的文字;這樣做每一步都不會多花成本。若有多餘的運算資源,先試試用較少的 epoch 訓練較寬的模型,再考慮把窄模型訓練得更久,並且兩者都要測量。每次訓練只改變一件事,並在關鍵之處固定步數,否則這個比較會同時測量到兩件事。
- 執行
-
Suggest the next word in the search box
- 執行
transformer-autocomplete.py - 實用原則 Serve the mix for autocomplete, and test it on rare prefixes as well as common ones, with control prefixes beside each. Treat a single striking suggestion as an illustration of a measured gain, never as the evidence for it.
- 執行
- 正式環境中會出什麼問題
- What this chapter decided
9. Choosing the next token
閱讀約需 39 分鐘,含 8 個範例。
學習結束時,學員能夠turn a language model's probabilities into text, and choose how:
- always the likeliest token
- the likeliest whole text by beam search
- a sample shaped by a temperature
- a top-k or top-p cut
- a repetition penalty and a minimum length
課程大綱:9 節
-
選擇最可能的詞元
- 執行
greedy-description.py - 實用原則 當你希望每次都得到相同的輸出,而且文字很短時,例如搜尋框的建議,而重點正是最可能的下一個字詞,就使用貪婪解碼。若文字長過一個片語,預期它會重複自己,並從後續各節的方法中選擇一種。
- 執行
-
搜尋最可能的文字
- 執行
beam-search.py - 實用原則 對於以最可能的詞組為目標的簡短補全,例如搜尋查詢,請使用束搜尋,並依總機率排序。對於較長的文字,請依每個詞元的機率來排序已完成的文字,因為總機率偏好最短的文字;即使如此,仍宜優先採用後續各節的取樣方法,它們寫出的文字更接近人類所寫。
- 執行
-
以溫度進行取樣
- 執行
temperature-by-hand.py - 執行
figure-temperature-flattens.py - 實用原則 把溫度視為在可預測與多樣化文字之間調整的旋鈕。若文字應貼近訓練文字通常的說法,例如產品描述,請將溫度維持在 1 或略低於 1。較低的溫度會讓文字更可預測,而不是更準確。
- 執行
-
取樣並截去尾部
- 執行
sample-descriptions.py - 實用原則 若要產生多樣的文字,請以約 0.9 的 top-p 或約 20 的 top-k 截去尾部,並將溫度設為 1 或略低於 1;需要重現結果時,請固定隨機種子。不要期望任何設定能讓文字變得真實:解碼是在模型認為合理的內容之間做選擇,而查核事實是另一項工作。
- 執行
-
測量每種設定寫出了什麼
- 執行
measure-decoding.py - 實用原則 在閱讀樣本之前,先以這類測量比較各種解碼設定,並以同類的真實文字作為對照。決定哪一項測量對這項工作最重要:對產品描述而言,緊扣產品與不重複最優先。接著仍要閱讀一部分輸出樣本,找出測量抓不到的問題,並對照產品資料查核每一項事實陳述。
- 執行
-
懲罰重複
- 執行
repetition-penalty-by-hand.py - 實用原則 以貪婪解碼或低溫度解碼時,加上約 1.2 至 1.3 的重複懲罰,並檢查它對長度的影響,因為它會縮短文字。經驗上,若描述顯得被截斷,可將常見的虛詞與標點符號排除在懲罰之外。
- 執行
-
禁止空白描述
- 執行
minimum-length.py - 實用原則 只要訓練文字中含有你所要產生之內容的空白或極短範例,就應設定最小長度。請將它與本章的其他設定合併使用,而不是用它取代其他設定;並且預期被它強迫產生的文字,需要和其他任何文字一樣接受檢查。
- 執行
- 正式環境中會出什麼問題
- 本章的決定
10. Inside an open model
閱讀約需 55 分鐘,含 9 個範例。
學習結束時,學員能夠read an open language model with what this book has built:
- count where its parameters go
- work out what it costs to run
- score text with it fairly against a model with a different tokenizer
- find the attention patterns of chapter 6 in its heads
- test what it copies
- learn what its size buys on the store's text
- what it doesn't
課程大綱:10 節
-
Count the parameters at scale
- 執行
open-model-parameters.py - 實用原則 Count an open model's parameters by part from its weights before you use it, and read the shapes for its design choices: tied embeddings, grouped keys and values, a gated feed-forward layer. Expect the blocks, not the embeddings, to hold most of a large model's parameters.
- 執行
-
比較同一系列的各種規模
- 執行
open-model-family.py - 實用原則 依照設定計算模型的參數量,並將計算結果與其權重核對;若兩者不符,代表你誤讀了某個細節。比較同一系列的各種規模,以了解開發者如何擴展設計,並且不要假設較大的模型與較小的模型只有規模上的差異。
- 執行
-
計算執行的成本
- 執行
open-model-memory.py - 執行
figure-kv-cache-grows.py - 實用原則 依模型的設定,將其記憶體預算編列為權重加上每段進行中文字各一份的快取。在處理長文字或同時處理多段文字時,優先選用有分組鍵值的模型,並將允許的文字長度上限訂在預算所能負擔的範圍內。
- 執行
-
以通用模型為商店的文字評分
- 執行
open-model-on-the-store.py - 實用原則 比較使用不同 tokenizer 的模型時,要在完全相同的文字與事件上,以每詞或每字元為單位,絕不以每詞元為單位。在選擇大型通用模型而不選擇以自己文字訓練的小模型之前,先在你的文字上量測兩者;模型的規模無法彌補文字與其所學內容截然不同的落差。
- 執行
-
Find the same heads at scale
- 執行
open-model-heads.py - 執行
figure-first-token-sinks.py - 實用原則 Describe a large model's heads by the same measured averages you'd use on a small one, compared with an even spread. Expect a few specialized heads and many that put their weight on the first token, and keep that token when you cut a model's context to save memory.
- 執行
-
Test copying at scale
- 執行
open-model-copying.py - 實用原則 Test a behaviour by changing the input and watching the output, and run the same test on every model you compare. When two models of very different sizes share a behaviour, it's a basic one; look for what differs elsewhere.
- 執行
-
Suggest the next word at scale
- 執行
open-model-autocomplete.py - 實用原則 Don't put a general model in front of shoppers without measuring its suggestions on your own prefixes against what you have. Where a model trained on your text suggests better, keep it, and measure a general model on the jobs where its broader knowledge could matter.
- 執行
-
將兩個模型並排比較
- 實用原則 把你要在其中挑選的每個模型,依對你的工作重要的指標並排比較,每一欄都使用相同的文字與相同的測試。依工作挑選模型,而不是用一個模型處理所有事情。
- 正式環境中會出什麼問題
- 本章的決定
11. 從預測到遵循指令
閱讀約需 46 分鐘,含 11 個範例。
讀完本章後,你將能說明一個預測下一個 token 的模型,如何成為能遵循請求的模型;建構達成這件事的兩種訓練損失;並衡量這項改變能解決與無法解決的問題。
課程大綱:10 節
-
Build the two training losses by hand
- 執行
instruction-loss-by-hand.py - 執行
dpo-loss-by-hand.py - 執行
figure-dpo-loss-curve.py - 實用原則 Mask the request out of the loss when you tune a model on requests and responses, and keep the reference model's log-probabilities beside the tuned model's when you train on preferences. Both are small changes to a loop you already have.
- 執行
-
詢問基礎模型與調校後的模型
- 執行
base-and-tuned.py - 實用原則 需要模型遵循請求時,使用調校後的模型;需要依照前文的風格接續文字時,使用基礎模型。不要把流暢當成知識:調校後的模型在同樣缺乏事實的情況下,只是寫出形式更好的描述。
- 執行
-
依模型調校時的格式來組成請求
- 關鍵詞 chat template
- 執行
chat-template.py - 實用原則 對調校後的模型,一律使用它自己的聊天範本來組成請求,並由函式庫從模型的分詞器檔案套用,不要手動拼裝。請檢查範本的預設系統訊息,因為模型在每次請求中都會讀到它;並且在保留每一則回答時,一併記錄完整格式化後的提示。
-
衡量捏造的產品細節
- 執行
made-up-materials.py - 實用原則 測試模型時,不要只用輸入能回答的問題,也要用輸入無法回答的問題,並將捏造的回答另外計數。模型對產品提出的每一項事實主張,都要與產品資料核對,能自動化就自動化,就像
lib.claims對材質所做的那樣。
- 執行
-
檢查信心是否能發出警訊
- 執行
answer-confidence.py - 執行
figure-confidence-overlap.py - 實用原則 不要單憑模型的信心來決定是否信任一個回答。請在自己的問題上衡量其信心與答對與否的關係;若要使用門檻,就依這些衡量結果來選擇,並計算它放過了多少錯誤。
- 執行
-
找出較長的上下文會遺失什麼
- 執行
answer-position.py - 實用原則 將模型最需要的細節放在上下文的開頭或結尾,而不是中間,並且在任務許可的範圍內,盡量少給它不相關的文字。在相信模型能從大量資料中找出細節之前,先測試它在較長上下文中各個位置的檢索表現。
- 執行
-
讓模型適應你的文字
- 執行
lora-parameters.py - 實用原則 要讓通用模型學會你的文字,就在該文字上對它進行微調;記憶體或儲存空間吃緊時,使用 LoRA;並在同類型的保留文字上衡量結果。不要期待指令微調或更巧妙的提示詞,能提供模型從未學過的知識。
- 執行
-
回顧評量標準
- 執行
test-names.py - 實用原則 比較模型時,應維持一套固定的評量標準,即每次都使用相同的文字、分詞器與衡量方式,如同本書所做的。然後,在選定模型來負責某項工作之前,先用針對該工作設計的測試衡量工作本身:較低的困惑度是測試某個模型的理由,而不是將它上線的理由。
- 執行
- 正式環境中會出什麼問題
- 本章的決定
測驗題庫
每章皆附習題與解答,供經驗證的教育工作者使用。每個解答都對應其所屬的節。 如何取得
正在載入測驗題庫…