大型語言模型(llm)正變得越來越流行,但是它需要很多的資源,尤其時GPU。在這篇文章中,我們将介紹如何使用Python中的llama.cpp庫在高性能的cpu上運作llm。
大型語言模型(llm)正變得越來越流行,但是它們的運作在計算上是非常消耗資源的。有很多研究人員正在為改進這個缺點而努力,比如HuggingFace開發出支援4位和8位的模型加載。但它們也需要GPU才能工作。雖然可以在直接在cpu上運作這些llm,但CPU的性能還無法滿足現有的需求。而Georgi Gerganov最近的工作使llm在高性能cpu上運作成為可能。這要歸功于他的llama.cpp庫,該庫為各種llm提供了高速推理。
原始的llama.cpp庫側重于在shell中本地運作模型。這并沒有為使用者提供很大的靈活性,并且使使用者很難利用大量的python庫來建構應用程式。而最近LangChain的發展使得我可以可以在python中使用llama.cpp。
在這篇文章中,我們将介紹如何在Python中使用llama-cpp-python包使用llama.cpp庫。我們還将介紹如何使用LLaMA -cpp-python庫來運作Vicuna LLM。
llama- pcp -python
pip install llama-cpp-python
更詳細的安裝說明,請參閱llama- pcp -python文檔:https://github.com/abetlen/llama-cpp-python#installation-from-pypi-recommended。
使用LLM和llama-cpp-python
隻要語言模型轉換為GGML格式,就可以被llama.cpp加載和使用。而大多數流行的LLM都有可用的GGML版本。
需要注意的重要一點是,在将原始llm轉換為GGML格式時,它們就已被量化過了。量化的好處是在不顯著降低性能的情況下,減少運作這些大型模型所需的記憶體。例如,在不到4GB的RAM中可以加載大小為13GB的70億個參數模型。
在本文中,我們使用GGML版本的Vicuna-7B,該模型可從HuggingFace下載下傳:https://huggingface.co/CRD716/ggml-vicuna-1.1-quantized。
下載下傳GGML檔案并加載LLM
可以使用以下代碼下載下傳模型。該代碼還在嘗試下載下傳檔案之前檢查該檔案是否已經存在。
import os
import urllib.request
def download_file(file_link, filename):
# Checks if the file already exists before downloading
if not os.path.isfile(filename):
urllib.request.urlretrieve(file_link, filename)
print("File downloaded successfully.")
else:
print("File already exists.")
# Dowloading GGML model from HuggingFace
ggml_model_path = "https://huggingface.co/CRD716/ggml-vicuna-1.1-quantized/resolve/main/ggml-vicuna-7b-1.1-q4_1.bin"
filename = "ggml-vicuna-7b-1.1-q4_1.bin"
download_file(ggml_model_path, filename)
下一步是加載模型:
from llama_cpp import Llama
llm = Llama(model_path="ggml-vicuna-7b-1.1-q4_1.bin", n_ctx=512, n_batch=126)
在加載模型時,應該設定兩個重要參數。
n_ctx:用于設定模型的最大上下文大小。預設值是512個token。
上下文大小是輸入提示符中的令牌數量和模型可以生成的令牌最大數量的總和。具有較小上下文大小的模型生成文本的速度比具有較大上下文大小的模型快得多。
n_batch:用于設定在生成文本時要批處理的提示令牌的最大數量。預設值是512個token。
應該仔細設定n_batch參數。降低n_batch有助于加速多線程cpu上的文本生成。但是太少可能會導緻文本生成明顯惡化。
使用LLM生成文本
下面的代碼編寫了一個簡單的包裝器函數來使用LLM生成文本。
def generate_text(
prompt="Who is the CEO of Apple?",
max_tokens=256,
temperature=0.1,
top_p=0.5,
echo=False,
stop=["#"],
):
output = llm(
prompt,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
echo=echo,
stop=stop,
)
output_text = output["choices"][0]["text"].strip()
return output_text
llm對象有幾個重要的參數:
prompt:模型的輸入提示。該文本被标記并傳遞給模型。
max_tokens:該參數用于設定模型可以生成的令牌的最大數量。此參數控制文本生成的長度。預設值是128個token。
temperature:溫度,介于0和1之間。較高的值(如0.8)将使輸出更加随機,而較低的值(如0.2)将使輸出更加集中和确定。預設值為1。
top_p:溫度采樣的替代方案,稱為核采樣,其中模型考慮具有top_p機率品質的标記的結果。是以0.1意味着隻考慮包含前10%機率品質的标記。
echo: 用于控制模型是否傳回(回顯)生成文本開頭的模型提示符。
stop:用于停止文本生成的字元串清單。如果模型遇到任何字元串,文本生成将在該标記處停止。用于控制模型幻覺,防止模型産生不必要的文本。
llm對象傳回如下形式的字典對象:
{
"id": "xxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", # text generation id
"object": "text_completion", # object name
"created": 1679561337, # time stamp
"model": "./models/7B/ggml-model.bin", # model path
"choices": [
{
"text": "Q: Name the planets in the solar system? A: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune and Pluto.", # generated text
"index": 0,
"logprobs": None,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 14, # Number of tokens present in the prompt
"completion_tokens": 28, # Number of tokens present in the generated text
"total_tokens": 42
}
}
可以使用output"choices"["text"]從字典對象中提取生成的文本。
使用Vicuna-7B生成文本的示例代碼
import os
import urllib.request
from llama_cpp import Llama
def download_file(file_link, filename):
# Checks if the file already exists before downloading
if not os.path.isfile(filename):
urllib.request.urlretrieve(file_link, filename)
print("File downloaded successfully.")
else:
print("File already exists.")
# Dowloading GGML model from HuggingFace
ggml_model_path = "https://huggingface.co/CRD716/ggml-vicuna-1.1-quantized/resolve/main/ggml-vicuna-7b-1.1-q4_1.bin"
filename = "ggml-vicuna-7b-1.1-q4_1.bin"
download_file(ggml_model_path, filename)
llm = Llama(model_path="ggml-vicuna-7b-1.1-q4_1.bin", n_ctx=512, n_batch=126)
def generate_text(
prompt="Who is the CEO of Apple?",
max_tokens=256,
temperature=0.1,
top_p=0.5,
echo=False,
stop=["#"],
):
output = llm(
prompt,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
echo=echo,
stop=stop,
)
output_text = output["choices"][0]["text"].strip()
return output_text
generate_text(
"Compose an engaging travel blog post about a recent trip to Hawaii, highlighting cultural experiences and must-see attractions.",
max_tokens=356,
)
生成的文本如下:
Hawaii is a state located in the United States of America that is known for its beautiful beaches, lush landscapes, and rich culture. It is made up of six islands: Oahu, Maui, Kauai, Lanai, Molokai, and Hawaii (also known as the Big Island). Each island has its own unique attractions and experiences to offer visitors.
One of the most interesting cultural experiences in Hawaii is visiting a traditional Hawaiian village or ahupuaa. An ahupuaa is a system of land use that was used by ancient Hawaiians to manage their resources sustainably. It consists of a coastal area, a freshwater stream, and the surrounding uplands and forests. Visitors can learn about this traditional way of life at the Polynesian Cultural Center in Oahu or by visiting a traditional Hawaiian village on one of the other islands.
Another must-see attraction in Hawaii is the Pearl Harbor Memorial. This historic site commemorates the attack on Pearl Harbor on December 7, 1941, which led to the United States' entry into World War II. Visitors can see the USS Arizona Memorial, a memorial that sits above the sunken battleship USS Arizona and provides an overview of the attack. They can also visit other museums and exhibits on the site to learn more about this important event in American history.
Hawaii is also known for its beautiful beaches and crystal clear waters, which are perfect for swimming, snorkeling, and sunbathing.
總結
在這篇文章中,我們介紹了如何在Python中使用llama.cpp庫和llama-cpp-python包。這些工具支援基于cpu的llm高性能執行。
Llama.cpp幾乎每天都在更新。推理的速度越來越快,社群定期增加對新模型的支援。在Llama.cpp有一個“convert.py”可以幫你将自己的Pytorch模型轉換為ggml格式。
llama.cpp庫和llama-cpp-python包為在cpu上高效運作llm提供了健壯的解決方案。如果您有興趣将llm合并到您的應用程式中,我建議深入的研究一下這個包。
本文作者:Ashwin Mathur