hf-cloud-sagemaker-production-defaults
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSageMaker Production Defaults
SageMaker 生产环境默认配置
The difference between a demo endpoint and one you can leave running is: it scales with traffic, it tells you when it breaks, and you can debug it later. This skill makes those three the default rather than optional extras.
By the time this skill runs, the planner has chosen a real-time endpoint, IAM has a usable role, and image-selection has resolved a container URI + AMI version. This skill turns those into an actual deployment.
演示用端点与可长期运行的端点的区别在于:前者能随流量自动扩缩容、故障时主动告警,且后续可调试。本技能将这三项设为默认配置,而非可选附加功能。
当执行本技能时,规划器已选定实时端点类型、IAM已配置可用角色,且镜像选择环节已确定容器URI + AMI版本。本技能会将这些资源转化为实际部署。
What gets created
创建的资源内容
For every endpoint, the skill creates these as a unit:
- SageMaker Model — image + env vars + execution role + S3 artifacts
- Endpoint config — instance type, initial count, optional data capture
- Endpoint — the real-time endpoint serving inference
- Autoscaling target + policy — target tracking on invocations per instance
- CloudWatch alarms — latency, errors, platform overhead
Data capture (logging requests/responses to S3) is off by default — useful for debugging but creates ongoing S3 costs the user didn't necessarily ask for. Enable with .
--enable-data-captureAll resources get a consistent tag set including for later cleanup.
CreatedBy=agentic-deploy-skillsDefaults and reasoning in .
references/deployment-template.md针对每个端点,本技能会统一创建以下资源:
- SageMaker Model — 镜像 + 环境变量 + 执行角色 + S3制品
- 端点配置 — 实例类型、初始实例数、可选数据捕获
- 端点 — 提供推理服务的实时端点
- 自动扩缩容目标 + 策略 — 基于单实例调用次数的目标追踪
- CloudWatch告警 — 延迟、错误、平台开销相关告警
数据捕获(将请求/响应日志存储到S3)默认关闭——虽有助于调试,但会产生用户未明确要求的持续S3成本。可通过开启。
--enable-data-capture所有资源都会添加统一标签集,包括用于后续清理的标签。
CreatedBy=agentic-deploy-skills默认配置及设计思路详见。
references/deployment-template.mdRunning the deployment
执行部署
—
文本生成大模型(vLLM)部署示例:
For a text-generation LLM (vLLM):
bash
python scripts/deploy.py \
--model-name qwen3-medical \
--image-uri "$IMAGE_URI" \
--inference-ami-version "$AMI" \
--role-arn "$ROLE_ARN" \
--instance-type ml.g5.xlarge \
--region "$REGION" \
--env SM_VLLM_MODEL=Qwen/Qwen3-0.6B \
--env SM_VLLM_HOST=0.0.0.0 \
--env SM_VLLM_TRUST_REMOTE_CODE=true \
--env SM_VLLM_MAX_MODEL_LEN=4096For an embedding model (TEI, often on CPU):
bash
python scripts/deploy.py \
--model-name bge-large-embeddings \
--image-uri "$IMAGE_URI" \
--role-arn "$ROLE_ARN" \
--instance-type ml.c6i.2xlarge \
--region "$REGION" \
--env HF_MODEL_ID=BAAI/bge-large-en-v1.5Note: TEI deployments do not need . That flag is vLLM-specific. TEI env vars are also simpler ( instead of , no host or trust-remote-code to configure).
--inference-ami-versionHF_MODEL_IDSM_VLLM_*Where each value comes from:
| Parameter | Source |
|---|---|
| |
| |
| |
| |
| User input or planner recommendation |
| Model-specific; see |
| Optional — S3 path to model artifacts; omit if loading from HF Hub |
The script creates resources in order with error handling, waits for (up to 30 min), surfaces failure reasons, registers autoscaling and alarms, and prints a summary including the teardown command. Outputs a JSON blob on stdout with endpoint/config/model names for downstream scripting.
InServiceThe scripts ship with this skill. If the installed copy is missing the directory (some harnesses copy only SKILL.md on install), fetch them from the source repo rather than re-implementing them from this description.
scripts/Cold-start expectation: when the model loads from HF Hub, the download happens inside the container after the endpoint starts — 5–15+ minutes to InService is normal, not a failure. waits 30 minutes; if you write custom wait code, don't time out at 15. Pre-staging weights in S3 () cuts this and removes the Hub dependency.
deploy.py--model-s3-uribash
python scripts/deploy.py \
--model-name qwen3-medical \
--image-uri "$IMAGE_URI" \
--inference-ami-version "$AMI" \
--role-arn "$ROLE_ARN" \
--instance-type ml.g5.xlarge \
--region "$REGION" \
--env SM_VLLM_MODEL=Qwen/Qwen3-0.6B \
--env SM_VLLM_HOST=0.0.0.0 \
--env SM_VLLM_TRUST_REMOTE_CODE=true \
--env SM_VLLM_MAX_MODEL_LEN=4096InService is not success — smoke-test before declaring victory
嵌入模型(TEI,通常部署在CPU)示例:
InService/ping-
One real invocation.
- Real-time: (below) with a minimal payload; require an HTTP 200 with a sane body.
invoke_endpoint.py - Async: upload one input to S3, call , poll the output URI for a few minutes (see "Invoking async endpoints"). A result object = success; an object at the failure URI, or nothing appearing, = broken.
invoke-endpoint-async
- Real-time:
-
Scan the endpoint logs for worker-crash markers — catches the crash-loop case even when the smoke request merely times out:bash
aws logs filter-log-events \ --log-group-name /aws/sagemaker/Endpoints/<endpoint-name> \ --filter-pattern '?"Worker died" ?"Load model failed" ?"ImportError"' \ --region <region> --max-items 5
Only report the deployment complete after both pass. If the log scan hits, surface the actual traceback from CloudWatch — not the InService status.
bash
python scripts/deploy.py \
--model-name bge-large-embeddings \
--image-uri "$IMAGE_URI" \
--role-arn "$ROLE_ARN" \
--instance-type ml.c6i.2xlarge \
--region "$REGION" \
--env HF_MODEL_ID=BAAI/bge-large-en-v1.5注意:TEI部署不需要参数,该参数仅针对vLLM。TEI的环境变量也更简单(使用而非,无需配置host或trust-remote-code)。
--inference-ami-versionHF_MODEL_IDSM_VLLM_*各参数来源说明:
| 参数 | 来源 |
|---|---|
| |
| |
| |
| |
| 用户输入或规划器推荐 |
| 模型专属配置;需查看 |
| 可选参数 — 模型制品的S3路径;若从HF Hub加载则可省略 |
脚本会按顺序创建资源并处理错误,等待端点进入状态(最长等待30分钟),展示失败原因,配置自动扩缩容和告警,并打印包含销毁命令的部署摘要。脚本会在标准输出中输出包含端点/配置/模型名称的JSON数据,供后续脚本调用。
InService这些脚本随本技能一同提供。若安装副本缺少目录(部分工具仅在安装时复制SKILL.md),请从源码仓库获取脚本,而非根据本文描述重新实现。
scripts/冷启动预期:当模型从HF Hub加载时,下载操作会在端点启动后在容器内进行——通常需要5-15+分钟才能进入状态,这属于正常情况而非故障。会等待30分钟;若你编写自定义等待代码,不要将超时时间设为15分钟。提前将权重预存到S3(使用参数)可缩短冷启动时间,并消除对HF Hub的依赖。
InServicedeploy.py--model-s3-uriTesting a real-time endpoint
InService状态不代表部署成功——务必先执行冒烟测试
Once the endpoint is , test it with the bundled helper. It is cross-platform and BOM-safe — use it instead of hand-writing a payload file and calling directly:
InServiceinvoke-endpointbash
undefinedInService/ping-
执行一次真实调用
- 实时端点:使用下方的脚本,传入最小有效载荷;要求返回HTTP 200状态码及合理响应体。
invoke_endpoint.py - 异步端点:将一个输入文件上传到S3,调用,轮询输出URI几分钟(详见“调用异步端点”部分)。若生成结果对象则表示成功;若失败URI下出现对象或无任何内容,则表示部署失败。
invoke-endpoint-async
- 实时端点:使用下方的
-
扫描端点日志查找Worker崩溃标记——即使冒烟请求仅超时,也能捕获崩溃循环情况:bash
aws logs filter-log-events \ --log-group-name /aws/sagemaker/Endpoints/<endpoint-name> \ --filter-pattern '?"Worker died" ?"Load model failed" ?"ImportError"' \ --region <region> --max-items 5
只有两项检查都通过后,才能报告部署完成。若日志扫描命中错误标记,需从CloudWatch提取实际回溯信息,而非仅报告InService状态。
macOS / Linux
测试实时端点
python3 scripts/invoke_endpoint.py
--endpoint-name <endpoint-name>
--payload '{"inputs": "Hello"}'
--region "$REGION"
--endpoint-name <endpoint-name>
--payload '{"inputs": "Hello"}'
--region "$REGION"
```powershell当端点进入状态后,可使用附带的辅助脚本进行测试。该脚本跨平台且无BOM问题——请使用此脚本,而非手动编写载荷文件并直接调用:
InServiceinvoke-endpointbash
undefinedWindows (PowerShell)
macOS / Linux
python scripts\invoke_endpoint.py
--payload-file payload.json `
--region $REGION
--endpoint-name <endpoint-name>
It accepts either `--payload '<json>'` (inline) or `--payload-file <path>`, validates JSON, writes the request body as plain UTF-8, invokes the endpoint, and prints the response body to stdout.python3 scripts/invoke_endpoint.py
--endpoint-name <endpoint-name>
--payload '{"inputs": "Hello"}'
--region "$REGION"
--endpoint-name <endpoint-name>
--payload '{"inputs": "Hello"}'
--region "$REGION"
```powershellThe UTF-8 BOM gotcha (Windows)
Windows (PowerShell)
If you write the request payload yourself on Windows, do not use — depending on the PowerShell version it prepends a UTF-8 byte-order mark (BOM). SageMaker's JSON parser rejects a BOM with a 400 :
Set-Content -Encoding UTF8ModelErrorUnexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)This is not a model, endpoint-health, or image problem — only the file encoding of the request body. avoids it entirely (it even strips a BOM from a that already has one). If you must call the CLI directly, write the body as BOM-free UTF-8:
invoke_endpoint.py--payload-filepowershell
undefinedpython scripts\invoke_endpoint.py
--payload-file payload.json `
--region $REGION
--endpoint-name <endpoint-name>
脚本支持`--payload '<json>'`(内联方式)或`--payload-file <path>`(文件方式),会验证JSON格式,将请求体以纯UTF-8格式写入,调用端点,并将响应体打印到标准输出。BOM-free UTF-8 — use this
Windows平台的UTF-8 BOM陷阱
[System.IO.File]::WriteAllText((Resolve-Path "payload.json"), $json, [System.Text.UTF8Encoding]::new($false))
aws sagemaker-runtime invoke-endpoint
--content-type application/json
--region $REGION `
response.json
--endpoint-name <endpoint-name> --body fileb://payload.json
**Fallback:** if any invocation fails with `Unexpected UTF-8 BOM`, rewrite the payload as BOM-free UTF-8 (or re-run via `invoke_endpoint.py`) and retry once before treating the endpoint or model as broken.若你在Windows平台自行编写请求载荷,不要使用命令——根据PowerShell版本不同,该命令可能会在文件开头添加UTF-8字节顺序标记(BOM)。SageMaker的JSON解析器会拒绝带BOM的请求,返回400错误:
Set-Content -Encoding UTF8ModelErrorUnexpected UTF-8 BOM (decode using utf-8-sig): line 1 column 1 (char 0)这不是模型、端点健康或镜像的问题——仅与请求体的文件编码有关。可完全避免此问题(即使指定的文件已包含BOM,脚本也会自动移除)。若你必须直接调用CLI,请将请求体写入无BOM的UTF-8文件:
invoke_endpoint.py--payload-filepowershell
undefinedInvoking a generative reranker (vLLM)
无BOM的UTF-8格式——请使用此命令
Generative rerankers (Qwen3-Reranker etc. — routed to the HuggingFace vLLM DLC by ) are causal LMs scored by their first generated token, not chat models. Use the completions API with a raw , not the messages/chat API: chat templating does not reliably honor such as , and a wrong template silently returns near-identical scores for every query–document pair instead of erroring.
hf-cloud-serving-image-selectionpromptchat_template_kwargs{"enable_thinking": false}Payload shape (Qwen3-Reranker's expected format — substitute / ):
{query}{document}json
{
"prompt": "<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n<|im_start|>user\n<Instruct>: Given a web search query, retrieve relevant passages that answer the query\n<Query>: {query}\n<Document>: {document}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
"max_tokens": 1,
"temperature": 0,
"logprobs": 20
}The trailing suffix is load-bearing: it pre-fills an empty thinking block so the first generated token is the yes/no judgment. Score from the returned logprobs: . Sanity check the endpoint with one relevant pair (expect >0.9) and one irrelevant pair (expect <0.05) — near-identical scores across pairs mean the prompt template is wrong, not that the model is broken.
<|im_start|>assistant\n<think>\n\n</think>\n\nP("yes") / (P("yes") + P("no"))The same rule generalizes: for any thinking-mode model where the prompt must be byte-exact, prefer the raw completions API over chat.
[System.IO.File]::WriteAllText((Resolve-Path "payload.json"), $json, [System.Text.UTF8Encoding]::new($false))
aws sagemaker-runtime invoke-endpoint
--content-type application/json
--region $REGION `
response.json
--endpoint-name <endpoint-name> --body fileb://payload.json
** fallback方案**:若调用时出现`Unexpected UTF-8 BOM`错误,请将载荷重新写入无BOM的UTF-8文件(或通过`invoke_endpoint.py`重新调用),并重试一次,再判断端点或模型是否存在问题。Picking the image URI
调用生成式重排模型(vLLM)
The agent reads the image URI from AWS's Deep Learning Containers catalog — pick the row that matches the model family (HuggingFace vLLM for LLMs, TEI for embeddings, etc.), substitute with the deployment region, and pass to .
<region>deploy.py --image-uriFor vLLM images specifically (both and the AWS fallback), also check the tag's CUDA version:
huggingface-vllmvllmbash
undefined生成式重排模型(如Qwen3-Reranker等——由路由到HuggingFace vLLM DLC)是因果语言模型,通过首个生成的token进行评分,而非对话模型。请使用带原始的补全API,而非消息/对话API:对话模板无法可靠支持(如),错误的模板会静默返回所有查询-文档对几乎相同的分数,而非抛出错误。
hf-cloud-serving-image-selectionpromptchat_template_kwargs{"enable_thinking": false}载荷格式(Qwen3-Reranker预期格式——替换 / ):
{query}{document}json
{
"prompt": "<|im_start|>system\nJudge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\".<|im_end|>\n<|im_start|>user\n<Instruct>: Given a web search query, retrieve relevant passages that answer the query\n<Query>: {query}\n<Document>: {document}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
"max_tokens": 1,
"temperature": 0,
"logprobs": 20
}末尾的后缀至关重要:它预填充了一个空的思考块,使首个生成的token即为yes/no判断结果。从返回的logprobs计算分数:。请用一对相关的查询-文档对(预期分数>0.9)和一对不相关的查询-文档对(预期分数<0.05)验证端点——若所有对的分数几乎相同,则说明提示模板错误,而非模型故障。
<|im_start|>assistant\n<think>\n\n</think>\n\nP("yes") / (P("yes") + P("no"))此规则可推广:对于任何要求提示字节级精确的思考模式模型,优先使用原始补全API而非对话API。
Example: HuggingFace vLLM 0.21.0 from the catalog
选择镜像URI
IMAGE_URI="763104351884.dkr.ecr.eu-west-1.amazonaws.com/huggingface-vllm:0.21.0-transformers5.8.1-gpu-py312-cu130-ubuntu22.04"
智能体从AWS的深度学习容器目录读取镜像URI——选择与模型家族匹配的行(LLM选HuggingFace vLLM,嵌入模型选TEI等),将替换为部署区域,然后传入参数。
<region>deploy.py --image-uri针对vLLM镜像(包括和AWS的备用镜像),还需检查标签的CUDA版本:
huggingface-vllmvllmbash
undefinedcu130 tag → must pass --inference-ami-version
示例:从目录获取的HuggingFace vLLM 0.21.0镜像
python deploy.py --image-uri "$IMAGE_URI"
--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1
...
--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1
...
For tags with `cu129` or lower, omit `--inference-ami-version`. See `hf-cloud-serving-image-selection` for the full vLLM AMI lookup table and the env-var requirements for each image family.IMAGE_URI="763104351884.dkr.ecr.eu-west-1.amazonaws.com/huggingface-vllm:0.21.0-transformers5.8.1-gpu-py312-cu130-ubuntu22.04"
Async inference deployments
cu130标签 → 必须传入--inference-ami-version参数
For long-running inferences (>60s), large payloads, or workloads that are bursty/sparse enough to benefit from scale-to-zero, use instead of . Async genuinely supports — real-time autoscaling can't.
deploy_async.pydeploy.pyMinCapacity=0bash
python scripts/deploy_async.py \
--model-name flux-text-to-image \
--image-uri "$IMAGE_URI" \
--role-arn "$ROLE_ARN" \
--instance-type ml.g5.2xlarge \
--region "$REGION" \
--output-s3-uri s3://my-bucket/async-output/ \
--env HF_MODEL_ID=black-forest-labs/FLUX.1-devRequired extras over :
deploy.py- — where async results land (results are not returned synchronously)
--output-s3-uri
Optional async-specific flags:
- — separate path for failed invocations
--failure-s3-uri - ,
--success-sns-topic— get notified when async results are ready or fail--error-sns-topic - (the default) — scale to zero between batches
--min-capacity 0 - — target queue depth per instance (default 5)
--backlog-per-instance-target N - — default 4
--max-concurrent-invocations-per-instance N
python deploy.py --image-uri "$IMAGE_URI"
--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1
...
--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1
...
对于`cu129`或更低版本的标签,可省略`--inference-ami-version`参数。完整的vLLM AMI查找表及各镜像家族的环境变量要求,请查看`hf-cloud-serving-image-selection`。How scale-to-zero works
异步推理部署
The async script registers two autoscaling policies on the variant:
- Target-tracking on — handles ongoing scaling between min and max
ApproximateBacklogSizePerInstance - Step-scaling triggered by a CloudWatch alarm — handles
HasBacklogWithoutCapacitywake-from-zero0→1
Both are needed. Target-tracking alone cannot transition from zero (it can't divide by zero instances), so without the step policy the endpoint comes up, scales to zero after the first batch, and never wakes again. The script wires this up automatically.
对于运行时间较长的推理(>60秒)、大载荷,或具有突发性/稀疏性可受益于缩容至零的工作负载,请使用而非。异步部署真正支持——实时自动扩缩容无法实现此功能。
deploy_async.pydeploy.pyMinCapacity=0bash
python scripts/deploy_async.py \
--model-name flux-text-to-image \
--image-uri "$IMAGE_URI" \
--role-arn "$ROLE_ARN" \
--instance-type ml.g5.2xlarge \
--region "$REGION" \
--output-s3-uri s3://my-bucket/async-output/ \
--env HF_MODEL_ID=black-forest-labs/FLUX.1-dev相较于,异步部署需额外传入以下必填参数:
deploy.py- — 异步推理结果的存储位置(结果不会同步返回)
--output-s3-uri
可选的异步专属参数:
- — 失败调用的单独存储路径
--failure-s3-uri - ,
--success-sns-topic— 异步推理完成或失败时接收通知--error-sns-topic - (默认值) — 批次间隔期间缩容至零
--min-capacity 0 - — 单实例的目标队列深度(默认值为5)
--backlog-per-instance-target N - — 默认值为4
--max-concurrent-invocations-per-instance N
Async alarms
缩容至零的实现机制
The script creates three CloudWatch alarms:
- — queue is building faster than capacity can drain it
ApproximateBacklogSize > 50 - — repeated processing failures
InvocationsFailed > 5 - — drives the wake-from-zero policy (not a notification alarm; its action is the step-scaling policy, not the SNS topic)
HasBacklogWithoutCapacity
If you pass , the first two notify on that topic. The wake alarm always points at the step policy.
--sns-alarm-topic <arn>异步脚本会为变体注册两个自动扩缩容策略:
- 目标追踪策略 — 基于指标,处理最小和最大容量之间的动态扩缩容
ApproximateBacklogSizePerInstance - 阶梯扩缩容策略 — 由CloudWatch告警触发,处理从0→1的唤醒逻辑
HasBacklogWithoutCapacity
两者缺一不可。仅使用目标追踪策略无法从零容量状态过渡(无法除以零实例数),因此若缺少阶梯策略,端点启动后会在首个批次完成后缩容至零,且无法再次唤醒。脚本会自动完成这些配置。
Invoking async endpoints
异步告警
Async endpoints aren't called synchronously. You upload the input to S3, call with the S3 input location, and SageMaker writes the result to your when done:
invoke-endpoint-async--output-s3-uribash
undefined脚本会创建三个CloudWatch告警:
- — 队列增长速度超过容量处理速度
ApproximateBacklogSize > 50 - — 出现多次处理失败
InvocationsFailed > 5 - — 驱动从零唤醒的策略(非通知告警;其关联动作是阶梯扩缩容策略,而非SNS主题)
HasBacklogWithoutCapacity
若传入参数,前两个告警会向该主题发送通知。唤醒告警始终关联阶梯策略。
--sns-alarm-topic <arn>Upload your input first
调用异步端点
aws s3 cp input.json s3://my-input-bucket/job1/input.json
异步端点不支持同步调用。你需要将输入文件上传到S3,调用并传入S3输入位置,SageMaker会在处理完成后将结果写入你指定的:
invoke-endpoint-async--output-s3-uribash
undefinedInvoke
先上传输入文件
aws sagemaker-runtime invoke-endpoint-async
--endpoint-name <endpoint-name>
--input-location s3://my-input-bucket/job1/input.json
--content-type application/json
--region <region>
--endpoint-name <endpoint-name>
--input-location s3://my-input-bucket/job1/input.json
--content-type application/json
--region <region>
aws s3 cp input.json s3://my-input-bucket/job1/input.json
Poll for the result at your output URI
调用端点
aws s3 cp s3://my-bucket/async-output/<inference-id>.out result.json
The same UTF-8 BOM caveat applies to the `input.json` you upload (see "The UTF-8 BOM gotcha" above) — if you build it on Windows, write it as BOM-free UTF-8 or the container's JSON parser will reject it.
Teardown works the same as real-time: `python3 scripts/teardown.py <endpoint-name>` (the teardown script discovers policies and alarms by name prefix, so it handles both deployment modes).aws sagemaker-runtime invoke-endpoint-async
--endpoint-name <endpoint-name>
--input-location s3://my-input-bucket/job1/input.json
--content-type application/json
--region <region>
--endpoint-name <endpoint-name>
--input-location s3://my-input-bucket/job1/input.json
--content-type application/json
--region <region>
Defaults at a glance
轮询输出URI获取结果
| Setting | Default | Override |
|---|---|---|
| Initial instance count | 1 | |
| Autoscaling min / max | 1 / 4 | |
| Autoscaling target | 20 invocations/min/instance | |
| Data capture | disabled (opt-in) | |
| CloudWatch alarms | 3 alarms | |
| SNS notification | none (alarms created but won't notify) | |
| Environment tag | | |
| InferenceAmiVersion | none (SageMaker default) | |
Not defaulted (user-specific input needed): VPC config, KMS key, multi-variant, async inference.
aws s3 cp s3://my-bucket/async-output/<inference-id>.out result.json
上传的`input.json`同样存在UTF-8 BOM陷阱(详见“Windows平台的UTF-8 BOM陷阱”部分)——若你在Windows平台创建该文件,请写入无BOM的UTF-8格式,否则容器的JSON解析器会拒绝该文件。
销毁操作与实时端点相同:`python3 scripts/teardown.py <endpoint-name>`(销毁脚本会通过名称前缀自动发现策略和告警,因此支持两种部署模式)。Autoscaling target — tune by model type
默认配置概览
The default is conservative and tuned for LLM workloads where each request takes 1–5 seconds. For embedding deployments (TEI), each request is much faster (typically <100ms on CPU, <20ms on GPU), so a single instance can handle far more throughput. For embedding deployments, raise the target to 100–500 depending on instance and model size. The default of 20 will trigger autoscaling far too aggressively for embeddings and waste money.
--target-invocations-per-instance 20A rule of thumb: target value ≈ 60 / (typical request latency in seconds). LLM at 3s latency → target 20. Embedding at 100ms → target 600. Generative rerankers sit in between — they generate a single token per request, so ~40–100 is a reasonable target.
| 设置项 | 默认值 | 覆盖方式 |
|---|---|---|
| 初始实例数 | 1 | |
| 自动扩缩容最小/最大容量 | 1 / 4 | |
| 自动扩缩容目标值 | 20 次调用/分钟/实例 | |
| 数据捕获 | 禁用(需手动开启) | |
| CloudWatch告警 | 3个告警 | |
| SNS通知 | 无(告警已创建但不会发送通知) | |
| 环境标签 | | |
| InferenceAmiVersion | 无(使用SageMaker默认值) | |
未设置默认值的项(需用户提供专属输入):VPC配置、KMS密钥、多变体、异步推理。
Data capture + IAM gotcha
自动扩缩容目标值——按模型类型调整
If the user enables data capture, the execution role needs S3 write access to the capture prefix. The default URI () is typically a different bucket than the model artifact bucket. If scoped the inline policy narrowly to just the model bucket, capture writes fail silently — endpoint keeps serving but no data appears.
s3://sagemaker-<region>-<account>/<endpoint>/data-capture/hf-cloud-sagemaker-iam-preflightIf the user reports "data capture isn't showing up", check the role's S3 access. Either widen the inline policy or pass pointing to a bucket the role can write.
--data-capture-s3-uri默认的是保守值,针对的是单次请求耗时1-5秒的LLM工作负载。对于嵌入模型(TEI),单次请求速度更快(CPU上通常<100ms,GPU上<20ms),因此单实例可处理更高吞吐量。对于嵌入模型部署,请将目标值提高到100-500,具体取决于实例和模型大小。默认值20会导致嵌入模型的自动扩缩容触发过于频繁,造成资源浪费。
--target-invocations-per-instance 20经验法则:目标值 ≈ 60 / (典型请求延迟,单位为秒)。LLM延迟3秒 → 目标值20;嵌入模型延迟100ms → 目标值600;生成式重排模型介于两者之间——单次请求生成一个token,因此目标值设为40-100较为合理。
Teardown
数据捕获 + IAM陷阱
bash
python3 scripts/teardown.py <endpoint-name> <region> # macOS / Linux
python scripts\teardown.py <endpoint-name> <region> # WindowsDeletes in safe order: alarms → autoscaling → endpoint (stops billing) → endpoint config → model. Idempotent.
Does not delete: the IAM execution role (might be shared), data capture S3 objects (user might want to keep), SNS topic, original model artifacts.
Always tell the user about the teardown command after the deployment summary. Users forget; endpoints accrue cost.
若用户启用数据捕获,执行角色需要对捕获前缀所在的S3桶拥有写入权限。默认URI()通常与模型制品桶不同。若将内联策略的范围严格限定为模型桶,则数据捕获写入会静默失败——端点仍能提供服务,但不会生成任何数据。
s3://sagemaker-<region>-<account>/<endpoint>/data-capture/hf-cloud-sagemaker-iam-preflight若用户反馈“数据捕获未生成内容”,请检查角色的S3访问权限。可放宽内联策略的范围,或传入参数指向角色拥有写入权限的桶。
--data-capture-s3-uriWhen the deployment fails
销毁部署
CannotStartContainerErrorcu130--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1hf-cloud-serving-image-selection"Failed to pass ping health check" — the container did start and produced logs, but isn't responding. Check CloudWatch at . Usually: wrong image for model architecture, missing HF token, or OOM.
/ping/aws/sagemaker/Endpoints/<endpoint-name>"Container failed to start" (with logs present) — entrypoint ran, then exited. Check CloudWatch. Common: missing required env vars (, , ), wrong format, unreadable model artifacts.
SM_VLLM_MODELSM_VLLM_HOSTSM_VLLM_TRUST_REMOTE_CODEModelDataUrlResourceLimitExceededhf-cloud-sagemaker-deployment-plannerImportError: libtorch_cuda.so: undefined symbol: ncclCommResumehuggingface-pytorch-inferencehf-cloud-serving-image-selectionInService, but invocations time out / async outputs never appear — dead Python worker behind a live MMS front-end. Run the log scan from "InService is not success" above; the traceback in CloudWatch is the real error.
403 Forbiddenhuggingface_hub--env HF_HUB_ENABLE_HF_TRANSFER=0Diagnostic rule: when failures look identical across multiple configurations (different images, roles, instance types) and no logs are ever produced, the cause is almost always below the container — host AMI, networking, account-level — not the deployment config. Stop iterating on config; check the AMI version and account state.
Don't retry blindly. The script prints the specific from — fix the root cause before retrying.
FailureReasondescribe-endpointbash
python3 scripts/teardown.py <endpoint-name> <region> # macOS / Linux
python scripts\teardown.py <endpoint-name> <region> # Windows销毁顺序(安全可靠):告警 → 自动扩缩容配置 → 端点(停止计费) → 端点配置 → 模型。该操作具有幂等性。
不会销毁的资源:IAM执行角色(可能被共享使用)、数据捕获的S3对象(用户可能需要保留)、SNS主题、原始模型制品。
部署摘要输出后,务必告知用户销毁命令。用户容易遗忘,端点会持续产生费用。
—
部署失败排查
—
CannotStartContainerErrorcu130--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1hf-cloud-serving-image-selection"Failed to pass ping health check"——容器已启动并生成日志,但请求无响应。请查看CloudWatch的日志。通常原因:模型架构与镜像不匹配、缺少HF令牌、内存不足(OOM)。
/ping/aws/sagemaker/Endpoints/<endpoint-name>"Container failed to start"(已生成日志)——入口脚本已执行,但随后退出。请查看CloudWatch日志。常见原因:缺少必填环境变量(、、)、格式错误、模型制品无法读取。
SM_VLLM_MODELSM_VLLM_HOSTSM_VLLM_TRUST_REMOTE_CODEModelDataUrlResourceLimitExceededhf-cloud-sagemaker-deployment-plannerCloudWatch日志中出现—— GPU镜像存在已知打包缺陷(详见中的“已知故障镜像”部分)。此问题发生在容器内部,无法通过环境变量、AMI、实例类型或其他标签修复。请切换到DJL Inference镜像。
ImportError: libtorch_cuda.so: undefined symbol: ncclCommResumehuggingface-pytorch-inferencehf-cloud-serving-image-selection处于InService状态,但调用超时 / 异步输出从未生成——Python Worker已崩溃,但MMS前端仍正常运行。请执行“InService状态不代表部署成功”部分的日志扫描;CloudWatch中的回溯信息才是真正的错误原因。
启动时从HF Hub下载权重出现——容器内置的版本早于HF的XET CDN认证机制。添加参数,或提前将权重预存到S3。注意:此操作可能会掩盖更深层的故障(Worker可能在下载成功后仍崩溃)——修复后请重新检查日志。
403 Forbiddenhuggingface_hub--env HF_HUB_ENABLE_HF_TRANSFER=0诊断规则:若故障在多种配置(不同镜像、角色、实例类型)下表现相同,且从未生成任何日志,则根本原因几乎总是在容器层面之下——主机AMI、网络、账户级问题,而非部署配置问题。停止迭代配置;请检查AMI版本和账户状态。
不要盲目重试。脚本会打印返回的具体——修复根本原因后再重试。
describe-endpointFailureReason