Hub Python 庫文件
推理端點
並獲得增強的文件體驗
開始使用
推理端點
推理端點提供了一個安全的生產解決方案,可以輕鬆地將任何 `transformers`、`sentence-transformers` 和 `diffusers` 模型部署在 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"
... )
在此示例中,我們建立了一個名為`"my-endpoint-name"`的`protected`推理端點,用於為gpt2提供`文字生成`服務。`protected`推理端點意味著訪問API需要您的token。我們還需要提供額外的資訊來配置硬體要求,例如供應商、區域、加速器、例項型別和大小。您可以在此處檢視可用資源的列表。或者,為了方便起見,您可以使用Web介面手動建立推理端點。有關高階設定及其用法的詳細資訊,請參閱本指南。
create_inference_endpoint() 返回的值是一個 InferenceEndpoint 物件
>>> endpoint
InferenceEndpoint(name='my-endpoint-name', namespace='Wauplin', repository='gpt2', status='pending', url=None)
它是一個數據類,包含有關端點的資訊。您可以訪問重要的屬性,例如 `name`、`repository`、`status`、`task`、`created_at`、`updated_at` 等。如果需要,您還可以透過 `endpoint.raw` 訪問來自伺服器的原始響應。
一旦您的推理端點建立成功,您可以在您的個人儀表板上找到它。
使用自定義映象
預設情況下,推理端點是根據 Hugging Face 提供的 Docker 映象構建的。但是,可以使用 `custom_image` 引數指定任何 Docker 映象。一個常見的用例是使用 text-generation-inference 框架執行大型語言模型。這可以像這樣完成
# 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), ...]
檢查部署狀態
在本指南的其餘部分,我們將假設我們有一個名為 `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)
您可以直接呼叫 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.
更新模型或硬體要求
在某些情況下,您可能還希望更新現有推理端點,而無需建立新的。您可以更新託管模型或執行模型的硬體要求。您可以使用 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)
刪除端點
最後,如果您不再使用推理端點,只需呼叫 `~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()