Hub Python 庫文件
推理端點
並獲得增強的文件體驗
開始使用
推理端點
推理端點提供了一個安全的生產解決方案,可以輕鬆地將任何 transformers、sentence-transformers 和 diffusers 模型部署到 Hugging Face 管理的專用且自動擴充套件的基礎設施上。推理端點是基於 Hugging Face Hub 上的模型構建的。在本指南中,我們將學習如何使用 huggingface_hub 以程式設計方式管理推理端點。有關推理端點產品本身的更多資訊,請檢視其官方文件。
本指南假設 huggingface_hub 已正確安裝並且您的機器已登入。如果尚未完成,請檢視《快速入門指南》。支援推理端點 API 的最低版本是 v0.19.0。
新功能:現在可以透過簡單的 API 呼叫從 HF 模型目錄部署推理端點。該目錄是經過精心策劃的模型列表,可以進行最佳化設定部署。您無需配置任何內容,我們負責所有繁重的工作!所有模型和設定都經過測試,可提供最佳的成本/效能平衡。 create_inference_endpoint_from_catalog() 的用法與 create_inference_endpoint() 相同,只需傳遞更少的引數。您可以使用 list_inference_catalog() 以程式設計方式檢索目錄。
請注意,這仍然是一項實驗性功能。如果您使用它,請告訴我們您的想法!
建立推理端點
第一步是使用 create_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 my-endpoint-name --repo openai/gpt-oss-120b在此示例中,我們建立了一個 protected 推理端點,名為 "my-endpoint-name",用於服務 Hugging Face Hub 上的 gpt2 模型,任務為 text-generation。protected 推理端點意味著訪問 API 需要您的令牌。我們還需要提供額外的資訊來配置硬體要求,例如供應商、區域、加速器、例項型別和大小。您可以在此處檢視可用資源的列表。或者,您可以方便地使用 Web 介面手動建立推理端點。有關高階設定及其用法的詳細資訊,請參閱本指南。
由 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 訪問伺服器的原始響應。
建立推理端點後,您可以在您的個人儀表板上找到它。

使用自定義映象
預設情況下,推理端點是從 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 文件。
獲取或列出現有推理端點
在某些情況下,您可能需要管理之前建立的推理端點。如果您知道名稱,可以使用 get_inference_endpoint() 獲取它,它會返回一個 InferenceEndpoint 物件。或者,您可以使用 list_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 屬性。當推理端點已部署且可訪問時,狀態應為 "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" 狀態之前,推理端點通常會經歷 "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
與其在等待推理端點執行時輪詢其狀態,不如直接呼叫 wait()。此輔助函式接受 timeout 和 fetch_every 引數(以秒為單位),並將阻塞執行緒直到推理端點部署完成。預設值為 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 並且推理端點載入時間過長,將引發 InferenceEndpointTimeoutError 超時錯誤。
執行推理
一旦您的推理端點啟動並執行,您終於可以對其進行推理了!
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")如果推理端點未執行,則會引發 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 的更多詳細資訊,請參閱《推理指南》。
管理生命週期
我們已經介紹瞭如何建立推理端點及其執行推理,現在讓我們看看如何管理其生命週期。
在本節中,我們將介紹諸如 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()。
暫停或縮減至零
為了在不使用推理端點時降低成本,您可以選擇使用 pause() 暫停它,或使用 scale_to_zero() 將其縮減至零。
暫停或縮減至零的推理端點不產生任何費用。這兩者之間的區別在於,暫停的端點需要使用 resume() 顯式恢復。相反,縮減至零的端點將在進行推理呼叫時自動啟動,並有額外的冷啟動延遲。推理端點也可以配置為在一段時間不活動後自動縮減至零。
# 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
更新模型或硬體要求
在某些情況下,您可能還希望更新推理端點而不建立新的端點。您可以更新託管模型或更新執行模型的硬體要求。您可以使用 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
刪除端點
最後,如果您不再需要該推理端點,只需呼叫 ~InferenceEndpoint.delete()。
這是一個不可逆的操作,將完全刪除該端點,包括其配置、日誌和使用指標。您無法恢復已刪除的推理端點。
端到端示例
推理端點的一個典型用例是批次處理作業,以限制基礎設施成本。您可以使用本指南中介紹的內容來自動化此過程。
>>> 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()或者,如果您的推理端點已存在且處於暫停狀態。
>>> 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()