自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用Llama.cpp在CPU上快速的運(yùn)行LLM

開(kāi)發(fā) 前端
大型語(yǔ)言模型(llm)正變得越來(lái)越流行,但是它需要很多的資源,尤其時(shí)GPU。在這篇文章中,我們將介紹如何使用Python中的llama.cpp庫(kù)在高性能的cpu上運(yùn)行l(wèi)lm。

大型語(yǔ)言模型(llm)正變得越來(lái)越流行,但是它需要很多的資源,尤其時(shí)GPU。在這篇文章中,我們將介紹如何使用Python中的llama.cpp庫(kù)在高性能的cpu上運(yùn)行l(wèi)lm。

大型語(yǔ)言模型(llm)正變得越來(lái)越流行,但是它們的運(yùn)行在計(jì)算上是非常消耗資源的。有很多研究人員正在為改進(jìn)這個(gè)缺點(diǎn)而努力,比如HuggingFace開(kāi)發(fā)出支持4位和8位的模型加載。但它們也需要GPU才能工作。雖然可以在直接在cpu上運(yùn)行這些llm,但CPU的性能還無(wú)法滿(mǎn)足現(xiàn)有的需求。而Georgi Gerganov最近的工作使llm在高性能cpu上運(yùn)行成為可能。這要?dú)w功于他的llama.cpp庫(kù),該庫(kù)為各種llm提供了高速推理。

原始的llama.cpp庫(kù)側(cè)重于在shell中本地運(yùn)行模型。這并沒(méi)有為用戶(hù)提供很大的靈活性,并且使用戶(hù)很難利用大量的python庫(kù)來(lái)構(gòu)建應(yīng)用程序。而最近LangChain的發(fā)展使得我可以可以在python中使用llama.cpp。

在這篇文章中,我們將介紹如何在Python中使用llama-cpp-python包使用llama.cpp庫(kù)。我們還將介紹如何使用LLaMA -cpp-python庫(kù)來(lái)運(yùn)行Vicuna LLM。

llama- pcp -python

pip install llama-cpp-python

更詳細(xì)的安裝說(shuō)明,請(qǐng)參閱llama- pcp -python文檔:https://github.com/abetlen/llama-cpp-python#installation-from-pypi-recommended。

使用LLM和llama-cpp-python

只要語(yǔ)言模型轉(zhuǎn)換為GGML格式,就可以被llama.cpp加載和使用。而大多數(shù)流行的LLM都有可用的GGML版本。

需要注意的重要一點(diǎn)是,在將原始llm轉(zhuǎn)換為GGML格式時(shí),它們就已被量化過(guò)了。量化的好處是在不顯著降低性能的情況下,減少運(yùn)行這些大型模型所需的內(nèi)存。例如,在不到4GB的RAM中可以加載大小為13GB的70億個(gè)參數(shù)模型。

在本文中,我們使用GGML版本的Vicuna-7B,該模型可從HuggingFace下載:https://huggingface.co/CRD716/ggml-vicuna-1.1-quantized。

下載GGML文件并加載LLM

可以使用以下代碼下載模型。該代碼還在嘗試下載文件之前檢查該文件是否已經(jīng)存在。

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)

在加載模型時(shí),應(yīng)該設(shè)置兩個(gè)重要參數(shù)。

n_ctx:用于設(shè)置模型的最大上下文大小。默認(rèn)值是512個(gè)token。

上下文大小是輸入提示符中的令牌數(shù)量和模型可以生成的令牌最大數(shù)量的總和。具有較小上下文大小的模型生成文本的速度比具有較大上下文大小的模型快得多。

n_batch:用于設(shè)置在生成文本時(shí)要批處理的提示令牌的最大數(shù)量。默認(rèn)值是512個(gè)token。

應(yīng)該仔細(xì)設(shè)置n_batch參數(shù)。降低n_batch有助于加速多線程cpu上的文本生成。但是太少可能會(huì)導(dǎo)致文本生成明顯惡化。

使用LLM生成文本

下面的代碼編寫(xiě)了一個(gè)簡(jiǎn)單的包裝器函數(shù)來(lái)使用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對(duì)象有幾個(gè)重要的參數(shù):

prompt:模型的輸入提示。該文本被標(biāo)記并傳遞給模型。

max_tokens:該參數(shù)用于設(shè)置模型可以生成的令牌的最大數(shù)量。此參數(shù)控制文本生成的長(zhǎng)度。默認(rèn)值是128個(gè)token。

temperature:溫度,介于0和1之間。較高的值(如0.8)將使輸出更加隨機(jī),而較低的值(如0.2)將使輸出更加集中和確定。缺省值為1。

top_p:溫度采樣的替代方案,稱(chēng)為核采樣,其中模型考慮具有top_p概率質(zhì)量的標(biāo)記的結(jié)果。所以0.1意味著只考慮包含前10%概率質(zhì)量的標(biāo)記。

echo: 用于控制模型是否返回(回顯)生成文本開(kāi)頭的模型提示符。

stop:用于停止文本生成的字符串列表。如果模型遇到任何字符串,文本生成將在該標(biāo)記處停止。用于控制模型幻覺(jué),防止模型產(chǎn)生不必要的文本。

llm對(duì)象返回如下形式的字典對(duì)象:

{
  "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"]從字典對(duì)象中提取生成的文本。

使用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.

總結(jié)

在這篇文章中,我們介紹了如何在Python中使用llama.cpp庫(kù)和llama-cpp-python包。這些工具支持基于cpu的llm高性能執(zhí)行。

Llama.cpp幾乎每天都在更新。推理的速度越來(lái)越快,社區(qū)定期增加對(duì)新模型的支持。在Llama.cpp有一個(gè)“convert.py”可以幫你將自己的Pytorch模型轉(zhuǎn)換為ggml格式。

llama.cpp庫(kù)和llama-cpp-python包為在cpu上高效運(yùn)行l(wèi)lm提供了健壯的解決方案。如果您有興趣將llm合并到您的應(yīng)用程序中,我建議深入的研究一下這個(gè)包。

本文源代碼:

https://github.com/awinml/llama-cpp-python-bindings

責(zé)任編輯:華軒 來(lái)源: DeepHub IMBA
相關(guān)推薦

2025-01-20 07:58:51

2024-08-13 14:20:00

模型數(shù)據(jù)

2023-08-17 16:07:16

模型優(yōu)化

2024-03-26 08:00:00

LLMVLMRaspberry

2025-04-29 07:47:27

2023-12-19 16:12:40

GPT-4AI聊天機(jī)器人人工智能

2023-08-01 13:31:18

模型Alpacaicuna

2020-04-02 16:02:44

PythonGithub博客

2020-04-02 18:30:28

PythonGitHub編程語(yǔ)言

2013-12-18 11:04:57

CPU雙核

2023-04-12 15:37:31

Linux系統(tǒng)CPU

2018-12-14 08:29:56

CPU編程x86

2024-12-16 07:00:00

2014-12-17 15:18:27

LinuxMonoWindows

2024-05-15 08:42:19

Phi-3LLM機(jī)器學(xué)習(xí)

2025-01-08 08:00:00

2022-01-18 17:57:21

PodmanLinux容器

2025-04-08 03:22:00

2022-06-30 13:54:16

BottlesLinuxWindows

2017-05-03 11:10:14

Linux進(jìn)程監(jiān)控cpustat
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)