LLM探索:GPT類模型的幾個常用參數 Top-k, Top-p, Temperature
前言
上一篇文章介紹了幾個開源LLM的環境搭建和本地部署,在使用ChatGPT接口或者自己本地部署的LLM大模型的時候,經常會遇到這幾個參數,本文簡單介紹一下~
- temperature
- top_p
- top_k
關于LLM
上一篇也有介紹過,這次看到一個不錯的圖
A recent breakthrough in artificial intelligence (AI) is the introduction of language processing technologies that enable us to build more intelligent systems with a richer understanding of language than ever before. Large pre-trained Transformer language models, or simply large language models, vastly extend the capabilities of what systems are able to do with text.
LLM看似很神奇,但本質還是一個概率問題,神經網絡根據輸入的文本,從預訓練的模型里面生成一堆候選詞,選擇概率高的作為輸出,上面這三個參數,都是跟采樣有關(也就是要如何從候選詞里選擇輸出)。
temperature
用于控制模型輸出的結果的隨機性,這個值越大隨機性越大。一般我們多次輸入相同的prompt之后,模型的每次輸出都不一樣。
- 設置為 0,對每個prompt都生成固定的輸出
- 較低的值,輸出更集中,更有確定性
- 較高的值,輸出更隨機(更有創意??)
一般來說,prompt 越長,描述得越清楚,模型生成的輸出質量就越好,置信度越高,這時可以適當調高 temperature 的值;反過來,如果 prompt 很短,很含糊,這時再設置一個比較高的 temperature 值,模型的輸出就很不穩定了。
遇事不決就調參,調一下,萬一就生成了不錯的回答呢?
PS:ChatGLM提供的例子把范圍限定在0-1之間。
top_k & top_p
這倆也是采樣參數,跟 temperature 不一樣的采樣方式。
前面有介紹到,模型在輸出之前,會生成一堆 token,這些 token 根據質量高低排名。
比如下面這個圖片,輸入 The name of that country is the
這句話,模型生成了一堆 token,然后根據不同的 decoding strategy
從 tokens 中選擇輸出。
這里的 decoding strategy
可以選擇
- greedy decoding: 總是選擇最高分的 token,有用但是有些弊端,詳見下文
- top-k: 從 tokens 里選擇 k 個作為候選,然后根據它們的
likelihood scores
來采樣 - top-p: 候選詞列表是動態的,從 tokens 里按百分比選擇候選詞
top-k 與 top-p 為選擇 token 引入了隨機性,讓其他高分的 token 有被選擇的機會,不像 greedy decoding 一樣總是選最高分的。
greedy decoding
好處是簡單,壞處是容易生成循環、重復的內容
Greedy decoding is a reasonable strategy but has some drawbacks such as outputs with repetitive loops of text. Think of the suggestions in your smartphone's auto-suggest. When you continually pick the highest suggested word, it may devolve into repeated sentences.
top-k
設置越大,生成的內容可能性越大;
設置越小,生成的內容越固定;
設置為1時,和 greedy decoding
效果一樣。
Changing the top-k parameter sets the size of the shortlist the model samples from as it outputs each token. Setting top-k to 1 gives us greedy decoding.
top-p
top-p 又名 Nucleus Sampling(核采樣)
與 top-k 固定選取前 k 個 tokens 不同,top-p 選取的 tokens 數量不是固定的,這個方法是設定一個概率閾值。
繼續上面的例子,將 top-p 設定為 0.15,即選擇前 15% 概率的 tokens 作為候選。如下圖所示,United 和 Netherlands 的概率加起來為 15% ,所以候選詞就是這倆,最后再從這些候選詞里,根據概率分數,選擇 united 這個詞。
Top-p is usually set to a high value (like 0.75) with the purpose of limiting the long tail of low-probability tokens that may be sampled. We can use both top-k and top-p together. If both
k
andp
are enabled,p
acts afterk
.
經常遇到的默認 top-p 值就是 0.7/0.8 這樣,還是那個說法,設置太低模型的輸出太固定,設置太高,模型徹底放飛自我也不好。