Hub Python Library documentation
推論エンドポイント
推論エンドポイント
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 です。
新機能: HF モデルカタログから、シンプルな API 呼び出しで Inference Endpoint をデプロイできるようになりました。カタログは、最適化された設定でデプロイ可能なモデルの厳選リストです。設定は不要で、面倒な作業はすべてこちらで対応します。すべてのモデルと設定は、コストとパフォーマンスの最適なバランスを提供するようにテスト済みです。create_inference_endpoint_from_catalog() は create_inference_endpoint() と同じように動作しますが、渡すパラメータが大幅に少なくなります。list_inference_catalog() を使用すると、カタログをプログラム的に取得できます。
これはまだ実験的な機能であることに注意してください。ご使用の場合は、ご意見をお聞かせください。
各カタログモデルは、レシピを通じてデプロイされます。レシピとは、そのモデル用にテスト済みのハードウェアとエンジンの組み合わせです。list_inference_catalog() は、モデルとそのレシピを返します。サーバーサイドのフィルター(accelerator、engine、license、task、search、limit)を受け取ります。
>>> from huggingface_hub import list_inference_catalog
>>> catalog = list_inference_catalog(task="text-generation", accelerator="neuron")
>>> catalog[0]
InferenceCatalogModel(repo_id='meta-llama/Llama-3.1-8B-Instruct', name='Llama-3.1-8B-Instruct', ...)
>>> catalog[0].recipes
[InferenceCatalogRecipe(id='sizzling-biryani-g4xsi1ac', accelerator='gpu', engine='vllm', gguf_file=None, revision=None),
InferenceCatalogRecipe(id='artisanal-quinoa-yz9ynamx', accelerator='neuron', engine='vllmNeuron', gguf_file=None, revision=None)]repo_id を create_inference_endpoint_from_catalog() に渡すことで、モデルのデフォルトのレシピをデプロイできます。必要に応じて accelerator("cpu"、"gpu" または "neuron")と gguf_file で絞り込むこともできます。また、recipe_id を渡すことで、特定のレシピをデプロイすることもできます。
>>> from huggingface_hub import create_inference_endpoint_from_catalog
>>> endpoint = create_inference_endpoint_from_catalog(repo_id="openai/gpt-oss-120b")
>>> endpoint = create_inference_endpoint_from_catalog(recipe_id="artisanal-quinoa-yz9ynamx")デプロイに使用するハードウェアを見つける
create_inference_endpoint() が受け付ける accelerator、vendor、region、instance_type、instance_size の値は、互いに依存関係があります。有効な組み合わせ、1 時間あたりの料金、および名前空間のアクセラレータ割当額を確認するには、list_inference_endpoints_hardware() を使用してください。
>>> from huggingface_hub import list_inference_endpoints_hardware
>>> for hw in list_inference_endpoints_hardware():
... if hw.accelerator == "gpu" and hw.status == "available":
... print(hw.vendor, hw.region, hw.instance_type, hw.instance_size, hw.price_per_hour)
aws us-east-1 nvidia-l4 x1 0.8
aws us-east-1 nvidia-l4 x4 3.8
...クォータはネームスペースごとに設定されるため、デプロイ先となるnamespaceを指定してください(デフォルトではご自身のアカウントが使用されます):
>>> list_inference_endpoints_hardware(namespace="my-org")または、CLI経由で:
hf endpoints hardware --accelerator gpu
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="authenticated",
... 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
# Deploy an exact catalog recipe, as listed by 'hf endpoints catalog ls'
hf endpoints catalog deploy --recipe artisanal-quinoa-yz9ynamxこの例では、text-generation 用に gpt2 を提供するため、authenticated の Inference Endpoint を "my-endpoint-name" という名前で作成しました。authenticated の Inference Endpoint とは、API にアクセスするためにトークンが必要であることを意味します。また、ベンダー、リージョン、アクセラレーター、インスタンスタイプ、サイズなどのハードウェア要件を設定するために、追加の情報も提供する必要があります。利用可能なリソースの一覧は こちら で確認できます。あるいは、Web interface を使用して 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="authenticated",
... instance_size="x1",
... instance_type="nvidia-a10g",
... custom_image={
... "healthRoute": "/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 ドキュメントを参照してください。
プライベートなコンテナレジストリにホストされているイメージの場合、container_registry_usernameを、またレジストリによって必要とされる場合はcontainer_registry_passwordを渡します。認証情報はプレーンなカスタムコンテナでのみサポートされます:
>>> endpoint = create_inference_endpoint(
... # Other endpoint and hardware arguments omitted for brevity.
... custom_image={"url": "private.registry.example/my-image:latest", "port": 8080},
... container_registry_username="user",
... container_registry_password="password",
... )等価なCLIオプションは--container-registry-usernameと--container-registry-passwordです:
hf endpoints deploy my-endpoint ... --custom-image private.registry.example/my-image:latest \ --container-registry-username user --container-registry-password password
custom_image は、フラットな構造にせず、エンジンの名前(vLLM、vLLMNeuron、sGLang、tgi、tgiNeuron、tei、llamacpp、hfServe、…)を辞書のキーとして指定することで、API がサポートするエンジン固有のコンテナ型も受け付けます。各エンジンは、通常のコンテナフィールド(url、port、healthRoute)に加えて、独自のチューニングオプションを指定できます。トップレベルに url を持たない辞書はすべて、そのまま API に転送されるため、後から API に追加されたエンジンも、huggingface_hub をアップグレードせずに利用できます。
# Start an Inference Endpoint running the vLLM engine image
>>> endpoint = create_inference_endpoint(
... "llama-3-1-8b-instruct-vllm",
... repository="meta-llama/Llama-3.1-8B-Instruct",
... framework="pytorch",
... task="text-generation",
... accelerator="gpu",
... vendor="aws",
... region="us-east-1",
... instance_size="x1",
... instance_type="nvidia-l4",
... custom_image={
... "vLLM": {
... "url": "vllm/vllm-openai:v0.23.0",
... "healthRoute": "/health",
... "port": 8000,
... "tensorParallelSize": 1,
... }
... },
... )エンジンキーがない場合、同じ辞書がプレーンなカスタムコンテナとして送信されるため、エンジン固有のオプション(ここではtensorParallelSize)が破棄されます。
カスタムエントリポイントやランタイムフラグが必要なコンテナの場合、container_command および/または container_args(それぞれトークンのリスト)を渡します。これらは API ペイロード内の model.command および model.args にマッピングされます。カスタムイメージに限定されません。マネージドエンジンイメージ(vLLM や SGLang など)も、container_args を通じてエンジンフラグを受け入れます。CLI では、hf endpoints deploy ... --container-command "..." --container-args "..." を使用して同様の設定を行うことができます。
マルチアクセラレータインスタンスでの並列化
vLLM と SGLang はデフォルトでアクセラレータを1つに設定するのに対し、エンドポイントはインスタンスのすべてのアクセラレータが割り当てられるため、並列性を設定しないままにすると、モデルは1つのアクセラレータに読み込まれ、残りはアイドル状態のまま、それでも正常と報告されます。その結果、すべてのアクセラレータの料金を支払うのに、1つのアクセラレータ分のスループットしか得られません。そのため、API はそのようなデプロイを拒否するようになりました。(TGI はインスタンスからシャード数を導出するため、影響を受けません。) tensorParallelSize を設定して1つのモデルコピーをアクセラレータ間でシャード化するか、dataParallelSize (vLLM のみ) を設定してアクセラレータごとに1つのコピーを実行してください:
>>> endpoint = create_inference_endpoint(
... "gpt-oss-120b-vllm",
... repository="openai/gpt-oss-120b",
... framework="custom",
... accelerator="gpu",
... instance_size="x8",
... instance_type="nvidia-h200",
... region="us-east-1",
... vendor="aws",
... custom_image={"vLLM": {"url": "vllm/vllm-openai:v0.23.0", "tensorParallelSize": 8}},
... )CLI から、--engine で管理対象のエンジンイメージを選択し、2つのフラグはその設定に書き込まれます:
hf endpoints deploy gpt-oss-120b-vllm --repo openai/gpt-oss-120b --framework custom \ --accelerator gpu --instance-size x8 --instance-type nvidia-h200 --region us-east-1 --vendor aws \ --engine vllm --custom-image vllm/vllm-openai:v0.23.0 --tensor-parallel-size 8
デプロイ済みエンドポイントを再チューニングするには、tensor_parallel_sizeのみをupdate()またはhf endpoints updateに渡します。model.imageは全体として送信され、urlを必要とするため、エンドポイントの現在のイメージを取得して、その場で更新されます:
>>> endpoint.update(tensor_parallel_size=4)container_args (--tp 8) は同等ではありません。これはエンジンにコマンドラインフラグとして渡されますが、API がインスタンスのアクセラレータ数に対して検証する model.image の設定ではありません。画像フィールドのないエンジンフラグ、および並列化フィールドを持たないプレーンなカスタムコンテナに使用してください。
既存の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には、それぞれInferenceClientオブジェクトとAsyncInferenceClientオブジェクトを返すclientとasync_clientという2つのプロパティがあります。
# 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ガイドを参照してください。
ライフサイクルの管理
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() を直接使用することもできます。
一時停止またはゼロにスケーリング
To reduce costs when your Inference Endpoint is not in use, you can choose to either pause it using pause() or scale it to zero using scale_to_zero().
一時停止またはゼロにスケーリングされた Inference Endpoint は、コストが発生しません。この2つの違いは、一時停止されたエンドポイントは、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を作成せずに、既存の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)
# Update the container arguments, e.g. engine flags on an endpoint running vLLM or SGLang.
# Replaces the current value, it is not appended.
>>> endpoint.update(container_args=["--enable-auto-tool-choice", "--tool-call-parser", "lfm2"])
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
hf endpoints update my-endpoint-name --container-args "--enable-auto-tool-choice --tool-call-parser lfm2"
# Merged into the image currently configured on the endpoint.
hf endpoints update my-endpoint-name --tensor-parallel-size 8
# Or replace the image entirely, in which case pass back the settings you want to keep.
hf endpoints update my-endpoint-name --engine vllm --custom-image vllm/vllm-openai:v0.23.0 --port 8000エンドポイントを削除します
最後に、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 = await 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 = await asyncio.gather(*[async_client.text_generation(...) for job in jobs])
# Pause endpoint
>>> endpoint.pause()