hf-cloud-sagemaker-production-defaults
Original:🇺🇸 English
Translated
5 scriptsChecked / no sensitive code detected
Create a SageMaker endpoint (real-time or async) with autoscaling, CloudWatch alarms, and tagging enabled by default. Use this skill whenever about to create a SageMaker endpoint, write deployment code that calls `create_endpoint`, or finalize a deployment after the image URI and IAM role are known. Provides deploy.py for real-time endpoints and deploy_async.py for async endpoints (with genuine scale-to-zero support). This is the last step in the SageMaker deployment workflow. Never generate a bare `create_endpoint` call without these defaults — endpoints without autoscaling or alarms are demos, not deployments.
14installs
Sourcehuggingface/skills
Added on
NPX Install
npx skill4agent add huggingface/skills hf-cloud-sagemaker-production-defaultsTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →SageMaker Production Defaults
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.
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.mdRunning the deployment
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-uriInService is not success — smoke-test before declaring victory
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.
Testing a real-time endpoint
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
# macOS / Linux
python3 scripts/invoke_endpoint.py \
--endpoint-name <endpoint-name> \
--payload '{"inputs": "Hello"}' \
--region "$REGION"powershell
# Windows (PowerShell)
python scripts\invoke_endpoint.py `
--endpoint-name <endpoint-name> `
--payload-file payload.json `
--region $REGIONIt accepts either (inline) or , validates JSON, writes the request body as plain UTF-8, invokes the endpoint, and prints the response body to stdout.
--payload '<json>'--payload-file <path>The UTF-8 BOM gotcha (Windows)
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
# BOM-free UTF-8 — use this
[System.IO.File]::WriteAllText((Resolve-Path "payload.json"), $json, [System.Text.UTF8Encoding]::new($false))
aws sagemaker-runtime invoke-endpoint `
--endpoint-name <endpoint-name> `
--content-type application/json `
--body fileb://payload.json `
--region $REGION `
response.jsonFallback: if any invocation fails with , rewrite the payload as BOM-free UTF-8 (or re-run via ) and retry once before treating the endpoint or model as broken.
Unexpected UTF-8 BOMinvoke_endpoint.pyInvoking a generative reranker (vLLM)
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.
Picking the image URI
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
# Example: HuggingFace vLLM 0.21.0 from the catalog
IMAGE_URI="763104351884.dkr.ecr.eu-west-1.amazonaws.com/huggingface-vllm:0.21.0-transformers5.8.1-gpu-py312-cu130-ubuntu22.04"
# cu130 tag → must pass --inference-ami-version
python deploy.py --image-uri "$IMAGE_URI" \
--inference-ami-version al2-ami-sagemaker-inference-gpu-3-1 \
...For tags with or lower, omit . See for the full vLLM AMI lookup table and the env-var requirements for each image family.
cu129--inference-ami-versionhf-cloud-serving-image-selectionAsync inference deployments
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
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.
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>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
# Upload your input first
aws s3 cp input.json s3://my-input-bucket/job1/input.json
# Invoke
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>
# Poll for the result at your output URI
aws s3 cp s3://my-bucket/async-output/<inference-id>.out result.jsonThe same UTF-8 BOM caveat applies to the 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.
input.jsonTeardown works the same as real-time: (the teardown script discovers policies and alarms by name prefix, so it handles both deployment modes).
python3 scripts/teardown.py <endpoint-name>Defaults at a glance
| 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.
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.
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-uriTeardown
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.
When 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-endpoint