Hub Python 库文档

在服务器上运行推理

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

在服务器上运行推理

推理是使用训练好的模型对新数据进行预测的过程。由于此过程可能需要大量的计算,因此在专用或外部服务上运行可能是一个有趣的选择。huggingface_hub 库提供了一个统一的接口,用于在托管在 Hugging Face Hub 上的模型的多个服务上运行推理。

  1. HF Inference API:一种无服务器解决方案,允许您在 Hugging Face 的基础设施上免费运行模型推理。此服务是快速入门、测试不同模型和原型 AI 产品的快捷方式。
  2. 第三方提供商:由外部提供商(Together、Sambanova 等)提供的各种无服务器解决方案。这些提供商以按需付费模式提供生产就绪的 API。这是将 AI 集成到您的产品中的最快方式,具有免维护和可扩展的解决方案。有关支持的提供商列表,请参阅支持的提供商和任务部分。
  3. Inference Endpoints:一种轻松将模型部署到生产环境的产品。推理由 Hugging Face 在您选择的云提供商的专用、完全托管的基础设施中运行。

这些服务都可以从 InferenceClient 对象调用。它充当旧版 InferenceApi 客户端的替代品,增加了对任务和第三方提供商的特定支持。在 旧版 InferenceAPI 客户端部分了解如何迁移到新客户端。

InferenceClient 是一个 Python 客户端,用于对我们的 API 进行 HTTP 调用。如果您想使用您偏好的工具(curl、postman 等)直接进行 HTTP 调用,请参阅 Inference APIInference Endpoints 文档页面。

对于 Web 开发,已经发布了 JS 客户端。如果您对游戏开发感兴趣,您可以查看我们的 C# 项目

开始使用

让我们从文本到图像的任务开始

>>> from huggingface_hub import InferenceClient

# Example with an external provider (e.g. replicate)
>>> replicate_client = InferenceClient(
    provider="replicate",
    api_key="my_replicate_api_key",
)
>>> replicate_image = replicate_client.text_to_image(
    "A flying car crossing a futuristic cityscape.",
    model="black-forest-labs/FLUX.1-schnell",
)
>>> replicate_image.save("flying_car.png")

在上面的示例中,我们使用第三方提供商 Replicate 初始化了 InferenceClient。当使用提供商时,您必须指定要使用的模型。模型 ID 必须是 Hugging Face Hub 上的模型 ID,而不是第三方提供商的模型 ID。在我们的示例中,我们从文本提示生成了一张图像。返回值是一个 PIL.Image 对象,可以保存到文件中。有关更多详细信息,请查看 text_to_image() 文档。

现在让我们看一个使用 chat_completion() API 的示例。此任务使用 LLM 从消息列表中生成响应

>>> from huggingface_hub import InferenceClient
>>> messages = [
    {
        "role": "user",
        "content": "What is the capital of France?",
    }
]
>>> client = InferenceClient(
    provider="together",
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    api_key="my_together_api_key",
)
>>> client.chat_completion(messages, max_tokens=100)
ChatCompletionOutput(
    choices=[
        ChatCompletionOutputComplete(
            finish_reason="eos_token",
            index=0,
            message=ChatCompletionOutputMessage(
                role="assistant", content="The capital of France is Paris.", name=None, tool_calls=None
            ),
            logprobs=None,
        )
    ],
    created=1719907176,
    id="",
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    object="text_completion",
    system_fingerprint="2.0.4-sha-f426a33",
    usage=ChatCompletionOutputUsage(completion_tokens=8, prompt_tokens=17, total_tokens=25),
)

在上面的示例中,我们使用了第三方提供商 (Together AI) 并指定了我们要使用的模型 ("meta-llama/Meta-Llama-3-8B-Instruct")。然后我们给出了要完成的消息列表(这里是一个问题),并向 API 传递了一个额外的参数 (max_token=100)。输出是一个 ChatCompletionOutput 对象,它遵循 OpenAI 规范。生成的内容可以使用 output.choices[0].message.content 访问。有关更多详细信息,请查看 chat_completion() 文档。

该 API 设计得非常简单。并非所有参数和选项都可供最终用户使用或描述。如果您有兴趣了解每个任务的所有可用参数,请查看 此页面

使用特定提供商

如果您想使用特定的提供商,您可以在初始化客户端时指定它。默认提供商是 “hf-inference”,即 Hugging Face 无服务器推理 API。有关支持的提供商列表,请参阅支持的提供商和任务部分。

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(provider="replicate", api_key="my_replicate_api_key")

使用特定模型

如果您想使用特定模型怎么办?您可以将其指定为参数,也可以直接在实例级别指定

>>> from huggingface_hub import InferenceClient
# Initialize client for a specific model
>>> client = InferenceClient(model="prompthero/openjourney-v4")
>>> client.text_to_image(...)
# Or use a generic client but pass your model as an argument
>>> client = InferenceClient()
>>> client.text_to_image(..., model="prompthero/openjourney-v4")

当使用 Hugging Face Inference API(默认提供商)时,每个任务都带有来自 Hub 上 20 万+ 模型的推荐模型。但是,此推荐可能会随着时间的推移而更改,因此一旦您决定使用哪个模型,最好显式设置模型。对于第三方提供商,您必须始终指定与该提供商兼容的模型。

访问 Hub 上的模型页面,浏览通过 Inference API 提供的模型,或查看提供商的文档以了解其支持的模型。

使用特定 URL

我们上面看到的示例使用 Hugging Face Inference API 或第三方提供商。虽然这些被证明对于快速原型设计和测试非常有用。但一旦您准备好将模型部署到生产环境,您将需要使用专用基础设施。这就是 Inference Endpoints 发挥作用的地方。它允许您部署任何模型并将其公开为私有 API。部署后,您将获得一个 URL,您可以使用与以前完全相同的代码连接到该 URL,只需更改 model 参数即可

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(model="https://uu149rez6gw9ehej.eu-west-1.aws.endpoints.huggingface.cloud/deepfloyd-if")
# or
>>> client = InferenceClient()
>>> client.text_to_image(..., model="https://uu149rez6gw9ehej.eu-west-1.aws.endpoints.huggingface.cloud/deepfloyd-if")

请注意,您不能同时指定 URL 和提供商 - 它们是互斥的。URL 用于直接连接到已部署的端点。

身份验证

身份验证取决于您使用的提供商

  1. 对于默认的 Hugging Face Inference API,您可以使用用户访问令牌进行身份验证
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(token="hf_***")

默认情况下,如果您已登录,它将使用保存在您机器上的令牌(请参阅如何进行身份验证)。

  1. 对于第三方提供商,您有两种选择

直接访问提供商:使用您自己的 API 密钥直接与提供商的服务交互

>>> client = InferenceClient(
    provider="replicate",
    api_key="r8_****"  # Your Replicate API key
)

通过 Hugging Face 路由:使用 Hugging Face 作为代理来访问第三方提供商。只需指定您的 Hugging Face 令牌和您要使用的提供商。调用将通过 Hugging Face 的基础设施使用我们的提供商密钥进行路由,并且使用情况将直接计入您的 Hugging Face 帐户

>>> client = InferenceClient(
    provider="replicate",
    token="hf_****"  # Your HF token
)

支持的提供商和任务

InferenceClient 的目标是为在任何提供商的 Hugging Face 模型上运行推理提供最简单的界面。它具有一个简单的 API,支持最常见的任务。下表显示了哪些提供商支持哪些任务

任务 Black Forest Labs Cerebras Cohere fal-ai Fireworks AI HF Inference Hyperbolic Nebius AI Studio Novita AI Replicate Sambanova Together
audio_classification()
audio_to_audio()
automatic_speech_recognition()
chat_completion()
document_question_answering()
feature_extraction()
fill_mask()
image_classification()
image_segmentation()
image_to_image()
image_to_text()
object_detection()
question_answering()
sentence_similarity()
summarization()
table_question_answering()
text_classification()
text_generation()
text_to_image()
text_to_speech()
text_to_video()
tabular_classification()
tabular_regression()
token_classification()
translation()
visual_question_answering()
zero_shot_image_classification()
zero_shot_classification()

查看任务页面以了解有关每个任务的更多信息。

OpenAI 兼容性

chat_completion 任务遵循 OpenAI 的 Python 客户端语法。这对您意味着什么?这意味着,如果您习惯使用 OpenAI 的 API,您将能够切换到 huggingface_hub.InferenceClient 来使用开源模型,只需更新 2 行代码!

- from openai import OpenAI
+ from huggingface_hub import InferenceClient

- client = OpenAI(
+ client = InferenceClient(
    base_url=...,
    api_key=...,
)


output = client.chat.completions.create(
    model="meta-llama/Meta-Llama-3-8B-Instruct",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Count to 10"},
    ],
    stream=True,
    max_tokens=1024,
)

for chunk in output:
    print(chunk.choices[0].delta.content)

就是这样!唯一需要的更改是将 from openai import OpenAI 替换为 from huggingface_hub import InferenceClient,并将 client = OpenAI(...) 替换为 client = InferenceClient(...)。您可以通过传递模型 ID 作为 model 参数,从 Hugging Face Hub 中选择任何 LLM 模型。这是一个支持的模型列表。对于身份验证,您应该传递有效的 用户访问令牌 作为 api_key,或者使用 huggingface_hub 进行身份验证(请参阅身份验证指南)。

所有输入参数和输出格式都完全相同。特别是,您可以传递 stream=True 以在生成令牌时接收令牌。您还可以使用 AsyncInferenceClient 使用 asyncio 运行推理

import asyncio
- from openai import AsyncOpenAI
+ from huggingface_hub import AsyncInferenceClient

- client = AsyncOpenAI()
+ client = AsyncInferenceClient()

async def main():
    stream = await client.chat.completions.create(
        model="meta-llama/Meta-Llama-3-8B-Instruct",
        messages=[{"role": "user", "content": "Say this is a test"}],
        stream=True,
    )
    async for chunk in stream:
        print(chunk.choices[0].delta.content or "", end="")

asyncio.run(main())

您可能想知道为什么使用 InferenceClient 而不是 OpenAI 的客户端?原因有以下几点

  1. InferenceClient 配置用于 Hugging Face 服务。您无需提供 base_url 即可在无服务器 Inference API 上运行模型。如果您的机器已正确登录,您也无需提供 tokenapi_key
  2. InferenceClient 专为 Text-Generation-Inference (TGI) 和 transformers 框架量身定制,这意味着您可以确保它始终与最新更新保持同步。
  3. InferenceClient 与我们的 Inference Endpoints 服务集成,使启动 Inference Endpoint、检查其状态并在其上运行推理变得更加容易。有关更多详细信息,请查看 Inference Endpoints 指南。

InferenceClient.chat.completions.create 只是 InferenceClient.chat_completion 的别名。有关更多详细信息,请查看 chat_completion() 的包参考。实例化客户端时的 base_urlapi_key 参数也是 modeltoken 的别名。定义这些别名是为了减少从 OpenAI 切换到 InferenceClient 时的摩擦。

异步客户端

还提供了客户端的异步版本,基于 asyncioaiohttp。您可以直接安装 aiohttp,也可以使用 [inference] 扩展

pip install --upgrade huggingface_hub[inference]
# or
# pip install aiohttp

安装后,所有异步 API 端点都可通过 AsyncInferenceClient 获得。其初始化和 API 与仅同步版本完全相同。

# Code must be run in an asyncio concurrent context.
# $ python -m asyncio
>>> from huggingface_hub import AsyncInferenceClient
>>> client = AsyncInferenceClient()

>>> image = await client.text_to_image("An astronaut riding a horse on the moon.")
>>> image.save("astronaut.png")

>>> async for token in await client.text_generation("The Huggingface Hub is", stream=True):
...     print(token, end="")
 a platform for sharing and discussing ML-related content.

有关 asyncio 模块的更多信息,请参阅官方文档

高级技巧

在以上部分中,我们看到了 InferenceClient 的主要方面。让我们深入了解一些更高级的技巧。

账单

作为 HF 用户,您每月都会获得积分,用于通过 Hub 上的各种提供商运行推理。您获得的积分数量取决于您的帐户类型(免费、PRO 或企业 Hub)。每次推理请求都会向您收费,具体取决于提供商的定价表。默认情况下,请求会记入您的个人帐户。但是,可以通过简单地将 bill_to="<your_org_name>" 传递给 InferenceClient 来设置账单,以便将请求记入您所属的组织。为此,您的组织必须订阅企业 Hub。有关账单的更多详细信息,请查看本指南

>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient(provider="fal-ai", bill_to="openai")
>>> image = client.text_to_image(
...     "A majestic lion in a fantasy forest",
...     model="black-forest-labs/FLUX.1-schnell",
... )
>>> image.save("lion.png")

请注意,无法向另一个用户或您不属于的组织收费。如果您想向其他人授予一些积分,您必须与他们创建一个联合组织。

超时

推理调用可能需要大量时间。默认情况下,InferenceClient 将“无限期”等待直到推理完成。如果您想在工作流程中进行更多控制,可以将 timeout 参数设置为特定值(以秒为单位)。如果超时延迟到期,则会引发 InferenceTimeoutError,您可以在代码中捕获它

>>> from huggingface_hub import InferenceClient, InferenceTimeoutError
>>> client = InferenceClient(timeout=30)
>>> try:
...     client.text_to_image(...)
... except InferenceTimeoutError:
...     print("Inference timed out after 30s.")

二进制输入

某些任务需要二进制输入,例如,在处理图像或音频文件时。在这种情况下,InferenceClient 尝试尽可能地宽松并接受不同的类型

  • 原始 bytes
  • 类文件对象,以二进制形式打开(with open("audio.flac", "rb") as f: ...
  • 指向本地文件的路径(strPath
  • 指向远程文件的 URL (str)(例如 https://...)。在这种情况下,文件将在本地下载,然后再发送到 Inference API。
>>> from huggingface_hub import InferenceClient
>>> client = InferenceClient()
>>> client.image_classification("https://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Cute_dog.jpg/320px-Cute_dog.jpg")
[{'score': 0.9779096841812134, 'label': 'Blenheim spaniel'}, ...]
< > 在 GitHub 上更新