Hub Python 库文档
推理端点
并获得增强的文档体验
开始使用
Inference Endpoints
Inference Endpoints 提供了一种安全的生产方案,可在由 Hugging Face 管理的专属且可自动扩展的基础设施上轻松部署任何 transformers、sentence-transformers 和 diffusers 模型。Inference Endpoint(推理端点)是基于 Hub 中的模型构建的。在本指南中,我们将学习如何使用 huggingface_hub 以编程方式管理 Inference Endpoints。有关 Inference Endpoints 产品本身的更多信息,请查看其官方文档。
本指南假设 huggingface_hub 已正确安装且您的机器已登录。如果尚未登录,请查看快速入门指南。支持 Inference Endpoints API 的最低版本为 v0.19.0。
新功能: 现在只需一个简单的 API 调用,就可以从 HF 模型目录 部署 Inference Endpoint。该目录是经过精心挑选的模型列表,可以使用优化后的设置进行部署。您无需配置任何内容,繁重的工作都由我们来承担!所有模型和设置均经过测试,确保能够提供最佳的性价比平衡。create_inference_endpoint_from_catalog() 的工作原理与 create_inference_endpoint() 相同,但需要传递的参数要少得多。您可以选择指定
accelerator("cpu"、"gpu"或"neuron")来覆盖默认的硬件选择。您可以使用 list_inference_catalog() 以编程方式检索该目录。请注意,这仍然是一项实验性功能。如果您使用它,请告诉我们您的想法!
创建 Inference Endpoint
第一步是使用 create_inference_endpoint() 创建 Inference Endpoint
>>> from huggingface_hub import create_inference_endpoint
>>> endpoint = create_inference_endpoint(
... "my-endpoint-name",
... repository="gpt2",
... framework="pytorch",
... task="text-generation",
... accelerator="cpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="x2",
... instance_type="intel-icl"
... )或通过 CLI:
hf endpoints deploy my-endpoint-name --repo gpt2 --framework pytorch --accelerator cpu --vendor aws --region us-east-1 --instance-size x2 --instance-type intel-icl --task text-generation
# Deploy from the catalog with a single command
hf endpoints catalog deploy --repo openai/gpt-oss-120b
# Deploy from the catalog with a specific accelerator
hf endpoints catalog deploy --repo openai/gpt-oss-120b --accelerator gpu在此示例中,我们创建了一个名为 "my-endpoint-name" 的 protected(受保护的)Inference Endpoint,用于为 gpt2 提供 text-generation(文本生成)服务。protected 的 Inference Endpoint 意味着访问该 API 需要使用您的 Token。我们还需要提供额外的信息来配置硬件需求,例如运营商(vendor)、区域(region)、加速器(accelerator)、实例类型(instance type)以及大小(size)。您可以在此处查看可用资源的列表。或者,为了方便起见,您也可以使用网页界面手动创建 Inference Endpoint。有关高级设置及其用法,请参阅此指南。
由 create_inference_endpoint() 返回的值是一个 InferenceEndpoint 对象
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='pending', url=None)或通过 CLI:
hf endpoints describe my-endpoint-name
它是一个保存端点信息的数据类(dataclass)。您可以访问重要的属性,如 name、repository、status、task、created_at、updated_at 等。如果您有需要,还可以通过 endpoint.raw 访问来自服务器的原始响应。
一旦创建了 Inference Endpoint,您就可以在您的个人控制面板中找到它。

使用自定义镜像
默认情况下,Inference Endpoint 是基于 Hugging Face 提供的 Docker 镜像构建的。不过,您可以使用 custom_image 参数指定任何 Docker 镜像。一个常见的用例是使用 text-generation-inference 框架来运行大语言模型(LLM)。您可以这样做:
# Start an Inference Endpoint running Zephyr-7b-beta on TGI
>>> from huggingface_hub import create_inference_endpoint
>>> endpoint = create_inference_endpoint(
... "aws-zephyr-7b-beta-0486",
... repository="HuggingFaceH4/zephyr-7b-beta",
... framework="pytorch",
... task="text-generation",
... accelerator="gpu",
... vendor="aws",
... region="us-east-1",
... type="protected",
... instance_size="x1",
... instance_type="nvidia-a10g",
... custom_image={
... "health_route": "/health",
... "env": {
... "MAX_BATCH_PREFILL_TOKENS": "2048",
... "MAX_INPUT_LENGTH": "1024",
... "MAX_TOTAL_TOKENS": "1512",
... "MODEL_ID": "/repository"
... },
... "url": "ghcr.io/huggingface/text-generation-inference:1.1.0",
... },
... )作为 custom_image 传递的值是一个包含 Docker 容器 URL 以及运行配置的字典。有关更多详细信息,请查看 Swagger 文档。
获取或列出已有的 Inference Endpoints
在某些情况下,您可能需要管理以前创建的 Inference Endpoints。如果您知道名称,可以使用 get_inference_endpoint() 来获取它,该方法会返回一个 InferenceEndpoint 对象。或者,您可以使用 list_inference_endpoints() 来获取所有 Inference Endpoints 的列表。这两种方法都接受一个可选的 namespace 参数。您可以将 namespace 设置为您所属的任何组织,否则默认为您的用户名。
>>> from huggingface_hub import get_inference_endpoint, list_inference_endpoints
# Get one
>>> get_inference_endpoint("my-endpoint-name")
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='pending', url=None)
# List all endpoints from an organization
>>> list_inference_endpoints(namespace="huggingface")
[InferenceEndpoint(name='aws-starchat-beta', namespace='huggingface', repository='HuggingFaceH4/starchat-beta', status='paused', url=None), ...]
# List all endpoints from all organizations the user belongs to
>>> list_inference_endpoints(namespace="*")
[InferenceEndpoint(name='aws-starchat-beta', namespace='huggingface', repository='HuggingFaceH4/starchat-beta', status='paused', url=None), ...]或通过 CLI:
hf endpoints describe my-endpoint-name
hf endpoints ls --namespace huggingface
hf endpoints ls --namespace '*'检查部署状态
在本指南的其余部分中,我们将假设我们拥有一个名为 endpoint 的 InferenceEndpoint 对象。您可能已经注意到,该端点具有一个类型为 InferenceEndpointStatus 的 status 属性。当 Inference Endpoint 部署完毕且可访问时,其状态应为 "running",并且 url 属性已被设置
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='running', url='https://jpj7k2q4j805b727.us-east-1.aws.endpoints.huggingface.cloud')在达到 "running" 状态之前,Inference Endpoint 通常会经历 "initializing"(初始化中)或 "pending"(等待中)阶段。您可以通过运行 fetch() 来获取端点的新状态。与 InferenceEndpoint 中向服务器发送请求的其他方法一样,endpoint 的内部属性会就地更新
>>> endpoint.fetch()
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='pending', url=None)或通过 CLI:
hf endpoints describe my-endpoint-name
您无需在等待运行时反复获取 Inference Endpoint 的状态,而是可以直接调用 wait()。这个辅助函数接受 timeout 和 fetch_every 参数(以秒为单位)作为输入,并将阻塞线程直到 Inference Endpoint 部署完成。默认值分别为 None(无超时)和 5 秒。
# Pending endpoint
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='pending', url=None)
# Wait 10s => raises a InferenceEndpointTimeoutError
>>> endpoint.wait(timeout=10)
raise InferenceEndpointTimeoutError("Timeout while waiting for Inference Endpoint to be deployed.")
huggingface_hub._inference_endpoints.InferenceEndpointTimeoutError: Timeout while waiting for Inference Endpoint to be deployed.
# Wait more
>>> endpoint.wait()
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='running', url='https://jpj7k2q4j805b727.us-east-1.aws.endpoints.huggingface.cloud')如果设置了 timeout,而 Inference Endpoint 加载花费了太多时间,则会抛出 InferenceEndpointTimeoutError 超时错误。
运行推理
一旦您的 Inference Endpoint 启动并运行,您终于可以在其上运行推理了!
InferenceEndpoint 具有两个属性 client 和 async_client,分别返回一个 InferenceClient 和一个 AsyncInferenceClient 对象。
# Run text_generation task:
>>> endpoint.client.text_generation("I am")
' not a fan of the idea of a "big-budget" movie. I think it\'s a'
# Or in an asyncio context:
>>> await endpoint.async_client.text_generation("I am")如果 Inference Endpoint 未运行,则会抛出 InferenceEndpointError 异常。
>>> endpoint.client
huggingface_hub._inference_endpoints.InferenceEndpointError: Cannot create a client for this Inference Endpoint as it is not yet deployed. Please wait for the Inference Endpoint to be deployed using `endpoint.wait()` and try again.有关如何使用 InferenceClient 的更多详细信息,请查看推理指南。
管理生命周期
我们已经了解了如何创建 Inference Endpoint 并在其上运行推理,下面让我们来看看如何管理它的生命周期。
在本节中,我们将介绍 pause()、resume()、scale_to_zero()、update() 和 delete() 等方法。为了方便使用,所有这些方法都是作为别名添加到了 InferenceEndpoint。如果您愿意,也可以使用
HfApi中定义的通用方法:pause_inference_endpoint()、resume_inference_endpoint()、scale_to_zero_inference_endpoint()、update_inference_endpoint() 和 delete_inference_endpoint()。
暂停或缩容至零
为了在不使用 Inference Endpoint 时降低成本,您可以选择使用 pause() 将其暂停,或者使用 scale_to_zero() 将其缩容至零。
处于 *已暂停*(paused)或 *缩容至零*(scaled to zero)状态的 Inference Endpoint 不会产生任何费用。这两者的区别在于,*已暂停* 的端点需要使用 resume() 显式地 *恢复*。相反,*缩容至零* 的端点在收到推理调用时会自动启动,但会伴随额外的冷启动延迟。您还可以将 Inference Endpoint 配置为在闲置一段时间后自动缩容至零。
# Pause and resume endpoint
>>> endpoint.pause()
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='paused', url=None)
>>> endpoint.resume()
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='pending', url=None)
>>> endpoint.wait().client.text_generation(...)
...
# Scale to zero
>>> endpoint.scale_to_zero()
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='scaledToZero', url='https://jpj7k2q4j805b727.us-east-1.aws.endpoints.huggingface.cloud')
# Endpoint is not 'running' but still has a URL and will restart on first call.或通过 CLI:
hf endpoints pause my-endpoint-name hf endpoints resume my-endpoint-name hf endpoints scale-to-zero my-endpoint-name
更新模型或硬件需求
在某些情况下,您可能还希望在不创建新端点的情况下更新已有的 Inference Endpoint。您可以更新托管的模型,也可以更新运行模型所需的硬件需求。您可以使用 update() 来完成此操作
# Change target model
>>> endpoint.update(repository="gpt2-large")
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2-large', status='pending', url=None)
# Update number of replicas
>>> endpoint.update(min_replica=2, max_replica=6)
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2-large', status='pending', url=None)
# Update to larger instance
>>> endpoint.update(accelerator="cpu", instance_size="x4", instance_type="intel-icl")
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2-large', status='pending', url=None)或通过 CLI:
hf endpoints update my-endpoint-name --repo gpt2-large hf endpoints update my-endpoint-name --min-replica 2 --max-replica 6 hf endpoints update my-endpoint-name --accelerator cpu --instance-size x4 --instance-type intel-icl
删除端点
最后,如果您不再使用该 Inference Endpoint,只需调用 ~InferenceEndpoint.delete() 即可。
这是一个不可逆的操作,将完全删除端点,包括其配置、日志和使用指标。您无法恢复已删除的 Inference Endpoint。
端到端示例
Inference Endpoints 的一个典型用例是一次性处理一批任务,以限制基础设施成本。您可以使用我们在本指南中看到的内容来自动化此过程
>>> import asyncio
>>> from huggingface_hub import create_inference_endpoint
# Start endpoint + wait until initialized
>>> endpoint = create_inference_endpoint(name="batch-endpoint",...).wait()
# Run inference
>>> client = endpoint.client
>>> results = [client.text_generation(...) for job in jobs]
# Or with asyncio
>>> async_client = endpoint.async_client
>>> results = asyncio.gather(*[async_client.text_generation(...) for job in jobs])
# Pause endpoint
>>> endpoint.pause()或者,如果您的 Inference Endpoint 已经存在并且处于暂停状态
>>> import asyncio
>>> from huggingface_hub import get_inference_endpoint
# Get endpoint + wait until initialized
>>> endpoint = get_inference_endpoint("batch-endpoint").resume().wait()
# Run inference
>>> async_client = endpoint.async_client
>>> results = asyncio.gather(*[async_client.text_generation(...) for job in jobs])
# Pause endpoint
>>> endpoint.pause()