在ctransformers
库中,我只能加载大约十几个支持的模型。我如何在CPU上(不仅仅是GPU)运行任何以GGUF格式量化的开源LLM模型的本地推理(例如,Llama 3、Mistral、Zephyr,即ctransformers
中不支持的模型)?
回答:
llama-cpp-python
是我个人的选择,因为它易于使用,并且通常是第一个支持新模型量化版本的库之一。要在CPU上安装它,只需运行pip install llama-cpp-python
。编译GPU版本稍微复杂一些,所以由于你特别询问了关于CPU推理的问题,我在这里就不发布那些指令了。我还建议安装huggingface_hub
(pip install huggingface_hub
)以便轻松下载模型。
一旦你安装了llama-cpp-python
和huggingface_hub
,你可以像这样下载并使用一个模型(例如mixtral-8x7b-instruct-v0.1-gguf):
## Importsfrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llama## Download the GGUF modelmodel_name = "TheBloke/Mixtral-8x7B-Instruct-v0.1-GGUF"model_file = "mixtral-8x7b-instruct-v0.1.Q4_K_M.gguf" # 这是我们在这个例子中将使用的特定模型文件。这是一个4位量化模型,但如果需要,模型仓库中还有其他量化级别的模型可供选择model_path = hf_hub_download(model_name, filename=model_file)## Instantiate model from downloaded filellm = Llama( model_path=model_path, n_ctx=16000, # 使用的上下文长度 n_threads=32, # 使用的CPU线程数 n_gpu_layers=0 # 卸载到GPU的模型层数)## Generation kwargsgeneration_kwargs = { "max_tokens":20000, "stop":["</s>"], "echo":False, # 在输出中回显提示 "top_k":1 # 这基本上是贪婪解码,因为模型总是返回概率最高的标记。将此值设置为>1以进行采样解码}## Run inferenceprompt = "The meaning of life is "res = llm(prompt, **generation_kwargs) # Res是一个字典## Unpack and the generated text from the LLM response dictionary and print itprint(res["choices"][0]["text"])# res是result的缩写
请注意,mixtral对于大多数笔记本电脑来说是一个相当大的模型,需要大约25+ GB的RAM,所以如果你需要一个更小的模型,可以尝试使用像llama-13b-chat-gguf(model_name="TheBloke/Llama-2-13B-chat-GGUF"; model_file="llama-2-13b-chat.Q4_K_M.gguf"
)或mistral-7b-openorca-gguf(model_name="TheBloke/Mistral-7B-OpenOrca-GGUF"; model_file="mistral-7b-openorca.Q4_K_M.gguf"
)这样的模型。