使用Llama.cpp在CPU上快速的运行LLM

大型语言模型(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合并到您的应用程序中,我建议深入的研究一下这个包。

本文源代码:

https://avoid.overfit.cn/post/257997272e4a454cae9d01556332d6a0

本文作者:Ashwin Mathur

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年12月27日
下一篇 2023年12月27日

相关推荐