google-cloud 文档
在 GKE 上使用 TGI DLC 部署 Llama 3.2 11B Vision
并获得增强的文档体验
开始使用
在 GKE 上使用 TGI DLC 部署 Llama 3.2 11B Vision
Llama 3.2 是 Meta 发布(截至 2024 年 10 月)的 Llama 系列开放 LLM 的最新版本;Llama 3.2 Vision 有两种尺寸:11B 用于在消费级 GPU 上高效部署和开发,90B 用于大规模应用。Text Generation Inference (TGI) 是 Hugging Face 开发的一套工具包,用于部署和提供 LLM 服务,具有高性能文本生成能力。而 Google Kubernetes Engine (GKE) 是 Google Cloud 中一项完全托管的 Kubernetes 服务,可用于使用 Google 基础设施大规模部署和运行容器化应用程序。
本示例展示了如何通过 Hugging Face 专门为 Google Cloud 上的 Text Generation Inference (TGI) 构建的深度学习容器 (DLC) 在 GKE 上部署 meta-llama/Llama-3.2-11B-Vision
。
关于许可条款,Llama 3.2 的许可与 Llama 3.1 非常相似,但可接受使用政策有一个关键区别:任何居住在欧盟 (EU) 或主要营业地在欧盟的公司均不被授予使用 Llama 3.2 中包含的多模态模型的许可权利。此限制不适用于包含此类多模态模型的产品或服务的最终用户,因此人们仍然可以使用视觉变体构建全球产品。
设置/配置
首先,您需要在本地机器上安装 gcloud
和 kubectl
,它们分别是 Google Cloud 和 Kubernetes 的命令行工具,用于与 GCP 和 GKE 集群交互。
- 要安装
gcloud
,请按照 Cloud SDK 文档 - 安装 gcloud CLI 中的说明进行操作。 - 要安装
kubectl
,请按照 Kubernetes 文档 - 安装工具 中的说明进行操作。
或者,为了简化本教程中命令的使用,您需要为 GCP 设置以下环境变量
export PROJECT_ID=your-project-id
export LOCATION=your-location
export CLUSTER_NAME=your-cluster-name
然后您需要登录到您的 GCP 账户,并将项目 ID 设置为您要用于部署 GKE 集群的项目。
gcloud auth login
gcloud auth application-default login # For local development
gcloud config set project $PROJECT_ID
登录后,您需要启用 GCP 中必要的服务 API,例如 Google Kubernetes Engine API、Google Container Registry API 和 Google Container File System API,这些都是部署 GKE 集群和 Hugging Face TGI DLC 所必需的。
gcloud services enable container.googleapis.com
gcloud services enable containerregistry.googleapis.com
gcloud services enable containerfilesystem.googleapis.com
此外,要将 kubectl
与 GKE 集群凭据一起使用,您还需要安装 gke-gcloud-auth-plugin
,可以如下使用 gcloud
进行安装
gcloud components install gke-gcloud-auth-plugin
gke-gcloud-auth-plugin
不需要通过 gcloud
专门安装,要了解更多替代安装方法,请访问 GKE 文档 - 安装 kubectl 并配置集群访问。
创建 GKE 集群
一切设置好后,您可以在 Autopilot 或 Standard 模式下创建 GKE 集群;对于 Autopilot 模式,您只需创建集群,节点池将根据部署要求创建;而在 Standard 模式下,您需要自行创建节点池,并管理大部分底层基础设施。
将使用“Autopilot”模式,因为它是大多数工作负载的推荐模式,因为底层基础设施由 Google 管理;但您也可以选择使用“Standard”模式。
在创建 GKE Autopilot 集群之前,请务必查看 GKE 文档 - 通过选择机器系列优化 Autopilot Pod 性能,因为并非所有版本都支持 GPU 加速器,例如 GKE 集群版本 1.28.3 或更低版本不支持 nvidia-l4
。
gcloud container clusters create-auto $CLUSTER_NAME \
--project=$PROJECT_ID \
--location=$LOCATION \
--release-channel=stable \
--cluster-version=1.29 \
--no-autoprovisioning-enable-insecure-kubelet-readonly-port
要选择您所在位置的特定 GKE 集群版本,您可以运行以下命令
gcloud container get-server-config \
--flatten="channels" \
--filter="channels.channel=STABLE" \
--format="yaml(channels.channel,channels.defaultVersion)" \
--location=$LOCATION
欲了解更多信息,请访问 GKE 文档 - 指定集群版本。
GKE 集群创建完成后,您可以使用以下命令通过 kubectl
获取访问它的凭据
gcloud container clusters get-credentials $CLUSTER_NAME --location=$LOCATION
获取 Hugging Face 令牌并在 GKE 中设置秘密
由于 meta-llama/Llama-3.2-11B-Vision-Instruct
是一个在欧盟 (EU) 受限访问的门控模型,您需要通过 kubectl
设置一个带有 Hugging Face Hub 令牌的 Kubernetes 秘密。
要为 Hugging Face Hub 生成自定义令牌,您可以按照 Hugging Face Hub - 用户访问令牌 中的说明进行操作;推荐的设置方式是安装 huggingface_hub
Python SDK,如下所示:
pip install --upgrade --quiet huggingface_hub
然后使用生成的具有对受限/私有模型读取权限的令牌登录
huggingface-cli login
最后,您可以使用 huggingface_hub
Python SDK 检索令牌,如下所示创建包含 Hugging Face Hub 生成令牌的 Kubernetes secret
kubectl create secret generic hf-secret \
--from-literal=hf_token=$(python -c "from huggingface_hub import get_token; print(get_token())") \
--dry-run=client -o yaml | kubectl apply -f -
或者,您可以直接按如下方式设置令牌
kubectl create secret generic hf-secret \ --from-literal=hf_token=hf_*** \ --dry-run=client -o yaml | kubectl apply -f -
有关如何在 GKE 集群中设置 Kubernetes 秘密的更多信息,请参阅 Secret Manager 文档 - 将 Secret Manager 附加组件与 Google Kubernetes Engine 结合使用。
部署 TGI
现在您可以继续进行 Hugging Face TGI DLC 的 Kubernetes 部署,该 DLC 将从 Hugging Face Hub 提供 meta-llama/Llama-3.2-11B-Vision-Instruct
模型。
要探索所有可以通过 TGI 提供的模型,您可以在 Hub 中探索标记为 text-generation-inference
的模型;具体而言,如果您对视觉语言模型 (VLM) 感兴趣,您可以在 Hub 中探索同时标记为 text-generation-inference
和 image-text-to-text
的模型。
Hugging Face TGI DLC 将通过 kubectl
部署,配置文件位于 config/
目录中。
deployment.yaml
:包含 Pod 的部署详情,包括对 Hugging Face DLC for TGI 的引用,将MODEL_ID
设置为meta-llama/Llama-3.2-11B-Vision-Instruct
。由于 GKE 集群部署在 Autopilot 模式下,指定的资源(即 2 个 L4)将自动分配;但如果您使用 Standard 模式,则应确保您的节点池具有这些 GPU。service.yaml
:包含 Pod 的服务详情,公开 TGI 服务的 8080 端口。- (可选)
ingress.yaml
:包含 Pod 的入口详情,将服务公开到外部世界,以便可以通过入口 IP 访问。
git clone https://github.com/huggingface/Google-Cloud-Containers
kubectl apply -f Google-Cloud-Containers/examples/gke/tgi-llama-vision-deployment/config
Kubernetes 部署可能需要几分钟才能准备就绪,您可以使用以下命令检查部署状态:
kubectl get pods
以及通过以下命令检查正在部署的 Pod 的日志
kubectl logs -f <POD>
或者,您也可以使用以下命令等待部署准备就绪:
kubectl wait --for=condition=Available --timeout=700s deployment/tgi-deployment
使用 TGI 进行推理
要对已部署的 TGI 服务运行推理,您可以选择以下方式:
将已部署的 TGI 服务端口转发到 8080 端口,以便通过
localhost
访问,命令如下:kubectl port-forward service/tgi-service 8080:8080
通过入口的外部 IP 访问 TGI 服务,这是默认场景,因为您已在
config/ingress.yaml
文件中定义了入口配置(但可以跳过以支持端口转发),可以使用以下命令检索:kubectl get ingress tgi-ingress -o jsonpath='{.status.loadBalancer.ingress[0].ip}'
通过 cURL
要使用 `cURL` 向 TGI 服务发送 POST 请求,您可以运行以下命令:
curl https://:8080/v1/chat/completions \
-X POST \
-d '{"messages":[{"role":"user","content":[{"type":"text","text":"What'\''s in this image?"},{"type":"image_url","image_url":{"url":"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png"}}]}],"temperature":0.7,"top_p":0.95,"max_tokens":128,"stream":false}' \
-H 'Content-Type: application/json'
或者向入口 IP 发送 POST 请求(无需指定端口,因为不需要)
curl http://$(kubectl get ingress tgi-ingress -o jsonpath='{.status.loadBalancer.ingress[0].ip}')/v1/chat/completions \
-X POST \
-d '{"messages":[{"role":"user","content":[{"type":"text","text":"What'\''s in this image?"},{"type":"image_url","image_url":{"url":"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png"}}]}],"temperature":0.7,"top_p":0.95,"max_tokens":128,"stream":false}' \
-H 'Content-Type: application/json'
生成以下输出
{"object":"chat.completion","id":"","created":1728041178,"model":"meta-llama/Llama-3.2-11B-Vision-Instruct","system_fingerprint":"2.3.1-native","choices":[{"index":0,"message":{"role":"assistant","content":"The image shows a rabbit wearing a space suit, standing on a rocky, orange-colored surface. The background is a reddish-brown color with a bright light shining from the right side of the image."},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":43,"completion_tokens":42,"total_tokens":85}}
通过 Python
要使用 Python 运行推理,您可以使用 huggingface_hub
Python SDK(推荐)或 openai
Python SDK。
在下面的示例中将使用 localhost
,但如果使用 ingress 部署了 TGI,请随意使用上述 ingress IP(无需指定端口)。
huggingface_hub
您可以通过 pip install --upgrade --quiet huggingface_hub
安装它,然后运行以下代码片段来模仿上面的 cURL
命令,即向 Messages API 发送请求
from huggingface_hub import InferenceClient
client = InferenceClient(base_url="https://:8080", api_key="-")
chat_completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png"
},
},
],
},
],
max_tokens=128,
)
生成以下输出
ChatCompletionOutput(choices=[ChatCompletionOutputComplete(finish_reason='length', index=0, message=ChatCompletionOutputMessage(role='assistant', content="The image depicts an astronaut rabbit standing on a rocky surface, which is likely Mars or a similar planet. The astronaut's suit takes up most of the shot, with a clear distinction between its lighter parts, such as the chest and limbs, and its darker parts, like the shell that protects it from space's toxic environment. The head portion consists of the full-length helmet that's transparent at the front, allowing the rabbit's face to be visible. \n\nThe astronaut rabbit stands vertically, looking into the distance, its head slightly pointed forward and pointing with its right arm down. Its left arm hangs at its side, adding balance to its stance", tool_calls=None), logprobs=None)], created=1728041247, id='', model='meta-llama/Llama-3.2-11B-Vision-Instruct', system_fingerprint='2.3.1-native', usage=ChatCompletionOutputUsage(completion_tokens=128, prompt_tokens=43, total_tokens=171))
openai
此外,您还可以通过 openai
使用 Messages API;您可以通过 pip
安装它,命令为 pip install --upgrade openai
,然后运行:
from openai import OpenAI
client = OpenAI(
base_url="https://:8080/v1/",
api_key="-",
)
chat_completion = client.chat.completions.create(
model="tgi",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit.png"
},
},
],
},
],
max_tokens=128,
)
生成以下输出
ChatCompletion(id='', choices=[Choice(finish_reason='length', index=0, logprobs=None, message=ChatCompletionMessage(content='The image features an astronaut rabbit on the surface of Mars. Given that rabbits (Oryctolagus cuniculus) are mammals, temperature regulation, gravity, and radiation exposure are all potential hazards in an extraterrestrial space suit designed for a rabbit. As optimal space exploration wear is human-centric, it is challenging to transpose a hypothetical rabbit astronaut suit to adapt to the specialized needs of rabbits.\n\n**Adaptations to Suit Rabbit Physiology**\n\nTo simulate a normalized temperature change, a cooling system designed for thermal comfort could be used. This system might involve a water-based cooling mechanism, similar to a panty hose or suit liner filled with', refusal=None, role='assistant', function_call=None, tool_calls=None))], created=1728041281, model='meta-llama/Llama-3.2-11B-Vision-Instruct', object='chat.completion', service_tier=None, system_fingerprint='2.3.1-native', usage=CompletionUsage(completion_tokens=128, prompt_tokens=43, total_tokens=171))
其他用例
此外,除上述图像字幕外,一些潜在的 VLM 用例如下:
视觉问答 (VQA)
给定图像和关于图像的问题,生成问题的答案。
curl https://:8080/v1/chat/completions \
-X POST \
-d '{"messages":[{"role":"user","content":[{"type":"text","text":"Which era does this piece belong to? Give details about the era."},{"type":"image_url","image_url":{"url":"https://huggingface.co/datasets/huggingface/release-assets/resolve/main/rococo.jpg"}}]}],"temperature":0.7,"top_p":0.95,"max_tokens":128,"stream":false}' \
-H 'Content-Type: application/json'
例如,给定一件艺术品,您可以向 VLM 询问有关它的问题。
![]() | 您所指的这件作品是一幅洛可可时代的画作,具体来说是 18 世纪的。洛可可风格于 18 世纪初在法国兴起,并在 18 世纪中期传遍欧洲,尤其是在德国和俄罗斯。 洛可可艺术的特点
|
图像信息检索
给定图像,从图像中检索信息。
curl https://:8080/v1/chat/completions \
-X POST \
-d '{"messages":[{"role":"user","content":[{"type":"text","text":"How long does it take from invoice date to due date? Be short and concise."},{"type":"image_url","image_url":{"url":"https://huggingface.co/datasets/huggingface/release-assets/resolve/main/invoice.png"}}]}],"temperature":0.7,"top_p":0.95,"max_tokens":128,"stream":false}' \
-H 'Content-Type: application/json'
例如,给定一张发票,您可以向 VLM 询问有关其中存在或可以从所提供的图像中推断出的信息。
![]() | 为了计算发票日期和到期日之间的时间差,我们需要从到期日中减去发票日期。 发票日期:2019/11/02 到期日期:2019/02/26 时间差 = 到期日期 - 发票日期 时间差 = 2019/02/26 - 2019/11/02 时间差 = 15 天 因此,从发票日期到到期日期需要 15 天。 |
删除 GKE 集群
最后,一旦您完成在 GKE 集群上使用 TGI,您可以安全地删除 GKE 集群以避免产生不必要的费用。
gcloud container clusters delete $CLUSTER_NAME --location=$LOCATION
或者,如果您想保留集群,也可以将副本数量缩减为零,因为 GKE 集群已部署在 Autopilot 模式下,即仅在需要时创建节点池,并在不需要时销毁;并且默认情况下,它仅在单个 e2-small
实例上运行。
kubectl scale --replicas=0 deployment/tgi-deployment
📍 在 GitHub 上找到完整的示例 此处!